code
stringlengths
3
1.18M
language
stringclasses
1 value
/* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.heightmapprofiler; import android.opengl.GLSurfaceView; import com.android.heightmapprofiler.SimpleGLRenderer; import com.android.heightmapprofiler.R; import android.app.Activity; import android.content.SharedPreferences; import android.graphics.Bitmap; import android.graphics.drawable.BitmapDrawable; import android.os.Bundle; import android.preference.PreferenceManager; import android.view.KeyEvent; import android.view.MotionEvent; // The main entry point for the actual landscape rendering test. // This class pulls options from the preferences set in the MainMenu // activity and builds the landscape accordingly. public class HeightMapTest extends Activity { private GLSurfaceView mGLSurfaceView; private SimpleGLRenderer mSimpleRenderer; private Game mGame; private Thread mGameThread; private float mLastScreenX; private float mLastScreenY; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); mGLSurfaceView = new GLSurfaceView(this); mGLSurfaceView.setEGLConfigChooser(true); mSimpleRenderer = new SimpleGLRenderer(this); SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this); final boolean runGame = prefs.getBoolean("runsim", true); final boolean bigWorld = prefs.getBoolean("bigworld", true); final boolean skybox = prefs.getBoolean("skybox", true); final boolean texture = prefs.getBoolean("texture", true); final boolean vertexColors = prefs.getBoolean("colors", true); final boolean useTextureLods = prefs.getBoolean("lodTexture", true); final boolean textureMips = prefs.getBoolean("textureMips", true); final boolean useColorTextureLods = prefs.getBoolean("lodTextureColored", false ); final int maxTextureSize = Integer.parseInt(prefs.getString("maxTextureSize", "512")); final String textureFilter = prefs.getString("textureFiltering", "bilinear"); final boolean useLods = prefs.getBoolean("lod", true); final int complexity = Integer.parseInt(prefs.getString("complexity", "24")); final boolean useFixedPoint = prefs.getBoolean("fixed", false); final boolean useVbos = prefs.getBoolean("vbo", true); final boolean useNdk = prefs.getBoolean("ndk", false); BitmapDrawable heightMapDrawable = (BitmapDrawable)getResources().getDrawable(R.drawable.heightmap); Bitmap heightmap = heightMapDrawable.getBitmap(); Bitmap lightmap = null; if (vertexColors != false) { BitmapDrawable lightMapDrawable = (BitmapDrawable)getResources().getDrawable(R.drawable.lightmap); lightmap = lightMapDrawable.getBitmap(); } LandTileMap tileMap = null; if (bigWorld) { final int tilesX = 4; final int tilesY = 4; tileMap = new LandTileMap(tilesX, tilesY, heightmap, lightmap, vertexColors, texture, useLods, complexity, useFixedPoint); } else { tileMap = new LandTileMap(1, 1, heightmap, lightmap, vertexColors, texture, useLods, complexity, useFixedPoint); } if (skybox) { BitmapDrawable skyboxDrawable = (BitmapDrawable)getResources().getDrawable(R.drawable.skybox); Bitmap skyboxBitmap = skyboxDrawable.getBitmap(); tileMap.setupSkybox(skyboxBitmap, useFixedPoint); } if (useNdk) { NativeRenderer renderer = new NativeRenderer(); tileMap.setNativeRenderer(renderer); mSimpleRenderer.setNativeRenderer(renderer); } ProfileRecorder.sSingleton.resetAll(); mSimpleRenderer.setUseHardwareBuffers(useVbos); if (texture) { mSimpleRenderer.setTiles(tileMap, R.drawable.road_texture, R.drawable.skybox_texture); mSimpleRenderer.setUseTextureLods( useTextureLods, textureMips ); mSimpleRenderer.setColorTextureLods( useColorTextureLods ); mSimpleRenderer.setMaxTextureSize(maxTextureSize); if (textureFilter == "nearest") { mSimpleRenderer.setTextureFilter(SimpleGLRenderer.FILTER_NEAREST_NEIGHBOR); } else if (textureFilter == "trilinear") { mSimpleRenderer.setTextureFilter(SimpleGLRenderer.FILTER_TRILINEAR); } else { mSimpleRenderer.setTextureFilter(SimpleGLRenderer.FILTER_BILINEAR); } } else { mSimpleRenderer.setTiles(tileMap, 0, 0); } mGLSurfaceView.setRenderer(mSimpleRenderer); setContentView(mGLSurfaceView); if (runGame) { mGame = new Game(mSimpleRenderer, tileMap); mGameThread = new Thread(mGame); mGameThread.start(); } } @Override protected void onPause() { super.onPause(); mGLSurfaceView.onPause(); if (mGame != null) { mGame.pause(); } } @Override protected void onResume() { super.onResume(); mGLSurfaceView.onResume(); if (mGame != null) { mGame.resume(); } } @Override public boolean onTrackballEvent(MotionEvent event) { if (mGame != null) { mGame.rotate(event.getRawX(), -event.getRawY()); } return true; } @Override public boolean onTouchEvent(MotionEvent event) { if (mGame != null) { if (event.getAction() == MotionEvent.ACTION_DOWN) { mGame.move(1.0f); } else if (event.getAction() == MotionEvent.ACTION_MOVE) { float xDelta = event.getX() - mLastScreenX; float yDelta = event.getY() - mLastScreenY; mGame.move(1.0f); // Scale the values we got down to make control usable. // A real game would probably figure out scale factors based // on the size of the screen rather than hard-coded constants // like this. mGame.rotate(xDelta * 0.01f, -yDelta * 0.005f); } } mLastScreenX = event.getX(); mLastScreenY = event.getY(); try { Thread.sleep(16); } catch (InterruptedException e) { // TODO Auto-generated catch block } return true; } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (mGame != null) { final float speed = 1.0f; switch (keyCode) { case KeyEvent.KEYCODE_DPAD_DOWN: mGame.rotate(0.0f, -speed); return true; case KeyEvent.KEYCODE_DPAD_LEFT: mGame.rotate(-speed, 0.0f); return true; case KeyEvent.KEYCODE_DPAD_RIGHT: mGame.rotate(speed, 0.0f); return true; case KeyEvent.KEYCODE_DPAD_UP: mGame.rotate(0.0f, speed); return true; } } return super.onKeyDown(keyCode, event); } }
Java
/* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.heightmapprofiler; import java.io.IOException; import java.io.InputStream; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.opengles.GL10; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import android.opengl.GLSurfaceView; import android.opengl.GLU; import android.opengl.GLUtils; import android.util.Log; /** * An OpenGL ES renderer based on the GLSurfaceView rendering framework. This * class is responsible for drawing a list of renderables to the screen every * frame. It also manages loading of textures and (when VBOs are used) the * allocation of vertex buffer objects. */ public class SimpleGLRenderer implements GLSurfaceView.Renderer { // Texture filtering modes. public final static int FILTER_NEAREST_NEIGHBOR = 0; public final static int FILTER_BILINEAR = 1; public final static int FILTER_TRILINEAR = 2; // Specifies the format our textures should be converted to upon load. private static BitmapFactory.Options sBitmapOptions = new BitmapFactory.Options(); // Pre-allocated arrays to use at runtime so that allocation during the // test can be avoided. private int[] mTextureNameWorkspace; // A reference to the application context. private Context mContext; private LandTileMap mTiles; private int mTextureResource; private int mTextureResource2; private int mTextureId2; private Vector3 mCameraPosition = new Vector3(); private Vector3 mLookAtPosition = new Vector3(); private Object mCameraLock = new Object(); private boolean mCameraDirty; private NativeRenderer mNativeRenderer; // Determines the use of vertex buffer objects. private boolean mUseHardwareBuffers; private boolean mUseTextureLods = false; private boolean mUseHardwareMips = false; boolean mColorTextureLods = false; private int mTextureFilter = FILTER_BILINEAR; private int mMaxTextureSize = 0; public SimpleGLRenderer(Context context) { // Pre-allocate and store these objects so we can use them at runtime // without allocating memory mid-frame. mTextureNameWorkspace = new int[1]; // Set our bitmaps to 16-bit, 565 format. sBitmapOptions.inPreferredConfig = Bitmap.Config.RGB_565; mContext = context; mUseHardwareBuffers = true; } public void setTiles(LandTileMap tiles, int textureResource, int textureResource2) { mTextureResource = textureResource; mTextureResource2 = textureResource2; mTiles = tiles; } /** Draws the landscape. */ public void onDrawFrame(GL10 gl) { ProfileRecorder.sSingleton.stop(ProfileRecorder.PROFILE_FRAME); ProfileRecorder.sSingleton.start(ProfileRecorder.PROFILE_FRAME); if (mTiles != null) { // Clear the screen. Note that a real application probably would only clear the depth buffer // (or maybe not even that). if (mNativeRenderer == null) { gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); } // If the camera has moved since the last frame, rebuild our projection matrix. if (mCameraDirty){ synchronized (mCameraLock) { if (mNativeRenderer != null) { mNativeRenderer.setCamera(mCameraPosition, mLookAtPosition); } else { gl.glMatrixMode(GL10.GL_MODELVIEW); gl.glLoadIdentity(); GLU.gluLookAt(gl, mCameraPosition.x, mCameraPosition.y, mCameraPosition.z, mLookAtPosition.x, mLookAtPosition.y, mLookAtPosition.z, 0.0f, 1.0f, 0.0f); } mCameraDirty = false; } } ProfileRecorder.sSingleton.start(ProfileRecorder.PROFILE_DRAW); // Draw the landscape. mTiles.draw(gl, mCameraPosition); ProfileRecorder.sSingleton.stop(ProfileRecorder.PROFILE_DRAW); } ProfileRecorder.sSingleton.endFrame(); } /* Called when the size of the window changes. */ public void onSurfaceChanged(GL10 gl, int width, int height) { gl.glViewport(0, 0, width, height); /* * Set our projection matrix. This doesn't have to be done each time we * draw, but usually a new projection needs to be set when the viewport * is resized. */ float ratio = (float)width / height; gl.glMatrixMode(GL10.GL_PROJECTION); gl.glLoadIdentity(); GLU.gluPerspective(gl, 60.0f, ratio, 2.0f, 3000.0f); mCameraDirty = true; } public void setCameraPosition(float x, float y, float z) { synchronized (mCameraLock) { mCameraPosition.set(x, y, z); mCameraDirty = true; } } public void setCameraLookAtPosition(float x, float y, float z) { synchronized (mCameraLock) { mLookAtPosition.set(x, y, z); mCameraDirty = true; } } public void setUseHardwareBuffers(boolean vbos) { mUseHardwareBuffers = vbos; } /** * Called to turn on Levels of Detail option for rendering textures * * @param mUseTextureLods */ public void setUseTextureLods(boolean useTextureLods, boolean useHardwareMips) { mUseTextureLods = useTextureLods; mUseHardwareMips = useHardwareMips; } /** * Turns on/off color the LOD bitmap textures based on their distance from view. * This feature is useful since it helps visualize the LOD being used while viewing the scene. * * @param colorTextureLods */ public void setColorTextureLods(boolean colorTextureLods) { this.mColorTextureLods = colorTextureLods; } public void setNativeRenderer(NativeRenderer render) { mNativeRenderer = render; } public void setMaxTextureSize(int maxTextureSize) { mMaxTextureSize = maxTextureSize; } public void setTextureFilter(int filter) { mTextureFilter = filter; } /** * Called whenever the surface is created. This happens at startup, and * may be called again at runtime if the device context is lost (the screen * goes to sleep, etc). This function must fill the contents of vram with * texture data and (when using VBOs) hardware vertex arrays. */ public void onSurfaceCreated(GL10 gl, EGLConfig config) { int[] textureNames = null; /* * Some one-time OpenGL initialization can be made here probably based * on features of this particular context */ gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_FASTEST); gl.glClearColor(0.5f, 0.5f, 0.5f, 1); gl.glDisable(GL10.GL_DITHER); gl.glDisable(GL10.GL_CULL_FACE); gl.glShadeModel(GL10.GL_SMOOTH); gl.glEnable(GL10.GL_DEPTH_TEST); gl.glEnable(GL10.GL_TEXTURE_2D); // set up some fog. gl.glEnable(GL10.GL_FOG); gl.glFogf(GL10.GL_FOG_MODE, GL10.GL_LINEAR); float fogColor[] = { 0.5f, 0.5f, 0.5f, 1.0f }; gl.glFogfv(GL10.GL_FOG_COLOR, fogColor, 0); gl.glFogf(GL10.GL_FOG_DENSITY, 0.15f); gl.glFogf(GL10.GL_FOG_START, 800.0f); gl.glFogf(GL10.GL_FOG_END, 2048.0f); gl.glHint(GL10.GL_FOG_HINT, GL10.GL_FASTEST); gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); // load textures and buffers here if (mUseHardwareBuffers && mTiles != null) { mTiles.generateHardwareBuffers(gl); } if (mTextureResource != 0) { textureNames = loadBitmap( mContext, gl, mTextureResource, mUseTextureLods, mUseHardwareMips ); } if (mTextureResource2 != 0) { mTextureId2 = loadBitmap(mContext, gl, mTextureResource2); } mTiles.setTextures(textureNames, mTextureId2); } /** * Loads a bitmap into OpenGL and sets up the common parameters for * 2D texture maps. */ protected int loadBitmap(Context context, GL10 gl, int resourceId) { int textureName = -1; InputStream is = context.getResources().openRawResource(resourceId); Bitmap bitmap; try { bitmap = BitmapFactory.decodeStream(is, null, sBitmapOptions); } finally { try { is.close(); } catch (IOException e) { // Ignore. } } if (mMaxTextureSize > 0 && Math.max(bitmap.getWidth(), bitmap.getHeight()) != mMaxTextureSize) { // we're assuming all our textures are square. sue me. Bitmap tempBitmap = Bitmap.createScaledBitmap( bitmap, mMaxTextureSize, mMaxTextureSize, false ); bitmap.recycle(); bitmap = tempBitmap; } textureName = loadBitmapIntoOpenGL(context, gl, bitmap, false); bitmap.recycle(); return textureName; } /** * Loads a bitmap into OpenGL and sets up the common parameters for * 2D texture maps. * * @param context * @param resourceId * @param numLevelsOfDetail number of detail textures to generate * * @return a array of OpenGL texture names corresponding to the different levels of detail textures */ protected int[] loadBitmap(Context context, GL10 gl, int resourceId, boolean generateMips, boolean useHardwareMips ) { InputStream is = context.getResources().openRawResource(resourceId); Bitmap bitmap; try { bitmap = BitmapFactory.decodeStream(is, null, sBitmapOptions); } finally { try { is.close(); } catch (IOException e) { // Ignore. } } if (mMaxTextureSize > 0 && Math.max(bitmap.getWidth(), bitmap.getHeight()) != mMaxTextureSize) { // we're assuming all our textures are square. sue me. Bitmap tempBitmap = Bitmap.createScaledBitmap( bitmap, mMaxTextureSize, mMaxTextureSize, false ); bitmap.recycle(); bitmap = tempBitmap; } final int minSide = Math.min(bitmap.getWidth(), bitmap.getHeight()); int numLevelsOfDetail = 1; if (generateMips) { for (int side = minSide / 2; side > 0; side /= 2) { numLevelsOfDetail++; } } int textureNames[]; if (generateMips && !useHardwareMips) { textureNames = new int[numLevelsOfDetail]; } else { textureNames = new int[1]; } textureNames[0] = loadBitmapIntoOpenGL(context, gl, bitmap, useHardwareMips); // Scale down base bitmap by powers of two to create lower resolution textures for( int i = 1; i < numLevelsOfDetail; ++i ) { int scale = (int)Math.pow(2, i); int dstWidth = bitmap.getWidth() / scale; int dstHeight = bitmap.getHeight() / scale; Bitmap tempBitmap = Bitmap.createScaledBitmap( bitmap, dstWidth, dstHeight, false ); // Set each LOD level to a different color to help visualization if( mColorTextureLods ) { int color = 0; switch( (int)(i % 4) ) { case 1: color = Color.RED; break; case 2: color = Color.YELLOW; break; case 3: color = Color.BLUE; break; } tempBitmap.eraseColor( color ); } if (!useHardwareMips) { textureNames[i] = loadBitmapIntoOpenGL( context, gl, tempBitmap, false); } else { addHardwareMipmap(gl, textureNames[0], tempBitmap, i ); } tempBitmap.recycle(); } bitmap.recycle(); return textureNames; } protected void addHardwareMipmap(GL10 gl, int textureName, Bitmap bitmap, int level) { gl.glBindTexture(GL10.GL_TEXTURE_2D, textureName); GLUtils.texImage2D(GL10.GL_TEXTURE_2D, level, bitmap, 0); } /** * Loads a bitmap into OpenGL and sets up the common parameters for * 2D texture maps. * * @return OpenGL texture entry id */ protected int loadBitmapIntoOpenGL(Context context, GL10 gl, Bitmap bitmap, boolean useMipmaps) { int textureName = -1; if (context != null && gl != null) { gl.glGenTextures(1, mTextureNameWorkspace, 0); textureName = mTextureNameWorkspace[0]; gl.glBindTexture(GL10.GL_TEXTURE_2D, textureName); if (useMipmaps) { if (mTextureFilter == FILTER_TRILINEAR) { gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_LINEAR_MIPMAP_LINEAR); } else { gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_LINEAR_MIPMAP_NEAREST); } } else { if (mTextureFilter == FILTER_NEAREST_NEIGHBOR) { gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST); } else { gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_LINEAR); } } if (mTextureFilter == FILTER_NEAREST_NEIGHBOR) { gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_NEAREST); } else { gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR); } gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_CLAMP_TO_EDGE); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_CLAMP_TO_EDGE); gl.glTexEnvf(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE, GL10.GL_MODULATE); GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0); int error = gl.glGetError(); if (error != GL10.GL_NO_ERROR) { Log.e("SimpleGLRenderer", "Texture Load GLError: " + error); } } return textureName; } }
Java
/* * Copyright (C) 2010 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.heightmapprofiler; import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.CharBuffer; import java.nio.FloatBuffer; import java.nio.IntBuffer; import javax.microedition.khronos.opengles.GL10; import javax.microedition.khronos.opengles.GL11; /** * A 2D rectangular mesh. Can be drawn textured or untextured. * This version is modified from the original Grid.java (found in * the SpriteText package in the APIDemos Android sample) to support hardware * vertex buffers. */ class Grid { private FloatBuffer mFloatVertexBuffer; private FloatBuffer mFloatTexCoordBuffer; private FloatBuffer mFloatColorBuffer; private IntBuffer mFixedVertexBuffer; private IntBuffer mFixedTexCoordBuffer; private IntBuffer mFixedColorBuffer; private CharBuffer mIndexBuffer; private Buffer mVertexBuffer; private Buffer mTexCoordBuffer; private Buffer mColorBuffer; private int mCoordinateSize; private int mCoordinateType; private int mW; private int mH; private int mIndexCount; private boolean mUseHardwareBuffers; private int mVertBufferIndex; private int mIndexBufferIndex; private int mTextureCoordBufferIndex; private int mColorBufferIndex; public Grid(int vertsAcross, int vertsDown, boolean useFixedPoint) { if (vertsAcross < 0 || vertsAcross >= 65536) { throw new IllegalArgumentException("vertsAcross"); } if (vertsDown < 0 || vertsDown >= 65536) { throw new IllegalArgumentException("vertsDown"); } if (vertsAcross * vertsDown >= 65536) { throw new IllegalArgumentException("vertsAcross * vertsDown >= 65536"); } mUseHardwareBuffers = false; mW = vertsAcross; mH = vertsDown; int size = vertsAcross * vertsDown; final int FLOAT_SIZE = 4; final int FIXED_SIZE = 4; final int CHAR_SIZE = 2; if (useFixedPoint) { mFixedVertexBuffer = ByteBuffer.allocateDirect(FIXED_SIZE * size * 3) .order(ByteOrder.nativeOrder()).asIntBuffer(); mFixedTexCoordBuffer = ByteBuffer.allocateDirect(FIXED_SIZE * size * 2) .order(ByteOrder.nativeOrder()).asIntBuffer(); mFixedColorBuffer = ByteBuffer.allocateDirect(FIXED_SIZE * size * 4) .order(ByteOrder.nativeOrder()).asIntBuffer(); mVertexBuffer = mFixedVertexBuffer; mTexCoordBuffer = mFixedTexCoordBuffer; mColorBuffer = mFixedColorBuffer; mCoordinateSize = FIXED_SIZE; mCoordinateType = GL10.GL_FIXED; } else { mFloatVertexBuffer = ByteBuffer.allocateDirect(FLOAT_SIZE * size * 3) .order(ByteOrder.nativeOrder()).asFloatBuffer(); mFloatTexCoordBuffer = ByteBuffer.allocateDirect(FLOAT_SIZE * size * 2) .order(ByteOrder.nativeOrder()).asFloatBuffer(); mFloatColorBuffer = ByteBuffer.allocateDirect(FLOAT_SIZE * size * 4) .order(ByteOrder.nativeOrder()).asFloatBuffer(); mVertexBuffer = mFloatVertexBuffer; mTexCoordBuffer = mFloatTexCoordBuffer; mColorBuffer = mFloatColorBuffer; mCoordinateSize = FLOAT_SIZE; mCoordinateType = GL10.GL_FLOAT; } int quadW = mW - 1; int quadH = mH - 1; int quadCount = quadW * quadH; int indexCount = quadCount * 6; mIndexCount = indexCount; mIndexBuffer = ByteBuffer.allocateDirect(CHAR_SIZE * indexCount) .order(ByteOrder.nativeOrder()).asCharBuffer(); /* * Initialize triangle list mesh. * * [0]-----[ 1] ... * | / | * | / | * | / | * [w]-----[w+1] ... * | | * */ { int i = 0; for (int y = 0; y < quadH; y++) { for (int x = 0; x < quadW; x++) { char a = (char) (y * mW + x); char b = (char) (y * mW + x + 1); char c = (char) ((y + 1) * mW + x); char d = (char) ((y + 1) * mW + x + 1); mIndexBuffer.put(i++, a); mIndexBuffer.put(i++, b); mIndexBuffer.put(i++, c); mIndexBuffer.put(i++, b); mIndexBuffer.put(i++, c); mIndexBuffer.put(i++, d); } } } mVertBufferIndex = 0; } void set(int i, int j, float x, float y, float z, float u, float v, float[] color) { if (i < 0 || i >= mW) { throw new IllegalArgumentException("i"); } if (j < 0 || j >= mH) { throw new IllegalArgumentException("j"); } final int index = mW * j + i; final int posIndex = index * 3; final int texIndex = index * 2; final int colorIndex = index * 4; if (mCoordinateType == GL10.GL_FLOAT) { mFloatVertexBuffer.put(posIndex, x); mFloatVertexBuffer.put(posIndex + 1, y); mFloatVertexBuffer.put(posIndex + 2, z); mFloatTexCoordBuffer.put(texIndex, u); mFloatTexCoordBuffer.put(texIndex + 1, v); if (color != null) { mFloatColorBuffer.put(colorIndex, color[0]); mFloatColorBuffer.put(colorIndex + 1, color[1]); mFloatColorBuffer.put(colorIndex + 2, color[2]); mFloatColorBuffer.put(colorIndex + 3, color[3]); } } else { mFixedVertexBuffer.put(posIndex, (int)(x * (1 << 16))); mFixedVertexBuffer.put(posIndex + 1, (int)(y * (1 << 16))); mFixedVertexBuffer.put(posIndex + 2, (int)(z * (1 << 16))); mFixedTexCoordBuffer.put(texIndex, (int)(u * (1 << 16))); mFixedTexCoordBuffer.put(texIndex + 1, (int)(v * (1 << 16))); if (color != null) { mFixedColorBuffer.put(colorIndex, (int)(color[0] * (1 << 16))); mFixedColorBuffer.put(colorIndex + 1, (int)(color[1] * (1 << 16))); mFixedColorBuffer.put(colorIndex + 2, (int)(color[2] * (1 << 16))); mFixedColorBuffer.put(colorIndex + 3, (int)(color[3] * (1 << 16))); } } } public static void beginDrawing(GL10 gl, boolean useTexture, boolean useColor) { gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); if (useTexture) { gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY); gl.glEnable(GL10.GL_TEXTURE_2D); } else { gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY); gl.glDisable(GL10.GL_TEXTURE_2D); } if (useColor) { gl.glEnableClientState(GL10.GL_COLOR_ARRAY); } else { gl.glDisableClientState(GL10.GL_COLOR_ARRAY); } } public void draw(GL10 gl, boolean useTexture, boolean useColor) { if (!mUseHardwareBuffers) { gl.glVertexPointer(3, mCoordinateType, 0, mVertexBuffer); if (useTexture) { gl.glTexCoordPointer(2, mCoordinateType, 0, mTexCoordBuffer); } if (useColor) { gl.glColorPointer(4, mCoordinateType, 0, mColorBuffer); } gl.glDrawElements(GL10.GL_TRIANGLES, mIndexCount, GL10.GL_UNSIGNED_SHORT, mIndexBuffer); } else { GL11 gl11 = (GL11)gl; // draw using hardware buffers gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, mVertBufferIndex); gl11.glVertexPointer(3, mCoordinateType, 0, 0); if (useTexture) { gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, mTextureCoordBufferIndex); gl11.glTexCoordPointer(2, mCoordinateType, 0, 0); } if (useColor) { gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, mColorBufferIndex); gl11.glColorPointer(4, mCoordinateType, 0, 0); } gl11.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, mIndexBufferIndex); gl11.glDrawElements(GL11.GL_TRIANGLES, mIndexCount, GL11.GL_UNSIGNED_SHORT, 0); gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, 0); gl11.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, 0); } } public static void endDrawing(GL10 gl) { gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); } public boolean usingHardwareBuffers() { return mUseHardwareBuffers; } /** * When the OpenGL ES device is lost, GL handles become invalidated. * In that case, we just want to "forget" the old handles (without * explicitly deleting them) and make new ones. */ public void invalidateHardwareBuffers() { mVertBufferIndex = 0; mIndexBufferIndex = 0; mTextureCoordBufferIndex = 0; mColorBufferIndex = 0; mUseHardwareBuffers = false; } /** * Deletes the hardware buffers allocated by this object (if any). */ public void releaseHardwareBuffers(GL10 gl) { if (mUseHardwareBuffers) { if (gl instanceof GL11) { GL11 gl11 = (GL11)gl; int[] buffer = new int[1]; buffer[0] = mVertBufferIndex; gl11.glDeleteBuffers(1, buffer, 0); buffer[0] = mTextureCoordBufferIndex; gl11.glDeleteBuffers(1, buffer, 0); buffer[0] = mColorBufferIndex; gl11.glDeleteBuffers(1, buffer, 0); buffer[0] = mIndexBufferIndex; gl11.glDeleteBuffers(1, buffer, 0); } invalidateHardwareBuffers(); } } /** * Allocates hardware buffers on the graphics card and fills them with * data if a buffer has not already been previously allocated. Note that * this function uses the GL_OES_vertex_buffer_object extension, which is * not guaranteed to be supported on every device. * @param gl A pointer to the OpenGL ES context. */ public void generateHardwareBuffers(GL10 gl) { if (!mUseHardwareBuffers) { if (gl instanceof GL11) { GL11 gl11 = (GL11)gl; int[] buffer = new int[1]; // Allocate and fill the vertex buffer. gl11.glGenBuffers(1, buffer, 0); mVertBufferIndex = buffer[0]; gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, mVertBufferIndex); final int vertexSize = mVertexBuffer.capacity() * mCoordinateSize; gl11.glBufferData(GL11.GL_ARRAY_BUFFER, vertexSize, mVertexBuffer, GL11.GL_STATIC_DRAW); // Allocate and fill the texture coordinate buffer. gl11.glGenBuffers(1, buffer, 0); mTextureCoordBufferIndex = buffer[0]; gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, mTextureCoordBufferIndex); final int texCoordSize = mTexCoordBuffer.capacity() * mCoordinateSize; gl11.glBufferData(GL11.GL_ARRAY_BUFFER, texCoordSize, mTexCoordBuffer, GL11.GL_STATIC_DRAW); // Allocate and fill the color buffer. gl11.glGenBuffers(1, buffer, 0); mColorBufferIndex = buffer[0]; gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, mColorBufferIndex); final int colorSize = mColorBuffer.capacity() * mCoordinateSize; gl11.glBufferData(GL11.GL_ARRAY_BUFFER, colorSize, mColorBuffer, GL11.GL_STATIC_DRAW); // Unbind the array buffer. gl11.glBindBuffer(GL11.GL_ARRAY_BUFFER, 0); // Allocate and fill the index buffer. gl11.glGenBuffers(1, buffer, 0); mIndexBufferIndex = buffer[0]; gl11.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, mIndexBufferIndex); // A char is 2 bytes. final int indexSize = mIndexBuffer.capacity() * 2; gl11.glBufferData(GL11.GL_ELEMENT_ARRAY_BUFFER, indexSize, mIndexBuffer, GL11.GL_STATIC_DRAW); // Unbind the element array buffer. gl11.glBindBuffer(GL11.GL_ELEMENT_ARRAY_BUFFER, 0); mUseHardwareBuffers = true; assert mVertBufferIndex != 0; assert mTextureCoordBufferIndex != 0; assert mIndexBufferIndex != 0; assert gl11.glGetError() == 0; } } } // These functions exposed to patch Grid info into native code. public final int getVertexBuffer() { return mVertBufferIndex; } public final int getTextureBuffer() { return mTextureCoordBufferIndex; } public final int getIndexBuffer() { return mIndexBufferIndex; } public final int getColorBuffer() { return mColorBufferIndex; } public final int getIndexCount() { return mIndexCount; } public boolean getFixedPoint() { return (mCoordinateType == GL10.GL_FIXED); } public long getVertexCount() { return mW * mH; } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.downloader; import android.app.Activity; import android.app.AlertDialog; import android.app.AlertDialog.Builder; import android.content.DialogInterface; import android.content.Intent; import org.apache.http.impl.client.DefaultHttpClient; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.os.SystemClock; import java.security.MessageDigest; import android.util.Log; import android.util.Xml; import android.view.View; import android.view.Window; import android.view.WindowManager; import android.widget.Button; import android.widget.TextView; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpHead; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.security.NoSuchAlgorithmException; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; public class DownloaderActivity extends Activity { /** * Checks if data has been downloaded. If so, returns true. If not, * starts an activity to download the data and returns false. If this * function returns false the caller should immediately return from its * onCreate method. The calling activity will later be restarted * (using a copy of its original intent) once the data download completes. * @param activity The calling activity. * @param customText A text string that is displayed in the downloader UI. * @param fileConfigUrl The URL of the download configuration URL. * @param configVersion The version of the configuration file. * @param dataPath The directory on the device where we want to store the * data. * @param userAgent The user agent string to use when fetching URLs. * @return true if the data has already been downloaded successfully, or * false if the data needs to be downloaded. */ public static boolean ensureDownloaded(Activity activity, String customText, String fileConfigUrl, String configVersion, String dataPath, String userAgent) { File dest = new File(dataPath); if (dest.exists()) { // Check version if (versionMatches(dest, configVersion)) { Log.i(LOG_TAG, "Versions match, no need to download."); return true; } } Intent intent = PreconditionActivityHelper.createPreconditionIntent( activity, DownloaderActivity.class); intent.putExtra(EXTRA_CUSTOM_TEXT, customText); intent.putExtra(EXTRA_FILE_CONFIG_URL, fileConfigUrl); intent.putExtra(EXTRA_CONFIG_VERSION, configVersion); intent.putExtra(EXTRA_DATA_PATH, dataPath); intent.putExtra(EXTRA_USER_AGENT, userAgent); PreconditionActivityHelper.startPreconditionActivityAndFinish( activity, intent); return false; } /** * Delete a directory and all its descendants. * @param directory The directory to delete * @return true if the directory was deleted successfully. */ public static boolean deleteData(String directory) { return deleteTree(new File(directory), true); } private static boolean deleteTree(File base, boolean deleteBase) { boolean result = true; if (base.isDirectory()) { for (File child : base.listFiles()) { result &= deleteTree(child, true); } } if (deleteBase) { result &= base.delete(); } return result; } private static boolean versionMatches(File dest, String expectedVersion) { Config config = getLocalConfig(dest, LOCAL_CONFIG_FILE); if (config != null) { return config.version.equals(expectedVersion); } return false; } private static Config getLocalConfig(File destPath, String configFilename) { File configPath = new File(destPath, configFilename); FileInputStream is; try { is = new FileInputStream(configPath); } catch (FileNotFoundException e) { return null; } try { Config config = ConfigHandler.parse(is); return config; } catch (Exception e) { Log.e(LOG_TAG, "Unable to read local config file", e); return null; } finally { quietClose(is); } } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent intent = getIntent(); requestWindowFeature(Window.FEATURE_CUSTOM_TITLE); setContentView(R.layout.downloader); getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.downloader_title); ((TextView) findViewById(R.id.customText)).setText( intent.getStringExtra(EXTRA_CUSTOM_TEXT)); mProgress = (TextView) findViewById(R.id.progress); mTimeRemaining = (TextView) findViewById(R.id.time_remaining); Button button = (Button) findViewById(R.id.cancel); button.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { if (mDownloadThread != null) { mSuppressErrorMessages = true; mDownloadThread.interrupt(); } } }); startDownloadThread(); } private void startDownloadThread() { mSuppressErrorMessages = false; mProgress.setText(""); mTimeRemaining.setText(""); mDownloadThread = new Thread(new Downloader(), "Downloader"); mDownloadThread.setPriority(Thread.NORM_PRIORITY - 1); mDownloadThread.start(); } @Override protected void onResume() { super.onResume(); } @Override protected void onDestroy() { super.onDestroy(); mSuppressErrorMessages = true; mDownloadThread.interrupt(); try { mDownloadThread.join(); } catch (InterruptedException e) { // Don't care. } } private void onDownloadSucceeded() { Log.i(LOG_TAG, "Download succeeded"); PreconditionActivityHelper.startOriginalActivityAndFinish(this); } private void onDownloadFailed(String reason) { Log.e(LOG_TAG, "Download stopped: " + reason); String shortReason; int index = reason.indexOf('\n'); if (index >= 0) { shortReason = reason.substring(0, index); } else { shortReason = reason; } AlertDialog alert = new Builder(this).create(); alert.setTitle(R.string.download_activity_download_stopped); if (!mSuppressErrorMessages) { alert.setMessage(shortReason); } alert.setButton(getString(R.string.download_activity_retry), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { startDownloadThread(); } }); alert.setButton2(getString(R.string.download_activity_quit), new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { finish(); } }); try { alert.show(); } catch (WindowManager.BadTokenException e) { // Happens when the Back button is used to exit the activity. // ignore. } } private void onReportProgress(int progress) { mProgress.setText(mPercentFormat.format(progress / 10000.0)); long now = SystemClock.elapsedRealtime(); if (mStartTime == 0) { mStartTime = now; } long delta = now - mStartTime; String timeRemaining = getString(R.string.download_activity_time_remaining_unknown); if ((delta > 3 * MS_PER_SECOND) && (progress > 100)) { long totalTime = 10000 * delta / progress; long timeLeft = Math.max(0L, totalTime - delta); if (timeLeft > MS_PER_DAY) { timeRemaining = Long.toString( (timeLeft + MS_PER_DAY - 1) / MS_PER_DAY) + " " + getString(R.string.download_activity_time_remaining_days); } else if (timeLeft > MS_PER_HOUR) { timeRemaining = Long.toString( (timeLeft + MS_PER_HOUR - 1) / MS_PER_HOUR) + " " + getString(R.string.download_activity_time_remaining_hours); } else if (timeLeft > MS_PER_MINUTE) { timeRemaining = Long.toString( (timeLeft + MS_PER_MINUTE - 1) / MS_PER_MINUTE) + " " + getString(R.string.download_activity_time_remaining_minutes); } else { timeRemaining = Long.toString( (timeLeft + MS_PER_SECOND - 1) / MS_PER_SECOND) + " " + getString(R.string.download_activity_time_remaining_seconds); } } mTimeRemaining.setText(timeRemaining); } private void onReportVerifying() { mProgress.setText(getString(R.string.download_activity_verifying)); mTimeRemaining.setText(""); } private static void quietClose(InputStream is) { try { if (is != null) { is.close(); } } catch (IOException e) { // Don't care. } } private static void quietClose(OutputStream os) { try { if (os != null) { os.close(); } } catch (IOException e) { // Don't care. } } private static class Config { long getSize() { long result = 0; for(File file : mFiles) { result += file.getSize(); } return result; } static class File { public File(String src, String dest, String md5, long size) { if (src != null) { this.mParts.add(new Part(src, md5, size)); } this.dest = dest; } static class Part { Part(String src, String md5, long size) { this.src = src; this.md5 = md5; this.size = size; } String src; String md5; long size; } ArrayList<Part> mParts = new ArrayList<Part>(); String dest; long getSize() { long result = 0; for(Part part : mParts) { if (part.size > 0) { result += part.size; } } return result; } } String version; ArrayList<File> mFiles = new ArrayList<File>(); } /** * <config version=""> * <file src="http:..." dest ="b.x" /> * <file dest="b.x"> * <part src="http:..." /> * ... * ... * </config> * */ private static class ConfigHandler extends DefaultHandler { public static Config parse(InputStream is) throws SAXException, UnsupportedEncodingException, IOException { ConfigHandler handler = new ConfigHandler(); Xml.parse(is, Xml.findEncodingByName("UTF-8"), handler); return handler.mConfig; } private ConfigHandler() { mConfig = new Config(); } @Override public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException { if (localName.equals("config")) { mConfig.version = getRequiredString(attributes, "version"); } else if (localName.equals("file")) { String src = attributes.getValue("", "src"); String dest = getRequiredString(attributes, "dest"); String md5 = attributes.getValue("", "md5"); long size = getLong(attributes, "size", -1); mConfig.mFiles.add(new Config.File(src, dest, md5, size)); } else if (localName.equals("part")) { String src = getRequiredString(attributes, "src"); String md5 = attributes.getValue("", "md5"); long size = getLong(attributes, "size", -1); int length = mConfig.mFiles.size(); if (length > 0) { mConfig.mFiles.get(length-1).mParts.add( new Config.File.Part(src, md5, size)); } } } private static String getRequiredString(Attributes attributes, String localName) throws SAXException { String result = attributes.getValue("", localName); if (result == null) { throw new SAXException("Expected attribute " + localName); } return result; } private static long getLong(Attributes attributes, String localName, long defaultValue) { String value = attributes.getValue("", localName); if (value == null) { return defaultValue; } else { return Long.parseLong(value); } } public Config mConfig; } private class DownloaderException extends Exception { public DownloaderException(String reason) { super(reason); } } private class Downloader implements Runnable { public void run() { Intent intent = getIntent(); mFileConfigUrl = intent.getStringExtra(EXTRA_FILE_CONFIG_URL); mConfigVersion = intent.getStringExtra(EXTRA_CONFIG_VERSION); mDataPath = intent.getStringExtra(EXTRA_DATA_PATH); mUserAgent = intent.getStringExtra(EXTRA_USER_AGENT); mDataDir = new File(mDataPath); try { // Download files. mHttpClient = new DefaultHttpClient(); Config config = getConfig(); filter(config); persistantDownload(config); verify(config); cleanup(); reportSuccess(); } catch (Exception e) { reportFailure(e.toString() + "\n" + Log.getStackTraceString(e)); } } private void persistantDownload(Config config) throws ClientProtocolException, DownloaderException, IOException { while(true) { try { download(config); break; } catch(java.net.SocketException e) { if (mSuppressErrorMessages) { throw e; } } catch(java.net.SocketTimeoutException e) { if (mSuppressErrorMessages) { throw e; } } Log.i(LOG_TAG, "Network connectivity issue, retrying."); } } private void filter(Config config) throws IOException, DownloaderException { File filteredFile = new File(mDataDir, LOCAL_FILTERED_FILE); if (filteredFile.exists()) { return; } File localConfigFile = new File(mDataDir, LOCAL_CONFIG_FILE_TEMP); HashSet<String> keepSet = new HashSet<String>(); keepSet.add(localConfigFile.getCanonicalPath()); HashMap<String, Config.File> fileMap = new HashMap<String, Config.File>(); for(Config.File file : config.mFiles) { String canonicalPath = new File(mDataDir, file.dest).getCanonicalPath(); fileMap.put(canonicalPath, file); } recursiveFilter(mDataDir, fileMap, keepSet, false); touch(filteredFile); } private void touch(File file) throws FileNotFoundException { FileOutputStream os = new FileOutputStream(file); quietClose(os); } private boolean recursiveFilter(File base, HashMap<String, Config.File> fileMap, HashSet<String> keepSet, boolean filterBase) throws IOException, DownloaderException { boolean result = true; if (base.isDirectory()) { for (File child : base.listFiles()) { result &= recursiveFilter(child, fileMap, keepSet, true); } } if (filterBase) { if (base.isDirectory()) { if (base.listFiles().length == 0) { result &= base.delete(); } } else { if (!shouldKeepFile(base, fileMap, keepSet)) { result &= base.delete(); } } } return result; } private boolean shouldKeepFile(File file, HashMap<String, Config.File> fileMap, HashSet<String> keepSet) throws IOException, DownloaderException { String canonicalPath = file.getCanonicalPath(); if (keepSet.contains(canonicalPath)) { return true; } Config.File configFile = fileMap.get(canonicalPath); if (configFile == null) { return false; } return verifyFile(configFile, false); } private void reportSuccess() { mHandler.sendMessage( Message.obtain(mHandler, MSG_DOWNLOAD_SUCCEEDED)); } private void reportFailure(String reason) { mHandler.sendMessage( Message.obtain(mHandler, MSG_DOWNLOAD_FAILED, reason)); } private void reportProgress(int progress) { mHandler.sendMessage( Message.obtain(mHandler, MSG_REPORT_PROGRESS, progress, 0)); } private void reportVerifying() { mHandler.sendMessage( Message.obtain(mHandler, MSG_REPORT_VERIFYING)); } private Config getConfig() throws DownloaderException, ClientProtocolException, IOException, SAXException { Config config = null; if (mDataDir.exists()) { config = getLocalConfig(mDataDir, LOCAL_CONFIG_FILE_TEMP); if ((config == null) || !mConfigVersion.equals(config.version)) { if (config == null) { Log.i(LOG_TAG, "Couldn't find local config."); } else { Log.i(LOG_TAG, "Local version out of sync. Wanted " + mConfigVersion + " but have " + config.version); } config = null; } } else { Log.i(LOG_TAG, "Creating directory " + mDataPath); mDataDir.mkdirs(); mDataDir.mkdir(); if (!mDataDir.exists()) { throw new DownloaderException( "Could not create the directory " + mDataPath); } } if (config == null) { File localConfig = download(mFileConfigUrl, LOCAL_CONFIG_FILE_TEMP); InputStream is = new FileInputStream(localConfig); try { config = ConfigHandler.parse(is); } finally { quietClose(is); } if (! config.version.equals(mConfigVersion)) { throw new DownloaderException( "Configuration file version mismatch. Expected " + mConfigVersion + " received " + config.version); } } return config; } private void noisyDelete(File file) throws IOException { if (! file.delete() ) { throw new IOException("could not delete " + file); } } private void download(Config config) throws DownloaderException, ClientProtocolException, IOException { mDownloadedSize = 0; getSizes(config); Log.i(LOG_TAG, "Total bytes to download: " + mTotalExpectedSize); for(Config.File file : config.mFiles) { downloadFile(file); } } private void downloadFile(Config.File file) throws DownloaderException, FileNotFoundException, IOException, ClientProtocolException { boolean append = false; File dest = new File(mDataDir, file.dest); long bytesToSkip = 0; if (dest.exists() && dest.isFile()) { append = true; bytesToSkip = dest.length(); mDownloadedSize += bytesToSkip; } FileOutputStream os = null; long offsetOfCurrentPart = 0; try { for(Config.File.Part part : file.mParts) { // The part.size==0 check below allows us to download // zero-length files. if ((part.size > bytesToSkip) || (part.size == 0)) { MessageDigest digest = null; if (part.md5 != null) { digest = createDigest(); if (bytesToSkip > 0) { FileInputStream is = openInput(file.dest); try { is.skip(offsetOfCurrentPart); readIntoDigest(is, bytesToSkip, digest); } finally { quietClose(is); } } } if (os == null) { os = openOutput(file.dest, append); } downloadPart(part.src, os, bytesToSkip, part.size, digest); if (digest != null) { String hash = getHash(digest); if (!hash.equalsIgnoreCase(part.md5)) { Log.e(LOG_TAG, "web MD5 checksums don't match. " + part.src + "\nExpected " + part.md5 + "\n got " + hash); quietClose(os); dest.delete(); throw new DownloaderException( "Received bad data from web server"); } else { Log.i(LOG_TAG, "web MD5 checksum matches."); } } } bytesToSkip -= Math.min(bytesToSkip, part.size); offsetOfCurrentPart += part.size; } } finally { quietClose(os); } } private void cleanup() throws IOException { File filtered = new File(mDataDir, LOCAL_FILTERED_FILE); noisyDelete(filtered); File tempConfig = new File(mDataDir, LOCAL_CONFIG_FILE_TEMP); File realConfig = new File(mDataDir, LOCAL_CONFIG_FILE); tempConfig.renameTo(realConfig); } private void verify(Config config) throws DownloaderException, ClientProtocolException, IOException { Log.i(LOG_TAG, "Verifying..."); String failFiles = null; for(Config.File file : config.mFiles) { if (! verifyFile(file, true) ) { if (failFiles == null) { failFiles = file.dest; } else { failFiles += " " + file.dest; } } } if (failFiles != null) { throw new DownloaderException( "Possible bad SD-Card. MD5 sum incorrect for file(s) " + failFiles); } } private boolean verifyFile(Config.File file, boolean deleteInvalid) throws FileNotFoundException, DownloaderException, IOException { Log.i(LOG_TAG, "verifying " + file.dest); reportVerifying(); File dest = new File(mDataDir, file.dest); if (! dest.exists()) { Log.e(LOG_TAG, "File does not exist: " + dest.toString()); return false; } long fileSize = file.getSize(); long destLength = dest.length(); if (fileSize != destLength) { Log.e(LOG_TAG, "Length doesn't match. Expected " + fileSize + " got " + destLength); if (deleteInvalid) { dest.delete(); return false; } } FileInputStream is = new FileInputStream(dest); try { for(Config.File.Part part : file.mParts) { if (part.md5 == null) { continue; } MessageDigest digest = createDigest(); readIntoDigest(is, part.size, digest); String hash = getHash(digest); if (!hash.equalsIgnoreCase(part.md5)) { Log.e(LOG_TAG, "MD5 checksums don't match. " + part.src + " Expected " + part.md5 + " got " + hash); if (deleteInvalid) { quietClose(is); dest.delete(); } return false; } } } finally { quietClose(is); } return true; } private void readIntoDigest(FileInputStream is, long bytesToRead, MessageDigest digest) throws IOException { while(bytesToRead > 0) { int chunkSize = (int) Math.min(mFileIOBuffer.length, bytesToRead); int bytesRead = is.read(mFileIOBuffer, 0, chunkSize); if (bytesRead < 0) { break; } updateDigest(digest, bytesRead); bytesToRead -= bytesRead; } } private MessageDigest createDigest() throws DownloaderException { MessageDigest digest; try { digest = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new DownloaderException("Couldn't create MD5 digest"); } return digest; } private void updateDigest(MessageDigest digest, int bytesRead) { if (bytesRead == mFileIOBuffer.length) { digest.update(mFileIOBuffer); } else { // Work around an awkward API: Create a // new buffer with just the valid bytes byte[] temp = new byte[bytesRead]; System.arraycopy(mFileIOBuffer, 0, temp, 0, bytesRead); digest.update(temp); } } private String getHash(MessageDigest digest) { StringBuilder builder = new StringBuilder(); for(byte b : digest.digest()) { builder.append(Integer.toHexString((b >> 4) & 0xf)); builder.append(Integer.toHexString(b & 0xf)); } return builder.toString(); } /** * Ensure we have sizes for all the items. * @param config * @throws ClientProtocolException * @throws IOException * @throws DownloaderException */ private void getSizes(Config config) throws ClientProtocolException, IOException, DownloaderException { for (Config.File file : config.mFiles) { for(Config.File.Part part : file.mParts) { if (part.size < 0) { part.size = getSize(part.src); } } } mTotalExpectedSize = config.getSize(); } private long getSize(String url) throws ClientProtocolException, IOException { url = normalizeUrl(url); Log.i(LOG_TAG, "Head " + url); HttpHead httpGet = new HttpHead(url); HttpResponse response = mHttpClient.execute(httpGet); if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) { throw new IOException("Unexpected Http status code " + response.getStatusLine().getStatusCode()); } Header[] clHeaders = response.getHeaders("Content-Length"); if (clHeaders.length > 0) { Header header = clHeaders[0]; return Long.parseLong(header.getValue()); } return -1; } private String normalizeUrl(String url) throws MalformedURLException { return (new URL(new URL(mFileConfigUrl), url)).toString(); } private InputStream get(String url, long startOffset, long expectedLength) throws ClientProtocolException, IOException { url = normalizeUrl(url); Log.i(LOG_TAG, "Get " + url); mHttpGet = new HttpGet(url); int expectedStatusCode = HttpStatus.SC_OK; if (startOffset > 0) { String range = "bytes=" + startOffset + "-"; if (expectedLength >= 0) { range += expectedLength-1; } Log.i(LOG_TAG, "requesting byte range " + range); mHttpGet.addHeader("Range", range); expectedStatusCode = HttpStatus.SC_PARTIAL_CONTENT; } HttpResponse response = mHttpClient.execute(mHttpGet); long bytesToSkip = 0; int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != expectedStatusCode) { if ((statusCode == HttpStatus.SC_OK) && (expectedStatusCode == HttpStatus.SC_PARTIAL_CONTENT)) { Log.i(LOG_TAG, "Byte range request ignored"); bytesToSkip = startOffset; } else { throw new IOException("Unexpected Http status code " + statusCode + " expected " + expectedStatusCode); } } HttpEntity entity = response.getEntity(); InputStream is = entity.getContent(); if (bytesToSkip > 0) { is.skip(bytesToSkip); } return is; } private File download(String src, String dest) throws DownloaderException, ClientProtocolException, IOException { File destFile = new File(mDataDir, dest); FileOutputStream os = openOutput(dest, false); try { downloadPart(src, os, 0, -1, null); } finally { os.close(); } return destFile; } private void downloadPart(String src, FileOutputStream os, long startOffset, long expectedLength, MessageDigest digest) throws ClientProtocolException, IOException, DownloaderException { boolean lengthIsKnown = expectedLength >= 0; if (startOffset < 0) { throw new IllegalArgumentException("Negative startOffset:" + startOffset); } if (lengthIsKnown && (startOffset > expectedLength)) { throw new IllegalArgumentException( "startOffset > expectedLength" + startOffset + " " + expectedLength); } InputStream is = get(src, startOffset, expectedLength); try { long bytesRead = downloadStream(is, os, digest); if (lengthIsKnown) { long expectedBytesRead = expectedLength - startOffset; if (expectedBytesRead != bytesRead) { Log.e(LOG_TAG, "Bad file transfer from server: " + src + " Expected " + expectedBytesRead + " Received " + bytesRead); throw new DownloaderException( "Incorrect number of bytes received from server"); } } } finally { is.close(); mHttpGet = null; } } private FileOutputStream openOutput(String dest, boolean append) throws FileNotFoundException, DownloaderException { File destFile = new File(mDataDir, dest); File parent = destFile.getParentFile(); if (! parent.exists()) { parent.mkdirs(); } if (! parent.exists()) { throw new DownloaderException("Could not create directory " + parent.toString()); } FileOutputStream os = new FileOutputStream(destFile, append); return os; } private FileInputStream openInput(String src) throws FileNotFoundException, DownloaderException { File srcFile = new File(mDataDir, src); File parent = srcFile.getParentFile(); if (! parent.exists()) { parent.mkdirs(); } if (! parent.exists()) { throw new DownloaderException("Could not create directory " + parent.toString()); } return new FileInputStream(srcFile); } private long downloadStream(InputStream is, FileOutputStream os, MessageDigest digest) throws DownloaderException, IOException { long totalBytesRead = 0; while(true){ if (Thread.interrupted()) { Log.i(LOG_TAG, "downloader thread interrupted."); mHttpGet.abort(); throw new DownloaderException("Thread interrupted"); } int bytesRead = is.read(mFileIOBuffer); if (bytesRead < 0) { break; } if (digest != null) { updateDigest(digest, bytesRead); } totalBytesRead += bytesRead; os.write(mFileIOBuffer, 0, bytesRead); mDownloadedSize += bytesRead; int progress = (int) (Math.min(mTotalExpectedSize, mDownloadedSize * 10000 / Math.max(1, mTotalExpectedSize))); if (progress != mReportedProgress) { mReportedProgress = progress; reportProgress(progress); } } return totalBytesRead; } private DefaultHttpClient mHttpClient; private HttpGet mHttpGet; private String mFileConfigUrl; private String mConfigVersion; private String mDataPath; private File mDataDir; private String mUserAgent; private long mTotalExpectedSize; private long mDownloadedSize; private int mReportedProgress; private final static int CHUNK_SIZE = 32 * 1024; byte[] mFileIOBuffer = new byte[CHUNK_SIZE]; } private final static String LOG_TAG = "Downloader"; private TextView mProgress; private TextView mTimeRemaining; private final DecimalFormat mPercentFormat = new DecimalFormat("0.00 %"); private long mStartTime; private Thread mDownloadThread; private boolean mSuppressErrorMessages; private final static long MS_PER_SECOND = 1000; private final static long MS_PER_MINUTE = 60 * 1000; private final static long MS_PER_HOUR = 60 * 60 * 1000; private final static long MS_PER_DAY = 24 * 60 * 60 * 1000; private final static String LOCAL_CONFIG_FILE = ".downloadConfig"; private final static String LOCAL_CONFIG_FILE_TEMP = ".downloadConfig_temp"; private final static String LOCAL_FILTERED_FILE = ".downloadConfig_filtered"; private final static String EXTRA_CUSTOM_TEXT = "DownloaderActivity_custom_text"; private final static String EXTRA_FILE_CONFIG_URL = "DownloaderActivity_config_url"; private final static String EXTRA_CONFIG_VERSION = "DownloaderActivity_config_version"; private final static String EXTRA_DATA_PATH = "DownloaderActivity_data_path"; private final static String EXTRA_USER_AGENT = "DownloaderActivity_user_agent"; private final static int MSG_DOWNLOAD_SUCCEEDED = 0; private final static int MSG_DOWNLOAD_FAILED = 1; private final static int MSG_REPORT_PROGRESS = 2; private final static int MSG_REPORT_VERIFYING = 3; private final Handler mHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case MSG_DOWNLOAD_SUCCEEDED: onDownloadSucceeded(); break; case MSG_DOWNLOAD_FAILED: onDownloadFailed((String) msg.obj); break; case MSG_REPORT_PROGRESS: onReportProgress(msg.arg1); break; case MSG_REPORT_VERIFYING: onReportVerifying(); break; default: throw new IllegalArgumentException("Unknown message id " + msg.what); } } }; }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.downloader; import android.app.Activity; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; public class DownloaderTest extends Activity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (! DownloaderActivity.ensureDownloaded(this, getString(R.string.app_name), FILE_CONFIG_URL, CONFIG_VERSION, DATA_PATH, USER_AGENT)) { return; } setContentView(R.layout.main); } @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { boolean handled = true; int id = item.getItemId(); if (id == R.id.menu_main_download_again) { downloadAgain(); } else { handled = false; } if (!handled) { handled = super.onOptionsItemSelected(item); } return handled; } private void downloadAgain() { DownloaderActivity.deleteData(DATA_PATH); startActivity(getIntent()); finish(); } /** * Fill this in with your own web server. */ private final static String FILE_CONFIG_URL = "http://example.com/download.config"; private final static String CONFIG_VERSION = "1.0"; private final static String DATA_PATH = "/sdcard/data/downloadTest"; private final static String USER_AGENT = "MyApp Downloader"; }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.downloader; import android.app.Activity; import android.content.Intent; /** * Usage: * * Intent intent = PreconditionActivityHelper.createPreconditionIntent( * activity, WaitActivity.class); * // Optionally add extras to pass arguments to the intent * intent.putExtra(Utils.EXTRA_ACCOUNT, account); * PreconditionActivityHelper.startPreconditionActivityAndFinish(this, intent); * * // And in the wait activity: * PreconditionActivityHelper.startOriginalActivityAndFinish(this); * */ public class PreconditionActivityHelper { /** * Create a precondition activity intent. * @param activity the original activity * @param preconditionActivityClazz the precondition activity's class * @return an intent which will launch the precondition activity. */ public static Intent createPreconditionIntent(Activity activity, Class preconditionActivityClazz) { Intent newIntent = new Intent(); newIntent.setClass(activity, preconditionActivityClazz); newIntent.putExtra(EXTRA_WRAPPED_INTENT, activity.getIntent()); return newIntent; } /** * Start the precondition activity using a given intent, which should * have been created by calling createPreconditionIntent. * @param activity * @param intent */ public static void startPreconditionActivityAndFinish(Activity activity, Intent intent) { activity.startActivity(intent); activity.finish(); } /** * Start the original activity, and finish the precondition activity. * @param preconditionActivity */ public static void startOriginalActivityAndFinish( Activity preconditionActivity) { preconditionActivity.startActivity( (Intent) preconditionActivity.getIntent() .getParcelableExtra(EXTRA_WRAPPED_INTENT)); preconditionActivity.finish(); } static private final String EXTRA_WRAPPED_INTENT = "PreconditionActivityHelper_wrappedIntent"; }
Java
package com.google.android.webviewdemo; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.webkit.JsResult; import android.webkit.WebChromeClient; import android.webkit.WebSettings; import android.webkit.WebView; /** * Demonstrates how to embed a WebView in your activity. Also demonstrates how * to have javascript in the WebView call into the activity, and how the activity * can invoke javascript. * <p> * In this example, clicking on the android in the WebView will result in a call into * the activities code in {@link DemoJavaScriptInterface#clickOnAndroid()}. This code * will turn around and invoke javascript using the {@link WebView#loadUrl(String)} * method. * <p> * Obviously all of this could have been accomplished without calling into the activity * and then back into javascript, but this code is intended to show how to set up the * code paths for this sort of communication. * */ public class WebViewDemo extends Activity { private static final String LOG_TAG = "WebViewDemo"; private WebView mWebView; private Handler mHandler = new Handler(); @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); mWebView = (WebView) findViewById(R.id.webview); WebSettings webSettings = mWebView.getSettings(); webSettings.setSavePassword(false); webSettings.setSaveFormData(false); webSettings.setJavaScriptEnabled(true); webSettings.setSupportZoom(false); mWebView.setWebChromeClient(new MyWebChromeClient()); mWebView.addJavascriptInterface(new DemoJavaScriptInterface(), "demo"); mWebView.loadUrl("file:///android_asset/demo.html"); } final class DemoJavaScriptInterface { DemoJavaScriptInterface() { } /** * This is not called on the UI thread. Post a runnable to invoke * loadUrl on the UI thread. */ public void clickOnAndroid() { mHandler.post(new Runnable() { public void run() { mWebView.loadUrl("javascript:wave()"); } }); } } /** * Provides a hook for calling "alert" from javascript. Useful for * debugging your javascript. */ final class MyWebChromeClient extends WebChromeClient { @Override public boolean onJsAlert(WebView view, String url, String message, JsResult result) { Log.d(LOG_TAG, message); result.confirm(); return true; } } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.opengles.spritetext; import javax.microedition.khronos.opengles.GL10; import android.graphics.Paint; public class NumericSprite { public NumericSprite() { mText = ""; mLabelMaker = null; } public void initialize(GL10 gl, Paint paint) { int height = roundUpPower2((int) paint.getFontSpacing()); final float interDigitGaps = 9 * 1.0f; int width = roundUpPower2((int) (interDigitGaps + paint.measureText(sStrike))); mLabelMaker = new LabelMaker(true, width, height); mLabelMaker.initialize(gl); mLabelMaker.beginAdding(gl); for (int i = 0; i < 10; i++) { String digit = sStrike.substring(i, i+1); mLabelId[i] = mLabelMaker.add(gl, digit, paint); mWidth[i] = (int) Math.ceil(mLabelMaker.getWidth(i)); } mLabelMaker.endAdding(gl); } public void shutdown(GL10 gl) { mLabelMaker.shutdown(gl); mLabelMaker = null; } /** * Find the smallest power of two >= the input value. * (Doesn't work for negative numbers.) */ private int roundUpPower2(int x) { x = x - 1; x = x | (x >> 1); x = x | (x >> 2); x = x | (x >> 4); x = x | (x >> 8); x = x | (x >>16); return x + 1; } public void setValue(int value) { mText = format(value); } public void draw(GL10 gl, float x, float y, float viewWidth, float viewHeight) { int length = mText.length(); mLabelMaker.beginDrawing(gl, viewWidth, viewHeight); for(int i = 0; i < length; i++) { char c = mText.charAt(i); int digit = c - '0'; mLabelMaker.draw(gl, x, y, mLabelId[digit]); x += mWidth[digit]; } mLabelMaker.endDrawing(gl); } public float width() { float width = 0.0f; int length = mText.length(); for(int i = 0; i < length; i++) { char c = mText.charAt(i); width += mWidth[c - '0']; } return width; } private String format(int value) { return Integer.toString(value); } private LabelMaker mLabelMaker; private String mText; private int[] mWidth = new int[10]; private int[] mLabelId = new int[10]; private final static String sStrike = "0123456789"; }
Java
/* * Copyright (C) 2007 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.opengles.spritetext; import android.opengl.Matrix; import java.nio.FloatBuffer; import java.nio.IntBuffer; /** * A matrix stack, similar to OpenGL ES's internal matrix stack. */ public class MatrixStack { public MatrixStack() { commonInit(DEFAULT_MAX_DEPTH); } public MatrixStack(int maxDepth) { commonInit(maxDepth); } private void commonInit(int maxDepth) { mMatrix = new float[maxDepth * MATRIX_SIZE]; mTemp = new float[MATRIX_SIZE * 2]; glLoadIdentity(); } public void glFrustumf(float left, float right, float bottom, float top, float near, float far) { Matrix.frustumM(mMatrix, mTop, left, right, bottom, top, near, far); } public void glFrustumx(int left, int right, int bottom, int top, int near, int far) { glFrustumf(fixedToFloat(left),fixedToFloat(right), fixedToFloat(bottom), fixedToFloat(top), fixedToFloat(near), fixedToFloat(far)); } public void glLoadIdentity() { Matrix.setIdentityM(mMatrix, mTop); } public void glLoadMatrixf(float[] m, int offset) { System.arraycopy(m, offset, mMatrix, mTop, MATRIX_SIZE); } public void glLoadMatrixf(FloatBuffer m) { m.get(mMatrix, mTop, MATRIX_SIZE); } public void glLoadMatrixx(int[] m, int offset) { for(int i = 0; i < MATRIX_SIZE; i++) { mMatrix[mTop + i] = fixedToFloat(m[offset + i]); } } public void glLoadMatrixx(IntBuffer m) { for(int i = 0; i < MATRIX_SIZE; i++) { mMatrix[mTop + i] = fixedToFloat(m.get()); } } public void glMultMatrixf(float[] m, int offset) { System.arraycopy(mMatrix, mTop, mTemp, 0, MATRIX_SIZE); Matrix.multiplyMM(mMatrix, mTop, mTemp, 0, m, offset); } public void glMultMatrixf(FloatBuffer m) { m.get(mTemp, MATRIX_SIZE, MATRIX_SIZE); glMultMatrixf(mTemp, MATRIX_SIZE); } public void glMultMatrixx(int[] m, int offset) { for(int i = 0; i < MATRIX_SIZE; i++) { mTemp[MATRIX_SIZE + i] = fixedToFloat(m[offset + i]); } glMultMatrixf(mTemp, MATRIX_SIZE); } public void glMultMatrixx(IntBuffer m) { for(int i = 0; i < MATRIX_SIZE; i++) { mTemp[MATRIX_SIZE + i] = fixedToFloat(m.get()); } glMultMatrixf(mTemp, MATRIX_SIZE); } public void glOrthof(float left, float right, float bottom, float top, float near, float far) { Matrix.orthoM(mMatrix, mTop, left, right, bottom, top, near, far); } public void glOrthox(int left, int right, int bottom, int top, int near, int far) { glOrthof(fixedToFloat(left), fixedToFloat(right), fixedToFloat(bottom), fixedToFloat(top), fixedToFloat(near), fixedToFloat(far)); } public void glPopMatrix() { preflight_adjust(-1); adjust(-1); } public void glPushMatrix() { preflight_adjust(1); System.arraycopy(mMatrix, mTop, mMatrix, mTop + MATRIX_SIZE, MATRIX_SIZE); adjust(1); } public void glRotatef(float angle, float x, float y, float z) { Matrix.setRotateM(mTemp, 0, angle, x, y, z); System.arraycopy(mMatrix, mTop, mTemp, MATRIX_SIZE, MATRIX_SIZE); Matrix.multiplyMM(mMatrix, mTop, mTemp, MATRIX_SIZE, mTemp, 0); } public void glRotatex(int angle, int x, int y, int z) { glRotatef(angle, fixedToFloat(x), fixedToFloat(y), fixedToFloat(z)); } public void glScalef(float x, float y, float z) { Matrix.scaleM(mMatrix, mTop, x, y, z); } public void glScalex(int x, int y, int z) { glScalef(fixedToFloat(x), fixedToFloat(y), fixedToFloat(z)); } public void glTranslatef(float x, float y, float z) { Matrix.translateM(mMatrix, mTop, x, y, z); } public void glTranslatex(int x, int y, int z) { glTranslatef(fixedToFloat(x), fixedToFloat(y), fixedToFloat(z)); } public void getMatrix(float[] dest, int offset) { System.arraycopy(mMatrix, mTop, dest, offset, MATRIX_SIZE); } private float fixedToFloat(int x) { return x * (1.0f / 65536.0f); } private void preflight_adjust(int dir) { int newTop = mTop + dir * MATRIX_SIZE; if (newTop < 0) { throw new IllegalArgumentException("stack underflow"); } if (newTop + MATRIX_SIZE > mMatrix.length) { throw new IllegalArgumentException("stack overflow"); } } private void adjust(int dir) { mTop += dir * MATRIX_SIZE; } private final static int DEFAULT_MAX_DEPTH = 32; private final static int MATRIX_SIZE = 16; private float[] mMatrix; private int mTop; private float[] mTemp; }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.opengles.spritetext; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import java.nio.ShortBuffer; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Paint; import android.opengl.GLU; import android.opengl.GLUtils; import android.os.SystemClock; import javax.microedition.khronos.egl.EGL10; import javax.microedition.khronos.opengles.GL10; public class SpriteTextRenderer implements GLView.Renderer{ public SpriteTextRenderer(Context context) { mContext = context; mTriangle = new Triangle(); mProjector = new Projector(); mLabelPaint = new Paint(); mLabelPaint.setTextSize(32); mLabelPaint.setAntiAlias(true); mLabelPaint.setARGB(0xff, 0x00, 0x00, 0x00); } public int[] getConfigSpec() { // We don't need a depth buffer, and don't care about our // color depth. int[] configSpec = { EGL10.EGL_DEPTH_SIZE, 0, EGL10.EGL_NONE }; return configSpec; } public void surfaceCreated(GL10 gl) { /* * By default, OpenGL enables features that improve quality * but reduce performance. One might want to tweak that * especially on software renderer. */ gl.glDisable(GL10.GL_DITHER); /* * Some one-time OpenGL initialization can be made here * probably based on features of this particular context */ gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_FASTEST); gl.glClearColor(.5f, .5f, .5f, 1); gl.glShadeModel(GL10.GL_SMOOTH); gl.glEnable(GL10.GL_DEPTH_TEST); gl.glEnable(GL10.GL_TEXTURE_2D); /* * Create our texture. This has to be done each time the * surface is created. */ int[] textures = new int[1]; gl.glGenTextures(1, textures, 0); mTextureID = textures[0]; gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureID); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_CLAMP_TO_EDGE); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_CLAMP_TO_EDGE); gl.glTexEnvf(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE, GL10.GL_REPLACE); InputStream is = mContext.getResources() .openRawResource(R.drawable.tex); Bitmap bitmap; try { bitmap = BitmapFactory.decodeStream(is); } finally { try { is.close(); } catch(IOException e) { // Ignore. } } GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0); bitmap.recycle(); if (mLabels != null) { mLabels.shutdown(gl); } else { mLabels = new LabelMaker(true, 256, 64); } mLabels.initialize(gl); mLabels.beginAdding(gl); mLabelA = mLabels.add(gl, "A", mLabelPaint); mLabelB = mLabels.add(gl, "B", mLabelPaint); mLabelC = mLabels.add(gl, "C", mLabelPaint); mLabelMsPF = mLabels.add(gl, "ms/f", mLabelPaint); mLabels.endAdding(gl); if (mNumericSprite != null) { mNumericSprite.shutdown(gl); } else { mNumericSprite = new NumericSprite(); } mNumericSprite.initialize(gl, mLabelPaint); } public void drawFrame(GL10 gl) { /* * By default, OpenGL enables features that improve quality * but reduce performance. One might want to tweak that * especially on software renderer. */ gl.glDisable(GL10.GL_DITHER); gl.glTexEnvx(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE, GL10.GL_MODULATE); /* * Usually, the first thing one might want to do is to clear * the screen. The most efficient way of doing this is to use * glClear(). */ gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); /* * Now we're ready to draw some 3D objects */ gl.glMatrixMode(GL10.GL_MODELVIEW); gl.glLoadIdentity(); GLU.gluLookAt(gl, 0.0f, 0.0f, -2.5f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f); gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY); gl.glActiveTexture(GL10.GL_TEXTURE0); gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureID); gl.glTexParameterx(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_REPEAT); gl.glTexParameterx(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_REPEAT); long time = SystemClock.uptimeMillis() % 4000L; float angle = 0.090f * ((int) time); gl.glRotatef(angle, 0, 0, 1.0f); gl.glScalef(2.0f, 2.0f, 2.0f); mTriangle.draw(gl); mProjector.getCurrentModelView(gl); mLabels.beginDrawing(gl, mWidth, mHeight); drawLabel(gl, 0, mLabelA); drawLabel(gl, 1, mLabelB); drawLabel(gl, 2, mLabelC); float msPFX = mWidth - mLabels.getWidth(mLabelMsPF) - 1; mLabels.draw(gl, msPFX, 0, mLabelMsPF); mLabels.endDrawing(gl); drawMsPF(gl, msPFX); } private void drawMsPF(GL10 gl, float rightMargin) { long time = SystemClock.uptimeMillis(); if (mStartTime == 0) { mStartTime = time; } if (mFrames++ == SAMPLE_PERIOD_FRAMES) { mFrames = 0; long delta = time - mStartTime; mStartTime = time; mMsPerFrame = (int) (delta * SAMPLE_FACTOR); } if (mMsPerFrame > 0) { mNumericSprite.setValue(mMsPerFrame); float numWidth = mNumericSprite.width(); float x = rightMargin - numWidth; mNumericSprite.draw(gl, x, 0, mWidth, mHeight); } } private void drawLabel(GL10 gl, int triangleVertex, int labelId) { float x = mTriangle.getX(triangleVertex); float y = mTriangle.getY(triangleVertex); mScratch[0] = x; mScratch[1] = y; mScratch[2] = 0.0f; mScratch[3] = 1.0f; mProjector.project(mScratch, 0, mScratch, 4); float sx = mScratch[4]; float sy = mScratch[5]; float height = mLabels.getHeight(labelId); float width = mLabels.getWidth(labelId); float tx = sx - width * 0.5f; float ty = sy - height * 0.5f; mLabels.draw(gl, tx, ty, labelId); } public void sizeChanged(GL10 gl, int w, int h) { mWidth = w; mHeight = h; gl.glViewport(0, 0, w, h); mProjector.setCurrentView(0, 0, w, h); /* * Set our projection matrix. This doesn't have to be done * each time we draw, but usually a new projection needs to * be set when the viewport is resized. */ float ratio = (float) w / h; gl.glMatrixMode(GL10.GL_PROJECTION); gl.glLoadIdentity(); gl.glFrustumf(-ratio, ratio, -1, 1, 1, 10); mProjector.getCurrentProjection(gl); } private int mWidth; private int mHeight; private Context mContext; private Triangle mTriangle; private int mTextureID; private int mFrames; private int mMsPerFrame; private final static int SAMPLE_PERIOD_FRAMES = 12; private final static float SAMPLE_FACTOR = 1.0f / SAMPLE_PERIOD_FRAMES; private long mStartTime; private LabelMaker mLabels; private Paint mLabelPaint; private int mLabelA; private int mLabelB; private int mLabelC; private int mLabelMsPF; private Projector mProjector; private NumericSprite mNumericSprite; private float[] mScratch = new float[8]; } class Triangle { public Triangle() { // Buffers to be passed to gl*Pointer() functions // must be direct, i.e., they must be placed on the // native heap where the garbage collector cannot // move them. // // Buffers with multi-byte datatypes (e.g., short, int, float) // must have their byte order set to native order ByteBuffer vbb = ByteBuffer.allocateDirect(VERTS * 3 * 4); vbb.order(ByteOrder.nativeOrder()); mFVertexBuffer = vbb.asFloatBuffer(); ByteBuffer tbb = ByteBuffer.allocateDirect(VERTS * 2 * 4); tbb.order(ByteOrder.nativeOrder()); mTexBuffer = tbb.asFloatBuffer(); ByteBuffer ibb = ByteBuffer.allocateDirect(VERTS * 2); ibb.order(ByteOrder.nativeOrder()); mIndexBuffer = ibb.asShortBuffer(); for (int i = 0; i < VERTS; i++) { for(int j = 0; j < 3; j++) { mFVertexBuffer.put(sCoords[i*3+j]); } } for (int i = 0; i < VERTS; i++) { for(int j = 0; j < 2; j++) { mTexBuffer.put(sCoords[i*3+j] * 2.0f + 0.5f); } } for(int i = 0; i < VERTS; i++) { mIndexBuffer.put((short) i); } mFVertexBuffer.position(0); mTexBuffer.position(0); mIndexBuffer.position(0); } public void draw(GL10 gl) { gl.glFrontFace(GL10.GL_CCW); gl.glVertexPointer(3, GL10.GL_FLOAT, 0, mFVertexBuffer); gl.glEnable(GL10.GL_TEXTURE_2D); gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, mTexBuffer); gl.glDrawElements(GL10.GL_TRIANGLE_STRIP, VERTS, GL10.GL_UNSIGNED_SHORT, mIndexBuffer); } public float getX(int vertex) { return sCoords[3*vertex]; } public float getY(int vertex) { return sCoords[3*vertex+1]; } private final static int VERTS = 3; private FloatBuffer mFVertexBuffer; private FloatBuffer mTexBuffer; private ShortBuffer mIndexBuffer; // A unit-sided equalateral triangle centered on the origin. private final static float[] sCoords = { // X, Y, Z -0.5f, -0.25f, 0, 0.5f, -0.25f, 0, 0.0f, 0.559016994f, 0 }; }
Java
/* * Copyright (C) 2007 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.opengles.spritetext; import javax.microedition.khronos.opengles.GL10; class MatrixGrabber { public MatrixGrabber() { mModelView = new float[16]; mProjection = new float[16]; } /** * Record the current modelView and projection matrix state. * Has the side effect of setting the current matrix state to GL_MODELVIEW * @param gl */ public void getCurrentState(GL10 gl) { getCurrentProjection(gl); getCurrentModelView(gl); } /** * Record the current modelView matrix state. Has the side effect of * setting the current matrix state to GL_MODELVIEW * @param gl */ public void getCurrentModelView(GL10 gl) { getMatrix(gl, GL10.GL_MODELVIEW, mModelView); } /** * Record the current projection matrix state. Has the side effect of * setting the current matrix state to GL_PROJECTION * @param gl */ public void getCurrentProjection(GL10 gl) { getMatrix(gl, GL10.GL_PROJECTION, mProjection); } private void getMatrix(GL10 gl, int mode, float[] mat) { MatrixTrackingGL gl2 = (MatrixTrackingGL) gl; gl2.glMatrixMode(mode); gl2.getMatrix(mat, 0); } public float[] mModelView; public float[] mProjection; }
Java
/* * Copyright (C) 2007 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.opengles.spritetext; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.Paint.Style; import android.graphics.drawable.Drawable; import android.opengl.GLUtils; import java.util.ArrayList; import javax.microedition.khronos.opengles.GL10; import javax.microedition.khronos.opengles.GL11; import javax.microedition.khronos.opengles.GL11Ext; /** * An OpenGL text label maker. * * * OpenGL labels are implemented by creating a Bitmap, drawing all the labels * into the Bitmap, converting the Bitmap into an Alpha texture, and creating a * mesh for each label * * The benefits of this approach are that the labels are drawn using the high * quality anti-aliased font rasterizer, full character set support, and all the * text labels are stored on a single texture, which makes it faster to use. * * The drawbacks are that you can only have as many labels as will fit onto one * texture, and you have to recreate the whole texture if any label text * changes. * */ public class LabelMaker { /** * Create a label maker * or maximum compatibility with various OpenGL ES implementations, * the strike width and height must be powers of two, * We want the strike width to be at least as wide as the widest window. * * @param fullColor true if we want a full color backing store (4444), * otherwise we generate a grey L8 backing store. * @param strikeWidth width of strike * @param strikeHeight height of strike */ public LabelMaker(boolean fullColor, int strikeWidth, int strikeHeight) { mFullColor = fullColor; mStrikeWidth = strikeWidth; mStrikeHeight = strikeHeight; mTexelWidth = (float) (1.0 / mStrikeWidth); mTexelHeight = (float) (1.0 / mStrikeHeight); mClearPaint = new Paint(); mClearPaint.setARGB(0, 0, 0, 0); mClearPaint.setStyle(Style.FILL); mState = STATE_NEW; } /** * Call to initialize the class. * Call whenever the surface has been created. * * @param gl */ public void initialize(GL10 gl) { mState = STATE_INITIALIZED; int[] textures = new int[1]; gl.glGenTextures(1, textures, 0); mTextureID = textures[0]; gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureID); // Use Nearest for performance. gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_NEAREST); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_CLAMP_TO_EDGE); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_CLAMP_TO_EDGE); gl.glTexEnvf(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE, GL10.GL_REPLACE); } /** * Call when the surface has been destroyed */ public void shutdown(GL10 gl) { if ( gl != null) { if (mState > STATE_NEW) { int[] textures = new int[1]; textures[0] = mTextureID; gl.glDeleteTextures(1, textures, 0); mState = STATE_NEW; } } } /** * Call before adding labels. Clears out any existing labels. * * @param gl */ public void beginAdding(GL10 gl) { checkState(STATE_INITIALIZED, STATE_ADDING); mLabels.clear(); mU = 0; mV = 0; mLineHeight = 0; Bitmap.Config config = mFullColor ? Bitmap.Config.ARGB_4444 : Bitmap.Config.ALPHA_8; mBitmap = Bitmap.createBitmap(mStrikeWidth, mStrikeHeight, config); mCanvas = new Canvas(mBitmap); mBitmap.eraseColor(0); } /** * Call to add a label * * @param gl * @param text the text of the label * @param textPaint the paint of the label * @return the id of the label, used to measure and draw the label */ public int add(GL10 gl, String text, Paint textPaint) { return add(gl, null, text, textPaint); } /** * Call to add a label * * @param gl * @param text the text of the label * @param textPaint the paint of the label * @return the id of the label, used to measure and draw the label */ public int add(GL10 gl, Drawable background, String text, Paint textPaint) { return add(gl, background, text, textPaint, 0, 0); } /** * Call to add a label * @return the id of the label, used to measure and draw the label */ public int add(GL10 gl, Drawable drawable, int minWidth, int minHeight) { return add(gl, drawable, null, null, minWidth, minHeight); } /** * Call to add a label * * @param gl * @param text the text of the label * @param textPaint the paint of the label * @return the id of the label, used to measure and draw the label */ public int add(GL10 gl, Drawable background, String text, Paint textPaint, int minWidth, int minHeight) { checkState(STATE_ADDING, STATE_ADDING); boolean drawBackground = background != null; boolean drawText = (text != null) && (textPaint != null); Rect padding = new Rect(); if (drawBackground) { background.getPadding(padding); minWidth = Math.max(minWidth, background.getMinimumWidth()); minHeight = Math.max(minHeight, background.getMinimumHeight()); } int ascent = 0; int descent = 0; int measuredTextWidth = 0; if (drawText) { // Paint.ascent is negative, so negate it. ascent = (int) Math.ceil(-textPaint.ascent()); descent = (int) Math.ceil(textPaint.descent()); measuredTextWidth = (int) Math.ceil(textPaint.measureText(text)); } int textHeight = ascent + descent; int textWidth = Math.min(mStrikeWidth,measuredTextWidth); int padHeight = padding.top + padding.bottom; int padWidth = padding.left + padding.right; int height = Math.max(minHeight, textHeight + padHeight); int width = Math.max(minWidth, textWidth + padWidth); int effectiveTextHeight = height - padHeight; int effectiveTextWidth = width - padWidth; int centerOffsetHeight = (effectiveTextHeight - textHeight) / 2; int centerOffsetWidth = (effectiveTextWidth - textWidth) / 2; // Make changes to the local variables, only commit them // to the member variables after we've decided not to throw // any exceptions. int u = mU; int v = mV; int lineHeight = mLineHeight; if (width > mStrikeWidth) { width = mStrikeWidth; } // Is there room for this string on the current line? if (u + width > mStrikeWidth) { // No room, go to the next line: u = 0; v += lineHeight; lineHeight = 0; } lineHeight = Math.max(lineHeight, height); if (v + lineHeight > mStrikeHeight) { throw new IllegalArgumentException("Out of texture space."); } int u2 = u + width; int vBase = v + ascent; int v2 = v + height; if (drawBackground) { background.setBounds(u, v, u + width, v + height); background.draw(mCanvas); } if (drawText) { mCanvas.drawText(text, u + padding.left + centerOffsetWidth, vBase + padding.top + centerOffsetHeight, textPaint); } Grid grid = new Grid(2, 2); // Grid.set arguments: i, j, x, y, z, u, v float texU = u * mTexelWidth; float texU2 = u2 * mTexelWidth; float texV = 1.0f - v * mTexelHeight; float texV2 = 1.0f - v2 * mTexelHeight; grid.set(0, 0, 0.0f, 0.0f, 0.0f, texU , texV2); grid.set(1, 0, width, 0.0f, 0.0f, texU2, texV2); grid.set(0, 1, 0.0f, height, 0.0f, texU , texV ); grid.set(1, 1, width, height, 0.0f, texU2, texV ); // We know there's enough space, so update the member variables mU = u + width; mV = v; mLineHeight = lineHeight; mLabels.add(new Label(grid, width, height, ascent, u, v + height, width, -height)); return mLabels.size() - 1; } /** * Call to end adding labels. Must be called before drawing starts. * * @param gl */ public void endAdding(GL10 gl) { checkState(STATE_ADDING, STATE_INITIALIZED); gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureID); GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, mBitmap, 0); // Reclaim storage used by bitmap and canvas. mBitmap.recycle(); mBitmap = null; mCanvas = null; } /** * Get the width in pixels of a given label. * * @param labelID * @return the width in pixels */ public float getWidth(int labelID) { return mLabels.get(labelID).width; } /** * Get the height in pixels of a given label. * * @param labelID * @return the height in pixels */ public float getHeight(int labelID) { return mLabels.get(labelID).height; } /** * Get the baseline of a given label. That's how many pixels from the top of * the label to the text baseline. (This is equivalent to the negative of * the label's paint's ascent.) * * @param labelID * @return the baseline in pixels. */ public float getBaseline(int labelID) { return mLabels.get(labelID).baseline; } /** * Begin drawing labels. Sets the OpenGL state for rapid drawing. * * @param gl * @param viewWidth * @param viewHeight */ public void beginDrawing(GL10 gl, float viewWidth, float viewHeight) { checkState(STATE_INITIALIZED, STATE_DRAWING); gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureID); gl.glShadeModel(GL10.GL_FLAT); gl.glEnable(GL10.GL_BLEND); gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); gl.glColor4x(0x10000, 0x10000, 0x10000, 0x10000); gl.glMatrixMode(GL10.GL_PROJECTION); gl.glPushMatrix(); gl.glLoadIdentity(); gl.glOrthof(0.0f, viewWidth, 0.0f, viewHeight, 0.0f, 1.0f); gl.glMatrixMode(GL10.GL_MODELVIEW); gl.glPushMatrix(); gl.glLoadIdentity(); // Magic offsets to promote consistent rasterization. gl.glTranslatef(0.375f, 0.375f, 0.0f); } /** * Draw a given label at a given x,y position, expressed in pixels, with the * lower-left-hand-corner of the view being (0,0). * * @param gl * @param x * @param y * @param labelID */ public void draw(GL10 gl, float x, float y, int labelID) { checkState(STATE_DRAWING, STATE_DRAWING); gl.glPushMatrix(); float snappedX = (float) Math.floor(x); float snappedY = (float) Math.floor(y); gl.glTranslatef(snappedX, snappedY, 0.0f); Label label = mLabels.get(labelID); gl.glEnable(GL10.GL_TEXTURE_2D); ((GL11)gl).glTexParameteriv(GL10.GL_TEXTURE_2D, GL11Ext.GL_TEXTURE_CROP_RECT_OES, label.mCrop, 0); ((GL11Ext)gl).glDrawTexiOES((int) snappedX, (int) snappedY, 0, (int) label.width, (int) label.height); gl.glPopMatrix(); } /** * Ends the drawing and restores the OpenGL state. * * @param gl */ public void endDrawing(GL10 gl) { checkState(STATE_DRAWING, STATE_INITIALIZED); gl.glDisable(GL10.GL_BLEND); gl.glMatrixMode(GL10.GL_PROJECTION); gl.glPopMatrix(); gl.glMatrixMode(GL10.GL_MODELVIEW); gl.glPopMatrix(); } private void checkState(int oldState, int newState) { if (mState != oldState) { throw new IllegalArgumentException("Can't call this method now."); } mState = newState; } private static class Label { public Label(Grid grid, float width, float height, float baseLine, int cropU, int cropV, int cropW, int cropH) { this.grid = grid; this.width = width; this.height = height; this.baseline = baseLine; int[] crop = new int[4]; crop[0] = cropU; crop[1] = cropV; crop[2] = cropW; crop[3] = cropH; mCrop = crop; } public Grid grid; public float width; public float height; public float baseline; public int[] mCrop; } private int mStrikeWidth; private int mStrikeHeight; private boolean mFullColor; private Bitmap mBitmap; private Canvas mCanvas; private Paint mClearPaint; private int mTextureID; private float mTexelWidth; // Convert texel to U private float mTexelHeight; // Convert texel to V private int mU; private int mV; private int mLineHeight; private ArrayList<Label> mLabels = new ArrayList<Label>(); private static final int STATE_NEW = 0; private static final int STATE_INITIALIZED = 1; private static final int STATE_ADDING = 2; private static final int STATE_DRAWING = 3; private int mState; }
Java
/* * Copyright (C) 2007 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.opengles.spritetext; import android.opengl.Matrix; import javax.microedition.khronos.opengles.GL10; /** * A utility that projects * */ class Projector { public Projector() { mMVP = new float[16]; mV = new float[4]; mGrabber = new MatrixGrabber(); } public void setCurrentView(int x, int y, int width, int height) { mX = x; mY = y; mViewWidth = width; mViewHeight = height; } public void project(float[] obj, int objOffset, float[] win, int winOffset) { if (!mMVPComputed) { Matrix.multiplyMM(mMVP, 0, mGrabber.mProjection, 0, mGrabber.mModelView, 0); mMVPComputed = true; } Matrix.multiplyMV(mV, 0, mMVP, 0, obj, objOffset); float rw = 1.0f / mV[3]; win[winOffset] = mX + mViewWidth * (mV[0] * rw + 1.0f) * 0.5f; win[winOffset + 1] = mY + mViewHeight * (mV[1] * rw + 1.0f) * 0.5f; win[winOffset + 2] = (mV[2] * rw + 1.0f) * 0.5f; } /** * Get the current projection matrix. Has the side-effect of * setting current matrix mode to GL_PROJECTION * @param gl */ public void getCurrentProjection(GL10 gl) { mGrabber.getCurrentProjection(gl); mMVPComputed = false; } /** * Get the current model view matrix. Has the side-effect of * setting current matrix mode to GL_MODELVIEW * @param gl */ public void getCurrentModelView(GL10 gl) { mGrabber.getCurrentModelView(gl); mMVPComputed = false; } private MatrixGrabber mGrabber; private boolean mMVPComputed; private float[] mMVP; private float[] mV; private int mX; private int mY; private int mViewWidth; private int mViewHeight; }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.opengles.spritetext; import android.content.Context; import android.util.AttributeSet; import android.view.SurfaceHolder; import android.view.SurfaceView; import java.util.ArrayList; import java.util.concurrent.Semaphore; import javax.microedition.khronos.egl.EGL10; import javax.microedition.khronos.egl.EGL11; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.egl.EGLContext; import javax.microedition.khronos.egl.EGLDisplay; import javax.microedition.khronos.egl.EGLSurface; import javax.microedition.khronos.opengles.GL; import javax.microedition.khronos.opengles.GL10; /** * An implementation of SurfaceView that uses the dedicated surface for * displaying an OpenGL animation. This allows the animation to run in a * separate thread, without requiring that it be driven by the update mechanism * of the view hierarchy. * * The application-specific rendering code is delegated to a GLView.Renderer * instance. */ class GLView extends SurfaceView implements SurfaceHolder.Callback { GLView(Context context) { super(context); init(); } public GLView(Context context, AttributeSet attrs) { super(context, attrs); init(); } private void init() { // Install a SurfaceHolder.Callback so we get notified when the // underlying surface is created and destroyed mHolder = getHolder(); mHolder.addCallback(this); mHolder.setType(SurfaceHolder.SURFACE_TYPE_GPU); } public void setGLWrapper(GLWrapper glWrapper) { mGLWrapper = glWrapper; } public void setRenderer(Renderer renderer) { mGLThread = new GLThread(renderer); mGLThread.start(); } public void surfaceCreated(SurfaceHolder holder) { mGLThread.surfaceCreated(); } public void surfaceDestroyed(SurfaceHolder holder) { // Surface will be destroyed when we return mGLThread.surfaceDestroyed(); } public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { // Surface size or format has changed. This should not happen in this // example. mGLThread.onWindowResize(w, h); } /** * Inform the view that the activity is paused. */ public void onPause() { mGLThread.onPause(); } /** * Inform the view that the activity is resumed. */ public void onResume() { mGLThread.onResume(); } /** * Inform the view that the window focus has changed. */ @Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); mGLThread.onWindowFocusChanged(hasFocus); } /** * Queue an "event" to be run on the GL rendering thread. * @param r the runnable to be run on the GL rendering thread. */ public void queueEvent(Runnable r) { mGLThread.queueEvent(r); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); mGLThread.requestExitAndWait(); } // ---------------------------------------------------------------------- public interface GLWrapper { GL wrap(GL gl); } // ---------------------------------------------------------------------- /** * A generic renderer interface. */ public interface Renderer { /** * @return the EGL configuration specification desired by the renderer. */ int[] getConfigSpec(); /** * Surface created. * Called when the surface is created. Called when the application * starts, and whenever the GPU is reinitialized. This will * typically happen when the device awakes after going to sleep. * Set your textures here. */ void surfaceCreated(GL10 gl); /** * Surface changed size. * Called after the surface is created and whenever * the OpenGL ES surface size changes. Set your viewport here. * @param gl * @param width * @param height */ void sizeChanged(GL10 gl, int width, int height); /** * Draw the current frame. * @param gl */ void drawFrame(GL10 gl); } /** * An EGL helper class. */ private class EglHelper { public EglHelper() { } /** * Initialize EGL for a given configuration spec. * @param configSpec */ public void start(int[] configSpec){ /* * Get an EGL instance */ mEgl = (EGL10) EGLContext.getEGL(); /* * Get to the default display. */ mEglDisplay = mEgl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY); /* * We can now initialize EGL for that display */ int[] version = new int[2]; mEgl.eglInitialize(mEglDisplay, version); EGLConfig[] configs = new EGLConfig[1]; int[] num_config = new int[1]; mEgl.eglChooseConfig(mEglDisplay, configSpec, configs, 1, num_config); mEglConfig = configs[0]; /* * Create an OpenGL ES context. This must be done only once, an * OpenGL context is a somewhat heavy object. */ mEglContext = mEgl.eglCreateContext(mEglDisplay, mEglConfig, EGL10.EGL_NO_CONTEXT, null); mEglSurface = null; } /* * Create and return an OpenGL surface */ public GL createSurface(SurfaceHolder holder) { /* * The window size has changed, so we need to create a new * surface. */ if (mEglSurface != null) { /* * Unbind and destroy the old EGL surface, if * there is one. */ mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT); mEgl.eglDestroySurface(mEglDisplay, mEglSurface); } /* * Create an EGL surface we can render into. */ mEglSurface = mEgl.eglCreateWindowSurface(mEglDisplay, mEglConfig, holder, null); /* * Before we can issue GL commands, we need to make sure * the context is current and bound to a surface. */ mEgl.eglMakeCurrent(mEglDisplay, mEglSurface, mEglSurface, mEglContext); GL gl = mEglContext.getGL(); if (mGLWrapper != null) { gl = mGLWrapper.wrap(gl); } return gl; } /** * Display the current render surface. * @return false if the context has been lost. */ public boolean swap() { mEgl.eglSwapBuffers(mEglDisplay, mEglSurface); /* * Always check for EGL_CONTEXT_LOST, which means the context * and all associated data were lost (For instance because * the device went to sleep). We need to sleep until we * get a new surface. */ return mEgl.eglGetError() != EGL11.EGL_CONTEXT_LOST; } public void finish() { if (mEglSurface != null) { mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT); mEgl.eglDestroySurface(mEglDisplay, mEglSurface); mEglSurface = null; } if (mEglContext != null) { mEgl.eglDestroyContext(mEglDisplay, mEglContext); mEglContext = null; } if (mEglDisplay != null) { mEgl.eglTerminate(mEglDisplay); mEglDisplay = null; } } EGL10 mEgl; EGLDisplay mEglDisplay; EGLSurface mEglSurface; EGLConfig mEglConfig; EGLContext mEglContext; } /** * A generic GL Thread. Takes care of initializing EGL and GL. Delegates * to a Renderer instance to do the actual drawing. * */ class GLThread extends Thread { GLThread(Renderer renderer) { super(); mDone = false; mWidth = 0; mHeight = 0; mRenderer = renderer; setName("GLThread"); } @Override public void run() { /* * When the android framework launches a second instance of * an activity, the new instance's onCreate() method may be * called before the first instance returns from onDestroy(). * * This semaphore ensures that only one instance at a time * accesses EGL. */ try { try { sEglSemaphore.acquire(); } catch (InterruptedException e) { return; } guardedRun(); } catch (InterruptedException e) { // fall thru and exit normally } finally { sEglSemaphore.release(); } } private void guardedRun() throws InterruptedException { mEglHelper = new EglHelper(); /* * Specify a configuration for our opengl session * and grab the first configuration that matches is */ int[] configSpec = mRenderer.getConfigSpec(); mEglHelper.start(configSpec); GL10 gl = null; boolean tellRendererSurfaceCreated = true; boolean tellRendererSurfaceChanged = true; /* * This is our main activity thread's loop, we go until * asked to quit. */ while (!mDone) { /* * Update the asynchronous state (window size) */ int w, h; boolean changed; boolean needStart = false; synchronized (this) { Runnable r; while ((r = getEvent()) != null) { r.run(); } if (mPaused) { mEglHelper.finish(); needStart = true; } if(needToWait()) { while (needToWait()) { wait(); } } if (mDone) { break; } changed = mSizeChanged; w = mWidth; h = mHeight; mSizeChanged = false; } if (needStart) { mEglHelper.start(configSpec); tellRendererSurfaceCreated = true; changed = true; } if (changed) { gl = (GL10) mEglHelper.createSurface(mHolder); tellRendererSurfaceChanged = true; } if (tellRendererSurfaceCreated) { mRenderer.surfaceCreated(gl); tellRendererSurfaceCreated = false; } if (tellRendererSurfaceChanged) { mRenderer.sizeChanged(gl, w, h); tellRendererSurfaceChanged = false; } if ((w > 0) && (h > 0)) { /* draw a frame here */ mRenderer.drawFrame(gl); /* * Once we're done with GL, we need to call swapBuffers() * to instruct the system to display the rendered frame */ mEglHelper.swap(); } } /* * clean-up everything... */ mEglHelper.finish(); } private boolean needToWait() { return (mPaused || (! mHasFocus) || (! mHasSurface) || mContextLost) && (! mDone); } public void surfaceCreated() { synchronized(this) { mHasSurface = true; mContextLost = false; notify(); } } public void surfaceDestroyed() { synchronized(this) { mHasSurface = false; notify(); } } public void onPause() { synchronized (this) { mPaused = true; } } public void onResume() { synchronized (this) { mPaused = false; notify(); } } public void onWindowFocusChanged(boolean hasFocus) { synchronized (this) { mHasFocus = hasFocus; if (mHasFocus == true) { notify(); } } } public void onWindowResize(int w, int h) { synchronized (this) { mWidth = w; mHeight = h; mSizeChanged = true; } } public void requestExitAndWait() { // don't call this from GLThread thread or it is a guaranteed // deadlock! synchronized(this) { mDone = true; notify(); } try { join(); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } } /** * Queue an "event" to be run on the GL rendering thread. * @param r the runnable to be run on the GL rendering thread. */ public void queueEvent(Runnable r) { synchronized(this) { mEventQueue.add(r); } } private Runnable getEvent() { synchronized(this) { if (mEventQueue.size() > 0) { return mEventQueue.remove(0); } } return null; } private boolean mDone; private boolean mPaused; private boolean mHasFocus; private boolean mHasSurface; private boolean mContextLost; private int mWidth; private int mHeight; private Renderer mRenderer; private ArrayList<Runnable> mEventQueue = new ArrayList<Runnable>(); private EglHelper mEglHelper; } private static final Semaphore sEglSemaphore = new Semaphore(1); private boolean mSizeChanged = true; private SurfaceHolder mHolder; private GLThread mGLThread; private GLWrapper mGLWrapper; }
Java
/* * Copyright (C) 2007 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.opengles.spritetext; import android.util.Log; import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.nio.ShortBuffer; import javax.microedition.khronos.opengles.GL; import javax.microedition.khronos.opengles.GL10; import javax.microedition.khronos.opengles.GL10Ext; import javax.microedition.khronos.opengles.GL11; import javax.microedition.khronos.opengles.GL11Ext; /** * Allows retrieving the current matrix even if the current OpenGL ES * driver does not support retrieving the current matrix. * * Note: the actual matrix may differ from the retrieved matrix, due * to differences in the way the math is implemented by GLMatrixWrapper * as compared to the way the math is implemented by the OpenGL ES * driver. */ class MatrixTrackingGL implements GL, GL10, GL10Ext, GL11, GL11Ext { private GL10 mgl; private GL10Ext mgl10Ext; private GL11 mgl11; private GL11Ext mgl11Ext; private int mMatrixMode; private MatrixStack mCurrent; private MatrixStack mModelView; private MatrixStack mTexture; private MatrixStack mProjection; private final static boolean _check = false; ByteBuffer mByteBuffer; FloatBuffer mFloatBuffer; float[] mCheckA; float[] mCheckB; public MatrixTrackingGL(GL gl) { mgl = (GL10) gl; if (gl instanceof GL10Ext) { mgl10Ext = (GL10Ext) gl; } if (gl instanceof GL11) { mgl11 = (GL11) gl; } if (gl instanceof GL11Ext) { mgl11Ext = (GL11Ext) gl; } mModelView = new MatrixStack(); mProjection = new MatrixStack(); mTexture = new MatrixStack(); mCurrent = mModelView; mMatrixMode = GL10.GL_MODELVIEW; } // --------------------------------------------------------------------- // GL10 methods: public void glActiveTexture(int texture) { mgl.glActiveTexture(texture); } public void glAlphaFunc(int func, float ref) { mgl.glAlphaFunc(func, ref); } public void glAlphaFuncx(int func, int ref) { mgl.glAlphaFuncx(func, ref); } public void glBindTexture(int target, int texture) { mgl.glBindTexture(target, texture); } public void glBlendFunc(int sfactor, int dfactor) { mgl.glBlendFunc(sfactor, dfactor); } public void glClear(int mask) { mgl.glClear(mask); } public void glClearColor(float red, float green, float blue, float alpha) { mgl.glClearColor(red, green, blue, alpha); } public void glClearColorx(int red, int green, int blue, int alpha) { mgl.glClearColorx(red, green, blue, alpha); } public void glClearDepthf(float depth) { mgl.glClearDepthf(depth); } public void glClearDepthx(int depth) { mgl.glClearDepthx(depth); } public void glClearStencil(int s) { mgl.glClearStencil(s); } public void glClientActiveTexture(int texture) { mgl.glClientActiveTexture(texture); } public void glColor4f(float red, float green, float blue, float alpha) { mgl.glColor4f(red, green, blue, alpha); } public void glColor4x(int red, int green, int blue, int alpha) { mgl.glColor4x(red, green, blue, alpha); } public void glColorMask(boolean red, boolean green, boolean blue, boolean alpha) { mgl.glColorMask(red, green, blue, alpha); } public void glColorPointer(int size, int type, int stride, Buffer pointer) { mgl.glColorPointer(size, type, stride, pointer); } public void glCompressedTexImage2D(int target, int level, int internalformat, int width, int height, int border, int imageSize, Buffer data) { mgl.glCompressedTexImage2D(target, level, internalformat, width, height, border, imageSize, data); } public void glCompressedTexSubImage2D(int target, int level, int xoffset, int yoffset, int width, int height, int format, int imageSize, Buffer data) { mgl.glCompressedTexSubImage2D(target, level, xoffset, yoffset, width, height, format, imageSize, data); } public void glCopyTexImage2D(int target, int level, int internalformat, int x, int y, int width, int height, int border) { mgl.glCopyTexImage2D(target, level, internalformat, x, y, width, height, border); } public void glCopyTexSubImage2D(int target, int level, int xoffset, int yoffset, int x, int y, int width, int height) { mgl.glCopyTexSubImage2D(target, level, xoffset, yoffset, x, y, width, height); } public void glCullFace(int mode) { mgl.glCullFace(mode); } public void glDeleteTextures(int n, int[] textures, int offset) { mgl.glDeleteTextures(n, textures, offset); } public void glDeleteTextures(int n, IntBuffer textures) { mgl.glDeleteTextures(n, textures); } public void glDepthFunc(int func) { mgl.glDepthFunc(func); } public void glDepthMask(boolean flag) { mgl.glDepthMask(flag); } public void glDepthRangef(float near, float far) { mgl.glDepthRangef(near, far); } public void glDepthRangex(int near, int far) { mgl.glDepthRangex(near, far); } public void glDisable(int cap) { mgl.glDisable(cap); } public void glDisableClientState(int array) { mgl.glDisableClientState(array); } public void glDrawArrays(int mode, int first, int count) { mgl.glDrawArrays(mode, first, count); } public void glDrawElements(int mode, int count, int type, Buffer indices) { mgl.glDrawElements(mode, count, type, indices); } public void glEnable(int cap) { mgl.glEnable(cap); } public void glEnableClientState(int array) { mgl.glEnableClientState(array); } public void glFinish() { mgl.glFinish(); } public void glFlush() { mgl.glFlush(); } public void glFogf(int pname, float param) { mgl.glFogf(pname, param); } public void glFogfv(int pname, float[] params, int offset) { mgl.glFogfv(pname, params, offset); } public void glFogfv(int pname, FloatBuffer params) { mgl.glFogfv(pname, params); } public void glFogx(int pname, int param) { mgl.glFogx(pname, param); } public void glFogxv(int pname, int[] params, int offset) { mgl.glFogxv(pname, params, offset); } public void glFogxv(int pname, IntBuffer params) { mgl.glFogxv(pname, params); } public void glFrontFace(int mode) { mgl.glFrontFace(mode); } public void glFrustumf(float left, float right, float bottom, float top, float near, float far) { mCurrent.glFrustumf(left, right, bottom, top, near, far); mgl.glFrustumf(left, right, bottom, top, near, far); if ( _check) check(); } public void glFrustumx(int left, int right, int bottom, int top, int near, int far) { mCurrent.glFrustumx(left, right, bottom, top, near, far); mgl.glFrustumx(left, right, bottom, top, near, far); if ( _check) check(); } public void glGenTextures(int n, int[] textures, int offset) { mgl.glGenTextures(n, textures, offset); } public void glGenTextures(int n, IntBuffer textures) { mgl.glGenTextures(n, textures); } public int glGetError() { int result = mgl.glGetError(); return result; } public void glGetIntegerv(int pname, int[] params, int offset) { mgl.glGetIntegerv(pname, params, offset); } public void glGetIntegerv(int pname, IntBuffer params) { mgl.glGetIntegerv(pname, params); } public String glGetString(int name) { String result = mgl.glGetString(name); return result; } public void glHint(int target, int mode) { mgl.glHint(target, mode); } public void glLightModelf(int pname, float param) { mgl.glLightModelf(pname, param); } public void glLightModelfv(int pname, float[] params, int offset) { mgl.glLightModelfv(pname, params, offset); } public void glLightModelfv(int pname, FloatBuffer params) { mgl.glLightModelfv(pname, params); } public void glLightModelx(int pname, int param) { mgl.glLightModelx(pname, param); } public void glLightModelxv(int pname, int[] params, int offset) { mgl.glLightModelxv(pname, params, offset); } public void glLightModelxv(int pname, IntBuffer params) { mgl.glLightModelxv(pname, params); } public void glLightf(int light, int pname, float param) { mgl.glLightf(light, pname, param); } public void glLightfv(int light, int pname, float[] params, int offset) { mgl.glLightfv(light, pname, params, offset); } public void glLightfv(int light, int pname, FloatBuffer params) { mgl.glLightfv(light, pname, params); } public void glLightx(int light, int pname, int param) { mgl.glLightx(light, pname, param); } public void glLightxv(int light, int pname, int[] params, int offset) { mgl.glLightxv(light, pname, params, offset); } public void glLightxv(int light, int pname, IntBuffer params) { mgl.glLightxv(light, pname, params); } public void glLineWidth(float width) { mgl.glLineWidth(width); } public void glLineWidthx(int width) { mgl.glLineWidthx(width); } public void glLoadIdentity() { mCurrent.glLoadIdentity(); mgl.glLoadIdentity(); if ( _check) check(); } public void glLoadMatrixf(float[] m, int offset) { mCurrent.glLoadMatrixf(m, offset); mgl.glLoadMatrixf(m, offset); if ( _check) check(); } public void glLoadMatrixf(FloatBuffer m) { int position = m.position(); mCurrent.glLoadMatrixf(m); m.position(position); mgl.glLoadMatrixf(m); if ( _check) check(); } public void glLoadMatrixx(int[] m, int offset) { mCurrent.glLoadMatrixx(m, offset); mgl.glLoadMatrixx(m, offset); if ( _check) check(); } public void glLoadMatrixx(IntBuffer m) { int position = m.position(); mCurrent.glLoadMatrixx(m); m.position(position); mgl.glLoadMatrixx(m); if ( _check) check(); } public void glLogicOp(int opcode) { mgl.glLogicOp(opcode); } public void glMaterialf(int face, int pname, float param) { mgl.glMaterialf(face, pname, param); } public void glMaterialfv(int face, int pname, float[] params, int offset) { mgl.glMaterialfv(face, pname, params, offset); } public void glMaterialfv(int face, int pname, FloatBuffer params) { mgl.glMaterialfv(face, pname, params); } public void glMaterialx(int face, int pname, int param) { mgl.glMaterialx(face, pname, param); } public void glMaterialxv(int face, int pname, int[] params, int offset) { mgl.glMaterialxv(face, pname, params, offset); } public void glMaterialxv(int face, int pname, IntBuffer params) { mgl.glMaterialxv(face, pname, params); } public void glMatrixMode(int mode) { switch (mode) { case GL10.GL_MODELVIEW: mCurrent = mModelView; break; case GL10.GL_TEXTURE: mCurrent = mTexture; break; case GL10.GL_PROJECTION: mCurrent = mProjection; break; default: throw new IllegalArgumentException("Unknown matrix mode: " + mode); } mgl.glMatrixMode(mode); mMatrixMode = mode; if ( _check) check(); } public void glMultMatrixf(float[] m, int offset) { mCurrent.glMultMatrixf(m, offset); mgl.glMultMatrixf(m, offset); if ( _check) check(); } public void glMultMatrixf(FloatBuffer m) { int position = m.position(); mCurrent.glMultMatrixf(m); m.position(position); mgl.glMultMatrixf(m); if ( _check) check(); } public void glMultMatrixx(int[] m, int offset) { mCurrent.glMultMatrixx(m, offset); mgl.glMultMatrixx(m, offset); if ( _check) check(); } public void glMultMatrixx(IntBuffer m) { int position = m.position(); mCurrent.glMultMatrixx(m); m.position(position); mgl.glMultMatrixx(m); if ( _check) check(); } public void glMultiTexCoord4f(int target, float s, float t, float r, float q) { mgl.glMultiTexCoord4f(target, s, t, r, q); } public void glMultiTexCoord4x(int target, int s, int t, int r, int q) { mgl.glMultiTexCoord4x(target, s, t, r, q); } public void glNormal3f(float nx, float ny, float nz) { mgl.glNormal3f(nx, ny, nz); } public void glNormal3x(int nx, int ny, int nz) { mgl.glNormal3x(nx, ny, nz); } public void glNormalPointer(int type, int stride, Buffer pointer) { mgl.glNormalPointer(type, stride, pointer); } public void glOrthof(float left, float right, float bottom, float top, float near, float far) { mCurrent.glOrthof(left, right, bottom, top, near, far); mgl.glOrthof(left, right, bottom, top, near, far); if ( _check) check(); } public void glOrthox(int left, int right, int bottom, int top, int near, int far) { mCurrent.glOrthox(left, right, bottom, top, near, far); mgl.glOrthox(left, right, bottom, top, near, far); if ( _check) check(); } public void glPixelStorei(int pname, int param) { mgl.glPixelStorei(pname, param); } public void glPointSize(float size) { mgl.glPointSize(size); } public void glPointSizex(int size) { mgl.glPointSizex(size); } public void glPolygonOffset(float factor, float units) { mgl.glPolygonOffset(factor, units); } public void glPolygonOffsetx(int factor, int units) { mgl.glPolygonOffsetx(factor, units); } public void glPopMatrix() { mCurrent.glPopMatrix(); mgl.glPopMatrix(); if ( _check) check(); } public void glPushMatrix() { mCurrent.glPushMatrix(); mgl.glPushMatrix(); if ( _check) check(); } public void glReadPixels(int x, int y, int width, int height, int format, int type, Buffer pixels) { mgl.glReadPixels(x, y, width, height, format, type, pixels); } public void glRotatef(float angle, float x, float y, float z) { mCurrent.glRotatef(angle, x, y, z); mgl.glRotatef(angle, x, y, z); if ( _check) check(); } public void glRotatex(int angle, int x, int y, int z) { mCurrent.glRotatex(angle, x, y, z); mgl.glRotatex(angle, x, y, z); if ( _check) check(); } public void glSampleCoverage(float value, boolean invert) { mgl.glSampleCoverage(value, invert); } public void glSampleCoveragex(int value, boolean invert) { mgl.glSampleCoveragex(value, invert); } public void glScalef(float x, float y, float z) { mCurrent.glScalef(x, y, z); mgl.glScalef(x, y, z); if ( _check) check(); } public void glScalex(int x, int y, int z) { mCurrent.glScalex(x, y, z); mgl.glScalex(x, y, z); if ( _check) check(); } public void glScissor(int x, int y, int width, int height) { mgl.glScissor(x, y, width, height); } public void glShadeModel(int mode) { mgl.glShadeModel(mode); } public void glStencilFunc(int func, int ref, int mask) { mgl.glStencilFunc(func, ref, mask); } public void glStencilMask(int mask) { mgl.glStencilMask(mask); } public void glStencilOp(int fail, int zfail, int zpass) { mgl.glStencilOp(fail, zfail, zpass); } public void glTexCoordPointer(int size, int type, int stride, Buffer pointer) { mgl.glTexCoordPointer(size, type, stride, pointer); } public void glTexEnvf(int target, int pname, float param) { mgl.glTexEnvf(target, pname, param); } public void glTexEnvfv(int target, int pname, float[] params, int offset) { mgl.glTexEnvfv(target, pname, params, offset); } public void glTexEnvfv(int target, int pname, FloatBuffer params) { mgl.glTexEnvfv(target, pname, params); } public void glTexEnvx(int target, int pname, int param) { mgl.glTexEnvx(target, pname, param); } public void glTexEnvxv(int target, int pname, int[] params, int offset) { mgl.glTexEnvxv(target, pname, params, offset); } public void glTexEnvxv(int target, int pname, IntBuffer params) { mgl.glTexEnvxv(target, pname, params); } public void glTexImage2D(int target, int level, int internalformat, int width, int height, int border, int format, int type, Buffer pixels) { mgl.glTexImage2D(target, level, internalformat, width, height, border, format, type, pixels); } public void glTexParameterf(int target, int pname, float param) { mgl.glTexParameterf(target, pname, param); } public void glTexParameterx(int target, int pname, int param) { mgl.glTexParameterx(target, pname, param); } public void glTexParameteriv(int target, int pname, int[] params, int offset) { mgl11.glTexParameteriv(target, pname, params, offset); } public void glTexParameteriv(int target, int pname, IntBuffer params) { mgl11.glTexParameteriv(target, pname, params); } public void glTexSubImage2D(int target, int level, int xoffset, int yoffset, int width, int height, int format, int type, Buffer pixels) { mgl.glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixels); } public void glTranslatef(float x, float y, float z) { mCurrent.glTranslatef(x, y, z); mgl.glTranslatef(x, y, z); if ( _check) check(); } public void glTranslatex(int x, int y, int z) { mCurrent.glTranslatex(x, y, z); mgl.glTranslatex(x, y, z); if ( _check) check(); } public void glVertexPointer(int size, int type, int stride, Buffer pointer) { mgl.glVertexPointer(size, type, stride, pointer); } public void glViewport(int x, int y, int width, int height) { mgl.glViewport(x, y, width, height); } public void glClipPlanef(int plane, float[] equation, int offset) { mgl11.glClipPlanef(plane, equation, offset); } public void glClipPlanef(int plane, FloatBuffer equation) { mgl11.glClipPlanef(plane, equation); } public void glClipPlanex(int plane, int[] equation, int offset) { mgl11.glClipPlanex(plane, equation, offset); } public void glClipPlanex(int plane, IntBuffer equation) { mgl11.glClipPlanex(plane, equation); } // Draw Texture Extension public void glDrawTexfOES(float x, float y, float z, float width, float height) { mgl11Ext.glDrawTexfOES(x, y, z, width, height); } public void glDrawTexfvOES(float[] coords, int offset) { mgl11Ext.glDrawTexfvOES(coords, offset); } public void glDrawTexfvOES(FloatBuffer coords) { mgl11Ext.glDrawTexfvOES(coords); } public void glDrawTexiOES(int x, int y, int z, int width, int height) { mgl11Ext.glDrawTexiOES(x, y, z, width, height); } public void glDrawTexivOES(int[] coords, int offset) { mgl11Ext.glDrawTexivOES(coords, offset); } public void glDrawTexivOES(IntBuffer coords) { mgl11Ext.glDrawTexivOES(coords); } public void glDrawTexsOES(short x, short y, short z, short width, short height) { mgl11Ext.glDrawTexsOES(x, y, z, width, height); } public void glDrawTexsvOES(short[] coords, int offset) { mgl11Ext.glDrawTexsvOES(coords, offset); } public void glDrawTexsvOES(ShortBuffer coords) { mgl11Ext.glDrawTexsvOES(coords); } public void glDrawTexxOES(int x, int y, int z, int width, int height) { mgl11Ext.glDrawTexxOES(x, y, z, width, height); } public void glDrawTexxvOES(int[] coords, int offset) { mgl11Ext.glDrawTexxvOES(coords, offset); } public void glDrawTexxvOES(IntBuffer coords) { mgl11Ext.glDrawTexxvOES(coords); } public int glQueryMatrixxOES(int[] mantissa, int mantissaOffset, int[] exponent, int exponentOffset) { return mgl10Ext.glQueryMatrixxOES(mantissa, mantissaOffset, exponent, exponentOffset); } public int glQueryMatrixxOES(IntBuffer mantissa, IntBuffer exponent) { return mgl10Ext.glQueryMatrixxOES(mantissa, exponent); } // Unsupported GL11 methods public void glBindBuffer(int target, int buffer) { throw new UnsupportedOperationException(); } public void glBufferData(int target, int size, Buffer data, int usage) { throw new UnsupportedOperationException(); } public void glBufferSubData(int target, int offset, int size, Buffer data) { throw new UnsupportedOperationException(); } public void glColor4ub(byte red, byte green, byte blue, byte alpha) { throw new UnsupportedOperationException(); } public void glDeleteBuffers(int n, int[] buffers, int offset) { throw new UnsupportedOperationException(); } public void glDeleteBuffers(int n, IntBuffer buffers) { throw new UnsupportedOperationException(); } public void glGenBuffers(int n, int[] buffers, int offset) { throw new UnsupportedOperationException(); } public void glGenBuffers(int n, IntBuffer buffers) { throw new UnsupportedOperationException(); } public void glGetBooleanv(int pname, boolean[] params, int offset) { throw new UnsupportedOperationException(); } public void glGetBooleanv(int pname, IntBuffer params) { throw new UnsupportedOperationException(); } public void glGetBufferParameteriv(int target, int pname, int[] params, int offset) { throw new UnsupportedOperationException(); } public void glGetBufferParameteriv(int target, int pname, IntBuffer params) { throw new UnsupportedOperationException(); } public void glGetClipPlanef(int pname, float[] eqn, int offset) { throw new UnsupportedOperationException(); } public void glGetClipPlanef(int pname, FloatBuffer eqn) { throw new UnsupportedOperationException(); } public void glGetClipPlanex(int pname, int[] eqn, int offset) { throw new UnsupportedOperationException(); } public void glGetClipPlanex(int pname, IntBuffer eqn) { throw new UnsupportedOperationException(); } public void glGetFixedv(int pname, int[] params, int offset) { throw new UnsupportedOperationException(); } public void glGetFixedv(int pname, IntBuffer params) { throw new UnsupportedOperationException(); } public void glGetFloatv(int pname, float[] params, int offset) { throw new UnsupportedOperationException(); } public void glGetFloatv(int pname, FloatBuffer params) { throw new UnsupportedOperationException(); } public void glGetLightfv(int light, int pname, float[] params, int offset) { throw new UnsupportedOperationException(); } public void glGetLightfv(int light, int pname, FloatBuffer params) { throw new UnsupportedOperationException(); } public void glGetLightxv(int light, int pname, int[] params, int offset) { throw new UnsupportedOperationException(); } public void glGetLightxv(int light, int pname, IntBuffer params) { throw new UnsupportedOperationException(); } public void glGetMaterialfv(int face, int pname, float[] params, int offset) { throw new UnsupportedOperationException(); } public void glGetMaterialfv(int face, int pname, FloatBuffer params) { throw new UnsupportedOperationException(); } public void glGetMaterialxv(int face, int pname, int[] params, int offset) { throw new UnsupportedOperationException(); } public void glGetMaterialxv(int face, int pname, IntBuffer params) { throw new UnsupportedOperationException(); } public void glGetTexEnviv(int env, int pname, int[] params, int offset) { throw new UnsupportedOperationException(); } public void glGetTexEnviv(int env, int pname, IntBuffer params) { throw new UnsupportedOperationException(); } public void glGetTexEnvxv(int env, int pname, int[] params, int offset) { throw new UnsupportedOperationException(); } public void glGetTexEnvxv(int env, int pname, IntBuffer params) { throw new UnsupportedOperationException(); } public void glGetTexParameterfv(int target, int pname, float[] params, int offset) { throw new UnsupportedOperationException(); } public void glGetTexParameterfv(int target, int pname, FloatBuffer params) { throw new UnsupportedOperationException(); } public void glGetTexParameteriv(int target, int pname, int[] params, int offset) { throw new UnsupportedOperationException(); } public void glGetTexParameteriv(int target, int pname, IntBuffer params) { throw new UnsupportedOperationException(); } public void glGetTexParameterxv(int target, int pname, int[] params, int offset) { throw new UnsupportedOperationException(); } public void glGetTexParameterxv(int target, int pname, IntBuffer params) { throw new UnsupportedOperationException(); } public boolean glIsBuffer(int buffer) { throw new UnsupportedOperationException(); } public boolean glIsEnabled(int cap) { throw new UnsupportedOperationException(); } public boolean glIsTexture(int texture) { throw new UnsupportedOperationException(); } public void glPointParameterf(int pname, float param) { throw new UnsupportedOperationException(); } public void glPointParameterfv(int pname, float[] params, int offset) { throw new UnsupportedOperationException(); } public void glPointParameterfv(int pname, FloatBuffer params) { throw new UnsupportedOperationException(); } public void glPointParameterx(int pname, int param) { throw new UnsupportedOperationException(); } public void glPointParameterxv(int pname, int[] params, int offset) { throw new UnsupportedOperationException(); } public void glPointParameterxv(int pname, IntBuffer params) { throw new UnsupportedOperationException(); } public void glPointSizePointerOES(int type, int stride, Buffer pointer) { throw new UnsupportedOperationException(); } public void glTexEnvi(int target, int pname, int param) { throw new UnsupportedOperationException(); } public void glTexEnviv(int target, int pname, int[] params, int offset) { throw new UnsupportedOperationException(); } public void glTexEnviv(int target, int pname, IntBuffer params) { throw new UnsupportedOperationException(); } public void glTexParameterfv(int target, int pname, float[] params, int offset) { throw new UnsupportedOperationException(); } public void glTexParameterfv(int target, int pname, FloatBuffer params) { throw new UnsupportedOperationException(); } public void glTexParameteri(int target, int pname, int param) { throw new UnsupportedOperationException(); } public void glTexParameterxv(int target, int pname, int[] params, int offset) { throw new UnsupportedOperationException(); } public void glTexParameterxv(int target, int pname, IntBuffer params) { throw new UnsupportedOperationException(); } public void glColorPointer(int size, int type, int stride, int offset) { throw new UnsupportedOperationException(); } public void glDrawElements(int mode, int count, int type, int offset) { throw new UnsupportedOperationException(); } public void glGetPointerv(int pname, Buffer[] params) { throw new UnsupportedOperationException(); } public void glNormalPointer(int type, int stride, int offset) { throw new UnsupportedOperationException(); } public void glTexCoordPointer(int size, int type, int stride, int offset) { throw new UnsupportedOperationException(); } public void glVertexPointer(int size, int type, int stride, int offset) { throw new UnsupportedOperationException(); } public void glCurrentPaletteMatrixOES(int matrixpaletteindex) { throw new UnsupportedOperationException(); } public void glLoadPaletteFromModelViewMatrixOES() { throw new UnsupportedOperationException(); } public void glMatrixIndexPointerOES(int size, int type, int stride, Buffer pointer) { throw new UnsupportedOperationException(); } public void glMatrixIndexPointerOES(int size, int type, int stride, int offset) { throw new UnsupportedOperationException(); } public void glWeightPointerOES(int size, int type, int stride, Buffer pointer) { throw new UnsupportedOperationException(); } public void glWeightPointerOES(int size, int type, int stride, int offset) { throw new UnsupportedOperationException(); } /** * Get the current matrix */ public void getMatrix(float[] m, int offset) { mCurrent.getMatrix(m, offset); } /** * Get the current matrix mode */ public int getMatrixMode() { return mMatrixMode; } private void check() { int oesMode; switch (mMatrixMode) { case GL_MODELVIEW: oesMode = GL11.GL_MODELVIEW_MATRIX_FLOAT_AS_INT_BITS_OES; break; case GL_PROJECTION: oesMode = GL11.GL_PROJECTION_MATRIX_FLOAT_AS_INT_BITS_OES; break; case GL_TEXTURE: oesMode = GL11.GL_TEXTURE_MATRIX_FLOAT_AS_INT_BITS_OES; break; default: throw new IllegalArgumentException("Unknown matrix mode"); } if ( mByteBuffer == null) { mCheckA = new float[16]; mCheckB = new float[16]; mByteBuffer = ByteBuffer.allocateDirect(64); mByteBuffer.order(ByteOrder.nativeOrder()); mFloatBuffer = mByteBuffer.asFloatBuffer(); } mgl.glGetIntegerv(oesMode, mByteBuffer.asIntBuffer()); for(int i = 0; i < 16; i++) { mCheckB[i] = mFloatBuffer.get(i); } mCurrent.getMatrix(mCheckA, 0); boolean fail = false; for(int i = 0; i < 16; i++) { if (mCheckA[i] != mCheckB[i]) { Log.d("GLMatWrap", "i:" + i + " a:" + mCheckA[i] + " a:" + mCheckB[i]); fail = true; } } if (fail) { throw new IllegalArgumentException("Matrix math difference."); } } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.opengles.spritetext; import javax.microedition.khronos.opengles.GL; import android.app.Activity; import android.os.Bundle; public class SpriteTextActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mGLView = (GLView) findViewById(R.id.glview); mGLView.setGLWrapper(new GLView.GLWrapper() { public GL wrap(GL gl) { return new MatrixTrackingGL(gl); }}); mGLView.setRenderer(new SpriteTextRenderer(this)); mGLView.requestFocus(); } @Override protected void onPause() { super.onPause(); mGLView.onPause(); } @Override protected void onResume() { super.onResume(); mGLView.onResume(); } private GLView mGLView; }
Java
/* * Copyright (C) 2007 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.opengles.spritetext; import java.nio.CharBuffer; import java.nio.FloatBuffer; import javax.microedition.khronos.opengles.GL10; /** * A 2D rectangular mesh. Can be drawn textured or untextured. * */ class Grid { public Grid(int w, int h) { if (w < 0 || w >= 65536) { throw new IllegalArgumentException("w"); } if (h < 0 || h >= 65536) { throw new IllegalArgumentException("h"); } if (w * h >= 65536) { throw new IllegalArgumentException("w * h >= 65536"); } mW = w; mH = h; int size = w * h; mVertexArray = new float[size * 3]; mVertexBuffer = FloatBuffer.wrap(mVertexArray); mTexCoordArray = new float[size * 2]; mTexCoordBuffer = FloatBuffer.wrap(mTexCoordArray); int quadW = mW - 1; int quadH = mH - 1; int quadCount = quadW * quadH; int indexCount = quadCount * 6; mIndexCount = indexCount; char[] indexArray = new char[indexCount]; /* * Initialize triangle list mesh. * * [0]-----[ 1] ... * | / | * | / | * | / | * [w]-----[w+1] ... * | | * */ { int i = 0; for (int y = 0; y < quadH; y++) { for (int x = 0; x < quadW; x++) { char a = (char) (y * mW + x); char b = (char) (y * mW + x + 1); char c = (char) ((y + 1) * mW + x); char d = (char) ((y + 1) * mW + x + 1); indexArray[i++] = a; indexArray[i++] = b; indexArray[i++] = c; indexArray[i++] = b; indexArray[i++] = c; indexArray[i++] = d; } } } mIndexBuffer = CharBuffer.wrap(indexArray); } void set(int i, int j, float x, float y, float z, float u, float v) { if (i < 0 || i >= mW) { throw new IllegalArgumentException("i"); } if (j < 0 || j >= mH) { throw new IllegalArgumentException("j"); } int index = mW * j + i; int posIndex = index * 3; mVertexArray[posIndex] = x; mVertexArray[posIndex + 1] = y; mVertexArray[posIndex + 2] = z; int texIndex = index * 2; mTexCoordArray[texIndex] = u; mTexCoordArray[texIndex + 1] = v; } public void draw(GL10 gl, boolean useTexture) { gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); gl.glVertexPointer(3, GL10.GL_FLOAT, 0, mVertexBuffer); if (useTexture) { gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY); gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, mTexCoordBuffer); gl.glEnable(GL10.GL_TEXTURE_2D); } else { gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY); gl.glDisable(GL10.GL_TEXTURE_2D); } gl.glDrawElements(GL10.GL_TRIANGLES, mIndexCount, GL10.GL_UNSIGNED_SHORT, mIndexBuffer); gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); } private FloatBuffer mVertexBuffer; private float[] mVertexArray; private FloatBuffer mTexCoordBuffer; private float[] mTexCoordArray; private CharBuffer mIndexBuffer; private int mW; private int mH; private int mIndexCount; }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.opengles.triangle; import javax.microedition.khronos.opengles.GL; import android.app.Activity; import android.opengl.GLDebugHelper; import android.os.Bundle; public class TriangleActivity extends Activity { /** Set to true to enable checking of the OpenGL error code after every OpenGL call. Set to * false for faster code. * */ private final static boolean DEBUG_CHECK_GL_ERROR = true; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mGLView = (GLView) findViewById(R.id.glview); if (DEBUG_CHECK_GL_ERROR) { mGLView.setGLWrapper(new GLView.GLWrapper() { public GL wrap(GL gl) { return GLDebugHelper.wrap(gl, GLDebugHelper.CONFIG_CHECK_GL_ERROR, null); }}); } mGLView.setRenderer(new TriangleRenderer(this)); mGLView.requestFocus(); } @Override protected void onPause() { super.onPause(); mGLView.onPause(); } @Override protected void onResume() { super.onResume(); mGLView.onResume(); } private GLView mGLView; }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.opengles.triangle; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import java.nio.ShortBuffer; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.opengl.GLU; import android.opengl.GLUtils; import android.os.SystemClock; import javax.microedition.khronos.egl.EGL10; import javax.microedition.khronos.opengles.GL10; public class TriangleRenderer implements GLView.Renderer{ public TriangleRenderer(Context context) { mContext = context; mTriangle = new Triangle(); } public int[] getConfigSpec() { // We don't need a depth buffer, and don't care about our // color depth. int[] configSpec = { EGL10.EGL_DEPTH_SIZE, 0, EGL10.EGL_NONE }; return configSpec; } public void surfaceCreated(GL10 gl) { /* * By default, OpenGL enables features that improve quality * but reduce performance. One might want to tweak that * especially on software renderer. */ gl.glDisable(GL10.GL_DITHER); /* * Some one-time OpenGL initialization can be made here * probably based on features of this particular context */ gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_FASTEST); gl.glClearColor(.5f, .5f, .5f, 1); gl.glShadeModel(GL10.GL_SMOOTH); gl.glEnable(GL10.GL_DEPTH_TEST); gl.glEnable(GL10.GL_TEXTURE_2D); /* * Create our texture. This has to be done each time the * surface is created. */ int[] textures = new int[1]; gl.glGenTextures(1, textures, 0); mTextureID = textures[0]; gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureID); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_CLAMP_TO_EDGE); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_CLAMP_TO_EDGE); gl.glTexEnvf(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE, GL10.GL_REPLACE); InputStream is = mContext.getResources() .openRawResource(R.drawable.tex); Bitmap bitmap; try { bitmap = BitmapFactory.decodeStream(is); } finally { try { is.close(); } catch(IOException e) { // Ignore. } } GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0); bitmap.recycle(); } public void drawFrame(GL10 gl) { /* * By default, OpenGL enables features that improve quality * but reduce performance. One might want to tweak that * especially on software renderer. */ gl.glDisable(GL10.GL_DITHER); gl.glTexEnvx(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE, GL10.GL_MODULATE); /* * Usually, the first thing one might want to do is to clear * the screen. The most efficient way of doing this is to use * glClear(). */ gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); /* * Now we're ready to draw some 3D objects */ gl.glMatrixMode(GL10.GL_MODELVIEW); gl.glLoadIdentity(); GLU.gluLookAt(gl, 0, 0, -5, 0f, 0f, 0f, 0f, 1.0f, 0.0f); gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY); gl.glActiveTexture(GL10.GL_TEXTURE0); gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureID); gl.glTexParameterx(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_REPEAT); gl.glTexParameterx(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_REPEAT); long time = SystemClock.uptimeMillis() % 4000L; float angle = 0.090f * ((int) time); gl.glRotatef(angle, 0, 0, 1.0f); mTriangle.draw(gl); } public void sizeChanged(GL10 gl, int w, int h) { gl.glViewport(0, 0, w, h); /* * Set our projection matrix. This doesn't have to be done * each time we draw, but usually a new projection needs to * be set when the viewport is resized. */ float ratio = (float) w / h; gl.glMatrixMode(GL10.GL_PROJECTION); gl.glLoadIdentity(); gl.glFrustumf(-ratio, ratio, -1, 1, 3, 7); } private Context mContext; private Triangle mTriangle; private int mTextureID; } class Triangle { public Triangle() { // Buffers to be passed to gl*Pointer() functions // must be direct, i.e., they must be placed on the // native heap where the garbage collector cannot // move them. // // Buffers with multi-byte datatypes (e.g., short, int, float) // must have their byte order set to native order ByteBuffer vbb = ByteBuffer.allocateDirect(VERTS * 3 * 4); vbb.order(ByteOrder.nativeOrder()); mFVertexBuffer = vbb.asFloatBuffer(); ByteBuffer tbb = ByteBuffer.allocateDirect(VERTS * 2 * 4); tbb.order(ByteOrder.nativeOrder()); mTexBuffer = tbb.asFloatBuffer(); ByteBuffer ibb = ByteBuffer.allocateDirect(VERTS * 2); ibb.order(ByteOrder.nativeOrder()); mIndexBuffer = ibb.asShortBuffer(); // A unit-sided equalateral triangle centered on the origin. float[] coords = { // X, Y, Z -0.5f, -0.25f, 0, 0.5f, -0.25f, 0, 0.0f, 0.559016994f, 0 }; for (int i = 0; i < VERTS; i++) { for(int j = 0; j < 3; j++) { mFVertexBuffer.put(coords[i*3+j] * 2.0f); } } for (int i = 0; i < VERTS; i++) { for(int j = 0; j < 2; j++) { mTexBuffer.put(coords[i*3+j] * 2.0f + 0.5f); } } for(int i = 0; i < VERTS; i++) { mIndexBuffer.put((short) i); } mFVertexBuffer.position(0); mTexBuffer.position(0); mIndexBuffer.position(0); } public void draw(GL10 gl) { gl.glFrontFace(GL10.GL_CCW); gl.glVertexPointer(3, GL10.GL_FLOAT, 0, mFVertexBuffer); gl.glEnable(GL10.GL_TEXTURE_2D); gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, mTexBuffer); gl.glDrawElements(GL10.GL_TRIANGLE_STRIP, VERTS, GL10.GL_UNSIGNED_SHORT, mIndexBuffer); } private final static int VERTS = 3; private FloatBuffer mFVertexBuffer; private FloatBuffer mTexBuffer; private ShortBuffer mIndexBuffer; }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.opengles.triangle; import android.content.Context; import android.util.AttributeSet; import android.view.SurfaceHolder; import android.view.SurfaceView; import java.util.ArrayList; import java.util.concurrent.Semaphore; import javax.microedition.khronos.egl.EGL10; import javax.microedition.khronos.egl.EGL11; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.egl.EGLContext; import javax.microedition.khronos.egl.EGLDisplay; import javax.microedition.khronos.egl.EGLSurface; import javax.microedition.khronos.opengles.GL; import javax.microedition.khronos.opengles.GL10; /** * An implementation of SurfaceView that uses the dedicated surface for * displaying an OpenGL animation. This allows the animation to run in a * separate thread, without requiring that it be driven by the update mechanism * of the view hierarchy. * * The application-specific rendering code is delegated to a GLView.Renderer * instance. */ class GLView extends SurfaceView implements SurfaceHolder.Callback { GLView(Context context) { super(context); init(); } public GLView(Context context, AttributeSet attrs) { super(context, attrs); init(); } private void init() { // Install a SurfaceHolder.Callback so we get notified when the // underlying surface is created and destroyed mHolder = getHolder(); mHolder.addCallback(this); mHolder.setType(SurfaceHolder.SURFACE_TYPE_GPU); } public void setGLWrapper(GLWrapper glWrapper) { mGLWrapper = glWrapper; } public void setRenderer(Renderer renderer) { mGLThread = new GLThread(renderer); mGLThread.start(); } public void surfaceCreated(SurfaceHolder holder) { mGLThread.surfaceCreated(); } public void surfaceDestroyed(SurfaceHolder holder) { // Surface will be destroyed when we return mGLThread.surfaceDestroyed(); } public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { // Surface size or format has changed. This should not happen in this // example. mGLThread.onWindowResize(w, h); } /** * Inform the view that the activity is paused. */ public void onPause() { mGLThread.onPause(); } /** * Inform the view that the activity is resumed. */ public void onResume() { mGLThread.onResume(); } /** * Inform the view that the window focus has changed. */ @Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); mGLThread.onWindowFocusChanged(hasFocus); } /** * Queue an "event" to be run on the GL rendering thread. * @param r the runnable to be run on the GL rendering thread. */ public void queueEvent(Runnable r) { mGLThread.queueEvent(r); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); mGLThread.requestExitAndWait(); } // ---------------------------------------------------------------------- public interface GLWrapper { GL wrap(GL gl); } // ---------------------------------------------------------------------- /** * A generic renderer interface. */ public interface Renderer { /** * @return the EGL configuration specification desired by the renderer. */ int[] getConfigSpec(); /** * Surface created. * Called when the surface is created. Called when the application * starts, and whenever the GPU is reinitialized. This will * typically happen when the device awakes after going to sleep. * Set your textures here. */ void surfaceCreated(GL10 gl); /** * Surface changed size. * Called after the surface is created and whenever * the OpenGL ES surface size changes. Set your viewport here. * @param gl * @param width * @param height */ void sizeChanged(GL10 gl, int width, int height); /** * Draw the current frame. * @param gl */ void drawFrame(GL10 gl); } /** * An EGL helper class. */ private class EglHelper { public EglHelper() { } /** * Initialize EGL for a given configuration spec. * @param configSpec */ public void start(int[] configSpec){ /* * Get an EGL instance */ mEgl = (EGL10) EGLContext.getEGL(); /* * Get to the default display. */ mEglDisplay = mEgl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY); /* * We can now initialize EGL for that display */ int[] version = new int[2]; mEgl.eglInitialize(mEglDisplay, version); EGLConfig[] configs = new EGLConfig[1]; int[] num_config = new int[1]; mEgl.eglChooseConfig(mEglDisplay, configSpec, configs, 1, num_config); mEglConfig = configs[0]; /* * Create an OpenGL ES context. This must be done only once, an * OpenGL context is a somewhat heavy object. */ mEglContext = mEgl.eglCreateContext(mEglDisplay, mEglConfig, EGL10.EGL_NO_CONTEXT, null); mEglSurface = null; } /* * Create and return an OpenGL surface */ public GL createSurface(SurfaceHolder holder) { /* * The window size has changed, so we need to create a new * surface. */ if (mEglSurface != null) { /* * Unbind and destroy the old EGL surface, if * there is one. */ mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT); mEgl.eglDestroySurface(mEglDisplay, mEglSurface); } /* * Create an EGL surface we can render into. */ mEglSurface = mEgl.eglCreateWindowSurface(mEglDisplay, mEglConfig, holder, null); /* * Before we can issue GL commands, we need to make sure * the context is current and bound to a surface. */ mEgl.eglMakeCurrent(mEglDisplay, mEglSurface, mEglSurface, mEglContext); GL gl = mEglContext.getGL(); if (mGLWrapper != null) { gl = mGLWrapper.wrap(gl); } return gl; } /** * Display the current render surface. * @return false if the context has been lost. */ public boolean swap() { mEgl.eglSwapBuffers(mEglDisplay, mEglSurface); /* * Always check for EGL_CONTEXT_LOST, which means the context * and all associated data were lost (For instance because * the device went to sleep). We need to sleep until we * get a new surface. */ return mEgl.eglGetError() != EGL11.EGL_CONTEXT_LOST; } public void finish() { if (mEglSurface != null) { mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT); mEgl.eglDestroySurface(mEglDisplay, mEglSurface); mEglSurface = null; } if (mEglContext != null) { mEgl.eglDestroyContext(mEglDisplay, mEglContext); mEglContext = null; } if (mEglDisplay != null) { mEgl.eglTerminate(mEglDisplay); mEglDisplay = null; } } EGL10 mEgl; EGLDisplay mEglDisplay; EGLSurface mEglSurface; EGLConfig mEglConfig; EGLContext mEglContext; } /** * A generic GL Thread. Takes care of initializing EGL and GL. Delegates * to a Renderer instance to do the actual drawing. * */ class GLThread extends Thread { GLThread(Renderer renderer) { super(); mDone = false; mWidth = 0; mHeight = 0; mRenderer = renderer; setName("GLThread"); } @Override public void run() { /* * When the android framework launches a second instance of * an activity, the new instance's onCreate() method may be * called before the first instance returns from onDestroy(). * * This semaphore ensures that only one instance at a time * accesses EGL. */ try { try { sEglSemaphore.acquire(); } catch (InterruptedException e) { return; } guardedRun(); } catch (InterruptedException e) { // fall thru and exit normally } finally { sEglSemaphore.release(); } } private void guardedRun() throws InterruptedException { mEglHelper = new EglHelper(); /* * Specify a configuration for our opengl session * and grab the first configuration that matches is */ int[] configSpec = mRenderer.getConfigSpec(); mEglHelper.start(configSpec); GL10 gl = null; boolean tellRendererSurfaceCreated = true; boolean tellRendererSurfaceChanged = true; /* * This is our main activity thread's loop, we go until * asked to quit. */ while (!mDone) { /* * Update the asynchronous state (window size) */ int w, h; boolean changed; boolean needStart = false; synchronized (this) { Runnable r; while ((r = getEvent()) != null) { r.run(); } if (mPaused) { mEglHelper.finish(); needStart = true; } if(needToWait()) { while (needToWait()) { wait(); } } if (mDone) { break; } changed = mSizeChanged; w = mWidth; h = mHeight; mSizeChanged = false; } if (needStart) { mEglHelper.start(configSpec); tellRendererSurfaceCreated = true; changed = true; } if (changed) { gl = (GL10) mEglHelper.createSurface(mHolder); tellRendererSurfaceChanged = true; } if (tellRendererSurfaceCreated) { mRenderer.surfaceCreated(gl); tellRendererSurfaceCreated = false; } if (tellRendererSurfaceChanged) { mRenderer.sizeChanged(gl, w, h); tellRendererSurfaceChanged = false; } if ((w > 0) && (h > 0)) { /* draw a frame here */ mRenderer.drawFrame(gl); /* * Once we're done with GL, we need to call swapBuffers() * to instruct the system to display the rendered frame */ mEglHelper.swap(); } } /* * clean-up everything... */ mEglHelper.finish(); } private boolean needToWait() { return (mPaused || (! mHasFocus) || (! mHasSurface) || mContextLost) && (! mDone); } public void surfaceCreated() { synchronized(this) { mHasSurface = true; mContextLost = false; notify(); } } public void surfaceDestroyed() { synchronized(this) { mHasSurface = false; notify(); } } public void onPause() { synchronized (this) { mPaused = true; } } public void onResume() { synchronized (this) { mPaused = false; notify(); } } public void onWindowFocusChanged(boolean hasFocus) { synchronized (this) { mHasFocus = hasFocus; if (mHasFocus == true) { notify(); } } } public void onWindowResize(int w, int h) { synchronized (this) { mWidth = w; mHeight = h; mSizeChanged = true; } } public void requestExitAndWait() { // don't call this from GLThread thread or it is a guaranteed // deadlock! synchronized(this) { mDone = true; notify(); } try { join(); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } } /** * Queue an "event" to be run on the GL rendering thread. * @param r the runnable to be run on the GL rendering thread. */ public void queueEvent(Runnable r) { synchronized(this) { mEventQueue.add(r); } } private Runnable getEvent() { synchronized(this) { if (mEventQueue.size() > 0) { return mEventQueue.remove(0); } } return null; } private boolean mDone; private boolean mPaused; private boolean mHasFocus; private boolean mHasSurface; private boolean mContextLost; private int mWidth; private int mHeight; private Renderer mRenderer; private ArrayList<Runnable> mEventQueue = new ArrayList<Runnable>(); private EglHelper mEglHelper; } private static final Semaphore sEglSemaphore = new Semaphore(1); private boolean mSizeChanged = true; private SurfaceHolder mHolder; private GLThread mGLThread; private GLWrapper mGLWrapper; }
Java
package com.google.clickin2dabeat; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import java.io.IOException; import java.io.InputStream; import java.net.URL; import java.net.URLConnection; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.FactoryConfigurationError; import javax.xml.parsers.ParserConfigurationException; /** * Checks for updates to the game. */ public class UpdateChecker { public String marketId; @SuppressWarnings("finally") public int getLatestVersionCode() { int version = 0; try { URLConnection cn; URL url = new URL( "http://apps-for-android.googlecode.com/svn/trunk/CLiCkin2DaBeaT/AndroidManifest.xml"); cn = url.openConnection(); cn.connect(); InputStream stream = cn.getInputStream(); DocumentBuilder docBuild = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document manifestDoc = docBuild.parse(stream); NodeList manifestNodeList = manifestDoc.getElementsByTagName("manifest"); String versionStr = manifestNodeList.item(0).getAttributes().getNamedItem("android:versionCode") .getNodeValue(); version = Integer.parseInt(versionStr); NodeList clcNodeList = manifestDoc.getElementsByTagName("clc"); marketId = clcNodeList.item(0).getAttributes().getNamedItem("marketId").getNodeValue(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ParserConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (FactoryConfigurationError e) { // TODO Auto-generated catch block e.printStackTrace(); } finally { return version; } } public void checkForNewerVersion(int currentVersion) { int latestVersion = getLatestVersionCode(); if (latestVersion > currentVersion) { } } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.clickin2dabeat; import android.graphics.Color; /** * Contains information about the when the beat should be displayed, where it * should be displayed, and what color it should be. */ public class Target { public double time; public int x; public int y; public int color; public Target(double timeToHit, int xpos, int ypos, String hexColor) { time = timeToHit; x = xpos; y = ypos; if (hexColor.length() == 6) { int r = Integer.parseInt(hexColor.substring(0, 2), 16); int g = Integer.parseInt(hexColor.substring(2, 4), 16); int b = Integer.parseInt(hexColor.substring(4, 6), 16); color = Color.rgb(r, g, b); } else { int colorChoice = ((int) (Math.random() * 100)) % 4; if (colorChoice == 0) { color = Color.RED; } else if (colorChoice == 1) { color = Color.GREEN; } else if (colorChoice == 2) { color = Color.BLUE; } else { color = Color.YELLOW; } } } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.clickin2dabeat; import android.app.Activity; import android.content.Context; import android.content.Intent; import android.content.pm.PackageManager.NameNotFoundException; import android.os.Bundle; public class DownloadC2BFile extends Activity { String dataSource; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); dataSource = this.getIntent().getData().toString(); (new Thread(new loader())).start(); } public void runMem() { startApp("com.google.clickin2dabeat", "C2B"); finish(); } private void startApp(String packageName, String className) { try { int flags = Context.CONTEXT_INCLUDE_CODE | Context.CONTEXT_IGNORE_SECURITY; Context myContext = createPackageContext(packageName, flags); Class<?> appClass = myContext.getClassLoader().loadClass(packageName + "." + className); Intent intent = new Intent(myContext, appClass); startActivity(intent); } catch (NameNotFoundException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } } public class loader implements Runnable { public void run() { Unzipper.unzip(dataSource); runMem(); } } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.clickin2dabeat; import android.app.Activity; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import java.io.File; import java.io.FileWriter; import java.io.IOException; /** * Creates a skeleton C2B file when an appropriate media object is opened. */ public class CreateC2BFile extends Activity { private String dataSource; @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); dataSource = this.getIntent().getData().toString(); setContentView(R.layout.c2b_creator_form); Button create = ((Button) findViewById(R.id.CreateButton)); create.setOnClickListener(new OnClickListener() { public void onClick(View arg0) { String title = ((EditText) findViewById(R.id.TitleEditText)).getText().toString(); String author = ((EditText) findViewById(R.id.AuthorEditText)).getText().toString(); if (!title.equals("") && !author.equals("")) { createC2BSkeleton(title, author, dataSource); finish(); } } }); Button cancel = ((Button) findViewById(R.id.CancelButton)); cancel.setOnClickListener(new OnClickListener() { public void onClick(View arg0) { finish(); } }); } private void createC2BSkeleton(String title, String author, String media) { String c2bDirStr = "/sdcard/c2b/"; String sanitizedTitle = title.replaceAll("'", " "); String sanitizedAuthor = author.replaceAll("'", " "); String filename = sanitizedTitle.replaceAll("[^a-zA-Z0-9,\\s]", ""); filename = c2bDirStr + filename + ".c2b"; String contents = "<c2b title='" + title + "' level='1' author='" + author + "' media='" + media + "'></c2b>"; File c2bDir = new File(c2bDirStr); boolean directoryExists = c2bDir.isDirectory(); if (!directoryExists) { c2bDir.mkdir(); } try { FileWriter writer = new FileWriter(filename); writer.write(contents); writer.close(); Toast.makeText(CreateC2BFile.this, getString(R.string.STAGE_CREATED), 5000).show(); } catch (IOException e) { Toast.makeText(CreateC2BFile.this, getString(R.string.NEED_SD_CARD), 30000).show(); } } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.clickin2dabeat; import java.util.ArrayList; /** * Adjusts the times for the beat targets using a linear least-squares fit. */ public class BeatTimingsAdjuster { private double[] adjustedBeatTimes; public void setRawBeatTimes(ArrayList<Integer> rawBeatTimes) { double[] beatTimes = new double[rawBeatTimes.size()]; for (int i = 0; i < beatTimes.length; i++) { beatTimes[i] = rawBeatTimes.get(i); } adjustedBeatTimes = new double[beatTimes.length]; double[] beatNumbers = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; double n = beatNumbers.length; // Some things can be computed once and never computed again double[] beatNumbersXNumbers = multiplyArrays(beatNumbers, beatNumbers); double sumOfBeatNumbersXNumbers = sum(beatNumbersXNumbers); double sumOfBeatNumbers = sum(beatNumbers); // The divisor is: // (n * sum(beatNumbersXNumbers) - (sum(beatNumbers) * sum(beatNumbers))) // Since these are all constants, they can be computed first for better // efficiency. double divisor = (n * sum(beatNumbersXNumbers) - (sum(beatNumbers) * sum(beatNumbers))); // Not enough data to adjust for the first 5 beats for (int i = 0; (i < beatTimes.length) && (i < 5); i++) { adjustedBeatTimes[i] = beatTimes[i]; } // Adjust time for beat i by using timings for beats i-5 through i+5 double[] beatWindow = new double[beatNumbers.length]; for (int i = 0; i < beatTimes.length - 10; i++) { System.arraycopy(beatTimes, i, beatWindow, 0, beatNumbers.length); double[] beatNumbersXTimes = multiplyArrays(beatNumbers, beatWindow); double a = (sum(beatTimes) * sumOfBeatNumbersXNumbers - sumOfBeatNumbers * sum(beatNumbersXTimes)) / divisor; double b = (n * sum(beatNumbersXTimes) - sumOfBeatNumbers * sum(beatTimes)) / divisor; adjustedBeatTimes[i + 5] = a + b * beatNumbers[5]; } if (beatTimes.length - 10 < 0) { return; } // Not enough data to adjust for the last 5 beats for (int i = beatTimes.length - 10; i < beatTimes.length; i++) { adjustedBeatTimes[i] = beatTimes[i]; } } public ArrayList<Target> adjustBeatTargets(ArrayList<Target> rawTargets) { ArrayList<Target> adjustedTargets = new ArrayList<Target>(); int j = 0; double threshold = 200; for (int i = 0; i < rawTargets.size(); i++) { Target t = rawTargets.get(i); while ((j < adjustedBeatTimes.length) && (adjustedBeatTimes[j] < t.time)) { j++; } double prevTime = 0; if (j > 0) { prevTime = adjustedBeatTimes[j - 1]; } double postTime = -1; if (j < adjustedBeatTimes.length) { postTime = adjustedBeatTimes[j]; } if ((Math.abs(t.time - prevTime) < Math.abs(t.time - postTime)) && Math.abs(t.time - prevTime) < threshold) { t.time = prevTime; } else if ((Math.abs(t.time - prevTime) > Math.abs(t.time - postTime)) && Math.abs(t.time - postTime) < threshold) { t.time = postTime; } adjustedTargets.add(t); } return adjustedTargets; } private double sum(double[] numbers) { double sum = 0; for (int i = 0; i < numbers.length; i++) { sum = sum + numbers[i]; } return sum; } private double[] multiplyArrays(double[] numberSetA, double[] numberSetB) { double[] sqArray = new double[numberSetA.length]; for (int i = 0; i < numberSetA.length; i++) { sqArray[i] = numberSetA[i] * numberSetB[i]; } return sqArray; } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.clickin2dabeat; import android.app.Activity; import android.app.AlertDialog.Builder; import android.content.ComponentName; import android.content.DialogInterface; import android.content.Intent; import android.content.DialogInterface.OnClickListener; import android.content.pm.PackageManager.NameNotFoundException; import android.content.res.Resources; import android.media.AudioManager; import android.media.MediaPlayer; import android.media.MediaPlayer.OnCompletionListener; import android.media.MediaPlayer.OnErrorListener; import android.media.MediaPlayer.OnPreparedListener; import android.net.Uri; import android.os.Bundle; import android.widget.FrameLayout; import android.widget.Toast; import android.widget.VideoView; import org.w3c.dom.Document; import org.w3c.dom.NamedNodeMap; import org.w3c.dom.Node; import org.w3c.dom.NodeList; import org.xml.sax.SAXException; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileWriter; import java.io.FilenameFilter; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import javax.xml.parsers.DocumentBuilder; import javax.xml.parsers.DocumentBuilderFactory; import javax.xml.parsers.FactoryConfigurationError; import javax.xml.parsers.ParserConfigurationException; /** * A rhythm/music game for Android that can use any video as the background. */ public class C2B extends Activity { public static final int GAME_MODE = 0; public static final int TWOPASS_MODE = 1; public static final int ONEPASS_MODE = 2; public int mode; public boolean wasEditMode; private boolean forceEditMode; private VideoView background; private GameView foreground; private FrameLayout layout; private String c2bFileName; private String[] filenames; private String marketId; // These are parsed in from the C2B file private String title; private String author; private String level; private String media; private Uri videoUri; public ArrayList<Target> targets; public ArrayList<Integer> beatTimes; private BeatTimingsAdjuster timingAdjuster; private boolean busyProcessing; /** Called when the activity is first created. */ @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); UpdateChecker checker = new UpdateChecker(); int latestVersion = checker.getLatestVersionCode(); String packageName = C2B.class.getPackage().getName(); int currentVersion = 0; try { currentVersion = getPackageManager().getPackageInfo(packageName, 0).versionCode; } catch (NameNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } if (latestVersion > currentVersion){ marketId = checker.marketId; displayUpdateMessage(); } else { resetGame(); } } private void resetGame() { targets = new ArrayList<Target>(); mode = GAME_MODE; forceEditMode = false; wasEditMode = false; busyProcessing = false; c2bFileName = ""; title = ""; author = ""; level = ""; media = ""; background = null; foreground = null; layout = null; background = new VideoView(this); foreground = new GameView(this); layout = new FrameLayout(this); layout.addView(background); layout.setPadding(30, 0, 0, 0); // Is there a better way to do layout? beatTimes = null; timingAdjuster = null; background.setOnPreparedListener(new OnPreparedListener() { public void onPrepared(MediaPlayer mp) { background.start(); } }); background.setOnErrorListener(new OnErrorListener() { public boolean onError(MediaPlayer arg0, int arg1, int arg2) { background.setVideoURI(videoUri); return true; } }); background.setOnCompletionListener(new OnCompletionListener() { public void onCompletion(MediaPlayer mp) { if (mode == ONEPASS_MODE) { Toast waitMessage = Toast.makeText(C2B.this, getString(R.string.PROCESSING), 5000); waitMessage.show(); (new Thread(new BeatsWriter())).start(); } else if (mode == TWOPASS_MODE) { mode = ONEPASS_MODE; (new Thread(new BeatsTimingAdjuster())).start(); displayCreateLevelInfo(); return; } displayStats(); } }); layout.addView(foreground); setContentView(layout); setVolumeControlStream(AudioManager.STREAM_MUSIC); displayStartupMessage(); } private void writeC2BFile(String filename) { String contents = "<c2b title='" + title + "' level='" + level + "' author='" + author + "' media='" + media + "'>"; ArrayList<Target> targets = foreground.recordedTargets; if (timingAdjuster != null) { targets = timingAdjuster.adjustBeatTargets(foreground.recordedTargets); } for (int i = 0; i < targets.size(); i++) { Target t = targets.get(i); contents = contents + "<beat time='" + Double.toString(t.time) + "' "; contents = contents + "x='" + Integer.toString(t.x) + "' "; contents = contents + "y='" + Integer.toString(t.y) + "' "; contents = contents + "color='" + Integer.toHexString(t.color) + "'/>"; } contents = contents + "</c2b>"; try { FileWriter writer = new FileWriter(filename); writer.write(contents); writer.close(); } catch (IOException e) { // TODO(clchen): Do better error handling here e.printStackTrace(); } } private void loadC2B(String fileUriString) { try { FileInputStream fis = new FileInputStream(fileUriString); DocumentBuilder docBuild; docBuild = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document c2b = docBuild.parse(fis); runC2B(c2b); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ParserConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (FactoryConfigurationError e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void runC2B(Document c2b) { Node root = c2b.getElementsByTagName("c2b").item(0); title = root.getAttributes().getNamedItem("title").getNodeValue(); author = root.getAttributes().getNamedItem("author").getNodeValue(); level = root.getAttributes().getNamedItem("level").getNodeValue(); media = root.getAttributes().getNamedItem("media").getNodeValue(); NodeList beats = c2b.getElementsByTagName("beat"); targets = new ArrayList<Target>(); for (int i = 0; i < beats.getLength(); i++) { NamedNodeMap attribs = beats.item(i).getAttributes(); double time = Double.parseDouble(attribs.getNamedItem("time").getNodeValue()); int x = Integer.parseInt(attribs.getNamedItem("x").getNodeValue()); int y = Integer.parseInt(attribs.getNamedItem("y").getNodeValue()); String colorStr = attribs.getNamedItem("color").getNodeValue(); targets.add(new Target(time, x, y, colorStr)); } if ((beats.getLength() == 0) || forceEditMode) { displayCreateLevelAlert(); } else { videoUri = Uri.parse(media); background.setVideoURI(videoUri); } } private void displayCreateLevelAlert() { mode = ONEPASS_MODE; Builder createLevelAlert = new Builder(this); String titleText = getString(R.string.NO_BEATS) + " \"" + title + "\""; createLevelAlert.setTitle(titleText); String[] choices = new String[2]; choices[0] = getString(R.string.ONE_PASS); choices[1] = getString(R.string.TWO_PASS); createLevelAlert.setSingleChoiceItems(choices, 0, new OnClickListener() { public void onClick(DialogInterface dialog, int which) { if (which == 0) { mode = ONEPASS_MODE; } else { mode = TWOPASS_MODE; } } }); createLevelAlert.setPositiveButton("Ok", new OnClickListener() { public void onClick(DialogInterface dialog, int which) { if (busyProcessing) { Toast.makeText(C2B.this, R.string.STILL_BUSY, 5000).show(); displayCreateLevelAlert(); return; } wasEditMode = true; if (mode == TWOPASS_MODE) { beatTimes = new ArrayList<Integer>(); timingAdjuster = new BeatTimingsAdjuster(); } displayCreateLevelInfo(); } }); createLevelAlert.setNegativeButton("Cancel", new OnClickListener() { public void onClick(DialogInterface dialog, int which) { if (busyProcessing) { Toast.makeText(C2B.this, R.string.STILL_BUSY, 5000).show(); displayCreateLevelAlert(); return; } displayC2BFiles(); } }); createLevelAlert.setCancelable(false); createLevelAlert.show(); } private void displayC2BFiles() { Builder c2bFilesAlert = new Builder(this); String titleText = getString(R.string.CHOOSE_STAGE); c2bFilesAlert.setTitle(titleText); File c2bDir = new File("/sdcard/c2b/"); filenames = c2bDir.list(new FilenameFilter() { public boolean accept(File dir, String filename) { return filename.endsWith(".c2b"); } }); if (filenames == null) { displayNoFilesMessage(); return; } if (filenames.length == 0) { displayNoFilesMessage(); return; } c2bFilesAlert.setSingleChoiceItems(filenames, -1, new OnClickListener() { public void onClick(DialogInterface dialog, int which) { c2bFileName = "/sdcard/c2b/" + filenames[which]; } }); c2bFilesAlert.setPositiveButton("Go!", new OnClickListener() { public void onClick(DialogInterface dialog, int which) { loadC2B(c2bFileName); dialog.dismiss(); } }); /* c2bFilesAlert.setNeutralButton("Set new beats", new OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); displaySetNewBeatsConfirmation(); } }); */ final Activity self = this; c2bFilesAlert.setNeutralButton(getString(R.string.MOAR_STAGES), new OnClickListener() { public void onClick(DialogInterface dialog, int which) { Intent i = new Intent(); ComponentName comp = new ComponentName("com.android.browser", "com.android.browser.BrowserActivity"); i.setComponent(comp); i.setAction("android.intent.action.VIEW"); i.addCategory("android.intent.category.BROWSABLE"); Uri uri = Uri.parse("http://groups.google.com/group/clickin-2-da-beat/files"); i.setData(uri); self.startActivity(i); finish(); } }); c2bFilesAlert.setNegativeButton(getString(R.string.QUIT), new OnClickListener() { public void onClick(DialogInterface dialog, int which) { finish(); } }); c2bFilesAlert.setCancelable(false); c2bFilesAlert.show(); } /* private void displaySetNewBeatsConfirmation() { Builder setNewBeatsConfirmation = new Builder(this); String titleText = getString(R.string.EDIT_CONFIRMATION); setNewBeatsConfirmation.setTitle(titleText); String message = getString(R.string.EDIT_WARNING); setNewBeatsConfirmation.setMessage(message); setNewBeatsConfirmation.setPositiveButton("Continue", new OnClickListener() { public void onClick(DialogInterface dialog, int which) { forceEditMode = true; loadC2B(c2bFileName); dialog.dismiss(); } }); setNewBeatsConfirmation.setNegativeButton("Cancel", new OnClickListener() { public void onClick(DialogInterface dialog, int which) { displayC2BFiles(); dialog.dismiss(); } }); setNewBeatsConfirmation.setCancelable(false); setNewBeatsConfirmation.show(); } */ private void displayCreateLevelInfo() { Builder createLevelInfoAlert = new Builder(this); String titleText = getString(R.string.BEAT_SETTING_INFO); createLevelInfoAlert.setTitle(titleText); String message = ""; if (mode == TWOPASS_MODE) { message = getString(R.string.TWO_PASS_INFO); } else { message = getString(R.string.ONE_PASS_INFO); } createLevelInfoAlert.setMessage(message); createLevelInfoAlert.setPositiveButton("Start", new OnClickListener() { public void onClick(DialogInterface dialog, int which) { dialog.dismiss(); videoUri = Uri.parse(media); background.setVideoURI(videoUri); } }); createLevelInfoAlert.setCancelable(false); createLevelInfoAlert.show(); } private void displayStats() { Builder statsAlert = new Builder(this); String titleText = ""; if (!wasEditMode) { titleText = "Game Over"; } else { titleText = "Stage created!"; } statsAlert.setTitle(titleText); int longestCombo = foreground.longestCombo; if (foreground.comboCount > longestCombo) { longestCombo = foreground.comboCount; } String message = ""; if (!wasEditMode) { message = "Longest combo: " + Integer.toString(longestCombo); } else { message = "Beats recorded!"; } statsAlert.setMessage(message); statsAlert.setPositiveButton("Play", new OnClickListener() { public void onClick(DialogInterface dialog, int which) { if (busyProcessing) { Toast.makeText(C2B.this, R.string.STILL_BUSY, 5000).show(); displayStats(); return; } resetGame(); } }); statsAlert.setNegativeButton("Quit", new OnClickListener() { public void onClick(DialogInterface dialog, int which) { if (busyProcessing) { Toast.makeText(C2B.this, R.string.STILL_BUSY, 5000).show(); displayStats(); return; } finish(); } }); statsAlert.setCancelable(false); statsAlert.show(); } private void displayNoFilesMessage() { Builder noFilesMessage = new Builder(this); String titleText = getString(R.string.NO_STAGES_FOUND); noFilesMessage.setTitle(titleText); String message = getString(R.string.NO_STAGES_INFO); noFilesMessage.setMessage(message); noFilesMessage.setPositiveButton(getString(R.string.SHUT_UP), new OnClickListener() { public void onClick(DialogInterface dialog, int which) { loadHardCodedRickroll(); } }); final Activity self = this; noFilesMessage.setNeutralButton(getString(R.string.ILL_GET_STAGES), new OnClickListener() { public void onClick(DialogInterface dialog, int which) { Intent i = new Intent(); ComponentName comp = new ComponentName("com.android.browser", "com.android.browser.BrowserActivity"); i.setComponent(comp); i.setAction("android.intent.action.VIEW"); i.addCategory("android.intent.category.BROWSABLE"); Uri uri = Uri.parse("http://groups.google.com/group/clickin-2-da-beat/files"); i.setData(uri); self.startActivity(i); finish(); } }); noFilesMessage.setNegativeButton(getString(R.string.QUIT), new OnClickListener() { public void onClick(DialogInterface dialog, int which) { finish(); } }); noFilesMessage.setCancelable(false); noFilesMessage.show(); } private void loadHardCodedRickroll() { try { Resources res = getResources(); InputStream fis = res.openRawResource(R.raw.rickroll); DocumentBuilder docBuild; docBuild = DocumentBuilderFactory.newInstance().newDocumentBuilder(); Document c2b = docBuild.parse(fis); runC2B(c2b); } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ParserConfigurationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (FactoryConfigurationError e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SAXException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private void displayStartupMessage() { Builder startupMessage = new Builder(this); String titleText = getString(R.string.WELCOME); startupMessage.setTitle(titleText); String message = getString(R.string.BETA_MESSAGE); startupMessage.setMessage(message); startupMessage.setPositiveButton(getString(R.string.START_GAME), new OnClickListener() { public void onClick(DialogInterface dialog, int which) { displayC2BFiles(); } }); final Activity self = this; startupMessage.setNeutralButton(getString(R.string.VISIT_WEBSITE), new OnClickListener() { public void onClick(DialogInterface dialog, int which) { Intent i = new Intent(); ComponentName comp = new ComponentName("com.android.browser", "com.android.browser.BrowserActivity"); i.setComponent(comp); i.setAction("android.intent.action.VIEW"); i.addCategory("android.intent.category.BROWSABLE"); Uri uri = Uri.parse("http://groups.google.com/group/clickin-2-da-beat"); i.setData(uri); self.startActivity(i); finish(); } }); startupMessage.setNegativeButton(getString(R.string.QUIT), new OnClickListener() { public void onClick(DialogInterface dialog, int which) { finish(); } }); startupMessage.setCancelable(false); startupMessage.show(); } private void displayUpdateMessage() { Builder updateMessage = new Builder(this); String titleText = getString(R.string.UPDATE_AVAILABLE); updateMessage.setTitle(titleText); String message = getString(R.string.UPDATE_MESSAGE); updateMessage.setMessage(message); updateMessage.setPositiveButton("Yes", new OnClickListener() { public void onClick(DialogInterface dialog, int which) { Uri marketUri = Uri.parse("market://details?id=" + marketId); Intent marketIntent = new Intent(Intent.ACTION_VIEW, marketUri); startActivity(marketIntent); finish(); } }); final Activity self = this; updateMessage.setNegativeButton("No", new OnClickListener() { public void onClick(DialogInterface dialog, int which) { resetGame(); } }); updateMessage.setCancelable(false); updateMessage.show(); } public int getCurrentTime() { try { return background.getCurrentPosition(); } catch (IllegalStateException e) { // This will be thrown if the player is exiting mid-game and the video // view is going away at the same time as the foreground is trying to get // the position. This error can be safely ignored without doing anything. e.printStackTrace(); return 0; } } // Do beats processing in another thread to avoid hogging the UI thread and // generating a "not responding" error public class BeatsWriter implements Runnable { public void run() { writeC2BFile(c2bFileName); busyProcessing = false; } } public class BeatsTimingAdjuster implements Runnable { public void run() { timingAdjuster.setRawBeatTimes(beatTimes); busyProcessing = false; } } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.clickin2dabeat; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.Typeface; import android.media.AudioManager; import android.media.SoundPool; import android.os.Vibrator; import android.view.MotionEvent; import android.view.View; import java.util.ArrayList; /** * Draws the beat targets and takes user input. * This view is used as the foreground; the background is the video * being played. */ public class GameView extends View { private static final long[] VIBE_PATTERN = {0, 1, 40, 41}; private static final int INTERVAL = 10; // in ms private static final int PRE_THRESHOLD = 1000; // in ms private static final int POST_THRESHOLD = 500; // in ms private static final int TOLERANCE = 100; // in ms private static final int POINTS_FOR_PERFECT = 100; private static final double PENALTY_FACTOR = .25; private static final double COMBO_FACTOR = .1; private static final float TARGET_RADIUS = 50; public static final String LAST_RATING_OK = "(^_')"; public static final String LAST_RATING_PERFECT = "(^_^)/"; public static final String LAST_RATING_MISS = "(X_X)"; private C2B parent; private Vibrator vibe; private SoundPool snd; private int hitOkSfx; private int hitPerfectSfx; private int missSfx; public int comboCount; public int longestCombo; public String lastRating; Paint innerPaint; Paint borderPaint; Paint haloPaint; private ArrayList<Target> drawnTargets; private int lastTarget; public ArrayList<Target> recordedTargets; private int score; public GameView(Context context) { super(context); parent = (C2B) context; lastTarget = 0; score = 0; comboCount = 0; longestCombo = 0; lastRating = ""; drawnTargets = new ArrayList<Target>(); recordedTargets = new ArrayList<Target>(); vibe = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE); snd = new SoundPool(10, AudioManager.STREAM_SYSTEM, 0); missSfx = snd.load(context, R.raw.miss, 0); hitOkSfx = snd.load(context, R.raw.ok, 0); hitPerfectSfx = snd.load(context, R.raw.perfect, 0); innerPaint = new Paint(); innerPaint.setColor(Color.argb(127, 0, 0, 0)); innerPaint.setStyle(Paint.Style.FILL); borderPaint = new Paint(); borderPaint.setStyle(Paint.Style.STROKE); borderPaint.setAntiAlias(true); borderPaint.setStrokeWidth(2); haloPaint = new Paint(); haloPaint.setStyle(Paint.Style.STROKE); haloPaint.setAntiAlias(true); haloPaint.setStrokeWidth(4); Thread monitorThread = (new Thread(new Monitor())); monitorThread.setPriority(Thread.MIN_PRIORITY); monitorThread.start(); } private void updateTargets() { int i = lastTarget; int currentTime = parent.getCurrentTime(); // Add any targets that are within the pre-threshold to the list of // drawnTargets boolean cont = true; while (cont && (i < parent.targets.size())) { if (parent.targets.get(i).time < currentTime + PRE_THRESHOLD) { drawnTargets.add(parent.targets.get(i)); i++; } else { cont = false; } } lastTarget = i; // Move any expired targets out of drawn targets for (int j = 0; j < drawnTargets.size(); j++) { Target t = drawnTargets.get(j); if (t == null) { // Do nothing - this is a concurrency issue where // the target is already gone, so just ignore it } else if (t.time + POST_THRESHOLD < currentTime) { try { drawnTargets.remove(j); } catch (IndexOutOfBoundsException e){ // Do nothing here, j is already gone } if (longestCombo < comboCount) { longestCombo = comboCount; } comboCount = 0; lastRating = LAST_RATING_MISS; } } } @Override public boolean onTouchEvent(MotionEvent event) { if (event.getAction() == MotionEvent.ACTION_DOWN) { int currentTime = parent.getCurrentTime(); float x = event.getX(); float y = event.getY(); boolean hadHit = false; if (parent.mode == C2B.ONEPASS_MODE) { // Record this point as a target hadHit = true; snd.play(hitPerfectSfx, 1, 1, 0, 0, 1); Target targ = new Target(currentTime, (int) x, (int) y, ""); recordedTargets.add(targ); } else if (parent.mode == C2B.TWOPASS_MODE) { hadHit = true; parent.beatTimes.add(currentTime); } else { // Play the game normally for (int i = 0; i < drawnTargets.size(); i++) { if (hitTarget(x, y, drawnTargets.get(i))) { Target t = drawnTargets.get(i); int points; double timeDiff = Math.abs(currentTime - t.time); if (timeDiff < TOLERANCE) { points = POINTS_FOR_PERFECT; snd.play(hitPerfectSfx, 1, 1, 0, 0, 1); lastRating = LAST_RATING_PERFECT; } else { points = (int) (POINTS_FOR_PERFECT - (timeDiff * PENALTY_FACTOR)); points = points + (int) (points * (comboCount * COMBO_FACTOR)); snd.play(hitOkSfx, 1, 1, 0, 0, 1); lastRating = LAST_RATING_OK; } if (points > 0) { score = score + points; hadHit = true; } drawnTargets.remove(i); break; } } } if (hadHit) { comboCount++; } else { if (longestCombo < comboCount) { longestCombo = comboCount; } comboCount = 0; snd.play(missSfx, 1, 1, 0, 0, 1); lastRating = LAST_RATING_MISS; } vibe.vibrate(VIBE_PATTERN, -1); } return true; } private boolean hitTarget(float x, float y, Target t) { if (t == null) { return false; } // Use the pythagorean theorem to solve this. float xSquared = (t.x - x) * (t.x - x); float ySquared = (t.y - y) * (t.y - y); if ((xSquared + ySquared) < (TARGET_RADIUS * TARGET_RADIUS)) { return true; } return false; } @Override public void onDraw(Canvas canvas) { if (parent.mode != C2B.GAME_MODE) { return; } int currentTime = parent.getCurrentTime(); // Draw the circles for (int i = 0; i < drawnTargets.size(); i++) { Target t = drawnTargets.get(i); if (t == null) { break; } // Insides should be semi-transparent canvas.drawCircle(t.x, t.y, TARGET_RADIUS, innerPaint); // Set colors for the target borderPaint.setColor(t.color); haloPaint.setColor(t.color); // Perfect timing == hitting the halo inside the borders canvas.drawCircle(t.x, t.y, TARGET_RADIUS - 5, borderPaint); canvas.drawCircle(t.x, t.y, TARGET_RADIUS, borderPaint); // Draw timing halos - may need to change the formula here float percentageOff = ((float) (t.time - currentTime)) / PRE_THRESHOLD; int haloSize = (int) (TARGET_RADIUS + (percentageOff * TARGET_RADIUS)); canvas.drawCircle(t.x, t.y, haloSize, haloPaint); } // Score and Combo info String scoreText = "Score: " + Integer.toString(score); int x = getWidth() - 100; // Fudge factor for making it on the top right // corner int y = 30; Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG); paint.setColor(Color.RED); paint.setTextAlign(Paint.Align.CENTER); paint.setTextSize(24); paint.setTypeface(Typeface.DEFAULT_BOLD); y -= paint.ascent() / 2; canvas.drawText(scoreText, x, y, paint); x = getWidth() / 2; canvas.drawText(lastRating, x, y, paint); String comboText = "Combo: " + Integer.toString(comboCount); x = 60; canvas.drawText(comboText, x, y, paint); } private class Monitor implements Runnable { public void run() { while (true) { try { Thread.sleep(INTERVAL); } catch (InterruptedException e) { // This should not be interrupted. If it is, just dump the stack // trace. e.printStackTrace(); } updateTargets(); postInvalidate(); } } } }
Java
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.clickin2dabeat; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Enumeration; import java.util.zip.ZipEntry; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.util.zip.ZipFile; public class Unzipper { public static String download(String fileUrl) { URLConnection cn; try { fileUrl = (new URL(new URL(fileUrl), fileUrl)).toString(); URL url = new URL(fileUrl); cn = url.openConnection(); cn.connect(); InputStream stream = cn.getInputStream(); File outputDir = new File("/sdcard/c2b/"); outputDir.mkdirs(); String filename = fileUrl.substring(fileUrl.lastIndexOf("/") + 1); filename = filename.substring(0, filename.indexOf("c2b.zip") + 7); File outputFile = new File("/sdcard/c2b/", filename); outputFile.createNewFile(); FileOutputStream out = new FileOutputStream(outputFile); byte buf[] = new byte[16384]; do { int numread = stream.read(buf); if (numread <= 0) { break; } else { out.write(buf, 0, numread); } } while (true); stream.close(); out.close(); return "/sdcard/c2b/" + filename; } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); return ""; } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); return ""; } } public static void unzip(String fileUrl) { try { String filename = download(fileUrl); ZipFile zip = new ZipFile(filename); Enumeration<? extends ZipEntry> zippedFiles = zip.entries(); while (zippedFiles.hasMoreElements()) { ZipEntry entry = zippedFiles.nextElement(); InputStream is = zip.getInputStream(entry); String name = entry.getName(); File outputFile = new File("/sdcard/c2b/" + name); String outputPath = outputFile.getCanonicalPath(); name = outputPath.substring(outputPath.lastIndexOf("/") + 1); outputPath = outputPath.substring(0, outputPath.lastIndexOf("/")); File outputDir = new File(outputPath); outputDir.mkdirs(); outputFile = new File(outputPath, name); outputFile.createNewFile(); FileOutputStream out = new FileOutputStream(outputFile); byte buf[] = new byte[16384]; do { int numread = is.read(buf); if (numread <= 0) { break; } else { out.write(buf, 0, numread); } } while (true); is.close(); out.close(); } File theZipFile = new File(filename); theZipFile.delete(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
Java
/* * Copyright (C) 2007 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.globaltime; import javax.microedition.khronos.opengles.GL10; public class Sphere extends Shape { public Sphere(boolean emitTextureCoordinates, boolean emitNormals, boolean emitColors) { super(GL10.GL_TRIANGLES, GL10.GL_UNSIGNED_SHORT, emitTextureCoordinates, emitNormals, emitColors); } }
Java
/* * Copyright (C) 2007 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.globaltime; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Arrays; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.TimeZone; /** * A class representing a city, with an associated position, time zone name, * and raw offset from UTC. */ public class City implements Comparable<City> { private static Map<String,City> cities = new HashMap<String,City>(); private static City[] citiesByRawOffset; private String name; private String timeZoneID; private TimeZone timeZone = null; private int rawOffset; private float latitude, longitude; private float x, y, z; /** * Loads the city database. The cities must be stored in order by raw * offset from UTC. */ public static void loadCities(InputStream is) throws IOException { DataInputStream dis = new DataInputStream(is); int numCities = dis.readInt(); citiesByRawOffset = new City[numCities]; byte[] buf = new byte[24]; for (int i = 0; i < numCities; i++) { String name = dis.readUTF(); String tzid = dis.readUTF(); dis.read(buf); // The code below is a faster version of: // int rawOffset = dis.readInt(); // float latitude = dis.readFloat(); // float longitude = dis.readFloat(); // float cx = dis.readFloat(); // float cy = dis.readFloat(); // float cz = dis.readFloat(); int rawOffset = (buf[ 0] << 24) | ((buf[ 1] & 0xff) << 16) | ((buf[ 2] & 0xff) << 8) | (buf[ 3] & 0xff); int ilat = (buf[ 4] << 24) | ((buf[ 5] & 0xff) << 16) | ((buf[ 6] & 0xff) << 8) | (buf[ 7] & 0xff); int ilon = (buf[ 8] << 24) | ((buf[ 9] & 0xff) << 16) | ((buf[10] & 0xff) << 8) | (buf[11] & 0xff); int icx = (buf[12] << 24) | ((buf[13] & 0xff) << 16) | ((buf[14] & 0xff) << 8) | (buf[15] & 0xff); int icy = (buf[16] << 24) | ((buf[17] & 0xff) << 16) | ((buf[18] & 0xff) << 8) | (buf[19] & 0xff); int icz = (buf[20] << 24) | ((buf[21] & 0xff) << 16) | ((buf[22] & 0xff) << 8) | (buf[23] & 0xff); float latitude = Float.intBitsToFloat(ilat); float longitude = Float.intBitsToFloat(ilon); float cx = Float.intBitsToFloat(icx); float cy = Float.intBitsToFloat(icy); float cz = Float.intBitsToFloat(icz); City city = new City(name, tzid, rawOffset, latitude, longitude, cx, cy, cz); cities.put(name, city); citiesByRawOffset[i] = city; } } /** * Returns the cities, ordered by name. */ public static City[] getCitiesByName() { City[] ocities = cities.values().toArray(new City[0]); Arrays.sort(ocities); return ocities; } /** * Returns the cities, ordered by offset, accounting for summer/daylight * savings time. This requires reading the entire time zone database * behind the scenes. */ public static City[] getCitiesByOffset() { City[] ocities = cities.values().toArray(new City[0]); Arrays.sort(ocities, new Comparator<City>() { public int compare(City c1, City c2) { long now = System.currentTimeMillis(); TimeZone tz1 = c1.getTimeZone(); TimeZone tz2 = c2.getTimeZone(); int off1 = tz1.getOffset(now); int off2 = tz2.getOffset(now); if (off1 == off2) { float dlat = c2.getLatitude() - c1.getLatitude(); if (dlat < 0.0f) return -1; if (dlat > 0.0f) return 1; return 0; } return off1 - off2; } }); return ocities; } /** * Returns the cities, ordered by offset, accounting for summer/daylight * savings time. This does not require reading the time zone database * since the cities are pre-sorted. */ public static City[] getCitiesByRawOffset() { return citiesByRawOffset; } /** * Returns an Iterator over all cities, in raw offset order. */ public static Iterator<City> iterator() { return cities.values().iterator(); } /** * Returns the total number of cities. */ public static int numCities() { return cities.size(); } /** * Constructs a city with the given name, time zone name, raw offset, * latitude, longitude, and 3D (X, Y, Z) coordinate. */ public City(String name, String timeZoneID, int rawOffset, float latitude, float longitude, float x, float y, float z) { this.name = name; this.timeZoneID = timeZoneID; this.rawOffset = rawOffset; this.latitude = latitude; this.longitude = longitude; this.x = x; this.y = y; this.z = z; } public String getName() { return name; } public TimeZone getTimeZone() { if (timeZone == null) { timeZone = TimeZone.getTimeZone(timeZoneID); } return timeZone; } public float getLongitude() { return longitude; } public float getLatitude() { return latitude; } public float getX() { return x; } public float getY() { return y; } public float getZ() { return z; } public float getRawOffset() { return rawOffset / 3600000.0f; } public int getRawOffsetMillis() { return rawOffset; } /** * Returns this city's offset from UTC, taking summer/daylight savigns * time into account. */ public float getOffset() { long now = System.currentTimeMillis(); if (timeZone == null) { timeZone = TimeZone.getTimeZone(timeZoneID); } return timeZone.getOffset(now) / 3600000.0f; } /** * Compares this city to another by name. */ public int compareTo(City o) { return name.compareTo(o.name); } }
Java
/* * Copyright (C) 2007 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.globaltime; import java.util.Calendar; import java.util.Date; import java.util.TimeZone; import java.text.DateFormat; import android.content.Context; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Path; import android.graphics.RectF; import android.text.format.DateUtils; //import android.text.format.DateFormat; import android.view.animation.AccelerateDecelerateInterpolator; import android.view.animation.Interpolator; /** * A class that draws an analog clock face with information about the current * time in a given city. */ public class Clock { static final int MILLISECONDS_PER_MINUTE = 60 * 1000; static final int MILLISECONDS_PER_HOUR = 60 * 60 * 1000; private City mCity = null; private long mCitySwitchTime; private long mTime; private float mColorRed = 1.0f; private float mColorGreen = 1.0f; private float mColorBlue = 1.0f; private long mOldOffset; private Interpolator mClockHandInterpolator = new AccelerateDecelerateInterpolator(); public Clock() { // Empty constructor } /** * Adds a line to the given Path. The line extends from * radius r0 to radius r1 about the center point (cx, cy), * at an angle given by pos. * * @param path the Path to draw to * @param radius the radius of the outer rim of the clock * @param pos the angle, with 0 and 1 at 12:00 * @param cx the X coordinate of the clock center * @param cy the Y coordinate of the clock center * @param r0 the starting radius for the line * @param r1 the ending radius for the line */ private static void drawLine(Path path, float radius, float pos, float cx, float cy, float r0, float r1) { float theta = pos * Shape.TWO_PI - Shape.PI_OVER_TWO; float dx = (float) Math.cos(theta); float dy = (float) Math.sin(theta); float p0x = cx + dx * r0; float p0y = cy + dy * r0; float p1x = cx + dx * r1; float p1y = cy + dy * r1; float ox = (p1y - p0y); float oy = -(p1x - p0x); float norm = (radius / 2.0f) / (float) Math.sqrt(ox * ox + oy * oy); ox *= norm; oy *= norm; path.moveTo(p0x - ox, p0y - oy); path.lineTo(p1x - ox, p1y - oy); path.lineTo(p1x + ox, p1y + oy); path.lineTo(p0x + ox, p0y + oy); path.close(); } /** * Adds a vertical arrow to the given Path. * * @param path the Path to draw to */ private static void drawVArrow(Path path, float cx, float cy, float width, float height) { path.moveTo(cx - width / 2.0f, cy); path.lineTo(cx, cy + height); path.lineTo(cx + width / 2.0f, cy); path.close(); } /** * Adds a horizontal arrow to the given Path. * * @param path the Path to draw to */ private static void drawHArrow(Path path, float cx, float cy, float width, float height) { path.moveTo(cx, cy - height / 2.0f); path.lineTo(cx + width, cy); path.lineTo(cx, cy + height / 2.0f); path.close(); } /** * Returns an offset in milliseconds to be subtracted from the current time * in order to obtain an smooth interpolation between the previously * displayed time and the current time. */ private long getOffset(float lerp) { long doffset = (long) (mCity.getOffset() * (float) MILLISECONDS_PER_HOUR - mOldOffset); int sign; if (doffset < 0) { doffset = -doffset; sign = -1; } else { sign = 1; } while (doffset > 12L * MILLISECONDS_PER_HOUR) { doffset -= 12L * MILLISECONDS_PER_HOUR; } if (doffset > 6L * MILLISECONDS_PER_HOUR) { doffset = 12L * MILLISECONDS_PER_HOUR - doffset; sign = -sign; } // Interpolate doffset towards 0 doffset = (long)((1.0f - lerp)*doffset); // Keep the same seconds count long dh = doffset / (MILLISECONDS_PER_HOUR); doffset -= dh * MILLISECONDS_PER_HOUR; long dm = doffset / MILLISECONDS_PER_MINUTE; doffset = sign * (60 * dh + dm) * MILLISECONDS_PER_MINUTE; return doffset; } /** * Set the city to be displayed. setCity(null) resets things so the clock * hand animation won't occur next time. */ public void setCity(City city) { if (mCity != city) { if (mCity != null) { mOldOffset = (long) (mCity.getOffset() * (float) MILLISECONDS_PER_HOUR); } else if (city != null) { mOldOffset = (long) (city.getOffset() * (float) MILLISECONDS_PER_HOUR); } else { mOldOffset = 0L; // this will never be used } this.mCitySwitchTime = System.currentTimeMillis(); this.mCity = city; } } public void setTime(long time) { this.mTime = time; } /** * Draws the clock face. * * @param canvas the Canvas to draw to * @param cx the X coordinate of the clock center * @param cy the Y coordinate of the clock center * @param radius the radius of the clock face * @param alpha the translucency of the clock face * @param textAlpha the translucency of the text * @param showCityName if true, display the city name * @param showTime if true, display the time digitally * @param showUpArrow if true, display an up arrow * @param showDownArrow if true, display a down arrow * @param showLeftRightArrows if true, display left and right arrows * @param prefixChars number of characters of the city name to draw in bold */ public void drawClock(Canvas canvas, float cx, float cy, float radius, float alpha, float textAlpha, boolean showCityName, boolean showTime, boolean showUpArrow, boolean showDownArrow, boolean showLeftRightArrows, int prefixChars) { Paint paint = new Paint(); paint.setAntiAlias(true); int iradius = (int)radius; TimeZone tz = mCity.getTimeZone(); // Compute an interpolated time to animate between the previously // displayed time and the current time float lerp = Math.min(1.0f, (System.currentTimeMillis() - mCitySwitchTime) / 500.0f); lerp = mClockHandInterpolator.getInterpolation(lerp); long doffset = lerp < 1.0f ? getOffset(lerp) : 0L; // Determine the interpolated time for the given time zone Calendar cal = Calendar.getInstance(tz); cal.setTimeInMillis(mTime - doffset); int hour = cal.get(Calendar.HOUR_OF_DAY); int minute = cal.get(Calendar.MINUTE); int second = cal.get(Calendar.SECOND); int milli = cal.get(Calendar.MILLISECOND); float offset = tz.getRawOffset() / (float) MILLISECONDS_PER_HOUR; float daylightOffset = tz.inDaylightTime(new Date(mTime)) ? tz.getDSTSavings() / (float) MILLISECONDS_PER_HOUR : 0.0f; float absOffset = offset < 0 ? -offset : offset; int offsetH = (int) absOffset; int offsetM = (int) (60.0f * (absOffset - offsetH)); hour %= 12; // Get the city name and digital time strings String cityName = mCity.getName(); cal.setTimeInMillis(mTime); //java.text.DateFormat mTimeFormat = android.text.format.DateFormat.getTimeFormat(this.getApplicationContext()); DateFormat mTimeFormat = DateFormat.getTimeInstance(); String time = mTimeFormat.format(cal.getTimeInMillis()) + " " + DateUtils.getDayOfWeekString(cal.get(Calendar.DAY_OF_WEEK), DateUtils.LENGTH_SHORT) + " " + " (UTC" + (offset >= 0 ? "+" : "-") + offsetH + (offsetM == 0 ? "" : ":" + offsetM) + (daylightOffset == 0 ? "" : "+" + daylightOffset) + ")"; float th = paint.getTextSize(); float tw; // Set the text color paint.setARGB((int) (textAlpha * 255.0f), (int) (mColorRed * 255.0f), (int) (mColorGreen * 255.0f), (int) (mColorBlue * 255.0f)); tw = paint.measureText(cityName); if (showCityName) { // Increment prefixChars to include any spaces for (int i = 0; i < prefixChars; i++) { if (cityName.charAt(i) == ' ') { ++prefixChars; } } // Draw the city name canvas.drawText(cityName, cx - tw / 2, cy - radius - th, paint); // Overstrike the first 'prefixChars' characters canvas.drawText(cityName.substring(0, prefixChars), cx - tw / 2 + 1, cy - radius - th, paint); } tw = paint.measureText(time); if (showTime) { canvas.drawText(time, cx - tw / 2, cy + radius + th + 5, paint); } paint.setARGB((int)(alpha * 255.0f), (int)(mColorRed * 255.0f), (int)(mColorGreen * 255.0f), (int)(mColorBlue * 255.0f)); paint.setStyle(Paint.Style.FILL); canvas.drawOval(new RectF(cx - 2, cy - 2, cx + 2, cy + 2), paint); paint.setStyle(Paint.Style.STROKE); paint.setStrokeWidth(radius * 0.12f); canvas.drawOval(new RectF(cx - iradius, cy - iradius, cx + iradius, cy + iradius), paint); float r0 = radius * 0.1f; float r1 = radius * 0.4f; float r2 = radius * 0.6f; float r3 = radius * 0.65f; float r4 = radius * 0.7f; float r5 = radius * 0.9f; Path path = new Path(); float ss = second + milli / 1000.0f; float mm = minute + ss / 60.0f; float hh = hour + mm / 60.0f; // Tics for the hours for (int i = 0; i < 12; i++) { drawLine(path, radius * 0.12f, i / 12.0f, cx, cy, r4, r5); } // Hour hand drawLine(path, radius * 0.12f, hh / 12.0f, cx, cy, r0, r1); // Minute hand drawLine(path, radius * 0.12f, mm / 60.0f, cx, cy, r0, r2); // Second hand drawLine(path, radius * 0.036f, ss / 60.0f, cx, cy, r0, r3); if (showUpArrow) { drawVArrow(path, cx + radius * 1.13f, cy - radius, radius * 0.15f, -radius * 0.1f); } if (showDownArrow) { drawVArrow(path, cx + radius * 1.13f, cy + radius, radius * 0.15f, radius * 0.1f); } if (showLeftRightArrows) { drawHArrow(path, cx - radius * 1.3f, cy, -radius * 0.1f, radius * 0.15f); drawHArrow(path, cx + radius * 1.3f, cy, radius * 0.1f, radius * 0.15f); } paint.setStyle(Paint.Style.FILL); canvas.drawPath(path, paint); } }
Java
/* * Copyright (C) 2007 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.globaltime; import javax.microedition.khronos.opengles.GL10; /** * A class representing a set of GL_POINT objects. GlobalTime uses this class * to draw city lights on the night side of the earth. */ public class PointCloud extends Shape { /** * Constructs a PointCloud with a point at each of the given vertex * (x, y, z) positions. * @param vertices an array of (x, y, z) positions given in fixed-point. */ public PointCloud(int[] vertices) { this(vertices, 0, vertices.length); } /** * Constructs a PointCloud with a point at each of the given vertex * (x, y, z) positions. * @param vertices an array of (x, y, z) positions given in fixed-point. * @param off the starting offset of the vertices array * @param len the number of elements of the vertices array to use */ public PointCloud(int[] vertices, int off, int len) { super(GL10.GL_POINTS, GL10.GL_UNSIGNED_SHORT, false, false, false); int numPoints = len / 3; short[] indices = new short[numPoints]; for (int i = 0; i < numPoints; i++) { indices[i] = (short)i; } allocateBuffers(vertices, null, null, null, indices); this.mNumIndices = mIndexBuffer.capacity(); } @Override public int getNumTriangles() { return mNumIndices * 2; } }
Java
/* * Copyright (C) 2007 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.globaltime; import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.IntBuffer; import java.nio.ShortBuffer; import javax.microedition.khronos.opengles.GL10; /** * An abstract superclass for various three-dimensional objects to be drawn * using OpenGL ES. Each subclass is responsible for setting up NIO buffers * containing vertices, texture coordinates, colors, normals, and indices. * The {@link #draw(GL10)} method draws the object to the given OpenGL context. */ public abstract class Shape { public static final int INT_BYTES = 4; public static final int SHORT_BYTES = 2; public static final float DEGREES_TO_RADIANS = (float) Math.PI / 180.0f; public static final float PI = (float) Math.PI; public static final float TWO_PI = (float) (2.0 * Math.PI); public static final float PI_OVER_TWO = (float) (Math.PI / 2.0); protected int mPrimitive; protected int mIndexDatatype; protected boolean mEmitTextureCoordinates; protected boolean mEmitNormals; protected boolean mEmitColors; protected IntBuffer mVertexBuffer; protected IntBuffer mTexcoordBuffer; protected IntBuffer mColorBuffer; protected IntBuffer mNormalBuffer; protected Buffer mIndexBuffer; protected int mNumIndices = -1; /** * Constructs a Shape. * * @param primitive a GL primitive type understood by glDrawElements, * such as GL10.GL_TRIANGLES * @param indexDatatype the GL datatype for the index buffer, such as * GL10.GL_UNSIGNED_SHORT * @param emitTextureCoordinates true to enable use of the texture * coordinate buffer * @param emitNormals true to enable use of the normal buffer * @param emitColors true to enable use of the color buffer */ protected Shape(int primitive, int indexDatatype, boolean emitTextureCoordinates, boolean emitNormals, boolean emitColors) { mPrimitive = primitive; mIndexDatatype = indexDatatype; mEmitTextureCoordinates = emitTextureCoordinates; mEmitNormals = emitNormals; mEmitColors = emitColors; } /** * Converts the given floating-point value to fixed-point. */ public static int toFixed(float x) { return (int) (x * 65536.0); } /** * Converts the given fixed-point value to floating-point. */ public static float toFloat(int x) { return (float) (x / 65536.0); } /** * Computes the cross-product of two vectors p and q and places * the result in out. */ public static void cross(float[] p, float[] q, float[] out) { out[0] = p[1] * q[2] - p[2] * q[1]; out[1] = p[2] * q[0] - p[0] * q[2]; out[2] = p[0] * q[1] - p[1] * q[0]; } /** * Returns the length of a vector, given as three floats. */ public static float length(float vx, float vy, float vz) { return (float) Math.sqrt(vx * vx + vy * vy + vz * vz); } /** * Returns the length of a vector, given as an array of three floats. */ public static float length(float[] v) { return length(v[0], v[1], v[2]); } /** * Normalizes the given vector of three floats to have length == 1.0. * Vectors with length zero are unaffected. */ public static void normalize(float[] v) { float length = length(v); if (length != 0.0f) { float norm = 1.0f / length; v[0] *= norm; v[1] *= norm; v[2] *= norm; } } /** * Returns the number of triangles associated with this shape. */ public int getNumTriangles() { if (mPrimitive == GL10.GL_TRIANGLES) { return mIndexBuffer.capacity() / 3; } else if (mPrimitive == GL10.GL_TRIANGLE_STRIP) { return mIndexBuffer.capacity() - 2; } return 0; } /** * Copies the given data into the instance * variables mVertexBuffer, mTexcoordBuffer, mNormalBuffer, mColorBuffer, * and mIndexBuffer. * * @param vertices an array of fixed-point vertex coordinates * @param texcoords an array of fixed-point texture coordinates * @param normals an array of fixed-point normal vector coordinates * @param colors an array of fixed-point color channel values * @param indices an array of short indices */ public void allocateBuffers(int[] vertices, int[] texcoords, int[] normals, int[] colors, short[] indices) { allocate(vertices, texcoords, normals, colors); ByteBuffer ibb = ByteBuffer.allocateDirect(indices.length * SHORT_BYTES); ibb.order(ByteOrder.nativeOrder()); ShortBuffer shortIndexBuffer = ibb.asShortBuffer(); shortIndexBuffer.put(indices); shortIndexBuffer.position(0); this.mIndexBuffer = shortIndexBuffer; } /** * Copies the given data into the instance * variables mVertexBuffer, mTexcoordBuffer, mNormalBuffer, mColorBuffer, * and mIndexBuffer. * * @param vertices an array of fixed-point vertex coordinates * @param texcoords an array of fixed-point texture coordinates * @param normals an array of fixed-point normal vector coordinates * @param colors an array of fixed-point color channel values * @param indices an array of int indices */ public void allocateBuffers(int[] vertices, int[] texcoords, int[] normals, int[] colors, int[] indices) { allocate(vertices, texcoords, normals, colors); ByteBuffer ibb = ByteBuffer.allocateDirect(indices.length * INT_BYTES); ibb.order(ByteOrder.nativeOrder()); IntBuffer intIndexBuffer = ibb.asIntBuffer(); intIndexBuffer.put(indices); intIndexBuffer.position(0); this.mIndexBuffer = intIndexBuffer; } /** * Allocate the vertex, texture coordinate, normal, and color buffer. */ private void allocate(int[] vertices, int[] texcoords, int[] normals, int[] colors) { ByteBuffer vbb = ByteBuffer.allocateDirect(vertices.length * INT_BYTES); vbb.order(ByteOrder.nativeOrder()); mVertexBuffer = vbb.asIntBuffer(); mVertexBuffer.put(vertices); mVertexBuffer.position(0); if ((texcoords != null) && mEmitTextureCoordinates) { ByteBuffer tbb = ByteBuffer.allocateDirect(texcoords.length * INT_BYTES); tbb.order(ByteOrder.nativeOrder()); mTexcoordBuffer = tbb.asIntBuffer(); mTexcoordBuffer.put(texcoords); mTexcoordBuffer.position(0); } if ((normals != null) && mEmitNormals) { ByteBuffer nbb = ByteBuffer.allocateDirect(normals.length * INT_BYTES); nbb.order(ByteOrder.nativeOrder()); mNormalBuffer = nbb.asIntBuffer(); mNormalBuffer.put(normals); mNormalBuffer.position(0); } if ((colors != null) && mEmitColors) { ByteBuffer cbb = ByteBuffer.allocateDirect(colors.length * INT_BYTES); cbb.order(ByteOrder.nativeOrder()); mColorBuffer = cbb.asIntBuffer(); mColorBuffer.put(colors); mColorBuffer.position(0); } } /** * Draws the shape to the given OpenGL ES 1.0 context. Texture coordinates, * normals, and colors are emitted according the the preferences set for * this shape. */ public void draw(GL10 gl) { gl.glVertexPointer(3, GL10.GL_FIXED, 0, mVertexBuffer); gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); if (mEmitTextureCoordinates) { gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY); gl.glTexCoordPointer(2, GL10.GL_FIXED, 0, mTexcoordBuffer); gl.glEnable(GL10.GL_TEXTURE_2D); } else { gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY); gl.glDisable(GL10.GL_TEXTURE_2D); } if (mEmitNormals) { gl.glEnableClientState(GL10.GL_NORMAL_ARRAY); gl.glNormalPointer(GL10.GL_FIXED, 0, mNormalBuffer); } else { gl.glDisableClientState(GL10.GL_NORMAL_ARRAY); } if (mEmitColors) { gl.glEnableClientState(GL10.GL_COLOR_ARRAY); gl.glColorPointer(4, GL10.GL_FIXED, 0, mColorBuffer); } else { gl.glDisableClientState(GL10.GL_COLOR_ARRAY); } gl.glDrawElements(mPrimitive, mNumIndices > 0 ? mNumIndices : mIndexBuffer.capacity(), mIndexDatatype, mIndexBuffer); } }
Java
/* * Copyright (C) 2007 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.globaltime; import javax.microedition.khronos.opengles.GL10; /** * A class that draws a ring with a given center and inner and outer radii. * The inner and outer rings each have a color and the remaining pixels are * colored by interpolation. GlobalTime uses this class to simulate an * "atmosphere" around the earth. */ public class Annulus extends Shape { /** * Constructs an annulus. * * @param centerX the X coordinate of the center point * @param centerY the Y coordinate of the center point * @param Z the fixed Z for the entire ring * @param innerRadius the inner radius * @param outerRadius the outer radius * @param rInner the red channel of the color of the inner ring * @param gInner the green channel of the color of the inner ring * @param bInner the blue channel of the color of the inner ring * @param aInner the alpha channel of the color of the inner ring * @param rOuter the red channel of the color of the outer ring * @param gOuter the green channel of the color of the outer ring * @param bOuter the blue channel of the color of the outer ring * @param aOuter the alpha channel of the color of the outer ring * @param sectors the number of sectors used to approximate curvature */ public Annulus(float centerX, float centerY, float Z, float innerRadius, float outerRadius, float rInner, float gInner, float bInner, float aInner, float rOuter, float gOuter, float bOuter, float aOuter, int sectors) { super(GL10.GL_TRIANGLES, GL10.GL_UNSIGNED_SHORT, false, false, true); int radii = sectors + 1; int[] vertices = new int[2 * 3 * radii]; int[] colors = new int[2 * 4 * radii]; short[] indices = new short[2 * 3 * radii]; int vidx = 0; int cidx = 0; int iidx = 0; for (int i = 0; i < radii; i++) { float theta = (i * TWO_PI) / (radii - 1); float cosTheta = (float) Math.cos(theta); float sinTheta = (float) Math.sin(theta); vertices[vidx++] = toFixed(centerX + innerRadius * cosTheta); vertices[vidx++] = toFixed(centerY + innerRadius * sinTheta); vertices[vidx++] = toFixed(Z); vertices[vidx++] = toFixed(centerX + outerRadius * cosTheta); vertices[vidx++] = toFixed(centerY + outerRadius * sinTheta); vertices[vidx++] = toFixed(Z); colors[cidx++] = toFixed(rInner); colors[cidx++] = toFixed(gInner); colors[cidx++] = toFixed(bInner); colors[cidx++] = toFixed(aInner); colors[cidx++] = toFixed(rOuter); colors[cidx++] = toFixed(gOuter); colors[cidx++] = toFixed(bOuter); colors[cidx++] = toFixed(aOuter); } for (int i = 0; i < sectors; i++) { indices[iidx++] = (short) (2 * i); indices[iidx++] = (short) (2 * i + 1); indices[iidx++] = (short) (2 * i + 2); indices[iidx++] = (short) (2 * i + 1); indices[iidx++] = (short) (2 * i + 3); indices[iidx++] = (short) (2 * i + 2); } allocateBuffers(vertices, null, null, colors, indices); } }
Java
/* * Copyright (C) 2007 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.globaltime; import java.io.ByteArrayInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Calendar; import java.util.List; import java.util.Locale; import java.util.TimeZone; import javax.microedition.khronos.egl.*; import javax.microedition.khronos.opengles.*; import android.app.Activity; import android.content.Context; import android.content.res.AssetManager; import android.graphics.Canvas; import android.opengl.Object3D; import android.os.Bundle; import android.os.Handler; import android.os.Looper; import android.os.Message; import android.os.MessageQueue; import android.util.Log; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.animation.AccelerateDecelerateInterpolator; import android.view.animation.DecelerateInterpolator; import android.view.animation.Interpolator; /** * The main View of the GlobalTime Activity. */ class GTView extends SurfaceView implements SurfaceHolder.Callback { /** * A TimeZone object used to compute the current UTC time. */ private static final TimeZone UTC_TIME_ZONE = TimeZone.getTimeZone("utc"); /** * The Sun's color is close to that of a 5780K blackbody. */ private static final float[] SUNLIGHT_COLOR = { 1.0f, 0.9375f, 0.91015625f, 1.0f }; /** * The inclination of the earth relative to the plane of the ecliptic * is 23.45 degrees. */ private static final float EARTH_INCLINATION = 23.45f * Shape.PI / 180.0f; /** Seconds in a day */ private static final int SECONDS_PER_DAY = 24 * 60 * 60; /** Flag for the depth test */ private static final boolean PERFORM_DEPTH_TEST= false; /** Use raw time zone offsets, disregarding "summer time." If false, * current offsets will be used, which requires a much longer startup time * in order to sort the city database. */ private static final boolean USE_RAW_OFFSETS = true; /** * The earth's atmosphere. */ private static final Annulus ATMOSPHERE = new Annulus(0.0f, 0.0f, 1.75f, 0.9f, 1.08f, 0.4f, 0.4f, 0.8f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 50); /** * The tesselation of the earth by latitude. */ private static final int SPHERE_LATITUDES = 25; /** * The tesselation of the earth by longitude. */ private static int SPHERE_LONGITUDES = 25; /** * A flattened version of the earth. The normals are computed identically * to those of the round earth, allowing the day/night lighting to be * applied to the flattened surface. */ private static Sphere worldFlat = new LatLongSphere(0.0f, 0.0f, 0.0f, 1.0f, SPHERE_LATITUDES, SPHERE_LONGITUDES, 0.0f, 360.0f, true, true, false, true); /** * The earth. */ private Object3D mWorld; /** * Geometry of the city lights */ private PointCloud mLights; /** * True if the activiy has been initialized. */ boolean mInitialized = false; /** * True if we're in alphabetic entry mode. */ private boolean mAlphaKeySet = false; private EGLContext mEGLContext; private EGLSurface mEGLSurface; private EGLDisplay mEGLDisplay; private EGLConfig mEGLConfig; GLView mGLView; // Rotation and tilt of the Earth private float mRotAngle = 0.0f; private float mTiltAngle = 0.0f; // Rotational velocity of the orbiting viewer private float mRotVelocity = 1.0f; // Rotation of the flat view private float mWrapX = 0.0f; private float mWrapVelocity = 0.0f; private float mWrapVelocityFactor = 0.01f; // Toggle switches private boolean mDisplayAtmosphere = true; private boolean mDisplayClock = false; private boolean mClockShowing = false; private boolean mDisplayLights = false; private boolean mDisplayWorld = true; private boolean mDisplayWorldFlat = false; private boolean mSmoothShading = true; // City search string private String mCityName = ""; // List of all cities private List<City> mClockCities; // List of cities matching a user-supplied prefix private List<City> mCityNameMatches = new ArrayList<City>(); private List<City> mCities; // Start time for clock fade animation private long mClockFadeTime; // Interpolator for clock fade animation private Interpolator mClockSizeInterpolator = new DecelerateInterpolator(1.0f); // Index of current clock private int mCityIndex; // Current clock private Clock mClock; // City-to-city flight animation parameters private boolean mFlyToCity = false; private long mCityFlyStartTime; private float mCityFlightTime; private float mRotAngleStart, mRotAngleDest; private float mTiltAngleStart, mTiltAngleDest; // Interpolator for flight motion animation private Interpolator mFlyToCityInterpolator = new AccelerateDecelerateInterpolator(); private static int sNumLights; private static int[] sLightCoords; // static Map<Float,int[]> cityCoords = new HashMap<Float,int[]>(); // Arrays for GL calls private float[] mClipPlaneEquation = new float[4]; private float[] mLightDir = new float[4]; // Calendar for computing the Sun's position Calendar mSunCal = Calendar.getInstance(UTC_TIME_ZONE); // Triangles drawn per frame private int mNumTriangles; private long startTime; private static final int MOTION_NONE = 0; private static final int MOTION_X = 1; private static final int MOTION_Y = 2; private static final int MIN_MANHATTAN_DISTANCE = 20; private static final float ROTATION_FACTOR = 1.0f / 30.0f; private static final float TILT_FACTOR = 0.35f; // Touchscreen support private float mMotionStartX; private float mMotionStartY; private float mMotionStartRotVelocity; private float mMotionStartTiltAngle; private int mMotionDirection; public void surfaceCreated(SurfaceHolder holder) { EGL10 egl = (EGL10)EGLContext.getEGL(); mEGLSurface = egl.eglCreateWindowSurface(mEGLDisplay, mEGLConfig, this, null); egl.eglMakeCurrent(mEGLDisplay, mEGLSurface, mEGLSurface, mEGLContext); } public void surfaceDestroyed(SurfaceHolder holder) { // nothing to do } public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { // nothing to do } /** * Set up the view. * * @param context the Context * @param am an AssetManager to retrieve the city database from */ public GTView(Context context) { super(context); getHolder().addCallback(this); getHolder().setType(SurfaceHolder.SURFACE_TYPE_GPU); AssetManager am = context.getAssets(); startTime = System.currentTimeMillis(); EGL10 egl = (EGL10)EGLContext.getEGL(); EGLDisplay dpy = egl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY); int[] version = new int[2]; egl.eglInitialize(dpy, version); int[] configSpec = { EGL10.EGL_DEPTH_SIZE, 16, EGL10.EGL_NONE }; EGLConfig[] configs = new EGLConfig[1]; int[] num_config = new int[1]; egl.eglChooseConfig(dpy, configSpec, configs, 1, num_config); mEGLConfig = configs[0]; mEGLContext = egl.eglCreateContext(dpy, mEGLConfig, EGL10.EGL_NO_CONTEXT, null); mEGLDisplay = dpy; mClock = new Clock(); setFocusable(true); setFocusableInTouchMode(true); requestFocus(); try { loadAssets(am); } catch (IOException ioe) { ioe.printStackTrace(); throw new RuntimeException(ioe); } catch (ArrayIndexOutOfBoundsException aioobe) { aioobe.printStackTrace(); throw new RuntimeException(aioobe); } } /** * Destroy the view. */ public void destroy() { EGL10 egl = (EGL10)EGLContext.getEGL(); egl.eglMakeCurrent(mEGLDisplay, egl.EGL_NO_SURFACE, egl.EGL_NO_SURFACE, egl.EGL_NO_CONTEXT); egl.eglDestroyContext(mEGLDisplay, mEGLContext); egl.eglDestroySurface(mEGLDisplay, mEGLSurface); egl.eglTerminate(mEGLDisplay); mEGLContext = null; } /** * Begin animation. */ public void startAnimating() { mHandler.sendEmptyMessage(INVALIDATE); } /** * Quit animation. */ public void stopAnimating() { mHandler.removeMessages(INVALIDATE); } /** * Read a two-byte integer from the input stream. */ private int readInt16(InputStream is) throws IOException { int lo = is.read(); int hi = is.read(); return (hi << 8) | lo; } /** * Returns the offset from UTC for the given city. If USE_RAW_OFFSETS * is true, summer/daylight savings is ignored. */ private static float getOffset(City c) { return USE_RAW_OFFSETS ? c.getRawOffset() : c.getOffset(); } private InputStream cache(InputStream is) throws IOException { int nbytes = is.available(); byte[] data = new byte[nbytes]; int nread = 0; while (nread < nbytes) { nread += is.read(data, nread, nbytes - nread); } return new ByteArrayInputStream(data); } /** * Load the city and lights databases. * * @param am the AssetManager to load from. */ private void loadAssets(final AssetManager am) throws IOException { Locale locale = Locale.getDefault(); String language = locale.getLanguage(); String country = locale.getCountry(); InputStream cis = null; try { // Look for (e.g.) cities_fr_FR.dat or cities_fr_CA.dat cis = am.open("cities_" + language + "_" + country + ".dat"); } catch (FileNotFoundException e1) { try { // Look for (e.g.) cities_fr.dat or cities_fr.dat cis = am.open("cities_" + language + ".dat"); } catch (FileNotFoundException e2) { try { // Use English city names by default cis = am.open("cities_en.dat"); } catch (FileNotFoundException e3) { throw e3; } } } cis = cache(cis); City.loadCities(cis); City[] cities; if (USE_RAW_OFFSETS) { cities = City.getCitiesByRawOffset(); } else { cities = City.getCitiesByOffset(); } mClockCities = new ArrayList<City>(cities.length); for (int i = 0; i < cities.length; i++) { mClockCities.add(cities[i]); } mCities = mClockCities; mCityIndex = 0; this.mWorld = new Object3D() { @Override public InputStream readFile(String filename) throws IOException { return cache(am.open(filename)); } }; mWorld.load("world.gles"); // lights.dat has the following format. All integers // are 16 bits, low byte first. // // width // height // N [# of lights] // light 0 X [in the range 0 to (width - 1)] // light 0 Y ]in the range 0 to (height - 1)] // light 1 X [in the range 0 to (width - 1)] // light 1 Y ]in the range 0 to (height - 1)] // ... // light (N - 1) X [in the range 0 to (width - 1)] // light (N - 1) Y ]in the range 0 to (height - 1)] // // For a larger number of lights, it could make more // sense to store the light positions in a bitmap // and extract them manually InputStream lis = am.open("lights.dat"); lis = cache(lis); int lightWidth = readInt16(lis); int lightHeight = readInt16(lis); sNumLights = readInt16(lis); sLightCoords = new int[3 * sNumLights]; int lidx = 0; float lightRadius = 1.009f; float lightScale = 65536.0f * lightRadius; float[] cosTheta = new float[lightWidth]; float[] sinTheta = new float[lightWidth]; float twoPi = (float) (2.0 * Math.PI); float scaleW = twoPi / lightWidth; for (int i = 0; i < lightWidth; i++) { float theta = twoPi - i * scaleW; cosTheta[i] = (float)Math.cos(theta); sinTheta[i] = (float)Math.sin(theta); } float[] cosPhi = new float[lightHeight]; float[] sinPhi = new float[lightHeight]; float scaleH = (float) (Math.PI / lightHeight); for (int j = 0; j < lightHeight; j++) { float phi = j * scaleH; cosPhi[j] = (float)Math.cos(phi); sinPhi[j] = (float)Math.sin(phi); } int nbytes = 4 * sNumLights; byte[] ilights = new byte[nbytes]; int nread = 0; while (nread < nbytes) { nread += lis.read(ilights, nread, nbytes - nread); } int idx = 0; for (int i = 0; i < sNumLights; i++) { int lx = (((ilights[idx + 1] & 0xff) << 8) | (ilights[idx ] & 0xff)); int ly = (((ilights[idx + 3] & 0xff) << 8) | (ilights[idx + 2] & 0xff)); idx += 4; float sin = sinPhi[ly]; float x = cosTheta[lx]*sin; float y = cosPhi[ly]; float z = sinTheta[lx]*sin; sLightCoords[lidx++] = (int) (x * lightScale); sLightCoords[lidx++] = (int) (y * lightScale); sLightCoords[lidx++] = (int) (z * lightScale); } mLights = new PointCloud(sLightCoords); } /** * Returns true if two time zone offsets are equal. We assume distinct * time zone offsets will differ by at least a few minutes. */ private boolean tzEqual(float o1, float o2) { return Math.abs(o1 - o2) < 0.001; } /** * Move to a different time zone. * * @param incr The increment between the current and future time zones. */ private void shiftTimeZone(int incr) { // If only 1 city in the current set, there's nowhere to go if (mCities.size() <= 1) { return; } float offset = getOffset(mCities.get(mCityIndex)); do { mCityIndex = (mCityIndex + mCities.size() + incr) % mCities.size(); } while (tzEqual(getOffset(mCities.get(mCityIndex)), offset)); offset = getOffset(mCities.get(mCityIndex)); locateCity(true, offset); goToCity(); } /** * Returns true if there is another city within the current time zone * that is the given increment away from the current city. * * @param incr the increment, +1 or -1 * @return */ private boolean atEndOfTimeZone(int incr) { if (mCities.size() <= 1) { return true; } float offset = getOffset(mCities.get(mCityIndex)); int nindex = (mCityIndex + mCities.size() + incr) % mCities.size(); if (tzEqual(getOffset(mCities.get(nindex)), offset)) { return false; } return true; } /** * Shifts cities within the current time zone. * * @param incr the increment, +1 or -1 */ private void shiftWithinTimeZone(int incr) { float offset = getOffset(mCities.get(mCityIndex)); int nindex = (mCityIndex + mCities.size() + incr) % mCities.size(); if (tzEqual(getOffset(mCities.get(nindex)), offset)) { mCityIndex = nindex; goToCity(); } } /** * Returns true if the city name matches the given prefix, ignoring spaces. */ private boolean nameMatches(City city, String prefix) { String cityName = city.getName().replaceAll("[ ]", ""); return prefix.regionMatches(true, 0, cityName, 0, prefix.length()); } /** * Returns true if there are cities matching the given name prefix. */ private boolean hasMatches(String prefix) { for (int i = 0; i < mClockCities.size(); i++) { City city = mClockCities.get(i); if (nameMatches(city, prefix)) { return true; } } return false; } /** * Shifts to the nearest city that matches the new prefix. */ private void shiftByName() { // Attempt to keep current city if it matches City finalCity = null; City currCity = mCities.get(mCityIndex); if (nameMatches(currCity, mCityName)) { finalCity = currCity; } mCityNameMatches.clear(); for (int i = 0; i < mClockCities.size(); i++) { City city = mClockCities.get(i); if (nameMatches(city, mCityName)) { mCityNameMatches.add(city); } } mCities = mCityNameMatches; if (finalCity != null) { for (int i = 0; i < mCityNameMatches.size(); i++) { if (mCityNameMatches.get(i) == finalCity) { mCityIndex = i; break; } } } else { // Find the closest matching city locateCity(false, 0.0f); } goToCity(); } /** * Increases or decreases the rotational speed of the earth. */ private void incrementRotationalVelocity(float incr) { if (mDisplayWorldFlat) { mWrapVelocity -= incr; } else { mRotVelocity -= incr; } } /** * Clears the current matching prefix, while keeping the focus on * the current city. */ private void clearCityMatches() { // Determine the global city index that matches the current city if (mCityNameMatches.size() > 0) { City city = mCityNameMatches.get(mCityIndex); for (int i = 0; i < mClockCities.size(); i++) { City ncity = mClockCities.get(i); if (city.equals(ncity)) { mCityIndex = i; break; } } } mCityName = ""; mCityNameMatches.clear(); mCities = mClockCities; goToCity(); } /** * Fade the clock in or out. */ private void enableClock(boolean enabled) { mClockFadeTime = System.currentTimeMillis(); mDisplayClock = enabled; mClockShowing = true; mAlphaKeySet = enabled; if (enabled) { // Find the closest matching city locateCity(false, 0.0f); } clearCityMatches(); } /** * Use the touchscreen to alter the rotational velocity or the * tilt of the earth. */ @Override public boolean onTouchEvent(MotionEvent event) { switch (event.getAction()) { case MotionEvent.ACTION_DOWN: mMotionStartX = event.getX(); mMotionStartY = event.getY(); mMotionStartRotVelocity = mDisplayWorldFlat ? mWrapVelocity : mRotVelocity; mMotionStartTiltAngle = mTiltAngle; // Stop the rotation if (mDisplayWorldFlat) { mWrapVelocity = 0.0f; } else { mRotVelocity = 0.0f; } mMotionDirection = MOTION_NONE; break; case MotionEvent.ACTION_MOVE: // Disregard motion events when the clock is displayed float dx = event.getX() - mMotionStartX; float dy = event.getY() - mMotionStartY; float delx = Math.abs(dx); float dely = Math.abs(dy); // Determine the direction of motion (major axis) // Once if has been determined, it's locked in until // we receive ACTION_UP or ACTION_CANCEL if ((mMotionDirection == MOTION_NONE) && (delx + dely > MIN_MANHATTAN_DISTANCE)) { if (delx > dely) { mMotionDirection = MOTION_X; } else { mMotionDirection = MOTION_Y; } } // If the clock is displayed, don't actually rotate or tilt; // just use mMotionDirection to record whether motion occurred if (!mDisplayClock) { if (mMotionDirection == MOTION_X) { if (mDisplayWorldFlat) { mWrapVelocity = mMotionStartRotVelocity + dx * ROTATION_FACTOR; } else { mRotVelocity = mMotionStartRotVelocity + dx * ROTATION_FACTOR; } mClock.setCity(null); } else if (mMotionDirection == MOTION_Y && !mDisplayWorldFlat) { mTiltAngle = mMotionStartTiltAngle + dy * TILT_FACTOR; if (mTiltAngle < -90.0f) { mTiltAngle = -90.0f; } if (mTiltAngle > 90.0f) { mTiltAngle = 90.0f; } mClock.setCity(null); } } break; case MotionEvent.ACTION_UP: mMotionDirection = MOTION_NONE; break; case MotionEvent.ACTION_CANCEL: mTiltAngle = mMotionStartTiltAngle; if (mDisplayWorldFlat) { mWrapVelocity = mMotionStartRotVelocity; } else { mRotVelocity = mMotionStartRotVelocity; } mMotionDirection = MOTION_NONE; break; } return true; } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (mInitialized && mGLView.processKey(keyCode)) { boolean drawing = (mClockShowing || mGLView.hasMessages()); this.setWillNotDraw(!drawing); return true; } boolean handled = false; // If we're not in alphabetical entry mode, convert letters // to their digit equivalents if (!mAlphaKeySet) { char numChar = event.getNumber(); if (numChar >= '0' && numChar <= '9') { keyCode = KeyEvent.KEYCODE_0 + (numChar - '0'); } } switch (keyCode) { // The 'space' key toggles the clock case KeyEvent.KEYCODE_SPACE: mAlphaKeySet = !mAlphaKeySet; enableClock(mAlphaKeySet); handled = true; break; // The 'left' and 'right' buttons shift time zones if the clock is // displayed, otherwise they alters the rotational speed of the earthh case KeyEvent.KEYCODE_DPAD_LEFT: if (mDisplayClock) { shiftTimeZone(-1); } else { mClock.setCity(null); incrementRotationalVelocity(1.0f); } handled = true; break; case KeyEvent.KEYCODE_DPAD_RIGHT: if (mDisplayClock) { shiftTimeZone(1); } else { mClock.setCity(null); incrementRotationalVelocity(-1.0f); } handled = true; break; // The 'up' and 'down' buttons shift cities within a time zone if the // clock is displayed, otherwise they tilt the earth case KeyEvent.KEYCODE_DPAD_UP: if (mDisplayClock) { shiftWithinTimeZone(-1); } else { mClock.setCity(null); if (!mDisplayWorldFlat) { mTiltAngle += 360.0f / 48.0f; } } handled = true; break; case KeyEvent.KEYCODE_DPAD_DOWN: if (mDisplayClock) { shiftWithinTimeZone(1); } else { mClock.setCity(null); if (!mDisplayWorldFlat) { mTiltAngle -= 360.0f / 48.0f; } } handled = true; break; // The center key stops the earth's rotation, then toggles between the // round and flat views of the earth case KeyEvent.KEYCODE_DPAD_CENTER: if ((!mDisplayWorldFlat && mRotVelocity == 0.0f) || (mDisplayWorldFlat && mWrapVelocity == 0.0f)) { mDisplayWorldFlat = !mDisplayWorldFlat; } else { if (mDisplayWorldFlat) { mWrapVelocity = 0.0f; } else { mRotVelocity = 0.0f; } } handled = true; break; // The 'L' key toggles the city lights case KeyEvent.KEYCODE_L: if (!mAlphaKeySet && !mDisplayWorldFlat) { mDisplayLights = !mDisplayLights; handled = true; } break; // The 'W' key toggles the earth (just for fun) case KeyEvent.KEYCODE_W: if (!mAlphaKeySet && !mDisplayWorldFlat) { mDisplayWorld = !mDisplayWorld; handled = true; } break; // The 'A' key toggles the atmosphere case KeyEvent.KEYCODE_A: if (!mAlphaKeySet && !mDisplayWorldFlat) { mDisplayAtmosphere = !mDisplayAtmosphere; handled = true; } break; // The '2' key zooms out case KeyEvent.KEYCODE_2: if (!mAlphaKeySet && !mDisplayWorldFlat) { mGLView.zoom(-2); handled = true; } break; // The '8' key zooms in case KeyEvent.KEYCODE_8: if (!mAlphaKeySet && !mDisplayWorldFlat) { mGLView.zoom(2); handled = true; } break; } // Handle letters in city names if (!handled && mAlphaKeySet) { switch (keyCode) { // Add a letter to the city name prefix case KeyEvent.KEYCODE_A: case KeyEvent.KEYCODE_B: case KeyEvent.KEYCODE_C: case KeyEvent.KEYCODE_D: case KeyEvent.KEYCODE_E: case KeyEvent.KEYCODE_F: case KeyEvent.KEYCODE_G: case KeyEvent.KEYCODE_H: case KeyEvent.KEYCODE_I: case KeyEvent.KEYCODE_J: case KeyEvent.KEYCODE_K: case KeyEvent.KEYCODE_L: case KeyEvent.KEYCODE_M: case KeyEvent.KEYCODE_N: case KeyEvent.KEYCODE_O: case KeyEvent.KEYCODE_P: case KeyEvent.KEYCODE_Q: case KeyEvent.KEYCODE_R: case KeyEvent.KEYCODE_S: case KeyEvent.KEYCODE_T: case KeyEvent.KEYCODE_U: case KeyEvent.KEYCODE_V: case KeyEvent.KEYCODE_W: case KeyEvent.KEYCODE_X: case KeyEvent.KEYCODE_Y: case KeyEvent.KEYCODE_Z: char c = (char)(keyCode - KeyEvent.KEYCODE_A + 'A'); if (hasMatches(mCityName + c)) { mCityName += c; shiftByName(); } handled = true; break; // Remove a letter from the city name prefix case KeyEvent.KEYCODE_DEL: if (mCityName.length() > 0) { mCityName = mCityName.substring(0, mCityName.length() - 1); shiftByName(); } else { clearCityMatches(); } handled = true; break; // Clear the city name prefix case KeyEvent.KEYCODE_ENTER: clearCityMatches(); handled = true; break; } } boolean drawing = (mClockShowing || ((mGLView != null) && (mGLView.hasMessages()))); this.setWillNotDraw(!drawing); // Let the system handle other keypresses if (!handled) { return super.onKeyDown(keyCode, event); } return true; } /** * Initialize OpenGL ES drawing. */ private synchronized void init(GL10 gl) { mGLView = new GLView(); mGLView.setNearFrustum(5.0f); mGLView.setFarFrustum(50.0f); mGLView.setLightModelAmbientIntensity(0.225f); mGLView.setAmbientIntensity(0.0f); mGLView.setDiffuseIntensity(1.5f); mGLView.setDiffuseColor(SUNLIGHT_COLOR); mGLView.setSpecularIntensity(0.0f); mGLView.setSpecularColor(SUNLIGHT_COLOR); if (PERFORM_DEPTH_TEST) { gl.glEnable(GL10.GL_DEPTH_TEST); } gl.glDisable(GL10.GL_SCISSOR_TEST); gl.glClearColor(0, 0, 0, 1); gl.glHint(GL10.GL_POINT_SMOOTH_HINT, GL10.GL_NICEST); mInitialized = true; } /** * Computes the vector from the center of the earth to the sun for a * particular moment in time. */ private void computeSunDirection() { mSunCal.setTimeInMillis(System.currentTimeMillis()); int day = mSunCal.get(Calendar.DAY_OF_YEAR); int seconds = 3600 * mSunCal.get(Calendar.HOUR_OF_DAY) + 60 * mSunCal.get(Calendar.MINUTE) + mSunCal.get(Calendar.SECOND); day += (float) seconds / SECONDS_PER_DAY; // Approximate declination of the sun, changes sinusoidally // during the year. The winter solstice occurs 10 days before // the start of the year. float decl = (float) (EARTH_INCLINATION * Math.cos(Shape.TWO_PI * (day + 10) / 365.0)); // Subsolar latitude, convert from (-PI/2, PI/2) -> (0, PI) form float phi = decl + Shape.PI_OVER_TWO; // Subsolar longitude float theta = Shape.TWO_PI * seconds / SECONDS_PER_DAY; float sinPhi = (float) Math.sin(phi); float cosPhi = (float) Math.cos(phi); float sinTheta = (float) Math.sin(theta); float cosTheta = (float) Math.cos(theta); // Convert from polar to rectangular coordinates float x = cosTheta * sinPhi; float y = cosPhi; float z = sinTheta * sinPhi; // Directional light -> w == 0 mLightDir[0] = x; mLightDir[1] = y; mLightDir[2] = z; mLightDir[3] = 0.0f; } /** * Computes the approximate spherical distance between two * (latitude, longitude) coordinates. */ private float distance(float lat1, float lon1, float lat2, float lon2) { lat1 *= Shape.DEGREES_TO_RADIANS; lat2 *= Shape.DEGREES_TO_RADIANS; lon1 *= Shape.DEGREES_TO_RADIANS; lon2 *= Shape.DEGREES_TO_RADIANS; float r = 6371.0f; // Earth's radius in km float dlat = lat2 - lat1; float dlon = lon2 - lon1; double sinlat2 = Math.sin(dlat / 2.0f); sinlat2 *= sinlat2; double sinlon2 = Math.sin(dlon / 2.0f); sinlon2 *= sinlon2; double a = sinlat2 + Math.cos(lat1) * Math.cos(lat2) * sinlon2; double c = 2.0 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a)); return (float) (r * c); } /** * Locates the closest city to the currently displayed center point, * optionally restricting the search to cities within a given time zone. */ private void locateCity(boolean useOffset, float offset) { float mindist = Float.MAX_VALUE; int minidx = -1; for (int i = 0; i < mCities.size(); i++) { City city = mCities.get(i); if (useOffset && !tzEqual(getOffset(city), offset)) { continue; } float dist = distance(city.getLatitude(), city.getLongitude(), mTiltAngle, mRotAngle - 90.0f); if (dist < mindist) { mindist = dist; minidx = i; } } mCityIndex = minidx; } /** * Animates the earth to be centered at the current city. */ private void goToCity() { City city = mCities.get(mCityIndex); float dist = distance(city.getLatitude(), city.getLongitude(), mTiltAngle, mRotAngle - 90.0f); mFlyToCity = true; mCityFlyStartTime = System.currentTimeMillis(); mCityFlightTime = dist / 5.0f; // 5000 km/sec mRotAngleStart = mRotAngle; mRotAngleDest = city.getLongitude() + 90; if (mRotAngleDest - mRotAngleStart > 180.0f) { mRotAngleDest -= 360.0f; } else if (mRotAngleStart - mRotAngleDest > 180.0f) { mRotAngleDest += 360.0f; } mTiltAngleStart = mTiltAngle; mTiltAngleDest = city.getLatitude(); mRotVelocity = 0.0f; } /** * Returns a linearly interpolated value between two values. */ private float lerp(float a, float b, float lerp) { return a + (b - a)*lerp; } /** * Draws the city lights, using a clip plane to restrict the lights * to the night side of the earth. */ private void drawCityLights(GL10 gl, float brightness) { gl.glEnable(GL10.GL_POINT_SMOOTH); gl.glDisable(GL10.GL_DEPTH_TEST); gl.glDisable(GL10.GL_LIGHTING); gl.glDisable(GL10.GL_DITHER); gl.glShadeModel(GL10.GL_FLAT); gl.glEnable(GL10.GL_BLEND); gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); gl.glPointSize(1.0f); float ls = lerp(0.8f, 0.3f, brightness); gl.glColor4f(ls * 1.0f, ls * 1.0f, ls * 0.8f, 1.0f); if (mDisplayWorld) { mClipPlaneEquation[0] = -mLightDir[0]; mClipPlaneEquation[1] = -mLightDir[1]; mClipPlaneEquation[2] = -mLightDir[2]; mClipPlaneEquation[3] = 0.0f; // Assume we have glClipPlanef() from OpenGL ES 1.1 ((GL11) gl).glClipPlanef(GL11.GL_CLIP_PLANE0, mClipPlaneEquation, 0); gl.glEnable(GL11.GL_CLIP_PLANE0); } mLights.draw(gl); if (mDisplayWorld) { gl.glDisable(GL11.GL_CLIP_PLANE0); } mNumTriangles += mLights.getNumTriangles()*2; } /** * Draws the atmosphere. */ private void drawAtmosphere(GL10 gl) { gl.glDisable(GL10.GL_LIGHTING); gl.glDisable(GL10.GL_CULL_FACE); gl.glDisable(GL10.GL_DITHER); gl.glDisable(GL10.GL_DEPTH_TEST); gl.glShadeModel(mSmoothShading ? GL10.GL_SMOOTH : GL10.GL_FLAT); // Draw the atmospheric layer float tx = mGLView.getTranslateX(); float ty = mGLView.getTranslateY(); float tz = mGLView.getTranslateZ(); gl.glMatrixMode(GL10.GL_MODELVIEW); gl.glLoadIdentity(); gl.glTranslatef(tx, ty, tz); // Blend in the atmosphere a bit gl.glEnable(GL10.GL_BLEND); gl.glBlendFunc(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); ATMOSPHERE.draw(gl); mNumTriangles += ATMOSPHERE.getNumTriangles(); } /** * Draws the world in a 2D map view. */ private void drawWorldFlat(GL10 gl) { gl.glDisable(GL10.GL_BLEND); gl.glEnable(GL10.GL_DITHER); gl.glShadeModel(mSmoothShading ? GL10.GL_SMOOTH : GL10.GL_FLAT); gl.glTranslatef(mWrapX - 2, 0.0f, 0.0f); worldFlat.draw(gl); gl.glTranslatef(2.0f, 0.0f, 0.0f); worldFlat.draw(gl); mNumTriangles += worldFlat.getNumTriangles() * 2; mWrapX += mWrapVelocity * mWrapVelocityFactor; while (mWrapX < 0.0f) { mWrapX += 2.0f; } while (mWrapX > 2.0f) { mWrapX -= 2.0f; } } /** * Draws the world in a 2D round view. */ private void drawWorldRound(GL10 gl) { gl.glDisable(GL10.GL_BLEND); gl.glEnable(GL10.GL_DITHER); gl.glShadeModel(mSmoothShading ? GL10.GL_SMOOTH : GL10.GL_FLAT); mWorld.draw(gl); mNumTriangles += mWorld.getNumTriangles(); } /** * Draws the clock. * * @param canvas the Canvas to draw to * @param now the current time * @param w the width of the screen * @param h the height of the screen * @param lerp controls the animation, between 0.0 and 1.0 */ private void drawClock(Canvas canvas, long now, int w, int h, float lerp) { float clockAlpha = lerp(0.0f, 0.8f, lerp); mClockShowing = clockAlpha > 0.0f; if (clockAlpha > 0.0f) { City city = mCities.get(mCityIndex); mClock.setCity(city); mClock.setTime(now); float cx = w / 2.0f; float cy = h / 2.0f; float smallRadius = 18.0f; float bigRadius = 0.75f * 0.5f * Math.min(w, h); float radius = lerp(smallRadius, bigRadius, lerp); // Only display left/right arrows if we are in a name search boolean scrollingByName = (mCityName.length() > 0) && (mCities.size() > 1); mClock.drawClock(canvas, cx, cy, radius, clockAlpha, 1.0f, lerp == 1.0f, lerp == 1.0f, !atEndOfTimeZone(-1), !atEndOfTimeZone(1), scrollingByName, mCityName.length()); } } /** * Draws the 2D layer. */ @Override protected void onDraw(Canvas canvas) { long now = System.currentTimeMillis(); if (startTime != -1) { startTime = -1; } int w = getWidth(); int h = getHeight(); // Interpolator for clock size, clock alpha, night lights intensity float lerp = Math.min((now - mClockFadeTime)/1000.0f, 1.0f); if (!mDisplayClock) { // Clock is receding lerp = 1.0f - lerp; } lerp = mClockSizeInterpolator.getInterpolation(lerp); // we don't need to make sure OpenGL rendering is done because // we're drawing in to a different surface drawClock(canvas, now, w, h, lerp); mGLView.showMessages(canvas); mGLView.showStatistics(canvas, w); } /** * Draws the 3D layer. */ protected void drawOpenGLScene() { long now = System.currentTimeMillis(); mNumTriangles = 0; EGL10 egl = (EGL10)EGLContext.getEGL(); GL10 gl = (GL10)mEGLContext.getGL(); if (!mInitialized) { init(gl); } int w = getWidth(); int h = getHeight(); gl.glViewport(0, 0, w, h); gl.glEnable(GL10.GL_LIGHTING); gl.glEnable(GL10.GL_LIGHT0); gl.glEnable(GL10.GL_CULL_FACE); gl.glFrontFace(GL10.GL_CCW); float ratio = (float) w / h; mGLView.setAspectRatio(ratio); mGLView.setTextureParameters(gl); if (PERFORM_DEPTH_TEST) { gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); } else { gl.glClear(GL10.GL_COLOR_BUFFER_BIT); } if (mDisplayWorldFlat) { gl.glMatrixMode(GL10.GL_PROJECTION); gl.glLoadIdentity(); gl.glFrustumf(-1.0f, 1.0f, -1.0f / ratio, 1.0f / ratio, 1.0f, 2.0f); gl.glMatrixMode(GL10.GL_MODELVIEW); gl.glLoadIdentity(); gl.glTranslatef(0.0f, 0.0f, -1.0f); } else { mGLView.setProjection(gl); mGLView.setView(gl); } if (!mDisplayWorldFlat) { if (mFlyToCity) { float lerp = (now - mCityFlyStartTime)/mCityFlightTime; if (lerp >= 1.0f) { mFlyToCity = false; } lerp = Math.min(lerp, 1.0f); lerp = mFlyToCityInterpolator.getInterpolation(lerp); mRotAngle = lerp(mRotAngleStart, mRotAngleDest, lerp); mTiltAngle = lerp(mTiltAngleStart, mTiltAngleDest, lerp); } // Rotate the viewpoint around the earth gl.glMatrixMode(GL10.GL_MODELVIEW); gl.glRotatef(mTiltAngle, 1, 0, 0); gl.glRotatef(mRotAngle, 0, 1, 0); // Increment the rotation angle mRotAngle += mRotVelocity; if (mRotAngle < 0.0f) { mRotAngle += 360.0f; } if (mRotAngle > 360.0f) { mRotAngle -= 360.0f; } } // Draw the world with lighting gl.glLightfv(GL10.GL_LIGHT0, GL10.GL_POSITION, mLightDir, 0); mGLView.setLights(gl, GL10.GL_LIGHT0); if (mDisplayWorldFlat) { drawWorldFlat(gl); } else if (mDisplayWorld) { drawWorldRound(gl); } if (mDisplayLights && !mDisplayWorldFlat) { // Interpolator for clock size, clock alpha, night lights intensity float lerp = Math.min((now - mClockFadeTime)/1000.0f, 1.0f); if (!mDisplayClock) { // Clock is receding lerp = 1.0f - lerp; } lerp = mClockSizeInterpolator.getInterpolation(lerp); drawCityLights(gl, lerp); } if (mDisplayAtmosphere && !mDisplayWorldFlat) { drawAtmosphere(gl); } mGLView.setNumTriangles(mNumTriangles); egl.eglSwapBuffers(mEGLDisplay, mEGLSurface); if (egl.eglGetError() == EGL11.EGL_CONTEXT_LOST) { // we lost the gpu, quit immediately Context c = getContext(); if (c instanceof Activity) { ((Activity)c).finish(); } } } private static final int INVALIDATE = 1; private static final int ONE_MINUTE = 60000; /** * Controls the animation using the message queue. Every time we receive * an INVALIDATE message, we redraw and place another message in the queue. */ private final Handler mHandler = new Handler() { private long mLastSunPositionTime = 0; @Override public void handleMessage(Message msg) { if (msg.what == INVALIDATE) { // Use the message's time, it's good enough and // allows us to avoid a system call. if ((msg.getWhen() - mLastSunPositionTime) >= ONE_MINUTE) { // Recompute the sun's position once per minute // Place the light at the Sun's direction computeSunDirection(); mLastSunPositionTime = msg.getWhen(); } // Draw the GL scene drawOpenGLScene(); // Send an update for the 2D overlay if needed if (mInitialized && (mClockShowing || mGLView.hasMessages())) { invalidate(); } // Just send another message immediately. This works because // drawOpenGLScene() does the timing for us -- it will // block until the last frame has been processed. // The invalidate message we're posting here will be // interleaved properly with motion/key events which // guarantee a prompt reaction to the user input. sendEmptyMessage(INVALIDATE); } } }; } /** * The main activity class for GlobalTime. */ public class GlobalTime extends Activity { GTView gtView = null; private void setGTView() { if (gtView == null) { gtView = new GTView(this); setContentView(gtView); } } @Override protected void onCreate(Bundle icicle) { super.onCreate(icicle); setGTView(); } @Override protected void onResume() { super.onResume(); setGTView(); Looper.myQueue().addIdleHandler(new Idler()); } @Override protected void onPause() { super.onPause(); gtView.stopAnimating(); } @Override protected void onStop() { super.onStop(); gtView.stopAnimating(); gtView.destroy(); gtView = null; } // Allow the activity to go idle before its animation starts class Idler implements MessageQueue.IdleHandler { public Idler() { super(); } public final boolean queueIdle() { if (gtView != null) { gtView.startAnimating(); } return false; } } }
Java
/* * Copyright (C) 2006-2007 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.globaltime; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.HashMap; import javax.microedition.khronos.opengles.GL10; import android.graphics.Canvas; import android.graphics.Paint; import android.view.KeyEvent; class Message { private String mText; private long mExpirationTime; public Message(String text, long expirationTime) { this.mText = text; this.mExpirationTime = expirationTime; } public String getText() { return mText; } public long getExpirationTime() { return mExpirationTime; } } /** * A helper class to simplify writing an Activity that renders using * OpenGL ES. * * <p> A GLView object stores common elements of GL state and allows * them to be modified interactively. This is particularly useful for * determining the proper settings of parameters such as the view * frustum and light intensities during application development. * * <p> A GLView is not an actual View; instead, it is meant to be * called from within a View to perform event processing on behalf of the * actual View. * * <p> By passing key events to the GLView object from the View, * the application can automatically allow certain parameters to * be user-controlled from the keyboard. Key events may be passed as * shown below: * * <pre> * GLView mGlView = new GLView(); * * public boolean onKeyDown(int keyCode, KeyEvent event) { * // Hand the key to the GLView object first * if (mGlView.processKey(keyCode)) { * return; * } * * switch (keyCode) { * case KeyEvent.KEY_CODE_X: * // perform app processing * break; * * default: * super.onKeyDown(keyCode, event); * break; * } * } * </pre> * * <p> During drawing of a frame, the GLView object should be given the * opportunity to manage GL parameters as shown below: * * OpenGLContext mGLContext; // initialization not shown * int mNumTrianglesDrawn = 0; * * protected void onDraw(Canvas canvas) { * int w = getWidth(); * int h = getHeight(); * * float ratio = (float) w / h; * mGLView.setAspectRatio(ratio); * * GL10 gl = (GL10) mGLContext.getGL(); * mGLContext.waitNative(canvas, this); * * // Enable a light for the GLView to manipulate * gl.glEnable(GL10.GL_LIGHTING); * gl.glEnable(GL10.GL_LIGHT0); * * // Allow the GLView to set GL parameters * mGLView.setTextureParameters(gl); * mGLView.setProjection(gl); * mGLView.setView(gl); * mGLView.setLights(gl, GL10.GL_LIGHT0); * * // Draw some stuff (not shown) * mNumTrianglesDrawn += <num triangles just drawn>; * * // Wait for GL drawing to complete * mGLContext.waitGL(); * * // Inform the GLView of what was drawn, and ask it to display statistics * mGLView.setNumTriangles(mNumTrianglesDrawn); * mGLView.showMessages(canvas); * mGLView.showStatistics(canvas, w); * } * </pre> * * <p> At the end of each frame, following the call to * GLContext.waitGL, the showStatistics and showMessages methods * will cause additional information to be displayed. * * <p> To enter the interactive command mode, the 'tab' key must be * pressed twice in succession. A subsequent press of the 'tab' key * exits the interactive command mode. Entering a multi-letter code * sets the parameter to be modified. The 'newline' key erases the * current code, and the 'del' key deletes the last letter of * the code. The parameter value may be modified by pressing the * keypad left or up to decrement the value and right or down to * increment the value. The current value will be displayed as an * overlay above the GL rendered content. * * <p> The supported keyboard commands are as follows: * * <ul> * <li> h - display a list of commands * <li> fn - near frustum * <li> ff - far frustum * <li> tx - translate x * <li> ty - translate y * <li> tz - translate z * <li> z - zoom (frustum size) * <li> la - ambient light (all RGB channels) * <li> lar - ambient light red channel * <li> lag - ambient light green channel * <li> lab - ambient light blue channel * <li> ld - diffuse light (all RGB channels) * <li> ldr - diffuse light red channel * <li> ldg - diffuse light green channel * <li> ldb - diffuse light blue channel * <li> ls - specular light (all RGB channels) * <li> lsr - specular light red channel * <li> lsg - specular light green channel * <li> lsb - specular light blue channel * <li> lma - light model ambient (all RGB channels) * <li> lmar - light model ambient light red channel * <li> lmag - light model ambient green channel * <li> lmab - light model ambient blue channel * <li> tmin - texture min filter * <li> tmag - texture mag filter * <li> tper - texture perspective correction * </ul> * * {@hide} */ public class GLView { private static final int DEFAULT_DURATION_MILLIS = 1000; private static final int STATE_KEY = KeyEvent.KEYCODE_TAB; private static final int HAVE_NONE = 0; private static final int HAVE_ONE = 1; private static final int HAVE_TWO = 2; private static final float MESSAGE_Y_SPACING = 12.0f; private int mState = HAVE_NONE; private static final int NEAR_FRUSTUM = 0; private static final int FAR_FRUSTUM = 1; private static final int TRANSLATE_X = 2; private static final int TRANSLATE_Y = 3; private static final int TRANSLATE_Z = 4; private static final int ZOOM_EXPONENT = 5; private static final int AMBIENT_INTENSITY = 6; private static final int AMBIENT_RED = 7; private static final int AMBIENT_GREEN = 8; private static final int AMBIENT_BLUE = 9; private static final int DIFFUSE_INTENSITY = 10; private static final int DIFFUSE_RED = 11; private static final int DIFFUSE_GREEN = 12; private static final int DIFFUSE_BLUE = 13; private static final int SPECULAR_INTENSITY = 14; private static final int SPECULAR_RED = 15; private static final int SPECULAR_GREEN = 16; private static final int SPECULAR_BLUE = 17; private static final int LIGHT_MODEL_AMBIENT_INTENSITY = 18; private static final int LIGHT_MODEL_AMBIENT_RED = 19; private static final int LIGHT_MODEL_AMBIENT_GREEN = 20; private static final int LIGHT_MODEL_AMBIENT_BLUE = 21; private static final int TEXTURE_MIN_FILTER = 22; private static final int TEXTURE_MAG_FILTER = 23; private static final int TEXTURE_PERSPECTIVE_CORRECTION = 24; private static final String[] commands = { "fn", "ff", "tx", "ty", "tz", "z", "la", "lar", "lag", "lab", "ld", "ldr", "ldg", "ldb", "ls", "lsr", "lsg", "lsb", "lma", "lmar", "lmag", "lmab", "tmin", "tmag", "tper" }; private static final String[] labels = { "Near Frustum", "Far Frustum", "Translate X", "Translate Y", "Translate Z", "Zoom", "Ambient Intensity", "Ambient Red", "Ambient Green", "Ambient Blue", "Diffuse Intensity", "Diffuse Red", "Diffuse Green", "Diffuse Blue", "Specular Intenstity", "Specular Red", "Specular Green", "Specular Blue", "Light Model Ambient Intensity", "Light Model Ambient Red", "Light Model Ambient Green", "Light Model Ambient Blue", "Texture Min Filter", "Texture Mag Filter", "Texture Perspective Correction", }; private static final float[] defaults = { 5.0f, 100.0f, 0.0f, 0.0f, -50.0f, 0, 0.125f, 1.0f, 1.0f, 1.0f, 0.125f, 1.0f, 1.0f, 1.0f, 0.125f, 1.0f, 1.0f, 1.0f, 0.125f, 1.0f, 1.0f, 1.0f, GL10.GL_NEAREST, GL10.GL_NEAREST, GL10.GL_FASTEST }; private static final float[] increments = { 0.01f, 0.5f, 0.125f, 0.125f, 0.125f, 1.0f, 0.03125f, 0.1f, 0.1f, 0.1f, 0.03125f, 0.1f, 0.1f, 0.1f, 0.03125f, 0.1f, 0.1f, 0.1f, 0.03125f, 0.1f, 0.1f, 0.1f, 0, 0, 0 }; private float[] params = new float[commands.length]; private static final float mZoomScale = 0.109f; private static final float mZoomBase = 1.01f; private int mParam = -1; private float mIncr = 0; private Paint mPaint = new Paint(); private float mAspectRatio = 1.0f; private float mZoom; // private boolean mPerspectiveCorrection = false; // private int mTextureMinFilter = GL10.GL_NEAREST; // private int mTextureMagFilter = GL10.GL_NEAREST; // Counters for FPS calculation private boolean mDisplayFPS = false; private boolean mDisplayCounts = false; private int mFramesFPS = 10; private long[] mTimes = new long[mFramesFPS]; private int mTimesIdx = 0; private Map<String,Message> mMessages = new HashMap<String,Message>(); /** * Constructs a new GLView. */ public GLView() { mPaint.setColor(0xffffffff); reset(); } /** * Sets the aspect ratio (width/height) of the screen. * * @param aspectRatio the screen width divided by the screen height */ public void setAspectRatio(float aspectRatio) { this.mAspectRatio = aspectRatio; } /** * Sets the overall ambient light intensity. This intensity will * be used to modify the ambient light value for each of the red, * green, and blue channels passed to glLightfv(...GL_AMBIENT...). * The default value is 0.125f. * * @param intensity a floating-point value controlling the overall * ambient light intensity. */ public void setAmbientIntensity(float intensity) { params[AMBIENT_INTENSITY] = intensity; } /** * Sets the light model ambient intensity. This intensity will be * used to modify the ambient light value for each of the red, * green, and blue channels passed to * glLightModelfv(GL_LIGHT_MODEL_AMBIENT...). The default value * is 0.125f. * * @param intensity a floating-point value controlling the overall * light model ambient intensity. */ public void setLightModelAmbientIntensity(float intensity) { params[LIGHT_MODEL_AMBIENT_INTENSITY] = intensity; } /** * Sets the ambient color for the red, green, and blue channels * that will be multiplied by the value of setAmbientIntensity and * passed to glLightfv(...GL_AMBIENT...). The default values are * {1, 1, 1}. * * @param ambient an arry of three floats containing ambient * red, green, and blue intensity values. */ public void setAmbientColor(float[] ambient) { params[AMBIENT_RED] = ambient[0]; params[AMBIENT_GREEN] = ambient[1]; params[AMBIENT_BLUE] = ambient[2]; } /** * Sets the overall diffuse light intensity. This intensity will * be used to modify the diffuse light value for each of the red, * green, and blue channels passed to glLightfv(...GL_DIFFUSE...). * The default value is 0.125f. * * @param intensity a floating-point value controlling the overall * ambient light intensity. */ public void setDiffuseIntensity(float intensity) { params[DIFFUSE_INTENSITY] = intensity; } /** * Sets the diffuse color for the red, green, and blue channels * that will be multiplied by the value of setDiffuseIntensity and * passed to glLightfv(...GL_DIFFUSE...). The default values are * {1, 1, 1}. * * @param diffuse an array of three floats containing diffuse * red, green, and blue intensity values. */ public void setDiffuseColor(float[] diffuse) { params[DIFFUSE_RED] = diffuse[0]; params[DIFFUSE_GREEN] = diffuse[1]; params[DIFFUSE_BLUE] = diffuse[2]; } /** * Sets the overall specular light intensity. This intensity will * be used to modify the diffuse light value for each of the red, * green, and blue channels passed to glLightfv(...GL_SPECULAR...). * The default value is 0.125f. * * @param intensity a floating-point value controlling the overall * ambient light intensity. */ public void setSpecularIntensity(float intensity) { params[SPECULAR_INTENSITY] = intensity; } /** * Sets the specular color for the red, green, and blue channels * that will be multiplied by the value of setSpecularIntensity and * passed to glLightfv(...GL_SPECULAR...). The default values are * {1, 1, 1}. * * @param specular an array of three floats containing specular * red, green, and blue intensity values. */ public void setSpecularColor(float[] specular) { params[SPECULAR_RED] = specular[0]; params[SPECULAR_GREEN] = specular[1]; params[SPECULAR_BLUE] = specular[2]; } /** * Returns the current X translation of the modelview * transformation as passed to glTranslatef. The default value is * 0.0f. * * @return the X modelview translation as a float. */ public float getTranslateX() { return params[TRANSLATE_X]; } /** * Returns the current Y translation of the modelview * transformation as passed to glTranslatef. The default value is * 0.0f. * * @return the Y modelview translation as a float. */ public float getTranslateY() { return params[TRANSLATE_Y]; } /** * Returns the current Z translation of the modelview * transformation as passed to glTranslatef. The default value is * -50.0f. * * @return the Z modelview translation as a float. */ public float getTranslateZ() { return params[TRANSLATE_Z]; } /** * Sets the position of the near frustum clipping plane as passed * to glFrustumf. The default value is 5.0f; * * @param nearFrustum the near frustum clipping plane distance as * a float. */ public void setNearFrustum(float nearFrustum) { params[NEAR_FRUSTUM] = nearFrustum; } /** * Sets the position of the far frustum clipping plane as passed * to glFrustumf. The default value is 100.0f; * * @param farFrustum the far frustum clipping plane distance as a * float. */ public void setFarFrustum(float farFrustum) { params[FAR_FRUSTUM] = farFrustum; } private void computeZoom() { mZoom = mZoomScale*(float)Math.pow(mZoomBase, -params[ZOOM_EXPONENT]); } /** * Resets all parameters to their default values. */ public void reset() { for (int i = 0; i < params.length; i++) { params[i] = defaults[i]; } computeZoom(); } private void removeExpiredMessages() { long now = System.currentTimeMillis(); List<String> toBeRemoved = new ArrayList<String>(); Iterator<String> keyIter = mMessages.keySet().iterator(); while (keyIter.hasNext()) { String key = keyIter.next(); Message msg = mMessages.get(key); if (msg.getExpirationTime() < now) { toBeRemoved.add(key); } } Iterator<String> tbrIter = toBeRemoved.iterator(); while (tbrIter.hasNext()) { String key = tbrIter.next(); mMessages.remove(key); } } /** * Displays the message overlay on the given Canvas. The * GLContext.waitGL method should be called prior to calling this * method. The interactive command display is drawn by this * method. * * @param canvas the Canvas on which messages are to appear. */ public void showMessages(Canvas canvas) { removeExpiredMessages(); float y = 10.0f; List<String> l = new ArrayList<String>(); l.addAll(mMessages.keySet()); Collections.sort(l); Iterator<String> iter = l.iterator(); while (iter.hasNext()) { String key = iter.next(); String text = mMessages.get(key).getText(); canvas.drawText(text, 10.0f, y, mPaint); y += MESSAGE_Y_SPACING; } } private int mTriangles; /** * Sets the number of triangles drawn in the previous frame for * display by the showStatistics method. The number of triangles * is not computed by GLView but must be supplied by the * calling Activity. * * @param triangles an Activity-supplied estimate of the number of * triangles drawn in the previous frame. */ public void setNumTriangles(int triangles) { this.mTriangles = triangles; } /** * Displays statistics on frames and triangles per second. The * GLContext.waitGL method should be called prior to calling this * method. * * @param canvas the Canvas on which statistics are to appear. * @param width the width of the Canvas. */ public void showStatistics(Canvas canvas, int width) { long endTime = mTimes[mTimesIdx] = System.currentTimeMillis(); mTimesIdx = (mTimesIdx + 1) % mFramesFPS; float th = mPaint.getTextSize(); if (mDisplayFPS) { // Use end time from mFramesFPS frames ago long startTime = mTimes[mTimesIdx]; String fps = "" + (1000.0f*mFramesFPS/(endTime - startTime)); // Normalize fps to XX.XX format if (fps.indexOf(".") == 1) { fps = " " + fps; } int len = fps.length(); if (len == 2) { fps += ".00"; } else if (len == 4) { fps += "0"; } else if (len > 5) { fps = fps.substring(0, 5); } canvas.drawText(fps + " fps", width - 60.0f, 10.0f, mPaint); } if (mDisplayCounts) { canvas.drawText(mTriangles + " triangles", width - 100.0f, 10.0f + th + 5, mPaint); } } private void addMessage(String key, String text, int durationMillis) { long expirationTime = System.currentTimeMillis() + durationMillis; mMessages.put(key, new Message(text, expirationTime)); } private void addMessage(String key, String text) { addMessage(key, text, DEFAULT_DURATION_MILLIS); } private void addMessage(String text) { addMessage(text, text, DEFAULT_DURATION_MILLIS); } private void clearMessages() { mMessages.clear(); } String command = ""; private void toggleFilter() { if (params[mParam] == GL10.GL_NEAREST) { params[mParam] = GL10.GL_LINEAR; } else { params[mParam] = GL10.GL_NEAREST; } addMessage(commands[mParam], "Texture " + (mParam == TEXTURE_MIN_FILTER ? "min" : "mag") + " filter = " + (params[mParam] == GL10.GL_NEAREST ? "nearest" : "linear")); } private void togglePerspectiveCorrection() { if (params[mParam] == GL10.GL_NICEST) { params[mParam] = GL10.GL_FASTEST; } else { params[mParam] = GL10.GL_NICEST; } addMessage(commands[mParam], "Texture perspective correction = " + (params[mParam] == GL10.GL_FASTEST ? "fastest" : "nicest")); } private String valueString() { if (mParam == TEXTURE_MIN_FILTER || mParam == TEXTURE_MAG_FILTER) { if (params[mParam] == GL10.GL_NEAREST) { return "nearest"; } if (params[mParam] == GL10.GL_LINEAR) { return "linear"; } } if (mParam == TEXTURE_PERSPECTIVE_CORRECTION) { if (params[mParam] == GL10.GL_FASTEST) { return "fastest"; } if (params[mParam] == GL10.GL_NICEST) { return "nicest"; } } return "" + params[mParam]; } /** * * @return true if the view */ public boolean hasMessages() { return mState == HAVE_TWO || mDisplayFPS || mDisplayCounts; } /** * Process a key stroke. The calling Activity should pass all * keys from its onKeyDown method to this method. If the key is * part of a GLView command, true is returned and the calling * Activity should ignore the key event. Otherwise, false is * returned and the calling Activity may process the key event * normally. * * @param keyCode the key code as passed to Activity.onKeyDown. * * @return true if the key is part of a GLView command sequence, * false otherwise. */ public boolean processKey(int keyCode) { // Pressing the state key twice enters the UI // Pressing it again exits the UI if ((keyCode == STATE_KEY) || (keyCode == KeyEvent.KEYCODE_SLASH) || (keyCode == KeyEvent.KEYCODE_PERIOD)) { mState = (mState + 1) % 3; if (mState == HAVE_NONE) { clearMessages(); } if (mState == HAVE_TWO) { clearMessages(); addMessage("aaaa", "GL", Integer.MAX_VALUE); addMessage("aaab", "", Integer.MAX_VALUE); command = ""; } return true; } else { if (mState == HAVE_ONE) { mState = HAVE_NONE; return false; } } // If we're not in the UI, exit without handling the key if (mState != HAVE_TWO) { return false; } if (keyCode == KeyEvent.KEYCODE_ENTER) { command = ""; } else if (keyCode == KeyEvent.KEYCODE_DEL) { if (command.length() > 0) { command = command.substring(0, command.length() - 1); } } else if (keyCode >= KeyEvent.KEYCODE_A && keyCode <= KeyEvent.KEYCODE_Z) { command += "" + (char)(keyCode - KeyEvent.KEYCODE_A + 'a'); } addMessage("aaaa", "GL " + command, Integer.MAX_VALUE); if (command.equals("h")) { addMessage("aaaa", "GL", Integer.MAX_VALUE); addMessage("h - help"); addMessage("fn/ff - frustum near/far clip Z"); addMessage("la/lar/lag/lab - abmient intensity/r/g/b"); addMessage("ld/ldr/ldg/ldb - diffuse intensity/r/g/b"); addMessage("ls/lsr/lsg/lsb - specular intensity/r/g/b"); addMessage("s - toggle statistics display"); addMessage("tmin/tmag - texture min/mag filter"); addMessage("tpersp - texture perspective correction"); addMessage("tx/ty/tz - view translate x/y/z"); addMessage("z - zoom"); command = ""; return true; } else if (command.equals("s")) { mDisplayCounts = !mDisplayCounts; mDisplayFPS = !mDisplayFPS; command = ""; return true; } mParam = -1; for (int i = 0; i < commands.length; i++) { if (command.equals(commands[i])) { mParam = i; mIncr = increments[i]; } } if (mParam == -1) { return true; } boolean addMessage = true; // Increment or decrement if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT || keyCode == KeyEvent.KEYCODE_DPAD_DOWN) { if (mParam == ZOOM_EXPONENT) { params[mParam] += mIncr; computeZoom(); } else if ((mParam == TEXTURE_MIN_FILTER) || (mParam == TEXTURE_MAG_FILTER)) { toggleFilter(); } else if (mParam == TEXTURE_PERSPECTIVE_CORRECTION) { togglePerspectiveCorrection(); } else { params[mParam] += mIncr; } } else if (keyCode == KeyEvent.KEYCODE_DPAD_UP || keyCode == KeyEvent.KEYCODE_DPAD_LEFT) { if (mParam == ZOOM_EXPONENT) { params[mParam] -= mIncr; computeZoom(); } else if ((mParam == TEXTURE_MIN_FILTER) || (mParam == TEXTURE_MAG_FILTER)) { toggleFilter(); } else if (mParam == TEXTURE_PERSPECTIVE_CORRECTION) { togglePerspectiveCorrection(); } else { params[mParam] -= mIncr; } } if (addMessage) { addMessage(commands[mParam], labels[mParam] + ": " + valueString()); } return true; } /** * Zoom in by a given number of steps. A negative value of steps * zooms out. Each step zooms in by 1%. * * @param steps the number of steps to zoom by. */ public void zoom(int steps) { params[ZOOM_EXPONENT] += steps; computeZoom(); } /** * Set the projection matrix using glFrustumf. The left and right * clipping planes are set at -+(aspectRatio*zoom), the bottom and * top clipping planes are set at -+zoom, and the near and far * clipping planes are set to the values set by setNearFrustum and * setFarFrustum or interactively. * * <p> GL side effects: * <ul> * <li>overwrites the matrix mode</li> * <li>overwrites the projection matrix</li> * </ul> * * @param gl a GL10 instance whose projection matrix is to be modified. */ public void setProjection(GL10 gl) { gl.glMatrixMode(GL10.GL_PROJECTION); gl.glLoadIdentity(); if (mAspectRatio >= 1.0f) { gl.glFrustumf(-mAspectRatio*mZoom, mAspectRatio*mZoom, -mZoom, mZoom, params[NEAR_FRUSTUM], params[FAR_FRUSTUM]); } else { gl.glFrustumf(-mZoom, mZoom, -mZoom / mAspectRatio, mZoom / mAspectRatio, params[NEAR_FRUSTUM], params[FAR_FRUSTUM]); } } /** * Set the modelview matrix using glLoadIdentity and glTranslatef. * The translation values are set interactively. * * <p> GL side effects: * <ul> * <li>overwrites the matrix mode</li> * <li>overwrites the modelview matrix</li> * </ul> * * @param gl a GL10 instance whose modelview matrix is to be modified. */ public void setView(GL10 gl) { gl.glMatrixMode(GL10.GL_MODELVIEW); gl.glLoadIdentity(); // Move the viewpoint backwards gl.glTranslatef(params[TRANSLATE_X], params[TRANSLATE_Y], params[TRANSLATE_Z]); } /** * Sets texture parameters. * * <p> GL side effects: * <ul> * <li>sets the GL_PERSPECTIVE_CORRECTION_HINT</li> * <li>sets the GL_TEXTURE_MIN_FILTER texture parameter</li> * <li>sets the GL_TEXTURE_MAX_FILTER texture parameter</li> * </ul> * * @param gl a GL10 instance whose texture parameters are to be modified. */ public void setTextureParameters(GL10 gl) { gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, (int)params[TEXTURE_PERSPECTIVE_CORRECTION]); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, params[TEXTURE_MIN_FILTER]); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, params[TEXTURE_MAG_FILTER]); } /** * Sets the lighting parameters for the given light. * * <p> GL side effects: * <ul> * <li>sets the GL_LIGHT_MODEL_AMBIENT intensities * <li>sets the GL_AMBIENT intensities for the given light</li> * <li>sets the GL_DIFFUSE intensities for the given light</li> * <li>sets the GL_SPECULAR intensities for the given light</li> * </ul> * * @param gl a GL10 instance whose texture parameters are to be modified. */ public void setLights(GL10 gl, int lightNum) { float[] light = new float[4]; light[3] = 1.0f; float lmi = params[LIGHT_MODEL_AMBIENT_INTENSITY]; light[0] = params[LIGHT_MODEL_AMBIENT_RED]*lmi; light[1] = params[LIGHT_MODEL_AMBIENT_GREEN]*lmi; light[2] = params[LIGHT_MODEL_AMBIENT_BLUE]*lmi; gl.glLightModelfv(GL10.GL_LIGHT_MODEL_AMBIENT, light, 0); float ai = params[AMBIENT_INTENSITY]; light[0] = params[AMBIENT_RED]*ai; light[1] = params[AMBIENT_GREEN]*ai; light[2] = params[AMBIENT_BLUE]*ai; gl.glLightfv(lightNum, GL10.GL_AMBIENT, light, 0); float di = params[DIFFUSE_INTENSITY]; light[0] = params[DIFFUSE_RED]*di; light[1] = params[DIFFUSE_GREEN]*di; light[2] = params[DIFFUSE_BLUE]*di; gl.glLightfv(lightNum, GL10.GL_DIFFUSE, light, 0); float si = params[SPECULAR_INTENSITY]; light[0] = params[SPECULAR_RED]*si; light[1] = params[SPECULAR_GREEN]*si; light[2] = params[SPECULAR_BLUE]*si; gl.glLightfv(lightNum, GL10.GL_SPECULAR, light, 0); } }
Java
/* * Copyright (C) 2007 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.globaltime; public class LatLongSphere extends Sphere { public LatLongSphere(float centerX, float centerY, float centerZ, float radius, int lats, int longs, float minLongitude, float maxLongitude, boolean emitTextureCoordinates, boolean emitNormals, boolean emitColors, boolean flatten) { super(emitTextureCoordinates, emitNormals, emitColors); int tris = 2 * (lats - 1) * (longs - 1); int[] vertices = new int[3 * lats * longs]; int[] texcoords = new int[2 * lats * longs]; int[] colors = new int[4 * lats * longs]; int[] normals = new int[3 * lats * longs]; short[] indices = new short[3 * tris]; int vidx = 0; int tidx = 0; int nidx = 0; int cidx = 0; int iidx = 0; minLongitude *= DEGREES_TO_RADIANS; maxLongitude *= DEGREES_TO_RADIANS; for (int i = 0; i < longs; i++) { float fi = (float) i / (longs - 1); // theta is the longitude float theta = (maxLongitude - minLongitude) * (1.0f - fi) + minLongitude; float sinTheta = (float) Math.sin(theta); float cosTheta = (float) Math.cos(theta); for (int j = 0; j < lats; j++) { float fj = (float) j / (lats - 1); // phi is the latitude float phi = PI * fj; float sinPhi = (float) Math.sin(phi); float cosPhi = (float) Math.cos(phi); float x = cosTheta * sinPhi; float y = cosPhi; float z = sinTheta * sinPhi; if (flatten) { // Place vertices onto a flat projection vertices[vidx++] = toFixed(2.0f * fi - 1.0f); vertices[vidx++] = toFixed(0.5f - fj); vertices[vidx++] = toFixed(0.0f); } else { // Place vertices onto the surface of a sphere // with the given center and radius vertices[vidx++] = toFixed(x * radius + centerX); vertices[vidx++] = toFixed(y * radius + centerY); vertices[vidx++] = toFixed(z * radius + centerZ); } if (emitTextureCoordinates) { texcoords[tidx++] = toFixed(1.0f - (theta / (TWO_PI))); texcoords[tidx++] = toFixed(fj); } if (emitNormals) { float norm = 1.0f / Shape.length(x, y, z); normals[nidx++] = toFixed(x * norm); normals[nidx++] = toFixed(y * norm); normals[nidx++] = toFixed(z * norm); } // 0 == black, 65536 == white if (emitColors) { colors[cidx++] = (i % 2) * 65536; colors[cidx++] = 0; colors[cidx++] = (j % 2) * 65536; colors[cidx++] = 65536; } } } for (int i = 0; i < longs - 1; i++) { for (int j = 0; j < lats - 1; j++) { int base = i * lats + j; // Ensure both triangles have the same final vertex // since this vertex carries the color for flat // shading indices[iidx++] = (short) (base); indices[iidx++] = (short) (base + 1); indices[iidx++] = (short) (base + lats + 1); indices[iidx++] = (short) (base + lats); indices[iidx++] = (short) (base); indices[iidx++] = (short) (base + lats + 1); } } allocateBuffers(vertices, texcoords, normals, colors, indices); } }
Java
/* * Copyright (C) 2007 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.globaltime; import java.nio.ByteBuffer; public class Texture { private ByteBuffer data; private int width, height; public Texture(ByteBuffer data, int width, int height) { this.data = data; this.width = width; this.height = height; } public ByteBuffer getData() { return data; } public int getWidth() { return width; } public int getHeight() { return height; } }
Java
package anonymouschat.utils; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.ObjectInputStream; import java.io.Serializable; import java.security.InvalidKeyException; import java.security.Key; import java.security.NoSuchAlgorithmException; import java.security.PublicKey; import java.util.ArrayList; import java.util.Random; import javax.crypto.Cipher; import javax.crypto.NoSuchPaddingException; import anonymouschat.client.Client; import anonymouschat.service.ServerIdentObject; import anonymouschat.service.serverEntry; public class ListOfServers { public static ArrayList<serverEntry> servers = new ArrayList<serverEntry>(); Random rand = new Random(); FileInputStream fin; public ListOfServers() { File dir = new File("publicServerIdentities"); String[] children = dir.list(); if (children == null) { System.err.println("No list of public servers to connect to"); System.exit(1); // Either dir does not exist or is not a directory } else { for (int i=0; i<children.length; i++) { // Get filename of file or directory String filename = children[i]; serverEntry ident = null; try { fin = new FileInputStream(filename); ObjectInputStream ois = new ObjectInputStream(fin); ident = (serverEntry) ois.readObject(); servers.add(ident); System.out.println("Added " + ident.serverName + " to list of known servers"); ois.close(); } catch (FileNotFoundException e) { e.printStackTrace(); System.err.println("Could not load public server identity file for " + filename); } catch (IOException e) { e.printStackTrace(); System.err.println("Unable to read serialized public server identity file for " + filename); } catch (ClassNotFoundException e) { e.printStackTrace(); System.err.println("Error occured when casting read in serialized public server identity object to serverEntry for " + filename); } } } //TODO: Pass in real public keys instead of NULL otherwise this will cause errors } public serverEntry getRandomServer() throws Exception { serverEntry se; if (servers.size() == 0) throw new Exception("The directory 'publicServerIdentities' which holds information about how to connect to servers is empty, public server identities are public[servername]Identity.dat files generated when a server is first run"); if (Client.serverChain.size() >= servers.size()) throw new Exception("Your number of server hops requested for anonymous routing is larger than the number of available servers, please reduce it to at most " + servers.size()); do { se = servers.get(rand.nextInt(servers.size())); } while (Client.serverChain.contains(se)); return se; } public serverEntry getByName(String name) { for(int i=0; i<servers.size(); i++) { if (servers.get(i).serverName.equalsIgnoreCase(name)) return servers.get(i); } return null; } }
Java
package anonymouschat.utils; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.PrintStream; import anonymouschat.Identity; import anonymouschat.NickList; /** * Interactions between client and local file. * * @author hb * */ public class LocalFileOps { /** * Read last identity from local file. * * @return * @throws IOException * @throws ClassNotFoundException */ public static Identity readLastIdentity() throws IOException, ClassNotFoundException { FileInputStream inputStream = new FileInputStream( ConstantVariables.ID_FILE_NAME ); ObjectInputStream ois = new ObjectInputStream( inputStream ); Identity id = (Identity) ois.readObject(); ois.close(); return id; } /** * write new identity to identity file * * @param newIdentity * @throws IOException * @throws FileNotFoundException */ public static void updateLastIdentity( Identity newIdentity ) throws FileNotFoundException, IOException { ObjectOutputStream ois = new ObjectOutputStream( new FileOutputStream( ConstantVariables.ID_FILE_NAME ) ); ois.writeObject( (Object) newIdentity ); ois.close(); } /** * remove all records associating with an obsolete identity. */ public static void removeAllRecords() { try { new File( ConstantVariables.NICK_LIST_FILE_NAME ).delete(); FileInputStream fin = null; fin = new FileInputStream( ConstantVariables.CHAT_USER_LIST ); InputStreamReader isr = new InputStreamReader( fin ); BufferedReader br = new BufferedReader( isr ); String strLine; try { while( (strLine = br.readLine()) != null ) { new File( ConstantVariables.CHAT_LOG_FILE_NAME_PREFIX + strLine ).delete(); } } catch( IOException e ) { e.printStackTrace(); } new File( ConstantVariables.CHAT_USER_LIST ).delete(); } catch( FileNotFoundException fnf ) { } } /** * Get chat history with target user. */ public static String getChatLog( String userID ) { FileInputStream fin = null; try { fin = new FileInputStream( ConstantVariables.CHAT_LOG_FILE_NAME_PREFIX + userID ); } catch( FileNotFoundException e1 ) { return null; } InputStreamReader isr = new InputStreamReader( fin ); BufferedReader br = new BufferedReader( isr ); StringBuffer sb = new StringBuffer(); try { sb.append( br.readLine() ); } catch( IOException e ) { e.printStackTrace(); } return sb.toString(); } /** * Append chat history to existing log file * * or * * Create new chat history * * @param userID * @param chatLog */ public static void appendChatLog( String userID, String chatLog ) { FileWriter fstream = null; try { fstream = new FileWriter( ConstantVariables.CHAT_LOG_FILE_NAME_PREFIX + userID, true ); } catch( IOException e ) { FileOutputStream fout = null; try { fout = new FileOutputStream( ConstantVariables.CHAT_LOG_FILE_NAME_PREFIX + userID ); } catch( FileNotFoundException e1 ) { e1.printStackTrace(); } new PrintStream( fout ).println( chatLog ); try { fout.close(); } catch( IOException e2 ) { e2.printStackTrace(); } } BufferedWriter out = new BufferedWriter( fstream ); try { out.write( chatLog ); } catch( IOException e ) { e.printStackTrace(); } try { out.close(); } catch( IOException e ) { e.printStackTrace(); } } /** * remove chat history * * @param userID */ public static void removeChatLog( String userID ) { new File( ConstantVariables.CHAT_LOG_FILE_NAME_PREFIX + userID ) .delete(); } /** * Get nick name list from file */ public static NickList getNickNameList() { FileInputStream inputStream; try { inputStream = new FileInputStream( ConstantVariables.NICK_LIST_FILE_NAME ); } catch( FileNotFoundException e ) { return null; } ObjectInputStream ois = null; try { ois = new ObjectInputStream( inputStream ); } catch( IOException e ) { e.printStackTrace(); } NickList tempList = null; try { tempList = (NickList) ois.readObject(); } catch( IOException e ) { e.printStackTrace(); } catch( ClassNotFoundException e ) { e.printStackTrace(); } try { ois.close(); } catch( IOException e ) { e.printStackTrace(); } return tempList; } public static void updateNicknameList( NickList nickList ) { ObjectOutputStream ois = null; try { ois = new ObjectOutputStream( new FileOutputStream( ConstantVariables.NICK_LIST_FILE_NAME ) ); } catch( FileNotFoundException e1 ) { e1.printStackTrace(); } catch( IOException e1 ) { e1.printStackTrace(); } try { ois.writeObject( (Object) nickList ); ois.close(); } catch( IOException e1 ) { e1.printStackTrace(); } } }
Java
package anonymouschat.utils; /** * Store a set of constant variables for anonymous chat. * * @author hb * */ public class ConstantVariables { public static String ASYMMETRIC_CYPHER_TYPE = "RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING"; public static final String ID_FILE_NAME = "ID_HIST"; public static final String CHAT_LOG_FILE_NAME_PREFIX = "LOG_"; public static final String CHAT_USER_LIST = "USER_HIST"; public static final String NICK_LIST_FILE_NAME = "NICK_NAMES_HIST"; public static final int numServerHops = 2; //Number of servers a client message hops through before it reaches destination server public static final String DEFAULT_CHATROOM_NAME = "B1GR3D Room"; //Name of the default chatroom all users first join public static final String SYMMETRIC_CIPHER_TYPE = "AES/CBC/PKCS5PADDING"; }
Java
package anonymouschat.utils; import java.io.ObjectOutputStream; import java.io.Serializable; import java.net.Socket; public class serverConnectionEntry implements Serializable { private static final long serialVersionUID = -3672628034657912265L; ObjectOutputStream socketConnection; Long serverConnectionNumber; String username; public void setSocketConnection(ObjectOutputStream out2) { socketConnection = out2; } public ObjectOutputStream getSocketConnection() { return socketConnection; } public void setServerConnectionNumber(Long connectionNumber) { serverConnectionNumber = connectionNumber; } public Long getServerConnectionNumber() { return serverConnectionNumber; } }
Java
package anonymouschat; import java.io.Serializable; import java.util.ArrayList; import java.util.List; public class NickList implements Serializable{ /** * */ private static final long serialVersionUID = 1L; private List<String> userIDList; private List<String> nickNameList; /** * Default Constructor Construct NickList by local file */ public NickList() { userIDList = new ArrayList<String>(); nickNameList = new ArrayList<String>(); } public int size() { if (userIDList.size() == nickNameList.size()) return userIDList.size(); else { return 0; } } public List<String> getNickNameList() { return nickNameList; } public List<String> getUserIDList() { return userIDList; } }
Java
package anonymouschat.service; import java.io.Serializable; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.PublicKey; import javax.crypto.Cipher; import javax.crypto.NoSuchPaddingException; import javax.crypto.SecretKey; import anonymouschat.utils.ConstantVariables; public class serverEntry implements Serializable { private static final long serialVersionUID = 4747248213859099964L; public serverEntry(String serverName, String serverIP, int serverPort, PublicKey publicKey) { System.out.println("Added server " + serverName + " at " + serverIP + ":" + serverPort + " to list of available servers"); this.serverName = serverName; this.serverIP = serverIP; this.serverPort = serverPort; this.publicKey = publicKey; } public String serverName; public int serverPort; public String serverIP; private PublicKey publicKey; private Cipher AsymmetricCipherEngine = null; private Cipher SymmetricCipherEngine = null; private SecretKey SymmetricKey = null; public void setPublicKey(PublicKey pub) { publicKey = pub; } public void setSymmetricKey(SecretKey sec) { SymmetricKey = sec; } public Cipher getAsymmetricCipherEngine() throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException { if (AsymmetricCipherEngine == null) { Cipher enc = Cipher.getInstance(ConstantVariables.ASYMMETRIC_CYPHER_TYPE); enc.init(Cipher.ENCRYPT_MODE, publicKey); AsymmetricCipherEngine = enc; } return AsymmetricCipherEngine; } public Cipher getSymmetricCipherEngine() throws Exception { if(!hasSymmetricKey()) { throw new Exception("No Symmetric Key"); } Cipher enc = Cipher.getInstance(ConstantVariables.SYMMETRIC_CIPHER_TYPE); enc.init(Cipher.ENCRYPT_MODE, SymmetricKey); SymmetricCipherEngine = enc; return SymmetricCipherEngine; } public boolean hasSymmetricKey() { if (SymmetricKey == null) return false; else return true; } }
Java
/** * */ package anonymouschat.service; import java.io.IOException; import java.io.ObjectInputStream; import java.net.ServerSocket; import java.net.Socket; import java.net.UnknownHostException; import java.security.SecureRandom; import java.util.ArrayList; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import anonymouschat.messages.ServerAnnounceMessage; import anonymouschat.messages.clientrequests.UserLoginRequest; import anonymouschat.messages.clientrequests.encryptedMessageWrapperMessage; /** * Runs the code for a server in the anonymous chat system Launch with main * method with the server's number as the argument (listens on port 7000 + srv#) * * @author Jonathan Mandeville * */ public class Server extends Thread { // XXX: these should all be changed to ConcurrentHashMap, HashTables are // out-dated // XXX: these should all be volatile; simply declaring them as static does // NOT ensure that all threads will see most recent values // public static Hashtable<String, ArrayList<String>> chatroomMemberList = // new Hashtable<String, ArrayList<String>>(); public static volatile ConcurrentMap<String, ArrayList<String>> chatroomMemberList = new ConcurrentHashMap<String, ArrayList<String>>(); // public static Hashtable<String, OutConnection> currentUserConnections = // new Hashtable<String, OutConnection>(); //public static volatile ConcurrentMap<String, OutConnection> currentUserConnections = new ConcurrentHashMap<String, OutConnection>(); // public static Hashtable<String, OutConnection> currentServerConnections = // new Hashtable<String, OutConnection>(); public static volatile ConcurrentMap<String, OutConnection> currentConnections = new ConcurrentHashMap<String, OutConnection>(); public static volatile ConcurrentMap<String, String> connectionMap; private static String serverName = ""; public static ServerIdentObject Identity; private static int port = -1; public static SecureRandom rand; /** * * @param name * the server name * @param portno * the port to use for accepting connections */ public Server( String name, int portno ) { serverName = name; port = portno; } /** * @param args */ public static void main( String[] args ) { // Initial implementation uses arguments for server names rand = new SecureRandom(); if( args.length > 1 ) { Server s = new Server( args[0], Integer.parseInt( args[1] ) ); s.start(); // ConstantVariables.serverListeningPort += Integer.parseInt( // args[0] ); } else { System.out .println( "You need to provide a name and port for this server" ); System.exit( 0 ); } } public static String getServerName() { return serverName; } private static ServerSocket serverSocket; /** * Run server thread (open new socket and listen for announce messages) */ public void run() { serverSocket = null; try { if (ServerIdentObject.identityExists(serverName)) Identity = ServerIdentObject.loadIdentity(serverName); else Identity = new ServerIdentObject(serverName); serverSocket = new ServerSocket( port ); System.out.println( serverName + ": Listening on port " + port ); } catch( UnknownHostException h ) { h.printStackTrace(); System.exit( 1 ); } catch( IOException e ) { e.printStackTrace(); System.exit( 1 ); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } while( true ) { try { listenForMessage(); } catch( Exception e ) { e.printStackTrace(); continue; } } } /** * Wait for an announce message, when received store the connection and * return * * @throws Exception */ public void listenForMessage() throws Exception { Socket clientSocket = null; try { clientSocket = serverSocket.accept(); clientSocket.setKeepAlive( true ); } catch( IOException e ) { System.err.println( "Accept failed." ); } ObjectInputStream in = null; Object message = null; try { in = new ObjectInputStream( clientSocket.getInputStream() ); } catch( IOException e ) { e.printStackTrace(); } //connectionMap.put(key, value) OutConnection newOutConnection = new OutConnection( clientSocket, "" ); //Server.currentConnections.put( connectionID, newOutConnection ); //System.out.println( "Note: New client/server connection" ); InConnectionThread newInConnection = new InConnectionThread(clientSocket, in, newOutConnection.getOutputStream()); newInConnection.start(); /* try { message = (Object) in.readObject(); } catch( IOException e ) { e.printStackTrace(); } catch( ClassNotFoundException e ) { e.printStackTrace(); } // check for type of message if( message instanceof UserLoginRequest ) { UserLoginRequest req = (UserLoginRequest) message; OutConnection newOutConnection = new OutConnection( clientSocket, req.getUserID() ); Server.currentUserConnections.put( req.getUserID(), newOutConnection ); System.out.println( "Note: New user connection" ); InConnectionThread newInConnection = new InConnectionThread( clientSocket, in, newOutConnection ); newInConnection.start(); } else if( message instanceof ServerAnnounceMessage ) { ServerAnnounceMessage req = (ServerAnnounceMessage) message; OutConnection newOutConnection = new OutConnection( clientSocket, req.getName() ); Server.currentServerConnections.put( req.getName(), newOutConnection ); System.out.println( "Note: New server connection" ); InConnectionThread newInConnection = new InConnectionThread( clientSocket, in, newOutConnection ); newInConnection.start(); } else { System.err .println( "Message object received is not of type AnnounceMessage from " + clientSocket.getInetAddress() + ":" + clientSocket.getPort() ); } */ } public static int getServerPort() { return port; } }
Java
package anonymouschat.service; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.net.InetAddress; import java.security.InvalidKeyException; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.PublicKey; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import anonymouschat.messages.clientrequests.encryptedMessageWrapperMessage; import anonymouschat.utils.ConstantVariables; public class ServerIdentObject implements Serializable { private static final long serialVersionUID = -2636702683734153948L; private PrivateKey privateKey; private PublicKey publicKey; private byte[] signatureOfPublicKeyByCA; //If a certificate authority signed this server's public key it says that this is a valid (not forged) key private String serverName; public ServerIdentObject(String svrName) throws NoSuchAlgorithmException { //Generate private and public key here System.out.println("Generating new identity file for server: " + svrName); KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA"); gen.initialize(3072); KeyPair keyPair = gen.generateKeyPair(); publicKey = keyPair.getPublic(); privateKey = keyPair.getPrivate(); serverName = svrName; saveIdentity(); //Save the identity to file so next time we can use it. } public static String getIdentityFileName(String svrName) { return svrName + "Identity.dat"; } public static boolean identityExists(String svrName) { File f = new File(getIdentityFileName(svrName)); return f.exists() && f.canRead(); } public static ServerIdentObject loadIdentity(String svrName) throws Exception { System.out.println("Loading existing identity for server: "+ svrName); ServerIdentObject ident = null; FileInputStream fin; try { fin = new FileInputStream(getIdentityFileName(svrName)); ObjectInputStream ois = new ObjectInputStream(fin); ident = (ServerIdentObject) ois.readObject(); ois.close(); } catch (FileNotFoundException e) { e.printStackTrace(); throw new Exception("Could not load identity file"); } catch (IOException e) { e.printStackTrace(); throw new Exception("Unable to read serialized server identity object from identity file"); } catch (ClassNotFoundException e) { e.printStackTrace(); throw new Exception("Error occured when casting read in serialized server identity object to ServerIdentObject"); } return ident; } public PublicKey getPublicKey() { return publicKey; } public byte[] getsignatureOfPublicKeyByCA() { return signatureOfPublicKeyByCA; } public Object unwrapEncryptionLayer(encryptedMessageWrapperMessage encryptedMessage) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException, IOException, ClassNotFoundException { //TODO: Perform unencryption on encryptedData using privateKey and return Cipher dec = Cipher.getInstance(ConstantVariables.ASYMMETRIC_CYPHER_TYPE); dec.init(Cipher.DECRYPT_MODE, privateKey); //byte[] unwrapped = dec.doFinal(encryptedMessage.getencryptedMessage()); byte[] unwrapped = encryptedMessage.getencryptedMessage(); ByteArrayInputStream bis = new ByteArrayInputStream (unwrapped); ObjectInputStream ois = new ObjectInputStream (bis); return ois.readObject(); } public void setPublicKeySignature(byte[] sig) { signatureOfPublicKeyByCA = sig; } public void saveIdentity() { try { FileOutputStream fout = new FileOutputStream(getIdentityFileName(serverName)); ObjectOutputStream oos = new ObjectOutputStream(fout); oos.writeObject(this); oos.close(); serverEntry publicID = new serverEntry(serverName, InetAddress.getLocalHost().getHostAddress(), Server.getServerPort(), getPublicKey()); fout = new FileOutputStream("public" + getIdentityFileName(serverName)); oos = new ObjectOutputStream(fout); oos.writeObject(publicID); oos.close(); } catch (Exception e) { e.printStackTrace(); } } }
Java
package anonymouschat.service; import java.io.IOException; import java.io.ObjectOutputStream; import java.net.Socket; import anonymouschat.messages.Message; import anonymouschat.messages.TextMessage; import anonymouschat.messages.serverresponses.ChatroomChangeResponse; import anonymouschat.messages.serverresponses.ChatroomMemberResponse; /** * Connection leaving a server (send messages FROM server with an instance of * this class) * */ public class OutConnection { private Socket clientSocket; private String name; private ObjectOutputStream out; /** * Create Instance with the socket connection clientSocketIn, and announcing * who is connected with messageIn * * @param clientSocketIn * - Socket connecting to CLIENT * @param messageIn * - ???? */ OutConnection( Socket clientSocketIn, String userNameIn ) { clientSocket = clientSocketIn; name = userNameIn; try { out = new ObjectOutputStream( clientSocket.getOutputStream() ); } catch( IOException e ) { e.printStackTrace(); } } public String getName() { return name; } public ObjectOutputStream getOutputStream() { return this.out; } /** * Send message using this OutConnection's Socket * * @param message * - message to send * @throws IOException */ public void sendMessage( Message message ) throws IOException { out.writeObject( message ); out.flush(); } }
Java
package anonymouschat.service; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.Socket; import java.net.UnknownHostException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.util.ArrayList; import java.util.List; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.crypto.SecretKey; import anonymouschat.Identity; import anonymouschat.messages.AESkeyMessage; import anonymouschat.messages.Message; import anonymouschat.messages.ServerAnnounceMessage; import anonymouschat.messages.TextMessage; import anonymouschat.messages.clientrequests.ChatroomChangeRequest; import anonymouschat.messages.clientrequests.UserLeaveRequest; import anonymouschat.messages.clientrequests.UserLoginRequest; import anonymouschat.messages.clientrequests.encryptedMessageWrapperMessage; import anonymouschat.messages.serverresponses.ChatroomChangeResponse; import anonymouschat.messages.serverresponses.ChatroomMemberResponse; import anonymouschat.utils.ConstantVariables; import anonymouschat.utils.ListOfServers; import anonymouschat.utils.serverConnectionEntry; /** * Connection coming into a server (send messages TO a server with an instance * of this class) * */ public class InConnectionThread extends Thread { private Socket clientSocket; private ObjectInputStream in = null; private ObjectOutputStream out = null; private String serverName; private SecretKey SymmetricKey; private Cipher decryptEngine; private SecureRandom rand = new SecureRandom(); private ArrayList<Long> usedConnectionNumbers = new ArrayList<Long>(); private ListOfServers availableServers = new ListOfServers(); private volatile ConcurrentMap<String, serverConnectionEntry> connections = new ConcurrentHashMap<String, serverConnectionEntry>(); /** * Server will read objects from the socket clientSocket, with the * ObjectInputStream inputStream * * @param clientSocketIn * @param inputStream */ InConnectionThread( Socket clientSocketIn, ObjectInputStream inputStream, ObjectOutputStream outStream ) { clientSocket = clientSocketIn; in = inputStream; out = outStream; this.serverName = Server.getServerName(); } @Override public void run() { // fix this Object message = null; Object unwrappedMessage = null; /* * try { in = new ObjectInputStream(clientSocket.getInputStream()); } * catch (IOException e) { e.printStackTrace(); } */ Long incommingConnectionNumber = null; while( clientSocket.isConnected() ) { try { message = (Object) in.readObject(); } catch( IOException e ) { // System.err.println("ERROR on SERVER when reading object from ObjectInputStream: IO Error, attempting to continue"); // e.printStackTrace(); continue; } catch( ClassNotFoundException e ) { System.err .println( "ERROR on SERVER when reading object from ObjectInputStream: Class not found" ); e.printStackTrace(); } if (message instanceof encryptedMessageWrapperMessage) { encryptedMessageWrapperMessage encMsg = (encryptedMessageWrapperMessage)message; incommingConnectionNumber = encMsg.getConnectionNumber(); //if (encMsg.isAsymmetricEncrypted()) // unwrappedMessage = Server.Identity.unwrapEncryptionLayer(encMsg); //else // unwrappedMessage = unwrapSymmetricEncryptionLayer(encMsg); ByteArrayInputStream bStream = new ByteArrayInputStream(encMsg.getencryptedMessage());; ObjectInputStream iStream; try { iStream = new ObjectInputStream(bStream); unwrappedMessage = iStream.readObject(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } System.out.println( "Received message: " + unwrappedMessage.toString() ); if( unwrappedMessage instanceof TextMessage ) { try { HandleTextMessage( (TextMessage) unwrappedMessage ); } catch( Exception e ) { e.printStackTrace(); } //} else if( unwrappedMessage instanceof ChatroomChangeRequest ) { //HandleChatroomChangeRequest( (ChatroomChangeRequest) unwrappedMessage ); } else if( unwrappedMessage instanceof UserLeaveRequest ) { HandleUserLeaveRequest( (UserLeaveRequest) unwrappedMessage ); } else if( unwrappedMessage instanceof encryptedMessageWrapperMessage) { HandleEncryptedMessage( (encryptedMessageWrapperMessage) unwrappedMessage, incommingConnectionNumber); } else if( unwrappedMessage instanceof UserLoginRequest ) { HandleUserLoginRequest( (UserLoginRequest) unwrappedMessage); } else if( unwrappedMessage instanceof ServerAnnounceMessage ) { HandleServerAnnounceMessage( (ServerAnnounceMessage) unwrappedMessage); } else if( unwrappedMessage instanceof AESkeyMessage ) { try { HandleAESkeyMessage( (AESkeyMessage) unwrappedMessage); } catch (NoSuchAlgorithmException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (NoSuchPaddingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } else { System.err.println( "ERROR: Unknown message received from ip:" + clientSocket.getInetAddress().toString() + ":" + clientSocket.getPort() ); } } } private Object unwrapSymmetricEncryptionLayer( encryptedMessageWrapperMessage encMsg) throws Exception { // TODO uncomment symmetric key for encryption //if (SymmetricKey == null) // throw new Exception("Symmetric key has not been recieved for this connection"); try { decryptEngine = Cipher.getInstance(ConstantVariables.SYMMETRIC_CIPHER_TYPE); decryptEngine.init(Cipher.DECRYPT_MODE, SymmetricKey, encMsg.getIV()); //TODO uncomment the following line to decrypt instead of the one below it //byte[] unwrapped = decryptEngine.doFinal(encMsg.getencryptedMessage()); byte[] unwrapped = encMsg.getencryptedMessage(); ByteArrayInputStream bStream = new ByteArrayInputStream(unwrapped); ObjectInputStream iStream = new ObjectInputStream(bStream); return iStream.readObject(); } catch (Exception e) { throw new Exception("Error encountered while decrypting encryptedMessage using Symmetric decryption" + e.getLocalizedMessage()); } } private void HandleAESkeyMessage(AESkeyMessage unwrappedMessage) throws NoSuchAlgorithmException, NoSuchPaddingException { // TODO Auto-generated method stub System.out.println("Server " + serverName + " recieved AES KEY"); SymmetricKey = unwrappedMessage.SharedAESKey; } private void HandleServerAnnounceMessage( ServerAnnounceMessage unwrappedMessage) { System.out.println("Server " + serverName + " recieved SERVER ANNOUNCE MESSAGE"); // TODO Auto-generated method stub } private void HandleUserLoginRequest(UserLoginRequest unwrappedMessage) { // TODO Auto-generated method stub System.out.println("Server " + serverName + " recieved USER LOGIN REQUEST MESSAGE"); //Server.currentConnections.put(unwrappedMessage.getUserID(), out); } /** * Handles messages that are encrypted and still need to be forwarded * @param unwrappedMessage The message that has already been decrypted at this server */ private void HandleEncryptedMessage( encryptedMessageWrapperMessage unwrappedMessage, Long incommingConnectionNumber) { // TODO Auto-generated method stub System.out.println("Server " + serverName + " recieved ENCRYPTED MESSAGE"); try { if (unwrappedMessage.getConnectionNumber() != null) { unwrappedMessage.setConnectionNumber(getUniqueNumber()); addConnectionInfo(unwrappedMessage.getConnectionNumber(), incommingConnectionNumber, out); } OutConnection o = getConnection(unwrappedMessage.getNextHop()); o.sendMessage(unwrappedMessage); } catch (Exception e) { System.err.println("Error occured while forwarding encrypted message to: " + unwrappedMessage.getNextHop()); e.printStackTrace(); } //TODO Send message to server specified in unwrappedMessage's next hop field } private void addConnectionInfo(Long connectionNumber, Long incommingConnectionNumber, ObjectOutputStream out2) { serverConnectionEntry s = new serverConnectionEntry(); s.setServerConnectionNumber(connectionNumber); s.setSocketConnection(out2); connections.put(""+incommingConnectionNumber, s); } private long getUniqueNumber() { Long result; do { result = rand.nextLong(); } while (usedConnectionNumbers.contains(result)); usedConnectionNumbers.add(result); return result; } /** * User leave. * * remove this user from chatroom member list. * * send ChatroomMemberResponse to everyone in the chatroom. * * @param message */ private void HandleUserLeaveRequest( UserLeaveRequest message ) { System.out.println("Server " + serverName + " recieved USER LEAVE REQUEST"); List<String> memberList = Server.chatroomMemberList.get( message .getChatroomName() ); if( memberList == null ) { System.out .println( "ERROR!! user asks to leave a non-existing chat room" ); } else { if( !memberList.remove( message.getUserID() ) ) { System.out .println( "ERROR!! user asks to leave a chatroom where they are not in" ); } } for( int i = 0; i < memberList.size(); i++ ) { try { ChatroomMemberResponse resp = new ChatroomMemberResponse( message.getChatroomName(), memberList ); Server.currentConnections.get( memberList.get( i ) ) .sendMessage( resp ); } catch( IOException e ) { System.err.println( "Unable to tell user '" + memberList.get( i ) + "' the updated user list" ); e.printStackTrace(); } } } private OutConnection getConnection(String destinationName) throws Exception { OutConnection con = null; if (!Server.currentConnections.containsKey(destinationName)) { try { serverEntry dest = availableServers.getByName(destinationName); // create new server to server connection Socket s2sSocket = new Socket(dest.serverIP, dest.serverPort ); ServerAnnounceMessage me = new ServerAnnounceMessage( serverName ); con = new OutConnection( s2sSocket, dest.serverName ); ObjectOutputStream out2 = con.getOutputStream(); //Write announce message to server try { encryptedMessageWrapperMessage enc = new encryptedMessageWrapperMessage(availableServers.getByName(destinationName).getAsymmetricCipherEngine(), me, true); out2.writeObject( enc ); out2.flush(); } catch( IOException e1 ) { throw new Exception("Erorr encountered while sending announce message to server: " + destinationName); } Server.currentConnections.put( dest.serverName, con ); InConnectionThread newInConnection = new InConnectionThread(s2sSocket, new ObjectInputStream(s2sSocket.getInputStream() ), out2 ); newInConnection.start(); } catch (Exception e) { throw new Exception("Unable to connect to server " + destinationName); } } if (Server.currentConnections.containsKey(destinationName)) return Server.currentConnections.get(destinationName); else throw new Exception("Unable to connect to server " + destinationName); } /** * * @param message */ private void HandleTextMessage( TextMessage message ) { // check if destination is local or another server System.out.println("Server " + serverName + " recieved TEXT MESSAGE"); // Check to see if talking to one person or a chatroom. String dest = null; if( message.destinationUser != null ) { dest = message.destinationUser; } else if( message.destinationChatroom != null ) { System.err.println( "Routing is not functioning for chatrooms at this time..." ); dest = message.destinationChatroom; } else { System.err.println( "Error in InConnectionThread: unable to handle text message because both destination user, and chatroom are null." ); } try { if (Server.currentConnections.containsKey(dest)) //Recipient also published here { //Connections contains links from username/unique server number to tcp connection //TODO more needs to be done here connections.get(dest).getSocketConnection().writeObject(message); } else { //TODO Put Jason's code here to determine server to send to //getConnection(server here).sendMessage(message); } } catch (Exception e) { System.err.println("Error handling text message: " + e.getLocalizedMessage()); e.printStackTrace(); } } public void serverSendMessage(Message msg, String destination) { try { encryptedMessageWrapperMessage enc = new encryptedMessageWrapperMessage(availableServers.getByName(destination).getAsymmetricCipherEngine(), msg, true); getConnection(destination).sendMessage(enc); } catch (Exception e) { // TODO Auto-generated catch block System.err.println("Error encountered when sending server->server message " + serverName + " -> " + destination); e.printStackTrace(); } } }
Java
package anonymouschat.client; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.Socket; import anonymouschat.client.frames.ChatFrame; import anonymouschat.messages.TextMessage; import anonymouschat.messages.serverresponses.ChatroomChangeResponse; import anonymouschat.messages.serverresponses.ChatroomMemberResponse; /** * This thread receives incoming * * 1. text messages * * 2. chat member response * * * @author bh349 * */ public class ClientInConnectionThread extends Thread { private ChatFrame chatFrame; private Socket incomingSocket; ObjectInputStream in = null; ObjectOutputStream out = null; //needed to write the initial AnnoinceMessage to server public ClientInConnectionThread(ChatFrame chatFrame, Socket clientSocket) { this.chatFrame = chatFrame; this.incomingSocket = clientSocket; } /** * Wait for out to be created and then return it. This method exists * because we can't use a socket's output stream to create a * object output stream more than once * TODO May need to have a time out and exception throw * @return */ public ObjectOutputStream getOutputStream(){ while(this.out == null){ try { Thread.sleep( 20); } catch( InterruptedException e ) { e.printStackTrace(); } } return out; } public void run() { // create output stream try { out = new ObjectOutputStream(incomingSocket.getOutputStream()); } catch( IOException e1 ) { e1.printStackTrace(); } Object receivedMessage = null; boolean openSocket = true; try { in = new ObjectInputStream(incomingSocket.getInputStream()); } catch( IOException e1 ) { e1.printStackTrace(); } while (openSocket == true){ try { try { receivedMessage = in.readObject(); if (receivedMessage instanceof TextMessage) { chatFrame.showTextMessage((TextMessage) receivedMessage); } else if (receivedMessage instanceof ChatroomMemberResponse) { chatFrame.updateChatMemberPanel((ChatroomMemberResponse)receivedMessage); }else if(receivedMessage instanceof ChatroomChangeResponse){ ChatroomChangeResponse resp = (ChatroomChangeResponse)receivedMessage; if(resp.isSuccess()){ chatFrame.switchChatroomOk(resp.getDstChatroomName()); }else{ chatFrame.showError( "Chat room is full. Cannot join." ); } } } catch (ClassNotFoundException e) { e.printStackTrace(); } } catch (IOException ioe) { ioe.printStackTrace(); openSocket = false; //Socket Closed, die gracefully } }//END-WHILE try { if (in != null) in.close(); if (incomingSocket != null) incomingSocket.close(); } catch( IOException e ) { e.printStackTrace(); } } }
Java
package anonymouschat.client.frames; import java.awt.Dimension; import java.awt.FlowLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.ArrayList; import java.util.List; import javax.swing.JButton; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSeparator; import javax.swing.SwingConstants; /** * Chat room member Panel shows current members in the chat room. * * Right click a name, show chat log with this user. * * Left click a name, put the name into chat room's dst text box. * * Upon created, it sends a ChatMemberRequest message to server, wait for a * ChatMember message. * * Refresh by sending and receiving the above messages in some condition. * * @author hb * */ public class ChatMemberPanel extends JPanel implements ActionListener { /** * Default serial */ private static final long serialVersionUID = 1L; private ChatFrame chatFrame; private List<String> memberList; private JPanel sendMsgPanel; private JPanel buttonPanel; private JPanel mainPanel; private JButton[] sendMsgButton; private List<JButton> sendMsgButtonList; private List<JButton> showHistoryButtonList; public ChatMemberPanel( ChatFrame chatFrame, String chatName ) { super(); this.chatFrame = chatFrame; this.setLayout( new GridLayout( 0, 1, 0, 0 ) ); this.add( new JLabel( "Members in '" + chatName + "'" ) ); mainPanel = new JPanel(); mainPanel.setLayout( new FlowLayout( 0, 0, 0 ) ); buttonPanel = new JPanel(); buttonPanel.setLayout( new GridLayout( 1, 2, 0, 0 ) ); // sendMsg Panel sendMsgPanel = new JPanel(); sendMsgPanel.setLayout( new GridLayout( 0, 1, 0, 0 ) ); sendMsgPanel.add( new JSeparator( SwingConstants.HORIZONTAL ) ); buttonPanel.setPreferredSize( new Dimension( 250, 2 * 50 ) ); buttonPanel.add( sendMsgPanel ); mainPanel.add( buttonPanel ); this.add( mainPanel ); } public void setMemberList( List<String> memberList ) { sendMsgPanel.removeAll(); sendMsgPanel.validate(); sendMsgButton = new JButton[memberList.size()]; sendMsgButtonList = new ArrayList<JButton>(); for( int i = 0; i < memberList.size(); i++ ) { chatFrame.showMessage( "User: " + memberList.get( i ) ); sendMsgButton[i] = new JButton( memberList.get( i ) ); sendMsgButton[i].addActionListener( this ); sendMsgButtonList.add( sendMsgButton[i] ); sendMsgPanel.add( sendMsgButton[i] ); } sendMsgPanel.validate(); } @Override public void actionPerformed( ActionEvent e ) { for( int i = 0; i < memberList.size(); i++ ) { if( e.getSource().equals( sendMsgButtonList.get( i ) ) ) { chatFrame.addChatDst( memberList.get( i ) ); return; } } for( int i = 0; i < memberList.size(); i++ ) { if( e.getSource().equals( showHistoryButtonList.get( i ) ) ) { new LogFrame( memberList.get( i ) ); return; } } } }
Java
package anonymouschat.client.frames; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.FileNotFoundException; import java.io.IOException; import javax.swing.JButton; import javax.swing.JFrame; import anonymouschat.Identity; import anonymouschat.client.Client; import anonymouschat.utils.ConstantVariables; import anonymouschat.utils.LocalFileOps; /** * ID selection GUI. By selecting persist or new identity, default chat room and * nick name list are displayed. * * @author hb * */ public class IDFrame extends JFrame implements ActionListener { /** * */ private static final long serialVersionUID = 1L; Client client; Identity lastIdentity; final int WIDTH = 500; final int HEIGHT = 500; JButton[] buttons; /** * Create a two button UI where user can either persist as their last id or * Generate a new one */ public IDFrame( final Client client ) { this.client = client; setTitle( "Welcome to Anonymous Chat System" ); setDefaultCloseOperation( JFrame.EXIT_ON_CLOSE ); setSize( WIDTH, HEIGHT ); setVisible( true ); buttons = new JButton[2]; for( int i = 0; i < 2; i++ ) { buttons[i] = new JButton(); } try { lastIdentity = LocalFileOps.readLastIdentity(); } catch( IOException e ) { e.printStackTrace(); } catch( ClassNotFoundException e ) { e.printStackTrace(); } if( lastIdentity == null ) { buttons[0].setEnabled( false ); } buttons[0].setText( "Persist on last Identity: " + lastIdentity ); buttons[0].addActionListener( this ); buttons[1].setText( "Use new Identity" ); buttons[1].addActionListener( this ); setLayout( new GridLayout( 2, 1 ) ); for( int i = 0; i < 2; i++ ) { add( buttons[i] ); } validate(); } @Override public void actionPerformed( ActionEvent e ) { String s = e.getActionCommand(); if( buttons[0].getText().equals( s ) ) { client.setUserID( lastIdentity ); } else { Identity newIdentity = new Identity( "newID" + (int) (Math.random() * 100) ); client.setUserID( newIdentity ); try { LocalFileOps.updateLastIdentity( newIdentity ); } catch( FileNotFoundException e1 ) { e1.printStackTrace(); } catch( IOException e1 ) { e1.printStackTrace(); } LocalFileOps.removeAllRecords(); } client.setNickListFrame( new NickListFrame( client ) ); client.setChatFrame( new ChatFrame( client, ConstantVariables.DEFAULT_CHATROOM_NAME ) ); dispose(); } }
Java
package anonymouschat.client.frames; import java.awt.BorderLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.IOException; import java.io.ObjectOutputStream; import java.net.Socket; import java.net.UnknownHostException; import java.security.InvalidKeyException; import java.security.Key; import java.security.NoSuchAlgorithmException; import java.util.ArrayList; import java.util.HashMap; import java.util.Map; import java.util.Random; import javax.crypto.Cipher; import javax.crypto.KeyGenerator; import javax.crypto.NoSuchPaddingException; import javax.crypto.SecretKey; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextArea; import javax.swing.JTextField; import anonymouschat.client.Client; import anonymouschat.client.ClientInConnectionThread; import anonymouschat.messages.AESkeyMessage; import anonymouschat.messages.Message; import anonymouschat.messages.TextMessage; import anonymouschat.messages.clientrequests.ChatroomChangeRequest; import anonymouschat.messages.clientrequests.UserLeaveRequest; import anonymouschat.messages.clientrequests.UserLoginRequest; import anonymouschat.messages.clientrequests.encryptedMessageWrapperMessage; import anonymouschat.messages.serverresponses.ChatroomMemberResponse; import anonymouschat.service.serverEntry; import anonymouschat.utils.ConstantVariables; import anonymouschat.utils.LocalFileOps; /** * A chat room panel. * * TODO: * * Dump chat log regularly to local file. * * When user clicks on change chat room option item, get a list of existing chat * rooms, by sending a ChatRoomListRequest and wait for ChatRoomListResponse. * * When user clicks on goto chat room button, create a new chat frame and close * the previous one. Dump chat log. * * @author hb * */ public class ChatFrame extends JFrame implements ActionListener { /** * */ private static final long serialVersionUID = 1L; Client client; static ObjectOutputStream out; Socket clientSocket; private static final int WIDTH = 800; private static final int HEIGHT = 500; String chatName; /* * put temporary chat log into this. dumpChatLog empty this, and outputs * into file. */ private HashMap<String, ArrayList<String>> tempChatLog; // chatInfoPanel private JPanel chatInfoPanel; private JPanel changeChatPanel; private JButton changeChatButton; private JTextField changeChatField; // msgPanel private JPanel msgPanel; private JLabel chatLabel; private JPanel namePanel; private JTextField dstField; private JScrollPane msgScr; private JTextArea msgArea; private JButton msgButton; private ChatMemberPanel chatMemberPanel; private JScrollPane textScr; private static JTextArea textArea; /** * Constructor by client instance and chat room name * * @param client * @param chatName */ public ChatFrame( Client client, String chatName ) { this.client = client; this.chatName = chatName; this.tempChatLog = new HashMap<String, ArrayList<String>>(); // main frame setTitle( "User : " + client.getIdentity() ); setSize( WIDTH, HEIGHT ); setVisible( true ); setLayout( new BorderLayout() ); // chatInfoPanel changeChatPanel = new JPanel(); changeChatPanel.add( new JLabel( "Go to Chatroom : " ) ); changeChatField = new JTextField( 10 ); changeChatPanel.add( changeChatField ); changeChatButton = new JButton( "Go" ); changeChatPanel.add( changeChatButton ); chatInfoPanel = new JPanel(); chatInfoPanel.setLayout( new GridLayout( 1, 2 ) ); chatLabel = new JLabel( "You are chatting in chatroom : '" + chatName + "'" ); chatLabel.setHorizontalAlignment( JLabel.CENTER ); chatInfoPanel.add( chatLabel ); chatInfoPanel.add( changeChatPanel ); add( chatInfoPanel, BorderLayout.NORTH ); chatMemberPanel = new ChatMemberPanel( this, chatName); getContentPane().add( chatMemberPanel, BorderLayout.EAST ); // msgPanel namePanel = new JPanel(); namePanel.setLayout( new GridLayout( 2, 1 ) ); namePanel.add( new JLabel( "You -> " ) ); dstField = new JTextField( 10 ); namePanel.add( dstField ); msgArea = new JTextArea(); msgScr = new JScrollPane( msgArea ); msgButton = new JButton( "SEND" ); msgButton.addActionListener( this ); msgPanel = new JPanel(); msgPanel.setLayout( new BorderLayout() ); msgPanel.add( namePanel, BorderLayout.WEST ); msgPanel.add( msgButton, BorderLayout.EAST ); msgPanel.add( msgScr, BorderLayout.CENTER ); add( msgPanel, BorderLayout.SOUTH ); // textArea textArea = new JTextArea(); textArea.setEditable( false ); textScr = new JScrollPane( textArea ); add( textScr ); addWindowListener( new WindowAdapter() { public void windowClosing( WindowEvent e ) { dumpChatLog(); leaveSystem(); } } ); try { establishAnonymousRouting(); } catch (Exception e) { System.err.println("ERROR encountered while trying to establish annonymous routing: " + e.getLocalizedMessage()); e.printStackTrace(); } sendUserLoginRequest(); // need to be placed in the right place, and check that there are not multiple private chatting window for same user // also need to deal with the log. The current solution is that do nothing when private chat ends. only save file when exiting chat room. //new OneOnOneChatFrame("Owner","TargetUser", tempChatLog, out); } private void establishAnonymousRouting() throws Exception { serverEntry randomServer; for(int i=0; i<ConstantVariables.numServerHops; i++) { randomServer = Client.ListOfAvailableServers.getRandomServer(); if (Client.serverChain.size() == 0) //we need to make the initial server connection, after that we can simply pass messages of to this server { clientSocket = new Socket( randomServer.serverIP, randomServer.serverPort ); showMessage( "Connected to port " + randomServer.serverPort ); showError( "Could not connect to server on port " + randomServer.serverPort ); ClientInConnectionThread t = new ClientInConnectionThread( this,clientSocket ); t.start(); out = t.getOutputStream(); } client.serverChain.add(randomServer); AESkeyMessage k = new AESkeyMessage(); k.SharedAESKey = generateAESkey(); sendMessage(k); randomServer.setSymmetricKey(k.SharedAESKey); } } public static SecretKey generateAESkey() throws NoSuchAlgorithmException { KeyGenerator kgen = KeyGenerator.getInstance("AES"); kgen.init(128); return kgen.generateKey(); } public static void sendMessage(Message msg) throws IOException { try{ encryptedMessageWrapperMessage wrapper; Cipher engine; for(int i =0; i<Client.serverChain.size(); i++) { System.out.print("Encrypting message to send ("); } for(int i = 0; i<Client.serverChain.size(); i++) { if(i > 0) ((encryptedMessageWrapperMessage)msg).setNextHop(Client.serverChain.get(i).serverName); System.out.print(Client.serverChain.get(i).serverName + ")"); if (Client.serverChain.get(i).hasSymmetricKey()) wrapper = new encryptedMessageWrapperMessage(Client.serverChain.get(i).getSymmetricCipherEngine(), msg, false); else wrapper = new encryptedMessageWrapperMessage(Client.serverChain.get(i).getAsymmetricCipherEngine(), msg, true); wrapper.setConnectionNumber(1); //TODO this next line was set by nick, the evil monkey WHat do we do with it? //wrapper.setUserLogin(login); msg = wrapper; } out.writeObject(msg); out.flush(); } catch( Exception e) { System.err.println("Error encoutered while attempting to send message client->server " + e.getLocalizedMessage()); e.printStackTrace(); } } /** * User first login request */ private void sendUserLoginRequest() { UserLoginRequest req = new UserLoginRequest( client.getIdentity().getUserID() ); try { sendMessage( req ); } catch( IOException e ) { showError( "Unable to send UserLoginRequest to server" ); e.printStackTrace(); } } /** * User leaves system. */ protected void leaveSystem() { UserLeaveRequest msg = new UserLeaveRequest( client.getIdentity().getUserID(), this.chatName ); try { out.writeObject( msg ); } catch( IOException e1 ) { System.err .println( "Error occured when sending UserLeaveRequest object to server" ); e1.printStackTrace(); } } /** * Save tempChatLog to file. */ private void dumpChatLog() { for( Map.Entry<String, ArrayList<String>> entry : tempChatLog .entrySet() ) { String userID = entry.getKey(); ArrayList<String> msgList = entry.getValue(); for( String s : msgList ) { LocalFileOps.appendChatLog( userID, s ); } } tempChatLog.clear(); } @Override public void actionPerformed( ActionEvent e ) { String s = e.getActionCommand(); if( "SEND".equals( s ) ) { sendTextMsg( dstField.getText(), msgArea.getText() ); msgArea.setText( "" ); } else if( "GO".equals( s ) ) { dumpChatLog(); sendSwitchChatroomRequest( changeChatField.getText() ); } } /** * action performed when a change chat room button is clicked. * * @param text */ private void sendSwitchChatroomRequest( String dstChatName ) { ChatroomChangeRequest msg = new ChatroomChangeRequest( client.getIdentity().getUserID(), this.chatName, dstChatName ); try { sendMessage( msg ); } catch( IOException e1 ) { System.err .println( "Error occured when sending ChatroomChangeRequest object to server" ); e1.printStackTrace(); } } /** * action performed when a send msg button is clicked. * * * @param dst * if dst is empty, send chat room message * @param data */ private void sendTextMsg( String dst, String data ) { TextMessage text = new TextMessage(); text.srcUser = client.getIdentity().getUserID(); if( dst.equals( "" ) ) { text.destinationChatroom = this.chatName; textArea.append( "You say to ALL: \n" ); } else { text.destinationUser = dst; String tempData = "You ->" + dst + ": " + data + "\n"; textArea.append( tempData ); if( tempChatLog.containsKey( dst ) ) { tempChatLog.get( dst ).add( tempData ); } else { tempChatLog.put( dst, new ArrayList<String>() ); tempChatLog.get( dst ).add( tempData ); } } text.encryptedData = data; try { sendMessage( text ); } catch( IOException e1 ) { showError( "Error occured when sending TextMessage object to server" ); e1.printStackTrace(); } } /** * show chat messages that clientInConnectionThread receives. save the * message in temporary chat record. * * @param msg */ public void showTextMessage( TextMessage msg ) { String userID = msg.srcUser; String tempData = msg.srcUser + " -> you: \n" + msg.encryptedData + "\n"; textArea.append( tempData ); if( tempChatLog.containsKey( userID ) ) { tempChatLog.get( userID ).add( tempData ); } else { tempChatLog.put( userID, new ArrayList<String>() ); tempChatLog.get( userID ).add( tempData ); } } /** * update chat room member list. * * @param receivedMessage */ public void updateChatMemberPanel( ChatroomMemberResponse receivedMessage ) { showMessage( "Updated list of users for chatroom " + receivedMessage.getChatroomName() ); chatMemberPanel.setMemberList( receivedMessage.getMembers() ); } /** * Display an error to the user via the text area */ public void showError( String error ) { textArea.append( "*****ERROR: " + error + " ******\n" ); } /** * Display a message to the user via the text area */ public void showMessage( String msg ) { textArea.append( msg ); } /** * add message receiver in dst field. * * @param dst */ public void addChatDst( String dst ) { dstField.setText( dst ); } /** * successfully changed chatroom * * @param dstChatroomName */ public void switchChatroomOk( String dstChatroomName ) { chatName = dstChatroomName; chatLabel.setText( "You are chatting in chatroom : '" + chatName + "'" ); dstField.setText( "" ); textArea.setText( "" ); } }
Java
package anonymouschat.client.frames; import java.awt.BorderLayout; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import java.util.ArrayList; import java.util.List; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JSeparator; import javax.swing.JTextField; import javax.swing.SwingConstants; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import anonymouschat.NickList; import anonymouschat.client.Client; import anonymouschat.utils.LocalFileOps; /** * Frame which contains a list of users and their nicknames Allows for adding * and deleting of users and nicknames * * @author Winters * */ public class NickListFrame extends JFrame implements ActionListener, DocumentListener, WindowListener { /** * */ private static final long serialVersionUID = 1L; private Client client; private JPanel textPanel; private JPanel buttonPanel; private JPanel userIDPanel; private JPanel nickNamePanel; private JPanel sendMsgPanel; private JPanel showHistoryPanel; private JPanel deletePanel; private NickList nickList; private JLabel userIDLabel = new JLabel( "UserID:" ); private JLabel nickNameLabel = new JLabel( "Nick Name:" ); private JButton[] sendMsgButton; private JButton[] showHistoryButton; private JButton[] deleteButton; private JButton addButton; private JTextField[] nickText; private JTextField[] idText; private List<JTextField> userIDList; private List<JTextField> nickNameList; private List<JButton> sendMsgButtonList; private List<JButton> showHistoryButtonList; private List<JButton> deleteButtonList; /** * Create NickListFrame UI * * @param userID * - the userid running the client app * @param nickList * - if null, creates a new list */ public NickListFrame( Client client ) { this.client = client; nickList = LocalFileOps.getNickNameList(); if(nickList == null){ nickList = new NickList(); } setTitle( "Nickname List for : " + client.getIdentity() ); setDefaultCloseOperation( JFrame.DISPOSE_ON_CLOSE ); addWindowListener( this ); setLocation( 0, 0 ); setVisible( true ); setResizable( false ); setLayout( new BorderLayout() ); textPanel = new JPanel(); textPanel.setLayout( new GridLayout( 1, 2 ) ); buttonPanel = new JPanel(); buttonPanel.setLayout( new GridLayout( 1, 3 ) ); // userID Panel userIDPanel = new JPanel(); userIDPanel.setLayout( new GridLayout( 0, 1, 0, 0 ) ); userIDPanel.add( userIDLabel ); userIDPanel.add( new JSeparator( SwingConstants.HORIZONTAL ) ); List<String> tempList = nickList.getUserIDList(); idText = new JTextField[tempList.size()]; userIDList = new ArrayList<JTextField>(); for( int i = 0; i < tempList.size(); i++ ) { idText[i] = new JTextField(); idText[i].setText( tempList.get( i ).toString() ); idText[i].addActionListener( this ); idText[i].getDocument().addDocumentListener( this ); userIDList.add( idText[i] ); userIDPanel.add( idText[i] ); } // nickName Panel nickNamePanel = new JPanel(); nickNamePanel.setLayout( new GridLayout( 0, 1, 0, 0 ) ); nickNamePanel.add( nickNameLabel ); nickNamePanel.add( new JSeparator( SwingConstants.HORIZONTAL ) ); tempList = nickList.getNickNameList(); nickText = new JTextField[tempList.size()]; nickNameList = new ArrayList<JTextField>(); for( int i = 0; i < tempList.size(); i++ ) { nickText[i] = new JTextField(); nickText[i].setText( tempList.get( i ).toString() ); nickText[i].addActionListener( this ); nickText[i].getDocument().addDocumentListener( this ); nickNameList.add( nickText[i] ); nickNamePanel.add( nickText[i] ); } // sendMsg Panel sendMsgPanel = new JPanel(); sendMsgPanel.setLayout( new GridLayout( 0, 1, 0, 0 ) ); sendMsgPanel.add( new JLabel( "" ) ); sendMsgPanel.add( new JSeparator( SwingConstants.HORIZONTAL ) ); sendMsgButton = new JButton[tempList.size()]; sendMsgButtonList = new ArrayList<JButton>(); for( int i = 0; i < tempList.size(); i++ ) { sendMsgButton[i] = new JButton( "Message" ); sendMsgButton[i].addActionListener( this ); sendMsgButtonList.add( sendMsgButton[i] ); sendMsgPanel.add( sendMsgButton[i] ); } // showHistory Panel showHistoryPanel = new JPanel(); showHistoryPanel.setLayout( new GridLayout( 0, 1, 0, 0 ) ); showHistoryPanel.add( new JLabel( "" ) ); showHistoryPanel.add( new JSeparator( SwingConstants.HORIZONTAL ) ); showHistoryButton = new JButton[tempList.size()]; showHistoryButtonList = new ArrayList<JButton>(); for( int i = 0; i < tempList.size(); i++ ) { showHistoryButton[i] = new JButton( "History" ); showHistoryButton[i].addActionListener( this ); showHistoryButtonList.add( showHistoryButton[i] ); showHistoryPanel.add( showHistoryButton[i] ); } // deleting Panel deletePanel = new JPanel(); deletePanel.setLayout( new GridLayout( 0, 1, 0, 0 ) ); deletePanel.add( new JLabel( "" ) ); deletePanel.add( new JSeparator( SwingConstants.HORIZONTAL ) ); deleteButton = new JButton[tempList.size()]; deleteButtonList = new ArrayList<JButton>(); for( int i = 0; i < tempList.size(); i++ ) { deleteButton[i] = new JButton( "Delete" ); deleteButton[i].addActionListener( this ); deleteButtonList.add( deleteButton[i] ); deletePanel.add( deleteButton[i] ); } // add button addButton = new JButton( "Add" ); addButton.addActionListener( this ); textPanel.add( userIDPanel ); textPanel.add( nickNamePanel ); buttonPanel.add( sendMsgPanel ); buttonPanel.add( showHistoryPanel ); buttonPanel.add( deletePanel ); getContentPane().add( textPanel, BorderLayout.WEST ); getContentPane().add( buttonPanel, BorderLayout.EAST ); getContentPane().add( addButton, BorderLayout.SOUTH ); pack(); validate(); } @Override public void actionPerformed( ActionEvent e ) { int i = -1; if( e.getSource() == addButton ) { nickList.getUserIDList().add( "" ); nickList.getNickNameList().add( "" ); JTextField tempTextField = new JTextField(); tempTextField.getDocument().addDocumentListener( this ); userIDList.add( tempTextField ); userIDPanel.add( tempTextField ); tempTextField = new JTextField(); tempTextField.getDocument().addDocumentListener( this ); nickNameList.add( tempTextField ); nickNamePanel.add( tempTextField ); JButton tempButton = new JButton( "Delete" ); tempButton.addActionListener( this ); deleteButtonList.add( tempButton ); deletePanel.add( tempButton ); tempButton = new JButton( "Message" ); tempButton.addActionListener( this ); sendMsgButtonList.add( tempButton ); sendMsgPanel.add( tempButton ); tempButton = new JButton( "History" ); tempButton.addActionListener( this ); showHistoryButtonList.add( tempButton ); showHistoryPanel.add( tempButton ); pack(); validate(); } else { i = deleteButtonList.indexOf( e.getSource() ); if( i != -1 ) { nickList.getNickNameList().remove( i ); nickList.getUserIDList().remove( i ); userIDPanel.remove( userIDList.get( i ) ); nickNamePanel.remove( nickNameList.get( i ) ); sendMsgPanel.remove( sendMsgButtonList.get( i ) ); showHistoryPanel.remove( showHistoryButtonList.get( i ) ); deletePanel.remove( deleteButtonList.get( i ) ); userIDList.remove( i ); nickNameList.remove( i ); sendMsgButtonList.remove( i ); showHistoryButtonList.remove( i ); deleteButtonList.remove( i ); if( nickNameList.size() != 0 ) pack(); validate(); return; } i = sendMsgButtonList.indexOf( e.getSource() ); if( i != -1 ) { client.getChatFrame().addChatDst( userIDList.get( userIDList.indexOf( e.getSource() ) ) .getText() ); return; } // } // handle show history // for( int i = 0; i < nickList.getNickNameList().size(); i++ ) { i = showHistoryButtonList.indexOf( e.getSource() ); if( i != -1 ) { new LogFrame( userIDList.get( userIDList.indexOf( e.getSource() ) ).getText() ); return; } } // } } @Override public void changedUpdate( DocumentEvent e ) { textChangeDetectioner( e ); } @Override public void insertUpdate( DocumentEvent e ) { textChangeDetectioner( e ); } @Override public void removeUpdate( DocumentEvent e ) { textChangeDetectioner( e ); } private void textChangeDetectioner( DocumentEvent e ) { for( int i = 0; i < nickList.getNickNameList().size(); i++ ) { if( e.getDocument().equals( userIDList.get( i ).getDocument() ) ) { nickList.getUserIDList().set( i, userIDList.get( i ).getText() ); } else { if( e.getDocument() .equals( nickNameList.get( i ).getDocument() ) ) { nickList.getNickNameList().set( i, nickNameList.get( i ).getText() ); } } } } @Override public void windowActivated( WindowEvent arg0 ) { } @Override public void windowClosed( WindowEvent arg0 ) { } @Override public void windowClosing( WindowEvent arg0 ) { LocalFileOps.updateNicknameList( nickList ); } @Override public void windowDeactivated( WindowEvent arg0 ) { } @Override public void windowDeiconified( WindowEvent arg0 ) { } @Override public void windowIconified( WindowEvent arg0 ) { } @Override public void windowOpened( WindowEvent arg0 ) { } }
Java
package anonymouschat.client.frames; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import java.io.ObjectOutputStream; import java.util.ArrayList; import java.util.HashMap; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTextArea; import anonymouschat.messages.TextMessage; /** * One on one chat frame, only supply two people to chat. ownerUser is the local * client, while targetUser is the user owner is chatting with. * * @author Winters */ public class OneOnOneChatFrame extends JFrame { /** * */ private static final long serialVersionUID = 1L; private HashMap<String, ArrayList<String>> tempChatLog; ObjectOutputStream out; private String ownerUserID; private String targetUserID; private JTextArea textArea; private JTextArea msgArea; private JScrollPane textScr; private JScrollPane msgScr; private JButton sendButton; final int WIDTH = 400; final int HEIGHT = 500; /** * Constructor by two user names and chatLog, outStream * * @param owner * @param target * @param tempChatLog * @param out */ public OneOnOneChatFrame( String owner, String target, HashMap<String, ArrayList<String>> tempChatLog, ObjectOutputStream out ) { this.out = out; this.tempChatLog = tempChatLog; ownerUserID = owner; targetUserID = target; setTitle( "Chatting with " + targetUserID ); setSize( WIDTH, HEIGHT ); // setResizable( false ); setVisible( true ); getContentPane().setLayout( null ); // textArea textArea = new JTextArea(); textScr = new JScrollPane( textArea ); textScr.setSize( WIDTH, HEIGHT - 100 ); textScr.setLocation( 0, 0 ); // sendMsg msgArea = new JTextArea(); msgScr = new JScrollPane( msgArea ); msgScr.setLocation( 10, HEIGHT - 90 ); msgScr.setSize( WIDTH - 130, 50 ); // sendButton sendButton = new JButton( "Send" ); sendButton.setLocation( WIDTH - 120, HEIGHT - 90 ); sendButton.setSize( 100, 50 ); sendButton.addActionListener( new ActionListener() { @Override public void actionPerformed( ActionEvent e ) { // TODO Auto-generated method stub sendTextMsg( msgArea.getText() ); msgArea.setText( "" ); } } ); this.getContentPane().add( textScr ); this.getContentPane().add( msgScr ); this.getContentPane().add( sendButton ); this.validate(); } private void sendTextMsg( String text ) { // TODO Auto-generated method stub TextMessage msg = new TextMessage(); msg.srcUser = ownerUserID; { msg.destinationUser = targetUserID; String tempData = "You ->" + msg.destinationUser + ": " + text + "\n"; textArea.append( tempData ); if( tempChatLog.containsKey( targetUserID ) ) { tempChatLog.get( targetUserID ).add( tempData ); } else { tempChatLog.put( targetUserID, new ArrayList<String>() ); tempChatLog.get( targetUserID ).add( tempData ); } } msg.encryptedData = text; // try { // ChatFrame.sendMessage( text ); // } catch( IOException e1 ) { // textArea.setText( "Error occured when sending TextMessage object to server" ); // e1.printStackTrace(); // } } }
Java
package anonymouschat.client.frames; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTextArea; import anonymouschat.utils.LocalFileOps; /** * Log Frame shows chat log with a specific user. * * @author hb * */ public class LogFrame extends JFrame{ /** * */ private static final long serialVersionUID = 1L; private static final int WIDTH = 300; private static final int HEIGHT = 500; private JTextArea msgArea; private JScrollPane msgScr; public LogFrame(String userID) { super(); this.msgArea = new JTextArea(); this.msgArea.setText(LocalFileOps.getChatLog(userID)); this.msgArea.setEditable(false); this.msgScr = new JScrollPane(msgArea); this.add(msgScr); this.setSize(WIDTH, HEIGHT); this.setVisible(true); } }
Java
package anonymouschat.client; import java.security.PublicKey; import java.util.ArrayList; import java.util.HashMap; import javax.crypto.Cipher; import anonymouschat.service.serverEntry; import anonymouschat.utils.*; import anonymouschat.Identity; import anonymouschat.NickList; import anonymouschat.client.frames.ChatFrame; import anonymouschat.client.frames.IDFrame; import anonymouschat.client.frames.NickListFrame; import anonymouschat.utils.ListOfServers; /** * UI: Open ID selection scene on start up. * * @author hb * */ public class Client { private Identity userID; private ChatFrame chatFrame; private NickListFrame nickListFrame; private NickList nickList; public static ArrayList<serverEntry> serverChain = new ArrayList<serverEntry>(); public static ListOfServers ListOfAvailableServers = new ListOfServers(); public Client() { new IDFrame( this ); } public static void main( String[] args ) { new Client(); } public Identity getIdentity() { return userID; } public void setUserID( Identity userID ) { this.userID = userID; } public ChatFrame getChatFrame() { return chatFrame; } public void setChatFrame( ChatFrame chatFrame ) { this.chatFrame = chatFrame; } public NickListFrame getNickListFrame() { return nickListFrame; } public void setNickListFrame( NickListFrame nickListFrame ) { this.nickListFrame = nickListFrame; } public NickList getNickList() { return nickList; } public void setNickList( NickList nickList ) { this.nickList = nickList; } }
Java
package anonymouschat; import java.io.Serializable; /** * Identity is an object that is used to store user information. * * @author bh349 * */ public class Identity implements Serializable { /** * */ private static final long serialVersionUID = 1L; private String userID; public Identity( String userID ) { this.setUserID( userID ); } public void setUserID( String userID ) { this.userID = userID; } public String getUserID() { return userID; } }
Java
package anonymouschat.messages; import java.io.Serializable; public class Message implements Serializable { /** * */ private static final long serialVersionUID = -1954148520479694286L; }
Java
package anonymouschat.messages; import java.io.Serializable; import javax.crypto.SecretKey; public class AESkeyMessage extends Message implements Serializable { private static final long serialVersionUID = 5674590802328543696L; public SecretKey SharedAESKey; }
Java
package anonymouschat.messages; import java.io.Serializable; /** * A class representation for an actual chat message. * It contains the destination user, chatroom, and cipher-text for the message * */ public class TextMessage extends Message implements Serializable { private static final long serialVersionUID = 3013551852027023617L; public String srcUser; public String destinationUser; //User to which the message will be delivered public String destinationChatroom; //Chat room the recipient is currently participating in. Note, is empty when sending private messages public String encryptedData; //Payload containing encrypted message }
Java
package anonymouschat.messages.serverresponses; import java.io.Serializable; import anonymouschat.messages.Message; public class ChatroomChangeResponse extends Message implements Serializable { /** * */ private static final long serialVersionUID = 1L; private boolean success; private String dstChatroomName; public ChatroomChangeResponse( boolean success ) { this.setSuccess( success ); } public void setSuccess( boolean success ) { this.success = success; } public boolean isSuccess() { return success; } public void setDstChatroomName( String dstChatroomName ) { this.dstChatroomName = dstChatroomName; } public String getDstChatroomName() { return dstChatroomName; } }
Java
package anonymouschat.messages.serverresponses; import java.io.Serializable; import java.util.List; import anonymouschat.messages.Message; /** * Server sends an instance of this to client. Client refreshes chat member * panel. * * @author bh349 * */ public class ChatroomMemberResponse extends Message implements Serializable { private static final long serialVersionUID = 7210280233927400809L; private List<String> members; private String chatroomName; public ChatroomMemberResponse( String chatRoom, List<String> members ) { setMembers( members ); chatroomName = chatRoom; } public String getChatroomName() { return chatroomName; } public void setMembers( List<String> members ) { this.members = members; } public List<String> getMembers() { return members; } }
Java
package anonymouschat.messages; import java.io.Serializable; public class ServerAnnounceMessage extends Message implements Serializable { private static final long serialVersionUID = 2188148542441890727L; private String name; public ServerAnnounceMessage( String nameIn ) { this.setName( nameIn ); } public void setName( String name ) { this.name = name; } public String getName() { return name; } }
Java
package anonymouschat.messages.clientrequests; import java.io.Serializable; /** * client sends an instance of this to server, indicating chat room change. * server creates new chat room if dst is an inexisting chat room. * * @author bh349 * */ public class ChatroomChangeRequest extends ClientRequest implements Serializable { /** * */ private static final long serialVersionUID = 1L; private String srcChatRoomName; private String dstChatRoomName; public ChatroomChangeRequest( String userID, String srcChatRoomName, String dstChatRoomName ) { super( userID ); this.setSrcChatRoomName( srcChatRoomName ); this.setDstChatRoomName( dstChatRoomName ); } public void setSrcChatRoomName( String srcChatRoomName ) { this.srcChatRoomName = srcChatRoomName; } public String getSrcChatRoomName() { return srcChatRoomName; } public void setDstChatRoomName( String dstChatRoomName ) { this.dstChatRoomName = dstChatRoomName; } public String getDstChatRoomName() { return dstChatRoomName; } }
Java
package anonymouschat.messages.clientrequests; public class UserLoginRequest extends ClientRequest { /** * */ private static final long serialVersionUID = 1L; public UserLoginRequest( String userID ) { super( userID ); } }
Java
package anonymouschat.messages.clientrequests; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.Serializable; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.spec.IvParameterSpec; import anonymouschat.messages.Message; public class encryptedMessageWrapperMessage extends Message implements Serializable{ /** * */ private static final long serialVersionUID = -5438981469645327144L; private String nextHop; private byte[] encryptedMessage; private boolean isAsymmetricEnc; //Is encrypted Asymetrically (pub/priv) or with Symmetric Key private byte[] iv; private Long connectionNumber = null; private UserLoginRequest login = null; /** * Wraps an object in encryption * @param enc * @param encryptedMessage * @throws IllegalBlockSizeException * @throws BadPaddingException * @throws IOException */ public encryptedMessageWrapperMessage(Cipher enc, Message encryptedMessage, boolean isAsymmetricEnc) throws IllegalBlockSizeException, BadPaddingException, IOException { ByteArrayOutputStream bStream = new ByteArrayOutputStream(); ObjectOutputStream oStream = new ObjectOutputStream(bStream); oStream.writeObject(encryptedMessage); //this.encryptedMessage = enc.doFinal(bStream.toByteArray()); this.encryptedMessage = bStream.toByteArray(); this.isAsymmetricEnc = isAsymmetricEnc; if (!isAsymmetricEnc) iv = enc.getIV(); } public Long getConnectionNumber() { return connectionNumber; } public void setConnectionNumber(long connectionNumber) { this.connectionNumber = connectionNumber; } public boolean isAsymmetricEncrypted() { return isAsymmetricEnc; } public IvParameterSpec getIV() { return new IvParameterSpec(iv); } public void setNextHop(String dest) { nextHop = dest; } /** * Returns the next hop in the annonymized routing chain * @return */ public String getNextHop() { return nextHop; } public byte[] getencryptedMessage() { return encryptedMessage; } public void setUserLogin( UserLoginRequest login) { this.login = login; } public UserLoginRequest getUserLogin() { return login; } }
Java
package anonymouschat.messages.clientrequests; public class RequestServerCertificate { }
Java
package anonymouschat.messages.clientrequests; import java.io.Serializable; import anonymouschat.messages.Message; public abstract class ClientRequest extends Message implements Serializable { private static final long serialVersionUID = -7443155251263210842L; private String userID; public ClientRequest(String userID) { this.setUserID( userID ); } public void setUserID( String userID ) { this.userID = userID; } public String getUserID() { return userID; } }
Java
package anonymouschat.messages.clientrequests; /** * client sends an instance of this to server, when it leaves the system. * * How to define LEAVE? * * close the chat room frame. * * @author bh349 * */ public class UserLeaveRequest extends ClientRequest { /** * */ private static final long serialVersionUID = 1L; private String chatroomName; public UserLeaveRequest( String userID, String chatroomName ) { super( userID ); setChatroomName( chatroomName ); } public void setChatroomName( String chatroomName ) { this.chatroomName = chatroomName; } public String getChatroomName() { return chatroomName; } }
Java
package anonymouschat.utils; import java.text.SimpleDateFormat; import java.util.Calendar; import anonymouschat.messages.Message; import anonymouschat.service.Server; public class Print { /** * Only print debug messages if debugging is turned on */ private static final boolean PRINT_DEBUG_MESSAGES = Constants.USE_DEBUG_MODE; private static final String DATE_FORMAT_NOW = "HH:mm:ss"; // used to format the string private static Calendar cal = null; /** * * @return String nice time format */ private static String now() { cal = Calendar.getInstance(); SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT_NOW); return sdf.format(cal.getTime()); } /** * Prints the message"\n", even if debugging is turned off * */ public static void info(String msg) { System.out.println(msg); } /** * Prints "&ltSOURCE&gt sending: &ltMESSAGE&gt at &ltNOW()&gt" * * @param source * who created the message * @param message * the message in plain text */ public static void sending(String source, String message) { if (source == null) source = "NULL"; if (message == null) message = "NULL"; System.out.println(source + " SENDING: " + message + " at " + now()); } /** * Prints "&ltDEST&gt received: &ltMESSAGE&gt at &ltNOW()&gt" * * @param dest * who received the message * @param message * the message in plain text */ public static void received(String dest, String message) { if (dest == null) dest = "NULL"; if (message == null) message = "NULL"; System.out.println(dest + " RECEIVED: " + message + " at " + now()); } /** * Prints "Debug: &ltDEBUGMESSAGE&gt" * * @param debugMessage * output only if debug is set to true */ public static void debug(String debugMessage) { if (debugMessage == null) debugMessage = "NULL"; if (PRINT_DEBUG_MESSAGES) { System.out.println(now() + " Debug: " + debugMessage); } } /** * Prints "&ltERRORMESSAGE&gt"` * * @param errorMessage * the error message to be displayed */ public static void error(String errorMessage, Server srv) { if (errorMessage == null) errorMessage = "NULL"; System.err.println(errorMessage); if (srv != null) { Server.addAlert(now() + ": " + errorMessage); } } /** * * Prints "&ltERRORMESSAGE&gt with &lte.STACKTRACE&gt" * * @param errorMessage * the message to display * @param e * the exception to print the stack trace of * @param srv * a handle to the server for updating the GUI */ public static void error(String errorMessage, Exception e, Server srv) { Print.error(errorMessage, srv); if (e == null) e = new Exception("NULL"); e.printStackTrace(); } /** * Prints a block that displays any printable information in a message * * @param msg * the message to be printed */ public static void debug(Message msg) { if (msg != null && PRINT_DEBUG_MESSAGES) { System.out.print("*****MESSAGE*****\n" + msg.getAllContents() + "\n*****END MESSAGE*****\n"); } } public static void error(String string) { Print.error(string, (Server) null); } public static void error(String string, Exception e) { Print.error(string, e, null); } }
Java
package anonymouschat.utils; import java.security.SecureRandom; /** * Store a set of constant variables for anonymous chat. * * @author hb * */ public class Constants { public static final String SERVER_FOLDER = "ServerData"; public static final String CLIENT_FOLDER = "ClientData"; public static final int numServerHops = 3; // Number of servers a client // message hops through before // it reaches destination server public static final String SYMMETRIC_CIPHER_TYPE = "AES/CBC/PKCS5PADDING"; public static final String ASYMMETRIC_CYPHER_TYPE = "RSA/ECB/OAEPWITHSHA-256ANDMGF1PADDING"; public static final String PREV_USERNAME_PASSWORD_FILE_NAME = CLIENT_FOLDER + "/" + "USERNAMES_PASSWORDS"; public static final String ID_FILE_NAME_PREFIX = CLIENT_FOLDER + "/" + "ID_"; public static final String CHAT_HIST_FILE_NAME_MIDDLE = "_LOG_"; public static final String NICKLIST_FILE_NAME_PREFIX = CLIENT_FOLDER + "/" + "NICK_"; public static final int UPSTREAM = 100; public static final int DOWNSTREAM = 500; public static final Long USER_DOWNSTREAM = -50L; public static final boolean SYMMETRIC_ENCRYPTION = false; public static final boolean ASYMMETRIC_ENCRYPTION = true; public static final String AUDIT_FILENAME = "Logs/LOCAL_AUDIT_FILE.txt"; public static SecureRandom secureRandom = new SecureRandom(); // Set to false to turn off debugging public static final boolean USE_DEBUG_MODE = true; public static final int MAX_ENC_SEGMENT_BYTES = 317; }
Java
package anonymouschat.utils; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.ObjectInputStream; import java.util.ArrayList; import java.util.LinkedList; import anonymouschat.client.Client; import anonymouschat.service.ServerEntry; /** * Create an object that reads in all of the authorized public server identities * (i.e. the ones that were placed in the Constants.SERVER_FOLDER folder * */ public class ListOfServers { public ArrayList<ServerEntry> servers = new ArrayList<ServerEntry>(); FileInputStream fin; Client client = null; /** * Read all the public identities available */ public ListOfServers() { Print.info("Creating a list of authorized servers. . ."); File dir = new File(Constants.SERVER_FOLDER); String[] children = dir.list(); if (children == null) { Print.error("No list of public servers to connect to"); System.exit(1); // Either dir does not exist or is not a directory } else { for (int i = 0; i < children.length; i++) { // Get filename of file or directory String filename = Constants.SERVER_FOLDER + "/" + children[i]; if (!filename.toLowerCase().endsWith(".dat") || filename.toLowerCase().contains("private") || filename.toLowerCase().contains("salt_") || filename.toLowerCase().contains(".svn")) { continue; } ServerEntry ident = null; try { Print.debug("Reading object from " + filename); fin = new FileInputStream(filename); ObjectInputStream ois = new ObjectInputStream(fin); ident = (ServerEntry) ois.readObject(); servers.add(ident); Print.debug("Added " + ident.serverName + " at " + ident.serverIP + "/" + ident.serverPort + " to list of known servers."); ois.close(); } catch (FileNotFoundException e) { Print.error( "Could not load public server identity file for " + filename, e); } catch (IOException e) { Print.error( "Unable to read serialized public server identity file for " + filename, e); } catch (ClassNotFoundException e) { Print.error( "Error occured when casting read in serialized public server identity object to serverEntry for " + filename, e, null); } } } } public ListOfServers(Client c) { this(); client = c; } /** * * @return a ServerEntry chosen at random, and not returned previously * @throws Exception */ public ServerEntry getRandomServer(LinkedList<ServerEntry> chain) throws Exception { if (client == null) { throw new Exception( "Unable to establish anonymous route with out setting ListOfServers.client"); } ServerEntry se; if (servers.size() == 0) throw new Exception( "The directory '" + Constants.SERVER_FOLDER + "' which holds information about how to connect to servers is empty, public server identities are [servername]Identity.dat files generated when a server is first run"); if (chain.size() >= servers.size()) throw new Exception( "Your number of server hops requested for anonymous routing is larger than the number of available servers, please reduce it to at most " + servers.size()); do { se = servers.get(Constants.secureRandom.nextInt(servers.size())); } while (chain.contains(se)); return se; } public ServerEntry getByName(String name) { for (int i = 0; i < servers.size(); i++) { if (servers.get(i).serverName.equalsIgnoreCase(name)) return servers.get(i); } return null; } }
Java
package anonymouschat.utils; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.FileWriter; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Date; import javax.crypto.SecretKey; import anonymouschat.client.Identity; import anonymouschat.client.NickNameList; import anonymouschat.exceptions.DecryptionException; import anonymouschat.exceptions.InvalidTagException; import anonymouschat.messages.securitymessages.AESEncryptedMessage; import anonymouschat.security.KeySalt; import anonymouschat.security.NameSaltPairs; import anonymouschat.security.SecurityUtils; import anonymouschat.security.SerializedObjectAndTag; /** * Interactions between client and local file. * * @author hb * */ public class LocalFileOps { /** * Loads the list of previous user names and the list of random salt and iv * values used in creating their AESKeys (with the user's password) * * @return */ public static NameSaltPairs getPreviousUserNamesAndSalt() { String fn = Constants.PREV_USERNAME_PASSWORD_FILE_NAME; NameSaltPairs nsp = null; try { nsp = (NameSaltPairs) LocalFileOps.readObject(fn); } catch (FileNotFoundException e) { Print.error("Previous Username and salt file -- " + fn + " not found."); nsp = new NameSaltPairs(); } return nsp; } /** * Saves the list of previous user identities and their random salt values * to the file system * * @param tosave */ public static void writePreviousUsers(NameSaltPairs tosave) { String f = Constants.PREV_USERNAME_PASSWORD_FILE_NAME; LocalFileOps.write(tosave, f); } /** * Get Private chatting history. Turn the List of Strings into one String. * * @param identity * @param dstUserName * @return * @throws ClassNotFoundException */ public static String getChatHist(Identity identity, String dstUserName) throws ClassNotFoundException, IOException, FileNotFoundException { String filename = Constants.CLIENT_FOLDER + "/" + identity.getUserName() + Constants.CHAT_HIST_FILE_NAME_MIDDLE + dstUserName; String chatHistory = ""; try { chatHistory = (String) LocalFileOps.readMacThenEncObject( identity.getFileEncKey(), identity.getFileMacKey(), identity.getFileSalt(), filename); } catch (FileNotFoundException e) { throw e; } catch (Exception e) { Print.error("Cannot read chat history", e); } return chatHistory; } /** * Append chat history file with a list of messages. If no existing history, * create new file. * * @param identity * @param dstUserName * @param string * @throws ClassNotFoundException * @throws IOException */ public static void appendChatHist(Identity identity, String dstUserName, String string) throws ClassNotFoundException { // read previous chat history first String chatHistory = ""; String filename = Constants.CLIENT_FOLDER + "/" + identity.getUserName() + Constants.CHAT_HIST_FILE_NAME_MIDDLE + dstUserName; try { chatHistory = LocalFileOps.getChatHist(identity, dstUserName); } catch (FileNotFoundException fnf) { try { File file = new File(filename); file.createNewFile(); } catch (IOException e) { Print.error("Cannont create file for chat log.", e); return; } } catch (IOException e1) { Print.error( "Failed to read chat history, so it could not be appended.", e1); return; } LocalFileOps.writeMacThenEncObject(chatHistory + string, identity, filename); } /** * Append the local audit file. * */ public static void appendAuditFile(String description) { Date date = new Date(); String oldFile = ""; String newFile = ""; try { oldFile = (String) readString(Constants.AUDIT_FILENAME); newFile = oldFile + date.toString() + "\t" + description + "\r\n"; } catch (FileNotFoundException e) { Print.debug("Created a new audit file"); File file = new File(Constants.AUDIT_FILENAME); try { file.createNewFile(); newFile = date.toString() + "\t" + description + "\r\n"; } catch (IOException e1) { Print.error("Cannot create a new audit file", e1); } } writeString(newFile, Constants.AUDIT_FILENAME); } /** * Write Nickname List file using MAC-then-Enc * * @param identity * @param nickList */ public static void writeNickList(Identity id, NickNameList nickList) throws IOException { try { String filename = Constants.NICKLIST_FILE_NAME_PREFIX + id.getUserName(); writeMacThenEncObject(nickList, id, filename); } catch (Exception e) { Print.error("Trouble writing nick name list as file.", e); } } /** * Write the object to the filesysten using the keys/salt associated with * the identity * * @param toSave * OBJECT TO SAVE * @param id * identity saving the object * @param filename * filename where saving */ public static void writeMacThenEncObject(Serializable toSave, Identity id, String filename) { writeMacThenEncObject(toSave, id.getFileEncKey(), id.getFileMacKey(), id.getFileSalt().getIv(), filename); } /** * Write the object to the file as Enc( {toSave, Mac(toSave; macKey); * encKey) * * @param toSave * object to save * @param encKey * key for encrypting the object after MAC-ing * @param macKey * key for MAC-ing the object to be encrypted * @param iv * encryption IV * @param filename * file to save */ public static void writeMacThenEncObject(Serializable toSave, SecretKey encKey, SecretKey macKey, byte[] iv, String filename) { // Create an object which wraps <toSave, MAC(toSave)> SerializedObjectAndTag objAndTag = new SerializedObjectAndTag(toSave, macKey); // Encrypt the association AESEncryptedMessage enced = SecurityUtils.encAES(objAndTag, encKey, iv); LocalFileOps.write(enced, filename); } /** * Get Nickname list from file. The file is saved in a MAC-then-Enc format, * so this method decrypts the object, and then checks if it is valid * * @param nickList * @return * @throws DecryptionException */ public static NickNameList getNickList(Identity id) throws DecryptionException { NickNameList nickList = null; String filename = Constants.NICKLIST_FILE_NAME_PREFIX + id.getUserName(); try { nickList = (NickNameList) LocalFileOps.readMacThenEncObject( id.getFileEncKey(), id.getFileMacKey(), id.getFileSalt(), filename); } catch (FileNotFoundException e) { Print.error("Nick name list file not found, creating new list"); } catch (InvalidTagException e) { Print.error("Failed to verify the integrity of the nickname list", e); } finally { if (nickList == null) nickList = new NickNameList(); } return nickList; } /** * Write string to the file system under the name filename * * @param writeme * @param filename */ public static void writeString(String writeme, String filename) { FileWriter fstream = null; BufferedWriter out = null; try { // Create file fstream = new FileWriter(filename); out = new BufferedWriter(fstream); out.write(writeme); } catch (Exception e) {// Catch exception if any System.err.println("Error: " + e.getMessage()); } finally { // Close the output stream try { if (out != null) out.close(); if (fstream != null) fstream.close(); } catch (IOException e) { Print.error("Failed to close streams correctly.", e); } } } /** * Write the Serializable object to the file system under the name filename * * @param writeme * @param filename */ public static void write(Serializable writeme, String filename) { FileOutputStream fos = null; ObjectOutputStream out = null; try { fos = new FileOutputStream(new File(filename)); out = new ObjectOutputStream(fos); out.writeObject(writeme); } catch (FileNotFoundException f) { Print.error("Could not find file " + filename + " write failed.", f); } catch (IOException e) { Print.error("Failed to write object to file -- " + filename, e); } finally { // close streams try { if (out != null) out.close(); if (fos != null) fos.close(); } catch (IOException e) { Print.error("Failed to close streams correctly.", e); } } } /** * Read string from file * * @param filename * @return * @throws FileNotFoundException */ public static String readString(String filename) throws FileNotFoundException { byte[] buffer = new byte[(int) new File(filename).length()]; FileInputStream f; f = new FileInputStream(filename); try { f.read(buffer); } catch (IOException e) { Print.error("Cannot read audit file", e); } finally { try { if (f != null) f.close(); } catch (IOException e) { Print.error("Failed to close file after write", e); } } return new String(buffer); } /** * Read object from file * * @param filename * @return * @throws FileNotFoundException */ public static Object readObject(String filename) throws FileNotFoundException { FileInputStream fis = null; ObjectInputStream ois = null; Object obj = null; try { fis = new FileInputStream(new File(filename)); ois = new ObjectInputStream(fis); obj = ois.readObject(); } catch (FileNotFoundException f) { throw f; } catch (IOException e) { Print.error("Cannon open file -- " + filename, e); } catch (ClassNotFoundException e) { Print.error("Cannot read object in from file.", e); } finally { try { if (ois != null) ois.close(); if (fis != null) fis.close(); } catch (IOException e) { Print.error("Failed to close streams input streams.", e); } } return obj; } /** * Decrypt and read in the Identity object associated with the user Must * provide the secret key (ie use Keys.createAESKey()) and must provide the * salt used to encrypt the user's files * * @param userName * @param key * @param salt * @return */ public static Identity getIdentityFromFile(String userName, SecretKey key, SecretKey tagkey, KeySalt salt) { String filename = Constants.ID_FILE_NAME_PREFIX + userName; Identity loaded = null; try { loaded = (Identity) readMacThenEncObject(key, tagkey, salt, filename); } catch (FileNotFoundException f) { Print.error("File not found for past ID -- " + userName); } catch (InvalidTagException e) { Print.error( "Integerity of previous Identity file can't be verified.", e); } catch (Exception e) { Print.error("Problem loading previous Idenity from file system", e); } return loaded; } /** * @param enckey * @param tagkey * @param salt * @param filename * @return * @throws FileNotFoundException * @throws InvalidTagException * @throws DecryptionException */ public static Serializable readMacThenEncObject(SecretKey enckey, SecretKey tagkey, KeySalt salt, String filename) throws FileNotFoundException, InvalidTagException, DecryptionException { Serializable loaded; // Read in encrypted wrapper <=> Enc(id,Mac(id);id_filekey) AESEncryptedMessage enced = (AESEncryptedMessage) LocalFileOps .readObject(filename); // Decrypt the wrapper SerializedObjectAndTag idAndTag = (SerializedObjectAndTag) SecurityUtils .decAES(enced, enckey, salt.getIv()); // Verify and get Id from wrapper loaded = idAndTag.getVerifiedObject(tagkey); return loaded; } /** * Write user identity as an encrypted file * * @param n * the identity to store * @param key * the key used to encrypt the identity * @param salt */ public static void writeUserId(Identity n, SecretKey key, KeySalt salt) { String fn = Constants.ID_FILE_NAME_PREFIX + n.getUserName(); try { LocalFileOps.writeMacThenEncObject(n, n, fn); } catch (Exception e) { Print.error("Failed to encrypt Identity.", e); } } /** * * @param svrName * the server name to use * @return &ltString&gt of the sub-folder and file name */ public static String getSaltFileName(String svrName) { return Constants.SERVER_FOLDER + "/salt_" + svrName + ".dat"; } /** * * @param svrName * the server identity to look for * @param isPublic * is the identity public or private * @return */ public static boolean identityExists(String svrName) { File f = null; f = new File(LocalFileOps.getPrivateIdentityFileName(svrName)); return f.exists() && f.canRead();// && g.exists() && g.canRead(); } /** * * @param svrName * the server name to use * @return &ltString&gt of the sub-folder and file name */ public static String getPrivateIdentityFileName(String svrName) { return Constants.SERVER_FOLDER + "/private" + svrName + "Identity.dat"; } /** * * @param svrName * the server name to use * @return &ltString&gt of the sub-folder and file name */ public static String getPublicIdentityFileName(String svrName) { return Constants.SERVER_FOLDER + "/public" + svrName + "Identity.dat"; } }
Java
package anonymouschat.utils; import java.net.InetAddress; import anonymouschat.service.ServerEntry; public class ServerUtils { public static void main(String[] args) throws Exception { if (args.length > 0) { // a list of servers was provided ListOfServers los = new ListOfServers(); for (int i = 0; i < args.length; i++) { ServerUtils.rebindServerIdentity(los.getByName(args[i])); } } else { // change all local public server identity files System.out .println("This will rebind all public server IDs on this " + "system to this IP address. " + "Cancel in the next 10 seconds if you don't want to do this"); for (int i = 10; i > 0; i--) { try { System.out.print(i); for (int j = 0; j < 4; j++) { Thread.sleep(250); System.out.print(" ."); } } catch (Exception e) { } } rebindAllServerIdentities(); } } public static void rebindAllServerIdentities() throws Exception { ListOfServers los = new ListOfServers(); for (ServerEntry svr : los.servers) { rebindServerIdentity(svr); } } /** * Rebind a specific serve Identity * * @param svrName * @throws Exception */ public static void rebindServerIdentity(ServerEntry oldPublicID) throws Exception { // oldPublicID.savePublicIdentity( oldPublicID.serverName, // oldPublicID.serverPort, oldPublicID.publicKey ); if (oldPublicID != null) { ServerEntry newPublicID = new ServerEntry(oldPublicID.serverName, InetAddress.getLocalHost().getHostAddress(), oldPublicID.serverPort, oldPublicID.publicKey); // store the public ID LocalFileOps.write(newPublicID, LocalFileOps .getPublicIdentityFileName(oldPublicID.serverName)); } else { Print.error("Cannot modify null object."); } } public static void rebindSpecificServer(String serverName) throws Exception { ListOfServers los = new ListOfServers(); rebindServerIdentity(los.getByName(serverName)); } }
Java
package anonymouschat.exceptions; /** * Thrown when a server fails to load a private identity from the file system * @author Jason * */ public class LoadPrivateIdentityException extends Exception { private static final long serialVersionUID = 4454394814759577841L; private String description; public LoadPrivateIdentityException(String description){ super(description); this.description = description; } public String getDescription(){ return description; } }
Java
package anonymouschat.exceptions; /** * Thrown when a server fails to send a message to a published user. */ public class SendMessageToPublishedUserException extends Exception { private static final long serialVersionUID = -5968138542205496997L; public SendMessageToPublishedUserException(String errMsg){ super(errMsg); } }
Java
package anonymouschat.exceptions; /** * Thrown when doing dec * * @author bh349 * */ public class DecryptionException extends Exception { private static final long serialVersionUID = -2111531216279248848L; public DecryptionException(String msg) { super(msg); } }
Java
package anonymouschat.exceptions; /** * Thrown when one server cannot connect to another server */ public class ServerToServerConnectionException extends Exception { public ServerToServerConnectionException(String string) { super(string); } private static final long serialVersionUID = -4310462956077682997L; }
Java
package anonymouschat.exceptions; /** * Exception thrown when the tag of an object does not match * @author jnfrye * */ public class InvalidTagException extends Exception { private static final long serialVersionUID = 8925808031880600791L; public InvalidTagException(String message){ super(message); } }
Java
package anonymouschat.exceptions; /** * Thrown when a server fails to connect to a socket. * */ public class ConnectionException extends Exception { private static final long serialVersionUID = 5447179585567596957L; public ConnectionException(String msg) { super(msg); } }
Java
package anonymouschat.service; import java.io.IOException; import java.net.ServerSocket; import java.net.UnknownHostException; import java.util.LinkedList; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import javax.swing.JOptionPane; import javax.swing.JPasswordField; import javax.swing.JProgressBar; import anonymouschat.client.PublicIdentity; import anonymouschat.exceptions.ConnectionException; import anonymouschat.security.KeySalt; import anonymouschat.utils.LocalFileOps; import anonymouschat.utils.Print; /** * Main server object, sets the server name and port based on command line * arguments * */ public class Server extends Thread { /** * Maps username or server names connected to this server to their outbound * channel */ public static volatile ConcurrentMap<String, Connection> currentConnections = new ConcurrentHashMap<String, Connection>(); /** * Maps users to their public identity (public keys) */ public static volatile ConcurrentHashMap<String, PublicIdentity> userNameToIdMap = new ConcurrentHashMap<String, PublicIdentity>(); /** * A list of all the users published at this server */ public static volatile LinkedList<String> locallyPublishedUsers = new LinkedList<String>(); /** * Maps a username to the last time the server received a user login message */ public static volatile ConcurrentHashMap<String, Long> userNameToLastHeardFrom = new ConcurrentHashMap<String, Long>(); /** * &lt Username, HostingServer &gt Tuple Discover a user's publishing * server, this server knows a way to get back to the user, but not the * entire route */ public static volatile ConcurrentHashMap<String, String> usernameToHostingServer = new ConcurrentHashMap<String, String>(); // the name of this server thread private String serverName = ""; // Identity of the current server (public/private keys) public ServerIdentObject serverIdentity; // Port the server listens on (updated later) private int port = -1; /** * Maps a pseudo-name (connection number) to another pseudo-name(connection * number) & socket */ public static final ServerConnectionIdManager connectionIdManager = new ServerConnectionIdManager(); // Whether the server is initialized and ready to accept messages (used for // GUI) private boolean isReady = false; // Whether someone has closed the server GUI, and the actual server should // shutdown private boolean shutDown = false; // Mapping from user id to their pseudo-name (connection number) at the next // hop in the route towards the recipient user (used only on publication // server) private static volatile ConcurrentHashMap<String, String> userToConnectionId = new ConcurrentHashMap<String, String>(); // The socket that the server listens on for new connections, or new // messages private ServerSocket serverSocket; private ServerGUI myGUI; private static String alerts = ""; private static String password = null; /** * * @param name * the server name * @param portno * the port to use for accepting connections */ public Server(String name, int portno) { serverName = name; port = portno; } /** * @param args */ public static void main(String[] args) { // Initial implementation uses arguments for server names if (args.length > 1) { Server s = new Server(args[0], Integer.parseInt(args[1])); Print.info("Starting server " + s.getName() + ". . ."); s.start(); if (args.length == 3) { password = args[2]; } } else { Print.error("You need to provide a name and port for this server"); System.exit(0); } } /** * Whether the server is initialized and ready to receive messages * * @return true if ready */ private boolean isReady() { return this.isReady; } /** * Return the server name associated with the currently running server * * @return String containing server name of this server */ public String getServerName() { return serverName; } /** * Run server thread (open new socket and listen for announce messages) */ @Override public void run() { // Opens server identity and initializes socket for server to listen on initialize(); // Wait until socket is open to accept messages / new connections while (!this.isReady()) { try { Thread.sleep(10); } catch (InterruptedException e) { Print.error("Error sleeping - you're hosed!", e); } } // Launch server GUI myGUI = new ServerGUI(this); Print.info("Starting server GUI. . . "); myGUI.start(); // Until the server GUI is closed accept new messages and handle them Print.info("Listening for messages."); while (!shutDown) { try { listenForMessage(); } catch (Exception e) { Print.error("cannot listen for message", e); continue; } } Print.debug("Exiting. . ."); } /** * Open server identity and create socket for listening */ public void initialize() { serverSocket = null; try { Print.debug("Trying to open server identity for " + serverName); // Prompt the admin of the server for a password used to encrypt // identity if (Server.password == null) { Server.password = this.getPassword(); } // If we already have a server identity created for this server if (LocalFileOps.identityExists(serverName)) { serverIdentity = ServerIdentObject.loadPrivateIdentity( serverName, password); } else { // Create a new server identity, one does not already exist JProgressBar progress = this .showProgressPane("Creating new identity. . ."); Print.debug("Creating new identity. . ."); KeySalt newSalt = new KeySalt(); serverIdentity = new ServerIdentObject(serverName, password, newSalt, this); progress.setString("Created Identity"); progress.setIndeterminate(false); progress.setValue(100); } password = null; // Open server socket to listen for new connections serverSocket = new ServerSocket(port); Print.info(serverName + ": Listening on port " + port); } catch (UnknownHostException e) { Print.error("Cannot load identity - unknown host", e); System.exit(1); } catch (IOException e) { Print.error("Cannot load identity - I/O error", e); System.exit(1); } catch (Exception e) { Print.error("Cannot load identity", e); System.exit(1); } // done initializing, ready for messages: this.isReady = true; } /** * Displays progress when creating or opening an identity * * @param string * * @return Progress bar that will display until the identity is * created/opened */ private JProgressBar showProgressPane(String string) { final JProgressBar prog = new JProgressBar(); prog.setIndeterminate(true); prog.setString(string); prog.setStringPainted(true); Thread t = new Thread() { @Override public void run() { Object[] obj = { prog }; JOptionPane.showMessageDialog(null, obj, "Progress", JOptionPane.PLAIN_MESSAGE); } }; t.start(); return prog; } /** * Prompt the user for a password (GUI) and make sure it fits our password * criteria * * @return Password as string */ private String getPassword() { String password = null; password = this.promptForPassword(); if (password == null || password.equalsIgnoreCase("")) { Print.error("Cannot use a blank password"); System.exit(1); } return password; } /** * Give user a popup asking to provide a password (GUI) * * @return Password as a string */ private String promptForPassword() { JPasswordField passwordField = new JPasswordField(); Object[] obj = { "Please input the password for " + serverName + ":", passwordField }; Object stringArray[] = { "OK", "Cancel" }; String password = null; if (JOptionPane.showOptionDialog(null, obj, "Password", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, stringArray, obj) == JOptionPane.YES_OPTION) { password = new String(passwordField.getPassword()); } return password; } /** * Wait for an announce message, when received store the connection and * return * * @throws Exception */ public void listenForMessage() throws Exception { // Wait for new connection Connection newConnection = null; try { newConnection = new Connection(this.serverName); newConnection.openCom(serverSocket.accept()); } catch (IOException e) { Print.error("Accept failed.", e); } catch (ConnectionException e) { Print.error("Creating the in/out streams failed.", e); } // Thread used to handle messages coming into this server on the newly // created connection InConnectionThread newInConnection = new InConnectionThread( newConnection, this); newInConnection.start(); } // Base number that connection numbers are created from private static Long connectionNumber = System.currentTimeMillis(); // Returns a unique number for each user session public static Long generateConnectionId() { return connectionNumber++; } /** * Return the port this server is running on * * @return &ltint&gt Port this server is running on * */ public int getServerPort() { return port; } /** * Returns the pseudo-name (connection number) associated with a username to * route from a publication server to the user * * @param destinationUser * @return &lt Long &gt the connection number */ public static String getConnectionIdFor(String destinationUser) { return userToConnectionId.get(destinationUser); } /** * Adds entry to map username to pseudo-name (connection number) * * @note Downstream means towards a client, away from a publication server * @param user * @param downstreamId */ public static void addUserConnectionId(String user, String downstreamId) { userToConnectionId.put(user, downstreamId); } /** * Get a list of the users currently logged onto the entire service * * @return &lt String&gt a list of all the users online and where they are * published */ public String getOnlineUsers() { StringBuffer sb = new StringBuffer(); for (String user : Server.usernameToHostingServer.keySet()) { sb.append(Server.getShortUserName(user) + "\t\t\t" + Server.usernameToHostingServer.get(user) + "\n"); } return sb.toString(); } /** * * @return &ltString&gt a list of all the users this server is publishing */ public String getPublishedUsers() { StringBuffer sb = new StringBuffer(); for (String user : Server.locallyPublishedUsers) { sb.append(user + "\n"); } return sb.toString(); } /** * * @param user * a long user ID string * @return &ltString&gt "the first two clusters. . . the last two clusters" */ public static String getShortUserName(String user) { String ret = ""; String tmp[] = null; tmp = user.split("-"); if (user.startsWith("-")) { tmp[0] = "-" + tmp[1]; tmp[1] = tmp[2]; } ret += tmp[0] + "-" + tmp[1] + "-. . .-" + tmp[tmp.length - 2] + "-" + tmp[tmp.length - 1]; return ret; } /** * * @return &ltString&gt the list of open connections, with their connection * numbers */ public static String getAllConnections() { return (Server.connectionIdManager.getConnectionMultiMap()); } /** * set the shutdown parameter to true to close the server * @param shutDown */ public void setShutDown(boolean shutDown) { this.shutDown = shutDown; } /** * Add an alert to the alerts String * @param alert */ public static void addAlert(String alert) { if (alerts.length() > 0) { alerts += "\n"; } alerts += alert + "\n"; } /** * Returns a string of all the new alerts this server is aware of * @return */ public static String getNewAlerts() { if (alerts.length() == 0) { return null; } String temp = new String(alerts); alerts = ""; return temp; } }
Java
package anonymouschat.service; import java.util.concurrent.ConcurrentHashMap; import javax.crypto.SecretKey; import anonymouschat.utils.Print; /** * Upstream is the path of client towards publication server Downstream is the * path of publication server towards client * * @author jnfrye * */ public class ServerConnectionIdManager { private ConcurrentHashMap<Long, String> up2fulldown = new ConcurrentHashMap<Long, String>(); private ConcurrentHashMap<String, Long> fulldown2up = new ConcurrentHashMap<String, Long>(); private ConcurrentHashMap<String, Connection> fullDown2OutputStream = new ConcurrentHashMap<String, Connection>(); private ConcurrentHashMap<String, Long> fullDown2Down = new ConcurrentHashMap<String, Long>(); private ConcurrentHashMap<String, SecretKey> fullDown2AESKey = new ConcurrentHashMap<String, SecretKey>(); private ConcurrentHashMap<Connection, ConcurrentHashMap<Long, Long>> allConnectionsMultiMap = new ConcurrentHashMap<Connection, ConcurrentHashMap<Long, Long>>(); /** * Create a new server connection object */ public ServerConnectionIdManager() { } /** * Add a new association to the manager * * @param upid * - upstream id that the server upstream server wants * @param downid * - id downstream server has associated with this number */ public void add( Long downid, Long upid, Connection channel ) { String fulldown; fulldown = getFullDown( channel, downid ); this.fullDown2Down.put( fulldown, downid ); this.fulldown2up.put( fulldown, upid ); this.up2fulldown.put( upid, fulldown ); this.fullDown2OutputStream.put( fulldown, channel ); if( !this.allConnectionsMultiMap.containsKey( channel ) ) { this.allConnectionsMultiMap.put( channel, new ConcurrentHashMap<Long, Long>() ); } this.allConnectionsMultiMap.get( channel ).put( downid, upid ); } public String getFullDown( Long upid ) { return this.up2fulldown.get( upid ); } public Connection getOutChannel( String fulldown ) { return this.fullDown2OutputStream.get( fulldown ); } public Long getDownStreamId( String fulldown ) { return this.fullDown2Down.get( fulldown ); } /** * A representation of the connection and the id provided by the remote * system */ public static String getFullDown( Connection c, Long downid ) { if( c == null ) { Print.error( "Connection in getFullDown is null" ); return ":" + downid.hashCode(); } if( downid == null ) { Print.error( "downid in getFullDown is null" ); return c.hashCode() + ":"; } return c.hashCode() + ":" + downid.hashCode(); } public Long getUpstreamId( String fulldown ) { return this.fulldown2up.get( fulldown ); } public void setAESKeyForRoute( String fulldown, SecretKey AESkey ) { this.fullDown2AESKey.put( fulldown, AESkey ); } public SecretKey getAESKeyForRoute( String fulldown ) { return this.fullDown2AESKey.get( fulldown ); } /** * Returns a list of sockets, with the psuedo-name mappings used on that socket * @return */ public String getConnectionMultiMap() { StringBuffer sb = new StringBuffer(); for( Connection conn : this.allConnectionsMultiMap.keySet()) { if( !conn.isOpen() ) { // clean it up this.allConnectionsMultiMap.remove( conn ); continue; } if( sb.length() > 0 ) { sb.append( "\n" ); } sb.append( conn.getInfo() + ": {" ); for( Long downid : this.allConnectionsMultiMap.get( conn ).keySet() ) { sb.append( downid + "->" + this.allConnectionsMultiMap.get( conn ).get( downid ) + ", " ); } sb.append( "}" ); } String result = new String( sb ); result = result.replace( ", }", "}" ); return result; } }
Java
package anonymouschat.service; import java.io.Serializable; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.PublicKey; import javax.crypto.Cipher; import javax.crypto.NoSuchPaddingException; import javax.crypto.SecretKey; import anonymouschat.utils.Constants; import anonymouschat.utils.Print; /** * * Contains String servername, string serverIP, int serverPort, PublicKey * publicKey * */ public class ServerEntry implements Serializable { private static final long serialVersionUID = 4747248213859099964L; public ServerIdentObject serverIdent = null; /** * Create a new server entry based on the server Identity * @param serverIdent */ public ServerEntry(ServerIdentObject serverIdent) { Print.debug("Added ServerIdentity to ServerEntry"); this.serverIdent = serverIdent; } /** * * @param serverName * the name of the server * @param serverIP * the server's IP * @param serverPort * the server's port * @param publicKey * the server's public key */ public ServerEntry(String serverName, String serverIP, int serverPort, PublicKey publicKey) { Print.debug("Created ServerEntry " + serverName + " at " + serverIP + ":" + serverPort); this.serverIdent = null; this.serverName = serverName; this.serverIP = serverIP; this.serverPort = serverPort; this.publicKey = publicKey; } public String serverName; public int serverPort; public String serverIP; public PublicKey publicKey; private transient Cipher asymmetricCipherEngine = null; private SecretKey SymmetricKey = null; public void setPublicKey(PublicKey pub) { publicKey = pub; } public void setSymmetricKey(SecretKey sec) { SymmetricKey = sec; } public SecretKey getSymmetricKey() { return SymmetricKey; } /** * Returns the Cipher object with this server's public key * @return * @throws NoSuchAlgorithmException * @throws NoSuchPaddingException * @throws InvalidKeyException */ public Cipher getAsymmetricCipherEngine() throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException { if (asymmetricCipherEngine == null) { Cipher enc = Cipher .getInstance(Constants.ASYMMETRIC_CYPHER_TYPE); enc.init(Cipher.ENCRYPT_MODE, publicKey); asymmetricCipherEngine = enc; } return asymmetricCipherEngine; } }
Java
package anonymouschat.service; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.io.ObjectInputStream; import java.io.Serializable; import java.net.InetAddress; import java.net.UnknownHostException; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.PublicKey; import javax.crypto.SecretKey; import anonymouschat.exceptions.DecryptionException; import anonymouschat.exceptions.InvalidTagException; import anonymouschat.exceptions.LoadPrivateIdentityException; import anonymouschat.messages.EncryptedMessageWrapperMessage; import anonymouschat.security.KeySalt; import anonymouschat.security.Keys; import anonymouschat.security.SecurityUtils; import anonymouschat.utils.LocalFileOps; import anonymouschat.utils.Print; /** * * A class to store public keys, and (optionally) private keys * */ public class ServerIdentObject implements Serializable { private static final long serialVersionUID = -2636702683734153948L; private PrivateKey privateKey; private SecretKey symmetricKey = null; private PublicKey publicKey; private PublicKey publicSigningKey; private PrivateKey privateSigningKey; private String serverName; private transient Server server; /** * Given server parameters, generate RSA keys, signing keys, and aes/mac * file keys * * @param svrName * the name of the server * @param password * the password to use for protecting private keys * @param newSalt * salt to use with a password * @param server * a handle to the server creating this object * @throws NoSuchAlgorithmException */ public ServerIdentObject(String svrName, String password, KeySalt newSalt, Server server) throws NoSuchAlgorithmException { // Generate private and public key here Print.debug("Generating new identity file for server: " + svrName); KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA"); gen.initialize(3072); KeyPair keyPair = gen.generateKeyPair(); SecretKey secret = Keys.createAESKey(password, newSalt.getSalt1Bytes()); SecretKey secret2 = Keys .createAESKey(password, newSalt.getSalt2Bytes()); publicKey = keyPair.getPublic(); privateKey = keyPair.getPrivate(); KeyPair signingKeyPair = gen.generateKeyPair(); publicSigningKey = signingKeyPair.getPublic(); privateSigningKey = signingKeyPair.getPrivate(); serverName = svrName; this.server = server; saveFullIdentity(secret, secret2, newSalt); // Save the identity to // file so next time we // can use it. } public void setSymmetricKey(SecretKey key) { symmetricKey = key; } public SecretKey getSymmetricKey() { return symmetricKey; } /** * Load an existing identity given the name and password * * @param svrName * the name of the server * @return &ltServerIdentObject&gt a server identity * @throws LoadPrivateIdentityException */ public static ServerIdentObject loadPrivateIdentity(String svrName, String password) throws LoadPrivateIdentityException { Print.debug("Loading existing identity: " + svrName); ServerIdentObject ident = null; File identityFile = null; File saltFile = null; identityFile = new File( LocalFileOps.getPrivateIdentityFileName(svrName)); saltFile = new File(LocalFileOps.getSaltFileName(svrName)); try { try { long idLength = identityFile.length(); byte[] encData = new byte[(int) idLength]; FileInputStream fin = new FileInputStream(identityFile); fin.read(encData); fin.close(); fin = new FileInputStream(saltFile); ObjectInputStream ois = new ObjectInputStream(fin); Object temp = ois.readObject(); KeySalt salt = null; if (temp instanceof KeySalt) { salt = (KeySalt) temp; } else { Print.error("Unexpected object type in salt file"); LocalFileOps.appendAuditFile("Failed to launch server " + svrName + " the salt file is corrupted."); System.exit(1); } ois.close(); fin.close(); temp = null; SecretKey secret = Keys.createAESKey(password, salt.getSalt1Bytes()); SecretKey secret2 = Keys.createAESKey(password, salt.getSalt2Bytes()); password = null; Print.debug("Decrypting " + encData.length + " bytes"); temp = LocalFileOps.readMacThenEncObject(secret, secret2, salt, LocalFileOps.getPrivateIdentityFileName(svrName)); if (temp instanceof ServerEntry) { ServerEntry entry = (ServerEntry) temp; ident = (ServerIdentObject) entry.serverIdent; } else { Print.error("Unexpected object type in identity file"); System.exit(1); } identityFile = null; } catch (FileNotFoundException e) { Print.error("Cannot find identity file", e); throw new LoadPrivateIdentityException( "Could not load identity file: " + e.getLocalizedMessage()); } catch (IOException e) { Print.error("I/O error opening iSdentity file", e); throw new LoadPrivateIdentityException( "Unable to read serialized server identity object from identity file: " + e.getLocalizedMessage()); } catch (ClassNotFoundException e) { Print.error("Failed to load salt file ", e); throw new LoadPrivateIdentityException( "Unable to read server salt file"); } catch (InvalidTagException e) { Print.error("Could not load server identity file because the MAC tag didn't match"); throw new LoadPrivateIdentityException( "The MAC tag didn't match"); } catch (DecryptionException e) { Print.error("Could not load server identity file because the password was incorrect."); throw new LoadPrivateIdentityException( "The password was incorrect."); } } catch (LoadPrivateIdentityException up) { LocalFileOps.appendAuditFile("Failed to load server file: " + up.getDescription()); throw up; } return ident; } public PublicKey getPublicKey() { return publicKey; } public PrivateKey getPrivateKey() { return privateKey; } public PublicKey getPublicSigningKey() { return publicSigningKey; } public PrivateKey getPrivateSigningKey() { return privateSigningKey; } /** * Removes the outer encryption layer of an EncryptedMessageWrapperMessage * * @param encryptedMessage * the nested message that you want to remove the outer layer of * @return &lt Object &gt the inner object that was encrypted * @throws DecryptionException */ public Object unwrapEncryptionLayer( EncryptedMessageWrapperMessage encryptedMessage) throws DecryptionException { // Decrypts, re-serializes message object. byte[] encryptedByteArray = encryptedMessage.getencryptedMessage(); byte[] unencryptedByteArray = null; if (encryptedMessage.isAsymmetricEncrypted()) { unencryptedByteArray = SecurityUtils.decRSA(encryptedByteArray, privateKey); } else { unencryptedByteArray = SecurityUtils.decAES(encryptedByteArray, symmetricKey, encryptedMessage.getIV().getIV()); } return SecurityUtils.byteArrayToObject(unencryptedByteArray); } /** * Save the private encryption key, the signing key, salt, iv, etc * * @param encKey * the key to encrypt with * @param macKey * the key to MAC with * @param newSalt * the salt used for the IV */ public void saveFullIdentity(SecretKey encKey, SecretKey macKey, KeySalt newSalt) { try { ServerEntry privateID = new ServerEntry(this); Print.debug("Wrote public identity file"); savePublicIdentity(this.serverName, this.server.getServerPort(), this.publicKey); LocalFileOps.writeMacThenEncObject(privateID, encKey, macKey, newSalt.getIv(), LocalFileOps.getPrivateIdentityFileName(serverName)); Print.debug("Successfully wrote private identity file"); LocalFileOps.write(newSalt, LocalFileOps.getSaltFileName(serverName)); Print.debug("Wrote salt file"); } catch (Exception e) { Print.error("Cannot save identities for " + serverName, e); } } /** * Save the public portion of an identity * * @param serverName * the friendly name of the server * @param serverPort * the port the server listens on * @param pubKey * the servers public keys * @throws UnknownHostException */ public void savePublicIdentity(String serverName, int serverPort, PublicKey pubKey) throws UnknownHostException { Print.debug("Storing server identity: " + serverName + "@" + InetAddress.getLocalHost().getHostAddress() + "/" + serverPort); ServerEntry publicID = new ServerEntry(serverName, InetAddress .getLocalHost().getHostAddress(), serverPort, pubKey); // store the public ID LocalFileOps.write(publicID, LocalFileOps.getPublicIdentityFileName(serverName)); } }
Java
package anonymouschat.service; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.net.Socket; import java.net.UnknownHostException; import anonymouschat.exceptions.ConnectionException; import anonymouschat.messages.Message; import anonymouschat.utils.Print; /** * * Holds a socket, input and output streams, and a string of the "local" and * "remote" sides * */ public class Connection implements Serializable { /** * */ private static final long serialVersionUID = 9205752104143856932L; private transient Socket socket = null; private transient ObjectOutputStream oos = null; private transient ObjectInputStream ois = null; /** * a representation of the local side of a connection, perhaps a name or an * IP:port */ private String localEnd = null; /** * a representation of the remote side of a connection, perhaps a name or an * IP:port */ private String remoteEnd = null; /** * false until the connection is open successfully */ private boolean isOpen = false; /** * An object to store a socket, in/output streams and when it was last used */ public Connection() { Print.debug("Creating a new connection object"); } /** * Sets information and opens a socket, including output and input streams * * @param server * the server to open a connection to * @param localEnd * the name of the client or server creating the connection * @param remoteEnd * the name of the destination client or server accepting a * connection * @throws ConnectionException */ public Connection(ServerEntry server, String localEnd) throws ConnectionException { this(); this.openCom(server); this.localEnd = localEnd; } /** * * @param socketToOpen * @param localEnd * @param remoteEnd * @throws ConnectionException */ public Connection(Socket socketToOpen, String localEnd, String remoteEnd) throws ConnectionException { this(); this.openCom(socketToOpen, remoteEnd); this.localEnd = localEnd; } /** * * @param localEnd * a string representation of the local end of this connection */ public Connection(String localEnd) { this(); this.localEnd = localEnd; } /** * close the in/out streams and socket, set all to null */ public void closeCom() { try { oos.close(); ois.close(); socket.close(); oos = null; ois = null; socket = null; } catch (IOException e) { } isOpen = false; } /** * A representation of the connection <br> * (local end) &lt -- &gt (remote end) * * @return the string representation of the local and remote ends of the * connection */ public String getInfo() { return localEnd + "<-->" + remoteEnd; } /** * @return the ObjectInputStream for this connection */ public ObjectInputStream getInputStream() { return ois; } /** * @return the string representing the local side of this connection */ public String getLocalEnd() { return localEnd; } /** * @return the ObjectOutputStream for this connection */ public ObjectOutputStream getOutputStream() { return oos; } /** * @return the string representing the remote side of this connection */ public String getRemoteEnd() { return remoteEnd; } /** * @return the socket for this connection */ public Socket getSocket() { return socket; } /** * @return <b>true</b> if the socket is open and connected */ public boolean isOpen() { return isOpen; } /** * * @param server * a server to open a connection with * @throws ConnectionException */ private void openCom(ServerEntry server) throws ConnectionException { try { this.openCom(new Socket(server.serverIP, server.serverPort), server.serverName); } catch (UnknownHostException e) { throw new ConnectionException("UnknownHostException"); } catch (IOException e) { throw new ConnectionException("IOException"); } } /** * * @param socketToOpen * a socket to use to create an in/out stream * @throws ConnectionException */ public void openCom(Socket socketToOpen) throws ConnectionException { this.openCom(socketToOpen, socketToOpen.getInetAddress().toString() + ":" + socketToOpen.getPort()); } /** * * @param newSocket * a socket to create the streams of * @throws ConnectionException */ public void openCom(Socket newSocket, String remoteEnd) throws ConnectionException { try { this.socket = newSocket; // new Socket( server.serverIP, // server.serverPort ); this.socket.setKeepAlive(true); oos = new ObjectOutputStream(socket.getOutputStream()); ois = new ObjectInputStream(socket.getInputStream()); this.remoteEnd = remoteEnd; } catch (IOException e) { throw new ConnectionException("IOException"); } isOpen = true; } /** * Send message using this OutConnection's Socket * * @param message * - message to send * @throws IOException */ public void sendMessage(Serializable message) throws IOException { Print.sending(this.localEnd, " serializable message " + message.toString() + " to " + this.remoteEnd); Print.debug((Message) message); this.oos.writeObject(message); this.oos.flush(); } /** * @param localEnd * set the string representing the local side of this connection */ public void setLocalEnd(String localEnd) { this.localEnd = localEnd; } /** * @param remoteEnd * set the string representing the remote side of this connection */ public void setRemoteEnd(String remoteEnd) { this.remoteEnd = remoteEnd; } }
Java
package anonymouschat.service; import java.io.IOException; import java.io.Serializable; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import anonymouschat.client.PublicIdentity; import anonymouschat.exceptions.DecryptionException; import anonymouschat.exceptions.SendMessageToPublishedUserException; import anonymouschat.exceptions.ServerToServerConnectionException; import anonymouschat.messages.AESkeyMessage; import anonymouschat.messages.EncryptedMessageWrapperMessage; import anonymouschat.messages.KeyResponse; import anonymouschat.messages.Message; import anonymouschat.messages.ServerAnnounceMessage; import anonymouschat.messages.clientrequests.ClientRequest; import anonymouschat.messages.clientrequests.KeyRequest; import anonymouschat.messages.clientrequests.UserLoginRequest; import anonymouschat.messages.clientrequests.UserLogoutRequest; import anonymouschat.messages.securitymessages.RSAEncryptedMessage; import anonymouschat.security.SecurityUtils; import anonymouschat.utils.Constants; import anonymouschat.utils.ListOfServers; import anonymouschat.utils.LocalFileOps; import anonymouschat.utils.Print; /** * Connection coming into a server (send messages TO a server with an instance * of this class) * */ public class InConnectionThread extends Thread { /** * the connection this thread will send and receive messages on */ private Connection connection = null; /** * The servername running this thread */ private String serverName; /** * a handle to the server object owning this thread */ private Server server = null; /** * A list of all servers authorized and available */ private ListOfServers availableServers = new ListOfServers(); /** * A pseudo-id to give to another server to keep track of sessions on the * same connection */ private Long outboundConnectionNumber; /** * A thread to handle incoming messages on existing connections * * @param newConnection * the connection to monitor * @param server * a handle to the server owning this thread */ InConnectionThread(Connection newConnection, Server server) { this.connection = newConnection; this.server = server; this.serverName = server.getServerName(); } /** * Listens to socket for new messages and handles them */ @Override public void run() { Print.debug("Thread started to handle connection " + connection.getInfo() + ". . ."); Object message = null; // As long as the connection is not closed, wait for a new message while (connection.isOpen()) { // Read in the next message to process try { message = (Object) connection.getInputStream().readObject(); } catch (IOException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } Print.debug("Received a message on connection " + connection.getInfo() + ": " + message.toString()); handleMessage(message); } } /** * check if a message has encryption and remove it, then handle it * * @param message * the message received * @return */ private void handleMessage(Object message) { /** * A pseudo-id provided by the remote end to keep track of sessions */ Long incomingConnectionNumber = null; Object unwrappedMessage = null; // check if the message needs to be unwrapped if (message instanceof EncryptedMessageWrapperMessage) { EncryptedMessageWrapperMessage encMsg = (EncryptedMessageWrapperMessage) message; // check if an incoming connection number was provided if (encMsg.getConnectionNumber() != null) { incomingConnectionNumber = encMsg.getConnectionNumber(); // (upstream) message is going client -> publication server if (encMsg.isGoingUpstream()) { handleUpstreamMessage(encMsg, incomingConnectionNumber); } else { handleDownstreamMessage(encMsg, incomingConnectionNumber); return; } } // remove the outer encryption layer try { unwrappedMessage = server.serverIdentity .unwrapEncryptionLayer(encMsg); } catch (DecryptionException e) { Print.error( "Unable to unwrap encryption layer on message recieved", e, server); LocalFileOps .appendAuditFile("@Server " + this.serverName + ", Failed to decrypt, and remove a layer of encryption."); } } else { // message is not an encrypted message wrapper message, and needs to // be handled directly unwrappedMessage = message; } handleUnwrappedMessage(unwrappedMessage, incomingConnectionNumber); } /** * handles an inner message after a layer of encryption is removed * * @param unwrappedMessage * an unwrapped (inner) message to be handled * @param incomingConnectionNumber * the connection number the outer message was address to */ private void handleUnwrappedMessage(Object unwrappedMessage, Long incomingConnectionNumber) { // handle the inner message if (unwrappedMessage instanceof RSAEncryptedMessage) { handleRSAEncryptedMessage((RSAEncryptedMessage) unwrappedMessage); } else if (unwrappedMessage instanceof ClientRequest) { handleClientRequest((ClientRequest) unwrappedMessage, incomingConnectionNumber); } else if (unwrappedMessage instanceof EncryptedMessageWrapperMessage) { handleEncryptedMessageWrapperMessage( (EncryptedMessageWrapperMessage) unwrappedMessage, incomingConnectionNumber); } else if (unwrappedMessage instanceof ServerAnnounceMessage) { handleServerAnnounceMessage((ServerAnnounceMessage) unwrappedMessage); } else if (unwrappedMessage instanceof AESkeyMessage) { try { handleAESkeyMessage((AESkeyMessage) unwrappedMessage, ServerConnectionIdManager.getFullDown(connection, incomingConnectionNumber)); } catch (NoSuchAlgorithmException e) { Print.error("Bad Algorithm for AES key handling", e); } catch (NoSuchPaddingException e) { Print.error("Bad Padding for AES key handling", e); } } else { Print.error("Unknown message received from:" + connection.getRemoteEnd()); } } private void handleClientRequest(ClientRequest unwrappedMessage, Long incomingConnectionNumber) { if (unwrappedMessage instanceof UserLoginRequest) { // if login is for this server if (((UserLoginRequest) unwrappedMessage).getPublicationServer() .equalsIgnoreCase(server.getServerName())) { handleUserLoginRequest((UserLoginRequest) unwrappedMessage, incomingConnectionNumber); } else { handlePublishedUserMessage((UserLoginRequest) unwrappedMessage); } } else if (unwrappedMessage instanceof UserLogoutRequest) { handleUserLogoutRequest((UserLogoutRequest) unwrappedMessage); } else if (unwrappedMessage instanceof KeyRequest) { handleKeyRequest((KeyRequest) unwrappedMessage); } } /** * Handles a message that is going downstream (server --> client) * * @param encMsg * an encryptedMessage that is heading downstream * @param incomingConnectionNumber * the connection number of the outer message */ private void handleDownstreamMessage(EncryptedMessageWrapperMessage encMsg, Long incomingConnectionNumber) { // If message is encrypted wrapper going // publication server -> client (downstream) String fulldown = Server.connectionIdManager .getFullDown(incomingConnectionNumber); Long downId = Server.connectionIdManager.getDownStreamId(fulldown); // get the out connection to the next server Connection outConn = Server.connectionIdManager.getOutChannel(fulldown); Cipher enc; try { enc = Cipher.getInstance(Constants.SYMMETRIC_CIPHER_TYPE); enc.init(Cipher.ENCRYPT_MODE, Server.connectionIdManager.getAESKeyForRoute(fulldown)); encMsg = new EncryptedMessageWrapperMessage(enc, encMsg, Constants.SYMMETRIC_ENCRYPTION); } catch (Exception e) { Print.error( "Unable to add encryption layer sending message server->client", e, server); } encMsg.setDirection(Constants.DOWNSTREAM); encMsg.setDownId(downId); encMsg.setConnectionNumber(downId); Print.debug("Passing a message downstream to a user."); try { outConn.sendMessage(encMsg); } catch (Exception e) { Print.error("Failed to write object when passing downstream", e); } return; } /** * handles a message that is going upstream (client --> server) * * @param encMsg * the encrypted message that is going upstream * @param incomingConnectionNumber * the connection number from the outer layer */ private void handleUpstreamMessage(EncryptedMessageWrapperMessage encMsg, long incomingConnectionNumber) { // the ip/port of and the connection number provided by // the remote downstream system String fulldown = null; // if the message is for a persistent route if (encMsg.usePersistentRoute()) { fulldown = ServerConnectionIdManager.getFullDown(connection, incomingConnectionNumber); // lookup a pseudo-id to forward to a remote upstream system Long upId = Server.connectionIdManager.getUpstreamId(fulldown); if (upId == null) { // there isn't a connection number associated // with it yet, so create a new number for the route upId = Server.generateConnectionId(); Server.connectionIdManager.add(incomingConnectionNumber, upId, connection); } // out bound connection number is sent as the pseudo // id for the user at this server outboundConnectionNumber = upId; } else { outboundConnectionNumber = (long) 0; } } /** * Sends a message back to the user who requests a key * * @param pkReq */ private void handleKeyRequest(KeyRequest pkReq) { Print.debug("A locally published user is asking for the keys for " + pkReq.getTargetUserName()); KeyResponse pkResp = null; // check if the user is currently online and send their keys if (Server.userNameToIdMap.containsKey(pkReq.getTargetUserName()) && Server.userNameToIdMap.get(pkReq.getTargetUserName()) != null) { PublicIdentity targetUserIdentity = Server.userNameToIdMap .get(pkReq.getTargetUserName()); pkResp = new KeyResponse(targetUserIdentity); Print.debug("*******************************"); Print.debug(targetUserIdentity.getPublicRSAKey().toString()); Print.debug("*******************************"); } else { // Target user not found online, send an empty response Print.debug("User is not online: " + pkReq.getTargetUserName()); pkResp = new KeyResponse(pkReq.getTargetUserName()); } try { sendMessageToPublishedUser(pkResp, pkReq.getSrcUserName()); Print.debug("Key Response is sent back. Target UserName is " + pkReq.getTargetUserName()); } catch (SendMessageToPublishedUserException e) { Print.error("Could not send message to published user", e); } } /** * A message sharing an AES key * * @param unwrappedMessage * an AES key message * @throws NoSuchAlgorithmException * @throws NoSuchPaddingException */ private void handleAESkeyMessage(AESkeyMessage unwrappedMessage, String fulldown) throws NoSuchAlgorithmException, NoSuchPaddingException { Print.received(serverName, "recieved AES KEY"); Server.connectionIdManager.setAESKeyForRoute(fulldown, unwrappedMessage.sharedAESKey); } /** * A server creating a new connection * * @param unwrappedMessage */ private void handleServerAnnounceMessage( ServerAnnounceMessage unwrappedMessage) { Print.received(serverName, "received SERVER ANNOUNCE MESSAGE from " + unwrappedMessage.getName()); } /** * Handles messages that are encrypted and still need to be forwarded * * @param unwrappedMessage * The message that has already been decrypted at this server */ private void handleEncryptedMessageWrapperMessage( EncryptedMessageWrapperMessage unwrappedMessage, Long incomingConnectionNumber) { Print.received(serverName, "ENCRYPTED WRAPPER MESSAGE"); try { Connection o = getConnection(unwrappedMessage.getNextHop()); unwrappedMessage.setConnectionNumber(this.outboundConnectionNumber); o.sendMessage(unwrappedMessage); } catch (Exception e) { Print.error("Error occured while forwarding encrypted message to: " + unwrappedMessage.getNextHop(), e); } } /** * * @param destinationName * the destination with which to make a connection * @return OutConnection an out-bound connection to the destination * @throws ServerToServerConnectionException */ private Connection getConnection(String destinationName) throws ServerToServerConnectionException { Connection newCon = null; if (!Server.currentConnections.containsKey(destinationName)) { try { ServerEntry dest = availableServers.getByName(destinationName); // create new server to server connection newCon = new Connection(dest, this.serverName); // Socket s2sSocket = new Socket( dest.serverIP, dest.serverPort // ); ServerAnnounceMessage me = new ServerAnnounceMessage(serverName); // con = new OutConnection( s2sSocket, dest.serverName ); // ObjectOutputStream out2 = con.getOutputStream(); // Write announce message to server try { EncryptedMessageWrapperMessage enc = new EncryptedMessageWrapperMessage( availableServers.getByName(destinationName) .getAsymmetricCipherEngine(), me, Constants.ASYMMETRIC_ENCRYPTION); Print.sending(serverName, "Sending wrapped server announce message"); Print.debug((Message) enc); newCon.getOutputStream().writeObject(enc); newCon.getOutputStream().flush(); // out2.writeObject( enc ); // out2.flush(); } catch (IOException e1) { throw new Exception( "Error encountered while sending announce message to server: " + destinationName); } Server.currentConnections.put(dest.serverName, newCon); // Create a way to handle objects coming in on the new // connection InConnectionThread newInConnection = new InConnectionThread( newCon, server); newInConnection.start(); } catch (Exception e) { Print.error("Unable to create new connection to server " + destinationName, e); throw new ServerToServerConnectionException( "Unable to connect to server " + destinationName); } } // end creation of new connection // verify the connection to the destination was created if (Server.currentConnections.containsKey(destinationName)) return Server.currentConnections.get(destinationName); else throw new ServerToServerConnectionException( "A connection could not be created to " + destinationName); } /** * * @param message * a chat message */ private void handleRSAEncryptedMessage(RSAEncryptedMessage message) { // check if destination is local or another server Print.received(serverName, "received RSAEncryptedMessage"); // extract the destination user String dest = null; if (message.getDstUserName() != null) { dest = message.getDstUserName(); } else { Print.error("Error in InConnectionThread: unable to handle text message because destination user is null."); } try { String hostingServer = Server.usernameToHostingServer.get(dest); if (hostingServer == null) throw new Exception("Unable to find user's publication server."); if (hostingServer.compareTo(this.serverName) == 0) // Recipient also published here { // Connections contains links from username/unique server number // to tcp connection Print.sending(serverName, "Send the message to the destination socket"); sendMessageToPublishedUser(message, dest); } else { // We need to send the message to the server which is // "hosting" the chatroom or user name Print.debug("The user '" + dest + "' isn't published here, they are at " + hostingServer); getConnection(hostingServer).sendMessage(message); } } catch (Exception e) { Print.error( "Error handling text message: " + e.getLocalizedMessage(), e); } } /** * send a message to a user published at this publication server * * @param message * the message to send to a locally published user * @param dstUser * the user to send the message to * @throws SendMessageToPublishedUserException */ private void sendMessageToPublishedUser(Message message, String dstUser) throws SendMessageToPublishedUserException { Print.debug("Sending a message to a locally published user"); String fullreturnId = Server.getConnectionIdFor(dstUser); Long returnId = Server.connectionIdManager .getDownStreamId(fullreturnId); Cipher enc; try { enc = Cipher.getInstance(Constants.SYMMETRIC_CIPHER_TYPE); enc.init(Cipher.ENCRYPT_MODE, Server.connectionIdManager.getAESKeyForRoute(fullreturnId)); EncryptedMessageWrapperMessage encMsg = new EncryptedMessageWrapperMessage( enc, message, Constants.SYMMETRIC_ENCRYPTION); encMsg.setDirection(Constants.DOWNSTREAM); encMsg.setDownId(returnId); encMsg.setConnectionNumber(returnId); Connection temp = Server.connectionIdManager .getOutChannel(fullreturnId); Print.sending("This server", encMsg.getAllContents()); temp.sendMessage(encMsg); // was message } catch (NoSuchAlgorithmException e) { throw (new SendMessageToPublishedUserException( "NoSuchAlgorithmException")); } catch (NoSuchPaddingException e) { throw (new SendMessageToPublishedUserException( "NoSuchPaddingException")); } catch (InvalidKeyException e) { throw (new SendMessageToPublishedUserException( "InvalidKeyException")); } catch (IOException e) { throw (new SendMessageToPublishedUserException("IOException")); } catch (IllegalBlockSizeException e) { throw (new SendMessageToPublishedUserException( "IllegalBlockSizeException")); } catch (BadPaddingException e) { throw (new SendMessageToPublishedUserException( "BadPaddingException")); } } /** * Send a message from this server to another * * @param msg * @param destination */ public void serverSendMessage(Serializable msg, String destination) { try { EncryptedMessageWrapperMessage enc = new EncryptedMessageWrapperMessage( availableServers.getByName(destination) .getAsymmetricCipherEngine(), msg, Constants.ASYMMETRIC_ENCRYPTION); // Set number expected by the other server // enc.setConnectionNumber( this.outboundConnectionNumber ); getConnection(destination).sendMessage(enc); } catch (Exception e) { Print.error( "Error encountered when sending server->server message " + serverName + " -> " + destination, e); } } /** * Log user into system, and broadcast to all other servers where user is * hosted (Of course only after verifying the message) * * @param login */ private void handleUserLoginRequest(UserLoginRequest login, Long returnId) { Print.received(serverName, "USER LOGIN REQUEST MESSAGE"); PublicIdentity pubId = login.getPubIdent(); String uid = PublicIdentity.composeUserName(pubId.getPublicRSAKey(), pubId.getVerKey()); if (this.verifyIntegrityOfLogin(login)) { // UserLoginAnnounce msg = new UserLoginAnnounce( login ); // Add user keys to mapping of their name Long time = login.getAnnounceTime(); Server.userNameToIdMap.put(uid, pubId); Server.locallyPublishedUsers.add(uid); Server.usernameToHostingServer.put(login.getSrcUserName(), login.getPublicationServer()); Print.debug("User added to locally published list: " + uid); String fullretId = null; fullretId = ServerConnectionIdManager.getFullDown(connection, returnId); Server.addUserConnectionId(uid, fullretId); Long latest = Server.userNameToLastHeardFrom.get(uid); if (latest != null) { if (time > latest) Server.userNameToLastHeardFrom.put(uid, time); } else Server.userNameToLastHeardFrom.put(uid, time); // Broadcast change to everyone for (ServerEntry server : availableServers.servers) { if (!server.serverName.equalsIgnoreCase(this.server .getServerName())) { try { serverSendMessage(login, server.serverName); } catch (Exception e) { Print.error("Cannot send to " + server.serverName, e); } } } } else { Print.error("Failed login attempt"); } } /** * Log user out of system, remove from list, and broadcast to all servers * (Of course only if the message is verified) * * @param unwrappedMessage */ private void handleUserLogoutRequest(UserLogoutRequest unwrappedMessage) { Print.received(serverName, "USER LOGOUT REQUEST MESSAGE"); // remove user from list Server.userNameToIdMap.remove(unwrappedMessage.getSrcUserName()); if (Server.locallyPublishedUsers.remove(unwrappedMessage .getSrcUserName())) { for (ServerEntry server : availableServers.servers) { try { serverSendMessage(unwrappedMessage, server.serverName); } catch (Exception e) { Print.error("Could not send message to " + server.serverName, e); } } } else { Server.usernameToHostingServer.remove(unwrappedMessage .getSrcUserName()); } } /** * Verify that the message was signed by the user that logged in and update * list * * @param publish * the message generated by the user */ private void handlePublishedUserMessage(UserLoginRequest req) { Print.received(serverName, "Publish notice for user " + req.getSrcUserName() + " at " + req.getPublicationServer()); if (this.verifyIntegrityOfLogin(req)) { Server.usernameToHostingServer.put(req.getSrcUserName(), req.getPublicationServer()); Server.userNameToIdMap.put(req.getSrcUserName(), req.getPubIdent()); } else { Print.error("Failed to verify published user message"); } } /** * Verify the user id and the signature are correct for the login message * * @param login * message to verify * @return true if the message is verified false if the message is not. */ private boolean verifyIntegrityOfLogin(UserLoginRequest login) { boolean verified = false; PublicIdentity pubId = login.getPubIdent(); String uid = PublicIdentity.composeUserName(pubId.getPublicRSAKey(), pubId.getVerKey()); if (login.getSrcUserName().equals(uid)) { if (SecurityUtils.ver(login.getSignedComponent(), login.getSig(), pubId.getVerKey())) { verified = true; } else { // Verification failed for the login request, because the // signature is incorrect. LocalFileOps .appendAuditFile("Verification failed for user login."); Print.error("@Server: " + this.serverName + " Verification failed for login of user '" + uid + "', the signature could not be verified."); } } else { // Failed to login because the user name trying to login didn't // match the one computed Print.error("@Server: " + this.serverName + " Verification failed for login of user '" + uid + "', because the keys provided don't belong to that user."); Print.error("Verification failed for user login."); } return verified; } }
Java
package anonymouschat.service; import org.eclipse.swt.SWT; import org.eclipse.swt.custom.StyledText; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import anonymouschat.utils.Print; /** * A GUI created by Eclipse's Visual Editor that facilitates understanding the * server state * */ public class ServerGUI extends Thread { /** * Create a new Server GUI with a handle to the server running it * * @param s */ public ServerGUI(Server s) { serverHandle = s; } // a handle to the server that creates this gui private Server serverHandle = null; private Shell sShell = null; // @jve:decl-index=0:visual-constraint="10,10" private StyledText publishedUsers_styledText = null; private StyledText onlineUsers_styledText = null; private StyledText existingConnections_styledText = null; private Label publishedUsers_label = null; private Label OnlineUsers_label = null; private Label existingConnections_label = null; private Label alerts_label = null; private Text alerts_textArea = null; /** * check if any of the boxes have changes */ private void redraw() { String prev = null; String next = null; prev = this.onlineUsers_styledText.getText(); next = serverHandle.getOnlineUsers(); try { if (!prev.equalsIgnoreCase(next.trim())) { this.onlineUsers_styledText.setText(next); this.onlineUsers_styledText.redraw(); } } catch (Exception e) { Print.error("Error updating online users", e); } prev = this.publishedUsers_styledText.getText().trim().toLowerCase(); next = serverHandle.getPublishedUsers(); try { if (!prev.equalsIgnoreCase(next.trim())) { this.publishedUsers_styledText.setText(next); this.publishedUsers_styledText.redraw(); } } catch (Exception e) { Print.error("Error updating locally published users", e); } prev = this.existingConnections_styledText.getText().trim() .toLowerCase(); next = Server.getAllConnections(); try { if (!prev.equalsIgnoreCase(next.trim())) { this.existingConnections_styledText.setText(next); this.existingConnections_styledText.redraw(); } } catch (Exception e) { Print.error("Error updating connection information"); } next = Server.getNewAlerts(); if (next != null) { this.alerts_textArea.append(next); this.alerts_textArea.redraw(); } } /** * This method initializes sShell */ private void createSShell() { sShell = new Shell(); sShell.setText("Server " + serverHandle.getServerName() + " GUI"); sShell.setLayout(null); sShell.setSize(new Point(673, 652)); publishedUsers_styledText = new StyledText(sShell, SWT.H_SCROLL | SWT.FULL_SELECTION | SWT.READ_ONLY); publishedUsers_styledText.setText("Published Users"); publishedUsers_styledText.setDoubleClickEnabled(false); publishedUsers_styledText.setBounds(new Rectangle(5, 27, 317, 318)); onlineUsers_styledText = new StyledText(sShell, SWT.READ_ONLY | SWT.H_SCROLL | SWT.V_SCROLL | SWT.FULL_SELECTION); onlineUsers_styledText.setText("Online Users"); onlineUsers_styledText.setDoubleClickEnabled(false); onlineUsers_styledText.setBounds(new Rectangle(329, 27, 317, 318)); existingConnections_styledText = new StyledText(sShell, SWT.V_SCROLL | SWT.H_SCROLL | SWT.READ_ONLY | SWT.FULL_SELECTION); existingConnections_styledText.setText("Existing Connections"); existingConnections_styledText.setDoubleClickEnabled(false); existingConnections_styledText .setBounds(new Rectangle(5, 369, 641, 79)); publishedUsers_label = new Label(sShell, SWT.NONE); publishedUsers_label.setBounds(new Rectangle(5, 2, 161, 20)); publishedUsers_label.setText("Locally Published Users"); OnlineUsers_label = new Label(sShell, SWT.NONE); OnlineUsers_label.setBounds(new Rectangle(329, 2, 92, 20)); OnlineUsers_label.setText("Online Users"); existingConnections_label = new Label(sShell, SWT.NONE); existingConnections_label.setBounds(new Rectangle(5, 347, 159, 20)); existingConnections_label.setText("Existing Connections"); existingConnections_label.setBounds(new Rectangle(5, 347, 151, 20)); existingConnections_label.setText("Existing Routes"); alerts_label = new Label(sShell, SWT.NONE); alerts_label.setBounds(new Rectangle(5, 452, 95, 20)); alerts_label.setText("Server Alerts"); alerts_textArea = new Text(sShell, SWT.MULTI | SWT.WRAP | SWT.V_SCROLL); alerts_textArea.setBounds(new Rectangle(8, 478, 641, 124)); } @Override public void run() { Display display = Display.getDefault(); this.createSShell(); this.sShell.open(); while (!this.sShell.isDisposed()) { this.redraw(); if (!display.readAndDispatch()) display.sleep(); } display.dispose(); serverHandle.setShutDown(true); System.exit(0); } public void addAlert(String alertMessage) { this.alerts_textArea.append(alertMessage); } }
Java
package anonymouschat.client; import java.io.Serializable; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.security.PublicKey; import anonymouschat.utils.Print; /** * Contains all the information to be distributed to the servers, and other users that wish * to communicate with a particular user * <br/> * <br/> * Static Methods:<br/> * composeUserName -- Used to see what user name is associated with two keys given */ public class PublicIdentity implements Serializable { private static final long serialVersionUID = 8577187468621789457L; private PublicKey publicRSAKey; // Key used to encrypt messages to the user private PublicKey verKey; //Key used to verify messages came from the user. private String userName; //User name = SHA-256_Hash(encKey || verKey) public PublicIdentity(Identity ident) { setPublicRSAKey(ident.getPublicRSAKey()); setVerKey(ident.getVerKey()); setUserName(ident.getUserName()); } private void setPublicRSAKey(PublicKey myPublicRSAKey) { this.publicRSAKey = myPublicRSAKey; } public PublicKey getPublicRSAKey() { return publicRSAKey; } private void setVerKey(PublicKey myVerKey) { this.verKey = myVerKey; } public PublicKey getVerKey() { return verKey; } private void setUserName(String myName) { this.userName = myName; } public String getUserName() { return userName; } /** * Generates the user's id string by composing the encKey and the verKey, then taking the hash * of the result. * @return * User's id string */ public static String composeUserName(PublicKey encKey,PublicKey verKey) { // hash sha 256 MessageDigest md; String userNameString = null; try { md = MessageDigest.getInstance("SHA-256"); byte[] pubKey = encKey.getEncoded(); byte[] vKey = verKey.getEncoded(); byte[] userKey = new byte[pubKey.length + vKey.length]; System.arraycopy(pubKey, 0, userKey, 0, pubKey.length); System.arraycopy(vKey, 0, userKey, pubKey.length, vKey.length); md.update(userKey); byte[] userID = md.digest(); StringBuffer sb = new StringBuffer(); for (int i = 0; i < userID.length; i++) { sb.append(Integer.toString(userID[i])); } userNameString = sb.toString(); Print.debug( "UserId is " + userNameString ); } catch( NoSuchAlgorithmException e ) { Print.error( "Failed to compose username",e ); } return userNameString; } }
Java
package anonymouschat.client.network; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.net.Socket; import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import javax.crypto.BadPaddingException; import javax.crypto.Cipher; import javax.crypto.IllegalBlockSizeException; import javax.crypto.NoSuchPaddingException; import javax.swing.JOptionPane; import anonymouschat.client.Client; import anonymouschat.client.PublicIdentity; import anonymouschat.messages.EncryptedMessageWrapperMessage; import anonymouschat.messages.KeyResponse; import anonymouschat.messages.securitymessages.RSAEncryptedMessage; import anonymouschat.utils.Constants; import anonymouschat.utils.LocalFileOps; import anonymouschat.utils.Print; /** * This thread receives incoming messages. * * @author bh349 * */ public class ClientInConnectionThread extends Thread { // Socket connected to the initial server for the clients route. private Socket incomingSocket; // Client this tread is processing incoming data for private Client client; ObjectInputStream in = null; ObjectOutputStream out = null; // needed to write the initial // AnnoinceMessage to server public ClientInConnectionThread( Client client, Socket clientSocket ) { this.client = client; this.incomingSocket = clientSocket; } /** * Wait for out to be created and then return it. This method exists because * we can't use a socket's output stream to create a object output stream * more than once * * @return * @throws Exception */ public ObjectOutputStream getOutputStream() throws Exception { int i=0; while( this.out == null ) { try { if (i > 500) throw new Exception("Could not establish output connection to initial server"); Thread.sleep( 20 ); i++; } catch( InterruptedException e ) { Print.error( "Error sleeping", e ); } } return out; } @Override public void run() { try { out = new ObjectOutputStream(incomingSocket.getOutputStream()); } catch (IOException e1) { Print.error("Error creating ObjectOutputStream", e1); } Object receivedMessage = null; boolean openSocket = true; try { in = new ObjectInputStream(incomingSocket.getInputStream()); } catch (IOException e1) { Print.error("Error creating ObjectInputStream", e1); } while (openSocket == true) { try { receivedMessage = in.readObject(); Print.debug( "Received a new message: " + receivedMessage.toString() ); if (receivedMessage instanceof EncryptedMessageWrapperMessage) { EncryptedMessageWrapperMessage encMsg = (EncryptedMessageWrapperMessage) receivedMessage; Object obj = null; for (int i = 0; i < Client.serverChain.size(); i++) { Print.debug( "Removing layer of encryption: " + i ); Cipher dec = Cipher .getInstance(Constants.SYMMETRIC_CIPHER_TYPE); dec.init(Cipher.DECRYPT_MODE, Client.serverChain.get(i) .getSymmetricKey(), encMsg.getIV()); ByteArrayInputStream bis = new ByteArrayInputStream( dec.doFinal(encMsg.getencryptedMessage())); ObjectInputStream is = new ObjectInputStream(bis); obj = is.readObject(); if (obj instanceof EncryptedMessageWrapperMessage) { encMsg = (EncryptedMessageWrapperMessage) obj; } else if(obj instanceof KeyResponse) { break; //done unwrapping } else if(obj instanceof RSAEncryptedMessage){ break; //done unwrapping } else { LocalFileOps.appendAuditFile("When decrypting EncryptedMessageWrapperMessage, got unexpected type of object" + obj.toString()); Print.error("When decrypting EncryptedMessageWrapperMessage, got unexpected type of object" + obj.toString()); } } if (obj instanceof KeyResponse) { // message type is key response KeyResponse pkResp = (KeyResponse) obj; if (pkResp.getPublicIdentity() == null) { // target identity not found. client.getPublicIdentityMap().put( pkResp.getUserName(), null); } else { String userNameString = PublicIdentity .composeUserName(pkResp.getPublicIdentity() .getPublicRSAKey(), pkResp .getPublicIdentity().getVerKey()); if (userNameString.equals(pkResp.getUserName())) { // correctly verified username. Print.debug("correctly verified username, get the publicIdentity of "+ pkResp.getUserName()); client.getPublicIdentityMap().put( pkResp.getUserName(), pkResp.getPublicIdentity()); } else { // user name doesn't match the identity. Print.error("The key response contains bad identity"); client.getPublicIdentityMap().put( pkResp.getUserName(), null); } } } else if (obj instanceof RSAEncryptedMessage) { //received encrypted text message Print.debug("RSAEncryptedMessage:"); Print.debug(new String(((RSAEncryptedMessage) obj).getEncryptedData())); client.handleRSAEncryptedMessage((RSAEncryptedMessage) obj); } } } catch (ClassNotFoundException e) { Print.error("Error reading an object", e, null); } catch (IOException ioe) { Print.error("IOError reading an object"); openSocket = false; // Socket Closed, die gracefully JOptionPane.showMessageDialog( null, "Your initialization server died. I am sorry but byebye...", "Error", JOptionPane.ERROR_MESSAGE ); System.exit(0); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (NoSuchPaddingException e) { e.printStackTrace(); } catch (InvalidKeyException e) { e.printStackTrace(); } catch (IllegalBlockSizeException e) { e.printStackTrace(); } catch (BadPaddingException e) { e.printStackTrace(); } catch (InvalidAlgorithmParameterException e) { e.printStackTrace(); } }// END-WHILE try { if (in != null) in.close(); if (incomingSocket != null) incomingSocket.close(); } catch (IOException e) { Print.error("Error closing sockets", e); } } }
Java
package anonymouschat.client.frames; import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.GridLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.awt.event.WindowListener; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import anonymouschat.client.Client; import anonymouschat.client.NickNameList; import anonymouschat.exceptions.DecryptionException; import anonymouschat.messages.TextMessage; import anonymouschat.messages.clientrequests.UserLogoutRequest; import anonymouschat.utils.LocalFileOps; import anonymouschat.utils.Print; /** * Frame which contains a list of users and their nicknames Allows for adding * and deleting of users and nicknames * * @author Winters * */ public class NickListFrame extends JFrame implements ActionListener, DocumentListener, WindowListener { private static final long serialVersionUID = 1L; private Client client; private JPanel textPanel; private JPanel buttonPanel; private JPanel userIDPanel; private JPanel nickNamePanel; private JPanel sendMsgPanel; private JPanel showHistoryPanel; private JPanel deletePanel; private NickNameList nickList; private JLabel userIDLabel = new JLabel("UserID:"); private JLabel nickNameLabel = new JLabel("Nick Name:"); private JButton[] sendMsgButton; private JButton[] showHistoryButton; private JButton[] deleteButton; private JButton addButton; private JLabel pathLabel; private JTextField[] nickText; private JTextField[] idText; private List<JTextField> userIDList; private List<JTextField> nickNameList; private List<JButton> sendMsgButtonList; private List<JButton> showHistoryButtonList; private List<JButton> deleteButtonList; private static final int HEIGHT = 35; private HashMap<String, ArrayList<String>> tempChatLog; private HashMap<String, OneOnOneChatFrame> oneOnOneChatList; /** * Create NickListFrame UI * * @param userID * - the userid running the client app * @param nickList * - if null, creates a new list * @throws DecryptionException * @throws ClassNotFoundException * @throws IOException */ public NickListFrame(Client client) throws DecryptionException { this.client = client; this.tempChatLog = new HashMap<String, ArrayList<String>>(); readNickList(); initComponents(); } private void initComponents() { setTitle("Friends of : " + client.getIdentity().getUserName()); setLocation(0, 0); setVisible(true); setResizable(false); setLayout(new BorderLayout()); textPanel = new JPanel(); textPanel.setLayout(new GridLayout(1, 2, 0, 0)); buttonPanel = new JPanel(); buttonPanel.setLayout(new GridLayout(1, 3, 0, 0)); setIDPanel(); // userID Panel setNickNamePanel();// nickName Panel setSendMsgPanel(); // sendMsg Panel setShowHistPanel(); // showHistory Panel setDelPanel(); // deleting Panel pathLabel = new JLabel("Routing Path: " + this.client.getPath()); pathLabel.setPreferredSize(new Dimension(300, 15)); addButton = new JButton("Add"); addButton.setPreferredSize(new Dimension(300, HEIGHT)); addButton.addActionListener(this); textPanel.add(userIDPanel); textPanel.add(nickNamePanel); buttonPanel.add(sendMsgPanel); buttonPanel.add(showHistoryPanel); buttonPanel.add(deletePanel); textPanel.setPreferredSize(new Dimension(300, HEIGHT * (nickList.getNickNameList().size() + 1))); buttonPanel.setPreferredSize(new Dimension(300, HEIGHT * (nickList.getNickNameList().size() + 1))); getContentPane().add(pathLabel, BorderLayout.NORTH); getContentPane().add(textPanel, BorderLayout.WEST); getContentPane().add(buttonPanel, BorderLayout.EAST); getContentPane().add(addButton, BorderLayout.SOUTH); pack(); validate(); addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { saveNickList(); dumpChatLog(); leaveSystem(); } private void saveNickList() { try { LocalFileOps.writeNickList(client.getIdentity(), nickList); } catch (IOException e) { Print.error("Cannot save nickList.", e); } } }); } /** * show chat messages that clientInConnectionThread receives. save the * message in temporary chat record. * * @author Winters * @param msg */ public void showTextMessage(TextMessage msg) { String userID = msg.getSrcUser(); OneOnOneChatFrame tempOneOnOneChatFrame; if (oneOnOneChatList == null) { oneOnOneChatList = new HashMap<String, OneOnOneChatFrame>(); } if (oneOnOneChatList.containsKey(userID) == true) // existing tempOneOnOneChatFrame = oneOnOneChatList.get(userID); else { tempOneOnOneChatFrame = new OneOnOneChatFrame(client, client.getIdentity(), msg.getSrcUser(), tempChatLog, oneOnOneChatList); oneOnOneChatList.put(userID, tempOneOnOneChatFrame); } String tempData = msg.getSrcUser() + "\n" + new Date() + "\n" + msg.getPlaintextData() + "\n\n"; String nickName = this.nickList.getNickNameFor(msg.getSrcUser()); if (nickName == null) { tempData = msg.getSrcUser() + tempData; } else { tempData = nickName + tempData; } tempOneOnOneChatFrame.textArea.append(tempData); if (tempChatLog.containsKey(userID)) { tempChatLog.get(userID).add(tempData); } else { tempChatLog.put(userID, new ArrayList<String>()); tempChatLog.get(userID).add(tempData); } } /** * Tell the publication server that the user is leaving */ protected void leaveSystem() { UserLogoutRequest msg = new UserLogoutRequest(client.getIdentity()); try { Print.debug(client.getIdentity().getUserName() + "is about to send Logoff message"); client.sendMessage(msg); client.getOutputStream().flush(); client.getOutputStream().close(); } catch (IOException e1) { Print.error( "Error occured when sending UserLeaveRequest object to server", e1); } Print.debug("Exiting. . ."); System.exit(0); } /** * Save tempChatLog to file. * * @throws IOException */ public void dumpChatLog() { for (Map.Entry<String, ArrayList<String>> entry : tempChatLog .entrySet()) { String dstUserName = entry.getKey(); ArrayList<String> msgList = entry.getValue(); StringBuffer sb = new StringBuffer(); for (String s : msgList) { sb.append(s); } try { LocalFileOps.appendChatHist(client.getIdentity(), dstUserName, sb.toString()); } catch (ClassNotFoundException e) { Print.error("Error appending to local chat history", e); } } tempChatLog.clear(); } /** * Read the nick name list saved on disk * @throws DecryptionException */ private void readNickList() throws DecryptionException { nickList = LocalFileOps.getNickList(client.getIdentity()); if (nickList == null) { nickList = new NickNameList(); } } private void setDelPanel() { deletePanel = new JPanel(); deletePanel.setLayout(new GridLayout(0, 1, 0, 0)); deletePanel.add(new JLabel("")); List<String> tempList = nickList.getNickNameList(); deleteButton = new JButton[tempList.size()]; deleteButtonList = new ArrayList<JButton>(); for (int i = 0; i < tempList.size(); i++) { deleteButton[i] = new JButton("Delete"); deleteButton[i].addActionListener(this); deleteButtonList.add(deleteButton[i]); deletePanel.add(deleteButton[i]); } } private void setShowHistPanel() { showHistoryPanel = new JPanel(); showHistoryPanel.setLayout(new GridLayout(0, 1, 0, 0)); showHistoryPanel.add(new JLabel("")); List<String> tempList = nickList.getNickNameList(); showHistoryButton = new JButton[tempList.size()]; showHistoryButtonList = new ArrayList<JButton>(); for (int i = 0; i < tempList.size(); i++) { showHistoryButton[i] = new JButton("History"); showHistoryButton[i].addActionListener(this); showHistoryButtonList.add(showHistoryButton[i]); showHistoryPanel.add(showHistoryButton[i]); } } private void setSendMsgPanel() { sendMsgPanel = new JPanel(); sendMsgPanel.setLayout(new GridLayout(0, 1, 0, 0)); sendMsgPanel.add(new JLabel("")); List<String> tempList = nickList.getNickNameList(); sendMsgButton = new JButton[tempList.size()]; sendMsgButtonList = new ArrayList<JButton>(); for (int i = 0; i < tempList.size(); i++) { sendMsgButton[i] = new JButton("Message"); sendMsgButton[i].addActionListener(this); sendMsgButtonList.add(sendMsgButton[i]); sendMsgPanel.add(sendMsgButton[i]); } } private void setNickNamePanel() { nickNamePanel = new JPanel(); nickNamePanel.setLayout(new GridLayout(0, 1, 0, 0)); nickNamePanel.add(nickNameLabel); List<String> tempList = nickList.getNickNameList(); nickText = new JTextField[tempList.size()]; nickNameList = new ArrayList<JTextField>(); for (int i = 0; i < tempList.size(); i++) { nickText[i] = new JTextField(); nickText[i].setText(tempList.get(i).toString()); nickText[i].addActionListener(this); nickText[i].getDocument().addDocumentListener(this); nickNameList.add(nickText[i]); nickNamePanel.add(nickText[i]); } } private void setIDPanel() { userIDPanel = new JPanel(); userIDPanel.setLayout(new GridLayout(0, 1, 0, 0)); userIDPanel.add(userIDLabel); List<String> tempList = nickList.getUserIDList(); idText = new JTextField[tempList.size()]; userIDList = new ArrayList<JTextField>(); for (int i = 0; i < tempList.size(); i++) { idText[i] = new JTextField(); idText[i].setText(tempList.get(i).toString()); idText[i].addActionListener(this); idText[i].getDocument().addDocumentListener(this); userIDList.add(idText[i]); userIDPanel.add(idText[i]); } } /** * show some txt on the user's oneOnOneChatWindow * * @param userID * @param msg */ public void showTxtOnUserWindow(String userID, String msg) { OneOnOneChatFrame tempOneOnOneChatFrame; if (oneOnOneChatList == null) { oneOnOneChatList = new HashMap<String, OneOnOneChatFrame>(); } if (oneOnOneChatList.containsKey(userID) == true) { tempOneOnOneChatFrame = oneOnOneChatList.get(userID); } else { tempOneOnOneChatFrame = new OneOnOneChatFrame(client, client.getIdentity(), userID, tempChatLog, oneOnOneChatList); oneOnOneChatList.put(userID, tempOneOnOneChatFrame); } tempOneOnOneChatFrame.showMsgInWindow(msg); } @Override public void actionPerformed(ActionEvent e) { int i = -1; if (e.getSource() == addButton) { // if click on add button nickList.getUserIDList().add(""); nickList.getNickNameList().add(""); JTextField tempTextField = new JTextField(); tempTextField.getDocument().addDocumentListener(this); userIDList.add(tempTextField); userIDPanel.add(tempTextField); tempTextField = new JTextField(); tempTextField.getDocument().addDocumentListener(this); nickNameList.add(tempTextField); nickNamePanel.add(tempTextField); JButton tempButton = new JButton("Delete"); tempButton.addActionListener(this); deleteButtonList.add(tempButton); deletePanel.add(tempButton); tempButton = new JButton("Message"); tempButton.addActionListener(this); sendMsgButtonList.add(tempButton); sendMsgPanel.add(tempButton); tempButton = new JButton("History"); tempButton.addActionListener(this); showHistoryButtonList.add(tempButton); showHistoryPanel.add(tempButton); textPanel.setPreferredSize(new Dimension(300, HEIGHT * (nickList.getNickNameList().size() + 1))); buttonPanel.setPreferredSize(new Dimension(300, HEIGHT * (nickList.getNickNameList().size() + 1))); Print.debug("nickList size: " + nickList.getNickNameList().size()); pack(); validate(); } else { i = deleteButtonList.indexOf(e.getSource()); if (i != -1) { // if click on delete button nickList.getNickNameList().remove(i); nickList.getUserIDList().remove(i); userIDPanel.remove(userIDList.get(i)); nickNamePanel.remove(nickNameList.get(i)); sendMsgPanel.remove(sendMsgButtonList.get(i)); showHistoryPanel.remove(showHistoryButtonList.get(i)); deletePanel.remove(deleteButtonList.get(i)); userIDList.remove(i); nickNameList.remove(i); sendMsgButtonList.remove(i); showHistoryButtonList.remove(i); deleteButtonList.remove(i); textPanel.setPreferredSize(new Dimension(300, HEIGHT * (nickList.getNickNameList().size() + 1))); buttonPanel.setPreferredSize(new Dimension(300, HEIGHT * (nickList.getNickNameList().size() + 1))); Print.debug("nickList size: " + nickList.getNickNameList().size()); pack(); validate(); return; } i = sendMsgButtonList.indexOf(e.getSource()); if (i != -1) { // if click on send message button String dst = userIDList.get(i).getText(); // open one on one OneOnOneChatFrame tempOneOnOneChatFrame; if (oneOnOneChatList == null) { oneOnOneChatList = new HashMap<String, OneOnOneChatFrame>(); } if (oneOnOneChatList.containsKey(dst) == true) { tempOneOnOneChatFrame = oneOnOneChatList.get(dst); } else { tempOneOnOneChatFrame = new OneOnOneChatFrame(client, client.getIdentity(), dst, tempChatLog, oneOnOneChatList); oneOnOneChatList.put(dst, tempOneOnOneChatFrame); } return; } i = showHistoryButtonList.indexOf(e.getSource()); if (i != -1) { // if click on show history button try { new LogFrame(client.getIdentity(), userIDList.get(i) .getText()); } catch (ClassNotFoundException e1) { Print.error("Error creating LogFrame", e1); } catch (IOException e1) { Print.error("IOexception creating LogFrame", e1); } return; } } } @Override public void changedUpdate(DocumentEvent e) { textChangeDetectioner(e); } @Override public void insertUpdate(DocumentEvent e) { textChangeDetectioner(e); } @Override public void removeUpdate(DocumentEvent e) { textChangeDetectioner(e); } private void textChangeDetectioner(DocumentEvent e) { for (int i = 0; i < nickList.getNickNameList().size(); i++) { if (e.getDocument().equals(userIDList.get(i).getDocument())) { nickList.getUserIDList().set(i, userIDList.get(i).getText()); } else { if (e.getDocument().equals(nickNameList.get(i).getDocument())) { nickList.getNickNameList().set(i, nickNameList.get(i).getText()); } } } } @Override public void windowActivated(WindowEvent arg0) { } @Override public void windowClosed(WindowEvent arg0) { } @Override public void windowClosing(WindowEvent arg0) { try { LocalFileOps.writeNickList(client.getIdentity(), nickList); } catch (IOException e) { Print.error("Error writing NickList", e); } } @Override public void windowDeactivated(WindowEvent arg0) { } @Override public void windowDeiconified(WindowEvent arg0) { } @Override public void windowIconified(WindowEvent arg0) { } @Override public void windowOpened(WindowEvent arg0) { } public Client getClient() { return this.client; } }
Java
package anonymouschat.client.frames; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.WindowAdapter; import java.awt.event.WindowEvent; import java.io.IOException; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.Map; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTextArea; import anonymouschat.client.Client; import anonymouschat.client.Identity; import anonymouschat.messages.Message; import anonymouschat.messages.TextMessage; import anonymouschat.messages.securitymessages.TextMessageWithSig; import anonymouschat.security.SecurityUtils; import anonymouschat.security.integrity.DigSig; import anonymouschat.utils.LocalFileOps; import anonymouschat.utils.Print; /** * One on one chat frame, only supply two people to chat. ownerUser is the local * client, while targetUser is the user owner is chatting with. * * @author Winters */ public class OneOnOneChatFrame extends JFrame { private static final long serialVersionUID = 1L; private HashMap<String, ArrayList<String>> tempChatLog; HashMap<String, OneOnOneChatFrame> oneOnOneChatList; private Identity ownerIdentity; private String ownerUserID; private String targetUserID; public JTextArea textArea; private JTextArea msgArea; private JScrollPane textScr; private JScrollPane msgScr; private JButton sendButton; private static final int WIDTH = 400; private static final int HEIGHT = 500; private Client client; /** * Constructor by two user names and chatLog, outStream * * @param owner * @param target * @param tempChatLog * @param out * @param oneOnOneChatList */ public OneOnOneChatFrame(Client client, Identity owner, String target, HashMap<String, ArrayList<String>> tempChatLog, HashMap<String, OneOnOneChatFrame> oneOnOneChatList) { this.client = client; this.tempChatLog = tempChatLog; this.oneOnOneChatList = oneOnOneChatList; ownerUserID = owner.getUserName(); targetUserID = target; ownerIdentity = owner; // main frame setTitle("Chatting with " + targetUserID); setSize(WIDTH, HEIGHT); setVisible(true); setResizable(false); getContentPane().setLayout(null); addWindowListener(new WindowAdapter() { @Override public void windowClosing(WindowEvent e) { closingWindow(); dumpChatLog(); } }); // textArea textArea = new JTextArea(); textArea.setEditable(false); textScr = new JScrollPane(textArea); textScr.setSize(WIDTH, HEIGHT - 100); textScr.setLocation(0, 0); // sendMsg msgArea = new JTextArea(); msgScr = new JScrollPane(msgArea); msgScr.setLocation(10, HEIGHT - 90); msgScr.setSize(WIDTH - 130, 50); // sendButton sendButton = new JButton("Send"); sendButton.setLocation(WIDTH - 120, HEIGHT - 90); sendButton.setSize(100, 50); sendButton.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { sendTextMsg(msgArea.getText()); msgArea.setText(""); } }); this.getContentPane().add(textScr); this.getContentPane().add(msgScr); this.getContentPane().add(sendButton); this.validate(); } private void closingWindow() { this.oneOnOneChatList.remove(targetUserID); dispose(); } /** * Save tempChatLog to file. * * @throws IOException */ private void dumpChatLog() { for (Map.Entry<String, ArrayList<String>> entry : tempChatLog .entrySet()) { String dstUserName = entry.getKey(); if (dstUserName.equals(targetUserID)) { ArrayList<String> msgList = entry.getValue(); StringBuffer sb = new StringBuffer(); for (String s : msgList) { sb.append(s); } try { LocalFileOps.appendChatHist(ownerIdentity, dstUserName, sb.toString()); } catch (ClassNotFoundException e) { Print.error("Error appending ChatHist", e); } entry.getValue().clear(); } } } /** * Wrap text message obj with signature, call sendChatMessage. * * @param text */ private void sendTextMsg(String text) { String tempData = "You" + "\n" + new Date() + "\n" + text + "\n\n"; textArea.append(tempData); if (tempChatLog.containsKey(targetUserID)) { tempChatLog.get(targetUserID).add(tempData); } else { tempChatLog.put(targetUserID, new ArrayList<String>()); tempChatLog.get(targetUserID).add(tempData); } TextMessage msg = new TextMessage(ownerUserID, targetUserID, text); DigSig signature = SecurityUtils.sign(msg, this.client.getIdentity() .getSigningKey()); TextMessageWithSig msgWithSig = new TextMessageWithSig(msg, signature); Print.sending(ownerUserID, "Sending Text Message"); Print.debug((Message) msgWithSig); client.sendChatMessage(msgWithSig); } public void showMsgInWindow(String text){ textArea.append("\n" + text + "\n"); } }
Java
package anonymouschat.client.frames; import java.io.IOException; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.JTextArea; import anonymouschat.client.Identity; import anonymouschat.utils.LocalFileOps; /** * Log Frame shows chat log with a specific user. * * @author hb * */ public class LogFrame extends JFrame { private static final long serialVersionUID = 1L; private static final int WIDTH = 500; private static final int HEIGHT = 500; private JTextArea msgArea; private JScrollPane msgScr; private Identity identity; /** * Constructor * * @param dstuserName * target userName * @throws IOException * @throws ClassNotFoundException */ public LogFrame(Identity identity, String dstUserName) throws ClassNotFoundException, IOException { super(); this.identity = identity; initComponents(dstUserName); } /** * Initialize components. * * @param dstUserName * @throws IOException * @throws ClassNotFoundException */ private void initComponents(String dstUserName) throws ClassNotFoundException, IOException { this.msgArea = new JTextArea(); this.msgArea.setText(LocalFileOps.getChatHist(identity, dstUserName)); this.msgArea.setEditable(false); this.msgScr = new JScrollPane(msgArea); this.add(msgScr); this.setSize(WIDTH, HEIGHT); this.setVisible(true); } }
Java
package anonymouschat.client; import java.io.Serializable; import java.util.ArrayList; import java.util.List; /** * NickList obj stores nick name information. Serializable. * * @author hb * */ public class NickNameList implements Serializable { private static final long serialVersionUID = 1L; private List<String> userNameList; private List<String> nickNameList; /** * Default Constructor Construct NickList by local file */ public NickNameList() { userNameList = new ArrayList<String>(); nickNameList = new ArrayList<String>(); } public int size() { if (userNameList.size() == nickNameList.size()) return userNameList.size(); else { return 0; } } public List<String> getNickNameList() { return nickNameList; } public List<String> getUserIDList() { return userNameList; } public String getNickNameFor(String srcUser) { int i = this.userNameList.indexOf(srcUser); if (i < 0) return null; return this.nickNameList.get(i); } }
Java
package anonymouschat.client; import java.io.IOException; import java.io.ObjectOutputStream; import java.net.Socket; import java.security.NoSuchAlgorithmException; import java.util.HashMap; import java.util.LinkedList; import java.util.Map; import javax.crypto.SecretKey; import javax.swing.JOptionPane; import javax.swing.JPasswordField; import javax.swing.JProgressBar; import anonymouschat.client.frames.NickListFrame; import anonymouschat.client.network.ClientInConnectionThread; import anonymouschat.exceptions.DecryptionException; import anonymouschat.messages.AESkeyMessage; import anonymouschat.messages.EncryptedMessageWrapperMessage; import anonymouschat.messages.Message; import anonymouschat.messages.clientrequests.KeyRequest; import anonymouschat.messages.clientrequests.UserLoginRequest; import anonymouschat.messages.securitymessages.RSAEncryptedMessage; import anonymouschat.messages.securitymessages.TextMessageWithSig; import anonymouschat.security.KeySalt; import anonymouschat.security.Keys; import anonymouschat.security.NameSaltPairs; import anonymouschat.security.SecurityUtils; import anonymouschat.service.ServerEntry; import anonymouschat.utils.Constants; import anonymouschat.utils.ListOfServers; import anonymouschat.utils.LocalFileOps; import anonymouschat.utils.Print; /** * Client program. * * @author hb * */ public class Client { // stream to write messages to the initail server in route private ObjectOutputStream out; // connection to initial server (first server in the route) private Socket clientSocket; // Full Identity (Private keys for the user running this client) private Identity identity; // Public keys and user name of the user running this client private PublicIdentity publicIdentity; // GUI for the nick name list private NickListFrame nickListFrame; // substance of the nick name list (pairs of user names to user assigned // nicknames) private NickNameList nickList; private ListOfServers listOfAvailableServers; // map of other clients' public keys private HashMap<String, PublicIdentity> publicIdentityMap; private StringBuffer chain; /** * List of servers used by the client to send/receive messages, first is the * initail server Last is the publication server of this client. Fully set * up when establishing anonymous route */ public static LinkedList<ServerEntry> serverChain = new LinkedList<ServerEntry>(); /** * Starting client * * @throws ClassNotFoundException * @throws IOException * @throws NoSuchAlgorithmException */ public Client() throws ClassNotFoundException, NoSuchAlgorithmException { Print.info("Starting Client. . ."); publicIdentityMap = new HashMap<String, PublicIdentity>(); identity = selectIdentity(); publicIdentity = new PublicIdentity(identity); listOfAvailableServers = new ListOfServers(this); try { establishAnonymousRouting(); } catch (Exception e) { Print.error( "ERROR encountered while trying to establish annonymous routing: " + e.getLocalizedMessage(), e); } sendUserLoginRequest(); } /** * Send the initial login request to a publication server * * @param out * an output stream to write the message */ private void sendUserLoginRequest() { UserLoginRequest req = new UserLoginRequest(getIdentity(), serverChain.getLast().serverName); try { Print.debug(getIdentity().getUserName() + " is about to send a request to login"); sendMessage(req, true); } catch (IOException e) { Print.error("Unable to send UserLoginRequest to server", e); } } /** * when client wants to send a chat message, it check for the client public * key if it does not know it yet, it will request it first then it will * wrap the message and send it * * @param msg */ public void sendChatMessage(TextMessageWithSig msg) { // check for public key // if does not exist, ask for it String otherUser = msg.getTextMessage().getDstUser(); if (!publicIdentityMap.containsKey(otherUser) || publicIdentityMap.get(otherUser) == null) { // need to request keys from the server requestKey(otherUser); } if (waitForKeys(msg)) { if (publicIdentityMap.get(msg.getTextMessage().getDstUser()) == null) { // user is not online nickListFrame.showTxtOnUserWindow(msg.getTextMessage() .getDstUser(), msg.getTextMessage().getDstUser() + " is not online."); Print.debug("user" + msg.getTextMessage().getDstUser() + " is not online."); } else { Print.debug("Get public key of client: " + msg.getTextMessage().getDstUser()); Print.debug(publicIdentityMap.get( msg.getTextMessage().getDstUser()).toString()); PublicIdentity publicIdentity = publicIdentityMap.get(msg .getTextMessage().getDstUser()); if (publicIdentity == null) { // user is not online. Print.debug("user is not online."); return; } // send encrypted message RSAEncryptedMessage emsg = SecurityUtils.encRSA(msg, publicIdentity.getPublicRSAKey(), msg.getTextMessage() .getDstUser(), this.getPublicIdentity()); try { Print.debug(getIdentity().getUserName() + " is about to send an encrypted message to user " + msg.getTextMessage().getDstUser()); sendMessage(emsg); } catch (IOException e) { Print.error("Unable to send encrypted message to server", e); } } } else { nickListFrame .showTxtOnUserWindow(msg.getTextMessage().getDstUser(), "Request public keys for user " + msg.getTextMessage().getDstUser() + " timed out."); Print.error("Cannot find keys. Request for public keys timed out..."); } } /** * wait for keys from the server, or until the request times out. * * @param msg * @return true if we have the keys for the client false if we don't have * the keys after a period of time */ public boolean waitForKeys(TextMessageWithSig msg) { int waitCount = 0; boolean haveKeys = false; int waitLimit = 1000; while (!publicIdentityMap .containsKey(msg.getTextMessage().getDstUser()) && waitCount < waitLimit) { // wait until we get the public keys are returned from the server try { Thread.sleep(100); } catch (InterruptedException e) { Print.error("While waiting for public keys...", e); } waitCount++; } if (waitCount < waitLimit) { // the request did not time out haveKeys = true; } return haveKeys; } /** * Request the public keys for a user * * @param user * User who's keys we want from the server. */ public void requestKey(String user) { KeyRequest reqPK = new KeyRequest(getIdentity().getUserName(), user); try { Print.debug(getIdentity().getUserName() + " is about to send a request for user " + user + "'s public key"); sendMessage(reqPK); } catch (IOException e) { Print.error("Unable to send PublicKeyRequest to server", e); } } private LinkedList<ServerEntry> pickServerChain(ServerEntry avoidAsInitial) throws Exception { ServerEntry randomServer; LinkedList<ServerEntry> chain = new LinkedList<ServerEntry>(); // Choose servers to create chain for (int i = 0; i < Constants.numServerHops; i++) { do randomServer = listOfAvailableServers.getRandomServer(chain); while (i == 0 && randomServer == avoidAsInitial); chain.add(randomServer); } return chain; } /** * /** Gets a list of random servers to use for routing * * @throws Exception */ private void establishAnonymousRouting() throws Exception { Client.serverChain = pickServerChain(null); chain = new StringBuffer(); for (int i = 0; i < Client.serverChain.size(); i++) { chain = chain.append(Client.serverChain.get(i).serverName); if (i != Client.serverChain.size() - 1) chain = chain.append("->"); } Print.info("Server chain: " + chain.toString()); // Establish connection to first server so we can send objects ServerEntry initialServer = Client.serverChain.get(0); clientSocket = new Socket(initialServer.serverIP, initialServer.serverPort); clientSocket.setKeepAlive(true); Print.debug("Connected to server " + initialServer.serverIP + ":" + initialServer.serverPort); ClientInConnectionThread t = new ClientInConnectionThread(this, clientSocket); t.start(); out = t.getOutputStream(); Print.info("Established connection to " + initialServer.serverName); ServerEntry currentServer; // Generate symmetric keys and send to all servers for (int i = 0; i < Constants.numServerHops; i++) { currentServer = Client.serverChain.get(i); AESkeyMessage k = new AESkeyMessage(); k.sharedAESKey = anonymouschat.security.Keys.generateAESkey(); currentServer.setSymmetricKey(k.sharedAESKey); EncryptedMessageWrapperMessage enc = new EncryptedMessageWrapperMessage( listOfAvailableServers.getByName(currentServer.serverName) .getAsymmetricCipherEngine(), k, Constants.ASYMMETRIC_ENCRYPTION); sendMessage(enc, currentServer, true, true); } } /** * Sends the message to the publication server of this client. * * @param msg * message to send * @throws IOException * Thrown if can't write object to stream */ public void sendMessage(Message msg) throws IOException { sendMessage(msg, Client.serverChain.get(Constants.numServerHops - 1), false, true); // Send to the published server } public void sendMessage(Message msg, boolean useReturnChain) throws IOException { sendMessage(msg, Client.serverChain.get(Constants.numServerHops - 1), false, useReturnChain); } /** * Sends message to a destination server in this user's route * * @param msgin * message to send * @param destination * destination server that the message is intended for * @param sendingAESkey * true if sending the server the key we want it to use for onion * wrapping on the way back * @throws IOException */ public void sendMessage(Message msgin, ServerEntry destination, boolean sendingAESkey, boolean useReturnChain) throws IOException { try { LinkedList<ServerEntry> chain; if (useReturnChain) chain = Client.serverChain; else chain = pickServerChain(Client.serverChain.get(0)); Message msg = msgin; String nextHop; boolean destFound = false; ServerEntry server; EncryptedMessageWrapperMessage wrapper; int i = 0; do { nextHop = null; server = chain.get(Constants.numServerHops - i - 1); nextHop = server.serverName;// Client.serverChain.get(i).serverName; if (server == destination) destFound = true; if (destFound) { Print.debug("{}" + server.serverName + " ->" + nextHop); if (!(destination.serverName .equalsIgnoreCase(server.serverName) && sendingAESkey)) { wrapper = new EncryptedMessageWrapperMessage( server.getAsymmetricCipherEngine(), msg, Constants.ASYMMETRIC_ENCRYPTION); wrapper.setNextHop(nextHop); if (useReturnChain) wrapper.setConnectionNumber(Constants.USER_DOWNSTREAM); else { wrapper.setUsePersistentRoute(false); wrapper.setConnectionNumber(0); } msg = wrapper; } else { ((EncryptedMessageWrapperMessage) msg) .setNextHop(nextHop); ((EncryptedMessageWrapperMessage) msg) .setConnectionNumber(Constants.USER_DOWNSTREAM); } } i++; } while (i < Constants.numServerHops); out.writeObject(msg); out.flush(); } catch (Exception e) { throw new IOException( "Error occured sending message from client to server " + e.getLocalizedMessage()); } } public static void main(String[] args) throws ClassNotFoundException, NoSuchAlgorithmException, DecryptionException { Client client = new Client(); client.setNickListFrame(new NickListFrame(client)); } public Identity getIdentity() { return identity; } public void setIdentity(Identity identity) { this.identity = identity; } public NickListFrame getNickListFrame() { return nickListFrame; } public void setNickListFrame(NickListFrame nickListFrame) { this.nickListFrame = nickListFrame; } public NickNameList getNickList() { return nickList; } public void setNickList(NickNameList nickList) { this.nickList = nickList; } public PublicIdentity getPublicIdentity() { return this.publicIdentity; } public ObjectOutputStream getOutputStream() { return out; } public Map<String, PublicIdentity> getPublicIdentityMap() { return publicIdentityMap; } /** * Select Identity from previous Identities, or select to create a new ID * * @return * @throws ClassNotFoundException * @throws IOException * @throws NoSuchAlgorithmException */ private Identity selectIdentity() throws ClassNotFoundException, NoSuchAlgorithmException { Identity userID = null; NameSaltPairs previous = LocalFileOps.getPreviousUserNamesAndSalt(); String[] prevUsers = previous.getUserNames(); String[] optionalUserNames = new String[prevUsers.length + 1]; optionalUserNames[0] = "New Identity"; for (int i = 0; i < prevUsers.length; i++) { // i is an index into prevUsers optionalUsers is 1 long that // prevUsers, with Constant as first element optionalUserNames[i + 1] = prevUsers[i]; } String selectedUserName = (String) JOptionPane.showInputDialog(null, "Choose an Identity", "Input", JOptionPane.INFORMATION_MESSAGE, null, optionalUserNames, optionalUserNames[optionalUserNames.length - 1]); if (selectedUserName == null) { Print.info("User canceled program, goodbye."); System.exit(0); } if (selectedUserName.equals(optionalUserNames[0])) { userID = makeNewIdentity(previous); } else { userID = usePreviousIdentity(previous, selectedUserName); } if (userID == null) { // Tell user they have the wrong password and end program LocalFileOps.appendAuditFile("Incorrect password for user " + selectedUserName); JOptionPane.showMessageDialog(null, "You got the wrong password. Byebye.", "Error", JOptionPane.ERROR_MESSAGE); System.exit(0); } return userID; } /** * Reuse an identity which was created prior to this run. Load the id from * the file system and check its integrity * * @param previous * previous salt and name pairs used by the sytem * @param selectedUserName * username to load * @return the loaded ID */ public Identity usePreviousIdentity(NameSaltPairs previous, String selectedUserName) { Identity userID; String password; // Existing ID // prompt password req // open file and read id Print.debug("Using previous ID. . ."); KeySalt prevSaltUsed = previous.getUserSalt(selectedUserName); if (prevSaltUsed == null) { Print.error("User's last salt value is null. Terminating the program"); System.exit(-1); } password = promptForPassword(); SecretKey secret = Keys.createAESKey(password, prevSaltUsed.getSalt1Bytes()); SecretKey secret2 = Keys.createAESKey(password, prevSaltUsed.getSalt2Bytes()); userID = LocalFileOps.getIdentityFromFile(selectedUserName, secret, secret2, prevSaltUsed); return userID; } /** * Creates a new user identity and saves it to the file system * * @param previousPairs * @return */ public Identity makeNewIdentity(NameSaltPairs previousPairs) { Identity userID; String password; // New ID Print.debug("Creating a new ID. . ."); password = this.promptForPassword(); if (password == null || password.equalsIgnoreCase("")) { Print.error("Cannot use a blank password"); System.exit(1); } // Create a new user id KeySalt newSalt = new KeySalt(); JProgressBar progress = this.showProgressPane(); Print.debug("Creating new id in progress"); userID = generateNewIdentity(password, newSalt); progress.setString("Created Identity"); progress.setIndeterminate(false); progress.setValue(100); // add the new user to the previous users of this system previousPairs.addPair(userID.getUserName(), newSalt); // Update the previous users file LocalFileOps.writePreviousUsers(previousPairs); return userID; } /** * Give user a popup asking to provide a password * * @return */ private String promptForPassword() { JPasswordField passwordField = new JPasswordField(); Object[] obj = { "Please input a password for this Identity", passwordField }; Object stringArray[] = { "OK", "Cancel" }; String password = null; if (JOptionPane.showOptionDialog(null, obj, "Password", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE, null, stringArray, obj) == JOptionPane.YES_OPTION) { password = new String(passwordField.getPassword()); } return password; } /** * Show a pane with a progress bar that lets the user know something is * happening * * @return */ private JProgressBar showProgressPane() { final JProgressBar prog = new JProgressBar(); prog.setIndeterminate(true); prog.setString("Creating new identity...."); prog.setStringPainted(true); Thread t = new Thread() { @Override public void run() { Object[] obj = { prog }; JOptionPane.showMessageDialog(null, obj, "Progress", JOptionPane.PLAIN_MESSAGE); } }; t.start(); return prog; } /** * Generate a new Identity, and save it to the file system encrypted * * @param password * - The user's provided password * @param salt * - KeySalt to use for protecting user's local files * @return The newly created identity */ private Identity generateNewIdentity(String password, KeySalt salt) { Identity n = null; try { SecretKey encSecret = Keys.createAESKey(password, salt.getSalt1Bytes()); SecretKey macSecret = Keys.createAESKey(password, salt.getSalt2Bytes()); n = new Identity(encSecret, macSecret, salt); LocalFileOps.writeUserId(n, encSecret, salt); } catch (NoSuchAlgorithmException e) { Print.error("Failed to create new Idenity.", e); JOptionPane .showMessageDialog( null, "Failed to create a new user identity. Program terminated.", "Error", JOptionPane.ERROR_MESSAGE); System.exit(0); } return n; } /** * Handle encrypted text message with sig. * * @param textWithSig */ public void handleRSAEncryptedMessage(RSAEncryptedMessage msg) { Print.debug("Get RSAencryptedMessage"); if (!publicIdentityMap.containsKey(msg.getSrcUserName()) || publicIdentityMap.get(msg.getSrcUserName()) == null) { String userNameString = PublicIdentity.composeUserName(msg .getPublicIdentity().getPublicRSAKey(), msg .getPublicIdentity().getVerKey()); if (msg.getSrcUserName().equals(userNameString)) { publicIdentityMap.put(msg.getSrcUserName(), msg.getPublicIdentity()); } else { Print.debug("PublicIdentity got compromised!!!!! Under attack!!!!"); System.exit(-1); } } Print.debug("Decrypting with privatekey"); TextMessageWithSig textWithSig = SecurityUtils.decRSA(msg, this .getIdentity().getPrivateRSAKey()); if (publicIdentityMap.get(msg.getSrcUserName()) == null) { // user is not online Print.debug("user" + msg.getSrcUserName() + " is not online."); } else { boolean verOk = SecurityUtils.ver(textWithSig.getTextMessage(), textWithSig.getSignature(), this.getPublicIdentityMap() .get(textWithSig.getTextMessage().getSrcUser()) .getVerKey()); if (verOk) { // signature of text message is verified. Print.debug("signature of text message is verified."); this.nickListFrame .showTextMessage(textWithSig.getTextMessage()); } else { LocalFileOps .appendAuditFile("Bad signature of text message from user " + msg.getSrcUserName()); Print.error("Bad signature of text message"); } } } public String getPath() { String path = null; if (this.chain != null) { path = this.chain.toString(); } return path; } }
Java
package anonymouschat.client; import java.io.Serializable; import java.security.KeyPair; import java.security.KeyPairGenerator; import java.security.NoSuchAlgorithmException; import java.security.PrivateKey; import java.security.PublicKey; import javax.crypto.SecretKey; import anonymouschat.security.KeySalt; import anonymouschat.utils.Print; /** * Identity is an object that is used to store all user information, including * public and private keys, user name, and salts. * * @author bh349 * */ public class Identity implements Serializable { private static final long serialVersionUID = -2982671647808071976L; private String userName; private PrivateKey privateRSAKey; private PublicKey publicRSAKey; private PrivateKey signingKey; private PublicKey verKey; private SecretKey fileEncKey; private SecretKey fileMacKey; private KeySalt fileKeySalt; /** * * @param fileEKey * a key for encrypting files * @param fileMacKey * a key for MACing files * @param salt * the salts to use for encryption and MAC * @throws NoSuchAlgorithmException */ public Identity(SecretKey fileEKey, SecretKey fileMacKey, KeySalt salt) throws NoSuchAlgorithmException { fileKeySalt = salt; fileEncKey = fileEKey; this.fileMacKey = fileMacKey; KeyPairGenerator gen = KeyPairGenerator.getInstance("RSA"); gen.initialize(3072); KeyPair keyPair = gen.generateKeyPair(); publicRSAKey = keyPair.getPublic(); privateRSAKey = keyPair.getPrivate(); keyPair = gen.generateKeyPair(); verKey = keyPair.getPublic(); signingKey = keyPair.getPrivate(); String userNameString = PublicIdentity.composeUserName(publicRSAKey, verKey); Print.debug("New Identity: " + userNameString + " created."); userName = userNameString; } /** * * @return String - the user name */ public String getUserName() { return userName; } /** * @return PrivateKey - the privateRSAKey */ public PrivateKey getPrivateRSAKey() { return privateRSAKey; } /** * @return PrivateKey - the signingKey */ public PrivateKey getSigningKey() { return signingKey; } /** * @return PublicKey - the publicRSAKey */ public PublicKey getPublicRSAKey() { return publicRSAKey; } /** * @return PublicKey - the verKey */ public PublicKey getVerKey() { return verKey; } /** * @return SecretKey - the fileEncKey */ public SecretKey getFileEncKey() { return fileEncKey; } /** * @return SecretKey - the Key used to mac local files */ public SecretKey getFileMacKey() { return fileMacKey; } public KeySalt getFileSalt() { return this.fileKeySalt; } }
Java
package anonymouschat.security; import java.io.Serializable; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; /** * Stores a mapping of user names to salt. Salt is used when creating an AES key * for password based authentication * <br/><br/> * When saved as a file, this class does not need to be password protected * because it only contains half the secert, and the user is suppose to keep * their half in their head * * @author jnfrye * */ public class NameSaltPairs implements Serializable { /** * */ private static final long serialVersionUID = 1401777585147197085L; /** * Pairs of user names and their respective slat values */ private ConcurrentHashMap<String, KeySalt> pairing = new ConcurrentHashMap<String, KeySalt>(); public NameSaltPairs() { } /** * Add a user to this the object, along with their salt values * @param u * @param salt */ public void addPair(String u, KeySalt salt) { this.pairing.put(u, salt); } public KeySalt getUserSalt(String u) { return this.pairing.get(u); } /** * Get all the user names stored in this file * * @return */ public String[] getUserNames() { Set<String> users = this.pairing.keySet(); String[] ret = new String[users.size()]; int i = 0; for (String u : users) { ret[i] = u; i++; } return ret; } }
Java
package anonymouschat.security; import java.io.Serializable; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import javax.crypto.spec.IvParameterSpec; import anonymouschat.utils.Print; /** * Holds random numbers used as salt in local file encryptions * @author jnfrye * */ public class KeySalt implements Serializable { private static final long serialVersionUID = 6651051088673383629L; private byte[] salt1; private byte[] salt2; private byte[] iv; /** * Create a 2 new peices of salt, and an IV to be used for encryptions */ public KeySalt() { SecureRandom secRand = null; try { secRand = SecureRandom.getInstance("SHA1PRNG"); salt1 = new byte[8]; secRand.nextBytes(salt1); salt2 = new byte[8]; secRand.nextBytes(salt2); iv = new byte[16]; secRand.nextBytes(iv); } catch (NoSuchAlgorithmException e) { Print.error("Error getting random data", e); } } public byte[] getSalt1Bytes() { return salt1.clone(); } public byte[] getSalt2Bytes() { return salt2.clone(); } /** * @return the iv */ public byte[] getIv() { return iv.clone(); } /** * Return the Initialization vector as an IvParamSpec object * * @return */ public IvParameterSpec getIvParameterSpec() { return new IvParameterSpec(iv); } }
Java
package anonymouschat.security; import java.io.Serializable; import javax.crypto.SecretKey; import anonymouschat.exceptions.InvalidTagException; import anonymouschat.security.integrity.MacTag; /** * Wrapper class of a serialized object and a MacTag of that object * This is used to check the integrity of files stored on the file system * @author Jason * */ public class SerializedObjectAndTag implements Serializable { private static final long serialVersionUID = 8069298856705435424L; /** Object wrapped by this class*/ private Serializable object; /** Tag of the object wrapped by this class */ private MacTag tagOfObj; /** * Create new SerializedObjectAndTag from a Serializable object and the key to mac with * @param ser * Object to tag, and save * @param key * Key used to MAC the object */ public SerializedObjectAndTag(Serializable ser, SecretKey key){ this.object = ser; this.tagOfObj = SecurityUtils.mac(ser, key); } /** * Verify the object's tag, and return the object if the tag is good * @param tagkey * key to verify against * @return * Serialized object wrapped in this class * @throws InvalidTagException * Thrown if the tag didn't match (ie integrity of the object is compromised) */ public Serializable getVerifiedObject(SecretKey tagkey) throws InvalidTagException{ if (SecurityUtils.ver(object, tagOfObj, tagkey) ){ return this.object; } else{ throw new anonymouschat.exceptions.InvalidTagException("Could not retrieve the object because its tag was not verified."); } } }
Java
package anonymouschat.security; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectInputStream; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import java.io.Serializable; import java.security.PrivateKey; import java.security.PublicKey; import java.security.Signature; import javax.crypto.Cipher; import javax.crypto.Mac; import javax.crypto.SecretKey; import javax.crypto.spec.IvParameterSpec; import anonymouschat.client.PublicIdentity; import anonymouschat.exceptions.DecryptionException; import anonymouschat.messages.securitymessages.AESEncryptedMessage; import anonymouschat.messages.securitymessages.RSAEncryptedMessage; import anonymouschat.messages.securitymessages.TextMessageWithSig; import anonymouschat.security.integrity.DigSig; import anonymouschat.security.integrity.MacTag; import anonymouschat.utils.Constants; import anonymouschat.utils.LocalFileOps; import anonymouschat.utils.Print; /** * This is the wrapper class of several static security util methods. * * AES & RSA; Enc & Dec; Sign & Ver & MAC; * * @author bh349 * */ public class SecurityUtils { /** * RSA Encryption for any length object * * @param obj * Serializable Object * @param pubKey * RSA publicKey * @return EncryptedMessage */ public static RSAEncryptedMessage encRSA( Serializable obj, PublicKey pubKey, String destUserID, PublicIdentity srcUser ) { byte[] result = encRSA( obj, pubKey ); return new RSAEncryptedMessage( result, destUserID, srcUser ); } /** * encrypts an arbitrary-length object * * @param obj * the object to be encrypted * @param pubKey * they key to encrypt with * @return &lt byte[] &gt array of encrypted bytes */ public static byte[] encRSA( Serializable obj, PublicKey pubKey ) { byte[] result = null; try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); Cipher enc = Cipher.getInstance( Constants.ASYMMETRIC_CYPHER_TYPE ); enc.init( Cipher.ENCRYPT_MODE, pubKey ); int offset = 0; byte[] unencryptedByteArray = objectToByteArray( obj ); while( offset < unencryptedByteArray.length ) { if( unencryptedByteArray.length - offset < Constants.MAX_ENC_SEGMENT_BYTES ) { byte[] outputBytes = new byte[unencryptedByteArray.length - offset]; System.arraycopy( unencryptedByteArray, offset, outputBytes, 0, unencryptedByteArray.length - offset ); bos.write( enc.doFinal( outputBytes ) ); break; } byte[] outputBytes = new byte[Constants.MAX_ENC_SEGMENT_BYTES]; System.arraycopy( unencryptedByteArray, offset, outputBytes, 0, Constants.MAX_ENC_SEGMENT_BYTES ); bos.write( enc.doFinal( outputBytes ) ); offset += Constants.MAX_ENC_SEGMENT_BYTES; } result = bos.toByteArray(); } catch( Exception e ) { Print.error( "RSA Enc exception", e ); } return result; } /** * AES Encryption * * @param obj * Serializable Object * @param key * AES SecretKey * @param iv * Initialization vector * @return EncryptedMessage */ public static AESEncryptedMessage encAES( Serializable obj, SecretKey key, byte[] iv ) { byte[] result = null; try { Cipher enc = Cipher.getInstance( Constants.SYMMETRIC_CIPHER_TYPE ); enc.init( Cipher.ENCRYPT_MODE, key, new IvParameterSpec( iv ) ); result = enc.doFinal( objectToByteArray( obj ) ); } catch( Exception e ) { Print.error( "AES Enc exception", e ); } return new AESEncryptedMessage( result ); } /** * Decrypt RSA * * @param obj * EncryptedMessage * @param priKey * Private key * @throws IOException */ public static TextMessageWithSig decRSA( RSAEncryptedMessage obj, PrivateKey priKey ) { TextMessageWithSig ret = (TextMessageWithSig) byteArrayToObject( decRSA( obj.getEncryptedData(), priKey ) ); return ret; } /** * RSA Decrypt a byte array to an unencrypted byte array * * @param encryptedByteArray * the data to decrypt * @param priKey * the key to decrypt with * @return */ public static byte[] decRSA( byte[] encryptedByteArray, PrivateKey priKey ) { byte[] result = null; try { Cipher dec = Cipher.getInstance( Constants.ASYMMETRIC_CYPHER_TYPE ); dec.init( Cipher.DECRYPT_MODE, priKey ); // Handle arbitrary sized encrypted messages with RSA ByteArrayOutputStream bos = new ByteArrayOutputStream(); int offset = 0; int maxDecLength = 384; while( offset < encryptedByteArray.length ) { byte[] outputBytes; if( encryptedByteArray.length - offset < maxDecLength ) { outputBytes = new byte[encryptedByteArray.length - offset]; System.arraycopy( encryptedByteArray, offset, outputBytes, 0, encryptedByteArray.length - offset ); bos.write( dec.doFinal( outputBytes ) ); break; } outputBytes = new byte[maxDecLength]; System.arraycopy( encryptedByteArray, offset, outputBytes, 0, maxDecLength ); bos.write( dec.doFinal( outputBytes ) ); offset += maxDecLength; } result = bos.toByteArray(); } catch( Exception e ) { LocalFileOps.appendAuditFile( "Unable to decrypt message." ); Print.error( "Cannot RSA decrypt data", e ); } return result; } /** * Decrypt AES * * @param expetedType * * @param obj * EncryptedMessage * @param key * AES SecretKey * @param iv * Initialization vector * @throws DecryptionException */ public static Serializable decAES( AESEncryptedMessage obj, SecretKey key, byte[] iv ) throws DecryptionException { Serializable result = SecurityUtils.byteArrayToObject( decAES( obj.getEncryptedData(), key, iv ) ); return result; } /** * AES Decrypt byte[] to unencrypted byte[] * * @param encryptedByteArray * the encrypted data * @param key * the secret key * @param iv * the initialization vector * @return * @throws DecryptionException */ public static byte[] decAES( byte[] encryptedByteArray, SecretKey key, byte[] iv ) throws DecryptionException { Cipher dec = null; byte[] ret = null; try { dec = Cipher.getInstance( Constants.SYMMETRIC_CIPHER_TYPE ); dec.init( Cipher.DECRYPT_MODE, key, new IvParameterSpec( iv ) ); ret = dec.doFinal( encryptedByteArray ); } catch( Exception e ) { throw(new DecryptionException( "Error AES decrypting the byte array" )); } return ret; } /** * Sign * * @param obj * Obj to sign * @param key * Signing Key * @return Signature */ public static DigSig sign( Serializable obj, PrivateKey key ) { byte[] signature = null; try { Signature sign = Signature.getInstance( "SHA256WITHRSA" ); sign.initSign( key ); byte[] data = objectToByteArray( obj ); sign.update( data ); signature = sign.sign(); } catch( Exception e ) { Print.error( "Digital signature SIGN exception", e ); } return new DigSig( signature ); } /** * Ver * * @param msg * msg to verify * @param sig * Signature * @param verKey * Ver key * @return true if successfully verified */ public static boolean ver( Serializable msg, DigSig sig, PublicKey verKey ) { try { Signature ver = Signature.getInstance( "SHA256WITHRSA" ); ver.initVerify( verKey ); byte[] data = objectToByteArray( msg ); ver.update( data ); return ver.verify( sig.getSig() ); } catch( Exception e ) { Print.error( "Digital signature VER exception", e ); } return false; } /** * key is generated by KeyGenerator.getInstance("HmacSHA256").generateKey() * * @param obj * msg to MAC * @param key * MAC key * @return MACTAG */ public static MacTag mac( Serializable msg, SecretKey key ) { byte[] tag = null; try { Mac m = Mac.getInstance( "HmacSHA256" ); m.init( key ); byte[] data = objectToByteArray( msg ); tag = m.doFinal( data ); } catch( Exception e ) { Print.error( "MAC exception", e ); } return new MacTag( tag ); } /** * Convert a byte array to a serializable object * @param bytes the bytes representing a serializable object * @return &lt Serializable &gt a new object */ public static Serializable byteArrayToObject( byte[] bytes ) { if( bytes == null ) return null; ObjectInput out = null; Serializable buf = null; try { // Serialize to a byte array ByteArrayInputStream bos = new ByteArrayInputStream( bytes ); out = new ObjectInputStream( bos ); buf = (Serializable) out.readObject(); } catch( Exception e ) { Print.error( "Failed to read bytes to object", e ); } finally { if( out != null ) try { out.close(); } catch( IOException e ) { } } return buf; } /** * * @param obj * a serializable objec to be converted * @return a byte[] array of the object * @throws IOException */ public static byte[] objectToByteArray( Serializable obj ) { if( obj == null ) return null; ObjectOutput out = null; byte[] buf = null; try { // Serialize to a byte array ByteArrayOutputStream bos = new ByteArrayOutputStream(); out = new ObjectOutputStream( bos ); out.writeObject( obj ); // Get the bytes of the serialized object buf = bos.toByteArray(); } catch( IOException e ) { Print.error( "Failed to convert obejct to bytes", e ); } finally { if( out != null ) try { out.close(); } catch( IOException e ) { } } return buf; } /** * Verify the MAC tag for the given object * * @param msg * Object to verify * @param tagOfObj * Computed tag to verify * @param verKey * MAC key used * @return */ public static boolean ver( Serializable msg, MacTag tagOfObj, SecretKey verKey ) { boolean verified = false; try { Mac m = Mac.getInstance( "HmacSHA256" ); m.init( verKey ); byte[] data = objectToByteArray( msg ); byte[] t = m.doFinal( data ); MacTag tag = new MacTag( t ); if( tag.equals( tagOfObj ) ) verified = true; // the MAC of the object matched } catch( Exception e ) { Print.error( "Digital signature VER exception", e ); } return verified; } }
Java
package anonymouschat.security; import java.security.NoSuchAlgorithmException; import java.security.spec.InvalidKeySpecException; import java.security.spec.KeySpec; import javax.crypto.KeyGenerator; import javax.crypto.SecretKey; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.PBEKeySpec; import javax.crypto.spec.SecretKeySpec; import anonymouschat.utils.Print; /** * Class with static methods used to generate AES keys from password and salt, * as well as system randomness * @author Jason * */ public class Keys { /** * Create an AES key from the password and the salt provided * * @param password * @param salt * @return */ public static SecretKey createAESKey(String password, byte[] salt) { SecretKeyFactory factory = null; try { factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); } catch (NoSuchAlgorithmException e1) { Print.error("Failed to create secret key.", e1); } // Password passed encryption, combined with the salt 128 bits long KeySpec spec = new PBEKeySpec(password.toCharArray(), salt.clone(), 1024, 128); SecretKey tmp = null; SecretKey secret = null; try { tmp = factory.generateSecret(spec); } catch (InvalidKeySpecException e) { Print.error("Failed to generate secret key.", e); } // use PBE key to create the AES key secret = new SecretKeySpec(tmp.getEncoded(), "AES"); // return the AES key return secret; } /** * Generate AES key * * @return SecretKey an AES key * @throws NoSuchAlgorithmException */ public static SecretKey generateAESkey() throws NoSuchAlgorithmException { KeyGenerator kgen = KeyGenerator.getInstance("AES"); kgen.init(128); return kgen.generateKey(); } }
Java