code stringlengths 1 2.01M | repo_name stringlengths 3 62 | path stringlengths 1 267 | language stringclasses 231
values | license stringclasses 13
values | size int64 1 2.01M |
|---|---|---|---|---|---|
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(false),
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;
// }
//
// }
}
| 061304011116lyj-and | src/com/ch_linghu/fanfoudroid/task/TweetCommonTask.java | Java | asf20 | 2,875 |
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);
}
| 061304011116lyj-and | src/com/ch_linghu/fanfoudroid/task/TaskListener.java | Java | asf20 | 287 |
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);
}
} | 061304011116lyj-and | src/com/ch_linghu/fanfoudroid/task/TaskManager.java | Java | asf20 | 451 |
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;
}
}
| 061304011116lyj-and | src/com/ch_linghu/fanfoudroid/task/GenericTask.java | Java | asf20 | 2,559 |
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) {
};
}
| 061304011116lyj-and | src/com/ch_linghu/fanfoudroid/task/TaskAdapter.java | Java | asf20 | 380 |
package com.ch_linghu.fanfoudroid.task;
public enum TaskResult {
OK, FAILED, CANCELLED,
NOT_FOLLOWED_ERROR, IO_ERROR, AUTH_ERROR
} | 061304011116lyj-and | src/com/ch_linghu/fanfoudroid/task/TaskResult.java | Java | asf20 | 134 |
/*
* Copyright (C) 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ch_linghu.fanfoudroid;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceScreen;
import android.util.Log;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.http.HttpClient;
import com.ch_linghu.fanfoudroid.ui.module.MyTextView;
import com.ch_linghu.fanfoudroid.R;
public class PreferencesActivity extends PreferenceActivity implements
SharedPreferences.OnSharedPreferenceChangeListener {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// 禁止横屏
if (TwitterApplication.mPref.getBoolean(
Preferences.FORCE_SCREEN_ORIENTATION_PORTRAIT, false)) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
// TODO: is this a hack?
setResult(RESULT_OK);
addPreferencesFromResource(R.xml.preferences);
}
@Override
protected void onResume() {
super.onResume();
// Set up a listener whenever a key changes
getPreferenceScreen().getSharedPreferences()
.registerOnSharedPreferenceChangeListener(this);
}
@Override
public boolean onPreferenceTreeClick(PreferenceScreen preferenceScreen,
Preference preference) {
return super.onPreferenceTreeClick(preferenceScreen, preference);
}
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences,
String key) {
if (key.equalsIgnoreCase(Preferences.NETWORK_TYPE)) {
HttpClient httpClient = TwitterApplication.mApi.getHttpClient();
String type = sharedPreferences.getString(Preferences.NETWORK_TYPE,
"");
if (type.equalsIgnoreCase(getString(R.string.pref_network_type_cmwap))) {
Log.d("LDS", "Set proxy for cmwap mode.");
httpClient.setProxy("10.0.0.172", 80, "http");
} else {
Log.d("LDS", "No proxy.");
httpClient.removeProxy();
}
} else if (key.equalsIgnoreCase(Preferences.UI_FONT_SIZE)) {
MyTextView.setFontSizeChanged(true);
}
}
}
| 061304011116lyj-and | src/com/ch_linghu/fanfoudroid/PreferencesActivity.java | Java | asf20 | 2,768 |
package com.ch_linghu.fanfoudroid.db;
/**
* All information of status table
*
*/
public final class StatusTablesInfo {
} | 061304011116lyj-and | src/com/ch_linghu/fanfoudroid/db/StatusTablesInfo.java | Java | asf20 | 126 |
package com.ch_linghu.fanfoudroid.db;
import android.database.Cursor;
import android.provider.BaseColumns;
import android.util.Log;
import com.ch_linghu.fanfoudroid.data.User;
public final class UserInfoTable implements BaseColumns {
public static final String TAG = "UserInfoTable";
public static final String TABLE_NAME = "userinfo";
public static final String FIELD_USER_NAME = "name";
public static final String FIELD_USER_SCREEN_NAME = "screen_name";
public static final String FIELD_LOCALTION = "location";
public static final String FIELD_DESCRIPTION = "description";
public static final String FIELD_PROFILE_IMAGE_URL = "profile_image_url";
public static final String FIELD_URL = "url";
public static final String FIELD_PROTECTED = "protected";
public static final String FIELD_FOLLOWERS_COUNT = "followers_count";
public static final String FIELD_FRIENDS_COUNT = "friends_count";
public static final String FIELD_FAVORITES_COUNT = "favourites_count";
public static final String FIELD_STATUSES_COUNT = "statuses_count";
public static final String FIELD_LAST_STATUS = "last_status";
public static final String FIELD_CREATED_AT = "created_at";
public static final String FIELD_FOLLOWING = "following";
public static final String FIELD_FOLLOWER_IDS = "follower_ids";
public static final String[] TABLE_COLUMNS = new String[] { _ID,
FIELD_USER_NAME, FIELD_USER_SCREEN_NAME, FIELD_LOCALTION,
FIELD_DESCRIPTION, FIELD_PROFILE_IMAGE_URL, FIELD_URL,
FIELD_PROTECTED, FIELD_FOLLOWERS_COUNT, FIELD_FRIENDS_COUNT,
FIELD_FAVORITES_COUNT, FIELD_STATUSES_COUNT, FIELD_LAST_STATUS,
FIELD_CREATED_AT, FIELD_FOLLOWING };
public static final String CREATE_TABLE = "create table " + TABLE_NAME
+ " (" + _ID + " text primary key on conflict replace, "
+ FIELD_USER_NAME + " text not null, " + FIELD_USER_SCREEN_NAME
+ " text, " + FIELD_LOCALTION + " text, " + FIELD_DESCRIPTION
+ " text, " + FIELD_PROFILE_IMAGE_URL + " text, " + FIELD_URL
+ " text, " + FIELD_PROTECTED + " boolean, "
+ FIELD_FOLLOWERS_COUNT + " integer, " + FIELD_FRIENDS_COUNT
+ " integer, " + FIELD_FAVORITES_COUNT + " integer, "
+ FIELD_STATUSES_COUNT + " integer, " + FIELD_LAST_STATUS
+ " text, " + FIELD_CREATED_AT + " date, " + FIELD_FOLLOWING
+ " boolean "
// +FIELD_FOLLOWER_IDS+" text"
+ ")";
/**
* TODO: 将游标解析为一条用户信息
*
* @param cursor
* 该方法不会关闭游标
* @return 成功返回User类型的单条数据, 失败返回null
*/
public static User parseCursor(Cursor cursor) {
if (null == cursor || 0 == cursor.getCount()) {
Log.w(TAG, "Cann't parse Cursor, bacause cursor is null or empty.");
return null;
}
User user = new User();
user.id = cursor.getString(cursor.getColumnIndex(_ID));
user.name = cursor.getString(cursor.getColumnIndex(FIELD_USER_NAME));
user.screenName = cursor.getString(cursor
.getColumnIndex(FIELD_USER_SCREEN_NAME));
user.location = cursor
.getString(cursor.getColumnIndex(FIELD_LOCALTION));
user.description = cursor.getString(cursor
.getColumnIndex(FIELD_DESCRIPTION));
user.profileImageUrl = cursor.getString(cursor
.getColumnIndex(FIELD_PROFILE_IMAGE_URL));
user.url = cursor.getString(cursor.getColumnIndex(FIELD_URL));
user.isProtected = (0 == cursor.getInt(cursor
.getColumnIndex(FIELD_PROTECTED))) ? false : true;
user.followersCount = cursor.getInt(cursor
.getColumnIndex(FIELD_FOLLOWERS_COUNT));
user.lastStatus = cursor.getString(cursor
.getColumnIndex(FIELD_LAST_STATUS));
user.friendsCount = cursor.getInt(cursor
.getColumnIndex(FIELD_FRIENDS_COUNT));
user.favoritesCount = cursor.getInt(cursor
.getColumnIndex(FIELD_FAVORITES_COUNT));
user.statusesCount = cursor.getInt(cursor
.getColumnIndex(FIELD_STATUSES_COUNT));
user.isFollowing = (0 == cursor.getInt(cursor
.getColumnIndex(FIELD_FOLLOWING))) ? false : true;
// TODO:报空指针异常,待查
// try {
// user.createdAt =
// StatusDatabase.DB_DATE_FORMATTER.parse(cursor.getString(cursor.getColumnIndex(MessageTable.FIELD_CREATED_AT)));
// } catch (ParseException e) {
// Log.w(TAG, "Invalid created at data.");
// }
return user;
}
} | 061304011116lyj-and | src/com/ch_linghu/fanfoudroid/db/UserInfoTable.java | Java | asf20 | 4,342 |
package com.ch_linghu.fanfoudroid.db;
import java.text.ParseException;
import android.database.Cursor;
import android.provider.BaseColumns;
import android.util.Log;
import com.ch_linghu.fanfoudroid.data.Dm;
/**
* Table - Direct Messages
*
*/
public final class MessageTable implements BaseColumns {
public static final String TAG = "MessageTable";
public static final int TYPE_GET = 0;
public static final int TYPE_SENT = 1;
public static final String TABLE_NAME = "message";
public static final int MAX_ROW_NUM = 20;
public static final String FIELD_USER_ID = "uid";
public static final String FIELD_USER_SCREEN_NAME = "screen_name";
public static final String FIELD_PROFILE_IMAGE_URL = "profile_image_url";
public static final String FIELD_CREATED_AT = "created_at";
public static final String FIELD_TEXT = "text";
public static final String FIELD_IN_REPLY_TO_STATUS_ID = "in_reply_to_status_id";
public static final String FIELD_IN_REPLY_TO_USER_ID = "in_reply_to_user_id";
public static final String FIELD_IN_REPLY_TO_SCREEN_NAME = "in_reply_to_screen_name";
public static final String FIELD_IS_UNREAD = "is_unread";
public static final String FIELD_IS_SENT = "is_send";
public static final String[] TABLE_COLUMNS = new String[] { _ID,
FIELD_USER_SCREEN_NAME, FIELD_TEXT, FIELD_PROFILE_IMAGE_URL,
FIELD_IS_UNREAD, FIELD_IS_SENT, FIELD_CREATED_AT, FIELD_USER_ID };
public static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME
+ " (" + _ID + " text primary key on conflict replace, "
+ FIELD_USER_SCREEN_NAME + " text not null, " + FIELD_TEXT
+ " text not null, " + FIELD_PROFILE_IMAGE_URL + " text not null, "
+ FIELD_IS_UNREAD + " boolean not null, " + FIELD_IS_SENT
+ " boolean not null, " + FIELD_CREATED_AT + " date not null, "
+ FIELD_USER_ID + " text)";
/**
* TODO: 将游标解析为一条私信
*
* @param cursor
* 该方法不会关闭游标
* @return 成功返回Dm类型的单条数据, 失败返回null
*/
public static Dm parseCursor(Cursor cursor) {
if (null == cursor || 0 == cursor.getCount()) {
Log.w(TAG, "Cann't parse Cursor, bacause cursor is null or empty.");
return null;
}
Dm dm = new Dm();
dm.id = cursor.getString(cursor.getColumnIndex(MessageTable._ID));
dm.screenName = cursor.getString(cursor
.getColumnIndex(MessageTable.FIELD_USER_SCREEN_NAME));
dm.text = cursor.getString(cursor
.getColumnIndex(MessageTable.FIELD_TEXT));
dm.profileImageUrl = cursor.getString(cursor
.getColumnIndex(MessageTable.FIELD_PROFILE_IMAGE_URL));
dm.isSent = (0 == cursor.getInt(cursor
.getColumnIndex(MessageTable.FIELD_IS_SENT))) ? false : true;
try {
dm.createdAt = TwitterDatabase.DB_DATE_FORMATTER.parse(cursor
.getString(cursor
.getColumnIndex(MessageTable.FIELD_CREATED_AT)));
} catch (ParseException e) {
Log.w(TAG, "Invalid created at data.");
}
dm.userId = cursor.getString(cursor
.getColumnIndex(MessageTable.FIELD_USER_ID));
return dm;
}
} | 061304011116lyj-and | src/com/ch_linghu/fanfoudroid/db/MessageTable.java | Java | asf20 | 3,028 |
package com.ch_linghu.fanfoudroid.db;
import android.database.Cursor;
import android.provider.BaseColumns;
import android.util.Log;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.util.DateTimeHelper;
/**
* Table - Statuses <br />
* <br />
* 为节省流量,故此表不保证本地数据库中所有消息具有前后连贯性, 而只确保最新的MAX_ROW_NUM条<br />
* 数据的连贯性, 超出部分则视为垃圾数据, 不再允许读取, 也不保证其是前后连续的.<br />
* <br />
* 因为用户可能中途长时间停止使用本客户端,而换其他客户端(如网页), <br />
* 如果保证本地所有数据的连贯性, 那么就必须自动去下载所有本地缺失的中间数据,<br />
* 而这些数据极有可能是用户通过其他客户端阅读过的无用信息, 浪费了用户流量.<br />
* <br />
* 即认为相对于旧信息而言, 新信息对于用户更为价值, 所以只会新信息进行维护, <br />
* 而旧信息一律视为无用的, 如用户需要查看超过MAX_ROW_NUM的旧数据, 可主动点击, <br />
* 从而请求服务器. 本地只缓存最有价值的MAX条最新信息.<br />
* <br />
* 本地数据库中前MAX_ROW_NUM条的数据模拟一个定长列队, 即在尾部插入N条消息, 就会使得头部<br />
* 的N条消息被标记为垃圾数据(但并不立即收回),只有在认为数据库数据过多时,<br />
* 可手动调用 <code>StatusDatabase.gc(int type)</code> 方法进行垃圾清理.<br />
*
*
*/
public final class StatusTable implements BaseColumns {
public static final String TAG = "StatusTable";
// Status Types
public static final int TYPE_HOME = 1; // 首页(我和我的好友)
public static final int TYPE_MENTION = 2; // 提到我的
public static final int TYPE_USER = 3; // 指定USER的
public static final int TYPE_FAVORITE = 4; // 收藏
public static final int TYPE_BROWSE = 5; // 随便看看
public static final String TABLE_NAME = "status";
public static final int MAX_ROW_NUM = 20; // 单类型数据安全区域
public static final String OWNER_ID = "owner"; // 用于标识数据的所有者。以便于处理其他用户的信息(如其他用户的收藏)
public static final String USER_ID = "uid";
public static final String USER_SCREEN_NAME = "screen_name";
public static final String PROFILE_IMAGE_URL = "profile_image_url";
public static final String CREATED_AT = "created_at";
public static final String TEXT = "text";
public static final String SOURCE = "source";
public static final String TRUNCATED = "truncated";
public static final String IN_REPLY_TO_STATUS_ID = "in_reply_to_status_id";
public static final String IN_REPLY_TO_USER_ID = "in_reply_to_user_id";
public static final String IN_REPLY_TO_SCREEN_NAME = "in_reply_to_screen_name";
public static final String FAVORITED = "favorited";
public static final String IS_UNREAD = "is_unread";
public static final String STATUS_TYPE = "status_type";
public static final String PIC_THUMB = "pic_thumbnail";
public static final String PIC_MID = "pic_middle";
public static final String PIC_ORIG = "pic_original";
// private static final String FIELD_PHOTO_URL = "photo_url";
// private double latitude = -1;
// private double longitude = -1;
// private String thumbnail_pic;
// private String bmiddle_pic;
// private String original_pic;
public static final String[] TABLE_COLUMNS = new String[] { _ID,
USER_SCREEN_NAME, TEXT, PROFILE_IMAGE_URL, IS_UNREAD, CREATED_AT,
FAVORITED, IN_REPLY_TO_STATUS_ID, IN_REPLY_TO_USER_ID,
IN_REPLY_TO_SCREEN_NAME, TRUNCATED, PIC_THUMB, PIC_MID, PIC_ORIG,
SOURCE, USER_ID, STATUS_TYPE, OWNER_ID };
public static final String CREATE_TABLE = "CREATE TABLE " + TABLE_NAME
+ " (" + _ID + " text not null," + STATUS_TYPE + " text not null, "
+ OWNER_ID + " text not null, " + USER_ID + " text not null, "
+ USER_SCREEN_NAME + " text not null, " + TEXT + " text not null, "
+ PROFILE_IMAGE_URL + " text not null, " + IS_UNREAD
+ " boolean not null, " + CREATED_AT
+ " date not null, "
+ SOURCE
+ " text not null, "
+ FAVORITED
+ " text, " // TODO : text -> boolean
+ IN_REPLY_TO_STATUS_ID + " text, " + IN_REPLY_TO_USER_ID
+ " text, " + IN_REPLY_TO_SCREEN_NAME + " text, " + PIC_THUMB
+ " text, " + PIC_MID + " text, " + PIC_ORIG + " text, "
+ TRUNCATED + " boolean ," + "PRIMARY KEY (" + _ID + "," + OWNER_ID
+ "," + STATUS_TYPE + "))";
/**
* 将游标解析为一条Tweet
*
*
* @param cursor
* 该方法不会移动或关闭游标
* @return 成功返回 Tweet 类型的单条数据, 失败返回null
*/
public static Tweet parseCursor(Cursor cursor) {
if (null == cursor || 0 == cursor.getCount()) {
Log.w(TAG, "Cann't parse Cursor, bacause cursor is null or empty.");
return null;
} else if (-1 == cursor.getPosition()) {
cursor.moveToFirst();
}
Tweet tweet = new Tweet();
tweet.id = cursor.getString(cursor.getColumnIndex(_ID));
tweet.createdAt = DateTimeHelper.parseDateTimeFromSqlite(cursor
.getString(cursor.getColumnIndex(CREATED_AT)));
tweet.favorited = cursor.getString(cursor.getColumnIndex(FAVORITED));
tweet.screenName = cursor.getString(cursor
.getColumnIndex(USER_SCREEN_NAME));
tweet.userId = cursor.getString(cursor.getColumnIndex(USER_ID));
tweet.text = cursor.getString(cursor.getColumnIndex(TEXT));
tweet.source = cursor.getString(cursor.getColumnIndex(SOURCE));
tweet.profileImageUrl = cursor.getString(cursor
.getColumnIndex(PROFILE_IMAGE_URL));
tweet.inReplyToScreenName = cursor.getString(cursor
.getColumnIndex(IN_REPLY_TO_SCREEN_NAME));
tweet.inReplyToStatusId = cursor.getString(cursor
.getColumnIndex(IN_REPLY_TO_STATUS_ID));
tweet.inReplyToUserId = cursor.getString(cursor
.getColumnIndex(IN_REPLY_TO_USER_ID));
tweet.truncated = cursor.getString(cursor.getColumnIndex(TRUNCATED));
tweet.thumbnail_pic = cursor
.getString(cursor.getColumnIndex(PIC_THUMB));
tweet.bmiddle_pic = cursor.getString(cursor.getColumnIndex(PIC_MID));
tweet.original_pic = cursor.getString(cursor.getColumnIndex(PIC_ORIG));
tweet.setStatusType(cursor.getInt(cursor.getColumnIndex(STATUS_TYPE)));
return tweet;
}
} | 061304011116lyj-and | src/com/ch_linghu/fanfoudroid/db/StatusTable.java | Java | asf20 | 6,291 |
package com.ch_linghu.fanfoudroid.db;
import java.text.ParseException;
import android.database.Cursor;
import android.provider.BaseColumns;
import android.util.Log;
import com.ch_linghu.fanfoudroid.data.User;
/**
* Table - Followers
*
*/
public final class FollowTable implements BaseColumns {
public static final String TAG = "FollowTable";
public static final String TABLE_NAME = "followers";
public static final String FIELD_USER_NAME = "name";
public static final String FIELD_USER_SCREEN_NAME = "screen_name";
public static final String FIELD_LOCALTION = "location";
public static final String FIELD_DESCRIPTION = "description";
public static final String FIELD_PROFILE_IMAGE_URL = "profile_image_url";
public static final String FIELD_URL = "url";
public static final String FIELD_PROTECTED = "protected";
public static final String FIELD_FOLLOWERS_COUNT = "followers_count";
public static final String FIELD_FRIENDS_COUNT = "friends_count";
public static final String FIELD_FAVORITES_COUNT = "favourites_count";
public static final String FIELD_STATUSES_COUNT = "statuses_count";
public static final String FIELD_LAST_STATUS = "last_status";
public static final String FIELD_CREATED_AT = "created_at";
public static final String FIELD_FOLLOWING = "following";
public static final String[] TABLE_COLUMNS = new String[] { _ID,
FIELD_USER_NAME, FIELD_USER_SCREEN_NAME, FIELD_LOCALTION,
FIELD_DESCRIPTION, FIELD_PROFILE_IMAGE_URL, FIELD_URL,
FIELD_PROTECTED, FIELD_FOLLOWERS_COUNT, FIELD_FRIENDS_COUNT,
FIELD_FAVORITES_COUNT, FIELD_STATUSES_COUNT, FIELD_LAST_STATUS,
FIELD_CREATED_AT, FIELD_FOLLOWING };
public static final String CREATE_TABLE = "create table " + TABLE_NAME
+ " (" + _ID + " text primary key on conflict replace, "
+ FIELD_USER_NAME + " text not null, " + FIELD_USER_SCREEN_NAME
+ " text, " + FIELD_LOCALTION + " text, " + FIELD_DESCRIPTION
+ " text, " + FIELD_PROFILE_IMAGE_URL + " text, " + FIELD_URL
+ " text, " + FIELD_PROTECTED + " boolean, "
+ FIELD_FOLLOWERS_COUNT + " integer, " + FIELD_FRIENDS_COUNT
+ " integer, " + FIELD_FAVORITES_COUNT + " integer, "
+ FIELD_STATUSES_COUNT + " integer, " + FIELD_LAST_STATUS
+ " text, " + FIELD_CREATED_AT + " date, " + FIELD_FOLLOWING
+ " boolean " + ")";
/**
* TODO: 将游标解析为一条用户信息
*
* @param cursor
* 该方法不会关闭游标
* @return 成功返回User类型的单条数据, 失败返回null
*/
public static User parseCursor(Cursor cursor) {
if (null == cursor || 0 == cursor.getCount()) {
Log.w(TAG, "Cann't parse Cursor, bacause cursor is null or empty.");
return null;
}
User user = new User();
user.id = cursor.getString(cursor.getColumnIndex(FollowTable._ID));
user.name = cursor.getString(cursor
.getColumnIndex(FollowTable.FIELD_USER_NAME));
user.screenName = cursor.getString(cursor
.getColumnIndex(FollowTable.FIELD_USER_SCREEN_NAME));
user.location = cursor.getString(cursor
.getColumnIndex(FollowTable.FIELD_LOCALTION));
user.description = cursor.getString(cursor
.getColumnIndex(FollowTable.FIELD_DESCRIPTION));
user.profileImageUrl = cursor.getString(cursor
.getColumnIndex(FollowTable.FIELD_PROFILE_IMAGE_URL));
user.url = cursor.getString(cursor
.getColumnIndex(FollowTable.FIELD_URL));
user.isProtected = (0 == cursor.getInt(cursor
.getColumnIndex(FollowTable.FIELD_PROTECTED))) ? false : true;
user.followersCount = cursor.getInt(cursor
.getColumnIndex(FollowTable.FIELD_FOLLOWERS_COUNT));
user.lastStatus = cursor.getString(cursor
.getColumnIndex(FollowTable.FIELD_LAST_STATUS));
;
user.friendsCount = cursor.getInt(cursor
.getColumnIndex(FollowTable.FIELD_FRIENDS_COUNT));
user.favoritesCount = cursor.getInt(cursor
.getColumnIndex(FollowTable.FIELD_FAVORITES_COUNT));
user.statusesCount = cursor.getInt(cursor
.getColumnIndex(FollowTable.FIELD_STATUSES_COUNT));
user.isFollowing = (0 == cursor.getInt(cursor
.getColumnIndex(FollowTable.FIELD_FOLLOWING))) ? false : true;
try {
user.createdAt = TwitterDatabase.DB_DATE_FORMATTER.parse(cursor
.getString(cursor
.getColumnIndex(MessageTable.FIELD_CREATED_AT)));
} catch (ParseException e) {
Log.w(TAG, "Invalid created at data.");
}
return user;
}
} | 061304011116lyj-and | src/com/ch_linghu/fanfoudroid/db/FollowTable.java | Java | asf20 | 4,341 |
package com.ch_linghu.fanfoudroid.db;
import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.List;
import java.util.Locale;
import android.content.ContentValues;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteDatabase.CursorFactory;
import android.database.sqlite.SQLiteOpenHelper;
import android.text.TextUtils;
import android.util.Log;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.dao.StatusDAO;
import com.ch_linghu.fanfoudroid.data.Dm;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.fanfou.Status;
import com.ch_linghu.fanfoudroid.util.DebugTimer;
/**
* A Database which contains all statuses and direct-messages, use
* getInstane(Context) to get a new instance
*
*/
public class TwitterDatabase {
private static final String TAG = "TwitterDatabase";
private static final String DATABASE_NAME = "status_db";
private static final int DATABASE_VERSION = 1;
private static TwitterDatabase instance = null;
private static DatabaseHelper mOpenHelper = null;
private Context mContext = null;
/**
* SQLiteOpenHelper
*
*/
private static class DatabaseHelper extends SQLiteOpenHelper {
// Construct
public DatabaseHelper(Context context, String name,
CursorFactory factory, int version) {
super(context, name, factory, version);
}
public DatabaseHelper(Context context, String name) {
this(context, name, DATABASE_VERSION);
}
public DatabaseHelper(Context context) {
this(context, DATABASE_NAME, DATABASE_VERSION);
}
public DatabaseHelper(Context context, int version) {
this(context, DATABASE_NAME, null, version);
}
public DatabaseHelper(Context context, String name, int version) {
this(context, name, null, version);
}
@Override
public void onCreate(SQLiteDatabase db) {
Log.d(TAG, "Create Database.");
// Log.d(TAG, StatusTable.STATUS_TABLE_CREATE);
db.execSQL(StatusTable.CREATE_TABLE);
db.execSQL(MessageTable.CREATE_TABLE);
db.execSQL(FollowTable.CREATE_TABLE);
// 2011.03.01 add beta
db.execSQL(UserInfoTable.CREATE_TABLE);
}
@Override
public synchronized void close() {
Log.d(TAG, "Close Database.");
super.close();
}
@Override
public void onOpen(SQLiteDatabase db) {
Log.d(TAG, "Open Database.");
super.onOpen(db);
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.d(TAG, "Upgrade Database.");
dropAllTables(db);
}
private void dropAllTables(SQLiteDatabase db) {
db.execSQL("DROP TABLE IF EXISTS " + StatusTable.TABLE_NAME);
db.execSQL("DROP TABLE IF EXISTS " + MessageTable.TABLE_NAME);
db.execSQL("DROP TABLE IF EXISTS " + FollowTable.TABLE_NAME);
// 2011.03.01 add
db.execSQL("DROP TABLE IF EXISTS " + UserInfoTable.TABLE_NAME);
}
}
private TwitterDatabase(Context context) {
mContext = context;
mOpenHelper = new DatabaseHelper(context);
}
public static synchronized TwitterDatabase getInstance(Context context) {
if (null == instance) {
return new TwitterDatabase(context);
}
return instance;
}
// 测试用
public SQLiteOpenHelper getSQLiteOpenHelper() {
return mOpenHelper;
}
public static SQLiteDatabase getDb(boolean writeable) {
if (writeable) {
return mOpenHelper.getWritableDatabase();
} else {
return mOpenHelper.getReadableDatabase();
}
}
public void close() {
if (null != instance) {
mOpenHelper.close();
instance = null;
}
}
/**
* 清空所有表中数据, 谨慎使用
*
*/
public void clearData() {
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
db.execSQL("DELETE FROM " + StatusTable.TABLE_NAME);
db.execSQL("DELETE FROM " + MessageTable.TABLE_NAME);
db.execSQL("DELETE FROM " + FollowTable.TABLE_NAME);
// 2011.03.01 add
db.execSQL("DELETE FROM " + UserInfoTable.TABLE_NAME);
}
/**
* 直接删除数据库文件, 调试用
*
* @return true if this file was deleted, false otherwise.
* @deprecated
*/
private boolean deleteDatabase() {
File dbFile = mContext.getDatabasePath(DATABASE_NAME);
return dbFile.delete();
}
/**
* 取出某类型的一条消息
*
* @param tweetId
* @param type
* of status <li>StatusTable.TYPE_HOME</li> <li>
* StatusTable.TYPE_MENTION</li> <li>StatusTable.TYPE_USER</li>
* <li>StatusTable.TYPE_FAVORITE</li> <li>-1 means all types</li>
* @return 将Cursor转换过的Tweet对象
* @deprecated use StatusDAO#findStatus()
*/
public Tweet queryTweet(String tweetId, int type) {
SQLiteDatabase Db = mOpenHelper.getWritableDatabase();
String selection = StatusTable._ID + "=? ";
if (-1 != type) {
selection += " AND " + StatusTable.STATUS_TYPE + "=" + type;
}
Cursor cursor = Db.query(StatusTable.TABLE_NAME,
StatusTable.TABLE_COLUMNS, selection, new String[] { tweetId },
null, null, null);
Tweet tweet = null;
if (cursor != null) {
cursor.moveToFirst();
if (cursor.getCount() > 0) {
tweet = StatusTable.parseCursor(cursor);
}
}
cursor.close();
return tweet;
}
/**
* 快速检查某条消息是否存在(指定类型)
*
* @param tweetId
* @param type
* <li>StatusTable.TYPE_HOME</li> <li>StatusTable.TYPE_MENTION</li>
* <li>StatusTable.TYPE_USER</li> <li>StatusTable.TYPE_FAVORITE</li>
* @return is exists
* @deprecated use StatusDAO#isExists()
*/
public boolean isExists(String tweetId, String owner, int type) {
SQLiteDatabase Db = mOpenHelper.getWritableDatabase();
boolean result = false;
Cursor cursor = Db.query(StatusTable.TABLE_NAME,
new String[] { StatusTable._ID }, StatusTable._ID + " =? AND "
+ StatusTable.OWNER_ID + "=? AND "
+ StatusTable.STATUS_TYPE + " = " + type, new String[] {
tweetId, owner }, null, null, null);
if (cursor != null && cursor.getCount() > 0) {
result = true;
}
cursor.close();
return result;
}
/**
* 删除一条消息
*
* @param tweetId
* @param type
* -1 means all types
* @return the number of rows affected if a whereClause is passed in, 0
* otherwise. To remove all rows and get a count pass "1" as the
* whereClause.
* @deprecated use {@link StatusDAO#deleteStatus(String, String, int)}
*/
public int deleteTweet(String tweetId, String owner, int type) {
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
String where = StatusTable._ID + " =? ";
if (!TextUtils.isEmpty(owner)) {
where += " AND " + StatusTable.OWNER_ID + " = '" + owner + "' ";
}
if (-1 != type) {
where += " AND " + StatusTable.STATUS_TYPE + " = " + type;
}
return db.delete(StatusTable.TABLE_NAME, where,
new String[] { tweetId });
}
/**
* 删除超过MAX_ROW_NUM垃圾数据
*
* @param type
* <li>StatusTable.TYPE_HOME</li> <li>StatusTable.TYPE_MENTION</li>
* <li>StatusTable.TYPE_USER</li> <li>StatusTable.TYPE_FAVORITE</li>
* <li>-1 means all types</li>
*/
public void gc(String owner, int type) {
SQLiteDatabase mDb = mOpenHelper.getWritableDatabase();
String sql = "DELETE FROM " + StatusTable.TABLE_NAME + " WHERE "
+ StatusTable._ID + " NOT IN " + " (SELECT " + StatusTable._ID // 子句
+ " FROM " + StatusTable.TABLE_NAME;
boolean first = true;
if (!TextUtils.isEmpty(owner)) {
sql += " WHERE " + StatusTable.OWNER_ID + " = '" + owner + "' ";
first = false;
}
if (type != -1) {
if (first) {
sql += " WHERE ";
} else {
sql += " AND ";
}
sql += StatusTable.STATUS_TYPE + " = " + type + " ";
}
sql += " ORDER BY " + StatusTable.CREATED_AT + " DESC LIMIT "
+ StatusTable.MAX_ROW_NUM + ")";
if (!TextUtils.isEmpty(owner)) {
sql += " AND " + StatusTable.OWNER_ID + " = '" + owner + "' ";
}
if (type != -1) {
sql += " AND " + StatusTable.STATUS_TYPE + " = " + type + " ";
}
Log.v(TAG, sql);
mDb.execSQL(sql);
}
public final static DateFormat DB_DATE_FORMATTER = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss.SSS", Locale.US);
private static final int CONFLICT_REPLACE = 0x00000005;
/**
* 向Status表中写入一行数据, 此方法为私有方法, 外部插入数据请使用 putTweets()
*
* @param tweet
* 需要写入的单条消息
* @return the row ID of the newly inserted row, or -1 if an error occurred
* @deprecated use {@link StatusDAO#insertStatus(Status, boolean)}
*/
public long insertTweet(Tweet tweet, String owner, int type,
boolean isUnread) {
SQLiteDatabase Db = mOpenHelper.getWritableDatabase();
if (isExists(tweet.id, owner, type)) {
Log.w(TAG, tweet.id + "is exists.");
return -1;
}
ContentValues initialValues = makeTweetValues(tweet, owner, type,
isUnread);
long id = Db.insert(StatusTable.TABLE_NAME, null, initialValues);
if (-1 == id) {
Log.e(TAG, "cann't insert the tweet : " + tweet.toString());
} else {
// Log.v(TAG, "Insert a status into database : " +
// tweet.toString());
}
return id;
}
/**
* 更新一条消息
*
* @param tweetId
* @param values
* ContentValues 需要更新字段的键值对
* @return the number of rows affected
* @deprecated use {@link StatusDAO#updateStatus(String, ContentValues)}
*/
public int updateTweet(String tweetId, ContentValues values) {
Log.v(TAG, "Update Tweet : " + tweetId + " " + values.toString());
SQLiteDatabase Db = mOpenHelper.getWritableDatabase();
return Db.update(StatusTable.TABLE_NAME, values,
StatusTable._ID + "=?", new String[] { tweetId });
}
/** @deprecated */
private ContentValues makeTweetValues(Tweet tweet, String owner, int type,
boolean isUnread) {
// 插入一条新消息
ContentValues initialValues = new ContentValues();
initialValues.put(StatusTable.OWNER_ID, owner);
initialValues.put(StatusTable.STATUS_TYPE, type);
initialValues.put(StatusTable._ID, tweet.id);
initialValues.put(StatusTable.TEXT, tweet.text);
initialValues.put(StatusTable.USER_ID, tweet.userId);
initialValues.put(StatusTable.USER_SCREEN_NAME, tweet.screenName);
initialValues.put(StatusTable.PROFILE_IMAGE_URL, tweet.profileImageUrl);
initialValues.put(StatusTable.PIC_THUMB, tweet.thumbnail_pic);
initialValues.put(StatusTable.PIC_MID, tweet.bmiddle_pic);
initialValues.put(StatusTable.PIC_ORIG, tweet.original_pic);
initialValues.put(StatusTable.FAVORITED, tweet.favorited);
initialValues.put(StatusTable.IN_REPLY_TO_STATUS_ID,
tweet.inReplyToStatusId);
initialValues.put(StatusTable.IN_REPLY_TO_USER_ID,
tweet.inReplyToUserId);
initialValues.put(StatusTable.IN_REPLY_TO_SCREEN_NAME,
tweet.inReplyToScreenName);
// initialValues.put(FIELD_IS_REPLY, tweet.isReply());
initialValues.put(StatusTable.CREATED_AT,
DB_DATE_FORMATTER.format(tweet.createdAt));
initialValues.put(StatusTable.SOURCE, tweet.source);
initialValues.put(StatusTable.IS_UNREAD, isUnread);
initialValues.put(StatusTable.TRUNCATED, tweet.truncated);
// TODO: truncated
return initialValues;
}
/**
* 写入N条消息
*
* @param tweets
* 需要写入的消息List
* @return 写入的记录条数
*/
public int putTweets(List<Tweet> tweets, String owner, int type,
boolean isUnread) {
if (TwitterApplication.DEBUG) {
DebugTimer.betweenStart("Status DB");
}
if (null == tweets || 0 == tweets.size()) {
return 0;
}
SQLiteDatabase db = mOpenHelper.getWritableDatabase();
int result = 0;
try {
db.beginTransaction();
for (int i = tweets.size() - 1; i >= 0; i--) {
Tweet tweet = tweets.get(i);
Log.d(TAG, "insertTweet, tweet id=" + tweet.id);
if (TextUtils.isEmpty(tweet.id) || tweet.id.equals("false")){
Log.e(TAG, "tweet id is null, ghost message encounted");
continue;
}
ContentValues initialValues = makeTweetValues(tweet, owner,
type, isUnread);
long id = db
.insert(StatusTable.TABLE_NAME, null, initialValues);
if (-1 == id) {
Log.e(TAG, "cann't insert the tweet : " + tweet.toString());
} else {
++result;
// Log.v(TAG,
// String.format("Insert a status into database[%s] : %s",
// owner, tweet.toString()));
Log.v("TAG", "Insert Status");
}
}
// gc(type); // 保持总量
db.setTransactionSuccessful();
} finally {
db.endTransaction();
}
if (TwitterApplication.DEBUG) {
DebugTimer.betweenEnd("Status DB");
}
return result;
}
/**
* 取出指定用户的某一类型的所有消息
*
* @param userId
* @param tableName
* @return a cursor
* @deprecated use {@link StatusDAO#findStatuses(String, int)}
*/
public Cursor fetchAllTweets(String owner, int type) {
SQLiteDatabase mDb = mOpenHelper.getReadableDatabase();
return mDb.query(StatusTable.TABLE_NAME, StatusTable.TABLE_COLUMNS,
StatusTable.OWNER_ID + " = ? AND " + StatusTable.STATUS_TYPE
+ " = " + type, new String[] { owner }, null, null,
StatusTable.CREATED_AT + " DESC ");
// LIMIT " + StatusTable.MAX_ROW_NUM);
}
/**
* 取出自己的某一类型的所有消息
*
* @param tableName
* @return a cursor
*/
public Cursor fetchAllTweets(int type) {
// 获取登录用户id
SharedPreferences preferences = TwitterApplication.mPref;
String myself = preferences.getString(Preferences.CURRENT_USER_ID,
TwitterApplication.mApi.getUserId());
return fetchAllTweets(myself, type);
}
/**
* 清空某类型的所有信息
*
* @param tableName
* @return the number of rows affected if a whereClause is passed in, 0
* otherwise. To remove all rows and get a count pass "1" as the
* whereClause.
*/
public int dropAllTweets(int type) {
SQLiteDatabase mDb = mOpenHelper.getReadableDatabase();
return mDb.delete(StatusTable.TABLE_NAME, StatusTable.STATUS_TYPE
+ " = " + type, null);
}
/**
* 取出本地某类型最新消息ID
*
* @param type
* @return The newest Status Id
*/
public String fetchMaxTweetId(String owner, int type) {
return fetchMaxOrMinTweetId(owner, type, true);
}
/**
* 取出本地某类型最旧消息ID
*
* @param tableName
* @return The oldest Status Id
*/
public String fetchMinTweetId(String owner, int type) {
return fetchMaxOrMinTweetId(owner, type, false);
}
private String fetchMaxOrMinTweetId(String owner, int type, boolean isMax) {
SQLiteDatabase mDb = mOpenHelper.getReadableDatabase();
String sql = "SELECT " + StatusTable._ID + " FROM "
+ StatusTable.TABLE_NAME + " WHERE " + StatusTable.STATUS_TYPE
+ " = " + type + " AND " + StatusTable.OWNER_ID + " = '"
+ owner + "' " + " ORDER BY " + StatusTable.CREATED_AT;
if (isMax)
sql += " DESC ";
Cursor mCursor = mDb.rawQuery(sql + " LIMIT 1", null);
String result = null;
if (mCursor == null) {
return result;
}
mCursor.moveToFirst();
if (mCursor.getCount() == 0) {
result = null;
} else {
result = mCursor.getString(0);
}
mCursor.close();
return result;
}
/**
* Count unread tweet
*
* @param tableName
* @return
*/
public int fetchUnreadCount(String owner, int type) {
SQLiteDatabase mDb = mOpenHelper.getReadableDatabase();
Cursor mCursor = mDb.rawQuery("SELECT COUNT(" + StatusTable._ID + ")"
+ " FROM " + StatusTable.TABLE_NAME + " WHERE "
+ StatusTable.STATUS_TYPE + " = " + type + " AND "
+ StatusTable.OWNER_ID + " = '" + owner + "' AND "
+ StatusTable.IS_UNREAD + " = 1 ",
// "LIMIT " + StatusTable.MAX_ROW_NUM,
null);
int result = 0;
if (mCursor == null) {
return result;
}
mCursor.moveToFirst();
result = mCursor.getInt(0);
mCursor.close();
return result;
}
public int addNewTweetsAndCountUnread(List<Tweet> tweets, String owner,
int type) {
putTweets(tweets, owner, type, true);
return fetchUnreadCount(owner, type);
}
/**
* Set isFavorited
*
* @param tweetId
* @param isFavorited
* @return Is Succeed
* @deprecated use {@link Status#setFavorited(boolean)} and
* {@link StatusDAO#updateStatus(Status)}
*/
public boolean setFavorited(String tweetId, String isFavorited) {
ContentValues values = new ContentValues();
values.put(StatusTable.FAVORITED, isFavorited);
int i = updateTweet(tweetId, values);
return (i > 0) ? true : false;
}
// DM & Follower
/**
* 写入一条私信
*
* @param dm
* @param isUnread
* @return the row ID of the newly inserted row, or -1 if an error occurred,
* 因为主键的原因,此处返回的不是 _ID 的值, 而是一个自增长的 row_id
*/
public long createDm(Dm dm, boolean isUnread) {
SQLiteDatabase mDb = mOpenHelper.getWritableDatabase();
ContentValues initialValues = new ContentValues();
initialValues.put(MessageTable._ID, dm.id);
initialValues.put(MessageTable.FIELD_USER_SCREEN_NAME, dm.screenName);
initialValues.put(MessageTable.FIELD_TEXT, dm.text);
initialValues.put(MessageTable.FIELD_PROFILE_IMAGE_URL,
dm.profileImageUrl);
initialValues.put(MessageTable.FIELD_IS_UNREAD, isUnread);
initialValues.put(MessageTable.FIELD_IS_SENT, dm.isSent);
initialValues.put(MessageTable.FIELD_CREATED_AT,
DB_DATE_FORMATTER.format(dm.createdAt));
initialValues.put(MessageTable.FIELD_USER_ID, dm.userId);
return mDb.insert(MessageTable.TABLE_NAME, null, initialValues);
}
//
/**
* Create a follower
*
* @param userId
* @return the row ID of the newly inserted row, or -1 if an error occurred
*/
public long createFollower(String userId) {
SQLiteDatabase mDb = mOpenHelper.getWritableDatabase();
ContentValues initialValues = new ContentValues();
initialValues.put(FollowTable._ID, userId);
long rowId = mDb.insert(FollowTable.TABLE_NAME, null, initialValues);
if (-1 == rowId) {
Log.e(TAG, "Cann't create Follower : " + userId);
} else {
Log.v(TAG, "Success create follower : " + userId);
}
return rowId;
}
/**
* 清空Followers表并添加新内容
*
* @param followers
*/
public void syncFollowers(List<String> followers) {
SQLiteDatabase mDb = mOpenHelper.getWritableDatabase();
try {
mDb.beginTransaction();
boolean result = deleteAllFollowers();
Log.v(TAG, "Result of DeleteAllFollowers: " + result);
for (String userId : followers) {
createFollower(userId);
}
mDb.setTransactionSuccessful();
} finally {
mDb.endTransaction();
}
}
/**
* @param type
* <li>MessageTable.TYPE_SENT</li> <li>MessageTable.TYPE_GET</li>
* <li>其他任何值都认为取出所有类型</li>
* @return
*/
public Cursor fetchAllDms(int type) {
SQLiteDatabase mDb = mOpenHelper.getReadableDatabase();
String selection = null;
if (MessageTable.TYPE_SENT == type) {
selection = MessageTable.FIELD_IS_SENT + " = "
+ MessageTable.TYPE_SENT;
} else if (MessageTable.TYPE_GET == type) {
selection = MessageTable.FIELD_IS_SENT + " = "
+ MessageTable.TYPE_GET;
}
return mDb.query(MessageTable.TABLE_NAME, MessageTable.TABLE_COLUMNS,
selection, null, null, null, MessageTable.FIELD_CREATED_AT
+ " DESC");
}
public Cursor fetchInboxDms() {
return fetchAllDms(MessageTable.TYPE_GET);
}
public Cursor fetchSendboxDms() {
return fetchAllDms(MessageTable.TYPE_SENT);
}
public Cursor fetchAllFollowers() {
SQLiteDatabase mDb = mOpenHelper.getReadableDatabase();
return mDb.query(FollowTable.TABLE_NAME, FollowTable.TABLE_COLUMNS,
null, null, null, null, null);
}
/**
* FIXME:
*
* @param filter
* @return
*/
public Cursor getFollowerUsernames(String filter) {
SQLiteDatabase mDb = mOpenHelper.getReadableDatabase();
String likeFilter = '%' + filter + '%';
// FIXME: 此方法的作用应该是在于在写私信时自动完成联系人的功能,
// 改造数据库后,因为本地tweets表中的数据有限, 所以几乎使得该功能没有实际价值(因为能从数据库中读到的联系人很少)
// 在完成关注者/被关注者两个界面后, 看能不能使得本地有一份
// [互相关注] 的 id/name 缓存(即getFriendsIds和getFollowersIds的交集, 因为客户端只能给他们发私信,
// 如果按现在
// 只提示followers的列表则很容易造成服务器返回"只能给互相关注的人发私信"的错误信息, 这会造成用户无法理解,
// 因为此联系人是我们提供给他们选择的,
// 并且将目前的自动完成功能的基础上加一个[选择联系人]按钮, 用于启动一个新的联系人列表页面以显示所有可发送私信的联系人对象,
// 类似手机写短信时的选择联系人功能
return null;
// FIXME: clean this up. 新数据库中失效, 表名, 列名
// return mDb.rawQuery(
// "SELECT user_id AS _id, user"
// + " FROM (SELECT user_id, user FROM tweets"
// + " INNER JOIN followers on tweets.user_id = followers._id UNION"
// + " SELECT user_id, user FROM dms INNER JOIN followers"
// + " on dms.user_id = followers._id)"
// + " WHERE user LIKE ?"
// + " ORDER BY user COLLATE NOCASE",
// new String[] { likeFilter });
}
/**
* @param userId
* 该用户是否follow Me
* @deprecated 未使用
* @return
*/
public boolean isFollower(String userId) {
SQLiteDatabase mDb = mOpenHelper.getReadableDatabase();
Cursor cursor = mDb.query(FollowTable.TABLE_NAME,
FollowTable.TABLE_COLUMNS, FollowTable._ID + "= ?",
new String[] { userId }, null, null, null);
boolean result = false;
if (cursor != null && cursor.moveToFirst()) {
result = true;
}
cursor.close();
return result;
}
public boolean deleteAllFollowers() {
SQLiteDatabase mDb = mOpenHelper.getWritableDatabase();
return mDb.delete(FollowTable.TABLE_NAME, null, null) > 0;
}
public boolean deleteDm(String id) {
SQLiteDatabase mDb = mOpenHelper.getWritableDatabase();
return mDb.delete(MessageTable.TABLE_NAME,
String.format("%s = '%s'", MessageTable._ID, id), null) > 0;
}
/**
* @param tableName
* @return the number of rows affected
*/
public int markAllTweetsRead(String owner, int type) {
SQLiteDatabase mDb = mOpenHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(StatusTable.IS_UNREAD, 0);
return mDb.update(StatusTable.TABLE_NAME, values,
StatusTable.STATUS_TYPE + "=" + type, null);
}
public boolean deleteAllDms() {
SQLiteDatabase mDb = mOpenHelper.getWritableDatabase();
return mDb.delete(MessageTable.TABLE_NAME, null, null) > 0;
}
public int markAllDmsRead() {
SQLiteDatabase mDb = mOpenHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(MessageTable.FIELD_IS_UNREAD, 0);
return mDb.update(MessageTable.TABLE_NAME, values, null, null);
}
public String fetchMaxDmId(boolean isSent) {
SQLiteDatabase mDb = mOpenHelper.getReadableDatabase();
Cursor mCursor = mDb.rawQuery("SELECT " + MessageTable._ID + " FROM "
+ MessageTable.TABLE_NAME + " WHERE "
+ MessageTable.FIELD_IS_SENT + " = ? " + " ORDER BY "
+ MessageTable.FIELD_CREATED_AT + " DESC LIMIT 1",
new String[] { isSent ? "1" : "0" });
String result = null;
if (mCursor == null) {
return result;
}
mCursor.moveToFirst();
if (mCursor.getCount() == 0) {
result = null;
} else {
result = mCursor.getString(0);
}
mCursor.close();
return result;
}
public int addNewDmsAndCountUnread(List<Dm> dms) {
addDms(dms, true);
return fetchUnreadDmCount();
}
public int fetchDmCount() {
SQLiteDatabase mDb = mOpenHelper.getReadableDatabase();
Cursor mCursor = mDb.rawQuery("SELECT COUNT(" + MessageTable._ID
+ ") FROM " + MessageTable.TABLE_NAME, null);
int result = 0;
if (mCursor == null) {
return result;
}
mCursor.moveToFirst();
result = mCursor.getInt(0);
mCursor.close();
return result;
}
private int fetchUnreadDmCount() {
SQLiteDatabase mDb = mOpenHelper.getReadableDatabase();
Cursor mCursor = mDb.rawQuery("SELECT COUNT(" + MessageTable._ID
+ ") FROM " + MessageTable.TABLE_NAME + " WHERE "
+ MessageTable.FIELD_IS_UNREAD + " = 1", null);
int result = 0;
if (mCursor == null) {
return result;
}
mCursor.moveToFirst();
result = mCursor.getInt(0);
mCursor.close();
return result;
}
public void addDms(List<Dm> dms, boolean isUnread) {
SQLiteDatabase mDb = mOpenHelper.getWritableDatabase();
try {
mDb.beginTransaction();
for (Dm dm : dms) {
createDm(dm, isUnread);
}
// limitRows(TABLE_DIRECTMESSAGE, TwitterApi.RETRIEVE_LIMIT);
mDb.setTransactionSuccessful();
} finally {
mDb.endTransaction();
}
}
// 2011.03.01 add
// UserInfo操作
public Cursor getAllUserInfo() {
SQLiteDatabase mDb = mOpenHelper.getReadableDatabase();
return mDb.query(UserInfoTable.TABLE_NAME, UserInfoTable.TABLE_COLUMNS,
null, null, null, null, null);
}
/**
* 根据id列表获取user数据
*
* @param userIds
* @return
*/
public Cursor getUserInfoByIds(String[] userIds) {
SQLiteDatabase mDb = mOpenHelper.getReadableDatabase();
String userIdStr = "";
for (String id : userIds) {
userIdStr += "'" + id + "',";
}
if (userIds.length == 0) {
userIdStr = "'',";
}
userIdStr = userIdStr.substring(0, userIdStr.lastIndexOf(","));// 删除最后的逗号
return mDb.query(UserInfoTable.TABLE_NAME, UserInfoTable.TABLE_COLUMNS,
UserInfoTable._ID + " in (" + userIdStr + ")", null, null,
null, null);
}
/**
* 新建用户
*
* @param user
* @return the row ID of the newly inserted row, or -1 if an error occurred
*/
public long createUserInfo(com.ch_linghu.fanfoudroid.data.User user) {
SQLiteDatabase mDb = mOpenHelper.getWritableDatabase();
ContentValues initialValues = new ContentValues();
initialValues.put(UserInfoTable._ID, user.id);
initialValues.put(UserInfoTable.FIELD_USER_NAME, user.name);
initialValues
.put(UserInfoTable.FIELD_USER_SCREEN_NAME, user.screenName);
initialValues.put(UserInfoTable.FIELD_LOCALTION, user.location);
initialValues.put(UserInfoTable.FIELD_DESCRIPTION, user.description);
initialValues.put(UserInfoTable.FIELD_PROFILE_IMAGE_URL,
user.profileImageUrl);
initialValues.put(UserInfoTable.FIELD_URL, user.url);
initialValues.put(UserInfoTable.FIELD_PROTECTED, user.isProtected);
initialValues.put(UserInfoTable.FIELD_FOLLOWERS_COUNT,
user.followersCount);
initialValues.put(UserInfoTable.FIELD_LAST_STATUS, user.lastStatus);
initialValues.put(UserInfoTable.FIELD_FRIENDS_COUNT, user.friendsCount);
initialValues.put(UserInfoTable.FIELD_FAVORITES_COUNT,
user.favoritesCount);
initialValues.put(UserInfoTable.FIELD_STATUSES_COUNT,
user.statusesCount);
initialValues.put(UserInfoTable.FIELD_FOLLOWING, user.isFollowing);
// long rowId = mDb.insertWithOnConflict(UserInfoTable.TABLE_NAME, null,
// initialValues,SQLiteDatabase.CONFLICT_REPLACE);
long rowId = insertWithOnConflict(mDb, UserInfoTable.TABLE_NAME, null,
initialValues, CONFLICT_REPLACE);
if (-1 == rowId) {
Log.e(TAG, "Cann't create user : " + user.id);
} else {
Log.v(TAG, "create create user : " + user.id);
}
return rowId;
}
// SQLiteDatabase.insertWithConflict是LEVEL 8(2.2)才引入的新方法
// 为了兼容旧版,这里给出一个简化的兼容实现
// 要注意的是这个实现和标准的函数行为并不完全一致
private long insertWithOnConflict(SQLiteDatabase db, String tableName,
String nullColumnHack, ContentValues initialValues,
int conflictReplace) {
long rowId = db.insert(tableName, nullColumnHack, initialValues);
if (-1 == rowId) {
// 尝试update
rowId = db.update(tableName, initialValues, UserInfoTable._ID + "="
+ initialValues.getAsString(UserInfoTable._ID), null);
}
return rowId;
}
public long createWeiboUserInfo(com.ch_linghu.fanfoudroid.fanfou.User user) {
SQLiteDatabase mDb = mOpenHelper.getWritableDatabase();
ContentValues args = new ContentValues();
args.put(UserInfoTable._ID, user.getId());
args.put(UserInfoTable.FIELD_USER_NAME, user.getName());
args.put(UserInfoTable.FIELD_USER_SCREEN_NAME, user.getScreenName());
String location = user.getLocation();
args.put(UserInfoTable.FIELD_LOCALTION, location);
String description = user.getDescription();
args.put(UserInfoTable.FIELD_DESCRIPTION, description);
args.put(UserInfoTable.FIELD_PROFILE_IMAGE_URL, user
.getProfileImageURL().toString());
if (user.getURL() != null) {
args.put(UserInfoTable.FIELD_URL, user.getURL().toString());
}
args.put(UserInfoTable.FIELD_PROTECTED, user.isProtected());
args.put(UserInfoTable.FIELD_FOLLOWERS_COUNT, user.getFollowersCount());
args.put(UserInfoTable.FIELD_LAST_STATUS, user.getStatusSource());
args.put(UserInfoTable.FIELD_FRIENDS_COUNT, user.getFriendsCount());
args.put(UserInfoTable.FIELD_FAVORITES_COUNT, user.getFavouritesCount());
args.put(UserInfoTable.FIELD_STATUSES_COUNT, user.getStatusesCount());
args.put(UserInfoTable.FIELD_FOLLOWING, user.isFollowing());
// long rowId = mDb.insert(UserInfoTable.TABLE_NAME, null, args);
// 省去判断existUser,如果存在数据则replace
// long rowId=mDb.insertWithOnConflict(UserInfoTable.TABLE_NAME, null,
// args, SQLiteDatabase.CONFLICT_REPLACE);
long rowId = insertWithOnConflict(mDb, UserInfoTable.TABLE_NAME, null,
args, CONFLICT_REPLACE);
if (-1 == rowId) {
Log.e(TAG, "Cann't createWeiboUserInfo : " + user.getId());
} else {
Log.v(TAG, "create createWeiboUserInfo : " + user.getId());
}
return rowId;
}
/**
* 查看数据是否已保存用户数据
*
* @param userId
* @return
*/
public boolean existsUser(String userId) {
SQLiteDatabase Db = mOpenHelper.getReadableDatabase();
boolean result = false;
Cursor cursor = Db.query(UserInfoTable.TABLE_NAME,
new String[] { UserInfoTable._ID }, UserInfoTable._ID + "='"
+ userId + "'", null, null, null, null);
Log.v("testesetesteste", String.valueOf(cursor.getCount()));
if (cursor != null && cursor.getCount() > 0) {
result = true;
}
cursor.close();
return result;
}
/**
* 根据userid提取信息
*
* @param userId
* @return
*/
public Cursor getUserInfoById(String userId) {
SQLiteDatabase Db = mOpenHelper.getReadableDatabase();
Cursor cursor = Db.query(UserInfoTable.TABLE_NAME,
UserInfoTable.TABLE_COLUMNS, UserInfoTable._ID + " = '"
+ userId + "'", null, null, null, null);
return cursor;
}
/**
* 更新用户
*
* @param uid
* @param args
* @return
*/
public boolean updateUser(String uid, ContentValues args) {
SQLiteDatabase Db = mOpenHelper.getWritableDatabase();
return Db.update(UserInfoTable.TABLE_NAME, args, UserInfoTable._ID
+ "='" + uid + "'", null) > 0;
}
/**
* 更新用户信息
*/
public boolean updateUser(com.ch_linghu.fanfoudroid.data.User user) {
SQLiteDatabase Db = mOpenHelper.getWritableDatabase();
ContentValues args = new ContentValues();
args.put(UserInfoTable._ID, user.id);
args.put(UserInfoTable.FIELD_USER_NAME, user.name);
args.put(UserInfoTable.FIELD_USER_SCREEN_NAME, user.screenName);
args.put(UserInfoTable.FIELD_LOCALTION, user.location);
args.put(UserInfoTable.FIELD_DESCRIPTION, user.description);
args.put(UserInfoTable.FIELD_PROFILE_IMAGE_URL, user.profileImageUrl);
args.put(UserInfoTable.FIELD_URL, user.url);
args.put(UserInfoTable.FIELD_PROTECTED, user.isProtected);
args.put(UserInfoTable.FIELD_FOLLOWERS_COUNT, user.followersCount);
args.put(UserInfoTable.FIELD_LAST_STATUS, user.lastStatus);
args.put(UserInfoTable.FIELD_FRIENDS_COUNT, user.friendsCount);
args.put(UserInfoTable.FIELD_FAVORITES_COUNT, user.favoritesCount);
args.put(UserInfoTable.FIELD_STATUSES_COUNT, user.statusesCount);
args.put(UserInfoTable.FIELD_FOLLOWING, user.isFollowing);
return Db.update(UserInfoTable.TABLE_NAME, args, UserInfoTable._ID
+ "='" + user.id + "'", null) > 0;
}
/**
* 减少转换的开销
*
* @param user
* @return
*/
public boolean updateWeiboUser(com.ch_linghu.fanfoudroid.fanfou.User user) {
SQLiteDatabase Db = mOpenHelper.getWritableDatabase();
ContentValues args = new ContentValues();
args.put(UserInfoTable._ID, user.getName());
args.put(UserInfoTable.FIELD_USER_NAME, user.getName());
args.put(UserInfoTable.FIELD_USER_SCREEN_NAME, user.getScreenName());
String location = user.getLocation();
args.put(UserInfoTable.FIELD_LOCALTION, location);
String description = user.getDescription();
args.put(UserInfoTable.FIELD_DESCRIPTION, description);
args.put(UserInfoTable.FIELD_PROFILE_IMAGE_URL, user
.getProfileImageURL().toString());
if (user.getURL() != null) {
args.put(UserInfoTable.FIELD_URL, user.getURL().toString());
}
args.put(UserInfoTable.FIELD_PROTECTED, user.isProtected());
args.put(UserInfoTable.FIELD_FOLLOWERS_COUNT, user.getFollowersCount());
args.put(UserInfoTable.FIELD_LAST_STATUS, user.getStatusSource());
args.put(UserInfoTable.FIELD_FRIENDS_COUNT, user.getFriendsCount());
args.put(UserInfoTable.FIELD_FAVORITES_COUNT, user.getFavouritesCount());
args.put(UserInfoTable.FIELD_STATUSES_COUNT, user.getStatusesCount());
args.put(UserInfoTable.FIELD_FOLLOWING, user.isFollowing());
return Db.update(UserInfoTable.TABLE_NAME, args, UserInfoTable._ID
+ "='" + user.getId() + "'", null) > 0;
}
/**
* 同步用户,更新已存在的用户,插入未存在的用户
*/
public void syncUsers(List<com.ch_linghu.fanfoudroid.data.User> users) {
SQLiteDatabase mDb = mOpenHelper.getWritableDatabase();
try {
mDb.beginTransaction();
for (com.ch_linghu.fanfoudroid.data.User u : users) {
// if(existsUser(u.id)){
// updateUser(u);
// }else{
// createUserInfo(u);
// }
createUserInfo(u);
}
mDb.setTransactionSuccessful();
} finally {
mDb.endTransaction();
}
}
public void syncWeiboUsers(List<com.ch_linghu.fanfoudroid.fanfou.User> users) {
SQLiteDatabase mDb = mOpenHelper.getWritableDatabase();
try {
mDb.beginTransaction();
for (com.ch_linghu.fanfoudroid.fanfou.User u : users) {
// if (existsUser(u.getId())) {
// updateWeiboUser(u);
// } else {
// createWeiboUserInfo(u);
// }
createWeiboUserInfo(u);
}
mDb.setTransactionSuccessful();
} finally {
mDb.endTransaction();
}
}
}
| 061304011116lyj-and | src/com/ch_linghu/fanfoudroid/db/TwitterDatabase.java | Java | asf20 | 34,712 |
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;
import com.ch_linghu.fanfoudroid.R;
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;
}
}
| 061304011116lyj-and | src/com/ch_linghu/fanfoudroid/SearchActivity.java | Java | asf20 | 11,514 |
/*
* 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;
import com.ch_linghu.fanfoudroid.R;
//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();
}
};
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;
}
};
} | 061304011116lyj-and | src/com/ch_linghu/fanfoudroid/WriteDmActivity.java | Java | asf20 | 12,236 |
package com.ch_linghu.fanfoudroid;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.Button;
import android.widget.CursorAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.ch_linghu.fanfoudroid.app.LazyImageLoader.ImageLoaderCallback;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.data.Dm;
import com.ch_linghu.fanfoudroid.db.MessageTable;
import com.ch_linghu.fanfoudroid.db.TwitterDatabase;
import com.ch_linghu.fanfoudroid.fanfou.DirectMessage;
import com.ch_linghu.fanfoudroid.fanfou.Paging;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.task.GenericTask;
import com.ch_linghu.fanfoudroid.task.TaskAdapter;
import com.ch_linghu.fanfoudroid.task.TaskListener;
import com.ch_linghu.fanfoudroid.task.TaskParams;
import com.ch_linghu.fanfoudroid.task.TaskResult;
import com.ch_linghu.fanfoudroid.ui.base.BaseActivity;
import com.ch_linghu.fanfoudroid.ui.base.Refreshable;
import com.ch_linghu.fanfoudroid.ui.module.Feedback;
import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory;
import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory.FeedbackType;
import com.ch_linghu.fanfoudroid.ui.module.NavBar;
import com.ch_linghu.fanfoudroid.ui.module.SimpleFeedback;
import com.ch_linghu.fanfoudroid.util.DateTimeHelper;
import com.ch_linghu.fanfoudroid.util.TextHelper;
import com.ch_linghu.fanfoudroid.R;
public class DmActivity extends BaseActivity implements Refreshable {
private static final String TAG = "DmActivity";
// Views.
private ListView mTweetList;
private Adapter mAdapter;
private Adapter mInboxAdapter;
private Adapter mSendboxAdapter;
Button inbox;
Button sendbox;
Button newMsg;
private int mDMType;
private static final int DM_TYPE_ALL = 0;
private static final int DM_TYPE_INBOX = 1;
private static final int DM_TYPE_SENDBOX = 2;
private TextView mProgressText;
private NavBar mNavbar;
private Feedback mFeedback;
// Tasks.
private GenericTask mRetrieveTask;
private GenericTask mDeleteTask;
private TaskListener mDeleteTaskListener = new TaskAdapter() {
@Override
public void onPreExecute(GenericTask task) {
updateProgress(getString(R.string.page_status_deleting));
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.AUTH_ERROR) {
logout();
} else if (result == TaskResult.OK) {
mAdapter.refresh();
} else {
// Do nothing.
}
updateProgress("");
}
@Override
public String getName() {
return "DmDeleteTask";
}
};
private TaskListener mRetrieveTaskListener = new TaskAdapter() {
@Override
public void onPreExecute(GenericTask task) {
updateProgress(getString(R.string.page_status_refreshing));
}
@Override
public void onProgressUpdate(GenericTask task, Object params) {
draw();
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.AUTH_ERROR) {
logout();
} else if (result == TaskResult.OK) {
SharedPreferences.Editor editor = mPreferences.edit();
editor.putLong(Preferences.LAST_DM_REFRESH_KEY,
DateTimeHelper.getNowTime());
editor.commit();
draw();
goTop();
} else {
// Do nothing.
}
updateProgress("");
}
@Override
public String getName() {
return "DmRetrieve";
}
};
// Refresh data at startup if last refresh was this long ago or greater.
private static final long REFRESH_THRESHOLD = 5 * 60 * 1000;
private static final String EXTRA_USER = "user";
private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.DMS";
public static Intent createIntent() {
return createIntent("");
}
public static Intent createIntent(String user) {
Intent intent = new Intent(LAUNCH_ACTION);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
if (!TextUtils.isEmpty(user)) {
intent.putExtra(EXTRA_USER, user);
}
return intent;
}
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
if (super._onCreate(savedInstanceState)) {
setContentView(R.layout.dm);
mNavbar = new NavBar(NavBar.HEADER_STYLE_HOME, this);
mNavbar.setHeaderTitle("我的私信");
mFeedback = FeedbackFactory.create(this, FeedbackType.PROGRESS);
bindFooterButtonEvent();
mTweetList = (ListView) findViewById(R.id.tweet_list);
mProgressText = (TextView) findViewById(R.id.progress_text);
TwitterDatabase db = getDb();
// Mark all as read.
db.markAllDmsRead();
setupAdapter(); // Make sure call bindFooterButtonEvent first
boolean shouldRetrieve = false;
long lastRefreshTime = mPreferences.getLong(
Preferences.LAST_DM_REFRESH_KEY, 0);
long nowTime = DateTimeHelper.getNowTime();
long diff = nowTime - lastRefreshTime;
Log.d(TAG, "Last refresh was " + diff + " ms ago.");
if (diff > REFRESH_THRESHOLD) {
shouldRetrieve = true;
} else if (isTrue(savedInstanceState, SIS_RUNNING_KEY)) {
// Check to see if it was running a send or retrieve task.
// It makes no sense to resend the send request (don't want
// dupes)
// so we instead retrieve (refresh) to see if the message has
// posted.
Log.d(TAG,
"Was last running a retrieve or send task. Let's refresh.");
shouldRetrieve = true;
}
if (shouldRetrieve) {
doRetrieve();
}
// Want to be able to focus on the items with the trackball.
// That way, we can navigate up and down by changing item focus.
mTweetList.setItemsCanFocus(true);
return true;
} else {
return false;
}
}
@Override
protected void onResume() {
super.onResume();
checkIsLogedIn();
}
private static final String SIS_RUNNING_KEY = "running";
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mRetrieveTask != null
&& mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) {
outState.putBoolean(SIS_RUNNING_KEY, true);
}
}
@Override
protected void onDestroy() {
Log.d(TAG, "onDestroy.");
if (mRetrieveTask != null
&& mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) {
mRetrieveTask.cancel(true);
}
if (mDeleteTask != null
&& mDeleteTask.getStatus() == GenericTask.Status.RUNNING) {
mDeleteTask.cancel(true);
}
super.onDestroy();
}
// UI helpers.
private void bindFooterButtonEvent() {
inbox = (Button) findViewById(R.id.inbox);
sendbox = (Button) findViewById(R.id.sendbox);
newMsg = (Button) findViewById(R.id.new_message);
inbox.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mDMType != DM_TYPE_INBOX) {
mDMType = DM_TYPE_INBOX;
inbox.setEnabled(false);
sendbox.setEnabled(true);
mTweetList.setAdapter(mInboxAdapter);
mInboxAdapter.refresh();
}
}
});
sendbox.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (mDMType != DM_TYPE_SENDBOX) {
mDMType = DM_TYPE_SENDBOX;
inbox.setEnabled(true);
sendbox.setEnabled(false);
mTweetList.setAdapter(mSendboxAdapter);
mSendboxAdapter.refresh();
}
}
});
newMsg.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setClass(DmActivity.this, WriteDmActivity.class);
intent.putExtra("reply_to_id", 0); // TODO: 传入实际的reply_to_id
startActivity(intent);
}
});
}
private void setupAdapter() {
Cursor cursor = getDb().fetchAllDms(-1);
startManagingCursor(cursor);
mAdapter = new Adapter(this, cursor);
Cursor inboxCursor = getDb().fetchInboxDms();
startManagingCursor(inboxCursor);
mInboxAdapter = new Adapter(this, inboxCursor);
Cursor sendboxCursor = getDb().fetchSendboxDms();
startManagingCursor(sendboxCursor);
mSendboxAdapter = new Adapter(this, sendboxCursor);
mTweetList.setAdapter(mInboxAdapter);
registerForContextMenu(mTweetList);
inbox.setEnabled(false);
}
private class DmRetrieveTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
List<DirectMessage> dmList;
ArrayList<Dm> dms = new ArrayList<Dm>();
TwitterDatabase db = getDb();
// ImageManager imageManager = getImageManager();
String maxId = db.fetchMaxDmId(false);
HashSet<String> imageUrls = new HashSet<String>();
try {
if (maxId != null) {
Paging paging = new Paging(maxId);
dmList = getApi().getDirectMessages(paging);
} else {
dmList = getApi().getDirectMessages();
}
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
return TaskResult.IO_ERROR;
}
publishProgress(SimpleFeedback.calProgressBySize(40, 20, dmList));
for (DirectMessage directMessage : dmList) {
if (isCancelled()) {
return TaskResult.CANCELLED;
}
Dm dm;
dm = Dm.create(directMessage, false);
dms.add(dm);
imageUrls.add(dm.profileImageUrl);
if (isCancelled()) {
return TaskResult.CANCELLED;
}
}
maxId = db.fetchMaxDmId(true);
try {
if (maxId != null) {
Paging paging = new Paging(maxId);
dmList = getApi().getSentDirectMessages(paging);
} else {
dmList = getApi().getSentDirectMessages();
}
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
return TaskResult.IO_ERROR;
}
for (DirectMessage directMessage : dmList) {
if (isCancelled()) {
return TaskResult.CANCELLED;
}
Dm dm;
dm = Dm.create(directMessage, true);
dms.add(dm);
imageUrls.add(dm.profileImageUrl);
if (isCancelled()) {
return TaskResult.CANCELLED;
}
}
db.addDms(dms, false);
// if (isCancelled()) {
// return TaskResult.CANCELLED;
// }
//
// publishProgress(null);
//
// for (String imageUrl : imageUrls) {
// if (!Utils.isEmpty(imageUrl)) {
// // Fetch image to cache.
// try {
// imageManager.put(imageUrl);
// } catch (IOException e) {
// Log.e(TAG, e.getMessage(), e);
// }
// }
//
// if (isCancelled()) {
// return TaskResult.CANCELLED;
// }
// }
return TaskResult.OK;
}
}
private static class Adapter extends CursorAdapter {
public Adapter(Context context, Cursor cursor) {
super(context, cursor);
mInflater = LayoutInflater.from(context);
// TODO: 可使用:
// DM dm = MessageTable.parseCursor(cursor);
mUserTextColumn = cursor
.getColumnIndexOrThrow(MessageTable.FIELD_USER_SCREEN_NAME);
mTextColumn = cursor.getColumnIndexOrThrow(MessageTable.FIELD_TEXT);
mProfileImageUrlColumn = cursor
.getColumnIndexOrThrow(MessageTable.FIELD_PROFILE_IMAGE_URL);
mCreatedAtColumn = cursor
.getColumnIndexOrThrow(MessageTable.FIELD_CREATED_AT);
mIsSentColumn = cursor
.getColumnIndexOrThrow(MessageTable.FIELD_IS_SENT);
}
private LayoutInflater mInflater;
private int mUserTextColumn;
private int mTextColumn;
private int mProfileImageUrlColumn;
private int mIsSentColumn;
private int mCreatedAtColumn;
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View view = mInflater.inflate(R.layout.direct_message, parent,
false);
ViewHolder holder = new ViewHolder();
holder.userText = (TextView) view
.findViewById(R.id.tweet_user_text);
holder.tweetText = (TextView) view.findViewById(R.id.tweet_text);
holder.profileImage = (ImageView) view
.findViewById(R.id.profile_image);
holder.metaText = (TextView) view
.findViewById(R.id.tweet_meta_text);
view.setTag(holder);
return view;
}
class ViewHolder {
public TextView userText;
public TextView tweetText;
public ImageView profileImage;
public TextView metaText;
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
ViewHolder holder = (ViewHolder) view.getTag();
int isSent = cursor.getInt(mIsSentColumn);
String user = cursor.getString(mUserTextColumn);
if (0 == isSent) {
holder.userText.setText(context
.getString(R.string.direct_message_label_from_prefix)
+ user);
} else {
holder.userText.setText(context
.getString(R.string.direct_message_label_to_prefix)
+ user);
}
TextHelper.setTweetText(holder.tweetText,
cursor.getString(mTextColumn));
String profileImageUrl = cursor.getString(mProfileImageUrlColumn);
if (!TextUtils.isEmpty(profileImageUrl)) {
holder.profileImage
.setImageBitmap(TwitterApplication.mImageLoader.get(
profileImageUrl, new ImageLoaderCallback() {
@Override
public void refresh(String url,
Bitmap bitmap) {
Adapter.this.refresh();
}
}));
}
try {
holder.metaText.setText(DateTimeHelper
.getRelativeDate(TwitterDatabase.DB_DATE_FORMATTER
.parse(cursor.getString(mCreatedAtColumn))));
} catch (ParseException e) {
Log.w(TAG, "Invalid created at data.");
}
}
public void refresh() {
getCursor().requery();
}
}
// Menu.
@Override
public boolean onCreateOptionsMenu(Menu menu) {
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// FIXME: 将刷新功能绑定到顶部的刷新按钮上,主菜单中的刷新选项已删除
// case OPTIONS_MENU_ID_REFRESH:
// doRetrieve();
// return true;
case OPTIONS_MENU_ID_TWEETS:
launchActivity(TwitterActivity.createIntent(this));
return true;
case OPTIONS_MENU_ID_REPLIES:
launchActivity(MentionActivity.createIntent(this));
return true;
}
return super.onOptionsItemSelected(item);
}
private static final int CONTEXT_REPLY_ID = 0;
private static final int CONTEXT_DELETE_ID = 1;
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.add(0, CONTEXT_REPLY_ID, 0, R.string.cmenu_reply);
menu.add(0, CONTEXT_DELETE_ID, 0, R.string.cmenu_delete);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item
.getMenuInfo();
Cursor cursor = (Cursor) mAdapter.getItem(info.position);
if (cursor == null) {
Log.w(TAG, "Selected item not available.");
return super.onContextItemSelected(item);
}
switch (item.getItemId()) {
case CONTEXT_REPLY_ID:
String user_id = cursor.getString(cursor
.getColumnIndexOrThrow(MessageTable.FIELD_USER_ID));
Intent intent = WriteDmActivity.createIntent(user_id);
startActivity(intent);
return true;
case CONTEXT_DELETE_ID:
int idIndex = cursor.getColumnIndexOrThrow(MessageTable._ID);
String id = cursor.getString(idIndex);
doDestroy(id);
return true;
default:
return super.onContextItemSelected(item);
}
}
private void doDestroy(String id) {
Log.d(TAG, "Attempting delete.");
if (mDeleteTask != null
&& mDeleteTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mDeleteTask = new DmDeleteTask();
mDeleteTask.setListener(mDeleteTaskListener);
TaskParams params = new TaskParams();
params.put("id", id);
mDeleteTask.execute(params);
}
}
private class DmDeleteTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
TaskParams param = params[0];
try {
String id = param.getString("id");
DirectMessage directMessage = getApi().destroyDirectMessage(id);
Dm.create(directMessage, false);
getDb().deleteDm(id);
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
return TaskResult.IO_ERROR;
}
if (isCancelled()) {
return TaskResult.CANCELLED;
}
return TaskResult.OK;
}
}
public void doRetrieve() {
Log.d(TAG, "Attempting retrieve.");
if (mRetrieveTask != null
&& mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mRetrieveTask = new DmRetrieveTask();
mRetrieveTask.setFeedback(mFeedback);
mRetrieveTask.setListener(mRetrieveTaskListener);
mRetrieveTask.execute();
}
}
public void goTop() {
mTweetList.setSelection(0);
}
public void draw() {
mAdapter.refresh();
mInboxAdapter.refresh();
mSendboxAdapter.refresh();
}
private void updateProgress(String msg) {
mProgressText.setText(msg);
}
}
| 061304011116lyj-and | src/com/ch_linghu/fanfoudroid/DmActivity.java | Java | asf20 | 17,743 |
package com.ch_linghu.fanfoudroid.util;
import java.io.InputStream;
import java.io.OutputStream;
public class StreamUtils {
public static void CopyStream(InputStream is, OutputStream os) {
final int buffer_size = 1024;
try {
byte[] bytes = new byte[buffer_size];
for (;;) {
int count = is.read(bytes, 0, buffer_size);
if (count == -1)
break;
os.write(bytes, 0, count);
}
} catch (Exception ex) {
}
}
} | 061304011116lyj-and | src/com/ch_linghu/fanfoudroid/util/StreamUtils.java | Java | asf20 | 458 |
package com.ch_linghu.fanfoudroid.util;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.Arrays;
import java.util.HashMap;
import android.util.Log;
import com.ch_linghu.fanfoudroid.TwitterApplication;
/**
* Debug Timer
*
* Usage: -------------------------------- DebugTimer.start();
* DebugTimer.mark("my_mark1"); // optional DebugTimer.stop();
*
* System.out.println(DebugTimer.__toString()); // get report
* --------------------------------
*
* @author LDS
*/
public class DebugTimer {
public static final int START = 0;
public static final int END = 1;
private static HashMap<String, Long> mTime = new HashMap<String, Long>();
private static long mStartTime = 0;
private static long mLastTime = 0;
/**
* Start a timer
*/
public static void start() {
reset();
mStartTime = touch();
}
/**
* Mark current time
*
* @param tag
* mark tag
* @return
*/
public static long mark(String tag) {
long time = System.currentTimeMillis() - mStartTime;
mTime.put(tag, time);
return time;
}
/**
* Mark current time
*
* @param tag
* mark tag
* @return
*/
public static long between(String tag, int startOrEnd) {
if (TwitterApplication.DEBUG) {
Log.v("DEBUG", tag + " " + startOrEnd);
}
switch (startOrEnd) {
case START:
return mark(tag);
case END:
long time = System.currentTimeMillis() - mStartTime
- get(tag, mStartTime);
mTime.put(tag, time);
// touch();
return time;
default:
return -1;
}
}
public static long betweenStart(String tag) {
return between(tag, START);
}
public static long betweenEnd(String tag) {
return between(tag, END);
}
/**
* Stop timer
*
* @return result
*/
public static String stop() {
mTime.put("_TOTLE", touch() - mStartTime);
return __toString();
}
public static String stop(String tag) {
mark(tag);
return stop();
}
/**
* Get a mark time
*
* @param tag
* mark tag
* @return time(milliseconds) or NULL
*/
public static long get(String tag) {
return get(tag, 0);
}
public static long get(String tag, long defaultValue) {
if (mTime.containsKey(tag)) {
return mTime.get(tag);
}
return defaultValue;
}
/**
* Reset timer
*/
public static void reset() {
mTime = new HashMap<String, Long>();
mStartTime = 0;
mLastTime = 0;
}
/**
* static toString()
*
* @return
*/
public static String __toString() {
return "Debuger [time =" + mTime.toString() + "]";
}
private static long touch() {
return mLastTime = System.currentTimeMillis();
}
public static DebugProfile[] getProfile() {
DebugProfile[] profile = new DebugProfile[mTime.size()];
long totel = mTime.get("_TOTLE");
int i = 0;
for (String key : mTime.keySet()) {
long time = mTime.get(key);
profile[i] = new DebugProfile(key, time, time / (totel * 1.0));
i++;
}
try {
Arrays.sort(profile);
} catch (NullPointerException e) {
// in case item is null, do nothing
}
return profile;
}
public static String getProfileAsString() {
StringBuilder sb = new StringBuilder();
for (DebugProfile p : getProfile()) {
sb.append("TAG: ");
sb.append(p.tag);
sb.append("\t INC: ");
sb.append(p.inc);
sb.append("\t INCP: ");
sb.append(p.incPercent);
sb.append("\n");
}
return sb.toString();
}
@Override
public String toString() {
return __toString();
}
}
class DebugProfile implements Comparable<DebugProfile> {
private static NumberFormat percent = NumberFormat.getPercentInstance();
public String tag;
public long inc;
public String incPercent;
public DebugProfile(String tag, long inc, double incPercent) {
this.tag = tag;
this.inc = inc;
percent = new DecimalFormat("0.00#%");
this.incPercent = percent.format(incPercent);
}
@Override
public int compareTo(DebugProfile o) {
// TODO Auto-generated method stub
return (int) (o.inc - this.inc);
}
}
| 061304011116lyj-and | src/com/ch_linghu/fanfoudroid/util/DebugTimer.java | Java | asf20 | 3,972 |
package com.ch_linghu.fanfoudroid.util;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import android.util.Log;
import com.ch_linghu.fanfoudroid.R;
import com.ch_linghu.fanfoudroid.TwitterApplication;
import com.ch_linghu.fanfoudroid.db.TwitterDatabase;
public class DateTimeHelper {
private static final String TAG = "DateTimeHelper";
// Wed Dec 15 02:53:36 +0000 2010
public static final DateFormat TWITTER_DATE_FORMATTER = new SimpleDateFormat(
"E MMM d HH:mm:ss Z yyyy", Locale.US);
public static final DateFormat TWITTER_SEARCH_API_DATE_FORMATTER = new SimpleDateFormat(
"E, d MMM yyyy HH:mm:ss Z", Locale.US); // TODO: Z -> z ?
public static final Date parseDateTime(String dateString) {
try {
Log.v(TAG, String.format("in parseDateTime, dateString=%s",
dateString));
return TWITTER_DATE_FORMATTER.parse(dateString);
} catch (ParseException e) {
Log.w(TAG, "Could not parse Twitter date string: " + dateString);
return null;
}
}
// Handle "yyyy-MM-dd'T'HH:mm:ss.SSS" from sqlite
public static final Date parseDateTimeFromSqlite(String dateString) {
try {
Log.v(TAG, String.format("in parseDateTime, dateString=%s",
dateString));
return TwitterDatabase.DB_DATE_FORMATTER.parse(dateString);
} catch (ParseException e) {
Log.w(TAG, "Could not parse Twitter date string: " + dateString);
return null;
}
}
public static final Date parseSearchApiDateTime(String dateString) {
try {
return TWITTER_SEARCH_API_DATE_FORMATTER.parse(dateString);
} catch (ParseException e) {
Log.w(TAG, "Could not parse Twitter search date string: "
+ dateString);
return null;
}
}
public static final DateFormat AGO_FULL_DATE_FORMATTER = new SimpleDateFormat(
"yyyy-MM-dd HH:mm");
public static String getRelativeDate(Date date) {
Date now = new Date();
String prefix = TwitterApplication.mContext
.getString(R.string.tweet_created_at_beautify_prefix);
String sec = TwitterApplication.mContext
.getString(R.string.tweet_created_at_beautify_sec);
String min = TwitterApplication.mContext
.getString(R.string.tweet_created_at_beautify_min);
String hour = TwitterApplication.mContext
.getString(R.string.tweet_created_at_beautify_hour);
String day = TwitterApplication.mContext
.getString(R.string.tweet_created_at_beautify_day);
String suffix = TwitterApplication.mContext
.getString(R.string.tweet_created_at_beautify_suffix);
// Seconds.
long diff = (now.getTime() - date.getTime()) / 1000;
if (diff < 0) {
diff = 0;
}
if (diff < 60) {
return diff + sec + suffix;
}
// Minutes.
diff /= 60;
if (diff < 60) {
return prefix + diff + min + suffix;
}
// Hours.
diff /= 60;
if (diff < 24) {
return prefix + diff + hour + suffix;
}
return AGO_FULL_DATE_FORMATTER.format(date);
}
public static long getNowTime() {
return Calendar.getInstance().getTime().getTime();
}
}
| 061304011116lyj-and | src/com/ch_linghu/fanfoudroid/util/DateTimeHelper.java | Java | asf20 | 3,060 |
package com.ch_linghu.fanfoudroid.util;
import java.io.File;
import java.io.IOException;
import android.os.Environment;
/**
* 对SD卡文件的管理
*
* @author ch.linghu
*
*/
public class FileHelper {
private static final String TAG = "FileHelper";
private static final String BASE_PATH = "fanfoudroid";
public static File getBasePath() throws IOException {
File basePath = new File(Environment.getExternalStorageDirectory(),
BASE_PATH);
if (!basePath.exists()) {
if (!basePath.mkdirs()) {
throw new IOException(String.format("%s cannot be created!",
basePath.toString()));
}
}
if (!basePath.isDirectory()) {
throw new IOException(String.format("%s is not a directory!",
basePath.toString()));
}
return basePath;
}
}
| 061304011116lyj-and | src/com/ch_linghu/fanfoudroid/util/FileHelper.java | Java | asf20 | 778 |
package com.ch_linghu.fanfoudroid.util;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.text.Html;
import android.text.util.Linkify;
import android.util.Log;
import android.widget.TextView;
import android.widget.TextView.BufferType;
public class TextHelper {
private static final String TAG = "TextHelper";
public static String stringifyStream(InputStream is) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
return sb.toString();
}
private static HashMap<String, String> _userLinkMapping = new HashMap<String, String>();
private static final Pattern NAME_MATCHER = Pattern.compile("@.+?\\s");
private static final Linkify.MatchFilter NAME_MATCHER_MATCH_FILTER = new Linkify.MatchFilter() {
@Override
public final boolean acceptMatch(final CharSequence s, final int start,
final int end) {
String name = s.subSequence(start + 1, end).toString().trim();
boolean result = _userLinkMapping.containsKey(name);
return result;
}
};
private static final Linkify.TransformFilter NAME_MATCHER_TRANSFORM_FILTER = new Linkify.TransformFilter() {
@Override
public String transformUrl(Matcher match, String url) {
// TODO Auto-generated method stub
String name = url.subSequence(1, url.length()).toString().trim();
return _userLinkMapping.get(name);
}
};
private static final String TWITTA_USER_URL = "twitta://users/";
public static void linkifyUsers(TextView view) {
Linkify.addLinks(view, NAME_MATCHER, TWITTA_USER_URL,
NAME_MATCHER_MATCH_FILTER, NAME_MATCHER_TRANSFORM_FILTER);
}
private static final Pattern TAG_MATCHER = Pattern.compile("#\\w+#");
private static final Linkify.TransformFilter TAG_MATCHER_TRANSFORM_FILTER = new Linkify.TransformFilter() {
@Override
public final String transformUrl(Matcher match, String url) {
String result = url.substring(1, url.length() - 1);
return result;
}
};
private static final String TWITTA_SEARCH_URL = "twitta://search/";
public static void linkifyTags(TextView view) {
Linkify.addLinks(view, TAG_MATCHER, TWITTA_SEARCH_URL, null,
TAG_MATCHER_TRANSFORM_FILTER);
}
private static Pattern USER_LINK = Pattern
.compile("@<a href=\"http:\\/\\/fanfou\\.com\\/(.*?)\" class=\"former\">(.*?)<\\/a>");
private static String preprocessText(String text) {
// 处理HTML格式返回的用户链接
Matcher m = USER_LINK.matcher(text);
while (m.find()) {
_userLinkMapping.put(m.group(2), m.group(1));
Log.d(TAG,
String.format("Found mapping! %s=%s", m.group(2),
m.group(1)));
}
// 将User Link的连接去掉
StringBuffer sb = new StringBuffer();
m = USER_LINK.matcher(text);
while (m.find()) {
m.appendReplacement(sb, "@$2");
}
m.appendTail(sb);
return sb.toString();
}
public static String getSimpleTweetText(String text) {
return Html.fromHtml(text).toString();
}
public static void setSimpleTweetText(TextView textView, String text) {
String processedText = getSimpleTweetText(text);
textView.setText(processedText);
}
public static void setTweetText(TextView textView, String text) {
String processedText = preprocessText(text);
textView.setText(Html.fromHtml(processedText), BufferType.SPANNABLE);
Linkify.addLinks(textView, Linkify.WEB_URLS | Linkify.EMAIL_ADDRESSES);
linkifyUsers(textView);
linkifyTags(textView);
_userLinkMapping.clear();
}
/**
* 从消息中获取全部提到的人,将它们按先后顺序放入一个列表
*
* @param msg
* 消息文本
* @return 消息中@的人的列表,按顺序存放
*/
public static List<String> getMentions(String msg) {
ArrayList<String> mentionList = new ArrayList<String>();
final Pattern p = Pattern.compile("@(.*?)\\s");
final int MAX_NAME_LENGTH = 12; // 简化判断,无论中英文最长12个字
Matcher m = p.matcher(msg);
while (m.find()) {
String mention = m.group(1);
// 过长的名字就忽略(不是合法名字) +1是为了补上“@”所占的长度
if (mention.length() <= MAX_NAME_LENGTH + 1) {
// 避免重复名字
if (!mentionList.contains(mention)) {
mentionList.add(m.group(1));
}
}
}
return mentionList;
}
}
| 061304011116lyj-and | src/com/ch_linghu/fanfoudroid/util/TextHelper.java | Java | asf20 | 4,585 |
/*
* Copyright (C) 2009 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ch_linghu.fanfoudroid;
import java.io.IOException;
import java.io.InputStream;
import java.text.MessageFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.text.ClipboardManager;
import android.text.TextUtils;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import com.ch_linghu.fanfoudroid.app.ImageCache;
import com.ch_linghu.fanfoudroid.app.LazyImageLoader.ImageLoaderCallback;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.data.Tweet;
import com.ch_linghu.fanfoudroid.http.HttpClient;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.http.Response;
import com.ch_linghu.fanfoudroid.task.GenericTask;
import com.ch_linghu.fanfoudroid.task.TaskAdapter;
import com.ch_linghu.fanfoudroid.task.TaskListener;
import com.ch_linghu.fanfoudroid.task.TaskParams;
import com.ch_linghu.fanfoudroid.task.TaskResult;
import com.ch_linghu.fanfoudroid.task.TweetCommonTask;
import com.ch_linghu.fanfoudroid.ui.base.BaseActivity;
import com.ch_linghu.fanfoudroid.ui.module.Feedback;
import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory;
import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory.FeedbackType;
import com.ch_linghu.fanfoudroid.ui.module.NavBar;
import com.ch_linghu.fanfoudroid.util.DateTimeHelper;
import com.ch_linghu.fanfoudroid.util.TextHelper;
import com.ch_linghu.fanfoudroid.R;
public class StatusActivity extends BaseActivity {
private static final String TAG = "StatusActivity";
private static final String SIS_RUNNING_KEY = "running";
private static final String PREFS_NAME = "com.ch_linghu.fanfoudroid";
private static final String EXTRA_TWEET = "tweet";
private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.STATUS";
static final private int CONTEXT_REFRESH_ID = 0x0001;
static final private int CONTEXT_CLIPBOARD_ID = 0x0002;
static final private int CONTEXT_DELETE_ID = 0x0003;
// Task TODO: tasks
private GenericTask mReplyTask;
private GenericTask mStatusTask;
private GenericTask mPhotoTask; // TODO: 压缩图片,提供获取图片的过程中可取消获取
private GenericTask mFavTask;
private GenericTask mDeleteTask;
private NavBar mNavbar;
private Feedback mFeedback;
private TaskListener mReplyTaskListener = new TaskAdapter() {
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
showReplyStatus(replyTweet);
StatusActivity.this.mFeedback.success("");
}
@Override
public String getName() {
return "GetReply";
}
};
private TaskListener mStatusTaskListener = new TaskAdapter() {
@Override
public void onPreExecute(GenericTask task) {
clean();
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
StatusActivity.this.mFeedback.success("");
draw();
}
@Override
public String getName() {
return "GetStatus";
}
};
private TaskListener mPhotoTaskListener = new TaskAdapter() {
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.OK) {
status_photo.setImageBitmap(mPhotoBitmap);
} else {
status_photo.setVisibility(View.GONE);
}
StatusActivity.this.mFeedback.success("");
}
@Override
public String getName() {
// TODO Auto-generated method stub
return "GetPhoto";
}
};
private TaskListener mFavTaskListener = new TaskAdapter() {
@Override
public String getName() {
return "FavoriteTask";
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.AUTH_ERROR) {
logout();
} else if (result == TaskResult.OK) {
onFavSuccess();
} else if (result == TaskResult.IO_ERROR) {
onFavFailure();
}
}
};
private TaskListener mDeleteTaskListener = new TaskAdapter() {
@Override
public String getName() {
return "DeleteTask";
}
@Override
public void onPostExecute(GenericTask task, TaskResult result) {
if (result == TaskResult.AUTH_ERROR) {
logout();
} else if (result == TaskResult.OK) {
onDeleteSuccess();
} else if (result == TaskResult.IO_ERROR) {
onDeleteFailure();
}
}
};
// View
private TextView tweet_screen_name;
private TextView tweet_text;
private TextView tweet_user_info;
private ImageView profile_image;
private TextView tweet_source;
private TextView tweet_created_at;
private ImageButton btn_person_more;
private ImageView status_photo = null; // if exists
private ViewGroup reply_wrap;
private TextView reply_status_text = null; // if exists
private TextView reply_status_date = null; // if exists
private ImageButton tweet_fav;
private Tweet tweet = null;
private Tweet replyTweet = null; // if exists
private HttpClient mClient;
private Bitmap mPhotoBitmap = ImageCache.mDefaultBitmap; // if exists
public static Intent createIntent(Tweet tweet) {
Intent intent = new Intent(LAUNCH_ACTION);
intent.putExtra(EXTRA_TWEET, tweet);
return intent;
}
private static Pattern PHOTO_PAGE_LINK = Pattern
.compile("http://fanfou.com(/photo/[-a-zA-Z0-9+&@#%?=~_|!:,.;]*[-a-zA-Z0-9+&@#%=~_|])");
private static Pattern PHOTO_SRC_LINK = Pattern
.compile("src=\"(http:\\/\\/photo\\.fanfou\\.com\\/.*?)\"");
/**
* 获得消息中的照片页面链接
*
* @param text
* 消息文本
* @param size
* 照片尺寸
* @return 照片页面的链接,若不存在,则返回null
*/
public static String getPhotoPageLink(String text, String size) {
Matcher m = PHOTO_PAGE_LINK.matcher(text);
if (m.find()) {
String THUMBNAIL = TwitterApplication.mContext
.getString(R.string.pref_photo_preview_type_thumbnail);
String MIDDLE = TwitterApplication.mContext
.getString(R.string.pref_photo_preview_type_middle);
String ORIGINAL = TwitterApplication.mContext
.getString(R.string.pref_photo_preview_type_original);
if (size.equals(THUMBNAIL) || size.equals(MIDDLE)) {
return "http://m.fanfou.com" + m.group(1);
} else if (size.endsWith(ORIGINAL)) {
return m.group(0);
} else {
return null;
}
} else {
return null;
}
}
/**
* 获得照片页面中的照片链接
*
* @param pageHtml
* 照片页面文本
* @return 照片链接,若不存在,则返回null
*/
public static String getPhotoURL(String pageHtml) {
Matcher m = PHOTO_SRC_LINK.matcher(pageHtml);
if (m.find()) {
return m.group(1);
} else {
return null;
}
}
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
Log.d(TAG, "onCreate.");
if (super._onCreate(savedInstanceState)) {
mClient = getApi().getHttpClient();
// Intent & Action & Extras
Intent intent = getIntent();
String action = intent.getAction();
Bundle extras = intent.getExtras();
// Must has extras
if (null == extras) {
Log.e(TAG, this.getClass().getName() + " must has extras.");
finish();
return false;
}
setContentView(R.layout.status);
mNavbar = new NavBar(NavBar.HEADER_STYLE_BACK, this);
mFeedback = FeedbackFactory.create(this, FeedbackType.PROGRESS);
findView();
bindNavBarListener();
// Set view with intent data
this.tweet = extras.getParcelable(EXTRA_TWEET);
draw();
bindFooterBarListener();
bindReplyViewListener();
return true;
} else {
return false;
}
}
private void findView() {
tweet_screen_name = (TextView) findViewById(R.id.tweet_screen_name);
tweet_user_info = (TextView) findViewById(R.id.tweet_user_info);
tweet_text = (TextView) findViewById(R.id.tweet_text);
tweet_source = (TextView) findViewById(R.id.tweet_source);
profile_image = (ImageView) findViewById(R.id.profile_image);
tweet_created_at = (TextView) findViewById(R.id.tweet_created_at);
btn_person_more = (ImageButton) findViewById(R.id.person_more);
tweet_fav = (ImageButton) findViewById(R.id.tweet_fav);
reply_wrap = (ViewGroup) findViewById(R.id.reply_wrap);
reply_status_text = (TextView) findViewById(R.id.reply_status_text);
reply_status_date = (TextView) findViewById(R.id.reply_tweet_created_at);
status_photo = (ImageView) findViewById(R.id.status_photo);
}
private void bindNavBarListener() {
mNavbar.getRefreshButton().setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
doGetStatus(tweet.id);
}
});
}
private void bindFooterBarListener() {
// person_more
btn_person_more.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = ProfileActivity.createIntent(tweet.userId);
startActivity(intent);
}
});
// Footer bar
TextView footer_btn_share = (TextView) findViewById(R.id.footer_btn_share);
TextView footer_btn_reply = (TextView) findViewById(R.id.footer_btn_reply);
TextView footer_btn_retweet = (TextView) findViewById(R.id.footer_btn_retweet);
TextView footer_btn_fav = (TextView) findViewById(R.id.footer_btn_fav);
TextView footer_btn_more = (TextView) findViewById(R.id.footer_btn_more);
// 分享
footer_btn_share.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(
Intent.EXTRA_TEXT,
String.format("@%s %s", tweet.screenName,
TextHelper.getSimpleTweetText(tweet.text)));
startActivity(Intent.createChooser(intent,
getString(R.string.cmenu_share)));
}
});
// 回复
footer_btn_reply.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = WriteActivity.createNewReplyIntent(tweet.text,
tweet.screenName, tweet.id);
startActivity(intent);
}
});
// 转发
footer_btn_retweet.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = WriteActivity.createNewRepostIntent(
StatusActivity.this, tweet.text, tweet.screenName,
tweet.id);
startActivity(intent);
}
});
// 收藏/取消收藏
footer_btn_fav.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (tweet.favorited.equals("true")) {
doFavorite("del", tweet.id);
} else {
doFavorite("add", tweet.id);
}
}
});
// TODO: 更多操作
registerForContextMenu(footer_btn_more);
footer_btn_more.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
openContextMenu(v);
}
});
}
private void bindReplyViewListener() {
// 点击回复消息打开新的Status界面
OnClickListener listener = new View.OnClickListener() {
@Override
public void onClick(View v) {
if (!TextUtils.isEmpty(tweet.inReplyToStatusId)) {
if (replyTweet == null) {
Log.w(TAG, "Selected item not available.");
} else {
launchActivity(StatusActivity.createIntent(replyTweet));
}
}
}
};
reply_wrap.setOnClickListener(listener);
}
@Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause.");
}
@Override
protected void onRestart() {
super.onRestart();
Log.d(TAG, "onRestart.");
}
@Override
protected void onResume() {
super.onResume();
Log.d(TAG, "onResume.");
}
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart.");
}
@Override
protected void onStop() {
super.onStop();
Log.d(TAG, "onStop.");
}
@Override
protected void onDestroy() {
Log.d(TAG, "onDestroy.");
if (mReplyTask != null
&& mReplyTask.getStatus() == GenericTask.Status.RUNNING) {
mReplyTask.cancel(true);
}
if (mPhotoTask != null
&& mPhotoTask.getStatus() == GenericTask.Status.RUNNING) {
mPhotoTask.cancel(true);
}
if (mFavTask != null
&& mFavTask.getStatus() == GenericTask.Status.RUNNING) {
mFavTask.cancel(true);
}
super.onDestroy();
}
private ImageLoaderCallback callback = new ImageLoaderCallback() {
@Override
public void refresh(String url, Bitmap bitmap) {
profile_image.setImageBitmap(bitmap);
}
};
private void clean() {
tweet_screen_name.setText("");
tweet_text.setText("");
tweet_created_at.setText("");
tweet_source.setText("");
tweet_user_info.setText("");
tweet_fav.setEnabled(false);
profile_image.setImageBitmap(ImageCache.mDefaultBitmap);
status_photo.setVisibility(View.GONE);
ViewGroup reply_wrap = (ViewGroup) findViewById(R.id.reply_wrap);
reply_wrap.setVisibility(View.GONE);
}
private void draw() {
Log.d(TAG, "draw");
String PHOTO_PREVIEW_TYPE_NONE = getString(R.string.pref_photo_preview_type_none);
String PHOTO_PREVIEW_TYPE_THUMBNAIL = getString(R.string.pref_photo_preview_type_thumbnail);
String PHOTO_PREVIEW_TYPE_MIDDLE = getString(R.string.pref_photo_preview_type_middle);
String PHOTO_PREVIEW_TYPE_ORIGINAL = getString(R.string.pref_photo_preview_type_original);
SharedPreferences pref = getPreferences();
String photoPreviewSize = pref.getString(Preferences.PHOTO_PREVIEW,
PHOTO_PREVIEW_TYPE_ORIGINAL);
boolean forceShowAllImage = pref.getBoolean(
Preferences.FORCE_SHOW_ALL_IMAGE, false);
tweet_screen_name.setText(tweet.screenName);
TextHelper.setTweetText(tweet_text, tweet.text);
tweet_created_at.setText(DateTimeHelper
.getRelativeDate(tweet.createdAt));
tweet_source.setText(getString(R.string.tweet_source_prefix)
+ tweet.source);
tweet_user_info.setText(tweet.userId);
boolean isFav = (tweet.favorited.equals("true")) ? true : false;
tweet_fav.setEnabled(isFav);
// Bitmap mProfileBitmap =
// TwitterApplication.mImageManager.get(tweet.profileImageUrl);
profile_image.setImageBitmap(TwitterApplication.mImageLoader.get(
tweet.profileImageUrl, callback));
// has photo
if (!photoPreviewSize.equals(PHOTO_PREVIEW_TYPE_NONE)) {
String photoLink;
boolean isPageLink = false;
if (photoPreviewSize.equals(PHOTO_PREVIEW_TYPE_THUMBNAIL)) {
photoLink = tweet.thumbnail_pic;
} else if (photoPreviewSize.equals(PHOTO_PREVIEW_TYPE_MIDDLE)) {
photoLink = tweet.bmiddle_pic;
} else if (photoPreviewSize.equals(PHOTO_PREVIEW_TYPE_ORIGINAL)) {
photoLink = tweet.original_pic;
} else {
Log.e(TAG, "Invalid Photo Preview Size Type");
photoLink = "";
}
// 如果选用了强制显示则再尝试分析图片链接
if (forceShowAllImage) {
photoLink = getPhotoPageLink(tweet.text, photoPreviewSize);
isPageLink = true;
}
if (!TextUtils.isEmpty(photoLink)) {
status_photo.setVisibility(View.VISIBLE);
status_photo.setImageBitmap(mPhotoBitmap);
doGetPhoto(photoLink, isPageLink);
}
} else {
status_photo.setVisibility(View.GONE);
}
// has reply
if (!TextUtils.isEmpty(tweet.inReplyToStatusId)) {
ViewGroup reply_wrap = (ViewGroup) findViewById(R.id.reply_wrap);
reply_wrap.setVisibility(View.VISIBLE);
reply_status_text = (TextView) findViewById(R.id.reply_status_text);
reply_status_date = (TextView) findViewById(R.id.reply_tweet_created_at);
doGetReply(tweet.inReplyToStatusId);
}
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (mReplyTask != null
&& mReplyTask.getStatus() == GenericTask.Status.RUNNING) {
outState.putBoolean(SIS_RUNNING_KEY, true);
}
}
private String fetchWebPage(String url) throws HttpException {
Log.d(TAG, "Fetching WebPage: " + url);
Response res = mClient.get(url);
return res.asString();
}
private Bitmap fetchPhotoBitmap(String url) throws HttpException,
IOException {
Log.d(TAG, "Fetching Photo: " + url);
Response res = mClient.get(url);
// FIXME:这里使用了一个作废的方法,如何修正?
InputStream is = res.asStream();
Bitmap bitmap = BitmapFactory.decodeStream(is);
is.close();
return bitmap;
}
private void doGetReply(String status_id) {
Log.d(TAG, "Attempting get status task.");
mFeedback.start("");
if (mReplyTask != null
&& mReplyTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mReplyTask = new GetReplyTask();
mReplyTask.setListener(mReplyTaskListener);
TaskParams params = new TaskParams();
params.put("reply_id", status_id);
mReplyTask.execute(params);
}
}
private class GetReplyTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
TaskParams param = params[0];
com.ch_linghu.fanfoudroid.fanfou.Status status;
try {
String reply_id = param.getString("reply_id");
if (!TextUtils.isEmpty(reply_id)) {
// 首先查看是否在数据库中,如不在再去获取
replyTweet = getDb().queryTweet(reply_id, -1);
if (replyTweet == null) {
status = getApi().showStatus(reply_id);
replyTweet = Tweet.create(status);
}
}
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
return TaskResult.IO_ERROR;
}
return TaskResult.OK;
}
}
private void doGetStatus(String status_id) {
Log.d(TAG, "Attempting get status task.");
mFeedback.start("");
if (mStatusTask != null
&& mStatusTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mStatusTask = new GetStatusTask();
mStatusTask.setListener(mStatusTaskListener);
TaskParams params = new TaskParams();
params.put("id", status_id);
mStatusTask.execute(params);
}
}
private class GetStatusTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
TaskParams param = params[0];
com.ch_linghu.fanfoudroid.fanfou.Status status;
try {
String id = param.getString("id");
if (!TextUtils.isEmpty(id)) {
status = getApi().showStatus(id);
mFeedback.update(80);
tweet = Tweet.create(status);
}
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
return TaskResult.IO_ERROR;
}
mFeedback.update(99);
return TaskResult.OK;
}
}
private void doGetPhoto(String photoPageURL, boolean isPageLink) {
mFeedback.start("");
if (mPhotoTask != null
&& mPhotoTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mPhotoTask = new GetPhotoTask();
mPhotoTask.setListener(mPhotoTaskListener);
TaskParams params = new TaskParams();
params.put("photo_url", photoPageURL);
params.put("is_page_link", isPageLink);
mPhotoTask.execute(params);
}
}
private class GetPhotoTask extends GenericTask {
@Override
protected TaskResult _doInBackground(TaskParams... params) {
TaskParams param = params[0];
try {
String photoURL = param.getString("photo_url");
boolean isPageLink = param.getBoolean("is_page_link");
if (!TextUtils.isEmpty(photoURL)) {
if (isPageLink) {
String pageHtml = fetchWebPage(photoURL);
String photoSrcURL = getPhotoURL(pageHtml);
if (photoSrcURL != null) {
mPhotoBitmap = fetchPhotoBitmap(photoSrcURL);
}
} else {
mPhotoBitmap = fetchPhotoBitmap(photoURL);
}
}
} catch (HttpException e) {
Log.e(TAG, e.getMessage(), e);
return TaskResult.IO_ERROR;
} catch (IOException e) {
Log.e(TAG, e.getMessage(), e);
return TaskResult.IO_ERROR;
}
return TaskResult.OK;
}
}
private void showReplyStatus(Tweet tweet) {
if (tweet != null) {
String text = tweet.screenName + " : " + tweet.text;
TextHelper.setSimpleTweetText(reply_status_text, text);
reply_status_date.setText(DateTimeHelper
.getRelativeDate(tweet.createdAt));
} else {
String msg = MessageFormat.format(
getString(R.string.status_status_reply_cannot_display),
this.tweet.inReplyToScreenName);
reply_status_text.setText(msg);
}
}
public void onDeleteFailure() {
Log.e(TAG, "Delete failed");
}
public void onDeleteSuccess() {
finish();
}
// for HasFavorite interface
public void doFavorite(String action, String id) {
if (mFavTask != null
&& mFavTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
if (!TextUtils.isEmpty(id)) {
Log.d(TAG, "doFavorite.");
mFavTask = new TweetCommonTask.FavoriteTask(this);
mFavTask.setListener(mFavTaskListener);
TaskParams param = new TaskParams();
param.put("action", action);
param.put("id", id);
mFavTask.execute(param);
}
}
}
public void onFavSuccess() {
// updateProgress(getString(R.string.refreshing));
if (((TweetCommonTask.FavoriteTask) mFavTask).getType().equals(
TweetCommonTask.FavoriteTask.TYPE_ADD)) {
tweet.favorited = "true";
tweet_fav.setEnabled(true);
} else {
tweet.favorited = "false";
tweet_fav.setEnabled(false);
}
}
public void onFavFailure() {
// updateProgress(getString(R.string.refreshing));
}
private void doDelete(String id) {
if (mDeleteTask != null
&& mDeleteTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mDeleteTask = new TweetCommonTask.DeleteTask(this);
mDeleteTask.setListener(mDeleteTaskListener);
TaskParams params = new TaskParams();
params.put("id", id);
mDeleteTask.execute(params);
}
}
@Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case CONTEXT_REFRESH_ID:
doGetStatus(tweet.id);
return true;
case CONTEXT_CLIPBOARD_ID:
ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
clipboard.setText(TextHelper.getSimpleTweetText(tweet.text));
return true;
case CONTEXT_DELETE_ID:
doDelete(tweet.id);
return true;
}
return super.onContextItemSelected(item);
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
menu.setHeaderIcon(android.R.drawable.ic_menu_more);
menu.setHeaderTitle(getString(R.string.cmenu_more));
menu.add(0, CONTEXT_REFRESH_ID, 0, R.string.omenu_refresh);
menu.add(0, CONTEXT_CLIPBOARD_ID, 0, R.string.cmenu_clipboard);
if (tweet.userId.equals(TwitterApplication.getMyselfId(false))) {
menu.add(0, CONTEXT_DELETE_ID, 0, R.string.cmenu_delete);
}
}
} | 061304011116lyj-and | src/com/ch_linghu/fanfoudroid/StatusActivity.java | Java | asf20 | 23,198 |
package com.ch_linghu.fanfoudroid;
import java.text.MessageFormat;
import java.util.List;
import android.content.Intent;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ListView;
import com.ch_linghu.fanfoudroid.data.User;
import com.ch_linghu.fanfoudroid.fanfou.Paging;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.ui.base.UserArrayBaseActivity;
import com.ch_linghu.fanfoudroid.ui.module.UserArrayAdapter;
import com.ch_linghu.fanfoudroid.R;
public class FollowingActivity extends UserArrayBaseActivity {
private ListView mUserList;
private UserArrayAdapter mAdapter;
private String userId;
private String userName;
private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.FOLLOWING";
private static final String USER_ID = "userId";
private static final String USER_NAME = "userName";
private int currentPage = 1;
String myself = "";
@Override
protected boolean _onCreate(Bundle savedInstanceState) {
Intent intent = getIntent();
Bundle extras = intent.getExtras();
if (extras != null) {
this.userId = extras.getString(USER_ID);
this.userName = extras.getString(USER_NAME);
} else {
// 获取登录用户id
userId = TwitterApplication.getMyselfId(false);
userName = TwitterApplication.getMyselfName(false);
}
if (super._onCreate(savedInstanceState)) {
myself = TwitterApplication.getMyselfId(false);
if (getUserId() == myself) {
mNavbar.setHeaderTitle(MessageFormat.format(
getString(R.string.profile_friends_count_title), "我"));
} else {
mNavbar.setHeaderTitle(MessageFormat.format(
getString(R.string.profile_friends_count_title),
userName));
}
return true;
} else {
return false;
}
}
/*
* 添加取消关注按钮
*
* @see
* com.ch_linghu.fanfoudroid.ui.base.UserListBaseActivity#onCreateContextMenu
* (android.view.ContextMenu, android.view.View,
* android.view.ContextMenu.ContextMenuInfo)
*/
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
if (getUserId() == myself) {
AdapterView.AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
User user = getContextItemUser(info.position);
menu.add(
0,
CONTENT_DEL_FRIEND,
0,
getResources().getString(
R.string.cmenu_user_addfriend_prefix)
+ user.screenName
+ getResources().getString(
R.string.cmenu_user_friend_suffix));
}
}
public static Intent createIntent(String userId, String userName) {
Intent intent = new Intent(LAUNCH_ACTION);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra(USER_ID, userId);
intent.putExtra(USER_NAME, userName);
return intent;
}
@Override
public Paging getNextPage() {
currentPage += 1;
return new Paging(currentPage);
}
@Override
protected String getUserId() {
return this.userId;
}
@Override
public Paging getCurrentPage() {
currentPage = 1;
return new Paging(this.currentPage);
}
@Override
protected List<com.ch_linghu.fanfoudroid.fanfou.User> getUsers(
String userId, Paging page) throws HttpException {
return getApi().getFriendsStatuses(userId, page);
}
}
| 061304011116lyj-and | src/com/ch_linghu/fanfoudroid/FollowingActivity.java | Java | asf20 | 3,452 |
package com.ch_linghu.fanfoudroid;
import java.util.HashSet;
//import org.acra.ReportingInteractionMode;
//import org.acra.annotation.ReportsCrashes;
import android.app.Application;
import android.content.Context;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.preference.PreferenceManager;
import android.widget.Toast;
import com.ch_linghu.fanfoudroid.app.LazyImageLoader;
import com.ch_linghu.fanfoudroid.app.Preferences;
import com.ch_linghu.fanfoudroid.db.StatusTable;
import com.ch_linghu.fanfoudroid.db.TwitterDatabase;
import com.ch_linghu.fanfoudroid.fanfou.Configuration;
import com.ch_linghu.fanfoudroid.fanfou.User;
import com.ch_linghu.fanfoudroid.fanfou.Weibo;
import com.ch_linghu.fanfoudroid.http.HttpException;
import com.ch_linghu.fanfoudroid.task.GenericTask;
import com.ch_linghu.fanfoudroid.task.TaskAdapter;
import com.ch_linghu.fanfoudroid.task.TaskParams;
import com.ch_linghu.fanfoudroid.task.TaskResult;
//@ReportsCrashes(formKey="dHowMk5LMXQweVJkWGthb1E1T1NUUHc6MQ",
// mode = ReportingInteractionMode.NOTIFICATION,
// resNotifTickerText = R.string.crash_notif_ticker_text,
// resNotifTitle = R.string.crash_notif_title,
// resNotifText = R.string.crash_notif_text,
// resNotifIcon = android.R.drawable.stat_notify_error, // optional. default is a warning sign
// resDialogText = R.string.crash_dialog_text,
// resDialogIcon = android.R.drawable.ic_dialog_info, //optional. default is a warning sign
// resDialogTitle = R.string.crash_dialog_title, // optional. default is your application name
// resDialogCommentPrompt = R.string.crash_dialog_comment_prompt, // optional. when defined, adds a user text field input with this text resource as a label
// resDialogOkToast = R.string.crash_dialog_ok_toast // optional. displays a Toast message when the user accepts to send a report.
//)
public class TwitterApplication extends Application {
public static final String TAG = "TwitterApplication";
// public static ImageManager mImageManager;
public static LazyImageLoader mImageLoader;
public static TwitterDatabase mDb;
public static Weibo mApi; // new API
public static Context mContext;
public static SharedPreferences mPref;
public static int networkType = 0;
public final static boolean DEBUG = Configuration.getDebug();
public GenericTask mUserInfoTask = new GetUserInfoTask();
// FIXME:获取登录用户id, 据肉眼观察,刚注册的用户系统分配id都是~开头的,因为不知道
// 用户何时去修改这个ID,目前只有把所有以~开头的ID在每次需要UserId时都去服务器
// 取一次数据,看看新的ID是否已经设定,判断依据是是否以~开头。这么判断会把有些用户
// 就是把自己ID设置的以~开头的造成,每次都需要去服务器取数。
// 只是简单处理了mPref没有CURRENT_USER_ID的情况,因为用户在登陆时,肯定会记一个CURRENT_USER_ID
// 到mPref.
private static void fetchMyselfInfo() {
User myself;
try {
myself = TwitterApplication.mApi.showUser(TwitterApplication.mApi
.getUserId());
TwitterApplication.mPref.edit()
.putString(Preferences.CURRENT_USER_ID, myself.getId())
.commit();
TwitterApplication.mPref
.edit()
.putString(Preferences.CURRENT_USER_SCREEN_NAME,
myself.getScreenName()).commit();
} catch (HttpException e) {
e.printStackTrace();
}
}
public static String getMyselfId(boolean forceGet) {
if (!mPref.contains(Preferences.CURRENT_USER_ID)){
if (forceGet && mPref.getString(Preferences.CURRENT_USER_ID, "~")
.startsWith("~")){
fetchMyselfInfo();
}
}
return mPref.getString(Preferences.CURRENT_USER_ID, "~");
}
public static String getMyselfName(boolean forceGet) {
if (!mPref.contains(Preferences.CURRENT_USER_ID)
|| !mPref.contains(Preferences.CURRENT_USER_SCREEN_NAME)) {
if (forceGet && mPref.getString(Preferences.CURRENT_USER_ID, "~")
.startsWith("~")){
fetchMyselfInfo();
}
}
return mPref.getString(Preferences.CURRENT_USER_SCREEN_NAME, "");
}
@Override
public void onCreate() {
// FIXME: StrictMode类在1.6以下的版本中没有,会导致类加载失败。
// 因此将这些代码设成关闭状态,仅在做性能调试时才打开。
// //NOTE: StrictMode模式需要2.3+ API支持。
// if (DEBUG){
// StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
// .detectAll()
// .penaltyLog()
// .build());
// StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
// .detectAll()
// .penaltyLog()
// .build());
// }
super.onCreate();
mContext = this.getApplicationContext();
// mImageManager = new ImageManager(this);
mImageLoader = new LazyImageLoader();
mApi = new Weibo();
mDb = TwitterDatabase.getInstance(this);
mPref = PreferenceManager.getDefaultSharedPreferences(this);
String username = mPref.getString(Preferences.USERNAME_KEY, "");
String password = mPref.getString(Preferences.PASSWORD_KEY, "");
password = LoginActivity.decryptPassword(password);
if (Weibo.isValidCredentials(username, password)) {
mApi.setCredentials(username, password); // Setup API and HttpClient
doGetUserInfo();
}
// 为cmwap用户设置代理上网
String type = getNetworkType();
if (null != type && type.equalsIgnoreCase("cmwap")) {
Toast.makeText(this, "您当前正在使用cmwap网络上网.", Toast.LENGTH_SHORT);
mApi.getHttpClient().setProxy("10.0.0.172", 80, "http");
}
}
public String getNetworkType() {
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
// NetworkInfo mobNetInfo = connectivityManager
// .getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (activeNetInfo != null) {
return activeNetInfo.getExtraInfo(); // 接入点名称: 此名称可被用户任意更改 如: cmwap,
// cmnet,
// internet ...
} else {
return null;
}
}
@Override
public void onTerminate() {
// FIXME: 根据android文档,onTerminate不会在真实机器上被执行到
// 因此这些清理动作需要再找合适的地方放置,以确保执行。
cleanupImages();
mDb.close();
Toast.makeText(this, "exit app", Toast.LENGTH_LONG);
super.onTerminate();
}
private void cleanupImages() {
HashSet<String> keepers = new HashSet<String>();
Cursor cursor = mDb.fetchAllTweets(StatusTable.TYPE_HOME);
if (cursor.moveToFirst()) {
int imageIndex = cursor
.getColumnIndexOrThrow(StatusTable.PROFILE_IMAGE_URL);
do {
keepers.add(cursor.getString(imageIndex));
} while (cursor.moveToNext());
}
cursor.close();
cursor = mDb.fetchAllDms(-1);
if (cursor.moveToFirst()) {
int imageIndex = cursor
.getColumnIndexOrThrow(StatusTable.PROFILE_IMAGE_URL);
do {
keepers.add(cursor.getString(imageIndex));
} while (cursor.moveToNext());
}
cursor.close();
mImageLoader.getImageManager().cleanup(keepers);
}
public void doGetUserInfo()
{
if (mUserInfoTask != null
&& mUserInfoTask.getStatus() == GenericTask.Status.RUNNING) {
return;
} else {
mUserInfoTask = new GetUserInfoTask();
mUserInfoTask.setListener(new TaskAdapter(){
@Override
public String getName() {
return "GetUserInfo";
}
});
mUserInfoTask.execute();
}
}
public class GetUserInfoTask extends GenericTask {
public static final String TAG = "DeleteTask";
@Override
protected TaskResult _doInBackground(TaskParams... params) {
getMyselfId(true);
getMyselfName(true);
return TaskResult.OK;
}
}
}
| 061304011116lyj-and | src/com/ch_linghu/fanfoudroid/TwitterApplication.java | Java | asf20 | 8,108 |
package com.markupartist.android.widget;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.LinearInterpolator;
import android.view.animation.RotateAnimation;
import android.widget.AbsListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.AbsListView.OnScrollListener;
import com.ch_linghu.fanfoudroid.R;
public class PullToRefreshListView extends ListView implements
OnScrollListener, GestureDetector.OnGestureListener {
private final int MAXHEIGHT = 20;
private static final int TAP_TO_REFRESH = 1;
private static final int PULL_TO_REFRESH = 2;
private static final int RELEASE_TO_REFRESH = 3;
private static final int REFRESHING = 4;
// private static final int RELEASING = 5;//释放过程做动画用
private static final String TAG = "PullToRefreshListView";
private OnRefreshListener mOnRefreshListener;
/**
* Listener that will receive notifications every time the list scrolls.
*/
private OnScrollListener mOnScrollListener;
private LayoutInflater mInflater;
private LinearLayout mRefreshView;
private TextView mRefreshViewText;
private ImageView mRefreshViewImage;
private ProgressBar mRefreshViewProgress;
private TextView mRefreshViewLastUpdated;
private int mCurrentScrollState;
private int mRefreshState;
private RotateAnimation mFlipAnimation;
private RotateAnimation mReverseFlipAnimation;
private int mRefreshViewHeight;
private int mRefreshOriginalTopPadding;
private int mLastMotionY;
private GestureDetector mDetector;
// private int mPadding;
public PullToRefreshListView(Context context) {
super(context);
init(context);
}
public PullToRefreshListView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public PullToRefreshListView(Context context, AttributeSet attrs,
int defStyle) {
super(context, attrs, defStyle);
init(context);
}
private void init(Context context) {
GestureDetector localGestureDetector = new GestureDetector(this);
this.mDetector = localGestureDetector;
// Load all of the animations we need in code rather than through XML
mFlipAnimation = new RotateAnimation(0, -180,
RotateAnimation.RELATIVE_TO_SELF, 0.5f,
RotateAnimation.RELATIVE_TO_SELF, 0.5f);
mFlipAnimation.setInterpolator(new LinearInterpolator());
mFlipAnimation.setDuration(200);
mFlipAnimation.setFillAfter(true);
mReverseFlipAnimation = new RotateAnimation(-180, 0,
RotateAnimation.RELATIVE_TO_SELF, 0.5f,
RotateAnimation.RELATIVE_TO_SELF, 0.5f);
mReverseFlipAnimation.setInterpolator(new LinearInterpolator());
mReverseFlipAnimation.setDuration(200);
mReverseFlipAnimation.setFillAfter(true);
mInflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mRefreshView = (LinearLayout) mInflater.inflate(
R.layout.pull_to_refresh_header, null);
mRefreshViewText = (TextView) mRefreshView
.findViewById(R.id.pull_to_refresh_text);
mRefreshViewImage = (ImageView) mRefreshView
.findViewById(R.id.pull_to_refresh_image);
mRefreshViewProgress = (ProgressBar) mRefreshView
.findViewById(R.id.pull_to_refresh_progress);
mRefreshViewLastUpdated = (TextView) mRefreshView
.findViewById(R.id.pull_to_refresh_updated_at);
mRefreshViewImage.setMinimumHeight(50);
mRefreshView.setOnClickListener(new OnClickRefreshListener());
mRefreshOriginalTopPadding = mRefreshView.getPaddingTop();
mRefreshState = TAP_TO_REFRESH;
addHeaderView(mRefreshView);
super.setOnScrollListener(this);
measureView(mRefreshView);
mRefreshViewHeight = mRefreshView.getMeasuredHeight();
}
@Override
public void setAdapter(ListAdapter adapter) {
super.setAdapter(adapter);
setSelection(1);
}
/**
* Set the listener that will receive notifications every time the list
* scrolls.
*
* @param l
* The scroll listener.
*/
@Override
public void setOnScrollListener(AbsListView.OnScrollListener l) {
mOnScrollListener = l;
}
/**
* Register a callback to be invoked when this list should be refreshed.
*
* @param onRefreshListener
* The callback to run.
*/
public void setOnRefreshListener(OnRefreshListener onRefreshListener) {
mOnRefreshListener = onRefreshListener;
}
/**
* Set a text to represent when the list was last updated.
*
* @param lastUpdated
* Last updated at.
*/
public void setLastUpdated(CharSequence lastUpdated) {
if (lastUpdated != null) {
mRefreshViewLastUpdated.setVisibility(View.VISIBLE);
mRefreshViewLastUpdated.setText(lastUpdated);
} else {
mRefreshViewLastUpdated.setVisibility(View.GONE);
}
}
@Override
/**
* TODO:此方法重写
*/
public boolean onTouchEvent(MotionEvent event) {
GestureDetector localGestureDetector = this.mDetector;
localGestureDetector.onTouchEvent(event);
final int y = (int) event.getY();
Log.d(TAG,
String.format(
"[onTouchEvent]event.Action=%d, currState=%d, refreshState=%d,y=%d",
event.getAction(), mCurrentScrollState, mRefreshState,
y));
switch (event.getAction()) {
case MotionEvent.ACTION_UP:
if (!isVerticalScrollBarEnabled()) {
setVerticalScrollBarEnabled(true);
}
if (getFirstVisiblePosition() == 0 && mRefreshState != REFRESHING) {
if ((mRefreshView.getBottom() >= mRefreshViewHeight + MAXHEIGHT || mRefreshView
.getTop() >= 0)) {
// Initiate the refresh
mRefreshState = REFRESHING;
prepareForRefresh();
onRefresh();
} else if (mRefreshView.getBottom() < mRefreshViewHeight
+ MAXHEIGHT
|| mRefreshView.getTop() <= 0) {
// Abort refresh and scroll down below the refresh view
resetHeader();
setSelection(1);
}
}
break;
case MotionEvent.ACTION_DOWN:
mLastMotionY = y;
break;
case MotionEvent.ACTION_MOVE:
applyHeaderPadding(event);
break;
}
return super.onTouchEvent(event);
}
/**
* TODO:此方法重写
* @param ev
*/
private void applyHeaderPadding(MotionEvent ev) {
final int historySize = ev.getHistorySize();
Log.d(TAG, String.format(
"[applyHeaderPadding]currState=%d, refreshState=%d",
mCurrentScrollState, mRefreshState));
// Workaround for getPointerCount() which is unavailable in 1.5
// (it's always 1 in 1.5)
int pointerCount = 1;
try {
Method method = MotionEvent.class.getMethod("getPointerCount");
pointerCount = (Integer) method.invoke(ev);
} catch (NoSuchMethodException e) {
pointerCount = 1;
} catch (IllegalArgumentException e) {
throw e;
} catch (IllegalAccessException e) {
System.err.println("unexpected " + e);
} catch (InvocationTargetException e) {
System.err.println("unexpected " + e);
}
if (mRefreshState == RELEASE_TO_REFRESH) {
// this.offsetTopAndBottom(-mPadding);
for (int h = 0; h < historySize; h++) {
for (int p = 0; p < pointerCount; p++) {
if (isVerticalFadingEdgeEnabled()) {
setVerticalScrollBarEnabled(false);
}
int historicalY = 0;
try {
// For Android > 2.0
Method method = MotionEvent.class.getMethod(
"getHistoricalY", Integer.TYPE, Integer.TYPE);
historicalY = ((Float) method.invoke(ev, p, h))
.intValue();
} catch (NoSuchMethodException e) {
// For Android < 2.0
historicalY = (int) (ev.getHistoricalY(h));
} catch (IllegalArgumentException e) {
throw e;
} catch (IllegalAccessException e) {
System.err.println("unexpected " + e);
} catch (InvocationTargetException e) {
System.err.println("unexpected " + e);
}
// Calculate the padding to apply, we divide by 1.7 to
// simulate a more resistant effect during pull.
int topPadding = (int) (((historicalY - mLastMotionY) - mRefreshViewHeight) / 1.7);
// Log.d(TAG,
// String.format(
// "[applyHeaderPadding]historicalY=%d,topPadding=%d,mRefreshViewHeight=%d,mLastMotionY=%d",
// historicalY, topPadding,
// mRefreshViewHeight, mLastMotionY));
mRefreshView.setPadding(mRefreshView.getPaddingLeft(),
topPadding, mRefreshView.getPaddingRight(),
mRefreshView.getPaddingBottom());
}
}
}
}
/**
* Sets the header padding back to original size.
*/
private void resetHeaderPadding() {
Log.d(TAG, String.format(
"[resetHeaderPadding]currState=%d, refreshState=%d",
mCurrentScrollState, mRefreshState));
// invalidate();
//this.mPadding=0;
//this.offsetTopAndBottom(this.mPadding);
mRefreshView.setPadding(mRefreshView.getPaddingLeft(),
mRefreshOriginalTopPadding, mRefreshView.getPaddingRight(),
mRefreshView.getPaddingBottom());
}
/**
* Resets the header to the original state.
*/
private void resetHeader() {
Log.d(TAG, String.format("[resetHeader]currState=%d, refreshState=%d",
mCurrentScrollState, mRefreshState));
if (mRefreshState != TAP_TO_REFRESH) {
mRefreshState = TAP_TO_REFRESH;
resetHeaderPadding();
// Set refresh view text to the pull label
// mRefreshViewText.setText(R.string.pull_to_refresh_tap_label);//点击刷新是否有用
mRefreshViewText.setText(R.string.pull_to_refresh_pull_label);
// Replace refresh drawable with arrow drawable
mRefreshViewImage
.setImageResource(R.drawable.ic_pulltorefresh_arrow);
// Clear the full rotation animation
mRefreshViewImage.clearAnimation();
// Hide progress bar and arrow.
mRefreshViewImage.setVisibility(View.GONE);
mRefreshViewProgress.setVisibility(View.GONE);
}
}
private void measureView(View child) {
Log.d(TAG, String.format("[measureView]currState=%d, refreshState=%d",
mCurrentScrollState, mRefreshState));
ViewGroup.LayoutParams p = child.getLayoutParams();
if (p == null) {
p = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,
ViewGroup.LayoutParams.WRAP_CONTENT);
}
int childWidthSpec = ViewGroup.getChildMeasureSpec(0, 0 + 0, p.width);
int lpHeight = p.height;
int childHeightSpec;
if (lpHeight > 0) {
childHeightSpec = MeasureSpec.makeMeasureSpec(lpHeight,
MeasureSpec.EXACTLY);
} else {
childHeightSpec = MeasureSpec.makeMeasureSpec(0,
MeasureSpec.UNSPECIFIED);
}
child.measure(childWidthSpec, childHeightSpec);
}
@Override
public void onScroll(AbsListView view, int firstVisibleItem,
int visibleItemCount, int totalItemCount) {
Log.d(TAG, "List onScroll");
if (mCurrentScrollState == SCROLL_STATE_FLING
&& firstVisibleItem == 0 && mRefreshState != REFRESHING) {
setSelection(1);
mRefreshViewImage.setVisibility(View.INVISIBLE);
}
if (mOnScrollListener != null) {
mOnScrollListener.onScroll(this, firstVisibleItem,
visibleItemCount, totalItemCount);
}
}
@Override
public void onScrollStateChanged(AbsListView view, int scrollState) {
mCurrentScrollState = scrollState;
if (mOnScrollListener != null) {
mOnScrollListener.onScrollStateChanged(view, scrollState);
}
}
public void prepareForRefresh() {
resetHeaderPadding();
mRefreshViewImage.setVisibility(View.GONE);
// We need this hack, otherwise it will keep the previous drawable.
mRefreshViewImage.setImageDrawable(null);
mRefreshViewProgress.setVisibility(View.VISIBLE);
// Set refresh view text to the refreshing label
mRefreshViewText.setText(R.string.pull_to_refresh_refreshing_label);
mRefreshState = REFRESHING;
}
public void onRefresh() {
Log.d(TAG, "onRefresh");
if (mOnRefreshListener != null) {
mOnRefreshListener.onRefresh();
}
}
/**
* Resets the list to a normal state after a refresh.
*
* @param lastUpdated
* Last updated at.
*/
public void onRefreshComplete(CharSequence lastUpdated) {
setLastUpdated(lastUpdated);
onRefreshComplete();
}
/**
* Resets the list to a normal state after a refresh.
*/
public void onRefreshComplete() {
Log.d(TAG, "onRefreshComplete");
resetHeader();
// If refresh view is visible when loading completes, scroll down to
// the next item.
if (mRefreshView.getBottom() > 0) {
invalidateViews();
// setSelection(1);
}
}
/**
* Invoked when the refresh view is clicked on. This is mainly used when
* there's only a few items in the list and it's not possible to drag the
* list.
*/
private class OnClickRefreshListener implements OnClickListener {
@Override
public void onClick(View v) {
if (mRefreshState != REFRESHING) {
prepareForRefresh();
onRefresh();
}
}
}
/**
* Interface definition for a callback to be invoked when list should be
* refreshed.
*/
public interface OnRefreshListener {
/**
* Called when the list should be refreshed.
* <p>
* A call to {@link PullToRefreshListView #onRefreshComplete()} is
* expected to indicate that the refresh has completed.
*/
public void onRefresh();
}
@Override
public boolean onDown(MotionEvent e) {
// TODO Auto-generated method stub
return false;
}
@Override
public void onShowPress(MotionEvent e) {
// TODO Auto-generated method stub
}
@Override
public boolean onSingleTapUp(MotionEvent e) {
// TODO Auto-generated method stub
return false;
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
float distanceY) {
int firstVisibleItem = this.getFirstVisiblePosition();
// When the refresh view is completely visible, change the text to say
// "Release to refresh..." and flip the arrow drawable.
Log.d(TAG, String.format(
"[OnScroll]first=%d, currState=%d, refreshState=%d",
firstVisibleItem, mCurrentScrollState, mRefreshState));
if (mCurrentScrollState == SCROLL_STATE_TOUCH_SCROLL
&& mRefreshState != REFRESHING) {
if (firstVisibleItem == 0) {
mRefreshViewImage.setVisibility(View.VISIBLE);
// Log.d(TAG,
// String.format(
// "getBottom=%d,refreshViewHeight=%d,getTop=%d,mRefreshOriginalTopPadding=%d",
// mRefreshView.getBottom(), mRefreshViewHeight
// + MAXHEIGHT,
// this.getTopPaddingOffset(),
// mRefreshOriginalTopPadding));
if ((mRefreshView.getBottom() >= mRefreshViewHeight + MAXHEIGHT || mRefreshView
.getTop() >= 0) && mRefreshState != RELEASE_TO_REFRESH) {
//this.mPadding+=distanceY;//备用
mRefreshViewText
.setText(R.string.pull_to_refresh_release_label);
mRefreshViewImage.clearAnimation();
mRefreshViewImage.startAnimation(mFlipAnimation);
mRefreshState = RELEASE_TO_REFRESH;
} else if (mRefreshView.getBottom() < mRefreshViewHeight
+ MAXHEIGHT
&& mRefreshState != PULL_TO_REFRESH) {
mRefreshViewText
.setText(R.string.pull_to_refresh_pull_label);
if (mRefreshState != TAP_TO_REFRESH) {
mRefreshViewImage.clearAnimation();
mRefreshViewImage.startAnimation(mReverseFlipAnimation);
}
mRefreshState = PULL_TO_REFRESH;
}
} else {
mRefreshViewImage.setVisibility(View.GONE);
resetHeader();
}
} /*not execute
else if (mCurrentScrollState == SCROLL_STATE_FLING
&& firstVisibleItem == 0 && mRefreshState != REFRESHING) {
setSelection(1);
}*/
return false;
}
@Override
public void onLongPress(MotionEvent e) {
// TODO Auto-generated method stub
}
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
// TODO Auto-generated method stub
return false;
}
}
| 061304011116lyj-and | src/com/markupartist/android/widget/PullToRefreshListView.java | Java | asf20 | 15,869 |
#!/bin/bash
# 打开apache.http调试信息
adb shell setprop log.tag.org.apache.http VERBOSE
adb shell setprop log.tag.org.apache.http.wire VERBOSE
adb shell setprop log.tag.org.apache.http.headers VERBOSE
echo "Enable Debug"
| 061304011116lyj-and | tools/openHttpDebug.sh | Shell | asf20 | 229 |
/* Javadoc 样式表 */
/* 在此处定义颜色、字体和其他样式属性以覆盖默认值 */
/* 页面背景颜色 */
body { background-color: #FFFFFF; color:#000000 }
/* 标题 */
h1 { font-size: 145% }
/* 表格颜色 */
.TableHeadingColor { background: #CCCCFF; color:#000000 } /* 深紫色 */
.TableSubHeadingColor { background: #EEEEFF; color:#000000 } /* 淡紫色 */
.TableRowColor { background: #FFFFFF; color:#000000 } /* 白色 */
/* 左侧的框架列表中使用的字体 */
.FrameTitleFont { font-size: 100%; font-family: Helvetica, Arial, sans-serif; color:#000000 }
.FrameHeadingFont { font-size: 90%; font-family: Helvetica, Arial, sans-serif; color:#000000 }
.FrameItemFont { font-size: 90%; font-family: Helvetica, Arial, sans-serif; color:#000000 }
/* 导航栏字体和颜色 */
.NavBarCell1 { background-color:#EEEEFF; color:#000000} /* 淡紫色 */
.NavBarCell1Rev { background-color:#00008B; color:#FFFFFF} /* 深蓝色 */
.NavBarFont1 { font-family: Arial, Helvetica, sans-serif; color:#000000;color:#000000;}
.NavBarFont1Rev { font-family: Arial, Helvetica, sans-serif; color:#FFFFFF;color:#FFFFFF;}
.NavBarCell2 { font-family: Arial, Helvetica, sans-serif; background-color:#FFFFFF; color:#000000}
.NavBarCell3 { font-family: Arial, Helvetica, sans-serif; background-color:#FFFFFF; color:#000000}
| 061304011116lyj-and | doc/stylesheet.css | CSS | asf20 | 1,370 |
<?php
$texto = file_get_contents('nuestra-carta');
preg_match_all('/\<div\sclass\=\"titulo-producto-cuerpo\"\>([^\>]*)\<\/div\>/', $texto, $matches);
$m = $matches[1];
$products = array();
foreach($m as $key => $value) {
$value = $m[$key] = trim($value);
if (preg_match("/^\d+.*/", $value) != 1) {
unset($m[$key]);
continue;
}
preg_match('/(\d+)\.\s*(.*)/', $value, $matches);
$products[$matches[1]] = $matches[2];
echo " products.add(generateProduct({$matches[1]}, \"{$matches[2]}\"));\n";
}
/*
$products = array_reverse($products);
preg_match_all('/\<img[^>]*class=\"imagecache\simagecache-preset_productos_listado_cuadricula\simagecache-default\simagecache-preset_productos_listado_cuadricula_default\"[^>]*>/', $texto, $matches);
foreach($matches[0] as $key => $value) {
preg_match('/src="(.*\d+[_0]?.png)"/', $value, $match);
if (isset($match[1]))
echo "wget " .$match[1] . "\n";
}
*/
| 100montaditos | trunk/data/a.php | PHP | gpl3 | 912 |
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/100_0.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/99_0.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/98_0.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/97_0.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/96_0.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/95_0.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/94_0.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/93_0.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/92_0.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/91_0.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/90.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/89.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/88.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/87.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/86.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/85.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/84.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/83.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/82.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/81.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/80.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/79.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/78.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/77.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/76.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/75.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/74.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/73.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/72.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/71.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/70.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/69.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/68.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/67.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/66.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/65.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/64.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/63.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/62.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/61.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/60.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/59.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/58.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/57.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/56.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/55.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/54.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/53.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/52.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/51.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/50.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/49.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/48.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/47.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/46.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/45.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/44.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/43.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/42.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/41.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/40.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/39.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/38.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/37.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/36.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/35.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/34.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/33.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/32.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/31.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/30.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/29.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/28.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/27.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/26.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/25.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/24.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/23.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/22.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/21_0.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/20.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/19.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/18.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/17.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/16.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/15.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/14.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/13_0.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/12.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/11.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/10.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/09.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/08.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/07.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/06.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/05.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/04.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/03.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/02.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/01.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/ensalada%20cesar_0.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/ensalada%20chef_0.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/ensalada%20mediterranea_0.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/ensalada%20tropical_0.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/ensalada%20salmon_1.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/aceitunas_1.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/aceitunas%20de%20la%20abuela_1.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/cartucho%20patatas%20fritas_1.png
wget http://www.100montaditos.com/sites/default/files/imagecache/preset_productos_listado_cuadricula/patatas%20fritas%204%20salsas_1.png
| 100montaditos | trunk/data/a.sh | Shell | gpl3 | 11,980 |
import sys
import os
from PIL import Image
def detectEdge(img, w, h):
left, upper, right, lower = w,h,0,0
pixels = img.load()
threshold = 10
for x in range(0,w):
for y in xrange(0,h):
pix = pixels[x,y]
if (pix[0]<(254-threshold) or pix[1]<(254-threshold) or pix[2]<(254-threshold)) and pix[3]>0:
left, upper, right, lower = min(x,left),min(y,upper),max(x,right),max(y,lower)
return (left, upper, right, lower)
if __name__ == '__main__':
dirList=os.listdir(sys.argv[1])
for fname in dirList:
if fname.endswith(sys.argv[3]):
img = Image.open(os.path.join(sys.argv[1],fname))
width, height = img.size
box = detectEdge(img,width,height)
print fname, box
img2 = img.crop(box)
# img2 = img2.resize((width, height), Image.ANTIALIAS)
img2 = img2.resize(((box[2]-box[0]), (box[3]-box[1])), Image.ANTIALIAS)
img2.save(os.path.join(sys.argv[2],fname))
| 100montaditos | trunk/tool/resize.py | Python | gpl3 | 1,035 |
package com.gs.montaditos;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import android.content.Context;
import android.util.Log;
class Montaditos {
private static Context context;
private static List<HashMap> montaditos;
public static void init (Context c) {
context = c;
montaditos = generateProducts();
}
public static List<HashMap> getAll() {
return montaditos;
}
public static HashMap get(Integer id) {
Iterator it = montaditos.iterator();
while (it.hasNext()) {
HashMap local = (HashMap)it.next();
if (local.get("montaditoId").equals(id.toString())) {
return local;
}
}
Log.d("m", "none");
return null;
}
private static List<HashMap> generateProducts() {
List<HashMap> products = new ArrayList<HashMap>();
products.add(generateProduct(100, "Hot dog: salchicha, bacon ahumado, queso cheddar, ketchup y mostaza"));
products.add(generateProduct(99, "Hot dog: salchicha, cebolla crujiente, ketchup y mostaza"));
products.add(generateProduct(98, "Burguer bacon: Hamburguesa, bacon ahumado, queso cheddar, ketchup y mostaza"));
products.add(generateProduct(97, "Burger: hamburguesa, lechuga, cebolla crujiente, ketchup y mostaza"));
products.add(generateProduct(96, "Taco mejicano: pollo asado, kebab de ternera y salsa mejicana"));
products.add(generateProduct(95, "Barbacoa: pollo asado, bacon ahumado, queso cheddar, cebolla crujiente y salsa barbacoa"));
products.add(generateProduct(94, "TU MONTADITO.COM: pollo asado, piña, lechuga y salsa rosa"));
products.add(generateProduct(93, "Napolitana: anchoa, mozarella, tomate natural y orégano"));
products.add(generateProduct(92, "Margarita: lacón, mozzarella, tomate natural y orégano"));
products.add(generateProduct(91, "Club: pollo asado, lechuga, tomate natural y mayonesa"));
products.add(generateProduct(90, "César: pollo asado, lechuga, queso ibérico, cebolla crujiente y salsa césar"));
products.add(generateProduct(89, "Serranito: jamón ibérico, lomo al ajillo, queso ibérico, pimiento verde y tomate natural"));
products.add(generateProduct(88, "Piripi: lomo al ajillo, queso brie, bacon ahumado, tomate natural y ali-oli"));
products.add(generateProduct(87, "Kebab: kebab de ternera, lechuga y tomate natural y salsa kebab"));
products.add(generateProduct(86, "Kebab de ternera con parmesano, cebolla crujiente y salsa kebab"));
products.add(generateProduct(85, "Kebab de ternera con pollo asado, cebolla crujiente y salsa kebab"));
products.add(generateProduct(84, "Pepito de ternera con queso ibérico y tomate natural"));
products.add(generateProduct(83, "Pepito de ternera con queso cheddar y salsa brava"));
products.add(generateProduct(82, "Pepito de ternera con pimiento verde"));
products.add(generateProduct(81, "Lomo al ajillo con queso ibérico, pimiento verde y salsa barbacoa"));
products.add(generateProduct(80, "Lomo al ajillo con cebolla crujiente y mojo picón"));
products.add(generateProduct(79, "Bacon ahumado con queso azul y chistorra a la piedra"));
products.add(generateProduct(78, "Cuatro quesos: queso ibérico, queso brie, queso azul y crema de queso"));
products.add(generateProduct(77, "Chorizo a la sidra con queso ibérico, cebolla crujiente y ali-oli"));
products.add(generateProduct(76, "Carne mechada con queso ibérico y pimiento verde"));
products.add(generateProduct(75, "Anchoas con queso ibérico y tomate natural"));
products.add(generateProduct(74, "Atún con anchoas y tomate natural"));
products.add(generateProduct(73, "Atún con lechuga y salsa rosa"));
products.add(generateProduct(72, "Gambas con crema de queso y piña"));
products.add(generateProduct(71, "Gambas con ali-oli"));
products.add(generateProduct(70, "Calamares con mojo picón"));
products.add(generateProduct(69, "Calamares con salsa brava"));
products.add(generateProduct(68, "Pollo asado con bacon ahumado, queso ibérico y salsa brava"));
products.add(generateProduct(67, "Jamón ibérico con queso ibérico y aceite de oliva"));
products.add(generateProduct(66, "El veggie: crema de queso, parmesano rallado, lechuga y tomate natural"));
products.add(generateProduct(65, "Lacón con tomate cherry y lechuga"));
products.add(generateProduct(64, "Salmón ahumado con lechuga y tomate natural"));
products.add(generateProduct(63, "Anchoas con crema de queso"));
products.add(generateProduct(62, "Atún con tomate natural y lechuga"));
products.add(generateProduct(61, "Pollo asado con salmorejo"));
products.add(generateProduct(60, "Anchoas con tomate natural"));
products.add(generateProduct(59, "Gambas con tomate natural y lechuga"));
products.add(generateProduct(58, "Gambas con crema de queso"));
products.add(generateProduct(57, "Lacón con salmorejo"));
products.add(generateProduct(56, "Vegetal: lechuga, atún, tomate natural y mayonesa"));
products.add(generateProduct(55, "Salmón ahumado con salmorejo"));
products.add(generateProduct(54, "Salmón ahumado con crema de queso"));
products.add(generateProduct(53, "Atún con crema de queso y tomate cherry"));
products.add(generateProduct(52, "Tortilla de patatas con pimiento verde"));
products.add(generateProduct(51, "Tortilla de patatas con salsa brava"));
products.add(generateProduct(50, "Tortilla de patatas con ali-oli"));
products.add(generateProduct(49, "Mousse de pato con queso brie"));
products.add(generateProduct(48, "Mousse de pato con cebolla crujiente"));
products.add(generateProduct(47, "Mousse de pato con confitura de frutos rojos"));
products.add(generateProduct(46, "Sobrasada con tortilla de patatas"));
products.add(generateProduct(45, "Lomo al ajillo con salsa mostaza y miel"));
products.add(generateProduct(44, "Lomo al ajillo con mayonesa"));
products.add(generateProduct(43, "Pollo asado con salsa rosa"));
products.add(generateProduct(42, "Pollo asado con salsa mostaza y miel"));
products.add(generateProduct(41, "Pollo asado con ali-oli"));
products.add(generateProduct(40, "Pollo asado con salsa césar"));
products.add(generateProduct(39, "El pichi: calamares y ali-oli"));
products.add(generateProduct(38, "Carrillada (carne con tomate) con queso ibérico"));
products.add(generateProduct(37, "Carrillada (carne con tomate) con pimiento verde"));
products.add(generateProduct(36, "Carne mechada con salsa brava"));
products.add(generateProduct(35, "Carne mechada con salsa mejicana"));
products.add(generateProduct(34, "Carne mechada con mojo picón"));
products.add(generateProduct(33, "Mixto: Lacón con queso brie"));
products.add(generateProduct(32, "Lacón con mozzarella y pimentón"));
products.add(generateProduct(31, "Lacón con queso azul"));
products.add(generateProduct(30, "Lacón a la gallega"));
products.add(generateProduct(29, "Chistorra a la piedra con queso ibérico"));
products.add(generateProduct(28, "Chistorra a la piedra con pimiento verde"));
products.add(generateProduct(27, "Chorizo a la sidra con guacamole y salsa mejicana"));
products.add(generateProduct(26, "Chorizo a la sidra con queso brie"));
products.add(generateProduct(25, "Chorizo a la sidra con tortilla de patatas"));
products.add(generateProduct(24, "Caña de lomo con queso ibérico"));
products.add(generateProduct(23, "Caña de lomo con tomate natural"));
products.add(generateProduct(22, "Jamón ibérico con salmorejo"));
products.add(generateProduct(21, "Jamón Iberico con tomate tatural"));
products.add(generateProduct(20, "Chocolate con leche y confitura de frutos rojos"));
products.add(generateProduct(19, "Chocolate con leche"));
products.add(generateProduct(18, "Dulce de leche"));
products.add(generateProduct(17, "Queso azul"));
products.add(generateProduct(16, "Queso brie"));
products.add(generateProduct(15, "Queso ibérico"));
products.add(generateProduct(14, "Atún en aceite"));
products.add(generateProduct(13, "Salmón ahumado"));
products.add(generateProduct(12, "Calamares"));
products.add(generateProduct(11, "Tortilla de patatas"));
products.add(generateProduct(10, "Mousse de pato"));
products.add(generateProduct(9, "Sobrasada ibérica"));
products.add(generateProduct(8, "Carrillada (carne con tomate)"));
products.add(generateProduct(7, "Carne mechada"));
products.add(generateProduct(6, "Bacon ahumado"));
products.add(generateProduct(5, "Lacón"));
products.add(generateProduct(4, "Chistorra a la piedra"));
products.add(generateProduct(3, "Chorizo a la sidra"));
products.add(generateProduct(2, "Caña de lomo"));
products.add(generateProduct(1, "Jamón ibérico con aceite de oliva"));
return products;
}
private static HashMap generateProduct(Integer id, String description) {
HashMap map = new HashMap();
map.put("montaditoId", String.valueOf(id));
map.put("name", description);
map.put("image", context.getResources().getIdentifier("drawable_" + (id < 10 ? "0" : "") + id, "drawable", "com.gs.montaditos"));
return map;
}
} | 100montaditos | trunk/src/com/gs/montaditos/Montaditos.java | Java | gpl3 | 9,400 |
package com.gs.montaditos;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
public class ListOrder extends Activity {
// Esto irá en la clase ListMontaditos cuando sepa inicializarla sin tener q
// cargarla previamente
public static HashMap<Integer, String> montaditos = new HashMap<Integer, String>();
SimpleAdapter adapter;
Boolean waiter;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
Intent i = getIntent();
waiter = i.getBooleanExtra("waiter", false);
}
/** Called when the activity is first created. */
@Override
protected void onStart() {
super.onStart();
if(!waiter){
setContentView(R.layout.order);
Button random = (Button) findViewById(R.id.random);
Button back = (Button) findViewById(R.id.back);
random.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), RandomOrder.class));
}
});
back.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
startActivity(new Intent(getApplicationContext(), mainActivity.class));
}
});
} else{
setContentView(R.layout.order_waiter);
}
ListView lv = (ListView) findViewById(R.id.listOrder);
setAdapter();
}
List<HashMap<String, String>> fillMaps;
private void setAdapter() {
ListView lv = (ListView) findViewById(R.id.listOrder);
// create the grid item mapping
String[] from = new String[] { "orderId", "montaditoId", "name",
"amount", "amount_string", "image" };
int[] to = new int[] { R.id.orderId, R.id.montaditoId, R.id.name,
R.id.amount, R.id.amount_string, R.id.image };
HashMap<Integer, Integer> items = Order.getAll();
// prepare the list of all records
fillMaps = new ArrayList<HashMap<String, String>>();
for(Integer id : items.keySet()){
HashMap<String, String> insert = Montaditos.get(id);
insert.put("amount", String.valueOf(items.get(id)));
insert.put("amount_string", "Cantidad: " + String.valueOf(items.get(id)));
fillMaps.add(insert);
}
if (fillMaps.size() == 0) {
TextView emptyText = (TextView)findViewById(R.id.empty_order);
emptyText.setVisibility(View.VISIBLE);
}
if(!waiter){
adapter = new SimpleAdapter(this, fillMaps,R.layout.orderitem, from, to);
setEvents(lv);
} else{
adapter = new SimpleAdapter(this, fillMaps,R.layout.order_item_waiter, from, to);
}
lv.setAdapter(adapter);
}
private void setEvents(ListView lv){
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View view,
int position, long id) {
final Integer pos = position;
final View v = view;
final Integer selected = new Integer(((TextView) view
.findViewById(R.id.montaditoId)).getText().toString());
AlertDialog.Builder dialog = new AlertDialog.Builder(
ListOrder.this);
dialog.setMessage(getString(R.string.list_text));
dialog.setTitle("");
dialog.setNegativeButton(R.string.remove,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
Order.remove(selected);
HashMap tmp = (HashMap)ListOrder.this.adapter.getItem(pos);
Integer a = new Integer(new Integer((String)tmp.get("amount").toString()) - 1);
if (a > 0) {
tmp.put("amount", a);
tmp.put("amount_string", "Cantidad: " + a);
} else {
Iterator it = fillMaps.iterator();
while (it.hasNext()) {
HashMap m = (HashMap) it.next();
TextView id = (TextView)v.findViewById(R.id.montaditoId);
if (m.get("montaditoId").equals(id.getText())) {
fillMaps.remove(m);
break;
}
}
}
ListOrder.this.adapter.notifyDataSetChanged();
ListOrder.this.adapter.notifyDataSetInvalidated();
}
});
dialog.setPositiveButton(R.string.add,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
Order.add(selected);
HashMap tmp = (HashMap)ListOrder.this.adapter.getItem(pos);
Integer a = new Integer(new Integer(tmp.get("amount").toString()) + 1);
tmp.put("amount", a);
tmp.put("amount_string", "Cantidad: " + a);
ListOrder.this.adapter.notifyDataSetChanged();
ListOrder.this.adapter.notifyDataSetInvalidated();
}
});
dialog.setNeutralButton(R.string.cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
}
});
dialog.show();
}
});
}
}
| 100montaditos | trunk/src/com/gs/montaditos/ListOrder.java | Java | gpl3 | 5,469 |
package com.gs.montaditos;
import java.util.HashMap;
public class Order {
private static HashMap<Integer, Integer> items = new HashMap<Integer, Integer>();
public static void reset() {
items = new HashMap<Integer, Integer>();
}
public static void add(int id) {
if(!items.containsKey(id)){
items.put(id, 1);
} else{
items.put(id, items.get(id)+1);
}
}
public static void remove(int id) {
if(items.containsKey(id)){
int amount = items.get(id);
if(amount > 1)
items.put(id, amount-1);
else
items.remove(id);
}
}
public static HashMap<Integer, Integer> getAll() {
return items;
}
}
| 100montaditos | trunk/src/com/gs/montaditos/Order.java | Java | gpl3 | 637 |
package com.gs.montaditos;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
public class mainActivity extends Activity {
SimpleAdapter adapter;
List<HashMap> fillMaps;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ListView lv= (ListView)findViewById(R.id.list);
// create the grid item mapping
String[] from = new String[] {"montaditoId", "name", "image"};
int[] to = new int[] { R.id.number, R.id.text, R.id.image};
// prepare the list of all records
Montaditos.init(getApplicationContext());
fillMaps = Montaditos.getAll();
// fill in the grid_item layout
adapter = new SimpleAdapter(this, (List<? extends Map<String, ?>>) fillMaps, R.layout.item, from, to);
lv.setAdapter(adapter);
ImageButton share = (ImageButton)findViewById(R.id.share);
share.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
ImageButton cart = (ImageButton)findViewById(R.id.cart);
cart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), ListOrder.class);
i.putExtra("waiter", false);
startActivity(i);
}
});
ImageButton waiter = (ImageButton)findViewById(R.id.waiter);
waiter.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
Intent i = new Intent(getApplicationContext(), ListOrder.class);
i.putExtra("waiter", true);
startActivity(i);
}
});
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
}
private void setEvents(ListView lv){
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> adapter, View view,
int position, long id) {
final Integer pos = position;
final View v = view;
final Integer selected = new Integer(((TextView) view
.findViewById(R.id.amount)).getText().toString());
AlertDialog.Builder dialog = new AlertDialog.Builder(
mainActivity.this);
dialog.setMessage(getString(R.string.list_text));
dialog.setTitle("");
dialog.setNegativeButton(R.string.remove,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
Order.remove(selected);
HashMap tmp = (HashMap)mainActivity.this.adapter.getItem(pos);
Integer a = new Integer(new Integer((String)tmp.get("amount")) - 1);
if (a > 0) {
tmp.put("amount", a);
} else {
Iterator it = fillMaps.iterator();
while (it.hasNext()) {
HashMap m = (HashMap) it.next();
TextView id = (TextView)v.findViewById(R.id.montaditoId);
if (m.get("montaditoId").equals(id.getText())) {
fillMaps.remove(m);
break;
}
}
}
mainActivity.this.adapter.notifyDataSetChanged();
mainActivity.this.adapter.notifyDataSetInvalidated();
}
});
dialog.setPositiveButton(R.string.add,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
Order.add(selected);
HashMap tmp = (HashMap)mainActivity.this.adapter.getItem(pos);
Integer a = new Integer(new Integer((String)tmp.get("amount")) + 1);
tmp.put("amount", a);
mainActivity.this.adapter.notifyDataSetChanged();
mainActivity.this.adapter.notifyDataSetInvalidated();
}
});
dialog.setNeutralButton(R.string.cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
}
});
dialog.show();
}
});
}
} | 100montaditos | trunk/src/com/gs/montaditos/mainActivity.java | Java | gpl3 | 4,646 |
package com.gs.montaditos;
import java.util.Random;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class RandomOrder extends Activity {
/** Called when the activity is first created. */
EditText personsField;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.random);
personsField = (EditText)findViewById(R.id.persons);
Button plus = (Button)findViewById(R.id.plus);
Button less = (Button)findViewById(R.id.less);
Button okay = (Button)findViewById(R.id.okay);
plus.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
int n = Integer.valueOf(personsField.getText().toString());
personsField.setText(String.valueOf(n+1));
}
});
less.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
int n = Integer.valueOf(personsField.getText().toString());
if(n>1){
personsField.setText(String.valueOf(n-1));
}
}
});
okay.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
Order.reset();
Montaditos.init(getApplicationContext());
Random randomGenerator = new Random();
int n = Integer.valueOf(personsField.getText().toString());
for (int idx = 1; idx <= n; ++idx){
int randomInt = randomGenerator.nextInt(100);
Order.add(randomInt);
}
startActivity(new Intent(getApplicationContext(), ListOrder.class));
Toast.makeText(getApplicationContext(), "Order Done", Toast.LENGTH_LONG).show();
}
});
}
}
| 100montaditos | trunk/src/com/gs/montaditos/RandomOrder.java | Java | gpl3 | 1,930 |
function [tdata tlabels edata elabels] = getTrainingData(data, labels, split=0.5)
tdata=tlabels=edata=elabels=[];
positives = data(labels(:,1)==1,:);
negatives = data(labels(:,1)==0,:);
size(positives)
size(negatives)
total=min(size(positives,1),size(negatives,1));
porder=randperm(size(positives,1));
norder=randperm(size(negatives,1));
split=floor(total*split);
for(i=1:split)
tdata=[tdata;negatives(norder(1,i),:);positives(porder(1,i),:)];
tlabels=[tlabels;0;1];
end;
for(i=split+1:total)
edata=[edata; negatives(norder(1,i),:); positives(porder(1,i),:)];
elabels=[elabels;0;1];
end;
end;
| 12l-mow | trunk/tools/getTrainingData.m | MATLAB | gpl3 | 697 |
function ans = uniqPerPatient(info)
patients = unique(info(:,5));
size(patients)
ans=zeros(1,size(info,2));
for(id=1:size(patients,1))
for(col=1:size(ans,2))
ans(id,col)= size(unique(info(find(info(:,5)==patients(id)),col)),1);
end;
end;
end;
| 12l-mow | trunk/tools/uniqPerPatient.m | MATLAB | gpl3 | 299 |
load("Features.txt");
load("Info.txt");
labels = Info(:,1);
labels(labels==-1)=0;
data = [Info(:,end-3:end), Features];
# find ccl, ccr, mlol, mlor
# Info(Info(:,6)==0 & Info(:,7)==1,:)
# LEFT = 1, MLO = 0
data_ccl = data(Info(:,6)==1 & Info(:,7)==0,:);
labels_ccl = labels(Info(:,6)==1 & Info(:,7)==0,:);
# LEFT = 0, MLO = 0
data_ccr = data(Info(:,6)==0 & Info(:,7)==0,:);
labels_ccr = labels(Info(:,6)==0 & Info(:,7)==0,:);
# LEFT = 1, MLO = 1
data_mlol = data(Info(:,6)==1 & Info(:,7)==0,:);
labels_mlol = labels(Info(:,6)==1 & Info(:,7)==0,:);
# LEFT = 0, MLO = 1
data_mlor = data(Info(:,6)==0 & Info(:,7)==1,:);
labels_mlor = labels(Info(:,6)==0 & Info(:,7)==1,:);
#Features(Info(:,7)==1,:)=[];
#Info(Info(:,7)==1,:)=[];
#malignant=Features(Info(:,1)==1,:);
#benign=Features(Info(:,1)==-1,:);
#addpath("~/Workspace/12l-rob-lab/lab5-6/src")
#td=[repmat(malignant(1:500,:),200,1);benign(1:100000,:)];
#tl=[ones(100000,1);zeros(100000,1)];
#ed=[malignant(501:end,:);benign(100001:end,:)];
#el=[ones(size(malignant(501:end,1)));zeros(size(benign(100001:end,1)))];
#net = train([],0.2,td,tl,0.1,20,[ed,el]);
#[td ed]=featureNormalize(td, ed)
| 12l-mow | trunk/tools/trials.m | MATLAB | gpl3 | 1,153 |
library(RWeka);
source("src/craftData.r");
source("src/unbindData.r");
selectors=list(breast="left", img.type="mlo");
trainData<-craftData(dataAll,selectors=selectors);
trainData<-unbindData(trainData, names(info), c("class"));
control=Weka_control("cost-matrix"=matrix(c(0,1000,1,0),ncol=2), W="weka.classifiers.functions.SMO");
classifier<-CostSensitiveClassifier(class~.,data=trainData, control=control);
print(evaluate_Weka_classifier(classifier, numFolds=10))
print("training a classifier for bagging");
control_bagging=Weka_control("cost-matrix"=matrix(c(0,100,1,0),ncol=2), W="weka.classifiers.meta.Bagging");
classifier_bagging<-CostSensitiveClassifier(class~.,data=trainData, control=control_bagging);
print(evaluate_Weka_classifier(classifier_bagging, numFolds=10))
| 12l-mow | trunk/src/costSensitiveLeftMLOScenario.r | R | gpl3 | 778 |
splitData <- function(info, features, trainShare=0.9, classAttr="class"){
if(trainShare>=1 || trainShare<=0){
print("Wrong trainShare");
return;
}
if(dim(info)[1]!=dim(features)[1]){
print("info and features dimension mismatch");
return;
}
crit=vector(mode="logical", length=dim(info)[1]);
if(is.null(classAttr)){
crit[sample(1:length(crit),length(crit)*trainShare,replace=FALSE)]=TRUE;
}else{
values=unique(info[classAttr])[,1];
for(i in 1 : length(values)){
matches = which(info[classAttr]==as.character(values[i]));
crit[sample(matches, length(matches)*trainShare, replace=FALSE)]=TRUE;
}
}
results<-list(
trainFeatures=features[crit,],
trainInfo=info[crit,],
testFeatures=features[!crit,],
testInfo=info[!crit,]);
results;
}
| 12l-mow | trunk/src/splitData.r | R | gpl3 | 769 |
cost<-1;
for(i in 1:7){
print(i);
control=Weka_control("cost-matrix"=matrix(c(0,cost,1,0),ncol=2), W="weka.classifiers.lazy.IBk");
classifier<-CostSensitiveClassifier(class~.,data=trainData, control=control);
results<-evaluate_Weka_classifier(classifier, numFolds=10)
confMx<-results$confusionMatrix;
IBk<-c(cost, ((confMx[1,1]+confMx[2,2])/sum(confMx)),
confMx["benign","malignant"]/sum(confMx["benign",]),
confMx["malignant","benign"]/sum(confMx["malignant",]),
confMx["malignant","malignant"]/sum(confMx["malignant",]),
confMx["benign","benign"]/sum(confMx["benign",]))
summary<-cbind(summary,IBk);
if(IBk[2]<=0.6){
break;
}
cost=cost*4;
}
print(summary);
cost<-1;
for(i in 1:7){
print(i);
control=Weka_control("cost-matrix"=matrix(c(0,cost,1,0),ncol=2), W="weka.classifiers.bayes.NaiveBayes");
classifier<-CostSensitiveClassifier(class~.,data=trainData, control=control);
results<-evaluate_Weka_classifier(classifier, numFolds=10)
confMx<-results$confusionMatrix;
NaiveBayes<-c(cost, ((confMx[1,1]+confMx[2,2])/sum(confMx)),
confMx["benign","malignant"]/sum(confMx["benign",]),
confMx["malignant","benign"]/sum(confMx["malignant",]),
confMx["malignant","malignant"]/sum(confMx["malignant",]),
confMx["benign","benign"]/sum(confMx["benign",]))
summary<-cbind(summary,NaiveBayes);
if(NaiveBayes[2]<=0.6){
break;
}
cost=cost*4;
}
print(summary);
| 12l-mow | trunk/src/scenarioRudiment.r | R | gpl3 | 1,395 |
# set working directory
setwd('C:/Users/luk/dev/R/12l-mow');
# read Info (from .arff) to info and Features (from .txt) to features
source('src/readData.r')
# bindData <- function(info, features, omitWhat=NULL);
#data<-bindData(info, features,
# c('img-finding-id', 'study-finding-id', 'study-id', 'img-id', 'study-id'));
| 12l-mow | trunk/src/tutorial.r | R | gpl3 | 338 |
#cutDownTo - parameter to equalise against (that is to cut data down to such a size, so that each value of qualiser occurs with the same frequency)
#selectors - list of key-value pairs denoting rows to extract from the table
# create it as crit<-list(); crit["breast"]="left"; crit["img-type"]="cc";
craftData <- function(dataFrame, cutDownTo=NULL, selectors=NULL){
resultDataFrame<-data.frame();
crit = vector(mode="logical", length=(dim(x=dataFrame)[1]));
crit[] = TRUE;
if(is.null(selectors)){
# print("selectors is null")
}else{
# print("selectors ain't null")
for(i in 1:length(selectors)){
crit=crit&dataFrame[names(selectors[i])]==selectors[i];
}
}
dataFrame<-dataFrame[crit,]
if(is.null(cutDownTo)){
#print("cutDownTo is null");
}else{
#print("cutDownTo ain't null");
supports=vector();
values=unique(dataFrame[cutDownTo]);
masks=matrix(ncol=dim(values)[1],nrow=dim(dataFrame)[1]);
for(i in 1:dim(values)[1]){
#print(dataFrame[cutDownTo])
logVec=(dataFrame[cutDownTo]==as.character(values[i,1]));
masks[,i]<-logVec;
supports[i]=(sum(masks[,i]));
# print(supports[i]);
}
minSup = min(supports);
# print(minSup);
for(i in 1:dim(values)[1]){
if(i==1){
resultDataFrame=dataFrame[masks[,i],][ sample( 1:supports[i], minSup, replace=FALSE), ];
#print("Some dimensions...")
#print(dim(resultDataFrame))
}else{
resultDataFrame=rbind(resultDataFrame,dataFrame[masks[,i],][ sample( 1:supports[i], minSup, replace=FALSE), ]);
}
}
dataFrame<-resultDataFrame;
}
dataFrame;
}
| 12l-mow | trunk/src/craftData.r | R | gpl3 | 1,899 |
library(RWeka);
print("Processing Info.txt... ")
info<-read.table("data/Info.txt");
names(info)=c("class","img-finding-id","study-finding-id","img-id","study-id","breast","img-type","X","Y","X-nipple","Y-nipple")
info["class"][info["class"]==-1]="benign";
info["class"][info["class"]==1]="malignant";
info["breast"][info["breast"]==1]="left";
info["breast"][info["breast"]==0]="right";
info["img-type"][info["img-type"]==1]="mlo";
info["img-type"][info["img-type"]==0]="cc";
info = transform(info, `class`=as.factor(`class`), `breast`=as.factor(`breast`), `img-type`=as.factor(`img-type`))
write.arff(x=info, file="data/info.arff");
print("Done. Ready to load files.")
| 12l-mow | trunk/src/prepData.r | R | gpl3 | 672 |
library(RWeka);
print("Reading data/info.arff... into info")
info<-read.arff("data/info.arff");
print("Done.")
print("Reading data/Features.txt... into features")
features<-read.table("data/Features.txt");
features<-scale(features);
print("Done.")
print("Merging Features and Info into one data")
dataAll<-cbind(info, features);
print("Done.")
| 12l-mow | trunk/src/readData.r | R | gpl3 | 348 |
cost<-16384;
for(i in 1:2){
print(i);
control=Weka_control("cost-matrix"=matrix(c(0,cost,1,0),ncol=2), W="weka.classifiers.meta.Bagging");
classifier<-CostSensitiveClassifier(class~.,data=trainData, control=control);
results<-evaluate_Weka_classifier(classifier, numFolds=10)
confMx<-results$confusionMatrix;
Bagging<-c(cost, ((confMx[1,1]+confMx[2,2])/sum(confMx)),
confMx["benign","malignant"]/sum(confMx["benign",]),
confMx["malignant","benign"]/sum(confMx["malignant",]),
confMx["malignant","malignant"]/sum(confMx["malignant",]),
confMx["benign","benign"]/sum(confMx["benign",]))
summary<-cbind(summary,Bagging);
if(Bagging[2]<=0.6 || Bagging[4]==0){
break;
}
cost=cost*2;
}
print(summary);
cost<-16384;
for(i in 1:2){
print(i);
control=Weka_control("cost-matrix"=matrix(c(0,cost,1,0),ncol=2), W="weka.classifiers.trees.J48");
classifier<-CostSensitiveClassifier(class~.,data=trainData, control=control);
results<-evaluate_Weka_classifier(classifier, numFolds=10)
confMx<-results$confusionMatrix;
J48<-c(cost, ((confMx[1,1]+confMx[2,2])/sum(confMx)),
confMx["benign","malignant"]/sum(confMx["benign",]),
confMx["malignant","benign"]/sum(confMx["malignant",]),
confMx["malignant","malignant"]/sum(confMx["malignant",]),
confMx["benign","benign"]/sum(confMx["benign",]))
summary<-cbind(summary,J48);
if(J48[2]<=0.6 || J48[4]==0){
break;
}
cost=cost*2;
}
print(summary);
| 12l-mow | trunk/src/scenarioWinningBody.r | R | gpl3 | 1,430 |
#unbinds all extra info except for data label
unbindData <-function(data, toRemove, toKeep=c()){
set<-data[,-which(names(data) %in% toRemove[-which(toRemove %in% toKeep)])];
set;
}
| 12l-mow | trunk/src/unbindData.r | R | gpl3 | 183 |
library(RWeka);
source("src/craftData.r");
source("src/unbindData.r");
summary<-matrix(nrow=6);
rownames(summary)<-c("Cost","Quality","False positives","False negatives","True positives","True negatives");
selectors=list(breast="right", img.type="cc");
trainData<-craftData(dataAll,selectors=selectors);
trainData<-unbindData(trainData,names(info),c("class"));
#source("src/scenarioBody.r");
| 12l-mow | trunk/src/scenarioRCC.r | R | gpl3 | 393 |
print(summary);
cost=cost*4;
for(i in 1:3){
print(i);
control=Weka_control("cost-matrix"=matrix(c(0,cost,1,0),ncol=2), W="weka.classifiers.functions.SimpleLogistic");
classifier<-CostSensitiveClassifier(class~.,data=trainData, control=control);
results<-evaluate_Weka_classifier(classifier, numFolds=10)
confMx<-results$confusionMatrix;
Logistic<-c(cost, ((confMx[1,1]+confMx[2,2])/sum(confMx)),
confMx["benign","malignant"]/sum(confMx["benign",]),
confMx["malignant","benign"]/sum(confMx["malignant",]),
confMx["malignant","malignant"]/sum(confMx["malignant",]),
confMx["benign","benign"]/sum(confMx["benign",]))
summary<-cbind(summary,Logistic);
if(Logistic[2]<=0.6 || Logistic[4]==0){
break;
}
cost=cost*4;
}
print(summary);
| 12l-mow | trunk/src/scenarioRRC.finish.r | R | gpl3 | 752 |
#simple scenario:
# 1. read data
# 2. take only left breasts and cc images and cut the set to size of malignant cases
# 3. train k-NN classifier
# 4. perform a 10-fold evaluation
library(RWeka);
source("src/craftData.r");
source("src/readData.r");
featuresNorm = features + abs(min(features)) + 1
result=chisq.test(x = featuresNorm, y = info[, "class"]); | 12l-mow | trunk/src/chiSquare.r | R | gpl3 | 354 |
library(RWeka);
source("src/craftData.r");
source("src/unbindData.r");
summary<-matrix(nrow=6);
rownames(summary)<-c("Cost","Quality","False positives","False negatives","True positives","True negatives");
trainData<-unbindData(dataAll,names(info),c("class"));
#source("src/scenarioBody.r");
| 12l-mow | trunk/src/scenarioAll.r | R | gpl3 | 294 |
library(RWeka);
source("src/craftData.r");
source("src/unbindData.r");
summary<-matrix(nrow=6);
rownames(summary)<-c("Cost","Quality","False positives","False negatives","True positives","True negatives");
selectors=list(breast="right", img.type="mlo");
trainData<-craftData(dataAll,selectors=selectors);
trainData<-unbindData(trainData,names(info),c("class"));
#source("src/scenarioBody.r");
| 12l-mow | trunk/src/scenarioMLOR.r | R | gpl3 | 394 |
cost<-1;
for(i in 1:7){
print(i);
control=Weka_control("cost-matrix"=matrix(c(0,cost,1,0),ncol=2), W="weka.classifiers.functions.SMO");
classifier<-CostSensitiveClassifier(class~.,data=trainData, control=control);
results<-evaluate_Weka_classifier(classifier, numFolds=10)
confMx<-results$confusionMatrix;
SMO<-c(cost, ((confMx[1,1]+confMx[2,2])/sum(confMx)),
confMx["benign","malignant"]/sum(confMx["benign",]),
confMx["malignant","benign"]/sum(confMx["malignant",]),
confMx["malignant","malignant"]/sum(confMx["malignant",]),
confMx["benign","benign"]/sum(confMx["benign",]))
if(i==dim(summary)[2]){
summary[,i]=SMO;
}else{
summary<-cbind(summary,SMO);
if(SMO[2]<=0.6 || SMO[4]==0){
break;
}
}
cost=cost*4;
}
print(summary);
cost<-1;
for(i in 1:7){
print(i);
control=Weka_control("cost-matrix"=matrix(c(0,cost,1,0),ncol=2), W="weka.classifiers.meta.Bagging");
classifier<-CostSensitiveClassifier(class~.,data=trainData, control=control);
results<-evaluate_Weka_classifier(classifier, numFolds=10)
confMx<-results$confusionMatrix;
Bagging<-c(cost, ((confMx[1,1]+confMx[2,2])/sum(confMx)),
confMx["benign","malignant"]/sum(confMx["benign",]),
confMx["malignant","benign"]/sum(confMx["malignant",]),
confMx["malignant","malignant"]/sum(confMx["malignant",]),
confMx["benign","benign"]/sum(confMx["benign",]))
summary<-cbind(summary,Bagging);
if(Bagging[2]<=0.6 || Bagging[4]==0){
break;
}
cost=cost*4;
}
print(summary);
cost<-1;
for(i in 1:7){
print(i);
control=Weka_control("cost-matrix"=matrix(c(0,cost,1,0),ncol=2), W="weka.classifiers.trees.J48");
classifier<-CostSensitiveClassifier(class~.,data=trainData, control=control);
results<-evaluate_Weka_classifier(classifier, numFolds=10)
confMx<-results$confusionMatrix;
J48<-c(cost, ((confMx[1,1]+confMx[2,2])/sum(confMx)),
confMx["benign","malignant"]/sum(confMx["benign",]),
confMx["malignant","benign"]/sum(confMx["malignant",]),
confMx["malignant","malignant"]/sum(confMx["malignant",]),
confMx["benign","benign"]/sum(confMx["benign",]))
summary<-cbind(summary,J48);
if(J48[2]<=0.6 || J48[4]==0){
break;
}
cost=cost*4;
}
print(summary);
cost<-1;
for(i in 1:7){
print(i);
control=Weka_control("cost-matrix"=matrix(c(0,cost,1,0),ncol=2), W="weka.classifiers.functions.SimpleLogistic");
classifier<-CostSensitiveClassifier(class~.,data=trainData, control=control);
results<-evaluate_Weka_classifier(classifier, numFolds=10)
confMx<-results$confusionMatrix;
Logistic<-c(cost, ((confMx[1,1]+confMx[2,2])/sum(confMx)),
confMx["benign","malignant"]/sum(confMx["benign",]),
confMx["malignant","benign"]/sum(confMx["malignant",]),
confMx["malignant","malignant"]/sum(confMx["malignant",]),
confMx["benign","benign"]/sum(confMx["benign",]))
summary<-cbind(summary,Logistic);
if(Logistic[2]<=0.6 || Logistic[4]==0){
break;
}
cost=cost*4;
}
print(summary);
| 12l-mow | trunk/src/scenarioBody.r | R | gpl3 | 2,914 |
library(RWeka);
source("src/craftData.r");
source("src/unbindData.r");
summary<-matrix(nrow=6);
rownames(summary)<-c("Cost","Quality","False positives","False negatives","True positives","True negatives");
selectors=list(breast="left", img.type="cc");
trainData<-craftData(dataAll,selectors=selectors);
trainData<-unbindData(trainData,names(info),c("class"));
#source("src/scenarioBody.r");
| 12l-mow | trunk/src/scenarioLCC.r | R | gpl3 | 393 |
#simple scenario:
# 1. read data
# 2. take only left breasts and cc images and cut the set to size of malignant cases
# 3. train k-NN classifier
# 4. perform a 10-fold evaluation
library(RWeka);
source("src/craftData.r");
source("src/unbindData.r");
#function definitions and libraries loaded.
#make sure readData has been executed
selectors=list(breast="left", img.type="cc");
trainData<-craftData(dataAll,"class",selectors);
trainData<-unbindData(trainData,names(info),c("class"));
classifier<-IBk(class~., data=trainData);
evaluate_Weka_classifier(classifier, numFolds=10)
results<-table(probToClass(predict(classifier, newdata=trainData, type=c("probability")), 0.99),trainData$class);
stats<-list(score=((results[1,1]+results[2,2])/sum(results)),
fp=results["benign","malignant"],fn=results["malignant","benign"])
print(stats);
| 12l-mow | trunk/src/simpleScenario.r | R | gpl3 | 835 |
bindData <- function(info, features, omitWhat=NULL) {
resultDataFrame<-data.frame();
crit = vector(mode="logical", length=(length(names(info))));
crit[]=TRUE
if(!is.null(omitWhat)) {
for(i in 1:length(names(info))) {
crit[i]<-!(names(info)[i] %in% omitWhat);
}
}
resultDataFrame=cbind(info[,crit], features);
} | 12l-mow | trunk/src/bindData.r | R | gpl3 | 351 |
library(RWeka);
source("src/craftData.r");
source("src/unbindData.r");
summary<-matrix(nrow=6);
rownames(summary)<-c("FN cost","Quality","False positives","False negatives","True positives","True negatives");
selectors=list(breast="left", img.type="cc");
trainData<-craftData(dataAll,"class",selectors);
trainData<-unbindData(trainData,names(info),c("class"));
source("src/scenarioBody.r");
| 12l-mow | trunk/src/simpleCostSensitiveScenario.r | R | gpl3 | 392 |
library(RWeka);
source("src/craftData.r");
source("src/unbindData.r");
summary<-matrix(nrow=6);
rownames(summary)<-c("Cost","Quality","False positives","False negatives","True positives","True negatives");
selectors=list(breast="left", img.type="mlo");
trainData<-craftData(dataAll,selectors=selectors);
trainData<-unbindData(trainData,names(info),c("class"));
#source("src/scenarioBody.r");
| 12l-mow | trunk/src/scenarioMLOL.r | R | gpl3 | 393 |
probToClass <- function(probabilities, threshold){
result<-vector(length=dim(probabilities)[1]);
for(i in 1:dim(probabilities)[1]){
if(probabilities[i,1]>threshold){
result[i]=colnames(probabilities)[1];
}else{
result[i]=colnames(probabilities)[2];
}
}
result;
}
| 12l-mow | trunk/src/probToClass.r | R | gpl3 | 279 |
\documentclass{article}
\usepackage{polski}
\usepackage[utf8]{inputenc}
\usepackage{listings}
\usepackage[usenames,dvipsnames]{color} % For colors and names
\usepackage{hyperref}
\usepackage{tabularx}
\usepackage{pgfplots}
\hyphenpenalty=1115000
\title{\textbf{Metody Odkrywania Wiedzy 12L} \\ Temat analityczny: Detekcja wczesnych stadiów raka piersi \\ Dokumentacja projektu} % Title
\author{Tomasz \textsc{Bawej} \\ Łukasz \textsc{Trzaska}} % Author name
\definecolor{mygrey}{gray}{.96} % Light Grey
\lstset{language=Verilog, tabsize=3, backgroundcolor=\color{mygrey}, basicstyle=\small, commentstyle=\color{BrickRed}}
\lstset{
language=[ISO]C++, % choose the language of the code ("language=Verilog" is popular as well)
tabsize=3, % sets the size of the tabs in spaces (1 Tab is replaced with 3 spaces)
basicstyle=\scriptsize, % the size of the fonts that are used for the code
numbers=left, % where to put the line-numbers
numberstyle=\scriptsize, % the size of the fonts that are used for the line-numbers
stepnumber=2, % the step between two line-numbers. If it's 1 each line will be numbered
numbersep=5pt, % how far the line-numbers are from the code
backgroundcolor=\color{mygrey}, % choose the background color. You must add \usepackage{color}
%showspaces=false, % show spaces adding particular underscores
%showstringspaces=false, % underline spaces within strings
%showtabs=false, % show tabs within strings adding particular underscores
frame=single, % adds a frame around the code
tabsize=3, % sets default tabsize to 2 spaces
captionpos=b, % sets the caption-position to bottom
breaklines=true, % sets automatic line breaking
breakatwhitespace=false, % sets if automatic breaks should only happen at whitespace
%escapeinside={\%*}{*)}, % if you want to add a comment within your code
commentstyle=\color{BrickRed} % sets the comment style
}
\begin{document}
\maketitle % Insert the title, author and date
\setlength\parindent{0pt} % Removes all indentation from paragraphs
% \renewcommand{\labelenumi}{\alph{enumi}.}
\newenvironment{packed_enum}{
\begin{enumerate}
\setlength{\itemsep}{1pt}
\setlength{\parskip}{0pt}
\setlength{\parsep}{0pt}
}{\end{enumerate}}
\section{Opis zadania}
Niniejszy dokument dotyczy analitycznego zadania klasyfikacji przeprowadzonej dla danych umieszczonych na stronie \url{http://www.sigkdd.org/kddcup/index.php?section=2008&method=info}
Zgodnie z wymaganiami zamieszczonymi na stronie przedmiotu, zakres projektu winien obejmować następujące czynności:
\begin{itemize}
\item przygotowanie danych,
\item statystyczny opis danych,
\item transformację danych (np. dyskretyzację, kodowanie atrybutów dyskretnych, standaryzację),
\item selekcja atrybutów,
\item strojenie parametrów algorytmów,
\item tworzenie modeli,
\item wnikliwa ocena jakości modeli,
\end{itemize}
Ponadto klasyfikacyjna natura zadania pociąga za sobą konieczność przeprowadzenia następujących czynności:
\begin{itemize}
\item ustalenia atrybutu dyskretnego reprezentującego pojęcie docelowe,
\item określenia zakresu przygotowania danych (np. przetworzenia do odpowiedniej postaci tabelarycznej, modyfikacji typów/zbiorów wartości atrybutów, eliminacji/naprawy defektów danych, modyfikacji rozkładu kategorii, losowania podzbiorów danych),
\item określenia zakresu i technik statystycznego opisu danych (np. charakterystyki rozkładu wartości atrybytów, detekcji wartości odstających, detekcji zależności między atrybutami),
\item wskazania możliwości zdefiniowania nowych atrybutów,
\item ustalenia kryteriów lub algorytmu selekcji atrybutów,
\item wyboru algorytmów klasyfikacji,
\item wskazania parametrów algorytmów klasyfikacji wymagających strojenia,
\item ustalenia procedur i kryteriów oceny jakości modeli (z uwzględnieniem rozkładu oraz, tam gdzie to uzasadnione, kosztów pomyłek).
\end{itemize}
Opis danych treningowych oraz czynności wynikających bezpośrednio z ich charakteru stanowi temat odrędbnego rozdziału: \ref{sec:data}.
\section{Cel klasyfikacji}
\begin{itemize}
\item Przyporządkować próbkę powstałą ze zdjęcia piersi do jednej z klas: zmiana łagodna (\textit{ang. benign}) / zmiana złośliwa (\textit{ang. malignant}).
\item Trenując klasyfikatory szczególną uwagę zwrócić na minimalizację błędu drugiego rodzaju (ang. \textit{false negative}), aby przypadki złośliwe nie uległy przeoczeniu.
\end{itemize}
\section{Opis dostępnych danych}
\label{sec:data}
Analizowane w ramach projektu dane pochodzą z konkursu \textit{KDD Cup 2008}, którego problematyka dotyczyła wczesnej detekcji raka piersi. Same dane reprezentują zbiór przetworzonych obszarów zdjęć rentgenowskich wykonanych dla grupy 118 chorych i 1594 zdrowych pacjentów. Zbór treningowy zawiera łącznie 102294 próbki (określane też zamiennie mianem obszarów lub kandydatów), z których jedynie niewielka część przedstawia zmiany złośliwe. Pewne uproszczenie zadania stanowi fakt, iż zgromadzone dane ograniczają się do przypadków, w których na jednego pacjenta przypada nie więcej niż jedna zmiana nowotworowa.
\\
Dane podzielone zostały na zbiór cech oraz informacji o każdej próbce. Zestaw cech liczy 117 atrybutów będących liczbowymi wynikami działania pewnych algorytmów przetwarzania obrazów. Informacja o próbce zawiera 11 atrybutów, które opisane została w Tabeli 1.
\begin{table}[h]\footnotesize
\caption{Atrybuty opsujące próbkę}
\begin{tabularx}{\textwidth}{ |X|X| }
\hline
\textbf{Atrybut} & \textbf{Opis} \\
\hline
\textit{Ground truth label} & 1 dla zmian złośliwych, -1 dla łagodnych.\\
\textit{Image-Finding-ID} & Unikalny identyfikator zmiany złośliwej, 0 dla zmian łagodnych. Wartość pozwala rozpoznać tę samą zmianę widoczną na różnych zdjęciach tego samego typu.\\
\textit{Study-Finding-ID} & Unikalny identyfikator zmiany pozwalający rozpoznać tę samą zmianę na różnych zdjęciach, bez względu na typ zdjęcia i złośliwość samej zmiany.\\
\hline
\textit{Image-ID} & Unikalny identifikator obrazu na podstawie którego wygenerowano próbkę.\\
\textit{Study-ID} & Unikalny identyfikator pacjenta. Dla każdego pacjenta przechowywane są 4 zdjęcia, na ogół ze wszystkich 4. generowane są próbki.\\
\textit{LeftBreast} & 1 jeśli obraz lewej piersi, 0 w przeciwnym przypadku.\\
\textit{MLO} & 1 jeśli obraz MLO, 0 w przeciwnym przypadku. \\
\textit{Candidate-X} & Współrzędna X zmiany.\\
\textit{Candidate-Y} & Współrzędna Y zmiany.\\
\textit{Nipple-X} & Współrzędna X sutka.\\
\textit{Nipple-Y} & Współrzędna Y sutka.\\
\hline
\end{tabularx}
\end{table}
\pagebreak
\paragraph*{Dane użyteczne.}
Udostępnione przez organizatorów konkursu dane podzielone zostały na zbiory: testowy oraz treningowy, przy czym ze względu na formułę konkursu zbiór testowy został pozbawiony pierwszych 3 elementów opisu (klasa próbki oraz identyfikatory zmiany). Tym samym zbiór danych użytecznych z punktu widzenia zadania ogranicza się do dostępnego zbioru treningowego. Wartość pierwszej kolumny ze zbioru informacji stanowi jednocześnie wartość pojęcia docelowego (atrybut \textit{Ground truth label}), podczas gdy kolumny \textit{MLO}, \textit{Candidate-X}, \textit{Candidate-Y}, \textit{Nipple-X}, \textit{Nipple-Y} prawdopodobnie nie mają wartości informacyjnej.
\begin{table}[h]\footnotesize
\caption{Statystyki danych dla pojedynczego pacjenta}
\begin{tabularx}{\textwidth}{ |X|X|X|X|X|X|X|X| }
\cline{1-8}
\textit{Image-ID} & \textit{Patient-ID} & \textit{LBreast} & \textit{MLO} &
\textit{Cand-X} & \textit{Cand-Y} & \textit{Nipple-X} & \textit{Nipple-Y} \\
\cline{1-8}
\multicolumn{8}{|c|}{Liczba unikalnych wartości} \\
\cline{1-8}
6848 & 1712 & 2 & 2 & 3273 & 3407 & 1449 & 1172 \\
\cline{1-8}
\multicolumn{8}{|c|}{Średnia liczba unikalnych wartości w przeliczeniu na pacjenta} \\
\cline{1-8}
4 & 1 & 2 & 2 & 57.44 & 57.34 & 3.99 & 3.99 \\
\cline{1-8}
\multicolumn{8}{|c|}{Minimalna liczba unikalnych wartości w przeliczeniu na pacjenta} \\
\cline{1-8}
4 & 1 & 2 & 2 & 302 & 307 & 4 & 4 \\
\cline{1-8}
\multicolumn{8}{|c|}{Maksymalna liczba unikalnych wartości w przeliczeniu na pacjenta} \\
\cline{1-8}
4 & 1 & 2 & 2 & 6 & 6 & 3 & 3 \\
\cline{1-8}
\end{tabularx}
\end{table}
\pagebreak
W Tabeli 2. zestawiono statystykę danych, która potwierdza, iż dla każdego pacjenta wykonano 4 zdjęcia. Następnie na ich podstawie utworzono pewną liczbę próbek (różną dla różnych pacjentów). Dodatkowym mankamentem, lub - operując nomenklaturą konkursową - wyzwaniem, jest także fakt, iż aż 101671 próbek reprezentuje przypadki łagodne (pierwsza klasa pojęcia docelowego), a tylko 623 reprezentuje przypadki złośliwe (druga klasa pojęcia docelowego) tzn. stosunek klas to w przybliżeniu $6/1000$.
\section{Rozwiązanie}
\paragraph*{Opis koncepcyjny.} Nie mogąc weryfikować rozwiązania na pełnoprawnym zbiorze testowym, użyto walidacji krzyżowej 10 stopniowej, przybliżając tym samym oczekiwaną jakość klasyfikatorów. Użyto klasyfikatora \textit{czułego an koszt pomyłek}, aby spróbować zrównoważyć znaczne dysproporcje liczności klas. Próbki podzielono na 4 grupy ze względu na typ zdjęcia, na których to grupach osobno trenowano klasyfikatory:
\begin{itemize}
\item lewa pierś i zdjęcie CC
\item lewa pierś i zdjęcie MLO
\item prawa pierś i zdjęcie CC
\item prawa pierś i zdjęcie MLO
\end{itemize}
Większość prezentowanych wyników dotyczy zatem czterech osobnych klasyfikatorów. Próba wytrenowania klasyfikatorów dla pełnego zbioru nierozróżnialnych ze względu na typ zdjęcia próbek nie rokowała lepiej pod względem wyników, a ostatecznie skazana została na porażkę ze względu na dużo dłuższy czas trenowania i szacowania jakości. O ile problem ewaluacji jakości można by usiłować łagodzić wprowadzając do zbioru cech atrybuty reprezentujące typ zdjęcia, o tyle problem czasochłonności rozwiązać mogło jedynie przycięcie zbioru treningowego do dwóch równolicznych ze względu na klasę próbki grup. Podejście to obarczone było jednak dużym błędem klasyfikacji dla pełnego zbioru danych (utrata zdolności generalizacji w stosunku do negatywnych próbek).
\paragraph*{Implementacja.}
Model zaimplementowano w języku R z użyciem biblioteki \textit{RWeka}. Procesowi trenowania i oceny jakości dla powyższych 4 typów próbek poddano następujące klasyfikatory:
\begin{itemize}
\item \textbf{SMO}: wektor maszyn podpierających trenowany algorytmem sekwencyjnej minimalizacji John'a C. Platt'a (biblioteka Weka: \textit{weka.classifiers.functions.SMO)}
\item \textbf{Bagging}: klasyfikator agregowany \\ (biblioteka Weka: \textit{weka.classifiers.meta.Bagging)}
\item \textbf{J48}: drzewo decyzyjne C4.5 \\ (biblioteka Weka: \textit{weka.classifiers.trees.J48)}
\item \textbf{SimpleLogistic}: logistyczna regresja liniowa \\ (biblioteka Weka: \textit{weka.classifiers.functions.SimpleLogistic)}
\item \textbf{KNN}: klasyfikator \textit{najbliższych sąsiadów} \\ (biblioteka Weka: \textit{weka.classifiers.functions.IBk)}.
\end{itemize}
Klasyfikator \textit{najbliższych sąsiadów} przetestowano kilkukrotnie i z uwagi na jego niską skuteczność oraz dużą czasochłonność zrezygnowano z prezentacji podsumowania jego osiągów.
\paragraph*{Iteracyjne strojenie algorytmów.}
Korzystając z dekoratora klasyfikatorów uwrażliwiającego je na koszty pomyłek (Weka: \textit{weka.classifiers.meta.CostSensitiveClassifier}), minimalizowany jest błąd drugiego rodzaju (ang. \textit{false negative}). W kolejnych iteracjach podawana jest macierz kosztów pomyłek, nakładająca większą karę za pomyłkę przydziału próbki \textit{malignant} do klasy \textit{benign}. Podsumowanie właściwości klasyfikatora strojonego w ten właśnie sposób zaprezentowano na Rysunku \ref{pic:najlep-rezultaty-cc} w rozdziale \ref{sec:wyniki}. Jako przykład obrano klasyfikator \textit{Bagging}, który w ostatniej iteracji uzyskał stosunkowo satysfakcjonujące wyniki.
\paragraph*{Kluczowe pliki} (funkcje i sekwencje czynności) zaimplementowane w R:
\begin{itemize}
\item \textbf{prepData.r} wczytuje plik źródłowy informacyjny \textit{info.txt} i przekształca go na format \textit{.arff}
\item \textbf{readData.r} wczytuje pliki źródłowe z danymi \textit{features.txt} oraz informacyjny \textit{info.txt} i scala je do jednej ramki danych \textit{dataAll}
\item \textbf{unbindData.r} z zadanej ramki danych eliminuje zadane kolumny
\item \textbf{craftData.r} przycina dane do konkretnej kategorii np. tylko lewa pierś
\item \textbf{scenarioBody.r} dla zadanej ramki danych \textit{trainData}, która była przygotowana wcześniej dla konkretnego typu danych, wykonuje trening i agreguje wyniki dla poszczególnych klasyfikatorów.\\
Wszystkie pliki źródłowe znajdują się w katalogu projektu \textit{/src}.
\end{itemize}
\paragraph*{Ocena jakości modeli}
Ewaluacji modeli dokonywano za pomocą metody walidacji krzyżowej 10 stopniowej. Do tego celu zastosowano dostępną w bibliotece Weka funkcję: \textit{evaluate\_Weka\_classifier}. W rezultacie jej działania otrzymano następujące wskaźniki: \textit{Quality}, \textit{False positive}, \textit{False}, \textit{True positive}, \textit{True negative}.
\section{Wyniki}
\label{sec:wyniki}
\paragraph*{Pliki w projekcie.} Wszystkie uzyskane rezultaty odnaleźć można w plikach projektowych w katalogu \textit{results}. Pliki z rozszerzeniem \textit{.txt} zawierają rezultaty czytelne dla człowieka, natomiast pliki z rozszerzeniem \textit{.table} czytelne dla funkcji \textit{read.table} środowiska R.\\
Jak zaprezentowano na Rysunku \ref{fig:postep-klasyf-bagging} postęp w strojeniu klasyfikatora Bagging pod kątem minimalizacji błędu drugiego rodzaju \textit{false-negative} towarzyszył spadkowi jakości klasyfikacji i wzrostowi błędu \textit{false-negative}, ale również poprawie wskaźnika \textit{true-positive}.
\begin{center}
\begin{figure}[h]
\pgfplotsset{width=12cm, compat=1.4}
\begin{tikzpicture}
\begin{axis}[
ybar,
enlargelimits=0.4,
legend style={at={(0.5,-0.25)},
anchor=north,legend columns=-1},
ylabel={wskaźniki},
symbolic x coords={SMO, Bagging, J48, Logistic},
xtick=data,
nodes near coords,
nodes near coords align={vertical}
]
\addplot coordinates {(SMO,0.603) (Bagging,0.952) (J48,0.930) (Logistic,0.947) };
\addplot coordinates {(SMO,0.038) (Bagging,0.31) (J48,0.438) (Logistic,0.289) };
\legend{accuracy, false-negative}
\end{axis}
\end{tikzpicture}
\caption{Najlepsze rezultaty osiągnięte dla próbek typu CC piersi lewej}
\label{pic:najlep-rezultaty-cc}
\end{figure}
\end{center}
Jak zaprezentowano na Rysunku \ref{fig:postep-klasyf-bagging} postęp w strojeniu klasyfikatora Bagging pod kątem minimalizacji błędu drugiego rodzaju \textit{false-negative} towarzyszył spadkowi jakości klasyfikacji i wzrostowi błędu \textit{false-negative}, ale również poprawie wskaźnika \textit{true-positive}.
\begin{center}
\begin{figure}[h]
\pgfplotsset{width=12cm, compat=1.4}
\begin{tikzpicture}
\begin{axis} [
ylabel={wskaźniki},
xlabel={koszt pomy\l{}ki},
]
\addplot+[color=yellow,mark=*]
coordinates
{(1, 0.99) (4, 0.995) (16, 0.995)
(64, 0.994) (256, 0.994) (1024, 0.986) (4096, 0.951)
};
\addlegendentry{accuracy}
\addplot+[color=green,mark=+]
coordinates{
(1, 0.81) (4, 0.66) (16, 0.62)
(64, 0.60) (256, 0.59) (1024, 0.49) (4096, 0.314)
};
\addlegendentry{false-negative rate}
\addplot+[color=red,mark=+]
coordinates{
(1, 0.37) (4, 0.0) (16, 0.0) (64, 0.0)
(256, 0.002) (1024, 0.01) (4096, 0.004)
};
\addlegendentry{false-positive rate}
\addplot+[blue,mark=*]
coordinates{
(1, 0.18) (4, 0.33) (16, 0.37) (64, 0.40)
(256, 0.40) (1024, 0.50) (4096, 0.65)
};
\addlegendentry{true-positive rate}
\end{axis}
\end{tikzpicture}
\caption{Postęp w strojeniu klasyfikatora Bagging pod kątem minimalizacji błędu drugiego rodzaju
\label{fig:postep-klasyf-bagging}
\textit{false-negative}}
\end{figure}
\end{center}
\section{Podsumowanie}
Tak uzyskane wyniki, jak i przebieg działań projektowych ciężko określić mianem sukcsesu, głównie ze względu na brak możliwośći jednoznacznej weryfikacji wyników naszych starań. O ile z konkursowego punktu widzenia operownie na zdegenrowanych danych (brak danych testowych, ogromna dysporoporcja klas) może się wydawać ciekawe, o tyle w przypadku analitycznego projektu staje się niemal pozbawione sensu, gdyż wszelkie wyniki przeprowadzonych analiz są co najwyżej estymacjami jakości klasyfikatorów. Pomimo wytworzenia odpowiedniego kodu, nie zdecydowalifśmy się jednak na podział dostępnych danych na zbior treningowy i testowy, ze względu na brak możliwości uzyskania reprezentatywnego zbioru testowego bez dalszej degenracji danych treningowych.
Po stronie pozytywów zapisać należy jednak zapoznanie się ze środowiskiem R, częścią pakietu RWeka i biblioteki Weka. Niedociągnięcia można by wyliczać dużo dłużej, jednak wielowymiarowość problemu (wybór typu klasyfikatora, parametrów tegoż, podzbiorów danych i atrybutów) uniemożliwiła równomierną analizę każdego możliwego podejścia w sensownych ramach czasowych.
\end{document}
| 12l-mow | trunk/doc/report.tex | TeX | gpl3 | 17,619 |
\relax
\ifx\hyper@anchor\@undefined
\global \let \oldcontentsline\contentsline
\gdef \contentsline#1#2#3#4{\oldcontentsline{#1}{#2}{#3}}
\global \let \oldnewlabel\newlabel
\gdef \newlabel#1#2{\newlabelxx{#1}#2}
\gdef \newlabelxx#1#2#3#4#5#6{\oldnewlabel{#1}{{#2}{#3}}}
\AtEndDocument{\let \contentsline\oldcontentsline
\let \newlabel\oldnewlabel}
\else
\global \let \hyper@last\relax
\fi
\@writefile{toc}{\contentsline {section}{\numberline {1}Opis zadania}{1}{section.1}}
\@writefile{toc}{\contentsline {section}{\numberline {2}Opis dost\IeC {\k e}pnych danych}{2}{section.2}}
\newlabel{sec:data}{{2}{2}{Opis dostępnych danych\relax }{section.2}{}}
\@writefile{lot}{\contentsline {table}{\numberline {1}{\ignorespaces Atrybuty opsuj\IeC {\k a}ce pr\IeC {\'o}bk\IeC {\k e}}}{3}{table.1}}
\@writefile{toc}{\contentsline {section}{\numberline {3}Rozwi\IeC {\k a}zanie}{3}{section.3}}
\@writefile{lot}{\contentsline {table}{\numberline {2}{\ignorespaces Charakterystyka danych... (jakie\IeC {\'s} procenty)}}{4}{table.2}}
\@writefile{toc}{\contentsline {section}{\numberline {4}Podsumowanie}{4}{section.4}}
\@writefile{toc}{\contentsline {section}{\numberline {5}Stara cz\IeC {\k e}\IeC {\'s}\IeC {\'c} dokumentacji - do przemia\IeC {\l }u}{4}{section.5}}
\@writefile{toc}{\contentsline {subsubsection}{\numberline {5.0.1}Dane treningowe - przyk\IeC {\l }ady etykietowane}{5}{subsubsection.5.0.1}}
\@writefile{toc}{\contentsline {subsubsection}{\numberline {5.0.2}Dane testowe}{5}{subsubsection.5.0.2}}
| 12l-mow | trunk/doc/report.aux | TeX | gpl3 | 1,504 |
function [Pd_patient_wise,FA_per_image,AUC,Pd,Pfa]=get_ROC_KDD(p, Y, patient_ID, FA_low, FA_high);
% [Pd_patient_wise,FA_per_image,AUC,Pd,Pfa]=get_ROC_KDD(p, Y, patient_ID, FP_low, FP_high);
% Compute: Malignant Patient detection rate <vs> False-alarmss-per-image
% FROC curves for KDD Cup 2008
% INPUTS: (the first 3 inputs have to be of the same size)
% p has predictions which are real numbers (ie not just in [0,1])
% Larger p indicates higher confidence that label Y is positive.
% Y denotes positive class labels elements by +1.
% All other values (eg 0, -1) in Y are considered -ve
% patient_ID has to be numbers, unique for each patient
% [FA_low,FA_high] is the region in which the area under FROC (AUC) has to be
% computed [default is [0.2,0.3]]
% OUTPUTS:
% Pd_patient_wise,FA_per_image: per-patient sensitivity and FA per image
% (for the Official KDD Cup FROC)
% AUC is the area under the Official FROC (see above) in the FA range
% [FA_low, FA_high]
% Pd, Pfa: Probability of detection and probability of false alarm for
% traditional ROC (not used for KDD Cup evaluation)
%------------------------------------------------------------
% Error checking:
%------------------------------------------------------------
if (rows(p)==1)
p=p';
end;
if (rows(Y)==1)
Y=Y';
end;
if (rows(patient_ID)==1)
Patient_ID=Patient_ID';
end;
if (rows(p)~=rows(Y))
error('p and Y are of different lengths');
end
if (rows(p)~=rows(patient_ID))
error('p and patient_ID are of different lengths');
end
if ~exist('FA_low','var')
FA_low=0.2;
end
if ~exist('FA_high','var')
FA_high=0.3;
end
%------------------------------------------------------------
% Preparatory code:
%------------------------------------------------------------
N_samples=length(Y); N_ROC_points=N_samples+1;
N_patients=length(unique(patient_ID));
Positive_patients=unique( patient_ID(find(Y==1)) );
N_positive_patients=length( Positive_patients );
N_images=4*N_patients;
Tot_positives=length(find(Y==1));
Tot_negatives=N_samples-Tot_positives;
numOfFA=zeros(N_ROC_points,1);
numOfD=numOfFA; numOfDetPatients=numOfFA;
numOfFA(1,1)=0; numOfD(1,1)=0; numOfDetPatients(1,1)=0;
Patients_detected_till_now=[];
%------------------------------------------------------------
% Sorting makes the algo work much faster
%------------------------------------------------------------
dat=sortrows([p, patient_ID, Y]);
dat=flipud(dat);
%get the indexes where each "uniquely scored" batch ends
[u_roc_scores, batch_idx]=unique(dat(:,1));
N_unique=size(u_roc_scores, 1);
temp=flipud([u_roc_scores, batch_idx]);
u_roc_scores=temp(:,1);
batch_idx=temp(:,2);
batch_idx=[0;batch_idx];
%------------------------------------------------------------
% Since the ROC curve is computed over patients and it depends on the
% ordering of the candidates with the same score, compute the average
% over the permutation of the orderings
% Thanks to Peter Gehler for pointing this out.
%------------------------------------------------------------
maxIter=50;
numOfFA_total=zeros(N_ROC_points,maxIter);
numOfDetPatients_total=numOfFA_total;
numOfD_total=numOfFA_total;
for i=1:maxIter
numOfFA=zeros(N_ROC_points,1);
numOfD=numOfFA; numOfDetPatients=numOfFA;
numOfFA(1,1)=0; numOfD(1,1)=0; numOfDetPatients(1,1)=0;
Patients_detected_till_now=[];
%first, permute the ordering in every "batch"
new_dat=zeros(size(dat));
for k=2:N_unique+1
data_batch=dat(batch_idx(k-1)+1:batch_idx(k),:);
n=size(data_batch,1);
idx=randperm(n);
data_batch=data_batch(idx,:);
new_dat(batch_idx(k-1)+1:batch_idx(k),:)=data_batch;
end
patient_ID=new_dat(:,2); Y=new_dat(:,3);
%------------------------------------------------------------
% Now, just sweep through the data once to get all points in ROC
%------------------------------------------------------------
for j = 2 : N_ROC_points
if (Y(j-1,1)==1)
% Another detection, but FP remains the same
numOfD(j,1)=numOfD(j-1,1)+1;
numOfFA(j,1)=numOfFA(j-1);
Patients_detected_till_now=union(Patients_detected_till_now, patient_ID(j-1,1) );
numOfDetPatients(j,1)=size(Patients_detected_till_now, 2);
else
% Patients_detected_till_now remains the same;
numOfD(j,1)=numOfD(j-1,1);
numOfDetPatients(j,1)=numOfDetPatients(j-1,1);
numOfFA(j,1)=numOfFA(j-1)+1;
end
end
numOfD_total(:,i)=numOfD;
numOfDetPatients_total(:,i)=numOfDetPatients;
numOfFA_total(:,i)=numOfFA;
end
%------------------------------------------------------------
% And normalize the final results in the form needed
%------------------------------------------------------------
numOfFA=mean(numOfFA_total,2);
numOfD=mean(numOfD_total,2);
numOfDetPatients=mean(numOfDetPatients_total,2);
Pfa = numOfFA / Tot_negatives;
Pd = numOfD / Tot_positives;
FA_per_image = numOfFA / N_images;
Pd_patient_wise = numOfDetPatients / N_positive_patients;
index1=min(find(FA_per_image>=FA_low));
index2=max(find(FA_per_image<=FA_high));
if FA_per_image(end)<FA_high
warning('AUC is incorrect because input parameter FA_high was higher than the maximum FA_per_image from the other parameters');
end
AUC=Pd_patient_wise(index1:(index2-1))' * (FA_per_image((index1+1):index2) - FA_per_image(index1:(index2-1)) );
return;
function n=rows(x);
n=size(x,1);
return;
%
%
| 12l-mow | trunk/lib/get_ROC_KDD.m | MATLAB | gpl3 | 5,515 |
#ifndef JSON_H
#define JSON_H
#include "block_allocator.h"
enum json_type
{
JSON_NULL,
JSON_OBJECT,
JSON_ARRAY,
JSON_STRING,
JSON_INT,
JSON_FLOAT,
JSON_BOOL,
};
struct json_value
{
json_value *parent;
json_value *next_sibling;
json_value *first_child;
json_value *last_child;
char *name;
union
{
char *string_value;
int int_value;
float float_value;
};
json_type type;
};
json_value *json_parse(char *source, char **error_pos, char **error_desc, int *error_line, block_allocator *allocator);
#endif
| 0705030223wfp-123123123123123123123123 | json.h | C | mit | 565 |
cmake_minimum_required(VERSION 2.8)
project(vjson)
add_executable(vjson_test block_allocator.cpp json.cpp main.cpp)
| 0705030223wfp-123123123123123123123123 | CMakeLists.txt | CMake | mit | 119 |
#include <vector>
#include <stdio.h>
#include "json.h"
void populate_sources(const char *filter, std::vector<std::vector<char> > &sources)
{
char filename[256];
for (int i = 1; i < 64; ++i)
{
sprintf(filename, filter, i);
FILE *fp = fopen(filename, "rb");
if (fp)
{
fseek(fp, 0, SEEK_END);
int size = ftell(fp);
fseek(fp, 0, SEEK_SET);
std::vector<char> buffer(size + 1);
fread (&buffer[0], 1, size, fp);
fclose(fp);
sources.push_back(buffer);
}
else
{
break;
}
}
printf("Loaded %d json files\n", sources.size());
}
#define IDENT(n) for (int i = 0; i < n; ++i) printf(" ")
void print(json_value *value, int ident = 0)
{
IDENT(ident);
if (value->name) printf("\"%s\" = ", value->name);
switch(value->type)
{
case JSON_NULL:
printf("null\n");
break;
case JSON_OBJECT:
case JSON_ARRAY:
printf(value->type == JSON_OBJECT ? "{\n" : "[\n");
for (json_value *it = value->first_child; it; it = it->next_sibling)
{
print(it, ident + 1);
}
IDENT(ident);
printf(value->type == JSON_OBJECT ? "}\n" : "]\n");
break;
case JSON_STRING:
printf("\"%s\"\n", value->string_value);
break;
case JSON_INT:
printf("%d\n", value->int_value);
break;
case JSON_FLOAT:
printf("%f\n", value->float_value);
break;
case JSON_BOOL:
printf(value->int_value ? "true\n" : "false\n");
break;
}
}
bool parse(char *source)
{
char *errorPos = 0;
char *errorDesc = 0;
int errorLine = 0;
block_allocator allocator(1 << 10);
json_value *root = json_parse(source, &errorPos, &errorDesc, &errorLine, &allocator);
if (root)
{
print(root);
return true;
}
printf("Error at line %d: %s\n%s\n\n", errorLine, errorDesc, errorPos);
return false;
}
int main(int argc, char **argv)
{
// Fail
printf("===FAIL===\n\n");
std::vector<std::vector<char> > sources;
populate_sources("test/fail%d.json", sources);
int passed = 0;
for (size_t i = 0; i < sources.size(); ++i)
{
printf("Parsing %d\n", i + 1);
if (parse(&sources[i][0]))
{
++passed;
}
}
printf("Passed %d from %d tests\n", passed, sources.size());
// Pass
sources.clear();
printf("\n===PASS===\n\n");
populate_sources("test/pass%d.json", sources);
passed = 0;
for (size_t i = 0; i < sources.size(); ++i)
{
printf("Parsing %d\n", i + 1);
if (parse(&sources[i][0]))
{
++passed;
}
}
printf("Passed %d from %d tests\n", passed, sources.size());
return 0;
}
| 0705030223wfp-123123123123123123123123 | main.cpp | C++ | mit | 2,537 |
#include <memory.h>
#include "json.h"
// true if character represent a digit
#define IS_DIGIT(c) (c >= '0' && c <= '9')
// convert string to integer
char *atoi(char *first, char *last, int *out)
{
int sign = 1;
if (first != last)
{
if (*first == '-')
{
sign = -1;
++first;
}
else if (*first == '+')
{
++first;
}
}
int result = 0;
for (; first != last && IS_DIGIT(*first); ++first)
{
result = 10 * result + (*first - '0');
}
*out = result * sign;
return first;
}
// convert hexadecimal string to unsigned integer
char *hatoui(char *first, char *last, unsigned int *out)
{
unsigned int result = 0;
for (; first != last; ++first)
{
int digit;
if (IS_DIGIT(*first))
{
digit = *first - '0';
}
else if (*first >= 'a' && *first <= 'f')
{
digit = *first - 'a' + 10;
}
else if (*first >= 'A' && *first <= 'F')
{
digit = *first - 'A' + 10;
}
else
{
break;
}
result = 16 * result + digit;
}
*out = result;
return first;
}
// convert string to floating point
char *atof(char *first, char *last, float *out)
{
// sign
float sign = 1;
if (first != last)
{
if (*first == '-')
{
sign = -1;
++first;
}
else if (*first == '+')
{
++first;
}
}
// integer part
float result = 0;
for (; first != last && IS_DIGIT(*first); ++first)
{
result = 10 * result + (*first - '0');
}
// fraction part
if (first != last && *first == '.')
{
++first;
float inv_base = 0.1f;
for (; first != last && IS_DIGIT(*first); ++first)
{
result += (*first - '0') * inv_base;
inv_base *= 0.1f;
}
}
// result w\o exponent
result *= sign;
// exponent
bool exponent_negative = false;
int exponent = 0;
if (first != last && (*first == 'e' || *first == 'E'))
{
++first;
if (*first == '-')
{
exponent_negative = true;
++first;
}
else if (*first == '+')
{
++first;
}
for (; first != last && IS_DIGIT(*first); ++first)
{
exponent = 10 * exponent + (*first - '0');
}
}
if (exponent)
{
float power_of_ten = 10;
for (; exponent > 1; exponent--)
{
power_of_ten *= 10;
}
if (exponent_negative)
{
result /= power_of_ten;
}
else
{
result *= power_of_ten;
}
}
*out = result;
return first;
}
json_value *json_alloc(block_allocator *allocator)
{
json_value *value = (json_value *)allocator->malloc(sizeof(json_value));
memset(value, 0, sizeof(json_value));
return value;
}
void json_append(json_value *lhs, json_value *rhs)
{
rhs->parent = lhs;
if (lhs->last_child)
{
lhs->last_child = lhs->last_child->next_sibling = rhs;
}
else
{
lhs->first_child = lhs->last_child = rhs;
}
}
#define ERROR(it, desc)\
*error_pos = it;\
*error_desc = (char *)desc;\
*error_line = 1 - escaped_newlines;\
for (char *c = it; c != source; --c)\
if (*c == '\n') ++*error_line;\
return 0
#define CHECK_TOP() if (!top) {ERROR(it, "Unexpected character");}
json_value *json_parse(char *source, char **error_pos, char **error_desc, int *error_line, block_allocator *allocator)
{
json_value *root = 0;
json_value *top = 0;
char *name = 0;
char *it = source;
int escaped_newlines = 0;
while (*it)
{
switch (*it)
{
case '{':
case '[':
{
// create new value
json_value *object = json_alloc(allocator);
// name
object->name = name;
name = 0;
// type
object->type = (*it == '{') ? JSON_OBJECT : JSON_ARRAY;
// skip open character
++it;
// set top and root
if (top)
{
json_append(top, object);
}
else if (!root)
{
root = object;
}
else
{
ERROR(it, "Second root. Only one root allowed");
}
top = object;
}
break;
case '}':
case ']':
{
if (!top || top->type != ((*it == '}') ? JSON_OBJECT : JSON_ARRAY))
{
ERROR(it, "Mismatch closing brace/bracket");
}
// skip close character
++it;
// set top
top = top->parent;
}
break;
case ':':
if (!top || top->type != JSON_OBJECT)
{
ERROR(it, "Unexpected character");
}
++it;
break;
case ',':
CHECK_TOP();
++it;
break;
case '"':
{
CHECK_TOP();
// skip '"' character
++it;
char *first = it;
char *last = it;
while (*it)
{
if ((unsigned char)*it < '\x20')
{
ERROR(first, "Control characters not allowed in strings");
}
else if (*it == '\\')
{
switch (it[1])
{
case '"':
*last = '"';
break;
case '\\':
*last = '\\';
break;
case '/':
*last = '/';
break;
case 'b':
*last = '\b';
break;
case 'f':
*last = '\f';
break;
case 'n':
*last = '\n';
++escaped_newlines;
break;
case 'r':
*last = '\r';
break;
case 't':
*last = '\t';
break;
case 'u':
{
unsigned int codepoint;
if (hatoui(it + 2, it + 6, &codepoint) != it + 6)
{
ERROR(it, "Bad unicode codepoint");
}
if (codepoint <= 0x7F)
{
*last = (char)codepoint;
}
else if (codepoint <= 0x7FF)
{
*last++ = (char)(0xC0 | (codepoint >> 6));
*last = (char)(0x80 | (codepoint & 0x3F));
}
else if (codepoint <= 0xFFFF)
{
*last++ = (char)(0xE0 | (codepoint >> 12));
*last++ = (char)(0x80 | ((codepoint >> 6) & 0x3F));
*last = (char)(0x80 | (codepoint & 0x3F));
}
}
it += 4;
break;
default:
ERROR(first, "Unrecognized escape sequence");
}
++last;
it += 2;
}
else if (*it == '"')
{
*last = 0;
++it;
break;
}
else
{
*last++ = *it++;
}
}
if (!name && top->type == JSON_OBJECT)
{
// field name in object
name = first;
}
else
{
// new string value
json_value *object = json_alloc(allocator);
object->name = name;
name = 0;
object->type = JSON_STRING;
object->string_value = first;
json_append(top, object);
}
}
break;
case 'n':
case 't':
case 'f':
{
CHECK_TOP();
// new null/bool value
json_value *object = json_alloc(allocator);
object->name = name;
name = 0;
// null
if (it[0] == 'n' && it[1] == 'u' && it[2] == 'l' && it[3] == 'l')
{
object->type = JSON_NULL;
it += 4;
}
// true
else if (it[0] == 't' && it[1] == 'r' && it[2] == 'u' && it[3] == 'e')
{
object->type = JSON_BOOL;
object->int_value = 1;
it += 4;
}
// false
else if (it[0] == 'f' && it[1] == 'a' && it[2] == 'l' && it[3] == 's' && it[4] == 'e')
{
object->type = JSON_BOOL;
object->int_value = 0;
it += 5;
}
else
{
ERROR(it, "Unknown identifier");
}
json_append(top, object);
}
break;
case '-':
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
{
CHECK_TOP();
// new number value
json_value *object = json_alloc(allocator);
object->name = name;
name = 0;
object->type = JSON_INT;
char *first = it;
while (*it != '\x20' && *it != '\x9' && *it != '\xD' && *it != '\xA' && *it != ',' && *it != ']' && *it != '}')
{
if (*it == '.' || *it == 'e' || *it == 'E')
{
object->type = JSON_FLOAT;
}
++it;
}
if (object->type == JSON_INT && atoi(first, it, &object->int_value) != it)
{
ERROR(first, "Bad integer number");
}
if (object->type == JSON_FLOAT && atof(first, it, &object->float_value) != it)
{
ERROR(first, "Bad float number");
}
json_append(top, object);
}
break;
default:
ERROR(it, "Unexpected character");
}
// skip white space
while (*it == '\x20' || *it == '\x9' || *it == '\xD' || *it == '\xA')
{
++it;
}
}
if (top)
{
ERROR(it, "Not all objects/arrays have been properly closed");
}
return root;
}
| 0705030223wfp-123123123123123123123123 | json.cpp | C++ | mit | 8,555 |
#ifndef BLOCK_ALLOCATOR_H
#define BLOCK_ALLOCATOR_H
class block_allocator
{
private:
struct block
{
size_t size;
size_t used;
char *buffer;
block *next;
};
block *m_head;
size_t m_blocksize;
block_allocator(const block_allocator &);
block_allocator &operator=(block_allocator &);
public:
block_allocator(size_t blocksize);
~block_allocator();
// exchange contents with rhs
void swap(block_allocator &rhs);
// allocate memory
void *malloc(size_t size);
// free all allocated blocks
void free();
};
#endif
| 0705030223wfp-123123123123123123123123 | block_allocator.h | C++ | mit | 570 |
#include <memory.h>
#include <algorithm>
#include "block_allocator.h"
block_allocator::block_allocator(size_t blocksize): m_head(0), m_blocksize(blocksize)
{
}
block_allocator::~block_allocator()
{
while (m_head)
{
block *temp = m_head->next;
::free(m_head);
m_head = temp;
}
}
void block_allocator::swap(block_allocator &rhs)
{
std::swap(m_blocksize, rhs.m_blocksize);
std::swap(m_head, rhs.m_head);
}
void *block_allocator::malloc(size_t size)
{
if ((m_head && m_head->used + size > m_head->size) || !m_head)
{
// calc needed size for allocation
size_t alloc_size = std::max(sizeof(block) + size, m_blocksize);
// create new block
char *buffer = (char *)::malloc(alloc_size);
block *b = reinterpret_cast<block *>(buffer);
b->size = alloc_size;
b->used = sizeof(block);
b->buffer = buffer;
b->next = m_head;
m_head = b;
}
void *ptr = m_head->buffer + m_head->used;
m_head->used += size;
return ptr;
}
void block_allocator::free()
{
block_allocator(0).swap(*this);
}
| 0705030223wfp-123123123123123123123123 | block_allocator.cpp | C++ | mit | 1,062 |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* 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.android.heightmapprofiler;
import java.io.IOException;
import java.io.InputStream;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.opengl.GLSurfaceView;
import android.opengl.GLU;
import android.opengl.GLUtils;
import android.util.Log;
/**
* An OpenGL ES renderer based on the GLSurfaceView rendering framework. This
* class is responsible for drawing a list of renderables to the screen every
* frame. It also manages loading of textures and (when VBOs are used) the
* allocation of vertex buffer objects.
*/
public class SimpleGLRenderer implements GLSurfaceView.Renderer {
// Texture filtering modes.
public final static int FILTER_NEAREST_NEIGHBOR = 0;
public final static int FILTER_BILINEAR = 1;
public final static int FILTER_TRILINEAR = 2;
// Specifies the format our textures should be converted to upon load.
private static BitmapFactory.Options sBitmapOptions
= new BitmapFactory.Options();
// Pre-allocated arrays to use at runtime so that allocation during the
// test can be avoided.
private int[] mTextureNameWorkspace;
// A reference to the application context.
private Context mContext;
private LandTileMap mTiles;
private int mTextureResource;
private int mTextureResource2;
private int mTextureId2;
private Vector3 mCameraPosition = new Vector3();
private Vector3 mLookAtPosition = new Vector3();
private Object mCameraLock = new Object();
private boolean mCameraDirty;
private NativeRenderer mNativeRenderer;
// Determines the use of vertex buffer objects.
private boolean mUseHardwareBuffers;
private boolean mUseTextureLods = false;
private boolean mUseHardwareMips = false;
boolean mColorTextureLods = false;
private int mTextureFilter = FILTER_BILINEAR;
private int mMaxTextureSize = 0;
public SimpleGLRenderer(Context context) {
// Pre-allocate and store these objects so we can use them at runtime
// without allocating memory mid-frame.
mTextureNameWorkspace = new int[1];
// Set our bitmaps to 16-bit, 565 format.
sBitmapOptions.inPreferredConfig = Bitmap.Config.RGB_565;
mContext = context;
mUseHardwareBuffers = true;
}
public void setTiles(LandTileMap tiles, int textureResource, int textureResource2) {
mTextureResource = textureResource;
mTextureResource2 = textureResource2;
mTiles = tiles;
}
/** Draws the landscape. */
public void onDrawFrame(GL10 gl) {
ProfileRecorder.sSingleton.stop(ProfileRecorder.PROFILE_FRAME);
ProfileRecorder.sSingleton.start(ProfileRecorder.PROFILE_FRAME);
if (mTiles != null) {
// Clear the screen. Note that a real application probably would only clear the depth buffer
// (or maybe not even that).
if (mNativeRenderer == null) {
gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
}
// If the camera has moved since the last frame, rebuild our projection matrix.
if (mCameraDirty){
synchronized (mCameraLock) {
if (mNativeRenderer != null) {
mNativeRenderer.setCamera(mCameraPosition, mLookAtPosition);
} else {
gl.glMatrixMode(GL10.GL_MODELVIEW);
gl.glLoadIdentity();
GLU.gluLookAt(gl, mCameraPosition.x, mCameraPosition.y, mCameraPosition.z,
mLookAtPosition.x, mLookAtPosition.y, mLookAtPosition.z,
0.0f, 1.0f, 0.0f);
}
mCameraDirty = false;
}
}
ProfileRecorder.sSingleton.start(ProfileRecorder.PROFILE_DRAW);
// Draw the landscape.
mTiles.draw(gl, mCameraPosition);
ProfileRecorder.sSingleton.stop(ProfileRecorder.PROFILE_DRAW);
}
ProfileRecorder.sSingleton.endFrame();
}
/* Called when the size of the window changes. */
public void onSurfaceChanged(GL10 gl, int width, int height) {
gl.glViewport(0, 0, width, height);
/*
* Set our projection matrix. This doesn't have to be done each time we
* draw, but usually a new projection needs to be set when the viewport
* is resized.
*/
float ratio = (float)width / height;
gl.glMatrixMode(GL10.GL_PROJECTION);
gl.glLoadIdentity();
GLU.gluPerspective(gl, 60.0f, ratio, 2.0f, 3000.0f);
mCameraDirty = true;
}
public void setCameraPosition(float x, float y, float z) {
synchronized (mCameraLock) {
mCameraPosition.set(x, y, z);
mCameraDirty = true;
}
}
public void setCameraLookAtPosition(float x, float y, float z) {
synchronized (mCameraLock) {
mLookAtPosition.set(x, y, z);
mCameraDirty = true;
}
}
public void setUseHardwareBuffers(boolean vbos) {
mUseHardwareBuffers = vbos;
}
/**
* Called to turn on Levels of Detail option for rendering textures
*
* @param mUseTextureLods
*/
public void setUseTextureLods(boolean useTextureLods, boolean useHardwareMips) {
mUseTextureLods = useTextureLods;
mUseHardwareMips = useHardwareMips;
}
/**
* Turns on/off color the LOD bitmap textures based on their distance from view.
* This feature is useful since it helps visualize the LOD being used while viewing the scene.
*
* @param colorTextureLods
*/
public void setColorTextureLods(boolean colorTextureLods) {
this.mColorTextureLods = colorTextureLods;
}
public void setNativeRenderer(NativeRenderer render) {
mNativeRenderer = render;
}
public void setMaxTextureSize(int maxTextureSize) {
mMaxTextureSize = maxTextureSize;
}
public void setTextureFilter(int filter) {
mTextureFilter = filter;
}
/**
* Called whenever the surface is created. This happens at startup, and
* may be called again at runtime if the device context is lost (the screen
* goes to sleep, etc). This function must fill the contents of vram with
* texture data and (when using VBOs) hardware vertex arrays.
*/
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
int[] textureNames = null;
/*
* Some one-time OpenGL initialization can be made here probably based
* on features of this particular context
*/
gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_FASTEST);
gl.glClearColor(0.5f, 0.5f, 0.5f, 1);
gl.glDisable(GL10.GL_DITHER);
gl.glDisable(GL10.GL_CULL_FACE);
gl.glShadeModel(GL10.GL_SMOOTH);
gl.glEnable(GL10.GL_DEPTH_TEST);
gl.glEnable(GL10.GL_TEXTURE_2D);
// set up some fog.
gl.glEnable(GL10.GL_FOG);
gl.glFogf(GL10.GL_FOG_MODE, GL10.GL_LINEAR);
float fogColor[] = { 0.5f, 0.5f, 0.5f, 1.0f };
gl.glFogfv(GL10.GL_FOG_COLOR, fogColor, 0);
gl.glFogf(GL10.GL_FOG_DENSITY, 0.15f);
gl.glFogf(GL10.GL_FOG_START, 800.0f);
gl.glFogf(GL10.GL_FOG_END, 2048.0f);
gl.glHint(GL10.GL_FOG_HINT, GL10.GL_FASTEST);
gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
// load textures and buffers here
if (mUseHardwareBuffers && mTiles != null) {
mTiles.generateHardwareBuffers(gl);
}
if (mTextureResource != 0) {
textureNames = loadBitmap( mContext, gl, mTextureResource, mUseTextureLods, mUseHardwareMips );
}
if (mTextureResource2 != 0) {
mTextureId2 = loadBitmap(mContext, gl, mTextureResource2);
}
mTiles.setTextures(textureNames, mTextureId2);
}
/**
* Loads a bitmap into OpenGL and sets up the common parameters for
* 2D texture maps.
*/
protected int loadBitmap(Context context, GL10 gl, int resourceId) {
int textureName = -1;
InputStream is = context.getResources().openRawResource(resourceId);
Bitmap bitmap;
try {
bitmap = BitmapFactory.decodeStream(is, null, sBitmapOptions);
} finally {
try {
is.close();
} catch (IOException e) {
// Ignore.
}
}
if (mMaxTextureSize > 0 && Math.max(bitmap.getWidth(), bitmap.getHeight()) != mMaxTextureSize) {
// we're assuming all our textures are square. sue me.
Bitmap tempBitmap = Bitmap.createScaledBitmap( bitmap, mMaxTextureSize, mMaxTextureSize, false );
bitmap.recycle();
bitmap = tempBitmap;
}
textureName = loadBitmapIntoOpenGL(context, gl, bitmap, false);
bitmap.recycle();
return textureName;
}
/**
* Loads a bitmap into OpenGL and sets up the common parameters for
* 2D texture maps.
*
* @param context
* @param resourceId
* @param numLevelsOfDetail number of detail textures to generate
*
* @return a array of OpenGL texture names corresponding to the different levels of detail textures
*/
protected int[] loadBitmap(Context context, GL10 gl, int resourceId, boolean generateMips, boolean useHardwareMips ) {
InputStream is = context.getResources().openRawResource(resourceId);
Bitmap bitmap;
try {
bitmap = BitmapFactory.decodeStream(is, null, sBitmapOptions);
} finally {
try {
is.close();
} catch (IOException e) {
// Ignore.
}
}
if (mMaxTextureSize > 0 && Math.max(bitmap.getWidth(), bitmap.getHeight()) != mMaxTextureSize) {
// we're assuming all our textures are square. sue me.
Bitmap tempBitmap = Bitmap.createScaledBitmap( bitmap, mMaxTextureSize, mMaxTextureSize, false );
bitmap.recycle();
bitmap = tempBitmap;
}
final int minSide = Math.min(bitmap.getWidth(), bitmap.getHeight());
int numLevelsOfDetail = 1;
if (generateMips) {
for (int side = minSide / 2; side > 0; side /= 2) {
numLevelsOfDetail++;
}
}
int textureNames[];
if (generateMips && !useHardwareMips) {
textureNames = new int[numLevelsOfDetail];
} else {
textureNames = new int[1];
}
textureNames[0] = loadBitmapIntoOpenGL(context, gl, bitmap, useHardwareMips);
// Scale down base bitmap by powers of two to create lower resolution textures
for( int i = 1; i < numLevelsOfDetail; ++i ) {
int scale = (int)Math.pow(2, i);
int dstWidth = bitmap.getWidth() / scale;
int dstHeight = bitmap.getHeight() / scale;
Bitmap tempBitmap = Bitmap.createScaledBitmap( bitmap, dstWidth, dstHeight, false );
// Set each LOD level to a different color to help visualization
if( mColorTextureLods ) {
int color = 0;
switch( (int)(i % 4) ) {
case 1:
color = Color.RED;
break;
case 2:
color = Color.YELLOW;
break;
case 3:
color = Color.BLUE;
break;
}
tempBitmap.eraseColor( color );
}
if (!useHardwareMips) {
textureNames[i] = loadBitmapIntoOpenGL( context, gl, tempBitmap, false);
} else {
addHardwareMipmap(gl, textureNames[0], tempBitmap, i );
}
tempBitmap.recycle();
}
bitmap.recycle();
return textureNames;
}
protected void addHardwareMipmap(GL10 gl, int textureName, Bitmap bitmap, int level) {
gl.glBindTexture(GL10.GL_TEXTURE_2D, textureName);
GLUtils.texImage2D(GL10.GL_TEXTURE_2D, level, bitmap, 0);
}
/**
* Loads a bitmap into OpenGL and sets up the common parameters for
* 2D texture maps.
*
* @return OpenGL texture entry id
*/
protected int loadBitmapIntoOpenGL(Context context, GL10 gl, Bitmap bitmap, boolean useMipmaps) {
int textureName = -1;
if (context != null && gl != null) {
gl.glGenTextures(1, mTextureNameWorkspace, 0);
textureName = mTextureNameWorkspace[0];
gl.glBindTexture(GL10.GL_TEXTURE_2D, textureName);
if (useMipmaps) {
if (mTextureFilter == FILTER_TRILINEAR) {
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_LINEAR_MIPMAP_LINEAR);
} else {
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_LINEAR_MIPMAP_NEAREST);
}
} else {
if (mTextureFilter == FILTER_NEAREST_NEIGHBOR) {
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST);
} else {
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_LINEAR);
}
}
if (mTextureFilter == FILTER_NEAREST_NEIGHBOR) {
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_NEAREST);
} else {
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR);
}
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_CLAMP_TO_EDGE);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_CLAMP_TO_EDGE);
gl.glTexEnvf(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE, GL10.GL_MODULATE);
GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0);
int error = gl.glGetError();
if (error != GL10.GL_NO_ERROR) {
Log.e("SimpleGLRenderer", "Texture Load GLError: " + error);
}
}
return textureName;
}
}
| 1219806112-wangyao | HeightMapProfiler/src/com/android/heightmapprofiler/SimpleGLRenderer.java | Java | asf20 | 14,372 |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* 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.android.heightmapprofiler;
import android.os.SystemClock;
// Very simple game runtime. Implements basic movement and collision detection with the landscape.
public class Game implements Runnable {
private Vector3 mCameraPosition = new Vector3(100.0f, 128.0f, 400.0f);
private Vector3 mTargetPosition = new Vector3(350.0f, 128.0f, 650.0f);
private Vector3 mWorkVector = new Vector3();
private float mCameraXZAngle;
private float mCameraYAngle;
private float mCameraLookAtDistance = (float)Math.sqrt(mTargetPosition.distance2(mCameraPosition));
private boolean mCameraDirty = true;
private boolean mRunning = true;
private boolean mPaused = false;
private Object mPauseLock = new Object();
private LandTileMap mTileMap;
private final static float CAMERA_ORBIT_SPEED = 0.3f;
private final static float CAMERA_MOVE_SPEED = 5.0f;
private final static float VIEWER_HEIGHT = 15.0f;
private SimpleGLRenderer mSimpleRenderer;
public Game(SimpleGLRenderer renderer, LandTileMap tiles) {
mSimpleRenderer = renderer;
mTileMap = tiles;
}
public void run() {
while (mRunning) {
ProfileRecorder.sSingleton.start(ProfileRecorder.PROFILE_SIM);
long startTime = SystemClock.uptimeMillis();
if (mCameraDirty) {
// snap the camera to the floor
float height = mTileMap.getHeight(mCameraPosition.x, mCameraPosition.z);
mCameraPosition.y = height + VIEWER_HEIGHT;
updateCamera();
}
long endTime = SystemClock.uptimeMillis();
ProfileRecorder.sSingleton.stop(ProfileRecorder.PROFILE_SIM);
if (endTime - startTime < 16) {
// we're running too fast! sleep for a bit to let the render thread do some work.
try {
Thread.sleep(16 - (endTime - startTime));
} catch (InterruptedException e) {
// Interruptions are not a big deal here.
}
}
synchronized(mPauseLock) {
if (mPaused) {
while (mPaused) {
try {
mPauseLock.wait();
} catch (InterruptedException e) {
// OK if this is interrupted.
}
}
}
}
}
}
synchronized private void updateCamera() {
mWorkVector.set((float)Math.cos(mCameraXZAngle), (float)Math.sin(mCameraYAngle), (float)Math.sin(mCameraXZAngle));
mWorkVector.multiply(mCameraLookAtDistance);
mWorkVector.add(mCameraPosition);
mTargetPosition.set(mWorkVector);
mSimpleRenderer.setCameraPosition(mCameraPosition.x, mCameraPosition.y, mCameraPosition.z);
mSimpleRenderer.setCameraLookAtPosition(mTargetPosition.x, mTargetPosition.y, mTargetPosition.z);
mCameraDirty = false;
}
synchronized public void rotate(float x, float y) {
if (x != 0.0f) {
mCameraXZAngle += x * CAMERA_ORBIT_SPEED;
mCameraDirty = true;
}
if (y != 0.0f) {
mCameraYAngle += y * CAMERA_ORBIT_SPEED;
mCameraDirty = true;
}
}
synchronized public void move(float amount) {
mWorkVector.set(mTargetPosition);
mWorkVector.subtract(mCameraPosition);
mWorkVector.normalize();
mWorkVector.multiply(amount * CAMERA_MOVE_SPEED);
mCameraPosition.add(mWorkVector);
mTargetPosition.add(mWorkVector);
mCameraDirty = true;
}
public void pause() {
synchronized(mPauseLock) {
mPaused = true;
}
}
public void resume() {
synchronized(mPauseLock) {
mPaused = false;
mPauseLock.notifyAll();
}
}
}
| 1219806112-wangyao | HeightMapProfiler/src/com/android/heightmapprofiler/Game.java | Java | asf20 | 3,986 |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* 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.android.heightmapprofiler;
import android.opengl.GLSurfaceView;
import com.android.heightmapprofiler.SimpleGLRenderer;
import com.android.heightmapprofiler.R;
import android.app.Activity;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.KeyEvent;
import android.view.MotionEvent;
// The main entry point for the actual landscape rendering test.
// This class pulls options from the preferences set in the MainMenu
// activity and builds the landscape accordingly.
public class HeightMapTest extends Activity {
private GLSurfaceView mGLSurfaceView;
private SimpleGLRenderer mSimpleRenderer;
private Game mGame;
private Thread mGameThread;
private float mLastScreenX;
private float mLastScreenY;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mGLSurfaceView = new GLSurfaceView(this);
mGLSurfaceView.setEGLConfigChooser(true);
mSimpleRenderer = new SimpleGLRenderer(this);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
final boolean runGame = prefs.getBoolean("runsim", true);
final boolean bigWorld = prefs.getBoolean("bigworld", true);
final boolean skybox = prefs.getBoolean("skybox", true);
final boolean texture = prefs.getBoolean("texture", true);
final boolean vertexColors = prefs.getBoolean("colors", true);
final boolean useTextureLods = prefs.getBoolean("lodTexture", true);
final boolean textureMips = prefs.getBoolean("textureMips", true);
final boolean useColorTextureLods = prefs.getBoolean("lodTextureColored", false );
final int maxTextureSize = Integer.parseInt(prefs.getString("maxTextureSize", "512"));
final String textureFilter = prefs.getString("textureFiltering", "bilinear");
final boolean useLods = prefs.getBoolean("lod", true);
final int complexity = Integer.parseInt(prefs.getString("complexity", "24"));
final boolean useFixedPoint = prefs.getBoolean("fixed", false);
final boolean useVbos = prefs.getBoolean("vbo", true);
final boolean useNdk = prefs.getBoolean("ndk", false);
BitmapDrawable heightMapDrawable = (BitmapDrawable)getResources().getDrawable(R.drawable.heightmap);
Bitmap heightmap = heightMapDrawable.getBitmap();
Bitmap lightmap = null;
if (vertexColors != false) {
BitmapDrawable lightMapDrawable = (BitmapDrawable)getResources().getDrawable(R.drawable.lightmap);
lightmap = lightMapDrawable.getBitmap();
}
LandTileMap tileMap = null;
if (bigWorld) {
final int tilesX = 4;
final int tilesY = 4;
tileMap = new LandTileMap(tilesX, tilesY, heightmap, lightmap, vertexColors, texture, useLods, complexity, useFixedPoint);
} else {
tileMap = new LandTileMap(1, 1, heightmap, lightmap, vertexColors, texture, useLods, complexity, useFixedPoint);
}
if (skybox) {
BitmapDrawable skyboxDrawable = (BitmapDrawable)getResources().getDrawable(R.drawable.skybox);
Bitmap skyboxBitmap = skyboxDrawable.getBitmap();
tileMap.setupSkybox(skyboxBitmap, useFixedPoint);
}
if (useNdk) {
NativeRenderer renderer = new NativeRenderer();
tileMap.setNativeRenderer(renderer);
mSimpleRenderer.setNativeRenderer(renderer);
}
ProfileRecorder.sSingleton.resetAll();
mSimpleRenderer.setUseHardwareBuffers(useVbos);
if (texture) {
mSimpleRenderer.setTiles(tileMap, R.drawable.road_texture, R.drawable.skybox_texture);
mSimpleRenderer.setUseTextureLods( useTextureLods, textureMips );
mSimpleRenderer.setColorTextureLods( useColorTextureLods );
mSimpleRenderer.setMaxTextureSize(maxTextureSize);
if (textureFilter == "nearest") {
mSimpleRenderer.setTextureFilter(SimpleGLRenderer.FILTER_NEAREST_NEIGHBOR);
} else if (textureFilter == "trilinear") {
mSimpleRenderer.setTextureFilter(SimpleGLRenderer.FILTER_TRILINEAR);
} else {
mSimpleRenderer.setTextureFilter(SimpleGLRenderer.FILTER_BILINEAR);
}
} else {
mSimpleRenderer.setTiles(tileMap, 0, 0);
}
mGLSurfaceView.setRenderer(mSimpleRenderer);
setContentView(mGLSurfaceView);
if (runGame) {
mGame = new Game(mSimpleRenderer, tileMap);
mGameThread = new Thread(mGame);
mGameThread.start();
}
}
@Override
protected void onPause() {
super.onPause();
mGLSurfaceView.onPause();
if (mGame != null) {
mGame.pause();
}
}
@Override
protected void onResume() {
super.onResume();
mGLSurfaceView.onResume();
if (mGame != null) {
mGame.resume();
}
}
@Override
public boolean onTrackballEvent(MotionEvent event) {
if (mGame != null) {
mGame.rotate(event.getRawX(), -event.getRawY());
}
return true;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (mGame != null) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
mGame.move(1.0f);
} else if (event.getAction() == MotionEvent.ACTION_MOVE) {
float xDelta = event.getX() - mLastScreenX;
float yDelta = event.getY() - mLastScreenY;
mGame.move(1.0f);
// Scale the values we got down to make control usable.
// A real game would probably figure out scale factors based
// on the size of the screen rather than hard-coded constants
// like this.
mGame.rotate(xDelta * 0.01f, -yDelta * 0.005f);
}
}
mLastScreenX = event.getX();
mLastScreenY = event.getY();
try {
Thread.sleep(16);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
}
return true;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (mGame != null) {
final float speed = 1.0f;
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_DOWN:
mGame.rotate(0.0f, -speed);
return true;
case KeyEvent.KEYCODE_DPAD_LEFT:
mGame.rotate(-speed, 0.0f);
return true;
case KeyEvent.KEYCODE_DPAD_RIGHT:
mGame.rotate(speed, 0.0f);
return true;
case KeyEvent.KEYCODE_DPAD_UP:
mGame.rotate(0.0f, speed);
return true;
}
}
return super.onKeyDown(keyCode, event);
}
} | 1219806112-wangyao | HeightMapProfiler/src/com/android/heightmapprofiler/HeightMapTest.java | Java | asf20 | 7,428 |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* 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.android.heightmapprofiler;
import com.android.heightmapprofiler.R;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceActivity;
/**
* Main entry point for the HeightMapTest application.
*/
public class MainMenu extends PreferenceActivity implements Preference.OnPreferenceClickListener {
private static final int ACTIVITY_TEST = 0;
private static final int RESULTS_DIALOG = 0;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.preferences);
Preference runTestButton = getPreferenceManager().findPreference("runtest");
if (runTestButton != null) {
runTestButton.setOnPreferenceClickListener(this);
}
}
/** Creates the test results dialog and fills in a dummy message. */
@Override
protected Dialog onCreateDialog(int id) {
Dialog dialog = null;
if (id == RESULTS_DIALOG) {
String dummy = "No results yet.";
CharSequence sequence = dummy.subSequence(0, dummy.length() -1);
dialog = new AlertDialog.Builder(this)
.setTitle(R.string.dialog_title)
.setPositiveButton(R.string.dialog_ok, null)
.setMessage(sequence)
.create();
}
return dialog;
}
/**
* Replaces the dummy message in the test results dialog with a string that
* describes the actual test results.
*/
protected void onPrepareDialog (int id, Dialog dialog) {
if (id == RESULTS_DIALOG) {
// Extract final timing information from the profiler.
final ProfileRecorder profiler = ProfileRecorder.sSingleton;
final long frameVerts = profiler.getAverageVerts();
final long frameTime =
profiler.getAverageTime(ProfileRecorder.PROFILE_FRAME);
final long frameMin =
profiler.getMinTime(ProfileRecorder.PROFILE_FRAME);
final long frameMax =
profiler.getMaxTime(ProfileRecorder.PROFILE_FRAME);
final long drawTime =
profiler.getAverageTime(ProfileRecorder.PROFILE_DRAW);
final long drawMin =
profiler.getMinTime(ProfileRecorder.PROFILE_DRAW);
final long drawMax =
profiler.getMaxTime(ProfileRecorder.PROFILE_DRAW);
final long simTime =
profiler.getAverageTime(ProfileRecorder.PROFILE_SIM);
final long simMin =
profiler.getMinTime(ProfileRecorder.PROFILE_SIM);
final long simMax =
profiler.getMaxTime(ProfileRecorder.PROFILE_SIM);
final float fps = frameTime > 0 ? 1000.0f / frameTime : 0.0f;
String result = "Frame: " + frameTime + "ms (" + fps + " fps)\n"
+ "\t\tMin: " + frameMin + "ms\t\tMax: " + frameMax + "\n"
+ "Draw: " + drawTime + "ms\n"
+ "\t\tMin: " + drawMin + "ms\t\tMax: " + drawMax + "\n"
+ "Sim: " + simTime + "ms\n"
+ "\t\tMin: " + simMin + "ms\t\tMax: " + simMax + "\n"
+ "\nVerts per frame: ~" + frameVerts + "\n";
CharSequence sequence = result.subSequence(0, result.length() -1);
AlertDialog alertDialog = (AlertDialog)dialog;
alertDialog.setMessage(sequence);
}
}
/** Shows the results dialog when the test activity closes. */
@Override
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
showDialog(RESULTS_DIALOG);
}
public boolean onPreferenceClick(Preference preference) {
Intent i = new Intent(this, HeightMapTest.class);
startActivityForResult(i, ACTIVITY_TEST);
return true;
}
} | 1219806112-wangyao | HeightMapProfiler/src/com/android/heightmapprofiler/MainMenu.java | Java | asf20 | 4,939 |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* 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.android.heightmapprofiler;
import android.os.SystemClock;
/**
* Implements a simple runtime profiler. The profiler records start and stop
* times for several different types of profiles and can then return min, max
* and average execution times per type. Profile types are independent and may
* be nested in calling code. This object is a singleton for convenience.
*/
public class ProfileRecorder {
// A type for recording actual draw command time.
public static final int PROFILE_DRAW = 0;
// A type for recording the time it takes to run a single simulation step.
public static final int PROFILE_SIM = 2;
// A type for recording the total amount of time spent rendering a frame.
public static final int PROFILE_FRAME = 3;
private static final int PROFILE_COUNT = PROFILE_FRAME + 1;
private ProfileRecord[] mProfiles;
private int mFrameCount;
private long mVertexCount;
public static ProfileRecorder sSingleton = new ProfileRecorder();
public ProfileRecorder() {
mProfiles = new ProfileRecord[PROFILE_COUNT];
for (int x = 0; x < PROFILE_COUNT; x++) {
mProfiles[x] = new ProfileRecord();
}
}
/** Starts recording execution time for a specific profile type.*/
public final void start(int profileType) {
if (profileType < PROFILE_COUNT) {
mProfiles[profileType].start(SystemClock.uptimeMillis());
}
}
/** Stops recording time for this profile type. */
public final void stop(int profileType) {
if (profileType < PROFILE_COUNT) {
mProfiles[profileType].stop(SystemClock.uptimeMillis());
}
}
/** Indicates the end of the frame.*/
public final void endFrame() {
mFrameCount++;
}
/* Flushes all recorded timings from the profiler. */
public final void resetAll() {
for (int x = 0; x < PROFILE_COUNT; x++) {
mProfiles[x].reset();
}
mFrameCount = 0;
mVertexCount = 0L;
}
/* Returns the average execution time, in milliseconds, for a given type. */
public long getAverageTime(int profileType) {
long time = 0;
if (profileType < PROFILE_COUNT) {
time = mProfiles[profileType].getAverageTime(mFrameCount);
}
return time;
}
/* Returns the minimum execution time in milliseconds for a given type. */
public long getMinTime(int profileType) {
long time = 0;
if (profileType < PROFILE_COUNT) {
time = mProfiles[profileType].getMinTime();
}
return time;
}
/* Returns the maximum execution time in milliseconds for a given type. */
public long getMaxTime(int profileType) {
long time = 0;
if (profileType < PROFILE_COUNT) {
time = mProfiles[profileType].getMaxTime();
}
return time;
}
public long getTotalVerts() {
return mVertexCount;
}
public long getAverageVerts() {
return mVertexCount / mFrameCount;
}
public void addVerts(long vertCount) {
mVertexCount += vertCount;
}
/**
* A simple class for storing timing information about a single profile
* type.
*/
protected class ProfileRecord {
private long mStartTime;
private long mTotalTime;
private long mMinTime;
private long mMaxTime;
public void start(long time) {
mStartTime = time;
}
public void stop(long time) {
if (mStartTime > 0) {
final long timeDelta = time - mStartTime;
mTotalTime += timeDelta;
if (mMinTime == 0 || timeDelta < mMinTime) {
mMinTime = timeDelta;
}
if (mMaxTime == 0 || timeDelta > mMaxTime) {
mMaxTime = timeDelta;
}
}
}
public long getAverageTime(int frameCount) {
long time = frameCount > 0 ? mTotalTime / frameCount : 0;
return time;
}
public long getMinTime() {
return mMinTime;
}
public long getMaxTime() {
return mMaxTime;
}
public void startNewProfilePeriod() {
mTotalTime = 0;
}
public void reset() {
mTotalTime = 0;
mStartTime = 0;
mMinTime = 0;
mMaxTime = 0;
}
}
}
| 1219806112-wangyao | HeightMapProfiler/src/com/android/heightmapprofiler/ProfileRecorder.java | Java | asf20 | 5,182 |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* 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.android.heightmapprofiler;
import android.graphics.Bitmap;
import android.graphics.Color;
// This class generates vertex arrays based on grayscale images.
// It defines 1.0 (white) as the tallest point and 0.0 (black) as the lowest point,
// and builds a mesh that represents that topology.
public class HeightMapMeshMaker {
public static final Grid makeGrid(Bitmap drawable, Bitmap lightmap, int subdivisions, float width, float height, float scale, boolean fixedPoint) {
Grid grid = null;
final float subdivisionRange = subdivisions - 1;
final float vertexSizeX = width / subdivisionRange;
final float vertexSizeZ = height / subdivisionRange;
if (drawable != null) {
grid = new Grid(subdivisions, subdivisions, fixedPoint);
final float heightMapScaleX = drawable.getWidth() / subdivisionRange;
final float heightMapScaleY = drawable.getHeight() / subdivisionRange;
final float lightMapScaleX = lightmap != null ? lightmap.getWidth() / subdivisions : 0.0f;
final float lightMapScaleY = lightmap != null ? lightmap.getHeight() / subdivisions : 0.0f;
final float[] vertexColor = { 1.0f, 1.0f, 1.0f, 1.0f };
for (int i = 0; i < subdivisions; i++) {
final float u = (float)(i + 1) / subdivisions;
for (int j = 0; j < subdivisions; j++) {
final float v = (float)(j + 1) / subdivisions;
final float vertexHeight = getBilinearFilteredHeight(drawable, (heightMapScaleX * i), (heightMapScaleY * j), scale);
if (lightmap != null) {
final int lightColor = lightmap.getPixel((int)(lightMapScaleX * i), (int)(lightMapScaleY * j));
final float colorScale = 1.0f / 255.0f;
vertexColor[0] = colorScale * Color.red(lightColor);
vertexColor[1] = colorScale * Color.green(lightColor);
vertexColor[2] = colorScale * Color.blue(lightColor);
vertexColor[3] = colorScale * Color.alpha(lightColor);
}
grid.set(i, j, i * vertexSizeX, vertexHeight, j * vertexSizeZ, u, v, vertexColor);
}
}
}
return grid;
}
// In order to get a smooth gradation between pixels from a low-resolution height map,
// this function uses a bilinear filter to calculate a weighted average of four pixels
// surrounding the requested point.
public static final float getBilinearFilteredHeight(Bitmap drawable, float x, float y, float scale) {
final int topLeftPixelX = clamp((int)Math.floor(x), 0, drawable.getWidth() - 1);
final int topLeftPixelY = clamp((int)Math.floor(y), 0, drawable.getHeight() - 1);
final int bottomRightPixelX = clamp((int)Math.ceil(x), 0, drawable.getWidth() - 1);
final int bottomRightPixelY = clamp((int)Math.ceil(y), 0, drawable.getHeight() - 1);
final float topLeftWeightX = x - topLeftPixelX;
final float topLeftWeightY = y - topLeftPixelY;
final float bottomRightWeightX = 1.0f - topLeftWeightX;
final float bottomRightWeightY = 1.0f - topLeftWeightY;
final int topLeft = drawable.getPixel(topLeftPixelX, topLeftPixelY);
final int topRight = drawable.getPixel(bottomRightPixelX, topLeftPixelY);
final int bottomLeft = drawable.getPixel(topLeftPixelX, bottomRightPixelY);
final int bottomRight = drawable.getPixel(bottomRightPixelX, bottomRightPixelY);
final float red1 = bottomRightWeightX * Color.red(topLeft) + topLeftWeightX * Color.red(topRight);
final float red2 = bottomRightWeightX * Color.red(bottomLeft) + topLeftWeightX * Color.red(bottomRight);
final float red = bottomRightWeightY * red1 + topLeftWeightY * red2;
final float height = red * scale;
return height;
}
private static final int clamp(int value, int min, int max) {
return value < min ? min : (value > max ? max : value);
}
}
| 1219806112-wangyao | HeightMapProfiler/src/com/android/heightmapprofiler/HeightMapMeshMaker.java | Java | asf20 | 4,425 |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* 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.android.heightmapprofiler;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.CharBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import javax.microedition.khronos.opengles.GL10;
import javax.microedition.khronos.opengles.GL11;
/**
* A 2D rectangular mesh. Can be drawn textured or untextured.
* This version is modified from the original Grid.java (found in
* the SpriteText package in the APIDemos Android sample) to support hardware
* vertex buffers.
*/
class Grid {
private FloatBuffer mFloatVertexBuffer;
private FloatBuffer mFloatTexCoordBuffer;
private FloatBuffer mFloatColorBuffer;
private IntBuffer mFixedVertexBuffer;
private IntBuffer mFixedTexCoordBuffer;
private IntBuffer mFixedColorBuffer;
private CharBuffer mIndexBuffer;
private Buffer mVertexBuffer;
private Buffer mTexCoordBuffer;
private Buffer mColorBuffer;
private int mCoordinateSize;
private int mCoordinateType;
private int mW;
private int mH;
private int mIndexCount;
private boolean mUseHardwareBuffers;
private int mVertBufferIndex;
private int mIndexBufferIndex;
private int mTextureCoordBufferIndex;
private int mColorBufferIndex;
public Grid(int vertsAcross, int vertsDown, boolean useFixedPoint) {
if (vertsAcross < 0 || vertsAcross >= 65536) {
throw new IllegalArgumentException("vertsAcross");
}
if (vertsDown < 0 || vertsDown >= 65536) {
throw new IllegalArgumentException("vertsDown");
}
if (vertsAcross * vertsDown >= 65536) {
throw new IllegalArgumentException("vertsAcross * vertsDown >= 65536");
}
mUseHardwareBuffers = false;
mW = vertsAcross;
mH = vertsDown;
int size = vertsAcross * vertsDown;
final int FLOAT_SIZE = 4;
final int FIXED_SIZE = 4;
final int CHAR_SIZE = 2;
if (useFixedPoint) {
mFixedVertexBuffer = ByteBuffer.allocateDirect(FIXED_SIZE * size * 3)
.order(ByteOrder.nativeOrder()).asIntBuffer();
mFixedTexCoordBuffer = ByteBuffer.allocateDirect(FIXED_SIZE * size * 2)
.order(ByteOrder.nativeOrder()).asIntBuffer();
mFixedColorBuffer = ByteBuffer.allocateDirect(FIXED_SIZE * size * 4)
.order(ByteOrder.nativeOrder()).asIntBuffer();
mVertexBuffer = mFixedVertexBuffer;
mTexCoordBuffer = mFixedTexCoordBuffer;
mColorBuffer = mFixedColorBuffer;
mCoordinateSize = FIXED_SIZE;
mCoordinateType = GL10.GL_FIXED;
} else {
mFloatVertexBuffer = ByteBuffer.allocateDirect(FLOAT_SIZE * size * 3)
.order(ByteOrder.nativeOrder()).asFloatBuffer();
mFloatTexCoordBuffer = ByteBuffer.allocateDirect(FLOAT_SIZE * size * 2)
.order(ByteOrder.nativeOrder()).asFloatBuffer();
mFloatColorBuffer = ByteBuffer.allocateDirect(FLOAT_SIZE * size * 4)
.order(ByteOrder.nativeOrder()).asFloatBuffer();
mVertexBuffer = mFloatVertexBuffer;
mTexCoordBuffer = mFloatTexCoordBuffer;
mColorBuffer = mFloatColorBuffer;
mCoordinateSize = FLOAT_SIZE;
mCoordinateType = GL10.GL_FLOAT;
}
int quadW = mW - 1;
int quadH = mH - 1;
int quadCount = quadW * quadH;
int indexCount = quadCount * 6;
mIndexCount = indexCount;
mIndexBuffer = ByteBuffer.allocateDirect(CHAR_SIZE * indexCount)
.order(ByteOrder.nativeOrder()).asCharBuffer();
/*
* Initialize triangle list mesh.
*
* [0]-----[ 1] ...
* | / |
* | / |
* | / |
* [w]-----[w+1] ...
* | |
*
*/
{
int i = 0;
for (int y = 0; y < quadH; y++) {
for (int x = 0; x < quadW; x++) {
char a = (char) (y * mW + x);
char b = (char) (y * mW + x + 1);
char c = (char) ((y + 1) * mW + x);
char d = (char) ((y + 1) * mW + x + 1);
mIndexBuffer.put(i++, a);
mIndexBuffer.put(i++, b);
mIndexBuffer.put(i++, c);
mIndexBuffer.put(i++, b);
mIndexBuffer.put(i++, c);
mIndexBuffer.put(i++, d);
}
}
}
mVertBufferIndex = 0;
}
void set(int i, int j, float x, float y, float z, float u, float v, float[] color) {
if (i < 0 || i >= mW) {
throw new IllegalArgumentException("i");
}
if (j < 0 || j >= mH) {
throw new IllegalArgumentException("j");
}
final int index = mW * j + i;
final int posIndex = index * 3;
final int texIndex = index * 2;
final int colorIndex = index * 4;
if (mCoordinateType == GL10.GL_FLOAT) {
mFloatVertexBuffer.put(posIndex, x);
mFloatVertexBuffer.put(posIndex + 1, y);
mFloatVertexBuffer.put(posIndex + 2, z);
mFloatTexCoordBuffer.put(texIndex, u);
mFloatTexCoordBuffer.put(texIndex + 1, v);
if (color != null) {
mFloatColorBuffer.put(colorIndex, color[0]);
mFloatColorBuffer.put(colorIndex + 1, color[1]);
mFloatColorBuffer.put(colorIndex + 2, color[2]);
mFloatColorBuffer.put(colorIndex + 3, color[3]);
}
} else {
mFixedVertexBuffer.put(posIndex, (int)(x * (1 << 16)));
mFixedVertexBuffer.put(posIndex + 1, (int)(y * (1 << 16)));
mFixedVertexBuffer.put(posIndex + 2, (int)(z * (1 << 16)));
mFixedTexCoordBuffer.put(texIndex, (int)(u * (1 << 16)));
mFixedTexCoordBuffer.put(texIndex + 1, (int)(v * (1 << 16)));
if (color != null) {
mFixedColorBuffer.put(colorIndex, (int)(color[0] * (1 << 16)));
mFixedColorBuffer.put(colorIndex + 1, (int)(color[1] * (1 << 16)));
mFixedColorBuffer.put(colorIndex + 2, (int)(color[2] * (1 << 16)));
mFixedColorBuffer.put(colorIndex + 3, (int)(color[3] * (1 << 16)));
}
}
}
public static void beginDrawing(GL10 gl, boolean useTexture, boolean useColor) {
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
if (useTexture) {
gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
gl.glEnable(GL10.GL_TEXTURE_2D);
} else {
gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
gl.glDisable(GL10.GL_TEXTURE_2D);
}
if (useColor) {
gl.glEnableClientState(GL10.GL_COLOR_ARRAY);
} else {
gl.glDisableClientState(GL10.GL_COLOR_ARRAY);
}
}
public void draw(GL10 gl, boolean useTexture, boolean useColor) {
if (!mUseHardwareBuffers) {
gl.glVertexPointer(3, mCoordinateType, 0, mVertexBuffer);
if (useTexture) {
gl.glTexCoordPointer(2, mCoordinateType, 0, mTexCoordBuffer);
}
if (useColor) {
gl.glColorPointer(4, mCoordinateType, 0, mColorBuffer);
}
gl.glDrawElements(GL10.GL_TRIANGLES, mIndexCount,
GL10.GL_UNSIGNED_SHORT, mIndexBuffer);
} else {
GL11 gl11 = (GL11)gl;
// draw using hardware buffers
gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, mVertBufferIndex);
gl11.glVertexPointer(3, mCoordinateType, 0, 0);
if (useTexture) {
gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, mTextureCoordBufferIndex);
gl11.glTexCoordPointer(2, mCoordinateType, 0, 0);
}
if (useColor) {
gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, mColorBufferIndex);
gl11.glColorPointer(4, mCoordinateType, 0, 0);
}
gl11.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, mIndexBufferIndex);
gl11.glDrawElements(GL11.GL_TRIANGLES, mIndexCount,
GL11.GL_UNSIGNED_SHORT, 0);
gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, 0);
gl11.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, 0);
}
}
public static void endDrawing(GL10 gl) {
gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
}
public boolean usingHardwareBuffers() {
return mUseHardwareBuffers;
}
/**
* When the OpenGL ES device is lost, GL handles become invalidated.
* In that case, we just want to "forget" the old handles (without
* explicitly deleting them) and make new ones.
*/
public void invalidateHardwareBuffers() {
mVertBufferIndex = 0;
mIndexBufferIndex = 0;
mTextureCoordBufferIndex = 0;
mColorBufferIndex = 0;
mUseHardwareBuffers = false;
}
/**
* Deletes the hardware buffers allocated by this object (if any).
*/
public void releaseHardwareBuffers(GL10 gl) {
if (mUseHardwareBuffers) {
if (gl instanceof GL11) {
GL11 gl11 = (GL11)gl;
int[] buffer = new int[1];
buffer[0] = mVertBufferIndex;
gl11.glDeleteBuffers(1, buffer, 0);
buffer[0] = mTextureCoordBufferIndex;
gl11.glDeleteBuffers(1, buffer, 0);
buffer[0] = mColorBufferIndex;
gl11.glDeleteBuffers(1, buffer, 0);
buffer[0] = mIndexBufferIndex;
gl11.glDeleteBuffers(1, buffer, 0);
}
invalidateHardwareBuffers();
}
}
/**
* Allocates hardware buffers on the graphics card and fills them with
* data if a buffer has not already been previously allocated. Note that
* this function uses the GL_OES_vertex_buffer_object extension, which is
* not guaranteed to be supported on every device.
* @param gl A pointer to the OpenGL ES context.
*/
public void generateHardwareBuffers(GL10 gl) {
if (!mUseHardwareBuffers) {
if (gl instanceof GL11) {
GL11 gl11 = (GL11)gl;
int[] buffer = new int[1];
// Allocate and fill the vertex buffer.
gl11.glGenBuffers(1, buffer, 0);
mVertBufferIndex = buffer[0];
gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, mVertBufferIndex);
final int vertexSize = mVertexBuffer.capacity() * mCoordinateSize;
gl11.glBufferData(GL11.GL_ARRAY_BUFFER, vertexSize,
mVertexBuffer, GL11.GL_STATIC_DRAW);
// Allocate and fill the texture coordinate buffer.
gl11.glGenBuffers(1, buffer, 0);
mTextureCoordBufferIndex = buffer[0];
gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER,
mTextureCoordBufferIndex);
final int texCoordSize =
mTexCoordBuffer.capacity() * mCoordinateSize;
gl11.glBufferData(GL11.GL_ARRAY_BUFFER, texCoordSize,
mTexCoordBuffer, GL11.GL_STATIC_DRAW);
// Allocate and fill the color buffer.
gl11.glGenBuffers(1, buffer, 0);
mColorBufferIndex = buffer[0];
gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER,
mColorBufferIndex);
final int colorSize =
mColorBuffer.capacity() * mCoordinateSize;
gl11.glBufferData(GL11.GL_ARRAY_BUFFER, colorSize,
mColorBuffer, GL11.GL_STATIC_DRAW);
// Unbind the array buffer.
gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, 0);
// Allocate and fill the index buffer.
gl11.glGenBuffers(1, buffer, 0);
mIndexBufferIndex = buffer[0];
gl11.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER,
mIndexBufferIndex);
// A char is 2 bytes.
final int indexSize = mIndexBuffer.capacity() * 2;
gl11.glBufferData(GL11.GL_ELEMENT_ARRAY_BUFFER, indexSize, mIndexBuffer,
GL11.GL_STATIC_DRAW);
// Unbind the element array buffer.
gl11.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, 0);
mUseHardwareBuffers = true;
assert mVertBufferIndex != 0;
assert mTextureCoordBufferIndex != 0;
assert mIndexBufferIndex != 0;
assert gl11.glGetError() == 0;
}
}
}
// These functions exposed to patch Grid info into native code.
public final int getVertexBuffer() {
return mVertBufferIndex;
}
public final int getTextureBuffer() {
return mTextureCoordBufferIndex;
}
public final int getIndexBuffer() {
return mIndexBufferIndex;
}
public final int getColorBuffer() {
return mColorBufferIndex;
}
public final int getIndexCount() {
return mIndexCount;
}
public boolean getFixedPoint() {
return (mCoordinateType == GL10.GL_FIXED);
}
public long getVertexCount() {
return mW * mH;
}
}
| 1219806112-wangyao | HeightMapProfiler/src/com/android/heightmapprofiler/Grid.java | Java | asf20 | 14,432 |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* 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.android.heightmapprofiler;
import java.util.ArrayList;
import javax.microedition.khronos.opengles.GL10;
// This is a central repository for all vertex arrays. It handles
// generation and invalidation of VBOs from each mesh.
public class MeshLibrary {
// This sample only has one type of mesh, Grid, but in a real game you might have
// multiple types of objects managing vertex arrays (animated objects, objects loaded from
// files, etc). This class could easily be modified to work with some basic Mesh class
// in that case.
private ArrayList<Grid[]> mMeshes = new ArrayList<Grid[]>();
public int addMesh(Grid[] lods) {
int index = mMeshes.size();
mMeshes.add(lods);
return index;
}
public Grid[] getMesh(int index) {
Grid[] mesh = null;
if (index >= 0 && index < mMeshes.size()) {
mesh = mMeshes.get(index);
}
return mesh;
}
public void generateHardwareBuffers(GL10 gl) {
final int count = mMeshes.size();
for (int x = 0; x < count; x++) {
Grid[] lods = mMeshes.get(x);
assert lods != null;
for (int y = 0; y < lods.length; y++) {
Grid lod = lods[y];
if (lod != null) {
lod.invalidateHardwareBuffers();
lod.generateHardwareBuffers(gl);
}
}
}
}
public void freeHardwareBuffers(GL10 gl) {
final int count = mMeshes.size();
for (int x = 0; x < count; x++) {
Grid[] lods = mMeshes.get(x);
assert lods != null;
for (int y = 0; y < lods.length; y++) {
Grid lod = lods[y];
if (lod != null) {
lod.releaseHardwareBuffers(gl);
}
}
}
}
}
| 1219806112-wangyao | HeightMapProfiler/src/com/android/heightmapprofiler/MeshLibrary.java | Java | asf20 | 2,184 |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* 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.android.heightmapprofiler;
import javax.microedition.khronos.opengles.GL10;
import android.graphics.Bitmap;
// This class defines a single land tile. It is built from
// a height map image and may contain several meshes defining different levels
// of detail.
public class LandTile {
public final static float TILE_SIZE = 512;
private final static float HALF_TILE_SIZE = TILE_SIZE / 2;
public final static float TILE_HEIGHT_THRESHOLD = 0.4f;
private final static int MAX_SUBDIVISIONS = 24;
private final static float LOD_STEP_SIZE = 300.0f;
public final static int LOD_LEVELS = 4;
private final static float MAX_LOD_DISTANCE = LOD_STEP_SIZE * (LOD_LEVELS - 1);
private final static float MAX_LOD_DISTANCE2 = MAX_LOD_DISTANCE * MAX_LOD_DISTANCE;
private Grid mLODMeshes[];
private int mLODTextures[];
private Vector3 mPosition = new Vector3();
private Vector3 mCenterPoint = new Vector3();
private Bitmap mHeightMap;
private float mHeightMapScaleX;
private float mHeightMapScaleY;
private int mLodLevels = LOD_LEVELS;
private int mMaxSubdivisions = MAX_SUBDIVISIONS;
private float mTileSizeX = TILE_SIZE;
private float mTileSizeZ = TILE_SIZE;
private float mHalfTileSizeX = HALF_TILE_SIZE;
private float mHalfTileSizeZ = HALF_TILE_SIZE;
private float mTileHeightScale = TILE_HEIGHT_THRESHOLD;
private float mMaxLodDistance = MAX_LOD_DISTANCE;
private float mMaxLodDistance2 = MAX_LOD_DISTANCE2;
public LandTile() {
}
public LandTile(boolean useLods, int maxSubdivisions ) {
if (!useLods) {
mLodLevels = 1;
}
mMaxSubdivisions = maxSubdivisions;
}
public LandTile(float sizeX, float sizeY, float sizeZ, int lodLevelCount, int maxSubdivisions, float maxLodDistance) {
mTileSizeX = sizeX;
mTileSizeZ = sizeZ;
mTileHeightScale = (1.0f / 255.0f) * sizeY;
mLodLevels = lodLevelCount;
mMaxSubdivisions = maxSubdivisions;
mMaxLodDistance = maxLodDistance;
mMaxLodDistance2 = maxLodDistance * maxLodDistance;
mHalfTileSizeX = sizeX / 2.0f;
mHalfTileSizeZ = sizeZ / 2.0f;
}
public void setLods(Grid[] lodMeshes, Bitmap heightmap) {
mHeightMap = heightmap;
mHeightMapScaleX = heightmap.getWidth() / mTileSizeX;
mHeightMapScaleY = heightmap.getHeight() / mTileSizeZ;
mLODMeshes = lodMeshes;
}
public void setLODTextures( int LODTextures[] ) {
mLODTextures = LODTextures;
}
public Grid[] generateLods(Bitmap heightmap, Bitmap lightmap, boolean useFixedPoint) {
final int subdivisionSizeStep = mMaxSubdivisions / mLodLevels;
mLODMeshes = new Grid[mLodLevels];
for (int x = 0; x < mLodLevels; x++) {
final int subdivisions = subdivisionSizeStep * (mLodLevels - x);
mLODMeshes[x] = HeightMapMeshMaker.makeGrid(heightmap, lightmap, subdivisions, mTileSizeX, mTileSizeZ, mTileHeightScale, useFixedPoint);
}
mHeightMap = heightmap;
mHeightMapScaleX = heightmap.getWidth() / mTileSizeX;
mHeightMapScaleY = heightmap.getHeight() / mTileSizeZ;
return mLODMeshes;
}
public final void setPosition(float x, float y, float z) {
mPosition.set(x, y, z);
mCenterPoint.set(x + mHalfTileSizeX, y, z + mHalfTileSizeZ);
}
public final void setPosition(Vector3 position) {
mPosition.set(position);
mCenterPoint.set(position.x + mHalfTileSizeX, position.y, position.z + mHalfTileSizeZ);
}
public final Vector3 getPosition() {
return mPosition;
}
public final Vector3 getCenterPoint() {
return mCenterPoint;
}
public final Grid[] getLods() {
return mLODMeshes;
}
public final float getMaxLodDistance() {
return mMaxLodDistance;
}
public float getHeight(float worldSpaceX, float worldSpaceZ) {
final float tileSpaceX = worldSpaceX - mPosition.x;
final float tileSpaceY = worldSpaceZ - mPosition.z;
final float imageSpaceX = tileSpaceX * mHeightMapScaleX;
final float imageSpaceY = tileSpaceY * mHeightMapScaleY;
float height = 0.0f;
if (imageSpaceX >= 0.0f && imageSpaceX < mHeightMap.getWidth()
&& imageSpaceY >= 0.0f && imageSpaceY < mHeightMap.getHeight()) {
height = HeightMapMeshMaker.getBilinearFilteredHeight(mHeightMap, imageSpaceX, imageSpaceY, mTileHeightScale);
}
return height;
}
public void draw(GL10 gl, Vector3 cameraPosition) {
mCenterPoint.y = cameraPosition.y; // HACK!
final float distanceFromCamera2 = cameraPosition.distance2(mCenterPoint);
int lod = mLodLevels - 1;
if (distanceFromCamera2 < mMaxLodDistance2) {
final int bucket = (int)((distanceFromCamera2 / mMaxLodDistance2) * mLodLevels);
lod = Math.min(bucket, mLodLevels - 1);
}
gl.glPushMatrix();
gl.glTranslatef(mPosition.x, mPosition.y, mPosition.z);
// TODO - should add some code to keep state of current Texture and only set it if a new texture is needed -
// may be taken care of natively by OpenGL lib.
if( mLODTextures != null ) {
// Check to see if we have different LODs to choose from (i.e. Text LOD feature is turned on). If not then
// just select the default texture
if( mLODTextures.length == 1 ) {
gl.glBindTexture(GL10.GL_TEXTURE_2D, mLODTextures[0]);
}
// if the LOD feature is enabled, use lod value to select correct texture to use
else {
gl.glBindTexture(GL10.GL_TEXTURE_2D, mLODTextures[lod]);
}
}
ProfileRecorder.sSingleton.addVerts(mLODMeshes[lod].getVertexCount());
mLODMeshes[lod].draw(gl, true, true);
gl.glPopMatrix();
}
}
| 1219806112-wangyao | HeightMapProfiler/src/com/android/heightmapprofiler/LandTile.java | Java | asf20 | 6,003 |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* 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.android.heightmapprofiler;
import javax.microedition.khronos.opengles.GL10;
import android.graphics.Bitmap;
// This class manages a regular grid of LandTile objects. In this sample,
// all the objects are the same mesh. In a real game, they would probably be
// different to create a more interesting landscape.
// This class also abstracts the concept of tiles away from the rest of the
// code, so that the collision system (amongst others) can query the height of any
// given point in the world.
public class LandTileMap {
private MeshLibrary mMeshLibrary = new MeshLibrary();
private LandTile[] mTiles;
private LandTile mSkybox;
private float mWorldWidth;
private float mWorldHeight;
private int mTilesAcross;
private int mSkyboxTexture;
private boolean mUseColors;
private boolean mUseTexture;
private NativeRenderer mNativeRenderer;
public LandTileMap(
int tilesAcross,
int tilesDown,
Bitmap heightmap,
Bitmap lightmap,
boolean useColors,
boolean useTexture,
boolean useLods,
int maxSubdivisions,
boolean useFixedPoint) {
Grid[] lodMeshes;
int lodLevels = 1;
if (useLods) {
lodLevels = LandTile.LOD_LEVELS;
}
lodMeshes = new Grid[lodLevels];
final int subdivisionSizeStep = maxSubdivisions / lodLevels;
for (int x = 0; x < lodLevels; x++) {
final int subdivisions = subdivisionSizeStep * (lodLevels - x);
lodMeshes[x] = HeightMapMeshMaker.makeGrid(
heightmap,
lightmap,
subdivisions,
LandTile.TILE_SIZE,
LandTile.TILE_SIZE,
LandTile.TILE_HEIGHT_THRESHOLD,
useFixedPoint);
}
mMeshLibrary.addMesh(lodMeshes);
LandTile[] tiles = new LandTile[tilesAcross * tilesDown];
for (int x = 0; x < tilesAcross; x++) {
for (int y = 0; y < tilesDown; y++) {
LandTile tile = new LandTile(useLods, maxSubdivisions);
tile.setLods(lodMeshes, heightmap);
tiles[x * tilesAcross + y] = tile;
tile.setPosition(x * LandTile.TILE_SIZE, 0.0f, y * LandTile.TILE_SIZE);
}
}
mTiles = tiles;
mWorldWidth = tilesAcross * LandTile.TILE_SIZE;
mWorldHeight = tilesDown * LandTile.TILE_SIZE;
mTilesAcross = tilesAcross;
mUseColors = useColors;
mUseTexture = useTexture;
}
public void setLandTextures( int landTextures[] ) {
for( LandTile landTile : mTiles ) {
landTile.setLODTextures( landTextures );
}
}
public void setupSkybox(Bitmap heightmap, boolean useFixedPoint) {
if (mSkybox == null) {
mSkybox = new LandTile(mWorldWidth, 1024, mWorldHeight, 1, 16, 1000000.0f);
mMeshLibrary.addMesh(mSkybox.generateLods(heightmap, null, useFixedPoint));
mSkybox.setPosition(0.0f, 0.0f, 0.0f);
}
}
public float getHeight(float worldX, float worldZ) {
float height = 0.0f;
if (worldX > 0.0f && worldX < mWorldWidth && worldZ > 0.0f && worldZ < mWorldHeight) {
int tileX = (int)(worldX / LandTile.TILE_SIZE);
int tileY = (int)(worldZ / LandTile.TILE_SIZE);
height = mTiles[tileX * mTilesAcross + tileY].getHeight(worldX, worldZ);
}
return height;
}
public void setTextures(int[] landTextures, int skyboxTexture) {
setLandTextures( landTextures );
mSkyboxTexture = skyboxTexture;
if (mNativeRenderer != null) {
final int count = mTiles.length;
for (int x = 0; x < count; x++) {
mNativeRenderer.registerTile(landTextures, mTiles[x], false);
}
if (mSkybox != null) {
// Work around since registerTile() takes an array of textures
int textures[] = new int[1];
textures[0] = skyboxTexture;
mNativeRenderer.registerTile(textures, mSkybox, true);
}
}
}
public void draw(GL10 gl, Vector3 cameraPosition) {
if (mNativeRenderer != null) {
mNativeRenderer.draw(true, true);
} else {
if (mSkyboxTexture != 0) {
gl.glBindTexture(GL10.GL_TEXTURE_2D, mSkyboxTexture);
}
Grid.beginDrawing(gl, mUseTexture, mUseColors);
if (mSkybox != null) {
gl.glDepthMask(false);
gl.glDisable(GL10.GL_DEPTH_TEST);
mSkybox.draw(gl, cameraPosition);
gl.glDepthMask(true);
gl.glEnable(GL10.GL_DEPTH_TEST);
}
final int count = mTiles.length;
for (int x = 0; x < count; x++) {
mTiles[x].draw(gl, cameraPosition);
}
Grid.endDrawing(gl);
}
}
public void generateHardwareBuffers(GL10 gl) {
mMeshLibrary.generateHardwareBuffers(gl);
}
public void setNativeRenderer(NativeRenderer nativeRenderer) {
mNativeRenderer = nativeRenderer;
}
}
| 1219806112-wangyao | HeightMapProfiler/src/com/android/heightmapprofiler/LandTileMap.java | Java | asf20 | 5,197 |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* 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.android.heightmapprofiler;
/**
* Simple 3D vector class. Handles basic vector math for 3D vectors.
*/
public final class Vector3 {
public float x;
public float y;
public float z;
public static final Vector3 ZERO = new Vector3(0, 0, 0);
public Vector3() {
}
public Vector3(float xValue, float yValue, float zValue) {
set(xValue, yValue, zValue);
}
public Vector3(Vector3 other) {
set(other);
}
public final void add(Vector3 other) {
x += other.x;
y += other.y;
z += other.z;
}
public final void add(float otherX, float otherY, float otherZ) {
x += otherX;
y += otherY;
z += otherZ;
}
public final void subtract(Vector3 other) {
x -= other.x;
y -= other.y;
z -= other.z;
}
public final void multiply(float magnitude) {
x *= magnitude;
y *= magnitude;
z *= magnitude;
}
public final void multiply(Vector3 other) {
x *= other.x;
y *= other.y;
z *= other.z;
}
public final void divide(float magnitude) {
if (magnitude != 0.0f) {
x /= magnitude;
y /= magnitude;
z /= magnitude;
}
}
public final void set(Vector3 other) {
x = other.x;
y = other.y;
z = other.z;
}
public final void set(float xValue, float yValue, float zValue) {
x = xValue;
y = yValue;
z = zValue;
}
public final float dot(Vector3 other) {
return (x * other.x) + (y * other.y) + (z * other.z);
}
public final float length() {
return (float) Math.sqrt(length2());
}
public final float length2() {
return (x * x) + (y * y) + (z * z);
}
public final float distance2(Vector3 other) {
float dx = x - other.x;
float dy = y - other.y;
float dz = z - other.z;
return (dx * dx) + (dy * dy) + (dz * dz);
}
public final float normalize() {
final float magnitude = length();
// TODO: I'm choosing safety over speed here.
if (magnitude != 0.0f) {
x /= magnitude;
y /= magnitude;
z /= magnitude;
}
return magnitude;
}
public final void zero() {
set(0.0f, 0.0f, 0.0f);
}
}
| 1219806112-wangyao | HeightMapProfiler/src/com/android/heightmapprofiler/Vector3.java | Java | asf20 | 3,028 |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* 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.android.heightmapprofiler;
// This is a thin interface for a renderer implemented in C++ using the NDK.
public class NativeRenderer {
private Vector3 mCameraPosition = new Vector3();
private Vector3 mLookAtPosition = new Vector3();
private boolean mCameraDirty = false;
static {
System.loadLibrary("heightmapprofiler");
}
public NativeRenderer() {
nativeReset();
}
public void setCamera(Vector3 camera, Vector3 lookat) {
mCameraPosition = camera;
mLookAtPosition = lookat;
mCameraDirty = true;
}
public void registerTile(int textures[], LandTile tile, boolean isSkybox) {
final Grid[] lods = tile.getLods();
final Vector3 position = tile.getPosition();
final Vector3 center = tile.getCenterPoint();
final int index = nativeAddTile(textures[0], lods.length, tile.getMaxLodDistance(), position.x, position.y, position.z, center.x, center.y, center.z);
if (index >= 0) {
for (int x = 0; x < lods.length; x++) {
nativeAddLod(index, lods[x].getVertexBuffer(), lods[x].getTextureBuffer(), lods[x].getIndexBuffer(), lods[x].getColorBuffer(), lods[x].getIndexCount(), lods[x].getFixedPoint());
}
if (isSkybox) {
nativeSetSkybox(index);
}
for( int i = 1; i < textures.length; ++i ) {
nativeAddTextureLod( index, i, textures[i]);
}
}
}
public void registerSkybox(int texture, Grid mesh, Vector3 position, Vector3 centerPoint) {
}
public void draw(boolean useTexture, boolean useColor) {
nativeRender(mCameraPosition.x, mCameraPosition.y, mCameraPosition.z, mLookAtPosition.x, mLookAtPosition.y, mLookAtPosition.z, useTexture, useColor, mCameraDirty);
mCameraDirty = false;
}
private static native void nativeReset();
private static native int nativeAddTile(int texture, int lodCount, float maxLodDistance, float x, float y, float z, float centerX, float centerY, float centerZ);
private static native void nativeAddLod(int index, int vertexBuffer, int textureBuffer, int indexBuffer, int colorBuffer, int indexCount, boolean useFixedPoint);
private static native void nativeSetSkybox(int index);
private static native void nativeRender(float cameraX, float cameraY, float cameraZ, float lookAtX, float lookAtY, float lookAtZ, boolean useTexture, boolean useColor, boolean cameraDirty);
private static native void nativeAddTextureLod(int tileIndex, int lod, int textureName);
}
| 1219806112-wangyao | HeightMapProfiler/src/com/android/heightmapprofiler/NativeRenderer.java | Java | asf20 | 3,021 |
/*
* Copyright (C) 2009 The Android Open Source Project
*
* 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.
*/
#include <assert.h>
#include <jni.h>
#include <android/log.h>
#include <stdio.h>
#include <stdint.h>
#include <math.h>
#include <GLES/gl.h>
static const char* LogTitle = "HeightMapProfiler";
#ifdef DEBUG
#define ASSERT(x) if (!(x)) { __assert(__FILE__, __LINE__, #x); }
#else
#define ASSERT(X)
#endif
#ifdef REPORTING
#define LOGE(...) __android_log_print(ANDROID_LOG_ERROR, LogTitle, __VA_ARGS__)
#define LOGI(...) __android_log_print(ANDROID_LOG_INFO, LogTitle, __VA_ARGS__)
#else
#define LOGE(...)
#define LOGI(...)
#endif
void __assert(const char* pFileName, const int line, const char* pMessage) {
__android_log_print(ANDROID_LOG_ERROR, "HeightMapProfiler", "Assert Failed! %s (%s:%d)", pMessage, pFileName, line);
assert(false);
}
struct Mesh {
int vertexBuffer;
int textureBuffer;
int colorBuffer;
int indexBuffer;
int indexCount;
bool useFixedPoint;
};
struct Tile {
// Store a texture value for each texture LOD (Level of Detail)
int textures[4];
float x;
float y;
float z;
float centerX;
float centerY;
float centerZ;
int maxLodCount;
int lodCount;
Mesh lods[4];
float maxLodDistance2;
};
static const int MAX_TILES = 17; //4x4 tiles + 1 skybox. This really shouldn't be hard coded this way though.
static int sTileCount = 0;
static Tile sTiles[MAX_TILES];
static int sSkybox = -1;
static void nativeReset(JNIEnv* env, jobject thiz) {
sTileCount = 0;
sSkybox = -1;
}
// static native int nativeAddTile(int texture, int lodCount, float maxLodDistance, float x, float y, float z, float centerX, float centerY, float centerZ);
static jint nativeAddTile(
JNIEnv* env,
jobject thiz,
jint texture,
jint lodCount,
jfloat maxLodDistance,
jfloat x,
jfloat y,
jfloat z,
jfloat centerX,
jfloat centerY,
jfloat centerZ) {
LOGI("nativeAddTile");
int index = -1;
if (sTileCount < MAX_TILES) {
index = sTileCount;
Tile* currentTile = &sTiles[index];
currentTile->x = x;
currentTile->y = y;
currentTile->z = z;
currentTile->centerX = centerX;
currentTile->centerY = centerY;
currentTile->centerZ = centerZ;
currentTile->lodCount = 0;
currentTile->maxLodCount = lodCount;
currentTile->maxLodDistance2 = maxLodDistance * maxLodDistance;
// Texture array size hard coded for now
currentTile->textures[0] = texture; // first element takes default LOD texture
currentTile->textures[1] = -1; // rest are set by nativeAddTextureLod() call
currentTile->textures[2] = -1;
currentTile->textures[3] = -1;
sTileCount++;
LOGI("Tile %d: (%g, %g, %g). Max lod: %d", index, x, y, z, lodCount);
}
return index;
}
static void nativeSetSkybox(
JNIEnv* env,
jobject thiz,
jint index) {
if (index < sTileCount && index >= 0) {
sSkybox = index;
}
}
// static native void nativeAddLod(int index, int vertexBuffer, int textureBuffer, int indexBuffer, int colorBuffer, int indexCount, boolean useFixedPoint);
static void nativeAddLod(
JNIEnv* env,
jobject thiz,
jint index,
jint vertexBuffer,
jint textureBuffer,
jint indexBuffer,
jint colorBuffer,
jint indexCount,
jboolean useFixedPoint) {
LOGI("nativeAddLod (%d)", index);
if (index < sTileCount && index >= 0) {
Tile* currentTile = &sTiles[index];
LOGI("Adding lod for tile %d (%d of %d) - %s", index, currentTile->lodCount, currentTile->maxLodCount, useFixedPoint ? "fixed" : "float");
if (currentTile->lodCount < currentTile->maxLodCount) {
const int meshIndex = currentTile->lodCount;
LOGI("Mesh %d: Index Count: %d", meshIndex, indexCount);
Mesh* lod = ¤tTile->lods[meshIndex];
lod->vertexBuffer = vertexBuffer;
lod->textureBuffer = textureBuffer;
lod->colorBuffer = colorBuffer;
lod->indexBuffer = indexBuffer;
lod->indexCount = indexCount;
lod->useFixedPoint = useFixedPoint;
currentTile->lodCount++;
}
}
}
// static native void nativeAddTextureLod(int index, int lod, int textureName);
static void nativeAddTextureLod(
JNIEnv* env,
jobject thiz,
jint tileIndex,
jint lod,
jint textureName) {
if (tileIndex < sTileCount && tileIndex >= 0) {
Tile* currentTile = &sTiles[tileIndex];
LOGI("Adding texture lod for tile %d lod %d texture name %d", tileIndex, lod, textureName);
if( lod >= sizeof(currentTile->textures)/sizeof(currentTile->textures[0]) ) {
LOGI("Error adding texture lod for tile %d lod %d is out of range ", tileIndex, lod );
}
currentTile->textures[lod] = textureName;
}
}
static void drawTile(int index, float cameraX, float cameraY, float cameraZ, bool useTexture, bool useColor) {
//LOGI("draw tile: %d", index);
if (index < sTileCount) {
Tile* currentTile = &sTiles[index];
const float dx = currentTile->centerX - cameraX;
const float dz = currentTile->centerZ - cameraZ;
const float distanceFromCamera2 = (dx * dx) + (dz * dz);
int lod = currentTile->lodCount - 1;
if (distanceFromCamera2 < currentTile->maxLodDistance2) {
const int bucket = (int)((distanceFromCamera2 / currentTile->maxLodDistance2) * currentTile->lodCount);
lod = bucket < (currentTile->lodCount - 1) ? bucket : currentTile->lodCount - 1;
}
ASSERT(lod < currentTile->lodCount);
Mesh* lodMesh = ¤tTile->lods[lod];
//LOGI("mesh %d: count: %d", index, lodMesh->indexCount);
const GLint coordinateType = lodMesh->useFixedPoint ? GL_FIXED : GL_FLOAT;
glPushMatrix();
glTranslatef(currentTile->x, currentTile->y, currentTile->z);
glBindBuffer(GL_ARRAY_BUFFER, lodMesh->vertexBuffer);
glVertexPointer(3, coordinateType, 0, 0);
if (useTexture) {
int texture = currentTile->textures[0];
if( currentTile->textures[lod] != -1 ) {
texture = currentTile->textures[lod];
}
glBindTexture(GL_TEXTURE_2D, texture);
glBindBuffer(GL_ARRAY_BUFFER, lodMesh->textureBuffer);
glTexCoordPointer(2, coordinateType, 0, 0);
}
if (useColor) {
glBindBuffer(GL_ARRAY_BUFFER, lodMesh->colorBuffer);
glColorPointer(4, coordinateType, 0, 0);
}
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, lodMesh->indexBuffer);
glDrawElements(GL_TRIANGLES, lodMesh->indexCount,
GL_UNSIGNED_SHORT, 0);
glPopMatrix();
}
}
// Blatantly copied from the GLU ES project:
// http://code.google.com/p/glues/
static void __gluMakeIdentityf(GLfloat m[16])
{
m[0+4*0] = 1; m[0+4*1] = 0; m[0+4*2] = 0; m[0+4*3] = 0;
m[1+4*0] = 0; m[1+4*1] = 1; m[1+4*2] = 0; m[1+4*3] = 0;
m[2+4*0] = 0; m[2+4*1] = 0; m[2+4*2] = 1; m[2+4*3] = 0;
m[3+4*0] = 0; m[3+4*1] = 0; m[3+4*2] = 0; m[3+4*3] = 1;
}
static void normalize(GLfloat v[3])
{
GLfloat r;
r=(GLfloat)sqrt(v[0]*v[0] + v[1]*v[1] + v[2]*v[2]);
if (r==0.0f)
{
return;
}
v[0]/=r;
v[1]/=r;
v[2]/=r;
}
static void cross(GLfloat v1[3], GLfloat v2[3], GLfloat result[3])
{
result[0] = v1[1]*v2[2] - v1[2]*v2[1];
result[1] = v1[2]*v2[0] - v1[0]*v2[2];
result[2] = v1[0]*v2[1] - v1[1]*v2[0];
}
static void gluLookAt(GLfloat eyex, GLfloat eyey, GLfloat eyez, GLfloat centerx,
GLfloat centery, GLfloat centerz, GLfloat upx, GLfloat upy,
GLfloat upz)
{
GLfloat forward[3], side[3], up[3];
GLfloat m[4][4];
forward[0] = centerx - eyex;
forward[1] = centery - eyey;
forward[2] = centerz - eyez;
up[0] = upx;
up[1] = upy;
up[2] = upz;
normalize(forward);
/* Side = forward x up */
cross(forward, up, side);
normalize(side);
/* Recompute up as: up = side x forward */
cross(side, forward, up);
__gluMakeIdentityf(&m[0][0]);
m[0][0] = side[0];
m[1][0] = side[1];
m[2][0] = side[2];
m[0][1] = up[0];
m[1][1] = up[1];
m[2][1] = up[2];
m[0][2] = -forward[0];
m[1][2] = -forward[1];
m[2][2] = -forward[2];
glMultMatrixf(&m[0][0]);
glTranslatef(-eyex, -eyey, -eyez);
}
/* Call to render the next GL frame */
static void nativeRender(
JNIEnv* env,
jobject thiz,
jfloat cameraX,
jfloat cameraY,
jfloat cameraZ,
jfloat lookAtX,
jfloat lookAtY,
jfloat lookAtZ,
jboolean useTexture,
jboolean useColor,
jboolean cameraDirty) {
//LOGI("render");
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
if (cameraDirty) {
glMatrixMode(GL_MODELVIEW);
glLoadIdentity();
gluLookAt(cameraX, cameraY, cameraZ,
lookAtX, lookAtY, lookAtZ,
0.0f, 1.0f, 0.0f);
}
glEnableClientState(GL_VERTEX_ARRAY);
if (useTexture) {
glEnableClientState(GL_TEXTURE_COORD_ARRAY);
glEnable(GL_TEXTURE_2D);
} else {
glDisableClientState(GL_TEXTURE_COORD_ARRAY);
glDisable(GL_TEXTURE_2D);
}
if (useColor) {
glEnableClientState(GL_COLOR_ARRAY);
} else {
glDisableClientState(GL_COLOR_ARRAY);
}
if (sSkybox != -1) {
glDepthMask(false);
glDisable(GL_DEPTH_TEST);
drawTile(sSkybox, cameraX, cameraY, cameraZ, useTexture, useColor);
glDepthMask(true);
glEnable(GL_DEPTH_TEST);
}
for (int x = 0; x < sTileCount; x++) {
if (x != sSkybox) {
drawTile(x, cameraX, cameraY, cameraZ, useTexture, useColor);
}
}
glDisableClientState(GL_VERTEX_ARRAY);
//LOGI("render complete");
}
static const char* classPathName = "com/android/heightmapprofiler/NativeRenderer";
static JNINativeMethod methods[] = {
{"nativeReset", "()V", (void*)nativeReset },
{"nativeRender", "(FFFFFFZZZ)V", (void*)nativeRender },
{"nativeAddTile", "(IIFFFFFFF)I", (void*)nativeAddTile },
{"nativeAddLod", "(IIIIIIZ)V", (void*)nativeAddLod },
{"nativeSetSkybox", "(I)V", (void*)nativeSetSkybox },
{"nativeAddTextureLod", "(III)V", (void*)nativeAddTextureLod},
};
/*
* Register several native methods for one class.
*/
static int registerNativeMethods(JNIEnv* env, const char* className,
JNINativeMethod* gMethods, int numMethods)
{
jclass clazz;
clazz = env->FindClass(className);
if (clazz == NULL) {
char error[255];
sprintf(error,
"Native registration unable to find class '%s'\n", className);
__android_log_print(ANDROID_LOG_ERROR, "HeightMapProfiler", error);
return JNI_FALSE;
}
if (env->RegisterNatives(clazz, gMethods, numMethods) < 0) {
char error[255];
sprintf(error, "RegisterNatives failed for '%s'\n", className);
__android_log_print(ANDROID_LOG_ERROR, "HeightMapProfiler", error);
return JNI_FALSE;
}
return JNI_TRUE;
}
/*
* Register native methods for all classes we know about.
*/
static int registerNatives(JNIEnv* env)
{
if (!registerNativeMethods(env, classPathName,
methods, sizeof(methods) / sizeof(methods[0]))) {
return JNI_FALSE;
}
return JNI_TRUE;
}
/*
* Set some test stuff up.
*
* Returns the JNI version on success, -1 on failure.
*/
JNIEXPORT jint JNI_OnLoad(JavaVM* vm, void* reserved)
{
JNIEnv* env = NULL;
jint result = -1;
if (vm->GetEnv((void**) &env, JNI_VERSION_1_4) != JNI_OK) {
LOGE("ERROR: GetEnv failed");
goto bail;
}
assert(env != NULL);
if (!registerNatives(env)) {
LOGE("ERROR: HeightMapProfiler native registration failed");
goto bail;
}
/* success -- return valid version number */
result = JNI_VERSION_1_4;
bail:
return result;
}
| 1219806112-wangyao | HeightMapProfiler/jni/height_map.cpp | C++ | asf20 | 11,671 |
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
LOCAL_MODULE := heightmapprofiler
LOCAL_CFLAGS := -DANDROID_NDK #-DREPORTING #-DDEBUG
LOCAL_SRC_FILES := \
height_map.cpp \
LOCAL_LDLIBS := -lGLESv1_CM -ldl -llog
include $(BUILD_SHARED_LIBRARY)
| 1219806112-wangyao | HeightMapProfiler/jni/Android.mk | Makefile | asf20 | 257 |
/*
* Copyright (C) 2008 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.google.android.panoramio;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
/**
* Utilities for loading a bitmap from a URL
*
*/
public class BitmapUtils {
private static final String TAG = "Panoramio";
private static final int IO_BUFFER_SIZE = 4 * 1024;
/**
* Loads a bitmap from the specified url. This can take a while, so it should not
* be called from the UI thread.
*
* @param url The location of the bitmap asset
*
* @return The bitmap, or null if it could not be loaded
*/
public static Bitmap loadBitmap(String url) {
Bitmap bitmap = null;
InputStream in = null;
BufferedOutputStream out = null;
try {
in = new BufferedInputStream(new URL(url).openStream(), IO_BUFFER_SIZE);
final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
copy(in, out);
out.flush();
final byte[] data = dataStream.toByteArray();
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
} catch (IOException e) {
Log.e(TAG, "Could not load Bitmap from: " + url);
} finally {
closeStream(in);
closeStream(out);
}
return bitmap;
}
/**
* Closes the specified stream.
*
* @param stream The stream to close.
*/
private static void closeStream(Closeable stream) {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
android.util.Log.e(TAG, "Could not close stream", e);
}
}
}
/**
* Copy the content of the input stream into the output stream, using a
* temporary byte array buffer whose size is defined by
* {@link #IO_BUFFER_SIZE}.
*
* @param in The input stream to copy from.
* @param out The output stream to copy to.
* @throws IOException If any error occurs during the copy.
*/
private static void copy(InputStream in, OutputStream out) throws IOException {
byte[] b = new byte[IO_BUFFER_SIZE];
int read;
while ((read = in.read(b)) != -1) {
out.write(b, 0, read);
}
}
} | 1219806112-wangyao | Panoramio/src/com/google/android/panoramio/BitmapUtils.java | Java | asf20 | 3,235 |
/*
* Copyright (C) 2008 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.google.android.panoramio;
import com.google.android.maps.GeoPoint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.TextView;
/**
* Activity which displays a single image.
*/
public class ViewImage extends Activity {
private static final String TAG = "Panoramio";
private static final int MENU_RADAR = Menu.FIRST + 1;
private static final int MENU_MAP = Menu.FIRST + 2;
private static final int MENU_AUTHOR = Menu.FIRST + 3;
private static final int MENU_VIEW = Menu.FIRST + 4;
private static final int DIALOG_NO_RADAR = 1;
PanoramioItem mItem;
private Handler mHandler;
private ImageView mImage;
private TextView mTitle;
private TextView mOwner;
private View mContent;
private int mMapZoom;
private int mMapLatitudeE6;
private int mMapLongitudeE6;
@Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
super.onCreate(savedInstanceState);
setContentView(R.layout.view_image);
// Remember the user's original search area and zoom level
Intent i = getIntent();
mItem = i.getParcelableExtra(ImageManager.PANORAMIO_ITEM_EXTRA);
mMapZoom = i.getIntExtra(ImageManager.ZOOM_EXTRA, Integer.MIN_VALUE);
mMapLatitudeE6 = i.getIntExtra(ImageManager.LATITUDE_E6_EXTRA, Integer.MIN_VALUE);
mMapLongitudeE6 = i.getIntExtra(ImageManager.LONGITUDE_E6_EXTRA, Integer.MIN_VALUE);
mHandler = new Handler();
mContent = findViewById(R.id.content);
mImage = (ImageView) findViewById(R.id.image);
mTitle = (TextView) findViewById(R.id.title);
mOwner = (TextView) findViewById(R.id.owner);
mContent.setVisibility(View.GONE);
getWindow().setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS,
Window.PROGRESS_VISIBILITY_ON);
new LoadThread().start();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(0, MENU_RADAR, 0, R.string.menu_radar)
.setIcon(R.drawable.ic_menu_radar)
.setAlphabeticShortcut('R');
menu.add(0, MENU_MAP, 0, R.string.menu_map)
.setIcon(R.drawable.ic_menu_map)
.setAlphabeticShortcut('M');
menu.add(0, MENU_AUTHOR, 0, R.string.menu_author)
.setIcon(R.drawable.ic_menu_author)
.setAlphabeticShortcut('A');
menu.add(0, MENU_VIEW, 0, R.string.menu_view)
.setIcon(android.R.drawable.ic_menu_view)
.setAlphabeticShortcut('V');
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_RADAR: {
// Launch the radar activity (if it is installed)
Intent i = new Intent("com.google.android.radar.SHOW_RADAR");
GeoPoint location = mItem.getLocation();
i.putExtra("latitude", (float)(location.getLatitudeE6() / 1000000f));
i.putExtra("longitude", (float)(location.getLongitudeE6() / 1000000f));
try {
startActivity(i);
} catch (ActivityNotFoundException ex) {
showDialog(DIALOG_NO_RADAR);
}
return true;
}
case MENU_MAP: {
// Display our custom map
Intent i = new Intent(this, ViewMap.class);
i.putExtra(ImageManager.PANORAMIO_ITEM_EXTRA, mItem);
i.putExtra(ImageManager.ZOOM_EXTRA, mMapZoom);
i.putExtra(ImageManager.LATITUDE_E6_EXTRA, mMapLatitudeE6);
i.putExtra(ImageManager.LONGITUDE_E6_EXTRA, mMapLongitudeE6);
startActivity(i);
return true;
}
case MENU_AUTHOR: {
// Display the author info page in the browser
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(mItem.getOwnerUrl()));
startActivity(i);
return true;
}
case MENU_VIEW: {
// Display the photo info page in the browser
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(mItem.getPhotoUrl()));
startActivity(i);
return true;
}
}
return super.onOptionsItemSelected(item);
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_NO_RADAR:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
return builder.setTitle(R.string.no_radar_title)
.setMessage(R.string.no_radar)
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(android.R.string.ok, null).create();
}
return null;
}
/**
* Utility to load a larger version of the image in a separate thread.
*
*/
private class LoadThread extends Thread {
public LoadThread() {
}
@Override
public void run() {
try {
String uri = mItem.getThumbUrl();
uri = uri.replace("thumbnail", "medium");
final Bitmap b = BitmapUtils.loadBitmap(uri);
mHandler.post(new Runnable() {
public void run() {
mImage.setImageBitmap(b);
mTitle.setText(mItem.getTitle());
mOwner.setText(mItem.getOwner());
mContent.setVisibility(View.VISIBLE);
getWindow().setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS,
Window.PROGRESS_VISIBILITY_OFF);
}
});
} catch (Exception e) {
Log.e(TAG, e.toString());
}
}
}
} | 1219806112-wangyao | Panoramio/src/com/google/android/panoramio/ViewImage.java | Java | asf20 | 7,005 |
/*
* Copyright (C) 2008 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.google.android.panoramio;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.FrameLayout;
/**
* Activity which lets the user select a search area
*
*/
public class Panoramio extends MapActivity implements OnClickListener {
private MapView mMapView;
private MyLocationOverlay mMyLocationOverlay;
private ImageManager mImageManager;
public static final int MILLION = 1000000;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mImageManager = ImageManager.getInstance(this);
FrameLayout frame = (FrameLayout) findViewById(R.id.frame);
Button goButton = (Button) findViewById(R.id.go);
goButton.setOnClickListener(this);
// Add the map view to the frame
mMapView = new MapView(this, "Panoramio_DummyAPIKey");
frame.addView(mMapView,
new FrameLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
// Create an overlay to show current location
mMyLocationOverlay = new MyLocationOverlay(this, mMapView);
mMyLocationOverlay.runOnFirstFix(new Runnable() { public void run() {
mMapView.getController().animateTo(mMyLocationOverlay.getMyLocation());
}});
mMapView.getOverlays().add(mMyLocationOverlay);
mMapView.getController().setZoom(15);
mMapView.setClickable(true);
mMapView.setEnabled(true);
mMapView.setSatellite(true);
addZoomControls(frame);
}
@Override
protected void onResume() {
super.onResume();
mMyLocationOverlay.enableMyLocation();
}
@Override
protected void onStop() {
mMyLocationOverlay.disableMyLocation();
super.onStop();
}
/**
* Add zoom controls to our frame layout
*/
private void addZoomControls(FrameLayout frame) {
// Get the zoom controls and add them to the bottom of the map
View zoomControls = mMapView.getZoomControls();
FrameLayout.LayoutParams p =
new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT, Gravity.BOTTOM + Gravity.CENTER_HORIZONTAL);
frame.addView(zoomControls, p);
}
@Override
protected boolean isRouteDisplayed() {
return false;
}
/**
* Starts a new search when the user clicks the search button.
*/
public void onClick(View view) {
// Get the search area
int latHalfSpan = mMapView.getLatitudeSpan() >> 1;
int longHalfSpan = mMapView.getLongitudeSpan() >> 1;
// Remember how the map was displayed so we can show it the same way later
GeoPoint center = mMapView.getMapCenter();
int zoom = mMapView.getZoomLevel();
int latitudeE6 = center.getLatitudeE6();
int longitudeE6 = center.getLongitudeE6();
Intent i = new Intent(this, ImageList.class);
i.putExtra(ImageManager.ZOOM_EXTRA, zoom);
i.putExtra(ImageManager.LATITUDE_E6_EXTRA, latitudeE6);
i.putExtra(ImageManager.LONGITUDE_E6_EXTRA, longitudeE6);
float minLong = ((float) (longitudeE6 - longHalfSpan)) / MILLION;
float maxLong = ((float) (longitudeE6 + longHalfSpan)) / MILLION;
float minLat = ((float) (latitudeE6 - latHalfSpan)) / MILLION;
float maxLat = ((float) (latitudeE6 + latHalfSpan)) / MILLION;
mImageManager.clear();
// Start downloading
mImageManager.load(minLong, maxLong, minLat, maxLat);
// Show results
startActivity(i);
}
}
| 1219806112-wangyao | Panoramio/src/com/google/android/panoramio/Panoramio.java | Java | asf20 | 4,712 |
/*
* Copyright (C) 2008 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.google.android.panoramio;
import com.google.android.maps.GeoPoint;
import android.graphics.Bitmap;
import android.os.Parcel;
import android.os.Parcelable;
/**
* Holds one item returned from the Panoramio server. This includes
* the bitmap along with other meta info.
*
*/
public class PanoramioItem implements Parcelable {
private long mId;
private Bitmap mBitmap;
private GeoPoint mLocation;
private String mTitle;
private String mOwner;
private String mThumbUrl;
private String mOwnerUrl;
private String mPhotoUrl;
public PanoramioItem(Parcel in) {
mId = in.readLong();
mBitmap = Bitmap.CREATOR.createFromParcel(in);
mLocation = new GeoPoint(in.readInt(), in.readInt());
mTitle = in.readString();
mOwner = in.readString();
mThumbUrl = in.readString();
mOwnerUrl = in.readString();
mPhotoUrl = in.readString();
}
public PanoramioItem(long id, String thumbUrl, Bitmap b, int latitudeE6, int longitudeE6,
String title, String owner, String ownerUrl, String photoUrl) {
mBitmap = b;
mLocation = new GeoPoint(latitudeE6, longitudeE6);
mTitle = title;
mOwner = owner;
mThumbUrl = thumbUrl;
mOwnerUrl = ownerUrl;
mPhotoUrl = photoUrl;
}
public long getId() {
return mId;
}
public Bitmap getBitmap() {
return mBitmap;
}
public GeoPoint getLocation() {
return mLocation;
}
public String getTitle() {
return mTitle;
}
public String getOwner() {
return mOwner;
}
public String getThumbUrl() {
return mThumbUrl;
}
public String getOwnerUrl() {
return mOwnerUrl;
}
public String getPhotoUrl() {
return mPhotoUrl;
}
public static final Parcelable.Creator<PanoramioItem> CREATOR =
new Parcelable.Creator<PanoramioItem>() {
public PanoramioItem createFromParcel(Parcel in) {
return new PanoramioItem(in);
}
public PanoramioItem[] newArray(int size) {
return new PanoramioItem[size];
}
};
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel parcel, int flags) {
parcel.writeLong(mId);
mBitmap.writeToParcel(parcel, 0);
parcel.writeInt(mLocation.getLatitudeE6());
parcel.writeInt(mLocation.getLongitudeE6());
parcel.writeString(mTitle);
parcel.writeString(mOwner);
parcel.writeString(mThumbUrl);
parcel.writeString(mOwnerUrl);
parcel.writeString(mPhotoUrl);
}
} | 1219806112-wangyao | Panoramio/src/com/google/android/panoramio/PanoramioItem.java | Java | asf20 | 3,312 |
/*
* Copyright (C) 2008 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.google.android.panoramio;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.database.DataSetObserver;
import android.graphics.Bitmap;
import android.os.Handler;
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.ref.WeakReference;
import java.net.URI;
import java.util.ArrayList;
/**
* This class is responsible for downloading and parsing the search results for
* a particular area. All of the work is done on a separate thread, and progress
* is reported back through the DataSetObserver set in
* {@link #addObserver(DataSetObserver). State is held in memory by in memory
* maintained by a single instance of the ImageManager class.
*/
public class ImageManager {
private static final String TAG = "Panoramio";
/**
* Base URL for Panoramio's web API
*/
private static final String THUMBNAIL_URL = "//www.panoramio.com/map/get_panoramas.php?order=popularity&set=public&from=0&to=20&miny=%f&minx=%f&maxy=%f&maxx=%f&size=thumbnail";
/**
* Used to post results back to the UI thread
*/
private Handler mHandler = new Handler();
/**
* Holds the single instance of a ImageManager that is shared by the process.
*/
private static ImageManager sInstance;
/**
* Holds the images and related data that have been downloaded
*/
private ArrayList<PanoramioItem> mImages = new ArrayList<PanoramioItem>();
/**
* Observers interested in changes to the current search results
*/
private ArrayList<WeakReference<DataSetObserver>> mObservers =
new ArrayList<WeakReference<DataSetObserver>>();
/**
* True if we are in the process of loading
*/
private boolean mLoading;
private Context mContext;
/**
* Key for an Intent extra. The value is the zoom level selected by the user.
*/
public static final String ZOOM_EXTRA = "zoom";
/**
* Key for an Intent extra. The value is the latitude of the center of the search
* area chosen by the user.
*/
public static final String LATITUDE_E6_EXTRA = "latitudeE6";
/**
* Key for an Intent extra. The value is the latitude of the center of the search
* area chosen by the user.
*/
public static final String LONGITUDE_E6_EXTRA = "longitudeE6";
/**
* Key for an Intent extra. The value is an item to display
*/
public static final String PANORAMIO_ITEM_EXTRA = "item";
public static ImageManager getInstance(Context c) {
if (sInstance == null) {
sInstance = new ImageManager(c.getApplicationContext());
}
return sInstance;
}
private ImageManager(Context c) {
mContext = c;
}
/**
* @return True if we are still loading content
*/
public boolean isLoading() {
return mLoading;
}
/**
* Clear all downloaded content
*/
public void clear() {
mImages.clear();
notifyObservers();
}
/**
* Add an item to and notify observers of the change.
* @param item The item to add
*/
private void add(PanoramioItem item) {
mImages.add(item);
notifyObservers();
}
/**
* @return The number of items displayed so far
*/
public int size() {
return mImages.size();
}
/**
* Gets the item at the specified position
*/
public PanoramioItem get(int position) {
return mImages.get(position);
}
/**
* Adds an observer to be notified when the set of items held by this ImageManager changes.
*/
public void addObserver(DataSetObserver observer) {
WeakReference<DataSetObserver> obs = new WeakReference<DataSetObserver>(observer);
mObservers.add(obs);
}
/**
* Load a new set of search results for the specified area.
*
* @param minLong The minimum longitude for the search area
* @param maxLong The maximum longitude for the search area
* @param minLat The minimum latitude for the search area
* @param maxLat The minimum latitude for the search area
*/
public void load(float minLong, float maxLong, float minLat, float maxLat) {
mLoading = true;
new NetworkThread(minLong, maxLong, minLat, maxLat).start();
}
/**
* Called when something changes in our data set. Cleans up any weak references that
* are no longer valid along the way.
*/
private void notifyObservers() {
final ArrayList<WeakReference<DataSetObserver>> observers = mObservers;
final int count = observers.size();
for (int i = count - 1; i >= 0; i--) {
WeakReference<DataSetObserver> weak = observers.get(i);
DataSetObserver obs = weak.get();
if (obs != null) {
obs.onChanged();
} else {
observers.remove(i);
}
}
}
/**
* This thread does the actual work of downloading and parsing data.
*
*/
private class NetworkThread extends Thread {
private float mMinLong;
private float mMaxLong;
private float mMinLat;
private float mMaxLat;
public NetworkThread(float minLong, float maxLong, float minLat, float maxLat) {
mMinLong = minLong;
mMaxLong = maxLong;
mMinLat = minLat;
mMaxLat = maxLat;
}
@Override
public void run() {
String url = THUMBNAIL_URL;
url = String.format(url, mMinLat, mMinLong, mMaxLat, mMaxLong);
try {
URI uri = new URI("http", url, null);
HttpGet get = new HttpGet(uri);
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(get);
HttpEntity entity = response.getEntity();
String str = convertStreamToString(entity.getContent());
JSONObject json = new JSONObject(str);
parse(json);
} catch (Exception e) {
Log.e(TAG, e.toString());
}
}
private void parse(JSONObject json) {
try {
JSONArray array = json.getJSONArray("photos");
int count = array.length();
for (int i = 0; i < count; i++) {
JSONObject obj = array.getJSONObject(i);
long id = obj.getLong("photo_id");
String title = obj.getString("photo_title");
String owner = obj.getString("owner_name");
String thumb = obj.getString("photo_file_url");
String ownerUrl = obj.getString("owner_url");
String photoUrl = obj.getString("photo_url");
double latitude = obj.getDouble("latitude");
double longitude = obj.getDouble("longitude");
Bitmap b = BitmapUtils.loadBitmap(thumb);
if (title == null) {
title = mContext.getString(R.string.untitled);
}
final PanoramioItem item = new PanoramioItem(id, thumb, b,
(int) (latitude * Panoramio.MILLION),
(int) (longitude * Panoramio.MILLION), title, owner,
ownerUrl, photoUrl);
final boolean done = i == count - 1;
mHandler.post(new Runnable() {
public void run() {
sInstance.mLoading = !done;
sInstance.add(item);
}
});
}
} catch (JSONException e) {
Log.e(TAG, e.toString());
}
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is), 8*1024);
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
}
| 1219806112-wangyao | Panoramio/src/com/google/android/panoramio/ImageManager.java | Java | asf20 | 9,706 |
/*
* Copyright (C) 2008 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.google.android.panoramio;
import android.content.Context;
import android.database.DataSetObserver;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
/**
* Adapter used to bind data for the main list of photos
*/
public class ImageAdapter extends BaseAdapter {
/**
* Maintains the state of our data
*/
private ImageManager mImageManager;
private Context mContext;
private MyDataSetObserver mObserver;
/**
* Used by the {@link ImageManager} to report changes in the list back to
* this adapter.
*/
private class MyDataSetObserver extends DataSetObserver {
@Override
public void onChanged() {
notifyDataSetChanged();
}
@Override
public void onInvalidated() {
notifyDataSetInvalidated();
}
}
public ImageAdapter(Context c) {
mImageManager = ImageManager.getInstance(c);
mContext = c;
mObserver = new MyDataSetObserver();
mImageManager.addObserver(mObserver);
}
/**
* Returns the number of images to display
*
* @see android.widget.Adapter#getCount()
*/
public int getCount() {
return mImageManager.size();
}
/**
* Returns the image at a specified position
*
* @see android.widget.Adapter#getItem(int)
*/
public Object getItem(int position) {
return mImageManager.get(position);
}
/**
* Returns the id of an image at a specified position
*
* @see android.widget.Adapter#getItemId(int)
*/
public long getItemId(int position) {
PanoramioItem s = mImageManager.get(position);
return s.getId();
}
/**
* Returns a view to display the image at a specified position
*
* @param position The position to display
* @param convertView An existing view that we can reuse. May be null.
* @param parent The parent view that will eventually hold the view we return.
* @return A view to display the image at a specified position
*/
public View getView(int position, View convertView, ViewGroup parent) {
View view;
if (convertView == null) {
// Make up a new view
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.image_item, null);
} else {
// Use convertView if it is available
view = convertView;
}
PanoramioItem s = mImageManager.get(position);
ImageView i = (ImageView) view.findViewById(R.id.image);
i.setImageBitmap(s.getBitmap());
i.setBackgroundResource(R.drawable.picture_frame);
TextView t = (TextView) view.findViewById(R.id.title);
t.setText(s.getTitle());
t = (TextView) view.findViewById(R.id.owner);
t.setText(s.getOwner());
return view;
}
} | 1219806112-wangyao | Panoramio/src/com/google/android/panoramio/ImageAdapter.java | Java | asf20 | 3,758 |
/*
* Copyright (C) 2008 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.google.android.panoramio;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.database.DataSetObserver;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.ListView;
/**
* Activity which displays the list of images.
*/
public class ImageList extends ListActivity {
ImageManager mImageManager;
private MyDataSetObserver mObserver = new MyDataSetObserver();
/**
* The zoom level the user chose when picking the search area
*/
private int mZoom;
/**
* The latitude of the center of the search area chosen by the user
*/
private int mLatitudeE6;
/**
* The longitude of the center of the search area chosen by the user
*/
private int mLongitudeE6;
/**
* Observer used to turn the progress indicator off when the {@link ImageManager} is
* done downloading.
*/
private class MyDataSetObserver extends DataSetObserver {
@Override
public void onChanged() {
if (!mImageManager.isLoading()) {
getWindow().setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS,
Window.PROGRESS_VISIBILITY_OFF);
}
}
@Override
public void onInvalidated() {
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
super.onCreate(savedInstanceState);
mImageManager = ImageManager.getInstance(this);
ListView listView = getListView();
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View footer = inflater.inflate(R.layout.list_footer, listView, false);
listView.addFooterView(footer, null, false);
setListAdapter(new ImageAdapter(this));
// Theme.Light sets a background on our list.
listView.setBackgroundDrawable(null);
if (mImageManager.isLoading()) {
getWindow().setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS,
Window.PROGRESS_VISIBILITY_ON);
mImageManager.addObserver(mObserver);
}
// Read the user's search area from the intent
Intent i = getIntent();
mZoom = i.getIntExtra(ImageManager.ZOOM_EXTRA, Integer.MIN_VALUE);
mLatitudeE6 = i.getIntExtra(ImageManager.LATITUDE_E6_EXTRA, Integer.MIN_VALUE);
mLongitudeE6 = i.getIntExtra(ImageManager.LONGITUDE_E6_EXTRA, Integer.MIN_VALUE);
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
PanoramioItem item = mImageManager.get(position);
// Create an intent to show a particular item.
// Pass the user's search area along so the next activity can use it
Intent i = new Intent(this, ViewImage.class);
i.putExtra(ImageManager.PANORAMIO_ITEM_EXTRA, item);
i.putExtra(ImageManager.ZOOM_EXTRA, mZoom);
i.putExtra(ImageManager.LATITUDE_E6_EXTRA, mLatitudeE6);
i.putExtra(ImageManager.LONGITUDE_E6_EXTRA, mLongitudeE6);
startActivity(i);
}
} | 1219806112-wangyao | Panoramio/src/com/google/android/panoramio/ImageList.java | Java | asf20 | 3,901 |
/*
* Copyright (C) 2008 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.google.android.panoramio;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;
import com.google.android.maps.Projection;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.FrameLayout;
import java.util.ArrayList;
import java.util.List;
/**
* Displays a custom map which shows our current location and the location
* where the photo was taken.
*/
public class ViewMap extends MapActivity {
private MapView mMapView;
private MyLocationOverlay mMyLocationOverlay;
ArrayList<PanoramioItem> mItems = null;
private PanoramioItem mItem;
private Drawable mMarker;
private int mMarkerXOffset;
private int mMarkerYOffset;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FrameLayout frame = new FrameLayout(this);
mMapView = new MapView(this, "MapViewCompassDemo_DummyAPIKey");
frame.addView(mMapView,
new FrameLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
setContentView(frame);
mMyLocationOverlay = new MyLocationOverlay(this, mMapView);
mMarker = getResources().getDrawable(R.drawable.map_pin);
// Make sure to give mMarker bounds so it will draw in the overlay
final int intrinsicWidth = mMarker.getIntrinsicWidth();
final int intrinsicHeight = mMarker.getIntrinsicHeight();
mMarker.setBounds(0, 0, intrinsicWidth, intrinsicHeight);
mMarkerXOffset = -(intrinsicWidth / 2);
mMarkerYOffset = -intrinsicHeight;
// Read the item we are displaying from the intent, along with the
// parameters used to set up the map
Intent i = getIntent();
mItem = i.getParcelableExtra(ImageManager.PANORAMIO_ITEM_EXTRA);
int mapZoom = i.getIntExtra(ImageManager.ZOOM_EXTRA, Integer.MIN_VALUE);
int mapLatitudeE6 = i.getIntExtra(ImageManager.LATITUDE_E6_EXTRA, Integer.MIN_VALUE);
int mapLongitudeE6 = i.getIntExtra(ImageManager.LONGITUDE_E6_EXTRA, Integer.MIN_VALUE);
final List<Overlay> overlays = mMapView.getOverlays();
overlays.add(mMyLocationOverlay);
overlays.add(new PanoramioOverlay());
final MapController controller = mMapView.getController();
if (mapZoom != Integer.MIN_VALUE && mapLatitudeE6 != Integer.MIN_VALUE
&& mapLongitudeE6 != Integer.MIN_VALUE) {
controller.setZoom(mapZoom);
controller.setCenter(new GeoPoint(mapLatitudeE6, mapLongitudeE6));
} else {
controller.setZoom(15);
mMyLocationOverlay.runOnFirstFix(new Runnable() {
public void run() {
controller.animateTo(mMyLocationOverlay.getMyLocation());
}
});
}
mMapView.setClickable(true);
mMapView.setEnabled(true);
mMapView.setSatellite(true);
addZoomControls(frame);
}
@Override
protected void onResume() {
super.onResume();
mMyLocationOverlay.enableMyLocation();
}
@Override
protected void onStop() {
mMyLocationOverlay.disableMyLocation();
super.onStop();
}
/**
* Get the zoom controls and add them to the bottom of the map
*/
private void addZoomControls(FrameLayout frame) {
View zoomControls = mMapView.getZoomControls();
FrameLayout.LayoutParams p =
new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT, Gravity.BOTTOM + Gravity.CENTER_HORIZONTAL);
frame.addView(zoomControls, p);
}
@Override
protected boolean isRouteDisplayed() {
return false;
}
/**
* Custom overlay to display the Panoramio pushpin
*/
public class PanoramioOverlay extends Overlay {
@Override
public void draw(Canvas canvas, MapView mapView, boolean shadow) {
if (!shadow) {
Point point = new Point();
Projection p = mapView.getProjection();
p.toPixels(mItem.getLocation(), point);
super.draw(canvas, mapView, shadow);
drawAt(canvas, mMarker, point.x + mMarkerXOffset, point.y + mMarkerYOffset, shadow);
}
}
}
}
| 1219806112-wangyao | Panoramio/src/com/google/android/panoramio/ViewMap.java | Java | asf20 | 5,413 |
/*
* Copyright (C) 2008 The Android Open Source Project
*
* 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.android.spritemethodtest;
import java.io.IOException;
import java.io.InputStream;
import javax.microedition.khronos.egl.EGL10;
import javax.microedition.khronos.opengles.GL10;
import javax.microedition.khronos.opengles.GL11;
import javax.microedition.khronos.opengles.GL11Ext;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.opengl.GLUtils;
import android.util.Log;
/**
* An OpenGL ES renderer based on the GLSurfaceView rendering framework. This
* class is responsible for drawing a list of renderables to the screen every
* frame. It also manages loading of textures and (when VBOs are used) the
* allocation of vertex buffer objects.
*/
public class SimpleGLRenderer implements GLSurfaceView.Renderer {
// Specifies the format our textures should be converted to upon load.
private static BitmapFactory.Options sBitmapOptions
= new BitmapFactory.Options();
// An array of things to draw every frame.
private GLSprite[] mSprites;
// Pre-allocated arrays to use at runtime so that allocation during the
// test can be avoided.
private int[] mTextureNameWorkspace;
private int[] mCropWorkspace;
// A reference to the application context.
private Context mContext;
// Determines the use of vertex arrays.
private boolean mUseVerts;
// Determines the use of vertex buffer objects.
private boolean mUseHardwareBuffers;
public SimpleGLRenderer(Context context) {
// Pre-allocate and store these objects so we can use them at runtime
// without allocating memory mid-frame.
mTextureNameWorkspace = new int[1];
mCropWorkspace = new int[4];
// Set our bitmaps to 16-bit, 565 format.
sBitmapOptions.inPreferredConfig = Bitmap.Config.RGB_565;
mContext = context;
}
public int[] getConfigSpec() {
// We don't need a depth buffer, and don't care about our
// color depth.
int[] configSpec = { EGL10.EGL_DEPTH_SIZE, 0, EGL10.EGL_NONE };
return configSpec;
}
public void setSprites(GLSprite[] sprites) {
mSprites = sprites;
}
/**
* Changes the vertex mode used for drawing.
* @param useVerts Specifies whether to use a vertex array. If false, the
* DrawTexture extension is used.
* @param useHardwareBuffers Specifies whether to store vertex arrays in
* main memory or on the graphics card. Ignored if useVerts is false.
*/
public void setVertMode(boolean useVerts, boolean useHardwareBuffers) {
mUseVerts = useVerts;
mUseHardwareBuffers = useVerts ? useHardwareBuffers : false;
}
/** Draws the sprites. */
public void drawFrame(GL10 gl) {
if (mSprites != null) {
gl.glMatrixMode(GL10.GL_MODELVIEW);
if (mUseVerts) {
Grid.beginDrawing(gl, true, false);
}
for (int x = 0; x < mSprites.length; x++) {
mSprites[x].draw(gl);
}
if (mUseVerts) {
Grid.endDrawing(gl);
}
}
}
/* Called when the size of the window changes. */
public void sizeChanged(GL10 gl, int width, int height) {
gl.glViewport(0, 0, width, height);
/*
* Set our projection matrix. This doesn't have to be done each time we
* draw, but usually a new projection needs to be set when the viewport
* is resized.
*/
gl.glMatrixMode(GL10.GL_PROJECTION);
gl.glLoadIdentity();
gl.glOrthof(0.0f, width, 0.0f, height, 0.0f, 1.0f);
gl.glShadeModel(GL10.GL_FLAT);
gl.glEnable(GL10.GL_BLEND);
gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
gl.glColor4x(0x10000, 0x10000, 0x10000, 0x10000);
gl.glEnable(GL10.GL_TEXTURE_2D);
}
/**
* Called whenever the surface is created. This happens at startup, and
* may be called again at runtime if the device context is lost (the screen
* goes to sleep, etc). This function must fill the contents of vram with
* texture data and (when using VBOs) hardware vertex arrays.
*/
public void surfaceCreated(GL10 gl) {
/*
* Some one-time OpenGL initialization can be made here probably based
* on features of this particular context
*/
gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_FASTEST);
gl.glClearColor(0.5f, 0.5f, 0.5f, 1);
gl.glShadeModel(GL10.GL_FLAT);
gl.glDisable(GL10.GL_DEPTH_TEST);
gl.glEnable(GL10.GL_TEXTURE_2D);
/*
* By default, OpenGL enables features that improve quality but reduce
* performance. One might want to tweak that especially on software
* renderer.
*/
gl.glDisable(GL10.GL_DITHER);
gl.glDisable(GL10.GL_LIGHTING);
gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
if (mSprites != null) {
// If we are using hardware buffers and the screen lost context
// then the buffer indexes that we recorded previously are now
// invalid. Forget them here and recreate them below.
if (mUseHardwareBuffers) {
for (int x = 0; x < mSprites.length; x++) {
// Ditch old buffer indexes.
mSprites[x].getGrid().invalidateHardwareBuffers();
}
}
// Load our texture and set its texture name on all sprites.
// To keep this sample simple we will assume that sprites that share
// the same texture are grouped together in our sprite list. A real
// app would probably have another level of texture management,
// like a texture hash.
int lastLoadedResource = -1;
int lastTextureId = -1;
for (int x = 0; x < mSprites.length; x++) {
int resource = mSprites[x].getResourceId();
if (resource != lastLoadedResource) {
lastTextureId = loadBitmap(mContext, gl, resource);
lastLoadedResource = resource;
}
mSprites[x].setTextureName(lastTextureId);
if (mUseHardwareBuffers) {
Grid currentGrid = mSprites[x].getGrid();
if (!currentGrid.usingHardwareBuffers()) {
currentGrid.generateHardwareBuffers(gl);
}
//mSprites[x].getGrid().generateHardwareBuffers(gl);
}
}
}
}
/**
* Called when the rendering thread shuts down. This is a good place to
* release OpenGL ES resources.
* @param gl
*/
public void shutdown(GL10 gl) {
if (mSprites != null) {
int lastFreedResource = -1;
int[] textureToDelete = new int[1];
for (int x = 0; x < mSprites.length; x++) {
int resource = mSprites[x].getResourceId();
if (resource != lastFreedResource) {
textureToDelete[0] = mSprites[x].getTextureName();
gl.glDeleteTextures(1, textureToDelete, 0);
mSprites[x].setTextureName(0);
}
if (mUseHardwareBuffers) {
mSprites[x].getGrid().releaseHardwareBuffers(gl);
}
}
}
}
/**
* Loads a bitmap into OpenGL and sets up the common parameters for
* 2D texture maps.
*/
protected int loadBitmap(Context context, GL10 gl, int resourceId) {
int textureName = -1;
if (context != null && gl != null) {
gl.glGenTextures(1, mTextureNameWorkspace, 0);
textureName = mTextureNameWorkspace[0];
gl.glBindTexture(GL10.GL_TEXTURE_2D, textureName);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_CLAMP_TO_EDGE);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_CLAMP_TO_EDGE);
gl.glTexEnvf(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE, GL10.GL_REPLACE);
InputStream is = context.getResources().openRawResource(resourceId);
Bitmap bitmap;
try {
bitmap = BitmapFactory.decodeStream(is, null, sBitmapOptions);
} finally {
try {
is.close();
} catch (IOException e) {
// Ignore.
}
}
GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0);
mCropWorkspace[0] = 0;
mCropWorkspace[1] = bitmap.getHeight();
mCropWorkspace[2] = bitmap.getWidth();
mCropWorkspace[3] = -bitmap.getHeight();
bitmap.recycle();
((GL11) gl).glTexParameteriv(GL10.GL_TEXTURE_2D,
GL11Ext.GL_TEXTURE_CROP_RECT_OES, mCropWorkspace, 0);
int error = gl.glGetError();
if (error != GL10.GL_NO_ERROR) {
Log.e("SpriteMethodTest", "Texture Load GLError: " + error);
}
}
return textureName;
}
}
| 1219806112-wangyao | SpriteMethodTest/src/com/android/spritemethodtest/SimpleGLRenderer.java | Java | asf20 | 10,357 |
/*
* Copyright (C) 2008 The Android Open Source Project
*
* 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.android.spritemethodtest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioGroup;
/**
* Main entry point for the SpriteMethodTest application. This application
* provides a simple interface for testing the relative speed of 2D rendering
* systems available on Android, namely the Canvas system and OpenGL ES. It
* also serves as an example of how SurfaceHolders can be used to create an
* efficient rendering thread for drawing.
*/
public class SpriteMethodTest extends Activity {
private static final int ACTIVITY_TEST = 0;
private static final int RESULTS_DIALOG = 0;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Sets up a click listener for the Run Test button.
Button button;
button = (Button) findViewById(R.id.runTest);
button.setOnClickListener(mRunTestListener);
// Turns on one item by default in our radio groups--as it should be!
RadioGroup group = (RadioGroup)findViewById(R.id.renderMethod);
group.setOnCheckedChangeListener(mMethodChangedListener);
group.check(R.id.methodCanvas);
RadioGroup glSettings = (RadioGroup)findViewById(R.id.GLSettings);
glSettings.check(R.id.settingVerts);
}
/** Passes preferences about the test via its intent. */
protected void initializeIntent(Intent i) {
final CheckBox checkBox = (CheckBox) findViewById(R.id.animateSprites);
final boolean animate = checkBox.isChecked();
final EditText editText = (EditText) findViewById(R.id.spriteCount);
final String spriteCountText = editText.getText().toString();
final int stringCount = Integer.parseInt(spriteCountText);
i.putExtra("animate", animate);
i.putExtra("spriteCount", stringCount);
}
/**
* Responds to a click on the Run Test button by launching a new test
* activity.
*/
View.OnClickListener mRunTestListener = new OnClickListener() {
public void onClick(View v) {
RadioGroup group = (RadioGroup)findViewById(R.id.renderMethod);
Intent i;
if (group.getCheckedRadioButtonId() == R.id.methodCanvas) {
i = new Intent(v.getContext(), CanvasTestActivity.class);
} else {
i = new Intent(v.getContext(), OpenGLTestActivity.class);
RadioGroup glSettings =
(RadioGroup)findViewById(R.id.GLSettings);
if (glSettings.getCheckedRadioButtonId() == R.id.settingVerts) {
i.putExtra("useVerts", true);
} else if (glSettings.getCheckedRadioButtonId()
== R.id.settingVBO) {
i.putExtra("useVerts", true);
i.putExtra("useHardwareBuffers", true);
}
}
initializeIntent(i);
startActivityForResult(i, ACTIVITY_TEST);
}
};
/**
* Enables or disables OpenGL ES-specific settings controls when the render
* method option changes.
*/
RadioGroup.OnCheckedChangeListener mMethodChangedListener
= new RadioGroup.OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (checkedId == R.id.methodCanvas) {
findViewById(R.id.settingDrawTexture).setEnabled(false);
findViewById(R.id.settingVerts).setEnabled(false);
findViewById(R.id.settingVBO).setEnabled(false);
} else {
findViewById(R.id.settingDrawTexture).setEnabled(true);
findViewById(R.id.settingVerts).setEnabled(true);
findViewById(R.id.settingVBO).setEnabled(true);
}
}
};
/** Creates the test results dialog and fills in a dummy message. */
@Override
protected Dialog onCreateDialog(int id) {
Dialog dialog = null;
if (id == RESULTS_DIALOG) {
String dummy = "No results yet.";
CharSequence sequence = dummy.subSequence(0, dummy.length() -1);
dialog = new AlertDialog.Builder(this)
.setTitle(R.string.dialog_title)
.setPositiveButton(R.string.dialog_ok, null)
.setMessage(sequence)
.create();
}
return dialog;
}
/**
* Replaces the dummy message in the test results dialog with a string that
* describes the actual test results.
*/
protected void onPrepareDialog (int id, Dialog dialog) {
if (id == RESULTS_DIALOG) {
// Extract final timing information from the profiler.
final ProfileRecorder profiler = ProfileRecorder.sSingleton;
final long frameTime =
profiler.getAverageTime(ProfileRecorder.PROFILE_FRAME);
final long frameMin =
profiler.getMinTime(ProfileRecorder.PROFILE_FRAME);
final long frameMax =
profiler.getMaxTime(ProfileRecorder.PROFILE_FRAME);
final long drawTime =
profiler.getAverageTime(ProfileRecorder.PROFILE_DRAW);
final long drawMin =
profiler.getMinTime(ProfileRecorder.PROFILE_DRAW);
final long drawMax =
profiler.getMaxTime(ProfileRecorder.PROFILE_DRAW);
final long flipTime =
profiler.getAverageTime(ProfileRecorder.PROFILE_PAGE_FLIP);
final long flipMin =
profiler.getMinTime(ProfileRecorder.PROFILE_PAGE_FLIP);
final long flipMax =
profiler.getMaxTime(ProfileRecorder.PROFILE_PAGE_FLIP);
final long simTime =
profiler.getAverageTime(ProfileRecorder.PROFILE_SIM);
final long simMin =
profiler.getMinTime(ProfileRecorder.PROFILE_SIM);
final long simMax =
profiler.getMaxTime(ProfileRecorder.PROFILE_SIM);
final float fps = frameTime > 0 ? 1000.0f / frameTime : 0.0f;
String result = "Frame: " + frameTime + "ms (" + fps + " fps)\n"
+ "\t\tMin: " + frameMin + "ms\t\tMax: " + frameMax + "\n"
+ "Draw: " + drawTime + "ms\n"
+ "\t\tMin: " + drawMin + "ms\t\tMax: " + drawMax + "\n"
+ "Page Flip: " + flipTime + "ms\n"
+ "\t\tMin: " + flipMin + "ms\t\tMax: " + flipMax + "\n"
+ "Sim: " + simTime + "ms\n"
+ "\t\tMin: " + simMin + "ms\t\tMax: " + simMax + "\n";
CharSequence sequence = result.subSequence(0, result.length() -1);
AlertDialog alertDialog = (AlertDialog)dialog;
alertDialog.setMessage(sequence);
}
}
/** Shows the results dialog when the test activity closes. */
@Override
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
showDialog(RESULTS_DIALOG);
}
} | 1219806112-wangyao | SpriteMethodTest/src/com/android/spritemethodtest/SpriteMethodTest.java | Java | asf20 | 8,313 |
/*
* Copyright (C) 2009 The Android Open Source Project
*
* 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.android.spritemethodtest;
import javax.microedition.khronos.opengles.GL10;
import javax.microedition.khronos.opengles.GL11Ext;
/**
* This is the OpenGL ES version of a sprite. It is more complicated than the
* CanvasSprite class because it can be used in more than one way. This class
* can draw using a grid of verts, a grid of verts stored in VBO objects, or
* using the DrawTexture extension.
*/
public class GLSprite extends Renderable {
// The OpenGL ES texture handle to draw.
private int mTextureName;
// The id of the original resource that mTextureName is based on.
private int mResourceId;
// If drawing with verts or VBO verts, the grid object defining those verts.
private Grid mGrid;
public GLSprite(int resourceId) {
super();
mResourceId = resourceId;
}
public void setTextureName(int name) {
mTextureName = name;
}
public int getTextureName() {
return mTextureName;
}
public void setResourceId(int id) {
mResourceId = id;
}
public int getResourceId() {
return mResourceId;
}
public void setGrid(Grid grid) {
mGrid = grid;
}
public Grid getGrid() {
return mGrid;
}
public void draw(GL10 gl) {
gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureName);
if (mGrid == null) {
// Draw using the DrawTexture extension.
((GL11Ext) gl).glDrawTexfOES(x, y, z, width, height);
} else {
// Draw using verts or VBO verts.
gl.glPushMatrix();
gl.glLoadIdentity();
gl.glTranslatef(
x,
y,
z);
mGrid.draw(gl, true, false);
gl.glPopMatrix();
}
}
}
| 1219806112-wangyao | SpriteMethodTest/src/com/android/spritemethodtest/GLSprite.java | Java | asf20 | 2,489 |
/*
* Copyright (C) 2009 The Android Open Source Project
*
* 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.android.spritemethodtest;
import android.graphics.Canvas;
import com.android.spritemethodtest.CanvasSurfaceView.Renderer;
/**
* An extremely simple renderer based on the CanvasSurfaceView drawing
* framework. Simply draws a list of sprites to a canvas every frame.
*/
public class SimpleCanvasRenderer implements Renderer {
private CanvasSprite[] mSprites;
public void setSprites(CanvasSprite[] sprites) {
mSprites = sprites;
}
public void drawFrame(Canvas canvas) {
if (mSprites != null) {
for (int x = 0; x < mSprites.length; x++) {
mSprites[x].draw(canvas);
}
}
}
public void sizeChanged(int width, int height) {
}
}
| 1219806112-wangyao | SpriteMethodTest/src/com/android/spritemethodtest/SimpleCanvasRenderer.java | Java | asf20 | 1,384 |
/*
* Copyright (C) 2009 The Android Open Source Project
*
* 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.android.spritemethodtest;
import android.os.SystemClock;
/**
* Implements a simple runtime profiler. The profiler records start and stop
* times for several different types of profiles and can then return min, max
* and average execution times per type. Profile types are independent and may
* be nested in calling code. This object is a singleton for convenience.
*/
public class ProfileRecorder {
// A type for recording actual draw command time.
public static final int PROFILE_DRAW = 0;
// A type for recording the time it takes to display the scene.
public static final int PROFILE_PAGE_FLIP = 1;
// A type for recording the time it takes to run a single simulation step.
public static final int PROFILE_SIM = 2;
// A type for recording the total amount of time spent rendering a frame.
public static final int PROFILE_FRAME = 3;
private static final int PROFILE_COUNT = PROFILE_FRAME + 1;
private ProfileRecord[] mProfiles;
private int mFrameCount;
public static ProfileRecorder sSingleton = new ProfileRecorder();
public ProfileRecorder() {
mProfiles = new ProfileRecord[PROFILE_COUNT];
for (int x = 0; x < PROFILE_COUNT; x++) {
mProfiles[x] = new ProfileRecord();
}
}
/** Starts recording execution time for a specific profile type.*/
public void start(int profileType) {
if (profileType < PROFILE_COUNT) {
mProfiles[profileType].start(SystemClock.uptimeMillis());
}
}
/** Stops recording time for this profile type. */
public void stop(int profileType) {
if (profileType < PROFILE_COUNT) {
mProfiles[profileType].stop(SystemClock.uptimeMillis());
}
}
/** Indicates the end of the frame.*/
public void endFrame() {
mFrameCount++;
}
/* Flushes all recorded timings from the profiler. */
public void resetAll() {
for (int x = 0; x < PROFILE_COUNT; x++) {
mProfiles[x].reset();
}
mFrameCount = 0;
}
/* Returns the average execution time, in milliseconds, for a given type. */
public long getAverageTime(int profileType) {
long time = 0;
if (profileType < PROFILE_COUNT) {
time = mProfiles[profileType].getAverageTime(mFrameCount);
}
return time;
}
/* Returns the minimum execution time in milliseconds for a given type. */
public long getMinTime(int profileType) {
long time = 0;
if (profileType < PROFILE_COUNT) {
time = mProfiles[profileType].getMinTime();
}
return time;
}
/* Returns the maximum execution time in milliseconds for a given type. */
public long getMaxTime(int profileType) {
long time = 0;
if (profileType < PROFILE_COUNT) {
time = mProfiles[profileType].getMaxTime();
}
return time;
}
/**
* A simple class for storing timing information about a single profile
* type.
*/
protected class ProfileRecord {
private long mStartTime;
private long mTotalTime;
private long mMinTime;
private long mMaxTime;
public void start(long time) {
mStartTime = time;
}
public void stop(long time) {
final long timeDelta = time - mStartTime;
mTotalTime += timeDelta;
if (mMinTime == 0 || timeDelta < mMinTime) {
mMinTime = timeDelta;
}
if (mMaxTime == 0 || timeDelta > mMaxTime) {
mMaxTime = timeDelta;
}
}
public long getAverageTime(int frameCount) {
long time = frameCount > 0 ? mTotalTime / frameCount : 0;
return time;
}
public long getMinTime() {
return mMinTime;
}
public long getMaxTime() {
return mMaxTime;
}
public void startNewProfilePeriod() {
mTotalTime = 0;
}
public void reset() {
mTotalTime = 0;
mStartTime = 0;
mMinTime = 0;
mMaxTime = 0;
}
}
}
| 1219806112-wangyao | SpriteMethodTest/src/com/android/spritemethodtest/ProfileRecorder.java | Java | asf20 | 4,931 |
/*
* Copyright (C) 2009 The Android Open Source Project
*
* 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.android.spritemethodtest;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.util.DisplayMetrics;
/**
* Activity for testing OpenGL ES drawing speed. This activity sets up sprites
* and passes them off to an OpenGLSurfaceView for rendering and movement.
*/
public class OpenGLTestActivity extends Activity {
private final static int SPRITE_WIDTH = 64;
private final static int SPRITE_HEIGHT = 64;
private GLSurfaceView mGLSurfaceView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mGLSurfaceView = new GLSurfaceView(this);
SimpleGLRenderer spriteRenderer = new SimpleGLRenderer(this);
// Clear out any old profile results.
ProfileRecorder.sSingleton.resetAll();
final Intent callingIntent = getIntent();
// Allocate our sprites and add them to an array.
final int robotCount = callingIntent.getIntExtra("spriteCount", 10);
final boolean animate = callingIntent.getBooleanExtra("animate", true);
final boolean useVerts =
callingIntent.getBooleanExtra("useVerts", false);
final boolean useHardwareBuffers =
callingIntent.getBooleanExtra("useHardwareBuffers", false);
// Allocate space for the robot sprites + one background sprite.
GLSprite[] spriteArray = new GLSprite[robotCount + 1];
// We need to know the width and height of the display pretty soon,
// so grab the information now.
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
GLSprite background = new GLSprite(R.drawable.background);
BitmapDrawable backgroundImage = (BitmapDrawable)getResources().getDrawable(R.drawable.background);
Bitmap backgoundBitmap = backgroundImage.getBitmap();
background.width = backgoundBitmap.getWidth();
background.height = backgoundBitmap.getHeight();
if (useVerts) {
// Setup the background grid. This is just a quad.
Grid backgroundGrid = new Grid(2, 2, false);
backgroundGrid.set(0, 0, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, null);
backgroundGrid.set(1, 0, background.width, 0.0f, 0.0f, 1.0f, 1.0f, null);
backgroundGrid.set(0, 1, 0.0f, background.height, 0.0f, 0.0f, 0.0f, null);
backgroundGrid.set(1, 1, background.width, background.height, 0.0f,
1.0f, 0.0f, null );
background.setGrid(backgroundGrid);
}
spriteArray[0] = background;
Grid spriteGrid = null;
if (useVerts) {
// Setup a quad for the sprites to use. All sprites will use the
// same sprite grid intance.
spriteGrid = new Grid(2, 2, false);
spriteGrid.set(0, 0, 0.0f, 0.0f, 0.0f, 0.0f , 1.0f, null);
spriteGrid.set(1, 0, SPRITE_WIDTH, 0.0f, 0.0f, 1.0f, 1.0f, null);
spriteGrid.set(0, 1, 0.0f, SPRITE_HEIGHT, 0.0f, 0.0f, 0.0f, null);
spriteGrid.set(1, 1, SPRITE_WIDTH, SPRITE_HEIGHT, 0.0f, 1.0f, 0.0f, null);
}
// This list of things to move. It points to the same content as the
// sprite list except for the background.
Renderable[] renderableArray = new Renderable[robotCount];
final int robotBucketSize = robotCount / 3;
for (int x = 0; x < robotCount; x++) {
GLSprite robot;
// Our robots come in three flavors. Split them up accordingly.
if (x < robotBucketSize) {
robot = new GLSprite(R.drawable.skate1);
} else if (x < robotBucketSize * 2) {
robot = new GLSprite(R.drawable.skate2);
} else {
robot = new GLSprite(R.drawable.skate3);
}
robot.width = SPRITE_WIDTH;
robot.height = SPRITE_HEIGHT;
// Pick a random location for this sprite.
robot.x = (float)(Math.random() * dm.widthPixels);
robot.y = (float)(Math.random() * dm.heightPixels);
// All sprites can reuse the same grid. If we're running the
// DrawTexture extension test, this is null.
robot.setGrid(spriteGrid);
// Add this robot to the spriteArray so it gets drawn and to the
// renderableArray so that it gets moved.
spriteArray[x + 1] = robot;
renderableArray[x] = robot;
}
// Now's a good time to run the GC. Since we won't do any explicit
// allocation during the test, the GC should stay dormant and not
// influence our results.
Runtime r = Runtime.getRuntime();
r.gc();
spriteRenderer.setSprites(spriteArray);
spriteRenderer.setVertMode(useVerts, useHardwareBuffers);
mGLSurfaceView.setRenderer(spriteRenderer);
if (animate) {
Mover simulationRuntime = new Mover();
simulationRuntime.setRenderables(renderableArray);
simulationRuntime.setViewSize(dm.widthPixels, dm.heightPixels);
mGLSurfaceView.setEvent(simulationRuntime);
}
setContentView(mGLSurfaceView);
}
}
| 1219806112-wangyao | SpriteMethodTest/src/com/android/spritemethodtest/OpenGLTestActivity.java | Java | asf20 | 6,189 |
/*
* Copyright (C) 2009 The Android Open Source Project
*
* 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.android.spritemethodtest;
import android.os.SystemClock;
/**
* A simple runnable that updates the position of each sprite on the screen
* every frame by applying a very simple gravity and bounce simulation. The
* sprites are jumbled with random velocities every once and a while.
*/
public class Mover implements Runnable {
private Renderable[] mRenderables;
private long mLastTime;
private long mLastJumbleTime;
private int mViewWidth;
private int mViewHeight;
static final float COEFFICIENT_OF_RESTITUTION = 0.75f;
static final float SPEED_OF_GRAVITY = 150.0f;
static final long JUMBLE_EVERYTHING_DELAY = 15 * 1000;
static final float MAX_VELOCITY = 8000.0f;
public void run() {
// Perform a single simulation step.
if (mRenderables != null) {
final long time = SystemClock.uptimeMillis();
final long timeDelta = time - mLastTime;
final float timeDeltaSeconds =
mLastTime > 0.0f ? timeDelta / 1000.0f : 0.0f;
mLastTime = time;
// Check to see if it's time to jumble again.
final boolean jumble =
(time - mLastJumbleTime > JUMBLE_EVERYTHING_DELAY);
if (jumble) {
mLastJumbleTime = time;
}
for (int x = 0; x < mRenderables.length; x++) {
Renderable object = mRenderables[x];
// Jumble! Apply random velocities.
if (jumble) {
object.velocityX += (MAX_VELOCITY / 2.0f)
- (float)(Math.random() * MAX_VELOCITY);
object.velocityY += (MAX_VELOCITY / 2.0f)
- (float)(Math.random() * MAX_VELOCITY);
}
// Move.
object.x = object.x + (object.velocityX * timeDeltaSeconds);
object.y = object.y + (object.velocityY * timeDeltaSeconds);
object.z = object.z + (object.velocityZ * timeDeltaSeconds);
// Apply Gravity.
object.velocityY -= SPEED_OF_GRAVITY * timeDeltaSeconds;
// Bounce.
if ((object.x < 0.0f && object.velocityX < 0.0f)
|| (object.x > mViewWidth - object.width
&& object.velocityX > 0.0f)) {
object.velocityX =
-object.velocityX * COEFFICIENT_OF_RESTITUTION;
object.x = Math.max(0.0f,
Math.min(object.x, mViewWidth - object.width));
if (Math.abs(object.velocityX) < 0.1f) {
object.velocityX = 0.0f;
}
}
if ((object.y < 0.0f && object.velocityY < 0.0f)
|| (object.y > mViewHeight - object.height
&& object.velocityY > 0.0f)) {
object.velocityY =
-object.velocityY * COEFFICIENT_OF_RESTITUTION;
object.y = Math.max(0.0f,
Math.min(object.y, mViewHeight - object.height));
if (Math.abs(object.velocityY) < 0.1f) {
object.velocityY = 0.0f;
}
}
}
}
}
public void setRenderables(Renderable[] renderables) {
mRenderables = renderables;
}
public void setViewSize(int width, int height) {
mViewHeight = height;
mViewWidth = width;
}
}
| 1219806112-wangyao | SpriteMethodTest/src/com/android/spritemethodtest/Mover.java | Java | asf20 | 4,381 |
/*
* Copyright (C) 2009 The Android Open Source Project
*
* 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.android.spritemethodtest;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.CharBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import javax.microedition.khronos.opengles.GL10;
import javax.microedition.khronos.opengles.GL11;
/**
* A 2D rectangular mesh. Can be drawn textured or untextured.
* This version is modified from the original Grid.java (found in
* the SpriteText package in the APIDemos Android sample) to support hardware
* vertex buffers.
*/
class Grid {
private FloatBuffer mFloatVertexBuffer;
private FloatBuffer mFloatTexCoordBuffer;
private FloatBuffer mFloatColorBuffer;
private IntBuffer mFixedVertexBuffer;
private IntBuffer mFixedTexCoordBuffer;
private IntBuffer mFixedColorBuffer;
private CharBuffer mIndexBuffer;
private Buffer mVertexBuffer;
private Buffer mTexCoordBuffer;
private Buffer mColorBuffer;
private int mCoordinateSize;
private int mCoordinateType;
private int mW;
private int mH;
private int mIndexCount;
private boolean mUseHardwareBuffers;
private int mVertBufferIndex;
private int mIndexBufferIndex;
private int mTextureCoordBufferIndex;
private int mColorBufferIndex;
public Grid(int vertsAcross, int vertsDown, boolean useFixedPoint) {
if (vertsAcross < 0 || vertsAcross >= 65536) {
throw new IllegalArgumentException("vertsAcross");
}
if (vertsDown < 0 || vertsDown >= 65536) {
throw new IllegalArgumentException("vertsDown");
}
if (vertsAcross * vertsDown >= 65536) {
throw new IllegalArgumentException("vertsAcross * vertsDown >= 65536");
}
mUseHardwareBuffers = false;
mW = vertsAcross;
mH = vertsDown;
int size = vertsAcross * vertsDown;
final int FLOAT_SIZE = 4;
final int FIXED_SIZE = 4;
final int CHAR_SIZE = 2;
if (useFixedPoint) {
mFixedVertexBuffer = ByteBuffer.allocateDirect(FIXED_SIZE * size * 3)
.order(ByteOrder.nativeOrder()).asIntBuffer();
mFixedTexCoordBuffer = ByteBuffer.allocateDirect(FIXED_SIZE * size * 2)
.order(ByteOrder.nativeOrder()).asIntBuffer();
mFixedColorBuffer = ByteBuffer.allocateDirect(FIXED_SIZE * size * 4)
.order(ByteOrder.nativeOrder()).asIntBuffer();
mVertexBuffer = mFixedVertexBuffer;
mTexCoordBuffer = mFixedTexCoordBuffer;
mColorBuffer = mFixedColorBuffer;
mCoordinateSize = FIXED_SIZE;
mCoordinateType = GL10.GL_FIXED;
} else {
mFloatVertexBuffer = ByteBuffer.allocateDirect(FLOAT_SIZE * size * 3)
.order(ByteOrder.nativeOrder()).asFloatBuffer();
mFloatTexCoordBuffer = ByteBuffer.allocateDirect(FLOAT_SIZE * size * 2)
.order(ByteOrder.nativeOrder()).asFloatBuffer();
mFloatColorBuffer = ByteBuffer.allocateDirect(FLOAT_SIZE * size * 4)
.order(ByteOrder.nativeOrder()).asFloatBuffer();
mVertexBuffer = mFloatVertexBuffer;
mTexCoordBuffer = mFloatTexCoordBuffer;
mColorBuffer = mFloatColorBuffer;
mCoordinateSize = FLOAT_SIZE;
mCoordinateType = GL10.GL_FLOAT;
}
int quadW = mW - 1;
int quadH = mH - 1;
int quadCount = quadW * quadH;
int indexCount = quadCount * 6;
mIndexCount = indexCount;
mIndexBuffer = ByteBuffer.allocateDirect(CHAR_SIZE * indexCount)
.order(ByteOrder.nativeOrder()).asCharBuffer();
/*
* Initialize triangle list mesh.
*
* [0]-----[ 1] ...
* | / |
* | / |
* | / |
* [w]-----[w+1] ...
* | |
*
*/
{
int i = 0;
for (int y = 0; y < quadH; y++) {
for (int x = 0; x < quadW; x++) {
char a = (char) (y * mW + x);
char b = (char) (y * mW + x + 1);
char c = (char) ((y + 1) * mW + x);
char d = (char) ((y + 1) * mW + x + 1);
mIndexBuffer.put(i++, a);
mIndexBuffer.put(i++, b);
mIndexBuffer.put(i++, c);
mIndexBuffer.put(i++, b);
mIndexBuffer.put(i++, c);
mIndexBuffer.put(i++, d);
}
}
}
mVertBufferIndex = 0;
}
void set(int i, int j, float x, float y, float z, float u, float v, float[] color) {
if (i < 0 || i >= mW) {
throw new IllegalArgumentException("i");
}
if (j < 0 || j >= mH) {
throw new IllegalArgumentException("j");
}
final int index = mW * j + i;
final int posIndex = index * 3;
final int texIndex = index * 2;
final int colorIndex = index * 4;
if (mCoordinateType == GL10.GL_FLOAT) {
mFloatVertexBuffer.put(posIndex, x);
mFloatVertexBuffer.put(posIndex + 1, y);
mFloatVertexBuffer.put(posIndex + 2, z);
mFloatTexCoordBuffer.put(texIndex, u);
mFloatTexCoordBuffer.put(texIndex + 1, v);
if (color != null) {
mFloatColorBuffer.put(colorIndex, color[0]);
mFloatColorBuffer.put(colorIndex + 1, color[1]);
mFloatColorBuffer.put(colorIndex + 2, color[2]);
mFloatColorBuffer.put(colorIndex + 3, color[3]);
}
} else {
mFixedVertexBuffer.put(posIndex, (int)(x * (1 << 16)));
mFixedVertexBuffer.put(posIndex + 1, (int)(y * (1 << 16)));
mFixedVertexBuffer.put(posIndex + 2, (int)(z * (1 << 16)));
mFixedTexCoordBuffer.put(texIndex, (int)(u * (1 << 16)));
mFixedTexCoordBuffer.put(texIndex + 1, (int)(v * (1 << 16)));
if (color != null) {
mFixedColorBuffer.put(colorIndex, (int)(color[0] * (1 << 16)));
mFixedColorBuffer.put(colorIndex + 1, (int)(color[1] * (1 << 16)));
mFixedColorBuffer.put(colorIndex + 2, (int)(color[2] * (1 << 16)));
mFixedColorBuffer.put(colorIndex + 3, (int)(color[3] * (1 << 16)));
}
}
}
public static void beginDrawing(GL10 gl, boolean useTexture, boolean useColor) {
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
if (useTexture) {
gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
gl.glEnable(GL10.GL_TEXTURE_2D);
} else {
gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
gl.glDisable(GL10.GL_TEXTURE_2D);
}
if (useColor) {
gl.glEnableClientState(GL10.GL_COLOR_ARRAY);
} else {
gl.glDisableClientState(GL10.GL_COLOR_ARRAY);
}
}
public void draw(GL10 gl, boolean useTexture, boolean useColor) {
if (!mUseHardwareBuffers) {
gl.glVertexPointer(3, mCoordinateType, 0, mVertexBuffer);
if (useTexture) {
gl.glTexCoordPointer(2, mCoordinateType, 0, mTexCoordBuffer);
}
if (useColor) {
gl.glColorPointer(4, mCoordinateType, 0, mColorBuffer);
}
gl.glDrawElements(GL10.GL_TRIANGLES, mIndexCount,
GL10.GL_UNSIGNED_SHORT, mIndexBuffer);
} else {
GL11 gl11 = (GL11)gl;
// draw using hardware buffers
gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, mVertBufferIndex);
gl11.glVertexPointer(3, mCoordinateType, 0, 0);
if (useTexture) {
gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, mTextureCoordBufferIndex);
gl11.glTexCoordPointer(2, mCoordinateType, 0, 0);
}
if (useColor) {
gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, mColorBufferIndex);
gl11.glColorPointer(4, mCoordinateType, 0, 0);
}
gl11.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, mIndexBufferIndex);
gl11.glDrawElements(GL11.GL_TRIANGLES, mIndexCount,
GL11.GL_UNSIGNED_SHORT, 0);
gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, 0);
gl11.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, 0);
}
}
public static void endDrawing(GL10 gl) {
gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
}
public boolean usingHardwareBuffers() {
return mUseHardwareBuffers;
}
/**
* When the OpenGL ES device is lost, GL handles become invalidated.
* In that case, we just want to "forget" the old handles (without
* explicitly deleting them) and make new ones.
*/
public void invalidateHardwareBuffers() {
mVertBufferIndex = 0;
mIndexBufferIndex = 0;
mTextureCoordBufferIndex = 0;
mColorBufferIndex = 0;
mUseHardwareBuffers = false;
}
/**
* Deletes the hardware buffers allocated by this object (if any).
*/
public void releaseHardwareBuffers(GL10 gl) {
if (mUseHardwareBuffers) {
if (gl instanceof GL11) {
GL11 gl11 = (GL11)gl;
int[] buffer = new int[1];
buffer[0] = mVertBufferIndex;
gl11.glDeleteBuffers(1, buffer, 0);
buffer[0] = mTextureCoordBufferIndex;
gl11.glDeleteBuffers(1, buffer, 0);
buffer[0] = mColorBufferIndex;
gl11.glDeleteBuffers(1, buffer, 0);
buffer[0] = mIndexBufferIndex;
gl11.glDeleteBuffers(1, buffer, 0);
}
invalidateHardwareBuffers();
}
}
/**
* Allocates hardware buffers on the graphics card and fills them with
* data if a buffer has not already been previously allocated. Note that
* this function uses the GL_OES_vertex_buffer_object extension, which is
* not guaranteed to be supported on every device.
* @param gl A pointer to the OpenGL ES context.
*/
public void generateHardwareBuffers(GL10 gl) {
if (!mUseHardwareBuffers) {
if (gl instanceof GL11) {
GL11 gl11 = (GL11)gl;
int[] buffer = new int[1];
// Allocate and fill the vertex buffer.
gl11.glGenBuffers(1, buffer, 0);
mVertBufferIndex = buffer[0];
gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, mVertBufferIndex);
final int vertexSize = mVertexBuffer.capacity() * mCoordinateSize;
gl11.glBufferData(GL11.GL_ARRAY_BUFFER, vertexSize,
mVertexBuffer, GL11.GL_STATIC_DRAW);
// Allocate and fill the texture coordinate buffer.
gl11.glGenBuffers(1, buffer, 0);
mTextureCoordBufferIndex = buffer[0];
gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER,
mTextureCoordBufferIndex);
final int texCoordSize =
mTexCoordBuffer.capacity() * mCoordinateSize;
gl11.glBufferData(GL11.GL_ARRAY_BUFFER, texCoordSize,
mTexCoordBuffer, GL11.GL_STATIC_DRAW);
// Allocate and fill the color buffer.
gl11.glGenBuffers(1, buffer, 0);
mColorBufferIndex = buffer[0];
gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER,
mColorBufferIndex);
final int colorSize =
mColorBuffer.capacity() * mCoordinateSize;
gl11.glBufferData(GL11.GL_ARRAY_BUFFER, colorSize,
mColorBuffer, GL11.GL_STATIC_DRAW);
// Unbind the array buffer.
gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, 0);
// Allocate and fill the index buffer.
gl11.glGenBuffers(1, buffer, 0);
mIndexBufferIndex = buffer[0];
gl11.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER,
mIndexBufferIndex);
// A char is 2 bytes.
final int indexSize = mIndexBuffer.capacity() * 2;
gl11.glBufferData(GL11.GL_ELEMENT_ARRAY_BUFFER, indexSize, mIndexBuffer,
GL11.GL_STATIC_DRAW);
// Unbind the element array buffer.
gl11.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, 0);
mUseHardwareBuffers = true;
assert mVertBufferIndex != 0;
assert mTextureCoordBufferIndex != 0;
assert mIndexBufferIndex != 0;
assert gl11.glGetError() == 0;
}
}
}
// These functions exposed to patch Grid info into native code.
public final int getVertexBuffer() {
return mVertBufferIndex;
}
public final int getTextureBuffer() {
return mTextureCoordBufferIndex;
}
public final int getIndexBuffer() {
return mIndexBufferIndex;
}
public final int getColorBuffer() {
return mColorBufferIndex;
}
public final int getIndexCount() {
return mIndexCount;
}
public boolean getFixedPoint() {
return (mCoordinateType == GL10.GL_FIXED);
}
}
| 1219806112-wangyao | SpriteMethodTest/src/com/android/spritemethodtest/Grid.java | Java | asf20 | 14,378 |
/*
* Copyright (C) 2009 The Android Open Source Project
*
* 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.android.spritemethodtest;
import java.io.IOException;
import java.io.InputStream;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.DisplayMetrics;
/**
* Activity for testing Canvas drawing speed. This activity sets up sprites and
* passes them off to a CanvasSurfaceView for rendering and movement. It is
* very similar to OpenGLTestActivity. Note that Bitmap objects come out of a
* pool and must be explicitly recycled on shutdown. See onDestroy().
*/
public class CanvasTestActivity extends Activity {
private CanvasSurfaceView mCanvasSurfaceView;
// Describes the image format our bitmaps should be converted to.
private static BitmapFactory.Options sBitmapOptions
= new BitmapFactory.Options();
private Bitmap[] mBitmaps;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mCanvasSurfaceView = new CanvasSurfaceView(this);
SimpleCanvasRenderer spriteRenderer = new SimpleCanvasRenderer();
// Sets our preferred image format to 16-bit, 565 format.
sBitmapOptions.inPreferredConfig = Bitmap.Config.RGB_565;
// Clear out any old profile results.
ProfileRecorder.sSingleton.resetAll();
final Intent callingIntent = getIntent();
// Allocate our sprites and add them to an array.
final int robotCount = callingIntent.getIntExtra("spriteCount", 10);
final boolean animate = callingIntent.getBooleanExtra("animate", true);
// Allocate space for the robot sprites + one background sprite.
CanvasSprite[] spriteArray = new CanvasSprite[robotCount + 1];
mBitmaps = new Bitmap[4];
mBitmaps[0] = loadBitmap(this, R.drawable.background);
mBitmaps[1] = loadBitmap(this, R.drawable.skate1);
mBitmaps[2] = loadBitmap(this, R.drawable.skate2);
mBitmaps[3] = loadBitmap(this, R.drawable.skate3);
// We need to know the width and height of the display pretty soon,
// so grab the information now.
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
// Make the background.
// Note that the background image is larger than the screen,
// so some clipping will occur when it is drawn.
CanvasSprite background = new CanvasSprite(mBitmaps[0]);
background.width = mBitmaps[0].getWidth();
background.height = mBitmaps[0].getHeight();
spriteArray[0] = background;
// This list of things to move. It points to the same content as
// spriteArray except for the background.
Renderable[] renderableArray = new Renderable[robotCount];
final int robotBucketSize = robotCount / 3;
for (int x = 0; x < robotCount; x++) {
CanvasSprite robot;
// Our robots come in three flavors. Split them up accordingly.
if (x < robotBucketSize) {
robot = new CanvasSprite(mBitmaps[1]);
} else if (x < robotBucketSize * 2) {
robot = new CanvasSprite(mBitmaps[2]);
} else {
robot = new CanvasSprite(mBitmaps[3]);
}
robot.width = 64;
robot.height = 64;
// Pick a random location for this sprite.
robot.x = (float)(Math.random() * dm.widthPixels);
robot.y = (float)(Math.random() * dm.heightPixels);
// Add this robot to the spriteArray so it gets drawn and to the
// renderableArray so that it gets moved.
spriteArray[x + 1] = robot;
renderableArray[x] = robot;
}
// Now's a good time to run the GC. Since we won't do any explicit
// allocation during the test, the GC should stay dormant and not
// influence our results.
Runtime r = Runtime.getRuntime();
r.gc();
spriteRenderer.setSprites(spriteArray);
mCanvasSurfaceView.setRenderer(spriteRenderer);
if (animate) {
Mover simulationRuntime = new Mover();
simulationRuntime.setRenderables(renderableArray);
simulationRuntime.setViewSize(dm.widthPixels, dm.heightPixels);
mCanvasSurfaceView.setEvent(simulationRuntime);
}
setContentView(mCanvasSurfaceView);
}
/** Recycles all of the bitmaps loaded in onCreate(). */
@Override
protected void onDestroy() {
super.onDestroy();
mCanvasSurfaceView.clearEvent();
mCanvasSurfaceView.stopDrawing();
for (int x = 0; x < mBitmaps.length; x++) {
mBitmaps[x].recycle();
mBitmaps[x] = null;
}
}
/**
* Loads a bitmap from a resource and converts it to a bitmap. This is
* a much-simplified version of the loadBitmap() that appears in
* SimpleGLRenderer.
* @param context The application context.
* @param resourceId The id of the resource to load.
* @return A bitmap containing the image contents of the resource, or null
* if there was an error.
*/
protected Bitmap loadBitmap(Context context, int resourceId) {
Bitmap bitmap = null;
if (context != null) {
InputStream is = context.getResources().openRawResource(resourceId);
try {
bitmap = BitmapFactory.decodeStream(is, null, sBitmapOptions);
} finally {
try {
is.close();
} catch (IOException e) {
// Ignore.
}
}
}
return bitmap;
}
}
| 1219806112-wangyao | SpriteMethodTest/src/com/android/spritemethodtest/CanvasTestActivity.java | Java | asf20 | 6,609 |
/*
* Copyright (C) 2009 The Android Open Source Project
*
* 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.
*/
// This file was lifted from the APIDemos sample. See:
// http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/index.html
package com.android.spritemethodtest;
import java.util.concurrent.Semaphore;
import javax.microedition.khronos.egl.EGL10;
import javax.microedition.khronos.egl.EGL11;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.egl.EGLContext;
import javax.microedition.khronos.egl.EGLDisplay;
import javax.microedition.khronos.egl.EGLSurface;
import javax.microedition.khronos.opengles.GL;
import javax.microedition.khronos.opengles.GL10;
import android.content.Context;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
/**
* An implementation of SurfaceView that uses the dedicated surface for
* displaying an OpenGL animation. This allows the animation to run in a
* separate thread, without requiring that it be driven by the update mechanism
* of the view hierarchy.
*
* The application-specific rendering code is delegated to a GLView.Renderer
* instance.
*/
public class GLSurfaceView extends SurfaceView implements SurfaceHolder.Callback {
public GLSurfaceView(Context context) {
super(context);
init();
}
public GLSurfaceView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed
mHolder = getHolder();
mHolder.addCallback(this);
mHolder.setType(SurfaceHolder.SURFACE_TYPE_GPU);
}
public SurfaceHolder getSurfaceHolder() {
return mHolder;
}
public void setGLWrapper(GLWrapper glWrapper) {
mGLWrapper = glWrapper;
}
public void setRenderer(Renderer renderer) {
mGLThread = new GLThread(renderer);
mGLThread.start();
}
public void surfaceCreated(SurfaceHolder holder) {
mGLThread.surfaceCreated();
}
public void surfaceDestroyed(SurfaceHolder holder) {
// Surface will be destroyed when we return
mGLThread.surfaceDestroyed();
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
// Surface size or format has changed. This should not happen in this
// example.
mGLThread.onWindowResize(w, h);
}
/**
* Inform the view that the activity is paused.
*/
public void onPause() {
mGLThread.onPause();
}
/**
* Inform the view that the activity is resumed.
*/
public void onResume() {
mGLThread.onResume();
}
/**
* Inform the view that the window focus has changed.
*/
@Override public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
mGLThread.onWindowFocusChanged(hasFocus);
}
/**
* Set an "event" to be run on the GL rendering thread.
* @param r the runnable to be run on the GL rendering thread.
*/
public void setEvent(Runnable r) {
mGLThread.setEvent(r);
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
mGLThread.requestExitAndWait();
}
// ----------------------------------------------------------------------
public interface GLWrapper {
GL wrap(GL gl);
}
// ----------------------------------------------------------------------
/**
* A generic renderer interface.
*/
public interface Renderer {
/**
* @return the EGL configuration specification desired by the renderer.
*/
int[] getConfigSpec();
/**
* Surface created.
* Called when the surface is created. Called when the application
* starts, and whenever the GPU is reinitialized. This will
* typically happen when the device awakes after going to sleep.
* Set your textures here.
*/
void surfaceCreated(GL10 gl);
/**
* Called when the rendering thread is about to shut down. This is a
* good place to release OpenGL ES resources (textures, buffers, etc).
* @param gl
*/
void shutdown(GL10 gl);
/**
* Surface changed size.
* Called after the surface is created and whenever
* the OpenGL ES surface size changes. Set your viewport here.
* @param gl
* @param width
* @param height
*/
void sizeChanged(GL10 gl, int width, int height);
/**
* Draw the current frame.
* @param gl
*/
void drawFrame(GL10 gl);
}
/**
* An EGL helper class.
*/
private class EglHelper {
public EglHelper() {
}
/**
* Initialize EGL for a given configuration spec.
* @param configSpec
*/
public void start(int[] configSpec){
/*
* Get an EGL instance
*/
mEgl = (EGL10) EGLContext.getEGL();
/*
* Get to the default display.
*/
mEglDisplay = mEgl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY);
/*
* We can now initialize EGL for that display
*/
int[] version = new int[2];
mEgl.eglInitialize(mEglDisplay, version);
EGLConfig[] configs = new EGLConfig[1];
int[] num_config = new int[1];
mEgl.eglChooseConfig(mEglDisplay, configSpec, configs, 1,
num_config);
mEglConfig = configs[0];
/*
* Create an OpenGL ES context. This must be done only once, an
* OpenGL context is a somewhat heavy object.
*/
mEglContext = mEgl.eglCreateContext(mEglDisplay, mEglConfig,
EGL10.EGL_NO_CONTEXT, null);
mEglSurface = null;
}
/*
* Create and return an OpenGL surface
*/
public GL createSurface(SurfaceHolder holder) {
/*
* The window size has changed, so we need to create a new
* surface.
*/
if (mEglSurface != null) {
/*
* Unbind and destroy the old EGL surface, if
* there is one.
*/
mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE,
EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT);
mEgl.eglDestroySurface(mEglDisplay, mEglSurface);
}
/*
* Create an EGL surface we can render into.
*/
mEglSurface = mEgl.eglCreateWindowSurface(mEglDisplay,
mEglConfig, holder, null);
/*
* Before we can issue GL commands, we need to make sure
* the context is current and bound to a surface.
*/
mEgl.eglMakeCurrent(mEglDisplay, mEglSurface, mEglSurface,
mEglContext);
GL gl = mEglContext.getGL();
if (mGLWrapper != null) {
gl = mGLWrapper.wrap(gl);
}
return gl;
}
/**
* Display the current render surface.
* @return false if the context has been lost.
*/
public boolean swap() {
mEgl.eglSwapBuffers(mEglDisplay, mEglSurface);
/*
* Always check for EGL_CONTEXT_LOST, which means the context
* and all associated data were lost (For instance because
* the device went to sleep). We need to sleep until we
* get a new surface.
*/
return mEgl.eglGetError() != EGL11.EGL_CONTEXT_LOST;
}
public void finish() {
if (mEglSurface != null) {
mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE,
EGL10.EGL_NO_SURFACE,
EGL10.EGL_NO_CONTEXT);
mEgl.eglDestroySurface(mEglDisplay, mEglSurface);
mEglSurface = null;
}
if (mEglContext != null) {
mEgl.eglDestroyContext(mEglDisplay, mEglContext);
mEglContext = null;
}
if (mEglDisplay != null) {
mEgl.eglTerminate(mEglDisplay);
mEglDisplay = null;
}
}
EGL10 mEgl;
EGLDisplay mEglDisplay;
EGLSurface mEglSurface;
EGLConfig mEglConfig;
EGLContext mEglContext;
}
/**
* A generic GL Thread. Takes care of initializing EGL and GL. Delegates
* to a Renderer instance to do the actual drawing.
*
*/
class GLThread extends Thread {
GLThread(Renderer renderer) {
super();
mDone = false;
mWidth = 0;
mHeight = 0;
mRenderer = renderer;
setName("GLThread");
}
@Override
public void run() {
/*
* When the android framework launches a second instance of
* an activity, the new instance's onCreate() method may be
* called before the first instance returns from onDestroy().
*
* This semaphore ensures that only one instance at a time
* accesses EGL.
*/
try {
try {
sEglSemaphore.acquire();
} catch (InterruptedException e) {
return;
}
guardedRun();
} catch (InterruptedException e) {
// fall thru and exit normally
} finally {
sEglSemaphore.release();
}
}
private void guardedRun() throws InterruptedException {
mEglHelper = new EglHelper();
/*
* Specify a configuration for our opengl session
* and grab the first configuration that matches is
*/
int[] configSpec = mRenderer.getConfigSpec();
mEglHelper.start(configSpec);
GL10 gl = null;
boolean tellRendererSurfaceCreated = true;
boolean tellRendererSurfaceChanged = true;
/*
* This is our main activity thread's loop, we go until
* asked to quit.
*/
while (!mDone) {
ProfileRecorder.sSingleton.start(ProfileRecorder.PROFILE_FRAME);
/*
* Update the asynchronous state (window size)
*/
int w, h;
boolean changed;
boolean needStart = false;
synchronized (this) {
if (mEvent != null) {
ProfileRecorder.sSingleton.start(ProfileRecorder.PROFILE_SIM);
mEvent.run();
ProfileRecorder.sSingleton.stop(ProfileRecorder.PROFILE_SIM);
}
if (mPaused) {
mEglHelper.finish();
needStart = true;
}
if(needToWait()) {
while (needToWait()) {
wait();
}
}
if (mDone) {
break;
}
changed = mSizeChanged;
w = mWidth;
h = mHeight;
mSizeChanged = false;
}
if (needStart) {
mEglHelper.start(configSpec);
tellRendererSurfaceCreated = true;
changed = true;
}
if (changed) {
gl = (GL10) mEglHelper.createSurface(mHolder);
tellRendererSurfaceChanged = true;
}
if (tellRendererSurfaceCreated) {
mRenderer.surfaceCreated(gl);
tellRendererSurfaceCreated = false;
}
if (tellRendererSurfaceChanged) {
mRenderer.sizeChanged(gl, w, h);
tellRendererSurfaceChanged = false;
}
if ((w > 0) && (h > 0)) {
ProfileRecorder.sSingleton.start(ProfileRecorder.PROFILE_DRAW);
/* draw a frame here */
mRenderer.drawFrame(gl);
ProfileRecorder.sSingleton.stop(ProfileRecorder.PROFILE_DRAW);
/*
* Once we're done with GL, we need to call swapBuffers()
* to instruct the system to display the rendered frame
*/
ProfileRecorder.sSingleton.start(ProfileRecorder.PROFILE_PAGE_FLIP);
mEglHelper.swap();
ProfileRecorder.sSingleton.stop(ProfileRecorder.PROFILE_PAGE_FLIP);
}
ProfileRecorder.sSingleton.stop(ProfileRecorder.PROFILE_FRAME);
ProfileRecorder.sSingleton.endFrame();
}
/*
* clean-up everything...
*/
if (gl != null) {
mRenderer.shutdown(gl);
}
mEglHelper.finish();
}
private boolean needToWait() {
return (mPaused || (! mHasFocus) || (! mHasSurface) || mContextLost)
&& (! mDone);
}
public void surfaceCreated() {
synchronized(this) {
mHasSurface = true;
mContextLost = false;
notify();
}
}
public void surfaceDestroyed() {
synchronized(this) {
mHasSurface = false;
notify();
}
}
public void onPause() {
synchronized (this) {
mPaused = true;
}
}
public void onResume() {
synchronized (this) {
mPaused = false;
notify();
}
}
public void onWindowFocusChanged(boolean hasFocus) {
synchronized (this) {
mHasFocus = hasFocus;
if (mHasFocus == true) {
notify();
}
}
}
public void onWindowResize(int w, int h) {
synchronized (this) {
mWidth = w;
mHeight = h;
mSizeChanged = true;
}
}
public void requestExitAndWait() {
// don't call this from GLThread thread or it is a guaranteed
// deadlock!
synchronized(this) {
mDone = true;
notify();
}
try {
join();
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
/**
* Queue an "event" to be run on the GL rendering thread.
* @param r the runnable to be run on the GL rendering thread.
*/
public void setEvent(Runnable r) {
synchronized(this) {
mEvent = r;
}
}
public void clearEvent() {
synchronized(this) {
mEvent = null;
}
}
private boolean mDone;
private boolean mPaused;
private boolean mHasFocus;
private boolean mHasSurface;
private boolean mContextLost;
private int mWidth;
private int mHeight;
private Renderer mRenderer;
private Runnable mEvent;
private EglHelper mEglHelper;
}
private static final Semaphore sEglSemaphore = new Semaphore(1);
private boolean mSizeChanged = true;
private SurfaceHolder mHolder;
private GLThread mGLThread;
private GLWrapper mGLWrapper;
}
| 1219806112-wangyao | SpriteMethodTest/src/com/android/spritemethodtest/GLSurfaceView.java | Java | asf20 | 16,883 |