code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
package com.ch_linghu.fanfoudroid.task; import android.app.ProgressDialog; import android.content.Context; import android.util.Log; import android.widget.Toast; import com.ch_linghu.fanfoudroid.ui.base.WithHeaderActivity; public abstract class TaskFeedback { private static TaskFeedback _instance = null; public static final int DIALOG_MODE = 0x01; public static final int REFRESH_MODE = 0x02; public static final int PROGRESS_MODE = 0x03; public static TaskFeedback getInstance(int type, Context context) { switch (type) { case DIALOG_MODE: _instance = DialogFeedback.getInstance(); break; case REFRESH_MODE: _instance = RefreshAnimationFeedback.getInstance(); break; case PROGRESS_MODE: _instance = ProgressBarFeedback.getInstance(); } _instance.setContext(context); return _instance; } protected Context _context; protected void setContext(Context context) { _context = context; } public Context getContent() { return _context; } // default do nothing public void start(String prompt) {}; public void cancel() {}; public void success(String prompt) {}; public void success() { success(""); }; public void failed(String prompt) {}; public void showProgress(int progress) {}; } /** * */ class DialogFeedback extends TaskFeedback { private static DialogFeedback _instance = null; public static DialogFeedback getInstance() { if (_instance == null) { _instance = new DialogFeedback(); } return _instance; } private ProgressDialog _dialog = null; @Override public void cancel() { if (_dialog != null) { _dialog.dismiss(); } } @Override public void failed(String prompt) { if (_dialog != null) { _dialog.dismiss(); } Toast toast = Toast.makeText(_context, prompt, Toast.LENGTH_LONG); toast.show(); } @Override public void start(String prompt) { _dialog = ProgressDialog.show(_context, "", prompt, true); _dialog.setCancelable(true); } @Override public void success(String prompt) { if (_dialog != null) { _dialog.dismiss(); } } } /** * */ class RefreshAnimationFeedback extends TaskFeedback { private static RefreshAnimationFeedback _instance = null; public static RefreshAnimationFeedback getInstance() { if (_instance == null) { _instance = new RefreshAnimationFeedback(); } return _instance; } private WithHeaderActivity _activity; @Override protected void setContext(Context context) { super.setContext(context); _activity = (WithHeaderActivity) context; } @Override public void cancel() { _activity.setRefreshAnimation(false); } @Override public void failed(String prompt) { _activity.setRefreshAnimation(false); Toast toast = Toast.makeText(_context, prompt, Toast.LENGTH_LONG); toast.show(); } @Override public void start(String prompt) { _activity.setRefreshAnimation(true); } @Override public void success(String prompt) { _activity.setRefreshAnimation(false); } } /** * */ class ProgressBarFeedback extends TaskFeedback { private static ProgressBarFeedback _instance = null; public static ProgressBarFeedback getInstance() { if (_instance == null) { _instance = new ProgressBarFeedback(); } return _instance; } private WithHeaderActivity _activity; @Override protected void setContext(Context context) { super.setContext(context); _activity = (WithHeaderActivity) context; } @Override public void cancel() { _activity.setGlobalProgress(0); } @Override public void failed(String prompt) { cancel(); Toast toast = Toast.makeText(_context, prompt, Toast.LENGTH_LONG); toast.show(); } @Override public void start(String prompt) { _activity.setGlobalProgress(10); } @Override public void success(String prompt) { Log.d("LDS", "ON SUCCESS"); _activity.setGlobalProgress(0); } @Override public void showProgress(int progress) { _activity.setGlobalProgress(progress); } // mProgress.setIndeterminate(true); }
zzunpzcmmk870208-mmk
src/com/ch_linghu/fanfoudroid/task/TaskFeedback.java
Java
asf20
4,562
package com.ch_linghu.fanfoudroid.task; public abstract class TaskAdapter implements TaskListener { public abstract String getName(); public void onPreExecute(GenericTask task) {}; public void onPostExecute(GenericTask task, TaskResult result) {}; public void onProgressUpdate(GenericTask task, Object param) {}; public void onCancelled(GenericTask task) {}; }
zzunpzcmmk870208-mmk
src/com/ch_linghu/fanfoudroid/task/TaskAdapter.java
Java
asf20
384
package com.ch_linghu.fanfoudroid.task; import android.util.Log; import com.ch_linghu.fanfoudroid.TwitterApplication; import com.ch_linghu.fanfoudroid.data.Tweet; import com.ch_linghu.fanfoudroid.db.StatusTable; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.ui.base.BaseActivity; public class TweetCommonTask { public static class DeleteTask extends GenericTask{ public static final String TAG="DeleteTask"; private BaseActivity activity; public DeleteTask(BaseActivity activity){ this.activity = activity; } @Override protected TaskResult _doInBackground(TaskParams... params) { TaskParams param = params[0]; try { String id = param.getString("id"); com.ch_linghu.fanfoudroid.fanfou.Status status = null; status = activity.getApi().destroyStatus(id); // 对所有相关表的对应消息都进行删除(如果存在的话) activity.getDb().deleteTweet(status.getId(), "", -1); } catch (HttpException e) { Log.e(TAG, e.getMessage(), e); return TaskResult.IO_ERROR; } return TaskResult.OK; } } public static class FavoriteTask extends GenericTask{ private static final String TAG = "FavoriteTask"; private BaseActivity activity; public static final String TYPE_ADD = "add"; public static final String TYPE_DEL = "del"; private String type; public String getType(){ return type; } public FavoriteTask(BaseActivity activity){ this.activity = activity; } @Override protected TaskResult _doInBackground(TaskParams...params){ TaskParams param = params[0]; try { String action = param.getString("action"); String id = param.getString("id"); com.ch_linghu.fanfoudroid.fanfou.Status status = null; if (action.equals(TYPE_ADD)) { status = activity.getApi().createFavorite(id); activity.getDb().setFavorited(id, "true"); type = TYPE_ADD; } else { status = activity.getApi().destroyFavorite(id); activity.getDb().setFavorited(id, "false"); type = TYPE_DEL; } Tweet tweet = Tweet.create(status); // if (!Utils.isEmpty(tweet.profileImageUrl)) { // // Fetch image to cache. // try { // activity.getImageManager().put(tweet.profileImageUrl); // } catch (IOException e) { // Log.e(TAG, e.getMessage(), e); // } // } if(action.equals(TYPE_DEL)){ activity.getDb().deleteTweet(tweet.id, TwitterApplication.getMyselfId(), StatusTable.TYPE_FAVORITE); } } catch (HttpException e) { Log.e(TAG, e.getMessage(), e); return TaskResult.IO_ERROR; } return TaskResult.OK; } } // public static class UserTask extends GenericTask{ // // @Override // protected TaskResult _doInBackground(TaskParams... params) { // // TODO Auto-generated method stub // return null; // } // // } }
zzunpzcmmk870208-mmk
src/com/ch_linghu/fanfoudroid/task/TweetCommonTask.java
Java
asf20
2,898
package com.ch_linghu.fanfoudroid.task; import java.util.HashMap; import org.json.JSONException; import com.ch_linghu.fanfoudroid.http.HttpException; /** * 暂未使用,待观察是否今后需要此类 * @author lds * */ public class TaskParams { private HashMap<String, Object> params = null; public TaskParams() { params = new HashMap<String, Object>(); } public TaskParams(String key, Object value) { this(); put(key, value); } public void put(String key, Object value) { params.put(key, value); } public Object get(String key) { return params.get(key); } /** * Get the boolean value associated with a key. * * @param key A key string. * @return The truth. * @throws HttpException * if the value is not a Boolean or the String "true" or "false". */ public boolean getBoolean(String key) throws HttpException { Object object = get(key); if (object.equals(Boolean.FALSE) || (object instanceof String && ((String)object).equalsIgnoreCase("false"))) { return false; } else if (object.equals(Boolean.TRUE) || (object instanceof String && ((String)object).equalsIgnoreCase("true"))) { return true; } throw new HttpException(key + " is not a Boolean."); } /** * Get the double value associated with a key. * @param key A key string. * @return The numeric value. * @throws HttpException if the key is not found or * if the value is not a Number object and cannot be converted to a number. */ public double getDouble(String key) throws HttpException { Object object = get(key); try { return object instanceof Number ? ((Number)object).doubleValue() : Double.parseDouble((String)object); } catch (Exception e) { throw new HttpException(key + " is not a number."); } } /** * Get the int value associated with a key. * * @param key A key string. * @return The integer value. * @throws HttpException if the key is not found or if the value cannot * be converted to an integer. */ public int getInt(String key) throws HttpException { Object object = get(key); try { return object instanceof Number ? ((Number)object).intValue() : Integer.parseInt((String)object); } catch (Exception e) { throw new HttpException(key + " is not an int."); } } /** * Get the string associated with a key. * * @param key A key string. * @return A string which is the value. * @throws JSONException if the key is not found. */ public String getString(String key) throws HttpException { Object object = get(key); return object == null ? null : object.toString(); } /** * Determine if the JSONObject contains a specific key. * @param key A key string. * @return true if the key exists in the JSONObject. */ public boolean has(String key) { return this.params.containsKey(key); } }
zzunpzcmmk870208-mmk
src/com/ch_linghu/fanfoudroid/task/TaskParams.java
Java
asf20
3,288
package com.ch_linghu.fanfoudroid.task; public interface TaskListener { String getName(); void onPreExecute(GenericTask task); void onPostExecute(GenericTask task, TaskResult result); void onProgressUpdate(GenericTask task, Object param); void onCancelled(GenericTask task); }
zzunpzcmmk870208-mmk
src/com/ch_linghu/fanfoudroid/task/TaskListener.java
Java
asf20
285
package com.ch_linghu.fanfoudroid.task; import java.util.Observable; import java.util.Observer; import android.os.AsyncTask; import android.util.Log; import android.widget.Toast; import com.ch_linghu.fanfoudroid.TwitterApplication; import com.ch_linghu.fanfoudroid.ui.module.Feedback; public abstract class GenericTask extends AsyncTask<TaskParams, Object, TaskResult> implements Observer { private static final String TAG = "TaskManager"; private TaskListener mListener = null; private Feedback mFeedback = null; private boolean isCancelable = true; abstract protected TaskResult _doInBackground(TaskParams... params); public void setListener(TaskListener taskListener) { mListener = taskListener; } public TaskListener getListener() { return mListener; } public void doPublishProgress(Object... values) { super.publishProgress(values); } @Override protected void onCancelled() { super.onCancelled(); if (mListener != null) { mListener.onCancelled(this); } Log.d(TAG, mListener.getName() + " has been Cancelled."); Toast.makeText(TwitterApplication.mContext, mListener.getName() + " has been cancelled", Toast.LENGTH_SHORT); } @Override protected void onPostExecute(TaskResult result) { super.onPostExecute(result); if (mListener != null) { mListener.onPostExecute(this, result); } if (mFeedback != null) { mFeedback.success(""); } /* Toast.makeText(TwitterApplication.mContext, mListener.getName() + " completed", Toast.LENGTH_SHORT); */ } @Override protected void onPreExecute() { super.onPreExecute(); if (mListener != null) { mListener.onPreExecute(this); } if (mFeedback != null) { mFeedback.start(""); } } @Override protected void onProgressUpdate(Object... values) { super.onProgressUpdate(values); if (mListener != null) { if (values != null && values.length > 0) { mListener.onProgressUpdate(this, values[0]); } } if (mFeedback != null) { mFeedback.update(values[0]); } } @Override protected TaskResult doInBackground(TaskParams... params) { TaskResult result = _doInBackground(params); if (mFeedback != null) { mFeedback.update(99); } return result; } public void update(Observable o, Object arg) { if (TaskManager.CANCEL_ALL == (Integer) arg && isCancelable) { if (getStatus() == GenericTask.Status.RUNNING) { cancel(true); } } } public void setCancelable(boolean flag) { isCancelable = flag; } public void setFeedback(Feedback feedback) { mFeedback = feedback; } }
zzunpzcmmk870208-mmk
src/com/ch_linghu/fanfoudroid/task/GenericTask.java
Java
asf20
3,039
package com.ch_linghu.fanfoudroid.task; import java.util.Observable; import java.util.Observer; import android.util.Log; public class TaskManager extends Observable { private static final String TAG = "TaskManager"; public static final Integer CANCEL_ALL = 1; public void cancelAll() { Log.d(TAG, "All task Cancelled."); setChanged(); notifyObservers(CANCEL_ALL); } public void addTask(Observer task) { super.addObserver(task); } }
zzunpzcmmk870208-mmk
src/com/ch_linghu/fanfoudroid/task/TaskManager.java
Java
asf20
505
/* * Copyright (C) 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ch_linghu.fanfoudroid; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.text.Editable; import android.text.TextUtils; import android.text.TextWatcher; import android.util.Log; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.CursorAdapter; import android.widget.EditText; import android.widget.TextView; import com.ch_linghu.fanfoudroid.data.Dm; import com.ch_linghu.fanfoudroid.db.StatusTable; import com.ch_linghu.fanfoudroid.db.TwitterDatabase; import com.ch_linghu.fanfoudroid.fanfou.DirectMessage; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.task.GenericTask; import com.ch_linghu.fanfoudroid.task.TaskAdapter; import com.ch_linghu.fanfoudroid.task.TaskListener; import com.ch_linghu.fanfoudroid.task.TaskParams; import com.ch_linghu.fanfoudroid.task.TaskResult; import com.ch_linghu.fanfoudroid.ui.base.BaseActivity; import com.ch_linghu.fanfoudroid.ui.module.NavBar; import com.ch_linghu.fanfoudroid.ui.module.TweetEdit; //FIXME: 将WriteDmActivity和WriteActivity进行整合。 /** * 撰写私信界面 * @author lds * */ public class WriteDmActivity extends BaseActivity { public static final String NEW_TWEET_ACTION = "com.ch_linghu.fanfoudroid.NEW"; public static final String EXTRA_TEXT = "text"; public static final String REPLY_ID = "reply_id"; private static final String TAG = "WriteActivity"; private static final String SIS_RUNNING_KEY = "running"; private static final String PREFS_NAME = "com.ch_linghu.fanfoudroid"; // View private TweetEdit mTweetEdit; private EditText mTweetEditText; private TextView mProgressText; private Button mSendButton; //private AutoCompleteTextView mToEdit; private TextView mToEdit; private NavBar mNavbar; // Task private GenericTask mSendTask; private TaskListener mSendTaskListener = new TaskAdapter() { @Override public void onPreExecute(GenericTask task) { disableEntry(); updateProgress(getString(R.string.page_status_updating)); } @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.AUTH_ERROR) { logout(); } else if (result == TaskResult.OK) { mToEdit.setText(""); mTweetEdit.setText(""); updateProgress(""); enableEntry(); // 发送成功就直接关闭界面 finish(); // 关闭软键盘 InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(mTweetEdit.getEditText().getWindowToken(), 0); } else if (result == TaskResult.NOT_FOLLOWED_ERROR) { updateProgress(getString(R.string.direct_meesage_status_the_person_not_following_you)); enableEntry(); } else if (result == TaskResult.IO_ERROR) { // TODO: 什么情况下会抛出IO_ERROR?需要给用户更为具体的失败原因 updateProgress(getString(R.string.page_status_unable_to_update)); enableEntry(); } } @Override public String getName() { return "DMSend"; } }; private FriendsAdapter mFriendsAdapter; // Adapter for To: recipient // autocomplete. private static final String EXTRA_USER = "user"; private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.DMSW"; public static Intent createIntent(String user) { Intent intent = new Intent(LAUNCH_ACTION); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); if (!TextUtils.isEmpty(user)) { intent.putExtra(EXTRA_USER, user); } return intent; } // sub menu // protected void createInsertPhotoDialog() { // // final CharSequence[] items = { // getString(R.string.write_label_take_a_picture), // getString(R.string.write_label_choose_a_picture) }; // // AlertDialog.Builder builder = new AlertDialog.Builder(this); // builder.setTitle(getString(R.string.write_label_insert_picture)); // builder.setItems(items, new DialogInterface.OnClickListener() { // public void onClick(DialogInterface dialog, int item) { // // Toast.makeText(getApplicationContext(), items[item], // // Toast.LENGTH_SHORT).show(); // switch (item) { // case 0: // openImageCaptureMenu(); // break; // case 1: // openPhotoLibraryMenu(); // } // } // }); // AlertDialog alert = builder.create(); // alert.show(); // } @Override protected boolean _onCreate(Bundle savedInstanceState) { Log.d(TAG, "onCreate."); if (super._onCreate(savedInstanceState)){ // init View setContentView(R.layout.write_dm); mNavbar = new NavBar(NavBar.HEADER_STYLE_WRITE, this); // Intent & Action & Extras Intent intent = getIntent(); Bundle extras = intent.getExtras(); // View mProgressText = (TextView) findViewById(R.id.progress_text); mTweetEditText = (EditText) findViewById(R.id.tweet_edit); TwitterDatabase db = getDb(); //FIXME: 暂时取消收件人自动完成功能 //FIXME: 可根据目前以后内容重新完成自动完成功能 //mToEdit = (AutoCompleteTextView) findViewById(R.id.to_edit); //Cursor cursor = db.getFollowerUsernames(""); //// startManagingCursor(cursor); //mFriendsAdapter = new FriendsAdapter(this, cursor); //mToEdit.setAdapter(mFriendsAdapter); mToEdit = (TextView) findViewById(R.id.to_edit); // Update status mTweetEdit = new TweetEdit(mTweetEditText, (TextView) findViewById(R.id.chars_text)); mTweetEdit.setOnKeyListener(editEnterHandler); mTweetEdit .addTextChangedListener(new MyTextWatcher(WriteDmActivity.this)); // With extras if (extras != null) { String to = extras.getString(EXTRA_USER); if (!TextUtils.isEmpty(to)) { mToEdit.setText(to); mTweetEdit.requestFocus(); } } View.OnClickListener sendListenner = new View.OnClickListener() { public void onClick(View v) { doSend(); } }; mSendButton = (Button) findViewById(R.id.send_button); mSendButton.setOnClickListener(sendListenner); Button mTopSendButton = (Button) findViewById(R.id.top_send_btn); mTopSendButton.setOnClickListener(sendListenner); return true; }else{ return false; } } @Override protected void onRestoreInstanceState(Bundle bundle) { super.onRestoreInstanceState(bundle); mTweetEdit.updateCharsRemain(); } @Override protected void onPause() { super.onPause(); Log.d(TAG, "onPause."); } @Override protected void onRestart() { super.onRestart(); Log.d(TAG, "onRestart."); } @Override protected void onResume() { super.onResume(); Log.d(TAG, "onResume."); } @Override protected void onStart() { super.onStart(); Log.d(TAG, "onStart."); } @Override protected void onStop() { super.onStop(); Log.d(TAG, "onStop."); } @Override protected void onDestroy() { Log.d(TAG, "onDestroy."); if (mSendTask != null && mSendTask.getStatus() == GenericTask.Status.RUNNING) { // Doesn't really cancel execution (we let it continue running). // See the SendTask code for more details. mSendTask.cancel(true); } // Don't need to cancel FollowersTask (assuming it ends properly). super.onDestroy(); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (mSendTask != null && mSendTask.getStatus() == GenericTask.Status.RUNNING) { outState.putBoolean(SIS_RUNNING_KEY, true); } } public static Intent createNewTweetIntent(String text) { Intent intent = new Intent(NEW_TWEET_ACTION); intent.putExtra(EXTRA_TEXT, text); return intent; } private class MyTextWatcher implements TextWatcher { private WriteDmActivity _activity; public MyTextWatcher(WriteDmActivity activity) { _activity = activity; } @Override public void afterTextChanged(Editable s) { // TODO Auto-generated method stub if (s.length() == 0) { } } @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { // TODO Auto-generated method stub } @Override public void onTextChanged(CharSequence s, int start, int before, int count) { // TODO Auto-generated method stub } } private void doSend() { if (mSendTask != null && mSendTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { String to = mToEdit.getText().toString(); String status = mTweetEdit.getText().toString(); if (!TextUtils.isEmpty(status) && !TextUtils.isEmpty(to)) { mSendTask = new DmSendTask(); mSendTask.setListener(mSendTaskListener); mSendTask.execute(); } else if (TextUtils.isEmpty(status)) { updateProgress(getString(R.string.direct_meesage_status_texting_is_null)); } else if (TextUtils.isEmpty(to)) { updateProgress(getString(R.string.direct_meesage_status_user_is_null)); } } } private class DmSendTask extends GenericTask { @Override protected TaskResult _doInBackground(TaskParams... params) { try { String user = mToEdit.getText().toString(); String text = mTweetEdit.getText().toString(); DirectMessage directMessage = getApi().sendDirectMessage(user, text); Dm dm = Dm.create(directMessage, true); // if (!Utils.isEmpty(dm.profileImageUrl)) { // // Fetch image to cache. // try { // getImageManager().put(dm.profileImageUrl); // } catch (IOException e) { // Log.e(TAG, e.getMessage(), e); // } // } getDb().createDm(dm, false); } catch (HttpException e) { Log.d(TAG, e.getMessage()); // TODO: check is this is actually the case. return TaskResult.NOT_FOLLOWED_ERROR; } return TaskResult.OK; } } private static class FriendsAdapter extends CursorAdapter { public FriendsAdapter(Context context, Cursor cursor) { super(context, cursor); mInflater = LayoutInflater.from(context); mUserTextColumn = cursor .getColumnIndexOrThrow(StatusTable.USER_SCREEN_NAME); } private LayoutInflater mInflater; private int mUserTextColumn; @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { View view = mInflater .inflate(R.layout.dropdown_item, parent, false); ViewHolder holder = new ViewHolder(); holder.userText = (TextView) view.findViewById(android.R.id.text1); view.setTag(holder); return view; } class ViewHolder { public TextView userText; } @Override public void bindView(View view, Context context, Cursor cursor) { ViewHolder holder = (ViewHolder) view.getTag(); holder.userText.setText(cursor.getString(mUserTextColumn)); } @Override public Cursor runQueryOnBackgroundThread(CharSequence constraint) { String filter = constraint == null ? "" : constraint.toString(); return TwitterApplication.mDb.getFollowerUsernames(filter); } @Override public String convertToString(Cursor cursor) { return cursor.getString(mUserTextColumn); } } private void enableEntry() { mTweetEdit.setEnabled(true); mSendButton.setEnabled(true); } private void disableEntry() { mTweetEdit.setEnabled(false); mSendButton.setEnabled(false); } // UI helpers. private void updateProgress(String progress) { mProgressText.setText(progress); } private View.OnKeyListener editEnterHandler = new View.OnKeyListener() { public boolean onKey(View v, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_ENTER || keyCode == KeyEvent.KEYCODE_DPAD_CENTER) { if (event.getAction() == KeyEvent.ACTION_UP) { doSend(); } return true; } return false; } }; }
zzunpzcmmk870208-mmk
src/com/ch_linghu/fanfoudroid/WriteDmActivity.java
Java
asf20
12,540
/* * Copyright (C) 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ch_linghu.fanfoudroid; import java.util.ArrayList; import java.util.List; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.os.Bundle; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.AdapterContextMenuInfo; import com.ch_linghu.fanfoudroid.data.Tweet; import com.ch_linghu.fanfoudroid.db.StatusTable; import com.ch_linghu.fanfoudroid.fanfou.Paging; import com.ch_linghu.fanfoudroid.fanfou.Status; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.task.GenericTask; import com.ch_linghu.fanfoudroid.task.TaskAdapter; import com.ch_linghu.fanfoudroid.task.TaskListener; import com.ch_linghu.fanfoudroid.task.TaskParams; import com.ch_linghu.fanfoudroid.task.TaskResult; import com.ch_linghu.fanfoudroid.task.TweetCommonTask; import com.ch_linghu.fanfoudroid.ui.base.TwitterCursorBaseActivity; public class TwitterActivity extends TwitterCursorBaseActivity { private static final String TAG = "TwitterActivity"; private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.TWEETS"; protected GenericTask mDeleteTask; private TaskListener mDeleteTaskListener = new TaskAdapter() { @Override public String getName() { return "DeleteTask"; } @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.AUTH_ERROR) { logout(); } else if (result == TaskResult.OK) { onDeleteSuccess(); } else if (result == TaskResult.IO_ERROR) { onDeleteFailure(); } } }; static final int DIALOG_WRITE_ID = 0; public static Intent createIntent(Context context) { Intent intent = new Intent(LAUNCH_ACTION); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); return intent; } public static Intent createNewTaskIntent(Context context) { Intent intent = createIntent(context); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); return intent; } @Override protected boolean _onCreate(Bundle savedInstanceState) { if (super._onCreate(savedInstanceState)) { mNavbar.setHeaderTitle("饭否fanfou.com"); //仅在这个页面进行schedule的处理 manageUpdateChecks(); return true; } else { return false; } } @Override protected void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); if (mDeleteTask != null && mDeleteTask.getStatus() == GenericTask.Status.RUNNING) { mDeleteTask.cancel(true); } } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (mDeleteTask != null && mDeleteTask.getStatus() == GenericTask.Status.RUNNING) { outState.putBoolean(SIS_RUNNING_KEY, true); } } // Menu. @Override public boolean onCreateOptionsMenu(Menu menu) { return super.onCreateOptionsMenu(menu); } private int CONTEXT_DELETE_ID = getLastContextMenuId() + 1; @Override protected int getLastContextMenuId() { return CONTEXT_DELETE_ID; } @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); AdapterView.AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo; Tweet tweet = getContextItemTweet(info.position); if (null != tweet) {// 当按钮为 刷新/更多的时候为空 if (tweet.userId.equals(TwitterApplication.getMyselfId())) { menu.add(0, CONTEXT_DELETE_ID, 0, R.string.cmenu_delete); } } } @Override public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) item .getMenuInfo(); Tweet tweet = getContextItemTweet(info.position); if (tweet == null) { Log.w(TAG, "Selected item not available."); return super.onContextItemSelected(item); } if (item.getItemId() == CONTEXT_DELETE_ID) { doDelete(tweet.id); return true; } else { return super.onContextItemSelected(item); } } @SuppressWarnings("deprecation") @Override protected Cursor fetchMessages() { return getDb().fetchAllTweets(getUserId(), StatusTable.TYPE_HOME); } @Override protected String getActivityTitle() { return getResources().getString(R.string.page_title_home); } @Override protected void markAllRead() { getDb().markAllTweetsRead(getUserId(), StatusTable.TYPE_HOME); } // hasRetrieveListTask interface @Override public int addMessages(ArrayList<Tweet> tweets, boolean isUnread) { // 获取消息的时候,将status里获取的user也存储到数据库 // ::MARK:: for (Tweet t : tweets) { getDb().createWeiboUserInfo(t.user); } return getDb().putTweets(tweets, getUserId(), StatusTable.TYPE_HOME, isUnread); } @Override public String fetchMaxId() { return getDb().fetchMaxTweetId(getUserId(), StatusTable.TYPE_HOME); } @Override public List<Status> getMessageSinceId(String maxId) throws HttpException { if (maxId != null) { return getApi().getFriendsTimeline(new Paging(maxId)); } else { return getApi().getFriendsTimeline(); } } public void onDeleteFailure() { Log.e(TAG, "Delete failed"); } public void onDeleteSuccess() { mTweetAdapter.refresh(); } private void doDelete(String id) { if (mDeleteTask != null && mDeleteTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { mDeleteTask = new TweetCommonTask.DeleteTask(this); mDeleteTask.setListener(mDeleteTaskListener); TaskParams params = new TaskParams(); params.put("id", id); mDeleteTask.execute(params); } } @Override public String fetchMinId() { return getDb().fetchMinTweetId(getUserId(), StatusTable.TYPE_HOME); } @Override public List<Status> getMoreMessageFromId(String minId) throws HttpException { Paging paging = new Paging(1, 20); paging.setMaxId(minId); return getApi().getFriendsTimeline(paging); } @Override public int getDatabaseType() { return StatusTable.TYPE_HOME; } @Override public String getUserId() { return TwitterApplication.getMyselfId(); } }
zzunpzcmmk870208-mmk
src/com/ch_linghu/fanfoudroid/TwitterActivity.java
Java
asf20
7,741
package com.ch_linghu.fanfoudroid; import java.text.MessageFormat; import java.util.List; import android.content.Intent; import android.os.Bundle; import android.widget.ListView; import com.ch_linghu.fanfoudroid.fanfou.Paging; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.ui.base.UserArrayBaseActivity; import com.ch_linghu.fanfoudroid.ui.module.UserArrayAdapter; public class FollowersActivity extends UserArrayBaseActivity { private ListView mUserList; private UserArrayAdapter mAdapter; private static final String TAG = "FollowersActivity"; private String userId; private String userName; private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.FOLLOWERS"; private static final String USER_ID = "userId"; private static final String USER_NAME = "userName"; private int currentPage=1; private int followersCount=0; private static final double PRE_PAGE_COUNT=100.0;//官方分页为每页100 private int pageCount=0; private String[] ids; @Override protected boolean _onCreate(Bundle savedInstanceState) { Intent intent = getIntent(); Bundle extras = intent.getExtras(); if (extras != null) { this.userId = extras.getString(USER_ID); this.userName = extras.getString(USER_NAME); } else { // 获取登录用户id userId=TwitterApplication.getMyselfId(); userName=TwitterApplication.getMyselfName(); } if (super._onCreate(savedInstanceState)) { String myself = TwitterApplication.getMyselfId(); if(getUserId()==myself){ mNavbar.setHeaderTitle(MessageFormat.format( getString(R.string.profile_followers_count_title), "我")); } else { mNavbar.setHeaderTitle(MessageFormat.format( getString(R.string.profile_followers_count_title), userName)); } return true; }else{ return false; } } public static Intent createIntent(String userId, String userName) { Intent intent = new Intent(LAUNCH_ACTION); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.putExtra(USER_ID, userId); intent.putExtra(USER_NAME, userName); return intent; } @Override public Paging getNextPage() { currentPage+=1; return new Paging(currentPage); } @Override protected String getUserId() { return this.userId; } @Override public Paging getCurrentPage() { return new Paging(this.currentPage); } @Override protected List<com.ch_linghu.fanfoudroid.fanfou.User> getUsers( String userId, Paging page) throws HttpException { return getApi().getFollowersList(userId, page); } }
zzunpzcmmk870208-mmk
src/com/ch_linghu/fanfoudroid/FollowersActivity.java
Java
asf20
2,576
package com.ch_linghu.fanfoudroid; import java.util.ArrayList; import java.util.List; import android.app.SearchManager; import android.content.Context; import android.content.Intent; import android.os.Bundle; import android.text.TextUtils; import android.util.Log; import android.view.KeyEvent; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.BaseAdapter; import android.widget.EditText; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.ch_linghu.fanfoudroid.fanfou.SavedSearch; import com.ch_linghu.fanfoudroid.fanfou.Trend; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.task.GenericTask; import com.ch_linghu.fanfoudroid.task.TaskAdapter; import com.ch_linghu.fanfoudroid.task.TaskListener; import com.ch_linghu.fanfoudroid.task.TaskParams; import com.ch_linghu.fanfoudroid.task.TaskResult; import com.ch_linghu.fanfoudroid.ui.base.BaseActivity; import com.ch_linghu.fanfoudroid.ui.module.Feedback; import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory; import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory.FeedbackType; import com.ch_linghu.fanfoudroid.ui.module.NavBar; import com.ch_linghu.fanfoudroid.util.TextHelper; import com.commonsware.cwac.merge.MergeAdapter; public class SearchActivity extends BaseActivity { private static final String TAG = SearchActivity.class.getSimpleName(); private static final int LOADING = 1; private static final int NETWORKERROR = 2; private static final int SUCCESS = 3; private EditText mSearchEdit; private ListView mSearchSectionList; private TextView trendsTitle; private TextView savedSearchTitle; private MergeAdapter mSearchSectionAdapter; private SearchAdapter trendsAdapter; private SearchAdapter savedSearchesAdapter; private ArrayList<SearchItem> trends; private ArrayList<SearchItem> savedSearch; private String initialQuery; private NavBar mNavbar; private Feedback mFeedback; private GenericTask trendsAndSavedSearchesTask; private TaskListener trendsAndSavedSearchesTaskListener = new TaskAdapter() { @Override public String getName() { return "trendsAndSavedSearchesTask"; } @Override public void onPreExecute(GenericTask task) { } @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.OK) { refreshSearchSectionList(SearchActivity.SUCCESS); } else if (result == TaskResult.IO_ERROR) { refreshSearchSectionList(SearchActivity.NETWORKERROR); Toast.makeText( SearchActivity.this, getResources() .getString( R.string.login_status_network_or_connection_error), Toast.LENGTH_SHORT).show(); } } }; @Override protected boolean _onCreate(Bundle savedInstanceState) { Log.d(TAG, "onCreate()..."); if (super._onCreate(savedInstanceState)) { setContentView(R.layout.search); mNavbar = new NavBar(NavBar.HEADER_STYLE_SEARCH, this); mFeedback = FeedbackFactory.create(this, FeedbackType.PROGRESS); initView(); initSearchSectionList(); refreshSearchSectionList(SearchActivity.LOADING); doGetSavedSearches(); return true; } else { return false; } } private void initView() { mSearchEdit = (EditText) findViewById(R.id.search_edit); mSearchEdit.setOnKeyListener(enterKeyHandler); trendsTitle = (TextView) getLayoutInflater().inflate( R.layout.search_section_header, null); trendsTitle.setText(getResources().getString(R.string.trends_title)); savedSearchTitle = (TextView) getLayoutInflater().inflate( R.layout.search_section_header, null); savedSearchTitle.setText(getResources().getString( R.string.saved_search_title)); mSearchSectionAdapter = new MergeAdapter(); mSearchSectionList = (ListView) findViewById(R.id.search_section_list); mNavbar.getSearchButton().setOnClickListener(new View.OnClickListener() { public void onClick(View v) { initialQuery = mSearchEdit.getText().toString(); startSearch(); } }); } @Override protected void onResume() { Log.d(TAG, "onResume()..."); super.onResume(); } private void doGetSavedSearches() { if (trendsAndSavedSearchesTask != null && trendsAndSavedSearchesTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { trendsAndSavedSearchesTask = new TrendsAndSavedSearchesTask(); trendsAndSavedSearchesTask .setListener(trendsAndSavedSearchesTaskListener); trendsAndSavedSearchesTask.setFeedback(mFeedback); trendsAndSavedSearchesTask.execute(); } } private void initSearchSectionList() { trends = new ArrayList<SearchItem>(); savedSearch = new ArrayList<SearchItem>(); trendsAdapter = new SearchAdapter(this); savedSearchesAdapter = new SearchAdapter(this); mSearchSectionAdapter.addView(savedSearchTitle); mSearchSectionAdapter.addAdapter(savedSearchesAdapter); mSearchSectionAdapter.addView(trendsTitle); mSearchSectionAdapter.addAdapter(trendsAdapter); mSearchSectionList.setAdapter(mSearchSectionAdapter); } /** * 辅助计算位置的类 * * @author jmx * */ class PositionHelper { /** * 返回指定位置属于哪一个小节 * * @param position * 绝对位置 * @return 小节的序号,0是第一小节,1是第二小节, -1为无效位置 */ public int getSectionIndex(int position) { int[] contentLength = new int[2]; contentLength[0] = savedSearchesAdapter.getCount(); contentLength[1] = trendsAdapter.getCount(); if (position > 0 && position < contentLength[0] + 1) { return 0; } else if (position > contentLength[0] + 1 && position < (contentLength[0] + contentLength[1] + 1) + 1) { return 1; } else { return -1; } } /** * 返回指定位置在自己所在小节的相对位置 * * @param position * 绝对位置 * @return 所在小节的相对位置,-1为无效位置 */ public int getRelativePostion(int position) { int[] contentLength = new int[2]; contentLength[0] = savedSearchesAdapter.getCount(); contentLength[1] = trendsAdapter.getCount(); int sectionIndex = getSectionIndex(position); int offset = 0; for (int i = 0; i < sectionIndex; ++i) { offset += contentLength[i] + 1; } return position - offset - 1; } } /** * flag: loading;network error;success */ PositionHelper pos_helper = new PositionHelper(); private void refreshSearchSectionList(int flag) { AdapterView.OnItemClickListener searchSectionListListener = new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) { MergeAdapter adapter = (MergeAdapter) (adapterView.getAdapter()); SearchAdapter subAdapter = (SearchAdapter) adapter .getAdapter(position); // 计算针对subAdapter中的相对位置 int relativePos = pos_helper.getRelativePostion(position); SearchItem item = (SearchItem) (subAdapter.getItem(relativePos)); initialQuery = item.query; startSearch(); } }; if (flag == SearchActivity.LOADING) { mSearchSectionList.setOnItemClickListener(null); savedSearch.clear(); trends.clear(); savedSearchesAdapter.refresh(getString(R.string.search_loading)); trendsAdapter.refresh(getString(R.string.search_loading)); } else if (flag == SearchActivity.NETWORKERROR) { mSearchSectionList.setOnItemClickListener(null); savedSearch.clear(); trends.clear(); savedSearchesAdapter .refresh(getString(R.string.login_status_network_or_connection_error)); trendsAdapter .refresh(getString(R.string.login_status_network_or_connection_error)); } else { savedSearchesAdapter.refresh(savedSearch); trendsAdapter.refresh(trends); } if (flag == SearchActivity.SUCCESS) { mSearchSectionList .setOnItemClickListener(searchSectionListListener); } } protected boolean startSearch() { if (!TextUtils.isEmpty(initialQuery)) { // 以下这个方法在7可用,在8就报空指针 // triggerSearch(initialQuery, null); Intent i = new Intent(this, SearchResultActivity.class); i.putExtra(SearchManager.QUERY, initialQuery); startActivity(i); } else if (TextUtils.isEmpty(initialQuery)) { Toast.makeText(this, getResources().getString(R.string.search_box_null), Toast.LENGTH_SHORT).show(); return false; } return false; } // 搜索框回车键判断 private View.OnKeyListener enterKeyHandler = new View.OnKeyListener() { public boolean onKey(View v, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_ENTER || keyCode == KeyEvent.KEYCODE_DPAD_CENTER) { if (event.getAction() == KeyEvent.ACTION_UP) { initialQuery = mSearchEdit.getText().toString(); startSearch(); } return true; } return false; } }; private class TrendsAndSavedSearchesTask extends GenericTask { Trend[] trendsList; List<SavedSearch> savedSearchsList; @Override protected TaskResult _doInBackground(TaskParams... params) { try { trendsList = getApi().getTrends().getTrends(); savedSearchsList = getApi().getSavedSearches(); } catch (HttpException e) { Log.e(TAG, e.getMessage(), e); return TaskResult.IO_ERROR; } trends.clear(); savedSearch.clear(); for (int i = 0; i < trendsList.length; i++) { SearchItem item = new SearchItem(); item.name = trendsList[i].getName(); item.query = trendsList[i].getQuery(); trends.add(item); } for (int i = 0; i < savedSearchsList.size(); i++) { SearchItem item = new SearchItem(); item.name = savedSearchsList.get(i).getName(); item.query = savedSearchsList.get(i).getQuery(); savedSearch.add(item); } return TaskResult.OK; } } } class SearchItem { public String name; public String query; } class SearchAdapter extends BaseAdapter { protected ArrayList<SearchItem> mSearchList; private Context mContext; protected LayoutInflater mInflater; protected StringBuilder mMetaBuilder; public SearchAdapter(Context context) { mSearchList = new ArrayList<SearchItem>(); mContext = context; mInflater = LayoutInflater.from(mContext); mMetaBuilder = new StringBuilder(); } public SearchAdapter(Context context, String prompt) { this(context); refresh(prompt); } public void refresh(ArrayList<SearchItem> searchList) { mSearchList = searchList; notifyDataSetChanged(); } public void refresh(String prompt) { SearchItem item = new SearchItem(); item.name = prompt; item.query = null; mSearchList.clear(); mSearchList.add(item); notifyDataSetChanged(); } @Override public int getCount() { return mSearchList.size(); } @Override public Object getItem(int position) { return mSearchList.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parent) { View view; if (convertView == null) { view = mInflater.inflate(R.layout.search_section_view, parent, false); TextView text = (TextView) view .findViewById(R.id.search_section_text); view.setTag(text); } else { view = convertView; } TextView text = (TextView) view.getTag(); SearchItem item = mSearchList.get(position); text.setText(item.name); return view; } }
zzunpzcmmk870208-mmk
src/com/ch_linghu/fanfoudroid/SearchActivity.java
Java
asf20
13,735
package com.ch_linghu.fanfoudroid.ui.module; import java.util.ArrayList; import android.content.Context; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.text.TextUtils; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import com.ch_linghu.fanfoudroid.R; import com.ch_linghu.fanfoudroid.TwitterApplication; import com.ch_linghu.fanfoudroid.app.LazyImageLoader.ImageLoaderCallback; import com.ch_linghu.fanfoudroid.app.Preferences; import com.ch_linghu.fanfoudroid.data.Tweet; import com.ch_linghu.fanfoudroid.util.TextHelper; public class TweetArrayAdapter extends BaseAdapter implements TweetAdapter { private static final String TAG = "TweetArrayAdapter"; protected ArrayList<Tweet> mTweets; private Context mContext; protected LayoutInflater mInflater; protected StringBuilder mMetaBuilder; private ImageLoaderCallback callback = new ImageLoaderCallback(){ @Override public void refresh(String url, Bitmap bitmap) { TweetArrayAdapter.this.refresh(); } }; public TweetArrayAdapter(Context context) { mTweets = new ArrayList<Tweet>(); mContext = context; mInflater = LayoutInflater.from(mContext); mMetaBuilder = new StringBuilder(); } @Override public int getCount() { return mTweets.size(); } @Override public Object getItem(int position) { return mTweets.get(position); } @Override public long getItemId(int position) { return position; } private static class ViewHolder { public TextView tweetUserText; public TextView tweetText; public ImageView profileImage; public TextView metaText; public ImageView fav; public ImageView has_image; } @Override public View getView(int position, View convertView, ViewGroup parent) { View view; SharedPreferences pref = TwitterApplication.mPref; //PreferenceManager.getDefaultSharedPreferences(mContext); boolean useProfileImage = pref.getBoolean(Preferences.USE_PROFILE_IMAGE, true); if (convertView == null) { view = mInflater.inflate(R.layout.tweet, parent, false); ViewHolder holder = new ViewHolder(); holder.tweetUserText = (TextView) view .findViewById(R.id.tweet_user_text); holder.tweetText = (TextView) view.findViewById(R.id.tweet_text); holder.profileImage = (ImageView) view .findViewById(R.id.profile_image); holder.metaText = (TextView) view .findViewById(R.id.tweet_meta_text); holder.fav = (ImageView) view.findViewById(R.id.tweet_fav); holder.has_image = (ImageView) view.findViewById(R.id.tweet_has_image); view.setTag(holder); } else { view = convertView; } ViewHolder holder = (ViewHolder) view.getTag(); Tweet tweet = mTweets.get(position); holder.tweetUserText.setText(tweet.screenName); TextHelper.setSimpleTweetText(holder.tweetText, tweet.text); // holder.tweetText.setText(tweet.text, BufferType.SPANNABLE); String profileImageUrl = tweet.profileImageUrl; if (useProfileImage){ if (!TextUtils.isEmpty(profileImageUrl)) { holder.profileImage.setImageBitmap(TwitterApplication.mImageLoader .get(profileImageUrl, callback)); } }else{ holder.profileImage.setVisibility(View.GONE); } holder.metaText.setText(Tweet.buildMetaText(mMetaBuilder, tweet.createdAt, tweet.source, tweet.inReplyToScreenName)); if (tweet.favorited.equals("true")) { holder.fav.setVisibility(View.VISIBLE); } else { holder.fav.setVisibility(View.GONE); } if (!TextUtils.isEmpty(tweet.thumbnail_pic)) { holder.has_image.setVisibility(View.VISIBLE); } else { holder.has_image.setVisibility(View.GONE); } return view; } public void refresh(ArrayList<Tweet> tweets) { mTweets = tweets; notifyDataSetChanged(); } @Override public void refresh() { notifyDataSetChanged(); } }
zzunpzcmmk870208-mmk
src/com/ch_linghu/fanfoudroid/ui/module/TweetArrayAdapter.java
Java
asf20
4,073
package com.ch_linghu.fanfoudroid.ui.module; import android.widget.ListAdapter; public interface TweetAdapter extends ListAdapter{ void refresh(); }
zzunpzcmmk870208-mmk
src/com/ch_linghu/fanfoudroid/ui/module/TweetAdapter.java
Java
asf20
152
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; } }
zzunpzcmmk870208-mmk
src/com/ch_linghu/fanfoudroid/ui/module/MyActivityFlipper.java
Java
asf20
2,183
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; } }
zzunpzcmmk870208-mmk
src/com/ch_linghu/fanfoudroid/ui/module/TweetEdit.java
Java
asf20
2,607
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(); } }
zzunpzcmmk870208-mmk
src/com/ch_linghu/fanfoudroid/ui/module/Widget.java
Java
asf20
1,456
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; } }
zzunpzcmmk870208-mmk
src/com/ch_linghu/fanfoudroid/ui/module/FlingGestureListener.java
Java
asf20
4,636
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; } }
zzunpzcmmk870208-mmk
src/com/ch_linghu/fanfoudroid/ui/module/MyListView.java
Java
asf20
1,620
package com.ch_linghu.fanfoudroid.ui.module; public interface IFlipper { void showNext(); void showPrevious(); }
zzunpzcmmk870208-mmk
src/com/ch_linghu/fanfoudroid/ui/module/IFlipper.java
Java
asf20
122
package com.ch_linghu.fanfoudroid.ui.module; import java.util.ArrayList; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.View.OnClickListener; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.ImageView; import android.widget.TextView; import android.widget.Toast; import com.ch_linghu.fanfoudroid.R; import com.ch_linghu.fanfoudroid.TwitterApplication; import com.ch_linghu.fanfoudroid.app.LazyImageLoader.ImageLoaderCallback; import com.ch_linghu.fanfoudroid.app.Preferences; import com.ch_linghu.fanfoudroid.data.User; import com.ch_linghu.fanfoudroid.fanfou.Weibo; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.task.GenericTask; import com.ch_linghu.fanfoudroid.task.TaskAdapter; import com.ch_linghu.fanfoudroid.task.TaskListener; import com.ch_linghu.fanfoudroid.task.TaskParams; import com.ch_linghu.fanfoudroid.task.TaskResult; //TODO: /* * 用于用户的Adapter */ public class UserArrayAdapter extends BaseAdapter implements TweetAdapter{ private static final String TAG = "UserArrayAdapter"; private static final String USER_ID="userId"; protected ArrayList<User> mUsers; private Context mContext; protected LayoutInflater mInflater; public UserArrayAdapter(Context context) { mUsers = new ArrayList<User>(); mContext = context; mInflater = LayoutInflater.from(mContext); } @Override public int getCount() { return mUsers.size(); } @Override public Object getItem(int position) { return mUsers.get(position); } @Override public long getItemId(int position) { return position; } private static class ViewHolder { public ImageView profileImage; public TextView screenName; public TextView userId; public TextView lastStatus; public TextView followBtn; } @Override public View getView(int position, View convertView, ViewGroup parent) { View view; SharedPreferences pref = TwitterApplication.mPref; //PreferenceManager.getDefaultSharedPreferences(mContext); boolean useProfileImage = pref.getBoolean(Preferences.USE_PROFILE_IMAGE, true); if (convertView == null) { view = mInflater.inflate(R.layout.follower_item, parent, false); ViewHolder holder = new ViewHolder(); holder.profileImage = (ImageView) view.findViewById(R.id.profile_image); holder.screenName = (TextView) view.findViewById(R.id.screen_name); holder.userId = (TextView) view.findViewById(R.id.user_id); //holder.lastStatus = (TextView) view.findViewById(R.id.last_status); holder.followBtn = (TextView) view.findViewById(R.id.follow_btn); view.setTag(holder); } else { view = convertView; } ViewHolder holder = (ViewHolder) view.getTag(); final User user = mUsers.get(position); String profileImageUrl = user.profileImageUrl; if (useProfileImage){ if (!TextUtils.isEmpty(profileImageUrl)) { holder.profileImage.setImageBitmap(TwitterApplication.mImageLoader .get(profileImageUrl, callback)); } }else{ holder.profileImage.setVisibility(View.GONE); } //holder.profileImage.setImageBitmap(ImageManager.mDefaultBitmap); holder.screenName.setText(user.screenName); holder.userId.setText(user.id); //holder.lastStatus.setText(user.lastStatus); holder.followBtn.setText(user.isFollowing ? mContext .getString(R.string.general_del_friend) : mContext .getString(R.string.general_add_friend)); holder.followBtn.setOnClickListener(user.isFollowing?new OnClickListener(){ @Override public void onClick(View v) { //Toast.makeText(mContext, user.name+"following", Toast.LENGTH_SHORT).show(); delFriend(user.id); }}:new OnClickListener(){ @Override public void onClick(View v) { //Toast.makeText(mContext, user.name+"not following", Toast.LENGTH_SHORT).show(); addFriend(user.id); }}); return view; } public void refresh(ArrayList<User> users) { mUsers = users; notifyDataSetChanged(); } @Override public void refresh() { notifyDataSetChanged(); } private ImageLoaderCallback callback = new ImageLoaderCallback(){ @Override public void refresh(String url, Bitmap bitmap) { UserArrayAdapter.this.refresh(); } }; /** * 取消关注 * @param id */ private void delFriend(final String id) { Builder diaBuilder = new AlertDialog.Builder(mContext) .setTitle("关注提示").setMessage("确实要取消关注吗?"); diaBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (cancelFollowingTask != null && cancelFollowingTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { cancelFollowingTask = new CancelFollowingTask(); cancelFollowingTask .setListener(cancelFollowingTaskLinstener); TaskParams params = new TaskParams(); params.put(USER_ID, id); cancelFollowingTask.execute(params); } } }); diaBuilder.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); Dialog dialog = diaBuilder.create(); dialog.show(); } private GenericTask cancelFollowingTask; /** * 取消关注 * * @author Dino * */ private class CancelFollowingTask extends GenericTask { @Override protected TaskResult _doInBackground(TaskParams... params) { try { //TODO:userid String userId=params[0].getString(USER_ID); getApi().destroyFriendship(userId); } catch (HttpException e) { Log.w(TAG, "create friend ship error"); return TaskResult.FAILED; } return TaskResult.OK; } } private TaskListener cancelFollowingTaskLinstener = new TaskAdapter() { @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.OK) { // followingBtn.setText("添加关注"); // isFollowingText.setText(getResources().getString( // R.string.profile_notfollowing)); // followingBtn.setOnClickListener(setfollowingListener); Toast.makeText(mContext, "取消关注成功", Toast.LENGTH_SHORT).show(); } else if (result == TaskResult.FAILED) { Toast.makeText(mContext, "取消关注失败", Toast.LENGTH_SHORT).show(); } } @Override public String getName() { // TODO Auto-generated method stub return null; } }; private GenericTask setFollowingTask; /** * 设置关注 * @param id */ private void addFriend(String id){ Builder diaBuilder = new AlertDialog.Builder(mContext) .setTitle("关注提示").setMessage("确实要添加关注吗?"); diaBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { if (setFollowingTask != null && setFollowingTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { setFollowingTask = new SetFollowingTask(); setFollowingTask .setListener(setFollowingTaskLinstener); TaskParams params = new TaskParams(); setFollowingTask.execute(params); } } }); diaBuilder.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); } }); Dialog dialog = diaBuilder.create(); dialog.show(); } /** * 设置关注 * * @author Dino * */ private class SetFollowingTask extends GenericTask { @Override protected TaskResult _doInBackground(TaskParams... params) { try { String userId=params[0].getString(USER_ID); getApi().createFriendship(userId); } catch (HttpException e) { Log.w(TAG, "create friend ship error"); return TaskResult.FAILED; } return TaskResult.OK; } } private TaskListener setFollowingTaskLinstener = new TaskAdapter() { @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.OK) { // followingBtn.setText("取消关注"); // isFollowingText.setText(getResources().getString( // R.string.profile_isfollowing)); // followingBtn.setOnClickListener(cancelFollowingListener); Toast.makeText(mContext, "关注成功", Toast.LENGTH_SHORT).show(); } else if (result == TaskResult.FAILED) { Toast.makeText(mContext, "关注失败", Toast.LENGTH_SHORT).show(); } } @Override public String getName() { // TODO Auto-generated method stub return null; } }; public Weibo getApi() { return TwitterApplication.mApi; } }
zzunpzcmmk870208-mmk
src/com/ch_linghu/fanfoudroid/ui/module/UserArrayAdapter.java
Java
asf20
9,395
/* * Copyright (C) 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ch_linghu.fanfoudroid.ui.module; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import android.app.Activity; import android.app.Dialog; import android.content.Context; import android.content.Intent; import android.view.Gravity; import android.view.View; import android.view.WindowManager.LayoutParams; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.Button; import android.widget.GridView; import android.widget.SimpleAdapter; import android.widget.Toast; import com.ch_linghu.fanfoudroid.BrowseActivity; import com.ch_linghu.fanfoudroid.DmActivity; import com.ch_linghu.fanfoudroid.FavoritesActivity; import com.ch_linghu.fanfoudroid.FollowersActivity; import com.ch_linghu.fanfoudroid.FollowingActivity; import com.ch_linghu.fanfoudroid.MentionActivity; import com.ch_linghu.fanfoudroid.ProfileActivity; import com.ch_linghu.fanfoudroid.R; import com.ch_linghu.fanfoudroid.TwitterActivity; import com.ch_linghu.fanfoudroid.TwitterApplication; import com.ch_linghu.fanfoudroid.UserTimelineActivity; /** * 顶部主菜单切换浮动层 * * @author lds * */ public class MenuDialog extends Dialog { private static final int PAGE_MINE = 0; private static final int PAGE_PROFILE = 1; private static final int PAGE_FOLLOWERS = 2; private static final int PAGE_FOLLOWING = 3; private static final int PAGE_HOME = 4; private static final int PAGE_MENTIONS = 5; private static final int PAGE_BROWSE = 6; private static final int PAGE_FAVORITES = 7; private static final int PAGE_MESSAGE = 8; private List<int[]> pages = new ArrayList<int[]>(); { pages.add(new int[] { R.drawable.menu_tweets, R.string.pages_mine }); pages.add(new int[] { R.drawable.menu_profile, R.string.pages_profile }); pages.add(new int[] { R.drawable.menu_followers, R.string.pages_followers }); pages.add(new int[] { R.drawable.menu_following, R.string.pages_following }); pages.add(new int[] { R.drawable.menu_list, R.string.pages_home }); pages.add(new int[] { R.drawable.menu_mentions, R.string.pages_mentions }); pages.add(new int[] { R.drawable.menu_listed, R.string.pages_browse }); pages.add(new int[] { R.drawable.menu_favorites, R.string.pages_search }); pages.add(new int[] { R.drawable.menu_create_list, R.string.pages_message }); }; private GridView gridview; public MenuDialog(Context context, boolean cancelable, OnCancelListener cancelListener) { super(context, cancelable, cancelListener); // TODO Auto-generated constructor stub } public MenuDialog(Context context, int theme) { super(context, theme); // TODO Auto-generated constructor stub } public MenuDialog(Context context) { super(context, R.style.Theme_Transparent); setContentView(R.layout.menu_dialog); // setTitle("Custom Dialog"); setCanceledOnTouchOutside(true); // 设置window属性 LayoutParams a = getWindow().getAttributes(); a.gravity = Gravity.TOP; a.dimAmount = 0; // 去背景遮盖 getWindow().setAttributes(a); initMenu(); } public void setPosition(int x, int y) { LayoutParams a = getWindow().getAttributes(); if (-1 != x) a.x = x; if (-1 != y) a.y = y; getWindow().setAttributes(a); } private void goTo(Class<?> cls, Intent intent) { if (getOwnerActivity().getClass() != cls) { dismiss(); intent.setClass(getContext(), cls); getContext().startActivity(intent); } else { String msg = getContext().getString(R.string.page_status_same_page); Toast.makeText(getContext(), msg, Toast.LENGTH_SHORT).show(); } } private void goTo(Class<?> cls){ Intent intent = new Intent(); goTo(cls, intent); } private void initMenu() { // 准备要添加的数据条目 List<Map<String, Object>> items = new ArrayList<Map<String, Object>>(); for (int[] item : pages) { Map<String, Object> map = new HashMap<String, Object>(); map.put("image", item[0]); map.put("title", getContext().getString(item[1]) ); items.add(map); } // 实例化一个适配器 SimpleAdapter adapter = new SimpleAdapter(getContext(), items, // data R.layout.menu_item, // grid item layout new String[] { "title", "image" }, // data's key new int[] { R.id.item_text, R.id.item_image }); // item view id // 获得GridView实例 gridview = (GridView) findViewById(R.id.mygridview); // 将GridView和数据适配器关联 gridview.setAdapter(adapter); } public void bindEvent(Activity activity) { setOwnerActivity(activity); // 绑定监听器 gridview.setOnItemClickListener(new OnItemClickListener() { public void onItemClick(AdapterView<?> parent, View v, int position, long id) { switch (position) { case PAGE_MINE: String user = TwitterApplication.getMyselfId(); String name = TwitterApplication.getMyselfName(); Intent intent = UserTimelineActivity.createIntent(user, name); goTo(UserTimelineActivity.class, intent); break; case PAGE_PROFILE: goTo(ProfileActivity.class); break; case PAGE_FOLLOWERS: goTo(FollowersActivity.class); break; case PAGE_FOLLOWING: goTo(FollowingActivity.class); break; case PAGE_HOME: goTo(TwitterActivity.class); break; case PAGE_MENTIONS: goTo(MentionActivity.class); break; case PAGE_BROWSE: goTo(BrowseActivity.class); break; case PAGE_FAVORITES: goTo(FavoritesActivity.class); break; case PAGE_MESSAGE: goTo(DmActivity.class); break; } } }); Button close_button = (Button) findViewById(R.id.close_menu); close_button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { dismiss(); } }); } }
zzunpzcmmk870208-mmk
src/com/ch_linghu/fanfoudroid/ui/module/MenuDialog.java
Java
asf20
6,885
/** * */ 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(); } }
zzunpzcmmk870208-mmk
src/com/ch_linghu/fanfoudroid/ui/module/UserCursorAdapter.java
Java
asf20
3,566
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); }
zzunpzcmmk870208-mmk
src/com/ch_linghu/fanfoudroid/ui/module/Feedback.java
Java
asf20
377
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); } }
zzunpzcmmk870208-mmk
src/com/ch_linghu/fanfoudroid/ui/module/MyTextView.java
Java
asf20
4,155
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(); } }
zzunpzcmmk870208-mmk
src/com/ch_linghu/fanfoudroid/ui/module/ActivityFlipper.java
Java
asf20
7,900
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(); } }
zzunpzcmmk870208-mmk
src/com/ch_linghu/fanfoudroid/ui/module/SimpleFeedback.java
Java
asf20
3,029
/** * */ package com.ch_linghu.fanfoudroid.ui.module; import java.text.ParseException; import java.util.Date; import android.content.Context; import android.content.SharedPreferences; import android.database.Cursor; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CursorAdapter; import android.widget.ImageView; import android.widget.TextView; import com.ch_linghu.fanfoudroid.R; import com.ch_linghu.fanfoudroid.TwitterApplication; import com.ch_linghu.fanfoudroid.app.Preferences; import com.ch_linghu.fanfoudroid.app.SimpleImageLoader; import com.ch_linghu.fanfoudroid.data.Tweet; import com.ch_linghu.fanfoudroid.db.StatusTable; import com.ch_linghu.fanfoudroid.db.TwitterDatabase; import com.ch_linghu.fanfoudroid.util.TextHelper; public class TweetCursorAdapter extends CursorAdapter implements TweetAdapter { private static final String TAG = "TweetCursorAdapter"; private Context mContext; public TweetCursorAdapter(Context context, Cursor cursor) { super(context, cursor); mContext = context; if (context != null) { mInflater = LayoutInflater.from(context); } if (cursor != null) { //TODO: 可使用: //Tweet tweet = StatusTable.parseCursor(cursor); mUserTextColumn = cursor .getColumnIndexOrThrow(StatusTable.USER_SCREEN_NAME); mTextColumn = cursor.getColumnIndexOrThrow(StatusTable.TEXT); mProfileImageUrlColumn = cursor .getColumnIndexOrThrow(StatusTable.PROFILE_IMAGE_URL); mCreatedAtColumn = cursor .getColumnIndexOrThrow(StatusTable.CREATED_AT); mSourceColumn = cursor.getColumnIndexOrThrow(StatusTable.SOURCE); mInReplyToScreenName = cursor .getColumnIndexOrThrow(StatusTable.IN_REPLY_TO_SCREEN_NAME); mFavorited = cursor.getColumnIndexOrThrow(StatusTable.FAVORITED); mThumbnailPic = cursor.getColumnIndexOrThrow(StatusTable.PIC_THUMB); mMiddlePic = cursor.getColumnIndexOrThrow(StatusTable.PIC_MID); mOriginalPic = cursor.getColumnIndexOrThrow(StatusTable.PIC_ORIG); } mMetaBuilder = new StringBuilder(); } private LayoutInflater mInflater; private int mUserTextColumn; private int mTextColumn; private int mProfileImageUrlColumn; private int mCreatedAtColumn; private int mSourceColumn; private int mInReplyToScreenName; private int mFavorited; private int mThumbnailPic; private int mMiddlePic; private int mOriginalPic; private StringBuilder mMetaBuilder; /* private ProfileImageCacheCallback callback = new ProfileImageCacheCallback(){ @Override public void refresh(String url, Bitmap bitmap) { TweetCursorAdapter.this.refresh(); } }; */ @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { View view = mInflater.inflate(R.layout.tweet, parent, false); TweetCursorAdapter.ViewHolder holder = new ViewHolder(); holder.tweetUserText = (TextView) view .findViewById(R.id.tweet_user_text); holder.tweetText = (TextView) view.findViewById(R.id.tweet_text); holder.profileImage = (ImageView) view.findViewById(R.id.profile_image); holder.metaText = (TextView) view.findViewById(R.id.tweet_meta_text); holder.fav = (ImageView) view.findViewById(R.id.tweet_fav); holder.has_image = (ImageView) view.findViewById(R.id.tweet_has_image); view.setTag(holder); return view; } private static class ViewHolder { public TextView tweetUserText; public TextView tweetText; public ImageView profileImage; public TextView metaText; public ImageView fav; public ImageView has_image; } @Override public void bindView(View view, Context context, Cursor cursor) { TweetCursorAdapter.ViewHolder holder = (TweetCursorAdapter.ViewHolder) view .getTag(); SharedPreferences pref = TwitterApplication.mPref; //PreferenceManager.getDefaultSharedPreferences(mContext);; boolean useProfileImage = pref.getBoolean(Preferences.USE_PROFILE_IMAGE, true); holder.tweetUserText.setText(cursor.getString(mUserTextColumn)); TextHelper.setSimpleTweetText(holder.tweetText, cursor.getString(mTextColumn)); String profileImageUrl = cursor.getString(mProfileImageUrlColumn); if (useProfileImage && !TextUtils.isEmpty(profileImageUrl)) { SimpleImageLoader.display(holder.profileImage, profileImageUrl); } else { holder.profileImage.setVisibility(View.GONE); } if (cursor.getString(mFavorited).equals("true")) { holder.fav.setVisibility(View.VISIBLE); } else { holder.fav.setVisibility(View.GONE); } if (!TextUtils.isEmpty(cursor.getString(mThumbnailPic))) { holder.has_image.setVisibility(View.VISIBLE); } else { holder.has_image.setVisibility(View.GONE); } try { Date createdAt = TwitterDatabase.DB_DATE_FORMATTER.parse(cursor .getString(mCreatedAtColumn)); holder.metaText.setText(Tweet.buildMetaText(mMetaBuilder, createdAt, cursor.getString(mSourceColumn), cursor .getString(mInReplyToScreenName))); } catch (ParseException e) { Log.w(TAG, "Invalid created at data."); } } @Override public void refresh() { getCursor().requery(); } }
zzunpzcmmk870208-mmk
src/com/ch_linghu/fanfoudroid/ui/module/TweetCursorAdapter.java
Java
asf20
5,303
package com.ch_linghu.fanfoudroid.ui.module; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.graphics.drawable.AnimationDrawable; import android.text.TextPaint; import android.util.Log; import android.view.View; import android.view.animation.Animation; import android.view.animation.AnimationUtils; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.ProgressBar; import android.widget.TextView; import com.ch_linghu.fanfoudroid.R; import com.ch_linghu.fanfoudroid.SearchActivity; import com.ch_linghu.fanfoudroid.TwitterActivity; import com.ch_linghu.fanfoudroid.WriteActivity; import com.ch_linghu.fanfoudroid.ui.base.Refreshable; public class NavBar implements Widget { private static final String TAG = "NavBar"; public static final int HEADER_STYLE_HOME = 1; public static final int HEADER_STYLE_WRITE = 2; public static final int HEADER_STYLE_BACK = 3; public static final int HEADER_STYLE_SEARCH = 4; private ImageView mRefreshButton; private ImageButton mSearchButton; private ImageButton mWriteButton; private TextView mTitleButton; private Button mBackButton; private ImageButton mHomeButton; private MenuDialog mDialog; private EditText mSearchEdit; /** @deprecated 已废弃 */ protected AnimationDrawable mRefreshAnimation; private ProgressBar mProgressBar = null; // 进度条(横) private ProgressBar mLoadingProgress = null; // 旋转图标 public NavBar(int style, Context context) { initHeader(style, (Activity) context); } private void initHeader(int style, final Activity activity) { switch (style) { case HEADER_STYLE_HOME: addTitleButtonTo(activity); addWriteButtonTo(activity); addSearchButtonTo(activity); addRefreshButtonTo(activity); break; case HEADER_STYLE_BACK: addBackButtonTo(activity); addWriteButtonTo(activity); addSearchButtonTo(activity); addRefreshButtonTo(activity); break; case HEADER_STYLE_WRITE: addBackButtonTo(activity); break; case HEADER_STYLE_SEARCH: addBackButtonTo(activity); addSearchBoxTo(activity); addSearchButtonTo(activity); break; } } /** * 搜索硬按键行为 * @deprecated 这个不晓得还有没有用, 已经是已经被新的搜索替代的吧 ? */ public boolean onSearchRequested() { /* Intent intent = new Intent(); intent.setClass(this, SearchActivity.class); startActivity(intent); */ return true; } /** * 添加[LOGO/标题]按钮 * @param acticity */ private void addTitleButtonTo(final Activity acticity) { mTitleButton = (TextView) acticity.findViewById(R.id.title); mTitleButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { int top = mTitleButton.getTop(); int height = mTitleButton.getHeight(); int x = top + height; if (null == mDialog) { Log.d(TAG, "Create menu dialog."); mDialog = new MenuDialog(acticity); mDialog.bindEvent(acticity); mDialog.setPosition(-1, x); } // toggle dialog if (mDialog.isShowing()) { mDialog.dismiss(); // 没机会触发 } else { mDialog.show(); } } }); } /** * 设置标题 * @param title */ public void setHeaderTitle(String title) { if (null != mTitleButton) { mTitleButton.setText(title); TextPaint tp = mTitleButton.getPaint(); tp.setFakeBoldText(true); // 中文粗体 } } /** * 设置标题 * @param resource R.string.xxx */ public void setHeaderTitle(int resource) { if (null != mTitleButton) { mTitleButton.setBackgroundResource(resource); } } /** * 添加[刷新]按钮 * @param activity */ private void addRefreshButtonTo(final Activity activity) { mRefreshButton = (ImageView) activity.findViewById(R.id.top_refresh); // FIXME: DELETE ME 暂时取消旋转效果, 测试ProgressBar // refreshButton.setBackgroundResource(R.drawable.top_refresh); // mRefreshAnimation = (AnimationDrawable) // refreshButton.getBackground(); mProgressBar = (ProgressBar) activity.findViewById(R.id.progress_bar); mLoadingProgress = (ProgressBar) activity .findViewById(R.id.top_refresh_progressBar); mRefreshButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { if (activity instanceof Refreshable) { ((Refreshable) activity).doRetrieve(); } else { Log.e(TAG, "The current view " + activity.getClass().getName() + " cann't be retrieved"); } } }); } /** * Start/Stop Top Refresh Button's Animation * * @param animate * start or stop * @deprecated use feedback */ public void setRefreshAnimation(boolean animate) { if (mRefreshAnimation != null) { if (animate) { mRefreshAnimation.start(); } else { mRefreshAnimation.setVisible(true, true); // restart mRefreshAnimation.start(); // goTo frame 0 mRefreshAnimation.stop(); } } else { Log.w(TAG, "mRefreshAnimation is null"); } } /** * 添加[搜索]按钮 * @param activity */ private void addSearchButtonTo(final Activity activity) { mSearchButton = (ImageButton) activity.findViewById(R.id.search); mSearchButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { startSearch(activity); } }); } // 这个方法会在SearchActivity里重写 protected boolean startSearch(final Activity activity) { Intent intent = new Intent(); intent.setClass(activity, SearchActivity.class); activity.startActivity(intent); return true; } /** * 添加[搜索框] * @param activity */ private void addSearchBoxTo(final Activity activity) { mSearchEdit = (EditText) activity.findViewById(R.id.search_edit); } /** * 添加[撰写]按钮 * @param activity */ private void addWriteButtonTo(final Activity activity) { mWriteButton = (ImageButton) activity.findViewById(R.id.writeMessage); mWriteButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // forward to write activity Intent intent = new Intent(); intent.setClass(v.getContext(), WriteActivity.class); v.getContext().startActivity(intent); } }); } /** * 添加[回首页]按钮 * @param activity */ @SuppressWarnings("unused") private void addHomeButton(final Activity activity) { mHomeButton = (ImageButton) activity.findViewById(R.id.home); mHomeButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // 动画 Animation anim = AnimationUtils.loadAnimation(v.getContext(), R.anim.scale_lite); v.startAnimation(anim); // forward to TwitterActivity Intent intent = new Intent(); intent.setClass(v.getContext(), TwitterActivity.class); v.getContext().startActivity(intent); } }); } /** * 添加[返回]按钮 * @param activity */ private void addBackButtonTo(final Activity activity) { mBackButton = (Button) activity.findViewById(R.id.top_back); // 中文粗体 // TextPaint tp = backButton.getPaint(); // tp.setFakeBoldText(true); mBackButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { // Go back to previous activity activity.finish(); } }); } public void destroy() { // dismiss dialog before destroy // to avoid android.view.WindowLeaked Exception if (mDialog != null) { mDialog.dismiss(); mDialog = null; } mRefreshButton = null; mSearchButton = null; mWriteButton = null; mTitleButton = null; mBackButton = null; mHomeButton = null; mSearchButton = null; mSearchEdit = null; mProgressBar = null; mLoadingProgress = null; } public ImageView getRefreshButton() { return mRefreshButton; } public ImageButton getSearchButton() { return mSearchButton; } public ImageButton getWriteButton() { return mWriteButton; } public TextView getTitleButton() { return mTitleButton; } public Button getBackButton() { return mBackButton; } public ImageButton getHomeButton() { return mHomeButton; } public MenuDialog getDialog() { return mDialog; } public EditText getSearchEdit() { return mSearchEdit; } /** @deprecated 已废弃 */ public AnimationDrawable getRefreshAnimation() { return mRefreshAnimation; } public ProgressBar getProgressBar() { return mProgressBar; } public ProgressBar getLoadingProgress() { return mLoadingProgress; } @Override public Context getContext() { if (null != mDialog) { return mDialog.getContext(); } if (null != mTitleButton) { return mTitleButton.getContext(); } return null; } }
zzunpzcmmk870208-mmk
src/com/ch_linghu/fanfoudroid/ui/module/NavBar.java
Java
asf20
10,493
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) {} } }
zzunpzcmmk870208-mmk
src/com/ch_linghu/fanfoudroid/ui/module/FeedbackFactory.java
Java
asf20
1,347
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(); } }
zzunpzcmmk870208-mmk
src/com/ch_linghu/fanfoudroid/ui/base/WithHeaderActivity.java
Java
asf20
8,811
package com.ch_linghu.fanfoudroid.ui.base; import java.util.ArrayList; import java.util.List; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; import com.ch_linghu.fanfoudroid.R; import com.ch_linghu.fanfoudroid.data.Tweet; import com.ch_linghu.fanfoudroid.data.User; import com.ch_linghu.fanfoudroid.fanfou.Paging; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.task.GenericTask; import com.ch_linghu.fanfoudroid.task.TaskAdapter; import com.ch_linghu.fanfoudroid.task.TaskListener; import com.ch_linghu.fanfoudroid.task.TaskManager; import com.ch_linghu.fanfoudroid.task.TaskParams; import com.ch_linghu.fanfoudroid.task.TaskResult; import com.ch_linghu.fanfoudroid.ui.module.SimpleFeedback; import com.ch_linghu.fanfoudroid.ui.module.TweetAdapter; import com.ch_linghu.fanfoudroid.ui.module.UserArrayAdapter; public abstract class UserArrayBaseActivity extends UserListBaseActivity { static final String TAG = "UserArrayBaseActivity"; // Views. protected ListView mUserList; protected UserArrayAdapter mUserListAdapter; protected TextView loadMoreBtn; protected ProgressBar loadMoreGIF; protected TextView loadMoreBtnTop; protected ProgressBar loadMoreGIFTop; protected static int lastPosition = 0; // Tasks. protected TaskManager taskManager = new TaskManager(); private GenericTask mRetrieveTask; private GenericTask mFollowersRetrieveTask; private GenericTask mGetMoreTask;// 每次100用户 public abstract Paging getCurrentPage();// 加载 public abstract Paging getNextPage();// 加载 // protected abstract String[] getIds(); protected abstract List<com.ch_linghu.fanfoudroid.fanfou.User> getUsers( String userId, Paging page) throws HttpException; private ArrayList<com.ch_linghu.fanfoudroid.data.User> allUserList; @Override protected boolean _onCreate(Bundle savedInstanceState) { Log.d(TAG, "onCreate."); if (super._onCreate(savedInstanceState)) { doRetrieve();// 加载第一页 return true; } else { return false; } } @Override public void doRetrieve() { Log.d(TAG, "Attempting retrieve."); if (mRetrieveTask != null && mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { mRetrieveTask = new RetrieveTask(); mRetrieveTask.setFeedback(mFeedback); mRetrieveTask.setListener(mRetrieveTaskListener); mRetrieveTask.execute(); // Add Task to manager taskManager.addTask(mRetrieveTask); } } private TaskListener mRetrieveTaskListener = new TaskAdapter() { @Override public String getName() { return "RetrieveTask"; } @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.AUTH_ERROR) { logout(); } else if (result == TaskResult.OK) { draw(); } updateProgress(""); } @Override public void onPreExecute(GenericTask task) { onRetrieveBegin(); } @Override public void onProgressUpdate(GenericTask task, Object param) { Log.d(TAG, "onProgressUpdate"); draw(); } }; public void updateProgress(String progress) { mProgressText.setText(progress); } public void onRetrieveBegin() { updateProgress(getString(R.string.page_status_refreshing)); } /** * TODO:从API获取当前Followers * * @author Dino * */ private class RetrieveTask extends GenericTask { @Override protected TaskResult _doInBackground(TaskParams... params) { Log.d(TAG, "load RetrieveTask"); List<com.ch_linghu.fanfoudroid.fanfou.User> usersList = null; try { usersList = getUsers(getUserId(), getCurrentPage()); } catch (HttpException e) { e.printStackTrace(); return TaskResult.IO_ERROR; } publishProgress(SimpleFeedback.calProgressBySize(40, 20, usersList)); for (com.ch_linghu.fanfoudroid.fanfou.User user : usersList) { if (isCancelled()) { return TaskResult.CANCELLED; } allUserList.add(User.create(user)); if (isCancelled()) { return TaskResult.CANCELLED; } } return TaskResult.OK; } } @Override protected int getLayoutId() { return R.layout.follower; } @Override protected void setupState() { setTitle(getActivityTitle()); mUserList = (ListView) findViewById(R.id.follower_list); setupListHeader(true); mUserListAdapter = new UserArrayAdapter(this); mUserList.setAdapter(mUserListAdapter); allUserList = new ArrayList<com.ch_linghu.fanfoudroid.data.User>(); } @Override protected String getActivityTitle() { // TODO Auto-generated method stub return null; } @Override protected boolean useBasicMenu() { return true; } @Override protected User getContextItemUser(int position) { // position = position - 1; // 加入footer跳过footer if (position < mUserListAdapter.getCount()) { User item = (User) mUserListAdapter.getItem(position); if (item == null) { return null; } else { return item; } } else { return null; } } /** * TODO:不知道啥用 */ @Override protected void updateTweet(Tweet tweet) { // TODO Auto-generated method stub } @Override protected ListView getUserList() { return mUserList; } @Override protected TweetAdapter getUserAdapter() { return mUserListAdapter; } /** * 绑定listView底部 - 载入更多 NOTE: 必须在listView#setAdapter之前调用 */ protected void setupListHeader(boolean addFooter) { // Add footer to Listview View footer = View.inflate(this, R.layout.listview_footer, null); mUserList.addFooterView(footer, null, true); // Find View loadMoreBtn = (TextView) findViewById(R.id.ask_for_more); loadMoreGIF = (ProgressBar) findViewById(R.id.rectangleProgressBar); } @Override protected void specialItemClicked(int position) { if (position == mUserList.getCount() - 1) { // footer loadMoreGIF.setVisibility(View.VISIBLE); doGetMore(); } } public void doGetMore() { Log.d(TAG, "Attempting getMore."); mFeedback.start(""); if (mGetMoreTask != null && mGetMoreTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { mGetMoreTask = new GetMoreTask(); mGetMoreTask.setListener(getMoreListener); mGetMoreTask.execute(); // Add Task to manager taskManager.addTask(mGetMoreTask); } } private TaskListener getMoreListener = new TaskAdapter() { @Override public String getName() { return "getMore"; } @Override public void onPostExecute(GenericTask task, TaskResult result) { super.onPostExecute(task, result); draw(); mFeedback.success(""); loadMoreGIF.setVisibility(View.GONE); } }; /** * TODO:需要重写,获取下一批用户,按页分100页一次 * * @author Dino * */ private class GetMoreTask extends GenericTask { @Override protected TaskResult _doInBackground(TaskParams... params) { Log.d(TAG, "load RetrieveTask"); List<com.ch_linghu.fanfoudroid.fanfou.User> usersList = null; try { usersList = getUsers(getUserId(), getNextPage()); mFeedback.update(60); } catch (HttpException e) { e.printStackTrace(); return TaskResult.IO_ERROR; } // 将获取到的数据(保存/更新)到数据库 getDb().syncWeiboUsers(usersList); mFeedback.update(100 - (int) Math.floor(usersList.size() * 2)); for (com.ch_linghu.fanfoudroid.fanfou.User user : usersList) { if (isCancelled()) { return TaskResult.CANCELLED; } allUserList.add(User.create(user)); if (isCancelled()) { return TaskResult.CANCELLED; } } mFeedback.update(99); return TaskResult.OK; } } public void draw() { mUserListAdapter.refresh(allUserList); } }
zzunpzcmmk870208-mmk
src/com/ch_linghu/fanfoudroid/ui/base/UserArrayBaseActivity.java
Java
asf20
9,608
/* * 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); } } }
zzunpzcmmk870208-mmk
src/com/ch_linghu/fanfoudroid/ui/base/UserCursorBaseActivity.java
Java
asf20
19,270
package com.ch_linghu.fanfoudroid.ui.base; public interface Refreshable { void doRetrieve(); }
zzunpzcmmk870208-mmk
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_rotate); return true; } protected static final int REQUEST_CODE_LAUNCH_ACTIVITY = 0; protected static final int REQUEST_CODE_PREFERENCES = 1; @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case OPTIONS_MENU_ID_LOGOUT: logout(); return true; case OPTIONS_MENU_ID_SEARCH: onSearchRequested(); return true; case OPTIONS_MENU_ID_PREFERENCES: Intent launchPreferencesIntent = new Intent().setClass(this, PreferencesActivity.class); startActivityForResult(launchPreferencesIntent, REQUEST_CODE_PREFERENCES); return true; case OPTIONS_MENU_ID_ABOUT: //AboutDialog.show(this); Intent intent = new Intent().setClass(this, AboutActivity.class); startActivity(intent); return true; case OPTIONS_MENU_ID_EXIT: exit(); return true; } return super.onOptionsItemSelected(item); } protected void exit() { TwitterService.unschedule(this); Intent i = new Intent(Intent.ACTION_MAIN); i.addCategory(Intent.CATEGORY_HOME); startActivity(i); } protected void launchActivity(Intent intent) { // TODO: probably don't need this result chaining to finish upon logout. // since the subclasses have to check in onResume. startActivityForResult(intent, REQUEST_CODE_LAUNCH_ACTIVITY); } protected void launchDefaultActivity() { Intent intent = new Intent(); intent.setClass(this, TwitterActivity.class); startActivity(intent); } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == REQUEST_CODE_PREFERENCES && resultCode == RESULT_OK) { manageUpdateChecks(); } else if (requestCode == REQUEST_CODE_LAUNCH_ACTIVITY && resultCode == RESULT_LOGOUT) { Log.d(TAG, "Result logout."); handleLoggedOut(); } } protected boolean checkIsLogedIn() { if (!getApi().isLoggedIn()) { Log.d(TAG, "Not logged in."); handleLoggedOut(); return false; } return true; } public static boolean isTrue(Bundle bundle, String key) { return bundle != null && bundle.containsKey(key) && bundle.getBoolean(key); } }
zzunpzcmmk870208-mmk
src/com/ch_linghu/fanfoudroid/ui/base/BaseActivity.java
Java
asf20
10,752
/* * Copyright (C) 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ch_linghu.fanfoudroid.ui.base; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import android.content.Context; import android.content.SharedPreferences; import android.database.Cursor; import android.os.Bundle; import android.util.Log; import android.view.GestureDetector; import android.view.GestureDetector.SimpleOnGestureListener; import android.view.Menu; import android.view.MotionEvent; import android.view.View; import android.view.View.OnTouchListener; import android.widget.ListView; import android.widget.ProgressBar; import android.widget.TextView; import com.ch_linghu.fanfoudroid.R; import com.ch_linghu.fanfoudroid.TwitterApplication; import com.ch_linghu.fanfoudroid.app.Preferences; import com.ch_linghu.fanfoudroid.data.Tweet; import com.ch_linghu.fanfoudroid.db.StatusTable; import com.ch_linghu.fanfoudroid.fanfou.IDs; import com.ch_linghu.fanfoudroid.fanfou.Status; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.task.GenericTask; import com.ch_linghu.fanfoudroid.task.TaskAdapter; import com.ch_linghu.fanfoudroid.task.TaskListener; import com.ch_linghu.fanfoudroid.task.TaskManager; import com.ch_linghu.fanfoudroid.task.TaskParams; import com.ch_linghu.fanfoudroid.task.TaskResult; import com.ch_linghu.fanfoudroid.ui.module.FlingGestureListener; import com.ch_linghu.fanfoudroid.ui.module.MyActivityFlipper; import com.ch_linghu.fanfoudroid.ui.module.SimpleFeedback; import com.ch_linghu.fanfoudroid.ui.module.TweetAdapter; import com.ch_linghu.fanfoudroid.ui.module.TweetCursorAdapter; import com.ch_linghu.fanfoudroid.ui.module.Widget; import com.ch_linghu.fanfoudroid.util.DateTimeHelper; import com.ch_linghu.fanfoudroid.util.DebugTimer; import com.hlidskialf.android.hardware.ShakeListener; /** * TwitterCursorBaseLine用于带有静态数据来源(对应数据库的,与twitter表同构的特定表)的展现 */ public abstract class TwitterCursorBaseActivity extends TwitterListBaseActivity { static final String TAG = "TwitterCursorBaseActivity"; // Views. protected ListView mTweetList; protected TweetCursorAdapter mTweetAdapter; protected View mListHeader; protected View mListFooter; protected TextView loadMoreBtn; protected ProgressBar loadMoreGIF; protected TextView loadMoreBtnTop; protected ProgressBar loadMoreGIFTop; protected static int lastPosition = 0; protected ShakeListener mShaker = null; // Tasks. protected TaskManager taskManager = new TaskManager(); private GenericTask mRetrieveTask; private GenericTask mFollowersRetrieveTask; private GenericTask mGetMoreTask; private int mRetrieveCount = 0; private TaskListener mRetrieveTaskListener = new TaskAdapter() { @Override public String getName() { return "RetrieveTask"; } @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.AUTH_ERROR) { mFeedback.failed("登录信息出错"); logout(); } else if (result == TaskResult.OK) { // TODO: XML处理, GC压力 SharedPreferences.Editor editor = getPreferences().edit(); editor.putLong(Preferences.LAST_TWEET_REFRESH_KEY, DateTimeHelper.getNowTime()); editor.commit(); // TODO: 1. StatusType(DONE) ; if (mRetrieveCount >= StatusTable.MAX_ROW_NUM) { // 只有在取回的数据大于MAX时才做GC, 因为小于时可以保证数据的连续性 getDb().gc(getUserId(), getDatabaseType()); // GC } draw(); if (task == mRetrieveTask) { goTop(); } } else if (result == TaskResult.IO_ERROR) { // FIXME: bad smell if (task == mRetrieveTask) { mFeedback.failed(((RetrieveTask) task).getErrorMsg()); } else if (task == mGetMoreTask) { mFeedback.failed(((GetMoreTask) task).getErrorMsg()); } } else { // do nothing } // 刷新按钮停止旋转 loadMoreGIFTop.setVisibility(View.GONE); loadMoreGIF.setVisibility(View.GONE); // DEBUG if (TwitterApplication.DEBUG) { DebugTimer.stop(); Log.v("DEBUG", DebugTimer.getProfileAsString()); } } @Override public void onPreExecute(GenericTask task) { mRetrieveCount = 0; if (TwitterApplication.DEBUG) { DebugTimer.start(); } } @Override public void onProgressUpdate(GenericTask task, Object param) { Log.d(TAG, "onProgressUpdate"); draw(); } }; private TaskListener mFollowerRetrieveTaskListener = new TaskAdapter() { @Override public String getName() { return "FollowerRetrieve"; } @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.OK) { SharedPreferences sp = getPreferences(); SharedPreferences.Editor editor = sp.edit(); editor.putLong(Preferences.LAST_FOLLOWERS_REFRESH_KEY, DateTimeHelper.getNowTime()); editor.commit(); } else { // Do nothing. } } }; // Refresh data at startup if last refresh was this long ago or greater. private static final long REFRESH_THRESHOLD = 5 * 60 * 1000; // Refresh followers if last refresh was this long ago or greater. private static final long FOLLOWERS_REFRESH_THRESHOLD = 12 * 60 * 60 * 1000; abstract protected void markAllRead(); abstract protected Cursor fetchMessages(); public abstract int getDatabaseType(); public abstract String getUserId(); public abstract String fetchMaxId(); public abstract String fetchMinId(); public abstract int addMessages(ArrayList<Tweet> tweets, boolean isUnread); public abstract List<Status> getMessageSinceId(String maxId) throws HttpException; public abstract List<Status> getMoreMessageFromId(String minId) throws HttpException; public static final int CONTEXT_REPLY_ID = Menu.FIRST + 1; // public static final int CONTEXT_AT_ID = Menu.FIRST + 2; public static final int CONTEXT_RETWEET_ID = Menu.FIRST + 3; public static final int CONTEXT_DM_ID = Menu.FIRST + 4; public static final int CONTEXT_MORE_ID = Menu.FIRST + 5; public static final int CONTEXT_ADD_FAV_ID = Menu.FIRST + 6; public static final int CONTEXT_DEL_FAV_ID = Menu.FIRST + 7; @Override protected void setupState() { Cursor cursor; cursor = fetchMessages(); // getDb().fetchMentions(); setTitle(getActivityTitle()); startManagingCursor(cursor); mTweetList = (ListView) findViewById(R.id.tweet_list); // TODO: 需处理没有数据时的情况 Log.d("LDS", cursor.getCount() + " cursor count"); setupListHeader(true); mTweetAdapter = new TweetCursorAdapter(this, cursor); mTweetList.setAdapter(mTweetAdapter); // ? registerOnClickListener(mTweetList); } /** * 绑定listView底部 - 载入更多 NOTE: 必须在listView#setAdapter之前调用 */ protected void setupListHeader(boolean addFooter) { // Add Header to ListView mListHeader = View.inflate(this, R.layout.listview_header, null); mTweetList.addHeaderView(mListHeader, null, true); // Add Footer to ListView mListFooter = View.inflate(this, R.layout.listview_footer, null); mTweetList.addFooterView(mListFooter, null, true); // Find View loadMoreBtn = (TextView) findViewById(R.id.ask_for_more); loadMoreGIF = (ProgressBar) findViewById(R.id.rectangleProgressBar); loadMoreBtnTop = (TextView) findViewById(R.id.ask_for_more_header); loadMoreGIFTop = (ProgressBar) findViewById(R.id.rectangleProgressBar_header); } @Override protected void specialItemClicked(int position) { // 注意 mTweetAdapter.getCount 和 mTweetList.getCount的区别 // 前者仅包含数据的数量(不包括foot和head),后者包含foot和head // 因此在同时存在foot和head的情况下,list.count = adapter.count + 2 if (position == 0) { // 第一个Item(header) loadMoreGIFTop.setVisibility(View.VISIBLE); doRetrieve(); } else if (position == mTweetList.getCount() - 1) { // 最后一个Item(footer) loadMoreGIF.setVisibility(View.VISIBLE); doGetMore(); } } @Override protected int getLayoutId() { return R.layout.main; } @Override protected ListView getTweetList() { return mTweetList; } @Override protected TweetAdapter getTweetAdapter() { return mTweetAdapter; } @Override protected boolean useBasicMenu() { return true; } @Override protected Tweet getContextItemTweet(int position) { position = position - 1; // 因为List加了Header和footer,所以要跳过第一个以及忽略最后一个 if (position >= 0 && position < mTweetAdapter.getCount()) { Cursor cursor = (Cursor) mTweetAdapter.getItem(position); if (cursor == null) { return null; } else { return StatusTable.parseCursor(cursor); } } else { return null; } } @Override protected void updateTweet(Tweet tweet) { // TODO: updateTweet() 在哪里调用的? 目前尚只支持: // updateTweet(String tweetId, ContentValues values) // setFavorited(String tweetId, String isFavorited) // 看是否还需要增加updateTweet(Tweet tweet)方法 // 对所有相关表的对应消息都进行刷新(如果存在的话) // getDb().updateTweet(TwitterDbAdapter.TABLE_FAVORITE, tweet); // getDb().updateTweet(TwitterDbAdapter.TABLE_MENTION, tweet); // getDb().updateTweet(TwitterDbAdapter.TABLE_TWEET, tweet); } @Override protected boolean _onCreate(Bundle savedInstanceState) { Log.d(TAG, "onCreate."); if (super._onCreate(savedInstanceState)) { goTop(); // skip the header // Mark all as read. // getDb().markAllMentionsRead(); markAllRead(); boolean shouldRetrieve = false; // FIXME: 该子类页面全部使用了这个统一的计时器,导致进入Mention等分页面后经常不会自动刷新 long lastRefreshTime = mPreferences.getLong( Preferences.LAST_TWEET_REFRESH_KEY, 0); long nowTime = DateTimeHelper.getNowTime(); long diff = nowTime - lastRefreshTime; Log.d(TAG, "Last refresh was " + diff + " ms ago."); if (diff > REFRESH_THRESHOLD) { shouldRetrieve = true; } else if (isTrue(savedInstanceState, SIS_RUNNING_KEY)) { // Check to see if it was running a send or retrieve task. // It makes no sense to resend the send request (don't want // dupes) // so we instead retrieve (refresh) to see if the message has // posted. Log.d(TAG, "Was last running a retrieve or send task. Let's refresh."); shouldRetrieve = true; } if (shouldRetrieve) { doRetrieve(); } long lastFollowersRefreshTime = mPreferences.getLong( Preferences.LAST_FOLLOWERS_REFRESH_KEY, 0); diff = nowTime - lastFollowersRefreshTime; Log.d(TAG, "Last followers refresh was " + diff + " ms ago."); // FIXME: 目前还没有对Followers列表做逻辑处理,因此暂时去除对Followers的获取。 // 未来需要实现@用户提示时,对Follower操作需要做一次review和refactoring // 现在频繁会出现主键冲突的问题。 // // Should Refresh Followers // if (diff > FOLLOWERS_REFRESH_THRESHOLD // && (mRetrieveTask == null || mRetrieveTask.getStatus() != // GenericTask.Status.RUNNING)) { // Log.d(TAG, "Refresh followers."); // doRetrieveFollowers(); // } // 手势识别 registerGestureListener(); //晃动刷新 registerShakeListener(); return true; } else { return false; } } @Override protected void onResume() { Log.d(TAG, "onResume."); if (lastPosition != 0) { mTweetList.setSelection(lastPosition); } if (mShaker != null){ mShaker.resume(); } super.onResume(); checkIsLogedIn(); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (mRetrieveTask != null && mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) { outState.putBoolean(SIS_RUNNING_KEY, true); } } @Override protected void onRestoreInstanceState(Bundle bundle) { super.onRestoreInstanceState(bundle); // mTweetEdit.updateCharsRemain(); } @Override protected void onDestroy() { Log.d(TAG, "onDestroy."); super.onDestroy(); taskManager.cancelAll(); } @Override protected void onPause() { Log.d(TAG, "onPause."); if (mShaker != null){ mShaker.pause(); } super.onPause(); lastPosition = mTweetList.getFirstVisiblePosition(); } @Override protected void onRestart() { Log.d(TAG, "onRestart."); super.onRestart(); } @Override protected void onStart() { Log.d(TAG, "onStart."); super.onStart(); } @Override protected void onStop() { Log.d(TAG, "onStop."); super.onStop(); } // UI helpers. @Override protected String getActivityTitle() { return null; } @Override protected void adapterRefresh() { mTweetAdapter.notifyDataSetChanged(); mTweetAdapter.refresh(); } // Retrieve interface public void updateProgress(String progress) { mProgressText.setText(progress); } public void draw() { mTweetAdapter.refresh(); } public void goTop() { Log.d(TAG, "goTop."); mTweetList.setSelection(1); } private void doRetrieveFollowers() { Log.d(TAG, "Attempting followers retrieve."); if (mFollowersRetrieveTask != null && mFollowersRetrieveTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { mFollowersRetrieveTask = new FollowersRetrieveTask(); mFollowersRetrieveTask.setListener(mFollowerRetrieveTaskListener); mFollowersRetrieveTask.execute(); taskManager.addTask(mFollowersRetrieveTask); // Don't need to cancel FollowersTask (assuming it ends properly). mFollowersRetrieveTask.setCancelable(false); } } public void doRetrieve() { Log.d(TAG, "Attempting retrieve."); if (mRetrieveTask != null && mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { mRetrieveTask = new RetrieveTask(); mRetrieveTask.setFeedback(mFeedback); mRetrieveTask.setListener(mRetrieveTaskListener); mRetrieveTask.execute(); // Add Task to manager taskManager.addTask(mRetrieveTask); } } private class RetrieveTask extends GenericTask { private String _errorMsg; public String getErrorMsg() { return _errorMsg; } @Override protected TaskResult _doInBackground(TaskParams... params) { List<com.ch_linghu.fanfoudroid.fanfou.Status> statusList; try { String maxId = fetchMaxId(); // getDb().fetchMaxMentionId(); statusList = getMessageSinceId(maxId); } catch (HttpException e) { Log.e(TAG, e.getMessage(), e); _errorMsg = e.getMessage(); return TaskResult.IO_ERROR; } ArrayList<Tweet> tweets = new ArrayList<Tweet>(); for (com.ch_linghu.fanfoudroid.fanfou.Status status : statusList) { if (isCancelled()) { return TaskResult.CANCELLED; } tweets.add(Tweet.create(status)); if (isCancelled()) { return TaskResult.CANCELLED; } } publishProgress(SimpleFeedback.calProgressBySize(40, 20, tweets)); mRetrieveCount = addMessages(tweets, false); return TaskResult.OK; } } private class FollowersRetrieveTask extends GenericTask { @Override protected TaskResult _doInBackground(TaskParams... params) { try { // TODO: 目前仅做新API兼容性改动,待完善Follower处理 IDs followers = getApi().getFollowersIDs(); List<String> followerIds = Arrays.asList(followers.getIDs()); getDb().syncFollowers(followerIds); } catch (HttpException e) { Log.e(TAG, e.getMessage(), e); return TaskResult.IO_ERROR; } return TaskResult.OK; } } // GET MORE TASK private class GetMoreTask extends GenericTask { private String _errorMsg; public String getErrorMsg() { return _errorMsg; } @Override protected TaskResult _doInBackground(TaskParams... params) { List<com.ch_linghu.fanfoudroid.fanfou.Status> statusList; String minId = fetchMinId(); // getDb().fetchMaxMentionId(); if (minId == null) { return TaskResult.FAILED; } try { statusList = getMoreMessageFromId(minId); } catch (HttpException e) { Log.e(TAG, e.getMessage(), e); _errorMsg = e.getMessage(); return TaskResult.IO_ERROR; } if (statusList == null) { return TaskResult.FAILED; } ArrayList<Tweet> tweets = new ArrayList<Tweet>(); publishProgress(SimpleFeedback.calProgressBySize(40, 20, tweets)); for (com.ch_linghu.fanfoudroid.fanfou.Status status : statusList) { if (isCancelled()) { return TaskResult.CANCELLED; } tweets.add(Tweet.create(status)); if (isCancelled()) { return TaskResult.CANCELLED; } } addMessages(tweets, false); // getDb().addMentions(tweets, false); return TaskResult.OK; } } public void doGetMore() { Log.d(TAG, "Attempting getMore."); if (mGetMoreTask != null && mGetMoreTask.getStatus() == GenericTask.Status.RUNNING) { return; } else { mGetMoreTask = new GetMoreTask(); mGetMoreTask.setFeedback(mFeedback); mGetMoreTask.setListener(mRetrieveTaskListener); mGetMoreTask.execute(); // Add Task to manager taskManager.addTask(mGetMoreTask); } } //////////////////// Gesture test ///////////////////////////////////// private static boolean useGestrue; { useGestrue = TwitterApplication.mPref.getBoolean( Preferences.USE_GESTRUE, false); if (useGestrue) { Log.v(TAG, "Using Gestrue!"); } else { Log.v(TAG, "Not Using Gestrue!"); } } //////////////////// Gesture test ///////////////////////////////////// private static boolean useShake; { useShake = TwitterApplication.mPref.getBoolean( Preferences.USE_SHAKE, false); if (useShake) { Log.v(TAG, "Using Shake to refresh!"); } else { Log.v(TAG, "Not Using Shake!"); } } protected FlingGestureListener myGestureListener = null; @Override public boolean onTouchEvent(MotionEvent event) { if (useGestrue && myGestureListener != null) { return myGestureListener.getDetector().onTouchEvent(event); } return super.onTouchEvent(event); } // use it in _onCreate private void registerGestureListener() { if (useGestrue) { myGestureListener = new FlingGestureListener(this, MyActivityFlipper.create(this)); getTweetList().setOnTouchListener(myGestureListener); } } // use it in _onCreate private void registerShakeListener() { if (useShake){ mShaker = new ShakeListener(this); mShaker.setOnShakeListener(new ShakeListener.OnShakeListener() { @Override public void onShake() { doRetrieve(); } }); } } }
zzunpzcmmk870208-mmk
src/com/ch_linghu/fanfoudroid/ui/base/TwitterCursorBaseActivity.java
Java
asf20
22,549
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 { }
zzunpzcmmk870208-mmk
src/com/ch_linghu/fanfoudroid/ui/base/BaseListActivity.java
Java
asf20
1,243
/* * 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); } } }
zzunpzcmmk870208-mmk
src/com/ch_linghu/fanfoudroid/ui/base/TwitterListBaseActivity.java
Java
asf20
9,533
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); } } }
zzunpzcmmk870208-mmk
src/com/ch_linghu/fanfoudroid/ui/base/UserListBaseActivity.java
Java
asf20
17,159
/*** 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()!"); } }
zzunpzcmmk870208-mmk
src/com/commonsware/cwac/sacklist/SackOfViewsAdapter.java
Java
asf20
4,593
/*** 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(); } } }
zzunpzcmmk870208-mmk
src/com/commonsware/cwac/merge/MergeAdapter.java
Java
asf20
8,420
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]; } } }
zzunpzcmmk870208-mmk
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}
zzunpzcmmk870208-mmk
doc/stylesheet.css
CSS
asf20
1,370
// ================================================== // read the solution from the website // created by lv zhipeng // ================================================== #include <stdio.h> #include <string.h> #include <assert.h> #include <time.h> #include <stdlib.h> #include"functions.h" //FILE *solRead; void solutionStandardRead( char s[NURSE_NUM][DAY_NUM], char ins_name[] ){ FILE *solRead; errno_t err; err = fopen_s(&solRead,ins_name, "r"); //err = fopen_s(&solRead,"sprint_late05_sol.txt", "r"); //err = fopen_s(&solRead,"medium_late04_sol.txt", "r"); //err = fopen_s(&solRead,"solutions\\long_late01_sol.txt", "r"); //err = fopen_s(&solRead,"sprint_hidden10_sol.txt", "r"); //err = fopen_s(&solRead,"solutions\\sprint03_sol.txt", "r"); //err = fopen_s(&solRead,"solutions\\sprint_late03_sol.txt", "r"); //err = fopen_s(&solRead,"solutions\\sprint_late06_sol.txt", "r"); //err = fopen_s(&solRead,"solutions\\zzrSolu.txt", "r"); char tmp[500]; // while( fscanf_s(solRead,"%s",tmp, 500) != EOF ){ // puts(tmp); // } int assNum = 0; for(int i = 0; i<12; i++){ fscanf_s(solRead,"%s",tmp, 500); if( i == 10 ){ assNum = atoi(tmp); //printf("ass num is %d\n", assNum); } } for(int i = 0; i < assNum ; i++){ //fscanf_s(solRead,"%s",tmp, 500); int t1 = 0; int t2 = 0; int dayIdx = 0; fscanf(solRead,"%d-%d-%d,",&t1,&t2,&dayIdx); //puts(tmp); //printf("%d %d %d ",t1,t2,dayIdx); int nurseIdx; fscanf(solRead,"%d,",&nurseIdx); //printf("%d \n", nurseIdx); char shiftTmp; fscanf_s(solRead,"%s",tmp, 500); if( tmp[0] == 'D' && tmp[1] == 'H'){ //printf(" H appears \n"); shiftTmp = 'H'; } else shiftTmp = tmp[0]; //printf("%c \n", shiftTmp); s[nurseIdx][dayIdx-1] = shiftTmp; } fclose(solRead); //solutionRosterShowScreen(s); //printf("the fit I evaluate is %d \n", evaluate(s)); }
zzr-cro-nurse
trunk/readsol.cpp
C++
gpl3
1,997
///////////////////////////////////////////////// // This module generate an initial solution based on the hard constraints // The main function is void creRanSol(){} // There is also an showSol function to show a solution. // After the searching, we also use it. ///////////////////////////////////////////////// #include <stdio.h> #include <string.h> #include <assert.h> #include <time.h> #include <stdlib.h> #include"functions.h" // initial int cover_h[7][5] = {0}; int nurseTotal = 0; //////////////////////////////////////////////////////////// // search for every day // step1: obtain the day's id, 1,2,3,...,0;Monday,... // step2: based on the cover_h[dayId][j], search the every type to obtain how // many nurses in current day, saved in nurseSumT. // step3: randomly select nurseSumT nurses saved in a[] // step4: creating... //////////////////////////////////////////////////////////// //void solutionCreate(){ void solutionCreate(char s[NURSE_NUM][DAY_NUM]){ // for(int i = 0; i < DAY_NUM; i++){ // because the time interval begins from Friday int dayId = (i + startTimeOffset) % 7; // //printf("%d\n", dayId); // loop cover_h to obtain nurse sum of current day int nurseSumT=0; for(int j = 0; j<TYPES; j++)nurseSumT = nurseSumT + cover_h[dayId][j]; // ========== randomly select nurse ========= // the new method int nurseIdxArray[NURSE_NUM] = {0}; // to hold the index number to choose for(int idx = 0; idx < nurseTotal; idx++)nurseIdxArray[idx] = idx; int a[NURSE_NUM] = {0}; // hold the randomly selected nurse index int lastIdx = nurseTotal-1; //printf("num need is %d \n",nurseSumT); int selectedIdx = 0; for(int nurseNeed = 0; nurseNeed < nurseSumT; nurseNeed++){ selectedIdx = rand() % (nurseTotal - nurseNeed); // 0 ~ nurseTotal-1 a[nurseNeed] = nurseIdxArray[selectedIdx]; // half swap nurseIdxArray[selectedIdx] = nurseIdxArray[lastIdx]; lastIdx--; //printf("%d ",a[nurseNeed]); } //printf("\n"); // ===== creating based on the cover constraint and randoms in a[] ======== int t3 = 0; for(int j = 0; j<TYPES; j++){ // for every type int t2 = cover_h[dayId][j]; // t2 is the needed nurse num in dayId of j type if( j == 0) for(int k = 0; k<t2; k++){ // k is for the num of times s[a[t3]][i] = 'E'; t3++; } else if( j == 1) for(int k = 0; k<t2; k++){ s[a[t3]][i] = 'L'; t3++; } else if( j == 2) for(int k = 0; k<t2; k++){ s[a[t3]][i] = 'D'; t3++; } else if( j == 3) for(int k = 0; k<t2; k++){ s[a[t3]][i] = 'N'; t3++; } else if( j == 4) for(int k = 0; k<t2; k++){ s[a[t3]][i] = 'H'; t3++; } } } //solutionShow(s); }
zzr-cro-nurse
trunk/generate.cpp
C++
gpl3
2,864
/////////////////////////////////////////////////////////// // This file contains the function to evaluate an solution // the loop order is first the nurses, then the days // // Max & Min working day 2 search and record the total // Max & Min consec working day 2 this part apply the new alg // Max & Min consec free day 2 // ........... // Max & Min consec working wkd 2 // // Max working wkd in four weeks 1 record it // No Night shift before free wkd // just check // alternative skill // this is also simple, just check it // // /////////////////////////////////////////////////////////// #include <stdio.h> #include <string.h> #include <assert.h> #include <time.h> #include <stdlib.h> #include"functions.h" // output the evaluation information //#define DEBUG struct penaltyRec pRec = {0}; // the whole penalty struct penaltyRec nursePenRec[NURSE_NUM] = {0}; int penArray[NURSE_NUM][DAY_NUM]; int evaluate(char s[NURSE_NUM][DAY_NUM]){ for( int i = 0; i < nurseTotal; i++){ nursePenRec[i].consecFree = 0; nursePenRec[i].consecWorkingday = 0; nursePenRec[i].consecWorkingWkd = 0; nursePenRec[i].maxwkd= 0; nursePenRec[i].pattern = 0; nursePenRec[i].shiftoff = 0; nursePenRec[i].threeWkd= 0; nursePenRec[i].dayoff= 0; nursePenRec[i].workingday= 0; nursePenRec[i].total= 0; } // reset the penalty array for( int i = 0; i < NURSE_NUM; i++ ){ for( int j = 0; j < DAY_NUM; j++ ){ penArray[i][j] = 0; } } //FILE* f_eva = fopen("eva_output.txt", "w"); // penalty reset int fitness = 0; int workingdayRec = 0; int consecWorkingdayRec= 0; int consecFreeRec= 0; int consecWorkingWkdRec= 0; int wkdRec= 0; int threeWkdRec= 0; int dayoffRec= 0; int shiftoffRec= 0; int patternRec= 0; int tempFit = 0; // ========================= for each nurse ========================= for(int nurseIdx = 0; nurseIdx < nurseTotal; nurseIdx++){ //for(int nurseIdx = 0; nurseIdx < 1; nurseIdx++){ // for test //for(int nurseIdx = 1; nurseIdx < 2; nurseIdx++){ // for test //for(int nurseIdx = 49; nurseIdx < 50; nurseIdx++){ // for test nursePenRec[nurseIdx].idx = nurseIdx; // ========================= max min working day ========================= tempFit = fitness; int maxf_t = contractArray[nursesContraMap[nurseIdx]].maxWorkDayOn; int minf_t = contractArray[nursesContraMap[nurseIdx]].minWorkDayOn; int max_t = contractArray[nursesContraMap[nurseIdx]].maxWorkDay; int min_t = contractArray[nursesContraMap[nurseIdx]].minWorkDay; int maxw_t = contractArray[nursesContraMap[nurseIdx]].maxWorkDayW; int minw_t = contractArray[nursesContraMap[nurseIdx]].minWorkDayW; int temp_workingday = 0; int total = 0; for(int i = 0; i < DAY_NUM; i++) if( s[nurseIdx][i] != 0)total++; if( maxf_t ) if( total > max_t ) { fitness = fitness + ( total - max_t ) * maxw_t; } if( minf_t ) if( total < min_t )fitness = fitness + ( min_t - total) * minw_t; workingdayRec += fitness - tempFit; nursePenRec[nurseIdx].workingday = fitness - tempFit; nursePenRec[nurseIdx].total += nursePenRec[nurseIdx].workingday; // test total //printf(" cons is %d %d, total is %d, fit is %d\n",contractArray[nursesContraMap[nurseIdx]].maxWorkDay, // contractArray[nursesContraMap[nurseIdx]].minWorkDay,total, fitness); // ========================= consec working day ========================= maxf_t = contractArray[nursesContraMap[nurseIdx]].maxConWorkDayOn; minf_t = contractArray[nursesContraMap[nurseIdx]].minConWorkDayOn; max_t = contractArray[nursesContraMap[nurseIdx]].maxConWorkDay; min_t = contractArray[nursesContraMap[nurseIdx]].minConWorkDay; maxw_t = contractArray[nursesContraMap[nurseIdx]].maxConWorkDayW; minw_t = contractArray[nursesContraMap[nurseIdx]].minConWorkDayW; int workingCounter = 0; tempFit = fitness; for(int i = 0; i < DAY_NUM; i++){ if( s[nurseIdx][i] != 0)workingCounter++; if ( s[nurseIdx][i] == 0 || i == DAY_NUM - 1 ) { if( workingCounter != 0 ){ //compare if( maxf_t ) if( workingCounter > max_t){ fitness = fitness + (workingCounter - max_t)* maxw_t; } if( minf_t ) if( workingCounter < min_t){ fitness = fitness + (min_t - workingCounter)* minw_t; }//printf("working consec is %d\n", workingCounter); } workingCounter = 0; } } consecWorkingdayRec += fitness - tempFit; nursePenRec[nurseIdx].consecWorkingday = fitness - tempFit; nursePenRec[nurseIdx].total += nursePenRec[nurseIdx].consecWorkingday; //printf(" cons is %d %d, weight is %d, fit is %d\n",contractArray[nursesContraMap[nurseIdx]].maxConWorkDay, // contractArray[nursesContraMap[nurseIdx]].minConWorkDay, contractArray[nursesContraMap[nurseIdx]].maxConWorkDayW,fitness); // ========================= consec free day ========================= maxf_t = contractArray[nursesContraMap[nurseIdx]].maxConFreeOn; minf_t = contractArray[nursesContraMap[nurseIdx]].minConFreeOn; max_t = contractArray[nursesContraMap[nurseIdx]].maxConFree; min_t = contractArray[nursesContraMap[nurseIdx]].minConFree; maxw_t = contractArray[nursesContraMap[nurseIdx]].maxConFreeW; minw_t = contractArray[nursesContraMap[nurseIdx]].minConFreeW; int freeCounter = 0; tempFit = fitness ; for(int i = 0; i < DAY_NUM; i++){ if( s[nurseIdx][i] == 0) freeCounter++; if ( s[nurseIdx][i] != 0 || i == DAY_NUM - 1 ) { if( freeCounter != 0 ){ if( maxf_t ) if( freeCounter > max_t){ fitness = fitness + (freeCounter - max_t)* maxw_t; } if( minf_t ) if( freeCounter < min_t){ fitness = fitness + (min_t - freeCounter)* minw_t; } //printf("free consec is %d\n", freeCounter); } freeCounter = 0; } } consecFreeRec += fitness - tempFit; nursePenRec[nurseIdx].consecFree = fitness - tempFit; nursePenRec[nurseIdx].total += nursePenRec[nurseIdx].consecFree; // ========================= consec working wkd ========================= tempFit = fitness; int weekArray[4] = {0}; int wkdOffset = 0; if ( contractArray[nursesContraMap[nurseIdx]].wkdDayNum == 3)wkdOffset = 1; // sometime weekend is 3 day for(int i = (7-startTimeOffset-1) - wkdOffset; i < DAY_NUM; i+=7) if( contractArray[nursesContraMap[nurseIdx]].wkdDayNum == 2){ if( s[nurseIdx][i] != 0 || s[nurseIdx][i+1] != 0)weekArray[i/7] = 1; } else if( contractArray[nursesContraMap[nurseIdx]].wkdDayNum == 3 ){ if( s[nurseIdx][i] != 0 || s[nurseIdx][i+1] != 0 || s[nurseIdx][i+2] != 0)weekArray[i/7] = 1; } // for(int i = 0; i < 4; i++ ){ // printf("%d ", weekArray[i]); // } maxf_t = contractArray[nursesContraMap[nurseIdx]].maxConWorkWeekendOn; minf_t = contractArray[nursesContraMap[nurseIdx]].minConWorkWeekendOn; max_t = contractArray[nursesContraMap[nurseIdx]].maxConWorkWeekend; min_t = contractArray[nursesContraMap[nurseIdx]].minConWorkWeekend; maxw_t = contractArray[nursesContraMap[nurseIdx]].maxConWorkWeekendW; minw_t = contractArray[nursesContraMap[nurseIdx]].minConWorkWeekendW; int workingWkdCounter = 0; for(int i = 0; i < 4; i++){ if( weekArray[i] != 0)workingWkdCounter++; if ( weekArray[i] == 0 || i == 3 ) { if( workingWkdCounter != 0 ){ if( maxf_t ) if( workingWkdCounter > max_t) fitness = fitness + (workingWkdCounter - max_t)* maxw_t; if( minf_t ) if( workingWkdCounter < min_t) fitness = fitness + (min_t - workingWkdCounter)* minw_t; } workingWkdCounter = 0; } } consecWorkingWkdRec += fitness - tempFit; nursePenRec[nurseIdx].consecWorkingWkd = fitness - tempFit; nursePenRec[nurseIdx].total += nursePenRec[nurseIdx].consecWorkingWkd; // ========================= max working wkd ========================= tempFit = fitness; int wkdtotal = 0; for(int i = 0; i < 4; i++ )wkdtotal += weekArray[i]; //printf("total wkd is %d\n", wkdtotal); if(contractArray[nursesContraMap[nurseIdx]].maxWorkingWeekendOn){ if( wkdtotal > contractArray[nursesContraMap[nurseIdx]].maxWorkingWeekend){ fitness = fitness + (wkdtotal - contractArray[nursesContraMap[nurseIdx]].maxWorkingWeekend)* (contractArray[nursesContraMap[nurseIdx]].maxWorkingWeekendW); } } wkdRec += fitness - tempFit; nursePenRec[nurseIdx].maxwkd = fitness - tempFit; nursePenRec[nurseIdx].total += nursePenRec[nurseIdx].maxwkd; // ========================= complete wkd ========================= // ========================= identical complete wkd ========================= // ========================= no night shift bf free wkd ========================= // complete wkd, the penalties should be 2 - x of days, directly hash the penalty // if the wkd is 3, special case xox should be considered tempFit = fitness; wkdOffset = 0; int penalty_comp = 0; int penalty_ide = 0; int penalty_nn = 0; int comp_sum = 0; if ( contractArray[nursesContraMap[nurseIdx]].wkdDayNum == 3)wkdOffset = 1; // sometime weekend is 3 day // day from 0, thus 1 is Saturday, if 3 wkd day, 0 is Friday //for(int i = 4 - wkdOffset; i < DAY_NUM; i+=7){ // TODO for(int i = (7-startTimeOffset-1) - wkdOffset; i < DAY_NUM; i+=7){ if( contractArray[nursesContraMap[nurseIdx]].wkdDayNum == 2){ // 2 wkd days if( (s[nurseIdx][i] != 0 && s[nurseIdx][i+1] == 0) ||(s[nurseIdx][i] == 0 && s[nurseIdx][i+1] != 0) ) { // not complete wkd penalty_comp++; comp_sum++; } else if( s[nurseIdx][i] == 0 && s[nurseIdx][i+1] == 0 ){ // check no night if( s[nurseIdx][i-1] == 'N' ){ penalty_nn += 1; } } if( s[nurseIdx][i] != s[nurseIdx][i+1] ){ // check for identical if( s[nurseIdx][i] != 0 && s[nurseIdx][i+1] != 0 ){ // 2 different shifts penalty_ide += 2; } else // a working and a free penalty_ide += 1; } } else if( contractArray[nursesContraMap[nurseIdx]].wkdDayNum == 3 ){ if( s[nurseIdx][i] != 0 && s[nurseIdx][i+1] == 0 && s[nurseIdx][i+2] != 0 ){ // xox penalty is 4 TODO to finish penalty_comp += 4; //penalty_comp += 2; //printf("penalty should be 4 in %d\n", i); } else if(s[nurseIdx][i] != 0 && s[nurseIdx][i+1] == 0 && s[nurseIdx][i+2] == 0){ // xoo penalty is 2 //printf("3 wkd day\n"); penalty_comp += 2; } else if(s[nurseIdx][i] == 0 && s[nurseIdx][i+1] != 0 && s[nurseIdx][i+2] == 0){ // oxo penalty is 2 penalty_comp += 2; } else if(s[nurseIdx][i] == 0 && s[nurseIdx][i+1] == 0 && s[nurseIdx][i+2] != 0){ // oox penalty is 2 penalty_comp += 2; } else if(s[nurseIdx][i] != 0 && s[nurseIdx][i+1] != 0 && s[nurseIdx][i+2] == 0){ // xxo penalty is 1 penalty_comp += 1; } else if(s[nurseIdx][i] == 0 && s[nurseIdx][i+1] != 0 && s[nurseIdx][i+2] != 0){ // oxx penalty is 1 penalty_comp += 1; } //printf("\n penalty_comp is %d\n ",penalty_comp); // check for identical if( s[nurseIdx][i] != 0 || s[nurseIdx][i+1] != 0 || s[nurseIdx][i+2] != 0){ //printf(" busy wkd in %d\n",i); // very complicated, hash again char c1,c2,c3; // temp vars for comparison c1 = s[nurseIdx][i]; c2 = s[nurseIdx][i+1]; c3 = s[nurseIdx][i+2]; if( c1 != 0 && c2 != 0 && c3 != 0){ if(( c1 == c2 ) && ( c2 == c3 ) ){ // no penalty } else if( ( c1 != c2) && ( c2 != c3) && ( c1 != c3) ){ penalty_ide += 6; } else if( (c1 == c2 && c2 != c3) || (c3 == c2 && c2 != c1) || (c1 == c3 && c2 != c1)){ penalty_ide += 3; } } else if( c1 == 0 && c2 != 0 && c3 != 0 ){ if( c2 != c3 ){ penalty_ide += 4; } else if( c2 == c3 ){ penalty_ide += 1; } } else if( c1 != 0 && c2 == 0 && c3 != 0 ){ if( c1 != c3 ){ penalty_ide += 4; } else if( c1 == c3 ){ penalty_ide += 1; } } else if( c1 != 0 && c2 != 0 && c3 == 0 ){ if( c1 != c2 ){ penalty_ide += 4; } else if( c1 == c2 ){ penalty_ide += 1; } } // oox oxo xoo else if( c1 == 0 && c2 == 0 && c3 != 0 ){ penalty_ide += 2; } else if( c1 != 0 && c2 == 0 && c3 == 0 ){ penalty_ide += 2; } else if( c1 == 0 && c2 != 0 && c3 == 0 ){ penalty_ide += 2; } // if( ( c1 == c2 ) && ( c2 == c3 ) ){ // // no penalty , it's identical // //printf("identical wkd \n"); // } // else if( ( c1 != c2 ) && ( c2 != c3 ) && ( c1 != c3 )){ // penalty_ide = +6; // //printf(" p is 6 in %d\n", i); // } // else if( ( c1 == c2 ) && ( c1 != c3 )){ // penalty_ide = +3; // //printf(" p is 3 in %d\n", i); // // } // else if( ( c1 != c2 ) && ( c2 == c3 )){ // penalty_ide = +3; // //printf(" p is 3 in %d\n", i); // } // else if( ( c1 != c2 ) && ( c1 == c3 )){ // penalty_ide = +3; // //printf(" p is 3 in %d\n", i); // } } // else if(s[nurseIdx][i] == 0 && s[nurseIdx][i+1] == 0 && s[nurseIdx][i+2] == 0){ // // check for no night // if( i != 0 ){ // the first day is Friday // if( s[nurseIdx][i-1] == 'N'){ // penalty_nn = +1; // //printf(" no night bf free wkd in %d\n", i); // } // } // } } } // wkd loop if(contractArray[nursesContraMap[nurseIdx]].idenShiftInWeekendOn) fitness = fitness + penalty_ide * contractArray[nursesContraMap[nurseIdx]].idenShiftInWeekendW; //if(contractArray[nursesContraMap[nurseIdx]].noNSBfFWeekendOn) //fitness = fitness + penalty_nn * contractArray[nursesContraMap[nurseIdx]].noNSBfFWeekendW; //printf("comp weight is %d %\n",contractArray[nursesContraMap[nurseIdx]].completeWeekendW); if(contractArray[nursesContraMap[nurseIdx]].completeWeekendOn) fitness = fitness + penalty_comp * contractArray[nursesContraMap[nurseIdx]].completeWeekendW; threeWkdRec += fitness - tempFit; //printf("comp sum is %d\n",comp_sum); nursePenRec[nurseIdx].threeWkd = fitness - tempFit; nursePenRec[nurseIdx].total += nursePenRec[nurseIdx].threeWkd; //printf("\npenalty of comp is %d\n", penalty_comp); //printf("\npenalty of comp is %d\n", penalty_comp* contractArray[nursesContraMap[nurseIdx]].completeWeekendW); // ========================= alter ========================= // search all the solution // using nurseSkill[nurse num], if it is 2, no action // if it is 1 and is 'H', penalty. Normal nurse being a headnurse skill //printf("skill level is %d \n", nurseSkill[nurseIdx]); if( nurseSkill[nurseIdx] != 2){ for(int i = 0; i < DAY_NUM; i++) if( s[nurseIdx][i] == 'H'){ //printf("not my work \n"); // add penlty if(contractArray[nursesContraMap[nurseIdx]].alternativeOn){ fitness += contractArray[nursesContraMap[nurseIdx]].alternativeW; //printf("altered \n"); } } } // ========================= dayoff request ========================= tempFit = fitness; for(int i = 0; i < DAY_NUM; i++){ if(nurseDayoff[nurseIdx][i]){ if( s[nurseIdx][i] != 0 ){ //printf("day off in %d is \n", i); fitness++; } } } dayoffRec += fitness - tempFit; nursePenRec[nurseIdx].dayoff = fitness - tempFit; nursePenRec[nurseIdx].total += nursePenRec[nurseIdx].dayoff; //// // // // // ========================= shift off request ========================= // note that this is the new, multiple shift offs should be considered // nurseShiftoff[i][j][k], there are k shift types // nurseShiftoffNum[i][j] records the shift number tempFit = fitness; for(int i = 0; i < DAY_NUM; i++){ if( nurseShiftoffNum[nurseIdx][i] ){ //printf("number of shift off request %d\n ",nurseShiftoffNum[nurseIdx][i]); for( int shiftIdx = 0; shiftIdx < nurseShiftoffNum[nurseIdx][i]; shiftIdx++){ //printf("type is %c\n",nurseShiftoff[nurseIdx][i][shiftIdx] ); if( s[nurseIdx][i] == nurseShiftoff[nurseIdx][i][shiftIdx] ){ fitness++; } } } } shiftoffRec += fitness - tempFit; nursePenRec[nurseIdx].shiftoff = fitness - tempFit; nursePenRec[nurseIdx].total += nursePenRec[nurseIdx].shiftoff; // TODO test new // ========================= unwanted pattern ========================= tempFit = fitness; for(int uwantedPatIndex = 0; uwantedPatIndex < contractArray[nursesContraMap[nurseIdx]].unWantPatTotal; uwantedPatIndex++ ){ // thus for each pattern. every nurse has a list of patterns. for( int dayIndex = 0; dayIndex < 28 - unPatArray[uwantedPatIndex].shiftTotal + 1 ; dayIndex++){ bool notMatch = false; // the normal seq if(unPatArray[uwantedPatIndex].patSeq[0] != 'F'){ for( int i = 0; i< unPatArray[uwantedPatIndex].shiftTotal; i++){ if( s[nurseIdx][dayIndex+i] != unPatArray[uwantedPatIndex].patSeq[i] ){ notMatch = true; break; } } if(notMatch == false) fitness += unPatArray[uwantedPatIndex].patWeight; } // the wkd seq else if(unPatArray[uwantedPatIndex].patSeq[0] == 'F'){ notMatch = false;// TODO if( (dayIndex + startTimeOffset)%7 == 5 ){ if(s[nurseIdx][dayIndex] != 0) notMatch = true; // either of the two wkd day has a shift will conflict if(s[nurseIdx][dayIndex+1] == 0 && s[nurseIdx][dayIndex+2] == 0) notMatch = true; if(notMatch == false) fitness += unPatArray[uwantedPatIndex].patWeight; } } } } patternRec += fitness - tempFit; nursePenRec[nurseIdx].pattern = fitness - tempFit; nursePenRec[nurseIdx].total += nursePenRec[nurseIdx].pattern; }// the nurse loop // a global struct to record the specifics of the penalties pRec.workingday = workingdayRec; pRec.consecWorkingday = consecWorkingdayRec; pRec.consecFree = consecFreeRec; pRec.consecWorkingWkd = consecWorkingWkdRec; pRec.maxwkd = wkdRec; pRec.threeWkd = threeWkdRec; pRec.dayoff = dayoffRec; pRec.shiftoff = shiftoffRec; pRec.pattern = patternRec; //fclose(f_eva); //showPenaltySpec(); return fitness; }
zzr-cro-nurse
trunk/evaluate.cpp
C++
gpl3
19,130
/////////////////////////////////////////////////////// // Load the constraint in the instance files // sprint first. /////////////////////////////////////////////////////// #include <stdio.h> #include <string.h> #include <assert.h> #include <stdlib.h> #include"functions.h" // the holder for reading the string #define STRMAX 500 char tmp[STRMAX]; uPattern unPatArray[UPATTERNNUMMAX] = {0}; // record the instance's attributes InstanceAttributeStruct instAttri = {0}; FILE *instance_fin; int startTimeOffset; // in cover_h, there is a mapping between the shift types // and the indices of 2ed dimension of the array // filling the cover_h array // cover_h[week day idx][shift idx] // cover_h records the hard cover void fillCoverMap(int a){ fscanf_s(instance_fin,"%s",tmp, STRMAX); // read the shift name if( !strcmp(tmp,"E,") ){ fscanf_s(instance_fin,"%s",tmp, STRMAX); // read the number cover_h[a][0] = atoi(tmp); } else if( !strcmp(tmp, "L,")){ fscanf_s(instance_fin,"%s",tmp, STRMAX); // read the number cover_h[a][1] = atoi(tmp); } else if( !strcmp(tmp,"D,") ){ fscanf_s(instance_fin,"%s",tmp, STRMAX); // read the number cover_h[a][2] = atoi(tmp); } else if(!strcmp(tmp,"N,")){ fscanf_s(instance_fin,"%s",tmp, STRMAX); // read the number cover_h[a][3] = atoi(tmp); } else if(!strcmp(tmp,"DH,")){ fscanf_s(instance_fin,"%s",tmp, STRMAX); // read the number cover_h[a][4] = atoi(tmp); } } void Load( char ins_name[] ){ // int nurseSkill[NURSE_NUM] = {0}; // // int nursesContraMap[NURSE_NUM]; // // int nurseDayoff[NURSE_NUM][DAY_NUM]; // // char nurseShiftoff[NURSE_NUM][DAY_NUM][10] = {0}; // weight is always 1 // int nurseShiftoffNum[NURSE_NUM][DAY_NUM] = {0}; // memset(&nurseSkill, 0, sizeof(nurseSkill)); memset(&nursesContraMap, 0, sizeof(nursesContraMap)); memset(&nurseDayoff, 0, sizeof(nurseDayoff)); memset(&nurseShiftoff, 0, sizeof(nurseShiftoff)); memset(&nurseShiftoffNum, 0, sizeof(nurseShiftoffNum)); memset(&instAttri, 0, sizeof(instAttri)); memset(&cover_h, 0, sizeof(cover_h)); memset(&unPatArray, 0, sizeof(unPatArray)); FILE *instanceLoadChk_fout = fopen("instanceLoadChk.txt", "w"); errno_t err; err = fopen_s(&instance_fin,ins_name, "r"); // ===== load loop ===== while( fscanf_s(instance_fin,"%s",tmp, STRMAX) != EOF ){ // ========================= read name and start time ========================= if( !strcmp("SCHEDULING_PERIOD;", tmp ) ){ fscanf_s(instance_fin,"%s",tmp, STRMAX); // the '/////' line fscanf_s(instance_fin,"%s,",instAttri.instanceName, STRMAX); fscanf_s(instance_fin,"%s,",instAttri.instanceStartTime, STRMAX); fscanf_s(instance_fin,"%s;",tmp, STRMAX); fprintf(instanceLoadChk_fout,"instance name is %s\n", instAttri.instanceName); fprintf(instanceLoadChk_fout,"instance start time is %s\n\n", instAttri.instanceStartTime); if( !strcmp(instAttri.instanceStartTime,"2010-01-01,") ){ startTimeOffset = 5; } else if( !strcmp(instAttri.instanceStartTime,"2010-06-01,") ){ startTimeOffset = 2; } } // ========================= read skills ========================= if( !strcmp("SKILLS", tmp) ){ fscanf_s(instance_fin,"%s",tmp, STRMAX); // read '=' symble fscanf_s(instance_fin,"%s",tmp, STRMAX);// skill number instAttri.skillNum = atoi(tmp); fprintf(instanceLoadChk_fout,"number of skill kind is %d\n\n", instAttri.skillNum); } // ========================= read shift types ========================= if( !strcmp("SHIFT_TYPES", tmp) ){ fscanf_s(instance_fin,"%s",tmp, STRMAX);// read '=' symble fscanf_s(instance_fin,"%s",tmp, STRMAX);// skill number instAttri.shiftTypeNum = atoi(tmp); fprintf(instanceLoadChk_fout,"number of shift type is %d\n\n", instAttri.shiftTypeNum); } // ========================= contract description ========================= // read the soft cons // read contracts arrays // if the weekend definition being the line // before it, there are 10 entries, except the first one being the hardconstraints // there are 9 entries which are : // Max & Min working day 2 // Max & Min consec working day 2 // Max & Min consec free day 2 // Max & Min consec working wkd 2 // Max working wkd in four weeks 1 // after the wkd definition there are 5 entries in .txt file but 4 entries in .xml files. // since the extra one (the fourth one)always keep 0, so it could be neglected. // It might be the two free days before the night shift,ref to nrpdesci page 19 // Thus there left 4 entries, which are // complete weekend 1 // identical shift type in complete wkd 1 // No Night shift before free wkd 1 // alternative skill 1 // ================================================== if( !strcmp("CONTRACTS", tmp) ){ fscanf_s(instance_fin,"%s",tmp, STRMAX); // read the '=' fscanf_s(instance_fin,"%s",tmp, STRMAX); // read the number of contra instAttri.contractNum = atoi(tmp); fprintf(instanceLoadChk_fout,"contract num is %d\n\n", instAttri.contractNum); fscanf_s(instance_fin,"%s",tmp, STRMAX); // read line /// // for each contra for(int i = 0; i < instAttri.contractNum; i++ ){ fscanf_s(instance_fin,"%s",tmp, STRMAX); int id = atoi(tmp); fprintf(instanceLoadChk_fout,"contrac id is %d ///////////\n", id); // the contract's name fscanf_s(instance_fin,"%s",tmp, STRMAX); fprintf(instanceLoadChk_fout,"contrac description is %s\n",tmp); // the first (1|1) is the hard constraints, always on fscanf_s(instance_fin,"%s",tmp, STRMAX); // max & min work day fscanf_s(instance_fin," (%d|%d|%d),",&contractArray[id].maxWorkDayOn,&contractArray[id].maxWorkDayW, &contractArray[id].maxWorkDay); fprintf(instanceLoadChk_fout,"max min wk day %d %d %d \n",contractArray[id].maxWorkDayOn, contractArray[id].maxWorkDayW,contractArray[id].maxWorkDay); fscanf_s(instance_fin," (%d|%d|%d),",&contractArray[id].minWorkDayOn,&contractArray[id].minWorkDayW, &contractArray[id].minWorkDay); fprintf(instanceLoadChk_fout,"max min wk day %d %d %d \n",contractArray[id].minWorkDayOn, contractArray[id].minWorkDayW,contractArray[id].minWorkDay); // max & min ConWorkDay fscanf_s(instance_fin," (%d|%d|%d),",&contractArray[id].maxConWorkDayOn,&contractArray[id].maxConWorkDayW, &contractArray[id].maxConWorkDay); // fprintf(instanceLoadChk_fout,"max min wk day %d %d %d \n",contractArray[id].maxConWorkDayOn, // contractArray[id].maxConWorkDayW,contractArray[id].maxConWorkDay); fscanf_s(instance_fin," (%d|%d|%d),",&contractArray[id].minConWorkDayOn,&contractArray[id].minConWorkDayW, &contractArray[id].minConWorkDay); // max & min ConFree fscanf_s(instance_fin," (%d|%d|%d),",&contractArray[id].maxConFreeOn,&contractArray[id].maxConFreeW, &contractArray[id].maxConFree); fscanf_s(instance_fin," (%d|%d|%d),",&contractArray[id].minConFreeOn,&contractArray[id].minConFreeW, &contractArray[id].minConFree); // max & min con work weekend fscanf(instance_fin," (%d|%d|%d),",&contractArray[id].maxConWorkWeekendOn,&contractArray[id].maxConWorkWeekendW, &contractArray[id].maxConWorkWeekend); fscanf(instance_fin," (%d|%d|%d),",&contractArray[id].minConWorkWeekendOn,&contractArray[id].minConWorkWeekendW, &contractArray[id].minConWorkWeekend); // max working weekend fscanf(instance_fin," (%d|%d|%d),",&contractArray[id].maxWorkingWeekendOn,&contractArray[id].maxWorkingWeekendW, &contractArray[id].maxWorkingWeekend); fprintf(instanceLoadChk_fout,"maxWorkingWeekend %d %d %d \n",contractArray[id].maxWorkingWeekendOn, contractArray[id].maxWorkingWeekendW,contractArray[id].maxWorkingWeekend); // wkd definition fscanf_s(instance_fin,"%s",tmp, STRMAX); //fprintf(instanceLoadChk_fout,"weekend is default \n"); if( !strcmp("SaturdaySunday,", tmp) ) contractArray[id].wkdDayNum = 2; else if( !strcmp("FridaySaturdaySunday,", tmp) ) contractArray[id].wkdDayNum = 3; fprintf(instanceLoadChk_fout, "wkd num is %d \n", contractArray[id].wkdDayNum); // complete wkd fscanf(instance_fin," (%d|%d),", &contractArray[id].completeWeekendOn,&contractArray[id].completeWeekendW); fprintf(instanceLoadChk_fout,"complete weekend %d %d \n",contractArray[id].completeWeekendOn, contractArray[id].completeWeekendW); // identical shift in wkd fscanf(instance_fin," (%d|%d),", &contractArray[id].idenShiftInWeekendOn,&contractArray[id].idenShiftInWeekendW); fprintf(instanceLoadChk_fout,"identical %d %d \n",contractArray[id].idenShiftInWeekendOn, contractArray[id].idenShiftInWeekendW); //no night shift fscanf(instance_fin," (%d|%d),", &contractArray[id].noNSBfFWeekendOn,&contractArray[id].noNSBfFWeekendW); fprintf(instanceLoadChk_fout,"no night is %d %d \n",contractArray[id].noNSBfFWeekendOn, contractArray[id].noNSBfFWeekendW); // not no use, maybe it is the no 2free days after a night shift // however, the cons is always 0|0 in every instance, so do not need // to load fscanf_s(instance_fin,"%s",tmp, STRMAX); // alternative fscanf(instance_fin," (%d|%d),", &contractArray[id].alternativeOn,&contractArray[id].alternativeW); fprintf(instanceLoadChk_fout,"alter is %d %d \n",contractArray[id].alternativeOn, contractArray[id].alternativeW); // read contracts' pattern // e.g. ... 3, 0 1 2; fscanf_s(instance_fin,"%s",tmp, STRMAX); int patternNum = atoi(tmp); contractArray[id].unWantPatTotal = patternNum; fprintf(instanceLoadChk_fout,"unwanted pattern num is %d\n",contractArray[id].unWantPatTotal); // each pattern, read the id for(int i = 0; i<patternNum; i++){ fscanf_s(instance_fin,"%s",tmp, STRMAX); contractArray[id].unWantPat[i] = atoi(tmp); fprintf(instanceLoadChk_fout,"unwant pattern is %d\n", contractArray[id].unWantPat[i]); } fprintf(instanceLoadChk_fout,"\n"); } } // ========================= read patterns ========================= //2, 1, 3 (None|Friday) (Any|Saturday) (Any|Sunday); //1, 1, 3 (D|Any) (E|Any) (D|Any); //0, 1, 2 (L|Any) (D|Any); if( !strcmp("PATTERNS", tmp) ){ fprintf(instanceLoadChk_fout,"\n//////////////////// PATTERN ///////////////////// \n"); fscanf_s(instance_fin,"%s",tmp, STRMAX); // the '=' symbol fscanf_s(instance_fin,"%s",tmp, STRMAX); // the pattern number int patternTotal = atoi(tmp); fprintf(instanceLoadChk_fout,"pattern total number is %d\n", patternTotal); fscanf_s(instance_fin,"%s",tmp, STRMAX); // read the //////////// // for each pattern, fill the unPatArray to record for(int j = 0; j < patternTotal; j++){ // pattern ID fscanf_s(instance_fin,"%s",tmp, STRMAX); int patternId = atoi(tmp); unPatArray[patternId].patIdx = patternId; fprintf(instanceLoadChk_fout,"pattern id is %d\n", patternId); // pattern weight, always 1, leave it alone fscanf_s(instance_fin,"%s",tmp, STRMAX); unPatArray[patternId].patWeight = atoi(tmp); // total number of shifts in a sequence fscanf_s(instance_fin,"%s",tmp, STRMAX); int shiftTotal = atoi(tmp); fprintf(instanceLoadChk_fout,"shift total is %d\n", shiftTotal); unPatArray[patternId].shiftTotal = shiftTotal; // loop the shift sequence // e.g. 2, 1, 3 (None|Friday) (Any|Saturday) (Any|Sunday); for(int i = 0; i<shiftTotal; i++){ fscanf_s(instance_fin,"%s",tmp, STRMAX); // the pattern related to wkd if( strlen(tmp) > 10 ){ unPatArray[patternId].patSeq[0] = 'F'; unPatArray[patternId].patSeq[1] = 'A'; unPatArray[patternId].patSeq[2] = 'A'; } else{ if(tmp[1] == 'D' && tmp[2] == 'H'){ // for DH unPatArray[patternId].patSeq[i] = tmp[2]; } else unPatArray[patternId].patSeq[i] = tmp[1]; } } } // pattern struct show //for(int i = 0; i< patternTotal ;i++){ // printf("idx is %d, weight is %d, shiftNum is %d", unPatArray[i].patIdx,unPatArray[i].patWeight,unPatArray[i].shiftTotal); // for(int j = 0; j < unPatArray[i].shiftTotal; j++ ){ // printf("%c ", unPatArray[i].patSeq[j]); // } // printf("\n"); //} } // read pattern // ========================= read employees ========================= if( !strcmp("EMPLOYEES", tmp) ){ fprintf(instanceLoadChk_fout,"\n//////////////////// EMPLOYEE READ ///////////////////// \n"); fscanf_s(instance_fin,"%s",tmp, STRMAX); nurseTotal = atoi(tmp); fprintf(instanceLoadChk_fout,"nurse number is %d\n", nurseTotal); fscanf_s(instance_fin,"%s",tmp, STRMAX); // read the line /// for(int i = 0; i<nurseTotal; i++){ int id; fscanf_s(instance_fin,"%s",tmp, STRMAX); // nurse id id = atoi(tmp); fscanf_s(instance_fin,"%s",tmp, STRMAX); // another id, no use fscanf_s(instance_fin,"%s",tmp, STRMAX); // contra id nursesContraMap[id] = atoi(tmp); fprintf(instanceLoadChk_fout,"nurse %d's contra id is %d ",id, nursesContraMap[id] ); // use another array to hold the skill level of a nurse fscanf_s(instance_fin,"%s",tmp, STRMAX); // skill level nurseSkill[id] = atoi(tmp); fprintf(instanceLoadChk_fout,"nurse %d's skill level is %d \n",id, nurseSkill[id] ); // 'nurse' of 'nurse and head nurse', // don't need to read, above information is enough fscanf_s(instance_fin,"%s",tmp, STRMAX); if(nurseSkill[id]>1)fscanf_s(instance_fin,"%s",tmp, STRMAX); } } // ========================= read hard cover ========================= if( !strcmp("DAY_OF_WEEK_COVER", tmp) ){ //if( compare("DAY_OF_WEEK_COVER", tmp, strlen(tmp)) ){ fprintf(instanceLoadChk_fout,"\n//////////////////// HARD COVER CONS ///////////////////// \n"); fscanf_s(instance_fin,"%s",tmp, STRMAX); // read the '=' fscanf_s(instance_fin,"%s",tmp, STRMAX); // read the number int weekcovernum = (tmp[0] - 48) * 10 + tmp[1] - 48; // the week cover total number fprintf(instanceLoadChk_fout," the weekcovernum is %d\n", weekcovernum); fscanf_s(instance_fin,"%s",tmp, STRMAX); // read the //line for(int i = 0; i<weekcovernum; i++){ fscanf_s(instance_fin,"%s",tmp, STRMAX);// read the week day name // there is a mapping between seven day name and the indice of cover_h // 0 is Sunday if( !strcmp("Monday,", tmp) )fillCoverMap(1); else if( !strcmp("Tuesday,", tmp) )fillCoverMap(2); else if( !strcmp("Wednesday,", tmp) )fillCoverMap(3); else if( !strcmp("Thursday,", tmp) )fillCoverMap(4); else if( !strcmp("Friday,", tmp) )fillCoverMap(5); else if( !strcmp("Saturday,", tmp) )fillCoverMap(6); else if( !strcmp("Sunday,", tmp) )fillCoverMap(0); } // check the cover_h for(int j = 0; j<7; j++) for(int i = 0; i<5; i++) fprintf(instanceLoadChk_fout,"the day cover is %d \n", cover_h[j][i]); } // ========================= load day off ========================= if( !strcmp("DAY_OFF_REQUESTS", tmp) ){ fprintf(instanceLoadChk_fout,"\n//////////////////// DAT OFF REQUESTS ///////////////////// \n"); fscanf_s(instance_fin,"%s",tmp, STRMAX); // read the '=' fscanf_s(instance_fin,"%s",tmp, STRMAX); // read the number int dayoffnum = atoi(tmp); //printf("day off number is %d", dayoffnum); fscanf_s(instance_fin,"%s",tmp, STRMAX); // read the //// for(int i = 0; i<dayoffnum; i++){ fscanf_s(instance_fin,"%s",tmp, STRMAX); // read the nurse id int nurseId = atoi(tmp); fscanf_s(instance_fin,"%s",tmp, STRMAX); // read the day name int day = (tmp[8]-48)*10 + tmp[9] - 48; fscanf_s(instance_fin,"%s",tmp, STRMAX); // read the weight nurseDayoff[nurseId][day-1] = atoi(tmp) ; // the dayIdx in array starts with '0' fprintf(instanceLoadChk_fout,"nurse % d in day %d the off is %d \n", nurseId, day, nurseDayoff[nurseId][day-1] ); //puts(tmp); } // for(int i = 0; i<nurseTotal ; i++){ // for(int j = 0; j<DAY_NUM; j++){ // fprintf(instanceLoadChk_fout,"%d ",nurseDayoff[i][j]); // } // fprintf(instanceLoadChk_fout,"\n"); // // } } // ========================= load the shift off ========================= if( !strcmp("SHIFT_OFF_REQUESTS", tmp) ){ fprintf(instanceLoadChk_fout,"\n//////////////////// SHIFT OFF REQUESTS ///////////////////// \n"); fscanf_s(instance_fin,"%s",tmp, STRMAX); // read the '=' fscanf_s(instance_fin,"%s",tmp, STRMAX); // read the number int shiftoffnum = atoi(tmp); //printf("shift off number is %d", shiftoffnum); fprintf(instanceLoadChk_fout,"shift off num is %d\n", shiftoffnum); fscanf_s(instance_fin,"%s",tmp, STRMAX); // read the //// for(int i = 0; i<shiftoffnum; i++){ fscanf_s(instance_fin,"%s",tmp, STRMAX); // read the nurse id int nurseId = atoi(tmp); fscanf_s(instance_fin,"%s",tmp, STRMAX); // read the day name int day = (tmp[8]-48)*10 + tmp[9] - 48; fscanf_s(instance_fin,"%s",tmp, STRMAX); // read the shift type //fprintf(instanceLoadChk_fout," len is %d ", strlen(tmp)); // for 'HD' shift if(strlen(tmp) == 3) tmp[0] = 'H'; // multiple shift off nurseShiftoff[nurseId][day-1][ nurseShiftoffNum[nurseId][day-1] ] = tmp[0]; nurseShiftoffNum[nurseId][day-1]++; fscanf_s(instance_fin,"%s",tmp, STRMAX); // read the weight, no use // fprintf(instanceLoadChk_fout,"nurse % d in day %d the shift is %c off weight is 1 \n", // nurseId, day-1, nurseShiftoff[nurseId][day-1]); } // check above // for(int i = 0; i<nurseTotal ; i++){ // for(int j = 0; j<DAY_NUM; j++){ // if(!nurseShiftoffNum[i][j]){ // fprintf(instanceLoadChk_fout,"-"); // } // for(int k = 0; k < nurseShiftoffNum[i][j]; k++){ // fprintf(instanceLoadChk_fout,"%c",nurseShiftoff[i][j][k]); // } // } // fprintf(instanceLoadChk_fout,"\n"); // // } } } fclose(instanceLoadChk_fout); fclose(instance_fin); //fclose(err); }
zzr-cro-nurse
trunk/load.cpp
C++
gpl3
18,900
// ================================================== // some support functions // ================================================== #include <stdio.h> #include <string.h> #include <assert.h> #include <time.h> #include <stdlib.h> #include"functions.h" // try for the day tabu int const stepL = 15; int dayRecord[stepL] = {0}; int nurseRecord[10]={0}; int randomInt[200] = {0}; int randomDayIdx[28] = {0}; int randomNurseIdx[10] = {0}; // 10 nurses, just for sprint track void swap2Ints( int* a, int* b){ int tmp; tmp = *a; *a = *b; *b = tmp; } int randIntInterval(int start, int end){ assert(start <= end); return (rand()% ( end - start + 1) ) + start; } void randArray(int len){ for(int i = 0; i < len; i++)randomInt[i] = i; int r; for(int i = 0; i < len; i++){ r = rand()% (len-i); swap2Ints( &randomInt[r],&randomInt[len - i - 1] ); } //for(int i = 0; i < len; i++)printf("%d ",randomInt[i]); //printf("\n"); } // void randomDayGen(int holdArray[], int len){ for(int i = 0; i < DAY_NUM; i++)randomDayIdx[i] = i; int r; for(int i = 0; i < DAY_NUM; i++){ r = rand()% ( DAY_NUM-i ); swap2Ints( &randomDayIdx[r],&randomDayIdx[ DAY_NUM - i - 1 ] ); } for(int i = 0; i < len; i++){ holdArray[i] = randomDayIdx[i]; } // for(int i = 0; i < len; i++) // printf("%d \n",holdArray[i]); } void randomNurseGen(int holdArray[], int len){ for(int i = 0; i < 10; i++)randomNurseIdx[i] = i; int r; for(int i = 0; i < 10; i++){ r = rand()% ( 10 - i ); swap2Ints( &randomNurseIdx[r],&randomNurseIdx[ 10 - i - 1 ] ); } for(int i = 0; i < len; i++){ holdArray[i] = randomNurseIdx[i]; } // for(int i = 0; i < len; i++) // printf("%d \n",holdArray[i]); } // ========================= show functions ========================= void showPop( struct Molecule pop[popSizeMax] ){ static FILE* file_t = fopen("popShow.txt", "w+"); for(int i = 0; i < currentPopSize; i++){ //printf("%d ",MoleculePop[i].PE ); //fprintf(file_t, "%d ", MoleculePop[i].PE ); fprintf(file_t, "%d ", pop[i].PE ); } fprintf(file_t,"\n"); fflush(file_t); fclose(file_t); } // show 2d view void solutionRosterShowScreen( char s[][DAY_NUM]){ printf(" "); for(int j = 0; j < DAY_NUM; j++){ if(j<10){ if( j % 7 == (7-startTimeOffset+1) ) printf(" %d",j); else printf(" %d",j); } else{ if( j % 7 == (7-startTimeOffset+1) ) printf(" %d",j); else printf("%d",j); } } printf("\n"); for(int i = 0; i < nurseTotal; i++){ printf("%d ",i); for(int j = 0; j < DAY_NUM; j++){ printf("%c ",s[i][j]); //printf("%d ",solution[i][j]); if( j%7 == 7-startTimeOffset )printf("|"); } printf("\n"); } } // show the standard solution style void solutionStandardOutputFile( char s[][DAY_NUM]){ //FILE *sol_fout_eva = fopen("zzrSolu.txt", "w"); FILE *sol_fout_eva = fopen("E:\\main_res\\working\\paper project\\roster project\\evaluator\\zzrSolu.txt", "w"); //FILE *sol_fout_eva = fopen("zzrSolu.out", "w"); //printf("errno[%d][%s]\n",errno,strerror(errno)); assert(sol_fout_eva != NULL); int sum = 0; for(int j = 0; j < DAY_NUM; j++){ for(int i = 0; i < nurseTotal; i++){ if(s[i][j]){ sum++; } } //printf("\n"); } //static FILE *sol_fout_eva = fopen("zzrSolu_show.txt", "w+"); fprintf(sol_fout_eva,"////////////////////////////////////////////////////////////////////\n"); //fprintf(sol_fout_eva,"SOLUTION = %s;\n",instAttri.instanceName); // TODO modify fprintf(sol_fout_eva,"SOLUTION = "); // TODO modify int cIdex = 0; while( instAttri.instanceName[cIdex] !=',' ){ fprintf(sol_fout_eva,"%c",instAttri.instanceName[cIdex]); // TODO modify cIdex++; } fprintf(sol_fout_eva,";\n"); // TODO modify fprintf(sol_fout_eva,"////////////////////////////////////////////////////////////////////\n"); fprintf(sol_fout_eva,"ziran, 00;\n"); // TODO modify fprintf(sol_fout_eva,"\n"); fprintf(sol_fout_eva,"\n"); fprintf(sol_fout_eva,"////////////////////////////////////////////////////////////////////\n"); fprintf(sol_fout_eva,"ASSIGNMENTS = "); fprintf(sol_fout_eva,"%d;\n",sum); fprintf(sol_fout_eva,"////////////////////////////////////////////////////////////////////\n"); int mon = 0; if( !strcmp(instAttri.instanceStartTime,"2010-01-01,") ){ mon = 1; } else if( !strcmp(instAttri.instanceStartTime,"2010-06-01,") ){ mon = 6; } for(int j = 0; j < DAY_NUM; j++){ for(int i = 0; i < nurseTotal; i++){ if(s[i][j]){ if(j < 9) fprintf(sol_fout_eva,"2010-0%d-0",mon); else fprintf(sol_fout_eva,"2010-0%d-",mon); fprintf(sol_fout_eva,"%d,",j+1); if(s[i][j] == 'H'){ fprintf(sol_fout_eva," %d, D%c;\n",i,s[i][j]); } else fprintf(sol_fout_eva," %d, %c;\n",i,s[i][j]); } } //printf("\n"); } // TODO modify TODO use the Medium to exclude the three fprintf(sol_fout_eva,"////////////////////////////////////////////////////////////////////\n"); //printf("%d",sum); fflush(sol_fout_eva); fclose(sol_fout_eva); } // show the 2d view void solutionShowTofile( char s[][DAY_NUM]){ FILE *sol_fout = fopen("solutionTmp.txt", "w"); for(int i = 0; i < nurseTotal; i++){ for(int j = 0; j < DAY_NUM; j++){ fprintf(sol_fout,"%c",s[i][j]); //printf("%d ",solution[i][j]); //if( j%7 == 2 )fprintf(sol_fout,"|"); } fprintf(sol_fout,"\n"); } fflush(sol_fout); fclose(sol_fout); } // ========================= solution related ========================= void solCopy(char a[NURSE_NUM][DAY_NUM],char b[NURSE_NUM][DAY_NUM]){ for (int i = 0; i < NURSE_NUM ; i++){ for (int j = 0; j < DAY_NUM ; j++){ a[i][j] = b[i][j]; } } } // for some log void solutionReadof53(char s[NURSE_NUM][DAY_NUM] ){ static FILE* fin_53; errno_t err; err = fopen_s(&fin_53,"solutionTmpForRead.txt", "r"); char tmp; for(int i = 0; i < NURSE_NUM; i++){ for(int j = 0; j < DAY_NUM; j++){ fscanf_s(fin_53,"%c",&s[i][j]); //printf("%d ",solution[i][j]); //if( j%7 == 2 )fprintf(sol_fout,"|"); } fscanf_s(fin_53,"%c",&tmp); //fprintf(sol_fout,"\n"); } //fscanf_s(solRead,"%s",tmp, 500); } // ========================= operators ========================= void swap2shifts( char* a, char* b){ char tmp; tmp = *a; *a = *b; *b = tmp; } void randNurIdx(){ for(int i = 0; i<10; i++){ nurseRecord[i]=i; //printf("%d ",nurseRecord[i]); } int r; int tmp; for(int i = 0; i<10; i++){ r = rand() % (10-i); tmp = nurseRecord[9-i]; nurseRecord[9-i] = nurseRecord[r]; nurseRecord[r] = tmp; } //for(int i = 0; i<10; i++){ // printf("%d ",nurseRecord[i]); //} } void singleShiftSwap(char sol[NURSE_NUM][DAY_NUM]){ int d = rand()% DAY_NUM; int n1 = rand()% nurseTotal; int n2 = rand()% nurseTotal; while ( (sol[n1][d] == sol[n2][d]) )n2 = rand()% nurseTotal; char temp; temp = sol[n1][d]; sol[n1][d] = sol[n2][d]; sol[n2][d] = temp; } //void multiNurseSingleDaySwap(char sol[NURSE_NUM][DAY_NUM]){ // // int dayIdx = rand()% DAY_NUM; // // for( int nurseIdx = 0; nurseIdx < 5; nurseIdx++){ // swap2shifts( &sol[nurseIdx][dayIdx], &sol[nurseIdx+5][dayIdx]); // } // //} void twoNurseMultiDaySwap(char sol[NURSE_NUM][DAY_NUM], int dayNum){ int randIdx[28]; randomDayGen(randIdx, 28); int n1 = rand()% nurseTotal; int n2 = rand()% nurseTotal; while ( n1 == n2 ) n2 = rand()% nurseTotal; for (int i = 0; i < dayNum; i++) swap2shifts(&sol[n1][randIdx[i]], &sol[n2][randIdx[i]]); } void cycle3nurse(char sol[NURSE_NUM][DAY_NUM]){ randNurIdx(); int n1 = nurseRecord[0]; int n2 = nurseRecord[1]; int n3 = nurseRecord[2]; int d = rand()% DAY_NUM; swap2shifts(&sol[n1][d], &sol[n2][d]); swap2shifts(&sol[n1][d], &sol[n3][d]); } // swap two working shifts void singleWorkingDaySwap(char sol[NURSE_NUM][DAY_NUM]){ int d = rand()% DAY_NUM; int n1 = rand()% nurseTotal; int n2 = rand()% nurseTotal; while ( (sol[n1][d] == sol[n2][d]) || ((sol[n1][d] != 0)&&(sol[n2][d] == 0)) || ((sol[n1][d] == 0)&&(sol[n2][d] != 0))){ n1 = rand()% nurseTotal; n2 = rand()% nurseTotal; } char temp; temp = sol[n1][d]; sol[n1][d] = sol[n2][d]; sol[n2][d] = temp; } void singleWorkingDayMove(char sol[NURSE_NUM][DAY_NUM]){ int d = rand()% DAY_NUM; int n1 = rand()% nurseTotal; int n2 = rand()% nurseTotal; while ( (sol[n1][d] == 0)&&(sol[n2][d] == 0) || (sol[n1][d] != 0)&&(sol[n2][d] != 0)){ n1 = rand()% nurseTotal; //n2 = rand()% nurseTotal; } swap2shifts(&sol[n1][d], &sol[n2][d]); } void diffNurseSwap(char sol[NURSE_NUM][DAY_NUM]){ int randIdx[28]; randomDayGen(randIdx, 28); int n1 = randIntInterval(0,7); int n2 = randIntInterval(8,9); int width = randIntInterval(2,9); for( int i = 0; i<width; i++){ swap2shifts(&sol[n1][randIdx[i]], &sol[n2][randIdx[i]]); } } void diffNurseSlotSwap(char sol[NURSE_NUM][DAY_NUM]){ int widthStart =14; int widthEnd = 27; int dayWidth = (rand()% ( widthEnd - widthStart + 1) ) + widthStart; int startDayIdx = rand()% (DAY_NUM - dayWidth + 1); int n1 = randIntInterval(0,7); int n2 = randIntInterval(8,9); for(int dayIdx = startDayIdx; dayIdx <= dayWidth; dayIdx++) swap2shifts(&sol[n1][dayIdx],&sol[n2][dayIdx]); } void singleNurseMultiDayMove(char sol[NURSE_NUM][DAY_NUM]){ int randIdx[8]; randomDayGen(randIdx, 8); int n1 = rand()% nurseTotal; int n2 = rand()% nurseTotal; for( int i = 0; i < 4; i++){ while ( (n1 == n2) || (sol[n1][randIdx[i]] == 0)&&(sol[n2][randIdx[i]] == 0) || (sol[n1][randIdx[i]] != 0)&&(sol[n2][randIdx[i]] != 0)){ n2 = rand()% nurseTotal; } swap2shifts(&sol[n1][randIdx[i]], &sol[n2][randIdx[i]]); } } // multi day swap void nurseSlotSwap(char sol[NURSE_NUM][DAY_NUM]){ int widthStart = 12; int widthEnd = 27; int dayWidth = (rand()% ( widthEnd - widthStart + 1) ) + widthStart; int startDayIdx = rand()% (DAY_NUM - dayWidth + 1); int n1 = rand()% nurseTotal; int n2 = rand()% nurseTotal; while ( n1 == n2 ) n2 = rand()% nurseTotal; for(int dayIdx = startDayIdx; dayIdx <= dayWidth; dayIdx++) swap2shifts(&sol[n1][dayIdx],&sol[n2][dayIdx]); } void nurseSlotSwap_mid(char sol[NURSE_NUM][DAY_NUM], int widthStart, int widthEnd, int interval1,int interval2 ){ // int widthStart = 20; // int widthEnd = 27; int dayWidth = (rand()% ( widthEnd - widthStart + 1) ) + widthStart; int startDayIdx = rand()% (DAY_NUM - dayWidth + 1); //int s = (rand() % (5 - 1 + 1)) + 1; // [1,5] int s = randIntInterval(interval1,interval2); //int x1 = (rand() % ( (10-2*s) - 0 +1)) + 0; int x1 = randIntInterval( 0, 30 - 2*s ); int x2 = x1 + s -1; //int y1 = (rand() % ( (10-s) - (x2+1) +1)) + (x2+1); int y1 = randIntInterval( x2+1, 30-s); //printf("%d %d %d\n", s, x1, y1); for( int stepIdx = 0; stepIdx < s; stepIdx++){ for(int dayIdx = startDayIdx; dayIdx <= dayWidth; dayIdx++){ swap2shifts(&sol[x1+stepIdx][dayIdx],&sol[y1+stepIdx][dayIdx]); } } } void nurseSlotSwap2(char sol[NURSE_NUM][DAY_NUM]){ int widthStart = 12; int widthEnd = 21; int dayWidth = (rand()% ( widthEnd - widthStart + 1) ) + widthStart; int startDayIdx = rand()% (DAY_NUM - dayWidth + 1); int n1 = rand()% nurseTotal; int n2 = rand()% nurseTotal; while ( n1 == n2 ) n2 = rand()% nurseTotal; for(int dayIdx = startDayIdx; dayIdx <= dayWidth; dayIdx++) swap2shifts(&sol[n1][dayIdx],&sol[n2][dayIdx]); } void nurseSlotSwap_short(char sol[NURSE_NUM][DAY_NUM]){ int widthStart =2; int widthEnd = 11; int dayWidth = (rand()% ( widthEnd - widthStart + 1) ) + widthStart; int startDayIdx = rand()% (DAY_NUM - dayWidth + 1); int n1 = rand()% nurseTotal; int n2 = rand()% nurseTotal; while (n1 == n2) n2 = rand()% nurseTotal; //static int moveTime = 0; //static int a[10] = {0}; //if( moveTime%5 == 0)randomNurseGen(a,10); //int n1 = a[(moveTime*2)%10]; //int n2 = a[((moveTime*2)%10) + 1]; //moveTime++; for(int dayIdx = startDayIdx; dayIdx <= dayWidth; dayIdx++) swap2shifts(&sol[n1][dayIdx],&sol[n2][dayIdx]); } void nurseSlotSwap_blk(char sol[NURSE_NUM][DAY_NUM]){ int widthStart =2; int widthEnd = 15; int dayWidth = (rand()% ( widthEnd - widthStart + 1) ) + widthStart; int startDayIdx = rand()% (DAY_NUM - dayWidth + 1); int s = (rand() % (5 - 1 + 1)) + 1; // [1,5] int x1 = (rand() % ( (10-2*s) - 0 +1)) + 0; int x2 = x1 + s -1; int y1 = (rand() % ( (10-s) - (x2+1) +1)) + (x2+1); int y2 = y1 + s -1; for( int stepIdx = 0; stepIdx < s; stepIdx++){ for(int dayIdx = startDayIdx; dayIdx <= dayWidth; dayIdx++){ swap2shifts(&sol[x1+stepIdx][dayIdx],&sol[y1+stepIdx][dayIdx]); } } } // wkd swap. Not that effective yet void nurseWkdSwap(char sol[NURSE_NUM][DAY_NUM]){ int n1 = rand()% nurseTotal; int n2 = rand()% nurseTotal; while (n1 == n2) n2 = rand()% nurseTotal; for(int i = (7-startTimeOffset-1) ; i < DAY_NUM; i+=7){ int rand_tmp = rand ()% 10; if ( rand_tmp > 4){ int rand_tmp_2 = rand()%10; if ( rand_tmp_2 > 4){ swap2shifts(&sol[n1][i],&sol[n2][i]); } else{ swap2shifts(&sol[n1][i+1],&sol[n2][i+1]); } } } // char temp; // for(int dayIdx = 0; dayIdx <= 3; dayIdx++){ // // temp = sol[n1][dayIdx*7 + 1]; // sol[n1][dayIdx*7 + 1] = sol[n2][dayIdx*7 + 1]; // sol[n2][dayIdx*7 + 1] = temp; // // temp = sol[n1][dayIdx*7 + 2]; // sol[n1][dayIdx*7 + 2] = sol[n2][dayIdx*7 + 2]; // sol[n2][dayIdx*7 + 2] = temp; // } } void cycleMove(char sol[NURSE_NUM][DAY_NUM]){ int stepLengh = (rand() % (3-1+1)) + 1; //int randDayIdx = rand()% DAY_NUM; int randIdx[28]; randomDayGen(randIdx, 28); int daywidth = (rand() % (25-2+1)) + 2; //daywidth = 1; for(int dayIdx = 0; dayIdx < daywidth; dayIdx++){ int tempDayArray[NURSE_NUM] = {0}; for( int nurseIdx = 0; nurseIdx < nurseTotal; nurseIdx++) tempDayArray[ (nurseIdx + stepLengh) % nurseTotal] = sol[nurseIdx][randIdx[dayIdx]]; for( int nurseIdx = 0; nurseIdx < nurseTotal; nurseIdx++) sol[nurseIdx][randIdx[dayIdx]] = tempDayArray[nurseIdx]; } } void shakingSingleNurse(char sol[NURSE_NUM][DAY_NUM], int nIdx){ int randIdx[28]; randomDayGen(randIdx, 28); int width = randIntInterval(5,15); for( int i = 0; i < width; i++){ int n1 = rand()% nurseTotal; while (n1 == nIdx) n1 = rand()% nurseTotal; swap2shifts(&sol[nIdx][randIdx[i]],&sol[n1][randIdx[i]]); } //int widthStart = 2; //int widthEnd = 6; //int dayWidth = (rand()% ( widthEnd - widthStart + 1) ) + widthStart; //int startDayIdx = rand()% (DAY_NUM - dayWidth + 1); //int n1 = rand()% nurseTotal; //while (n1 == nIdx) // n1 = rand()% nurseTotal; //for(int dayIdx = startDayIdx; dayIdx <= dayWidth; dayIdx++) // swap2shifts(&sol[n1][dayIdx],&sol[nIdx][dayIdx]); } void twoNurseShaking(char sol[NURSE_NUM][DAY_NUM]){ //int n1 = rand()% nurseTotal; //int n2 = rand()% nurseTotal; //while (n1 == n2) // n2 = rand()% nurseTotal; //int n3 = rand()% nurseTotal; //int n4 = rand()% nurseTotal; int a[5]; randomNurseGen(a,5); shakingSingleNurse(sol, a[0]); shakingSingleNurse(sol, a[1]); //shakingSingleNurse(sol, a[2]); //shakingSingleNurse(sol, a[3]); //shakingSingleNurse(sol, a[4]); //shakingSingleNurse(sol, a[5]); } // the major force of the search void findNeigh(char sol[NURSE_NUM][DAY_NUM]){ static int run_time = 0; // if( run_time % 500 == 0 ){ // //nurseSlotSwap_blk(sol); // twoNurseShaking(sol); // // } int thehold = rand()% 100; if(thehold >40){ if( thehold > 60 ){ nurseSlotSwap(sol); } else { //nurseSlotSwap(sol); nurseSlotSwap_short(sol); //twoNurseMultiDaySwap(sol,5); typeIdx = 1; } } else{ if(thehold >20){ twoNurseMultiDaySwap(sol,2); //nurseWkdSwap(sol); typeIdx = 2; } else { singleWorkingDayMove(sol); //diffNurseSwap(sol); typeIdx = 3; } /* else { nurseSlotSwap_blk(sol); }*/ } run_time++; } void findNeigh_mid(char sol[NURSE_NUM][DAY_NUM]){ static int run_time = 0; // if( run_time % 500 == 0 ){ // //nurseSlotSwap_blk(sol); // twoNurseShaking(sol); // // } int thehold = rand()% 100; if(thehold > 50){ if( thehold > 70 ){ if( thehold > 90) nurseSlotSwap_mid(sol,20,27,2,9); else nurseSlotSwap_mid(sol,12,21,2,9); } else { nurseSlotSwap_mid(sol,3,9,1,9); typeIdx = 1; } } else{ if(thehold > 5){ twoNurseMultiDaySwap(sol,2); typeIdx = 2; } else { singleWorkingDayMove(sol); typeIdx = 3; } /* else { nurseSlotSwap_blk(sol); }*/ } run_time++; } void findNeigh_test1(char sol[NURSE_NUM][DAY_NUM]){ static int run_time = 0; if( run_time % 2 == 1){ twoNurseMultiDaySwap(sol,2); } else if( run_time %3 == 1){ nurseSlotSwap(sol); } else if( run_time % 5 == 1){ nurseSlotSwap_short(sol); } else if( run_time % 7 == 1){ singleWorkingDayMove(sol); } run_time++; } void findNeigh_intelligent( char sol[NURSE_NUM][DAY_NUM] ){ char sol_temp[4][NURSE_NUM][DAY_NUM]; int r[4] = {0}; solCopy(sol_temp[0], sol); twoNurseMultiDaySwap(sol_temp[0],2); r[0] = evaluate(sol_temp[0]); solCopy(sol_temp[1], sol); nurseSlotSwap_short(sol_temp[1]); r[1] = evaluate(sol_temp[1]); solCopy(sol_temp[2], sol); nurseSlotSwap(sol_temp[2]); r[2] = evaluate(sol_temp[2]); solCopy(sol_temp[3], sol); singleWorkingDayMove(sol_temp[3]); r[3] = evaluate(sol_temp[3]); //printf("\n the 4 are: %d %d %d %d \n", r[0], r[1], r[2], r[3]); int min = 1000000; int min_idx = 0; if( r[0] == r[1] && r[1] == r[2] && r[2] == r[3]){ min_idx = randIntInterval(0,3); } else{ for( int i = 0 ; i < 4; i++){ if( r[i] < min){ min = r[i]; min_idx = i; } } } //printf("idx is %d \n", min_idx); solCopy(sol, sol_temp[min_idx]); } int distanceShift(char a[NURSE_NUM][DAY_NUM],char b[NURSE_NUM][DAY_NUM]){ int sum = 0; for(int i = 0; i < nurseTotal; i++){ for(int j = 0; j < DAY_NUM; j++){ if( a[i][j] != b[i][j] ){ sum++; } } } return sum; } int distanceWorkingDay(char a[NURSE_NUM][DAY_NUM],char b[NURSE_NUM][DAY_NUM]){ int sum = 0; for(int i = 0; i < nurseTotal; i++){ for(int j = 0; j < DAY_NUM; j++){ if( a[i][j] != 0 && b[i][j] != 0){ if( a[i][j] != b[i][j] ){ sum++; } } } } return sum; } void partDayCopy(char a[NURSE_NUM][DAY_NUM], char b[NURSE_NUM][DAY_NUM],int startDay, int endDay){ assert(startDay <= endDay); assert(startDay >=0 && endDay <= DAY_NUM); for(int i = 0; i < NURSE_NUM; i++){ for(int j = startDay; j<endDay; j++){ a[i][j] = b[i][j]; } } } void copyDecomp(char a[NURSE_NUM][DAY_NUM], char b[NURSE_NUM][DAY_NUM], char s[NURSE_NUM][DAY_NUM]){ const int dayNum = 27; int randIdx[dayNum]; randomDayGen(randIdx, dayNum); for(int dayIdx = 0; dayIdx < dayNum; dayIdx++){ for(int nIdx = 0; nIdx < nurseTotal; nIdx++){ a[nIdx][randIdx[dayIdx]] = s[nIdx][randIdx[dayIdx]]; } } randomDayGen(randIdx, dayNum); for(int dayIdx = 0; dayIdx < dayNum; dayIdx++){ for(int nIdx = 0; nIdx < nurseTotal; nIdx++){ b[nIdx][randIdx[dayIdx]] = s[nIdx][randIdx[dayIdx]]; } } } void initShake(char a[NURSE_NUM][DAY_NUM],char s[NURSE_NUM][DAY_NUM]){ const int dayNum = 2; int randIdx[dayNum]; randomDayGen(randIdx, dayNum); for(int dayIdx = 0; dayIdx < dayNum; dayIdx++){ for(int nIdx = 0; nIdx < nurseTotal; nIdx++){ a[nIdx][randIdx[dayIdx]] = s[nIdx][randIdx[dayIdx]]; } } } // ========================= solution support ========================= void initMole(struct Molecule *a){ solutionCreate(a->mole); //printf("the fitness is %d \n",evaluate(MoleculePop[i].mole)); a->PE = evaluate(a->mole); solCopy(a->MinStruct, a->mole); a->KE = initialKE; a->NumHit = 0; a->MinPe = a->PE; a->MinHit = 0; //showMole(a); } void resetEnergy(struct Molecule *a){ a->KE = initialKE; //showMole(a); } void computInfo(struct Molecule *a){ a->PE = evaluate(a->mole); solCopy(a->MinStruct, a->mole); a->KE = initialKE; a->NumHit = 0; a->MinPe = a->PE; a->MinHit = 0; //showMole(a); } // find the optimal value int findMinEp( struct Molecule pop[popSizeMax] ){ int fitMin = 100000; int optiIdx = 0; for(int i = 0; i < currentPopSize; i++){ //if (MoleculePop[i].MinPe < fitMin ){ if ( pop[i].MinPe < fitMin ){ //fitMin = MoleculePop[i].MinPe; fitMin = pop[i].MinPe; optiIdx = i; } } return fitMin; } // find the optimal index int findMinIdx( struct Molecule pop[popSizeMax] ){ int fitMin = 100000; int optiIdx = 0; for(int i = 0; i < currentPopSize; i++){ //if (MoleculePop[i].MinPe < fitMin ){ if ( pop[i].MinPe < fitMin ){ // fitMin = MoleculePop[i].MinPe; fitMin = pop[i].MinPe; optiIdx = i; } } return optiIdx; } //void watchingCro(){ // int watTimes = 1; // for(int i = 0; i<watTimes; i++){ // crosearch(); // solCopy(optiHolder[i],optiSolution); // //printf("opti is %d\n", evaluate(optiSolution)); // } // for(int i = 0; i<watTimes; i++){ // printf("distance is %d\n", hDistance(optiHolder[0],optiHolder[i])); // } //} void solutionSwap(char sol[NURSE_NUM][DAY_NUM], int dayIdx, int nurse1, int nurse2){ swap2shifts( &sol[nurse1][dayIdx], &sol[nurse2][dayIdx]); }
zzr-cro-nurse
trunk/supportFunctions.cpp
C++
gpl3
22,412
#include <stdio.h> #include <string.h> #include <assert.h> #include <time.h> #include <stdlib.h> #include"functions.h"
zzr-cro-nurse
trunk/operators.cpp
C++
gpl3
137
#include <stdio.h> #include <string.h> #include <assert.h> #include <time.h> #include <stdlib.h> #include"functions.h" int holder[10] = {0}; int idx_6_10[210][6] = {0}; int sum = 0; void comb(int a, int b){ if ( a == 6 ) { for (int i =0; i<6; i++){ // printf("%d ",holder[i]); idx_6_10[sum][i] = holder[i]; } //printf("\n"); sum++; return; } for ( int i = b + 1; i <= 10 - 6 + a + 1; i++) { holder[a] = i; comb(a+1, i); } } int main(void) { initial(); //comb(0,0); //printf("sum is %d",sum); //for (int i = 0; i < 210; i++){ // for (int j = 0; j < 6; j++) { // printf("%d ",idx_6_10[i][j]); // } // printf("\n"); //} //getchar(); experiment(); // ---------- block start end test --------------- // int s = (rand() % (5- 1 + 1)) + 1; // [1,5] // int x1 = (rand() % ( (10-2*s) - 0 +1)) + 0; // int x2 = x1 + s -1; // // int y1 = (rand() % ( (10-s) - (x2+1) +1)) + (x2+1); // int y2 = y1 + s -1; // printf("step %d, x1 %d x2 %d, y1 %d y2 %d\n", s,x1,x2,y1,y2); // --------------- penalty test ----------------- //Load("instance\\sprint04.txt"); //char s[NURSE_NUM][DAY_NUM] = {0}; //solutionCreate(s); //printf("value is %d", evaluate(s)); //solutionRosterShowScreen(s); //getchar(); //showPenaltySpec(); //for( int i = 0; i < nurseTotal; i++) // printf("nurse %d, total penalty is %d\n", nursePenRec[i].idx,nursePenRec[i].total); // ////for( int i = 0; i < nurseTotal; i++) //printf("\n"); //qsort(nursePenRec,NURSE_NUM,sizeof(nursePenRec[0]),cmp); //for( int i = 0; i < nurseTotal; i++) // printf("nurse %d, total penalty is %d\n", nursePenRec[i].idx,nursePenRec[i].total); // --------------- compare ----------------- //Load("instance\\sprint04.txt"); // char lv[NURSE_NUM][DAY_NUM] = {0}; // solutionStandardRead(lv,"solutions\\zzrSolu_s04_59.txt"); ////solutionCreate(lv); // solutionRosterShowScreen(lv); // printf("value is %d", evaluate(lv)); // showPenaltySpec(); //for( int i = 0; i < nurseTotal; i++) // printf("nurse %d, has a pen of workingday of %d\n", i,nursePenRec[i].workingday); // //for( int i = 0; i < nurseTotal; i++) // printf("nurse %d, total penalty is %d\n", i,nursePenRec[i].total); //char zz[NURSE_NUM][DAY_NUM] = {0}; //solutionStandardRead(zz,"solutions\\zzrSolu_s04_60.txt"); // solutionRosterShowScreen(zz); //printf("value is %d", evaluate(zz)); //showPenaltySpec(); // //for( int i = 0; i < nurseTotal; i++){ // printf("nurse %d, has a pen of workingday of %d\n", i,nursePenRec[i].workingday); //} // //printf("\ndistance of shift is %d", distanceShift(lv,zz)); //printf("\ndistance of working day is %d", distanceWorkingDay(lv,zz)); //int a[10]; //randomNurseGen(a,10); // int a[4]; // randomDayGen(a, 4); //--------------------------------- test solution create ------------------------------- //char s[NURSE_NUM][DAY_NUM] = {0}; //solutionCreate(s); //---------------------------------- search ------------------------ //for(int i = 0; i < 1; i++) // read the optimal solution //char s[NURSE_NUM][DAY_NUM] = {0}; //solutionRead(s); //printf("game over\n"); //getchar(); return 0; }
zzr-cro-nurse
trunk/main.cpp
C++
gpl3
3,371
#include <stdio.h> #include <string.h> #include <assert.h> #include <time.h> #include <stdlib.h> #include"functions.h" // the current solution //char sol[NURSE_NUM][DAY_NUM]={0}; ///////////////////////////////////////// // constraints need to be loaded from the instance //////////////////////////////////////// // cover constraint, which is one of the hard cons. // '7' is the dayidx and 4 is the type that needed // because the head nurse add, another shift type add, so the number is 5 //int cover_h[7][5] = {0}; //int nurseTotal = 0; int nurseSkill[NURSE_NUM] = {0}; int nursesContraMap[NURSE_NUM]; int nurseDayoff[NURSE_NUM][DAY_NUM]; char nurseShiftoff[NURSE_NUM][DAY_NUM][10] = {0}; // weight is always 1 int nurseShiftoffNum[NURSE_NUM][DAY_NUM] = {0}; // mutiple shift off request, record the number //int nurseShiftoff[NURSE_NUM][DAY_NUM][2]; contra contractArray[5] = {0}; char uPatterns[10][10] = {'F'}; //srand((unsigned)time(NULL)); void initial(){ //printf("\n %d %d",rTestP1[0][0], nTest[3][1]); //uPatterns[10][10] = {0}; // initialize the special pattern // uPatterns[2][0] = 3; // uPatterns[2][1] = 'F'; // uPatterns[2][2] = 'A'; // uPatterns[2][3] = 'A'; //char solution[NURSE_NUM][DAY_NUM]; }
zzr-cro-nurse
trunk/initialization.cpp
C++
gpl3
1,322
// ==================================================== // The four elementary reaction // and the complete process of CRO // // // ==================================================== #include <stdio.h> #include <string.h> #include <assert.h> #include <time.h> #include <stdlib.h> #include"functions.h" int randomTool = (srand(time(NULL)), 0) ; char Sol55[NURSE_NUM][DAY_NUM] = {0}; char beforeDecomp[NURSE_NUM][DAY_NUM] = {0}; struct historyArrayStruct historyArray[20] = {0}; clock_t start, finish; double duration; // ========================= the debug ========================= // debug for getchar() in searching //#define debug_getchar //#define intell_change int currentPopSize; // the inital popSize double MoleColl; int initialKE; // the tolerance double be; int buffer; double KElossRate; int al; int local_num; int generation_num; int optiValueGlo; char optiSolution[NURSE_NUM][DAY_NUM] = {0}; // 1 for slot // 2 for move // 3 for swap int typeIdx = 0; int lastSwapDay = 0; int lastSwapNurse1 = 0; int lastSwapNurse2 = 0; int a1 = 90; int a2 = 60; int a3 = 30; // ========================= for record ========================= int onwallNum = 0; int decompNum = 0; // TODO: from global to inter int synthNum = 0; int intcollNum = 0; char tmpSol1[NURSE_NUM][DAY_NUM] = {0}; char tmpSol2[NURSE_NUM][DAY_NUM] = {0}; int cmp( const void *b ,const void *a){ return (*(penaltyRec*)a).total > (*(penaltyRec*)b).total ? 1 : -1; } void showPenaltySpec(){ printf("\nMaxMinWorkingDay %d, conDay %d, conFree %d, conWkd %d, wkd %d\nthree %d, dayoff %d, shiftoff %d, pat %d\n", pRec.workingday, pRec.consecWorkingday, pRec.consecFree, pRec.consecWorkingWkd, pRec.maxwkd, pRec.threeWkd, pRec.dayoff, pRec.shiftoff, pRec.pattern); } void onwall(int idx, struct Molecule pop[popSizeMax] ){ onwallNum++; char newSol[NURSE_NUM][DAY_NUM] = {0}; //solCopy( newSol, MoleculePop[idx].mole); solCopy( newSol, pop[idx].mole ); //solCopy( newSol, MoleculePop[idx].MinStruct); // main search force findNeigh(newSol); //findNeigh_mid(newSol); //findNeigh_intelligent(newSol); //findNeigh_test1(newSol); int newPE = evaluate(newSol); //printf("%d \n", MoleculePop[idx].PE - newPE ); //MoleculePop[idx].NumHit++; pop[idx].NumHit++; if (pop[idx].PE + pop[idx].KE >= newPE){ // a is between (KElossrate,1) double a = KElossRate + ((double)rand()/RAND_MAX)*(1-KElossRate); //double a = 0.95; //printf("loss a is %f ",a); // TODO: the tweak of the interval, such as (0.05,0.1) or (0.95,1)? // more faster more better, or more slower more better? // the newKE should be more and more less //int newKE = (MoleculePop[idx].PE + MoleculePop[idx].KE - newPE)*a; int newKE = (pop[idx].PE + pop[idx].KE - newPE)*a; //buffer += (MoleculePop[idx].PE + MoleculePop[idx].KE - newPE) - newKE; buffer += (pop[idx].PE + pop[idx].KE - newPE) - newKE; //solCopy( MoleculePop[idx].mole, newSol ); solCopy( pop[idx].mole, newSol ); //MoleculePop[idx].PE = newPE; pop[idx].PE = newPE; //MoleculePop[idx].KE = newKE; pop[idx].KE = newKE; if( onwallNum %100 == 0) pop[idx].KE += 2;// for test // update the best // if(MoleculePop[idx].PE < MoleculePop[idx].MinPe){ // MoleculePop[idx].MinPe = MoleculePop[idx].PE; // MoleculePop[idx].MinHit = MoleculePop[idx].NumHit; // solCopy(MoleculePop[idx].MinStruct, MoleculePop[idx].mole); // } if(pop[idx].PE < pop[idx].MinPe){ pop[idx].MinPe = pop[idx].PE; pop[idx].MinHit = pop[idx].NumHit; solCopy(pop[idx].MinStruct, pop[idx].mole); } //showMole( MoleculePop[idx] ); } } void decomp(int idx, struct Molecule pop[popSizeMax]){ // a1 = (rand() % (100-50+1)) + 50; // a2 = (rand() % (a1-10+1)) + 10; // a3 = (rand() % (a2+1)); // static int decompIdx = 0; // // printf("================\n"); // for(int i = 0; i < decompIdx%20; i++ ){ // printf("distance is: %d %d\n", distanceShift(pop[findMinIdx(pop)].MinStruct, historyArray[i].sol), // distanceWorkingDay(pop[findMinIdx(pop)].MinStruct, historyArray[i].sol)); // } // printf("================\n"); // // solCopy(historyArray[decompIdx%20].sol,pop[findMinIdx(pop)].MinStruct); // decompIdx++; // printf("distance is: %d %d\n", distanceShift(pop[findMinIdx(pop)].MinStruct, beforeDecomp), // distanceWorkingDay(pop[findMinIdx(pop)].MinStruct, beforeDecomp)); // solCopy(beforeDecomp,pop[findMinIdx(pop)].MinStruct); //al = 90000; decompNum++; struct Molecule new1; struct Molecule new2; struct Molecule new3; //solCopy(new1.mole,pop[findMinIdx(pop)].MinStruct); //solCopy(new2.mole,pop[findMinIdx(pop)].MinStruct); //solCopy(new3.mole,pop[findMinIdx(pop)].MinStruct); solCopy(new1.mole,optiSolution); solCopy(new2.mole,optiSolution); solCopy(new3.mole,optiSolution); //initMole(&new1); //initMole(&new2); //copyDecomp(new1.mole, new2.mole, pop[findMinIdx(pop)].MinStruct); for(int i = 0; i <1; i++ ){ //for(int i = 0; i < 20; i++ ){ // medium //diffNurseSwap(new1.mole); //diffNurseSwap(new2.mole); //diffNurseSwap(new3.mole); diffNurseSlotSwap(new1.mole); diffNurseSlotSwap(new2.mole); diffNurseSlotSwap(new3.mole); //evaluate(new2.mole); //qsort(nursePenRec,NURSE_NUM,sizeof(nursePenRec[0]),cmp); //shakingSingleNurse(new2.mole,nursePenRec[0].idx); //cycleMove(new1.mole); //cycleMove(new2.mole); //cycleMove(new3.mole); // nurseWkdSwap(new1.mole); // nurseWkdSwap(new2.mole); // nurseWkdSwap(new3.mole); // char s1[NURSE_NUM][DAY_NUM] = {0}; // solutionCreate(s1); // initShake(new1.mole,s1); // //nurseSlotSwap_blk(new1.mole); // nurseSlotSwap_blk(new2.mole); //twoNurseShaking(new2.mole); //cycleMove(new3.mole); // twoNurseShaking(new1.mole); //singleNurseMultiDayMove(new1.mole); //singleNurseMultiDayMove(new2.mole); //findNeigh(new1.mole); //findNeigh(new2.mole); //nurseSlotSwap(new1.mole); //nurseSlotSwap(new2.mole); } computInfo(&new1); computInfo(&new2); computInfo(&new3); //printf("new1's value is %d",new1.PE); //printf("new2's value is %d",new2.PE); float Edec; // if (MoleculePop[idx].PE + MoleculePop[idx].KE > new1.PE + new2.PE){ //if ( pop[idx].PE + pop[idx].KE > new1.PE + new2.PE){ if ( pop[idx].PE * 2 + pop[idx].KE > new1.PE + new2.PE + new3.PE){ //Edec = MoleculePop[idx].PE + MoleculePop[idx].KE - (new1.PE + new2.PE); Edec = pop[idx].PE * 2 + pop[idx].KE - (new1.PE + new2.PE); goto step13; } else { double delta1 = (double)rand()/RAND_MAX; double delta2 = (double)rand()/RAND_MAX; delta1 = 1; delta2 = 0.99; //Edec = pop[idx].PE + pop[idx].KE + // delta1 * delta2 * buffer - (new1.PE + new2.PE); Edec = pop[idx].PE * 2 + pop[idx].KE + delta1 * delta2 * buffer - (new1.PE + new2.PE + new3.PE); if ( Edec >= 0 ){ buffer = buffer - buffer *delta1 * delta2 ; step13: //double delta3 = (double)rand()/RAND_MAX; //double delta3 = 0.5; //new1.KE = Edec * delta3; //new2.KE = Edec - new1.KE; double delta3 = 0.3; double delta4 = 0.3; new1.KE = Edec * delta3; new2.KE = Edec * delta4; new3.KE = Edec - new1.KE - new2.KE; // add to the population // copy one new to the selected // copy another one to the last //MoleculePop[currentPopSize] = new2; //MoleculePop[idx] = new1; pop[currentPopSize] = new2; pop[currentPopSize+1] = new3; pop[idx] = new1; currentPopSize+=2; //currentPopSize++; } else { pop[idx].NumHit++; } } } void synthe(int idx1, int idx2, struct Molecule pop[popSizeMax] ){ //printf("synthe \n"); assert(idx1 < currentPopSize && idx2 < currentPopSize); synthNum++; // combination of two into one // there should be many method, first, we use two half combine into one struct Molecule new1 = {0}; if( (double)rand()/RAND_MAX > 0.5 ){ //if( evaluate(pop[idx1].mole) < evaluate(pop[idx2].mole) ){ solCopy(new1.mole, pop[idx1].mole); } else solCopy(new1.mole, pop[idx2].mole); // should not use the initialization function but combine the above two //first half from idx1 // for (int i = 0; i < NURSE_NUM ; i++) // for (int j = 0; j < halfpoint ; j++) // //new1.mole[i][j]= MoleculePop[idx1].mole[i][j]; // new1.mole[i][j]= pop[idx1].mole[i][j]; // // // second half from idx2 // for (int i = 0; i < NURSE_NUM ; i++) // for (int j = halfpoint; j < DAY_NUM ; j++) // //new1.mole[i][j]= MoleculePop[idx2].mole[i][j]; // new1.mole[i][j]= pop[idx2].mole[i][j]; new1.PE = evaluate(new1.mole); solCopy(new1.MinStruct, new1.mole); new1.NumHit = 0; new1.MinPe = new1.PE; new1.MinHit = 0; //left KE //if(MoleculePop[idx1].PE + MoleculePop[idx2].PE + MoleculePop[idx1].KE + MoleculePop[idx2].KE >= if( pop[idx1].PE + pop[idx2].PE + pop[idx1].KE + pop[idx2].KE >= new1.PE){ //new1.KE = MoleculePop[idx1].PE + MoleculePop[idx2].PE + MoleculePop[idx1].KE + new1.KE = pop[idx1].PE + pop[idx2].PE + pop[idx1].KE + // MoleculePop[idx2].KE - new1.PE; pop[idx2].KE - new1.PE; // add the two new into the population int smallerIdx = (idx1 < idx2 )?idx1:idx2; //MoleculePop[smallerIdx] = new1; pop[smallerIdx] = new1; int biggerIdx = (idx1 > idx2 )?idx1:idx2; //MoleculePop[biggerIdx] = MoleculePop[currentPopSize-1]; pop[biggerIdx] = pop[currentPopSize-1]; //memset( &MoleculePop[currentPopSize-1], 0, sizeof(Molecule) ); memset( &pop[currentPopSize-1], 0, sizeof(Molecule) ); currentPopSize--; //printf("pop minus\n"); } else{ // leave alone //MoleculePop[idx1].NumHit++; pop[idx1].NumHit++; //MoleculePop[idx2].NumHit++; pop[idx2].NumHit++; } ////showMole(a); // TODO test this function } void intcolli(int idx1,int idx2, struct Molecule pop[popSizeMax]){ intcollNum++; char newSol1[NURSE_NUM][DAY_NUM] = {0}; char newSol2[NURSE_NUM][DAY_NUM] = {0}; solCopy( newSol1, pop[idx1].mole); solCopy( newSol2, pop[idx2].mole); // int halfpoint = rand()%(DAY_NUM -2 -1+1) + 1; // // for( int dayIdx = 0; dayIdx < halfpoint; dayIdx++){ // for(int nIdx = 0; nIdx < nurseTotal; nIdx++){ // swap2shifts(&newSol1[nIdx][dayIdx], &newSol2[nIdx][dayIdx]); // } // } // // findNeigh(newSol1); // findNeigh(newSol2); //findNeigh_intelligent(newSol1); //findNeigh_intelligent(newSol2); int randIdx[15]; randomDayGen(randIdx, 15); for( int i = 0; i < 15; i++){ for(int nIdx = 0; nIdx < nurseTotal; nIdx++){ swap2shifts(&newSol1[nIdx][randIdx[i]], &newSol2[nIdx][randIdx[i]]); } } int newPE1 = evaluate(newSol1); pop[idx1].NumHit++; int newPE2 = evaluate(newSol2); pop[idx2].NumHit++; // int Einter = (MoleculePop[idx1].PE + MoleculePop[idx2].PE // + MoleculePop[idx1].KE + MoleculePop[idx2].KE)-( newPE1 + newPE2); int Einter = ( pop[idx1].PE + pop[idx2].PE + pop[idx1].KE + pop[idx2].KE)-( newPE1 + newPE2); if( Einter >= 0 ){ //printf(" adding \n"); double a = (double)rand()/RAND_MAX; pop[idx1].KE = Einter * a; pop[idx2].KE = Einter - pop[idx1].KE; solCopy( pop[idx1].mole, newSol1); solCopy( pop[idx2].mole, newSol2); pop[idx1].PE = newPE1; pop[idx2].PE = newPE2; if( pop[idx1].PE < pop[idx1].MinPe){ pop[idx1].MinPe = pop[idx1].PE; pop[idx1].MinHit = pop[idx1].NumHit; solCopy(pop[idx1].MinStruct, pop[idx1].mole); } if( pop[idx2].PE < pop[idx2].MinPe){ pop[idx2].MinPe = pop[idx2].PE; pop[idx2].MinHit = pop[idx2].NumHit; solCopy(pop[idx2].MinStruct, pop[idx2].mole); } } } //void crosearch( int opt_value){ //float crosearch( int opt_value){ int crosearch(){ // initialization currentPopSize = 1; MoleColl= 0.9; initialKE = 1000; // the tolerance be = 50;// sprint be = 5; buffer =500; KElossRate = 0.5; al = 100000; //sprint al = 20000; //sprint //al = 10000; //sprint //al = 500000; //medium local_num = 0; generation_num = 500000000; // generation_num = 1; optiValueGlo= 0; //static FILE *decomp_fout = fopen("decomp_show.txt", "w+"); struct Molecule MoleculePop[popSizeMax] = {0}; // create a larger holder //char optiHolder[10][NURSE_NUM][DAY_NUM] = {0}; // for h distance //optiSolution[NURSE_NUM][DAY_NUM] = {0}; // ================ initial every mole ================= for(int moleidx = 0; moleidx < currentPopSize; moleidx++) // initalize the small size :10 { initMole(&MoleculePop[moleidx]); //solutionShow(MoleculePop[moleidx].mole); printf("\n"); } memset(optiSolution, 0, sizeof(optiSolution));// reset opti // =================== search =================== int optiFit = 10000; int optiFitForLog = 10000; start = clock(); //for (int generationIndex = 0; generationIndex <0 ; generationIndex++){ for (int generationIndex = 0; generationIndex < generation_num; generationIndex++){ //for (int generationIndex = 0; generationIndex < 1; generationIndex++){ double b = (double)rand()/RAND_MAX; if( b > MoleColl || currentPopSize == 1){// =================== uni reaction ====================== int selectedIdx = rand()% (currentPopSize); if (MoleculePop[selectedIdx].NumHit - MoleculePop[selectedIdx].MinHit > al ){ //for(int moleidx = 0; moleidx < currentPopSize; moleidx++) // initalize the small size :10 // resetEnergy(&MoleculePop[moleidx]); //solutionShow(MoleculePop[moleidx].mole); //printf("\n"); //int holder = 1; decomp(selectedIdx, MoleculePop); } else onwall(selectedIdx, MoleculePop); } else{//=================== inter reaction =================== int selectedIdx1 = rand()% (currentPopSize); int selectedIdx2 = rand()% (currentPopSize); while ( selectedIdx2 == selectedIdx1 ) selectedIdx2 = rand()% (currentPopSize); #ifdef intell_change // use this condition to let this reaction as effective as the onwall if(MoleculePop[selectedIdx1].NumHit - MoleculePop[selectedIdx1].MinHit > (al/100) || MoleculePop[selectedIdx2].NumHit - MoleculePop[selectedIdx2].MinHit > (al/100)){ #endif #ifndef intell_change if(MoleculePop[selectedIdx1].KE <= be && MoleculePop[selectedIdx2].KE <= be){ #endif //if(MoleculePop[selectedIdx1].KE > be && MoleculePop[selectedIdx2].KE > be){ //printf("KE are %d %d\n",MoleculePop[selectedIdx1].KE,MoleculePop[selectedIdx2].KE); //intcolli(selectedIdx1,selectedIdx2); //if(findMinEp() < 65) synthe(selectedIdx1,selectedIdx2, MoleculePop); } else intcolli(selectedIdx1,selectedIdx2,MoleculePop); } // logging the pop //if( findMinEp(MoleculePop) < optiFitForLog || currentPopSize >1){ ////if( findMinEp() < optiFitForLog ){ // //printf("what the \n"); // //showPop(MoleculePop); // // optiFitForLog = findMinEp(MoleculePop); // if(currentPopSize >1){ // optiFitForLog = 10000; // } //} optiValueGlo = findMinEp(MoleculePop); if ( findMinEp(MoleculePop) < optiFit ){ optiFit = findMinEp(MoleculePop); //printf("min is %d \n", optiFit); printf("min is %d buffer is %d wall %d decom %d syn %d int %d\n", optiFit,buffer, onwallNum,decompNum,synthNum,intcollNum); //showPenaltySpec(); solCopy(optiSolution,MoleculePop[findMinIdx(MoleculePop)].MinStruct); solutionStandardOutputFile(optiSolution); //finish = clock(); //duration = (double)(finish - start) / CLOCKS_PER_SEC; //printf( " %1.2f sec\n", duration ); // for evaluator test //if( optiFit == opt_value){ // //solutionOutput(optiSolution); // printf("%d \n", evaluate(optiSolution)); // solutionRosterShowScreen(optiSolution); // showPenaltySpec(); // solutionStandardOutputFile(optiSolution); // // finish = clock(); // duration = (double)(finish - start) / CLOCKS_PER_SEC; // printf( "%f seconds\n", duration ); // // printf("\n%s",instAttri.instanceName); // return duration; // break; //} } finish = clock(); duration = (double)(finish - start) / CLOCKS_PER_SEC; if ( duration >8.3){ printf("min is %d \n", optiFit); return optiFit; //break; } #ifdef debug_getchar //if( findMinEp(MoleculePop) < 80 ){ getchar(); //} #endif } // search of generations //fclose(decomp_fout); } void experiment(){ char instance_name[200][30] = { "holder", "instance\\sprint01.txt","instance\\sprint02.txt","instance\\sprint03.txt","instance\\sprint04.txt", "instance\\sprint05.txt","instance\\sprint06.txt","instance\\sprint07.txt","instance\\sprint08.txt", "instance\\sprint09.txt","instance\\sprint10.txt", "instance\\sprint_late01.txt","instance\\sprint_late02.txt","instance\\sprint_late03.txt", "instance\\sprint_late04.txt","instance\\sprint_late05.txt","instance\\sprint_late06.txt", "instance\\sprint_late07.txt","instance\\sprint_late08.txt","instance\\sprint_late09.txt", "instance\\sprint_late10.txt", "instance\\sprint_hidden01.txt","instance\\sprint_hidden02.txt","instance\\sprint_hidden03.txt","instance\\sprint_hidden04.txt", "instance\\sprint_hidden05.txt", "instance\\medium01.txt","instance\\medium02.txt","instance\\medium03.txt","instance\\medium04.txt", "instance\\medium05.txt", "instance\\medium_late01.txt","instance\\medium_late02.txt","instance\\medium_late03.txt","instance\\medium_late04.txt", "instance\\medium_late05.txt", "instance\\medium_hidden01.txt","instance\\medium_hidden02.txt","instance\\medium_hidden03.txt","instance\\medium_hidden04.txt", "instance\\medium_hidden05.txt", }; int opti_array[50] = { 0, 56,58,51,59,58,54,56,56,55,52, // sprint 1 ~ 10; difficult: #4,#7,#10 37,42,48,73,44,42,42,17,17,43, // sprint late 11 ~ 20; easy:18,19, almost diff 33,32,62,67,59, // sprint hidden 21-25: tend to trap into the near-optimal 240,240,236,237,303, // medium 26 ~ 30 158,18,29,35,107, // medium late 31 ~ 35 130,221,36,80,122, // medium hidden 36 ~ 40 }; //float time_found = 0; // single test int sprint_id = 13; Load(instance_name[sprint_id]); printf("value is %d", crosearch()); getchar(); //FILE *file_result = fopen("test_result.txt", "w+"); //for (int instance_id = 1; instance_id <= 25; instance_id++){ // int run_num = 5; // int max_value = 0; // int min_value = 1000; // float total_value = 0; // //float avg_value = 0; // Load(instance_name[instance_id]); // for(int i = 0; i < run_num; i++){ // int t = crosearch(); // //printf("value is %d", t); // if( t < min_value) min_value = t; // if( t > max_value) max_value = t; // total_value += t; // } // fprintf(file_result,"%s: opti %d max %d, min %d, avg %1.2f\n",instance_name[instance_id], // opti_array[instance_id],max_value,min_value,total_value/run_num); // //printf("%s: max %d, min %d, avg %1.2f\n",instance_name[instance_id],max_value, // // min_value,total_value/run_num); //} // //fclose(file_result); //getchar(); // bat test //int run_num = 20; // float min_time = 100000; // float max_time = 0; // // //FILE *experiment_fout = fopen("experiment.txt", "w"); // FILE *experiment_fout = fopen("test_dec_neigh_sp03_nurseShakingdecomp.txt", "w"); // // for( int sprint_id = 3 ; sprint_id < 4 ; sprint_id++){ // // time_found = 0; // // Load(instance_name[sprint_id]); // // for(int i = 0; i < run_num; i++){ // int t = crosearch(opti_array[sprint_id]); // if( t < min_time) min_time = t; // if( t > max_time) max_time = t; // time_found += t; // } // //printf("mean is %f", time_found/time_test); // fprintf(experiment_fout,"inst id is %s, run num is %d, mean time is %3.1f, min is %3.1f, max is %3.1f\n", // instance_name[sprint_id],run_num,time_found/run_num, min_time, max_time); // } // fclose(experiment_fout); }
zzr-cro-nurse
trunk/crosearch.cpp
C++
gpl3
20,798
//#ifndef HEADER_H //#define HEADER_H // ==================== instance loading =================== #define NURSE_NUM 50 // the max number of nurses.max is 50,in long instances. #define DAY_NUM 28 // period #define TYPES 5 // shift types, required to increase to 5 later once the head nurse comes in // different start time of the instances // For some instances have other start time extern int startTimeOffset; extern int nurseTotal; // nurse skill level extern int nurseSkill[NURSE_NUM]; // day off request [nurse number][28days] hold the weight extern int nurseDayoff[NURSE_NUM][DAY_NUM]; //shift off request [nurse num][28 days][shift type;weight] //extern int nurseShiftoff[NURSE_NUM][DAY_NUM][2]; extern char nurseShiftoff[NURSE_NUM][DAY_NUM][10]; // weight is always 1 extern int nurseShiftoffNum[NURSE_NUM][DAY_NUM]; // one nurse can has multiple request // because every nurse has her contract, // we use this array to map from nurses to contract // nurse number is NURSE_NUM = 30 extern int nursesContraMap[NURSE_NUM]; // hold instance information struct InstanceAttributeStruct{ char instanceName[30]; char instanceStartTime[30]; int skillNum; int shiftTypeNum; int contractNum; int patternNum; int nurseNum; int weekCoverNum; int dayOffReqNum; int shiftOffReqNum; // dayOn, shiftOn, dateSpecific cover // the above three are all zero in // each instance }; extern InstanceAttributeStruct instAttri; // constraints need to be loaded from the instance //this is the hard cover, since the 4 weeks are the same // cover_h[i][j] hold the number of j type needed in weed day i extern int cover_h[7][5]; // hold contract #define contra struct contract extern contra{ // hard constraints, usually leave it alone int hardOn1,hardOn2; int maxWorkDayOn,maxWorkDayW,maxWorkDay; int minWorkDayOn,minWorkDayW,minWorkDay; int maxConWorkDayOn,maxConWorkDayW,maxConWorkDay; int minConWorkDayOn,minConWorkDayW,minConWorkDay; int maxConFreeOn,maxConFreeW,maxConFree; int minConFreeOn,minConFreeW,minConFree; int maxConWorkWeekendOn,maxConWorkWeekendW,maxConWorkWeekend; int minConWorkWeekendOn,minConWorkWeekendW,minConWorkWeekend; int maxWorkingWeekendOn,maxWorkingWeekendW,maxWorkingWeekend; int wkdDayNum; int completeWeekendW,completeWeekendOn; int idenShiftInWeekendW,idenShiftInWeekendOn; int noNSBfFWeekendW,noNSBfFWeekendOn; //////////////////////////////// // because every skill has a job attribute. for example, L -> nurse, DH->Headnurse // thus, if the alter is on, every nurse should work only their job type // this cons appears in the long instances /////////////////////////////////// int alternativeW,alternativeOn; // not considered now int unWantPatTotal; int unWantPat[20]; // each contract has a list of unwanted pattern ID }; // contract array // number of contract is 5 // since the in the sprint track, max num of contract is 4. I use 5 extern contra contractArray[5]; // hold unwanted patterns typedef struct uPattern{ int patIdx; // no use int patWeight; int shiftTotal; char patSeq[10]; }uPattern; #define UPATTERNNUMMAX 20 // hold the unwanted pattern ID extern uPattern unPatArray[UPATTERNNUMMAX]; // check the evaluation method extern struct penaltyRec pRec; extern struct penaltyRec nursePenRec[NURSE_NUM]; struct penaltyRec { int workingday; int consecWorkingday; int consecFree; int consecWorkingWkd; int maxwkd; int threeWkd; int dayoff; int shiftoff; int pattern; int total; int idx; }; // record the sorted nurse with penalty extern struct structSortedNurseWithPen sortedNurseWithPen[NURSE_NUM]; struct structSortedNurseWithPen { int totalpen; int idx; }; extern int penArray[NURSE_NUM][DAY_NUM]; // ==================== solution ================== #define popSizeMax 50 // hold the optimal extern char optiSolution[NURSE_NUM][DAY_NUM]; // ====================== cro search ================== // CRO global parameters extern int currentPopSize; extern double KElossRate; extern double MoleColl; extern int initialKE; extern int al; extern double be; extern int buffer; extern int optiValueGlo; // for global random number extern int randomTool; struct Molecule{ char mole[NURSE_NUM][DAY_NUM]; int PE; int KE; int NumHit; int MinPe; int MinHit; char MinStruct[NURSE_NUM][DAY_NUM]; int tabulist[NURSE_NUM][DAY_NUM]; }; // ====================== functions ================== void solutionCreate(char s[NURSE_NUM][DAY_NUM]); void solutionRosterShowScreen(char s[][DAY_NUM]); // to screen void solutionShowTofile( char s[][DAY_NUM]); // 2d view to file void solutionStandardOutputFile( char s[][DAY_NUM]); // standard view to file int evaluate(char s[NURSE_NUM][DAY_NUM]); void Load(char ins_name[]); void initial(); //float crosearch(int opt_value); int crosearch(); void experiment(); void onlyNeiSearch(); void tabuTest(); void onlyOnwallSearch(); void watchingCro(); void localSearch(char currentSol[NURSE_NUM][DAY_NUM]); // ========================= solution ========================= void solutionStandardRead( char s[NURSE_NUM][DAY_NUM], char ins_name[] ); // ========================= operator ========================= void singleShiftSwap(char sol[NURSE_NUM][DAY_NUM]); void twoNurseMultiDaySwap(char sol[NURSE_NUM][DAY_NUM]); void singleWorkingDaySwap(char sol[NURSE_NUM][DAY_NUM]); void nurseSlotSwap2(char sol[NURSE_NUM][DAY_NUM]); void cycle3nurse(char sol[NURSE_NUM][DAY_NUM]); void copyDecomp(char a[NURSE_NUM][DAY_NUM], char b[NURSE_NUM][DAY_NUM], char s[NURSE_NUM][DAY_NUM]); void initShake(char a[NURSE_NUM][DAY_NUM],char s[NURSE_NUM][DAY_NUM]); void randNurIdx(); int randIntInterval(int start, int end); void showPop(struct Molecule pop[popSizeMax]); void randArray(int len); void randomDayGen(int holdArray[], int len); void randomNurseGen(int holdArray[], int len); void solCopy(char a[NURSE_NUM][DAY_NUM],char b[NURSE_NUM][DAY_NUM]); void blockSwap(char sol[NURSE_NUM][DAY_NUM]); void cycleMove(char sol[NURSE_NUM][DAY_NUM]); void findNeigh(char sol[NURSE_NUM][DAY_NUM]); void findNeigh_test1(char sol[NURSE_NUM][DAY_NUM]); void findNeigh_intelligent( char sol[NURSE_NUM][DAY_NUM] ); void findNeigh_mid(char sol[NURSE_NUM][DAY_NUM]); void multiNurseSingleDaySwap(char sol[NURSE_NUM][DAY_NUM]); void singleWorkingDayMove(char sol[NURSE_NUM][DAY_NUM]); void nurseSlotSwap(char sol[NURSE_NUM][DAY_NUM]); void nurseSlotSwap_mid(char sol[NURSE_NUM][DAY_NUM], int widthStart, int widthEnd, int interval1,int interval2); void nurseSlotSwap2(char sol[NURSE_NUM][DAY_NUM]); void shakingSingleNurse(char sol[NURSE_NUM][DAY_NUM], int nIdx); void twoNurseShaking(char sol[NURSE_NUM][DAY_NUM]); void twoNurseMultiDaySwap(char sol[NURSE_NUM][DAY_NUM], int dayNum); void singleNurseMultiDayMove(char sol[NURSE_NUM][DAY_NUM]); void nurseSlotSwap_blk(char sol[NURSE_NUM][DAY_NUM]); void swap2shifts( char* a, char* b); void nurseWkdSwap(char sol[NURSE_NUM][DAY_NUM]); void diffNurseSwap(char sol[NURSE_NUM][DAY_NUM]); void diffNurseSlotSwap(char sol[NURSE_NUM][DAY_NUM]); int cmp( const void *b ,const void *a); //int hDistance(char a[NURSE_NUM][DAY_NUM],char b[NURSE_NUM][DAY_NUM]); int distanceShift(char a[NURSE_NUM][DAY_NUM],char b[NURSE_NUM][DAY_NUM]); int distanceWorkingDay(char a[NURSE_NUM][DAY_NUM],char b[NURSE_NUM][DAY_NUM]); struct historyArrayStruct{ char sol[NURSE_NUM][DAY_NUM]; }; void initMole(struct Molecule *a); void resetEnergy(struct Molecule *a); void computInfo(struct Molecule *a); int findMinIdx(struct Molecule pop[popSizeMax]); int findMinEp(struct Molecule pop[popSizeMax]); void showPenaltySpec(); extern int typeIdx; extern int lastSwapDay; extern int lastSwapNurse1; extern int lastSwapNurse2; extern int a1; extern int a2; extern int a3; void solutionSwap(char sol[NURSE_NUM][DAY_NUM], int nurseIdx, int day1, int day2);
zzr-cro-nurse
trunk/functions.h
C
gpl3
8,294
package com.zzyijia.framework.oms.bo; public class OmsDepartment { }
zzyijia
zzyijia/src/com/zzyijia/framework/oms/bo/OmsDepartment.java
Java
asf20
76
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="web/common/bootstrap/css/bootstrap.min.css" rel="stylesheet" media="screen"> <style type="text/css"> body { padding-top: 40px; padding-bottom: 40px; background-color: #f5f5f5; } .form-signin { max-width: 300px; padding: 19px 29px 29px; margin: 0 auto 20px; background-color: #fff; border: 1px solid #e5e5e5; -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px; -webkit-box-shadow: 0 1px 2px rgba(0,0,0,.05); -moz-box-shadow: 0 1px 2px rgba(0,0,0,.05); box-shadow: 0 1px 2px rgba(0,0,0,.05); } .form-signin .form-signin-heading, .form-signin .checkbox { margin-bottom: 10px; } .form-signin input[type="text"], .form-signin input[type="password"] { font-size: 16px; height: auto; margin-bottom: 15px; padding: 7px 9px; } </style> <title>Insert title here</title> </head> <body> <div class="container"> <form class="form-signin"> <h2 class="form-signin-heading">Please sign in</h2> <input type="text" class="input-block-level" placeholder="Email address"> <input type="password" class="input-block-level" placeholder="Password"> <label class="checkbox"> <input type="checkbox" value="remember-me"> Remember me </label> <button class="btn btn-large btn-primary" type="submit">Sign in</button> </form> </div> <script src="web/common/js/jquery.min.js"></script> <script src="web/common/bootstrap/js/bootstrap.min.js"></script> </body> </html>
zz-spring-mvc
trunk/zztest/WebContent/index.jsp
Java Server Pages
bsd
2,095
package com.zz.dbutil; import java.util.Map; public class ZZResultList { Map resultList; int pageNo; int pageNum; ZZResultList(int no,int num){ pageNo = no; pageNum = num; } }
zz-spring-mvc
trunk/zztest/WebContent/WEB-INF/src/com/zz/dbutil/ZZResultList.java
Java
bsd
213
package com.zz.database; import org.springframework.jdbc.core.JdbcTemplate; public class ZZDAO{ private JdbcTemplate jdbcTemplate; static String COLUMNNAMES = ""; static String QUERY_ALL = " SELECT * FROM " ; public Integer CommonQuery(String tablename,String condition,String order){ String sql = QUERY_ALL + tablename + condition + order; return 1; } public Integer CommonQuery(String COLUMNNAMES,String QUERY_ALL){ return 1; } }
zz-spring-mvc
trunk/zztest/WebContent/WEB-INF/src/com/zz/database/ZZDAO.java
Java
bsd
487
package com.zz.action; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; @Controller @RequestMapping("/demo") public class DemoAction { @RequestMapping("/login") public void login(){ System.out.println("add"); } }
zz-spring-mvc
trunk/zztest/WebContent/WEB-INF/src/com/zz/action/DemoAction.java
Java
bsd
313
package com.osmino.contacts.model.contacts; import java.util.List; import android.content.Context; public class ContactProviderProxy implements IContactProvider{ IContactProvider provider; Context context; public ContactProviderProxy(Context context, IContactProvider provider){ this.context = context; this.provider = provider; } @Override public void add(List<IContact> contacts) { provider.add(contacts); } @Override public void modify(List<IContact> contacts) { provider.modify(contacts); } @Override public void merge(List<IContact> contacts) { provider.merge(contacts); } @Override public void delete(List<IContact> contacts) { provider.delete(contacts); } @Override public List<IContact> select() { return provider.select(); } }
zzz-zzz-zzz
trunk/src/com/osmino/contacts/model/contacts/ContactProviderProxy.java
Java
gpl3
806
package com.osmino.contacts.model.contacts; import java.io.InputStream; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import android.content.ContentResolver; import android.content.ContentUris; import android.content.Context; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.BitmapDrawable; import android.net.Uri; import android.provider.ContactsContract; import android.provider.ContactsContract.CommonDataKinds; import android.provider.ContactsContract.CommonDataKinds.Phone; import android.provider.ContactsContract.CommonDataKinds.StructuredName; import android.provider.ContactsContract.Contacts; import android.provider.ContactsContract.Data; import android.provider.ContactsContract.RawContacts; import android.text.TextUtils; public class ContactProviderAndroid implements IContactProvider{ private final boolean DBG = true; Context context; public ContactProviderAndroid(Context context){ this.context = context; } @Override public void add(List<IContact> contacts) { // TODO Auto-generated method stub } @Override public void modify(List<IContact> contacts) { // TODO Auto-generated method stub } @Override public void merge(List<IContact> contacts) { // TODO Auto-generated method stub } @Override public void delete(List<IContact> contacts) { // TODO Auto-generated method stub } @Override public List<IContact> select() { //raw_contact table List<IContactBuilder> blist = new ArrayList<IContactBuilder>(); List<IContact> clist = new ArrayList<IContact>(); String[] projection = new String[]{RawContacts.CONTACT_ID, RawContacts._ID, RawContacts.ACCOUNT_NAME, RawContacts.ACCOUNT_TYPE}; Cursor c = context.getContentResolver().query(RawContacts.CONTENT_URI, projection, RawContacts._ID + ">0", null, null ); if(c.moveToFirst()){ do{ IContactBuilder cb = new ContactBuilderAndroid(); int id = c.getInt(c.getColumnIndexOrThrow(RawContacts.CONTACT_ID)); int rawid = c.getInt(c.getColumnIndexOrThrow(RawContacts._ID)); String aname = c.getString(c.getColumnIndexOrThrow(RawContacts.ACCOUNT_NAME)); String atype = c.getString(c.getColumnIndexOrThrow(RawContacts.ACCOUNT_TYPE)); cb.set(IContact.ID_I, id > 0 ? id : IContact.UNDEF_I); cb.set(IContact.ID_RAW_I, rawid); cb.set(IContact.ACCOUNT_NAME_S, TextUtils.isEmpty(aname) ? IContact.UNDEF_S : aname); cb.set(IContact.ACCOUNT_TYPE_S, TextUtils.isEmpty(atype) ? IContact.UNDEF_S : atype); clist.add(cb.create()); } while(c.moveToNext()); } c.close(); //is phone, is photo projection = new String[]{Contacts._ID, Contacts.HAS_PHONE_NUMBER, Contacts.PHOTO_ID}; c = context.getContentResolver().query( Contacts.CONTENT_URI, projection, Contacts._ID + ">0", null, null ); int size = clist.size(); if(c.moveToFirst()){ do{ int cursorId = c.getInt(c.getColumnIndexOrThrow(Contacts._ID)); boolean hasPhone = c.getInt(c.getColumnIndexOrThrow(Contacts.HAS_PHONE_NUMBER))>0 ? true : false; boolean hasPhoto = c.getInt(c.getColumnIndexOrThrow(Contacts.PHOTO_ID))> 0 ? true : false ; boolean found = false; for(int i=0;i<size;i++){ if(clist.get(i).containsKey(IContact.ID_I)){ int listId = clist.get(i).getData(IContact.ID_I); found = (cursorId == listId); } if(found){ clist.get(i).setData(IContact.HAS_PHONE_B, hasPhone); clist.get(i).setData(IContact.HAS_PHOTO_B, hasPhoto); if(hasPhone){ clist.get(i).setData(IContact.PHONES_H_IS, new HashMap()); } if(hasPhoto){ clist.get(i).setData(IContact.PHOTO_ID_I, c.getInt(c.getColumnIndexOrThrow(Contacts.PHOTO_ID))); } break; } } } while(c.moveToNext()); } c.close(); //phones && names projection = new String[]{ Data._ID, Data.RAW_CONTACT_ID, Data.MIMETYPE, Data.IS_PRIMARY, Data.IS_SUPER_PRIMARY, Data. DATA1, Data. DATA2, Data. DATA3, Data. DATA4, Data. DATA5, Data. DATA6, Data. DATA7, Data. DATA8, Data. DATA9, Data. DATA10, Data. DATA11, Data. DATA12, Data. DATA13, Data. DATA14, Data. DATA15, }; c = context.getContentResolver().query( Data.CONTENT_URI, projection, String.format( "%s = \"%s\" OR %s = \"%s\"", Data.MIMETYPE, Phone.CONTENT_ITEM_TYPE, Data.MIMETYPE, StructuredName.CONTENT_ITEM_TYPE ), null, null ); if(c.moveToFirst()){ do{ int dataRawId = c.getInt(c.getColumnIndexOrThrow(Data.RAW_CONTACT_ID)); String mimetype = c.getString(c.getColumnIndexOrThrow(Data.MIMETYPE)); boolean found = false; for(int i=0;i<size;i++){ if(clist.get(i).containsKey(IContact.ID_RAW_I)){ int listRawId = clist.get(i).getData(IContact.ID_RAW_I); found = (dataRawId == listRawId); } if(!found){ continue; } if( mimetype.equals(CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE )){ if(DBG) System.out.println("mimetype == CommonDataKinds.StructuredName.CONTENT_ITEM_TYP"); String displayName = c.getString(c.getColumnIndexOrThrow(CommonDataKinds.StructuredName.DISPLAY_NAME)); String givenName = c.getString(c.getColumnIndexOrThrow(CommonDataKinds.StructuredName.GIVEN_NAME)); String familyName = c.getString(c.getColumnIndexOrThrow(CommonDataKinds.StructuredName.FAMILY_NAME)); if(!TextUtils.isEmpty(displayName)){ clist.get(i).setData(IContact.DISPLAY_NAME_S, displayName); } if(!TextUtils.isEmpty(givenName)){ clist.get(i).setData(IContact.FIRST_NAME_S, givenName); } if(!TextUtils.isEmpty(familyName)){ clist.get(i).setData(IContact.LAST_NAME_S, familyName); } } else if(mimetype.equals(CommonDataKinds.Phone.CONTENT_ITEM_TYPE)){ if(DBG) System.out.println("mimetype == CommonDataKinds.Phone.CONTENT_ITEM_TYPE"); int ptype = c.getInt(c.getColumnIndexOrThrow(CommonDataKinds.Phone.TYPE)); String pnumber = c.getString(c.getColumnIndexOrThrow(CommonDataKinds.Phone.NUMBER)); boolean isPrimary = c.getInt(c.getColumnIndexOrThrow(CommonDataKinds.Phone.IS_PRIMARY)) > 0 ? true : false ; boolean isSuperPrimary = c.getInt(c.getColumnIndexOrThrow(CommonDataKinds.Phone.IS_SUPER_PRIMARY)) > 0 ? true : false ; if(isSuperPrimary || isPrimary){ clist.get(i).setData(IContact.PHONE_PRI_I, ptype); } clist.get(i).getData(IContact.PHONES_H_IS, HashMap.class).put(ptype, pnumber); } else{ if(DBG) System.out.println("mimetype == "+mimetype); } } } while(c.moveToNext()); } c.close(); //photos for(int i=0;i<size;i++){ boolean hasPhoto = clist.get(i).containsKey(IContact.HAS_PHOTO_B) && clist.get(i).getData(IContact.HAS_PHOTO_B, Boolean.class); if(hasPhoto){ int photoId = clist.get(i).getData(IContact.PHOTO_ID_I, Integer.class); int contactId = clist.get(i).getData(IContact.ID_I, Integer.class); BitmapDrawable bd = getPhoto(context, contactId, 30, 30, Bitmap.Config.RGB_565); clist.get(i).setData(IContact.PHOTO_BD, bd); } } return clist; } private static BitmapDrawable getPhoto(Context context, int contactId, int w, int h, Bitmap.Config config){ Uri photoUri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, contactId); Bitmap photoBitmap; ContentResolver cr = context.getContentResolver(); InputStream is = ContactsContract.Contacts.openContactPhotoInputStream(cr, photoUri); BitmapFactory.Options options = new BitmapFactory.Options(); options.inPreferredConfig = config; photoBitmap = BitmapFactory.decodeStream(is, null, options); if(photoBitmap==null) return null; Bitmap scaled = Bitmap.createScaledBitmap(photoBitmap, w, h, true); photoBitmap.recycle(); BitmapDrawable bd = new BitmapDrawable(scaled); return bd; } }
zzz-zzz-zzz
trunk/src/com/osmino/contacts/model/contacts/ContactProviderAndroid.java
Java
gpl3
8,362
package com.osmino.contacts.model.contacts; import java.util.List; public interface IContactProvider{ public void add(List<IContact> contacts);// public void modify(List<IContact> contacts);// public void merge (List<IContact> contacts); public void delete (List<IContact> contacts);// public List<IContact> select();// }
zzz-zzz-zzz
trunk/src/com/osmino/contacts/model/contacts/IContactProvider.java
Java
gpl3
338
package com.osmino.contacts.model.contacts; public interface IContactBuilder{ public IContact create(); public IContactBuilder set(String which, Object data); }
zzz-zzz-zzz
trunk/src/com/osmino/contacts/model/contacts/IContactBuilder.java
Java
gpl3
171
package com.osmino.contacts.model.contacts; import java.util.ArrayList; import java.util.List; public class ContactProviderFake implements IContactProvider{ private final boolean DBG = true; List<IContact> list = new ArrayList<IContact>(); public ContactProviderFake(){ init(); } private void init() { for(int i = 0;i<100;i++){ IContactBuilder builder = new ContactBuilderAndroid(); builder.set(IContact.ID_I, i); builder.set(IContact.DISPLAY_NAME_S, "Contact #"+i); list.add(builder.create()); } } @Override public void add(List<IContact> contacts) { list.addAll(contacts); } @Override public void modify(List<IContact> contacts) { throw new UnsupportedOperationException("modify doesn't work"); } @Override public void merge(List<IContact> contacts) { throw new UnsupportedOperationException("merge doesn't work"); } @Override public void delete(List<IContact> contacts) { ArrayList<Integer> ids = new ArrayList<Integer>(); for(IContact c:contacts){ int id = c.getData(IContact.ID_I); ids.add(id); } int size = list.size(); for(int i = size-1;i>=0;i--){ int id = list.get(i).getData(IContact.ID_I); if(ids.contains(id)){ list.remove(i); } } } @Override public List<IContact> select() { return list; } }
zzz-zzz-zzz
trunk/src/com/osmino/contacts/model/contacts/ContactProviderFake.java
Java
gpl3
1,356
package com.osmino.contacts.model.contacts; public final class ContactBuilderAndroid implements IContactBuilder { private final boolean DBG = true; IContact contact; public ContactBuilderAndroid() { contact = new ContactAndroid(); } public ContactBuilderAndroid(IContact contact){ if(contact==null) throw new NullPointerException("ContactBuilderAndroid: constructor arg == null"); this.contact = contact; } @Override public IContact create() { if (DBG) System.out.println( contact.toString() ); return contact; } @Override public ContactBuilderAndroid set(String which, Object data) { contact.setData(which, data); return this; } }
zzz-zzz-zzz
trunk/src/com/osmino/contacts/model/contacts/ContactBuilderAndroid.java
Java
gpl3
698
package com.osmino.contacts.model.contacts; import java.util.HashMap; import java.util.Map; import java.util.Set; public class ContactAndroid implements IContact{ private HashMap<String, Object> values; // public static int EQUALS_METHOD = 0; // public static final int EQUALS_BY_OBJ = 0; // public static final int EQUALS_BY_ID = 1; // public static final int EQUALS_BY_RAW_ID = 2; public ContactAndroid(){ values = new HashMap<String, Object>(); } @Override public IContactBuilder getBuilder() { if(isEmpty()){ return new ContactBuilderAndroid(); } else{ return new ContactBuilderAndroid(this); } } @SuppressWarnings("unchecked") @Override public <T> T getData(String which) { return (T)values.get(which); } public <T> T getData(String which, Class<T> type) { return type.cast( values.get(which) ); } public Set<String> getKeys(){ return values.keySet(); } public boolean containsKey(String key){ return values.containsKey(key); } public int size(){ return values.size(); } public boolean isEmpty(){ return values.isEmpty(); } @Override public void setData(String which, Object object) { values.put(which, object); } @Override public String toString(){ StringBuilder sb = new StringBuilder(); sb.append("<Contact>\n"); for(Map.Entry<String, Object> entry : values.entrySet()){ sb.append(" "); sb.append( entry.getKey() ); sb.append( "=>" ); sb.append( entry.getValue().toString() ); sb.append( "\n" ); } sb.append("</Contact>\n"); return sb.toString(); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((values == null) ? 0 : values.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; ContactAndroid other = (ContactAndroid) obj; if (values == null) { if (other.values != null) return false; } else if (!values.equals(other.values)) return false; return true; } }
zzz-zzz-zzz
trunk/src/com/osmino/contacts/model/contacts/ContactAndroid.java
Java
gpl3
2,210
package com.osmino.contacts.model.contacts; import java.util.Set; public interface IContact{ public static final int UNDEF_I = -1; public static final String UNDEF_S = "_undef"; public static final String ID_I = "id"; public static final String ID_RAW_I = "rawid"; public static final String DISPLAY_NAME_S = "displayname"; public static final String FIRST_NAME_S = "firstname"; public static final String LAST_NAME_S = "lastname"; public static final String PHONES_H_IS = "phones"; public static final String PHONE_PRI_I = "primaryphone"; public static final String HAS_PHONE_B = "hasphone"; public static final String HAS_PHOTO_B = "hasphoto"; public static final String PHOTO_ID_I = "photoid"; public static final String ACCOUNT_NAME_S = "accountname"; public static final String ACCOUNT_TYPE_S = "accounttype"; public static final String PHOTO_BD = "photo";//BitmapDrawable public void setData(String which, Object object); public <T> T getData(String which); public <T> T getData(String which, Class<T> type); public IContactBuilder getBuilder(); public Set<String> getKeys(); public boolean containsKey(String key); public int size(); public boolean isEmpty(); } /** ContactProviderProxy manager = new ContactProviderProxy(this, new ContactProviderFake()); List<Contact> list = manager.select(); Log.e("CONTACT", "SELECT==================================================================="); for (Contact c : list) { int id = c.getData(ContactAndroid.ID); String name = c.getData(ContactAndroid.NAME); Log.e("CONTACT", String.format("Contact: id-%d, name-%s", id, name)); } Log.e("CONTACT", "ADD==================================================================="); List<Contact> addList = new ArrayList<Contact>(); for (int i = 0; i < 5; i++) { addList.add(new ContactBuilderAndroid().set(ContactAndroid.ID, 200 + i) .set(ContactAndroid.NAME, "Added Contact #" + i).create()); } manager.add(addList); list = manager.select(); Log.e("CONTACT", "SELECT==================================================================="); for (Contact c : list) { int id = c.getData(ContactAndroid.ID); String name = c.getData(ContactAndroid.NAME); Log.e("CONTACT", String.format("Contact: id-%d, name-%s", id, name)); } Log.e("CONTACT", "DELETE==================================================================="); List<Contact> deleteList = addList; manager.delete(deleteList); Log.e("CONTACT", "SELECT==================================================================="); list = manager.select(); for (Contact c : list) { int id = c.getData(ContactAndroid.ID); String name = c.getData(ContactAndroid.NAME); Log.e("CONTACT", String.format("Contact: id-%d, name-%s", id, name)); } **/
zzz-zzz-zzz
trunk/src/com/osmino/contacts/model/contacts/IContact.java
Java
gpl3
2,827
package com.osmino.contacts.model.contacts.utils; import android.text.TextUtils; import com.osmino.contacts.model.contacts.IContact; public final class ContactUtils{ public static String getStructuredName(IContact contact){ String name = contact.getData(IContact.DISPLAY_NAME_S); return TextUtils.isEmpty(name) ? "NO NAME" : name ; } }
zzz-zzz-zzz
trunk/src/com/osmino/contacts/model/contacts/utils/ContactUtils.java
Java
gpl3
356
package com.osmino.contacts.view.list; import java.util.ArrayList; import java.util.List; import com.osmino.contacts.model.contacts.IContact; import android.app.Activity; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; public final class ContactListAdapter extends BaseAdapter { private final Activity mActivity; private List<IContact> mListContact; public ContactListAdapter(Activity activity) { mActivity = activity; mListContact = new ArrayList<IContact>(); } @Override public int getCount() { return mListContact.size(); } @Override public Object getItem(int position) { return mListContact.get(position); } @Override public long getItemId(int position) { return position; } @Override public View getView(int position, View convertView, ViewGroup parentView) { ContactItem item = null; if (convertView == null) { item = new ContactItem(mActivity, mListContact.get(position), position); } else { item = (ContactItem) convertView; item.clearInfo(); item.setInfo(mListContact.get(position)); } return item; } public void refreshList(List<IContact> listContactInfo) { mListContact.clear(); mListContact.addAll(listContactInfo); notifyDataSetChanged(); } }
zzz-zzz-zzz
trunk/src/com/osmino/contacts/view/list/ContactListAdapter.java
Java
gpl3
1,326
package com.osmino.contacts.view.list; import java.util.ArrayList; import java.util.List; import android.app.Activity; import android.view.View; import android.widget.AdapterView; import android.widget.ListView; import com.osmino.contacts.model.contacts.IContact; public class ContactListView extends ListView implements android.widget.AdapterView.OnItemClickListener{ List<IContact> contacList; ContactListAdapter adapter; public ContactListView(Activity activity, ListViewClient client) { super(activity); setDividerHeight(0); setVerticalFadingEdgeEnabled(true); contacList = new ArrayList<IContact>(); setOnItemClickListener(this); adapter = new ContactListAdapter(activity); setAdapter(adapter); } @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { contacList.get(position); }; public void fill(List<IContact> list) { contacList.clear(); contacList.addAll(list); adapter.refreshList(contacList); } public interface ListViewClient{ public void onContactClick(IContact contact); } }
zzz-zzz-zzz
trunk/src/com/osmino/contacts/view/list/ContactListView.java
Java
gpl3
1,121
package com.osmino.contacts.view.list; import android.app.Activity; import android.graphics.drawable.BitmapDrawable; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import com.osmino.contacts.R; import com.osmino.contacts.model.contacts.IContact; import com.osmino.contacts.model.contacts.utils.ContactUtils; import com.osmino.contacts.view.IStyleableView; import com.osmino.contacts.view.style.Style; public class ContactItem extends RelativeLayout implements IStyleableView{ private final int LAYOUT = R.layout.contact_item; private final int BG_ONE = R.drawable.base_list_bg_1; private final int BG_TWO = R.drawable.base_list_bg_2; public static final int ROOT_RL = R.id.contact_item_bg_rl; public static final int TEXT = R.id.contact_item_text_tv; public static final int PIC = R.id.contact_item_pic_iv; private static final int PIC_DEF = R.drawable.base_no_avatar_ic; private RelativeLayout root; public ContactItem(Activity activity, IContact contact, int position){ super(activity); root = (RelativeLayout) activity.getLayoutInflater().inflate(LAYOUT, this); // findViewById(ROOT_RL).setBackgroundResource(position%2==0 ? BG_TWO : BG_ONE); } public void clearInfo() { TextView tv = (TextView)root.findViewById(TEXT); ImageView iv = (ImageView) root.findViewById(PIC); tv.setText(""); iv.setImageResource(PIC_DEF); } public void setInfo(IContact iContact) { clearInfo(); TextView tv = (TextView)root.findViewById(TEXT); ImageView iv = (ImageView) root.findViewById(PIC); tv.setText(ContactUtils.getStructuredName(iContact)); if(iContact.getData(IContact.HAS_PHOTO_B, Boolean.class)){ BitmapDrawable bd = iContact.getData(IContact.PHOTO_BD, BitmapDrawable.class); if(bd!=null){ iv.setImageDrawable( bd ); } } } @Override public void setStyle(Style style) { } }
zzz-zzz-zzz
trunk/src/com/osmino/contacts/view/list/ContactItem.java
Java
gpl3
1,948
package com.osmino.contacts.view; import android.graphics.drawable.Drawable; import android.graphics.drawable.StateListDrawable; public class StateDrawable extends StateListDrawable { private final boolean DBG = true; private static final int PRESSED = android.R.attr.state_pressed; private static final int FOCUSED = android.R.attr.state_focused; private static final int IDLE = android.R.attr.state_enabled; public StateDrawable(Drawable[] layers) { addState(new int[]{PRESSED, FOCUSED}, layers[0]); addState(new int[]{IDLE}, layers[1]); setState(new int[]{IDLE}); } @Override protected boolean onStateChange(int[] states) { for (int state : states) { if (state == PRESSED || state == FOCUSED) { setState(new int[]{PRESSED, FOCUSED}); return true; } } setState(new int[]{IDLE}); return true; } @Override public boolean isStateful() { return true; } }
zzz-zzz-zzz
trunk/src/com/osmino/contacts/view/StateDrawable.java
Java
gpl3
1,038
package com.osmino.contacts.view.style.tools; import android.view.View; import android.widget.ImageButton; import android.widget.ImageView; import android.widget.TextView; import com.osmino.contacts.view.style.StyleAttribute; public class Tools{ private static final boolean DBG = true; public static void applyViewAttribute(View root, StyleAttribute attribute){ if(DBG){ System.out.println("id"+attribute.getViewId()); System.out.println("type"+attribute.getTypeOfView()); System.out.println("att"+attribute.getAttribute()); System.out.println("val"+attribute.getValue()); } if(!attribute.isValid()){ throw new IllegalStateException("!attribute.isValid()"); } int id = attribute.getViewId(); int type = attribute.getTypeOfView(); int att = attribute.getAttribute(); int val = attribute.getValue(); switch(att){ case StyleAttribute.ATT_IMAGE_BUTTON_BACKGROUND: ((ImageButton)root.findViewById(id)).setBackgroundResource(val); break; case StyleAttribute.ATT_IMAGE_BUTTON_FOREGROUND: ((ImageButton)root.findViewById(id)).setImageResource(val); break; case StyleAttribute.ATT_IMAGE_VIEW_BACKGROUND: ((ImageView)root.findViewById(id)).setBackgroundResource(val); break; case StyleAttribute.ATT_IMAGE_VIEW_FOREGROUND: ((ImageView)root.findViewById(id)).setImageResource(val); break; case StyleAttribute.ATT_TEXT_VIEW_BACKGROUND: ((TextView)root.findViewById(id)).setBackgroundResource(val); break; case StyleAttribute.ATT_TEXT_VIEW_TEXT_COLOR: ((TextView)root.findViewById(id)).setTextColor(val); break; case StyleAttribute.ATT_TEXT_VIEW_TEXT_SIZE: ((TextView)root.findViewById(id)).setTextSize(val); break; } } }
zzz-zzz-zzz
trunk/src/com/osmino/contacts/view/style/tools/Tools.java
Java
gpl3
1,760
package com.osmino.contacts.view.style; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; public class StyleAttribute { public static final int NONE = 0; public static final int VIEW_IMAGE_BUTTON = 1; public static final int VIEW_IMAGE_VIEW = 2; public static final int VIEW_TEXT_VIEW = 3; public static final int ATT_IMAGE_BUTTON_BACKGROUND = 101; public static final int ATT_IMAGE_BUTTON_FOREGROUND = 102; public static final int ATT_IMAGE_VIEW_BACKGROUND = 103; public static final int ATT_IMAGE_VIEW_FOREGROUND = 104; public static final int ATT_TEXT_VIEW_BACKGROUND = 105; public static final int ATT_TEXT_VIEW_TEXT_COLOR = 106; public static final int ATT_TEXT_VIEW_TEXT_SIZE = 107; private int mViewId = NONE; private int mTypeOfView = NONE; private int mAttribute = NONE; private int mValue = NONE; private static HashMap<Integer, HashSet<Integer>> map; static{ map = getViewMap(); } public static HashMap<Integer, HashSet<Integer>> getViewMap() { if(map!=null){ return map; } HashMap<Integer, HashSet<Integer>> map = new HashMap<Integer, HashSet<Integer>>(); map.put(VIEW_IMAGE_BUTTON, new HashSet<Integer>(Arrays.asList(ATT_IMAGE_BUTTON_BACKGROUND, ATT_IMAGE_BUTTON_FOREGROUND))); map.put(VIEW_IMAGE_VIEW, new HashSet<Integer>(Arrays.asList(ATT_IMAGE_VIEW_BACKGROUND, ATT_IMAGE_VIEW_FOREGROUND))); map.put(VIEW_TEXT_VIEW, new HashSet<Integer>(Arrays.asList(ATT_TEXT_VIEW_BACKGROUND, ATT_TEXT_VIEW_TEXT_COLOR, ATT_TEXT_VIEW_TEXT_SIZE))); return map; } public StyleAttribute() { } public StyleAttribute(int viewId, int typeOfView, int attribute, int value) { mViewId = viewId; mTypeOfView = typeOfView; mAttribute = attribute; mValue = value; } public void setAttribute(int viewId, int typeOfView, int attribute, int value) { mViewId = viewId; mTypeOfView = typeOfView; mAttribute = attribute; mValue = value; } /** * return true if everything in attribute is equal except value */ @Override public boolean equals(Object o) { if (!o.getClass().isInstance(this)) { return false; } StyleAttribute sa = (StyleAttribute) o; if (mViewId == sa.getViewId() && mTypeOfView == sa.getTypeOfView() && mAttribute == sa.getAttribute()) { return true; } else { return false; } } @Override public int hashCode() { throw new UnsupportedOperationException(); } public int getViewId() { return mViewId; } public void setViewId(int mViewId) { this.mViewId = mViewId; } public int getTypeOfView() { return mTypeOfView; } public void setTypeOfView(int mTypeOfView) { this.mTypeOfView = mTypeOfView; } public int getAttribute() { return mAttribute; } public void setAttribute(int mAttribute) { this.mAttribute = mAttribute; } public int getValue() { return mValue; } public void setValue(int mValue) { this.mValue = mValue; } public boolean isValid() { boolean result; if (mAttribute == NONE || mTypeOfView == NONE || mValue == NONE || mViewId == NONE) { result = false; } else { if(getViewMap().containsKey(mTypeOfView)){ if(getViewMap().get(mTypeOfView).contains(mAttribute)){ result = true; } else{ result = false; } } else{ result = false; } } return result; } }
zzz-zzz-zzz
trunk/src/com/osmino/contacts/view/style/StyleAttribute.java
Java
gpl3
3,442
package com.osmino.contacts.view.style; import java.util.List; public abstract class Style{ private List<StyleAttribute> list; public Style(){ list = init(); } protected abstract List<StyleAttribute> init(); public int getStyleAttribute(StyleAttribute attribute) { if(attribute==null){ return StyleAttribute.NONE; } if(attribute.getViewId() == StyleAttribute.NONE || attribute.getTypeOfView() == StyleAttribute.NONE || attribute.getAttribute() == StyleAttribute.NONE ){ return StyleAttribute.NONE; } for(StyleAttribute s:list){ if(s.equals(attribute)){ return s.getValue(); } } return StyleAttribute.NONE; } }
zzz-zzz-zzz
trunk/src/com/osmino/contacts/view/style/Style.java
Java
gpl3
703
package com.osmino.contacts.view.dialer; import android.app.Activity; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnLongClickListener; import android.widget.ImageButton; import android.widget.LinearLayout; import android.widget.TextView; import com.osmino.contacts.R; import com.osmino.contacts.view.IStyleableView; import com.osmino.contacts.view.style.Style; public class Dialer extends LinearLayout implements IStyleableView, OnClickListener, OnLongClickListener { public static final String NAME = "dialer"; private boolean DBG = true; private static final int LAYOUT = R.layout.dialer; private static final int ID_INPUT_BG = R.id.dialer_input_ll; private static final int ID_INPUT_FIELD = R.id.dialer_input_tv; private static final int[] sButtonsIds = { R.id.dialer_1_ib, R.id.dialer_2_ib, R.id.dialer_3_ib, R.id.dialer_4_ib, R.id.dialer_5_ib, R.id.dialer_6_ib, R.id.dialer_7_ib, R.id.dialer_8_ib, R.id.dialer_9_ib, R.id.dialer_0_ib, R.id.dialer_star_ib, R.id.dialer_n_ib, R.id.dialer_call_ib, R.id.dialer_bs_ib }; private final TextView mInput; private static final String mChars = " 1234567890#*+"; private DialerClient mClient; private LinearLayout root; private boolean isCross = false; public Dialer(Activity activity, DialerClient client, Style style) { super(activity); root = (LinearLayout) activity.getLayoutInflater().inflate(LAYOUT, this); for (int i = 0; i < sButtonsIds.length; i++) { ImageButton ib = (ImageButton) findViewById(sButtonsIds[i]); ib.setOnClickListener(this); ib.setOnLongClickListener(this); } setClient(client); mInput = (TextView) findViewById(ID_INPUT_FIELD); } @Override public void setStyle(Style style) { } @Override public void onClick(View view) { int id = view.getId(); if(isCross && id==R.id.dialer_0_ib){ isCross = false; return; } processClick(id); isCross = false; } @Override public boolean onLongClick(View view) { int id = view.getId(); switch (id) { case R.id.dialer_0_ib: mInput.setText(mInput.getText().toString() + mChars.charAt(13)); isCross = true; break; case R.id.dialer_bs_ib: mInput.setText(""); break; } return false; } // String url = "tel:3334444"; // Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse(url)); private void processClick(int id) { switch (id) { case R.id.dialer_1_ib: mInput.setText(mInput.getText().toString() + mChars.charAt(1)); break; case R.id.dialer_2_ib: mInput.setText(mInput.getText().toString() + mChars.charAt(2)); break; case R.id.dialer_3_ib: mInput.setText(mInput.getText().toString() + mChars.charAt(3)); break; case R.id.dialer_4_ib: mInput.setText(mInput.getText().toString() + mChars.charAt(4)); break; case R.id.dialer_5_ib: mInput.setText(mInput.getText().toString() + mChars.charAt(5)); break; case R.id.dialer_6_ib: mInput.setText(mInput.getText().toString() + mChars.charAt(6)); break; case R.id.dialer_7_ib: mInput.setText(mInput.getText().toString() + mChars.charAt(7)); break; case R.id.dialer_8_ib: mInput.setText(mInput.getText().toString() + mChars.charAt(8)); break; case R.id.dialer_9_ib: mInput.setText(mInput.getText().toString() + mChars.charAt(9)); break; case R.id.dialer_0_ib: mInput.setText(mInput.getText().toString() + mChars.charAt(10)); break; case R.id.dialer_star_ib: mInput.setText(mInput.getText().toString() + mChars.charAt(11)); break; case R.id.dialer_n_ib: mInput.setText(mInput.getText().toString() + mChars.charAt(12)); break; case R.id.dialer_call_ib: mClient.onCall(mInput.getText().toString()); break; case R.id.dialer_bs_ib: String text = mInput.getText().toString(); int len = text.length(); String trimEnd = text.length() > 0 ? text.substring(0, len - 1) : ""; mInput.setText(trimEnd); break; } } public interface DialerClient{ public void onCall(String phoneNumber); } public DialerClient getClient() { return mClient; } public void setClient(DialerClient mClient) { this.mClient = mClient; } }
zzz-zzz-zzz
trunk/src/com/osmino/contacts/view/dialer/Dialer.java
Java
gpl3
4,348
package com.osmino.contacts.view; import com.osmino.contacts.view.style.Style; public interface IStyleableView{ public void setStyle(Style style); }
zzz-zzz-zzz
trunk/src/com/osmino/contacts/view/IStyleableView.java
Java
gpl3
161
package com.osmino.contacts.view.base; import com.osmino.contacts.view.IStyleableView; import com.osmino.contacts.view.style.Style; import com.osmino.contacts.R; import android.app.Activity; import android.content.Context; import android.widget.RelativeLayout; public class Title extends RelativeLayout implements IStyleableView{ public static final int LAYOUT = R.layout.title; public static final int ROOT_RL = R.id.title_bg_rl; public static final int TEXT = R.id.title_title_tv; public static final int PIC1 = R.id.title_pic_right_1_iv; public static final int PIC2 = R.id.title_pic_right_2_iv; private RelativeLayout root; public Title(Activity activity) { super(activity); root = (RelativeLayout) activity.getLayoutInflater().inflate(LAYOUT, this); } @Override public void setStyle(Style style) { } }
zzz-zzz-zzz
trunk/src/com/osmino/contacts/view/base/Title.java
Java
gpl3
868
package com.osmino.contacts.view.base; import android.content.Context; import android.widget.LinearLayout; import com.osmino.contacts.view.IStyleableView; import com.osmino.contacts.view.style.Style; public class TabPanel extends LinearLayout implements IStyleableView{ public TabPanel(Context context) { super(context); setLayoutParams(new LinearLayout.LayoutParams(-1, -2)); setOrientation(LinearLayout.HORIZONTAL); } @Override public void setStyle(Style style) { } }
zzz-zzz-zzz
trunk/src/com/osmino/contacts/view/base/TabPanel.java
Java
gpl3
505
package com.osmino.contacts.view.base; import android.graphics.Color; import android.widget.LinearLayout; import android.widget.RelativeLayout; import com.osmino.contacts.LaunchActivity; import com.osmino.contacts.R; import com.osmino.contacts.model.contacts.ContactProviderAndroid; import com.osmino.contacts.model.contacts.IContactProvider; import com.osmino.contacts.view.IStyleableView; import com.osmino.contacts.view.dialer.Dialer; import com.osmino.contacts.view.list.ContactListView; import com.osmino.contacts.view.style.Style; public class BaseView extends RelativeLayout implements IStyleableView{ Dialer d; ContactListView clv; public BaseView(LaunchActivity activity) { super(activity); setLayoutParams(new RelativeLayout.LayoutParams(-1, -1)); setBackgroundColor(Color.WHITE); LinearLayout ll = new LinearLayout(activity); RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(-1, 40); lp.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM); ll.setOrientation(LinearLayout.HORIZONTAL); RelativeLayout.LayoutParams taplp = new RelativeLayout.LayoutParams(60, 40); Tab tab1 = new Tab(activity, activity); tab1.setId(1); tab1.setPic(R.drawable.base_tab_keypad_ic); tab1.setText("keypad"); tab1.setLayoutParams(taplp); Tab tab2 = new Tab(activity, activity); tab2.setId(2); tab2.setPic(R.drawable.base_tab_contacts_ic); tab2.setText("contact"); tab2.setLayoutParams(taplp); ll.addView(tab1); ll.addView(tab2); ll.setLayoutParams(lp); d = new Dialer(activity, activity, null); RelativeLayout.LayoutParams dlp = new RelativeLayout.LayoutParams(-1, -1); dlp.setMargins(0, 0, 0, 40); d.setLayoutParams(dlp); clv = new ContactListView(activity, activity); ContactProviderAndroid provider = new ContactProviderAndroid(activity); clv.fill(provider.select()); addView(clv); addView(d); addView(ll); } @Override public void setStyle(Style style) { } public void bringToFrontById(int id){ if(id == 1) d.setVisibility(VISIBLE); if(id == 2) d.setVisibility(GONE); } }
zzz-zzz-zzz
trunk/src/com/osmino/contacts/view/base/BaseView.java
Java
gpl3
2,184
package com.osmino.contacts.view.base; import com.osmino.contacts.view.IStyleableView; import com.osmino.contacts.view.style.Style; import android.content.Context; import android.widget.RelativeLayout; public class TabSeparator extends RelativeLayout implements IStyleableView{ public TabSeparator(Context context) { super(context); } @Override public void setStyle(Style style) { } }
zzz-zzz-zzz
trunk/src/com/osmino/contacts/view/base/TabSeparator.java
Java
gpl3
411
package com.osmino.contacts.view.base; import android.app.Activity; import android.view.View; import android.view.View.OnClickListener; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.TextView; import com.osmino.contacts.R; import com.osmino.contacts.view.IStyleableView; import com.osmino.contacts.view.style.Style; public class Tab extends RelativeLayout implements IStyleableView, OnClickListener{ public static final int LAYOUT = R.layout.tab; public static final int ROOT_RL = R.id.tab_bg_rl; public static final int IV = R.id.tab_iv; public static final int TEXT = R.id.tab_text_tv; private RelativeLayout root; private TabClient client; public Tab(Activity activity, TabClient client) { super(activity); root = (RelativeLayout) activity.getLayoutInflater().inflate(LAYOUT, this); this.client = client; setOnClickListener(this); } @Override public void setStyle(Style style) { } public void setText(String text){ TextView tv = (TextView) findViewById(TEXT); tv.setText(text); } public void setPic(int resource){ ImageView iv = (ImageView) findViewById(IV); iv.setImageResource(resource); } public interface TabClient{ public void onTabClick(View v); } @Override public void onClick(View v) { client.onTabClick(v); } }
zzz-zzz-zzz
trunk/src/com/osmino/contacts/view/base/Tab.java
Java
gpl3
1,380
package com.osmino.contacts.view.base; import com.osmino.contacts.view.IStyleableView; import com.osmino.contacts.view.style.Style; import android.content.Context; import android.widget.RelativeLayout; public class Window extends RelativeLayout implements IStyleableView{ public Window(Context context) { super(context); } @Override public void setStyle(Style style) { } }
zzz-zzz-zzz
trunk/src/com/osmino/contacts/view/base/Window.java
Java
gpl3
406
package com.osmino.contacts; import android.app.Activity; import android.os.Bundle; import android.view.View; import com.osmino.contacts.model.contacts.IContact; import com.osmino.contacts.view.base.BaseView; import com.osmino.contacts.view.base.Tab.TabClient; import com.osmino.contacts.view.dialer.Dialer.DialerClient; import com.osmino.contacts.view.list.ContactListView.ListViewClient; public class LaunchActivity extends Activity implements TabClient, DialerClient, ListViewClient { /** Called when the activity is first created. */ private BaseView bv; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Dialer d = new Dialer(this, new DialerClient() { // // @Override // public void onCall(String phoneNumber) { // // TODO Auto-generated method stub // // } // }, new Default()); bv = new BaseView(this); setContentView(bv); } @Override public void onTabClick(View v) { System.out.println(v.getId()); bv.bringToFrontById(v.getId()); } @Override public void onCall(String phoneNumber) { System.out.println(phoneNumber); } @Override public void onContactClick(IContact contact) { System.out.println(contact.toString()); } }
zzz-zzz-zzz
trunk/src/com/osmino/contacts/LaunchActivity.java
Java
gpl3
1,277
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Project.Common { public static class ProjectGlobal { } }
zznhgzf-t4-code-generator-clone
Project.Common/ProjectGlobal.cs
C#
asf20
161
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection.Emit; using System.Reflection; using System.Linq.Expressions; namespace Project.Common { public class ReflectionTools { /// <summary> /// 排序列,根据类名和字段名返回:例: x=>x.Name /// </summary> /// <typeparam name="T">类名</typeparam> /// <param name="propertyName">字段名</param> /// <returns>x=>x.Name</returns> public static Expression<Func<T, object>> GetClassPropertyExpression<T>(string propertyName) { if (string.IsNullOrEmpty(propertyName)) return null; ParameterExpression paramter = Expression.Parameter(typeof(T)); MemberExpression memberExpression = Expression.Property(paramter, propertyName); UnaryExpression unaryExpression = Expression.Convert(memberExpression, typeof(object)); Expression<Func<T, object>> tempExpression = Expression.Lambda<Func<T, object>>(unaryExpression, paramter); return tempExpression; } /// <summary> /// 根据表达式返回 属性名称 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="propertyExpression"></param> /// <returns></returns> public static string GetPropertyNameFromExpression<T>(Expression<Func<T, object>> propertyExpression) { MemberExpression memberExpr = null; if (propertyExpression.Body.NodeType == ExpressionType.Convert) memberExpr = ((UnaryExpression)propertyExpression.Body).Operand as MemberExpression; else if (propertyExpression.Body.NodeType == ExpressionType.MemberAccess) memberExpr = propertyExpression.Body as MemberExpression; return memberExpr.Member.Name; } /// <summary> /// 根据数据源返回其中两个字段的Dictionary /// </summary> /// <typeparam name="T"></typeparam> /// <param name="sources"></param> /// <param name="key"></param> /// <param name="value"></param> /// <returns></returns> public static Dictionary<string, object> ComposeDictionaryFromCollection<T>(IList<T> sources, Expression<Func<T, object>> key, Expression<Func<T, object>> value) { Dictionary<string, object> dictionary = new Dictionary<string, object>(); if (sources == null || sources.Count == 0) return dictionary; Type t = typeof(T); PropertyInfo keyProperty = t.GetProperty(GetPropertyNameFromExpression(key)); PropertyInfo valueProperty = t.GetProperty(GetPropertyNameFromExpression(value)); foreach (var item in sources) { object keyObj = keyProperty.GetValue(item, null); object valueObj = valueProperty.GetValue(item, null); if (keyObj == null) continue; if (dictionary.ContainsKey(keyObj.ToString())) continue; dictionary.Add(keyObj.ToString(), valueObj); } return dictionary; } /// <summary> /// 根据枚举返回text和Description /// key : text /// description : description /// </summary> /// <typeparam name="T">需要提取key,Discription的枚举</typeparam> /// <returns></returns> public static Dictionary<string, string> GetEnumDescriptionText<T>() { Dictionary<string, string> dictDescriptionText = new Dictionary<string, string>(); T[] values = (T[])System.Enum.GetValues(typeof(T)); for (int i = 0; i < values.Length; i++) { string description = AttachDataAttribute.GetAttachedData<T>(values[i].ToString(), EnumAttachDataKey.String) == null ? values[i].ToString() : AttachDataAttribute.GetAttachedData<T>(values[i].ToString(), EnumAttachDataKey.String); string text = AttachDataAttribute.GetAttachedData<T>(values[i].ToString(), EnumAttachDataKey.String) != null ? values[i].ToString() : Convert.ToString((int)(Object)values[i]); dictDescriptionText.Add(text, description); //string value = Convert.ToString((int)(Object)values[i]); } return dictDescriptionText; } /// <summary> /// 根据枚举返回text和Description dic keys 中必须存在key /// key : text /// description : description /// </summary> /// <typeparam name="T">需要提取key,Discription的枚举</typeparam> /// <param name="key">必须包含key</param> /// <returns></returns> public static Dictionary<string, string> GetEnumDescriptionText<T>(string key) { Dictionary<string, string> dictDescriptionText = new Dictionary<string, string>(); T[] values = (T[])System.Enum.GetValues(typeof(T)); for (int i = 0; i < values.Length; i++) { string description = AttachDataAttribute.GetAttachedData<T>(values[i].ToString(), EnumAttachDataKey.String); string text = values[i].ToString(); //必须包含key if (!text.Contains(key)) { continue; } dictDescriptionText.Add(text, description); //string value = Convert.ToString((int)(Object)values[i]); } return dictDescriptionText; } public static IList<T> BuildListHelper<T>() { List<T> list = new List<T>(); return list; } /// <summary> /// 返回一个列表,根据T 两个属性,决定text、value,找出text 中包含keyword 对应的value值,然后返回IList<U>列表 /// </summary> /// <typeparam name="T"></typeparam> /// <typeparam name="U"></typeparam> /// <param name="keyword"></param> /// <param name="sources"></param> /// <param name="text"></param> /// <param name="value"></param> /// <returns></returns> public static IList<U> ListValueByKeyword<T, U>(string keyword, IList<T> sources, Expression<Func<T, object>> text, Expression<Func<T, object>> value) { IList<U> result = new List<U>(); if (sources == null || sources.Count == 0) return result; Type t = typeof(T); PropertyInfo keyProperty = t.GetProperty(GetPropertyNameFromExpression(text)); PropertyInfo valueProperty = t.GetProperty(GetPropertyNameFromExpression(value)); foreach (var item in sources) { object textObj = keyProperty.GetValue(item, null); object valueObj = valueProperty.GetValue(item, null); if (textObj == null) continue; if (!textObj.ToString().Contains(keyword)) continue; if (result.Contains((U)valueObj)) continue; result.Add((U)valueObj); } return result; } } }
zznhgzf-t4-code-generator-clone
Project.Common/ReflectionTools.cs
C#
asf20
6,143
using System; using System.Collections.Generic; using System.Linq; using System.Text; using log4net.Config; using log4net; using System.IO; namespace Project.Common { public class Log4netHelper { private static ILog logger; public static void Configure() { log4net.Config.XmlConfigurator.Configure(); logger = LogManager.GetLogger("LJZ"); } public static ILog Logger { get { return logger; } } } }
zznhgzf-t4-code-generator-clone
Project.Common/Log4netHelper.cs
C#
asf20
439
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Project.Common { [AttributeUsage(AttributeTargets.Property)] public class PaginateNotComposeAttribute : System.Attribute { } }
zznhgzf-t4-code-generator-clone
Project.Common/Attributes.cs
C#
asf20
232
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Project.Common { /// <summary> /// 实现IEqualityComparer 接口 /// Func<int, int, bool> f = (x, y) => x == y; /// var comparer = new Comparer<int>(f); /// Console.WriteLine(comparer.Equals(1, 1)); /// Console.WriteLine(comparer.Equals(1, 2)); /// </summary> /// <typeparam name="T"></typeparam> public class EqualityComparerComparer<T> : IEqualityComparer<T> { private readonly Func<T, T, bool> _comparer; public EqualityComparerComparer(Func<T, T, bool> comparer) { if (comparer == null) throw new ArgumentNullException("comparer"); _comparer = comparer; } public bool Equals(T x, T y) { return _comparer(x, y); } public int GetHashCode(T obj) { return obj.ToString().ToLower().GetHashCode(); } } }
zznhgzf-t4-code-generator-clone
Project.Common/Comparer.cs
C#
asf20
854
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; namespace Project.Common { public static class StringUtility { public static string ConvertToString<T>(IEnumerable<T> source) { if (source == null || source.Count() <= 0) return ""; StringBuilder sb = new StringBuilder(); foreach (var item in source) { sb.Append(item).Append(','); } var result = sb.Remove(sb.Length - 1, 1).ToString(); return result; } public static string ArrayJoin(string[] array, string joinStr) { string str = ""; for (int i = 0; i < array.Count(); i++) { if (string.IsNullOrEmpty(array[i])) continue; str += array[i] + joinStr; } return str == "" ? "" : str.Substring(0, str.Length - joinStr.Length); } /// <summary> /// 根据ID获得文件保存路径以及文件名(不带扩展名) /// </summary> /// <param name="id"></param> /// <param name="fileName"></param> /// <returns></returns> public static string GetSavePath(int id, out string fileName) { string src = string.Format("{0:X8}", id); fileName = src.Substring(6, 2); return string.Format("/{0}/{1}/{2}/", src.Substring(0, 2), src.Substring(2, 2), src.Substring(4, 2)); } public static string CutString(string source, int length) { if (source == null || source.Length <= length) return source; return source.Substring(0, length) + "..."; } public static string ClearWhiteSpace(string source) { Regex r = new Regex(@"\s+"); return r.Replace(source, @" "); } public static string AddURLParameter(string url, string parameterName, string parameterValue) { if (url.IndexOf("?") == -1) url = url + "?"; else url = url + "&"; return url + parameterName + "=" + parameterValue; } public static string StripHTML(string source, int remainLength) { string temp = StripHTML(source); return temp.Length > remainLength ? temp.Substring(0, remainLength) : temp; } public static string StripHTML(string source) { try { string result; // Remove HTML Development formatting // Replace line breaks with space // because browsers inserts space result = source.Replace("\r", " "); // Replace line breaks with space // because browsers inserts space result = result.Replace("\n", " "); // Remove step-formatting result = result.Replace("\t", string.Empty); // Remove repeating spaces because browsers ignore them result = System.Text.RegularExpressions.Regex.Replace(result, @"( )+", " "); // Remove the header (prepare first by clearing attributes) result = System.Text.RegularExpressions.Regex.Replace(result, @"<( )*head([^>])*>", "<head>", System.Text.RegularExpressions.RegexOptions.IgnoreCase); result = System.Text.RegularExpressions.Regex.Replace(result, @"(<( )*(/)( )*head( )*>)", "</head>", System.Text.RegularExpressions.RegexOptions.IgnoreCase); result = System.Text.RegularExpressions.Regex.Replace(result, "(<head>).*(</head>)", string.Empty, System.Text.RegularExpressions.RegexOptions.IgnoreCase); // remove all scripts (prepare first by clearing attributes) result = System.Text.RegularExpressions.Regex.Replace(result, @"<( )*script([^>])*>", "<script>", System.Text.RegularExpressions.RegexOptions.IgnoreCase); result = System.Text.RegularExpressions.Regex.Replace(result, @"(<( )*(/)( )*script( )*>)", "</script>", System.Text.RegularExpressions.RegexOptions.IgnoreCase); //result = System.Text.RegularExpressions.Regex.Replace(result, // @"(<script>)([^(<script>\.</script>)])*(</script>)", // string.Empty, // System.Text.RegularExpressions.RegexOptions.IgnoreCase); result = System.Text.RegularExpressions.Regex.Replace(result, @"(<script>).*(</script>)", string.Empty, System.Text.RegularExpressions.RegexOptions.IgnoreCase); // remove all styles (prepare first by clearing attributes) result = System.Text.RegularExpressions.Regex.Replace(result, @"<( )*style([^>])*>", "<style>", System.Text.RegularExpressions.RegexOptions.IgnoreCase); result = System.Text.RegularExpressions.Regex.Replace(result, @"(<( )*(/)( )*style( )*>)", "</style>", System.Text.RegularExpressions.RegexOptions.IgnoreCase); result = System.Text.RegularExpressions.Regex.Replace(result, "(<style>).*(</style>)", string.Empty, System.Text.RegularExpressions.RegexOptions.IgnoreCase); // insert tabs in spaces of <td> tags result = System.Text.RegularExpressions.Regex.Replace(result, @"<( )*td([^>])*>", "\t", System.Text.RegularExpressions.RegexOptions.IgnoreCase); // insert line breaks in places of <BR> and <LI> tags result = System.Text.RegularExpressions.Regex.Replace(result, @"<( )*br( )*>", "\r", System.Text.RegularExpressions.RegexOptions.IgnoreCase); result = System.Text.RegularExpressions.Regex.Replace(result, @"<( )*li( )*>", "\r", System.Text.RegularExpressions.RegexOptions.IgnoreCase); // insert line paragraphs (double line breaks) in place // if <P>, <DIV> and <TR> tags result = System.Text.RegularExpressions.Regex.Replace(result, @"<( )*div([^>])*>", "\r\r", System.Text.RegularExpressions.RegexOptions.IgnoreCase); result = System.Text.RegularExpressions.Regex.Replace(result, @"<( )*tr([^>])*>", "\r\r", System.Text.RegularExpressions.RegexOptions.IgnoreCase); result = System.Text.RegularExpressions.Regex.Replace(result, @"<( )*p([^>])*>", "\r\r", System.Text.RegularExpressions.RegexOptions.IgnoreCase); // Remove remaining tags like <a>, links, images, // comments etc - anything that's enclosed inside < > result = System.Text.RegularExpressions.Regex.Replace(result, @"<[^>]*>", string.Empty, System.Text.RegularExpressions.RegexOptions.IgnoreCase); // replace special characters: result = System.Text.RegularExpressions.Regex.Replace(result, @" ", " ", System.Text.RegularExpressions.RegexOptions.IgnoreCase); result = System.Text.RegularExpressions.Regex.Replace(result, @"&bull;", " * ", System.Text.RegularExpressions.RegexOptions.IgnoreCase); result = System.Text.RegularExpressions.Regex.Replace(result, @"&lsaquo;", "<", System.Text.RegularExpressions.RegexOptions.IgnoreCase); result = System.Text.RegularExpressions.Regex.Replace(result, @"&rsaquo;", ">", System.Text.RegularExpressions.RegexOptions.IgnoreCase); result = System.Text.RegularExpressions.Regex.Replace(result, @"&trade;", "(tm)", System.Text.RegularExpressions.RegexOptions.IgnoreCase); result = System.Text.RegularExpressions.Regex.Replace(result, @"&frasl;", "/", System.Text.RegularExpressions.RegexOptions.IgnoreCase); result = System.Text.RegularExpressions.Regex.Replace(result, @"&lt;", "<", System.Text.RegularExpressions.RegexOptions.IgnoreCase); result = System.Text.RegularExpressions.Regex.Replace(result, @"&gt;", ">", System.Text.RegularExpressions.RegexOptions.IgnoreCase); result = System.Text.RegularExpressions.Regex.Replace(result, @"&copy;", "(c)", System.Text.RegularExpressions.RegexOptions.IgnoreCase); result = System.Text.RegularExpressions.Regex.Replace(result, @"&reg;", "(r)", System.Text.RegularExpressions.RegexOptions.IgnoreCase); // Remove all others. More can be added, see // http://hotwired.lycos.com/webmonkey/reference/special_characters/ result = System.Text.RegularExpressions.Regex.Replace(result, @"&(.{2,6});", string.Empty, System.Text.RegularExpressions.RegexOptions.IgnoreCase); // for testing //System.Text.RegularExpressions.Regex.Replace(result, // this.txtRegex.Text,string.Empty, // System.Text.RegularExpressions.RegexOptions.IgnoreCase); // make line breaking consistent result = result.Replace("\n", "\r"); // Remove extra line breaks and tabs: // replace over 2 breaks with 2 and over 4 tabs with 4. // Prepare first to remove any whitespaces in between // the escaped characters and remove redundant tabs in between line breaks result = System.Text.RegularExpressions.Regex.Replace(result, "(\r)( )+(\r)", "\r\r", System.Text.RegularExpressions.RegexOptions.IgnoreCase); result = System.Text.RegularExpressions.Regex.Replace(result, "(\t)( )+(\t)", "\t\t", System.Text.RegularExpressions.RegexOptions.IgnoreCase); result = System.Text.RegularExpressions.Regex.Replace(result, "(\t)( )+(\r)", "\t\r", System.Text.RegularExpressions.RegexOptions.IgnoreCase); result = System.Text.RegularExpressions.Regex.Replace(result, "(\r)( )+(\t)", "\r\t", System.Text.RegularExpressions.RegexOptions.IgnoreCase); // Remove redundant tabs result = System.Text.RegularExpressions.Regex.Replace(result, "(\r)(\t)+(\r)", "\r\r", System.Text.RegularExpressions.RegexOptions.IgnoreCase); // Remove multiple tabs following a line break with just one tab result = System.Text.RegularExpressions.Regex.Replace(result, "(\r)(\t)+", "\r\t", System.Text.RegularExpressions.RegexOptions.IgnoreCase); // Initial replacement target string for line breaks string breaks = "\r\r\r"; // Initial replacement target string for tabs string tabs = "\t\t\t\t\t"; for (int index = 0; index < result.Length; index++) { result = result.Replace(breaks, "\r\r"); result = result.Replace(tabs, "\t\t\t\t"); breaks = breaks + "\r"; tabs = tabs + "\t"; } // That's it. return result; } catch { return source; } } public static string GetMD5Hash(string input) { System.Security.Cryptography.MD5CryptoServiceProvider x = new System.Security.Cryptography.MD5CryptoServiceProvider(); byte[] bs = System.Text.Encoding.UTF8.GetBytes(input); bs = x.ComputeHash(bs); System.Text.StringBuilder s = new System.Text.StringBuilder(); foreach (byte b in bs) { s.Append(b.ToString("x2").ToLower()); } string password = s.ToString(); return password; } /// <summary> /// 判断guid是否为空 /// </summary> /// <param name="guid"></param> /// <returns></returns> public static bool IsEmptyGuid(Guid guid) { return guid == Guid.Empty; } public static string EncodeBase64(string str) { byte[] encbuff = System.Text.Encoding.UTF8.GetBytes(str); return Convert.ToBase64String(encbuff); } public static string DecodeBase64(string str) { byte[] decbuff = Convert.FromBase64String(str); return System.Text.Encoding.UTF8.GetString(decbuff); } /// <summary> /// DES加密字符串 /// </summary> /// <param name="encryptString">待加密的字符串</param> /// <returns>加密成功返回加密后的字符串, 有异常返回 NULL </returns> public static string Encrypt(string encryptString) { return Security.Encrypt(encryptString); } /// <summary> /// DES解密字符串 /// </summary> /// <param name="decryptString">待解密的字符串</param> /// <returns>解密成功返回解密后的字符串</returns> /// <param name="keys"></param> public static string Decrypt(string decryptString, string keys) { return Security.Decrypt(decryptString, keys); } } }
zznhgzf-t4-code-generator-clone
Project.Common/StringUtility.cs
C#
asf20
11,648
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Reflection; namespace Project.Common { public enum EnumAttachDataKey { String, Int, Decimal } [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class AttachDataAttribute : Attribute { public AttachDataAttribute(object key, object value) { this.Key = key; this.Value = value; } public object Key { get; private set; } public object Value { get; private set; } public static string GetAttachedData<T>(string memeberName, EnumAttachDataKey key) { var type = typeof(T); var memInfos = type.GetMember(memeberName); var attributes = memInfos[0].GetCustomAttributes(typeof(AttachDataAttribute), false); if (attributes.Length == 0) return null; foreach (var item in attributes) { if (((AttachDataAttribute)item).Key.ToString() == key.ToString()) { return ((AttachDataAttribute)item).Value.ToString(); } } return ((AttachDataAttribute)attributes[0]).Value.ToString(); } } public static class AttachDataExtensions { public static object GetAttachedData( this ICustomAttributeProvider provider, object key) { var attributes = (AttachDataAttribute[])provider.GetCustomAttributes( typeof(AttachDataAttribute), false); return attributes.First(a => a.Key.Equals(key)).Value; } public static T GetAttachedData<T>( this ICustomAttributeProvider provider, object key) { return (T)provider.GetAttachedData(key); } public static object GetAttachedData(this Enum value, object key) { return value.GetType().GetField(value.ToString()).GetAttachedData(key); } public static T GetAttachedData<T>(this Enum value, object key) { return (T)value.GetAttachedData(key); } } }
zznhgzf-t4-code-generator-clone
Project.Common/AttachData.cs
C#
asf20
1,809
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Project.Common { /// <summary> /// 排序 /// 作者:黄剑锋 /// 时间:2011-10-14 /// </summary> public enum EnumOrder { ASC = 0, DESC = 1 } /// <summary> /// 选择模式 /// </summary> public enum EnumSelectModel { CheckBox = 0, Radio = 1 } }
zznhgzf-t4-code-generator-clone
Project.Common/CommonEnum.cs
C#
asf20
380
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Linq.Expressions; namespace Project.Common { public class LinqOrder<T> { public Expression<Func<T, object>> Path{get;set;} public EnumOrder Direction { get; set; } } }
zznhgzf-t4-code-generator-clone
Project.Common/LinqOrder.cs
C#
asf20
278
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("Project.Common")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Project.Common")] [assembly: AssemblyCopyright("Copyright © 2011")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("9c5bec9c-432c-4f57-858d-a5e2d50a5c0f")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
zznhgzf-t4-code-generator-clone
Project.Common/Properties/AssemblyInfo.cs
C#
asf20
1,404
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Project.Common { /// <summary> /// 常量类 /// 作者:姚东 /// 时间:20111020 /// </summary> public class Consts { /// <summary> /// HTML的内容类型 /// 作者:姚东 /// 时间:20111020 /// </summary> public const string CONTENTTYPE = "text/html;"; /// <summary> /// 陆家嘴人才公寓企业GUID /// </summary> public const string 陆家嘴人才公寓企业 = "19B7CF8E-536F-4A85-83F8-307A15185141"; /// <summary> /// 陆家嘴金融城人才公寓Guid /// </summary> //TODO: Guid修改 public const string 陆家嘴金融城人才公寓 = "47236c25-b16f-4d43-8f61-9fe900f80d44"; /// <summary> /// 用户账户用到的Cookie(内网) /// </summary> public const string SYS_USER_COOKIE_KEY = "SYS_USER_COOKIE_KEY"; /// <summary> /// 用户账户用到的Cookie(外网) /// </summary> public const string SYS_USER_OUT_COOKIE_KEY = "SYS_USER_OUT_COOKIE_KEY"; public const string SYS_USER_SESSION_KEY = "SYS_USER_SESSION_KEY"; //grid默认记录行 public const int PAGE_SIZE = 20; } }
zznhgzf-t4-code-generator-clone
Project.Common/Consts.cs
C#
asf20
1,170
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Forms; namespace T4WinHost { public delegate void DelegateSetLabelText(string text,Label label); public class ThreadStateObject { public string TemplateName { get; set; } public Label LblTip { get; set; } } }
zznhgzf-t4-code-generator-clone
T4/T4WinHost/Common.cs
C#
asf20
328
using System; using System.Collections.Generic; using System.Linq; using System.Windows.Forms; namespace T4WinHost { static class Program { /// <summary> /// The main entry point for the application. /// </summary> [STAThread] static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Main()); } } }
zznhgzf-t4-code-generator-clone
T4/T4WinHost/Program.cs
C#
asf20
401
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; using System.IO; using Microsoft.VisualStudio.TextTemplating; using T4WinHost.Base; using System.CodeDom.Compiler; using System.Runtime.Remoting.Messaging; using System.Data.SqlClient; using System.Threading; using T4Common; using T4Common.Domain; using System.Threading.Tasks; namespace T4WinHost { public partial class Main : Form { private static object synObject = new object(); private static object synObj = new object(); private SqlServerProcMetaReader procMetaReader = null; private SqlServerTableMetaReader tableMetaReader = null; private IList<Table> tables = null; private int dealFileCount = 0; private int taskFinishedCount = 0; private DataGridViewCell contextCell; public Main() { InitializeComponent(); } private void Main_Load(object sender, EventArgs e) { InitialTemplateInfo(); InitialSettingInfo(); if (TestConnection()) { procMetaReader = new SqlServerProcMetaReader(txtCon.Text); tableMetaReader = new SqlServerTableMetaReader(txtCon.Text); InitialGvProcedures(); tables = tableMetaReader.GetTables("dbo"); InitialGvTables(tables); InitialGvViews(tables); } } private void InitialSettingInfo() { txtNameSpace.Text = T4Common.Properties.Settings.Default.NamespacePrefix; txtFolder.Text = T4Common.Properties.Settings.Default.ProjectRootPath; txtCon.Text = T4Common.Properties.Settings.Default.SqlConnectionString; } private void InitialTemplateInfo() { string templateFolder = string.Format(@"{0}\Templates", Environment.CurrentDirectory); string[] files = Directory.GetFiles(templateFolder); List<TemplateInfo> templateInfos = new List<TemplateInfo>(); for (int i = 0; i < files.Count(); i++) { if (Path.GetExtension(Path.GetFileName(files[i])) != ".tt") continue; templateInfos.Add(new TemplateInfo() { Name = Path.GetFileName(files[i]), Description = "", FullPath = files[i] }); } DataGridViewTextBoxColumn ColTemplateName = new DataGridViewTextBoxColumn(); ColTemplateName.DataPropertyName = "name"; ColTemplateName.Name = "name"; ColTemplateName.HeaderText = "Template file"; ColTemplateName.ReadOnly = true; ColTemplateName.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; DataGridViewTextBoxColumn ColDescription = new DataGridViewTextBoxColumn(); ColDescription.DataPropertyName = "description"; ColDescription.HeaderText = "Description"; ColDescription.Name = "Description"; ColDescription.Width = 300; ColDescription.ReadOnly = true; DataGridViewTextBoxColumn ColTemplateFullPath = new DataGridViewTextBoxColumn(); ColTemplateFullPath.DataPropertyName = "FullPath"; ColTemplateFullPath.Name = "FullPath"; ColTemplateFullPath.Visible = false; gvTemplate.Columns.Add(ColTemplateName); gvTemplate.Columns.Add(ColDescription); gvTemplate.Columns.Add(ColTemplateFullPath); gvTemplate.DataSource = templateInfos; } private void ProcessTemplate(params string[] args) { string templateFileName = null; if (args.Length == 0) { throw new System.Exception("you must provide a text template file path"); } templateFileName = args[0]; if (templateFileName == null) { throw new ArgumentNullException("the file name cannot be null"); } if (!File.Exists(templateFileName)) { throw new FileNotFoundException("the file cannot be found"); } OnShowWorkInfoEventHandler(this, new WorkEventArgs(WorkStage.InitializeWork, string.Format("processing template: {0}", Path.GetFileName(templateFileName)))); TextTemplatingSession session = new TextTemplatingSession(); session.Add("t4Parameter", T4Parameters.Default); CustomCmdLineHost host = new CustomCmdLineHost(); host.TemplateFileValue = templateFileName; host.Session = session; Engine engine = new Engine(); //Read the text template. string input = File.ReadAllText(templateFileName); input = input.Replace(@"$(ProjectDir)\", ""); //Transform the text template. string output = engine.ProcessTemplate(input, host); foreach (CompilerError error in host.Errors) { Console.WriteLine(error.ToString()); } lock (synObject) { int prograssBarValue = OnGetValueEventHandler(this, null); prograssBarValue++; OnDoWorkEventHandler(this, new WorkEventArgs(WorkStage.DoWork, string.Format("{0} has been processed...", templateFileName), prograssBarValue) { TemplateName = Path.GetFileName(templateFileName) }); } } private void BtnGenerateAll_Click(object sender, EventArgs e) { this.progressBar.Value = 0; this.BtnGenerateAll.Enabled = false; this.lblInfo.Text = ""; RecoverBackground(); if (!CheckIntegrity()) return; if (!TestConnection()) MessageBox.Show("Connection failed!"); T4Parameters.Default.IsGenerateSingle = false; SaveSettings(); ThreadPool.QueueUserWorkItem(InitialStoreProcedures, null); } private void Process() { List<string> selectFiles = RetriveGridViewSelect(gvTemplate, "FullPath", "ColCheck"); OnStartWorkEventHandler(this, new WorkEventArgs(WorkStage.BeginWork, "Start to work...", selectFiles.Count)); for (int i = 0; i < selectFiles.Count(); i++) { ThreadPool.QueueUserWorkItem(MutipleThreadDo, selectFiles[i]); } dealFileCount = selectFiles.Count; Thread monitor = new Thread(Monitor); monitor.Start(); } private void InitialStoreProcedures(object state) { List<string> selectFiles = RetriveGridViewSelect(gvTemplate, "FullPath", "ColCheck"); int i = 0; for (i = 0; i < selectFiles.Count; i++) { if (Path.GetFileName(selectFiles[i]) != "Biz.tt" && Path.GetFileName(selectFiles[i]) != "Dal.tt" && Path.GetFileName(selectFiles[i]) != "CSProj.Enum.tt" && Path.GetFileName(selectFiles[i]) != "CSProj.Solution.tt" && Path.GetFileName(selectFiles[i]) != "Entity.tt" && Path.GetFileName(selectFiles[i]) != "EntityMapping.tt" && Path.GetFileName(selectFiles[i]) != "Enum.tt") break; } if (i == selectFiles.Count) { InitailTables(); Process(); return; } SqlServerProcMetaReader procMetaReader = new SqlServerProcMetaReader(T4Parameters.Default.SqlConnectionString); T4Parameters.Default.StoreProcedureParametersMeta = procMetaReader.SpParaMeta; T4Parameters.Default.StoreProcedureResultMeta = procMetaReader.SpResultMeta; if (procMetaReader.SpFailed.Count > 0) { StringBuilder spErrorBuilder = new StringBuilder(); spErrorBuilder.AppendLine(string.Format("{0} store procedure failed", procMetaReader.SpFailed.Count)); spErrorBuilder.AppendLine("**********************************************************************"); foreach (var item in procMetaReader.SpFailed) { spErrorBuilder.AppendLine(string.Format("Procedure name : {0}", item.Key)); } spErrorBuilder.AppendLine("**********************************************************************"); OnSetLogHandler(this, new WorkEventArgs(WorkStage.DoWork, "") { ErrorInfo = spErrorBuilder.ToString() }); } InitailTables(); Process(); } private void InitailTables() { List<string> selectFiles = RetriveGridViewSelect(gvTemplate, "FullPath", "ColCheck"); int i = 0; for (i = 0; i < selectFiles.Count; i++) { if (Path.GetFileName(selectFiles[i]) != "CSProj.Solution.tt") break; } if (i == selectFiles.Count) return; OnShowWorkInfoEventHandler(this, new WorkEventArgs(WorkStage.InitializeWork, "Initialize Tables..")); SqlServerTableMetaReader tableReader = new SqlServerTableMetaReader(T4Parameters.Default.SqlConnectionString); T4Parameters.Default.Tables = tableReader.RetriveTableDetails(); //table no primary key and view no keyID List<string> errorTables = new List<string>(); List<string> errorViews = new List<string>(); for (int j = 0; j < T4Parameters.Default.Tables.Count; j++) { if (T4Parameters.Default.Tables[j].TableType == T4Common.Domain.EnumTableType.Table && T4Parameters.Default.Tables[j].PrimaryKey.Columns.Count == 0) errorTables.Add(T4Parameters.Default.Tables[j].Name); else if ((T4Parameters.Default.Tables[j].TableType == T4Common.Domain.EnumTableType.View && T4Parameters.Default.Tables[j].Columns.Count(x => x.Name.Equals("KeyID", StringComparison.OrdinalIgnoreCase)) == 0)) errorViews.Add(T4Parameters.Default.Tables[j].Name); } SetTableErrorlog(errorTables, EnumTableType.Table); SetTableErrorlog(errorViews, EnumTableType.View); } private void SetTableErrorlog(List<string> errors, EnumTableType tableType) { if (errors.Count() > 0) { StringBuilder tableErrorBuilder = new StringBuilder(); tableErrorBuilder.AppendLine(string.Format("{0} {1} failed", errors.Count(), tableType.ToString())); tableErrorBuilder.AppendLine("**********************************************************************"); foreach (var item in errors) { tableErrorBuilder.AppendLine(string.Format("{1} name : {0} , has no {2} .", item, tableType.ToString(), tableType == EnumTableType.Table ? "primary key" : "keyID")); } tableErrorBuilder.AppendLine("**********************************************************************"); OnSetLogHandler(this, new WorkEventArgs(WorkStage.DoWork, "") { ErrorInfo = tableErrorBuilder.ToString() }); } } private List<string> RetriveGridViewSelect(DataGridView gridView, string dataColName, string gridColName) { List<string> selects = new List<string>(); for (int i = 0; i < gridView.Rows.Count; i++) { DataGridViewCheckBoxCell colCheck = gridView.Rows[i].Cells[gridColName] as DataGridViewCheckBoxCell; if (colCheck.Value != null && Convert.ToBoolean(colCheck.Value)) { DataGridViewTextBoxCell colIdentity = gridView.Rows[i].Cells[dataColName] as DataGridViewTextBoxCell; selects.Add(colIdentity.Value.ToString()); } } return selects; } public void Monitor() { while (true) { Thread.Sleep(1000); int prograssBarValue = OnGetValueEventHandler(this, null); if (prograssBarValue == dealFileCount) { OnEndWorkEventHandler(this, new WorkEventArgs(WorkStage.EndWork, "Process is finished!", dealFileCount)); return; } } } private void MutipleThreadDo(object o) { ProcessTemplate(o as string); } private void SaveSettings() { T4Common.Properties.Settings.Default.NamespacePrefix = txtNameSpace.Text.Trim(); T4Common.Properties.Settings.Default.ProjectRootPath = txtFolder.Text.EndsWith("\\") ? txtFolder.Text : txtFolder.Text + "\\"; T4Common.Properties.Settings.Default.SqlConnectionString = txtCon.Text; T4Common.Properties.Settings.Default.Save(); T4Parameters.Default.SqlConnectionString = T4Common.Properties.Settings.Default.SqlConnectionString; T4Parameters.Default.NamespacePrefix = T4Common.Properties.Settings.Default.NamespacePrefix; T4Parameters.Default.ProjectRootPath = T4Common.Properties.Settings.Default.ProjectRootPath; T4Parameters.Default.DalFolder = string.Format("{0}.Dal", T4Parameters.Default.NamespacePrefix); T4Parameters.Default.BizFolder = string.Format("{0}.Biz", T4Parameters.Default.NamespacePrefix); T4Parameters.Default.EntityFolder = string.Format("{0}.Entity", T4Parameters.Default.NamespacePrefix); T4Parameters.Default.EnumFolder = string.Format("{0}.Enum", T4Parameters.Default.NamespacePrefix); } private void BtnCon_Click(object sender, EventArgs e) { if (TestConnection()) { MessageBox.Show("Successful connection!", "Connection information"); procMetaReader = new SqlServerProcMetaReader(txtCon.Text); tableMetaReader = new SqlServerTableMetaReader(txtCon.Text); tables = tableMetaReader.GetTables("dbo"); InitialGvProcedures(); InitialGvTables(tables); InitialGvViews(tables); } else MessageBox.Show("Connection failed!"); } private bool CheckIntegrity() { string message = ""; if (string.IsNullOrEmpty(txtCon.Text)) message += "DB Connection String can't be empty!\n"; if (string.IsNullOrEmpty(txtFolder.Text)) message += "Destination folder can't be emty!\n"; if (string.IsNullOrEmpty(txtNameSpace.Text)) message += "Namespace can't be emty!\n"; if (message == "") return true; return false; } private bool TestConnection() { SqlConnection connection = new SqlConnection(); try { connection.ConnectionString = txtCon.Text.Trim(); connection.Open(); this.Text = string.Format("{0} - {1}", "T4 Engine", connection.Database); return true; } catch { return false; } } private void btnSelectFolder_Click(object sender, EventArgs e) { FolderBrowserDialog openDialog = new FolderBrowserDialog(); DialogResult result = openDialog.ShowDialog(); if (result.ToString() == "OK") txtFolder.Text = openDialog.SelectedPath; } private void BtnClose_Click(object sender, EventArgs e) { this.Close(); this.Dispose(); } private void cbSelectAll_CheckedChanged(object sender, EventArgs e) { CheckBoxSelectAll(gvTemplate, cbSelectAll, "ColCheck"); } private void CheckBoxSelectAll(DataGridView gridView, CheckBox checkbox, string colName) { for (int i = 0; i < gridView.Rows.Count; i++) { DataGridViewCheckBoxCell colCheck = gridView.Rows[i].Cells[colName] as DataGridViewCheckBoxCell; colCheck.Value = checkbox.Checked; } } private void cbReverse_CheckedChanged(object sender, EventArgs e) { CheckBoxReverse(gvTemplate, "ColCheck"); } private void CheckBoxReverse(DataGridView gridView, string colName) { for (int i = 0; i < gridView.Rows.Count; i++) { DataGridViewCheckBoxCell colCheck = gridView.Rows[i].Cells[colName] as DataGridViewCheckBoxCell; if (colCheck.Value != null && Convert.ToBoolean(colCheck.Value)) colCheck.Value = false; else colCheck.Value = true; } } private void SetGridRecordBackground(string templateName) { for (int i = 0; i < gvTemplate.Rows.Count; i++) { DataGridViewTextBoxCell colName = gvTemplate.Rows[i].Cells["name"] as DataGridViewTextBoxCell; if (!colName.Value.Equals(templateName)) continue; gvTemplate.Rows[i].DefaultCellStyle.BackColor = Color.Green; } } private void RecoverBackground() { for (int i = 0; i < gvTemplate.Rows.Count; i++) { gvTemplate.Rows[i].DefaultCellStyle.BackColor = Color.White; } } #region Tab Tables public void InitialGvTables(IList<Table> tables) { CommonInitialGridView(tables, gvTables, EnumTableType.Table); } private void FilterTables() { if (string.IsNullOrEmpty(txtTableName.Text.Trim())) { gvTables.DataSource = tables.Where(x => x.TableType == EnumTableType.Table).ToList(); return; } gvTables.DataSource = tables.Where(x => (x.Name.ToLower().Contains(txtTableName.Text.Trim().ToLower()) || x.Remark.Contains(txtTableName.Text.Trim())) && x.TableType == EnumTableType.Table).ToList(); } private void btnSearchTable_Click(object sender, EventArgs e) { FilterTables(); } private void txtTableName_TextChanged(object sender, EventArgs e) { FilterTables(); } private void CommonInitialGridView(IList<Table> tables, DataGridView gridView, EnumTableType tableType) { gridView.AutoGenerateColumns = false; if (gridView.ColumnCount <= 1) { DataGridViewTextBoxColumn ColTemplateName = new DataGridViewTextBoxColumn(); ColTemplateName.DataPropertyName = "Name"; ColTemplateName.Name = "name"; ColTemplateName.HeaderText = "Name"; ColTemplateName.ReadOnly = true; ColTemplateName.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; DataGridViewTextBoxColumn ColRemark = new DataGridViewTextBoxColumn(); ColRemark.DataPropertyName = "Remark"; ColRemark.Name = "Remark"; ColRemark.HeaderText = "Remark"; ColRemark.ReadOnly = true; ColRemark.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; gridView.Columns.Add(ColTemplateName); gridView.Columns.Add(ColRemark); gridView.AllowUserToResizeRows = false; } gridView.DataSource = tables.Where(x => x.TableType == tableType).ToList(); } private void CommonGenerateTable(IList<string> selectObjectNames, Label lblTip, Button btnGenerate) { IList<Table> tableDetails = new List<Table>(); for (int i = 0; i < selectObjectNames.Count; i++) { var tempTable = tables.First(x => x.Name == selectObjectNames[i]); tempTable.Columns = tableMetaReader.GetTableDetails(tempTable, "dbo"); tableDetails.Add(tempTable); } if (!CheckIntegrity()) { MessageBox.Show("设置不正确,请确认!"); return; } SaveSettings(); T4Parameters.Default.Tables = tableDetails; T4Parameters.Default.IsGenerateSingle = true; var taskEntity = Task.Factory.StartNew( () => GenerateFile(new ThreadStateObject() { TemplateName = "Entity.tt", LblTip = lblTip }) ); var taskMapping = Task.Factory.StartNew( () => GenerateFile(new ThreadStateObject() { TemplateName = "EntityMapping.tt", LblTip = lblTip }) ); var taskBiz = Task.Factory.StartNew( () => GenerateFile(new ThreadStateObject() { TemplateName = "Biz.tt", LblTip = lblTip }) ); var taskDal = Task.Factory.StartNew( () => GenerateFile(new ThreadStateObject() { TemplateName = "Dal.tt", LblTip = lblTip }) ); var taskSyn = Task.Factory.StartNew( () => MonitorTask(lblTip, btnGenerate) ); } private void btnGenerateSelectTable_Click(object sender, EventArgs e) { var selectTableNames = RetriveGridViewSelect(gvTables, "name", "ColTableCheck"); if (selectTableNames.Count == 0) { lblGenerateTable.Text = "请选择表."; return; } btnGenerateSelectTable.Enabled = false; CommonGenerateTable(selectTableNames, lblGenerateTable, btnGenerateSelectTable); } private void GenerateFile(ThreadStateObject threadStateObject) { try { SetLabelText(string.Format("正在生成 {0} ", threadStateObject.TemplateName.ToString()), threadStateObject.LblTip); string templateFolder = string.Format(@"{0}\Templates\", Environment.CurrentDirectory); TextTemplatingSession session = new TextTemplatingSession(); session.Add("t4Parameter", T4Parameters.Default); CustomCmdLineHost host = new CustomCmdLineHost(); host.TemplateFileValue = threadStateObject.TemplateName.ToString(); host.Session = session; Engine engine = new Engine(); //Read the text template. string input = File.ReadAllText(templateFolder + threadStateObject.TemplateName); input = input.Replace(@"$(ProjectDir)\", ""); //Transform the text template. string output = engine.ProcessTemplate(input, host); foreach (CompilerError error in host.Errors) { Console.WriteLine(error.ToString()); } } catch { } lock (synObj) { taskFinishedCount = taskFinishedCount + 1; } } private void MonitorTask(Label lblTip, Button btnGenerate) { while (true) { if (taskFinishedCount == 4) { T4Parameters.Default.Tables = null; MethodInvoker methodInvoker = new MethodInvoker( () => btnGenerate.Enabled = true ); Invoke(methodInvoker); taskFinishedCount = 0; SetLabelText("生成结束", lblTip); return; } Thread.Sleep(1000); } } public void SetLabelText(string text, Label label) { DelegateSetLabelText method = new DelegateSetLabelText((x, l) => l.Text = x); this.Invoke(method, text, label); } private void cbTableSelectAll_CheckedChanged(object sender, EventArgs e) { CheckBoxSelectAll(gvTables, cbTableSelectAll, "ColTableCheck"); } private void cbTableReverse_CheckedChanged(object sender, EventArgs e) { CheckBoxReverse(gvTables, "ColTableCheck"); } private void gvTables_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e) { if (e.RowIndex == -1) return; if (e.ColumnIndex == 1) { contextCell = gvTables.Rows[e.RowIndex].Cells[e.ColumnIndex]; contextCell.ContextMenuStrip = contextMenuStrip; } gvTables.Rows[e.RowIndex].Selected = true; if (gvTables.Rows[e.RowIndex].Cells[e.ColumnIndex].Value != null && !string.IsNullOrEmpty(gvTables.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString())) Clipboard.SetText(gvTables.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString()); DataGridViewTextBoxCell colIdentity = gvTables.Rows[e.RowIndex].Cells["name"] as DataGridViewTextBoxCell; var tempTable = tables.First(x => x.Name == colIdentity.Value); tempTable.Columns = tableMetaReader.GetTableDetails(tempTable, "dbo"); gvTableDetail.DataSource = tempTable.Columns; } private void gvTableDetail_CellClick(object sender, DataGridViewCellEventArgs e) { if (e.RowIndex <= 0 || e.ColumnIndex > 1 || e.ColumnIndex < 0) return; if (gvTableDetail.Rows[e.RowIndex].Cells[e.ColumnIndex].Value == null || string.IsNullOrEmpty(gvTableDetail.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString())) return; Clipboard.SetText(gvTableDetail.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString()); } #endregion #region Tab Views public void InitialGvViews(IList<Table> tables) { CommonInitialGridView(tables, gvViews, EnumTableType.View); } private void FilterViews() { if (string.IsNullOrEmpty(txtViewName.Text.Trim())) { gvViews.DataSource = tables.Where(x => x.TableType == EnumTableType.View).ToList(); return; } gvViews.DataSource = tables.Where(x => (x.Name.ToLower().Contains(txtViewName.Text.Trim().ToLower()) || x.Remark.Contains(txtViewName.Text.Trim())) && x.TableType == EnumTableType.View).ToList(); } private void btnSearchView_Click(object sender, EventArgs e) { FilterViews(); } private void txtViewName_TextChanged(object sender, EventArgs e) { FilterViews(); } private void btnGenerateView_Click(object sender, EventArgs e) { var selectViewNames = RetriveGridViewSelect(gvViews, "name", "ColViewCheck"); if (selectViewNames.Count == 0) { lblGenerateView.Text = "请选择视图."; return; } btnGenerateView.Enabled = false; CommonGenerateTable(selectViewNames, lblGenerateView, btnGenerateView); } private void cbViewSelectAll_CheckedChanged(object sender, EventArgs e) { CheckBoxSelectAll(gvViews, cbViewSelectAll, "ColViewCheck"); } private void cbViewReverse_CheckedChanged(object sender, EventArgs e) { CheckBoxReverse(gvViews, "ColViewCheck"); } private void gvViews_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e) { if (e.RowIndex == -1) return; if (e.ColumnIndex == 1) { contextCell = gvViews.Rows[e.RowIndex].Cells[e.ColumnIndex]; contextCell.ContextMenuStrip = contextMenuStrip; } gvViews.Rows[e.RowIndex].Selected = true; if (gvViews.Rows[e.RowIndex].Cells[e.ColumnIndex].Value != null && !string.IsNullOrEmpty(gvViews.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString())) Clipboard.SetText(gvViews.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString()); DataGridViewTextBoxCell colIdentity = gvViews.Rows[e.RowIndex].Cells["name"] as DataGridViewTextBoxCell; var tempTable = tables.First(x => x.Name == colIdentity.Value); tempTable.Columns = tableMetaReader.GetTableDetails(tempTable, "dbo"); gvViewDetail.DataSource = tempTable.Columns; } private void gvViewDetail_CellClick(object sender, DataGridViewCellEventArgs e) { if (e.RowIndex < 0 || e.ColumnIndex > 1 || e.ColumnIndex < 0) return; if (gvViewDetail.Rows[e.RowIndex].Cells[e.ColumnIndex].Value == null || string.IsNullOrEmpty(gvViewDetail.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString())) return; Clipboard.SetText(gvViewDetail.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString()); } #endregion #region Tab Procedure public StoreProcedure StoreProcedure { get; set; } public SqlParameterCollection ParameterCollection { get; set; } public bool IsCanGenerateFile { get; set; } public void InitialGvProcedures() { List<StoreProcedure> procedures = procMetaReader.StoreProcedures; if (gvProcedures.ColumnCount == 1) { DataGridViewTextBoxColumn ColTemplateName = new DataGridViewTextBoxColumn(); ColTemplateName.DataPropertyName = "name"; ColTemplateName.Name = "name"; ColTemplateName.HeaderText = "Name"; ColTemplateName.ReadOnly = true; ColTemplateName.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; gvProcedures.Columns.Add(ColTemplateName); gvProcedures.AutoGenerateColumns = false; } gvProcedures.DataSource = procedures; } private void InitialGvProcedureParameters() { DataGridViewTextBoxColumn ColTemplateName = new DataGridViewTextBoxColumn(); ColTemplateName.DataPropertyName = "CName"; ColTemplateName.Name = "CName"; ColTemplateName.HeaderText = "Name"; ColTemplateName.ReadOnly = true; ColTemplateName.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; DataGridViewCheckBoxColumn ColNullable = new DataGridViewCheckBoxColumn(); ColNullable.DataPropertyName = "IsNullable"; ColNullable.HeaderText = "IsNullable"; ColNullable.Name = "IsNullable"; ColNullable.Width = 100; ColNullable.ReadOnly = true; ColNullable.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; DataGridViewTextBoxColumn ColType = new DataGridViewTextBoxColumn(); ColType.DataPropertyName = "CType"; ColType.Name = "CType"; ColType.HeaderText = "Type"; ColType.ReadOnly = true; ColType.Width = 150; ColType.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill; gvParameters.AutoGenerateColumns = false; if (gvParameters.ColumnCount == 1) { gvParameters.Columns.Insert(0, ColTemplateName); gvParameters.Columns.Insert(1, ColNullable); gvParameters.Columns.Insert(2, ColType); } gvParameters.DataSource = StoreProcedure.Parameters; } private void gvProcedures_CellClick(object sender, DataGridViewCellEventArgs e) { if (e.RowIndex == -1) return; if (gvProcedures.Rows[e.RowIndex].Cells[e.ColumnIndex].Value != null && !string.IsNullOrEmpty(gvProcedures.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString())) Clipboard.SetText(gvProcedures.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString()); var procedureName = gvProcedures.Rows[e.RowIndex].Cells["Name"] as DataGridViewTextBoxCell; StoreProcedure = procMetaReader.StoreProcedures.First(x => x.Name == procedureName.Value.ToString()); ParameterCollection = procMetaReader.GetParameterCollectionByProcedure(procedureName.Value.ToString()); IsCanGenerateFile = CheckIntegrity(); if (IsCanGenerateFile) SaveSettings(); procMetaReader.FillParameter(StoreProcedure); InitialGvProcedureParameters(); } private void btnExecuteProcedure_Click(object sender, EventArgs e) { SqlConnection connection = new SqlConnection(txtCon.Text); SqlCommand innerCommand = new SqlCommand() { Connection = connection }; SqlDataAdapter adapter = new SqlDataAdapter(innerCommand); innerCommand.CommandType = CommandType.StoredProcedure; innerCommand.CommandText = StoreProcedure.Name; var parameters = RetriveCommandParametersFromUI(); if (parameters != null) innerCommand.Parameters.AddRange(parameters); else { innerCommand.Parameters.AddRange(procMetaReader.RetriveParametersWithDefaultValue(StoreProcedure.Name)); } DataSet ds = new DataSet(); try { adapter.Fill(ds); gvResult.DataSource = ds.Tables[0]; } catch (Exception ex) { MessageBox.Show(ex.Message); } } private SqlParameter[] RetriveCommandParametersFromUI() { bool isAllNull = true; List<SqlParameter> parameters = new List<SqlParameter>(); for (int i = 0; i < gvParameters.RowCount; i++) { var parameterName = gvParameters.Rows[i].Cells["CName"].Value.ToString(); var parameterValue = gvParameters.Rows[i].Cells["ColParameterValue"].Value; if (parameterValue == null) continue; isAllNull = false; SqlParameter newParameter = new SqlParameter(parameterName, parameterValue); parameters.Add(newParameter); } if (isAllNull) return null; return parameters.ToArray(); } private void gvParameters_CellDoubleClick(object sender, DataGridViewCellEventArgs e) { if (e.ColumnIndex != 0) return; } private void btnGenerateProcedure_Click(object sender, EventArgs e) { btnGenerateProcedure.Enabled = false; Dictionary<string, List<SpColumn>> storeProcedureResultMeta = null; Dictionary<string, List<SpColumn>> storeProcedureParameterMeta = null; try { storeProcedureParameterMeta = procMetaReader.RetriveStoreProcedureParameterMeta(new string[] { StoreProcedure.Name }); Dictionary<string, SqlParameter[]> storeProcedureParameters = null; var parameters = RetriveCommandParametersFromUI(); if (parameters != null) { if (storeProcedureParameters == null) storeProcedureParameters = new Dictionary<string, SqlParameter[]>(); storeProcedureParameters.Add(StoreProcedure.Name, parameters); } Dictionary<string, string> failedProcedures = new Dictionary<string, string>(); storeProcedureResultMeta = procMetaReader.RetriveStoreProcedureResultMeta(failedProcedures, new string[] { StoreProcedure.Name }, storeProcedureParameters); if (failedProcedures.Count != 0) { MessageBox.Show(failedProcedures.First().Value); btnGenerateProcedure.Enabled = true; return; } } catch (Exception ex) { MessageBox.Show(ex.Message); btnGenerateProcedure.Enabled = true; return; } T4Parameters.Default.StoreProcedureParametersMeta = storeProcedureParameterMeta; T4Parameters.Default.StoreProcedureResultMeta = storeProcedureResultMeta; var taskEntity = Task.Factory.StartNew( () => GenerateFile(new ThreadStateObject() { TemplateName = "SPEntity.tt", LblTip = lblGenerateProcedure }) ); var taskEntityMapping = Task.Factory.StartNew( () => GenerateFile(new ThreadStateObject() { TemplateName = "SPEntityMapping.tt", LblTip = lblGenerateProcedure }) ); var taskDal = Task.Factory.StartNew( () => GenerateFile(new ThreadStateObject() { TemplateName = "SPDal.tt", LblTip = lblGenerateProcedure }) ); var taskBiz = Task.Factory.StartNew( () => GenerateFile(new ThreadStateObject() { TemplateName = "SPBiz.tt", LblTip = lblGenerateProcedure }) ); var taskSyn = Task.Factory.StartNew( () => MonitorProcedureTask() ); } private void MonitorProcedureTask() { while (true) { if (taskFinishedCount == 4) { T4Parameters.Default.StoreProcedureParametersMeta = null; T4Parameters.Default.StoreProcedureResultMeta = null; MethodInvoker methodInvoker = new MethodInvoker( () => btnGenerateProcedure.Enabled = true ); Invoke(methodInvoker); taskFinishedCount = 0; SetLabelText("生成结束", lblGenerateProcedure); return; } Thread.Sleep(1000); } } private void txtProcedureName_TextChanged(object sender, EventArgs e) { gvProcedures.DataSource = procMetaReader.StoreProcedures.Where(x => x.Name.ToLower().Contains(txtProcedureName.Text.Trim().ToLower())).ToList(); } #endregion #region Progress bar //线程开始的时候调用的委托 private delegate void MaxValueDelegate(WorkEventArgs e); //线程执行中调用的委托 private delegate void NowValueDelegate(WorkEventArgs e); //线程执行结束调用的委托 private delegate void EndValueDelegate(WorkEventArgs e); //获得Progress bar value private delegate int GetValueDelegate(EventArgs e); //线程初始化设置 private delegate void InitialDelegate(WorkEventArgs e); //线程设置log private delegate void SetLogDelegate(WorkEventArgs e); void OnShowWorkInfoEventHandler(object sender, WorkEventArgs e) { InitialDelegate initial = new InitialDelegate(Initialize); this.Invoke(initial, e); } void OnSetLogHandler(object sender, WorkEventArgs e) { SetLogDelegate setLog = new SetLogDelegate(SetLog); this.Invoke(setLog, e); } /// <summary> /// 线程开始事件,设置进度条最大值,需要一个委托来替我完成 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void OnStartWorkEventHandler(object sender, WorkEventArgs e) { MaxValueDelegate max = new MaxValueDelegate(SetMaxValue); this.Invoke(max, e); } /// <summary> /// 线程执行中的事件,设置进度条当前进度,需要一个委托来替我完成 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void OnDoWorkEventHandler(object sender, WorkEventArgs e) { NowValueDelegate now = new NowValueDelegate(SetNowValue); this.Invoke(now, e); } int OnGetValueEventHandler(object sender, EventArgs e) { GetValueDelegate getvalue = new GetValueDelegate(GetValue); return Convert.ToInt32(this.Invoke(getvalue, e)); } /// <summary> /// 线程完成事件 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> void OnEndWorkEventHandler(object sender, WorkEventArgs e) { EndValueDelegate end = new EndValueDelegate(SetEndValue); this.Invoke(end, e); } /// <summary> /// 被委托调用,专门设置进度条最大值的 /// </summary> /// <param name="maxValue"></param> private void SetMaxValue(WorkEventArgs e) { this.progressBar.Maximum = e.Position; this.progressBar.Value = 0; this.lblInfo.Text = e.Info; } private int GetValue(EventArgs e) { return this.progressBar.Value; } private void Initialize(WorkEventArgs e) { this.lblInfo.Text = e.Info; //this.progressBar.Value = 0; } private void SetLog(WorkEventArgs e) { txtLog.Text = txtLog.Text + e.ErrorInfo + "\n"; } /// <summary> /// 被委托调用,专门设置进度条当前值的 /// </summary> /// <param name="nowValue"></param> private void SetNowValue(WorkEventArgs e) { this.progressBar.Value = e.Position; lblInfo.Text = e.Info; SetGridRecordBackground(e.TemplateName); } /// <summary> /// 被委托调用,专门设置进度条结束后的处理 /// </summary> /// <param name="nowValue"></param> private void SetEndValue(WorkEventArgs e) { this.progressBar.Value = e.Position; lblInfo.Text = e.Info; BtnGenerateAll.Enabled = true; RecoverBackground(); } class WorkEventArgs : EventArgs { //主要是用来往外传递信息的 public WorkStage Stage; public string Info = ""; public int Position = 0; public string TemplateName { get; set; } public string ErrorInfo { get; set; } public WorkEventArgs(WorkStage Stage, string Info, int Position) { this.Stage = Stage; this.Info = Info; this.Position = Position; } public WorkEventArgs(WorkStage Stage, string Info) { this.Stage = Stage; this.Info = Info; } } public enum WorkStage { InitializeWork, BeginWork, //准备工作 DoWork, //正在工作 EndWork, //工作结束 } #endregion private void contextMenuStrip_ItemClicked(object sender, ToolStripItemClickedEventArgs e) { switch (e.ClickedItem.Name) { case "entity": Clipboard.SetText(contextCell.Value.ToString().Replace("_", "")); break; case "dal": Clipboard.SetText(string.Format("Dal{0}", contextCell.Value.ToString().Replace("_", ""))); break; case "biz": Clipboard.SetText(string.Format("Biz{0}", contextCell.Value.ToString().Replace("_", ""))); break; case "defEntityProperty": Clipboard.SetText(string.Format("public {0} {0}Entity {{ get; set; }}", contextCell.Value.ToString().Replace("_", ""))); break; case "defEntityVariable": Clipboard.SetText(string.Format("{0} {1}Entity;", contextCell.Value.ToString().Replace("_", ""), contextCell.Value.ToString().Substring(0, 1).ToLower() + contextCell.Value.ToString().Substring(1, contextCell.Value.ToString().Length - 1).Replace("_", ""))); break; case "defBizVariable": Clipboard.SetText(string.Format("private {0} {1};", string.Format("Biz{0}", contextCell.Value.ToString().Replace("_", "")), string.Format("biz{0}", contextCell.Value.ToString().Replace("_", "")))); break; case "defDalVariable": Clipboard.SetText(string.Format("private {0} {1};", string.Format("Dal{0}", contextCell.Value.ToString().Replace("_", "")), string.Format("dal{0}", contextCell.Value.ToString().Replace("_", "")))); break; case "defIListVariable": Clipboard.SetText(string.Format("IList<{0}> {1}Collection;", string.Format("{0}", contextCell.Value.ToString().Replace("_", "")), string.Format("{0}", contextCell.Value.ToString().Replace("_", "")))); break; case "defIListProperty": Clipboard.SetText(string.Format("public IList<{0}> {0}Collection {{ get; set; }}", contextCell.Value.ToString().Replace("_", ""))); break; } } protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { if (keyData.ToString() == "F5" && tabCommand.Visible) { var conn = new SqlConnection(txtCon.Text); conn.Open(); using (conn) { using (var command = new SqlCommand()) { try { command.Connection = conn; command.CommandText = string.IsNullOrEmpty(richTbCommand.SelectedText) ? richTbCommand.Text : richTbCommand.SelectedText; SqlDataAdapter adapter = new SqlDataAdapter(command); DataTable dataTable = new DataTable(); adapter.Fill(dataTable); gvCommandResult.DataSource = dataTable; } catch(Exception ex) { } } } } return base.ProcessCmdKey(ref msg, keyData); } } }
zznhgzf-t4-code-generator-clone
T4/T4WinHost/Main.cs
C#
asf20
38,033
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("T4WinHost")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("T4WinHost")] [assembly: AssemblyCopyright("Copyright © 2011")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("033f352f-8ab4-431a-a834-124a6b4e22a2")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
zznhgzf-t4-code-generator-clone
T4/T4WinHost/Properties/AssemblyInfo.cs
C#
asf20
1,394
using System; using System.Collections.Generic; using System.Linq; using System.Text; using T4Common; using T4Common.Domain; namespace T4WinHost.Base { [Serializable] public class T4Parameters { #region Initial info public string SqlConnectionString { get; set; } public string NamespacePrefix { get; set; } public string ProjectRootPath { get; set; } public string DalFolder { get; set; } public string BizFolder { get; set; } public string EntityFolder { get; set; } public string EnumFolder { get; set; } public bool IsGenerateSingle { get; set; } #endregion #region StoreProcedure public Dictionary<string, List<SpColumn>> StoreProcedureParametersMeta { get; set; } public Dictionary<string, List<SpColumn>> StoreProcedureResultMeta { get; set; } #endregion #region Tables public IList<Table> Tables { get; set; } #endregion private static T4Parameters _default; public static T4Parameters Default { get { if (_default != null) return _default; _default = new T4Parameters(); return _default; } } private T4Parameters() { } } }
zznhgzf-t4-code-generator-clone
T4/T4WinHost/Base/T4Parameters.cs
C#
asf20
1,120
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace T4WinHost.Base { public class TemplateInfo { public string Name { get; set; } public string Description { get; set; } public string FullPath { get; set; } } }
zznhgzf-t4-code-generator-clone
T4/T4WinHost/Base/TemplateInfo.cs
C#
asf20
268
using System; using System.IO; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Text; using System.Linq; using Microsoft.VisualStudio.TextTemplating; using T4Common; using System.Runtime.Remoting.Messaging; namespace T4WinHost { //The text template transformation engine is responsible for running //the transformation process. //The host is responsible for all input and output, locating files, //and anything else related to the external environment. //------------------------------------------------------------------------- [Serializable] public class CustomCmdLineHost : ITextTemplatingSessionHost,ITextTemplatingEngineHost { //the path and file name of the text template that is being processed //--------------------------------------------------------------------- internal string TemplateFileValue; public string TemplateFile { get { return TemplateFileValue; } } //This will be the extension of the generated text output file. //The host can provide a default by setting the value of the field here. //The engine can change this value based on the optional output directive //if the user specifies it in the text template. //--------------------------------------------------------------------- private string fileExtensionValue = ".txt"; public string FileExtension { get { return fileExtensionValue; } } //This will be the encoding of the generated text output file. //The host can provide a default by setting the value of the field here. //The engine can change this value based on the optional output directive //if the user specifies it in the text template. //--------------------------------------------------------------------- private Encoding fileEncodingValue = Encoding.UTF8; public Encoding FileEncoding { get { return fileEncodingValue; } } //These are the errors that occur when the engine processes a template. //The engine passes the errors to the host when it is done processing, //and the host can decide how to display them. For example, the host //can display the errors in the UI or write them to a file. //--------------------------------------------------------------------- private CompilerErrorCollection errorsValue; public CompilerErrorCollection Errors { get { return errorsValue; } } //The host can provide standard assembly references. //The engine will use these references when compiling and //executing the generated transformation class. //-------------------------------------------------------------- //这个是你的代码中要引入的包包,这个例子中引入了 System.dll 和 本项目的 dll, //如果你不想引用,那么就得在 你的 tt 文件中引入 public IList<string> StandardAssemblyReferences { get { return new string[] { typeof(System.Uri).Assembly.Location, typeof(CustomCmdLineHost).Assembly.Location, typeof(System.Linq.Enumerable).Assembly.Location, typeof(T4Common.CodeOutputType).Assembly.Location, typeof(System.Xml.ConformanceLevel).Assembly.Location, typeof(System.Xml.Linq.LoadOptions).Assembly.Location, typeof(System.Data.Linq.ChangeAction).Assembly.Location, string.Format("{0}\\EnvDTE.dll",Environment.CurrentDirectory), typeof(CallContext).Assembly.Location }; } } //The host can provide standard imports or using statements. //The engine will add these statements to the generated //transformation class. //-------------------------------------------------------------- //这个是你的代码中要using 的命名空间,这个例子中引入了 System 和 本项目的, //如果你不想引用,那么就得在 你的 tt 文件中写 public IList<string> StandardImports { get { return new string[] { "System", "T4WinHost", "T4WinHost.Base", "System.Collections.Generic", "System.Data.Linq", "System.Data.Linq.Mapping", "System.IO", "System.Linq", "System.Reflection", "System.Text", "System.Xml.Linq", "Microsoft.VisualStudio.TextTemplating", "System.IO", "System.Collections", "EnvDTE" }; } } //The engine calls this method based on the optional include directive //if the user has specified it in the text template. //This method can be called 0, 1, or more times. //--------------------------------------------------------------------- //The included text is returned in the context parameter. //If the host searches the registry for the location of include files, //or if the host searches multiple locations by default, the host can //return the final path of the include file in the location parameter. //--------------------------------------------------------------------- public bool LoadIncludeText(string requestFileName, out string content, out string location) { content = System.String.Empty; location = System.String.Empty; //If the argument is the fully qualified path of an existing file, //then we are done. //---------------------------------------------------------------- if (File.Exists(requestFileName)) { content = File.ReadAllText(requestFileName); return true; } //This can be customized to search specific paths for the file. //This can be customized to accept paths to search as command line //arguments. //---------------------------------------------------------------- else { return false; } } //Passes in the name of a service. If you have that service, you need to //pass back a pointer to it. Otherwise, you need to pass back NULL to //indicate that you have no knowledge of that service. //-------------------------------------------------------------------- public object GetHostOption(string optionName) { object returnObject; switch (optionName) { case "CacheAssemblies": returnObject = true; break; default: returnObject = null; break; } return returnObject; } //The engine calls this method to resolve assembly references used in //the generated transformation class project and for the optional //assembly directive if the user has specified it in the text template. //This method can be called 0, 1, or more times. //--------------------------------------------------------------------- public string ResolveAssemblyReference(string assemblyReference) { //If the argument is the fully qualified path of an existing file, //then we are done. (This does not do any work.) //---------------------------------------------------------------- if (File.Exists(assemblyReference)) { return assemblyReference; } //Maybe the assembly is in the same folder as the text template that //called the directive. //---------------------------------------------------------------- string candidate = Path.Combine(Path.GetDirectoryName(this.TemplateFile), assemblyReference); if (File.Exists(candidate)) { return candidate; } //This can be customized to search specific paths for the file //or to search the GAC. //---------------------------------------------------------------- //This can be customized to accept paths to search as command line //arguments. //---------------------------------------------------------------- //If we cannot do better, return the original file name. return ""; } //The engine calls this method based on the directives the user has //specified in the text template. //This method can be called 0, 1, or more times. //--------------------------------------------------------------------- public Type ResolveDirectiveProcessor(string processorName) { //This host will not resolve any specific processors. //Check the processor name, and if it is the name of a processor the //host wants to support, return the type of the processor. //--------------------------------------------------------------------- if (string.Compare(processorName, "XYZ", StringComparison.OrdinalIgnoreCase) == 0) { //return typeof(); } //This can be customized to search specific paths for the file //or to search the GAC //If the directive processor cannot be found, throw an error. throw new Exception("Directive Processor not found"); } //A directive processor can call this method if a file name does not //have a path. //The host can attempt to provide path information by searching //specific paths for the file and returning the file and path if found. //This method can be called 0, 1, or more times. //--------------------------------------------------------------------- public string ResolvePath(string fileName) { if (fileName == null) { throw new ArgumentNullException("the file name cannot be null"); } //If the argument is the fully qualified path of an existing file, //then we are done //---------------------------------------------------------------- if (File.Exists(fileName)) { return fileName; } //Maybe the file is in the same folder as the text template that //called the directive. //---------------------------------------------------------------- string candidate = Path.Combine(Path.GetDirectoryName(this.TemplateFile), fileName); if (File.Exists(candidate)) { return candidate; } //Look more places. //---------------------------------------------------------------- //More code can go here... //If we cannot do better, return the original file name. return fileName; } //If a call to a directive in a text template does not provide a value //for a required parameter, the directive processor can try to get it //from the host by calling this method. //This method can be called 0, 1, or more times. //--------------------------------------------------------------------- public string ResolveParameterValue(string directiveId, string processorName, string parameterName) { if (directiveId == null) { throw new ArgumentNullException("the directiveId cannot be null"); } if (processorName == null) { throw new ArgumentNullException("the processorName cannot be null"); } if (parameterName == null) { throw new ArgumentNullException("the parameterName cannot be null"); } //Code to provide "hard-coded" parameter values goes here. //This code depends on the directive processors this host will interact with. //If we cannot do better, return the empty string. return String.Empty; } //The engine calls this method to change the extension of the //generated text output file based on the optional output directive //if the user specifies it in the text template. //--------------------------------------------------------------------- public void SetFileExtension(string extension) { //The parameter extension has a '.' in front of it already. //-------------------------------------------------------- fileExtensionValue = extension; } //The engine calls this method to change the encoding of the //generated text output file based on the optional output directive //if the user specifies it in the text template. //---------------------------------------------------------------------- public void SetOutputEncoding(System.Text.Encoding encoding, bool fromOutputDirective) { fileEncodingValue = encoding; } //The engine calls this method when it is done processing a text //template to pass any errors that occurred to the host. //The host can decide how to display them. //--------------------------------------------------------------------- public void LogErrors(CompilerErrorCollection errors) { errorsValue = errors; } //This is the application domain that is used to compile and run //the generated transformation class to create the generated text output. //---------------------------------------------------------------------- public AppDomain ProvideTemplatingAppDomain(string content) { //This host will provide a new application domain each time the //engine processes a text template. //------------------------------------------------------------- return AppDomain.CreateDomain("Generation App Domain"); //This could be changed to return the current appdomain, but new //assemblies are loaded into this AppDomain on a regular basis. //If the AppDomain lasts too long, it will grow indefintely, //which might be regarded as a leak. //This could be customized to cache the application domain for //a certain number of text template generations (for example, 10). //This could be customized based on the contents of the text //template, which are provided as a parameter for that purpose. } //public CustomCmdLineHost() //{ // this.LoadIncludeText( [0] = @"D:\Project Test\CustomHost\CustomHost\bin\Debug\CustomHost.exe"; //} public ITextTemplatingSession CreateSession() { return Session; } public ITextTemplatingSession Session { get; set; } } }
zznhgzf-t4-code-generator-clone
T4/T4WinHost/CustomCmdLineHost.cs
C#
asf20
13,302