code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
/* * Copyright (C) 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); } }
zzhangumd-apps-for-android
AndroidGlobalTime/src/com/android/globaltime/Shape.java
Java
asf20
9,431
/* * 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); } }
zzhangumd-apps-for-android
AndroidGlobalTime/src/com/android/globaltime/Clock.java
Java
asf20
11,777
/* * 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); } }
zzhangumd-apps-for-android
AndroidGlobalTime/src/com/android/globaltime/Annulus.java
Java
asf20
3,935
/* * 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; } }
zzhangumd-apps-for-android
AndroidGlobalTime/src/com/android/globaltime/Texture.java
Java
asf20
1,079
/* * 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); } }
zzhangumd-apps-for-android
AndroidGlobalTime/src/com/android/globaltime/Sphere.java
Java
asf20
951
/* * 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; } }
zzhangumd-apps-for-android
AndroidGlobalTime/src/com/android/globaltime/PointCloud.java
Java
asf20
2,010
/* * 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; } } }
zzhangumd-apps-for-android
AndroidGlobalTime/src/com/android/globaltime/GlobalTime.java
Java
asf20
46,167
/* * 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); } }
zzhangumd-apps-for-android
AndroidGlobalTime/src/com/android/globaltime/GLView.java
Java
asf20
30,586
/* * 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); } } }
zzhangumd-apps-for-android
Photostream/src/com/google/android/photostream/BootReceiver.java
Java
asf20
1,142
/* * 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; } }
zzhangumd-apps-for-android
Photostream/src/com/google/android/photostream/Flickr.java
Java
asf20
47,139
/* * 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; } } }
zzhangumd-apps-for-android
Photostream/src/com/google/android/photostream/PhotostreamActivity.java
Java
asf20
14,439
/* * 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&lt;URL, Integer, Long&gt; { * 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; } } }
zzhangumd-apps-for-android
Photostream/src/com/google/android/photostream/UserTask.java
Java
asf20
17,155
/* * 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(); } } } }
zzhangumd-apps-for-android
Photostream/src/com/google/android/photostream/ViewPhotoActivity.java
Java
asf20
21,743
/* * 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); } }
zzhangumd-apps-for-android
Photostream/src/com/google/android/photostream/SettingsActivity.java
Java
asf20
1,391
/* * 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()); } } } }
zzhangumd-apps-for-android
Photostream/src/com/google/android/photostream/GridLayout.java
Java
asf20
5,307
/* * 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); } }
zzhangumd-apps-for-android
Photostream/src/com/google/android/photostream/UserDatabase.java
Java
asf20
4,073
/* * 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 } } } }
zzhangumd-apps-for-android
Photostream/src/com/google/android/photostream/Eula.java
Java
asf20
4,525
/* * 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; } }
zzhangumd-apps-for-android
Photostream/src/com/google/android/photostream/LoginActivity.java
Java
asf20
15,461
/* * 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() { } }
zzhangumd-apps-for-android
Photostream/src/com/google/android/photostream/Preferences.java
Java
asf20
1,027
/* * 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; } }
zzhangumd-apps-for-android
Photostream/src/com/google/android/photostream/ImageUtilities.java
Java
asf20
4,964
/* * 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(); } } }
zzhangumd-apps-for-android
Photostream/src/com/google/android/photostream/CheckUpdateService.java
Java
asf20
7,464
/* * 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; } }
zzhangumd-apps-for-android
Photostream/src/com/google/android/photostream/FastBitmapDrawable.java
Java
asf20
1,728
<html> <head> <title>Click, Link, Compete</title> </head> <body> <h1>Click, Link, Compete</h1> <h3>by Charles L. Chen (clchen@google.com)</h3> <p> Click, Link, Compete aims to make multiplayer gaming simple on Android. </p><p> To developers, it offers a layer of abstraction over the Bluetooth APIs; instead of worrying about sockets and input/output streams, developers can think in terms of sending messages and responding to message received events. </p><p> To players, it offers a gaming lobby that enables players to simply CLICK on whether they want to host or join a game, LINK their phones, and COMPETE. </p><p> Click, Link, Compete is still in early beta; feedback and patches are VERY welcome! </p><p> As with all the other apps on AppsForAndroid, Click, Link, Compete is free and open source under Apache License 2.0. Feel free to use it in your apps (whether they are free or not), and if you build something cool with it, please let me know! </p><p> <a href="http://apps-for-android.googlecode.com/svn/trunk/BTClickLinkCompete/for_developers/net.clc.bt_library_1.0.0.jar">Click, Link, Compete Library (1.0.0) for developers</a> </p><p> <a href="http://apps-for-android.googlecode.com/svn/trunk/BTClickLinkCompete/docs/javadoc/index.html">Click, Link, Compete Library JavaDoc</a> </p><p> <a href="http://apps-for-android.googlecode.com/svn/trunk/BTClickLinkCompete/">Click, Link, Compete Source Code</a> </p> </body>
zzhangumd-apps-for-android
BTClickLinkCompete/docs/index.html
HTML
asf20
1,428
/* Javadoc style sheet */ /* Define colors, fonts and other style attributes here to override the defaults */ /* Page background color */ body { background-color: #FFFFFF; color:#000000 } /* Headings */ h1 { font-size: 145% } /* Table colors */ .TableHeadingColor { background: #CCCCFF; color:#000000 } /* Dark mauve */ .TableSubHeadingColor { background: #EEEEFF; color:#000000 } /* Light mauve */ .TableRowColor { background: #FFFFFF; color:#000000 } /* White */ /* Font used in left-hand frame lists */ .FrameTitleFont { font-size: 100%; font-family: Helvetica, Arial, sans-serif; color:#000000 } .FrameHeadingFont { font-size: 90%; font-family: Helvetica, Arial, sans-serif; color:#000000 } .FrameItemFont { font-size: 90%; font-family: Helvetica, Arial, sans-serif; color:#000000 } /* Navigation bar fonts and colors */ .NavBarCell1 { background-color:#EEEEFF; color:#000000} /* Light mauve */ .NavBarCell1Rev { background-color:#00008B; color:#FFFFFF} /* Dark Blue */ .NavBarFont1 { font-family: Arial, Helvetica, sans-serif; color:#000000;color:#000000;} .NavBarFont1Rev { font-family: Arial, Helvetica, sans-serif; color:#FFFFFF;color:#FFFFFF;} .NavBarCell2 { font-family: Arial, Helvetica, sans-serif; background-color:#FFFFFF; color:#000000} .NavBarCell3 { font-family: Arial, Helvetica, sans-serif; background-color:#FFFFFF; color:#000000}
zzhangumd-apps-for-android
BTClickLinkCompete/docs/javadoc/stylesheet.css
CSS
asf20
1,420
/* * 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. */ /** * AIDL for the Bluetooth Connect, Link, Compete Service * IConnection.java is autogenerated from this */ package net.clc.bt; // TODO: Ideally, we would import BluetoothDevice here // and use that instead of just a String in the connect // method for better type safety, but this is currently // not possible yet. import net.clc.bt.IConnectionCallback; // Declare the interface. interface IConnection { String getAddress(); String getName(); int startServer(in String srcApp, in int maxConnections); int connect(in String srcApp, in String device); int sendMessage(in String srcApp, in String device, in String message); int broadcastMessage(in String srcApp, in String message); String getConnections(in String srcApp); int getVersion(); int registerCallback(in String srcApp, IConnectionCallback cb); int unregisterCallback(in String srcApp); void shutdown(in String srcApp); }
zzhangumd-apps-for-android
BTClickLinkCompete/src/net/clc/bt/IConnection.aidl
AIDL
asf20
1,576
/* * 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. */ /** * AIDL for the Bluetooth Connect, Link, Compete Service * IConnectionCallback.java is autogenerated from this */ package net.clc.bt; // Declare the interface. oneway interface IConnectionCallback { void incomingConnection(String device); void maxConnectionsReached(); void messageReceived(String device, String message); void connectionLost(String device); }
zzhangumd-apps-for-android
BTClickLinkCompete/src/net/clc/bt/IConnectionCallback.aidl
AIDL
asf20
1,026
/* * 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); } }
zzhangumd-apps-for-android
BTClickLinkCompete/src/net/clc/bt/Demo_Ball.java
Java
asf20
8,379
/* * 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); } } }
zzhangumd-apps-for-android
BTClickLinkCompete/src/net/clc/bt/Connection.java
Java
asf20
9,455
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(); } } } }
zzhangumd-apps-for-android
BTClickLinkCompete/src/net/clc/bt/AirHockey.java
Java
asf20
17,962
/* * 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(); } }
zzhangumd-apps-for-android
BTClickLinkCompete/src/net/clc/bt/StartDiscoverableModeActivity.java
Java
asf20
3,138
/* * 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(); } }; }
zzhangumd-apps-for-android
BTClickLinkCompete/src/net/clc/bt/ConnectionService.java
Java
asf20
13,167
/* * 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; } }
zzhangumd-apps-for-android
BTClickLinkCompete/src/net/clc/bt/Demo_Multiscreen.java
Java
asf20
12,508
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(); } } }
zzhangumd-apps-for-android
BTClickLinkCompete/src/net/clc/bt/MultiScreenVideo.java
Java
asf20
9,035
/* * 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 } } }
zzhangumd-apps-for-android
BTClickLinkCompete/src/net/clc/bt/ServerListActivity.java
Java
asf20
3,839
/* * 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); } }); } }
zzhangumd-apps-for-android
BTClickLinkCompete/src/net/clc/bt/ConfigActivity.java
Java
asf20
4,743
/* * 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&lt;URL, Integer, Long&gt; { * 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; } } }
zzhangumd-apps-for-android
AnyCut/src/com/google/android/photostream/UserTask.java
Java
asf20
17,144
/* * 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); } }
zzhangumd-apps-for-android
AnyCut/src/com/example/anycut/CustomShortcutCreatorActivity.java
Java
asf20
2,671
/* * 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; } } }
zzhangumd-apps-for-android
AnyCut/src/com/example/anycut/CreateShortcutActivity.java
Java
asf20
11,555
/* * 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); } }
zzhangumd-apps-for-android
AnyCut/src/com/example/anycut/ShortcutEditorDialog.java
Java
asf20
5,566
/* * 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(); } }
zzhangumd-apps-for-android
AnyCut/src/com/example/anycut/ActivityPickerActivity.java
Java
asf20
6,057
/* * 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(); } } } }
zzhangumd-apps-for-android
AnyCut/src/com/example/anycut/FrontDoorActivity.java
Java
asf20
2,594
/* * 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(); } } }
zzhangumd-apps-for-android
CLiCkin2DaBeaT/src/com/google/clickin2dabeat/CreateC2BFile.java
Java
asf20
3,018
/* * 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(); } } } }
zzhangumd-apps-for-android
CLiCkin2DaBeaT/src/com/google/clickin2dabeat/GameView.java
Java
asf20
9,137
/* * 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(); } } }
zzhangumd-apps-for-android
CLiCkin2DaBeaT/src/com/google/clickin2dabeat/DownloadC2BFile.java
Java
asf20
1,904
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) { } } }
zzhangumd-apps-for-android
CLiCkin2DaBeaT/src/com/google/clickin2dabeat/UpdateChecker.java
Java
asf20
2,183
/* * 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; } } }
zzhangumd-apps-for-android
CLiCkin2DaBeaT/src/com/google/clickin2dabeat/C2B.java
Java
asf20
20,275
/* * 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(); } } }
zzhangumd-apps-for-android
CLiCkin2DaBeaT/src/com/google/clickin2dabeat/Unzipper.java
Java
asf20
3,633
/* * 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; } } } }
zzhangumd-apps-for-android
CLiCkin2DaBeaT/src/com/google/clickin2dabeat/Target.java
Java
asf20
1,660
/* * 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; } }
zzhangumd-apps-for-android
CLiCkin2DaBeaT/src/com/google/clickin2dabeat/BeatTimingsAdjuster.java
Java
asf20
4,312
/* * 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(&quot;foo&quot;, 0xA1), escape(&quot;\u00A1&quot;) will return * &quot;&amp;foo;&quot; * </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(&quot;foo&quot;, 0xA1), unescape(&quot;&amp;foo;&quot;) will return * &quot;\u00A1&quot; * </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); } } } }
zzhangumd-apps-for-android
Translate/src/com/beust/android/translate/Entities.java
Java
asf20
40,695
/* * 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(); } }
zzhangumd-apps-for-android
Translate/src/com/beust/android/translate/History.java
Java
asf20
5,374
/* * 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(); } }
zzhangumd-apps-for-android
Translate/src/com/beust/android/translate/Translate.java
Java
asf20
4,350
/* * 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; } }
zzhangumd-apps-for-android
Translate/src/com/beust/android/translate/Lists.java
Java
asf20
2,185
/* * 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); } }
zzhangumd-apps-for-android
Translate/src/com/beust/android/translate/Languages.java
Java
asf20
7,500
/* * 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; } }
zzhangumd-apps-for-android
Translate/src/com/beust/android/translate/HistoryRecord.java
Java
asf20
2,499
// 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; } }
zzhangumd-apps-for-android
Translate/src/com/beust/android/translate/TranslateService.java
Java
asf20
1,806
/* * 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)); } }
zzhangumd-apps-for-android
Translate/src/com/beust/android/translate/LanguageDialog.java
Java
asf20
3,202
/* * 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>(); } }
zzhangumd-apps-for-android
Translate/src/com/beust/android/translate/Maps.java
Java
asf20
1,021
/* * 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); } }
zzhangumd-apps-for-android
Translate/src/com/beust/android/translate/TranslateActivity.java
Java
asf20
16,327
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.beust.android.translate; import android.app.AlertDialog; import android.content.Context; import android.webkit.WebView; /** * Display a simple about dialog. */ public class AboutDialog extends AlertDialog { protected AboutDialog(Context context) { super(context); setContentView(R.layout.about_dialog); setTitle(R.string.about_title); setCancelable(true); WebView webView = (WebView) findViewById(R.id.webview); webView.loadData("Written by C&eacute;dric Beust (<a href=\"mailto:cedric@beust.com\">cedric@beust.com)</a>", "text/html", "utf-8"); } }
zzhangumd-apps-for-android
Translate/src/com/beust/android/translate/AboutDialog.java
Java
asf20
1,234
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.beust.android.translate; import android.app.ListActivity; import android.content.SharedPreferences.Editor; import android.os.Bundle; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.widget.AdapterView; import android.widget.SimpleAdapter; import android.widget.AdapterView.OnItemClickListener; import java.util.List; import java.util.Map; /** * This activity displays the history of past translations. * * @author Cedric Beust * @author Daniel Rall */ public class HistoryActivity extends ListActivity implements OnItemClickListener { private SimpleAdapter mAdapter; private List<Map<String, String>> mListData; private History mHistory; private static final String INPUT = "input"; private static final String OUTPUT = "output"; private static final String FROM = "from"; private static final String TO = "to"; private static final String FROM_SHORT_NAME = "from-short-name"; private static final String TO_SHORT_NAME = "to-short-name"; // These constants are used to bind the adapter to the list view private static final String[] COLUMN_NAMES = { INPUT, OUTPUT, FROM, TO }; private static final int[] VIEW_IDS = { R.id.input, R.id.output, R.id.from, R.id.to }; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.history_activity); mHistory = new History(TranslateActivity.getPrefs(this)); initializeAdapter(mHistory.getHistoryRecordsMostRecentFirst()); getListView().setEmptyView(findViewById(R.id.empty)); } private void initializeAdapter(List<HistoryRecord> historyRecords) { mListData = Lists.newArrayList(); for (HistoryRecord hr : historyRecords) { Map<String, String> data = Maps.newHashMap(); // Values that are bound to views data.put(INPUT, hr.input); data.put(OUTPUT, hr.output); data.put(FROM, hr.from.name().toLowerCase()); data.put(TO, hr.to.name().toLowerCase()); // Extra values we keep around for convenience data.put(FROM_SHORT_NAME, hr.from.getShortName()); data.put(TO_SHORT_NAME, hr.to.getShortName()); mListData.add(data); } mAdapter = new SimpleAdapter(this, mListData, R.layout.history_record, COLUMN_NAMES, VIEW_IDS); getListView().setAdapter(mAdapter); getListView().setOnItemClickListener(this); } @Override public boolean onCreateOptionsMenu(Menu menu) { MenuInflater inflater = getMenuInflater(); inflater.inflate(R.menu.history_activity_menu, menu); return super.onCreateOptionsMenu(menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()) { case R.id.most_recent: initializeAdapter(mHistory.getHistoryRecordsMostRecentFirst()); break; case R.id.languages: initializeAdapter(mHistory.getHistoryRecordsByLanguages()); break; case R.id.clear_history: mHistory.clear(this); initializeAdapter(mHistory.getHistoryRecordsByLanguages()); break; } return true; } public void onItemClick(AdapterView<?> parent, View view, int position, long id) { Map<String, String> data = (Map<String, String>) parent.getItemAtPosition(position); Editor edit = TranslateActivity.getPrefs(this).edit(); TranslateActivity.savePreferences(edit, data.get(FROM_SHORT_NAME), data.get(TO_SHORT_NAME), data.get(INPUT), data.get(OUTPUT)); finish(); } }
zzhangumd-apps-for-android
Translate/src/com/beust/android/translate/HistoryActivity.java
Java
asf20
4,437
/* * 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; /** * AIDL for the TranslateService (generates ITranslate.java). * * @author Daniel Rall */ interface ITranslate { String translate(in String text, in String from, in String to); int getVersion(); }
zzhangumd-apps-for-android
Translate/src/com/beust/android/translate/ITranslate.aidl
AIDL
asf20
850
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.divideandconquer; import android.content.Context; import android.content.res.Resources; import android.graphics.*; import android.graphics.drawable.GradientDrawable; import android.os.Debug; import android.os.SystemClock; import android.util.AttributeSet; import android.util.TypedValue; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import java.util.List; import java.util.ArrayList; /** * Handles the visual display and touch input for the game. */ public class DivideAndConquerView extends View implements BallEngine.BallEventCallBack { static final int BORDER_WIDTH = 10; // this needs to match size of ball drawable static final float BALL_RADIUS = 5f; static final float BALL_SPEED = 80f; // if true, will profile the drawing code during each animating line and export // the result to a file named 'BallsDrawing.trace' on the sd card // this file can be pulled off and profiled with traceview // $ adb pull /sdcard/BallsDrawing.trace . // traceview BallsDrawing.trace private static final boolean PROFILE_DRAWING = false; private boolean mDrawingProfilingStarted = false; private final Paint mPaint; private BallEngine mEngine; private Mode mMode = Mode.Paused; private BallEngineCallBack mCallback; // interface for starting a line private DirectionPoint mDirectionPoint = null; private Bitmap mBallBitmap; private float mBallBitmapRadius; private final Bitmap mExplosion1; private final Bitmap mExplosion2; private final Bitmap mExplosion3; /** * Callback notifying of events related to the ball engine. */ static interface BallEngineCallBack { /** * The engine has its dimensions and is ready to go. * @param ballEngine The ball engine. */ void onEngineReady(BallEngine ballEngine); /** * A ball has hit a moving line. * @param ballEngine The engine. * @param x The x coordinate of the ball. * @param y The y coordinate of the ball. */ void onBallHitsMovingLine(BallEngine ballEngine, float x, float y); /** * A line made it to the edges of its region, splitting off a new region. * @param ballEngine The engine. */ void onAreaChange(BallEngine ballEngine); } /** * @return The ball engine associated with the game. */ public BallEngine getEngine() { return mEngine; } /** * Keeps track of the mode of this view. */ enum Mode { /** * The balls are bouncing around. */ Bouncing, /** * The animation has stopped and the balls won't move around. The user * may not unpause it; this is used to temporarily stop games between * levels, or when the game is over and the activity places a dialog up. */ Paused, /** * Same as {@link #Paused}, but paints the word 'touch to unpause' on * the screen, so the user knows he/she can unpause the game. */ PausedByUser } public DivideAndConquerView(Context context, AttributeSet attrs) { super(context, attrs); mPaint = new Paint(); mPaint.setAntiAlias(true); mPaint.setStrokeWidth(2); mPaint.setColor(Color.BLACK); // so we can see the back key setFocusableInTouchMode(true); drawBackgroundGradient(); mBallBitmap = BitmapFactory.decodeResource( context.getResources(), R.drawable.ball); mBallBitmapRadius = ((float) mBallBitmap.getWidth()) / 2f; mExplosion1 = BitmapFactory.decodeResource( context.getResources(), R.drawable.explosion1); mExplosion2 = BitmapFactory.decodeResource( context.getResources(), R.drawable.explosion2); mExplosion3 = BitmapFactory.decodeResource( context.getResources(), R.drawable.explosion3); } final GradientDrawable mBackgroundGradient = new GradientDrawable( GradientDrawable.Orientation.TOP_BOTTOM, new int[]{Color.RED, Color.YELLOW}); void drawBackgroundGradient() { setBackgroundDrawable(mBackgroundGradient); } /** * Set the callback that will be notified of events related to the ball * engine. * @param callback The callback. */ public void setCallback(BallEngineCallBack callback) { mCallback = callback; } @Override protected void onSizeChanged(int i, int i1, int i2, int i3) { super.onSizeChanged(i, i1, i2, i3); // this should only happen once when the activity is first launched. // we could be smarter about saving / restoring across activity // lifecycles, but for now, this is good enough to handle in game play, // and most cases of navigating away with the home key and coming back. mEngine = new BallEngine( BORDER_WIDTH, getWidth() - BORDER_WIDTH, BORDER_WIDTH, getHeight() - BORDER_WIDTH, BALL_SPEED, BALL_RADIUS); mEngine.setCallBack(this); mCallback.onEngineReady(mEngine); } /** * @return the current mode of operation. */ public Mode getMode() { return mMode; } /** * Set the mode of operation. * @param mode The mode. */ public void setMode(Mode mode) { mMode = mode; if (mMode == Mode.Bouncing && mEngine != null) { // when starting up again, the engine needs to know what 'now' is. final long now = SystemClock.elapsedRealtime(); mEngine.setNow(now); mExplosions.clear(); invalidate(); } } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { // the first time the user hits back while the balls are moving, // we'll pause the game. but if they hit back again, we'll do the usual // (exit the activity) if (keyCode == KeyEvent.KEYCODE_BACK && mMode == Mode.Bouncing) { setMode(Mode.PausedByUser); return true; } return super.onKeyDown(keyCode, event); } @Override public boolean onTouchEvent(MotionEvent motionEvent) { if (mMode == Mode.PausedByUser) { // touching unpauses when the game was paused by the user. setMode(Mode.Bouncing); return true; } else if (mMode == Mode.Paused) { return false; } final float x = motionEvent.getX(); final float y = motionEvent.getY(); switch(motionEvent.getAction()) { case MotionEvent.ACTION_DOWN: if (mEngine.canStartLineAt(x, y)) { mDirectionPoint = new DirectionPoint(x, y); } return true; case MotionEvent.ACTION_MOVE: if (mDirectionPoint != null) { mDirectionPoint.updateEndPoint(x, y); } else if (mEngine.canStartLineAt(x, y)) { mDirectionPoint = new DirectionPoint(x, y); } return true; case MotionEvent.ACTION_UP: if (mDirectionPoint != null) { switch (mDirectionPoint.getDirection()) { case Unknown: // do nothing break; case Horizonal: mEngine.startHorizontalLine(SystemClock.elapsedRealtime(), mDirectionPoint.getX(), mDirectionPoint.getY()); if (PROFILE_DRAWING) { if (!mDrawingProfilingStarted) { Debug.startMethodTracing("BallsDrawing"); mDrawingProfilingStarted = true; } } break; case Vertical: mEngine.startVerticalLine(SystemClock.elapsedRealtime(), mDirectionPoint.getX(), mDirectionPoint.getY()); if (PROFILE_DRAWING) { if (!mDrawingProfilingStarted) { Debug.startMethodTracing("BallsDrawing"); mDrawingProfilingStarted = true; } } break; } } mDirectionPoint = null; return true; case MotionEvent.ACTION_CANCEL: mDirectionPoint = null; return true; } return false; } /** {@inheritDoc} */ public void onBallHitsBall(Ball ballA, Ball ballB) { } /** {@inheritDoc} */ public void onBallHitsLine(long when, Ball ball, AnimatingLine animatingLine) { mCallback.onBallHitsMovingLine(mEngine, ball.getX(), ball.getY()); mExplosions.add( new Explosion( when, ball.getX(), ball.getY(), mExplosion1, mExplosion2, mExplosion3)); } static class Explosion { private long mLastUpdate; private long mProgress = 0; private final float mX; private final float mY; private final Bitmap mExplosion1; private final Bitmap mExplosion2; private final Bitmap mExplosion3; private final float mRadius; Explosion(long mLastUpdate, float mX, float mY, Bitmap explosion1, Bitmap explosion2, Bitmap explosion3) { this.mLastUpdate = mLastUpdate; this.mX = mX; this.mY = mY; this.mExplosion1 = explosion1; this.mExplosion2 = explosion2; this.mExplosion3 = explosion3; mRadius = ((float) mExplosion1.getWidth()) / 2f; } public void update(long now) { mProgress += (now - mLastUpdate); mLastUpdate = now; } public void setNow(long now) { mLastUpdate = now; } public void draw(Canvas canvas, Paint paint) { if (mProgress < 80L) { canvas.drawBitmap(mExplosion1, mX - mRadius, mY - mRadius, paint); } else if (mProgress < 160L) { canvas.drawBitmap(mExplosion2, mX - mRadius, mY - mRadius, paint); } else if (mProgress < 400L) { canvas.drawBitmap(mExplosion3, mX - mRadius, mY - mRadius, paint); } } public boolean done() { return mProgress > 700L; } } private ArrayList<Explosion> mExplosions = new ArrayList<Explosion>(); @Override protected void onDraw(Canvas canvas) { boolean newRegion = false; if (mMode == Mode.Bouncing) { // handle the ball engine final long now = SystemClock.elapsedRealtime(); newRegion = mEngine.update(now); if (newRegion) { mCallback.onAreaChange(mEngine); // reset back to full alpha bg color drawBackgroundGradient(); } if (PROFILE_DRAWING) { if (newRegion && mDrawingProfilingStarted) { mDrawingProfilingStarted = false; Debug.stopMethodTracing(); } } // the X-plosions for (int i = 0; i < mExplosions.size(); i++) { final Explosion explosion = mExplosions.get(i); explosion.update(now); } } for (int i = 0; i < mEngine.getRegions().size(); i++) { BallRegion region = mEngine.getRegions().get(i); drawRegion(canvas, region); } for (int i = 0; i < mExplosions.size(); i++) { final Explosion explosion = mExplosions.get(i); explosion.draw(canvas, mPaint); // TODO prune explosions that are done } if (mMode == Mode.PausedByUser) { drawPausedText(canvas); } else if (mMode == Mode.Bouncing) { // keep em' bouncing! invalidate(); } } /** * Pain the text instructing the user how to unpause the game. */ private void drawPausedText(Canvas canvas) { mPaint.setColor(Color.BLACK); mPaint.setAntiAlias(true); mPaint.setTextSize( TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_SP, 20, getResources().getDisplayMetrics())); final String unpauseInstructions = getContext().getString(R.string.unpause_instructions); canvas.drawText(unpauseInstructions, getWidth() / 5, getHeight() / 2, mPaint); mPaint.setAntiAlias(false); } private RectF mRectF = new RectF(); /** * Draw a ball region. */ private void drawRegion(Canvas canvas, BallRegion region) { // draw fill rect to offset against background mPaint.setColor(Color.LTGRAY); mRectF.set(region.getLeft(), region.getTop(), region.getRight(), region.getBottom()); canvas.drawRect(mRectF, mPaint); //draw an outline mPaint.setStyle(Paint.Style.STROKE); mPaint.setColor(Color.WHITE); canvas.drawRect(mRectF, mPaint); mPaint.setStyle(Paint.Style.FILL); // restore style // draw each ball for (Ball ball : region.getBalls()) { // canvas.drawCircle(ball.getX(), ball.getY(), BALL_RADIUS, mPaint); canvas.drawBitmap( mBallBitmap, ball.getX() - mBallBitmapRadius, ball.getY() - mBallBitmapRadius, mPaint); } // draw the animating line final AnimatingLine al = region.getAnimatingLine(); if (al != null) { drawAnimatingLine(canvas, al); } } private static int scaleToBlack(int component, float percentage) { // return (int) ((1f - percentage*0.4f) * component); return (int) (percentage * 0.6f * (0xFF - component) + component); } /** * Draw an animating line. */ private void drawAnimatingLine(Canvas canvas, AnimatingLine al) { final float perc = al.getPercentageDone(); final int color = Color.RED; mPaint.setColor(Color.argb( 0xFF, scaleToBlack(Color.red(color), perc), scaleToBlack(Color.green(color), perc), scaleToBlack(Color.blue(color), perc) )); switch (al.getDirection()) { case Horizontal: canvas.drawLine( al.getStart(), al.getPerpAxisOffset(), al.getEnd(), al.getPerpAxisOffset(), mPaint); break; case Vertical: canvas.drawLine( al.getPerpAxisOffset(), al.getStart(), al.getPerpAxisOffset(), al.getEnd(), mPaint); break; } } }
zzhangumd-apps-for-android
DivideAndConquer/src/com/google/android/divideandconquer/DivideAndConquerView.java
Java
asf20
16,341
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.divideandconquer; /** * A 2d shape has left, right, top and bottom dimensions. * */ public abstract class Shape2d { public abstract float getLeft(); public abstract float getRight(); public abstract float getTop(); public abstract float getBottom(); /** * @param other Another 2d shape * @return Whether this shape is intersecting with the other. */ public boolean isIntersecting(Shape2d other) { return getLeft() <= other.getRight() && getRight() >= other.getLeft() && getTop() <= other.getBottom() && getBottom() >= other.getTop(); } /** * @param x An x coordinate * @param y A y coordinate * @return Whether the point is within this shape */ public boolean isPointWithin(float x, float y) { return (x > getLeft() && x < getRight() && y > getTop() && y < getBottom()); } public float getArea() { return getHeight() * getWidth(); } public float getHeight() { return getBottom() - getTop(); } public float getWidth () { return getRight() - getLeft(); } }
zzhangumd-apps-for-android
DivideAndConquer/src/com/google/android/divideandconquer/Shape2d.java
Java
asf20
1,765
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.divideandconquer; /** * Used by dialogs to tell the activity the user wants a new game. */ public interface NewGameCallback { /** * The user wants to start a new game. */ void onNewGame(); }
zzhangumd-apps-for-android
DivideAndConquer/src/com/google/android/divideandconquer/NewGameCallback.java
Java
asf20
840
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.divideandconquer; /** * Either vertical or horizontal. Used by animating lines and * ball regions. */ public enum Direction { Vertical, Horizontal }
zzhangumd-apps-for-android
DivideAndConquer/src/com/google/android/divideandconquer/Direction.java
Java
asf20
789
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.divideandconquer; import android.app.Activity; import android.app.Dialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.os.Bundle; import android.os.SystemClock; import android.os.Vibrator; import android.preference.PreferenceManager; import android.view.Menu; import android.view.MenuItem; import android.view.Window; import android.view.Gravity; import android.widget.TextView; import android.widget.Toast; import android.graphics.Color; import java.util.Stack; /** * The activity for the game. Listens for callbacks from the game engine, and * response appropriately, such as bringing up a 'game over' dialog when a ball * hits a moving line and there is only one life left. */ public class DivideAndConquerActivity extends Activity implements DivideAndConquerView.BallEngineCallBack, NewGameCallback, DialogInterface.OnCancelListener { private static final int NEW_GAME_NUM_BALLS = 1; private static final double LEVEL_UP_THRESHOLD = 0.8; private static final int COLLISION_VIBRATE_MILLIS = 50; private boolean mVibrateOn; private int mNumBalls = NEW_GAME_NUM_BALLS; private DivideAndConquerView mBallsView; private static final int WELCOME_DIALOG = 20; private static final int GAME_OVER_DIALOG = 21; private WelcomeDialog mWelcomeDialog; private GameOverDialog mGameOverDialog; private TextView mLivesLeft; private TextView mPercentContained; private int mNumLives; private Vibrator mVibrator; private TextView mLevelInfo; private int mNumLivesStart = 5; private Toast mCurrentToast; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // Turn off the title bar requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.main); mBallsView = (DivideAndConquerView) findViewById(R.id.ballsView); mBallsView.setCallback(this); mPercentContained = (TextView) findViewById(R.id.percentContained); mLevelInfo = (TextView) findViewById(R.id.levelInfo); mLivesLeft = (TextView) findViewById(R.id.livesLeft); // we'll vibrate when the ball hits the moving line mVibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE); } /** {@inheritDoc} */ public void onEngineReady(BallEngine ballEngine) { // display 10 balls bouncing around for visual effect ballEngine.reset(SystemClock.elapsedRealtime(), 10); mBallsView.setMode(DivideAndConquerView.Mode.Bouncing); // show the welcome dialog showDialog(WELCOME_DIALOG); } @Override protected Dialog onCreateDialog(int id) { if (id == WELCOME_DIALOG) { mWelcomeDialog = new WelcomeDialog(this, this); mWelcomeDialog.setOnCancelListener(this); return mWelcomeDialog; } else if (id == GAME_OVER_DIALOG) { mGameOverDialog = new GameOverDialog(this, this); mGameOverDialog.setOnCancelListener(this); return mGameOverDialog; } return null; } @Override protected void onPause() { super.onPause(); mBallsView.setMode(DivideAndConquerView.Mode.PausedByUser); } @Override protected void onResume() { super.onResume(); mVibrateOn = PreferenceManager.getDefaultSharedPreferences(this) .getBoolean(Preferences.KEY_VIBRATE, true); mNumLivesStart = Preferences.getCurrentDifficulty(this).getLivesToStart(); } private static final int MENU_NEW_GAME = Menu.FIRST; private static final int MENU_SETTINGS = Menu.FIRST + 1; @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); menu.add(0, MENU_NEW_GAME, MENU_NEW_GAME, "New Game"); menu.add(0, MENU_SETTINGS, MENU_SETTINGS, "Settings"); return true; } /** * We pause the game while the menu is open; this remembers what it was * so we can restore when the menu closes */ Stack<DivideAndConquerView.Mode> mRestoreMode = new Stack<DivideAndConquerView.Mode>(); @Override public boolean onMenuOpened(int featureId, Menu menu) { saveMode(); mBallsView.setMode(DivideAndConquerView.Mode.Paused); return super.onMenuOpened(featureId, menu); } @Override public boolean onOptionsItemSelected(MenuItem item) { super.onOptionsItemSelected(item); switch (item.getItemId()) { case MENU_NEW_GAME: cancelToasts(); onNewGame(); break; case MENU_SETTINGS: final Intent intent = new Intent(); intent.setClass(this, Preferences.class); startActivity(intent); break; } mRestoreMode.pop(); // don't want to restore when an action was taken return true; } @Override public void onOptionsMenuClosed(Menu menu) { super.onOptionsMenuClosed(menu); restoreMode(); } private void saveMode() { // don't want to restore to a state where user can't resume game. final DivideAndConquerView.Mode mode = mBallsView.getMode(); final DivideAndConquerView.Mode toRestore = (mode == DivideAndConquerView.Mode.Paused) ? DivideAndConquerView.Mode.PausedByUser : mode; mRestoreMode.push(toRestore); } private void restoreMode() { if (!mRestoreMode.isEmpty()) { mBallsView.setMode(mRestoreMode.pop()); } } /** {@inheritDoc} */ public void onBallHitsMovingLine(final BallEngine ballEngine, float x, float y) { if (--mNumLives == 0) { saveMode(); mBallsView.setMode(DivideAndConquerView.Mode.Paused); // vibrate three times if (mVibrateOn) { mVibrator.vibrate( new long[]{0l, COLLISION_VIBRATE_MILLIS, 50l, COLLISION_VIBRATE_MILLIS, 50l, COLLISION_VIBRATE_MILLIS}, -1); } showDialog(GAME_OVER_DIALOG); } else { if (mVibrateOn) { mVibrator.vibrate(COLLISION_VIBRATE_MILLIS); } updateLivesDisplay(mNumLives); if (mNumLives <= 1) { mBallsView.postDelayed(mOneLifeToastRunnable, 700); } else { mBallsView.postDelayed(mLivesBlinkRedRunnable, 700); } } } private Runnable mOneLifeToastRunnable = new Runnable() { public void run() { showToast("1 life left!"); } }; private Runnable mLivesBlinkRedRunnable = new Runnable() { public void run() { mLivesLeft.setTextColor(Color.RED); mLivesLeft.postDelayed(mLivesTextWhiteRunnable, 2000); } }; /** {@inheritDoc} */ public void onAreaChange(final BallEngine ballEngine) { final float percentageFilled = ballEngine.getPercentageFilled(); updatePercentDisplay(percentageFilled); if (percentageFilled > LEVEL_UP_THRESHOLD) { levelUp(ballEngine); } } /** * Go to the next level * @param ballEngine The ball engine. */ private void levelUp(final BallEngine ballEngine) { mNumBalls++; updatePercentDisplay(0); updateLevelDisplay(mNumBalls); ballEngine.reset(SystemClock.elapsedRealtime(), mNumBalls); mBallsView.setMode(DivideAndConquerView.Mode.Bouncing); if (mNumBalls % 4 == 0) { mNumLives++; updateLivesDisplay(mNumLives); showToast("bonus life!"); } if (mNumBalls == 10) { showToast("Level 10? You ROCK!"); } else if (mNumBalls == 15) { showToast("BALLS TO THE WALL!"); } } private Runnable mLivesTextWhiteRunnable = new Runnable() { public void run() { mLivesLeft.setTextColor(Color.WHITE); } }; private void showToast(String text) { cancelToasts(); mCurrentToast = Toast.makeText(this, text, Toast.LENGTH_SHORT); mCurrentToast.show(); } private void cancelToasts() { if (mCurrentToast != null) { mCurrentToast.cancel(); mCurrentToast = null; } } /** * Update the header that displays how much of the space has been contained. * @param amountFilled The fraction, between 0 and 1, that is filled. */ private void updatePercentDisplay(float amountFilled) { final int prettyPercent = (int) (amountFilled *100); mPercentContained.setText( getString(R.string.percent_contained, prettyPercent)); } /** {@inheritDoc} */ public void onNewGame() { mNumBalls = NEW_GAME_NUM_BALLS; mNumLives = mNumLivesStart; updatePercentDisplay(0); updateLivesDisplay(mNumLives); updateLevelDisplay(mNumBalls); mBallsView.getEngine().reset(SystemClock.elapsedRealtime(), mNumBalls); mBallsView.setMode(DivideAndConquerView.Mode.Bouncing); } /** * Update the header displaying the current level */ private void updateLevelDisplay(int numBalls) { mLevelInfo.setText(getString(R.string.level, numBalls)); } /** * Update the display showing the number of lives left. * @param numLives The number of lives left. */ void updateLivesDisplay(int numLives) { String text = (numLives == 1) ? getString(R.string.one_life_left) : getString(R.string.lives_left, numLives); mLivesLeft.setText(text); } /** {@inheritDoc} */ public void onCancel(DialogInterface dialog) { if (dialog == mWelcomeDialog || dialog == mGameOverDialog) { // user hit back, they're done finish(); } } }
zzhangumd-apps-for-android
DivideAndConquer/src/com/google/android/divideandconquer/DivideAndConquerActivity.java
Java
asf20
10,785
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.divideandconquer; import android.util.Log; import android.content.Context; import android.widget.Toast; import java.util.List; import java.util.ArrayList; import java.util.Iterator; /** * Keeps track of the current state of balls bouncing around within a a set of * regions. * * Note: 'now' is the elapsed time in milliseconds since some consistent point in time. * As long as the reference point stays consistent, the engine will be happy, though * typically this is {@link android.os.SystemClock#elapsedRealtime()} */ public class BallEngine { static public interface BallEventCallBack { void onBallHitsBall(Ball ballA, Ball ballB); void onBallHitsLine(long when, Ball ball, AnimatingLine animatingLine); } private final float mMinX; private final float mMaxX; private final float mMinY; private final float mMaxY; private float mBallSpeed; private float mBallRadius; private BallEventCallBack mCallBack; /** * Holds onto new regions during a split */ private List<BallRegion> mNewRegions = new ArrayList<BallRegion>(8); private List<BallRegion> mRegions = new ArrayList<BallRegion>(8); public BallEngine(float minX, float maxX, float minY, float maxY, float ballSpeed, float ballRadius) { mMinX = minX; mMaxX = maxX; mMinY = minY; mMaxY = maxY; mBallSpeed = ballSpeed; mBallRadius = ballRadius; } public void setCallBack(BallEventCallBack mCallBack) { this.mCallBack = mCallBack; } /** * Update the notion of 'now' in milliseconds. This can be usefull * when unpausing for instance. * @param now Milliseconds since some consistent point in time. */ public void setNow(long now) { for (int i = 0; i < mRegions.size(); i++) { final BallRegion region = mRegions.get(i); region.setNow(now); } } /** * Rest the engine back to a single region with a certain number of balls * that will be placed randomly and sent in random directions. * @param now milliseconds since some consistent point in time. * @param numBalls */ public void reset(long now, int numBalls) { mRegions.clear(); ArrayList<Ball> balls = new ArrayList<Ball>(numBalls); for (int i = 0; i < numBalls; i++) { Ball ball = new Ball.Builder() .setNow(now) .setPixelsPerSecond(mBallSpeed) .setAngle(Math.random() * 2 * Math.PI) .setX((float) Math.random() * (mMaxX - mMinX) + mMinX) .setY((float) Math.random() * (mMaxY - mMinY) + mMinY) .setRadiusPixels(mBallRadius) .create(); balls.add(ball); } BallRegion region = new BallRegion(now, mMinX, mMaxX, mMinY, mMaxY, balls); region.setCallBack(mCallBack); mRegions.add(region); } public List<BallRegion> getRegions() { return mRegions; } public float getPercentageFilled() { float total = 0f; for (int i = 0; i < mRegions.size(); i++) { BallRegion region = mRegions.get(i); total += region.getArea(); Log.d("Balls", "total now " + total); } return 1f - (total / getArea()); } /** * @return the area in the region in pixel*pixel */ public float getArea() { return (mMaxX - mMinX) * (mMaxY - mMinY); } /** * Can any of the regions within start a line at this point? * @param x The x coordinate. * @param y The y coordinate * @return Whether a region can start a line. */ public boolean canStartLineAt(float x, float y) { for (BallRegion region : mRegions) { if (region.canStartLineAt(x, y)) { return true; } } return false; } /** * Start a horizontal line at a certain point. * @throws IllegalArgumentException if there is no region that can start a * line at the point. */ public void startHorizontalLine(long now, float x, float y) { for (BallRegion region : mRegions) { if (region.canStartLineAt(x, y)) { region.startHorizontalLine(now, x, y); return; } } throw new IllegalArgumentException("no region can start a new line at " + x + ", " + y + "."); } /** * Start a vertical line at a certain point. * @throws IllegalArgumentException if there is no region that can start a * line at the point. */ public void startVerticalLine(long now, float x, float y) { for (BallRegion region : mRegions) { if (region.canStartLineAt(x, y)) { region.startVerticalLine(now, x, y); return; } } throw new IllegalArgumentException("no region can start a new line at " + x + ", " + y + "."); } /** * @param now The latest notion of 'now' * @return whether any new regions were added by the update. */ public boolean update(long now) { boolean regionChange = false; Iterator<BallRegion> it = mRegions.iterator(); while (it.hasNext()) { final BallRegion region = it.next(); final BallRegion newRegion = region.update(now); if (newRegion != null) { regionChange = true; if (!newRegion.getBalls().isEmpty()) { mNewRegions.add(newRegion); } // current region may not have any balls left if (region.getBalls().isEmpty()) { it.remove(); } } else if (region.consumeDoneShrinking()) { regionChange = true; } } mRegions.addAll(mNewRegions); mNewRegions.clear(); return regionChange; } }
zzhangumd-apps-for-android
DivideAndConquer/src/com/google/android/divideandconquer/BallEngine.java
Java
asf20
6,737
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.divideandconquer; /** * Keeps the state for the line that extends in two directions until it hits its boundaries. This is triggered * by the user gesture in a horizontal or vertical direction. */ public class AnimatingLine extends Shape2d { private Direction mDirection; // for vertical lines, the y offset // for horizontal, the x offset float mPerpAxisOffset; float mStart; float mEnd; float mMin; float mMax; private long mLastUpdate = 0; private float mPixelsPerSecond = 101.0f; /** * @param direction The direction of the line * @param now What 'now' is * @param axisStart Where on the perpindicular axis the line is extending from * @param start The point the line is extending from on the parallel axis * @param min The lower bound for the line (i.e the left most point) * @param max The upper bound for the line (i.e the right most point) */ public AnimatingLine( Direction direction, long now, float axisStart, float start, float min, float max) { mDirection = direction; mLastUpdate = now; mPerpAxisOffset = axisStart; mStart = mEnd = start; mMin = min; mMax = max; } public Direction getDirection() { return mDirection; } public float getPerpAxisOffset() { return mPerpAxisOffset; } public float getStart() { return mStart; } public float getEnd() { return mEnd; } public float getMin() { return mMin; } public float getMax() { return mMax; } public float getLeft() { return mDirection == Direction.Horizontal ? mStart : mPerpAxisOffset; } public float getRight() { return mDirection == Direction.Horizontal ? mEnd : mPerpAxisOffset; } public float getTop() { return mDirection == Direction.Vertical ? mStart : mPerpAxisOffset; } public float getBottom() { return mDirection == Direction.Vertical ? mEnd : mPerpAxisOffset; } public float getPercentageDone() { return (mEnd - mStart) / (mMax - mMin); } /** * Extend the line according to the animation. * @return whether the line has reached its end. */ public boolean update(long time) { if (time == mLastUpdate) return false; float delta = (time - mLastUpdate) * mPixelsPerSecond; delta = delta / 1000; mLastUpdate = time; mStart -= delta; mEnd += delta; if (mStart < mMin) mStart = mMin; if (mEnd > mMax) mEnd = mMax; return mStart == mMin && mEnd == mMax; } public void setNow(long now) { mLastUpdate = now; } }
zzhangumd-apps-for-android
DivideAndConquer/src/com/google/android/divideandconquer/AnimatingLine.java
Java
asf20
3,416
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.divideandconquer; import java.util.List; import java.util.ArrayList; import java.util.Iterator; import java.lang.ref.WeakReference; /** * A ball region is a rectangular region that contains bouncing * balls, and possibly one animating line. In its {@link #update(long)} method, * it will update all of its balls, the moving line. It detects collisions * between the balls and the moving line, and when the line is complete, handles * splitting off a new region. */ public class BallRegion extends Shape2d { private float mLeft; private float mRight; private float mTop; private float mBottom; private List<Ball> mBalls; private AnimatingLine mAnimatingLine; private boolean mShrinkingToFit = false; private long mLastUpdate = 0; private static final float PIXELS_PER_SECOND = 25.0f; private static final float SHRINK_TO_FIT_AREA_THRESH = 10000.0f; private static final float SHRINK_TO_FIT_AREA_THRESH_ONE_BALL = 20000.0f; private static final float SHRINK_TO_FIT_AREA = 1000f; private static final float MIN_EDGE = 30f; private boolean mDoneShrinking = false; private WeakReference<BallEngine.BallEventCallBack> mCallBack; /* * @param left The minimum x component * @param right The maximum x component * @param top The minimum y component * @param bottom The maximum y component * @param balls the balls of the region */ public BallRegion(long now, float left, float right, float top, float bottom, ArrayList<Ball> balls) { mLastUpdate = now; mLeft = left; mRight = right; mTop = top; mBottom = bottom; mBalls = balls; final int numBalls = mBalls.size(); for (int i = 0; i < numBalls; i++) { final Ball ball = mBalls.get(i); ball.setRegion(this); } checkShrinkToFit(); } public void setCallBack(BallEngine.BallEventCallBack callBack) { this.mCallBack = new WeakReference<BallEngine.BallEventCallBack>(callBack); } private void checkShrinkToFit() { final float area = getArea(); if (area < SHRINK_TO_FIT_AREA_THRESH) { mShrinkingToFit = true; } else if (area < SHRINK_TO_FIT_AREA_THRESH_ONE_BALL && mBalls.size() == 1) { mShrinkingToFit = true; } } public float getLeft() { return mLeft; } public float getRight() { return mRight; } public float getTop() { return mTop; } public float getBottom() { return mBottom; } public List<Ball> getBalls() { return mBalls; } public AnimatingLine getAnimatingLine() { return mAnimatingLine; } public boolean consumeDoneShrinking() { if (mDoneShrinking) { mDoneShrinking = false; return true; } return false; } public void setNow(long now) { mLastUpdate = now; // update the balls final int numBalls = mBalls.size(); for (int i = 0; i < numBalls; i++) { final Ball ball = mBalls.get(i); ball.setNow(now); } if (mAnimatingLine != null) { mAnimatingLine.setNow(now); } } /** * Update the balls an (if it exists) the animating line in this region. * @param now in millis * @return A new region if a split has occured because the animating line * finished. */ public BallRegion update(long now) { // update the animating line final boolean newRegion = (mAnimatingLine != null && mAnimatingLine.update(now)); final int numBalls = mBalls.size(); // move balls, check for collision with animating line for (int i = 0; i < numBalls; i++) { final Ball ball = mBalls.get(i); ball.update(now); if (mAnimatingLine != null && ball.isIntersecting(mAnimatingLine)) { mAnimatingLine = null; if (mCallBack != null) mCallBack.get().onBallHitsLine(now, ball, mAnimatingLine); } } // update ball to ball collisions for (int i = 0; i < numBalls; i++) { final Ball ball = mBalls.get(i); for (int j = i + 1; j < numBalls; j++) { Ball other = mBalls.get(j); if (ball.isCircleOverlapping(other)) { Ball.adjustForCollision(ball, other); break; } } } handleShrinkToFit(now); // no collsion, new region means we need to split out the apropriate // balls into a new region if (newRegion && mAnimatingLine != null) { BallRegion otherRegion = splitRegion( now, mAnimatingLine.getDirection(), mAnimatingLine.getPerpAxisOffset()); mAnimatingLine = null; return otherRegion; } else { return null; } } private void handleShrinkToFit(long now) { // update shrinking to fit if (mShrinkingToFit && mAnimatingLine == null) { if (now == mLastUpdate) return; float delta = (now - mLastUpdate) * PIXELS_PER_SECOND; delta = delta / 1000; if (getHeight() > MIN_EDGE) { mTop += delta; mBottom -= delta; } if (getWidth() > MIN_EDGE) { mLeft += delta; mRight -= delta; } final int numBalls = mBalls.size(); for (int i = 0; i < numBalls; i++) { final Ball ball = mBalls.get(i); ball.setRegion(this); } if (getArea() <= SHRINK_TO_FIT_AREA) { mShrinkingToFit = false; mDoneShrinking = true; } } mLastUpdate = now; } /** * Return whether this region can start a line at a certain point. */ public boolean canStartLineAt(float x, float y) { return !mShrinkingToFit && mAnimatingLine == null && isPointWithin(x, y); } /** * Start a horizontal line at a point. * @param now What 'now' is. * @param x The x coordinate. * @param y The y coordinate. */ public void startHorizontalLine(long now, float x, float y) { if (!canStartLineAt(x, y)) { throw new IllegalArgumentException( "can't start line with point (" + x + "," + y + ")"); } mAnimatingLine = new AnimatingLine(Direction.Horizontal, now, y, x, mLeft, mRight); } /** * Start a vertical line at a point. * @param now What 'now' is. * @param x The x coordinate. * @param y The y coordinate. */ public void startVerticalLine(long now, float x, float y) { if (!canStartLineAt(x, y)) { throw new IllegalArgumentException( "can't start line with point (" + x + "," + y + ")"); } mAnimatingLine = new AnimatingLine(Direction.Vertical, now, x, y, mTop, mBottom); } /** * Splits this region at a certain offset, shrinking this one down and returning * the other region that makes up the rest. * @param direction The direction of the line. * @param perpAxisOffset The offset of the perpendicular axis of the line. * @return A new region containing a portion of the balls. */ private BallRegion splitRegion(long now, Direction direction, float perpAxisOffset) { ArrayList<Ball> splitBalls = new ArrayList<Ball>(); if (direction == Direction.Horizontal) { Iterator<Ball> it = mBalls.iterator(); while (it.hasNext()) { Ball ball = it.next(); if (ball.getY() > perpAxisOffset) { it.remove(); splitBalls.add(ball); } } float oldBottom = mBottom; mBottom = perpAxisOffset; checkShrinkToFit(); final BallRegion region = new BallRegion(now, mLeft, mRight, perpAxisOffset, oldBottom, splitBalls); region.setCallBack(mCallBack.get()); return region; } else { assert(direction == Direction.Vertical); Iterator<Ball> it = mBalls.iterator(); while (it.hasNext()) { Ball ball = it.next(); if (ball.getX() > perpAxisOffset) { it.remove(); splitBalls.add(ball); } } float oldRight = mRight; mRight = perpAxisOffset; checkShrinkToFit(); final BallRegion region = new BallRegion(now, perpAxisOffset, oldRight, mTop, mBottom, splitBalls); region.setCallBack(mCallBack.get()); return region; } } }
zzhangumd-apps-for-android
DivideAndConquer/src/com/google/android/divideandconquer/BallRegion.java
Java
asf20
9,737
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.divideandconquer; import android.app.Dialog; import android.view.View; import android.content.Context; import android.os.Bundle; public class GameOverDialog extends Dialog implements View.OnClickListener { private View mNewGame; private final NewGameCallback mCallback; private View mQuit; public GameOverDialog(Context context, NewGameCallback callback) { super(context); mCallback = callback; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTitle(R.string.game_over); setContentView(R.layout.game_over_dialog); mNewGame = findViewById(R.id.newGame); mNewGame.setOnClickListener(this); mQuit = findViewById(R.id.quit); mQuit.setOnClickListener(this); } /** {@inheritDoc} */ public void onClick(View v) { if (v == mNewGame) { mCallback.onNewGame(); dismiss(); } else if (v == mQuit) { cancel(); } } }
zzhangumd-apps-for-android
DivideAndConquer/src/com/google/android/divideandconquer/GameOverDialog.java
Java
asf20
1,672
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.divideandconquer; /** * To specify a dividing line, a user hits the screen and drags in a * certain direction. Once the line has been drawn long enough and mostly * in a particular direction (vertical, or horizontal), we can decide we * know what they mean. Otherwise, it is unknown. * * This is also nice because if the user decides they don't want to send * a dividing line, they can just drag their finger back to where they first * touched and let go, cancelling. */ public class DirectionPoint { enum AmbiguousDirection { Vertical, Horizonal, Unknown } private float mX; private float mY; private float endLineX; private float endLineY; public DirectionPoint(float x, float y) { mX = x; mY = y; endLineX = x; endLineY = y; } public void updateEndPoint(float x, float y) { endLineX = x; endLineY = y; } public float getX() { return mX; } public float getY() { return mY; } /** * We know the direction when the line is at leat 20 pixels long, * and the angle is no more than PI / 6 away from a definitive direction. */ public AmbiguousDirection getDirection() { float dx = endLineX - mX; double distance = Math.hypot(dx, endLineY - mY); if (distance < 10) { return AmbiguousDirection.Unknown; } double angle = Math.acos(dx / distance); double thresh = Math.PI / 6; if ((angle < thresh || (angle > (Math.PI - thresh)))) { return AmbiguousDirection.Horizonal; } if ((angle > 2 * thresh) && angle < 4*thresh) { return AmbiguousDirection.Vertical; } return AmbiguousDirection.Unknown; } }
zzhangumd-apps-for-android
DivideAndConquer/src/com/google/android/divideandconquer/DirectionPoint.java
Java
asf20
2,430
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.divideandconquer; import android.os.Bundle; import android.preference.*; import android.content.Context; import android.content.SharedPreferences; /** * Holds preferences for the game */ public class Preferences extends PreferenceActivity { public static final String KEY_VIBRATE = "key_vibrate"; public static final String KEY_DIFFICULTY = "key_difficulty"; public enum Difficulty { Easy(5), Medium(3), Hard(1); private final int mLivesToStart; Difficulty(int livesToStart) { mLivesToStart = livesToStart; } public int getLivesToStart() { return mLivesToStart; } } public static Difficulty getCurrentDifficulty(Context context) { final SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context); final String diffic = preferences .getString(KEY_DIFFICULTY, DEFAULT_DIFFICULTY.toString()); return Difficulty.valueOf(diffic); } public static final Difficulty DEFAULT_DIFFICULTY = Difficulty.Medium; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setPreferenceScreen(createPreferenceHierarchy()); } private PreferenceScreen createPreferenceHierarchy() { // Root PreferenceScreen root = getPreferenceManager().createPreferenceScreen(this); // vibrate on/off CheckBoxPreference vibratePref = new CheckBoxPreference(this); vibratePref.setDefaultValue(true); vibratePref.setKey(KEY_VIBRATE); vibratePref.setTitle(R.string.settings_vibrate); vibratePref.setSummary(R.string.settings_vibrate_summary); root.addPreference(vibratePref); // difficulty level ListPreference difficultyPref = new ListPreference(this); difficultyPref.setEntries(new String[] { getString(R.string.settings_five_lives), getString(R.string.settings_three_lives), getString(R.string.settings_one_life)}); difficultyPref.setEntryValues(new String[] { Difficulty.Easy.toString(), Difficulty.Medium.toString(), Difficulty.Hard.toString()}); difficultyPref.setKey(KEY_DIFFICULTY); difficultyPref.setTitle(R.string.settings_difficulty); difficultyPref.setSummary(R.string.settings_difficulty_summary); final SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(this); if (!sharedPrefs.contains(KEY_DIFFICULTY)) { difficultyPref.setValue(DEFAULT_DIFFICULTY.toString()); } root.addPreference(difficultyPref); return root; } }
zzhangumd-apps-for-android
DivideAndConquer/src/com/google/android/divideandconquer/Preferences.java
Java
asf20
3,429
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.divideandconquer; /** * A ball has a current location, a trajectory angle, a speed in pixels per * second, and a last update time. It is capable of updating itself based on * its trajectory and speed. * * It also knows its boundaries, and will 'bounce' off them when it reaches them. */ public class Ball extends Shape2d { private long mLastUpdate; private float mX; private float mY; private double mAngle; private final float mPixelsPerSecond; private final float mRadiusPixels; private Shape2d mRegion; private Ball(long now, float pixelsPerSecond, float x, float y, double angle, float radiusPixels) { mLastUpdate = now; mPixelsPerSecond = pixelsPerSecond; mX = x; mY = y; mAngle = angle; mRadiusPixels = radiusPixels; } public float getX() { return mX; } public float getY() { return mY; } public float getLeft() { return mX - mRadiusPixels; } public float getRight() { return mX + mRadiusPixels; } public float getTop() { return mY - mRadiusPixels; } public float getBottom() { return mY + mRadiusPixels; } public float getRadiusPixels() { return mRadiusPixels; } public double getAngle() { return mAngle; } /** * Get the region the ball is contained in. */ public Shape2d getRegion() { return mRegion; } /** * Set the region that the ball is contained in. * @param region The region. */ public void setRegion(Shape2d region) { if (mX < region.getLeft()) { mX = region.getLeft(); bounceOffLeft(); } else if (mX > region.getRight()) { mX = region.getRight(); bounceOffRight(); } if (mY < region.getTop()) { mY = region.getTop(); bounceOffTop(); } else if (mY > region.getBottom()) { mY = region.getBottom(); bounceOffBottom(); } mRegion = region; } public void setNow(long now) { mLastUpdate = now; } public boolean isCircleOverlapping(Ball otherBall) { final float dy = otherBall.mY - mY; final float dx = otherBall.mX - mX; final float distance = dy * dy + dx * dx; return (distance < ((2 * mRadiusPixels) * (2 *mRadiusPixels))) // avoid jittery collisions && !movingAwayFromEachother(this, otherBall); } private boolean movingAwayFromEachother(Ball ballA, Ball ballB) { double collA = Math.atan2(ballB.mY - ballA.mY, ballB.mX - ballA.mX); double collB = Math.atan2(ballA.mY - ballB.mY, ballA.mX - ballB.mX); double ax = Math.cos(ballA.mAngle - collA); double bx = Math.cos(ballB.mAngle - collB); return ax + bx < 0; } public void update(long now) { if (now <= mLastUpdate) return; // bounce when at walls if (mX <= mRegion.getLeft() + mRadiusPixels) { // we're at left wall mX = mRegion.getLeft() + mRadiusPixels; bounceOffLeft(); } else if (mY <= mRegion.getTop() + mRadiusPixels) { // at top wall mY = mRegion.getTop() + mRadiusPixels; bounceOffTop(); } else if (mX >= mRegion.getRight() - mRadiusPixels) { // at right wall mX = mRegion.getRight() - mRadiusPixels; bounceOffRight(); } else if (mY >= mRegion.getBottom() - mRadiusPixels) { // at bottom wall mY = mRegion.getBottom() - mRadiusPixels; bounceOffBottom(); } float delta = (now - mLastUpdate) * mPixelsPerSecond; delta = delta / 1000f; mX += (delta * Math.cos(mAngle)); mY += (delta * Math.sin(mAngle)); mLastUpdate = now; } private void bounceOffBottom() { if (mAngle < 0.5*Math.PI) { // going right mAngle = -mAngle; } else { // going left mAngle += (Math.PI - mAngle) * 2; } } private void bounceOffRight() { if (mAngle > 1.5*Math.PI) { // going up mAngle -= (mAngle - 1.5*Math.PI) * 2; } else { // going down mAngle += (.5*Math.PI - mAngle) * 2; } } private void bounceOffTop() { if (mAngle < 1.5 * Math.PI) { // going left mAngle -= (mAngle - Math.PI) * 2; } else { // going right mAngle += (2*Math.PI - mAngle) * 2; mAngle -= 2*Math.PI; } } private void bounceOffLeft() { if (mAngle < Math.PI) { // going down mAngle -= ((mAngle - (Math.PI / 2)) * 2); } else { // going up mAngle += (((1.5 * Math.PI) - mAngle) * 2); } } /** * Given that ball a and b have collided, adjust their angles to reflect their state * after the collision. * * This method works based on the conservation of energy and momentum in an elastic * collision. Because the balls have equal mass and speed, it ends up being that they * simply swap velocities along the axis of the collision, keeping the velocities tangent * to the collision constant. * * @param ballA The first ball in a collision * @param ballB The second ball in a collision */ public static void adjustForCollision(Ball ballA, Ball ballB) { final double collA = Math.atan2(ballB.mY - ballA.mY, ballB.mX - ballA.mX); final double collB = Math.atan2(ballA.mY - ballB.mY, ballA.mX - ballB.mX); final double ax = Math.cos(ballA.mAngle - collA); final double ay = Math.sin(ballA.mAngle - collA); final double bx = Math.cos(ballB.mAngle - collB); final double by = Math.cos(ballB.mAngle - collB); final double diffA = Math.atan2(ay, -bx); final double diffB = Math.atan2(by, -ax); ballA.mAngle = collA + diffA; ballB.mAngle = collB + diffB; } @Override public String toString() { return String.format( "Ball(x=%f, y=%f, angle=%f)", mX, mY, Math.toDegrees(mAngle)); } /** * A more readable way to create balls than using a 5 param * constructor of all numbers. */ public static class Builder { private long mNow = -1; private float mX = -1; private float mY = -1; private double mAngle = -1; private float mRadiusPixels = -1; private float mPixelsPerSecond = 45f; public Ball create() { if (mNow < 0) { throw new IllegalStateException("must set 'now'"); } if (mX < 0) { throw new IllegalStateException("X must be set"); } if (mY < 0) { throw new IllegalStateException("Y must be stet"); } if (mAngle < 0) { throw new IllegalStateException("angle must be set"); } if (mAngle > 2 * Math.PI) { throw new IllegalStateException("angle must be less that 2Pi"); } if (mRadiusPixels <= 0) { throw new IllegalStateException("radius must be set"); } return new Ball(mNow, mPixelsPerSecond, mX, mY, mAngle, mRadiusPixels); } public Builder setNow(long now) { mNow = now; return this; } public Builder setPixelsPerSecond(float pixelsPerSecond) { mPixelsPerSecond = pixelsPerSecond; return this; } public Builder setX(float x) { mX = x; return this; } public Builder setY(float y) { mY = y; return this; } public Builder setAngle(double angle) { mAngle = angle; return this; } public Builder setRadiusPixels(float pixels) { mRadiusPixels = pixels; return this; } } }
zzhangumd-apps-for-android
DivideAndConquer/src/com/google/android/divideandconquer/Ball.java
Java
asf20
8,884
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.divideandconquer; import android.app.Dialog; import android.content.Context; import android.os.Bundle; import android.view.View; /** * When the game starts, the user is welcomed with a message, and buttons for * starting a new game, or getting instructions about the game. */ public class WelcomeDialog extends Dialog implements View.OnClickListener { private final NewGameCallback mCallback; private View mNewGame; public WelcomeDialog(Context context, NewGameCallback callback) { super(context); mCallback = callback; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setTitle(R.string.app_name); setContentView(R.layout.welcome_dialog); mNewGame = findViewById(R.id.newGame); mNewGame.setOnClickListener(this); } /** {@inheritDoc} */ public void onClick(View v) { if (v == mNewGame) { mCallback.onNewGame(); dismiss(); } } }
zzhangumd-apps-for-android
DivideAndConquer/src/com/google/android/divideandconquer/WelcomeDialog.java
Java
asf20
1,656
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.radar; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.Paint.Align; import android.graphics.Paint.Style; import android.graphics.drawable.BitmapDrawable; import android.hardware.SensorListener; import android.location.Location; import android.location.LocationListener; import android.location.LocationManager; import android.location.LocationProvider; import android.os.Bundle; import android.os.SystemClock; import android.util.AttributeSet; import android.view.View; import android.widget.TextView; public class RadarView extends View implements SensorListener, LocationListener { private static final long RETAIN_GPS_MILLIS = 10000L; private Paint mGridPaint; private Paint mErasePaint; private float mOrientation; private double mTargetLat; private double mTargetLon; private double mMyLocationLat; private double mMyLocationLon; private int mLastScale = -1; private String[] mDistanceScale = new String[4]; private static float KM_PER_METERS = 0.001f; private static float METERS_PER_KM = 1000f; /** * These are the list of choices for the radius of the outer circle on the * screen when using metric units. All items are in kilometers. This array is * used to choose the scale of the radar display. */ private static double mMetricScaleChoices[] = { 100 * KM_PER_METERS, 200 * KM_PER_METERS, 400 * KM_PER_METERS, 1, 2, 4, 8, 20, 40, 100, 200, 400, 1000, 2000, 4000, 10000, 20000, 40000, 80000 }; /** * Once the scale is chosen, this array is used to convert the number of * kilometers on the screen to an integer. (Note that for short distances we * use meters, so we multiply the distance by {@link #METERS_PER_KM}. (This * array is for metric measurements.) */ private static float mMetricDisplayUnitsPerKm[] = { METERS_PER_KM, METERS_PER_KM, METERS_PER_KM, METERS_PER_KM, METERS_PER_KM, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f }; /** * This array holds the formatting string used to display the distance to * the target. (This array is for metric measurements.) */ private static String mMetricDisplayFormats[] = { "%.0fm", "%.0fm", "%.0fm", "%.0fm", "%.0fm", "%.1fkm", "%.1fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm" }; /** * This array holds the formatting string used to display the distance on * each ring of the radar screen. (This array is for metric measurements.) */ private static String mMetricScaleFormats[] = { "%.0fm", "%.0fm", "%.0fm", "%.0fm", "%.0fm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm", "%.0fkm" }; private static float KM_PER_YARDS = 0.0009144f; private static float KM_PER_MILES = 1.609344f; private static float YARDS_PER_KM = 1093.6133f; private static float MILES_PER_KM = 0.621371192f; /** * These are the list of choices for the radius of the outer circle on the * screen when using standard units. All items are in kilometers. This array is * used to choose the scale of the radar display. */ private static double mEnglishScaleChoices[] = { 100 * KM_PER_YARDS, 200 * KM_PER_YARDS, 400 * KM_PER_YARDS, 1000 * KM_PER_YARDS, 1 * KM_PER_MILES, 2 * KM_PER_MILES, 4 * KM_PER_MILES, 8 * KM_PER_MILES, 20 * KM_PER_MILES, 40 * KM_PER_MILES, 100 * KM_PER_MILES, 200 * KM_PER_MILES, 400 * KM_PER_MILES, 1000 * KM_PER_MILES, 2000 * KM_PER_MILES, 4000 * KM_PER_MILES, 10000 * KM_PER_MILES, 20000 * KM_PER_MILES, 40000 * KM_PER_MILES, 80000 * KM_PER_MILES }; /** * Once the scale is chosen, this array is used to convert the number of * kilometers on the screen to an integer. (Note that for short distances we * use meters, so we multiply the distance by {@link #YARDS_PER_KM}. (This * array is for standard measurements.) */ private static float mEnglishDisplayUnitsPerKm[] = { YARDS_PER_KM, YARDS_PER_KM, YARDS_PER_KM, YARDS_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM, MILES_PER_KM }; /** * This array holds the formatting string used to display the distance to * the target. (This array is for standard measurements.) */ private static String mEnglishDisplayFormats[] = { "%.0fyd", "%.0fyd", "%.0fyd", "%.0fyd", "%.1fmi", "%.1fmi", "%.1fmi", "%.1fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi" }; /** * This array holds the formatting string used to display the distance on * each ring of the radar screen. (This array is for standard measurements.) */ private static String mEnglishScaleFormats[] = { "%.0fyd", "%.0fyd", "%.0fyd", "%.0fyd", "%.2fmi", "%.1fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi", "%.0fmi" }; /** * True when we have know our own location */ private boolean mHaveLocation = false; /** * The view that will display the distance text */ private TextView mDistanceView; /** * Distance to target, in KM */ private double mDistance; /** * Bearing to target, in degrees */ private double mBearing; /** * Ratio of the distance to the target to the radius of the outermost ring on the radar screen */ private float mDistanceRatio; /** * Utility rect for calculating the ring labels */ private Rect mTextBounds = new Rect(); /** * The bitmap used to draw the target */ private Bitmap mBlip; /** * Used to draw the animated ring that sweeps out from the center */ private Paint mSweepPaint0; /** * Used to draw the animated ring that sweeps out from the center */ private Paint mSweepPaint1; /** * Used to draw the animated ring that sweeps out from the center */ private Paint mSweepPaint2; /** * Time in millis when the most recent sweep began */ private long mSweepTime; /** * True if the sweep has not yet intersected the blip */ private boolean mSweepBefore; /** * Time in millis when the sweep last crossed the blip */ private long mBlipTime; /** * True if the display should use metric units; false if the display should use standard * units */ private boolean mUseMetric; /** * Time in millis for the last time GPS reported a location */ private long mLastGpsFixTime = 0L; /** * The last location reported by the network provider. Use this if we can't get a location from * GPS */ private Location mNetworkLocation; /** * True if GPS is reporting a location */ private boolean mGpsAvailable; /** * True if the network provider is reporting a location */ private boolean mNetworkAvailable; public RadarView(Context context) { this(context, null); } public RadarView(Context context, AttributeSet attrs) { this(context, attrs, 0); } public RadarView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); // Paint used for the rings and ring text mGridPaint = new Paint(); mGridPaint.setColor(0xFF00FF00); mGridPaint.setAntiAlias(true); mGridPaint.setStyle(Style.STROKE); mGridPaint.setStrokeWidth(1.0f); mGridPaint.setTextSize(10.0f); mGridPaint.setTextAlign(Align.CENTER); // Paint used to erase the rectangle behing the ring text mErasePaint = new Paint(); mErasePaint.setColor(0xFF191919); mErasePaint.setStyle(Style.FILL); // Outer ring of the sweep mSweepPaint0 = new Paint(); mSweepPaint0.setColor(0xFF33FF33); mSweepPaint0.setAntiAlias(true); mSweepPaint0.setStyle(Style.STROKE); mSweepPaint0.setStrokeWidth(2f); // Middle ring of the sweep mSweepPaint1 = new Paint(); mSweepPaint1.setColor(0x7733FF33); mSweepPaint1.setAntiAlias(true); mSweepPaint1.setStyle(Style.STROKE); mSweepPaint1.setStrokeWidth(2f); // Inner ring of the sweep mSweepPaint2 = new Paint(); mSweepPaint2.setColor(0x3333FF33); mSweepPaint2.setAntiAlias(true); mSweepPaint2.setStyle(Style.STROKE); mSweepPaint2.setStrokeWidth(2f); mBlip = ((BitmapDrawable)getResources().getDrawable(R.drawable.blip)).getBitmap(); } /** * Sets the target to track on the radar * @param latE6 Latitude of the target, multiplied by 1,000,000 * @param lonE6 Longitude of the target, multiplied by 1,000,000 */ public void setTarget(int latE6, int lonE6) { mTargetLat = latE6 / (double) GeoUtils.MILLION; mTargetLon = lonE6 / (double) GeoUtils.MILLION; } /** * Sets the view that we will use to report distance * * @param t The text view used to report distance */ public void setDistanceView(TextView t) { mDistanceView = t; } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); int center = getWidth() / 2; int radius = center - 8; // Draw the rings final Paint gridPaint = mGridPaint; canvas.drawCircle(center, center, radius, gridPaint); canvas.drawCircle(center, center, radius * 3 / 4, gridPaint); canvas.drawCircle(center, center, radius >> 1, gridPaint); canvas.drawCircle(center, center, radius >> 2, gridPaint); int blipRadius = (int) (mDistanceRatio * radius); final long now = SystemClock.uptimeMillis(); if (mSweepTime > 0 && mHaveLocation) { // Draw the sweep. Radius is determined by how long ago it started long sweepDifference = now - mSweepTime; if (sweepDifference < 512L) { int sweepRadius = (int) (((radius + 6) * sweepDifference) >> 9); canvas.drawCircle(center, center, sweepRadius, mSweepPaint0); canvas.drawCircle(center, center, sweepRadius - 2, mSweepPaint1); canvas.drawCircle(center, center, sweepRadius - 4, mSweepPaint2); // Note when the sweep has passed the blip boolean before = sweepRadius < blipRadius; if (!before && mSweepBefore) { mSweepBefore = false; mBlipTime = now; } } else { mSweepTime = now + 1000; mSweepBefore = true; } postInvalidate(); } // Draw horizontal and vertical lines canvas.drawLine(center, center - (radius >> 2) + 6, center, center - radius - 6, gridPaint); canvas.drawLine(center, center + (radius >> 2) - 6 , center, center + radius + 6, gridPaint); canvas.drawLine(center - (radius >> 2) + 6, center, center - radius - 6, center, gridPaint); canvas.drawLine(center + (radius >> 2) - 6, center, center + radius + 6, center, gridPaint); // Draw X in the center of the screen canvas.drawLine(center - 4, center - 4, center + 4, center + 4, gridPaint); canvas.drawLine(center - 4, center + 4, center + 4, center - 4, gridPaint); if (mHaveLocation) { double bearingToTarget = mBearing - mOrientation; double drawingAngle = Math.toRadians(bearingToTarget) - (Math.PI / 2); float cos = (float) Math.cos(drawingAngle); float sin = (float) Math.sin(drawingAngle); // Draw the text for the rings final String[] distanceScale = mDistanceScale; addText(canvas, distanceScale[0], center, center + (radius >> 2)); addText(canvas, distanceScale[1], center, center + (radius >> 1)); addText(canvas, distanceScale[2], center, center + radius * 3 / 4); addText(canvas, distanceScale[3], center, center + radius); // Draw the blip. Alpha is based on how long ago the sweep crossed the blip long blipDifference = now - mBlipTime; gridPaint.setAlpha(255 - (int)((128 * blipDifference) >> 10)); canvas.drawBitmap(mBlip, center + (cos * blipRadius) - 8 , center + (sin * blipRadius) - 8, gridPaint); gridPaint.setAlpha(255); } } private void addText(Canvas canvas, String str, int x, int y) { mGridPaint.getTextBounds(str, 0, str.length(), mTextBounds); mTextBounds.offset(x - (mTextBounds.width() >> 1), y); mTextBounds.inset(-2, -2); canvas.drawRect(mTextBounds, mErasePaint); canvas.drawText(str, x, y, mGridPaint); } public void onAccuracyChanged(int sensor, int accuracy) { } /** * Called when we get a new value from the compass * * @see android.hardware.SensorListener#onSensorChanged(int, float[]) */ public void onSensorChanged(int sensor, float[] values) { mOrientation = values[0]; postInvalidate(); } /** * Called when a location provider has a new location to report * * @see android.location.LocationListener#onLocationChanged(android.location.Location) */ public void onLocationChanged(Location location) { if (!mHaveLocation) { mHaveLocation = true; } final long now = SystemClock.uptimeMillis(); boolean useLocation = false; final String provider = location.getProvider(); if (LocationManager.GPS_PROVIDER.equals(provider)) { // Use GPS if available mLastGpsFixTime = SystemClock.uptimeMillis(); useLocation = true; } else if (LocationManager.NETWORK_PROVIDER.equals(provider)) { // Use network provider if GPS is getting stale useLocation = now - mLastGpsFixTime > RETAIN_GPS_MILLIS; if (mNetworkLocation == null) { mNetworkLocation = new Location(location); } else { mNetworkLocation.set(location); } mLastGpsFixTime = 0L; } if (useLocation) { mMyLocationLat = location.getLatitude(); mMyLocationLon = location.getLongitude(); mDistance = GeoUtils.distanceKm(mMyLocationLat, mMyLocationLon, mTargetLat, mTargetLon); mBearing = GeoUtils.bearing(mMyLocationLat, mMyLocationLon, mTargetLat, mTargetLon); updateDistance(mDistance); } } public void onProviderDisabled(String provider) { } public void onProviderEnabled(String provider) { } /** * Called when a location provider has changed its availability. * * @see android.location.LocationListener#onStatusChanged(java.lang.String, int, android.os.Bundle) */ public void onStatusChanged(String provider, int status, Bundle extras) { if (LocationManager.GPS_PROVIDER.equals(provider)) { switch (status) { case LocationProvider.AVAILABLE: mGpsAvailable = true; break; case LocationProvider.OUT_OF_SERVICE: case LocationProvider.TEMPORARILY_UNAVAILABLE: mGpsAvailable = false; if (mNetworkLocation != null && mNetworkAvailable) { // Fallback to network location mLastGpsFixTime = 0L; onLocationChanged(mNetworkLocation); } else { handleUnknownLocation(); } break; } } else if (LocationManager.NETWORK_PROVIDER.equals(provider)) { switch (status) { case LocationProvider.AVAILABLE: mNetworkAvailable = true; break; case LocationProvider.OUT_OF_SERVICE: case LocationProvider.TEMPORARILY_UNAVAILABLE: mNetworkAvailable = false; if (!mGpsAvailable) { handleUnknownLocation(); } break; } } } /** * Called when we no longer have a valid lcoation. */ private void handleUnknownLocation() { mHaveLocation = false; mDistanceView.setText(R.string.scanning); } /** * Update state to reflect whether we are using metric or standard units. * * @param useMetric True if the display should use metric units */ public void setUseMetric(boolean useMetric) { mUseMetric = useMetric; mLastScale = -1; if (mHaveLocation) { updateDistance(mDistance); } invalidate(); } /** * Update our state to reflect a new distance to the target. This may require * choosing a new scale for the radar rings. * * @param distanceKm The new distance to the target */ private void updateDistance(double distanceKm) { final double[] scaleChoices; final float[] displayUnitsPerKm; final String[] displayFormats; final String[] scaleFormats; String distanceStr = null; if (mUseMetric) { scaleChoices = mMetricScaleChoices; displayUnitsPerKm = mMetricDisplayUnitsPerKm; displayFormats = mMetricDisplayFormats; scaleFormats = mMetricScaleFormats; } else { scaleChoices = mEnglishScaleChoices; displayUnitsPerKm = mEnglishDisplayUnitsPerKm; displayFormats = mEnglishDisplayFormats; scaleFormats = mEnglishScaleFormats; } int count = scaleChoices.length; for (int i = 0; i < count; i++) { if (distanceKm < scaleChoices[i] || i == (count - 1)) { String format = displayFormats[i]; double distanceDisplay = distanceKm * displayUnitsPerKm[i]; if (mLastScale != i) { mLastScale = i; String scaleFormat = scaleFormats[i]; float scaleDistance = (float) (scaleChoices[i] * displayUnitsPerKm[i]); mDistanceScale[0] = String.format(scaleFormat, (scaleDistance / 4)); mDistanceScale[1] = String.format(scaleFormat, (scaleDistance / 2)); mDistanceScale[2] = String.format(scaleFormat, (scaleDistance * 3 / 4)); mDistanceScale[3] = String.format(scaleFormat, scaleDistance); } mDistanceRatio = (float) (mDistance / scaleChoices[mLastScale]); distanceStr = String.format(format, distanceDisplay); break; } } mDistanceView.setText(distanceStr); } /** * Turn on the sweep animation starting with the next draw */ public void startSweep() { mSweepTime = SystemClock.uptimeMillis(); mSweepBefore = true; } /** * Turn off the sweep animation */ public void stopSweep() { mSweepTime = 0L; } }
zzhangumd-apps-for-android
Radar/src/com/google/android/radar/RadarView.java
Java
asf20
21,993
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.radar; import com.google.android.maps.GeoPoint; /** * Library for some use useful latitude/longitude math */ public class GeoUtils { private static int EARTH_RADIUS_KM = 6371; public static int MILLION = 1000000; /** * Computes the distance in kilometers between two points on Earth. * * @param lat1 Latitude of the first point * @param lon1 Longitude of the first point * @param lat2 Latitude of the second point * @param lon2 Longitude of the second point * @return Distance between the two points in kilometers. */ public static double distanceKm(double lat1, double lon1, double lat2, double lon2) { double lat1Rad = Math.toRadians(lat1); double lat2Rad = Math.toRadians(lat2); double deltaLonRad = Math.toRadians(lon2 - lon1); return Math.acos(Math.sin(lat1Rad) * Math.sin(lat2Rad) + Math.cos(lat1Rad) * Math.cos(lat2Rad) * Math.cos(deltaLonRad)) * EARTH_RADIUS_KM; } /** * Computes the distance in kilometers between two points on Earth. * * @param p1 First point * @param p2 Second point * @return Distance between the two points in kilometers. */ public static double distanceKm(GeoPoint p1, GeoPoint p2) { double lat1 = p1.getLatitudeE6() / (double)MILLION; double lon1 = p1.getLongitudeE6() / (double)MILLION; double lat2 = p2.getLatitudeE6() / (double)MILLION; double lon2 = p2.getLongitudeE6() / (double)MILLION; return distanceKm(lat1, lon1, lat2, lon2); } /** * Computes the bearing in degrees between two points on Earth. * * @param p1 First point * @param p2 Second point * @return Bearing between the two points in degrees. A value of 0 means due * north. */ public static double bearing(GeoPoint p1, GeoPoint p2) { double lat1 = p1.getLatitudeE6() / (double) MILLION; double lon1 = p1.getLongitudeE6() / (double) MILLION; double lat2 = p2.getLatitudeE6() / (double) MILLION; double lon2 = p2.getLongitudeE6() / (double) MILLION; return bearing(lat1, lon1, lat2, lon2); } /** * Computes the bearing in degrees between two points on Earth. * * @param lat1 Latitude of the first point * @param lon1 Longitude of the first point * @param lat2 Latitude of the second point * @param lon2 Longitude of the second point * @return Bearing between the two points in degrees. A value of 0 means due * north. */ public static double bearing(double lat1, double lon1, double lat2, double lon2) { double lat1Rad = Math.toRadians(lat1); double lat2Rad = Math.toRadians(lat2); double deltaLonRad = Math.toRadians(lon2 - lon1); double y = Math.sin(deltaLonRad) * Math.cos(lat2Rad); double x = Math.cos(lat1Rad) * Math.sin(lat2Rad) - Math.sin(lat1Rad) * Math.cos(lat2Rad) * Math.cos(deltaLonRad); return radToBearing(Math.atan2(y, x)); } /** * Converts an angle in radians to degrees */ public static double radToBearing(double rad) { return (Math.toDegrees(rad) + 360) % 360; } }
zzhangumd-apps-for-android
Radar/src/com/google/android/radar/GeoUtils.java
Java
asf20
3,910
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.radar; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.hardware.SensorManager; import android.location.LocationManager; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.Window; import android.widget.TextView; /** * Simple Activity wrapper that hosts a {@link RadarView} * */ public class RadarActivity extends Activity { private static final int LOCATION_UPDATE_INTERVAL_MILLIS = 1000; private static final int MENU_STANDARD = Menu.FIRST + 1; private static final int MENU_METRIC = Menu.FIRST + 2; private static final String RADAR = "radar"; private static final String PREF_METRIC = "metric"; private SensorManager mSensorManager; private RadarView mRadar; private LocationManager mLocationManager; private SharedPreferences mPrefs; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_NO_TITLE); setContentView(R.layout.radar); mRadar = (RadarView) findViewById(R.id.radar); mSensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE); mLocationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); // Metric or standard units? mPrefs = getSharedPreferences(RADAR, MODE_PRIVATE); boolean useMetric = mPrefs.getBoolean(PREF_METRIC, false); mRadar.setUseMetric(useMetric); // Read the target from our intent Intent i = getIntent(); int latE6 = (int)(i.getFloatExtra("latitude", 0) * GeoUtils.MILLION); int lonE6 = (int)(i.getFloatExtra("longitude", 0) * GeoUtils.MILLION); mRadar.setTarget(latE6, lonE6); mRadar.setDistanceView((TextView) findViewById(R.id.distance)); } @Override protected void onResume() { super.onResume(); mSensorManager.registerListener(mRadar, SensorManager.SENSOR_ORIENTATION, SensorManager.SENSOR_DELAY_GAME); // Start animating the radar screen mRadar.startSweep(); // Register for location updates mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, LOCATION_UPDATE_INTERVAL_MILLIS, 1, mRadar); mLocationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, LOCATION_UPDATE_INTERVAL_MILLIS, 1, mRadar); } @Override protected void onPause() { mSensorManager.unregisterListener(mRadar); mLocationManager.removeUpdates(mRadar); // Stop animating the radar screen mRadar.stopSweep(); super.onStop(); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); menu.add(0, MENU_STANDARD, 0, R.string.menu_standard) .setIcon(R.drawable.ic_menu_standard) .setAlphabeticShortcut('A'); menu.add(0, MENU_METRIC, 0, R.string.menu_metric) .setIcon(R.drawable.ic_menu_metric) .setAlphabeticShortcut('C'); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case MENU_STANDARD: { setUseMetric(false); return true; } case MENU_METRIC: { setUseMetric(true); return true; } } return super.onOptionsItemSelected(item); } private void setUseMetric(boolean useMetric) { SharedPreferences.Editor e = mPrefs.edit(); e.putBoolean(PREF_METRIC, useMetric); e.commit(); mRadar.setUseMetric(useMetric); } }
zzhangumd-apps-for-android
Radar/src/com/google/android/radar/RadarActivity.java
Java
asf20
4,510
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.google.android.wikinotes; import java.util.regex.Pattern; import android.app.Activity; import android.content.ContentUris; import android.content.ContentValues; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.text.util.Linkify; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.widget.TextView; import com.google.android.wikinotes.db.WikiNote; /** * The WikiNotes activity is the default handler for displaying individual * wiki notes. It takes the wiki note name to view from the intent data URL * and defaults to a page name defined in R.strings.start_page if no page name * is given. The lifecycle events store the current content URL being viewed. * It uses Linkify to turn wiki words in the body of the wiki note into * clickable links which in turn call back into the WikiNotes activity from * the Android operating system. If a URL is passed to the WikiNotes activity * for a page that does not yet exist, the WikiNoteEditor activity is * automatically started to place the user into edit mode for a new wiki note * with the given name. */ public class WikiNotes extends Activity { /** * The view URL which is prepended to a matching wikiword in order to fire * the WikiNotes activity again through Linkify */ private static final String KEY_URL = "wikiNotesURL"; public static final int EDIT_ID = Menu.FIRST; public static final int HOME_ID = Menu.FIRST + 1; public static final int LIST_ID = Menu.FIRST + 3; public static final int DELETE_ID = Menu.FIRST + 4; public static final int ABOUT_ID = Menu.FIRST + 5; public static final int EXPORT_ID = Menu.FIRST + 6; public static final int IMPORT_ID = Menu.FIRST + 7; public static final int EMAIL_ID = Menu.FIRST + 8; private TextView mNoteView; Cursor mCursor; private Uri mURI; String mNoteName; private static final Pattern WIKI_WORD_MATCHER; private WikiActivityHelper mHelper; static { // Compile the regular expression pattern that will be used to // match WikiWords in the body of the note WIKI_WORD_MATCHER = Pattern .compile("\\b[A-Z]+[a-z0-9]+[A-Z][A-Za-z0-9]+\\b"); } @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); mNoteView = (TextView) findViewById(R.id.noteview); // get the URL we are being asked to view Uri uri = getIntent().getData(); if ((uri == null) && (icicle != null)) { // perhaps we have the URI in the icicle instead? uri = Uri.parse(icicle.getString(KEY_URL)); } // do we have a correct URI including the note name? if ((uri == null) || (uri.getPathSegments().size() < 2)) { // if not, build one using the default StartPage name uri = Uri.withAppendedPath(WikiNote.Notes.ALL_NOTES_URI, getResources() .getString(R.string.start_page)); } // can we find a matching note? Cursor cursor = managedQuery(uri, WikiNote.WIKI_NOTES_PROJECTION, null, null, null); boolean newNote = false; if ((cursor == null) || (cursor.getCount() == 0)) { // no matching wikinote, so create it uri = getContentResolver().insert(uri, null); if (uri == null) { Log.e("WikiNotes", "Failed to insert new wikinote into " + getIntent().getData()); finish(); return; } // make sure that the new note was created successfully, and // select // it cursor = managedQuery(uri, WikiNote.WIKI_NOTES_PROJECTION, null, null, null); if ((cursor == null) || (cursor.getCount() == 0)) { Log.e("WikiNotes", "Failed to open new wikinote: " + getIntent().getData()); finish(); return; } newNote = true; } mURI = uri; mCursor = cursor; cursor.moveToFirst(); mHelper = new WikiActivityHelper(this); // get the note name String noteName = cursor.getString(cursor .getColumnIndexOrThrow(WikiNote.Notes.TITLE)); mNoteName = noteName; // set the title to the name of the page setTitle(getResources().getString(R.string.wiki_title, noteName)); // If a new note was created, jump straight into editing it if (newNote) { mHelper.editNote(noteName, null); } else if (!getSharedPreferences(Eula.PREFERENCES_EULA, Activity.MODE_PRIVATE) .getBoolean(Eula.PREFERENCE_EULA_ACCEPTED, false)) { Eula.showEula(this); } // Set the menu shortcut keys to be default keys for the activity as // well setDefaultKeyMode(DEFAULT_KEYS_SHORTCUT); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); // Put the URL currently being viewed into the icicle outState.putString(KEY_URL, mURI.toString()); } @Override protected void onResume() { super.onResume(); Cursor c = mCursor; if (c.getCount() < 1) { // if the note can't be found, don't try to load it -- bail out // (probably means it got deleted while we were frozen; // thx to joe.bowbeer for the find) finish(); return; } c.requery(); c.moveToFirst(); showWikiNote(c .getString(c.getColumnIndexOrThrow(WikiNote.Notes.BODY))); } /** * Show the wiki note in the text edit view with both the default Linkify * options and the regular expression for WikiWords matched and turned * into live links. * * @param body * The plain text to linkify and put into the edit view. */ private void showWikiNote(CharSequence body) { TextView noteView = mNoteView; noteView.setText(body); // Add default links first - phone numbers, URLs, etc. Linkify.addLinks(noteView, Linkify.ALL); // Now add in the custom linkify match for WikiWords Linkify.addLinks(noteView, WIKI_WORD_MATCHER, WikiNote.Notes.ALL_NOTES_URI.toString() + "/"); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); menu.add(0, EDIT_ID, 0, R.string.menu_edit).setShortcut('1', 'e') .setIcon(R.drawable.icon_delete); menu.add(0, HOME_ID, 0, R.string.menu_start).setShortcut('4', 'h') .setIcon(R.drawable.icon_start); menu.add(0, LIST_ID, 0, R.string.menu_recent).setShortcut('3', 'r') .setIcon(R.drawable.icon_recent); menu.add(0, DELETE_ID, 0, R.string.menu_delete).setShortcut('2', 'd') .setIcon(R.drawable.icon_delete); menu.add(0, ABOUT_ID, 0, R.string.menu_about).setShortcut('5', 'a') .setIcon(android.R.drawable.ic_dialog_info); menu.add(0, EXPORT_ID, 0, R.string.menu_export).setShortcut('7', 'x') .setIcon(android.R.drawable.ic_dialog_info); menu.add(0, IMPORT_ID, 0, R.string.menu_import).setShortcut('8', 'm') .setIcon(android.R.drawable.ic_dialog_info); menu.add(0, EMAIL_ID, 0, R.string.menu_email).setShortcut('6', 'm') .setIcon(android.R.drawable.ic_dialog_info); return true; } @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { switch (item.getItemId()) { case EDIT_ID: mHelper.editNote(mNoteName, mCursor); return true; case HOME_ID: mHelper.goHome(); return true; case DELETE_ID: mHelper.deleteNote(mCursor); return true; case LIST_ID: mHelper.listNotes(); return true; case WikiNotes.ABOUT_ID: Eula.showEula(this); return true; case WikiNotes.EXPORT_ID: mHelper.exportNotes(); return true; case WikiNotes.IMPORT_ID: mHelper.importNotes(); return true; case WikiNotes.EMAIL_ID: mHelper.mailNote(mCursor); return true; default: return false; } } /** * If the note was edited and not canceled, commit the update to the * database and then refresh the current view of the linkified note. */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent result) { super.onActivityResult(requestCode, resultCode, result); if ((requestCode == WikiActivityHelper.ACTIVITY_EDIT) && (resultCode == RESULT_OK)) { // edit was confirmed - store the update Cursor c = mCursor; c.requery(); c.moveToFirst(); Uri noteUri = ContentUris .withAppendedId(WikiNote.Notes.ALL_NOTES_URI, c.getInt(0)); ContentValues values = new ContentValues(); values.put(WikiNote.Notes.BODY, result .getStringExtra(WikiNoteEditor.ACTIVITY_RESULT)); values.put(WikiNote.Notes.MODIFIED_DATE, System .currentTimeMillis()); getContentResolver().update(noteUri, values, "_id = " + c.getInt(0), null); showWikiNote(c.getString(c .getColumnIndexOrThrow(WikiNote.Notes.BODY))); } } }
zzhangumd-apps-for-android
WikiNotes/src/com/google/android/wikinotes/WikiNotes.java
Java
asf20
9,256
/* * Copyright (C) 2008 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.wikinotes; import android.app.Activity; import android.app.AlertDialog; import android.content.DialogInterface; import android.content.SharedPreferences; /** * Displays an EULA ("End User License Agreement") that the user has to accept * before using the application. Your application should call * {@link Eula#showEula(android.app.Activity)} in the onCreate() method of the * first activity. If the user accepts the EULA, it will never be shown again. * If the user refuses, {@link android.app.Activity#finish()} is invoked on your * activity. */ class Eula { public static final String PREFERENCE_EULA_ACCEPTED = "eula.accepted"; public static final String PREFERENCES_EULA = "eula"; /** * Displays the EULA if necessary. This method should be called from the * onCreate() method of your main Activity. * * @param activity * The Activity to finish if the user rejects the EULA. */ static void showEula(final Activity activity) { final SharedPreferences preferences = activity.getSharedPreferences( PREFERENCES_EULA, Activity.MODE_PRIVATE); final AlertDialog.Builder builder = new AlertDialog.Builder(activity); builder.setTitle(R.string.about_title); builder.setCancelable(false); builder.setPositiveButton(R.string.about_dismiss_button, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { preferences.edit().putBoolean(PREFERENCE_EULA_ACCEPTED, true).commit(); } }); builder.setMessage(R.string.about_body); builder.create().show(); } }
zzhangumd-apps-for-android
WikiNotes/src/com/google/android/wikinotes/Eula.java
Java
asf20
2,223
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.google.android.wikinotes; import android.app.ListActivity; import android.app.SearchManager; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.ListAdapter; import android.widget.ListView; import android.widget.SimpleCursorAdapter; import com.google.android.wikinotes.db.WikiNote; /** * Activity to list wikinotes. By default, the notes are listed in the order * of most recently modified to least recently modified. This activity can * handle requests to either show all notes, or the results of a title or body * search performed by the content provider. */ public class WikiNotesList extends ListActivity { /** * A key to store/retrieve the search criteria in a bundle */ public static final String SEARCH_CRITERIA_KEY = "SearchCriteria"; /** * The projection to use (columns to retrieve) for a query of wikinotes */ public static final String[] PROJECTION = { WikiNote.Notes._ID, WikiNote.Notes.TITLE, WikiNote.Notes.MODIFIED_DATE }; private Cursor mCursor; private WikiActivityHelper mHelper; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent = getIntent(); Uri uri = null; String query = null; // locate a query string; prefer a fresh search Intent over saved // state if (Intent.ACTION_SEARCH.equals(intent.getAction())) { query = intent.getStringExtra(SearchManager.QUERY); } else if (savedInstanceState != null) { query = savedInstanceState.getString(SearchManager.QUERY); } if (query != null && query.length() > 0) { uri = Uri.withAppendedPath(WikiNote.Notes.SEARCH_URI, Uri .encode(query)); } if (uri == null) { // somehow we got called w/o a query so fall back to a reasonable // default (all notes) uri = WikiNote.Notes.ALL_NOTES_URI; } // Do the query Cursor c = managedQuery(uri, PROJECTION, null, null, WikiNote.Notes.DEFAULT_SORT_ORDER); mCursor = c; mHelper = new WikiActivityHelper(this); // Bind the results of the search into the list ListAdapter adapter = new SimpleCursorAdapter( this, android.R.layout.simple_list_item_1, mCursor, new String[] { WikiNote.Notes.TITLE }, new int[] { android.R.id.text1 }); setListAdapter(adapter); // use the menu shortcut keys as default key bindings for the entire // activity setDefaultKeyMode(DEFAULT_KEYS_SHORTCUT); } /** * Override the onListItemClick to open the wiki note to view when it is * selected from the list. */ @Override protected void onListItemClick(ListView list, View view, int position, long id) { Cursor c = mCursor; c.moveToPosition(position); String title = c.getString(c .getColumnIndexOrThrow(WikiNote.Notes.TITLE)); // Create the URI of the note we want to view based on the title Uri uri = Uri.withAppendedPath(WikiNote.Notes.ALL_NOTES_URI, title); Intent i = new Intent(Intent.ACTION_VIEW, uri); startActivity(i); } @Override public boolean onCreateOptionsMenu(Menu menu) { super.onCreateOptionsMenu(menu); menu.add(0, WikiNotes.HOME_ID, 0, R.string.menu_start) .setShortcut('4', 'h').setIcon(R.drawable.icon_start); menu.add(0, WikiNotes.LIST_ID, 0, R.string.menu_recent) .setShortcut('3', 'r').setIcon(R.drawable.icon_recent); menu.add(0, WikiNotes.ABOUT_ID, 0, R.string.menu_about) .setShortcut('5', 'a').setIcon(android.R.drawable.ic_dialog_info); menu.add(0, WikiNotes.EXPORT_ID, 0, R.string.menu_export) .setShortcut('6', 'x').setIcon(android.R.drawable.ic_dialog_info); menu.add(0, WikiNotes.IMPORT_ID, 0, R.string.menu_import) .setShortcut('7', 'm').setIcon(android.R.drawable.ic_dialog_info); return true; } @Override public boolean onMenuItemSelected(int featureId, MenuItem item) { switch (item.getItemId()) { case WikiNotes.HOME_ID: mHelper.goHome(); return true; case WikiNotes.LIST_ID: mHelper.listNotes(); return true; case WikiNotes.ABOUT_ID: Eula.showEula(this); return true; case WikiNotes.EXPORT_ID: mHelper.exportNotes(); return true; case WikiNotes.IMPORT_ID: mHelper.importNotes(); return true; default: return false; } } }
zzhangumd-apps-for-android
WikiNotes/src/com/google/android/wikinotes/WikiNotesList.java
Java
asf20
5,062
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.google.android.wikinotes.db; import android.content.ContentProvider; import android.content.ContentValues; import android.content.Context; import android.content.UriMatcher; import android.database.Cursor; import android.database.SQLException; import android.database.sqlite.SQLiteDatabase; import android.database.sqlite.SQLiteOpenHelper; import android.database.sqlite.SQLiteQueryBuilder; import android.net.Uri; import android.text.TextUtils; import android.util.Log; import java.util.HashMap; /** * The Wikinotes Content Provider is the guts of the wikinotes application. It * handles Content URLs to list all wiki notes, retrieve a note by name, or * return a list of matching notes based on text in the body or the title of * the note. It also handles all set up of the database, and reports back MIME * types for the individual notes or lists of notes to help Android route the * data to activities that can display that data (in this case either the * WikiNotes activity itself, or the WikiNotesList activity to list multiple * notes). */ public class WikiNotesProvider extends ContentProvider { private DatabaseHelper dbHelper; private static final String TAG = "WikiNotesProvider"; private static final String DATABASE_NAME = "wikinotes.db"; private static final int DATABASE_VERSION = 2; private static HashMap<String, String> NOTES_LIST_PROJECTION_MAP; private static final int NOTES = 1; private static final int NOTE_NAME = 2; private static final int NOTE_SEARCH = 3; private static final UriMatcher URI_MATCHER; /** * This inner DatabaseHelper class defines methods to create and upgrade * the database from previous versions. */ private static class DatabaseHelper extends SQLiteOpenHelper { public DatabaseHelper(Context context) { super(context, DATABASE_NAME, null, DATABASE_VERSION); } @Override public void onCreate(SQLiteDatabase db) { db.execSQL("CREATE TABLE wikinotes (_id INTEGER PRIMARY KEY," + "title TEXT COLLATE LOCALIZED NOT NULL," + "body TEXT," + "created INTEGER," + "modified INTEGER" + ");"); } @Override public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { Log.w(TAG, "Upgrading database from version " + oldVersion + " to " + newVersion + ", which will destroy all old data"); db.execSQL("DROP TABLE IF EXISTS wikinotes"); onCreate(db); } } @Override public boolean onCreate() { // On the creation of the content provider, open the database, // the Database helper will create a new version of the database // if needed through the functionality in SQLiteOpenHelper dbHelper = new DatabaseHelper(getContext()); return true; } /** * Figure out which query to run based on the URL requested and any other * parameters provided. */ @Override public Cursor query(Uri uri, String[] projection, String selection, String[] selectionArgs, String sort) { // Query the database using the arguments provided SQLiteQueryBuilder qb = new SQLiteQueryBuilder(); String[] whereArgs = null; // What type of query are we going to use - the URL_MATCHER // defined at the bottom of this class is used to pattern-match // the URL and select the right query from the switch statement switch (URI_MATCHER.match(uri)) { case NOTES: // this match lists all notes qb.setTables("wikinotes"); qb.setProjectionMap(NOTES_LIST_PROJECTION_MAP); break; case NOTE_SEARCH: // this match searches for a text match in the body of notes qb.setTables("wikinotes"); qb.setProjectionMap(NOTES_LIST_PROJECTION_MAP); qb.appendWhere("body like ? or title like ?"); whereArgs = new String[2]; whereArgs[0] = whereArgs[1] = "%" + uri.getLastPathSegment() + "%"; break; case NOTE_NAME: // this match searches for an exact match for a specific note name qb.setTables("wikinotes"); qb.appendWhere("title=?"); whereArgs = new String[] { uri.getLastPathSegment() }; break; default: // anything else is considered and illegal request throw new IllegalArgumentException("Unknown URL " + uri); } // If no sort order is specified use the default String orderBy; if (TextUtils.isEmpty(sort)) { orderBy = WikiNote.Notes.DEFAULT_SORT_ORDER; } else { orderBy = sort; } // Run the query and return the results as a Cursor SQLiteDatabase mDb = dbHelper.getReadableDatabase(); Cursor c = qb.query(mDb, projection, null, whereArgs, null, null, orderBy); c.setNotificationUri(getContext().getContentResolver(), uri); return c; } /** * For a given URL, return a MIME type for the data that will be returned * from that URL. This will help Android decide what to do with the data * it gets back. */ @Override public String getType(Uri uri) { switch (URI_MATCHER.match(uri)) { case NOTES: case NOTE_SEARCH: // for a notes list, or search results, return a mimetype // indicating // a directory of wikinotes return "vnd.android.cursor.dir/vnd.google.wikinote"; case NOTE_NAME: // for a specific note name, return a mimetype indicating a single // item representing a wikinote return "vnd.android.cursor.item/vnd.google.wikinote"; default: // any other kind of URL is illegal throw new IllegalArgumentException("Unknown URL " + uri); } } /** * For a URL and a list of initial values, insert a row using those values * into the database. */ @Override public Uri insert(Uri uri, ContentValues initialValues) { long rowID; ContentValues values; if (initialValues != null) { values = new ContentValues(initialValues); } else { values = new ContentValues(); } // We can only insert a note, no other URLs make sense here if (URI_MATCHER.match(uri) != NOTE_NAME) { throw new IllegalArgumentException("Unknown URL " + uri); } // Update the modified time of the record Long now = Long.valueOf(System.currentTimeMillis()); // Make sure that the fields are all set if (values.containsKey(WikiNote.Notes.CREATED_DATE) == false) { values.put(WikiNote.Notes.CREATED_DATE, now); } if (values.containsKey(WikiNote.Notes.MODIFIED_DATE) == false) { values.put(WikiNote.Notes.MODIFIED_DATE, now); } if (values.containsKey(WikiNote.Notes.TITLE) == false) { values.put(WikiNote.Notes.TITLE, uri.getLastPathSegment()); } if (values.containsKey(WikiNote.Notes.BODY) == false) { values.put(WikiNote.Notes.BODY, ""); } SQLiteDatabase db = dbHelper.getWritableDatabase(); rowID = db.insert("wikinotes", "body", values); if (rowID > 0) { Uri newUri = Uri.withAppendedPath(WikiNote.Notes.ALL_NOTES_URI, uri.getLastPathSegment()); getContext().getContentResolver().notifyChange(newUri, null); return newUri; } throw new SQLException("Failed to insert row into " + uri); } /** * Delete rows matching the where clause and args for the supplied URL. * The URL can be either the all notes URL (in which case all notes * matching the where clause will be deleted), or the note name, in which * case it will delete the note with the exactly matching title. Any of * the other URLs will be rejected as invalid. For deleting notes by title * we use ReST style arguments from the URI and don't support where clause * and args. */ @Override public int delete(Uri uri, String where, String[] whereArgs) { /* This is kind of dangerous: it deletes all records with a single Intent. It might make sense to make this ContentProvider non-public, since this is kind of over-powerful and the provider isn't generally intended to be public. But for now it's still public. */ if (WikiNote.Notes.ALL_NOTES_URI.equals(uri)) { return dbHelper.getWritableDatabase().delete("wikinotes", null, null); } int count; SQLiteDatabase db = dbHelper.getWritableDatabase(); switch (URI_MATCHER.match(uri)) { case NOTES: count = db.delete("wikinotes", where, whereArgs); break; case NOTE_NAME: if (!TextUtils.isEmpty(where) || (whereArgs != null)) { throw new UnsupportedOperationException( "Cannot update note using where clause"); } String noteId = uri.getPathSegments().get(1); count = db.delete("wikinotes", "_id=?", new String[] { noteId }); break; default: throw new IllegalArgumentException("Unknown URL " + uri); } getContext().getContentResolver().notifyChange(uri, null); return count; } /** * The update method, which will allow either a mass update using a where * clause, or an update targeted to a specific note name (the latter will * be more common). Other matched URLs will be rejected as invalid. For * updating notes by title we use ReST style arguments from the URI and do * not support using the where clause or args. */ @Override public int update(Uri uri, ContentValues values, String where, String[] whereArgs) { int count; SQLiteDatabase db = dbHelper.getWritableDatabase(); switch (URI_MATCHER.match(uri)) { case NOTES: count = db.update("wikinotes", values, where, whereArgs); break; case NOTE_NAME: values.put(WikiNote.Notes.MODIFIED_DATE, System .currentTimeMillis()); count = db.update("wikinotes", values, where, whereArgs); break; default: throw new IllegalArgumentException("Unknown URL " + uri); } getContext().getContentResolver().notifyChange(uri, null); return count; } /* * This static block sets up the pattern matches for the various URIs that * this content provider can handle. It also sets up the default projection * block (which defines what columns are returned from the database for the * results of a query). */ static { URI_MATCHER = new UriMatcher(UriMatcher.NO_MATCH); URI_MATCHER.addURI(WikiNote.WIKINOTES_AUTHORITY, "wikinotes", NOTES); URI_MATCHER.addURI(WikiNote.WIKINOTES_AUTHORITY, "wikinotes/*", NOTE_NAME); URI_MATCHER.addURI(WikiNote.WIKINOTES_AUTHORITY, "wiki/search/*", NOTE_SEARCH); NOTES_LIST_PROJECTION_MAP = new HashMap<String, String>(); NOTES_LIST_PROJECTION_MAP.put(WikiNote.Notes._ID, "_id"); NOTES_LIST_PROJECTION_MAP.put(WikiNote.Notes.TITLE, "title"); NOTES_LIST_PROJECTION_MAP.put(WikiNote.Notes.BODY, "body"); NOTES_LIST_PROJECTION_MAP.put(WikiNote.Notes.CREATED_DATE, "created"); NOTES_LIST_PROJECTION_MAP.put(WikiNote.Notes.MODIFIED_DATE, "modified"); } }
zzhangumd-apps-for-android
WikiNotes/src/com/google/android/wikinotes/db/WikiNotesProvider.java
Java
asf20
11,275
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.wikinotes.db; import android.net.Uri; import android.provider.BaseColumns; /** * This class defines columns and URIs used in the wikinotes application */ public class WikiNote { /** * Notes table */ public static final class Notes implements BaseColumns { /** * The content:// style URI for this table - this to see all notes or * append a note name to see just the matching note. */ public static final Uri ALL_NOTES_URI = Uri .parse("content://com.google.android.wikinotes.db.wikinotes/wikinotes"); /** * This URI can be used to search the bodies of notes for an appended * search term. */ public static final Uri SEARCH_URI = Uri .parse("content://com.google.android.wikinotes.db.wikinotes/wiki/search"); /** * The default sort order for this table - most recently modified first */ public static final String DEFAULT_SORT_ORDER = "modified DESC"; /** * The title of the note * <P> * Type: TEXT * </P> */ public static final String TITLE = "title"; /** * The note body * <P> * Type: TEXT * </P> */ public static final String BODY = "body"; /** * The timestamp for when the note was created * <P> * Type: INTEGER (long) * </P> */ public static final String CREATED_DATE = "created"; /** * The timestamp for when the note was last modified * <P> * Type: INTEGER (long) * </P> */ public static final String MODIFIED_DATE = "modified"; } /** * Convenience definition for the projection we will use to retrieve columns * from the wikinotes */ public static final String[] WIKI_NOTES_PROJECTION = {Notes._ID, Notes.TITLE, Notes.BODY, Notes.MODIFIED_DATE}; public static final String[] WIKI_EXPORT_PROJECTION = {Notes.TITLE, Notes.BODY, Notes.CREATED_DATE, Notes.MODIFIED_DATE}; /** * The root authority for the WikiNotesProvider */ public static final String WIKINOTES_AUTHORITY = "com.google.android.wikinotes.db.wikinotes"; }
zzhangumd-apps-for-android
WikiNotes/src/com/google/android/wikinotes/db/WikiNote.java
Java
asf20
2,672
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.google.android.wikinotes; import java.io.File; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.util.ArrayList; import java.util.Calendar; import org.xmlpull.v1.XmlPullParser; import org.xmlpull.v1.XmlPullParserException; import org.xmlpull.v1.XmlPullParserFactory; import android.app.Activity; import android.app.AlertDialog; import android.content.ContentUris; import android.content.ContentValues; import android.content.DialogInterface; import android.content.Intent; import android.content.DialogInterface.OnClickListener; import android.database.Cursor; import android.net.Uri; import android.os.Environment; import com.google.android.wikinotes.db.WikiNote; /** * A helper class that implements operations required by Activities in the * system. Notably, this includes launching the Activities for edit and * delete. */ public class WikiActivityHelper { public static final int ACTIVITY_EDIT = 1; public static final int ACTIVITY_DELETE = 2; public static final int ACTIVITY_LIST = 3; public static final int ACTIVITY_SEARCH = 4; private Activity mContext; /** * Preferred constructor. * * @param context * the Activity to be used for things like calling * startActivity */ public WikiActivityHelper(Activity context) { mContext = context; } /** * @see #WikiActivityHelper(Activity) */ // intentionally private; tell IDEs not to warn us about it @SuppressWarnings("unused") private WikiActivityHelper() { } /** * If a list of notes is requested, fire the WikiNotes list Content URI * and let the WikiNotesList activity handle it. */ public void listNotes() { Intent i = new Intent(Intent.ACTION_VIEW, WikiNote.Notes.ALL_NOTES_URI); mContext.startActivity(i); } /** * If requested, go back to the start page wikinote by requesting an * intent with the default start page URI */ public void goHome() { Uri startPageURL = Uri .withAppendedPath(WikiNote.Notes.ALL_NOTES_URI, mContext .getResources().getString(R.string.start_page)); Intent startPage = new Intent(Intent.ACTION_VIEW, startPageURL); mContext.startActivity(startPage); } /** * Create an intent to start the WikiNoteEditor using the current title * and body information (if any). */ public void editNote(String mNoteName, Cursor cursor) { // This intent could use the android.intent.action.EDIT for a wiki // note // to invoke, but instead I wanted to demonstrate the mechanism for // invoking // an intent on a known class within the same application directly. // Note // also that the title and body of the note to edit are passed in // using // the extras bundle. Intent i = new Intent(mContext, WikiNoteEditor.class); i.putExtra(WikiNote.Notes.TITLE, mNoteName); String body; if (cursor != null) { body = cursor.getString(cursor .getColumnIndexOrThrow(WikiNote.Notes.BODY)); } else { body = ""; } i.putExtra(WikiNote.Notes.BODY, body); mContext.startActivityForResult(i, ACTIVITY_EDIT); } /** * If requested, delete the current note. The user is prompted to confirm * this operation with a dialog, and if they choose to go ahead with the * deletion, the current activity is finish()ed once the data has been * removed, so that android naturally backtracks to the previous activity. */ public void deleteNote(final Cursor cursor) { new AlertDialog.Builder(mContext) .setTitle( mContext.getResources() .getString(R.string.delete_title)) .setMessage(R.string.delete_message) .setPositiveButton(R.string.yes_button, new OnClickListener() { public void onClick(DialogInterface dialog, int arg1) { Uri noteUri = ContentUris .withAppendedId(WikiNote.Notes.ALL_NOTES_URI, cursor .getInt(0)); mContext.getContentResolver().delete(noteUri, null, null); mContext.setResult(Activity.RESULT_OK); mContext.finish(); } }).setNegativeButton(R.string.no_button, null).show(); } /** * Equivalent to showOutcomeDialog(titleId, msg, false). * * @see #showOutcomeDialog(int, String, boolean) * @param titleId * the resource ID of the title of the dialog window * @param msg * the message to display */ private void showOutcomeDialog(int titleId, String msg) { showOutcomeDialog(titleId, msg, false); } /** * Creates and displays a Dialog with the indicated title and body. If * kill is true, the Dialog calls finish() on the hosting Activity and * restarts it with an identical Intent. This effectively restarts or * refreshes the Activity, so that it can reload whatever data it was * displaying. * * @param titleId * the resource ID of the title of the dialog window * @param msg * the message to display */ private void showOutcomeDialog(int titleId, String msg, final boolean kill) { new AlertDialog.Builder(mContext).setCancelable(false) .setTitle(mContext.getResources().getString(titleId)) .setMessage(msg) .setPositiveButton(R.string.export_dismiss_button, new DialogInterface.OnClickListener() { public void onClick( DialogInterface dialog, int which) { if (kill) { // restart the Activity w/ same // Intent Intent intent = mContext .getIntent(); mContext.finish(); mContext.startActivity(intent); } } }).create().show(); } /** * Exports notes to the SD card. Displays Dialogs as appropriate (using * the Activity provided in the constructor as a Context) to inform the * user as to what is going on. */ public void exportNotes() { // first see if an SD card is even present; abort if not if (!Environment.MEDIA_MOUNTED.equals(Environment .getExternalStorageState())) { showOutcomeDialog(R.string.export_failure_title, mContext .getResources().getString(R.string.export_failure_missing_sd)); return; } // do a query for all records Cursor c = mContext.managedQuery(WikiNote.Notes.ALL_NOTES_URI, WikiNote.WIKI_EXPORT_PROJECTION, null, null, WikiNote.Notes.DEFAULT_SORT_ORDER); // iterate over all Notes, building up an XML StringBuffer along the // way boolean dataAvailable = c.moveToFirst(); StringBuffer sb = new StringBuffer(); String title, body, created, modified; int cnt = 0; sb.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<wiki-notes>"); while (dataAvailable) { title = c.getString(c.getColumnIndexOrThrow("title")); body = c.getString(c.getColumnIndexOrThrow("body")); modified = c.getString(c.getColumnIndexOrThrow("modified")); created = c.getString(c.getColumnIndexOrThrow("created")); // do a quick sanity check to make sure the note is worth saving if (!"".equals(title) && !"".equals(body) && title != null && body != null) { sb.append("\n").append("<note>\n\t<title><![CDATA[") .append(title).append("]]></title>\n\t<body><![CDATA["); sb.append(body).append("]]></body>\n\t<created>") .append(created).append("</created>\n\t"); sb.append("<modified>").append(modified) .append("</modified>\n</note>"); cnt++; } dataAvailable = c.moveToNext(); } sb.append("\n</wiki-notes>\n"); // open a file on the SD card under some useful name, and write out // XML FileWriter fw = null; File f = null; try { f = new File(Environment.getExternalStorageDirectory() + "/" + EXPORT_DIR); f.mkdirs(); // EXPORT_FILENAME includes current date+time, for user benefit String fileName = String.format(EXPORT_FILENAME, Calendar .getInstance()); f = new File(Environment.getExternalStorageDirectory() + "/" + EXPORT_DIR + "/" + fileName); if (!f.createNewFile()) { showOutcomeDialog(R.string.export_failure_title, mContext .getResources() .getString(R.string.export_failure_io_error)); return; } fw = new FileWriter(f); fw.write(sb.toString()); } catch (IOException e) { showOutcomeDialog(R.string.export_failure_title, mContext .getResources().getString(R.string.export_failure_io_error)); return; } finally { if (fw != null) { try { fw.close(); } catch (IOException ex) { } } } if (f == null) { showOutcomeDialog(R.string.export_failure_title, mContext .getResources().getString(R.string.export_failure_io_error)); return; } // Victory! Tell the user and display the filename just written. showOutcomeDialog(R.string.export_success_title, String .format(mContext.getResources() .getString(R.string.export_success), cnt, f.getName())); } /** * Imports records from SD card. Note that this is a destructive * operation: all existing records are destroyed. Displays confirmation * and outcome Dialogs before erasing data and after loading data. * * Note that this is the method that actually does the work; * {@link #importNotes()} is the method that should be called to kick * things off. * * @see #importNotes() */ public void doImport() { // first see if an SD card is even present; abort if not if (!Environment.MEDIA_MOUNTED.equals(Environment .getExternalStorageState())) { showOutcomeDialog(R.string.import_failure_title, mContext .getResources().getString(R.string.export_failure_missing_sd)); return; } int cnt = 0; FileReader fr = null; ArrayList<StringBuffer[]> records = new ArrayList<StringBuffer[]>(); try { // first, find the file to load fr = new FileReader(new File(Environment .getExternalStorageDirectory() + "/" + IMPORT_FILENAME)); // don't destroy data until AFTER we find a file to import! mContext.getContentResolver() .delete(WikiNote.Notes.ALL_NOTES_URI, null, null); // next, parse that sucker XmlPullParserFactory factory = XmlPullParserFactory.newInstance(); factory.setNamespaceAware(false); XmlPullParser xpp = factory.newPullParser(); xpp.setInput(fr); int eventType = xpp.getEventType(); StringBuffer[] cur = new StringBuffer[4]; int curIdx = -1; while (eventType != XmlPullParser.END_DOCUMENT) { // save the previous note data-holder when we end a <note> tag if (eventType == XmlPullParser.END_TAG && "note".equals(xpp.getName())) { if (cur[0] != null && cur[1] != null && !"".equals(cur[0]) && !"".equals(cur[1])) { records.add(cur); } cur = new StringBuffer[4]; curIdx = -1; } else if (eventType == XmlPullParser.START_TAG && "title".equals(xpp.getName())) { curIdx = 0; } else if (eventType == XmlPullParser.START_TAG && "body".equals(xpp.getName())) { curIdx = 1; } else if (eventType == XmlPullParser.START_TAG && "created".equals(xpp.getName())) { curIdx = 2; } else if (eventType == XmlPullParser.START_TAG && "modified".equals(xpp.getName())) { curIdx = 3; } else if (eventType == XmlPullParser.TEXT && curIdx > -1) { if (cur[curIdx] == null) { cur[curIdx] = new StringBuffer(); } cur[curIdx].append(xpp.getText()); } eventType = xpp.next(); } // we stored data in a stringbuffer so we can skip empty records; // now process the successful records & save to Provider for (StringBuffer[] record : records) { Uri uri = Uri.withAppendedPath(WikiNote.Notes.ALL_NOTES_URI, record[0].toString()); ContentValues values = new ContentValues(); values.put("title", record[0].toString().trim()); values.put("body", record[1].toString().trim()); values.put("created", Long.parseLong(record[2].toString() .trim())); values.put("modified", Long.parseLong(record[3].toString() .trim())); if (mContext.getContentResolver().insert(uri, values) != null) { cnt++; } } } catch (FileNotFoundException e) { showOutcomeDialog(R.string.import_failure_title, mContext .getResources().getString(R.string.import_failure_nofile)); return; } catch (XmlPullParserException e) { showOutcomeDialog(R.string.import_failure_title, mContext .getResources().getString(R.string.import_failure_corrupt)); return; } catch (IOException e) { showOutcomeDialog(R.string.import_failure_title, mContext .getResources().getString(R.string.import_failure_io)); return; } finally { if (fr != null) { try { fr.close(); } catch (IOException e) { } } } // Victory! Inform the user. showOutcomeDialog(R.string.import_success_title, String .format(mContext.getResources() .getString(R.string.import_success), cnt), true); } /** * Starts a note import. Essentially this method just displays a Dialog * requesting confirmation from the user for the destructive operation. If * the user confirms, {@link #doImport()} is called. * * @see #doImport() */ public void importNotes() { new AlertDialog.Builder(mContext).setCancelable(true) .setTitle( mContext.getResources() .getString(R.string.import_confirm_title)) .setMessage(R.string.import_confirm_body) .setPositiveButton(R.string.import_confirm_button, new DialogInterface.OnClickListener() { public void onClick(DialogInterface arg0, int arg1) { doImport(); } }) .setNegativeButton(R.string.import_cancel_button, null).create() .show(); } /** * Launches the email system client to send a mail with the current * message. */ public void mailNote(final Cursor cursor) { Intent intent = new Intent(Intent.ACTION_SEND); intent.setType("message/rfc822"); intent.putExtra(Intent.EXTRA_SUBJECT, cursor.getString(cursor .getColumnIndexOrThrow("title"))); String body = String.format(mContext.getResources() .getString(R.string.email_leader), cursor.getString(cursor .getColumnIndexOrThrow("body"))); intent.putExtra(Intent.EXTRA_TEXT, body); mContext.startActivity(Intent.createChooser(intent, "Title:")); } /* Some constants for filename structures. Could conceivably go into * strings.xml, but these don't need to be internationalized, so... */ private static final String EXPORT_DIR = "WikiNotes"; private static final String EXPORT_FILENAME = "WikiNotes_%1$tY-%1$tm-%1$td_%1$tH-%1$tM-%1$tS.xml"; private static final String IMPORT_FILENAME = "WikiNotes-import.xml"; }
zzhangumd-apps-for-android
WikiNotes/src/com/google/android/wikinotes/WikiActivityHelper.java
Java
asf20
15,387
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.wikinotes; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.text.TextUtils; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import com.google.android.wikinotes.db.WikiNote; /** * Wikinote editor activity. This is a very simple activity that allows the user * to edit a wikinote using a text editor and confirm or cancel the changes. The * title and body for the wikinote to edit are passed in using the extras bundle * and the onFreeze() method provisions for those values to be stored in the * icicle on a lifecycle event, so that the user retains control over whether * the changes are committed to the database. */ public class WikiNoteEditor extends Activity { protected static final String ACTIVITY_RESULT = "com.google.android.wikinotes.EDIT"; private EditText mNoteEdit; private String mWikiNoteTitle; @Override protected void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.wiki_note_edit); mNoteEdit = (EditText) findViewById(R.id.noteEdit); // Check to see if the icicle has body and title values to restore String wikiNoteText = icicle == null ? null : icicle.getString(WikiNote.Notes.BODY); String wikiNoteTitle = icicle == null ? null : icicle.getString(WikiNote.Notes.TITLE); // If not, check to see if the extras bundle has these values passed in if (wikiNoteTitle == null) { Bundle extras = getIntent().getExtras(); wikiNoteText = extras == null ? null : extras .getString(WikiNote.Notes.BODY); wikiNoteTitle = extras == null ? null : extras .getString(WikiNote.Notes.TITLE); } // If we have no title information, this is an invalid intent request if (TextUtils.isEmpty(wikiNoteTitle)) { // no note title - bail setResult(RESULT_CANCELED); finish(); return; } mWikiNoteTitle = wikiNoteTitle; // but if the body is null, just set it to empty - first edit of this // note wikiNoteText = wikiNoteText == null ? "" : wikiNoteText; // set the title so we know which note we are editing setTitle(getString(R.string.wiki_editing, wikiNoteTitle)); // set the note body to edit mNoteEdit.setText(wikiNoteText); // set listeners for the confirm and cancel buttons ((Button) findViewById(R.id.confirmButton)) .setOnClickListener(new OnClickListener() { public void onClick(View view) { Intent i = new Intent(); i.putExtra(ACTIVITY_RESULT, mNoteEdit.getText() .toString()); setResult(RESULT_OK, i); finish(); } }); ((Button) findViewById(R.id.cancelButton)) .setOnClickListener(new OnClickListener() { public void onClick(View view) { setResult(RESULT_CANCELED); finish(); } }); if (!getSharedPreferences(Eula.PREFERENCES_EULA, Activity.MODE_PRIVATE) .getBoolean(Eula.PREFERENCE_EULA_ACCEPTED, false)) { Eula.showEula(this); } } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); outState.putString(WikiNote.Notes.TITLE, mWikiNoteTitle); outState.putString(WikiNote.Notes.BODY, mNoteEdit.getText().toString()); } }
zzhangumd-apps-for-android
WikiNotes/src/com/google/android/wikinotes/WikiNoteEditor.java
Java
asf20
3,997
/* * Copyright (C) 2007 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.opengles.spritetext; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.Paint.Style; import android.graphics.drawable.Drawable; import android.opengl.GLUtils; import java.util.ArrayList; import javax.microedition.khronos.opengles.GL10; import javax.microedition.khronos.opengles.GL11; import javax.microedition.khronos.opengles.GL11Ext; /** * An OpenGL text label maker. * * * OpenGL labels are implemented by creating a Bitmap, drawing all the labels * into the Bitmap, converting the Bitmap into an Alpha texture, and creating a * mesh for each label * * The benefits of this approach are that the labels are drawn using the high * quality anti-aliased font rasterizer, full character set support, and all the * text labels are stored on a single texture, which makes it faster to use. * * The drawbacks are that you can only have as many labels as will fit onto one * texture, and you have to recreate the whole texture if any label text * changes. * */ public class LabelMaker { /** * Create a label maker * or maximum compatibility with various OpenGL ES implementations, * the strike width and height must be powers of two, * We want the strike width to be at least as wide as the widest window. * * @param fullColor true if we want a full color backing store (4444), * otherwise we generate a grey L8 backing store. * @param strikeWidth width of strike * @param strikeHeight height of strike */ public LabelMaker(boolean fullColor, int strikeWidth, int strikeHeight) { mFullColor = fullColor; mStrikeWidth = strikeWidth; mStrikeHeight = strikeHeight; mTexelWidth = (float) (1.0 / mStrikeWidth); mTexelHeight = (float) (1.0 / mStrikeHeight); mClearPaint = new Paint(); mClearPaint.setARGB(0, 0, 0, 0); mClearPaint.setStyle(Style.FILL); mState = STATE_NEW; } /** * Call to initialize the class. * Call whenever the surface has been created. * * @param gl */ public void initialize(GL10 gl) { mState = STATE_INITIALIZED; int[] textures = new int[1]; gl.glGenTextures(1, textures, 0); mTextureID = textures[0]; gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureID); // Use Nearest for performance. gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_NEAREST); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_CLAMP_TO_EDGE); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_CLAMP_TO_EDGE); gl.glTexEnvf(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE, GL10.GL_REPLACE); } /** * Call when the surface has been destroyed */ public void shutdown(GL10 gl) { if ( gl != null) { if (mState > STATE_NEW) { int[] textures = new int[1]; textures[0] = mTextureID; gl.glDeleteTextures(1, textures, 0); mState = STATE_NEW; } } } /** * Call before adding labels. Clears out any existing labels. * * @param gl */ public void beginAdding(GL10 gl) { checkState(STATE_INITIALIZED, STATE_ADDING); mLabels.clear(); mU = 0; mV = 0; mLineHeight = 0; Bitmap.Config config = mFullColor ? Bitmap.Config.ARGB_4444 : Bitmap.Config.ALPHA_8; mBitmap = Bitmap.createBitmap(mStrikeWidth, mStrikeHeight, config); mCanvas = new Canvas(mBitmap); mBitmap.eraseColor(0); } /** * Call to add a label * * @param gl * @param text the text of the label * @param textPaint the paint of the label * @return the id of the label, used to measure and draw the label */ public int add(GL10 gl, String text, Paint textPaint) { return add(gl, null, text, textPaint); } /** * Call to add a label * * @param gl * @param text the text of the label * @param textPaint the paint of the label * @return the id of the label, used to measure and draw the label */ public int add(GL10 gl, Drawable background, String text, Paint textPaint) { return add(gl, background, text, textPaint, 0, 0); } /** * Call to add a label * @return the id of the label, used to measure and draw the label */ public int add(GL10 gl, Drawable drawable, int minWidth, int minHeight) { return add(gl, drawable, null, null, minWidth, minHeight); } /** * Call to add a label * * @param gl * @param text the text of the label * @param textPaint the paint of the label * @return the id of the label, used to measure and draw the label */ public int add(GL10 gl, Drawable background, String text, Paint textPaint, int minWidth, int minHeight) { checkState(STATE_ADDING, STATE_ADDING); boolean drawBackground = background != null; boolean drawText = (text != null) && (textPaint != null); Rect padding = new Rect(); if (drawBackground) { background.getPadding(padding); minWidth = Math.max(minWidth, background.getMinimumWidth()); minHeight = Math.max(minHeight, background.getMinimumHeight()); } int ascent = 0; int descent = 0; int measuredTextWidth = 0; if (drawText) { // Paint.ascent is negative, so negate it. ascent = (int) Math.ceil(-textPaint.ascent()); descent = (int) Math.ceil(textPaint.descent()); measuredTextWidth = (int) Math.ceil(textPaint.measureText(text)); } int textHeight = ascent + descent; int textWidth = Math.min(mStrikeWidth,measuredTextWidth); int padHeight = padding.top + padding.bottom; int padWidth = padding.left + padding.right; int height = Math.max(minHeight, textHeight + padHeight); int width = Math.max(minWidth, textWidth + padWidth); int effectiveTextHeight = height - padHeight; int effectiveTextWidth = width - padWidth; int centerOffsetHeight = (effectiveTextHeight - textHeight) / 2; int centerOffsetWidth = (effectiveTextWidth - textWidth) / 2; // Make changes to the local variables, only commit them // to the member variables after we've decided not to throw // any exceptions. int u = mU; int v = mV; int lineHeight = mLineHeight; if (width > mStrikeWidth) { width = mStrikeWidth; } // Is there room for this string on the current line? if (u + width > mStrikeWidth) { // No room, go to the next line: u = 0; v += lineHeight; lineHeight = 0; } lineHeight = Math.max(lineHeight, height); if (v + lineHeight > mStrikeHeight) { throw new IllegalArgumentException("Out of texture space."); } int u2 = u + width; int vBase = v + ascent; int v2 = v + height; if (drawBackground) { background.setBounds(u, v, u + width, v + height); background.draw(mCanvas); } if (drawText) { mCanvas.drawText(text, u + padding.left + centerOffsetWidth, vBase + padding.top + centerOffsetHeight, textPaint); } Grid grid = new Grid(2, 2); // Grid.set arguments: i, j, x, y, z, u, v float texU = u * mTexelWidth; float texU2 = u2 * mTexelWidth; float texV = 1.0f - v * mTexelHeight; float texV2 = 1.0f - v2 * mTexelHeight; grid.set(0, 0, 0.0f, 0.0f, 0.0f, texU , texV2); grid.set(1, 0, width, 0.0f, 0.0f, texU2, texV2); grid.set(0, 1, 0.0f, height, 0.0f, texU , texV ); grid.set(1, 1, width, height, 0.0f, texU2, texV ); // We know there's enough space, so update the member variables mU = u + width; mV = v; mLineHeight = lineHeight; mLabels.add(new Label(grid, width, height, ascent, u, v + height, width, -height)); return mLabels.size() - 1; } /** * Call to end adding labels. Must be called before drawing starts. * * @param gl */ public void endAdding(GL10 gl) { checkState(STATE_ADDING, STATE_INITIALIZED); gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureID); GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, mBitmap, 0); // Reclaim storage used by bitmap and canvas. mBitmap.recycle(); mBitmap = null; mCanvas = null; } /** * Get the width in pixels of a given label. * * @param labelID * @return the width in pixels */ public float getWidth(int labelID) { return mLabels.get(labelID).width; } /** * Get the height in pixels of a given label. * * @param labelID * @return the height in pixels */ public float getHeight(int labelID) { return mLabels.get(labelID).height; } /** * Get the baseline of a given label. That's how many pixels from the top of * the label to the text baseline. (This is equivalent to the negative of * the label's paint's ascent.) * * @param labelID * @return the baseline in pixels. */ public float getBaseline(int labelID) { return mLabels.get(labelID).baseline; } /** * Begin drawing labels. Sets the OpenGL state for rapid drawing. * * @param gl * @param viewWidth * @param viewHeight */ public void beginDrawing(GL10 gl, float viewWidth, float viewHeight) { checkState(STATE_INITIALIZED, STATE_DRAWING); gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureID); gl.glShadeModel(GL10.GL_FLAT); gl.glEnable(GL10.GL_BLEND); gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); gl.glColor4x(0x10000, 0x10000, 0x10000, 0x10000); gl.glMatrixMode(GL10.GL_PROJECTION); gl.glPushMatrix(); gl.glLoadIdentity(); gl.glOrthof(0.0f, viewWidth, 0.0f, viewHeight, 0.0f, 1.0f); gl.glMatrixMode(GL10.GL_MODELVIEW); gl.glPushMatrix(); gl.glLoadIdentity(); // Magic offsets to promote consistent rasterization. gl.glTranslatef(0.375f, 0.375f, 0.0f); } /** * Draw a given label at a given x,y position, expressed in pixels, with the * lower-left-hand-corner of the view being (0,0). * * @param gl * @param x * @param y * @param labelID */ public void draw(GL10 gl, float x, float y, int labelID) { checkState(STATE_DRAWING, STATE_DRAWING); gl.glPushMatrix(); float snappedX = (float) Math.floor(x); float snappedY = (float) Math.floor(y); gl.glTranslatef(snappedX, snappedY, 0.0f); Label label = mLabels.get(labelID); gl.glEnable(GL10.GL_TEXTURE_2D); ((GL11)gl).glTexParameteriv(GL10.GL_TEXTURE_2D, GL11Ext.GL_TEXTURE_CROP_RECT_OES, label.mCrop, 0); ((GL11Ext)gl).glDrawTexiOES((int) snappedX, (int) snappedY, 0, (int) label.width, (int) label.height); gl.glPopMatrix(); } /** * Ends the drawing and restores the OpenGL state. * * @param gl */ public void endDrawing(GL10 gl) { checkState(STATE_DRAWING, STATE_INITIALIZED); gl.glDisable(GL10.GL_BLEND); gl.glMatrixMode(GL10.GL_PROJECTION); gl.glPopMatrix(); gl.glMatrixMode(GL10.GL_MODELVIEW); gl.glPopMatrix(); } private void checkState(int oldState, int newState) { if (mState != oldState) { throw new IllegalArgumentException("Can't call this method now."); } mState = newState; } private static class Label { public Label(Grid grid, float width, float height, float baseLine, int cropU, int cropV, int cropW, int cropH) { this.grid = grid; this.width = width; this.height = height; this.baseline = baseLine; int[] crop = new int[4]; crop[0] = cropU; crop[1] = cropV; crop[2] = cropW; crop[3] = cropH; mCrop = crop; } public Grid grid; public float width; public float height; public float baseline; public int[] mCrop; } private int mStrikeWidth; private int mStrikeHeight; private boolean mFullColor; private Bitmap mBitmap; private Canvas mCanvas; private Paint mClearPaint; private int mTextureID; private float mTexelWidth; // Convert texel to U private float mTexelHeight; // Convert texel to V private int mU; private int mV; private int mLineHeight; private ArrayList<Label> mLabels = new ArrayList<Label>(); private static final int STATE_NEW = 0; private static final int STATE_INITIALIZED = 1; private static final int STATE_ADDING = 2; private static final int STATE_DRAWING = 3; private int mState; }
zzhangumd-apps-for-android
Samples/OpenGLES/SpriteText/src/com/google/android/opengles/spritetext/LabelMaker.java
Java
asf20
14,238
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.opengles.spritetext; import javax.microedition.khronos.opengles.GL10; import android.graphics.Paint; public class NumericSprite { public NumericSprite() { mText = ""; mLabelMaker = null; } public void initialize(GL10 gl, Paint paint) { int height = roundUpPower2((int) paint.getFontSpacing()); final float interDigitGaps = 9 * 1.0f; int width = roundUpPower2((int) (interDigitGaps + paint.measureText(sStrike))); mLabelMaker = new LabelMaker(true, width, height); mLabelMaker.initialize(gl); mLabelMaker.beginAdding(gl); for (int i = 0; i < 10; i++) { String digit = sStrike.substring(i, i+1); mLabelId[i] = mLabelMaker.add(gl, digit, paint); mWidth[i] = (int) Math.ceil(mLabelMaker.getWidth(i)); } mLabelMaker.endAdding(gl); } public void shutdown(GL10 gl) { mLabelMaker.shutdown(gl); mLabelMaker = null; } /** * Find the smallest power of two >= the input value. * (Doesn't work for negative numbers.) */ private int roundUpPower2(int x) { x = x - 1; x = x | (x >> 1); x = x | (x >> 2); x = x | (x >> 4); x = x | (x >> 8); x = x | (x >>16); return x + 1; } public void setValue(int value) { mText = format(value); } public void draw(GL10 gl, float x, float y, float viewWidth, float viewHeight) { int length = mText.length(); mLabelMaker.beginDrawing(gl, viewWidth, viewHeight); for(int i = 0; i < length; i++) { char c = mText.charAt(i); int digit = c - '0'; mLabelMaker.draw(gl, x, y, mLabelId[digit]); x += mWidth[digit]; } mLabelMaker.endDrawing(gl); } public float width() { float width = 0.0f; int length = mText.length(); for(int i = 0; i < length; i++) { char c = mText.charAt(i); width += mWidth[c - '0']; } return width; } private String format(int value) { return Integer.toString(value); } private LabelMaker mLabelMaker; private String mText; private int[] mWidth = new int[10]; private int[] mLabelId = new int[10]; private final static String sStrike = "0123456789"; }
zzhangumd-apps-for-android
Samples/OpenGLES/SpriteText/src/com/google/android/opengles/spritetext/NumericSprite.java
Java
asf20
3,006
/* * Copyright (C) 2007 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.opengles.spritetext; import java.nio.CharBuffer; import java.nio.FloatBuffer; import javax.microedition.khronos.opengles.GL10; /** * A 2D rectangular mesh. Can be drawn textured or untextured. * */ class Grid { public Grid(int w, int h) { if (w < 0 || w >= 65536) { throw new IllegalArgumentException("w"); } if (h < 0 || h >= 65536) { throw new IllegalArgumentException("h"); } if (w * h >= 65536) { throw new IllegalArgumentException("w * h >= 65536"); } mW = w; mH = h; int size = w * h; mVertexArray = new float[size * 3]; mVertexBuffer = FloatBuffer.wrap(mVertexArray); mTexCoordArray = new float[size * 2]; mTexCoordBuffer = FloatBuffer.wrap(mTexCoordArray); int quadW = mW - 1; int quadH = mH - 1; int quadCount = quadW * quadH; int indexCount = quadCount * 6; mIndexCount = indexCount; char[] indexArray = new char[indexCount]; /* * Initialize triangle list mesh. * * [0]-----[ 1] ... * | / | * | / | * | / | * [w]-----[w+1] ... * | | * */ { int i = 0; for (int y = 0; y < quadH; y++) { for (int x = 0; x < quadW; x++) { char a = (char) (y * mW + x); char b = (char) (y * mW + x + 1); char c = (char) ((y + 1) * mW + x); char d = (char) ((y + 1) * mW + x + 1); indexArray[i++] = a; indexArray[i++] = b; indexArray[i++] = c; indexArray[i++] = b; indexArray[i++] = c; indexArray[i++] = d; } } } mIndexBuffer = CharBuffer.wrap(indexArray); } void set(int i, int j, float x, float y, float z, float u, float v) { if (i < 0 || i >= mW) { throw new IllegalArgumentException("i"); } if (j < 0 || j >= mH) { throw new IllegalArgumentException("j"); } int index = mW * j + i; int posIndex = index * 3; mVertexArray[posIndex] = x; mVertexArray[posIndex + 1] = y; mVertexArray[posIndex + 2] = z; int texIndex = index * 2; mTexCoordArray[texIndex] = u; mTexCoordArray[texIndex + 1] = v; } public void draw(GL10 gl, boolean useTexture) { gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); gl.glVertexPointer(3, GL10.GL_FLOAT, 0, mVertexBuffer); if (useTexture) { gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY); gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, mTexCoordBuffer); gl.glEnable(GL10.GL_TEXTURE_2D); } else { gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY); gl.glDisable(GL10.GL_TEXTURE_2D); } gl.glDrawElements(GL10.GL_TRIANGLES, mIndexCount, GL10.GL_UNSIGNED_SHORT, mIndexBuffer); gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); } private FloatBuffer mVertexBuffer; private float[] mVertexArray; private FloatBuffer mTexCoordBuffer; private float[] mTexCoordArray; private CharBuffer mIndexBuffer; private int mW; private int mH; private int mIndexCount; }
zzhangumd-apps-for-android
Samples/OpenGLES/SpriteText/src/com/google/android/opengles/spritetext/Grid.java
Java
asf20
3,501
/* * Copyright (C) 2007 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.opengles.spritetext; import android.opengl.Matrix; import javax.microedition.khronos.opengles.GL10; /** * A utility that projects * */ class Projector { public Projector() { mMVP = new float[16]; mV = new float[4]; mGrabber = new MatrixGrabber(); } public void setCurrentView(int x, int y, int width, int height) { mX = x; mY = y; mViewWidth = width; mViewHeight = height; } public void project(float[] obj, int objOffset, float[] win, int winOffset) { if (!mMVPComputed) { Matrix.multiplyMM(mMVP, 0, mGrabber.mProjection, 0, mGrabber.mModelView, 0); mMVPComputed = true; } Matrix.multiplyMV(mV, 0, mMVP, 0, obj, objOffset); float rw = 1.0f / mV[3]; win[winOffset] = mX + mViewWidth * (mV[0] * rw + 1.0f) * 0.5f; win[winOffset + 1] = mY + mViewHeight * (mV[1] * rw + 1.0f) * 0.5f; win[winOffset + 2] = (mV[2] * rw + 1.0f) * 0.5f; } /** * Get the current projection matrix. Has the side-effect of * setting current matrix mode to GL_PROJECTION * @param gl */ public void getCurrentProjection(GL10 gl) { mGrabber.getCurrentProjection(gl); mMVPComputed = false; } /** * Get the current model view matrix. Has the side-effect of * setting current matrix mode to GL_MODELVIEW * @param gl */ public void getCurrentModelView(GL10 gl) { mGrabber.getCurrentModelView(gl); mMVPComputed = false; } private MatrixGrabber mGrabber; private boolean mMVPComputed; private float[] mMVP; private float[] mV; private int mX; private int mY; private int mViewWidth; private int mViewHeight; }
zzhangumd-apps-for-android
Samples/OpenGLES/SpriteText/src/com/google/android/opengles/spritetext/Projector.java
Java
asf20
2,404
/* * Copyright (C) 2007 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.opengles.spritetext; import javax.microedition.khronos.opengles.GL10; class MatrixGrabber { public MatrixGrabber() { mModelView = new float[16]; mProjection = new float[16]; } /** * Record the current modelView and projection matrix state. * Has the side effect of setting the current matrix state to GL_MODELVIEW * @param gl */ public void getCurrentState(GL10 gl) { getCurrentProjection(gl); getCurrentModelView(gl); } /** * Record the current modelView matrix state. Has the side effect of * setting the current matrix state to GL_MODELVIEW * @param gl */ public void getCurrentModelView(GL10 gl) { getMatrix(gl, GL10.GL_MODELVIEW, mModelView); } /** * Record the current projection matrix state. Has the side effect of * setting the current matrix state to GL_PROJECTION * @param gl */ public void getCurrentProjection(GL10 gl) { getMatrix(gl, GL10.GL_PROJECTION, mProjection); } private void getMatrix(GL10 gl, int mode, float[] mat) { MatrixTrackingGL gl2 = (MatrixTrackingGL) gl; gl2.glMatrixMode(mode); gl2.getMatrix(mat, 0); } public float[] mModelView; public float[] mProjection; }
zzhangumd-apps-for-android
Samples/OpenGLES/SpriteText/src/com/google/android/opengles/spritetext/MatrixGrabber.java
Java
asf20
1,920
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.opengles.spritetext; import javax.microedition.khronos.opengles.GL; import android.app.Activity; import android.os.Bundle; public class SpriteTextActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mGLView = (GLView) findViewById(R.id.glview); mGLView.setGLWrapper(new GLView.GLWrapper() { public GL wrap(GL gl) { return new MatrixTrackingGL(gl); }}); mGLView.setRenderer(new SpriteTextRenderer(this)); mGLView.requestFocus(); } @Override protected void onPause() { super.onPause(); mGLView.onPause(); } @Override protected void onResume() { super.onResume(); mGLView.onResume(); } private GLView mGLView; }
zzhangumd-apps-for-android
Samples/OpenGLES/SpriteText/src/com/google/android/opengles/spritetext/SpriteTextActivity.java
Java
asf20
1,509
/* * Copyright (C) 2007 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.opengles.spritetext; import android.util.Log; import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.nio.ShortBuffer; import javax.microedition.khronos.opengles.GL; import javax.microedition.khronos.opengles.GL10; import javax.microedition.khronos.opengles.GL10Ext; import javax.microedition.khronos.opengles.GL11; import javax.microedition.khronos.opengles.GL11Ext; /** * Allows retrieving the current matrix even if the current OpenGL ES * driver does not support retrieving the current matrix. * * Note: the actual matrix may differ from the retrieved matrix, due * to differences in the way the math is implemented by GLMatrixWrapper * as compared to the way the math is implemented by the OpenGL ES * driver. */ class MatrixTrackingGL implements GL, GL10, GL10Ext, GL11, GL11Ext { private GL10 mgl; private GL10Ext mgl10Ext; private GL11 mgl11; private GL11Ext mgl11Ext; private int mMatrixMode; private MatrixStack mCurrent; private MatrixStack mModelView; private MatrixStack mTexture; private MatrixStack mProjection; private final static boolean _check = false; ByteBuffer mByteBuffer; FloatBuffer mFloatBuffer; float[] mCheckA; float[] mCheckB; public MatrixTrackingGL(GL gl) { mgl = (GL10) gl; if (gl instanceof GL10Ext) { mgl10Ext = (GL10Ext) gl; } if (gl instanceof GL11) { mgl11 = (GL11) gl; } if (gl instanceof GL11Ext) { mgl11Ext = (GL11Ext) gl; } mModelView = new MatrixStack(); mProjection = new MatrixStack(); mTexture = new MatrixStack(); mCurrent = mModelView; mMatrixMode = GL10.GL_MODELVIEW; } // --------------------------------------------------------------------- // GL10 methods: public void glActiveTexture(int texture) { mgl.glActiveTexture(texture); } public void glAlphaFunc(int func, float ref) { mgl.glAlphaFunc(func, ref); } public void glAlphaFuncx(int func, int ref) { mgl.glAlphaFuncx(func, ref); } public void glBindTexture(int target, int texture) { mgl.glBindTexture(target, texture); } public void glBlendFunc(int sfactor, int dfactor) { mgl.glBlendFunc(sfactor, dfactor); } public void glClear(int mask) { mgl.glClear(mask); } public void glClearColor(float red, float green, float blue, float alpha) { mgl.glClearColor(red, green, blue, alpha); } public void glClearColorx(int red, int green, int blue, int alpha) { mgl.glClearColorx(red, green, blue, alpha); } public void glClearDepthf(float depth) { mgl.glClearDepthf(depth); } public void glClearDepthx(int depth) { mgl.glClearDepthx(depth); } public void glClearStencil(int s) { mgl.glClearStencil(s); } public void glClientActiveTexture(int texture) { mgl.glClientActiveTexture(texture); } public void glColor4f(float red, float green, float blue, float alpha) { mgl.glColor4f(red, green, blue, alpha); } public void glColor4x(int red, int green, int blue, int alpha) { mgl.glColor4x(red, green, blue, alpha); } public void glColorMask(boolean red, boolean green, boolean blue, boolean alpha) { mgl.glColorMask(red, green, blue, alpha); } public void glColorPointer(int size, int type, int stride, Buffer pointer) { mgl.glColorPointer(size, type, stride, pointer); } public void glCompressedTexImage2D(int target, int level, int internalformat, int width, int height, int border, int imageSize, Buffer data) { mgl.glCompressedTexImage2D(target, level, internalformat, width, height, border, imageSize, data); } public void glCompressedTexSubImage2D(int target, int level, int xoffset, int yoffset, int width, int height, int format, int imageSize, Buffer data) { mgl.glCompressedTexSubImage2D(target, level, xoffset, yoffset, width, height, format, imageSize, data); } public void glCopyTexImage2D(int target, int level, int internalformat, int x, int y, int width, int height, int border) { mgl.glCopyTexImage2D(target, level, internalformat, x, y, width, height, border); } public void glCopyTexSubImage2D(int target, int level, int xoffset, int yoffset, int x, int y, int width, int height) { mgl.glCopyTexSubImage2D(target, level, xoffset, yoffset, x, y, width, height); } public void glCullFace(int mode) { mgl.glCullFace(mode); } public void glDeleteTextures(int n, int[] textures, int offset) { mgl.glDeleteTextures(n, textures, offset); } public void glDeleteTextures(int n, IntBuffer textures) { mgl.glDeleteTextures(n, textures); } public void glDepthFunc(int func) { mgl.glDepthFunc(func); } public void glDepthMask(boolean flag) { mgl.glDepthMask(flag); } public void glDepthRangef(float near, float far) { mgl.glDepthRangef(near, far); } public void glDepthRangex(int near, int far) { mgl.glDepthRangex(near, far); } public void glDisable(int cap) { mgl.glDisable(cap); } public void glDisableClientState(int array) { mgl.glDisableClientState(array); } public void glDrawArrays(int mode, int first, int count) { mgl.glDrawArrays(mode, first, count); } public void glDrawElements(int mode, int count, int type, Buffer indices) { mgl.glDrawElements(mode, count, type, indices); } public void glEnable(int cap) { mgl.glEnable(cap); } public void glEnableClientState(int array) { mgl.glEnableClientState(array); } public void glFinish() { mgl.glFinish(); } public void glFlush() { mgl.glFlush(); } public void glFogf(int pname, float param) { mgl.glFogf(pname, param); } public void glFogfv(int pname, float[] params, int offset) { mgl.glFogfv(pname, params, offset); } public void glFogfv(int pname, FloatBuffer params) { mgl.glFogfv(pname, params); } public void glFogx(int pname, int param) { mgl.glFogx(pname, param); } public void glFogxv(int pname, int[] params, int offset) { mgl.glFogxv(pname, params, offset); } public void glFogxv(int pname, IntBuffer params) { mgl.glFogxv(pname, params); } public void glFrontFace(int mode) { mgl.glFrontFace(mode); } public void glFrustumf(float left, float right, float bottom, float top, float near, float far) { mCurrent.glFrustumf(left, right, bottom, top, near, far); mgl.glFrustumf(left, right, bottom, top, near, far); if ( _check) check(); } public void glFrustumx(int left, int right, int bottom, int top, int near, int far) { mCurrent.glFrustumx(left, right, bottom, top, near, far); mgl.glFrustumx(left, right, bottom, top, near, far); if ( _check) check(); } public void glGenTextures(int n, int[] textures, int offset) { mgl.glGenTextures(n, textures, offset); } public void glGenTextures(int n, IntBuffer textures) { mgl.glGenTextures(n, textures); } public int glGetError() { int result = mgl.glGetError(); return result; } public void glGetIntegerv(int pname, int[] params, int offset) { mgl.glGetIntegerv(pname, params, offset); } public void glGetIntegerv(int pname, IntBuffer params) { mgl.glGetIntegerv(pname, params); } public String glGetString(int name) { String result = mgl.glGetString(name); return result; } public void glHint(int target, int mode) { mgl.glHint(target, mode); } public void glLightModelf(int pname, float param) { mgl.glLightModelf(pname, param); } public void glLightModelfv(int pname, float[] params, int offset) { mgl.glLightModelfv(pname, params, offset); } public void glLightModelfv(int pname, FloatBuffer params) { mgl.glLightModelfv(pname, params); } public void glLightModelx(int pname, int param) { mgl.glLightModelx(pname, param); } public void glLightModelxv(int pname, int[] params, int offset) { mgl.glLightModelxv(pname, params, offset); } public void glLightModelxv(int pname, IntBuffer params) { mgl.glLightModelxv(pname, params); } public void glLightf(int light, int pname, float param) { mgl.glLightf(light, pname, param); } public void glLightfv(int light, int pname, float[] params, int offset) { mgl.glLightfv(light, pname, params, offset); } public void glLightfv(int light, int pname, FloatBuffer params) { mgl.glLightfv(light, pname, params); } public void glLightx(int light, int pname, int param) { mgl.glLightx(light, pname, param); } public void glLightxv(int light, int pname, int[] params, int offset) { mgl.glLightxv(light, pname, params, offset); } public void glLightxv(int light, int pname, IntBuffer params) { mgl.glLightxv(light, pname, params); } public void glLineWidth(float width) { mgl.glLineWidth(width); } public void glLineWidthx(int width) { mgl.glLineWidthx(width); } public void glLoadIdentity() { mCurrent.glLoadIdentity(); mgl.glLoadIdentity(); if ( _check) check(); } public void glLoadMatrixf(float[] m, int offset) { mCurrent.glLoadMatrixf(m, offset); mgl.glLoadMatrixf(m, offset); if ( _check) check(); } public void glLoadMatrixf(FloatBuffer m) { int position = m.position(); mCurrent.glLoadMatrixf(m); m.position(position); mgl.glLoadMatrixf(m); if ( _check) check(); } public void glLoadMatrixx(int[] m, int offset) { mCurrent.glLoadMatrixx(m, offset); mgl.glLoadMatrixx(m, offset); if ( _check) check(); } public void glLoadMatrixx(IntBuffer m) { int position = m.position(); mCurrent.glLoadMatrixx(m); m.position(position); mgl.glLoadMatrixx(m); if ( _check) check(); } public void glLogicOp(int opcode) { mgl.glLogicOp(opcode); } public void glMaterialf(int face, int pname, float param) { mgl.glMaterialf(face, pname, param); } public void glMaterialfv(int face, int pname, float[] params, int offset) { mgl.glMaterialfv(face, pname, params, offset); } public void glMaterialfv(int face, int pname, FloatBuffer params) { mgl.glMaterialfv(face, pname, params); } public void glMaterialx(int face, int pname, int param) { mgl.glMaterialx(face, pname, param); } public void glMaterialxv(int face, int pname, int[] params, int offset) { mgl.glMaterialxv(face, pname, params, offset); } public void glMaterialxv(int face, int pname, IntBuffer params) { mgl.glMaterialxv(face, pname, params); } public void glMatrixMode(int mode) { switch (mode) { case GL10.GL_MODELVIEW: mCurrent = mModelView; break; case GL10.GL_TEXTURE: mCurrent = mTexture; break; case GL10.GL_PROJECTION: mCurrent = mProjection; break; default: throw new IllegalArgumentException("Unknown matrix mode: " + mode); } mgl.glMatrixMode(mode); mMatrixMode = mode; if ( _check) check(); } public void glMultMatrixf(float[] m, int offset) { mCurrent.glMultMatrixf(m, offset); mgl.glMultMatrixf(m, offset); if ( _check) check(); } public void glMultMatrixf(FloatBuffer m) { int position = m.position(); mCurrent.glMultMatrixf(m); m.position(position); mgl.glMultMatrixf(m); if ( _check) check(); } public void glMultMatrixx(int[] m, int offset) { mCurrent.glMultMatrixx(m, offset); mgl.glMultMatrixx(m, offset); if ( _check) check(); } public void glMultMatrixx(IntBuffer m) { int position = m.position(); mCurrent.glMultMatrixx(m); m.position(position); mgl.glMultMatrixx(m); if ( _check) check(); } public void glMultiTexCoord4f(int target, float s, float t, float r, float q) { mgl.glMultiTexCoord4f(target, s, t, r, q); } public void glMultiTexCoord4x(int target, int s, int t, int r, int q) { mgl.glMultiTexCoord4x(target, s, t, r, q); } public void glNormal3f(float nx, float ny, float nz) { mgl.glNormal3f(nx, ny, nz); } public void glNormal3x(int nx, int ny, int nz) { mgl.glNormal3x(nx, ny, nz); } public void glNormalPointer(int type, int stride, Buffer pointer) { mgl.glNormalPointer(type, stride, pointer); } public void glOrthof(float left, float right, float bottom, float top, float near, float far) { mCurrent.glOrthof(left, right, bottom, top, near, far); mgl.glOrthof(left, right, bottom, top, near, far); if ( _check) check(); } public void glOrthox(int left, int right, int bottom, int top, int near, int far) { mCurrent.glOrthox(left, right, bottom, top, near, far); mgl.glOrthox(left, right, bottom, top, near, far); if ( _check) check(); } public void glPixelStorei(int pname, int param) { mgl.glPixelStorei(pname, param); } public void glPointSize(float size) { mgl.glPointSize(size); } public void glPointSizex(int size) { mgl.glPointSizex(size); } public void glPolygonOffset(float factor, float units) { mgl.glPolygonOffset(factor, units); } public void glPolygonOffsetx(int factor, int units) { mgl.glPolygonOffsetx(factor, units); } public void glPopMatrix() { mCurrent.glPopMatrix(); mgl.glPopMatrix(); if ( _check) check(); } public void glPushMatrix() { mCurrent.glPushMatrix(); mgl.glPushMatrix(); if ( _check) check(); } public void glReadPixels(int x, int y, int width, int height, int format, int type, Buffer pixels) { mgl.glReadPixels(x, y, width, height, format, type, pixels); } public void glRotatef(float angle, float x, float y, float z) { mCurrent.glRotatef(angle, x, y, z); mgl.glRotatef(angle, x, y, z); if ( _check) check(); } public void glRotatex(int angle, int x, int y, int z) { mCurrent.glRotatex(angle, x, y, z); mgl.glRotatex(angle, x, y, z); if ( _check) check(); } public void glSampleCoverage(float value, boolean invert) { mgl.glSampleCoverage(value, invert); } public void glSampleCoveragex(int value, boolean invert) { mgl.glSampleCoveragex(value, invert); } public void glScalef(float x, float y, float z) { mCurrent.glScalef(x, y, z); mgl.glScalef(x, y, z); if ( _check) check(); } public void glScalex(int x, int y, int z) { mCurrent.glScalex(x, y, z); mgl.glScalex(x, y, z); if ( _check) check(); } public void glScissor(int x, int y, int width, int height) { mgl.glScissor(x, y, width, height); } public void glShadeModel(int mode) { mgl.glShadeModel(mode); } public void glStencilFunc(int func, int ref, int mask) { mgl.glStencilFunc(func, ref, mask); } public void glStencilMask(int mask) { mgl.glStencilMask(mask); } public void glStencilOp(int fail, int zfail, int zpass) { mgl.glStencilOp(fail, zfail, zpass); } public void glTexCoordPointer(int size, int type, int stride, Buffer pointer) { mgl.glTexCoordPointer(size, type, stride, pointer); } public void glTexEnvf(int target, int pname, float param) { mgl.glTexEnvf(target, pname, param); } public void glTexEnvfv(int target, int pname, float[] params, int offset) { mgl.glTexEnvfv(target, pname, params, offset); } public void glTexEnvfv(int target, int pname, FloatBuffer params) { mgl.glTexEnvfv(target, pname, params); } public void glTexEnvx(int target, int pname, int param) { mgl.glTexEnvx(target, pname, param); } public void glTexEnvxv(int target, int pname, int[] params, int offset) { mgl.glTexEnvxv(target, pname, params, offset); } public void glTexEnvxv(int target, int pname, IntBuffer params) { mgl.glTexEnvxv(target, pname, params); } public void glTexImage2D(int target, int level, int internalformat, int width, int height, int border, int format, int type, Buffer pixels) { mgl.glTexImage2D(target, level, internalformat, width, height, border, format, type, pixels); } public void glTexParameterf(int target, int pname, float param) { mgl.glTexParameterf(target, pname, param); } public void glTexParameterx(int target, int pname, int param) { mgl.glTexParameterx(target, pname, param); } public void glTexParameteriv(int target, int pname, int[] params, int offset) { mgl11.glTexParameteriv(target, pname, params, offset); } public void glTexParameteriv(int target, int pname, IntBuffer params) { mgl11.glTexParameteriv(target, pname, params); } public void glTexSubImage2D(int target, int level, int xoffset, int yoffset, int width, int height, int format, int type, Buffer pixels) { mgl.glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixels); } public void glTranslatef(float x, float y, float z) { mCurrent.glTranslatef(x, y, z); mgl.glTranslatef(x, y, z); if ( _check) check(); } public void glTranslatex(int x, int y, int z) { mCurrent.glTranslatex(x, y, z); mgl.glTranslatex(x, y, z); if ( _check) check(); } public void glVertexPointer(int size, int type, int stride, Buffer pointer) { mgl.glVertexPointer(size, type, stride, pointer); } public void glViewport(int x, int y, int width, int height) { mgl.glViewport(x, y, width, height); } public void glClipPlanef(int plane, float[] equation, int offset) { mgl11.glClipPlanef(plane, equation, offset); } public void glClipPlanef(int plane, FloatBuffer equation) { mgl11.glClipPlanef(plane, equation); } public void glClipPlanex(int plane, int[] equation, int offset) { mgl11.glClipPlanex(plane, equation, offset); } public void glClipPlanex(int plane, IntBuffer equation) { mgl11.glClipPlanex(plane, equation); } // Draw Texture Extension public void glDrawTexfOES(float x, float y, float z, float width, float height) { mgl11Ext.glDrawTexfOES(x, y, z, width, height); } public void glDrawTexfvOES(float[] coords, int offset) { mgl11Ext.glDrawTexfvOES(coords, offset); } public void glDrawTexfvOES(FloatBuffer coords) { mgl11Ext.glDrawTexfvOES(coords); } public void glDrawTexiOES(int x, int y, int z, int width, int height) { mgl11Ext.glDrawTexiOES(x, y, z, width, height); } public void glDrawTexivOES(int[] coords, int offset) { mgl11Ext.glDrawTexivOES(coords, offset); } public void glDrawTexivOES(IntBuffer coords) { mgl11Ext.glDrawTexivOES(coords); } public void glDrawTexsOES(short x, short y, short z, short width, short height) { mgl11Ext.glDrawTexsOES(x, y, z, width, height); } public void glDrawTexsvOES(short[] coords, int offset) { mgl11Ext.glDrawTexsvOES(coords, offset); } public void glDrawTexsvOES(ShortBuffer coords) { mgl11Ext.glDrawTexsvOES(coords); } public void glDrawTexxOES(int x, int y, int z, int width, int height) { mgl11Ext.glDrawTexxOES(x, y, z, width, height); } public void glDrawTexxvOES(int[] coords, int offset) { mgl11Ext.glDrawTexxvOES(coords, offset); } public void glDrawTexxvOES(IntBuffer coords) { mgl11Ext.glDrawTexxvOES(coords); } public int glQueryMatrixxOES(int[] mantissa, int mantissaOffset, int[] exponent, int exponentOffset) { return mgl10Ext.glQueryMatrixxOES(mantissa, mantissaOffset, exponent, exponentOffset); } public int glQueryMatrixxOES(IntBuffer mantissa, IntBuffer exponent) { return mgl10Ext.glQueryMatrixxOES(mantissa, exponent); } // Unsupported GL11 methods public void glBindBuffer(int target, int buffer) { throw new UnsupportedOperationException(); } public void glBufferData(int target, int size, Buffer data, int usage) { throw new UnsupportedOperationException(); } public void glBufferSubData(int target, int offset, int size, Buffer data) { throw new UnsupportedOperationException(); } public void glColor4ub(byte red, byte green, byte blue, byte alpha) { throw new UnsupportedOperationException(); } public void glDeleteBuffers(int n, int[] buffers, int offset) { throw new UnsupportedOperationException(); } public void glDeleteBuffers(int n, IntBuffer buffers) { throw new UnsupportedOperationException(); } public void glGenBuffers(int n, int[] buffers, int offset) { throw new UnsupportedOperationException(); } public void glGenBuffers(int n, IntBuffer buffers) { throw new UnsupportedOperationException(); } public void glGetBooleanv(int pname, boolean[] params, int offset) { throw new UnsupportedOperationException(); } public void glGetBooleanv(int pname, IntBuffer params) { throw new UnsupportedOperationException(); } public void glGetBufferParameteriv(int target, int pname, int[] params, int offset) { throw new UnsupportedOperationException(); } public void glGetBufferParameteriv(int target, int pname, IntBuffer params) { throw new UnsupportedOperationException(); } public void glGetClipPlanef(int pname, float[] eqn, int offset) { throw new UnsupportedOperationException(); } public void glGetClipPlanef(int pname, FloatBuffer eqn) { throw new UnsupportedOperationException(); } public void glGetClipPlanex(int pname, int[] eqn, int offset) { throw new UnsupportedOperationException(); } public void glGetClipPlanex(int pname, IntBuffer eqn) { throw new UnsupportedOperationException(); } public void glGetFixedv(int pname, int[] params, int offset) { throw new UnsupportedOperationException(); } public void glGetFixedv(int pname, IntBuffer params) { throw new UnsupportedOperationException(); } public void glGetFloatv(int pname, float[] params, int offset) { throw new UnsupportedOperationException(); } public void glGetFloatv(int pname, FloatBuffer params) { throw new UnsupportedOperationException(); } public void glGetLightfv(int light, int pname, float[] params, int offset) { throw new UnsupportedOperationException(); } public void glGetLightfv(int light, int pname, FloatBuffer params) { throw new UnsupportedOperationException(); } public void glGetLightxv(int light, int pname, int[] params, int offset) { throw new UnsupportedOperationException(); } public void glGetLightxv(int light, int pname, IntBuffer params) { throw new UnsupportedOperationException(); } public void glGetMaterialfv(int face, int pname, float[] params, int offset) { throw new UnsupportedOperationException(); } public void glGetMaterialfv(int face, int pname, FloatBuffer params) { throw new UnsupportedOperationException(); } public void glGetMaterialxv(int face, int pname, int[] params, int offset) { throw new UnsupportedOperationException(); } public void glGetMaterialxv(int face, int pname, IntBuffer params) { throw new UnsupportedOperationException(); } public void glGetTexEnviv(int env, int pname, int[] params, int offset) { throw new UnsupportedOperationException(); } public void glGetTexEnviv(int env, int pname, IntBuffer params) { throw new UnsupportedOperationException(); } public void glGetTexEnvxv(int env, int pname, int[] params, int offset) { throw new UnsupportedOperationException(); } public void glGetTexEnvxv(int env, int pname, IntBuffer params) { throw new UnsupportedOperationException(); } public void glGetTexParameterfv(int target, int pname, float[] params, int offset) { throw new UnsupportedOperationException(); } public void glGetTexParameterfv(int target, int pname, FloatBuffer params) { throw new UnsupportedOperationException(); } public void glGetTexParameteriv(int target, int pname, int[] params, int offset) { throw new UnsupportedOperationException(); } public void glGetTexParameteriv(int target, int pname, IntBuffer params) { throw new UnsupportedOperationException(); } public void glGetTexParameterxv(int target, int pname, int[] params, int offset) { throw new UnsupportedOperationException(); } public void glGetTexParameterxv(int target, int pname, IntBuffer params) { throw new UnsupportedOperationException(); } public boolean glIsBuffer(int buffer) { throw new UnsupportedOperationException(); } public boolean glIsEnabled(int cap) { throw new UnsupportedOperationException(); } public boolean glIsTexture(int texture) { throw new UnsupportedOperationException(); } public void glPointParameterf(int pname, float param) { throw new UnsupportedOperationException(); } public void glPointParameterfv(int pname, float[] params, int offset) { throw new UnsupportedOperationException(); } public void glPointParameterfv(int pname, FloatBuffer params) { throw new UnsupportedOperationException(); } public void glPointParameterx(int pname, int param) { throw new UnsupportedOperationException(); } public void glPointParameterxv(int pname, int[] params, int offset) { throw new UnsupportedOperationException(); } public void glPointParameterxv(int pname, IntBuffer params) { throw new UnsupportedOperationException(); } public void glPointSizePointerOES(int type, int stride, Buffer pointer) { throw new UnsupportedOperationException(); } public void glTexEnvi(int target, int pname, int param) { throw new UnsupportedOperationException(); } public void glTexEnviv(int target, int pname, int[] params, int offset) { throw new UnsupportedOperationException(); } public void glTexEnviv(int target, int pname, IntBuffer params) { throw new UnsupportedOperationException(); } public void glTexParameterfv(int target, int pname, float[] params, int offset) { throw new UnsupportedOperationException(); } public void glTexParameterfv(int target, int pname, FloatBuffer params) { throw new UnsupportedOperationException(); } public void glTexParameteri(int target, int pname, int param) { throw new UnsupportedOperationException(); } public void glTexParameterxv(int target, int pname, int[] params, int offset) { throw new UnsupportedOperationException(); } public void glTexParameterxv(int target, int pname, IntBuffer params) { throw new UnsupportedOperationException(); } public void glColorPointer(int size, int type, int stride, int offset) { throw new UnsupportedOperationException(); } public void glDrawElements(int mode, int count, int type, int offset) { throw new UnsupportedOperationException(); } public void glGetPointerv(int pname, Buffer[] params) { throw new UnsupportedOperationException(); } public void glNormalPointer(int type, int stride, int offset) { throw new UnsupportedOperationException(); } public void glTexCoordPointer(int size, int type, int stride, int offset) { throw new UnsupportedOperationException(); } public void glVertexPointer(int size, int type, int stride, int offset) { throw new UnsupportedOperationException(); } public void glCurrentPaletteMatrixOES(int matrixpaletteindex) { throw new UnsupportedOperationException(); } public void glLoadPaletteFromModelViewMatrixOES() { throw new UnsupportedOperationException(); } public void glMatrixIndexPointerOES(int size, int type, int stride, Buffer pointer) { throw new UnsupportedOperationException(); } public void glMatrixIndexPointerOES(int size, int type, int stride, int offset) { throw new UnsupportedOperationException(); } public void glWeightPointerOES(int size, int type, int stride, Buffer pointer) { throw new UnsupportedOperationException(); } public void glWeightPointerOES(int size, int type, int stride, int offset) { throw new UnsupportedOperationException(); } /** * Get the current matrix */ public void getMatrix(float[] m, int offset) { mCurrent.getMatrix(m, offset); } /** * Get the current matrix mode */ public int getMatrixMode() { return mMatrixMode; } private void check() { int oesMode; switch (mMatrixMode) { case GL_MODELVIEW: oesMode = GL11.GL_MODELVIEW_MATRIX_FLOAT_AS_INT_BITS_OES; break; case GL_PROJECTION: oesMode = GL11.GL_PROJECTION_MATRIX_FLOAT_AS_INT_BITS_OES; break; case GL_TEXTURE: oesMode = GL11.GL_TEXTURE_MATRIX_FLOAT_AS_INT_BITS_OES; break; default: throw new IllegalArgumentException("Unknown matrix mode"); } if ( mByteBuffer == null) { mCheckA = new float[16]; mCheckB = new float[16]; mByteBuffer = ByteBuffer.allocateDirect(64); mByteBuffer.order(ByteOrder.nativeOrder()); mFloatBuffer = mByteBuffer.asFloatBuffer(); } mgl.glGetIntegerv(oesMode, mByteBuffer.asIntBuffer()); for(int i = 0; i < 16; i++) { mCheckB[i] = mFloatBuffer.get(i); } mCurrent.getMatrix(mCheckA, 0); boolean fail = false; for(int i = 0; i < 16; i++) { if (mCheckA[i] != mCheckB[i]) { Log.d("GLMatWrap", "i:" + i + " a:" + mCheckA[i] + " a:" + mCheckB[i]); fail = true; } } if (fail) { throw new IllegalArgumentException("Matrix math difference."); } } }
zzhangumd-apps-for-android
Samples/OpenGLES/SpriteText/src/com/google/android/opengles/spritetext/MatrixTrackingGL.java
Java
asf20
32,510
/* * Copyright (C) 2007 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.opengles.spritetext; import android.opengl.Matrix; import java.nio.FloatBuffer; import java.nio.IntBuffer; /** * A matrix stack, similar to OpenGL ES's internal matrix stack. */ public class MatrixStack { public MatrixStack() { commonInit(DEFAULT_MAX_DEPTH); } public MatrixStack(int maxDepth) { commonInit(maxDepth); } private void commonInit(int maxDepth) { mMatrix = new float[maxDepth * MATRIX_SIZE]; mTemp = new float[MATRIX_SIZE * 2]; glLoadIdentity(); } public void glFrustumf(float left, float right, float bottom, float top, float near, float far) { Matrix.frustumM(mMatrix, mTop, left, right, bottom, top, near, far); } public void glFrustumx(int left, int right, int bottom, int top, int near, int far) { glFrustumf(fixedToFloat(left),fixedToFloat(right), fixedToFloat(bottom), fixedToFloat(top), fixedToFloat(near), fixedToFloat(far)); } public void glLoadIdentity() { Matrix.setIdentityM(mMatrix, mTop); } public void glLoadMatrixf(float[] m, int offset) { System.arraycopy(m, offset, mMatrix, mTop, MATRIX_SIZE); } public void glLoadMatrixf(FloatBuffer m) { m.get(mMatrix, mTop, MATRIX_SIZE); } public void glLoadMatrixx(int[] m, int offset) { for(int i = 0; i < MATRIX_SIZE; i++) { mMatrix[mTop + i] = fixedToFloat(m[offset + i]); } } public void glLoadMatrixx(IntBuffer m) { for(int i = 0; i < MATRIX_SIZE; i++) { mMatrix[mTop + i] = fixedToFloat(m.get()); } } public void glMultMatrixf(float[] m, int offset) { System.arraycopy(mMatrix, mTop, mTemp, 0, MATRIX_SIZE); Matrix.multiplyMM(mMatrix, mTop, mTemp, 0, m, offset); } public void glMultMatrixf(FloatBuffer m) { m.get(mTemp, MATRIX_SIZE, MATRIX_SIZE); glMultMatrixf(mTemp, MATRIX_SIZE); } public void glMultMatrixx(int[] m, int offset) { for(int i = 0; i < MATRIX_SIZE; i++) { mTemp[MATRIX_SIZE + i] = fixedToFloat(m[offset + i]); } glMultMatrixf(mTemp, MATRIX_SIZE); } public void glMultMatrixx(IntBuffer m) { for(int i = 0; i < MATRIX_SIZE; i++) { mTemp[MATRIX_SIZE + i] = fixedToFloat(m.get()); } glMultMatrixf(mTemp, MATRIX_SIZE); } public void glOrthof(float left, float right, float bottom, float top, float near, float far) { Matrix.orthoM(mMatrix, mTop, left, right, bottom, top, near, far); } public void glOrthox(int left, int right, int bottom, int top, int near, int far) { glOrthof(fixedToFloat(left), fixedToFloat(right), fixedToFloat(bottom), fixedToFloat(top), fixedToFloat(near), fixedToFloat(far)); } public void glPopMatrix() { preflight_adjust(-1); adjust(-1); } public void glPushMatrix() { preflight_adjust(1); System.arraycopy(mMatrix, mTop, mMatrix, mTop + MATRIX_SIZE, MATRIX_SIZE); adjust(1); } public void glRotatef(float angle, float x, float y, float z) { Matrix.setRotateM(mTemp, 0, angle, x, y, z); System.arraycopy(mMatrix, mTop, mTemp, MATRIX_SIZE, MATRIX_SIZE); Matrix.multiplyMM(mMatrix, mTop, mTemp, MATRIX_SIZE, mTemp, 0); } public void glRotatex(int angle, int x, int y, int z) { glRotatef(angle, fixedToFloat(x), fixedToFloat(y), fixedToFloat(z)); } public void glScalef(float x, float y, float z) { Matrix.scaleM(mMatrix, mTop, x, y, z); } public void glScalex(int x, int y, int z) { glScalef(fixedToFloat(x), fixedToFloat(y), fixedToFloat(z)); } public void glTranslatef(float x, float y, float z) { Matrix.translateM(mMatrix, mTop, x, y, z); } public void glTranslatex(int x, int y, int z) { glTranslatef(fixedToFloat(x), fixedToFloat(y), fixedToFloat(z)); } public void getMatrix(float[] dest, int offset) { System.arraycopy(mMatrix, mTop, dest, offset, MATRIX_SIZE); } private float fixedToFloat(int x) { return x * (1.0f / 65536.0f); } private void preflight_adjust(int dir) { int newTop = mTop + dir * MATRIX_SIZE; if (newTop < 0) { throw new IllegalArgumentException("stack underflow"); } if (newTop + MATRIX_SIZE > mMatrix.length) { throw new IllegalArgumentException("stack overflow"); } } private void adjust(int dir) { mTop += dir * MATRIX_SIZE; } private final static int DEFAULT_MAX_DEPTH = 32; private final static int MATRIX_SIZE = 16; private float[] mMatrix; private int mTop; private float[] mTemp; }
zzhangumd-apps-for-android
Samples/OpenGLES/SpriteText/src/com/google/android/opengles/spritetext/MatrixStack.java
Java
asf20
5,512
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.opengles.spritetext; import android.content.Context; import android.util.AttributeSet; import android.view.SurfaceHolder; import android.view.SurfaceView; import java.util.ArrayList; import java.util.concurrent.Semaphore; import javax.microedition.khronos.egl.EGL10; import javax.microedition.khronos.egl.EGL11; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.egl.EGLContext; import javax.microedition.khronos.egl.EGLDisplay; import javax.microedition.khronos.egl.EGLSurface; import javax.microedition.khronos.opengles.GL; import javax.microedition.khronos.opengles.GL10; /** * An implementation of SurfaceView that uses the dedicated surface for * displaying an OpenGL animation. This allows the animation to run in a * separate thread, without requiring that it be driven by the update mechanism * of the view hierarchy. * * The application-specific rendering code is delegated to a GLView.Renderer * instance. */ class GLView extends SurfaceView implements SurfaceHolder.Callback { GLView(Context context) { super(context); init(); } public GLView(Context context, AttributeSet attrs) { super(context, attrs); init(); } private void init() { // Install a SurfaceHolder.Callback so we get notified when the // underlying surface is created and destroyed mHolder = getHolder(); mHolder.addCallback(this); mHolder.setType(SurfaceHolder.SURFACE_TYPE_GPU); } public void setGLWrapper(GLWrapper glWrapper) { mGLWrapper = glWrapper; } public void setRenderer(Renderer renderer) { mGLThread = new GLThread(renderer); mGLThread.start(); } public void surfaceCreated(SurfaceHolder holder) { mGLThread.surfaceCreated(); } public void surfaceDestroyed(SurfaceHolder holder) { // Surface will be destroyed when we return mGLThread.surfaceDestroyed(); } public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { // Surface size or format has changed. This should not happen in this // example. mGLThread.onWindowResize(w, h); } /** * Inform the view that the activity is paused. */ public void onPause() { mGLThread.onPause(); } /** * Inform the view that the activity is resumed. */ public void onResume() { mGLThread.onResume(); } /** * Inform the view that the window focus has changed. */ @Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); mGLThread.onWindowFocusChanged(hasFocus); } /** * Queue an "event" to be run on the GL rendering thread. * @param r the runnable to be run on the GL rendering thread. */ public void queueEvent(Runnable r) { mGLThread.queueEvent(r); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); mGLThread.requestExitAndWait(); } // ---------------------------------------------------------------------- public interface GLWrapper { GL wrap(GL gl); } // ---------------------------------------------------------------------- /** * A generic renderer interface. */ public interface Renderer { /** * @return the EGL configuration specification desired by the renderer. */ int[] getConfigSpec(); /** * Surface created. * Called when the surface is created. Called when the application * starts, and whenever the GPU is reinitialized. This will * typically happen when the device awakes after going to sleep. * Set your textures here. */ void surfaceCreated(GL10 gl); /** * Surface changed size. * Called after the surface is created and whenever * the OpenGL ES surface size changes. Set your viewport here. * @param gl * @param width * @param height */ void sizeChanged(GL10 gl, int width, int height); /** * Draw the current frame. * @param gl */ void drawFrame(GL10 gl); } /** * An EGL helper class. */ private class EglHelper { public EglHelper() { } /** * Initialize EGL for a given configuration spec. * @param configSpec */ public void start(int[] configSpec){ /* * Get an EGL instance */ mEgl = (EGL10) EGLContext.getEGL(); /* * Get to the default display. */ mEglDisplay = mEgl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY); /* * We can now initialize EGL for that display */ int[] version = new int[2]; mEgl.eglInitialize(mEglDisplay, version); EGLConfig[] configs = new EGLConfig[1]; int[] num_config = new int[1]; mEgl.eglChooseConfig(mEglDisplay, configSpec, configs, 1, num_config); mEglConfig = configs[0]; /* * Create an OpenGL ES context. This must be done only once, an * OpenGL context is a somewhat heavy object. */ mEglContext = mEgl.eglCreateContext(mEglDisplay, mEglConfig, EGL10.EGL_NO_CONTEXT, null); mEglSurface = null; } /* * Create and return an OpenGL surface */ public GL createSurface(SurfaceHolder holder) { /* * The window size has changed, so we need to create a new * surface. */ if (mEglSurface != null) { /* * Unbind and destroy the old EGL surface, if * there is one. */ mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT); mEgl.eglDestroySurface(mEglDisplay, mEglSurface); } /* * Create an EGL surface we can render into. */ mEglSurface = mEgl.eglCreateWindowSurface(mEglDisplay, mEglConfig, holder, null); /* * Before we can issue GL commands, we need to make sure * the context is current and bound to a surface. */ mEgl.eglMakeCurrent(mEglDisplay, mEglSurface, mEglSurface, mEglContext); GL gl = mEglContext.getGL(); if (mGLWrapper != null) { gl = mGLWrapper.wrap(gl); } return gl; } /** * Display the current render surface. * @return false if the context has been lost. */ public boolean swap() { mEgl.eglSwapBuffers(mEglDisplay, mEglSurface); /* * Always check for EGL_CONTEXT_LOST, which means the context * and all associated data were lost (For instance because * the device went to sleep). We need to sleep until we * get a new surface. */ return mEgl.eglGetError() != EGL11.EGL_CONTEXT_LOST; } public void finish() { if (mEglSurface != null) { mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT); mEgl.eglDestroySurface(mEglDisplay, mEglSurface); mEglSurface = null; } if (mEglContext != null) { mEgl.eglDestroyContext(mEglDisplay, mEglContext); mEglContext = null; } if (mEglDisplay != null) { mEgl.eglTerminate(mEglDisplay); mEglDisplay = null; } } EGL10 mEgl; EGLDisplay mEglDisplay; EGLSurface mEglSurface; EGLConfig mEglConfig; EGLContext mEglContext; } /** * A generic GL Thread. Takes care of initializing EGL and GL. Delegates * to a Renderer instance to do the actual drawing. * */ class GLThread extends Thread { GLThread(Renderer renderer) { super(); mDone = false; mWidth = 0; mHeight = 0; mRenderer = renderer; setName("GLThread"); } @Override public void run() { /* * When the android framework launches a second instance of * an activity, the new instance's onCreate() method may be * called before the first instance returns from onDestroy(). * * This semaphore ensures that only one instance at a time * accesses EGL. */ try { try { sEglSemaphore.acquire(); } catch (InterruptedException e) { return; } guardedRun(); } catch (InterruptedException e) { // fall thru and exit normally } finally { sEglSemaphore.release(); } } private void guardedRun() throws InterruptedException { mEglHelper = new EglHelper(); /* * Specify a configuration for our opengl session * and grab the first configuration that matches is */ int[] configSpec = mRenderer.getConfigSpec(); mEglHelper.start(configSpec); GL10 gl = null; boolean tellRendererSurfaceCreated = true; boolean tellRendererSurfaceChanged = true; /* * This is our main activity thread's loop, we go until * asked to quit. */ while (!mDone) { /* * Update the asynchronous state (window size) */ int w, h; boolean changed; boolean needStart = false; synchronized (this) { Runnable r; while ((r = getEvent()) != null) { r.run(); } if (mPaused) { mEglHelper.finish(); needStart = true; } if(needToWait()) { while (needToWait()) { wait(); } } if (mDone) { break; } changed = mSizeChanged; w = mWidth; h = mHeight; mSizeChanged = false; } if (needStart) { mEglHelper.start(configSpec); tellRendererSurfaceCreated = true; changed = true; } if (changed) { gl = (GL10) mEglHelper.createSurface(mHolder); tellRendererSurfaceChanged = true; } if (tellRendererSurfaceCreated) { mRenderer.surfaceCreated(gl); tellRendererSurfaceCreated = false; } if (tellRendererSurfaceChanged) { mRenderer.sizeChanged(gl, w, h); tellRendererSurfaceChanged = false; } if ((w > 0) && (h > 0)) { /* draw a frame here */ mRenderer.drawFrame(gl); /* * Once we're done with GL, we need to call swapBuffers() * to instruct the system to display the rendered frame */ mEglHelper.swap(); } } /* * clean-up everything... */ mEglHelper.finish(); } private boolean needToWait() { return (mPaused || (! mHasFocus) || (! mHasSurface) || mContextLost) && (! mDone); } public void surfaceCreated() { synchronized(this) { mHasSurface = true; mContextLost = false; notify(); } } public void surfaceDestroyed() { synchronized(this) { mHasSurface = false; notify(); } } public void onPause() { synchronized (this) { mPaused = true; } } public void onResume() { synchronized (this) { mPaused = false; notify(); } } public void onWindowFocusChanged(boolean hasFocus) { synchronized (this) { mHasFocus = hasFocus; if (mHasFocus == true) { notify(); } } } public void onWindowResize(int w, int h) { synchronized (this) { mWidth = w; mHeight = h; mSizeChanged = true; } } public void requestExitAndWait() { // don't call this from GLThread thread or it is a guaranteed // deadlock! synchronized(this) { mDone = true; notify(); } try { join(); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } } /** * Queue an "event" to be run on the GL rendering thread. * @param r the runnable to be run on the GL rendering thread. */ public void queueEvent(Runnable r) { synchronized(this) { mEventQueue.add(r); } } private Runnable getEvent() { synchronized(this) { if (mEventQueue.size() > 0) { return mEventQueue.remove(0); } } return null; } private boolean mDone; private boolean mPaused; private boolean mHasFocus; private boolean mHasSurface; private boolean mContextLost; private int mWidth; private int mHeight; private Renderer mRenderer; private ArrayList<Runnable> mEventQueue = new ArrayList<Runnable>(); private EglHelper mEglHelper; } private static final Semaphore sEglSemaphore = new Semaphore(1); private boolean mSizeChanged = true; private SurfaceHolder mHolder; private GLThread mGLThread; private GLWrapper mGLWrapper; }
zzhangumd-apps-for-android
Samples/OpenGLES/SpriteText/src/com/google/android/opengles/spritetext/GLView.java
Java
asf20
15,729
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.opengles.spritetext; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import java.nio.ShortBuffer; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Paint; import android.opengl.GLU; import android.opengl.GLUtils; import android.os.SystemClock; import javax.microedition.khronos.egl.EGL10; import javax.microedition.khronos.opengles.GL10; public class SpriteTextRenderer implements GLView.Renderer{ public SpriteTextRenderer(Context context) { mContext = context; mTriangle = new Triangle(); mProjector = new Projector(); mLabelPaint = new Paint(); mLabelPaint.setTextSize(32); mLabelPaint.setAntiAlias(true); mLabelPaint.setARGB(0xff, 0x00, 0x00, 0x00); } public int[] getConfigSpec() { // We don't need a depth buffer, and don't care about our // color depth. int[] configSpec = { EGL10.EGL_DEPTH_SIZE, 0, EGL10.EGL_NONE }; return configSpec; } public void surfaceCreated(GL10 gl) { /* * By default, OpenGL enables features that improve quality * but reduce performance. One might want to tweak that * especially on software renderer. */ gl.glDisable(GL10.GL_DITHER); /* * Some one-time OpenGL initialization can be made here * probably based on features of this particular context */ gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_FASTEST); gl.glClearColor(.5f, .5f, .5f, 1); gl.glShadeModel(GL10.GL_SMOOTH); gl.glEnable(GL10.GL_DEPTH_TEST); gl.glEnable(GL10.GL_TEXTURE_2D); /* * Create our texture. This has to be done each time the * surface is created. */ int[] textures = new int[1]; gl.glGenTextures(1, textures, 0); mTextureID = textures[0]; gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureID); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_CLAMP_TO_EDGE); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_CLAMP_TO_EDGE); gl.glTexEnvf(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE, GL10.GL_REPLACE); InputStream is = mContext.getResources() .openRawResource(R.drawable.tex); Bitmap bitmap; try { bitmap = BitmapFactory.decodeStream(is); } finally { try { is.close(); } catch(IOException e) { // Ignore. } } GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0); bitmap.recycle(); if (mLabels != null) { mLabels.shutdown(gl); } else { mLabels = new LabelMaker(true, 256, 64); } mLabels.initialize(gl); mLabels.beginAdding(gl); mLabelA = mLabels.add(gl, "A", mLabelPaint); mLabelB = mLabels.add(gl, "B", mLabelPaint); mLabelC = mLabels.add(gl, "C", mLabelPaint); mLabelMsPF = mLabels.add(gl, "ms/f", mLabelPaint); mLabels.endAdding(gl); if (mNumericSprite != null) { mNumericSprite.shutdown(gl); } else { mNumericSprite = new NumericSprite(); } mNumericSprite.initialize(gl, mLabelPaint); } public void drawFrame(GL10 gl) { /* * By default, OpenGL enables features that improve quality * but reduce performance. One might want to tweak that * especially on software renderer. */ gl.glDisable(GL10.GL_DITHER); gl.glTexEnvx(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE, GL10.GL_MODULATE); /* * Usually, the first thing one might want to do is to clear * the screen. The most efficient way of doing this is to use * glClear(). */ gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); /* * Now we're ready to draw some 3D objects */ gl.glMatrixMode(GL10.GL_MODELVIEW); gl.glLoadIdentity(); GLU.gluLookAt(gl, 0.0f, 0.0f, -2.5f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f); gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY); gl.glActiveTexture(GL10.GL_TEXTURE0); gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureID); gl.glTexParameterx(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_REPEAT); gl.glTexParameterx(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_REPEAT); long time = SystemClock.uptimeMillis() % 4000L; float angle = 0.090f * ((int) time); gl.glRotatef(angle, 0, 0, 1.0f); gl.glScalef(2.0f, 2.0f, 2.0f); mTriangle.draw(gl); mProjector.getCurrentModelView(gl); mLabels.beginDrawing(gl, mWidth, mHeight); drawLabel(gl, 0, mLabelA); drawLabel(gl, 1, mLabelB); drawLabel(gl, 2, mLabelC); float msPFX = mWidth - mLabels.getWidth(mLabelMsPF) - 1; mLabels.draw(gl, msPFX, 0, mLabelMsPF); mLabels.endDrawing(gl); drawMsPF(gl, msPFX); } private void drawMsPF(GL10 gl, float rightMargin) { long time = SystemClock.uptimeMillis(); if (mStartTime == 0) { mStartTime = time; } if (mFrames++ == SAMPLE_PERIOD_FRAMES) { mFrames = 0; long delta = time - mStartTime; mStartTime = time; mMsPerFrame = (int) (delta * SAMPLE_FACTOR); } if (mMsPerFrame > 0) { mNumericSprite.setValue(mMsPerFrame); float numWidth = mNumericSprite.width(); float x = rightMargin - numWidth; mNumericSprite.draw(gl, x, 0, mWidth, mHeight); } } private void drawLabel(GL10 gl, int triangleVertex, int labelId) { float x = mTriangle.getX(triangleVertex); float y = mTriangle.getY(triangleVertex); mScratch[0] = x; mScratch[1] = y; mScratch[2] = 0.0f; mScratch[3] = 1.0f; mProjector.project(mScratch, 0, mScratch, 4); float sx = mScratch[4]; float sy = mScratch[5]; float height = mLabels.getHeight(labelId); float width = mLabels.getWidth(labelId); float tx = sx - width * 0.5f; float ty = sy - height * 0.5f; mLabels.draw(gl, tx, ty, labelId); } public void sizeChanged(GL10 gl, int w, int h) { mWidth = w; mHeight = h; gl.glViewport(0, 0, w, h); mProjector.setCurrentView(0, 0, w, h); /* * Set our projection matrix. This doesn't have to be done * each time we draw, but usually a new projection needs to * be set when the viewport is resized. */ float ratio = (float) w / h; gl.glMatrixMode(GL10.GL_PROJECTION); gl.glLoadIdentity(); gl.glFrustumf(-ratio, ratio, -1, 1, 1, 10); mProjector.getCurrentProjection(gl); } private int mWidth; private int mHeight; private Context mContext; private Triangle mTriangle; private int mTextureID; private int mFrames; private int mMsPerFrame; private final static int SAMPLE_PERIOD_FRAMES = 12; private final static float SAMPLE_FACTOR = 1.0f / SAMPLE_PERIOD_FRAMES; private long mStartTime; private LabelMaker mLabels; private Paint mLabelPaint; private int mLabelA; private int mLabelB; private int mLabelC; private int mLabelMsPF; private Projector mProjector; private NumericSprite mNumericSprite; private float[] mScratch = new float[8]; } class Triangle { public Triangle() { // Buffers to be passed to gl*Pointer() functions // must be direct, i.e., they must be placed on the // native heap where the garbage collector cannot // move them. // // Buffers with multi-byte datatypes (e.g., short, int, float) // must have their byte order set to native order ByteBuffer vbb = ByteBuffer.allocateDirect(VERTS * 3 * 4); vbb.order(ByteOrder.nativeOrder()); mFVertexBuffer = vbb.asFloatBuffer(); ByteBuffer tbb = ByteBuffer.allocateDirect(VERTS * 2 * 4); tbb.order(ByteOrder.nativeOrder()); mTexBuffer = tbb.asFloatBuffer(); ByteBuffer ibb = ByteBuffer.allocateDirect(VERTS * 2); ibb.order(ByteOrder.nativeOrder()); mIndexBuffer = ibb.asShortBuffer(); for (int i = 0; i < VERTS; i++) { for(int j = 0; j < 3; j++) { mFVertexBuffer.put(sCoords[i*3+j]); } } for (int i = 0; i < VERTS; i++) { for(int j = 0; j < 2; j++) { mTexBuffer.put(sCoords[i*3+j] * 2.0f + 0.5f); } } for(int i = 0; i < VERTS; i++) { mIndexBuffer.put((short) i); } mFVertexBuffer.position(0); mTexBuffer.position(0); mIndexBuffer.position(0); } public void draw(GL10 gl) { gl.glFrontFace(GL10.GL_CCW); gl.glVertexPointer(3, GL10.GL_FLOAT, 0, mFVertexBuffer); gl.glEnable(GL10.GL_TEXTURE_2D); gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, mTexBuffer); gl.glDrawElements(GL10.GL_TRIANGLE_STRIP, VERTS, GL10.GL_UNSIGNED_SHORT, mIndexBuffer); } public float getX(int vertex) { return sCoords[3*vertex]; } public float getY(int vertex) { return sCoords[3*vertex+1]; } private final static int VERTS = 3; private FloatBuffer mFVertexBuffer; private FloatBuffer mTexBuffer; private ShortBuffer mIndexBuffer; // A unit-sided equalateral triangle centered on the origin. private final static float[] sCoords = { // X, Y, Z -0.5f, -0.25f, 0, 0.5f, -0.25f, 0, 0.0f, 0.559016994f, 0 }; }
zzhangumd-apps-for-android
Samples/OpenGLES/SpriteText/src/com/google/android/opengles/spritetext/SpriteTextRenderer.java
Java
asf20
11,162
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.opengles.triangle; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import java.nio.ShortBuffer; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.opengl.GLU; import android.opengl.GLUtils; import android.os.SystemClock; import javax.microedition.khronos.egl.EGL10; import javax.microedition.khronos.opengles.GL10; public class TriangleRenderer implements GLView.Renderer{ public TriangleRenderer(Context context) { mContext = context; mTriangle = new Triangle(); } public int[] getConfigSpec() { // We don't need a depth buffer, and don't care about our // color depth. int[] configSpec = { EGL10.EGL_DEPTH_SIZE, 0, EGL10.EGL_NONE }; return configSpec; } public void surfaceCreated(GL10 gl) { /* * By default, OpenGL enables features that improve quality * but reduce performance. One might want to tweak that * especially on software renderer. */ gl.glDisable(GL10.GL_DITHER); /* * Some one-time OpenGL initialization can be made here * probably based on features of this particular context */ gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_FASTEST); gl.glClearColor(.5f, .5f, .5f, 1); gl.glShadeModel(GL10.GL_SMOOTH); gl.glEnable(GL10.GL_DEPTH_TEST); gl.glEnable(GL10.GL_TEXTURE_2D); /* * Create our texture. This has to be done each time the * surface is created. */ int[] textures = new int[1]; gl.glGenTextures(1, textures, 0); mTextureID = textures[0]; gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureID); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_CLAMP_TO_EDGE); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_CLAMP_TO_EDGE); gl.glTexEnvf(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE, GL10.GL_REPLACE); InputStream is = mContext.getResources() .openRawResource(R.drawable.tex); Bitmap bitmap; try { bitmap = BitmapFactory.decodeStream(is); } finally { try { is.close(); } catch(IOException e) { // Ignore. } } GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0); bitmap.recycle(); } public void drawFrame(GL10 gl) { /* * By default, OpenGL enables features that improve quality * but reduce performance. One might want to tweak that * especially on software renderer. */ gl.glDisable(GL10.GL_DITHER); gl.glTexEnvx(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE, GL10.GL_MODULATE); /* * Usually, the first thing one might want to do is to clear * the screen. The most efficient way of doing this is to use * glClear(). */ gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); /* * Now we're ready to draw some 3D objects */ gl.glMatrixMode(GL10.GL_MODELVIEW); gl.glLoadIdentity(); GLU.gluLookAt(gl, 0, 0, -5, 0f, 0f, 0f, 0f, 1.0f, 0.0f); gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY); gl.glActiveTexture(GL10.GL_TEXTURE0); gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureID); gl.glTexParameterx(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_REPEAT); gl.glTexParameterx(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_REPEAT); long time = SystemClock.uptimeMillis() % 4000L; float angle = 0.090f * ((int) time); gl.glRotatef(angle, 0, 0, 1.0f); mTriangle.draw(gl); } public void sizeChanged(GL10 gl, int w, int h) { gl.glViewport(0, 0, w, h); /* * Set our projection matrix. This doesn't have to be done * each time we draw, but usually a new projection needs to * be set when the viewport is resized. */ float ratio = (float) w / h; gl.glMatrixMode(GL10.GL_PROJECTION); gl.glLoadIdentity(); gl.glFrustumf(-ratio, ratio, -1, 1, 3, 7); } private Context mContext; private Triangle mTriangle; private int mTextureID; } class Triangle { public Triangle() { // Buffers to be passed to gl*Pointer() functions // must be direct, i.e., they must be placed on the // native heap where the garbage collector cannot // move them. // // Buffers with multi-byte datatypes (e.g., short, int, float) // must have their byte order set to native order ByteBuffer vbb = ByteBuffer.allocateDirect(VERTS * 3 * 4); vbb.order(ByteOrder.nativeOrder()); mFVertexBuffer = vbb.asFloatBuffer(); ByteBuffer tbb = ByteBuffer.allocateDirect(VERTS * 2 * 4); tbb.order(ByteOrder.nativeOrder()); mTexBuffer = tbb.asFloatBuffer(); ByteBuffer ibb = ByteBuffer.allocateDirect(VERTS * 2); ibb.order(ByteOrder.nativeOrder()); mIndexBuffer = ibb.asShortBuffer(); // A unit-sided equalateral triangle centered on the origin. float[] coords = { // X, Y, Z -0.5f, -0.25f, 0, 0.5f, -0.25f, 0, 0.0f, 0.559016994f, 0 }; for (int i = 0; i < VERTS; i++) { for(int j = 0; j < 3; j++) { mFVertexBuffer.put(coords[i*3+j] * 2.0f); } } for (int i = 0; i < VERTS; i++) { for(int j = 0; j < 2; j++) { mTexBuffer.put(coords[i*3+j] * 2.0f + 0.5f); } } for(int i = 0; i < VERTS; i++) { mIndexBuffer.put((short) i); } mFVertexBuffer.position(0); mTexBuffer.position(0); mIndexBuffer.position(0); } public void draw(GL10 gl) { gl.glFrontFace(GL10.GL_CCW); gl.glVertexPointer(3, GL10.GL_FLOAT, 0, mFVertexBuffer); gl.glEnable(GL10.GL_TEXTURE_2D); gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, mTexBuffer); gl.glDrawElements(GL10.GL_TRIANGLE_STRIP, VERTS, GL10.GL_UNSIGNED_SHORT, mIndexBuffer); } private final static int VERTS = 3; private FloatBuffer mFVertexBuffer; private FloatBuffer mTexBuffer; private ShortBuffer mIndexBuffer; }
zzhangumd-apps-for-android
Samples/OpenGLES/Triangle/src/com/google/android/opengles/triangle/TriangleRenderer.java
Java
asf20
7,690
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.opengles.triangle; import javax.microedition.khronos.opengles.GL; import android.app.Activity; import android.opengl.GLDebugHelper; import android.os.Bundle; public class TriangleActivity extends Activity { /** Set to true to enable checking of the OpenGL error code after every OpenGL call. Set to * false for faster code. * */ private final static boolean DEBUG_CHECK_GL_ERROR = true; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mGLView = (GLView) findViewById(R.id.glview); if (DEBUG_CHECK_GL_ERROR) { mGLView.setGLWrapper(new GLView.GLWrapper() { public GL wrap(GL gl) { return GLDebugHelper.wrap(gl, GLDebugHelper.CONFIG_CHECK_GL_ERROR, null); }}); } mGLView.setRenderer(new TriangleRenderer(this)); mGLView.requestFocus(); } @Override protected void onPause() { super.onPause(); mGLView.onPause(); } @Override protected void onResume() { super.onResume(); mGLView.onResume(); } private GLView mGLView; }
zzhangumd-apps-for-android
Samples/OpenGLES/Triangle/src/com/google/android/opengles/triangle/TriangleActivity.java
Java
asf20
1,848
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.opengles.triangle; import android.content.Context; import android.util.AttributeSet; import android.view.SurfaceHolder; import android.view.SurfaceView; import java.util.ArrayList; import java.util.concurrent.Semaphore; import javax.microedition.khronos.egl.EGL10; import javax.microedition.khronos.egl.EGL11; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.egl.EGLContext; import javax.microedition.khronos.egl.EGLDisplay; import javax.microedition.khronos.egl.EGLSurface; import javax.microedition.khronos.opengles.GL; import javax.microedition.khronos.opengles.GL10; /** * An implementation of SurfaceView that uses the dedicated surface for * displaying an OpenGL animation. This allows the animation to run in a * separate thread, without requiring that it be driven by the update mechanism * of the view hierarchy. * * The application-specific rendering code is delegated to a GLView.Renderer * instance. */ class GLView extends SurfaceView implements SurfaceHolder.Callback { GLView(Context context) { super(context); init(); } public GLView(Context context, AttributeSet attrs) { super(context, attrs); init(); } private void init() { // Install a SurfaceHolder.Callback so we get notified when the // underlying surface is created and destroyed mHolder = getHolder(); mHolder.addCallback(this); mHolder.setType(SurfaceHolder.SURFACE_TYPE_GPU); } public void setGLWrapper(GLWrapper glWrapper) { mGLWrapper = glWrapper; } public void setRenderer(Renderer renderer) { mGLThread = new GLThread(renderer); mGLThread.start(); } public void surfaceCreated(SurfaceHolder holder) { mGLThread.surfaceCreated(); } public void surfaceDestroyed(SurfaceHolder holder) { // Surface will be destroyed when we return mGLThread.surfaceDestroyed(); } public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { // Surface size or format has changed. This should not happen in this // example. mGLThread.onWindowResize(w, h); } /** * Inform the view that the activity is paused. */ public void onPause() { mGLThread.onPause(); } /** * Inform the view that the activity is resumed. */ public void onResume() { mGLThread.onResume(); } /** * Inform the view that the window focus has changed. */ @Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); mGLThread.onWindowFocusChanged(hasFocus); } /** * Queue an "event" to be run on the GL rendering thread. * @param r the runnable to be run on the GL rendering thread. */ public void queueEvent(Runnable r) { mGLThread.queueEvent(r); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); mGLThread.requestExitAndWait(); } // ---------------------------------------------------------------------- public interface GLWrapper { GL wrap(GL gl); } // ---------------------------------------------------------------------- /** * A generic renderer interface. */ public interface Renderer { /** * @return the EGL configuration specification desired by the renderer. */ int[] getConfigSpec(); /** * Surface created. * Called when the surface is created. Called when the application * starts, and whenever the GPU is reinitialized. This will * typically happen when the device awakes after going to sleep. * Set your textures here. */ void surfaceCreated(GL10 gl); /** * Surface changed size. * Called after the surface is created and whenever * the OpenGL ES surface size changes. Set your viewport here. * @param gl * @param width * @param height */ void sizeChanged(GL10 gl, int width, int height); /** * Draw the current frame. * @param gl */ void drawFrame(GL10 gl); } /** * An EGL helper class. */ private class EglHelper { public EglHelper() { } /** * Initialize EGL for a given configuration spec. * @param configSpec */ public void start(int[] configSpec){ /* * Get an EGL instance */ mEgl = (EGL10) EGLContext.getEGL(); /* * Get to the default display. */ mEglDisplay = mEgl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY); /* * We can now initialize EGL for that display */ int[] version = new int[2]; mEgl.eglInitialize(mEglDisplay, version); EGLConfig[] configs = new EGLConfig[1]; int[] num_config = new int[1]; mEgl.eglChooseConfig(mEglDisplay, configSpec, configs, 1, num_config); mEglConfig = configs[0]; /* * Create an OpenGL ES context. This must be done only once, an * OpenGL context is a somewhat heavy object. */ mEglContext = mEgl.eglCreateContext(mEglDisplay, mEglConfig, EGL10.EGL_NO_CONTEXT, null); mEglSurface = null; } /* * Create and return an OpenGL surface */ public GL createSurface(SurfaceHolder holder) { /* * The window size has changed, so we need to create a new * surface. */ if (mEglSurface != null) { /* * Unbind and destroy the old EGL surface, if * there is one. */ mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT); mEgl.eglDestroySurface(mEglDisplay, mEglSurface); } /* * Create an EGL surface we can render into. */ mEglSurface = mEgl.eglCreateWindowSurface(mEglDisplay, mEglConfig, holder, null); /* * Before we can issue GL commands, we need to make sure * the context is current and bound to a surface. */ mEgl.eglMakeCurrent(mEglDisplay, mEglSurface, mEglSurface, mEglContext); GL gl = mEglContext.getGL(); if (mGLWrapper != null) { gl = mGLWrapper.wrap(gl); } return gl; } /** * Display the current render surface. * @return false if the context has been lost. */ public boolean swap() { mEgl.eglSwapBuffers(mEglDisplay, mEglSurface); /* * Always check for EGL_CONTEXT_LOST, which means the context * and all associated data were lost (For instance because * the device went to sleep). We need to sleep until we * get a new surface. */ return mEgl.eglGetError() != EGL11.EGL_CONTEXT_LOST; } public void finish() { if (mEglSurface != null) { mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT); mEgl.eglDestroySurface(mEglDisplay, mEglSurface); mEglSurface = null; } if (mEglContext != null) { mEgl.eglDestroyContext(mEglDisplay, mEglContext); mEglContext = null; } if (mEglDisplay != null) { mEgl.eglTerminate(mEglDisplay); mEglDisplay = null; } } EGL10 mEgl; EGLDisplay mEglDisplay; EGLSurface mEglSurface; EGLConfig mEglConfig; EGLContext mEglContext; } /** * A generic GL Thread. Takes care of initializing EGL and GL. Delegates * to a Renderer instance to do the actual drawing. * */ class GLThread extends Thread { GLThread(Renderer renderer) { super(); mDone = false; mWidth = 0; mHeight = 0; mRenderer = renderer; setName("GLThread"); } @Override public void run() { /* * When the android framework launches a second instance of * an activity, the new instance's onCreate() method may be * called before the first instance returns from onDestroy(). * * This semaphore ensures that only one instance at a time * accesses EGL. */ try { try { sEglSemaphore.acquire(); } catch (InterruptedException e) { return; } guardedRun(); } catch (InterruptedException e) { // fall thru and exit normally } finally { sEglSemaphore.release(); } } private void guardedRun() throws InterruptedException { mEglHelper = new EglHelper(); /* * Specify a configuration for our opengl session * and grab the first configuration that matches is */ int[] configSpec = mRenderer.getConfigSpec(); mEglHelper.start(configSpec); GL10 gl = null; boolean tellRendererSurfaceCreated = true; boolean tellRendererSurfaceChanged = true; /* * This is our main activity thread's loop, we go until * asked to quit. */ while (!mDone) { /* * Update the asynchronous state (window size) */ int w, h; boolean changed; boolean needStart = false; synchronized (this) { Runnable r; while ((r = getEvent()) != null) { r.run(); } if (mPaused) { mEglHelper.finish(); needStart = true; } if(needToWait()) { while (needToWait()) { wait(); } } if (mDone) { break; } changed = mSizeChanged; w = mWidth; h = mHeight; mSizeChanged = false; } if (needStart) { mEglHelper.start(configSpec); tellRendererSurfaceCreated = true; changed = true; } if (changed) { gl = (GL10) mEglHelper.createSurface(mHolder); tellRendererSurfaceChanged = true; } if (tellRendererSurfaceCreated) { mRenderer.surfaceCreated(gl); tellRendererSurfaceCreated = false; } if (tellRendererSurfaceChanged) { mRenderer.sizeChanged(gl, w, h); tellRendererSurfaceChanged = false; } if ((w > 0) && (h > 0)) { /* draw a frame here */ mRenderer.drawFrame(gl); /* * Once we're done with GL, we need to call swapBuffers() * to instruct the system to display the rendered frame */ mEglHelper.swap(); } } /* * clean-up everything... */ mEglHelper.finish(); } private boolean needToWait() { return (mPaused || (! mHasFocus) || (! mHasSurface) || mContextLost) && (! mDone); } public void surfaceCreated() { synchronized(this) { mHasSurface = true; mContextLost = false; notify(); } } public void surfaceDestroyed() { synchronized(this) { mHasSurface = false; notify(); } } public void onPause() { synchronized (this) { mPaused = true; } } public void onResume() { synchronized (this) { mPaused = false; notify(); } } public void onWindowFocusChanged(boolean hasFocus) { synchronized (this) { mHasFocus = hasFocus; if (mHasFocus == true) { notify(); } } } public void onWindowResize(int w, int h) { synchronized (this) { mWidth = w; mHeight = h; mSizeChanged = true; } } public void requestExitAndWait() { // don't call this from GLThread thread or it is a guaranteed // deadlock! synchronized(this) { mDone = true; notify(); } try { join(); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } } /** * Queue an "event" to be run on the GL rendering thread. * @param r the runnable to be run on the GL rendering thread. */ public void queueEvent(Runnable r) { synchronized(this) { mEventQueue.add(r); } } private Runnable getEvent() { synchronized(this) { if (mEventQueue.size() > 0) { return mEventQueue.remove(0); } } return null; } private boolean mDone; private boolean mPaused; private boolean mHasFocus; private boolean mHasSurface; private boolean mContextLost; private int mWidth; private int mHeight; private Renderer mRenderer; private ArrayList<Runnable> mEventQueue = new ArrayList<Runnable>(); private EglHelper mEglHelper; } private static final Semaphore sEglSemaphore = new Semaphore(1); private boolean mSizeChanged = true; private SurfaceHolder mHolder; private GLThread mGLThread; private GLWrapper mGLWrapper; }
zzhangumd-apps-for-android
Samples/OpenGLES/Triangle/src/com/google/android/opengles/triangle/GLView.java
Java
asf20
15,727
package com.google.android.webviewdemo; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.webkit.JsResult; import android.webkit.WebChromeClient; import android.webkit.WebSettings; import android.webkit.WebView; /** * Demonstrates how to embed a WebView in your activity. Also demonstrates how * to have javascript in the WebView call into the activity, and how the activity * can invoke javascript. * <p> * In this example, clicking on the android in the WebView will result in a call into * the activities code in {@link DemoJavaScriptInterface#clickOnAndroid()}. This code * will turn around and invoke javascript using the {@link WebView#loadUrl(String)} * method. * <p> * Obviously all of this could have been accomplished without calling into the activity * and then back into javascript, but this code is intended to show how to set up the * code paths for this sort of communication. * */ public class WebViewDemo extends Activity { private static final String LOG_TAG = "WebViewDemo"; private WebView mWebView; private Handler mHandler = new Handler(); @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); mWebView = (WebView) findViewById(R.id.webview); WebSettings webSettings = mWebView.getSettings(); webSettings.setSavePassword(false); webSettings.setSaveFormData(false); webSettings.setJavaScriptEnabled(true); webSettings.setSupportZoom(false); mWebView.setWebChromeClient(new MyWebChromeClient()); mWebView.addJavascriptInterface(new DemoJavaScriptInterface(), "demo"); mWebView.loadUrl("file:///android_asset/demo.html"); } final class DemoJavaScriptInterface { DemoJavaScriptInterface() { } /** * This is not called on the UI thread. Post a runnable to invoke * loadUrl on the UI thread. */ public void clickOnAndroid() { mHandler.post(new Runnable() { public void run() { mWebView.loadUrl("javascript:wave()"); } }); } } /** * Provides a hook for calling "alert" from javascript. Useful for * debugging your javascript. */ final class MyWebChromeClient extends WebChromeClient { @Override public boolean onJsAlert(WebView view, String url, String message, JsResult result) { Log.d(LOG_TAG, message); result.confirm(); return true; } } }
zzhangumd-apps-for-android
Samples/WebViewDemo/src/com/google/android/webviewdemo/WebViewDemo.java
Java
asf20
2,659
<html> <script language="javascript"> /* This function is invoked by the activity */ function wave() { alert("1"); document.getElementById("droid").src="android_waving.png"; alert("2"); } </script> <body> <!-- Calls into the javascript interface for the activity --> <a onClick="window.demo.clickOnAndroid()"><div style="width:80px; margin:0px auto; padding:10px; text-align:center; border:2px solid #202020;" > <img id="droid" src="android_normal.png"/><br> Click me! </div></a> </body> </html>
zzhangumd-apps-for-android
Samples/WebViewDemo/assets/demo.html
HTML
asf20
552