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
/* * 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; } }; }
zzys3228-fanfou
src/com/ch_linghu/fanfoudroid/WriteDmActivity.java
Java
asf20
12,236
/* * Copyright (C) 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ch_linghu.fanfoudroid; import java.util.ArrayList; import java.util.List; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.AdapterContextMenuInfo; import com.ch_linghu.fanfoudroid.data.Tweet; import com.ch_linghu.fanfoudroid.db.StatusTable; import com.ch_linghu.fanfoudroid.fanfou.Paging; import com.ch_linghu.fanfoudroid.fanfou.Status; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.task.GenericTask; import com.ch_linghu.fanfoudroid.task.TaskAdapter; import com.ch_linghu.fanfoudroid.task.TaskListener; import com.ch_linghu.fanfoudroid.task.TaskParams; import com.ch_linghu.fanfoudroid.task.TaskResult; import com.ch_linghu.fanfoudroid.task.TweetCommonTask; import com.ch_linghu.fanfoudroid.ui.base.TwitterCursorBaseActivity; import com.ch_linghu.fanfoudroid.R; public class TwitterActivity extends TwitterCursorBaseActivity { private static final String TAG = "TwitterActivity"; private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.TWEETS"; protected GenericTask mDeleteTask; private TaskListener mDeleteTaskListener = new TaskAdapter() { @Override public String getName() { return "DeleteTask"; } @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.AUTH_ERROR) { logout(); } else if (result == TaskResult.OK) { onDeleteSuccess(); } else if (result == TaskResult.IO_ERROR) { onDeleteFailure(); } } }; static final int DIALOG_WRITE_ID = 0; public static Intent createIntent(Context context) { Intent intent = new Intent(LAUNCH_ACTION); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); return intent; } public static Intent createNewTaskIntent(Context context) { Intent intent = createIntent(context); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); return intent; } @Override protected boolean _onCreate(Bundle savedInstanceState) { if (super._onCreate(savedInstanceState)) { mNavbar.setHeaderTitle("饭否fanfou.com"); // 仅在这个页面进行schedule的处理 manageUpdateChecks(); return true; } else { return false; } } @Override protected void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); if (mDeleteTask != null && mDeleteTask.getStatus() == GenericTask.Status.RUNNING) { mDeleteTask.cancel(true); } } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (mDeleteTask != null && mDeleteTask.getStatus() == GenericTask.Status.RUNNING) { outState.putBoolean(SIS_RUNNING_KEY, true); } } // Menu. @Override public boolean onCreateOptionsMenu(Menu menu) { return super.onCreateOptionsMenu(menu); } private int CONTEXT_DELETE_ID = getLastContextMenuId() + 1; @Override protected int getLastContextMenuId() { return CONTEXT_DELETE_ID; } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); AdapterView.AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo; Tweet tweet = getContextItemTweet(info.position); if (null != tweet) {// 当按钮为 刷新/更多的时候为空 if (tweet.userId.equals(TwitterApplication.getMyselfId(false))) { menu.add(0, CONTEXT_DELETE_ID, 0, R.string.cmenu_delete); } } } @Override public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) item .getMenuInfo(); Tweet tweet = getContextItemTweet(info.position); if (tweet == null) { Log.w(TAG, "Selected item not available."); return super.onContextItemSelected(item); } if (item.getItemId() == CONTEXT_DELETE_ID) { doDelete(tweet.id); return true; } else { return super.onContextItemSelected(item); } } @SuppressWarnings("deprecation") @Override protected Cursor fetchMessages() { return getDb().fetchAllTweets(getUserId(), StatusTable.TYPE_HOME); } @Override protected String getActivityTitle() { return getResources().getString(R.string.page_title_home); } @Override protected void markAllRead() { getDb().markAllTweetsRead(getUserId(), StatusTable.TYPE_HOME); } // hasRetrieveListTask interface @Override public int addMessages(ArrayList<Tweet> tweets, boolean isUnread) { // 获取消息的时候,将status里获取的user也存储到数据库 // ::MARK:: for (Tweet t : tweets) { getDb().createWeiboUserInfo(t.user); } return getDb().putTweets(tweets, getUserId(), StatusTable.TYPE_HOME, isUnread); } @Override public String fetchMaxId() { return getDb().fetchMaxTweetId(getUserId(), StatusTable.TYPE_HOME); } @Override public List<Status> getMessageSinceId(String maxId) throws HttpException { if (maxId != null) { return getApi().getFriendsTimeline(new Paging(maxId)); } else { return getApi().getFriendsTimeline(); } } public void onDeleteFailure() { Log.e(TAG, "Delete failed"); } public void onDeleteSuccess() { mTweetAdapter.refresh(); } private void doDelete(String id) { if (mDeleteTask != null && mDeleteTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { mDeleteTask = new TweetCommonTask.DeleteTask(this); mDeleteTask.setListener(mDeleteTaskListener); TaskParams params = new TaskParams(); params.put("id", id); mDeleteTask.execute(params); } } @Override public String fetchMinId() { return getDb().fetchMinTweetId(getUserId(), StatusTable.TYPE_HOME); } @Override public List<Status> getMoreMessageFromId(String minId) throws HttpException { Paging paging = new Paging(1, 20); paging.setMaxId(minId); return getApi().getFriendsTimeline(paging); } @Override public int getDatabaseType() { return StatusTable.TYPE_HOME; } @Override public String getUserId() { return TwitterApplication.getMyselfId(false); } }
zzys3228-fanfou
src/com/ch_linghu/fanfoudroid/TwitterActivity.java
Java
asf20
6,852
package com.ch_linghu.fanfoudroid; import java.util.ArrayList; import java.util.List; import android.app.ActivityManager; import android.app.ActivityManager.RunningServiceInfo; import android.app.PendingIntent; import android.appwidget.AppWidgetManager; import android.appwidget.AppWidgetProvider; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.hardware.SensorManager; import android.util.Log; import android.widget.RemoteViews; import com.ch_linghu.fanfoudroid.app.LazyImageLoader.ImageLoaderCallback; import com.ch_linghu.fanfoudroid.data.Tweet; import com.ch_linghu.fanfoudroid.db.StatusTable; import com.ch_linghu.fanfoudroid.db.TwitterDatabase; import com.ch_linghu.fanfoudroid.service.TwitterService; import com.ch_linghu.fanfoudroid.util.DateTimeHelper; import com.ch_linghu.fanfoudroid.util.TextHelper; import com.ch_linghu.fanfoudroid.R; public class FanfouWidgetSmall extends AppWidgetProvider { public final String TAG = "FanfouWidgetSmall"; public final String NEXTACTION = "com.ch_linghu.fanfoudroid.FanfouWidgetSmall.NEXT"; public final String PREACTION = "com.ch_linghu.fanfoudroid.FanfouWidgetSmall.PREV"; private static List<Tweet> tweets; private SensorManager sensorManager; private static int position = 0; class CacheCallback implements ImageLoaderCallback { private RemoteViews updateViews; CacheCallback(RemoteViews updateViews) { this.updateViews = updateViews; } @Override public void refresh(String url, Bitmap bitmap) { // updateViews.setImageViewBitmap(R.id.small_status_image, bitmap); } } @Override public void onUpdate(Context context, AppWidgetManager appwidgetmanager, int[] appWidgetIds) { Log.d(TAG, "onUpdate"); TwitterService.setWidgetStatus(true); // if (!isRunning(context, WidgetService.class.getName())) { // Intent i = new Intent(context, WidgetService.class); // context.startService(i); // } update(context); } private void update(Context context) { fetchMessages(); position = 0; refreshView(context, NEXTACTION); } private TwitterDatabase getDb() { return TwitterApplication.mDb; } public String getUserId() { return TwitterApplication.getMyselfId(false); } private void fetchMessages() { if (tweets == null) { tweets = new ArrayList<Tweet>(); } else { tweets.clear(); } Cursor cursor = getDb().fetchAllTweets(getUserId(), StatusTable.TYPE_HOME); if (cursor != null) { if (cursor.moveToFirst()) { do { Tweet tweet = StatusTable.parseCursor(cursor); tweets.add(tweet); } while (cursor.moveToNext()); } } Log.d(TAG, "Tweets size " + tweets.size()); } private void refreshView(Context context) { ComponentName fanfouWidget = new ComponentName(context, FanfouWidgetSmall.class); AppWidgetManager manager = AppWidgetManager.getInstance(context); manager.updateAppWidget(fanfouWidget, buildLogin(context)); } private RemoteViews buildLogin(Context context) { RemoteViews updateViews = new RemoteViews(context.getPackageName(), R.layout.widget_small_initial_layout); // updateViews.setTextViewText(R.id.small_status_text, // TextHelper.getSimpleTweetText("请登录")); // updateViews.setTextViewText(R.id.small_status_screen_name, ""); // updateViews.setTextViewText(R.id.small_tweet_source, ""); // updateViews.setTextViewText(R.id.small_tweet_created_at, ""); return updateViews; } private void refreshView(Context context, String action) { // 某些情况下,tweets会为null if (tweets == null) { fetchMessages(); } // 防止引发IndexOutOfBoundsException if (tweets.size() != 0) { if (action.equals(NEXTACTION)) { --position; } else if (action.equals(PREACTION)) { ++position; } // Log.d(TAG, "Tweets size =" + tweets.size()); if (position >= tweets.size() || position < 0) { position = 0; } // Log.d(TAG, "position=" + position); ComponentName fanfouWidget = new ComponentName(context, FanfouWidgetSmall.class); AppWidgetManager manager = AppWidgetManager.getInstance(context); manager.updateAppWidget(fanfouWidget, buildUpdate(context)); } } public RemoteViews buildUpdate(Context context) { RemoteViews updateViews = new RemoteViews(context.getPackageName(), R.layout.widget_small_initial_layout); Tweet t = tweets.get(position); Log.d(TAG, "tweet=" + t); // updateViews.setTextViewText(R.id.small_status_screen_name, t.screenName); // updateViews.setTextViewText(R.id.small_status_text, // TextHelper.getSimpleTweetText(t.text)); // // updateViews.setTextViewText(R.id.small_tweet_source, // context.getString(R.string.tweet_source_prefix) + t.source); // updateViews.setTextViewText(R.id.small_tweet_created_at, // DateTimeHelper.getRelativeDate(t.createdAt)); // // updateViews.setImageViewBitmap(R.id.small_status_image, // TwitterApplication.mImageLoader.get(t.profileImageUrl, // new CacheCallback(updateViews))); // Intent inext = new Intent(context, FanfouWidgetSmall.class); // inext.setAction(NEXTACTION); // PendingIntent pinext = PendingIntent.getBroadcast(context, 0, inext, // PendingIntent.FLAG_UPDATE_CURRENT); // updateViews.setOnClickPendingIntent(R.id.small_btn_next, pinext); // Intent ipre = new Intent(context, FanfouWidgetSmall.class); // ipre.setAction(PREACTION); // PendingIntent pipre = PendingIntent.getBroadcast(context, 0, ipre, // PendingIntent.FLAG_UPDATE_CURRENT); // updateViews.setOnClickPendingIntent(R.id.small_btn_pre, pipre); Intent write = WriteActivity.createNewTweetIntent(""); PendingIntent piwrite = PendingIntent.getActivity(context, 0, write, PendingIntent.FLAG_UPDATE_CURRENT); updateViews.setOnClickPendingIntent(R.id.small_write_message, piwrite); Intent home = TwitterActivity.createIntent(context); PendingIntent pihome = PendingIntent.getActivity(context, 0, home, PendingIntent.FLAG_UPDATE_CURRENT); updateViews.setOnClickPendingIntent(R.id.small_logo_image, pihome); Intent status = StatusActivity.createIntent(t); PendingIntent pistatus = PendingIntent.getActivity(context, 0, status, PendingIntent.FLAG_UPDATE_CURRENT); // updateViews.setOnClickPendingIntent(R.id.small_main_body, pistatus); return updateViews; } @Override public void onReceive(Context context, Intent intent) { Log.d(TAG, "OnReceive"); // FIXME: NullPointerException Log.i(TAG, context.getApplicationContext().toString()); if (!TwitterApplication.mApi.isLoggedIn()) { refreshView(context); } else { super.onReceive(context, intent); String action = intent.getAction(); if (NEXTACTION.equals(action) || PREACTION.equals(action)) { refreshView(context, intent.getAction()); } else if (AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action)) { update(context); } } } /** * * @param c * @param serviceName * @return */ @Deprecated public boolean isRunning(Context c, String serviceName) { ActivityManager myAM = (ActivityManager) c .getSystemService(Context.ACTIVITY_SERVICE); ArrayList<RunningServiceInfo> runningServices = (ArrayList<RunningServiceInfo>) myAM .getRunningServices(40); // 获取最多40个当前正在运行的服务,放进ArrList里,以现在手机的处理能力,要是超过40个服务,估计已经卡死,所以不用考虑超过40个该怎么办 int servicesSize = runningServices.size(); for (int i = 0; i < servicesSize; i++)// 循环枚举对比 { if (runningServices.get(i).service.getClassName().toString() .equals(serviceName)) { return true; } } return false; } @Override public void onDeleted(Context context, int[] appWidgetIds) { Log.d(TAG, "onDeleted"); } @Override public void onEnabled(Context context) { Log.d(TAG, "onEnabled"); TwitterService.setWidgetStatus(true); } @Override public void onDisabled(Context context) { Log.d(TAG, "onDisabled"); TwitterService.setWidgetStatus(false); } }
zzys3228-fanfou
src/com/ch_linghu/fanfoudroid/FanfouWidgetSmall.java
Java
asf20
8,339
package com.ch_linghu.fanfoudroid; import java.text.MessageFormat; import java.util.List; import android.content.Intent; import android.os.Bundle; 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.R; public class FollowersActivity extends UserArrayBaseActivity { private static final String TAG = "FollowersActivity"; private String userId; private String userName; private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.FOLLOWERS"; private static final String USER_ID = "userId"; private static final String USER_NAME = "userName"; private int currentPage = 1; @Override protected boolean _onCreate(Bundle savedInstanceState) { if (super._onCreate(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); } String myself = TwitterApplication.getMyselfId(false); if (getUserId() == myself) { mNavbar.setHeaderTitle(MessageFormat.format( getString(R.string.profile_followers_count_title), "我")); } else { mNavbar.setHeaderTitle(MessageFormat.format( getString(R.string.profile_followers_count_title), userName)); } return true; } else { return false; } } public static Intent createIntent(String userId, String userName) { Intent intent = new Intent(LAUNCH_ACTION); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.putExtra(USER_ID, userId); intent.putExtra(USER_NAME, userName); return intent; } @Override public Paging getNextPage() { currentPage += 1; return new Paging(currentPage); } @Override protected String getUserId() { return this.userId; } @Override public Paging getCurrentPage() { 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().getFollowersList(userId, page); } }
zzys3228-fanfou
src/com/ch_linghu/fanfoudroid/FollowersActivity.java
Java
asf20
2,322
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; } }
zzys3228-fanfou
src/com/ch_linghu/fanfoudroid/SearchActivity.java
Java
asf20
11,514
package com.ch_linghu.fanfoudroid.ui.module; import java.util.ArrayList; import android.content.Context; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.graphics.Color; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.ch_linghu.fanfoudroid.R; import com.ch_linghu.fanfoudroid.TwitterApplication; import com.ch_linghu.fanfoudroid.app.LazyImageLoader.ImageLoaderCallback; import com.ch_linghu.fanfoudroid.app.Preferences; import com.ch_linghu.fanfoudroid.app.SimpleImageLoader; import com.ch_linghu.fanfoudroid.data.Tweet; import com.ch_linghu.fanfoudroid.util.TextHelper; public class TweetArrayAdapter extends BaseAdapter implements TweetAdapter { private static final String TAG = "TweetArrayAdapter"; protected ArrayList<Tweet> mTweets; private Context mContext; protected LayoutInflater mInflater; protected StringBuilder mMetaBuilder; public TweetArrayAdapter(Context context) { mTweets = new ArrayList<Tweet>(); mContext = context; mInflater = LayoutInflater.from(mContext); mMetaBuilder = new StringBuilder(); } @Override public int getCount() { return mTweets.size(); } @Override public Object getItem(int position) { return mTweets.get(position); } @Override public long getItemId(int position) { return position; } private static class ViewHolder { public LinearLayout tweetLayout; public TextView tweetUserText; public TextView tweetText; public FrameLayout profileLayout; public ImageView profileImage; public TextView metaText; public ImageView fav; public ImageView has_image; } @Override public View getView(int position, View convertView, ViewGroup parent) { View view; SharedPreferences pref = TwitterApplication.mPref; // PreferenceManager.getDefaultSharedPreferences(mContext); boolean useProfileImage = pref.getBoolean( Preferences.USE_PROFILE_IMAGE, true); boolean useHighlightBackground = pref.getBoolean( Preferences.HIGHLIGHT_BACKGROUND, true); if (convertView == null) { view = mInflater.inflate(R.layout.tweet, parent, false); ViewHolder holder = new ViewHolder(); holder.tweetLayout=(LinearLayout) view.findViewById(R.id.tweet_layout); holder.tweetUserText = (TextView) view .findViewById(R.id.tweet_user_text); holder.tweetText = (TextView) view.findViewById(R.id.tweet_text); holder.profileLayout = (FrameLayout) view .findViewById(R.id.profile_layout); holder.profileImage = (ImageView) view .findViewById(R.id.profile_image); holder.metaText = (TextView) view .findViewById(R.id.tweet_meta_text); holder.fav = (ImageView) view.findViewById(R.id.tweet_fav); holder.has_image = (ImageView) view .findViewById(R.id.tweet_has_image); view.setTag(holder); } else { view = convertView; } ViewHolder holder = (ViewHolder) view.getTag(); Tweet tweet = mTweets.get(position); holder.tweetUserText.setText(tweet.screenName); TextHelper.setSimpleTweetText(holder.tweetText, tweet.text); // holder.tweetText.setText(tweet.text, BufferType.SPANNABLE); String profileImageUrl = tweet.profileImageUrl; if (useProfileImage && !TextUtils.isEmpty(profileImageUrl)) { holder.profileLayout.setVisibility(View.VISIBLE); SimpleImageLoader.display(holder.profileImage, profileImageUrl); } else { holder.profileLayout.setVisibility(View.GONE); } holder.metaText.setText(Tweet.buildMetaText(mMetaBuilder, tweet.createdAt, tweet.source, tweet.inReplyToScreenName)); if (tweet.favorited.equals("true")) { holder.fav.setVisibility(View.VISIBLE); } else { holder.fav.setVisibility(View.GONE); } if (!TextUtils.isEmpty(tweet.thumbnail_pic)) { holder.has_image.setVisibility(View.VISIBLE); } else { holder.has_image.setVisibility(View.GONE); } /** * 添加特殊行的背景色 */ if (useHighlightBackground){ String myself = TwitterApplication.getMyselfName(false); StringBuilder b = new StringBuilder(); b.append("@"); b.append(myself); String to_myself = b.toString(); //FIXME: contains操作影响效率,应该在获得时作判断,置标志,在这里对标志进行直接判断。 if(holder.tweetUserText.getText().equals(myself)){ holder.tweetLayout.setBackgroundResource(R.drawable.list_selector_self); holder.profileLayout.setBackgroundResource(R.color.self_background); }else if(holder.tweetText.getText().toString().contains(to_myself)){ holder.tweetLayout.setBackgroundResource(R.drawable.list_selector_mention); holder.profileLayout.setBackgroundResource(R.color.mention_background); }else{ holder.tweetLayout.setBackgroundResource(android.R.drawable.list_selector_background); holder.profileLayout.setBackgroundResource(android.R.color.transparent); } }else{ holder.tweetLayout.setBackgroundResource(android.R.drawable.list_selector_background); holder.profileLayout.setBackgroundResource(android.R.color.transparent); } return view; } public void refresh(ArrayList<Tweet> tweets) { mTweets = tweets; notifyDataSetChanged(); } @Override public void refresh() { notifyDataSetChanged(); } }
zzys3228-fanfou
src/com/ch_linghu/fanfoudroid/ui/module/TweetArrayAdapter.java
Java
asf20
5,626
package com.ch_linghu.fanfoudroid.ui.module; import android.widget.ListAdapter; public interface TweetAdapter extends ListAdapter { void refresh(); }
zzys3228-fanfou
src/com/ch_linghu/fanfoudroid/ui/module/TweetAdapter.java
Java
asf20
153
package com.ch_linghu.fanfoudroid.ui.module; import android.app.Activity; import android.view.MotionEvent; import com.ch_linghu.fanfoudroid.BrowseActivity; import com.ch_linghu.fanfoudroid.MentionActivity; import com.ch_linghu.fanfoudroid.R; import com.ch_linghu.fanfoudroid.TwitterActivity; /** * MyActivityFlipper 利用左右滑动手势切换Activity * * 1. 切换Activity, 继承与 {@link ActivityFlipper} 2. 手势识别, 实现接口 * {@link Widget.OnGestureListener} * */ public class MyActivityFlipper extends ActivityFlipper implements Widget.OnGestureListener { public MyActivityFlipper() { super(); } public MyActivityFlipper(Activity activity) { super(activity); // TODO Auto-generated constructor stub } // factory public static MyActivityFlipper create(Activity activity) { MyActivityFlipper flipper = new MyActivityFlipper(activity); flipper.addActivity(BrowseActivity.class); flipper.addActivity(TwitterActivity.class); flipper.addActivity(MentionActivity.class); flipper.setToastResource(new int[] { R.drawable.point_left, R.drawable.point_center, R.drawable.point_right }); flipper.setInAnimation(R.anim.push_left_in); flipper.setOutAnimation(R.anim.push_left_out); flipper.setPreviousInAnimation(R.anim.push_right_in); flipper.setPreviousOutAnimation(R.anim.push_right_out); return flipper; } @Override public boolean onFlingDown(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { return false; // do nothing } @Override public boolean onFlingUp(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { return false; // do nothing } @Override public boolean onFlingLeft(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { autoShowNext(); return true; } @Override public boolean onFlingRight(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { autoShowPrevious(); return true; } }
zzys3228-fanfou
src/com/ch_linghu/fanfoudroid/ui/module/MyActivityFlipper.java
Java
asf20
1,958
package com.ch_linghu.fanfoudroid.ui.module; import android.graphics.Color; import android.text.Editable; import android.text.InputFilter; import android.text.Selection; import android.text.TextWatcher; import android.view.View.OnKeyListener; import android.widget.EditText; import android.widget.TextView; public class TweetEdit { private EditText mEditText; private TextView mCharsRemainText; private int originTextColor; public TweetEdit(EditText editText, TextView charsRemainText) { mEditText = editText; mCharsRemainText = charsRemainText; originTextColor = mCharsRemainText.getTextColors().getDefaultColor(); mEditText.addTextChangedListener(mTextWatcher); mEditText.setFilters(new InputFilter[] { new InputFilter.LengthFilter( MAX_TWEET_INPUT_LENGTH) }); } private static final int MAX_TWEET_LENGTH = 140; private static final int MAX_TWEET_INPUT_LENGTH = 400; public void setTextAndFocus(String text, boolean start) { setText(text); Editable editable = mEditText.getText(); if (!start) { Selection.setSelection(editable, editable.length()); } else { Selection.setSelection(editable, 0); } mEditText.requestFocus(); } public void setText(String text) { mEditText.setText(text); updateCharsRemain(); } private TextWatcher mTextWatcher = new TextWatcher() { @Override public void afterTextChanged(Editable e) { updateCharsRemain(); } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { } }; public void updateCharsRemain() { int remaining = MAX_TWEET_LENGTH - mEditText.length(); if (remaining < 0) { mCharsRemainText.setTextColor(Color.RED); } else { mCharsRemainText.setTextColor(originTextColor); } mCharsRemainText.setText(remaining + ""); } public String getText() { return mEditText.getText().toString(); } public void setEnabled(boolean b) { mEditText.setEnabled(b); } public void setOnKeyListener(OnKeyListener listener) { mEditText.setOnKeyListener(listener); } public void addTextChangedListener(TextWatcher watcher) { mEditText.addTextChangedListener(watcher); } public void requestFocus() { mEditText.requestFocus(); } public EditText getEditText() { return mEditText; } }
zzys3228-fanfou
src/com/ch_linghu/fanfoudroid/ui/module/TweetEdit.java
Java
asf20
2,457
package com.ch_linghu.fanfoudroid.ui.module; import android.content.Context; import android.view.GestureDetector.SimpleOnGestureListener; import android.view.MotionEvent; public interface Widget { Context getContext(); // TEMP public static interface OnGestureListener { /** * @param e1 * The first down motion event that started the fling. * @param e2 * The move motion event that triggered the current onFling. * @param velocityX * The velocity of this fling measured in pixels per second * along the x axis. * @param velocityY * The velocity of this fling measured in pixels per second * along the y axis. * @return true if the event is consumed, else false * * @see SimpleOnGestureListener#onFling */ boolean onFlingDown(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY); boolean onFlingUp(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY); boolean onFlingLeft(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY); boolean onFlingRight(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY); } public static interface OnRefreshListener { void onRefresh(); } }
zzys3228-fanfou
src/com/ch_linghu/fanfoudroid/ui/module/Widget.java
Java
asf20
1,270
package com.ch_linghu.fanfoudroid.ui.module; import com.ch_linghu.fanfoudroid.R; import android.app.Activity; import android.util.Log; import android.view.GestureDetector; import android.view.GestureDetector.SimpleOnGestureListener; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; /** * FlingGestureLIstener, 封装 {@link SimpleOnGestureListener} . * 主要用于识别类似向上下或向左右滑动等基本手势. * * 该类主要解决了与ListView自带的上下滑动冲突问题. 解决方法为将listView的onTouchListener进行覆盖:<code> * FlingGestureListener gListener = new FlingGestureListener(this, * MyActivityFlipper.create(this)); * myListView.setOnTouchListener(gListener); * </code> * * 该类一般和实现了 {@link Widget.OnGestureListener} 接口的类共同协作. 在识别到手势后会自动调用其相关的回调方法, * 以实现手势触发事件效果. * * @see Widget.OnGestureListener * */ public class FlingGestureListener extends SimpleOnGestureListener implements OnTouchListener { private static final String TAG = "FlipperGestureListener"; private static final int SWIPE_MIN_DISTANCE = 120; private static final int SWIPE_MAX_DISTANCE = 400; private static final int SWIPE_THRESHOLD_VELOCITY = 200; private Widget.OnGestureListener mListener; private GestureDetector gDetector; private Activity activity; public FlingGestureListener(Activity activity, Widget.OnGestureListener listener) { this(activity, listener, null); } public FlingGestureListener(Activity activity, Widget.OnGestureListener listener, GestureDetector gDetector) { if (gDetector == null) { gDetector = new GestureDetector(activity, this); } this.gDetector = gDetector; mListener = listener; this.activity = activity; } @Override public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) { Log.d(TAG, "On fling"); boolean result = super.onFling(e1, e2, velocityX, velocityY); float xDistance = Math.abs(e1.getX() - e2.getX()); float yDistance = Math.abs(e1.getY() - e2.getY()); velocityX = Math.abs(velocityX); velocityY = Math.abs(velocityY); try { if (xDistance > SWIPE_MAX_DISTANCE || yDistance > SWIPE_MAX_DISTANCE) { Log.d(TAG, "OFF_PATH"); return result; } if (velocityX > SWIPE_THRESHOLD_VELOCITY && xDistance > SWIPE_MIN_DISTANCE) { if (e1.getX() > e2.getX()) { Log.d(TAG, "<------"); result = mListener .onFlingLeft(e1, e1, velocityX, velocityY); activity.overridePendingTransition(R.anim.push_left_in, R.anim.push_left_out); } else { Log.d(TAG, "------>"); result = mListener.onFlingRight(e1, e1, velocityX, velocityY); activity.overridePendingTransition(R.anim.push_right_in, R.anim.push_right_out); } } else if (velocityY > SWIPE_THRESHOLD_VELOCITY && yDistance > SWIPE_MIN_DISTANCE) { if (e1.getY() > e2.getY()) { Log.d(TAG, "up"); result = mListener.onFlingUp(e1, e1, velocityX, velocityY); } else { Log.d(TAG, "down"); result = mListener .onFlingDown(e1, e1, velocityX, velocityY); } } else { Log.d(TAG, "not hint"); } } catch (Exception e) { e.printStackTrace(); Log.e(TAG, "onFling error " + e.getMessage()); } return result; } @Override public void onLongPress(MotionEvent e) { // TODO Auto-generated method stub super.onLongPress(e); } @Override public boolean onTouch(View v, MotionEvent event) { Log.d(TAG, "On Touch"); // Within the MyGestureListener class you can now manage the // event.getAction() codes. // Note that we are now calling the gesture Detectors onTouchEvent. // And given we've set this class as the GestureDetectors listener // the onFling, onSingleTap etc methods will be executed. return gDetector.onTouchEvent(event); } public GestureDetector getDetector() { return gDetector; } }
zzys3228-fanfou
src/com/ch_linghu/fanfoudroid/ui/module/FlingGestureListener.java
Java
asf20
4,028
package com.ch_linghu.fanfoudroid.ui.module; import android.content.Context; import android.util.AttributeSet; import android.view.MotionEvent; import android.widget.AbsListView; import android.widget.ListView; public class MyListView extends ListView implements ListView.OnScrollListener { private int mScrollState = OnScrollListener.SCROLL_STATE_IDLE; public MyListView(Context context, AttributeSet attrs) { super(context, attrs); setOnScrollListener(this); } @Override public boolean onInterceptTouchEvent(MotionEvent event) { boolean result = super.onInterceptTouchEvent(event); if (mScrollState == OnScrollListener.SCROLL_STATE_FLING) { return true; } return result; } private OnNeedMoreListener mOnNeedMoreListener; public static interface OnNeedMoreListener { public void needMore(); } public void setOnNeedMoreListener(OnNeedMoreListener onNeedMoreListener) { mOnNeedMoreListener = onNeedMoreListener; } private int mFirstVisibleItem; @Override public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) { if (mOnNeedMoreListener == null) { return; } if (firstVisibleItem != mFirstVisibleItem) { if (firstVisibleItem + visibleItemCount >= totalItemCount) { mOnNeedMoreListener.needMore(); } } else { mFirstVisibleItem = firstVisibleItem; } } @Override public void onScrollStateChanged(AbsListView view, int scrollState) { mScrollState = scrollState; } }
zzys3228-fanfou
src/com/ch_linghu/fanfoudroid/ui/module/MyListView.java
Java
asf20
1,552
package com.ch_linghu.fanfoudroid.ui.module; public interface IFlipper { void showNext(); void showPrevious(); }
zzys3228-fanfou
src/com/ch_linghu/fanfoudroid/ui/module/IFlipper.java
Java
asf20
117
package com.ch_linghu.fanfoudroid.ui.module; import java.util.ArrayList; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.ch_linghu.fanfoudroid.R; import com.ch_linghu.fanfoudroid.TwitterApplication; import com.ch_linghu.fanfoudroid.app.LazyImageLoader.ImageLoaderCallback; import com.ch_linghu.fanfoudroid.app.Preferences; import com.ch_linghu.fanfoudroid.data.User; import com.ch_linghu.fanfoudroid.fanfou.Weibo; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.task.GenericTask; import com.ch_linghu.fanfoudroid.task.TaskAdapter; import com.ch_linghu.fanfoudroid.task.TaskListener; import com.ch_linghu.fanfoudroid.task.TaskParams; import com.ch_linghu.fanfoudroid.task.TaskResult; /* * 用于用户的Adapter */ public class UserArrayAdapter extends BaseAdapter implements TweetAdapter { private static final String TAG = "UserArrayAdapter"; private static final String USER_ID = "userId"; protected ArrayList<User> mUsers; private Context mContext; protected LayoutInflater mInflater; public UserArrayAdapter(Context context) { mUsers = new ArrayList<User>(); mContext = context; mInflater = LayoutInflater.from(mContext); } @Override public int getCount() { return mUsers.size(); } @Override public Object getItem(int position) { return mUsers.get(position); } @Override public long getItemId(int position) { return position; } private static class ViewHolder { public ImageView profileImage; public TextView screenName; public TextView userId; public TextView lastStatus; public TextView followBtn; } @Override public View getView(int position, View convertView, ViewGroup parent) { View view; SharedPreferences pref = TwitterApplication.mPref; // PreferenceManager.getDefaultSharedPreferences(mContext); boolean useProfileImage = pref.getBoolean( Preferences.USE_PROFILE_IMAGE, true); if (convertView == null) { view = mInflater.inflate(R.layout.follower_item, parent, false); ViewHolder holder = new ViewHolder(); holder.profileImage = (ImageView) view .findViewById(R.id.profile_image); holder.screenName = (TextView) view.findViewById(R.id.screen_name); holder.userId = (TextView) view.findViewById(R.id.user_id); // holder.lastStatus = (TextView) // view.findViewById(R.id.last_status); holder.followBtn = (TextView) view.findViewById(R.id.follow_btn); view.setTag(holder); } else { view = convertView; } ViewHolder holder = (ViewHolder) view.getTag(); final User user = mUsers.get(position); String profileImageUrl = user.profileImageUrl; if (useProfileImage) { if (!TextUtils.isEmpty(profileImageUrl)) { holder.profileImage .setImageBitmap(TwitterApplication.mImageLoader.get( profileImageUrl, callback)); } } else { holder.profileImage.setVisibility(View.GONE); } // holder.profileImage.setImageBitmap(ImageManager.mDefaultBitmap); holder.screenName.setText(user.screenName); holder.userId.setText(user.id); // holder.lastStatus.setText(user.lastStatus); holder.followBtn.setText(user.isFollowing ? mContext .getString(R.string.general_del_friend) : mContext .getString(R.string.general_add_friend)); holder.followBtn .setOnClickListener(user.isFollowing ? new OnClickListener() { @Override public void onClick(View v) { // Toast.makeText(mContext, user.name+"following", // Toast.LENGTH_SHORT).show(); delFriend(user.id,v); } } : new OnClickListener() { @Override public void onClick(View v) { // Toast.makeText(mContext, user.name+"not following", // Toast.LENGTH_SHORT).show(); addFriend(user.id,v); } }); return view; } public void refresh(ArrayList<User> users) { mUsers = (ArrayList<User>)users.clone(); notifyDataSetChanged(); } @Override public void refresh() { notifyDataSetChanged(); } private ImageLoaderCallback callback = new ImageLoaderCallback() { @Override public void refresh(String url, Bitmap bitmap) { UserArrayAdapter.this.refresh(); } }; /** * 取消关注 * * @param id */ private void delFriend(final String id,final View v) { Builder diaBuilder = new AlertDialog.Builder(mContext).setTitle("关注提示") .setMessage("确实要取消关注吗?"); diaBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (cancelFollowingTask != null && cancelFollowingTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { cancelFollowingTask = new CancelFollowingTask(); cancelFollowingTask.setListener(new TaskAdapter() {//闭包? @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.OK) { //添加成功后动态改变按钮 TextView followBtn=(TextView)v.findViewById(R.id.follow_btn); followBtn.setText("添加关注"); followBtn.setOnClickListener( new OnClickListener() { @Override public void onClick(View view) { addFriend(id,view); } }); Toast.makeText(mContext, "取消关注成功", Toast.LENGTH_SHORT).show(); } else if (result == TaskResult.FAILED) { Toast.makeText(mContext, "取消关注失败", Toast.LENGTH_SHORT).show(); } } @Override public String getName() { return null; } }); TaskParams params = new TaskParams(); params.put(USER_ID, id); cancelFollowingTask.execute(params); } } }); diaBuilder.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); Dialog dialog = diaBuilder.create(); dialog.show(); } private GenericTask cancelFollowingTask; /** * 取消关注 * * @author Dino * */ private class CancelFollowingTask extends GenericTask { @Override protected TaskResult _doInBackground(TaskParams... params) { try { String userId = params[0].getString(USER_ID); getApi().destroyFriendship(userId); } catch (HttpException e) { Log.w(TAG, "create friend ship error"); return TaskResult.FAILED; } return TaskResult.OK; } } private GenericTask setFollowingTask; /** * 设置关注 * * @param id */ private void addFriend(final String id,final View view) { Builder diaBuilder = new AlertDialog.Builder(mContext).setTitle("关注提示") .setMessage("确实要添加关注吗?"); diaBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (setFollowingTask != null && setFollowingTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { setFollowingTask = new SetFollowingTask(); setFollowingTask .setListener(new TaskAdapter() { @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.OK) { //添加成功后动态改变按钮 TextView followBtn=(TextView)view.findViewById(R.id.follow_btn); followBtn.setText("取消关注"); followBtn.setOnClickListener( new OnClickListener() { @Override public void onClick(View v) { delFriend(id,v); } }); Toast.makeText(mContext, "关注成功", Toast.LENGTH_SHORT).show(); } else if (result == TaskResult.FAILED) { Toast.makeText(mContext, "关注失败", Toast.LENGTH_SHORT).show(); } } @Override public String getName() { // TODO Auto-generated method stub return null; } }); TaskParams params = new TaskParams(); params.put(USER_ID, id); setFollowingTask.execute(params); } } }); diaBuilder.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); Dialog dialog = diaBuilder.create(); dialog.show(); } /** * 设置关注 * * @author Dino * */ private class SetFollowingTask extends GenericTask { @Override protected TaskResult _doInBackground(TaskParams... params) { try { String userId = params[0].getString(USER_ID); getApi().createFriendship(userId); } catch (HttpException e) { Log.w(TAG, "create friend ship error"); return TaskResult.FAILED; } return TaskResult.OK; } } public Weibo getApi() { return TwitterApplication.mApi; } }
zzys3228-fanfou
src/com/ch_linghu/fanfoudroid/ui/module/UserArrayAdapter.java
Java
asf20
9,914
/* * Copyright (C) 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ch_linghu.fanfoudroid.ui.module; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import android.app.Activity; import android.app.Dialog; import android.content.Context; import android.content.Intent; import android.view.Gravity; import android.view.View; import android.view.WindowManager.LayoutParams; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Button; import android.widget.GridView; import android.widget.SimpleAdapter; import android.widget.Toast; import com.ch_linghu.fanfoudroid.BrowseActivity; import com.ch_linghu.fanfoudroid.DmActivity; import com.ch_linghu.fanfoudroid.FavoritesActivity; import com.ch_linghu.fanfoudroid.FollowersActivity; import com.ch_linghu.fanfoudroid.FollowingActivity; import com.ch_linghu.fanfoudroid.MentionActivity; import com.ch_linghu.fanfoudroid.ProfileActivity; import com.ch_linghu.fanfoudroid.R; import com.ch_linghu.fanfoudroid.TwitterActivity; import com.ch_linghu.fanfoudroid.TwitterApplication; import com.ch_linghu.fanfoudroid.UserTimelineActivity; /** * 顶部主菜单切换浮动层 * * @author lds * */ public class MenuDialog extends Dialog { private static final int PAGE_MINE = 0; private static final int PAGE_PROFILE = 1; private static final int PAGE_FOLLOWERS = 2; private static final int PAGE_FOLLOWING = 3; private static final int PAGE_HOME = 4; private static final int PAGE_MENTIONS = 5; private static final int PAGE_BROWSE = 6; private static final int PAGE_FAVORITES = 7; private static final int PAGE_MESSAGE = 8; private List<int[]> pages = new ArrayList<int[]>(); { pages.add(new int[] { R.drawable.menu_tweets, R.string.pages_mine }); pages.add(new int[] { R.drawable.menu_profile, R.string.pages_profile }); pages.add(new int[] { R.drawable.menu_followers, R.string.pages_followers }); pages.add(new int[] { R.drawable.menu_following, R.string.pages_following }); pages.add(new int[] { R.drawable.menu_list, R.string.pages_home }); pages.add(new int[] { R.drawable.menu_mentions, R.string.pages_mentions }); pages.add(new int[] { R.drawable.menu_listed, R.string.pages_browse }); pages.add(new int[] { R.drawable.menu_favorites, R.string.pages_search }); pages.add(new int[] { R.drawable.menu_create_list, R.string.pages_message }); }; private GridView gridview; public MenuDialog(Context context, boolean cancelable, OnCancelListener cancelListener) { super(context, cancelable, cancelListener); // TODO Auto-generated constructor stub } public MenuDialog(Context context, int theme) { super(context, theme); // TODO Auto-generated constructor stub } public MenuDialog(Context context) { super(context, R.style.Theme_Transparent); setContentView(R.layout.menu_dialog); // setTitle("Custom Dialog"); setCanceledOnTouchOutside(true); // 设置window属性 LayoutParams a = getWindow().getAttributes(); a.gravity = Gravity.TOP; a.dimAmount = 0; // 去背景遮盖 getWindow().setAttributes(a); initMenu(); } public void setPosition(int x, int y) { LayoutParams a = getWindow().getAttributes(); if (-1 != x) a.x = x; if (-1 != y) a.y = y; getWindow().setAttributes(a); } private void goTo(Class<?> cls, Intent intent) { if (getOwnerActivity().getClass() != cls) { dismiss(); intent.setClass(getContext(), cls); getContext().startActivity(intent); } else { String msg = getContext().getString(R.string.page_status_same_page); Toast.makeText(getContext(), msg, Toast.LENGTH_SHORT).show(); } } private void goTo(Class<?> cls) { Intent intent = new Intent(); goTo(cls, intent); } private void initMenu() { // 准备要添加的数据条目 List<Map<String, Object>> items = new ArrayList<Map<String, Object>>(); for (int[] item : pages) { Map<String, Object> map = new HashMap<String, Object>(); map.put("image", item[0]); map.put("title", getContext().getString(item[1])); items.add(map); } // 实例化一个适配器 SimpleAdapter adapter = new SimpleAdapter(getContext(), items, // data R.layout.menu_item, // grid item layout new String[] { "title", "image" }, // data's key new int[] { R.id.item_text, R.id.item_image }); // item view id // 获得GridView实例 gridview = (GridView) findViewById(R.id.mygridview); // 将GridView和数据适配器关联 gridview.setAdapter(adapter); } public void bindEvent(Activity activity) { setOwnerActivity(activity); // 绑定监听器 gridview.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View v, int position, long id) { switch (position) { case PAGE_MINE: String user = TwitterApplication.getMyselfId(false); String name = TwitterApplication.getMyselfName(false); Intent intent = UserTimelineActivity.createIntent(user, name); goTo(UserTimelineActivity.class, intent); break; case PAGE_PROFILE: goTo(ProfileActivity.class); break; case PAGE_FOLLOWERS: goTo(FollowersActivity.class); break; case PAGE_FOLLOWING: goTo(FollowingActivity.class); break; case PAGE_HOME: goTo(TwitterActivity.class); break; case PAGE_MENTIONS: goTo(MentionActivity.class); break; case PAGE_BROWSE: goTo(BrowseActivity.class); break; case PAGE_FAVORITES: goTo(FavoritesActivity.class); break; case PAGE_MESSAGE: goTo(DmActivity.class); break; } } }); Button close_button = (Button) findViewById(R.id.close_menu); close_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dismiss(); } }); } }
zzys3228-fanfou
src/com/ch_linghu/fanfoudroid/ui/module/MenuDialog.java
Java
asf20
6,622
/** * */ package com.ch_linghu.fanfoudroid.ui.module; import android.content.Context; import android.content.SharedPreferences; import android.database.Cursor; import android.graphics.Bitmap; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CursorAdapter; import android.widget.ImageView; import android.widget.TextView; import com.ch_linghu.fanfoudroid.R; import com.ch_linghu.fanfoudroid.TwitterApplication; import com.ch_linghu.fanfoudroid.app.LazyImageLoader.ImageLoaderCallback; import com.ch_linghu.fanfoudroid.app.Preferences; import com.ch_linghu.fanfoudroid.db.UserInfoTable; public class UserCursorAdapter extends CursorAdapter implements TweetAdapter { private static final String TAG = "TweetCursorAdapter"; private Context mContext; public UserCursorAdapter(Context context, Cursor cursor) { super(context, cursor); mContext = context; if (context != null) { mInflater = LayoutInflater.from(context); } if (cursor != null) { mScreenNametColumn = cursor .getColumnIndexOrThrow(UserInfoTable.FIELD_USER_SCREEN_NAME); mUserIdColumn = cursor.getColumnIndexOrThrow(UserInfoTable._ID); mProfileImageUrlColumn = cursor .getColumnIndexOrThrow(UserInfoTable.FIELD_PROFILE_IMAGE_URL); // mLastStatusColumn=cursor.getColumnIndexOrThrow(UserInfoTable.FIELD_LAST_STATUS); } mMetaBuilder = new StringBuilder(); } private LayoutInflater mInflater; private int mScreenNametColumn; private int mUserIdColumn; private int mProfileImageUrlColumn; // private int mLastStatusColumn; private StringBuilder mMetaBuilder; private ImageLoaderCallback callback = new ImageLoaderCallback() { @Override public void refresh(String url, Bitmap bitmap) { UserCursorAdapter.this.refresh(); } }; @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { View view = mInflater.inflate(R.layout.follower_item, parent, false); Log.d(TAG, "load newView"); UserCursorAdapter.ViewHolder holder = new ViewHolder(); holder.screenName = (TextView) view.findViewById(R.id.screen_name); holder.profileImage = (ImageView) view.findViewById(R.id.profile_image); // holder.lastStatus=(TextView) view.findViewById(R.id.last_status); holder.userId = (TextView) view.findViewById(R.id.user_id); view.setTag(holder); return view; } private static class ViewHolder { public TextView screenName; public TextView userId; public TextView lastStatus; public ImageView profileImage; } @Override public void bindView(View view, Context context, Cursor cursor) { UserCursorAdapter.ViewHolder holder = (UserCursorAdapter.ViewHolder) view .getTag(); Log.d(TAG, "cursor count=" + cursor.getCount()); Log.d(TAG, "holder is null?" + (holder == null ? "yes" : "no")); SharedPreferences pref = TwitterApplication.mPref; // PreferenceManager.getDefaultSharedPreferences(mContext);; boolean useProfileImage = pref.getBoolean( Preferences.USE_PROFILE_IMAGE, true); String profileImageUrl = cursor.getString(mProfileImageUrlColumn); if (useProfileImage) { if (!TextUtils.isEmpty(profileImageUrl)) { holder.profileImage .setImageBitmap(TwitterApplication.mImageLoader.get( profileImageUrl, callback)); } } else { holder.profileImage.setVisibility(View.GONE); } holder.screenName.setText(cursor.getString(mScreenNametColumn)); holder.userId.setText(cursor.getString(mUserIdColumn)); } @Override public void refresh() { getCursor().requery(); } }
zzys3228-fanfou
src/com/ch_linghu/fanfoudroid/ui/module/UserCursorAdapter.java
Java
asf20
3,612
package com.ch_linghu.fanfoudroid.ui.module; public interface Feedback { public boolean isAvailable(); public void start(CharSequence text); public void cancel(CharSequence text); public void success(CharSequence text); public void failed(CharSequence text); public void update(Object arg0); public void setIndeterminate(boolean indeterminate); }
zzys3228-fanfou
src/com/ch_linghu/fanfoudroid/ui/module/Feedback.java
Java
asf20
361
package com.ch_linghu.fanfoudroid.ui.module; import android.content.Context; import android.content.SharedPreferences; import android.content.res.Resources; import android.graphics.Color; import android.text.Layout; import android.text.Spannable; import android.text.Spanned; import android.text.style.ForegroundColorSpan; import android.text.style.URLSpan; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import android.widget.TextView; import com.ch_linghu.fanfoudroid.R; import com.ch_linghu.fanfoudroid.TwitterApplication; import com.ch_linghu.fanfoudroid.app.Preferences; public class MyTextView extends TextView { private static float mFontSize = 15; private static boolean mFontSizeChanged = true; public MyTextView(Context context) { super(context, null); } public MyTextView(Context context, AttributeSet attrs) { super(context, attrs); setLinksClickable(false); Resources res = getResources(); int color = res.getColor(R.color.link_color); setLinkTextColor(color); initFontSize(); } public void initFontSize() { if (mFontSizeChanged) { mFontSize = getFontSizeFromPreferences(mFontSize); setFontSizeChanged(false); // reset } setTextSize(mFontSize); } private float getFontSizeFromPreferences(float defaultValue) { SharedPreferences preferences = TwitterApplication.mPref; if (preferences.contains(Preferences.UI_FONT_SIZE)) { Log.v("DEBUG", preferences.getString(Preferences.UI_FONT_SIZE, "null") + " CHANGE FONT SIZE"); return Float.parseFloat(preferences.getString( Preferences.UI_FONT_SIZE, "14")); } return defaultValue; } private URLSpan mCurrentLink; private ForegroundColorSpan mLinkFocusStyle = new ForegroundColorSpan( Color.RED); @Override public boolean onTouchEvent(MotionEvent event) { CharSequence text = getText(); int action = event.getAction(); if (!(text instanceof Spannable)) { return super.onTouchEvent(event); } Spannable buffer = (Spannable) text; if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_DOWN || action == MotionEvent.ACTION_MOVE) { TextView widget = this; int x = (int) event.getX(); int y = (int) event.getY(); x -= widget.getTotalPaddingLeft(); y -= widget.getTotalPaddingTop(); x += widget.getScrollX(); y += widget.getScrollY(); Layout layout = widget.getLayout(); int line = layout.getLineForVertical(y); int off = layout.getOffsetForHorizontal(line, x); URLSpan[] link = buffer.getSpans(off, off, URLSpan.class); if (link.length != 0) { if (action == MotionEvent.ACTION_UP) { if (mCurrentLink == link[0]) { link[0].onClick(widget); } mCurrentLink = null; buffer.removeSpan(mLinkFocusStyle); } else if (action == MotionEvent.ACTION_DOWN) { mCurrentLink = link[0]; buffer.setSpan(mLinkFocusStyle, buffer.getSpanStart(link[0]), buffer.getSpanEnd(link[0]), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } return true; } } mCurrentLink = null; buffer.removeSpan(mLinkFocusStyle); return super.onTouchEvent(event); } public static void setFontSizeChanged(boolean isChanged) { mFontSizeChanged = isChanged; } @Override public void onWindowFocusChanged(boolean hasWindowFocus) { super.onWindowFocusChanged(hasWindowFocus); } }
zzys3228-fanfou
src/com/ch_linghu/fanfoudroid/ui/module/MyTextView.java
Java
asf20
3,502
package com.ch_linghu.fanfoudroid.ui.module; import java.util.ArrayList; import java.util.List; import android.app.Activity; import android.content.Intent; import android.util.Log; import android.view.Gravity; import android.widget.ImageView; import android.widget.Toast; import android.widget.ViewSwitcher.ViewFactory; import com.ch_linghu.fanfoudroid.R; /** * ActivityFlipper, 和 {@link ViewFactory} 类似, 只是设计用于切换activity. * * 切换的前后顺序取决与注册时的先后顺序 * * USAGE: <code> * ActivityFlipper mFlipper = new ActivityFlipper(this); * mFlipper.addActivity(TwitterActivity.class); * mFlipper.addActivity(MentionActivity.class); * mFlipper.addActivity(DmActivity.class); * * // switch activity * mFlipper.setCurrentActivity(TwitterActivity.class); * mFlipper.showNext(); * mFlipper.showPrevious(); * * // or without set current activity * mFlipper.showNextOf(TwitterActivity.class); * mFlipper.showPreviousOf(TwitterActivity.class); * * // or auto mode, use the context as current activity * mFlipper.autoShowNext(); * mFlipper.autoShowPrevious(); * * // set toast * mFlipper.setToastResource(new int[] { * R.drawable.point_left, * R.drawable.point_center, * R.drawable.point_right * }); * * // set Animation * mFlipper.setInAnimation(R.anim.push_left_in); * mFlipper.setOutAnimation(R.anim.push_left_out); * mFlipper.setPreviousInAnimation(R.anim.push_right_in); * mFlipper.setPreviousOutAnimation(R.anim.push_right_out); * </code> * */ public class ActivityFlipper implements IFlipper { private static final String TAG = "ActivityFlipper"; private static final int SHOW_NEXT = 0; private static final int SHOW_PROVIOUS = 1; private int mDirection = SHOW_NEXT; private boolean mToastEnabled = false; private int[] mToastResourcesMap = new int[] {}; private boolean mAnimationEnabled = false; private int mNextInAnimation = -1; private int mNextOutAnimation = -1; private int mPreviousInAnimation = -1; private int mPreviousOutAnimation = -1; private Activity mActivity; private List<Class<?>> mActivities = new ArrayList<Class<?>>();; private int mWhichActivity = 0; public ActivityFlipper() { } public ActivityFlipper(Activity activity) { mActivity = activity; } /** * Launch Activity * * @param cls * class of activity */ public void launchActivity(Class<?> cls) { Log.v(TAG, "launch activity :" + cls.getName()); Intent intent = new Intent(); intent.setClass(mActivity, cls); mActivity.startActivity(intent); } public void setToastResource(int[] resourceIds) { mToastEnabled = true; mToastResourcesMap = resourceIds; } private void maybeShowToast(int whichActicity) { if (mToastEnabled && whichActicity < mToastResourcesMap.length) { final Toast myToast = new Toast(mActivity); final ImageView myView = new ImageView(mActivity); myView.setImageResource(mToastResourcesMap[whichActicity]); myToast.setView(myView); myToast.setDuration(Toast.LENGTH_SHORT); myToast.setGravity(Gravity.BOTTOM | Gravity.CENTER, 0, 0); myToast.show(); } } private void maybeShowAnimation(int whichActivity) { if (mAnimationEnabled) { boolean showPrevious = (mDirection == SHOW_PROVIOUS); if (showPrevious && mPreviousInAnimation != -1 && mPreviousOutAnimation != -1) { mActivity.overridePendingTransition(mPreviousInAnimation, mPreviousOutAnimation); return; // use Previous Animation } if (mNextInAnimation != -1 && mNextOutAnimation != -1) { mActivity.overridePendingTransition(mNextInAnimation, mNextOutAnimation); } } } /** * Launch Activity by index * * @param whichActivity * the index of Activity */ private void launchActivity(int whichActivity) { launchActivity(mActivities.get(whichActivity)); maybeShowToast(whichActivity); maybeShowAnimation(whichActivity); } /** * Add Activity NOTE: 添加的顺序很重要 * * @param cls * class of activity */ public void addActivity(Class<?> cls) { mActivities.add(cls); } /** * Get index of the Activity * * @param cls * class of activity * @return */ private int getIndexOf(Class<?> cls) { int index = mActivities.indexOf(cls); if (-1 == index) { Log.e(TAG, "No such activity: " + cls.getName()); } return index; } @SuppressWarnings("unused") private Class<?> getActivityAt(int index) { if (index > 0 && index < mActivities.size()) { return mActivities.get(index); } return null; } /** * Show next activity(already setCurrentActivity) */ @Override public void showNext() { mDirection = SHOW_NEXT; setDisplayedActivity(mWhichActivity + 1, true); } /** * Show next activity of * * @param cls * class of activity */ public void showNextOf(Class<?> cls) { setCurrentActivity(cls); showNext(); } /** * Show next activity(use current context as a activity) */ public void autoShowNext() { showNextOf(mActivity.getClass()); } /** * Show previous activity(already setCurrentActivity) */ @Override public void showPrevious() { mDirection = SHOW_PROVIOUS; setDisplayedActivity(mWhichActivity - 1, true); } /** * Show previous activity of * * @param cls * class of activity */ public void showPreviousOf(Class<?> cls) { setCurrentActivity(cls); showPrevious(); } /** * Show previous activity(use current context as a activity) */ public void autoShowPrevious() { showPreviousOf(mActivity.getClass()); } /** * Sets which child view will be displayed * * @param whichActivity * the index of the child view to display * @param display * display immediately */ public void setDisplayedActivity(int whichActivity, boolean display) { mWhichActivity = whichActivity; if (whichActivity >= getCount()) { mWhichActivity = 0; } else if (whichActivity < 0) { mWhichActivity = getCount() - 1; } if (display) { launchActivity(mWhichActivity); } } /** * Set current Activity * * @param cls * class of activity */ public void setCurrentActivity(Class<?> cls) { setDisplayedActivity(getIndexOf(cls), false); } public void setInAnimation(int resourceId) { setEnableAnimation(true); mNextInAnimation = resourceId; } public void setOutAnimation(int resourceId) { setEnableAnimation(true); mNextOutAnimation = resourceId; } public void setPreviousInAnimation(int resourceId) { mPreviousInAnimation = resourceId; } public void setPreviousOutAnimation(int resourceId) { mPreviousOutAnimation = resourceId; } public void setEnableAnimation(boolean enable) { mAnimationEnabled = enable; } /** * Count activities * * @return the number of activities */ public int getCount() { return mActivities.size(); } }
zzys3228-fanfou
src/com/ch_linghu/fanfoudroid/ui/module/ActivityFlipper.java
Java
asf20
6,954
package com.ch_linghu.fanfoudroid.ui.module; import java.util.List; import android.app.Activity; import android.content.Context; import android.util.Log; import android.view.View; import android.widget.ProgressBar; import android.widget.Toast; import com.ch_linghu.fanfoudroid.R; public class SimpleFeedback implements Feedback, Widget { private static final String TAG = "SimpleFeedback"; public static final int MAX = 100; private ProgressBar mProgress = null; //private ProgressBar mLoadingProgress = null; public SimpleFeedback(Context context) { mProgress = (ProgressBar) ((Activity) context) .findViewById(R.id.progress_bar); //mLoadingProgress = (ProgressBar) ((Activity) context) // .findViewById(R.id.top_refresh_progressBar); } @Override public void start(CharSequence text) { mProgress.setProgress(20); //mLoadingProgress.setVisibility(View.VISIBLE); } @Override public void success(CharSequence text) { mProgress.setProgress(100); //mLoadingProgress.setVisibility(View.GONE); resetProgressBar(); } @Override public void failed(CharSequence text) { resetProgressBar(); showMessage(text); } @Override public void cancel(CharSequence text) { } @Override public void update(Object arg0) { if (arg0 instanceof Integer) { mProgress.setProgress((Integer) arg0); } else if (arg0 instanceof CharSequence) { showMessage((String) arg0); } } @Override public void setIndeterminate(boolean indeterminate) { mProgress.setIndeterminate(indeterminate); } @Override public Context getContext() { if (mProgress != null) { return mProgress.getContext(); } //if (mLoadingProgress != null) { // return mLoadingProgress.getContext(); //} return null; } @Override public boolean isAvailable() { if (null == mProgress) { Log.e(TAG, "R.id.progress_bar is missing"); return false; } //if (null == mLoadingProgress) { // Log.e(TAG, "R.id.top_refresh_progressBar is missing"); // return false; //} return true; } /** * @param total * 0~100 * @param maxSize * max size of list * @param list * @return */ public static int calProgressBySize(int total, int maxSize, List<?> list) { if (null != list) { return (MAX - (int) Math.floor(list.size() * (total / maxSize))); } return MAX; } private void resetProgressBar() { if (mProgress.isIndeterminate()) { // TODO: 第二次不会出现 mProgress.setIndeterminate(false); } mProgress.setProgress(0); } private void showMessage(CharSequence text) { Toast.makeText(getContext(), text, Toast.LENGTH_LONG).show(); } }
zzys3228-fanfou
src/com/ch_linghu/fanfoudroid/ui/module/SimpleFeedback.java
Java
asf20
2,632
/** * */ package com.ch_linghu.fanfoudroid.ui.module; import java.text.ParseException; import java.util.Date; import android.content.Context; import android.content.SharedPreferences; import android.database.Cursor; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CursorAdapter; import android.widget.FrameLayout; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import com.ch_linghu.fanfoudroid.R; import com.ch_linghu.fanfoudroid.TwitterApplication; import com.ch_linghu.fanfoudroid.app.Preferences; import com.ch_linghu.fanfoudroid.app.SimpleImageLoader; import com.ch_linghu.fanfoudroid.data.Tweet; import com.ch_linghu.fanfoudroid.db.StatusTable; import com.ch_linghu.fanfoudroid.db.TwitterDatabase; import com.ch_linghu.fanfoudroid.util.TextHelper; public class TweetCursorAdapter extends CursorAdapter implements TweetAdapter { private static final String TAG = "TweetCursorAdapter"; private Context mContext; public TweetCursorAdapter(Context context, Cursor cursor) { super(context, cursor); mContext = context; if (context != null) { mInflater = LayoutInflater.from(context); } if (cursor != null) { // TODO: 可使用: // Tweet tweet = StatusTable.parseCursor(cursor); mUserTextColumn = cursor .getColumnIndexOrThrow(StatusTable.USER_SCREEN_NAME); mTextColumn = cursor.getColumnIndexOrThrow(StatusTable.TEXT); mProfileImageUrlColumn = cursor .getColumnIndexOrThrow(StatusTable.PROFILE_IMAGE_URL); mCreatedAtColumn = cursor .getColumnIndexOrThrow(StatusTable.CREATED_AT); mSourceColumn = cursor.getColumnIndexOrThrow(StatusTable.SOURCE); mInReplyToScreenName = cursor .getColumnIndexOrThrow(StatusTable.IN_REPLY_TO_SCREEN_NAME); mFavorited = cursor.getColumnIndexOrThrow(StatusTable.FAVORITED); mThumbnailPic = cursor.getColumnIndexOrThrow(StatusTable.PIC_THUMB); mMiddlePic = cursor.getColumnIndexOrThrow(StatusTable.PIC_MID); mOriginalPic = cursor.getColumnIndexOrThrow(StatusTable.PIC_ORIG); } mMetaBuilder = new StringBuilder(); } private LayoutInflater mInflater; private int mUserTextColumn; private int mTextColumn; private int mProfileImageUrlColumn; private int mCreatedAtColumn; private int mSourceColumn; private int mInReplyToScreenName; private int mFavorited; private int mThumbnailPic; private int mMiddlePic; private int mOriginalPic; private StringBuilder mMetaBuilder; /* * private ProfileImageCacheCallback callback = new * ProfileImageCacheCallback(){ * * @Override public void refresh(String url, Bitmap bitmap) { * TweetCursorAdapter.this.refresh(); } * * }; */ @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { View view = mInflater.inflate(R.layout.tweet, parent, false); TweetCursorAdapter.ViewHolder holder = new ViewHolder(); holder.tweetUserText = (TextView) view .findViewById(R.id.tweet_user_text); holder.tweetText = (TextView) view.findViewById(R.id.tweet_text); holder.profileLayout = (FrameLayout) view.findViewById(R.id.profile_layout); holder.profileImage = (ImageView) view.findViewById(R.id.profile_image); holder.metaText = (TextView) view.findViewById(R.id.tweet_meta_text); holder.fav = (ImageView) view.findViewById(R.id.tweet_fav); holder.has_image = (ImageView) view.findViewById(R.id.tweet_has_image); holder.tweetLayout=(LinearLayout)view.findViewById(R.id.tweet_layout); view.setTag(holder); return view; } private static class ViewHolder { public LinearLayout tweetLayout; public TextView tweetUserText; public TextView tweetText; public FrameLayout profileLayout; public ImageView profileImage; public TextView metaText; public ImageView fav; public ImageView has_image; } @Override public void bindView(View view, Context context, Cursor cursor) { TweetCursorAdapter.ViewHolder holder = (TweetCursorAdapter.ViewHolder) view .getTag(); SharedPreferences pref = TwitterApplication.mPref; // PreferenceManager.getDefaultSharedPreferences(mContext);; boolean useProfileImage = pref.getBoolean( Preferences.USE_PROFILE_IMAGE, true); boolean useHighlightBackground = pref.getBoolean( Preferences.HIGHLIGHT_BACKGROUND, true); holder.tweetUserText.setText(cursor.getString(mUserTextColumn)); TextHelper.setSimpleTweetText(holder.tweetText, cursor.getString(mTextColumn)); String profileImageUrl = cursor.getString(mProfileImageUrlColumn); if (useProfileImage && !TextUtils.isEmpty(profileImageUrl)) { holder.profileLayout.setVisibility(View.VISIBLE); SimpleImageLoader.display(holder.profileImage, profileImageUrl); } else { holder.profileLayout.setVisibility(View.GONE); } if (cursor.getString(mFavorited).equals("true")) { holder.fav.setVisibility(View.VISIBLE); } else { holder.fav.setVisibility(View.GONE); } if (!TextUtils.isEmpty(cursor.getString(mThumbnailPic))) { holder.has_image.setVisibility(View.VISIBLE); } else { holder.has_image.setVisibility(View.GONE); } try { Date createdAt = TwitterDatabase.DB_DATE_FORMATTER.parse(cursor .getString(mCreatedAtColumn)); holder.metaText.setText(Tweet.buildMetaText(mMetaBuilder, createdAt, cursor.getString(mSourceColumn), cursor.getString(mInReplyToScreenName))); } catch (ParseException e) { Log.w(TAG, "Invalid created at data."); } /** * 添加特殊行的背景色 */ if (useHighlightBackground){ String myself = TwitterApplication.getMyselfName(false); StringBuilder b = new StringBuilder(); b.append("@"); b.append(myself); String to_myself = b.toString(); //FIXME: contains操作影响效率,应该在获得时作判断,置标志,在这里对标志进行直接判断。 if(holder.tweetUserText.getText().equals(myself)){ holder.tweetLayout.setBackgroundResource(R.drawable.list_selector_self); holder.profileLayout.setBackgroundResource(R.color.self_background); }else if(holder.tweetText.getText().toString().contains(to_myself)){ holder.tweetLayout.setBackgroundResource(R.drawable.list_selector_mention); holder.profileLayout.setBackgroundResource(R.color.mention_background); }else{ holder.tweetLayout.setBackgroundResource(android.R.drawable.list_selector_background); holder.profileLayout.setBackgroundResource(android.R.color.transparent); } }else{ holder.tweetLayout.setBackgroundResource(android.R.drawable.list_selector_background); holder.profileLayout.setBackgroundResource(android.R.color.transparent); } } @Override public void refresh() { getCursor().requery(); } }
zzys3228-fanfou
src/com/ch_linghu/fanfoudroid/ui/module/TweetCursorAdapter.java
Java
asf20
6,786
package com.ch_linghu.fanfoudroid.ui.module; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.graphics.drawable.AnimationDrawable; import android.text.TextPaint; import android.util.Log; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import com.ch_linghu.fanfoudroid.R; import com.ch_linghu.fanfoudroid.SearchActivity; import com.ch_linghu.fanfoudroid.TwitterActivity; import com.ch_linghu.fanfoudroid.WriteActivity; import com.ch_linghu.fanfoudroid.ui.base.Refreshable; public class NavBar implements Widget { private static final String TAG = "NavBar"; public static final int HEADER_STYLE_HOME = 1; public static final int HEADER_STYLE_WRITE = 2; public static final int HEADER_STYLE_BACK = 3; public static final int HEADER_STYLE_SEARCH = 4; private ImageView mRefreshButton; private ImageButton mSearchButton; private ImageButton mWriteButton; private TextView mTitleButton; private Button mBackButton; private ImageButton mHomeButton; private MenuDialog mDialog; private EditText mSearchEdit; /** @deprecated 已废弃 */ protected AnimationDrawable mRefreshAnimation; private ProgressBar mProgressBar = null; // 进度条(横) private ProgressBar mLoadingProgress = null; // 旋转图标 public NavBar(int style, Context context) { initHeader(style, (Activity) context); } private void initHeader(int style, final Activity activity) { switch (style) { case HEADER_STYLE_HOME: addTitleButtonTo(activity); addWriteButtonTo(activity); addSearchButtonTo(activity); addRefreshButtonTo(activity); break; case HEADER_STYLE_BACK: addBackButtonTo(activity); addWriteButtonTo(activity); addSearchButtonTo(activity); addRefreshButtonTo(activity); break; case HEADER_STYLE_WRITE: addBackButtonTo(activity); break; case HEADER_STYLE_SEARCH: addBackButtonTo(activity); addSearchBoxTo(activity); addSearchButtonTo(activity); break; } } /** * 搜索硬按键行为 * * @deprecated 这个不晓得还有没有用, 已经是已经被新的搜索替代的吧 ? */ public boolean onSearchRequested() { /* * Intent intent = new Intent(); intent.setClass(this, * SearchActivity.class); startActivity(intent); */ return true; } /** * 添加[LOGO/标题]按钮 * * @param acticity */ private void addTitleButtonTo(final Activity acticity) { mTitleButton = (TextView) acticity.findViewById(R.id.title); mTitleButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { int top = mTitleButton.getTop(); int height = mTitleButton.getHeight(); int x = top + height; if (null == mDialog) { Log.d(TAG, "Create menu dialog."); mDialog = new MenuDialog(acticity); mDialog.bindEvent(acticity); mDialog.setPosition(-1, x); } // toggle dialog if (mDialog.isShowing()) { mDialog.dismiss(); // 没机会触发 } else { mDialog.show(); } } }); } /** * 设置标题 * * @param title */ public void setHeaderTitle(String title) { if (null != mTitleButton) { mTitleButton.setText(title); TextPaint tp = mTitleButton.getPaint(); tp.setFakeBoldText(true); // 中文粗体 } } /** * 设置标题 * * @param resource * R.string.xxx */ public void setHeaderTitle(int resource) { if (null != mTitleButton) { mTitleButton.setBackgroundResource(resource); } } /** * 添加[刷新]按钮 * * @param activity */ private void addRefreshButtonTo(final Activity activity) { mRefreshButton = (ImageView) activity.findViewById(R.id.top_refresh); mProgressBar = (ProgressBar) activity.findViewById(R.id.progress_bar); mLoadingProgress = (ProgressBar) activity .findViewById(R.id.top_refresh_progressBar); mRefreshButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if (activity instanceof Refreshable) { ((Refreshable) activity).doRetrieve(); } else { Log.e(TAG, "The current view " + activity.getClass().getName() + " cann't be retrieved"); } } }); } /** * Start/Stop Top Refresh Button's Animation * * @param animate * start or stop * @deprecated use feedback */ public void setRefreshAnimation(boolean animate) { if (mRefreshAnimation != null) { if (animate) { mRefreshAnimation.start(); } else { mRefreshAnimation.setVisible(true, true); // restart mRefreshAnimation.start(); // goTo frame 0 mRefreshAnimation.stop(); } } else { Log.w(TAG, "mRefreshAnimation is null"); } } /** * 添加[搜索]按钮 * * @param activity */ private void addSearchButtonTo(final Activity activity) { mSearchButton = (ImageButton) activity.findViewById(R.id.search); mSearchButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { startSearch(activity); } }); } // 这个方法会在SearchActivity里重写 protected boolean startSearch(final Activity activity) { Intent intent = new Intent(); intent.setClass(activity, SearchActivity.class); activity.startActivity(intent); return true; } /** * 添加[搜索框] * * @param activity */ private void addSearchBoxTo(final Activity activity) { mSearchEdit = (EditText) activity.findViewById(R.id.search_edit); } /** * 添加[撰写]按钮 * * @param activity */ private void addWriteButtonTo(final Activity activity) { mWriteButton = (ImageButton) activity.findViewById(R.id.writeMessage); mWriteButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // forward to write activity Intent intent = new Intent(); intent.setClass(v.getContext(), WriteActivity.class); v.getContext().startActivity(intent); } }); } /** * 添加[回首页]按钮 * * @param activity */ @SuppressWarnings("unused") private void addHomeButton(final Activity activity) { mHomeButton = (ImageButton) activity.findViewById(R.id.home); mHomeButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // 动画 Animation anim = AnimationUtils.loadAnimation(v.getContext(), R.anim.scale_lite); v.startAnimation(anim); // forward to TwitterActivity Intent intent = new Intent(); intent.setClass(v.getContext(), TwitterActivity.class); v.getContext().startActivity(intent); } }); } /** * 添加[返回]按钮 * * @param activity */ private void addBackButtonTo(final Activity activity) { mBackButton = (Button) activity.findViewById(R.id.top_back); // 中文粗体 // TextPaint tp = backButton.getPaint(); // tp.setFakeBoldText(true); mBackButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // Go back to previous activity activity.finish(); } }); } public void destroy() { // dismiss dialog before destroy // to avoid android.view.WindowLeaked Exception if (mDialog != null) { mDialog.dismiss(); mDialog = null; } mRefreshButton = null; mSearchButton = null; mWriteButton = null; mTitleButton = null; mBackButton = null; mHomeButton = null; mSearchButton = null; mSearchEdit = null; mProgressBar = null; mLoadingProgress = null; } public ImageView getRefreshButton() { return mRefreshButton; } public ImageButton getSearchButton() { return mSearchButton; } public ImageButton getWriteButton() { return mWriteButton; } public TextView getTitleButton() { return mTitleButton; } public Button getBackButton() { return mBackButton; } public ImageButton getHomeButton() { return mHomeButton; } public MenuDialog getDialog() { return mDialog; } public EditText getSearchEdit() { return mSearchEdit; } /** @deprecated 已废弃 */ public AnimationDrawable getRefreshAnimation() { return mRefreshAnimation; } public ProgressBar getProgressBar() { return mProgressBar; } public ProgressBar getLoadingProgress() { return mLoadingProgress; } @Override public Context getContext() { if (null != mDialog) { return mDialog.getContext(); } if (null != mTitleButton) { return mTitleButton.getContext(); } return null; } }
zzys3228-fanfou
src/com/ch_linghu/fanfoudroid/ui/module/NavBar.java
Java
asf20
8,578
package com.ch_linghu.fanfoudroid.ui.module; import android.content.Context; import android.util.Log; public class FeedbackFactory { private static final String TAG = "FeedbackFactory"; public static enum FeedbackType { DIALOG, PROGRESS, REFRESH }; public static Feedback create(Context context, FeedbackType type) { Feedback feedback = null; switch (type) { case PROGRESS: feedback = new SimpleFeedback(context); break; } if (null == feedback || !feedback.isAvailable()) { feedback = new FeedbackAdapter(context); Log.e(TAG, type + " feedback is not available."); } return feedback; } public static class FeedbackAdapter implements Feedback { public FeedbackAdapter(Context context) { } @Override public void start(CharSequence text) { } @Override public void cancel(CharSequence text) { } @Override public void success(CharSequence text) { } @Override public void failed(CharSequence text) { } @Override public void update(Object arg0) { } @Override public boolean isAvailable() { return true; } @Override public void setIndeterminate(boolean indeterminate) { } } }
zzys3228-fanfou
src/com/ch_linghu/fanfoudroid/ui/module/FeedbackFactory.java
Java
asf20
1,165
package com.ch_linghu.fanfoudroid.ui.base; import android.app.Activity; import android.content.Intent; import android.graphics.drawable.AnimationDrawable; import android.graphics.drawable.BitmapDrawable; import android.text.TextPaint; import android.util.Log; import android.view.View; import android.view.ViewGroup; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.RelativeLayout.LayoutParams; import android.widget.TextView; import com.ch_linghu.fanfoudroid.R; import com.ch_linghu.fanfoudroid.SearchActivity; import com.ch_linghu.fanfoudroid.TwitterActivity; import com.ch_linghu.fanfoudroid.WriteActivity; import com.ch_linghu.fanfoudroid.ui.module.Feedback; import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory; import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory.FeedbackType; import com.ch_linghu.fanfoudroid.ui.module.MenuDialog; import com.ch_linghu.fanfoudroid.ui.module.NavBar; /** * @deprecated 使用 {@link NavBar} 代替 */ public class WithHeaderActivity extends BaseActivity { private static final String TAG = "WithHeaderActivity"; public static final int HEADER_STYLE_HOME = 1; public static final int HEADER_STYLE_WRITE = 2; public static final int HEADER_STYLE_BACK = 3; public static final int HEADER_STYLE_SEARCH = 4; protected ImageView refreshButton; protected ImageButton searchButton; protected ImageButton writeButton; protected TextView titleButton; protected Button backButton; protected ImageButton homeButton; protected MenuDialog dialog; protected EditText searchEdit; protected Feedback mFeedback; // FIXME: 刷新动画二选一, DELETE ME protected AnimationDrawable mRefreshAnimation; protected ProgressBar mProgress = null; protected ProgressBar mLoadingProgress = null; // 搜索硬按键行为 @Override public boolean onSearchRequested() { Intent intent = new Intent(); intent.setClass(this, SearchActivity.class); startActivity(intent); return true; } // LOGO按钮 protected void addTitleButton() { titleButton = (TextView) findViewById(R.id.title); titleButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { int top = titleButton.getTop(); int height = titleButton.getHeight(); int x = top + height; if (null == dialog) { Log.d(TAG, "Create menu dialog."); dialog = new MenuDialog(WithHeaderActivity.this); dialog.bindEvent(WithHeaderActivity.this); dialog.setPosition(-1, x); } // toggle dialog if (dialog.isShowing()) { dialog.dismiss(); // 没机会触发 } else { dialog.show(); } } }); } protected void setHeaderTitle(String title) { titleButton.setBackgroundDrawable(new BitmapDrawable()); titleButton.setText(title); LayoutParams lp = new LayoutParams( android.view.ViewGroup.LayoutParams.WRAP_CONTENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT); lp.setMargins(3, 12, 0, 0); titleButton.setLayoutParams(lp); // 中文粗体 TextPaint tp = titleButton.getPaint(); tp.setFakeBoldText(true); } protected void setHeaderTitle(int resource) { titleButton.setBackgroundResource(resource); } // 刷新 protected void addRefreshButton() { final Activity that = this; refreshButton = (ImageView) findViewById(R.id.top_refresh); // FIXME: 暂时取消旋转效果, 测试ProgressBar // refreshButton.setBackgroundResource(R.drawable.top_refresh); // mRefreshAnimation = (AnimationDrawable) // refreshButton.getBackground(); // FIXME: DELETE ME mProgress = (ProgressBar) findViewById(R.id.progress_bar); mLoadingProgress = (ProgressBar) findViewById(R.id.top_refresh_progressBar); mFeedback = FeedbackFactory.create(this, FeedbackType.PROGRESS); refreshButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if (that instanceof Refreshable) { ((Refreshable) that).doRetrieve(); } else { Log.e(TAG, "The current view " + that.getClass().getName() + " cann't be retrieved"); } } }); } /** * @param v * @deprecated use {@link WithHeaderActivity#setRefreshAnimation(boolean)} */ protected void animRotate(View v) { setRefreshAnimation(true); } /** * @param progress * 0~100 * @deprecated use feedback */ public void setGlobalProgress(int progress) { if (null != mProgress) { mProgress.setProgress(progress); } } /** * Start/Stop Top Refresh Button's Animation * * @param animate * start or stop * @deprecated use feedback */ public void setRefreshAnimation(boolean animate) { if (mRefreshAnimation != null) { if (animate) { mRefreshAnimation.start(); } else { mRefreshAnimation.setVisible(true, true); // restart mRefreshAnimation.start(); // goTo frame 0 mRefreshAnimation.stop(); } } else { Log.w(TAG, "mRefreshAnimation is null"); } } // 搜索 protected void addSearchButton() { searchButton = (ImageButton) findViewById(R.id.search); searchButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // // 旋转动画 // Animation anim = AnimationUtils.loadAnimation(v.getContext(), // R.anim.scale_lite); // v.startAnimation(anim); // go to SearchActivity startSearch(); } }); } // 这个方法会在SearchActivity里重写 protected boolean startSearch() { Intent intent = new Intent(); intent.setClass(this, SearchActivity.class); startActivity(intent); return true; } // 搜索框 protected void addSearchBox() { searchEdit = (EditText) findViewById(R.id.search_edit); } // 撰写 protected void addWriteButton() { writeButton = (ImageButton) findViewById(R.id.writeMessage); writeButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // 动画 Animation anim = AnimationUtils.loadAnimation(v.getContext(), R.anim.scale_lite); v.startAnimation(anim); // forward to write activity Intent intent = new Intent(); intent.setClass(v.getContext(), WriteActivity.class); v.getContext().startActivity(intent); } }); } // 回首页 protected void addHomeButton() { homeButton = (ImageButton) findViewById(R.id.home); homeButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // 动画 Animation anim = AnimationUtils.loadAnimation(v.getContext(), R.anim.scale_lite); v.startAnimation(anim); // forward to TwitterActivity Intent intent = new Intent(); intent.setClass(v.getContext(), TwitterActivity.class); v.getContext().startActivity(intent); } }); } // 返回 protected void addBackButton() { backButton = (Button) findViewById(R.id.top_back); // 中文粗体 // TextPaint tp = backButton.getPaint(); // tp.setFakeBoldText(true); backButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // Go back to previous activity finish(); } }); } protected void initHeader(int style) { // FIXME: android 1.6似乎不支持addHeaderView中使用的方法 // 来增加header,造成header无法显示和使用。 // 改用在layout xml里include的方法来确保显示 switch (style) { case HEADER_STYLE_HOME: // addHeaderView(R.layout.header); addTitleButton(); addWriteButton(); addSearchButton(); addRefreshButton(); break; case HEADER_STYLE_BACK: // addHeaderView(R.layout.header_back); addBackButton(); addWriteButton(); addSearchButton(); addRefreshButton(); break; case HEADER_STYLE_WRITE: // addHeaderView(R.layout.header_write); addBackButton(); // addHomeButton(); break; case HEADER_STYLE_SEARCH: // addHeaderView(R.layout.header_search); addBackButton(); addSearchBox(); addSearchButton(); break; } } private void addHeaderView(int resource) { // find content root view ViewGroup root = (ViewGroup) getWindow().getDecorView(); ViewGroup content = (ViewGroup) root.getChildAt(0); View header = View.inflate(WithHeaderActivity.this, resource, null); // LayoutParams params = new // LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT); content.addView(header, 0); } @Override protected void onDestroy() { // dismiss dialog before destroy // to avoid android.view.WindowLeaked Exception if (dialog != null) { dialog.dismiss(); } super.onDestroy(); } }
zzys3228-fanfou
src/com/ch_linghu/fanfoudroid/ui/base/WithHeaderActivity.java
Java
asf20
8,671
package com.ch_linghu.fanfoudroid.ui.base; import java.util.ArrayList; import java.util.List; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; import com.ch_linghu.fanfoudroid.R; import com.ch_linghu.fanfoudroid.data.Tweet; import com.ch_linghu.fanfoudroid.data.User; import com.ch_linghu.fanfoudroid.fanfou.Paging; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.task.GenericTask; import com.ch_linghu.fanfoudroid.task.TaskAdapter; import com.ch_linghu.fanfoudroid.task.TaskListener; import com.ch_linghu.fanfoudroid.task.TaskManager; import com.ch_linghu.fanfoudroid.task.TaskParams; import com.ch_linghu.fanfoudroid.task.TaskResult; import com.ch_linghu.fanfoudroid.ui.module.SimpleFeedback; import com.ch_linghu.fanfoudroid.ui.module.TweetAdapter; import com.ch_linghu.fanfoudroid.ui.module.UserArrayAdapter; public abstract class UserArrayBaseActivity extends UserListBaseActivity { static final String TAG = "UserArrayBaseActivity"; // Views. //protected PullToRefreshListView mUserList; protected ListView mUserList; protected UserArrayAdapter mUserListAdapter; protected TextView loadMoreBtn; protected ProgressBar loadMoreGIF; protected TextView loadMoreBtnTop; protected ProgressBar loadMoreGIFTop; // Tasks. protected TaskManager taskManager = new TaskManager(); private GenericTask mRetrieveTask; private GenericTask mFollowersRetrieveTask; private GenericTask mGetMoreTask;// 每次100用户 private static class State { State(UserArrayBaseActivity activity) { allUserList = activity.allUserList; } public ArrayList<com.ch_linghu.fanfoudroid.data.User> allUserList; } public abstract Paging getCurrentPage();// 加载 public abstract Paging getNextPage();// 加载 // protected abstract String[] getIds(); protected abstract List<com.ch_linghu.fanfoudroid.fanfou.User> getUsers( String userId, Paging page) throws HttpException; private ArrayList<com.ch_linghu.fanfoudroid.data.User> allUserList; @Override protected boolean _onCreate(Bundle savedInstanceState) { Log.d(TAG, "onCreate."); if (super._onCreate(savedInstanceState)) { State state = (State) getLastNonConfigurationInstance(); if (state != null){ allUserList = state.allUserList; draw(); }else{ doRetrieve();// 加载第一页 } return true; } else { return false; } } @Override protected String getUserId() { // TODO Auto-generated method stub return null; } @Override public void doRetrieve() { Log.d(TAG, "Attempting retrieve."); if (mRetrieveTask != null && mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { mRetrieveTask = new RetrieveTask(); mRetrieveTask.setFeedback(mFeedback); mRetrieveTask.setListener(mRetrieveTaskListener); mRetrieveTask.execute(); // Add Task to manager taskManager.addTask(mRetrieveTask); } } private TaskListener mRetrieveTaskListener = new TaskAdapter() { @Override public String getName() { return "RetrieveTask"; } @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.AUTH_ERROR) { logout(); } else if (result == TaskResult.OK) { draw(); } //mUserList.onRefreshComplete(); updateProgress(""); } @Override public void onPreExecute(GenericTask task) { onRetrieveBegin(); } @Override public void onProgressUpdate(GenericTask task, Object param) { Log.d(TAG, "onProgressUpdate"); draw(); } }; public void updateProgress(String progress) { mProgressText.setText(progress); } public void onRetrieveBegin() { updateProgress(getString(R.string.page_status_refreshing)); } /** * TODO:从API获取当前Followers * * @author Dino * */ private class RetrieveTask extends GenericTask { @Override protected TaskResult _doInBackground(TaskParams... params) { Log.d(TAG, "load RetrieveTask"); List<com.ch_linghu.fanfoudroid.fanfou.User> usersList = null; try { usersList = getUsers(getUserId(), getCurrentPage()); } catch (HttpException e) { e.printStackTrace(); return TaskResult.IO_ERROR; } publishProgress(SimpleFeedback.calProgressBySize(40, 20, usersList)); allUserList.clear(); for (com.ch_linghu.fanfoudroid.fanfou.User user : usersList) { if (isCancelled()) { return TaskResult.CANCELLED; } User u = User.create(user); allUserList.add(u); if (isCancelled()) { return TaskResult.CANCELLED; } } return TaskResult.OK; } } @Override protected int getLayoutId() { return R.layout.follower; } @Override protected void setupState() { setTitle(getActivityTitle()); mUserList = (ListView) findViewById(R.id.follower_list); setupListHeader(true); mUserListAdapter = new UserArrayAdapter(this); mUserList.setAdapter(mUserListAdapter); allUserList = new ArrayList<com.ch_linghu.fanfoudroid.data.User>(); } @Override protected String getActivityTitle() { // TODO Auto-generated method stub return null; } @Override protected boolean useBasicMenu() { return true; } @Override protected User getContextItemUser(int position) { // position = position - 1; Log.d(TAG, "list position:" + position); // 加入footer跳过footer if (position < mUserListAdapter.getCount()) { User item = (User) mUserListAdapter.getItem(position); if (item == null) { return null; } else { return item; } } else { return null; } } /** * TODO:不知道啥用 */ @Override protected void updateTweet(Tweet tweet) { // TODO Auto-generated method stub } @Override protected ListView getUserList() { return mUserList; } @Override protected TweetAdapter getUserAdapter() { return mUserListAdapter; } /** * 绑定listView底部 - 载入更多 NOTE: 必须在listView#setAdapter之前调用 */ protected void setupListHeader(boolean addFooter) { // Add footer to Listview View footer = View.inflate(this, R.layout.listview_footer, null); mUserList.addFooterView(footer, null, true); // mUserList.setOnRefreshListener(new OnRefreshListener() { // // @Override // public void onRefresh() { // doRetrieve(); // // } // }); // Find View loadMoreBtn = (TextView) findViewById(R.id.ask_for_more); loadMoreGIF = (ProgressBar) findViewById(R.id.rectangleProgressBar); } @Override protected void specialItemClicked(int position) { if (position == mUserList.getCount() - 1) { // footer loadMoreGIF.setVisibility(View.VISIBLE); doGetMore(); } } public void doGetMore() { Log.d(TAG, "Attempting getMore."); mFeedback.start(""); if (mGetMoreTask != null && mGetMoreTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { mGetMoreTask = new GetMoreTask(); mGetMoreTask.setListener(getMoreListener); mGetMoreTask.execute(); // Add Task to manager taskManager.addTask(mGetMoreTask); } } private TaskListener getMoreListener = new TaskAdapter() { @Override public String getName() { return "getMore"; } @Override public void onPostExecute(GenericTask task, TaskResult result) { super.onPostExecute(task, result); draw(); mFeedback.success(""); loadMoreGIF.setVisibility(View.GONE); } }; /** * TODO:需要重写,获取下一批用户,按页分100页一次 * * @author Dino * */ private class GetMoreTask extends GenericTask { @Override protected TaskResult _doInBackground(TaskParams... params) { Log.d(TAG, "load RetrieveTask"); List<com.ch_linghu.fanfoudroid.fanfou.User> usersList = null; try { usersList = getUsers(getUserId(), getNextPage()); mFeedback.update(60); } catch (HttpException e) { e.printStackTrace(); return TaskResult.IO_ERROR; } // 将获取到的数据(保存/更新)到数据库 getDb().syncWeiboUsers(usersList); mFeedback.update(100 - (int) Math.floor(usersList.size() * 2)); for (com.ch_linghu.fanfoudroid.fanfou.User user : usersList) { if (isCancelled()) { return TaskResult.CANCELLED; } allUserList.add(User.create(user)); if (isCancelled()) { return TaskResult.CANCELLED; } } mFeedback.update(99); return TaskResult.OK; } } public void draw() { mUserListAdapter.refresh(allUserList); } @Override public Object onRetainNonConfigurationInstance() { return createState(); } private synchronized State createState() { return new State(this); } }
zzys3228-fanfou
src/com/ch_linghu/fanfoudroid/ui/base/UserArrayBaseActivity.java
Java
asf20
9,000
/* * Copyright (C) 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ch_linghu.fanfoudroid.ui.base; import java.util.ArrayList; import java.util.List; import android.content.SharedPreferences; import android.database.Cursor; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.View; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; import com.ch_linghu.fanfoudroid.R; import com.ch_linghu.fanfoudroid.app.Preferences; import com.ch_linghu.fanfoudroid.data.Tweet; import com.ch_linghu.fanfoudroid.data.User; import com.ch_linghu.fanfoudroid.db.UserInfoTable; import com.ch_linghu.fanfoudroid.fanfou.Paging; import com.ch_linghu.fanfoudroid.fanfou.Status; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.task.GenericTask; import com.ch_linghu.fanfoudroid.task.TaskAdapter; import com.ch_linghu.fanfoudroid.task.TaskListener; import com.ch_linghu.fanfoudroid.task.TaskManager; import com.ch_linghu.fanfoudroid.task.TaskParams; import com.ch_linghu.fanfoudroid.task.TaskResult; import com.ch_linghu.fanfoudroid.ui.module.SimpleFeedback; import com.ch_linghu.fanfoudroid.ui.module.TweetAdapter; import com.ch_linghu.fanfoudroid.ui.module.UserCursorAdapter; import com.ch_linghu.fanfoudroid.util.DateTimeHelper; /** * TwitterCursorBaseLine用于带有静态数据来源(对应数据库的,与twitter表同构的特定表)的展现 */ public abstract class UserCursorBaseActivity extends UserListBaseActivity { /** * 第一种方案:(采取第一种) 暂不放在数据库中,直接从Api读取。 * * 第二种方案: 麻烦的是api数据与数据库同步,当收听人数比较多的时候,一次性读取太费流量 按照饭否api每次分页100人 * 当收听数<100时先从数据库一次性根据API返回的ID列表读取数据,如果数据库中的收听数<总数,那么从API中读取所有用户信息并同步到数据库中。 * 当收听数>100时采取分页加载,先按照id * 获取数据库里前100用户,如果用户数量<100则从api中加载,从page=1开始下载,同步到数据库中,单击更多继续从数据库中加载 * 当数据库中的数据读取到最后一页后,则从api中加载并更新到数据库中。 单击刷新按钮则从api加载并同步到数据库中 * */ static final String TAG = "UserCursorBaseActivity"; // Views. protected ListView mUserList; protected UserCursorAdapter mUserListAdapter; protected TextView loadMoreBtn; protected ProgressBar loadMoreGIF; protected TextView loadMoreBtnTop; protected ProgressBar loadMoreGIFTop; protected static int lastPosition = 0; // Tasks. protected TaskManager taskManager = new TaskManager(); private GenericTask mRetrieveTask; private GenericTask mFollowersRetrieveTask; private GenericTask mGetMoreTask;// 每次十个用户 protected abstract String getUserId();// 获得用户id private TaskListener mRetrieveTaskListener = new TaskAdapter() { @Override public String getName() { return "RetrieveTask"; } @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.AUTH_ERROR) { logout(); } else if (result == TaskResult.OK) { SharedPreferences.Editor editor = getPreferences().edit(); editor.putLong(Preferences.LAST_TWEET_REFRESH_KEY, DateTimeHelper.getNowTime()); editor.commit(); // TODO: 1. StatusType(DONE) ; 2. 只有在取回的数据大于MAX时才做GC, // 因为小于时可以保证数据的连续性 // FIXME: gc需要带owner // getDb().gc(getDatabaseType()); // GC draw(); goTop(); } else { // Do nothing. } // loadMoreGIFTop.setVisibility(View.GONE); updateProgress(""); } @Override public void onPreExecute(GenericTask task) { onRetrieveBegin(); } @Override public void onProgressUpdate(GenericTask task, Object param) { Log.d(TAG, "onProgressUpdate"); draw(); } }; private TaskListener mFollowerRetrieveTaskListener = new TaskAdapter() { @Override public String getName() { return "FollowerRetrieve"; } @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.OK) { SharedPreferences sp = getPreferences(); SharedPreferences.Editor editor = sp.edit(); editor.putLong(Preferences.LAST_FOLLOWERS_REFRESH_KEY, DateTimeHelper.getNowTime()); editor.commit(); } else { // Do nothing. } } }; // Refresh data at startup if last refresh was this long ago or greater. private static final long REFRESH_THRESHOLD = 5 * 60 * 1000; // Refresh followers if last refresh was this long ago or greater. private static final long FOLLOWERS_REFRESH_THRESHOLD = 12 * 60 * 60 * 1000; abstract protected Cursor fetchUsers(); public abstract int getDatabaseType(); public abstract String fetchMaxId(); public abstract String fetchMinId(); public abstract List<com.ch_linghu.fanfoudroid.fanfou.User> getUsers() throws HttpException; public abstract void addUsers( ArrayList<com.ch_linghu.fanfoudroid.data.User> tusers); // public abstract List<Status> getMessageSinceId(String maxId) // throws WeiboException; public abstract List<com.ch_linghu.fanfoudroid.fanfou.User> getUserSinceId( String maxId) throws HttpException; public abstract List<Status> getMoreMessageFromId(String minId) throws HttpException; public abstract Paging getNextPage();// 下一页数 public abstract Paging getCurrentPage();// 当前页数 protected abstract String[] getIds(); public static final int CONTEXT_REPLY_ID = Menu.FIRST + 1; // public static final int CONTEXT_AT_ID = Menu.FIRST + 2; public static final int CONTEXT_RETWEET_ID = Menu.FIRST + 3; public static final int CONTEXT_DM_ID = Menu.FIRST + 4; public static final int CONTEXT_MORE_ID = Menu.FIRST + 5; public static final int CONTEXT_ADD_FAV_ID = Menu.FIRST + 6; public static final int CONTEXT_DEL_FAV_ID = Menu.FIRST + 7; @Override protected void setupState() { Cursor cursor; cursor = fetchUsers(); // setTitle(getActivityTitle()); startManagingCursor(cursor); mUserList = (ListView) findViewById(R.id.follower_list); // TODO: 需处理没有数据时的情况 Log.d("LDS", cursor.getCount() + " cursor count"); setupListHeader(true); mUserListAdapter = new UserCursorAdapter(this, cursor); mUserList.setAdapter(mUserListAdapter); // ? registerOnClickListener(mTweetList); } /** * 绑定listView底部 - 载入更多 NOTE: 必须在listView#setAdapter之前调用 */ protected void setupListHeader(boolean addFooter) { // Add footer to Listview View footer = View.inflate(this, R.layout.listview_footer, null); mUserList.addFooterView(footer, null, true); // Find View loadMoreBtn = (TextView) findViewById(R.id.ask_for_more); loadMoreGIF = (ProgressBar) findViewById(R.id.rectangleProgressBar); // loadMoreBtnTop = (TextView)findViewById(R.id.ask_for_more_header); // loadMoreGIFTop = // (ProgressBar)findViewById(R.id.rectangleProgressBar_header); // loadMoreAnimation = (AnimationDrawable) // loadMoreGIF.getIndeterminateDrawable(); } @Override protected void specialItemClicked(int position) { if (position == mUserList.getCount() - 1) { // footer loadMoreGIF.setVisibility(View.VISIBLE); doGetMore(); } } @Override protected int getLayoutId() { return R.layout.follower; } @Override protected ListView getUserList() { return mUserList; } @Override protected TweetAdapter getUserAdapter() { return mUserListAdapter; } @Override protected boolean useBasicMenu() { return true; } protected User getContextItemUser(int position) { // position = position - 1; // 加入footer跳过footer if (position < mUserListAdapter.getCount()) { Cursor cursor = (Cursor) mUserListAdapter.getItem(position); if (cursor == null) { return null; } else { return UserInfoTable.parseCursor(cursor); } } else { return null; } } @Override protected void updateTweet(Tweet tweet) { // TODO: updateTweet() 在哪里调用的? 目前尚只支持: // updateTweet(String tweetId, ContentValues values) // setFavorited(String tweetId, String isFavorited) // 看是否还需要增加updateTweet(Tweet tweet)方法 // 对所有相关表的对应消息都进行刷新(如果存在的话) // getDb().updateTweet(TwitterDbAdapter.TABLE_FAVORITE, tweet); // getDb().updateTweet(TwitterDbAdapter.TABLE_MENTION, tweet); // getDb().updateTweet(TwitterDbAdapter.TABLE_TWEET, tweet); } @Override protected boolean _onCreate(Bundle savedInstanceState) { Log.d(TAG, "onCreate."); if (super._onCreate(savedInstanceState)) { goTop(); // skip the header boolean shouldRetrieve = false; // FIXME: 该子类页面全部使用了这个统一的计时器,导致进入Mention等分页面后经常不会自动刷新 long lastRefreshTime = mPreferences.getLong( Preferences.LAST_TWEET_REFRESH_KEY, 0); long nowTime = DateTimeHelper.getNowTime(); long diff = nowTime - lastRefreshTime; Log.d(TAG, "Last refresh was " + diff + " ms ago."); /* * if (diff > REFRESH_THRESHOLD) { shouldRetrieve = true; } else if * (Utils.isTrue(savedInstanceState, SIS_RUNNING_KEY)) { // Check to * see if it was running a send or retrieve task. // It makes no * sense to resend the send request (don't want dupes) // so we * instead retrieve (refresh) to see if the message has // posted. * Log.d(TAG, * "Was last running a retrieve or send task. Let's refresh."); * shouldRetrieve = true; } */ shouldRetrieve = true; if (shouldRetrieve) { doRetrieve(); } long lastFollowersRefreshTime = mPreferences.getLong( Preferences.LAST_FOLLOWERS_REFRESH_KEY, 0); diff = nowTime - lastFollowersRefreshTime; Log.d(TAG, "Last followers refresh was " + diff + " ms ago."); /* * if (diff > FOLLOWERS_REFRESH_THRESHOLD && (mRetrieveTask == null * || mRetrieveTask.getStatus() != GenericTask.Status.RUNNING)) { * Log.d(TAG, "Refresh followers."); doRetrieveFollowers(); } */ return true; } else { return false; } } @Override protected void onResume() { Log.d(TAG, "onResume."); if (lastPosition != 0) { mUserList.setSelection(lastPosition); } super.onResume(); checkIsLogedIn(); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (mRetrieveTask != null && mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) { outState.putBoolean(SIS_RUNNING_KEY, true); } } @Override protected void onRestoreInstanceState(Bundle bundle) { super.onRestoreInstanceState(bundle); // mTweetEdit.updateCharsRemain(); } @Override protected void onDestroy() { Log.d(TAG, "onDestroy."); super.onDestroy(); taskManager.cancelAll(); } @Override protected void onPause() { Log.d(TAG, "onPause."); super.onPause(); lastPosition = mUserList.getFirstVisiblePosition(); } @Override protected void onRestart() { Log.d(TAG, "onRestart."); super.onRestart(); } @Override protected void onStart() { Log.d(TAG, "onStart."); super.onStart(); } @Override protected void onStop() { Log.d(TAG, "onStop."); super.onStop(); } // UI helpers. @Override protected String getActivityTitle() { // TODO Auto-generated method stub return null; } @Override protected void adapterRefresh() { mUserListAdapter.notifyDataSetChanged(); mUserListAdapter.refresh(); } // Retrieve interface public void updateProgress(String progress) { mProgressText.setText(progress); } public void draw() { mUserListAdapter.refresh(); } public void goTop() { Log.d(TAG, "goTop."); mUserList.setSelection(1); } private void doRetrieveFollowers() { Log.d(TAG, "Attempting followers retrieve."); if (mFollowersRetrieveTask != null && mFollowersRetrieveTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { mFollowersRetrieveTask = new FollowersRetrieveTask(); mFollowersRetrieveTask.setListener(mFollowerRetrieveTaskListener); mFollowersRetrieveTask.execute(); taskManager.addTask(mFollowersRetrieveTask); // Don't need to cancel FollowersTask (assuming it ends properly). mFollowersRetrieveTask.setCancelable(false); } } public void onRetrieveBegin() { updateProgress(getString(R.string.page_status_refreshing)); } public void doRetrieve() { Log.d(TAG, "Attempting retrieve."); if (mRetrieveTask != null && mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { mRetrieveTask = new RetrieveTask(); mRetrieveTask.setListener(mRetrieveTaskListener); mRetrieveTask.setFeedback(mFeedback); mRetrieveTask.execute(); // Add Task to manager taskManager.addTask(mRetrieveTask); } } /** * TODO:从API获取当前Followers,并同步到数据库 * * @author Dino * */ private class RetrieveTask extends GenericTask { @Override protected TaskResult _doInBackground(TaskParams... params) { Log.d(TAG, "load RetrieveTask"); List<com.ch_linghu.fanfoudroid.fanfou.User> usersList = null; try { usersList = getApi().getFollowersList(getUserId(), getCurrentPage()); } catch (HttpException e) { e.printStackTrace(); } publishProgress(SimpleFeedback.calProgressBySize(40, 20, usersList)); ArrayList<User> users = new ArrayList<User>(); for (com.ch_linghu.fanfoudroid.fanfou.User user : usersList) { if (isCancelled()) { return TaskResult.CANCELLED; } users.add(User.create(user)); if (isCancelled()) { return TaskResult.CANCELLED; } } addUsers(users); return TaskResult.OK; } } private class FollowersRetrieveTask extends GenericTask { @Override protected TaskResult _doInBackground(TaskParams... params) { try { Log.d(TAG, "load FollowersErtrieveTask"); List<com.ch_linghu.fanfoudroid.fanfou.User> t_users = getUsers(); getDb().syncWeiboUsers(t_users); } catch (HttpException e) { Log.e(TAG, e.getMessage(), e); return TaskResult.IO_ERROR; } return TaskResult.OK; } } /** * TODO:需要重写,获取下一批用户,按页分100页一次 * * @author Dino * */ private class GetMoreTask extends GenericTask { @Override protected TaskResult _doInBackground(TaskParams... params) { Log.d(TAG, "load RetrieveTask"); List<com.ch_linghu.fanfoudroid.fanfou.User> usersList = null; try { usersList = getApi().getFollowersList(getUserId(), getNextPage()); } catch (HttpException e) { e.printStackTrace(); } publishProgress(SimpleFeedback.calProgressBySize(40, 20, usersList)); ArrayList<User> users = new ArrayList<User>(); for (com.ch_linghu.fanfoudroid.fanfou.User user : usersList) { if (isCancelled()) { return TaskResult.CANCELLED; } users.add(User.create(user)); if (isCancelled()) { return TaskResult.CANCELLED; } } addUsers(users); return TaskResult.OK; } } private TaskListener getMoreListener = new TaskAdapter() { @Override public String getName() { return "getMore"; } @Override public void onPostExecute(GenericTask task, TaskResult result) { super.onPostExecute(task, result); draw(); loadMoreGIF.setVisibility(View.GONE); } }; public void doGetMore() { Log.d(TAG, "Attempting getMore."); if (mGetMoreTask != null && mGetMoreTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { mGetMoreTask = new GetMoreTask(); mGetMoreTask.setFeedback(mFeedback); mGetMoreTask.setListener(getMoreListener); mGetMoreTask.execute(); // Add Task to manager taskManager.addTask(mGetMoreTask); } } }
zzys3228-fanfou
src/com/ch_linghu/fanfoudroid/ui/base/UserCursorBaseActivity.java
Java
asf20
16,453
package com.ch_linghu.fanfoudroid.ui.base; public interface Refreshable { void doRetrieve(); }
zzys3228-fanfou
src/com/ch_linghu/fanfoudroid/ui/base/Refreshable.java
Java
asf20
97
package com.ch_linghu.fanfoudroid.ui.base; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.ActivityInfo; import android.os.Bundle; import android.preference.PreferenceManager; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import com.ch_linghu.fanfoudroid.AboutActivity; import com.ch_linghu.fanfoudroid.LoginActivity; import com.ch_linghu.fanfoudroid.PreferencesActivity; import com.ch_linghu.fanfoudroid.R; import com.ch_linghu.fanfoudroid.TwitterActivity; import com.ch_linghu.fanfoudroid.TwitterApplication; import com.ch_linghu.fanfoudroid.app.Preferences; import com.ch_linghu.fanfoudroid.db.TwitterDatabase; import com.ch_linghu.fanfoudroid.fanfou.Weibo; import com.ch_linghu.fanfoudroid.service.TwitterService; /** * A BaseActivity has common routines and variables for an Activity that * contains a list of tweets and a text input field. * * Not the cleanest design, but works okay for several Activities in this app. */ public class BaseActivity extends Activity { private static final String TAG = "BaseActivity"; protected SharedPreferences mPreferences; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); _onCreate(savedInstanceState); } // 因为onCreate方法无法返回状态,因此无法进行状态判断, // 为了能对上层返回的信息进行判断处理,我们使用_onCreate代替真正的 // onCreate进行工作。onCreate仅在顶层调用_onCreate。 protected boolean _onCreate(Bundle savedInstanceState) { if (TwitterApplication.mPref.getBoolean( Preferences.FORCE_SCREEN_ORIENTATION_PORTRAIT, false)) { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } if (!checkIsLogedIn()) { return false; } else { PreferenceManager.setDefaultValues(this, R.xml.preferences, false); mPreferences = TwitterApplication.mPref; // PreferenceManager.getDefaultSharedPreferences(this); return true; } } protected void handleLoggedOut() { if (isTaskRoot()) { showLogin(); } else { setResult(RESULT_LOGOUT); } finish(); } public TwitterDatabase getDb() { return TwitterApplication.mDb; } public Weibo getApi() { return TwitterApplication.mApi; } public SharedPreferences getPreferences() { return mPreferences; } @Override protected void onDestroy() { super.onDestroy(); } protected boolean isLoggedIn() { return getApi().isLoggedIn(); } private static final int RESULT_LOGOUT = RESULT_FIRST_USER + 1; // Retrieve interface // public ImageManager getImageManager() { // return TwitterApplication.mImageManager; // } private void _logout() { TwitterService.unschedule(BaseActivity.this); getDb().clearData(); getApi().reset(); // Clear SharedPreferences SharedPreferences.Editor editor = mPreferences.edit(); editor.clear(); editor.commit(); // TODO: 提供用户手动情况所有缓存选项 TwitterApplication.mImageLoader.getImageManager().clear(); // TODO: cancel notifications. TwitterService.unschedule(BaseActivity.this); handleLoggedOut(); } public void logout() { Dialog dialog = new AlertDialog.Builder(BaseActivity.this) .setTitle("提示").setMessage("确实要注销吗?") .setPositiveButton("确定", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { _logout(); } }).setNegativeButton("取消", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }).create(); dialog.show(); } protected void showLogin() { Intent intent = new Intent(this, LoginActivity.class); // TODO: might be a hack? intent.putExtra(Intent.EXTRA_INTENT, getIntent()); startActivity(intent); } protected void manageUpdateChecks() { // 检查后台更新状态设置 boolean isUpdateEnabled = mPreferences.getBoolean( Preferences.CHECK_UPDATES_KEY, false); if (isUpdateEnabled) { TwitterService.schedule(this); } else if (!TwitterService.isWidgetEnabled()) { TwitterService.unschedule(this); } // 检查强制竖屏设置 boolean isOrientationPortrait = mPreferences.getBoolean( Preferences.FORCE_SCREEN_ORIENTATION_PORTRAIT, false); if (isOrientationPortrait) { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); } else { setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED); } } // Menus. protected static final int OPTIONS_MENU_ID_LOGOUT = 1; protected static final int OPTIONS_MENU_ID_PREFERENCES = 2; protected static final int OPTIONS_MENU_ID_ABOUT = 3; protected static final int OPTIONS_MENU_ID_SEARCH = 4; protected static final int OPTIONS_MENU_ID_REPLIES = 5; protected static final int OPTIONS_MENU_ID_DM = 6; protected static final int OPTIONS_MENU_ID_TWEETS = 7; protected static final int OPTIONS_MENU_ID_TOGGLE_REPLIES = 8; protected static final int OPTIONS_MENU_ID_FOLLOW = 9; protected static final int OPTIONS_MENU_ID_UNFOLLOW = 10; protected static final int OPTIONS_MENU_ID_IMAGE_CAPTURE = 11; protected static final int OPTIONS_MENU_ID_PHOTO_LIBRARY = 12; protected static final int OPTIONS_MENU_ID_EXIT = 13; /** * 如果增加了Option Menu常量的数量,则必须重载此方法, 以保证其他人使用常量时不产生重复 * * @return 最大的Option Menu常量 */ protected int getLastOptionMenuId() { return OPTIONS_MENU_ID_EXIT; } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); // SubMenu submenu = // menu.addSubMenu(R.string.write_label_insert_picture); // submenu.setIcon(android.R.drawable.ic_menu_gallery); // // submenu.add(0, OPTIONS_MENU_ID_IMAGE_CAPTURE, 0, // R.string.write_label_take_a_picture); // submenu.add(0, OPTIONS_MENU_ID_PHOTO_LIBRARY, 0, // R.string.write_label_choose_a_picture); // // MenuItem item = menu.add(0, OPTIONS_MENU_ID_SEARCH, 0, // R.string.omenu_search); // item.setIcon(android.R.drawable.ic_search_category_default); // item.setAlphabeticShortcut(SearchManager.MENU_KEY); MenuItem item; item = menu.add(0, OPTIONS_MENU_ID_PREFERENCES, 0, R.string.omenu_settings); item.setIcon(android.R.drawable.ic_menu_preferences); item = menu.add(0, OPTIONS_MENU_ID_LOGOUT, 0, R.string.omenu_signout); item.setIcon(android.R.drawable.ic_menu_revert); item = menu.add(0, OPTIONS_MENU_ID_ABOUT, 0, R.string.omenu_about); item.setIcon(android.R.drawable.ic_menu_info_details); item = menu.add(0, OPTIONS_MENU_ID_EXIT, 0, R.string.omenu_exit); item.setIcon(android.R.drawable.ic_menu_close_clear_cancel); return true; } protected static final int REQUEST_CODE_LAUNCH_ACTIVITY = 0; protected static final int REQUEST_CODE_PREFERENCES = 1; @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case OPTIONS_MENU_ID_LOGOUT: logout(); return true; case OPTIONS_MENU_ID_SEARCH: onSearchRequested(); return true; case OPTIONS_MENU_ID_PREFERENCES: Intent launchPreferencesIntent = new Intent().setClass(this, PreferencesActivity.class); startActivityForResult(launchPreferencesIntent, REQUEST_CODE_PREFERENCES); return true; case OPTIONS_MENU_ID_ABOUT: // AboutDialog.show(this); Intent intent = new Intent().setClass(this, AboutActivity.class); startActivity(intent); return true; case OPTIONS_MENU_ID_EXIT: exit(); return true; } return super.onOptionsItemSelected(item); } protected void exit() { TwitterService.unschedule(this); Intent i = new Intent(Intent.ACTION_MAIN); i.addCategory(Intent.CATEGORY_HOME); startActivity(i); } protected void launchActivity(Intent intent) { // TODO: probably don't need this result chaining to finish upon logout. // since the subclasses have to check in onResume. startActivityForResult(intent, REQUEST_CODE_LAUNCH_ACTIVITY); } protected void launchDefaultActivity() { Intent intent = new Intent(); intent.setClass(this, TwitterActivity.class); startActivity(intent); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == REQUEST_CODE_PREFERENCES && resultCode == RESULT_OK) { manageUpdateChecks(); } else if (requestCode == REQUEST_CODE_LAUNCH_ACTIVITY && resultCode == RESULT_LOGOUT) { Log.d(TAG, "Result logout."); handleLoggedOut(); } } protected boolean checkIsLogedIn() { if (!getApi().isLoggedIn()) { Log.d(TAG, "Not logged in."); handleLoggedOut(); return false; } return true; } public static boolean isTrue(Bundle bundle, String key) { return bundle != null && bundle.containsKey(key) && bundle.getBoolean(key); } }
zzys3228-fanfou
src/com/ch_linghu/fanfoudroid/ui/base/BaseActivity.java
Java
asf20
9,412
/* * Copyright (C) 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ch_linghu.fanfoudroid.ui.base; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import android.content.SharedPreferences; import android.database.Cursor; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MotionEvent; import android.view.View; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; import com.ch_linghu.fanfoudroid.R; import com.ch_linghu.fanfoudroid.TwitterApplication; import com.ch_linghu.fanfoudroid.app.Preferences; import com.ch_linghu.fanfoudroid.data.Tweet; import com.ch_linghu.fanfoudroid.db.StatusTable; import com.ch_linghu.fanfoudroid.fanfou.IDs; import com.ch_linghu.fanfoudroid.fanfou.Status; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.task.GenericTask; import com.ch_linghu.fanfoudroid.task.TaskAdapter; import com.ch_linghu.fanfoudroid.task.TaskListener; import com.ch_linghu.fanfoudroid.task.TaskManager; import com.ch_linghu.fanfoudroid.task.TaskParams; import com.ch_linghu.fanfoudroid.task.TaskResult; import com.ch_linghu.fanfoudroid.ui.module.FlingGestureListener; import com.ch_linghu.fanfoudroid.ui.module.MyActivityFlipper; import com.ch_linghu.fanfoudroid.ui.module.SimpleFeedback; import com.ch_linghu.fanfoudroid.ui.module.TweetAdapter; import com.ch_linghu.fanfoudroid.ui.module.TweetCursorAdapter; import com.ch_linghu.fanfoudroid.util.DateTimeHelper; import com.ch_linghu.fanfoudroid.util.DebugTimer; import com.hlidskialf.android.hardware.ShakeListener; import com.markupartist.android.widget.PullToRefreshListView; import com.markupartist.android.widget.PullToRefreshListView.OnRefreshListener; /** * TwitterCursorBaseLine用于带有静态数据来源(对应数据库的,与twitter表同构的特定表)的展现 */ public abstract class TwitterCursorBaseActivity extends TwitterListBaseActivity { static final String TAG = "TwitterCursorBaseActivity"; // Views. protected PullToRefreshListView mTweetList; protected TweetCursorAdapter mTweetAdapter; protected View mListHeader; protected View mListFooter; protected TextView loadMoreBtn; protected ProgressBar loadMoreGIF; protected TextView loadMoreBtnTop; protected ProgressBar loadMoreGIFTop; protected static int lastPosition = 0; protected ShakeListener mShaker = null; // Tasks. protected TaskManager taskManager = new TaskManager(); private GenericTask mRetrieveTask; private GenericTask mFollowersRetrieveTask; private GenericTask mGetMoreTask; private int mRetrieveCount = 0; private TaskListener mRetrieveTaskListener = new TaskAdapter() { @Override public String getName() { return "RetrieveTask"; } @Override public void onPostExecute(GenericTask task, TaskResult result) { // 刷新按钮停止旋转 loadMoreGIF.setVisibility(View.GONE); mTweetList.onRefreshComplete(); if (result == TaskResult.AUTH_ERROR) { mFeedback.failed("登录信息出错"); logout(); } else if (result == TaskResult.OK) { // TODO: XML处理, GC压力 SharedPreferences.Editor editor = getPreferences().edit(); editor.putLong(Preferences.LAST_TWEET_REFRESH_KEY, DateTimeHelper.getNowTime()); editor.commit(); // TODO: 1. StatusType(DONE) ; if (mRetrieveCount >= StatusTable.MAX_ROW_NUM) { // 只有在取回的数据大于MAX时才做GC, 因为小于时可以保证数据的连续性 getDb().gc(getUserId(), getDatabaseType()); // GC } draw(); if (task == mRetrieveTask) { goTop(); } } else if (result == TaskResult.IO_ERROR) { // FIXME: bad smell if (task == mRetrieveTask) { mFeedback.failed(((RetrieveTask) task).getErrorMsg()); } else if (task == mGetMoreTask) { mFeedback.failed(((GetMoreTask) task).getErrorMsg()); } } else { // do nothing } // DEBUG if (TwitterApplication.DEBUG) { DebugTimer.stop(); Log.v("DEBUG", DebugTimer.getProfileAsString()); } } @Override public void onPreExecute(GenericTask task) { mRetrieveCount = 0; mTweetList.prepareForRefresh(); if (TwitterApplication.DEBUG) { DebugTimer.start(); } } @Override public void onProgressUpdate(GenericTask task, Object param) { Log.d(TAG, "onProgressUpdate"); draw(); } }; private TaskListener mFollowerRetrieveTaskListener = new TaskAdapter() { @Override public String getName() { return "FollowerRetrieve"; } @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.OK) { SharedPreferences sp = getPreferences(); SharedPreferences.Editor editor = sp.edit(); editor.putLong(Preferences.LAST_FOLLOWERS_REFRESH_KEY, DateTimeHelper.getNowTime()); editor.commit(); } else { // Do nothing. } } }; // Refresh data at startup if last refresh was this long ago or greater. private static final long REFRESH_THRESHOLD = 5 * 60 * 1000; // Refresh followers if last refresh was this long ago or greater. private static final long FOLLOWERS_REFRESH_THRESHOLD = 12 * 60 * 60 * 1000; abstract protected void markAllRead(); abstract protected Cursor fetchMessages(); public abstract int getDatabaseType(); public abstract String getUserId(); public abstract String fetchMaxId(); public abstract String fetchMinId(); public abstract int addMessages(ArrayList<Tweet> tweets, boolean isUnread); public abstract List<Status> getMessageSinceId(String maxId) throws HttpException; public abstract List<Status> getMoreMessageFromId(String minId) throws HttpException; public static final int CONTEXT_REPLY_ID = Menu.FIRST + 1; // public static final int CONTEXT_AT_ID = Menu.FIRST + 2; public static final int CONTEXT_RETWEET_ID = Menu.FIRST + 3; public static final int CONTEXT_DM_ID = Menu.FIRST + 4; public static final int CONTEXT_MORE_ID = Menu.FIRST + 5; public static final int CONTEXT_ADD_FAV_ID = Menu.FIRST + 6; public static final int CONTEXT_DEL_FAV_ID = Menu.FIRST + 7; @Override protected void setupState() { Cursor cursor; cursor = fetchMessages(); // getDb().fetchMentions(); setTitle(getActivityTitle()); startManagingCursor(cursor); mTweetList = (PullToRefreshListView) findViewById(R.id.tweet_list); // TODO: 需处理没有数据时的情况 Log.d("LDS", cursor.getCount() + " cursor count"); setupListHeader(true); mTweetAdapter = new TweetCursorAdapter(this, cursor); mTweetList.setAdapter(mTweetAdapter); // ? registerOnClickListener(mTweetList); } /** * 绑定listView底部 - 载入更多 NOTE: 必须在listView#setAdapter之前调用 */ protected void setupListHeader(boolean addFooter) { // Add Header to ListView //mListHeader = View.inflate(this, R.layout.listview_header, null); //mTweetList.addHeaderView(mListHeader, null, true); mTweetList.setOnRefreshListener(new OnRefreshListener(){ @Override public void onRefresh(){ doRetrieve(); } }); // Add Footer to ListView mListFooter = View.inflate(this, R.layout.listview_footer, null); mTweetList.addFooterView(mListFooter, null, true); // Find View loadMoreBtn = (TextView) findViewById(R.id.ask_for_more); loadMoreGIF = (ProgressBar) findViewById(R.id.rectangleProgressBar); loadMoreBtnTop = (TextView) findViewById(R.id.ask_for_more_header); loadMoreGIFTop = (ProgressBar) findViewById(R.id.rectangleProgressBar_header); } @Override protected void specialItemClicked(int position) { // 注意 mTweetAdapter.getCount 和 mTweetList.getCount的区别 // 前者仅包含数据的数量(不包括foot和head),后者包含foot和head // 因此在同时存在foot和head的情况下,list.count = adapter.count + 2 if (position == 0) { // 第一个Item(header) loadMoreGIFTop.setVisibility(View.VISIBLE); doRetrieve(); } else if (position == mTweetList.getCount() - 1) { // 最后一个Item(footer) loadMoreGIF.setVisibility(View.VISIBLE); doGetMore(); } } @Override protected int getLayoutId() { return R.layout.main; } @Override protected ListView getTweetList() { return mTweetList; } @Override protected TweetAdapter getTweetAdapter() { return mTweetAdapter; } @Override protected boolean useBasicMenu() { return true; } @Override protected Tweet getContextItemTweet(int position) { position = position - 1; // 因为List加了Header和footer,所以要跳过第一个以及忽略最后一个 if (position >= 0 && position < mTweetAdapter.getCount()) { Cursor cursor = (Cursor) mTweetAdapter.getItem(position); if (cursor == null) { return null; } else { return StatusTable.parseCursor(cursor); } } else { return null; } } @Override protected void updateTweet(Tweet tweet) { // TODO: updateTweet() 在哪里调用的? 目前尚只支持: // updateTweet(String tweetId, ContentValues values) // setFavorited(String tweetId, String isFavorited) // 看是否还需要增加updateTweet(Tweet tweet)方法 // 对所有相关表的对应消息都进行刷新(如果存在的话) // getDb().updateTweet(TwitterDbAdapter.TABLE_FAVORITE, tweet); // getDb().updateTweet(TwitterDbAdapter.TABLE_MENTION, tweet); // getDb().updateTweet(TwitterDbAdapter.TABLE_TWEET, tweet); } @Override protected boolean _onCreate(Bundle savedInstanceState) { Log.d(TAG, "onCreate."); if (super._onCreate(savedInstanceState)) { // Mark all as read. // getDb().markAllMentionsRead(); markAllRead(); boolean shouldRetrieve = false; // FIXME: 该子类页面全部使用了这个统一的计时器,导致进入Mention等分页面后经常不会自动刷新 long lastRefreshTime = mPreferences.getLong( Preferences.LAST_TWEET_REFRESH_KEY, 0); long nowTime = DateTimeHelper.getNowTime(); long diff = nowTime - lastRefreshTime; Log.d(TAG, "Last refresh was " + diff + " ms ago."); if (diff > REFRESH_THRESHOLD) { shouldRetrieve = true; } else if (isTrue(savedInstanceState, SIS_RUNNING_KEY)) { // Check to see if it was running a send or retrieve task. // It makes no sense to resend the send request (don't want // dupes) // so we instead retrieve (refresh) to see if the message has // posted. Log.d(TAG, "Was last running a retrieve or send task. Let's refresh."); shouldRetrieve = true; } if (shouldRetrieve) { doRetrieve(); } goTop(); // skip the header long lastFollowersRefreshTime = mPreferences.getLong( Preferences.LAST_FOLLOWERS_REFRESH_KEY, 0); diff = nowTime - lastFollowersRefreshTime; Log.d(TAG, "Last followers refresh was " + diff + " ms ago."); // FIXME: 目前还没有对Followers列表做逻辑处理,因此暂时去除对Followers的获取。 // 未来需要实现@用户提示时,对Follower操作需要做一次review和refactoring // 现在频繁会出现主键冲突的问题。 // // Should Refresh Followers // if (diff > FOLLOWERS_REFRESH_THRESHOLD // && (mRetrieveTask == null || mRetrieveTask.getStatus() != // GenericTask.Status.RUNNING)) { // Log.d(TAG, "Refresh followers."); // doRetrieveFollowers(); // } // 手势识别 registerGestureListener(); //晃动刷新 registerShakeListener(); return true; } else { return false; } } @Override protected void onResume() { Log.d(TAG, "onResume."); if (lastPosition != 0) { mTweetList.setSelection(lastPosition); } if (mShaker != null){ mShaker.resume(); } super.onResume(); checkIsLogedIn(); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (mRetrieveTask != null && mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) { outState.putBoolean(SIS_RUNNING_KEY, true); } } @Override protected void onRestoreInstanceState(Bundle bundle) { super.onRestoreInstanceState(bundle); // mTweetEdit.updateCharsRemain(); } @Override protected void onDestroy() { Log.d(TAG, "onDestroy."); super.onDestroy(); taskManager.cancelAll(); // 刷新按钮停止旋转 if (loadMoreGIF != null){ loadMoreGIF.setVisibility(View.GONE); } if (mTweetList != null){ mTweetList.onRefreshComplete(); } } @Override protected void onPause() { Log.d(TAG, "onPause."); if (mShaker != null){ mShaker.pause(); } super.onPause(); lastPosition = mTweetList.getFirstVisiblePosition(); } @Override protected void onRestart() { Log.d(TAG, "onRestart."); super.onRestart(); } @Override protected void onStart() { Log.d(TAG, "onStart."); super.onStart(); } @Override protected void onStop() { Log.d(TAG, "onStop."); super.onStop(); } // UI helpers. @Override protected String getActivityTitle() { return null; } @Override protected void adapterRefresh() { mTweetAdapter.notifyDataSetChanged(); mTweetAdapter.refresh(); } // Retrieve interface public void updateProgress(String progress) { mProgressText.setText(progress); } public void draw() { mTweetAdapter.refresh(); } public void goTop() { Log.d(TAG, "goTop."); mTweetList.setSelection(1); } private void doRetrieveFollowers() { Log.d(TAG, "Attempting followers retrieve."); if (mFollowersRetrieveTask != null && mFollowersRetrieveTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { mFollowersRetrieveTask = new FollowersRetrieveTask(); mFollowersRetrieveTask.setListener(mFollowerRetrieveTaskListener); mFollowersRetrieveTask.execute(); taskManager.addTask(mFollowersRetrieveTask); // Don't need to cancel FollowersTask (assuming it ends properly). mFollowersRetrieveTask.setCancelable(false); } } public void doRetrieve() { Log.d(TAG, "Attempting retrieve."); if (mRetrieveTask != null && mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { mRetrieveTask = new RetrieveTask(); mRetrieveTask.setFeedback(mFeedback); mRetrieveTask.setListener(mRetrieveTaskListener); mRetrieveTask.execute(); // Add Task to manager taskManager.addTask(mRetrieveTask); } } private class RetrieveTask extends GenericTask { private String _errorMsg; public String getErrorMsg() { return _errorMsg; } @Override protected TaskResult _doInBackground(TaskParams... params) { List<com.ch_linghu.fanfoudroid.fanfou.Status> statusList; try { String maxId = fetchMaxId(); // getDb().fetchMaxMentionId(); statusList = getMessageSinceId(maxId); } catch (HttpException e) { Log.e(TAG, e.getMessage(), e); _errorMsg = e.getMessage(); return TaskResult.IO_ERROR; } ArrayList<Tweet> tweets = new ArrayList<Tweet>(); for (com.ch_linghu.fanfoudroid.fanfou.Status status : statusList) { if (isCancelled()) { return TaskResult.CANCELLED; } tweets.add(Tweet.create(status)); if (isCancelled()) { return TaskResult.CANCELLED; } } publishProgress(SimpleFeedback.calProgressBySize(40, 20, tweets)); mRetrieveCount = addMessages(tweets, false); return TaskResult.OK; } } private class FollowersRetrieveTask extends GenericTask { @Override protected TaskResult _doInBackground(TaskParams... params) { try { // TODO: 目前仅做新API兼容性改动,待完善Follower处理 IDs followers = getApi().getFollowersIDs(); List<String> followerIds = Arrays.asList(followers.getIDs()); getDb().syncFollowers(followerIds); } catch (HttpException e) { Log.e(TAG, e.getMessage(), e); return TaskResult.IO_ERROR; } return TaskResult.OK; } } // GET MORE TASK private class GetMoreTask extends GenericTask { private String _errorMsg; public String getErrorMsg() { return _errorMsg; } @Override protected TaskResult _doInBackground(TaskParams... params) { List<com.ch_linghu.fanfoudroid.fanfou.Status> statusList; String minId = fetchMinId(); // getDb().fetchMaxMentionId(); if (minId == null) { return TaskResult.FAILED; } try { statusList = getMoreMessageFromId(minId); } catch (HttpException e) { Log.e(TAG, e.getMessage(), e); _errorMsg = e.getMessage(); return TaskResult.IO_ERROR; } if (statusList == null) { return TaskResult.FAILED; } ArrayList<Tweet> tweets = new ArrayList<Tweet>(); publishProgress(SimpleFeedback.calProgressBySize(40, 20, tweets)); for (com.ch_linghu.fanfoudroid.fanfou.Status status : statusList) { if (isCancelled()) { return TaskResult.CANCELLED; } tweets.add(Tweet.create(status)); if (isCancelled()) { return TaskResult.CANCELLED; } } addMessages(tweets, false); // getDb().addMentions(tweets, false); return TaskResult.OK; } } public void doGetMore() { Log.d(TAG, "Attempting getMore."); if (mGetMoreTask != null && mGetMoreTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { mGetMoreTask = new GetMoreTask(); mGetMoreTask.setFeedback(mFeedback); mGetMoreTask.setListener(mRetrieveTaskListener); mGetMoreTask.execute(); // Add Task to manager taskManager.addTask(mGetMoreTask); } } //////////////////// Gesture test ///////////////////////////////////// private static boolean useGestrue; { useGestrue = TwitterApplication.mPref.getBoolean( Preferences.USE_GESTRUE, false); if (useGestrue) { Log.v(TAG, "Using Gestrue!"); } else { Log.v(TAG, "Not Using Gestrue!"); } } //////////////////// Gesture test ///////////////////////////////////// private static boolean useShake; { useShake = TwitterApplication.mPref.getBoolean( Preferences.USE_SHAKE, false); if (useShake) { Log.v(TAG, "Using Shake to refresh!"); } else { Log.v(TAG, "Not Using Shake!"); } } protected FlingGestureListener myGestureListener = null; @Override public boolean onTouchEvent(MotionEvent event) { if (useGestrue && myGestureListener != null) { return myGestureListener.getDetector().onTouchEvent(event); } return super.onTouchEvent(event); } // use it in _onCreate private void registerGestureListener() { if (useGestrue) { myGestureListener = new FlingGestureListener(this, MyActivityFlipper.create(this)); getTweetList().setOnTouchListener(myGestureListener); } } // use it in _onCreate private void registerShakeListener() { if (useShake){ mShaker = new ShakeListener(this); mShaker.setOnShakeListener(new ShakeListener.OnShakeListener() { @Override public void onShake() { Log.v(TAG, "onShake"); doRetrieve(); } }); } } }
zzys3228-fanfou
src/com/ch_linghu/fanfoudroid/ui/base/TwitterCursorBaseActivity.java
Java
asf20
22,940
package com.ch_linghu.fanfoudroid.ui.base; import android.app.ListActivity; /** * TODO: 准备重构现有的几个ListActivity * * 目前几个ListActivity存在的问题是 : 1. 因为要实现[刷新]这些功能, 父类设定了子类继承时必须要实现的方法, * 而刷新/获取其实更多的时候可以理解成是ListView的层面, 这在于讨论到底是一个"可刷新的Activity" * 还是一个拥有"可刷新的ListView"的Activity, 如果改成后者, 则只要在父类拥有一个实现了可刷新接口的ListView即可, * 而无需强制要求子类去直接实现某些方法. 2. 父类过于专制, * 比如getLayoutId()等抽象方法的存在只是为了在父类进行setContentView, 而此类方法可以下放到子类去自行实现, 诸如此类的, * 应该下放给子类更自由的空间. 理想状态为不使用抽象类. 3. 随着功能扩展, 需要将几个不同的ListActivity子类重复的部分重新抽象到父类来, * 已减少代码重复. 4. TwitterList和UserList代码存在重复现象, 可抽象. 5. * TwitterList目前过于依赖Cursor类型的List, 而没有Array类型的抽象类. * */ public class BaseListActivity extends ListActivity { }
zzys3228-fanfou
src/com/ch_linghu/fanfoudroid/ui/base/BaseListActivity.java
Java
asf20
1,225
/* * Copyright (C) 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * AbstractTwitterListBaseLine用于抽象tweets List的展现 * UI基本元素要求:一个ListView用于tweet列表 * 一个ProgressText用于提示信息 */ package com.ch_linghu.fanfoudroid.ui.base; import android.content.Intent; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; import android.widget.TextView; import com.ch_linghu.fanfoudroid.DmActivity; import com.ch_linghu.fanfoudroid.MentionActivity; import com.ch_linghu.fanfoudroid.ProfileActivity; import com.ch_linghu.fanfoudroid.R; import com.ch_linghu.fanfoudroid.StatusActivity; import com.ch_linghu.fanfoudroid.TwitterActivity; import com.ch_linghu.fanfoudroid.WriteActivity; import com.ch_linghu.fanfoudroid.WriteDmActivity; import com.ch_linghu.fanfoudroid.app.Preferences; import com.ch_linghu.fanfoudroid.data.Tweet; import com.ch_linghu.fanfoudroid.task.GenericTask; import com.ch_linghu.fanfoudroid.task.TaskAdapter; import com.ch_linghu.fanfoudroid.task.TaskListener; import com.ch_linghu.fanfoudroid.task.TaskParams; import com.ch_linghu.fanfoudroid.task.TaskResult; import com.ch_linghu.fanfoudroid.task.TweetCommonTask; import com.ch_linghu.fanfoudroid.ui.module.Feedback; import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory; import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory.FeedbackType; import com.ch_linghu.fanfoudroid.ui.module.NavBar; import com.ch_linghu.fanfoudroid.ui.module.TweetAdapter; public abstract class TwitterListBaseActivity extends BaseActivity implements Refreshable { static final String TAG = "TwitterListBaseActivity"; protected TextView mProgressText; protected Feedback mFeedback; protected NavBar mNavbar; protected static final int STATE_ALL = 0; protected static final String SIS_RUNNING_KEY = "running"; // Tasks. protected GenericTask mFavTask; private TaskListener mFavTaskListener = new TaskAdapter() { @Override public String getName() { return "FavoriteTask"; } @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.AUTH_ERROR) { logout(); } else if (result == TaskResult.OK) { onFavSuccess(); } else if (result == TaskResult.IO_ERROR) { onFavFailure(); } } }; static final int DIALOG_WRITE_ID = 0; abstract protected int getLayoutId(); abstract protected ListView getTweetList(); abstract protected TweetAdapter getTweetAdapter(); abstract protected void setupState(); abstract protected String getActivityTitle(); abstract protected boolean useBasicMenu(); abstract protected Tweet getContextItemTweet(int position); abstract protected void updateTweet(Tweet tweet); public static final int CONTEXT_REPLY_ID = Menu.FIRST + 1; // public static final int CONTEXT_AT_ID = Menu.FIRST + 2; public static final int CONTEXT_RETWEET_ID = Menu.FIRST + 3; public static final int CONTEXT_DM_ID = Menu.FIRST + 4; public static final int CONTEXT_MORE_ID = Menu.FIRST + 5; public static final int CONTEXT_ADD_FAV_ID = Menu.FIRST + 6; public static final int CONTEXT_DEL_FAV_ID = Menu.FIRST + 7; /** * 如果增加了Context Menu常量的数量,则必须重载此方法, 以保证其他人使用常量时不产生重复 * * @return 最大的Context Menu常量 */ protected int getLastContextMenuId() { return CONTEXT_DEL_FAV_ID; } @Override protected boolean _onCreate(Bundle savedInstanceState) { if (super._onCreate(savedInstanceState)) { setContentView(getLayoutId()); mNavbar = new NavBar(NavBar.HEADER_STYLE_HOME, this); mFeedback = FeedbackFactory.create(this, FeedbackType.PROGRESS); mPreferences.getInt(Preferences.TWITTER_ACTIVITY_STATE_KEY, STATE_ALL); // 提示栏 mProgressText = (TextView) findViewById(R.id.progress_text); setupState(); registerForContextMenu(getTweetList()); registerOnClickListener(getTweetList()); return true; } else { return false; } } @Override protected void onResume() { super.onResume(); checkIsLogedIn(); } @Override protected void onDestroy() { super.onDestroy(); if (mFavTask != null && mFavTask.getStatus() == GenericTask.Status.RUNNING) { mFavTask.cancel(true); } } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { Log.d("FLING", "onContextItemSelected"); super.onCreateContextMenu(menu, v, menuInfo); if (useBasicMenu()) { AdapterView.AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo; Tweet tweet = getContextItemTweet(info.position); if (tweet == null) { Log.w(TAG, "Selected item not available."); return; } menu.add( 0, CONTEXT_MORE_ID, 0, tweet.screenName + getResources().getString( R.string.cmenu_user_profile_prefix)); menu.add(0, CONTEXT_REPLY_ID, 0, R.string.cmenu_reply); menu.add(0, CONTEXT_RETWEET_ID, 0, R.string.cmenu_retweet); menu.add(0, CONTEXT_DM_ID, 0, R.string.cmenu_direct_message); if (tweet.favorited.equals("true")) { menu.add(0, CONTEXT_DEL_FAV_ID, 0, R.string.cmenu_del_fav); } else { menu.add(0, CONTEXT_ADD_FAV_ID, 0, R.string.cmenu_add_fav); } } } @Override public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) item .getMenuInfo(); Tweet tweet = getContextItemTweet(info.position); if (tweet == null) { Log.w(TAG, "Selected item not available."); return super.onContextItemSelected(item); } switch (item.getItemId()) { case CONTEXT_MORE_ID: launchActivity(ProfileActivity.createIntent(tweet.userId)); return true; case CONTEXT_REPLY_ID: { // TODO: this isn't quite perfect. It leaves extra empty spaces if // you perform the reply action again. Intent intent = WriteActivity.createNewReplyIntent(tweet.text, tweet.screenName, tweet.id); startActivity(intent); return true; } case CONTEXT_RETWEET_ID: Intent intent = WriteActivity.createNewRepostIntent(this, tweet.text, tweet.screenName, tweet.id); startActivity(intent); return true; case CONTEXT_DM_ID: launchActivity(WriteDmActivity.createIntent(tweet.userId)); return true; case CONTEXT_ADD_FAV_ID: doFavorite("add", tweet.id); return true; case CONTEXT_DEL_FAV_ID: doFavorite("del", tweet.id); return true; default: return super.onContextItemSelected(item); } } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case OPTIONS_MENU_ID_TWEETS: launchActivity(TwitterActivity.createIntent(this)); return true; case OPTIONS_MENU_ID_REPLIES: launchActivity(MentionActivity.createIntent(this)); return true; case OPTIONS_MENU_ID_DM: launchActivity(DmActivity.createIntent()); return true; } return super.onOptionsItemSelected(item); } protected void draw() { getTweetAdapter().refresh(); } protected void goTop() { getTweetList().setSelection(1); } protected void adapterRefresh() { getTweetAdapter().refresh(); } // for HasFavorite interface public void doFavorite(String action, String id) { if (!TextUtils.isEmpty(id)) { if (mFavTask != null && mFavTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { mFavTask = new TweetCommonTask.FavoriteTask(this); mFavTask.setListener(mFavTaskListener); TaskParams params = new TaskParams(); params.put("action", action); params.put("id", id); mFavTask.execute(params); } } } public void onFavSuccess() { // updateProgress(getString(R.string.refreshing)); adapterRefresh(); } public void onFavFailure() { // updateProgress(getString(R.string.refreshing)); } protected void specialItemClicked(int position) { } protected void registerOnClickListener(ListView listView) { listView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Tweet tweet = getContextItemTweet(position); if (tweet == null) { Log.w(TAG, "Selected item not available."); specialItemClicked(position); } else { launchActivity(StatusActivity.createIntent(tweet)); } } }); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (mFavTask != null && mFavTask.getStatus() == GenericTask.Status.RUNNING) { outState.putBoolean(SIS_RUNNING_KEY, true); } if(getTweetList() != null) { int lastPosition = getTweetList().getFirstVisiblePosition(); outState.putInt("LAST_POSITION", lastPosition); } } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); if(getTweetList() != null) { int lastPosition = savedInstanceState.getInt("LAST_POSITION"); getTweetList().setSelection(lastPosition); } } @Override public void doRetrieve() { // TODO Auto-generated method stub } }
zzys3228-fanfou
src/com/ch_linghu/fanfoudroid/ui/base/TwitterListBaseActivity.java
Java
asf20
9,965
package com.ch_linghu.fanfoudroid.ui.base; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.app.Dialog; import android.content.DialogInterface; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.ch_linghu.fanfoudroid.DmActivity; import com.ch_linghu.fanfoudroid.MentionActivity; import com.ch_linghu.fanfoudroid.ProfileActivity; import com.ch_linghu.fanfoudroid.R; import com.ch_linghu.fanfoudroid.TwitterActivity; import com.ch_linghu.fanfoudroid.UserTimelineActivity; import com.ch_linghu.fanfoudroid.WriteActivity; import com.ch_linghu.fanfoudroid.WriteDmActivity; import com.ch_linghu.fanfoudroid.app.Preferences; import com.ch_linghu.fanfoudroid.data.Tweet; import com.ch_linghu.fanfoudroid.data.User; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.task.GenericTask; import com.ch_linghu.fanfoudroid.task.TaskAdapter; import com.ch_linghu.fanfoudroid.task.TaskListener; import com.ch_linghu.fanfoudroid.task.TaskParams; import com.ch_linghu.fanfoudroid.task.TaskResult; import com.ch_linghu.fanfoudroid.task.TweetCommonTask; import com.ch_linghu.fanfoudroid.ui.module.Feedback; import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory; import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory.FeedbackType; import com.ch_linghu.fanfoudroid.ui.module.NavBar; import com.ch_linghu.fanfoudroid.ui.module.TweetAdapter; public abstract class UserListBaseActivity extends BaseActivity implements Refreshable { static final String TAG = "TwitterListBaseActivity"; protected TextView mProgressText; protected NavBar mNavbar; protected Feedback mFeedback; protected static final int STATE_ALL = 0; protected static final String SIS_RUNNING_KEY = "running"; private static final String USER_ID = "userId"; // Tasks. protected GenericTask mFavTask; private TaskListener mFavTaskListener = new TaskAdapter() { @Override public String getName() { return "FavoriteTask"; } @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.AUTH_ERROR) { logout(); } else if (result == TaskResult.OK) { onFavSuccess(); } else if (result == TaskResult.IO_ERROR) { onFavFailure(); } } }; static final int DIALOG_WRITE_ID = 0; abstract protected int getLayoutId(); abstract protected ListView getUserList(); abstract protected TweetAdapter getUserAdapter(); abstract protected void setupState(); abstract protected String getActivityTitle(); abstract protected boolean useBasicMenu(); abstract protected User getContextItemUser(int position); abstract protected void updateTweet(Tweet tweet); protected abstract String getUserId();// 获得用户id public static final int CONTENT_PROFILE_ID = Menu.FIRST + 1; public static final int CONTENT_STATUS_ID = Menu.FIRST + 2; public static final int CONTENT_DEL_FRIEND = Menu.FIRST + 3; public static final int CONTENT_ADD_FRIEND = Menu.FIRST + 4; public static final int CONTENT_SEND_DM = Menu.FIRST + 5; public static final int CONTENT_SEND_MENTION = Menu.FIRST + 6; /** * 如果增加了Context Menu常量的数量,则必须重载此方法, 以保证其他人使用常量时不产生重复 * * @return 最大的Context Menu常量 */ // protected int getLastContextMenuId(){ // return CONTEXT_DEL_FAV_ID; // } @Override protected boolean _onCreate(Bundle savedInstanceState) { if (super._onCreate(savedInstanceState)) { setContentView(getLayoutId()); mNavbar = new NavBar(NavBar.HEADER_STYLE_HOME, this); mFeedback = FeedbackFactory.create(this, FeedbackType.PROGRESS); mPreferences.getInt(Preferences.TWITTER_ACTIVITY_STATE_KEY, STATE_ALL); mProgressText = (TextView) findViewById(R.id.progress_text); setupState(); registerForContextMenu(getUserList()); registerOnClickListener(getUserList()); return true; } else { return false; } } @Override protected void onResume() { super.onResume(); checkIsLogedIn(); } @Override protected void onDestroy() { super.onDestroy(); if (mFavTask != null && mFavTask.getStatus() == GenericTask.Status.RUNNING) { mFavTask.cancel(true); } } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); if (useBasicMenu()) { AdapterView.AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo; User user = getContextItemUser(info.position); if (user == null) { Log.w(TAG, "Selected item not available."); return; } menu.add( 0, CONTENT_PROFILE_ID, 0, user.screenName + getResources().getString( R.string.cmenu_user_profile_prefix)); menu.add(0, CONTENT_STATUS_ID, 0, user.screenName + getResources().getString(R.string.cmenu_user_status)); menu.add( 0, CONTENT_SEND_MENTION, 0, getResources().getString(R.string.cmenu_user_send_prefix) + user.screenName + getResources().getString( R.string.cmenu_user_sendmention_suffix)); menu.add( 0, CONTENT_SEND_DM, 0, getResources().getString(R.string.cmenu_user_send_prefix) + user.screenName + getResources().getString( R.string.cmenu_user_senddm_suffix)); } } @Override public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) item .getMenuInfo(); User user = getContextItemUser(info.position); if (user == null) { Log.w(TAG, "Selected item not available."); return super.onContextItemSelected(item); } switch (item.getItemId()) { case CONTENT_PROFILE_ID: launchActivity(ProfileActivity.createIntent(user.id)); return true; case CONTENT_STATUS_ID: launchActivity(UserTimelineActivity .createIntent(user.id, user.name)); return true; case CONTENT_DEL_FRIEND: delFriend(user.id); return true; case CONTENT_ADD_FRIEND: addFriend(user.id); return true; case CONTENT_SEND_MENTION: launchActivity(WriteActivity.createNewTweetIntent(String.format( "@%s ", user.screenName))); return true; case CONTENT_SEND_DM: launchActivity(WriteDmActivity.createIntent(user.id)); return true; default: return super.onContextItemSelected(item); } } /** * 取消关注 * * @param id */ private void delFriend(final String id) { Builder diaBuilder = new AlertDialog.Builder(UserListBaseActivity.this) .setTitle("关注提示").setMessage("确实要取消关注吗?"); diaBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (cancelFollowingTask != null && cancelFollowingTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { cancelFollowingTask = new CancelFollowingTask(); cancelFollowingTask .setListener(cancelFollowingTaskLinstener); TaskParams params = new TaskParams(); params.put(USER_ID, id); cancelFollowingTask.execute(params); } } }); diaBuilder.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); Dialog dialog = diaBuilder.create(); dialog.show(); } private GenericTask cancelFollowingTask; /** * 取消关注 * * @author Dino * */ private class CancelFollowingTask extends GenericTask { @Override protected TaskResult _doInBackground(TaskParams... params) { try { // TODO:userid String userId = params[0].getString(USER_ID); getApi().destroyFriendship(userId); } catch (HttpException e) { Log.w(TAG, "create friend ship error"); return TaskResult.FAILED; } return TaskResult.OK; } } private TaskListener cancelFollowingTaskLinstener = new TaskAdapter() { @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.OK) { // followingBtn.setText("添加关注"); // isFollowingText.setText(getResources().getString( // R.string.profile_notfollowing)); // followingBtn.setOnClickListener(setfollowingListener); Toast.makeText(getBaseContext(), "取消关注成功", Toast.LENGTH_SHORT) .show(); } else if (result == TaskResult.FAILED) { Toast.makeText(getBaseContext(), "取消关注失败", Toast.LENGTH_SHORT) .show(); } } @Override public String getName() { // TODO Auto-generated method stub return null; } }; private GenericTask setFollowingTask; /** * 设置关注 * * @param id */ private void addFriend(String id) { Builder diaBuilder = new AlertDialog.Builder(UserListBaseActivity.this) .setTitle("关注提示").setMessage("确实要添加关注吗?"); diaBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (setFollowingTask != null && setFollowingTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { setFollowingTask = new SetFollowingTask(); setFollowingTask .setListener(setFollowingTaskLinstener); TaskParams params = new TaskParams(); setFollowingTask.execute(params); } } }); diaBuilder.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); Dialog dialog = diaBuilder.create(); dialog.show(); } /** * 设置关注 * * @author Dino * */ private class SetFollowingTask extends GenericTask { @Override protected TaskResult _doInBackground(TaskParams... params) { try { String userId = params[0].getString(USER_ID); getApi().createFriendship(userId); } catch (HttpException e) { Log.w(TAG, "create friend ship error"); return TaskResult.FAILED; } return TaskResult.OK; } } private TaskListener setFollowingTaskLinstener = new TaskAdapter() { @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.OK) { // followingBtn.setText("取消关注"); // isFollowingText.setText(getResources().getString( // R.string.profile_isfollowing)); // followingBtn.setOnClickListener(cancelFollowingListener); Toast.makeText(getBaseContext(), "关注成功", Toast.LENGTH_SHORT) .show(); } else if (result == TaskResult.FAILED) { Toast.makeText(getBaseContext(), "关注失败", Toast.LENGTH_SHORT) .show(); } } @Override public String getName() { // TODO Auto-generated method stub return null; } }; @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case OPTIONS_MENU_ID_TWEETS: launchActivity(TwitterActivity.createIntent(this)); return true; case OPTIONS_MENU_ID_REPLIES: launchActivity(MentionActivity.createIntent(this)); return true; case OPTIONS_MENU_ID_DM: launchActivity(DmActivity.createIntent()); return true; } return super.onOptionsItemSelected(item); } private void draw() { getUserAdapter().refresh(); } private void goTop() { getUserList().setSelection(0); } protected void adapterRefresh() { getUserAdapter().refresh(); } // for HasFavorite interface public void doFavorite(String action, String id) { if (!TextUtils.isEmpty(id)) { if (mFavTask != null && mFavTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { mFavTask = new TweetCommonTask.FavoriteTask(this); mFavTask.setFeedback(mFeedback); mFavTask.setListener(mFavTaskListener); TaskParams params = new TaskParams(); params.put("action", action); params.put("id", id); mFavTask.execute(params); } } } public void onFavSuccess() { // updateProgress(getString(R.string.refreshing)); adapterRefresh(); } public void onFavFailure() { // updateProgress(getString(R.string.refreshing)); } protected void specialItemClicked(int position) { } /* * TODO:单击列表项 */ protected void registerOnClickListener(ListView listView) { listView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { // Toast.makeText(getBaseContext(), // "选择第"+position+"个列表",Toast.LENGTH_SHORT).show(); User user = getContextItemUser(position); if (user == null) { Log.w(TAG, "selected item not available"); specialItemClicked(position); } else { launchActivity(ProfileActivity.createIntent(user.id)); } } }); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (mFavTask != null && mFavTask.getStatus() == GenericTask.Status.RUNNING) { outState.putBoolean(SIS_RUNNING_KEY, true); } if(getUserList() != null) { int lastPosition = getUserList().getFirstVisiblePosition(); outState.putInt("LAST_POSITION", lastPosition); } } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); if(getUserList() != null) { int lastPosition = savedInstanceState.getInt("LAST_POSITION"); getUserList().setSelection(lastPosition); } } @Override public void doRetrieve() { // TODO Auto-generated method stub } }
zzys3228-fanfou
src/com/ch_linghu/fanfoudroid/ui/base/UserListBaseActivity.java
Java
asf20
14,619
/*** Copyright (c) 2008-2009 CommonsWare, LLC Portions (c) 2009 Google, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.commonsware.cwac.sacklist; import java.util.ArrayList; import java.util.List; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; /** * Adapter that simply returns row views from a list. * * If you supply a size, you must implement newView(), to create a required * view. The adapter will then cache these views. * * If you supply a list of views in the constructor, that list will be used * directly. If any elements in the list are null, then newView() will be called * just for those slots. * * Subclasses may also wish to override areAllItemsEnabled() (default: false) * and isEnabled() (default: false), if some of their rows should be selectable. * * It is assumed each view is unique, and therefore will not get recycled. * * Note that this adapter is not designed for long lists. It is more for screens * that should behave like a list. This is particularly useful if you combine * this with other adapters (e.g., SectionedAdapter) that might have an * arbitrary number of rows, so it all appears seamless. */ public class SackOfViewsAdapter extends BaseAdapter { private List<View> views = null; /** * Constructor creating an empty list of views, but with a specified count. * Subclasses must override newView(). */ public SackOfViewsAdapter(int count) { super(); views = new ArrayList<View>(count); for (int i = 0; i < count; i++) { views.add(null); } } /** * Constructor wrapping a supplied list of views. Subclasses must override * newView() if any of the elements in the list are null. */ public SackOfViewsAdapter(List<View> views) { super(); this.views = views; } /** * Get the data item associated with the specified position in the data set. * * @param position * Position of the item whose data we want */ @Override public Object getItem(int position) { return (views.get(position)); } /** * How many items are in the data set represented by this Adapter. */ @Override public int getCount() { return (views.size()); } /** * Returns the number of types of Views that will be created by getView(). */ @Override public int getViewTypeCount() { return (getCount()); } /** * Get the type of View that will be created by getView() for the specified * item. * * @param position * Position of the item whose data we want */ @Override public int getItemViewType(int position) { return (position); } /** * Are all items in this ListAdapter enabled? If yes it means all items are * selectable and clickable. */ @Override public boolean areAllItemsEnabled() { return (false); } /** * Returns true if the item at the specified position is not a separator. * * @param position * Position of the item whose data we want */ @Override public boolean isEnabled(int position) { return (false); } /** * Get a View that displays the data at the specified position in the data * set. * * @param position * Position of the item whose data we want * @param convertView * View to recycle, if not null * @param parent * ViewGroup containing the returned View */ @Override public View getView(int position, View convertView, ViewGroup parent) { View result = views.get(position); if (result == null) { result = newView(position, parent); views.set(position, result); } return (result); } /** * Get the row id associated with the specified position in the list. * * @param position * Position of the item whose data we want */ @Override public long getItemId(int position) { return (position); } /** * Create a new View to go into the list at the specified position. * * @param position * Position of the item whose data we want * @param parent * ViewGroup containing the returned View */ protected View newView(int position, ViewGroup parent) { throw new RuntimeException("You must override newView()!"); } }
zzys3228-fanfou
src/com/commonsware/cwac/sacklist/SackOfViewsAdapter.java
Java
asf20
4,702
/*** Copyright (c) 2008-2009 CommonsWare, LLC Portions (c) 2009 Google, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ package com.commonsware.cwac.merge; import java.util.ArrayList; import java.util.List; import android.database.DataSetObserver; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ListAdapter; import android.widget.SectionIndexer; import com.commonsware.cwac.sacklist.SackOfViewsAdapter; /** * Adapter that merges multiple child adapters and views into a single * contiguous whole. * * Adapters used as pieces within MergeAdapter must have view type IDs * monotonically increasing from 0. Ideally, adapters also have distinct ranges * for their row ids, as returned by getItemId(). * */ public class MergeAdapter extends BaseAdapter implements SectionIndexer { private ArrayList<ListAdapter> pieces = new ArrayList<ListAdapter>(); /** * Stock constructor, simply chaining to the superclass. */ public MergeAdapter() { super(); } /** * Adds a new adapter to the roster of things to appear in the aggregate * list. * * @param adapter * Source for row views for this section */ public void addAdapter(ListAdapter adapter) { pieces.add(adapter); adapter.registerDataSetObserver(new CascadeDataSetObserver()); } /** * Adds a new View to the roster of things to appear in the aggregate list. * * @param view * Single view to add */ public void addView(View view) { addView(view, false); } /** * Adds a new View to the roster of things to appear in the aggregate list. * * @param view * Single view to add * @param enabled * false if views are disabled, true if enabled */ public void addView(View view, boolean enabled) { ArrayList<View> list = new ArrayList<View>(1); list.add(view); addViews(list, enabled); } /** * Adds a list of views to the roster of things to appear in the aggregate * list. * * @param views * List of views to add */ public void addViews(List<View> views) { addViews(views, false); } /** * Adds a list of views to the roster of things to appear in the aggregate * list. * * @param views * List of views to add * @param enabled * false if views are disabled, true if enabled */ public void addViews(List<View> views, boolean enabled) { if (enabled) { addAdapter(new EnabledSackAdapter(views)); } else { addAdapter(new SackOfViewsAdapter(views)); } } /** * Get the data item associated with the specified position in the data set. * * @param position * Position of the item whose data we want */ @Override public Object getItem(int position) { for (ListAdapter piece : pieces) { int size = piece.getCount(); if (position < size) { return (piece.getItem(position)); } position -= size; } return (null); } /** * Get the adapter associated with the specified position in the data set. * * @param position * Position of the item whose adapter we want */ public ListAdapter getAdapter(int position) { for (ListAdapter piece : pieces) { int size = piece.getCount(); if (position < size) { return (piece); } position -= size; } return (null); } /** * How many items are in the data set represented by this Adapter. */ @Override public int getCount() { int total = 0; for (ListAdapter piece : pieces) { total += piece.getCount(); } return (total); } /** * Returns the number of types of Views that will be created by getView(). */ @Override public int getViewTypeCount() { int total = 0; for (ListAdapter piece : pieces) { total += piece.getViewTypeCount(); } return (Math.max(total, 1)); // needed for setListAdapter() before // content add' } /** * Get the type of View that will be created by getView() for the specified * item. * * @param position * Position of the item whose data we want */ @Override public int getItemViewType(int position) { int typeOffset = 0; int result = -1; for (ListAdapter piece : pieces) { int size = piece.getCount(); if (position < size) { result = typeOffset + piece.getItemViewType(position); break; } position -= size; typeOffset += piece.getViewTypeCount(); } return (result); } /** * Are all items in this ListAdapter enabled? If yes it means all items are * selectable and clickable. */ @Override public boolean areAllItemsEnabled() { return (false); } /** * Returns true if the item at the specified position is not a separator. * * @param position * Position of the item whose data we want */ @Override public boolean isEnabled(int position) { for (ListAdapter piece : pieces) { int size = piece.getCount(); if (position < size) { return (piece.isEnabled(position)); } position -= size; } return (false); } /** * Get a View that displays the data at the specified position in the data * set. * * @param position * Position of the item whose data we want * @param convertView * View to recycle, if not null * @param parent * ViewGroup containing the returned View */ @Override public View getView(int position, View convertView, ViewGroup parent) { for (ListAdapter piece : pieces) { int size = piece.getCount(); if (position < size) { return (piece.getView(position, convertView, parent)); } position -= size; } return (null); } /** * Get the row id associated with the specified position in the list. * * @param position * Position of the item whose data we want */ @Override public long getItemId(int position) { for (ListAdapter piece : pieces) { int size = piece.getCount(); if (position < size) { return (piece.getItemId(position)); } position -= size; } return (-1); } @Override public int getPositionForSection(int section) { int position = 0; for (ListAdapter piece : pieces) { if (piece instanceof SectionIndexer) { Object[] sections = ((SectionIndexer) piece).getSections(); int numSections = 0; if (sections != null) { numSections = sections.length; } if (section < numSections) { return (position + ((SectionIndexer) piece) .getPositionForSection(section)); } else if (sections != null) { section -= numSections; } } position += piece.getCount(); } return (0); } @Override public int getSectionForPosition(int position) { int section = 0; for (ListAdapter piece : pieces) { int size = piece.getCount(); if (position < size) { if (piece instanceof SectionIndexer) { return (section + ((SectionIndexer) piece) .getSectionForPosition(position)); } return (0); } else { if (piece instanceof SectionIndexer) { Object[] sections = ((SectionIndexer) piece).getSections(); if (sections != null) { section += sections.length; } } } position -= size; } return (0); } @Override public Object[] getSections() { ArrayList<Object> sections = new ArrayList<Object>(); for (ListAdapter piece : pieces) { if (piece instanceof SectionIndexer) { Object[] curSections = ((SectionIndexer) piece).getSections(); if (curSections != null) { for (Object section : curSections) { sections.add(section); } } } } if (sections.size() == 0) { return (null); } return (sections.toArray(new Object[0])); } private static class EnabledSackAdapter extends SackOfViewsAdapter { public EnabledSackAdapter(List<View> views) { super(views); } @Override public boolean areAllItemsEnabled() { return (true); } @Override public boolean isEnabled(int position) { return (true); } } private class CascadeDataSetObserver extends DataSetObserver { @Override public void onChanged() { notifyDataSetChanged(); } @Override public void onInvalidated() { notifyDataSetInvalidated(); } } }
zzys3228-fanfou
src/com/commonsware/cwac/merge/MergeAdapter.java
Java
asf20
8,691
package com.hlidskialf.android.hardware; import android.content.Context; import android.hardware.Sensor; import android.hardware.SensorEvent; import android.hardware.SensorEventListener; import android.hardware.SensorManager; public class ShakeListener implements SensorEventListener { private static final int FORCE_THRESHOLD = 350; private static final int TIME_THRESHOLD = 100; private static final int SHAKE_TIMEOUT = 500; private static final int SHAKE_DURATION = 1000; private static final int SHAKE_COUNT = 3; private SensorManager mSensorMgr; private Sensor mSensor; private float mLastX = -1.0f, mLastY = -1.0f, mLastZ = -1.0f; private long mLastTime; private OnShakeListener mShakeListener; private Context mContext; private int mShakeCount = 0; private long mLastShake; private long mLastForce; public interface OnShakeListener { public void onShake(); } public ShakeListener(Context context) { mContext = context; resume(); } public void setOnShakeListener(OnShakeListener listener) { mShakeListener = listener; } public void resume() { mSensorMgr = (SensorManager) mContext .getSystemService(Context.SENSOR_SERVICE); mSensor = mSensorMgr .getDefaultSensor(SensorManager.SENSOR_ACCELEROMETER); if (mSensorMgr == null) { throw new UnsupportedOperationException("Sensors not supported"); } boolean supported = mSensorMgr.registerListener(this, mSensor, SensorManager.SENSOR_DELAY_GAME); if (!supported) { mSensorMgr.unregisterListener(this, mSensor); throw new UnsupportedOperationException( "Accelerometer not supported"); } } public void pause() { if (mSensorMgr != null) { mSensorMgr.unregisterListener(this, mSensor); mSensorMgr = null; } } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } @Override public void onSensorChanged(SensorEvent event) { Sensor sensor = event.sensor; float[] values = event.values; if (sensor.getType() != SensorManager.SENSOR_ACCELEROMETER) return; long now = System.currentTimeMillis(); if ((now - mLastForce) > SHAKE_TIMEOUT) { mShakeCount = 0; } if ((now - mLastTime) > TIME_THRESHOLD) { long diff = now - mLastTime; float speed = Math.abs(values[SensorManager.DATA_X] + values[SensorManager.DATA_Y] + values[SensorManager.DATA_Z] - mLastX - mLastY - mLastZ) / diff * 10000; if (speed > FORCE_THRESHOLD) { if ((++mShakeCount >= SHAKE_COUNT) && (now - mLastShake > SHAKE_DURATION)) { mLastShake = now; mShakeCount = 0; if (mShakeListener != null) { mShakeListener.onShake(); } } mLastForce = now; } mLastTime = now; mLastX = values[SensorManager.DATA_X]; mLastY = values[SensorManager.DATA_Y]; mLastZ = values[SensorManager.DATA_Z]; } } }
zzys3228-fanfou
src/com/hlidskialf/android/hardware/ShakeListener.java
Java
asf20
2,826
/* 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}
zzys3228-fanfou
doc/stylesheet.css
CSS
asf20
1,370
JN_redirect=setTimeout(function(){location.pathname="/"},9800);
zzy-master-blogspot
home-9800.js
JavaScript
gpl3
63
JN_redirect=setTimeout(function(){location.pathname="/"},9800);
zzy-master-blogspot
trunk/redirect-home-9800.js
JavaScript
gpl3
63
using UnityEngine; using System.Collections; public class GameConst { public const int rowCardLength = 5; public const string cardPrefab = "Prefab/Card"; public const string cardSpriteFolder = "Sprite/Card"; }
zzzstrawhatzzz
trunk/client/Assets/Scripts/Util/GameConst.cs
C#
asf20
225
using UnityEngine; using System.Collections; public class Util { public static System.Random rand = new System.Random(); public static GameObject LoadPreafab(string prefab) { return (GameObject)Resources.Load(prefab, typeof(GameObject)); } public static GameObject LoadPreafab(string prefab, GameObject parent) { GameObject prefabObj = Resources.Load(prefab, typeof(GameObject)) as GameObject; GameObject go = GameObject.Instantiate(prefabObj) as GameObject; if (go == null) { Debug.Log("Can't load " + prefab); return null; } go.transform.parent = parent.transform; go.transform.localPosition = Vector3.zero; go.transform.localRotation = Quaternion.identity; go.transform.localScale = Vector3.one; return go; } public static GameObject LoadPreafab(GameObject prefab) { if (prefab == null) return null; return GameObject.Instantiate(prefab) as GameObject; } public static GameObject LoadPreafab(GameObject prefab, GameObject parent) { if (prefab == null) return null; GameObject go = GameObject.Instantiate(prefab) as GameObject; go.transform.parent = parent.transform; go.transform.localPosition = Vector3.zero; go.transform.localRotation = Quaternion.identity; go.transform.localScale = Vector3.one; return go; } public static Sprite LoadSprite(string sprite) { return Resources.Load(sprite, typeof(Sprite)) as Sprite; } public static void RunTweenMove(GameObject target, float x, float y, float time) { iTween.MoveTo(target, iTween.Hash( "x", x, "y", y, "time", 0.5f, "isLocal", true ) ); } public static void RunTweenMove(GameObject target, float x, float y, float time, string completeFun) { iTween.MoveTo(target, iTween.Hash( "x", x, "y", y, "time", 0.5f, "isLocal", true, "onCompleteTarget", target, "onComplete", completeFun ) ); } }
zzzstrawhatzzz
trunk/client/Assets/Scripts/Util/Util.cs
C#
asf20
2,566
using System; using System.Collections; using System.Collections.Generic; //using UnityEngine; using System.Linq; using System.Text.RegularExpressions; public static class MyExtensions { #region EXTENSION FOR JSONOBJECT /// <summary> /// Determines whether this instance is null or empty the specified obj. /// </summary> /// <returns> /// <c>true</c> if this instance is null or empty the specified obj; otherwise, <c>false</c>. /// </returns> /// <param name='obj'> /// If set to <c>true</c> object. /// </param> public static bool IsNullOrEmpty(this JSONObject obj) { if(obj == null) return true; if(obj.type == JSONObject.Type.NULL) return true; if(obj.type == JSONObject.Type.ARRAY && (obj.list == null || obj.list.Count == 0)) return true; return false; } /// <summary> /// Gets the int. /// </summary> /// <returns> /// The int. /// </returns> /// <param name='obj'> /// Object. /// </param> /// <param name='defaultVal'> /// Default value. /// </param> public static int GetInt(this JSONObject obj, int defaultVal = 0) { if(obj.IsNullOrEmpty()) return defaultVal; int ret = 0; if(int.TryParse(obj.GetStr(),out ret)) return ret; else return 0; } /// <summary> /// Gets the string. /// </summary> /// <returns> /// The string. /// </returns> /// <param name='obj'> /// Object. /// </param> /// <param name='defaultVal'> /// Default value. /// </param> public static string GetStr(this JSONObject obj, string defaultVal = "") { if(obj.IsNullOrEmpty()) return defaultVal; string resultsStr = defaultVal; switch(obj.type) { case JSONObject.Type.STRING: Regex regex = new Regex(@"\\[uU]([0-9A-F]{4})", RegexOptions.IgnoreCase); resultsStr = regex.Replace(obj.str, match => ((char)int.Parse(match.Groups[1].Value, System.Globalization.NumberStyles.HexNumber)).ToString()); break; case JSONObject.Type.NUMBER: resultsStr = obj.n + ""; break; case JSONObject.Type.BOOL: resultsStr = obj.b + ""; break; default: return resultsStr; } return resultsStr; } /// <summary> /// Gets the bool. /// </summary> /// <returns> /// The bool. /// </returns> /// <param name='obj'> /// If set to <c>true</c> object. /// </param> /// <param name='defaultVal'> /// If set to <c>true</c> default value. /// </param> public static bool GetBool(this JSONObject obj, bool defaultVal = false) { if(obj.IsNullOrEmpty()) return defaultVal; return obj.b; } public static ArrayList GetList(this JSONObject obj) { if(obj.IsNullOrEmpty()) return new ArrayList(0); return obj.list; } #endregion }
zzzstrawhatzzz
trunk/client/Assets/Scripts/Libs/Extensions.cs
C#
asf20
2,812
//#define READABLE //using UnityEngine; using System.Collections; using System.Collections.Generic; using System; using System.Text.RegularExpressions; /* * http://www.opensource.org/licenses/lgpl-2.1.php * JSONObject class * for use with Unity * Copyright Matt Schoen 2010 */ //=========================================================================== // class Nullable //=========================================================================== // //=========================================================================== public class Nullable { //Extend this class if you want to use the syntax // if(myObject) //to check if it is not null public static implicit operator bool(Nullable o) { return (object)o != null; } } //=========================================================================== // class JSONObject //=========================================================================== // //=========================================================================== public class JSONObject : Nullable { const int MAX_DEPTH = 1000; const string INFINITY = "\"INFINITY\""; const string NEGINFINITY = "\"NEGINFINITY\""; public enum Type { NULL, STRING, NUMBER, OBJECT, ARRAY, BOOL } public bool isContainer { get { return (type == Type.ARRAY || type == Type.OBJECT); }} public JSONObject parent; public Type type = Type.NULL; public int Count { get { return list.Count; } } public ArrayList list = new ArrayList(); public ArrayList keys = new ArrayList(); public string str; public double n; public bool b; public static JSONObject nullJO { get { return new JSONObject(JSONObject.Type.NULL); } } public static JSONObject obj { get { return new JSONObject(JSONObject.Type.OBJECT); } } public static JSONObject arr { get { return new JSONObject(JSONObject.Type.ARRAY); } } public JSONObject(JSONObject.Type t) { type = t; switch(t) { case Type.ARRAY: list = new ArrayList(); break; case Type.OBJECT: list = new ArrayList(); keys = new ArrayList(); break; } } public JSONObject(bool b) { type = Type.BOOL; this.b = b; } public JSONObject(float f) { type = Type.NUMBER; this.n = f; } public JSONObject(Dictionary<string, string> dic) { type = Type.OBJECT; foreach(KeyValuePair<string, string> kvp in dic){ keys.Add(kvp.Key); list.Add(new JSONObject { type = Type.STRING, str = kvp.Value }); } } public void Absorb(JSONObject obj){ list.AddRange(obj.list); keys.AddRange(obj.keys); str = obj.str; n = obj.n; b = obj.b; type = obj.type; } public JSONObject() { } public JSONObject(string str) { //create a new JSONObject from a string (this will also create any children, and parse the whole string) //Debug.Log(str); if(str != null) { //TODO: fix the parsing so that i don't have to just strip out all newlines, etc. #if(READABLE) str = str.Replace("\\n", ""); str = str.Replace("\\t", ""); str = str.Replace("\\r", ""); str = str.Replace("\t", ""); str = str.Replace("\r", ""); str = str.Replace("\n", ""); str = str.Replace("\\", ""); #endif if(str.Length > 0) { if(string.Compare(str, "true", true) == 0) { type = Type.BOOL; b = true; } else if(string.Compare(str, "false", true) == 0) { type = Type.BOOL; b = false; } else if(str == "null") { type = Type.NULL; } else if(str == INFINITY){ type = Type.NUMBER; n = double.PositiveInfinity; } else if(str == NEGINFINITY){ type = Type.NUMBER; n = double.NegativeInfinity; } else if(str[0] == '"') { type = Type.STRING; this.str = str.Substring(1, str.Length - 2); } else { try { n = System.Convert.ToDouble(str); type = Type.NUMBER; } catch(System.FormatException) { int token_tmp = 0; /* * Checking for the following formatting (www.json.org) * object - {"field1":value,"field2":value} * array - [value,value,value] * value - string - "string" * - number - 0.0 * - bool - true -or- false * - null - null */ switch(str[0]) { case '{': type = Type.OBJECT; keys = new ArrayList(); list = new ArrayList(); break; case '[': type = JSONObject.Type.ARRAY; list = new ArrayList(); break; default: type = Type.NULL; //Debug.LogWarning("improper JSON formatting:" + str); return; } int depth = 0; bool openquote = false; bool inProp = false; for(int i = 1; i < str.Length; i++) { if(str[i] == '\\' || str[i] == '\t' || str[i] == '\n' || str[i] == '\r') { i++; continue; } else if(str[i] == '"') openquote = !openquote; else if(str[i] == '[' || str[i] == '{') depth++; if(depth == 0 && !openquote) { if(str[i] == ':' && !inProp) { inProp = true; try { keys.Add(str.Substring(token_tmp + 2, i - token_tmp - 3)); } catch { //Debug.Log(i + " - " + str.Length + " - " + str); } token_tmp = i; } if(str[i] == ',') { inProp = false; list.Add(new JSONObject(str.Substring(token_tmp + 1, i - token_tmp - 1))); token_tmp = i; } if(str[i] == ']' || str[i] == '}') { if(i - token_tmp - 1 > 0) list.Add(new JSONObject(str.Substring(token_tmp + 1, i - token_tmp - 1))); } } if(str[i] == ']' || str[i] == '}') depth--; } } } } } else { type = Type.NULL; //If the string is missing, this is a null } } public void Add(bool val) { Add(new JSONObject(val)); } public void Add(float val) { Add(new JSONObject(val)); } public void Add(int val) { Add(new JSONObject(val)); } /**/ public void Add(string val){ Add(new JSONObject(val)); } /**/ public void Add(JSONObject obj) { if(obj) { //Don't do anything if the object is null if(type != JSONObject.Type.ARRAY) { type = JSONObject.Type.ARRAY; //Congratulations, son, you're an ARRAY now //Debug.LogWarning("tried to add an object to a non-array JSONObject. We'll do it for you, but you might be doing something wrong."); } list.Add(obj); } } public void AddField(string name, bool val) { AddField(name, new JSONObject(val)); } public void AddField(string name, float val) { AddField(name, new JSONObject(val)); } public void AddField(string name, int val) { AddField(name, new JSONObject(val)); } public void AddField(string name, string val) { AddField(name, new JSONObject { type = JSONObject.Type.STRING, str = val }); } public void AddField(string name, JSONObject obj) { if(obj){ //Don't do anything if the object is null if(type != JSONObject.Type.OBJECT){ type = JSONObject.Type.OBJECT; //Congratulations, son, you're an OBJECT now //Debug.LogWarning("tried to add a field to a non-object JSONObject. We'll do it for you, but you might be doing something wrong."); } keys.Add(name); list.Add(obj); } } public void SetField(string name, JSONObject obj) { if(HasField(name)) { list.Remove(this[name]); keys.Remove(name); } AddField(name, obj); } public JSONObject GetField(string name) { if(type == JSONObject.Type.OBJECT) for(int i = 0; i < keys.Count; i++) if((string)keys[i] == name) return (JSONObject)list[i]; return null; } public bool HasField(string name) { if(type == JSONObject.Type.OBJECT) for(int i = 0; i < keys.Count; i++) if((string)keys[i] == name) return true; return false; } public void Clear() { type = JSONObject.Type.NULL; list.Clear(); keys.Clear(); str = ""; n = 0; b = false; } public JSONObject Copy() { return new JSONObject(print()); } /* * The Merge function is experimental. Use at your own risk. */ public void Merge(JSONObject obj) { MergeRecur(this, obj); } /// <summary> /// Merge object right into left recursively /// </summary> /// <param name="left">The left (base) object</param> /// <param name="right">The right (new) object</param> static void MergeRecur(JSONObject left, JSONObject right) { if(left.type == JSONObject.Type.NULL) left.Absorb(right); else if(left.type == Type.OBJECT && right.type == Type.OBJECT) { for(int i = 0; i < right.list.Count; i++) { string key = (string)right.keys[i]; if(right[i].isContainer){ if(left.HasField(key)) MergeRecur(left[key], right[i]); else left.AddField(key, right[i]); } else { if(left.HasField(key)) left.SetField(key, right[i]); else left.AddField(key, right[i]); } } } else if(left.type == Type.ARRAY && right.type == Type.ARRAY) { if(right.Count > left.Count){ //Debug.LogError("Cannot merge arrays when right object has more elements"); return; } for(int i = 0; i < right.list.Count; i++) { if(left[i].type == right[i].type) { //Only overwrite with the same type if(left[i].isContainer) MergeRecur(left[i], right[i]); else{ left[i] = right[i]; } } } } } public string print() { return print(0); } public string print(int depth) { //Convert the JSONObject into a stiring if(depth++ > MAX_DEPTH) { //Debug.Log("reached max depth!"); return ""; } string str = ""; switch(type) { case Type.STRING: str = "\"" + this.str + "\""; break; case Type.NUMBER: if(n == double.PositiveInfinity) str = INFINITY; else if (n == double.NegativeInfinity) str = NEGINFINITY; else str += n; break; case JSONObject.Type.OBJECT: if(list.Count > 0) { str = "{"; #if(READABLE) //for a bit more readability, comment the define above to save space str += "\n"; depth++; #endif for(int i = 0; i < list.Count; i++) { string key = (string)keys[i]; JSONObject obj = (JSONObject)list[i]; if(obj) { #if(READABLE) for(int j = 0; j < depth; j++) str += "\t"; //for a bit more readability #endif str += "\"" + key + "\":"; str += obj.print(depth) + ","; #if(READABLE) str += "\n"; #endif } } #if(READABLE) str = str.Substring(0, str.Length - 1); #endif str = str.Substring(0, str.Length - 1); str += "}"; } else str = "null"; break; case JSONObject.Type.ARRAY: if(list.Count > 0) { str = "["; #if(READABLE) str += "\n"; //for a bit more readability depth++; #endif foreach(JSONObject obj in list) { if(obj) { #if(READABLE) for(int j = 0; j < depth; j++) str += "\t"; //for a bit more readability #endif str += obj.print(depth) + ","; #if(READABLE) str += "\n"; //for a bit more readability #endif } } #if(READABLE) str = str.Substring(0, str.Length - 1); #endif str = str.Substring(0, str.Length - 1); str += "]"; } else str = "null"; break; case Type.BOOL: if(b) str = "true"; else str = "false"; break; case Type.NULL: str = "null"; break; } return str; } public JSONObject this[int index] { get { if(list.Count > index) return (JSONObject)list[index]; else return null; } set { if(list.Count > index) list[index] = value; } } public JSONObject this[string index] { get { return GetLongField(index); } set { SetLongField(index, value); } } public override string ToString() { return print(); } public Dictionary<string, string> ToDictionary() { if (type == Type.OBJECT) { Dictionary<string, string> result = new Dictionary<string, string>(); for (int i = 0; i < list.Count; i++) { JSONObject val = (JSONObject)list[i]; switch (val.type) { case Type.STRING: result.Add((string)keys[i], val.str); break; case Type.NUMBER: result.Add((string)keys[i], val.n + ""); break; case Type.BOOL: result.Add((string)keys[i], val.b + ""); break; default: //Debug.LogWarning("Omitting object: " + (string)keys[i] + " in dictionary conversion"); break; } } return result; } else { //Debug.LogWarning("Tried to turn non-Object JSONObject into a dictionary"); } return null; } /// <summary> /// Gets the long field. /// </summary> /// <returns> /// The long field. /// </returns> /// <param name='longfields'> /// Longfields. /// </param> private JSONObject GetLongField(string longfields) { string[] listField = longfields.Split('.'); JSONObject result = GetField(listField[0]); for (int i = 1; i < listField.Length && !result.IsNullOrEmpty(); i++) { string field = listField[i]; result = result.GetField(field); } return result; } public void SetLongField(string longfields, JSONObject obj) { int idx = longfields.IndexOf('.'); if(idx > 0) { JSONObject result = GetField(longfields.Substring(0, idx)); if(!result.IsNullOrEmpty()) result.SetLongField(longfields.Substring(idx + 1, longfields.Length - idx), obj); } else { SetField(longfields, obj); } } }
zzzstrawhatzzz
trunk/client/Assets/Scripts/Libs/JSONObject.cs
C#
asf20
17,554
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using MessageBox; public class GUIMessageDialog : GUIDialogBase { #region Dialog Button Control public class DialogBtnControl { public Transform tranformBtn; public UILabel text; public DialogResult result; public DialogBtnControl(Transform _tran, UILabel _labelText) { tranformBtn = _tran; text = _labelText; } public void Reset() { result = DialogResult.None; text.text = ""; tranformBtn.gameObject.SetActive(false); } public void SetInfomation(DialogResult _result, int _textId, Vector3 _location) { tranformBtn.gameObject.SetActive(true); result = _result; //text.text = AvLocalizationManager.GetString(_textId); tranformBtn.localPosition = _location; } } #endregion #region delegate public ButtonClick bt1_click; public ButtonClick bt2_click; public ButtonClick bt3_click; #endregion // content private UILabel contentMessage; private UILabel captionText; // image title private UISprite imageTitle; // location btn first save public Vector3 location1Btn; public Vector3 location2Btn; public Vector3 location3Btn; public float distance = 125.0f; // current Result for three button private DialogBtnControl[] btnDialog = new DialogBtnControl[3]; // control static private static List<MessageItem> items = new List<MessageItem>(); private List<SpriteRenderer> listShow = new List<SpriteRenderer>(); // private static GUIMessageDialog messageHandler; public void Awake() { //messageHandler = this; } //********************* Overide *********************// public override GameObject OnInit() { //Debug.Log("dialog messagebox on init"); GameObject obj = Util.LoadPreafab(GUI_PATH_PREFAB + "UIMessageDialog", gameObject); // AvGameObjectUtils.LoadGameObject(gameObject.transform, ); obj.name = "UIMessageDialog"; guiControlLocation = obj.transform.Find("UIContent").gameObject; guiControlLocation.transform.localPosition = new Vector3(0, 1000, -100.0f); // find object contentMessage = guiControlLocation.transform.FindChild("messageText").GetComponent<UILabel>(); captionText = guiControlLocation.transform.Find("captionText").GetComponent<UILabel>(); for (int i = 0; i < 3; i++) { Transform _tran = guiControlLocation.transform.Find("Btn0" + (i + 1).ToString()); _tran.gameObject.GetComponent<UIForwardEvents>().target = gameObject; UILabel _label = _tran.Find("staticText").GetComponent<UILabel>(); btnDialog[i] = new DialogBtnControl(_tran, _label); btnDialog[i].Reset(); } layer =20; UIPanel panel = obj.GetComponent<UIPanel>(); if (panel != null) panel.depth = layer; /*UIWidget[] wiget = gameObject.GetComponentsInChildren<UIWidget>(); //Debug.LogError(wiget.Length); for (int i = 0; i < wiget.Length; i++) { wiget[i].depth += (layer +50); }*/ return obj; } protected override float OnBeginShow(object parameter) { // to do if (listShow.Count > 0) { for (int i = 0; i < listShow.Count; i++) { listShow[i].enabled = true; } } listShow.Clear(); Transform parent = gameObject.transform.parent; SpriteRenderer[] _sprites= parent.gameObject.GetComponentsInChildren<SpriteRenderer>(); for (int i = 0; i < _sprites.Length; i++) { if (_sprites[i].enabled == true) { listShow.Add(_sprites[i]); } } for (int i = 0; i < listShow.Count; i++) { listShow[i].enabled = false; } guiControlDlg.SetActive(true); //MessageItem item1=new MessageItem(); if (parameter != null) { MessageItem item = (MessageItem)parameter; SetupDisplayButtons(item); contentMessage.text = item.message; captionText.text = item.caption; guiControlLocation.transform.localPosition = new Vector3(0, 0, -100.0f); } else { Debug.LogError("Method to open Message Dialog is not exactly"); } return base.OnBeginShow(parameter); } protected override float OnBeginHide(object parameter) { return base.OnBeginHide(parameter); } protected override void OnEndHide(bool isDestroy) { for (int i = 0; i < listShow.Count; i++) { listShow[i].enabled = true; } listShow.Clear(); } protected override void OnEndShow() { } //******************** End override ****************// void OnClick() { switch (UICamera.selectedObject.name) { case "Btn01": { //Debug.LogError("111"); OnBtnClick(0); if (bt1_click != null) bt1_click(); } break; case "Btn02": { //Debug.LogError("222"); OnBtnClick(1); if (bt2_click != null) bt2_click(); } break; case "Btn03": { //Debug.LogError("333"); OnBtnClick(2); if (bt3_click != null) bt3_click(); } break; } } public void OnBtnClick(int i) { bool close = true; if (items[items.Count - 1].callback != null) close = items[items.Count - 1].callback(btnDialog[i].result); if (!close) return; items.RemoveAt(items.Count - 1); if (close && !CheckShowMessageDialog()) AvUIManager.instance.HideDialog(DialogName.MessageBox); } public bool CheckShowMessageDialog() { if (items.Count > 0) { MessageItem _item=items[items.Count - 1]; AvUIManager.instance.ShowDialog(DialogName.MessageBox, _item); return true; } return false; } #region simulator message same with .Net private void ResetMessageState() { for (int i = 0; i < 3; i++) { btnDialog[i].Reset(); } } private void SetupDisplayButtons(MessageItem item) { ResetMessageState(); switch (item.buttons) { case Buttons.OK: btnDialog[0].SetInfomation(DialogResult.Ok, 9017, location1Btn); break; case Buttons.OKCancel: btnDialog[0].SetInfomation(DialogResult.Ok, 9017, new Vector3(location2Btn.x+260,location2Btn.y,location2Btn.z)); btnDialog[1].SetInfomation(DialogResult.Cancel, 31,location2Btn); break; case Buttons.AbortRetryIgnore: btnDialog[0].SetInfomation(DialogResult.Abort, 34, location3Btn); btnDialog[1].SetInfomation(DialogResult.Retry, 35, new Vector3(location3Btn.x + 200, location2Btn.y, location2Btn.z)); btnDialog[2].SetInfomation(DialogResult.Ignore, 36, new Vector3(location3Btn.x + 200*2, location2Btn.y, location2Btn.z)); break; case Buttons.YesNoCancel: btnDialog[0].SetInfomation(DialogResult.Yes, 32, location3Btn); btnDialog[1].SetInfomation(DialogResult.No, 33, new Vector3(location3Btn.x + 200, location2Btn.y, location2Btn.z)); btnDialog[2].SetInfomation(DialogResult.Cancel, 31, new Vector3(location3Btn.x + 200 * 2, location2Btn.y, location2Btn.z)); break; case Buttons.YesNo: btnDialog[0].SetInfomation(DialogResult.Yes, 32, new Vector3(location2Btn.x + 260, location2Btn.y, location2Btn.z)); btnDialog[1].SetInfomation(DialogResult.No, 33, location2Btn); break; case Buttons.RetryCancel: btnDialog[0].SetInfomation(DialogResult.Retry, 35, location2Btn); btnDialog[1].SetInfomation(DialogResult.Cancel, 31, new Vector3(location2Btn.x + 260, location2Btn.y, location2Btn.z)); break; default: btnDialog[0].SetInfomation(DialogResult.None, 37, location1Btn); break; } } public static void Show( string message) { Show(null, message, string.Empty, Buttons.OK, Icon.None, MessageBox.DefaultButton.Button1); } public static void Show(MessageCallback callback, string message) { Show(callback, message, string.Empty, Buttons.OK, Icon.None, MessageBox.DefaultButton.Button1); } public static void Show(MessageCallback callback, string message, string caption) { Show(callback, message, caption, Buttons.OK, Icon.None, MessageBox.DefaultButton.Button1); } public static void Show(MessageCallback callback, string message, string caption, Buttons buttons) { Show(callback, message, caption, buttons, Icon.None, MessageBox.DefaultButton.Button1); } public static void Show(MessageCallback callback, string message, string caption, Buttons buttons, Icon icon) { Show(callback, message, caption, buttons, icon, MessageBox.DefaultButton.Button1); } public static void Show(MessageCallback callback, string message, string caption, Buttons buttons, Icon icon, MessageBox.DefaultButton defaultButton) { //if(string.IsNullOrEmpty(caption)) //caption = AvLocalizationManager.GetString(6); MessageItem item = new MessageItem { caption = caption, buttons = buttons, defaultButton = defaultButton, callback = callback }; item.message = message; switch (icon) { case Icon.Hand: case Icon.Stop: case Icon.Error: //item.message.image = messageHandler.error; break; case Icon.Exclamation: case Icon.Warning: //item.message.image = messageHandler.warning; break; case Icon.Asterisk: case Icon.Information: //item.message.image = messageHandler.info; break; } if (items.Count > 2) { items.RemoveAt(0); } items.Add(item); AvUIManager.instance.ShowDialog(DialogName.MessageBox, item); } #endregion }
zzzstrawhatzzz
trunk/client/Assets/Scripts/GUI/Base/GUIMessageDialog.cs
C#
asf20
11,223
using UnityEngine; using System.Collections; using System; namespace MessageBox { public enum DialogResult { None, Ok, Cancel, Abort, Retry, Ignore, Yes, No } public enum Buttons { OK=0, OKCancel, AbortRetryIgnore, YesNoCancel, YesNo, RetryCancel } public enum DefaultButton { Button1, Button2, Button3 } public enum Icon { None, Hand, Exclamation, Asterisk, Stop, Error, Warning, Information } public delegate bool MessageCallback(DialogResult result); public class MessageItem { // Fields public Buttons buttons; public MessageCallback callback; public string caption; public DefaultButton defaultButton; public string message; // Methods public MessageItem() { this.message = string.Empty; this.caption = string.Empty; this.buttons = Buttons.OK; this.defaultButton = DefaultButton.Button1; } public MessageItem(MessageCallback call, string content, string cap, Buttons btns, DefaultButton defaultBtn) { this.message = content; this.caption = cap; this.buttons = btns; this.defaultButton = defaultBtn; } } }
zzzstrawhatzzz
trunk/client/Assets/Scripts/GUI/Base/MessageBox.cs
C#
asf20
1,564
using UnityEngine; using System; using System.Linq; using System.Collections; using System.Collections.Generic; #if UNITY_EDITOR using UnityEditor; #endif public enum GUIPanelHideAction { Disable = 0, Destroy, } public class GUIDialogBase : MonoBehaviour { public enum GUIPanelStatus { Invalid, Ok, Showing, Showed, Hiding, Hidden } public const string GUI_PATH_PREFAB = "Prefabs/Dialogs/"; // Hide action public DialogName dialogName = DialogName.None; public string dialogPrefab=""; public string locationName = "UIContent"; public int layer =0; public GUIPanelHideAction hideAction; public float destroyTimeout = 120; public float showDelay; // Show/Hide tween public string showTweenName = "show"; public string hideTweenName = "hide"; public bool useBlackBackground = true; // Active state private Dictionary<GameObject, bool> activeSave; [HideInInspector] public GUIPanelStatus status = GUIPanelStatus.Invalid; private bool isHasAlpha = false; public bool isSetupLocation=false; public Vector2 vectorSetupLocation = new Vector2(0, 0); [HideInInspector] public GameObject guiControlDlg; [HideInInspector] public GameObject guiControlLocation; [HideInInspector] GUIBaseDialogHandler uiBaseDialogHandler; public GUIBaseDialogHandler GetDialogHandler() { return uiBaseDialogHandler; } public virtual GameObject OnInit() { try { //Debug.LogError("Init Dialog" + name); Debug.Log("Load dialog " + dialogPrefab); GameObject obj = Util.LoadPreafab(GUI_PATH_PREFAB + dialogPrefab, gameObject); obj.name = dialogPrefab; if (obj.transform.Find(locationName) != null) { guiControlLocation = obj.transform.Find(locationName).gameObject; guiControlLocation.transform.localPosition = new Vector3(1000,0,0); } UIPanel panel = obj.GetComponent<UIPanel>(); if (panel != null) panel.depth = layer; UIPanel[] panels = obj.GetComponentsInChildren<UIPanel>(); for (int i = 0; i < panels.Length; i++) { panels[i].depth = layer; } uiBaseDialogHandler = gameObject.GetComponentInChildren<GUIBaseDialogHandler>(); return obj; } catch (Exception ex) { Debug.LogError("Error:" + ex.Message); } return null; } /// <summary> /// Inits this instance. /// </summary> public bool Init() { if (status >= GUIPanelStatus.Ok) return true; status = GUIPanelStatus.Invalid; try { guiControlDlg = OnInit(); if (guiControlDlg != null) { status = GUIPanelStatus.Ok; } return true; } catch (System.Exception ex) { Debug.LogError("Init GUI panel - Init " + this.GetType().Name + "Exception - "+ ex); } return false; } /// <summary> /// Tries the show. /// </summary> public bool TryShow(object parameter) { if (status == GUIPanelStatus.Invalid) { Init(); } StopCoroutine("WaitForDestroy"); // End hiding if (status == GUIPanelStatus.Hiding) { iTween.Stop(guiControlLocation); OnEndHide(hideAction == GUIPanelHideAction.Destroy); status = GUIPanelStatus.Hidden; } if (status == GUIPanelStatus.Hidden || status == GUIPanelStatus.Ok) { status = GUIPanelStatus.Showing; RestoreActiveState(true); if (isHasAlpha) { isHasAlpha = false; OnResetAlpha(); } //Debug.LogWarning("2" + parameter); StartCoroutine(DoShow(parameter)); //Debug.LogWarning("3"); return true; } if (status == GUIPanelStatus.Showed || status == GUIPanelStatus.Showing) { StartCoroutine(DoShow(parameter)); Debug.LogWarning("4"); return true; } Debug.LogWarning("5"); return false; } private IEnumerator DoShow(object parameter) { //Debug.LogWarning("DoShow" + parameter); yield return new WaitForSeconds(showDelay); if (isSetupLocation && guiControlLocation!=null) { Vector3 pos = guiControlLocation.transform.localPosition; pos.x = vectorSetupLocation.x; pos.y = vectorSetupLocation.y; pos.z = 0; guiControlLocation.transform.localPosition = pos; } //Debug.LogWarning("OnBeginShow" + parameter); float wait = OnBeginShow(parameter); AvUIManager.instance.CheckShowBorder(); if (wait > 0) yield return new WaitForSeconds(wait); else yield return null; if (status == GUIPanelStatus.Showing) { OnEndShow(); status = GUIPanelStatus.Showed; } } /// <summary> /// Hides the specified after time out. /// </summary> public void Hide(object parameter) { if (gameObject == null) return; // End showing if (status == GUIPanelStatus.Showing) { iTween.Stop(guiControlLocation); OnEndShow(); status = GUIPanelStatus.Showed; } if (status == GUIPanelStatus.Showed) { status = GUIPanelStatus.Hiding; SaveActiveState(); StartCoroutine(DoHide(parameter)); } AvUIManager.instance.CheckShowBorder(); } public void InitialDefaulState() { status = GUIPanelStatus.Hiding; SaveActiveState(); guiControlDlg.SetActive(false); } /// <summary> /// Does the hide. /// </summary> private IEnumerator DoHide(object parameter) { float wait = OnBeginHide(parameter); if (wait > 0) yield return new WaitForSeconds(wait); else yield return null; if (status == GUIPanelStatus.Hiding) { OnEndHide(hideAction == GUIPanelHideAction.Destroy); switch (hideAction) { case GUIPanelHideAction.Disable: guiControlDlg.SetActive(false); status = GUIPanelStatus.Hidden; break; case GUIPanelHideAction.Destroy: guiControlDlg.SetActive(false); status = GUIPanelStatus.Hidden; StartCoroutine("WaitForDestroy"); break; } } } IEnumerator WaitForDestroy() { yield return new WaitForSeconds(destroyTimeout); Destroy(guiControlDlg); status = GUIPanelStatus.Invalid; } /// <summary> /// Does the tween. /// </summary> protected float DoTween(string tweenName) { if (string.IsNullOrEmpty(tweenName)) return 0; iTweenEvent tween = gameObject.GetComponents<iTweenEvent>().Where(tw => tw.tweenName == tweenName).FirstOrDefault(); if (tween != null) { if (tween.type != iTweenEvent.TweenType.ValueTo) { tween.SetObjectTarget(guiControlLocation); } else { tween.SetObjectTarget(gameObject); } tween.Play(); if (!tween.Values.ContainsKey("time")) return 2f; return (float)tween.Values["time"]; } return 0; } private void OnUpdateAlpha(double alpha) { UIPanel[] panels = gameObject.GetComponentsInChildren<UIPanel>(); for (int i = 0; i < panels.Length; i++) { if (alpha > 1) alpha = 1; else if (alpha < 0) alpha = 0; panels[i].alpha = (float)alpha; } isHasAlpha = true; } private void OnResetAlpha() { UIPanel[] panels = gameObject.GetComponentsInChildren<UIPanel>(); for (int i = 0; i < panels.Length; i++) { panels[i].alpha = 0.99f; } } /// <summary> /// Called when [begin show]. /// </summary> protected virtual float OnBeginShow(object parameter) { if (uiBaseDialogHandler != null) { uiBaseDialogHandler.OnBeginShow(parameter); } ApplyDepthPosition(guiControlLocation); AvUIManager.instance.CheckShowBorder(); return DoTween(showTweenName); } /// <summary> /// Called when [end show]. /// </summary> protected virtual void OnEndShow() { ApplyDepthPosition(guiControlLocation); AvUIManager.instance.CheckShowBorder(); } /// <summary> /// Called when [begin hide]. /// </summary> protected virtual float OnBeginHide(object parameter) { if (uiBaseDialogHandler != null) { uiBaseDialogHandler.OnBeginHide(parameter); } return DoTween(hideTweenName); } /// <summary> /// Called when [end hide]. /// </summary> protected virtual void OnEndHide(bool isDestroy) { } /// <summary> /// Saves the state of the active. /// </summary> protected void SaveActiveState() { if (guiControlDlg == null) return; //Debug.LogError("save"); if (activeSave == null) activeSave = new Dictionary<GameObject, bool>(); else activeSave.Clear(); activeSave[guiControlDlg] = gameObject.activeSelf; Transform[] children = gameObject.GetComponentsInChildren<Transform>(true); foreach (var child in children) { activeSave[child.gameObject] = child.gameObject.activeSelf; } } /// <summary> /// Restores the state of the active. /// </summary> protected void RestoreActiveState(bool defaultState) { if (gameObject == null || activeSave == null) return; //Debug.LogError("restore"); bool isActive = false; if (activeSave.TryGetValue(gameObject, out isActive)) gameObject.SetActive(isActive); Transform[] children = gameObject.GetComponentsInChildren<Transform>(true); foreach (var child in children) { if (activeSave.TryGetValue(child.gameObject, out isActive)) child.gameObject.SetActive(isActive); else child.gameObject.SetActive(defaultState); } } public void ApplyDepthPosition(GameObject guiObject) { if (guiObject == null) return; if (layer >=15) { layer = 15; } Vector3 pos = guiObject.transform.localPosition; if (layer >= 0) { pos.z = -20-layer*10; } else { pos.z = -20-150; } guiObject.transform.localPosition = pos; } }
zzzstrawhatzzz
trunk/client/Assets/Scripts/GUI/Base/GUIDialogBase.cs
C#
asf20
10,787
using System; using System.Collections.Generic; using System.Linq; //using System.Diagnostics; using System.Text; using SimpleJson.Reflection; using UnityEngine; namespace FHNetSocket { public class JsonEncodedEventMessage { public string name { get; set; } public object[] args { get; set; } public JsonEncodedEventMessage() { } public JsonEncodedEventMessage(string name, object payload) : this(name, new[]{payload}) { } public JsonEncodedEventMessage(string name, object[] payloads) { this.name = name; this.args = payloads; } public T GetFirstArgAs<T>() { try { var firstArg = this.args.FirstOrDefault(); if (firstArg != null) return SimpleJson.SimpleJson.DeserializeObject<T>(firstArg.ToString()); } catch (Exception ex) { // add error logging here throw; } return default(T); } public IEnumerable<T> GetArgsAs<T>() { List<T> items = new List<T>(); foreach (var i in this.args) { items.Add( SimpleJson.SimpleJson.DeserializeObject<T>(i.ToString()) ); } return items.AsEnumerable(); } public string ToJsonString() { #if UNITY_TESTING || IOS return ToSimpleJSON(); #else return SimpleJson.SimpleJson.SerializeObject(this); #endif } public static JsonEncodedEventMessage Deserialize(string jsonString) { JsonEncodedEventMessage msg = null; #if UNITY_TESTING || IOS msg = DeserializeSimpleJSON(jsonString); #else try { msg = SimpleJson.SimpleJson.DeserializeObject<JsonEncodedEventMessage>(jsonString); } catch (Exception ex) { Debug.LogError(ex); } #endif return msg; } private string ToSimpleJSON() { return "{" + GetStringElement() + "}"; } private string GetStringElement() { string str = ""; str += "\"name\":" + "\"" +name + "\""+","; str += "\"args\":" + "["; for (int i = 0; i < args.Length; i++) { str += args[i].ToString(); } str += "]"; return str; } public static JsonEncodedEventMessage DeserializeSimpleJSON(string str_json) { SimpleJSON.JSONNode json = SimpleJSON.JSONNode.Parse(str_json); JsonEncodedEventMessage msg = new JsonEncodedEventMessage(); try { msg.name = (string)json["name"]; SimpleJSON.JSONArray arr = (SimpleJSON.JSONArray)SimpleJSON.JSONArray.Parse(json["args"].ToString()); if (arr != null) { msg.args = new string[arr.Count]; for (int i = 0; i < arr.Count; i++) { msg.args[i] = arr[i].ToString(); } } return msg; } catch (Exception ex) { return null; } } } }
zzzstrawhatzzz
trunk/client/Assets/Scripts/NetworkOnline/JsonHelper/JsonEncodedEventMessage.cs
C#
asf20
3,492
using UnityEngine; using System.Collections; public class BoardCellHandler : MonoBehaviour { public eCardType typeContains; bool isContainer = false; public BoardCellAnimator animator; Rect rectInScreen = new Rect(0,0,50,50); public CardHandler card; public bool IsContainer { get { return isContainer; } set { isContainer = value; } } // Use this for initialization void Start () { } // Update is called once per frame void Update () { } void Awake() { animator = GetComponent<BoardCellAnimator>(); Vector3 pos = Camera.mainCamera.WorldToScreenPoint(transform.position); rectInScreen.center = new Vector2(pos.x, pos.y); } public bool IsContain(Vector2 screenPos) { return rectInScreen.Contains(screenPos); } }
zzzstrawhatzzz
trunk/client/Assets/Scripts/Game/BoardCellHandler.cs
C#
asf20
881
using UnityEngine; using System.Collections; public class GameOfflineManager : SingletonMono<GameOfflineManager> { public PlayerCardManager playerCardManager; public AICardManager aiCardManager; void Awake() { } // Use this for initialization void Start () { } public void StartGame() { if(playerCardManager == null) playerCardManager = GameObject.FindObjectOfType<PlayerCardManager>(); if(aiCardManager == null) aiCardManager = GameObject.FindObjectOfType<AICardManager>(); playerCardManager.onCompleteDeal += OnCompleteDeal; playerCardManager.DealCard(); } // Update is called once per frame void Update () { } public void OnCompleteDeal(ePlayerType type) { if (type == ePlayerType.Player) aiCardManager.DealCard(); } }
zzzstrawhatzzz
trunk/client/Assets/Scripts/Game/GameOfflineManager.cs
C#
asf20
908
using UnityEngine; using System.Collections; public class CameraManager : SingletonMono<CameraManager> { public Camera uiCamera; }
zzzstrawhatzzz
trunk/client/Assets/Scripts/Game/CameraManager.cs
C#
asf20
146
using UnityEngine; using System.Collections; public class CardHandler : MonoBehaviour { //public BoardCellAnimator animator; const float inRowY = -13; const float inViewY = -11; public ePlayerType playerType; public eCardType type; public eCardStatus status = eCardStatus.InRow; bool isDragging = false; bool isLock = false; public BoardCellHandler cellContainer; public SpriteRenderer sprite; int rowPileIndex = 0; public int RowPileIndex { get { return rowPileIndex; } set { rowPileIndex = value; } } public bool Lock { get { return isLock; } set { isLock = value; } } public bool Dragging { get { return isDragging; } set { isDragging = value; } } void Awake() { } // Use this for initialization void Start () { } // Update is called once per frame void Update () { } public void PutToCell(BoardCellHandler cell) { transform.parent = cell.transform; transform.localPosition = Vector3.zero; transform.localRotation = Quaternion.identity; sprite.sortingOrder = -1; cellContainer = cell; } public void Deal(int index) { rowPileIndex = index; } public void OnClick() { if (isDragging) return; if (status == eCardStatus.InRow) { GameUIHandler.instance.ShowCardMenu(BoardManager.instance.GetFrontPileByIndex(rowPileIndex)); status = eCardStatus.InView; isDragging = true; Util.RunTweenMove(gameObject, transform.localPosition.x, inViewY, 0.5f, "onTweenComplete"); } else if(status == eCardStatus.InView) { GameUIHandler.instance.HideCardMenu(); status = eCardStatus.InRow; isDragging = true; Util.RunTweenMove(gameObject, transform.localPosition.x, inRowY, 0.5f, "onTweenComplete"); } } public void OnEndFocus() { if (status == eCardStatus.InView) { status = eCardStatus.InRow; isDragging = true; GameUIHandler.instance.HideCardMenu(); Util.RunTweenMove(gameObject, transform.localPosition.x, inRowY, 0.5f, "onTweenComplete"); } } public void Summon() { if (playerType != ePlayerType.Player || type != eCardType.Monster || status != eCardStatus.InView) return; BoardCellHandler cell = BoardManager.instance.GetCellForPlayerMonster(); if (cell == null) return; } public void Set() { } public void onTweenComplete() { isDragging = false; } }
zzzstrawhatzzz
trunk/client/Assets/Scripts/Game/CardHandler.cs
C#
asf20
2,838
using UnityEngine; using System.Collections; public class CardColliderHandler : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame void Update () { } void OnTriggerEnter2D(Collider2D other) { //Debug.LogError("Enter " + other.name); } void OnTriggerExit2D(Collider2D other) { Debug.LogError("Exit " + other.name); } }
zzzstrawhatzzz
trunk/client/Assets/Scripts/Game/CardColliderHandler.cs
C#
asf20
459
using UnityEngine; using System.Collections; public class BoardCellAnimator : MonoBehaviour { // Use this for initialization Animator animator; void Awake() { animator = GetComponent<Animator>(); } void Start () { } // Update is called once per frame void Update () { } public void PlayAnimation(eBoardCellAnimation ani) { if(animator == null) return; switch (ani) { case eBoardCellAnimation.Idle: animator.SetTrigger("Idle"); break; case eBoardCellAnimation.IsCanSelect: animator.SetTrigger("Select"); break; } } }
zzzstrawhatzzz
trunk/client/Assets/Scripts/Game/BoardCellAnimator.cs
C#
asf20
736
using UnityEngine; using System.Collections; using System.Collections.Generic; public class BoardManager : SingletonMono<BoardManager> { public GameObject cardContainer; public List<BoardCellHandler> frontMonster; public List<BoardCellHandler> frontMagic; public List<BoardCellHandler> backMonster; public List<BoardCellHandler> backMagic; public List<BoardCellHandler> canSelectList = new List<BoardCellHandler>(); public GameObject[] frontRowPileList; public GameObject[] backRowPileList; // Use this for initialization void Start () { } // Update is called once per frame void Update () { } public void ShowCellCanSelect() { CardHandler card = PlayerController.GetCurrentCard(); if (card == null) return; if(card.type == eCardType.Monster) { if (frontMonster != null) { foreach (BoardCellHandler cell in frontMonster) { if (cell.card == null) { cell.animator.PlayAnimation(eBoardCellAnimation.IsCanSelect); canSelectList.Add(cell); } } } } } public void HideCellCanSelect() { foreach (BoardCellHandler cell in canSelectList) { cell.animator.PlayAnimation(eBoardCellAnimation.Idle); } canSelectList.Clear(); } public bool PutCard(Vector2 screenPos) { CardHandler curCard = PlayerController.GetCurrentCard(); if (curCard == null) return false; foreach (BoardCellHandler cell in canSelectList) { if (cell.IsContain(screenPos)) { curCard.PutToCell(cell); cell.card = curCard; return true; } } return false; } public BoardCellHandler GetCellForPlayerMonster() { foreach (BoardCellHandler cell in frontMonster) { if (cell.card == null) return cell; } return null; } public GameObject GetFrontPileByIndex(int index) { return frontRowPileList[index]; } public GameObject GetBackPileByIndex(int index) { return backRowPileList[index]; } }
zzzstrawhatzzz
trunk/client/Assets/Scripts/Game/BoardManager.cs
C#
asf20
2,454
using UnityEngine; using System.Collections; public class AICardManager : PlayerCardManager { void Awake() { rowCardCheck = new bool[GameConst.rowCardLength]; for (int i = 0; i < GameConst.rowCardLength; i++) rowCardCheck[i] = false; SetupDesk(); } // Use this for initialization void Start () { } // Update is called once per frame void Update () { } }
zzzstrawhatzzz
trunk/client/Assets/Scripts/Game/AICardManager.cs
C#
asf20
444
using UnityEngine; using System.Collections; public class PlayerController : MonoBehaviour { // Use this for initialization static CardHandler curCard; void Start () { FingerGestures.OnFingerDown += OnFingerDown; //FingerGestures.OnDragMove += OnDragMove; //FingerGestures.OnDragBegin += OnDragBegin; //ingerGestures.OnDragEnd += OnDragEnd; //FingerGestures.OnFingerUp += OnFingerUp; } // Update is called once per frame void Update () { } public void OnFingerDown( int fingerIndex, Vector2 fingerPos ) { CardHandler preCard = curCard; Camera uiCam = CameraManager.instance.uiCamera; if (uiCam != null) { Ray ray = uiCam.ScreenPointToRay(fingerPos); if (Physics.Raycast(ray, Mathf.Infinity, 1 << (int)eLayerName.UI)) { return; } } GameObject obj = PickObject(fingerPos); if (obj != null && obj.layer == (int)eLayerName.Card) { Debug.Log("Touch Down " + fingerPos); CardHandler card = obj.GetComponent<CardHandler>(); curCard = card; if (preCard != null && curCard != preCard ) preCard.OnEndFocus(); if (card.playerType == ePlayerType.Player) { curCard.OnClick(); } else { } } else if (preCard != null) { preCard.OnEndFocus(); } } public void OnDragMove( Vector2 fingerPos, Vector2 delta ) { if (curCard != null && curCard.playerType == ePlayerType.Player && curCard.Dragging) { Camera mainCamera = Camera.main; Vector3 pos = mainCamera.ScreenToWorldPoint(new Vector3(fingerPos.x, fingerPos.y, Mathf.Abs(curCard.gameObject.transform.position.z - mainCamera.transform.position.z))); //Debug.LogError(pos); //pos.z = 0; curCard.gameObject.transform.position = pos; //Debug.Log("Move " +delta); //Vector3 pos = curCard.transform.localPosition; //curCard.transform.localPosition = Vector3.MoveTowards(pos, new Vector3(pos.x + delta.x, pos.y + delta.y, pos.z), 20); } } public void OnFingerUp(int fingerIndex, Vector2 fingerPos, float timeHeldDown) { if(curCard != null && !curCard.Dragging) Debug.LogError("Up"); } public static GameObject PickObject(Vector2 screenPos) { /*Vector3 MousePosition = Camera.main.ScreenToWorldPoint(new Vector3(screenPos.x, screenPos.y, Camera.main.transform.position.z)); RaycastHit2D hit = Physics2D.Raycast(MousePosition, -Vector2.up); if (hit != null && hit.collider != null) { return hit.collider.gameObject; } return null;*/ Ray ray = Camera.main.ScreenPointToRay(screenPos); RaycastHit hit; if (Physics.Raycast(ray, out hit)) return hit.collider.gameObject; return null; } public static CardHandler GetCurrentCard() { return curCard; } }
zzzstrawhatzzz
trunk/client/Assets/Scripts/Game/PlayerController.cs
C#
asf20
3,368
using UnityEngine; using System.Collections; using System.Collections.Generic; public delegate void CompleteDealEvent(ePlayerType type); public class PlayerCardManager : MonoBehaviour { public ePlayerType type; public GameObject cardContainer; public List<ConfigCardRecord> cardDesk = new List<ConfigCardRecord>(); public List<CardHandler> rowCard = new List<CardHandler>(); public List<CardHandler> putCard = new List<CardHandler>(); public List<CardHandler> lockCard = new List<CardHandler>(); public bool[] rowCardCheck; int curPileIndex = 1; int curRowCardCount = 0; public CompleteDealEvent onCompleteDeal; void Awake() { rowCardCheck = new bool[GameConst.rowCardLength]; for (int i = 0; i < GameConst.rowCardLength; i++) rowCardCheck[i] = false; SetupDesk(); } // Use this for initialization void Start () { } // Update is called once per frame void Update () { } public void SetupDesk() { if (ConfigManager.configCard == null) ConfigManager.instance.Init(); List<ConfigCardRecord> records = ConfigManager.configCard.GetAllCard(); List<ConfigCardRecord> cards = new List<ConfigCardRecord>(); foreach (ConfigCardRecord c in records) { cards.Add(c); } int count = cards.Count; while (count > 0) { int index = Util.rand.Next(count); cardDesk.Add(cards[index]); cards.RemoveAt(index); count--; } Debug.LogError(cardDesk.Count); } public void DealCard() { //Debug.LogError("AAAAAAA"); if(cardDesk.Count > 0 && curRowCardCount < GameConst.rowCardLength) { //Debug.LogError("AAAAAAA"); GameObject card = Util.LoadPreafab(GameConst.cardPrefab, cardContainer); CardHandler hander = card.GetComponent<CardHandler>(); hander.playerType = type; hander.sprite.sprite = Util.LoadSprite(cardDesk[0].GetSpritePath()); cardDesk.RemoveAt(0); GameObject target; if(type == ePlayerType.Player) { card.transform.localPosition = BoardManager.instance.GetFrontPileByIndex(0).transform.localPosition; target = BoardManager.instance.GetFrontPileByIndex(curPileIndex); } else { card.transform.localPosition = BoardManager.instance.GetBackPileByIndex(0).transform.localPosition; target = BoardManager.instance.GetBackPileByIndex(curPileIndex); } card.transform.localScale = target.transform.localScale; hander.Deal(curPileIndex); rowCard.Add(hander); rowCardCheck[curPileIndex - 1] = true; curPileIndex++; curRowCardCount++; iTween.MoveTo(card, iTween.Hash( "x", target.transform.localPosition.x, "y", target.transform.localPosition.y, "time", 1, "isLocal", true, "oncompletetarget", gameObject, "oncomplete", "CompleteDealTween" ) ); } else { if (onCompleteDeal != null) onCompleteDeal(type); } } public void CompleteDealTween() { DealCard(); } public void Lock() { SortCard(); foreach (CardHandler card in putCard) { lockCard.Add(card); card.Lock = true; card.RowPileIndex = -1; } putCard.Clear(); } public virtual void SortCard() { if (rowCard.Count == 0) return; Debug.LogError("i'm here"); for (int i = 0; i < GameConst.rowCardLength; i++) { if (!rowCardCheck[i]) { int j = 0; while (j < rowCard.Count) { CardHandler car = rowCard[j]; if (car.RowPileIndex - 1 <= i) j++; else { rowCardCheck[car.RowPileIndex - 1] = false; car.RowPileIndex = i + 1; rowCardCheck[i] = true; GameObject target = BoardManager.instance.GetFrontPileByIndex(car.RowPileIndex); iTween.MoveTo(car.gameObject, iTween.Hash( "x", target.transform.localPosition.x, "y", target.transform.localPosition.y, "time", 1, "isLocal", true ) ); break; } } if (j >= rowCard.Count) break; } } } public virtual void PutCard() { CardHandler curCard = PlayerController.GetCurrentCard(); if (curCard == null) return; rowCardCheck[curCard.RowPileIndex - 1] = false; rowCard.Remove(curCard); putCard.Add(curCard); } }
zzzstrawhatzzz
trunk/client/Assets/Scripts/Game/PlayerCardManager.cs
C#
asf20
5,549
using UnityEngine; using System.Collections; public enum eLayerName { Card = 8, UI = 11, } public enum eCardType { Monster = 0, Magic = 1 } public enum eBoardCellAnimation { Idle = 0, IsCanSelect = 1, } public enum ePlayerType { Player, AI, Other } public enum eCardStatus { InRow, InView, Summon, Set, Dead }
zzzstrawhatzzz
trunk/client/Assets/Scripts/Game/DefineData.cs
C#
asf20
422
using UnityEngine; using System.Collections; using System.Collections.Generic; using FileHelpers; using GFramework; [DelimitedRecord("\t")] [IgnoreFirst(1)] [IgnoreCommentedLines("//")] [IgnoreEmptyLines(true)] public class ConfigCardRecord { public int id; public string name; public string icon; public int attack; public int defent; public string effect; public string note; public string GetSpritePath() { return "Sprite/Card/" + name; } } public class ConfigCard : GConfigDataTable<ConfigCardRecord> { public ConfigCard() : base("ConfigCard") { } protected override void OnDataLoaded() { //rebuild index to get RebuildIndexField<int>("id"); } public ConfigCardRecord GetCardByID(int id) { return FindRecordByIndex<int>("id", id); } public List<ConfigCardRecord> GetAllCard() { return records; } }
zzzstrawhatzzz
trunk/client/Assets/Scripts/Config/ConfigCard.cs
C#
asf20
953
using UnityEngine; using System.Collections; using System.Collections.Generic; using GFramework; public class ConfigManager : Singleton<ConfigManager> { //public static ConfigString configString; public static ConfigCard configCard; private void LoadDataConfig<TConfigTable>(ref TConfigTable configTable, params string[] dataPaths) where TConfigTable : IConfigDataTable, new() { try { if (configTable == null) { configTable = new TConfigTable(); configTable.BeginLoadAppend(); foreach (var path in dataPaths) { configTable.LoadFromAssetPath(path); } configTable.EndLoadAppend(); Debug.LogWarning("Config loaded:"+ configTable.GetName()); } } catch (System.Exception ex) { Debug.LogError("Load Config Error:"+ configTable.GetName()+", "+ ex.ToString()); } } public void Init() { InitLevel(); } public void InitLevel() { LoadDataConfig<ConfigCard>(ref configCard, "Config/ConfigCard"); } public void Init1() { //sLoadDataConfig<ConfigString>(ref configString, "Config/ConfigString"); } public void UnLoad() { } }
zzzstrawhatzzz
trunk/client/Assets/Scripts/Config/ConfigManager.cs
C#
asf20
1,221
using UnityEngine; using System.Collections; public class GameUIHandler : SingletonMono<GameUIHandler> { public UIFollowTarget cardMenu; // Use this for initialization void Start () { GameOfflineManager.instance.StartGame(); } // Update is called once per frame void Update () { } public void FinishPutCard() { GameOfflineManager.instance.playerCardManager.Lock(); } public void ShowCardMenu(GameObject target) { cardMenu.target = target.transform; cardMenu.gameObject.SetActive(true); } public void HideCardMenu() { cardMenu.gameObject.SetActive(false); } public void Summon() { CardHandler curCard = PlayerController.GetCurrentCard(); if (curCard != null) curCard.Summon(); } }
zzzstrawhatzzz
trunk/client/Assets/Scripts/UI/GameUIHandler.cs
C#
asf20
844
using UnityEngine; using System.Collections; /// <summary> /// Put this script on any object you want to move to the first contact position of a finger /// </summary> public class MoveToFinger : MonoBehaviour { void OnEnable() { // subscribe to the finger down event FingerGestures.OnFingerDown += this.OnFingerDown; } void OnDisable() { // unsubscribe from the finger down event FingerGestures.OnFingerDown -= this.OnFingerDown; } // handle the fingerdown event void OnFingerDown( int fingerIndex, Vector2 fingerPos ) { transform.position = GetWorldPos( fingerPos ); } // convert from screen-space coordinates to world-space coordinates in the XY plane Vector3 GetWorldPos( Vector2 screenPos ) { Camera mainCamera = Camera.main; return mainCamera.ScreenToWorldPoint( new Vector3( screenPos.x, screenPos.y, Mathf.Abs( transform.position.z - mainCamera.transform.position.z ) ) ); } }
zzzstrawhatzzz
trunk/client/Assets/FingerGestures/Utils/MoveToFinger.cs
C#
asf20
1,035
using UnityEngine; using System.Collections; public class GestureStateTracker : MonoBehaviour { public GestureRecognizer gesture; void Awake() { if( !gesture ) gesture = GetComponent<GestureRecognizer>(); } void OnEnable() { if( gesture ) gesture.OnStateChanged += gesture_OnStateChanged; } void OnDisable() { if( gesture ) gesture.OnStateChanged -= gesture_OnStateChanged; } void gesture_OnStateChanged( GestureRecognizer source ) { Debug.Log( "Gesture " + source + " changed from " + source.PreviousState + " to " + source.State ); } }
zzzstrawhatzzz
trunk/client/Assets/FingerGestures/Utils/GestureStateTracker.cs
C#
asf20
689
using UnityEngine; using System.Collections; public class CSharpSkeleton : MonoBehaviour { void OnEnable() { // Register to FingerGestures events // per-finger gestures FingerGestures.OnFingerDown += FingerGestures_OnFingerDown; FingerGestures.OnFingerStationaryBegin += FingerGestures_OnFingerStationaryBegin; FingerGestures.OnFingerStationary += FingerGestures_OnFingerStationary; FingerGestures.OnFingerStationaryEnd += FingerGestures_OnFingerStationaryEnd; FingerGestures.OnFingerMoveBegin += FingerGestures_OnFingerMoveBegin; FingerGestures.OnFingerMove += FingerGestures_OnFingerMove; FingerGestures.OnFingerMoveEnd += FingerGestures_OnFingerMoveEnd; FingerGestures.OnFingerUp += FingerGestures_OnFingerUp; FingerGestures.OnFingerLongPress += FingerGestures_OnFingerLongPress; FingerGestures.OnFingerTap += FingerGestures_OnFingerTap; FingerGestures.OnFingerSwipe += FingerGestures_OnFingerSwipe; FingerGestures.OnFingerDragBegin += FingerGestures_OnFingerDragBegin; FingerGestures.OnFingerDragMove += FingerGestures_OnFingerDragMove; FingerGestures.OnFingerDragEnd += FingerGestures_OnFingerDragEnd; // global gestures FingerGestures.OnLongPress += FingerGestures_OnLongPress; FingerGestures.OnTap += FingerGestures_OnTap; FingerGestures.OnSwipe += FingerGestures_OnSwipe; FingerGestures.OnDragBegin += FingerGestures_OnDragBegin; FingerGestures.OnDragMove += FingerGestures_OnDragMove; FingerGestures.OnDragEnd += FingerGestures_OnDragEnd; FingerGestures.OnPinchBegin += FingerGestures_OnPinchBegin; FingerGestures.OnPinchMove += FingerGestures_OnPinchMove; FingerGestures.OnPinchEnd += FingerGestures_OnPinchEnd; FingerGestures.OnRotationBegin += FingerGestures_OnRotationBegin; FingerGestures.OnRotationMove += FingerGestures_OnRotationMove; FingerGestures.OnRotationEnd += FingerGestures_OnRotationEnd; FingerGestures.OnTwoFingerLongPress += FingerGestures_OnTwoFingerLongPress; FingerGestures.OnTwoFingerTap += FingerGestures_OnTwoFingerTap; FingerGestures.OnTwoFingerSwipe += FingerGestures_OnTwoFingerSwipe; FingerGestures.OnTwoFingerDragBegin += FingerGestures_OnTwoFingerDragBegin; FingerGestures.OnTwoFingerDragMove += FingerGestures_OnTwoFingerDragMove; FingerGestures.OnTwoFingerDragEnd += FingerGestures_OnTwoFingerDragEnd; } void OnDisable() { // Unregister FingerGestures events so we will no longer receive notifications after this object is disabled // per-finger gestures FingerGestures.OnFingerDown -= FingerGestures_OnFingerDown; FingerGestures.OnFingerStationaryBegin -= FingerGestures_OnFingerStationaryBegin; FingerGestures.OnFingerStationary -= FingerGestures_OnFingerStationary; FingerGestures.OnFingerStationaryEnd -= FingerGestures_OnFingerStationaryEnd; FingerGestures.OnFingerMoveBegin -= FingerGestures_OnFingerMoveBegin; FingerGestures.OnFingerMove -= FingerGestures_OnFingerMove; FingerGestures.OnFingerMoveEnd -= FingerGestures_OnFingerMoveEnd; FingerGestures.OnFingerUp -= FingerGestures_OnFingerUp; FingerGestures.OnFingerLongPress -= FingerGestures_OnFingerLongPress; FingerGestures.OnFingerTap -= FingerGestures_OnFingerTap; FingerGestures.OnFingerSwipe -= FingerGestures_OnFingerSwipe; FingerGestures.OnFingerDragBegin -= FingerGestures_OnFingerDragBegin; FingerGestures.OnFingerDragMove -= FingerGestures_OnFingerDragMove; FingerGestures.OnFingerDragEnd -= FingerGestures_OnFingerDragEnd; // global gestures FingerGestures.OnLongPress -= FingerGestures_OnLongPress; FingerGestures.OnTap -= FingerGestures_OnTap; FingerGestures.OnSwipe -= FingerGestures_OnSwipe; FingerGestures.OnDragBegin -= FingerGestures_OnDragBegin; FingerGestures.OnDragMove -= FingerGestures_OnDragMove; FingerGestures.OnDragEnd -= FingerGestures_OnDragEnd; FingerGestures.OnPinchBegin -= FingerGestures_OnPinchBegin; FingerGestures.OnPinchMove -= FingerGestures_OnPinchMove; FingerGestures.OnPinchEnd -= FingerGestures_OnPinchEnd; FingerGestures.OnRotationBegin -= FingerGestures_OnRotationBegin; FingerGestures.OnRotationMove -= FingerGestures_OnRotationMove; FingerGestures.OnRotationEnd -= FingerGestures_OnRotationEnd; FingerGestures.OnTwoFingerLongPress -= FingerGestures_OnTwoFingerLongPress; FingerGestures.OnTwoFingerTap -= FingerGestures_OnTwoFingerTap; FingerGestures.OnTwoFingerSwipe -= FingerGestures_OnTwoFingerSwipe; FingerGestures.OnTwoFingerDragBegin -= FingerGestures_OnTwoFingerDragBegin; FingerGestures.OnTwoFingerDragMove -= FingerGestures_OnTwoFingerDragMove; FingerGestures.OnTwoFingerDragEnd -= FingerGestures_OnTwoFingerDragEnd; } #region Per-Finger Event Callbacks void FingerGestures_OnFingerDown( int fingerIndex, Vector2 fingerPos ) { } void FingerGestures_OnFingerMoveBegin( int fingerIndex, Vector2 fingerPos ) { } void FingerGestures_OnFingerMove( int fingerIndex, Vector2 fingerPos ) { } void FingerGestures_OnFingerMoveEnd( int fingerIndex, Vector2 fingerPos ) { } void FingerGestures_OnFingerStationaryBegin( int fingerIndex, Vector2 fingerPos ) { } void FingerGestures_OnFingerStationary( int fingerIndex, Vector2 fingerPos, float elapsedTime ) { } void FingerGestures_OnFingerStationaryEnd( int fingerIndex, Vector2 fingerPos, float elapsedTime ) { } void FingerGestures_OnFingerUp( int fingerIndex, Vector2 fingerPos, float timeHeldDown ) { } void FingerGestures_OnFingerLongPress( int fingerIndex, Vector2 fingerPos ) { } void FingerGestures_OnFingerTap( int fingerIndex, Vector2 fingerPos, int tapCount ) { } void FingerGestures_OnFingerSwipe( int fingerIndex, Vector2 startPos, FingerGestures.SwipeDirection direction, float velocity ) { } void FingerGestures_OnFingerDragBegin( int fingerIndex, Vector2 fingerPos, Vector2 startPos ) { } void FingerGestures_OnFingerDragMove( int fingerIndex, Vector2 fingerPos, Vector2 delta ) { } void FingerGestures_OnFingerDragEnd( int fingerIndex, Vector2 fingerPos ) { } #endregion #region Global Gesture Callbacks void FingerGestures_OnLongPress( Vector2 fingerPos ) { } void FingerGestures_OnTap( Vector2 fingerPos, int tapCount ) { } void FingerGestures_OnSwipe( Vector2 startPos, FingerGestures.SwipeDirection direction, float velocity ) { } void FingerGestures_OnDragBegin( Vector2 fingerPos, Vector2 startPos ) { } void FingerGestures_OnDragMove( Vector2 fingerPos, Vector2 delta ) { } void FingerGestures_OnDragEnd( Vector2 fingerPos ) { } void FingerGestures_OnPinchBegin( Vector2 fingerPos1, Vector2 fingerPos2 ) { } void FingerGestures_OnPinchMove( Vector2 fingerPos1, Vector2 fingerPos2, float delta ) { } void FingerGestures_OnPinchEnd( Vector2 fingerPos1, Vector2 fingerPos2 ) { } void FingerGestures_OnRotationBegin( Vector2 fingerPos1, Vector2 fingerPos2 ) { } void FingerGestures_OnRotationMove( Vector2 fingerPos1, Vector2 fingerPos2, float rotationAngleDelta ) { } void FingerGestures_OnRotationEnd( Vector2 fingerPos1, Vector2 fingerPos2, float totalRotationAngle ) { } void FingerGestures_OnTwoFingerLongPress( Vector2 fingerPos ) { } void FingerGestures_OnTwoFingerTap( Vector2 fingerPos, int tapCount ) { } void FingerGestures_OnTwoFingerSwipe( Vector2 startPos, FingerGestures.SwipeDirection direction, float velocity ) { } void FingerGestures_OnTwoFingerDragBegin( Vector2 fingerPos, Vector2 startPos ) { } void FingerGestures_OnTwoFingerDragMove( Vector2 fingerPos, Vector2 delta ) { } void FingerGestures_OnTwoFingerDragEnd( Vector2 fingerPos ) { } #endregion }
zzzstrawhatzzz
trunk/client/Assets/FingerGestures/SkeletonCode/CSharpSkeleton.cs
C#
asf20
8,629
function OnEnable() { // Register to FingerGestures events // per-finger gestures FingerGestures.OnFingerDown += FingerGestures_OnFingerDown; FingerGestures.OnFingerStationaryBegin += FingerGestures_OnFingerStationaryBegin; FingerGestures.OnFingerStationary += FingerGestures_OnFingerStationary; FingerGestures.OnFingerStationaryEnd += FingerGestures_OnFingerStationaryEnd; FingerGestures.OnFingerMoveBegin += FingerGestures_OnFingerMoveBegin; FingerGestures.OnFingerMove += FingerGestures_OnFingerMove; FingerGestures.OnFingerMoveEnd += FingerGestures_OnFingerMoveEnd; FingerGestures.OnFingerUp += FingerGestures_OnFingerUp; FingerGestures.OnFingerLongPress += FingerGestures_OnFingerLongPress; FingerGestures.OnFingerTap += FingerGestures_OnFingerTap; FingerGestures.OnFingerSwipe += FingerGestures_OnFingerSwipe; FingerGestures.OnFingerDragBegin += FingerGestures_OnFingerDragBegin; FingerGestures.OnFingerDragMove += FingerGestures_OnFingerDragMove; FingerGestures.OnFingerDragEnd += FingerGestures_OnFingerDragEnd; // global gestures FingerGestures.OnLongPress += FingerGestures_OnLongPress; FingerGestures.OnTap += FingerGestures_OnTap; FingerGestures.OnSwipe += FingerGestures_OnSwipe; FingerGestures.OnDragBegin += FingerGestures_OnDragBegin; FingerGestures.OnDragMove += FingerGestures_OnDragMove; FingerGestures.OnDragEnd += FingerGestures_OnDragEnd; FingerGestures.OnPinchBegin += FingerGestures_OnPinchBegin; FingerGestures.OnPinchMove += FingerGestures_OnPinchMove; FingerGestures.OnPinchEnd += FingerGestures_OnPinchEnd; FingerGestures.OnRotationBegin += FingerGestures_OnRotationBegin; FingerGestures.OnRotationMove += FingerGestures_OnRotationMove; FingerGestures.OnRotationEnd += FingerGestures_OnRotationEnd; FingerGestures.OnTwoFingerLongPress += FingerGestures_OnTwoFingerLongPress; FingerGestures.OnTwoFingerTap += FingerGestures_OnTwoFingerTap; FingerGestures.OnTwoFingerSwipe += FingerGestures_OnTwoFingerSwipe; FingerGestures.OnTwoFingerDragBegin += FingerGestures_OnTwoFingerDragBegin; FingerGestures.OnTwoFingerDragMove += FingerGestures_OnTwoFingerDragMove; FingerGestures.OnTwoFingerDragEnd += FingerGestures_OnTwoFingerDragEnd; } function OnDisable() { // Unregister FingerGestures events so we will no longer receive notifications after this object is disabled // per-finger gestures FingerGestures.OnFingerDown -= FingerGestures_OnFingerDown; FingerGestures.OnFingerStationaryBegin -= FingerGestures_OnFingerStationaryBegin; FingerGestures.OnFingerStationary -= FingerGestures_OnFingerStationary; FingerGestures.OnFingerStationaryEnd -= FingerGestures_OnFingerStationaryEnd; FingerGestures.OnFingerMoveBegin -= FingerGestures_OnFingerMoveBegin; FingerGestures.OnFingerMove -= FingerGestures_OnFingerMove; FingerGestures.OnFingerMoveEnd -= FingerGestures_OnFingerMoveEnd; FingerGestures.OnFingerUp -= FingerGestures_OnFingerUp; FingerGestures.OnFingerLongPress -= FingerGestures_OnFingerLongPress; FingerGestures.OnFingerTap -= FingerGestures_OnFingerTap; FingerGestures.OnFingerSwipe -= FingerGestures_OnFingerSwipe; FingerGestures.OnFingerDragBegin -= FingerGestures_OnFingerDragBegin; FingerGestures.OnFingerDragMove -= FingerGestures_OnFingerDragMove; FingerGestures.OnFingerDragEnd -= FingerGestures_OnFingerDragEnd; // global gestures FingerGestures.OnLongPress -= FingerGestures_OnLongPress; FingerGestures.OnTap -= FingerGestures_OnTap; FingerGestures.OnSwipe -= FingerGestures_OnSwipe; FingerGestures.OnDragBegin -= FingerGestures_OnDragBegin; FingerGestures.OnDragMove -= FingerGestures_OnDragMove; FingerGestures.OnDragEnd -= FingerGestures_OnDragEnd; FingerGestures.OnPinchBegin -= FingerGestures_OnPinchBegin; FingerGestures.OnPinchMove -= FingerGestures_OnPinchMove; FingerGestures.OnPinchEnd -= FingerGestures_OnPinchEnd; FingerGestures.OnRotationBegin -= FingerGestures_OnRotationBegin; FingerGestures.OnRotationMove -= FingerGestures_OnRotationMove; FingerGestures.OnRotationEnd -= FingerGestures_OnRotationEnd; FingerGestures.OnTwoFingerLongPress -= FingerGestures_OnTwoFingerLongPress; FingerGestures.OnTwoFingerTap -= FingerGestures_OnTwoFingerTap; FingerGestures.OnTwoFingerSwipe -= FingerGestures_OnTwoFingerSwipe; FingerGestures.OnTwoFingerDragBegin -= FingerGestures_OnTwoFingerDragBegin; FingerGestures.OnTwoFingerDragMove -= FingerGestures_OnTwoFingerDragMove; FingerGestures.OnTwoFingerDragEnd -= FingerGestures_OnTwoFingerDragEnd; } //-------------------------------------------------------------------------------------- // Per-Finger Gestures Callbacks //-------------------------------------------------------------------------------------- function FingerGestures_OnFingerDown( fingerIndex : int, fingerPos : Vector2 ) { } function FingerGestures_OnFingerUp( fingerIndex : int, fingerPos : Vector2, timeHeldDown : float ) { } function FingerGestures_OnFingerMoveBegin( fingerIndex : int, fingerPos : Vector2 ) { } function FingerGestures_OnFingerMove( fingerIndex : int, fingerPos : Vector2 ) { } function FingerGestures_OnFingerMoveEnd( fingerIndex : int, fingerPos : Vector2 ) { } function FingerGestures_OnFingerStationaryBegin( fingerIndex : int, fingerPos : Vector2 ) { } function FingerGestures_OnFingerStationary( fingerIndex : int, fingerPos : Vector2, elapsedTime : float ) { } function FingerGestures_OnFingerStationaryEnd( fingerIndex : int, fingerPos : Vector2, elapsedTime : float ) { } function FingerGestures_OnFingerLongPress( fingerIndex : int, fingerPos : Vector2 ) { } function FingerGestures_OnFingerTap( fingerIndex : int, fingerPos : Vector2, tapCount : int ) { } function FingerGestures_OnFingerSwipe( fingerIndex : int, startPos : Vector2, direction : FingerGestures.SwipeDirection, velocity : float ) { } function FingerGestures_OnFingerDragBegin( fingerIndex : int, fingerPos : Vector2, startPos : Vector2 ) { } function FingerGestures_OnFingerDragMove( fingerIndex : int, fingerPos : Vector2, delta : Vector2 ) { } function FingerGestures_OnFingerDragEnd( fingerIndex : int, fingerPos : Vector2 ) { } //-------------------------------------------------------------------------------------- // Global Gestures Callbacks //-------------------------------------------------------------------------------------- function FingerGestures_OnLongPress( fingerPos : Vector2 ) { } function FingerGestures_OnTap( fingerPos : Vector2, tapCount : int ) { } function FingerGestures_OnSwipe( startPos : Vector2, direction : FingerGestures.SwipeDirection, velocity : float ) { } function FingerGestures_OnDragBegin( fingerPos : Vector2, startPos : Vector2 ) { } function FingerGestures_OnDragMove( fingerPos : Vector2, delta : Vector2 ) { } function FingerGestures_OnDragEnd( fingerPos : Vector2 ) { } function FingerGestures_OnPinchBegin( fingerPos1 : Vector2, fingerPos2 : Vector2 ) { } function FingerGestures_OnPinchMove( fingerPos1 : Vector2, fingerPos2 : Vector2, delta : float ) { } function FingerGestures_OnPinchEnd( fingerPos1 : Vector2, fingerPos2 : Vector2 ) { } function FingerGestures_OnRotationBegin( fingerPos1 : Vector2, fingerPos2 : Vector2 ) { } function FingerGestures_OnRotationMove( fingerPos1 : Vector2, fingerPos2 : Vector2, rotationAngleDelta : float ) { } function FingerGestures_OnRotationEnd( fingerPos1 : Vector2, fingerPos2 : Vector2, totalRotationAngle : float ) { } function FingerGestures_OnTwoFingerLongPress( fingerPos : Vector2 ) { } function FingerGestures_OnTwoFingerTap( fingerPos : Vector2, tapCount : int ) { } function FingerGestures_OnTwoFingerSwipe( startPos : Vector2, direction : FingerGestures.SwipeDirection, velocity : float ) { } function FingerGestures_OnTwoFingerDragBegin( fingerPos : Vector2, startPos : Vector2 ) { } function FingerGestures_OnTwoFingerDragMove( fingerPos : Vector2, delta : Vector2 ) { } function FingerGestures_OnTwoFingerDragEnd( fingerPos : Vector2 ) { }
zzzstrawhatzzz
trunk/client/Assets/FingerGestures/SkeletonCode/JavascriptSkeleton.js
JavaScript
asf20
8,469
using UnityEngine; using System.Collections; /// <summary> /// This sample demonstrates the use of various toolbox scripts to replicate the functionalities of /// the original sample, with almost no coding required this time around! /// /// This sample uses the following Toolbox scripts: /// - TBLongPress /// - TBTap /// - TBDrag /// - TBSwipe /// </summary> public class ToolboxOneFingerGestureSample : SampleBase { #region Properties exposed to the editor #endregion #region Misc protected override string GetHelpText() { return @"This sample demonstrates the use of various toolbox scripts to replicate the functionalities of the original sample, with almost no coding required this time around!"; } #endregion }
zzzstrawhatzzz
trunk/client/Assets/FingerGestures/Samples/Scripts/ToolboxOneFingerGestureSample.cs
C#
asf20
789
var textField : TextMesh; function OnEnable() { // register to finger down event FingerGestures.OnFingerDown += FingerGestures_OnFingerDown; } function OnDisable() { // unregister from finger down event FingerGestures.OnFingerDown -= FingerGestures_OnFingerDown; } function FingerGestures_OnFingerDown( fingerIndex : int, fingerPos : Vector2 ) { var obj : GameObject = PickObject( fingerPos ); if( obj ) DisplayText( "You pressed " + obj.name ); else DisplayText( "You didn't pressed any object" ); } function DisplayText( text ) { if( textField ) textField.text = text; else Debug.Log( text ); } function PickObject( screenPos : Vector2 ) : GameObject { var ray : Ray = Camera.main.ScreenPointToRay( screenPos ); var hit : RaycastHit; if( Physics.Raycast( ray, hit ) ) return hit.collider.gameObject; return null; }
zzzstrawhatzzz
trunk/client/Assets/FingerGestures/Samples/Scripts/TapToPickObject.js
JavaScript
asf20
959
using UnityEngine; using System.Collections; /// <summary> /// This sample demonstrates the use of the Toolbox's Drag & Drop scripts /// </summary> public class ToolboxDragDropSample : SampleBase { #region Properties exposed to the editor public TBInputManager inputMgr; public Transform[] dragObjects; public Collider dragSphere; public Collider dragPlane; public Light pointlight; #endregion #region Drag Plane Mode enum DragPlaneMode { XY, Plane, Sphere } DragPlaneMode dragPlaneMode = DragPlaneMode.XY; void SetDragPlaneMode( DragPlaneMode mode ) { switch( mode ) { case DragPlaneMode.XY: RestoreInitialPositions(); dragSphere.gameObject.active = false; dragPlane.gameObject.active = false; inputMgr.dragPlaneType = TBInputManager.DragPlaneType.XY; break; case DragPlaneMode.Plane: RestoreInitialPositions(); dragSphere.gameObject.active = false; dragPlane.gameObject.active = true; inputMgr.dragPlaneCollider = dragPlane; inputMgr.dragPlaneType = TBInputManager.DragPlaneType.UseCollider; break; case DragPlaneMode.Sphere: RestoreInitialPositions(); dragSphere.gameObject.active = true; dragPlane.gameObject.active = false; inputMgr.dragPlaneCollider = dragSphere; inputMgr.dragPlaneType = TBInputManager.DragPlaneType.UseCollider; break; } dragPlaneMode = mode; } #endregion #region Initial positions save / restore Vector3[] initialPositions; void SaveInitialPositions() { initialPositions = new Vector3[dragObjects.Length]; for( int i = 0; i < initialPositions.Length; ++i ) initialPositions[i] = dragObjects[i].position; } void RestoreInitialPositions() { for( int i = 0; i < initialPositions.Length; ++i ) dragObjects[i].position = initialPositions[i]; } #endregion #region Setup protected override string GetHelpText() { return @"This sample demonstrates the use of the Toolbox's Drag & Drop scripts"; } protected override void Start() { base.Start(); SaveInitialPositions(); SetDragPlaneMode( DragPlaneMode.XY ); } #endregion #region GUI public Rect dragModeButtonRect; void OnGUI() { if( UI.showHelp ) return; SampleUI.ApplyVirtualScreen(); string buttonText; DragPlaneMode nextDragPlaneMode; switch( dragPlaneMode ) { case DragPlaneMode.Plane: buttonText = "Drag On Plane"; nextDragPlaneMode = DragPlaneMode.Sphere; break; case DragPlaneMode.Sphere: buttonText = "Drag On Sphere"; nextDragPlaneMode = DragPlaneMode.XY; break; default: buttonText = "Drag On XZ"; nextDragPlaneMode = DragPlaneMode.Plane; break; } if( GUI.Button( dragModeButtonRect, buttonText ) ) SetDragPlaneMode( nextDragPlaneMode ); } #endregion void ToggleLight() { pointlight.enabled = !pointlight.enabled; } }
zzzstrawhatzzz
trunk/client/Assets/FingerGestures/Samples/Scripts/ToolboxDragDropSample.cs
C#
asf20
3,673
using UnityEngine; using System.Collections; /// <summary> /// This sample demonstrates uses the following Toolbox scripts: /// - TBFingerDown /// - TBFingerUp /// </summary> public class ToolboxFingerEventsSample : SampleBase { #region Properties exposed to the editor public Light light1; public Light light2; #endregion // this is called by TBFingerDown message void ToggleLight1() { light1.enabled = !light1.enabled; } // this is called by TBFingerUp message void ToggleLight2() { light2.enabled = !light2.enabled; } #region Misc protected override string GetHelpText() { return @"This sample demonstrates the use of the toolbox scripts TBFingerDown and TBFingerUp. It also shows how you can use the message target property to turn the light on & off."; } #endregion }
zzzstrawhatzzz
trunk/client/Assets/FingerGestures/Samples/Scripts/ToolboxFingerEventsSample.cs
C#
asf20
911
using UnityEngine; using System.Collections; // iphone3 480 x 320 // iphone4 960 x 640 public class SampleUI : MonoBehaviour { public GUISkin skin; public Color titleColor = Color.white; GUIStyle titleStyle; GUIStyle statusStyle; GUIStyle helpStyle; Rect topBarRect = new Rect( 0, -4, 600, 56 ); Rect backButtonRect = new Rect( 5, 2, 80, 46 ); Rect titleRect = new Rect( 100, 2, 400, 46 ); Rect helpButtonRect = new Rect( 515, 2, 80, 46 ); Rect statusTextRect = new Rect( 30, 336, 540, 60 ); Rect helpRect = new Rect( 50, 60, 500, 300 ); string statusText = "";//"status text goes here"; public string StatusText { get { return statusText; } set { statusText = value; } } public bool showStatusText = true; public string helpText = ""; public bool showHelpButton = true; public bool showHelp = false; void Awake() { titleStyle = new GUIStyle( skin.label ); titleStyle.alignment = TextAnchor.MiddleCenter; titleStyle.normal.textColor = titleColor; statusStyle = new GUIStyle( skin.label ); statusStyle.alignment = TextAnchor.LowerCenter; helpStyle = new GUIStyle( skin.label ); helpStyle.alignment = TextAnchor.UpperLeft; helpStyle.padding.left = 5; helpStyle.padding.right = 5; } #region Virtual Screen for automatic UI resolution scaling public static readonly float VirtualScreenWidth = 600; public static readonly float VirtualScreenHeight = 400; public static void ApplyVirtualScreen() { // resolution scaling matrix GUI.matrix = Matrix4x4.Scale( new Vector3( Screen.width / VirtualScreenWidth, Screen.height / VirtualScreenHeight, 1 ) ); } #endregion protected virtual void OnGUI() { if( skin != null ) GUI.skin = skin; ApplyVirtualScreen(); GUI.Box( topBarRect, "" ); if( GUI.Button( backButtonRect, "Back" ) ) Application.LoadLevel( "start" ); GUI.Label( titleRect, "FingerGestures - " + this.name, titleStyle ); if( showStatusText ) GUI.Label( statusTextRect, statusText, statusStyle ); if( helpText.Length > 0 && showHelpButton && !showHelp && GUI.Button( helpButtonRect, "Help" ) ) showHelp = true; if( showHelp ) { GUI.Box( helpRect, "Help" ); GUILayout.BeginArea( helpRect ); GUILayout.BeginVertical(); { GUILayout.Space( 25 ); GUILayout.Label( helpText, helpStyle ); GUILayout.FlexibleSpace(); if( GUILayout.Button( "Close", GUILayout.Height( 40 ) ) ) showHelp = false; } GUILayout.EndVertical(); GUILayout.EndArea(); } } }
zzzstrawhatzzz
trunk/client/Assets/FingerGestures/Samples/Scripts/Internal/SampleUI.cs
C#
asf20
3,005
using UnityEngine; using System.Collections; public class StartMenu : MonoBehaviour { public GUIStyle titleStyle; public GUIStyle buttonStyle; public float buttonHeight = 80; public Transform itemsTree; Transform currentMenuRoot; public Transform CurrentMenuRoot { get { return currentMenuRoot; } set { currentMenuRoot = value; } } // Use this for initialization void Start() { CurrentMenuRoot = itemsTree; } Rect screenRect = new Rect( 0, 0, SampleUI.VirtualScreenWidth, SampleUI.VirtualScreenHeight ); public float menuWidth = 450; public float sideBorder = 30; void OnGUI() { SampleUI.ApplyVirtualScreen(); GUILayout.BeginArea( screenRect ); GUILayout.BeginHorizontal(); GUILayout.Space( sideBorder ); if( CurrentMenuRoot ) { GUILayout.BeginVertical(); GUILayout.Space( 15 ); GUILayout.Label( CurrentMenuRoot.name, titleStyle ); for( int i = 0; i < CurrentMenuRoot.childCount; ++i ) { Transform item = CurrentMenuRoot.GetChild( i ); if( GUILayout.Button( item.name, GUILayout.Height( buttonHeight ) ) ) { MenuNode menuNode = item.GetComponent<MenuNode>(); if( menuNode && menuNode.sceneName != null && menuNode.sceneName.Length > 0 ) Application.LoadLevel( menuNode.sceneName ); else if( item.childCount > 0 ) CurrentMenuRoot = item; } GUILayout.Space( 5 ); } GUILayout.FlexibleSpace(); if( CurrentMenuRoot != itemsTree && CurrentMenuRoot.parent ) { if( GUILayout.Button( "<< BACK <<", GUILayout.Height( buttonHeight ) ) ) CurrentMenuRoot = CurrentMenuRoot.parent; GUILayout.Space( 15 ); } GUILayout.EndVertical(); } GUILayout.Space( sideBorder ); GUILayout.EndHorizontal(); GUILayout.EndArea(); } }
zzzstrawhatzzz
trunk/client/Assets/FingerGestures/Samples/Scripts/Internal/StartMenu.cs
C#
asf20
2,291
using UnityEngine; using System.Collections; public class BasicSample : SampleBase { public string helpText = "Help text here"; protected override string GetHelpText() { return helpText; } public string statusText = ""; protected override void Start() { base.Start(); UI.StatusText = statusText; } }
zzzstrawhatzzz
trunk/client/Assets/FingerGestures/Samples/Scripts/Internal/BasicSample.cs
C#
asf20
382
using UnityEngine; using System.Collections; public class EmitParticles : MonoBehaviour { public ParticleEmitter emitter; public Transform left; public Transform right; public Transform up; public Transform down; public void Emit() { emitter.Emit(); } public void EmitLeft() { emitter.transform.rotation = left.rotation; Emit(); } public void EmitRight() { emitter.transform.rotation = right.rotation; Emit(); } public void EmitUp() { emitter.transform.rotation = up.rotation; Emit(); } public void EmitDown() { emitter.transform.rotation = down.rotation; Emit(); } }
zzzstrawhatzzz
trunk/client/Assets/FingerGestures/Samples/Scripts/Internal/EmitParticles.cs
C#
asf20
767
using UnityEngine; using System.Collections; /// <summary> /// Base class for all sample scripts /// </summary> [RequireComponent( typeof( SampleUI ) )] public class SampleBase : MonoBehaviour { protected virtual string GetHelpText() { return ""; } // reference to the shared sample UI script SampleUI ui; public SampleUI UI { get { return ui; } } protected virtual void Awake() { ui = GetComponent<SampleUI>(); } protected virtual void Start() { ui.helpText = GetHelpText(); } #region Utils // Convert from screen-space coordinates to world-space coordinates on the Z = 0 plane public static Vector3 GetWorldPos( Vector2 screenPos ) { Ray ray = Camera.main.ScreenPointToRay( screenPos ); // we solve for intersection with z = 0 plane float t = -ray.origin.z / ray.direction.z; return ray.GetPoint( t ); } // Return the GameObject at the given screen position, or null if no valid object was found public static GameObject PickObject( Vector2 screenPos ) { Ray ray = Camera.main.ScreenPointToRay( screenPos ); RaycastHit hit; if( Physics.Raycast( ray, out hit ) ) return hit.collider.gameObject; return null; } #endregion }
zzzstrawhatzzz
trunk/client/Assets/FingerGestures/Samples/Scripts/Internal/SampleBase.cs
C#
asf20
1,398
using UnityEngine; using System.Collections; public class MenuNode : MonoBehaviour { public string sceneName; }
zzzstrawhatzzz
trunk/client/Assets/FingerGestures/Samples/Scripts/Internal/MenuNode.cs
C#
asf20
125
using UnityEngine; using System.Collections; public class SwipeParticlesEmitter : MonoBehaviour { public ParticleEmitter emitter; public float baseSpeed = 4.0f; public float swipeVelocityScale = 0.001f; void Start() { if( !emitter ) emitter = particleEmitter; emitter.emit = false; } public void Emit( FingerGestures.SwipeDirection direction, float swipeVelocity ) { Vector3 heading; // convert the swipe direction to a 3D vector we can use as our new forward direction for the particle emitter if( direction == FingerGestures.SwipeDirection.Up ) heading = Vector3.up; else if( direction == FingerGestures.SwipeDirection.Down ) heading = Vector3.down; else if( direction == FingerGestures.SwipeDirection.Right ) heading = Vector3.right; else heading = Vector3.left; // orient our emitter towards the swipe direction emitter.transform.rotation = Quaternion.LookRotation( heading ); Vector3 localEmitVelocity = emitter.localVelocity; localEmitVelocity.z = baseSpeed * swipeVelocityScale * swipeVelocity; emitter.localVelocity = localEmitVelocity; // fire away! emitter.Emit(); } }
zzzstrawhatzzz
trunk/client/Assets/FingerGestures/Samples/Scripts/Internal/SwipeParticlesEmitter.cs
C#
asf20
1,346
using UnityEngine; using System.Collections; public class DragTrail : MonoBehaviour { public LineRenderer lineRendererPrefab; LineRenderer lineRenderer; // Use this for initialization void Start() { lineRenderer = Instantiate( lineRendererPrefab, transform.position, transform.rotation ) as LineRenderer; lineRenderer.transform.parent = this.transform; lineRenderer.enabled = false; } // call triggered by the Draggable script void OnDragBegin() { // initialize the line renderer lineRenderer.enabled = true; lineRenderer.SetPosition( 0, transform.position ); lineRenderer.SetPosition( 1, transform.position ); // keep end point width in sync with object's current scale lineRenderer.SetWidth( 0.01f, transform.localScale.x ); } // call triggered by the Draggable script void OnDragEnd() { lineRenderer.enabled = false; } void Update() { if( lineRenderer.enabled ) { // update position of the line's end point lineRenderer.SetPosition( 1, transform.position ); } } }
zzzstrawhatzzz
trunk/client/Assets/FingerGestures/Samples/Scripts/Internal/DragTrail.cs
C#
asf20
1,075
using UnityEngine; using System.Collections; using System.Collections.Generic; public class MultiFingerSwipeSample : SampleBase { #region Properties exposed to the editor public SwipeGestureRecognizer swipeGesture; public GameObject sphereObject; public float baseEmitSpeed = 4.0f; public float swipeVelocityEmitSpeedScale = 0.001f; #endregion #region Misc protected override string GetHelpText() { return @"Swipe: press the yellow sphere with " + swipeGesture.RequiredFingerCount + " fingers and move them in one of the four cardinal directions, then release. The speed of the motion is taken into account."; } #endregion protected override void Start() { base.Start(); swipeGesture.OnSwipe += OnSwipe; } void OnSwipe( SwipeGestureRecognizer source ) { // make sure we started the swipe gesture on our swipe object GameObject selection = PickObject( source.StartPosition ); if( selection == sphereObject ) { UI.StatusText = "Swiped " + source.Direction + " with velocity: " + source.Velocity; SwipeParticlesEmitter emitter = selection.GetComponentInChildren<SwipeParticlesEmitter>(); if( emitter ) emitter.Emit( source.Direction, source.Velocity ); } } #region Utils // attempt to pick the scene object at the given finger position and compare it to the given requiredObject. // If it's this object spawn its particles. bool CheckSpawnParticles( Vector2 fingerPos, GameObject requiredObject ) { GameObject selection = PickObject( fingerPos ); if( !selection || selection != requiredObject ) return false; SpawnParticles( selection ); return true; } void SpawnParticles( GameObject obj ) { ParticleEmitter emitter = obj.GetComponentInChildren<ParticleEmitter>(); if( emitter ) emitter.Emit(); } #endregion }
zzzstrawhatzzz
trunk/client/Assets/FingerGestures/Samples/Scripts/MultiFingerSwipeSample.cs
C#
asf20
2,090
using UnityEngine; using System.Collections; /// <summary> /// This sample demonstrates how to use the two-fingers Pinch and Rotation gesture events to control the scale and orientation of a rectangle on the screen /// </summary> public class AdvancedPinchRotationSample : SampleBase { public PinchGestureRecognizer pinchGesture; public RotationGestureRecognizer rotationGesture; public Transform target; public Material rotationMaterial; public Material pinchMaterial; public Material pinchAndRotationMaterial; public float pinchScaleFactor = 0.02f; Material originalMaterial; protected override void Start() { base.Start(); UI.StatusText = "Use two fingers anywhere on the screen to rotate and scale the green object."; originalMaterial = target.renderer.sharedMaterial; pinchGesture.OnStateChanged += Gesture_OnStateChanged; pinchGesture.OnPinchMove += OnPinchMove; pinchGesture.SetCanBeginDelegate( CanBeginPinch ); rotationGesture.OnStateChanged += Gesture_OnStateChanged; rotationGesture.OnRotationMove += OnRotationMove; rotationGesture.SetCanBeginDelegate( CanBeginRotation ); } bool CanBeginRotation( GestureRecognizer gr, FingerGestures.IFingerList touches ) { return !pinchGesture.IsActive; } bool CanBeginPinch( GestureRecognizer gr, FingerGestures.IFingerList touches ) { return !rotationGesture.IsActive; } void Gesture_OnStateChanged( GestureRecognizer source ) { if( source.PreviousState == GestureRecognizer.GestureState.Ready && source.State == GestureRecognizer.GestureState.InProgress ) UI.StatusText = source + " gesture started"; else if( source.PreviousState == GestureRecognizer.GestureState.InProgress ) { if( source.State == GestureRecognizer.GestureState.Failed ) UI.StatusText = source + " gesture failed"; else if( source.State == GestureRecognizer.GestureState.Recognized ) UI.StatusText = source + " gesture ended"; } UpdateTargetMaterial(); } void OnPinchMove( PinchGestureRecognizer source ) { UI.StatusText = "Pinch updated by " + source.Delta + " degrees"; // change the scale of the target based on the pinch delta value target.transform.localScale += source.Delta * pinchScaleFactor * Vector3.one; } void OnRotationMove( RotationGestureRecognizer source ) { UI.StatusText = "Rotation updated by " + source.RotationDelta + " degrees"; // apply a rotation around the Z axis by rotationAngleDelta degrees on our target object target.Rotate( 0, 0, source.RotationDelta ); } #region Misc protected override string GetHelpText() { return @"This sample demonstrates advanced use of the GestureRecognizer classes for Pinch and Rotation"; } void UpdateTargetMaterial() { Material m; if( pinchGesture.IsActive && rotationGesture.IsActive ) m = pinchAndRotationMaterial; else if( pinchGesture.IsActive ) m = pinchMaterial; else if( rotationGesture.IsActive ) m = rotationMaterial; else m = originalMaterial; target.renderer.sharedMaterial = m; } #endregion }
zzzstrawhatzzz
trunk/client/Assets/FingerGestures/Samples/Scripts/AdvancedPinchRotationSample.cs
C#
asf20
3,504
using UnityEngine; using System.Collections; /// <summary> /// This sample demonstrates some of the supported one-finger gestures: /// - LongPress /// - Tap /// - Drag /// - Swipe /// </summary> public class OneFingerGestureSample : SampleBase { #region Properties exposed to the editor public GameObject longPressObject; public GameObject tapObject; public GameObject swipeObject; public GameObject dragObject; public int requiredTapCount = 2; #endregion #region Misc protected override string GetHelpText() { return @"This sample demonstrates some of the supported single-finger gestures: - Drag: press the red sphere and move your finger to drag it around - LongPress: keep your finger pressed on the cyan sphere for at least " + FingerGestures.Defaults.Fingers[0].LongPress.Duration + @" seconds - Tap: rapidly press & release the purple sphere - Swipe: press the yellow sphere and move your finger in one of the four cardinal directions, then release. The speed of the motion is taken into account."; } #endregion #region Gesture event registration/unregistration void OnEnable() { Debug.Log( "Registering finger gesture events from C# script" ); // register input events FingerGestures.OnFingerLongPress += FingerGestures_OnFingerLongPress; FingerGestures.OnFingerTap += FingerGestures_OnFingerTap; FingerGestures.OnFingerSwipe += FingerGestures_OnFingerSwipe; FingerGestures.OnFingerDragBegin += FingerGestures_OnFingerDragBegin; FingerGestures.OnFingerDragMove += FingerGestures_OnFingerDragMove; FingerGestures.OnFingerDragEnd += FingerGestures_OnFingerDragEnd; } void OnDisable() { // unregister finger gesture events FingerGestures.OnFingerLongPress -= FingerGestures_OnFingerLongPress; FingerGestures.OnFingerTap -= FingerGestures_OnFingerTap; FingerGestures.OnFingerSwipe -= FingerGestures_OnFingerSwipe; FingerGestures.OnFingerDragBegin -= FingerGestures_OnFingerDragBegin; FingerGestures.OnFingerDragMove -= FingerGestures_OnFingerDragMove; FingerGestures.OnFingerDragEnd -= FingerGestures_OnFingerDragEnd; } #endregion #region Reaction to gesture events void FingerGestures_OnFingerLongPress( int fingerIndex, Vector2 fingerPos ) { if( CheckSpawnParticles( fingerPos, longPressObject ) ) { UI.StatusText = "Performed a long-press with finger " + fingerIndex; } } void FingerGestures_OnFingerTap( int fingerIndex, Vector2 fingerPos, int tapCount ) { // spawn some particles when tapping the object at least requiredTapCount times if( tapCount >= requiredTapCount ) { Debug.Log( "Tapcount: " + tapCount ); if( CheckSpawnParticles( fingerPos, tapObject ) ) { UI.StatusText = "Tapped " + tapCount + " times with finger " + fingerIndex; } } } // spin the yellow cube when swipping it void FingerGestures_OnFingerSwipe( int fingerIndex, Vector2 startPos, FingerGestures.SwipeDirection direction, float velocity ) { // make sure we started the swipe gesture on our swipe object GameObject selection = PickObject( startPos ); if( selection == swipeObject ) { UI.StatusText = "Swiped " + direction + " with finger " + fingerIndex; SwipeParticlesEmitter emitter = selection.GetComponentInChildren<SwipeParticlesEmitter>(); if( emitter ) emitter.Emit( direction, velocity ); } } #region Drag & Drop Gesture int dragFingerIndex = -1; void FingerGestures_OnFingerDragBegin( int fingerIndex, Vector2 fingerPos, Vector2 startPos ) { // make sure we raycast from the initial finger position, not the current finger position (see remark about dragTreshold in comments) GameObject selection = PickObject( startPos ); if( selection == dragObject ) { UI.StatusText = "Started dragging with finger " + fingerIndex; // remember which finger is dragging dragObject dragFingerIndex = fingerIndex; // spawn some particles because it's cool. SpawnParticles( selection ); } } void FingerGestures_OnFingerDragMove( int fingerIndex, Vector2 fingerPos, Vector2 delta ) { // we make sure that this event comes from the finger that is dragging our dragObject if( fingerIndex == dragFingerIndex ) { // update the position by converting the current screen position of the finger to a world position on the Z = 0 plane dragObject.transform.position = GetWorldPos( fingerPos ); } } void FingerGestures_OnFingerDragEnd( int fingerIndex, Vector2 fingerPos ) { // we make sure that this event comes from the finger that is dragging our dragObject if( fingerIndex == dragFingerIndex ) { UI.StatusText = "Stopped dragging with finger " + fingerIndex; // reset our drag finger index dragFingerIndex = -1; // spawn some particles because it's cool. SpawnParticles( dragObject ); } } #endregion #endregion #region Utils // attempt to pick the scene object at the given finger position and compare it to the given requiredObject. // If it's this object spawn its particles. bool CheckSpawnParticles( Vector2 fingerPos, GameObject requiredObject ) { GameObject selection = PickObject( fingerPos ); if( !selection || selection != requiredObject ) return false; SpawnParticles( selection ); return true; } void SpawnParticles( GameObject obj ) { ParticleEmitter emitter = obj.GetComponentInChildren<ParticleEmitter>(); if( emitter ) emitter.Emit(); } #endregion }
zzzstrawhatzzz
trunk/client/Assets/FingerGestures/Samples/Scripts/OneFingerGestureSample.cs
C#
asf20
6,226
using UnityEngine; using System.Collections; /// <summary> /// This sample lets you visualize and understand the following finger input events: /// - OnFingerDown /// - OnFingerStationaryBegin /// - OnFingerStationary /// - OnFingerStationaryEnd /// - OnFingerUp /// </summary> public class FingerEventsSamplePart1 : SampleBase { #region Properties exposed to the editor public GameObject fingerDownObject; public GameObject fingerStationaryObject; public GameObject fingerUpObject; public float chargeDelay = 0.5f; public float chargeTime = 5.0f; public float minSationaryParticleEmissionCount = 5; public float maxSationaryParticleEmissionCount = 50; public Material stationaryMaterial; public int requiredTapCount = 2; #endregion #region Setup protected override string GetHelpText() { return @"This sample lets you visualize and understand the FingerDown, FingerStationary and FingerUp events. INSTRUCTIONS: - Press, hold and release the red and blue spheres - Press & hold the green sphere without moving for a few seconds"; } ParticleEmitter stationaryParticleEmitter; protected override void Start() { base.Start(); if( fingerStationaryObject ) stationaryParticleEmitter = fingerStationaryObject.GetComponentInChildren<ParticleEmitter>(); } void StopStationaryParticleEmitter() { stationaryParticleEmitter.emit = false; UI.StatusText = ""; } #endregion #region Gesture event registration/unregistration void OnEnable() { Debug.Log( "Registering finger gesture events from C# script" ); // register input events FingerGestures.OnFingerDown += FingerGestures_OnFingerDown; FingerGestures.OnFingerUp += FingerGestures_OnFingerUp; FingerGestures.OnFingerStationaryBegin += FingerGestures_OnFingerStationaryBegin; FingerGestures.OnFingerStationary += FingerGestures_OnFingerStationary; FingerGestures.OnFingerStationaryEnd += FingerGestures_OnFingerStationaryEnd; } void OnDisable() { // unregister finger gesture events FingerGestures.OnFingerDown -= FingerGestures_OnFingerDown; FingerGestures.OnFingerUp -= FingerGestures_OnFingerUp; FingerGestures.OnFingerStationaryBegin -= FingerGestures_OnFingerStationaryBegin; FingerGestures.OnFingerStationary -= FingerGestures_OnFingerStationary; FingerGestures.OnFingerStationaryEnd -= FingerGestures_OnFingerStationaryEnd; } #endregion #region Reaction to gesture events void FingerGestures_OnFingerDown( int fingerIndex, Vector2 fingerPos ) { CheckSpawnParticles( fingerPos, fingerDownObject ); } void FingerGestures_OnFingerUp( int fingerIndex, Vector2 fingerPos, float timeHeldDown ) { CheckSpawnParticles( fingerPos, fingerUpObject ); // this shows how to access a finger object using its index // The finger object contains useful information not available through the event arguments that you might want to use FingerGestures.Finger finger = FingerGestures.GetFinger( fingerIndex ); Debug.Log( "Finger was lifted up at " + finger.Position + " and moved " + finger.DistanceFromStart.ToString( "N0" ) + " pixels from its initial position at " + finger.StartPosition ); } #region Stationary events int stationaryFingerIndex = -1; Material originalMaterial; void FingerGestures_OnFingerStationaryBegin( int fingerIndex, Vector2 fingerPos ) { // skip if we're already holding another finger stationary on our object if( stationaryFingerIndex != -1 ) return; GameObject selection = PickObject( fingerPos ); if( selection == fingerStationaryObject ) { UI.StatusText = "Begin stationary on finger " + fingerIndex; // remember which finger we're using stationaryFingerIndex = fingerIndex; // remember the original material originalMaterial = selection.renderer.sharedMaterial; // change the material to show we've started the stationary state selection.renderer.sharedMaterial = stationaryMaterial; } } void FingerGestures_OnFingerStationary( int fingerIndex, Vector2 fingerPos, float elapsedTime ) { if( elapsedTime < chargeDelay ) return; GameObject selection = PickObject( fingerPos ); if( selection == fingerStationaryObject ) { // compute charge progress % (0 to 1) float chargePercent = Mathf.Clamp01( ( elapsedTime - chargeDelay ) / chargeTime ); // compute and apply new particle emission rate based on charge % float emissionRate = Mathf.Lerp( minSationaryParticleEmissionCount, maxSationaryParticleEmissionCount, chargePercent ); stationaryParticleEmitter.minEmission = emissionRate; stationaryParticleEmitter.maxEmission = emissionRate; // make sure the emitter is turned on stationaryParticleEmitter.emit = true; UI.StatusText = "Charge: " + ( 100 * chargePercent ).ToString( "N1" ) + "%"; } } void FingerGestures_OnFingerStationaryEnd( int fingerIndex, Vector2 fingerPos, float elapsedTime ) { if( fingerIndex == stationaryFingerIndex ) { UI.StatusText = "Stationary ended on finger " + fingerIndex + " - " + elapsedTime.ToString( "N1" ) + " seconds elapsed"; // turn off the stationary particle emitter when we begin to move the finger, as it's no longer stationary StopStationaryParticleEmitter(); // restore the original material fingerStationaryObject.renderer.sharedMaterial = originalMaterial; // reset our stationary finger index stationaryFingerIndex = -1; } } #endregion #endregion #region Utils // attempt to pick the scene object at the given finger position and compare it to the given requiredObject. // If it's this object spawn its particles. bool CheckSpawnParticles( Vector2 fingerPos, GameObject requiredObject ) { GameObject selection = PickObject( fingerPos ); if( !selection || selection != requiredObject ) return false; SpawnParticles( selection ); return true; } void SpawnParticles( GameObject obj ) { ParticleEmitter emitter = obj.GetComponentInChildren<ParticleEmitter>(); if( emitter ) emitter.Emit(); } #endregion }
zzzstrawhatzzz
trunk/client/Assets/FingerGestures/Samples/Scripts/FingerEventsSamplePart1.cs
C#
asf20
6,905
using UnityEngine; using System.Collections; /// <summary> /// This sample demonstrates how to use the two-fingers Pinch and Rotation gesture events to control the scale and orientation of a rectangle on the screen /// </summary> public class PinchRotationSample : SampleBase { public Transform target; public Material rotationMaterial; public Material pinchMaterial; public Material pinchAndRotationMaterial; public float pinchScaleFactor = 0.02f; Material originalMaterial; #region Input Mode public enum InputMode { PinchOnly, RotationOnly, PinchAndRotation } InputMode inputMode = InputMode.PinchAndRotation; #endregion #region Setup protected override string GetHelpText() { return @"This sample demonstrates how to use the two-fingers Pinch and Rotation gesture events to control the scale and orientation of a rectangle on the screen - Pinch: move two fingers closer or further apart to change the scale of the rectangle - Rotation: twist two fingers in a circular motion to rotate the rectangle "; } protected override void Start() { base.Start(); UI.StatusText = "Use two fingers anywhere on the screen to rotate and scale the green object."; originalMaterial = target.renderer.sharedMaterial; } #endregion #region Events registeration void OnEnable() { FingerGestures.OnRotationBegin += FingerGestures_OnRotationBegin; FingerGestures.OnRotationMove += FingerGestures_OnRotationMove; FingerGestures.OnRotationEnd += FingerGestures_OnRotationEnd; FingerGestures.OnPinchBegin += FingerGestures_OnPinchBegin; FingerGestures.OnPinchMove += FingerGestures_OnPinchMove; FingerGestures.OnPinchEnd += FingerGestures_OnPinchEnd; } void OnDisable() { FingerGestures.OnRotationBegin -= FingerGestures_OnRotationBegin; FingerGestures.OnRotationMove -= FingerGestures_OnRotationMove; FingerGestures.OnRotationEnd -= FingerGestures_OnRotationEnd; FingerGestures.OnPinchBegin -= FingerGestures_OnPinchBegin; FingerGestures.OnPinchMove -= FingerGestures_OnPinchMove; FingerGestures.OnPinchEnd -= FingerGestures_OnPinchEnd; } #endregion #region Rotation gesture bool rotating = false; bool Rotating { get { return rotating; } set { if( rotating != value ) { rotating = value; UpdateTargetMaterial(); } } } public bool RotationAllowed { get { return inputMode == InputMode.RotationOnly || inputMode == InputMode.PinchAndRotation; } } void FingerGestures_OnRotationBegin( Vector2 fingerPos1, Vector2 fingerPos2 ) { if( RotationAllowed ) { UI.StatusText = "Rotation gesture started."; Rotating = true; } } void FingerGestures_OnRotationMove( Vector2 fingerPos1, Vector2 fingerPos2, float rotationAngleDelta ) { if( Rotating ) { UI.StatusText = "Rotation updated by " + rotationAngleDelta + " degrees"; // apply a rotation around the Z axis by rotationAngleDelta degrees on our target object target.Rotate( 0, 0, rotationAngleDelta ); } } void FingerGestures_OnRotationEnd( Vector2 fingerPos1, Vector2 fingerPos2, float totalRotationAngle ) { if( Rotating ) { UI.StatusText = "Rotation gesture ended. Total rotation: " + totalRotationAngle; Rotating = false; } } #endregion #region Pinch Gesture bool pinching = false; bool Pinching { get { return pinching; } set { if( pinching != value ) { pinching = value; UpdateTargetMaterial(); } } } public bool PinchAllowed { get { return inputMode == InputMode.PinchOnly || inputMode == InputMode.PinchAndRotation; } } void FingerGestures_OnPinchBegin( Vector2 fingerPos1, Vector2 fingerPos2 ) { if( !PinchAllowed ) return; Pinching = true; } void FingerGestures_OnPinchMove( Vector2 fingerPos1, Vector2 fingerPos2, float delta ) { if( Pinching ) { // change the scale of the target based on the pinch delta value target.transform.localScale += delta * pinchScaleFactor * Vector3.one; } } void FingerGestures_OnPinchEnd( Vector2 fingerPos1, Vector2 fingerPos2 ) { if( Pinching ) { Pinching = false; } } #endregion #region Misc void UpdateTargetMaterial() { Material m; if( pinching && rotating ) m = pinchAndRotationMaterial; else if( pinching ) m = pinchMaterial; else if( rotating ) m = rotationMaterial; else m = originalMaterial; target.renderer.sharedMaterial = m; } #endregion #region GUI public Rect inputModeButtonRect; void OnGUI() { SampleUI.ApplyVirtualScreen(); string buttonText; InputMode nextInputMode; switch( inputMode ) { case InputMode.PinchOnly: buttonText = "Pinch Only"; nextInputMode = InputMode.RotationOnly; break; case InputMode.RotationOnly: buttonText = "Rotation Only"; nextInputMode = InputMode.PinchAndRotation; break; default: buttonText = "Pinch + Rotation"; nextInputMode = InputMode.PinchOnly; break; } if( GUI.Button( inputModeButtonRect, buttonText ) ) { inputMode = nextInputMode; } } #endregion }
zzzstrawhatzzz
trunk/client/Assets/FingerGestures/Samples/Scripts/PinchRotationSample.cs
C#
asf20
6,268
using UnityEngine; using System.Collections; /// <summary> /// This sample demonstrates some of the supported one-finger gestures: /// - TwoFingerLongPress /// - TwoFingerTap /// - TwoFingerDrag /// - TwoFingerSwipe /// </summary> public class TwoFingerGestureSample : SampleBase { #region Properties exposed to the editor public GameObject longPressObject; public GameObject tapObject; public GameObject swipeObject; public GameObject dragObject; public int requiredTapCount = 2; #endregion #region Misc protected override string GetHelpText() { return @"This sample demonstrates some of the supported two-finger gestures: - Drag: press the red sphere with two fingers and move them to drag the sphere around - LongPress: keep your two fingers pressed on the cyan sphere for at least " + FingerGestures.Defaults.Fingers[0].LongPress.Duration + @" seconds - Tap: rapidly press & release the purple sphere " + requiredTapCount + @" times with two fingers - Swipe: press the yellow sphere with two fingers and move them in one of the four cardinal directions, then release your fingers. The speed of the motion is taken into account."; } #endregion #region Gesture event registration/unregistration void OnEnable() { Debug.Log( "Registering finger gesture events from C# script" ); // register input events FingerGestures.OnTwoFingerLongPress += FingerGestures_OnTwoFingerLongPress; FingerGestures.OnTwoFingerTap += FingerGestures_OnTwoFingerTap; FingerGestures.OnTwoFingerSwipe += FingerGestures_OnTwoFingerSwipe; FingerGestures.OnTwoFingerDragBegin += FingerGestures_OnTwoFingerDragBegin; FingerGestures.OnTwoFingerDragMove += FingerGestures_OnTwoFingerDragMove; FingerGestures.OnTwoFingerDragEnd += FingerGestures_OnTwoFingerDragEnd; } void OnDisable() { // unregister finger gesture events FingerGestures.OnTwoFingerLongPress -= FingerGestures_OnTwoFingerLongPress; FingerGestures.OnTwoFingerTap -= FingerGestures_OnTwoFingerTap; FingerGestures.OnTwoFingerSwipe -= FingerGestures_OnTwoFingerSwipe; FingerGestures.OnTwoFingerDragBegin -= FingerGestures_OnTwoFingerDragBegin; FingerGestures.OnTwoFingerDragMove -= FingerGestures_OnTwoFingerDragMove; FingerGestures.OnTwoFingerDragEnd -= FingerGestures_OnTwoFingerDragEnd; } #endregion #region Reaction to gesture events void FingerGestures_OnTwoFingerLongPress( Vector2 fingerPos ) { if( CheckSpawnParticles( fingerPos, longPressObject ) ) { UI.StatusText = "Performed a two-finger long-press"; } } void FingerGestures_OnTwoFingerTap( Vector2 fingerPos, int tapCount ) { // spawn some particles when tapping the object at least requiredTapCount times if( tapCount == requiredTapCount ) { if( CheckSpawnParticles( fingerPos, tapObject ) ) { UI.StatusText = "Tapped " + requiredTapCount + " times with two fingers"; } } } // spin the yellow cube when swipping it void FingerGestures_OnTwoFingerSwipe( Vector2 startPos, FingerGestures.SwipeDirection direction, float velocity ) { // make sure we started the swipe gesture on our swipe object GameObject selection = PickObject( startPos ); if( selection == swipeObject ) { UI.StatusText = "Swiped " + direction + " with two fingers"; SwipeParticlesEmitter emitter = selection.GetComponentInChildren<SwipeParticlesEmitter>(); if( emitter ) emitter.Emit( direction, velocity ); } } #region Drag & Drop Gesture bool dragging = false; void FingerGestures_OnTwoFingerDragBegin( Vector2 fingerPos, Vector2 startPos ) { // make sure we raycast from the initial finger position, not the current finger position (see remark about dragTreshold in comments) GameObject selection = PickObject( startPos ); if( selection == dragObject ) { dragging = true; UI.StatusText = "Started dragging with two fingers"; // spawn some particles because it's cool. SpawnParticles( selection ); } } void FingerGestures_OnTwoFingerDragMove( Vector2 fingerPos, Vector2 delta ) { if( dragging ) { // update the position by converting the current screen position of the finger to a world position on the Z = 0 plane dragObject.transform.position = GetWorldPos( fingerPos ); } } void FingerGestures_OnTwoFingerDragEnd( Vector2 fingerPos ) { if( dragging ) { UI.StatusText = "Stopped dragging with two fingers"; // spawn some particles because it's cool. SpawnParticles( dragObject ); dragging = false; } } #endregion #endregion #region Utils // attempt to pick the scene object at the given finger position and compare it to the given requiredObject. // If it's this object spawn its particles. bool CheckSpawnParticles( Vector2 fingerPos, GameObject requiredObject ) { GameObject selection = PickObject( fingerPos ); if( !selection || selection != requiredObject ) return false; SpawnParticles( selection ); return true; } void SpawnParticles( GameObject obj ) { ParticleEmitter emitter = obj.GetComponentInChildren<ParticleEmitter>(); if( emitter ) emitter.Emit(); } #endregion }
zzzstrawhatzzz
trunk/client/Assets/FingerGestures/Samples/Scripts/TwoFingerGestureSample.cs
C#
asf20
5,912
var textField : TextMesh; function OnEnable() { // register to global single-finger tap event FingerGestures.OnFingerDown += FingerGestures_OnFingerDown; } function OnDisable() { // unregister from global single-finger tap event FingerGestures.OnFingerDown -= FingerGestures_OnFingerDown; } function FingerGestures_OnFingerDown( fingerIndex : int, fingerPos : Vector2 ) { var obj : GameObject = PickObject( fingerPos ); if( obj ) DisplayText( "You pressed " + obj.name ); else DisplayText( "You didn't pressed any object" ); } function DisplayText( text ) { if( textField ) textField.text = text; else Debug.Log( text ); } function PickObject( screenPos : Vector2 ) : GameObject { var ray : Ray = Camera.main.ScreenPointToRay( screenPos ); var hit : RaycastHit; if( Physics.Raycast( ray, hit ) ) return hit.collider.gameObject; return null; }
zzzstrawhatzzz
trunk/client/Assets/FingerGestures/Samples/Scripts/PickObject.js
JavaScript
asf20
985
using UnityEngine; using System.Collections; using System.Collections.Generic; /// <summary> /// This sample helps visualize the following finger events: /// - OnFingerDown /// - OnFingerMoveBegin /// - OnFingerMove /// - OnFingerMoveEnd /// - OnFingerUp /// </summary> public class FingerEventsSamplePart2 : SampleBase { #region Properties exposed to the editor public LineRenderer lineRendererPrefab; public GameObject fingerDownMarkerPrefab; public GameObject fingerMoveBeginMarkerPrefab; public GameObject fingerMoveEndMarkerPrefab; public GameObject fingerUpMarkerPrefab; #endregion #region Utility class that represent a single finger path class PathRenderer { LineRenderer lineRenderer; // passage points List<Vector3> points = new List<Vector3>(); // list of marker objects currently instantiated List<GameObject> markers = new List<GameObject>(); public PathRenderer( int index, LineRenderer lineRendererPrefab ) { lineRenderer = Instantiate( lineRendererPrefab ) as LineRenderer; lineRenderer.name = lineRendererPrefab.name + index; lineRenderer.enabled = true; UpdateLines(); } public void Reset() { points.Clear(); UpdateLines(); // destroy markers foreach( GameObject marker in markers ) Destroy( marker ); markers.Clear(); } public void AddPoint( Vector2 screenPos ) { AddPoint( screenPos, null ); } public void AddPoint( Vector2 screenPos, GameObject markerPrefab ) { Vector3 pos = SampleBase.GetWorldPos( screenPos ); if( markerPrefab ) AddMarker( pos, markerPrefab ); points.Add( pos ); UpdateLines(); } GameObject AddMarker( Vector2 pos, GameObject prefab ) { GameObject instance = Instantiate( prefab, pos, Quaternion.identity ) as GameObject; instance.name = prefab.name + "(" + markers.Count + ")"; markers.Add( instance ); return instance; } void UpdateLines() { lineRenderer.SetVertexCount( points.Count ); for( int i = 0; i < points.Count; ++i ) lineRenderer.SetPosition( i, points[i] ); } } #endregion // one PathRenderer per finger PathRenderer[] paths; #region Setup protected override void Start() { base.Start(); UI.StatusText = "Drag your fingers anywhere on the screen"; // create one PathRenderer per finger paths = new PathRenderer[FingerGestures.Instance.MaxFingers]; for( int i = 0; i < paths.Length; ++i ) paths[i] = new PathRenderer( i, lineRendererPrefab ); } protected override string GetHelpText() { return @"This sample lets you visualize the FingerDown, FingerMoveBegin, FingerMove, FingerMoveEnd and FingerUp events. INSTRUCTIONS: Move your finger accross the screen and observe what happens. LEGEND: - Red Circle = FingerDown position - Yellow Square = FingerMoveBegin position - Green Sphere = FingerMoveEnd position - Blue Circle = FingerUp position"; } #endregion #region Gesture event registration/unregistration void OnEnable() { Debug.Log( "Registering finger gesture events from C# script" ); // register input events FingerGestures.OnFingerDown += FingerGestures_OnFingerDown; FingerGestures.OnFingerUp += FingerGestures_OnFingerUp; FingerGestures.OnFingerMoveBegin += FingerGestures_OnFingerMoveBegin; FingerGestures.OnFingerMove += FingerGestures_OnFingerMove; FingerGestures.OnFingerMoveEnd += FingerGestures_OnFingerMoveEnd; } void OnDisable() { // unregister finger gesture events FingerGestures.OnFingerDown -= FingerGestures_OnFingerDown; FingerGestures.OnFingerUp -= FingerGestures_OnFingerUp; FingerGestures.OnFingerMoveBegin -= FingerGestures_OnFingerMoveBegin; FingerGestures.OnFingerMove -= FingerGestures_OnFingerMove; FingerGestures.OnFingerMoveEnd -= FingerGestures_OnFingerMoveEnd; } #endregion #region Reaction to finger events void FingerGestures_OnFingerDown( int fingerIndex, Vector2 fingerPos ) { PathRenderer path = paths[fingerIndex]; path.Reset(); path.AddPoint( fingerPos, fingerDownMarkerPrefab ); } void FingerGestures_OnFingerUp( int fingerIndex, Vector2 fingerPos, float timeHeldDown ) { PathRenderer path = paths[fingerIndex]; path.AddPoint( fingerPos, fingerUpMarkerPrefab ); UI.StatusText = "Finger " + fingerIndex + " was held down for " + timeHeldDown.ToString( "N2" ) + " seconds"; } void FingerGestures_OnFingerMoveBegin( int fingerIndex, Vector2 fingerPos ) { UI.StatusText = "Started moving finger " + fingerIndex; PathRenderer path = paths[fingerIndex]; path.AddPoint( fingerPos, fingerMoveBeginMarkerPrefab ); } void FingerGestures_OnFingerMove( int fingerIndex, Vector2 fingerPos ) { PathRenderer path = paths[fingerIndex]; path.AddPoint( fingerPos ); } void FingerGestures_OnFingerMoveEnd( int fingerIndex, Vector2 fingerPos ) { UI.StatusText = "Stopped moving finger " + fingerIndex; PathRenderer path = paths[fingerIndex]; path.AddPoint( fingerPos, fingerMoveEndMarkerPrefab ); } #endregion #region Utils // attempt to pick the scene object at the given finger position and compare it to the given requiredObject. // If it's this object spawn its particles. bool CheckSpawnParticles( Vector2 fingerPos, GameObject requiredObject ) { GameObject selection = PickObject( fingerPos ); if( !selection || selection != requiredObject ) return false; SpawnParticles( selection ); return true; } void SpawnParticles( GameObject obj ) { ParticleEmitter emitter = obj.GetComponentInChildren<ParticleEmitter>(); if( emitter ) emitter.Emit(); } #endregion }
zzzstrawhatzzz
trunk/client/Assets/FingerGestures/Samples/Scripts/FingerEventsSamplePart2.cs
C#
asf20
6,575
using UnityEngine; using System.Collections; public class TouchPhaseVisualizer : MonoBehaviour { public Rect rectLabel = new Rect( 50, 50, 200, 200 ); bool touchDown = false; TouchPhase phase = TouchPhase.Canceled; public TouchPhase Phase { get { return phase; } set { if( phase != value ) { Debug.Log( "Phase transition: " + phase + " -> " + value ); phase = value; } } } // Update is called once per frame void Update() { touchDown = Input.touchCount > 0; if( touchDown ) { Phase = Input.touches[0].phase; } } void OnGUI() { if( touchDown ) GUI.Label( rectLabel, Phase.ToString() ); else GUI.Label( rectLabel, "N/A" ); } }
zzzstrawhatzzz
trunk/client/Assets/FingerGestures/Samples/TouchPhaseVisualizer.cs
C#
asf20
911
using UnityEngine; using System.Collections; /// <summary> /// Toolbox InputManager /// /// This class acts as a HUB/manager for the various input gesture events. It dispatches calls to the various TB* classes, /// such as TBDrag, TBTap, etc... There should be exactly one instance of this class in the scene. /// /// The set of toolbox scripts currently supports: /// - FingerDown /// - FingerUp /// - Drag & Drop /// - Tap /// - Long-Press /// - Swipe /// /// Please check the ToolboxDragDrop sample scenes for a solid example on how to use this system. /// /// - Drag & Drop Implementation Details - /// This class listens to the FingerGestures.OnFingerDragBegin event and raycasts into the scene at the given finger position /// in order to find a valid object equipped with a TBDrag component. If it finds one, it calls TBDrag.BeginDrag() on this object, /// and starts listening to TBDrag.OnDragMove and TBDrag.OnDragEnd. The TBDrag object position is updated in dragged_OnDragMove. /// </summary> [AddComponentMenu( "FingerGestures/Toolbox/Input Manager" )] public class TBInputManager : MonoBehaviour { // changing these at runtime wont have any effect unless you disable and re-enable the Input Manager public bool trackFingerUp = true; public bool trackFingerDown = true; public bool trackDrag = true; public bool trackTap = true; public bool trackLongPress = true; public bool trackSwipe = true; public Camera raycastCamera; // which camera to fire the raycats through. If set to null, this will default to the main camera public LayerMask ignoreLayers = 0; // layers to ignore when doing the pick raycasts void Start() { if( !raycastCamera ) raycastCamera = Camera.main; } void OnEnable() { // subscribe to the FingerGestures events if( trackFingerDown ) FingerGestures.OnFingerDown += FingerGestures_OnFingerDown; if( trackFingerUp ) FingerGestures.OnFingerUp += FingerGestures_OnFingerUp; if( trackDrag ) FingerGestures.OnFingerDragBegin += FingerGestures_OnFingerDragBegin; if( trackTap ) FingerGestures.OnFingerTap += FingerGestures_OnFingerTap; if( trackLongPress) FingerGestures.OnFingerLongPress += FingerGestures_OnFingerLongPress; if( trackSwipe ) FingerGestures.OnFingerSwipe += FingerGestures_OnFingerSwipe; } void OnDisable() { // unsubscribe to FingerGestures events FingerGestures.OnFingerDown -= FingerGestures_OnFingerDown; FingerGestures.OnFingerUp -= FingerGestures_OnFingerUp; FingerGestures.OnFingerDragBegin -= FingerGestures_OnFingerDragBegin; FingerGestures.OnFingerTap -= FingerGestures_OnFingerTap; FingerGestures.OnFingerLongPress -= FingerGestures_OnFingerLongPress; FingerGestures.OnFingerSwipe -= FingerGestures_OnFingerSwipe; } #region Fingers Input Events void FingerGestures_OnFingerUp( int fingerIndex, Vector2 fingerPos, float timeHeldDown ) { TBFingerUp fingerUpComp = PickComponent<TBFingerUp>( fingerPos ); if( fingerUpComp ) fingerUpComp.RaiseFingerUp( fingerIndex, fingerPos, timeHeldDown ); } void FingerGestures_OnFingerDown( int fingerIndex, Vector2 fingerPos ) { TBFingerDown fingerDownComp = PickComponent<TBFingerDown>( fingerPos ); if( fingerDownComp ) fingerDownComp.RaiseFingerDown( fingerIndex, fingerPos ); } #endregion #region Drag & Drop public enum DragPlaneType { XY, // drag along the absolute XY plane (regular view) XZ, // drag along the absolute XZ plane (topdown view) ZY, // drag along the absolute ZY plane (side view) UseCollider, // project on the collider specified by dragPlaneCollider Camera, // drag along a plane parallal to the camera's screen plane (XY) } public DragPlaneType dragPlaneType = DragPlaneType.Camera; // current drag plane type used to convert the 2d finger position to a 3d world position public Collider dragPlaneCollider; // collider used when dragPlaneType is set to DragPlaneType.UseCollider public float dragPlaneOffset = 0.0f; // distance between dragged object and drag constraint plane void FingerGestures_OnFingerDragBegin( int fingerIndex, Vector2 fingerPos, Vector2 startPos ) { // check if the object is draggable TBDrag draggable = PickComponent<TBDrag>( startPos ); if( draggable && !draggable.Dragging ) { // initiate the drag operation draggable.BeginDrag( fingerIndex, fingerPos ); // register to the drag move & end events so we can update this object's position and unsubscribe to these events when done. draggable.OnDragMove += draggable_OnDragMove; draggable.OnDragEnd += draggable_OnDragEnd; } } // converts a screen-space position to a world-space position constrained to the current drag plane type // returns false if it was unable to get a valid world-space position bool ProjectScreenPointOnDragPlane( Vector3 refPos, Vector2 screenPos, out Vector3 worldPos ) { worldPos = refPos; switch( dragPlaneType ) { case DragPlaneType.XY: worldPos = raycastCamera.ScreenToWorldPoint( new Vector3( screenPos.x, screenPos.y, Mathf.Abs( refPos.z - raycastCamera.transform.position.z ) ) ); return true; case DragPlaneType.XZ: worldPos = raycastCamera.ScreenToWorldPoint( new Vector3( screenPos.x, screenPos.y, Mathf.Abs( refPos.y - raycastCamera.transform.position.y ) ) ); return true; case DragPlaneType.ZY: worldPos = raycastCamera.ScreenToWorldPoint( new Vector3( screenPos.x, screenPos.y, Mathf.Abs( refPos.x - raycastCamera.transform.position.x ) ) ); return true; case DragPlaneType.UseCollider: { Ray ray = raycastCamera.ScreenPointToRay( screenPos ); RaycastHit hit; if( !dragPlaneCollider.Raycast( ray, out hit, float.MaxValue ) ) return false; worldPos = hit.point + dragPlaneOffset * hit.normal; } return true; case DragPlaneType.Camera: { Transform camTransform = raycastCamera.transform; // create a plane passing through refPos and facing toward the camera Plane plane = new Plane( -camTransform.forward, refPos ); Ray ray = raycastCamera.ScreenPointToRay( screenPos ); float t = 0; if( !plane.Raycast( ray, out t ) ) return false; worldPos = ray.GetPoint( t ); } return true; } return false; } // one of the fingers holding a draggable object is moving. // Update the dragged object position accordingly. void draggable_OnDragMove( TBDrag sender ) { // figure out our previous screen space finger position Vector2 prevFingerPos = sender.FingerPos - sender.MoveDelta; Vector3 fingerPos3d, prevFingerPos3d; // convert these to world-space coordinates, and compute the amount of motion we need to apply to the object if( ProjectScreenPointOnDragPlane( sender.transform.position, prevFingerPos, out prevFingerPos3d ) && ProjectScreenPointOnDragPlane( sender.transform.position, sender.FingerPos, out fingerPos3d ) ) { Vector3 move = fingerPos3d - prevFingerPos3d; sender.transform.position += move; } } void draggable_OnDragEnd( TBDrag source ) { // unsubscribe from this object's drag events source.OnDragMove -= draggable_OnDragMove; source.OnDragEnd -= draggable_OnDragEnd; } #endregion #region Tap void FingerGestures_OnFingerTap( int fingerIndex, Vector2 fingerPos, int tapCount ) { TBTap tapComp = PickComponent<TBTap>( fingerPos ); if( tapComp ) tapComp.RaiseTap( fingerIndex, fingerPos, tapCount ); } #endregion #region LongPress void FingerGestures_OnFingerLongPress( int fingerIndex, Vector2 fingerPos ) { TBLongPress longPressComp = PickComponent<TBLongPress>( fingerPos ); if( longPressComp ) longPressComp.RaiseLongPress( fingerIndex, fingerPos ); } #endregion #region Swipe void FingerGestures_OnFingerSwipe( int fingerIndex, Vector2 startPos, FingerGestures.SwipeDirection direction, float velocity ) { TBSwipe swipeComp = PickComponent<TBSwipe>( startPos ); if( swipeComp ) swipeComp.RaiseSwipe( fingerIndex, startPos, direction, velocity ); } #endregion #region Utils // Return the GameObject at the given screen position, or null if no valid object was found GameObject PickObject( Vector2 screenPos ) { Ray ray = Camera.main.ScreenPointToRay( screenPos ); RaycastHit hit; if( Physics.Raycast( ray, out hit, float.MaxValue, ~ignoreLayers ) ) return hit.collider.gameObject; return null; } T PickComponent<T>( Vector2 screenPos ) where T:TBComponent { GameObject go = PickObject( screenPos ); if( !go ) return null; return go.GetComponent<T>(); } #endregion }
zzzstrawhatzzz
trunk/client/Assets/FingerGestures/Toolbox/TBInputManager.cs
C#
asf20
10,026
using UnityEngine; using System.Collections; /// <summary> /// Adaptation of the standard MouseOrbit script to use the finger drag gesture to rotate the current object using /// the fingers/mouse around a target object /// NOTE: TBInputManager NOT required /// </summary> [AddComponentMenu( "FingerGestures/Toolbox/Misc/DragOrbit" )] public class TBDragOrbit : MonoBehaviour { public enum PanMode { Disabled, OneFinger, TwoFingers } /// <summary> /// The object to orbit around /// </summary> public Transform target; /// <summary> /// Initial camera distance to target /// </summary> public float initialDistance = 10.0f; /// <summary> /// Minimum distance between camera and target /// </summary> public float minDistance = 1.0f; /// <summary> /// Maximum distance between camera and target /// </summary> public float maxDistance = 20.0f; /// <summary> /// Affects horizontal rotation speed /// </summary> public float yawSensitivity = 80.0f; /// <summary> /// Affects vertical rotation speed /// </summary> public float pitchSensitivity = 80.0f; /// <summary> /// Keep pitch angle value between minPitch and maxPitch? /// </summary> public bool clampPitchAngle = true; public float minPitch = -20; public float maxPitch = 80; /// <summary> /// Allow the user to affect the orbit distance using the pinch zoom gesture /// </summary> public bool allowPinchZoom = true; /// <summary> /// Affects pinch zoom speed /// </summary> public float pinchZoomSensitivity = 2.0f; /// <summary> /// Use smooth camera motions? /// </summary> public bool smoothMotion = true; public float smoothZoomSpeed = 3.0f; public float smoothOrbitSpeed = 4.0f; /// <summary> /// Two-Finger camera panning. /// Panning will apply an offset to the pivot/camera target point /// </summary> public bool allowPanning = false; public bool invertPanningDirections = false; public float panningSensitivity = 1.0f; public Transform panningPlane; // reference transform used to apply the panning translation (using panningPlane.right and panningPlane.up vectors) public bool smoothPanning = true; public float smoothPanningSpeed = 8.0f; float lastPanTime = 0; float distance = 10.0f; float yaw = 0; float pitch = 0; float idealDistance = 0; float idealYaw = 0; float idealPitch = 0; Vector3 idealPanOffset = Vector3.zero; Vector3 panOffset = Vector3.zero; public float Distance { get { return distance; } } public float IdealDistance { get { return idealDistance; } set { idealDistance = Mathf.Clamp( value, minDistance, maxDistance ); } } public float Yaw { get { return yaw; } } public float IdealYaw { get { return idealYaw; } set { idealYaw = value; } } public float Pitch { get { return pitch; } } public float IdealPitch { get { return idealPitch; } set { idealPitch = clampPitchAngle ? ClampAngle( value, minPitch, maxPitch ) : value; } } public Vector3 IdealPanOffset { get { return idealPanOffset; } set { idealPanOffset = value; } } public Vector3 PanOffset { get { return panOffset; } } void Start() { if( !panningPlane ) panningPlane = this.transform; Vector3 angles = transform.eulerAngles; distance = IdealDistance = initialDistance; yaw = IdealYaw = angles.y; pitch = IdealPitch = angles.x; // Make the rigid body not change rotation if( rigidbody ) rigidbody.freezeRotation = true; Apply(); } void OnEnable() { FingerGestures.OnDragMove += FingerGestures_OnDragMove; FingerGestures.OnPinchMove += FingerGestures_OnPinchMove; FingerGestures.OnTwoFingerDragMove += FingerGestures_OnTwoFingerDragMove; } void OnDisable() { FingerGestures.OnDragMove -= FingerGestures_OnDragMove; FingerGestures.OnPinchMove -= FingerGestures_OnPinchMove; FingerGestures.OnTwoFingerDragMove -= FingerGestures_OnTwoFingerDragMove; } void FingerGestures_OnDragMove( Vector2 fingerPos, Vector2 delta ) { // if we panned recently, give a bit of time for all the fingers to lift off before we allow for one-finger drag if( Time.time - lastPanTime < 0.25f ) return; if( target ) { IdealYaw += delta.x * yawSensitivity * 0.02f; IdealPitch -= delta.y * pitchSensitivity * 0.02f; } } void FingerGestures_OnPinchMove( Vector2 fingerPos1, Vector2 fingerPos2, float delta ) { if( allowPinchZoom ) IdealDistance -= delta * pinchZoomSensitivity; } void FingerGestures_OnTwoFingerDragMove( Vector2 fingerPos, Vector2 delta ) { if( allowPanning ) { Vector3 move = -0.02f * panningSensitivity * ( panningPlane.right * delta.x + panningPlane.up * delta.y ); if( invertPanningDirections ) IdealPanOffset -= move; else IdealPanOffset += move; lastPanTime = Time.time; } } void Apply() { if( smoothMotion ) { distance = Mathf.Lerp( distance, IdealDistance, Time.deltaTime * smoothZoomSpeed ); yaw = Mathf.Lerp( yaw, IdealYaw, Time.deltaTime * smoothOrbitSpeed ); pitch = Mathf.Lerp( pitch, IdealPitch, Time.deltaTime * smoothOrbitSpeed ); } else { distance = IdealDistance; yaw = IdealYaw; pitch = IdealPitch; } if( smoothPanning ) panOffset = Vector3.Lerp( panOffset, idealPanOffset, Time.deltaTime * smoothPanningSpeed ); else panOffset = idealPanOffset; transform.rotation = Quaternion.Euler( pitch, yaw, 0 ); transform.position = ( target.position + panOffset ) - distance * transform.forward; } void LateUpdate() { Apply(); } static float ClampAngle( float angle, float min, float max ) { if( angle < -360 ) angle += 360; if( angle > 360 ) angle -= 360; return Mathf.Clamp( angle, min, max ); } // recenter the camera public void ResetPanning() { IdealPanOffset = Vector3.zero; } }
zzzstrawhatzzz
trunk/client/Assets/FingerGestures/Toolbox/Misc/TBDragOrbit.cs
C#
asf20
6,945
using UnityEngine; using System.Collections; /// <summary> /// Put this script on a Camera object to allow for pinch-zoom gesture. /// NOTE: this script does NOT require a TBInputManager instance to be present in the scene. /// </summary> [RequireComponent(typeof(Camera))] [AddComponentMenu( "FingerGestures/Toolbox/Misc/Pinch-Zoom" )] public class TBPinchZoom : MonoBehaviour { public enum ZoomMethod { // move the camera position forward/backward Position, // change the field of view of the camera, or projection size for orthographic cameras FOV, } public ZoomMethod zoomMethod = ZoomMethod.Position; public float zoomSpeed = 1.5f; public float minZoomAmount = 0; public float maxZoomAmount = 50; Vector3 defaultPos = Vector3.zero; public Vector3 DefaultPos { get { return defaultPos; } set { defaultPos = value; } } float defaultFov = 0; public float DefaultFov { get { return defaultFov; } set { defaultFov = value; } } float defaultOrthoSize = 0; public float DefaultOrthoSize { get { return defaultOrthoSize; } set { defaultOrthoSize = value; } } float zoomAmount = 0; public float ZoomAmount { get { return zoomAmount; } set { zoomAmount = Mathf.Clamp( value, minZoomAmount, maxZoomAmount ); switch( zoomMethod ) { case ZoomMethod.Position: transform.position = defaultPos + zoomAmount * transform.forward; break; case ZoomMethod.FOV: if( camera.orthographic ) camera.orthographicSize = Mathf.Max( defaultOrthoSize - zoomAmount, 0.1f ); else camera.fov = Mathf.Max( defaultFov - zoomAmount, 0.1f ); break; } } } void Start() { SetDefaults(); } public void SetDefaults() { DefaultPos = transform.position; DefaultFov = camera.fov; DefaultOrthoSize = camera.orthographicSize; } #region FingerGestures events void OnEnable() { FingerGestures.OnPinchMove += FingerGestures_OnPinchMove; } void OnDisable() { FingerGestures.OnPinchMove -= FingerGestures_OnPinchMove; } void FingerGestures_OnPinchMove( Vector2 fingerPos1, Vector2 fingerPos2, float delta ) { ZoomAmount += zoomSpeed * delta; } #endregion }
zzzstrawhatzzz
trunk/client/Assets/FingerGestures/Toolbox/Misc/TBPinchZoom.cs
C#
asf20
2,693
using UnityEngine; using System.Collections; /// <summary> /// ToolBox FingerDown Component /// Put this script on any 3D GameObject to detect when a finger has just been pressed on them /// </summary> [AddComponentMenu( "FingerGestures/Toolbox/FingerDown" )] public class TBFingerDown : TBComponent { public Message message = new Message( "OnFingerDown" ); public event EventHandler<TBFingerDown> OnFingerDown; public bool RaiseFingerDown( int fingerIndex, Vector2 fingerPos ) { FingerIndex = fingerIndex; FingerPos = fingerPos; if( OnFingerDown != null ) OnFingerDown( this ); Send( message ); return true; } }
zzzstrawhatzzz
trunk/client/Assets/FingerGestures/Toolbox/TBFingerDown.cs
C#
asf20
714
using UnityEngine; using System.Collections; /// <summary> /// Base class for all the TB* gesture components (TBDrag, TBTap, TBLongPress, TBSwipe...). /// Implements commonly use methods and data structures. /// /// NOTE: the GameObject must have a collider (it's used by the TBInputManager when raycasting into the scene to find the object under the finger). /// Currently, this won't work out of the box with GUIText objects, due to the way they are behind rendered (2D). It will work with a 3D TextMesh though. /// </summary> public abstract class TBComponent : MonoBehaviour { public delegate void EventHandler<T>( T sender ) where T : TBComponent; // index of finger that triggered the latest input event int fingerIndex = -1; public int FingerIndex { get { return fingerIndex; } protected set { fingerIndex = value; } } // finger screen position provided by the latest input event Vector2 fingerPos; public Vector2 FingerPos { get { return fingerPos; } protected set { fingerPos = value; } } // Use this for initialization protected virtual void Start() { if( !collider ) { Debug.LogError( this.name + " must have a valid collider." ); enabled = false; } } #region Message sending [System.Serializable] public class Message { public bool enabled = true; public string methodName = "MethodToCall"; public GameObject target = null; public Message() { } public Message( string methodName ) { this.methodName = methodName; } public Message( string methodName, bool enabled ) { this.enabled = enabled; this.methodName = methodName; } } protected bool Send( Message msg ) { if( !msg.enabled ) return false; GameObject target = msg.target; if( !target ) target = this.gameObject; target.SendMessage( msg.methodName, SendMessageOptions.DontRequireReceiver ); return true; } #endregion }
zzzstrawhatzzz
trunk/client/Assets/FingerGestures/Toolbox/TBComponent.cs
C#
asf20
2,231
using UnityEngine; using System.Collections; /// <summary> /// ToolBox LongPress Component /// /// Put this script on any 3D GameObject to detect when they are long-pressed /// </summary> [AddComponentMenu( "FingerGestures/Toolbox/LongPress" )] public class TBLongPress : TBComponent { public Message message = new Message( "OnLongPress" ); public event EventHandler<TBLongPress> OnLongPress; public bool RaiseLongPress( int fingerIndex, Vector2 fingerPos ) { FingerIndex = fingerIndex; FingerPos = fingerPos; if( OnLongPress != null ) OnLongPress( this ); Send( message ); return true; } }
zzzstrawhatzzz
trunk/client/Assets/FingerGestures/Toolbox/TBLongPress.cs
C#
asf20
700
using UnityEngine; using System.Collections; /// <summary> /// ToolBox Drag Component /// Put this script on any 3D GameObject that you want to drag around. /// </summary> [AddComponentMenu( "FingerGestures/Toolbox/Drag" )] public class TBDrag : TBComponent { public Message dragBeginMessage = new Message( "OnDragBegin" ); public Message dragMoveMessage = new Message( "OnDragMove", false ); public Message dragEndMessage = new Message( "OnDragEnd" ); public event EventHandler<TBDrag> OnDragBegin; public event EventHandler<TBDrag> OnDragMove; public event EventHandler<TBDrag> OnDragEnd; // are we being dragged? bool dragging = false; public bool Dragging { get { return dragging; } private set { if( dragging != value ) { dragging = value; if( dragging ) { // register to the drag events FingerGestures.OnFingerDragMove += FingerGestures_OnDragMove; FingerGestures.OnFingerDragEnd += FingerGestures_OnDragEnd; } else { // unregister from the drag events FingerGestures.OnFingerDragMove -= FingerGestures_OnDragMove; FingerGestures.OnFingerDragEnd -= FingerGestures_OnDragEnd; } } } } Vector2 moveDelta; public Vector2 MoveDelta { get { return moveDelta; } private set { moveDelta = value; } } public bool BeginDrag( int fingerIndex, Vector2 fingerPos ) { // already dragging if( Dragging ) return false; FingerIndex = fingerIndex; FingerPos = fingerPos; Dragging = true; if( OnDragBegin != null ) OnDragBegin( this ); // notify other components on this object that we've started the drag operation Send( dragBeginMessage ); return true; } public bool EndDrag() { if( !Dragging ) return false; if( OnDragEnd != null ) OnDragEnd( this ); // notify other components on this object that we've just finished the drag operation Send( dragEndMessage ); // reset Dragging = false; FingerIndex = -1; return true; } #region FingerGestures events void FingerGestures_OnDragMove( int fingerIndex, Vector2 fingerPos, Vector2 delta ) { if( Dragging && FingerIndex == fingerIndex ) { FingerPos = fingerPos; MoveDelta = delta; if( OnDragMove != null ) OnDragMove( this ); Send( dragMoveMessage ); } } void FingerGestures_OnDragEnd( int fingerIndex, Vector2 fingerPos ) { if( Dragging && FingerIndex == fingerIndex ) { FingerPos = fingerPos; EndDrag(); } } #endregion #region Unity callbacks void OnDisable() { // if this gets disabled while dragging, make sure we cancel the drag operation if( Dragging ) EndDrag(); } #endregion }
zzzstrawhatzzz
trunk/client/Assets/FingerGestures/Toolbox/TBDrag.cs
C#
asf20
3,369
using UnityEngine; using System.Collections; /// <summary> /// ToolBox FingerUp Component /// Put this script on any 3D GameObject to detect when a finger has just been lifted from them /// </summary> [AddComponentMenu( "FingerGestures/Toolbox/FingerUp" )] public class TBFingerUp : TBComponent { public Message message = new Message( "OnFingerUp" ); public event EventHandler<TBFingerUp> OnFingerUp; float timeHeldDown = 0; public float TimeHeldDown { get { return timeHeldDown; } private set { timeHeldDown = value; } } public bool RaiseFingerUp( int fingerIndex, Vector2 fingerPos, float timeHeldDown ) { FingerIndex = fingerIndex; FingerPos = fingerPos; TimeHeldDown = timeHeldDown; if( OnFingerUp != null ) OnFingerUp( this ); Send( message ); return true; } }
zzzstrawhatzzz
trunk/client/Assets/FingerGestures/Toolbox/TBFingerUp.cs
C#
asf20
916
using UnityEngine; using System.Collections; /// <summary> /// ToolBox Tap Component /// Put this script on any 3D GameObject to detect when they are tapped /// </summary> [AddComponentMenu( "FingerGestures/Toolbox/Tap" )] public class TBTap : TBComponent { // number of taps required to raise the event public int tapCount = 1; public Message message = new Message( "OnTap" ); public event EventHandler<TBTap> OnTap; public bool RaiseTap( int fingerIndex, Vector2 fingerPos, int tapCount ) { if( tapCount != this.tapCount ) return false; FingerIndex = fingerIndex; FingerPos = fingerPos; if( OnTap != null ) OnTap( this ); Send( message ); return true; } }
zzzstrawhatzzz
trunk/client/Assets/FingerGestures/Toolbox/TBTap.cs
C#
asf20
799
using UnityEngine; using System.Collections; /// <summary> /// ToolBox Swipe Component /// Put this script on any 3D GameObject to detect when they are swipped /// </summary> [AddComponentMenu( "FingerGestures/Toolbox/Swipe" )] public class TBSwipe : TBComponent { public bool swipeLeft = true; public bool swipeRight = true; public bool swipeUp = true; public bool swipeDown = true; public float minVelocity = 0; public Message swipeMessage = new Message( "OnSwipe" ); public Message swipeLeftMessage = new Message( "OnSwipeLeft", false ); public Message swipeRightMessage = new Message( "OnSwipeRight", false ); public Message swipeUpMessage = new Message( "OnSwipeUp", false ); public Message swipeDownMessage = new Message( "OnSwipeDown", false ); public event EventHandler<TBSwipe> OnSwipe; FingerGestures.SwipeDirection direction; public FingerGestures.SwipeDirection Direction { get { return direction; } protected set { direction = value; } } float velocity; public float Velocity { get { return velocity; } protected set { velocity = value; } } public bool IsValid( FingerGestures.SwipeDirection direction ) { if( direction == FingerGestures.SwipeDirection.Left ) return swipeLeft; if( direction == FingerGestures.SwipeDirection.Right ) return swipeRight; if( direction == FingerGestures.SwipeDirection.Up ) return swipeUp; if( direction == FingerGestures.SwipeDirection.Down ) return swipeDown; return false; } Message GetMessageForSwipeDirection( FingerGestures.SwipeDirection direction ) { if( direction == FingerGestures.SwipeDirection.Left ) return swipeLeftMessage; if( direction == FingerGestures.SwipeDirection.Right ) return swipeRightMessage; if( direction == FingerGestures.SwipeDirection.Up ) return swipeUpMessage; return swipeDownMessage; } public bool RaiseSwipe( int fingerIndex, Vector2 fingerPos, FingerGestures.SwipeDirection direction, float velocity ) { if( velocity < minVelocity ) return false; if( !IsValid( direction ) ) return false; FingerIndex = fingerIndex; FingerPos = fingerPos; Direction = direction; Velocity = velocity; if( OnSwipe != null ) OnSwipe( this ); Send( swipeMessage ); Send( GetMessageForSwipeDirection( direction ) ); return true; } }
zzzstrawhatzzz
trunk/client/Assets/FingerGestures/Toolbox/TBSwipe.cs
C#
asf20
2,734
//by Bob Berkebile : Pixelplacement : http://www.pixelplacement.com using UnityEngine; using UnityEditor; using System.Collections; [CustomEditor(typeof(iTweenPath))] public class iTweenPathEditor : Editor { iTweenPath _target; GUIStyle style = new GUIStyle(); public static int count = 0; void OnEnable(){ //i like bold handle labels since I'm getting old: style.fontStyle = FontStyle.Bold; style.normal.textColor = Color.white; _target = (iTweenPath)target; //lock in a default path name: if(!_target.initialized){ _target.initialized = true; _target.pathName = "New Path " + ++count; _target.initialName = _target.pathName; } } public override void OnInspectorGUI(){ //path name: EditorGUILayout.BeginHorizontal(); EditorGUILayout.PrefixLabel("Path Name"); _target.pathName = EditorGUILayout.TextField(_target.pathName); EditorGUILayout.EndHorizontal(); if(_target.pathName == ""){ _target.pathName = _target.initialName; } //path color: EditorGUILayout.BeginHorizontal(); EditorGUILayout.PrefixLabel("Path Color"); _target.pathColor = EditorGUILayout.ColorField(_target.pathColor); EditorGUILayout.EndHorizontal(); //exploration segment count control: EditorGUILayout.BeginHorizontal(); EditorGUILayout.PrefixLabel("Node Count"); _target.nodeCount = Mathf.Clamp(EditorGUILayout.IntSlider(_target.nodeCount, 0, 10), 2,100); EditorGUILayout.EndHorizontal(); //add node? if(_target.nodeCount > _target.nodes.Count){ for (int i = 0; i < _target.nodeCount - _target.nodes.Count; i++) { _target.nodes.Add(Vector3.zero); } } //remove node? if(_target.nodeCount < _target.nodes.Count){ if(EditorUtility.DisplayDialog("Remove path node?","Shortening the node list will permantently destory parts of your path. This operation cannot be undone.", "OK", "Cancel")){ int removeCount = _target.nodes.Count - _target.nodeCount; _target.nodes.RemoveRange(_target.nodes.Count-removeCount,removeCount); }else{ _target.nodeCount = _target.nodes.Count; } } //node display: EditorGUI.indentLevel = 4; for (int i = 0; i < _target.nodes.Count; i++) { _target.nodes[i] = EditorGUILayout.Vector3Field("Node " + (i+1), _target.nodes[i]); } //update and redraw: if(GUI.changed){ EditorUtility.SetDirty(_target); } } void OnSceneGUI(){ if(_target.enabled) { // dkoontz if(_target.nodes.Count > 0){ //allow path adjustment undo: Undo.SetSnapshotTarget(_target,"Adjust iTween Path"); //path begin and end labels: Handles.Label(_target.nodes[0], "'" + _target.pathName + "' Begin", style); Handles.Label(_target.nodes[_target.nodes.Count-1], "'" + _target.pathName + "' End", style); //node handle display: for (int i = 0; i < _target.nodes.Count; i++) { _target.nodes[i] = Handles.PositionHandle(_target.nodes[i], Quaternion.identity); } } } // dkoontz } }
zzzstrawhatzzz
trunk/client/Assets/iTweenEditor/Editor/iTweenPathEditor.cs
C#
asf20
2,961
// Copyright (c) 2009-2012 David Koontz // Please direct any bugs/comments/suggestions to david@koontzfamily.org // // Thanks to Gabriel Gheorghiu (gabison@gmail.com) for his code submission // that lead to the integration with the iTween visual path editor. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using UnityEditor; using UnityEngine; using System.Collections; using System.Collections.Generic; using System.IO; using System.Runtime.Serialization.Formatters.Binary; using System.Text; using System.Linq; [CustomEditor(typeof(iTweenEvent))] public class iTweenEventDataEditor : Editor { List<string> trueFalseOptions = new List<string>() {"True", "False"}; Dictionary<string, object> values; Dictionary<string, bool> propertiesEnabled = new Dictionary<string, bool>(); iTweenEvent.TweenType previousType; [MenuItem("Component/iTween/iTweenEvent")] static void AddiTweenEvent () { if(Selection.activeGameObject != null) { Selection.activeGameObject.AddComponent(typeof(iTweenEvent)); } } [MenuItem("Component/iTween/Prepare Visual Editor for Javascript Usage")] static void CopyFilesForJavascriptUsage() { if(Directory.Exists(Application.dataPath + "/iTweenEditor/Helper Classes")) { if(!Directory.Exists(Application.dataPath + "/Plugins")) { Directory.CreateDirectory(Application.dataPath + "/Plugins"); } if(!Directory.Exists(Application.dataPath + "/Plugins/iTweenEditor")) { Directory.CreateDirectory(Application.dataPath + "/Plugins/iTweenEditor"); } FileUtil.MoveFileOrDirectory(Application.dataPath + "/iTweenEditor/Helper Classes", Application.dataPath + "/Plugins/iTweenEditor/Helper Classes"); FileUtil.MoveFileOrDirectory(Application.dataPath + "/iTweenEditor/iTweenEvent.cs", Application.dataPath + "/Plugins/iTweenEvent.cs"); FileUtil.MoveFileOrDirectory(Application.dataPath + "/iTweenEditor/iTween.cs", Application.dataPath + "/Plugins/iTween.cs"); FileUtil.MoveFileOrDirectory(Application.dataPath + "/iTweenEditor/iTweenPath.cs", Application.dataPath + "/Plugins/iTweenPath.cs"); AssetDatabase.Refresh(); } else { EditorUtility.DisplayDialog("Can't move files", "Your files have already been moved", "Ok"); } } [MenuItem("Component/iTween/Donate to support the Visual Editor")] static void Donate() { Application.OpenURL("https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=WD3GQ6HHD257C"); } public void OnEnable() { var evt = (iTweenEvent)target; foreach(var key in EventParamMappings.mappings[evt.type].Keys) { propertiesEnabled[key] = false; } previousType = evt.type; if(!Directory.Exists(Application.dataPath + "/Gizmos")) { Directory.CreateDirectory(Application.dataPath + "/Gizmos"); } if(!File.Exists(Application.dataPath + "/Gizmos/iTweenIcon.tif")) { FileUtil.CopyFileOrDirectory(Application.dataPath + "/iTweenEditor/Gizmos/iTweenIcon.tif", Application.dataPath + "/Gizmos/iTweenIcon.tif"); } } public override void OnInspectorGUI() { var evt = (iTweenEvent)target; values = evt.Values; var keys = values.Keys.ToArray(); foreach(var key in keys) { propertiesEnabled[key] = true; if(typeof(Vector3OrTransform) == EventParamMappings.mappings[evt.type][key]) { var val = new Vector3OrTransform(); if(null == values[key] || typeof(Transform) == values[key].GetType()) { if(null == values[key]) { val.transform = null; } else { val.transform = (Transform)values[key]; } val.selected = Vector3OrTransform.transformSelected; } else if(typeof(Vector3) == values[key].GetType()) { val.vector = (Vector3)values[key]; val.selected = Vector3OrTransform.vector3Selected; } values[key] = val; } if(typeof(Vector3OrTransformArray) == EventParamMappings.mappings[evt.type][key]) { var val = new Vector3OrTransformArray(); if(null == values[key] || typeof(Transform[]) == values[key].GetType()) { if(null == values[key]) { val.transformArray = null; } else { val.transformArray = (Transform[])values[key]; } val.selected = Vector3OrTransformArray.transformSelected; } else if(typeof(Vector3[]) == values[key].GetType()) { val.vectorArray = (Vector3[])values[key]; val.selected = Vector3OrTransformArray.vector3Selected; } else if(typeof(string) == values[key].GetType()) { val.pathName = (string)values[key]; val.selected = Vector3OrTransformArray.iTweenPathSelected; } values[key] = val; } } GUILayout.Label(string.Format("iTween Event Editor v{0}", iTweenEvent.VERSION)); EditorGUILayout.Separator(); GUILayout.BeginHorizontal(); GUILayout.Label("Name"); evt.tweenName = EditorGUILayout.TextField(evt.tweenName); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); evt.showIconInInspector = GUILayout.Toggle(evt.showIconInInspector, " Show Icon In Scene"); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); evt.playAutomatically = GUILayout.Toggle(evt.playAutomatically, " Play Automatically"); GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); GUILayout.Label("Initial Start Delay (delay begins once the iTweenEvent is played)"); evt.delay = EditorGUILayout.FloatField(evt.delay); GUILayout.EndHorizontal(); EditorGUILayout.Separator(); GUILayout.BeginHorizontal(); GUILayout.Label("Event Type"); evt.type = (iTweenEvent.TweenType)EditorGUILayout.EnumPopup(evt.type); GUILayout.EndHorizontal(); if(evt.type != previousType) { foreach(var key in EventParamMappings.mappings[evt.type].Keys) { propertiesEnabled[key] = false; } evt.Values = new Dictionary<string, object>(); previousType = evt.type; return; } var properties = EventParamMappings.mappings[evt.type]; foreach(var pair in properties) { var key = pair.Key; GUILayout.BeginHorizontal(); if(EditorGUILayout.BeginToggleGroup(key, propertiesEnabled[key])) { propertiesEnabled[key] = true; GUILayout.BeginVertical(); if(typeof(string) == pair.Value) { values[key] = EditorGUILayout.TextField(values.ContainsKey(key) ? (string)values[key] : ""); } else if(typeof(float) == pair.Value) { values[key] = EditorGUILayout.FloatField(values.ContainsKey(key) ? (float)values[key] : 0); } else if(typeof(int) == pair.Value) { values[key] = EditorGUILayout.IntField(values.ContainsKey(key) ? (int)values[key] : 0); } else if(typeof(bool) == pair.Value) { GUILayout.BeginHorizontal(); var currentValueString = (values.ContainsKey(key) ? (bool)values[key] : false).ToString(); currentValueString = currentValueString.Substring(0, 1).ToUpper() + currentValueString.Substring(1); var index = EditorGUILayout.Popup(trueFalseOptions.IndexOf(currentValueString), trueFalseOptions.ToArray()); GUILayout.EndHorizontal(); values[key] = bool.Parse(trueFalseOptions[index]); } else if(typeof(GameObject) == pair.Value) { values[key] = EditorGUILayout.ObjectField(values.ContainsKey(key) ? (GameObject)values[key] : null, typeof(GameObject), true); } else if(typeof(Vector3) == pair.Value) { values[key] = EditorGUILayout.Vector3Field("", values.ContainsKey(key) ? (Vector3)values[key] : Vector3.zero); } else if(typeof(Vector3OrTransform) == pair.Value) { if(!values.ContainsKey(key)) { values[key] = new Vector3OrTransform(); } var val = (Vector3OrTransform)values[key]; val.selected = GUILayout.SelectionGrid(val.selected, Vector3OrTransform.choices, 2); if(Vector3OrTransform.vector3Selected == val.selected) { val.vector = EditorGUILayout.Vector3Field("", val.vector); } else { val.transform = (Transform)EditorGUILayout.ObjectField(val.transform, typeof(Transform), true); } values[key] = val; } else if(typeof(Vector3OrTransformArray) == pair.Value) { if(!values.ContainsKey(key)) { values[key] = new Vector3OrTransformArray(); } var val = (Vector3OrTransformArray)values[key]; val.selected = GUILayout.SelectionGrid(val.selected, Vector3OrTransformArray.choices, Vector3OrTransformArray.choices.Length); if(Vector3OrTransformArray.vector3Selected == val.selected) { if(null == val.vectorArray) { val.vectorArray = new Vector3[0]; } var elements = val.vectorArray.Length; GUILayout.BeginHorizontal(); GUILayout.Label("Number of points"); elements = EditorGUILayout.IntField(elements); GUILayout.EndHorizontal(); if(elements != val.vectorArray.Length) { var resizedArray = new Vector3[elements]; val.vectorArray.CopyTo(resizedArray, 0); val.vectorArray = resizedArray; } for(var i = 0; i < val.vectorArray.Length; ++i) { val.vectorArray[i] = EditorGUILayout.Vector3Field("", val.vectorArray[i]); } } else if(Vector3OrTransformArray.transformSelected == val.selected) { if(null == val.transformArray) { val.transformArray = new Transform[0]; } var elements = val.transformArray.Length; GUILayout.BeginHorizontal(); GUILayout.Label("Number of points"); elements = EditorGUILayout.IntField(elements); GUILayout.EndHorizontal(); if(elements != val.transformArray.Length) { var resizedArray = new Transform[elements]; val.transformArray.CopyTo(resizedArray, 0); val.transformArray = resizedArray; } for(var i = 0; i < val.transformArray.Length; ++i) { val.transformArray[i] = (Transform)EditorGUILayout.ObjectField(val.transformArray[i], typeof(Transform), true); } } else if(Vector3OrTransformArray.iTweenPathSelected == val.selected) { var index = 0; var paths = (GameObject.FindObjectsOfType(typeof(iTweenPath)) as iTweenPath[]); if(0 == paths.Length) { val.pathName = ""; GUILayout.Label("No paths are defined"); } else { for(var i = 0; i < paths.Length; ++i) { if(paths[i].pathName == val.pathName) { index = i; } } index = EditorGUILayout.Popup(index, (GameObject.FindObjectsOfType(typeof(iTweenPath)) as iTweenPath[]).Select(path => path.pathName).ToArray()); val.pathName = paths[index].pathName; } } values[key] = val; } else if(typeof(iTween.LoopType) == pair.Value) { values[key] = EditorGUILayout.EnumPopup(values.ContainsKey(key) ? (iTween.LoopType)values[key] : iTween.LoopType.none); } else if(typeof(iTween.EaseType) == pair.Value) { values[key] = EditorGUILayout.EnumPopup(values.ContainsKey(key) ? (iTween.EaseType)values[key] : iTween.EaseType.linear); } else if(typeof(AudioSource) == pair.Value) { values[key] = (AudioSource)EditorGUILayout.ObjectField(values.ContainsKey(key) ? (AudioSource)values[key] : null, typeof(AudioSource), true); } else if(typeof(AudioClip) == pair.Value) { values[key] = (AudioClip)EditorGUILayout.ObjectField(values.ContainsKey(key) ? (AudioClip)values[key] : null, typeof(AudioClip), true); } else if(typeof(Color) == pair.Value) { values[key] = EditorGUILayout.ColorField(values.ContainsKey(key) ? (Color)values[key] : Color.white); } else if(typeof(Space) == pair.Value) { values[key] = EditorGUILayout.EnumPopup(values.ContainsKey(key) ? (Space)values[key] : Space.Self); } GUILayout.EndVertical(); } else { propertiesEnabled[key] = false; values.Remove(key); } EditorGUILayout.EndToggleGroup(); GUILayout.EndHorizontal(); EditorGUILayout.Separator(); } keys = values.Keys.ToArray(); foreach(var key in keys) { if(values[key] != null && values[key].GetType() == typeof(Vector3OrTransform)) { var val = (Vector3OrTransform)values[key]; if(Vector3OrTransform.vector3Selected == val.selected) { values[key] = val.vector; } else { values[key] = val.transform; } } else if(values[key] != null && values[key].GetType() == typeof(Vector3OrTransformArray)) { var val = (Vector3OrTransformArray)values[key]; if(Vector3OrTransformArray.vector3Selected == val.selected) { values[key] = val.vectorArray; } else if(Vector3OrTransformArray.transformSelected == val.selected) { values[key] = val.transformArray; } else if(Vector3OrTransformArray.iTweenPathSelected == val.selected) { values[key] = val.pathName; } } } evt.Values = values; previousType = evt.type; } }
zzzstrawhatzzz
trunk/client/Assets/iTweenEditor/Editor/iTweenEventDataEditor.cs
C#
asf20
13,699
// Copyright (c) 2009 David Koontz // Please direct any bugs/comments/suggestions to david@koontzfamily.org // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using UnityEngine; public class Vector3OrTransformArray { public static readonly string[] choices = {"Vector3", "Transform", "Path"}; public static readonly int vector3Selected = 0; public static readonly int transformSelected = 1; public static readonly int iTweenPathSelected = 2; public int selected = 0; public Vector3[] vectorArray; public Transform[] transformArray; public string pathName; }
zzzstrawhatzzz
trunk/client/Assets/iTweenEditor/Helper Classes/Vector3OrTransformArray.cs
C#
asf20
1,596
// Copyright (c) 2009 David Koontz // Please direct any bugs/comments/suggestions to david@koontzfamily.org // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using UnityEngine; public class Vector3OrTransform { public static readonly string[] choices = {"Vector3", "Transform"}; public static readonly int vector3Selected = 0; public static readonly int transformSelected = 1; public int selected = 0; public Vector3 vector; public Transform transform; }
zzzstrawhatzzz
trunk/client/Assets/iTweenEditor/Helper Classes/Vector3OrTransform.cs
C#
asf20
1,490
// Copyright (c) 2009 David Koontz // Please direct any bugs/comments/suggestions to david@koontzfamily.org // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; using System.Collections.Generic; using UnityEngine; public class EventParamMappings { public static Dictionary<iTweenEvent.TweenType, Dictionary<string, Type>> mappings = new Dictionary<iTweenEvent.TweenType, Dictionary<string, Type>>(); static EventParamMappings() { // AUDIO FROM mappings.Add(iTweenEvent.TweenType.AudioFrom, new Dictionary<string, Type>()); mappings[iTweenEvent.TweenType.AudioFrom]["audiosource"] = typeof(AudioSource); mappings[iTweenEvent.TweenType.AudioFrom]["volume"] = typeof(float); mappings[iTweenEvent.TweenType.AudioFrom]["pitch"] = typeof(float); mappings[iTweenEvent.TweenType.AudioFrom]["time"] = typeof(float); mappings[iTweenEvent.TweenType.AudioFrom]["delay"] = typeof(float); mappings[iTweenEvent.TweenType.AudioFrom]["easetype"] = typeof(iTween.EaseType); mappings[iTweenEvent.TweenType.AudioFrom]["looptype"] = typeof(iTween.LoopType); mappings[iTweenEvent.TweenType.AudioFrom]["onstart"] = typeof(string); mappings[iTweenEvent.TweenType.AudioFrom]["onstarttarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.AudioFrom]["onstartparams"] = typeof(string); mappings[iTweenEvent.TweenType.AudioFrom]["onupdate"] = typeof(string); mappings[iTweenEvent.TweenType.AudioFrom]["onupdatetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.AudioFrom]["onupdateparams"] = typeof(string); mappings[iTweenEvent.TweenType.AudioFrom]["oncomplete"] = typeof(string); mappings[iTweenEvent.TweenType.AudioFrom]["oncompletetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.AudioFrom]["oncompleteparams"] = typeof(string); mappings[iTweenEvent.TweenType.AudioFrom]["ignoretimescale"] = typeof(bool); // AUDIO TO mappings.Add(iTweenEvent.TweenType.AudioTo, new Dictionary<string, Type>()); mappings[iTweenEvent.TweenType.AudioTo]["audiosource"] = typeof(AudioSource); mappings[iTweenEvent.TweenType.AudioTo]["volume"] = typeof(float); mappings[iTweenEvent.TweenType.AudioTo]["pitch"] = typeof(float); mappings[iTweenEvent.TweenType.AudioTo]["time"] = typeof(float); mappings[iTweenEvent.TweenType.AudioTo]["delay"] = typeof(float); mappings[iTweenEvent.TweenType.AudioTo]["easetype"] = typeof(iTween.EaseType); mappings[iTweenEvent.TweenType.AudioTo]["looptype"] = typeof(iTween.LoopType); mappings[iTweenEvent.TweenType.AudioTo]["onstart"] = typeof(string); mappings[iTweenEvent.TweenType.AudioTo]["onstarttarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.AudioTo]["onstartparams"] = typeof(string); mappings[iTweenEvent.TweenType.AudioTo]["onupdate"] = typeof(string); mappings[iTweenEvent.TweenType.AudioTo]["onupdatetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.AudioTo]["onupdateparams"] = typeof(string); mappings[iTweenEvent.TweenType.AudioTo]["oncomplete"] = typeof(string); mappings[iTweenEvent.TweenType.AudioTo]["oncompletetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.AudioTo]["oncompleteparams"] = typeof(string); mappings[iTweenEvent.TweenType.AudioTo]["ignoretimescale"] = typeof(bool); // AUDIO UPDATE mappings.Add(iTweenEvent.TweenType.AudioUpdate, new Dictionary<string, Type>()); mappings[iTweenEvent.TweenType.AudioUpdate]["audiosource"] = typeof(AudioSource); mappings[iTweenEvent.TweenType.AudioUpdate]["volume"] = typeof(float); mappings[iTweenEvent.TweenType.AudioUpdate]["pitch"] = typeof(float); mappings[iTweenEvent.TweenType.AudioUpdate]["time"] = typeof(float); // CAMERA FADE FROM mappings.Add(iTweenEvent.TweenType.CameraFadeFrom, new Dictionary<string, Type>()); mappings[iTweenEvent.TweenType.CameraFadeFrom]["amount"] = typeof(float); mappings[iTweenEvent.TweenType.CameraFadeFrom]["time"] = typeof(float); mappings[iTweenEvent.TweenType.CameraFadeFrom]["delay"] = typeof(float); mappings[iTweenEvent.TweenType.CameraFadeFrom]["easetype"] = typeof(iTween.EaseType); mappings[iTweenEvent.TweenType.CameraFadeFrom]["looptype"] = typeof(iTween.LoopType); mappings[iTweenEvent.TweenType.CameraFadeFrom]["onstart"] = typeof(string); mappings[iTweenEvent.TweenType.CameraFadeFrom]["onstarttarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.CameraFadeFrom]["onstartparams"] = typeof(string); mappings[iTweenEvent.TweenType.CameraFadeFrom]["onupdate"] = typeof(string); mappings[iTweenEvent.TweenType.CameraFadeFrom]["onupdatetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.CameraFadeFrom]["onupdateparams"] = typeof(string); mappings[iTweenEvent.TweenType.CameraFadeFrom]["oncomplete"] = typeof(string); mappings[iTweenEvent.TweenType.CameraFadeFrom]["oncompletetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.CameraFadeFrom]["oncompleteparams"] = typeof(string); mappings[iTweenEvent.TweenType.CameraFadeFrom]["ignoretimescale"] = typeof(bool); // CAMERA FADE TO mappings.Add(iTweenEvent.TweenType.CameraFadeTo, new Dictionary<string, Type>()); mappings[iTweenEvent.TweenType.CameraFadeTo]["amount"] = typeof(float); mappings[iTweenEvent.TweenType.CameraFadeTo]["time"] = typeof(float); mappings[iTweenEvent.TweenType.CameraFadeTo]["delay"] = typeof(float); mappings[iTweenEvent.TweenType.CameraFadeTo]["easetype"] = typeof(iTween.EaseType); mappings[iTweenEvent.TweenType.CameraFadeTo]["looptype"] = typeof(iTween.LoopType); mappings[iTweenEvent.TweenType.CameraFadeTo]["onstart"] = typeof(string); mappings[iTweenEvent.TweenType.CameraFadeTo]["onstarttarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.CameraFadeTo]["onstartparams"] = typeof(string); mappings[iTweenEvent.TweenType.CameraFadeTo]["onupdate"] = typeof(string); mappings[iTweenEvent.TweenType.CameraFadeTo]["onupdatetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.CameraFadeTo]["onupdateparams"] = typeof(string); mappings[iTweenEvent.TweenType.CameraFadeTo]["oncomplete"] = typeof(string); mappings[iTweenEvent.TweenType.CameraFadeTo]["oncompletetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.CameraFadeTo]["oncompleteparams"] = typeof(string); mappings[iTweenEvent.TweenType.CameraFadeTo]["ignoretimescale"] = typeof(bool); // COLOR FROM mappings.Add(iTweenEvent.TweenType.ColorFrom, new Dictionary<string, Type>()); mappings[iTweenEvent.TweenType.ColorFrom]["color"] = typeof(Color); mappings[iTweenEvent.TweenType.ColorFrom]["r"] = typeof(float); mappings[iTweenEvent.TweenType.ColorFrom]["g"] = typeof(float); mappings[iTweenEvent.TweenType.ColorFrom]["b"] = typeof(float); mappings[iTweenEvent.TweenType.ColorFrom]["a"] = typeof(float); mappings[iTweenEvent.TweenType.ColorFrom]["namedcolorvalue"] = typeof(string); mappings[iTweenEvent.TweenType.ColorFrom]["includechildren"] = typeof(bool); mappings[iTweenEvent.TweenType.ColorFrom]["time"] = typeof(float); mappings[iTweenEvent.TweenType.ColorFrom]["delay"] = typeof(float); mappings[iTweenEvent.TweenType.ColorFrom]["easetype"] = typeof(iTween.EaseType); mappings[iTweenEvent.TweenType.ColorFrom]["looptype"] = typeof(iTween.LoopType); mappings[iTweenEvent.TweenType.ColorFrom]["onstart"] = typeof(string); mappings[iTweenEvent.TweenType.ColorFrom]["onstarttarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.ColorFrom]["onstartparams"] = typeof(string); mappings[iTweenEvent.TweenType.ColorFrom]["onupdate"] = typeof(string); mappings[iTweenEvent.TweenType.ColorFrom]["onupdatetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.ColorFrom]["onupdateparams"] = typeof(string); mappings[iTweenEvent.TweenType.ColorFrom]["oncomplete"] = typeof(string); mappings[iTweenEvent.TweenType.ColorFrom]["oncompletetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.ColorFrom]["oncompleteparams"] = typeof(string); mappings[iTweenEvent.TweenType.ColorFrom]["ignoretimescale"] = typeof(bool); // COLOR TO mappings.Add(iTweenEvent.TweenType.ColorTo, new Dictionary<string, Type>()); mappings[iTweenEvent.TweenType.ColorTo]["color"] = typeof(Color); mappings[iTweenEvent.TweenType.ColorTo]["r"] = typeof(float); mappings[iTweenEvent.TweenType.ColorTo]["g"] = typeof(float); mappings[iTweenEvent.TweenType.ColorTo]["b"] = typeof(float); mappings[iTweenEvent.TweenType.ColorTo]["a"] = typeof(float); mappings[iTweenEvent.TweenType.ColorTo]["namedcolorvalue"] = typeof(string); mappings[iTweenEvent.TweenType.ColorTo]["includechildren"] = typeof(bool); mappings[iTweenEvent.TweenType.ColorTo]["time"] = typeof(float); mappings[iTweenEvent.TweenType.ColorTo]["delay"] = typeof(float); mappings[iTweenEvent.TweenType.ColorTo]["easetype"] = typeof(iTween.EaseType); mappings[iTweenEvent.TweenType.ColorTo]["looptype"] = typeof(iTween.LoopType); mappings[iTweenEvent.TweenType.ColorTo]["onstart"] = typeof(string); mappings[iTweenEvent.TweenType.ColorTo]["onstarttarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.ColorTo]["onstartparams"] = typeof(string); mappings[iTweenEvent.TweenType.ColorTo]["onupdate"] = typeof(string); mappings[iTweenEvent.TweenType.ColorTo]["onupdatetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.ColorTo]["onupdateparams"] = typeof(string); mappings[iTweenEvent.TweenType.ColorTo]["oncomplete"] = typeof(string); mappings[iTweenEvent.TweenType.ColorTo]["oncompletetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.ColorTo]["oncompleteparams"] = typeof(string); mappings[iTweenEvent.TweenType.ColorTo]["ignoretimescale"] = typeof(bool); // COLOR UPDATE mappings.Add(iTweenEvent.TweenType.ColorUpdate, new Dictionary<string, Type>()); mappings[iTweenEvent.TweenType.ColorUpdate]["color"] = typeof(Color); mappings[iTweenEvent.TweenType.ColorUpdate]["r"] = typeof(float); mappings[iTweenEvent.TweenType.ColorUpdate]["g"] = typeof(float); mappings[iTweenEvent.TweenType.ColorUpdate]["b"] = typeof(float); mappings[iTweenEvent.TweenType.ColorUpdate]["a"] = typeof(float); mappings[iTweenEvent.TweenType.ColorUpdate]["namedcolorvalue"] = typeof(string); mappings[iTweenEvent.TweenType.ColorUpdate]["includechildren"] = typeof(bool); mappings[iTweenEvent.TweenType.ColorUpdate]["time"] = typeof(float); // FADE FROM mappings.Add(iTweenEvent.TweenType.FadeFrom, new Dictionary<string, Type>()); mappings[iTweenEvent.TweenType.FadeFrom]["alpha"] = typeof(float); mappings[iTweenEvent.TweenType.FadeFrom]["amount"] = typeof(float); mappings[iTweenEvent.TweenType.FadeFrom]["includechildren"] = typeof(bool); mappings[iTweenEvent.TweenType.FadeFrom]["time"] = typeof(float); mappings[iTweenEvent.TweenType.FadeFrom]["delay"] = typeof(float); mappings[iTweenEvent.TweenType.FadeFrom]["easetype"] = typeof(iTween.EaseType); mappings[iTweenEvent.TweenType.FadeFrom]["looptype"] = typeof(iTween.LoopType); mappings[iTweenEvent.TweenType.FadeFrom]["onstart"] = typeof(string); mappings[iTweenEvent.TweenType.FadeFrom]["onstarttarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.FadeFrom]["onstartparams"] = typeof(string); mappings[iTweenEvent.TweenType.FadeFrom]["onupdate"] = typeof(string); mappings[iTweenEvent.TweenType.FadeFrom]["onupdatetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.FadeFrom]["onupdateparams"] = typeof(string); mappings[iTweenEvent.TweenType.FadeFrom]["oncomplete"] = typeof(string); mappings[iTweenEvent.TweenType.FadeFrom]["oncompletetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.FadeFrom]["oncompleteparams"] = typeof(string); mappings[iTweenEvent.TweenType.FadeFrom]["ignoretimescale"] = typeof(bool); // FADE TO mappings.Add(iTweenEvent.TweenType.FadeTo, new Dictionary<string, Type>()); mappings[iTweenEvent.TweenType.FadeTo]["alpha"] = typeof(float); mappings[iTweenEvent.TweenType.FadeTo]["amount"] = typeof(float); mappings[iTweenEvent.TweenType.FadeTo]["includechildren"] = typeof(bool); mappings[iTweenEvent.TweenType.FadeTo]["time"] = typeof(float); mappings[iTweenEvent.TweenType.FadeTo]["delay"] = typeof(float); mappings[iTweenEvent.TweenType.FadeTo]["easetype"] = typeof(iTween.EaseType); mappings[iTweenEvent.TweenType.FadeTo]["looptype"] = typeof(iTween.LoopType); mappings[iTweenEvent.TweenType.FadeTo]["onstart"] = typeof(string); mappings[iTweenEvent.TweenType.FadeTo]["onstarttarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.FadeTo]["onstartparams"] = typeof(string); mappings[iTweenEvent.TweenType.FadeTo]["onupdate"] = typeof(string); mappings[iTweenEvent.TweenType.FadeTo]["onupdatetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.FadeTo]["onupdateparams"] = typeof(string); mappings[iTweenEvent.TweenType.FadeTo]["oncomplete"] = typeof(string); mappings[iTweenEvent.TweenType.FadeTo]["oncompletetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.FadeTo]["oncompleteparams"] = typeof(string); mappings[iTweenEvent.TweenType.FadeTo]["ignoretimescale"] = typeof(bool); // FADE UPDATE mappings.Add(iTweenEvent.TweenType.FadeUpdate, new Dictionary<string, Type>()); mappings[iTweenEvent.TweenType.FadeUpdate]["alpha"] = typeof(float); mappings[iTweenEvent.TweenType.FadeUpdate]["includechildren"] = typeof(bool); mappings[iTweenEvent.TweenType.FadeUpdate]["time"] = typeof(float); // LOOK FROM mappings.Add(iTweenEvent.TweenType.LookFrom, new Dictionary<string, Type>()); mappings[iTweenEvent.TweenType.LookFrom]["looktarget"] = typeof(Vector3OrTransform); mappings[iTweenEvent.TweenType.LookFrom]["axis"] = typeof(string); mappings[iTweenEvent.TweenType.LookFrom]["time"] = typeof(float); mappings[iTweenEvent.TweenType.LookFrom]["speed"] = typeof(float); mappings[iTweenEvent.TweenType.LookFrom]["delay"] = typeof(float); mappings[iTweenEvent.TweenType.LookFrom]["easetype"] = typeof(iTween.EaseType); mappings[iTweenEvent.TweenType.LookFrom]["looptype"] = typeof(iTween.LoopType); mappings[iTweenEvent.TweenType.LookFrom]["onstart"] = typeof(string); mappings[iTweenEvent.TweenType.LookFrom]["onstarttarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.LookFrom]["onstartparams"] = typeof(string); mappings[iTweenEvent.TweenType.LookFrom]["onupdate"] = typeof(string); mappings[iTweenEvent.TweenType.LookFrom]["onupdatetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.LookFrom]["onupdateparams"] = typeof(string); mappings[iTweenEvent.TweenType.LookFrom]["oncomplete"] = typeof(string); mappings[iTweenEvent.TweenType.LookFrom]["oncompletetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.LookFrom]["oncompleteparams"] = typeof(string); mappings[iTweenEvent.TweenType.LookFrom]["ignoretimescale"] = typeof(bool); // LOOK TO mappings.Add(iTweenEvent.TweenType.LookTo, new Dictionary<string, Type>()); mappings[iTweenEvent.TweenType.LookTo]["looktarget"] = typeof(Vector3OrTransform); mappings[iTweenEvent.TweenType.LookTo]["axis"] = typeof(string); mappings[iTweenEvent.TweenType.LookTo]["time"] = typeof(float); mappings[iTweenEvent.TweenType.LookTo]["speed"] = typeof(float); mappings[iTweenEvent.TweenType.LookTo]["delay"] = typeof(float); mappings[iTweenEvent.TweenType.LookTo]["easetype"] = typeof(iTween.EaseType); mappings[iTweenEvent.TweenType.LookTo]["looptype"] = typeof(iTween.LoopType); mappings[iTweenEvent.TweenType.LookTo]["onstart"] = typeof(string); mappings[iTweenEvent.TweenType.LookTo]["onstarttarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.LookTo]["onstartparams"] = typeof(string); mappings[iTweenEvent.TweenType.LookTo]["onupdate"] = typeof(string); mappings[iTweenEvent.TweenType.LookTo]["onupdatetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.LookTo]["onupdateparams"] = typeof(string); mappings[iTweenEvent.TweenType.LookTo]["oncomplete"] = typeof(string); mappings[iTweenEvent.TweenType.LookTo]["oncompletetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.LookTo]["oncompleteparams"] = typeof(string); mappings[iTweenEvent.TweenType.LookTo]["ignoretimescale"] = typeof(bool); // LOOK UPDATE mappings.Add(iTweenEvent.TweenType.LookUpdate, new Dictionary<string, Type>()); mappings[iTweenEvent.TweenType.LookUpdate]["looktarget"] = typeof(Vector3OrTransform); mappings[iTweenEvent.TweenType.LookUpdate]["axis"] = typeof(string); mappings[iTweenEvent.TweenType.LookUpdate]["time"] = typeof(float); // MOVE ADD mappings.Add(iTweenEvent.TweenType.MoveAdd, new Dictionary<string, Type>()); mappings[iTweenEvent.TweenType.MoveAdd]["amount"] = typeof(Vector3); mappings[iTweenEvent.TweenType.MoveAdd]["x"] = typeof(float); mappings[iTweenEvent.TweenType.MoveAdd]["y"] = typeof(float); mappings[iTweenEvent.TweenType.MoveAdd]["z"] = typeof(float); mappings[iTweenEvent.TweenType.MoveAdd]["orienttopath"] = typeof(bool); mappings[iTweenEvent.TweenType.MoveAdd]["looktarget"] = typeof(Vector3OrTransform); mappings[iTweenEvent.TweenType.MoveAdd]["looktime"] = typeof(float); mappings[iTweenEvent.TweenType.MoveAdd]["axis"] = typeof(string); mappings[iTweenEvent.TweenType.MoveAdd]["space"] = typeof(Space); mappings[iTweenEvent.TweenType.MoveAdd]["time"] = typeof(float); mappings[iTweenEvent.TweenType.MoveAdd]["speed"] = typeof(float); mappings[iTweenEvent.TweenType.MoveAdd]["delay"] = typeof(float); mappings[iTweenEvent.TweenType.MoveAdd]["easetype"] = typeof(iTween.EaseType); mappings[iTweenEvent.TweenType.MoveAdd]["looptype"] = typeof(iTween.LoopType); mappings[iTweenEvent.TweenType.MoveAdd]["onstart"] = typeof(string); mappings[iTweenEvent.TweenType.MoveAdd]["onstarttarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.MoveAdd]["onstartparams"] = typeof(string); mappings[iTweenEvent.TweenType.MoveAdd]["onupdate"] = typeof(string); mappings[iTweenEvent.TweenType.MoveAdd]["onupdatetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.MoveAdd]["onupdateparams"] = typeof(string); mappings[iTweenEvent.TweenType.MoveAdd]["oncomplete"] = typeof(string); mappings[iTweenEvent.TweenType.MoveAdd]["oncompletetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.MoveAdd]["oncompleteparams"] = typeof(string); mappings[iTweenEvent.TweenType.MoveAdd]["ignoretimescale"] = typeof(bool); // MOVE BY mappings.Add(iTweenEvent.TweenType.MoveBy, new Dictionary<string, Type>()); mappings[iTweenEvent.TweenType.MoveBy]["time"] = typeof(float); mappings[iTweenEvent.TweenType.MoveBy]["speed"] = typeof(float); mappings[iTweenEvent.TweenType.MoveBy]["delay"] = typeof(float); mappings[iTweenEvent.TweenType.MoveBy]["amount"] = typeof(Vector3); mappings[iTweenEvent.TweenType.MoveBy]["x"] = typeof(float); mappings[iTweenEvent.TweenType.MoveBy]["y"] = typeof(float); mappings[iTweenEvent.TweenType.MoveBy]["z"] = typeof(float); mappings[iTweenEvent.TweenType.MoveBy]["orienttopath"] = typeof(bool); mappings[iTweenEvent.TweenType.MoveBy]["looktarget"] = typeof(Vector3OrTransform); mappings[iTweenEvent.TweenType.MoveBy]["looktime"] = typeof(float); mappings[iTweenEvent.TweenType.MoveBy]["axis"] = typeof(string); mappings[iTweenEvent.TweenType.MoveBy]["space"] = typeof(Space); mappings[iTweenEvent.TweenType.MoveBy]["easetype"] = typeof(iTween.EaseType); mappings[iTweenEvent.TweenType.MoveBy]["looptype"] = typeof(iTween.LoopType); mappings[iTweenEvent.TweenType.MoveBy]["onstart"] = typeof(string); mappings[iTweenEvent.TweenType.MoveBy]["onstarttarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.MoveBy]["onstartparams"] = typeof(string); mappings[iTweenEvent.TweenType.MoveBy]["onupdate"] = typeof(string); mappings[iTweenEvent.TweenType.MoveBy]["onupdatetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.MoveBy]["onupdateparams"] = typeof(string); mappings[iTweenEvent.TweenType.MoveBy]["oncomplete"] = typeof(string); mappings[iTweenEvent.TweenType.MoveBy]["oncompletetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.MoveBy]["oncompleteparams"] = typeof(string); mappings[iTweenEvent.TweenType.MoveBy]["ignoretimescale"] = typeof(bool); // MOVE FROM mappings.Add(iTweenEvent.TweenType.MoveFrom, new Dictionary<string, Type>()); mappings[iTweenEvent.TweenType.MoveFrom]["position"] = typeof(Vector3OrTransform); mappings[iTweenEvent.TweenType.MoveFrom]["path"] = typeof(Vector3OrTransformArray); mappings[iTweenEvent.TweenType.MoveFrom]["movetopath"] = typeof(bool); mappings[iTweenEvent.TweenType.MoveFrom]["x"] = typeof(float); mappings[iTweenEvent.TweenType.MoveFrom]["y"] = typeof(float); mappings[iTweenEvent.TweenType.MoveFrom]["z"] = typeof(float); mappings[iTweenEvent.TweenType.MoveFrom]["orienttopath"] = typeof(bool); mappings[iTweenEvent.TweenType.MoveFrom]["looktarget"] = typeof(Vector3OrTransform); mappings[iTweenEvent.TweenType.MoveFrom]["looktime"] = typeof(float); mappings[iTweenEvent.TweenType.MoveFrom]["lookahead"] = typeof(float); mappings[iTweenEvent.TweenType.MoveFrom]["axis"] = typeof(string); mappings[iTweenEvent.TweenType.MoveFrom]["islocal"] = typeof(bool); mappings[iTweenEvent.TweenType.MoveFrom]["time"] = typeof(float); mappings[iTweenEvent.TweenType.MoveFrom]["speed"] = typeof(float); mappings[iTweenEvent.TweenType.MoveFrom]["delay"] = typeof(float); mappings[iTweenEvent.TweenType.MoveFrom]["easetype"] = typeof(iTween.EaseType); mappings[iTweenEvent.TweenType.MoveFrom]["looptype"] = typeof(iTween.LoopType); mappings[iTweenEvent.TweenType.MoveFrom]["onstart"] = typeof(string); mappings[iTweenEvent.TweenType.MoveFrom]["onstarttarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.MoveFrom]["onstartparams"] = typeof(string); mappings[iTweenEvent.TweenType.MoveFrom]["onupdate"] = typeof(string); mappings[iTweenEvent.TweenType.MoveFrom]["onupdatetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.MoveFrom]["onupdateparams"] = typeof(string); mappings[iTweenEvent.TweenType.MoveFrom]["oncomplete"] = typeof(string); mappings[iTweenEvent.TweenType.MoveFrom]["oncompletetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.MoveFrom]["oncompleteparams"] = typeof(string); mappings[iTweenEvent.TweenType.MoveFrom]["ignoretimescale"] = typeof(bool); // MOVE TO mappings.Add(iTweenEvent.TweenType.MoveTo, new Dictionary<string, Type>()); mappings[iTweenEvent.TweenType.MoveTo]["position"] = typeof(Vector3OrTransform); mappings[iTweenEvent.TweenType.MoveTo]["path"] = typeof(Vector3OrTransformArray); mappings[iTweenEvent.TweenType.MoveTo]["movetopath"] = typeof(bool); mappings[iTweenEvent.TweenType.MoveTo]["x"] = typeof(float); mappings[iTweenEvent.TweenType.MoveTo]["y"] = typeof(float); mappings[iTweenEvent.TweenType.MoveTo]["z"] = typeof(float); mappings[iTweenEvent.TweenType.MoveTo]["orienttopath"] = typeof(bool); mappings[iTweenEvent.TweenType.MoveTo]["looktarget"] = typeof(Vector3OrTransform); mappings[iTweenEvent.TweenType.MoveTo]["looktime"] = typeof(float); mappings[iTweenEvent.TweenType.MoveTo]["lookahead"] = typeof(float); mappings[iTweenEvent.TweenType.MoveTo]["axis"] = typeof(string); mappings[iTweenEvent.TweenType.MoveTo]["islocal"] = typeof(bool); mappings[iTweenEvent.TweenType.MoveTo]["time"] = typeof(float); mappings[iTweenEvent.TweenType.MoveTo]["speed"] = typeof(float); mappings[iTweenEvent.TweenType.MoveTo]["delay"] = typeof(float); mappings[iTweenEvent.TweenType.MoveTo]["easetype"] = typeof(iTween.EaseType); mappings[iTweenEvent.TweenType.MoveTo]["looptype"] = typeof(iTween.LoopType); mappings[iTweenEvent.TweenType.MoveTo]["onstart"] = typeof(string); mappings[iTweenEvent.TweenType.MoveTo]["onstarttarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.MoveTo]["onstartparams"] = typeof(string); mappings[iTweenEvent.TweenType.MoveTo]["onupdate"] = typeof(string); mappings[iTweenEvent.TweenType.MoveTo]["onupdatetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.MoveTo]["onupdateparams"] = typeof(string); mappings[iTweenEvent.TweenType.MoveTo]["oncomplete"] = typeof(string); mappings[iTweenEvent.TweenType.MoveTo]["oncompletetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.MoveTo]["oncompleteparams"] = typeof(string); mappings[iTweenEvent.TweenType.MoveTo]["ignoretimescale"] = typeof(bool); // MOVE UPDATE mappings.Add(iTweenEvent.TweenType.MoveUpdate, new Dictionary<string, Type>()); mappings[iTweenEvent.TweenType.MoveUpdate]["position"] = typeof(Vector3OrTransform); mappings[iTweenEvent.TweenType.MoveUpdate]["x"] = typeof(float); mappings[iTweenEvent.TweenType.MoveUpdate]["y"] = typeof(float); mappings[iTweenEvent.TweenType.MoveUpdate]["z"] = typeof(float); mappings[iTweenEvent.TweenType.MoveUpdate]["orienttopath"] = typeof(bool); mappings[iTweenEvent.TweenType.MoveUpdate]["looktarget"] = typeof(Vector3OrTransform); mappings[iTweenEvent.TweenType.MoveUpdate]["looktime"] = typeof(float); mappings[iTweenEvent.TweenType.MoveUpdate]["axis"] = typeof(string); mappings[iTweenEvent.TweenType.MoveUpdate]["islocal"] = typeof(bool); mappings[iTweenEvent.TweenType.MoveUpdate]["time"] = typeof(float); // PUNCH POSITION mappings.Add(iTweenEvent.TweenType.PunchPosition, new Dictionary<string, Type>()); mappings[iTweenEvent.TweenType.PunchPosition]["position"] = typeof(Vector3OrTransform); mappings[iTweenEvent.TweenType.PunchPosition]["amount"] = typeof(Vector3); mappings[iTweenEvent.TweenType.PunchPosition]["x"] = typeof(float); mappings[iTweenEvent.TweenType.PunchPosition]["y"] = typeof(float); mappings[iTweenEvent.TweenType.PunchPosition]["z"] = typeof(float); mappings[iTweenEvent.TweenType.PunchPosition]["space"] = typeof(Space); mappings[iTweenEvent.TweenType.PunchPosition]["looktarget"] = typeof(Vector3OrTransform); mappings[iTweenEvent.TweenType.PunchPosition]["looktime"] = typeof(float); mappings[iTweenEvent.TweenType.PunchPosition]["axis"] = typeof(string); mappings[iTweenEvent.TweenType.PunchPosition]["time"] = typeof(float); mappings[iTweenEvent.TweenType.PunchPosition]["delay"] = typeof(float); mappings[iTweenEvent.TweenType.PunchPosition]["looptype"] = typeof(iTween.LoopType); mappings[iTweenEvent.TweenType.PunchPosition]["onstart"] = typeof(string); mappings[iTweenEvent.TweenType.PunchPosition]["onstarttarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.PunchPosition]["onstartparams"] = typeof(string); mappings[iTweenEvent.TweenType.PunchPosition]["onupdate"] = typeof(string); mappings[iTweenEvent.TweenType.PunchPosition]["onupdatetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.PunchPosition]["onupdateparams"] = typeof(string); mappings[iTweenEvent.TweenType.PunchPosition]["oncomplete"] = typeof(string); mappings[iTweenEvent.TweenType.PunchPosition]["oncompletetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.PunchPosition]["oncompleteparams"] = typeof(string); mappings[iTweenEvent.TweenType.PunchPosition]["ignoretimescale"] = typeof(bool); // PUNCH ROTATION mappings.Add(iTweenEvent.TweenType.PunchRotation, new Dictionary<string, Type>()); mappings[iTweenEvent.TweenType.PunchRotation]["position"] = typeof(Vector3OrTransform); mappings[iTweenEvent.TweenType.PunchRotation]["amount"] = typeof(Vector3); mappings[iTweenEvent.TweenType.PunchRotation]["x"] = typeof(float); mappings[iTweenEvent.TweenType.PunchRotation]["y"] = typeof(float); mappings[iTweenEvent.TweenType.PunchRotation]["z"] = typeof(float); mappings[iTweenEvent.TweenType.PunchRotation]["space"] = typeof(Space); mappings[iTweenEvent.TweenType.PunchRotation]["time"] = typeof(float); mappings[iTweenEvent.TweenType.PunchRotation]["delay"] = typeof(float); mappings[iTweenEvent.TweenType.PunchRotation]["looptype"] = typeof(iTween.LoopType); mappings[iTweenEvent.TweenType.PunchRotation]["onstart"] = typeof(string); mappings[iTweenEvent.TweenType.PunchRotation]["onstarttarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.PunchRotation]["onstartparams"] = typeof(string); mappings[iTweenEvent.TweenType.PunchRotation]["onupdate"] = typeof(string); mappings[iTweenEvent.TweenType.PunchRotation]["onupdatetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.PunchRotation]["onupdateparams"] = typeof(string); mappings[iTweenEvent.TweenType.PunchRotation]["oncomplete"] = typeof(string); mappings[iTweenEvent.TweenType.PunchRotation]["oncompletetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.PunchRotation]["oncompleteparams"] = typeof(string); mappings[iTweenEvent.TweenType.PunchRotation]["ignoretimescale"] = typeof(bool); // PUNCH SCALE mappings.Add(iTweenEvent.TweenType.PunchScale, new Dictionary<string, Type>()); mappings[iTweenEvent.TweenType.PunchScale]["position"] = typeof(Vector3OrTransform); mappings[iTweenEvent.TweenType.PunchScale]["amount"] = typeof(Vector3); mappings[iTweenEvent.TweenType.PunchScale]["x"] = typeof(float); mappings[iTweenEvent.TweenType.PunchScale]["y"] = typeof(float); mappings[iTweenEvent.TweenType.PunchScale]["z"] = typeof(float); mappings[iTweenEvent.TweenType.PunchScale]["time"] = typeof(float); mappings[iTweenEvent.TweenType.PunchScale]["delay"] = typeof(float); mappings[iTweenEvent.TweenType.PunchScale]["looptype"] = typeof(iTween.LoopType); mappings[iTweenEvent.TweenType.PunchScale]["onstart"] = typeof(string); mappings[iTweenEvent.TweenType.PunchScale]["onstarttarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.PunchScale]["onstartparams"] = typeof(string); mappings[iTweenEvent.TweenType.PunchScale]["onupdate"] = typeof(string); mappings[iTweenEvent.TweenType.PunchScale]["onupdatetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.PunchScale]["onupdateparams"] = typeof(string); mappings[iTweenEvent.TweenType.PunchScale]["oncomplete"] = typeof(string); mappings[iTweenEvent.TweenType.PunchScale]["oncompletetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.PunchScale]["oncompleteparams"] = typeof(string); mappings[iTweenEvent.TweenType.PunchScale]["ignoretimescale"] = typeof(bool); // ROTATE ADD mappings.Add(iTweenEvent.TweenType.RotateAdd, new Dictionary<string, Type>()); mappings[iTweenEvent.TweenType.RotateAdd]["amount"] = typeof(Vector3); mappings[iTweenEvent.TweenType.RotateAdd]["x"] = typeof(float); mappings[iTweenEvent.TweenType.RotateAdd]["y"] = typeof(float); mappings[iTweenEvent.TweenType.RotateAdd]["z"] = typeof(float); mappings[iTweenEvent.TweenType.RotateAdd]["space"] = typeof(Space); mappings[iTweenEvent.TweenType.RotateAdd]["time"] = typeof(float); mappings[iTweenEvent.TweenType.RotateAdd]["speed"] = typeof(float); mappings[iTweenEvent.TweenType.RotateAdd]["delay"] = typeof(float); mappings[iTweenEvent.TweenType.RotateAdd]["easetype"] = typeof(iTween.EaseType); mappings[iTweenEvent.TweenType.RotateAdd]["looptype"] = typeof(iTween.LoopType); mappings[iTweenEvent.TweenType.RotateAdd]["onstart"] = typeof(string); mappings[iTweenEvent.TweenType.RotateAdd]["onstarttarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.RotateAdd]["onstartparams"] = typeof(string); mappings[iTweenEvent.TweenType.RotateAdd]["onupdate"] = typeof(string); mappings[iTweenEvent.TweenType.RotateAdd]["onupdatetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.RotateAdd]["onupdateparams"] = typeof(string); mappings[iTweenEvent.TweenType.RotateAdd]["oncomplete"] = typeof(string); mappings[iTweenEvent.TweenType.RotateAdd]["oncompletetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.RotateAdd]["oncompleteparams"] = typeof(string); mappings[iTweenEvent.TweenType.RotateAdd]["ignoretimescale"] = typeof(bool); // ROTATE BY mappings.Add(iTweenEvent.TweenType.RotateBy, new Dictionary<string, Type>()); mappings[iTweenEvent.TweenType.RotateBy]["amount"] = typeof(Vector3); mappings[iTweenEvent.TweenType.RotateBy]["x"] = typeof(float); mappings[iTweenEvent.TweenType.RotateBy]["y"] = typeof(float); mappings[iTweenEvent.TweenType.RotateBy]["z"] = typeof(float); mappings[iTweenEvent.TweenType.RotateBy]["space"] = typeof(Space); mappings[iTweenEvent.TweenType.RotateBy]["time"] = typeof(float); mappings[iTweenEvent.TweenType.RotateBy]["speed"] = typeof(float); mappings[iTweenEvent.TweenType.RotateBy]["delay"] = typeof(float); mappings[iTweenEvent.TweenType.RotateBy]["easetype"] = typeof(iTween.EaseType); mappings[iTweenEvent.TweenType.RotateBy]["looptype"] = typeof(iTween.LoopType); mappings[iTweenEvent.TweenType.RotateBy]["onstart"] = typeof(string); mappings[iTweenEvent.TweenType.RotateBy]["onstarttarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.RotateBy]["onstartparams"] = typeof(string); mappings[iTweenEvent.TweenType.RotateBy]["onupdate"] = typeof(string); mappings[iTweenEvent.TweenType.RotateBy]["onupdatetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.RotateBy]["onupdateparams"] = typeof(string); mappings[iTweenEvent.TweenType.RotateBy]["oncomplete"] = typeof(string); mappings[iTweenEvent.TweenType.RotateBy]["oncompletetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.RotateBy]["oncompleteparams"] = typeof(string); mappings[iTweenEvent.TweenType.RotateBy]["ignoretimescale"] = typeof(bool); // ROTATE FROM mappings.Add(iTweenEvent.TweenType.RotateFrom, new Dictionary<string, Type>()); mappings[iTweenEvent.TweenType.RotateFrom]["rotation"] = typeof(Vector3OrTransform); mappings[iTweenEvent.TweenType.RotateFrom]["x"] = typeof(float); mappings[iTweenEvent.TweenType.RotateFrom]["y"] = typeof(float); mappings[iTweenEvent.TweenType.RotateFrom]["z"] = typeof(float); mappings[iTweenEvent.TweenType.RotateFrom]["islocal"] = typeof(bool); mappings[iTweenEvent.TweenType.RotateFrom]["time"] = typeof(float); mappings[iTweenEvent.TweenType.RotateFrom]["speed"] = typeof(float); mappings[iTweenEvent.TweenType.RotateFrom]["delay"] = typeof(float); mappings[iTweenEvent.TweenType.RotateFrom]["easetype"] = typeof(iTween.EaseType); mappings[iTweenEvent.TweenType.RotateFrom]["looptype"] = typeof(iTween.LoopType); mappings[iTweenEvent.TweenType.RotateFrom]["onstart"] = typeof(string); mappings[iTweenEvent.TweenType.RotateFrom]["onstarttarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.RotateFrom]["onstartparams"] = typeof(string); mappings[iTweenEvent.TweenType.RotateFrom]["onupdate"] = typeof(string); mappings[iTweenEvent.TweenType.RotateFrom]["onupdatetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.RotateFrom]["onupdateparams"] = typeof(string); mappings[iTweenEvent.TweenType.RotateFrom]["oncomplete"] = typeof(string); mappings[iTweenEvent.TweenType.RotateFrom]["oncompletetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.RotateFrom]["oncompleteparams"] = typeof(string); mappings[iTweenEvent.TweenType.RotateFrom]["ignoretimescale"] = typeof(bool); // ROTATE TO mappings.Add(iTweenEvent.TweenType.RotateTo, new Dictionary<string, Type>()); mappings[iTweenEvent.TweenType.RotateTo]["rotation"] = typeof(Vector3OrTransform); mappings[iTweenEvent.TweenType.RotateTo]["x"] = typeof(float); mappings[iTweenEvent.TweenType.RotateTo]["y"] = typeof(float); mappings[iTweenEvent.TweenType.RotateTo]["z"] = typeof(float); mappings[iTweenEvent.TweenType.RotateTo]["islocal"] = typeof(bool); mappings[iTweenEvent.TweenType.RotateTo]["time"] = typeof(float); mappings[iTweenEvent.TweenType.RotateTo]["speed"] = typeof(float); mappings[iTweenEvent.TweenType.RotateTo]["delay"] = typeof(float); mappings[iTweenEvent.TweenType.RotateTo]["easetype"] = typeof(iTween.EaseType); mappings[iTweenEvent.TweenType.RotateTo]["looptype"] = typeof(iTween.LoopType); mappings[iTweenEvent.TweenType.RotateTo]["onstart"] = typeof(string); mappings[iTweenEvent.TweenType.RotateTo]["onstarttarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.RotateTo]["onstartparams"] = typeof(string); mappings[iTweenEvent.TweenType.RotateTo]["onupdate"] = typeof(string); mappings[iTweenEvent.TweenType.RotateTo]["onupdatetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.RotateTo]["onupdateparams"] = typeof(string); mappings[iTweenEvent.TweenType.RotateTo]["oncomplete"] = typeof(string); mappings[iTweenEvent.TweenType.RotateTo]["oncompletetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.RotateTo]["oncompleteparams"] = typeof(string); mappings[iTweenEvent.TweenType.RotateTo]["ignoretimescale"] = typeof(bool); // ROTATE UPDATE mappings.Add(iTweenEvent.TweenType.RotateUpdate, new Dictionary<string, Type>()); mappings[iTweenEvent.TweenType.RotateUpdate]["rotation"] = typeof(Vector3OrTransform); mappings[iTweenEvent.TweenType.RotateUpdate]["x"] = typeof(float); mappings[iTweenEvent.TweenType.RotateUpdate]["y"] = typeof(float); mappings[iTweenEvent.TweenType.RotateUpdate]["z"] = typeof(float); mappings[iTweenEvent.TweenType.RotateUpdate]["islocal"] = typeof(bool); mappings[iTweenEvent.TweenType.RotateUpdate]["time"] = typeof(float); // SCALE ADD mappings.Add(iTweenEvent.TweenType.ScaleAdd, new Dictionary<string, Type>()); mappings[iTweenEvent.TweenType.ScaleAdd]["amount"] = typeof(Vector3); mappings[iTweenEvent.TweenType.ScaleAdd]["x"] = typeof(float); mappings[iTweenEvent.TweenType.ScaleAdd]["y"] = typeof(float); mappings[iTweenEvent.TweenType.ScaleAdd]["z"] = typeof(float); mappings[iTweenEvent.TweenType.ScaleAdd]["time"] = typeof(float); mappings[iTweenEvent.TweenType.ScaleAdd]["speed"] = typeof(float); mappings[iTweenEvent.TweenType.ScaleAdd]["delay"] = typeof(float); mappings[iTweenEvent.TweenType.ScaleAdd]["easetype"] = typeof(iTween.EaseType); mappings[iTweenEvent.TweenType.ScaleAdd]["looptype"] = typeof(iTween.LoopType); mappings[iTweenEvent.TweenType.ScaleAdd]["onstart"] = typeof(string); mappings[iTweenEvent.TweenType.ScaleAdd]["onstarttarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.ScaleAdd]["onstartparams"] = typeof(string); mappings[iTweenEvent.TweenType.ScaleAdd]["onupdate"] = typeof(string); mappings[iTweenEvent.TweenType.ScaleAdd]["onupdatetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.ScaleAdd]["onupdateparams"] = typeof(string); mappings[iTweenEvent.TweenType.ScaleAdd]["oncomplete"] = typeof(string); mappings[iTweenEvent.TweenType.ScaleAdd]["oncompletetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.ScaleAdd]["oncompleteparams"] = typeof(string); mappings[iTweenEvent.TweenType.ScaleAdd]["ignoretimescale"] = typeof(bool); // SCALE BY mappings.Add(iTweenEvent.TweenType.ScaleBy, new Dictionary<string, Type>()); mappings[iTweenEvent.TweenType.ScaleBy]["amount"] = typeof(Vector3); mappings[iTweenEvent.TweenType.ScaleBy]["x"] = typeof(float); mappings[iTweenEvent.TweenType.ScaleBy]["y"] = typeof(float); mappings[iTweenEvent.TweenType.ScaleBy]["z"] = typeof(float); mappings[iTweenEvent.TweenType.ScaleBy]["time"] = typeof(float); mappings[iTweenEvent.TweenType.ScaleBy]["speed"] = typeof(float); mappings[iTweenEvent.TweenType.ScaleBy]["delay"] = typeof(float); mappings[iTweenEvent.TweenType.ScaleBy]["easetype"] = typeof(iTween.EaseType); mappings[iTweenEvent.TweenType.ScaleBy]["looptype"] = typeof(iTween.LoopType); mappings[iTweenEvent.TweenType.ScaleBy]["onstart"] = typeof(string); mappings[iTweenEvent.TweenType.ScaleBy]["onstarttarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.ScaleBy]["onstartparams"] = typeof(string); mappings[iTweenEvent.TweenType.ScaleBy]["onupdate"] = typeof(string); mappings[iTweenEvent.TweenType.ScaleBy]["onupdatetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.ScaleBy]["onupdateparams"] = typeof(string); mappings[iTweenEvent.TweenType.ScaleBy]["oncomplete"] = typeof(string); mappings[iTweenEvent.TweenType.ScaleBy]["oncompletetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.ScaleBy]["oncompleteparams"] = typeof(string); mappings[iTweenEvent.TweenType.ScaleBy]["ignoretimescale"] = typeof(bool); // SCALE FROM mappings.Add(iTweenEvent.TweenType.ScaleFrom, new Dictionary<string, Type>()); mappings[iTweenEvent.TweenType.ScaleFrom]["scale"] = typeof(Vector3OrTransform); mappings[iTweenEvent.TweenType.ScaleFrom]["x"] = typeof(float); mappings[iTweenEvent.TweenType.ScaleFrom]["y"] = typeof(float); mappings[iTweenEvent.TweenType.ScaleFrom]["z"] = typeof(float); mappings[iTweenEvent.TweenType.ScaleFrom]["time"] = typeof(float); mappings[iTweenEvent.TweenType.ScaleFrom]["speed"] = typeof(float); mappings[iTweenEvent.TweenType.ScaleFrom]["delay"] = typeof(float); mappings[iTweenEvent.TweenType.ScaleFrom]["easetype"] = typeof(iTween.EaseType); mappings[iTweenEvent.TweenType.ScaleFrom]["looptype"] = typeof(iTween.LoopType); mappings[iTweenEvent.TweenType.ScaleFrom]["onstart"] = typeof(string); mappings[iTweenEvent.TweenType.ScaleFrom]["onstarttarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.ScaleFrom]["onstartparams"] = typeof(string); mappings[iTweenEvent.TweenType.ScaleFrom]["onupdate"] = typeof(string); mappings[iTweenEvent.TweenType.ScaleFrom]["onupdatetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.ScaleFrom]["onupdateparams"] = typeof(string); mappings[iTweenEvent.TweenType.ScaleFrom]["oncomplete"] = typeof(string); mappings[iTweenEvent.TweenType.ScaleFrom]["oncompletetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.ScaleFrom]["oncompleteparams"] = typeof(string); mappings[iTweenEvent.TweenType.ScaleFrom]["ignoretimescale"] = typeof(bool); // SCALE TO mappings.Add(iTweenEvent.TweenType.ScaleTo, new Dictionary<string, Type>()); mappings[iTweenEvent.TweenType.ScaleTo]["scale"] = typeof(Vector3OrTransform); mappings[iTweenEvent.TweenType.ScaleTo]["x"] = typeof(float); mappings[iTweenEvent.TweenType.ScaleTo]["y"] = typeof(float); mappings[iTweenEvent.TweenType.ScaleTo]["z"] = typeof(float); mappings[iTweenEvent.TweenType.ScaleTo]["time"] = typeof(float); mappings[iTweenEvent.TweenType.ScaleTo]["speed"] = typeof(float); mappings[iTweenEvent.TweenType.ScaleTo]["delay"] = typeof(float); mappings[iTweenEvent.TweenType.ScaleTo]["easetype"] = typeof(iTween.EaseType); mappings[iTweenEvent.TweenType.ScaleTo]["looptype"] = typeof(iTween.LoopType); mappings[iTweenEvent.TweenType.ScaleTo]["onstart"] = typeof(string); mappings[iTweenEvent.TweenType.ScaleTo]["onstarttarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.ScaleTo]["onstartparams"] = typeof(string); mappings[iTweenEvent.TweenType.ScaleTo]["onupdate"] = typeof(string); mappings[iTweenEvent.TweenType.ScaleTo]["onupdatetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.ScaleTo]["onupdateparams"] = typeof(string); mappings[iTweenEvent.TweenType.ScaleTo]["oncomplete"] = typeof(string); mappings[iTweenEvent.TweenType.ScaleTo]["oncompletetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.ScaleTo]["oncompleteparams"] = typeof(string); mappings[iTweenEvent.TweenType.ScaleTo]["ignoretimescale"] = typeof(bool); // SCALE UPDATE mappings.Add(iTweenEvent.TweenType.ScaleUpdate, new Dictionary<string, Type>()); mappings[iTweenEvent.TweenType.ScaleUpdate]["scale"] = typeof(Vector3OrTransform); mappings[iTweenEvent.TweenType.ScaleUpdate]["x"] = typeof(float); mappings[iTweenEvent.TweenType.ScaleUpdate]["y"] = typeof(float); mappings[iTweenEvent.TweenType.ScaleUpdate]["z"] = typeof(float); mappings[iTweenEvent.TweenType.ScaleUpdate]["time"] = typeof(float); // SHAKE POSITION mappings.Add(iTweenEvent.TweenType.ShakePosition, new Dictionary<string, Type>()); mappings[iTweenEvent.TweenType.ShakePosition]["amount"] = typeof(Vector3); mappings[iTweenEvent.TweenType.ShakePosition]["x"] = typeof(float); mappings[iTweenEvent.TweenType.ShakePosition]["y"] = typeof(float); mappings[iTweenEvent.TweenType.ShakePosition]["z"] = typeof(float); mappings[iTweenEvent.TweenType.ShakePosition]["space"] = typeof(Space); mappings[iTweenEvent.TweenType.ShakePosition]["orienttopath"] = typeof(bool); mappings[iTweenEvent.TweenType.ShakePosition]["looktarget"] = typeof(Vector3OrTransform); mappings[iTweenEvent.TweenType.ShakePosition]["looktime"] = typeof(float); mappings[iTweenEvent.TweenType.ShakePosition]["axis"] = typeof(string); mappings[iTweenEvent.TweenType.ShakePosition]["time"] = typeof(float); mappings[iTweenEvent.TweenType.ShakePosition]["delay"] = typeof(float); mappings[iTweenEvent.TweenType.ShakePosition]["looptype"] = typeof(iTween.LoopType); mappings[iTweenEvent.TweenType.ShakePosition]["onstart"] = typeof(string); mappings[iTweenEvent.TweenType.ShakePosition]["onstarttarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.ShakePosition]["onstartparams"] = typeof(string); mappings[iTweenEvent.TweenType.ShakePosition]["onupdate"] = typeof(string); mappings[iTweenEvent.TweenType.ShakePosition]["onupdatetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.ShakePosition]["onupdateparams"] = typeof(string); mappings[iTweenEvent.TweenType.ShakePosition]["oncomplete"] = typeof(string); mappings[iTweenEvent.TweenType.ShakePosition]["oncompletetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.ShakePosition]["oncompleteparams"] = typeof(string); mappings[iTweenEvent.TweenType.ShakePosition]["ignoretimescale"] = typeof(bool); // SHAKE ROTATION mappings.Add(iTweenEvent.TweenType.ShakeRotation, new Dictionary<string, Type>()); mappings[iTweenEvent.TweenType.ShakeRotation]["amount"] = typeof(Vector3); mappings[iTweenEvent.TweenType.ShakeRotation]["x"] = typeof(float); mappings[iTweenEvent.TweenType.ShakeRotation]["y"] = typeof(float); mappings[iTweenEvent.TweenType.ShakeRotation]["z"] = typeof(float); mappings[iTweenEvent.TweenType.ShakeRotation]["space"] = typeof(Space); mappings[iTweenEvent.TweenType.ShakeRotation]["time"] = typeof(float); mappings[iTweenEvent.TweenType.ShakeRotation]["delay"] = typeof(float); mappings[iTweenEvent.TweenType.ShakeRotation]["looptype"] = typeof(iTween.LoopType); mappings[iTweenEvent.TweenType.ShakeRotation]["onstart"] = typeof(string); mappings[iTweenEvent.TweenType.ShakeRotation]["onstarttarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.ShakeRotation]["onstartparams"] = typeof(string); mappings[iTweenEvent.TweenType.ShakeRotation]["onupdate"] = typeof(string); mappings[iTweenEvent.TweenType.ShakeRotation]["onupdatetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.ShakeRotation]["onupdateparams"] = typeof(string); mappings[iTweenEvent.TweenType.ShakeRotation]["oncomplete"] = typeof(string); mappings[iTweenEvent.TweenType.ShakeRotation]["oncompletetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.ShakeRotation]["oncompleteparams"] = typeof(string); mappings[iTweenEvent.TweenType.ShakeRotation]["ignoretimescale"] = typeof(bool); // SHAKE SCALE mappings.Add(iTweenEvent.TweenType.ShakeScale, new Dictionary<string, Type>()); mappings[iTweenEvent.TweenType.ShakeScale]["amount"] = typeof(Vector3); mappings[iTweenEvent.TweenType.ShakeScale]["x"] = typeof(float); mappings[iTweenEvent.TweenType.ShakeScale]["y"] = typeof(float); mappings[iTweenEvent.TweenType.ShakeScale]["z"] = typeof(float); mappings[iTweenEvent.TweenType.ShakeScale]["time"] = typeof(float); mappings[iTweenEvent.TweenType.ShakeScale]["delay"] = typeof(float); mappings[iTweenEvent.TweenType.ShakeScale]["looptype"] = typeof(iTween.LoopType); mappings[iTweenEvent.TweenType.ShakeScale]["onstart"] = typeof(string); mappings[iTweenEvent.TweenType.ShakeScale]["onstarttarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.ShakeScale]["onstartparams"] = typeof(string); mappings[iTweenEvent.TweenType.ShakeScale]["onupdate"] = typeof(string); mappings[iTweenEvent.TweenType.ShakeScale]["onupdatetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.ShakeScale]["onupdateparams"] = typeof(string); mappings[iTweenEvent.TweenType.ShakeScale]["oncomplete"] = typeof(string); mappings[iTweenEvent.TweenType.ShakeScale]["oncompletetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.ShakeScale]["oncompleteparams"] = typeof(string); mappings[iTweenEvent.TweenType.ShakeScale]["ignoretimescale"] = typeof(bool); // STAB mappings.Add(iTweenEvent.TweenType.Stab, new Dictionary<string, Type>()); mappings[iTweenEvent.TweenType.Stab]["audioclip"] = typeof(AudioClip); mappings[iTweenEvent.TweenType.Stab]["audiosource"] = typeof(AudioSource); mappings[iTweenEvent.TweenType.Stab]["volume"] = typeof(float); mappings[iTweenEvent.TweenType.Stab]["pitch"] = typeof(float); mappings[iTweenEvent.TweenType.Stab]["delay"] = typeof(float); mappings[iTweenEvent.TweenType.Stab]["onstart"] = typeof(string); mappings[iTweenEvent.TweenType.Stab]["onstarttarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.Stab]["onstartparams"] = typeof(string); mappings[iTweenEvent.TweenType.Stab]["onupdate"] = typeof(string); mappings[iTweenEvent.TweenType.Stab]["onupdatetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.Stab]["onupdateparams"] = typeof(string); mappings[iTweenEvent.TweenType.Stab]["oncomplete"] = typeof(string); mappings[iTweenEvent.TweenType.Stab]["oncompletetarget"] = typeof(GameObject); mappings[iTweenEvent.TweenType.Stab]["oncompleteparams"] = typeof(string); } }
zzzstrawhatzzz
trunk/client/Assets/iTweenEditor/Helper Classes/EventParamMappings.cs
C#
asf20
50,844