code stringlengths 3 1.18M | language stringclasses 1
value |
|---|---|
package com.gs.montaditos;
import java.util.Random;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class RandomOrder extends Activity {
/** Called when the activity is first created. */
EditText personsField;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.random);
personsField = (EditText)findViewById(R.id.persons);
Button plus = (Button)findViewById(R.id.plus);
Button less = (Button)findViewById(R.id.less);
Button okay = (Button)findViewById(R.id.okay);
plus.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
int n = Integer.valueOf(personsField.getText().toString());
personsField.setText(String.valueOf(n+1));
}
});
less.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
int n = Integer.valueOf(personsField.getText().toString());
if(n>1){
personsField.setText(String.valueOf(n-1));
}
}
});
okay.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
Order.reset();
Montaditos.init(getApplicationContext());
Random randomGenerator = new Random();
int n = Integer.valueOf(personsField.getText().toString());
for (int idx = 1; idx <= n; ++idx){
int randomInt = randomGenerator.nextInt(100);
Order.add(randomInt);
}
startActivity(new Intent(getApplicationContext(), ListOrder.class));
Toast.makeText(getApplicationContext(), "Order Done", Toast.LENGTH_LONG).show();
}
});
}
}
| Java |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.heightmapprofiler;
import java.io.IOException;
import java.io.InputStream;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.opengles.GL10;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.opengl.GLSurfaceView;
import android.opengl.GLU;
import android.opengl.GLUtils;
import android.util.Log;
/**
* An OpenGL ES renderer based on the GLSurfaceView rendering framework. This
* class is responsible for drawing a list of renderables to the screen every
* frame. It also manages loading of textures and (when VBOs are used) the
* allocation of vertex buffer objects.
*/
public class SimpleGLRenderer implements GLSurfaceView.Renderer {
// Texture filtering modes.
public final static int FILTER_NEAREST_NEIGHBOR = 0;
public final static int FILTER_BILINEAR = 1;
public final static int FILTER_TRILINEAR = 2;
// Specifies the format our textures should be converted to upon load.
private static BitmapFactory.Options sBitmapOptions
= new BitmapFactory.Options();
// Pre-allocated arrays to use at runtime so that allocation during the
// test can be avoided.
private int[] mTextureNameWorkspace;
// A reference to the application context.
private Context mContext;
private LandTileMap mTiles;
private int mTextureResource;
private int mTextureResource2;
private int mTextureId2;
private Vector3 mCameraPosition = new Vector3();
private Vector3 mLookAtPosition = new Vector3();
private Object mCameraLock = new Object();
private boolean mCameraDirty;
private NativeRenderer mNativeRenderer;
// Determines the use of vertex buffer objects.
private boolean mUseHardwareBuffers;
private boolean mUseTextureLods = false;
private boolean mUseHardwareMips = false;
boolean mColorTextureLods = false;
private int mTextureFilter = FILTER_BILINEAR;
private int mMaxTextureSize = 0;
public SimpleGLRenderer(Context context) {
// Pre-allocate and store these objects so we can use them at runtime
// without allocating memory mid-frame.
mTextureNameWorkspace = new int[1];
// Set our bitmaps to 16-bit, 565 format.
sBitmapOptions.inPreferredConfig = Bitmap.Config.RGB_565;
mContext = context;
mUseHardwareBuffers = true;
}
public void setTiles(LandTileMap tiles, int textureResource, int textureResource2) {
mTextureResource = textureResource;
mTextureResource2 = textureResource2;
mTiles = tiles;
}
/** Draws the landscape. */
public void onDrawFrame(GL10 gl) {
ProfileRecorder.sSingleton.stop(ProfileRecorder.PROFILE_FRAME);
ProfileRecorder.sSingleton.start(ProfileRecorder.PROFILE_FRAME);
if (mTiles != null) {
// Clear the screen. Note that a real application probably would only clear the depth buffer
// (or maybe not even that).
if (mNativeRenderer == null) {
gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
}
// If the camera has moved since the last frame, rebuild our projection matrix.
if (mCameraDirty){
synchronized (mCameraLock) {
if (mNativeRenderer != null) {
mNativeRenderer.setCamera(mCameraPosition, mLookAtPosition);
} else {
gl.glMatrixMode(GL10.GL_MODELVIEW);
gl.glLoadIdentity();
GLU.gluLookAt(gl, mCameraPosition.x, mCameraPosition.y, mCameraPosition.z,
mLookAtPosition.x, mLookAtPosition.y, mLookAtPosition.z,
0.0f, 1.0f, 0.0f);
}
mCameraDirty = false;
}
}
ProfileRecorder.sSingleton.start(ProfileRecorder.PROFILE_DRAW);
// Draw the landscape.
mTiles.draw(gl, mCameraPosition);
ProfileRecorder.sSingleton.stop(ProfileRecorder.PROFILE_DRAW);
}
ProfileRecorder.sSingleton.endFrame();
}
/* Called when the size of the window changes. */
public void onSurfaceChanged(GL10 gl, int width, int height) {
gl.glViewport(0, 0, width, height);
/*
* Set our projection matrix. This doesn't have to be done each time we
* draw, but usually a new projection needs to be set when the viewport
* is resized.
*/
float ratio = (float)width / height;
gl.glMatrixMode(GL10.GL_PROJECTION);
gl.glLoadIdentity();
GLU.gluPerspective(gl, 60.0f, ratio, 2.0f, 3000.0f);
mCameraDirty = true;
}
public void setCameraPosition(float x, float y, float z) {
synchronized (mCameraLock) {
mCameraPosition.set(x, y, z);
mCameraDirty = true;
}
}
public void setCameraLookAtPosition(float x, float y, float z) {
synchronized (mCameraLock) {
mLookAtPosition.set(x, y, z);
mCameraDirty = true;
}
}
public void setUseHardwareBuffers(boolean vbos) {
mUseHardwareBuffers = vbos;
}
/**
* Called to turn on Levels of Detail option for rendering textures
*
* @param mUseTextureLods
*/
public void setUseTextureLods(boolean useTextureLods, boolean useHardwareMips) {
mUseTextureLods = useTextureLods;
mUseHardwareMips = useHardwareMips;
}
/**
* Turns on/off color the LOD bitmap textures based on their distance from view.
* This feature is useful since it helps visualize the LOD being used while viewing the scene.
*
* @param colorTextureLods
*/
public void setColorTextureLods(boolean colorTextureLods) {
this.mColorTextureLods = colorTextureLods;
}
public void setNativeRenderer(NativeRenderer render) {
mNativeRenderer = render;
}
public void setMaxTextureSize(int maxTextureSize) {
mMaxTextureSize = maxTextureSize;
}
public void setTextureFilter(int filter) {
mTextureFilter = filter;
}
/**
* Called whenever the surface is created. This happens at startup, and
* may be called again at runtime if the device context is lost (the screen
* goes to sleep, etc). This function must fill the contents of vram with
* texture data and (when using VBOs) hardware vertex arrays.
*/
public void onSurfaceCreated(GL10 gl, EGLConfig config) {
int[] textureNames = null;
/*
* Some one-time OpenGL initialization can be made here probably based
* on features of this particular context
*/
gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_FASTEST);
gl.glClearColor(0.5f, 0.5f, 0.5f, 1);
gl.glDisable(GL10.GL_DITHER);
gl.glDisable(GL10.GL_CULL_FACE);
gl.glShadeModel(GL10.GL_SMOOTH);
gl.glEnable(GL10.GL_DEPTH_TEST);
gl.glEnable(GL10.GL_TEXTURE_2D);
// set up some fog.
gl.glEnable(GL10.GL_FOG);
gl.glFogf(GL10.GL_FOG_MODE, GL10.GL_LINEAR);
float fogColor[] = { 0.5f, 0.5f, 0.5f, 1.0f };
gl.glFogfv(GL10.GL_FOG_COLOR, fogColor, 0);
gl.glFogf(GL10.GL_FOG_DENSITY, 0.15f);
gl.glFogf(GL10.GL_FOG_START, 800.0f);
gl.glFogf(GL10.GL_FOG_END, 2048.0f);
gl.glHint(GL10.GL_FOG_HINT, GL10.GL_FASTEST);
gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
// load textures and buffers here
if (mUseHardwareBuffers && mTiles != null) {
mTiles.generateHardwareBuffers(gl);
}
if (mTextureResource != 0) {
textureNames = loadBitmap( mContext, gl, mTextureResource, mUseTextureLods, mUseHardwareMips );
}
if (mTextureResource2 != 0) {
mTextureId2 = loadBitmap(mContext, gl, mTextureResource2);
}
mTiles.setTextures(textureNames, mTextureId2);
}
/**
* Loads a bitmap into OpenGL and sets up the common parameters for
* 2D texture maps.
*/
protected int loadBitmap(Context context, GL10 gl, int resourceId) {
int textureName = -1;
InputStream is = context.getResources().openRawResource(resourceId);
Bitmap bitmap;
try {
bitmap = BitmapFactory.decodeStream(is, null, sBitmapOptions);
} finally {
try {
is.close();
} catch (IOException e) {
// Ignore.
}
}
if (mMaxTextureSize > 0 && Math.max(bitmap.getWidth(), bitmap.getHeight()) != mMaxTextureSize) {
// we're assuming all our textures are square. sue me.
Bitmap tempBitmap = Bitmap.createScaledBitmap( bitmap, mMaxTextureSize, mMaxTextureSize, false );
bitmap.recycle();
bitmap = tempBitmap;
}
textureName = loadBitmapIntoOpenGL(context, gl, bitmap, false);
bitmap.recycle();
return textureName;
}
/**
* Loads a bitmap into OpenGL and sets up the common parameters for
* 2D texture maps.
*
* @param context
* @param resourceId
* @param numLevelsOfDetail number of detail textures to generate
*
* @return a array of OpenGL texture names corresponding to the different levels of detail textures
*/
protected int[] loadBitmap(Context context, GL10 gl, int resourceId, boolean generateMips, boolean useHardwareMips ) {
InputStream is = context.getResources().openRawResource(resourceId);
Bitmap bitmap;
try {
bitmap = BitmapFactory.decodeStream(is, null, sBitmapOptions);
} finally {
try {
is.close();
} catch (IOException e) {
// Ignore.
}
}
if (mMaxTextureSize > 0 && Math.max(bitmap.getWidth(), bitmap.getHeight()) != mMaxTextureSize) {
// we're assuming all our textures are square. sue me.
Bitmap tempBitmap = Bitmap.createScaledBitmap( bitmap, mMaxTextureSize, mMaxTextureSize, false );
bitmap.recycle();
bitmap = tempBitmap;
}
final int minSide = Math.min(bitmap.getWidth(), bitmap.getHeight());
int numLevelsOfDetail = 1;
if (generateMips) {
for (int side = minSide / 2; side > 0; side /= 2) {
numLevelsOfDetail++;
}
}
int textureNames[];
if (generateMips && !useHardwareMips) {
textureNames = new int[numLevelsOfDetail];
} else {
textureNames = new int[1];
}
textureNames[0] = loadBitmapIntoOpenGL(context, gl, bitmap, useHardwareMips);
// Scale down base bitmap by powers of two to create lower resolution textures
for( int i = 1; i < numLevelsOfDetail; ++i ) {
int scale = (int)Math.pow(2, i);
int dstWidth = bitmap.getWidth() / scale;
int dstHeight = bitmap.getHeight() / scale;
Bitmap tempBitmap = Bitmap.createScaledBitmap( bitmap, dstWidth, dstHeight, false );
// Set each LOD level to a different color to help visualization
if( mColorTextureLods ) {
int color = 0;
switch( (int)(i % 4) ) {
case 1:
color = Color.RED;
break;
case 2:
color = Color.YELLOW;
break;
case 3:
color = Color.BLUE;
break;
}
tempBitmap.eraseColor( color );
}
if (!useHardwareMips) {
textureNames[i] = loadBitmapIntoOpenGL( context, gl, tempBitmap, false);
} else {
addHardwareMipmap(gl, textureNames[0], tempBitmap, i );
}
tempBitmap.recycle();
}
bitmap.recycle();
return textureNames;
}
protected void addHardwareMipmap(GL10 gl, int textureName, Bitmap bitmap, int level) {
gl.glBindTexture(GL10.GL_TEXTURE_2D, textureName);
GLUtils.texImage2D(GL10.GL_TEXTURE_2D, level, bitmap, 0);
}
/**
* Loads a bitmap into OpenGL and sets up the common parameters for
* 2D texture maps.
*
* @return OpenGL texture entry id
*/
protected int loadBitmapIntoOpenGL(Context context, GL10 gl, Bitmap bitmap, boolean useMipmaps) {
int textureName = -1;
if (context != null && gl != null) {
gl.glGenTextures(1, mTextureNameWorkspace, 0);
textureName = mTextureNameWorkspace[0];
gl.glBindTexture(GL10.GL_TEXTURE_2D, textureName);
if (useMipmaps) {
if (mTextureFilter == FILTER_TRILINEAR) {
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_LINEAR_MIPMAP_LINEAR);
} else {
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_LINEAR_MIPMAP_NEAREST);
}
} else {
if (mTextureFilter == FILTER_NEAREST_NEIGHBOR) {
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST);
} else {
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_LINEAR);
}
}
if (mTextureFilter == FILTER_NEAREST_NEIGHBOR) {
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_NEAREST);
} else {
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR);
}
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_CLAMP_TO_EDGE);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_CLAMP_TO_EDGE);
gl.glTexEnvf(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE, GL10.GL_MODULATE);
GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0);
int error = gl.glGetError();
if (error != GL10.GL_NO_ERROR) {
Log.e("SimpleGLRenderer", "Texture Load GLError: " + error);
}
}
return textureName;
}
}
| Java |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.heightmapprofiler;
import android.os.SystemClock;
// Very simple game runtime. Implements basic movement and collision detection with the landscape.
public class Game implements Runnable {
private Vector3 mCameraPosition = new Vector3(100.0f, 128.0f, 400.0f);
private Vector3 mTargetPosition = new Vector3(350.0f, 128.0f, 650.0f);
private Vector3 mWorkVector = new Vector3();
private float mCameraXZAngle;
private float mCameraYAngle;
private float mCameraLookAtDistance = (float)Math.sqrt(mTargetPosition.distance2(mCameraPosition));
private boolean mCameraDirty = true;
private boolean mRunning = true;
private boolean mPaused = false;
private Object mPauseLock = new Object();
private LandTileMap mTileMap;
private final static float CAMERA_ORBIT_SPEED = 0.3f;
private final static float CAMERA_MOVE_SPEED = 5.0f;
private final static float VIEWER_HEIGHT = 15.0f;
private SimpleGLRenderer mSimpleRenderer;
public Game(SimpleGLRenderer renderer, LandTileMap tiles) {
mSimpleRenderer = renderer;
mTileMap = tiles;
}
public void run() {
while (mRunning) {
ProfileRecorder.sSingleton.start(ProfileRecorder.PROFILE_SIM);
long startTime = SystemClock.uptimeMillis();
if (mCameraDirty) {
// snap the camera to the floor
float height = mTileMap.getHeight(mCameraPosition.x, mCameraPosition.z);
mCameraPosition.y = height + VIEWER_HEIGHT;
updateCamera();
}
long endTime = SystemClock.uptimeMillis();
ProfileRecorder.sSingleton.stop(ProfileRecorder.PROFILE_SIM);
if (endTime - startTime < 16) {
// we're running too fast! sleep for a bit to let the render thread do some work.
try {
Thread.sleep(16 - (endTime - startTime));
} catch (InterruptedException e) {
// Interruptions are not a big deal here.
}
}
synchronized(mPauseLock) {
if (mPaused) {
while (mPaused) {
try {
mPauseLock.wait();
} catch (InterruptedException e) {
// OK if this is interrupted.
}
}
}
}
}
}
synchronized private void updateCamera() {
mWorkVector.set((float)Math.cos(mCameraXZAngle), (float)Math.sin(mCameraYAngle), (float)Math.sin(mCameraXZAngle));
mWorkVector.multiply(mCameraLookAtDistance);
mWorkVector.add(mCameraPosition);
mTargetPosition.set(mWorkVector);
mSimpleRenderer.setCameraPosition(mCameraPosition.x, mCameraPosition.y, mCameraPosition.z);
mSimpleRenderer.setCameraLookAtPosition(mTargetPosition.x, mTargetPosition.y, mTargetPosition.z);
mCameraDirty = false;
}
synchronized public void rotate(float x, float y) {
if (x != 0.0f) {
mCameraXZAngle += x * CAMERA_ORBIT_SPEED;
mCameraDirty = true;
}
if (y != 0.0f) {
mCameraYAngle += y * CAMERA_ORBIT_SPEED;
mCameraDirty = true;
}
}
synchronized public void move(float amount) {
mWorkVector.set(mTargetPosition);
mWorkVector.subtract(mCameraPosition);
mWorkVector.normalize();
mWorkVector.multiply(amount * CAMERA_MOVE_SPEED);
mCameraPosition.add(mWorkVector);
mTargetPosition.add(mWorkVector);
mCameraDirty = true;
}
public void pause() {
synchronized(mPauseLock) {
mPaused = true;
}
}
public void resume() {
synchronized(mPauseLock) {
mPaused = false;
mPauseLock.notifyAll();
}
}
}
| Java |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.heightmapprofiler;
import android.opengl.GLSurfaceView;
import com.android.heightmapprofiler.SimpleGLRenderer;
import com.android.heightmapprofiler.R;
import android.app.Activity;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.KeyEvent;
import android.view.MotionEvent;
// The main entry point for the actual landscape rendering test.
// This class pulls options from the preferences set in the MainMenu
// activity and builds the landscape accordingly.
public class HeightMapTest extends Activity {
private GLSurfaceView mGLSurfaceView;
private SimpleGLRenderer mSimpleRenderer;
private Game mGame;
private Thread mGameThread;
private float mLastScreenX;
private float mLastScreenY;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mGLSurfaceView = new GLSurfaceView(this);
mGLSurfaceView.setEGLConfigChooser(true);
mSimpleRenderer = new SimpleGLRenderer(this);
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
final boolean runGame = prefs.getBoolean("runsim", true);
final boolean bigWorld = prefs.getBoolean("bigworld", true);
final boolean skybox = prefs.getBoolean("skybox", true);
final boolean texture = prefs.getBoolean("texture", true);
final boolean vertexColors = prefs.getBoolean("colors", true);
final boolean useTextureLods = prefs.getBoolean("lodTexture", true);
final boolean textureMips = prefs.getBoolean("textureMips", true);
final boolean useColorTextureLods = prefs.getBoolean("lodTextureColored", false );
final int maxTextureSize = Integer.parseInt(prefs.getString("maxTextureSize", "512"));
final String textureFilter = prefs.getString("textureFiltering", "bilinear");
final boolean useLods = prefs.getBoolean("lod", true);
final int complexity = Integer.parseInt(prefs.getString("complexity", "24"));
final boolean useFixedPoint = prefs.getBoolean("fixed", false);
final boolean useVbos = prefs.getBoolean("vbo", true);
final boolean useNdk = prefs.getBoolean("ndk", false);
BitmapDrawable heightMapDrawable = (BitmapDrawable)getResources().getDrawable(R.drawable.heightmap);
Bitmap heightmap = heightMapDrawable.getBitmap();
Bitmap lightmap = null;
if (vertexColors != false) {
BitmapDrawable lightMapDrawable = (BitmapDrawable)getResources().getDrawable(R.drawable.lightmap);
lightmap = lightMapDrawable.getBitmap();
}
LandTileMap tileMap = null;
if (bigWorld) {
final int tilesX = 4;
final int tilesY = 4;
tileMap = new LandTileMap(tilesX, tilesY, heightmap, lightmap, vertexColors, texture, useLods, complexity, useFixedPoint);
} else {
tileMap = new LandTileMap(1, 1, heightmap, lightmap, vertexColors, texture, useLods, complexity, useFixedPoint);
}
if (skybox) {
BitmapDrawable skyboxDrawable = (BitmapDrawable)getResources().getDrawable(R.drawable.skybox);
Bitmap skyboxBitmap = skyboxDrawable.getBitmap();
tileMap.setupSkybox(skyboxBitmap, useFixedPoint);
}
if (useNdk) {
NativeRenderer renderer = new NativeRenderer();
tileMap.setNativeRenderer(renderer);
mSimpleRenderer.setNativeRenderer(renderer);
}
ProfileRecorder.sSingleton.resetAll();
mSimpleRenderer.setUseHardwareBuffers(useVbos);
if (texture) {
mSimpleRenderer.setTiles(tileMap, R.drawable.road_texture, R.drawable.skybox_texture);
mSimpleRenderer.setUseTextureLods( useTextureLods, textureMips );
mSimpleRenderer.setColorTextureLods( useColorTextureLods );
mSimpleRenderer.setMaxTextureSize(maxTextureSize);
if (textureFilter == "nearest") {
mSimpleRenderer.setTextureFilter(SimpleGLRenderer.FILTER_NEAREST_NEIGHBOR);
} else if (textureFilter == "trilinear") {
mSimpleRenderer.setTextureFilter(SimpleGLRenderer.FILTER_TRILINEAR);
} else {
mSimpleRenderer.setTextureFilter(SimpleGLRenderer.FILTER_BILINEAR);
}
} else {
mSimpleRenderer.setTiles(tileMap, 0, 0);
}
mGLSurfaceView.setRenderer(mSimpleRenderer);
setContentView(mGLSurfaceView);
if (runGame) {
mGame = new Game(mSimpleRenderer, tileMap);
mGameThread = new Thread(mGame);
mGameThread.start();
}
}
@Override
protected void onPause() {
super.onPause();
mGLSurfaceView.onPause();
if (mGame != null) {
mGame.pause();
}
}
@Override
protected void onResume() {
super.onResume();
mGLSurfaceView.onResume();
if (mGame != null) {
mGame.resume();
}
}
@Override
public boolean onTrackballEvent(MotionEvent event) {
if (mGame != null) {
mGame.rotate(event.getRawX(), -event.getRawY());
}
return true;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (mGame != null) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
mGame.move(1.0f);
} else if (event.getAction() == MotionEvent.ACTION_MOVE) {
float xDelta = event.getX() - mLastScreenX;
float yDelta = event.getY() - mLastScreenY;
mGame.move(1.0f);
// Scale the values we got down to make control usable.
// A real game would probably figure out scale factors based
// on the size of the screen rather than hard-coded constants
// like this.
mGame.rotate(xDelta * 0.01f, -yDelta * 0.005f);
}
}
mLastScreenX = event.getX();
mLastScreenY = event.getY();
try {
Thread.sleep(16);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
}
return true;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (mGame != null) {
final float speed = 1.0f;
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_DOWN:
mGame.rotate(0.0f, -speed);
return true;
case KeyEvent.KEYCODE_DPAD_LEFT:
mGame.rotate(-speed, 0.0f);
return true;
case KeyEvent.KEYCODE_DPAD_RIGHT:
mGame.rotate(speed, 0.0f);
return true;
case KeyEvent.KEYCODE_DPAD_UP:
mGame.rotate(0.0f, speed);
return true;
}
}
return super.onKeyDown(keyCode, event);
}
} | Java |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.heightmapprofiler;
import com.android.heightmapprofiler.R;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceActivity;
/**
* Main entry point for the HeightMapTest application.
*/
public class MainMenu extends PreferenceActivity implements Preference.OnPreferenceClickListener {
private static final int ACTIVITY_TEST = 0;
private static final int RESULTS_DIALOG = 0;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.preferences);
Preference runTestButton = getPreferenceManager().findPreference("runtest");
if (runTestButton != null) {
runTestButton.setOnPreferenceClickListener(this);
}
}
/** Creates the test results dialog and fills in a dummy message. */
@Override
protected Dialog onCreateDialog(int id) {
Dialog dialog = null;
if (id == RESULTS_DIALOG) {
String dummy = "No results yet.";
CharSequence sequence = dummy.subSequence(0, dummy.length() -1);
dialog = new AlertDialog.Builder(this)
.setTitle(R.string.dialog_title)
.setPositiveButton(R.string.dialog_ok, null)
.setMessage(sequence)
.create();
}
return dialog;
}
/**
* Replaces the dummy message in the test results dialog with a string that
* describes the actual test results.
*/
protected void onPrepareDialog (int id, Dialog dialog) {
if (id == RESULTS_DIALOG) {
// Extract final timing information from the profiler.
final ProfileRecorder profiler = ProfileRecorder.sSingleton;
final long frameVerts = profiler.getAverageVerts();
final long frameTime =
profiler.getAverageTime(ProfileRecorder.PROFILE_FRAME);
final long frameMin =
profiler.getMinTime(ProfileRecorder.PROFILE_FRAME);
final long frameMax =
profiler.getMaxTime(ProfileRecorder.PROFILE_FRAME);
final long drawTime =
profiler.getAverageTime(ProfileRecorder.PROFILE_DRAW);
final long drawMin =
profiler.getMinTime(ProfileRecorder.PROFILE_DRAW);
final long drawMax =
profiler.getMaxTime(ProfileRecorder.PROFILE_DRAW);
final long simTime =
profiler.getAverageTime(ProfileRecorder.PROFILE_SIM);
final long simMin =
profiler.getMinTime(ProfileRecorder.PROFILE_SIM);
final long simMax =
profiler.getMaxTime(ProfileRecorder.PROFILE_SIM);
final float fps = frameTime > 0 ? 1000.0f / frameTime : 0.0f;
String result = "Frame: " + frameTime + "ms (" + fps + " fps)\n"
+ "\t\tMin: " + frameMin + "ms\t\tMax: " + frameMax + "\n"
+ "Draw: " + drawTime + "ms\n"
+ "\t\tMin: " + drawMin + "ms\t\tMax: " + drawMax + "\n"
+ "Sim: " + simTime + "ms\n"
+ "\t\tMin: " + simMin + "ms\t\tMax: " + simMax + "\n"
+ "\nVerts per frame: ~" + frameVerts + "\n";
CharSequence sequence = result.subSequence(0, result.length() -1);
AlertDialog alertDialog = (AlertDialog)dialog;
alertDialog.setMessage(sequence);
}
}
/** Shows the results dialog when the test activity closes. */
@Override
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
showDialog(RESULTS_DIALOG);
}
public boolean onPreferenceClick(Preference preference) {
Intent i = new Intent(this, HeightMapTest.class);
startActivityForResult(i, ACTIVITY_TEST);
return true;
}
} | Java |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.heightmapprofiler;
import android.os.SystemClock;
/**
* Implements a simple runtime profiler. The profiler records start and stop
* times for several different types of profiles and can then return min, max
* and average execution times per type. Profile types are independent and may
* be nested in calling code. This object is a singleton for convenience.
*/
public class ProfileRecorder {
// A type for recording actual draw command time.
public static final int PROFILE_DRAW = 0;
// A type for recording the time it takes to run a single simulation step.
public static final int PROFILE_SIM = 2;
// A type for recording the total amount of time spent rendering a frame.
public static final int PROFILE_FRAME = 3;
private static final int PROFILE_COUNT = PROFILE_FRAME + 1;
private ProfileRecord[] mProfiles;
private int mFrameCount;
private long mVertexCount;
public static ProfileRecorder sSingleton = new ProfileRecorder();
public ProfileRecorder() {
mProfiles = new ProfileRecord[PROFILE_COUNT];
for (int x = 0; x < PROFILE_COUNT; x++) {
mProfiles[x] = new ProfileRecord();
}
}
/** Starts recording execution time for a specific profile type.*/
public final void start(int profileType) {
if (profileType < PROFILE_COUNT) {
mProfiles[profileType].start(SystemClock.uptimeMillis());
}
}
/** Stops recording time for this profile type. */
public final void stop(int profileType) {
if (profileType < PROFILE_COUNT) {
mProfiles[profileType].stop(SystemClock.uptimeMillis());
}
}
/** Indicates the end of the frame.*/
public final void endFrame() {
mFrameCount++;
}
/* Flushes all recorded timings from the profiler. */
public final void resetAll() {
for (int x = 0; x < PROFILE_COUNT; x++) {
mProfiles[x].reset();
}
mFrameCount = 0;
mVertexCount = 0L;
}
/* Returns the average execution time, in milliseconds, for a given type. */
public long getAverageTime(int profileType) {
long time = 0;
if (profileType < PROFILE_COUNT) {
time = mProfiles[profileType].getAverageTime(mFrameCount);
}
return time;
}
/* Returns the minimum execution time in milliseconds for a given type. */
public long getMinTime(int profileType) {
long time = 0;
if (profileType < PROFILE_COUNT) {
time = mProfiles[profileType].getMinTime();
}
return time;
}
/* Returns the maximum execution time in milliseconds for a given type. */
public long getMaxTime(int profileType) {
long time = 0;
if (profileType < PROFILE_COUNT) {
time = mProfiles[profileType].getMaxTime();
}
return time;
}
public long getTotalVerts() {
return mVertexCount;
}
public long getAverageVerts() {
return mVertexCount / mFrameCount;
}
public void addVerts(long vertCount) {
mVertexCount += vertCount;
}
/**
* A simple class for storing timing information about a single profile
* type.
*/
protected class ProfileRecord {
private long mStartTime;
private long mTotalTime;
private long mMinTime;
private long mMaxTime;
public void start(long time) {
mStartTime = time;
}
public void stop(long time) {
if (mStartTime > 0) {
final long timeDelta = time - mStartTime;
mTotalTime += timeDelta;
if (mMinTime == 0 || timeDelta < mMinTime) {
mMinTime = timeDelta;
}
if (mMaxTime == 0 || timeDelta > mMaxTime) {
mMaxTime = timeDelta;
}
}
}
public long getAverageTime(int frameCount) {
long time = frameCount > 0 ? mTotalTime / frameCount : 0;
return time;
}
public long getMinTime() {
return mMinTime;
}
public long getMaxTime() {
return mMaxTime;
}
public void startNewProfilePeriod() {
mTotalTime = 0;
}
public void reset() {
mTotalTime = 0;
mStartTime = 0;
mMinTime = 0;
mMaxTime = 0;
}
}
}
| Java |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.heightmapprofiler;
import android.graphics.Bitmap;
import android.graphics.Color;
// This class generates vertex arrays based on grayscale images.
// It defines 1.0 (white) as the tallest point and 0.0 (black) as the lowest point,
// and builds a mesh that represents that topology.
public class HeightMapMeshMaker {
public static final Grid makeGrid(Bitmap drawable, Bitmap lightmap, int subdivisions, float width, float height, float scale, boolean fixedPoint) {
Grid grid = null;
final float subdivisionRange = subdivisions - 1;
final float vertexSizeX = width / subdivisionRange;
final float vertexSizeZ = height / subdivisionRange;
if (drawable != null) {
grid = new Grid(subdivisions, subdivisions, fixedPoint);
final float heightMapScaleX = drawable.getWidth() / subdivisionRange;
final float heightMapScaleY = drawable.getHeight() / subdivisionRange;
final float lightMapScaleX = lightmap != null ? lightmap.getWidth() / subdivisions : 0.0f;
final float lightMapScaleY = lightmap != null ? lightmap.getHeight() / subdivisions : 0.0f;
final float[] vertexColor = { 1.0f, 1.0f, 1.0f, 1.0f };
for (int i = 0; i < subdivisions; i++) {
final float u = (float)(i + 1) / subdivisions;
for (int j = 0; j < subdivisions; j++) {
final float v = (float)(j + 1) / subdivisions;
final float vertexHeight = getBilinearFilteredHeight(drawable, (heightMapScaleX * i), (heightMapScaleY * j), scale);
if (lightmap != null) {
final int lightColor = lightmap.getPixel((int)(lightMapScaleX * i), (int)(lightMapScaleY * j));
final float colorScale = 1.0f / 255.0f;
vertexColor[0] = colorScale * Color.red(lightColor);
vertexColor[1] = colorScale * Color.green(lightColor);
vertexColor[2] = colorScale * Color.blue(lightColor);
vertexColor[3] = colorScale * Color.alpha(lightColor);
}
grid.set(i, j, i * vertexSizeX, vertexHeight, j * vertexSizeZ, u, v, vertexColor);
}
}
}
return grid;
}
// In order to get a smooth gradation between pixels from a low-resolution height map,
// this function uses a bilinear filter to calculate a weighted average of four pixels
// surrounding the requested point.
public static final float getBilinearFilteredHeight(Bitmap drawable, float x, float y, float scale) {
final int topLeftPixelX = clamp((int)Math.floor(x), 0, drawable.getWidth() - 1);
final int topLeftPixelY = clamp((int)Math.floor(y), 0, drawable.getHeight() - 1);
final int bottomRightPixelX = clamp((int)Math.ceil(x), 0, drawable.getWidth() - 1);
final int bottomRightPixelY = clamp((int)Math.ceil(y), 0, drawable.getHeight() - 1);
final float topLeftWeightX = x - topLeftPixelX;
final float topLeftWeightY = y - topLeftPixelY;
final float bottomRightWeightX = 1.0f - topLeftWeightX;
final float bottomRightWeightY = 1.0f - topLeftWeightY;
final int topLeft = drawable.getPixel(topLeftPixelX, topLeftPixelY);
final int topRight = drawable.getPixel(bottomRightPixelX, topLeftPixelY);
final int bottomLeft = drawable.getPixel(topLeftPixelX, bottomRightPixelY);
final int bottomRight = drawable.getPixel(bottomRightPixelX, bottomRightPixelY);
final float red1 = bottomRightWeightX * Color.red(topLeft) + topLeftWeightX * Color.red(topRight);
final float red2 = bottomRightWeightX * Color.red(bottomLeft) + topLeftWeightX * Color.red(bottomRight);
final float red = bottomRightWeightY * red1 + topLeftWeightY * red2;
final float height = red * scale;
return height;
}
private static final int clamp(int value, int min, int max) {
return value < min ? min : (value > max ? max : value);
}
}
| Java |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.heightmapprofiler;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.CharBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import javax.microedition.khronos.opengles.GL10;
import javax.microedition.khronos.opengles.GL11;
/**
* A 2D rectangular mesh. Can be drawn textured or untextured.
* This version is modified from the original Grid.java (found in
* the SpriteText package in the APIDemos Android sample) to support hardware
* vertex buffers.
*/
class Grid {
private FloatBuffer mFloatVertexBuffer;
private FloatBuffer mFloatTexCoordBuffer;
private FloatBuffer mFloatColorBuffer;
private IntBuffer mFixedVertexBuffer;
private IntBuffer mFixedTexCoordBuffer;
private IntBuffer mFixedColorBuffer;
private CharBuffer mIndexBuffer;
private Buffer mVertexBuffer;
private Buffer mTexCoordBuffer;
private Buffer mColorBuffer;
private int mCoordinateSize;
private int mCoordinateType;
private int mW;
private int mH;
private int mIndexCount;
private boolean mUseHardwareBuffers;
private int mVertBufferIndex;
private int mIndexBufferIndex;
private int mTextureCoordBufferIndex;
private int mColorBufferIndex;
public Grid(int vertsAcross, int vertsDown, boolean useFixedPoint) {
if (vertsAcross < 0 || vertsAcross >= 65536) {
throw new IllegalArgumentException("vertsAcross");
}
if (vertsDown < 0 || vertsDown >= 65536) {
throw new IllegalArgumentException("vertsDown");
}
if (vertsAcross * vertsDown >= 65536) {
throw new IllegalArgumentException("vertsAcross * vertsDown >= 65536");
}
mUseHardwareBuffers = false;
mW = vertsAcross;
mH = vertsDown;
int size = vertsAcross * vertsDown;
final int FLOAT_SIZE = 4;
final int FIXED_SIZE = 4;
final int CHAR_SIZE = 2;
if (useFixedPoint) {
mFixedVertexBuffer = ByteBuffer.allocateDirect(FIXED_SIZE * size * 3)
.order(ByteOrder.nativeOrder()).asIntBuffer();
mFixedTexCoordBuffer = ByteBuffer.allocateDirect(FIXED_SIZE * size * 2)
.order(ByteOrder.nativeOrder()).asIntBuffer();
mFixedColorBuffer = ByteBuffer.allocateDirect(FIXED_SIZE * size * 4)
.order(ByteOrder.nativeOrder()).asIntBuffer();
mVertexBuffer = mFixedVertexBuffer;
mTexCoordBuffer = mFixedTexCoordBuffer;
mColorBuffer = mFixedColorBuffer;
mCoordinateSize = FIXED_SIZE;
mCoordinateType = GL10.GL_FIXED;
} else {
mFloatVertexBuffer = ByteBuffer.allocateDirect(FLOAT_SIZE * size * 3)
.order(ByteOrder.nativeOrder()).asFloatBuffer();
mFloatTexCoordBuffer = ByteBuffer.allocateDirect(FLOAT_SIZE * size * 2)
.order(ByteOrder.nativeOrder()).asFloatBuffer();
mFloatColorBuffer = ByteBuffer.allocateDirect(FLOAT_SIZE * size * 4)
.order(ByteOrder.nativeOrder()).asFloatBuffer();
mVertexBuffer = mFloatVertexBuffer;
mTexCoordBuffer = mFloatTexCoordBuffer;
mColorBuffer = mFloatColorBuffer;
mCoordinateSize = FLOAT_SIZE;
mCoordinateType = GL10.GL_FLOAT;
}
int quadW = mW - 1;
int quadH = mH - 1;
int quadCount = quadW * quadH;
int indexCount = quadCount * 6;
mIndexCount = indexCount;
mIndexBuffer = ByteBuffer.allocateDirect(CHAR_SIZE * indexCount)
.order(ByteOrder.nativeOrder()).asCharBuffer();
/*
* Initialize triangle list mesh.
*
* [0]-----[ 1] ...
* | / |
* | / |
* | / |
* [w]-----[w+1] ...
* | |
*
*/
{
int i = 0;
for (int y = 0; y < quadH; y++) {
for (int x = 0; x < quadW; x++) {
char a = (char) (y * mW + x);
char b = (char) (y * mW + x + 1);
char c = (char) ((y + 1) * mW + x);
char d = (char) ((y + 1) * mW + x + 1);
mIndexBuffer.put(i++, a);
mIndexBuffer.put(i++, b);
mIndexBuffer.put(i++, c);
mIndexBuffer.put(i++, b);
mIndexBuffer.put(i++, c);
mIndexBuffer.put(i++, d);
}
}
}
mVertBufferIndex = 0;
}
void set(int i, int j, float x, float y, float z, float u, float v, float[] color) {
if (i < 0 || i >= mW) {
throw new IllegalArgumentException("i");
}
if (j < 0 || j >= mH) {
throw new IllegalArgumentException("j");
}
final int index = mW * j + i;
final int posIndex = index * 3;
final int texIndex = index * 2;
final int colorIndex = index * 4;
if (mCoordinateType == GL10.GL_FLOAT) {
mFloatVertexBuffer.put(posIndex, x);
mFloatVertexBuffer.put(posIndex + 1, y);
mFloatVertexBuffer.put(posIndex + 2, z);
mFloatTexCoordBuffer.put(texIndex, u);
mFloatTexCoordBuffer.put(texIndex + 1, v);
if (color != null) {
mFloatColorBuffer.put(colorIndex, color[0]);
mFloatColorBuffer.put(colorIndex + 1, color[1]);
mFloatColorBuffer.put(colorIndex + 2, color[2]);
mFloatColorBuffer.put(colorIndex + 3, color[3]);
}
} else {
mFixedVertexBuffer.put(posIndex, (int)(x * (1 << 16)));
mFixedVertexBuffer.put(posIndex + 1, (int)(y * (1 << 16)));
mFixedVertexBuffer.put(posIndex + 2, (int)(z * (1 << 16)));
mFixedTexCoordBuffer.put(texIndex, (int)(u * (1 << 16)));
mFixedTexCoordBuffer.put(texIndex + 1, (int)(v * (1 << 16)));
if (color != null) {
mFixedColorBuffer.put(colorIndex, (int)(color[0] * (1 << 16)));
mFixedColorBuffer.put(colorIndex + 1, (int)(color[1] * (1 << 16)));
mFixedColorBuffer.put(colorIndex + 2, (int)(color[2] * (1 << 16)));
mFixedColorBuffer.put(colorIndex + 3, (int)(color[3] * (1 << 16)));
}
}
}
public static void beginDrawing(GL10 gl, boolean useTexture, boolean useColor) {
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
if (useTexture) {
gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
gl.glEnable(GL10.GL_TEXTURE_2D);
} else {
gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
gl.glDisable(GL10.GL_TEXTURE_2D);
}
if (useColor) {
gl.glEnableClientState(GL10.GL_COLOR_ARRAY);
} else {
gl.glDisableClientState(GL10.GL_COLOR_ARRAY);
}
}
public void draw(GL10 gl, boolean useTexture, boolean useColor) {
if (!mUseHardwareBuffers) {
gl.glVertexPointer(3, mCoordinateType, 0, mVertexBuffer);
if (useTexture) {
gl.glTexCoordPointer(2, mCoordinateType, 0, mTexCoordBuffer);
}
if (useColor) {
gl.glColorPointer(4, mCoordinateType, 0, mColorBuffer);
}
gl.glDrawElements(GL10.GL_TRIANGLES, mIndexCount,
GL10.GL_UNSIGNED_SHORT, mIndexBuffer);
} else {
GL11 gl11 = (GL11)gl;
// draw using hardware buffers
gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, mVertBufferIndex);
gl11.glVertexPointer(3, mCoordinateType, 0, 0);
if (useTexture) {
gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, mTextureCoordBufferIndex);
gl11.glTexCoordPointer(2, mCoordinateType, 0, 0);
}
if (useColor) {
gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, mColorBufferIndex);
gl11.glColorPointer(4, mCoordinateType, 0, 0);
}
gl11.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, mIndexBufferIndex);
gl11.glDrawElements(GL11.GL_TRIANGLES, mIndexCount,
GL11.GL_UNSIGNED_SHORT, 0);
gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, 0);
gl11.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, 0);
}
}
public static void endDrawing(GL10 gl) {
gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
}
public boolean usingHardwareBuffers() {
return mUseHardwareBuffers;
}
/**
* When the OpenGL ES device is lost, GL handles become invalidated.
* In that case, we just want to "forget" the old handles (without
* explicitly deleting them) and make new ones.
*/
public void invalidateHardwareBuffers() {
mVertBufferIndex = 0;
mIndexBufferIndex = 0;
mTextureCoordBufferIndex = 0;
mColorBufferIndex = 0;
mUseHardwareBuffers = false;
}
/**
* Deletes the hardware buffers allocated by this object (if any).
*/
public void releaseHardwareBuffers(GL10 gl) {
if (mUseHardwareBuffers) {
if (gl instanceof GL11) {
GL11 gl11 = (GL11)gl;
int[] buffer = new int[1];
buffer[0] = mVertBufferIndex;
gl11.glDeleteBuffers(1, buffer, 0);
buffer[0] = mTextureCoordBufferIndex;
gl11.glDeleteBuffers(1, buffer, 0);
buffer[0] = mColorBufferIndex;
gl11.glDeleteBuffers(1, buffer, 0);
buffer[0] = mIndexBufferIndex;
gl11.glDeleteBuffers(1, buffer, 0);
}
invalidateHardwareBuffers();
}
}
/**
* Allocates hardware buffers on the graphics card and fills them with
* data if a buffer has not already been previously allocated. Note that
* this function uses the GL_OES_vertex_buffer_object extension, which is
* not guaranteed to be supported on every device.
* @param gl A pointer to the OpenGL ES context.
*/
public void generateHardwareBuffers(GL10 gl) {
if (!mUseHardwareBuffers) {
if (gl instanceof GL11) {
GL11 gl11 = (GL11)gl;
int[] buffer = new int[1];
// Allocate and fill the vertex buffer.
gl11.glGenBuffers(1, buffer, 0);
mVertBufferIndex = buffer[0];
gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, mVertBufferIndex);
final int vertexSize = mVertexBuffer.capacity() * mCoordinateSize;
gl11.glBufferData(GL11.GL_ARRAY_BUFFER, vertexSize,
mVertexBuffer, GL11.GL_STATIC_DRAW);
// Allocate and fill the texture coordinate buffer.
gl11.glGenBuffers(1, buffer, 0);
mTextureCoordBufferIndex = buffer[0];
gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER,
mTextureCoordBufferIndex);
final int texCoordSize =
mTexCoordBuffer.capacity() * mCoordinateSize;
gl11.glBufferData(GL11.GL_ARRAY_BUFFER, texCoordSize,
mTexCoordBuffer, GL11.GL_STATIC_DRAW);
// Allocate and fill the color buffer.
gl11.glGenBuffers(1, buffer, 0);
mColorBufferIndex = buffer[0];
gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER,
mColorBufferIndex);
final int colorSize =
mColorBuffer.capacity() * mCoordinateSize;
gl11.glBufferData(GL11.GL_ARRAY_BUFFER, colorSize,
mColorBuffer, GL11.GL_STATIC_DRAW);
// Unbind the array buffer.
gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, 0);
// Allocate and fill the index buffer.
gl11.glGenBuffers(1, buffer, 0);
mIndexBufferIndex = buffer[0];
gl11.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER,
mIndexBufferIndex);
// A char is 2 bytes.
final int indexSize = mIndexBuffer.capacity() * 2;
gl11.glBufferData(GL11.GL_ELEMENT_ARRAY_BUFFER, indexSize, mIndexBuffer,
GL11.GL_STATIC_DRAW);
// Unbind the element array buffer.
gl11.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, 0);
mUseHardwareBuffers = true;
assert mVertBufferIndex != 0;
assert mTextureCoordBufferIndex != 0;
assert mIndexBufferIndex != 0;
assert gl11.glGetError() == 0;
}
}
}
// These functions exposed to patch Grid info into native code.
public final int getVertexBuffer() {
return mVertBufferIndex;
}
public final int getTextureBuffer() {
return mTextureCoordBufferIndex;
}
public final int getIndexBuffer() {
return mIndexBufferIndex;
}
public final int getColorBuffer() {
return mColorBufferIndex;
}
public final int getIndexCount() {
return mIndexCount;
}
public boolean getFixedPoint() {
return (mCoordinateType == GL10.GL_FIXED);
}
public long getVertexCount() {
return mW * mH;
}
}
| Java |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.heightmapprofiler;
import java.util.ArrayList;
import javax.microedition.khronos.opengles.GL10;
// This is a central repository for all vertex arrays. It handles
// generation and invalidation of VBOs from each mesh.
public class MeshLibrary {
// This sample only has one type of mesh, Grid, but in a real game you might have
// multiple types of objects managing vertex arrays (animated objects, objects loaded from
// files, etc). This class could easily be modified to work with some basic Mesh class
// in that case.
private ArrayList<Grid[]> mMeshes = new ArrayList<Grid[]>();
public int addMesh(Grid[] lods) {
int index = mMeshes.size();
mMeshes.add(lods);
return index;
}
public Grid[] getMesh(int index) {
Grid[] mesh = null;
if (index >= 0 && index < mMeshes.size()) {
mesh = mMeshes.get(index);
}
return mesh;
}
public void generateHardwareBuffers(GL10 gl) {
final int count = mMeshes.size();
for (int x = 0; x < count; x++) {
Grid[] lods = mMeshes.get(x);
assert lods != null;
for (int y = 0; y < lods.length; y++) {
Grid lod = lods[y];
if (lod != null) {
lod.invalidateHardwareBuffers();
lod.generateHardwareBuffers(gl);
}
}
}
}
public void freeHardwareBuffers(GL10 gl) {
final int count = mMeshes.size();
for (int x = 0; x < count; x++) {
Grid[] lods = mMeshes.get(x);
assert lods != null;
for (int y = 0; y < lods.length; y++) {
Grid lod = lods[y];
if (lod != null) {
lod.releaseHardwareBuffers(gl);
}
}
}
}
}
| Java |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.heightmapprofiler;
import javax.microedition.khronos.opengles.GL10;
import android.graphics.Bitmap;
// This class defines a single land tile. It is built from
// a height map image and may contain several meshes defining different levels
// of detail.
public class LandTile {
public final static float TILE_SIZE = 512;
private final static float HALF_TILE_SIZE = TILE_SIZE / 2;
public final static float TILE_HEIGHT_THRESHOLD = 0.4f;
private final static int MAX_SUBDIVISIONS = 24;
private final static float LOD_STEP_SIZE = 300.0f;
public final static int LOD_LEVELS = 4;
private final static float MAX_LOD_DISTANCE = LOD_STEP_SIZE * (LOD_LEVELS - 1);
private final static float MAX_LOD_DISTANCE2 = MAX_LOD_DISTANCE * MAX_LOD_DISTANCE;
private Grid mLODMeshes[];
private int mLODTextures[];
private Vector3 mPosition = new Vector3();
private Vector3 mCenterPoint = new Vector3();
private Bitmap mHeightMap;
private float mHeightMapScaleX;
private float mHeightMapScaleY;
private int mLodLevels = LOD_LEVELS;
private int mMaxSubdivisions = MAX_SUBDIVISIONS;
private float mTileSizeX = TILE_SIZE;
private float mTileSizeZ = TILE_SIZE;
private float mHalfTileSizeX = HALF_TILE_SIZE;
private float mHalfTileSizeZ = HALF_TILE_SIZE;
private float mTileHeightScale = TILE_HEIGHT_THRESHOLD;
private float mMaxLodDistance = MAX_LOD_DISTANCE;
private float mMaxLodDistance2 = MAX_LOD_DISTANCE2;
public LandTile() {
}
public LandTile(boolean useLods, int maxSubdivisions ) {
if (!useLods) {
mLodLevels = 1;
}
mMaxSubdivisions = maxSubdivisions;
}
public LandTile(float sizeX, float sizeY, float sizeZ, int lodLevelCount, int maxSubdivisions, float maxLodDistance) {
mTileSizeX = sizeX;
mTileSizeZ = sizeZ;
mTileHeightScale = (1.0f / 255.0f) * sizeY;
mLodLevels = lodLevelCount;
mMaxSubdivisions = maxSubdivisions;
mMaxLodDistance = maxLodDistance;
mMaxLodDistance2 = maxLodDistance * maxLodDistance;
mHalfTileSizeX = sizeX / 2.0f;
mHalfTileSizeZ = sizeZ / 2.0f;
}
public void setLods(Grid[] lodMeshes, Bitmap heightmap) {
mHeightMap = heightmap;
mHeightMapScaleX = heightmap.getWidth() / mTileSizeX;
mHeightMapScaleY = heightmap.getHeight() / mTileSizeZ;
mLODMeshes = lodMeshes;
}
public void setLODTextures( int LODTextures[] ) {
mLODTextures = LODTextures;
}
public Grid[] generateLods(Bitmap heightmap, Bitmap lightmap, boolean useFixedPoint) {
final int subdivisionSizeStep = mMaxSubdivisions / mLodLevels;
mLODMeshes = new Grid[mLodLevels];
for (int x = 0; x < mLodLevels; x++) {
final int subdivisions = subdivisionSizeStep * (mLodLevels - x);
mLODMeshes[x] = HeightMapMeshMaker.makeGrid(heightmap, lightmap, subdivisions, mTileSizeX, mTileSizeZ, mTileHeightScale, useFixedPoint);
}
mHeightMap = heightmap;
mHeightMapScaleX = heightmap.getWidth() / mTileSizeX;
mHeightMapScaleY = heightmap.getHeight() / mTileSizeZ;
return mLODMeshes;
}
public final void setPosition(float x, float y, float z) {
mPosition.set(x, y, z);
mCenterPoint.set(x + mHalfTileSizeX, y, z + mHalfTileSizeZ);
}
public final void setPosition(Vector3 position) {
mPosition.set(position);
mCenterPoint.set(position.x + mHalfTileSizeX, position.y, position.z + mHalfTileSizeZ);
}
public final Vector3 getPosition() {
return mPosition;
}
public final Vector3 getCenterPoint() {
return mCenterPoint;
}
public final Grid[] getLods() {
return mLODMeshes;
}
public final float getMaxLodDistance() {
return mMaxLodDistance;
}
public float getHeight(float worldSpaceX, float worldSpaceZ) {
final float tileSpaceX = worldSpaceX - mPosition.x;
final float tileSpaceY = worldSpaceZ - mPosition.z;
final float imageSpaceX = tileSpaceX * mHeightMapScaleX;
final float imageSpaceY = tileSpaceY * mHeightMapScaleY;
float height = 0.0f;
if (imageSpaceX >= 0.0f && imageSpaceX < mHeightMap.getWidth()
&& imageSpaceY >= 0.0f && imageSpaceY < mHeightMap.getHeight()) {
height = HeightMapMeshMaker.getBilinearFilteredHeight(mHeightMap, imageSpaceX, imageSpaceY, mTileHeightScale);
}
return height;
}
public void draw(GL10 gl, Vector3 cameraPosition) {
mCenterPoint.y = cameraPosition.y; // HACK!
final float distanceFromCamera2 = cameraPosition.distance2(mCenterPoint);
int lod = mLodLevels - 1;
if (distanceFromCamera2 < mMaxLodDistance2) {
final int bucket = (int)((distanceFromCamera2 / mMaxLodDistance2) * mLodLevels);
lod = Math.min(bucket, mLodLevels - 1);
}
gl.glPushMatrix();
gl.glTranslatef(mPosition.x, mPosition.y, mPosition.z);
// TODO - should add some code to keep state of current Texture and only set it if a new texture is needed -
// may be taken care of natively by OpenGL lib.
if( mLODTextures != null ) {
// Check to see if we have different LODs to choose from (i.e. Text LOD feature is turned on). If not then
// just select the default texture
if( mLODTextures.length == 1 ) {
gl.glBindTexture(GL10.GL_TEXTURE_2D, mLODTextures[0]);
}
// if the LOD feature is enabled, use lod value to select correct texture to use
else {
gl.glBindTexture(GL10.GL_TEXTURE_2D, mLODTextures[lod]);
}
}
ProfileRecorder.sSingleton.addVerts(mLODMeshes[lod].getVertexCount());
mLODMeshes[lod].draw(gl, true, true);
gl.glPopMatrix();
}
}
| Java |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.heightmapprofiler;
import javax.microedition.khronos.opengles.GL10;
import android.graphics.Bitmap;
// This class manages a regular grid of LandTile objects. In this sample,
// all the objects are the same mesh. In a real game, they would probably be
// different to create a more interesting landscape.
// This class also abstracts the concept of tiles away from the rest of the
// code, so that the collision system (amongst others) can query the height of any
// given point in the world.
public class LandTileMap {
private MeshLibrary mMeshLibrary = new MeshLibrary();
private LandTile[] mTiles;
private LandTile mSkybox;
private float mWorldWidth;
private float mWorldHeight;
private int mTilesAcross;
private int mSkyboxTexture;
private boolean mUseColors;
private boolean mUseTexture;
private NativeRenderer mNativeRenderer;
public LandTileMap(
int tilesAcross,
int tilesDown,
Bitmap heightmap,
Bitmap lightmap,
boolean useColors,
boolean useTexture,
boolean useLods,
int maxSubdivisions,
boolean useFixedPoint) {
Grid[] lodMeshes;
int lodLevels = 1;
if (useLods) {
lodLevels = LandTile.LOD_LEVELS;
}
lodMeshes = new Grid[lodLevels];
final int subdivisionSizeStep = maxSubdivisions / lodLevels;
for (int x = 0; x < lodLevels; x++) {
final int subdivisions = subdivisionSizeStep * (lodLevels - x);
lodMeshes[x] = HeightMapMeshMaker.makeGrid(
heightmap,
lightmap,
subdivisions,
LandTile.TILE_SIZE,
LandTile.TILE_SIZE,
LandTile.TILE_HEIGHT_THRESHOLD,
useFixedPoint);
}
mMeshLibrary.addMesh(lodMeshes);
LandTile[] tiles = new LandTile[tilesAcross * tilesDown];
for (int x = 0; x < tilesAcross; x++) {
for (int y = 0; y < tilesDown; y++) {
LandTile tile = new LandTile(useLods, maxSubdivisions);
tile.setLods(lodMeshes, heightmap);
tiles[x * tilesAcross + y] = tile;
tile.setPosition(x * LandTile.TILE_SIZE, 0.0f, y * LandTile.TILE_SIZE);
}
}
mTiles = tiles;
mWorldWidth = tilesAcross * LandTile.TILE_SIZE;
mWorldHeight = tilesDown * LandTile.TILE_SIZE;
mTilesAcross = tilesAcross;
mUseColors = useColors;
mUseTexture = useTexture;
}
public void setLandTextures( int landTextures[] ) {
for( LandTile landTile : mTiles ) {
landTile.setLODTextures( landTextures );
}
}
public void setupSkybox(Bitmap heightmap, boolean useFixedPoint) {
if (mSkybox == null) {
mSkybox = new LandTile(mWorldWidth, 1024, mWorldHeight, 1, 16, 1000000.0f);
mMeshLibrary.addMesh(mSkybox.generateLods(heightmap, null, useFixedPoint));
mSkybox.setPosition(0.0f, 0.0f, 0.0f);
}
}
public float getHeight(float worldX, float worldZ) {
float height = 0.0f;
if (worldX > 0.0f && worldX < mWorldWidth && worldZ > 0.0f && worldZ < mWorldHeight) {
int tileX = (int)(worldX / LandTile.TILE_SIZE);
int tileY = (int)(worldZ / LandTile.TILE_SIZE);
height = mTiles[tileX * mTilesAcross + tileY].getHeight(worldX, worldZ);
}
return height;
}
public void setTextures(int[] landTextures, int skyboxTexture) {
setLandTextures( landTextures );
mSkyboxTexture = skyboxTexture;
if (mNativeRenderer != null) {
final int count = mTiles.length;
for (int x = 0; x < count; x++) {
mNativeRenderer.registerTile(landTextures, mTiles[x], false);
}
if (mSkybox != null) {
// Work around since registerTile() takes an array of textures
int textures[] = new int[1];
textures[0] = skyboxTexture;
mNativeRenderer.registerTile(textures, mSkybox, true);
}
}
}
public void draw(GL10 gl, Vector3 cameraPosition) {
if (mNativeRenderer != null) {
mNativeRenderer.draw(true, true);
} else {
if (mSkyboxTexture != 0) {
gl.glBindTexture(GL10.GL_TEXTURE_2D, mSkyboxTexture);
}
Grid.beginDrawing(gl, mUseTexture, mUseColors);
if (mSkybox != null) {
gl.glDepthMask(false);
gl.glDisable(GL10.GL_DEPTH_TEST);
mSkybox.draw(gl, cameraPosition);
gl.glDepthMask(true);
gl.glEnable(GL10.GL_DEPTH_TEST);
}
final int count = mTiles.length;
for (int x = 0; x < count; x++) {
mTiles[x].draw(gl, cameraPosition);
}
Grid.endDrawing(gl);
}
}
public void generateHardwareBuffers(GL10 gl) {
mMeshLibrary.generateHardwareBuffers(gl);
}
public void setNativeRenderer(NativeRenderer nativeRenderer) {
mNativeRenderer = nativeRenderer;
}
}
| Java |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.heightmapprofiler;
/**
* Simple 3D vector class. Handles basic vector math for 3D vectors.
*/
public final class Vector3 {
public float x;
public float y;
public float z;
public static final Vector3 ZERO = new Vector3(0, 0, 0);
public Vector3() {
}
public Vector3(float xValue, float yValue, float zValue) {
set(xValue, yValue, zValue);
}
public Vector3(Vector3 other) {
set(other);
}
public final void add(Vector3 other) {
x += other.x;
y += other.y;
z += other.z;
}
public final void add(float otherX, float otherY, float otherZ) {
x += otherX;
y += otherY;
z += otherZ;
}
public final void subtract(Vector3 other) {
x -= other.x;
y -= other.y;
z -= other.z;
}
public final void multiply(float magnitude) {
x *= magnitude;
y *= magnitude;
z *= magnitude;
}
public final void multiply(Vector3 other) {
x *= other.x;
y *= other.y;
z *= other.z;
}
public final void divide(float magnitude) {
if (magnitude != 0.0f) {
x /= magnitude;
y /= magnitude;
z /= magnitude;
}
}
public final void set(Vector3 other) {
x = other.x;
y = other.y;
z = other.z;
}
public final void set(float xValue, float yValue, float zValue) {
x = xValue;
y = yValue;
z = zValue;
}
public final float dot(Vector3 other) {
return (x * other.x) + (y * other.y) + (z * other.z);
}
public final float length() {
return (float) Math.sqrt(length2());
}
public final float length2() {
return (x * x) + (y * y) + (z * z);
}
public final float distance2(Vector3 other) {
float dx = x - other.x;
float dy = y - other.y;
float dz = z - other.z;
return (dx * dx) + (dy * dy) + (dz * dz);
}
public final float normalize() {
final float magnitude = length();
// TODO: I'm choosing safety over speed here.
if (magnitude != 0.0f) {
x /= magnitude;
y /= magnitude;
z /= magnitude;
}
return magnitude;
}
public final void zero() {
set(0.0f, 0.0f, 0.0f);
}
}
| Java |
/*
* Copyright (C) 2010 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.heightmapprofiler;
// This is a thin interface for a renderer implemented in C++ using the NDK.
public class NativeRenderer {
private Vector3 mCameraPosition = new Vector3();
private Vector3 mLookAtPosition = new Vector3();
private boolean mCameraDirty = false;
static {
System.loadLibrary("heightmapprofiler");
}
public NativeRenderer() {
nativeReset();
}
public void setCamera(Vector3 camera, Vector3 lookat) {
mCameraPosition = camera;
mLookAtPosition = lookat;
mCameraDirty = true;
}
public void registerTile(int textures[], LandTile tile, boolean isSkybox) {
final Grid[] lods = tile.getLods();
final Vector3 position = tile.getPosition();
final Vector3 center = tile.getCenterPoint();
final int index = nativeAddTile(textures[0], lods.length, tile.getMaxLodDistance(), position.x, position.y, position.z, center.x, center.y, center.z);
if (index >= 0) {
for (int x = 0; x < lods.length; x++) {
nativeAddLod(index, lods[x].getVertexBuffer(), lods[x].getTextureBuffer(), lods[x].getIndexBuffer(), lods[x].getColorBuffer(), lods[x].getIndexCount(), lods[x].getFixedPoint());
}
if (isSkybox) {
nativeSetSkybox(index);
}
for( int i = 1; i < textures.length; ++i ) {
nativeAddTextureLod( index, i, textures[i]);
}
}
}
public void registerSkybox(int texture, Grid mesh, Vector3 position, Vector3 centerPoint) {
}
public void draw(boolean useTexture, boolean useColor) {
nativeRender(mCameraPosition.x, mCameraPosition.y, mCameraPosition.z, mLookAtPosition.x, mLookAtPosition.y, mLookAtPosition.z, useTexture, useColor, mCameraDirty);
mCameraDirty = false;
}
private static native void nativeReset();
private static native int nativeAddTile(int texture, int lodCount, float maxLodDistance, float x, float y, float z, float centerX, float centerY, float centerZ);
private static native void nativeAddLod(int index, int vertexBuffer, int textureBuffer, int indexBuffer, int colorBuffer, int indexCount, boolean useFixedPoint);
private static native void nativeSetSkybox(int index);
private static native void nativeRender(float cameraX, float cameraY, float cameraZ, float lookAtX, float lookAtY, float lookAtZ, boolean useTexture, boolean useColor, boolean cameraDirty);
private static native void nativeAddTextureLod(int tileIndex, int lod, int textureName);
}
| 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.panoramio;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
/**
* Utilities for loading a bitmap from a URL
*
*/
public class BitmapUtils {
private static final String TAG = "Panoramio";
private static final int IO_BUFFER_SIZE = 4 * 1024;
/**
* Loads a bitmap from the specified url. This can take a while, so it should not
* be called from the UI thread.
*
* @param url The location of the bitmap asset
*
* @return The bitmap, or null if it could not be loaded
*/
public static Bitmap loadBitmap(String url) {
Bitmap bitmap = null;
InputStream in = null;
BufferedOutputStream out = null;
try {
in = new BufferedInputStream(new URL(url).openStream(), IO_BUFFER_SIZE);
final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
copy(in, out);
out.flush();
final byte[] data = dataStream.toByteArray();
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
} catch (IOException e) {
Log.e(TAG, "Could not load Bitmap from: " + url);
} finally {
closeStream(in);
closeStream(out);
}
return bitmap;
}
/**
* Closes the specified stream.
*
* @param stream The stream to close.
*/
private static void closeStream(Closeable stream) {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
android.util.Log.e(TAG, "Could not close stream", e);
}
}
}
/**
* Copy the content of the input stream into the output stream, using a
* temporary byte array buffer whose size is defined by
* {@link #IO_BUFFER_SIZE}.
*
* @param in The input stream to copy from.
* @param out The output stream to copy to.
* @throws IOException If any error occurs during the copy.
*/
private static void copy(InputStream in, OutputStream out) throws IOException {
byte[] b = new byte[IO_BUFFER_SIZE];
int read;
while ((read = in.read(b)) != -1) {
out.write(b, 0, read);
}
}
} | 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.panoramio;
import com.google.android.maps.GeoPoint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.widget.ImageView;
import android.widget.TextView;
/**
* Activity which displays a single image.
*/
public class ViewImage extends Activity {
private static final String TAG = "Panoramio";
private static final int MENU_RADAR = Menu.FIRST + 1;
private static final int MENU_MAP = Menu.FIRST + 2;
private static final int MENU_AUTHOR = Menu.FIRST + 3;
private static final int MENU_VIEW = Menu.FIRST + 4;
private static final int DIALOG_NO_RADAR = 1;
PanoramioItem mItem;
private Handler mHandler;
private ImageView mImage;
private TextView mTitle;
private TextView mOwner;
private View mContent;
private int mMapZoom;
private int mMapLatitudeE6;
private int mMapLongitudeE6;
@Override
protected void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
super.onCreate(savedInstanceState);
setContentView(R.layout.view_image);
// Remember the user's original search area and zoom level
Intent i = getIntent();
mItem = i.getParcelableExtra(ImageManager.PANORAMIO_ITEM_EXTRA);
mMapZoom = i.getIntExtra(ImageManager.ZOOM_EXTRA, Integer.MIN_VALUE);
mMapLatitudeE6 = i.getIntExtra(ImageManager.LATITUDE_E6_EXTRA, Integer.MIN_VALUE);
mMapLongitudeE6 = i.getIntExtra(ImageManager.LONGITUDE_E6_EXTRA, Integer.MIN_VALUE);
mHandler = new Handler();
mContent = findViewById(R.id.content);
mImage = (ImageView) findViewById(R.id.image);
mTitle = (TextView) findViewById(R.id.title);
mOwner = (TextView) findViewById(R.id.owner);
mContent.setVisibility(View.GONE);
getWindow().setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS,
Window.PROGRESS_VISIBILITY_ON);
new LoadThread().start();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(0, MENU_RADAR, 0, R.string.menu_radar)
.setIcon(R.drawable.ic_menu_radar)
.setAlphabeticShortcut('R');
menu.add(0, MENU_MAP, 0, R.string.menu_map)
.setIcon(R.drawable.ic_menu_map)
.setAlphabeticShortcut('M');
menu.add(0, MENU_AUTHOR, 0, R.string.menu_author)
.setIcon(R.drawable.ic_menu_author)
.setAlphabeticShortcut('A');
menu.add(0, MENU_VIEW, 0, R.string.menu_view)
.setIcon(android.R.drawable.ic_menu_view)
.setAlphabeticShortcut('V');
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case MENU_RADAR: {
// Launch the radar activity (if it is installed)
Intent i = new Intent("com.google.android.radar.SHOW_RADAR");
GeoPoint location = mItem.getLocation();
i.putExtra("latitude", (float)(location.getLatitudeE6() / 1000000f));
i.putExtra("longitude", (float)(location.getLongitudeE6() / 1000000f));
try {
startActivity(i);
} catch (ActivityNotFoundException ex) {
showDialog(DIALOG_NO_RADAR);
}
return true;
}
case MENU_MAP: {
// Display our custom map
Intent i = new Intent(this, ViewMap.class);
i.putExtra(ImageManager.PANORAMIO_ITEM_EXTRA, mItem);
i.putExtra(ImageManager.ZOOM_EXTRA, mMapZoom);
i.putExtra(ImageManager.LATITUDE_E6_EXTRA, mMapLatitudeE6);
i.putExtra(ImageManager.LONGITUDE_E6_EXTRA, mMapLongitudeE6);
startActivity(i);
return true;
}
case MENU_AUTHOR: {
// Display the author info page in the browser
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(mItem.getOwnerUrl()));
startActivity(i);
return true;
}
case MENU_VIEW: {
// Display the photo info page in the browser
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(mItem.getPhotoUrl()));
startActivity(i);
return true;
}
}
return super.onOptionsItemSelected(item);
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case DIALOG_NO_RADAR:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
return builder.setTitle(R.string.no_radar_title)
.setMessage(R.string.no_radar)
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(android.R.string.ok, null).create();
}
return null;
}
/**
* Utility to load a larger version of the image in a separate thread.
*
*/
private class LoadThread extends Thread {
public LoadThread() {
}
@Override
public void run() {
try {
String uri = mItem.getThumbUrl();
uri = uri.replace("thumbnail", "medium");
final Bitmap b = BitmapUtils.loadBitmap(uri);
mHandler.post(new Runnable() {
public void run() {
mImage.setImageBitmap(b);
mTitle.setText(mItem.getTitle());
mOwner.setText(mItem.getOwner());
mContent.setVisibility(View.VISIBLE);
getWindow().setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS,
Window.PROGRESS_VISIBILITY_OFF);
}
});
} catch (Exception e) {
Log.e(TAG, e.toString());
}
}
}
} | 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.panoramio;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import android.content.Intent;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.FrameLayout;
/**
* Activity which lets the user select a search area
*
*/
public class Panoramio extends MapActivity implements OnClickListener {
private MapView mMapView;
private MyLocationOverlay mMyLocationOverlay;
private ImageManager mImageManager;
public static final int MILLION = 1000000;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mImageManager = ImageManager.getInstance(this);
FrameLayout frame = (FrameLayout) findViewById(R.id.frame);
Button goButton = (Button) findViewById(R.id.go);
goButton.setOnClickListener(this);
// Add the map view to the frame
mMapView = new MapView(this, "Panoramio_DummyAPIKey");
frame.addView(mMapView,
new FrameLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
// Create an overlay to show current location
mMyLocationOverlay = new MyLocationOverlay(this, mMapView);
mMyLocationOverlay.runOnFirstFix(new Runnable() { public void run() {
mMapView.getController().animateTo(mMyLocationOverlay.getMyLocation());
}});
mMapView.getOverlays().add(mMyLocationOverlay);
mMapView.getController().setZoom(15);
mMapView.setClickable(true);
mMapView.setEnabled(true);
mMapView.setSatellite(true);
addZoomControls(frame);
}
@Override
protected void onResume() {
super.onResume();
mMyLocationOverlay.enableMyLocation();
}
@Override
protected void onStop() {
mMyLocationOverlay.disableMyLocation();
super.onStop();
}
/**
* Add zoom controls to our frame layout
*/
private void addZoomControls(FrameLayout frame) {
// Get the zoom controls and add them to the bottom of the map
View zoomControls = mMapView.getZoomControls();
FrameLayout.LayoutParams p =
new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT, Gravity.BOTTOM + Gravity.CENTER_HORIZONTAL);
frame.addView(zoomControls, p);
}
@Override
protected boolean isRouteDisplayed() {
return false;
}
/**
* Starts a new search when the user clicks the search button.
*/
public void onClick(View view) {
// Get the search area
int latHalfSpan = mMapView.getLatitudeSpan() >> 1;
int longHalfSpan = mMapView.getLongitudeSpan() >> 1;
// Remember how the map was displayed so we can show it the same way later
GeoPoint center = mMapView.getMapCenter();
int zoom = mMapView.getZoomLevel();
int latitudeE6 = center.getLatitudeE6();
int longitudeE6 = center.getLongitudeE6();
Intent i = new Intent(this, ImageList.class);
i.putExtra(ImageManager.ZOOM_EXTRA, zoom);
i.putExtra(ImageManager.LATITUDE_E6_EXTRA, latitudeE6);
i.putExtra(ImageManager.LONGITUDE_E6_EXTRA, longitudeE6);
float minLong = ((float) (longitudeE6 - longHalfSpan)) / MILLION;
float maxLong = ((float) (longitudeE6 + longHalfSpan)) / MILLION;
float minLat = ((float) (latitudeE6 - latHalfSpan)) / MILLION;
float maxLat = ((float) (latitudeE6 + latHalfSpan)) / MILLION;
mImageManager.clear();
// Start downloading
mImageManager.load(minLong, maxLong, minLat, maxLat);
// Show results
startActivity(i);
}
}
| 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.panoramio;
import com.google.android.maps.GeoPoint;
import android.graphics.Bitmap;
import android.os.Parcel;
import android.os.Parcelable;
/**
* Holds one item returned from the Panoramio server. This includes
* the bitmap along with other meta info.
*
*/
public class PanoramioItem implements Parcelable {
private long mId;
private Bitmap mBitmap;
private GeoPoint mLocation;
private String mTitle;
private String mOwner;
private String mThumbUrl;
private String mOwnerUrl;
private String mPhotoUrl;
public PanoramioItem(Parcel in) {
mId = in.readLong();
mBitmap = Bitmap.CREATOR.createFromParcel(in);
mLocation = new GeoPoint(in.readInt(), in.readInt());
mTitle = in.readString();
mOwner = in.readString();
mThumbUrl = in.readString();
mOwnerUrl = in.readString();
mPhotoUrl = in.readString();
}
public PanoramioItem(long id, String thumbUrl, Bitmap b, int latitudeE6, int longitudeE6,
String title, String owner, String ownerUrl, String photoUrl) {
mBitmap = b;
mLocation = new GeoPoint(latitudeE6, longitudeE6);
mTitle = title;
mOwner = owner;
mThumbUrl = thumbUrl;
mOwnerUrl = ownerUrl;
mPhotoUrl = photoUrl;
}
public long getId() {
return mId;
}
public Bitmap getBitmap() {
return mBitmap;
}
public GeoPoint getLocation() {
return mLocation;
}
public String getTitle() {
return mTitle;
}
public String getOwner() {
return mOwner;
}
public String getThumbUrl() {
return mThumbUrl;
}
public String getOwnerUrl() {
return mOwnerUrl;
}
public String getPhotoUrl() {
return mPhotoUrl;
}
public static final Parcelable.Creator<PanoramioItem> CREATOR =
new Parcelable.Creator<PanoramioItem>() {
public PanoramioItem createFromParcel(Parcel in) {
return new PanoramioItem(in);
}
public PanoramioItem[] newArray(int size) {
return new PanoramioItem[size];
}
};
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel parcel, int flags) {
parcel.writeLong(mId);
mBitmap.writeToParcel(parcel, 0);
parcel.writeInt(mLocation.getLatitudeE6());
parcel.writeInt(mLocation.getLongitudeE6());
parcel.writeString(mTitle);
parcel.writeString(mOwner);
parcel.writeString(mThumbUrl);
parcel.writeString(mOwnerUrl);
parcel.writeString(mPhotoUrl);
}
} | 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.panoramio;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.content.Context;
import android.database.DataSetObserver;
import android.graphics.Bitmap;
import android.os.Handler;
import android.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.ref.WeakReference;
import java.net.URI;
import java.util.ArrayList;
/**
* This class is responsible for downloading and parsing the search results for
* a particular area. All of the work is done on a separate thread, and progress
* is reported back through the DataSetObserver set in
* {@link #addObserver(DataSetObserver). State is held in memory by in memory
* maintained by a single instance of the ImageManager class.
*/
public class ImageManager {
private static final String TAG = "Panoramio";
/**
* Base URL for Panoramio's web API
*/
private static final String THUMBNAIL_URL = "//www.panoramio.com/map/get_panoramas.php?order=popularity&set=public&from=0&to=20&miny=%f&minx=%f&maxy=%f&maxx=%f&size=thumbnail";
/**
* Used to post results back to the UI thread
*/
private Handler mHandler = new Handler();
/**
* Holds the single instance of a ImageManager that is shared by the process.
*/
private static ImageManager sInstance;
/**
* Holds the images and related data that have been downloaded
*/
private ArrayList<PanoramioItem> mImages = new ArrayList<PanoramioItem>();
/**
* Observers interested in changes to the current search results
*/
private ArrayList<WeakReference<DataSetObserver>> mObservers =
new ArrayList<WeakReference<DataSetObserver>>();
/**
* True if we are in the process of loading
*/
private boolean mLoading;
private Context mContext;
/**
* Key for an Intent extra. The value is the zoom level selected by the user.
*/
public static final String ZOOM_EXTRA = "zoom";
/**
* Key for an Intent extra. The value is the latitude of the center of the search
* area chosen by the user.
*/
public static final String LATITUDE_E6_EXTRA = "latitudeE6";
/**
* Key for an Intent extra. The value is the latitude of the center of the search
* area chosen by the user.
*/
public static final String LONGITUDE_E6_EXTRA = "longitudeE6";
/**
* Key for an Intent extra. The value is an item to display
*/
public static final String PANORAMIO_ITEM_EXTRA = "item";
public static ImageManager getInstance(Context c) {
if (sInstance == null) {
sInstance = new ImageManager(c.getApplicationContext());
}
return sInstance;
}
private ImageManager(Context c) {
mContext = c;
}
/**
* @return True if we are still loading content
*/
public boolean isLoading() {
return mLoading;
}
/**
* Clear all downloaded content
*/
public void clear() {
mImages.clear();
notifyObservers();
}
/**
* Add an item to and notify observers of the change.
* @param item The item to add
*/
private void add(PanoramioItem item) {
mImages.add(item);
notifyObservers();
}
/**
* @return The number of items displayed so far
*/
public int size() {
return mImages.size();
}
/**
* Gets the item at the specified position
*/
public PanoramioItem get(int position) {
return mImages.get(position);
}
/**
* Adds an observer to be notified when the set of items held by this ImageManager changes.
*/
public void addObserver(DataSetObserver observer) {
WeakReference<DataSetObserver> obs = new WeakReference<DataSetObserver>(observer);
mObservers.add(obs);
}
/**
* Load a new set of search results for the specified area.
*
* @param minLong The minimum longitude for the search area
* @param maxLong The maximum longitude for the search area
* @param minLat The minimum latitude for the search area
* @param maxLat The minimum latitude for the search area
*/
public void load(float minLong, float maxLong, float minLat, float maxLat) {
mLoading = true;
new NetworkThread(minLong, maxLong, minLat, maxLat).start();
}
/**
* Called when something changes in our data set. Cleans up any weak references that
* are no longer valid along the way.
*/
private void notifyObservers() {
final ArrayList<WeakReference<DataSetObserver>> observers = mObservers;
final int count = observers.size();
for (int i = count - 1; i >= 0; i--) {
WeakReference<DataSetObserver> weak = observers.get(i);
DataSetObserver obs = weak.get();
if (obs != null) {
obs.onChanged();
} else {
observers.remove(i);
}
}
}
/**
* This thread does the actual work of downloading and parsing data.
*
*/
private class NetworkThread extends Thread {
private float mMinLong;
private float mMaxLong;
private float mMinLat;
private float mMaxLat;
public NetworkThread(float minLong, float maxLong, float minLat, float maxLat) {
mMinLong = minLong;
mMaxLong = maxLong;
mMinLat = minLat;
mMaxLat = maxLat;
}
@Override
public void run() {
String url = THUMBNAIL_URL;
url = String.format(url, mMinLat, mMinLong, mMaxLat, mMaxLong);
try {
URI uri = new URI("http", url, null);
HttpGet get = new HttpGet(uri);
HttpClient client = new DefaultHttpClient();
HttpResponse response = client.execute(get);
HttpEntity entity = response.getEntity();
String str = convertStreamToString(entity.getContent());
JSONObject json = new JSONObject(str);
parse(json);
} catch (Exception e) {
Log.e(TAG, e.toString());
}
}
private void parse(JSONObject json) {
try {
JSONArray array = json.getJSONArray("photos");
int count = array.length();
for (int i = 0; i < count; i++) {
JSONObject obj = array.getJSONObject(i);
long id = obj.getLong("photo_id");
String title = obj.getString("photo_title");
String owner = obj.getString("owner_name");
String thumb = obj.getString("photo_file_url");
String ownerUrl = obj.getString("owner_url");
String photoUrl = obj.getString("photo_url");
double latitude = obj.getDouble("latitude");
double longitude = obj.getDouble("longitude");
Bitmap b = BitmapUtils.loadBitmap(thumb);
if (title == null) {
title = mContext.getString(R.string.untitled);
}
final PanoramioItem item = new PanoramioItem(id, thumb, b,
(int) (latitude * Panoramio.MILLION),
(int) (longitude * Panoramio.MILLION), title, owner,
ownerUrl, photoUrl);
final boolean done = i == count - 1;
mHandler.post(new Runnable() {
public void run() {
sInstance.mLoading = !done;
sInstance.add(item);
}
});
}
} catch (JSONException e) {
Log.e(TAG, e.toString());
}
}
private String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is), 8*1024);
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
}
}
| 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.panoramio;
import android.content.Context;
import android.database.DataSetObserver;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;
/**
* Adapter used to bind data for the main list of photos
*/
public class ImageAdapter extends BaseAdapter {
/**
* Maintains the state of our data
*/
private ImageManager mImageManager;
private Context mContext;
private MyDataSetObserver mObserver;
/**
* Used by the {@link ImageManager} to report changes in the list back to
* this adapter.
*/
private class MyDataSetObserver extends DataSetObserver {
@Override
public void onChanged() {
notifyDataSetChanged();
}
@Override
public void onInvalidated() {
notifyDataSetInvalidated();
}
}
public ImageAdapter(Context c) {
mImageManager = ImageManager.getInstance(c);
mContext = c;
mObserver = new MyDataSetObserver();
mImageManager.addObserver(mObserver);
}
/**
* Returns the number of images to display
*
* @see android.widget.Adapter#getCount()
*/
public int getCount() {
return mImageManager.size();
}
/**
* Returns the image at a specified position
*
* @see android.widget.Adapter#getItem(int)
*/
public Object getItem(int position) {
return mImageManager.get(position);
}
/**
* Returns the id of an image at a specified position
*
* @see android.widget.Adapter#getItemId(int)
*/
public long getItemId(int position) {
PanoramioItem s = mImageManager.get(position);
return s.getId();
}
/**
* Returns a view to display the image at a specified position
*
* @param position The position to display
* @param convertView An existing view that we can reuse. May be null.
* @param parent The parent view that will eventually hold the view we return.
* @return A view to display the image at a specified position
*/
public View getView(int position, View convertView, ViewGroup parent) {
View view;
if (convertView == null) {
// Make up a new view
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.image_item, null);
} else {
// Use convertView if it is available
view = convertView;
}
PanoramioItem s = mImageManager.get(position);
ImageView i = (ImageView) view.findViewById(R.id.image);
i.setImageBitmap(s.getBitmap());
i.setBackgroundResource(R.drawable.picture_frame);
TextView t = (TextView) view.findViewById(R.id.title);
t.setText(s.getTitle());
t = (TextView) view.findViewById(R.id.owner);
t.setText(s.getOwner());
return view;
}
} | 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.panoramio;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.database.DataSetObserver;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.ListView;
/**
* Activity which displays the list of images.
*/
public class ImageList extends ListActivity {
ImageManager mImageManager;
private MyDataSetObserver mObserver = new MyDataSetObserver();
/**
* The zoom level the user chose when picking the search area
*/
private int mZoom;
/**
* The latitude of the center of the search area chosen by the user
*/
private int mLatitudeE6;
/**
* The longitude of the center of the search area chosen by the user
*/
private int mLongitudeE6;
/**
* Observer used to turn the progress indicator off when the {@link ImageManager} is
* done downloading.
*/
private class MyDataSetObserver extends DataSetObserver {
@Override
public void onChanged() {
if (!mImageManager.isLoading()) {
getWindow().setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS,
Window.PROGRESS_VISIBILITY_OFF);
}
}
@Override
public void onInvalidated() {
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
super.onCreate(savedInstanceState);
mImageManager = ImageManager.getInstance(this);
ListView listView = getListView();
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View footer = inflater.inflate(R.layout.list_footer, listView, false);
listView.addFooterView(footer, null, false);
setListAdapter(new ImageAdapter(this));
// Theme.Light sets a background on our list.
listView.setBackgroundDrawable(null);
if (mImageManager.isLoading()) {
getWindow().setFeatureInt(Window.FEATURE_INDETERMINATE_PROGRESS,
Window.PROGRESS_VISIBILITY_ON);
mImageManager.addObserver(mObserver);
}
// Read the user's search area from the intent
Intent i = getIntent();
mZoom = i.getIntExtra(ImageManager.ZOOM_EXTRA, Integer.MIN_VALUE);
mLatitudeE6 = i.getIntExtra(ImageManager.LATITUDE_E6_EXTRA, Integer.MIN_VALUE);
mLongitudeE6 = i.getIntExtra(ImageManager.LONGITUDE_E6_EXTRA, Integer.MIN_VALUE);
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
PanoramioItem item = mImageManager.get(position);
// Create an intent to show a particular item.
// Pass the user's search area along so the next activity can use it
Intent i = new Intent(this, ViewImage.class);
i.putExtra(ImageManager.PANORAMIO_ITEM_EXTRA, item);
i.putExtra(ImageManager.ZOOM_EXTRA, mZoom);
i.putExtra(ImageManager.LATITUDE_E6_EXTRA, mLatitudeE6);
i.putExtra(ImageManager.LONGITUDE_E6_EXTRA, mLongitudeE6);
startActivity(i);
}
} | 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.panoramio;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;
import com.google.android.maps.Projection;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.FrameLayout;
import java.util.ArrayList;
import java.util.List;
/**
* Displays a custom map which shows our current location and the location
* where the photo was taken.
*/
public class ViewMap extends MapActivity {
private MapView mMapView;
private MyLocationOverlay mMyLocationOverlay;
ArrayList<PanoramioItem> mItems = null;
private PanoramioItem mItem;
private Drawable mMarker;
private int mMarkerXOffset;
private int mMarkerYOffset;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FrameLayout frame = new FrameLayout(this);
mMapView = new MapView(this, "MapViewCompassDemo_DummyAPIKey");
frame.addView(mMapView,
new FrameLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
setContentView(frame);
mMyLocationOverlay = new MyLocationOverlay(this, mMapView);
mMarker = getResources().getDrawable(R.drawable.map_pin);
// Make sure to give mMarker bounds so it will draw in the overlay
final int intrinsicWidth = mMarker.getIntrinsicWidth();
final int intrinsicHeight = mMarker.getIntrinsicHeight();
mMarker.setBounds(0, 0, intrinsicWidth, intrinsicHeight);
mMarkerXOffset = -(intrinsicWidth / 2);
mMarkerYOffset = -intrinsicHeight;
// Read the item we are displaying from the intent, along with the
// parameters used to set up the map
Intent i = getIntent();
mItem = i.getParcelableExtra(ImageManager.PANORAMIO_ITEM_EXTRA);
int mapZoom = i.getIntExtra(ImageManager.ZOOM_EXTRA, Integer.MIN_VALUE);
int mapLatitudeE6 = i.getIntExtra(ImageManager.LATITUDE_E6_EXTRA, Integer.MIN_VALUE);
int mapLongitudeE6 = i.getIntExtra(ImageManager.LONGITUDE_E6_EXTRA, Integer.MIN_VALUE);
final List<Overlay> overlays = mMapView.getOverlays();
overlays.add(mMyLocationOverlay);
overlays.add(new PanoramioOverlay());
final MapController controller = mMapView.getController();
if (mapZoom != Integer.MIN_VALUE && mapLatitudeE6 != Integer.MIN_VALUE
&& mapLongitudeE6 != Integer.MIN_VALUE) {
controller.setZoom(mapZoom);
controller.setCenter(new GeoPoint(mapLatitudeE6, mapLongitudeE6));
} else {
controller.setZoom(15);
mMyLocationOverlay.runOnFirstFix(new Runnable() {
public void run() {
controller.animateTo(mMyLocationOverlay.getMyLocation());
}
});
}
mMapView.setClickable(true);
mMapView.setEnabled(true);
mMapView.setSatellite(true);
addZoomControls(frame);
}
@Override
protected void onResume() {
super.onResume();
mMyLocationOverlay.enableMyLocation();
}
@Override
protected void onStop() {
mMyLocationOverlay.disableMyLocation();
super.onStop();
}
/**
* Get the zoom controls and add them to the bottom of the map
*/
private void addZoomControls(FrameLayout frame) {
View zoomControls = mMapView.getZoomControls();
FrameLayout.LayoutParams p =
new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT, Gravity.BOTTOM + Gravity.CENTER_HORIZONTAL);
frame.addView(zoomControls, p);
}
@Override
protected boolean isRouteDisplayed() {
return false;
}
/**
* Custom overlay to display the Panoramio pushpin
*/
public class PanoramioOverlay extends Overlay {
@Override
public void draw(Canvas canvas, MapView mapView, boolean shadow) {
if (!shadow) {
Point point = new Point();
Projection p = mapView.getProjection();
p.toPixels(mItem.getLocation(), point);
super.draw(canvas, mapView, shadow);
drawAt(canvas, mMarker, point.x + mMarkerXOffset, point.y + mMarkerYOffset, shadow);
}
}
}
}
| 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.android.spritemethodtest;
import java.io.IOException;
import java.io.InputStream;
import javax.microedition.khronos.egl.EGL10;
import javax.microedition.khronos.opengles.GL10;
import javax.microedition.khronos.opengles.GL11;
import javax.microedition.khronos.opengles.GL11Ext;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.opengl.GLUtils;
import android.util.Log;
/**
* An OpenGL ES renderer based on the GLSurfaceView rendering framework. This
* class is responsible for drawing a list of renderables to the screen every
* frame. It also manages loading of textures and (when VBOs are used) the
* allocation of vertex buffer objects.
*/
public class SimpleGLRenderer implements GLSurfaceView.Renderer {
// Specifies the format our textures should be converted to upon load.
private static BitmapFactory.Options sBitmapOptions
= new BitmapFactory.Options();
// An array of things to draw every frame.
private GLSprite[] mSprites;
// Pre-allocated arrays to use at runtime so that allocation during the
// test can be avoided.
private int[] mTextureNameWorkspace;
private int[] mCropWorkspace;
// A reference to the application context.
private Context mContext;
// Determines the use of vertex arrays.
private boolean mUseVerts;
// Determines the use of vertex buffer objects.
private boolean mUseHardwareBuffers;
public SimpleGLRenderer(Context context) {
// Pre-allocate and store these objects so we can use them at runtime
// without allocating memory mid-frame.
mTextureNameWorkspace = new int[1];
mCropWorkspace = new int[4];
// Set our bitmaps to 16-bit, 565 format.
sBitmapOptions.inPreferredConfig = Bitmap.Config.RGB_565;
mContext = context;
}
public int[] getConfigSpec() {
// We don't need a depth buffer, and don't care about our
// color depth.
int[] configSpec = { EGL10.EGL_DEPTH_SIZE, 0, EGL10.EGL_NONE };
return configSpec;
}
public void setSprites(GLSprite[] sprites) {
mSprites = sprites;
}
/**
* Changes the vertex mode used for drawing.
* @param useVerts Specifies whether to use a vertex array. If false, the
* DrawTexture extension is used.
* @param useHardwareBuffers Specifies whether to store vertex arrays in
* main memory or on the graphics card. Ignored if useVerts is false.
*/
public void setVertMode(boolean useVerts, boolean useHardwareBuffers) {
mUseVerts = useVerts;
mUseHardwareBuffers = useVerts ? useHardwareBuffers : false;
}
/** Draws the sprites. */
public void drawFrame(GL10 gl) {
if (mSprites != null) {
gl.glMatrixMode(GL10.GL_MODELVIEW);
if (mUseVerts) {
Grid.beginDrawing(gl, true, false);
}
for (int x = 0; x < mSprites.length; x++) {
mSprites[x].draw(gl);
}
if (mUseVerts) {
Grid.endDrawing(gl);
}
}
}
/* Called when the size of the window changes. */
public void sizeChanged(GL10 gl, int width, int height) {
gl.glViewport(0, 0, width, height);
/*
* Set our projection matrix. This doesn't have to be done each time we
* draw, but usually a new projection needs to be set when the viewport
* is resized.
*/
gl.glMatrixMode(GL10.GL_PROJECTION);
gl.glLoadIdentity();
gl.glOrthof(0.0f, width, 0.0f, height, 0.0f, 1.0f);
gl.glShadeModel(GL10.GL_FLAT);
gl.glEnable(GL10.GL_BLEND);
gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
gl.glColor4x(0x10000, 0x10000, 0x10000, 0x10000);
gl.glEnable(GL10.GL_TEXTURE_2D);
}
/**
* Called whenever the surface is created. This happens at startup, and
* may be called again at runtime if the device context is lost (the screen
* goes to sleep, etc). This function must fill the contents of vram with
* texture data and (when using VBOs) hardware vertex arrays.
*/
public void surfaceCreated(GL10 gl) {
/*
* Some one-time OpenGL initialization can be made here probably based
* on features of this particular context
*/
gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_FASTEST);
gl.glClearColor(0.5f, 0.5f, 0.5f, 1);
gl.glShadeModel(GL10.GL_FLAT);
gl.glDisable(GL10.GL_DEPTH_TEST);
gl.glEnable(GL10.GL_TEXTURE_2D);
/*
* By default, OpenGL enables features that improve quality but reduce
* performance. One might want to tweak that especially on software
* renderer.
*/
gl.glDisable(GL10.GL_DITHER);
gl.glDisable(GL10.GL_LIGHTING);
gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
if (mSprites != null) {
// If we are using hardware buffers and the screen lost context
// then the buffer indexes that we recorded previously are now
// invalid. Forget them here and recreate them below.
if (mUseHardwareBuffers) {
for (int x = 0; x < mSprites.length; x++) {
// Ditch old buffer indexes.
mSprites[x].getGrid().invalidateHardwareBuffers();
}
}
// Load our texture and set its texture name on all sprites.
// To keep this sample simple we will assume that sprites that share
// the same texture are grouped together in our sprite list. A real
// app would probably have another level of texture management,
// like a texture hash.
int lastLoadedResource = -1;
int lastTextureId = -1;
for (int x = 0; x < mSprites.length; x++) {
int resource = mSprites[x].getResourceId();
if (resource != lastLoadedResource) {
lastTextureId = loadBitmap(mContext, gl, resource);
lastLoadedResource = resource;
}
mSprites[x].setTextureName(lastTextureId);
if (mUseHardwareBuffers) {
Grid currentGrid = mSprites[x].getGrid();
if (!currentGrid.usingHardwareBuffers()) {
currentGrid.generateHardwareBuffers(gl);
}
//mSprites[x].getGrid().generateHardwareBuffers(gl);
}
}
}
}
/**
* Called when the rendering thread shuts down. This is a good place to
* release OpenGL ES resources.
* @param gl
*/
public void shutdown(GL10 gl) {
if (mSprites != null) {
int lastFreedResource = -1;
int[] textureToDelete = new int[1];
for (int x = 0; x < mSprites.length; x++) {
int resource = mSprites[x].getResourceId();
if (resource != lastFreedResource) {
textureToDelete[0] = mSprites[x].getTextureName();
gl.glDeleteTextures(1, textureToDelete, 0);
mSprites[x].setTextureName(0);
}
if (mUseHardwareBuffers) {
mSprites[x].getGrid().releaseHardwareBuffers(gl);
}
}
}
}
/**
* Loads a bitmap into OpenGL and sets up the common parameters for
* 2D texture maps.
*/
protected int loadBitmap(Context context, GL10 gl, int resourceId) {
int textureName = -1;
if (context != null && gl != null) {
gl.glGenTextures(1, mTextureNameWorkspace, 0);
textureName = mTextureNameWorkspace[0];
gl.glBindTexture(GL10.GL_TEXTURE_2D, textureName);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_CLAMP_TO_EDGE);
gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_CLAMP_TO_EDGE);
gl.glTexEnvf(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE, GL10.GL_REPLACE);
InputStream is = context.getResources().openRawResource(resourceId);
Bitmap bitmap;
try {
bitmap = BitmapFactory.decodeStream(is, null, sBitmapOptions);
} finally {
try {
is.close();
} catch (IOException e) {
// Ignore.
}
}
GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0);
mCropWorkspace[0] = 0;
mCropWorkspace[1] = bitmap.getHeight();
mCropWorkspace[2] = bitmap.getWidth();
mCropWorkspace[3] = -bitmap.getHeight();
bitmap.recycle();
((GL11) gl).glTexParameteriv(GL10.GL_TEXTURE_2D,
GL11Ext.GL_TEXTURE_CROP_RECT_OES, mCropWorkspace, 0);
int error = gl.glGetError();
if (error != GL10.GL_NO_ERROR) {
Log.e("SpriteMethodTest", "Texture Load GLError: " + error);
}
}
return textureName;
}
}
| 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.android.spritemethodtest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioGroup;
/**
* Main entry point for the SpriteMethodTest application. This application
* provides a simple interface for testing the relative speed of 2D rendering
* systems available on Android, namely the Canvas system and OpenGL ES. It
* also serves as an example of how SurfaceHolders can be used to create an
* efficient rendering thread for drawing.
*/
public class SpriteMethodTest extends Activity {
private static final int ACTIVITY_TEST = 0;
private static final int RESULTS_DIALOG = 0;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Sets up a click listener for the Run Test button.
Button button;
button = (Button) findViewById(R.id.runTest);
button.setOnClickListener(mRunTestListener);
// Turns on one item by default in our radio groups--as it should be!
RadioGroup group = (RadioGroup)findViewById(R.id.renderMethod);
group.setOnCheckedChangeListener(mMethodChangedListener);
group.check(R.id.methodCanvas);
RadioGroup glSettings = (RadioGroup)findViewById(R.id.GLSettings);
glSettings.check(R.id.settingVerts);
}
/** Passes preferences about the test via its intent. */
protected void initializeIntent(Intent i) {
final CheckBox checkBox = (CheckBox) findViewById(R.id.animateSprites);
final boolean animate = checkBox.isChecked();
final EditText editText = (EditText) findViewById(R.id.spriteCount);
final String spriteCountText = editText.getText().toString();
final int stringCount = Integer.parseInt(spriteCountText);
i.putExtra("animate", animate);
i.putExtra("spriteCount", stringCount);
}
/**
* Responds to a click on the Run Test button by launching a new test
* activity.
*/
View.OnClickListener mRunTestListener = new OnClickListener() {
public void onClick(View v) {
RadioGroup group = (RadioGroup)findViewById(R.id.renderMethod);
Intent i;
if (group.getCheckedRadioButtonId() == R.id.methodCanvas) {
i = new Intent(v.getContext(), CanvasTestActivity.class);
} else {
i = new Intent(v.getContext(), OpenGLTestActivity.class);
RadioGroup glSettings =
(RadioGroup)findViewById(R.id.GLSettings);
if (glSettings.getCheckedRadioButtonId() == R.id.settingVerts) {
i.putExtra("useVerts", true);
} else if (glSettings.getCheckedRadioButtonId()
== R.id.settingVBO) {
i.putExtra("useVerts", true);
i.putExtra("useHardwareBuffers", true);
}
}
initializeIntent(i);
startActivityForResult(i, ACTIVITY_TEST);
}
};
/**
* Enables or disables OpenGL ES-specific settings controls when the render
* method option changes.
*/
RadioGroup.OnCheckedChangeListener mMethodChangedListener
= new RadioGroup.OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup group, int checkedId) {
if (checkedId == R.id.methodCanvas) {
findViewById(R.id.settingDrawTexture).setEnabled(false);
findViewById(R.id.settingVerts).setEnabled(false);
findViewById(R.id.settingVBO).setEnabled(false);
} else {
findViewById(R.id.settingDrawTexture).setEnabled(true);
findViewById(R.id.settingVerts).setEnabled(true);
findViewById(R.id.settingVBO).setEnabled(true);
}
}
};
/** Creates the test results dialog and fills in a dummy message. */
@Override
protected Dialog onCreateDialog(int id) {
Dialog dialog = null;
if (id == RESULTS_DIALOG) {
String dummy = "No results yet.";
CharSequence sequence = dummy.subSequence(0, dummy.length() -1);
dialog = new AlertDialog.Builder(this)
.setTitle(R.string.dialog_title)
.setPositiveButton(R.string.dialog_ok, null)
.setMessage(sequence)
.create();
}
return dialog;
}
/**
* Replaces the dummy message in the test results dialog with a string that
* describes the actual test results.
*/
protected void onPrepareDialog (int id, Dialog dialog) {
if (id == RESULTS_DIALOG) {
// Extract final timing information from the profiler.
final ProfileRecorder profiler = ProfileRecorder.sSingleton;
final long frameTime =
profiler.getAverageTime(ProfileRecorder.PROFILE_FRAME);
final long frameMin =
profiler.getMinTime(ProfileRecorder.PROFILE_FRAME);
final long frameMax =
profiler.getMaxTime(ProfileRecorder.PROFILE_FRAME);
final long drawTime =
profiler.getAverageTime(ProfileRecorder.PROFILE_DRAW);
final long drawMin =
profiler.getMinTime(ProfileRecorder.PROFILE_DRAW);
final long drawMax =
profiler.getMaxTime(ProfileRecorder.PROFILE_DRAW);
final long flipTime =
profiler.getAverageTime(ProfileRecorder.PROFILE_PAGE_FLIP);
final long flipMin =
profiler.getMinTime(ProfileRecorder.PROFILE_PAGE_FLIP);
final long flipMax =
profiler.getMaxTime(ProfileRecorder.PROFILE_PAGE_FLIP);
final long simTime =
profiler.getAverageTime(ProfileRecorder.PROFILE_SIM);
final long simMin =
profiler.getMinTime(ProfileRecorder.PROFILE_SIM);
final long simMax =
profiler.getMaxTime(ProfileRecorder.PROFILE_SIM);
final float fps = frameTime > 0 ? 1000.0f / frameTime : 0.0f;
String result = "Frame: " + frameTime + "ms (" + fps + " fps)\n"
+ "\t\tMin: " + frameMin + "ms\t\tMax: " + frameMax + "\n"
+ "Draw: " + drawTime + "ms\n"
+ "\t\tMin: " + drawMin + "ms\t\tMax: " + drawMax + "\n"
+ "Page Flip: " + flipTime + "ms\n"
+ "\t\tMin: " + flipMin + "ms\t\tMax: " + flipMax + "\n"
+ "Sim: " + simTime + "ms\n"
+ "\t\tMin: " + simMin + "ms\t\tMax: " + simMax + "\n";
CharSequence sequence = result.subSequence(0, result.length() -1);
AlertDialog alertDialog = (AlertDialog)dialog;
alertDialog.setMessage(sequence);
}
}
/** Shows the results dialog when the test activity closes. */
@Override
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
showDialog(RESULTS_DIALOG);
}
} | Java |
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.spritemethodtest;
import javax.microedition.khronos.opengles.GL10;
import javax.microedition.khronos.opengles.GL11Ext;
/**
* This is the OpenGL ES version of a sprite. It is more complicated than the
* CanvasSprite class because it can be used in more than one way. This class
* can draw using a grid of verts, a grid of verts stored in VBO objects, or
* using the DrawTexture extension.
*/
public class GLSprite extends Renderable {
// The OpenGL ES texture handle to draw.
private int mTextureName;
// The id of the original resource that mTextureName is based on.
private int mResourceId;
// If drawing with verts or VBO verts, the grid object defining those verts.
private Grid mGrid;
public GLSprite(int resourceId) {
super();
mResourceId = resourceId;
}
public void setTextureName(int name) {
mTextureName = name;
}
public int getTextureName() {
return mTextureName;
}
public void setResourceId(int id) {
mResourceId = id;
}
public int getResourceId() {
return mResourceId;
}
public void setGrid(Grid grid) {
mGrid = grid;
}
public Grid getGrid() {
return mGrid;
}
public void draw(GL10 gl) {
gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureName);
if (mGrid == null) {
// Draw using the DrawTexture extension.
((GL11Ext) gl).glDrawTexfOES(x, y, z, width, height);
} else {
// Draw using verts or VBO verts.
gl.glPushMatrix();
gl.glLoadIdentity();
gl.glTranslatef(
x,
y,
z);
mGrid.draw(gl, true, false);
gl.glPopMatrix();
}
}
}
| Java |
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.spritemethodtest;
import android.graphics.Canvas;
import com.android.spritemethodtest.CanvasSurfaceView.Renderer;
/**
* An extremely simple renderer based on the CanvasSurfaceView drawing
* framework. Simply draws a list of sprites to a canvas every frame.
*/
public class SimpleCanvasRenderer implements Renderer {
private CanvasSprite[] mSprites;
public void setSprites(CanvasSprite[] sprites) {
mSprites = sprites;
}
public void drawFrame(Canvas canvas) {
if (mSprites != null) {
for (int x = 0; x < mSprites.length; x++) {
mSprites[x].draw(canvas);
}
}
}
public void sizeChanged(int width, int height) {
}
}
| Java |
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.spritemethodtest;
import android.os.SystemClock;
/**
* Implements a simple runtime profiler. The profiler records start and stop
* times for several different types of profiles and can then return min, max
* and average execution times per type. Profile types are independent and may
* be nested in calling code. This object is a singleton for convenience.
*/
public class ProfileRecorder {
// A type for recording actual draw command time.
public static final int PROFILE_DRAW = 0;
// A type for recording the time it takes to display the scene.
public static final int PROFILE_PAGE_FLIP = 1;
// A type for recording the time it takes to run a single simulation step.
public static final int PROFILE_SIM = 2;
// A type for recording the total amount of time spent rendering a frame.
public static final int PROFILE_FRAME = 3;
private static final int PROFILE_COUNT = PROFILE_FRAME + 1;
private ProfileRecord[] mProfiles;
private int mFrameCount;
public static ProfileRecorder sSingleton = new ProfileRecorder();
public ProfileRecorder() {
mProfiles = new ProfileRecord[PROFILE_COUNT];
for (int x = 0; x < PROFILE_COUNT; x++) {
mProfiles[x] = new ProfileRecord();
}
}
/** Starts recording execution time for a specific profile type.*/
public void start(int profileType) {
if (profileType < PROFILE_COUNT) {
mProfiles[profileType].start(SystemClock.uptimeMillis());
}
}
/** Stops recording time for this profile type. */
public void stop(int profileType) {
if (profileType < PROFILE_COUNT) {
mProfiles[profileType].stop(SystemClock.uptimeMillis());
}
}
/** Indicates the end of the frame.*/
public void endFrame() {
mFrameCount++;
}
/* Flushes all recorded timings from the profiler. */
public void resetAll() {
for (int x = 0; x < PROFILE_COUNT; x++) {
mProfiles[x].reset();
}
mFrameCount = 0;
}
/* Returns the average execution time, in milliseconds, for a given type. */
public long getAverageTime(int profileType) {
long time = 0;
if (profileType < PROFILE_COUNT) {
time = mProfiles[profileType].getAverageTime(mFrameCount);
}
return time;
}
/* Returns the minimum execution time in milliseconds for a given type. */
public long getMinTime(int profileType) {
long time = 0;
if (profileType < PROFILE_COUNT) {
time = mProfiles[profileType].getMinTime();
}
return time;
}
/* Returns the maximum execution time in milliseconds for a given type. */
public long getMaxTime(int profileType) {
long time = 0;
if (profileType < PROFILE_COUNT) {
time = mProfiles[profileType].getMaxTime();
}
return time;
}
/**
* A simple class for storing timing information about a single profile
* type.
*/
protected class ProfileRecord {
private long mStartTime;
private long mTotalTime;
private long mMinTime;
private long mMaxTime;
public void start(long time) {
mStartTime = time;
}
public void stop(long time) {
final long timeDelta = time - mStartTime;
mTotalTime += timeDelta;
if (mMinTime == 0 || timeDelta < mMinTime) {
mMinTime = timeDelta;
}
if (mMaxTime == 0 || timeDelta > mMaxTime) {
mMaxTime = timeDelta;
}
}
public long getAverageTime(int frameCount) {
long time = frameCount > 0 ? mTotalTime / frameCount : 0;
return time;
}
public long getMinTime() {
return mMinTime;
}
public long getMaxTime() {
return mMaxTime;
}
public void startNewProfilePeriod() {
mTotalTime = 0;
}
public void reset() {
mTotalTime = 0;
mStartTime = 0;
mMinTime = 0;
mMaxTime = 0;
}
}
}
| Java |
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.spritemethodtest;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.os.Bundle;
import android.util.DisplayMetrics;
/**
* Activity for testing OpenGL ES drawing speed. This activity sets up sprites
* and passes them off to an OpenGLSurfaceView for rendering and movement.
*/
public class OpenGLTestActivity extends Activity {
private final static int SPRITE_WIDTH = 64;
private final static int SPRITE_HEIGHT = 64;
private GLSurfaceView mGLSurfaceView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mGLSurfaceView = new GLSurfaceView(this);
SimpleGLRenderer spriteRenderer = new SimpleGLRenderer(this);
// Clear out any old profile results.
ProfileRecorder.sSingleton.resetAll();
final Intent callingIntent = getIntent();
// Allocate our sprites and add them to an array.
final int robotCount = callingIntent.getIntExtra("spriteCount", 10);
final boolean animate = callingIntent.getBooleanExtra("animate", true);
final boolean useVerts =
callingIntent.getBooleanExtra("useVerts", false);
final boolean useHardwareBuffers =
callingIntent.getBooleanExtra("useHardwareBuffers", false);
// Allocate space for the robot sprites + one background sprite.
GLSprite[] spriteArray = new GLSprite[robotCount + 1];
// We need to know the width and height of the display pretty soon,
// so grab the information now.
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
GLSprite background = new GLSprite(R.drawable.background);
BitmapDrawable backgroundImage = (BitmapDrawable)getResources().getDrawable(R.drawable.background);
Bitmap backgoundBitmap = backgroundImage.getBitmap();
background.width = backgoundBitmap.getWidth();
background.height = backgoundBitmap.getHeight();
if (useVerts) {
// Setup the background grid. This is just a quad.
Grid backgroundGrid = new Grid(2, 2, false);
backgroundGrid.set(0, 0, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, null);
backgroundGrid.set(1, 0, background.width, 0.0f, 0.0f, 1.0f, 1.0f, null);
backgroundGrid.set(0, 1, 0.0f, background.height, 0.0f, 0.0f, 0.0f, null);
backgroundGrid.set(1, 1, background.width, background.height, 0.0f,
1.0f, 0.0f, null );
background.setGrid(backgroundGrid);
}
spriteArray[0] = background;
Grid spriteGrid = null;
if (useVerts) {
// Setup a quad for the sprites to use. All sprites will use the
// same sprite grid intance.
spriteGrid = new Grid(2, 2, false);
spriteGrid.set(0, 0, 0.0f, 0.0f, 0.0f, 0.0f , 1.0f, null);
spriteGrid.set(1, 0, SPRITE_WIDTH, 0.0f, 0.0f, 1.0f, 1.0f, null);
spriteGrid.set(0, 1, 0.0f, SPRITE_HEIGHT, 0.0f, 0.0f, 0.0f, null);
spriteGrid.set(1, 1, SPRITE_WIDTH, SPRITE_HEIGHT, 0.0f, 1.0f, 0.0f, null);
}
// This list of things to move. It points to the same content as the
// sprite list except for the background.
Renderable[] renderableArray = new Renderable[robotCount];
final int robotBucketSize = robotCount / 3;
for (int x = 0; x < robotCount; x++) {
GLSprite robot;
// Our robots come in three flavors. Split them up accordingly.
if (x < robotBucketSize) {
robot = new GLSprite(R.drawable.skate1);
} else if (x < robotBucketSize * 2) {
robot = new GLSprite(R.drawable.skate2);
} else {
robot = new GLSprite(R.drawable.skate3);
}
robot.width = SPRITE_WIDTH;
robot.height = SPRITE_HEIGHT;
// Pick a random location for this sprite.
robot.x = (float)(Math.random() * dm.widthPixels);
robot.y = (float)(Math.random() * dm.heightPixels);
// All sprites can reuse the same grid. If we're running the
// DrawTexture extension test, this is null.
robot.setGrid(spriteGrid);
// Add this robot to the spriteArray so it gets drawn and to the
// renderableArray so that it gets moved.
spriteArray[x + 1] = robot;
renderableArray[x] = robot;
}
// Now's a good time to run the GC. Since we won't do any explicit
// allocation during the test, the GC should stay dormant and not
// influence our results.
Runtime r = Runtime.getRuntime();
r.gc();
spriteRenderer.setSprites(spriteArray);
spriteRenderer.setVertMode(useVerts, useHardwareBuffers);
mGLSurfaceView.setRenderer(spriteRenderer);
if (animate) {
Mover simulationRuntime = new Mover();
simulationRuntime.setRenderables(renderableArray);
simulationRuntime.setViewSize(dm.widthPixels, dm.heightPixels);
mGLSurfaceView.setEvent(simulationRuntime);
}
setContentView(mGLSurfaceView);
}
}
| Java |
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.spritemethodtest;
import android.os.SystemClock;
/**
* A simple runnable that updates the position of each sprite on the screen
* every frame by applying a very simple gravity and bounce simulation. The
* sprites are jumbled with random velocities every once and a while.
*/
public class Mover implements Runnable {
private Renderable[] mRenderables;
private long mLastTime;
private long mLastJumbleTime;
private int mViewWidth;
private int mViewHeight;
static final float COEFFICIENT_OF_RESTITUTION = 0.75f;
static final float SPEED_OF_GRAVITY = 150.0f;
static final long JUMBLE_EVERYTHING_DELAY = 15 * 1000;
static final float MAX_VELOCITY = 8000.0f;
public void run() {
// Perform a single simulation step.
if (mRenderables != null) {
final long time = SystemClock.uptimeMillis();
final long timeDelta = time - mLastTime;
final float timeDeltaSeconds =
mLastTime > 0.0f ? timeDelta / 1000.0f : 0.0f;
mLastTime = time;
// Check to see if it's time to jumble again.
final boolean jumble =
(time - mLastJumbleTime > JUMBLE_EVERYTHING_DELAY);
if (jumble) {
mLastJumbleTime = time;
}
for (int x = 0; x < mRenderables.length; x++) {
Renderable object = mRenderables[x];
// Jumble! Apply random velocities.
if (jumble) {
object.velocityX += (MAX_VELOCITY / 2.0f)
- (float)(Math.random() * MAX_VELOCITY);
object.velocityY += (MAX_VELOCITY / 2.0f)
- (float)(Math.random() * MAX_VELOCITY);
}
// Move.
object.x = object.x + (object.velocityX * timeDeltaSeconds);
object.y = object.y + (object.velocityY * timeDeltaSeconds);
object.z = object.z + (object.velocityZ * timeDeltaSeconds);
// Apply Gravity.
object.velocityY -= SPEED_OF_GRAVITY * timeDeltaSeconds;
// Bounce.
if ((object.x < 0.0f && object.velocityX < 0.0f)
|| (object.x > mViewWidth - object.width
&& object.velocityX > 0.0f)) {
object.velocityX =
-object.velocityX * COEFFICIENT_OF_RESTITUTION;
object.x = Math.max(0.0f,
Math.min(object.x, mViewWidth - object.width));
if (Math.abs(object.velocityX) < 0.1f) {
object.velocityX = 0.0f;
}
}
if ((object.y < 0.0f && object.velocityY < 0.0f)
|| (object.y > mViewHeight - object.height
&& object.velocityY > 0.0f)) {
object.velocityY =
-object.velocityY * COEFFICIENT_OF_RESTITUTION;
object.y = Math.max(0.0f,
Math.min(object.y, mViewHeight - object.height));
if (Math.abs(object.velocityY) < 0.1f) {
object.velocityY = 0.0f;
}
}
}
}
}
public void setRenderables(Renderable[] renderables) {
mRenderables = renderables;
}
public void setViewSize(int width, int height) {
mViewHeight = height;
mViewWidth = width;
}
}
| Java |
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.spritemethodtest;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.CharBuffer;
import java.nio.FloatBuffer;
import java.nio.IntBuffer;
import javax.microedition.khronos.opengles.GL10;
import javax.microedition.khronos.opengles.GL11;
/**
* A 2D rectangular mesh. Can be drawn textured or untextured.
* This version is modified from the original Grid.java (found in
* the SpriteText package in the APIDemos Android sample) to support hardware
* vertex buffers.
*/
class Grid {
private FloatBuffer mFloatVertexBuffer;
private FloatBuffer mFloatTexCoordBuffer;
private FloatBuffer mFloatColorBuffer;
private IntBuffer mFixedVertexBuffer;
private IntBuffer mFixedTexCoordBuffer;
private IntBuffer mFixedColorBuffer;
private CharBuffer mIndexBuffer;
private Buffer mVertexBuffer;
private Buffer mTexCoordBuffer;
private Buffer mColorBuffer;
private int mCoordinateSize;
private int mCoordinateType;
private int mW;
private int mH;
private int mIndexCount;
private boolean mUseHardwareBuffers;
private int mVertBufferIndex;
private int mIndexBufferIndex;
private int mTextureCoordBufferIndex;
private int mColorBufferIndex;
public Grid(int vertsAcross, int vertsDown, boolean useFixedPoint) {
if (vertsAcross < 0 || vertsAcross >= 65536) {
throw new IllegalArgumentException("vertsAcross");
}
if (vertsDown < 0 || vertsDown >= 65536) {
throw new IllegalArgumentException("vertsDown");
}
if (vertsAcross * vertsDown >= 65536) {
throw new IllegalArgumentException("vertsAcross * vertsDown >= 65536");
}
mUseHardwareBuffers = false;
mW = vertsAcross;
mH = vertsDown;
int size = vertsAcross * vertsDown;
final int FLOAT_SIZE = 4;
final int FIXED_SIZE = 4;
final int CHAR_SIZE = 2;
if (useFixedPoint) {
mFixedVertexBuffer = ByteBuffer.allocateDirect(FIXED_SIZE * size * 3)
.order(ByteOrder.nativeOrder()).asIntBuffer();
mFixedTexCoordBuffer = ByteBuffer.allocateDirect(FIXED_SIZE * size * 2)
.order(ByteOrder.nativeOrder()).asIntBuffer();
mFixedColorBuffer = ByteBuffer.allocateDirect(FIXED_SIZE * size * 4)
.order(ByteOrder.nativeOrder()).asIntBuffer();
mVertexBuffer = mFixedVertexBuffer;
mTexCoordBuffer = mFixedTexCoordBuffer;
mColorBuffer = mFixedColorBuffer;
mCoordinateSize = FIXED_SIZE;
mCoordinateType = GL10.GL_FIXED;
} else {
mFloatVertexBuffer = ByteBuffer.allocateDirect(FLOAT_SIZE * size * 3)
.order(ByteOrder.nativeOrder()).asFloatBuffer();
mFloatTexCoordBuffer = ByteBuffer.allocateDirect(FLOAT_SIZE * size * 2)
.order(ByteOrder.nativeOrder()).asFloatBuffer();
mFloatColorBuffer = ByteBuffer.allocateDirect(FLOAT_SIZE * size * 4)
.order(ByteOrder.nativeOrder()).asFloatBuffer();
mVertexBuffer = mFloatVertexBuffer;
mTexCoordBuffer = mFloatTexCoordBuffer;
mColorBuffer = mFloatColorBuffer;
mCoordinateSize = FLOAT_SIZE;
mCoordinateType = GL10.GL_FLOAT;
}
int quadW = mW - 1;
int quadH = mH - 1;
int quadCount = quadW * quadH;
int indexCount = quadCount * 6;
mIndexCount = indexCount;
mIndexBuffer = ByteBuffer.allocateDirect(CHAR_SIZE * indexCount)
.order(ByteOrder.nativeOrder()).asCharBuffer();
/*
* Initialize triangle list mesh.
*
* [0]-----[ 1] ...
* | / |
* | / |
* | / |
* [w]-----[w+1] ...
* | |
*
*/
{
int i = 0;
for (int y = 0; y < quadH; y++) {
for (int x = 0; x < quadW; x++) {
char a = (char) (y * mW + x);
char b = (char) (y * mW + x + 1);
char c = (char) ((y + 1) * mW + x);
char d = (char) ((y + 1) * mW + x + 1);
mIndexBuffer.put(i++, a);
mIndexBuffer.put(i++, b);
mIndexBuffer.put(i++, c);
mIndexBuffer.put(i++, b);
mIndexBuffer.put(i++, c);
mIndexBuffer.put(i++, d);
}
}
}
mVertBufferIndex = 0;
}
void set(int i, int j, float x, float y, float z, float u, float v, float[] color) {
if (i < 0 || i >= mW) {
throw new IllegalArgumentException("i");
}
if (j < 0 || j >= mH) {
throw new IllegalArgumentException("j");
}
final int index = mW * j + i;
final int posIndex = index * 3;
final int texIndex = index * 2;
final int colorIndex = index * 4;
if (mCoordinateType == GL10.GL_FLOAT) {
mFloatVertexBuffer.put(posIndex, x);
mFloatVertexBuffer.put(posIndex + 1, y);
mFloatVertexBuffer.put(posIndex + 2, z);
mFloatTexCoordBuffer.put(texIndex, u);
mFloatTexCoordBuffer.put(texIndex + 1, v);
if (color != null) {
mFloatColorBuffer.put(colorIndex, color[0]);
mFloatColorBuffer.put(colorIndex + 1, color[1]);
mFloatColorBuffer.put(colorIndex + 2, color[2]);
mFloatColorBuffer.put(colorIndex + 3, color[3]);
}
} else {
mFixedVertexBuffer.put(posIndex, (int)(x * (1 << 16)));
mFixedVertexBuffer.put(posIndex + 1, (int)(y * (1 << 16)));
mFixedVertexBuffer.put(posIndex + 2, (int)(z * (1 << 16)));
mFixedTexCoordBuffer.put(texIndex, (int)(u * (1 << 16)));
mFixedTexCoordBuffer.put(texIndex + 1, (int)(v * (1 << 16)));
if (color != null) {
mFixedColorBuffer.put(colorIndex, (int)(color[0] * (1 << 16)));
mFixedColorBuffer.put(colorIndex + 1, (int)(color[1] * (1 << 16)));
mFixedColorBuffer.put(colorIndex + 2, (int)(color[2] * (1 << 16)));
mFixedColorBuffer.put(colorIndex + 3, (int)(color[3] * (1 << 16)));
}
}
}
public static void beginDrawing(GL10 gl, boolean useTexture, boolean useColor) {
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
if (useTexture) {
gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
gl.glEnable(GL10.GL_TEXTURE_2D);
} else {
gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
gl.glDisable(GL10.GL_TEXTURE_2D);
}
if (useColor) {
gl.glEnableClientState(GL10.GL_COLOR_ARRAY);
} else {
gl.glDisableClientState(GL10.GL_COLOR_ARRAY);
}
}
public void draw(GL10 gl, boolean useTexture, boolean useColor) {
if (!mUseHardwareBuffers) {
gl.glVertexPointer(3, mCoordinateType, 0, mVertexBuffer);
if (useTexture) {
gl.glTexCoordPointer(2, mCoordinateType, 0, mTexCoordBuffer);
}
if (useColor) {
gl.glColorPointer(4, mCoordinateType, 0, mColorBuffer);
}
gl.glDrawElements(GL10.GL_TRIANGLES, mIndexCount,
GL10.GL_UNSIGNED_SHORT, mIndexBuffer);
} else {
GL11 gl11 = (GL11)gl;
// draw using hardware buffers
gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, mVertBufferIndex);
gl11.glVertexPointer(3, mCoordinateType, 0, 0);
if (useTexture) {
gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, mTextureCoordBufferIndex);
gl11.glTexCoordPointer(2, mCoordinateType, 0, 0);
}
if (useColor) {
gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, mColorBufferIndex);
gl11.glColorPointer(4, mCoordinateType, 0, 0);
}
gl11.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, mIndexBufferIndex);
gl11.glDrawElements(GL11.GL_TRIANGLES, mIndexCount,
GL11.GL_UNSIGNED_SHORT, 0);
gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, 0);
gl11.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, 0);
}
}
public static void endDrawing(GL10 gl) {
gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);
}
public boolean usingHardwareBuffers() {
return mUseHardwareBuffers;
}
/**
* When the OpenGL ES device is lost, GL handles become invalidated.
* In that case, we just want to "forget" the old handles (without
* explicitly deleting them) and make new ones.
*/
public void invalidateHardwareBuffers() {
mVertBufferIndex = 0;
mIndexBufferIndex = 0;
mTextureCoordBufferIndex = 0;
mColorBufferIndex = 0;
mUseHardwareBuffers = false;
}
/**
* Deletes the hardware buffers allocated by this object (if any).
*/
public void releaseHardwareBuffers(GL10 gl) {
if (mUseHardwareBuffers) {
if (gl instanceof GL11) {
GL11 gl11 = (GL11)gl;
int[] buffer = new int[1];
buffer[0] = mVertBufferIndex;
gl11.glDeleteBuffers(1, buffer, 0);
buffer[0] = mTextureCoordBufferIndex;
gl11.glDeleteBuffers(1, buffer, 0);
buffer[0] = mColorBufferIndex;
gl11.glDeleteBuffers(1, buffer, 0);
buffer[0] = mIndexBufferIndex;
gl11.glDeleteBuffers(1, buffer, 0);
}
invalidateHardwareBuffers();
}
}
/**
* Allocates hardware buffers on the graphics card and fills them with
* data if a buffer has not already been previously allocated. Note that
* this function uses the GL_OES_vertex_buffer_object extension, which is
* not guaranteed to be supported on every device.
* @param gl A pointer to the OpenGL ES context.
*/
public void generateHardwareBuffers(GL10 gl) {
if (!mUseHardwareBuffers) {
if (gl instanceof GL11) {
GL11 gl11 = (GL11)gl;
int[] buffer = new int[1];
// Allocate and fill the vertex buffer.
gl11.glGenBuffers(1, buffer, 0);
mVertBufferIndex = buffer[0];
gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, mVertBufferIndex);
final int vertexSize = mVertexBuffer.capacity() * mCoordinateSize;
gl11.glBufferData(GL11.GL_ARRAY_BUFFER, vertexSize,
mVertexBuffer, GL11.GL_STATIC_DRAW);
// Allocate and fill the texture coordinate buffer.
gl11.glGenBuffers(1, buffer, 0);
mTextureCoordBufferIndex = buffer[0];
gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER,
mTextureCoordBufferIndex);
final int texCoordSize =
mTexCoordBuffer.capacity() * mCoordinateSize;
gl11.glBufferData(GL11.GL_ARRAY_BUFFER, texCoordSize,
mTexCoordBuffer, GL11.GL_STATIC_DRAW);
// Allocate and fill the color buffer.
gl11.glGenBuffers(1, buffer, 0);
mColorBufferIndex = buffer[0];
gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER,
mColorBufferIndex);
final int colorSize =
mColorBuffer.capacity() * mCoordinateSize;
gl11.glBufferData(GL11.GL_ARRAY_BUFFER, colorSize,
mColorBuffer, GL11.GL_STATIC_DRAW);
// Unbind the array buffer.
gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, 0);
// Allocate and fill the index buffer.
gl11.glGenBuffers(1, buffer, 0);
mIndexBufferIndex = buffer[0];
gl11.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER,
mIndexBufferIndex);
// A char is 2 bytes.
final int indexSize = mIndexBuffer.capacity() * 2;
gl11.glBufferData(GL11.GL_ELEMENT_ARRAY_BUFFER, indexSize, mIndexBuffer,
GL11.GL_STATIC_DRAW);
// Unbind the element array buffer.
gl11.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, 0);
mUseHardwareBuffers = true;
assert mVertBufferIndex != 0;
assert mTextureCoordBufferIndex != 0;
assert mIndexBufferIndex != 0;
assert gl11.glGetError() == 0;
}
}
}
// These functions exposed to patch Grid info into native code.
public final int getVertexBuffer() {
return mVertBufferIndex;
}
public final int getTextureBuffer() {
return mTextureCoordBufferIndex;
}
public final int getIndexBuffer() {
return mIndexBufferIndex;
}
public final int getColorBuffer() {
return mColorBufferIndex;
}
public final int getIndexCount() {
return mIndexCount;
}
public boolean getFixedPoint() {
return (mCoordinateType == GL10.GL_FIXED);
}
}
| Java |
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.spritemethodtest;
import java.io.IOException;
import java.io.InputStream;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.DisplayMetrics;
/**
* Activity for testing Canvas drawing speed. This activity sets up sprites and
* passes them off to a CanvasSurfaceView for rendering and movement. It is
* very similar to OpenGLTestActivity. Note that Bitmap objects come out of a
* pool and must be explicitly recycled on shutdown. See onDestroy().
*/
public class CanvasTestActivity extends Activity {
private CanvasSurfaceView mCanvasSurfaceView;
// Describes the image format our bitmaps should be converted to.
private static BitmapFactory.Options sBitmapOptions
= new BitmapFactory.Options();
private Bitmap[] mBitmaps;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mCanvasSurfaceView = new CanvasSurfaceView(this);
SimpleCanvasRenderer spriteRenderer = new SimpleCanvasRenderer();
// Sets our preferred image format to 16-bit, 565 format.
sBitmapOptions.inPreferredConfig = Bitmap.Config.RGB_565;
// Clear out any old profile results.
ProfileRecorder.sSingleton.resetAll();
final Intent callingIntent = getIntent();
// Allocate our sprites and add them to an array.
final int robotCount = callingIntent.getIntExtra("spriteCount", 10);
final boolean animate = callingIntent.getBooleanExtra("animate", true);
// Allocate space for the robot sprites + one background sprite.
CanvasSprite[] spriteArray = new CanvasSprite[robotCount + 1];
mBitmaps = new Bitmap[4];
mBitmaps[0] = loadBitmap(this, R.drawable.background);
mBitmaps[1] = loadBitmap(this, R.drawable.skate1);
mBitmaps[2] = loadBitmap(this, R.drawable.skate2);
mBitmaps[3] = loadBitmap(this, R.drawable.skate3);
// We need to know the width and height of the display pretty soon,
// so grab the information now.
DisplayMetrics dm = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
// Make the background.
// Note that the background image is larger than the screen,
// so some clipping will occur when it is drawn.
CanvasSprite background = new CanvasSprite(mBitmaps[0]);
background.width = mBitmaps[0].getWidth();
background.height = mBitmaps[0].getHeight();
spriteArray[0] = background;
// This list of things to move. It points to the same content as
// spriteArray except for the background.
Renderable[] renderableArray = new Renderable[robotCount];
final int robotBucketSize = robotCount / 3;
for (int x = 0; x < robotCount; x++) {
CanvasSprite robot;
// Our robots come in three flavors. Split them up accordingly.
if (x < robotBucketSize) {
robot = new CanvasSprite(mBitmaps[1]);
} else if (x < robotBucketSize * 2) {
robot = new CanvasSprite(mBitmaps[2]);
} else {
robot = new CanvasSprite(mBitmaps[3]);
}
robot.width = 64;
robot.height = 64;
// Pick a random location for this sprite.
robot.x = (float)(Math.random() * dm.widthPixels);
robot.y = (float)(Math.random() * dm.heightPixels);
// Add this robot to the spriteArray so it gets drawn and to the
// renderableArray so that it gets moved.
spriteArray[x + 1] = robot;
renderableArray[x] = robot;
}
// Now's a good time to run the GC. Since we won't do any explicit
// allocation during the test, the GC should stay dormant and not
// influence our results.
Runtime r = Runtime.getRuntime();
r.gc();
spriteRenderer.setSprites(spriteArray);
mCanvasSurfaceView.setRenderer(spriteRenderer);
if (animate) {
Mover simulationRuntime = new Mover();
simulationRuntime.setRenderables(renderableArray);
simulationRuntime.setViewSize(dm.widthPixels, dm.heightPixels);
mCanvasSurfaceView.setEvent(simulationRuntime);
}
setContentView(mCanvasSurfaceView);
}
/** Recycles all of the bitmaps loaded in onCreate(). */
@Override
protected void onDestroy() {
super.onDestroy();
mCanvasSurfaceView.clearEvent();
mCanvasSurfaceView.stopDrawing();
for (int x = 0; x < mBitmaps.length; x++) {
mBitmaps[x].recycle();
mBitmaps[x] = null;
}
}
/**
* Loads a bitmap from a resource and converts it to a bitmap. This is
* a much-simplified version of the loadBitmap() that appears in
* SimpleGLRenderer.
* @param context The application context.
* @param resourceId The id of the resource to load.
* @return A bitmap containing the image contents of the resource, or null
* if there was an error.
*/
protected Bitmap loadBitmap(Context context, int resourceId) {
Bitmap bitmap = null;
if (context != null) {
InputStream is = context.getResources().openRawResource(resourceId);
try {
bitmap = BitmapFactory.decodeStream(is, null, sBitmapOptions);
} finally {
try {
is.close();
} catch (IOException e) {
// Ignore.
}
}
}
return bitmap;
}
}
| Java |
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
// This file was lifted from the APIDemos sample. See:
// http://developer.android.com/guide/samples/ApiDemos/src/com/example/android/apis/graphics/index.html
package com.android.spritemethodtest;
import java.util.concurrent.Semaphore;
import javax.microedition.khronos.egl.EGL10;
import javax.microedition.khronos.egl.EGL11;
import javax.microedition.khronos.egl.EGLConfig;
import javax.microedition.khronos.egl.EGLContext;
import javax.microedition.khronos.egl.EGLDisplay;
import javax.microedition.khronos.egl.EGLSurface;
import javax.microedition.khronos.opengles.GL;
import javax.microedition.khronos.opengles.GL10;
import android.content.Context;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
/**
* An implementation of SurfaceView that uses the dedicated surface for
* displaying an OpenGL animation. This allows the animation to run in a
* separate thread, without requiring that it be driven by the update mechanism
* of the view hierarchy.
*
* The application-specific rendering code is delegated to a GLView.Renderer
* instance.
*/
public class GLSurfaceView extends SurfaceView implements SurfaceHolder.Callback {
public GLSurfaceView(Context context) {
super(context);
init();
}
public GLSurfaceView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
// Install a SurfaceHolder.Callback so we get notified when the
// underlying surface is created and destroyed
mHolder = getHolder();
mHolder.addCallback(this);
mHolder.setType(SurfaceHolder.SURFACE_TYPE_GPU);
}
public SurfaceHolder getSurfaceHolder() {
return mHolder;
}
public void setGLWrapper(GLWrapper glWrapper) {
mGLWrapper = glWrapper;
}
public void setRenderer(Renderer renderer) {
mGLThread = new GLThread(renderer);
mGLThread.start();
}
public void surfaceCreated(SurfaceHolder holder) {
mGLThread.surfaceCreated();
}
public void surfaceDestroyed(SurfaceHolder holder) {
// Surface will be destroyed when we return
mGLThread.surfaceDestroyed();
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
// Surface size or format has changed. This should not happen in this
// example.
mGLThread.onWindowResize(w, h);
}
/**
* Inform the view that the activity is paused.
*/
public void onPause() {
mGLThread.onPause();
}
/**
* Inform the view that the activity is resumed.
*/
public void onResume() {
mGLThread.onResume();
}
/**
* Inform the view that the window focus has changed.
*/
@Override public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
mGLThread.onWindowFocusChanged(hasFocus);
}
/**
* Set an "event" to be run on the GL rendering thread.
* @param r the runnable to be run on the GL rendering thread.
*/
public void setEvent(Runnable r) {
mGLThread.setEvent(r);
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
mGLThread.requestExitAndWait();
}
// ----------------------------------------------------------------------
public interface GLWrapper {
GL wrap(GL gl);
}
// ----------------------------------------------------------------------
/**
* A generic renderer interface.
*/
public interface Renderer {
/**
* @return the EGL configuration specification desired by the renderer.
*/
int[] getConfigSpec();
/**
* Surface created.
* Called when the surface is created. Called when the application
* starts, and whenever the GPU is reinitialized. This will
* typically happen when the device awakes after going to sleep.
* Set your textures here.
*/
void surfaceCreated(GL10 gl);
/**
* Called when the rendering thread is about to shut down. This is a
* good place to release OpenGL ES resources (textures, buffers, etc).
* @param gl
*/
void shutdown(GL10 gl);
/**
* Surface changed size.
* Called after the surface is created and whenever
* the OpenGL ES surface size changes. Set your viewport here.
* @param gl
* @param width
* @param height
*/
void sizeChanged(GL10 gl, int width, int height);
/**
* Draw the current frame.
* @param gl
*/
void drawFrame(GL10 gl);
}
/**
* An EGL helper class.
*/
private class EglHelper {
public EglHelper() {
}
/**
* Initialize EGL for a given configuration spec.
* @param configSpec
*/
public void start(int[] configSpec){
/*
* Get an EGL instance
*/
mEgl = (EGL10) EGLContext.getEGL();
/*
* Get to the default display.
*/
mEglDisplay = mEgl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY);
/*
* We can now initialize EGL for that display
*/
int[] version = new int[2];
mEgl.eglInitialize(mEglDisplay, version);
EGLConfig[] configs = new EGLConfig[1];
int[] num_config = new int[1];
mEgl.eglChooseConfig(mEglDisplay, configSpec, configs, 1,
num_config);
mEglConfig = configs[0];
/*
* Create an OpenGL ES context. This must be done only once, an
* OpenGL context is a somewhat heavy object.
*/
mEglContext = mEgl.eglCreateContext(mEglDisplay, mEglConfig,
EGL10.EGL_NO_CONTEXT, null);
mEglSurface = null;
}
/*
* Create and return an OpenGL surface
*/
public GL createSurface(SurfaceHolder holder) {
/*
* The window size has changed, so we need to create a new
* surface.
*/
if (mEglSurface != null) {
/*
* Unbind and destroy the old EGL surface, if
* there is one.
*/
mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE,
EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT);
mEgl.eglDestroySurface(mEglDisplay, mEglSurface);
}
/*
* Create an EGL surface we can render into.
*/
mEglSurface = mEgl.eglCreateWindowSurface(mEglDisplay,
mEglConfig, holder, null);
/*
* Before we can issue GL commands, we need to make sure
* the context is current and bound to a surface.
*/
mEgl.eglMakeCurrent(mEglDisplay, mEglSurface, mEglSurface,
mEglContext);
GL gl = mEglContext.getGL();
if (mGLWrapper != null) {
gl = mGLWrapper.wrap(gl);
}
return gl;
}
/**
* Display the current render surface.
* @return false if the context has been lost.
*/
public boolean swap() {
mEgl.eglSwapBuffers(mEglDisplay, mEglSurface);
/*
* Always check for EGL_CONTEXT_LOST, which means the context
* and all associated data were lost (For instance because
* the device went to sleep). We need to sleep until we
* get a new surface.
*/
return mEgl.eglGetError() != EGL11.EGL_CONTEXT_LOST;
}
public void finish() {
if (mEglSurface != null) {
mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE,
EGL10.EGL_NO_SURFACE,
EGL10.EGL_NO_CONTEXT);
mEgl.eglDestroySurface(mEglDisplay, mEglSurface);
mEglSurface = null;
}
if (mEglContext != null) {
mEgl.eglDestroyContext(mEglDisplay, mEglContext);
mEglContext = null;
}
if (mEglDisplay != null) {
mEgl.eglTerminate(mEglDisplay);
mEglDisplay = null;
}
}
EGL10 mEgl;
EGLDisplay mEglDisplay;
EGLSurface mEglSurface;
EGLConfig mEglConfig;
EGLContext mEglContext;
}
/**
* A generic GL Thread. Takes care of initializing EGL and GL. Delegates
* to a Renderer instance to do the actual drawing.
*
*/
class GLThread extends Thread {
GLThread(Renderer renderer) {
super();
mDone = false;
mWidth = 0;
mHeight = 0;
mRenderer = renderer;
setName("GLThread");
}
@Override
public void run() {
/*
* When the android framework launches a second instance of
* an activity, the new instance's onCreate() method may be
* called before the first instance returns from onDestroy().
*
* This semaphore ensures that only one instance at a time
* accesses EGL.
*/
try {
try {
sEglSemaphore.acquire();
} catch (InterruptedException e) {
return;
}
guardedRun();
} catch (InterruptedException e) {
// fall thru and exit normally
} finally {
sEglSemaphore.release();
}
}
private void guardedRun() throws InterruptedException {
mEglHelper = new EglHelper();
/*
* Specify a configuration for our opengl session
* and grab the first configuration that matches is
*/
int[] configSpec = mRenderer.getConfigSpec();
mEglHelper.start(configSpec);
GL10 gl = null;
boolean tellRendererSurfaceCreated = true;
boolean tellRendererSurfaceChanged = true;
/*
* This is our main activity thread's loop, we go until
* asked to quit.
*/
while (!mDone) {
ProfileRecorder.sSingleton.start(ProfileRecorder.PROFILE_FRAME);
/*
* Update the asynchronous state (window size)
*/
int w, h;
boolean changed;
boolean needStart = false;
synchronized (this) {
if (mEvent != null) {
ProfileRecorder.sSingleton.start(ProfileRecorder.PROFILE_SIM);
mEvent.run();
ProfileRecorder.sSingleton.stop(ProfileRecorder.PROFILE_SIM);
}
if (mPaused) {
mEglHelper.finish();
needStart = true;
}
if(needToWait()) {
while (needToWait()) {
wait();
}
}
if (mDone) {
break;
}
changed = mSizeChanged;
w = mWidth;
h = mHeight;
mSizeChanged = false;
}
if (needStart) {
mEglHelper.start(configSpec);
tellRendererSurfaceCreated = true;
changed = true;
}
if (changed) {
gl = (GL10) mEglHelper.createSurface(mHolder);
tellRendererSurfaceChanged = true;
}
if (tellRendererSurfaceCreated) {
mRenderer.surfaceCreated(gl);
tellRendererSurfaceCreated = false;
}
if (tellRendererSurfaceChanged) {
mRenderer.sizeChanged(gl, w, h);
tellRendererSurfaceChanged = false;
}
if ((w > 0) && (h > 0)) {
ProfileRecorder.sSingleton.start(ProfileRecorder.PROFILE_DRAW);
/* draw a frame here */
mRenderer.drawFrame(gl);
ProfileRecorder.sSingleton.stop(ProfileRecorder.PROFILE_DRAW);
/*
* Once we're done with GL, we need to call swapBuffers()
* to instruct the system to display the rendered frame
*/
ProfileRecorder.sSingleton.start(ProfileRecorder.PROFILE_PAGE_FLIP);
mEglHelper.swap();
ProfileRecorder.sSingleton.stop(ProfileRecorder.PROFILE_PAGE_FLIP);
}
ProfileRecorder.sSingleton.stop(ProfileRecorder.PROFILE_FRAME);
ProfileRecorder.sSingleton.endFrame();
}
/*
* clean-up everything...
*/
if (gl != null) {
mRenderer.shutdown(gl);
}
mEglHelper.finish();
}
private boolean needToWait() {
return (mPaused || (! mHasFocus) || (! mHasSurface) || mContextLost)
&& (! mDone);
}
public void surfaceCreated() {
synchronized(this) {
mHasSurface = true;
mContextLost = false;
notify();
}
}
public void surfaceDestroyed() {
synchronized(this) {
mHasSurface = false;
notify();
}
}
public void onPause() {
synchronized (this) {
mPaused = true;
}
}
public void onResume() {
synchronized (this) {
mPaused = false;
notify();
}
}
public void onWindowFocusChanged(boolean hasFocus) {
synchronized (this) {
mHasFocus = hasFocus;
if (mHasFocus == true) {
notify();
}
}
}
public void onWindowResize(int w, int h) {
synchronized (this) {
mWidth = w;
mHeight = h;
mSizeChanged = true;
}
}
public void requestExitAndWait() {
// don't call this from GLThread thread or it is a guaranteed
// deadlock!
synchronized(this) {
mDone = true;
notify();
}
try {
join();
} catch (InterruptedException ex) {
Thread.currentThread().interrupt();
}
}
/**
* Queue an "event" to be run on the GL rendering thread.
* @param r the runnable to be run on the GL rendering thread.
*/
public void setEvent(Runnable r) {
synchronized(this) {
mEvent = r;
}
}
public void clearEvent() {
synchronized(this) {
mEvent = null;
}
}
private boolean mDone;
private boolean mPaused;
private boolean mHasFocus;
private boolean mHasSurface;
private boolean mContextLost;
private int mWidth;
private int mHeight;
private Renderer mRenderer;
private Runnable mEvent;
private EglHelper mEglHelper;
}
private static final Semaphore sEglSemaphore = new Semaphore(1);
private boolean mSizeChanged = true;
private SurfaceHolder mHolder;
private GLThread mGLThread;
private GLWrapper mGLWrapper;
}
| Java |
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.spritemethodtest;
import android.content.Context;
import android.graphics.Canvas;
import android.util.AttributeSet;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
/**
* Implements a surface view which writes updates to the surface's canvas using
* a separate rendering thread. This class is based heavily on GLSurfaceView.
*/
public class CanvasSurfaceView extends SurfaceView
implements SurfaceHolder.Callback {
private boolean mSizeChanged = true;
private SurfaceHolder mHolder;
private CanvasThread mCanvasThread;
public CanvasSurfaceView(Context context) {
super(context);
init();
}
public CanvasSurfaceView(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_NORMAL);
}
public SurfaceHolder getSurfaceHolder() {
return mHolder;
}
/** Sets the user's renderer and kicks off the rendering thread. */
public void setRenderer(Renderer renderer) {
mCanvasThread = new CanvasThread(mHolder, renderer);
mCanvasThread.start();
}
public void surfaceCreated(SurfaceHolder holder) {
mCanvasThread.surfaceCreated();
}
public void surfaceDestroyed(SurfaceHolder holder) {
// Surface will be destroyed when we return
mCanvasThread.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.
mCanvasThread.onWindowResize(w, h);
}
/** Inform the view that the activity is paused.*/
public void onPause() {
mCanvasThread.onPause();
}
/** Inform the view that the activity is resumed. */
public void onResume() {
mCanvasThread.onResume();
}
/** Inform the view that the window focus has changed. */
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
mCanvasThread.onWindowFocusChanged(hasFocus);
}
/**
* Set an "event" to be run on the rendering thread.
* @param r the runnable to be run on the rendering thread.
*/
public void setEvent(Runnable r) {
mCanvasThread.setEvent(r);
}
/** Clears the runnable event, if any, from the rendering thread. */
public void clearEvent() {
mCanvasThread.clearEvent();
}
@Override
protected void onDetachedFromWindow() {
super.onDetachedFromWindow();
mCanvasThread.requestExitAndWait();
}
protected void stopDrawing() {
mCanvasThread.requestExitAndWait();
}
// ----------------------------------------------------------------------
/** A generic renderer interface. */
public interface Renderer {
/**
* Surface changed size.
* Called after the surface is created and whenever
* the surface size changes. Set your viewport here.
* @param width
* @param height
*/
void sizeChanged(int width, int height);
/**
* Draw the current frame.
* @param canvas The target canvas to draw into.
*/
void drawFrame(Canvas canvas);
}
/**
* A generic Canvas rendering Thread. Delegates to a Renderer instance to do
* the actual drawing.
*/
class CanvasThread extends Thread {
private boolean mDone;
private boolean mPaused;
private boolean mHasFocus;
private boolean mHasSurface;
private boolean mContextLost;
private int mWidth;
private int mHeight;
private Renderer mRenderer;
private Runnable mEvent;
private SurfaceHolder mSurfaceHolder;
CanvasThread(SurfaceHolder holder, Renderer renderer) {
super();
mDone = false;
mWidth = 0;
mHeight = 0;
mRenderer = renderer;
mSurfaceHolder = holder;
setName("CanvasThread");
}
@Override
public void run() {
boolean tellRendererSurfaceChanged = true;
/*
* This is our main activity thread's loop, we go until
* asked to quit.
*/
final ProfileRecorder profiler = ProfileRecorder.sSingleton;
while (!mDone) {
profiler.start(ProfileRecorder.PROFILE_FRAME);
/*
* Update the asynchronous state (window size)
*/
int w;
int h;
synchronized (this) {
// If the user has set a runnable to run in this thread,
// execute it and record the amount of time it takes to
// run.
if (mEvent != null) {
profiler.start(ProfileRecorder.PROFILE_SIM);
mEvent.run();
profiler.stop(ProfileRecorder.PROFILE_SIM);
}
if(needToWait()) {
while (needToWait()) {
try {
wait();
} catch (InterruptedException e) {
}
}
}
if (mDone) {
break;
}
tellRendererSurfaceChanged = mSizeChanged;
w = mWidth;
h = mHeight;
mSizeChanged = false;
}
if (tellRendererSurfaceChanged) {
mRenderer.sizeChanged(w, h);
tellRendererSurfaceChanged = false;
}
if ((w > 0) && (h > 0)) {
// Get ready to draw.
// We record both lockCanvas() and unlockCanvasAndPost()
// as part of "page flip" time because either may block
// until the previous frame is complete.
profiler.start(ProfileRecorder.PROFILE_PAGE_FLIP);
Canvas canvas = mSurfaceHolder.lockCanvas();
profiler.start(ProfileRecorder.PROFILE_PAGE_FLIP);
if (canvas != null) {
// Draw a frame!
profiler.start(ProfileRecorder.PROFILE_DRAW);
mRenderer.drawFrame(canvas);
profiler.stop(ProfileRecorder.PROFILE_DRAW);
profiler.start(ProfileRecorder.PROFILE_PAGE_FLIP);
mSurfaceHolder.unlockCanvasAndPost(canvas);
profiler.stop(ProfileRecorder.PROFILE_PAGE_FLIP);
}
}
profiler.stop(ProfileRecorder.PROFILE_FRAME);
profiler.endFrame();
}
}
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 CanvasThread 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 rendering thread.
* @param r the runnable to be run on the rendering thread.
*/
public void setEvent(Runnable r) {
synchronized(this) {
mEvent = r;
}
}
public void clearEvent() {
synchronized(this) {
mEvent = null;
}
}
}
}
| Java |
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.spritemethodtest;
import android.graphics.Bitmap;
import android.graphics.Canvas;
/**
* The Canvas version of a sprite. This class keeps a pointer to a bitmap
* and draws it at the Sprite's current location.
*/
public class CanvasSprite extends Renderable {
private Bitmap mBitmap;
public CanvasSprite(Bitmap bitmap) {
mBitmap = bitmap;
}
public void draw(Canvas canvas) {
// The Canvas system uses a screen-space coordinate system, that is,
// 0,0 is the top-left point of the canvas. But in order to align
// with OpenGL's coordinate space (which places 0,0 and the lower-left),
// for this test I flip the y coordinate.
canvas.drawBitmap(mBitmap, x, canvas.getHeight() - (y + height), null);
}
}
| Java |
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.spritemethodtest;
/**
* Base class defining the core set of information necessary to render (and move
* an object on the screen. This is an abstract type and must be derived to
* add methods to actually draw (see CanvasSprite and GLSprite).
*/
public abstract class Renderable {
// Position.
public float x;
public float y;
public float z;
// Velocity.
public float velocityX;
public float velocityY;
public float velocityZ;
// Size.
public float width;
public float height;
}
| Java |
/*
* Copyright (C) 2008 Jason Tomlinson.
*
* 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.example.amazed;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.Log;
/**
* Maze drawn on screen, each new level is loaded once the previous level has
* been completed.
*/
public class Maze {
// maze tile size and dimension
private final static int TILE_SIZE = 16;
private final static int MAZE_COLS = 20;
private final static int MAZE_ROWS = 26;
// tile types
public final static int PATH_TILE = 0;
public final static int VOID_TILE = 1;
public final static int EXIT_TILE = 2;
// tile colors
private final static int VOID_COLOR = Color.BLACK;
// maze level data
private static int[] mMazeData;
// number of level
public final static int MAX_LEVELS = 10;
// current tile attributes
private Rect mRect = new Rect();
private int mRow;
private int mCol;
private int mX;
private int mY;
// tile bitmaps
private Bitmap mImgPath;
private Bitmap mImgExit;
/**
* Maze constructor.
*
* @param context
* Application context used to load images.
*/
Maze(Activity activity) {
// load bitmaps.
mImgPath = BitmapFactory.decodeResource(activity.getApplicationContext().getResources(),
R.drawable.path);
mImgExit = BitmapFactory.decodeResource(activity.getApplicationContext().getResources(),
R.drawable.exit);
}
/**
* Load specified maze level.
*
* @param activity
* Activity controlled the maze, we use this load the level data
* @param newLevel
* Maze level to be loaded.
*/
void load(Activity activity, int newLevel) {
// maze data is stored in the assets folder as level1.txt, level2.txt
// etc....
String mLevel = "level" + newLevel + ".txt";
InputStream is = null;
try {
// construct our maze data array.
mMazeData = new int[MAZE_ROWS * MAZE_COLS];
// attempt to load maze data.
is = activity.getAssets().open(mLevel);
// we need to loop through the input stream and load each tile for
// the current maze.
for (int i = 0; i < mMazeData.length; i++) {
// data is stored in unicode so we need to convert it.
mMazeData[i] = Character.getNumericValue(is.read());
// skip the "," and white space in our human readable file.
is.read();
is.read();
}
} catch (Exception e) {
Log.i("Maze", "load exception: " + e);
} finally {
closeStream(is);
}
}
/**
* Draw the maze.
*
* @param canvas
* Canvas object to draw too.
* @param paint
* Paint object used to draw with.
*/
public void draw(Canvas canvas, Paint paint) {
// loop through our maze and draw each tile individually.
for (int i = 0; i < mMazeData.length; i++) {
// calculate the row and column of the current tile.
mRow = i / MAZE_COLS;
mCol = i % MAZE_COLS;
// convert the row and column into actual x,y co-ordinates so we can
// draw it on screen.
mX = mCol * TILE_SIZE;
mY = mRow * TILE_SIZE;
// draw the actual tile based on type.
if (mMazeData[i] == PATH_TILE)
canvas.drawBitmap(mImgPath, mX, mY, paint);
else if (mMazeData[i] == EXIT_TILE)
canvas.drawBitmap(mImgExit, mX, mY, paint);
else if (mMazeData[i] == VOID_TILE) {
// since our "void" tile is purely black lets draw a rectangle
// instead of using an image.
// tile attributes we are going to paint.
mRect.left = mX;
mRect.top = mY;
mRect.right = mX + TILE_SIZE;
mRect.bottom = mY + TILE_SIZE;
paint.setColor(VOID_COLOR);
canvas.drawRect(mRect, paint);
}
}
}
/**
* Determine which cell the marble currently occupies.
*
* @param x
* Current x co-ordinate.
* @param y
* Current y co-ordinate.
* @return The actual cell occupied by the marble.
*/
public int getCellType(int x, int y) {
// convert the x,y co-ordinate into row and col values.
int mCellCol = x / TILE_SIZE;
int mCellRow = y / TILE_SIZE;
// location is the row,col coordinate converted so we know where in the
// maze array to look.
int mLocation = 0;
// if we are beyond the 1st row need to multiple by the number of
// columns.
if (mCellRow > 0)
mLocation = mCellRow * MAZE_COLS;
// add the column location.
mLocation += mCellCol;
return mMazeData[mLocation];
}
/**
* Closes the specified stream.
*
* @param stream
* The stream to close.
*/
private static void closeStream(Closeable stream) {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
// Ignore
}
}
}
} | Java |
/*
* Copyright (C) 2008 Jason Tomlinson.
*
* 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.example.amazed;
import android.app.Activity;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.hardware.SensorListener;
import android.hardware.SensorManager;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
/**
* Custom view used to draw the maze and marble. Responds to accelerometer
* updates to roll the marble around the screen.
*/
public class AmazedView extends View {
// Game objects
private Marble mMarble;
private Maze mMaze;
private Activity mActivity;
// canvas we paint to.
private Canvas mCanvas;
private Paint mPaint;
private Typeface mFont = Typeface.create(Typeface.SANS_SERIF, Typeface.BOLD);
private int mTextPadding = 10;
private int mHudTextY = 440;
// game states
private final static int NULL_STATE = -1;
private final static int GAME_INIT = 0;
private final static int GAME_RUNNING = 1;
private final static int GAME_OVER = 2;
private final static int GAME_COMPLETE = 3;
private final static int GAME_LANDSCAPE = 4;
// current state of the game
private static int mCurState = NULL_STATE;
// game strings
private final static int TXT_LIVES = 0;
private final static int TXT_LEVEL = 1;
private final static int TXT_TIME = 2;
private final static int TXT_TAP_SCREEN = 3;
private final static int TXT_GAME_COMPLETE = 4;
private final static int TXT_GAME_OVER = 5;
private final static int TXT_TOTAL_TIME = 6;
private final static int TXT_GAME_OVER_MSG_A = 7;
private final static int TXT_GAME_OVER_MSG_B = 8;
private final static int TXT_RESTART = 9;
private final static int TXT_LANDSCAPE_MODE = 10;
private static String mStrings[];
// this prevents the user from dying instantly when they start a level if
// the device is tilted.
private boolean mWarning = false;
// screen dimensions
private int mCanvasWidth = 0;
private int mCanvasHeight = 0;
private int mCanvasHalfWidth = 0;
private int mCanvasHalfHeight = 0;
// are we running in portrait mode.
private boolean mPortrait;
// current level
private int mlevel = 1;
// timing used for scoring.
private long mTotalTime = 0;
private long mStartTime = 0;
private long mEndTime = 0;
// sensor manager used to control the accelerometer sensor.
private SensorManager mSensorManager;
// accelerometer sensor values.
private float mAccelX = 0;
private float mAccelY = 0;
private float mAccelZ = 0; // this is never used but just in-case future
// versions make use of it.
// accelerometer buffer, currently set to 0 so even the slightest movement
// will roll the marble.
private float mSensorBuffer = 0;
// http://code.google.com/android/reference/android/hardware/SensorManager.html#SENSOR_ACCELEROMETER
// for an explanation on the values reported by SENSOR_ACCELEROMETER.
private final SensorListener mSensorAccelerometer = new SensorListener() {
// method called whenever new sensor values are reported.
public void onSensorChanged(int sensor, float[] values) {
// grab the values required to respond to user movement.
mAccelX = values[0];
mAccelY = values[1];
mAccelZ = values[2];
}
// reports when the accuracy of sensor has change
// SENSOR_STATUS_ACCURACY_HIGH = 3
// SENSOR_STATUS_ACCURACY_LOW = 1
// SENSOR_STATUS_ACCURACY_MEDIUM = 2
// SENSOR_STATUS_UNRELIABLE = 0 //calibration required.
public void onAccuracyChanged(int sensor, int accuracy) {
// currently not used
}
};
/**
* Custom view constructor.
*
* @param context
* Application context
* @param activity
* Activity controlling the view
*/
public AmazedView(Context context, Activity activity) {
super(context);
mActivity = activity;
// init paint and make is look "nice" with anti-aliasing.
mPaint = new Paint();
mPaint.setTextSize(14);
mPaint.setTypeface(mFont);
mPaint.setAntiAlias(true);
// setup accelerometer sensor manager.
mSensorManager = (SensorManager) activity.getSystemService(Context.SENSOR_SERVICE);
// register our accelerometer so we can receive values.
// SENSOR_DELAY_GAME is the recommended rate for games
mSensorManager.registerListener(mSensorAccelerometer, SensorManager.SENSOR_ACCELEROMETER,
SensorManager.SENSOR_DELAY_GAME);
// setup our maze and marble.
mMaze = new Maze(mActivity);
mMarble = new Marble(this);
// load array from /res/values/strings.xml
mStrings = getResources().getStringArray(R.array.gameStrings);
// set the starting state of the game.
switchGameState(GAME_INIT);
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
// get new screen dimensions.
mCanvasWidth = w;
mCanvasHeight = h;
mCanvasHalfWidth = w / 2;
mCanvasHalfHeight = h / 2;
// are we in portrait or landscape mode now?
// you could use bPortrait = !bPortrait however in the future who know's
// how many different ways a device screen may be rotated.
if (mCanvasHeight > mCanvasWidth)
mPortrait = true;
else {
mPortrait = false;
switchGameState(GAME_LANDSCAPE);
}
}
/**
* Called every cycle, used to process current game state.
*/
public void gameTick() {
// very basic state machine, makes a good foundation for a more complex
// game.
switch (mCurState) {
case GAME_INIT:
// prepare a new game for the user.
initNewGame();
switchGameState(GAME_RUNNING);
case GAME_RUNNING:
// update our marble.
if (!mWarning)
updateMarble();
break;
}
// redraw the screen once our tick function is complete.
invalidate();
}
/**
* Reset game variables in preparation for a new game.
*/
public void initNewGame() {
mMarble.setLives(5);
mTotalTime = 0;
mlevel = 0;
initLevel();
}
/**
* Initialize the next level.
*/
public void initLevel() {
if (mlevel < mMaze.MAX_LEVELS) {
// setup the next level.
mWarning = true;
mlevel++;
mMaze.load(mActivity, mlevel);
mMarble.init();
} else {
// user has finished the game, update state machine.
switchGameState(GAME_COMPLETE);
}
}
/**
* Called from gameTick(), update marble x,y based on latest values obtained
* from the Accelerometer sensor. AccelX and accelY are values received from
* the accelerometer, higher values represent the device tilted at a more
* acute angle.
*/
public void updateMarble() {
// we CAN give ourselves a buffer to stop the marble from rolling even
// though we think the device is "flat".
if (mAccelX > mSensorBuffer || mAccelX < -mSensorBuffer)
mMarble.updateX(mAccelX);
if (mAccelY > mSensorBuffer || mAccelY < -mSensorBuffer)
mMarble.updateY(mAccelY);
// check which cell the marble is currently occupying.
if (mMaze.getCellType(mMarble.getX(), mMarble.getY()) == mMaze.VOID_TILE) {
// user entered the "void".
if (mMarble.getLives() > 0) {
// user still has some lives remaining, restart the level.
mMarble.death();
mMarble.init();
mWarning = true;
} else {
// user has no more lives left, end of game.
mEndTime = System.currentTimeMillis();
mTotalTime += mEndTime - mStartTime;
switchGameState(GAME_OVER);
}
} else if (mMaze.getCellType(mMarble.getX(), mMarble.getY()) == mMaze.EXIT_TILE) {
// user has reached the exit tiles, prepare the next level.
mEndTime = System.currentTimeMillis();
mTotalTime += mEndTime - mStartTime;
initLevel();
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// we only want to handle down events .
if (event.getAction() == MotionEvent.ACTION_DOWN) {
if (mCurState == GAME_OVER || mCurState == GAME_COMPLETE) {
// re-start the game.
mCurState = GAME_INIT;
} else if (mCurState == GAME_RUNNING) {
// in-game, remove the pop-up text so user can play.
mWarning = false;
mStartTime = System.currentTimeMillis();
}
}
return true;
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// quit application if user presses the back key.
if (keyCode == KeyEvent.KEYCODE_BACK)
cleanUp();
return true;
}
@Override
public void onDraw(Canvas canvas) {
// update our canvas reference.
mCanvas = canvas;
// clear the screen.
mPaint.setColor(Color.WHITE);
mCanvas.drawRect(0, 0, mCanvasWidth, mCanvasHeight, mPaint);
// simple state machine, draw screen depending on the current state.
switch (mCurState) {
case GAME_RUNNING:
// draw our maze first since everything else appears "on top" of it.
mMaze.draw(mCanvas, mPaint);
// draw our marble and hud.
mMarble.draw(mCanvas, mPaint);
// draw hud
drawHUD();
break;
case GAME_OVER:
drawGameOver();
break;
case GAME_COMPLETE:
drawGameComplete();
break;
case GAME_LANDSCAPE:
drawLandscapeMode();
break;
}
gameTick();
}
/**
* Called from onDraw(), draws the in-game HUD
*/
public void drawHUD() {
mPaint.setColor(Color.BLACK);
mPaint.setTextAlign(Paint.Align.LEFT);
mCanvas.drawText(mStrings[TXT_TIME] + ": " + (mTotalTime / 1000), mTextPadding, mHudTextY,
mPaint);
mPaint.setTextAlign(Paint.Align.CENTER);
mCanvas.drawText(mStrings[TXT_LEVEL] + ": " + mlevel, mCanvasHalfWidth, mHudTextY, mPaint);
mPaint.setTextAlign(Paint.Align.RIGHT);
mCanvas.drawText(mStrings[TXT_LIVES] + ": " + mMarble.getLives(), mCanvasWidth - mTextPadding,
mHudTextY, mPaint);
// do we need to display the warning message to save the user from
// possibly dying instantly.
if (mWarning) {
mPaint.setColor(Color.BLUE);
mCanvas
.drawRect(0, mCanvasHalfHeight - 15, mCanvasWidth, mCanvasHalfHeight + 5,
mPaint);
mPaint.setColor(Color.WHITE);
mPaint.setTextAlign(Paint.Align.CENTER);
mCanvas.drawText(mStrings[TXT_TAP_SCREEN], mCanvasHalfWidth, mCanvasHalfHeight, mPaint);
}
}
/**
* Called from onDraw(), draws the game over screen.
*/
public void drawGameOver() {
mPaint.setColor(Color.BLACK);
mPaint.setTextAlign(Paint.Align.CENTER);
mCanvas.drawText(mStrings[TXT_GAME_OVER], mCanvasHalfWidth, mCanvasHalfHeight, mPaint);
mCanvas.drawText(mStrings[TXT_TOTAL_TIME] + ": " + (mTotalTime / 1000) + "s",
mCanvasHalfWidth, mCanvasHalfHeight + mPaint.getFontSpacing(), mPaint);
mCanvas.drawText(mStrings[TXT_GAME_OVER_MSG_A] + " " + (mlevel - 1) + " "
+ mStrings[TXT_GAME_OVER_MSG_B], mCanvasHalfWidth, mCanvasHalfHeight
+ (mPaint.getFontSpacing() * 2), mPaint);
mCanvas.drawText(mStrings[TXT_RESTART], mCanvasHalfWidth, mCanvasHeight
- (mPaint.getFontSpacing() * 3), mPaint);
}
/**
* Called from onDraw(), draws the game complete screen.
*/
public void drawGameComplete() {
mPaint.setColor(Color.BLACK);
mPaint.setTextAlign(Paint.Align.CENTER);
mCanvas.drawText(mStrings[GAME_COMPLETE], mCanvasHalfWidth, mCanvasHalfHeight, mPaint);
mCanvas.drawText(mStrings[TXT_TOTAL_TIME] + ": " + (mTotalTime / 1000) + "s",
mCanvasHalfWidth, mCanvasHalfHeight + mPaint.getFontSpacing(), mPaint);
mCanvas.drawText(mStrings[TXT_RESTART], mCanvasHalfWidth, mCanvasHeight
- (mPaint.getFontSpacing() * 3), mPaint);
}
/**
* Called from onDraw(), displays a message asking the user to return the
* device back to portrait mode.
*/
public void drawLandscapeMode() {
mPaint.setColor(Color.WHITE);
mPaint.setTextAlign(Paint.Align.CENTER);
mCanvas.drawRect(0, 0, mCanvasWidth, mCanvasHeight, mPaint);
mPaint.setColor(Color.BLACK);
mCanvas.drawText(mStrings[TXT_LANDSCAPE_MODE], mCanvasHalfWidth, mCanvasHalfHeight, mPaint);
}
/**
* Updates the current game state with a new state. At the moment this is
* very basic however if the game was to get more complicated the code
* required for changing game states could grow quickly.
*
* @param newState
* New game state
*/
public void switchGameState(int newState) {
mCurState = newState;
}
/**
* Register the accelerometer sensor so we can use it in-game.
*/
public void registerListener() {
mSensorManager.registerListener(mSensorAccelerometer, SensorManager.SENSOR_ACCELEROMETER,
SensorManager.SENSOR_DELAY_GAME);
}
/**
* Unregister the accelerometer sensor otherwise it will continue to operate
* and report values.
*/
public void unregisterListener() {
mSensorManager.unregisterListener(mSensorAccelerometer);
}
/**
* Clean up the custom view and exit the application.
*/
public void cleanUp() {
mMarble = null;
mMaze = null;
mStrings = null;
unregisterListener();
mActivity.finish();
}
} | Java |
/*
* Copyright (C) 2008 Jason Tomlinson.
*
* 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.example.amazed;
import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
/**
* Activity responsible for controlling the application.
*/
public class AmazedActivity extends Activity {
// custom view
private AmazedView mView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// remove title bar.
requestWindowFeature(Window.FEATURE_NO_TITLE);
// setup our view, give it focus and display.
mView = new AmazedView(getApplicationContext(), this);
mView.setFocusable(true);
setContentView(mView);
}
@Override
protected void onResume() {
super.onResume();
mView.registerListener();
}
@Override
public void onSaveInstanceState(Bundle icicle) {
super.onSaveInstanceState(icicle);
mView.unregisterListener();
}
} | Java |
/*
* Copyright (C) 2008 Jason Tomlinson.
*
* 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.example.amazed;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.view.View;
/**
* Marble drawn in the maze.
*/
public class Marble {
// View controlling the marble.
private View mView;
// marble attributes
// x,y are private because we need boundary checking on any new values to
// make sure they are valid.
private int mX = 0;
private int mY = 0;
private int mRadius = 8;
private int mColor = Color.WHITE;
private int mLives = 5;
/**
* Marble constructor.
*
* @param view
* View controlling the marble
*/
public Marble(View view) {
this.mView = view;
init();
}
/**
* Setup marble starting co-ords.
*/
public void init() {
mX = mRadius * 6;
mY = mRadius * 6;
}
/**
* Draw the marble.
*
* @param canvas
* Canvas object to draw too.
* @param paint
* Paint object used to draw with.
*/
public void draw(Canvas canvas, Paint paint) {
paint.setColor(mColor);
canvas.drawCircle(mX, mY, mRadius, paint);
}
/**
* Attempt to update the marble with a new x value, boundary checking
* enabled to make sure the new co-ordinate is valid.
*
* @param newX
* Incremental value to add onto current x co-ordinate.
*/
public void updateX(float newX) {
mX += newX;
// boundary checking, don't want the marble rolling off-screen.
if (mX + mRadius >= mView.getWidth())
mX = mView.getWidth() - mRadius;
else if (mX - mRadius < 0)
mX = mRadius;
}
/**
* Attempt to update the marble with a new y value, boundary checking
* enabled to make sure the new co-ordinate is valid.
*
* @param newY
* Incremental value to add onto current y co-ordinate.
*/
public void updateY(float newY) {
mY -= newY;
// boundary checking, don't want the marble rolling off-screen.
if (mY + mRadius >= mView.getHeight())
mY = mView.getHeight() - mRadius;
else if (mY - mRadius < 0)
mY = mRadius;
}
/**
* Marble has died
*/
public void death() {
mLives--;
}
/**
* Set the number of lives for the marble
*
* @param Number
* of lives
*/
public void setLives(int val) {
mLives = val;
}
/**
* @return Number of lives left
*/
public int getLives() {
return mLives;
}
/**
* @return Current x co-ordinate.
*/
public int getX() {
return mX;
}
/**
* @return Current y co-ordinate.
*/
public int getY() {
return mY;
}
} | 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.example.android.rings_extended;
import android.database.Cursor;
import android.database.DataSetObserver;
import android.util.SparseIntArray;
/**
* This class essentially helps in building an index of section boundaries of a
* sorted column of a cursor. For instance, if a cursor contains a data set
* sorted by first name of a person or the title of a song, this class will
* perform a binary search to identify the first row that begins with a
* particular letter. The search is case-insensitive. The class caches the index
* such that subsequent queries for the same letter will return right away.
*
* <p>This file was copied from the Contacts application. In the future it
* should be provided as a standard part of the Android framework.
*/
public class AlphabetIndexer extends DataSetObserver {
protected Cursor mDataCursor;
protected int mColumnIndex;
protected Object[] mAlphabetArray;
private SparseIntArray mAlphaMap;
private java.text.Collator mCollator;
/**
* Constructs the indexer.
* @param cursor the cursor containing the data set
* @param columnIndex the column number in the cursor that is sorted
* alphabetically
* @param sections the array of objects that represent the sections. The
* toString() method of each item is called and the first letter of the
* String is used as the letter to search for.
*/
public AlphabetIndexer(Cursor cursor, int columnIndex, Object[] sections) {
mDataCursor = cursor;
mColumnIndex = columnIndex;
mAlphabetArray = sections;
mAlphaMap = new SparseIntArray(26 /* Optimize for English */);
if (cursor != null) {
cursor.registerDataSetObserver(this);
}
// Get a Collator for the current locale for string comparisons.
mCollator = java.text.Collator.getInstance();
mCollator.setStrength(java.text.Collator.PRIMARY);
}
/**
* Sets a new cursor as the data set and resets the cache of indices.
* @param cursor the new cursor to use as the data set
*/
public void setCursor(Cursor cursor) {
if (mDataCursor != null) {
mDataCursor.unregisterDataSetObserver(this);
}
mDataCursor = cursor;
if (cursor != null) {
mDataCursor.registerDataSetObserver(this);
}
mAlphaMap.clear();
}
/**
* Performs a binary search or cache lookup to find the first row that
* matches a given section's starting letter.
* @param sectionIndex the section to search for
* @return the row index of the first occurrence, or the nearest next letter.
* For instance, if searching for "T" and no "T" is found, then the first
* row starting with "U" or any higher letter is returned. If there is no
* data following "T" at all, then the list size is returned.
*/
public int indexOf(int sectionIndex) {
final SparseIntArray alphaMap = mAlphaMap;
final Cursor cursor = mDataCursor;
if (cursor == null || mAlphabetArray == null) {
return 0;
}
// Check bounds
if (sectionIndex <= 0) {
return 0;
}
if (sectionIndex >= mAlphabetArray.length) {
sectionIndex = mAlphabetArray.length - 1;
}
int savedCursorPos = cursor.getPosition();
int count = cursor.getCount();
int start = 0;
int end = count;
int pos;
String letter = mAlphabetArray[sectionIndex].toString();
letter = letter.toUpperCase();
int key = letter.charAt(0);
// Check map
if (Integer.MIN_VALUE != (pos = alphaMap.get(key, Integer.MIN_VALUE))) {
// Is it approximate? Using negative value to indicate that it's
// an approximation and positive value when it is the accurate
// position.
if (pos < 0) {
pos = -pos;
end = pos;
} else {
// Not approximate, this is the confirmed start of section, return it
return pos;
}
}
// Do we have the position of the previous section?
if (sectionIndex > 0) {
int prevLetter =
mAlphabetArray[sectionIndex - 1].toString().charAt(0);
int prevLetterPos = alphaMap.get(prevLetter, Integer.MIN_VALUE);
if (prevLetterPos != Integer.MIN_VALUE) {
start = Math.abs(prevLetterPos);
}
}
// Now that we have a possibly optimized start and end, let's binary search
pos = (end + start) / 2;
while (pos < end) {
// Get letter at pos
cursor.moveToPosition(pos);
String curName = cursor.getString(mColumnIndex);
if (curName == null) {
if (pos == 0) {
break;
} else {
pos--;
continue;
}
}
int curLetter = Character.toUpperCase(curName.charAt(0));
if (curLetter != key) {
// Enter approximation in hash if a better solution doesn't exist
int curPos = alphaMap.get(curLetter, Integer.MIN_VALUE);
if (curPos == Integer.MIN_VALUE || Math.abs(curPos) > pos) {
// Negative pos indicates that it is an approximation
alphaMap.put(curLetter, -pos);
}
if (mCollator.compare(curName, letter) < 0) {
start = pos + 1;
if (start >= count) {
pos = count;
break;
}
} else {
end = pos;
}
} else {
// They're the same, but that doesn't mean it's the start
if (start == pos) {
// This is it
break;
} else {
// Need to go further lower to find the starting row
end = pos;
}
}
pos = (start + end) / 2;
}
alphaMap.put(key, pos);
cursor.moveToPosition(savedCursorPos);
return pos;
}
@Override
public void onChanged() {
super.onChanged();
mAlphaMap.clear();
}
@Override
public void onInvalidated() {
super.onInvalidated();
mAlphaMap.clear();
}
}
| Java |
package com.example.android.rings_extended;
import android.app.ListActivity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.drawable.Drawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Config;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* The RingsExtended application, implementing an advanced ringtone picker.
* This is a ListActivity display an adapter of dynamic state built by the
* activity: at the top are simple options the user can be picked, next an
* item to run the built-in ringtone picker, and next are any other activities
* that can supply music Uris.
*/
public class RingsExtended extends ListActivity
implements View.OnClickListener, MediaPlayer.OnCompletionListener {
static final boolean DBG = false;
static final String TAG = "RingsExtended";
/**
* Request code when we are launching an activity to handle our same
* original Intent, meaning we can propagate its result back to our caller
* as-is.
*/
static final int REQUEST_ORIGINAL = 2;
/**
* Request code when launching an activity that returns an audio Uri,
* meaning we need to translate its result into one that our caller
* expects.
*/
static final int REQUEST_SOUND = 1;
Adapter mAdapter;
private View mOkayButton;
private View mCancelButton;
/** Where the silent option item is in the list, or -1 if there is none. */
private int mSilentItemIdx = -1;
/** The Uri to play when the 'Default' item is clicked. */
private Uri mUriForDefaultItem;
/** Where the default option item is in the list, or -1 if there is none. */
private int mDefaultItemIdx = -1;
/** The Uri to place a checkmark next to. */
private Uri mExistingUri;
/** Where the existing option item is in the list. */
private int mExistingItemIdx;
/** Currently selected options in the radio buttons, if any. */
private long mSelectedItem = -1;
/** Loaded ringtone for the existing URI. */
private Ringtone mExistingRingtone;
/** Id of option that is currently playing. */
private long mPlayingId = -1;
/** Used for playing previews of ring tones. */
private MediaPlayer mMediaPlayer;
/**
* Information about one static item in the list. This is used for items
* that are added and handled manually, which don't have an Intent
* associated with them.
*/
final static class ItemInfo {
final CharSequence name;
final CharSequence subtitle;
final Drawable icon;
ItemInfo(CharSequence _name, CharSequence _subtitle, Drawable _icon) {
name = _name;
subtitle = _subtitle;
icon = _icon;
}
}
/**
* Our special adapter implementation, merging the various kinds of items
* that we will display into one list. There are two sections to the
* list of items:
* (1) First are any fixed items as described by ItemInfo objects.
* (2) Next are any activities that do the same thing as our own.
* (3) Finally are any activities that can execute a different Intent.
*/
private final class Adapter extends BaseAdapter {
private final List<ItemInfo> mInitialItems;
private final Intent mIntent;
private final Intent mOrigIntent;
private final LayoutInflater mInflater;
private List<ResolveInfo> mList;
private int mRealListStart = 0;
class ViewHolder {
ImageView icon;
RadioButton radio;
TextView textSingle;
TextView textDouble1;
TextView textDouble2;
ImageView more;
}
/**
* Create a new adapter with the items to be displayed.
*
* @param context The Context we are running in.
* @param initialItems A fixed set of items that appear at the
* top of the list.
* @param origIntent The original Intent that was used to launch this
* activity, used to find all activities that can do the same thing.
* @param excludeOrigIntent Our component name, to exclude from the
* origIntent list since that is what the user is already running!
* @param intent An Intent used to query for additional items to
* appear in the rest of the list.
*/
public Adapter(Context context, List<ItemInfo> initialItems,
Intent origIntent, ComponentName excludeOrigIntent, Intent intent) {
mInitialItems = initialItems;
mIntent = new Intent(intent);
mIntent.setComponent(null);
mIntent.setFlags(0);
if (origIntent != null) {
mOrigIntent = new Intent(origIntent);
mOrigIntent.setComponent(null);
mOrigIntent.setFlags(0);
} else {
mOrigIntent = null;
}
mInflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
mList = getActivities(context, mIntent, null);
if (origIntent != null) {
List<ResolveInfo> orig = getActivities(context, mOrigIntent,
excludeOrigIntent);
if (orig != null && orig.size() > 0) {
mRealListStart = orig.size();
orig.addAll(mList);
mList = orig;
}
}
}
/**
* If the position is within the range of initial items, return the
* corresponding index into that array. Otherwise return -1.
*/
public int initialItemForPosition(int position) {
if (position >= getIntentStartIndex()) {
return -1;
}
return position;
}
/**
* Returns true if the given position is for one of the
* "original intent" items.
*/
public boolean isOrigIntentPosition(int position) {
position -= getIntentStartIndex();
return position >= 0 && position < mRealListStart;
}
/**
* Returns the ResolveInfo corresponding to the given position, or null
* if that position is not an Intent item (that is if it is one
* of the static list items).
*/
public ResolveInfo resolveInfoForPosition(int position) {
position -= getIntentStartIndex();
if (mList == null || position < 0) {
return null;
}
return mList.get(position);
}
/**
* Returns the Intent corresponding to the given position, or null
* if that position is not an Intent item (that is if it is one
* of the static list items).
*/
public Intent intentForPosition(int position) {
position -= getIntentStartIndex();
if (mList == null || position < 0) {
return null;
}
Intent intent = new Intent(
position >= mRealListStart ? mIntent : mOrigIntent);
ActivityInfo ai = mList.get(position).activityInfo;
intent.setComponent(new ComponentName(
ai.applicationInfo.packageName, ai.name));
return intent;
}
public int getCount() {
return getIntentStartIndex() + (mList != null ? mList.size() : 0);
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
View view;
if (convertView == null) {
view = mInflater.inflate(R.layout.list_item, parent, false);
ViewHolder vh = new ViewHolder();
vh.icon = (ImageView)view.findViewById(R.id.icon);
vh.radio = (RadioButton)view.findViewById(R.id.radio);
vh.textSingle = (TextView)view.findViewById(R.id.textSingle);
vh.textDouble1 = (TextView)view.findViewById(R.id.textDouble1);
vh.textDouble2 = (TextView)view.findViewById(R.id.textDouble2);
vh.more = (ImageView)view.findViewById(R.id.more);
view.setTag(vh);
} else {
view = convertView;
}
int intentStart = getIntentStartIndex();
if (position < intentStart) {
bindView(view, position, mInitialItems.get(position));
} else {
bindView(view, mList.get(position-intentStart));
}
return view;
}
private final int getIntentStartIndex() {
return mInitialItems != null ? mInitialItems.size() : 0;
}
private final void bindView(View view, ResolveInfo info) {
PackageManager pm = getPackageManager();
ViewHolder vh = (ViewHolder)view.getTag();
CharSequence label = info.loadLabel(pm);
if (label == null) label = info.activityInfo.name;
bindTextViews(vh, label, null);
vh.icon.setImageDrawable(info.loadIcon(pm));
vh.icon.setVisibility(View.VISIBLE);
vh.radio.setVisibility(View.GONE);
vh.more.setImageResource(R.drawable.icon_more);
vh.more.setVisibility(View.VISIBLE);
}
private final void bindTextViews(ViewHolder vh, CharSequence txt1,
CharSequence txt2) {
if (txt2 == null) {
vh.textSingle.setText(txt1);
vh.textSingle.setVisibility(View.VISIBLE);
vh.textDouble1.setVisibility(View.INVISIBLE);
vh.textDouble2.setVisibility(View.INVISIBLE);
} else {
vh.textDouble1.setText(txt1);
vh.textDouble1.setVisibility(View.VISIBLE);
vh.textDouble2.setText(txt2);
vh.textDouble2.setVisibility(View.VISIBLE);
vh.textSingle.setVisibility(View.INVISIBLE);
}
}
private final void bindView(View view, int position, ItemInfo inf) {
ViewHolder vh = (ViewHolder)view.getTag();
bindTextViews(vh, inf.name, inf.subtitle);
// Set the standard icon and radio button. When the radio button
// is displayed, we mark it if this is the currently selected row,
// meaning we need to invalidate the view list whenever the
// selection changes.
if (inf.icon != null) {
vh.icon.setImageDrawable(inf.icon);
vh.icon.setVisibility(View.VISIBLE);
vh.radio.setVisibility(View.GONE);
} else {
vh.icon.setVisibility(View.GONE);
vh.radio.setVisibility(View.VISIBLE);
vh.radio.setChecked(position == mSelectedItem);
}
// Show the "now playing" icon if this item is playing. Doing this
// means that we need to invalidate the displayed views when the
// playing state changes.
if (mPlayingId == position) {
vh.more.setImageResource(R.drawable.now_playing);
vh.more.setVisibility(View.VISIBLE);
} else {
vh.more.setVisibility(View.GONE);
}
}
}
/**
* Retrieve a list of all of the activities that can handle the given Intent,
* optionally excluding the explicit component 'exclude'. The returned list
* is sorted by the label for reach resolved activity.
*/
static final List<ResolveInfo> getActivities(Context context, Intent intent,
ComponentName exclude) {
PackageManager pm = context.getPackageManager();
List<ResolveInfo> list = pm.queryIntentActivities(intent,
PackageManager.MATCH_DEFAULT_ONLY);
if (list != null) {
int N = list.size();
if (exclude != null) {
for (int i=0; i<N; i++) {
ResolveInfo ri = list.get(i);
if (ri.activityInfo.packageName.equals(exclude.getPackageName())
|| ri.activityInfo.name.equals(exclude.getClassName())) {
list.remove(i);
N--;
}
}
}
if (N > 1) {
// Only display the first matches that are either of equal
// priority or have asked to be default options.
ResolveInfo r0 = list.get(0);
for (int i=1; i<N; i++) {
ResolveInfo ri = list.get(i);
if (Config.LOGV) Log.v(
"ResolveListActivity",
r0.activityInfo.name + "=" +
r0.priority + "/" + r0.isDefault + " vs " +
ri.activityInfo.name + "=" +
ri.priority + "/" + ri.isDefault);
if (r0.priority != ri.priority ||
r0.isDefault != ri.isDefault) {
while (i < N) {
list.remove(i);
N--;
}
}
}
Collections.sort(list, new ResolveInfo.DisplayNameComparator(pm));
}
}
return list;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rings_extended);
mOkayButton = findViewById(R.id.okayButton);
mOkayButton.setOnClickListener(this);
mCancelButton = findViewById(R.id.cancelButton);
mCancelButton.setOnClickListener(this);
Intent intent = getIntent();
/*
* Get whether to show the 'Default' item, and the URI to play when the
* default is clicked
*/
mUriForDefaultItem = intent.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_DEFAULT_URI);
if (mUriForDefaultItem == null) {
mUriForDefaultItem = Settings.System.DEFAULT_RINGTONE_URI;
}
// Get the URI whose list item should have a checkmark
mExistingUri = intent
.getParcelableExtra(RingtoneManager.EXTRA_RINGTONE_EXISTING_URI);
// We are now going to build the set of static items.
ArrayList<ItemInfo> initialItems = new ArrayList<ItemInfo>();
// If the caller has asked to allow the user to select "silent", then
// show an option for that.
if (intent.getBooleanExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_SILENT, true)) {
mSilentItemIdx = initialItems.size();
initialItems.add(new ItemInfo(getText(R.string.silentLabel),
null, null));
}
// If the caller has asked to allow the user to select "default", then
// show an option for that.
if (intent.getBooleanExtra(RingtoneManager.EXTRA_RINGTONE_SHOW_DEFAULT, true)) {
mDefaultItemIdx = initialItems.size();
Ringtone defRing = RingtoneManager.getRingtone(this, mUriForDefaultItem);
initialItems.add(new ItemInfo(getText(R.string.defaultRingtoneLabel),
defRing.getTitle(this), null));
}
// If the caller has supplied a currently selected Uri, then show an
// open for keeping that.
if (mExistingUri != null) {
mExistingRingtone = RingtoneManager.getRingtone(this, mExistingUri);
mExistingItemIdx = initialItems.size();
initialItems.add(new ItemInfo(getText(R.string.existingRingtoneLabel),
mExistingRingtone.getTitle(this), null));
}
if (DBG) {
Log.v(TAG, "default=" + mUriForDefaultItem);
Log.v(TAG, "existing=" + mExistingUri);
}
// Figure out which of the static items should start out with its
// radio button checked.
if (mExistingUri == null) {
if (mSilentItemIdx >= 0) {
mSelectedItem = mSilentItemIdx;
}
} else if (mDefaultItemIdx >= 0 && mExistingUri.equals(mUriForDefaultItem)) {
mSelectedItem = mDefaultItemIdx;
} else {
mSelectedItem = mExistingItemIdx;
}
if (mSelectedItem >= 0) {
mOkayButton.setEnabled(true);
}
mAdapter = new Adapter(this, initialItems, getIntent(), getComponentName(),
new Intent(Intent.ACTION_GET_CONTENT).setType("audio/mp3")
.addCategory(Intent.CATEGORY_OPENABLE));
this.setListAdapter(mAdapter);
}
@Override public void onPause() {
super.onPause();
stopMediaPlayer();
}
public void onCompletion(MediaPlayer mp) {
if (mMediaPlayer == mp) {
mp.stop();
mp.release();
mMediaPlayer = null;
mPlayingId = -1;
getListView().invalidateViews();
}
}
private void stopMediaPlayer() {
if (mMediaPlayer != null) {
mMediaPlayer.stop();
mMediaPlayer.release();
mMediaPlayer = null;
mPlayingId = -1;
}
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
int initialItem = mAdapter.initialItemForPosition((int)id);
if (initialItem >= 0) {
// If the selected item is from our static list, then take
// care of handling it.
mSelectedItem = initialItem;
Uri uri = getSelectedUri();
// If a new item has been selected, then play it for the user.
if (uri != null && (id != mPlayingId || mMediaPlayer == null)) {
stopMediaPlayer();
mMediaPlayer = new MediaPlayer();
try {
if (DBG) Log.v(TAG, "Playing: " + uri);
mMediaPlayer.setDataSource(this, uri);
mMediaPlayer.setOnCompletionListener(this);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_RING);
mMediaPlayer.prepare();
mMediaPlayer.start();
mPlayingId = id;
getListView().invalidateViews();
} catch (IOException e) {
Log.w("MusicPicker", "Unable to play track", e);
}
// Otherwise stop any currently playing item.
} else if (mMediaPlayer != null) {
stopMediaPlayer();
getListView().invalidateViews();
}
getListView().invalidateViews();
mOkayButton.setEnabled(true);
} else if (mAdapter.isOrigIntentPosition((int)id)) {
// If the item is one of the original intent activities, then
// launch it with the result code to simply propagate its result
// back to our caller.
Intent intent = mAdapter.intentForPosition((int)id);
startActivityForResult(intent, REQUEST_ORIGINAL);
} else {
// If the item is one of the music retrieval activities, then launch
// it with the result code to transform its result into our caller's
// expected result.
Intent intent = mAdapter.intentForPosition((int)id);
intent.putExtras(getIntent());
startActivityForResult(intent, REQUEST_SOUND);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_SOUND && resultCode == RESULT_OK) {
Intent resultIntent = new Intent();
Uri uri = data != null ? data.getData() : null;
resultIntent.putExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI, uri);
setResult(RESULT_OK, resultIntent);
finish();
} else if (requestCode == REQUEST_ORIGINAL && resultCode == RESULT_OK) {
setResult(RESULT_OK, data);
finish();
}
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.okayButton:
Intent resultIntent = new Intent();
Uri uri = getSelectedUri();
resultIntent.putExtra(RingtoneManager.EXTRA_RINGTONE_PICKED_URI, uri);
setResult(RESULT_OK, resultIntent);
finish();
break;
case R.id.cancelButton:
finish();
break;
}
}
private Uri getSelectedUri() {
if (mSelectedItem == mSilentItemIdx) {
// The null uri is silent.
return null;
} else if (mSelectedItem == mDefaultItemIdx) {
return mUriForDefaultItem;
} else if (mSelectedItem == mExistingItemIdx) {
return mExistingUri;
}
return null;
}
}
| 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.example.android.rings_extended;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.RectF;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.SystemClock;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup.OnHierarchyChangeListener;
import android.widget.AbsListView;
import android.widget.Adapter;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.HeaderViewListAdapter;
import android.widget.ListView;
import android.widget.AbsListView.OnScrollListener;
/**
* FastScrollView is meant for embedding {@link ListView}s that contain a large number of
* items that can be indexed in some fashion. It displays a special scroll bar that allows jumping
* quickly to indexed sections of the list in touch-mode. Only one child can be added to this
* view group and it must be a {@link ListView}, with an adapter that is derived from
* {@link BaseAdapter}.
*
* <p>This file was copied from the Contacts application. In the future it
* should be provided as a standard part of the Android framework.
*/
public class FastScrollView extends FrameLayout
implements OnScrollListener, OnHierarchyChangeListener {
private Drawable mCurrentThumb;
private Drawable mOverlayDrawable;
private int mThumbH;
private int mThumbW;
private int mThumbY;
private RectF mOverlayPos;
// Hard coding these for now
private int mOverlaySize = 104;
private boolean mDragging;
private ListView mList;
private boolean mScrollCompleted;
private boolean mThumbVisible;
private int mVisibleItem;
private Paint mPaint;
private int mListOffset;
private Object [] mSections;
private String mSectionText;
private boolean mDrawOverlay;
private ScrollFade mScrollFade;
private Handler mHandler = new Handler();
private BaseAdapter mListAdapter;
private boolean mChangedBounds;
interface SectionIndexer {
Object[] getSections();
int getPositionForSection(int section);
int getSectionForPosition(int position);
}
public FastScrollView(Context context) {
super(context);
init(context);
}
public FastScrollView(Context context, AttributeSet attrs) {
super(context, attrs);
init(context);
}
public FastScrollView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context);
}
private void useThumbDrawable(Drawable drawable) {
mCurrentThumb = drawable;
mThumbW = 64; //mCurrentThumb.getIntrinsicWidth();
mThumbH = 52; //mCurrentThumb.getIntrinsicHeight();
mChangedBounds = true;
}
private void init(Context context) {
// Get both the scrollbar states drawables
final Resources res = context.getResources();
useThumbDrawable(res.getDrawable(
R.drawable.scrollbar_handle_accelerated_anim2));
mOverlayDrawable = res.getDrawable(android.R.drawable.alert_dark_frame);
mScrollCompleted = true;
setWillNotDraw(false);
// Need to know when the ListView is added
setOnHierarchyChangeListener(this);
mOverlayPos = new RectF();
mScrollFade = new ScrollFade();
mPaint = new Paint();
mPaint.setAntiAlias(true);
mPaint.setTextAlign(Paint.Align.CENTER);
mPaint.setTextSize(mOverlaySize / 2);
mPaint.setColor(0xFFFFFFFF);
mPaint.setStyle(Paint.Style.FILL_AND_STROKE);
}
private void removeThumb() {
mThumbVisible = false;
// Draw one last time to remove thumb
invalidate();
}
@Override
public void draw(Canvas canvas) {
super.draw(canvas);
if (!mThumbVisible) {
// No need to draw the rest
return;
}
final int y = mThumbY;
final int viewWidth = getWidth();
final FastScrollView.ScrollFade scrollFade = mScrollFade;
int alpha = -1;
if (scrollFade.mStarted) {
alpha = scrollFade.getAlpha();
if (alpha < ScrollFade.ALPHA_MAX / 2) {
mCurrentThumb.setAlpha(alpha * 2);
}
int left = viewWidth - (mThumbW * alpha) / ScrollFade.ALPHA_MAX;
mCurrentThumb.setBounds(left, 0, viewWidth, mThumbH);
mChangedBounds = true;
}
canvas.translate(0, y);
mCurrentThumb.draw(canvas);
canvas.translate(0, -y);
// If user is dragging the scroll bar, draw the alphabet overlay
if (mDragging && mDrawOverlay) {
mOverlayDrawable.draw(canvas);
final Paint paint = mPaint;
float descent = paint.descent();
final RectF rectF = mOverlayPos;
canvas.drawText(mSectionText, (int) (rectF.left + rectF.right) / 2,
(int) (rectF.bottom + rectF.top) / 2 + mOverlaySize / 4 - descent, paint);
} else if (alpha == 0) {
scrollFade.mStarted = false;
removeThumb();
} else {
invalidate(viewWidth - mThumbW, y, viewWidth, y + mThumbH);
}
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
if (mCurrentThumb != null) {
mCurrentThumb.setBounds(w - mThumbW, 0, w, mThumbH);
}
final RectF pos = mOverlayPos;
pos.left = (w - mOverlaySize) / 2;
pos.right = pos.left + mOverlaySize;
pos.top = h / 10; // 10% from top
pos.bottom = pos.top + mOverlaySize;
mOverlayDrawable.setBounds((int) pos.left, (int) pos.top,
(int) pos.right, (int) pos.bottom);
}
public void onScrollStateChanged(AbsListView view, int scrollState) {
}
public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount,
int totalItemCount) {
if (totalItemCount - visibleItemCount > 0 && !mDragging) {
mThumbY = ((getHeight() - mThumbH) * firstVisibleItem) / (totalItemCount - visibleItemCount);
if (mChangedBounds) {
final int viewWidth = getWidth();
mCurrentThumb.setBounds(viewWidth - mThumbW, 0, viewWidth, mThumbH);
mChangedBounds = false;
}
}
mScrollCompleted = true;
if (firstVisibleItem == mVisibleItem) {
return;
}
mVisibleItem = firstVisibleItem;
if (!mThumbVisible || mScrollFade.mStarted) {
mThumbVisible = true;
mCurrentThumb.setAlpha(ScrollFade.ALPHA_MAX);
}
mHandler.removeCallbacks(mScrollFade);
mScrollFade.mStarted = false;
if (!mDragging) {
mHandler.postDelayed(mScrollFade, 1500);
}
}
private void getSections() {
Adapter adapter = mList.getAdapter();
if (adapter instanceof HeaderViewListAdapter) {
mListOffset = ((HeaderViewListAdapter)adapter).getHeadersCount();
adapter = ((HeaderViewListAdapter)adapter).getWrappedAdapter();
}
if (adapter instanceof SectionIndexer) {
mListAdapter = (BaseAdapter) adapter;
mSections = ((SectionIndexer) mListAdapter).getSections();
}
}
public void onChildViewAdded(View parent, View child) {
if (child instanceof ListView) {
mList = (ListView)child;
mList.setOnScrollListener(this);
getSections();
}
}
public void onChildViewRemoved(View parent, View child) {
if (child == mList) {
mList = null;
mListAdapter = null;
mSections = null;
}
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
if (mThumbVisible && ev.getAction() == MotionEvent.ACTION_DOWN) {
if (ev.getX() > getWidth() - mThumbW && ev.getY() >= mThumbY &&
ev.getY() <= mThumbY + mThumbH) {
mDragging = true;
return true;
}
}
return false;
}
private void scrollTo(float position) {
int count = mList.getCount();
mScrollCompleted = false;
final Object[] sections = mSections;
int sectionIndex;
if (sections != null && sections.length > 1) {
final int nSections = sections.length;
int section = (int) (position * nSections);
if (section >= nSections) {
section = nSections - 1;
}
sectionIndex = section;
final SectionIndexer baseAdapter = (SectionIndexer) mListAdapter;
int index = baseAdapter.getPositionForSection(section);
// Given the expected section and index, the following code will
// try to account for missing sections (no names starting with..)
// It will compute the scroll space of surrounding empty sections
// and interpolate the currently visible letter's range across the
// available space, so that there is always some list movement while
// the user moves the thumb.
int nextIndex = count;
int prevIndex = index;
int prevSection = section;
int nextSection = section + 1;
// Assume the next section is unique
if (section < nSections - 1) {
nextIndex = baseAdapter.getPositionForSection(section + 1);
}
// Find the previous index if we're slicing the previous section
if (nextIndex == index) {
// Non-existent letter
while (section > 0) {
section--;
prevIndex = baseAdapter.getPositionForSection(section);
if (prevIndex != index) {
prevSection = section;
sectionIndex = section;
break;
}
}
}
// Find the next index, in case the assumed next index is not
// unique. For instance, if there is no P, then request for P's
// position actually returns Q's. So we need to look ahead to make
// sure that there is really a Q at Q's position. If not, move
// further down...
int nextNextSection = nextSection + 1;
while (nextNextSection < nSections &&
baseAdapter.getPositionForSection(nextNextSection) == nextIndex) {
nextNextSection++;
nextSection++;
}
// Compute the beginning and ending scroll range percentage of the
// currently visible letter. This could be equal to or greater than
// (1 / nSections).
float fPrev = (float) prevSection / nSections;
float fNext = (float) nextSection / nSections;
index = prevIndex + (int) ((nextIndex - prevIndex) * (position - fPrev)
/ (fNext - fPrev));
// Don't overflow
if (index > count - 1) index = count - 1;
mList.setSelectionFromTop(index + mListOffset, 0);
} else {
int index = (int) (position * count);
mList.setSelectionFromTop(index + mListOffset, 0);
sectionIndex = -1;
}
if (sectionIndex >= 0) {
String text = mSectionText = sections[sectionIndex].toString();
mDrawOverlay = (text.length() != 1 || text.charAt(0) != ' ') &&
sectionIndex < sections.length;
} else {
mDrawOverlay = false;
}
}
private void cancelFling() {
// Cancel the list fling
MotionEvent cancelFling = MotionEvent.obtain(0, 0, MotionEvent.ACTION_CANCEL, 0, 0, 0);
mList.onTouchEvent(cancelFling);
cancelFling.recycle();
}
@Override
public boolean onTouchEvent(MotionEvent me) {
if (me.getAction() == MotionEvent.ACTION_DOWN) {
if (me.getX() > getWidth() - mThumbW
&& me.getY() >= mThumbY
&& me.getY() <= mThumbY + mThumbH) {
mDragging = true;
if (mListAdapter == null && mList != null) {
getSections();
}
cancelFling();
return true;
}
} else if (me.getAction() == MotionEvent.ACTION_UP) {
if (mDragging) {
mDragging = false;
final Handler handler = mHandler;
handler.removeCallbacks(mScrollFade);
handler.postDelayed(mScrollFade, 1000);
return true;
}
} else if (me.getAction() == MotionEvent.ACTION_MOVE) {
if (mDragging) {
final int viewHeight = getHeight();
mThumbY = (int) me.getY() - mThumbH + 10;
if (mThumbY < 0) {
mThumbY = 0;
} else if (mThumbY + mThumbH > viewHeight) {
mThumbY = viewHeight - mThumbH;
}
// If the previous scrollTo is still pending
if (mScrollCompleted) {
scrollTo((float) mThumbY / (viewHeight - mThumbH));
}
return true;
}
}
return super.onTouchEvent(me);
}
public class ScrollFade implements Runnable {
long mStartTime;
long mFadeDuration;
boolean mStarted;
static final int ALPHA_MAX = 255;
static final long FADE_DURATION = 200;
void startFade() {
mFadeDuration = FADE_DURATION;
mStartTime = SystemClock.uptimeMillis();
mStarted = true;
}
int getAlpha() {
if (!mStarted) {
return ALPHA_MAX;
}
int alpha;
long now = SystemClock.uptimeMillis();
if (now > mStartTime + mFadeDuration) {
alpha = 0;
} else {
alpha = (int) (ALPHA_MAX - ((now - mStartTime) * ALPHA_MAX) / mFadeDuration);
}
return alpha;
}
public void run() {
if (!mStarted) {
startFade();
invalidate();
}
if (getAlpha() > 0) {
final int y = mThumbY;
final int viewWidth = getWidth();
invalidate(viewWidth - mThumbW, y, viewWidth, y + mThumbH);
} else {
mStarted = false;
removeThumb();
}
}
}
}
| Java |
package com.example.android.rings_extended;
import android.app.ListActivity;
import android.content.AsyncQueryHandler;
import android.content.ContentUris;
import android.content.Context;
import android.content.Intent;
import android.database.CharArrayBuffer;
import android.database.Cursor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import java.io.IOException;
import java.text.Collator;
import java.util.Formatter;
import java.util.Locale;
/**
* Activity allowing the user to select a music track on the device, and
* return it to its caller. The music picker user interface is fairly
* extensive, providing information about each track like the music
* application (title, author, album, duration), as well as the ability to
* previous tracks and sort them in different orders.
*
* <p>This class also illustrates how you can load data from a content
* provider asynchronously, providing a good UI while doing so, perform
* indexing of the content for use inside of a {@link FastScrollView}, and
* perform filtering of the data as the user presses keys.
*/
public class MusicPicker extends ListActivity
implements View.OnClickListener, MediaPlayer.OnCompletionListener {
static final boolean DBG = false;
static final String TAG = "MusicPicker";
/** Holds the previous state of the list, to restore after the async
* query has completed. */
static final String LIST_STATE_KEY = "liststate";
/** Remember whether the list last had focus for restoring its state. */
static final String FOCUS_KEY = "focused";
/** Remember the last ordering mode for restoring state. */
static final String SORT_MODE_KEY = "sortMode";
/** Arbitrary number, doesn't matter since we only do one query type. */
final int MY_QUERY_TOKEN = 42;
/** Menu item to sort the music list by track title. */
static final int TRACK_MENU = Menu.FIRST;
/** Menu item to sort the music list by album title. */
static final int ALBUM_MENU = Menu.FIRST+1;
/** Menu item to sort the music list by artist name. */
static final int ARTIST_MENU = Menu.FIRST+2;
/** These are the columns in the music cursor that we are interested in. */
static final String[] CURSOR_COLS = new String[] {
MediaStore.Audio.Media._ID,
MediaStore.Audio.Media.TITLE,
MediaStore.Audio.Media.TITLE_KEY,
MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media.ALBUM,
MediaStore.Audio.Media.ARTIST,
MediaStore.Audio.Media.ARTIST_ID,
MediaStore.Audio.Media.DURATION,
MediaStore.Audio.Media.TRACK
};
/** Formatting optimization to avoid creating many temporary objects. */
static StringBuilder sFormatBuilder = new StringBuilder();
/** Formatting optimization to avoid creating many temporary objects. */
static Formatter sFormatter = new Formatter(sFormatBuilder, Locale.getDefault());
/** Formatting optimization to avoid creating many temporary objects. */
static final Object[] sTimeArgs = new Object[5];
/** Uri to the directory of all music being displayed. */
Uri mBaseUri;
/** This is the adapter used to display all of the tracks. */
TrackListAdapter mAdapter;
/** Our instance of QueryHandler used to perform async background queries. */
QueryHandler mQueryHandler;
/** Used to keep track of the last scroll state of the list. */
Parcelable mListState = null;
/** Used to keep track of whether the list last had focus. */
boolean mListHasFocus;
/** The current cursor on the music that is being displayed. */
Cursor mCursor;
/** The actual sort order the user has selected. */
int mSortMode = -1;
/** SQL order by string describing the currently selected sort order. */
String mSortOrder;
/** Container of the in-screen progress indicator, to be able to hide it
* when done loading the initial cursor. */
View mProgressContainer;
/** Container of the list view hierarchy, to be able to show it when done
* loading the initial cursor. */
View mListContainer;
/** Set to true when the list view has been shown for the first time. */
boolean mListShown;
/** View holding the okay button. */
View mOkayButton;
/** View holding the cancel button. */
View mCancelButton;
/** Which track row ID the user has last selected. */
long mSelectedId = -1;
/** Completel Uri that the user has last selected. */
Uri mSelectedUri;
/** If >= 0, we are currently playing a track for preview, and this is its
* row ID. */
long mPlayingId = -1;
/** This is used for playing previews of the music files. */
MediaPlayer mMediaPlayer;
/**
* A special implementation of SimpleCursorAdapter that knows how to bind
* our cursor data to our list item structure, and takes care of other
* advanced features such as indexing and filtering.
*/
class TrackListAdapter extends SimpleCursorAdapter
implements FastScrollView.SectionIndexer {
final ListView mListView;
private final StringBuilder mBuilder = new StringBuilder();
private final String mUnknownArtist;
private final String mUnknownAlbum;
private int mIdIdx;
private int mTitleIdx;
private int mArtistIdx;
private int mAlbumIdx;
private int mDurationIdx;
private int mAudioIdIdx;
private int mTrackIdx;
private boolean mLoading = true;
private String [] mAlphabet;
private int mIndexerSortMode;
private boolean mIndexerOutOfDate;
private AlphabetIndexer mIndexer;
class ViewHolder {
TextView line1;
TextView line2;
TextView duration;
RadioButton radio;
ImageView play_indicator;
CharArrayBuffer buffer1;
char [] buffer2;
}
TrackListAdapter(Context context, ListView listView, int layout,
String[] from, int[] to) {
super(context, layout, null, from, to);
mListView = listView;
mUnknownArtist = context.getString(R.string.unknownArtistName);
mUnknownAlbum = context.getString(R.string.unknownAlbumName);
getAlphabet(context);
}
/**
* The mLoading flag is set while we are performing a background
* query, to avoid displaying the "No music" empty view during
* this time.
*/
public void setLoading(boolean loading) {
mLoading = loading;
}
@Override
public boolean isEmpty() {
if (mLoading) {
// We don't want the empty state to show when loading.
return false;
} else {
return super.isEmpty();
}
}
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
View v = super.newView(context, cursor, parent);
ViewHolder vh = new ViewHolder();
vh.line1 = (TextView) v.findViewById(R.id.line1);
vh.line2 = (TextView) v.findViewById(R.id.line2);
vh.duration = (TextView) v.findViewById(R.id.duration);
vh.radio = (RadioButton) v.findViewById(R.id.radio);
vh.play_indicator = (ImageView) v.findViewById(R.id.play_indicator);
vh.buffer1 = new CharArrayBuffer(100);
vh.buffer2 = new char[200];
v.setTag(vh);
return v;
}
@Override
public void bindView(View view, Context context, Cursor cursor) {
ViewHolder vh = (ViewHolder) view.getTag();
cursor.copyStringToBuffer(mTitleIdx, vh.buffer1);
vh.line1.setText(vh.buffer1.data, 0, vh.buffer1.sizeCopied);
int secs = cursor.getInt(mDurationIdx) / 1000;
if (secs == 0) {
vh.duration.setText("");
} else {
vh.duration.setText(makeTimeString(context, secs));
}
final StringBuilder builder = mBuilder;
builder.delete(0, builder.length());
String name = cursor.getString(mAlbumIdx);
if (name == null || name.equals(MediaStore.UNKNOWN_STRING)) {
builder.append(mUnknownAlbum);
} else {
builder.append(name);
}
builder.append('\n');
name = cursor.getString(mArtistIdx);
if (name == null || name.equals(MediaStore.UNKNOWN_STRING)) {
builder.append(mUnknownArtist);
} else {
builder.append(name);
}
int len = builder.length();
if (vh.buffer2.length < len) {
vh.buffer2 = new char[len];
}
builder.getChars(0, len, vh.buffer2, 0);
vh.line2.setText(vh.buffer2, 0, len);
// Update the checkbox of the item, based on which the user last
// selected. Note that doing it this way means we must have the
// list view update all of its items when the selected item
// changes.
final long id = cursor.getLong(mIdIdx);
vh.radio.setChecked(id == mSelectedId);
if (DBG) Log.v(TAG, "Binding id=" + id + " sel=" + mSelectedId
+ " playing=" + mPlayingId + " cursor=" + cursor);
// Likewise, display the "now playing" icon if this item is
// currently being previewed for the user.
ImageView iv = vh.play_indicator;
if (id == mPlayingId) {
iv.setImageResource(R.drawable.now_playing);
iv.setVisibility(View.VISIBLE);
} else {
iv.setVisibility(View.GONE);
}
}
/**
* This method is called whenever we receive a new cursor due to
* an async query, and must take care of plugging the new one in
* to the adapter.
*/
@Override
public void changeCursor(Cursor cursor) {
super.changeCursor(cursor);
if (DBG) Log.v(TAG, "Setting cursor to: " + cursor
+ " from: " + MusicPicker.this.mCursor);
MusicPicker.this.mCursor = cursor;
if (cursor != null) {
// Retrieve indices of the various columns we are interested in.
mIdIdx = cursor.getColumnIndex(MediaStore.Audio.Media._ID);
mTitleIdx = cursor.getColumnIndex(MediaStore.Audio.Media.TITLE);
mArtistIdx = cursor.getColumnIndex(MediaStore.Audio.Media.ARTIST);
mAlbumIdx = cursor.getColumnIndex(MediaStore.Audio.Media.ALBUM);
mDurationIdx = cursor.getColumnIndex(MediaStore.Audio.Media.DURATION);
int audioIdIdx = cursor.getColumnIndex(MediaStore.Audio.Playlists.Members.AUDIO_ID);
if (audioIdIdx < 0) {
audioIdIdx = cursor.getColumnIndex(MediaStore.Audio.Media._ID);
}
mAudioIdIdx = audioIdIdx;
mTrackIdx = cursor.getColumnIndex(MediaStore.Audio.Media.TRACK);
}
// The next time the indexer is needed, we will need to rebind it
// to this cursor.
mIndexerOutOfDate = true;
// Ensure that the list is shown (and initial progress indicator
// hidden) in case this is the first cursor we have gotten.
makeListShown();
}
/**
* This method is called from a background thread by the list view
* when the user has typed a letter that should result in a filtering
* of the displayed items. It returns a Cursor, when will then be
* handed to changeCursor.
*/
@Override
public Cursor runQueryOnBackgroundThread(CharSequence constraint) {
if (DBG) Log.v(TAG, "Getting new cursor...");
return doQuery(true, constraint.toString());
}
/**
* Build a list of alphabetic characters appropriate for the
* current locale.
*/
private void getAlphabet(Context context) {
String alphabetString = context.getResources().getString(R.string.alphabet);
mAlphabet = new String[alphabetString.length()];
for (int i = 0; i < mAlphabet.length; i++) {
mAlphabet[i] = String.valueOf(alphabetString.charAt(i));
}
}
public int getPositionForSection(int section) {
Cursor cursor = getCursor();
if (cursor == null) {
// No cursor, the section doesn't exist so just return 0
return 0;
}
// If the sort mode has changed, or we haven't yet created an
// indexer one, then create a new one that is indexing the
// appropriate column based on the sort mode.
if (mIndexerSortMode != mSortMode || mIndexer == null) {
mIndexerSortMode = mSortMode;
int idx = mTitleIdx;
switch (mIndexerSortMode) {
case ARTIST_MENU:
idx = mArtistIdx;
break;
case ALBUM_MENU:
idx = mAlbumIdx;
break;
}
mIndexer = new AlphabetIndexer(cursor, idx, mAlphabet);
// If we have a valid indexer, but the cursor has changed since
// its last use, then point it to the current cursor.
} else if (mIndexerOutOfDate) {
mIndexer.setCursor(cursor);
}
mIndexerOutOfDate = false;
return mIndexer.indexOf(section);
}
public int getSectionForPosition(int position) {
return 0;
}
public Object[] getSections() {
return mAlphabet;
}
}
/**
* This is our specialization of AsyncQueryHandler applies new cursors
* to our state as they become available.
*/
private final class QueryHandler extends AsyncQueryHandler {
public QueryHandler(Context context) {
super(context.getContentResolver());
}
@Override
protected void onQueryComplete(int token, Object cookie, Cursor cursor) {
if (!isFinishing()) {
// Update the adapter: we are no longer loading, and have
// a new cursor for it.
mAdapter.setLoading(false);
mAdapter.changeCursor(cursor);
setProgressBarIndeterminateVisibility(false);
// Now that the cursor is populated again, it's possible to restore the list state
if (mListState != null) {
getListView().onRestoreInstanceState(mListState);
if (mListHasFocus) {
getListView().requestFocus();
}
mListHasFocus = false;
mListState = null;
}
} else {
cursor.close();
}
}
}
public static String makeTimeString(Context context, long secs) {
String durationformat = context.getString(R.string.durationformat);
/* Provide multiple arguments so the format can be changed easily
* by modifying the xml.
*/
sFormatBuilder.setLength(0);
final Object[] timeArgs = sTimeArgs;
timeArgs[0] = secs / 3600;
timeArgs[1] = secs / 60;
timeArgs[2] = (secs / 60) % 60;
timeArgs[3] = secs;
timeArgs[4] = secs % 60;
return sFormatter.format(durationformat, timeArgs).toString();
}
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setTitle(R.string.musicPickerTitle);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
int sortMode = TRACK_MENU;
if (icicle == null) {
mSelectedUri = getIntent().getParcelableExtra(
RingtoneManager.EXTRA_RINGTONE_EXISTING_URI);
} else {
mSelectedUri = (Uri)icicle.getParcelable(
RingtoneManager.EXTRA_RINGTONE_EXISTING_URI);
// Retrieve list state. This will be applied after the
// QueryHandler has run
mListState = icicle.getParcelable(LIST_STATE_KEY);
mListHasFocus = icicle.getBoolean(FOCUS_KEY);
sortMode = icicle.getInt(SORT_MODE_KEY, sortMode);
}
if (Intent.ACTION_GET_CONTENT.equals(getIntent().getAction())) {
mBaseUri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
} else {
mBaseUri = getIntent().getData();
if (mBaseUri == null) {
Log.w("MusicPicker", "No data URI given to PICK action");
finish();
return;
}
}
setContentView(R.layout.music_picker);
mSortOrder = MediaStore.Audio.Media.TITLE_KEY;
final ListView listView = getListView();
listView.setItemsCanFocus(false);
mAdapter = new TrackListAdapter(this, listView,
R.layout.track_list_item, new String[] {},
new int[] {});
setListAdapter(mAdapter);
listView.setTextFilterEnabled(true);
// We manually save/restore the listview state
listView.setSaveEnabled(false);
mQueryHandler = new QueryHandler(this);
mProgressContainer = findViewById(R.id.progressContainer);
mListContainer = findViewById(R.id.listContainer);
mOkayButton = findViewById(R.id.okayButton);
mOkayButton.setOnClickListener(this);
mCancelButton = findViewById(R.id.cancelButton);
mCancelButton.setOnClickListener(this);
// If there is a currently selected Uri, then try to determine who
// it is.
if (mSelectedUri != null) {
Uri.Builder builder = mSelectedUri.buildUpon();
String path = mSelectedUri.getEncodedPath();
int idx = path.lastIndexOf('/');
if (idx >= 0) {
path = path.substring(0, idx);
}
builder.encodedPath(path);
Uri baseSelectedUri = builder.build();
if (DBG) Log.v(TAG, "Selected Uri: " + mSelectedUri);
if (DBG) Log.v(TAG, "Selected base Uri: " + baseSelectedUri);
if (DBG) Log.v(TAG, "Base Uri: " + mBaseUri);
if (baseSelectedUri.equals(mBaseUri)) {
// If the base Uri of the selected Uri is the same as our
// content's base Uri, then use the selection!
mSelectedId = ContentUris.parseId(mSelectedUri);
}
}
setSortMode(sortMode);
}
@Override public void onRestart() {
super.onRestart();
doQuery(false, null);
}
@Override public boolean onOptionsItemSelected(MenuItem item) {
if (setSortMode(item.getItemId())) {
return true;
}
return super.onOptionsItemSelected(item);
}
@Override public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(Menu.NONE, TRACK_MENU, Menu.NONE, R.string.sortByTrack);
menu.add(Menu.NONE, ALBUM_MENU, Menu.NONE, R.string.sortByAlbum);
menu.add(Menu.NONE, ARTIST_MENU, Menu.NONE, R.string.sortByArtist);
return true;
}
@Override protected void onSaveInstanceState(Bundle icicle) {
super.onSaveInstanceState(icicle);
// Save list state in the bundle so we can restore it after the
// QueryHandler has run
icicle.putParcelable(LIST_STATE_KEY, getListView().onSaveInstanceState());
icicle.putBoolean(FOCUS_KEY, getListView().hasFocus());
icicle.putInt(SORT_MODE_KEY, mSortMode);
}
@Override public void onPause() {
super.onPause();
stopMediaPlayer();
}
@Override public void onStop() {
super.onStop();
// We don't want the list to display the empty state, since when we
// resume it will still be there and show up while the new query is
// happening. After the async query finishes in response to onResume()
// setLoading(false) will be called.
mAdapter.setLoading(true);
mAdapter.changeCursor(null);
}
/**
* Changes the current sort order, building the appropriate query string
* for the selected order.
*/
boolean setSortMode(int sortMode) {
if (sortMode != mSortMode) {
switch (sortMode) {
case TRACK_MENU:
mSortMode = sortMode;
mSortOrder = MediaStore.Audio.Media.TITLE_KEY;
doQuery(false, null);
return true;
case ALBUM_MENU:
mSortMode = sortMode;
mSortOrder = MediaStore.Audio.Media.ALBUM_KEY + " ASC, "
+ MediaStore.Audio.Media.TRACK + " ASC, "
+ MediaStore.Audio.Media.TITLE_KEY + " ASC";
doQuery(false, null);
return true;
case ARTIST_MENU:
mSortMode = sortMode;
mSortOrder = MediaStore.Audio.Media.ARTIST_KEY + " ASC, "
+ MediaStore.Audio.Media.ALBUM_KEY + " ASC, "
+ MediaStore.Audio.Media.TRACK + " ASC, "
+ MediaStore.Audio.Media.TITLE_KEY + " ASC";
doQuery(false, null);
return true;
}
}
return false;
}
/**
* The first time this is called, we hide the large progress indicator
* and show the list view, doing fade animations between them.
*/
void makeListShown() {
if (!mListShown) {
mListShown = true;
mProgressContainer.startAnimation(AnimationUtils.loadAnimation(
this, android.R.anim.fade_out));
mProgressContainer.setVisibility(View.GONE);
mListContainer.startAnimation(AnimationUtils.loadAnimation(
this, android.R.anim.fade_in));
mListContainer.setVisibility(View.VISIBLE);
}
}
/**
* Common method for performing a query of the music database, called for
* both top-level queries and filtering.
*
* @param sync If true, this query should be done synchronously and the
* resulting cursor returned. If false, it will be done asynchronously and
* null returned.
* @param filterstring If non-null, this is a filter to apply to the query.
*/
Cursor doQuery(boolean sync, String filterstring) {
// Cancel any pending queries
mQueryHandler.cancelOperation(MY_QUERY_TOKEN);
StringBuilder where = new StringBuilder();
where.append(MediaStore.Audio.Media.TITLE + " != ''");
// Add in the filtering constraints
String [] keywords = null;
if (filterstring != null) {
String [] searchWords = filterstring.split(" ");
keywords = new String[searchWords.length];
Collator col = Collator.getInstance();
col.setStrength(Collator.PRIMARY);
for (int i = 0; i < searchWords.length; i++) {
keywords[i] = '%' + MediaStore.Audio.keyFor(searchWords[i]) + '%';
}
for (int i = 0; i < searchWords.length; i++) {
where.append(" AND ");
where.append(MediaStore.Audio.Media.ARTIST_KEY + "||");
where.append(MediaStore.Audio.Media.ALBUM_KEY + "||");
where.append(MediaStore.Audio.Media.TITLE_KEY + " LIKE ?");
}
}
// We want to show all audio files, even recordings. Enforcing the
// following condition would hide recordings.
//where.append(" AND " + MediaStore.Audio.Media.IS_MUSIC + "=1");
if (sync) {
try {
return getContentResolver().query(mBaseUri, CURSOR_COLS,
where.toString(), keywords, mSortOrder);
} catch (UnsupportedOperationException ex) {
}
} else {
mAdapter.setLoading(true);
setProgressBarIndeterminateVisibility(true);
mQueryHandler.startQuery(MY_QUERY_TOKEN, null, mBaseUri, CURSOR_COLS,
where.toString(), keywords, mSortOrder);
}
return null;
}
@Override protected void onListItemClick(ListView l, View v, int position,
long id) {
mCursor.moveToPosition(position);
if (DBG) Log.v(TAG, "Click on " + position + " (id=" + id
+ ", cursid="
+ mCursor.getLong(mCursor.getColumnIndex(MediaStore.Audio.Media._ID))
+ ") in cursor " + mCursor
+ " adapter=" + l.getAdapter());
setSelected(mCursor);
}
void setSelected(Cursor c) {
Uri uri = MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
long newId = mCursor.getLong(mCursor.getColumnIndex(MediaStore.Audio.Media._ID));
mSelectedUri = ContentUris.withAppendedId(uri, newId);
mSelectedId = newId;
if (newId != mPlayingId || mMediaPlayer == null) {
stopMediaPlayer();
mMediaPlayer = new MediaPlayer();
try {
mMediaPlayer.setDataSource(this, mSelectedUri);
mMediaPlayer.setOnCompletionListener(this);
mMediaPlayer.setAudioStreamType(AudioManager.STREAM_RING);
mMediaPlayer.prepare();
mMediaPlayer.start();
mPlayingId = newId;
getListView().invalidateViews();
} catch (IOException e) {
Log.w("MusicPicker", "Unable to play track", e);
}
} else if (mMediaPlayer != null) {
stopMediaPlayer();
getListView().invalidateViews();
}
}
public void onCompletion(MediaPlayer mp) {
if (mMediaPlayer == mp) {
mp.stop();
mp.release();
mMediaPlayer = null;
mPlayingId = -1;
getListView().invalidateViews();
}
}
void stopMediaPlayer() {
if (mMediaPlayer != null) {
mMediaPlayer.stop();
mMediaPlayer.release();
mMediaPlayer = null;
mPlayingId = -1;
}
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.okayButton:
if (mSelectedId >= 0) {
setResult(RESULT_OK, new Intent().setData(mSelectedUri));
finish();
}
break;
case R.id.cancelButton:
finish();
break;
}
}
}
| Java |
package com.example.android.rings_extended;
import android.content.Context;
import android.util.AttributeSet;
import android.widget.Checkable;
import android.widget.RelativeLayout;
/**
* A special variation of RelativeLayout that can be used as a checkable object.
* This allows it to be used as the top-level view of a list view item, which
* also supports checking. Otherwise, it works identically to a RelativeLayout.
*/
public class CheckableRelativeLayout extends RelativeLayout implements Checkable {
private boolean mChecked;
private static final int[] CHECKED_STATE_SET = {
android.R.attr.state_checked
};
public CheckableRelativeLayout(Context context, AttributeSet attrs) {
super(context, attrs);
}
@Override
protected int[] onCreateDrawableState(int extraSpace) {
final int[] drawableState = super.onCreateDrawableState(extraSpace + 1);
if (isChecked()) {
mergeDrawableStates(drawableState, CHECKED_STATE_SET);
}
return drawableState;
}
public void toggle() {
setChecked(!mChecked);
}
public boolean isChecked() {
return mChecked;
}
public void setChecked(boolean checked) {
if (mChecked != checked) {
mChecked = checked;
refreshDrawableState();
}
}
}
| 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.android.globaltime;
public class LatLongSphere extends Sphere {
public LatLongSphere(float centerX, float centerY, float centerZ,
float radius, int lats, int longs,
float minLongitude, float maxLongitude,
boolean emitTextureCoordinates,
boolean emitNormals,
boolean emitColors,
boolean flatten) {
super(emitTextureCoordinates, emitNormals, emitColors);
int tris = 2 * (lats - 1) * (longs - 1);
int[] vertices = new int[3 * lats * longs];
int[] texcoords = new int[2 * lats * longs];
int[] colors = new int[4 * lats * longs];
int[] normals = new int[3 * lats * longs];
short[] indices = new short[3 * tris];
int vidx = 0;
int tidx = 0;
int nidx = 0;
int cidx = 0;
int iidx = 0;
minLongitude *= DEGREES_TO_RADIANS;
maxLongitude *= DEGREES_TO_RADIANS;
for (int i = 0; i < longs; i++) {
float fi = (float) i / (longs - 1);
// theta is the longitude
float theta =
(maxLongitude - minLongitude) * (1.0f - fi) + minLongitude;
float sinTheta = (float) Math.sin(theta);
float cosTheta = (float) Math.cos(theta);
for (int j = 0; j < lats; j++) {
float fj = (float) j / (lats - 1);
// phi is the latitude
float phi = PI * fj;
float sinPhi = (float) Math.sin(phi);
float cosPhi = (float) Math.cos(phi);
float x = cosTheta * sinPhi;
float y = cosPhi;
float z = sinTheta * sinPhi;
if (flatten) {
// Place vertices onto a flat projection
vertices[vidx++] = toFixed(2.0f * fi - 1.0f);
vertices[vidx++] = toFixed(0.5f - fj);
vertices[vidx++] = toFixed(0.0f);
} else {
// Place vertices onto the surface of a sphere
// with the given center and radius
vertices[vidx++] = toFixed(x * radius + centerX);
vertices[vidx++] = toFixed(y * radius + centerY);
vertices[vidx++] = toFixed(z * radius + centerZ);
}
if (emitTextureCoordinates) {
texcoords[tidx++] = toFixed(1.0f - (theta / (TWO_PI)));
texcoords[tidx++] = toFixed(fj);
}
if (emitNormals) {
float norm = 1.0f / Shape.length(x, y, z);
normals[nidx++] = toFixed(x * norm);
normals[nidx++] = toFixed(y * norm);
normals[nidx++] = toFixed(z * norm);
}
// 0 == black, 65536 == white
if (emitColors) {
colors[cidx++] = (i % 2) * 65536;
colors[cidx++] = 0;
colors[cidx++] = (j % 2) * 65536;
colors[cidx++] = 65536;
}
}
}
for (int i = 0; i < longs - 1; i++) {
for (int j = 0; j < lats - 1; j++) {
int base = i * lats + j;
// Ensure both triangles have the same final vertex
// since this vertex carries the color for flat
// shading
indices[iidx++] = (short) (base);
indices[iidx++] = (short) (base + 1);
indices[iidx++] = (short) (base + lats + 1);
indices[iidx++] = (short) (base + lats);
indices[iidx++] = (short) (base);
indices[iidx++] = (short) (base + lats + 1);
}
}
allocateBuffers(vertices, texcoords, normals, colors, indices);
}
}
| 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.android.globaltime;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.TimeZone;
/**
* A class representing a city, with an associated position, time zone name,
* and raw offset from UTC.
*/
public class City implements Comparable<City> {
private static Map<String,City> cities = new HashMap<String,City>();
private static City[] citiesByRawOffset;
private String name;
private String timeZoneID;
private TimeZone timeZone = null;
private int rawOffset;
private float latitude, longitude;
private float x, y, z;
/**
* Loads the city database. The cities must be stored in order by raw
* offset from UTC.
*/
public static void loadCities(InputStream is) throws IOException {
DataInputStream dis = new DataInputStream(is);
int numCities = dis.readInt();
citiesByRawOffset = new City[numCities];
byte[] buf = new byte[24];
for (int i = 0; i < numCities; i++) {
String name = dis.readUTF();
String tzid = dis.readUTF();
dis.read(buf);
// The code below is a faster version of:
// int rawOffset = dis.readInt();
// float latitude = dis.readFloat();
// float longitude = dis.readFloat();
// float cx = dis.readFloat();
// float cy = dis.readFloat();
// float cz = dis.readFloat();
int rawOffset =
(buf[ 0] << 24) | ((buf[ 1] & 0xff) << 16) |
((buf[ 2] & 0xff) << 8) | (buf[ 3] & 0xff);
int ilat = (buf[ 4] << 24) | ((buf[ 5] & 0xff) << 16) |
((buf[ 6] & 0xff) << 8) | (buf[ 7] & 0xff);
int ilon = (buf[ 8] << 24) | ((buf[ 9] & 0xff) << 16) |
((buf[10] & 0xff) << 8) | (buf[11] & 0xff);
int icx = (buf[12] << 24) | ((buf[13] & 0xff) << 16) |
((buf[14] & 0xff) << 8) | (buf[15] & 0xff);
int icy = (buf[16] << 24) | ((buf[17] & 0xff) << 16) |
((buf[18] & 0xff) << 8) | (buf[19] & 0xff);
int icz = (buf[20] << 24) | ((buf[21] & 0xff) << 16) |
((buf[22] & 0xff) << 8) | (buf[23] & 0xff);
float latitude = Float.intBitsToFloat(ilat);
float longitude = Float.intBitsToFloat(ilon);
float cx = Float.intBitsToFloat(icx);
float cy = Float.intBitsToFloat(icy);
float cz = Float.intBitsToFloat(icz);
City city = new City(name, tzid, rawOffset,
latitude, longitude, cx, cy, cz);
cities.put(name, city);
citiesByRawOffset[i] = city;
}
}
/**
* Returns the cities, ordered by name.
*/
public static City[] getCitiesByName() {
City[] ocities = cities.values().toArray(new City[0]);
Arrays.sort(ocities);
return ocities;
}
/**
* Returns the cities, ordered by offset, accounting for summer/daylight
* savings time. This requires reading the entire time zone database
* behind the scenes.
*/
public static City[] getCitiesByOffset() {
City[] ocities = cities.values().toArray(new City[0]);
Arrays.sort(ocities, new Comparator<City>() {
public int compare(City c1, City c2) {
long now = System.currentTimeMillis();
TimeZone tz1 = c1.getTimeZone();
TimeZone tz2 = c2.getTimeZone();
int off1 = tz1.getOffset(now);
int off2 = tz2.getOffset(now);
if (off1 == off2) {
float dlat = c2.getLatitude() - c1.getLatitude();
if (dlat < 0.0f) return -1;
if (dlat > 0.0f) return 1;
return 0;
}
return off1 - off2;
}
});
return ocities;
}
/**
* Returns the cities, ordered by offset, accounting for summer/daylight
* savings time. This does not require reading the time zone database
* since the cities are pre-sorted.
*/
public static City[] getCitiesByRawOffset() {
return citiesByRawOffset;
}
/**
* Returns an Iterator over all cities, in raw offset order.
*/
public static Iterator<City> iterator() {
return cities.values().iterator();
}
/**
* Returns the total number of cities.
*/
public static int numCities() {
return cities.size();
}
/**
* Constructs a city with the given name, time zone name, raw offset,
* latitude, longitude, and 3D (X, Y, Z) coordinate.
*/
public City(String name, String timeZoneID,
int rawOffset,
float latitude, float longitude,
float x, float y, float z) {
this.name = name;
this.timeZoneID = timeZoneID;
this.rawOffset = rawOffset;
this.latitude = latitude;
this.longitude = longitude;
this.x = x;
this.y = y;
this.z = z;
}
public String getName() {
return name;
}
public TimeZone getTimeZone() {
if (timeZone == null) {
timeZone = TimeZone.getTimeZone(timeZoneID);
}
return timeZone;
}
public float getLongitude() {
return longitude;
}
public float getLatitude() {
return latitude;
}
public float getX() {
return x;
}
public float getY() {
return y;
}
public float getZ() {
return z;
}
public float getRawOffset() {
return rawOffset / 3600000.0f;
}
public int getRawOffsetMillis() {
return rawOffset;
}
/**
* Returns this city's offset from UTC, taking summer/daylight savigns
* time into account.
*/
public float getOffset() {
long now = System.currentTimeMillis();
if (timeZone == null) {
timeZone = TimeZone.getTimeZone(timeZoneID);
}
return timeZone.getOffset(now) / 3600000.0f;
}
/**
* Compares this city to another by name.
*/
public int compareTo(City o) {
return name.compareTo(o.name);
}
}
| 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.android.globaltime;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.IntBuffer;
import java.nio.ShortBuffer;
import javax.microedition.khronos.opengles.GL10;
/**
* An abstract superclass for various three-dimensional objects to be drawn
* using OpenGL ES. Each subclass is responsible for setting up NIO buffers
* containing vertices, texture coordinates, colors, normals, and indices.
* The {@link #draw(GL10)} method draws the object to the given OpenGL context.
*/
public abstract class Shape {
public static final int INT_BYTES = 4;
public static final int SHORT_BYTES = 2;
public static final float DEGREES_TO_RADIANS = (float) Math.PI / 180.0f;
public static final float PI = (float) Math.PI;
public static final float TWO_PI = (float) (2.0 * Math.PI);
public static final float PI_OVER_TWO = (float) (Math.PI / 2.0);
protected int mPrimitive;
protected int mIndexDatatype;
protected boolean mEmitTextureCoordinates;
protected boolean mEmitNormals;
protected boolean mEmitColors;
protected IntBuffer mVertexBuffer;
protected IntBuffer mTexcoordBuffer;
protected IntBuffer mColorBuffer;
protected IntBuffer mNormalBuffer;
protected Buffer mIndexBuffer;
protected int mNumIndices = -1;
/**
* Constructs a Shape.
*
* @param primitive a GL primitive type understood by glDrawElements,
* such as GL10.GL_TRIANGLES
* @param indexDatatype the GL datatype for the index buffer, such as
* GL10.GL_UNSIGNED_SHORT
* @param emitTextureCoordinates true to enable use of the texture
* coordinate buffer
* @param emitNormals true to enable use of the normal buffer
* @param emitColors true to enable use of the color buffer
*/
protected Shape(int primitive,
int indexDatatype,
boolean emitTextureCoordinates,
boolean emitNormals,
boolean emitColors) {
mPrimitive = primitive;
mIndexDatatype = indexDatatype;
mEmitTextureCoordinates = emitTextureCoordinates;
mEmitNormals = emitNormals;
mEmitColors = emitColors;
}
/**
* Converts the given floating-point value to fixed-point.
*/
public static int toFixed(float x) {
return (int) (x * 65536.0);
}
/**
* Converts the given fixed-point value to floating-point.
*/
public static float toFloat(int x) {
return (float) (x / 65536.0);
}
/**
* Computes the cross-product of two vectors p and q and places
* the result in out.
*/
public static void cross(float[] p, float[] q, float[] out) {
out[0] = p[1] * q[2] - p[2] * q[1];
out[1] = p[2] * q[0] - p[0] * q[2];
out[2] = p[0] * q[1] - p[1] * q[0];
}
/**
* Returns the length of a vector, given as three floats.
*/
public static float length(float vx, float vy, float vz) {
return (float) Math.sqrt(vx * vx + vy * vy + vz * vz);
}
/**
* Returns the length of a vector, given as an array of three floats.
*/
public static float length(float[] v) {
return length(v[0], v[1], v[2]);
}
/**
* Normalizes the given vector of three floats to have length == 1.0.
* Vectors with length zero are unaffected.
*/
public static void normalize(float[] v) {
float length = length(v);
if (length != 0.0f) {
float norm = 1.0f / length;
v[0] *= norm;
v[1] *= norm;
v[2] *= norm;
}
}
/**
* Returns the number of triangles associated with this shape.
*/
public int getNumTriangles() {
if (mPrimitive == GL10.GL_TRIANGLES) {
return mIndexBuffer.capacity() / 3;
} else if (mPrimitive == GL10.GL_TRIANGLE_STRIP) {
return mIndexBuffer.capacity() - 2;
}
return 0;
}
/**
* Copies the given data into the instance
* variables mVertexBuffer, mTexcoordBuffer, mNormalBuffer, mColorBuffer,
* and mIndexBuffer.
*
* @param vertices an array of fixed-point vertex coordinates
* @param texcoords an array of fixed-point texture coordinates
* @param normals an array of fixed-point normal vector coordinates
* @param colors an array of fixed-point color channel values
* @param indices an array of short indices
*/
public void allocateBuffers(int[] vertices, int[] texcoords, int[] normals,
int[] colors, short[] indices) {
allocate(vertices, texcoords, normals, colors);
ByteBuffer ibb =
ByteBuffer.allocateDirect(indices.length * SHORT_BYTES);
ibb.order(ByteOrder.nativeOrder());
ShortBuffer shortIndexBuffer = ibb.asShortBuffer();
shortIndexBuffer.put(indices);
shortIndexBuffer.position(0);
this.mIndexBuffer = shortIndexBuffer;
}
/**
* Copies the given data into the instance
* variables mVertexBuffer, mTexcoordBuffer, mNormalBuffer, mColorBuffer,
* and mIndexBuffer.
*
* @param vertices an array of fixed-point vertex coordinates
* @param texcoords an array of fixed-point texture coordinates
* @param normals an array of fixed-point normal vector coordinates
* @param colors an array of fixed-point color channel values
* @param indices an array of int indices
*/
public void allocateBuffers(int[] vertices, int[] texcoords, int[] normals,
int[] colors, int[] indices) {
allocate(vertices, texcoords, normals, colors);
ByteBuffer ibb =
ByteBuffer.allocateDirect(indices.length * INT_BYTES);
ibb.order(ByteOrder.nativeOrder());
IntBuffer intIndexBuffer = ibb.asIntBuffer();
intIndexBuffer.put(indices);
intIndexBuffer.position(0);
this.mIndexBuffer = intIndexBuffer;
}
/**
* Allocate the vertex, texture coordinate, normal, and color buffer.
*/
private void allocate(int[] vertices, int[] texcoords, int[] normals,
int[] colors) {
ByteBuffer vbb =
ByteBuffer.allocateDirect(vertices.length * INT_BYTES);
vbb.order(ByteOrder.nativeOrder());
mVertexBuffer = vbb.asIntBuffer();
mVertexBuffer.put(vertices);
mVertexBuffer.position(0);
if ((texcoords != null) && mEmitTextureCoordinates) {
ByteBuffer tbb =
ByteBuffer.allocateDirect(texcoords.length * INT_BYTES);
tbb.order(ByteOrder.nativeOrder());
mTexcoordBuffer = tbb.asIntBuffer();
mTexcoordBuffer.put(texcoords);
mTexcoordBuffer.position(0);
}
if ((normals != null) && mEmitNormals) {
ByteBuffer nbb =
ByteBuffer.allocateDirect(normals.length * INT_BYTES);
nbb.order(ByteOrder.nativeOrder());
mNormalBuffer = nbb.asIntBuffer();
mNormalBuffer.put(normals);
mNormalBuffer.position(0);
}
if ((colors != null) && mEmitColors) {
ByteBuffer cbb =
ByteBuffer.allocateDirect(colors.length * INT_BYTES);
cbb.order(ByteOrder.nativeOrder());
mColorBuffer = cbb.asIntBuffer();
mColorBuffer.put(colors);
mColorBuffer.position(0);
}
}
/**
* Draws the shape to the given OpenGL ES 1.0 context. Texture coordinates,
* normals, and colors are emitted according the the preferences set for
* this shape.
*/
public void draw(GL10 gl) {
gl.glVertexPointer(3, GL10.GL_FIXED, 0, mVertexBuffer);
gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);
if (mEmitTextureCoordinates) {
gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
gl.glTexCoordPointer(2, GL10.GL_FIXED, 0, mTexcoordBuffer);
gl.glEnable(GL10.GL_TEXTURE_2D);
} else {
gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY);
gl.glDisable(GL10.GL_TEXTURE_2D);
}
if (mEmitNormals) {
gl.glEnableClientState(GL10.GL_NORMAL_ARRAY);
gl.glNormalPointer(GL10.GL_FIXED, 0, mNormalBuffer);
} else {
gl.glDisableClientState(GL10.GL_NORMAL_ARRAY);
}
if (mEmitColors) {
gl.glEnableClientState(GL10.GL_COLOR_ARRAY);
gl.glColorPointer(4, GL10.GL_FIXED, 0, mColorBuffer);
} else {
gl.glDisableClientState(GL10.GL_COLOR_ARRAY);
}
gl.glDrawElements(mPrimitive,
mNumIndices > 0 ? mNumIndices : mIndexBuffer.capacity(),
mIndexDatatype,
mIndexBuffer);
}
}
| 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.android.globaltime;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import java.text.DateFormat;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.RectF;
import android.text.format.DateUtils;
//import android.text.format.DateFormat;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.Interpolator;
/**
* A class that draws an analog clock face with information about the current
* time in a given city.
*/
public class Clock {
static final int MILLISECONDS_PER_MINUTE = 60 * 1000;
static final int MILLISECONDS_PER_HOUR = 60 * 60 * 1000;
private City mCity = null;
private long mCitySwitchTime;
private long mTime;
private float mColorRed = 1.0f;
private float mColorGreen = 1.0f;
private float mColorBlue = 1.0f;
private long mOldOffset;
private Interpolator mClockHandInterpolator =
new AccelerateDecelerateInterpolator();
public Clock() {
// Empty constructor
}
/**
* Adds a line to the given Path. The line extends from
* radius r0 to radius r1 about the center point (cx, cy),
* at an angle given by pos.
*
* @param path the Path to draw to
* @param radius the radius of the outer rim of the clock
* @param pos the angle, with 0 and 1 at 12:00
* @param cx the X coordinate of the clock center
* @param cy the Y coordinate of the clock center
* @param r0 the starting radius for the line
* @param r1 the ending radius for the line
*/
private static void drawLine(Path path,
float radius, float pos, float cx, float cy, float r0, float r1) {
float theta = pos * Shape.TWO_PI - Shape.PI_OVER_TWO;
float dx = (float) Math.cos(theta);
float dy = (float) Math.sin(theta);
float p0x = cx + dx * r0;
float p0y = cy + dy * r0;
float p1x = cx + dx * r1;
float p1y = cy + dy * r1;
float ox = (p1y - p0y);
float oy = -(p1x - p0x);
float norm = (radius / 2.0f) / (float) Math.sqrt(ox * ox + oy * oy);
ox *= norm;
oy *= norm;
path.moveTo(p0x - ox, p0y - oy);
path.lineTo(p1x - ox, p1y - oy);
path.lineTo(p1x + ox, p1y + oy);
path.lineTo(p0x + ox, p0y + oy);
path.close();
}
/**
* Adds a vertical arrow to the given Path.
*
* @param path the Path to draw to
*/
private static void drawVArrow(Path path,
float cx, float cy, float width, float height) {
path.moveTo(cx - width / 2.0f, cy);
path.lineTo(cx, cy + height);
path.lineTo(cx + width / 2.0f, cy);
path.close();
}
/**
* Adds a horizontal arrow to the given Path.
*
* @param path the Path to draw to
*/
private static void drawHArrow(Path path,
float cx, float cy, float width, float height) {
path.moveTo(cx, cy - height / 2.0f);
path.lineTo(cx + width, cy);
path.lineTo(cx, cy + height / 2.0f);
path.close();
}
/**
* Returns an offset in milliseconds to be subtracted from the current time
* in order to obtain an smooth interpolation between the previously
* displayed time and the current time.
*/
private long getOffset(float lerp) {
long doffset = (long) (mCity.getOffset() *
(float) MILLISECONDS_PER_HOUR - mOldOffset);
int sign;
if (doffset < 0) {
doffset = -doffset;
sign = -1;
} else {
sign = 1;
}
while (doffset > 12L * MILLISECONDS_PER_HOUR) {
doffset -= 12L * MILLISECONDS_PER_HOUR;
}
if (doffset > 6L * MILLISECONDS_PER_HOUR) {
doffset = 12L * MILLISECONDS_PER_HOUR - doffset;
sign = -sign;
}
// Interpolate doffset towards 0
doffset = (long)((1.0f - lerp)*doffset);
// Keep the same seconds count
long dh = doffset / (MILLISECONDS_PER_HOUR);
doffset -= dh * MILLISECONDS_PER_HOUR;
long dm = doffset / MILLISECONDS_PER_MINUTE;
doffset = sign * (60 * dh + dm) * MILLISECONDS_PER_MINUTE;
return doffset;
}
/**
* Set the city to be displayed. setCity(null) resets things so the clock
* hand animation won't occur next time.
*/
public void setCity(City city) {
if (mCity != city) {
if (mCity != null) {
mOldOffset =
(long) (mCity.getOffset() * (float) MILLISECONDS_PER_HOUR);
} else if (city != null) {
mOldOffset =
(long) (city.getOffset() * (float) MILLISECONDS_PER_HOUR);
} else {
mOldOffset = 0L; // this will never be used
}
this.mCitySwitchTime = System.currentTimeMillis();
this.mCity = city;
}
}
public void setTime(long time) {
this.mTime = time;
}
/**
* Draws the clock face.
*
* @param canvas the Canvas to draw to
* @param cx the X coordinate of the clock center
* @param cy the Y coordinate of the clock center
* @param radius the radius of the clock face
* @param alpha the translucency of the clock face
* @param textAlpha the translucency of the text
* @param showCityName if true, display the city name
* @param showTime if true, display the time digitally
* @param showUpArrow if true, display an up arrow
* @param showDownArrow if true, display a down arrow
* @param showLeftRightArrows if true, display left and right arrows
* @param prefixChars number of characters of the city name to draw in bold
*/
public void drawClock(Canvas canvas,
float cx, float cy, float radius, float alpha, float textAlpha,
boolean showCityName, boolean showTime,
boolean showUpArrow, boolean showDownArrow, boolean showLeftRightArrows,
int prefixChars) {
Paint paint = new Paint();
paint.setAntiAlias(true);
int iradius = (int)radius;
TimeZone tz = mCity.getTimeZone();
// Compute an interpolated time to animate between the previously
// displayed time and the current time
float lerp = Math.min(1.0f,
(System.currentTimeMillis() - mCitySwitchTime) / 500.0f);
lerp = mClockHandInterpolator.getInterpolation(lerp);
long doffset = lerp < 1.0f ? getOffset(lerp) : 0L;
// Determine the interpolated time for the given time zone
Calendar cal = Calendar.getInstance(tz);
cal.setTimeInMillis(mTime - doffset);
int hour = cal.get(Calendar.HOUR_OF_DAY);
int minute = cal.get(Calendar.MINUTE);
int second = cal.get(Calendar.SECOND);
int milli = cal.get(Calendar.MILLISECOND);
float offset = tz.getRawOffset() / (float) MILLISECONDS_PER_HOUR;
float daylightOffset = tz.inDaylightTime(new Date(mTime)) ?
tz.getDSTSavings() / (float) MILLISECONDS_PER_HOUR : 0.0f;
float absOffset = offset < 0 ? -offset : offset;
int offsetH = (int) absOffset;
int offsetM = (int) (60.0f * (absOffset - offsetH));
hour %= 12;
// Get the city name and digital time strings
String cityName = mCity.getName();
cal.setTimeInMillis(mTime);
//java.text.DateFormat mTimeFormat = android.text.format.DateFormat.getTimeFormat(this.getApplicationContext());
DateFormat mTimeFormat = DateFormat.getTimeInstance();
String time = mTimeFormat.format(cal.getTimeInMillis()) + " " +
DateUtils.getDayOfWeekString(cal.get(Calendar.DAY_OF_WEEK),
DateUtils.LENGTH_SHORT) + " " +
" (UTC" +
(offset >= 0 ? "+" : "-") +
offsetH +
(offsetM == 0 ? "" : ":" + offsetM) +
(daylightOffset == 0 ? "" : "+" + daylightOffset) +
")";
float th = paint.getTextSize();
float tw;
// Set the text color
paint.setARGB((int) (textAlpha * 255.0f),
(int) (mColorRed * 255.0f),
(int) (mColorGreen * 255.0f),
(int) (mColorBlue * 255.0f));
tw = paint.measureText(cityName);
if (showCityName) {
// Increment prefixChars to include any spaces
for (int i = 0; i < prefixChars; i++) {
if (cityName.charAt(i) == ' ') {
++prefixChars;
}
}
// Draw the city name
canvas.drawText(cityName, cx - tw / 2, cy - radius - th, paint);
// Overstrike the first 'prefixChars' characters
canvas.drawText(cityName.substring(0, prefixChars),
cx - tw / 2 + 1, cy - radius - th, paint);
}
tw = paint.measureText(time);
if (showTime) {
canvas.drawText(time, cx - tw / 2, cy + radius + th + 5, paint);
}
paint.setARGB((int)(alpha * 255.0f),
(int)(mColorRed * 255.0f),
(int)(mColorGreen * 255.0f),
(int)(mColorBlue * 255.0f));
paint.setStyle(Paint.Style.FILL);
canvas.drawOval(new RectF(cx - 2, cy - 2, cx + 2, cy + 2), paint);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(radius * 0.12f);
canvas.drawOval(new RectF(cx - iradius, cy - iradius,
cx + iradius, cy + iradius),
paint);
float r0 = radius * 0.1f;
float r1 = radius * 0.4f;
float r2 = radius * 0.6f;
float r3 = radius * 0.65f;
float r4 = radius * 0.7f;
float r5 = radius * 0.9f;
Path path = new Path();
float ss = second + milli / 1000.0f;
float mm = minute + ss / 60.0f;
float hh = hour + mm / 60.0f;
// Tics for the hours
for (int i = 0; i < 12; i++) {
drawLine(path, radius * 0.12f, i / 12.0f, cx, cy, r4, r5);
}
// Hour hand
drawLine(path, radius * 0.12f, hh / 12.0f, cx, cy, r0, r1);
// Minute hand
drawLine(path, radius * 0.12f, mm / 60.0f, cx, cy, r0, r2);
// Second hand
drawLine(path, radius * 0.036f, ss / 60.0f, cx, cy, r0, r3);
if (showUpArrow) {
drawVArrow(path, cx + radius * 1.13f, cy - radius,
radius * 0.15f, -radius * 0.1f);
}
if (showDownArrow) {
drawVArrow(path, cx + radius * 1.13f, cy + radius,
radius * 0.15f, radius * 0.1f);
}
if (showLeftRightArrows) {
drawHArrow(path, cx - radius * 1.3f, cy, -radius * 0.1f,
radius * 0.15f);
drawHArrow(path, cx + radius * 1.3f, cy, radius * 0.1f,
radius * 0.15f);
}
paint.setStyle(Paint.Style.FILL);
canvas.drawPath(path, paint);
}
}
| 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.android.globaltime;
import javax.microedition.khronos.opengles.GL10;
/**
* A class that draws a ring with a given center and inner and outer radii.
* The inner and outer rings each have a color and the remaining pixels are
* colored by interpolation. GlobalTime uses this class to simulate an
* "atmosphere" around the earth.
*/
public class Annulus extends Shape {
/**
* Constructs an annulus.
*
* @param centerX the X coordinate of the center point
* @param centerY the Y coordinate of the center point
* @param Z the fixed Z for the entire ring
* @param innerRadius the inner radius
* @param outerRadius the outer radius
* @param rInner the red channel of the color of the inner ring
* @param gInner the green channel of the color of the inner ring
* @param bInner the blue channel of the color of the inner ring
* @param aInner the alpha channel of the color of the inner ring
* @param rOuter the red channel of the color of the outer ring
* @param gOuter the green channel of the color of the outer ring
* @param bOuter the blue channel of the color of the outer ring
* @param aOuter the alpha channel of the color of the outer ring
* @param sectors the number of sectors used to approximate curvature
*/
public Annulus(float centerX, float centerY, float Z,
float innerRadius, float outerRadius,
float rInner, float gInner, float bInner, float aInner,
float rOuter, float gOuter, float bOuter, float aOuter,
int sectors) {
super(GL10.GL_TRIANGLES, GL10.GL_UNSIGNED_SHORT,
false, false, true);
int radii = sectors + 1;
int[] vertices = new int[2 * 3 * radii];
int[] colors = new int[2 * 4 * radii];
short[] indices = new short[2 * 3 * radii];
int vidx = 0;
int cidx = 0;
int iidx = 0;
for (int i = 0; i < radii; i++) {
float theta = (i * TWO_PI) / (radii - 1);
float cosTheta = (float) Math.cos(theta);
float sinTheta = (float) Math.sin(theta);
vertices[vidx++] = toFixed(centerX + innerRadius * cosTheta);
vertices[vidx++] = toFixed(centerY + innerRadius * sinTheta);
vertices[vidx++] = toFixed(Z);
vertices[vidx++] = toFixed(centerX + outerRadius * cosTheta);
vertices[vidx++] = toFixed(centerY + outerRadius * sinTheta);
vertices[vidx++] = toFixed(Z);
colors[cidx++] = toFixed(rInner);
colors[cidx++] = toFixed(gInner);
colors[cidx++] = toFixed(bInner);
colors[cidx++] = toFixed(aInner);
colors[cidx++] = toFixed(rOuter);
colors[cidx++] = toFixed(gOuter);
colors[cidx++] = toFixed(bOuter);
colors[cidx++] = toFixed(aOuter);
}
for (int i = 0; i < sectors; i++) {
indices[iidx++] = (short) (2 * i);
indices[iidx++] = (short) (2 * i + 1);
indices[iidx++] = (short) (2 * i + 2);
indices[iidx++] = (short) (2 * i + 1);
indices[iidx++] = (short) (2 * i + 3);
indices[iidx++] = (short) (2 * i + 2);
}
allocateBuffers(vertices, null, null, colors, indices);
}
}
| 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.android.globaltime;
import java.nio.ByteBuffer;
public class Texture {
private ByteBuffer data;
private int width, height;
public Texture(ByteBuffer data, int width, int height) {
this.data = data;
this.width = width;
this.height = height;
}
public ByteBuffer getData() {
return data;
}
public int getWidth() {
return width;
}
public int getHeight() {
return height;
}
}
| 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.android.globaltime;
import javax.microedition.khronos.opengles.GL10;
public class Sphere extends Shape {
public Sphere(boolean emitTextureCoordinates,
boolean emitNormals, boolean emitColors) {
super(GL10.GL_TRIANGLES, GL10.GL_UNSIGNED_SHORT,
emitTextureCoordinates, emitNormals, emitColors);
}
}
| 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.android.globaltime;
import javax.microedition.khronos.opengles.GL10;
/**
* A class representing a set of GL_POINT objects. GlobalTime uses this class
* to draw city lights on the night side of the earth.
*/
public class PointCloud extends Shape {
/**
* Constructs a PointCloud with a point at each of the given vertex
* (x, y, z) positions.
* @param vertices an array of (x, y, z) positions given in fixed-point.
*/
public PointCloud(int[] vertices) {
this(vertices, 0, vertices.length);
}
/**
* Constructs a PointCloud with a point at each of the given vertex
* (x, y, z) positions.
* @param vertices an array of (x, y, z) positions given in fixed-point.
* @param off the starting offset of the vertices array
* @param len the number of elements of the vertices array to use
*/
public PointCloud(int[] vertices, int off, int len) {
super(GL10.GL_POINTS, GL10.GL_UNSIGNED_SHORT,
false, false, false);
int numPoints = len / 3;
short[] indices = new short[numPoints];
for (int i = 0; i < numPoints; i++) {
indices[i] = (short)i;
}
allocateBuffers(vertices, null, null, null, indices);
this.mNumIndices = mIndexBuffer.capacity();
}
@Override public int getNumTriangles() {
return mNumIndices * 2;
}
}
| 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.android.globaltime;
import java.io.ByteArrayInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;
import java.util.TimeZone;
import javax.microedition.khronos.egl.*;
import javax.microedition.khronos.opengles.*;
import android.app.Activity;
import android.content.Context;
import android.content.res.AssetManager;
import android.graphics.Canvas;
import android.opengl.Object3D;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.MessageQueue;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.DecelerateInterpolator;
import android.view.animation.Interpolator;
/**
* The main View of the GlobalTime Activity.
*/
class GTView extends SurfaceView implements SurfaceHolder.Callback {
/**
* A TimeZone object used to compute the current UTC time.
*/
private static final TimeZone UTC_TIME_ZONE = TimeZone.getTimeZone("utc");
/**
* The Sun's color is close to that of a 5780K blackbody.
*/
private static final float[] SUNLIGHT_COLOR = {
1.0f, 0.9375f, 0.91015625f, 1.0f
};
/**
* The inclination of the earth relative to the plane of the ecliptic
* is 23.45 degrees.
*/
private static final float EARTH_INCLINATION = 23.45f * Shape.PI / 180.0f;
/** Seconds in a day */
private static final int SECONDS_PER_DAY = 24 * 60 * 60;
/** Flag for the depth test */
private static final boolean PERFORM_DEPTH_TEST= false;
/** Use raw time zone offsets, disregarding "summer time." If false,
* current offsets will be used, which requires a much longer startup time
* in order to sort the city database.
*/
private static final boolean USE_RAW_OFFSETS = true;
/**
* The earth's atmosphere.
*/
private static final Annulus ATMOSPHERE =
new Annulus(0.0f, 0.0f, 1.75f, 0.9f, 1.08f, 0.4f, 0.4f, 0.8f, 0.0f,
0.0f, 0.0f, 0.0f, 1.0f, 50);
/**
* The tesselation of the earth by latitude.
*/
private static final int SPHERE_LATITUDES = 25;
/**
* The tesselation of the earth by longitude.
*/
private static int SPHERE_LONGITUDES = 25;
/**
* A flattened version of the earth. The normals are computed identically
* to those of the round earth, allowing the day/night lighting to be
* applied to the flattened surface.
*/
private static Sphere worldFlat = new LatLongSphere(0.0f, 0.0f, 0.0f, 1.0f,
SPHERE_LATITUDES, SPHERE_LONGITUDES,
0.0f, 360.0f, true, true, false, true);
/**
* The earth.
*/
private Object3D mWorld;
/**
* Geometry of the city lights
*/
private PointCloud mLights;
/**
* True if the activiy has been initialized.
*/
boolean mInitialized = false;
/**
* True if we're in alphabetic entry mode.
*/
private boolean mAlphaKeySet = false;
private EGLContext mEGLContext;
private EGLSurface mEGLSurface;
private EGLDisplay mEGLDisplay;
private EGLConfig mEGLConfig;
GLView mGLView;
// Rotation and tilt of the Earth
private float mRotAngle = 0.0f;
private float mTiltAngle = 0.0f;
// Rotational velocity of the orbiting viewer
private float mRotVelocity = 1.0f;
// Rotation of the flat view
private float mWrapX = 0.0f;
private float mWrapVelocity = 0.0f;
private float mWrapVelocityFactor = 0.01f;
// Toggle switches
private boolean mDisplayAtmosphere = true;
private boolean mDisplayClock = false;
private boolean mClockShowing = false;
private boolean mDisplayLights = false;
private boolean mDisplayWorld = true;
private boolean mDisplayWorldFlat = false;
private boolean mSmoothShading = true;
// City search string
private String mCityName = "";
// List of all cities
private List<City> mClockCities;
// List of cities matching a user-supplied prefix
private List<City> mCityNameMatches = new ArrayList<City>();
private List<City> mCities;
// Start time for clock fade animation
private long mClockFadeTime;
// Interpolator for clock fade animation
private Interpolator mClockSizeInterpolator =
new DecelerateInterpolator(1.0f);
// Index of current clock
private int mCityIndex;
// Current clock
private Clock mClock;
// City-to-city flight animation parameters
private boolean mFlyToCity = false;
private long mCityFlyStartTime;
private float mCityFlightTime;
private float mRotAngleStart, mRotAngleDest;
private float mTiltAngleStart, mTiltAngleDest;
// Interpolator for flight motion animation
private Interpolator mFlyToCityInterpolator =
new AccelerateDecelerateInterpolator();
private static int sNumLights;
private static int[] sLightCoords;
// static Map<Float,int[]> cityCoords = new HashMap<Float,int[]>();
// Arrays for GL calls
private float[] mClipPlaneEquation = new float[4];
private float[] mLightDir = new float[4];
// Calendar for computing the Sun's position
Calendar mSunCal = Calendar.getInstance(UTC_TIME_ZONE);
// Triangles drawn per frame
private int mNumTriangles;
private long startTime;
private static final int MOTION_NONE = 0;
private static final int MOTION_X = 1;
private static final int MOTION_Y = 2;
private static final int MIN_MANHATTAN_DISTANCE = 20;
private static final float ROTATION_FACTOR = 1.0f / 30.0f;
private static final float TILT_FACTOR = 0.35f;
// Touchscreen support
private float mMotionStartX;
private float mMotionStartY;
private float mMotionStartRotVelocity;
private float mMotionStartTiltAngle;
private int mMotionDirection;
public void surfaceCreated(SurfaceHolder holder) {
EGL10 egl = (EGL10)EGLContext.getEGL();
mEGLSurface = egl.eglCreateWindowSurface(mEGLDisplay, mEGLConfig, this, null);
egl.eglMakeCurrent(mEGLDisplay, mEGLSurface, mEGLSurface, mEGLContext);
}
public void surfaceDestroyed(SurfaceHolder holder) {
// nothing to do
}
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
// nothing to do
}
/**
* Set up the view.
*
* @param context the Context
* @param am an AssetManager to retrieve the city database from
*/
public GTView(Context context) {
super(context);
getHolder().addCallback(this);
getHolder().setType(SurfaceHolder.SURFACE_TYPE_GPU);
AssetManager am = context.getAssets();
startTime = System.currentTimeMillis();
EGL10 egl = (EGL10)EGLContext.getEGL();
EGLDisplay dpy = egl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY);
int[] version = new int[2];
egl.eglInitialize(dpy, version);
int[] configSpec = {
EGL10.EGL_DEPTH_SIZE, 16,
EGL10.EGL_NONE
};
EGLConfig[] configs = new EGLConfig[1];
int[] num_config = new int[1];
egl.eglChooseConfig(dpy, configSpec, configs, 1, num_config);
mEGLConfig = configs[0];
mEGLContext = egl.eglCreateContext(dpy, mEGLConfig, EGL10.EGL_NO_CONTEXT, null);
mEGLDisplay = dpy;
mClock = new Clock();
setFocusable(true);
setFocusableInTouchMode(true);
requestFocus();
try {
loadAssets(am);
} catch (IOException ioe) {
ioe.printStackTrace();
throw new RuntimeException(ioe);
} catch (ArrayIndexOutOfBoundsException aioobe) {
aioobe.printStackTrace();
throw new RuntimeException(aioobe);
}
}
/**
* Destroy the view.
*/
public void destroy() {
EGL10 egl = (EGL10)EGLContext.getEGL();
egl.eglMakeCurrent(mEGLDisplay,
egl.EGL_NO_SURFACE, egl.EGL_NO_SURFACE, egl.EGL_NO_CONTEXT);
egl.eglDestroyContext(mEGLDisplay, mEGLContext);
egl.eglDestroySurface(mEGLDisplay, mEGLSurface);
egl.eglTerminate(mEGLDisplay);
mEGLContext = null;
}
/**
* Begin animation.
*/
public void startAnimating() {
mHandler.sendEmptyMessage(INVALIDATE);
}
/**
* Quit animation.
*/
public void stopAnimating() {
mHandler.removeMessages(INVALIDATE);
}
/**
* Read a two-byte integer from the input stream.
*/
private int readInt16(InputStream is) throws IOException {
int lo = is.read();
int hi = is.read();
return (hi << 8) | lo;
}
/**
* Returns the offset from UTC for the given city. If USE_RAW_OFFSETS
* is true, summer/daylight savings is ignored.
*/
private static float getOffset(City c) {
return USE_RAW_OFFSETS ? c.getRawOffset() : c.getOffset();
}
private InputStream cache(InputStream is) throws IOException {
int nbytes = is.available();
byte[] data = new byte[nbytes];
int nread = 0;
while (nread < nbytes) {
nread += is.read(data, nread, nbytes - nread);
}
return new ByteArrayInputStream(data);
}
/**
* Load the city and lights databases.
*
* @param am the AssetManager to load from.
*/
private void loadAssets(final AssetManager am) throws IOException {
Locale locale = Locale.getDefault();
String language = locale.getLanguage();
String country = locale.getCountry();
InputStream cis = null;
try {
// Look for (e.g.) cities_fr_FR.dat or cities_fr_CA.dat
cis = am.open("cities_" + language + "_" + country + ".dat");
} catch (FileNotFoundException e1) {
try {
// Look for (e.g.) cities_fr.dat or cities_fr.dat
cis = am.open("cities_" + language + ".dat");
} catch (FileNotFoundException e2) {
try {
// Use English city names by default
cis = am.open("cities_en.dat");
} catch (FileNotFoundException e3) {
throw e3;
}
}
}
cis = cache(cis);
City.loadCities(cis);
City[] cities;
if (USE_RAW_OFFSETS) {
cities = City.getCitiesByRawOffset();
} else {
cities = City.getCitiesByOffset();
}
mClockCities = new ArrayList<City>(cities.length);
for (int i = 0; i < cities.length; i++) {
mClockCities.add(cities[i]);
}
mCities = mClockCities;
mCityIndex = 0;
this.mWorld = new Object3D() {
@Override
public InputStream readFile(String filename)
throws IOException {
return cache(am.open(filename));
}
};
mWorld.load("world.gles");
// lights.dat has the following format. All integers
// are 16 bits, low byte first.
//
// width
// height
// N [# of lights]
// light 0 X [in the range 0 to (width - 1)]
// light 0 Y ]in the range 0 to (height - 1)]
// light 1 X [in the range 0 to (width - 1)]
// light 1 Y ]in the range 0 to (height - 1)]
// ...
// light (N - 1) X [in the range 0 to (width - 1)]
// light (N - 1) Y ]in the range 0 to (height - 1)]
//
// For a larger number of lights, it could make more
// sense to store the light positions in a bitmap
// and extract them manually
InputStream lis = am.open("lights.dat");
lis = cache(lis);
int lightWidth = readInt16(lis);
int lightHeight = readInt16(lis);
sNumLights = readInt16(lis);
sLightCoords = new int[3 * sNumLights];
int lidx = 0;
float lightRadius = 1.009f;
float lightScale = 65536.0f * lightRadius;
float[] cosTheta = new float[lightWidth];
float[] sinTheta = new float[lightWidth];
float twoPi = (float) (2.0 * Math.PI);
float scaleW = twoPi / lightWidth;
for (int i = 0; i < lightWidth; i++) {
float theta = twoPi - i * scaleW;
cosTheta[i] = (float)Math.cos(theta);
sinTheta[i] = (float)Math.sin(theta);
}
float[] cosPhi = new float[lightHeight];
float[] sinPhi = new float[lightHeight];
float scaleH = (float) (Math.PI / lightHeight);
for (int j = 0; j < lightHeight; j++) {
float phi = j * scaleH;
cosPhi[j] = (float)Math.cos(phi);
sinPhi[j] = (float)Math.sin(phi);
}
int nbytes = 4 * sNumLights;
byte[] ilights = new byte[nbytes];
int nread = 0;
while (nread < nbytes) {
nread += lis.read(ilights, nread, nbytes - nread);
}
int idx = 0;
for (int i = 0; i < sNumLights; i++) {
int lx = (((ilights[idx + 1] & 0xff) << 8) |
(ilights[idx ] & 0xff));
int ly = (((ilights[idx + 3] & 0xff) << 8) |
(ilights[idx + 2] & 0xff));
idx += 4;
float sin = sinPhi[ly];
float x = cosTheta[lx]*sin;
float y = cosPhi[ly];
float z = sinTheta[lx]*sin;
sLightCoords[lidx++] = (int) (x * lightScale);
sLightCoords[lidx++] = (int) (y * lightScale);
sLightCoords[lidx++] = (int) (z * lightScale);
}
mLights = new PointCloud(sLightCoords);
}
/**
* Returns true if two time zone offsets are equal. We assume distinct
* time zone offsets will differ by at least a few minutes.
*/
private boolean tzEqual(float o1, float o2) {
return Math.abs(o1 - o2) < 0.001;
}
/**
* Move to a different time zone.
*
* @param incr The increment between the current and future time zones.
*/
private void shiftTimeZone(int incr) {
// If only 1 city in the current set, there's nowhere to go
if (mCities.size() <= 1) {
return;
}
float offset = getOffset(mCities.get(mCityIndex));
do {
mCityIndex = (mCityIndex + mCities.size() + incr) % mCities.size();
} while (tzEqual(getOffset(mCities.get(mCityIndex)), offset));
offset = getOffset(mCities.get(mCityIndex));
locateCity(true, offset);
goToCity();
}
/**
* Returns true if there is another city within the current time zone
* that is the given increment away from the current city.
*
* @param incr the increment, +1 or -1
* @return
*/
private boolean atEndOfTimeZone(int incr) {
if (mCities.size() <= 1) {
return true;
}
float offset = getOffset(mCities.get(mCityIndex));
int nindex = (mCityIndex + mCities.size() + incr) % mCities.size();
if (tzEqual(getOffset(mCities.get(nindex)), offset)) {
return false;
}
return true;
}
/**
* Shifts cities within the current time zone.
*
* @param incr the increment, +1 or -1
*/
private void shiftWithinTimeZone(int incr) {
float offset = getOffset(mCities.get(mCityIndex));
int nindex = (mCityIndex + mCities.size() + incr) % mCities.size();
if (tzEqual(getOffset(mCities.get(nindex)), offset)) {
mCityIndex = nindex;
goToCity();
}
}
/**
* Returns true if the city name matches the given prefix, ignoring spaces.
*/
private boolean nameMatches(City city, String prefix) {
String cityName = city.getName().replaceAll("[ ]", "");
return prefix.regionMatches(true, 0,
cityName, 0,
prefix.length());
}
/**
* Returns true if there are cities matching the given name prefix.
*/
private boolean hasMatches(String prefix) {
for (int i = 0; i < mClockCities.size(); i++) {
City city = mClockCities.get(i);
if (nameMatches(city, prefix)) {
return true;
}
}
return false;
}
/**
* Shifts to the nearest city that matches the new prefix.
*/
private void shiftByName() {
// Attempt to keep current city if it matches
City finalCity = null;
City currCity = mCities.get(mCityIndex);
if (nameMatches(currCity, mCityName)) {
finalCity = currCity;
}
mCityNameMatches.clear();
for (int i = 0; i < mClockCities.size(); i++) {
City city = mClockCities.get(i);
if (nameMatches(city, mCityName)) {
mCityNameMatches.add(city);
}
}
mCities = mCityNameMatches;
if (finalCity != null) {
for (int i = 0; i < mCityNameMatches.size(); i++) {
if (mCityNameMatches.get(i) == finalCity) {
mCityIndex = i;
break;
}
}
} else {
// Find the closest matching city
locateCity(false, 0.0f);
}
goToCity();
}
/**
* Increases or decreases the rotational speed of the earth.
*/
private void incrementRotationalVelocity(float incr) {
if (mDisplayWorldFlat) {
mWrapVelocity -= incr;
} else {
mRotVelocity -= incr;
}
}
/**
* Clears the current matching prefix, while keeping the focus on
* the current city.
*/
private void clearCityMatches() {
// Determine the global city index that matches the current city
if (mCityNameMatches.size() > 0) {
City city = mCityNameMatches.get(mCityIndex);
for (int i = 0; i < mClockCities.size(); i++) {
City ncity = mClockCities.get(i);
if (city.equals(ncity)) {
mCityIndex = i;
break;
}
}
}
mCityName = "";
mCityNameMatches.clear();
mCities = mClockCities;
goToCity();
}
/**
* Fade the clock in or out.
*/
private void enableClock(boolean enabled) {
mClockFadeTime = System.currentTimeMillis();
mDisplayClock = enabled;
mClockShowing = true;
mAlphaKeySet = enabled;
if (enabled) {
// Find the closest matching city
locateCity(false, 0.0f);
}
clearCityMatches();
}
/**
* Use the touchscreen to alter the rotational velocity or the
* tilt of the earth.
*/
@Override public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
mMotionStartX = event.getX();
mMotionStartY = event.getY();
mMotionStartRotVelocity = mDisplayWorldFlat ?
mWrapVelocity : mRotVelocity;
mMotionStartTiltAngle = mTiltAngle;
// Stop the rotation
if (mDisplayWorldFlat) {
mWrapVelocity = 0.0f;
} else {
mRotVelocity = 0.0f;
}
mMotionDirection = MOTION_NONE;
break;
case MotionEvent.ACTION_MOVE:
// Disregard motion events when the clock is displayed
float dx = event.getX() - mMotionStartX;
float dy = event.getY() - mMotionStartY;
float delx = Math.abs(dx);
float dely = Math.abs(dy);
// Determine the direction of motion (major axis)
// Once if has been determined, it's locked in until
// we receive ACTION_UP or ACTION_CANCEL
if ((mMotionDirection == MOTION_NONE) &&
(delx + dely > MIN_MANHATTAN_DISTANCE)) {
if (delx > dely) {
mMotionDirection = MOTION_X;
} else {
mMotionDirection = MOTION_Y;
}
}
// If the clock is displayed, don't actually rotate or tilt;
// just use mMotionDirection to record whether motion occurred
if (!mDisplayClock) {
if (mMotionDirection == MOTION_X) {
if (mDisplayWorldFlat) {
mWrapVelocity = mMotionStartRotVelocity +
dx * ROTATION_FACTOR;
} else {
mRotVelocity = mMotionStartRotVelocity +
dx * ROTATION_FACTOR;
}
mClock.setCity(null);
} else if (mMotionDirection == MOTION_Y &&
!mDisplayWorldFlat) {
mTiltAngle = mMotionStartTiltAngle + dy * TILT_FACTOR;
if (mTiltAngle < -90.0f) {
mTiltAngle = -90.0f;
}
if (mTiltAngle > 90.0f) {
mTiltAngle = 90.0f;
}
mClock.setCity(null);
}
}
break;
case MotionEvent.ACTION_UP:
mMotionDirection = MOTION_NONE;
break;
case MotionEvent.ACTION_CANCEL:
mTiltAngle = mMotionStartTiltAngle;
if (mDisplayWorldFlat) {
mWrapVelocity = mMotionStartRotVelocity;
} else {
mRotVelocity = mMotionStartRotVelocity;
}
mMotionDirection = MOTION_NONE;
break;
}
return true;
}
@Override public boolean onKeyDown(int keyCode, KeyEvent event) {
if (mInitialized && mGLView.processKey(keyCode)) {
boolean drawing = (mClockShowing || mGLView.hasMessages());
this.setWillNotDraw(!drawing);
return true;
}
boolean handled = false;
// If we're not in alphabetical entry mode, convert letters
// to their digit equivalents
if (!mAlphaKeySet) {
char numChar = event.getNumber();
if (numChar >= '0' && numChar <= '9') {
keyCode = KeyEvent.KEYCODE_0 + (numChar - '0');
}
}
switch (keyCode) {
// The 'space' key toggles the clock
case KeyEvent.KEYCODE_SPACE:
mAlphaKeySet = !mAlphaKeySet;
enableClock(mAlphaKeySet);
handled = true;
break;
// The 'left' and 'right' buttons shift time zones if the clock is
// displayed, otherwise they alters the rotational speed of the earthh
case KeyEvent.KEYCODE_DPAD_LEFT:
if (mDisplayClock) {
shiftTimeZone(-1);
} else {
mClock.setCity(null);
incrementRotationalVelocity(1.0f);
}
handled = true;
break;
case KeyEvent.KEYCODE_DPAD_RIGHT:
if (mDisplayClock) {
shiftTimeZone(1);
} else {
mClock.setCity(null);
incrementRotationalVelocity(-1.0f);
}
handled = true;
break;
// The 'up' and 'down' buttons shift cities within a time zone if the
// clock is displayed, otherwise they tilt the earth
case KeyEvent.KEYCODE_DPAD_UP:
if (mDisplayClock) {
shiftWithinTimeZone(-1);
} else {
mClock.setCity(null);
if (!mDisplayWorldFlat) {
mTiltAngle += 360.0f / 48.0f;
}
}
handled = true;
break;
case KeyEvent.KEYCODE_DPAD_DOWN:
if (mDisplayClock) {
shiftWithinTimeZone(1);
} else {
mClock.setCity(null);
if (!mDisplayWorldFlat) {
mTiltAngle -= 360.0f / 48.0f;
}
}
handled = true;
break;
// The center key stops the earth's rotation, then toggles between the
// round and flat views of the earth
case KeyEvent.KEYCODE_DPAD_CENTER:
if ((!mDisplayWorldFlat && mRotVelocity == 0.0f) ||
(mDisplayWorldFlat && mWrapVelocity == 0.0f)) {
mDisplayWorldFlat = !mDisplayWorldFlat;
} else {
if (mDisplayWorldFlat) {
mWrapVelocity = 0.0f;
} else {
mRotVelocity = 0.0f;
}
}
handled = true;
break;
// The 'L' key toggles the city lights
case KeyEvent.KEYCODE_L:
if (!mAlphaKeySet && !mDisplayWorldFlat) {
mDisplayLights = !mDisplayLights;
handled = true;
}
break;
// The 'W' key toggles the earth (just for fun)
case KeyEvent.KEYCODE_W:
if (!mAlphaKeySet && !mDisplayWorldFlat) {
mDisplayWorld = !mDisplayWorld;
handled = true;
}
break;
// The 'A' key toggles the atmosphere
case KeyEvent.KEYCODE_A:
if (!mAlphaKeySet && !mDisplayWorldFlat) {
mDisplayAtmosphere = !mDisplayAtmosphere;
handled = true;
}
break;
// The '2' key zooms out
case KeyEvent.KEYCODE_2:
if (!mAlphaKeySet && !mDisplayWorldFlat) {
mGLView.zoom(-2);
handled = true;
}
break;
// The '8' key zooms in
case KeyEvent.KEYCODE_8:
if (!mAlphaKeySet && !mDisplayWorldFlat) {
mGLView.zoom(2);
handled = true;
}
break;
}
// Handle letters in city names
if (!handled && mAlphaKeySet) {
switch (keyCode) {
// Add a letter to the city name prefix
case KeyEvent.KEYCODE_A:
case KeyEvent.KEYCODE_B:
case KeyEvent.KEYCODE_C:
case KeyEvent.KEYCODE_D:
case KeyEvent.KEYCODE_E:
case KeyEvent.KEYCODE_F:
case KeyEvent.KEYCODE_G:
case KeyEvent.KEYCODE_H:
case KeyEvent.KEYCODE_I:
case KeyEvent.KEYCODE_J:
case KeyEvent.KEYCODE_K:
case KeyEvent.KEYCODE_L:
case KeyEvent.KEYCODE_M:
case KeyEvent.KEYCODE_N:
case KeyEvent.KEYCODE_O:
case KeyEvent.KEYCODE_P:
case KeyEvent.KEYCODE_Q:
case KeyEvent.KEYCODE_R:
case KeyEvent.KEYCODE_S:
case KeyEvent.KEYCODE_T:
case KeyEvent.KEYCODE_U:
case KeyEvent.KEYCODE_V:
case KeyEvent.KEYCODE_W:
case KeyEvent.KEYCODE_X:
case KeyEvent.KEYCODE_Y:
case KeyEvent.KEYCODE_Z:
char c = (char)(keyCode - KeyEvent.KEYCODE_A + 'A');
if (hasMatches(mCityName + c)) {
mCityName += c;
shiftByName();
}
handled = true;
break;
// Remove a letter from the city name prefix
case KeyEvent.KEYCODE_DEL:
if (mCityName.length() > 0) {
mCityName = mCityName.substring(0, mCityName.length() - 1);
shiftByName();
} else {
clearCityMatches();
}
handled = true;
break;
// Clear the city name prefix
case KeyEvent.KEYCODE_ENTER:
clearCityMatches();
handled = true;
break;
}
}
boolean drawing = (mClockShowing ||
((mGLView != null) && (mGLView.hasMessages())));
this.setWillNotDraw(!drawing);
// Let the system handle other keypresses
if (!handled) {
return super.onKeyDown(keyCode, event);
}
return true;
}
/**
* Initialize OpenGL ES drawing.
*/
private synchronized void init(GL10 gl) {
mGLView = new GLView();
mGLView.setNearFrustum(5.0f);
mGLView.setFarFrustum(50.0f);
mGLView.setLightModelAmbientIntensity(0.225f);
mGLView.setAmbientIntensity(0.0f);
mGLView.setDiffuseIntensity(1.5f);
mGLView.setDiffuseColor(SUNLIGHT_COLOR);
mGLView.setSpecularIntensity(0.0f);
mGLView.setSpecularColor(SUNLIGHT_COLOR);
if (PERFORM_DEPTH_TEST) {
gl.glEnable(GL10.GL_DEPTH_TEST);
}
gl.glDisable(GL10.GL_SCISSOR_TEST);
gl.glClearColor(0, 0, 0, 1);
gl.glHint(GL10.GL_POINT_SMOOTH_HINT, GL10.GL_NICEST);
mInitialized = true;
}
/**
* Computes the vector from the center of the earth to the sun for a
* particular moment in time.
*/
private void computeSunDirection() {
mSunCal.setTimeInMillis(System.currentTimeMillis());
int day = mSunCal.get(Calendar.DAY_OF_YEAR);
int seconds = 3600 * mSunCal.get(Calendar.HOUR_OF_DAY) +
60 * mSunCal.get(Calendar.MINUTE) + mSunCal.get(Calendar.SECOND);
day += (float) seconds / SECONDS_PER_DAY;
// Approximate declination of the sun, changes sinusoidally
// during the year. The winter solstice occurs 10 days before
// the start of the year.
float decl = (float) (EARTH_INCLINATION *
Math.cos(Shape.TWO_PI * (day + 10) / 365.0));
// Subsolar latitude, convert from (-PI/2, PI/2) -> (0, PI) form
float phi = decl + Shape.PI_OVER_TWO;
// Subsolar longitude
float theta = Shape.TWO_PI * seconds / SECONDS_PER_DAY;
float sinPhi = (float) Math.sin(phi);
float cosPhi = (float) Math.cos(phi);
float sinTheta = (float) Math.sin(theta);
float cosTheta = (float) Math.cos(theta);
// Convert from polar to rectangular coordinates
float x = cosTheta * sinPhi;
float y = cosPhi;
float z = sinTheta * sinPhi;
// Directional light -> w == 0
mLightDir[0] = x;
mLightDir[1] = y;
mLightDir[2] = z;
mLightDir[3] = 0.0f;
}
/**
* Computes the approximate spherical distance between two
* (latitude, longitude) coordinates.
*/
private float distance(float lat1, float lon1,
float lat2, float lon2) {
lat1 *= Shape.DEGREES_TO_RADIANS;
lat2 *= Shape.DEGREES_TO_RADIANS;
lon1 *= Shape.DEGREES_TO_RADIANS;
lon2 *= Shape.DEGREES_TO_RADIANS;
float r = 6371.0f; // Earth's radius in km
float dlat = lat2 - lat1;
float dlon = lon2 - lon1;
double sinlat2 = Math.sin(dlat / 2.0f);
sinlat2 *= sinlat2;
double sinlon2 = Math.sin(dlon / 2.0f);
sinlon2 *= sinlon2;
double a = sinlat2 + Math.cos(lat1) * Math.cos(lat2) * sinlon2;
double c = 2.0 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
return (float) (r * c);
}
/**
* Locates the closest city to the currently displayed center point,
* optionally restricting the search to cities within a given time zone.
*/
private void locateCity(boolean useOffset, float offset) {
float mindist = Float.MAX_VALUE;
int minidx = -1;
for (int i = 0; i < mCities.size(); i++) {
City city = mCities.get(i);
if (useOffset && !tzEqual(getOffset(city), offset)) {
continue;
}
float dist = distance(city.getLatitude(), city.getLongitude(),
mTiltAngle, mRotAngle - 90.0f);
if (dist < mindist) {
mindist = dist;
minidx = i;
}
}
mCityIndex = minidx;
}
/**
* Animates the earth to be centered at the current city.
*/
private void goToCity() {
City city = mCities.get(mCityIndex);
float dist = distance(city.getLatitude(), city.getLongitude(),
mTiltAngle, mRotAngle - 90.0f);
mFlyToCity = true;
mCityFlyStartTime = System.currentTimeMillis();
mCityFlightTime = dist / 5.0f; // 5000 km/sec
mRotAngleStart = mRotAngle;
mRotAngleDest = city.getLongitude() + 90;
if (mRotAngleDest - mRotAngleStart > 180.0f) {
mRotAngleDest -= 360.0f;
} else if (mRotAngleStart - mRotAngleDest > 180.0f) {
mRotAngleDest += 360.0f;
}
mTiltAngleStart = mTiltAngle;
mTiltAngleDest = city.getLatitude();
mRotVelocity = 0.0f;
}
/**
* Returns a linearly interpolated value between two values.
*/
private float lerp(float a, float b, float lerp) {
return a + (b - a)*lerp;
}
/**
* Draws the city lights, using a clip plane to restrict the lights
* to the night side of the earth.
*/
private void drawCityLights(GL10 gl, float brightness) {
gl.glEnable(GL10.GL_POINT_SMOOTH);
gl.glDisable(GL10.GL_DEPTH_TEST);
gl.glDisable(GL10.GL_LIGHTING);
gl.glDisable(GL10.GL_DITHER);
gl.glShadeModel(GL10.GL_FLAT);
gl.glEnable(GL10.GL_BLEND);
gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
gl.glPointSize(1.0f);
float ls = lerp(0.8f, 0.3f, brightness);
gl.glColor4f(ls * 1.0f, ls * 1.0f, ls * 0.8f, 1.0f);
if (mDisplayWorld) {
mClipPlaneEquation[0] = -mLightDir[0];
mClipPlaneEquation[1] = -mLightDir[1];
mClipPlaneEquation[2] = -mLightDir[2];
mClipPlaneEquation[3] = 0.0f;
// Assume we have glClipPlanef() from OpenGL ES 1.1
((GL11) gl).glClipPlanef(GL11.GL_CLIP_PLANE0,
mClipPlaneEquation, 0);
gl.glEnable(GL11.GL_CLIP_PLANE0);
}
mLights.draw(gl);
if (mDisplayWorld) {
gl.glDisable(GL11.GL_CLIP_PLANE0);
}
mNumTriangles += mLights.getNumTriangles()*2;
}
/**
* Draws the atmosphere.
*/
private void drawAtmosphere(GL10 gl) {
gl.glDisable(GL10.GL_LIGHTING);
gl.glDisable(GL10.GL_CULL_FACE);
gl.glDisable(GL10.GL_DITHER);
gl.glDisable(GL10.GL_DEPTH_TEST);
gl.glShadeModel(mSmoothShading ? GL10.GL_SMOOTH : GL10.GL_FLAT);
// Draw the atmospheric layer
float tx = mGLView.getTranslateX();
float ty = mGLView.getTranslateY();
float tz = mGLView.getTranslateZ();
gl.glMatrixMode(GL10.GL_MODELVIEW);
gl.glLoadIdentity();
gl.glTranslatef(tx, ty, tz);
// Blend in the atmosphere a bit
gl.glEnable(GL10.GL_BLEND);
gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA);
ATMOSPHERE.draw(gl);
mNumTriangles += ATMOSPHERE.getNumTriangles();
}
/**
* Draws the world in a 2D map view.
*/
private void drawWorldFlat(GL10 gl) {
gl.glDisable(GL10.GL_BLEND);
gl.glEnable(GL10.GL_DITHER);
gl.glShadeModel(mSmoothShading ? GL10.GL_SMOOTH : GL10.GL_FLAT);
gl.glTranslatef(mWrapX - 2, 0.0f, 0.0f);
worldFlat.draw(gl);
gl.glTranslatef(2.0f, 0.0f, 0.0f);
worldFlat.draw(gl);
mNumTriangles += worldFlat.getNumTriangles() * 2;
mWrapX += mWrapVelocity * mWrapVelocityFactor;
while (mWrapX < 0.0f) {
mWrapX += 2.0f;
}
while (mWrapX > 2.0f) {
mWrapX -= 2.0f;
}
}
/**
* Draws the world in a 2D round view.
*/
private void drawWorldRound(GL10 gl) {
gl.glDisable(GL10.GL_BLEND);
gl.glEnable(GL10.GL_DITHER);
gl.glShadeModel(mSmoothShading ? GL10.GL_SMOOTH : GL10.GL_FLAT);
mWorld.draw(gl);
mNumTriangles += mWorld.getNumTriangles();
}
/**
* Draws the clock.
*
* @param canvas the Canvas to draw to
* @param now the current time
* @param w the width of the screen
* @param h the height of the screen
* @param lerp controls the animation, between 0.0 and 1.0
*/
private void drawClock(Canvas canvas,
long now,
int w, int h,
float lerp) {
float clockAlpha = lerp(0.0f, 0.8f, lerp);
mClockShowing = clockAlpha > 0.0f;
if (clockAlpha > 0.0f) {
City city = mCities.get(mCityIndex);
mClock.setCity(city);
mClock.setTime(now);
float cx = w / 2.0f;
float cy = h / 2.0f;
float smallRadius = 18.0f;
float bigRadius = 0.75f * 0.5f * Math.min(w, h);
float radius = lerp(smallRadius, bigRadius, lerp);
// Only display left/right arrows if we are in a name search
boolean scrollingByName =
(mCityName.length() > 0) && (mCities.size() > 1);
mClock.drawClock(canvas, cx, cy, radius,
clockAlpha,
1.0f,
lerp == 1.0f, lerp == 1.0f,
!atEndOfTimeZone(-1),
!atEndOfTimeZone(1),
scrollingByName,
mCityName.length());
}
}
/**
* Draws the 2D layer.
*/
@Override protected void onDraw(Canvas canvas) {
long now = System.currentTimeMillis();
if (startTime != -1) {
startTime = -1;
}
int w = getWidth();
int h = getHeight();
// Interpolator for clock size, clock alpha, night lights intensity
float lerp = Math.min((now - mClockFadeTime)/1000.0f, 1.0f);
if (!mDisplayClock) {
// Clock is receding
lerp = 1.0f - lerp;
}
lerp = mClockSizeInterpolator.getInterpolation(lerp);
// we don't need to make sure OpenGL rendering is done because
// we're drawing in to a different surface
drawClock(canvas, now, w, h, lerp);
mGLView.showMessages(canvas);
mGLView.showStatistics(canvas, w);
}
/**
* Draws the 3D layer.
*/
protected void drawOpenGLScene() {
long now = System.currentTimeMillis();
mNumTriangles = 0;
EGL10 egl = (EGL10)EGLContext.getEGL();
GL10 gl = (GL10)mEGLContext.getGL();
if (!mInitialized) {
init(gl);
}
int w = getWidth();
int h = getHeight();
gl.glViewport(0, 0, w, h);
gl.glEnable(GL10.GL_LIGHTING);
gl.glEnable(GL10.GL_LIGHT0);
gl.glEnable(GL10.GL_CULL_FACE);
gl.glFrontFace(GL10.GL_CCW);
float ratio = (float) w / h;
mGLView.setAspectRatio(ratio);
mGLView.setTextureParameters(gl);
if (PERFORM_DEPTH_TEST) {
gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT);
} else {
gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
}
if (mDisplayWorldFlat) {
gl.glMatrixMode(GL10.GL_PROJECTION);
gl.glLoadIdentity();
gl.glFrustumf(-1.0f, 1.0f, -1.0f / ratio, 1.0f / ratio, 1.0f, 2.0f);
gl.glMatrixMode(GL10.GL_MODELVIEW);
gl.glLoadIdentity();
gl.glTranslatef(0.0f, 0.0f, -1.0f);
} else {
mGLView.setProjection(gl);
mGLView.setView(gl);
}
if (!mDisplayWorldFlat) {
if (mFlyToCity) {
float lerp = (now - mCityFlyStartTime)/mCityFlightTime;
if (lerp >= 1.0f) {
mFlyToCity = false;
}
lerp = Math.min(lerp, 1.0f);
lerp = mFlyToCityInterpolator.getInterpolation(lerp);
mRotAngle = lerp(mRotAngleStart, mRotAngleDest, lerp);
mTiltAngle = lerp(mTiltAngleStart, mTiltAngleDest, lerp);
}
// Rotate the viewpoint around the earth
gl.glMatrixMode(GL10.GL_MODELVIEW);
gl.glRotatef(mTiltAngle, 1, 0, 0);
gl.glRotatef(mRotAngle, 0, 1, 0);
// Increment the rotation angle
mRotAngle += mRotVelocity;
if (mRotAngle < 0.0f) {
mRotAngle += 360.0f;
}
if (mRotAngle > 360.0f) {
mRotAngle -= 360.0f;
}
}
// Draw the world with lighting
gl.glLightfv(GL10.GL_LIGHT0, GL10.GL_POSITION, mLightDir, 0);
mGLView.setLights(gl, GL10.GL_LIGHT0);
if (mDisplayWorldFlat) {
drawWorldFlat(gl);
} else if (mDisplayWorld) {
drawWorldRound(gl);
}
if (mDisplayLights && !mDisplayWorldFlat) {
// Interpolator for clock size, clock alpha, night lights intensity
float lerp = Math.min((now - mClockFadeTime)/1000.0f, 1.0f);
if (!mDisplayClock) {
// Clock is receding
lerp = 1.0f - lerp;
}
lerp = mClockSizeInterpolator.getInterpolation(lerp);
drawCityLights(gl, lerp);
}
if (mDisplayAtmosphere && !mDisplayWorldFlat) {
drawAtmosphere(gl);
}
mGLView.setNumTriangles(mNumTriangles);
egl.eglSwapBuffers(mEGLDisplay, mEGLSurface);
if (egl.eglGetError() == EGL11.EGL_CONTEXT_LOST) {
// we lost the gpu, quit immediately
Context c = getContext();
if (c instanceof Activity) {
((Activity)c).finish();
}
}
}
private static final int INVALIDATE = 1;
private static final int ONE_MINUTE = 60000;
/**
* Controls the animation using the message queue. Every time we receive
* an INVALIDATE message, we redraw and place another message in the queue.
*/
private final Handler mHandler = new Handler() {
private long mLastSunPositionTime = 0;
@Override public void handleMessage(Message msg) {
if (msg.what == INVALIDATE) {
// Use the message's time, it's good enough and
// allows us to avoid a system call.
if ((msg.getWhen() - mLastSunPositionTime) >= ONE_MINUTE) {
// Recompute the sun's position once per minute
// Place the light at the Sun's direction
computeSunDirection();
mLastSunPositionTime = msg.getWhen();
}
// Draw the GL scene
drawOpenGLScene();
// Send an update for the 2D overlay if needed
if (mInitialized &&
(mClockShowing || mGLView.hasMessages())) {
invalidate();
}
// Just send another message immediately. This works because
// drawOpenGLScene() does the timing for us -- it will
// block until the last frame has been processed.
// The invalidate message we're posting here will be
// interleaved properly with motion/key events which
// guarantee a prompt reaction to the user input.
sendEmptyMessage(INVALIDATE);
}
}
};
}
/**
* The main activity class for GlobalTime.
*/
public class GlobalTime extends Activity {
GTView gtView = null;
private void setGTView() {
if (gtView == null) {
gtView = new GTView(this);
setContentView(gtView);
}
}
@Override protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setGTView();
}
@Override protected void onResume() {
super.onResume();
setGTView();
Looper.myQueue().addIdleHandler(new Idler());
}
@Override protected void onPause() {
super.onPause();
gtView.stopAnimating();
}
@Override protected void onStop() {
super.onStop();
gtView.stopAnimating();
gtView.destroy();
gtView = null;
}
// Allow the activity to go idle before its animation starts
class Idler implements MessageQueue.IdleHandler {
public Idler() {
super();
}
public final boolean queueIdle() {
if (gtView != null) {
gtView.startAnimating();
}
return false;
}
}
}
| Java |
/*
* Copyright (C) 2006-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.android.globaltime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
import javax.microedition.khronos.opengles.GL10;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.view.KeyEvent;
class Message {
private String mText;
private long mExpirationTime;
public Message(String text, long expirationTime) {
this.mText = text;
this.mExpirationTime = expirationTime;
}
public String getText() {
return mText;
}
public long getExpirationTime() {
return mExpirationTime;
}
}
/**
* A helper class to simplify writing an Activity that renders using
* OpenGL ES.
*
* <p> A GLView object stores common elements of GL state and allows
* them to be modified interactively. This is particularly useful for
* determining the proper settings of parameters such as the view
* frustum and light intensities during application development.
*
* <p> A GLView is not an actual View; instead, it is meant to be
* called from within a View to perform event processing on behalf of the
* actual View.
*
* <p> By passing key events to the GLView object from the View,
* the application can automatically allow certain parameters to
* be user-controlled from the keyboard. Key events may be passed as
* shown below:
*
* <pre>
* GLView mGlView = new GLView();
*
* public boolean onKeyDown(int keyCode, KeyEvent event) {
* // Hand the key to the GLView object first
* if (mGlView.processKey(keyCode)) {
* return;
* }
*
* switch (keyCode) {
* case KeyEvent.KEY_CODE_X:
* // perform app processing
* break;
*
* default:
* super.onKeyDown(keyCode, event);
* break;
* }
* }
* </pre>
*
* <p> During drawing of a frame, the GLView object should be given the
* opportunity to manage GL parameters as shown below:
*
* OpenGLContext mGLContext; // initialization not shown
* int mNumTrianglesDrawn = 0;
*
* protected void onDraw(Canvas canvas) {
* int w = getWidth();
* int h = getHeight();
*
* float ratio = (float) w / h;
* mGLView.setAspectRatio(ratio);
*
* GL10 gl = (GL10) mGLContext.getGL();
* mGLContext.waitNative(canvas, this);
*
* // Enable a light for the GLView to manipulate
* gl.glEnable(GL10.GL_LIGHTING);
* gl.glEnable(GL10.GL_LIGHT0);
*
* // Allow the GLView to set GL parameters
* mGLView.setTextureParameters(gl);
* mGLView.setProjection(gl);
* mGLView.setView(gl);
* mGLView.setLights(gl, GL10.GL_LIGHT0);
*
* // Draw some stuff (not shown)
* mNumTrianglesDrawn += <num triangles just drawn>;
*
* // Wait for GL drawing to complete
* mGLContext.waitGL();
*
* // Inform the GLView of what was drawn, and ask it to display statistics
* mGLView.setNumTriangles(mNumTrianglesDrawn);
* mGLView.showMessages(canvas);
* mGLView.showStatistics(canvas, w);
* }
* </pre>
*
* <p> At the end of each frame, following the call to
* GLContext.waitGL, the showStatistics and showMessages methods
* will cause additional information to be displayed.
*
* <p> To enter the interactive command mode, the 'tab' key must be
* pressed twice in succession. A subsequent press of the 'tab' key
* exits the interactive command mode. Entering a multi-letter code
* sets the parameter to be modified. The 'newline' key erases the
* current code, and the 'del' key deletes the last letter of
* the code. The parameter value may be modified by pressing the
* keypad left or up to decrement the value and right or down to
* increment the value. The current value will be displayed as an
* overlay above the GL rendered content.
*
* <p> The supported keyboard commands are as follows:
*
* <ul>
* <li> h - display a list of commands
* <li> fn - near frustum
* <li> ff - far frustum
* <li> tx - translate x
* <li> ty - translate y
* <li> tz - translate z
* <li> z - zoom (frustum size)
* <li> la - ambient light (all RGB channels)
* <li> lar - ambient light red channel
* <li> lag - ambient light green channel
* <li> lab - ambient light blue channel
* <li> ld - diffuse light (all RGB channels)
* <li> ldr - diffuse light red channel
* <li> ldg - diffuse light green channel
* <li> ldb - diffuse light blue channel
* <li> ls - specular light (all RGB channels)
* <li> lsr - specular light red channel
* <li> lsg - specular light green channel
* <li> lsb - specular light blue channel
* <li> lma - light model ambient (all RGB channels)
* <li> lmar - light model ambient light red channel
* <li> lmag - light model ambient green channel
* <li> lmab - light model ambient blue channel
* <li> tmin - texture min filter
* <li> tmag - texture mag filter
* <li> tper - texture perspective correction
* </ul>
*
* {@hide}
*/
public class GLView {
private static final int DEFAULT_DURATION_MILLIS = 1000;
private static final int STATE_KEY = KeyEvent.KEYCODE_TAB;
private static final int HAVE_NONE = 0;
private static final int HAVE_ONE = 1;
private static final int HAVE_TWO = 2;
private static final float MESSAGE_Y_SPACING = 12.0f;
private int mState = HAVE_NONE;
private static final int NEAR_FRUSTUM = 0;
private static final int FAR_FRUSTUM = 1;
private static final int TRANSLATE_X = 2;
private static final int TRANSLATE_Y = 3;
private static final int TRANSLATE_Z = 4;
private static final int ZOOM_EXPONENT = 5;
private static final int AMBIENT_INTENSITY = 6;
private static final int AMBIENT_RED = 7;
private static final int AMBIENT_GREEN = 8;
private static final int AMBIENT_BLUE = 9;
private static final int DIFFUSE_INTENSITY = 10;
private static final int DIFFUSE_RED = 11;
private static final int DIFFUSE_GREEN = 12;
private static final int DIFFUSE_BLUE = 13;
private static final int SPECULAR_INTENSITY = 14;
private static final int SPECULAR_RED = 15;
private static final int SPECULAR_GREEN = 16;
private static final int SPECULAR_BLUE = 17;
private static final int LIGHT_MODEL_AMBIENT_INTENSITY = 18;
private static final int LIGHT_MODEL_AMBIENT_RED = 19;
private static final int LIGHT_MODEL_AMBIENT_GREEN = 20;
private static final int LIGHT_MODEL_AMBIENT_BLUE = 21;
private static final int TEXTURE_MIN_FILTER = 22;
private static final int TEXTURE_MAG_FILTER = 23;
private static final int TEXTURE_PERSPECTIVE_CORRECTION = 24;
private static final String[] commands = {
"fn",
"ff",
"tx",
"ty",
"tz",
"z",
"la", "lar", "lag", "lab",
"ld", "ldr", "ldg", "ldb",
"ls", "lsr", "lsg", "lsb",
"lma", "lmar", "lmag", "lmab",
"tmin", "tmag", "tper"
};
private static final String[] labels = {
"Near Frustum",
"Far Frustum",
"Translate X",
"Translate Y",
"Translate Z",
"Zoom",
"Ambient Intensity",
"Ambient Red",
"Ambient Green",
"Ambient Blue",
"Diffuse Intensity",
"Diffuse Red",
"Diffuse Green",
"Diffuse Blue",
"Specular Intenstity",
"Specular Red",
"Specular Green",
"Specular Blue",
"Light Model Ambient Intensity",
"Light Model Ambient Red",
"Light Model Ambient Green",
"Light Model Ambient Blue",
"Texture Min Filter",
"Texture Mag Filter",
"Texture Perspective Correction",
};
private static final float[] defaults = {
5.0f, 100.0f,
0.0f, 0.0f, -50.0f,
0,
0.125f, 1.0f, 1.0f, 1.0f,
0.125f, 1.0f, 1.0f, 1.0f,
0.125f, 1.0f, 1.0f, 1.0f,
0.125f, 1.0f, 1.0f, 1.0f,
GL10.GL_NEAREST, GL10.GL_NEAREST,
GL10.GL_FASTEST
};
private static final float[] increments = {
0.01f, 0.5f,
0.125f, 0.125f, 0.125f,
1.0f,
0.03125f, 0.1f, 0.1f, 0.1f,
0.03125f, 0.1f, 0.1f, 0.1f,
0.03125f, 0.1f, 0.1f, 0.1f,
0.03125f, 0.1f, 0.1f, 0.1f,
0, 0, 0
};
private float[] params = new float[commands.length];
private static final float mZoomScale = 0.109f;
private static final float mZoomBase = 1.01f;
private int mParam = -1;
private float mIncr = 0;
private Paint mPaint = new Paint();
private float mAspectRatio = 1.0f;
private float mZoom;
// private boolean mPerspectiveCorrection = false;
// private int mTextureMinFilter = GL10.GL_NEAREST;
// private int mTextureMagFilter = GL10.GL_NEAREST;
// Counters for FPS calculation
private boolean mDisplayFPS = false;
private boolean mDisplayCounts = false;
private int mFramesFPS = 10;
private long[] mTimes = new long[mFramesFPS];
private int mTimesIdx = 0;
private Map<String,Message> mMessages = new HashMap<String,Message>();
/**
* Constructs a new GLView.
*/
public GLView() {
mPaint.setColor(0xffffffff);
reset();
}
/**
* Sets the aspect ratio (width/height) of the screen.
*
* @param aspectRatio the screen width divided by the screen height
*/
public void setAspectRatio(float aspectRatio) {
this.mAspectRatio = aspectRatio;
}
/**
* Sets the overall ambient light intensity. This intensity will
* be used to modify the ambient light value for each of the red,
* green, and blue channels passed to glLightfv(...GL_AMBIENT...).
* The default value is 0.125f.
*
* @param intensity a floating-point value controlling the overall
* ambient light intensity.
*/
public void setAmbientIntensity(float intensity) {
params[AMBIENT_INTENSITY] = intensity;
}
/**
* Sets the light model ambient intensity. This intensity will be
* used to modify the ambient light value for each of the red,
* green, and blue channels passed to
* glLightModelfv(GL_LIGHT_MODEL_AMBIENT...). The default value
* is 0.125f.
*
* @param intensity a floating-point value controlling the overall
* light model ambient intensity.
*/
public void setLightModelAmbientIntensity(float intensity) {
params[LIGHT_MODEL_AMBIENT_INTENSITY] = intensity;
}
/**
* Sets the ambient color for the red, green, and blue channels
* that will be multiplied by the value of setAmbientIntensity and
* passed to glLightfv(...GL_AMBIENT...). The default values are
* {1, 1, 1}.
*
* @param ambient an arry of three floats containing ambient
* red, green, and blue intensity values.
*/
public void setAmbientColor(float[] ambient) {
params[AMBIENT_RED] = ambient[0];
params[AMBIENT_GREEN] = ambient[1];
params[AMBIENT_BLUE] = ambient[2];
}
/**
* Sets the overall diffuse light intensity. This intensity will
* be used to modify the diffuse light value for each of the red,
* green, and blue channels passed to glLightfv(...GL_DIFFUSE...).
* The default value is 0.125f.
*
* @param intensity a floating-point value controlling the overall
* ambient light intensity.
*/
public void setDiffuseIntensity(float intensity) {
params[DIFFUSE_INTENSITY] = intensity;
}
/**
* Sets the diffuse color for the red, green, and blue channels
* that will be multiplied by the value of setDiffuseIntensity and
* passed to glLightfv(...GL_DIFFUSE...). The default values are
* {1, 1, 1}.
*
* @param diffuse an array of three floats containing diffuse
* red, green, and blue intensity values.
*/
public void setDiffuseColor(float[] diffuse) {
params[DIFFUSE_RED] = diffuse[0];
params[DIFFUSE_GREEN] = diffuse[1];
params[DIFFUSE_BLUE] = diffuse[2];
}
/**
* Sets the overall specular light intensity. This intensity will
* be used to modify the diffuse light value for each of the red,
* green, and blue channels passed to glLightfv(...GL_SPECULAR...).
* The default value is 0.125f.
*
* @param intensity a floating-point value controlling the overall
* ambient light intensity.
*/
public void setSpecularIntensity(float intensity) {
params[SPECULAR_INTENSITY] = intensity;
}
/**
* Sets the specular color for the red, green, and blue channels
* that will be multiplied by the value of setSpecularIntensity and
* passed to glLightfv(...GL_SPECULAR...). The default values are
* {1, 1, 1}.
*
* @param specular an array of three floats containing specular
* red, green, and blue intensity values.
*/
public void setSpecularColor(float[] specular) {
params[SPECULAR_RED] = specular[0];
params[SPECULAR_GREEN] = specular[1];
params[SPECULAR_BLUE] = specular[2];
}
/**
* Returns the current X translation of the modelview
* transformation as passed to glTranslatef. The default value is
* 0.0f.
*
* @return the X modelview translation as a float.
*/
public float getTranslateX() {
return params[TRANSLATE_X];
}
/**
* Returns the current Y translation of the modelview
* transformation as passed to glTranslatef. The default value is
* 0.0f.
*
* @return the Y modelview translation as a float.
*/
public float getTranslateY() {
return params[TRANSLATE_Y];
}
/**
* Returns the current Z translation of the modelview
* transformation as passed to glTranslatef. The default value is
* -50.0f.
*
* @return the Z modelview translation as a float.
*/
public float getTranslateZ() {
return params[TRANSLATE_Z];
}
/**
* Sets the position of the near frustum clipping plane as passed
* to glFrustumf. The default value is 5.0f;
*
* @param nearFrustum the near frustum clipping plane distance as
* a float.
*/
public void setNearFrustum(float nearFrustum) {
params[NEAR_FRUSTUM] = nearFrustum;
}
/**
* Sets the position of the far frustum clipping plane as passed
* to glFrustumf. The default value is 100.0f;
*
* @param farFrustum the far frustum clipping plane distance as a
* float.
*/
public void setFarFrustum(float farFrustum) {
params[FAR_FRUSTUM] = farFrustum;
}
private void computeZoom() {
mZoom = mZoomScale*(float)Math.pow(mZoomBase, -params[ZOOM_EXPONENT]);
}
/**
* Resets all parameters to their default values.
*/
public void reset() {
for (int i = 0; i < params.length; i++) {
params[i] = defaults[i];
}
computeZoom();
}
private void removeExpiredMessages() {
long now = System.currentTimeMillis();
List<String> toBeRemoved = new ArrayList<String>();
Iterator<String> keyIter = mMessages.keySet().iterator();
while (keyIter.hasNext()) {
String key = keyIter.next();
Message msg = mMessages.get(key);
if (msg.getExpirationTime() < now) {
toBeRemoved.add(key);
}
}
Iterator<String> tbrIter = toBeRemoved.iterator();
while (tbrIter.hasNext()) {
String key = tbrIter.next();
mMessages.remove(key);
}
}
/**
* Displays the message overlay on the given Canvas. The
* GLContext.waitGL method should be called prior to calling this
* method. The interactive command display is drawn by this
* method.
*
* @param canvas the Canvas on which messages are to appear.
*/
public void showMessages(Canvas canvas) {
removeExpiredMessages();
float y = 10.0f;
List<String> l = new ArrayList<String>();
l.addAll(mMessages.keySet());
Collections.sort(l);
Iterator<String> iter = l.iterator();
while (iter.hasNext()) {
String key = iter.next();
String text = mMessages.get(key).getText();
canvas.drawText(text, 10.0f, y, mPaint);
y += MESSAGE_Y_SPACING;
}
}
private int mTriangles;
/**
* Sets the number of triangles drawn in the previous frame for
* display by the showStatistics method. The number of triangles
* is not computed by GLView but must be supplied by the
* calling Activity.
*
* @param triangles an Activity-supplied estimate of the number of
* triangles drawn in the previous frame.
*/
public void setNumTriangles(int triangles) {
this.mTriangles = triangles;
}
/**
* Displays statistics on frames and triangles per second. The
* GLContext.waitGL method should be called prior to calling this
* method.
*
* @param canvas the Canvas on which statistics are to appear.
* @param width the width of the Canvas.
*/
public void showStatistics(Canvas canvas, int width) {
long endTime = mTimes[mTimesIdx] = System.currentTimeMillis();
mTimesIdx = (mTimesIdx + 1) % mFramesFPS;
float th = mPaint.getTextSize();
if (mDisplayFPS) {
// Use end time from mFramesFPS frames ago
long startTime = mTimes[mTimesIdx];
String fps = "" + (1000.0f*mFramesFPS/(endTime - startTime));
// Normalize fps to XX.XX format
if (fps.indexOf(".") == 1) {
fps = " " + fps;
}
int len = fps.length();
if (len == 2) {
fps += ".00";
} else if (len == 4) {
fps += "0";
} else if (len > 5) {
fps = fps.substring(0, 5);
}
canvas.drawText(fps + " fps", width - 60.0f, 10.0f, mPaint);
}
if (mDisplayCounts) {
canvas.drawText(mTriangles + " triangles",
width - 100.0f, 10.0f + th + 5, mPaint);
}
}
private void addMessage(String key, String text, int durationMillis) {
long expirationTime = System.currentTimeMillis() + durationMillis;
mMessages.put(key, new Message(text, expirationTime));
}
private void addMessage(String key, String text) {
addMessage(key, text, DEFAULT_DURATION_MILLIS);
}
private void addMessage(String text) {
addMessage(text, text, DEFAULT_DURATION_MILLIS);
}
private void clearMessages() {
mMessages.clear();
}
String command = "";
private void toggleFilter() {
if (params[mParam] == GL10.GL_NEAREST) {
params[mParam] = GL10.GL_LINEAR;
} else {
params[mParam] = GL10.GL_NEAREST;
}
addMessage(commands[mParam],
"Texture " +
(mParam == TEXTURE_MIN_FILTER ? "min" : "mag") +
" filter = " +
(params[mParam] == GL10.GL_NEAREST ?
"nearest" : "linear"));
}
private void togglePerspectiveCorrection() {
if (params[mParam] == GL10.GL_NICEST) {
params[mParam] = GL10.GL_FASTEST;
} else {
params[mParam] = GL10.GL_NICEST;
}
addMessage(commands[mParam],
"Texture perspective correction = " +
(params[mParam] == GL10.GL_FASTEST ?
"fastest" : "nicest"));
}
private String valueString() {
if (mParam == TEXTURE_MIN_FILTER ||
mParam == TEXTURE_MAG_FILTER) {
if (params[mParam] == GL10.GL_NEAREST) {
return "nearest";
}
if (params[mParam] == GL10.GL_LINEAR) {
return "linear";
}
}
if (mParam == TEXTURE_PERSPECTIVE_CORRECTION) {
if (params[mParam] == GL10.GL_FASTEST) {
return "fastest";
}
if (params[mParam] == GL10.GL_NICEST) {
return "nicest";
}
}
return "" + params[mParam];
}
/**
*
* @return true if the view
*/
public boolean hasMessages() {
return mState == HAVE_TWO || mDisplayFPS || mDisplayCounts;
}
/**
* Process a key stroke. The calling Activity should pass all
* keys from its onKeyDown method to this method. If the key is
* part of a GLView command, true is returned and the calling
* Activity should ignore the key event. Otherwise, false is
* returned and the calling Activity may process the key event
* normally.
*
* @param keyCode the key code as passed to Activity.onKeyDown.
*
* @return true if the key is part of a GLView command sequence,
* false otherwise.
*/
public boolean processKey(int keyCode) {
// Pressing the state key twice enters the UI
// Pressing it again exits the UI
if ((keyCode == STATE_KEY) ||
(keyCode == KeyEvent.KEYCODE_SLASH) ||
(keyCode == KeyEvent.KEYCODE_PERIOD))
{
mState = (mState + 1) % 3;
if (mState == HAVE_NONE) {
clearMessages();
}
if (mState == HAVE_TWO) {
clearMessages();
addMessage("aaaa", "GL", Integer.MAX_VALUE);
addMessage("aaab", "", Integer.MAX_VALUE);
command = "";
}
return true;
} else {
if (mState == HAVE_ONE) {
mState = HAVE_NONE;
return false;
}
}
// If we're not in the UI, exit without handling the key
if (mState != HAVE_TWO) {
return false;
}
if (keyCode == KeyEvent.KEYCODE_ENTER) {
command = "";
} else if (keyCode == KeyEvent.KEYCODE_DEL) {
if (command.length() > 0) {
command = command.substring(0, command.length() - 1);
}
} else if (keyCode >= KeyEvent.KEYCODE_A &&
keyCode <= KeyEvent.KEYCODE_Z) {
command += "" + (char)(keyCode - KeyEvent.KEYCODE_A + 'a');
}
addMessage("aaaa", "GL " + command, Integer.MAX_VALUE);
if (command.equals("h")) {
addMessage("aaaa", "GL", Integer.MAX_VALUE);
addMessage("h - help");
addMessage("fn/ff - frustum near/far clip Z");
addMessage("la/lar/lag/lab - abmient intensity/r/g/b");
addMessage("ld/ldr/ldg/ldb - diffuse intensity/r/g/b");
addMessage("ls/lsr/lsg/lsb - specular intensity/r/g/b");
addMessage("s - toggle statistics display");
addMessage("tmin/tmag - texture min/mag filter");
addMessage("tpersp - texture perspective correction");
addMessage("tx/ty/tz - view translate x/y/z");
addMessage("z - zoom");
command = "";
return true;
} else if (command.equals("s")) {
mDisplayCounts = !mDisplayCounts;
mDisplayFPS = !mDisplayFPS;
command = "";
return true;
}
mParam = -1;
for (int i = 0; i < commands.length; i++) {
if (command.equals(commands[i])) {
mParam = i;
mIncr = increments[i];
}
}
if (mParam == -1) {
return true;
}
boolean addMessage = true;
// Increment or decrement
if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT ||
keyCode == KeyEvent.KEYCODE_DPAD_DOWN) {
if (mParam == ZOOM_EXPONENT) {
params[mParam] += mIncr;
computeZoom();
} else if ((mParam == TEXTURE_MIN_FILTER) ||
(mParam == TEXTURE_MAG_FILTER)) {
toggleFilter();
} else if (mParam == TEXTURE_PERSPECTIVE_CORRECTION) {
togglePerspectiveCorrection();
} else {
params[mParam] += mIncr;
}
} else if (keyCode == KeyEvent.KEYCODE_DPAD_UP ||
keyCode == KeyEvent.KEYCODE_DPAD_LEFT) {
if (mParam == ZOOM_EXPONENT) {
params[mParam] -= mIncr;
computeZoom();
} else if ((mParam == TEXTURE_MIN_FILTER) ||
(mParam == TEXTURE_MAG_FILTER)) {
toggleFilter();
} else if (mParam == TEXTURE_PERSPECTIVE_CORRECTION) {
togglePerspectiveCorrection();
} else {
params[mParam] -= mIncr;
}
}
if (addMessage) {
addMessage(commands[mParam],
labels[mParam] + ": " + valueString());
}
return true;
}
/**
* Zoom in by a given number of steps. A negative value of steps
* zooms out. Each step zooms in by 1%.
*
* @param steps the number of steps to zoom by.
*/
public void zoom(int steps) {
params[ZOOM_EXPONENT] += steps;
computeZoom();
}
/**
* Set the projection matrix using glFrustumf. The left and right
* clipping planes are set at -+(aspectRatio*zoom), the bottom and
* top clipping planes are set at -+zoom, and the near and far
* clipping planes are set to the values set by setNearFrustum and
* setFarFrustum or interactively.
*
* <p> GL side effects:
* <ul>
* <li>overwrites the matrix mode</li>
* <li>overwrites the projection matrix</li>
* </ul>
*
* @param gl a GL10 instance whose projection matrix is to be modified.
*/
public void setProjection(GL10 gl) {
gl.glMatrixMode(GL10.GL_PROJECTION);
gl.glLoadIdentity();
if (mAspectRatio >= 1.0f) {
gl.glFrustumf(-mAspectRatio*mZoom, mAspectRatio*mZoom,
-mZoom, mZoom,
params[NEAR_FRUSTUM], params[FAR_FRUSTUM]);
} else {
gl.glFrustumf(-mZoom, mZoom,
-mZoom / mAspectRatio, mZoom / mAspectRatio,
params[NEAR_FRUSTUM], params[FAR_FRUSTUM]);
}
}
/**
* Set the modelview matrix using glLoadIdentity and glTranslatef.
* The translation values are set interactively.
*
* <p> GL side effects:
* <ul>
* <li>overwrites the matrix mode</li>
* <li>overwrites the modelview matrix</li>
* </ul>
*
* @param gl a GL10 instance whose modelview matrix is to be modified.
*/
public void setView(GL10 gl) {
gl.glMatrixMode(GL10.GL_MODELVIEW);
gl.glLoadIdentity();
// Move the viewpoint backwards
gl.glTranslatef(params[TRANSLATE_X],
params[TRANSLATE_Y],
params[TRANSLATE_Z]);
}
/**
* Sets texture parameters.
*
* <p> GL side effects:
* <ul>
* <li>sets the GL_PERSPECTIVE_CORRECTION_HINT</li>
* <li>sets the GL_TEXTURE_MIN_FILTER texture parameter</li>
* <li>sets the GL_TEXTURE_MAX_FILTER texture parameter</li>
* </ul>
*
* @param gl a GL10 instance whose texture parameters are to be modified.
*/
public void setTextureParameters(GL10 gl) {
gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT,
(int)params[TEXTURE_PERSPECTIVE_CORRECTION]);
gl.glTexParameterf(GL10.GL_TEXTURE_2D,
GL10.GL_TEXTURE_MIN_FILTER,
params[TEXTURE_MIN_FILTER]);
gl.glTexParameterf(GL10.GL_TEXTURE_2D,
GL10.GL_TEXTURE_MAG_FILTER,
params[TEXTURE_MAG_FILTER]);
}
/**
* Sets the lighting parameters for the given light.
*
* <p> GL side effects:
* <ul>
* <li>sets the GL_LIGHT_MODEL_AMBIENT intensities
* <li>sets the GL_AMBIENT intensities for the given light</li>
* <li>sets the GL_DIFFUSE intensities for the given light</li>
* <li>sets the GL_SPECULAR intensities for the given light</li>
* </ul>
*
* @param gl a GL10 instance whose texture parameters are to be modified.
*/
public void setLights(GL10 gl, int lightNum) {
float[] light = new float[4];
light[3] = 1.0f;
float lmi = params[LIGHT_MODEL_AMBIENT_INTENSITY];
light[0] = params[LIGHT_MODEL_AMBIENT_RED]*lmi;
light[1] = params[LIGHT_MODEL_AMBIENT_GREEN]*lmi;
light[2] = params[LIGHT_MODEL_AMBIENT_BLUE]*lmi;
gl.glLightModelfv(GL10.GL_LIGHT_MODEL_AMBIENT, light, 0);
float ai = params[AMBIENT_INTENSITY];
light[0] = params[AMBIENT_RED]*ai;
light[1] = params[AMBIENT_GREEN]*ai;
light[2] = params[AMBIENT_BLUE]*ai;
gl.glLightfv(lightNum, GL10.GL_AMBIENT, light, 0);
float di = params[DIFFUSE_INTENSITY];
light[0] = params[DIFFUSE_RED]*di;
light[1] = params[DIFFUSE_GREEN]*di;
light[2] = params[DIFFUSE_BLUE]*di;
gl.glLightfv(lightNum, GL10.GL_DIFFUSE, light, 0);
float si = params[SPECULAR_INTENSITY];
light[0] = params[SPECULAR_RED]*si;
light[1] = params[SPECULAR_GREEN]*si;
light[2] = params[SPECULAR_BLUE]*si;
gl.glLightfv(lightNum, GL10.GL_SPECULAR, light, 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.photostream;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
/**
* This broadcast receiver is awoken after boot and registers the service that
* checks for new photos from all the known contacts.
*/
public class BootReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
if (Intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())) {
CheckUpdateService.schedule(context);
}
}
}
| 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.photostream;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpVersion;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.params.HttpParams;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.OutputStream;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.net.URL;
import android.util.Xml;
import android.view.InflateException;
import android.net.Uri;
import android.os.Parcelable;
import android.os.Parcel;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
/**
* Utility class to interact with the Flickr REST-based web services.
*
* This class uses a default Flickr API key that you should replace with your own if
* you reuse this code to redistribute it with your application(s).
*
* This class is used as a singleton and cannot be instanciated. Instead, you must use
* {@link #get()} to retrieve the unique instance of this class.
*/
class Flickr {
static final String LOG_TAG = "Photostream";
// IMPORTANT: Replace this Flickr API key with your own
private static final String API_KEY = "730e3a4f253b30adf30177df803d38c4";
private static final String API_REST_HOST = "api.flickr.com";
private static final String API_REST_URL = "/services/rest/";
private static final String API_FEED_URL = "/services/feeds/photos_public.gne";
private static final String API_PEOPLE_FIND_BY_USERNAME = "flickr.people.findByUsername";
private static final String API_PEOPLE_GET_INFO = "flickr.people.getInfo";
private static final String API_PEOPLE_GET_PUBLIC_PHOTOS = "flickr.people.getPublicPhotos";
private static final String API_PEOPLE_GET_LOCATION = "flickr.photos.geo.getLocation";
private static final String PARAM_API_KEY = "api_key";
private static final String PARAM_METHOD= "method";
private static final String PARAM_USERNAME = "username";
private static final String PARAM_USERID = "user_id";
private static final String PARAM_PER_PAGE = "per_page";
private static final String PARAM_PAGE = "page";
private static final String PARAM_EXTRAS = "extras";
private static final String PARAM_PHOTO_ID = "photo_id";
private static final String PARAM_FEED_ID = "id";
private static final String PARAM_FEED_FORMAT = "format";
private static final String VALUE_DEFAULT_EXTRAS = "date_taken";
private static final String VALUE_DEFAULT_FORMAT = "atom";
private static final String RESPONSE_TAG_RSP = "rsp";
private static final String RESPONSE_ATTR_STAT = "stat";
private static final String RESPONSE_STATUS_OK = "ok";
private static final String RESPONSE_TAG_USER = "user";
private static final String RESPONSE_ATTR_NSID = "nsid";
private static final String RESPONSE_TAG_PHOTOS = "photos";
private static final String RESPONSE_ATTR_PAGE = "page";
private static final String RESPONSE_ATTR_PAGES = "pages";
private static final String RESPONSE_TAG_PHOTO = "photo";
private static final String RESPONSE_ATTR_ID = "id";
private static final String RESPONSE_ATTR_SECRET = "secret";
private static final String RESPONSE_ATTR_SERVER = "server";
private static final String RESPONSE_ATTR_FARM = "farm";
private static final String RESPONSE_ATTR_TITLE = "title";
private static final String RESPONSE_ATTR_DATE_TAKEN = "datetaken";
private static final String RESPONSE_TAG_PERSON = "person";
private static final String RESPONSE_ATTR_ISPRO = "ispro";
private static final String RESPONSE_ATTR_ICONSERVER = "iconserver";
private static final String RESPONSE_ATTR_ICONFARM = "iconfarm";
private static final String RESPONSE_TAG_USERNAME = "username";
private static final String RESPONSE_TAG_REALNAME = "realname";
private static final String RESPONSE_TAG_LOCATION = "location";
private static final String RESPONSE_ATTR_LATITUDE = "latitude";
private static final String RESPONSE_ATTR_LONGITUDE = "longitude";
private static final String RESPONSE_TAG_PHOTOSURL = "photosurl";
private static final String RESPONSE_TAG_PROFILEURL = "profileurl";
private static final String RESPONSE_TAG_MOBILEURL = "mobileurl";
private static final String RESPONSE_TAG_FEED = "feed";
private static final String RESPONSE_TAG_UPDATED = "updated";
private static final String PHOTO_IMAGE_URL = "http://farm%s.static.flickr.com/%s/%s_%s%s.jpg";
private static final String BUDDY_ICON_URL =
"http://farm%s.static.flickr.com/%s/buddyicons/%s.jpg";
private static final String DEFAULT_BUDDY_ICON_URL =
"http://www.flickr.com/images/buddyicon.jpg";
private static final int IO_BUFFER_SIZE = 4 * 1024;
private static final boolean FLAG_DECODE_PHOTO_STREAM_WITH_SKIA = false;
private static final Flickr sInstance = new Flickr();
private HttpClient mClient;
/**
* Defines the size of the image to download from Flickr.
*
* @see com.google.android.photostream.Flickr.Photo
*/
enum PhotoSize {
/**
* Small square image (75x75 px).
*/
SMALL_SQUARE("_s", 75),
/**
* Thumbnail image (the longest side measures 100 px).
*/
THUMBNAIL("_t", 100),
/**
* Small image (the longest side measures 240 px).
*/
SMALL("_m", 240),
/**
* Medium image (the longest side measures 500 px).
*/
MEDIUM("", 500),
/**
* Large image (the longest side measures 1024 px).
*/
LARGE("_b", 1024);
private final String mSize;
private final int mLongSide;
private PhotoSize(String size, int longSide) {
mSize = size;
mLongSide = longSide;
}
/**
* Returns the size in pixels of the longest side of the image.
*
* @return THe dimension in pixels of the longest side.
*/
int longSide() {
return mLongSide;
}
/**
* Returns the name of the size, as defined by Flickr. For instance,
* the LARGE size is defined by the String "_b".
*
* @return
*/
String size() {
return mSize;
}
@Override
public String toString() {
return name() + ", longSide=" + mLongSide;
}
}
/**
* Represents the geographical location of a photo.
*/
static class Location {
private float mLatitude;
private float mLongitude;
private Location(float latitude, float longitude) {
mLatitude = latitude;
mLongitude = longitude;
}
float getLatitude() {
return mLatitude;
}
float getLongitude() {
return mLongitude;
}
}
/**
* A Flickr user, in the strictest sense, is only defined by its NSID. The NSID
* is usually obtained by {@link Flickr#findByUserName(String)
* looking up a user by its user name}.
*
* To obtain more information about a given user, refer to the UserInfo class.
*
* @see Flickr#findByUserName(String)
* @see Flickr#getUserInfo(com.google.android.photostream.Flickr.User)
* @see com.google.android.photostream.Flickr.UserInfo
*/
static class User implements Parcelable {
private final String mId;
private User(String id) {
mId = id;
}
private User(Parcel in) {
mId = in.readString();
}
/**
* Returns the Flickr NSDID of the user. The NSID is used to identify the
* user with any operation performed on Flickr.
*
* @return The user's NSID.
*/
String getId() {
return mId;
}
/**
* Creates a new instance of this class from the specified Flickr NSID.
*
* @param id The NSID of the Flickr user.
*
* @return An instance of User whose id might not be valid.
*/
static User fromId(String id) {
return new User(id);
}
@Override
public String toString() {
return "User[" + mId + "]";
}
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(mId);
}
public static final Parcelable.Creator<User> CREATOR = new Parcelable.Creator<User>() {
public User createFromParcel(Parcel in) {
return new User(in);
}
public User[] newArray(int size) {
return new User[size];
}
};
}
/**
* A set of information for a given Flickr user. The information exposed include:
* - The user's NSDID
* - The user's name
* - The user's real name
* - The user's location
* - The URL to the user's photos
* - The URL to the user's profile
* - The URL to the user's mobile web site
* - Whether the user has a pro account
*/
static class UserInfo implements Parcelable {
private String mId;
private String mUserName;
private String mRealName;
private String mLocation;
private String mPhotosUrl;
private String mProfileUrl;
private String mMobileUrl;
private boolean mIsPro;
private String mIconServer;
private String mIconFarm;
private UserInfo(String nsid) {
mId = nsid;
}
private UserInfo(Parcel in) {
mId = in.readString();
mUserName = in.readString();
mRealName = in.readString();
mLocation = in.readString();
mPhotosUrl = in.readString();
mProfileUrl = in.readString();
mMobileUrl = in.readString();
mIsPro = in.readInt() == 1;
mIconServer = in.readString();
mIconFarm = in.readString();
}
/**
* Returns the Flickr NSID that identifies this user.
*
* @return The Flickr NSID.
*/
String getId() {
return mId;
}
/**
* Returns the user's name. This is the name that the user authenticates with,
* and the name that Flickr uses in the URLs
* (for instance, http://flickr.com/photos/romainguy, where romainguy is the user
* name.)
*
* @return The user's Flickr name.
*/
String getUserName() {
return mUserName;
}
/**
* Returns the user's real name. The real name is chosen by the user when
* creating his account and might not reflect his civil name.
*
* @return The real name of the user.
*/
String getRealName() {
return mRealName;
}
/**
* Returns the user's location, if publicly exposed.
*
* @return The location of the user.
*/
String getLocation() {
return mLocation;
}
/**
* Returns the URL to the photos of the user. For instance,
* http://flickr.com/photos/romainguy.
*
* @return The URL to the photos of the user.
*/
String getPhotosUrl() {
return mPhotosUrl;
}
/**
* Returns the URL to the profile of the user. For instance,
* http://flickr.com/people/romainguy/.
*
* @return The URL to the photos of the user.
*/
String getProfileUrl() {
return mProfileUrl;
}
/**
* Returns the mobile URL of the user.
*
* @return The mobile URL of the user.
*/
String getMobileUrl() {
return mMobileUrl;
}
/**
* Indicates whether the user owns a pro account.
*
* @return true, if the user has a pro account, false otherwise.
*/
boolean isPro() {
return mIsPro;
}
/**
* Returns the URL to the user's buddy icon. The buddy icon is a 48x48
* image chosen by the user. If no icon can be found, a default image
* URL is returned.
*
* @return The URL to the user's buddy icon.
*/
String getBuddyIconUrl() {
if (mIconFarm == null || mIconServer == null || mId == null) {
return DEFAULT_BUDDY_ICON_URL;
}
return String.format(BUDDY_ICON_URL, mIconFarm, mIconServer, mId);
}
/**
* Loads the user's buddy icon as a Bitmap. The user's buddy icon is loaded
* from the URL returned by {@link #getBuddyIconUrl()}. The buddy icon is
* not cached locally.
*
* @return A 48x48 bitmap if the icon was loaded successfully or null otherwise.
*/
Bitmap loadBuddyIcon() {
Bitmap bitmap = null;
InputStream in = null;
OutputStream out = null;
try {
in = new BufferedInputStream(new URL(getBuddyIconUrl()).openStream(),
IO_BUFFER_SIZE);
if (FLAG_DECODE_PHOTO_STREAM_WITH_SKIA) {
bitmap = BitmapFactory.decodeStream(in);
} else {
final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
copy(in, out);
out.flush();
final byte[] data = dataStream.toByteArray();
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
}
} catch (IOException e) {
android.util.Log.e(Flickr.LOG_TAG, "Could not load buddy icon: " + this, e);
} finally {
closeStream(in);
closeStream(out);
}
return bitmap;
}
@Override
public String toString() {
return mRealName + " (" + mUserName + ", " + mId + ")";
}
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(mId);
dest.writeString(mUserName);
dest.writeString(mRealName);
dest.writeString(mLocation);
dest.writeString(mPhotosUrl);
dest.writeString(mProfileUrl);
dest.writeString(mMobileUrl);
dest.writeInt(mIsPro ? 1 : 0);
dest.writeString(mIconServer);
dest.writeString(mIconFarm);
}
public static final Parcelable.Creator<UserInfo> CREATOR =
new Parcelable.Creator<UserInfo>() {
public UserInfo createFromParcel(Parcel in) {
return new UserInfo(in);
}
public UserInfo[] newArray(int size) {
return new UserInfo[size];
}
};
}
/**
* A photo is represented by a title, the date at which it was taken and a URL.
* The URL depends on the desired {@link com.google.android.photostream.Flickr.PhotoSize}.
*/
static class Photo implements Parcelable {
private String mId;
private String mSecret;
private String mServer;
private String mFarm;
private String mTitle;
private String mDate;
private Photo() {
}
private Photo(Parcel in) {
mId = in.readString();
mSecret = in.readString();
mServer = in.readString();
mFarm = in.readString();
mTitle = in.readString();
mDate = in.readString();
}
/**
* Returns the title of the photo, if specified.
*
* @return The title of the photo. The returned value can be empty or null.
*/
String getTitle() {
return mTitle;
}
/**
* Returns the date at which the photo was taken, formatted in the current locale
* with the following pattern: MMMM d, yyyy.
*
* @return The title of the photo. The returned value can be empty or null.
*/
String getDate() {
return mDate;
}
/**
* Returns the URL to the photo for the specified size.
*
* @param photoSize The required size of the photo.
*
* @return A URL to the photo for the specified size.
*
* @see com.google.android.photostream.Flickr.PhotoSize
*/
String getUrl(PhotoSize photoSize) {
return String.format(PHOTO_IMAGE_URL, mFarm, mServer, mId, mSecret, photoSize.size());
}
/**
* Loads a Bitmap representing the photo for the specified size. The Bitmap is loaded
* from the URL returned by
* {@link #getUrl(com.google.android.photostream.Flickr.PhotoSize)}.
*
* @param size The size of the photo to load.
*
* @return A Bitmap whose longest size is the same as the longest side of the
* specified {@link com.google.android.photostream.Flickr.PhotoSize}, or null
* if the photo could not be loaded.
*/
Bitmap loadPhotoBitmap(PhotoSize size) {
Bitmap bitmap = null;
InputStream in = null;
BufferedOutputStream out = null;
try {
in = new BufferedInputStream(new URL(getUrl(size)).openStream(),
IO_BUFFER_SIZE);
if (FLAG_DECODE_PHOTO_STREAM_WITH_SKIA) {
bitmap = BitmapFactory.decodeStream(in);
} else {
final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
copy(in, out);
out.flush();
final byte[] data = dataStream.toByteArray();
bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
}
} catch (IOException e) {
android.util.Log.e(Flickr.LOG_TAG, "Could not load photo: " + this, e);
} finally {
closeStream(in);
closeStream(out);
}
return bitmap;
}
@Override
public String toString() {
return mTitle + ", " + mDate + " @" + mId;
}
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel dest, int flags) {
dest.writeString(mId);
dest.writeString(mSecret);
dest.writeString(mServer);
dest.writeString(mFarm);
dest.writeString(mTitle);
dest.writeString(mDate);
}
public static final Parcelable.Creator<Photo> CREATOR = new Parcelable.Creator<Photo>() {
public Photo createFromParcel(Parcel in) {
return new Photo(in);
}
public Photo[] newArray(int size) {
return new Photo[size];
}
};
}
/**
* A list of {@link com.google.android.photostream.Flickr.Photo photos}. A list
* represents a series of photo on a page from the user's photostream, a list is
* therefore associated with a page index and a page count. The page index and the
* page count both depend on the number of photos per page.
*/
static class PhotoList {
private ArrayList<Photo> mPhotos;
private int mPage;
private int mPageCount;
private void add(Photo photo) {
mPhotos.add(photo);
}
/**
* Returns the photo at the specified index in the current set. An
* {@link ArrayIndexOutOfBoundsException} can be thrown if the index is
* less than 0 or greater then or equals to {@link #getCount()}.
*
* @param index The index of the photo to retrieve from the list.
*
* @return A valid {@link com.google.android.photostream.Flickr.Photo}.
*/
public Photo get(int index) {
return mPhotos.get(index);
}
/**
* Returns the number of photos in the list.
*
* @return A positive integer, or 0 if the list is empty.
*/
public int getCount() {
return mPhotos.size();
}
/**
* Returns the page index of the photos from this list.
*
* @return The index of the Flickr page that contains the photos of this list.
*/
public int getPage() {
return mPage;
}
/**
* Returns the total number of photo pages.
*
* @return A positive integer, or 0 if the photostream is empty.
*/
public int getPageCount() {
return mPageCount;
}
}
/**
* Returns the unique instance of this class.
*
* @return The unique instance of this class.
*/
static Flickr get() {
return sInstance;
}
private Flickr() {
final HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, "UTF-8");
final SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
final ThreadSafeClientConnManager manager =
new ThreadSafeClientConnManager(params, registry);
mClient = new DefaultHttpClient(manager, params);
}
/**
* Finds a user by its user name. This method will return an instance of
* {@link com.google.android.photostream.Flickr.User} containing the user's
* NSID, or null if the user could not be found.
*
* The returned User contains only the user's NSID. To retrieve more information
* about the user, please refer to
* {@link #getUserInfo(com.google.android.photostream.Flickr.User)}
*
* @param userName The name of the user to find.
*
* @return A User instance with a valid NSID, or null if the user cannot be found.
*
* @see #getUserInfo(com.google.android.photostream.Flickr.User)
* @see com.google.android.photostream.Flickr.User
* @see com.google.android.photostream.Flickr.UserInfo
*/
User findByUserName(String userName) {
final Uri.Builder uri = buildGetMethod(API_PEOPLE_FIND_BY_USERNAME);
uri.appendQueryParameter(PARAM_USERNAME, userName);
final HttpGet get = new HttpGet(uri.build().toString());
final String[] userId = new String[1];
try {
executeRequest(get, new ResponseHandler() {
public void handleResponse(InputStream in) throws IOException {
parseResponse(in, new ResponseParser() {
public void parseResponse(XmlPullParser parser)
throws XmlPullParserException, IOException {
parseUser(parser, userId);
}
});
}
});
if (userId[0] != null) {
return new User(userId[0]);
}
} catch (IOException e) {
android.util.Log.e(LOG_TAG, "Could not find the user with name: " + userName);
}
return null;
}
/**
* Retrieves a public set of information about the specified user. The user can
* either be {@link com.google.android.photostream.Flickr.User#fromId(String) created manually}
* or {@link #findByUserName(String) obtained from a user name}.
*
* @param user The user, whose NSID is valid, to retrive public information for.
*
* @return An instance of {@link com.google.android.photostream.Flickr.UserInfo} or null
* if the user could not be found.
*
* @see com.google.android.photostream.Flickr.UserInfo
* @see com.google.android.photostream.Flickr.User
* @see #findByUserName(String)
*/
UserInfo getUserInfo(User user) {
final String nsid = user.getId();
final Uri.Builder uri = buildGetMethod(API_PEOPLE_GET_INFO);
uri.appendQueryParameter(PARAM_USERID, nsid);
final HttpGet get = new HttpGet(uri.build().toString());
try {
final UserInfo info = new UserInfo(nsid);
executeRequest(get, new ResponseHandler() {
public void handleResponse(InputStream in) throws IOException {
parseResponse(in, new ResponseParser() {
public void parseResponse(XmlPullParser parser)
throws XmlPullParserException, IOException {
parseUserInfo(parser, info);
}
});
}
});
return info;
} catch (IOException e) {
android.util.Log.e(LOG_TAG, "Could not find the user with id: " + nsid);
}
return null;
}
/**
* Retrives a list of photos for the specified user. The list contains at most the
* number of photos specified by <code>perPage</code>. The photos are retrieved
* starting a the specified page index. For instance, if a user has 10 photos in
* his photostream, calling getPublicPhotos(user, 5, 2) will return the last 5 photos
* of the photo stream.
*
* The page index starts at 1, not 0.
*
* @param user The user to retrieve photos from.
* @param perPage The maximum number of photos to retrieve.
* @param page The index (starting at 1) of the page in the photostream.
*
* @return A list of at most perPage photos.
*
* @see com.google.android.photostream.Flickr.Photo
* @see com.google.android.photostream.Flickr.PhotoList
* @see #downloadPhoto(com.google.android.photostream.Flickr.Photo,
* com.google.android.photostream.Flickr.PhotoSize, java.io.OutputStream)
*/
PhotoList getPublicPhotos(User user, int perPage, int page) {
final Uri.Builder uri = buildGetMethod(API_PEOPLE_GET_PUBLIC_PHOTOS);
uri.appendQueryParameter(PARAM_USERID, user.getId());
uri.appendQueryParameter(PARAM_PER_PAGE, String.valueOf(perPage));
uri.appendQueryParameter(PARAM_PAGE, String.valueOf(page));
uri.appendQueryParameter(PARAM_EXTRAS, VALUE_DEFAULT_EXTRAS);
final HttpGet get = new HttpGet(uri.build().toString());
final PhotoList photos = new PhotoList();
try {
executeRequest(get, new ResponseHandler() {
public void handleResponse(InputStream in) throws IOException {
parseResponse(in, new ResponseParser() {
public void parseResponse(XmlPullParser parser)
throws XmlPullParserException, IOException {
parsePhotos(parser, photos);
}
});
}
});
} catch (IOException e) {
android.util.Log.e(LOG_TAG, "Could not find photos for user: " + user);
}
return photos;
}
/**
* Retrieves the geographical location of the specified photo. If the photo
* has no geodata associated with it, this method returns null.
*
* @param photo The photo to get the location of.
*
* @return The geo location of the photo, or null if the photo has no geodata
* or the photo cannot be found.
*
* @see com.google.android.photostream.Flickr.Location
*/
Location getLocation(Flickr.Photo photo) {
final Uri.Builder uri = buildGetMethod(API_PEOPLE_GET_LOCATION);
uri.appendQueryParameter(PARAM_PHOTO_ID, photo.mId);
final HttpGet get = new HttpGet(uri.build().toString());
final Location location = new Location(0.0f, 0.0f);
try {
executeRequest(get, new ResponseHandler() {
public void handleResponse(InputStream in) throws IOException {
parseResponse(in, new ResponseParser() {
public void parseResponse(XmlPullParser parser)
throws XmlPullParserException, IOException {
parsePhotoLocation(parser, location);
}
});
}
});
return location;
} catch (IOException e) {
android.util.Log.e(LOG_TAG, "Could not find location for photo: " + photo);
}
return null;
}
/**
* Checks the specified user's feed to see if any updated occured after the
* specified date.
*
* @param user The user whose feed must be checked.
* @param reference The date after which to check for updates.
*
* @return True if any update occured after the reference date, false otherwise.
*/
boolean hasUpdates(User user, final Calendar reference) {
final Uri.Builder uri = new Uri.Builder();
uri.path(API_FEED_URL);
uri.appendQueryParameter(PARAM_FEED_ID, user.getId());
uri.appendQueryParameter(PARAM_FEED_FORMAT, VALUE_DEFAULT_FORMAT);
final HttpGet get = new HttpGet(uri.build().toString());
final boolean[] updated = new boolean[1];
try {
executeRequest(get, new ResponseHandler() {
public void handleResponse(InputStream in) throws IOException {
parseFeedResponse(in, new ResponseParser() {
public void parseResponse(XmlPullParser parser)
throws XmlPullParserException, IOException {
updated[0] = parseUpdated(parser, reference);
}
});
}
});
} catch (IOException e) {
android.util.Log.e(LOG_TAG, "Could not find feed for user: " + user);
}
return updated[0];
}
/**
* Downloads the specified photo at the specified size in the specified destination.
*
* @param photo The photo to download.
* @param size The size of the photo to download.
* @param destination The output stream in which to write the downloaded photo.
*
* @throws IOException If any network exception occurs during the download.
*/
void downloadPhoto(Photo photo, PhotoSize size, OutputStream destination) throws IOException {
final BufferedOutputStream out = new BufferedOutputStream(destination, IO_BUFFER_SIZE);
final String url = photo.getUrl(size);
final HttpGet get = new HttpGet(url);
HttpEntity entity = null;
try {
final HttpResponse response = mClient.execute(get);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
entity = response.getEntity();
entity.writeTo(out);
out.flush();
}
} finally {
if (entity != null) {
entity.consumeContent();
}
}
}
private boolean parseUpdated(XmlPullParser parser, Calendar reference) throws IOException,
XmlPullParserException {
int type;
String name;
final int depth = parser.getDepth();
while (((type = parser.next()) != XmlPullParser.END_TAG ||
parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
if (type != XmlPullParser.START_TAG) {
continue;
}
name = parser.getName();
if (RESPONSE_TAG_UPDATED.equals(name)) {
if (parser.next() == XmlPullParser.TEXT) {
final SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
try {
final String text = parser.getText().replace('T', ' ').replace('Z', ' ');
final Calendar calendar = new GregorianCalendar();
calendar.setTimeInMillis(format.parse(text).getTime());
return calendar.after(reference);
} catch (ParseException e) {
// Ignore
}
}
}
}
return false;
}
private void parsePhotos(XmlPullParser parser, PhotoList photos)
throws XmlPullParserException, IOException {
int type;
String name;
SimpleDateFormat parseFormat = null;
SimpleDateFormat outputFormat = null;
final int depth = parser.getDepth();
while (((type = parser.next()) != XmlPullParser.END_TAG ||
parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
if (type != XmlPullParser.START_TAG) {
continue;
}
name = parser.getName();
if (RESPONSE_TAG_PHOTOS.equals(name)) {
photos.mPage = Integer.parseInt(parser.getAttributeValue(null, RESPONSE_ATTR_PAGE));
photos.mPageCount = Integer.parseInt(parser.getAttributeValue(null,
RESPONSE_ATTR_PAGES));
photos.mPhotos = new ArrayList<Photo>();
} else if (RESPONSE_TAG_PHOTO.equals(name)) {
final Photo photo = new Photo();
photo.mId = parser.getAttributeValue(null, RESPONSE_ATTR_ID);
photo.mSecret = parser.getAttributeValue(null, RESPONSE_ATTR_SECRET);
photo.mServer = parser.getAttributeValue(null, RESPONSE_ATTR_SERVER);
photo.mFarm = parser.getAttributeValue(null, RESPONSE_ATTR_FARM);
photo.mTitle = parser.getAttributeValue(null, RESPONSE_ATTR_TITLE);
photo.mDate = parser.getAttributeValue(null, RESPONSE_ATTR_DATE_TAKEN);
if (parseFormat == null) {
parseFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
outputFormat = new SimpleDateFormat("MMMM d, yyyy");
}
try {
photo.mDate = outputFormat.format(parseFormat.parse(photo.mDate));
} catch (ParseException e) {
android.util.Log.w(LOG_TAG, "Could not parse photo date", e);
}
photos.add(photo);
}
}
}
private void parsePhotoLocation(XmlPullParser parser, Location location)
throws XmlPullParserException, IOException {
int type;
String name;
final int depth = parser.getDepth();
while (((type = parser.next()) != XmlPullParser.END_TAG ||
parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
if (type != XmlPullParser.START_TAG) {
continue;
}
name = parser.getName();
if (RESPONSE_TAG_LOCATION.equals(name)) {
try {
location.mLatitude = Float.parseFloat(parser.getAttributeValue(null,
RESPONSE_ATTR_LATITUDE));
location.mLongitude = Float.parseFloat(parser.getAttributeValue(null,
RESPONSE_ATTR_LONGITUDE));
} catch (NumberFormatException e) {
throw new XmlPullParserException("Could not parse lat/lon", parser, e);
}
}
}
}
private void parseUser(XmlPullParser parser, String[] userId)
throws XmlPullParserException, IOException {
int type;
String name;
final int depth = parser.getDepth();
while (((type = parser.next()) != XmlPullParser.END_TAG ||
parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
if (type != XmlPullParser.START_TAG) {
continue;
}
name = parser.getName();
if (RESPONSE_TAG_USER.equals(name)) {
userId[0] = parser.getAttributeValue(null, RESPONSE_ATTR_NSID);
}
}
}
private void parseUserInfo(XmlPullParser parser, UserInfo info)
throws XmlPullParserException, IOException {
int type;
String name;
final int depth = parser.getDepth();
while (((type = parser.next()) != XmlPullParser.END_TAG ||
parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
if (type != XmlPullParser.START_TAG) {
continue;
}
name = parser.getName();
if (RESPONSE_TAG_PERSON.equals(name)) {
info.mIsPro = "1".equals(parser.getAttributeValue(null, RESPONSE_ATTR_ISPRO));
info.mIconServer = parser.getAttributeValue(null, RESPONSE_ATTR_ICONSERVER);
info.mIconFarm = parser.getAttributeValue(null, RESPONSE_ATTR_ICONFARM);
} else if (RESPONSE_TAG_USERNAME.equals(name)) {
if (parser.next() == XmlPullParser.TEXT) {
info.mUserName = parser.getText();
}
} else if (RESPONSE_TAG_REALNAME.equals(name)) {
if (parser.next() == XmlPullParser.TEXT) {
info.mRealName = parser.getText();
}
} else if (RESPONSE_TAG_LOCATION.equals(name)) {
if (parser.next() == XmlPullParser.TEXT) {
info.mLocation = parser.getText();
}
} else if (RESPONSE_TAG_PHOTOSURL.equals(name)) {
if (parser.next() == XmlPullParser.TEXT) {
info.mPhotosUrl = parser.getText();
}
} else if (RESPONSE_TAG_PROFILEURL.equals(name)) {
if (parser.next() == XmlPullParser.TEXT) {
info.mProfileUrl = parser.getText();
}
} else if (RESPONSE_TAG_MOBILEURL.equals(name)) {
if (parser.next() == XmlPullParser.TEXT) {
info.mMobileUrl = parser.getText();
}
}
}
}
/**
* Parses a valid Flickr XML response from the specified input stream. When the Flickr
* response contains the OK tag, the response is sent to the specified response parser.
*
* @param in The input stream containing the response sent by Flickr.
* @param responseParser The parser to use when the response is valid.
*
* @throws IOException
*/
private void parseResponse(InputStream in, ResponseParser responseParser) throws IOException {
final XmlPullParser parser = Xml.newPullParser();
try {
parser.setInput(new InputStreamReader(in));
int type;
while ((type = parser.next()) != XmlPullParser.START_TAG &&
type != XmlPullParser.END_DOCUMENT) {
// Empty
}
if (type != XmlPullParser.START_TAG) {
throw new InflateException(parser.getPositionDescription()
+ ": No start tag found!");
}
String name = parser.getName();
if (RESPONSE_TAG_RSP.equals(name)) {
final String value = parser.getAttributeValue(null, RESPONSE_ATTR_STAT);
if (!RESPONSE_STATUS_OK.equals(value)) {
throw new IOException("Wrong status: " + value);
}
}
responseParser.parseResponse(parser);
} catch (XmlPullParserException e) {
final IOException ioe = new IOException("Could not parser the response");
ioe.initCause(e);
throw ioe;
}
}
/**
* Parses a valid Flickr Atom feed response from the specified input stream.
*
* @param in The input stream containing the response sent by Flickr.
* @param responseParser The parser to use when the response is valid.
*
* @throws IOException
*/
private void parseFeedResponse(InputStream in, ResponseParser responseParser)
throws IOException {
final XmlPullParser parser = Xml.newPullParser();
try {
parser.setInput(new InputStreamReader(in));
int type;
while ((type = parser.next()) != XmlPullParser.START_TAG &&
type != XmlPullParser.END_DOCUMENT) {
// Empty
}
if (type != XmlPullParser.START_TAG) {
throw new InflateException(parser.getPositionDescription()
+ ": No start tag found!");
}
String name = parser.getName();
if (RESPONSE_TAG_FEED.equals(name)) {
responseParser.parseResponse(parser);
} else {
throw new IOException("Wrong start tag: " + name);
}
} catch (XmlPullParserException e) {
final IOException ioe = new IOException("Could not parser the response");
ioe.initCause(e);
throw ioe;
}
}
/**
* Executes an HTTP request on Flickr's web service. If the response is ok, the content
* is sent to the specified response handler.
*
* @param get The GET request to executed.
* @param handler The handler which will parse the response.
*
* @throws IOException
*/
private void executeRequest(HttpGet get, ResponseHandler handler) throws IOException {
HttpEntity entity = null;
HttpHost host = new HttpHost(API_REST_HOST, 80, "http");
try {
final HttpResponse response = mClient.execute(host, get);
if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
entity = response.getEntity();
final InputStream in = entity.getContent();
handler.handleResponse(in);
}
} finally {
if (entity != null) {
entity.consumeContent();
}
}
}
/**
* Builds an HTTP GET request for the specified Flickr API method. The returned request
* contains the web service path, the query parameter for the API KEY and the query
* parameter for the specified method.
*
* @param method The Flickr API method to invoke.
*
* @return A Uri.Builder containing the GET path, the API key and the method already
* encoded.
*/
private static Uri.Builder buildGetMethod(String method) {
final Uri.Builder builder = new Uri.Builder();
builder.path(API_REST_URL).appendQueryParameter(PARAM_API_KEY, API_KEY);
builder.appendQueryParameter(PARAM_METHOD, method);
return builder;
}
/**
* Copy the content of the input stream into the output stream, using a temporary
* byte array buffer whose size is defined by {@link #IO_BUFFER_SIZE}.
*
* @param in The input stream to copy from.
* @param out The output stream to copy to.
*
* @throws IOException If any error occurs during the copy.
*/
private static void copy(InputStream in, OutputStream out) throws IOException {
byte[] b = new byte[IO_BUFFER_SIZE];
int read;
while ((read = in.read(b)) != -1) {
out.write(b, 0, read);
}
}
/**
* Closes the specified stream.
*
* @param stream The stream to close.
*/
private static void closeStream(Closeable stream) {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
android.util.Log.e(Flickr.LOG_TAG, "Could not close stream", e);
}
}
}
/**
* Response handler used with
* {@link Flickr#executeRequest(org.apache.http.client.methods.HttpGet,
* com.google.android.photostream.Flickr.ResponseHandler)}. The handler is invoked when
* a response is sent by the server. The response is made available as an input stream.
*/
private static interface ResponseHandler {
/**
* Processes the responses sent by the HTTP server following a GET request.
*
* @param in The stream containing the server's response.
*
* @throws IOException
*/
public void handleResponse(InputStream in) throws IOException;
}
/**
* Response parser used with {@link Flickr#parseResponse(java.io.InputStream,
* com.google.android.photostream.Flickr.ResponseParser)}. When Flickr returns a valid
* response, this parser is invoked to process the XML response.
*/
private static interface ResponseParser {
/**
* Processes the XML response sent by the Flickr web service after a successful
* request.
*
* @param parser The parser containing the XML responses.
*
* @throws XmlPullParserException
* @throws IOException
*/
public void parseResponse(XmlPullParser parser) throws XmlPullParserException, IOException;
}
}
| 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.photostream;
import android.app.Activity;
import android.app.NotificationManager;
import android.os.Bundle;
import android.content.Intent;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.animation.TranslateAnimation;
import android.view.animation.Animation;
import android.view.animation.AccelerateDecelerateInterpolator;
import android.view.animation.AnimationUtils;
import android.view.animation.LayoutAnimationController;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.widget.ImageView;
import android.widget.ViewAnimator;
import java.util.Random;
import java.util.List;
/**
* Activity used to display a Flickr user's photostream. This activity shows a fixed
* number of photos at a time. The activity is invoked either by LoginActivity, when
* the application is launched normally, or by a Home shortcut, or by an Intent with
* the view action and a flickr://photos/nsid URI.
*/
public class PhotostreamActivity extends Activity implements
View.OnClickListener, Animation.AnimationListener {
static final String ACTION = "com.google.android.photostream.FLICKR_STREAM";
static final String EXTRA_NOTIFICATION = "com.google.android.photostream.extra_notify_id";
static final String EXTRA_NSID = "com.google.android.photostream.extra_nsid";
static final String EXTRA_USER = "com.google.android.photostream.extra_user";
private static final String STATE_USER = "com.google.android.photostream.state_user";
private static final String STATE_PAGE = "com.google.android.photostream.state_page";
private static final String STATE_PAGE_COUNT = "com.google.android.photostream.state_pagecount";
private static final int PHOTOS_COUNT_PER_PAGE = 6;
private Flickr.User mUser;
private int mCurrentPage = 1;
private int mPageCount = 0;
private LayoutInflater mInflater;
private ViewAnimator mSwitcher;
private View mMenuNext;
private View mMenuBack;
private View mMenuSeparator;
private GridLayout mGrid;
private LayoutAnimationController mNextAnimation;
private LayoutAnimationController mBackAnimation;
private UserTask<?, ?, ?> mTask;
private String mUsername;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
clearNotification();
// Try to find a user name in the saved instance state or the intent
// that launched the activity. If no valid user NSID can be found, we
// just close the activity.
if (!initialize(savedInstanceState)) {
finish();
return;
}
setContentView(R.layout.screen_photostream);
setupViews();
loadPhotos();
}
private void clearNotification() {
final int notification = getIntent().getIntExtra(EXTRA_NOTIFICATION, -1);
if (notification != -1) {
NotificationManager manager = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
manager.cancel(notification);
}
}
/**
* Starts the PhotostreamActivity for the specified user.
*
* @param context The application's environment.
* @param user The user whose photos to display with a PhotostreamActivity.
*/
static void show(Context context, Flickr.User user) {
final Intent intent = new Intent(ACTION);
intent.putExtra(EXTRA_USER, user);
context.startActivity(intent);
}
/**
* Restores a previously saved state or, if missing, finds the user's NSID
* from the intent used to start the activity.
*
* @param savedInstanceState The saved state, if any.
*
* @return true if a {@link com.google.android.photostream.Flickr.User} was
* found either in the saved state or the intent.
*/
private boolean initialize(Bundle savedInstanceState) {
Flickr.User user;
if (savedInstanceState != null) {
user = savedInstanceState.getParcelable(STATE_USER);
mCurrentPage = savedInstanceState.getInt(STATE_PAGE);
mPageCount = savedInstanceState.getInt(STATE_PAGE_COUNT);
} else {
user = getUser();
}
mUser = user;
return mUser != null || mUsername != null;
}
/**
* Creates a {@link com.google.android.photostream.Flickr.User} instance
* from the intent used to start this activity.
*
* @return The user whose photos will be displayed, or null if no
* user was found.
*/
private Flickr.User getUser() {
final Intent intent = getIntent();
final String action = intent.getAction();
Flickr.User user = null;
if (ACTION.equals(action)) {
final Bundle extras = intent.getExtras();
if (extras != null) {
user = extras.getParcelable(EXTRA_USER);
if (user == null) {
final String nsid = extras.getString(EXTRA_NSID);
if (nsid != null) {
user = Flickr.User.fromId(nsid);
}
}
}
} else if (Intent.ACTION_VIEW.equals(action)) {
final List<String> segments = intent.getData().getPathSegments();
if (segments.size() > 1) {
mUsername = segments.get(1);
}
}
return user;
}
private void setupViews() {
mInflater = LayoutInflater.from(PhotostreamActivity.this);
mNextAnimation = AnimationUtils.loadLayoutAnimation(this, R.anim.layout_slide_next);
mBackAnimation = AnimationUtils.loadLayoutAnimation(this, R.anim.layout_slide_back);
mSwitcher = (ViewAnimator) findViewById(R.id.switcher_menu);
mMenuNext = findViewById(R.id.menu_next);
mMenuBack = findViewById(R.id.menu_back);
mMenuSeparator = findViewById(R.id.menu_separator);
mGrid = (GridLayout) findViewById(R.id.grid_photos);
mMenuNext.setOnClickListener(this);
mMenuBack.setOnClickListener(this);
mMenuBack.setVisibility(View.GONE);
mMenuSeparator.setVisibility(View.GONE);
mGrid.setClipToPadding(false);
}
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putParcelable(STATE_USER, mUser);
outState.putInt(STATE_PAGE, mCurrentPage);
outState.putInt(STATE_PAGE_COUNT, mPageCount);
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mTask != null && mTask.getStatus() == UserTask.Status.RUNNING) {
mTask.cancel(true);
}
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.menu_next:
onNext();
break;
case R.id.menu_back:
onBack();
break;
default:
onShowPhoto((Flickr.Photo) v.getTag());
break;
}
}
@Override
public Object onRetainNonConfigurationInstance() {
final GridLayout grid = mGrid;
final int count = grid.getChildCount();
final LoadedPhoto[] list = new LoadedPhoto[count];
for (int i = 0; i < count; i++) {
final ImageView v = (ImageView) grid.getChildAt(i);
list[i] = new LoadedPhoto(((BitmapDrawable) v.getDrawable()).getBitmap(),
(Flickr.Photo) v.getTag());
}
return list;
}
private void prepareMenu(int pageCount) {
final boolean backVisible = mCurrentPage > 1;
final boolean nextVisible = mCurrentPage < pageCount;
mMenuBack.setVisibility(backVisible ? View.VISIBLE : View.GONE);
mMenuNext.setVisibility(nextVisible ? View.VISIBLE : View.GONE);
mMenuSeparator.setVisibility(backVisible && nextVisible ? View.VISIBLE : View.GONE);
}
private void loadPhotos() {
final Object data = getLastNonConfigurationInstance();
if (data == null) {
mTask = new GetPhotoListTask().execute(mCurrentPage);
} else {
final LoadedPhoto[] photos = (LoadedPhoto[]) data;
for (LoadedPhoto photo : photos) {
addPhoto(photo);
}
prepareMenu(mPageCount);
mSwitcher.showNext();
}
}
private void showPhotos(Flickr.PhotoList photos) {
mTask = new LoadPhotosTask().execute(photos);
}
private void onShowPhoto(Flickr.Photo photo) {
ViewPhotoActivity.show(this, photo);
}
private void onNext() {
mCurrentPage++;
animateAndLoadPhotos(mNextAnimation);
}
private void onBack() {
mCurrentPage--;
animateAndLoadPhotos(mBackAnimation);
}
private void animateAndLoadPhotos(LayoutAnimationController animation) {
mSwitcher.showNext();
mGrid.setLayoutAnimationListener(this);
mGrid.setLayoutAnimation(animation);
mGrid.invalidate();
}
public void onAnimationEnd(Animation animation) {
mGrid.setLayoutAnimationListener(null);
mGrid.setLayoutAnimation(null);
mGrid.removeAllViews();
loadPhotos();
}
public void onAnimationStart(Animation animation) {
}
public void onAnimationRepeat(Animation animation) {
}
private static Animation createAnimationForChild(int childIndex) {
boolean firstColumn = (childIndex & 0x1) == 0;
Animation translate = new TranslateAnimation(
Animation.RELATIVE_TO_SELF, firstColumn ? -1.1f : 1.1f,
Animation.RELATIVE_TO_SELF, 0.0f,
Animation.RELATIVE_TO_SELF, 0.0f,
Animation.RELATIVE_TO_SELF, 0.0f);
translate.setInterpolator(new AccelerateDecelerateInterpolator());
translate.setFillAfter(false);
translate.setDuration(300);
return translate;
}
private void addPhoto(LoadedPhoto... value) {
ImageView image = (ImageView) mInflater.inflate(R.layout.grid_item_photo, mGrid, false);
image.setImageBitmap(value[0].mBitmap);
image.startAnimation(createAnimationForChild(mGrid.getChildCount()));
image.setTag(value[0].mPhoto);
image.setOnClickListener(PhotostreamActivity.this);
mGrid.addView(image);
}
/**
* Background task used to load each individual photo. The task loads each photo
* in order and publishes each loaded Bitmap as a progress unit. The tasks ends
* by hiding the progress bar and showing the menu.
*/
private class LoadPhotosTask extends UserTask<Flickr.PhotoList, LoadedPhoto, Flickr.PhotoList> {
private final Random mRandom;
private LoadPhotosTask() {
mRandom = new Random();
}
public Flickr.PhotoList doInBackground(Flickr.PhotoList... params) {
final Flickr.PhotoList list = params[0];
final int count = list.getCount();
for (int i = 0; i < count; i++) {
if (isCancelled()) break;
final Flickr.Photo photo = list.get(i);
Bitmap bitmap = photo.loadPhotoBitmap(Flickr.PhotoSize.THUMBNAIL);
if (!isCancelled()) {
if (bitmap == null) {
final boolean portrait = mRandom.nextFloat() >= 0.5f;
bitmap = BitmapFactory.decodeResource(getResources(), portrait ?
R.drawable.not_found_small_1 : R.drawable.not_found_small_2);
}
publishProgress(new LoadedPhoto(ImageUtilities.rotateAndFrame(bitmap), photo));
bitmap.recycle();
}
}
return list;
}
/**
* Whenever a photo's Bitmap is loaded from the background thread, it is
* displayed in this method by adding a new ImageView in the photos grid.
* Each ImageView's tag contains the {@link com.google.android.photostream.Flickr.Photo}
* it was loaded from.
*
* @param value The photo and its bitmap.
*/
@Override
public void onProgressUpdate(LoadedPhoto... value) {
addPhoto(value);
}
@Override
public void onPostExecute(Flickr.PhotoList result) {
mPageCount = result.getPageCount();
prepareMenu(mPageCount);
mSwitcher.showNext();
mTask = null;
}
}
/**
* Background task used to load the list of photos. The tasks queries Flickr for the
* list of photos to display and ends by starting the LoadPhotosTask.
*/
private class GetPhotoListTask extends UserTask<Integer, Void, Flickr.PhotoList> {
public Flickr.PhotoList doInBackground(Integer... params) {
if (mUsername != null) {
mUser = Flickr.get().findByUserName(mUsername);
mUsername = null;
}
return Flickr.get().getPublicPhotos(mUser, PHOTOS_COUNT_PER_PAGE, params[0]);
}
@Override
public void onPostExecute(Flickr.PhotoList photoList) {
showPhotos(photoList);
mTask = null;
}
}
/**
* A LoadedPhoto contains the Flickr photo and the Bitmap loaded for that photo.
*/
private static class LoadedPhoto {
Bitmap mBitmap;
Flickr.Photo mPhoto;
LoadedPhoto(Bitmap bitmap, Flickr.Photo photo) {
mBitmap = bitmap;
mPhoto = photo;
}
}
}
| 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.photostream;
import android.os.*;
import android.os.Process;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.CancellationException;
import java.util.concurrent.atomic.AtomicInteger;
/**
* <p>UserTask enables proper and easy use of the UI thread. This class allows to
* perform background operations and publish results on the UI thread without
* having to manipulate threads and/or handlers.</p>
*
* <p>A user task is defined by a computation that runs on a background thread and
* whose result is published on the UI thread. A user task is defined by 3 generic
* types, called <code>Params</code>, <code>Progress</code> and <code>Result</code>,
* and 4 steps, called <code>begin</code>, <code>doInBackground</code>,
* <code>processProgress<code> and <code>end</code>.</p>
*
* <h2>Usage</h2>
* <p>UserTask must be subclassed to be used. The subclass will override at least
* one method ({@link #doInBackground(Object[])}), and most often will override a
* second one ({@link #onPostExecute(Object)}.)</p>
*
* <p>Here is an example of subclassing:</p>
* <pre>
* private class DownloadFilesTask extends UserTask<URL, Integer, Long> {
* public File doInBackground(URL... urls) {
* int count = urls.length;
* long totalSize = 0;
* for (int i = 0; i < count; i++) {
* totalSize += Downloader.downloadFile(urls[i]);
* publishProgress((int) ((i / (float) count) * 100));
* }
* }
*
* public void onProgressUpdate(Integer... progress) {
* setProgressPercent(progress[0]);
* }
*
* public void onPostExecute(Long result) {
* showDialog("Downloaded " + result + " bytes");
* }
* }
* </pre>
*
* <p>Once created, a task is executed very simply:</p>
* <pre>
* new DownloadFilesTask().execute(new URL[] { ... });
* </pre>
*
* <h2>User task's generic types</h2>
* <p>The three types used by a user task are the following:</p>
* <ol>
* <li><code>Params</code>, the type of the parameters sent to the task upon
* execution.</li>
* <li><code>Progress</code>, the type of the progress units published during
* the background computation.</li>
* <li><code>Result</code>, the type of the result of the background
* computation.</li>
* </ol>
* <p>Not all types are always used by a user task. To mark a type as unused,
* simply use the type {@link Void}:</p>
* <pre>
* private class MyTask extends UserTask<Void, Void, Void) { ... }
* </pre>
*
* <h2>The 4 steps</h2>
* <p>When a user task is executed, the task goes through 4 steps:</p>
* <ol>
* <li>{@link #onPreExecute()}, invoked on the UI thread immediately after the task
* is executed. This step is normally used to setup the task, for instance by
* showing a progress bar in the user interface.</li>
* <li>{@link #doInBackground(Object[])}, invoked on the background thread
* immediately after {@link # onPreExecute ()} finishes executing. This step is used
* to perform background computation that can take a long time. The parameters
* of the user task are passed to this step. The result of the computation must
* be returned by this step and will be passed back to the last step. This step
* can also use {@link #publishProgress(Object[])} to publish one or more units
* of progress. These values are published on the UI thread, in the
* {@link #onProgressUpdate(Object[])} step.</li>
* <li>{@link # onProgressUpdate (Object[])}, invoked on the UI thread after a
* call to {@link #publishProgress(Object[])}. The timing of the execution is
* undefined. This method is used to display any form of progress in the user
* interface while the background computation is still executing. For instance,
* it can be used to animate a progress bar or show logs in a text field.</li>
* <li>{@link # onPostExecute (Object)}, invoked on the UI thread after the background
* computation finishes. The result of the background computation is passed to
* this step as a parameter.</li>
* </ol>
*
* <h2>Threading rules</h2>
* <p>There are a few threading rules that must be followed for this class to
* work properly:</p>
* <ul>
* <li>The task instance must be created on the UI thread.</li>
* <li>{@link #execute(Object[])} must be invoked on the UI thread.</li>
* <li>Do not call {@link # onPreExecute ()}, {@link # onPostExecute (Object)},
* {@link #doInBackground(Object[])}, {@link # onProgressUpdate (Object[])}
* manually.</li>
* <li>The task can be executed only once (an exception will be thrown if
* a second execution is attempted.)</li>
* </ul>
*/
public abstract class UserTask<Params, Progress, Result> {
private static final String LOG_TAG = "UserTask";
private static final int CORE_POOL_SIZE = 1;
private static final int MAXIMUM_POOL_SIZE = 10;
private static final int KEEP_ALIVE = 10;
private static final BlockingQueue<Runnable> sWorkQueue =
new LinkedBlockingQueue<Runnable>(MAXIMUM_POOL_SIZE);
private static final ThreadFactory sThreadFactory = new ThreadFactory() {
private final AtomicInteger mCount = new AtomicInteger(1);
public Thread newThread(Runnable r) {
return new Thread(r, "UserTask #" + mCount.getAndIncrement());
}
};
private static final ThreadPoolExecutor sExecutor = new ThreadPoolExecutor(CORE_POOL_SIZE,
MAXIMUM_POOL_SIZE, KEEP_ALIVE, TimeUnit.SECONDS, sWorkQueue, sThreadFactory);
private static final int MESSAGE_POST_RESULT = 0x1;
private static final int MESSAGE_POST_PROGRESS = 0x2;
private static final int MESSAGE_POST_CANCEL = 0x3;
private static final InternalHandler sHandler = new InternalHandler();
private final WorkerRunnable<Params, Result> mWorker;
private final FutureTask<Result> mFuture;
private volatile Status mStatus = Status.PENDING;
/**
* Indicates the current status of the task. Each status will be set only once
* during the lifetime of a task.
*/
public enum Status {
/**
* Indicates that the task has not been executed yet.
*/
PENDING,
/**
* Indicates that the task is running.
*/
RUNNING,
/**
* Indicates that {@link UserTask#onPostExecute(Object)} has finished.
*/
FINISHED,
}
/**
* Creates a new user task. This constructor must be invoked on the UI thread.
*/
public UserTask() {
mWorker = new WorkerRunnable<Params, Result>() {
public Result call() throws Exception {
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
return doInBackground(mParams);
}
};
mFuture = new FutureTask<Result>(mWorker) {
@Override
protected void done() {
Message message;
Result result = null;
try {
result = get();
} catch (InterruptedException e) {
android.util.Log.w(LOG_TAG, e);
} catch (ExecutionException e) {
throw new RuntimeException("An error occured while executing doInBackground()",
e.getCause());
} catch (CancellationException e) {
message = sHandler.obtainMessage(MESSAGE_POST_CANCEL,
new UserTaskResult<Result>(UserTask.this, (Result[]) null));
message.sendToTarget();
return;
} catch (Throwable t) {
throw new RuntimeException("An error occured while executing "
+ "doInBackground()", t);
}
message = sHandler.obtainMessage(MESSAGE_POST_RESULT,
new UserTaskResult<Result>(UserTask.this, result));
message.sendToTarget();
}
};
}
/**
* Returns the current status of this task.
*
* @return The current status.
*/
public final Status getStatus() {
return mStatus;
}
/**
* Override this method to perform a computation on a background thread. The
* specified parameters are the parameters passed to {@link #execute(Object[])}
* by the caller of this task.
*
* This method can call {@link #publishProgress(Object[])} to publish updates
* on the UI thread.
*
* @param params The parameters of the task.
*
* @return A result, defined by the subclass of this task.
*
* @see #onPreExecute()
* @see #onPostExecute(Object)
* @see #publishProgress(Object[])
*/
public abstract Result doInBackground(Params... params);
/**
* Runs on the UI thread before {@link #doInBackground(Object[])}.
*
* @see #onPostExecute(Object)
* @see #doInBackground(Object[])
*/
public void onPreExecute() {
}
/**
* Runs on the UI thread after {@link #doInBackground(Object[])}. The
* specified result is the value returned by {@link #doInBackground(Object[])}
* or null if the task was cancelled or an exception occured.
*
* @param result The result of the operation computed by {@link #doInBackground(Object[])}.
*
* @see #onPreExecute()
* @see #doInBackground(Object[])
*/
@SuppressWarnings({"UnusedDeclaration"})
public void onPostExecute(Result result) {
}
/**
* Runs on the UI thread after {@link #publishProgress(Object[])} is invoked.
* The specified values are the values passed to {@link #publishProgress(Object[])}.
*
* @param values The values indicating progress.
*
* @see #publishProgress(Object[])
* @see #doInBackground(Object[])
*/
@SuppressWarnings({"UnusedDeclaration"})
public void onProgressUpdate(Progress... values) {
}
/**
* Runs on the UI thread after {@link #cancel(boolean)} is invoked.
*
* @see #cancel(boolean)
* @see #isCancelled()
*/
public void onCancelled() {
}
/**
* Returns <tt>true</tt> if this task was cancelled before it completed
* normally.
*
* @return <tt>true</tt> if task was cancelled before it completed
*
* @see #cancel(boolean)
*/
public final boolean isCancelled() {
return mFuture.isCancelled();
}
/**
* Attempts to cancel execution of this task. This attempt will
* fail if the task has already completed, already been cancelled,
* or could not be cancelled for some other reason. If successful,
* and this task has not started when <tt>cancel</tt> is called,
* this task should never run. If the task has already started,
* then the <tt>mayInterruptIfRunning</tt> parameter determines
* whether the thread executing this task should be interrupted in
* an attempt to stop the task.
*
* @param mayInterruptIfRunning <tt>true</tt> if the thread executing this
* task should be interrupted; otherwise, in-progress tasks are allowed
* to complete.
*
* @return <tt>false</tt> if the task could not be cancelled,
* typically because it has already completed normally;
* <tt>true</tt> otherwise
*
* @see #isCancelled()
* @see #onCancelled()
*/
public final boolean cancel(boolean mayInterruptIfRunning) {
return mFuture.cancel(mayInterruptIfRunning);
}
/**
* Waits if necessary for the computation to complete, and then
* retrieves its result.
*
* @return The computed result.
*
* @throws CancellationException If the computation was cancelled.
* @throws ExecutionException If the computation threw an exception.
* @throws InterruptedException If the current thread was interrupted
* while waiting.
*/
public final Result get() throws InterruptedException, ExecutionException {
return mFuture.get();
}
/**
* Waits if necessary for at most the given time for the computation
* to complete, and then retrieves its result.
*
* @param timeout Time to wait before cancelling the operation.
* @param unit The time unit for the timeout.
*
* @return The computed result.
*
* @throws CancellationException If the computation was cancelled.
* @throws ExecutionException If the computation threw an exception.
* @throws InterruptedException If the current thread was interrupted
* while waiting.
* @throws TimeoutException If the wait timed out.
*/
public final Result get(long timeout, TimeUnit unit) throws InterruptedException,
ExecutionException, TimeoutException {
return mFuture.get(timeout, unit);
}
/**
* Executes the task with the specified parameters. The task returns
* itself (this) so that the caller can keep a reference to it.
*
* This method must be invoked on the UI thread.
*
* @param params The parameters of the task.
*
* @return This instance of UserTask.
*
* @throws IllegalStateException If {@link #getStatus()} returns either
* {@link UserTask.Status#RUNNING} or {@link UserTask.Status#FINISHED}.
*/
public final UserTask<Params, Progress, Result> execute(Params... params) {
if (mStatus != Status.PENDING) {
switch (mStatus) {
case RUNNING:
throw new IllegalStateException("Cannot execute task:"
+ " the task is already running.");
case FINISHED:
throw new IllegalStateException("Cannot execute task:"
+ " the task has already been executed "
+ "(a task can be executed only once)");
}
}
mStatus = Status.RUNNING;
onPreExecute();
mWorker.mParams = params;
sExecutor.execute(mFuture);
return this;
}
/**
* This method can be invoked from {@link #doInBackground(Object[])} to
* publish updates on the UI thread while the background computation is
* still running. Each call to this method will trigger the execution of
* {@link #onProgressUpdate(Object[])} on the UI thread.
*
* @param values The progress values to update the UI with.
*
* @see # onProgressUpdate (Object[])
* @see #doInBackground(Object[])
*/
protected final void publishProgress(Progress... values) {
sHandler.obtainMessage(MESSAGE_POST_PROGRESS,
new UserTaskResult<Progress>(this, values)).sendToTarget();
}
private void finish(Result result) {
onPostExecute(result);
mStatus = Status.FINISHED;
}
private static class InternalHandler extends Handler {
@SuppressWarnings({"unchecked", "RawUseOfParameterizedType"})
@Override
public void handleMessage(Message msg) {
UserTaskResult result = (UserTaskResult) msg.obj;
switch (msg.what) {
case MESSAGE_POST_RESULT:
// There is only one result
result.mTask.finish(result.mData[0]);
break;
case MESSAGE_POST_PROGRESS:
result.mTask.onProgressUpdate(result.mData);
break;
case MESSAGE_POST_CANCEL:
result.mTask.onCancelled();
break;
}
}
}
private static abstract class WorkerRunnable<Params, Result> implements Callable<Result> {
Params[] mParams;
}
@SuppressWarnings({"RawUseOfParameterizedType"})
private static class UserTaskResult<Data> {
final UserTask mTask;
final Data[] mData;
UserTaskResult(UserTask task, Data... data) {
mTask = task;
mData = data;
}
}
}
| 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.photostream;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.ActivityNotFoundException;
import android.content.pm.ResolveInfo;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.os.Bundle;
import android.widget.TextView;
import android.widget.ImageView;
import android.widget.ViewAnimator;
import android.widget.LinearLayout;
import android.widget.Toast;
import android.widget.ArrayAdapter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.BitmapDrawable;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.Menu;
import android.view.MenuItem;
import android.view.animation.AnimationUtils;
import android.view.LayoutInflater;
import android.net.Uri;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.io.InputStream;
import java.io.FileNotFoundException;
import java.util.List;
import java.util.ArrayList;
/**
* Activity that displays a photo along with its title and the date at which it was taken.
* This activity also lets the user set the photo as the wallpaper.
*/
public class ViewPhotoActivity extends Activity implements View.OnClickListener,
ViewTreeObserver.OnGlobalLayoutListener {
static final String ACTION = "com.google.android.photostream.FLICKR_PHOTO";
private static final String RADAR_ACTION = "com.google.android.radar.SHOW_RADAR";
private static final String RADAR_EXTRA_LATITUDE = "latitude";
private static final String RADAR_EXTRA_LONGITUDE = "longitude";
private static final String EXTRA_PHOTO = "com.google.android.photostream.photo";
private static final String WALLPAPER_FILE_NAME = "wallpaper";
private static final int REQUEST_CROP_IMAGE = 42;
private Flickr.Photo mPhoto;
private ViewAnimator mSwitcher;
private ImageView mPhotoView;
private ViewGroup mContainer;
private UserTask<?, ?, ?> mTask;
private TextView mPhotoTitle;
private TextView mPhotoDate;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mPhoto = getPhoto();
setContentView(R.layout.screen_photo);
setupViews();
}
/**
* Starts the ViewPhotoActivity for the specified photo.
*
* @param context The application's environment.
* @param photo The photo to display and optionally set as a wallpaper.
*/
static void show(Context context, Flickr.Photo photo) {
final Intent intent = new Intent(ACTION);
intent.putExtra(EXTRA_PHOTO, photo);
context.startActivity(intent);
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mTask != null && mTask.getStatus() != UserTask.Status.RUNNING) {
mTask.cancel(true);
}
}
private void setupViews() {
mContainer = (ViewGroup) findViewById(R.id.container_photo);
mSwitcher = (ViewAnimator) findViewById(R.id.switcher_menu);
mPhotoView = (ImageView) findViewById(R.id.image_photo);
mPhotoTitle = (TextView) findViewById(R.id.caption_title);
mPhotoDate = (TextView) findViewById(R.id.caption_date);
findViewById(R.id.menu_back).setOnClickListener(this);
findViewById(R.id.menu_set).setOnClickListener(this);
mPhotoTitle.setText(mPhoto.getTitle());
mPhotoDate.setText(mPhoto.getDate());
mContainer.setVisibility(View.INVISIBLE);
// Sets up a view tree observer. The photo will be scaled using the size
// of one of our views so we must wait for the first layout pass to be
// done to make sure we have the correct size.
mContainer.getViewTreeObserver().addOnGlobalLayoutListener(this);
}
/**
* Loads the photo after the first layout. The photo is scaled using the
* dimension of the ImageView that will ultimately contain the photo's
* bitmap. We make sure that the ImageView is laid out at least once to
* get its correct size.
*/
public void onGlobalLayout() {
mContainer.getViewTreeObserver().removeGlobalOnLayoutListener(this);
loadPhoto(mPhotoView.getMeasuredWidth(), mPhotoView.getMeasuredHeight());
}
/**
* Loads the photo either from the last known instance or from the network.
* Loading it from the last known instance allows for fast display rotation
* without having to download the photo from the network again.
*
* @param width The desired maximum width of the photo.
* @param height The desired maximum height of the photo.
*/
private void loadPhoto(int width, int height) {
final Object data = getLastNonConfigurationInstance();
if (data == null) {
mTask = new LoadPhotoTask().execute(mPhoto, width, height);
} else {
mPhotoView.setImageBitmap((Bitmap) data);
mSwitcher.showNext();
}
}
/**
* Loads the {@link com.google.android.photostream.Flickr.Photo} to display
* from the intent used to start the activity.
*
* @return The photo to display, or null if the photo cannot be found.
*/
public Flickr.Photo getPhoto() {
final Intent intent = getIntent();
final Bundle extras = intent.getExtras();
Flickr.Photo photo = null;
if (extras != null) {
photo = extras.getParcelable(EXTRA_PHOTO);
}
return photo;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.view_photo, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_item_radar:
onShowRadar();
break;
}
return super.onMenuItemSelected(featureId, item);
}
private void onShowRadar() {
new ShowRadarTask().execute(mPhoto);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.menu_back:
onBack();
break;
case R.id.menu_set:
onSet();
break;
}
}
private void onSet() {
mTask = new CropWallpaperTask().execute(mPhoto);
}
private void onBack() {
finish();
}
/**
* If we successfully loaded a photo, send it to our future self to allow
* for fast display rotation. By doing so, we avoid reloading the photo
* from the network when the activity is taken down and recreated upon
* display rotation.
*
* @return The Bitmap displayed in the ImageView, or null if the photo
* wasn't loaded.
*/
@Override
public Object onRetainNonConfigurationInstance() {
final Drawable d = mPhotoView.getDrawable();
return d != null ? ((BitmapDrawable) d).getBitmap() : null;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// Spawns a new task to set the wallpaper in a background thread when/if
// we receive a successful result from the image cropper.
if (requestCode == REQUEST_CROP_IMAGE) {
if (resultCode == RESULT_OK) {
mTask = new SetWallpaperTask().execute();
} else {
cleanupWallpaper();
showWallpaperError();
}
}
}
private void showWallpaperError() {
Toast.makeText(ViewPhotoActivity.this, R.string.error_cannot_save_file,
Toast.LENGTH_SHORT).show();
}
private void showWallpaperSuccess() {
Toast.makeText(ViewPhotoActivity.this, R.string.success_wallpaper_set,
Toast.LENGTH_SHORT).show();
}
private void cleanupWallpaper() {
deleteFile(WALLPAPER_FILE_NAME);
mSwitcher.showNext();
}
/**
* Background task to load the photo from Flickr. The task loads the bitmap,
* then scale it to the appropriate dimension. The task ends by readjusting
* the activity's layout so that everything aligns correctly.
*/
private class LoadPhotoTask extends UserTask<Object, Void, Bitmap> {
public Bitmap doInBackground(Object... params) {
Bitmap bitmap = ((Flickr.Photo) params[0]).loadPhotoBitmap(Flickr.PhotoSize.MEDIUM);
if (bitmap == null) {
bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.not_found);
}
final int width = (Integer) params[1];
final int height = (Integer) params[2];
final Bitmap framed = ImageUtilities.scaleAndFrame(bitmap, width, height);
bitmap.recycle();
return framed;
}
@Override
public void onPostExecute(Bitmap result) {
mPhotoView.setImageBitmap(result);
// Find by how many pixels the title and date must be shifted on the
// horizontal axis to be left aligned with the photo
final int offsetX = (mPhotoView.getMeasuredWidth() - result.getWidth()) / 2;
// Forces the ImageView to have the same size as its embedded bitmap
// This will remove the empty space between the title/date pair and
// the photo itself
LinearLayout.LayoutParams params;
params = (LinearLayout.LayoutParams) mPhotoView.getLayoutParams();
params.height = result.getHeight();
params.weight = 0.0f;
mPhotoView.setLayoutParams(params);
params = (LinearLayout.LayoutParams) mPhotoTitle.getLayoutParams();
params.leftMargin = offsetX;
mPhotoTitle.setLayoutParams(params);
params = (LinearLayout.LayoutParams) mPhotoDate.getLayoutParams();
params.leftMargin = offsetX;
mPhotoDate.setLayoutParams(params);
mSwitcher.showNext();
mContainer.startAnimation(AnimationUtils.loadAnimation(ViewPhotoActivity.this,
R.anim.fade_in));
mContainer.setVisibility(View.VISIBLE);
mTask = null;
}
}
/**
* Background task to crop a large version of the image. The cropped result will
* be set as a wallpaper. The tasks sarts by showing the progress bar, then
* downloads the large version of hthe photo into a temporary file and ends by
* sending an intent to the Camera application to crop the image.
*/
private class CropWallpaperTask extends UserTask<Flickr.Photo, Void, Boolean> {
private File mFile;
private Uri _captureUri;
private boolean startCrop;
// this is something to keep our information
class CropOption
{
CharSequence TITLE;
Drawable ICON;
Intent CROP_APP;
}
// we will present the available selection in a list dialog, so we need an adapter
class CropOptionAdapter extends ArrayAdapter<CropOption>
{
private List<CropOption> _items;
private Context _ctx;
CropOptionAdapter(Context ctx, List<CropOption> items)
{
super(ctx, R.layout.crop_option, items);
_items = items;
_ctx = ctx;
}
@Override
public View getView( int position, View convertView, ViewGroup parent )
{
if ( convertView == null )
convertView = LayoutInflater.from( _ctx ).inflate( R.layout.crop_option, null );
CropOption item = _items.get( position );
if ( item != null )
{
( ( ImageView ) convertView.findViewById( R.id.crop_icon ) ).setImageDrawable( item.ICON );
( ( TextView ) convertView.findViewById( R.id.crop_name ) ).setText( item.TITLE );
return convertView;
}
return null;
}
}
@Override
public void onPreExecute() {
mFile = getFileStreamPath(WALLPAPER_FILE_NAME);
mSwitcher.showNext();
}
public Boolean doInBackground(Flickr.Photo... params) {
boolean success = false;
OutputStream out = null;
try {
out = openFileOutput(mFile.getName(), MODE_WORLD_READABLE | MODE_WORLD_WRITEABLE);
Flickr.get().downloadPhoto(params[0], Flickr.PhotoSize.LARGE, out);
success = true;
} catch (FileNotFoundException e) {
android.util.Log.e(Flickr.LOG_TAG, "Could not download photo", e);
success = false;
} catch (IOException e) {
android.util.Log.e(Flickr.LOG_TAG, "Could not download photo", e);
success = false;
} finally {
if (out != null) {
try {
out.close();
} catch (IOException e) {
success = false;
}
}
}
return success;
}
@Override
public void onPostExecute(Boolean result) {
if (!result) {
cleanupWallpaper();
showWallpaperError();
} else {
final int width = getWallpaperDesiredMinimumWidth();
final int height = getWallpaperDesiredMinimumHeight();
// Initilize the default
_captureUri = Uri.fromFile(mFile);
startCrop = false;
try
{
final List<CropOption> cropOptions = new ArrayList<CropOption>();
// this 2 lines are all you need to find the intent!!!
Intent intent = new Intent( "com.android.camera.action.CROP" );
intent.setType( "image/*" );
List<ResolveInfo> list = getPackageManager().queryIntentActivities( intent, 0 );
if ( list.size() == 0 )
{
// I tend to put any kind of text to be presented to the user as a resource for easier translation (if it ever comes to that...)
Toast.makeText(ViewPhotoActivity.this, getText( R.string.error_crop_option ), Toast.LENGTH_LONG ).show();
// this is the URI returned from the camera, it could be a file or a content URI, the crop app will take any
_captureUri = null; // leave the picture there
}
else
{
intent.setData( _captureUri );
intent.putExtra("outputX", width);
intent.putExtra("outputY", height);
intent.putExtra("aspectX", width);
intent.putExtra("aspectY", height);
intent.putExtra("scale", true);
intent.putExtra("noFaceDetection", true);
intent.putExtra("output", Uri.parse("file:/" + mFile.getAbsolutePath()));
//intent.putExtra( "", true ); // I seem to have lost the option to have the crop app auto rotate the image, any takers?
intent.putExtra( "return-data", false );
for ( ResolveInfo res : list )
{
final CropOption co = new CropOption();
co.TITLE = getPackageManager().getApplicationLabel( res.activityInfo.applicationInfo );
co.ICON = getPackageManager().getApplicationIcon( res.activityInfo.applicationInfo );
co.CROP_APP = new Intent( intent );
co.CROP_APP.setComponent( new ComponentName( res.activityInfo.packageName, res.activityInfo.name ) );
cropOptions.add( co );
}
// set up the chooser dialog
CropOptionAdapter adapter = new CropOptionAdapter( ViewPhotoActivity.this, cropOptions );
AlertDialog.Builder builder = new AlertDialog.Builder( ViewPhotoActivity.this );
builder.setTitle( R.string.choose_crop_title );
builder.setAdapter( adapter, new DialogInterface.OnClickListener() {
public void onClick( DialogInterface dialog, int item )
{
startCrop = true;
startActivityForResult( cropOptions.get( item ).CROP_APP, REQUEST_CROP_IMAGE);
}
} );
builder.setOnCancelListener( new DialogInterface.OnCancelListener() {
@Override
public void onCancel( DialogInterface dialog )
{
if (startCrop == true)
{
// we don't want to keep the capture around if we cancel the crop because
// we don't want it anymore
if ( _captureUri != null)
{
getContentResolver().delete( _captureUri, null, null );
_captureUri = null;
}
}
else
{
// User canceled the selection of a Crop Application
cleanupWallpaper();
showWallpaperError();
}
}
} );
AlertDialog alert = builder.create();
alert.show();
}
}
catch ( Exception e )
{
android.util.Log.e(Flickr.LOG_TAG, "processing capture", e );
}
}
mTask = null;
}
}
/**
* Background task to set the cropped image as the wallpaper. The task simply
* open the temporary file and sets it as the new wallpaper. The task ends by
* deleting the temporary file and display a message to the user.
*/
private class SetWallpaperTask extends UserTask<Void, Void, Boolean> {
public Boolean doInBackground(Void... params) {
boolean success = false;
InputStream in = null;
try {
in = openFileInput(WALLPAPER_FILE_NAME);
setWallpaper(in);
success = true;
} catch (IOException e) {
success = false;
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
success = false;
}
}
}
return success;
}
@Override
public void onPostExecute(Boolean result) {
cleanupWallpaper();
if (!result) {
showWallpaperError();
} else {
showWallpaperSuccess();
}
mTask = null;
}
}
private class ShowRadarTask extends UserTask<Flickr.Photo, Void, Flickr.Location> {
public Flickr.Location doInBackground(Flickr.Photo... params) {
return Flickr.get().getLocation(params[0]);
}
@Override
public void onPostExecute(Flickr.Location location) {
if (location != null) {
final Intent intent = new Intent(RADAR_ACTION);
intent.putExtra(RADAR_EXTRA_LATITUDE, location.getLatitude());
intent.putExtra(RADAR_EXTRA_LONGITUDE, location.getLongitude());
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(ViewPhotoActivity.this, R.string.error_cannot_find_radar,
Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(ViewPhotoActivity.this, R.string.error_cannot_find_location,
Toast.LENGTH_SHORT).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.photostream;
import android.os.Bundle;
import android.preference.PreferenceActivity;
import android.content.Context;
import android.content.Intent;
public class SettingsActivity extends PreferenceActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getPreferenceManager().setSharedPreferencesName(Preferences.NAME);
addPreferencesFromResource(R.xml.preferences);
}
/**
* Starts the PreferencesActivity for the specified user.
*
* @param context The application's environment.
*/
static void show(Context context) {
final Intent intent = new Intent(context, SettingsActivity.class);
context.startActivity(intent);
}
}
| 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.photostream;
import android.view.ViewGroup;
import android.view.View;
import android.view.animation.GridLayoutAnimationController;
import android.content.Context;
import android.content.res.TypedArray;
import android.util.AttributeSet;
/**
* A GridLayout positions its children in a static grid, defined by a fixed number of rows
* and columns. The size of the rows and columns is dynamically computed depending on the
* size of the GridLayout itself. As a result, GridLayout children's layout parameters
* are ignored.
*
* The number of rows and columns are specified in XML using the attributes android:numRows
* and android:numColumns.
*
* The GridLayout cannot be used when its size is unspecified.
*
* @attr ref com.google.android.photostream.R.styleable#GridLayout_numColumns
* @attr ref com.google.android.photostream.R.styleable#GridLayout_numRows
*/
public class GridLayout extends ViewGroup {
private int mNumColumns;
private int mNumRows;
private int mColumnWidth;
private int mRowHeight;
public GridLayout(Context context) {
this(context, null);
}
public GridLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public GridLayout(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.GridLayout, defStyle, 0);
mNumColumns = a.getInt(R.styleable.GridLayout_numColumns, 1);
mNumRows = a.getInt(R.styleable.GridLayout_numRows, 1);
a.recycle();
}
@Override
protected void attachLayoutAnimationParameters(View child,
ViewGroup.LayoutParams params, int index, int count) {
GridLayoutAnimationController.AnimationParameters animationParams =
(GridLayoutAnimationController.AnimationParameters)
params.layoutAnimationParameters;
if (animationParams == null) {
animationParams = new GridLayoutAnimationController.AnimationParameters();
params.layoutAnimationParameters = animationParams;
}
animationParams.count = count;
animationParams.index = index;
animationParams.columnsCount = mNumColumns;
animationParams.rowsCount = mNumRows;
animationParams.column = index % mNumColumns;
animationParams.row = index / mNumColumns;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
final int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
final int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec);
final int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
final int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec);
if (widthSpecMode == MeasureSpec.UNSPECIFIED || heightSpecMode == MeasureSpec.UNSPECIFIED) {
throw new RuntimeException("GridLayout cannot have UNSPECIFIED dimensions");
}
final int width = widthSpecSize - getPaddingLeft() - getPaddingRight();
final int height = heightSpecSize - getPaddingTop() - getPaddingBottom();
final int columnWidth = mColumnWidth = width / mNumColumns;
final int rowHeight = mRowHeight = height / mNumRows;
final int count = getChildCount();
for (int i = 0; i < count; i++) {
final View child = getChildAt(i);
int childWidthSpec = MeasureSpec.makeMeasureSpec(columnWidth, MeasureSpec.EXACTLY);
int childheightSpec = MeasureSpec.makeMeasureSpec(rowHeight, MeasureSpec.EXACTLY);
child.measure(childWidthSpec, childheightSpec);
}
setMeasuredDimension(widthSpecSize, heightSpecSize);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
final int columns = mNumColumns;
final int paddingLeft = getPaddingLeft();
final int paddingTop = getPaddingTop();
final int columnWidth = mColumnWidth;
final int rowHeight = mRowHeight;
final int count = getChildCount();
for (int i = 0; i < count; i++) {
View child = getChildAt(i);
if (child.getVisibility() != GONE) {
final int column = i % columns;
final int row = i / columns;
int childLeft = paddingLeft + column * columnWidth;
int childTop = paddingTop + row * rowHeight;
child.layout(childLeft, childTop, childLeft + child.getMeasuredWidth(),
childTop + child.getMeasuredHeight());
}
}
}
}
| 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.photostream;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteDatabase;
import android.content.Context;
import android.content.ContentValues;
import android.util.Log;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.provider.BaseColumns;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
/**
* Helper class to interact with the database that stores the Flickr contacts.
*/
class UserDatabase extends SQLiteOpenHelper implements BaseColumns {
private static final String DATABASE_NAME = "flickr";
private static final int DATABASE_VERSION = 1;
static final String TABLE_USERS = "users";
static final String COLUMN_USERNAME = "username";
static final String COLUMN_REALNAME = "realname";
static final String COLUMN_NSID = "nsid";
static final String COLUMN_BUDDY_ICON = "buddy_icon";
static final String COLUMN_LAST_UPDATE = "last_update";
static final String SORT_DEFAULT = COLUMN_USERNAME + " ASC";
private Context mContext;
UserDatabase(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
mContext = context;
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL("CREATE TABLE users ("
+ "_id INTEGER PRIMARY KEY, "
+ "username TEXT, "
+ "realname TEXT, "
+ "nsid TEXT, "
+ "buddy_icon BLOB,"
+ "last_update INTEGER);");
addUser(db, "Bob Lee", "Bob Lee", "45701389@N00", R.drawable.boblee_buddyicon);
addUser(db, "ericktseng", "Erick Tseng", "76701017@N00", R.drawable.ericktseng_buddyicon);
addUser(db, "romainguy", "Romain Guy", "24046097@N00", R.drawable.romainguy_buddyicon);
}
private void addUser(SQLiteDatabase db, String userName, String realName,
String nsid, int icon) {
final ContentValues values = new ContentValues();
values.put(COLUMN_USERNAME, userName);
values.put(COLUMN_REALNAME, realName);
values.put(COLUMN_NSID, nsid);
values.put(COLUMN_LAST_UPDATE, System.currentTimeMillis());
final Bitmap bitmap = BitmapFactory.decodeResource(mContext.getResources(), icon);
writeBitmap(values, COLUMN_BUDDY_ICON, bitmap);
db.insert(TABLE_USERS, COLUMN_LAST_UPDATE, values);
}
static void writeBitmap(ContentValues values, String name, Bitmap bitmap) {
if (bitmap != null) {
// Try go guesstimate how much space the icon will take when serialized
// to avoid unnecessary allocations/copies during the write.
int size = bitmap.getWidth() * bitmap.getHeight() * 2;
ByteArrayOutputStream out = new ByteArrayOutputStream(size);
try {
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
values.put(name, out.toByteArray());
} catch (IOException e) {
// Ignore
}
}
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
Log.w(Flickr.LOG_TAG, "Upgrading database from version " + oldVersion + " to " +
newVersion + ", which will destroy all old data");
db.execSQL("DROP TABLE IF EXISTS users");
onCreate(db);
}
}
| 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.photostream;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import java.io.IOException;
import java.io.BufferedReader;
import java.io.Closeable;
import java.io.InputStreamReader;
/**
* 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 {
private static final String PREFERENCE_EULA_ACCEPTED = "eula.accepted";
private 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);
if (!preferences.getBoolean(PREFERENCE_EULA_ACCEPTED, false)) {
final AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setTitle(R.string.eula_title);
builder.setCancelable(true);
builder.setPositiveButton(R.string.eula_accept, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
accept(preferences);
}
});
builder.setNegativeButton(R.string.eula_refuse, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
refuse(activity);
}
});
builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
public void onCancel(DialogInterface dialog) {
refuse(activity);
}
});
// UNCOMMENT TO ENABLE EULA
//builder.setMessage(readFile(activity, R.raw.eula));
builder.create().show();
}
}
private static void accept(SharedPreferences preferences) {
preferences.edit().putBoolean(PREFERENCE_EULA_ACCEPTED, true).commit();
}
private static void refuse(Activity activity) {
activity.finish();
}
static void showDisclaimer(Activity activity) {
final AlertDialog.Builder builder = new AlertDialog.Builder(activity);
builder.setMessage(readFile(activity, R.raw.disclaimer));
builder.setCancelable(true);
builder.setTitle(R.string.disclaimer_title);
builder.setPositiveButton(R.string.disclaimer_accept, null);
builder.create().show();
}
private static CharSequence readFile(Activity activity, int id) {
BufferedReader in = null;
try {
in = new BufferedReader(new InputStreamReader(
activity.getResources().openRawResource(id)));
String line;
StringBuilder buffer = new StringBuilder();
while ((line = in.readLine()) != null) buffer.append(line).append('\n');
return buffer;
} catch (IOException e) {
return "";
} finally {
closeStream(in);
}
}
/**
* Closes the specified stream.
*
* @param stream The stream to close.
*/
private static void closeStream(Closeable stream) {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
// Ignore
}
}
}
}
| 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.photostream;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.LayoutInflater;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.Menu;
import android.view.KeyEvent;
import android.view.animation.AnimationUtils;
import android.view.animation.Animation;
import android.widget.TextView;
import android.widget.ListView;
import android.widget.CursorAdapter;
import android.widget.AdapterView;
import android.widget.ProgressBar;
import android.content.Intent;
import android.content.Context;
import android.content.ContentValues;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import java.util.HashMap;
/**
* Activity used to login the user. The activity asks for the user name and then add
* the user to the users list upong successful login. If the login is unsuccessful,
* an error message is displayed. Clicking any stored user launches PhotostreamActivity.
*
* This activity is also used to create Home shortcuts. When the intent
* {@link Intent#ACTION_CREATE_SHORTCUT} is used to start this activity, sucessful login
* returns a shortcut Intent to Home instead of proceeding to PhotostreamActivity.
*
* The shortcut Intent contains the real name of the user, his buddy icon, the action
* {@link android.content.Intent#ACTION_VIEW} and the URI flickr://photos/nsid.
*/
public class LoginActivity extends Activity implements View.OnKeyListener,
AdapterView.OnItemClickListener {
private static final int MENU_ID_SHOW = 1;
private static final int MENU_ID_DELETE = 2;
private boolean mCreateShortcut;
private TextView mUsername;
private ProgressBar mProgress;
private SQLiteDatabase mDatabase;
private UsersAdapter mAdapter;
private UserTask<String, Void, Flickr.User> mTask;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
schedule();
// If the activity was started with the "create shortcut" action, we
// remember this to change the behavior upon successful login
if (Intent.ACTION_CREATE_SHORTCUT.equals(getIntent().getAction())) {
mCreateShortcut = true;
}
mDatabase = new UserDatabase(this).getWritableDatabase();
setContentView(R.layout.screen_login);
setupViews();
}
private void schedule() {
//SharedPreferences preferences = getSharedPreferences(Preferences.NAME, MODE_PRIVATE);
//if (!preferences.getBoolean(Preferences.KEY_ALARM_SCHEDULED, false)) {
CheckUpdateService.schedule(this);
// preferences.edit().putBoolean(Preferences.KEY_ALARM_SCHEDULED, true).commit();
//}
}
private void setupViews() {
mUsername = (TextView) findViewById(R.id.input_username);
mUsername.setOnKeyListener(this);
mUsername.requestFocus();
mAdapter = new UsersAdapter(this, initializeCursor());
final ListView userList = (ListView) findViewById(R.id.list_users);
userList.setAdapter(mAdapter);
userList.setOnItemClickListener(this);
registerForContextMenu(userList);
mProgress = (ProgressBar) findViewById(R.id.progress);
}
private Cursor initializeCursor() {
Cursor cursor = mDatabase.query(UserDatabase.TABLE_USERS,
new String[] { UserDatabase._ID, UserDatabase.COLUMN_REALNAME,
UserDatabase.COLUMN_NSID, UserDatabase.COLUMN_BUDDY_ICON },
null, null, null, null, UserDatabase.SORT_DEFAULT);
startManagingCursor(cursor);
return cursor;
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.login, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_item_settings:
SettingsActivity.show(this);
return true;
case R.id.menu_item_info:
Eula.showDisclaimer(this);
return true;
}
return super.onMenuItemSelected(featureId, item);
}
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_UP) {
switch (v.getId()) {
case R.id.input_username:
if (keyCode == KeyEvent.KEYCODE_ENTER ||
keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
onAddUser(mUsername.getText().toString());
return true;
}
break;
}
}
return false;
}
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
final Flickr.User user = Flickr.User.fromId(((UserDescription) view.getTag()).nsid);
if (!mCreateShortcut) {
onShowPhotostream(user);
} else {
onCreateShortcut(user);
}
}
@Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
menu.setHeaderTitle(((TextView) info.targetView).getText());
menu.add(0, MENU_ID_SHOW, 0, R.string.context_menu_show_photostream);
menu.add(0, MENU_ID_DELETE, 0, R.string.context_menu_delete_user);
}
@Override
public boolean onContextItemSelected(MenuItem item) {
final AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo)
item.getMenuInfo();
final UserDescription description = (UserDescription) info.targetView.getTag();
switch (item.getItemId()) {
case MENU_ID_SHOW:
final Flickr.User user = Flickr.User.fromId(description.nsid);
onShowPhotostream(user);
return true;
case MENU_ID_DELETE:
onRemoveUser(description.id);
return true;
}
return super.onContextItemSelected(item);
}
@Override
protected void onResume() {
super.onResume();
if (mProgress.getVisibility() == View.VISIBLE) {
mProgress.setVisibility(View.GONE);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mTask != null && mTask.getStatus() == UserTask.Status.RUNNING) {
mTask.cancel(true);
}
mAdapter.cleanup();
mDatabase.close();
}
private void onAddUser(String username) {
// When the user enters his user name, we need to find his NSID before
// adding it to the list.
mTask = new FindUserTask().execute(username);
}
private void onRemoveUser(String id) {
int rows = mDatabase.delete(UserDatabase.TABLE_USERS, UserDatabase._ID + "=?",
new String[] { id });
if (rows > 0) {
mAdapter.refresh();
}
}
private void onError() {
hideProgress();
mUsername.setError(getString(R.string.screen_login_error));
}
private void hideProgress() {
if (mProgress.getVisibility() != View.GONE) {
final Animation fadeOut = AnimationUtils.loadAnimation(this, R.anim.fade_out);
mProgress.setVisibility(View.GONE);
mProgress.startAnimation(fadeOut);
}
}
private void showProgress() {
if (mProgress.getVisibility() != View.VISIBLE) {
final Animation fadeIn = AnimationUtils.loadAnimation(this, R.anim.fade_in);
mProgress.setVisibility(View.VISIBLE);
mProgress.startAnimation(fadeIn);
}
}
private void onShowPhotostream(Flickr.User user) {
PhotostreamActivity.show(this, user);
}
/**
* Creates the shortcut Intent to send back to Home. The intent is a view action
* to a flickr://photos/nsid URI, with a title (real name or user name) and a
* custom icon (the user's buddy icon.)
*
* @param user The user to create a shortcut for.
*/
private void onCreateShortcut(Flickr.User user) {
final Cursor cursor = mDatabase.query(UserDatabase.TABLE_USERS,
new String[] { UserDatabase.COLUMN_REALNAME, UserDatabase.COLUMN_USERNAME,
UserDatabase.COLUMN_BUDDY_ICON }, UserDatabase.COLUMN_NSID + "=?",
new String[] { user.getId() }, null, null, UserDatabase.SORT_DEFAULT);
cursor.moveToFirst();
final Intent shortcutIntent = new Intent(PhotostreamActivity.ACTION);
shortcutIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
shortcutIntent.putExtra(PhotostreamActivity.EXTRA_NSID, user.getId());
// Sets the custom shortcut's title to the real name of the user. If no
// real name was found, use the user name instead.
final Intent intent = new Intent();
intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, shortcutIntent);
String name = cursor.getString(cursor.getColumnIndexOrThrow(UserDatabase.COLUMN_REALNAME));
if (name == null || name.length() == 0) {
name = cursor.getString(cursor.getColumnIndexOrThrow(UserDatabase.COLUMN_USERNAME));
}
intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, name);
// Sets the custom shortcut icon to the user's buddy icon. If no buddy
// icon was found, use a default local buddy icon instead.
byte[] data = cursor.getBlob(cursor.getColumnIndexOrThrow(UserDatabase.COLUMN_BUDDY_ICON));
Bitmap icon = BitmapFactory.decodeByteArray(data, 0, data.length);
if (icon != null) {
intent.putExtra(Intent.EXTRA_SHORTCUT_ICON, icon);
} else {
intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE,
Intent.ShortcutIconResource.fromContext(this, R.drawable.default_buddyicon));
}
setResult(RESULT_OK, intent);
finish();
}
/**
* Background task used to load the user's NSID. The task begins by showing the
* progress bar, then loads the user NSID from the network and finally open
* PhotostreamActivity.
*/
private class FindUserTask extends UserTask<String, Void, Flickr.User> {
@Override
public void onPreExecute() {
showProgress();
}
public Flickr.User doInBackground(String... params) {
final String name = params[0].trim();
if (name.length() == 0) return null;
final Flickr.User user = Flickr.get().findByUserName(name);
if (isCancelled() || user == null) return null;
Flickr.UserInfo info = Flickr.get().getUserInfo(user);
if (isCancelled() || info == null) return null;
String realname = info.getRealName();
if (realname == null) realname = name;
final ContentValues values = new ContentValues();
values.put(UserDatabase.COLUMN_USERNAME, name);
values.put(UserDatabase.COLUMN_REALNAME, realname);
values.put(UserDatabase.COLUMN_NSID, user.getId());
values.put(UserDatabase.COLUMN_LAST_UPDATE, System.currentTimeMillis());
UserDatabase.writeBitmap(values, UserDatabase.COLUMN_BUDDY_ICON,
info.loadBuddyIcon());
long result = -1;
if (!isCancelled()) {
result = mDatabase.insert(UserDatabase.TABLE_USERS,
UserDatabase.COLUMN_REALNAME, values);
}
return result != -1 ? user : null;
}
@Override
public void onPostExecute(Flickr.User user) {
if (user == null) {
onError();
} else {
mAdapter.refresh();
hideProgress();
}
}
}
private class UsersAdapter extends CursorAdapter {
private final LayoutInflater mInflater;
private final int mRealname;
private final int mId;
private final int mNsid;
private final int mBuddyIcon;
private final Drawable mDefaultIcon;
private final HashMap<String, Drawable> mIcons = new HashMap<String, Drawable>();
public UsersAdapter(Context context, Cursor cursor) {
super(context, cursor, true);
mInflater = LayoutInflater.from(context);
mDefaultIcon = context.getResources().getDrawable(R.drawable.default_buddyicon);
mRealname = cursor.getColumnIndexOrThrow(UserDatabase.COLUMN_REALNAME);
mId = cursor.getColumnIndexOrThrow(UserDatabase._ID);
mNsid = cursor.getColumnIndexOrThrow(UserDatabase.COLUMN_NSID);
mBuddyIcon = cursor.getColumnIndexOrThrow(UserDatabase.COLUMN_BUDDY_ICON);
}
public View newView(Context context, Cursor cursor, ViewGroup parent) {
final View view = mInflater.inflate(R.layout.list_item_user, parent, false);
final UserDescription description = new UserDescription();
view.setTag(description);
return view;
}
public void bindView(View view, Context context, Cursor cursor) {
final UserDescription description = (UserDescription) view.getTag();
description.id = cursor.getString(mId);
description.nsid = cursor.getString(mNsid);
final TextView textView = (TextView) view;
textView.setText(cursor.getString(mRealname));
Drawable icon = mIcons.get(description.nsid);
if (icon == null) {
final byte[] data = cursor.getBlob(mBuddyIcon);
Bitmap bitmap = null;
if (data != null) bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
if (bitmap != null) {
icon = new FastBitmapDrawable(bitmap);
} else {
icon = mDefaultIcon;
}
mIcons.put(description.nsid, icon);
}
textView.setCompoundDrawablesWithIntrinsicBounds(icon, null, null, null);
}
void cleanup() {
for (Drawable icon : mIcons.values()) {
icon.setCallback(null);
}
}
void refresh() {
getCursor().requery();
}
}
private static class UserDescription {
String id;
String nsid;
}
}
| 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.photostream;
final class Preferences {
static final String NAME = "Photostream";
static final String KEY_ALARM_SCHEDULED = "photostream.scheduled";
static final String KEY_ENABLE_NOTIFICATIONS = "photostream.enable-notifications";
static final String KEY_VIBRATE = "photostream.vibrate";
static final String KEY_RINGTONE = "photostream.ringtone";
Preferences() {
}
}
| 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.photostream;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import java.util.Random;
/**
* This class contains various utilities to manipulate Bitmaps. The methods of this class,
* although static, are not thread safe and cannot be invoked by several threads at the
* same time. Synchronization is required by the caller.
*/
final class ImageUtilities {
private static final float PHOTO_BORDER_WIDTH = 3.0f;
private static final int PHOTO_BORDER_COLOR = 0xffffffff;
private static final float ROTATION_ANGLE_MIN = 2.5f;
private static final float ROTATION_ANGLE_EXTRA = 5.5f;
private static final Random sRandom = new Random();
private static final Paint sPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.FILTER_BITMAP_FLAG);
private static final Paint sStrokePaint = new Paint(Paint.ANTI_ALIAS_FLAG);
static {
sStrokePaint.setStrokeWidth(PHOTO_BORDER_WIDTH);
sStrokePaint.setStyle(Paint.Style.STROKE);
sStrokePaint.setColor(PHOTO_BORDER_COLOR);
}
/**
* Rotate specified Bitmap by a random angle. The angle is either negative or positive,
* and ranges, in degrees, from 2.5 to 8. After rotation a frame is overlaid on top
* of the rotated image.
*
* This method is not thread safe.
*
* @param bitmap The Bitmap to rotate and apply a frame onto.
*
* @return A new Bitmap whose dimension are different from the original bitmap.
*/
static Bitmap rotateAndFrame(Bitmap bitmap) {
final boolean positive = sRandom.nextFloat() >= 0.5f;
final float angle = (ROTATION_ANGLE_MIN + sRandom.nextFloat() * ROTATION_ANGLE_EXTRA) *
(positive ? 1.0f : -1.0f);
final double radAngle = Math.toRadians(angle);
final int bitmapWidth = bitmap.getWidth();
final int bitmapHeight = bitmap.getHeight();
final double cosAngle = Math.abs(Math.cos(radAngle));
final double sinAngle = Math.abs(Math.sin(radAngle));
final int strokedWidth = (int) (bitmapWidth + 2 * PHOTO_BORDER_WIDTH);
final int strokedHeight = (int) (bitmapHeight + 2 * PHOTO_BORDER_WIDTH);
final int width = (int) (strokedHeight * sinAngle + strokedWidth * cosAngle);
final int height = (int) (strokedWidth * sinAngle + strokedHeight * cosAngle);
final float x = (width - bitmapWidth) / 2.0f;
final float y = (height - bitmapHeight) / 2.0f;
final Bitmap decored = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
final Canvas canvas = new Canvas(decored);
canvas.rotate(angle, width / 2.0f, height / 2.0f);
canvas.drawBitmap(bitmap, x, y, sPaint);
canvas.drawRect(x, y, x + bitmapWidth, y + bitmapHeight, sStrokePaint);
return decored;
}
/**
* Scales the specified Bitmap to fit within the specified dimensions. After scaling,
* a frame is overlaid on top of the scaled image.
*
* This method is not thread safe.
*
* @param bitmap The Bitmap to scale to fit the specified dimensions and to apply
* a frame onto.
* @param width The maximum width of the new Bitmap.
* @param height The maximum height of the new Bitmap.
*
* @return A scaled version of the original bitmap, whose dimension are less than or
* equal to the specified width and height.
*/
static Bitmap scaleAndFrame(Bitmap bitmap, int width, int height) {
final int bitmapWidth = bitmap.getWidth();
final int bitmapHeight = bitmap.getHeight();
final float scale = Math.min((float) width / (float) bitmapWidth,
(float) height / (float) bitmapHeight);
final int scaledWidth = (int) (bitmapWidth * scale);
final int scaledHeight = (int) (bitmapHeight * scale);
final Bitmap decored = Bitmap.createScaledBitmap(bitmap, scaledWidth, scaledHeight, true);
final Canvas canvas = new Canvas(decored);
final int offset = (int) (PHOTO_BORDER_WIDTH / 2);
sStrokePaint.setAntiAlias(false);
canvas.drawRect(offset, offset, scaledWidth - offset - 1,
scaledHeight - offset - 1, sStrokePaint);
sStrokePaint.setAntiAlias(true);
return decored;
}
}
| 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.photostream;
import android.app.Service;
import android.app.NotificationManager;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.AlarmManager;
import android.os.IBinder;
import android.os.SystemClock;
import android.content.Intent;
import android.content.Context;
import android.content.ContentValues;
import android.content.SharedPreferences;
import android.database.sqlite.SQLiteDatabase;
import android.database.Cursor;
import android.net.Uri;
import android.text.TextUtils;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;
/**
* CheckUpdateService checks every 24 hours if updates have been made to the photostreams
* of the current contacts. This service simply polls an RSS feed and compares the
* modification timestamp with the one stored in the database.
*/
public class CheckUpdateService extends Service {
private static boolean DEBUG = false;
// Check interval: every 24 hours
private static long UPDATES_CHECK_INTERVAL = 24 * 60 * 60 * 1000;
private CheckForUpdatesTask mTask;
@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
(mTask = new CheckForUpdatesTask()).execute();
}
@Override
public void onDestroy() {
super.onDestroy();
if (mTask != null && mTask.getStatus() == UserTask.Status.RUNNING) {
mTask.cancel(true);
}
}
public IBinder onBind(Intent intent) {
return null;
}
static void schedule(Context context) {
final Intent intent = new Intent(context, CheckUpdateService.class);
final PendingIntent pending = PendingIntent.getService(context, 0, intent, 0);
Calendar c = new GregorianCalendar();
c.add(Calendar.DAY_OF_YEAR, 1);
c.set(Calendar.HOUR_OF_DAY, 0);
c.set(Calendar.MINUTE, 0);
c.set(Calendar.SECOND, 0);
c.set(Calendar.MILLISECOND, 0);
final AlarmManager alarm = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarm.cancel(pending);
if (DEBUG) {
alarm.setRepeating(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime(),
30 * 1000, pending);
} else {
alarm.setRepeating(AlarmManager.RTC, c.getTimeInMillis(),
UPDATES_CHECK_INTERVAL, pending);
}
}
private class CheckForUpdatesTask extends UserTask<Void, Object, Void> {
private SharedPreferences mPreferences;
private NotificationManager mManager;
@Override
public void onPreExecute() {
mPreferences = getSharedPreferences(Preferences.NAME, MODE_PRIVATE);
mManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
}
public Void doInBackground(Void... params) {
final UserDatabase helper = new UserDatabase(CheckUpdateService.this);
final SQLiteDatabase database = helper.getWritableDatabase();
Cursor cursor = null;
try {
cursor = database.query(UserDatabase.TABLE_USERS,
new String[] { UserDatabase._ID, UserDatabase.COLUMN_NSID,
UserDatabase.COLUMN_REALNAME, UserDatabase.COLUMN_LAST_UPDATE },
null, null, null, null, null);
int idIndex = cursor.getColumnIndexOrThrow(UserDatabase._ID);
int realNameIndex = cursor.getColumnIndexOrThrow(UserDatabase.COLUMN_REALNAME);
int nsidIndex = cursor.getColumnIndexOrThrow(UserDatabase.COLUMN_NSID);
int lastUpdateIndex = cursor.getColumnIndexOrThrow(UserDatabase.COLUMN_LAST_UPDATE);
final Flickr flickr = Flickr.get();
final Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
final Calendar reference = Calendar.getInstance();
while (!isCancelled() && cursor.moveToNext()) {
final String nsid = cursor.getString(nsidIndex);
calendar.setTimeInMillis(cursor.getLong(lastUpdateIndex));
reference.set(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH),
calendar.get(Calendar.DAY_OF_MONTH), calendar.get(Calendar.HOUR_OF_DAY),
calendar.get(Calendar.MINUTE), calendar.get(Calendar.SECOND));
if (flickr.hasUpdates(Flickr.User.fromId(nsid), reference)) {
publishProgress(nsid, cursor.getString(realNameIndex),
cursor.getInt(idIndex));
}
}
final ContentValues values = new ContentValues();
values.put(UserDatabase.COLUMN_LAST_UPDATE, System.currentTimeMillis());
database.update(UserDatabase.TABLE_USERS, values, null, null);
} finally {
if (cursor != null) cursor.close();
database.close();
}
return null;
}
@Override
public void onProgressUpdate(Object... values) {
if (mPreferences.getBoolean(Preferences.KEY_ENABLE_NOTIFICATIONS, true)) {
final Integer id = (Integer) values[2];
final Intent intent = new Intent(PhotostreamActivity.ACTION);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra(PhotostreamActivity.EXTRA_NOTIFICATION, id);
intent.putExtra(PhotostreamActivity.EXTRA_NSID, values[0].toString());
Notification notification = new Notification(R.drawable.stat_notify,
getString(R.string.notification_new_photos, values[1]),
System.currentTimeMillis());
notification.setLatestEventInfo(CheckUpdateService.this,
getString(R.string.notification_title),
getString(R.string.notification_contact_has_new_photos, values[1]),
PendingIntent.getActivity(CheckUpdateService.this, 0, intent,
PendingIntent.FLAG_CANCEL_CURRENT));
if (mPreferences.getBoolean(Preferences.KEY_VIBRATE, false)) {
notification.defaults |= Notification.DEFAULT_VIBRATE;
}
String ringtoneUri = mPreferences.getString(Preferences.KEY_RINGTONE, null);
notification.sound = TextUtils.isEmpty(ringtoneUri) ? null : Uri.parse(ringtoneUri);
mManager.notify(id, notification);
}
}
@Override
public void onPostExecute(Void aVoid) {
stopSelf();
}
}
}
| 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.photostream;
import android.graphics.drawable.Drawable;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.ColorFilter;
class FastBitmapDrawable extends Drawable {
private Bitmap mBitmap;
FastBitmapDrawable(Bitmap b) {
mBitmap = b;
}
@Override
public void draw(Canvas canvas) {
canvas.drawBitmap(mBitmap, 0.0f, 0.0f, null);
}
@Override
public int getOpacity() {
return PixelFormat.TRANSLUCENT;
}
@Override
public void setAlpha(int alpha) {
}
@Override
public void setColorFilter(ColorFilter cf) {
}
@Override
public int getIntrinsicWidth() {
return mBitmap.getWidth();
}
@Override
public int getIntrinsicHeight() {
return mBitmap.getHeight();
}
@Override
public int getMinimumWidth() {
return mBitmap.getWidth();
}
@Override
public int getMinimumHeight() {
return mBitmap.getHeight();
}
public Bitmap getBitmap() {
return mBitmap;
}
} | Java |
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.clc.bt;
import java.util.Arrays;
import java.util.List;
/**
* Model of a "ball" object used by the demo app.
*/
public class Demo_Ball {
public enum BOUNCE_TYPE {
TOPLEFT, TOP, TOPRIGHT, LEFT, RIGHT, BOTTOMLEFT, BOTTOM, BOTTOMRIGHT
}
private final float radius = 20;
private final float pxPerM = 2; // Let 2 pixels represent 1 meter
private final float reboundEnergyFactor = 0.6f; // Amount of energy returned
// when rebounding
private float xPos = 160;
private float yPos = 240;
private float xMax = 320;
private float yMax = 410;
private float xAcceleration = 0;
private float yAcceleration = 0;
private float xVelocity = 0;
private float yVelocity = 0;
private float reboundXPos = 0;
private float reboundYPos = 0;
private float reboundXVelocity = 0;
private float reboundYVelocity = 0;
private long lastUpdate;
private boolean onScreen;
public Demo_Ball(boolean visible) {
onScreen = visible;
lastUpdate = System.currentTimeMillis();
}
public Demo_Ball(boolean visible, int screenSizeX, int screenSizeY) {
onScreen = visible;
lastUpdate = System.currentTimeMillis();
xMax = screenSizeX;
yMax = screenSizeY;
}
public float getRadius() {
return radius;
}
public float getXVelocity() {
return xVelocity;
}
public float getX() {
if (!onScreen) {
return -1;
}
return xPos;
}
public float getY() {
if (!onScreen) {
return -1;
}
return yPos;
}
public void putOnScreen(float x, float y, float ax, float ay, float vx, float vy,
int startingSide) {
xPos = x;
yPos = y;
xVelocity = vx;
yVelocity = vy;
xAcceleration = ax;
yAcceleration = ay;
lastUpdate = System.currentTimeMillis();
if (startingSide == Demo_Multiscreen.RIGHT) {
xPos = xMax - radius - 2;
} else if (startingSide == Demo_Multiscreen.LEFT) {
xPos = radius + 2;
} else if (startingSide == Demo_Multiscreen.UP) {
yPos = radius + 2;
} else if (startingSide == Demo_Multiscreen.DOWN) {
yPos = yMax - radius - 2;
} else if (startingSide == AirHockey.FLIPTOP) {
yPos = radius + 2;
xPos = xMax - x;
if (xPos < 0){
xPos = 0;
}
yVelocity = -vy;
yAcceleration = -ay;
}
onScreen = true;
}
public void setAcceleration(float ax, float ay) {
if (!onScreen) {
return;
}
xAcceleration = ax;
yAcceleration = ay;
}
public boolean isOnScreen(){
return onScreen;
}
public int update() {
if (!onScreen) {
return 0;
}
long currentTime = System.currentTimeMillis();
long elapsed = currentTime - lastUpdate;
lastUpdate = currentTime;
xVelocity += ((elapsed * xAcceleration) / 1000) * pxPerM;
yVelocity += ((elapsed * yAcceleration) / 1000) * pxPerM;
xPos += ((xVelocity * elapsed) / 1000) * pxPerM;
yPos += ((yVelocity * elapsed) / 1000) * pxPerM;
// Handle rebounding
if (yPos - radius < 0) {
reboundXPos = xPos;
reboundYPos = radius;
reboundXVelocity = xVelocity;
reboundYVelocity = -yVelocity * reboundEnergyFactor;
onScreen = false;
return Demo_Multiscreen.UP;
} else if (yPos + radius > yMax) {
reboundXPos = xPos;
reboundYPos = yMax - radius;
reboundXVelocity = xVelocity;
reboundYVelocity = -yVelocity * reboundEnergyFactor;
onScreen = false;
return Demo_Multiscreen.DOWN;
}
if (xPos - radius < 0) {
reboundXPos = radius;
reboundYPos = yPos;
reboundXVelocity = -xVelocity * reboundEnergyFactor;
reboundYVelocity = yVelocity;
onScreen = false;
return Demo_Multiscreen.LEFT;
} else if (xPos + radius > xMax) {
reboundXPos = xMax - radius;
reboundYPos = yPos;
reboundXVelocity = -xVelocity * reboundEnergyFactor;
reboundYVelocity = yVelocity;
onScreen = false;
return Demo_Multiscreen.RIGHT;
}
return Demo_Multiscreen.CENTER;
}
public void doRebound() {
xPos = reboundXPos;
yPos = reboundYPos;
xVelocity = reboundXVelocity;
yVelocity = reboundYVelocity;
onScreen = true;
}
public String getState() {
String state = "";
state = xPos + "|" + yPos + "|" + xAcceleration + "|" + yAcceleration + "|" + xVelocity
+ "|" + yVelocity;
return state;
}
public void restoreState(String state) {
List<String> stateInfo = Arrays.asList(state.split("\\|"));
putOnScreen(Float.parseFloat(stateInfo.get(0)), Float.parseFloat(stateInfo.get(1)), Float
.parseFloat(stateInfo.get(2)), Float.parseFloat(stateInfo.get(3)), Float
.parseFloat(stateInfo.get(4)), Float.parseFloat(stateInfo.get(5)), Integer
.parseInt(stateInfo.get(6)));
}
public void doBounce(BOUNCE_TYPE bounceType, float vX, float vY){
switch (bounceType){
case TOPLEFT:
if (xVelocity > 0){
xVelocity = -xVelocity * reboundEnergyFactor;
}
if (yVelocity > 0){
yVelocity = -yVelocity * reboundEnergyFactor;
}
break;
case TOP:
if (yVelocity > 0){
yVelocity = -yVelocity * reboundEnergyFactor;
}
break;
case TOPRIGHT:
if (xVelocity < 0){
xVelocity = -xVelocity * reboundEnergyFactor;
}
if (yVelocity > 0){
yVelocity = -yVelocity * reboundEnergyFactor;
}
break;
case LEFT:
if (xVelocity > 0){
xVelocity = -xVelocity * reboundEnergyFactor;
}
break;
case RIGHT:
if (xVelocity < 0){
xVelocity = -xVelocity * reboundEnergyFactor;
}
break;
case BOTTOMLEFT:
if (xVelocity > 0){
xVelocity = -xVelocity * reboundEnergyFactor;
}
if (yVelocity < 0){
yVelocity = -yVelocity * reboundEnergyFactor;
}
break;
case BOTTOM:
if (yVelocity < 0){
yVelocity = -yVelocity * reboundEnergyFactor;
}
break;
case BOTTOMRIGHT:
if (xVelocity < 0){
xVelocity = -xVelocity * reboundEnergyFactor;
}
if (yVelocity < 0){
yVelocity = -yVelocity * reboundEnergyFactor;
}
break;
}
xVelocity = xVelocity + (vX * 500);
yVelocity = yVelocity + (vY * 150);
}
}
| Java |
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.clc.bt;
import net.clc.bt.IConnection;
import net.clc.bt.IConnectionCallback;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
/**
* API for the Bluetooth Click, Link, Compete library. This library simplifies
* the process of establishing Bluetooth connections and sending data in a way
* that is geared towards multi-player games.
*/
public class Connection {
public static final String TAG = "net.clc.bt.Connection";
public static final int SUCCESS = 0;
public static final int FAILURE = 1;
public static final int MAX_SUPPORTED = 7;
public interface OnConnectionServiceReadyListener {
public void OnConnectionServiceReady();
}
public interface OnIncomingConnectionListener {
public void OnIncomingConnection(String device);
}
public interface OnMaxConnectionsReachedListener {
public void OnMaxConnectionsReached();
}
public interface OnMessageReceivedListener {
public void OnMessageReceived(String device, String message);
}
public interface OnConnectionLostListener {
public void OnConnectionLost(String device);
}
private OnConnectionServiceReadyListener mOnConnectionServiceReadyListener;
private OnIncomingConnectionListener mOnIncomingConnectionListener;
private OnMaxConnectionsReachedListener mOnMaxConnectionsReachedListener;
private OnMessageReceivedListener mOnMessageReceivedListener;
private OnConnectionLostListener mOnConnectionLostListener;
private ServiceConnection mServiceConnection;
private Context mContext;
private String mPackageName = "";
private boolean mStarted = false;
private final Object mStartLock = new Object();
private IConnection mIconnection;
private IConnectionCallback mIccb = new IConnectionCallback.Stub() {
public void incomingConnection(String device) throws RemoteException {
if (mOnIncomingConnectionListener != null) {
mOnIncomingConnectionListener.OnIncomingConnection(device);
}
}
public void connectionLost(String device) throws RemoteException {
if (mOnConnectionLostListener != null) {
mOnConnectionLostListener.OnConnectionLost(device);
}
}
public void maxConnectionsReached() throws RemoteException {
if (mOnMaxConnectionsReachedListener != null) {
mOnMaxConnectionsReachedListener.OnMaxConnectionsReached();
}
}
public void messageReceived(String device, String message) throws RemoteException {
if (mOnMessageReceivedListener != null) {
mOnMessageReceivedListener.OnMessageReceived(device, message);
}
}
};
// TODO: Add a check to autodownload this service from Market if the user
// does not have it already.
public Connection(Context ctx, OnConnectionServiceReadyListener ocsrListener) {
mOnConnectionServiceReadyListener = ocsrListener;
mContext = ctx;
mPackageName = ctx.getPackageName();
mServiceConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName name, IBinder service) {
synchronized (mStartLock) {
mIconnection = IConnection.Stub.asInterface(service);
mStarted = true;
if (mOnConnectionServiceReadyListener != null) {
mOnConnectionServiceReadyListener.OnConnectionServiceReady();
}
}
}
public void onServiceDisconnected(ComponentName name) {
synchronized (mStartLock) {
try {
mStarted = false;
mIconnection.unregisterCallback(mPackageName);
mIconnection.shutdown(mPackageName);
} catch (RemoteException e) {
Log.e(TAG, "RemoteException in onServiceDisconnected", e);
}
mIconnection = null;
}
}
};
Intent intent = new Intent("com.google.intent.action.BT_ClickLinkCompete_SERVICE");
intent.addCategory("com.google.intent.category.BT_ClickLinkCompete");
mContext.bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
}
public int startServer(final int maxConnections, OnIncomingConnectionListener oicListener,
OnMaxConnectionsReachedListener omcrListener, OnMessageReceivedListener omrListener,
OnConnectionLostListener oclListener) {
if (!mStarted) {
return Connection.FAILURE;
}
if (maxConnections > MAX_SUPPORTED) {
Log.e(TAG, "The maximum number of allowed connections is " + MAX_SUPPORTED);
return Connection.FAILURE;
}
mOnIncomingConnectionListener = oicListener;
mOnMaxConnectionsReachedListener = omcrListener;
mOnMessageReceivedListener = omrListener;
mOnConnectionLostListener = oclListener;
try {
int result = mIconnection.startServer(mPackageName, maxConnections);
mIconnection.registerCallback(mPackageName, mIccb);
return result;
} catch (RemoteException e) {
Log.e(TAG, "RemoteException in startServer", e);
}
return Connection.FAILURE;
}
public int connect(String device, OnMessageReceivedListener omrListener,
OnConnectionLostListener oclListener) {
if (!mStarted) {
return Connection.FAILURE;
}
mOnMessageReceivedListener = omrListener;
mOnConnectionLostListener = oclListener;
try {
int result = mIconnection.connect(mPackageName, device);
mIconnection.registerCallback(mPackageName, mIccb);
return result;
} catch (RemoteException e) {
Log.e(TAG, "RemoteException in connect", e);
}
return Connection.FAILURE;
}
public int sendMessage(String device, String message) {
if (!mStarted) {
return Connection.FAILURE;
}
try {
return mIconnection.sendMessage(mPackageName, device, message);
} catch (RemoteException e) {
Log.e(TAG, "RemoteException in sendMessage", e);
}
return Connection.FAILURE;
}
public int broadcastMessage(String message) {
if (!mStarted) {
return Connection.FAILURE;
}
try {
return mIconnection.broadcastMessage(mPackageName, message);
} catch (RemoteException e) {
Log.e(TAG, "RemoteException in broadcastMessage", e);
}
return Connection.FAILURE;
}
public String getConnections() {
if (!mStarted) {
return "";
}
try {
return mIconnection.getConnections(mPackageName);
} catch (RemoteException e) {
Log.e(TAG, "RemoteException in getConnections", e);
}
return "";
}
public int getVersion() {
if (!mStarted) {
return Connection.FAILURE;
}
try {
return mIconnection.getVersion();
} catch (RemoteException e) {
Log.e(TAG, "RemoteException in getVersion", e);
}
return Connection.FAILURE;
}
public String getAddress() {
if (!mStarted) {
return "";
}
try {
return mIconnection.getAddress();
} catch (RemoteException e) {
Log.e(TAG, "RemoteException in getAddress", e);
}
return "";
}
public String getName() {
if (!mStarted) {
return "";
}
try {
return mIconnection.getName();
} catch (RemoteException e) {
Log.e(TAG, "RemoteException in getVersion", e);
}
return "";
}
public void shutdown() {
try {
mStarted = false;
if (mIconnection != null) {
mIconnection.shutdown(mPackageName);
}
mContext.unbindService(mServiceConnection);
} catch (RemoteException e) {
Log.e(TAG, "RemoteException in shutdown", e);
}
}
}
| Java |
package net.clc.bt;
import net.clc.bt.Connection.OnConnectionLostListener;
import net.clc.bt.Connection.OnConnectionServiceReadyListener;
import net.clc.bt.Connection.OnIncomingConnectionListener;
import net.clc.bt.Connection.OnMaxConnectionsReachedListener;
import net.clc.bt.Connection.OnMessageReceivedListener;
import net.clc.bt.Demo_Ball.BOUNCE_TYPE;
import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.SoundPool;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.WindowManager;
import android.view.SurfaceHolder.Callback;
import android.view.WindowManager.BadTokenException;
import android.widget.Toast;
import java.util.ArrayList;
public class AirHockey extends Activity implements Callback {
public static final String TAG = "AirHockey";
private static final int SERVER_LIST_RESULT_CODE = 42;
public static final int UP = 3;
public static final int DOWN = 4;
public static final int FLIPTOP = 5;
private AirHockey self;
private int mType; // 0 = server, 1 = client
private SurfaceView mSurface;
private SurfaceHolder mHolder;
private Paint bgPaint;
private Paint goalPaint;
private Paint ballPaint;
private Paint paddlePaint;
private PhysicsLoop pLoop;
private ArrayList<Point> mPaddlePoints;
private ArrayList<Long> mPaddleTimes;
private int mPaddlePointWindowSize = 5;
private int mPaddleRadius = 55;
private Bitmap mPaddleBmp;
private Demo_Ball mBall;
private int mBallRadius = 40;
private Connection mConnection;
private String rivalDevice = "";
private SoundPool mSoundPool;
private int tockSound = 0;
private MediaPlayer mPlayer;
private int hostScore = 0;
private int clientScore = 0;
private OnMessageReceivedListener dataReceivedListener = new OnMessageReceivedListener() {
public void OnMessageReceived(String device, String message) {
if (message.indexOf("SCORE") == 0) {
String[] scoreMessageSplit = message.split(":");
hostScore = Integer.parseInt(scoreMessageSplit[1]);
clientScore = Integer.parseInt(scoreMessageSplit[2]);
showScore();
} else {
mBall.restoreState(message);
}
}
};
private OnMaxConnectionsReachedListener maxConnectionsListener = new OnMaxConnectionsReachedListener() {
public void OnMaxConnectionsReached() {
}
};
private OnIncomingConnectionListener connectedListener = new OnIncomingConnectionListener() {
public void OnIncomingConnection(String device) {
rivalDevice = device;
WindowManager w = getWindowManager();
Display d = w.getDefaultDisplay();
int width = d.getWidth();
int height = d.getHeight();
mBall = new Demo_Ball(true, width, height - 60);
mBall.putOnScreen(width / 2, (height / 2 + (int) (height * .05)), 0, 0, 0, 0, 0);
}
};
private OnConnectionLostListener disconnectedListener = new OnConnectionLostListener() {
public void OnConnectionLost(String device) {
class displayConnectionLostAlert implements Runnable {
public void run() {
Builder connectionLostAlert = new Builder(self);
connectionLostAlert.setTitle("Connection lost");
connectionLostAlert
.setMessage("Your connection with the other player has been lost.");
connectionLostAlert.setPositiveButton("Ok", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
connectionLostAlert.setCancelable(false);
try {
connectionLostAlert.show();
} catch (BadTokenException e){
// Something really bad happened here;
// seems like the Activity itself went away before
// the runnable finished.
// Bail out gracefully here and do nothing.
}
}
}
self.runOnUiThread(new displayConnectionLostAlert());
}
};
private OnConnectionServiceReadyListener serviceReadyListener = new OnConnectionServiceReadyListener() {
public void OnConnectionServiceReady() {
if (mType == 0) {
mConnection.startServer(1, connectedListener, maxConnectionsListener,
dataReceivedListener, disconnectedListener);
self.setTitle("Air Hockey: " + mConnection.getName() + "-" + mConnection.getAddress());
} else {
WindowManager w = getWindowManager();
Display d = w.getDefaultDisplay();
int width = d.getWidth();
int height = d.getHeight();
mBall = new Demo_Ball(false, width, height - 60);
Intent serverListIntent = new Intent(self, ServerListActivity.class);
startActivityForResult(serverListIntent, SERVER_LIST_RESULT_CODE);
}
}
};
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
self = this;
mPaddleBmp = BitmapFactory.decodeResource(getResources(), R.drawable.paddlelarge);
mPaddlePoints = new ArrayList<Point>();
mPaddleTimes = new ArrayList<Long>();
Intent startingIntent = getIntent();
mType = startingIntent.getIntExtra("TYPE", 0);
setContentView(R.layout.main);
mSurface = (SurfaceView) findViewById(R.id.surface);
mHolder = mSurface.getHolder();
bgPaint = new Paint();
bgPaint.setColor(Color.BLACK);
goalPaint = new Paint();
goalPaint.setColor(Color.RED);
ballPaint = new Paint();
ballPaint.setColor(Color.GREEN);
ballPaint.setAntiAlias(true);
paddlePaint = new Paint();
paddlePaint.setColor(Color.BLUE);
paddlePaint.setAntiAlias(true);
mPlayer = MediaPlayer.create(this, R.raw.collision);
mConnection = new Connection(this, serviceReadyListener);
mHolder.addCallback(self);
}
@Override
protected void onDestroy() {
if (mConnection != null) {
mConnection.shutdown();
}
if (mPlayer != null) {
mPlayer.release();
}
super.onDestroy();
}
public void surfaceCreated(SurfaceHolder holder) {
pLoop = new PhysicsLoop();
pLoop.start();
}
private void draw() {
Canvas canvas = null;
try {
canvas = mHolder.lockCanvas();
if (canvas != null) {
doDraw(canvas);
}
} finally {
if (canvas != null) {
mHolder.unlockCanvasAndPost(canvas);
}
}
}
private void doDraw(Canvas c) {
c.drawRect(0, 0, c.getWidth(), c.getHeight(), bgPaint);
c.drawRect(0, c.getHeight() - (int) (c.getHeight() * 0.02), c.getWidth(), c.getHeight(),
goalPaint);
if (mPaddleTimes.size() > 0) {
Point p = mPaddlePoints.get(mPaddlePoints.size() - 1);
// Debug circle
// Point debugPaddleCircle = getPaddleCenter();
// c.drawCircle(debugPaddleCircle.x, debugPaddleCircle.y,
// mPaddleRadius, ballPaint);
if (p != null) {
c.drawBitmap(mPaddleBmp, p.x - 60, p.y - 200, new Paint());
}
}
if ((mBall == null) || !mBall.isOnScreen()) {
return;
}
float x = mBall.getX();
float y = mBall.getY();
if ((x != -1) && (y != -1)) {
float xv = mBall.getXVelocity();
Bitmap bmp = BitmapFactory
.decodeResource(this.getResources(), R.drawable.android_right);
if (xv < 0) {
bmp = BitmapFactory.decodeResource(this.getResources(), R.drawable.android_left);
}
// Debug circle
Point debugBallCircle = getBallCenter();
// c.drawCircle(debugBallCircle.x, debugBallCircle.y, mBallRadius,
// ballPaint);
c.drawBitmap(bmp, x - 17, y - 23, new Paint());
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
try {
pLoop.safeStop();
} finally {
pLoop = null;
}
}
private class PhysicsLoop extends Thread {
private volatile boolean running = true;
@Override
public void run() {
while (running) {
try {
Thread.sleep(5);
draw();
if (mBall != null) {
handleCollision();
int position = mBall.update();
mBall.setAcceleration(0, 0);
if (position != 0) {
if ((position == UP) && (rivalDevice.length() > 1)) {
mConnection.sendMessage(rivalDevice, mBall.getState() + "|"
+ FLIPTOP);
} else if (position == DOWN) {
if (mType == 0) {
clientScore = clientScore + 1;
} else {
hostScore = hostScore + 1;
}
mConnection.sendMessage(rivalDevice, "SCORE:" + hostScore + ":"
+ clientScore);
showScore();
WindowManager w = getWindowManager();
Display d = w.getDefaultDisplay();
int width = d.getWidth();
int height = d.getHeight();
mBall.putOnScreen(width / 2, (height / 2 + (int) (height * .05)),
0, 0, 0, 0, 0);
} else {
mBall.doRebound();
}
}
}
} catch (InterruptedException ie) {
running = false;
}
}
}
public void safeStop() {
running = false;
interrupt();
}
}
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if ((resultCode == Activity.RESULT_OK) && (requestCode == SERVER_LIST_RESULT_CODE)) {
String device = data.getStringExtra(ServerListActivity.EXTRA_SELECTED_ADDRESS);
int connectionStatus = mConnection.connect(device, dataReceivedListener,
disconnectedListener);
if (connectionStatus != Connection.SUCCESS) {
Toast.makeText(self, "Unable to connect; please try again.", 1).show();
} else {
rivalDevice = device;
}
return;
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
Point p = new Point((int) event.getX(), (int) event.getY());
mPaddlePoints.add(p);
mPaddleTimes.add(System.currentTimeMillis());
} else if (event.getAction() == MotionEvent.ACTION_MOVE) {
Point p = new Point((int) event.getX(), (int) event.getY());
mPaddlePoints.add(p);
mPaddleTimes.add(System.currentTimeMillis());
if (mPaddleTimes.size() > mPaddlePointWindowSize) {
mPaddleTimes.remove(0);
mPaddlePoints.remove(0);
}
} else {
mPaddleTimes = new ArrayList<Long>();
mPaddlePoints = new ArrayList<Point>();
}
return false;
}
// TODO: Scale this for G1 sized screens
public Point getBallCenter() {
if (mBall == null) {
return new Point(-1, -1);
}
int x = (int) mBall.getX();
int y = (int) mBall.getY();
return new Point(x + 10, y + 12);
}
// TODO: Scale this for G1 sized screens
public Point getPaddleCenter() {
if (mPaddleTimes.size() > 0) {
Point p = mPaddlePoints.get(mPaddlePoints.size() - 1);
int x = p.x + 10;
int y = p.y - 130;
return new Point(x, y);
} else {
return new Point(-1, -1);
}
}
private void showScore() {
class showScoreRunnable implements Runnable {
public void run() {
String scoreString = "";
if (mType == 0) {
scoreString = hostScore + " - " + clientScore;
} else {
scoreString = clientScore + " - " + hostScore;
}
Toast.makeText(self, scoreString, 0).show();
}
}
self.runOnUiThread(new showScoreRunnable());
}
private void handleCollision() {
// TODO: Handle multiball case
if (mBall == null) {
return;
}
if (mPaddleTimes.size() < 1) {
return;
}
Point ballCenter = getBallCenter();
Point paddleCenter = getPaddleCenter();
final int dy = ballCenter.y - paddleCenter.y;
final int dx = ballCenter.x - paddleCenter.x;
final float distance = dy * dy + dx * dx;
if (distance < ((2 * mBallRadius) * (2 * mPaddleRadius))) {
// Get paddle velocity
float vX = 0;
float vY = 0;
Point endPoint = new Point(-1, -1);
Point startPoint = new Point(-1, -1);
long timeDiff = 0;
try {
endPoint = mPaddlePoints.get(mPaddlePoints.size() - 1);
startPoint = mPaddlePoints.get(0);
timeDiff = mPaddleTimes.get(mPaddleTimes.size() - 1) - mPaddleTimes.get(0);
} catch (IndexOutOfBoundsException e) {
// Paddle points were removed at the last moment
return;
}
if (timeDiff > 0) {
vX = ((float) (endPoint.x - startPoint.x)) / timeDiff;
vY = ((float) (endPoint.y - startPoint.y)) / timeDiff;
}
// Determine the bounce type
BOUNCE_TYPE bounceType = BOUNCE_TYPE.TOP;
if ((ballCenter.x < (paddleCenter.x - mPaddleRadius / 2))
&& (ballCenter.y < (paddleCenter.y - mPaddleRadius / 2))) {
bounceType = BOUNCE_TYPE.TOPLEFT;
} else if ((ballCenter.x > (paddleCenter.x + mPaddleRadius / 2))
&& (ballCenter.y < (paddleCenter.y - mPaddleRadius / 2))) {
bounceType = BOUNCE_TYPE.TOPRIGHT;
} else if ((ballCenter.x < (paddleCenter.x - mPaddleRadius / 2))
&& (ballCenter.y > (paddleCenter.y + mPaddleRadius / 2))) {
bounceType = BOUNCE_TYPE.BOTTOMLEFT;
} else if ((ballCenter.x > (paddleCenter.x + mPaddleRadius / 2))
&& (ballCenter.y > (paddleCenter.y + mPaddleRadius / 2))) {
bounceType = BOUNCE_TYPE.BOTTOMRIGHT;
} else if ((ballCenter.x < paddleCenter.x)
&& (ballCenter.y > (paddleCenter.y - mPaddleRadius / 2))
&& (ballCenter.y < (paddleCenter.y + mPaddleRadius / 2))) {
bounceType = BOUNCE_TYPE.LEFT;
} else if ((ballCenter.x > paddleCenter.x)
&& (ballCenter.y > (paddleCenter.y - mPaddleRadius / 2))
&& (ballCenter.y < (paddleCenter.y + mPaddleRadius / 2))) {
bounceType = BOUNCE_TYPE.RIGHT;
} else if ((ballCenter.x > (paddleCenter.x - mPaddleRadius / 2))
&& (ballCenter.x < (paddleCenter.x + mPaddleRadius / 2))
&& (ballCenter.y > paddleCenter.y)) {
bounceType = BOUNCE_TYPE.RIGHT;
}
mBall.doBounce(bounceType, vX, vY);
if (!mPlayer.isPlaying()) {
mPlayer.release();
mPlayer = MediaPlayer.create(this, R.raw.collision);
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mPlayer.start();
}
}
}
}
| Java |
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.clc.bt;
import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.bluetooth.BluetoothAdapter;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.widget.Toast;
/**
* A simple activity that displays a prompt telling users to enable discoverable
* mode for Bluetooth.
*/
public class StartDiscoverableModeActivity extends Activity {
public static final int REQUEST_DISCOVERABLE_CODE = 42;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent i = new Intent();
i.setAction(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivityForResult(i, REQUEST_DISCOVERABLE_CODE);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_DISCOVERABLE_CODE) {
// Bluetooth Discoverable Mode does not return the standard
// Activity result codes.
// Instead, the result code is the duration (seconds) of
// discoverability or a negative number if the user answered "NO".
if (resultCode < 0) {
showWarning();
} else {
Toast.makeText(this, "Discoverable mode enabled.", 1).show();
finish();
}
}
}
private void showWarning() {
Builder warningDialog = new Builder(this);
final Activity self = this;
warningDialog.setTitle(R.string.DISCOVERABLE_MODE_NOT_ENABLED);
warningDialog.setMessage(R.string.WARNING_MESSAGE);
warningDialog.setPositiveButton("Yes", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent i = new Intent();
i.setAction(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivityForResult(i, REQUEST_DISCOVERABLE_CODE);
}
});
warningDialog.setNegativeButton("No", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(self, "Discoverable mode NOT enabled.", 1).show();
finish();
}
});
warningDialog.setCancelable(false);
warningDialog.show();
}
}
| Java |
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.clc.bt;
import net.clc.bt.IConnection;
import net.clc.bt.IConnectionCallback;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothServerSocket;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.UUID;
/**
* Service for simplifying the process of establishing Bluetooth connections and
* sending data in a way that is geared towards multi-player games.
*/
public class ConnectionService extends Service {
public static final String TAG = "net.clc.bt.ConnectionService";
private ArrayList<UUID> mUuid;
private ConnectionService mSelf;
private String mApp; // Assume only one app can use this at a time; may
// change this later
private IConnectionCallback mCallback;
private ArrayList<String> mBtDeviceAddresses;
private HashMap<String, BluetoothSocket> mBtSockets;
private HashMap<String, Thread> mBtStreamWatcherThreads;
private BluetoothAdapter mBtAdapter;
public ConnectionService() {
mSelf = this;
mBtAdapter = BluetoothAdapter.getDefaultAdapter();
mApp = "";
mBtSockets = new HashMap<String, BluetoothSocket>();
mBtDeviceAddresses = new ArrayList<String>();
mBtStreamWatcherThreads = new HashMap<String, Thread>();
mUuid = new ArrayList<UUID>();
// Allow up to 7 devices to connect to the server
mUuid.add(UUID.fromString("a60f35f0-b93a-11de-8a39-08002009c666"));
mUuid.add(UUID.fromString("503c7430-bc23-11de-8a39-0800200c9a66"));
mUuid.add(UUID.fromString("503c7431-bc23-11de-8a39-0800200c9a66"));
mUuid.add(UUID.fromString("503c7432-bc23-11de-8a39-0800200c9a66"));
mUuid.add(UUID.fromString("503c7433-bc23-11de-8a39-0800200c9a66"));
mUuid.add(UUID.fromString("503c7434-bc23-11de-8a39-0800200c9a66"));
mUuid.add(UUID.fromString("503c7435-bc23-11de-8a39-0800200c9a66"));
}
@Override
public IBinder onBind(Intent arg0) {
return mBinder;
}
private class BtStreamWatcher implements Runnable {
private String address;
public BtStreamWatcher(String deviceAddress) {
address = deviceAddress;
}
public void run() {
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
BluetoothSocket bSock = mBtSockets.get(address);
try {
InputStream instream = bSock.getInputStream();
int bytesRead = -1;
String message = "";
while (true) {
message = "";
bytesRead = instream.read(buffer);
if (bytesRead != -1) {
while ((bytesRead == bufferSize) && (buffer[bufferSize - 1] != 0)) {
message = message + new String(buffer, 0, bytesRead);
bytesRead = instream.read(buffer);
}
message = message + new String(buffer, 0, bytesRead - 1); // Remove
// the
// stop
// marker
mCallback.messageReceived(address, message);
}
}
} catch (IOException e) {
Log.i(TAG,
"IOException in BtStreamWatcher - probably caused by normal disconnection",
e);
} catch (RemoteException e) {
Log.e(TAG, "RemoteException in BtStreamWatcher while reading data", e);
}
// Getting out of the while loop means the connection is dead.
try {
mBtDeviceAddresses.remove(address);
mBtSockets.remove(address);
mBtStreamWatcherThreads.remove(address);
mCallback.connectionLost(address);
} catch (RemoteException e) {
Log.e(TAG, "RemoteException in BtStreamWatcher while disconnecting", e);
}
}
}
private class ConnectionWaiter implements Runnable {
private String srcApp;
private int maxConnections;
public ConnectionWaiter(String theApp, int connections) {
srcApp = theApp;
maxConnections = connections;
}
public void run() {
try {
for (int i = 0; i < Connection.MAX_SUPPORTED && maxConnections > 0; i++) {
BluetoothServerSocket myServerSocket = mBtAdapter
.listenUsingRfcommWithServiceRecord(srcApp, mUuid.get(i));
BluetoothSocket myBSock = myServerSocket.accept();
myServerSocket.close(); // Close the socket now that the
// connection has been made.
String address = myBSock.getRemoteDevice().getAddress();
mBtSockets.put(address, myBSock);
mBtDeviceAddresses.add(address);
Thread mBtStreamWatcherThread = new Thread(new BtStreamWatcher(address));
mBtStreamWatcherThread.start();
mBtStreamWatcherThreads.put(address, mBtStreamWatcherThread);
maxConnections = maxConnections - 1;
if (mCallback != null) {
mCallback.incomingConnection(address);
}
}
if (mCallback != null) {
mCallback.maxConnectionsReached();
}
} catch (IOException e) {
Log.i(TAG, "IOException in ConnectionService:ConnectionWaiter", e);
} catch (RemoteException e) {
Log.e(TAG, "RemoteException in ConnectionService:ConnectionWaiter", e);
}
}
}
private BluetoothSocket getConnectedSocket(BluetoothDevice myBtServer, UUID uuidToTry) {
BluetoothSocket myBSock;
try {
myBSock = myBtServer.createRfcommSocketToServiceRecord(uuidToTry);
myBSock.connect();
return myBSock;
} catch (IOException e) {
Log.i(TAG, "IOException in getConnectedSocket", e);
}
return null;
}
private final IConnection.Stub mBinder = new IConnection.Stub() {
public int startServer(String srcApp, int maxConnections) throws RemoteException {
if (mApp.length() > 0) {
return Connection.FAILURE;
}
mApp = srcApp;
(new Thread(new ConnectionWaiter(srcApp, maxConnections))).start();
Intent i = new Intent();
i.setClass(mSelf, StartDiscoverableModeActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
return Connection.SUCCESS;
}
public int connect(String srcApp, String device) throws RemoteException {
if (mApp.length() > 0) {
return Connection.FAILURE;
}
mApp = srcApp;
BluetoothDevice myBtServer = mBtAdapter.getRemoteDevice(device);
BluetoothSocket myBSock = null;
for (int i = 0; i < Connection.MAX_SUPPORTED && myBSock == null; i++) {
for (int j = 0; j < 3 && myBSock == null; j++) {
myBSock = getConnectedSocket(myBtServer, mUuid.get(i));
if (myBSock == null) {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
Log.e(TAG, "InterruptedException in connect", e);
}
}
}
}
if (myBSock == null) {
return Connection.FAILURE;
}
mBtSockets.put(device, myBSock);
mBtDeviceAddresses.add(device);
Thread mBtStreamWatcherThread = new Thread(new BtStreamWatcher(device));
mBtStreamWatcherThread.start();
mBtStreamWatcherThreads.put(device, mBtStreamWatcherThread);
return Connection.SUCCESS;
}
public int broadcastMessage(String srcApp, String message) throws RemoteException {
if (!mApp.equals(srcApp)) {
return Connection.FAILURE;
}
for (int i = 0; i < mBtDeviceAddresses.size(); i++) {
sendMessage(srcApp, mBtDeviceAddresses.get(i), message);
}
return Connection.SUCCESS;
}
public String getConnections(String srcApp) throws RemoteException {
if (!mApp.equals(srcApp)) {
return "";
}
String connections = "";
for (int i = 0; i < mBtDeviceAddresses.size(); i++) {
connections = connections + mBtDeviceAddresses.get(i) + ",";
}
return connections;
}
public int getVersion() throws RemoteException {
try {
PackageManager pm = mSelf.getPackageManager();
PackageInfo pInfo = pm.getPackageInfo(mSelf.getPackageName(), 0);
return pInfo.versionCode;
} catch (NameNotFoundException e) {
Log.e(TAG, "NameNotFoundException in getVersion", e);
}
return 0;
}
public int registerCallback(String srcApp, IConnectionCallback cb) throws RemoteException {
if (!mApp.equals(srcApp)) {
return Connection.FAILURE;
}
mCallback = cb;
return Connection.SUCCESS;
}
public int sendMessage(String srcApp, String destination, String message)
throws RemoteException {
if (!mApp.equals(srcApp)) {
return Connection.FAILURE;
}
try {
BluetoothSocket myBsock = mBtSockets.get(destination);
if (myBsock != null) {
OutputStream outStream = myBsock.getOutputStream();
byte[] stringAsBytes = (message + " ").getBytes();
stringAsBytes[stringAsBytes.length - 1] = 0; // Add a stop
// marker
outStream.write(stringAsBytes);
return Connection.SUCCESS;
}
} catch (IOException e) {
Log.i(TAG, "IOException in sendMessage - Dest:" + destination + ", Msg:" + message,
e);
}
return Connection.FAILURE;
}
public void shutdown(String srcApp) throws RemoteException {
try {
for (int i = 0; i < mBtDeviceAddresses.size(); i++) {
BluetoothSocket myBsock = mBtSockets.get(mBtDeviceAddresses.get(i));
myBsock.close();
}
mBtSockets = new HashMap<String, BluetoothSocket>();
mBtStreamWatcherThreads = new HashMap<String, Thread>();
mBtDeviceAddresses = new ArrayList<String>();
mApp = "";
} catch (IOException e) {
Log.i(TAG, "IOException in shutdown", e);
}
}
public int unregisterCallback(String srcApp) throws RemoteException {
if (!mApp.equals(srcApp)) {
return Connection.FAILURE;
}
mCallback = null;
return Connection.SUCCESS;
}
public String getAddress() throws RemoteException {
return mBtAdapter.getAddress();
}
public String getName() throws RemoteException {
return mBtAdapter.getName();
}
};
}
| Java |
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.clc.bt;
import net.clc.bt.Connection.OnConnectionLostListener;
import net.clc.bt.Connection.OnConnectionServiceReadyListener;
import net.clc.bt.Connection.OnIncomingConnectionListener;
import net.clc.bt.Connection.OnMaxConnectionsReachedListener;
import net.clc.bt.Connection.OnMessageReceivedListener;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.SurfaceHolder.Callback;
import android.widget.Toast;
/**
* Demo application that allows multiple Androids to be linked together as if
* they were one large screen. The center screen is the server, and it can link
* to 4 other devices: right, left, up, and down.
*/
public class Demo_Multiscreen extends Activity implements Callback {
public static final String TAG = "Demo_Multiscreen";
public static final int CENTER = 0;
public static final int RIGHT = 1;
public static final int LEFT = 2;
public static final int UP = 3;
public static final int DOWN = 4;
private static final int SERVER_LIST_RESULT_CODE = 42;
private Demo_Multiscreen self;
private long lastTouchedTime = 0;
private int mType; // 0 = server, 1 = client
private int mPosition; // The device that has the ball
private SurfaceView mSurface;
private SurfaceHolder mHolder;
private Demo_Ball mBall;
private Paint bgPaint;
private Paint ballPaint;
private Connection mConnection;
private String rightDevice = "";
private String leftDevice = "";
private String upDevice = "";
private String downDevice = "";
private OnMessageReceivedListener dataReceivedListener = new OnMessageReceivedListener() {
public void OnMessageReceived(String device, String message) {
if (message.startsWith("ASSIGNMENT:")) {
if (message.equals("ASSIGNMENT:RIGHT")) {
leftDevice = device;
} else if (message.equals("ASSIGNMENT:LEFT")) {
rightDevice = device;
} else if (message.equals("ASSIGNMENT:UP")) {
downDevice = device;
} else if (message.equals("ASSIGNMENT:DOWN")) {
upDevice = device;
}
} else {
mPosition = CENTER;
mBall.restoreState(message);
}
}
};
private OnMaxConnectionsReachedListener maxConnectionsListener = new OnMaxConnectionsReachedListener() {
public void OnMaxConnectionsReached() {
Log.e(TAG, "Max connections reached!");
}
};
private OnIncomingConnectionListener connectedListener = new OnIncomingConnectionListener() {
public void OnIncomingConnection(String device) {
if (rightDevice.length() < 1) {
mConnection.sendMessage(device, "ASSIGNMENT:RIGHT");
rightDevice = device;
} else if (leftDevice.length() < 1) {
mConnection.sendMessage(device, "ASSIGNMENT:LEFT");
leftDevice = device;
} else if (upDevice.length() < 1) {
mConnection.sendMessage(device, "ASSIGNMENT:UP");
upDevice = device;
} else if (downDevice.length() < 1) {
mConnection.sendMessage(device, "ASSIGNMENT:DOWN");
downDevice = device;
}
}
};
private OnConnectionLostListener disconnectedListener = new OnConnectionLostListener() {
public void OnConnectionLost(String device) {
if (rightDevice.equals(device)) {
rightDevice = "";
if (mPosition == RIGHT) {
mBall = new Demo_Ball(true);
}
} else if (leftDevice.equals(device)) {
leftDevice = "";
if (mPosition == LEFT) {
mBall = new Demo_Ball(true);
}
} else if (upDevice.equals(device)) {
upDevice = "";
if (mPosition == UP) {
mBall = new Demo_Ball(true);
}
} else if (downDevice.equals(device)) {
downDevice = "";
if (mPosition == DOWN) {
mBall = new Demo_Ball(true);
}
}
}
};
private OnConnectionServiceReadyListener serviceReadyListener = new OnConnectionServiceReadyListener() {
public void OnConnectionServiceReady() {
if (mType == 0) {
mBall = new Demo_Ball(true);
mConnection.startServer(4, connectedListener, maxConnectionsListener,
dataReceivedListener, disconnectedListener);
self.setTitle("MultiScreen: " + mConnection.getName() + "-" + mConnection.getAddress());
} else {
mBall = new Demo_Ball(false);
Intent serverListIntent = new Intent(self, ServerListActivity.class);
startActivityForResult(serverListIntent, SERVER_LIST_RESULT_CODE);
}
}
};
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
self = this;
Intent startingIntent = getIntent();
mType = startingIntent.getIntExtra("TYPE", 0);
setContentView(R.layout.main);
mSurface = (SurfaceView) findViewById(R.id.surface);
mHolder = mSurface.getHolder();
bgPaint = new Paint();
bgPaint.setColor(Color.BLACK);
ballPaint = new Paint();
ballPaint.setColor(Color.GREEN);
ballPaint.setAntiAlias(true);
mConnection = new Connection(this, serviceReadyListener);
mHolder.addCallback(self);
}
private PhysicsLoop pLoop;
@Override
protected void onDestroy() {
if (mConnection != null) {
mConnection.shutdown();
}
super.onDestroy();
}
public void surfaceCreated(SurfaceHolder holder) {
pLoop = new PhysicsLoop();
pLoop.start();
}
private void draw() {
Canvas canvas = null;
try {
canvas = mHolder.lockCanvas();
if (canvas != null) {
doDraw(canvas);
}
} finally {
if (canvas != null) {
mHolder.unlockCanvasAndPost(canvas);
}
}
}
private void doDraw(Canvas c) {
c.drawRect(0, 0, c.getWidth(), c.getHeight(), bgPaint);
if (mBall == null) {
return;
}
float x = mBall.getX();
float y = mBall.getY();
if ((x != -1) && (y != -1)) {
float xv = mBall.getXVelocity();
Bitmap bmp = BitmapFactory
.decodeResource(this.getResources(), R.drawable.android_right);
if (xv < 0) {
bmp = BitmapFactory.decodeResource(this.getResources(), R.drawable.android_left);
}
c.drawBitmap(bmp, x - 17, y - 23, new Paint());
}
}
public void surfaceDestroyed(SurfaceHolder holder) {
try {
pLoop.safeStop();
} finally {
pLoop = null;
}
}
private class PhysicsLoop extends Thread {
private volatile boolean running = true;
@Override
public void run() {
while (running) {
try {
Thread.sleep(5);
draw();
if (mBall != null) {
int position = mBall.update();
mBall.setAcceleration(0, 0);
if (position == RIGHT) {
if ((rightDevice.length() > 1)
&& (mConnection.sendMessage(rightDevice, mBall.getState() + "|"
+ LEFT) == Connection.SUCCESS)) {
mPosition = RIGHT;
} else {
mBall.doRebound();
}
} else if (position == LEFT) {
if ((leftDevice.length() > 1)
&& (mConnection.sendMessage(leftDevice, mBall.getState() + "|"
+ RIGHT) == Connection.SUCCESS)) {
mPosition = LEFT;
} else {
mBall.doRebound();
}
} else if (position == UP) {
if ((upDevice.length() > 1)
&& (mConnection.sendMessage(upDevice, mBall.getState() + "|"
+ DOWN) == Connection.SUCCESS)) {
mPosition = UP;
} else {
mBall.doRebound();
}
} else if (position == DOWN) {
if ((downDevice.length() > 1)
&& (mConnection.sendMessage(downDevice, mBall.getState() + "|"
+ UP) == Connection.SUCCESS)) {
mPosition = DOWN;
} else {
mBall.doRebound();
}
}
}
} catch (InterruptedException ie) {
running = false;
}
}
}
public void safeStop() {
running = false;
interrupt();
}
}
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if ((resultCode == Activity.RESULT_OK) && (requestCode == SERVER_LIST_RESULT_CODE)) {
String device = data.getStringExtra(ServerListActivity.EXTRA_SELECTED_ADDRESS);
int connectionStatus = mConnection.connect(device, dataReceivedListener,
disconnectedListener);
if (connectionStatus != Connection.SUCCESS) {
Toast.makeText(self, "Unable to connect; please try again.", 1).show();
}
return;
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
lastTouchedTime = System.currentTimeMillis();
} else if (event.getAction() == MotionEvent.ACTION_UP) {
float startX = event.getHistoricalX(0);
float startY = event.getHistoricalY(0);
float endX = event.getX();
float endY = event.getY();
long timeMs = (System.currentTimeMillis() - lastTouchedTime);
float time = timeMs / 1000.0f;
float aX = 2 * (endX - startX) / (time * time * 5);
float aY = 2 * (endY - startY) / (time * time * 5);
// Log.e("Physics debug", startX + " : " + startY + " : " + endX +
// " : " + endY + " : " + time + " : " + aX + " : " + aY);
float dampeningFudgeFactor = (float) 0.3;
if (mBall != null) {
mBall.setAcceleration(aX * dampeningFudgeFactor, aY * dampeningFudgeFactor);
}
return true;
}
return false;
}
}
| Java |
package net.clc.bt;
import net.clc.bt.Connection.OnConnectionLostListener;
import net.clc.bt.Connection.OnConnectionServiceReadyListener;
import net.clc.bt.Connection.OnIncomingConnectionListener;
import net.clc.bt.Connection.OnMaxConnectionsReachedListener;
import net.clc.bt.Connection.OnMessageReceivedListener;
import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.Gravity;
import android.view.SurfaceView;
import android.view.WindowManager;
import android.view.WindowManager.BadTokenException;
import android.widget.LinearLayout;
import android.widget.Toast;
import android.widget.VideoView;
import java.util.ArrayList;
public class MultiScreenVideo extends Activity {
private class MultiScreenVideoView extends VideoView {
public static final int POSITION_LEFT = 0;
public static final int POSITION_RIGHT = 1;
private int pos;
public MultiScreenVideoView(Context context, int position) {
super(context);
pos = position;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
widthMeasureSpec = MeasureSpec.makeMeasureSpec(960, MeasureSpec.EXACTLY);
heightMeasureSpec = MeasureSpec.makeMeasureSpec(640, MeasureSpec.EXACTLY);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
}
private boolean canSend = true;
private class PositionSyncerThread implements Runnable {
public void run() {
while (mVideo != null) {
if (canSend) {
canSend = false;
mConnection.sendMessage(connectedDevice, "SYNC:" + mVideo.getCurrentPosition());
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
private static final int SERVER_LIST_RESULT_CODE = 42;
private MultiScreenVideo self;
private MultiScreenVideoView mVideo;
private Connection mConnection;
private String connectedDevice = "";
private boolean isMaster = false;
private int lastSynced = 0;
private OnMessageReceivedListener dataReceivedListener = new OnMessageReceivedListener() {
public void OnMessageReceived(String device, String message) {
if (message.indexOf("SYNC") == 0) {
try {
String[] syncMessageSplit = message.split(":");
int diff = Integer.parseInt(syncMessageSplit[1]) - mVideo.getCurrentPosition();
Log.e("master - slave diff", Integer.parseInt(syncMessageSplit[1])
- mVideo.getCurrentPosition() + "");
if ((Math.abs(diff) > 100) && (mVideo.getCurrentPosition() - lastSynced > 1000)) {
mVideo.seekTo(mVideo.getCurrentPosition() + diff + 300);
lastSynced = mVideo.getCurrentPosition() + diff + 300;
}
} catch (IllegalStateException e) {
// Do nothing; this can happen as you are quitting the app
// mid video
}
mConnection.sendMessage(connectedDevice, "ACK");
} else if (message.indexOf("START") == 0) {
Log.e("received start", "0");
mVideo.start();
} else if (message.indexOf("ACK") == 0) {
canSend = true;
}
}
};
private OnMaxConnectionsReachedListener maxConnectionsListener = new OnMaxConnectionsReachedListener() {
public void OnMaxConnectionsReached() {
}
};
private OnIncomingConnectionListener connectedListener = new OnIncomingConnectionListener() {
public void OnIncomingConnection(String device) {
connectedDevice = device;
if (isMaster) {
Log.e("device connected", connectedDevice);
mConnection.sendMessage(connectedDevice, "START");
new Thread(new PositionSyncerThread()).start();
try {
Thread.sleep(400);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mVideo.start();
}
}
};
private OnConnectionLostListener disconnectedListener = new OnConnectionLostListener() {
public void OnConnectionLost(String device) {
class displayConnectionLostAlert implements Runnable {
public void run() {
Builder connectionLostAlert = new Builder(self);
connectionLostAlert.setTitle("Connection lost");
connectionLostAlert
.setMessage("Your connection with the other Android has been lost.");
connectionLostAlert.setPositiveButton("Ok", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
connectionLostAlert.setCancelable(false);
try {
connectionLostAlert.show();
} catch (BadTokenException e) {
// Something really bad happened here;
// seems like the Activity itself went away before
// the runnable finished.
// Bail out gracefully here and do nothing.
}
}
}
self.runOnUiThread(new displayConnectionLostAlert());
}
};
private OnConnectionServiceReadyListener serviceReadyListener = new OnConnectionServiceReadyListener() {
public void OnConnectionServiceReady() {
if (isMaster) {
mConnection.startServer(1, connectedListener, maxConnectionsListener,
dataReceivedListener, disconnectedListener);
self.setTitle("MultiScreen Video: " + mConnection.getName() + "-"
+ mConnection.getAddress());
} else {
Intent serverListIntent = new Intent(self, ServerListActivity.class);
startActivityForResult(serverListIntent, SERVER_LIST_RESULT_CODE);
}
}
};
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
self = this;
Intent startingIntent = getIntent();
isMaster = startingIntent.getBooleanExtra("isMaster", false);
int pos = MultiScreenVideoView.POSITION_LEFT;
if (!isMaster) {
pos = MultiScreenVideoView.POSITION_RIGHT;
}
mVideo = new MultiScreenVideoView(this, pos);
mVideo.setVideoPath("/sdcard/android.mp4");
LinearLayout mLinearLayout = new LinearLayout(this);
if (!isMaster) {
mLinearLayout.setOrientation(LinearLayout.HORIZONTAL);
mLinearLayout.setGravity(Gravity.RIGHT);
mLinearLayout.setPadding(0, 0, 120, 0);
}
mLinearLayout.addView(mVideo);
setContentView(mLinearLayout);
mConnection = new Connection(this, serviceReadyListener);
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if ((resultCode == Activity.RESULT_OK) && (requestCode == SERVER_LIST_RESULT_CODE)) {
String device = data.getStringExtra(ServerListActivity.EXTRA_SELECTED_ADDRESS);
int connectionStatus = mConnection.connect(device, dataReceivedListener,
disconnectedListener);
if (connectionStatus != Connection.SUCCESS) {
Toast.makeText(self, "Unable to connect; please try again.", 1).show();
} else {
connectedDevice = device;
}
return;
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if (mConnection != null) {
mConnection.shutdown();
}
}
}
| Java |
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.clc.bt;
import android.app.Activity;
import android.app.ListActivity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Parcelable;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
/**
* A simple list activity that displays Bluetooth devices that are in
* discoverable mode. This can be used as a gamelobby where players can see
* available servers and pick the one they wish to connect to.
*/
public class ServerListActivity extends ListActivity {
public static String EXTRA_SELECTED_ADDRESS = "btaddress";
private BluetoothAdapter myBt;
private ServerListActivity self;
private ArrayAdapter<String> arrayAdapter;
private BroadcastReceiver myReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Parcelable btParcel = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
BluetoothDevice btDevice = (BluetoothDevice) btParcel;
arrayAdapter.add(btDevice.getName() + " - " + btDevice.getAddress());
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
self = this;
arrayAdapter = new ArrayAdapter<String>(self, R.layout.text);
ListView lv = self.getListView();
lv.setAdapter(arrayAdapter);
lv.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
myBt.cancelDiscovery(); // Cancel BT discovery explicitly so
// that connections can go through
String btDeviceInfo = ((TextView) arg1).getText().toString();
String btHardwareAddress = btDeviceInfo.substring(btDeviceInfo.length() - 17);
Intent i = new Intent();
i.putExtra(EXTRA_SELECTED_ADDRESS, btHardwareAddress);
self.setResult(Activity.RESULT_OK, i);
finish();
}
});
myBt = BluetoothAdapter.getDefaultAdapter();
myBt.startDiscovery();
self.setResult(Activity.RESULT_CANCELED);
}
@Override
protected void onResume() {
super.onResume();
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
this.registerReceiver(myReceiver, filter);
}
@Override
protected void onPause() {
super.onPause();
this.unregisterReceiver(myReceiver);
}
@Override
protected void onDestroy() {
super.onDestroy();
if (myBt != null) {
myBt.cancelDiscovery(); // Ensure that we don't leave discovery
// running by accident
}
}
}
| Java |
/*
* Copyright (C) 2009 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.clc.bt;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
/**
* A simple configuration screen that displays the user's current Bluetooth
* information along with buttons for entering the Bluetooth settings menu and
* for starting a demo app. This is work in progress and only the demo app
* buttons are currently available.
*/
public class ConfigActivity extends Activity {
private ConfigActivity self;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
self = this;
setContentView(R.layout.config);
Button startServer = (Button) findViewById(R.id.start_hockey_server);
startServer.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//Intent serverIntent = new Intent(self, Demo_Multiscreen.class);
Intent serverIntent = new Intent(self, AirHockey.class);
serverIntent.putExtra("TYPE", 0);
startActivity(serverIntent);
}
});
Button startClient = (Button) findViewById(R.id.start_hockey_client);
startClient.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//Intent clientIntent = new Intent(self, Demo_Multiscreen.class);
Intent clientIntent = new Intent(self, AirHockey.class);
clientIntent.putExtra("TYPE", 1);
startActivity(clientIntent);
}
});
Button startMultiScreenServer = (Button) findViewById(R.id.start_demo_server);
startMultiScreenServer.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//Intent serverIntent = new Intent(self, Demo_Multiscreen.class);
Intent serverIntent = new Intent(self, Demo_Multiscreen.class);
serverIntent.putExtra("TYPE", 0);
startActivity(serverIntent);
}
});
Button startMultiScreenClient = (Button) findViewById(R.id.start_demo_client);
startMultiScreenClient.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
//Intent clientIntent = new Intent(self, Demo_Multiscreen.class);
Intent clientIntent = new Intent(self, Demo_Multiscreen.class);
clientIntent.putExtra("TYPE", 1);
startActivity(clientIntent);
}
});
Button startVideoServer = (Button) findViewById(R.id.start_video_server);
startVideoServer.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent serverIntent = new Intent(self, MultiScreenVideo.class);
serverIntent.putExtra("isMaster", true);
startActivity(serverIntent);
}
});
Button startVideoClient = (Button) findViewById(R.id.start_video_client);
startVideoClient.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent clientIntent = new Intent(self, MultiScreenVideo.class);
clientIntent.putExtra("isMaster", false);
startActivity(clientIntent);
}
});
Button gotoWeb = (Button) findViewById(R.id.goto_website);
gotoWeb.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent i = new Intent();
i.setAction("android.intent.action.VIEW");
i.addCategory("android.intent.category.BROWSABLE");
Uri uri = Uri.parse("http://apps-for-android.googlecode.com/svn/trunk/BTClickLinkCompete/docs/index.html");
i.setData(uri);
self.startActivity(i);
}
});
}
}
| 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.photostream;
import android.os.*;
import android.os.Process;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.Callable;
import java.util.concurrent.FutureTask;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.CancellationException;
import java.util.concurrent.atomic.AtomicInteger;
/**
* <p>UserTask enables proper and easy use of the UI thread. This class allows to
* perform background operations and publish results on the UI thread without
* having to manipulate threads and/or handlers.</p>
*
* <p>A user task is defined by a computation that runs on a background thread and
* whose result is published on the UI thread. A user task is defined by 3 generic
* types, called <code>Params</code>, <code>Progress</code> and <code>Result</code>,
* and 4 steps, called <code>begin</code>, <code>doInBackground</code>,
* <code>processProgress<code> and <code>end</code>.</p>
*
* <h2>Usage</h2>
* <p>UserTask must be subclassed to be used. The subclass will override at least
* one method ({@link #doInBackground(Object[])}), and most often will override a
* second one ({@link #onPostExecute(Object)}.)</p>
*
* <p>Here is an example of subclassing:</p>
* <pre>
* private class DownloadFilesTask extends UserTask<URL, Integer, Long> {
* public File doInBackground(URL... urls) {
* int count = urls.length;
* long totalSize = 0;
* for (int i = 0; i < count; i++) {
* totalSize += Downloader.downloadFile(urls[i]);
* publishProgress((int) ((i / (float) count) * 100));
* }
* }
*
* public void processProgress(Integer... progress) {
* setProgressPercent(progress[0]);
* }
*
* public void end(Long result) {
* showDialog("Downloaded " + result + " bytes");
* }
* }
* </pre>
*
* <p>Once created, a task is executed very simply:</p>
* <pre>
* new DownloadFilesTask().execute(new URL[] { ... });
* </pre>
*
* <h2>User task's generic types</h2>
* <p>The three types used by a user task are the following:</p>
* <ol>
* <li><code>Params</code>, the type of the parameters sent to the task upon
* execution.</li>
* <li><code>Progress</code>, the type of the progress units published during
* the background computation.</li>
* <li><code>Result</code>, the type of the result of the background
* computation.</li>
* </ol>
* <p>Not all types are always used by a user task. To mark a type as unused,
* simply use the type {@link Void}:</p>
* <pre>
* private class MyTask extends UserTask<Void, Void, Void) { ... }
* </pre>
*
* <h2>The 4 steps</h2>
* <p>When a user task is executed, the task goes through 4 steps:</p>
* <ol>
* <li>{@link #onPreExecute()}, invoked on the UI thread immediately after the task
* is executed. This step is normally used to setup the task, for instance by
* showing a progress bar in the user interface.</li>
* <li>{@link #doInBackground(Object[])}, invoked on the background thread
* immediately after {@link # onPreExecute ()} finishes executing. This step is used
* to perform background computation that can take a long time. The parameters
* of the user task are passed to this step. The result of the computation must
* be returned by this step and will be passed back to the last step. This step
* can also use {@link #publishProgress(Object[])} to publish one or more units
* of progress. These values are published on the UI thread, in the
* {@link #onProgressUpdate(Object[])} step.</li>
* <li>{@link # onProgressUpdate (Object[])}, invoked on the UI thread after a
* call to {@link #publishProgress(Object[])}. The timing of the execution is
* undefined. This method is used to display any form of progress in the user
* interface while the background computation is still executing. For instance,
* it can be used to animate a progress bar or show logs in a text field.</li>
* <li>{@link # onPostExecute (Object)}, invoked on the UI thread after the background
* computation finishes. The result of the background computation is passed to
* this step as a parameter.</li>
* </ol>
*
* <h2>Threading rules</h2>
* <p>There are a few threading rules that must be followed for this class to
* work properly:</p>
* <ul>
* <li>The task instance must be created on the UI thread.</li>
* <li>{@link #execute(Object[])} must be invoked on the UI thread.</li>
* <li>Do not call {@link # onPreExecute ()}, {@link # onPostExecute (Object)},
* {@link #doInBackground(Object[])}, {@link # onProgressUpdate (Object[])}
* manually.</li>
* <li>The task can be executed only once (an exception will be thrown if
* a second execution is attempted.)</li>
* </ul>
*/
public abstract class UserTask<Params, Progress, Result> {
private static final String LOG_TAG = "UserTask";
private static final int CORE_POOL_SIZE = 1;
private static final int MAXIMUM_POOL_SIZE = 10;
private static final int KEEP_ALIVE = 10;
private static final BlockingQueue<Runnable> sWorkQueue =
new LinkedBlockingQueue<Runnable>(MAXIMUM_POOL_SIZE);
private static final ThreadFactory sThreadFactory = new ThreadFactory() {
private final AtomicInteger mCount = new AtomicInteger(1);
public Thread newThread(Runnable r) {
return new Thread(r, "UserTask #" + mCount.getAndIncrement());
}
};
private static final ThreadPoolExecutor sExecutor = new ThreadPoolExecutor(CORE_POOL_SIZE,
MAXIMUM_POOL_SIZE, KEEP_ALIVE, TimeUnit.SECONDS, sWorkQueue, sThreadFactory);
private static final int MESSAGE_POST_RESULT = 0x1;
private static final int MESSAGE_POST_PROGRESS = 0x2;
private static final int MESSAGE_POST_CANCEL = 0x3;
private static final InternalHandler sHandler = new InternalHandler();
private final WorkerRunnable<Params, Result> mWorker;
private final FutureTask<Result> mFuture;
private volatile Status mStatus = Status.PENDING;
/**
* Indicates the current status of the task. Each status will be set only once
* during the lifetime of a task.
*/
public enum Status {
/**
* Indicates that the task has not been executed yet.
*/
PENDING,
/**
* Indicates that the task is running.
*/
RUNNING,
/**
* Indicates that {@link UserTask#onPostExecute(Object)} has finished.
*/
FINISHED,
}
/**
* Creates a new user task. This constructor must be invoked on the UI thread.
*/
public UserTask() {
mWorker = new WorkerRunnable<Params, Result>() {
public Result call() throws Exception {
Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
return doInBackground(mParams);
}
};
mFuture = new FutureTask<Result>(mWorker) {
@Override
protected void done() {
Message message;
Result result = null;
try {
result = get();
} catch (InterruptedException e) {
android.util.Log.w(LOG_TAG, e);
} catch (ExecutionException e) {
throw new RuntimeException("An error occured while executing doInBackground()",
e.getCause());
} catch (CancellationException e) {
message = sHandler.obtainMessage(MESSAGE_POST_CANCEL,
new UserTaskResult<Result>(UserTask.this, (Result[]) null));
message.sendToTarget();
return;
} catch (Throwable t) {
throw new RuntimeException("An error occured while executing "
+ "doInBackground()", t);
}
message = sHandler.obtainMessage(MESSAGE_POST_RESULT,
new UserTaskResult<Result>(UserTask.this, result));
message.sendToTarget();
}
};
}
/**
* Returns the current status of this task.
*
* @return The current status.
*/
public final Status getStatus() {
return mStatus;
}
/**
* Override this method to perform a computation on a background thread. The
* specified parameters are the parameters passed to {@link #execute(Object[])}
* by the caller of this task.
*
* This method can call {@link #publishProgress(Object[])} to publish updates
* on the UI thread.
*
* @param params The parameters of the task.
*
* @return A result, defined by the subclass of this task.
*
* @see #onPreExecute()
* @see #onPostExecute(Object)
* @see #publishProgress(Object[])
*/
public abstract Result doInBackground(Params... params);
/**
* Runs on the UI thread before {@link #doInBackground(Object[])}.
*
* @see #onPostExecute(Object)
* @see #doInBackground(Object[])
*/
public void onPreExecute() {
}
/**
* Runs on the UI thread after {@link #doInBackground(Object[])}. The
* specified result is the value returned by {@link #doInBackground(Object[])}
* or null if the task was cancelled or an exception occured.
*
* @param result The result of the operation computed by {@link #doInBackground(Object[])}.
*
* @see #onPreExecute()
* @see #doInBackground(Object[])
*/
@SuppressWarnings({"UnusedDeclaration"})
public void onPostExecute(Result result) {
}
/**
* Runs on the UI thread after {@link #publishProgress(Object[])} is invoked.
* The specified values are the values passed to {@link #publishProgress(Object[])}.
*
* @param values The values indicating progress.
*
* @see #publishProgress(Object[])
* @see #doInBackground(Object[])
*/
@SuppressWarnings({"UnusedDeclaration"})
public void onProgressUpdate(Progress... values) {
}
/**
* Runs on the UI thread after {@link #cancel(boolean)} is invoked.
*
* @see #cancel(boolean)
* @see #isCancelled()
*/
public void onCancelled() {
}
/**
* Returns <tt>true</tt> if this task was cancelled before it completed
* normally.
*
* @return <tt>true</tt> if task was cancelled before it completed
*
* @see #cancel(boolean)
*/
public final boolean isCancelled() {
return mFuture.isCancelled();
}
/**
* Attempts to cancel execution of this task. This attempt will
* fail if the task has already completed, already been cancelled,
* or could not be cancelled for some other reason. If successful,
* and this task has not started when <tt>cancel</tt> is called,
* this task should never run. If the task has already started,
* then the <tt>mayInterruptIfRunning</tt> parameter determines
* whether the thread executing this task should be interrupted in
* an attempt to stop the task.
*
* @param mayInterruptIfRunning <tt>true</tt> if the thread executing this
* task should be interrupted; otherwise, in-progress tasks are allowed
* to complete.
*
* @return <tt>false</tt> if the task could not be cancelled,
* typically because it has already completed normally;
* <tt>true</tt> otherwise
*
* @see #isCancelled()
* @see #onCancelled()
*/
public final boolean cancel(boolean mayInterruptIfRunning) {
return mFuture.cancel(mayInterruptIfRunning);
}
/**
* Waits if necessary for the computation to complete, and then
* retrieves its result.
*
* @return The computed result.
*
* @throws CancellationException If the computation was cancelled.
* @throws ExecutionException If the computation threw an exception.
* @throws InterruptedException If the current thread was interrupted
* while waiting.
*/
public final Result get() throws InterruptedException, ExecutionException {
return mFuture.get();
}
/**
* Waits if necessary for at most the given time for the computation
* to complete, and then retrieves its result.
*
* @param timeout Time to wait before cancelling the operation.
* @param unit The time unit for the timeout.
*
* @return The computed result.
*
* @throws CancellationException If the computation was cancelled.
* @throws ExecutionException If the computation threw an exception.
* @throws InterruptedException If the current thread was interrupted
* while waiting.
* @throws TimeoutException If the wait timed out.
*/
public final Result get(long timeout, TimeUnit unit) throws InterruptedException,
ExecutionException, TimeoutException {
return mFuture.get(timeout, unit);
}
/**
* Executes the task with the specified parameters. The task returns
* itself (this) so that the caller can keep a reference to it.
*
* This method must be invoked on the UI thread.
*
* @param params The parameters of the task.
*
* @return This instance of UserTask.
*
* @throws IllegalStateException If {@link #getStatus()} returns either
* {@link UserTask.Status#RUNNING} or {@link UserTask.Status#FINISHED}.
*/
public final UserTask<Params, Progress, Result> execute(Params... params) {
if (mStatus != Status.PENDING) {
switch (mStatus) {
case RUNNING:
throw new IllegalStateException("Cannot execute task:"
+ " the task is already running.");
case FINISHED:
throw new IllegalStateException("Cannot execute task:"
+ " the task has already been executed "
+ "(a task can be executed only once)");
}
}
mStatus = Status.RUNNING;
onPreExecute();
mWorker.mParams = params;
sExecutor.execute(mFuture);
return this;
}
/**
* This method can be invoked from {@link #doInBackground(Object[])} to
* publish updates on the UI thread while the background computation is
* still running. Each call to this method will trigger the execution of
* {@link #onProgressUpdate(Object[])} on the UI thread.
*
* @param values The progress values to update the UI with.
*
* @see # onProgressUpdate (Object[])
* @see #doInBackground(Object[])
*/
protected final void publishProgress(Progress... values) {
sHandler.obtainMessage(MESSAGE_POST_PROGRESS,
new UserTaskResult<Progress>(this, values)).sendToTarget();
}
private void finish(Result result) {
onPostExecute(result);
mStatus = Status.FINISHED;
}
private static class InternalHandler extends Handler {
@SuppressWarnings({"unchecked", "RawUseOfParameterizedType"})
@Override
public void handleMessage(Message msg) {
UserTaskResult result = (UserTaskResult) msg.obj;
switch (msg.what) {
case MESSAGE_POST_RESULT:
// There is only one result
result.mTask.finish(result.mData[0]);
break;
case MESSAGE_POST_PROGRESS:
result.mTask.onProgressUpdate(result.mData);
break;
case MESSAGE_POST_CANCEL:
result.mTask.onCancelled();
break;
}
}
}
private static abstract class WorkerRunnable<Params, Result> implements Callable<Result> {
Params[] mParams;
}
@SuppressWarnings({"RawUseOfParameterizedType"})
private static class UserTaskResult<Data> {
final UserTask mTask;
final Data[] mData;
UserTaskResult(UserTask task, Data... data) {
mTask = task;
mData = data;
}
}
}
| 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.example.anycut;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
/**
* A simple activity to allow the user to manually type in an Intent.
*/
public class CustomShortcutCreatorActivity extends Activity implements View.OnClickListener {
@Override
protected void onCreate(Bundle savedState) {
super.onCreate(savedState);
setContentView(R.layout.custom_shortcut_creator);
findViewById(R.id.ok).setOnClickListener(this);
findViewById(R.id.cancel).setOnClickListener(this);
}
public void onClick(View view) {
switch (view.getId()) {
case R.id.ok: {
Intent intent = createShortcutIntent();
setResult(RESULT_OK, intent);
finish();
break;
}
case R.id.cancel: {
setResult(RESULT_CANCELED);
finish();
break;
}
}
}
private Intent createShortcutIntent() {
Intent intent = new Intent();
EditText view;
view = (EditText) findViewById(R.id.action);
intent.setAction(view.getText().toString());
view = (EditText) findViewById(R.id.data);
String data = view.getText().toString();
view = (EditText) findViewById(R.id.type);
String type = view.getText().toString();
boolean dataEmpty = TextUtils.isEmpty(data);
boolean typeEmpty = TextUtils.isEmpty(type);
if (!dataEmpty && typeEmpty) {
intent.setData(Uri.parse(data));
} else if (!typeEmpty && dataEmpty) {
intent.setType(type);
} else if (!typeEmpty && !dataEmpty) {
intent.setDataAndType(Uri.parse(data), type);
}
return new Intent().putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent);
}
}
| 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.example.anycut;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.ContentUris;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Contacts;
import android.provider.Contacts.People;
import android.provider.Contacts.Phones;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
/**
* Presents the user with a list of types of shortucts that can be created.
* When Any Cut is launched through the home screen this is the activity that comes up.
*/
public class CreateShortcutActivity extends ListActivity implements DialogInterface.OnClickListener,
Dialog.OnCancelListener {
private static final boolean ENABLE_ACTION_ICON_OVERLAYS = false;
private static final int REQUEST_PHONE = 1;
private static final int REQUEST_TEXT = 2;
private static final int REQUEST_ACTIVITY = 3;
private static final int REQUEST_CUSTOM = 4;
private static final int LIST_ITEM_DIRECT_CALL = 0;
private static final int LIST_ITEM_DIRECT_TEXT = 1;
private static final int LIST_ITEM_ACTIVITY = 2;
private static final int LIST_ITEM_CUSTOM = 3;
private static final int DIALOG_SHORTCUT_EDITOR = 1;
private Intent mEditorIntent;
@Override
public void onCreate(Bundle savedState) {
super.onCreate(savedState);
setListAdapter(ArrayAdapter.createFromResource(this, R.array.mainMenu,
android.R.layout.simple_list_item_1));
}
@Override
protected void onListItemClick(ListView list, View view, int position, long id) {
switch (position) {
case LIST_ITEM_DIRECT_CALL: {
Intent intent = new Intent(Intent.ACTION_PICK, Phones.CONTENT_URI);
intent.putExtra(Contacts.Intents.UI.TITLE_EXTRA_KEY,
getText(R.string.callShortcutActivityTitle));
startActivityForResult(intent, REQUEST_PHONE);
break;
}
case LIST_ITEM_DIRECT_TEXT: {
Intent intent = new Intent(Intent.ACTION_PICK, Phones.CONTENT_URI);
intent.putExtra(Contacts.Intents.UI.TITLE_EXTRA_KEY,
getText(R.string.textShortcutActivityTitle));
startActivityForResult(intent, REQUEST_TEXT);
break;
}
case LIST_ITEM_ACTIVITY: {
Intent intent = new Intent();
intent.setClass(this, ActivityPickerActivity.class);
startActivityForResult(intent, REQUEST_ACTIVITY);
break;
}
case LIST_ITEM_CUSTOM: {
Intent intent = new Intent();
intent.setClass(this, CustomShortcutCreatorActivity.class);
startActivityForResult(intent, REQUEST_CUSTOM);
break;
}
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent result) {
if (resultCode != RESULT_OK) {
return;
}
switch (requestCode) {
case REQUEST_PHONE: {
startShortcutEditor(generatePhoneShortcut(result, R.drawable.sym_action_call,
"tel", Intent.ACTION_CALL));
break;
}
case REQUEST_TEXT: {
startShortcutEditor(generatePhoneShortcut(result, R.drawable.sym_action_sms,
"smsto", Intent.ACTION_SENDTO));
break;
}
case REQUEST_ACTIVITY:
case REQUEST_CUSTOM: {
startShortcutEditor(result);
break;
}
}
}
@Override
protected Dialog onCreateDialog(int dialogId) {
switch (dialogId) {
case DIALOG_SHORTCUT_EDITOR: {
return new ShortcutEditorDialog(this, this, this);
}
}
return super.onCreateDialog(dialogId);
}
@Override
protected void onPrepareDialog(int dialogId, Dialog dialog) {
switch (dialogId) {
case DIALOG_SHORTCUT_EDITOR: {
if (mEditorIntent != null) {
// If the editor intent hasn't been set already set it
ShortcutEditorDialog editor = (ShortcutEditorDialog) dialog;
editor.setIntent(mEditorIntent);
mEditorIntent = null;
}
}
}
}
/**
* Starts the shortcut editor
*
* @param shortcutIntent The shortcut intent to edit
*/
private void startShortcutEditor(Intent shortcutIntent) {
mEditorIntent = shortcutIntent;
showDialog(DIALOG_SHORTCUT_EDITOR);
}
public void onCancel(DialogInterface dialog) {
// Remove the dialog, it won't be used again
removeDialog(DIALOG_SHORTCUT_EDITOR);
}
public void onClick(DialogInterface dialog, int which) {
if (which == DialogInterface.BUTTON1) {
// OK button
ShortcutEditorDialog editor = (ShortcutEditorDialog) dialog;
Intent shortcut = editor.getIntent();
setResult(RESULT_OK, shortcut);
finish();
}
// Remove the dialog, it won't be used again
removeDialog(DIALOG_SHORTCUT_EDITOR);
}
/**
* Returns an Intent describing a direct text message shortcut.
*
* @param result The result from the phone number picker
* @return an Intent describing a phone number shortcut
*/
private Intent generatePhoneShortcut(Intent result, int actionResId, String scheme, String action) {
Uri phoneUri = result.getData();
long personId = 0;
String name = null;
String number = null;
int type;
Cursor cursor = getContentResolver().query(phoneUri,
new String[] { Phones.PERSON_ID, Phones.DISPLAY_NAME, Phones.NUMBER, Phones.TYPE },
null, null, null);
try {
cursor.moveToFirst();
personId = cursor.getLong(0);
name = cursor.getString(1);
number = cursor.getString(2);
type = cursor.getInt(3);
} finally {
if (cursor != null) {
cursor.close();
}
}
Intent intent = new Intent();
Uri personUri = ContentUris.withAppendedId(People.CONTENT_URI, personId);
intent.putExtra(Intent.EXTRA_SHORTCUT_ICON,
generatePhoneNumberIcon(personUri, type, actionResId));
// Make the URI a direct tel: URI so that it will always continue to work
phoneUri = Uri.fromParts(scheme, number, null);
intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent(action, phoneUri));
intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, name);
return intent;
}
/**
* Generates a phone number shortcut icon. Adds an overlay describing the type of the phone
* number, and if there is a photo also adds the call action icon.
*
* @param personUri The person the phone number belongs to
* @param type The type of the phone number
* @param actionResId The ID for the action resource
* @return The bitmap for the icon
*/
private Bitmap generatePhoneNumberIcon(Uri personUri, int type, int actionResId) {
final Resources r = getResources();
boolean drawPhoneOverlay = true;
Bitmap photo = People.loadContactPhoto(this, personUri, 0, null);
if (photo == null) {
// If there isn't a photo use the generic phone action icon instead
Bitmap phoneIcon = getPhoneActionIcon(r, actionResId);
if (phoneIcon != null) {
photo = phoneIcon;
drawPhoneOverlay = false;
} else {
return null;
}
}
// Setup the drawing classes
int iconSize = (int) r.getDimension(android.R.dimen.app_icon_size);
Bitmap icon = Bitmap.createBitmap(iconSize, iconSize, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(icon);
// Copy in the photo
Paint photoPaint = new Paint();
photoPaint.setDither(true);
photoPaint.setFilterBitmap(true);
Rect src = new Rect(0,0, photo.getWidth(),photo.getHeight());
Rect dst = new Rect(0,0, iconSize,iconSize);
canvas.drawBitmap(photo, src, dst, photoPaint);
// Create an overlay for the phone number type
String overlay = null;
switch (type) {
case Phones.TYPE_HOME:
overlay = "H";
break;
case Phones.TYPE_MOBILE:
overlay = "M";
break;
case Phones.TYPE_WORK:
overlay = "W";
break;
case Phones.TYPE_PAGER:
overlay = "P";
break;
case Phones.TYPE_OTHER:
overlay = "O";
break;
}
if (overlay != null) {
Paint textPaint = new Paint(Paint.ANTI_ALIAS_FLAG | Paint.DEV_KERN_TEXT_FLAG);
textPaint.setTextSize(20.0f);
textPaint.setTypeface(Typeface.DEFAULT_BOLD);
textPaint.setColor(r.getColor(R.color.textColorIconOverlay));
textPaint.setShadowLayer(3f, 1, 1, r.getColor(R.color.textColorIconOverlayShadow));
canvas.drawText(overlay, 2, 16, textPaint);
}
// Draw the phone action icon as an overlay
if (ENABLE_ACTION_ICON_OVERLAYS && drawPhoneOverlay) {
Bitmap phoneIcon = getPhoneActionIcon(r, actionResId);
if (phoneIcon != null) {
src.set(0,0, phoneIcon.getWidth(),phoneIcon.getHeight());
int iconWidth = icon.getWidth();
dst.set(iconWidth - 20, -1, iconWidth, 19);
canvas.drawBitmap(phoneIcon, src, dst, photoPaint);
}
}
return icon;
}
/**
* Returns the icon for the phone call action.
*
* @param r The resources to load the icon from
* @param resId The resource ID to load
* @return the icon for the phone call action
*/
private Bitmap getPhoneActionIcon(Resources r, int resId) {
Drawable phoneIcon = r.getDrawable(resId);
if (phoneIcon instanceof BitmapDrawable) {
BitmapDrawable bd = (BitmapDrawable) phoneIcon;
return bd.getBitmap();
} else {
return null;
}
}
} | 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.example.anycut;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent.ShortcutIconResource;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
/**
* A dialog that can edit a shortcut intent. For now the icon is displayed, and only
* the name may be edited.
*/
public class ShortcutEditorDialog extends AlertDialog implements OnClickListener, TextWatcher {
static final String STATE_INTENT = "intent";
private boolean mCreated = false;
private Intent mIntent;
private ImageView mIconView;
private EditText mNameView;
private OnClickListener mOnClick;
private OnCancelListener mOnCancel;
public ShortcutEditorDialog(Context context, OnClickListener onClick,
OnCancelListener onCancel) {
super(context);
mOnClick = onClick;
mOnCancel = onCancel;
// Setup the dialog
View view = getLayoutInflater().inflate(R.layout.shortcut_editor, null, false);
setTitle(R.string.shortcutEditorTitle);
setButton(context.getText(android.R.string.ok), this);
setButton2(context.getText(android.R.string.cancel), mOnClick);
setOnCancelListener(mOnCancel);
setCancelable(true);
setView(view);
mIconView = (ImageView) view.findViewById(R.id.shortcutIcon);
mNameView = (EditText) view.findViewById(R.id.shortcutName);
}
public void onClick(DialogInterface dialog, int which) {
if (which == BUTTON1) {
String name = mNameView.getText().toString();
if (TextUtils.isEmpty(name)) {
// Don't allow an empty name
mNameView.setError(getContext().getText(R.string.errorEmptyName));
return;
}
mIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, name);
}
mOnClick.onClick(dialog, which);
}
@Override
protected void onCreate(Bundle state) {
super.onCreate(state);
if (state != null) {
mIntent = state.getParcelable(STATE_INTENT);
}
mCreated = true;
// If an intent is set make sure to load it now that it's safe
if (mIntent != null) {
loadIntent(mIntent);
}
}
@Override
public Bundle onSaveInstanceState() {
Bundle state = super.onSaveInstanceState();
state.putParcelable(STATE_INTENT, getIntent());
return state;
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
// Do nothing
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
// Do nothing
}
public void afterTextChanged(Editable text) {
if (text.length() == 0) {
mNameView.setError(getContext().getText(R.string.errorEmptyName));
} else {
mNameView.setError(null);
}
}
/**
* Saves the current state of the editor into the intent and returns it.
*
* @return the intent for the shortcut being edited
*/
public Intent getIntent() {
mIntent.putExtra(Intent.EXTRA_SHORTCUT_NAME, mNameView.getText().toString());
return mIntent;
}
/**
* Reads the state of the shortcut from the intent and sets up the editor
*
* @param intent A shortcut intent to edit
*/
public void setIntent(Intent intent) {
mIntent = intent;
if (mCreated) {
loadIntent(intent);
}
}
/**
* Loads the editor state from a shortcut intent.
*
* @param intent The shortcut intent to load the editor from
*/
private void loadIntent(Intent intent) {
// Show the icon
Bitmap iconBitmap = intent.getParcelableExtra(Intent.EXTRA_SHORTCUT_ICON);
if (iconBitmap != null) {
mIconView.setImageBitmap(iconBitmap);
} else {
ShortcutIconResource iconRes = intent.getParcelableExtra(
Intent.EXTRA_SHORTCUT_ICON_RESOURCE);
if (iconRes != null) {
int res = getContext().getResources().getIdentifier(iconRes.resourceName, null,
iconRes.packageName);
mIconView.setImageResource(res);
} else {
mIconView.setVisibility(View.INVISIBLE);
}
}
// Fill in the name field for editing
mNameView.addTextChangedListener(this);
mNameView.setText(intent.getStringExtra(Intent.EXTRA_SHORTCUT_NAME));
// Ensure the intent has the proper flags
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
}
}
| 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.example.anycut;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import android.app.Activity;
import android.app.ListActivity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import com.google.android.photostream.UserTask;
/**
* Presents a list of activities to choose from. This list only contains activities
* that have ACTION_MAIN, since other types may require data as input.
*/
public class ActivityPickerActivity extends ListActivity {
PackageManager mPackageManager;
/**
* This class is used to wrap ResolveInfo so that it can be filtered using
* ArrayAdapter's built int filtering logic, which depends on toString().
*/
private final class ResolveInfoWrapper {
private ResolveInfo mInfo;
public ResolveInfoWrapper(ResolveInfo info) {
mInfo = info;
}
@Override
public String toString() {
return mInfo.loadLabel(mPackageManager).toString();
}
public ResolveInfo getInfo() {
return mInfo;
}
}
private class ActivityAdapter extends ArrayAdapter<ResolveInfoWrapper> {
LayoutInflater mInflater;
public ActivityAdapter(Activity activity, ArrayList<ResolveInfoWrapper> activities) {
super(activity, 0, activities);
mInflater = activity.getLayoutInflater();
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
final ResolveInfoWrapper info = getItem(position);
View view = convertView;
if (view == null) {
// Inflate the view and cache the pointer to the text view
view = mInflater.inflate(android.R.layout.simple_list_item_1, parent, false);
view.setTag(view.findViewById(android.R.id.text1));
}
final TextView textView = (TextView) view.getTag();
textView.setText(info.getInfo().loadLabel(mPackageManager));
return view;
}
}
private final class LoadingTask extends UserTask<Object, Object, ActivityAdapter> {
@Override
public void onPreExecute() {
setProgressBarIndeterminateVisibility(true);
}
@Override
public ActivityAdapter doInBackground(Object... params) {
// Load the activities
Intent queryIntent = new Intent(Intent.ACTION_MAIN);
List<ResolveInfo> list = mPackageManager.queryIntentActivities(queryIntent, 0);
// Sort the list
Collections.sort(list, new ResolveInfo.DisplayNameComparator(mPackageManager));
// Make the wrappers
ArrayList<ResolveInfoWrapper> activities = new ArrayList<ResolveInfoWrapper>(list.size());
for(ResolveInfo item : list) {
activities.add(new ResolveInfoWrapper(item));
}
return new ActivityAdapter(ActivityPickerActivity.this, activities);
}
@Override
public void onPostExecute(ActivityAdapter result) {
setProgressBarIndeterminateVisibility(false);
setListAdapter(result);
}
}
@Override
protected void onCreate(Bundle savedState) {
super.onCreate(savedState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.list);
getListView().setTextFilterEnabled(true);
mPackageManager = getPackageManager();
// Start loading the data
new LoadingTask().execute((Object[]) null);
}
@Override
protected void onListItemClick(ListView list, View view, int position, long id) {
ResolveInfoWrapper wrapper = (ResolveInfoWrapper) getListAdapter().getItem(position);
ResolveInfo info = wrapper.getInfo();
// Build the intent for the chosen activity
Intent intent = new Intent();
intent.setComponent(new ComponentName(info.activityInfo.applicationInfo.packageName,
info.activityInfo.name));
Intent result = new Intent();
result.putExtra(Intent.EXTRA_SHORTCUT_INTENT, intent);
// Set the name of the activity
result.putExtra(Intent.EXTRA_SHORTCUT_NAME, info.loadLabel(mPackageManager));
// Build the icon info for the activity
Drawable drawable = info.loadIcon(mPackageManager);
if (drawable instanceof BitmapDrawable) {
BitmapDrawable bd = (BitmapDrawable) drawable;
result.putExtra(Intent.EXTRA_SHORTCUT_ICON, bd.getBitmap());
}
// ShortcutIconResource iconResource = new ShortcutIconResource();
// iconResource.packageName = info.activityInfo.packageName;
// iconResource.resourceName = getResources().getResourceEntryName(info.getIconResource());
// result.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, iconResource);
// Set the result
setResult(RESULT_OK, result);
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.example.anycut;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;
/**
* The activity that shows up in the list of all applications. It has a button
* allowing the user to create a new shortcut, and guides them to using Any Cut
* through long pressing on the location of the desired shortcut.
*/
public class FrontDoorActivity extends Activity implements OnClickListener {
private static final int REQUEST_SHORTCUT = 1;
@Override
protected void onCreate(Bundle savedState) {
super.onCreate(savedState);
setContentView(R.layout.front_door);
// Setup the new shortcut button
View view = findViewById(R.id.newShortcut);
if (view != null) {
view.setOnClickListener(this);
}
}
public void onClick(View view) {
switch (view.getId()) {
case R.id.newShortcut: {
// Start the activity to create a shortcut intent
Intent intent = new Intent(this, CreateShortcutActivity.class);
startActivityForResult(intent, REQUEST_SHORTCUT);
break;
}
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent result) {
if (resultCode != RESULT_OK) {
return;
}
switch (requestCode) {
case REQUEST_SHORTCUT: {
// Boradcast an intent that tells the home screen to create a new shortcut
result.setAction("com.android.launcher.action.INSTALL_SHORTCUT");
sendBroadcast(result);
// Inform the user that the shortcut has been created
Toast.makeText(this, R.string.shortcutCreated, Toast.LENGTH_SHORT).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.clickin2dabeat;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
/**
* Creates a skeleton C2B file when an appropriate media object is opened.
*/
public class CreateC2BFile extends Activity {
private String dataSource;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
dataSource = this.getIntent().getData().toString();
setContentView(R.layout.c2b_creator_form);
Button create = ((Button) findViewById(R.id.CreateButton));
create.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
String title = ((EditText) findViewById(R.id.TitleEditText)).getText().toString();
String author = ((EditText) findViewById(R.id.AuthorEditText)).getText().toString();
if (!title.equals("") && !author.equals("")) {
createC2BSkeleton(title, author, dataSource);
finish();
}
}
});
Button cancel = ((Button) findViewById(R.id.CancelButton));
cancel.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
finish();
}
});
}
private void createC2BSkeleton(String title, String author, String media) {
String c2bDirStr = "/sdcard/c2b/";
String sanitizedTitle = title.replaceAll("'", " ");
String sanitizedAuthor = author.replaceAll("'", " ");
String filename = sanitizedTitle.replaceAll("[^a-zA-Z0-9,\\s]", "");
filename = c2bDirStr + filename + ".c2b";
String contents =
"<c2b title='" + title + "' level='1' author='" + author + "' media='" + media + "'></c2b>";
File c2bDir = new File(c2bDirStr);
boolean directoryExists = c2bDir.isDirectory();
if (!directoryExists) {
c2bDir.mkdir();
}
try {
FileWriter writer = new FileWriter(filename);
writer.write(contents);
writer.close();
Toast.makeText(CreateC2BFile.this, getString(R.string.STAGE_CREATED), 5000).show();
} catch (IOException e) {
Toast.makeText(CreateC2BFile.this, getString(R.string.NEED_SD_CARD), 30000).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.clickin2dabeat;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Vibrator;
import android.view.MotionEvent;
import android.view.View;
import java.util.ArrayList;
/**
* Draws the beat targets and takes user input.
* This view is used as the foreground; the background is the video
* being played.
*/
public class GameView extends View {
private static final long[] VIBE_PATTERN = {0, 1, 40, 41};
private static final int INTERVAL = 10; // in ms
private static final int PRE_THRESHOLD = 1000; // in ms
private static final int POST_THRESHOLD = 500; // in ms
private static final int TOLERANCE = 100; // in ms
private static final int POINTS_FOR_PERFECT = 100;
private static final double PENALTY_FACTOR = .25;
private static final double COMBO_FACTOR = .1;
private static final float TARGET_RADIUS = 50;
public static final String LAST_RATING_OK = "(^_')";
public static final String LAST_RATING_PERFECT = "(^_^)/";
public static final String LAST_RATING_MISS = "(X_X)";
private C2B parent;
private Vibrator vibe;
private SoundPool snd;
private int hitOkSfx;
private int hitPerfectSfx;
private int missSfx;
public int comboCount;
public int longestCombo;
public String lastRating;
Paint innerPaint;
Paint borderPaint;
Paint haloPaint;
private ArrayList<Target> drawnTargets;
private int lastTarget;
public ArrayList<Target> recordedTargets;
private int score;
public GameView(Context context) {
super(context);
parent = (C2B) context;
lastTarget = 0;
score = 0;
comboCount = 0;
longestCombo = 0;
lastRating = "";
drawnTargets = new ArrayList<Target>();
recordedTargets = new ArrayList<Target>();
vibe = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
snd = new SoundPool(10, AudioManager.STREAM_SYSTEM, 0);
missSfx = snd.load(context, R.raw.miss, 0);
hitOkSfx = snd.load(context, R.raw.ok, 0);
hitPerfectSfx = snd.load(context, R.raw.perfect, 0);
innerPaint = new Paint();
innerPaint.setColor(Color.argb(127, 0, 0, 0));
innerPaint.setStyle(Paint.Style.FILL);
borderPaint = new Paint();
borderPaint.setStyle(Paint.Style.STROKE);
borderPaint.setAntiAlias(true);
borderPaint.setStrokeWidth(2);
haloPaint = new Paint();
haloPaint.setStyle(Paint.Style.STROKE);
haloPaint.setAntiAlias(true);
haloPaint.setStrokeWidth(4);
Thread monitorThread = (new Thread(new Monitor()));
monitorThread.setPriority(Thread.MIN_PRIORITY);
monitorThread.start();
}
private void updateTargets() {
int i = lastTarget;
int currentTime = parent.getCurrentTime();
// Add any targets that are within the pre-threshold to the list of
// drawnTargets
boolean cont = true;
while (cont && (i < parent.targets.size())) {
if (parent.targets.get(i).time < currentTime + PRE_THRESHOLD) {
drawnTargets.add(parent.targets.get(i));
i++;
} else {
cont = false;
}
}
lastTarget = i;
// Move any expired targets out of drawn targets
for (int j = 0; j < drawnTargets.size(); j++) {
Target t = drawnTargets.get(j);
if (t == null) {
// Do nothing - this is a concurrency issue where
// the target is already gone, so just ignore it
} else if (t.time + POST_THRESHOLD < currentTime) {
try {
drawnTargets.remove(j);
} catch (IndexOutOfBoundsException e){
// Do nothing here, j is already gone
}
if (longestCombo < comboCount) {
longestCombo = comboCount;
}
comboCount = 0;
lastRating = LAST_RATING_MISS;
}
}
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
int currentTime = parent.getCurrentTime();
float x = event.getX();
float y = event.getY();
boolean hadHit = false;
if (parent.mode == C2B.ONEPASS_MODE) { // Record this point as a target
hadHit = true;
snd.play(hitPerfectSfx, 1, 1, 0, 0, 1);
Target targ = new Target(currentTime, (int) x, (int) y, "");
recordedTargets.add(targ);
} else if (parent.mode == C2B.TWOPASS_MODE) {
hadHit = true;
parent.beatTimes.add(currentTime);
} else { // Play the game normally
for (int i = 0; i < drawnTargets.size(); i++) {
if (hitTarget(x, y, drawnTargets.get(i))) {
Target t = drawnTargets.get(i);
int points;
double timeDiff = Math.abs(currentTime - t.time);
if (timeDiff < TOLERANCE) {
points = POINTS_FOR_PERFECT;
snd.play(hitPerfectSfx, 1, 1, 0, 0, 1);
lastRating = LAST_RATING_PERFECT;
} else {
points = (int) (POINTS_FOR_PERFECT - (timeDiff * PENALTY_FACTOR));
points = points + (int) (points * (comboCount * COMBO_FACTOR));
snd.play(hitOkSfx, 1, 1, 0, 0, 1);
lastRating = LAST_RATING_OK;
}
if (points > 0) {
score = score + points;
hadHit = true;
}
drawnTargets.remove(i);
break;
}
}
}
if (hadHit) {
comboCount++;
} else {
if (longestCombo < comboCount) {
longestCombo = comboCount;
}
comboCount = 0;
snd.play(missSfx, 1, 1, 0, 0, 1);
lastRating = LAST_RATING_MISS;
}
vibe.vibrate(VIBE_PATTERN, -1);
}
return true;
}
private boolean hitTarget(float x, float y, Target t) {
if (t == null) {
return false;
}
// Use the pythagorean theorem to solve this.
float xSquared = (t.x - x) * (t.x - x);
float ySquared = (t.y - y) * (t.y - y);
if ((xSquared + ySquared) < (TARGET_RADIUS * TARGET_RADIUS)) {
return true;
}
return false;
}
@Override
public void onDraw(Canvas canvas) {
if (parent.mode != C2B.GAME_MODE) {
return;
}
int currentTime = parent.getCurrentTime();
// Draw the circles
for (int i = 0; i < drawnTargets.size(); i++) {
Target t = drawnTargets.get(i);
if (t == null) {
break;
}
// Insides should be semi-transparent
canvas.drawCircle(t.x, t.y, TARGET_RADIUS, innerPaint);
// Set colors for the target
borderPaint.setColor(t.color);
haloPaint.setColor(t.color);
// Perfect timing == hitting the halo inside the borders
canvas.drawCircle(t.x, t.y, TARGET_RADIUS - 5, borderPaint);
canvas.drawCircle(t.x, t.y, TARGET_RADIUS, borderPaint);
// Draw timing halos - may need to change the formula here
float percentageOff = ((float) (t.time - currentTime)) / PRE_THRESHOLD;
int haloSize = (int) (TARGET_RADIUS + (percentageOff * TARGET_RADIUS));
canvas.drawCircle(t.x, t.y, haloSize, haloPaint);
}
// Score and Combo info
String scoreText = "Score: " + Integer.toString(score);
int x = getWidth() - 100; // Fudge factor for making it on the top right
// corner
int y = 30;
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(Color.RED);
paint.setTextAlign(Paint.Align.CENTER);
paint.setTextSize(24);
paint.setTypeface(Typeface.DEFAULT_BOLD);
y -= paint.ascent() / 2;
canvas.drawText(scoreText, x, y, paint);
x = getWidth() / 2;
canvas.drawText(lastRating, x, y, paint);
String comboText = "Combo: " + Integer.toString(comboCount);
x = 60;
canvas.drawText(comboText, x, y, paint);
}
private class Monitor implements Runnable {
public void run() {
while (true) {
try {
Thread.sleep(INTERVAL);
} catch (InterruptedException e) {
// This should not be interrupted. If it is, just dump the stack
// trace.
e.printStackTrace();
}
updateTargets();
postInvalidate();
}
}
}
}
| 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.clickin2dabeat;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.os.Bundle;
public class DownloadC2BFile extends Activity {
String dataSource;
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
dataSource = this.getIntent().getData().toString();
(new Thread(new loader())).start();
}
public void runMem() {
startApp("com.google.clickin2dabeat", "C2B");
finish();
}
private void startApp(String packageName, String className) {
try {
int flags = Context.CONTEXT_INCLUDE_CODE | Context.CONTEXT_IGNORE_SECURITY;
Context myContext = createPackageContext(packageName, flags);
Class<?> appClass = myContext.getClassLoader().loadClass(packageName + "." + className);
Intent intent = new Intent(myContext, appClass);
startActivity(intent);
} catch (NameNotFoundException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public class loader implements Runnable {
public void run() {
Unzipper.unzip(dataSource);
runMem();
}
}
}
| Java |
package com.google.clickin2dabeat;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
/**
* Checks for updates to the game.
*/
public class UpdateChecker {
public String marketId;
@SuppressWarnings("finally")
public int getLatestVersionCode() {
int version = 0;
try {
URLConnection cn;
URL url =
new URL(
"http://apps-for-android.googlecode.com/svn/trunk/CLiCkin2DaBeaT/AndroidManifest.xml");
cn = url.openConnection();
cn.connect();
InputStream stream = cn.getInputStream();
DocumentBuilder docBuild = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document manifestDoc = docBuild.parse(stream);
NodeList manifestNodeList = manifestDoc.getElementsByTagName("manifest");
String versionStr =
manifestNodeList.item(0).getAttributes().getNamedItem("android:versionCode")
.getNodeValue();
version = Integer.parseInt(versionStr);
NodeList clcNodeList = manifestDoc.getElementsByTagName("clc");
marketId = clcNodeList.item(0).getAttributes().getNamedItem("marketId").getNodeValue();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FactoryConfigurationError e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
return version;
}
}
public void checkForNewerVersion(int currentVersion) {
int latestVersion = getLatestVersionCode();
if (latestVersion > currentVersion) {
}
}
}
| 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.clickin2dabeat;
import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.content.ComponentName;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Resources;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.net.Uri;
import android.os.Bundle;
import android.widget.FrameLayout;
import android.widget.Toast;
import android.widget.VideoView;
import org.w3c.dom.Document;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.FilenameFilter;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.FactoryConfigurationError;
import javax.xml.parsers.ParserConfigurationException;
/**
* A rhythm/music game for Android that can use any video as the background.
*/
public class C2B extends Activity {
public static final int GAME_MODE = 0;
public static final int TWOPASS_MODE = 1;
public static final int ONEPASS_MODE = 2;
public int mode;
public boolean wasEditMode;
private boolean forceEditMode;
private VideoView background;
private GameView foreground;
private FrameLayout layout;
private String c2bFileName;
private String[] filenames;
private String marketId;
// These are parsed in from the C2B file
private String title;
private String author;
private String level;
private String media;
private Uri videoUri;
public ArrayList<Target> targets;
public ArrayList<Integer> beatTimes;
private BeatTimingsAdjuster timingAdjuster;
private boolean busyProcessing;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
UpdateChecker checker = new UpdateChecker();
int latestVersion = checker.getLatestVersionCode();
String packageName = C2B.class.getPackage().getName();
int currentVersion = 0;
try {
currentVersion = getPackageManager().getPackageInfo(packageName, 0).versionCode;
} catch (NameNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (latestVersion > currentVersion){
marketId = checker.marketId;
displayUpdateMessage();
} else {
resetGame();
}
}
private void resetGame() {
targets = new ArrayList<Target>();
mode = GAME_MODE;
forceEditMode = false;
wasEditMode = false;
busyProcessing = false;
c2bFileName = "";
title = "";
author = "";
level = "";
media = "";
background = null;
foreground = null;
layout = null;
background = new VideoView(this);
foreground = new GameView(this);
layout = new FrameLayout(this);
layout.addView(background);
layout.setPadding(30, 0, 0, 0); // Is there a better way to do layout?
beatTimes = null;
timingAdjuster = null;
background.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
background.start();
}
});
background.setOnErrorListener(new OnErrorListener() {
public boolean onError(MediaPlayer arg0, int arg1, int arg2) {
background.setVideoURI(videoUri);
return true;
}
});
background.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
if (mode == ONEPASS_MODE) {
Toast waitMessage = Toast.makeText(C2B.this, getString(R.string.PROCESSING), 5000);
waitMessage.show();
(new Thread(new BeatsWriter())).start();
} else if (mode == TWOPASS_MODE) {
mode = ONEPASS_MODE;
(new Thread(new BeatsTimingAdjuster())).start();
displayCreateLevelInfo();
return;
}
displayStats();
}
});
layout.addView(foreground);
setContentView(layout);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
displayStartupMessage();
}
private void writeC2BFile(String filename) {
String contents =
"<c2b title='" + title + "' level='" + level + "' author='" + author + "' media='" + media
+ "'>";
ArrayList<Target> targets = foreground.recordedTargets;
if (timingAdjuster != null) {
targets = timingAdjuster.adjustBeatTargets(foreground.recordedTargets);
}
for (int i = 0; i < targets.size(); i++) {
Target t = targets.get(i);
contents = contents + "<beat time='" + Double.toString(t.time) + "' ";
contents = contents + "x='" + Integer.toString(t.x) + "' ";
contents = contents + "y='" + Integer.toString(t.y) + "' ";
contents = contents + "color='" + Integer.toHexString(t.color) + "'/>";
}
contents = contents + "</c2b>";
try {
FileWriter writer = new FileWriter(filename);
writer.write(contents);
writer.close();
} catch (IOException e) {
// TODO(clchen): Do better error handling here
e.printStackTrace();
}
}
private void loadC2B(String fileUriString) {
try {
FileInputStream fis = new FileInputStream(fileUriString);
DocumentBuilder docBuild;
docBuild = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document c2b = docBuild.parse(fis);
runC2B(c2b);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FactoryConfigurationError e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void runC2B(Document c2b) {
Node root = c2b.getElementsByTagName("c2b").item(0);
title = root.getAttributes().getNamedItem("title").getNodeValue();
author = root.getAttributes().getNamedItem("author").getNodeValue();
level = root.getAttributes().getNamedItem("level").getNodeValue();
media = root.getAttributes().getNamedItem("media").getNodeValue();
NodeList beats = c2b.getElementsByTagName("beat");
targets = new ArrayList<Target>();
for (int i = 0; i < beats.getLength(); i++) {
NamedNodeMap attribs = beats.item(i).getAttributes();
double time = Double.parseDouble(attribs.getNamedItem("time").getNodeValue());
int x = Integer.parseInt(attribs.getNamedItem("x").getNodeValue());
int y = Integer.parseInt(attribs.getNamedItem("y").getNodeValue());
String colorStr = attribs.getNamedItem("color").getNodeValue();
targets.add(new Target(time, x, y, colorStr));
}
if ((beats.getLength() == 0) || forceEditMode) {
displayCreateLevelAlert();
} else {
videoUri = Uri.parse(media);
background.setVideoURI(videoUri);
}
}
private void displayCreateLevelAlert() {
mode = ONEPASS_MODE;
Builder createLevelAlert = new Builder(this);
String titleText = getString(R.string.NO_BEATS) + " \"" + title + "\"";
createLevelAlert.setTitle(titleText);
String[] choices = new String[2];
choices[0] = getString(R.string.ONE_PASS);
choices[1] = getString(R.string.TWO_PASS);
createLevelAlert.setSingleChoiceItems(choices, 0, new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (which == 0) {
mode = ONEPASS_MODE;
} else {
mode = TWOPASS_MODE;
}
}
});
createLevelAlert.setPositiveButton("Ok", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (busyProcessing) {
Toast.makeText(C2B.this, R.string.STILL_BUSY, 5000).show();
displayCreateLevelAlert();
return;
}
wasEditMode = true;
if (mode == TWOPASS_MODE) {
beatTimes = new ArrayList<Integer>();
timingAdjuster = new BeatTimingsAdjuster();
}
displayCreateLevelInfo();
}
});
createLevelAlert.setNegativeButton("Cancel", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (busyProcessing) {
Toast.makeText(C2B.this, R.string.STILL_BUSY, 5000).show();
displayCreateLevelAlert();
return;
}
displayC2BFiles();
}
});
createLevelAlert.setCancelable(false);
createLevelAlert.show();
}
private void displayC2BFiles() {
Builder c2bFilesAlert = new Builder(this);
String titleText = getString(R.string.CHOOSE_STAGE);
c2bFilesAlert.setTitle(titleText);
File c2bDir = new File("/sdcard/c2b/");
filenames = c2bDir.list(new FilenameFilter() {
public boolean accept(File dir, String filename) {
return filename.endsWith(".c2b");
}
});
if (filenames == null) {
displayNoFilesMessage();
return;
}
if (filenames.length == 0) {
displayNoFilesMessage();
return;
}
c2bFilesAlert.setSingleChoiceItems(filenames, -1, new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
c2bFileName = "/sdcard/c2b/" + filenames[which];
}
});
c2bFilesAlert.setPositiveButton("Go!", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
loadC2B(c2bFileName);
dialog.dismiss();
}
});
/*
c2bFilesAlert.setNeutralButton("Set new beats", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
displaySetNewBeatsConfirmation();
}
});
*/
final Activity self = this;
c2bFilesAlert.setNeutralButton(getString(R.string.MOAR_STAGES), new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent i = new Intent();
ComponentName comp =
new ComponentName("com.android.browser", "com.android.browser.BrowserActivity");
i.setComponent(comp);
i.setAction("android.intent.action.VIEW");
i.addCategory("android.intent.category.BROWSABLE");
Uri uri = Uri.parse("http://groups.google.com/group/clickin-2-da-beat/files");
i.setData(uri);
self.startActivity(i);
finish();
}
});
c2bFilesAlert.setNegativeButton(getString(R.string.QUIT), new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
c2bFilesAlert.setCancelable(false);
c2bFilesAlert.show();
}
/*
private void displaySetNewBeatsConfirmation() {
Builder setNewBeatsConfirmation = new Builder(this);
String titleText = getString(R.string.EDIT_CONFIRMATION);
setNewBeatsConfirmation.setTitle(titleText);
String message = getString(R.string.EDIT_WARNING);
setNewBeatsConfirmation.setMessage(message);
setNewBeatsConfirmation.setPositiveButton("Continue", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
forceEditMode = true;
loadC2B(c2bFileName);
dialog.dismiss();
}
});
setNewBeatsConfirmation.setNegativeButton("Cancel", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
displayC2BFiles();
dialog.dismiss();
}
});
setNewBeatsConfirmation.setCancelable(false);
setNewBeatsConfirmation.show();
}
*/
private void displayCreateLevelInfo() {
Builder createLevelInfoAlert = new Builder(this);
String titleText = getString(R.string.BEAT_SETTING_INFO);
createLevelInfoAlert.setTitle(titleText);
String message = "";
if (mode == TWOPASS_MODE) {
message = getString(R.string.TWO_PASS_INFO);
} else {
message = getString(R.string.ONE_PASS_INFO);
}
createLevelInfoAlert.setMessage(message);
createLevelInfoAlert.setPositiveButton("Start", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
videoUri = Uri.parse(media);
background.setVideoURI(videoUri);
}
});
createLevelInfoAlert.setCancelable(false);
createLevelInfoAlert.show();
}
private void displayStats() {
Builder statsAlert = new Builder(this);
String titleText = "";
if (!wasEditMode) {
titleText = "Game Over";
} else {
titleText = "Stage created!";
}
statsAlert.setTitle(titleText);
int longestCombo = foreground.longestCombo;
if (foreground.comboCount > longestCombo) {
longestCombo = foreground.comboCount;
}
String message = "";
if (!wasEditMode) {
message = "Longest combo: " + Integer.toString(longestCombo);
} else {
message = "Beats recorded!";
}
statsAlert.setMessage(message);
statsAlert.setPositiveButton("Play", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (busyProcessing) {
Toast.makeText(C2B.this, R.string.STILL_BUSY, 5000).show();
displayStats();
return;
}
resetGame();
}
});
statsAlert.setNegativeButton("Quit", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
if (busyProcessing) {
Toast.makeText(C2B.this, R.string.STILL_BUSY, 5000).show();
displayStats();
return;
}
finish();
}
});
statsAlert.setCancelable(false);
statsAlert.show();
}
private void displayNoFilesMessage() {
Builder noFilesMessage = new Builder(this);
String titleText = getString(R.string.NO_STAGES_FOUND);
noFilesMessage.setTitle(titleText);
String message = getString(R.string.NO_STAGES_INFO);
noFilesMessage.setMessage(message);
noFilesMessage.setPositiveButton(getString(R.string.SHUT_UP), new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
loadHardCodedRickroll();
}
});
final Activity self = this;
noFilesMessage.setNeutralButton(getString(R.string.ILL_GET_STAGES), new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent i = new Intent();
ComponentName comp =
new ComponentName("com.android.browser", "com.android.browser.BrowserActivity");
i.setComponent(comp);
i.setAction("android.intent.action.VIEW");
i.addCategory("android.intent.category.BROWSABLE");
Uri uri = Uri.parse("http://groups.google.com/group/clickin-2-da-beat/files");
i.setData(uri);
self.startActivity(i);
finish();
}
});
noFilesMessage.setNegativeButton(getString(R.string.QUIT),
new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
noFilesMessage.setCancelable(false);
noFilesMessage.show();
}
private void loadHardCodedRickroll() {
try {
Resources res = getResources();
InputStream fis = res.openRawResource(R.raw.rickroll);
DocumentBuilder docBuild;
docBuild = DocumentBuilderFactory.newInstance().newDocumentBuilder();
Document c2b = docBuild.parse(fis);
runC2B(c2b);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ParserConfigurationException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FactoryConfigurationError e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void displayStartupMessage() {
Builder startupMessage = new Builder(this);
String titleText = getString(R.string.WELCOME);
startupMessage.setTitle(titleText);
String message = getString(R.string.BETA_MESSAGE);
startupMessage.setMessage(message);
startupMessage.setPositiveButton(getString(R.string.START_GAME), new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
displayC2BFiles();
}
});
final Activity self = this;
startupMessage.setNeutralButton(getString(R.string.VISIT_WEBSITE), new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent i = new Intent();
ComponentName comp =
new ComponentName("com.android.browser", "com.android.browser.BrowserActivity");
i.setComponent(comp);
i.setAction("android.intent.action.VIEW");
i.addCategory("android.intent.category.BROWSABLE");
Uri uri = Uri.parse("http://groups.google.com/group/clickin-2-da-beat");
i.setData(uri);
self.startActivity(i);
finish();
}
});
startupMessage.setNegativeButton(getString(R.string.QUIT), new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
startupMessage.setCancelable(false);
startupMessage.show();
}
private void displayUpdateMessage() {
Builder updateMessage = new Builder(this);
String titleText = getString(R.string.UPDATE_AVAILABLE);
updateMessage.setTitle(titleText);
String message = getString(R.string.UPDATE_MESSAGE);
updateMessage.setMessage(message);
updateMessage.setPositiveButton("Yes", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Uri marketUri = Uri.parse("market://details?id=" + marketId);
Intent marketIntent = new Intent(Intent.ACTION_VIEW, marketUri);
startActivity(marketIntent);
finish();
}
});
final Activity self = this;
updateMessage.setNegativeButton("No", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
resetGame();
}
});
updateMessage.setCancelable(false);
updateMessage.show();
}
public int getCurrentTime() {
try {
return background.getCurrentPosition();
} catch (IllegalStateException e) {
// This will be thrown if the player is exiting mid-game and the video
// view is going away at the same time as the foreground is trying to get
// the position. This error can be safely ignored without doing anything.
e.printStackTrace();
return 0;
}
}
// Do beats processing in another thread to avoid hogging the UI thread and
// generating a "not responding" error
public class BeatsWriter implements Runnable {
public void run() {
writeC2BFile(c2bFileName);
busyProcessing = false;
}
}
public class BeatsTimingAdjuster implements Runnable {
public void run() {
timingAdjuster.setRawBeatTimes(beatTimes);
busyProcessing = 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.clickin2dabeat;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.zip.ZipFile;
public class Unzipper {
public static String download(String fileUrl) {
URLConnection cn;
try {
fileUrl = (new URL(new URL(fileUrl), fileUrl)).toString();
URL url = new URL(fileUrl);
cn = url.openConnection();
cn.connect();
InputStream stream = cn.getInputStream();
File outputDir = new File("/sdcard/c2b/");
outputDir.mkdirs();
String filename = fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
filename = filename.substring(0, filename.indexOf("c2b.zip") + 7);
File outputFile = new File("/sdcard/c2b/", filename);
outputFile.createNewFile();
FileOutputStream out = new FileOutputStream(outputFile);
byte buf[] = new byte[16384];
do {
int numread = stream.read(buf);
if (numread <= 0) {
break;
} else {
out.write(buf, 0, numread);
}
} while (true);
stream.close();
out.close();
return "/sdcard/c2b/" + filename;
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "";
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return "";
}
}
public static void unzip(String fileUrl) {
try {
String filename = download(fileUrl);
ZipFile zip = new ZipFile(filename);
Enumeration<? extends ZipEntry> zippedFiles = zip.entries();
while (zippedFiles.hasMoreElements()) {
ZipEntry entry = zippedFiles.nextElement();
InputStream is = zip.getInputStream(entry);
String name = entry.getName();
File outputFile = new File("/sdcard/c2b/" + name);
String outputPath = outputFile.getCanonicalPath();
name = outputPath.substring(outputPath.lastIndexOf("/") + 1);
outputPath = outputPath.substring(0, outputPath.lastIndexOf("/"));
File outputDir = new File(outputPath);
outputDir.mkdirs();
outputFile = new File(outputPath, name);
outputFile.createNewFile();
FileOutputStream out = new FileOutputStream(outputFile);
byte buf[] = new byte[16384];
do {
int numread = is.read(buf);
if (numread <= 0) {
break;
} else {
out.write(buf, 0, numread);
}
} while (true);
is.close();
out.close();
}
File theZipFile = new File(filename);
theZipFile.delete();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
| 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.clickin2dabeat;
import android.graphics.Color;
/**
* Contains information about the when the beat should be displayed, where it
* should be displayed, and what color it should be.
*/
public class Target {
public double time;
public int x;
public int y;
public int color;
public Target(double timeToHit, int xpos, int ypos, String hexColor) {
time = timeToHit;
x = xpos;
y = ypos;
if (hexColor.length() == 6) {
int r = Integer.parseInt(hexColor.substring(0, 2), 16);
int g = Integer.parseInt(hexColor.substring(2, 4), 16);
int b = Integer.parseInt(hexColor.substring(4, 6), 16);
color = Color.rgb(r, g, b);
} else {
int colorChoice = ((int) (Math.random() * 100)) % 4;
if (colorChoice == 0) {
color = Color.RED;
} else if (colorChoice == 1) {
color = Color.GREEN;
} else if (colorChoice == 2) {
color = Color.BLUE;
} else {
color = Color.YELLOW;
}
}
}
}
| 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.clickin2dabeat;
import java.util.ArrayList;
/**
* Adjusts the times for the beat targets using a linear least-squares fit.
*/
public class BeatTimingsAdjuster {
private double[] adjustedBeatTimes;
public void setRawBeatTimes(ArrayList<Integer> rawBeatTimes) {
double[] beatTimes = new double[rawBeatTimes.size()];
for (int i = 0; i < beatTimes.length; i++) {
beatTimes[i] = rawBeatTimes.get(i);
}
adjustedBeatTimes = new double[beatTimes.length];
double[] beatNumbers = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
double n = beatNumbers.length;
// Some things can be computed once and never computed again
double[] beatNumbersXNumbers = multiplyArrays(beatNumbers, beatNumbers);
double sumOfBeatNumbersXNumbers = sum(beatNumbersXNumbers);
double sumOfBeatNumbers = sum(beatNumbers);
// The divisor is:
// (n * sum(beatNumbersXNumbers) - (sum(beatNumbers) * sum(beatNumbers)))
// Since these are all constants, they can be computed first for better
// efficiency.
double divisor = (n * sum(beatNumbersXNumbers) - (sum(beatNumbers) * sum(beatNumbers)));
// Not enough data to adjust for the first 5 beats
for (int i = 0; (i < beatTimes.length) && (i < 5); i++) {
adjustedBeatTimes[i] = beatTimes[i];
}
// Adjust time for beat i by using timings for beats i-5 through i+5
double[] beatWindow = new double[beatNumbers.length];
for (int i = 0; i < beatTimes.length - 10; i++) {
System.arraycopy(beatTimes, i, beatWindow, 0, beatNumbers.length);
double[] beatNumbersXTimes = multiplyArrays(beatNumbers, beatWindow);
double a =
(sum(beatTimes) * sumOfBeatNumbersXNumbers - sumOfBeatNumbers * sum(beatNumbersXTimes))
/ divisor;
double b = (n * sum(beatNumbersXTimes) - sumOfBeatNumbers * sum(beatTimes)) / divisor;
adjustedBeatTimes[i + 5] = a + b * beatNumbers[5];
}
if (beatTimes.length - 10 < 0) {
return;
}
// Not enough data to adjust for the last 5 beats
for (int i = beatTimes.length - 10; i < beatTimes.length; i++) {
adjustedBeatTimes[i] = beatTimes[i];
}
}
public ArrayList<Target> adjustBeatTargets(ArrayList<Target> rawTargets) {
ArrayList<Target> adjustedTargets = new ArrayList<Target>();
int j = 0;
double threshold = 200;
for (int i = 0; i < rawTargets.size(); i++) {
Target t = rawTargets.get(i);
while ((j < adjustedBeatTimes.length) && (adjustedBeatTimes[j] < t.time)) {
j++;
}
double prevTime = 0;
if (j > 0) {
prevTime = adjustedBeatTimes[j - 1];
}
double postTime = -1;
if (j < adjustedBeatTimes.length) {
postTime = adjustedBeatTimes[j];
}
if ((Math.abs(t.time - prevTime) < Math.abs(t.time - postTime))
&& Math.abs(t.time - prevTime) < threshold) {
t.time = prevTime;
} else if ((Math.abs(t.time - prevTime) > Math.abs(t.time - postTime))
&& Math.abs(t.time - postTime) < threshold) {
t.time = postTime;
}
adjustedTargets.add(t);
}
return adjustedTargets;
}
private double sum(double[] numbers) {
double sum = 0;
for (int i = 0; i < numbers.length; i++) {
sum = sum + numbers[i];
}
return sum;
}
private double[] multiplyArrays(double[] numberSetA, double[] numberSetB) {
double[] sqArray = new double[numberSetA.length];
for (int i = 0; i < numberSetA.length; i++) {
sqArray[i] = numberSetA[i] * numberSetB[i];
}
return sqArray;
}
}
| Java |
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You 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 java.io.IOException;
import java.io.StringWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;
/**
* <p>
* Provides HTML and XML entity utilities.
* </p>
*
* @see <a href="http://hotwired.lycos.com/webmonkey/reference/special_characters/">ISO Entities</a>
* @see <a href="http://www.w3.org/TR/REC-html32#latin1">HTML 3.2 Character Entities for ISO Latin-1</a>
* @see <a href="http://www.w3.org/TR/REC-html40/sgml/entities.html">HTML 4.0 Character entity references</a>
* @see <a href="http://www.w3.org/TR/html401/charset.html#h-5.3">HTML 4.01 Character References</a>
* @see <a href="http://www.w3.org/TR/html401/charset.html#code-position">HTML 4.01 Code positions</a>
*
* @author <a href="mailto:alex@purpletech.com">Alexander Day Chaffee</a>
* @author <a href="mailto:ggregory@seagullsw.com">Gary Gregory</a>
* @since 2.0
* @version $Id: Entities.java 636641 2008-03-13 06:11:30Z bayard $
*/
class Entities {
private static final String[][] BASIC_ARRAY = {{"quot", "34"}, // " - double-quote
{"amp", "38"}, // & - ampersand
{"lt", "60"}, // < - less-than
{"gt", "62"}, // > - greater-than
};
private static final String[][] APOS_ARRAY = {{"apos", "39"}, // XML apostrophe
};
// package scoped for testing
static final String[][] ISO8859_1_ARRAY = {{"nbsp", "160"}, // non-breaking space
{"iexcl", "161"}, // inverted exclamation mark
{"cent", "162"}, // cent sign
{"pound", "163"}, // pound sign
{"curren", "164"}, // currency sign
{"yen", "165"}, // yen sign = yuan sign
{"brvbar", "166"}, // broken bar = broken vertical bar
{"sect", "167"}, // section sign
{"uml", "168"}, // diaeresis = spacing diaeresis
{"copy", "169"}, // - copyright sign
{"ordf", "170"}, // feminine ordinal indicator
{"laquo", "171"}, // left-pointing double angle quotation mark = left pointing guillemet
{"not", "172"}, // not sign
{"shy", "173"}, // soft hyphen = discretionary hyphen
{"reg", "174"}, // - registered trademark sign
{"macr", "175"}, // macron = spacing macron = overline = APL overbar
{"deg", "176"}, // degree sign
{"plusmn", "177"}, // plus-minus sign = plus-or-minus sign
{"sup2", "178"}, // superscript two = superscript digit two = squared
{"sup3", "179"}, // superscript three = superscript digit three = cubed
{"acute", "180"}, // acute accent = spacing acute
{"micro", "181"}, // micro sign
{"para", "182"}, // pilcrow sign = paragraph sign
{"middot", "183"}, // middle dot = Georgian comma = Greek middle dot
{"cedil", "184"}, // cedilla = spacing cedilla
{"sup1", "185"}, // superscript one = superscript digit one
{"ordm", "186"}, // masculine ordinal indicator
{"raquo", "187"}, // right-pointing double angle quotation mark = right pointing guillemet
{"frac14", "188"}, // vulgar fraction one quarter = fraction one quarter
{"frac12", "189"}, // vulgar fraction one half = fraction one half
{"frac34", "190"}, // vulgar fraction three quarters = fraction three quarters
{"iquest", "191"}, // inverted question mark = turned question mark
{"Agrave", "192"}, // - uppercase A, grave accent
{"Aacute", "193"}, // - uppercase A, acute accent
{"Acirc", "194"}, // - uppercase A, circumflex accent
{"Atilde", "195"}, // - uppercase A, tilde
{"Auml", "196"}, // - uppercase A, umlaut
{"Aring", "197"}, // - uppercase A, ring
{"AElig", "198"}, // - uppercase AE
{"Ccedil", "199"}, // - uppercase C, cedilla
{"Egrave", "200"}, // - uppercase E, grave accent
{"Eacute", "201"}, // - uppercase E, acute accent
{"Ecirc", "202"}, // - uppercase E, circumflex accent
{"Euml", "203"}, // - uppercase E, umlaut
{"Igrave", "204"}, // - uppercase I, grave accent
{"Iacute", "205"}, // - uppercase I, acute accent
{"Icirc", "206"}, // - uppercase I, circumflex accent
{"Iuml", "207"}, // - uppercase I, umlaut
{"ETH", "208"}, // - uppercase Eth, Icelandic
{"Ntilde", "209"}, // - uppercase N, tilde
{"Ograve", "210"}, // - uppercase O, grave accent
{"Oacute", "211"}, // - uppercase O, acute accent
{"Ocirc", "212"}, // - uppercase O, circumflex accent
{"Otilde", "213"}, // - uppercase O, tilde
{"Ouml", "214"}, // - uppercase O, umlaut
{"times", "215"}, // multiplication sign
{"Oslash", "216"}, // - uppercase O, slash
{"Ugrave", "217"}, // - uppercase U, grave accent
{"Uacute", "218"}, // - uppercase U, acute accent
{"Ucirc", "219"}, // - uppercase U, circumflex accent
{"Uuml", "220"}, // - uppercase U, umlaut
{"Yacute", "221"}, // - uppercase Y, acute accent
{"THORN", "222"}, // - uppercase THORN, Icelandic
{"szlig", "223"}, // - lowercase sharps, German
{"agrave", "224"}, // - lowercase a, grave accent
{"aacute", "225"}, // - lowercase a, acute accent
{"acirc", "226"}, // - lowercase a, circumflex accent
{"atilde", "227"}, // - lowercase a, tilde
{"auml", "228"}, // - lowercase a, umlaut
{"aring", "229"}, // - lowercase a, ring
{"aelig", "230"}, // - lowercase ae
{"ccedil", "231"}, // - lowercase c, cedilla
{"egrave", "232"}, // - lowercase e, grave accent
{"eacute", "233"}, // - lowercase e, acute accent
{"ecirc", "234"}, // - lowercase e, circumflex accent
{"euml", "235"}, // - lowercase e, umlaut
{"igrave", "236"}, // - lowercase i, grave accent
{"iacute", "237"}, // - lowercase i, acute accent
{"icirc", "238"}, // - lowercase i, circumflex accent
{"iuml", "239"}, // - lowercase i, umlaut
{"eth", "240"}, // - lowercase eth, Icelandic
{"ntilde", "241"}, // - lowercase n, tilde
{"ograve", "242"}, // - lowercase o, grave accent
{"oacute", "243"}, // - lowercase o, acute accent
{"ocirc", "244"}, // - lowercase o, circumflex accent
{"otilde", "245"}, // - lowercase o, tilde
{"ouml", "246"}, // - lowercase o, umlaut
{"divide", "247"}, // division sign
{"oslash", "248"}, // - lowercase o, slash
{"ugrave", "249"}, // - lowercase u, grave accent
{"uacute", "250"}, // - lowercase u, acute accent
{"ucirc", "251"}, // - lowercase u, circumflex accent
{"uuml", "252"}, // - lowercase u, umlaut
{"yacute", "253"}, // - lowercase y, acute accent
{"thorn", "254"}, // - lowercase thorn, Icelandic
{"yuml", "255"}, // - lowercase y, umlaut
};
// http://www.w3.org/TR/REC-html40/sgml/entities.html
// package scoped for testing
static final String[][] HTML40_ARRAY = {
// <!-- Latin Extended-B -->
{"fnof", "402"}, // latin small f with hook = function= florin, U+0192 ISOtech -->
// <!-- Greek -->
{"Alpha", "913"}, // greek capital letter alpha, U+0391 -->
{"Beta", "914"}, // greek capital letter beta, U+0392 -->
{"Gamma", "915"}, // greek capital letter gamma,U+0393 ISOgrk3 -->
{"Delta", "916"}, // greek capital letter delta,U+0394 ISOgrk3 -->
{"Epsilon", "917"}, // greek capital letter epsilon, U+0395 -->
{"Zeta", "918"}, // greek capital letter zeta, U+0396 -->
{"Eta", "919"}, // greek capital letter eta, U+0397 -->
{"Theta", "920"}, // greek capital letter theta,U+0398 ISOgrk3 -->
{"Iota", "921"}, // greek capital letter iota, U+0399 -->
{"Kappa", "922"}, // greek capital letter kappa, U+039A -->
{"Lambda", "923"}, // greek capital letter lambda,U+039B ISOgrk3 -->
{"Mu", "924"}, // greek capital letter mu, U+039C -->
{"Nu", "925"}, // greek capital letter nu, U+039D -->
{"Xi", "926"}, // greek capital letter xi, U+039E ISOgrk3 -->
{"Omicron", "927"}, // greek capital letter omicron, U+039F -->
{"Pi", "928"}, // greek capital letter pi, U+03A0 ISOgrk3 -->
{"Rho", "929"}, // greek capital letter rho, U+03A1 -->
// <!-- there is no Sigmaf, and no U+03A2 character either -->
{"Sigma", "931"}, // greek capital letter sigma,U+03A3 ISOgrk3 -->
{"Tau", "932"}, // greek capital letter tau, U+03A4 -->
{"Upsilon", "933"}, // greek capital letter upsilon,U+03A5 ISOgrk3 -->
{"Phi", "934"}, // greek capital letter phi,U+03A6 ISOgrk3 -->
{"Chi", "935"}, // greek capital letter chi, U+03A7 -->
{"Psi", "936"}, // greek capital letter psi,U+03A8 ISOgrk3 -->
{"Omega", "937"}, // greek capital letter omega,U+03A9 ISOgrk3 -->
{"alpha", "945"}, // greek small letter alpha,U+03B1 ISOgrk3 -->
{"beta", "946"}, // greek small letter beta, U+03B2 ISOgrk3 -->
{"gamma", "947"}, // greek small letter gamma,U+03B3 ISOgrk3 -->
{"delta", "948"}, // greek small letter delta,U+03B4 ISOgrk3 -->
{"epsilon", "949"}, // greek small letter epsilon,U+03B5 ISOgrk3 -->
{"zeta", "950"}, // greek small letter zeta, U+03B6 ISOgrk3 -->
{"eta", "951"}, // greek small letter eta, U+03B7 ISOgrk3 -->
{"theta", "952"}, // greek small letter theta,U+03B8 ISOgrk3 -->
{"iota", "953"}, // greek small letter iota, U+03B9 ISOgrk3 -->
{"kappa", "954"}, // greek small letter kappa,U+03BA ISOgrk3 -->
{"lambda", "955"}, // greek small letter lambda,U+03BB ISOgrk3 -->
{"mu", "956"}, // greek small letter mu, U+03BC ISOgrk3 -->
{"nu", "957"}, // greek small letter nu, U+03BD ISOgrk3 -->
{"xi", "958"}, // greek small letter xi, U+03BE ISOgrk3 -->
{"omicron", "959"}, // greek small letter omicron, U+03BF NEW -->
{"pi", "960"}, // greek small letter pi, U+03C0 ISOgrk3 -->
{"rho", "961"}, // greek small letter rho, U+03C1 ISOgrk3 -->
{"sigmaf", "962"}, // greek small letter final sigma,U+03C2 ISOgrk3 -->
{"sigma", "963"}, // greek small letter sigma,U+03C3 ISOgrk3 -->
{"tau", "964"}, // greek small letter tau, U+03C4 ISOgrk3 -->
{"upsilon", "965"}, // greek small letter upsilon,U+03C5 ISOgrk3 -->
{"phi", "966"}, // greek small letter phi, U+03C6 ISOgrk3 -->
{"chi", "967"}, // greek small letter chi, U+03C7 ISOgrk3 -->
{"psi", "968"}, // greek small letter psi, U+03C8 ISOgrk3 -->
{"omega", "969"}, // greek small letter omega,U+03C9 ISOgrk3 -->
{"thetasym", "977"}, // greek small letter theta symbol,U+03D1 NEW -->
{"upsih", "978"}, // greek upsilon with hook symbol,U+03D2 NEW -->
{"piv", "982"}, // greek pi symbol, U+03D6 ISOgrk3 -->
// <!-- General Punctuation -->
{"bull", "8226"}, // bullet = black small circle,U+2022 ISOpub -->
// <!-- bullet is NOT the same as bullet operator, U+2219 -->
{"hellip", "8230"}, // horizontal ellipsis = three dot leader,U+2026 ISOpub -->
{"prime", "8242"}, // prime = minutes = feet, U+2032 ISOtech -->
{"Prime", "8243"}, // double prime = seconds = inches,U+2033 ISOtech -->
{"oline", "8254"}, // overline = spacing overscore,U+203E NEW -->
{"frasl", "8260"}, // fraction slash, U+2044 NEW -->
// <!-- Letterlike Symbols -->
{"weierp", "8472"}, // script capital P = power set= Weierstrass p, U+2118 ISOamso -->
{"image", "8465"}, // blackletter capital I = imaginary part,U+2111 ISOamso -->
{"real", "8476"}, // blackletter capital R = real part symbol,U+211C ISOamso -->
{"trade", "8482"}, // trade mark sign, U+2122 ISOnum -->
{"alefsym", "8501"}, // alef symbol = first transfinite cardinal,U+2135 NEW -->
// <!-- alef symbol is NOT the same as hebrew letter alef,U+05D0 although the
// same glyph could be used to depict both characters -->
// <!-- Arrows -->
{"larr", "8592"}, // leftwards arrow, U+2190 ISOnum -->
{"uarr", "8593"}, // upwards arrow, U+2191 ISOnum-->
{"rarr", "8594"}, // rightwards arrow, U+2192 ISOnum -->
{"darr", "8595"}, // downwards arrow, U+2193 ISOnum -->
{"harr", "8596"}, // left right arrow, U+2194 ISOamsa -->
{"crarr", "8629"}, // downwards arrow with corner leftwards= carriage return, U+21B5 NEW -->
{"lArr", "8656"}, // leftwards double arrow, U+21D0 ISOtech -->
// <!-- ISO 10646 does not say that lArr is the same as the 'is implied by'
// arrow but also does not have any other character for that function.
// So ? lArr canbe used for 'is implied by' as ISOtech suggests -->
{"uArr", "8657"}, // upwards double arrow, U+21D1 ISOamsa -->
{"rArr", "8658"}, // rightwards double arrow,U+21D2 ISOtech -->
// <!-- ISO 10646 does not say this is the 'implies' character but does not
// have another character with this function so ?rArr can be used for
// 'implies' as ISOtech suggests -->
{"dArr", "8659"}, // downwards double arrow, U+21D3 ISOamsa -->
{"hArr", "8660"}, // left right double arrow,U+21D4 ISOamsa -->
// <!-- Mathematical Operators -->
{"forall", "8704"}, // for all, U+2200 ISOtech -->
{"part", "8706"}, // partial differential, U+2202 ISOtech -->
{"exist", "8707"}, // there exists, U+2203 ISOtech -->
{"empty", "8709"}, // empty set = null set = diameter,U+2205 ISOamso -->
{"nabla", "8711"}, // nabla = backward difference,U+2207 ISOtech -->
{"isin", "8712"}, // element of, U+2208 ISOtech -->
{"notin", "8713"}, // not an element of, U+2209 ISOtech -->
{"ni", "8715"}, // contains as member, U+220B ISOtech -->
// <!-- should there be a more memorable name than 'ni'? -->
{"prod", "8719"}, // n-ary product = product sign,U+220F ISOamsb -->
// <!-- prod is NOT the same character as U+03A0 'greek capital letter pi'
// though the same glyph might be used for both -->
{"sum", "8721"}, // n-ary summation, U+2211 ISOamsb -->
// <!-- sum is NOT the same character as U+03A3 'greek capital letter sigma'
// though the same glyph might be used for both -->
{"minus", "8722"}, // minus sign, U+2212 ISOtech -->
{"lowast", "8727"}, // asterisk operator, U+2217 ISOtech -->
{"radic", "8730"}, // square root = radical sign,U+221A ISOtech -->
{"prop", "8733"}, // proportional to, U+221D ISOtech -->
{"infin", "8734"}, // infinity, U+221E ISOtech -->
{"ang", "8736"}, // angle, U+2220 ISOamso -->
{"and", "8743"}, // logical and = wedge, U+2227 ISOtech -->
{"or", "8744"}, // logical or = vee, U+2228 ISOtech -->
{"cap", "8745"}, // intersection = cap, U+2229 ISOtech -->
{"cup", "8746"}, // union = cup, U+222A ISOtech -->
{"int", "8747"}, // integral, U+222B ISOtech -->
{"there4", "8756"}, // therefore, U+2234 ISOtech -->
{"sim", "8764"}, // tilde operator = varies with = similar to,U+223C ISOtech -->
// <!-- tilde operator is NOT the same character as the tilde, U+007E,although
// the same glyph might be used to represent both -->
{"cong", "8773"}, // approximately equal to, U+2245 ISOtech -->
{"asymp", "8776"}, // almost equal to = asymptotic to,U+2248 ISOamsr -->
{"ne", "8800"}, // not equal to, U+2260 ISOtech -->
{"equiv", "8801"}, // identical to, U+2261 ISOtech -->
{"le", "8804"}, // less-than or equal to, U+2264 ISOtech -->
{"ge", "8805"}, // greater-than or equal to,U+2265 ISOtech -->
{"sub", "8834"}, // subset of, U+2282 ISOtech -->
{"sup", "8835"}, // superset of, U+2283 ISOtech -->
// <!-- note that nsup, 'not a superset of, U+2283' is not covered by the
// Symbol font encoding and is not included. Should it be, for symmetry?
// It is in ISOamsn --> <!ENTITY nsub", "8836"},
// not a subset of, U+2284 ISOamsn -->
{"sube", "8838"}, // subset of or equal to, U+2286 ISOtech -->
{"supe", "8839"}, // superset of or equal to,U+2287 ISOtech -->
{"oplus", "8853"}, // circled plus = direct sum,U+2295 ISOamsb -->
{"otimes", "8855"}, // circled times = vector product,U+2297 ISOamsb -->
{"perp", "8869"}, // up tack = orthogonal to = perpendicular,U+22A5 ISOtech -->
{"sdot", "8901"}, // dot operator, U+22C5 ISOamsb -->
// <!-- dot operator is NOT the same character as U+00B7 middle dot -->
// <!-- Miscellaneous Technical -->
{"lceil", "8968"}, // left ceiling = apl upstile,U+2308 ISOamsc -->
{"rceil", "8969"}, // right ceiling, U+2309 ISOamsc -->
{"lfloor", "8970"}, // left floor = apl downstile,U+230A ISOamsc -->
{"rfloor", "8971"}, // right floor, U+230B ISOamsc -->
{"lang", "9001"}, // left-pointing angle bracket = bra,U+2329 ISOtech -->
// <!-- lang is NOT the same character as U+003C 'less than' or U+2039 'single left-pointing angle quotation
// mark' -->
{"rang", "9002"}, // right-pointing angle bracket = ket,U+232A ISOtech -->
// <!-- rang is NOT the same character as U+003E 'greater than' or U+203A
// 'single right-pointing angle quotation mark' -->
// <!-- Geometric Shapes -->
{"loz", "9674"}, // lozenge, U+25CA ISOpub -->
// <!-- Miscellaneous Symbols -->
{"spades", "9824"}, // black spade suit, U+2660 ISOpub -->
// <!-- black here seems to mean filled as opposed to hollow -->
{"clubs", "9827"}, // black club suit = shamrock,U+2663 ISOpub -->
{"hearts", "9829"}, // black heart suit = valentine,U+2665 ISOpub -->
{"diams", "9830"}, // black diamond suit, U+2666 ISOpub -->
// <!-- Latin Extended-A -->
{"OElig", "338"}, // -- latin capital ligature OE,U+0152 ISOlat2 -->
{"oelig", "339"}, // -- latin small ligature oe, U+0153 ISOlat2 -->
// <!-- ligature is a misnomer, this is a separate character in some languages -->
{"Scaron", "352"}, // -- latin capital letter S with caron,U+0160 ISOlat2 -->
{"scaron", "353"}, // -- latin small letter s with caron,U+0161 ISOlat2 -->
{"Yuml", "376"}, // -- latin capital letter Y with diaeresis,U+0178 ISOlat2 -->
// <!-- Spacing Modifier Letters -->
{"circ", "710"}, // -- modifier letter circumflex accent,U+02C6 ISOpub -->
{"tilde", "732"}, // small tilde, U+02DC ISOdia -->
// <!-- General Punctuation -->
{"ensp", "8194"}, // en space, U+2002 ISOpub -->
{"emsp", "8195"}, // em space, U+2003 ISOpub -->
{"thinsp", "8201"}, // thin space, U+2009 ISOpub -->
{"zwnj", "8204"}, // zero width non-joiner,U+200C NEW RFC 2070 -->
{"zwj", "8205"}, // zero width joiner, U+200D NEW RFC 2070 -->
{"lrm", "8206"}, // left-to-right mark, U+200E NEW RFC 2070 -->
{"rlm", "8207"}, // right-to-left mark, U+200F NEW RFC 2070 -->
{"ndash", "8211"}, // en dash, U+2013 ISOpub -->
{"mdash", "8212"}, // em dash, U+2014 ISOpub -->
{"lsquo", "8216"}, // left single quotation mark,U+2018 ISOnum -->
{"rsquo", "8217"}, // right single quotation mark,U+2019 ISOnum -->
{"sbquo", "8218"}, // single low-9 quotation mark, U+201A NEW -->
{"ldquo", "8220"}, // left double quotation mark,U+201C ISOnum -->
{"rdquo", "8221"}, // right double quotation mark,U+201D ISOnum -->
{"bdquo", "8222"}, // double low-9 quotation mark, U+201E NEW -->
{"dagger", "8224"}, // dagger, U+2020 ISOpub -->
{"Dagger", "8225"}, // double dagger, U+2021 ISOpub -->
{"permil", "8240"}, // per mille sign, U+2030 ISOtech -->
{"lsaquo", "8249"}, // single left-pointing angle quotation mark,U+2039 ISO proposed -->
// <!-- lsaquo is proposed but not yet ISO standardized -->
{"rsaquo", "8250"}, // single right-pointing angle quotation mark,U+203A ISO proposed -->
// <!-- rsaquo is proposed but not yet ISO standardized -->
{"euro", "8364"}, // -- euro sign, U+20AC NEW -->
};
/**
* <p>
* The set of entities supported by standard XML.
* </p>
*/
public static final Entities XML;
/**
* <p>
* The set of entities supported by HTML 3.2.
* </p>
*/
public static final Entities HTML32;
/**
* <p>
* The set of entities supported by HTML 4.0.
* </p>
*/
public static final Entities HTML40;
static {
XML = new Entities();
XML.addEntities(BASIC_ARRAY);
XML.addEntities(APOS_ARRAY);
}
static {
HTML32 = new Entities();
HTML32.addEntities(BASIC_ARRAY);
HTML32.addEntities(ISO8859_1_ARRAY);
}
static {
HTML40 = new Entities();
fillWithHtml40Entities(HTML40);
}
/**
* <p>
* Fills the specified entities instance with HTML 40 entities.
* </p>
*
* @param entities
* the instance to be filled.
*/
static void fillWithHtml40Entities(Entities entities) {
entities.addEntities(BASIC_ARRAY);
entities.addEntities(ISO8859_1_ARRAY);
entities.addEntities(HTML40_ARRAY);
}
static interface EntityMap {
/**
* <p>
* Add an entry to this entity map.
* </p>
*
* @param name
* the entity name
* @param value
* the entity value
*/
void add(String name, int value);
/**
* <p>
* Returns the name of the entity identified by the specified value.
* </p>
*
* @param value
* the value to locate
* @return entity name associated with the specified value
*/
String name(int value);
/**
* <p>
* Returns the value of the entity identified by the specified name.
* </p>
*
* @param name
* the name to locate
* @return entity value associated with the specified name
*/
int value(String name);
}
static class PrimitiveEntityMap implements EntityMap {
private Map mapNameToValue = new HashMap();
private Map<Integer, Object> mapValueToName = Maps.newHashMap();
/**
* {@inheritDoc}
*/
public void add(String name, int value) {
mapNameToValue.put(name, new Integer(value));
mapValueToName.put(value, name);
}
/**
* {@inheritDoc}
*/
public String name(int value) {
return (String) mapValueToName.get(value);
}
/**
* {@inheritDoc}
*/
public int value(String name) {
Object value = mapNameToValue.get(name);
if (value == null) {
return -1;
}
return ((Integer) value).intValue();
}
}
static abstract class MapIntMap implements Entities.EntityMap {
protected Map mapNameToValue;
protected Map mapValueToName;
/**
* {@inheritDoc}
*/
public void add(String name, int value) {
mapNameToValue.put(name, new Integer(value));
mapValueToName.put(new Integer(value), name);
}
/**
* {@inheritDoc}
*/
public String name(int value) {
return (String) mapValueToName.get(new Integer(value));
}
/**
* {@inheritDoc}
*/
public int value(String name) {
Object value = mapNameToValue.get(name);
if (value == null) {
return -1;
}
return ((Integer) value).intValue();
}
}
static class HashEntityMap extends MapIntMap {
/**
* Constructs a new instance of <code>HashEntityMap</code>.
*/
public HashEntityMap() {
mapNameToValue = new HashMap();
mapValueToName = new HashMap();
}
}
static class TreeEntityMap extends MapIntMap {
/**
* Constructs a new instance of <code>TreeEntityMap</code>.
*/
public TreeEntityMap() {
mapNameToValue = new TreeMap();
mapValueToName = new TreeMap();
}
}
static class LookupEntityMap extends PrimitiveEntityMap {
private String[] lookupTable;
private int LOOKUP_TABLE_SIZE = 256;
/**
* {@inheritDoc}
*/
public String name(int value) {
if (value < LOOKUP_TABLE_SIZE) {
return lookupTable()[value];
}
return super.name(value);
}
/**
* <p>
* Returns the lookup table for this entity map. The lookup table is created if it has not been previously.
* </p>
*
* @return the lookup table
*/
private String[] lookupTable() {
if (lookupTable == null) {
createLookupTable();
}
return lookupTable;
}
/**
* <p>
* Creates an entity lookup table of LOOKUP_TABLE_SIZE elements, initialized with entity names.
* </p>
*/
private void createLookupTable() {
lookupTable = new String[LOOKUP_TABLE_SIZE];
for (int i = 0; i < LOOKUP_TABLE_SIZE; ++i) {
lookupTable[i] = super.name(i);
}
}
}
static class ArrayEntityMap implements EntityMap {
protected int growBy = 100;
protected int size = 0;
protected String[] names;
protected int[] values;
/**
* Constructs a new instance of <code>ArrayEntityMap</code>.
*/
public ArrayEntityMap() {
names = new String[growBy];
values = new int[growBy];
}
/**
* Constructs a new instance of <code>ArrayEntityMap</code> specifying the size by which the array should
* grow.
*
* @param growBy
* array will be initialized to and will grow by this amount
*/
public ArrayEntityMap(int growBy) {
this.growBy = growBy;
names = new String[growBy];
values = new int[growBy];
}
/**
* {@inheritDoc}
*/
public void add(String name, int value) {
ensureCapacity(size + 1);
names[size] = name;
values[size] = value;
size++;
}
/**
* Verifies the capacity of the entity array, adjusting the size if necessary.
*
* @param capacity
* size the array should be
*/
protected void ensureCapacity(int capacity) {
if (capacity > names.length) {
int newSize = Math.max(capacity, size + growBy);
String[] newNames = new String[newSize];
System.arraycopy(names, 0, newNames, 0, size);
names = newNames;
int[] newValues = new int[newSize];
System.arraycopy(values, 0, newValues, 0, size);
values = newValues;
}
}
/**
* {@inheritDoc}
*/
public String name(int value) {
for (int i = 0; i < size; ++i) {
if (values[i] == value) {
return names[i];
}
}
return null;
}
/**
* {@inheritDoc}
*/
public int value(String name) {
for (int i = 0; i < size; ++i) {
if (names[i].equals(name)) {
return values[i];
}
}
return -1;
}
}
static class BinaryEntityMap extends ArrayEntityMap {
/**
* Constructs a new instance of <code>BinaryEntityMap</code>.
*/
public BinaryEntityMap() {
super();
}
/**
* Constructs a new instance of <code>ArrayEntityMap</code> specifying the size by which the underlying array
* should grow.
*
* @param growBy
* array will be initialized to and will grow by this amount
*/
public BinaryEntityMap(int growBy) {
super(growBy);
}
/**
* Performs a binary search of the entity array for the specified key. This method is based on code in
* {@link java.util.Arrays}.
*
* @param key
* the key to be found
* @return the index of the entity array matching the specified key
*/
private int binarySearch(int key) {
int low = 0;
int high = size - 1;
while (low <= high) {
int mid = (low + high) >>> 1;
int midVal = values[mid];
if (midVal < key) {
low = mid + 1;
} else if (midVal > key) {
high = mid - 1;
} else {
return mid; // key found
}
}
return -(low + 1); // key not found.
}
/**
* {@inheritDoc}
*/
public void add(String name, int value) {
ensureCapacity(size + 1);
int insertAt = binarySearch(value);
if (insertAt > 0) {
return; // note: this means you can't insert the same value twice
}
insertAt = -(insertAt + 1); // binarySearch returns it negative and off-by-one
System.arraycopy(values, insertAt, values, insertAt + 1, size - insertAt);
values[insertAt] = value;
System.arraycopy(names, insertAt, names, insertAt + 1, size - insertAt);
names[insertAt] = name;
size++;
}
/**
* {@inheritDoc}
*/
public String name(int value) {
int index = binarySearch(value);
if (index < 0) {
return null;
}
return names[index];
}
}
// package scoped for testing
EntityMap map = new Entities.LookupEntityMap();
/**
* <p>
* Adds entities to this entity.
* </p>
*
* @param entityArray
* array of entities to be added
*/
public void addEntities(String[][] entityArray) {
for (int i = 0; i < entityArray.length; ++i) {
addEntity(entityArray[i][0], Integer.parseInt(entityArray[i][1]));
}
}
/**
* <p>
* Add an entity to this entity.
* </p>
*
* @param name
* name of the entity
* @param value
* vale of the entity
*/
public void addEntity(String name, int value) {
map.add(name, value);
}
/**
* <p>
* Returns the name of the entity identified by the specified value.
* </p>
*
* @param value
* the value to locate
* @return entity name associated with the specified value
*/
public String entityName(int value) {
return map.name(value);
}
/**
* <p>
* Returns the value of the entity identified by the specified name.
* </p>
*
* @param name
* the name to locate
* @return entity value associated with the specified name
*/
public int entityValue(String name) {
return map.value(name);
}
/**
* <p>
* Escapes the characters in a <code>String</code>.
* </p>
*
* <p>
* For example, if you have called addEntity("foo", 0xA1), escape("\u00A1") will return
* "&foo;"
* </p>
*
* @param str
* The <code>String</code> to escape.
* @return A new escaped <code>String</code>.
*/
public String escape(String str) {
StringWriter stringWriter = createStringWriter(str);
try {
this.escape(stringWriter, str);
} catch (IOException e) {
// This should never happen because ALL the StringWriter methods called by #escape(Writer, String) do not
// throw IOExceptions.
throw new RuntimeException(e);
}
return stringWriter.toString();
}
/**
* <p>
* Escapes the characters in the <code>String</code> passed and writes the result to the <code>Writer</code>
* passed.
* </p>
*
* @param writer
* The <code>Writer</code> to write the results of the escaping to. Assumed to be a non-null value.
* @param str
* The <code>String</code> to escape. Assumed to be a non-null value.
* @throws IOException
* when <code>Writer</code> passed throws the exception from calls to the {@link Writer#write(int)}
* methods.
*
* @see #escape(String)
* @see Writer
*/
public void escape(Writer writer, String str) throws IOException {
int len = str.length();
for (int i = 0; i < len; i++) {
char c = str.charAt(i);
String entityName = this.entityName(c);
if (entityName == null) {
if (c > 0x7F) {
writer.write("&#");
writer.write(Integer.toString(c, 10));
writer.write(';');
} else {
writer.write(c);
}
} else {
writer.write('&');
writer.write(entityName);
writer.write(';');
}
}
}
/**
* <p>
* Unescapes the entities in a <code>String</code>.
* </p>
*
* <p>
* For example, if you have called addEntity("foo", 0xA1), unescape("&foo;") will return
* "\u00A1"
* </p>
*
* @param str
* The <code>String</code> to escape.
* @return A new escaped <code>String</code>.
*/
public String unescape(String str) {
int firstAmp = str.indexOf('&');
if (firstAmp < 0) {
return str;
} else {
StringWriter stringWriter = createStringWriter(str);
try {
this.doUnescape(stringWriter, str, firstAmp);
} catch (IOException e) {
// This should never happen because ALL the StringWriter methods called by #escape(Writer, String)
// do not throw IOExceptions.
throw new RuntimeException(e);
}
return stringWriter.toString();
}
}
/**
* Make the StringWriter 10% larger than the source String to avoid growing the writer
*
* @param str The source string
* @return A newly created StringWriter
*/
private StringWriter createStringWriter(String str) {
return new StringWriter((int) (str.length() + (str.length() * 0.1)));
}
/**
* <p>
* Unescapes the escaped entities in the <code>String</code> passed and writes the result to the
* <code>Writer</code> passed.
* </p>
*
* @param writer
* The <code>Writer</code> to write the results to; assumed to be non-null.
* @param str
* The source <code>String</code> to unescape; assumed to be non-null.
* @throws IOException
* when <code>Writer</code> passed throws the exception from calls to the {@link Writer#write(int)}
* methods.
*
* @see #escape(String)
* @see Writer
*/
public void unescape(Writer writer, String str) throws IOException {
int firstAmp = str.indexOf('&');
if (firstAmp < 0) {
writer.write(str);
return;
} else {
doUnescape(writer, str, firstAmp);
}
}
/**
* Underlying unescape method that allows the optimisation of not starting from the 0 index again.
*
* @param writer
* The <code>Writer</code> to write the results to; assumed to be non-null.
* @param str
* The source <code>String</code> to unescape; assumed to be non-null.
* @param firstAmp
* The <code>int</code> index of the first ampersand in the source String.
* @throws IOException
* when <code>Writer</code> passed throws the exception from calls to the {@link Writer#write(int)}
* methods.
*/
private void doUnescape(Writer writer, String str, int firstAmp) throws IOException {
writer.write(str, 0, firstAmp);
int len = str.length();
for (int i = firstAmp; i < len; i++) {
char c = str.charAt(i);
if (c == '&') {
int nextIdx = i + 1;
int semiColonIdx = str.indexOf(';', nextIdx);
if (semiColonIdx == -1) {
writer.write(c);
continue;
}
int amphersandIdx = str.indexOf('&', i + 1);
if (amphersandIdx != -1 && amphersandIdx < semiColonIdx) {
// Then the text looks like &...&...;
writer.write(c);
continue;
}
String entityContent = str.substring(nextIdx, semiColonIdx);
int entityValue = -1;
int entityContentLen = entityContent.length();
if (entityContentLen > 0) {
if (entityContent.charAt(0) == '#') { // escaped value content is an integer (decimal or
// hexidecimal)
if (entityContentLen > 1) {
char isHexChar = entityContent.charAt(1);
try {
switch (isHexChar) {
case 'X' :
case 'x' : {
entityValue = Integer.parseInt(entityContent.substring(2), 16);
break;
}
default : {
entityValue = Integer.parseInt(entityContent.substring(1), 10);
}
}
if (entityValue > 0xFFFF) {
entityValue = -1;
}
} catch (NumberFormatException e) {
entityValue = -1;
}
}
} else { // escaped value content is an entity name
entityValue = this.entityValue(entityContent);
}
}
if (entityValue == -1) {
writer.write('&');
writer.write(entityContent);
writer.write(';');
} else {
writer.write(entityValue);
}
i = semiColonIdx; // move index up to the semi-colon
} else {
writer.write(c);
}
}
}
}
| 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 com.beust.android.translate.Languages.Language;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.util.Log;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
/**
* This class handles the history of past translations.
*/
public class History {
private static final String HISTORY = "history";
/**
* Sort the translations by timestamp.
*/
private static final Comparator<HistoryRecord> MOST_RECENT_COMPARATOR
= new Comparator<HistoryRecord>() {
public int compare(HistoryRecord object1, HistoryRecord object2) {
return (int) (object2.when - object1.when);
}
};
/**
* Sort the translations by destination language and then by input.
*/
private static final Comparator<HistoryRecord> LANGUAGE_COMPARATOR
= new Comparator<HistoryRecord>() {
public int compare(HistoryRecord object1, HistoryRecord object2) {
int result = object1.to.getLongName().compareTo(object2.to.getLongName());
if (result == 0) {
result = object1.input.compareTo(object2.input);
}
return result;
}
};
private List<HistoryRecord> mHistoryRecords = Lists.newArrayList();
public History(SharedPreferences prefs) {
mHistoryRecords = restoreHistory(prefs);
}
public static List<HistoryRecord> restoreHistory(SharedPreferences prefs) {
List<HistoryRecord> result = Lists.newArrayList();
boolean done = false;
int i = 0;
Map<String, ?> allKeys = prefs.getAll();
for (String key : allKeys.keySet()) {
if (key.startsWith(HISTORY)) {
String value = (String) allKeys.get(key);
result.add(HistoryRecord.decode(value));
}
}
// while (! done) {
// String history = prefs.getString(HISTORY + "-" + i++, null);
// if (history != null) {
// result.add(HistoryRecord.decode(history));
// } else {
// done = true;
// }
// }
return result;
}
// public void saveHistory(Editor edit) {
// log("Saving history");
// for (int i = 0; i < mHistoryRecords.size(); i++) {
// HistoryRecord hr = mHistoryRecords.get(i);
// edit.putString(HISTORY + "-" + i, hr.encode());
// }
// }
public static void addHistoryRecord(Context context,
Language from, Language to, String input, String output) {
History historyRecord = new History(TranslateActivity.getPrefs(context));
HistoryRecord hr = new HistoryRecord(from, to, input, output, System.currentTimeMillis());
// Find an empty key to add this history record
SharedPreferences prefs = TranslateActivity.getPrefs(context);
int i = 0;
while (true) {
String key = HISTORY + "-" + i;
if (!prefs.contains(key)) {
Editor edit = prefs.edit();
edit.putString(key, hr.encode());
log("Committing " + key + " " + hr.encode());
edit.commit();
return;
} else {
i++;
}
}
}
// public static void addHistoryRecord(Context context, List<HistoryRecord> result, HistoryRecord hr) {
// if (! result.contains(hr)) {
// result.add(hr);
// }
// Editor edit = getPrefs(context).edit();
// }
private static void log(String s) {
Log.d(TranslateActivity.TAG, "[History] " + s);
}
public List<HistoryRecord> getHistoryRecordsMostRecentFirst() {
Collections.sort(mHistoryRecords, MOST_RECENT_COMPARATOR);
return mHistoryRecords;
}
public List<HistoryRecord> getHistoryRecordsByLanguages() {
Collections.sort(mHistoryRecords, LANGUAGE_COMPARATOR);
return mHistoryRecords;
}
public List<HistoryRecord> getHistoryRecords(Comparator<HistoryRecord> comparator) {
if (comparator != null) {
Collections.sort(mHistoryRecords, comparator);
}
return mHistoryRecords;
}
public void clear(Context context) {
int size = mHistoryRecords.size();
mHistoryRecords = Lists.newArrayList();
Editor edit = TranslateActivity.getPrefs(context).edit();
for (int i = 0; i < size; i++) {
String key = HISTORY + "-" + i;
log("Removing key " + key);
edit.remove(key);
}
edit.commit();
}
}
| 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.util.Log;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import org.json.JSONObject;
/**
* Makes the Google Translate API available to Java applications.
*
* @author Richard Midwinter
* @author Emeric Vernat
* @author Juan B Cabral
* @author Cedric Beust
*/
public class Translate {
private static final String ENCODING = "UTF-8";
private static final String URL_STRING = "http://ajax.googleapis.com/ajax/services/language/translate?v=1.0&langpair=";
private static final String TEXT_VAR = "&q=";
/**
* Translates text from a given language to another given language using Google Translate
*
* @param text The String to translate.
* @param from The language code to translate from.
* @param to The language code to translate to.
* @return The translated String.
* @throws MalformedURLException
* @throws IOException
*/
public static String translate(String text, String from, String to) throws Exception {
return retrieveTranslation(text, from, to);
}
/**
* Forms an HTTP request and parses the response for a translation.
*
* @param text The String to translate.
* @param from The language code to translate from.
* @param to The language code to translate to.
* @return The translated String.
* @throws Exception
*/
private static String retrieveTranslation(String text, String from, String to) throws Exception {
try {
StringBuilder url = new StringBuilder();
url.append(URL_STRING).append(from).append("%7C").append(to);
url.append(TEXT_VAR).append(URLEncoder.encode(text, ENCODING));
Log.d(TranslateService.TAG, "Connecting to " + url.toString());
HttpURLConnection uc = (HttpURLConnection) new URL(url.toString()).openConnection();
uc.setDoInput(true);
uc.setDoOutput(true);
try {
Log.d(TranslateService.TAG, "getInputStream()");
InputStream is= uc.getInputStream();
String result = toString(is);
JSONObject json = new JSONObject(result);
return ((JSONObject)json.get("responseData")).getString("translatedText");
} finally { // http://java.sun.com/j2se/1.5.0/docs/guide/net/http-keepalive.html
uc.getInputStream().close();
if (uc.getErrorStream() != null) uc.getErrorStream().close();
}
} catch (Exception ex) {
throw ex;
}
}
/**
* Reads an InputStream and returns its contents as a String. Also effects rate control.
* @param inputStream The InputStream to read from.
* @return The contents of the InputStream as a String.
* @throws Exception
*/
private static String toString(InputStream inputStream) throws Exception {
StringBuilder outputBuilder = new StringBuilder();
try {
String string;
if (inputStream != null) {
BufferedReader reader =
new BufferedReader(new InputStreamReader(inputStream, ENCODING));
while (null != (string = reader.readLine())) {
outputBuilder.append(string).append('\n');
}
}
} catch (Exception ex) {
Log.e(TranslateService.TAG, "Error reading translation stream.", ex);
}
return outputBuilder.toString();
}
} | Java |
/*
* 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 com.beust.android.translate;
import java.util.ArrayList;
import java.util.Collections;
/**
* Provides static methods for creating {@code List} instances easily, and other
* utility methods for working with lists.
*/
public class Lists {
/**
* Creates an empty {@code ArrayList} instance.
*
* <p><b>Note:</b> if you only need an <i>immutable</i> empty List, use
* {@link Collections#emptyList} instead.
*
* @return a newly-created, initially-empty {@code ArrayList}
*/
public static <E> ArrayList<E> newArrayList() {
return new ArrayList<E>();
}
/**
* Creates a resizable {@code ArrayList} instance containing the given
* elements.
*
* <p><b>Note:</b> due to a bug in javac 1.5.0_06, we cannot support the
* following:
*
* <p>{@code List<Base> list = Lists.newArrayList(sub1, sub2);}
*
* <p>where {@code sub1} and {@code sub2} are references to subtypes of
* {@code Base}, not of {@code Base} itself. To get around this, you must
* use:
*
* <p>{@code List<Base> list = Lists.<Base>newArrayList(sub1, sub2);}
*
* @param elements the elements that the list should contain, in order
* @return a newly-created {@code ArrayList} containing those elements
*/
public static <E> ArrayList<E> newArrayList(E... elements) {
int capacity = (elements.length * 110) / 100 + 5;
ArrayList<E> list = new ArrayList<E>(capacity);
Collections.addAll(list, elements);
return list;
}
}
| 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.Activity;
import android.graphics.drawable.Drawable;
import android.util.Log;
import android.widget.Button;
import java.util.Map;
/**
* Language information for the Google Translate API.
*/
public final class Languages {
/**
* Reference at http://en.wikipedia.org/wiki/ISO_3166-1_alpha-2
*/
static enum Language {
// AFRIKAANS("af", "Afrikaans", R.drawable.af),
// ALBANIAN("sq", "Albanian"),
// AMHARIC("am", "Amharic", R.drawable.am),
// ARABIC("ar", "Arabic", R.drawable.ar),
// ARMENIAN("hy", "Armenian"),
// AZERBAIJANI("az", "Azerbaijani", R.drawable.az),
// BASQUE("eu", "Basque"),
// BELARUSIAN("be", "Belarusian", R.drawable.be),
// BENGALI("bn", "Bengali", R.drawable.bn),
// BIHARI("bh", "Bihari", R.drawable.bh),
BULGARIAN("bg", "Bulgarian", R.drawable.bg),
// BURMESE("my", "Burmese", R.drawable.my),
CATALAN("ca", "Catalan"),
CHINESE("zh", "Chinese", R.drawable.cn),
CHINESE_SIMPLIFIED("zh-CN", "Chinese simplified", R.drawable.cn),
CHINESE_TRADITIONAL("zh-TW", "Chinese traditional", R.drawable.tw),
CROATIAN("hr", "Croatian", R.drawable.hr),
CZECH("cs", "Czech", R.drawable.cs),
DANISH("da", "Danish", R.drawable.dk),
// DHIVEHI("dv", "Dhivehi"),
DUTCH("nl", "Dutch", R.drawable.nl),
ENGLISH("en", "English", R.drawable.us),
// ESPERANTO("eo", "Esperanto"),
// ESTONIAN("et", "Estonian", R.drawable.et),
FILIPINO("tl", "Filipino", R.drawable.ph),
FINNISH("fi", "Finnish", R.drawable.fi),
FRENCH("fr", "French", R.drawable.fr),
// GALICIAN("gl", "Galician", R.drawable.gl),
// GEORGIAN("ka", "Georgian"),
GERMAN("de", "German", R.drawable.de),
GREEK("el", "Greek", R.drawable.gr),
// GUARANI("gn", "Guarani", R.drawable.gn),
// GUJARATI("gu", "Gujarati", R.drawable.gu),
// HEBREW("iw", "Hebrew", R.drawable.il),
// HINDI("hi", "Hindi"),
// HUNGARIAN("hu", "Hungarian", R.drawable.hu),
// ICELANDIC("is", "Icelandic", R.drawable.is),
INDONESIAN("id", "Indonesian", R.drawable.id),
// INUKTITUT("iu", "Inuktitut"),
ITALIAN("it", "Italian", R.drawable.it),
JAPANESE("ja", "Japanese", R.drawable.jp),
// KANNADA("kn", "Kannada", R.drawable.kn),
// KAZAKH("kk", "Kazakh"),
// KHMER("km", "Khmer", R.drawable.km),
KOREAN("ko", "Korean", R.drawable.kr),
// KURDISH("ky", "Kurdish", R.drawable.ky),
// LAOTHIAN("lo", "Laothian"),
// LATVIAN("la", "Latvian", R.drawable.la),
LITHUANIAN("lt", "Lithuanian", R.drawable.lt),
// MACEDONIAN("mk", "Macedonian", R.drawable.mk),
// MALAY("ms", "Malay", R.drawable.ms),
// MALAYALAM("ml", "Malayalam", R.drawable.ml),
// MALTESE("mt", "Maltese", R.drawable.mt),
// MARATHI("mr", "Marathi", R.drawable.mr),
// MONGOLIAN("mn", "Mongolian", R.drawable.mn),
// NEPALI("ne", "Nepali", R.drawable.ne),
NORWEGIAN("no", "Norwegian", R.drawable.no),
// ORIYA("or", "Oriya"),
// PASHTO("ps", "Pashto", R.drawable.ps),
// PERSIAN("fa", "Persian"),
POLISH("pl", "Polish", R.drawable.pl),
PORTUGUESE("pt", "Portuguese", R.drawable.pt),
// PUNJABI("pa", "Punjabi", R.drawable.pa),
ROMANIAN("ro", "Romanian", R.drawable.ro),
RUSSIAN("ru", "Russian", R.drawable.ru),
// SANSKRIT("sa", "Sanskrit", R.drawable.sa),
SERBIAN("sr", "Serbian", R.drawable.sr),
// SINDHI("sd", "Sindhi", R.drawable.sd),
// SINHALESE("si", "Sinhalese", R.drawable.si),
SLOVAK("sk", "Slovak", R.drawable.sk),
SLOVENIAN("sl", "Slovenian", R.drawable.sl),
SPANISH("es", "Spanish", R.drawable.es),
// SWAHILI("sw", "Swahili"),
SWEDISH("sv", "Swedish", R.drawable.sv),
// TAJIK("tg", "Tajik", R.drawable.tg),
// TAMIL("ta", "Tamil"),
TAGALOG("tl", "Tagalog", R.drawable.ph),
// TELUGU("te", "Telugu"),
// THAI("th", "Thai", R.drawable.th),
// TIBETAN("bo", "Tibetan", R.drawable.bo),
// TURKISH("tr", "Turkish", R.drawable.tr),
UKRAINIAN("uk", "Ukrainian", R.drawable.ua),
// URDU("ur", "Urdu"),
// UZBEK("uz", "Uzbek", R.drawable.uz),
// UIGHUR("ug", "Uighur", R.drawable.ug),
;
private String mShortName;
private String mLongName;
private int mFlag;
private static Map<String, String> mLongNameToShortName = Maps.newHashMap();
private static Map<String, Language> mShortNameToLanguage = Maps.newHashMap();
static {
for (Language language : values()) {
mLongNameToShortName.put(language.getLongName(), language.getShortName());
mShortNameToLanguage.put(language.getShortName(), language);
}
}
private Language(String shortName, String longName, int flag) {
init(shortName, longName, flag);
}
private Language(String shortName, String longName) {
init(shortName, longName, -1);
}
private void init(String shortName, String longName, int flag) {
mShortName = shortName;
mLongName = longName;
mFlag = flag;
}
public String getShortName() {
return mShortName;
}
public String getLongName() {
return mLongName;
}
public int getFlag() {
return mFlag;
}
@Override
public String toString() {
return mLongName;
}
public static Language findLanguageByShortName(String shortName) {
return mShortNameToLanguage.get(shortName);
}
public void configureButton(Activity activity, Button button) {
button.setTag(this);
button.setText(getLongName());
int f = getFlag();
if (f != -1) {
Drawable flag = activity.getResources().getDrawable(f);
button.setCompoundDrawablesWithIntrinsicBounds(flag, null, null, null);
button.setCompoundDrawablePadding(5);
}
}
}
public static String getShortName(String longName) {
return Language.mLongNameToShortName.get(longName);
}
private static void log(String s) {
Log.d(TranslateActivity.TAG, "[Languages] " + s);
}
}
| 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 static com.beust.android.translate.Languages.Language;
/**
* This class describes one entry in the history
*/
public class HistoryRecord {
private static final String SEPARATOR = "@";
public Language from;
public Language to;
public String input;
public String output;
public long when;
public HistoryRecord(Language from, Language to, String input, String output, long when) {
super();
this.from = from;
this.to = to;
this.input = input;
this.output = output;
this.when = when;
}
@Override
public boolean equals(Object o) {
if (o == null) return false;
if (o == this) return true;
try {
HistoryRecord other = (HistoryRecord) o;
return other.from.equals(from) && other.to.equals(to) &&
other.input.equals(input) && other.output.equals(output);
} catch(Exception ex) {
return false;
}
}
@Override
public int hashCode() {
return from.hashCode() ^ to.hashCode() ^ input.hashCode() ^ output.hashCode();
}
public String encode() {
return from.name() + SEPARATOR + to.name() + SEPARATOR + input
+ SEPARATOR + output + SEPARATOR + new Long(when);
}
@Override
public String toString() {
return encode();
}
public static HistoryRecord decode(String s) {
Object[] o = s.split(SEPARATOR);
int i = 0;
Language from = Language.valueOf((String) o[i++]);
Language to = Language.valueOf((String) o[i++]);
String input = (String) o[i++];
String output = (String) o[i++];
Long when = Long.valueOf((String) o[i++]);
HistoryRecord result = new HistoryRecord(from, to, input, output, when);
return result;
}
}
| Java |
// Copyright 2008 Google Inc. All Rights Reserved.
package com.beust.android.translate;
import com.beust.android.translate.ITranslate;
import com.beust.android.translate.Translate;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
/**
* Performs language translation.
*
* @author Daniel Rall
*/
public class TranslateService extends Service {
public static final String TAG = "TranslateService";
private static final String[] TRANSLATE_ACTIONS = {
Intent.ACTION_GET_CONTENT,
Intent.ACTION_PICK,
Intent.ACTION_VIEW
};
private final ITranslate.Stub mBinder = new ITranslate.Stub() {
/**
* Translates text from a given language to another given language
* using Google Translate.
*
* @param text The text to translate.
* @param from The language code to translate from.
* @param to The language code to translate to.
* @return The translated text, or <code>null</code> on error.
*/
public String translate(String text, String from, String to) {
try {
return Translate.translate(text, from, to);
} catch (Exception e) {
Log.e(TAG, "Failed to perform translation: " + e.getMessage());
return null;
}
}
/**
* @return The service version number.
*/
public int getVersion() {
return 1;
}
};
@Override
public IBinder onBind(Intent intent) {
for (int i = 0; i < TRANSLATE_ACTIONS.length; i++) {
if (TRANSLATE_ACTIONS[i].equals(intent.getAction())) {
return mBinder;
}
}
return null;
}
}
| 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 static android.view.ViewGroup.LayoutParams.FILL_PARENT;
import com.beust.android.translate.Languages.Language;
import android.app.AlertDialog;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ScrollView;
/**
* This dialog displays a list of languages and then tells the calling activity which language
* was selected.
*/
public class LanguageDialog extends AlertDialog implements OnClickListener {
private TranslateActivity mActivity;
private boolean mFrom;
protected LanguageDialog(TranslateActivity activity) {
super(activity);
mActivity = activity;
LayoutInflater inflater = (LayoutInflater) activity.getSystemService(
Context.LAYOUT_INFLATER_SERVICE);
ScrollView scrollView = (ScrollView) inflater.inflate(R.layout.language_dialog, null);
setView(scrollView);
LinearLayout layout = (LinearLayout) scrollView.findViewById(R.id.languages);
LinearLayout current = null;
Language[] languages = Language.values();
for (int i = 0; i < languages.length; i++) {
if (current != null) {
layout.addView(current, new LayoutParams(FILL_PARENT, FILL_PARENT));
}
current = new LinearLayout(activity);
current.setOrientation(LinearLayout.HORIZONTAL);
Button button = (Button) inflater.inflate(R.layout.language_entry, current, false);
Language language = languages[i];
language.configureButton(mActivity, button);
button.setOnClickListener(this);
current.addView(button, button.getLayoutParams());
}
if (current != null) {
layout.addView(current, new LayoutParams(FILL_PARENT, FILL_PARENT));
}
setTitle(" "); // set later, but necessary to put a non-empty string here
}
private void log(String s) {
Log.d(TranslateActivity.TAG, s);
}
public void onClick(View v) {
mActivity.setNewLanguage((Language) v.getTag(), mFrom, true /* translate */);
dismiss();
}
public void setFrom(boolean from) {
log("From set to " + from);
mFrom = from;
setTitle(from ? mActivity.getString(R.string.translate_from) : mActivity.getString(R.string.translate_to));
}
}
| Java |
/*
* 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 com.beust.android.translate;
import java.util.HashMap;
/**
* Provides static methods for creating mutable {@code Maps} instances easily.
*/
public class Maps {
/**
* Creates a {@code HashMap} instance.
*
* @return a newly-created, initially-empty {@code HashMap}
*/
public static <K, V> HashMap<K, V> newHashMap() {
return new HashMap<K, V>();
}
}
| 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 com.beust.android.translate.Languages.Language;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.provider.Contacts;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.zip.GZIPInputStream;
/**
* Main activity for the Translate application.
*
* @author Cedric Beust
* @author Daniel Rall
*/
public class TranslateActivity extends Activity implements OnClickListener {
static final String TAG = "Translate";
private EditText mToEditText;
private EditText mFromEditText;
private Button mFromButton;
private Button mToButton;
private Button mTranslateButton;
private Button mSwapButton;
private Handler mHandler = new Handler();
private ProgressBar mProgressBar;
private TextView mStatusView;
// true if changing a language should automatically trigger a translation
private boolean mDoTranslate = true;
// Dialog id's
private static final int LANGUAGE_DIALOG_ID = 1;
private static final int ABOUT_DIALOG_ID = 2;
// Saved preferences
private static final String FROM = "from";
private static final String TO = "to";
private static final String INPUT = "input";
private static final String OUTPUT = "output";
// Default language pair if no saved preferences are found
private static final String DEFAULT_FROM = Language.ENGLISH.getShortName();
private static final String DEFAULT_TO = Language.GERMAN.getShortName();
private Button mLatestButton;
private OnClickListener mClickListener = new OnClickListener() {
public void onClick(View v) {
mLatestButton = (Button) v;
showDialog(LANGUAGE_DIALOG_ID);
}
};
// Translation service handle.
private ITranslate mTranslateService;
// ServiceConnection implementation for translation.
private ServiceConnection mTranslateConn = new ServiceConnection() {
public void onServiceConnected(ComponentName name, IBinder service) {
mTranslateService = ITranslate.Stub.asInterface(service);
/* TODO(dlr): Register a callback to assure we don't lose our svc.
try {
mTranslateervice.registerCallback(mTranslateCallback);
} catch (RemoteException e) {
log("Failed to establish Translate service connection: " + e);
return;
}
*/
if (mTranslateService != null) {
mTranslateButton.setEnabled(true);
} else {
mTranslateButton.setEnabled(false);
mStatusView.setText(getString(R.string.error));
log("Unable to acquire TranslateService");
}
}
public void onServiceDisconnected(ComponentName name) {
mTranslateButton.setEnabled(false);
mTranslateService = null;
}
};
// Dictionary
private static byte[] mWordBuffer;
private static int mWordCount;
private static ArrayList<Integer> mWordIndices;
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.translate_activity);
mFromEditText = (EditText) findViewById(R.id.input);
mToEditText = (EditText) findViewById(R.id.translation);
mFromButton = (Button) findViewById(R.id.from);
mToButton = (Button) findViewById(R.id.to);
mTranslateButton = (Button) findViewById(R.id.button_translate);
mSwapButton = (Button) findViewById(R.id.button_swap);
mProgressBar = (ProgressBar) findViewById(R.id.progress_bar);
mStatusView = (TextView) findViewById(R.id.status);
//
// Install the language adapters on both the From and To spinners.
//
mFromButton.setOnClickListener(mClickListener);
mToButton.setOnClickListener(mClickListener);
mTranslateButton.setOnClickListener(this);
mSwapButton.setOnClickListener(this);
mFromEditText.selectAll();
connectToTranslateService();
}
private void connectToTranslateService() {
Intent intent = new Intent(Intent.ACTION_VIEW);
bindService(intent, mTranslateConn, Context.BIND_AUTO_CREATE);
}
@Override
public void onResume() {
super.onResume();
SharedPreferences prefs = getPrefs(this);
mDoTranslate = false;
//
// See if we have any saved preference for From
//
Language from = Language.findLanguageByShortName(prefs.getString(FROM, DEFAULT_FROM));
updateButton(mFromButton, from, false /* don't translate */);
//
// See if we have any saved preference for To
//
//
Language to = Language.findLanguageByShortName(prefs.getString(TO, DEFAULT_TO));
updateButton(mToButton, to, true /* translate */);
//
// Restore input and output, if any
//
mFromEditText.setText(prefs.getString(INPUT, ""));
setOutputText(prefs.getString(OUTPUT, ""));
mDoTranslate = true;
}
private void setOutputText(String string) {
log("Setting output to " + string);
mToEditText.setText(new Entities().unescape(string));
}
private void updateButton(Button button, Language language, boolean translate) {
language.configureButton(this, button);
if (translate) maybeTranslate();
}
/**
* Launch the translation if the input text field is not empty.
*/
private void maybeTranslate() {
if (mDoTranslate && !TextUtils.isEmpty(mFromEditText.getText().toString())) {
doTranslate();
}
}
@Override
public void onPause() {
super.onPause();
//
// Save the content of our views to the shared preferences
//
Editor edit = getPrefs(this).edit();
String f = ((Language) mFromButton.getTag()).getShortName();
String t = ((Language) mToButton.getTag()).getShortName();
String input = mFromEditText.getText().toString();
String output = mToEditText.getText().toString();
savePreferences(edit, f, t, input, output);
}
static void savePreferences(Editor edit, String from, String to, String input, String output) {
log("Saving preferences " + from + " " + to + " " + input + " " + output);
edit.putString(FROM, from);
edit.putString(TO, to);
edit.putString(INPUT, input);
edit.putString(OUTPUT, output);
edit.commit();
}
static SharedPreferences getPrefs(Context context) {
return context.getSharedPreferences(TAG, Context.MODE_PRIVATE);
}
@Override
protected void onDestroy() {
super.onDestroy();
unbindService(mTranslateConn);
}
public void onClick(View v) {
if (v == mTranslateButton) {
maybeTranslate();
} else if (v == mSwapButton) {
Object newFrom = mToButton.getTag();
Object newTo = mFromButton.getTag();
mFromEditText.setText(mToEditText.getText());
mToEditText.setText("");
setNewLanguage((Language) newFrom, true /* from */, false /* don't translate */);
setNewLanguage((Language) newTo, false /* to */, true /* translate */);
mFromEditText.requestFocus();
mStatusView.setText(R.string.languages_swapped);
}
}
private void doTranslate() {
mStatusView.setText(R.string.retrieving_translation);
mHandler.post(new Runnable() {
public void run() {
mProgressBar.setVisibility(View.VISIBLE);
String result = "";
try {
Language from = (Language) mFromButton.getTag();
Language to = (Language) mToButton.getTag();
String fromShortName = from.getShortName();
String toShortName = to.getShortName();
String input = mFromEditText.getText().toString();
log("Translating from " + fromShortName + " to " + toShortName);
result = mTranslateService.translate(input, fromShortName, toShortName);
if (result == null) {
throw new Exception(getString(R.string.translation_failed));
}
History.addHistoryRecord(TranslateActivity.this, from, to, input, result);
mStatusView.setText(R.string.found_translation);
setOutputText(result);
mProgressBar.setVisibility(View.INVISIBLE);
mFromEditText.selectAll();
} catch (Exception e) {
mProgressBar.setVisibility(View.INVISIBLE);
mStatusView.setText("Error:" + e.getMessage());
}
}
});
}
@Override
protected void onPrepareDialog(int id, Dialog d) {
if (id == LANGUAGE_DIALOG_ID) {
boolean from = mLatestButton == mFromButton;
((LanguageDialog) d).setFrom(from);
}
}
@Override
protected Dialog onCreateDialog(int id) {
if (id == LANGUAGE_DIALOG_ID) {
return new LanguageDialog(this);
} else if (id == ABOUT_DIALOG_ID) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(R.string.about_title);
builder.setMessage(getString(R.string.about_message));
builder.setIcon(R.drawable.babelfish);
builder.setPositiveButton(android.R.string.ok, null);
builder.setNeutralButton(R.string.send_email,
new android.content.DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Intent.ACTION_SENDTO);
intent.setData(Uri.parse("mailto:cedric@beust.com"));
startActivity(intent);
}
});
builder.setCancelable(true);
return builder.create();
}
return null;
}
/**
* Pick a random word and set it as the input word.
*/
public void selectRandomWord() {
BufferedReader fr = null;
try {
GZIPInputStream is =
new GZIPInputStream(getResources().openRawResource(R.raw.dictionary));
if (mWordBuffer == null) {
mWordBuffer = new byte[601000];
int n = is.read(mWordBuffer, 0, mWordBuffer.length);
int current = n;
while (n != -1) {
n = is.read(mWordBuffer, current, mWordBuffer.length - current);
current += n;
}
is.close();
mWordCount = 0;
mWordIndices = Lists.newArrayList();
for (int i = 0; i < mWordBuffer.length; i++) {
if (mWordBuffer[i] == '\n') {
mWordCount++;
mWordIndices.add(i);
}
}
log("Found " + mWordCount + " words");
}
int randomWordIndex = (int) (System.currentTimeMillis() % (mWordCount - 1));
log("Random word index:" + randomWordIndex + " wordCount:" + mWordCount);
int start = mWordIndices.get(randomWordIndex);
int end = mWordIndices.get(randomWordIndex + 1);
byte[] b = new byte[end - start - 2];
System.arraycopy(mWordBuffer, start + 1, b, 0, (end - start - 2));
String randomWord = new String(b);
mFromEditText.setText(randomWord);
updateButton(mFromButton,
Language.findLanguageByShortName(Language.ENGLISH.getShortName()),
true /* translate */);
} catch (FileNotFoundException e) {
Log.e(TAG, e.getMessage(), e);
} catch (IOException e) {
Log.e(TAG, e.getMessage(), e);
}
}
public void setNewLanguage(Language language, boolean from, boolean translate) {
updateButton(from ? mFromButton : mToButton, language, translate);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.translate_activity_menu, menu);
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch(item.getItemId()) {
case R.id.about:
showDialog(ABOUT_DIALOG_ID);
break;
case R.id.show_history:
showHistory();
break;
case R.id.random_word:
selectRandomWord();
break;
// We shouldn't need this menu item but because of a bug in 1.0, neither SMS nor Email
// filter on the ACTION_SEND intent. Since they won't be shown in the activity chooser,
// I need to make an explicit menu for SMS
case R.id.send_with_sms: {
Intent i = new Intent(Intent.ACTION_PICK, Contacts.Phones.CONTENT_URI);
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType(Contacts.Phones.CONTENT_TYPE);
startActivityForResult(intent, 42 /* not used */);
break;
}
case R.id.send_with_email:
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, mToEditText.getText());
startActivity(Intent.createChooser(intent, null));
break;
}
return true;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent resultIntent) {
if (resultIntent != null) {
Uri contactURI = resultIntent.getData();
Cursor cursor = getContentResolver().query(contactURI,
new String[] { Contacts.PhonesColumns.NUMBER },
null, null, null);
if (cursor.moveToFirst()) {
String phone = cursor.getString(0);
Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.parse("smsto://" + phone));
intent.putExtra("sms_body", mToEditText.getText().toString());
startActivity(intent);
}
}
}
private void showHistory() {
startActivity(new Intent(this, HistoryActivity.class));
}
private static void log(String s) {
Log.d(TAG, "[TranslateActivity] " + s);
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.