code
stringlengths
3
1.18M
language
stringclasses
1 value
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.beust.android.translate; import android.app.AlertDialog; import android.content.Context; import android.webkit.WebView; /** * Display a simple about dialog. */ public class AboutDialog extends AlertDialog { protected AboutDialog(Context context) { super(context); setContentView(R.layout.about_dialog); setTitle(R.string.about_title); setCancelable(true); WebView webView = (WebView) findViewById(R.id.webview); webView.loadData("Written by C&eacute;dric Beust (<a href=\"mailto:cedric@beust.com\">cedric@beust.com)</a>", "text/html", "utf-8"); } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.beust.android.translate; import android.app.ListActivity; import android.content.SharedPreferences.Editor; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.SimpleAdapter; import android.widget.AdapterView.OnItemClickListener; import java.util.List; import java.util.Map; /** * This activity displays the history of past translations. * * @author Cedric Beust * @author Daniel Rall */ public class HistoryActivity extends ListActivity implements OnItemClickListener { private SimpleAdapter mAdapter; private List<Map<String, String>> mListData; private History mHistory; private static final String INPUT = "input"; private static final String OUTPUT = "output"; private static final String FROM = "from"; private static final String TO = "to"; private static final String FROM_SHORT_NAME = "from-short-name"; private static final String TO_SHORT_NAME = "to-short-name"; // These constants are used to bind the adapter to the list view private static final String[] COLUMN_NAMES = { INPUT, OUTPUT, FROM, TO }; private static final int[] VIEW_IDS = { R.id.input, R.id.output, R.id.from, R.id.to }; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.history_activity); mHistory = new History(TranslateActivity.getPrefs(this)); initializeAdapter(mHistory.getHistoryRecordsMostRecentFirst()); getListView().setEmptyView(findViewById(R.id.empty)); } private void initializeAdapter(List<HistoryRecord> historyRecords) { mListData = Lists.newArrayList(); for (HistoryRecord hr : historyRecords) { Map<String, String> data = Maps.newHashMap(); // Values that are bound to views data.put(INPUT, hr.input); data.put(OUTPUT, hr.output); data.put(FROM, hr.from.name().toLowerCase()); data.put(TO, hr.to.name().toLowerCase()); // Extra values we keep around for convenience data.put(FROM_SHORT_NAME, hr.from.getShortName()); data.put(TO_SHORT_NAME, hr.to.getShortName()); mListData.add(data); } mAdapter = new SimpleAdapter(this, mListData, R.layout.history_record, COLUMN_NAMES, VIEW_IDS); getListView().setAdapter(mAdapter); getListView().setOnItemClickListener(this); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.history_activity_menu, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) { case R.id.most_recent: initializeAdapter(mHistory.getHistoryRecordsMostRecentFirst()); break; case R.id.languages: initializeAdapter(mHistory.getHistoryRecordsByLanguages()); break; case R.id.clear_history: mHistory.clear(this); initializeAdapter(mHistory.getHistoryRecordsByLanguages()); break; } return true; } public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Map<String, String> data = (Map<String, String>) parent.getItemAtPosition(position); Editor edit = TranslateActivity.getPrefs(this).edit(); TranslateActivity.savePreferences(edit, data.get(FROM_SHORT_NAME), data.get(TO_SHORT_NAME), data.get(INPUT), data.get(OUTPUT)); finish(); } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.divideandconquer; import android.content.Context; import android.content.res.Resources; import android.graphics.*; import android.graphics.drawable.GradientDrawable; import android.os.Debug; import android.os.SystemClock; import android.util.AttributeSet; import android.util.TypedValue; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import java.util.List; import java.util.ArrayList; /** * Handles the visual display and touch input for the game. */ public class DivideAndConquerView extends View implements BallEngine.BallEventCallBack { static final int BORDER_WIDTH = 10; // this needs to match size of ball drawable static final float BALL_RADIUS = 5f; static final float BALL_SPEED = 80f; // if true, will profile the drawing code during each animating line and export // the result to a file named 'BallsDrawing.trace' on the sd card // this file can be pulled off and profiled with traceview // $ adb pull /sdcard/BallsDrawing.trace . // traceview BallsDrawing.trace private static final boolean PROFILE_DRAWING = false; private boolean mDrawingProfilingStarted = false; private final Paint mPaint; private BallEngine mEngine; private Mode mMode = Mode.Paused; private BallEngineCallBack mCallback; // interface for starting a line private DirectionPoint mDirectionPoint = null; private Bitmap mBallBitmap; private float mBallBitmapRadius; private final Bitmap mExplosion1; private final Bitmap mExplosion2; private final Bitmap mExplosion3; /** * Callback notifying of events related to the ball engine. */ static interface BallEngineCallBack { /** * The engine has its dimensions and is ready to go. * @param ballEngine The ball engine. */ void onEngineReady(BallEngine ballEngine); /** * A ball has hit a moving line. * @param ballEngine The engine. * @param x The x coordinate of the ball. * @param y The y coordinate of the ball. */ void onBallHitsMovingLine(BallEngine ballEngine, float x, float y); /** * A line made it to the edges of its region, splitting off a new region. * @param ballEngine The engine. */ void onAreaChange(BallEngine ballEngine); } /** * @return The ball engine associated with the game. */ public BallEngine getEngine() { return mEngine; } /** * Keeps track of the mode of this view. */ enum Mode { /** * The balls are bouncing around. */ Bouncing, /** * The animation has stopped and the balls won't move around. The user * may not unpause it; this is used to temporarily stop games between * levels, or when the game is over and the activity places a dialog up. */ Paused, /** * Same as {@link #Paused}, but paints the word 'touch to unpause' on * the screen, so the user knows he/she can unpause the game. */ PausedByUser } public DivideAndConquerView(Context context, AttributeSet attrs) { super(context, attrs); mPaint = new Paint(); mPaint.setAntiAlias(true); mPaint.setStrokeWidth(2); mPaint.setColor(Color.BLACK); // so we can see the back key setFocusableInTouchMode(true); drawBackgroundGradient(); mBallBitmap = BitmapFactory.decodeResource( context.getResources(), R.drawable.ball); mBallBitmapRadius = ((float) mBallBitmap.getWidth()) / 2f; mExplosion1 = BitmapFactory.decodeResource( context.getResources(), R.drawable.explosion1); mExplosion2 = BitmapFactory.decodeResource( context.getResources(), R.drawable.explosion2); mExplosion3 = BitmapFactory.decodeResource( context.getResources(), R.drawable.explosion3); } final GradientDrawable mBackgroundGradient = new GradientDrawable( GradientDrawable.Orientation.TOP_BOTTOM, new int[]{Color.RED, Color.YELLOW}); void drawBackgroundGradient() { setBackgroundDrawable(mBackgroundGradient); } /** * Set the callback that will be notified of events related to the ball * engine. * @param callback The callback. */ public void setCallback(BallEngineCallBack callback) { mCallback = callback; } @Override protected void onSizeChanged(int i, int i1, int i2, int i3) { super.onSizeChanged(i, i1, i2, i3); // this should only happen once when the activity is first launched. // we could be smarter about saving / restoring across activity // lifecycles, but for now, this is good enough to handle in game play, // and most cases of navigating away with the home key and coming back. mEngine = new BallEngine( BORDER_WIDTH, getWidth() - BORDER_WIDTH, BORDER_WIDTH, getHeight() - BORDER_WIDTH, BALL_SPEED, BALL_RADIUS); mEngine.setCallBack(this); mCallback.onEngineReady(mEngine); } /** * @return the current mode of operation. */ public Mode getMode() { return mMode; } /** * Set the mode of operation. * @param mode The mode. */ public void setMode(Mode mode) { mMode = mode; if (mMode == Mode.Bouncing && mEngine != null) { // when starting up again, the engine needs to know what 'now' is. final long now = SystemClock.elapsedRealtime(); mEngine.setNow(now); mExplosions.clear(); invalidate(); } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { // the first time the user hits back while the balls are moving, // we'll pause the game. but if they hit back again, we'll do the usual // (exit the activity) if (keyCode == KeyEvent.KEYCODE_BACK && mMode == Mode.Bouncing) { setMode(Mode.PausedByUser); return true; } return super.onKeyDown(keyCode, event); } @Override public boolean onTouchEvent(MotionEvent motionEvent) { if (mMode == Mode.PausedByUser) { // touching unpauses when the game was paused by the user. setMode(Mode.Bouncing); return true; } else if (mMode == Mode.Paused) { return false; } final float x = motionEvent.getX(); final float y = motionEvent.getY(); switch(motionEvent.getAction()) { case MotionEvent.ACTION_DOWN: if (mEngine.canStartLineAt(x, y)) { mDirectionPoint = new DirectionPoint(x, y); } return true; case MotionEvent.ACTION_MOVE: if (mDirectionPoint != null) { mDirectionPoint.updateEndPoint(x, y); } else if (mEngine.canStartLineAt(x, y)) { mDirectionPoint = new DirectionPoint(x, y); } return true; case MotionEvent.ACTION_UP: if (mDirectionPoint != null) { switch (mDirectionPoint.getDirection()) { case Unknown: // do nothing break; case Horizonal: mEngine.startHorizontalLine(SystemClock.elapsedRealtime(), mDirectionPoint.getX(), mDirectionPoint.getY()); if (PROFILE_DRAWING) { if (!mDrawingProfilingStarted) { Debug.startMethodTracing("BallsDrawing"); mDrawingProfilingStarted = true; } } break; case Vertical: mEngine.startVerticalLine(SystemClock.elapsedRealtime(), mDirectionPoint.getX(), mDirectionPoint.getY()); if (PROFILE_DRAWING) { if (!mDrawingProfilingStarted) { Debug.startMethodTracing("BallsDrawing"); mDrawingProfilingStarted = true; } } break; } } mDirectionPoint = null; return true; case MotionEvent.ACTION_CANCEL: mDirectionPoint = null; return true; } return false; } /** {@inheritDoc} */ public void onBallHitsBall(Ball ballA, Ball ballB) { } /** {@inheritDoc} */ public void onBallHitsLine(long when, Ball ball, AnimatingLine animatingLine) { mCallback.onBallHitsMovingLine(mEngine, ball.getX(), ball.getY()); mExplosions.add( new Explosion( when, ball.getX(), ball.getY(), mExplosion1, mExplosion2, mExplosion3)); } static class Explosion { private long mLastUpdate; private long mProgress = 0; private final float mX; private final float mY; private final Bitmap mExplosion1; private final Bitmap mExplosion2; private final Bitmap mExplosion3; private final float mRadius; Explosion(long mLastUpdate, float mX, float mY, Bitmap explosion1, Bitmap explosion2, Bitmap explosion3) { this.mLastUpdate = mLastUpdate; this.mX = mX; this.mY = mY; this.mExplosion1 = explosion1; this.mExplosion2 = explosion2; this.mExplosion3 = explosion3; mRadius = ((float) mExplosion1.getWidth()) / 2f; } public void update(long now) { mProgress += (now - mLastUpdate); mLastUpdate = now; } public void setNow(long now) { mLastUpdate = now; } public void draw(Canvas canvas, Paint paint) { if (mProgress < 80L) { canvas.drawBitmap(mExplosion1, mX - mRadius, mY - mRadius, paint); } else if (mProgress < 160L) { canvas.drawBitmap(mExplosion2, mX - mRadius, mY - mRadius, paint); } else if (mProgress < 400L) { canvas.drawBitmap(mExplosion3, mX - mRadius, mY - mRadius, paint); } } public boolean done() { return mProgress > 700L; } } private ArrayList<Explosion> mExplosions = new ArrayList<Explosion>(); @Override protected void onDraw(Canvas canvas) { boolean newRegion = false; if (mMode == Mode.Bouncing) { // handle the ball engine final long now = SystemClock.elapsedRealtime(); newRegion = mEngine.update(now); if (newRegion) { mCallback.onAreaChange(mEngine); // reset back to full alpha bg color drawBackgroundGradient(); } if (PROFILE_DRAWING) { if (newRegion && mDrawingProfilingStarted) { mDrawingProfilingStarted = false; Debug.stopMethodTracing(); } } // the X-plosions for (int i = 0; i < mExplosions.size(); i++) { final Explosion explosion = mExplosions.get(i); explosion.update(now); } } for (int i = 0; i < mEngine.getRegions().size(); i++) { BallRegion region = mEngine.getRegions().get(i); drawRegion(canvas, region); } for (int i = 0; i < mExplosions.size(); i++) { final Explosion explosion = mExplosions.get(i); explosion.draw(canvas, mPaint); // TODO prune explosions that are done } if (mMode == Mode.PausedByUser) { drawPausedText(canvas); } else if (mMode == Mode.Bouncing) { // keep em' bouncing! invalidate(); } } /** * Pain the text instructing the user how to unpause the game. */ private void drawPausedText(Canvas canvas) { mPaint.setColor(Color.BLACK); mPaint.setAntiAlias(true); mPaint.setTextSize( TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_SP, 20, getResources().getDisplayMetrics())); final String unpauseInstructions = getContext().getString(R.string.unpause_instructions); canvas.drawText(unpauseInstructions, getWidth() / 5, getHeight() / 2, mPaint); mPaint.setAntiAlias(false); } private RectF mRectF = new RectF(); /** * Draw a ball region. */ private void drawRegion(Canvas canvas, BallRegion region) { // draw fill rect to offset against background mPaint.setColor(Color.LTGRAY); mRectF.set(region.getLeft(), region.getTop(), region.getRight(), region.getBottom()); canvas.drawRect(mRectF, mPaint); //draw an outline mPaint.setStyle(Paint.Style.STROKE); mPaint.setColor(Color.WHITE); canvas.drawRect(mRectF, mPaint); mPaint.setStyle(Paint.Style.FILL); // restore style // draw each ball for (Ball ball : region.getBalls()) { // canvas.drawCircle(ball.getX(), ball.getY(), BALL_RADIUS, mPaint); canvas.drawBitmap( mBallBitmap, ball.getX() - mBallBitmapRadius, ball.getY() - mBallBitmapRadius, mPaint); } // draw the animating line final AnimatingLine al = region.getAnimatingLine(); if (al != null) { drawAnimatingLine(canvas, al); } } private static int scaleToBlack(int component, float percentage) { // return (int) ((1f - percentage*0.4f) * component); return (int) (percentage * 0.6f * (0xFF - component) + component); } /** * Draw an animating line. */ private void drawAnimatingLine(Canvas canvas, AnimatingLine al) { final float perc = al.getPercentageDone(); final int color = Color.RED; mPaint.setColor(Color.argb( 0xFF, scaleToBlack(Color.red(color), perc), scaleToBlack(Color.green(color), perc), scaleToBlack(Color.blue(color), perc) )); switch (al.getDirection()) { case Horizontal: canvas.drawLine( al.getStart(), al.getPerpAxisOffset(), al.getEnd(), al.getPerpAxisOffset(), mPaint); break; case Vertical: canvas.drawLine( al.getPerpAxisOffset(), al.getStart(), al.getPerpAxisOffset(), al.getEnd(), mPaint); break; } } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.divideandconquer; /** * A 2d shape has left, right, top and bottom dimensions. * */ public abstract class Shape2d { public abstract float getLeft(); public abstract float getRight(); public abstract float getTop(); public abstract float getBottom(); /** * @param other Another 2d shape * @return Whether this shape is intersecting with the other. */ public boolean isIntersecting(Shape2d other) { return getLeft() <= other.getRight() && getRight() >= other.getLeft() && getTop() <= other.getBottom() && getBottom() >= other.getTop(); } /** * @param x An x coordinate * @param y A y coordinate * @return Whether the point is within this shape */ public boolean isPointWithin(float x, float y) { return (x > getLeft() && x < getRight() && y > getTop() && y < getBottom()); } public float getArea() { return getHeight() * getWidth(); } public float getHeight() { return getBottom() - getTop(); } public float getWidth () { return getRight() - getLeft(); } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.divideandconquer; /** * Used by dialogs to tell the activity the user wants a new game. */ public interface NewGameCallback { /** * The user wants to start a new game. */ void onNewGame(); }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.divideandconquer; /** * Either vertical or horizontal. Used by animating lines and * ball regions. */ public enum Direction { Vertical, Horizontal }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.divideandconquer; import android.app.Activity; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.os.SystemClock; import android.os.Vibrator; import android.preference.PreferenceManager; import android.view.Menu; import android.view.MenuItem; import android.view.Window; import android.view.Gravity; import android.widget.TextView; import android.widget.Toast; import android.graphics.Color; import java.util.Stack; /** * The activity for the game. Listens for callbacks from the game engine, and * response appropriately, such as bringing up a 'game over' dialog when a ball * hits a moving line and there is only one life left. */ public class DivideAndConquerActivity extends Activity implements DivideAndConquerView.BallEngineCallBack, NewGameCallback, DialogInterface.OnCancelListener { private static final int NEW_GAME_NUM_BALLS = 1; private static final double LEVEL_UP_THRESHOLD = 0.8; private static final int COLLISION_VIBRATE_MILLIS = 50; private boolean mVibrateOn; private int mNumBalls = NEW_GAME_NUM_BALLS; private DivideAndConquerView mBallsView; private static final int WELCOME_DIALOG = 20; private static final int GAME_OVER_DIALOG = 21; private WelcomeDialog mWelcomeDialog; private GameOverDialog mGameOverDialog; private TextView mLivesLeft; private TextView mPercentContained; private int mNumLives; private Vibrator mVibrator; private TextView mLevelInfo; private int mNumLivesStart = 5; private Toast mCurrentToast; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Turn off the title bar requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.main); mBallsView = (DivideAndConquerView) findViewById(R.id.ballsView); mBallsView.setCallback(this); mPercentContained = (TextView) findViewById(R.id.percentContained); mLevelInfo = (TextView) findViewById(R.id.levelInfo); mLivesLeft = (TextView) findViewById(R.id.livesLeft); // we'll vibrate when the ball hits the moving line mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); } /** {@inheritDoc} */ public void onEngineReady(BallEngine ballEngine) { // display 10 balls bouncing around for visual effect ballEngine.reset(SystemClock.elapsedRealtime(), 10); mBallsView.setMode(DivideAndConquerView.Mode.Bouncing); // show the welcome dialog showDialog(WELCOME_DIALOG); } @Override protected Dialog onCreateDialog(int id) { if (id == WELCOME_DIALOG) { mWelcomeDialog = new WelcomeDialog(this, this); mWelcomeDialog.setOnCancelListener(this); return mWelcomeDialog; } else if (id == GAME_OVER_DIALOG) { mGameOverDialog = new GameOverDialog(this, this); mGameOverDialog.setOnCancelListener(this); return mGameOverDialog; } return null; } @Override protected void onPause() { super.onPause(); mBallsView.setMode(DivideAndConquerView.Mode.PausedByUser); } @Override protected void onResume() { super.onResume(); mVibrateOn = PreferenceManager.getDefaultSharedPreferences(this) .getBoolean(Preferences.KEY_VIBRATE, true); mNumLivesStart = Preferences.getCurrentDifficulty(this).getLivesToStart(); } private static final int MENU_NEW_GAME = Menu.FIRST; private static final int MENU_SETTINGS = Menu.FIRST + 1; @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); menu.add(0, MENU_NEW_GAME, MENU_NEW_GAME, "New Game"); menu.add(0, MENU_SETTINGS, MENU_SETTINGS, "Settings"); return true; } /** * We pause the game while the menu is open; this remembers what it was * so we can restore when the menu closes */ Stack<DivideAndConquerView.Mode> mRestoreMode = new Stack<DivideAndConquerView.Mode>(); @Override public boolean onMenuOpened(int featureId, Menu menu) { saveMode(); mBallsView.setMode(DivideAndConquerView.Mode.Paused); return super.onMenuOpened(featureId, menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { super.onOptionsItemSelected(item); switch (item.getItemId()) { case MENU_NEW_GAME: cancelToasts(); onNewGame(); break; case MENU_SETTINGS: final Intent intent = new Intent(); intent.setClass(this, Preferences.class); startActivity(intent); break; } mRestoreMode.pop(); // don't want to restore when an action was taken return true; } @Override public void onOptionsMenuClosed(Menu menu) { super.onOptionsMenuClosed(menu); restoreMode(); } private void saveMode() { // don't want to restore to a state where user can't resume game. final DivideAndConquerView.Mode mode = mBallsView.getMode(); final DivideAndConquerView.Mode toRestore = (mode == DivideAndConquerView.Mode.Paused) ? DivideAndConquerView.Mode.PausedByUser : mode; mRestoreMode.push(toRestore); } private void restoreMode() { if (!mRestoreMode.isEmpty()) { mBallsView.setMode(mRestoreMode.pop()); } } /** {@inheritDoc} */ public void onBallHitsMovingLine(final BallEngine ballEngine, float x, float y) { if (--mNumLives == 0) { saveMode(); mBallsView.setMode(DivideAndConquerView.Mode.Paused); // vibrate three times if (mVibrateOn) { mVibrator.vibrate( new long[]{0l, COLLISION_VIBRATE_MILLIS, 50l, COLLISION_VIBRATE_MILLIS, 50l, COLLISION_VIBRATE_MILLIS}, -1); } showDialog(GAME_OVER_DIALOG); } else { if (mVibrateOn) { mVibrator.vibrate(COLLISION_VIBRATE_MILLIS); } updateLivesDisplay(mNumLives); if (mNumLives <= 1) { mBallsView.postDelayed(mOneLifeToastRunnable, 700); } else { mBallsView.postDelayed(mLivesBlinkRedRunnable, 700); } } } private Runnable mOneLifeToastRunnable = new Runnable() { public void run() { showToast("1 life left!"); } }; private Runnable mLivesBlinkRedRunnable = new Runnable() { public void run() { mLivesLeft.setTextColor(Color.RED); mLivesLeft.postDelayed(mLivesTextWhiteRunnable, 2000); } }; /** {@inheritDoc} */ public void onAreaChange(final BallEngine ballEngine) { final float percentageFilled = ballEngine.getPercentageFilled(); updatePercentDisplay(percentageFilled); if (percentageFilled > LEVEL_UP_THRESHOLD) { levelUp(ballEngine); } } /** * Go to the next level * @param ballEngine The ball engine. */ private void levelUp(final BallEngine ballEngine) { mNumBalls++; updatePercentDisplay(0); updateLevelDisplay(mNumBalls); ballEngine.reset(SystemClock.elapsedRealtime(), mNumBalls); mBallsView.setMode(DivideAndConquerView.Mode.Bouncing); if (mNumBalls % 4 == 0) { mNumLives++; updateLivesDisplay(mNumLives); showToast("bonus life!"); } if (mNumBalls == 10) { showToast("Level 10? You ROCK!"); } else if (mNumBalls == 15) { showToast("BALLS TO THE WALL!"); } } private Runnable mLivesTextWhiteRunnable = new Runnable() { public void run() { mLivesLeft.setTextColor(Color.WHITE); } }; private void showToast(String text) { cancelToasts(); mCurrentToast = Toast.makeText(this, text, Toast.LENGTH_SHORT); mCurrentToast.show(); } private void cancelToasts() { if (mCurrentToast != null) { mCurrentToast.cancel(); mCurrentToast = null; } } /** * Update the header that displays how much of the space has been contained. * @param amountFilled The fraction, between 0 and 1, that is filled. */ private void updatePercentDisplay(float amountFilled) { final int prettyPercent = (int) (amountFilled *100); mPercentContained.setText( getString(R.string.percent_contained, prettyPercent)); } /** {@inheritDoc} */ public void onNewGame() { mNumBalls = NEW_GAME_NUM_BALLS; mNumLives = mNumLivesStart; updatePercentDisplay(0); updateLivesDisplay(mNumLives); updateLevelDisplay(mNumBalls); mBallsView.getEngine().reset(SystemClock.elapsedRealtime(), mNumBalls); mBallsView.setMode(DivideAndConquerView.Mode.Bouncing); } /** * Update the header displaying the current level */ private void updateLevelDisplay(int numBalls) { mLevelInfo.setText(getString(R.string.level, numBalls)); } /** * Update the display showing the number of lives left. * @param numLives The number of lives left. */ void updateLivesDisplay(int numLives) { String text = (numLives == 1) ? getString(R.string.one_life_left) : getString(R.string.lives_left, numLives); mLivesLeft.setText(text); } /** {@inheritDoc} */ public void onCancel(DialogInterface dialog) { if (dialog == mWelcomeDialog || dialog == mGameOverDialog) { // user hit back, they're done finish(); } } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.divideandconquer; import android.util.Log; import android.content.Context; import android.widget.Toast; import java.util.List; import java.util.ArrayList; import java.util.Iterator; /** * Keeps track of the current state of balls bouncing around within a a set of * regions. * * Note: 'now' is the elapsed time in milliseconds since some consistent point in time. * As long as the reference point stays consistent, the engine will be happy, though * typically this is {@link android.os.SystemClock#elapsedRealtime()} */ public class BallEngine { static public interface BallEventCallBack { void onBallHitsBall(Ball ballA, Ball ballB); void onBallHitsLine(long when, Ball ball, AnimatingLine animatingLine); } private final float mMinX; private final float mMaxX; private final float mMinY; private final float mMaxY; private float mBallSpeed; private float mBallRadius; private BallEventCallBack mCallBack; /** * Holds onto new regions during a split */ private List<BallRegion> mNewRegions = new ArrayList<BallRegion>(8); private List<BallRegion> mRegions = new ArrayList<BallRegion>(8); public BallEngine(float minX, float maxX, float minY, float maxY, float ballSpeed, float ballRadius) { mMinX = minX; mMaxX = maxX; mMinY = minY; mMaxY = maxY; mBallSpeed = ballSpeed; mBallRadius = ballRadius; } public void setCallBack(BallEventCallBack mCallBack) { this.mCallBack = mCallBack; } /** * Update the notion of 'now' in milliseconds. This can be usefull * when unpausing for instance. * @param now Milliseconds since some consistent point in time. */ public void setNow(long now) { for (int i = 0; i < mRegions.size(); i++) { final BallRegion region = mRegions.get(i); region.setNow(now); } } /** * Rest the engine back to a single region with a certain number of balls * that will be placed randomly and sent in random directions. * @param now milliseconds since some consistent point in time. * @param numBalls */ public void reset(long now, int numBalls) { mRegions.clear(); ArrayList<Ball> balls = new ArrayList<Ball>(numBalls); for (int i = 0; i < numBalls; i++) { Ball ball = new Ball.Builder() .setNow(now) .setPixelsPerSecond(mBallSpeed) .setAngle(Math.random() * 2 * Math.PI) .setX((float) Math.random() * (mMaxX - mMinX) + mMinX) .setY((float) Math.random() * (mMaxY - mMinY) + mMinY) .setRadiusPixels(mBallRadius) .create(); balls.add(ball); } BallRegion region = new BallRegion(now, mMinX, mMaxX, mMinY, mMaxY, balls); region.setCallBack(mCallBack); mRegions.add(region); } public List<BallRegion> getRegions() { return mRegions; } public float getPercentageFilled() { float total = 0f; for (int i = 0; i < mRegions.size(); i++) { BallRegion region = mRegions.get(i); total += region.getArea(); Log.d("Balls", "total now " + total); } return 1f - (total / getArea()); } /** * @return the area in the region in pixel*pixel */ public float getArea() { return (mMaxX - mMinX) * (mMaxY - mMinY); } /** * Can any of the regions within start a line at this point? * @param x The x coordinate. * @param y The y coordinate * @return Whether a region can start a line. */ public boolean canStartLineAt(float x, float y) { for (BallRegion region : mRegions) { if (region.canStartLineAt(x, y)) { return true; } } return false; } /** * Start a horizontal line at a certain point. * @throws IllegalArgumentException if there is no region that can start a * line at the point. */ public void startHorizontalLine(long now, float x, float y) { for (BallRegion region : mRegions) { if (region.canStartLineAt(x, y)) { region.startHorizontalLine(now, x, y); return; } } throw new IllegalArgumentException("no region can start a new line at " + x + ", " + y + "."); } /** * Start a vertical line at a certain point. * @throws IllegalArgumentException if there is no region that can start a * line at the point. */ public void startVerticalLine(long now, float x, float y) { for (BallRegion region : mRegions) { if (region.canStartLineAt(x, y)) { region.startVerticalLine(now, x, y); return; } } throw new IllegalArgumentException("no region can start a new line at " + x + ", " + y + "."); } /** * @param now The latest notion of 'now' * @return whether any new regions were added by the update. */ public boolean update(long now) { boolean regionChange = false; Iterator<BallRegion> it = mRegions.iterator(); while (it.hasNext()) { final BallRegion region = it.next(); final BallRegion newRegion = region.update(now); if (newRegion != null) { regionChange = true; if (!newRegion.getBalls().isEmpty()) { mNewRegions.add(newRegion); } // current region may not have any balls left if (region.getBalls().isEmpty()) { it.remove(); } } else if (region.consumeDoneShrinking()) { regionChange = true; } } mRegions.addAll(mNewRegions); mNewRegions.clear(); return regionChange; } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.divideandconquer; /** * Keeps the state for the line that extends in two directions until it hits its boundaries. This is triggered * by the user gesture in a horizontal or vertical direction. */ public class AnimatingLine extends Shape2d { private Direction mDirection; // for vertical lines, the y offset // for horizontal, the x offset float mPerpAxisOffset; float mStart; float mEnd; float mMin; float mMax; private long mLastUpdate = 0; private float mPixelsPerSecond = 101.0f; /** * @param direction The direction of the line * @param now What 'now' is * @param axisStart Where on the perpindicular axis the line is extending from * @param start The point the line is extending from on the parallel axis * @param min The lower bound for the line (i.e the left most point) * @param max The upper bound for the line (i.e the right most point) */ public AnimatingLine( Direction direction, long now, float axisStart, float start, float min, float max) { mDirection = direction; mLastUpdate = now; mPerpAxisOffset = axisStart; mStart = mEnd = start; mMin = min; mMax = max; } public Direction getDirection() { return mDirection; } public float getPerpAxisOffset() { return mPerpAxisOffset; } public float getStart() { return mStart; } public float getEnd() { return mEnd; } public float getMin() { return mMin; } public float getMax() { return mMax; } public float getLeft() { return mDirection == Direction.Horizontal ? mStart : mPerpAxisOffset; } public float getRight() { return mDirection == Direction.Horizontal ? mEnd : mPerpAxisOffset; } public float getTop() { return mDirection == Direction.Vertical ? mStart : mPerpAxisOffset; } public float getBottom() { return mDirection == Direction.Vertical ? mEnd : mPerpAxisOffset; } public float getPercentageDone() { return (mEnd - mStart) / (mMax - mMin); } /** * Extend the line according to the animation. * @return whether the line has reached its end. */ public boolean update(long time) { if (time == mLastUpdate) return false; float delta = (time - mLastUpdate) * mPixelsPerSecond; delta = delta / 1000; mLastUpdate = time; mStart -= delta; mEnd += delta; if (mStart < mMin) mStart = mMin; if (mEnd > mMax) mEnd = mMax; return mStart == mMin && mEnd == mMax; } public void setNow(long now) { mLastUpdate = now; } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.divideandconquer; import java.util.List; import java.util.ArrayList; import java.util.Iterator; import java.lang.ref.WeakReference; /** * A ball region is a rectangular region that contains bouncing * balls, and possibly one animating line. In its {@link #update(long)} method, * it will update all of its balls, the moving line. It detects collisions * between the balls and the moving line, and when the line is complete, handles * splitting off a new region. */ public class BallRegion extends Shape2d { private float mLeft; private float mRight; private float mTop; private float mBottom; private List<Ball> mBalls; private AnimatingLine mAnimatingLine; private boolean mShrinkingToFit = false; private long mLastUpdate = 0; private static final float PIXELS_PER_SECOND = 25.0f; private static final float SHRINK_TO_FIT_AREA_THRESH = 10000.0f; private static final float SHRINK_TO_FIT_AREA_THRESH_ONE_BALL = 20000.0f; private static final float SHRINK_TO_FIT_AREA = 1000f; private static final float MIN_EDGE = 30f; private boolean mDoneShrinking = false; private WeakReference<BallEngine.BallEventCallBack> mCallBack; /* * @param left The minimum x component * @param right The maximum x component * @param top The minimum y component * @param bottom The maximum y component * @param balls the balls of the region */ public BallRegion(long now, float left, float right, float top, float bottom, ArrayList<Ball> balls) { mLastUpdate = now; mLeft = left; mRight = right; mTop = top; mBottom = bottom; mBalls = balls; final int numBalls = mBalls.size(); for (int i = 0; i < numBalls; i++) { final Ball ball = mBalls.get(i); ball.setRegion(this); } checkShrinkToFit(); } public void setCallBack(BallEngine.BallEventCallBack callBack) { this.mCallBack = new WeakReference<BallEngine.BallEventCallBack>(callBack); } private void checkShrinkToFit() { final float area = getArea(); if (area < SHRINK_TO_FIT_AREA_THRESH) { mShrinkingToFit = true; } else if (area < SHRINK_TO_FIT_AREA_THRESH_ONE_BALL && mBalls.size() == 1) { mShrinkingToFit = true; } } public float getLeft() { return mLeft; } public float getRight() { return mRight; } public float getTop() { return mTop; } public float getBottom() { return mBottom; } public List<Ball> getBalls() { return mBalls; } public AnimatingLine getAnimatingLine() { return mAnimatingLine; } public boolean consumeDoneShrinking() { if (mDoneShrinking) { mDoneShrinking = false; return true; } return false; } public void setNow(long now) { mLastUpdate = now; // update the balls final int numBalls = mBalls.size(); for (int i = 0; i < numBalls; i++) { final Ball ball = mBalls.get(i); ball.setNow(now); } if (mAnimatingLine != null) { mAnimatingLine.setNow(now); } } /** * Update the balls an (if it exists) the animating line in this region. * @param now in millis * @return A new region if a split has occured because the animating line * finished. */ public BallRegion update(long now) { // update the animating line final boolean newRegion = (mAnimatingLine != null && mAnimatingLine.update(now)); final int numBalls = mBalls.size(); // move balls, check for collision with animating line for (int i = 0; i < numBalls; i++) { final Ball ball = mBalls.get(i); ball.update(now); if (mAnimatingLine != null && ball.isIntersecting(mAnimatingLine)) { mAnimatingLine = null; if (mCallBack != null) mCallBack.get().onBallHitsLine(now, ball, mAnimatingLine); } } // update ball to ball collisions for (int i = 0; i < numBalls; i++) { final Ball ball = mBalls.get(i); for (int j = i + 1; j < numBalls; j++) { Ball other = mBalls.get(j); if (ball.isCircleOverlapping(other)) { Ball.adjustForCollision(ball, other); break; } } } handleShrinkToFit(now); // no collsion, new region means we need to split out the apropriate // balls into a new region if (newRegion && mAnimatingLine != null) { BallRegion otherRegion = splitRegion( now, mAnimatingLine.getDirection(), mAnimatingLine.getPerpAxisOffset()); mAnimatingLine = null; return otherRegion; } else { return null; } } private void handleShrinkToFit(long now) { // update shrinking to fit if (mShrinkingToFit && mAnimatingLine == null) { if (now == mLastUpdate) return; float delta = (now - mLastUpdate) * PIXELS_PER_SECOND; delta = delta / 1000; if (getHeight() > MIN_EDGE) { mTop += delta; mBottom -= delta; } if (getWidth() > MIN_EDGE) { mLeft += delta; mRight -= delta; } final int numBalls = mBalls.size(); for (int i = 0; i < numBalls; i++) { final Ball ball = mBalls.get(i); ball.setRegion(this); } if (getArea() <= SHRINK_TO_FIT_AREA) { mShrinkingToFit = false; mDoneShrinking = true; } } mLastUpdate = now; } /** * Return whether this region can start a line at a certain point. */ public boolean canStartLineAt(float x, float y) { return !mShrinkingToFit && mAnimatingLine == null && isPointWithin(x, y); } /** * Start a horizontal line at a point. * @param now What 'now' is. * @param x The x coordinate. * @param y The y coordinate. */ public void startHorizontalLine(long now, float x, float y) { if (!canStartLineAt(x, y)) { throw new IllegalArgumentException( "can't start line with point (" + x + "," + y + ")"); } mAnimatingLine = new AnimatingLine(Direction.Horizontal, now, y, x, mLeft, mRight); } /** * Start a vertical line at a point. * @param now What 'now' is. * @param x The x coordinate. * @param y The y coordinate. */ public void startVerticalLine(long now, float x, float y) { if (!canStartLineAt(x, y)) { throw new IllegalArgumentException( "can't start line with point (" + x + "," + y + ")"); } mAnimatingLine = new AnimatingLine(Direction.Vertical, now, x, y, mTop, mBottom); } /** * Splits this region at a certain offset, shrinking this one down and returning * the other region that makes up the rest. * @param direction The direction of the line. * @param perpAxisOffset The offset of the perpendicular axis of the line. * @return A new region containing a portion of the balls. */ private BallRegion splitRegion(long now, Direction direction, float perpAxisOffset) { ArrayList<Ball> splitBalls = new ArrayList<Ball>(); if (direction == Direction.Horizontal) { Iterator<Ball> it = mBalls.iterator(); while (it.hasNext()) { Ball ball = it.next(); if (ball.getY() > perpAxisOffset) { it.remove(); splitBalls.add(ball); } } float oldBottom = mBottom; mBottom = perpAxisOffset; checkShrinkToFit(); final BallRegion region = new BallRegion(now, mLeft, mRight, perpAxisOffset, oldBottom, splitBalls); region.setCallBack(mCallBack.get()); return region; } else { assert(direction == Direction.Vertical); Iterator<Ball> it = mBalls.iterator(); while (it.hasNext()) { Ball ball = it.next(); if (ball.getX() > perpAxisOffset) { it.remove(); splitBalls.add(ball); } } float oldRight = mRight; mRight = perpAxisOffset; checkShrinkToFit(); final BallRegion region = new BallRegion(now, perpAxisOffset, oldRight, mTop, mBottom, splitBalls); region.setCallBack(mCallBack.get()); return region; } } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.divideandconquer; import android.app.Dialog; import android.view.View; import android.content.Context; import android.os.Bundle; public class GameOverDialog extends Dialog implements View.OnClickListener { private View mNewGame; private final NewGameCallback mCallback; private View mQuit; public GameOverDialog(Context context, NewGameCallback callback) { super(context); mCallback = callback; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTitle(R.string.game_over); setContentView(R.layout.game_over_dialog); mNewGame = findViewById(R.id.newGame); mNewGame.setOnClickListener(this); mQuit = findViewById(R.id.quit); mQuit.setOnClickListener(this); } /** {@inheritDoc} */ public void onClick(View v) { if (v == mNewGame) { mCallback.onNewGame(); dismiss(); } else if (v == mQuit) { cancel(); } } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.divideandconquer; /** * To specify a dividing line, a user hits the screen and drags in a * certain direction. Once the line has been drawn long enough and mostly * in a particular direction (vertical, or horizontal), we can decide we * know what they mean. Otherwise, it is unknown. * * This is also nice because if the user decides they don't want to send * a dividing line, they can just drag their finger back to where they first * touched and let go, cancelling. */ public class DirectionPoint { enum AmbiguousDirection { Vertical, Horizonal, Unknown } private float mX; private float mY; private float endLineX; private float endLineY; public DirectionPoint(float x, float y) { mX = x; mY = y; endLineX = x; endLineY = y; } public void updateEndPoint(float x, float y) { endLineX = x; endLineY = y; } public float getX() { return mX; } public float getY() { return mY; } /** * We know the direction when the line is at leat 20 pixels long, * and the angle is no more than PI / 6 away from a definitive direction. */ public AmbiguousDirection getDirection() { float dx = endLineX - mX; double distance = Math.hypot(dx, endLineY - mY); if (distance < 10) { return AmbiguousDirection.Unknown; } double angle = Math.acos(dx / distance); double thresh = Math.PI / 6; if ((angle < thresh || (angle > (Math.PI - thresh)))) { return AmbiguousDirection.Horizonal; } if ((angle > 2 * thresh) && angle < 4*thresh) { return AmbiguousDirection.Vertical; } return AmbiguousDirection.Unknown; } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.divideandconquer; import android.os.Bundle; import android.preference.*; import android.content.Context; import android.content.SharedPreferences; /** * Holds preferences for the game */ public class Preferences extends PreferenceActivity { public static final String KEY_VIBRATE = "key_vibrate"; public static final String KEY_DIFFICULTY = "key_difficulty"; public enum Difficulty { Easy(5), Medium(3), Hard(1); private final int mLivesToStart; Difficulty(int livesToStart) { mLivesToStart = livesToStart; } public int getLivesToStart() { return mLivesToStart; } } public static Difficulty getCurrentDifficulty(Context context) { final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); final String diffic = preferences .getString(KEY_DIFFICULTY, DEFAULT_DIFFICULTY.toString()); return Difficulty.valueOf(diffic); } public static final Difficulty DEFAULT_DIFFICULTY = Difficulty.Medium; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setPreferenceScreen(createPreferenceHierarchy()); } private PreferenceScreen createPreferenceHierarchy() { // Root PreferenceScreen root = getPreferenceManager().createPreferenceScreen(this); // vibrate on/off CheckBoxPreference vibratePref = new CheckBoxPreference(this); vibratePref.setDefaultValue(true); vibratePref.setKey(KEY_VIBRATE); vibratePref.setTitle(R.string.settings_vibrate); vibratePref.setSummary(R.string.settings_vibrate_summary); root.addPreference(vibratePref); // difficulty level ListPreference difficultyPref = new ListPreference(this); difficultyPref.setEntries(new String[] { getString(R.string.settings_five_lives), getString(R.string.settings_three_lives), getString(R.string.settings_one_life)}); difficultyPref.setEntryValues(new String[] { Difficulty.Easy.toString(), Difficulty.Medium.toString(), Difficulty.Hard.toString()}); difficultyPref.setKey(KEY_DIFFICULTY); difficultyPref.setTitle(R.string.settings_difficulty); difficultyPref.setSummary(R.string.settings_difficulty_summary); final SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this); if (!sharedPrefs.contains(KEY_DIFFICULTY)) { difficultyPref.setValue(DEFAULT_DIFFICULTY.toString()); } root.addPreference(difficultyPref); return root; } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.divideandconquer; /** * A ball has a current location, a trajectory angle, a speed in pixels per * second, and a last update time. It is capable of updating itself based on * its trajectory and speed. * * It also knows its boundaries, and will 'bounce' off them when it reaches them. */ public class Ball extends Shape2d { private long mLastUpdate; private float mX; private float mY; private double mAngle; private final float mPixelsPerSecond; private final float mRadiusPixels; private Shape2d mRegion; private Ball(long now, float pixelsPerSecond, float x, float y, double angle, float radiusPixels) { mLastUpdate = now; mPixelsPerSecond = pixelsPerSecond; mX = x; mY = y; mAngle = angle; mRadiusPixels = radiusPixels; } public float getX() { return mX; } public float getY() { return mY; } public float getLeft() { return mX - mRadiusPixels; } public float getRight() { return mX + mRadiusPixels; } public float getTop() { return mY - mRadiusPixels; } public float getBottom() { return mY + mRadiusPixels; } public float getRadiusPixels() { return mRadiusPixels; } public double getAngle() { return mAngle; } /** * Get the region the ball is contained in. */ public Shape2d getRegion() { return mRegion; } /** * Set the region that the ball is contained in. * @param region The region. */ public void setRegion(Shape2d region) { if (mX < region.getLeft()) { mX = region.getLeft(); bounceOffLeft(); } else if (mX > region.getRight()) { mX = region.getRight(); bounceOffRight(); } if (mY < region.getTop()) { mY = region.getTop(); bounceOffTop(); } else if (mY > region.getBottom()) { mY = region.getBottom(); bounceOffBottom(); } mRegion = region; } public void setNow(long now) { mLastUpdate = now; } public boolean isCircleOverlapping(Ball otherBall) { final float dy = otherBall.mY - mY; final float dx = otherBall.mX - mX; final float distance = dy * dy + dx * dx; return (distance < ((2 * mRadiusPixels) * (2 *mRadiusPixels))) // avoid jittery collisions && !movingAwayFromEachother(this, otherBall); } private boolean movingAwayFromEachother(Ball ballA, Ball ballB) { double collA = Math.atan2(ballB.mY - ballA.mY, ballB.mX - ballA.mX); double collB = Math.atan2(ballA.mY - ballB.mY, ballA.mX - ballB.mX); double ax = Math.cos(ballA.mAngle - collA); double bx = Math.cos(ballB.mAngle - collB); return ax + bx < 0; } public void update(long now) { if (now <= mLastUpdate) return; // bounce when at walls if (mX <= mRegion.getLeft() + mRadiusPixels) { // we're at left wall mX = mRegion.getLeft() + mRadiusPixels; bounceOffLeft(); } else if (mY <= mRegion.getTop() + mRadiusPixels) { // at top wall mY = mRegion.getTop() + mRadiusPixels; bounceOffTop(); } else if (mX >= mRegion.getRight() - mRadiusPixels) { // at right wall mX = mRegion.getRight() - mRadiusPixels; bounceOffRight(); } else if (mY >= mRegion.getBottom() - mRadiusPixels) { // at bottom wall mY = mRegion.getBottom() - mRadiusPixels; bounceOffBottom(); } float delta = (now - mLastUpdate) * mPixelsPerSecond; delta = delta / 1000f; mX += (delta * Math.cos(mAngle)); mY += (delta * Math.sin(mAngle)); mLastUpdate = now; } private void bounceOffBottom() { if (mAngle < 0.5*Math.PI) { // going right mAngle = -mAngle; } else { // going left mAngle += (Math.PI - mAngle) * 2; } } private void bounceOffRight() { if (mAngle > 1.5*Math.PI) { // going up mAngle -= (mAngle - 1.5*Math.PI) * 2; } else { // going down mAngle += (.5*Math.PI - mAngle) * 2; } } private void bounceOffTop() { if (mAngle < 1.5 * Math.PI) { // going left mAngle -= (mAngle - Math.PI) * 2; } else { // going right mAngle += (2*Math.PI - mAngle) * 2; mAngle -= 2*Math.PI; } } private void bounceOffLeft() { if (mAngle < Math.PI) { // going down mAngle -= ((mAngle - (Math.PI / 2)) * 2); } else { // going up mAngle += (((1.5 * Math.PI) - mAngle) * 2); } } /** * Given that ball a and b have collided, adjust their angles to reflect their state * after the collision. * * This method works based on the conservation of energy and momentum in an elastic * collision. Because the balls have equal mass and speed, it ends up being that they * simply swap velocities along the axis of the collision, keeping the velocities tangent * to the collision constant. * * @param ballA The first ball in a collision * @param ballB The second ball in a collision */ public static void adjustForCollision(Ball ballA, Ball ballB) { final double collA = Math.atan2(ballB.mY - ballA.mY, ballB.mX - ballA.mX); final double collB = Math.atan2(ballA.mY - ballB.mY, ballA.mX - ballB.mX); final double ax = Math.cos(ballA.mAngle - collA); final double ay = Math.sin(ballA.mAngle - collA); final double bx = Math.cos(ballB.mAngle - collB); final double by = Math.cos(ballB.mAngle - collB); final double diffA = Math.atan2(ay, -bx); final double diffB = Math.atan2(by, -ax); ballA.mAngle = collA + diffA; ballB.mAngle = collB + diffB; } @Override public String toString() { return String.format( "Ball(x=%f, y=%f, angle=%f)", mX, mY, Math.toDegrees(mAngle)); } /** * A more readable way to create balls than using a 5 param * constructor of all numbers. */ public static class Builder { private long mNow = -1; private float mX = -1; private float mY = -1; private double mAngle = -1; private float mRadiusPixels = -1; private float mPixelsPerSecond = 45f; public Ball create() { if (mNow < 0) { throw new IllegalStateException("must set 'now'"); } if (mX < 0) { throw new IllegalStateException("X must be set"); } if (mY < 0) { throw new IllegalStateException("Y must be stet"); } if (mAngle < 0) { throw new IllegalStateException("angle must be set"); } if (mAngle > 2 * Math.PI) { throw new IllegalStateException("angle must be less that 2Pi"); } if (mRadiusPixels <= 0) { throw new IllegalStateException("radius must be set"); } return new Ball(mNow, mPixelsPerSecond, mX, mY, mAngle, mRadiusPixels); } public Builder setNow(long now) { mNow = now; return this; } public Builder setPixelsPerSecond(float pixelsPerSecond) { mPixelsPerSecond = pixelsPerSecond; return this; } public Builder setX(float x) { mX = x; return this; } public Builder setY(float y) { mY = y; return this; } public Builder setAngle(double angle) { mAngle = angle; return this; } public Builder setRadiusPixels(float pixels) { mRadiusPixels = pixels; return this; } } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.divideandconquer; import android.app.Dialog; import android.content.Context; import android.os.Bundle; import android.view.View; /** * When the game starts, the user is welcomed with a message, and buttons for * starting a new game, or getting instructions about the game. */ public class WelcomeDialog extends Dialog implements View.OnClickListener { private final NewGameCallback mCallback; private View mNewGame; public WelcomeDialog(Context context, NewGameCallback callback) { super(context); mCallback = callback; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTitle(R.string.app_name); setContentView(R.layout.welcome_dialog); mNewGame = findViewById(R.id.newGame); mNewGame.setOnClickListener(this); } /** {@inheritDoc} */ public void onClick(View v) { if (v == mNewGame) { mCallback.onNewGame(); dismiss(); } } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.radar; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.Paint.Align; import android.graphics.Paint.Style; import android.graphics.drawable.BitmapDrawable; import android.hardware.SensorListener; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.location.LocationProvider; import android.os.Bundle; import android.os.SystemClock; import android.util.AttributeSet; import android.view.View; import android.widget.TextView; public class RadarView extends View implements SensorListener, LocationListener { private static final long RETAIN_GPS_MILLIS = 10000L; private Paint mGridPaint; private Paint mErasePaint; private float mOrientation; private double mTargetLat; private double mTargetLon; private double mMyLocationLat; private double mMyLocationLon; private int mLastScale = -1; private String[] mDistanceScale = new String[4]; private static float KM_PER_METERS = 0.001f; private static float METERS_PER_KM = 1000f; /** * These are the list of choices for the radius of the outer circle on the * screen when using metric units. All items are in kilometers. This array is * used to choose the scale of the radar display. */ private static double mMetricScaleChoices[] = { 100 * KM_PER_METERS, 200 * KM_PER_METERS, 400 * KM_PER_METERS, 1, 2, 4, 8, 20, 40, 100, 200, 400, 1000, 2000, 4000, 10000, 20000, 40000, 80000 }; /** * Once the scale is chosen, this array is used to convert the number of * kilometers on the screen to an integer. (Note that for short distances we * use meters, so we multiply the distance by {@link #METERS_PER_KM}. (This * array is for metric measurements.) */ private static float mMetricDisplayUnitsPerKm[] = { METERS_PER_KM, METERS_PER_KM, METERS_PER_KM, METERS_PER_KM, METERS_PER_KM, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f }; /** * This array holds the formatting string used to display the distance to * the target. (This array is for metric measurements.) */ private static String mMetricDisplayFormats[] = { "%.0fm", "%.0fm", "%.0fm", "%.0fm", "%.0fm", "%.1fkm", "%.1fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm" }; /** * This array holds the formatting string used to display the distance on * each ring of the radar screen. (This array is for metric measurements.) */ private static String mMetricScaleFormats[] = { "%.0fm", "%.0fm", "%.0fm", "%.0fm", "%.0fm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm" }; private static float KM_PER_YARDS = 0.0009144f; private static float KM_PER_MILES = 1.609344f; private static float YARDS_PER_KM = 1093.6133f; private static float MILES_PER_KM = 0.621371192f; /** * These are the list of choices for the radius of the outer circle on the * screen when using standard units. All items are in kilometers. This array is * used to choose the scale of the radar display. */ private static double mEnglishScaleChoices[] = { 100 * KM_PER_YARDS, 200 * KM_PER_YARDS, 400 * KM_PER_YARDS, 1000 * KM_PER_YARDS, 1 * KM_PER_MILES, 2 * KM_PER_MILES, 4 * KM_PER_MILES, 8 * KM_PER_MILES, 20 * KM_PER_MILES, 40 * KM_PER_MILES, 100 * KM_PER_MILES, 200 * KM_PER_MILES, 400 * KM_PER_MILES, 1000 * KM_PER_MILES, 2000 * KM_PER_MILES, 4000 * KM_PER_MILES, 10000 * KM_PER_MILES, 20000 * KM_PER_MILES, 40000 * KM_PER_MILES, 80000 * KM_PER_MILES }; /** * Once the scale is chosen, this array is used to convert the number of * kilometers on the screen to an integer. (Note that for short distances we * use meters, so we multiply the distance by {@link #YARDS_PER_KM}. (This * array is for standard measurements.) */ private static float mEnglishDisplayUnitsPerKm[] = { YARDS_PER_KM, YARDS_PER_KM, YARDS_PER_KM, YARDS_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM }; /** * This array holds the formatting string used to display the distance to * the target. (This array is for standard measurements.) */ private static String mEnglishDisplayFormats[] = { "%.0fyd", "%.0fyd", "%.0fyd", "%.0fyd", "%.1fmi", "%.1fmi", "%.1fmi", "%.1fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi" }; /** * This array holds the formatting string used to display the distance on * each ring of the radar screen. (This array is for standard measurements.) */ private static String mEnglishScaleFormats[] = { "%.0fyd", "%.0fyd", "%.0fyd", "%.0fyd", "%.2fmi", "%.1fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi" }; /** * True when we have know our own location */ private boolean mHaveLocation = false; /** * The view that will display the distance text */ private TextView mDistanceView; /** * Distance to target, in KM */ private double mDistance; /** * Bearing to target, in degrees */ private double mBearing; /** * Ratio of the distance to the target to the radius of the outermost ring on the radar screen */ private float mDistanceRatio; /** * Utility rect for calculating the ring labels */ private Rect mTextBounds = new Rect(); /** * The bitmap used to draw the target */ private Bitmap mBlip; /** * Used to draw the animated ring that sweeps out from the center */ private Paint mSweepPaint0; /** * Used to draw the animated ring that sweeps out from the center */ private Paint mSweepPaint1; /** * Used to draw the animated ring that sweeps out from the center */ private Paint mSweepPaint2; /** * Time in millis when the most recent sweep began */ private long mSweepTime; /** * True if the sweep has not yet intersected the blip */ private boolean mSweepBefore; /** * Time in millis when the sweep last crossed the blip */ private long mBlipTime; /** * True if the display should use metric units; false if the display should use standard * units */ private boolean mUseMetric; /** * Time in millis for the last time GPS reported a location */ private long mLastGpsFixTime = 0L; /** * The last location reported by the network provider. Use this if we can't get a location from * GPS */ private Location mNetworkLocation; /** * True if GPS is reporting a location */ private boolean mGpsAvailable; /** * True if the network provider is reporting a location */ private boolean mNetworkAvailable; public RadarView(Context context) { this(context, null); } public RadarView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public RadarView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); // Paint used for the rings and ring text mGridPaint = new Paint(); mGridPaint.setColor(0xFF00FF00); mGridPaint.setAntiAlias(true); mGridPaint.setStyle(Style.STROKE); mGridPaint.setStrokeWidth(1.0f); mGridPaint.setTextSize(10.0f); mGridPaint.setTextAlign(Align.CENTER); // Paint used to erase the rectangle behing the ring text mErasePaint = new Paint(); mErasePaint.setColor(0xFF191919); mErasePaint.setStyle(Style.FILL); // Outer ring of the sweep mSweepPaint0 = new Paint(); mSweepPaint0.setColor(0xFF33FF33); mSweepPaint0.setAntiAlias(true); mSweepPaint0.setStyle(Style.STROKE); mSweepPaint0.setStrokeWidth(2f); // Middle ring of the sweep mSweepPaint1 = new Paint(); mSweepPaint1.setColor(0x7733FF33); mSweepPaint1.setAntiAlias(true); mSweepPaint1.setStyle(Style.STROKE); mSweepPaint1.setStrokeWidth(2f); // Inner ring of the sweep mSweepPaint2 = new Paint(); mSweepPaint2.setColor(0x3333FF33); mSweepPaint2.setAntiAlias(true); mSweepPaint2.setStyle(Style.STROKE); mSweepPaint2.setStrokeWidth(2f); mBlip = ((BitmapDrawable)getResources().getDrawable(R.drawable.blip)).getBitmap(); } /** * Sets the target to track on the radar * @param latE6 Latitude of the target, multiplied by 1,000,000 * @param lonE6 Longitude of the target, multiplied by 1,000,000 */ public void setTarget(int latE6, int lonE6) { mTargetLat = latE6 / (double) GeoUtils.MILLION; mTargetLon = lonE6 / (double) GeoUtils.MILLION; } /** * Sets the view that we will use to report distance * * @param t The text view used to report distance */ public void setDistanceView(TextView t) { mDistanceView = t; } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); int center = getWidth() / 2; int radius = center - 8; // Draw the rings final Paint gridPaint = mGridPaint; canvas.drawCircle(center, center, radius, gridPaint); canvas.drawCircle(center, center, radius * 3 / 4, gridPaint); canvas.drawCircle(center, center, radius >> 1, gridPaint); canvas.drawCircle(center, center, radius >> 2, gridPaint); int blipRadius = (int) (mDistanceRatio * radius); final long now = SystemClock.uptimeMillis(); if (mSweepTime > 0 && mHaveLocation) { // Draw the sweep. Radius is determined by how long ago it started long sweepDifference = now - mSweepTime; if (sweepDifference < 512L) { int sweepRadius = (int) (((radius + 6) * sweepDifference) >> 9); canvas.drawCircle(center, center, sweepRadius, mSweepPaint0); canvas.drawCircle(center, center, sweepRadius - 2, mSweepPaint1); canvas.drawCircle(center, center, sweepRadius - 4, mSweepPaint2); // Note when the sweep has passed the blip boolean before = sweepRadius < blipRadius; if (!before && mSweepBefore) { mSweepBefore = false; mBlipTime = now; } } else { mSweepTime = now + 1000; mSweepBefore = true; } postInvalidate(); } // Draw horizontal and vertical lines canvas.drawLine(center, center - (radius >> 2) + 6, center, center - radius - 6, gridPaint); canvas.drawLine(center, center + (radius >> 2) - 6 , center, center + radius + 6, gridPaint); canvas.drawLine(center - (radius >> 2) + 6, center, center - radius - 6, center, gridPaint); canvas.drawLine(center + (radius >> 2) - 6, center, center + radius + 6, center, gridPaint); // Draw X in the center of the screen canvas.drawLine(center - 4, center - 4, center + 4, center + 4, gridPaint); canvas.drawLine(center - 4, center + 4, center + 4, center - 4, gridPaint); if (mHaveLocation) { double bearingToTarget = mBearing - mOrientation; double drawingAngle = Math.toRadians(bearingToTarget) - (Math.PI / 2); float cos = (float) Math.cos(drawingAngle); float sin = (float) Math.sin(drawingAngle); // Draw the text for the rings final String[] distanceScale = mDistanceScale; addText(canvas, distanceScale[0], center, center + (radius >> 2)); addText(canvas, distanceScale[1], center, center + (radius >> 1)); addText(canvas, distanceScale[2], center, center + radius * 3 / 4); addText(canvas, distanceScale[3], center, center + radius); // Draw the blip. Alpha is based on how long ago the sweep crossed the blip long blipDifference = now - mBlipTime; gridPaint.setAlpha(255 - (int)((128 * blipDifference) >> 10)); canvas.drawBitmap(mBlip, center + (cos * blipRadius) - 8 , center + (sin * blipRadius) - 8, gridPaint); gridPaint.setAlpha(255); } } private void addText(Canvas canvas, String str, int x, int y) { mGridPaint.getTextBounds(str, 0, str.length(), mTextBounds); mTextBounds.offset(x - (mTextBounds.width() >> 1), y); mTextBounds.inset(-2, -2); canvas.drawRect(mTextBounds, mErasePaint); canvas.drawText(str, x, y, mGridPaint); } public void onAccuracyChanged(int sensor, int accuracy) { } /** * Called when we get a new value from the compass * * @see android.hardware.SensorListener#onSensorChanged(int, float[]) */ public void onSensorChanged(int sensor, float[] values) { mOrientation = values[0]; postInvalidate(); } /** * Called when a location provider has a new location to report * * @see android.location.LocationListener#onLocationChanged(android.location.Location) */ public void onLocationChanged(Location location) { if (!mHaveLocation) { mHaveLocation = true; } final long now = SystemClock.uptimeMillis(); boolean useLocation = false; final String provider = location.getProvider(); if (LocationManager.GPS_PROVIDER.equals(provider)) { // Use GPS if available mLastGpsFixTime = SystemClock.uptimeMillis(); useLocation = true; } else if (LocationManager.NETWORK_PROVIDER.equals(provider)) { // Use network provider if GPS is getting stale useLocation = now - mLastGpsFixTime > RETAIN_GPS_MILLIS; if (mNetworkLocation == null) { mNetworkLocation = new Location(location); } else { mNetworkLocation.set(location); } mLastGpsFixTime = 0L; } if (useLocation) { mMyLocationLat = location.getLatitude(); mMyLocationLon = location.getLongitude(); mDistance = GeoUtils.distanceKm(mMyLocationLat, mMyLocationLon, mTargetLat, mTargetLon); mBearing = GeoUtils.bearing(mMyLocationLat, mMyLocationLon, mTargetLat, mTargetLon); updateDistance(mDistance); } } public void onProviderDisabled(String provider) { } public void onProviderEnabled(String provider) { } /** * Called when a location provider has changed its availability. * * @see android.location.LocationListener#onStatusChanged(java.lang.String, int, android.os.Bundle) */ public void onStatusChanged(String provider, int status, Bundle extras) { if (LocationManager.GPS_PROVIDER.equals(provider)) { switch (status) { case LocationProvider.AVAILABLE: mGpsAvailable = true; break; case LocationProvider.OUT_OF_SERVICE: case LocationProvider.TEMPORARILY_UNAVAILABLE: mGpsAvailable = false; if (mNetworkLocation != null && mNetworkAvailable) { // Fallback to network location mLastGpsFixTime = 0L; onLocationChanged(mNetworkLocation); } else { handleUnknownLocation(); } break; } } else if (LocationManager.NETWORK_PROVIDER.equals(provider)) { switch (status) { case LocationProvider.AVAILABLE: mNetworkAvailable = true; break; case LocationProvider.OUT_OF_SERVICE: case LocationProvider.TEMPORARILY_UNAVAILABLE: mNetworkAvailable = false; if (!mGpsAvailable) { handleUnknownLocation(); } break; } } } /** * Called when we no longer have a valid lcoation. */ private void handleUnknownLocation() { mHaveLocation = false; mDistanceView.setText(R.string.scanning); } /** * Update state to reflect whether we are using metric or standard units. * * @param useMetric True if the display should use metric units */ public void setUseMetric(boolean useMetric) { mUseMetric = useMetric; mLastScale = -1; if (mHaveLocation) { updateDistance(mDistance); } invalidate(); } /** * Update our state to reflect a new distance to the target. This may require * choosing a new scale for the radar rings. * * @param distanceKm The new distance to the target */ private void updateDistance(double distanceKm) { final double[] scaleChoices; final float[] displayUnitsPerKm; final String[] displayFormats; final String[] scaleFormats; String distanceStr = null; if (mUseMetric) { scaleChoices = mMetricScaleChoices; displayUnitsPerKm = mMetricDisplayUnitsPerKm; displayFormats = mMetricDisplayFormats; scaleFormats = mMetricScaleFormats; } else { scaleChoices = mEnglishScaleChoices; displayUnitsPerKm = mEnglishDisplayUnitsPerKm; displayFormats = mEnglishDisplayFormats; scaleFormats = mEnglishScaleFormats; } int count = scaleChoices.length; for (int i = 0; i < count; i++) { if (distanceKm < scaleChoices[i] || i == (count - 1)) { String format = displayFormats[i]; double distanceDisplay = distanceKm * displayUnitsPerKm[i]; if (mLastScale != i) { mLastScale = i; String scaleFormat = scaleFormats[i]; float scaleDistance = (float) (scaleChoices[i] * displayUnitsPerKm[i]); mDistanceScale[0] = String.format(scaleFormat, (scaleDistance / 4)); mDistanceScale[1] = String.format(scaleFormat, (scaleDistance / 2)); mDistanceScale[2] = String.format(scaleFormat, (scaleDistance * 3 / 4)); mDistanceScale[3] = String.format(scaleFormat, scaleDistance); } mDistanceRatio = (float) (mDistance / scaleChoices[mLastScale]); distanceStr = String.format(format, distanceDisplay); break; } } mDistanceView.setText(distanceStr); } /** * Turn on the sweep animation starting with the next draw */ public void startSweep() { mSweepTime = SystemClock.uptimeMillis(); mSweepBefore = true; } /** * Turn off the sweep animation */ public void stopSweep() { mSweepTime = 0L; } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.radar; import com.google.android.maps.GeoPoint; /** * Library for some use useful latitude/longitude math */ public class GeoUtils { private static int EARTH_RADIUS_KM = 6371; public static int MILLION = 1000000; /** * Computes the distance in kilometers between two points on Earth. * * @param lat1 Latitude of the first point * @param lon1 Longitude of the first point * @param lat2 Latitude of the second point * @param lon2 Longitude of the second point * @return Distance between the two points in kilometers. */ public static double distanceKm(double lat1, double lon1, double lat2, double lon2) { double lat1Rad = Math.toRadians(lat1); double lat2Rad = Math.toRadians(lat2); double deltaLonRad = Math.toRadians(lon2 - lon1); return Math.acos(Math.sin(lat1Rad) * Math.sin(lat2Rad) + Math.cos(lat1Rad) * Math.cos(lat2Rad) * Math.cos(deltaLonRad)) * EARTH_RADIUS_KM; } /** * Computes the distance in kilometers between two points on Earth. * * @param p1 First point * @param p2 Second point * @return Distance between the two points in kilometers. */ public static double distanceKm(GeoPoint p1, GeoPoint p2) { double lat1 = p1.getLatitudeE6() / (double)MILLION; double lon1 = p1.getLongitudeE6() / (double)MILLION; double lat2 = p2.getLatitudeE6() / (double)MILLION; double lon2 = p2.getLongitudeE6() / (double)MILLION; return distanceKm(lat1, lon1, lat2, lon2); } /** * Computes the bearing in degrees between two points on Earth. * * @param p1 First point * @param p2 Second point * @return Bearing between the two points in degrees. A value of 0 means due * north. */ public static double bearing(GeoPoint p1, GeoPoint p2) { double lat1 = p1.getLatitudeE6() / (double) MILLION; double lon1 = p1.getLongitudeE6() / (double) MILLION; double lat2 = p2.getLatitudeE6() / (double) MILLION; double lon2 = p2.getLongitudeE6() / (double) MILLION; return bearing(lat1, lon1, lat2, lon2); } /** * Computes the bearing in degrees between two points on Earth. * * @param lat1 Latitude of the first point * @param lon1 Longitude of the first point * @param lat2 Latitude of the second point * @param lon2 Longitude of the second point * @return Bearing between the two points in degrees. A value of 0 means due * north. */ public static double bearing(double lat1, double lon1, double lat2, double lon2) { double lat1Rad = Math.toRadians(lat1); double lat2Rad = Math.toRadians(lat2); double deltaLonRad = Math.toRadians(lon2 - lon1); double y = Math.sin(deltaLonRad) * Math.cos(lat2Rad); double x = Math.cos(lat1Rad) * Math.sin(lat2Rad) - Math.sin(lat1Rad) * Math.cos(lat2Rad) * Math.cos(deltaLonRad); return radToBearing(Math.atan2(y, x)); } /** * Converts an angle in radians to degrees */ public static double radToBearing(double rad) { return (Math.toDegrees(rad) + 360) % 360; } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.radar; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.hardware.SensorManager; import android.location.LocationManager; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.Window; import android.widget.TextView; /** * Simple Activity wrapper that hosts a {@link RadarView} * */ public class RadarActivity extends Activity { private static final int LOCATION_UPDATE_INTERVAL_MILLIS = 1000; private static final int MENU_STANDARD = Menu.FIRST + 1; private static final int MENU_METRIC = Menu.FIRST + 2; private static final String RADAR = "radar"; private static final String PREF_METRIC = "metric"; private SensorManager mSensorManager; private RadarView mRadar; private LocationManager mLocationManager; private SharedPreferences mPrefs; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.radar); mRadar = (RadarView) findViewById(R.id.radar); mSensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE); mLocationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); // Metric or standard units? mPrefs = getSharedPreferences(RADAR, MODE_PRIVATE); boolean useMetric = mPrefs.getBoolean(PREF_METRIC, false); mRadar.setUseMetric(useMetric); // Read the target from our intent Intent i = getIntent(); int latE6 = (int)(i.getFloatExtra("latitude", 0) * GeoUtils.MILLION); int lonE6 = (int)(i.getFloatExtra("longitude", 0) * GeoUtils.MILLION); mRadar.setTarget(latE6, lonE6); mRadar.setDistanceView((TextView) findViewById(R.id.distance)); } @Override protected void onResume() { super.onResume(); mSensorManager.registerListener(mRadar, SensorManager.SENSOR_ORIENTATION, SensorManager.SENSOR_DELAY_GAME); // Start animating the radar screen mRadar.startSweep(); // Register for location updates mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, LOCATION_UPDATE_INTERVAL_MILLIS, 1, mRadar); mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, LOCATION_UPDATE_INTERVAL_MILLIS, 1, mRadar); } @Override protected void onPause() { mSensorManager.unregisterListener(mRadar); mLocationManager.removeUpdates(mRadar); // Stop animating the radar screen mRadar.stopSweep(); super.onStop(); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); menu.add(0, MENU_STANDARD, 0, R.string.menu_standard) .setIcon(R.drawable.ic_menu_standard) .setAlphabeticShortcut('A'); menu.add(0, MENU_METRIC, 0, R.string.menu_metric) .setIcon(R.drawable.ic_menu_metric) .setAlphabeticShortcut('C'); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case MENU_STANDARD: { setUseMetric(false); return true; } case MENU_METRIC: { setUseMetric(true); return true; } } return super.onOptionsItemSelected(item); } private void setUseMetric(boolean useMetric) { SharedPreferences.Editor e = mPrefs.edit(); e.putBoolean(PREF_METRIC, useMetric); e.commit(); mRadar.setUseMetric(useMetric); } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.google.android.wikinotes; import java.util.regex.Pattern; import android.app.Activity; import android.content.ContentUris; import android.content.ContentValues; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.text.util.Linkify; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.widget.TextView; import com.google.android.wikinotes.db.WikiNote; /** * The WikiNotes activity is the default handler for displaying individual * wiki notes. It takes the wiki note name to view from the intent data URL * and defaults to a page name defined in R.strings.start_page if no page name * is given. The lifecycle events store the current content URL being viewed. * It uses Linkify to turn wiki words in the body of the wiki note into * clickable links which in turn call back into the WikiNotes activity from * the Android operating system. If a URL is passed to the WikiNotes activity * for a page that does not yet exist, the WikiNoteEditor activity is * automatically started to place the user into edit mode for a new wiki note * with the given name. */ public class WikiNotes extends Activity { /** * The view URL which is prepended to a matching wikiword in order to fire * the WikiNotes activity again through Linkify */ private static final String KEY_URL = "wikiNotesURL"; public static final int EDIT_ID = Menu.FIRST; public static final int HOME_ID = Menu.FIRST + 1; public static final int LIST_ID = Menu.FIRST + 3; public static final int DELETE_ID = Menu.FIRST + 4; public static final int ABOUT_ID = Menu.FIRST + 5; public static final int EXPORT_ID = Menu.FIRST + 6; public static final int IMPORT_ID = Menu.FIRST + 7; public static final int EMAIL_ID = Menu.FIRST + 8; private TextView mNoteView; Cursor mCursor; private Uri mURI; String mNoteName; private static final Pattern WIKI_WORD_MATCHER; private WikiActivityHelper mHelper; static { // Compile the regular expression pattern that will be used to // match WikiWords in the body of the note WIKI_WORD_MATCHER = Pattern .compile("\\b[A-Z]+[a-z0-9]+[A-Z][A-Za-z0-9]+\\b"); } @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); mNoteView = (TextView) findViewById(R.id.noteview); // get the URL we are being asked to view Uri uri = getIntent().getData(); if ((uri == null) && (icicle != null)) { // perhaps we have the URI in the icicle instead? uri = Uri.parse(icicle.getString(KEY_URL)); } // do we have a correct URI including the note name? if ((uri == null) || (uri.getPathSegments().size() < 2)) { // if not, build one using the default StartPage name uri = Uri.withAppendedPath(WikiNote.Notes.ALL_NOTES_URI, getResources() .getString(R.string.start_page)); } // can we find a matching note? Cursor cursor = managedQuery(uri, WikiNote.WIKI_NOTES_PROJECTION, null, null, null); boolean newNote = false; if ((cursor == null) || (cursor.getCount() == 0)) { // no matching wikinote, so create it uri = getContentResolver().insert(uri, null); if (uri == null) { Log.e("WikiNotes", "Failed to insert new wikinote into " + getIntent().getData()); finish(); return; } // make sure that the new note was created successfully, and // select // it cursor = managedQuery(uri, WikiNote.WIKI_NOTES_PROJECTION, null, null, null); if ((cursor == null) || (cursor.getCount() == 0)) { Log.e("WikiNotes", "Failed to open new wikinote: " + getIntent().getData()); finish(); return; } newNote = true; } mURI = uri; mCursor = cursor; cursor.moveToFirst(); mHelper = new WikiActivityHelper(this); // get the note name String noteName = cursor.getString(cursor .getColumnIndexOrThrow(WikiNote.Notes.TITLE)); mNoteName = noteName; // set the title to the name of the page setTitle(getResources().getString(R.string.wiki_title, noteName)); // If a new note was created, jump straight into editing it if (newNote) { mHelper.editNote(noteName, null); } else if (!getSharedPreferences(Eula.PREFERENCES_EULA, Activity.MODE_PRIVATE) .getBoolean(Eula.PREFERENCE_EULA_ACCEPTED, false)) { Eula.showEula(this); } // Set the menu shortcut keys to be default keys for the activity as // well setDefaultKeyMode(DEFAULT_KEYS_SHORTCUT); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); // Put the URL currently being viewed into the icicle outState.putString(KEY_URL, mURI.toString()); } @Override protected void onResume() { super.onResume(); Cursor c = mCursor; if (c.getCount() < 1) { // if the note can't be found, don't try to load it -- bail out // (probably means it got deleted while we were frozen; // thx to joe.bowbeer for the find) finish(); return; } c.requery(); c.moveToFirst(); showWikiNote(c .getString(c.getColumnIndexOrThrow(WikiNote.Notes.BODY))); } /** * Show the wiki note in the text edit view with both the default Linkify * options and the regular expression for WikiWords matched and turned * into live links. * * @param body * The plain text to linkify and put into the edit view. */ private void showWikiNote(CharSequence body) { TextView noteView = mNoteView; noteView.setText(body); // Add default links first - phone numbers, URLs, etc. Linkify.addLinks(noteView, Linkify.ALL); // Now add in the custom linkify match for WikiWords Linkify.addLinks(noteView, WIKI_WORD_MATCHER, WikiNote.Notes.ALL_NOTES_URI.toString() + "/"); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); menu.add(0, EDIT_ID, 0, R.string.menu_edit).setShortcut('1', 'e') .setIcon(R.drawable.icon_delete); menu.add(0, HOME_ID, 0, R.string.menu_start).setShortcut('4', 'h') .setIcon(R.drawable.icon_start); menu.add(0, LIST_ID, 0, R.string.menu_recent).setShortcut('3', 'r') .setIcon(R.drawable.icon_recent); menu.add(0, DELETE_ID, 0, R.string.menu_delete).setShortcut('2', 'd') .setIcon(R.drawable.icon_delete); menu.add(0, ABOUT_ID, 0, R.string.menu_about).setShortcut('5', 'a') .setIcon(android.R.drawable.ic_dialog_info); menu.add(0, EXPORT_ID, 0, R.string.menu_export).setShortcut('7', 'x') .setIcon(android.R.drawable.ic_dialog_info); menu.add(0, IMPORT_ID, 0, R.string.menu_import).setShortcut('8', 'm') .setIcon(android.R.drawable.ic_dialog_info); menu.add(0, EMAIL_ID, 0, R.string.menu_email).setShortcut('6', 'm') .setIcon(android.R.drawable.ic_dialog_info); return true; } @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { switch (item.getItemId()) { case EDIT_ID: mHelper.editNote(mNoteName, mCursor); return true; case HOME_ID: mHelper.goHome(); return true; case DELETE_ID: mHelper.deleteNote(mCursor); return true; case LIST_ID: mHelper.listNotes(); return true; case WikiNotes.ABOUT_ID: Eula.showEula(this); return true; case WikiNotes.EXPORT_ID: mHelper.exportNotes(); return true; case WikiNotes.IMPORT_ID: mHelper.importNotes(); return true; case WikiNotes.EMAIL_ID: mHelper.mailNote(mCursor); return true; default: return false; } } /** * If the note was edited and not canceled, commit the update to the * database and then refresh the current view of the linkified note. */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent result) { super.onActivityResult(requestCode, resultCode, result); if ((requestCode == WikiActivityHelper.ACTIVITY_EDIT) && (resultCode == RESULT_OK)) { // edit was confirmed - store the update Cursor c = mCursor; c.requery(); c.moveToFirst(); Uri noteUri = ContentUris .withAppendedId(WikiNote.Notes.ALL_NOTES_URI, c.getInt(0)); ContentValues values = new ContentValues(); values.put(WikiNote.Notes.BODY, result .getStringExtra(WikiNoteEditor.ACTIVITY_RESULT)); values.put(WikiNote.Notes.MODIFIED_DATE, System .currentTimeMillis()); getContentResolver().update(noteUri, values, "_id = " + c.getInt(0), null); showWikiNote(c.getString(c .getColumnIndexOrThrow(WikiNote.Notes.BODY))); } } }
Java
/* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.wikinotes; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.SharedPreferences; /** * Displays an EULA ("End User License Agreement") that the user has to accept * before using the application. Your application should call * {@link Eula#showEula(android.app.Activity)} in the onCreate() method of the * first activity. If the user accepts the EULA, it will never be shown again. * If the user refuses, {@link android.app.Activity#finish()} is invoked on your * activity. */ class Eula { public static final String PREFERENCE_EULA_ACCEPTED = "eula.accepted"; public static final String PREFERENCES_EULA = "eula"; /** * Displays the EULA if necessary. This method should be called from the * onCreate() method of your main Activity. * * @param activity * The Activity to finish if the user rejects the EULA. */ static void showEula(final Activity activity) { final SharedPreferences preferences = activity.getSharedPreferences( PREFERENCES_EULA, Activity.MODE_PRIVATE); final AlertDialog.Builder builder = new AlertDialog.Builder(activity); builder.setTitle(R.string.about_title); builder.setCancelable(false); builder.setPositiveButton(R.string.about_dismiss_button, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { preferences.edit().putBoolean(PREFERENCE_EULA_ACCEPTED, true).commit(); } }); builder.setMessage(R.string.about_body); builder.create().show(); } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.google.android.wikinotes; import android.app.ListActivity; import android.app.SearchManager; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.SimpleCursorAdapter; import com.google.android.wikinotes.db.WikiNote; /** * Activity to list wikinotes. By default, the notes are listed in the order * of most recently modified to least recently modified. This activity can * handle requests to either show all notes, or the results of a title or body * search performed by the content provider. */ public class WikiNotesList extends ListActivity { /** * A key to store/retrieve the search criteria in a bundle */ public static final String SEARCH_CRITERIA_KEY = "SearchCriteria"; /** * The projection to use (columns to retrieve) for a query of wikinotes */ public static final String[] PROJECTION = { WikiNote.Notes._ID, WikiNote.Notes.TITLE, WikiNote.Notes.MODIFIED_DATE }; private Cursor mCursor; private WikiActivityHelper mHelper; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent = getIntent(); Uri uri = null; String query = null; // locate a query string; prefer a fresh search Intent over saved // state if (Intent.ACTION_SEARCH.equals(intent.getAction())) { query = intent.getStringExtra(SearchManager.QUERY); } else if (savedInstanceState != null) { query = savedInstanceState.getString(SearchManager.QUERY); } if (query != null && query.length() > 0) { uri = Uri.withAppendedPath(WikiNote.Notes.SEARCH_URI, Uri .encode(query)); } if (uri == null) { // somehow we got called w/o a query so fall back to a reasonable // default (all notes) uri = WikiNote.Notes.ALL_NOTES_URI; } // Do the query Cursor c = managedQuery(uri, PROJECTION, null, null, WikiNote.Notes.DEFAULT_SORT_ORDER); mCursor = c; mHelper = new WikiActivityHelper(this); // Bind the results of the search into the list ListAdapter adapter = new SimpleCursorAdapter( this, android.R.layout.simple_list_item_1, mCursor, new String[] { WikiNote.Notes.TITLE }, new int[] { android.R.id.text1 }); setListAdapter(adapter); // use the menu shortcut keys as default key bindings for the entire // activity setDefaultKeyMode(DEFAULT_KEYS_SHORTCUT); } /** * Override the onListItemClick to open the wiki note to view when it is * selected from the list. */ @Override protected void onListItemClick(ListView list, View view, int position, long id) { Cursor c = mCursor; c.moveToPosition(position); String title = c.getString(c .getColumnIndexOrThrow(WikiNote.Notes.TITLE)); // Create the URI of the note we want to view based on the title Uri uri = Uri.withAppendedPath(WikiNote.Notes.ALL_NOTES_URI, title); Intent i = new Intent(Intent.ACTION_VIEW, uri); startActivity(i); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); menu.add(0, WikiNotes.HOME_ID, 0, R.string.menu_start) .setShortcut('4', 'h').setIcon(R.drawable.icon_start); menu.add(0, WikiNotes.LIST_ID, 0, R.string.menu_recent) .setShortcut('3', 'r').setIcon(R.drawable.icon_recent); menu.add(0, WikiNotes.ABOUT_ID, 0, R.string.menu_about) .setShortcut('5', 'a').setIcon(android.R.drawable.ic_dialog_info); menu.add(0, WikiNotes.EXPORT_ID, 0, R.string.menu_export) .setShortcut('6', 'x').setIcon(android.R.drawable.ic_dialog_info); menu.add(0, WikiNotes.IMPORT_ID, 0, R.string.menu_import) .setShortcut('7', 'm').setIcon(android.R.drawable.ic_dialog_info); return true; } @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { switch (item.getItemId()) { case WikiNotes.HOME_ID: mHelper.goHome(); return true; case WikiNotes.LIST_ID: mHelper.listNotes(); return true; case WikiNotes.ABOUT_ID: Eula.showEula(this); return true; case WikiNotes.EXPORT_ID: mHelper.exportNotes(); return true; case WikiNotes.IMPORT_ID: mHelper.importNotes(); return true; default: return false; } } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.google.android.wikinotes.db; import android.content.ContentProvider; import android.content.ContentValues; import android.content.Context; import android.content.UriMatcher; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteQueryBuilder; import android.net.Uri; import android.text.TextUtils; import android.util.Log; import java.util.HashMap; /** * The Wikinotes Content Provider is the guts of the wikinotes application. It * handles Content URLs to list all wiki notes, retrieve a note by name, or * return a list of matching notes based on text in the body or the title of * the note. It also handles all set up of the database, and reports back MIME * types for the individual notes or lists of notes to help Android route the * data to activities that can display that data (in this case either the * WikiNotes activity itself, or the WikiNotesList activity to list multiple * notes). */ public class WikiNotesProvider extends ContentProvider { private DatabaseHelper dbHelper; private static final String TAG = "WikiNotesProvider"; private static final String DATABASE_NAME = "wikinotes.db"; private static final int DATABASE_VERSION = 2; private static HashMap<String, String> NOTES_LIST_PROJECTION_MAP; private static final int NOTES = 1; private static final int NOTE_NAME = 2; private static final int NOTE_SEARCH = 3; private static final UriMatcher URI_MATCHER; /** * This inner DatabaseHelper class defines methods to create and upgrade * the database from previous versions. */ private static class DatabaseHelper extends SQLiteOpenHelper { public DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE wikinotes (_id INTEGER PRIMARY KEY," + "title TEXT COLLATE LOCALIZED NOT NULL," + "body TEXT," + "created INTEGER," + "modified INTEGER" + ");"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data"); db.execSQL("DROP TABLE IF EXISTS wikinotes"); onCreate(db); } } @Override public boolean onCreate() { // On the creation of the content provider, open the database, // the Database helper will create a new version of the database // if needed through the functionality in SQLiteOpenHelper dbHelper = new DatabaseHelper(getContext()); return true; } /** * Figure out which query to run based on the URL requested and any other * parameters provided. */ @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sort) { // Query the database using the arguments provided SQLiteQueryBuilder qb = new SQLiteQueryBuilder(); String[] whereArgs = null; // What type of query are we going to use - the URL_MATCHER // defined at the bottom of this class is used to pattern-match // the URL and select the right query from the switch statement switch (URI_MATCHER.match(uri)) { case NOTES: // this match lists all notes qb.setTables("wikinotes"); qb.setProjectionMap(NOTES_LIST_PROJECTION_MAP); break; case NOTE_SEARCH: // this match searches for a text match in the body of notes qb.setTables("wikinotes"); qb.setProjectionMap(NOTES_LIST_PROJECTION_MAP); qb.appendWhere("body like ? or title like ?"); whereArgs = new String[2]; whereArgs[0] = whereArgs[1] = "%" + uri.getLastPathSegment() + "%"; break; case NOTE_NAME: // this match searches for an exact match for a specific note name qb.setTables("wikinotes"); qb.appendWhere("title=?"); whereArgs = new String[] { uri.getLastPathSegment() }; break; default: // anything else is considered and illegal request throw new IllegalArgumentException("Unknown URL " + uri); } // If no sort order is specified use the default String orderBy; if (TextUtils.isEmpty(sort)) { orderBy = WikiNote.Notes.DEFAULT_SORT_ORDER; } else { orderBy = sort; } // Run the query and return the results as a Cursor SQLiteDatabase mDb = dbHelper.getReadableDatabase(); Cursor c = qb.query(mDb, projection, null, whereArgs, null, null, orderBy); c.setNotificationUri(getContext().getContentResolver(), uri); return c; } /** * For a given URL, return a MIME type for the data that will be returned * from that URL. This will help Android decide what to do with the data * it gets back. */ @Override public String getType(Uri uri) { switch (URI_MATCHER.match(uri)) { case NOTES: case NOTE_SEARCH: // for a notes list, or search results, return a mimetype // indicating // a directory of wikinotes return "vnd.android.cursor.dir/vnd.google.wikinote"; case NOTE_NAME: // for a specific note name, return a mimetype indicating a single // item representing a wikinote return "vnd.android.cursor.item/vnd.google.wikinote"; default: // any other kind of URL is illegal throw new IllegalArgumentException("Unknown URL " + uri); } } /** * For a URL and a list of initial values, insert a row using those values * into the database. */ @Override public Uri insert(Uri uri, ContentValues initialValues) { long rowID; ContentValues values; if (initialValues != null) { values = new ContentValues(initialValues); } else { values = new ContentValues(); } // We can only insert a note, no other URLs make sense here if (URI_MATCHER.match(uri) != NOTE_NAME) { throw new IllegalArgumentException("Unknown URL " + uri); } // Update the modified time of the record Long now = Long.valueOf(System.currentTimeMillis()); // Make sure that the fields are all set if (values.containsKey(WikiNote.Notes.CREATED_DATE) == false) { values.put(WikiNote.Notes.CREATED_DATE, now); } if (values.containsKey(WikiNote.Notes.MODIFIED_DATE) == false) { values.put(WikiNote.Notes.MODIFIED_DATE, now); } if (values.containsKey(WikiNote.Notes.TITLE) == false) { values.put(WikiNote.Notes.TITLE, uri.getLastPathSegment()); } if (values.containsKey(WikiNote.Notes.BODY) == false) { values.put(WikiNote.Notes.BODY, ""); } SQLiteDatabase db = dbHelper.getWritableDatabase(); rowID = db.insert("wikinotes", "body", values); if (rowID > 0) { Uri newUri = Uri.withAppendedPath(WikiNote.Notes.ALL_NOTES_URI, uri.getLastPathSegment()); getContext().getContentResolver().notifyChange(newUri, null); return newUri; } throw new SQLException("Failed to insert row into " + uri); } /** * Delete rows matching the where clause and args for the supplied URL. * The URL can be either the all notes URL (in which case all notes * matching the where clause will be deleted), or the note name, in which * case it will delete the note with the exactly matching title. Any of * the other URLs will be rejected as invalid. For deleting notes by title * we use ReST style arguments from the URI and don't support where clause * and args. */ @Override public int delete(Uri uri, String where, String[] whereArgs) { /* This is kind of dangerous: it deletes all records with a single Intent. It might make sense to make this ContentProvider non-public, since this is kind of over-powerful and the provider isn't generally intended to be public. But for now it's still public. */ if (WikiNote.Notes.ALL_NOTES_URI.equals(uri)) { return dbHelper.getWritableDatabase().delete("wikinotes", null, null); } int count; SQLiteDatabase db = dbHelper.getWritableDatabase(); switch (URI_MATCHER.match(uri)) { case NOTES: count = db.delete("wikinotes", where, whereArgs); break; case NOTE_NAME: if (!TextUtils.isEmpty(where) || (whereArgs != null)) { throw new UnsupportedOperationException( "Cannot update note using where clause"); } String noteId = uri.getPathSegments().get(1); count = db.delete("wikinotes", "_id=?", new String[] { noteId }); break; default: throw new IllegalArgumentException("Unknown URL " + uri); } getContext().getContentResolver().notifyChange(uri, null); return count; } /** * The update method, which will allow either a mass update using a where * clause, or an update targeted to a specific note name (the latter will * be more common). Other matched URLs will be rejected as invalid. For * updating notes by title we use ReST style arguments from the URI and do * not support using the where clause or args. */ @Override public int update(Uri uri, ContentValues values, String where, String[] whereArgs) { int count; SQLiteDatabase db = dbHelper.getWritableDatabase(); switch (URI_MATCHER.match(uri)) { case NOTES: count = db.update("wikinotes", values, where, whereArgs); break; case NOTE_NAME: values.put(WikiNote.Notes.MODIFIED_DATE, System .currentTimeMillis()); count = db.update("wikinotes", values, where, whereArgs); break; default: throw new IllegalArgumentException("Unknown URL " + uri); } getContext().getContentResolver().notifyChange(uri, null); return count; } /* * This static block sets up the pattern matches for the various URIs that * this content provider can handle. It also sets up the default projection * block (which defines what columns are returned from the database for the * results of a query). */ static { URI_MATCHER = new UriMatcher(UriMatcher.NO_MATCH); URI_MATCHER.addURI(WikiNote.WIKINOTES_AUTHORITY, "wikinotes", NOTES); URI_MATCHER.addURI(WikiNote.WIKINOTES_AUTHORITY, "wikinotes/*", NOTE_NAME); URI_MATCHER.addURI(WikiNote.WIKINOTES_AUTHORITY, "wiki/search/*", NOTE_SEARCH); NOTES_LIST_PROJECTION_MAP = new HashMap<String, String>(); NOTES_LIST_PROJECTION_MAP.put(WikiNote.Notes._ID, "_id"); NOTES_LIST_PROJECTION_MAP.put(WikiNote.Notes.TITLE, "title"); NOTES_LIST_PROJECTION_MAP.put(WikiNote.Notes.BODY, "body"); NOTES_LIST_PROJECTION_MAP.put(WikiNote.Notes.CREATED_DATE, "created"); NOTES_LIST_PROJECTION_MAP.put(WikiNote.Notes.MODIFIED_DATE, "modified"); } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.wikinotes.db; import android.net.Uri; import android.provider.BaseColumns; /** * This class defines columns and URIs used in the wikinotes application */ public class WikiNote { /** * Notes table */ public static final class Notes implements BaseColumns { /** * The content:// style URI for this table - this to see all notes or * append a note name to see just the matching note. */ public static final Uri ALL_NOTES_URI = Uri .parse("content://com.google.android.wikinotes.db.wikinotes/wikinotes"); /** * This URI can be used to search the bodies of notes for an appended * search term. */ public static final Uri SEARCH_URI = Uri .parse("content://com.google.android.wikinotes.db.wikinotes/wiki/search"); /** * The default sort order for this table - most recently modified first */ public static final String DEFAULT_SORT_ORDER = "modified DESC"; /** * The title of the note * <P> * Type: TEXT * </P> */ public static final String TITLE = "title"; /** * The note body * <P> * Type: TEXT * </P> */ public static final String BODY = "body"; /** * The timestamp for when the note was created * <P> * Type: INTEGER (long) * </P> */ public static final String CREATED_DATE = "created"; /** * The timestamp for when the note was last modified * <P> * Type: INTEGER (long) * </P> */ public static final String MODIFIED_DATE = "modified"; } /** * Convenience definition for the projection we will use to retrieve columns * from the wikinotes */ public static final String[] WIKI_NOTES_PROJECTION = {Notes._ID, Notes.TITLE, Notes.BODY, Notes.MODIFIED_DATE}; public static final String[] WIKI_EXPORT_PROJECTION = {Notes.TITLE, Notes.BODY, Notes.CREATED_DATE, Notes.MODIFIED_DATE}; /** * The root authority for the WikiNotesProvider */ public static final String WIKINOTES_AUTHORITY = "com.google.android.wikinotes.db.wikinotes"; }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.google.android.wikinotes; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Calendar; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlPullParserFactory; import android.app.Activity; import android.app.AlertDialog; import android.content.ContentUris; import android.content.ContentValues; import android.content.DialogInterface; import android.content.Intent; import android.content.DialogInterface.OnClickListener; import android.database.Cursor; import android.net.Uri; import android.os.Environment; import com.google.android.wikinotes.db.WikiNote; /** * A helper class that implements operations required by Activities in the * system. Notably, this includes launching the Activities for edit and * delete. */ public class WikiActivityHelper { public static final int ACTIVITY_EDIT = 1; public static final int ACTIVITY_DELETE = 2; public static final int ACTIVITY_LIST = 3; public static final int ACTIVITY_SEARCH = 4; private Activity mContext; /** * Preferred constructor. * * @param context * the Activity to be used for things like calling * startActivity */ public WikiActivityHelper(Activity context) { mContext = context; } /** * @see #WikiActivityHelper(Activity) */ // intentionally private; tell IDEs not to warn us about it @SuppressWarnings("unused") private WikiActivityHelper() { } /** * If a list of notes is requested, fire the WikiNotes list Content URI * and let the WikiNotesList activity handle it. */ public void listNotes() { Intent i = new Intent(Intent.ACTION_VIEW, WikiNote.Notes.ALL_NOTES_URI); mContext.startActivity(i); } /** * If requested, go back to the start page wikinote by requesting an * intent with the default start page URI */ public void goHome() { Uri startPageURL = Uri .withAppendedPath(WikiNote.Notes.ALL_NOTES_URI, mContext .getResources().getString(R.string.start_page)); Intent startPage = new Intent(Intent.ACTION_VIEW, startPageURL); mContext.startActivity(startPage); } /** * Create an intent to start the WikiNoteEditor using the current title * and body information (if any). */ public void editNote(String mNoteName, Cursor cursor) { // This intent could use the android.intent.action.EDIT for a wiki // note // to invoke, but instead I wanted to demonstrate the mechanism for // invoking // an intent on a known class within the same application directly. // Note // also that the title and body of the note to edit are passed in // using // the extras bundle. Intent i = new Intent(mContext, WikiNoteEditor.class); i.putExtra(WikiNote.Notes.TITLE, mNoteName); String body; if (cursor != null) { body = cursor.getString(cursor .getColumnIndexOrThrow(WikiNote.Notes.BODY)); } else { body = ""; } i.putExtra(WikiNote.Notes.BODY, body); mContext.startActivityForResult(i, ACTIVITY_EDIT); } /** * If requested, delete the current note. The user is prompted to confirm * this operation with a dialog, and if they choose to go ahead with the * deletion, the current activity is finish()ed once the data has been * removed, so that android naturally backtracks to the previous activity. */ public void deleteNote(final Cursor cursor) { new AlertDialog.Builder(mContext) .setTitle( mContext.getResources() .getString(R.string.delete_title)) .setMessage(R.string.delete_message) .setPositiveButton(R.string.yes_button, new OnClickListener() { public void onClick(DialogInterface dialog, int arg1) { Uri noteUri = ContentUris .withAppendedId(WikiNote.Notes.ALL_NOTES_URI, cursor .getInt(0)); mContext.getContentResolver().delete(noteUri, null, null); mContext.setResult(Activity.RESULT_OK); mContext.finish(); } }).setNegativeButton(R.string.no_button, null).show(); } /** * Equivalent to showOutcomeDialog(titleId, msg, false). * * @see #showOutcomeDialog(int, String, boolean) * @param titleId * the resource ID of the title of the dialog window * @param msg * the message to display */ private void showOutcomeDialog(int titleId, String msg) { showOutcomeDialog(titleId, msg, false); } /** * Creates and displays a Dialog with the indicated title and body. If * kill is true, the Dialog calls finish() on the hosting Activity and * restarts it with an identical Intent. This effectively restarts or * refreshes the Activity, so that it can reload whatever data it was * displaying. * * @param titleId * the resource ID of the title of the dialog window * @param msg * the message to display */ private void showOutcomeDialog(int titleId, String msg, final boolean kill) { new AlertDialog.Builder(mContext).setCancelable(false) .setTitle(mContext.getResources().getString(titleId)) .setMessage(msg) .setPositiveButton(R.string.export_dismiss_button, new DialogInterface.OnClickListener() { public void onClick( DialogInterface dialog, int which) { if (kill) { // restart the Activity w/ same // Intent Intent intent = mContext .getIntent(); mContext.finish(); mContext.startActivity(intent); } } }).create().show(); } /** * Exports notes to the SD card. Displays Dialogs as appropriate (using * the Activity provided in the constructor as a Context) to inform the * user as to what is going on. */ public void exportNotes() { // first see if an SD card is even present; abort if not if (!Environment.MEDIA_MOUNTED.equals(Environment .getExternalStorageState())) { showOutcomeDialog(R.string.export_failure_title, mContext .getResources().getString(R.string.export_failure_missing_sd)); return; } // do a query for all records Cursor c = mContext.managedQuery(WikiNote.Notes.ALL_NOTES_URI, WikiNote.WIKI_EXPORT_PROJECTION, null, null, WikiNote.Notes.DEFAULT_SORT_ORDER); // iterate over all Notes, building up an XML StringBuffer along the // way boolean dataAvailable = c.moveToFirst(); StringBuffer sb = new StringBuffer(); String title, body, created, modified; int cnt = 0; sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<wiki-notes>"); while (dataAvailable) { title = c.getString(c.getColumnIndexOrThrow("title")); body = c.getString(c.getColumnIndexOrThrow("body")); modified = c.getString(c.getColumnIndexOrThrow("modified")); created = c.getString(c.getColumnIndexOrThrow("created")); // do a quick sanity check to make sure the note is worth saving if (!"".equals(title) && !"".equals(body) && title != null && body != null) { sb.append("\n").append("<note>\n\t<title><![CDATA[") .append(title).append("]]></title>\n\t<body><![CDATA["); sb.append(body).append("]]></body>\n\t<created>") .append(created).append("</created>\n\t"); sb.append("<modified>").append(modified) .append("</modified>\n</note>"); cnt++; } dataAvailable = c.moveToNext(); } sb.append("\n</wiki-notes>\n"); // open a file on the SD card under some useful name, and write out // XML FileWriter fw = null; File f = null; try { f = new File(Environment.getExternalStorageDirectory() + "/" + EXPORT_DIR); f.mkdirs(); // EXPORT_FILENAME includes current date+time, for user benefit String fileName = String.format(EXPORT_FILENAME, Calendar .getInstance()); f = new File(Environment.getExternalStorageDirectory() + "/" + EXPORT_DIR + "/" + fileName); if (!f.createNewFile()) { showOutcomeDialog(R.string.export_failure_title, mContext .getResources() .getString(R.string.export_failure_io_error)); return; } fw = new FileWriter(f); fw.write(sb.toString()); } catch (IOException e) { showOutcomeDialog(R.string.export_failure_title, mContext .getResources().getString(R.string.export_failure_io_error)); return; } finally { if (fw != null) { try { fw.close(); } catch (IOException ex) { } } } if (f == null) { showOutcomeDialog(R.string.export_failure_title, mContext .getResources().getString(R.string.export_failure_io_error)); return; } // Victory! Tell the user and display the filename just written. showOutcomeDialog(R.string.export_success_title, String .format(mContext.getResources() .getString(R.string.export_success), cnt, f.getName())); } /** * Imports records from SD card. Note that this is a destructive * operation: all existing records are destroyed. Displays confirmation * and outcome Dialogs before erasing data and after loading data. * * Note that this is the method that actually does the work; * {@link #importNotes()} is the method that should be called to kick * things off. * * @see #importNotes() */ public void doImport() { // first see if an SD card is even present; abort if not if (!Environment.MEDIA_MOUNTED.equals(Environment .getExternalStorageState())) { showOutcomeDialog(R.string.import_failure_title, mContext .getResources().getString(R.string.export_failure_missing_sd)); return; } int cnt = 0; FileReader fr = null; ArrayList<StringBuffer[]> records = new ArrayList<StringBuffer[]>(); try { // first, find the file to load fr = new FileReader(new File(Environment .getExternalStorageDirectory() + "/" + IMPORT_FILENAME)); // don't destroy data until AFTER we find a file to import! mContext.getContentResolver() .delete(WikiNote.Notes.ALL_NOTES_URI, null, null); // next, parse that sucker XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); factory.setNamespaceAware(false); XmlPullParser xpp = factory.newPullParser(); xpp.setInput(fr); int eventType = xpp.getEventType(); StringBuffer[] cur = new StringBuffer[4]; int curIdx = -1; while (eventType != XmlPullParser.END_DOCUMENT) { // save the previous note data-holder when we end a <note> tag if (eventType == XmlPullParser.END_TAG && "note".equals(xpp.getName())) { if (cur[0] != null && cur[1] != null && !"".equals(cur[0]) && !"".equals(cur[1])) { records.add(cur); } cur = new StringBuffer[4]; curIdx = -1; } else if (eventType == XmlPullParser.START_TAG && "title".equals(xpp.getName())) { curIdx = 0; } else if (eventType == XmlPullParser.START_TAG && "body".equals(xpp.getName())) { curIdx = 1; } else if (eventType == XmlPullParser.START_TAG && "created".equals(xpp.getName())) { curIdx = 2; } else if (eventType == XmlPullParser.START_TAG && "modified".equals(xpp.getName())) { curIdx = 3; } else if (eventType == XmlPullParser.TEXT && curIdx > -1) { if (cur[curIdx] == null) { cur[curIdx] = new StringBuffer(); } cur[curIdx].append(xpp.getText()); } eventType = xpp.next(); } // we stored data in a stringbuffer so we can skip empty records; // now process the successful records & save to Provider for (StringBuffer[] record : records) { Uri uri = Uri.withAppendedPath(WikiNote.Notes.ALL_NOTES_URI, record[0].toString()); ContentValues values = new ContentValues(); values.put("title", record[0].toString().trim()); values.put("body", record[1].toString().trim()); values.put("created", Long.parseLong(record[2].toString() .trim())); values.put("modified", Long.parseLong(record[3].toString() .trim())); if (mContext.getContentResolver().insert(uri, values) != null) { cnt++; } } } catch (FileNotFoundException e) { showOutcomeDialog(R.string.import_failure_title, mContext .getResources().getString(R.string.import_failure_nofile)); return; } catch (XmlPullParserException e) { showOutcomeDialog(R.string.import_failure_title, mContext .getResources().getString(R.string.import_failure_corrupt)); return; } catch (IOException e) { showOutcomeDialog(R.string.import_failure_title, mContext .getResources().getString(R.string.import_failure_io)); return; } finally { if (fr != null) { try { fr.close(); } catch (IOException e) { } } } // Victory! Inform the user. showOutcomeDialog(R.string.import_success_title, String .format(mContext.getResources() .getString(R.string.import_success), cnt), true); } /** * Starts a note import. Essentially this method just displays a Dialog * requesting confirmation from the user for the destructive operation. If * the user confirms, {@link #doImport()} is called. * * @see #doImport() */ public void importNotes() { new AlertDialog.Builder(mContext).setCancelable(true) .setTitle( mContext.getResources() .getString(R.string.import_confirm_title)) .setMessage(R.string.import_confirm_body) .setPositiveButton(R.string.import_confirm_button, new DialogInterface.OnClickListener() { public void onClick(DialogInterface arg0, int arg1) { doImport(); } }) .setNegativeButton(R.string.import_cancel_button, null).create() .show(); } /** * Launches the email system client to send a mail with the current * message. */ public void mailNote(final Cursor cursor) { Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("message/rfc822"); intent.putExtra(Intent.EXTRA_SUBJECT, cursor.getString(cursor .getColumnIndexOrThrow("title"))); String body = String.format(mContext.getResources() .getString(R.string.email_leader), cursor.getString(cursor .getColumnIndexOrThrow("body"))); intent.putExtra(Intent.EXTRA_TEXT, body); mContext.startActivity(Intent.createChooser(intent, "Title:")); } /* Some constants for filename structures. Could conceivably go into * strings.xml, but these don't need to be internationalized, so... */ private static final String EXPORT_DIR = "WikiNotes"; private static final String EXPORT_FILENAME = "WikiNotes_%1$tY-%1$tm-%1$td_%1$tH-%1$tM-%1$tS.xml"; private static final String IMPORT_FILENAME = "WikiNotes-import.xml"; }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.wikinotes; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import com.google.android.wikinotes.db.WikiNote; /** * Wikinote editor activity. This is a very simple activity that allows the user * to edit a wikinote using a text editor and confirm or cancel the changes. The * title and body for the wikinote to edit are passed in using the extras bundle * and the onFreeze() method provisions for those values to be stored in the * icicle on a lifecycle event, so that the user retains control over whether * the changes are committed to the database. */ public class WikiNoteEditor extends Activity { protected static final String ACTIVITY_RESULT = "com.google.android.wikinotes.EDIT"; private EditText mNoteEdit; private String mWikiNoteTitle; @Override protected void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.wiki_note_edit); mNoteEdit = (EditText) findViewById(R.id.noteEdit); // Check to see if the icicle has body and title values to restore String wikiNoteText = icicle == null ? null : icicle.getString(WikiNote.Notes.BODY); String wikiNoteTitle = icicle == null ? null : icicle.getString(WikiNote.Notes.TITLE); // If not, check to see if the extras bundle has these values passed in if (wikiNoteTitle == null) { Bundle extras = getIntent().getExtras(); wikiNoteText = extras == null ? null : extras .getString(WikiNote.Notes.BODY); wikiNoteTitle = extras == null ? null : extras .getString(WikiNote.Notes.TITLE); } // If we have no title information, this is an invalid intent request if (TextUtils.isEmpty(wikiNoteTitle)) { // no note title - bail setResult(RESULT_CANCELED); finish(); return; } mWikiNoteTitle = wikiNoteTitle; // but if the body is null, just set it to empty - first edit of this // note wikiNoteText = wikiNoteText == null ? "" : wikiNoteText; // set the title so we know which note we are editing setTitle(getString(R.string.wiki_editing, wikiNoteTitle)); // set the note body to edit mNoteEdit.setText(wikiNoteText); // set listeners for the confirm and cancel buttons ((Button) findViewById(R.id.confirmButton)) .setOnClickListener(new OnClickListener() { public void onClick(View view) { Intent i = new Intent(); i.putExtra(ACTIVITY_RESULT, mNoteEdit.getText() .toString()); setResult(RESULT_OK, i); finish(); } }); ((Button) findViewById(R.id.cancelButton)) .setOnClickListener(new OnClickListener() { public void onClick(View view) { setResult(RESULT_CANCELED); finish(); } }); if (!getSharedPreferences(Eula.PREFERENCES_EULA, Activity.MODE_PRIVATE) .getBoolean(Eula.PREFERENCE_EULA_ACCEPTED, false)) { Eula.showEula(this); } } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putString(WikiNote.Notes.TITLE, mWikiNoteTitle); outState.putString(WikiNote.Notes.BODY, mNoteEdit.getText().toString()); } }
Java
/* * Copyright (C) 2007 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.opengles.spritetext; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.Paint.Style; import android.graphics.drawable.Drawable; import android.opengl.GLUtils; import java.util.ArrayList; import javax.microedition.khronos.opengles.GL10; import javax.microedition.khronos.opengles.GL11; import javax.microedition.khronos.opengles.GL11Ext; /** * An OpenGL text label maker. * * * OpenGL labels are implemented by creating a Bitmap, drawing all the labels * into the Bitmap, converting the Bitmap into an Alpha texture, and creating a * mesh for each label * * The benefits of this approach are that the labels are drawn using the high * quality anti-aliased font rasterizer, full character set support, and all the * text labels are stored on a single texture, which makes it faster to use. * * The drawbacks are that you can only have as many labels as will fit onto one * texture, and you have to recreate the whole texture if any label text * changes. * */ public class LabelMaker { /** * Create a label maker * or maximum compatibility with various OpenGL ES implementations, * the strike width and height must be powers of two, * We want the strike width to be at least as wide as the widest window. * * @param fullColor true if we want a full color backing store (4444), * otherwise we generate a grey L8 backing store. * @param strikeWidth width of strike * @param strikeHeight height of strike */ public LabelMaker(boolean fullColor, int strikeWidth, int strikeHeight) { mFullColor = fullColor; mStrikeWidth = strikeWidth; mStrikeHeight = strikeHeight; mTexelWidth = (float) (1.0 / mStrikeWidth); mTexelHeight = (float) (1.0 / mStrikeHeight); mClearPaint = new Paint(); mClearPaint.setARGB(0, 0, 0, 0); mClearPaint.setStyle(Style.FILL); mState = STATE_NEW; } /** * Call to initialize the class. * Call whenever the surface has been created. * * @param gl */ public void initialize(GL10 gl) { mState = STATE_INITIALIZED; int[] textures = new int[1]; gl.glGenTextures(1, textures, 0); mTextureID = textures[0]; gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureID); // Use Nearest for performance. gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_NEAREST); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_CLAMP_TO_EDGE); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_CLAMP_TO_EDGE); gl.glTexEnvf(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE, GL10.GL_REPLACE); } /** * Call when the surface has been destroyed */ public void shutdown(GL10 gl) { if ( gl != null) { if (mState > STATE_NEW) { int[] textures = new int[1]; textures[0] = mTextureID; gl.glDeleteTextures(1, textures, 0); mState = STATE_NEW; } } } /** * Call before adding labels. Clears out any existing labels. * * @param gl */ public void beginAdding(GL10 gl) { checkState(STATE_INITIALIZED, STATE_ADDING); mLabels.clear(); mU = 0; mV = 0; mLineHeight = 0; Bitmap.Config config = mFullColor ? Bitmap.Config.ARGB_4444 : Bitmap.Config.ALPHA_8; mBitmap = Bitmap.createBitmap(mStrikeWidth, mStrikeHeight, config); mCanvas = new Canvas(mBitmap); mBitmap.eraseColor(0); } /** * Call to add a label * * @param gl * @param text the text of the label * @param textPaint the paint of the label * @return the id of the label, used to measure and draw the label */ public int add(GL10 gl, String text, Paint textPaint) { return add(gl, null, text, textPaint); } /** * Call to add a label * * @param gl * @param text the text of the label * @param textPaint the paint of the label * @return the id of the label, used to measure and draw the label */ public int add(GL10 gl, Drawable background, String text, Paint textPaint) { return add(gl, background, text, textPaint, 0, 0); } /** * Call to add a label * @return the id of the label, used to measure and draw the label */ public int add(GL10 gl, Drawable drawable, int minWidth, int minHeight) { return add(gl, drawable, null, null, minWidth, minHeight); } /** * Call to add a label * * @param gl * @param text the text of the label * @param textPaint the paint of the label * @return the id of the label, used to measure and draw the label */ public int add(GL10 gl, Drawable background, String text, Paint textPaint, int minWidth, int minHeight) { checkState(STATE_ADDING, STATE_ADDING); boolean drawBackground = background != null; boolean drawText = (text != null) && (textPaint != null); Rect padding = new Rect(); if (drawBackground) { background.getPadding(padding); minWidth = Math.max(minWidth, background.getMinimumWidth()); minHeight = Math.max(minHeight, background.getMinimumHeight()); } int ascent = 0; int descent = 0; int measuredTextWidth = 0; if (drawText) { // Paint.ascent is negative, so negate it. ascent = (int) Math.ceil(-textPaint.ascent()); descent = (int) Math.ceil(textPaint.descent()); measuredTextWidth = (int) Math.ceil(textPaint.measureText(text)); } int textHeight = ascent + descent; int textWidth = Math.min(mStrikeWidth,measuredTextWidth); int padHeight = padding.top + padding.bottom; int padWidth = padding.left + padding.right; int height = Math.max(minHeight, textHeight + padHeight); int width = Math.max(minWidth, textWidth + padWidth); int effectiveTextHeight = height - padHeight; int effectiveTextWidth = width - padWidth; int centerOffsetHeight = (effectiveTextHeight - textHeight) / 2; int centerOffsetWidth = (effectiveTextWidth - textWidth) / 2; // Make changes to the local variables, only commit them // to the member variables after we've decided not to throw // any exceptions. int u = mU; int v = mV; int lineHeight = mLineHeight; if (width > mStrikeWidth) { width = mStrikeWidth; } // Is there room for this string on the current line? if (u + width > mStrikeWidth) { // No room, go to the next line: u = 0; v += lineHeight; lineHeight = 0; } lineHeight = Math.max(lineHeight, height); if (v + lineHeight > mStrikeHeight) { throw new IllegalArgumentException("Out of texture space."); } int u2 = u + width; int vBase = v + ascent; int v2 = v + height; if (drawBackground) { background.setBounds(u, v, u + width, v + height); background.draw(mCanvas); } if (drawText) { mCanvas.drawText(text, u + padding.left + centerOffsetWidth, vBase + padding.top + centerOffsetHeight, textPaint); } Grid grid = new Grid(2, 2); // Grid.set arguments: i, j, x, y, z, u, v float texU = u * mTexelWidth; float texU2 = u2 * mTexelWidth; float texV = 1.0f - v * mTexelHeight; float texV2 = 1.0f - v2 * mTexelHeight; grid.set(0, 0, 0.0f, 0.0f, 0.0f, texU , texV2); grid.set(1, 0, width, 0.0f, 0.0f, texU2, texV2); grid.set(0, 1, 0.0f, height, 0.0f, texU , texV ); grid.set(1, 1, width, height, 0.0f, texU2, texV ); // We know there's enough space, so update the member variables mU = u + width; mV = v; mLineHeight = lineHeight; mLabels.add(new Label(grid, width, height, ascent, u, v + height, width, -height)); return mLabels.size() - 1; } /** * Call to end adding labels. Must be called before drawing starts. * * @param gl */ public void endAdding(GL10 gl) { checkState(STATE_ADDING, STATE_INITIALIZED); gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureID); GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, mBitmap, 0); // Reclaim storage used by bitmap and canvas. mBitmap.recycle(); mBitmap = null; mCanvas = null; } /** * Get the width in pixels of a given label. * * @param labelID * @return the width in pixels */ public float getWidth(int labelID) { return mLabels.get(labelID).width; } /** * Get the height in pixels of a given label. * * @param labelID * @return the height in pixels */ public float getHeight(int labelID) { return mLabels.get(labelID).height; } /** * Get the baseline of a given label. That's how many pixels from the top of * the label to the text baseline. (This is equivalent to the negative of * the label's paint's ascent.) * * @param labelID * @return the baseline in pixels. */ public float getBaseline(int labelID) { return mLabels.get(labelID).baseline; } /** * Begin drawing labels. Sets the OpenGL state for rapid drawing. * * @param gl * @param viewWidth * @param viewHeight */ public void beginDrawing(GL10 gl, float viewWidth, float viewHeight) { checkState(STATE_INITIALIZED, STATE_DRAWING); gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureID); gl.glShadeModel(GL10.GL_FLAT); gl.glEnable(GL10.GL_BLEND); gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); gl.glColor4x(0x10000, 0x10000, 0x10000, 0x10000); gl.glMatrixMode(GL10.GL_PROJECTION); gl.glPushMatrix(); gl.glLoadIdentity(); gl.glOrthof(0.0f, viewWidth, 0.0f, viewHeight, 0.0f, 1.0f); gl.glMatrixMode(GL10.GL_MODELVIEW); gl.glPushMatrix(); gl.glLoadIdentity(); // Magic offsets to promote consistent rasterization. gl.glTranslatef(0.375f, 0.375f, 0.0f); } /** * Draw a given label at a given x,y position, expressed in pixels, with the * lower-left-hand-corner of the view being (0,0). * * @param gl * @param x * @param y * @param labelID */ public void draw(GL10 gl, float x, float y, int labelID) { checkState(STATE_DRAWING, STATE_DRAWING); gl.glPushMatrix(); float snappedX = (float) Math.floor(x); float snappedY = (float) Math.floor(y); gl.glTranslatef(snappedX, snappedY, 0.0f); Label label = mLabels.get(labelID); gl.glEnable(GL10.GL_TEXTURE_2D); ((GL11)gl).glTexParameteriv(GL10.GL_TEXTURE_2D, GL11Ext.GL_TEXTURE_CROP_RECT_OES, label.mCrop, 0); ((GL11Ext)gl).glDrawTexiOES((int) snappedX, (int) snappedY, 0, (int) label.width, (int) label.height); gl.glPopMatrix(); } /** * Ends the drawing and restores the OpenGL state. * * @param gl */ public void endDrawing(GL10 gl) { checkState(STATE_DRAWING, STATE_INITIALIZED); gl.glDisable(GL10.GL_BLEND); gl.glMatrixMode(GL10.GL_PROJECTION); gl.glPopMatrix(); gl.glMatrixMode(GL10.GL_MODELVIEW); gl.glPopMatrix(); } private void checkState(int oldState, int newState) { if (mState != oldState) { throw new IllegalArgumentException("Can't call this method now."); } mState = newState; } private static class Label { public Label(Grid grid, float width, float height, float baseLine, int cropU, int cropV, int cropW, int cropH) { this.grid = grid; this.width = width; this.height = height; this.baseline = baseLine; int[] crop = new int[4]; crop[0] = cropU; crop[1] = cropV; crop[2] = cropW; crop[3] = cropH; mCrop = crop; } public Grid grid; public float width; public float height; public float baseline; public int[] mCrop; } private int mStrikeWidth; private int mStrikeHeight; private boolean mFullColor; private Bitmap mBitmap; private Canvas mCanvas; private Paint mClearPaint; private int mTextureID; private float mTexelWidth; // Convert texel to U private float mTexelHeight; // Convert texel to V private int mU; private int mV; private int mLineHeight; private ArrayList<Label> mLabels = new ArrayList<Label>(); private static final int STATE_NEW = 0; private static final int STATE_INITIALIZED = 1; private static final int STATE_ADDING = 2; private static final int STATE_DRAWING = 3; private int mState; }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.opengles.spritetext; import javax.microedition.khronos.opengles.GL10; import android.graphics.Paint; public class NumericSprite { public NumericSprite() { mText = ""; mLabelMaker = null; } public void initialize(GL10 gl, Paint paint) { int height = roundUpPower2((int) paint.getFontSpacing()); final float interDigitGaps = 9 * 1.0f; int width = roundUpPower2((int) (interDigitGaps + paint.measureText(sStrike))); mLabelMaker = new LabelMaker(true, width, height); mLabelMaker.initialize(gl); mLabelMaker.beginAdding(gl); for (int i = 0; i < 10; i++) { String digit = sStrike.substring(i, i+1); mLabelId[i] = mLabelMaker.add(gl, digit, paint); mWidth[i] = (int) Math.ceil(mLabelMaker.getWidth(i)); } mLabelMaker.endAdding(gl); } public void shutdown(GL10 gl) { mLabelMaker.shutdown(gl); mLabelMaker = null; } /** * Find the smallest power of two >= the input value. * (Doesn't work for negative numbers.) */ private int roundUpPower2(int x) { x = x - 1; x = x | (x >> 1); x = x | (x >> 2); x = x | (x >> 4); x = x | (x >> 8); x = x | (x >>16); return x + 1; } public void setValue(int value) { mText = format(value); } public void draw(GL10 gl, float x, float y, float viewWidth, float viewHeight) { int length = mText.length(); mLabelMaker.beginDrawing(gl, viewWidth, viewHeight); for(int i = 0; i < length; i++) { char c = mText.charAt(i); int digit = c - '0'; mLabelMaker.draw(gl, x, y, mLabelId[digit]); x += mWidth[digit]; } mLabelMaker.endDrawing(gl); } public float width() { float width = 0.0f; int length = mText.length(); for(int i = 0; i < length; i++) { char c = mText.charAt(i); width += mWidth[c - '0']; } return width; } private String format(int value) { return Integer.toString(value); } private LabelMaker mLabelMaker; private String mText; private int[] mWidth = new int[10]; private int[] mLabelId = new int[10]; private final static String sStrike = "0123456789"; }
Java
/* * Copyright (C) 2007 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.opengles.spritetext; import java.nio.CharBuffer; import java.nio.FloatBuffer; import javax.microedition.khronos.opengles.GL10; /** * A 2D rectangular mesh. Can be drawn textured or untextured. * */ class Grid { public Grid(int w, int h) { if (w < 0 || w >= 65536) { throw new IllegalArgumentException("w"); } if (h < 0 || h >= 65536) { throw new IllegalArgumentException("h"); } if (w * h >= 65536) { throw new IllegalArgumentException("w * h >= 65536"); } mW = w; mH = h; int size = w * h; mVertexArray = new float[size * 3]; mVertexBuffer = FloatBuffer.wrap(mVertexArray); mTexCoordArray = new float[size * 2]; mTexCoordBuffer = FloatBuffer.wrap(mTexCoordArray); int quadW = mW - 1; int quadH = mH - 1; int quadCount = quadW * quadH; int indexCount = quadCount * 6; mIndexCount = indexCount; char[] indexArray = new char[indexCount]; /* * Initialize triangle list mesh. * * [0]-----[ 1] ... * | / | * | / | * | / | * [w]-----[w+1] ... * | | * */ { int i = 0; for (int y = 0; y < quadH; y++) { for (int x = 0; x < quadW; x++) { char a = (char) (y * mW + x); char b = (char) (y * mW + x + 1); char c = (char) ((y + 1) * mW + x); char d = (char) ((y + 1) * mW + x + 1); indexArray[i++] = a; indexArray[i++] = b; indexArray[i++] = c; indexArray[i++] = b; indexArray[i++] = c; indexArray[i++] = d; } } } mIndexBuffer = CharBuffer.wrap(indexArray); } void set(int i, int j, float x, float y, float z, float u, float v) { if (i < 0 || i >= mW) { throw new IllegalArgumentException("i"); } if (j < 0 || j >= mH) { throw new IllegalArgumentException("j"); } int index = mW * j + i; int posIndex = index * 3; mVertexArray[posIndex] = x; mVertexArray[posIndex + 1] = y; mVertexArray[posIndex + 2] = z; int texIndex = index * 2; mTexCoordArray[texIndex] = u; mTexCoordArray[texIndex + 1] = v; } public void draw(GL10 gl, boolean useTexture) { gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); gl.glVertexPointer(3, GL10.GL_FLOAT, 0, mVertexBuffer); if (useTexture) { gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY); gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, mTexCoordBuffer); gl.glEnable(GL10.GL_TEXTURE_2D); } else { gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY); gl.glDisable(GL10.GL_TEXTURE_2D); } gl.glDrawElements(GL10.GL_TRIANGLES, mIndexCount, GL10.GL_UNSIGNED_SHORT, mIndexBuffer); gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); } private FloatBuffer mVertexBuffer; private float[] mVertexArray; private FloatBuffer mTexCoordBuffer; private float[] mTexCoordArray; private CharBuffer mIndexBuffer; private int mW; private int mH; private int mIndexCount; }
Java
/* * Copyright (C) 2007 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.opengles.spritetext; import android.opengl.Matrix; import javax.microedition.khronos.opengles.GL10; /** * A utility that projects * */ class Projector { public Projector() { mMVP = new float[16]; mV = new float[4]; mGrabber = new MatrixGrabber(); } public void setCurrentView(int x, int y, int width, int height) { mX = x; mY = y; mViewWidth = width; mViewHeight = height; } public void project(float[] obj, int objOffset, float[] win, int winOffset) { if (!mMVPComputed) { Matrix.multiplyMM(mMVP, 0, mGrabber.mProjection, 0, mGrabber.mModelView, 0); mMVPComputed = true; } Matrix.multiplyMV(mV, 0, mMVP, 0, obj, objOffset); float rw = 1.0f / mV[3]; win[winOffset] = mX + mViewWidth * (mV[0] * rw + 1.0f) * 0.5f; win[winOffset + 1] = mY + mViewHeight * (mV[1] * rw + 1.0f) * 0.5f; win[winOffset + 2] = (mV[2] * rw + 1.0f) * 0.5f; } /** * Get the current projection matrix. Has the side-effect of * setting current matrix mode to GL_PROJECTION * @param gl */ public void getCurrentProjection(GL10 gl) { mGrabber.getCurrentProjection(gl); mMVPComputed = false; } /** * Get the current model view matrix. Has the side-effect of * setting current matrix mode to GL_MODELVIEW * @param gl */ public void getCurrentModelView(GL10 gl) { mGrabber.getCurrentModelView(gl); mMVPComputed = false; } private MatrixGrabber mGrabber; private boolean mMVPComputed; private float[] mMVP; private float[] mV; private int mX; private int mY; private int mViewWidth; private int mViewHeight; }
Java
/* * Copyright (C) 2007 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.opengles.spritetext; import javax.microedition.khronos.opengles.GL10; class MatrixGrabber { public MatrixGrabber() { mModelView = new float[16]; mProjection = new float[16]; } /** * Record the current modelView and projection matrix state. * Has the side effect of setting the current matrix state to GL_MODELVIEW * @param gl */ public void getCurrentState(GL10 gl) { getCurrentProjection(gl); getCurrentModelView(gl); } /** * Record the current modelView matrix state. Has the side effect of * setting the current matrix state to GL_MODELVIEW * @param gl */ public void getCurrentModelView(GL10 gl) { getMatrix(gl, GL10.GL_MODELVIEW, mModelView); } /** * Record the current projection matrix state. Has the side effect of * setting the current matrix state to GL_PROJECTION * @param gl */ public void getCurrentProjection(GL10 gl) { getMatrix(gl, GL10.GL_PROJECTION, mProjection); } private void getMatrix(GL10 gl, int mode, float[] mat) { MatrixTrackingGL gl2 = (MatrixTrackingGL) gl; gl2.glMatrixMode(mode); gl2.getMatrix(mat, 0); } public float[] mModelView; public float[] mProjection; }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.opengles.spritetext; import javax.microedition.khronos.opengles.GL; import android.app.Activity; import android.os.Bundle; public class SpriteTextActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mGLView = (GLView) findViewById(R.id.glview); mGLView.setGLWrapper(new GLView.GLWrapper() { public GL wrap(GL gl) { return new MatrixTrackingGL(gl); }}); mGLView.setRenderer(new SpriteTextRenderer(this)); mGLView.requestFocus(); } @Override protected void onPause() { super.onPause(); mGLView.onPause(); } @Override protected void onResume() { super.onResume(); mGLView.onResume(); } private GLView mGLView; }
Java
/* * Copyright (C) 2007 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.opengles.spritetext; import android.util.Log; import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.nio.ShortBuffer; import javax.microedition.khronos.opengles.GL; import javax.microedition.khronos.opengles.GL10; import javax.microedition.khronos.opengles.GL10Ext; import javax.microedition.khronos.opengles.GL11; import javax.microedition.khronos.opengles.GL11Ext; /** * Allows retrieving the current matrix even if the current OpenGL ES * driver does not support retrieving the current matrix. * * Note: the actual matrix may differ from the retrieved matrix, due * to differences in the way the math is implemented by GLMatrixWrapper * as compared to the way the math is implemented by the OpenGL ES * driver. */ class MatrixTrackingGL implements GL, GL10, GL10Ext, GL11, GL11Ext { private GL10 mgl; private GL10Ext mgl10Ext; private GL11 mgl11; private GL11Ext mgl11Ext; private int mMatrixMode; private MatrixStack mCurrent; private MatrixStack mModelView; private MatrixStack mTexture; private MatrixStack mProjection; private final static boolean _check = false; ByteBuffer mByteBuffer; FloatBuffer mFloatBuffer; float[] mCheckA; float[] mCheckB; public MatrixTrackingGL(GL gl) { mgl = (GL10) gl; if (gl instanceof GL10Ext) { mgl10Ext = (GL10Ext) gl; } if (gl instanceof GL11) { mgl11 = (GL11) gl; } if (gl instanceof GL11Ext) { mgl11Ext = (GL11Ext) gl; } mModelView = new MatrixStack(); mProjection = new MatrixStack(); mTexture = new MatrixStack(); mCurrent = mModelView; mMatrixMode = GL10.GL_MODELVIEW; } // --------------------------------------------------------------------- // GL10 methods: public void glActiveTexture(int texture) { mgl.glActiveTexture(texture); } public void glAlphaFunc(int func, float ref) { mgl.glAlphaFunc(func, ref); } public void glAlphaFuncx(int func, int ref) { mgl.glAlphaFuncx(func, ref); } public void glBindTexture(int target, int texture) { mgl.glBindTexture(target, texture); } public void glBlendFunc(int sfactor, int dfactor) { mgl.glBlendFunc(sfactor, dfactor); } public void glClear(int mask) { mgl.glClear(mask); } public void glClearColor(float red, float green, float blue, float alpha) { mgl.glClearColor(red, green, blue, alpha); } public void glClearColorx(int red, int green, int blue, int alpha) { mgl.glClearColorx(red, green, blue, alpha); } public void glClearDepthf(float depth) { mgl.glClearDepthf(depth); } public void glClearDepthx(int depth) { mgl.glClearDepthx(depth); } public void glClearStencil(int s) { mgl.glClearStencil(s); } public void glClientActiveTexture(int texture) { mgl.glClientActiveTexture(texture); } public void glColor4f(float red, float green, float blue, float alpha) { mgl.glColor4f(red, green, blue, alpha); } public void glColor4x(int red, int green, int blue, int alpha) { mgl.glColor4x(red, green, blue, alpha); } public void glColorMask(boolean red, boolean green, boolean blue, boolean alpha) { mgl.glColorMask(red, green, blue, alpha); } public void glColorPointer(int size, int type, int stride, Buffer pointer) { mgl.glColorPointer(size, type, stride, pointer); } public void glCompressedTexImage2D(int target, int level, int internalformat, int width, int height, int border, int imageSize, Buffer data) { mgl.glCompressedTexImage2D(target, level, internalformat, width, height, border, imageSize, data); } public void glCompressedTexSubImage2D(int target, int level, int xoffset, int yoffset, int width, int height, int format, int imageSize, Buffer data) { mgl.glCompressedTexSubImage2D(target, level, xoffset, yoffset, width, height, format, imageSize, data); } public void glCopyTexImage2D(int target, int level, int internalformat, int x, int y, int width, int height, int border) { mgl.glCopyTexImage2D(target, level, internalformat, x, y, width, height, border); } public void glCopyTexSubImage2D(int target, int level, int xoffset, int yoffset, int x, int y, int width, int height) { mgl.glCopyTexSubImage2D(target, level, xoffset, yoffset, x, y, width, height); } public void glCullFace(int mode) { mgl.glCullFace(mode); } public void glDeleteTextures(int n, int[] textures, int offset) { mgl.glDeleteTextures(n, textures, offset); } public void glDeleteTextures(int n, IntBuffer textures) { mgl.glDeleteTextures(n, textures); } public void glDepthFunc(int func) { mgl.glDepthFunc(func); } public void glDepthMask(boolean flag) { mgl.glDepthMask(flag); } public void glDepthRangef(float near, float far) { mgl.glDepthRangef(near, far); } public void glDepthRangex(int near, int far) { mgl.glDepthRangex(near, far); } public void glDisable(int cap) { mgl.glDisable(cap); } public void glDisableClientState(int array) { mgl.glDisableClientState(array); } public void glDrawArrays(int mode, int first, int count) { mgl.glDrawArrays(mode, first, count); } public void glDrawElements(int mode, int count, int type, Buffer indices) { mgl.glDrawElements(mode, count, type, indices); } public void glEnable(int cap) { mgl.glEnable(cap); } public void glEnableClientState(int array) { mgl.glEnableClientState(array); } public void glFinish() { mgl.glFinish(); } public void glFlush() { mgl.glFlush(); } public void glFogf(int pname, float param) { mgl.glFogf(pname, param); } public void glFogfv(int pname, float[] params, int offset) { mgl.glFogfv(pname, params, offset); } public void glFogfv(int pname, FloatBuffer params) { mgl.glFogfv(pname, params); } public void glFogx(int pname, int param) { mgl.glFogx(pname, param); } public void glFogxv(int pname, int[] params, int offset) { mgl.glFogxv(pname, params, offset); } public void glFogxv(int pname, IntBuffer params) { mgl.glFogxv(pname, params); } public void glFrontFace(int mode) { mgl.glFrontFace(mode); } public void glFrustumf(float left, float right, float bottom, float top, float near, float far) { mCurrent.glFrustumf(left, right, bottom, top, near, far); mgl.glFrustumf(left, right, bottom, top, near, far); if ( _check) check(); } public void glFrustumx(int left, int right, int bottom, int top, int near, int far) { mCurrent.glFrustumx(left, right, bottom, top, near, far); mgl.glFrustumx(left, right, bottom, top, near, far); if ( _check) check(); } public void glGenTextures(int n, int[] textures, int offset) { mgl.glGenTextures(n, textures, offset); } public void glGenTextures(int n, IntBuffer textures) { mgl.glGenTextures(n, textures); } public int glGetError() { int result = mgl.glGetError(); return result; } public void glGetIntegerv(int pname, int[] params, int offset) { mgl.glGetIntegerv(pname, params, offset); } public void glGetIntegerv(int pname, IntBuffer params) { mgl.glGetIntegerv(pname, params); } public String glGetString(int name) { String result = mgl.glGetString(name); return result; } public void glHint(int target, int mode) { mgl.glHint(target, mode); } public void glLightModelf(int pname, float param) { mgl.glLightModelf(pname, param); } public void glLightModelfv(int pname, float[] params, int offset) { mgl.glLightModelfv(pname, params, offset); } public void glLightModelfv(int pname, FloatBuffer params) { mgl.glLightModelfv(pname, params); } public void glLightModelx(int pname, int param) { mgl.glLightModelx(pname, param); } public void glLightModelxv(int pname, int[] params, int offset) { mgl.glLightModelxv(pname, params, offset); } public void glLightModelxv(int pname, IntBuffer params) { mgl.glLightModelxv(pname, params); } public void glLightf(int light, int pname, float param) { mgl.glLightf(light, pname, param); } public void glLightfv(int light, int pname, float[] params, int offset) { mgl.glLightfv(light, pname, params, offset); } public void glLightfv(int light, int pname, FloatBuffer params) { mgl.glLightfv(light, pname, params); } public void glLightx(int light, int pname, int param) { mgl.glLightx(light, pname, param); } public void glLightxv(int light, int pname, int[] params, int offset) { mgl.glLightxv(light, pname, params, offset); } public void glLightxv(int light, int pname, IntBuffer params) { mgl.glLightxv(light, pname, params); } public void glLineWidth(float width) { mgl.glLineWidth(width); } public void glLineWidthx(int width) { mgl.glLineWidthx(width); } public void glLoadIdentity() { mCurrent.glLoadIdentity(); mgl.glLoadIdentity(); if ( _check) check(); } public void glLoadMatrixf(float[] m, int offset) { mCurrent.glLoadMatrixf(m, offset); mgl.glLoadMatrixf(m, offset); if ( _check) check(); } public void glLoadMatrixf(FloatBuffer m) { int position = m.position(); mCurrent.glLoadMatrixf(m); m.position(position); mgl.glLoadMatrixf(m); if ( _check) check(); } public void glLoadMatrixx(int[] m, int offset) { mCurrent.glLoadMatrixx(m, offset); mgl.glLoadMatrixx(m, offset); if ( _check) check(); } public void glLoadMatrixx(IntBuffer m) { int position = m.position(); mCurrent.glLoadMatrixx(m); m.position(position); mgl.glLoadMatrixx(m); if ( _check) check(); } public void glLogicOp(int opcode) { mgl.glLogicOp(opcode); } public void glMaterialf(int face, int pname, float param) { mgl.glMaterialf(face, pname, param); } public void glMaterialfv(int face, int pname, float[] params, int offset) { mgl.glMaterialfv(face, pname, params, offset); } public void glMaterialfv(int face, int pname, FloatBuffer params) { mgl.glMaterialfv(face, pname, params); } public void glMaterialx(int face, int pname, int param) { mgl.glMaterialx(face, pname, param); } public void glMaterialxv(int face, int pname, int[] params, int offset) { mgl.glMaterialxv(face, pname, params, offset); } public void glMaterialxv(int face, int pname, IntBuffer params) { mgl.glMaterialxv(face, pname, params); } public void glMatrixMode(int mode) { switch (mode) { case GL10.GL_MODELVIEW: mCurrent = mModelView; break; case GL10.GL_TEXTURE: mCurrent = mTexture; break; case GL10.GL_PROJECTION: mCurrent = mProjection; break; default: throw new IllegalArgumentException("Unknown matrix mode: " + mode); } mgl.glMatrixMode(mode); mMatrixMode = mode; if ( _check) check(); } public void glMultMatrixf(float[] m, int offset) { mCurrent.glMultMatrixf(m, offset); mgl.glMultMatrixf(m, offset); if ( _check) check(); } public void glMultMatrixf(FloatBuffer m) { int position = m.position(); mCurrent.glMultMatrixf(m); m.position(position); mgl.glMultMatrixf(m); if ( _check) check(); } public void glMultMatrixx(int[] m, int offset) { mCurrent.glMultMatrixx(m, offset); mgl.glMultMatrixx(m, offset); if ( _check) check(); } public void glMultMatrixx(IntBuffer m) { int position = m.position(); mCurrent.glMultMatrixx(m); m.position(position); mgl.glMultMatrixx(m); if ( _check) check(); } public void glMultiTexCoord4f(int target, float s, float t, float r, float q) { mgl.glMultiTexCoord4f(target, s, t, r, q); } public void glMultiTexCoord4x(int target, int s, int t, int r, int q) { mgl.glMultiTexCoord4x(target, s, t, r, q); } public void glNormal3f(float nx, float ny, float nz) { mgl.glNormal3f(nx, ny, nz); } public void glNormal3x(int nx, int ny, int nz) { mgl.glNormal3x(nx, ny, nz); } public void glNormalPointer(int type, int stride, Buffer pointer) { mgl.glNormalPointer(type, stride, pointer); } public void glOrthof(float left, float right, float bottom, float top, float near, float far) { mCurrent.glOrthof(left, right, bottom, top, near, far); mgl.glOrthof(left, right, bottom, top, near, far); if ( _check) check(); } public void glOrthox(int left, int right, int bottom, int top, int near, int far) { mCurrent.glOrthox(left, right, bottom, top, near, far); mgl.glOrthox(left, right, bottom, top, near, far); if ( _check) check(); } public void glPixelStorei(int pname, int param) { mgl.glPixelStorei(pname, param); } public void glPointSize(float size) { mgl.glPointSize(size); } public void glPointSizex(int size) { mgl.glPointSizex(size); } public void glPolygonOffset(float factor, float units) { mgl.glPolygonOffset(factor, units); } public void glPolygonOffsetx(int factor, int units) { mgl.glPolygonOffsetx(factor, units); } public void glPopMatrix() { mCurrent.glPopMatrix(); mgl.glPopMatrix(); if ( _check) check(); } public void glPushMatrix() { mCurrent.glPushMatrix(); mgl.glPushMatrix(); if ( _check) check(); } public void glReadPixels(int x, int y, int width, int height, int format, int type, Buffer pixels) { mgl.glReadPixels(x, y, width, height, format, type, pixels); } public void glRotatef(float angle, float x, float y, float z) { mCurrent.glRotatef(angle, x, y, z); mgl.glRotatef(angle, x, y, z); if ( _check) check(); } public void glRotatex(int angle, int x, int y, int z) { mCurrent.glRotatex(angle, x, y, z); mgl.glRotatex(angle, x, y, z); if ( _check) check(); } public void glSampleCoverage(float value, boolean invert) { mgl.glSampleCoverage(value, invert); } public void glSampleCoveragex(int value, boolean invert) { mgl.glSampleCoveragex(value, invert); } public void glScalef(float x, float y, float z) { mCurrent.glScalef(x, y, z); mgl.glScalef(x, y, z); if ( _check) check(); } public void glScalex(int x, int y, int z) { mCurrent.glScalex(x, y, z); mgl.glScalex(x, y, z); if ( _check) check(); } public void glScissor(int x, int y, int width, int height) { mgl.glScissor(x, y, width, height); } public void glShadeModel(int mode) { mgl.glShadeModel(mode); } public void glStencilFunc(int func, int ref, int mask) { mgl.glStencilFunc(func, ref, mask); } public void glStencilMask(int mask) { mgl.glStencilMask(mask); } public void glStencilOp(int fail, int zfail, int zpass) { mgl.glStencilOp(fail, zfail, zpass); } public void glTexCoordPointer(int size, int type, int stride, Buffer pointer) { mgl.glTexCoordPointer(size, type, stride, pointer); } public void glTexEnvf(int target, int pname, float param) { mgl.glTexEnvf(target, pname, param); } public void glTexEnvfv(int target, int pname, float[] params, int offset) { mgl.glTexEnvfv(target, pname, params, offset); } public void glTexEnvfv(int target, int pname, FloatBuffer params) { mgl.glTexEnvfv(target, pname, params); } public void glTexEnvx(int target, int pname, int param) { mgl.glTexEnvx(target, pname, param); } public void glTexEnvxv(int target, int pname, int[] params, int offset) { mgl.glTexEnvxv(target, pname, params, offset); } public void glTexEnvxv(int target, int pname, IntBuffer params) { mgl.glTexEnvxv(target, pname, params); } public void glTexImage2D(int target, int level, int internalformat, int width, int height, int border, int format, int type, Buffer pixels) { mgl.glTexImage2D(target, level, internalformat, width, height, border, format, type, pixels); } public void glTexParameterf(int target, int pname, float param) { mgl.glTexParameterf(target, pname, param); } public void glTexParameterx(int target, int pname, int param) { mgl.glTexParameterx(target, pname, param); } public void glTexParameteriv(int target, int pname, int[] params, int offset) { mgl11.glTexParameteriv(target, pname, params, offset); } public void glTexParameteriv(int target, int pname, IntBuffer params) { mgl11.glTexParameteriv(target, pname, params); } public void glTexSubImage2D(int target, int level, int xoffset, int yoffset, int width, int height, int format, int type, Buffer pixels) { mgl.glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixels); } public void glTranslatef(float x, float y, float z) { mCurrent.glTranslatef(x, y, z); mgl.glTranslatef(x, y, z); if ( _check) check(); } public void glTranslatex(int x, int y, int z) { mCurrent.glTranslatex(x, y, z); mgl.glTranslatex(x, y, z); if ( _check) check(); } public void glVertexPointer(int size, int type, int stride, Buffer pointer) { mgl.glVertexPointer(size, type, stride, pointer); } public void glViewport(int x, int y, int width, int height) { mgl.glViewport(x, y, width, height); } public void glClipPlanef(int plane, float[] equation, int offset) { mgl11.glClipPlanef(plane, equation, offset); } public void glClipPlanef(int plane, FloatBuffer equation) { mgl11.glClipPlanef(plane, equation); } public void glClipPlanex(int plane, int[] equation, int offset) { mgl11.glClipPlanex(plane, equation, offset); } public void glClipPlanex(int plane, IntBuffer equation) { mgl11.glClipPlanex(plane, equation); } // Draw Texture Extension public void glDrawTexfOES(float x, float y, float z, float width, float height) { mgl11Ext.glDrawTexfOES(x, y, z, width, height); } public void glDrawTexfvOES(float[] coords, int offset) { mgl11Ext.glDrawTexfvOES(coords, offset); } public void glDrawTexfvOES(FloatBuffer coords) { mgl11Ext.glDrawTexfvOES(coords); } public void glDrawTexiOES(int x, int y, int z, int width, int height) { mgl11Ext.glDrawTexiOES(x, y, z, width, height); } public void glDrawTexivOES(int[] coords, int offset) { mgl11Ext.glDrawTexivOES(coords, offset); } public void glDrawTexivOES(IntBuffer coords) { mgl11Ext.glDrawTexivOES(coords); } public void glDrawTexsOES(short x, short y, short z, short width, short height) { mgl11Ext.glDrawTexsOES(x, y, z, width, height); } public void glDrawTexsvOES(short[] coords, int offset) { mgl11Ext.glDrawTexsvOES(coords, offset); } public void glDrawTexsvOES(ShortBuffer coords) { mgl11Ext.glDrawTexsvOES(coords); } public void glDrawTexxOES(int x, int y, int z, int width, int height) { mgl11Ext.glDrawTexxOES(x, y, z, width, height); } public void glDrawTexxvOES(int[] coords, int offset) { mgl11Ext.glDrawTexxvOES(coords, offset); } public void glDrawTexxvOES(IntBuffer coords) { mgl11Ext.glDrawTexxvOES(coords); } public int glQueryMatrixxOES(int[] mantissa, int mantissaOffset, int[] exponent, int exponentOffset) { return mgl10Ext.glQueryMatrixxOES(mantissa, mantissaOffset, exponent, exponentOffset); } public int glQueryMatrixxOES(IntBuffer mantissa, IntBuffer exponent) { return mgl10Ext.glQueryMatrixxOES(mantissa, exponent); } // Unsupported GL11 methods public void glBindBuffer(int target, int buffer) { throw new UnsupportedOperationException(); } public void glBufferData(int target, int size, Buffer data, int usage) { throw new UnsupportedOperationException(); } public void glBufferSubData(int target, int offset, int size, Buffer data) { throw new UnsupportedOperationException(); } public void glColor4ub(byte red, byte green, byte blue, byte alpha) { throw new UnsupportedOperationException(); } public void glDeleteBuffers(int n, int[] buffers, int offset) { throw new UnsupportedOperationException(); } public void glDeleteBuffers(int n, IntBuffer buffers) { throw new UnsupportedOperationException(); } public void glGenBuffers(int n, int[] buffers, int offset) { throw new UnsupportedOperationException(); } public void glGenBuffers(int n, IntBuffer buffers) { throw new UnsupportedOperationException(); } public void glGetBooleanv(int pname, boolean[] params, int offset) { throw new UnsupportedOperationException(); } public void glGetBooleanv(int pname, IntBuffer params) { throw new UnsupportedOperationException(); } public void glGetBufferParameteriv(int target, int pname, int[] params, int offset) { throw new UnsupportedOperationException(); } public void glGetBufferParameteriv(int target, int pname, IntBuffer params) { throw new UnsupportedOperationException(); } public void glGetClipPlanef(int pname, float[] eqn, int offset) { throw new UnsupportedOperationException(); } public void glGetClipPlanef(int pname, FloatBuffer eqn) { throw new UnsupportedOperationException(); } public void glGetClipPlanex(int pname, int[] eqn, int offset) { throw new UnsupportedOperationException(); } public void glGetClipPlanex(int pname, IntBuffer eqn) { throw new UnsupportedOperationException(); } public void glGetFixedv(int pname, int[] params, int offset) { throw new UnsupportedOperationException(); } public void glGetFixedv(int pname, IntBuffer params) { throw new UnsupportedOperationException(); } public void glGetFloatv(int pname, float[] params, int offset) { throw new UnsupportedOperationException(); } public void glGetFloatv(int pname, FloatBuffer params) { throw new UnsupportedOperationException(); } public void glGetLightfv(int light, int pname, float[] params, int offset) { throw new UnsupportedOperationException(); } public void glGetLightfv(int light, int pname, FloatBuffer params) { throw new UnsupportedOperationException(); } public void glGetLightxv(int light, int pname, int[] params, int offset) { throw new UnsupportedOperationException(); } public void glGetLightxv(int light, int pname, IntBuffer params) { throw new UnsupportedOperationException(); } public void glGetMaterialfv(int face, int pname, float[] params, int offset) { throw new UnsupportedOperationException(); } public void glGetMaterialfv(int face, int pname, FloatBuffer params) { throw new UnsupportedOperationException(); } public void glGetMaterialxv(int face, int pname, int[] params, int offset) { throw new UnsupportedOperationException(); } public void glGetMaterialxv(int face, int pname, IntBuffer params) { throw new UnsupportedOperationException(); } public void glGetTexEnviv(int env, int pname, int[] params, int offset) { throw new UnsupportedOperationException(); } public void glGetTexEnviv(int env, int pname, IntBuffer params) { throw new UnsupportedOperationException(); } public void glGetTexEnvxv(int env, int pname, int[] params, int offset) { throw new UnsupportedOperationException(); } public void glGetTexEnvxv(int env, int pname, IntBuffer params) { throw new UnsupportedOperationException(); } public void glGetTexParameterfv(int target, int pname, float[] params, int offset) { throw new UnsupportedOperationException(); } public void glGetTexParameterfv(int target, int pname, FloatBuffer params) { throw new UnsupportedOperationException(); } public void glGetTexParameteriv(int target, int pname, int[] params, int offset) { throw new UnsupportedOperationException(); } public void glGetTexParameteriv(int target, int pname, IntBuffer params) { throw new UnsupportedOperationException(); } public void glGetTexParameterxv(int target, int pname, int[] params, int offset) { throw new UnsupportedOperationException(); } public void glGetTexParameterxv(int target, int pname, IntBuffer params) { throw new UnsupportedOperationException(); } public boolean glIsBuffer(int buffer) { throw new UnsupportedOperationException(); } public boolean glIsEnabled(int cap) { throw new UnsupportedOperationException(); } public boolean glIsTexture(int texture) { throw new UnsupportedOperationException(); } public void glPointParameterf(int pname, float param) { throw new UnsupportedOperationException(); } public void glPointParameterfv(int pname, float[] params, int offset) { throw new UnsupportedOperationException(); } public void glPointParameterfv(int pname, FloatBuffer params) { throw new UnsupportedOperationException(); } public void glPointParameterx(int pname, int param) { throw new UnsupportedOperationException(); } public void glPointParameterxv(int pname, int[] params, int offset) { throw new UnsupportedOperationException(); } public void glPointParameterxv(int pname, IntBuffer params) { throw new UnsupportedOperationException(); } public void glPointSizePointerOES(int type, int stride, Buffer pointer) { throw new UnsupportedOperationException(); } public void glTexEnvi(int target, int pname, int param) { throw new UnsupportedOperationException(); } public void glTexEnviv(int target, int pname, int[] params, int offset) { throw new UnsupportedOperationException(); } public void glTexEnviv(int target, int pname, IntBuffer params) { throw new UnsupportedOperationException(); } public void glTexParameterfv(int target, int pname, float[] params, int offset) { throw new UnsupportedOperationException(); } public void glTexParameterfv(int target, int pname, FloatBuffer params) { throw new UnsupportedOperationException(); } public void glTexParameteri(int target, int pname, int param) { throw new UnsupportedOperationException(); } public void glTexParameterxv(int target, int pname, int[] params, int offset) { throw new UnsupportedOperationException(); } public void glTexParameterxv(int target, int pname, IntBuffer params) { throw new UnsupportedOperationException(); } public void glColorPointer(int size, int type, int stride, int offset) { throw new UnsupportedOperationException(); } public void glDrawElements(int mode, int count, int type, int offset) { throw new UnsupportedOperationException(); } public void glGetPointerv(int pname, Buffer[] params) { throw new UnsupportedOperationException(); } public void glNormalPointer(int type, int stride, int offset) { throw new UnsupportedOperationException(); } public void glTexCoordPointer(int size, int type, int stride, int offset) { throw new UnsupportedOperationException(); } public void glVertexPointer(int size, int type, int stride, int offset) { throw new UnsupportedOperationException(); } public void glCurrentPaletteMatrixOES(int matrixpaletteindex) { throw new UnsupportedOperationException(); } public void glLoadPaletteFromModelViewMatrixOES() { throw new UnsupportedOperationException(); } public void glMatrixIndexPointerOES(int size, int type, int stride, Buffer pointer) { throw new UnsupportedOperationException(); } public void glMatrixIndexPointerOES(int size, int type, int stride, int offset) { throw new UnsupportedOperationException(); } public void glWeightPointerOES(int size, int type, int stride, Buffer pointer) { throw new UnsupportedOperationException(); } public void glWeightPointerOES(int size, int type, int stride, int offset) { throw new UnsupportedOperationException(); } /** * Get the current matrix */ public void getMatrix(float[] m, int offset) { mCurrent.getMatrix(m, offset); } /** * Get the current matrix mode */ public int getMatrixMode() { return mMatrixMode; } private void check() { int oesMode; switch (mMatrixMode) { case GL_MODELVIEW: oesMode = GL11.GL_MODELVIEW_MATRIX_FLOAT_AS_INT_BITS_OES; break; case GL_PROJECTION: oesMode = GL11.GL_PROJECTION_MATRIX_FLOAT_AS_INT_BITS_OES; break; case GL_TEXTURE: oesMode = GL11.GL_TEXTURE_MATRIX_FLOAT_AS_INT_BITS_OES; break; default: throw new IllegalArgumentException("Unknown matrix mode"); } if ( mByteBuffer == null) { mCheckA = new float[16]; mCheckB = new float[16]; mByteBuffer = ByteBuffer.allocateDirect(64); mByteBuffer.order(ByteOrder.nativeOrder()); mFloatBuffer = mByteBuffer.asFloatBuffer(); } mgl.glGetIntegerv(oesMode, mByteBuffer.asIntBuffer()); for(int i = 0; i < 16; i++) { mCheckB[i] = mFloatBuffer.get(i); } mCurrent.getMatrix(mCheckA, 0); boolean fail = false; for(int i = 0; i < 16; i++) { if (mCheckA[i] != mCheckB[i]) { Log.d("GLMatWrap", "i:" + i + " a:" + mCheckA[i] + " a:" + mCheckB[i]); fail = true; } } if (fail) { throw new IllegalArgumentException("Matrix math difference."); } } }
Java
/* * Copyright (C) 2007 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.opengles.spritetext; import android.opengl.Matrix; import java.nio.FloatBuffer; import java.nio.IntBuffer; /** * A matrix stack, similar to OpenGL ES's internal matrix stack. */ public class MatrixStack { public MatrixStack() { commonInit(DEFAULT_MAX_DEPTH); } public MatrixStack(int maxDepth) { commonInit(maxDepth); } private void commonInit(int maxDepth) { mMatrix = new float[maxDepth * MATRIX_SIZE]; mTemp = new float[MATRIX_SIZE * 2]; glLoadIdentity(); } public void glFrustumf(float left, float right, float bottom, float top, float near, float far) { Matrix.frustumM(mMatrix, mTop, left, right, bottom, top, near, far); } public void glFrustumx(int left, int right, int bottom, int top, int near, int far) { glFrustumf(fixedToFloat(left),fixedToFloat(right), fixedToFloat(bottom), fixedToFloat(top), fixedToFloat(near), fixedToFloat(far)); } public void glLoadIdentity() { Matrix.setIdentityM(mMatrix, mTop); } public void glLoadMatrixf(float[] m, int offset) { System.arraycopy(m, offset, mMatrix, mTop, MATRIX_SIZE); } public void glLoadMatrixf(FloatBuffer m) { m.get(mMatrix, mTop, MATRIX_SIZE); } public void glLoadMatrixx(int[] m, int offset) { for(int i = 0; i < MATRIX_SIZE; i++) { mMatrix[mTop + i] = fixedToFloat(m[offset + i]); } } public void glLoadMatrixx(IntBuffer m) { for(int i = 0; i < MATRIX_SIZE; i++) { mMatrix[mTop + i] = fixedToFloat(m.get()); } } public void glMultMatrixf(float[] m, int offset) { System.arraycopy(mMatrix, mTop, mTemp, 0, MATRIX_SIZE); Matrix.multiplyMM(mMatrix, mTop, mTemp, 0, m, offset); } public void glMultMatrixf(FloatBuffer m) { m.get(mTemp, MATRIX_SIZE, MATRIX_SIZE); glMultMatrixf(mTemp, MATRIX_SIZE); } public void glMultMatrixx(int[] m, int offset) { for(int i = 0; i < MATRIX_SIZE; i++) { mTemp[MATRIX_SIZE + i] = fixedToFloat(m[offset + i]); } glMultMatrixf(mTemp, MATRIX_SIZE); } public void glMultMatrixx(IntBuffer m) { for(int i = 0; i < MATRIX_SIZE; i++) { mTemp[MATRIX_SIZE + i] = fixedToFloat(m.get()); } glMultMatrixf(mTemp, MATRIX_SIZE); } public void glOrthof(float left, float right, float bottom, float top, float near, float far) { Matrix.orthoM(mMatrix, mTop, left, right, bottom, top, near, far); } public void glOrthox(int left, int right, int bottom, int top, int near, int far) { glOrthof(fixedToFloat(left), fixedToFloat(right), fixedToFloat(bottom), fixedToFloat(top), fixedToFloat(near), fixedToFloat(far)); } public void glPopMatrix() { preflight_adjust(-1); adjust(-1); } public void glPushMatrix() { preflight_adjust(1); System.arraycopy(mMatrix, mTop, mMatrix, mTop + MATRIX_SIZE, MATRIX_SIZE); adjust(1); } public void glRotatef(float angle, float x, float y, float z) { Matrix.setRotateM(mTemp, 0, angle, x, y, z); System.arraycopy(mMatrix, mTop, mTemp, MATRIX_SIZE, MATRIX_SIZE); Matrix.multiplyMM(mMatrix, mTop, mTemp, MATRIX_SIZE, mTemp, 0); } public void glRotatex(int angle, int x, int y, int z) { glRotatef(angle, fixedToFloat(x), fixedToFloat(y), fixedToFloat(z)); } public void glScalef(float x, float y, float z) { Matrix.scaleM(mMatrix, mTop, x, y, z); } public void glScalex(int x, int y, int z) { glScalef(fixedToFloat(x), fixedToFloat(y), fixedToFloat(z)); } public void glTranslatef(float x, float y, float z) { Matrix.translateM(mMatrix, mTop, x, y, z); } public void glTranslatex(int x, int y, int z) { glTranslatef(fixedToFloat(x), fixedToFloat(y), fixedToFloat(z)); } public void getMatrix(float[] dest, int offset) { System.arraycopy(mMatrix, mTop, dest, offset, MATRIX_SIZE); } private float fixedToFloat(int x) { return x * (1.0f / 65536.0f); } private void preflight_adjust(int dir) { int newTop = mTop + dir * MATRIX_SIZE; if (newTop < 0) { throw new IllegalArgumentException("stack underflow"); } if (newTop + MATRIX_SIZE > mMatrix.length) { throw new IllegalArgumentException("stack overflow"); } } private void adjust(int dir) { mTop += dir * MATRIX_SIZE; } private final static int DEFAULT_MAX_DEPTH = 32; private final static int MATRIX_SIZE = 16; private float[] mMatrix; private int mTop; private float[] mTemp; }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.opengles.spritetext; import android.content.Context; import android.util.AttributeSet; import android.view.SurfaceHolder; import android.view.SurfaceView; import java.util.ArrayList; import java.util.concurrent.Semaphore; import javax.microedition.khronos.egl.EGL10; import javax.microedition.khronos.egl.EGL11; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.egl.EGLContext; import javax.microedition.khronos.egl.EGLDisplay; import javax.microedition.khronos.egl.EGLSurface; import javax.microedition.khronos.opengles.GL; import javax.microedition.khronos.opengles.GL10; /** * An implementation of SurfaceView that uses the dedicated surface for * displaying an OpenGL animation. This allows the animation to run in a * separate thread, without requiring that it be driven by the update mechanism * of the view hierarchy. * * The application-specific rendering code is delegated to a GLView.Renderer * instance. */ class GLView extends SurfaceView implements SurfaceHolder.Callback { GLView(Context context) { super(context); init(); } public GLView(Context context, AttributeSet attrs) { super(context, attrs); init(); } private void init() { // Install a SurfaceHolder.Callback so we get notified when the // underlying surface is created and destroyed mHolder = getHolder(); mHolder.addCallback(this); mHolder.setType(SurfaceHolder.SURFACE_TYPE_GPU); } public void setGLWrapper(GLWrapper glWrapper) { mGLWrapper = glWrapper; } public void setRenderer(Renderer renderer) { mGLThread = new GLThread(renderer); mGLThread.start(); } public void surfaceCreated(SurfaceHolder holder) { mGLThread.surfaceCreated(); } public void surfaceDestroyed(SurfaceHolder holder) { // Surface will be destroyed when we return mGLThread.surfaceDestroyed(); } public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { // Surface size or format has changed. This should not happen in this // example. mGLThread.onWindowResize(w, h); } /** * Inform the view that the activity is paused. */ public void onPause() { mGLThread.onPause(); } /** * Inform the view that the activity is resumed. */ public void onResume() { mGLThread.onResume(); } /** * Inform the view that the window focus has changed. */ @Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); mGLThread.onWindowFocusChanged(hasFocus); } /** * Queue an "event" to be run on the GL rendering thread. * @param r the runnable to be run on the GL rendering thread. */ public void queueEvent(Runnable r) { mGLThread.queueEvent(r); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); mGLThread.requestExitAndWait(); } // ---------------------------------------------------------------------- public interface GLWrapper { GL wrap(GL gl); } // ---------------------------------------------------------------------- /** * A generic renderer interface. */ public interface Renderer { /** * @return the EGL configuration specification desired by the renderer. */ int[] getConfigSpec(); /** * Surface created. * Called when the surface is created. Called when the application * starts, and whenever the GPU is reinitialized. This will * typically happen when the device awakes after going to sleep. * Set your textures here. */ void surfaceCreated(GL10 gl); /** * Surface changed size. * Called after the surface is created and whenever * the OpenGL ES surface size changes. Set your viewport here. * @param gl * @param width * @param height */ void sizeChanged(GL10 gl, int width, int height); /** * Draw the current frame. * @param gl */ void drawFrame(GL10 gl); } /** * An EGL helper class. */ private class EglHelper { public EglHelper() { } /** * Initialize EGL for a given configuration spec. * @param configSpec */ public void start(int[] configSpec){ /* * Get an EGL instance */ mEgl = (EGL10) EGLContext.getEGL(); /* * Get to the default display. */ mEglDisplay = mEgl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY); /* * We can now initialize EGL for that display */ int[] version = new int[2]; mEgl.eglInitialize(mEglDisplay, version); EGLConfig[] configs = new EGLConfig[1]; int[] num_config = new int[1]; mEgl.eglChooseConfig(mEglDisplay, configSpec, configs, 1, num_config); mEglConfig = configs[0]; /* * Create an OpenGL ES context. This must be done only once, an * OpenGL context is a somewhat heavy object. */ mEglContext = mEgl.eglCreateContext(mEglDisplay, mEglConfig, EGL10.EGL_NO_CONTEXT, null); mEglSurface = null; } /* * Create and return an OpenGL surface */ public GL createSurface(SurfaceHolder holder) { /* * The window size has changed, so we need to create a new * surface. */ if (mEglSurface != null) { /* * Unbind and destroy the old EGL surface, if * there is one. */ mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT); mEgl.eglDestroySurface(mEglDisplay, mEglSurface); } /* * Create an EGL surface we can render into. */ mEglSurface = mEgl.eglCreateWindowSurface(mEglDisplay, mEglConfig, holder, null); /* * Before we can issue GL commands, we need to make sure * the context is current and bound to a surface. */ mEgl.eglMakeCurrent(mEglDisplay, mEglSurface, mEglSurface, mEglContext); GL gl = mEglContext.getGL(); if (mGLWrapper != null) { gl = mGLWrapper.wrap(gl); } return gl; } /** * Display the current render surface. * @return false if the context has been lost. */ public boolean swap() { mEgl.eglSwapBuffers(mEglDisplay, mEglSurface); /* * Always check for EGL_CONTEXT_LOST, which means the context * and all associated data were lost (For instance because * the device went to sleep). We need to sleep until we * get a new surface. */ return mEgl.eglGetError() != EGL11.EGL_CONTEXT_LOST; } public void finish() { if (mEglSurface != null) { mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT); mEgl.eglDestroySurface(mEglDisplay, mEglSurface); mEglSurface = null; } if (mEglContext != null) { mEgl.eglDestroyContext(mEglDisplay, mEglContext); mEglContext = null; } if (mEglDisplay != null) { mEgl.eglTerminate(mEglDisplay); mEglDisplay = null; } } EGL10 mEgl; EGLDisplay mEglDisplay; EGLSurface mEglSurface; EGLConfig mEglConfig; EGLContext mEglContext; } /** * A generic GL Thread. Takes care of initializing EGL and GL. Delegates * to a Renderer instance to do the actual drawing. * */ class GLThread extends Thread { GLThread(Renderer renderer) { super(); mDone = false; mWidth = 0; mHeight = 0; mRenderer = renderer; setName("GLThread"); } @Override public void run() { /* * When the android framework launches a second instance of * an activity, the new instance's onCreate() method may be * called before the first instance returns from onDestroy(). * * This semaphore ensures that only one instance at a time * accesses EGL. */ try { try { sEglSemaphore.acquire(); } catch (InterruptedException e) { return; } guardedRun(); } catch (InterruptedException e) { // fall thru and exit normally } finally { sEglSemaphore.release(); } } private void guardedRun() throws InterruptedException { mEglHelper = new EglHelper(); /* * Specify a configuration for our opengl session * and grab the first configuration that matches is */ int[] configSpec = mRenderer.getConfigSpec(); mEglHelper.start(configSpec); GL10 gl = null; boolean tellRendererSurfaceCreated = true; boolean tellRendererSurfaceChanged = true; /* * This is our main activity thread's loop, we go until * asked to quit. */ while (!mDone) { /* * Update the asynchronous state (window size) */ int w, h; boolean changed; boolean needStart = false; synchronized (this) { Runnable r; while ((r = getEvent()) != null) { r.run(); } if (mPaused) { mEglHelper.finish(); needStart = true; } if(needToWait()) { while (needToWait()) { wait(); } } if (mDone) { break; } changed = mSizeChanged; w = mWidth; h = mHeight; mSizeChanged = false; } if (needStart) { mEglHelper.start(configSpec); tellRendererSurfaceCreated = true; changed = true; } if (changed) { gl = (GL10) mEglHelper.createSurface(mHolder); tellRendererSurfaceChanged = true; } if (tellRendererSurfaceCreated) { mRenderer.surfaceCreated(gl); tellRendererSurfaceCreated = false; } if (tellRendererSurfaceChanged) { mRenderer.sizeChanged(gl, w, h); tellRendererSurfaceChanged = false; } if ((w > 0) && (h > 0)) { /* draw a frame here */ mRenderer.drawFrame(gl); /* * Once we're done with GL, we need to call swapBuffers() * to instruct the system to display the rendered frame */ mEglHelper.swap(); } } /* * clean-up everything... */ mEglHelper.finish(); } private boolean needToWait() { return (mPaused || (! mHasFocus) || (! mHasSurface) || mContextLost) && (! mDone); } public void surfaceCreated() { synchronized(this) { mHasSurface = true; mContextLost = false; notify(); } } public void surfaceDestroyed() { synchronized(this) { mHasSurface = false; notify(); } } public void onPause() { synchronized (this) { mPaused = true; } } public void onResume() { synchronized (this) { mPaused = false; notify(); } } public void onWindowFocusChanged(boolean hasFocus) { synchronized (this) { mHasFocus = hasFocus; if (mHasFocus == true) { notify(); } } } public void onWindowResize(int w, int h) { synchronized (this) { mWidth = w; mHeight = h; mSizeChanged = true; } } public void requestExitAndWait() { // don't call this from GLThread thread or it is a guaranteed // deadlock! synchronized(this) { mDone = true; notify(); } try { join(); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } } /** * Queue an "event" to be run on the GL rendering thread. * @param r the runnable to be run on the GL rendering thread. */ public void queueEvent(Runnable r) { synchronized(this) { mEventQueue.add(r); } } private Runnable getEvent() { synchronized(this) { if (mEventQueue.size() > 0) { return mEventQueue.remove(0); } } return null; } private boolean mDone; private boolean mPaused; private boolean mHasFocus; private boolean mHasSurface; private boolean mContextLost; private int mWidth; private int mHeight; private Renderer mRenderer; private ArrayList<Runnable> mEventQueue = new ArrayList<Runnable>(); private EglHelper mEglHelper; } private static final Semaphore sEglSemaphore = new Semaphore(1); private boolean mSizeChanged = true; private SurfaceHolder mHolder; private GLThread mGLThread; private GLWrapper mGLWrapper; }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.opengles.spritetext; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import java.nio.ShortBuffer; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Paint; import android.opengl.GLU; import android.opengl.GLUtils; import android.os.SystemClock; import javax.microedition.khronos.egl.EGL10; import javax.microedition.khronos.opengles.GL10; public class SpriteTextRenderer implements GLView.Renderer{ public SpriteTextRenderer(Context context) { mContext = context; mTriangle = new Triangle(); mProjector = new Projector(); mLabelPaint = new Paint(); mLabelPaint.setTextSize(32); mLabelPaint.setAntiAlias(true); mLabelPaint.setARGB(0xff, 0x00, 0x00, 0x00); } public int[] getConfigSpec() { // We don't need a depth buffer, and don't care about our // color depth. int[] configSpec = { EGL10.EGL_DEPTH_SIZE, 0, EGL10.EGL_NONE }; return configSpec; } public void surfaceCreated(GL10 gl) { /* * By default, OpenGL enables features that improve quality * but reduce performance. One might want to tweak that * especially on software renderer. */ gl.glDisable(GL10.GL_DITHER); /* * Some one-time OpenGL initialization can be made here * probably based on features of this particular context */ gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_FASTEST); gl.glClearColor(.5f, .5f, .5f, 1); gl.glShadeModel(GL10.GL_SMOOTH); gl.glEnable(GL10.GL_DEPTH_TEST); gl.glEnable(GL10.GL_TEXTURE_2D); /* * Create our texture. This has to be done each time the * surface is created. */ int[] textures = new int[1]; gl.glGenTextures(1, textures, 0); mTextureID = textures[0]; gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureID); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_CLAMP_TO_EDGE); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_CLAMP_TO_EDGE); gl.glTexEnvf(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE, GL10.GL_REPLACE); InputStream is = mContext.getResources() .openRawResource(R.drawable.tex); Bitmap bitmap; try { bitmap = BitmapFactory.decodeStream(is); } finally { try { is.close(); } catch(IOException e) { // Ignore. } } GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0); bitmap.recycle(); if (mLabels != null) { mLabels.shutdown(gl); } else { mLabels = new LabelMaker(true, 256, 64); } mLabels.initialize(gl); mLabels.beginAdding(gl); mLabelA = mLabels.add(gl, "A", mLabelPaint); mLabelB = mLabels.add(gl, "B", mLabelPaint); mLabelC = mLabels.add(gl, "C", mLabelPaint); mLabelMsPF = mLabels.add(gl, "ms/f", mLabelPaint); mLabels.endAdding(gl); if (mNumericSprite != null) { mNumericSprite.shutdown(gl); } else { mNumericSprite = new NumericSprite(); } mNumericSprite.initialize(gl, mLabelPaint); } public void drawFrame(GL10 gl) { /* * By default, OpenGL enables features that improve quality * but reduce performance. One might want to tweak that * especially on software renderer. */ gl.glDisable(GL10.GL_DITHER); gl.glTexEnvx(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE, GL10.GL_MODULATE); /* * Usually, the first thing one might want to do is to clear * the screen. The most efficient way of doing this is to use * glClear(). */ gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); /* * Now we're ready to draw some 3D objects */ gl.glMatrixMode(GL10.GL_MODELVIEW); gl.glLoadIdentity(); GLU.gluLookAt(gl, 0.0f, 0.0f, -2.5f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f); gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY); gl.glActiveTexture(GL10.GL_TEXTURE0); gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureID); gl.glTexParameterx(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_REPEAT); gl.glTexParameterx(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_REPEAT); long time = SystemClock.uptimeMillis() % 4000L; float angle = 0.090f * ((int) time); gl.glRotatef(angle, 0, 0, 1.0f); gl.glScalef(2.0f, 2.0f, 2.0f); mTriangle.draw(gl); mProjector.getCurrentModelView(gl); mLabels.beginDrawing(gl, mWidth, mHeight); drawLabel(gl, 0, mLabelA); drawLabel(gl, 1, mLabelB); drawLabel(gl, 2, mLabelC); float msPFX = mWidth - mLabels.getWidth(mLabelMsPF) - 1; mLabels.draw(gl, msPFX, 0, mLabelMsPF); mLabels.endDrawing(gl); drawMsPF(gl, msPFX); } private void drawMsPF(GL10 gl, float rightMargin) { long time = SystemClock.uptimeMillis(); if (mStartTime == 0) { mStartTime = time; } if (mFrames++ == SAMPLE_PERIOD_FRAMES) { mFrames = 0; long delta = time - mStartTime; mStartTime = time; mMsPerFrame = (int) (delta * SAMPLE_FACTOR); } if (mMsPerFrame > 0) { mNumericSprite.setValue(mMsPerFrame); float numWidth = mNumericSprite.width(); float x = rightMargin - numWidth; mNumericSprite.draw(gl, x, 0, mWidth, mHeight); } } private void drawLabel(GL10 gl, int triangleVertex, int labelId) { float x = mTriangle.getX(triangleVertex); float y = mTriangle.getY(triangleVertex); mScratch[0] = x; mScratch[1] = y; mScratch[2] = 0.0f; mScratch[3] = 1.0f; mProjector.project(mScratch, 0, mScratch, 4); float sx = mScratch[4]; float sy = mScratch[5]; float height = mLabels.getHeight(labelId); float width = mLabels.getWidth(labelId); float tx = sx - width * 0.5f; float ty = sy - height * 0.5f; mLabels.draw(gl, tx, ty, labelId); } public void sizeChanged(GL10 gl, int w, int h) { mWidth = w; mHeight = h; gl.glViewport(0, 0, w, h); mProjector.setCurrentView(0, 0, w, h); /* * Set our projection matrix. This doesn't have to be done * each time we draw, but usually a new projection needs to * be set when the viewport is resized. */ float ratio = (float) w / h; gl.glMatrixMode(GL10.GL_PROJECTION); gl.glLoadIdentity(); gl.glFrustumf(-ratio, ratio, -1, 1, 1, 10); mProjector.getCurrentProjection(gl); } private int mWidth; private int mHeight; private Context mContext; private Triangle mTriangle; private int mTextureID; private int mFrames; private int mMsPerFrame; private final static int SAMPLE_PERIOD_FRAMES = 12; private final static float SAMPLE_FACTOR = 1.0f / SAMPLE_PERIOD_FRAMES; private long mStartTime; private LabelMaker mLabels; private Paint mLabelPaint; private int mLabelA; private int mLabelB; private int mLabelC; private int mLabelMsPF; private Projector mProjector; private NumericSprite mNumericSprite; private float[] mScratch = new float[8]; } class Triangle { public Triangle() { // Buffers to be passed to gl*Pointer() functions // must be direct, i.e., they must be placed on the // native heap where the garbage collector cannot // move them. // // Buffers with multi-byte datatypes (e.g., short, int, float) // must have their byte order set to native order ByteBuffer vbb = ByteBuffer.allocateDirect(VERTS * 3 * 4); vbb.order(ByteOrder.nativeOrder()); mFVertexBuffer = vbb.asFloatBuffer(); ByteBuffer tbb = ByteBuffer.allocateDirect(VERTS * 2 * 4); tbb.order(ByteOrder.nativeOrder()); mTexBuffer = tbb.asFloatBuffer(); ByteBuffer ibb = ByteBuffer.allocateDirect(VERTS * 2); ibb.order(ByteOrder.nativeOrder()); mIndexBuffer = ibb.asShortBuffer(); for (int i = 0; i < VERTS; i++) { for(int j = 0; j < 3; j++) { mFVertexBuffer.put(sCoords[i*3+j]); } } for (int i = 0; i < VERTS; i++) { for(int j = 0; j < 2; j++) { mTexBuffer.put(sCoords[i*3+j] * 2.0f + 0.5f); } } for(int i = 0; i < VERTS; i++) { mIndexBuffer.put((short) i); } mFVertexBuffer.position(0); mTexBuffer.position(0); mIndexBuffer.position(0); } public void draw(GL10 gl) { gl.glFrontFace(GL10.GL_CCW); gl.glVertexPointer(3, GL10.GL_FLOAT, 0, mFVertexBuffer); gl.glEnable(GL10.GL_TEXTURE_2D); gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, mTexBuffer); gl.glDrawElements(GL10.GL_TRIANGLE_STRIP, VERTS, GL10.GL_UNSIGNED_SHORT, mIndexBuffer); } public float getX(int vertex) { return sCoords[3*vertex]; } public float getY(int vertex) { return sCoords[3*vertex+1]; } private final static int VERTS = 3; private FloatBuffer mFVertexBuffer; private FloatBuffer mTexBuffer; private ShortBuffer mIndexBuffer; // A unit-sided equalateral triangle centered on the origin. private final static float[] sCoords = { // X, Y, Z -0.5f, -0.25f, 0, 0.5f, -0.25f, 0, 0.0f, 0.559016994f, 0 }; }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.opengles.triangle; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import java.nio.ShortBuffer; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.opengl.GLU; import android.opengl.GLUtils; import android.os.SystemClock; import javax.microedition.khronos.egl.EGL10; import javax.microedition.khronos.opengles.GL10; public class TriangleRenderer implements GLView.Renderer{ public TriangleRenderer(Context context) { mContext = context; mTriangle = new Triangle(); } public int[] getConfigSpec() { // We don't need a depth buffer, and don't care about our // color depth. int[] configSpec = { EGL10.EGL_DEPTH_SIZE, 0, EGL10.EGL_NONE }; return configSpec; } public void surfaceCreated(GL10 gl) { /* * By default, OpenGL enables features that improve quality * but reduce performance. One might want to tweak that * especially on software renderer. */ gl.glDisable(GL10.GL_DITHER); /* * Some one-time OpenGL initialization can be made here * probably based on features of this particular context */ gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_FASTEST); gl.glClearColor(.5f, .5f, .5f, 1); gl.glShadeModel(GL10.GL_SMOOTH); gl.glEnable(GL10.GL_DEPTH_TEST); gl.glEnable(GL10.GL_TEXTURE_2D); /* * Create our texture. This has to be done each time the * surface is created. */ int[] textures = new int[1]; gl.glGenTextures(1, textures, 0); mTextureID = textures[0]; gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureID); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_CLAMP_TO_EDGE); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_CLAMP_TO_EDGE); gl.glTexEnvf(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE, GL10.GL_REPLACE); InputStream is = mContext.getResources() .openRawResource(R.drawable.tex); Bitmap bitmap; try { bitmap = BitmapFactory.decodeStream(is); } finally { try { is.close(); } catch(IOException e) { // Ignore. } } GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0); bitmap.recycle(); } public void drawFrame(GL10 gl) { /* * By default, OpenGL enables features that improve quality * but reduce performance. One might want to tweak that * especially on software renderer. */ gl.glDisable(GL10.GL_DITHER); gl.glTexEnvx(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE, GL10.GL_MODULATE); /* * Usually, the first thing one might want to do is to clear * the screen. The most efficient way of doing this is to use * glClear(). */ gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); /* * Now we're ready to draw some 3D objects */ gl.glMatrixMode(GL10.GL_MODELVIEW); gl.glLoadIdentity(); GLU.gluLookAt(gl, 0, 0, -5, 0f, 0f, 0f, 0f, 1.0f, 0.0f); gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY); gl.glActiveTexture(GL10.GL_TEXTURE0); gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureID); gl.glTexParameterx(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_REPEAT); gl.glTexParameterx(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_REPEAT); long time = SystemClock.uptimeMillis() % 4000L; float angle = 0.090f * ((int) time); gl.glRotatef(angle, 0, 0, 1.0f); mTriangle.draw(gl); } public void sizeChanged(GL10 gl, int w, int h) { gl.glViewport(0, 0, w, h); /* * Set our projection matrix. This doesn't have to be done * each time we draw, but usually a new projection needs to * be set when the viewport is resized. */ float ratio = (float) w / h; gl.glMatrixMode(GL10.GL_PROJECTION); gl.glLoadIdentity(); gl.glFrustumf(-ratio, ratio, -1, 1, 3, 7); } private Context mContext; private Triangle mTriangle; private int mTextureID; } class Triangle { public Triangle() { // Buffers to be passed to gl*Pointer() functions // must be direct, i.e., they must be placed on the // native heap where the garbage collector cannot // move them. // // Buffers with multi-byte datatypes (e.g., short, int, float) // must have their byte order set to native order ByteBuffer vbb = ByteBuffer.allocateDirect(VERTS * 3 * 4); vbb.order(ByteOrder.nativeOrder()); mFVertexBuffer = vbb.asFloatBuffer(); ByteBuffer tbb = ByteBuffer.allocateDirect(VERTS * 2 * 4); tbb.order(ByteOrder.nativeOrder()); mTexBuffer = tbb.asFloatBuffer(); ByteBuffer ibb = ByteBuffer.allocateDirect(VERTS * 2); ibb.order(ByteOrder.nativeOrder()); mIndexBuffer = ibb.asShortBuffer(); // A unit-sided equalateral triangle centered on the origin. float[] coords = { // X, Y, Z -0.5f, -0.25f, 0, 0.5f, -0.25f, 0, 0.0f, 0.559016994f, 0 }; for (int i = 0; i < VERTS; i++) { for(int j = 0; j < 3; j++) { mFVertexBuffer.put(coords[i*3+j] * 2.0f); } } for (int i = 0; i < VERTS; i++) { for(int j = 0; j < 2; j++) { mTexBuffer.put(coords[i*3+j] * 2.0f + 0.5f); } } for(int i = 0; i < VERTS; i++) { mIndexBuffer.put((short) i); } mFVertexBuffer.position(0); mTexBuffer.position(0); mIndexBuffer.position(0); } public void draw(GL10 gl) { gl.glFrontFace(GL10.GL_CCW); gl.glVertexPointer(3, GL10.GL_FLOAT, 0, mFVertexBuffer); gl.glEnable(GL10.GL_TEXTURE_2D); gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, mTexBuffer); gl.glDrawElements(GL10.GL_TRIANGLE_STRIP, VERTS, GL10.GL_UNSIGNED_SHORT, mIndexBuffer); } private final static int VERTS = 3; private FloatBuffer mFVertexBuffer; private FloatBuffer mTexBuffer; private ShortBuffer mIndexBuffer; }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.opengles.triangle; import javax.microedition.khronos.opengles.GL; import android.app.Activity; import android.opengl.GLDebugHelper; import android.os.Bundle; public class TriangleActivity extends Activity { /** Set to true to enable checking of the OpenGL error code after every OpenGL call. Set to * false for faster code. * */ private final static boolean DEBUG_CHECK_GL_ERROR = true; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mGLView = (GLView) findViewById(R.id.glview); if (DEBUG_CHECK_GL_ERROR) { mGLView.setGLWrapper(new GLView.GLWrapper() { public GL wrap(GL gl) { return GLDebugHelper.wrap(gl, GLDebugHelper.CONFIG_CHECK_GL_ERROR, null); }}); } mGLView.setRenderer(new TriangleRenderer(this)); mGLView.requestFocus(); } @Override protected void onPause() { super.onPause(); mGLView.onPause(); } @Override protected void onResume() { super.onResume(); mGLView.onResume(); } private GLView mGLView; }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.opengles.triangle; import android.content.Context; import android.util.AttributeSet; import android.view.SurfaceHolder; import android.view.SurfaceView; import java.util.ArrayList; import java.util.concurrent.Semaphore; import javax.microedition.khronos.egl.EGL10; import javax.microedition.khronos.egl.EGL11; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.egl.EGLContext; import javax.microedition.khronos.egl.EGLDisplay; import javax.microedition.khronos.egl.EGLSurface; import javax.microedition.khronos.opengles.GL; import javax.microedition.khronos.opengles.GL10; /** * An implementation of SurfaceView that uses the dedicated surface for * displaying an OpenGL animation. This allows the animation to run in a * separate thread, without requiring that it be driven by the update mechanism * of the view hierarchy. * * The application-specific rendering code is delegated to a GLView.Renderer * instance. */ class GLView extends SurfaceView implements SurfaceHolder.Callback { GLView(Context context) { super(context); init(); } public GLView(Context context, AttributeSet attrs) { super(context, attrs); init(); } private void init() { // Install a SurfaceHolder.Callback so we get notified when the // underlying surface is created and destroyed mHolder = getHolder(); mHolder.addCallback(this); mHolder.setType(SurfaceHolder.SURFACE_TYPE_GPU); } public void setGLWrapper(GLWrapper glWrapper) { mGLWrapper = glWrapper; } public void setRenderer(Renderer renderer) { mGLThread = new GLThread(renderer); mGLThread.start(); } public void surfaceCreated(SurfaceHolder holder) { mGLThread.surfaceCreated(); } public void surfaceDestroyed(SurfaceHolder holder) { // Surface will be destroyed when we return mGLThread.surfaceDestroyed(); } public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { // Surface size or format has changed. This should not happen in this // example. mGLThread.onWindowResize(w, h); } /** * Inform the view that the activity is paused. */ public void onPause() { mGLThread.onPause(); } /** * Inform the view that the activity is resumed. */ public void onResume() { mGLThread.onResume(); } /** * Inform the view that the window focus has changed. */ @Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); mGLThread.onWindowFocusChanged(hasFocus); } /** * Queue an "event" to be run on the GL rendering thread. * @param r the runnable to be run on the GL rendering thread. */ public void queueEvent(Runnable r) { mGLThread.queueEvent(r); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); mGLThread.requestExitAndWait(); } // ---------------------------------------------------------------------- public interface GLWrapper { GL wrap(GL gl); } // ---------------------------------------------------------------------- /** * A generic renderer interface. */ public interface Renderer { /** * @return the EGL configuration specification desired by the renderer. */ int[] getConfigSpec(); /** * Surface created. * Called when the surface is created. Called when the application * starts, and whenever the GPU is reinitialized. This will * typically happen when the device awakes after going to sleep. * Set your textures here. */ void surfaceCreated(GL10 gl); /** * Surface changed size. * Called after the surface is created and whenever * the OpenGL ES surface size changes. Set your viewport here. * @param gl * @param width * @param height */ void sizeChanged(GL10 gl, int width, int height); /** * Draw the current frame. * @param gl */ void drawFrame(GL10 gl); } /** * An EGL helper class. */ private class EglHelper { public EglHelper() { } /** * Initialize EGL for a given configuration spec. * @param configSpec */ public void start(int[] configSpec){ /* * Get an EGL instance */ mEgl = (EGL10) EGLContext.getEGL(); /* * Get to the default display. */ mEglDisplay = mEgl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY); /* * We can now initialize EGL for that display */ int[] version = new int[2]; mEgl.eglInitialize(mEglDisplay, version); EGLConfig[] configs = new EGLConfig[1]; int[] num_config = new int[1]; mEgl.eglChooseConfig(mEglDisplay, configSpec, configs, 1, num_config); mEglConfig = configs[0]; /* * Create an OpenGL ES context. This must be done only once, an * OpenGL context is a somewhat heavy object. */ mEglContext = mEgl.eglCreateContext(mEglDisplay, mEglConfig, EGL10.EGL_NO_CONTEXT, null); mEglSurface = null; } /* * Create and return an OpenGL surface */ public GL createSurface(SurfaceHolder holder) { /* * The window size has changed, so we need to create a new * surface. */ if (mEglSurface != null) { /* * Unbind and destroy the old EGL surface, if * there is one. */ mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT); mEgl.eglDestroySurface(mEglDisplay, mEglSurface); } /* * Create an EGL surface we can render into. */ mEglSurface = mEgl.eglCreateWindowSurface(mEglDisplay, mEglConfig, holder, null); /* * Before we can issue GL commands, we need to make sure * the context is current and bound to a surface. */ mEgl.eglMakeCurrent(mEglDisplay, mEglSurface, mEglSurface, mEglContext); GL gl = mEglContext.getGL(); if (mGLWrapper != null) { gl = mGLWrapper.wrap(gl); } return gl; } /** * Display the current render surface. * @return false if the context has been lost. */ public boolean swap() { mEgl.eglSwapBuffers(mEglDisplay, mEglSurface); /* * Always check for EGL_CONTEXT_LOST, which means the context * and all associated data were lost (For instance because * the device went to sleep). We need to sleep until we * get a new surface. */ return mEgl.eglGetError() != EGL11.EGL_CONTEXT_LOST; } public void finish() { if (mEglSurface != null) { mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT); mEgl.eglDestroySurface(mEglDisplay, mEglSurface); mEglSurface = null; } if (mEglContext != null) { mEgl.eglDestroyContext(mEglDisplay, mEglContext); mEglContext = null; } if (mEglDisplay != null) { mEgl.eglTerminate(mEglDisplay); mEglDisplay = null; } } EGL10 mEgl; EGLDisplay mEglDisplay; EGLSurface mEglSurface; EGLConfig mEglConfig; EGLContext mEglContext; } /** * A generic GL Thread. Takes care of initializing EGL and GL. Delegates * to a Renderer instance to do the actual drawing. * */ class GLThread extends Thread { GLThread(Renderer renderer) { super(); mDone = false; mWidth = 0; mHeight = 0; mRenderer = renderer; setName("GLThread"); } @Override public void run() { /* * When the android framework launches a second instance of * an activity, the new instance's onCreate() method may be * called before the first instance returns from onDestroy(). * * This semaphore ensures that only one instance at a time * accesses EGL. */ try { try { sEglSemaphore.acquire(); } catch (InterruptedException e) { return; } guardedRun(); } catch (InterruptedException e) { // fall thru and exit normally } finally { sEglSemaphore.release(); } } private void guardedRun() throws InterruptedException { mEglHelper = new EglHelper(); /* * Specify a configuration for our opengl session * and grab the first configuration that matches is */ int[] configSpec = mRenderer.getConfigSpec(); mEglHelper.start(configSpec); GL10 gl = null; boolean tellRendererSurfaceCreated = true; boolean tellRendererSurfaceChanged = true; /* * This is our main activity thread's loop, we go until * asked to quit. */ while (!mDone) { /* * Update the asynchronous state (window size) */ int w, h; boolean changed; boolean needStart = false; synchronized (this) { Runnable r; while ((r = getEvent()) != null) { r.run(); } if (mPaused) { mEglHelper.finish(); needStart = true; } if(needToWait()) { while (needToWait()) { wait(); } } if (mDone) { break; } changed = mSizeChanged; w = mWidth; h = mHeight; mSizeChanged = false; } if (needStart) { mEglHelper.start(configSpec); tellRendererSurfaceCreated = true; changed = true; } if (changed) { gl = (GL10) mEglHelper.createSurface(mHolder); tellRendererSurfaceChanged = true; } if (tellRendererSurfaceCreated) { mRenderer.surfaceCreated(gl); tellRendererSurfaceCreated = false; } if (tellRendererSurfaceChanged) { mRenderer.sizeChanged(gl, w, h); tellRendererSurfaceChanged = false; } if ((w > 0) && (h > 0)) { /* draw a frame here */ mRenderer.drawFrame(gl); /* * Once we're done with GL, we need to call swapBuffers() * to instruct the system to display the rendered frame */ mEglHelper.swap(); } } /* * clean-up everything... */ mEglHelper.finish(); } private boolean needToWait() { return (mPaused || (! mHasFocus) || (! mHasSurface) || mContextLost) && (! mDone); } public void surfaceCreated() { synchronized(this) { mHasSurface = true; mContextLost = false; notify(); } } public void surfaceDestroyed() { synchronized(this) { mHasSurface = false; notify(); } } public void onPause() { synchronized (this) { mPaused = true; } } public void onResume() { synchronized (this) { mPaused = false; notify(); } } public void onWindowFocusChanged(boolean hasFocus) { synchronized (this) { mHasFocus = hasFocus; if (mHasFocus == true) { notify(); } } } public void onWindowResize(int w, int h) { synchronized (this) { mWidth = w; mHeight = h; mSizeChanged = true; } } public void requestExitAndWait() { // don't call this from GLThread thread or it is a guaranteed // deadlock! synchronized(this) { mDone = true; notify(); } try { join(); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } } /** * Queue an "event" to be run on the GL rendering thread. * @param r the runnable to be run on the GL rendering thread. */ public void queueEvent(Runnable r) { synchronized(this) { mEventQueue.add(r); } } private Runnable getEvent() { synchronized(this) { if (mEventQueue.size() > 0) { return mEventQueue.remove(0); } } return null; } private boolean mDone; private boolean mPaused; private boolean mHasFocus; private boolean mHasSurface; private boolean mContextLost; private int mWidth; private int mHeight; private Renderer mRenderer; private ArrayList<Runnable> mEventQueue = new ArrayList<Runnable>(); private EglHelper mEglHelper; } private static final Semaphore sEglSemaphore = new Semaphore(1); private boolean mSizeChanged = true; private SurfaceHolder mHolder; private GLThread mGLThread; private GLWrapper mGLWrapper; }
Java
package com.google.android.webviewdemo; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.webkit.JsResult; import android.webkit.WebChromeClient; import android.webkit.WebSettings; import android.webkit.WebView; /** * Demonstrates how to embed a WebView in your activity. Also demonstrates how * to have javascript in the WebView call into the activity, and how the activity * can invoke javascript. * <p> * In this example, clicking on the android in the WebView will result in a call into * the activities code in {@link DemoJavaScriptInterface#clickOnAndroid()}. This code * will turn around and invoke javascript using the {@link WebView#loadUrl(String)} * method. * <p> * Obviously all of this could have been accomplished without calling into the activity * and then back into javascript, but this code is intended to show how to set up the * code paths for this sort of communication. * */ public class WebViewDemo extends Activity { private static final String LOG_TAG = "WebViewDemo"; private WebView mWebView; private Handler mHandler = new Handler(); @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); mWebView = (WebView) findViewById(R.id.webview); WebSettings webSettings = mWebView.getSettings(); webSettings.setSavePassword(false); webSettings.setSaveFormData(false); webSettings.setJavaScriptEnabled(true); webSettings.setSupportZoom(false); mWebView.setWebChromeClient(new MyWebChromeClient()); mWebView.addJavascriptInterface(new DemoJavaScriptInterface(), "demo"); mWebView.loadUrl("file:///android_asset/demo.html"); } final class DemoJavaScriptInterface { DemoJavaScriptInterface() { } /** * This is not called on the UI thread. Post a runnable to invoke * loadUrl on the UI thread. */ public void clickOnAndroid() { mHandler.post(new Runnable() { public void run() { mWebView.loadUrl("javascript:wave()"); } }); } } /** * Provides a hook for calling "alert" from javascript. Useful for * debugging your javascript. */ final class MyWebChromeClient extends WebChromeClient { @Override public boolean onJsAlert(WebView view, String url, String message, JsResult result) { Log.d(LOG_TAG, message); result.confirm(); return true; } } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.downloader; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; public class DownloaderTest extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (! DownloaderActivity.ensureDownloaded(this, getString(R.string.app_name), FILE_CONFIG_URL, CONFIG_VERSION, DATA_PATH, USER_AGENT)) { return; } setContentView(R.layout.main); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { boolean handled = true; int id = item.getItemId(); if (id == R.id.menu_main_download_again) { downloadAgain(); } else { handled = false; } if (!handled) { handled = super.onOptionsItemSelected(item); } return handled; } private void downloadAgain() { DownloaderActivity.deleteData(DATA_PATH); startActivity(getIntent()); finish(); } /** * Fill this in with your own web server. */ private final static String FILE_CONFIG_URL = "http://example.com/download.config"; private final static String CONFIG_VERSION = "1.0"; private final static String DATA_PATH = "/sdcard/data/downloadTest"; private final static String USER_AGENT = "MyApp Downloader"; }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.downloader; import android.app.Activity; import android.content.Intent; /** * Usage: * * Intent intent = PreconditionActivityHelper.createPreconditionIntent( * activity, WaitActivity.class); * // Optionally add extras to pass arguments to the intent * intent.putExtra(Utils.EXTRA_ACCOUNT, account); * PreconditionActivityHelper.startPreconditionActivityAndFinish(this, intent); * * // And in the wait activity: * PreconditionActivityHelper.startOriginalActivityAndFinish(this); * */ public class PreconditionActivityHelper { /** * Create a precondition activity intent. * @param activity the original activity * @param preconditionActivityClazz the precondition activity's class * @return an intent which will launch the precondition activity. */ public static Intent createPreconditionIntent(Activity activity, Class preconditionActivityClazz) { Intent newIntent = new Intent(); newIntent.setClass(activity, preconditionActivityClazz); newIntent.putExtra(EXTRA_WRAPPED_INTENT, activity.getIntent()); return newIntent; } /** * Start the precondition activity using a given intent, which should * have been created by calling createPreconditionIntent. * @param activity * @param intent */ public static void startPreconditionActivityAndFinish(Activity activity, Intent intent) { activity.startActivity(intent); activity.finish(); } /** * Start the original activity, and finish the precondition activity. * @param preconditionActivity */ public static void startOriginalActivityAndFinish( Activity preconditionActivity) { preconditionActivity.startActivity( (Intent) preconditionActivity.getIntent() .getParcelableExtra(EXTRA_WRAPPED_INTENT)); preconditionActivity.finish(); } static private final String EXTRA_WRAPPED_INTENT = "PreconditionActivityHelper_wrappedIntent"; }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.downloader; import android.app.Activity; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.content.DialogInterface; import android.content.Intent; import org.apache.http.impl.client.DefaultHttpClient; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.os.SystemClock; import java.security.MessageDigest; import android.util.Log; import android.util.Xml; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.Button; import android.widget.TextView; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpHead; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.security.NoSuchAlgorithmException; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; public class DownloaderActivity extends Activity { /** * Checks if data has been downloaded. If so, returns true. If not, * starts an activity to download the data and returns false. If this * function returns false the caller should immediately return from its * onCreate method. The calling activity will later be restarted * (using a copy of its original intent) once the data download completes. * @param activity The calling activity. * @param customText A text string that is displayed in the downloader UI. * @param fileConfigUrl The URL of the download configuration URL. * @param configVersion The version of the configuration file. * @param dataPath The directory on the device where we want to store the * data. * @param userAgent The user agent string to use when fetching URLs. * @return true if the data has already been downloaded successfully, or * false if the data needs to be downloaded. */ public static boolean ensureDownloaded(Activity activity, String customText, String fileConfigUrl, String configVersion, String dataPath, String userAgent) { File dest = new File(dataPath); if (dest.exists()) { // Check version if (versionMatches(dest, configVersion)) { Log.i(LOG_TAG, "Versions match, no need to download."); return true; } } Intent intent = PreconditionActivityHelper.createPreconditionIntent( activity, DownloaderActivity.class); intent.putExtra(EXTRA_CUSTOM_TEXT, customText); intent.putExtra(EXTRA_FILE_CONFIG_URL, fileConfigUrl); intent.putExtra(EXTRA_CONFIG_VERSION, configVersion); intent.putExtra(EXTRA_DATA_PATH, dataPath); intent.putExtra(EXTRA_USER_AGENT, userAgent); PreconditionActivityHelper.startPreconditionActivityAndFinish( activity, intent); return false; } /** * Delete a directory and all its descendants. * @param directory The directory to delete * @return true if the directory was deleted successfully. */ public static boolean deleteData(String directory) { return deleteTree(new File(directory), true); } private static boolean deleteTree(File base, boolean deleteBase) { boolean result = true; if (base.isDirectory()) { for (File child : base.listFiles()) { result &= deleteTree(child, true); } } if (deleteBase) { result &= base.delete(); } return result; } private static boolean versionMatches(File dest, String expectedVersion) { Config config = getLocalConfig(dest, LOCAL_CONFIG_FILE); if (config != null) { return config.version.equals(expectedVersion); } return false; } private static Config getLocalConfig(File destPath, String configFilename) { File configPath = new File(destPath, configFilename); FileInputStream is; try { is = new FileInputStream(configPath); } catch (FileNotFoundException e) { return null; } try { Config config = ConfigHandler.parse(is); return config; } catch (Exception e) { Log.e(LOG_TAG, "Unable to read local config file", e); return null; } finally { quietClose(is); } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent = getIntent(); requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); setContentView(R.layout.downloader); getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.downloader_title); ((TextView) findViewById(R.id.customText)).setText( intent.getStringExtra(EXTRA_CUSTOM_TEXT)); mProgress = (TextView) findViewById(R.id.progress); mTimeRemaining = (TextView) findViewById(R.id.time_remaining); Button button = (Button) findViewById(R.id.cancel); button.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { if (mDownloadThread != null) { mSuppressErrorMessages = true; mDownloadThread.interrupt(); } } }); startDownloadThread(); } private void startDownloadThread() { mSuppressErrorMessages = false; mProgress.setText(""); mTimeRemaining.setText(""); mDownloadThread = new Thread(new Downloader(), "Downloader"); mDownloadThread.setPriority(Thread.NORM_PRIORITY - 1); mDownloadThread.start(); } @Override protected void onResume() { super.onResume(); } @Override protected void onDestroy() { super.onDestroy(); mSuppressErrorMessages = true; mDownloadThread.interrupt(); try { mDownloadThread.join(); } catch (InterruptedException e) { // Don't care. } } private void onDownloadSucceeded() { Log.i(LOG_TAG, "Download succeeded"); PreconditionActivityHelper.startOriginalActivityAndFinish(this); } private void onDownloadFailed(String reason) { Log.e(LOG_TAG, "Download stopped: " + reason); String shortReason; int index = reason.indexOf('\n'); if (index >= 0) { shortReason = reason.substring(0, index); } else { shortReason = reason; } AlertDialog alert = new Builder(this).create(); alert.setTitle(R.string.download_activity_download_stopped); if (!mSuppressErrorMessages) { alert.setMessage(shortReason); } alert.setButton(getString(R.string.download_activity_retry), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { startDownloadThread(); } }); alert.setButton2(getString(R.string.download_activity_quit), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { finish(); } }); try { alert.show(); } catch (WindowManager.BadTokenException e) { // Happens when the Back button is used to exit the activity. // ignore. } } private void onReportProgress(int progress) { mProgress.setText(mPercentFormat.format(progress / 10000.0)); long now = SystemClock.elapsedRealtime(); if (mStartTime == 0) { mStartTime = now; } long delta = now - mStartTime; String timeRemaining = getString(R.string.download_activity_time_remaining_unknown); if ((delta > 3 * MS_PER_SECOND) && (progress > 100)) { long totalTime = 10000 * delta / progress; long timeLeft = Math.max(0L, totalTime - delta); if (timeLeft > MS_PER_DAY) { timeRemaining = Long.toString( (timeLeft + MS_PER_DAY - 1) / MS_PER_DAY) + " " + getString(R.string.download_activity_time_remaining_days); } else if (timeLeft > MS_PER_HOUR) { timeRemaining = Long.toString( (timeLeft + MS_PER_HOUR - 1) / MS_PER_HOUR) + " " + getString(R.string.download_activity_time_remaining_hours); } else if (timeLeft > MS_PER_MINUTE) { timeRemaining = Long.toString( (timeLeft + MS_PER_MINUTE - 1) / MS_PER_MINUTE) + " " + getString(R.string.download_activity_time_remaining_minutes); } else { timeRemaining = Long.toString( (timeLeft + MS_PER_SECOND - 1) / MS_PER_SECOND) + " " + getString(R.string.download_activity_time_remaining_seconds); } } mTimeRemaining.setText(timeRemaining); } private void onReportVerifying() { mProgress.setText(getString(R.string.download_activity_verifying)); mTimeRemaining.setText(""); } private static void quietClose(InputStream is) { try { if (is != null) { is.close(); } } catch (IOException e) { // Don't care. } } private static void quietClose(OutputStream os) { try { if (os != null) { os.close(); } } catch (IOException e) { // Don't care. } } private static class Config { long getSize() { long result = 0; for(File file : mFiles) { result += file.getSize(); } return result; } static class File { public File(String src, String dest, String md5, long size) { if (src != null) { this.mParts.add(new Part(src, md5, size)); } this.dest = dest; } static class Part { Part(String src, String md5, long size) { this.src = src; this.md5 = md5; this.size = size; } String src; String md5; long size; } ArrayList<Part> mParts = new ArrayList<Part>(); String dest; long getSize() { long result = 0; for(Part part : mParts) { if (part.size > 0) { result += part.size; } } return result; } } String version; ArrayList<File> mFiles = new ArrayList<File>(); } /** * <config version=""> * <file src="http:..." dest ="b.x" /> * <file dest="b.x"> * <part src="http:..." /> * ... * ... * </config> * */ private static class ConfigHandler extends DefaultHandler { public static Config parse(InputStream is) throws SAXException, UnsupportedEncodingException, IOException { ConfigHandler handler = new ConfigHandler(); Xml.parse(is, Xml.findEncodingByName("UTF-8"), handler); return handler.mConfig; } private ConfigHandler() { mConfig = new Config(); } @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (localName.equals("config")) { mConfig.version = getRequiredString(attributes, "version"); } else if (localName.equals("file")) { String src = attributes.getValue("", "src"); String dest = getRequiredString(attributes, "dest"); String md5 = attributes.getValue("", "md5"); long size = getLong(attributes, "size", -1); mConfig.mFiles.add(new Config.File(src, dest, md5, size)); } else if (localName.equals("part")) { String src = getRequiredString(attributes, "src"); String md5 = attributes.getValue("", "md5"); long size = getLong(attributes, "size", -1); int length = mConfig.mFiles.size(); if (length > 0) { mConfig.mFiles.get(length-1).mParts.add( new Config.File.Part(src, md5, size)); } } } private static String getRequiredString(Attributes attributes, String localName) throws SAXException { String result = attributes.getValue("", localName); if (result == null) { throw new SAXException("Expected attribute " + localName); } return result; } private static long getLong(Attributes attributes, String localName, long defaultValue) { String value = attributes.getValue("", localName); if (value == null) { return defaultValue; } else { return Long.parseLong(value); } } public Config mConfig; } private class DownloaderException extends Exception { public DownloaderException(String reason) { super(reason); } } private class Downloader implements Runnable { public void run() { Intent intent = getIntent(); mFileConfigUrl = intent.getStringExtra(EXTRA_FILE_CONFIG_URL); mConfigVersion = intent.getStringExtra(EXTRA_CONFIG_VERSION); mDataPath = intent.getStringExtra(EXTRA_DATA_PATH); mUserAgent = intent.getStringExtra(EXTRA_USER_AGENT); mDataDir = new File(mDataPath); try { // Download files. mHttpClient = new DefaultHttpClient(); Config config = getConfig(); filter(config); persistantDownload(config); verify(config); cleanup(); reportSuccess(); } catch (Exception e) { reportFailure(e.toString() + "\n" + Log.getStackTraceString(e)); } } private void persistantDownload(Config config) throws ClientProtocolException, DownloaderException, IOException { while(true) { try { download(config); break; } catch(java.net.SocketException e) { if (mSuppressErrorMessages) { throw e; } } catch(java.net.SocketTimeoutException e) { if (mSuppressErrorMessages) { throw e; } } Log.i(LOG_TAG, "Network connectivity issue, retrying."); } } private void filter(Config config) throws IOException, DownloaderException { File filteredFile = new File(mDataDir, LOCAL_FILTERED_FILE); if (filteredFile.exists()) { return; } File localConfigFile = new File(mDataDir, LOCAL_CONFIG_FILE_TEMP); HashSet<String> keepSet = new HashSet<String>(); keepSet.add(localConfigFile.getCanonicalPath()); HashMap<String, Config.File> fileMap = new HashMap<String, Config.File>(); for(Config.File file : config.mFiles) { String canonicalPath = new File(mDataDir, file.dest).getCanonicalPath(); fileMap.put(canonicalPath, file); } recursiveFilter(mDataDir, fileMap, keepSet, false); touch(filteredFile); } private void touch(File file) throws FileNotFoundException { FileOutputStream os = new FileOutputStream(file); quietClose(os); } private boolean recursiveFilter(File base, HashMap<String, Config.File> fileMap, HashSet<String> keepSet, boolean filterBase) throws IOException, DownloaderException { boolean result = true; if (base.isDirectory()) { for (File child : base.listFiles()) { result &= recursiveFilter(child, fileMap, keepSet, true); } } if (filterBase) { if (base.isDirectory()) { if (base.listFiles().length == 0) { result &= base.delete(); } } else { if (!shouldKeepFile(base, fileMap, keepSet)) { result &= base.delete(); } } } return result; } private boolean shouldKeepFile(File file, HashMap<String, Config.File> fileMap, HashSet<String> keepSet) throws IOException, DownloaderException { String canonicalPath = file.getCanonicalPath(); if (keepSet.contains(canonicalPath)) { return true; } Config.File configFile = fileMap.get(canonicalPath); if (configFile == null) { return false; } return verifyFile(configFile, false); } private void reportSuccess() { mHandler.sendMessage( Message.obtain(mHandler, MSG_DOWNLOAD_SUCCEEDED)); } private void reportFailure(String reason) { mHandler.sendMessage( Message.obtain(mHandler, MSG_DOWNLOAD_FAILED, reason)); } private void reportProgress(int progress) { mHandler.sendMessage( Message.obtain(mHandler, MSG_REPORT_PROGRESS, progress, 0)); } private void reportVerifying() { mHandler.sendMessage( Message.obtain(mHandler, MSG_REPORT_VERIFYING)); } private Config getConfig() throws DownloaderException, ClientProtocolException, IOException, SAXException { Config config = null; if (mDataDir.exists()) { config = getLocalConfig(mDataDir, LOCAL_CONFIG_FILE_TEMP); if ((config == null) || !mConfigVersion.equals(config.version)) { if (config == null) { Log.i(LOG_TAG, "Couldn't find local config."); } else { Log.i(LOG_TAG, "Local version out of sync. Wanted " + mConfigVersion + " but have " + config.version); } config = null; } } else { Log.i(LOG_TAG, "Creating directory " + mDataPath); mDataDir.mkdirs(); mDataDir.mkdir(); if (!mDataDir.exists()) { throw new DownloaderException( "Could not create the directory " + mDataPath); } } if (config == null) { File localConfig = download(mFileConfigUrl, LOCAL_CONFIG_FILE_TEMP); InputStream is = new FileInputStream(localConfig); try { config = ConfigHandler.parse(is); } finally { quietClose(is); } if (! config.version.equals(mConfigVersion)) { throw new DownloaderException( "Configuration file version mismatch. Expected " + mConfigVersion + " received " + config.version); } } return config; } private void noisyDelete(File file) throws IOException { if (! file.delete() ) { throw new IOException("could not delete " + file); } } private void download(Config config) throws DownloaderException, ClientProtocolException, IOException { mDownloadedSize = 0; getSizes(config); Log.i(LOG_TAG, "Total bytes to download: " + mTotalExpectedSize); for(Config.File file : config.mFiles) { downloadFile(file); } } private void downloadFile(Config.File file) throws DownloaderException, FileNotFoundException, IOException, ClientProtocolException { boolean append = false; File dest = new File(mDataDir, file.dest); long bytesToSkip = 0; if (dest.exists() && dest.isFile()) { append = true; bytesToSkip = dest.length(); mDownloadedSize += bytesToSkip; } FileOutputStream os = null; long offsetOfCurrentPart = 0; try { for(Config.File.Part part : file.mParts) { // The part.size==0 check below allows us to download // zero-length files. if ((part.size > bytesToSkip) || (part.size == 0)) { MessageDigest digest = null; if (part.md5 != null) { digest = createDigest(); if (bytesToSkip > 0) { FileInputStream is = openInput(file.dest); try { is.skip(offsetOfCurrentPart); readIntoDigest(is, bytesToSkip, digest); } finally { quietClose(is); } } } if (os == null) { os = openOutput(file.dest, append); } downloadPart(part.src, os, bytesToSkip, part.size, digest); if (digest != null) { String hash = getHash(digest); if (!hash.equalsIgnoreCase(part.md5)) { Log.e(LOG_TAG, "web MD5 checksums don't match. " + part.src + "\nExpected " + part.md5 + "\n got " + hash); quietClose(os); dest.delete(); throw new DownloaderException( "Received bad data from web server"); } else { Log.i(LOG_TAG, "web MD5 checksum matches."); } } } bytesToSkip -= Math.min(bytesToSkip, part.size); offsetOfCurrentPart += part.size; } } finally { quietClose(os); } } private void cleanup() throws IOException { File filtered = new File(mDataDir, LOCAL_FILTERED_FILE); noisyDelete(filtered); File tempConfig = new File(mDataDir, LOCAL_CONFIG_FILE_TEMP); File realConfig = new File(mDataDir, LOCAL_CONFIG_FILE); tempConfig.renameTo(realConfig); } private void verify(Config config) throws DownloaderException, ClientProtocolException, IOException { Log.i(LOG_TAG, "Verifying..."); String failFiles = null; for(Config.File file : config.mFiles) { if (! verifyFile(file, true) ) { if (failFiles == null) { failFiles = file.dest; } else { failFiles += " " + file.dest; } } } if (failFiles != null) { throw new DownloaderException( "Possible bad SD-Card. MD5 sum incorrect for file(s) " + failFiles); } } private boolean verifyFile(Config.File file, boolean deleteInvalid) throws FileNotFoundException, DownloaderException, IOException { Log.i(LOG_TAG, "verifying " + file.dest); reportVerifying(); File dest = new File(mDataDir, file.dest); if (! dest.exists()) { Log.e(LOG_TAG, "File does not exist: " + dest.toString()); return false; } long fileSize = file.getSize(); long destLength = dest.length(); if (fileSize != destLength) { Log.e(LOG_TAG, "Length doesn't match. Expected " + fileSize + " got " + destLength); if (deleteInvalid) { dest.delete(); return false; } } FileInputStream is = new FileInputStream(dest); try { for(Config.File.Part part : file.mParts) { if (part.md5 == null) { continue; } MessageDigest digest = createDigest(); readIntoDigest(is, part.size, digest); String hash = getHash(digest); if (!hash.equalsIgnoreCase(part.md5)) { Log.e(LOG_TAG, "MD5 checksums don't match. " + part.src + " Expected " + part.md5 + " got " + hash); if (deleteInvalid) { quietClose(is); dest.delete(); } return false; } } } finally { quietClose(is); } return true; } private void readIntoDigest(FileInputStream is, long bytesToRead, MessageDigest digest) throws IOException { while(bytesToRead > 0) { int chunkSize = (int) Math.min(mFileIOBuffer.length, bytesToRead); int bytesRead = is.read(mFileIOBuffer, 0, chunkSize); if (bytesRead < 0) { break; } updateDigest(digest, bytesRead); bytesToRead -= bytesRead; } } private MessageDigest createDigest() throws DownloaderException { MessageDigest digest; try { digest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new DownloaderException("Couldn't create MD5 digest"); } return digest; } private void updateDigest(MessageDigest digest, int bytesRead) { if (bytesRead == mFileIOBuffer.length) { digest.update(mFileIOBuffer); } else { // Work around an awkward API: Create a // new buffer with just the valid bytes byte[] temp = new byte[bytesRead]; System.arraycopy(mFileIOBuffer, 0, temp, 0, bytesRead); digest.update(temp); } } private String getHash(MessageDigest digest) { StringBuilder builder = new StringBuilder(); for(byte b : digest.digest()) { builder.append(Integer.toHexString((b >> 4) & 0xf)); builder.append(Integer.toHexString(b & 0xf)); } return builder.toString(); } /** * Ensure we have sizes for all the items. * @param config * @throws ClientProtocolException * @throws IOException * @throws DownloaderException */ private void getSizes(Config config) throws ClientProtocolException, IOException, DownloaderException { for (Config.File file : config.mFiles) { for(Config.File.Part part : file.mParts) { if (part.size < 0) { part.size = getSize(part.src); } } } mTotalExpectedSize = config.getSize(); } private long getSize(String url) throws ClientProtocolException, IOException { url = normalizeUrl(url); Log.i(LOG_TAG, "Head " + url); HttpHead httpGet = new HttpHead(url); HttpResponse response = mHttpClient.execute(httpGet); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { throw new IOException("Unexpected Http status code " + response.getStatusLine().getStatusCode()); } Header[] clHeaders = response.getHeaders("Content-Length"); if (clHeaders.length > 0) { Header header = clHeaders[0]; return Long.parseLong(header.getValue()); } return -1; } private String normalizeUrl(String url) throws MalformedURLException { return (new URL(new URL(mFileConfigUrl), url)).toString(); } private InputStream get(String url, long startOffset, long expectedLength) throws ClientProtocolException, IOException { url = normalizeUrl(url); Log.i(LOG_TAG, "Get " + url); mHttpGet = new HttpGet(url); int expectedStatusCode = HttpStatus.SC_OK; if (startOffset > 0) { String range = "bytes=" + startOffset + "-"; if (expectedLength >= 0) { range += expectedLength-1; } Log.i(LOG_TAG, "requesting byte range " + range); mHttpGet.addHeader("Range", range); expectedStatusCode = HttpStatus.SC_PARTIAL_CONTENT; } HttpResponse response = mHttpClient.execute(mHttpGet); long bytesToSkip = 0; int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != expectedStatusCode) { if ((statusCode == HttpStatus.SC_OK) && (expectedStatusCode == HttpStatus.SC_PARTIAL_CONTENT)) { Log.i(LOG_TAG, "Byte range request ignored"); bytesToSkip = startOffset; } else { throw new IOException("Unexpected Http status code " + statusCode + " expected " + expectedStatusCode); } } HttpEntity entity = response.getEntity(); InputStream is = entity.getContent(); if (bytesToSkip > 0) { is.skip(bytesToSkip); } return is; } private File download(String src, String dest) throws DownloaderException, ClientProtocolException, IOException { File destFile = new File(mDataDir, dest); FileOutputStream os = openOutput(dest, false); try { downloadPart(src, os, 0, -1, null); } finally { os.close(); } return destFile; } private void downloadPart(String src, FileOutputStream os, long startOffset, long expectedLength, MessageDigest digest) throws ClientProtocolException, IOException, DownloaderException { boolean lengthIsKnown = expectedLength >= 0; if (startOffset < 0) { throw new IllegalArgumentException("Negative startOffset:" + startOffset); } if (lengthIsKnown && (startOffset > expectedLength)) { throw new IllegalArgumentException( "startOffset > expectedLength" + startOffset + " " + expectedLength); } InputStream is = get(src, startOffset, expectedLength); try { long bytesRead = downloadStream(is, os, digest); if (lengthIsKnown) { long expectedBytesRead = expectedLength - startOffset; if (expectedBytesRead != bytesRead) { Log.e(LOG_TAG, "Bad file transfer from server: " + src + " Expected " + expectedBytesRead + " Received " + bytesRead); throw new DownloaderException( "Incorrect number of bytes received from server"); } } } finally { is.close(); mHttpGet = null; } } private FileOutputStream openOutput(String dest, boolean append) throws FileNotFoundException, DownloaderException { File destFile = new File(mDataDir, dest); File parent = destFile.getParentFile(); if (! parent.exists()) { parent.mkdirs(); } if (! parent.exists()) { throw new DownloaderException("Could not create directory " + parent.toString()); } FileOutputStream os = new FileOutputStream(destFile, append); return os; } private FileInputStream openInput(String src) throws FileNotFoundException, DownloaderException { File srcFile = new File(mDataDir, src); File parent = srcFile.getParentFile(); if (! parent.exists()) { parent.mkdirs(); } if (! parent.exists()) { throw new DownloaderException("Could not create directory " + parent.toString()); } return new FileInputStream(srcFile); } private long downloadStream(InputStream is, FileOutputStream os, MessageDigest digest) throws DownloaderException, IOException { long totalBytesRead = 0; while(true){ if (Thread.interrupted()) { Log.i(LOG_TAG, "downloader thread interrupted."); mHttpGet.abort(); throw new DownloaderException("Thread interrupted"); } int bytesRead = is.read(mFileIOBuffer); if (bytesRead < 0) { break; } if (digest != null) { updateDigest(digest, bytesRead); } totalBytesRead += bytesRead; os.write(mFileIOBuffer, 0, bytesRead); mDownloadedSize += bytesRead; int progress = (int) (Math.min(mTotalExpectedSize, mDownloadedSize * 10000 / Math.max(1, mTotalExpectedSize))); if (progress != mReportedProgress) { mReportedProgress = progress; reportProgress(progress); } } return totalBytesRead; } private DefaultHttpClient mHttpClient; private HttpGet mHttpGet; private String mFileConfigUrl; private String mConfigVersion; private String mDataPath; private File mDataDir; private String mUserAgent; private long mTotalExpectedSize; private long mDownloadedSize; private int mReportedProgress; private final static int CHUNK_SIZE = 32 * 1024; byte[] mFileIOBuffer = new byte[CHUNK_SIZE]; } private final static String LOG_TAG = "Downloader"; private TextView mProgress; private TextView mTimeRemaining; private final DecimalFormat mPercentFormat = new DecimalFormat("0.00 %"); private long mStartTime; private Thread mDownloadThread; private boolean mSuppressErrorMessages; private final static long MS_PER_SECOND = 1000; private final static long MS_PER_MINUTE = 60 * 1000; private final static long MS_PER_HOUR = 60 * 60 * 1000; private final static long MS_PER_DAY = 24 * 60 * 60 * 1000; private final static String LOCAL_CONFIG_FILE = ".downloadConfig"; private final static String LOCAL_CONFIG_FILE_TEMP = ".downloadConfig_temp"; private final static String LOCAL_FILTERED_FILE = ".downloadConfig_filtered"; private final static String EXTRA_CUSTOM_TEXT = "DownloaderActivity_custom_text"; private final static String EXTRA_FILE_CONFIG_URL = "DownloaderActivity_config_url"; private final static String EXTRA_CONFIG_VERSION = "DownloaderActivity_config_version"; private final static String EXTRA_DATA_PATH = "DownloaderActivity_data_path"; private final static String EXTRA_USER_AGENT = "DownloaderActivity_user_agent"; private final static int MSG_DOWNLOAD_SUCCEEDED = 0; private final static int MSG_DOWNLOAD_FAILED = 1; private final static int MSG_REPORT_PROGRESS = 2; private final static int MSG_REPORT_VERIFYING = 3; private final Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case MSG_DOWNLOAD_SUCCEEDED: onDownloadSucceeded(); break; case MSG_DOWNLOAD_FAILED: onDownloadFailed((String) msg.obj); break; case MSG_REPORT_PROGRESS: onReportProgress(msg.arg1); break; case MSG_REPORT_VERIFYING: onReportVerifying(); break; default: throw new IllegalArgumentException("Unknown message id " + msg.what); } } }; }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.lolcat; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.Typeface; import android.graphics.drawable.BitmapDrawable; import android.net.Uri; import android.text.TextUtils; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import android.widget.ImageView; /** * Lolcat-specific subclass of ImageView, which manages the various * scaled-down Bitmaps and knows how to render and manipulate the * image captions. */ public class LolcatView extends ImageView { private static final String TAG = "LolcatView"; // Standard lolcat size is 500x375. (But to preserve the original // image's aspect ratio, we rescale so that the larger dimension ends // up being 500 pixels.) private static final float SCALED_IMAGE_MAX_DIMENSION = 500f; // Other standard lolcat image parameters private static final int FONT_SIZE = 44; private Bitmap mScaledBitmap; // The photo picked by the user, scaled-down private Bitmap mWorkingBitmap; // The Bitmap we render the caption text into // Current state of the captions. // TODO: This array currently has a hardcoded length of 2 (for "top" // and "bottom" captions), but eventually should support as many // captions as the user wants to add. private final Caption[] mCaptions = new Caption[] { new Caption(), new Caption() }; // State used while dragging a caption around private boolean mDragging; private int mDragCaptionIndex; // index of the caption (in mCaptions[]) that's being dragged private int mTouchDownX, mTouchDownY; private final Rect mInitialDragBox = new Rect(); private final Rect mCurrentDragBox = new Rect(); private final RectF mCurrentDragBoxF = new RectF(); // used in onDraw() private final RectF mTransformedDragBoxF = new RectF(); // used in onDraw() private final Rect mTmpRect = new Rect(); public LolcatView(Context context) { super(context); } public LolcatView(Context context, AttributeSet attrs) { super(context, attrs); } public LolcatView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public Bitmap getWorkingBitmap() { return mWorkingBitmap; } public String getTopCaption() { return mCaptions[0].caption; } public String getBottomCaption() { return mCaptions[1].caption; } /** * @return true if the user has set caption(s) for this LolcatView. */ public boolean hasValidCaption() { return !TextUtils.isEmpty(mCaptions[0].caption) || !TextUtils.isEmpty(mCaptions[1].caption); } public void clear() { mScaledBitmap = null; mWorkingBitmap = null; setImageDrawable(null); // TODO: Anything else we need to do here to release resources // associated with this object, like maybe the Bitmap that got // created by the previous setImageURI() call? } public void loadFromUri(Uri uri) { // For now, directly load the specified Uri. setImageURI(uri); // TODO: Rather than calling setImageURI() with the URI of // the (full-size) photo, it would be better to turn the URI into // a scaled-down Bitmap right here, and load *that* into ourself. // I'd do that basically the same way that ImageView.setImageURI does it: // [ . . . ] // android.graphics.BitmapFactory.nativeDecodeStream(Native Method) // android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:304) // android.graphics.drawable.Drawable.createFromStream(Drawable.java:635) // android.widget.ImageView.resolveUri(ImageView.java:477) // android.widget.ImageView.setImageURI(ImageView.java:281) // [ . . . ] // But for now let's let ImageView do the work: we call setImageURI (above) // and immediately pull out a Bitmap (below). // Stash away a scaled-down bitmap. // TODO: is it safe to assume this will always be a BitmapDrawable? BitmapDrawable drawable = (BitmapDrawable) getDrawable(); Log.i(TAG, "===> current drawable: " + drawable); Bitmap fullSizeBitmap = drawable.getBitmap(); Log.i(TAG, "===> fullSizeBitmap: " + fullSizeBitmap + " dimensions: " + fullSizeBitmap.getWidth() + " x " + fullSizeBitmap.getHeight()); Bitmap.Config config = fullSizeBitmap.getConfig(); Log.i(TAG, " - config = " + config); // Standard lolcat size is 500x375. But we don't want to distort // the image if it isn't 4x3, so let's just set the larger // dimension to 500 pixels and preserve the source aspect ratio. float origWidth = fullSizeBitmap.getWidth(); float origHeight = fullSizeBitmap.getHeight(); float aspect = origWidth / origHeight; Log.i(TAG, " - aspect = " + aspect + "(" + origWidth + " x " + origHeight + ")"); float scaleFactor = ((aspect > 1.0) ? origWidth : origHeight) / SCALED_IMAGE_MAX_DIMENSION; int scaledWidth = Math.round(origWidth / scaleFactor); int scaledHeight = Math.round(origHeight / scaleFactor); mScaledBitmap = Bitmap.createScaledBitmap(fullSizeBitmap, scaledWidth, scaledHeight, true /* filter */); Log.i(TAG, " ===> mScaledBitmap: " + mScaledBitmap + " dimensions: " + mScaledBitmap.getWidth() + " x " + mScaledBitmap.getHeight()); Log.i(TAG, " isMutable = " + mScaledBitmap.isMutable()); } /** * Sets the captions for this LolcatView. */ public void setCaptions(String topCaption, String bottomCaption) { Log.i(TAG, "setCaptions: '" + topCaption + "', '" + bottomCaption + "'"); if (topCaption == null) topCaption = ""; if (bottomCaption == null) bottomCaption = ""; mCaptions[0].caption = topCaption; mCaptions[1].caption = bottomCaption; // If the user clears a caption, reset its position (so that it'll // come back in the default position if the user re-adds it.) if (TextUtils.isEmpty(mCaptions[0].caption)) { Log.i(TAG, "- invalidating position of caption 0..."); mCaptions[0].positionValid = false; } if (TextUtils.isEmpty(mCaptions[1].caption)) { Log.i(TAG, "- invalidating position of caption 1..."); mCaptions[1].positionValid = false; } // And *any* time the captions change, blow away the cached // caption bounding boxes to make sure we'll recompute them in // renderCaptions(). mCaptions[0].captionBoundingBox = null; mCaptions[1].captionBoundingBox = null; renderCaptions(mCaptions); } /** * Clears the captions for this LolcatView. */ public void clearCaptions() { setCaptions("", ""); } /** * Renders this LolcatView's current image captions into our * underlying ImageView. * * We start with a scaled-down version of the photo originally chosed * by the user (mScaledBitmap), make a mutable copy (mWorkingBitmap), * render the specified strings into the bitmap, and show the * resulting image onscreen. */ public void renderCaptions(Caption[] captions) { // TODO: handle an arbitrary array of strings, rather than // assuming "top" and "bottom" captions. String topString = captions[0].caption; boolean topStringValid = !TextUtils.isEmpty(topString); String bottomString = captions[1].caption; boolean bottomStringValid = !TextUtils.isEmpty(bottomString); Log.i(TAG, "renderCaptions: '" + topString + "', '" + bottomString + "'"); if (mScaledBitmap == null) return; // Make a fresh (mutable) copy of the scaled-down photo Bitmap, // and render the desired text into it. Bitmap.Config config = mScaledBitmap.getConfig(); Log.i(TAG, " - mScaledBitmap config = " + config); mWorkingBitmap = mScaledBitmap.copy(config, true /* isMutable */); Log.i(TAG, " ===> mWorkingBitmap: " + mWorkingBitmap + " dimensions: " + mWorkingBitmap.getWidth() + " x " + mWorkingBitmap.getHeight()); Log.i(TAG, " isMutable = " + mWorkingBitmap.isMutable()); Canvas canvas = new Canvas(mWorkingBitmap); Log.i(TAG, "- Canvas: " + canvas + " dimensions: " + canvas.getWidth() + " x " + canvas.getHeight()); Paint textPaint = new Paint(); textPaint.setAntiAlias(true); textPaint.setTextSize(FONT_SIZE); textPaint.setColor(0xFFFFFFFF); Log.i(TAG, "- Paint: " + textPaint); Typeface face = textPaint.getTypeface(); Log.i(TAG, "- default typeface: " + face); // The most standard font for lolcat captions is Impact. (Arial // Black is also common.) Unfortunately we don't have either of // these on the device by default; the closest we can do is // DroidSans-Bold: face = Typeface.DEFAULT_BOLD; Log.i(TAG, "- new face: " + face); textPaint.setTypeface(face); // Look up the positions of the captions, or if this is our very // first time rendering them, initialize the positions to default // values. final int edgeBorder = 20; final int fontHeight = textPaint.getFontMetricsInt(null); Log.i(TAG, "- fontHeight: " + fontHeight); Log.i(TAG, "- Caption positioning:"); int topX = 0; int topY = 0; if (topStringValid) { if (mCaptions[0].positionValid) { topX = mCaptions[0].xpos; topY = mCaptions[0].ypos; Log.i(TAG, " - TOP: already had a valid position: " + topX + ", " + topY); } else { // Start off with the "top" caption at the upper-left: topX = edgeBorder; topY = edgeBorder + (fontHeight * 3 / 4); mCaptions[0].setPosition(topX, topY); Log.i(TAG, " - TOP: initializing to default position: " + topX + ", " + topY); } } int bottomX = 0; int bottomY = 0; if (bottomStringValid) { if (mCaptions[1].positionValid) { bottomX = mCaptions[1].xpos; bottomY = mCaptions[1].ypos; Log.i(TAG, " - Bottom: already had a valid position: " + bottomX + ", " + bottomY); } else { // Start off with the "bottom" caption at the lower-right: final int bottomTextWidth = (int) textPaint.measureText(bottomString); Log.i(TAG, "- bottomTextWidth (" + bottomString + "): " + bottomTextWidth); bottomX = canvas.getWidth() - edgeBorder - bottomTextWidth; bottomY = canvas.getHeight() - edgeBorder; mCaptions[1].setPosition(bottomX, bottomY); Log.i(TAG, " - BOTTOM: initializing to default position: " + bottomX + ", " + bottomY); } } // Finally, render the text. // Standard lolcat captions are drawn in white with a heavy black // outline (i.e. white fill, black stroke). Our Canvas APIs can't // do this exactly, though. // We *could* get something decent-looking using a regular // drop-shadow, like this: // textPaint.setShadowLayer(3.0f, 3, 3, 0xff000000); // but instead let's simulate the "outline" style by drawing the // text 4 separate times, with the shadow in a different direction // each time. // (TODO: This is a hack, and still doesn't look as good // as a real "white fill, black stroke" style.) final float shadowRadius = 2.0f; final int shadowOffset = 2; final int shadowColor = 0xff000000; // TODO: Right now we use offsets of 2,2 / -2,2 / 2,-2 / -2,-2 . // But 2,0 / 0,2 / -2,0 / 0,-2 might look better. textPaint.setShadowLayer(shadowRadius, shadowOffset, shadowOffset, shadowColor); if (topStringValid) canvas.drawText(topString, topX, topY, textPaint); if (bottomStringValid) canvas.drawText(bottomString, bottomX, bottomY, textPaint); // textPaint.setShadowLayer(shadowRadius, -shadowOffset, shadowOffset, shadowColor); if (topStringValid) canvas.drawText(topString, topX, topY, textPaint); if (bottomStringValid) canvas.drawText(bottomString, bottomX, bottomY, textPaint); // textPaint.setShadowLayer(shadowRadius, shadowOffset, -shadowOffset, shadowColor); if (topStringValid) canvas.drawText(topString, topX, topY, textPaint); if (bottomStringValid) canvas.drawText(bottomString, bottomX, bottomY, textPaint); // textPaint.setShadowLayer(shadowRadius, -shadowOffset, -shadowOffset, shadowColor); if (topStringValid) canvas.drawText(topString, topX, topY, textPaint); if (bottomStringValid) canvas.drawText(bottomString, bottomX, bottomY, textPaint); // Stash away bounding boxes for the captions if this // is our first time rendering them. // Watch out: the x/y position we use for drawing the text is // actually the *lower* left corner of the bounding box... int textWidth, textHeight; if (topStringValid && mCaptions[0].captionBoundingBox == null) { Log.i(TAG, "- Computing initial bounding box for top caption..."); textPaint.getTextBounds(topString, 0, topString.length(), mTmpRect); textWidth = mTmpRect.width(); textHeight = mTmpRect.height(); Log.i(TAG, "- text dimensions: " + textWidth + " x " + textHeight); mCaptions[0].captionBoundingBox = new Rect(topX, topY - textHeight, topX + textWidth, topY); Log.i(TAG, "- RESULTING RECT: " + mCaptions[0].captionBoundingBox); } if (bottomStringValid && mCaptions[1].captionBoundingBox == null) { Log.i(TAG, "- Computing initial bounding box for bottom caption..."); textPaint.getTextBounds(bottomString, 0, bottomString.length(), mTmpRect); textWidth = mTmpRect.width(); textHeight = mTmpRect.height(); Log.i(TAG, "- text dimensions: " + textWidth + " x " + textHeight); mCaptions[1].captionBoundingBox = new Rect(bottomX, bottomY - textHeight, bottomX + textWidth, bottomY); Log.i(TAG, "- RESULTING RECT: " + mCaptions[1].captionBoundingBox); } // Finally, display the new Bitmap to the user: setImageBitmap(mWorkingBitmap); } @Override protected void onDraw(Canvas canvas) { Log.i(TAG, "onDraw: " + canvas); super.onDraw(canvas); if (mDragging) { Log.i(TAG, "- dragging! Drawing box at " + mCurrentDragBox); // mCurrentDragBox is in the coordinate system of our bitmap; // need to convert it into the coordinate system of the // overall LolcatView. // // To transform between coordinate systems we need to apply the // transformation described by the ImageView's matrix *and* also // account for our left and top padding. Matrix m = getImageMatrix(); mCurrentDragBoxF.set(mCurrentDragBox); m.mapRect(mTransformedDragBoxF, mCurrentDragBoxF); mTransformedDragBoxF.offset(getPaddingLeft(), getPaddingTop()); Paint p = new Paint(); p.setColor(0xFFFFFFFF); p.setStyle(Paint.Style.STROKE); p.setStrokeWidth(2f); Log.i(TAG, "- Paint: " + p); canvas.drawRect(mTransformedDragBoxF, p); } } @Override public boolean onTouchEvent(MotionEvent ev) { Log.i(TAG, "onTouchEvent: " + ev); // Watch out: ev.getX() and ev.getY() are in the // coordinate system of the entire LolcatView, although // all the positions and rects we use here (like // mCaptions[].captionBoundingBox) are relative to the bitmap // that's drawn inside the LolcatView. // // To transform between coordinate systems we need to apply the // transformation described by the ImageView's matrix *and* also // account for our left and top padding. Matrix m = getImageMatrix(); Matrix invertedMatrix = new Matrix(); m.invert(invertedMatrix); float[] pointArray = new float[] { ev.getX() - getPaddingLeft(), ev.getY() - getPaddingTop() }; Log.i(TAG, " - BEFORE: pointArray = " + pointArray[0] + ", " + pointArray[1]); // Transform the X/Y position of the DOWN event back into bitmap coords invertedMatrix.mapPoints(pointArray); Log.i(TAG, " - AFTER: pointArray = " + pointArray[0] + ", " + pointArray[1]); int eventX = (int) pointArray[0]; int eventY = (int) pointArray[1]; int action = ev.getAction(); switch (action) { case MotionEvent.ACTION_DOWN: if (mDragging) { Log.w(TAG, "Got an ACTION_DOWN, but we were already dragging!"); mDragging = false; // and continue as if we weren't already dragging... } if (!hasValidCaption()) { Log.w(TAG, "No caption(s) yet; ignoring this ACTION_DOWN event."); return true; } // See if this DOWN event hit one of the caption bounding // boxes. If so, start dragging! for (int i = 0; i < mCaptions.length; i++) { Rect boundingBox = mCaptions[i].captionBoundingBox; Log.i(TAG, " - boundingBox #" + i + ": " + boundingBox + "..."); if (boundingBox != null) { // Expand the bounding box by a fudge factor to make it // easier to hit (since touch accuracy is pretty poor on a // real device, and the captions are fairly small...) mTmpRect.set(boundingBox); final int touchPositionSlop = 40; // pixels mTmpRect.inset(-touchPositionSlop, -touchPositionSlop); Log.i(TAG, " - Checking expanded bounding box #" + i + ": " + mTmpRect + "..."); if (mTmpRect.contains(eventX, eventY)) { Log.i(TAG, " - Hit! " + mCaptions[i]); mDragging = true; mDragCaptionIndex = i; break; } } } if (!mDragging) { Log.i(TAG, "- ACTION_DOWN event didn't hit any captions; ignoring."); return true; } mTouchDownX = eventX; mTouchDownY = eventY; mInitialDragBox.set(mCaptions[mDragCaptionIndex].captionBoundingBox); mCurrentDragBox.set(mCaptions[mDragCaptionIndex].captionBoundingBox); invalidate(); return true; case MotionEvent.ACTION_MOVE: if (!mDragging) { return true; } int displacementX = eventX - mTouchDownX; int displacementY = eventY - mTouchDownY; mCurrentDragBox.set(mInitialDragBox); mCurrentDragBox.offset(displacementX, displacementY); invalidate(); return true; case MotionEvent.ACTION_UP: if (!mDragging) { return true; } mDragging = false; // Reposition the selected caption! Log.i(TAG, "- Done dragging! Repositioning caption #" + mDragCaptionIndex + ": " + mCaptions[mDragCaptionIndex]); int offsetX = eventX - mTouchDownX; int offsetY = eventY - mTouchDownY; Log.i(TAG, " - OFFSET: " + offsetX + ", " + offsetY); // Reposition the the caption we just dragged, and blow // away the cached bounding box to make sure it'll get // recomputed in renderCaptions(). mCaptions[mDragCaptionIndex].xpos += offsetX; mCaptions[mDragCaptionIndex].ypos += offsetY; mCaptions[mDragCaptionIndex].captionBoundingBox = null; Log.i(TAG, " - Updated caption: " + mCaptions[mDragCaptionIndex]); // Finally, refresh the screen. renderCaptions(mCaptions); return true; // This case isn't expected to happen. case MotionEvent.ACTION_CANCEL: if (!mDragging) { return true; } mDragging = false; // Refresh the screen. renderCaptions(mCaptions); return true; default: return super.onTouchEvent(ev); } } /** * Returns an array containing the xpos/ypos of each Caption in our * array of captions. (This method and setCaptionPositions() are used * by LolcatActivity to save and restore the activity state across * orientation changes.) */ public int[] getCaptionPositions() { // TODO: mCaptions currently has a hardcoded length of 2 (for // "top" and "bottom" captions). int[] captionPositions = new int[4]; if (mCaptions[0].positionValid) { captionPositions[0] = mCaptions[0].xpos; captionPositions[1] = mCaptions[0].ypos; } else { captionPositions[0] = -1; captionPositions[1] = -1; } if (mCaptions[1].positionValid) { captionPositions[2] = mCaptions[1].xpos; captionPositions[3] = mCaptions[1].ypos; } else { captionPositions[2] = -1; captionPositions[3] = -1; } Log.i(TAG, "getCaptionPositions: returning " + captionPositions); return captionPositions; } /** * Sets the xpos and ypos values of each Caption in our array based on * the specified values. (This method and getCaptionPositions() are * used by LolcatActivity to save and restore the activity state * across orientation changes.) */ public void setCaptionPositions(int[] captionPositions) { // TODO: mCaptions currently has a hardcoded length of 2 (for // "top" and "bottom" captions). Log.i(TAG, "setCaptionPositions(" + captionPositions + ")..."); if (captionPositions[0] < 0) { mCaptions[0].positionValid = false; Log.i(TAG, "- TOP caption: no valid position"); } else { mCaptions[0].setPosition(captionPositions[0], captionPositions[1]); Log.i(TAG, "- TOP caption: got valid position: " + mCaptions[0].xpos + ", " + mCaptions[0].ypos); } if (captionPositions[2] < 0) { mCaptions[1].positionValid = false; Log.i(TAG, "- BOTTOM caption: no valid position"); } else { mCaptions[1].setPosition(captionPositions[2], captionPositions[3]); Log.i(TAG, "- BOTTOM caption: got valid position: " + mCaptions[1].xpos + ", " + mCaptions[1].ypos); } // Finally, refresh the screen. renderCaptions(mCaptions); } /** * Structure used to hold the entire state of a single caption. */ class Caption { public String caption; public Rect captionBoundingBox; // updated by renderCaptions() public int xpos, ypos; public boolean positionValid; public void setPosition(int x, int y) { positionValid = true; xpos = x; ypos = y; // Also blow away the cached bounding box, to make sure it'll // get recomputed in renderCaptions(). captionBoundingBox = null; } @Override public String toString() { return "Caption['" + caption + "'; bbox " + captionBoundingBox + "; pos " + xpos + ", " + ypos + "; posValid = " + positionValid + "]"; } } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.lolcat; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import android.media.MediaScannerConnection; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; /** * Lolcat builder activity. * * Instructions: * (1) Take photo of cat using Camera * (2) Run LolcatActivity * (3) Pick photo * (4) Add caption(s) * (5) Save and share * * See README.txt for a list of currently-missing features and known bugs. */ public class LolcatActivity extends Activity implements View.OnClickListener { private static final String TAG = "LolcatActivity"; // Location on the SD card for saving lolcat images private static final String LOLCAT_SAVE_DIRECTORY = "lolcats/"; // Mime type / format / extension we use (must be self-consistent!) private static final String SAVED_IMAGE_EXTENSION = ".png"; private static final Bitmap.CompressFormat SAVED_IMAGE_COMPRESS_FORMAT = Bitmap.CompressFormat.PNG; private static final String SAVED_IMAGE_MIME_TYPE = "image/png"; // UI Elements private Button mPickButton; private Button mCaptionButton; private Button mSaveButton; private Button mClearCaptionButton; private Button mClearPhotoButton; private LolcatView mLolcatView; private AlertDialog mCaptionDialog; private ProgressDialog mSaveProgressDialog; private AlertDialog mSaveSuccessDialog; private Handler mHandler; private Uri mPhotoUri; private String mSavedImageFilename; private Uri mSavedImageUri; private MediaScannerConnection mMediaScannerConnection; // Request codes used with startActivityForResult() private static final int PHOTO_PICKED = 1; // Dialog IDs private static final int DIALOG_CAPTION = 1; private static final int DIALOG_SAVE_PROGRESS = 2; private static final int DIALOG_SAVE_SUCCESS = 3; // Keys used with onSaveInstanceState() private static final String PHOTO_URI_KEY = "photo_uri"; private static final String SAVED_IMAGE_FILENAME_KEY = "saved_image_filename"; private static final String SAVED_IMAGE_URI_KEY = "saved_image_uri"; private static final String TOP_CAPTION_KEY = "top_caption"; private static final String BOTTOM_CAPTION_KEY = "bottom_caption"; private static final String CAPTION_POSITIONS_KEY = "caption_positions"; @Override protected void onCreate(Bundle icicle) { Log.i(TAG, "onCreate()... icicle = " + icicle); super.onCreate(icicle); setContentView(R.layout.lolcat_activity); // Look up various UI elements mPickButton = (Button) findViewById(R.id.pick_button); mPickButton.setOnClickListener(this); mCaptionButton = (Button) findViewById(R.id.caption_button); mCaptionButton.setOnClickListener(this); mSaveButton = (Button) findViewById(R.id.save_button); mSaveButton.setOnClickListener(this); mClearCaptionButton = (Button) findViewById(R.id.clear_caption_button); // This button doesn't exist in portrait mode. if (mClearCaptionButton != null) mClearCaptionButton.setOnClickListener(this); mClearPhotoButton = (Button) findViewById(R.id.clear_photo_button); mClearPhotoButton.setOnClickListener(this); mLolcatView = (LolcatView) findViewById(R.id.main_image); // Need one of these to call back to the UI thread // (and run AlertDialog.show(), for that matter) mHandler = new Handler(); mMediaScannerConnection = new MediaScannerConnection(this, mMediaScanConnClient); if (icicle != null) { Log.i(TAG, "- reloading state from icicle!"); restoreStateFromIcicle(icicle); } } @Override protected void onResume() { Log.i(TAG, "onResume()..."); super.onResume(); updateButtons(); } @Override protected void onSaveInstanceState(Bundle outState) { Log.i(TAG, "onSaveInstanceState()..."); super.onSaveInstanceState(outState); // State from the Activity: outState.putParcelable(PHOTO_URI_KEY, mPhotoUri); outState.putString(SAVED_IMAGE_FILENAME_KEY, mSavedImageFilename); outState.putParcelable(SAVED_IMAGE_URI_KEY, mSavedImageUri); // State from the LolcatView: // (TODO: Consider making Caption objects, or even the LolcatView // itself, Parcelable? Probably overkill, though...) outState.putString(TOP_CAPTION_KEY, mLolcatView.getTopCaption()); outState.putString(BOTTOM_CAPTION_KEY, mLolcatView.getBottomCaption()); outState.putIntArray(CAPTION_POSITIONS_KEY, mLolcatView.getCaptionPositions()); } /** * Restores the activity state from the specified icicle. * @see onCreate() * @see onSaveInstanceState() */ private void restoreStateFromIcicle(Bundle icicle) { Log.i(TAG, "restoreStateFromIcicle()..."); // State of the Activity: Uri photoUri = icicle.getParcelable(PHOTO_URI_KEY); Log.i(TAG, " - photoUri: " + photoUri); if (photoUri != null) { loadPhoto(photoUri); } mSavedImageFilename = icicle.getString(SAVED_IMAGE_FILENAME_KEY); mSavedImageUri = icicle.getParcelable(SAVED_IMAGE_URI_KEY); // State of the LolcatView: String topCaption = icicle.getString(TOP_CAPTION_KEY); String bottomCaption = icicle.getString(BOTTOM_CAPTION_KEY); int[] captionPositions = icicle.getIntArray(CAPTION_POSITIONS_KEY); Log.i(TAG, " - captions: '" + topCaption + "', '" + bottomCaption + "'"); if (!TextUtils.isEmpty(topCaption) || !TextUtils.isEmpty(bottomCaption)) { mLolcatView.setCaptions(topCaption, bottomCaption); mLolcatView.setCaptionPositions(captionPositions); } } @Override protected void onDestroy() { Log.i(TAG, "onDestroy()..."); super.onDestroy(); clearPhoto(); // Free up some resources, and force a GC } // View.OnClickListener implementation public void onClick(View view) { int id = view.getId(); Log.i(TAG, "onClick(View " + view + ", id " + id + ")..."); switch (id) { case R.id.pick_button: Log.i(TAG, "onClick: pick_button..."); Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null); intent.setType("image/*"); // Note: we could have the "crop" UI come up here by // default by doing this: // intent.putExtra("crop", "true"); // (But watch out: if you do that, the Intent that comes // back to onActivityResult() will have the URI (of the // cropped image) in the "action" field, not the "data" // field!) startActivityForResult(intent, PHOTO_PICKED); break; case R.id.caption_button: Log.i(TAG, "onClick: caption_button..."); showCaptionDialog(); break; case R.id.save_button: Log.i(TAG, "onClick: save_button..."); saveImage(); break; case R.id.clear_caption_button: Log.i(TAG, "onClick: clear_caption_button..."); clearCaptions(); updateButtons(); break; case R.id.clear_photo_button: Log.i(TAG, "onClick: clear_photo_button..."); clearPhoto(); // Also does clearCaptions() updateButtons(); break; default: Log.w(TAG, "Click from unexpected source: " + view + ", id " + id); break; } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { Log.i(TAG, "onActivityResult(request " + requestCode + ", result " + resultCode + ", data " + data + ")..."); if (resultCode != RESULT_OK) { Log.i(TAG, "==> result " + resultCode + " from subactivity! Ignoring..."); Toast t = Toast.makeText(this, R.string.lolcat_nothing_picked, Toast.LENGTH_SHORT); t.show(); return; } if (requestCode == PHOTO_PICKED) { // "data" is an Intent containing (presumably) a URI like // "content://media/external/images/media/3". if (data == null) { Log.w(TAG, "Null data, but RESULT_OK, from image picker!"); Toast t = Toast.makeText(this, R.string.lolcat_nothing_picked, Toast.LENGTH_SHORT); t.show(); return; } if (data.getData() == null) { Log.w(TAG, "'data' intent from image picker contained no data!"); Toast t = Toast.makeText(this, R.string.lolcat_nothing_picked, Toast.LENGTH_SHORT); t.show(); return; } loadPhoto(data.getData()); updateButtons(); } } /** * Updates the enabled/disabled state of the onscreen buttons. */ private void updateButtons() { Log.i(TAG, "updateButtons()..."); // mPickButton is always enabled. // Do we have a valid photo and/or caption(s) yet? Drawable d = mLolcatView.getDrawable(); // Log.i(TAG, "===> current mLolcatView drawable: " + d); boolean validPhoto = (d != null); boolean validCaption = mLolcatView.hasValidCaption(); mCaptionButton.setText(validCaption ? R.string.lolcat_change_captions : R.string.lolcat_add_captions); mCaptionButton.setEnabled(validPhoto); mSaveButton.setEnabled(validPhoto && validCaption); if (mClearCaptionButton != null) { mClearCaptionButton.setEnabled(validPhoto && validCaption); } mClearPhotoButton.setEnabled(validPhoto); } /** * Clears out any already-entered captions for this lolcat. */ private void clearCaptions() { mLolcatView.clearCaptions(); // Clear the text fields in the caption dialog too. if (mCaptionDialog != null) { EditText topText = (EditText) mCaptionDialog.findViewById(R.id.top_edittext); topText.setText(""); EditText bottomText = (EditText) mCaptionDialog.findViewById(R.id.bottom_edittext); bottomText.setText(""); topText.requestFocus(); } // This also invalidates any image we've previously written to the // SD card... mSavedImageFilename = null; mSavedImageUri = null; } /** * Completely resets the UI to its initial state, with no photo * loaded, and no captions. */ private void clearPhoto() { mLolcatView.clear(); mPhotoUri = null; mSavedImageFilename = null; mSavedImageUri = null; clearCaptions(); // Force a gc (to be sure to reclaim the memory used by our // potentially huge bitmap): System.gc(); } /** * Loads the image with the specified Uri into the UI. */ private void loadPhoto(Uri uri) { Log.i(TAG, "loadPhoto: uri = " + uri); clearPhoto(); // Be sure to release the previous bitmap // before creating another one mPhotoUri = uri; // A new photo always starts out uncaptioned. clearCaptions(); // Load the selected photo into our ImageView. mLolcatView.loadFromUri(mPhotoUri); } private void showCaptionDialog() { // If the dialog already exists, always reset focus to the top // item each time it comes up. if (mCaptionDialog != null) { EditText topText = (EditText) mCaptionDialog.findViewById(R.id.top_edittext); topText.requestFocus(); } showDialog(DIALOG_CAPTION); } private void showSaveSuccessDialog() { // If the dialog already exists, update the body text based on the // current values of mSavedImageFilename and mSavedImageUri // (otherwise the dialog will still have the body text from when // it was first created!) if (mSaveSuccessDialog != null) { updateSaveSuccessDialogBody(); } showDialog(DIALOG_SAVE_SUCCESS); } private void updateSaveSuccessDialogBody() { if (mSaveSuccessDialog == null) { throw new IllegalStateException( "updateSaveSuccessDialogBody: mSaveSuccessDialog hasn't been created yet"); } String dialogBody = String.format( getResources().getString(R.string.lolcat_save_succeeded_dialog_body_format), mSavedImageFilename, mSavedImageUri); mSaveSuccessDialog.setMessage(dialogBody); } @Override protected Dialog onCreateDialog(int id) { Log.i(TAG, "onCreateDialog(id " + id + ")..."); // This is only run once (per dialog), the very first time // a given dialog needs to be shown. switch (id) { case DIALOG_CAPTION: LayoutInflater factory = LayoutInflater.from(this); final View textEntryView = factory.inflate(R.layout.lolcat_caption_dialog, null); mCaptionDialog = new AlertDialog.Builder(this) .setTitle(R.string.lolcat_caption_dialog_title) .setIcon(0) .setView(textEntryView) .setPositiveButton( R.string.lolcat_caption_dialog_ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Log.i(TAG, "Caption dialog: OK..."); updateCaptionsFromDialog(); } }) .setNegativeButton( R.string.lolcat_caption_dialog_cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Log.i(TAG, "Caption dialog: CANCEL..."); // Nothing to do here (for now at least) } }) .create(); return mCaptionDialog; case DIALOG_SAVE_PROGRESS: mSaveProgressDialog = new ProgressDialog(this); mSaveProgressDialog.setMessage(getResources().getString(R.string.lolcat_saving)); mSaveProgressDialog.setIndeterminate(true); mSaveProgressDialog.setCancelable(false); return mSaveProgressDialog; case DIALOG_SAVE_SUCCESS: mSaveSuccessDialog = new AlertDialog.Builder(this) .setTitle(R.string.lolcat_save_succeeded_dialog_title) .setIcon(0) .setPositiveButton( R.string.lolcat_save_succeeded_dialog_view, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Log.i(TAG, "Save dialog: View..."); viewSavedImage(); } }) .setNeutralButton( R.string.lolcat_save_succeeded_dialog_share, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Log.i(TAG, "Save dialog: Share..."); shareSavedImage(); } }) .setNegativeButton( R.string.lolcat_save_succeeded_dialog_cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Log.i(TAG, "Save dialog: CANCEL..."); // Nothing to do here... } }) .create(); updateSaveSuccessDialogBody(); return mSaveSuccessDialog; default: Log.w(TAG, "Request for unexpected dialog id: " + id); break; } return null; } private void updateCaptionsFromDialog() { Log.i(TAG, "updateCaptionsFromDialog()..."); if (mCaptionDialog == null) { Log.w(TAG, "updateCaptionsFromDialog: null mCaptionDialog!"); return; } // Get the two caption strings: EditText topText = (EditText) mCaptionDialog.findViewById(R.id.top_edittext); Log.i(TAG, "- Top editText: " + topText); String topString = topText.getText().toString(); Log.i(TAG, " - String: '" + topString + "'"); EditText bottomText = (EditText) mCaptionDialog.findViewById(R.id.bottom_edittext); Log.i(TAG, "- Bottom editText: " + bottomText); String bottomString = bottomText.getText().toString(); Log.i(TAG, " - String: '" + bottomString + "'"); mLolcatView.setCaptions(topString, bottomString); updateButtons(); } /** * Kicks off the process of saving the LolcatView's working Bitmap to * the SD card, in preparation for viewing it later and/or sharing it. */ private void saveImage() { Log.i(TAG, "saveImage()..."); // First of all, bring up a progress dialog. showDialog(DIALOG_SAVE_PROGRESS); // We now need to save the bitmap to the SD card, and then ask the // MediaScanner to scan it. Do the actual work of all this in a // helper thread, since it's fairly slow (and will occasionally // ANR if we do it here in the UI thread.) Thread t = new Thread() { public void run() { Log.i(TAG, "Running worker thread..."); saveImageInternal(); } }; t.start(); // Next steps: // - saveImageInternal() // - onMediaScannerConnected() // - onScanCompleted } /** * Saves the LolcatView's working Bitmap to the SD card, in * preparation for viewing it later and/or sharing it. * * The bitmap will be saved as a new file in the directory * LOLCAT_SAVE_DIRECTORY, with an automatically-generated filename * based on the current time. It also connects to the * MediaScanner service, since we'll need to scan that new file (in * order to get a Uri we can then VIEW or share.) * * This method is run in a worker thread; @see saveImage(). */ private void saveImageInternal() { Log.i(TAG, "saveImageInternal()..."); // TODO: Currently we save the bitmap to a file on the sdcard, // then ask the MediaScanner to scan it (which gives us a Uri we // can then do an ACTION_VIEW on.) But rather than doing these // separate steps, maybe there's some easy way (given an // OutputStream) to directly talk to the MediaProvider // (i.e. com.android.provider.MediaStore) and say "here's an // image, please save it somwhere and return the URI to me"... // Save the bitmap to a file on the sdcard. // (Based on similar code in MusicUtils.java.) // TODO: Make this filename more human-readable? Maybe "Lolcat-YYYY-MM-DD-HHMMSS.png"? String filename = Environment.getExternalStorageDirectory() + "/" + LOLCAT_SAVE_DIRECTORY + String.valueOf(System.currentTimeMillis() + SAVED_IMAGE_EXTENSION); Log.i(TAG, "- filename: '" + filename + "'"); if (ensureFileExists(filename)) { try { OutputStream outstream = new FileOutputStream(filename); Bitmap bitmap = mLolcatView.getWorkingBitmap(); boolean success = bitmap.compress(SAVED_IMAGE_COMPRESS_FORMAT, 100, outstream); Log.i(TAG, "- success code from Bitmap.compress: " + success); outstream.close(); if (success) { Log.i(TAG, "- Saved! filename = " + filename); mSavedImageFilename = filename; // Ok, now we need to get the MediaScanner to scan the // file we just wrote. Step 1 is to get our // MediaScannerConnection object to connect to the // MediaScanner service. mMediaScannerConnection.connect(); // See onMediaScannerConnected() for the next step } else { Log.w(TAG, "Bitmap.compress failed: bitmap " + bitmap + ", filename '" + filename + "'"); onSaveFailed(R.string.lolcat_save_failed); } } catch (FileNotFoundException e) { Log.w(TAG, "error creating file", e); onSaveFailed(R.string.lolcat_save_failed); } catch (IOException e) { Log.w(TAG, "error creating file", e); onSaveFailed(R.string.lolcat_save_failed); } } else { Log.w(TAG, "ensureFileExists failed for filename '" + filename + "'"); onSaveFailed(R.string.lolcat_save_failed); } } // // MediaScanner-related code // /** * android.media.MediaScannerConnection.MediaScannerConnectionClient implementation. */ private MediaScannerConnection.MediaScannerConnectionClient mMediaScanConnClient = new MediaScannerConnection.MediaScannerConnectionClient() { /** * Called when a connection to the MediaScanner service has been established. */ public void onMediaScannerConnected() { Log.i(TAG, "MediaScannerConnectionClient.onMediaScannerConnected..."); // The next step happens in the UI thread: mHandler.post(new Runnable() { public void run() { LolcatActivity.this.onMediaScannerConnected(); } }); } /** * Called when the media scanner has finished scanning a file. * @param path the path to the file that has been scanned. * @param uri the Uri for the file if the scanning operation succeeded * and the file was added to the media database, or null if scanning failed. */ public void onScanCompleted(final String path, final Uri uri) { Log.i(TAG, "MediaScannerConnectionClient.onScanCompleted: path " + path + ", uri " + uri); // Just run the "real" onScanCompleted() method in the UI thread: mHandler.post(new Runnable() { public void run() { LolcatActivity.this.onScanCompleted(path, uri); } }); } }; /** * This method is called when our MediaScannerConnection successfully * connects to the MediaScanner service. At that point we fire off a * request to scan the lolcat image we just saved. * * This needs to run in the UI thread, so it's called from * mMediaScanConnClient's onMediaScannerConnected() method via our Handler. */ private void onMediaScannerConnected() { Log.i(TAG, "onMediaScannerConnected()..."); // Update the message in the progress dialog... mSaveProgressDialog.setMessage(getResources().getString(R.string.lolcat_scanning)); // Fire off a request to the MediaScanner service to scan this // file; we'll get notified when the scan completes. Log.i(TAG, "- Requesting scan for file: " + mSavedImageFilename); mMediaScannerConnection.scanFile(mSavedImageFilename, null /* mimeType */); // Next step: mMediaScanConnClient will get an onScanCompleted() callback, // which calls our own onScanCompleted() method via our Handler. } /** * Updates the UI after the media scanner finishes the scanFile() * request we issued from onMediaScannerConnected(). * * This needs to run in the UI thread, so it's called from * mMediaScanConnClient's onScanCompleted() method via our Handler. */ private void onScanCompleted(String path, final Uri uri) { Log.i(TAG, "onScanCompleted: path " + path + ", uri " + uri); mMediaScannerConnection.disconnect(); if (uri == null) { Log.w(TAG, "onScanCompleted: scan failed."); mSavedImageUri = null; onSaveFailed(R.string.lolcat_scan_failed); return; } // Success! dismissDialog(DIALOG_SAVE_PROGRESS); // We can now access the saved lolcat image using the specified Uri. mSavedImageUri = uri; // Bring up a success dialog, giving the user the option to go to // the pictures app (so you can share the image). showSaveSuccessDialog(); } // // Other misc utility methods // /** * Ensure that the specified file exists on the SD card, creating it * if necessary. * * Copied from MediaProvider / MusicUtils. * * @return true if the file already exists, or we * successfully created it. */ private static boolean ensureFileExists(String path) { File file = new File(path); if (file.exists()) { return true; } else { // we will not attempt to create the first directory in the path // (for example, do not create /sdcard if the SD card is not mounted) int secondSlash = path.indexOf('/', 1); if (secondSlash < 1) return false; String directoryPath = path.substring(0, secondSlash); File directory = new File(directoryPath); if (!directory.exists()) return false; file.getParentFile().mkdirs(); try { return file.createNewFile(); } catch (IOException ioe) { Log.w(TAG, "File creation failed", ioe); } return false; } } /** * Updates the UI after a failure anywhere in the bitmap saving / scanning * sequence. */ private void onSaveFailed(int errorMessageResId) { dismissDialog(DIALOG_SAVE_PROGRESS); Toast.makeText(this, errorMessageResId, Toast.LENGTH_SHORT).show(); } /** * Goes to the Pictures app for the specified URI. */ private void viewSavedImage(Uri uri) { Log.i(TAG, "viewSavedImage(" + uri + ")..."); if (uri == null) { Log.w(TAG, "viewSavedImage: null uri!"); return; } Intent intent = new Intent(Intent.ACTION_VIEW, uri); Log.i(TAG, "- running startActivity... Intent = " + intent); startActivity(intent); } private void viewSavedImage() { viewSavedImage(mSavedImageUri); } /** * Shares the image with the specified URI. */ private void shareSavedImage(Uri uri) { Log.i(TAG, "shareSavedImage(" + uri + ")..."); if (uri == null) { Log.w(TAG, "shareSavedImage: null uri!"); return; } Intent intent = new Intent(); intent.setAction(Intent.ACTION_SEND); intent.setType(SAVED_IMAGE_MIME_TYPE); intent.putExtra(Intent.EXTRA_STREAM, uri); try { startActivity( Intent.createChooser( intent, getResources().getString(R.string.lolcat_sendImage_label))); } catch (android.content.ActivityNotFoundException ex) { Log.w(TAG, "shareSavedImage: startActivity failed", ex); Toast.makeText(this, R.string.lolcat_share_failed, Toast.LENGTH_SHORT).show(); } } private void shareSavedImage() { shareSavedImage(mSavedImageUri); } }
Java
/* * Copyright 2011 Rodrigo Damazio * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.damazio.notifier.comm.encryption; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import javax.crypto.spec.SecretKeySpec; public class PassKey { private static final String HASH_ALGORITHM = "MD5"; private static final String ENCRYPTION_KEY_TYPE = "AES"; private final byte[] keyBytes; private byte[] iv; private SecretKeySpec keySpec; public PassKey(String passPhrase, int numHashes) { // Use an MD5 to generate an arbitrary initialization vector this.keyBytes = passPhraseToKey(passPhrase, HASH_ALGORITHM, numHashes); } public PassKey(byte[] keyBytes) { this.keyBytes = keyBytes; } public byte[] getKeyBytes() { return keyBytes; } public SecretKeySpec getKeySpec() { if (keySpec == null) { keySpec = new SecretKeySpec(keyBytes, ENCRYPTION_KEY_TYPE); } return keySpec; } public byte[] getInitVector() { if (iv == null) { iv = doDigest(keyBytes, "MD5"); } return iv; } /** * Converts a user-entered pass phrase into a hashed binary value which is * used as the encryption key. */ private byte[] passPhraseToKey(String passphrase, String hashAlgorithm, int numHashes) { if (numHashes < 1) { throw new IllegalArgumentException("Need a positive hash count"); } byte[] passPhraseBytes; try { passPhraseBytes = passphrase.getBytes("UTF8"); } catch (UnsupportedEncodingException e) { throw new IllegalArgumentException("Bad passphrase encoding", e); } // Hash it multiple times to keep the paranoid people happy :) byte[] keyBytes = passPhraseBytes; for (int i = 0; i < numHashes; i++) { keyBytes = doDigest(keyBytes, hashAlgorithm); } return keyBytes; } private byte[] doDigest(byte[] data, String algorithm) { try { MessageDigest md = MessageDigest.getInstance(algorithm); md.update(data); return md.digest(); } catch (NoSuchAlgorithmException e) { throw new IllegalArgumentException("Algorithm not available", e); } } }
Java
/* * Copyright 2011 Rodrigo Damazio * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.damazio.notifier.comm.encryption; import java.io.InputStream; import java.io.OutputStream; import java.security.GeneralSecurityException; import javax.crypto.Cipher; import javax.crypto.CipherInputStream; import javax.crypto.CipherOutputStream; import javax.crypto.spec.IvParameterSpec; /** * Helper class for encrypting and decrypting payloads using arbitrary string passphrases. * This requires converting the passphrase into a byte array key. * This class also includes utilities for encoding that byte array in a string-safe way * for storage. * * @author Rodrigo Damazio */ public class Coder { static final String ENCRYPTION_ALGORITHM = "AES/CBC/PKCS7Padding"; private final PassKey key; public Coder(PassKey key) { this.key = key; } public byte[] encrypt(byte[] unencrypted) throws GeneralSecurityException { return doCipher(unencrypted, Cipher.ENCRYPT_MODE); } public byte[] decrypt(byte[] encrypted) throws GeneralSecurityException { return doCipher(encrypted, Cipher.DECRYPT_MODE); } private byte[] doCipher(byte[] original, int mode) throws GeneralSecurityException { Cipher cipher = createCipher(mode); return cipher.doFinal(original); } public InputStream wrapInputStream(InputStream inputStream) throws GeneralSecurityException { return new CipherInputStream(inputStream, createCipher(Cipher.DECRYPT_MODE)); } public OutputStream wrapOutputStream(OutputStream outputStream) throws GeneralSecurityException { return new CipherOutputStream(outputStream, createCipher(Cipher.ENCRYPT_MODE)); } private Cipher createCipher(int mode) throws GeneralSecurityException { Cipher cipher = Cipher.getInstance(ENCRYPTION_ALGORITHM); cipher.init(mode, key.getKeySpec(), new IvParameterSpec(key.getInitVector())); return cipher; } }
Java
package org.damazio.notifier.comm.pairing; import java.util.Collection; import java.util.HashMap; import java.util.Map; public class DeviceManager { public static class Device { public final long deviceId; public final String ipAddress; public final String bluetoothAddress; public Device(long deviceId, String ipAddress, String bluetoothAddress) { this.deviceId = deviceId; this.ipAddress = ipAddress; this.bluetoothAddress = bluetoothAddress; } } private final Map<Long, Device> devicesById = new HashMap<Long, DeviceManager.Device>(); public Device getDeviceForId(long deviceId) { return devicesById.get(deviceId); } public Collection<Device> getAllDevices() { return devicesById.values(); } }
Java
package org.damazio.notifier.comm.transport.cloud; import static org.damazio.notifier.Constants.TAG; import java.util.Arrays; import org.damazio.notifier.event.EventManager; import org.damazio.notifier.protocol.Common.Event; import com.google.protobuf.InvalidProtocolBufferException; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; public class CloudMessageReceiver extends BroadcastReceiver { private static final String EVENT_EXTRA = "event"; @Override public void onReceive(Context context, Intent intent) { if (!"com.google.android.c2dm.intent.RECEIVE".equals(intent.getAction())) { Log.e(TAG, "Bad C2DM intent: " + intent); return; } // TODO: Handle payload > 1024 bytes byte[] eventBytes = intent.getExtras().getByteArray(EVENT_EXTRA); Event event; try { event = Event.parseFrom(eventBytes); } catch (InvalidProtocolBufferException e) { Log.e(TAG, "Got bad payload: " + Arrays.toString(eventBytes)); return; } EventManager eventManager = new EventManager(context); eventManager.handleRemoteEvent(event); } }
Java
package org.damazio.notifier.comm.transport.cloud; import static org.damazio.notifier.Constants.TAG; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; public class RegistrationReceiver extends BroadcastReceiver { private static final String REGISTRATION_ACTION = "com.google.android.c2dm.intent.REGISTRATION"; @Override public void onReceive(Context context, Intent intent) { if (!intent.getAction().equals(REGISTRATION_ACTION)) { Log.e(TAG, "Got bad intent at C2DM registration receiver: " + intent); return; } String error = intent.getStringExtra("error"); if (error != null) { RegistrationManager.handleError(error); } String registrationId = intent.getStringExtra("registration_id"); RegistrationManager.registrationIdReceived(context, registrationId); } }
Java
package org.damazio.notifier.comm.transport; public enum TransportType { IP, BLUETOOTH, USB, CLOUD; }
Java
/* * Copyright 2011 Rodrigo Damazio * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.damazio.notifier.comm.transport; import org.damazio.notifier.NotifierService.NotifierServiceModule; import org.damazio.notifier.event.EventContext; import org.damazio.notifier.prefs.Preferences.PreferenceListener; /** * Listens to and receives remote events. * * @author Rodrigo Damazio */ public class RemoteEventReceiver implements NotifierServiceModule { private final EventContext eventContext; private final PreferenceListener preferenceListener = new PreferenceListener() { // TODO }; public RemoteEventReceiver(EventContext eventContext) { this.eventContext = eventContext; } public void onCreate() { // Register to learn about changes in transport methods. // This will also trigger the initial starting of the enabled ones. eventContext.getPreferences().registerListener(preferenceListener, true); } public void onDestroy() { eventContext.getPreferences().unregisterListener(preferenceListener); } }
Java
package org.damazio.notifier.comm.transport; import static org.damazio.notifier.Constants.TAG; import org.damazio.notifier.event.EventContext; import org.damazio.notifier.protocol.Common.Event; import android.os.Handler; import android.os.HandlerThread; import android.os.Message; import android.os.Process; import android.util.Log; // TODO: Maybe this is overkill - should we use the DB for retries? public abstract class BaseEventSender { private static final int MSG_EVENT = 42; private static final long RETRY_BACKOFF_MS = 200L; private static final int MAX_RETRIES = 10; private static class EventState { public EventContext context; public Event event; public long eventId; public int retries = 0; public EventState(EventContext context, long eventId, Event event) { this.context = context; this.event = event; this.eventId = eventId; } } private class EventHandler implements Handler.Callback { public boolean handleMessage(Message msg) { if (msg.what != MSG_EVENT) { Log.e(TAG, "Got bad message type: " + msg.what); return true; } Object msgObj = msg.obj; if (!(msgObj instanceof Event)) { Log.e(TAG, "Got bad event object: " + msgObj.getClass().getName()); return true; } EventState state = (EventState) msgObj; boolean handled = handleEvent(state.context, state.eventId, state.event); if (handled) { state.context.getEventManager().markEventProcessed(state.eventId); } if (handled || !scheduleRetry(msg, state)) { // We're done with this message msg.recycle(); } return true; } } private HandlerThread sendThread; private Handler sendHandler; public void start() { sendThread = new HandlerThread( "sender-" + getTransportType(), Process.THREAD_PRIORITY_BACKGROUND); sendThread.start(); sendHandler = new Handler(sendThread.getLooper(), new EventHandler()); } private boolean scheduleRetry(Message msg, EventState state) { if (state.retries >= MAX_RETRIES) { Log.w(TAG, "Too many retries, giving up."); return false; } // Schedule a retry state.retries++; long delayMs = state.retries * RETRY_BACKOFF_MS; sendHandler.sendMessageDelayed(msg, delayMs); return true; } public void sendEvent(EventContext context, long eventId, Event event) { EventState state = new EventState(context, eventId, event); Message message = Message.obtain(sendHandler, MSG_EVENT, state); message.sendToTarget(); } public void shutdown() { sendThread.quit(); try { sendThread.join(); } catch (InterruptedException e) { Log.w(TAG, "Got exception waiting for send thread for " + getTransportType(), e); } } protected abstract boolean handleEvent(EventContext context, long eventId, Event event); protected abstract TransportType getTransportType(); }
Java
package org.damazio.notifier.comm.transport; import java.util.EnumMap; import java.util.EnumSet; import org.damazio.notifier.NotifierService.NotifierServiceModule; import org.damazio.notifier.comm.transport.ip.IpEventSender; import org.damazio.notifier.event.EventContext; import org.damazio.notifier.event.EventListener; import org.damazio.notifier.prefs.Preferences; import org.damazio.notifier.prefs.Preferences.PreferenceListener; import org.damazio.notifier.protocol.Common.Event; import org.damazio.notifier.util.DeviceUtils; /** * Sends local events to remote devices. * * @author Rodrigo Damazio */ public class LocalEventSender implements EventListener, NotifierServiceModule { private final EnumMap<TransportType, BaseEventSender> senders = new EnumMap<TransportType, BaseEventSender>(TransportType.class); private final PreferenceListener preferenceListener = new PreferenceListener() { @Override public void onTransportStateChanged(TransportType type, boolean enabled) { synchronized (senders) { if (enabled) { onTransportEnabled(type); } else { onTransportDisabled(type); } } } }; private final EventContext eventContext; public LocalEventSender(EventContext eventContext) { this.eventContext = eventContext; } public void onCreate() { // Register for changes on transport types, and initially get a // notification about the current types. eventContext.getPreferences().registerListener(preferenceListener, true); } public void onDestroy() { eventContext.getPreferences().unregisterListener(preferenceListener); // Shutdown all transports. synchronized (senders) { for (TransportType type : TransportType.values()) { onTransportDisabled(type); } } } private void onTransportEnabled(TransportType type) { BaseEventSender sender = null; switch (type) { case BLUETOOTH: // TODO break; case CLOUD: // TODO break; case IP: sender = new IpEventSender(eventContext); break; case USB: // TODO break; } if (sender != null) { sender.start(); senders.put(type, sender); } } private void onTransportDisabled(TransportType type) { BaseEventSender sender = senders.remove(type); if (sender != null) { sender.shutdown(); } } @Override public void onNewEvent(EventContext context, long eventId, Event event, boolean isLocal, boolean isCommand) { if (!isLocal) { // Non-local events should not be sent. return; } // Add source device ID to the event. event = event.toBuilder() .setSourceDeviceId(DeviceUtils.getDeviceId(context.getAndroidContext())) .build(); Preferences preferences = context.getPreferences(); EnumSet<TransportType> transportTypes = preferences.getEnabledTransports(); synchronized (senders) { for (TransportType transportType : transportTypes) { BaseEventSender sender = senders.get(transportType); sender.sendEvent(context, eventId, event); } } } }
Java
package org.damazio.notifier.comm.transport.ip; import static org.damazio.notifier.Constants.TAG; import java.io.IOException; import java.io.OutputStream; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketAddress; import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Collection; import org.damazio.notifier.comm.pairing.DeviceManager; import org.damazio.notifier.comm.pairing.DeviceManager.Device; import org.damazio.notifier.comm.transport.BaseEventSender; import org.damazio.notifier.comm.transport.TransportType; import org.damazio.notifier.event.EventContext; import org.damazio.notifier.prefs.Preferences; import org.damazio.notifier.protocol.Common.Event; import android.content.Context; import android.net.ConnectivityManager; import android.net.wifi.WifiManager; import android.util.Log; public class IpEventSender extends BaseEventSender { private static final int DEFAULT_PORT = 10600; private static final int TCP_CONNECT_TIMEOUT_MS = 10 * 1000; private final EventContext context; private final WifiManager wifi; private final ConnectivityManager connectivity; public IpEventSender(EventContext context) { this.context = context; Context androidContext = context.getAndroidContext(); this.wifi = (WifiManager) androidContext.getSystemService(Context.WIFI_SERVICE); this.connectivity = (ConnectivityManager) androidContext.getSystemService(Context.CONNECTIVITY_SERVICE); } @Override protected boolean handleEvent(EventContext context, long eventId, Event event) { byte[] payload = event.toByteArray(); Preferences preferences = context.getPreferences(); // TODO: This belongs somewhere common to all transports DeviceManager deviceManager = context.getDeviceManager(); Collection<Device> targetDevices; if (event.getTargetDeviceIdCount() > 0) { targetDevices = new ArrayList<DeviceManager.Device>(event.getTargetDeviceIdCount()); for (long targetDeviceId : event.getTargetDeviceIdList()) { Device device = deviceManager.getDeviceForId(targetDeviceId); if (device != null) { targetDevices.add(device); } } } else { targetDevices = deviceManager.getAllDevices(); } // TODO: Enabling wifi, wifi lock, send over 3G, check background data. for (Device device : targetDevices) { if (preferences.isIpOverTcp()) { // Try sending over TCP. if (trySendOverTcp(context, payload, device)) { // Stop when the first delivery succeeds. return true; } } } return false; } private boolean trySendOverTcp(EventContext context, byte[] payload, Device device) { Log.d(TAG, "Sending over TCP"); try { InetAddress address = InetAddress.getByName(device.ipAddress); Socket socket = new Socket(); // TODO: Custom port SocketAddress remoteAddr = new InetSocketAddress(address, DEFAULT_PORT); socket.connect(remoteAddr, TCP_CONNECT_TIMEOUT_MS); socket.setSendBufferSize(payload.length * 2); OutputStream stream = socket.getOutputStream(); stream.write(payload); stream.flush(); socket.close(); Log.d(TAG, "Sent over TCP"); return true; } catch (UnknownHostException e) { Log.w(TAG, "Failed to send over TCP", e); return false; } catch (IOException e) { Log.w(TAG, "Failed to send over TCP", e); return false; } } private boolean trySendOverUdp(EventContext context, byte[] payload) { return false; } @Override protected TransportType getTransportType() { return TransportType.IP; } }
Java
/* * Copyright 2011 Rodrigo Damazio * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.damazio.notifier.event.display; import org.damazio.notifier.R; import org.damazio.notifier.event.EventContext; import org.damazio.notifier.event.EventListener; import org.damazio.notifier.prefs.Preferences; import org.damazio.notifier.protocol.Common.Event; import android.app.Notification; import android.app.NotificationManager; import android.content.Context; import android.content.Intent; import android.widget.Toast; /** * Locally displays remote notifications. * * @author Rodrigo Damazio */ public class RemoteNotificationDisplayer implements EventListener { public void onNewEvent(EventContext context, long eventId, Event event, boolean isLocal, boolean isCommand) { // Only care about remote notifications. if (isLocal || isCommand) { return; } // TODO: Proper text String shortText = event.toString(); Preferences preferences = context.getPreferences(); Context androidContext = context.getAndroidContext(); if (preferences.isSystemDisplayEnabled()) { Notification notification = new Notification(R.drawable.icon, shortText, System.currentTimeMillis()); // TODO: Intent = event log // TODO: Configurable defaults notification.defaults = Notification.DEFAULT_ALL; notification.flags |= Notification.FLAG_AUTO_CANCEL; NotificationManager notificationManager = (NotificationManager) androidContext.getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify( "display", (int) (event.getTimestamp() & Integer.MAX_VALUE), notification); } if (preferences.isToastDisplayEnabled()) { Toast.makeText(androidContext, shortText, Toast.LENGTH_LONG).show(); } if (preferences.isPopupDisplayEnabled()) { Intent intent = new Intent(androidContext, PopupDisplayActivity.class); intent.putExtra(PopupDisplayActivity.EXTRA_POPUP_TEXT, shortText); } context.getEventManager().markEventProcessed(eventId); } }
Java
/* * Copyright 2011 Rodrigo Damazio * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.damazio.notifier.event.display; import org.damazio.notifier.R; import android.app.Activity; import android.app.AlertDialog; import android.content.Intent; import android.os.Bundle; /** * Simple activity which displays a pop-up. * * @author Rodrigo Damazio */ public class PopupDisplayActivity extends Activity { public static final String EXTRA_POPUP_TEXT = "popup_text"; @Override public void onCreate(Bundle savedState) { Intent intent = getIntent(); String text = intent.getStringExtra(EXTRA_POPUP_TEXT); AlertDialog popup = new AlertDialog.Builder(this) .setCancelable(true) .setTitle(R.string.popup_display_title) .setMessage(text) .setNeutralButton(android.R.string.ok, null) .create(); popup.show(); } }
Java
/* * Copyright 2011 Rodrigo Damazio * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.damazio.notifier.event; import org.damazio.notifier.protocol.Common.Event; public interface EventListener { void onNewEvent(EventContext context, long eventId, Event event, boolean isLocal, boolean isCommand); }
Java
/* * Copyright 2011 Rodrigo Damazio * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.damazio.notifier.event.util; import static org.damazio.notifier.Constants.TAG; import org.damazio.notifier.protocol.Common.PhoneNumber; import org.damazio.notifier.protocol.Common.PhoneNumber.Builder; import android.content.Context; import android.database.Cursor; import android.net.Uri; import android.provider.ContactsContract.CommonDataKinds.Phone; import android.provider.ContactsContract.PhoneLookup; import android.util.Log; public class PhoneNumberUtils { private final Context context; public PhoneNumberUtils(Context context) { this.context = context; } public PhoneNumber resolvePhoneNumber(String number) { Builder numberBuilder = PhoneNumber.newBuilder(); if (number == null) { return numberBuilder.build(); } numberBuilder.setNumber(number); // Do the contact lookup by number Uri uri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number)); Cursor cursor = null; try { cursor = context.getContentResolver().query(uri, new String[] { PhoneLookup.DISPLAY_NAME, PhoneLookup.TYPE, PhoneLookup.LABEL }, null, null, null); } catch (IllegalArgumentException e) { Log.w(TAG, "Unable to look up caller ID", e); } // Take the first match only if (cursor != null && cursor.moveToFirst()) { int nameIndex = cursor.getColumnIndex(PhoneLookup.DISPLAY_NAME); int typeIndex = cursor.getColumnIndex(PhoneLookup.TYPE); int labelIndex = cursor.getColumnIndex(PhoneLookup.LABEL); if (nameIndex != -1) { numberBuilder.setName(cursor.getString(nameIndex)); // Get the phone type if possible if (typeIndex != -1) { int numberType = cursor.getInt(typeIndex); String label = ""; if (labelIndex != -1) { label = cursor.getString(labelIndex); } numberBuilder.setNumberType( Phone.getTypeLabel(context.getResources(), numberType, label).toString()); } } } return numberBuilder.build(); } }
Java
/* * Copyright 2011 Rodrigo Damazio * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.damazio.notifier.event; import org.damazio.notifier.comm.pairing.DeviceManager; import org.damazio.notifier.event.util.PhoneNumberUtils; import org.damazio.notifier.prefs.Preferences; import android.content.Context; public class EventContext { private final Context context; private final EventManager eventManager; private final DeviceManager deviceManager; private final Preferences preferences; private PhoneNumberUtils numberUtils; public EventContext(Context context, EventManager eventManager, DeviceManager deviceManager, Preferences preferences) { this.context = context; this.eventManager = eventManager; this.preferences = preferences; this.deviceManager = deviceManager; } public synchronized PhoneNumberUtils getNumberUtils() { if (numberUtils == null) { numberUtils = new PhoneNumberUtils(context); } return numberUtils; } public Context getAndroidContext() { return context; } public Preferences getPreferences() { return preferences; } public EventManager getEventManager() { return eventManager; } public DeviceManager getDeviceManager() { return deviceManager; } }
Java
/* * Copyright 2011 Rodrigo Damazio * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.damazio.notifier.event.receivers.sms; import static org.damazio.notifier.Constants.TAG; import org.damazio.notifier.event.EventContext; import org.damazio.notifier.event.receivers.EventBroadcastReceiver; import org.damazio.notifier.protocol.Common.Event; import org.damazio.notifier.protocol.Common.Event.Type; import org.damazio.notifier.protocol.Notifications.SmsNotification; import android.content.Intent; import android.os.Bundle; import android.util.Log; public class SmsReceiver extends EventBroadcastReceiver { private static final String ACTION = "android.provider.Telephony.SMS_RECEIVED"; @Override protected void onReceiveEvent(EventContext context, Intent intent) { // Create the notification contents using the SMS contents boolean notificationSent = false; Bundle bundle = intent.getExtras(); if (bundle != null) { Object[] pdus = (Object[]) bundle.get("pdus"); SmsDecoder decoder = new SmsDecoder(context.getAndroidContext(), context.getNumberUtils()); for (int i = 0; i < pdus.length; i++) { SmsNotification sms = decoder.decodeSms(pdus[i]); if (sms == null) { continue; } handleEvent(sms); notificationSent = true; } } if (!notificationSent) { // If no notification sent (extra info was not there), send one without info Log.w(TAG, "Got SMS but failed to extract details."); handleEvent(null); } } @Override protected Type getEventType() { return Event.Type.NOTIFICATION_SMS; } @Override protected String getExpectedAction() { return ACTION; } }
Java
/* * Copyright 2011 Rodrigo Damazio * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.damazio.notifier.event.receivers.sms; import static org.damazio.notifier.Constants.TAG; import org.damazio.notifier.R; import org.damazio.notifier.event.util.PhoneNumberUtils; import org.damazio.notifier.protocol.Common.PhoneNumber; import org.damazio.notifier.protocol.Notifications.SmsNotification; import android.content.Context; import android.telephony.SmsMessage; import android.util.Log; /** * Class which handles decoding SMS messages in the proper way depending on the * version of Android being run. * * @author Rodrigo Damazio */ class SmsDecoder { private final Context context; private final PhoneNumberUtils numberUtils; public SmsDecoder(Context context, PhoneNumberUtils numberUtils) { this.context = context; this.numberUtils = numberUtils; } public SmsNotification decodeSms(Object pdu) { SmsMessage message = null; try { message = SmsMessage.createFromPdu((byte[]) pdu); } catch (NullPointerException e) { // Workaround for Android bug // http://code.google.com/p/android/issues/detail?id=11345 Log.w(TAG, "Invalid PDU", e); return null; } PhoneNumber number = numberUtils.resolvePhoneNumber(message.getOriginatingAddress()); String body = message.getMessageBody(); if (body == null) { body = context.getString(R.string.sms_body_unavailable); } return SmsNotification.newBuilder() .setSender(number) .setText(body) .build(); } }
Java
/* * Copyright 2011 Rodrigo Damazio * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.damazio.notifier.event.receivers.battery; import static org.damazio.notifier.Constants.TAG; import java.util.HashMap; import java.util.Map; import org.damazio.notifier.event.EventContext; import org.damazio.notifier.event.receivers.EventBroadcastReceiver; import org.damazio.notifier.prefs.Preferences; import org.damazio.notifier.protocol.Common.Event; import org.damazio.notifier.protocol.Common.Event.Type; import org.damazio.notifier.protocol.Notifications.BatteryNotification; import org.damazio.notifier.protocol.Notifications.BatteryNotification.State; import android.content.Intent; import android.os.BatteryManager; import android.os.Bundle; import android.util.Log; public class BatteryEventReceiver extends EventBroadcastReceiver { private static final Map<Integer, State> STATE_MAP = new HashMap<Integer, State>(); static { STATE_MAP.put(BatteryManager.BATTERY_STATUS_CHARGING, State.CHARGING); STATE_MAP.put(BatteryManager.BATTERY_STATUS_DISCHARGING, State.DISCHARGING); STATE_MAP.put(BatteryManager.BATTERY_STATUS_FULL, State.FULL); STATE_MAP.put(BatteryManager.BATTERY_STATUS_NOT_CHARGING, State.NOT_CHARGING); STATE_MAP.put(BatteryManager.BATTERY_STATUS_UNKNOWN, null); } private int lastLevelPercentage; private State lastState; @Override protected void onReceiveEvent(EventContext context, Intent intent) { // Try to read extras from intent Bundle extras = intent.getExtras(); if (extras == null) { return; } int level = extras.getInt(BatteryManager.EXTRA_LEVEL, -1); int maxLevel = extras.getInt(BatteryManager.EXTRA_SCALE, -1); int status = extras.getInt(BatteryManager.EXTRA_STATUS, -1); BatteryNotification.Builder notificationBuilder = BatteryNotification.newBuilder(); State state = STATE_MAP.get(status); if (state != null) { notificationBuilder.setState(state); } int levelPercentage = -1; if (level != -1 && maxLevel != -1) { levelPercentage = 100 * level / maxLevel; notificationBuilder.setChargePercentage(levelPercentage); } Log.d(TAG, "Got battery level=" + levelPercentage + "; state=" + state); if (!shouldReport(state, levelPercentage, context.getPreferences())) { Log.d(TAG, "Not reporting battery state"); return; } lastLevelPercentage = levelPercentage; lastState = state; handleEvent(notificationBuilder.build()); } private boolean shouldReport(State state, int levelPercentage, Preferences preferences) { if (state != lastState) { // State changed return true; } int maxPercentage = preferences.getMaxBatteryLevel(); int minPercentage = preferences.getMinBatteryLevel(); if (levelPercentage > maxPercentage || levelPercentage < minPercentage) { // Outside the range return false; } if (levelPercentage == maxPercentage || levelPercentage == minPercentage) { // About to go in or out of range, always make a first/last report return true; } int percentageChange = Math.abs(levelPercentage - lastLevelPercentage); if (percentageChange < preferences.getMinBatteryLevelChange()) { // Too small change return false; } // With range and above or equal to min change return true; } @Override protected Type getEventType() { return Event.Type.NOTIFICATION_BATTERY; } @Override protected String getExpectedAction() { return Intent.ACTION_BATTERY_CHANGED; } }
Java
/* * Copyright 2011 Rodrigo Damazio * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.damazio.notifier.event.receivers.phone; import org.damazio.notifier.event.EventContext; import org.damazio.notifier.protocol.Common.Event; import org.damazio.notifier.protocol.Notifications.VoicemailNotification; import android.telephony.PhoneStateListener; public class VoicemailListener extends PhoneStateListener { private final EventContext eventContext; public VoicemailListener(EventContext eventContext) { this.eventContext = eventContext; } @Override public void onMessageWaitingIndicatorChanged(boolean mwi) { if (!eventContext.getPreferences().isEventTypeEnabled(Event.Type.NOTIFICATION_VOICEMAIL)) { return; } VoicemailNotification notification = VoicemailNotification.newBuilder() .setHasVoicemail(mwi) .build(); eventContext.getEventManager().handleLocalEvent(Event.Type.NOTIFICATION_VOICEMAIL, notification); } }
Java
/* * Copyright 2011 Rodrigo Damazio * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.damazio.notifier.event.receivers.phone; import org.damazio.notifier.event.EventContext; import org.damazio.notifier.event.receivers.EventBroadcastReceiver; import org.damazio.notifier.event.util.PhoneNumberUtils; import org.damazio.notifier.protocol.Common.Event; import org.damazio.notifier.protocol.Common.Event.Type; import org.damazio.notifier.protocol.Common.PhoneNumber; import org.damazio.notifier.protocol.Notifications.RingNotification; import android.content.Intent; import android.telephony.TelephonyManager; public class RingReceiver extends EventBroadcastReceiver { @Override protected void onReceiveEvent(EventContext context, Intent intent) { String stateStr = intent.getStringExtra(TelephonyManager.EXTRA_STATE); if (TelephonyManager.EXTRA_STATE_RINGING.equals(stateStr)) { PhoneNumberUtils numberUtils = context.getNumberUtils(); String incomingNumberStr = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER); PhoneNumber incomingNumber = numberUtils.resolvePhoneNumber(incomingNumberStr); RingNotification ring = RingNotification.newBuilder() .setNumber(incomingNumber) .build(); handleEvent(ring); } } @Override protected Type getEventType() { return Event.Type.NOTIFICATION_RING; } @Override protected String getExpectedAction() { return TelephonyManager.ACTION_PHONE_STATE_CHANGED; } }
Java
/* * Copyright 2011 Rodrigo Damazio * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.damazio.notifier.event.receivers.phone; import org.damazio.notifier.event.EventContext; import org.damazio.notifier.event.EventManager; import org.damazio.notifier.event.util.PhoneNumberUtils; import org.damazio.notifier.protocol.Common.Event; import org.damazio.notifier.protocol.Common.PhoneNumber; import org.damazio.notifier.protocol.Notifications.MissedCallNotification; import android.content.ContentResolver; import android.database.ContentObserver; import android.database.Cursor; import android.os.Handler; import android.provider.CallLog; public class MissedCallListener { private class CallLogObserver extends ContentObserver { private CallLogObserver(Handler handler) { super(handler); } public void onChange(boolean selfChange) { super.onChange(selfChange); onCallLogChanged(); } } private final EventContext eventContext; private final ContentResolver resolver; private final CallLogObserver observer; private long lastMissedCall; public MissedCallListener(EventContext eventContext) { this.eventContext = eventContext; this.resolver = eventContext.getAndroidContext().getContentResolver(); this.observer = new CallLogObserver(new Handler()); } public void onCreate() { this.lastMissedCall = System.currentTimeMillis(); resolver.registerContentObserver(CallLog.Calls.CONTENT_URI, false, observer); } public void onDestroy() { resolver.unregisterContentObserver(observer); } private void onCallLogChanged() { Cursor cursor = resolver.query( CallLog.Calls.CONTENT_URI, new String[] { CallLog.Calls.NUMBER, CallLog.Calls.DATE }, CallLog.Calls.DATE + " > ? AND " + CallLog.Calls.TYPE + " = ?", new String[] { Long.toString(lastMissedCall), Integer.toString(CallLog.Calls.MISSED_TYPE) }, CallLog.Calls.DATE + " DESC"); EventManager eventManager = eventContext.getEventManager(); PhoneNumberUtils numberUtils = eventContext.getNumberUtils(); while (cursor.moveToNext()) { int numberIdx = cursor.getColumnIndexOrThrow(CallLog.Calls.NUMBER); int dateIdx = cursor.getColumnIndexOrThrow(CallLog.Calls.DATE); if (cursor.isNull(numberIdx) || cursor.isNull(dateIdx)) { eventManager.handleLocalEvent(Event.Type.NOTIFICATION_MISSED_CALL, null); continue; } String number = cursor.getString(numberIdx); long callDate = cursor.getLong(dateIdx); PhoneNumber phoneNumber = numberUtils.resolvePhoneNumber(number); MissedCallNotification notification = MissedCallNotification.newBuilder() .setTimestamp((int) (callDate / 1000L)) .setNumber(phoneNumber) .build(); eventManager.handleLocalEvent(Event.Type.NOTIFICATION_MISSED_CALL, notification); lastMissedCall = callDate; } } }
Java
/* * Copyright (C) 2007 Esmertec AG. * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.damazio.notifier.event.receivers.mms; import java.io.UnsupportedEncodingException; import java.util.HashMap; class CharacterSets { /** * IANA assigned MIB enum numbers. * * From wap-230-wsp-20010705-a.pdf * Any-charset = <Octet 128> * Equivalent to the special RFC2616 charset value "*" */ public static final int ANY_CHARSET = 0x00; public static final int US_ASCII = 0x03; public static final int ISO_8859_1 = 0x04; public static final int ISO_8859_2 = 0x05; public static final int ISO_8859_3 = 0x06; public static final int ISO_8859_4 = 0x07; public static final int ISO_8859_5 = 0x08; public static final int ISO_8859_6 = 0x09; public static final int ISO_8859_7 = 0x0A; public static final int ISO_8859_8 = 0x0B; public static final int ISO_8859_9 = 0x0C; public static final int SHIFT_JIS = 0x11; public static final int UTF_8 = 0x6A; public static final int BIG5 = 0x07EA; public static final int UCS2 = 0x03E8; public static final int UTF_16 = 0x03F7; /** * If the encoding of given data is unsupported, use UTF_8 to decode it. */ public static final int DEFAULT_CHARSET = UTF_8; /** * Array of MIB enum numbers. */ private static final int[] MIBENUM_NUMBERS = { ANY_CHARSET, US_ASCII, ISO_8859_1, ISO_8859_2, ISO_8859_3, ISO_8859_4, ISO_8859_5, ISO_8859_6, ISO_8859_7, ISO_8859_8, ISO_8859_9, SHIFT_JIS, UTF_8, BIG5, UCS2, UTF_16, }; /** * The Well-known-charset Mime name. */ public static final String MIMENAME_ANY_CHARSET = "*"; public static final String MIMENAME_US_ASCII = "us-ascii"; public static final String MIMENAME_ISO_8859_1 = "iso-8859-1"; public static final String MIMENAME_ISO_8859_2 = "iso-8859-2"; public static final String MIMENAME_ISO_8859_3 = "iso-8859-3"; public static final String MIMENAME_ISO_8859_4 = "iso-8859-4"; public static final String MIMENAME_ISO_8859_5 = "iso-8859-5"; public static final String MIMENAME_ISO_8859_6 = "iso-8859-6"; public static final String MIMENAME_ISO_8859_7 = "iso-8859-7"; public static final String MIMENAME_ISO_8859_8 = "iso-8859-8"; public static final String MIMENAME_ISO_8859_9 = "iso-8859-9"; public static final String MIMENAME_SHIFT_JIS = "shift_JIS"; public static final String MIMENAME_UTF_8 = "utf-8"; public static final String MIMENAME_BIG5 = "big5"; public static final String MIMENAME_UCS2 = "iso-10646-ucs-2"; public static final String MIMENAME_UTF_16 = "utf-16"; public static final String DEFAULT_CHARSET_NAME = MIMENAME_UTF_8; /** * Array of the names of character sets. */ private static final String[] MIME_NAMES = { MIMENAME_ANY_CHARSET, MIMENAME_US_ASCII, MIMENAME_ISO_8859_1, MIMENAME_ISO_8859_2, MIMENAME_ISO_8859_3, MIMENAME_ISO_8859_4, MIMENAME_ISO_8859_5, MIMENAME_ISO_8859_6, MIMENAME_ISO_8859_7, MIMENAME_ISO_8859_8, MIMENAME_ISO_8859_9, MIMENAME_SHIFT_JIS, MIMENAME_UTF_8, MIMENAME_BIG5, MIMENAME_UCS2, MIMENAME_UTF_16, }; private static final HashMap<Integer, String> MIBENUM_TO_NAME_MAP; private static final HashMap<String, Integer> NAME_TO_MIBENUM_MAP; static { // Create the HashMaps. MIBENUM_TO_NAME_MAP = new HashMap<Integer, String>(); NAME_TO_MIBENUM_MAP = new HashMap<String, Integer>(); assert(MIBENUM_NUMBERS.length == MIME_NAMES.length); int count = MIBENUM_NUMBERS.length - 1; for(int i = 0; i <= count; i++) { MIBENUM_TO_NAME_MAP.put(MIBENUM_NUMBERS[i], MIME_NAMES[i]); NAME_TO_MIBENUM_MAP.put(MIME_NAMES[i], MIBENUM_NUMBERS[i]); } } private CharacterSets() {} // Non-instantiatable /** * Map an MIBEnum number to the name of the charset which this number * is assigned to by IANA. * * @param mibEnumValue An IANA assigned MIBEnum number. * @return The name string of the charset. * @throws UnsupportedEncodingException */ public static String getMimeName(int mibEnumValue) throws UnsupportedEncodingException { String name = MIBENUM_TO_NAME_MAP.get(mibEnumValue); if (name == null) { throw new UnsupportedEncodingException(); } return name; } /** * Map a well-known charset name to its assigned MIBEnum number. * * @param mimeName The charset name. * @return The MIBEnum number assigned by IANA for this charset. * @throws UnsupportedEncodingException */ public static int getMibEnumValue(String mimeName) throws UnsupportedEncodingException { if(null == mimeName) { return -1; } Integer mibEnumValue = NAME_TO_MIBENUM_MAP.get(mimeName); if (mibEnumValue == null) { throw new UnsupportedEncodingException(); } return mibEnumValue; } }
Java
/* * Copyright 2011 Rodrigo Damazio * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.damazio.notifier.event.receivers.mms; import static org.damazio.notifier.Constants.TAG; import org.damazio.notifier.event.EventContext; import org.damazio.notifier.event.receivers.EventBroadcastReceiver; import org.damazio.notifier.event.util.PhoneNumberUtils; import org.damazio.notifier.protocol.Common.Event; import org.damazio.notifier.protocol.Common.Event.Type; import org.damazio.notifier.protocol.Common.PhoneNumber; import org.damazio.notifier.protocol.Notifications.MmsNotification; import android.content.Intent; import android.util.Log; public class MmsReceiver extends EventBroadcastReceiver { private static final String DATA_TYPE = "application/vnd.wap.mms-message"; @Override protected void onReceiveEvent(EventContext context, Intent intent) { if (!DATA_TYPE.equals(intent.getType())) { Log.e(TAG, "Got wrong data type for MMS: " + intent.getType()); return; } // Parse the WAP push contents PduParser parser = new PduParser(); PduHeaders headers = parser.parseHeaders(intent.getByteArrayExtra("data")); if (headers == null) { Log.e(TAG, "Couldn't parse headers for WAP PUSH."); return; } int messageType = headers.getMessageType(); Log.d(TAG, "WAP PUSH message type: 0x" + Integer.toHexString(messageType)); // Check if it's a MMS notification if (messageType == PduHeaders.MESSAGE_TYPE_NOTIFICATION_IND) { String fromStr = null; EncodedStringValue encodedFrom = headers.getFrom(); if (encodedFrom != null) { fromStr = encodedFrom.getString(); } PhoneNumberUtils numberUtils = context.getNumberUtils(); PhoneNumber from = numberUtils.resolvePhoneNumber(fromStr); // TODO: Add text/image/etc. MmsNotification mms = MmsNotification.newBuilder() .setSender(from) .build(); handleEvent(mms); } } @Override protected String getExpectedAction() { return "android.provider.Telephony.WAP_PUSH_RECEIVED"; } @Override protected Type getEventType() { return Event.Type.NOTIFICATION_MMS; } }
Java
/* * Copyright (C) 2007-2008 Esmertec AG. * Copyright (C) 2007-2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.damazio.notifier.event.receivers.mms; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.UnsupportedEncodingException; import java.util.Arrays; import java.util.HashMap; import android.util.Log; class PduParser { /** * The next are WAP values defined in WSP specification. */ private static final int QUOTE = 127; private static final int LENGTH_QUOTE = 31; private static final int TEXT_MIN = 32; private static final int TEXT_MAX = 127; private static final int SHORT_INTEGER_MAX = 127; private static final int SHORT_LENGTH_MAX = 30; private static final int LONG_INTEGER_LENGTH_MAX = 8; private static final int QUOTED_STRING_FLAG = 34; private static final int END_STRING_FLAG = 0x00; //The next two are used by the interface "parseWapString" to //distinguish Text-String and Quoted-String. private static final int TYPE_TEXT_STRING = 0; private static final int TYPE_QUOTED_STRING = 1; private static final int TYPE_TOKEN_STRING = 2; /** * The log tag. */ private static final String LOG_TAG = "PduParser"; /** * Parse the pdu. * * @return the pdu structure if parsing successfully. * null if parsing error happened or mandatory fields are not set. */ public PduHeaders parseHeaders(byte[] pduData){ ByteArrayInputStream pduDataStream = new ByteArrayInputStream(pduData); /* parse headers */ PduHeaders headers = parseHeaders(pduDataStream); if (null == headers) { // Parse headers failed. return null; } /* check mandatory header fields */ if (false == checkMandatoryHeader(headers)) { log("check mandatory headers failed!"); return null; } return headers; } /** * Parse pdu headers. * * @param pduDataStream pdu data input stream * @return headers in PduHeaders structure, null when parse fail */ protected PduHeaders parseHeaders(ByteArrayInputStream pduDataStream){ if (pduDataStream == null) { return null; } boolean keepParsing = true; PduHeaders headers = new PduHeaders(); while (keepParsing && (pduDataStream.available() > 0)) { int headerField = extractByteValue(pduDataStream); switch (headerField) { case PduHeaders.MESSAGE_TYPE: { int messageType = extractByteValue(pduDataStream); switch (messageType) { // We don't support these kind of messages now. case PduHeaders.MESSAGE_TYPE_FORWARD_REQ: case PduHeaders.MESSAGE_TYPE_FORWARD_CONF: case PduHeaders.MESSAGE_TYPE_MBOX_STORE_REQ: case PduHeaders.MESSAGE_TYPE_MBOX_STORE_CONF: case PduHeaders.MESSAGE_TYPE_MBOX_VIEW_REQ: case PduHeaders.MESSAGE_TYPE_MBOX_VIEW_CONF: case PduHeaders.MESSAGE_TYPE_MBOX_UPLOAD_REQ: case PduHeaders.MESSAGE_TYPE_MBOX_UPLOAD_CONF: case PduHeaders.MESSAGE_TYPE_MBOX_DELETE_REQ: case PduHeaders.MESSAGE_TYPE_MBOX_DELETE_CONF: case PduHeaders.MESSAGE_TYPE_MBOX_DESCR: case PduHeaders.MESSAGE_TYPE_DELETE_REQ: case PduHeaders.MESSAGE_TYPE_DELETE_CONF: case PduHeaders.MESSAGE_TYPE_CANCEL_REQ: case PduHeaders.MESSAGE_TYPE_CANCEL_CONF: return null; } try { headers.setOctet(messageType, headerField); } catch(IllegalArgumentException e) { log("Set invalid Octet value: " + messageType + " into the header filed: " + headerField); return null; } catch(RuntimeException e) { log(headerField + "is not Octet header field!"); return null; } break; } /* Octect value */ case PduHeaders.REPORT_ALLOWED: case PduHeaders.ADAPTATION_ALLOWED: case PduHeaders.DELIVERY_REPORT: case PduHeaders.DRM_CONTENT: case PduHeaders.DISTRIBUTION_INDICATOR: case PduHeaders.QUOTAS: case PduHeaders.READ_REPORT: case PduHeaders.STORE: case PduHeaders.STORED: case PduHeaders.TOTALS: case PduHeaders.SENDER_VISIBILITY: case PduHeaders.READ_STATUS: case PduHeaders.CANCEL_STATUS: case PduHeaders.PRIORITY: case PduHeaders.STATUS: case PduHeaders.REPLY_CHARGING: case PduHeaders.MM_STATE: case PduHeaders.RECOMMENDED_RETRIEVAL_MODE: case PduHeaders.CONTENT_CLASS: case PduHeaders.RETRIEVE_STATUS: case PduHeaders.STORE_STATUS: /** * The following field has a different value when * used in the M-Mbox-Delete.conf and M-Delete.conf PDU. * For now we ignore this fact, since we do not support these PDUs */ case PduHeaders.RESPONSE_STATUS: { int value = extractByteValue(pduDataStream); try { headers.setOctet(value, headerField); } catch(IllegalArgumentException e) { log("Set invalid Octet value: " + value + " into the header filed: " + headerField); return null; } catch(RuntimeException e) { log(headerField + "is not Octet header field!"); return null; } break; } /* Long-Integer */ case PduHeaders.DATE: case PduHeaders.REPLY_CHARGING_SIZE: case PduHeaders.MESSAGE_SIZE: { try { long value = parseLongInteger(pduDataStream); headers.setLongInteger(value, headerField); } catch(RuntimeException e) { log(headerField + "is not Long-Integer header field!"); return null; } break; } /* Integer-Value */ case PduHeaders.MESSAGE_COUNT: case PduHeaders.START: case PduHeaders.LIMIT: { try { long value = parseIntegerValue(pduDataStream); headers.setLongInteger(value, headerField); } catch(RuntimeException e) { log(headerField + "is not Long-Integer header field!"); return null; } break; } /* Text-String */ case PduHeaders.TRANSACTION_ID: case PduHeaders.REPLY_CHARGING_ID: case PduHeaders.AUX_APPLIC_ID: case PduHeaders.APPLIC_ID: case PduHeaders.REPLY_APPLIC_ID: /** * The next three header fields are email addresses * as defined in RFC2822, * not including the characters "<" and ">" */ case PduHeaders.MESSAGE_ID: case PduHeaders.REPLACE_ID: case PduHeaders.CANCEL_ID: /** * The following field has a different value when * used in the M-Mbox-Delete.conf and M-Delete.conf PDU. * For now we ignore this fact, since we do not support these PDUs */ case PduHeaders.CONTENT_LOCATION: { byte[] value = parseWapString(pduDataStream, TYPE_TEXT_STRING); if (null != value) { try { headers.setTextString(value, headerField); } catch(NullPointerException e) { log("null pointer error!"); } catch(RuntimeException e) { log(headerField + "is not Text-String header field!"); return null; } } break; } /* Encoded-string-value */ case PduHeaders.SUBJECT: case PduHeaders.RECOMMENDED_RETRIEVAL_MODE_TEXT: case PduHeaders.RETRIEVE_TEXT: case PduHeaders.STATUS_TEXT: case PduHeaders.STORE_STATUS_TEXT: /* the next one is not support * M-Mbox-Delete.conf and M-Delete.conf now */ case PduHeaders.RESPONSE_TEXT: { EncodedStringValue value = parseEncodedStringValue(pduDataStream); if (null != value) { try { headers.setEncodedStringValue(value, headerField); } catch(NullPointerException e) { log("null pointer error!"); } catch (RuntimeException e) { log(headerField + "is not Encoded-String-Value header field!"); return null; } } break; } /* Addressing model */ case PduHeaders.BCC: case PduHeaders.CC: case PduHeaders.TO: { EncodedStringValue value = parseEncodedStringValue(pduDataStream); if (null != value) { byte[] address = value.getTextString(); if (null != address) { String str = new String(address); int endIndex = str.indexOf("/"); if (endIndex > 0) { str = str.substring(0, endIndex); } try { value.setTextString(str.getBytes()); } catch(NullPointerException e) { log("null pointer error!"); return null; } } try { headers.appendEncodedStringValue(value, headerField); } catch(NullPointerException e) { log("null pointer error!"); } catch(RuntimeException e) { log(headerField + "is not Encoded-String-Value header field!"); return null; } } break; } /* Value-length * (Absolute-token Date-value | Relative-token Delta-seconds-value) */ case PduHeaders.DELIVERY_TIME: case PduHeaders.EXPIRY: case PduHeaders.REPLY_CHARGING_DEADLINE: { /* parse Value-length */ parseValueLength(pduDataStream); /* Absolute-token or Relative-token */ int token = extractByteValue(pduDataStream); /* Date-value or Delta-seconds-value */ long timeValue; try { timeValue = parseLongInteger(pduDataStream); } catch(RuntimeException e) { log(headerField + "is not Long-Integer header field!"); return null; } if (PduHeaders.VALUE_RELATIVE_TOKEN == token) { /* need to convert the Delta-seconds-value * into Date-value */ timeValue = System.currentTimeMillis()/1000 + timeValue; } try { headers.setLongInteger(timeValue, headerField); } catch(RuntimeException e) { log(headerField + "is not Long-Integer header field!"); return null; } break; } case PduHeaders.FROM: { /* From-value = * Value-length * (Address-present-token Encoded-string-value | Insert-address-token) */ EncodedStringValue from = null; parseValueLength(pduDataStream); /* parse value-length */ /* Address-present-token or Insert-address-token */ int fromToken = extractByteValue(pduDataStream); /* Address-present-token or Insert-address-token */ if (PduHeaders.FROM_ADDRESS_PRESENT_TOKEN == fromToken) { /* Encoded-string-value */ from = parseEncodedStringValue(pduDataStream); if (null != from) { byte[] address = from.getTextString(); if (null != address) { String str = new String(address); int endIndex = str.indexOf("/"); if (endIndex > 0) { str = str.substring(0, endIndex); } try { from.setTextString(str.getBytes()); } catch(NullPointerException e) { log("null pointer error!"); return null; } } } } else { try { from = new EncodedStringValue( PduHeaders.FROM_INSERT_ADDRESS_TOKEN_STR.getBytes()); } catch(NullPointerException e) { log(headerField + "is not Encoded-String-Value header field!"); return null; } } try { headers.setEncodedStringValue(from, PduHeaders.FROM); } catch(NullPointerException e) { log("null pointer error!"); } catch(RuntimeException e) { log(headerField + "is not Encoded-String-Value header field!"); return null; } break; } case PduHeaders.MESSAGE_CLASS: { /* Message-class-value = Class-identifier | Token-text */ pduDataStream.mark(1); int messageClass = extractByteValue(pduDataStream); if (messageClass >= PduHeaders.MESSAGE_CLASS_PERSONAL) { /* Class-identifier */ try { if (PduHeaders.MESSAGE_CLASS_PERSONAL == messageClass) { headers.setTextString( PduHeaders.MESSAGE_CLASS_PERSONAL_STR.getBytes(), PduHeaders.MESSAGE_CLASS); } else if (PduHeaders.MESSAGE_CLASS_ADVERTISEMENT == messageClass) { headers.setTextString( PduHeaders.MESSAGE_CLASS_ADVERTISEMENT_STR.getBytes(), PduHeaders.MESSAGE_CLASS); } else if (PduHeaders.MESSAGE_CLASS_INFORMATIONAL == messageClass) { headers.setTextString( PduHeaders.MESSAGE_CLASS_INFORMATIONAL_STR.getBytes(), PduHeaders.MESSAGE_CLASS); } else if (PduHeaders.MESSAGE_CLASS_AUTO == messageClass) { headers.setTextString( PduHeaders.MESSAGE_CLASS_AUTO_STR.getBytes(), PduHeaders.MESSAGE_CLASS); } } catch(NullPointerException e) { log("null pointer error!"); } catch(RuntimeException e) { log(headerField + "is not Text-String header field!"); return null; } } else { /* Token-text */ pduDataStream.reset(); byte[] messageClassString = parseWapString(pduDataStream, TYPE_TEXT_STRING); if (null != messageClassString) { try { headers.setTextString(messageClassString, PduHeaders.MESSAGE_CLASS); } catch(NullPointerException e) { log("null pointer error!"); } catch(RuntimeException e) { log(headerField + "is not Text-String header field!"); return null; } } } break; } case PduHeaders.MMS_VERSION: { int version = parseShortInteger(pduDataStream); try { headers.setOctet(version, PduHeaders.MMS_VERSION); } catch(IllegalArgumentException e) { log("Set invalid Octet value: " + version + " into the header filed: " + headerField); return null; } catch(RuntimeException e) { log(headerField + "is not Octet header field!"); return null; } break; } case PduHeaders.PREVIOUSLY_SENT_BY: { /* Previously-sent-by-value = * Value-length Forwarded-count-value Encoded-string-value */ /* parse value-length */ parseValueLength(pduDataStream); /* parse Forwarded-count-value */ try { parseIntegerValue(pduDataStream); } catch(RuntimeException e) { log(headerField + " is not Integer-Value"); return null; } /* parse Encoded-string-value */ EncodedStringValue previouslySentBy = parseEncodedStringValue(pduDataStream); if (null != previouslySentBy) { try { headers.setEncodedStringValue(previouslySentBy, PduHeaders.PREVIOUSLY_SENT_BY); } catch(NullPointerException e) { log("null pointer error!"); } catch(RuntimeException e) { log(headerField + "is not Encoded-String-Value header field!"); return null; } } break; } case PduHeaders.PREVIOUSLY_SENT_DATE: { /* Previously-sent-date-value = * Value-length Forwarded-count-value Date-value */ /* parse value-length */ parseValueLength(pduDataStream); /* parse Forwarded-count-value */ try { parseIntegerValue(pduDataStream); } catch(RuntimeException e) { log(headerField + " is not Integer-Value"); return null; } /* Date-value */ try { long perviouslySentDate = parseLongInteger(pduDataStream); headers.setLongInteger(perviouslySentDate, PduHeaders.PREVIOUSLY_SENT_DATE); } catch(RuntimeException e) { log(headerField + "is not Long-Integer header field!"); return null; } break; } case PduHeaders.MM_FLAGS: { /* MM-flags-value = * Value-length * ( Add-token | Remove-token | Filter-token ) * Encoded-string-value */ /* parse Value-length */ parseValueLength(pduDataStream); /* Add-token | Remove-token | Filter-token */ extractByteValue(pduDataStream); /* Encoded-string-value */ parseEncodedStringValue(pduDataStream); /* not store this header filed in "headers", * because now PduHeaders doesn't support it */ break; } /* Value-length * (Message-total-token | Size-total-token) Integer-Value */ case PduHeaders.MBOX_TOTALS: case PduHeaders.MBOX_QUOTAS: { /* Value-length */ parseValueLength(pduDataStream); /* Message-total-token | Size-total-token */ extractByteValue(pduDataStream); /*Integer-Value*/ try { parseIntegerValue(pduDataStream); } catch(RuntimeException e) { log(headerField + " is not Integer-Value"); return null; } /* not store these headers filed in "headers", because now PduHeaders doesn't support them */ break; } case PduHeaders.ELEMENT_DESCRIPTOR: { parseContentType(pduDataStream, null); /* not store this header filed in "headers", because now PduHeaders doesn't support it */ break; } case PduHeaders.CONTENT_TYPE: { HashMap<Integer, Object> map = new HashMap<Integer, Object>(); byte[] contentType = parseContentType(pduDataStream, map); if (null != contentType) { try { headers.setTextString(contentType, PduHeaders.CONTENT_TYPE); } catch(NullPointerException e) { log("null pointer error!"); } catch(RuntimeException e) { log(headerField + "is not Text-String header field!"); return null; } } keepParsing = false; break; } case PduHeaders.CONTENT: case PduHeaders.ADDITIONAL_HEADERS: case PduHeaders.ATTRIBUTES: default: { log("Unknown header"); } } } return headers; } /** * Log status. * * @param text log information */ private static void log(String text) { Log.v(LOG_TAG, text); } /** * Parse unsigned integer. * * @param pduDataStream pdu data input stream * @return the integer, -1 when failed */ protected static int parseUnsignedInt(ByteArrayInputStream pduDataStream) { /** * From wap-230-wsp-20010705-a.pdf * The maximum size of a uintvar is 32 bits. * So it will be encoded in no more than 5 octets. */ assert(null != pduDataStream); int result = 0; int temp = pduDataStream.read(); if (temp == -1) { return temp; } while((temp & 0x80) != 0) { result = result << 7; result |= temp & 0x7F; temp = pduDataStream.read(); if (temp == -1) { return temp; } } result = result << 7; result |= temp & 0x7F; return result; } /** * Parse value length. * * @param pduDataStream pdu data input stream * @return the integer */ protected static int parseValueLength(ByteArrayInputStream pduDataStream) { /** * From wap-230-wsp-20010705-a.pdf * Value-length = Short-length | (Length-quote Length) * Short-length = <Any octet 0-30> * Length-quote = <Octet 31> * Length = Uintvar-integer * Uintvar-integer = 1*5 OCTET */ assert(null != pduDataStream); int temp = pduDataStream.read(); assert(-1 != temp); int first = temp & 0xFF; if (first <= SHORT_LENGTH_MAX) { return first; } else if (first == LENGTH_QUOTE) { return parseUnsignedInt(pduDataStream); } throw new RuntimeException ("Value length > LENGTH_QUOTE!"); } /** * Parse encoded string value. * * @param pduDataStream pdu data input stream * @return the EncodedStringValue */ protected static EncodedStringValue parseEncodedStringValue(ByteArrayInputStream pduDataStream){ /** * From OMA-TS-MMS-ENC-V1_3-20050927-C.pdf * Encoded-string-value = Text-string | Value-length Char-set Text-string */ assert(null != pduDataStream); pduDataStream.mark(1); EncodedStringValue returnValue = null; int charset = 0; int temp = pduDataStream.read(); assert(-1 != temp); int first = temp & 0xFF; pduDataStream.reset(); if (first < TEXT_MIN) { parseValueLength(pduDataStream); charset = parseShortInteger(pduDataStream); //get the "Charset" } byte[] textString = parseWapString(pduDataStream, TYPE_TEXT_STRING); try { if (0 != charset) { returnValue = new EncodedStringValue(charset, textString); } else { returnValue = new EncodedStringValue(textString); } } catch(Exception e) { return null; } return returnValue; } /** * Parse Text-String or Quoted-String. * * @param pduDataStream pdu data input stream * @param stringType TYPE_TEXT_STRING or TYPE_QUOTED_STRING * @return the string without End-of-string in byte array */ protected static byte[] parseWapString(ByteArrayInputStream pduDataStream, int stringType) { assert(null != pduDataStream); /** * From wap-230-wsp-20010705-a.pdf * Text-string = [Quote] *TEXT End-of-string * If the first character in the TEXT is in the range of 128-255, * a Quote character must precede it. * Otherwise the Quote character must be omitted. * The Quote is not part of the contents. * Quote = <Octet 127> * End-of-string = <Octet 0> * * Quoted-string = <Octet 34> *TEXT End-of-string * * Token-text = Token End-of-string */ // Mark supposed beginning of Text-string // We will have to mark again if first char is QUOTE or QUOTED_STRING_FLAG pduDataStream.mark(1); // Check first char int temp = pduDataStream.read(); assert(-1 != temp); if ((TYPE_QUOTED_STRING == stringType) && (QUOTED_STRING_FLAG == temp)) { // Mark again if QUOTED_STRING_FLAG and ignore it pduDataStream.mark(1); } else if ((TYPE_TEXT_STRING == stringType) && (QUOTE == temp)) { // Mark again if QUOTE and ignore it pduDataStream.mark(1); } else { // Otherwise go back to origin pduDataStream.reset(); } // We are now definitely at the beginning of string /** * Return *TOKEN or *TEXT (Text-String without QUOTE, * Quoted-String without QUOTED_STRING_FLAG and without End-of-string) */ return getWapString(pduDataStream, stringType); } /** * Check TOKEN data defined in RFC2616. * @param ch checking data * @return true when ch is TOKEN, false when ch is not TOKEN */ protected static boolean isTokenCharacter(int ch) { /** * Token = 1*<any CHAR except CTLs or separators> * separators = "("(40) | ")"(41) | "<"(60) | ">"(62) | "@"(64) * | ","(44) | ";"(59) | ":"(58) | "\"(92) | <">(34) * | "/"(47) | "["(91) | "]"(93) | "?"(63) | "="(61) * | "{"(123) | "}"(125) | SP(32) | HT(9) * CHAR = <any US-ASCII character (octets 0 - 127)> * CTL = <any US-ASCII control character * (octets 0 - 31) and DEL (127)> * SP = <US-ASCII SP, space (32)> * HT = <US-ASCII HT, horizontal-tab (9)> */ if((ch < 33) || (ch > 126)) { return false; } switch(ch) { case '"': /* '"' */ case '(': /* '(' */ case ')': /* ')' */ case ',': /* ',' */ case '/': /* '/' */ case ':': /* ':' */ case ';': /* ';' */ case '<': /* '<' */ case '=': /* '=' */ case '>': /* '>' */ case '?': /* '?' */ case '@': /* '@' */ case '[': /* '[' */ case '\\': /* '\' */ case ']': /* ']' */ case '{': /* '{' */ case '}': /* '}' */ return false; } return true; } /** * Check TEXT data defined in RFC2616. * @param ch checking data * @return true when ch is TEXT, false when ch is not TEXT */ protected static boolean isText(int ch) { /** * TEXT = <any OCTET except CTLs, * but including LWS> * CTL = <any US-ASCII control character * (octets 0 - 31) and DEL (127)> * LWS = [CRLF] 1*( SP | HT ) * CRLF = CR LF * CR = <US-ASCII CR, carriage return (13)> * LF = <US-ASCII LF, linefeed (10)> */ if(((ch >= 32) && (ch <= 126)) || ((ch >= 128) && (ch <= 255))) { return true; } switch(ch) { case '\t': /* '\t' */ case '\n': /* '\n' */ case '\r': /* '\r' */ return true; } return false; } protected static byte[] getWapString(ByteArrayInputStream pduDataStream, int stringType) { assert(null != pduDataStream); ByteArrayOutputStream out = new ByteArrayOutputStream(); int temp = pduDataStream.read(); assert(-1 != temp); while((-1 != temp) && ('\0' != temp)) { // check each of the character if (stringType == TYPE_TOKEN_STRING) { if (isTokenCharacter(temp)) { out.write(temp); } } else { if (isText(temp)) { out.write(temp); } } temp = pduDataStream.read(); assert(-1 != temp); } if (out.size() > 0) { return out.toByteArray(); } return null; } /** * Extract a byte value from the input stream. * * @param pduDataStream pdu data input stream * @return the byte */ protected static int extractByteValue(ByteArrayInputStream pduDataStream) { assert(null != pduDataStream); int temp = pduDataStream.read(); assert(-1 != temp); return temp & 0xFF; } /** * Parse Short-Integer. * * @param pduDataStream pdu data input stream * @return the byte */ protected static int parseShortInteger(ByteArrayInputStream pduDataStream) { /** * From wap-230-wsp-20010705-a.pdf * Short-integer = OCTET * Integers in range 0-127 shall be encoded as a one * octet value with the most significant bit set to one (1xxx xxxx) * and with the value in the remaining least significant bits. */ assert(null != pduDataStream); int temp = pduDataStream.read(); assert(-1 != temp); return temp & 0x7F; } /** * Parse Long-Integer. * * @param pduDataStream pdu data input stream * @return long integer */ protected static long parseLongInteger(ByteArrayInputStream pduDataStream) { /** * From wap-230-wsp-20010705-a.pdf * Long-integer = Short-length Multi-octet-integer * The Short-length indicates the length of the Multi-octet-integer * Multi-octet-integer = 1*30 OCTET * The content octets shall be an unsigned integer value * with the most significant octet encoded first (big-endian representation). * The minimum number of octets must be used to encode the value. * Short-length = <Any octet 0-30> */ assert(null != pduDataStream); int temp = pduDataStream.read(); assert(-1 != temp); int count = temp & 0xFF; if (count > LONG_INTEGER_LENGTH_MAX) { throw new RuntimeException("Octet count greater than 8 and I can't represent that!"); } long result = 0; for (int i = 0 ; i < count ; i++) { temp = pduDataStream.read(); assert(-1 != temp); result <<= 8; result += (temp & 0xFF); } return result; } /** * Parse Integer-Value. * * @param pduDataStream pdu data input stream * @return long integer */ protected static long parseIntegerValue(ByteArrayInputStream pduDataStream) { /** * From wap-230-wsp-20010705-a.pdf * Integer-Value = Short-integer | Long-integer */ assert(null != pduDataStream); pduDataStream.mark(1); int temp = pduDataStream.read(); assert(-1 != temp); pduDataStream.reset(); if (temp > SHORT_INTEGER_MAX) { return parseShortInteger(pduDataStream); } else { return parseLongInteger(pduDataStream); } } /** * To skip length of the wap value. * * @param pduDataStream pdu data input stream * @param length area size * @return the values in this area */ protected static int skipWapValue(ByteArrayInputStream pduDataStream, int length) { assert(null != pduDataStream); byte[] area = new byte[length]; int readLen = pduDataStream.read(area, 0, length); if (readLen < length) { //The actually read length is lower than the length return -1; } else { return readLen; } } /** * Parse content type parameters. For now we just support * four parameters used in mms: "type", "start", "name", "charset". * * @param pduDataStream pdu data input stream * @param map to store parameters of Content-Type field * @param length length of all the parameters */ protected static void parseContentTypeParams(ByteArrayInputStream pduDataStream, HashMap<Integer, Object> map, Integer length) { /** * From wap-230-wsp-20010705-a.pdf * Parameter = Typed-parameter | Untyped-parameter * Typed-parameter = Well-known-parameter-token Typed-value * the actual expected type of the value is implied by the well-known parameter * Well-known-parameter-token = Integer-value * the code values used for parameters are specified in the Assigned Numbers appendix * Typed-value = Compact-value | Text-value * In addition to the expected type, there may be no value. * If the value cannot be encoded using the expected type, it shall be encoded as text. * Compact-value = Integer-value | * Date-value | Delta-seconds-value | Q-value | Version-value | * Uri-value * Untyped-parameter = Token-text Untyped-value * the type of the value is unknown, but it shall be encoded as an integer, * if that is possible. * Untyped-value = Integer-value | Text-value */ assert(null != pduDataStream); assert(length > 0); int startPos = pduDataStream.available(); int tempPos = 0; int lastLen = length; while(0 < lastLen) { int param = pduDataStream.read(); assert(-1 != param); lastLen--; switch (param) { /** * From rfc2387, chapter 3.1 * The type parameter must be specified and its value is the MIME media * type of the "root" body part. It permits a MIME user agent to * determine the content-type without reference to the enclosed body * part. If the value of the type parameter and the root body part's * content-type differ then the User Agent's behavior is undefined. * * From wap-230-wsp-20010705-a.pdf * type = Constrained-encoding * Constrained-encoding = Extension-Media | Short-integer * Extension-media = *TEXT End-of-string */ case PduPart.P_TYPE: case PduPart.P_CT_MR_TYPE: pduDataStream.mark(1); int first = extractByteValue(pduDataStream); pduDataStream.reset(); if (first > TEXT_MAX) { // Short-integer (well-known type) int index = parseShortInteger(pduDataStream); if (index < PduContentTypes.contentTypes.length) { byte[] type = (PduContentTypes.contentTypes[index]).getBytes(); map.put(PduPart.P_TYPE, type); } else { //not support this type, ignore it. } } else { // Text-String (extension-media) byte[] type = parseWapString(pduDataStream, TYPE_TEXT_STRING); if ((null != type) && (null != map)) { map.put(PduPart.P_TYPE, type); } } tempPos = pduDataStream.available(); lastLen = length - (startPos - tempPos); break; /** * From oma-ts-mms-conf-v1_3.pdf, chapter 10.2.3. * Start Parameter Referring to Presentation * * From rfc2387, chapter 3.2 * The start parameter, if given, is the content-ID of the compound * object's "root". If not present the "root" is the first body part in * the Multipart/Related entity. The "root" is the element the * applications processes first. * * From wap-230-wsp-20010705-a.pdf * start = Text-String */ case PduPart.P_START: case PduPart.P_DEP_START: byte[] start = parseWapString(pduDataStream, TYPE_TEXT_STRING); if ((null != start) && (null != map)) { map.put(PduPart.P_START, start); } tempPos = pduDataStream.available(); lastLen = length - (startPos - tempPos); break; /** * From oma-ts-mms-conf-v1_3.pdf * In creation, the character set SHALL be either us-ascii * (IANA MIBenum 3) or utf-8 (IANA MIBenum 106)[Unicode]. * In retrieval, both us-ascii and utf-8 SHALL be supported. * * From wap-230-wsp-20010705-a.pdf * charset = Well-known-charset|Text-String * Well-known-charset = Any-charset | Integer-value * Both are encoded using values from Character Set * Assignments table in Assigned Numbers * Any-charset = <Octet 128> * Equivalent to the special RFC2616 charset value "*" */ case PduPart.P_CHARSET: pduDataStream.mark(1); int firstValue = extractByteValue(pduDataStream); pduDataStream.reset(); //Check first char if (((firstValue > TEXT_MIN) && (firstValue < TEXT_MAX)) || (END_STRING_FLAG == firstValue)) { //Text-String (extension-charset) byte[] charsetStr = parseWapString(pduDataStream, TYPE_TEXT_STRING); try { int charsetInt = CharacterSets.getMibEnumValue( new String(charsetStr)); map.put(PduPart.P_CHARSET, charsetInt); } catch (UnsupportedEncodingException e) { // Not a well-known charset, use "*". Log.e(LOG_TAG, Arrays.toString(charsetStr), e); map.put(PduPart.P_CHARSET, CharacterSets.ANY_CHARSET); } } else { //Well-known-charset int charset = (int) parseIntegerValue(pduDataStream); if (map != null) { map.put(PduPart.P_CHARSET, charset); } } tempPos = pduDataStream.available(); lastLen = length - (startPos - tempPos); break; /** * From oma-ts-mms-conf-v1_3.pdf * A name for multipart object SHALL be encoded using name-parameter * for Content-Type header in WSP multipart headers. * * From wap-230-wsp-20010705-a.pdf * name = Text-String */ case PduPart.P_DEP_NAME: case PduPart.P_NAME: byte[] name = parseWapString(pduDataStream, TYPE_TEXT_STRING); if ((null != name) && (null != map)) { map.put(PduPart.P_NAME, name); } tempPos = pduDataStream.available(); lastLen = length - (startPos - tempPos); break; default: Log.v(LOG_TAG, "Not supported Content-Type parameter"); if (-1 == skipWapValue(pduDataStream, lastLen)) { Log.e(LOG_TAG, "Corrupt Content-Type"); } else { lastLen = 0; } break; } } if (0 != lastLen) { Log.e(LOG_TAG, "Corrupt Content-Type"); } } /** * Parse content type. * * @param pduDataStream pdu data input stream * @param map to store parameters in Content-Type header field * @return Content-Type value */ protected static byte[] parseContentType(ByteArrayInputStream pduDataStream, HashMap<Integer, Object> map) { /** * From wap-230-wsp-20010705-a.pdf * Content-type-value = Constrained-media | Content-general-form * Content-general-form = Value-length Media-type * Media-type = (Well-known-media | Extension-Media) *(Parameter) */ assert(null != pduDataStream); byte[] contentType = null; pduDataStream.mark(1); int temp = pduDataStream.read(); assert(-1 != temp); pduDataStream.reset(); int cur = (temp & 0xFF); if (cur < TEXT_MIN) { int length = parseValueLength(pduDataStream); int startPos = pduDataStream.available(); pduDataStream.mark(1); temp = pduDataStream.read(); assert(-1 != temp); pduDataStream.reset(); int first = (temp & 0xFF); if ((first >= TEXT_MIN) && (first <= TEXT_MAX)) { contentType = parseWapString(pduDataStream, TYPE_TEXT_STRING); } else if (first > TEXT_MAX) { int index = parseShortInteger(pduDataStream); if (index < PduContentTypes.contentTypes.length) { //well-known type contentType = (PduContentTypes.contentTypes[index]).getBytes(); } else { pduDataStream.reset(); contentType = parseWapString(pduDataStream, TYPE_TEXT_STRING); } } else { Log.e(LOG_TAG, "Corrupt content-type"); return (PduContentTypes.contentTypes[0]).getBytes(); //"*/*" } int endPos = pduDataStream.available(); int parameterLen = length - (startPos - endPos); if (parameterLen > 0) {//have parameters parseContentTypeParams(pduDataStream, map, parameterLen); } if (parameterLen < 0) { Log.e(LOG_TAG, "Corrupt MMS message"); return (PduContentTypes.contentTypes[0]).getBytes(); //"*/*" } } else if (cur <= TEXT_MAX) { contentType = parseWapString(pduDataStream, TYPE_TEXT_STRING); } else { contentType = (PduContentTypes.contentTypes[parseShortInteger(pduDataStream)]).getBytes(); } return contentType; } /** * Check mandatory headers of a pdu. * * @param headers pdu headers * @return true if the pdu has all of the mandatory headers, false otherwise. */ protected static boolean checkMandatoryHeader(PduHeaders headers) { if (null == headers) { return false; } /* get message type */ int messageType = headers.getOctet(PduHeaders.MESSAGE_TYPE); /* check Mms-Version field */ int mmsVersion = headers.getOctet(PduHeaders.MMS_VERSION); if (0 == mmsVersion) { // Every message should have Mms-Version field. return false; } /* check mandatory header fields */ switch (messageType) { case PduHeaders.MESSAGE_TYPE_SEND_REQ: // Content-Type field. byte[] srContentType = headers.getTextString(PduHeaders.CONTENT_TYPE); if (null == srContentType) { return false; } // From field. EncodedStringValue srFrom = headers.getEncodedStringValue(PduHeaders.FROM); if (null == srFrom) { return false; } // Transaction-Id field. byte[] srTransactionId = headers.getTextString(PduHeaders.TRANSACTION_ID); if (null == srTransactionId) { return false; } break; case PduHeaders.MESSAGE_TYPE_SEND_CONF: // Response-Status field. int scResponseStatus = headers.getOctet(PduHeaders.RESPONSE_STATUS); if (0 == scResponseStatus) { return false; } // Transaction-Id field. byte[] scTransactionId = headers.getTextString(PduHeaders.TRANSACTION_ID); if (null == scTransactionId) { return false; } break; case PduHeaders.MESSAGE_TYPE_NOTIFICATION_IND: // Content-Location field. byte[] niContentLocation = headers.getTextString(PduHeaders.CONTENT_LOCATION); if (null == niContentLocation) { return false; } // Expiry field. long niExpiry = headers.getLongInteger(PduHeaders.EXPIRY); if (-1 == niExpiry) { return false; } // Message-Class field. byte[] niMessageClass = headers.getTextString(PduHeaders.MESSAGE_CLASS); if (null == niMessageClass) { return false; } // Message-Size field. long niMessageSize = headers.getLongInteger(PduHeaders.MESSAGE_SIZE); if (-1 == niMessageSize) { return false; } // Transaction-Id field. byte[] niTransactionId = headers.getTextString(PduHeaders.TRANSACTION_ID); if (null == niTransactionId) { return false; } break; case PduHeaders.MESSAGE_TYPE_NOTIFYRESP_IND: // Status field. int nriStatus = headers.getOctet(PduHeaders.STATUS); if (0 == nriStatus) { return false; } // Transaction-Id field. byte[] nriTransactionId = headers.getTextString(PduHeaders.TRANSACTION_ID); if (null == nriTransactionId) { return false; } break; case PduHeaders.MESSAGE_TYPE_RETRIEVE_CONF: // Content-Type field. byte[] rcContentType = headers.getTextString(PduHeaders.CONTENT_TYPE); if (null == rcContentType) { return false; } // Date field. long rcDate = headers.getLongInteger(PduHeaders.DATE); if (-1 == rcDate) { return false; } break; case PduHeaders.MESSAGE_TYPE_DELIVERY_IND: // Date field. long diDate = headers.getLongInteger(PduHeaders.DATE); if (-1 == diDate) { return false; } // Message-Id field. byte[] diMessageId = headers.getTextString(PduHeaders.MESSAGE_ID); if (null == diMessageId) { return false; } // Status field. int diStatus = headers.getOctet(PduHeaders.STATUS); if (0 == diStatus) { return false; } // To field. EncodedStringValue[] diTo = headers.getEncodedStringValues(PduHeaders.TO); if (null == diTo) { return false; } break; case PduHeaders.MESSAGE_TYPE_ACKNOWLEDGE_IND: // Transaction-Id field. byte[] aiTransactionId = headers.getTextString(PduHeaders.TRANSACTION_ID); if (null == aiTransactionId) { return false; } break; case PduHeaders.MESSAGE_TYPE_READ_ORIG_IND: // Date field. long roDate = headers.getLongInteger(PduHeaders.DATE); if (-1 == roDate) { return false; } // From field. EncodedStringValue roFrom = headers.getEncodedStringValue(PduHeaders.FROM); if (null == roFrom) { return false; } // Message-Id field. byte[] roMessageId = headers.getTextString(PduHeaders.MESSAGE_ID); if (null == roMessageId) { return false; } // Read-Status field. int roReadStatus = headers.getOctet(PduHeaders.READ_STATUS); if (0 == roReadStatus) { return false; } // To field. EncodedStringValue[] roTo = headers.getEncodedStringValues(PduHeaders.TO); if (null == roTo) { return false; } break; case PduHeaders.MESSAGE_TYPE_READ_REC_IND: // From field. EncodedStringValue rrFrom = headers.getEncodedStringValue(PduHeaders.FROM); if (null == rrFrom) { return false; } // Message-Id field. byte[] rrMessageId = headers.getTextString(PduHeaders.MESSAGE_ID); if (null == rrMessageId) { return false; } // Read-Status field. int rrReadStatus = headers.getOctet(PduHeaders.READ_STATUS); if (0 == rrReadStatus) { return false; } // To field. EncodedStringValue[] rrTo = headers.getEncodedStringValues(PduHeaders.TO); if (null == rrTo) { return false; } break; default: // Parser doesn't support this message type in this version. return false; } return true; } }
Java
/* * Copyright (C) 2007 Esmertec AG. * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.damazio.notifier.event.receivers.mms; class PduContentTypes { /** * All content types. From: * http://www.openmobilealliance.org/tech/omna/omna-wsp-content-type.htm */ static final String[] contentTypes = { "*/*", /* 0x00 */ "text/*", /* 0x01 */ "text/html", /* 0x02 */ "text/plain", /* 0x03 */ "text/x-hdml", /* 0x04 */ "text/x-ttml", /* 0x05 */ "text/x-vCalendar", /* 0x06 */ "text/x-vCard", /* 0x07 */ "text/vnd.wap.wml", /* 0x08 */ "text/vnd.wap.wmlscript", /* 0x09 */ "text/vnd.wap.wta-event", /* 0x0A */ "multipart/*", /* 0x0B */ "multipart/mixed", /* 0x0C */ "multipart/form-data", /* 0x0D */ "multipart/byterantes", /* 0x0E */ "multipart/alternative", /* 0x0F */ "application/*", /* 0x10 */ "application/java-vm", /* 0x11 */ "application/x-www-form-urlencoded", /* 0x12 */ "application/x-hdmlc", /* 0x13 */ "application/vnd.wap.wmlc", /* 0x14 */ "application/vnd.wap.wmlscriptc", /* 0x15 */ "application/vnd.wap.wta-eventc", /* 0x16 */ "application/vnd.wap.uaprof", /* 0x17 */ "application/vnd.wap.wtls-ca-certificate", /* 0x18 */ "application/vnd.wap.wtls-user-certificate", /* 0x19 */ "application/x-x509-ca-cert", /* 0x1A */ "application/x-x509-user-cert", /* 0x1B */ "image/*", /* 0x1C */ "image/gif", /* 0x1D */ "image/jpeg", /* 0x1E */ "image/tiff", /* 0x1F */ "image/png", /* 0x20 */ "image/vnd.wap.wbmp", /* 0x21 */ "application/vnd.wap.multipart.*", /* 0x22 */ "application/vnd.wap.multipart.mixed", /* 0x23 */ "application/vnd.wap.multipart.form-data", /* 0x24 */ "application/vnd.wap.multipart.byteranges", /* 0x25 */ "application/vnd.wap.multipart.alternative", /* 0x26 */ "application/xml", /* 0x27 */ "text/xml", /* 0x28 */ "application/vnd.wap.wbxml", /* 0x29 */ "application/x-x968-cross-cert", /* 0x2A */ "application/x-x968-ca-cert", /* 0x2B */ "application/x-x968-user-cert", /* 0x2C */ "text/vnd.wap.si", /* 0x2D */ "application/vnd.wap.sic", /* 0x2E */ "text/vnd.wap.sl", /* 0x2F */ "application/vnd.wap.slc", /* 0x30 */ "text/vnd.wap.co", /* 0x31 */ "application/vnd.wap.coc", /* 0x32 */ "application/vnd.wap.multipart.related", /* 0x33 */ "application/vnd.wap.sia", /* 0x34 */ "text/vnd.wap.connectivity-xml", /* 0x35 */ "application/vnd.wap.connectivity-wbxml", /* 0x36 */ "application/pkcs7-mime", /* 0x37 */ "application/vnd.wap.hashed-certificate", /* 0x38 */ "application/vnd.wap.signed-certificate", /* 0x39 */ "application/vnd.wap.cert-response", /* 0x3A */ "application/xhtml+xml", /* 0x3B */ "application/wml+xml", /* 0x3C */ "text/css", /* 0x3D */ "application/vnd.wap.mms-message", /* 0x3E */ "application/vnd.wap.rollover-certificate", /* 0x3F */ "application/vnd.wap.locc+wbxml", /* 0x40 */ "application/vnd.wap.loc+xml", /* 0x41 */ "application/vnd.syncml.dm+wbxml", /* 0x42 */ "application/vnd.syncml.dm+xml", /* 0x43 */ "application/vnd.syncml.notification", /* 0x44 */ "application/vnd.wap.xhtml+xml", /* 0x45 */ "application/vnd.wv.csp.cir", /* 0x46 */ "application/vnd.oma.dd+xml", /* 0x47 */ "application/vnd.oma.drm.message", /* 0x48 */ "application/vnd.oma.drm.content", /* 0x49 */ "application/vnd.oma.drm.rights+xml", /* 0x4A */ "application/vnd.oma.drm.rights+wbxml", /* 0x4B */ "application/vnd.wv.csp+xml", /* 0x4C */ "application/vnd.wv.csp+wbxml", /* 0x4D */ "application/vnd.syncml.ds.notification", /* 0x4E */ "audio/*", /* 0x4F */ "video/*", /* 0x50 */ "application/vnd.oma.dd2+xml", /* 0x51 */ "application/mikey" /* 0x52 */ }; }
Java
/* * Copyright (C) 2007 Esmertec AG. * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.damazio.notifier.event.receivers.mms; import java.util.ArrayList; import java.util.HashMap; class PduHeaders { /** * All pdu header fields. */ public static final int BCC = 0x81; public static final int CC = 0x82; public static final int CONTENT_LOCATION = 0x83; public static final int CONTENT_TYPE = 0x84; public static final int DATE = 0x85; public static final int DELIVERY_REPORT = 0x86; public static final int DELIVERY_TIME = 0x87; public static final int EXPIRY = 0x88; public static final int FROM = 0x89; public static final int MESSAGE_CLASS = 0x8A; public static final int MESSAGE_ID = 0x8B; public static final int MESSAGE_TYPE = 0x8C; public static final int MMS_VERSION = 0x8D; public static final int MESSAGE_SIZE = 0x8E; public static final int PRIORITY = 0x8F; public static final int READ_REPLY = 0x90; public static final int READ_REPORT = 0x90; public static final int REPORT_ALLOWED = 0x91; public static final int RESPONSE_STATUS = 0x92; public static final int RESPONSE_TEXT = 0x93; public static final int SENDER_VISIBILITY = 0x94; public static final int STATUS = 0x95; public static final int SUBJECT = 0x96; public static final int TO = 0x97; public static final int TRANSACTION_ID = 0x98; public static final int RETRIEVE_STATUS = 0x99; public static final int RETRIEVE_TEXT = 0x9A; public static final int READ_STATUS = 0x9B; public static final int REPLY_CHARGING = 0x9C; public static final int REPLY_CHARGING_DEADLINE = 0x9D; public static final int REPLY_CHARGING_ID = 0x9E; public static final int REPLY_CHARGING_SIZE = 0x9F; public static final int PREVIOUSLY_SENT_BY = 0xA0; public static final int PREVIOUSLY_SENT_DATE = 0xA1; public static final int STORE = 0xA2; public static final int MM_STATE = 0xA3; public static final int MM_FLAGS = 0xA4; public static final int STORE_STATUS = 0xA5; public static final int STORE_STATUS_TEXT = 0xA6; public static final int STORED = 0xA7; public static final int ATTRIBUTES = 0xA8; public static final int TOTALS = 0xA9; public static final int MBOX_TOTALS = 0xAA; public static final int QUOTAS = 0xAB; public static final int MBOX_QUOTAS = 0xAC; public static final int MESSAGE_COUNT = 0xAD; public static final int CONTENT = 0xAE; public static final int START = 0xAF; public static final int ADDITIONAL_HEADERS = 0xB0; public static final int DISTRIBUTION_INDICATOR = 0xB1; public static final int ELEMENT_DESCRIPTOR = 0xB2; public static final int LIMIT = 0xB3; public static final int RECOMMENDED_RETRIEVAL_MODE = 0xB4; public static final int RECOMMENDED_RETRIEVAL_MODE_TEXT = 0xB5; public static final int STATUS_TEXT = 0xB6; public static final int APPLIC_ID = 0xB7; public static final int REPLY_APPLIC_ID = 0xB8; public static final int AUX_APPLIC_ID = 0xB9; public static final int CONTENT_CLASS = 0xBA; public static final int DRM_CONTENT = 0xBB; public static final int ADAPTATION_ALLOWED = 0xBC; public static final int REPLACE_ID = 0xBD; public static final int CANCEL_ID = 0xBE; public static final int CANCEL_STATUS = 0xBF; /** * X-Mms-Message-Type field types. */ public static final int MESSAGE_TYPE_SEND_REQ = 0x80; public static final int MESSAGE_TYPE_SEND_CONF = 0x81; public static final int MESSAGE_TYPE_NOTIFICATION_IND = 0x82; public static final int MESSAGE_TYPE_NOTIFYRESP_IND = 0x83; public static final int MESSAGE_TYPE_RETRIEVE_CONF = 0x84; public static final int MESSAGE_TYPE_ACKNOWLEDGE_IND = 0x85; public static final int MESSAGE_TYPE_DELIVERY_IND = 0x86; public static final int MESSAGE_TYPE_READ_REC_IND = 0x87; public static final int MESSAGE_TYPE_READ_ORIG_IND = 0x88; public static final int MESSAGE_TYPE_FORWARD_REQ = 0x89; public static final int MESSAGE_TYPE_FORWARD_CONF = 0x8A; public static final int MESSAGE_TYPE_MBOX_STORE_REQ = 0x8B; public static final int MESSAGE_TYPE_MBOX_STORE_CONF = 0x8C; public static final int MESSAGE_TYPE_MBOX_VIEW_REQ = 0x8D; public static final int MESSAGE_TYPE_MBOX_VIEW_CONF = 0x8E; public static final int MESSAGE_TYPE_MBOX_UPLOAD_REQ = 0x8F; public static final int MESSAGE_TYPE_MBOX_UPLOAD_CONF = 0x90; public static final int MESSAGE_TYPE_MBOX_DELETE_REQ = 0x91; public static final int MESSAGE_TYPE_MBOX_DELETE_CONF = 0x92; public static final int MESSAGE_TYPE_MBOX_DESCR = 0x93; public static final int MESSAGE_TYPE_DELETE_REQ = 0x94; public static final int MESSAGE_TYPE_DELETE_CONF = 0x95; public static final int MESSAGE_TYPE_CANCEL_REQ = 0x96; public static final int MESSAGE_TYPE_CANCEL_CONF = 0x97; /** * X-Mms-Delivery-Report | * X-Mms-Read-Report | * X-Mms-Report-Allowed | * X-Mms-Sender-Visibility | * X-Mms-Store | * X-Mms-Stored | * X-Mms-Totals | * X-Mms-Quotas | * X-Mms-Distribution-Indicator | * X-Mms-DRM-Content | * X-Mms-Adaptation-Allowed | * field types. */ public static final int VALUE_YES = 0x80; public static final int VALUE_NO = 0x81; /** * Delivery-Time | * Expiry and Reply-Charging-Deadline | * field type components. */ public static final int VALUE_ABSOLUTE_TOKEN = 0x80; public static final int VALUE_RELATIVE_TOKEN = 0x81; /** * X-Mms-MMS-Version field types. */ public static final int MMS_VERSION_1_3 = ((1 << 4) | 3); public static final int MMS_VERSION_1_2 = ((1 << 4) | 2); public static final int MMS_VERSION_1_1 = ((1 << 4) | 1); public static final int MMS_VERSION_1_0 = ((1 << 4) | 0); // Current version is 1.2. public static final int CURRENT_MMS_VERSION = MMS_VERSION_1_2; /** * From field type components. */ public static final int FROM_ADDRESS_PRESENT_TOKEN = 0x80; public static final int FROM_INSERT_ADDRESS_TOKEN = 0x81; public static final String FROM_ADDRESS_PRESENT_TOKEN_STR = "address-present-token"; public static final String FROM_INSERT_ADDRESS_TOKEN_STR = "insert-address-token"; /** * X-Mms-Status Field. */ public static final int STATUS_EXPIRED = 0x80; public static final int STATUS_RETRIEVED = 0x81; public static final int STATUS_REJECTED = 0x82; public static final int STATUS_DEFERRED = 0x83; public static final int STATUS_UNRECOGNIZED = 0x84; public static final int STATUS_INDETERMINATE = 0x85; public static final int STATUS_FORWARDED = 0x86; public static final int STATUS_UNREACHABLE = 0x87; /** * MM-Flags field type components. */ public static final int MM_FLAGS_ADD_TOKEN = 0x80; public static final int MM_FLAGS_REMOVE_TOKEN = 0x81; public static final int MM_FLAGS_FILTER_TOKEN = 0x82; /** * X-Mms-Message-Class field types. */ public static final int MESSAGE_CLASS_PERSONAL = 0x80; public static final int MESSAGE_CLASS_ADVERTISEMENT = 0x81; public static final int MESSAGE_CLASS_INFORMATIONAL = 0x82; public static final int MESSAGE_CLASS_AUTO = 0x83; public static final String MESSAGE_CLASS_PERSONAL_STR = "personal"; public static final String MESSAGE_CLASS_ADVERTISEMENT_STR = "advertisement"; public static final String MESSAGE_CLASS_INFORMATIONAL_STR = "informational"; public static final String MESSAGE_CLASS_AUTO_STR = "auto"; /** * X-Mms-Priority field types. */ public static final int PRIORITY_LOW = 0x80; public static final int PRIORITY_NORMAL = 0x81; public static final int PRIORITY_HIGH = 0x82; /** * X-Mms-Response-Status field types. */ public static final int RESPONSE_STATUS_OK = 0x80; public static final int RESPONSE_STATUS_ERROR_UNSPECIFIED = 0x81; public static final int RESPONSE_STATUS_ERROR_SERVICE_DENIED = 0x82; public static final int RESPONSE_STATUS_ERROR_MESSAGE_FORMAT_CORRUPT = 0x83; public static final int RESPONSE_STATUS_ERROR_SENDING_ADDRESS_UNRESOLVED = 0x84; public static final int RESPONSE_STATUS_ERROR_MESSAGE_NOT_FOUND = 0x85; public static final int RESPONSE_STATUS_ERROR_NETWORK_PROBLEM = 0x86; public static final int RESPONSE_STATUS_ERROR_CONTENT_NOT_ACCEPTED = 0x87; public static final int RESPONSE_STATUS_ERROR_UNSUPPORTED_MESSAGE = 0x88; public static final int RESPONSE_STATUS_ERROR_TRANSIENT_FAILURE = 0xC0; public static final int RESPONSE_STATUS_ERROR_TRANSIENT_SENDNG_ADDRESS_UNRESOLVED = 0xC1; public static final int RESPONSE_STATUS_ERROR_TRANSIENT_MESSAGE_NOT_FOUND = 0xC2; public static final int RESPONSE_STATUS_ERROR_TRANSIENT_NETWORK_PROBLEM = 0xC3; public static final int RESPONSE_STATUS_ERROR_TRANSIENT_PARTIAL_SUCCESS = 0xC4; public static final int RESPONSE_STATUS_ERROR_PERMANENT_FAILURE = 0xE0; public static final int RESPONSE_STATUS_ERROR_PERMANENT_SERVICE_DENIED = 0xE1; public static final int RESPONSE_STATUS_ERROR_PERMANENT_MESSAGE_FORMAT_CORRUPT = 0xE2; public static final int RESPONSE_STATUS_ERROR_PERMANENT_SENDING_ADDRESS_UNRESOLVED = 0xE3; public static final int RESPONSE_STATUS_ERROR_PERMANENT_MESSAGE_NOT_FOUND = 0xE4; public static final int RESPONSE_STATUS_ERROR_PERMANENT_CONTENT_NOT_ACCEPTED = 0xE5; public static final int RESPONSE_STATUS_ERROR_PERMANENT_REPLY_CHARGING_LIMITATIONS_NOT_MET = 0xE6; public static final int RESPONSE_STATUS_ERROR_PERMANENT_REPLY_CHARGING_REQUEST_NOT_ACCEPTED = 0xE6; public static final int RESPONSE_STATUS_ERROR_PERMANENT_REPLY_CHARGING_FORWARDING_DENIED = 0xE8; public static final int RESPONSE_STATUS_ERROR_PERMANENT_REPLY_CHARGING_NOT_SUPPORTED = 0xE9; public static final int RESPONSE_STATUS_ERROR_PERMANENT_ADDRESS_HIDING_NOT_SUPPORTED = 0xEA; public static final int RESPONSE_STATUS_ERROR_PERMANENT_LACK_OF_PREPAID = 0xEB; public static final int RESPONSE_STATUS_ERROR_PERMANENT_END = 0xFF; /** * X-Mms-Retrieve-Status field types. */ public static final int RETRIEVE_STATUS_OK = 0x80; public static final int RETRIEVE_STATUS_ERROR_TRANSIENT_FAILURE = 0xC0; public static final int RETRIEVE_STATUS_ERROR_TRANSIENT_MESSAGE_NOT_FOUND = 0xC1; public static final int RETRIEVE_STATUS_ERROR_TRANSIENT_NETWORK_PROBLEM = 0xC2; public static final int RETRIEVE_STATUS_ERROR_PERMANENT_FAILURE = 0xE0; public static final int RETRIEVE_STATUS_ERROR_PERMANENT_SERVICE_DENIED = 0xE1; public static final int RETRIEVE_STATUS_ERROR_PERMANENT_MESSAGE_NOT_FOUND = 0xE2; public static final int RETRIEVE_STATUS_ERROR_PERMANENT_CONTENT_UNSUPPORTED = 0xE3; public static final int RETRIEVE_STATUS_ERROR_END = 0xFF; /** * X-Mms-Sender-Visibility field types. */ public static final int SENDER_VISIBILITY_HIDE = 0x80; public static final int SENDER_VISIBILITY_SHOW = 0x81; /** * X-Mms-Read-Status field types. */ public static final int READ_STATUS_READ = 0x80; public static final int READ_STATUS__DELETED_WITHOUT_BEING_READ = 0x81; /** * X-Mms-Cancel-Status field types. */ public static final int CANCEL_STATUS_REQUEST_SUCCESSFULLY_RECEIVED = 0x80; public static final int CANCEL_STATUS_REQUEST_CORRUPTED = 0x81; /** * X-Mms-Reply-Charging field types. */ public static final int REPLY_CHARGING_REQUESTED = 0x80; public static final int REPLY_CHARGING_REQUESTED_TEXT_ONLY = 0x81; public static final int REPLY_CHARGING_ACCEPTED = 0x82; public static final int REPLY_CHARGING_ACCEPTED_TEXT_ONLY = 0x83; /** * X-Mms-MM-State field types. */ public static final int MM_STATE_DRAFT = 0x80; public static final int MM_STATE_SENT = 0x81; public static final int MM_STATE_NEW = 0x82; public static final int MM_STATE_RETRIEVED = 0x83; public static final int MM_STATE_FORWARDED = 0x84; /** * X-Mms-Recommended-Retrieval-Mode field types. */ public static final int RECOMMENDED_RETRIEVAL_MODE_MANUAL = 0x80; /** * X-Mms-Content-Class field types. */ public static final int CONTENT_CLASS_TEXT = 0x80; public static final int CONTENT_CLASS_IMAGE_BASIC = 0x81; public static final int CONTENT_CLASS_IMAGE_RICH = 0x82; public static final int CONTENT_CLASS_VIDEO_BASIC = 0x83; public static final int CONTENT_CLASS_VIDEO_RICH = 0x84; public static final int CONTENT_CLASS_MEGAPIXEL = 0x85; public static final int CONTENT_CLASS_CONTENT_BASIC = 0x86; public static final int CONTENT_CLASS_CONTENT_RICH = 0x87; /** * X-Mms-Store-Status field types. */ public static final int STORE_STATUS_SUCCESS = 0x80; public static final int STORE_STATUS_ERROR_TRANSIENT_FAILURE = 0xC0; public static final int STORE_STATUS_ERROR_TRANSIENT_NETWORK_PROBLEM = 0xC1; public static final int STORE_STATUS_ERROR_PERMANENT_FAILURE = 0xE0; public static final int STORE_STATUS_ERROR_PERMANENT_SERVICE_DENIED = 0xE1; public static final int STORE_STATUS_ERROR_PERMANENT_MESSAGE_FORMAT_CORRUPT = 0xE2; public static final int STORE_STATUS_ERROR_PERMANENT_MESSAGE_NOT_FOUND = 0xE3; public static final int STORE_STATUS_ERROR_PERMANENT_MMBOX_FULL = 0xE4; public static final int STORE_STATUS_ERROR_END = 0xFF; /** * The map contains the value of all headers. */ private HashMap<Integer, Object> mHeaderMap = null; /** * Constructor of PduHeaders. */ public PduHeaders() { mHeaderMap = new HashMap<Integer, Object>(); } /** * Get octet value by header field. * * @param field the field * @return the octet value of the pdu header * with specified header field. Return 0 if * the value is not set. */ protected int getOctet(int field) { Integer octet = (Integer) mHeaderMap.get(field); if (null == octet) { return 0; } return octet; } /** * Set octet value to pdu header by header field. * * @param value the value * @param field the field * @throws InvalidHeaderValueException if the value is invalid. */ protected void setOctet(int value, int field) throws IllegalArgumentException{ /** * Check whether this field can be set for specific * header and check validity of the field. */ switch (field) { case REPORT_ALLOWED: case ADAPTATION_ALLOWED: case DELIVERY_REPORT: case DRM_CONTENT: case DISTRIBUTION_INDICATOR: case QUOTAS: case READ_REPORT: case STORE: case STORED: case TOTALS: case SENDER_VISIBILITY: if ((VALUE_YES != value) && (VALUE_NO != value)) { // Invalid value. throw new IllegalArgumentException("Invalid Octet value!"); } break; case READ_STATUS: if ((READ_STATUS_READ != value) && (READ_STATUS__DELETED_WITHOUT_BEING_READ != value)) { // Invalid value. throw new IllegalArgumentException("Invalid Octet value!"); } break; case CANCEL_STATUS: if ((CANCEL_STATUS_REQUEST_SUCCESSFULLY_RECEIVED != value) && (CANCEL_STATUS_REQUEST_CORRUPTED != value)) { // Invalid value. throw new IllegalArgumentException("Invalid Octet value!"); } break; case PRIORITY: if ((value < PRIORITY_LOW) || (value > PRIORITY_HIGH)) { // Invalid value. throw new IllegalArgumentException("Invalid Octet value!"); } break; case STATUS: if ((value < STATUS_EXPIRED) || (value > STATUS_UNREACHABLE)) { // Invalid value. throw new IllegalArgumentException("Invalid Octet value!"); } break; case REPLY_CHARGING: if ((value < REPLY_CHARGING_REQUESTED) || (value > REPLY_CHARGING_ACCEPTED_TEXT_ONLY)) { // Invalid value. throw new IllegalArgumentException("Invalid Octet value!"); } break; case MM_STATE: if ((value < MM_STATE_DRAFT) || (value > MM_STATE_FORWARDED)) { // Invalid value. throw new IllegalArgumentException("Invalid Octet value!"); } break; case RECOMMENDED_RETRIEVAL_MODE: if (RECOMMENDED_RETRIEVAL_MODE_MANUAL != value) { // Invalid value. throw new IllegalArgumentException("Invalid Octet value!"); } break; case CONTENT_CLASS: if ((value < CONTENT_CLASS_TEXT) || (value > CONTENT_CLASS_CONTENT_RICH)) { // Invalid value. throw new IllegalArgumentException("Invalid Octet value!"); } break; case RETRIEVE_STATUS: // According to oma-ts-mms-enc-v1_3, section 7.3.50, we modify the invalid value. if ((value > RETRIEVE_STATUS_ERROR_TRANSIENT_NETWORK_PROBLEM) && (value < RETRIEVE_STATUS_ERROR_PERMANENT_FAILURE)) { value = RETRIEVE_STATUS_ERROR_TRANSIENT_FAILURE; } else if ((value > RETRIEVE_STATUS_ERROR_PERMANENT_CONTENT_UNSUPPORTED) && (value <= RETRIEVE_STATUS_ERROR_END)) { value = RETRIEVE_STATUS_ERROR_PERMANENT_FAILURE; } else if ((value < RETRIEVE_STATUS_OK) || ((value > RETRIEVE_STATUS_OK) && (value < RETRIEVE_STATUS_ERROR_TRANSIENT_FAILURE)) || (value > RETRIEVE_STATUS_ERROR_END)) { value = RETRIEVE_STATUS_ERROR_PERMANENT_FAILURE; } break; case STORE_STATUS: // According to oma-ts-mms-enc-v1_3, section 7.3.58, we modify the invalid value. if ((value > STORE_STATUS_ERROR_TRANSIENT_NETWORK_PROBLEM) && (value < STORE_STATUS_ERROR_PERMANENT_FAILURE)) { value = STORE_STATUS_ERROR_TRANSIENT_FAILURE; } else if ((value > STORE_STATUS_ERROR_PERMANENT_MMBOX_FULL) && (value <= STORE_STATUS_ERROR_END)) { value = STORE_STATUS_ERROR_PERMANENT_FAILURE; } else if ((value < STORE_STATUS_SUCCESS) || ((value > STORE_STATUS_SUCCESS) && (value < STORE_STATUS_ERROR_TRANSIENT_FAILURE)) || (value > STORE_STATUS_ERROR_END)) { value = STORE_STATUS_ERROR_PERMANENT_FAILURE; } break; case RESPONSE_STATUS: // According to oma-ts-mms-enc-v1_3, section 7.3.48, we modify the invalid value. if ((value > RESPONSE_STATUS_ERROR_TRANSIENT_PARTIAL_SUCCESS) && (value < RESPONSE_STATUS_ERROR_PERMANENT_FAILURE)) { value = RESPONSE_STATUS_ERROR_TRANSIENT_FAILURE; } else if (((value > RESPONSE_STATUS_ERROR_PERMANENT_LACK_OF_PREPAID) && (value <= RESPONSE_STATUS_ERROR_PERMANENT_END)) || (value < RESPONSE_STATUS_OK) || ((value > RESPONSE_STATUS_ERROR_UNSUPPORTED_MESSAGE) && (value < RESPONSE_STATUS_ERROR_TRANSIENT_FAILURE)) || (value > RESPONSE_STATUS_ERROR_PERMANENT_END)) { value = RESPONSE_STATUS_ERROR_PERMANENT_FAILURE; } break; case MMS_VERSION: if ((value < MMS_VERSION_1_0)|| (value > MMS_VERSION_1_3)) { value = CURRENT_MMS_VERSION; // Current version is the default value. } break; case MESSAGE_TYPE: if ((value < MESSAGE_TYPE_SEND_REQ) || (value > MESSAGE_TYPE_CANCEL_CONF)) { // Invalid value. throw new IllegalArgumentException("Invalid Octet value!"); } break; default: // This header value should not be Octect. throw new RuntimeException("Invalid header field!"); } mHeaderMap.put(field, value); } /** * Get TextString value by header field. * * @param field the field * @return the TextString value of the pdu header * with specified header field */ protected byte[] getTextString(int field) { return (byte[]) mHeaderMap.get(field); } /** * Set TextString value to pdu header by header field. * * @param value the value * @param field the field * @return the TextString value of the pdu header * with specified header field * @throws NullPointerException if the value is null. */ protected void setTextString(byte[] value, int field) { /** * Check whether this field can be set for specific * header and check validity of the field. */ if (null == value) { throw new NullPointerException(); } switch (field) { case TRANSACTION_ID: case REPLY_CHARGING_ID: case AUX_APPLIC_ID: case APPLIC_ID: case REPLY_APPLIC_ID: case MESSAGE_ID: case REPLACE_ID: case CANCEL_ID: case CONTENT_LOCATION: case MESSAGE_CLASS: case CONTENT_TYPE: break; default: // This header value should not be Text-String. throw new RuntimeException("Invalid header field!"); } mHeaderMap.put(field, value); } /** * Get EncodedStringValue value by header field. * * @param field the field * @return the EncodedStringValue value of the pdu header * with specified header field */ protected EncodedStringValue getEncodedStringValue(int field) { return (EncodedStringValue) mHeaderMap.get(field); } /** * Get TO, CC or BCC header value. * * @param field the field * @return the EncodeStringValue array of the pdu header * with specified header field */ protected EncodedStringValue[] getEncodedStringValues(int field) { @SuppressWarnings("unchecked") ArrayList<EncodedStringValue> list = (ArrayList<EncodedStringValue>) mHeaderMap.get(field); if (null == list) { return null; } EncodedStringValue[] values = new EncodedStringValue[list.size()]; return list.toArray(values); } /** * Set EncodedStringValue value to pdu header by header field. * * @param value the value * @param field the field * @return the EncodedStringValue value of the pdu header * with specified header field * @throws NullPointerException if the value is null. */ protected void setEncodedStringValue(EncodedStringValue value, int field) { /** * Check whether this field can be set for specific * header and check validity of the field. */ if (null == value) { throw new NullPointerException(); } switch (field) { case SUBJECT: case RECOMMENDED_RETRIEVAL_MODE_TEXT: case RETRIEVE_TEXT: case STATUS_TEXT: case STORE_STATUS_TEXT: case RESPONSE_TEXT: case FROM: case PREVIOUSLY_SENT_BY: case MM_FLAGS: break; default: // This header value should not be Encoded-String-Value. throw new RuntimeException("Invalid header field!"); } mHeaderMap.put(field, value); } /** * Set TO, CC or BCC header value. * * @param value the value * @param field the field * @return the EncodedStringValue value array of the pdu header * with specified header field * @throws NullPointerException if the value is null. */ protected void setEncodedStringValues(EncodedStringValue[] value, int field) { /** * Check whether this field can be set for specific * header and check validity of the field. */ if (null == value) { throw new NullPointerException(); } switch (field) { case BCC: case CC: case TO: break; default: // This header value should not be Encoded-String-Value. throw new RuntimeException("Invalid header field!"); } ArrayList<EncodedStringValue> list = new ArrayList<EncodedStringValue>(); for (int i = 0; i < value.length; i++) { list.add(value[i]); } mHeaderMap.put(field, list); } /** * Append one EncodedStringValue to another. * * @param value the EncodedStringValue to append * @param field the field * @throws NullPointerException if the value is null. */ protected void appendEncodedStringValue(EncodedStringValue value, int field) { if (null == value) { throw new NullPointerException(); } switch (field) { case BCC: case CC: case TO: break; default: throw new RuntimeException("Invalid header field!"); } @SuppressWarnings("unchecked") ArrayList<EncodedStringValue> list = (ArrayList<EncodedStringValue>) mHeaderMap.get(field); if (null == list) { list = new ArrayList<EncodedStringValue>(); } list.add(value); mHeaderMap.put(field, list); } /** * Get LongInteger value by header field. * * @param field the field * @return the LongInteger value of the pdu header * with specified header field. if return -1, the * field is not existed in pdu header. */ protected long getLongInteger(int field) { Long longInteger = (Long) mHeaderMap.get(field); if (null == longInteger) { return -1; } return longInteger.longValue(); } /** * Set LongInteger value to pdu header by header field. * * @param value the value * @param field the field */ protected void setLongInteger(long value, int field) { /** * Check whether this field can be set for specific * header and check validity of the field. */ switch (field) { case DATE: case REPLY_CHARGING_SIZE: case MESSAGE_SIZE: case MESSAGE_COUNT: case START: case LIMIT: case DELIVERY_TIME: case EXPIRY: case REPLY_CHARGING_DEADLINE: case PREVIOUSLY_SENT_DATE: break; default: // This header value should not be LongInteger. throw new RuntimeException("Invalid header field!"); } mHeaderMap.put(field, value); } public int getMessageType() { return getOctet(PduHeaders.MESSAGE_TYPE); } public EncodedStringValue getFrom() { return getEncodedStringValue(PduHeaders.FROM); } }
Java
/* * Copyright (C) 2007-2008 Esmertec AG. * Copyright (C) 2007-2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.damazio.notifier.event.receivers.mms; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.util.ArrayList; import android.util.Log; /** * Encoded-string-value = Text-string | Value-length Char-set Text-string */ class EncodedStringValue implements Cloneable { private static final String TAG = "EncodedStringValue"; /** * The Char-set value. */ private int mCharacterSet; /** * The Text-string value. */ private byte[] mData; /** * Constructor. * * @param charset the Char-set value * @param data the Text-string value * @throws NullPointerException if Text-string value is null. */ public EncodedStringValue(int charset, byte[] data) { // TODO: CharSet needs to be validated against MIBEnum. if(null == data) { throw new NullPointerException("EncodedStringValue: Text-string is null."); } mCharacterSet = charset; mData = new byte[data.length]; System.arraycopy(data, 0, mData, 0, data.length); } /** * Constructor. * * @param data the Text-string value * @throws NullPointerException if Text-string value is null. */ public EncodedStringValue(byte[] data) { this(CharacterSets.DEFAULT_CHARSET, data); } public EncodedStringValue(String data) { try { mData = data.getBytes(CharacterSets.DEFAULT_CHARSET_NAME); mCharacterSet = CharacterSets.DEFAULT_CHARSET; } catch (UnsupportedEncodingException e) { Log.e(TAG, "Default encoding must be supported.", e); } } /** * Get Char-set value. * * @return the value */ public int getCharacterSet() { return mCharacterSet; } /** * Set Char-set value. * * @param charset the Char-set value */ public void setCharacterSet(int charset) { // TODO: CharSet needs to be validated against MIBEnum. mCharacterSet = charset; } /** * Get Text-string value. * * @return the value */ public byte[] getTextString() { byte[] byteArray = new byte[mData.length]; System.arraycopy(mData, 0, byteArray, 0, mData.length); return byteArray; } /** * Set Text-string value. * * @param textString the Text-string value * @throws NullPointerException if Text-string value is null. */ public void setTextString(byte[] textString) { if(null == textString) { throw new NullPointerException("EncodedStringValue: Text-string is null."); } mData = new byte[textString.length]; System.arraycopy(textString, 0, mData, 0, textString.length); } /** * Convert this object to a {@link java.lang.String}. If the encoding of * the EncodedStringValue is null or unsupported, it will be * treated as iso-8859-1 encoding. * * @return The decoded String. */ public String getString() { if (CharacterSets.ANY_CHARSET == mCharacterSet) { return new String(mData); // system default encoding. } else { try { String name = CharacterSets.getMimeName(mCharacterSet); return new String(mData, name); } catch (UnsupportedEncodingException e) { try { return new String(mData, CharacterSets.MIMENAME_ISO_8859_1); } catch (UnsupportedEncodingException _) { return new String(mData); // system default encoding. } } } } /** * Append to Text-string. * * @param textString the textString to append * @throws NullPointerException if the text String is null * or an IOException occured. */ public void appendTextString(byte[] textString) { if(null == textString) { throw new NullPointerException("Text-string is null."); } if(null == mData) { mData = new byte[textString.length]; System.arraycopy(textString, 0, mData, 0, textString.length); } else { ByteArrayOutputStream newTextString = new ByteArrayOutputStream(); try { newTextString.write(mData); newTextString.write(textString); } catch (IOException e) { e.printStackTrace(); throw new NullPointerException( "appendTextString: failed when write a new Text-string"); } mData = newTextString.toByteArray(); } } /* * (non-Javadoc) * @see java.lang.Object#clone() */ @Override public Object clone() throws CloneNotSupportedException { super.clone(); int len = mData.length; byte[] dstBytes = new byte[len]; System.arraycopy(mData, 0, dstBytes, 0, len); try { return new EncodedStringValue(mCharacterSet, dstBytes); } catch (Exception e) { Log.e(TAG, "failed to clone an EncodedStringValue: " + this); e.printStackTrace(); throw new CloneNotSupportedException(e.getMessage()); } } /** * Split this encoded string around matches of the given pattern. * * @param pattern the delimiting pattern * @return the array of encoded strings computed by splitting this encoded * string around matches of the given pattern */ public EncodedStringValue[] split(String pattern) { String[] temp = getString().split(pattern); EncodedStringValue[] ret = new EncodedStringValue[temp.length]; for (int i = 0; i < ret.length; ++i) { try { ret[i] = new EncodedStringValue(mCharacterSet, temp[i].getBytes()); } catch (NullPointerException _) { // Can't arrive here return null; } } return ret; } /** * Extract an EncodedStringValue[] from a given String. */ public static EncodedStringValue[] extract(String src) { String[] values = src.split(";"); ArrayList<EncodedStringValue> list = new ArrayList<EncodedStringValue>(); for (int i = 0; i < values.length; i++) { if (values[i].length() > 0) { list.add(new EncodedStringValue(values[i])); } } int len = list.size(); if (len > 0) { return list.toArray(new EncodedStringValue[len]); } else { return null; } } /** * Concatenate an EncodedStringValue[] into a single String. */ public static String concat(EncodedStringValue[] addr) { StringBuilder sb = new StringBuilder(); int maxIndex = addr.length - 1; for (int i = 0; i <= maxIndex; i++) { sb.append(addr[i].getString()); if (i < maxIndex) { sb.append(";"); } } return sb.toString(); } public static EncodedStringValue copy(EncodedStringValue value) { if (value == null) { return null; } return new EncodedStringValue(value.mCharacterSet, value.mData); } public static EncodedStringValue[] encodeStrings(String[] array) { int count = array.length; if (count > 0) { EncodedStringValue[] encodedArray = new EncodedStringValue[count]; for (int i = 0; i < count; i++) { encodedArray[i] = new EncodedStringValue(array[i]); } return encodedArray; } return null; } }
Java
/* * Copyright (C) 2007-2008 Esmertec AG. * Copyright (C) 2007-2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.damazio.notifier.event.receivers.mms; /** * The pdu part. */ class PduPart { /** * Well-Known Parameters. */ public static final int P_Q = 0x80; public static final int P_CHARSET = 0x81; public static final int P_LEVEL = 0x82; public static final int P_TYPE = 0x83; public static final int P_DEP_NAME = 0x85; public static final int P_DEP_FILENAME = 0x86; public static final int P_DIFFERENCES = 0x87; public static final int P_PADDING = 0x88; // This value of "TYPE" s used with Content-Type: multipart/related public static final int P_CT_MR_TYPE = 0x89; public static final int P_DEP_START = 0x8A; public static final int P_DEP_START_INFO = 0x8B; public static final int P_DEP_COMMENT = 0x8C; public static final int P_DEP_DOMAIN = 0x8D; public static final int P_MAX_AGE = 0x8E; public static final int P_DEP_PATH = 0x8F; public static final int P_SECURE = 0x90; public static final int P_SEC = 0x91; public static final int P_MAC = 0x92; public static final int P_CREATION_DATE = 0x93; public static final int P_MODIFICATION_DATE = 0x94; public static final int P_READ_DATE = 0x95; public static final int P_SIZE = 0x96; public static final int P_NAME = 0x97; public static final int P_FILENAME = 0x98; public static final int P_START = 0x99; public static final int P_START_INFO = 0x9A; public static final int P_COMMENT = 0x9B; public static final int P_DOMAIN = 0x9C; public static final int P_PATH = 0x9D; /** * Header field names. */ public static final int P_CONTENT_TYPE = 0x91; public static final int P_CONTENT_LOCATION = 0x8E; public static final int P_CONTENT_ID = 0xC0; public static final int P_DEP_CONTENT_DISPOSITION = 0xAE; public static final int P_CONTENT_DISPOSITION = 0xC5; // The next header is unassigned header, use reserved header(0x48) value. public static final int P_CONTENT_TRANSFER_ENCODING = 0xC8; /** * Content=Transfer-Encoding string. */ public static final String CONTENT_TRANSFER_ENCODING = "Content-Transfer-Encoding"; /** * Value of Content-Transfer-Encoding. */ public static final String P_BINARY = "binary"; public static final String P_7BIT = "7bit"; public static final String P_8BIT = "8bit"; public static final String P_BASE64 = "base64"; public static final String P_QUOTED_PRINTABLE = "quoted-printable"; /** * Value of disposition can be set to PduPart when the value is octet in * the PDU. * "from-data" instead of Form-data<Octet 128>. * "attachment" instead of Attachment<Octet 129>. * "inline" instead of Inline<Octet 130>. */ static final byte[] DISPOSITION_FROM_DATA = "from-data".getBytes(); static final byte[] DISPOSITION_ATTACHMENT = "attachment".getBytes(); static final byte[] DISPOSITION_INLINE = "inline".getBytes(); /** * Content-Disposition value. */ public static final int P_DISPOSITION_FROM_DATA = 0x80; public static final int P_DISPOSITION_ATTACHMENT = 0x81; public static final int P_DISPOSITION_INLINE = 0x82; private PduPart() { } }
Java
/* * Copyright 2011 Rodrigo Damazio * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.damazio.notifier.event.receivers; import static org.damazio.notifier.Constants.TAG; import org.damazio.notifier.NotifierService.NotifierServiceModule; import org.damazio.notifier.event.EventContext; import org.damazio.notifier.event.receivers.battery.BatteryEventReceiver; import org.damazio.notifier.event.receivers.phone.MissedCallListener; import org.damazio.notifier.event.receivers.phone.VoicemailListener; import org.damazio.notifier.prefs.Preferences.PreferenceListener; import org.damazio.notifier.protocol.Common.Event.Type; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.telephony.PhoneStateListener; import android.telephony.TelephonyManager; import android.util.Log; /** * Module which manages local event receivers. * (except those driven by broadcasts, which are registered directly in the Manifest) * * @author Rodrigo Damazio */ public class LocalEventReceiver implements NotifierServiceModule { private final EventContext eventContext; private final PreferenceListener preferenceListener = new PreferenceListener() { @Override public synchronized void onSendEventStateChanged(Type type, boolean enabled) { switch (type) { case NOTIFICATION_MISSED_CALL: onMissedCallStateChanged(enabled); break; case NOTIFICATION_BATTERY: onBatteryStateChanged(enabled); break; case NOTIFICATION_VOICEMAIL: onVoicemailStateChanged(enabled); break; case NOTIFICATION_RING: case NOTIFICATION_SMS: case NOTIFICATION_MMS: case NOTIFICATION_THIRD_PARTY: // These come in via global broadcast receivers, nothing to do. break; default: Log.w(TAG, "Unknown event type's state changed: " + type); } } }; private VoicemailListener voicemailListener; private BatteryEventReceiver batteryReceiver; private MissedCallListener missedCallListener; public LocalEventReceiver(EventContext eventContext) { this.eventContext = eventContext; } public void onCreate() { if (voicemailListener != null) { throw new IllegalStateException("Already started"); } // Register for preference changes, and also do an initial notification of // the current values. eventContext.getPreferences().registerListener(preferenceListener, true); } public void onDestroy() { eventContext.getPreferences().unregisterListener(preferenceListener); // Disable all events. onMissedCallStateChanged(false); onBatteryStateChanged(false); onVoicemailStateChanged(false); } private synchronized void onVoicemailStateChanged(boolean enabled) { if (voicemailListener != null ^ !enabled) { Log.d(TAG, "Voicemail state didn't change"); return; } TelephonyManager telephonyManager = (TelephonyManager) eventContext.getAndroidContext().getSystemService(Context.TELEPHONY_SERVICE); if (enabled) { voicemailListener = new VoicemailListener(eventContext); telephonyManager.listen(voicemailListener, PhoneStateListener.LISTEN_MESSAGE_WAITING_INDICATOR); } else { telephonyManager.listen(voicemailListener, PhoneStateListener.LISTEN_NONE); voicemailListener = null; } } private void onBatteryStateChanged(boolean enabled) { if (batteryReceiver != null ^ !enabled) { Log.d(TAG, "Battery state didn't change"); return; } if (enabled) { // Register the battery receiver // (can't be registered in the manifest for some reason) batteryReceiver = new BatteryEventReceiver(); eventContext.getAndroidContext().registerReceiver( batteryReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); } else { eventContext.getAndroidContext().unregisterReceiver(batteryReceiver); } } private synchronized void onMissedCallStateChanged(boolean enabled) { if (missedCallListener != null ^ !enabled) { Log.d(TAG, "Missed call state didn't change"); return; } if (enabled) { missedCallListener = new MissedCallListener(eventContext); missedCallListener.onCreate(); } else { missedCallListener.onDestroy(); missedCallListener = null; } } }
Java
/* * Copyright 2011 Rodrigo Damazio * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.damazio.notifier.event.receivers; import static org.damazio.notifier.Constants.TAG; import org.damazio.notifier.NotifierService; import org.damazio.notifier.comm.pairing.DeviceManager; import org.damazio.notifier.event.EventContext; import org.damazio.notifier.event.EventManager; import org.damazio.notifier.prefs.Preferences; import org.damazio.notifier.protocol.Common.Event; import org.damazio.notifier.protocol.Common.Event.Type; import com.google.protobuf.MessageLite; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; /** * Base class for all broadcast receivers which receive events. * * @author Rodrigo Damazio */ public abstract class EventBroadcastReceiver extends BroadcastReceiver { private EventManager eventManager; @Override public final void onReceive(Context context, Intent intent) { Type eventType = getEventType(); if (!intent.getAction().equals(getExpectedAction())) { Log.e(TAG, "Wrong intent received by receiver for " + eventType.name() + ": " + intent.getAction()); return; } NotifierService.startIfNotRunning(context); Preferences preferences = new Preferences(context); if (!preferences.isEventTypeEnabled(eventType)) { return; } synchronized (this) { DeviceManager deviceManager = new DeviceManager(); eventManager = new EventManager(context, deviceManager, preferences); onReceiveEvent(eventManager.getEventContext(), intent); eventManager = null; } } protected void handleEvent(MessageLite notification) { eventManager.handleLocalEvent(getEventType(), notification); } /** * Returns the event type being generated. */ protected abstract Event.Type getEventType(); /** * Returns the broadcast action this receiver handles. */ protected abstract String getExpectedAction(); /** * Processes the broadcast intent and calls {@link #handleEvent} with the results. */ protected abstract void onReceiveEvent(EventContext context, Intent intent); }
Java
/* * Copyright 2011 Rodrigo Damazio * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.damazio.notifier.event.log; import android.net.Uri; import android.provider.BaseColumns; public interface EventLogColumns extends BaseColumns { public static final Uri URI = Uri.parse("content://org.damazio.notifier.eventlog/events"); public static final String URI_AUTHORITY = "org.damazio.notifier.eventlog"; public static final String TABLE_TYPE = "vnd.android.cursor.dir/vnd.damazio.event"; public static final String ITEM_TYPE = "vnd.android.cursor.item/vnd.damazio.event"; public static final String TABLE_NAME = "events"; public static final String COLUMN_TIMESTAMP = "timestamp"; public static final String COLUMN_SOURCE_DEVICE_ID = "source_device_id"; public static final String COLUMN_PROCESSED = "processed"; public static final String COLUMN_EVENT_TYPE = "event_type"; public static final String COLUMN_PAYLOAD = "payload"; }
Java
/* * Copyright 2011 Rodrigo Damazio * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.damazio.notifier.event.log; import static org.damazio.notifier.Constants.TAG; import java.util.Arrays; import android.content.ContentProvider; import android.content.ContentResolver; import android.content.ContentUris; import android.content.ContentValues; import android.content.UriMatcher; import android.database.Cursor; import android.database.sqlite.SQLiteDatabase; import android.net.Uri; import android.util.Log; /** * Content provider for the event log. * * @author Rodrigo Damazio */ public class EventLogProvider extends ContentProvider { /** If at least this many rows are deleted, we'll vacuum the database. */ private static final int VACUUM_DELETION_TRESHOLD = 100; private static final int MATCH_DIR = 1; private static final int MATCH_ITEM = 2; private LogDbHelper dbHelper; private SQLiteDatabase db; private UriMatcher uriMatcher; private ContentResolver contentResolver; public EventLogProvider() { this.uriMatcher = new UriMatcher(UriMatcher.NO_MATCH); uriMatcher.addURI(EventLogColumns.URI_AUTHORITY, "events", MATCH_DIR); uriMatcher.addURI(EventLogColumns.URI_AUTHORITY, "events/#", MATCH_ITEM); } @Override public boolean onCreate() { this.contentResolver = getContext().getContentResolver(); this.dbHelper = new LogDbHelper(getContext()); this.db = dbHelper.getWritableDatabase(); return db != null; } @Override public int delete(Uri uri, String selection, String[] selectionArgs) { // TODO: Extract if (matchUriOrThrow(uri) == MATCH_ITEM) { String id = uri.getLastPathSegment(); if (selection != null) { selection = "(" + selection + ") AND _id = ?"; } else { selection = "_id = ?"; } if (selectionArgs != null) { selectionArgs = Arrays.copyOf(selectionArgs, selectionArgs.length + 1); } else { selectionArgs = new String[1]; } selectionArgs[selectionArgs.length - 1] = id; } int rows = db.delete(EventLogColumns.TABLE_NAME, selection, selectionArgs); contentResolver.notifyChange(uri, null); if (rows > VACUUM_DELETION_TRESHOLD) { Log.i(TAG, "Vacuuming the database"); db.execSQL("VACUUM"); } return rows; } @Override public String getType(Uri uri) { switch (uriMatcher.match(uri)) { case MATCH_DIR: return EventLogColumns.TABLE_TYPE; case MATCH_ITEM: return EventLogColumns.ITEM_TYPE; default: throw new IllegalArgumentException("Invalid URI type for '" + uri + "'."); } } @Override public Uri insert(Uri uri, ContentValues values) { if (matchUriOrThrow(uri) != MATCH_DIR) { throw new IllegalStateException("Cannot insert inside an item"); } long rowId = db.insertOrThrow(EventLogColumns.TABLE_NAME, null, values); Uri insertedUri = ContentUris.withAppendedId(uri, rowId); contentResolver.notifyChange(insertedUri, null); return insertedUri; } @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sortOrder) { if (matchUriOrThrow(uri) == MATCH_ITEM) { String id = uri.getLastPathSegment(); if (selection != null) { selection = "(" + selection + ") AND _id = ?"; } else { selection = "_id = ?"; } if (selectionArgs != null) { selectionArgs = Arrays.copyOf(selectionArgs, selectionArgs.length + 1); } else { selectionArgs = new String[1]; } selectionArgs[selectionArgs.length - 1] = id; } Cursor cursor = db.query(EventLogColumns.TABLE_NAME, projection, selection, selectionArgs, null, null, sortOrder); cursor.setNotificationUri(contentResolver, uri); return cursor; } @Override public int update(Uri uri, ContentValues values, String selection, String[] selectionArgs) { if (matchUriOrThrow(uri) == MATCH_ITEM) { String id = uri.getLastPathSegment(); if (selection != null) { selection = "(" + selection + ") AND _id = ?"; } else { selection = "_id = ?"; } if (selectionArgs != null) { selectionArgs = Arrays.copyOf(selectionArgs, selectionArgs.length + 1); } else { selectionArgs = new String[1]; } selectionArgs[selectionArgs.length - 1] = id; } int numRows = db.update(EventLogColumns.TABLE_NAME, values, selection, selectionArgs); contentResolver.notifyChange(uri, null); return numRows; } private int matchUriOrThrow(Uri uri) { int match = uriMatcher.match(uri); if (match == UriMatcher.NO_MATCH) { throw new IllegalArgumentException("Invalid URI type for '" + uri + "'."); } return match; } }
Java
/* * Copyright 2011 Rodrigo Damazio * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.damazio.notifier.event.log; import static org.damazio.notifier.Constants.TAG; import org.damazio.notifier.protocol.Common.Event; import org.damazio.notifier.protocol.Common.Event.Builder; import com.google.protobuf.ByteString; import android.content.ContentResolver; import android.content.ContentValues; import android.database.ContentObserver; import android.database.Cursor; import android.net.Uri; import android.util.Log; public class EventLogHelper { private final ContentResolver contentResolver; public EventLogHelper(ContentResolver contentResolver) { this.contentResolver = contentResolver; } /** * * @param type * @param payload * @param timestamp * @param sourceDeviceId the ID of the device that sent the notification, or null if it was generated locally */ public void insertEvent(Event.Type type, byte[] payload, long timestamp, Long sourceDeviceId) { ContentValues values = new ContentValues(5); values.put(EventLogColumns.COLUMN_EVENT_TYPE, type.getNumber()); values.put(EventLogColumns.COLUMN_SOURCE_DEVICE_ID, sourceDeviceId); values.put(EventLogColumns.COLUMN_TIMESTAMP, timestamp); values.put(EventLogColumns.COLUMN_PAYLOAD, payload); Uri inserted = contentResolver.insert(EventLogColumns.URI, values); Log.d(TAG, "Created event row " + inserted); } public void registerContentObserver(ContentObserver observer) { contentResolver.registerContentObserver( EventLogColumns.URI, true, observer); } public void unregisterContentObserver(ContentObserver observber) { contentResolver.unregisterContentObserver(observber); } public Cursor getUnprocessedEvents(long minEventId) { return contentResolver.query(EventLogColumns.URI, null, EventLogColumns.COLUMN_PROCESSED + " = FALSE AND" + EventLogColumns._ID + " >= ?", new String[] { Long.toString(minEventId) }, null); } public Event buildEvent(Cursor cursor) { int typeIdx = cursor.getColumnIndexOrThrow(EventLogColumns.COLUMN_EVENT_TYPE); int sourceDeviceIdx = cursor.getColumnIndex(EventLogColumns.COLUMN_SOURCE_DEVICE_ID); int timestampIdx = cursor.getColumnIndexOrThrow(EventLogColumns.COLUMN_TIMESTAMP); int payloadIdx = cursor.getColumnIndex(EventLogColumns.COLUMN_PAYLOAD); Builder eventBuilder = Event.newBuilder(); eventBuilder.setTimestamp(cursor.getLong(timestampIdx)); eventBuilder.setType(Event.Type.valueOf(cursor.getInt(typeIdx))); if (payloadIdx != -1 && !cursor.isNull(payloadIdx)) { eventBuilder.setPayload(ByteString.copyFrom(cursor.getBlob(payloadIdx))); } if (sourceDeviceIdx != -1 && !cursor.isNull(sourceDeviceIdx)) { eventBuilder.setSourceDeviceId(cursor.getLong(sourceDeviceIdx)); } return eventBuilder.build(); } public void markEventProcessed(long eventId) { Uri uri = getEventUri(eventId); ContentValues values = new ContentValues(1); values.put(EventLogColumns.COLUMN_PROCESSED, true); contentResolver.update(uri, values , null, null); Log.d(TAG, "Marked event " + eventId + " as processed"); } public void deleteEvent(long eventId) { Uri uri = getEventUri(eventId); contentResolver.delete(uri, null, null); Log.d(TAG, "Deleted event" + eventId); } private Uri getEventUri(long eventId) { return Uri.withAppendedPath(EventLogColumns.URI, Long.toString(eventId)); } }
Java
/* * Copyright 2011 Rodrigo Damazio * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.damazio.notifier.event.log; import static org.damazio.notifier.Constants.TAG; import java.io.InputStream; import java.util.Scanner; import org.damazio.notifier.R; import android.content.Context; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.util.Log; public class LogDbHelper extends SQLiteOpenHelper { private static final int CURRENT_DB_VERSION = 1; private static final String DB_NAME = "eventlog"; private final Context context; public LogDbHelper(Context context) { super(context, DB_NAME, null, CURRENT_DB_VERSION); this.context = context; } @Override public void onCreate(SQLiteDatabase db) { InputStream schemaStream = context.getResources().openRawResource(R.raw.logdb_schema); Scanner schemaScanner = new Scanner(schemaStream, "UTF-8"); schemaScanner.useDelimiter(";"); Log.i(TAG, "Creating database"); try { db.beginTransaction(); while (schemaScanner.hasNext()) { String statement = schemaScanner.next(); Log.d(TAG, "Creating database: " + statement); db.execSQL(statement); } db.setTransactionSuccessful(); } finally { db.endTransaction(); } } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // No upgrade for now. } }
Java
/* * Copyright 2011 Rodrigo Damazio * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.damazio.notifier.event; import static org.damazio.notifier.Constants.TAG; import java.util.HashSet; import java.util.Set; import org.damazio.notifier.comm.pairing.DeviceManager; import org.damazio.notifier.event.log.EventLogColumns; import org.damazio.notifier.event.log.EventLogHelper; import org.damazio.notifier.prefs.Preferences; import org.damazio.notifier.protocol.Common.Event; import android.content.Context; import android.database.ContentObserver; import android.database.Cursor; import android.os.Handler; import android.os.HandlerThread; import android.util.Log; import com.google.protobuf.MessageLite; public class EventManager { private final EventLogHelper logHelper; private final Preferences preferences; private final EventContext eventContext; private HandlerThread eventThread; private final Set<EventListener> listeners = new HashSet<EventListener>(); private ContentObserver logObserver; private long lastEventId; public EventManager(Context context) { this(context, new DeviceManager(), new Preferences(context)); } public EventManager(Context context, DeviceManager deviceManager, Preferences preferences) { this.logHelper = new EventLogHelper(context.getContentResolver()); this.preferences = preferences; // TODO: Cut this circular dependency this.eventContext = new EventContext(context, this, deviceManager, preferences); } public EventContext getEventContext() { return eventContext; } // TODO: How to ensure a wake lock is kept until the event is handled? public void handleLocalEvent(Event.Type eventType, MessageLite payload) { // Save the event to the event log. // Listeners will be notified by the logObserver. Log.d(TAG, "Saved event with type=" + eventType + "; payload=" + payload); logHelper.insertEvent(eventType, payload.toByteArray(), System.currentTimeMillis(), null); } public void handleRemoteEvent(Event event) { // Save the event to the event log. // Listeners will be notified by the logObserver. Log.d(TAG, "Received event " + event); logHelper.insertEvent(event.getType(), event.getPayload().toByteArray(), event.getTimestamp(), event.getSourceDeviceId()); } public void markEventProcessed(long eventId) { if (preferences.shouldPruneLog() && preferences.getPruneLogDays() == 0) { // Prune immediately. logHelper.deleteEvent(eventId); } else { logHelper.markEventProcessed(eventId); } } public void registerEventListeners(EventListener... addedListeners) { synchronized (listeners) { if (listeners.isEmpty()) { registerEventLogListener(); } for (EventListener listener : addedListeners) { listeners.add(listener); } } } public void unregisterEventListeners(EventListener... removedListeners) { synchronized (listeners) { for (EventListener listener : removedListeners) { listeners.remove(listener); } if (listeners.isEmpty()) { unregisterEventLogListener(); } } } public void forceRetryProcessing() { logObserver.dispatchChange(false); } private void registerEventLogListener() { if (eventThread != null) return; // Listen for new events in the event log. eventThread = new HandlerThread("EventObserverThread"); eventThread.start(); Handler handler = new Handler(eventThread.getLooper()); logObserver = new ContentObserver(handler) { @Override public void onChange(boolean selfChange) { notifyNewEvents(); } }; logHelper.registerContentObserver(logObserver); // Do an initial run to ensure any missed events are delivered. logObserver.dispatchChange(false); } private void unregisterEventLogListener() { if (eventThread == null) return; logHelper.unregisterContentObserver(logObserver); eventThread.quit(); try { eventThread.join(1000); } catch (InterruptedException e) { Log.e(TAG, "Failed to join event thread", e); } eventThread = null; logObserver = null; } private void notifyNewEvents() { // Get all unprocessed events since the last one. // TODO: Also retry older ones, up to a certain deadline, but not too quickly. Cursor cursor = logHelper.getUnprocessedEvents(lastEventId + 1); synchronized (listeners) { while (cursor.moveToNext()) { Event event = logHelper.buildEvent(cursor); Log.d(TAG, "Notifying about " + event.toString()); boolean isLocal = !event.hasSourceDeviceId(); boolean isCommand = ((event.getType().getNumber() & Event.Type.COMMAND_MASK_VALUE) != 0); lastEventId = cursor.getLong(cursor.getColumnIndexOrThrow(EventLogColumns._ID)); for (EventListener listener : listeners) { listener.onNewEvent(eventContext, lastEventId, event, isLocal, isCommand); } } } } }
Java
/* * Copyright 2011 Rodrigo Damazio * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.damazio.notifier.prefs; import org.damazio.notifier.Constants; import android.app.backup.BackupAgentHelper; import android.app.backup.SharedPreferencesBackupHelper; /** * Backup agent for notifier data. * * @author Rodrigo Damazio */ public class BackupAgent extends BackupAgentHelper { @Override public void onCreate() { super.onCreate(); addHelper("sharedPrefs", new SharedPreferencesBackupHelper(this, Constants.PREFERENCES_NAME)); // TODO: Backup event log } }
Java
/* * Copyright 2011 Rodrigo Damazio * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.damazio.notifier.prefs; import java.util.EnumSet; import java.util.HashSet; import java.util.Set; import org.damazio.notifier.Constants; import org.damazio.notifier.R; import org.damazio.notifier.comm.transport.TransportType; import org.damazio.notifier.protocol.Common.Event; import org.damazio.notifier.protocol.Common.Event.Type; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; /** * Wrapper for preference access. * * @author Rodrigo Damazio */ public class Preferences { private final SharedPreferences prefs; private final Context context; private final Set<PreferenceListener> listeners = new HashSet<Preferences.PreferenceListener>(); private final OnSharedPreferenceChangeListener prefsListener = new OnSharedPreferenceChangeListener() { public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { notifyPreferenceChanged(key); } }; /** Semantic listener for preference changes. */ public static abstract class PreferenceListener { public void onStartForegroundChanged(boolean startForeground) {} public void onSendEventStateChanged(Event.Type type, boolean enabled) {} public void onTransportStateChanged(TransportType type, boolean enabled) {} } public Preferences(Context ctx) { this(ctx, ctx.getSharedPreferences(Constants.PREFERENCES_NAME, Context.MODE_PRIVATE)); } public Preferences(Context ctx, SharedPreferences prefs) { this.context = ctx; this.prefs = prefs; } public void registerListener(PreferenceListener listener) { registerListener(listener, false); } public void registerListener(PreferenceListener listener, boolean initialNotification) { synchronized (listeners) { if (listeners.isEmpty()) { prefs.registerOnSharedPreferenceChangeListener(prefsListener); } listeners.add(listener); if (initialNotification) { notifyAllPreferencesTo(listener); } } } public void unregisterListener(PreferenceListener listener) { synchronized (listeners) { listeners.remove(listener); if (listeners.isEmpty()) { prefs.unregisterOnSharedPreferenceChangeListener(prefsListener); } } } private void notifyPreferenceChanged(String key) { if (context.getString(R.string.prefkey_start_foreground).equals(key)) { synchronized (listeners) { boolean startForeground = startForeground(); for (PreferenceListener listener : listeners) { listener.onStartForegroundChanged(startForeground); } } } // TODO: Transport and event states } private void notifyAllPreferencesTo(PreferenceListener listener) { listener.onStartForegroundChanged(startForeground()); EnumSet<TransportType> enabledSendTransports = getEnabledTransports(); for (TransportType type : TransportType.values()) { listener.onTransportStateChanged(type, enabledSendTransports.contains(type)); } EnumSet<Type> enabledSendEventTypes = getEnabledSendEventTypes(); for (Event.Type type : Event.Type.values()) { listener.onSendEventStateChanged(type, enabledSendEventTypes.contains(type)); } } public boolean isEventTypeEnabled(Event.Type type) { String prefName = context.getString(R.string.prefkey_event_type_format, type.name()); return prefs.getBoolean(prefName, true); } public boolean startForeground() { return prefs.getBoolean(context.getString(R.string.prefkey_start_foreground), true); } public int getMaxBatteryLevel() { return prefs.getInt(context.getString(R.string.prefkey_max_battery_level), 100); } public int getMinBatteryLevel() { return prefs.getInt(context.getString(R.string.prefkey_min_battery_level), 0); } public int getMinBatteryLevelChange() { return prefs.getInt(context.getString(R.string.prefkey_min_battery_level_change), 5); } public boolean shouldPruneLog() { return prefs.getBoolean(context.getString(R.string.prefkey_prune_log), false); } public int getPruneLogDays() { String daysStr = prefs.getString(context.getString(R.string.prefkey_prune_log_days), "7"); return Integer.parseInt(daysStr); } public boolean isSystemDisplayEnabled() { return prefs.getBoolean(context.getString(R.string.prefkey_display_system), true); } public boolean isToastDisplayEnabled() { return prefs.getBoolean(context.getString(R.string.prefkey_display_toast), false); } public boolean isPopupDisplayEnabled() { return prefs.getBoolean(context.getString(R.string.prefkey_display_popup), false); } public EnumSet<TransportType> getEnabledTransports() { EnumSet<TransportType> transports = EnumSet.noneOf(TransportType.class); if (prefs.getBoolean(context.getString(R.string.prefkey_comm_method_bluetooth), false)) { transports.add(TransportType.BLUETOOTH); } if (prefs.getBoolean(context.getString(R.string.prefkey_comm_method_ip), false)) { transports.add(TransportType.IP); } if (prefs.getBoolean(context.getString(R.string.prefkey_comm_method_usb), false)) { transports.add(TransportType.USB); } if (prefs.getBoolean(context.getString(R.string.prefkey_comm_method_cloud), false)) { transports.add(TransportType.CLOUD); } return transports; } public EnumSet<Event.Type> getEnabledSendEventTypes() { EnumSet<Event.Type> events = EnumSet.noneOf(Event.Type.class); if (!prefs.getBoolean(context.getString(R.string.prefkey_send_notifications), true)) { // Master switch disabled. return events; } if (prefs.getBoolean(context.getString(R.string.prefkey_send_battery), true)) { events.add(Event.Type.NOTIFICATION_BATTERY); } if (prefs.getBoolean(context.getString(R.string.prefkey_send_missed_call), true)) { events.add(Event.Type.NOTIFICATION_MISSED_CALL); } if (prefs.getBoolean(context.getString(R.string.prefkey_send_mms), true)) { events.add(Event.Type.NOTIFICATION_MMS); } if (prefs.getBoolean(context.getString(R.string.prefkey_send_ring), true)) { events.add(Event.Type.NOTIFICATION_RING); } if (prefs.getBoolean(context.getString(R.string.prefkey_send_sms), true)) { events.add(Event.Type.NOTIFICATION_SMS); } if (prefs.getBoolean(context.getString(R.string.prefkey_send_third_party), true)) { events.add(Event.Type.NOTIFICATION_THIRD_PARTY); } if (prefs.getBoolean(context.getString(R.string.prefkey_send_voicemail), true)) { events.add(Event.Type.NOTIFICATION_VOICEMAIL); } return events; } public boolean isIpOverTcp() { // TODO Auto-generated method stub return false; } public void setC2dmRegistrationId(String registrationId) { // TODO Auto-generated method stub } public void setC2dmServerRegistered(boolean b) { // TODO Auto-generated method stub } }
Java
/* * Copyright 2011 Rodrigo Damazio * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.damazio.notifier.prefs; import org.damazio.notifier.R; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.os.Bundle; import android.preference.PreferenceManager; public class PreferenceActivity extends android.preference.PreferenceActivity { private SharedPreferences preferences; private OnSharedPreferenceChangeListener backupListener; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); preferences = PreferenceManager.getDefaultSharedPreferences(this); backupListener = BackupPreferenceListener.create(this); addPreferencesFromResource(R.xml.prefs); } @Override protected void onStart() { super.onStart(); preferences.registerOnSharedPreferenceChangeListener(backupListener); } @Override protected void onStop() { preferences.unregisterOnSharedPreferenceChangeListener(backupListener); super.onStop(); } }
Java
/* * Copyright 2011 Rodrigo Damazio * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.damazio.notifier.prefs; import android.app.backup.BackupManager; import android.content.Context; import android.content.SharedPreferences; import android.content.SharedPreferences.OnSharedPreferenceChangeListener; import android.os.Build; public class BackupPreferenceListener { /** * Real implementation of the listener, which calls the {@link BackupManager}. */ private static class BackupPreferencesListenerImpl implements OnSharedPreferenceChangeListener{ private final BackupManager backupManager; public BackupPreferencesListenerImpl(Context context) { this.backupManager = new BackupManager(context); } public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) { backupManager.dataChanged(); } } /** * Creates and returns a proper instance of the listener for this device. */ public static OnSharedPreferenceChangeListener create(Context context) { if (Build.VERSION.SDK_INT >= 8) { return new BackupPreferencesListenerImpl(context); } else { return null; } } private BackupPreferenceListener() {} }
Java
/* * Copyright 2011 Rodrigo Damazio * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.damazio.notifier; import static org.damazio.notifier.Constants.TAG; import org.damazio.notifier.prefs.Preferences; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; public class BootServiceStarter extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction() != Intent.ACTION_BOOT_COMPLETED) { Log.w(TAG, "Received unexpected intent: " + intent); return; } Preferences preferences = new Preferences(context); // TODO: Check if start at boot requested. context.startService(new Intent(context, NotifierService.class)); } }
Java
package org.damazio.notifier.util; import static org.damazio.notifier.Constants.TAG; import android.content.Context; import android.provider.Settings; import android.util.Log; public class DeviceUtils { public static long getDeviceId(Context context) { String deviceIdStr = Settings.Secure.getString( context.getContentResolver(), Settings.Secure.ANDROID_ID); if (deviceIdStr == null) { long rand = Double.doubleToRawLongBits(Math.random() * Long.MAX_VALUE); Log.w(TAG, "No device ID found - created random ID " + rand); return rand; } else { return Long.parseLong(deviceIdStr, 16); } } private DeviceUtils() {} }
Java
/* * Copyright 2011 Rodrigo Damazio * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.damazio.notifier.command.executers.call; import org.damazio.notifier.command.executers.CommandExecuter; import android.content.Context; import com.google.protobuf.ByteString; public class HangUpExecuter implements CommandExecuter { public void executeCommand(Context context, ByteString payload) { // TODO: Implement } }
Java
/* * Copyright 2011 Rodrigo Damazio * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.damazio.notifier.command.executers.call; import static org.damazio.notifier.Constants.TAG; import org.damazio.notifier.command.executers.CommandExecuter; import org.damazio.notifier.protocol.Commands.CallCommand; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.util.Log; import com.google.protobuf.ByteString; import com.google.protobuf.InvalidProtocolBufferException; public class CallExecuter implements CommandExecuter { public void executeCommand(Context context, ByteString payload) { CallCommand cmd; try { cmd = CallCommand.parseFrom(payload); } catch (InvalidProtocolBufferException e) { throw new IllegalArgumentException("Unable to parse call command: " + payload, e); } Log.i(TAG, "Calling " + cmd.getNumber()); Uri numberUri = Uri.fromParts("tel", cmd.getNumber(), null); Intent intent = new Intent(Intent.ACTION_CALL); intent.setData(numberUri); context.startActivity(intent); } }
Java
/* * Copyright 2011 Rodrigo Damazio * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.damazio.notifier.command.executers; import com.google.protobuf.ByteString; import android.content.Context; public interface CommandExecuter { void executeCommand(Context context, ByteString payload); }
Java
/* * Copyright 2011 Rodrigo Damazio * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.damazio.notifier.command.executers.sms; import static org.damazio.notifier.Constants.TAG; import java.util.ArrayList; import org.damazio.notifier.command.executers.CommandExecuter; import org.damazio.notifier.protocol.Commands.SmsCommand; import com.google.protobuf.ByteString; import com.google.protobuf.InvalidProtocolBufferException; import android.content.Context; import android.telephony.SmsManager; import android.util.Log; public class SmsExecuter implements CommandExecuter { public void executeCommand(Context context, ByteString payload) { SmsCommand command; try { command = SmsCommand.parseFrom(payload); } catch (InvalidProtocolBufferException e) { Log.e(TAG, "Failed to parse SMS command", e); return; } String text = command.getText(); String number = command.getToNumber(); SmsManager smsManager = SmsManager.getDefault(); ArrayList<String> textParts = smsManager.divideMessage(text); // TODO: Some day, notify back about sent and delivered. smsManager.sendMultipartTextMessage(number, null, textParts, null, null); } }
Java
/* * Copyright 2011 Rodrigo Damazio * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.damazio.notifier.command.executers; import static org.damazio.notifier.Constants.TAG; import org.damazio.notifier.command.executers.call.CallExecuter; import org.damazio.notifier.command.executers.call.HangUpExecuter; import org.damazio.notifier.command.executers.sms.SmsExecuter; import org.damazio.notifier.event.EventContext; import org.damazio.notifier.event.EventListener; import org.damazio.notifier.protocol.Common.Event; import android.util.Log; /** * Locally executes remote commands. * * @author Rodrigo Damazio */ public class RemoteCommandExecuter implements EventListener { public void onNewEvent(EventContext context, long eventId, Event event, boolean isLocal, boolean isCommand) { // Ensure it's a command sent from another device. if (isLocal || !isCommand) { return; } Log.d(TAG, "Executing command " + event); CommandExecuter executer = getExecuterForType(event.getType()); executer.executeCommand(context.getAndroidContext(), event.getPayload()); context.getEventManager().markEventProcessed(eventId); } private CommandExecuter getExecuterForType(Event.Type type) { switch (type) { case COMMAND_CALL: return new CallExecuter(); case COMMAND_HANGUP: return new HangUpExecuter(); case COMMAND_SMS: return new SmsExecuter(); default: throw new IllegalArgumentException("Don't know how to handle type " + type); } } }
Java
/* * Copyright 2011 Rodrigo Damazio * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.damazio.notifier.command; import android.app.Activity; /** * Activity used to send commands to other devices. * * @author Rodrigo Damazio */ public class CommandsActivity extends Activity { }
Java
/* * Copyright 2011 Rodrigo Damazio * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.damazio.notifier; public class Constants { /** * The tag to use for all logging done in the application. */ public static final String TAG = "RemoteNotifier"; /** * Name of the preferences, as generated by * {@link android.preference.PreferenceManager#getDefaultSharedPreferences}. */ public static final String PREFERENCES_NAME = "org.damazio.notifier_preferences"; /** * Maximum time after which a notification will still be sent. */ public static final int MAX_NOTIFICATION_AGE_SEC = 10 * 60; }
Java
/* * Copyright 2011 Rodrigo Damazio * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.damazio.notifier; import java.util.List; import org.damazio.notifier.comm.pairing.DeviceManager; import org.damazio.notifier.comm.transport.RemoteEventReceiver; import org.damazio.notifier.comm.transport.LocalEventSender; import org.damazio.notifier.command.executers.RemoteCommandExecuter; import org.damazio.notifier.event.EventContext; import org.damazio.notifier.event.EventManager; import org.damazio.notifier.event.display.RemoteNotificationDisplayer; import org.damazio.notifier.event.receivers.LocalEventReceiver; import org.damazio.notifier.prefs.Preferences; import org.damazio.notifier.prefs.Preferences.PreferenceListener; import android.app.ActivityManager; import android.app.ActivityManager.RunningServiceInfo; import android.app.Notification; import android.app.PendingIntent; import android.app.Service; import android.content.ComponentName; import android.content.Context; import android.content.Intent; import android.os.IBinder; public class NotifierService extends Service { /** An independent module which has the same lifecycle as the service. */ public static interface NotifierServiceModule { void onCreate(); void onDestroy(); } private final PreferenceListener preferencesListener = new PreferenceListener() { @Override public void onStartForegroundChanged(boolean startForeground) { updateForegroundState(startForeground); } }; private Preferences preferences; private DeviceManager deviceManager; /** Manages events and the event log. */ private EventManager eventManager; /** Receives events from other devices. */ private RemoteEventReceiver remoteEventReceiver; /** Receives events from the local system. */ private LocalEventReceiver localEventReceiver; /** Sends events to other devices. */ private LocalEventSender localEventSender; /** Executes remote commands locally. */ private RemoteCommandExecuter commandExecuter; /** Displays remote notifications locally. */ private RemoteNotificationDisplayer notificationDisplayer; @Override public void onCreate() { super.onCreate(); preferences = new Preferences(this); preferences.registerListener(preferencesListener); updateForegroundState(preferences.startForeground()); deviceManager = new DeviceManager(); eventManager = new EventManager(this, deviceManager, preferences); EventContext eventContext = new EventContext(this, eventManager, deviceManager, preferences); // Modules (external-event-driven) remoteEventReceiver = new RemoteEventReceiver(eventContext); localEventReceiver = new LocalEventReceiver(eventContext); remoteEventReceiver.onCreate(); localEventReceiver.onCreate(); // Event-log-driven localEventSender = new LocalEventSender(eventContext); localEventSender.onCreate(); commandExecuter = new RemoteCommandExecuter(); notificationDisplayer = new RemoteNotificationDisplayer(); eventManager.registerEventListeners(localEventSender, commandExecuter, notificationDisplayer); } private void updateForegroundState(boolean startForeground) { if (startForeground) { startForeground(); } else { stopForeground(true); } } private void startForeground() { PendingIntent intent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), 0); Notification notification = new Notification(R.drawable.icon, null /* ticker */, System.currentTimeMillis()); notification.setLatestEventInfo(this, getString(R.string.notification_title), getString(R.string.notification_text), intent); notification.flags |= Notification.FLAG_NO_CLEAR; notification.flags |= Notification.FLAG_ONGOING_EVENT; // TODO: Ensure this never collides with event display notification IDs startForeground(0x91287346, notification); } @Override public void onStart(Intent intent, int startId) { handleCommand(intent); } @Override public int onStartCommand(Intent intent, int flags, int startId) { handleCommand(intent); return START_STICKY; } private void handleCommand(Intent intent) { // TODO: Intents for locale and otherss } @Override public IBinder onBind(Intent intent) { return null; } @Override public void onDestroy() { preferences.unregisterListener(preferencesListener); eventManager.unregisterEventListeners(localEventSender, commandExecuter, notificationDisplayer); localEventReceiver.onDestroy(); remoteEventReceiver.onDestroy(); stopForeground(true); super.onDestroy(); } @Override public void onLowMemory() { // TODO: We run in the foreground, so it's probably polite to do something here. } public static void startIfNotRunning(Context context) { if (!isRunning(context)) { context.startService(new Intent(context, NotifierService.class)); } } /** * Uses the given context to determine whether the service is already running. */ public static boolean isRunning(Context context) { ActivityManager activityManager = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE); List<RunningServiceInfo> services = activityManager.getRunningServices(Integer.MAX_VALUE); for (RunningServiceInfo serviceInfo : services) { ComponentName componentName = serviceInfo.service; String serviceName = componentName.getClassName(); if (serviceName.equals(NotifierService.class.getName())) { return true; } } return false; } protected Preferences getPreferences() { return preferences; } }
Java
/* * Copyright 2011 Rodrigo Damazio * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.damazio.notifier; import org.damazio.notifier.prefs.PreferenceActivity; import android.app.Activity; import android.content.Intent; import android.os.Bundle; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // For now, just go to preferences. startActivity(new Intent(this, PreferenceActivity.class)); } }
Java
package com.ch_linghu.fanfoudroid; import java.text.ParseException; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.database.Cursor; import android.graphics.Bitmap; import android.os.Bundle; import android.util.Log; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.Button; import android.widget.CursorAdapter; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import com.ch_linghu.fanfoudroid.app.LazyImageLoader.ImageLoaderCallback; import com.ch_linghu.fanfoudroid.app.Preferences; import com.ch_linghu.fanfoudroid.data.Dm; import com.ch_linghu.fanfoudroid.db.MessageTable; import com.ch_linghu.fanfoudroid.db.TwitterDatabase; import com.ch_linghu.fanfoudroid.fanfou.DirectMessage; import com.ch_linghu.fanfoudroid.fanfou.Paging; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.task.GenericTask; import com.ch_linghu.fanfoudroid.task.TaskAdapter; import com.ch_linghu.fanfoudroid.task.TaskListener; import com.ch_linghu.fanfoudroid.task.TaskParams; import com.ch_linghu.fanfoudroid.task.TaskResult; import com.ch_linghu.fanfoudroid.ui.base.BaseActivity; import com.ch_linghu.fanfoudroid.ui.base.Refreshable; import com.ch_linghu.fanfoudroid.ui.module.Feedback; import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory; import com.ch_linghu.fanfoudroid.ui.module.FeedbackFactory.FeedbackType; import com.ch_linghu.fanfoudroid.ui.module.NavBar; import com.ch_linghu.fanfoudroid.ui.module.SimpleFeedback; import com.ch_linghu.fanfoudroid.util.DateTimeHelper; import com.ch_linghu.fanfoudroid.util.MiscHelper; import com.ch_linghu.fanfoudroid.util.TextHelper; public class DmActivity extends BaseActivity implements Refreshable { private static final String TAG = "DmActivity"; // Views. private ListView mTweetList; private Adapter mAdapter; private Adapter mInboxAdapter; private Adapter mSendboxAdapter; Button inbox; Button sendbox; Button newMsg; private int mDMType; private static final int DM_TYPE_ALL = 0; private static final int DM_TYPE_INBOX = 1; private static final int DM_TYPE_SENDBOX = 2; private TextView mProgressText; private NavBar mNavbar; private Feedback mFeedback; // Tasks. private GenericTask mRetrieveTask; private GenericTask mDeleteTask; private TaskListener mDeleteTaskListener = new TaskAdapter(){ @Override public void onPreExecute(GenericTask task) { updateProgress(getString(R.string.page_status_deleting)); } @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.AUTH_ERROR) { logout(); } else if (result == TaskResult.OK) { mAdapter.refresh(); } else { // Do nothing. } updateProgress(""); } @Override public String getName() { return "DmDeleteTask"; } }; private TaskListener mRetrieveTaskListener = new TaskAdapter(){ @Override public void onPreExecute(GenericTask task) { updateProgress(getString(R.string.page_status_refreshing)); } @Override public void onProgressUpdate(GenericTask task, Object params) { draw(); } @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.AUTH_ERROR) { logout(); } else if (result == TaskResult.OK) { SharedPreferences.Editor editor = mPreferences.edit(); editor.putLong(Preferences.LAST_DM_REFRESH_KEY, DateTimeHelper.getNowTime()); editor.commit(); draw(); goTop(); } else { // Do nothing. } updateProgress(""); } @Override public String getName() { return "DmRetrieve"; } }; // Refresh data at startup if last refresh was this long ago or greater. private static final long REFRESH_THRESHOLD = 5 * 60 * 1000; private static final String EXTRA_USER = "user"; private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.DMS"; public static Intent createIntent() { return createIntent(""); } public static Intent createIntent(String user) { Intent intent = new Intent(LAUNCH_ACTION); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); if (!TextHelper.isEmpty(user)) { intent.putExtra(EXTRA_USER, user); } return intent; } @Override protected boolean _onCreate(Bundle savedInstanceState) { if (super._onCreate(savedInstanceState)) { setContentView(R.layout.dm); mNavbar = new NavBar(NavBar.HEADER_STYLE_HOME, this); mNavbar.setHeaderTitle("我的私信"); mFeedback = FeedbackFactory.create(this, FeedbackType.PROGRESS); bindFooterButtonEvent(); mTweetList = (ListView) findViewById(R.id.tweet_list); mProgressText = (TextView) findViewById(R.id.progress_text); TwitterDatabase db = getDb(); // Mark all as read. db.markAllDmsRead(); setupAdapter(); // Make sure call bindFooterButtonEvent first boolean shouldRetrieve = false; long lastRefreshTime = mPreferences.getLong( Preferences.LAST_DM_REFRESH_KEY, 0); long nowTime = DateTimeHelper.getNowTime(); long diff = nowTime - lastRefreshTime; Log.d(TAG, "Last refresh was " + diff + " ms ago."); if (diff > REFRESH_THRESHOLD) { shouldRetrieve = true; } else if (MiscHelper.isTrue(savedInstanceState, SIS_RUNNING_KEY)) { // Check to see if it was running a send or retrieve task. // It makes no sense to resend the send request (don't want dupes) // so we instead retrieve (refresh) to see if the message has // posted. Log.d(TAG, "Was last running a retrieve or send task. Let's refresh."); shouldRetrieve = true; } if (shouldRetrieve) { doRetrieve(); } // Want to be able to focus on the items with the trackball. // That way, we can navigate up and down by changing item focus. mTweetList.setItemsCanFocus(true); return true; }else{ return false; } } @Override protected void onResume() { super.onResume(); checkIsLogedIn(); } private static final String SIS_RUNNING_KEY = "running"; @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (mRetrieveTask != null && mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) { outState.putBoolean(SIS_RUNNING_KEY, true); } } @Override protected void onDestroy() { Log.d(TAG, "onDestroy."); if (mRetrieveTask != null && mRetrieveTask.getStatus() == GenericTask.Status.RUNNING) { mRetrieveTask.cancel(true); } if (mDeleteTask != null && mDeleteTask.getStatus() == GenericTask.Status.RUNNING) { mDeleteTask.cancel(true); } super.onDestroy(); } // UI helpers. private void bindFooterButtonEvent() { inbox = (Button) findViewById(R.id.inbox); sendbox = (Button) findViewById(R.id.sendbox); newMsg = (Button) findViewById(R.id.new_message); inbox.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mDMType != DM_TYPE_INBOX) { mDMType = DM_TYPE_INBOX; inbox.setEnabled(false); sendbox.setEnabled(true); mTweetList.setAdapter(mInboxAdapter); mInboxAdapter.refresh(); } } }); sendbox.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mDMType != DM_TYPE_SENDBOX) { mDMType = DM_TYPE_SENDBOX; inbox.setEnabled(true); sendbox.setEnabled(false); mTweetList.setAdapter(mSendboxAdapter); mSendboxAdapter.refresh(); } } }); newMsg.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent intent = new Intent(); intent.setClass(DmActivity.this, WriteDmActivity.class); intent.putExtra("reply_to_id", 0); // TODO: 传入实际的reply_to_id startActivity(intent); } }); } private void setupAdapter() { Cursor cursor = getDb().fetchAllDms(-1); startManagingCursor(cursor); mAdapter = new Adapter(this, cursor); Cursor inboxCursor = getDb().fetchInboxDms(); startManagingCursor(inboxCursor); mInboxAdapter = new Adapter(this, inboxCursor); Cursor sendboxCursor = getDb().fetchSendboxDms(); startManagingCursor(sendboxCursor); mSendboxAdapter = new Adapter(this, sendboxCursor); mTweetList.setAdapter(mInboxAdapter); registerForContextMenu(mTweetList); inbox.setEnabled(false); } private class DmRetrieveTask extends GenericTask { @Override protected TaskResult _doInBackground(TaskParams...params) { List<DirectMessage> dmList; ArrayList<Dm> dms = new ArrayList<Dm>(); TwitterDatabase db = getDb(); //ImageManager imageManager = getImageManager(); String maxId = db.fetchMaxDmId(false); HashSet<String> imageUrls = new HashSet<String>(); try { if (maxId != null) { Paging paging = new Paging(maxId); dmList = getApi().getDirectMessages(paging); } else { dmList = getApi().getDirectMessages(); } } catch (HttpException e) { Log.e(TAG, e.getMessage(), e); return TaskResult.IO_ERROR; } publishProgress(SimpleFeedback.calProgressBySize(40, 20, dmList)); for (DirectMessage directMessage : dmList) { if (isCancelled()) { return TaskResult.CANCELLED; } Dm dm; dm = Dm.create(directMessage, false); dms.add(dm); imageUrls.add(dm.profileImageUrl); if (isCancelled()) { return TaskResult.CANCELLED; } } maxId = db.fetchMaxDmId(true); try { if (maxId != null) { Paging paging = new Paging(maxId); dmList = getApi().getSentDirectMessages(paging); } else { dmList = getApi().getSentDirectMessages(); } } catch (HttpException e) { Log.e(TAG, e.getMessage(), e); return TaskResult.IO_ERROR; } for (DirectMessage directMessage : dmList) { if (isCancelled()) { return TaskResult.CANCELLED; } Dm dm; dm = Dm.create(directMessage, true); dms.add(dm); imageUrls.add(dm.profileImageUrl); if (isCancelled()) { return TaskResult.CANCELLED; } } db.addDms(dms, false); // if (isCancelled()) { // return TaskResult.CANCELLED; // } // // publishProgress(null); // // for (String imageUrl : imageUrls) { // if (!Utils.isEmpty(imageUrl)) { // // Fetch image to cache. // try { // imageManager.put(imageUrl); // } catch (IOException e) { // Log.e(TAG, e.getMessage(), e); // } // } // // if (isCancelled()) { // return TaskResult.CANCELLED; // } // } return TaskResult.OK; } } private static class Adapter extends CursorAdapter { public Adapter(Context context, Cursor cursor) { super(context, cursor); mInflater = LayoutInflater.from(context); // TODO: 可使用: //DM dm = MessageTable.parseCursor(cursor); mUserTextColumn = cursor .getColumnIndexOrThrow(MessageTable.FIELD_USER_SCREEN_NAME); mTextColumn = cursor .getColumnIndexOrThrow(MessageTable.FIELD_TEXT); mProfileImageUrlColumn = cursor .getColumnIndexOrThrow(MessageTable.FIELD_PROFILE_IMAGE_URL); mCreatedAtColumn = cursor .getColumnIndexOrThrow(MessageTable.FIELD_CREATED_AT); mIsSentColumn = cursor .getColumnIndexOrThrow(MessageTable.FIELD_IS_SENT); } private LayoutInflater mInflater; private int mUserTextColumn; private int mTextColumn; private int mProfileImageUrlColumn; private int mIsSentColumn; private int mCreatedAtColumn; @Override public View newView(Context context, Cursor cursor, ViewGroup parent) { View view = mInflater.inflate(R.layout.direct_message, parent, false); ViewHolder holder = new ViewHolder(); holder.userText = (TextView) view .findViewById(R.id.tweet_user_text); holder.tweetText = (TextView) view.findViewById(R.id.tweet_text); holder.profileImage = (ImageView) view .findViewById(R.id.profile_image); holder.metaText = (TextView) view .findViewById(R.id.tweet_meta_text); view.setTag(holder); return view; } class ViewHolder { public TextView userText; public TextView tweetText; public ImageView profileImage; public TextView metaText; } @Override public void bindView(View view, Context context, Cursor cursor) { ViewHolder holder = (ViewHolder) view.getTag(); int isSent = cursor.getInt(mIsSentColumn); String user = cursor.getString(mUserTextColumn); if (0 == isSent) { holder.userText.setText(context .getString(R.string.direct_message_label_from_prefix) + user); } else { holder.userText.setText(context .getString(R.string.direct_message_label_to_prefix) + user); } TextHelper.setTweetText(holder.tweetText, cursor.getString(mTextColumn)); String profileImageUrl = cursor.getString(mProfileImageUrlColumn); if (!TextHelper.isEmpty(profileImageUrl)) { holder.profileImage .setImageBitmap(TwitterApplication.mImageLoader .get(profileImageUrl, new ImageLoaderCallback(){ @Override public void refresh(String url, Bitmap bitmap) { Adapter.this.refresh(); } })); } try { holder.metaText.setText(DateTimeHelper .getRelativeDate(TwitterDatabase.DB_DATE_FORMATTER .parse(cursor.getString(mCreatedAtColumn)))); } catch (ParseException e) { Log.w(TAG, "Invalid created at data."); } } public void refresh() { getCursor().requery(); } } // Menu. @Override public boolean onCreateOptionsMenu(Menu menu) { return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { // FIXME: 将刷新功能绑定到顶部的刷新按钮上,主菜单中的刷新选项已删除 // case OPTIONS_MENU_ID_REFRESH: // doRetrieve(); // return true; case OPTIONS_MENU_ID_TWEETS: launchActivity(TwitterActivity.createIntent(this)); return true; case OPTIONS_MENU_ID_REPLIES: launchActivity(MentionActivity.createIntent(this)); return true; } return super.onOptionsItemSelected(item); } private static final int CONTEXT_REPLY_ID = 0; private static final int CONTEXT_DELETE_ID = 1; @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); menu.add(0, CONTEXT_REPLY_ID, 0, R.string.cmenu_reply); menu.add(0, CONTEXT_DELETE_ID, 0, R.string.cmenu_delete); } @Override public boolean onContextItemSelected(MenuItem item) { AdapterContextMenuInfo info = (AdapterContextMenuInfo) item .getMenuInfo(); Cursor cursor = (Cursor) mAdapter.getItem(info.position); if (cursor == null) { Log.w(TAG, "Selected item not available."); return super.onContextItemSelected(item); } switch (item.getItemId()) { case CONTEXT_REPLY_ID: String user_id = cursor.getString(cursor .getColumnIndexOrThrow(MessageTable.FIELD_USER_ID)); Intent intent = WriteDmActivity.createIntent(user_id); startActivity(intent); return true; case CONTEXT_DELETE_ID: int idIndex = cursor.getColumnIndexOrThrow(MessageTable._ID); String id = cursor.getString(idIndex); doDestroy(id); return true; default: return super.onContextItemSelected(item); } } private void doDestroy(String id) { Log.d(TAG, "Attempting delete."); if (mDeleteTask != null && mDeleteTask.getStatus() == GenericTask.Status.RUNNING){ return; }else{ mDeleteTask = new DmDeleteTask(); mDeleteTask.setListener(mDeleteTaskListener); TaskParams params = new TaskParams(); params.put("id", id); mDeleteTask.execute(params); } } private class DmDeleteTask extends GenericTask { @Override protected TaskResult _doInBackground(TaskParams...params) { TaskParams param = params[0]; try { String id = param.getString("id"); DirectMessage directMessage = getApi().destroyDirectMessage(id); Dm.create(directMessage, false); getDb().deleteDm(id); } catch (HttpException e) { Log.e(TAG, e.getMessage(), e); return TaskResult.IO_ERROR; } if (isCancelled()) { return TaskResult.CANCELLED; } return TaskResult.OK; } } public void doRetrieve() { Log.d(TAG, "Attempting retrieve."); if (mRetrieveTask != null && mRetrieveTask.getStatus() == GenericTask.Status.RUNNING){ return; }else{ mRetrieveTask = new DmRetrieveTask(); mRetrieveTask.setFeedback(mFeedback); mRetrieveTask.setListener(mRetrieveTaskListener); mRetrieveTask.execute(); } } public void goTop() { mTweetList.setSelection(0); } public void draw() { mAdapter.refresh(); mInboxAdapter.refresh(); mSendboxAdapter.refresh(); } private void updateProgress(String msg) { mProgressText.setText(msg); } }
Java
package com.ch_linghu.fanfoudroid; import java.text.MessageFormat; import java.util.List; import android.content.Intent; import android.os.Bundle; import android.view.ContextMenu; import android.view.ContextMenu.ContextMenuInfo; import android.view.View; import android.widget.AdapterView; import android.widget.AdapterView.AdapterContextMenuInfo; import android.widget.ListView; import com.ch_linghu.fanfoudroid.data.User; import com.ch_linghu.fanfoudroid.fanfou.Paging; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.ui.base.UserArrayBaseActivity; import com.ch_linghu.fanfoudroid.ui.module.UserArrayAdapter; public class FollowingActivity extends UserArrayBaseActivity { private ListView mUserList; private UserArrayAdapter mAdapter; private String userId; private String userName; private static final String LAUNCH_ACTION = "com.ch_linghu.fanfoudroid.FOLLOWING"; private static final String USER_ID = "userId"; private static final String USER_NAME = "userName"; private int currentPage=1; String myself=""; @Override protected boolean _onCreate(Bundle savedInstanceState) { Intent intent = getIntent(); Bundle extras = intent.getExtras(); if (extras != null) { this.userId = extras.getString(USER_ID); this.userName = extras.getString(USER_NAME); } else { // 获取登录用户id userId=TwitterApplication.getMyselfId(); userName = TwitterApplication.getMyselfName(); } if(super._onCreate(savedInstanceState)){ myself = TwitterApplication.getMyselfId(); if(getUserId()==myself){ mNavbar.setHeaderTitle(MessageFormat.format( getString(R.string.profile_friends_count_title), "我")); } else { mNavbar.setHeaderTitle(MessageFormat.format( getString(R.string.profile_friends_count_title), userName)); } return true; }else{ return false; } } /* * 添加取消关注按钮 * @see com.ch_linghu.fanfoudroid.ui.base.UserListBaseActivity#onCreateContextMenu(android.view.ContextMenu, android.view.View, android.view.ContextMenu.ContextMenuInfo) */ @Override public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) { super.onCreateContextMenu(menu, v, menuInfo); if(getUserId()==myself){ AdapterView.AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo; User user = getContextItemUser(info.position); menu.add(0,CONTENT_DEL_FRIEND,0,getResources().getString(R.string.cmenu_user_addfriend_prefix)+user.screenName+getResources().getString(R.string.cmenu_user_friend_suffix)); } } public static Intent createIntent(String userId, String userName) { Intent intent = new Intent(LAUNCH_ACTION); intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); intent.putExtra(USER_ID, userId); intent.putExtra(USER_NAME, userName); return intent; } @Override public Paging getNextPage() { currentPage+=1; return new Paging(currentPage); } @Override protected String getUserId() { return this.userId; } @Override public Paging getCurrentPage() { return new Paging(this.currentPage); } @Override protected List<com.ch_linghu.fanfoudroid.fanfou.User> getUsers( String userId, Paging page) throws HttpException { return getApi().getFriendsStatuses(userId, page); } }
Java
/* * Copyright (C) 2009 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ch_linghu.fanfoudroid; import android.app.Activity; import android.app.PendingIntent; import android.app.PendingIntent.CanceledException; import android.app.ProgressDialog; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.text.method.LinkMovementMethod; import android.util.Log; import android.view.KeyEvent; import android.view.View; import android.view.Window; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import com.ch_linghu.fanfoudroid.app.Preferences; import com.ch_linghu.fanfoudroid.fanfou.User; import com.ch_linghu.fanfoudroid.http.HttpAuthException; import com.ch_linghu.fanfoudroid.http.HttpException; import com.ch_linghu.fanfoudroid.http.HttpRefusedException; import com.ch_linghu.fanfoudroid.task.GenericTask; import com.ch_linghu.fanfoudroid.task.TaskAdapter; import com.ch_linghu.fanfoudroid.task.TaskFeedback; import com.ch_linghu.fanfoudroid.task.TaskListener; import com.ch_linghu.fanfoudroid.task.TaskParams; import com.ch_linghu.fanfoudroid.task.TaskResult; import com.ch_linghu.fanfoudroid.util.*; //登录页面需要个性化的菜单绑定, 不直接继承 BaseActivity public class LoginActivity extends Activity { private static final String TAG = "LoginActivity"; private static final String SIS_RUNNING_KEY = "running"; private String mUsername; private String mPassword; // Views. private EditText mUsernameEdit; private EditText mPasswordEdit; private TextView mProgressText; private Button mSigninButton; private ProgressDialog dialog; // Preferences. private SharedPreferences mPreferences; // Tasks. private GenericTask mLoginTask; private User user; private TaskListener mLoginTaskListener = new TaskAdapter(){ @Override public void onPreExecute(GenericTask task) { onLoginBegin(); } @Override public void onProgressUpdate(GenericTask task, Object param) { updateProgress((String)param); } @Override public void onPostExecute(GenericTask task, TaskResult result) { if (result == TaskResult.OK) { onLoginSuccess(); } else { onLoginFailure(((LoginTask)task).getMsg()); } } @Override public String getName() { // TODO Auto-generated method stub return "Login"; } }; @Override protected void onCreate(Bundle savedInstanceState) { Log.d(TAG, "onCreate"); super.onCreate(savedInstanceState); // No Title bar requestWindowFeature(Window.FEATURE_NO_TITLE); requestWindowFeature(Window.FEATURE_PROGRESS); mPreferences = PreferenceManager.getDefaultSharedPreferences(this); setContentView(R.layout.login); // TextView中嵌入HTML链接 TextView registerLink = (TextView) findViewById(R.id.register_link); registerLink.setMovementMethod(LinkMovementMethod.getInstance()); mUsernameEdit = (EditText) findViewById(R.id.username_edit); mPasswordEdit = (EditText) findViewById(R.id.password_edit); // mUsernameEdit.setOnKeyListener(enterKeyHandler); mPasswordEdit.setOnKeyListener(enterKeyHandler); mProgressText = (TextView) findViewById(R.id.progress_text); mProgressText.setFreezesText(true); mSigninButton = (Button) findViewById(R.id.signin_button); if (savedInstanceState != null) { if (savedInstanceState.containsKey(SIS_RUNNING_KEY)) { if (savedInstanceState.getBoolean(SIS_RUNNING_KEY)) { Log.d(TAG, "Was previously logging in. Restart action."); doLogin(); } } } mSigninButton.setOnClickListener(new View.OnClickListener() { public void onClick(View v) { doLogin(); } }); } @Override protected void onDestroy() { Log.d(TAG, "onDestory"); if (mLoginTask != null && mLoginTask.getStatus() == GenericTask.Status.RUNNING) { mLoginTask.cancel(true); } // dismiss dialog before destroy // to avoid android.view.WindowLeaked Exception TaskFeedback.getInstance(TaskFeedback.DIALOG_MODE, LoginActivity.this).cancel(); super.onDestroy(); } @Override protected void onStop() { Log.d(TAG, "onStop"); // TODO Auto-generated method stub super.onStop(); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (mLoginTask != null && mLoginTask.getStatus() == GenericTask.Status.RUNNING) { // If the task was running, want to start it anew when the // Activity restarts. // This addresses the case where you user changes orientation // in the middle of execution. outState.putBoolean(SIS_RUNNING_KEY, true); } } // UI helpers. private void updateProgress(String progress) { mProgressText.setText(progress); } private void enableLogin() { mUsernameEdit.setEnabled(true); mPasswordEdit.setEnabled(true); mSigninButton.setEnabled(true); } private void disableLogin() { mUsernameEdit.setEnabled(false); mPasswordEdit.setEnabled(false); mSigninButton.setEnabled(false); } // Login task. private void doLogin() { mUsername = mUsernameEdit.getText().toString(); mPassword = mPasswordEdit.getText().toString(); if (mLoginTask != null && mLoginTask.getStatus() == GenericTask.Status.RUNNING){ return; }else{ if (!TextHelper.isEmpty(mUsername) & !TextHelper.isEmpty(mPassword) ) { mLoginTask = new LoginTask(); mLoginTask.setListener(mLoginTaskListener); TaskParams params = new TaskParams(); params.put("username", mUsername); params.put("password", mPassword); mLoginTask.execute(params); } else { updateProgress(getString(R.string.login_status_null_username_or_password)); } } } private void onLoginBegin() { disableLogin(); TaskFeedback.getInstance(TaskFeedback.DIALOG_MODE, LoginActivity.this).start( getString(R.string.login_status_logging_in)); } private void onLoginSuccess() { TaskFeedback.getInstance(TaskFeedback.DIALOG_MODE, LoginActivity.this).success(""); updateProgress(""); mUsernameEdit.setText(""); mPasswordEdit.setText(""); Log.d(TAG, "Storing credentials."); TwitterApplication.mApi.setCredentials(mUsername, mPassword); Intent intent = getIntent().getParcelableExtra(Intent.EXTRA_INTENT); String action = intent.getAction(); if (intent.getAction() == null || !Intent.ACTION_SEND.equals(action)) { // We only want to reuse the intent if it was photo send. // Or else default to the main activity. intent = new Intent(this, TwitterActivity.class); } //发送消息给widget Intent reflogin = new Intent(this.getBaseContext(), FanfouWidget.class); reflogin.setAction("android.appwidget.action.APPWIDGET_UPDATE"); PendingIntent l = PendingIntent.getBroadcast(this.getBaseContext(), 0, reflogin, PendingIntent.FLAG_UPDATE_CURRENT); try { l.send(); } catch (CanceledException e) { // TODO Auto-generated catch block e.printStackTrace(); } startActivity(intent); finish(); } private void onLoginFailure(String reason) { TaskFeedback.getInstance(TaskFeedback.DIALOG_MODE, LoginActivity.this).failed(reason); enableLogin(); } private class LoginTask extends GenericTask { private String msg = getString(R.string.login_status_failure); public String getMsg(){ return msg; } @Override protected TaskResult _doInBackground(TaskParams...params) { TaskParams param = params[0]; publishProgress(getString(R.string.login_status_logging_in) + "..."); try { String username = param.getString("username"); String password = param.getString("password"); user= TwitterApplication.mApi.login(username, password); } catch (HttpException e) { Log.e(TAG, e.getMessage(), e); //TODO:确切的应该从HttpException中返回的消息中获取错误信息 //Throwable cause = e.getCause(); // Maybe null // if (cause instanceof HttpAuthException) { if (e instanceof HttpAuthException) { // Invalid userName/password msg = getString(R.string.login_status_invalid_username_or_password); } else { msg = getString(R.string.login_status_network_or_connection_error); } publishProgress(msg); return TaskResult.FAILED; } SharedPreferences.Editor editor = mPreferences.edit(); editor.putString(Preferences.USERNAME_KEY, mUsername); editor.putString(Preferences.PASSWORD_KEY, EncryptUtils.encryptPassword(mPassword)); // add 存储当前用户的id editor.putString(Preferences.CURRENT_USER_ID, user.getId()); editor.commit(); return TaskResult.OK; } } private View.OnKeyListener enterKeyHandler = new View.OnKeyListener() { public boolean onKey(View v, int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_ENTER || keyCode == KeyEvent.KEYCODE_DPAD_CENTER) { if (event.getAction() == KeyEvent.ACTION_UP) { doLogin(); } return true; } return false; } }; }
Java
package com.ch_linghu.fanfoudroid.data; import com.ch_linghu.fanfoudroid.fanfou.DirectMessage; import com.ch_linghu.fanfoudroid.fanfou.User; import com.ch_linghu.fanfoudroid.util.*; public class Dm extends Message { @SuppressWarnings("unused") private static final String TAG = "Dm"; public boolean isSent; public static Dm create(DirectMessage directMessage, boolean isSent){ Dm dm = new Dm(); dm.id = directMessage.getId(); dm.text = directMessage.getText(); dm.createdAt = directMessage.getCreatedAt(); dm.isSent = isSent; User user = dm.isSent ? directMessage.getRecipient() : directMessage.getSender(); dm.screenName = TextHelper.getSimpleTweetText(user.getScreenName()); dm.userId = user.getId(); dm.profileImageUrl = user.getProfileImageURL().toString(); return dm; } }
Java
package com.ch_linghu.fanfoudroid.data; import java.util.Date; public class Message { public String id; public String screenName; public String text; public String profileImageUrl; public Date createdAt; public String userId; public String favorited; public String truncated; public String inReplyToStatusId; public String inReplyToUserId; public String inReplyToScreenName; public String thumbnail_pic; public String bmiddle_pic; public String original_pic; }
Java
package com.ch_linghu.fanfoudroid.data; import android.content.ContentValues; import android.database.Cursor; public interface BaseContent { long insert(); int delete(); int update(); Cursor select(); }
Java