code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
/* * Copyright (C) 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"; }
1219806112-wangyao
Samples/OpenGLES/SpriteText/src/com/google/android/opengles/spritetext/NumericSprite.java
Java
asf20
3,006
/* * Copyright (C) 2007 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.opengles.spritetext; import java.nio.CharBuffer; import java.nio.FloatBuffer; import javax.microedition.khronos.opengles.GL10; /** * A 2D rectangular mesh. Can be drawn textured or untextured. * */ class Grid { public Grid(int w, int h) { if (w < 0 || w >= 65536) { throw new IllegalArgumentException("w"); } if (h < 0 || h >= 65536) { throw new IllegalArgumentException("h"); } if (w * h >= 65536) { throw new IllegalArgumentException("w * h >= 65536"); } mW = w; mH = h; int size = w * h; mVertexArray = new float[size * 3]; mVertexBuffer = FloatBuffer.wrap(mVertexArray); mTexCoordArray = new float[size * 2]; mTexCoordBuffer = FloatBuffer.wrap(mTexCoordArray); int quadW = mW - 1; int quadH = mH - 1; int quadCount = quadW * quadH; int indexCount = quadCount * 6; mIndexCount = indexCount; char[] indexArray = new char[indexCount]; /* * Initialize triangle list mesh. * * [0]-----[ 1] ... * | / | * | / | * | / | * [w]-----[w+1] ... * | | * */ { int i = 0; for (int y = 0; y < quadH; y++) { for (int x = 0; x < quadW; x++) { char a = (char) (y * mW + x); char b = (char) (y * mW + x + 1); char c = (char) ((y + 1) * mW + x); char d = (char) ((y + 1) * mW + x + 1); indexArray[i++] = a; indexArray[i++] = b; indexArray[i++] = c; indexArray[i++] = b; indexArray[i++] = c; indexArray[i++] = d; } } } mIndexBuffer = CharBuffer.wrap(indexArray); } void set(int i, int j, float x, float y, float z, float u, float v) { if (i < 0 || i >= mW) { throw new IllegalArgumentException("i"); } if (j < 0 || j >= mH) { throw new IllegalArgumentException("j"); } int index = mW * j + i; int posIndex = index * 3; mVertexArray[posIndex] = x; mVertexArray[posIndex + 1] = y; mVertexArray[posIndex + 2] = z; int texIndex = index * 2; mTexCoordArray[texIndex] = u; mTexCoordArray[texIndex + 1] = v; } public void draw(GL10 gl, boolean useTexture) { gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); gl.glVertexPointer(3, GL10.GL_FLOAT, 0, mVertexBuffer); if (useTexture) { gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY); gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, mTexCoordBuffer); gl.glEnable(GL10.GL_TEXTURE_2D); } else { gl.glDisableClientState(GL10.GL_TEXTURE_COORD_ARRAY); gl.glDisable(GL10.GL_TEXTURE_2D); } gl.glDrawElements(GL10.GL_TRIANGLES, mIndexCount, GL10.GL_UNSIGNED_SHORT, mIndexBuffer); gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); } private FloatBuffer mVertexBuffer; private float[] mVertexArray; private FloatBuffer mTexCoordBuffer; private float[] mTexCoordArray; private CharBuffer mIndexBuffer; private int mW; private int mH; private int mIndexCount; }
1219806112-wangyao
Samples/OpenGLES/SpriteText/src/com/google/android/opengles/spritetext/Grid.java
Java
asf20
3,501
/* * Copyright (C) 2007 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.opengles.spritetext; import android.opengl.Matrix; import javax.microedition.khronos.opengles.GL10; /** * A utility that projects * */ class Projector { public Projector() { mMVP = new float[16]; mV = new float[4]; mGrabber = new MatrixGrabber(); } public void setCurrentView(int x, int y, int width, int height) { mX = x; mY = y; mViewWidth = width; mViewHeight = height; } public void project(float[] obj, int objOffset, float[] win, int winOffset) { if (!mMVPComputed) { Matrix.multiplyMM(mMVP, 0, mGrabber.mProjection, 0, mGrabber.mModelView, 0); mMVPComputed = true; } Matrix.multiplyMV(mV, 0, mMVP, 0, obj, objOffset); float rw = 1.0f / mV[3]; win[winOffset] = mX + mViewWidth * (mV[0] * rw + 1.0f) * 0.5f; win[winOffset + 1] = mY + mViewHeight * (mV[1] * rw + 1.0f) * 0.5f; win[winOffset + 2] = (mV[2] * rw + 1.0f) * 0.5f; } /** * Get the current projection matrix. Has the side-effect of * setting current matrix mode to GL_PROJECTION * @param gl */ public void getCurrentProjection(GL10 gl) { mGrabber.getCurrentProjection(gl); mMVPComputed = false; } /** * Get the current model view matrix. Has the side-effect of * setting current matrix mode to GL_MODELVIEW * @param gl */ public void getCurrentModelView(GL10 gl) { mGrabber.getCurrentModelView(gl); mMVPComputed = false; } private MatrixGrabber mGrabber; private boolean mMVPComputed; private float[] mMVP; private float[] mV; private int mX; private int mY; private int mViewWidth; private int mViewHeight; }
1219806112-wangyao
Samples/OpenGLES/SpriteText/src/com/google/android/opengles/spritetext/Projector.java
Java
asf20
2,404
/* * Copyright (C) 2007 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.android.opengles.spritetext; import javax.microedition.khronos.opengles.GL10; class MatrixGrabber { public MatrixGrabber() { mModelView = new float[16]; mProjection = new float[16]; } /** * Record the current modelView and projection matrix state. * Has the side effect of setting the current matrix state to GL_MODELVIEW * @param gl */ public void getCurrentState(GL10 gl) { getCurrentProjection(gl); getCurrentModelView(gl); } /** * Record the current modelView matrix state. Has the side effect of * setting the current matrix state to GL_MODELVIEW * @param gl */ public void getCurrentModelView(GL10 gl) { getMatrix(gl, GL10.GL_MODELVIEW, mModelView); } /** * Record the current projection matrix state. Has the side effect of * setting the current matrix state to GL_PROJECTION * @param gl */ public void getCurrentProjection(GL10 gl) { getMatrix(gl, GL10.GL_PROJECTION, mProjection); } private void getMatrix(GL10 gl, int mode, float[] mat) { MatrixTrackingGL gl2 = (MatrixTrackingGL) gl; gl2.glMatrixMode(mode); gl2.getMatrix(mat, 0); } public float[] mModelView; public float[] mProjection; }
1219806112-wangyao
Samples/OpenGLES/SpriteText/src/com/google/android/opengles/spritetext/MatrixGrabber.java
Java
asf20
1,920
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.opengles.spritetext; import javax.microedition.khronos.opengles.GL; import android.app.Activity; import android.os.Bundle; public class SpriteTextActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mGLView = (GLView) findViewById(R.id.glview); mGLView.setGLWrapper(new GLView.GLWrapper() { public GL wrap(GL gl) { return new MatrixTrackingGL(gl); }}); mGLView.setRenderer(new SpriteTextRenderer(this)); mGLView.requestFocus(); } @Override protected void onPause() { super.onPause(); mGLView.onPause(); } @Override protected void onResume() { super.onResume(); mGLView.onResume(); } private GLView mGLView; }
1219806112-wangyao
Samples/OpenGLES/SpriteText/src/com/google/android/opengles/spritetext/SpriteTextActivity.java
Java
asf20
1,509
/* * Copyright (C) 2007 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.opengles.spritetext; import android.util.Log; import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.nio.ShortBuffer; import javax.microedition.khronos.opengles.GL; import javax.microedition.khronos.opengles.GL10; import javax.microedition.khronos.opengles.GL10Ext; import javax.microedition.khronos.opengles.GL11; import javax.microedition.khronos.opengles.GL11Ext; /** * Allows retrieving the current matrix even if the current OpenGL ES * driver does not support retrieving the current matrix. * * Note: the actual matrix may differ from the retrieved matrix, due * to differences in the way the math is implemented by GLMatrixWrapper * as compared to the way the math is implemented by the OpenGL ES * driver. */ class MatrixTrackingGL implements GL, GL10, GL10Ext, GL11, GL11Ext { private GL10 mgl; private GL10Ext mgl10Ext; private GL11 mgl11; private GL11Ext mgl11Ext; private int mMatrixMode; private MatrixStack mCurrent; private MatrixStack mModelView; private MatrixStack mTexture; private MatrixStack mProjection; private final static boolean _check = false; ByteBuffer mByteBuffer; FloatBuffer mFloatBuffer; float[] mCheckA; float[] mCheckB; public MatrixTrackingGL(GL gl) { mgl = (GL10) gl; if (gl instanceof GL10Ext) { mgl10Ext = (GL10Ext) gl; } if (gl instanceof GL11) { mgl11 = (GL11) gl; } if (gl instanceof GL11Ext) { mgl11Ext = (GL11Ext) gl; } mModelView = new MatrixStack(); mProjection = new MatrixStack(); mTexture = new MatrixStack(); mCurrent = mModelView; mMatrixMode = GL10.GL_MODELVIEW; } // --------------------------------------------------------------------- // GL10 methods: public void glActiveTexture(int texture) { mgl.glActiveTexture(texture); } public void glAlphaFunc(int func, float ref) { mgl.glAlphaFunc(func, ref); } public void glAlphaFuncx(int func, int ref) { mgl.glAlphaFuncx(func, ref); } public void glBindTexture(int target, int texture) { mgl.glBindTexture(target, texture); } public void glBlendFunc(int sfactor, int dfactor) { mgl.glBlendFunc(sfactor, dfactor); } public void glClear(int mask) { mgl.glClear(mask); } public void glClearColor(float red, float green, float blue, float alpha) { mgl.glClearColor(red, green, blue, alpha); } public void glClearColorx(int red, int green, int blue, int alpha) { mgl.glClearColorx(red, green, blue, alpha); } public void glClearDepthf(float depth) { mgl.glClearDepthf(depth); } public void glClearDepthx(int depth) { mgl.glClearDepthx(depth); } public void glClearStencil(int s) { mgl.glClearStencil(s); } public void glClientActiveTexture(int texture) { mgl.glClientActiveTexture(texture); } public void glColor4f(float red, float green, float blue, float alpha) { mgl.glColor4f(red, green, blue, alpha); } public void glColor4x(int red, int green, int blue, int alpha) { mgl.glColor4x(red, green, blue, alpha); } public void glColorMask(boolean red, boolean green, boolean blue, boolean alpha) { mgl.glColorMask(red, green, blue, alpha); } public void glColorPointer(int size, int type, int stride, Buffer pointer) { mgl.glColorPointer(size, type, stride, pointer); } public void glCompressedTexImage2D(int target, int level, int internalformat, int width, int height, int border, int imageSize, Buffer data) { mgl.glCompressedTexImage2D(target, level, internalformat, width, height, border, imageSize, data); } public void glCompressedTexSubImage2D(int target, int level, int xoffset, int yoffset, int width, int height, int format, int imageSize, Buffer data) { mgl.glCompressedTexSubImage2D(target, level, xoffset, yoffset, width, height, format, imageSize, data); } public void glCopyTexImage2D(int target, int level, int internalformat, int x, int y, int width, int height, int border) { mgl.glCopyTexImage2D(target, level, internalformat, x, y, width, height, border); } public void glCopyTexSubImage2D(int target, int level, int xoffset, int yoffset, int x, int y, int width, int height) { mgl.glCopyTexSubImage2D(target, level, xoffset, yoffset, x, y, width, height); } public void glCullFace(int mode) { mgl.glCullFace(mode); } public void glDeleteTextures(int n, int[] textures, int offset) { mgl.glDeleteTextures(n, textures, offset); } public void glDeleteTextures(int n, IntBuffer textures) { mgl.glDeleteTextures(n, textures); } public void glDepthFunc(int func) { mgl.glDepthFunc(func); } public void glDepthMask(boolean flag) { mgl.glDepthMask(flag); } public void glDepthRangef(float near, float far) { mgl.glDepthRangef(near, far); } public void glDepthRangex(int near, int far) { mgl.glDepthRangex(near, far); } public void glDisable(int cap) { mgl.glDisable(cap); } public void glDisableClientState(int array) { mgl.glDisableClientState(array); } public void glDrawArrays(int mode, int first, int count) { mgl.glDrawArrays(mode, first, count); } public void glDrawElements(int mode, int count, int type, Buffer indices) { mgl.glDrawElements(mode, count, type, indices); } public void glEnable(int cap) { mgl.glEnable(cap); } public void glEnableClientState(int array) { mgl.glEnableClientState(array); } public void glFinish() { mgl.glFinish(); } public void glFlush() { mgl.glFlush(); } public void glFogf(int pname, float param) { mgl.glFogf(pname, param); } public void glFogfv(int pname, float[] params, int offset) { mgl.glFogfv(pname, params, offset); } public void glFogfv(int pname, FloatBuffer params) { mgl.glFogfv(pname, params); } public void glFogx(int pname, int param) { mgl.glFogx(pname, param); } public void glFogxv(int pname, int[] params, int offset) { mgl.glFogxv(pname, params, offset); } public void glFogxv(int pname, IntBuffer params) { mgl.glFogxv(pname, params); } public void glFrontFace(int mode) { mgl.glFrontFace(mode); } public void glFrustumf(float left, float right, float bottom, float top, float near, float far) { mCurrent.glFrustumf(left, right, bottom, top, near, far); mgl.glFrustumf(left, right, bottom, top, near, far); if ( _check) check(); } public void glFrustumx(int left, int right, int bottom, int top, int near, int far) { mCurrent.glFrustumx(left, right, bottom, top, near, far); mgl.glFrustumx(left, right, bottom, top, near, far); if ( _check) check(); } public void glGenTextures(int n, int[] textures, int offset) { mgl.glGenTextures(n, textures, offset); } public void glGenTextures(int n, IntBuffer textures) { mgl.glGenTextures(n, textures); } public int glGetError() { int result = mgl.glGetError(); return result; } public void glGetIntegerv(int pname, int[] params, int offset) { mgl.glGetIntegerv(pname, params, offset); } public void glGetIntegerv(int pname, IntBuffer params) { mgl.glGetIntegerv(pname, params); } public String glGetString(int name) { String result = mgl.glGetString(name); return result; } public void glHint(int target, int mode) { mgl.glHint(target, mode); } public void glLightModelf(int pname, float param) { mgl.glLightModelf(pname, param); } public void glLightModelfv(int pname, float[] params, int offset) { mgl.glLightModelfv(pname, params, offset); } public void glLightModelfv(int pname, FloatBuffer params) { mgl.glLightModelfv(pname, params); } public void glLightModelx(int pname, int param) { mgl.glLightModelx(pname, param); } public void glLightModelxv(int pname, int[] params, int offset) { mgl.glLightModelxv(pname, params, offset); } public void glLightModelxv(int pname, IntBuffer params) { mgl.glLightModelxv(pname, params); } public void glLightf(int light, int pname, float param) { mgl.glLightf(light, pname, param); } public void glLightfv(int light, int pname, float[] params, int offset) { mgl.glLightfv(light, pname, params, offset); } public void glLightfv(int light, int pname, FloatBuffer params) { mgl.glLightfv(light, pname, params); } public void glLightx(int light, int pname, int param) { mgl.glLightx(light, pname, param); } public void glLightxv(int light, int pname, int[] params, int offset) { mgl.glLightxv(light, pname, params, offset); } public void glLightxv(int light, int pname, IntBuffer params) { mgl.glLightxv(light, pname, params); } public void glLineWidth(float width) { mgl.glLineWidth(width); } public void glLineWidthx(int width) { mgl.glLineWidthx(width); } public void glLoadIdentity() { mCurrent.glLoadIdentity(); mgl.glLoadIdentity(); if ( _check) check(); } public void glLoadMatrixf(float[] m, int offset) { mCurrent.glLoadMatrixf(m, offset); mgl.glLoadMatrixf(m, offset); if ( _check) check(); } public void glLoadMatrixf(FloatBuffer m) { int position = m.position(); mCurrent.glLoadMatrixf(m); m.position(position); mgl.glLoadMatrixf(m); if ( _check) check(); } public void glLoadMatrixx(int[] m, int offset) { mCurrent.glLoadMatrixx(m, offset); mgl.glLoadMatrixx(m, offset); if ( _check) check(); } public void glLoadMatrixx(IntBuffer m) { int position = m.position(); mCurrent.glLoadMatrixx(m); m.position(position); mgl.glLoadMatrixx(m); if ( _check) check(); } public void glLogicOp(int opcode) { mgl.glLogicOp(opcode); } public void glMaterialf(int face, int pname, float param) { mgl.glMaterialf(face, pname, param); } public void glMaterialfv(int face, int pname, float[] params, int offset) { mgl.glMaterialfv(face, pname, params, offset); } public void glMaterialfv(int face, int pname, FloatBuffer params) { mgl.glMaterialfv(face, pname, params); } public void glMaterialx(int face, int pname, int param) { mgl.glMaterialx(face, pname, param); } public void glMaterialxv(int face, int pname, int[] params, int offset) { mgl.glMaterialxv(face, pname, params, offset); } public void glMaterialxv(int face, int pname, IntBuffer params) { mgl.glMaterialxv(face, pname, params); } public void glMatrixMode(int mode) { switch (mode) { case GL10.GL_MODELVIEW: mCurrent = mModelView; break; case GL10.GL_TEXTURE: mCurrent = mTexture; break; case GL10.GL_PROJECTION: mCurrent = mProjection; break; default: throw new IllegalArgumentException("Unknown matrix mode: " + mode); } mgl.glMatrixMode(mode); mMatrixMode = mode; if ( _check) check(); } public void glMultMatrixf(float[] m, int offset) { mCurrent.glMultMatrixf(m, offset); mgl.glMultMatrixf(m, offset); if ( _check) check(); } public void glMultMatrixf(FloatBuffer m) { int position = m.position(); mCurrent.glMultMatrixf(m); m.position(position); mgl.glMultMatrixf(m); if ( _check) check(); } public void glMultMatrixx(int[] m, int offset) { mCurrent.glMultMatrixx(m, offset); mgl.glMultMatrixx(m, offset); if ( _check) check(); } public void glMultMatrixx(IntBuffer m) { int position = m.position(); mCurrent.glMultMatrixx(m); m.position(position); mgl.glMultMatrixx(m); if ( _check) check(); } public void glMultiTexCoord4f(int target, float s, float t, float r, float q) { mgl.glMultiTexCoord4f(target, s, t, r, q); } public void glMultiTexCoord4x(int target, int s, int t, int r, int q) { mgl.glMultiTexCoord4x(target, s, t, r, q); } public void glNormal3f(float nx, float ny, float nz) { mgl.glNormal3f(nx, ny, nz); } public void glNormal3x(int nx, int ny, int nz) { mgl.glNormal3x(nx, ny, nz); } public void glNormalPointer(int type, int stride, Buffer pointer) { mgl.glNormalPointer(type, stride, pointer); } public void glOrthof(float left, float right, float bottom, float top, float near, float far) { mCurrent.glOrthof(left, right, bottom, top, near, far); mgl.glOrthof(left, right, bottom, top, near, far); if ( _check) check(); } public void glOrthox(int left, int right, int bottom, int top, int near, int far) { mCurrent.glOrthox(left, right, bottom, top, near, far); mgl.glOrthox(left, right, bottom, top, near, far); if ( _check) check(); } public void glPixelStorei(int pname, int param) { mgl.glPixelStorei(pname, param); } public void glPointSize(float size) { mgl.glPointSize(size); } public void glPointSizex(int size) { mgl.glPointSizex(size); } public void glPolygonOffset(float factor, float units) { mgl.glPolygonOffset(factor, units); } public void glPolygonOffsetx(int factor, int units) { mgl.glPolygonOffsetx(factor, units); } public void glPopMatrix() { mCurrent.glPopMatrix(); mgl.glPopMatrix(); if ( _check) check(); } public void glPushMatrix() { mCurrent.glPushMatrix(); mgl.glPushMatrix(); if ( _check) check(); } public void glReadPixels(int x, int y, int width, int height, int format, int type, Buffer pixels) { mgl.glReadPixels(x, y, width, height, format, type, pixels); } public void glRotatef(float angle, float x, float y, float z) { mCurrent.glRotatef(angle, x, y, z); mgl.glRotatef(angle, x, y, z); if ( _check) check(); } public void glRotatex(int angle, int x, int y, int z) { mCurrent.glRotatex(angle, x, y, z); mgl.glRotatex(angle, x, y, z); if ( _check) check(); } public void glSampleCoverage(float value, boolean invert) { mgl.glSampleCoverage(value, invert); } public void glSampleCoveragex(int value, boolean invert) { mgl.glSampleCoveragex(value, invert); } public void glScalef(float x, float y, float z) { mCurrent.glScalef(x, y, z); mgl.glScalef(x, y, z); if ( _check) check(); } public void glScalex(int x, int y, int z) { mCurrent.glScalex(x, y, z); mgl.glScalex(x, y, z); if ( _check) check(); } public void glScissor(int x, int y, int width, int height) { mgl.glScissor(x, y, width, height); } public void glShadeModel(int mode) { mgl.glShadeModel(mode); } public void glStencilFunc(int func, int ref, int mask) { mgl.glStencilFunc(func, ref, mask); } public void glStencilMask(int mask) { mgl.glStencilMask(mask); } public void glStencilOp(int fail, int zfail, int zpass) { mgl.glStencilOp(fail, zfail, zpass); } public void glTexCoordPointer(int size, int type, int stride, Buffer pointer) { mgl.glTexCoordPointer(size, type, stride, pointer); } public void glTexEnvf(int target, int pname, float param) { mgl.glTexEnvf(target, pname, param); } public void glTexEnvfv(int target, int pname, float[] params, int offset) { mgl.glTexEnvfv(target, pname, params, offset); } public void glTexEnvfv(int target, int pname, FloatBuffer params) { mgl.glTexEnvfv(target, pname, params); } public void glTexEnvx(int target, int pname, int param) { mgl.glTexEnvx(target, pname, param); } public void glTexEnvxv(int target, int pname, int[] params, int offset) { mgl.glTexEnvxv(target, pname, params, offset); } public void glTexEnvxv(int target, int pname, IntBuffer params) { mgl.glTexEnvxv(target, pname, params); } public void glTexImage2D(int target, int level, int internalformat, int width, int height, int border, int format, int type, Buffer pixels) { mgl.glTexImage2D(target, level, internalformat, width, height, border, format, type, pixels); } public void glTexParameterf(int target, int pname, float param) { mgl.glTexParameterf(target, pname, param); } public void glTexParameterx(int target, int pname, int param) { mgl.glTexParameterx(target, pname, param); } public void glTexParameteriv(int target, int pname, int[] params, int offset) { mgl11.glTexParameteriv(target, pname, params, offset); } public void glTexParameteriv(int target, int pname, IntBuffer params) { mgl11.glTexParameteriv(target, pname, params); } public void glTexSubImage2D(int target, int level, int xoffset, int yoffset, int width, int height, int format, int type, Buffer pixels) { mgl.glTexSubImage2D(target, level, xoffset, yoffset, width, height, format, type, pixels); } public void glTranslatef(float x, float y, float z) { mCurrent.glTranslatef(x, y, z); mgl.glTranslatef(x, y, z); if ( _check) check(); } public void glTranslatex(int x, int y, int z) { mCurrent.glTranslatex(x, y, z); mgl.glTranslatex(x, y, z); if ( _check) check(); } public void glVertexPointer(int size, int type, int stride, Buffer pointer) { mgl.glVertexPointer(size, type, stride, pointer); } public void glViewport(int x, int y, int width, int height) { mgl.glViewport(x, y, width, height); } public void glClipPlanef(int plane, float[] equation, int offset) { mgl11.glClipPlanef(plane, equation, offset); } public void glClipPlanef(int plane, FloatBuffer equation) { mgl11.glClipPlanef(plane, equation); } public void glClipPlanex(int plane, int[] equation, int offset) { mgl11.glClipPlanex(plane, equation, offset); } public void glClipPlanex(int plane, IntBuffer equation) { mgl11.glClipPlanex(plane, equation); } // Draw Texture Extension public void glDrawTexfOES(float x, float y, float z, float width, float height) { mgl11Ext.glDrawTexfOES(x, y, z, width, height); } public void glDrawTexfvOES(float[] coords, int offset) { mgl11Ext.glDrawTexfvOES(coords, offset); } public void glDrawTexfvOES(FloatBuffer coords) { mgl11Ext.glDrawTexfvOES(coords); } public void glDrawTexiOES(int x, int y, int z, int width, int height) { mgl11Ext.glDrawTexiOES(x, y, z, width, height); } public void glDrawTexivOES(int[] coords, int offset) { mgl11Ext.glDrawTexivOES(coords, offset); } public void glDrawTexivOES(IntBuffer coords) { mgl11Ext.glDrawTexivOES(coords); } public void glDrawTexsOES(short x, short y, short z, short width, short height) { mgl11Ext.glDrawTexsOES(x, y, z, width, height); } public void glDrawTexsvOES(short[] coords, int offset) { mgl11Ext.glDrawTexsvOES(coords, offset); } public void glDrawTexsvOES(ShortBuffer coords) { mgl11Ext.glDrawTexsvOES(coords); } public void glDrawTexxOES(int x, int y, int z, int width, int height) { mgl11Ext.glDrawTexxOES(x, y, z, width, height); } public void glDrawTexxvOES(int[] coords, int offset) { mgl11Ext.glDrawTexxvOES(coords, offset); } public void glDrawTexxvOES(IntBuffer coords) { mgl11Ext.glDrawTexxvOES(coords); } public int glQueryMatrixxOES(int[] mantissa, int mantissaOffset, int[] exponent, int exponentOffset) { return mgl10Ext.glQueryMatrixxOES(mantissa, mantissaOffset, exponent, exponentOffset); } public int glQueryMatrixxOES(IntBuffer mantissa, IntBuffer exponent) { return mgl10Ext.glQueryMatrixxOES(mantissa, exponent); } // Unsupported GL11 methods public void glBindBuffer(int target, int buffer) { throw new UnsupportedOperationException(); } public void glBufferData(int target, int size, Buffer data, int usage) { throw new UnsupportedOperationException(); } public void glBufferSubData(int target, int offset, int size, Buffer data) { throw new UnsupportedOperationException(); } public void glColor4ub(byte red, byte green, byte blue, byte alpha) { throw new UnsupportedOperationException(); } public void glDeleteBuffers(int n, int[] buffers, int offset) { throw new UnsupportedOperationException(); } public void glDeleteBuffers(int n, IntBuffer buffers) { throw new UnsupportedOperationException(); } public void glGenBuffers(int n, int[] buffers, int offset) { throw new UnsupportedOperationException(); } public void glGenBuffers(int n, IntBuffer buffers) { throw new UnsupportedOperationException(); } public void glGetBooleanv(int pname, boolean[] params, int offset) { throw new UnsupportedOperationException(); } public void glGetBooleanv(int pname, IntBuffer params) { throw new UnsupportedOperationException(); } public void glGetBufferParameteriv(int target, int pname, int[] params, int offset) { throw new UnsupportedOperationException(); } public void glGetBufferParameteriv(int target, int pname, IntBuffer params) { throw new UnsupportedOperationException(); } public void glGetClipPlanef(int pname, float[] eqn, int offset) { throw new UnsupportedOperationException(); } public void glGetClipPlanef(int pname, FloatBuffer eqn) { throw new UnsupportedOperationException(); } public void glGetClipPlanex(int pname, int[] eqn, int offset) { throw new UnsupportedOperationException(); } public void glGetClipPlanex(int pname, IntBuffer eqn) { throw new UnsupportedOperationException(); } public void glGetFixedv(int pname, int[] params, int offset) { throw new UnsupportedOperationException(); } public void glGetFixedv(int pname, IntBuffer params) { throw new UnsupportedOperationException(); } public void glGetFloatv(int pname, float[] params, int offset) { throw new UnsupportedOperationException(); } public void glGetFloatv(int pname, FloatBuffer params) { throw new UnsupportedOperationException(); } public void glGetLightfv(int light, int pname, float[] params, int offset) { throw new UnsupportedOperationException(); } public void glGetLightfv(int light, int pname, FloatBuffer params) { throw new UnsupportedOperationException(); } public void glGetLightxv(int light, int pname, int[] params, int offset) { throw new UnsupportedOperationException(); } public void glGetLightxv(int light, int pname, IntBuffer params) { throw new UnsupportedOperationException(); } public void glGetMaterialfv(int face, int pname, float[] params, int offset) { throw new UnsupportedOperationException(); } public void glGetMaterialfv(int face, int pname, FloatBuffer params) { throw new UnsupportedOperationException(); } public void glGetMaterialxv(int face, int pname, int[] params, int offset) { throw new UnsupportedOperationException(); } public void glGetMaterialxv(int face, int pname, IntBuffer params) { throw new UnsupportedOperationException(); } public void glGetTexEnviv(int env, int pname, int[] params, int offset) { throw new UnsupportedOperationException(); } public void glGetTexEnviv(int env, int pname, IntBuffer params) { throw new UnsupportedOperationException(); } public void glGetTexEnvxv(int env, int pname, int[] params, int offset) { throw new UnsupportedOperationException(); } public void glGetTexEnvxv(int env, int pname, IntBuffer params) { throw new UnsupportedOperationException(); } public void glGetTexParameterfv(int target, int pname, float[] params, int offset) { throw new UnsupportedOperationException(); } public void glGetTexParameterfv(int target, int pname, FloatBuffer params) { throw new UnsupportedOperationException(); } public void glGetTexParameteriv(int target, int pname, int[] params, int offset) { throw new UnsupportedOperationException(); } public void glGetTexParameteriv(int target, int pname, IntBuffer params) { throw new UnsupportedOperationException(); } public void glGetTexParameterxv(int target, int pname, int[] params, int offset) { throw new UnsupportedOperationException(); } public void glGetTexParameterxv(int target, int pname, IntBuffer params) { throw new UnsupportedOperationException(); } public boolean glIsBuffer(int buffer) { throw new UnsupportedOperationException(); } public boolean glIsEnabled(int cap) { throw new UnsupportedOperationException(); } public boolean glIsTexture(int texture) { throw new UnsupportedOperationException(); } public void glPointParameterf(int pname, float param) { throw new UnsupportedOperationException(); } public void glPointParameterfv(int pname, float[] params, int offset) { throw new UnsupportedOperationException(); } public void glPointParameterfv(int pname, FloatBuffer params) { throw new UnsupportedOperationException(); } public void glPointParameterx(int pname, int param) { throw new UnsupportedOperationException(); } public void glPointParameterxv(int pname, int[] params, int offset) { throw new UnsupportedOperationException(); } public void glPointParameterxv(int pname, IntBuffer params) { throw new UnsupportedOperationException(); } public void glPointSizePointerOES(int type, int stride, Buffer pointer) { throw new UnsupportedOperationException(); } public void glTexEnvi(int target, int pname, int param) { throw new UnsupportedOperationException(); } public void glTexEnviv(int target, int pname, int[] params, int offset) { throw new UnsupportedOperationException(); } public void glTexEnviv(int target, int pname, IntBuffer params) { throw new UnsupportedOperationException(); } public void glTexParameterfv(int target, int pname, float[] params, int offset) { throw new UnsupportedOperationException(); } public void glTexParameterfv(int target, int pname, FloatBuffer params) { throw new UnsupportedOperationException(); } public void glTexParameteri(int target, int pname, int param) { throw new UnsupportedOperationException(); } public void glTexParameterxv(int target, int pname, int[] params, int offset) { throw new UnsupportedOperationException(); } public void glTexParameterxv(int target, int pname, IntBuffer params) { throw new UnsupportedOperationException(); } public void glColorPointer(int size, int type, int stride, int offset) { throw new UnsupportedOperationException(); } public void glDrawElements(int mode, int count, int type, int offset) { throw new UnsupportedOperationException(); } public void glGetPointerv(int pname, Buffer[] params) { throw new UnsupportedOperationException(); } public void glNormalPointer(int type, int stride, int offset) { throw new UnsupportedOperationException(); } public void glTexCoordPointer(int size, int type, int stride, int offset) { throw new UnsupportedOperationException(); } public void glVertexPointer(int size, int type, int stride, int offset) { throw new UnsupportedOperationException(); } public void glCurrentPaletteMatrixOES(int matrixpaletteindex) { throw new UnsupportedOperationException(); } public void glLoadPaletteFromModelViewMatrixOES() { throw new UnsupportedOperationException(); } public void glMatrixIndexPointerOES(int size, int type, int stride, Buffer pointer) { throw new UnsupportedOperationException(); } public void glMatrixIndexPointerOES(int size, int type, int stride, int offset) { throw new UnsupportedOperationException(); } public void glWeightPointerOES(int size, int type, int stride, Buffer pointer) { throw new UnsupportedOperationException(); } public void glWeightPointerOES(int size, int type, int stride, int offset) { throw new UnsupportedOperationException(); } /** * Get the current matrix */ public void getMatrix(float[] m, int offset) { mCurrent.getMatrix(m, offset); } /** * Get the current matrix mode */ public int getMatrixMode() { return mMatrixMode; } private void check() { int oesMode; switch (mMatrixMode) { case GL_MODELVIEW: oesMode = GL11.GL_MODELVIEW_MATRIX_FLOAT_AS_INT_BITS_OES; break; case GL_PROJECTION: oesMode = GL11.GL_PROJECTION_MATRIX_FLOAT_AS_INT_BITS_OES; break; case GL_TEXTURE: oesMode = GL11.GL_TEXTURE_MATRIX_FLOAT_AS_INT_BITS_OES; break; default: throw new IllegalArgumentException("Unknown matrix mode"); } if ( mByteBuffer == null) { mCheckA = new float[16]; mCheckB = new float[16]; mByteBuffer = ByteBuffer.allocateDirect(64); mByteBuffer.order(ByteOrder.nativeOrder()); mFloatBuffer = mByteBuffer.asFloatBuffer(); } mgl.glGetIntegerv(oesMode, mByteBuffer.asIntBuffer()); for(int i = 0; i < 16; i++) { mCheckB[i] = mFloatBuffer.get(i); } mCurrent.getMatrix(mCheckA, 0); boolean fail = false; for(int i = 0; i < 16; i++) { if (mCheckA[i] != mCheckB[i]) { Log.d("GLMatWrap", "i:" + i + " a:" + mCheckA[i] + " a:" + mCheckB[i]); fail = true; } } if (fail) { throw new IllegalArgumentException("Matrix math difference."); } } }
1219806112-wangyao
Samples/OpenGLES/SpriteText/src/com/google/android/opengles/spritetext/MatrixTrackingGL.java
Java
asf20
32,510
/* * Copyright (C) 2007 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.opengles.spritetext; import android.opengl.Matrix; import java.nio.FloatBuffer; import java.nio.IntBuffer; /** * A matrix stack, similar to OpenGL ES's internal matrix stack. */ public class MatrixStack { public MatrixStack() { commonInit(DEFAULT_MAX_DEPTH); } public MatrixStack(int maxDepth) { commonInit(maxDepth); } private void commonInit(int maxDepth) { mMatrix = new float[maxDepth * MATRIX_SIZE]; mTemp = new float[MATRIX_SIZE * 2]; glLoadIdentity(); } public void glFrustumf(float left, float right, float bottom, float top, float near, float far) { Matrix.frustumM(mMatrix, mTop, left, right, bottom, top, near, far); } public void glFrustumx(int left, int right, int bottom, int top, int near, int far) { glFrustumf(fixedToFloat(left),fixedToFloat(right), fixedToFloat(bottom), fixedToFloat(top), fixedToFloat(near), fixedToFloat(far)); } public void glLoadIdentity() { Matrix.setIdentityM(mMatrix, mTop); } public void glLoadMatrixf(float[] m, int offset) { System.arraycopy(m, offset, mMatrix, mTop, MATRIX_SIZE); } public void glLoadMatrixf(FloatBuffer m) { m.get(mMatrix, mTop, MATRIX_SIZE); } public void glLoadMatrixx(int[] m, int offset) { for(int i = 0; i < MATRIX_SIZE; i++) { mMatrix[mTop + i] = fixedToFloat(m[offset + i]); } } public void glLoadMatrixx(IntBuffer m) { for(int i = 0; i < MATRIX_SIZE; i++) { mMatrix[mTop + i] = fixedToFloat(m.get()); } } public void glMultMatrixf(float[] m, int offset) { System.arraycopy(mMatrix, mTop, mTemp, 0, MATRIX_SIZE); Matrix.multiplyMM(mMatrix, mTop, mTemp, 0, m, offset); } public void glMultMatrixf(FloatBuffer m) { m.get(mTemp, MATRIX_SIZE, MATRIX_SIZE); glMultMatrixf(mTemp, MATRIX_SIZE); } public void glMultMatrixx(int[] m, int offset) { for(int i = 0; i < MATRIX_SIZE; i++) { mTemp[MATRIX_SIZE + i] = fixedToFloat(m[offset + i]); } glMultMatrixf(mTemp, MATRIX_SIZE); } public void glMultMatrixx(IntBuffer m) { for(int i = 0; i < MATRIX_SIZE; i++) { mTemp[MATRIX_SIZE + i] = fixedToFloat(m.get()); } glMultMatrixf(mTemp, MATRIX_SIZE); } public void glOrthof(float left, float right, float bottom, float top, float near, float far) { Matrix.orthoM(mMatrix, mTop, left, right, bottom, top, near, far); } public void glOrthox(int left, int right, int bottom, int top, int near, int far) { glOrthof(fixedToFloat(left), fixedToFloat(right), fixedToFloat(bottom), fixedToFloat(top), fixedToFloat(near), fixedToFloat(far)); } public void glPopMatrix() { preflight_adjust(-1); adjust(-1); } public void glPushMatrix() { preflight_adjust(1); System.arraycopy(mMatrix, mTop, mMatrix, mTop + MATRIX_SIZE, MATRIX_SIZE); adjust(1); } public void glRotatef(float angle, float x, float y, float z) { Matrix.setRotateM(mTemp, 0, angle, x, y, z); System.arraycopy(mMatrix, mTop, mTemp, MATRIX_SIZE, MATRIX_SIZE); Matrix.multiplyMM(mMatrix, mTop, mTemp, MATRIX_SIZE, mTemp, 0); } public void glRotatex(int angle, int x, int y, int z) { glRotatef(angle, fixedToFloat(x), fixedToFloat(y), fixedToFloat(z)); } public void glScalef(float x, float y, float z) { Matrix.scaleM(mMatrix, mTop, x, y, z); } public void glScalex(int x, int y, int z) { glScalef(fixedToFloat(x), fixedToFloat(y), fixedToFloat(z)); } public void glTranslatef(float x, float y, float z) { Matrix.translateM(mMatrix, mTop, x, y, z); } public void glTranslatex(int x, int y, int z) { glTranslatef(fixedToFloat(x), fixedToFloat(y), fixedToFloat(z)); } public void getMatrix(float[] dest, int offset) { System.arraycopy(mMatrix, mTop, dest, offset, MATRIX_SIZE); } private float fixedToFloat(int x) { return x * (1.0f / 65536.0f); } private void preflight_adjust(int dir) { int newTop = mTop + dir * MATRIX_SIZE; if (newTop < 0) { throw new IllegalArgumentException("stack underflow"); } if (newTop + MATRIX_SIZE > mMatrix.length) { throw new IllegalArgumentException("stack overflow"); } } private void adjust(int dir) { mTop += dir * MATRIX_SIZE; } private final static int DEFAULT_MAX_DEPTH = 32; private final static int MATRIX_SIZE = 16; private float[] mMatrix; private int mTop; private float[] mTemp; }
1219806112-wangyao
Samples/OpenGLES/SpriteText/src/com/google/android/opengles/spritetext/MatrixStack.java
Java
asf20
5,512
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.opengles.spritetext; import android.content.Context; import android.util.AttributeSet; import android.view.SurfaceHolder; import android.view.SurfaceView; import java.util.ArrayList; import java.util.concurrent.Semaphore; import javax.microedition.khronos.egl.EGL10; import javax.microedition.khronos.egl.EGL11; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.egl.EGLContext; import javax.microedition.khronos.egl.EGLDisplay; import javax.microedition.khronos.egl.EGLSurface; import javax.microedition.khronos.opengles.GL; import javax.microedition.khronos.opengles.GL10; /** * An implementation of SurfaceView that uses the dedicated surface for * displaying an OpenGL animation. This allows the animation to run in a * separate thread, without requiring that it be driven by the update mechanism * of the view hierarchy. * * The application-specific rendering code is delegated to a GLView.Renderer * instance. */ class GLView extends SurfaceView implements SurfaceHolder.Callback { GLView(Context context) { super(context); init(); } public GLView(Context context, AttributeSet attrs) { super(context, attrs); init(); } private void init() { // Install a SurfaceHolder.Callback so we get notified when the // underlying surface is created and destroyed mHolder = getHolder(); mHolder.addCallback(this); mHolder.setType(SurfaceHolder.SURFACE_TYPE_GPU); } public void setGLWrapper(GLWrapper glWrapper) { mGLWrapper = glWrapper; } public void setRenderer(Renderer renderer) { mGLThread = new GLThread(renderer); mGLThread.start(); } public void surfaceCreated(SurfaceHolder holder) { mGLThread.surfaceCreated(); } public void surfaceDestroyed(SurfaceHolder holder) { // Surface will be destroyed when we return mGLThread.surfaceDestroyed(); } public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { // Surface size or format has changed. This should not happen in this // example. mGLThread.onWindowResize(w, h); } /** * Inform the view that the activity is paused. */ public void onPause() { mGLThread.onPause(); } /** * Inform the view that the activity is resumed. */ public void onResume() { mGLThread.onResume(); } /** * Inform the view that the window focus has changed. */ @Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); mGLThread.onWindowFocusChanged(hasFocus); } /** * Queue an "event" to be run on the GL rendering thread. * @param r the runnable to be run on the GL rendering thread. */ public void queueEvent(Runnable r) { mGLThread.queueEvent(r); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); mGLThread.requestExitAndWait(); } // ---------------------------------------------------------------------- public interface GLWrapper { GL wrap(GL gl); } // ---------------------------------------------------------------------- /** * A generic renderer interface. */ public interface Renderer { /** * @return the EGL configuration specification desired by the renderer. */ int[] getConfigSpec(); /** * Surface created. * Called when the surface is created. Called when the application * starts, and whenever the GPU is reinitialized. This will * typically happen when the device awakes after going to sleep. * Set your textures here. */ void surfaceCreated(GL10 gl); /** * Surface changed size. * Called after the surface is created and whenever * the OpenGL ES surface size changes. Set your viewport here. * @param gl * @param width * @param height */ void sizeChanged(GL10 gl, int width, int height); /** * Draw the current frame. * @param gl */ void drawFrame(GL10 gl); } /** * An EGL helper class. */ private class EglHelper { public EglHelper() { } /** * Initialize EGL for a given configuration spec. * @param configSpec */ public void start(int[] configSpec){ /* * Get an EGL instance */ mEgl = (EGL10) EGLContext.getEGL(); /* * Get to the default display. */ mEglDisplay = mEgl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY); /* * We can now initialize EGL for that display */ int[] version = new int[2]; mEgl.eglInitialize(mEglDisplay, version); EGLConfig[] configs = new EGLConfig[1]; int[] num_config = new int[1]; mEgl.eglChooseConfig(mEglDisplay, configSpec, configs, 1, num_config); mEglConfig = configs[0]; /* * Create an OpenGL ES context. This must be done only once, an * OpenGL context is a somewhat heavy object. */ mEglContext = mEgl.eglCreateContext(mEglDisplay, mEglConfig, EGL10.EGL_NO_CONTEXT, null); mEglSurface = null; } /* * Create and return an OpenGL surface */ public GL createSurface(SurfaceHolder holder) { /* * The window size has changed, so we need to create a new * surface. */ if (mEglSurface != null) { /* * Unbind and destroy the old EGL surface, if * there is one. */ mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT); mEgl.eglDestroySurface(mEglDisplay, mEglSurface); } /* * Create an EGL surface we can render into. */ mEglSurface = mEgl.eglCreateWindowSurface(mEglDisplay, mEglConfig, holder, null); /* * Before we can issue GL commands, we need to make sure * the context is current and bound to a surface. */ mEgl.eglMakeCurrent(mEglDisplay, mEglSurface, mEglSurface, mEglContext); GL gl = mEglContext.getGL(); if (mGLWrapper != null) { gl = mGLWrapper.wrap(gl); } return gl; } /** * Display the current render surface. * @return false if the context has been lost. */ public boolean swap() { mEgl.eglSwapBuffers(mEglDisplay, mEglSurface); /* * Always check for EGL_CONTEXT_LOST, which means the context * and all associated data were lost (For instance because * the device went to sleep). We need to sleep until we * get a new surface. */ return mEgl.eglGetError() != EGL11.EGL_CONTEXT_LOST; } public void finish() { if (mEglSurface != null) { mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT); mEgl.eglDestroySurface(mEglDisplay, mEglSurface); mEglSurface = null; } if (mEglContext != null) { mEgl.eglDestroyContext(mEglDisplay, mEglContext); mEglContext = null; } if (mEglDisplay != null) { mEgl.eglTerminate(mEglDisplay); mEglDisplay = null; } } EGL10 mEgl; EGLDisplay mEglDisplay; EGLSurface mEglSurface; EGLConfig mEglConfig; EGLContext mEglContext; } /** * A generic GL Thread. Takes care of initializing EGL and GL. Delegates * to a Renderer instance to do the actual drawing. * */ class GLThread extends Thread { GLThread(Renderer renderer) { super(); mDone = false; mWidth = 0; mHeight = 0; mRenderer = renderer; setName("GLThread"); } @Override public void run() { /* * When the android framework launches a second instance of * an activity, the new instance's onCreate() method may be * called before the first instance returns from onDestroy(). * * This semaphore ensures that only one instance at a time * accesses EGL. */ try { try { sEglSemaphore.acquire(); } catch (InterruptedException e) { return; } guardedRun(); } catch (InterruptedException e) { // fall thru and exit normally } finally { sEglSemaphore.release(); } } private void guardedRun() throws InterruptedException { mEglHelper = new EglHelper(); /* * Specify a configuration for our opengl session * and grab the first configuration that matches is */ int[] configSpec = mRenderer.getConfigSpec(); mEglHelper.start(configSpec); GL10 gl = null; boolean tellRendererSurfaceCreated = true; boolean tellRendererSurfaceChanged = true; /* * This is our main activity thread's loop, we go until * asked to quit. */ while (!mDone) { /* * Update the asynchronous state (window size) */ int w, h; boolean changed; boolean needStart = false; synchronized (this) { Runnable r; while ((r = getEvent()) != null) { r.run(); } if (mPaused) { mEglHelper.finish(); needStart = true; } if(needToWait()) { while (needToWait()) { wait(); } } if (mDone) { break; } changed = mSizeChanged; w = mWidth; h = mHeight; mSizeChanged = false; } if (needStart) { mEglHelper.start(configSpec); tellRendererSurfaceCreated = true; changed = true; } if (changed) { gl = (GL10) mEglHelper.createSurface(mHolder); tellRendererSurfaceChanged = true; } if (tellRendererSurfaceCreated) { mRenderer.surfaceCreated(gl); tellRendererSurfaceCreated = false; } if (tellRendererSurfaceChanged) { mRenderer.sizeChanged(gl, w, h); tellRendererSurfaceChanged = false; } if ((w > 0) && (h > 0)) { /* draw a frame here */ mRenderer.drawFrame(gl); /* * Once we're done with GL, we need to call swapBuffers() * to instruct the system to display the rendered frame */ mEglHelper.swap(); } } /* * clean-up everything... */ mEglHelper.finish(); } private boolean needToWait() { return (mPaused || (! mHasFocus) || (! mHasSurface) || mContextLost) && (! mDone); } public void surfaceCreated() { synchronized(this) { mHasSurface = true; mContextLost = false; notify(); } } public void surfaceDestroyed() { synchronized(this) { mHasSurface = false; notify(); } } public void onPause() { synchronized (this) { mPaused = true; } } public void onResume() { synchronized (this) { mPaused = false; notify(); } } public void onWindowFocusChanged(boolean hasFocus) { synchronized (this) { mHasFocus = hasFocus; if (mHasFocus == true) { notify(); } } } public void onWindowResize(int w, int h) { synchronized (this) { mWidth = w; mHeight = h; mSizeChanged = true; } } public void requestExitAndWait() { // don't call this from GLThread thread or it is a guaranteed // deadlock! synchronized(this) { mDone = true; notify(); } try { join(); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } } /** * Queue an "event" to be run on the GL rendering thread. * @param r the runnable to be run on the GL rendering thread. */ public void queueEvent(Runnable r) { synchronized(this) { mEventQueue.add(r); } } private Runnable getEvent() { synchronized(this) { if (mEventQueue.size() > 0) { return mEventQueue.remove(0); } } return null; } private boolean mDone; private boolean mPaused; private boolean mHasFocus; private boolean mHasSurface; private boolean mContextLost; private int mWidth; private int mHeight; private Renderer mRenderer; private ArrayList<Runnable> mEventQueue = new ArrayList<Runnable>(); private EglHelper mEglHelper; } private static final Semaphore sEglSemaphore = new Semaphore(1); private boolean mSizeChanged = true; private SurfaceHolder mHolder; private GLThread mGLThread; private GLWrapper mGLWrapper; }
1219806112-wangyao
Samples/OpenGLES/SpriteText/src/com/google/android/opengles/spritetext/GLView.java
Java
asf20
15,729
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.opengles.spritetext; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import java.nio.ShortBuffer; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Paint; import android.opengl.GLU; import android.opengl.GLUtils; import android.os.SystemClock; import javax.microedition.khronos.egl.EGL10; import javax.microedition.khronos.opengles.GL10; public class SpriteTextRenderer implements GLView.Renderer{ public SpriteTextRenderer(Context context) { mContext = context; mTriangle = new Triangle(); mProjector = new Projector(); mLabelPaint = new Paint(); mLabelPaint.setTextSize(32); mLabelPaint.setAntiAlias(true); mLabelPaint.setARGB(0xff, 0x00, 0x00, 0x00); } public int[] getConfigSpec() { // We don't need a depth buffer, and don't care about our // color depth. int[] configSpec = { EGL10.EGL_DEPTH_SIZE, 0, EGL10.EGL_NONE }; return configSpec; } public void surfaceCreated(GL10 gl) { /* * By default, OpenGL enables features that improve quality * but reduce performance. One might want to tweak that * especially on software renderer. */ gl.glDisable(GL10.GL_DITHER); /* * Some one-time OpenGL initialization can be made here * probably based on features of this particular context */ gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_FASTEST); gl.glClearColor(.5f, .5f, .5f, 1); gl.glShadeModel(GL10.GL_SMOOTH); gl.glEnable(GL10.GL_DEPTH_TEST); gl.glEnable(GL10.GL_TEXTURE_2D); /* * Create our texture. This has to be done each time the * surface is created. */ int[] textures = new int[1]; gl.glGenTextures(1, textures, 0); mTextureID = textures[0]; gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureID); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_CLAMP_TO_EDGE); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_CLAMP_TO_EDGE); gl.glTexEnvf(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE, GL10.GL_REPLACE); InputStream is = mContext.getResources() .openRawResource(R.drawable.tex); Bitmap bitmap; try { bitmap = BitmapFactory.decodeStream(is); } finally { try { is.close(); } catch(IOException e) { // Ignore. } } GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0); bitmap.recycle(); if (mLabels != null) { mLabels.shutdown(gl); } else { mLabels = new LabelMaker(true, 256, 64); } mLabels.initialize(gl); mLabels.beginAdding(gl); mLabelA = mLabels.add(gl, "A", mLabelPaint); mLabelB = mLabels.add(gl, "B", mLabelPaint); mLabelC = mLabels.add(gl, "C", mLabelPaint); mLabelMsPF = mLabels.add(gl, "ms/f", mLabelPaint); mLabels.endAdding(gl); if (mNumericSprite != null) { mNumericSprite.shutdown(gl); } else { mNumericSprite = new NumericSprite(); } mNumericSprite.initialize(gl, mLabelPaint); } public void drawFrame(GL10 gl) { /* * By default, OpenGL enables features that improve quality * but reduce performance. One might want to tweak that * especially on software renderer. */ gl.glDisable(GL10.GL_DITHER); gl.glTexEnvx(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE, GL10.GL_MODULATE); /* * Usually, the first thing one might want to do is to clear * the screen. The most efficient way of doing this is to use * glClear(). */ gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); /* * Now we're ready to draw some 3D objects */ gl.glMatrixMode(GL10.GL_MODELVIEW); gl.glLoadIdentity(); GLU.gluLookAt(gl, 0.0f, 0.0f, -2.5f, 0.0f, 0.0f, 0.0f, 0.0f, 1.0f, 0.0f); gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY); gl.glActiveTexture(GL10.GL_TEXTURE0); gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureID); gl.glTexParameterx(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_REPEAT); gl.glTexParameterx(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_REPEAT); long time = SystemClock.uptimeMillis() % 4000L; float angle = 0.090f * ((int) time); gl.glRotatef(angle, 0, 0, 1.0f); gl.glScalef(2.0f, 2.0f, 2.0f); mTriangle.draw(gl); mProjector.getCurrentModelView(gl); mLabels.beginDrawing(gl, mWidth, mHeight); drawLabel(gl, 0, mLabelA); drawLabel(gl, 1, mLabelB); drawLabel(gl, 2, mLabelC); float msPFX = mWidth - mLabels.getWidth(mLabelMsPF) - 1; mLabels.draw(gl, msPFX, 0, mLabelMsPF); mLabels.endDrawing(gl); drawMsPF(gl, msPFX); } private void drawMsPF(GL10 gl, float rightMargin) { long time = SystemClock.uptimeMillis(); if (mStartTime == 0) { mStartTime = time; } if (mFrames++ == SAMPLE_PERIOD_FRAMES) { mFrames = 0; long delta = time - mStartTime; mStartTime = time; mMsPerFrame = (int) (delta * SAMPLE_FACTOR); } if (mMsPerFrame > 0) { mNumericSprite.setValue(mMsPerFrame); float numWidth = mNumericSprite.width(); float x = rightMargin - numWidth; mNumericSprite.draw(gl, x, 0, mWidth, mHeight); } } private void drawLabel(GL10 gl, int triangleVertex, int labelId) { float x = mTriangle.getX(triangleVertex); float y = mTriangle.getY(triangleVertex); mScratch[0] = x; mScratch[1] = y; mScratch[2] = 0.0f; mScratch[3] = 1.0f; mProjector.project(mScratch, 0, mScratch, 4); float sx = mScratch[4]; float sy = mScratch[5]; float height = mLabels.getHeight(labelId); float width = mLabels.getWidth(labelId); float tx = sx - width * 0.5f; float ty = sy - height * 0.5f; mLabels.draw(gl, tx, ty, labelId); } public void sizeChanged(GL10 gl, int w, int h) { mWidth = w; mHeight = h; gl.glViewport(0, 0, w, h); mProjector.setCurrentView(0, 0, w, h); /* * Set our projection matrix. This doesn't have to be done * each time we draw, but usually a new projection needs to * be set when the viewport is resized. */ float ratio = (float) w / h; gl.glMatrixMode(GL10.GL_PROJECTION); gl.glLoadIdentity(); gl.glFrustumf(-ratio, ratio, -1, 1, 1, 10); mProjector.getCurrentProjection(gl); } private int mWidth; private int mHeight; private Context mContext; private Triangle mTriangle; private int mTextureID; private int mFrames; private int mMsPerFrame; private final static int SAMPLE_PERIOD_FRAMES = 12; private final static float SAMPLE_FACTOR = 1.0f / SAMPLE_PERIOD_FRAMES; private long mStartTime; private LabelMaker mLabels; private Paint mLabelPaint; private int mLabelA; private int mLabelB; private int mLabelC; private int mLabelMsPF; private Projector mProjector; private NumericSprite mNumericSprite; private float[] mScratch = new float[8]; } class Triangle { public Triangle() { // Buffers to be passed to gl*Pointer() functions // must be direct, i.e., they must be placed on the // native heap where the garbage collector cannot // move them. // // Buffers with multi-byte datatypes (e.g., short, int, float) // must have their byte order set to native order ByteBuffer vbb = ByteBuffer.allocateDirect(VERTS * 3 * 4); vbb.order(ByteOrder.nativeOrder()); mFVertexBuffer = vbb.asFloatBuffer(); ByteBuffer tbb = ByteBuffer.allocateDirect(VERTS * 2 * 4); tbb.order(ByteOrder.nativeOrder()); mTexBuffer = tbb.asFloatBuffer(); ByteBuffer ibb = ByteBuffer.allocateDirect(VERTS * 2); ibb.order(ByteOrder.nativeOrder()); mIndexBuffer = ibb.asShortBuffer(); for (int i = 0; i < VERTS; i++) { for(int j = 0; j < 3; j++) { mFVertexBuffer.put(sCoords[i*3+j]); } } for (int i = 0; i < VERTS; i++) { for(int j = 0; j < 2; j++) { mTexBuffer.put(sCoords[i*3+j] * 2.0f + 0.5f); } } for(int i = 0; i < VERTS; i++) { mIndexBuffer.put((short) i); } mFVertexBuffer.position(0); mTexBuffer.position(0); mIndexBuffer.position(0); } public void draw(GL10 gl) { gl.glFrontFace(GL10.GL_CCW); gl.glVertexPointer(3, GL10.GL_FLOAT, 0, mFVertexBuffer); gl.glEnable(GL10.GL_TEXTURE_2D); gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, mTexBuffer); gl.glDrawElements(GL10.GL_TRIANGLE_STRIP, VERTS, GL10.GL_UNSIGNED_SHORT, mIndexBuffer); } public float getX(int vertex) { return sCoords[3*vertex]; } public float getY(int vertex) { return sCoords[3*vertex+1]; } private final static int VERTS = 3; private FloatBuffer mFVertexBuffer; private FloatBuffer mTexBuffer; private ShortBuffer mIndexBuffer; // A unit-sided equalateral triangle centered on the origin. private final static float[] sCoords = { // X, Y, Z -0.5f, -0.25f, 0, 0.5f, -0.25f, 0, 0.0f, 0.559016994f, 0 }; }
1219806112-wangyao
Samples/OpenGLES/SpriteText/src/com/google/android/opengles/spritetext/SpriteTextRenderer.java
Java
asf20
11,162
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.opengles.triangle; import java.io.IOException; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.FloatBuffer; import java.nio.ShortBuffer; import android.content.Context; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.opengl.GLU; import android.opengl.GLUtils; import android.os.SystemClock; import javax.microedition.khronos.egl.EGL10; import javax.microedition.khronos.opengles.GL10; public class TriangleRenderer implements GLView.Renderer{ public TriangleRenderer(Context context) { mContext = context; mTriangle = new Triangle(); } public int[] getConfigSpec() { // We don't need a depth buffer, and don't care about our // color depth. int[] configSpec = { EGL10.EGL_DEPTH_SIZE, 0, EGL10.EGL_NONE }; return configSpec; } public void surfaceCreated(GL10 gl) { /* * By default, OpenGL enables features that improve quality * but reduce performance. One might want to tweak that * especially on software renderer. */ gl.glDisable(GL10.GL_DITHER); /* * Some one-time OpenGL initialization can be made here * probably based on features of this particular context */ gl.glHint(GL10.GL_PERSPECTIVE_CORRECTION_HINT, GL10.GL_FASTEST); gl.glClearColor(.5f, .5f, .5f, 1); gl.glShadeModel(GL10.GL_SMOOTH); gl.glEnable(GL10.GL_DEPTH_TEST); gl.glEnable(GL10.GL_TEXTURE_2D); /* * Create our texture. This has to be done each time the * surface is created. */ int[] textures = new int[1]; gl.glGenTextures(1, textures, 0); mTextureID = textures[0]; gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureID); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_NEAREST); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_CLAMP_TO_EDGE); gl.glTexParameterf(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_CLAMP_TO_EDGE); gl.glTexEnvf(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE, GL10.GL_REPLACE); InputStream is = mContext.getResources() .openRawResource(R.drawable.tex); Bitmap bitmap; try { bitmap = BitmapFactory.decodeStream(is); } finally { try { is.close(); } catch(IOException e) { // Ignore. } } GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bitmap, 0); bitmap.recycle(); } public void drawFrame(GL10 gl) { /* * By default, OpenGL enables features that improve quality * but reduce performance. One might want to tweak that * especially on software renderer. */ gl.glDisable(GL10.GL_DITHER); gl.glTexEnvx(GL10.GL_TEXTURE_ENV, GL10.GL_TEXTURE_ENV_MODE, GL10.GL_MODULATE); /* * Usually, the first thing one might want to do is to clear * the screen. The most efficient way of doing this is to use * glClear(). */ gl.glClear(GL10.GL_COLOR_BUFFER_BIT | GL10.GL_DEPTH_BUFFER_BIT); /* * Now we're ready to draw some 3D objects */ gl.glMatrixMode(GL10.GL_MODELVIEW); gl.glLoadIdentity(); GLU.gluLookAt(gl, 0, 0, -5, 0f, 0f, 0f, 0f, 1.0f, 0.0f); gl.glEnableClientState(GL10.GL_VERTEX_ARRAY); gl.glEnableClientState(GL10.GL_TEXTURE_COORD_ARRAY); gl.glActiveTexture(GL10.GL_TEXTURE0); gl.glBindTexture(GL10.GL_TEXTURE_2D, mTextureID); gl.glTexParameterx(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_S, GL10.GL_REPEAT); gl.glTexParameterx(GL10.GL_TEXTURE_2D, GL10.GL_TEXTURE_WRAP_T, GL10.GL_REPEAT); long time = SystemClock.uptimeMillis() % 4000L; float angle = 0.090f * ((int) time); gl.glRotatef(angle, 0, 0, 1.0f); mTriangle.draw(gl); } public void sizeChanged(GL10 gl, int w, int h) { gl.glViewport(0, 0, w, h); /* * Set our projection matrix. This doesn't have to be done * each time we draw, but usually a new projection needs to * be set when the viewport is resized. */ float ratio = (float) w / h; gl.glMatrixMode(GL10.GL_PROJECTION); gl.glLoadIdentity(); gl.glFrustumf(-ratio, ratio, -1, 1, 3, 7); } private Context mContext; private Triangle mTriangle; private int mTextureID; } class Triangle { public Triangle() { // Buffers to be passed to gl*Pointer() functions // must be direct, i.e., they must be placed on the // native heap where the garbage collector cannot // move them. // // Buffers with multi-byte datatypes (e.g., short, int, float) // must have their byte order set to native order ByteBuffer vbb = ByteBuffer.allocateDirect(VERTS * 3 * 4); vbb.order(ByteOrder.nativeOrder()); mFVertexBuffer = vbb.asFloatBuffer(); ByteBuffer tbb = ByteBuffer.allocateDirect(VERTS * 2 * 4); tbb.order(ByteOrder.nativeOrder()); mTexBuffer = tbb.asFloatBuffer(); ByteBuffer ibb = ByteBuffer.allocateDirect(VERTS * 2); ibb.order(ByteOrder.nativeOrder()); mIndexBuffer = ibb.asShortBuffer(); // A unit-sided equalateral triangle centered on the origin. float[] coords = { // X, Y, Z -0.5f, -0.25f, 0, 0.5f, -0.25f, 0, 0.0f, 0.559016994f, 0 }; for (int i = 0; i < VERTS; i++) { for(int j = 0; j < 3; j++) { mFVertexBuffer.put(coords[i*3+j] * 2.0f); } } for (int i = 0; i < VERTS; i++) { for(int j = 0; j < 2; j++) { mTexBuffer.put(coords[i*3+j] * 2.0f + 0.5f); } } for(int i = 0; i < VERTS; i++) { mIndexBuffer.put((short) i); } mFVertexBuffer.position(0); mTexBuffer.position(0); mIndexBuffer.position(0); } public void draw(GL10 gl) { gl.glFrontFace(GL10.GL_CCW); gl.glVertexPointer(3, GL10.GL_FLOAT, 0, mFVertexBuffer); gl.glEnable(GL10.GL_TEXTURE_2D); gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, mTexBuffer); gl.glDrawElements(GL10.GL_TRIANGLE_STRIP, VERTS, GL10.GL_UNSIGNED_SHORT, mIndexBuffer); } private final static int VERTS = 3; private FloatBuffer mFVertexBuffer; private FloatBuffer mTexBuffer; private ShortBuffer mIndexBuffer; }
1219806112-wangyao
Samples/OpenGLES/Triangle/src/com/google/android/opengles/triangle/TriangleRenderer.java
Java
asf20
7,690
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.opengles.triangle; import javax.microedition.khronos.opengles.GL; import android.app.Activity; import android.opengl.GLDebugHelper; import android.os.Bundle; public class TriangleActivity extends Activity { /** Set to true to enable checking of the OpenGL error code after every OpenGL call. Set to * false for faster code. * */ private final static boolean DEBUG_CHECK_GL_ERROR = true; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mGLView = (GLView) findViewById(R.id.glview); if (DEBUG_CHECK_GL_ERROR) { mGLView.setGLWrapper(new GLView.GLWrapper() { public GL wrap(GL gl) { return GLDebugHelper.wrap(gl, GLDebugHelper.CONFIG_CHECK_GL_ERROR, null); }}); } mGLView.setRenderer(new TriangleRenderer(this)); mGLView.requestFocus(); } @Override protected void onPause() { super.onPause(); mGLView.onPause(); } @Override protected void onResume() { super.onResume(); mGLView.onResume(); } private GLView mGLView; }
1219806112-wangyao
Samples/OpenGLES/Triangle/src/com/google/android/opengles/triangle/TriangleActivity.java
Java
asf20
1,848
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.opengles.triangle; import android.content.Context; import android.util.AttributeSet; import android.view.SurfaceHolder; import android.view.SurfaceView; import java.util.ArrayList; import java.util.concurrent.Semaphore; import javax.microedition.khronos.egl.EGL10; import javax.microedition.khronos.egl.EGL11; import javax.microedition.khronos.egl.EGLConfig; import javax.microedition.khronos.egl.EGLContext; import javax.microedition.khronos.egl.EGLDisplay; import javax.microedition.khronos.egl.EGLSurface; import javax.microedition.khronos.opengles.GL; import javax.microedition.khronos.opengles.GL10; /** * An implementation of SurfaceView that uses the dedicated surface for * displaying an OpenGL animation. This allows the animation to run in a * separate thread, without requiring that it be driven by the update mechanism * of the view hierarchy. * * The application-specific rendering code is delegated to a GLView.Renderer * instance. */ class GLView extends SurfaceView implements SurfaceHolder.Callback { GLView(Context context) { super(context); init(); } public GLView(Context context, AttributeSet attrs) { super(context, attrs); init(); } private void init() { // Install a SurfaceHolder.Callback so we get notified when the // underlying surface is created and destroyed mHolder = getHolder(); mHolder.addCallback(this); mHolder.setType(SurfaceHolder.SURFACE_TYPE_GPU); } public void setGLWrapper(GLWrapper glWrapper) { mGLWrapper = glWrapper; } public void setRenderer(Renderer renderer) { mGLThread = new GLThread(renderer); mGLThread.start(); } public void surfaceCreated(SurfaceHolder holder) { mGLThread.surfaceCreated(); } public void surfaceDestroyed(SurfaceHolder holder) { // Surface will be destroyed when we return mGLThread.surfaceDestroyed(); } public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) { // Surface size or format has changed. This should not happen in this // example. mGLThread.onWindowResize(w, h); } /** * Inform the view that the activity is paused. */ public void onPause() { mGLThread.onPause(); } /** * Inform the view that the activity is resumed. */ public void onResume() { mGLThread.onResume(); } /** * Inform the view that the window focus has changed. */ @Override public void onWindowFocusChanged(boolean hasFocus) { super.onWindowFocusChanged(hasFocus); mGLThread.onWindowFocusChanged(hasFocus); } /** * Queue an "event" to be run on the GL rendering thread. * @param r the runnable to be run on the GL rendering thread. */ public void queueEvent(Runnable r) { mGLThread.queueEvent(r); } @Override protected void onDetachedFromWindow() { super.onDetachedFromWindow(); mGLThread.requestExitAndWait(); } // ---------------------------------------------------------------------- public interface GLWrapper { GL wrap(GL gl); } // ---------------------------------------------------------------------- /** * A generic renderer interface. */ public interface Renderer { /** * @return the EGL configuration specification desired by the renderer. */ int[] getConfigSpec(); /** * Surface created. * Called when the surface is created. Called when the application * starts, and whenever the GPU is reinitialized. This will * typically happen when the device awakes after going to sleep. * Set your textures here. */ void surfaceCreated(GL10 gl); /** * Surface changed size. * Called after the surface is created and whenever * the OpenGL ES surface size changes. Set your viewport here. * @param gl * @param width * @param height */ void sizeChanged(GL10 gl, int width, int height); /** * Draw the current frame. * @param gl */ void drawFrame(GL10 gl); } /** * An EGL helper class. */ private class EglHelper { public EglHelper() { } /** * Initialize EGL for a given configuration spec. * @param configSpec */ public void start(int[] configSpec){ /* * Get an EGL instance */ mEgl = (EGL10) EGLContext.getEGL(); /* * Get to the default display. */ mEglDisplay = mEgl.eglGetDisplay(EGL10.EGL_DEFAULT_DISPLAY); /* * We can now initialize EGL for that display */ int[] version = new int[2]; mEgl.eglInitialize(mEglDisplay, version); EGLConfig[] configs = new EGLConfig[1]; int[] num_config = new int[1]; mEgl.eglChooseConfig(mEglDisplay, configSpec, configs, 1, num_config); mEglConfig = configs[0]; /* * Create an OpenGL ES context. This must be done only once, an * OpenGL context is a somewhat heavy object. */ mEglContext = mEgl.eglCreateContext(mEglDisplay, mEglConfig, EGL10.EGL_NO_CONTEXT, null); mEglSurface = null; } /* * Create and return an OpenGL surface */ public GL createSurface(SurfaceHolder holder) { /* * The window size has changed, so we need to create a new * surface. */ if (mEglSurface != null) { /* * Unbind and destroy the old EGL surface, if * there is one. */ mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT); mEgl.eglDestroySurface(mEglDisplay, mEglSurface); } /* * Create an EGL surface we can render into. */ mEglSurface = mEgl.eglCreateWindowSurface(mEglDisplay, mEglConfig, holder, null); /* * Before we can issue GL commands, we need to make sure * the context is current and bound to a surface. */ mEgl.eglMakeCurrent(mEglDisplay, mEglSurface, mEglSurface, mEglContext); GL gl = mEglContext.getGL(); if (mGLWrapper != null) { gl = mGLWrapper.wrap(gl); } return gl; } /** * Display the current render surface. * @return false if the context has been lost. */ public boolean swap() { mEgl.eglSwapBuffers(mEglDisplay, mEglSurface); /* * Always check for EGL_CONTEXT_LOST, which means the context * and all associated data were lost (For instance because * the device went to sleep). We need to sleep until we * get a new surface. */ return mEgl.eglGetError() != EGL11.EGL_CONTEXT_LOST; } public void finish() { if (mEglSurface != null) { mEgl.eglMakeCurrent(mEglDisplay, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_SURFACE, EGL10.EGL_NO_CONTEXT); mEgl.eglDestroySurface(mEglDisplay, mEglSurface); mEglSurface = null; } if (mEglContext != null) { mEgl.eglDestroyContext(mEglDisplay, mEglContext); mEglContext = null; } if (mEglDisplay != null) { mEgl.eglTerminate(mEglDisplay); mEglDisplay = null; } } EGL10 mEgl; EGLDisplay mEglDisplay; EGLSurface mEglSurface; EGLConfig mEglConfig; EGLContext mEglContext; } /** * A generic GL Thread. Takes care of initializing EGL and GL. Delegates * to a Renderer instance to do the actual drawing. * */ class GLThread extends Thread { GLThread(Renderer renderer) { super(); mDone = false; mWidth = 0; mHeight = 0; mRenderer = renderer; setName("GLThread"); } @Override public void run() { /* * When the android framework launches a second instance of * an activity, the new instance's onCreate() method may be * called before the first instance returns from onDestroy(). * * This semaphore ensures that only one instance at a time * accesses EGL. */ try { try { sEglSemaphore.acquire(); } catch (InterruptedException e) { return; } guardedRun(); } catch (InterruptedException e) { // fall thru and exit normally } finally { sEglSemaphore.release(); } } private void guardedRun() throws InterruptedException { mEglHelper = new EglHelper(); /* * Specify a configuration for our opengl session * and grab the first configuration that matches is */ int[] configSpec = mRenderer.getConfigSpec(); mEglHelper.start(configSpec); GL10 gl = null; boolean tellRendererSurfaceCreated = true; boolean tellRendererSurfaceChanged = true; /* * This is our main activity thread's loop, we go until * asked to quit. */ while (!mDone) { /* * Update the asynchronous state (window size) */ int w, h; boolean changed; boolean needStart = false; synchronized (this) { Runnable r; while ((r = getEvent()) != null) { r.run(); } if (mPaused) { mEglHelper.finish(); needStart = true; } if(needToWait()) { while (needToWait()) { wait(); } } if (mDone) { break; } changed = mSizeChanged; w = mWidth; h = mHeight; mSizeChanged = false; } if (needStart) { mEglHelper.start(configSpec); tellRendererSurfaceCreated = true; changed = true; } if (changed) { gl = (GL10) mEglHelper.createSurface(mHolder); tellRendererSurfaceChanged = true; } if (tellRendererSurfaceCreated) { mRenderer.surfaceCreated(gl); tellRendererSurfaceCreated = false; } if (tellRendererSurfaceChanged) { mRenderer.sizeChanged(gl, w, h); tellRendererSurfaceChanged = false; } if ((w > 0) && (h > 0)) { /* draw a frame here */ mRenderer.drawFrame(gl); /* * Once we're done with GL, we need to call swapBuffers() * to instruct the system to display the rendered frame */ mEglHelper.swap(); } } /* * clean-up everything... */ mEglHelper.finish(); } private boolean needToWait() { return (mPaused || (! mHasFocus) || (! mHasSurface) || mContextLost) && (! mDone); } public void surfaceCreated() { synchronized(this) { mHasSurface = true; mContextLost = false; notify(); } } public void surfaceDestroyed() { synchronized(this) { mHasSurface = false; notify(); } } public void onPause() { synchronized (this) { mPaused = true; } } public void onResume() { synchronized (this) { mPaused = false; notify(); } } public void onWindowFocusChanged(boolean hasFocus) { synchronized (this) { mHasFocus = hasFocus; if (mHasFocus == true) { notify(); } } } public void onWindowResize(int w, int h) { synchronized (this) { mWidth = w; mHeight = h; mSizeChanged = true; } } public void requestExitAndWait() { // don't call this from GLThread thread or it is a guaranteed // deadlock! synchronized(this) { mDone = true; notify(); } try { join(); } catch (InterruptedException ex) { Thread.currentThread().interrupt(); } } /** * Queue an "event" to be run on the GL rendering thread. * @param r the runnable to be run on the GL rendering thread. */ public void queueEvent(Runnable r) { synchronized(this) { mEventQueue.add(r); } } private Runnable getEvent() { synchronized(this) { if (mEventQueue.size() > 0) { return mEventQueue.remove(0); } } return null; } private boolean mDone; private boolean mPaused; private boolean mHasFocus; private boolean mHasSurface; private boolean mContextLost; private int mWidth; private int mHeight; private Renderer mRenderer; private ArrayList<Runnable> mEventQueue = new ArrayList<Runnable>(); private EglHelper mEglHelper; } private static final Semaphore sEglSemaphore = new Semaphore(1); private boolean mSizeChanged = true; private SurfaceHolder mHolder; private GLThread mGLThread; private GLWrapper mGLWrapper; }
1219806112-wangyao
Samples/OpenGLES/Triangle/src/com/google/android/opengles/triangle/GLView.java
Java
asf20
15,727
package com.google.android.webviewdemo; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.util.Log; import android.webkit.JsResult; import android.webkit.WebChromeClient; import android.webkit.WebSettings; import android.webkit.WebView; /** * Demonstrates how to embed a WebView in your activity. Also demonstrates how * to have javascript in the WebView call into the activity, and how the activity * can invoke javascript. * <p> * In this example, clicking on the android in the WebView will result in a call into * the activities code in {@link DemoJavaScriptInterface#clickOnAndroid()}. This code * will turn around and invoke javascript using the {@link WebView#loadUrl(String)} * method. * <p> * Obviously all of this could have been accomplished without calling into the activity * and then back into javascript, but this code is intended to show how to set up the * code paths for this sort of communication. * */ public class WebViewDemo extends Activity { private static final String LOG_TAG = "WebViewDemo"; private WebView mWebView; private Handler mHandler = new Handler(); @Override public void onCreate(Bundle icicle) { super.onCreate(icicle); setContentView(R.layout.main); mWebView = (WebView) findViewById(R.id.webview); WebSettings webSettings = mWebView.getSettings(); webSettings.setSavePassword(false); webSettings.setSaveFormData(false); webSettings.setJavaScriptEnabled(true); webSettings.setSupportZoom(false); mWebView.setWebChromeClient(new MyWebChromeClient()); mWebView.addJavascriptInterface(new DemoJavaScriptInterface(), "demo"); mWebView.loadUrl("file:///android_asset/demo.html"); } final class DemoJavaScriptInterface { DemoJavaScriptInterface() { } /** * This is not called on the UI thread. Post a runnable to invoke * loadUrl on the UI thread. */ public void clickOnAndroid() { mHandler.post(new Runnable() { public void run() { mWebView.loadUrl("javascript:wave()"); } }); } } /** * Provides a hook for calling "alert" from javascript. Useful for * debugging your javascript. */ final class MyWebChromeClient extends WebChromeClient { @Override public boolean onJsAlert(WebView view, String url, String message, JsResult result) { Log.d(LOG_TAG, message); result.confirm(); return true; } } }
1219806112-wangyao
Samples/WebViewDemo/src/com/google/android/webviewdemo/WebViewDemo.java
Java
asf20
2,659
<html> <script language="javascript"> /* This function is invoked by the activity */ function wave() { alert("1"); document.getElementById("droid").src="android_waving.png"; alert("2"); } </script> <body> <!-- Calls into the javascript interface for the activity --> <a onClick="window.demo.clickOnAndroid()"><div style="width:80px; margin:0px auto; padding:10px; text-align:center; border:2px solid #202020;" > <img id="droid" src="android_normal.png"/><br> Click me! </div></a> </body> </html>
1219806112-wangyao
Samples/WebViewDemo/assets/demo.html
HTML
asf20
552
/* * 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"; }
1219806112-wangyao
Samples/Downloader/src/com/google/android/downloader/DownloaderTest.java
Java
asf20
2,200
/* * 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"; }
1219806112-wangyao
Samples/Downloader/src/com/google/android/downloader/PreconditionActivityHelper.java
Java
asf20
2,672
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.android.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); } } }; }
1219806112-wangyao
Samples/Downloader/src/com/google/android/downloader/DownloaderActivity.java
Java
asf20
40,004
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.lolcat; import android.content.Context; import android.graphics.Bitmap; import android.graphics.Canvas; import android.graphics.Matrix; import android.graphics.Paint; import android.graphics.Rect; import android.graphics.RectF; import android.graphics.Typeface; import android.graphics.drawable.BitmapDrawable; import android.net.Uri; import android.text.TextUtils; import android.util.AttributeSet; import android.util.Log; import android.view.MotionEvent; import android.widget.ImageView; /** * Lolcat-specific subclass of ImageView, which manages the various * scaled-down Bitmaps and knows how to render and manipulate the * image captions. */ public class LolcatView extends ImageView { private static final String TAG = "LolcatView"; // Standard lolcat size is 500x375. (But to preserve the original // image's aspect ratio, we rescale so that the larger dimension ends // up being 500 pixels.) private static final float SCALED_IMAGE_MAX_DIMENSION = 500f; // Other standard lolcat image parameters private static final int FONT_SIZE = 44; private Bitmap mScaledBitmap; // The photo picked by the user, scaled-down private Bitmap mWorkingBitmap; // The Bitmap we render the caption text into // Current state of the captions. // TODO: This array currently has a hardcoded length of 2 (for "top" // and "bottom" captions), but eventually should support as many // captions as the user wants to add. private final Caption[] mCaptions = new Caption[] { new Caption(), new Caption() }; // State used while dragging a caption around private boolean mDragging; private int mDragCaptionIndex; // index of the caption (in mCaptions[]) that's being dragged private int mTouchDownX, mTouchDownY; private final Rect mInitialDragBox = new Rect(); private final Rect mCurrentDragBox = new Rect(); private final RectF mCurrentDragBoxF = new RectF(); // used in onDraw() private final RectF mTransformedDragBoxF = new RectF(); // used in onDraw() private final Rect mTmpRect = new Rect(); public LolcatView(Context context) { super(context); } public LolcatView(Context context, AttributeSet attrs) { super(context, attrs); } public LolcatView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); } public Bitmap getWorkingBitmap() { return mWorkingBitmap; } public String getTopCaption() { return mCaptions[0].caption; } public String getBottomCaption() { return mCaptions[1].caption; } /** * @return true if the user has set caption(s) for this LolcatView. */ public boolean hasValidCaption() { return !TextUtils.isEmpty(mCaptions[0].caption) || !TextUtils.isEmpty(mCaptions[1].caption); } public void clear() { mScaledBitmap = null; mWorkingBitmap = null; setImageDrawable(null); // TODO: Anything else we need to do here to release resources // associated with this object, like maybe the Bitmap that got // created by the previous setImageURI() call? } public void loadFromUri(Uri uri) { // For now, directly load the specified Uri. setImageURI(uri); // TODO: Rather than calling setImageURI() with the URI of // the (full-size) photo, it would be better to turn the URI into // a scaled-down Bitmap right here, and load *that* into ourself. // I'd do that basically the same way that ImageView.setImageURI does it: // [ . . . ] // android.graphics.BitmapFactory.nativeDecodeStream(Native Method) // android.graphics.BitmapFactory.decodeStream(BitmapFactory.java:304) // android.graphics.drawable.Drawable.createFromStream(Drawable.java:635) // android.widget.ImageView.resolveUri(ImageView.java:477) // android.widget.ImageView.setImageURI(ImageView.java:281) // [ . . . ] // But for now let's let ImageView do the work: we call setImageURI (above) // and immediately pull out a Bitmap (below). // Stash away a scaled-down bitmap. // TODO: is it safe to assume this will always be a BitmapDrawable? BitmapDrawable drawable = (BitmapDrawable) getDrawable(); Log.i(TAG, "===> current drawable: " + drawable); Bitmap fullSizeBitmap = drawable.getBitmap(); Log.i(TAG, "===> fullSizeBitmap: " + fullSizeBitmap + " dimensions: " + fullSizeBitmap.getWidth() + " x " + fullSizeBitmap.getHeight()); Bitmap.Config config = fullSizeBitmap.getConfig(); Log.i(TAG, " - config = " + config); // Standard lolcat size is 500x375. But we don't want to distort // the image if it isn't 4x3, so let's just set the larger // dimension to 500 pixels and preserve the source aspect ratio. float origWidth = fullSizeBitmap.getWidth(); float origHeight = fullSizeBitmap.getHeight(); float aspect = origWidth / origHeight; Log.i(TAG, " - aspect = " + aspect + "(" + origWidth + " x " + origHeight + ")"); float scaleFactor = ((aspect > 1.0) ? origWidth : origHeight) / SCALED_IMAGE_MAX_DIMENSION; int scaledWidth = Math.round(origWidth / scaleFactor); int scaledHeight = Math.round(origHeight / scaleFactor); mScaledBitmap = Bitmap.createScaledBitmap(fullSizeBitmap, scaledWidth, scaledHeight, true /* filter */); Log.i(TAG, " ===> mScaledBitmap: " + mScaledBitmap + " dimensions: " + mScaledBitmap.getWidth() + " x " + mScaledBitmap.getHeight()); Log.i(TAG, " isMutable = " + mScaledBitmap.isMutable()); } /** * Sets the captions for this LolcatView. */ public void setCaptions(String topCaption, String bottomCaption) { Log.i(TAG, "setCaptions: '" + topCaption + "', '" + bottomCaption + "'"); if (topCaption == null) topCaption = ""; if (bottomCaption == null) bottomCaption = ""; mCaptions[0].caption = topCaption; mCaptions[1].caption = bottomCaption; // If the user clears a caption, reset its position (so that it'll // come back in the default position if the user re-adds it.) if (TextUtils.isEmpty(mCaptions[0].caption)) { Log.i(TAG, "- invalidating position of caption 0..."); mCaptions[0].positionValid = false; } if (TextUtils.isEmpty(mCaptions[1].caption)) { Log.i(TAG, "- invalidating position of caption 1..."); mCaptions[1].positionValid = false; } // And *any* time the captions change, blow away the cached // caption bounding boxes to make sure we'll recompute them in // renderCaptions(). mCaptions[0].captionBoundingBox = null; mCaptions[1].captionBoundingBox = null; renderCaptions(mCaptions); } /** * Clears the captions for this LolcatView. */ public void clearCaptions() { setCaptions("", ""); } /** * Renders this LolcatView's current image captions into our * underlying ImageView. * * We start with a scaled-down version of the photo originally chosed * by the user (mScaledBitmap), make a mutable copy (mWorkingBitmap), * render the specified strings into the bitmap, and show the * resulting image onscreen. */ public void renderCaptions(Caption[] captions) { // TODO: handle an arbitrary array of strings, rather than // assuming "top" and "bottom" captions. String topString = captions[0].caption; boolean topStringValid = !TextUtils.isEmpty(topString); String bottomString = captions[1].caption; boolean bottomStringValid = !TextUtils.isEmpty(bottomString); Log.i(TAG, "renderCaptions: '" + topString + "', '" + bottomString + "'"); if (mScaledBitmap == null) return; // Make a fresh (mutable) copy of the scaled-down photo Bitmap, // and render the desired text into it. Bitmap.Config config = mScaledBitmap.getConfig(); Log.i(TAG, " - mScaledBitmap config = " + config); mWorkingBitmap = mScaledBitmap.copy(config, true /* isMutable */); Log.i(TAG, " ===> mWorkingBitmap: " + mWorkingBitmap + " dimensions: " + mWorkingBitmap.getWidth() + " x " + mWorkingBitmap.getHeight()); Log.i(TAG, " isMutable = " + mWorkingBitmap.isMutable()); Canvas canvas = new Canvas(mWorkingBitmap); Log.i(TAG, "- Canvas: " + canvas + " dimensions: " + canvas.getWidth() + " x " + canvas.getHeight()); Paint textPaint = new Paint(); textPaint.setAntiAlias(true); textPaint.setTextSize(FONT_SIZE); textPaint.setColor(0xFFFFFFFF); Log.i(TAG, "- Paint: " + textPaint); Typeface face = textPaint.getTypeface(); Log.i(TAG, "- default typeface: " + face); // The most standard font for lolcat captions is Impact. (Arial // Black is also common.) Unfortunately we don't have either of // these on the device by default; the closest we can do is // DroidSans-Bold: face = Typeface.DEFAULT_BOLD; Log.i(TAG, "- new face: " + face); textPaint.setTypeface(face); // Look up the positions of the captions, or if this is our very // first time rendering them, initialize the positions to default // values. final int edgeBorder = 20; final int fontHeight = textPaint.getFontMetricsInt(null); Log.i(TAG, "- fontHeight: " + fontHeight); Log.i(TAG, "- Caption positioning:"); int topX = 0; int topY = 0; if (topStringValid) { if (mCaptions[0].positionValid) { topX = mCaptions[0].xpos; topY = mCaptions[0].ypos; Log.i(TAG, " - TOP: already had a valid position: " + topX + ", " + topY); } else { // Start off with the "top" caption at the upper-left: topX = edgeBorder; topY = edgeBorder + (fontHeight * 3 / 4); mCaptions[0].setPosition(topX, topY); Log.i(TAG, " - TOP: initializing to default position: " + topX + ", " + topY); } } int bottomX = 0; int bottomY = 0; if (bottomStringValid) { if (mCaptions[1].positionValid) { bottomX = mCaptions[1].xpos; bottomY = mCaptions[1].ypos; Log.i(TAG, " - Bottom: already had a valid position: " + bottomX + ", " + bottomY); } else { // Start off with the "bottom" caption at the lower-right: final int bottomTextWidth = (int) textPaint.measureText(bottomString); Log.i(TAG, "- bottomTextWidth (" + bottomString + "): " + bottomTextWidth); bottomX = canvas.getWidth() - edgeBorder - bottomTextWidth; bottomY = canvas.getHeight() - edgeBorder; mCaptions[1].setPosition(bottomX, bottomY); Log.i(TAG, " - BOTTOM: initializing to default position: " + bottomX + ", " + bottomY); } } // Finally, render the text. // Standard lolcat captions are drawn in white with a heavy black // outline (i.e. white fill, black stroke). Our Canvas APIs can't // do this exactly, though. // We *could* get something decent-looking using a regular // drop-shadow, like this: // textPaint.setShadowLayer(3.0f, 3, 3, 0xff000000); // but instead let's simulate the "outline" style by drawing the // text 4 separate times, with the shadow in a different direction // each time. // (TODO: This is a hack, and still doesn't look as good // as a real "white fill, black stroke" style.) final float shadowRadius = 2.0f; final int shadowOffset = 2; final int shadowColor = 0xff000000; // TODO: Right now we use offsets of 2,2 / -2,2 / 2,-2 / -2,-2 . // But 2,0 / 0,2 / -2,0 / 0,-2 might look better. textPaint.setShadowLayer(shadowRadius, shadowOffset, shadowOffset, shadowColor); if (topStringValid) canvas.drawText(topString, topX, topY, textPaint); if (bottomStringValid) canvas.drawText(bottomString, bottomX, bottomY, textPaint); // textPaint.setShadowLayer(shadowRadius, -shadowOffset, shadowOffset, shadowColor); if (topStringValid) canvas.drawText(topString, topX, topY, textPaint); if (bottomStringValid) canvas.drawText(bottomString, bottomX, bottomY, textPaint); // textPaint.setShadowLayer(shadowRadius, shadowOffset, -shadowOffset, shadowColor); if (topStringValid) canvas.drawText(topString, topX, topY, textPaint); if (bottomStringValid) canvas.drawText(bottomString, bottomX, bottomY, textPaint); // textPaint.setShadowLayer(shadowRadius, -shadowOffset, -shadowOffset, shadowColor); if (topStringValid) canvas.drawText(topString, topX, topY, textPaint); if (bottomStringValid) canvas.drawText(bottomString, bottomX, bottomY, textPaint); // Stash away bounding boxes for the captions if this // is our first time rendering them. // Watch out: the x/y position we use for drawing the text is // actually the *lower* left corner of the bounding box... int textWidth, textHeight; if (topStringValid && mCaptions[0].captionBoundingBox == null) { Log.i(TAG, "- Computing initial bounding box for top caption..."); textPaint.getTextBounds(topString, 0, topString.length(), mTmpRect); textWidth = mTmpRect.width(); textHeight = mTmpRect.height(); Log.i(TAG, "- text dimensions: " + textWidth + " x " + textHeight); mCaptions[0].captionBoundingBox = new Rect(topX, topY - textHeight, topX + textWidth, topY); Log.i(TAG, "- RESULTING RECT: " + mCaptions[0].captionBoundingBox); } if (bottomStringValid && mCaptions[1].captionBoundingBox == null) { Log.i(TAG, "- Computing initial bounding box for bottom caption..."); textPaint.getTextBounds(bottomString, 0, bottomString.length(), mTmpRect); textWidth = mTmpRect.width(); textHeight = mTmpRect.height(); Log.i(TAG, "- text dimensions: " + textWidth + " x " + textHeight); mCaptions[1].captionBoundingBox = new Rect(bottomX, bottomY - textHeight, bottomX + textWidth, bottomY); Log.i(TAG, "- RESULTING RECT: " + mCaptions[1].captionBoundingBox); } // Finally, display the new Bitmap to the user: setImageBitmap(mWorkingBitmap); } @Override protected void onDraw(Canvas canvas) { Log.i(TAG, "onDraw: " + canvas); super.onDraw(canvas); if (mDragging) { Log.i(TAG, "- dragging! Drawing box at " + mCurrentDragBox); // mCurrentDragBox is in the coordinate system of our bitmap; // need to convert it into the coordinate system of the // overall LolcatView. // // To transform between coordinate systems we need to apply the // transformation described by the ImageView's matrix *and* also // account for our left and top padding. Matrix m = getImageMatrix(); mCurrentDragBoxF.set(mCurrentDragBox); m.mapRect(mTransformedDragBoxF, mCurrentDragBoxF); mTransformedDragBoxF.offset(getPaddingLeft(), getPaddingTop()); Paint p = new Paint(); p.setColor(0xFFFFFFFF); p.setStyle(Paint.Style.STROKE); p.setStrokeWidth(2f); Log.i(TAG, "- Paint: " + p); canvas.drawRect(mTransformedDragBoxF, p); } } @Override public boolean onTouchEvent(MotionEvent ev) { Log.i(TAG, "onTouchEvent: " + ev); // Watch out: ev.getX() and ev.getY() are in the // coordinate system of the entire LolcatView, although // all the positions and rects we use here (like // mCaptions[].captionBoundingBox) are relative to the bitmap // that's drawn inside the LolcatView. // // To transform between coordinate systems we need to apply the // transformation described by the ImageView's matrix *and* also // account for our left and top padding. Matrix m = getImageMatrix(); Matrix invertedMatrix = new Matrix(); m.invert(invertedMatrix); float[] pointArray = new float[] { ev.getX() - getPaddingLeft(), ev.getY() - getPaddingTop() }; Log.i(TAG, " - BEFORE: pointArray = " + pointArray[0] + ", " + pointArray[1]); // Transform the X/Y position of the DOWN event back into bitmap coords invertedMatrix.mapPoints(pointArray); Log.i(TAG, " - AFTER: pointArray = " + pointArray[0] + ", " + pointArray[1]); int eventX = (int) pointArray[0]; int eventY = (int) pointArray[1]; int action = ev.getAction(); switch (action) { case MotionEvent.ACTION_DOWN: if (mDragging) { Log.w(TAG, "Got an ACTION_DOWN, but we were already dragging!"); mDragging = false; // and continue as if we weren't already dragging... } if (!hasValidCaption()) { Log.w(TAG, "No caption(s) yet; ignoring this ACTION_DOWN event."); return true; } // See if this DOWN event hit one of the caption bounding // boxes. If so, start dragging! for (int i = 0; i < mCaptions.length; i++) { Rect boundingBox = mCaptions[i].captionBoundingBox; Log.i(TAG, " - boundingBox #" + i + ": " + boundingBox + "..."); if (boundingBox != null) { // Expand the bounding box by a fudge factor to make it // easier to hit (since touch accuracy is pretty poor on a // real device, and the captions are fairly small...) mTmpRect.set(boundingBox); final int touchPositionSlop = 40; // pixels mTmpRect.inset(-touchPositionSlop, -touchPositionSlop); Log.i(TAG, " - Checking expanded bounding box #" + i + ": " + mTmpRect + "..."); if (mTmpRect.contains(eventX, eventY)) { Log.i(TAG, " - Hit! " + mCaptions[i]); mDragging = true; mDragCaptionIndex = i; break; } } } if (!mDragging) { Log.i(TAG, "- ACTION_DOWN event didn't hit any captions; ignoring."); return true; } mTouchDownX = eventX; mTouchDownY = eventY; mInitialDragBox.set(mCaptions[mDragCaptionIndex].captionBoundingBox); mCurrentDragBox.set(mCaptions[mDragCaptionIndex].captionBoundingBox); invalidate(); return true; case MotionEvent.ACTION_MOVE: if (!mDragging) { return true; } int displacementX = eventX - mTouchDownX; int displacementY = eventY - mTouchDownY; mCurrentDragBox.set(mInitialDragBox); mCurrentDragBox.offset(displacementX, displacementY); invalidate(); return true; case MotionEvent.ACTION_UP: if (!mDragging) { return true; } mDragging = false; // Reposition the selected caption! Log.i(TAG, "- Done dragging! Repositioning caption #" + mDragCaptionIndex + ": " + mCaptions[mDragCaptionIndex]); int offsetX = eventX - mTouchDownX; int offsetY = eventY - mTouchDownY; Log.i(TAG, " - OFFSET: " + offsetX + ", " + offsetY); // Reposition the the caption we just dragged, and blow // away the cached bounding box to make sure it'll get // recomputed in renderCaptions(). mCaptions[mDragCaptionIndex].xpos += offsetX; mCaptions[mDragCaptionIndex].ypos += offsetY; mCaptions[mDragCaptionIndex].captionBoundingBox = null; Log.i(TAG, " - Updated caption: " + mCaptions[mDragCaptionIndex]); // Finally, refresh the screen. renderCaptions(mCaptions); return true; // This case isn't expected to happen. case MotionEvent.ACTION_CANCEL: if (!mDragging) { return true; } mDragging = false; // Refresh the screen. renderCaptions(mCaptions); return true; default: return super.onTouchEvent(ev); } } /** * Returns an array containing the xpos/ypos of each Caption in our * array of captions. (This method and setCaptionPositions() are used * by LolcatActivity to save and restore the activity state across * orientation changes.) */ public int[] getCaptionPositions() { // TODO: mCaptions currently has a hardcoded length of 2 (for // "top" and "bottom" captions). int[] captionPositions = new int[4]; if (mCaptions[0].positionValid) { captionPositions[0] = mCaptions[0].xpos; captionPositions[1] = mCaptions[0].ypos; } else { captionPositions[0] = -1; captionPositions[1] = -1; } if (mCaptions[1].positionValid) { captionPositions[2] = mCaptions[1].xpos; captionPositions[3] = mCaptions[1].ypos; } else { captionPositions[2] = -1; captionPositions[3] = -1; } Log.i(TAG, "getCaptionPositions: returning " + captionPositions); return captionPositions; } /** * Sets the xpos and ypos values of each Caption in our array based on * the specified values. (This method and getCaptionPositions() are * used by LolcatActivity to save and restore the activity state * across orientation changes.) */ public void setCaptionPositions(int[] captionPositions) { // TODO: mCaptions currently has a hardcoded length of 2 (for // "top" and "bottom" captions). Log.i(TAG, "setCaptionPositions(" + captionPositions + ")..."); if (captionPositions[0] < 0) { mCaptions[0].positionValid = false; Log.i(TAG, "- TOP caption: no valid position"); } else { mCaptions[0].setPosition(captionPositions[0], captionPositions[1]); Log.i(TAG, "- TOP caption: got valid position: " + mCaptions[0].xpos + ", " + mCaptions[0].ypos); } if (captionPositions[2] < 0) { mCaptions[1].positionValid = false; Log.i(TAG, "- BOTTOM caption: no valid position"); } else { mCaptions[1].setPosition(captionPositions[2], captionPositions[3]); Log.i(TAG, "- BOTTOM caption: got valid position: " + mCaptions[1].xpos + ", " + mCaptions[1].ypos); } // Finally, refresh the screen. renderCaptions(mCaptions); } /** * Structure used to hold the entire state of a single caption. */ class Caption { public String caption; public Rect captionBoundingBox; // updated by renderCaptions() public int xpos, ypos; public boolean positionValid; public void setPosition(int x, int y) { positionValid = true; xpos = x; ypos = y; // Also blow away the cached bounding box, to make sure it'll // get recomputed in renderCaptions(). captionBoundingBox = null; } @Override public String toString() { return "Caption['" + caption + "'; bbox " + captionBoundingBox + "; pos " + xpos + ", " + ypos + "; posValid = " + positionValid + "]"; } } }
1219806112-wangyao
LolcatBuilder/src/com/android/lolcat/LolcatView.java
Java
asf20
25,915
/* * Copyright (C) 2008 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.android.lolcat; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.ProgressDialog; import android.content.DialogInterface; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.drawable.Drawable; import android.media.MediaScannerConnection; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.text.TextUtils; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStream; /** * Lolcat builder activity. * * Instructions: * (1) Take photo of cat using Camera * (2) Run LolcatActivity * (3) Pick photo * (4) Add caption(s) * (5) Save and share * * See README.txt for a list of currently-missing features and known bugs. */ public class LolcatActivity extends Activity implements View.OnClickListener { private static final String TAG = "LolcatActivity"; // Location on the SD card for saving lolcat images private static final String LOLCAT_SAVE_DIRECTORY = "lolcats/"; // Mime type / format / extension we use (must be self-consistent!) private static final String SAVED_IMAGE_EXTENSION = ".png"; private static final Bitmap.CompressFormat SAVED_IMAGE_COMPRESS_FORMAT = Bitmap.CompressFormat.PNG; private static final String SAVED_IMAGE_MIME_TYPE = "image/png"; // UI Elements private Button mPickButton; private Button mCaptionButton; private Button mSaveButton; private Button mClearCaptionButton; private Button mClearPhotoButton; private LolcatView mLolcatView; private AlertDialog mCaptionDialog; private ProgressDialog mSaveProgressDialog; private AlertDialog mSaveSuccessDialog; private Handler mHandler; private Uri mPhotoUri; private String mSavedImageFilename; private Uri mSavedImageUri; private MediaScannerConnection mMediaScannerConnection; // Request codes used with startActivityForResult() private static final int PHOTO_PICKED = 1; // Dialog IDs private static final int DIALOG_CAPTION = 1; private static final int DIALOG_SAVE_PROGRESS = 2; private static final int DIALOG_SAVE_SUCCESS = 3; // Keys used with onSaveInstanceState() private static final String PHOTO_URI_KEY = "photo_uri"; private static final String SAVED_IMAGE_FILENAME_KEY = "saved_image_filename"; private static final String SAVED_IMAGE_URI_KEY = "saved_image_uri"; private static final String TOP_CAPTION_KEY = "top_caption"; private static final String BOTTOM_CAPTION_KEY = "bottom_caption"; private static final String CAPTION_POSITIONS_KEY = "caption_positions"; @Override protected void onCreate(Bundle icicle) { Log.i(TAG, "onCreate()... icicle = " + icicle); super.onCreate(icicle); setContentView(R.layout.lolcat_activity); // Look up various UI elements mPickButton = (Button) findViewById(R.id.pick_button); mPickButton.setOnClickListener(this); mCaptionButton = (Button) findViewById(R.id.caption_button); mCaptionButton.setOnClickListener(this); mSaveButton = (Button) findViewById(R.id.save_button); mSaveButton.setOnClickListener(this); mClearCaptionButton = (Button) findViewById(R.id.clear_caption_button); // This button doesn't exist in portrait mode. if (mClearCaptionButton != null) mClearCaptionButton.setOnClickListener(this); mClearPhotoButton = (Button) findViewById(R.id.clear_photo_button); mClearPhotoButton.setOnClickListener(this); mLolcatView = (LolcatView) findViewById(R.id.main_image); // Need one of these to call back to the UI thread // (and run AlertDialog.show(), for that matter) mHandler = new Handler(); mMediaScannerConnection = new MediaScannerConnection(this, mMediaScanConnClient); if (icicle != null) { Log.i(TAG, "- reloading state from icicle!"); restoreStateFromIcicle(icicle); } } @Override protected void onResume() { Log.i(TAG, "onResume()..."); super.onResume(); updateButtons(); } @Override protected void onSaveInstanceState(Bundle outState) { Log.i(TAG, "onSaveInstanceState()..."); super.onSaveInstanceState(outState); // State from the Activity: outState.putParcelable(PHOTO_URI_KEY, mPhotoUri); outState.putString(SAVED_IMAGE_FILENAME_KEY, mSavedImageFilename); outState.putParcelable(SAVED_IMAGE_URI_KEY, mSavedImageUri); // State from the LolcatView: // (TODO: Consider making Caption objects, or even the LolcatView // itself, Parcelable? Probably overkill, though...) outState.putString(TOP_CAPTION_KEY, mLolcatView.getTopCaption()); outState.putString(BOTTOM_CAPTION_KEY, mLolcatView.getBottomCaption()); outState.putIntArray(CAPTION_POSITIONS_KEY, mLolcatView.getCaptionPositions()); } /** * Restores the activity state from the specified icicle. * @see onCreate() * @see onSaveInstanceState() */ private void restoreStateFromIcicle(Bundle icicle) { Log.i(TAG, "restoreStateFromIcicle()..."); // State of the Activity: Uri photoUri = icicle.getParcelable(PHOTO_URI_KEY); Log.i(TAG, " - photoUri: " + photoUri); if (photoUri != null) { loadPhoto(photoUri); } mSavedImageFilename = icicle.getString(SAVED_IMAGE_FILENAME_KEY); mSavedImageUri = icicle.getParcelable(SAVED_IMAGE_URI_KEY); // State of the LolcatView: String topCaption = icicle.getString(TOP_CAPTION_KEY); String bottomCaption = icicle.getString(BOTTOM_CAPTION_KEY); int[] captionPositions = icicle.getIntArray(CAPTION_POSITIONS_KEY); Log.i(TAG, " - captions: '" + topCaption + "', '" + bottomCaption + "'"); if (!TextUtils.isEmpty(topCaption) || !TextUtils.isEmpty(bottomCaption)) { mLolcatView.setCaptions(topCaption, bottomCaption); mLolcatView.setCaptionPositions(captionPositions); } } @Override protected void onDestroy() { Log.i(TAG, "onDestroy()..."); super.onDestroy(); clearPhoto(); // Free up some resources, and force a GC } // View.OnClickListener implementation public void onClick(View view) { int id = view.getId(); Log.i(TAG, "onClick(View " + view + ", id " + id + ")..."); switch (id) { case R.id.pick_button: Log.i(TAG, "onClick: pick_button..."); Intent intent = new Intent(Intent.ACTION_GET_CONTENT, null); intent.setType("image/*"); // Note: we could have the "crop" UI come up here by // default by doing this: // intent.putExtra("crop", "true"); // (But watch out: if you do that, the Intent that comes // back to onActivityResult() will have the URI (of the // cropped image) in the "action" field, not the "data" // field!) startActivityForResult(intent, PHOTO_PICKED); break; case R.id.caption_button: Log.i(TAG, "onClick: caption_button..."); showCaptionDialog(); break; case R.id.save_button: Log.i(TAG, "onClick: save_button..."); saveImage(); break; case R.id.clear_caption_button: Log.i(TAG, "onClick: clear_caption_button..."); clearCaptions(); updateButtons(); break; case R.id.clear_photo_button: Log.i(TAG, "onClick: clear_photo_button..."); clearPhoto(); // Also does clearCaptions() updateButtons(); break; default: Log.w(TAG, "Click from unexpected source: " + view + ", id " + id); break; } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { Log.i(TAG, "onActivityResult(request " + requestCode + ", result " + resultCode + ", data " + data + ")..."); if (resultCode != RESULT_OK) { Log.i(TAG, "==> result " + resultCode + " from subactivity! Ignoring..."); Toast t = Toast.makeText(this, R.string.lolcat_nothing_picked, Toast.LENGTH_SHORT); t.show(); return; } if (requestCode == PHOTO_PICKED) { // "data" is an Intent containing (presumably) a URI like // "content://media/external/images/media/3". if (data == null) { Log.w(TAG, "Null data, but RESULT_OK, from image picker!"); Toast t = Toast.makeText(this, R.string.lolcat_nothing_picked, Toast.LENGTH_SHORT); t.show(); return; } if (data.getData() == null) { Log.w(TAG, "'data' intent from image picker contained no data!"); Toast t = Toast.makeText(this, R.string.lolcat_nothing_picked, Toast.LENGTH_SHORT); t.show(); return; } loadPhoto(data.getData()); updateButtons(); } } /** * Updates the enabled/disabled state of the onscreen buttons. */ private void updateButtons() { Log.i(TAG, "updateButtons()..."); // mPickButton is always enabled. // Do we have a valid photo and/or caption(s) yet? Drawable d = mLolcatView.getDrawable(); // Log.i(TAG, "===> current mLolcatView drawable: " + d); boolean validPhoto = (d != null); boolean validCaption = mLolcatView.hasValidCaption(); mCaptionButton.setText(validCaption ? R.string.lolcat_change_captions : R.string.lolcat_add_captions); mCaptionButton.setEnabled(validPhoto); mSaveButton.setEnabled(validPhoto && validCaption); if (mClearCaptionButton != null) { mClearCaptionButton.setEnabled(validPhoto && validCaption); } mClearPhotoButton.setEnabled(validPhoto); } /** * Clears out any already-entered captions for this lolcat. */ private void clearCaptions() { mLolcatView.clearCaptions(); // Clear the text fields in the caption dialog too. if (mCaptionDialog != null) { EditText topText = (EditText) mCaptionDialog.findViewById(R.id.top_edittext); topText.setText(""); EditText bottomText = (EditText) mCaptionDialog.findViewById(R.id.bottom_edittext); bottomText.setText(""); topText.requestFocus(); } // This also invalidates any image we've previously written to the // SD card... mSavedImageFilename = null; mSavedImageUri = null; } /** * Completely resets the UI to its initial state, with no photo * loaded, and no captions. */ private void clearPhoto() { mLolcatView.clear(); mPhotoUri = null; mSavedImageFilename = null; mSavedImageUri = null; clearCaptions(); // Force a gc (to be sure to reclaim the memory used by our // potentially huge bitmap): System.gc(); } /** * Loads the image with the specified Uri into the UI. */ private void loadPhoto(Uri uri) { Log.i(TAG, "loadPhoto: uri = " + uri); clearPhoto(); // Be sure to release the previous bitmap // before creating another one mPhotoUri = uri; // A new photo always starts out uncaptioned. clearCaptions(); // Load the selected photo into our ImageView. mLolcatView.loadFromUri(mPhotoUri); } private void showCaptionDialog() { // If the dialog already exists, always reset focus to the top // item each time it comes up. if (mCaptionDialog != null) { EditText topText = (EditText) mCaptionDialog.findViewById(R.id.top_edittext); topText.requestFocus(); } showDialog(DIALOG_CAPTION); } private void showSaveSuccessDialog() { // If the dialog already exists, update the body text based on the // current values of mSavedImageFilename and mSavedImageUri // (otherwise the dialog will still have the body text from when // it was first created!) if (mSaveSuccessDialog != null) { updateSaveSuccessDialogBody(); } showDialog(DIALOG_SAVE_SUCCESS); } private void updateSaveSuccessDialogBody() { if (mSaveSuccessDialog == null) { throw new IllegalStateException( "updateSaveSuccessDialogBody: mSaveSuccessDialog hasn't been created yet"); } String dialogBody = String.format( getResources().getString(R.string.lolcat_save_succeeded_dialog_body_format), mSavedImageFilename, mSavedImageUri); mSaveSuccessDialog.setMessage(dialogBody); } @Override protected Dialog onCreateDialog(int id) { Log.i(TAG, "onCreateDialog(id " + id + ")..."); // This is only run once (per dialog), the very first time // a given dialog needs to be shown. switch (id) { case DIALOG_CAPTION: LayoutInflater factory = LayoutInflater.from(this); final View textEntryView = factory.inflate(R.layout.lolcat_caption_dialog, null); mCaptionDialog = new AlertDialog.Builder(this) .setTitle(R.string.lolcat_caption_dialog_title) .setIcon(0) .setView(textEntryView) .setPositiveButton( R.string.lolcat_caption_dialog_ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Log.i(TAG, "Caption dialog: OK..."); updateCaptionsFromDialog(); } }) .setNegativeButton( R.string.lolcat_caption_dialog_cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Log.i(TAG, "Caption dialog: CANCEL..."); // Nothing to do here (for now at least) } }) .create(); return mCaptionDialog; case DIALOG_SAVE_PROGRESS: mSaveProgressDialog = new ProgressDialog(this); mSaveProgressDialog.setMessage(getResources().getString(R.string.lolcat_saving)); mSaveProgressDialog.setIndeterminate(true); mSaveProgressDialog.setCancelable(false); return mSaveProgressDialog; case DIALOG_SAVE_SUCCESS: mSaveSuccessDialog = new AlertDialog.Builder(this) .setTitle(R.string.lolcat_save_succeeded_dialog_title) .setIcon(0) .setPositiveButton( R.string.lolcat_save_succeeded_dialog_view, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Log.i(TAG, "Save dialog: View..."); viewSavedImage(); } }) .setNeutralButton( R.string.lolcat_save_succeeded_dialog_share, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Log.i(TAG, "Save dialog: Share..."); shareSavedImage(); } }) .setNegativeButton( R.string.lolcat_save_succeeded_dialog_cancel, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { Log.i(TAG, "Save dialog: CANCEL..."); // Nothing to do here... } }) .create(); updateSaveSuccessDialogBody(); return mSaveSuccessDialog; default: Log.w(TAG, "Request for unexpected dialog id: " + id); break; } return null; } private void updateCaptionsFromDialog() { Log.i(TAG, "updateCaptionsFromDialog()..."); if (mCaptionDialog == null) { Log.w(TAG, "updateCaptionsFromDialog: null mCaptionDialog!"); return; } // Get the two caption strings: EditText topText = (EditText) mCaptionDialog.findViewById(R.id.top_edittext); Log.i(TAG, "- Top editText: " + topText); String topString = topText.getText().toString(); Log.i(TAG, " - String: '" + topString + "'"); EditText bottomText = (EditText) mCaptionDialog.findViewById(R.id.bottom_edittext); Log.i(TAG, "- Bottom editText: " + bottomText); String bottomString = bottomText.getText().toString(); Log.i(TAG, " - String: '" + bottomString + "'"); mLolcatView.setCaptions(topString, bottomString); updateButtons(); } /** * Kicks off the process of saving the LolcatView's working Bitmap to * the SD card, in preparation for viewing it later and/or sharing it. */ private void saveImage() { Log.i(TAG, "saveImage()..."); // First of all, bring up a progress dialog. showDialog(DIALOG_SAVE_PROGRESS); // We now need to save the bitmap to the SD card, and then ask the // MediaScanner to scan it. Do the actual work of all this in a // helper thread, since it's fairly slow (and will occasionally // ANR if we do it here in the UI thread.) Thread t = new Thread() { public void run() { Log.i(TAG, "Running worker thread..."); saveImageInternal(); } }; t.start(); // Next steps: // - saveImageInternal() // - onMediaScannerConnected() // - onScanCompleted } /** * Saves the LolcatView's working Bitmap to the SD card, in * preparation for viewing it later and/or sharing it. * * The bitmap will be saved as a new file in the directory * LOLCAT_SAVE_DIRECTORY, with an automatically-generated filename * based on the current time. It also connects to the * MediaScanner service, since we'll need to scan that new file (in * order to get a Uri we can then VIEW or share.) * * This method is run in a worker thread; @see saveImage(). */ private void saveImageInternal() { Log.i(TAG, "saveImageInternal()..."); // TODO: Currently we save the bitmap to a file on the sdcard, // then ask the MediaScanner to scan it (which gives us a Uri we // can then do an ACTION_VIEW on.) But rather than doing these // separate steps, maybe there's some easy way (given an // OutputStream) to directly talk to the MediaProvider // (i.e. com.android.provider.MediaStore) and say "here's an // image, please save it somwhere and return the URI to me"... // Save the bitmap to a file on the sdcard. // (Based on similar code in MusicUtils.java.) // TODO: Make this filename more human-readable? Maybe "Lolcat-YYYY-MM-DD-HHMMSS.png"? String filename = Environment.getExternalStorageDirectory() + "/" + LOLCAT_SAVE_DIRECTORY + String.valueOf(System.currentTimeMillis() + SAVED_IMAGE_EXTENSION); Log.i(TAG, "- filename: '" + filename + "'"); if (ensureFileExists(filename)) { try { OutputStream outstream = new FileOutputStream(filename); Bitmap bitmap = mLolcatView.getWorkingBitmap(); boolean success = bitmap.compress(SAVED_IMAGE_COMPRESS_FORMAT, 100, outstream); Log.i(TAG, "- success code from Bitmap.compress: " + success); outstream.close(); if (success) { Log.i(TAG, "- Saved! filename = " + filename); mSavedImageFilename = filename; // Ok, now we need to get the MediaScanner to scan the // file we just wrote. Step 1 is to get our // MediaScannerConnection object to connect to the // MediaScanner service. mMediaScannerConnection.connect(); // See onMediaScannerConnected() for the next step } else { Log.w(TAG, "Bitmap.compress failed: bitmap " + bitmap + ", filename '" + filename + "'"); onSaveFailed(R.string.lolcat_save_failed); } } catch (FileNotFoundException e) { Log.w(TAG, "error creating file", e); onSaveFailed(R.string.lolcat_save_failed); } catch (IOException e) { Log.w(TAG, "error creating file", e); onSaveFailed(R.string.lolcat_save_failed); } } else { Log.w(TAG, "ensureFileExists failed for filename '" + filename + "'"); onSaveFailed(R.string.lolcat_save_failed); } } // // MediaScanner-related code // /** * android.media.MediaScannerConnection.MediaScannerConnectionClient implementation. */ private MediaScannerConnection.MediaScannerConnectionClient mMediaScanConnClient = new MediaScannerConnection.MediaScannerConnectionClient() { /** * Called when a connection to the MediaScanner service has been established. */ public void onMediaScannerConnected() { Log.i(TAG, "MediaScannerConnectionClient.onMediaScannerConnected..."); // The next step happens in the UI thread: mHandler.post(new Runnable() { public void run() { LolcatActivity.this.onMediaScannerConnected(); } }); } /** * Called when the media scanner has finished scanning a file. * @param path the path to the file that has been scanned. * @param uri the Uri for the file if the scanning operation succeeded * and the file was added to the media database, or null if scanning failed. */ public void onScanCompleted(final String path, final Uri uri) { Log.i(TAG, "MediaScannerConnectionClient.onScanCompleted: path " + path + ", uri " + uri); // Just run the "real" onScanCompleted() method in the UI thread: mHandler.post(new Runnable() { public void run() { LolcatActivity.this.onScanCompleted(path, uri); } }); } }; /** * This method is called when our MediaScannerConnection successfully * connects to the MediaScanner service. At that point we fire off a * request to scan the lolcat image we just saved. * * This needs to run in the UI thread, so it's called from * mMediaScanConnClient's onMediaScannerConnected() method via our Handler. */ private void onMediaScannerConnected() { Log.i(TAG, "onMediaScannerConnected()..."); // Update the message in the progress dialog... mSaveProgressDialog.setMessage(getResources().getString(R.string.lolcat_scanning)); // Fire off a request to the MediaScanner service to scan this // file; we'll get notified when the scan completes. Log.i(TAG, "- Requesting scan for file: " + mSavedImageFilename); mMediaScannerConnection.scanFile(mSavedImageFilename, null /* mimeType */); // Next step: mMediaScanConnClient will get an onScanCompleted() callback, // which calls our own onScanCompleted() method via our Handler. } /** * Updates the UI after the media scanner finishes the scanFile() * request we issued from onMediaScannerConnected(). * * This needs to run in the UI thread, so it's called from * mMediaScanConnClient's onScanCompleted() method via our Handler. */ private void onScanCompleted(String path, final Uri uri) { Log.i(TAG, "onScanCompleted: path " + path + ", uri " + uri); mMediaScannerConnection.disconnect(); if (uri == null) { Log.w(TAG, "onScanCompleted: scan failed."); mSavedImageUri = null; onSaveFailed(R.string.lolcat_scan_failed); return; } // Success! dismissDialog(DIALOG_SAVE_PROGRESS); // We can now access the saved lolcat image using the specified Uri. mSavedImageUri = uri; // Bring up a success dialog, giving the user the option to go to // the pictures app (so you can share the image). showSaveSuccessDialog(); } // // Other misc utility methods // /** * Ensure that the specified file exists on the SD card, creating it * if necessary. * * Copied from MediaProvider / MusicUtils. * * @return true if the file already exists, or we * successfully created it. */ private static boolean ensureFileExists(String path) { File file = new File(path); if (file.exists()) { return true; } else { // we will not attempt to create the first directory in the path // (for example, do not create /sdcard if the SD card is not mounted) int secondSlash = path.indexOf('/', 1); if (secondSlash < 1) return false; String directoryPath = path.substring(0, secondSlash); File directory = new File(directoryPath); if (!directory.exists()) return false; file.getParentFile().mkdirs(); try { return file.createNewFile(); } catch (IOException ioe) { Log.w(TAG, "File creation failed", ioe); } return false; } } /** * Updates the UI after a failure anywhere in the bitmap saving / scanning * sequence. */ private void onSaveFailed(int errorMessageResId) { dismissDialog(DIALOG_SAVE_PROGRESS); Toast.makeText(this, errorMessageResId, Toast.LENGTH_SHORT).show(); } /** * Goes to the Pictures app for the specified URI. */ private void viewSavedImage(Uri uri) { Log.i(TAG, "viewSavedImage(" + uri + ")..."); if (uri == null) { Log.w(TAG, "viewSavedImage: null uri!"); return; } Intent intent = new Intent(Intent.ACTION_VIEW, uri); Log.i(TAG, "- running startActivity... Intent = " + intent); startActivity(intent); } private void viewSavedImage() { viewSavedImage(mSavedImageUri); } /** * Shares the image with the specified URI. */ private void shareSavedImage(Uri uri) { Log.i(TAG, "shareSavedImage(" + uri + ")..."); if (uri == null) { Log.w(TAG, "shareSavedImage: null uri!"); return; } Intent intent = new Intent(); intent.setAction(Intent.ACTION_SEND); intent.setType(SAVED_IMAGE_MIME_TYPE); intent.putExtra(Intent.EXTRA_STREAM, uri); try { startActivity( Intent.createChooser( intent, getResources().getString(R.string.lolcat_sendImage_label))); } catch (android.content.ActivityNotFoundException ex) { Log.w(TAG, "shareSavedImage: startActivity failed", ex); Toast.makeText(this, R.string.lolcat_share_failed, Toast.LENGTH_SHORT).show(); } } private void shareSavedImage() { shareSavedImage(mSavedImageUri); } }
1219806112-wangyao
LolcatBuilder/src/com/android/lolcat/LolcatActivity.java
Java
asf20
30,490
/* * Copyright (c) 2011 * Spoken Language Systems Group * MIT Computer Science and Artificial Intelligence Laboratory * Massachusetts Institute of Technology * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package edu.mit.csail.wami.client { import edu.mit.csail.wami.audio.AudioFormat; import edu.mit.csail.wami.utils.External; import flash.media.Microphone; import flash.utils.ByteArray; import flash.utils.Endian; /** * A class documents the possible parameters and sets a few defaults. * The defaults are set up to stream to localhost. */ public class WamiParams { private var mic:Microphone; // Show the debug interface. public var visible:Boolean = true; // Append this many milliseconds of audio before // and after calls to startRecording/stopRecording. public var paddingMillis:uint = 250; // Send the audio using multiple HTTP Posts. public var stream:Boolean = false; // The URLs used in the debugging interface. public var testRecordUrl:String = "https://wami-recorder.appspot.com/audio"; public var testPlayUrl:String = "https://wami-recorder.appspot.com/audio"; // Callbacks for loading the client. public var loadedCallback:String; public var format:AudioFormat; public function WamiParams(params:Object):void { mic = Microphone.getMicrophone(); External.addCallback("setSettings", setSettings); External.addCallback("getSettings", getSettings); if (params.stream != undefined) { stream = params.stream == "true"; } if (params.visible != undefined) { visible = params.visible == "true"; } if (params.console != undefined) { External.debugToConsole = params.console == "true"; } // Override to allow recording at 8000 and 16000 as well. // Note that playback at these sample-rates will be sped up. if (params.allrates != undefined) { AudioFormat.allrates = params.allrates == "true"; } loadedCallback = params.loadedCallback; var rate:uint = 22050; if (params.rate != undefined) { rate = uint(params.rate); } format = new AudioFormat(rate, 1, 16, Endian.LITTLE_ENDIAN); } public function getMicrophone():Microphone { return mic; } // Settings (including microphone security) are passed back here. internal function getSettings():Object { var json:Object = { "container" : (stream) ? "au" : "wav", "encoding" : "pcm", "signed" : true, "sampleSize" : format.bits, "bigEndian" : format.endian == Endian.BIG_ENDIAN, "sampleRate" : format.rate, "numChannels" : format.channels, "interleaved" : true, "microphone" : { "granted" : (mic != null && !mic.muted) } }; return json; } internal function setSettings(json:Object):void { if (json) { // For now the type also specifies streaming or not. if (json.container == "au") { stream = true; } else if (json.container == "wav") { stream = false; } if (json.encoding) { throw new Error("Encodings such as mu-law could be implemented."); } if (json.signed) { throw new Error("Not implemented yet."); } if (json.bigEndian) { throw new Error("Automatically determined."); } if (json.numChannels) { format.channels = json.numChannels; } if (json.sampleSize) { format.bits = json.sampleSize; } if (json.interleaved) { throw new Error("Always true."); } if (json.microphone) { throw new Error("Only the user can change the microphone security settings."); } if (json.sampleRate) { format.rate = json.sampleRate; } } } } }
10sexcoil-gmail
src/edu/mit/csail/wami/client/WamiParams.as
ActionScript
mit
4,788
/* * Copyright (c) 2011 * Spoken Language Systems Group * MIT Computer Science and Artificial Intelligence Laboratory * Massachusetts Institute of Technology * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package edu.mit.csail.wami.client { import edu.mit.csail.wami.utils.External; import edu.mit.csail.wami.utils.StateListener; /** * Translates audio events into Javascript callbacks. */ public class WamiListener implements StateListener { private var startCallback:String, finishedCallback:String, failedCallback:String; function WamiListener(startCallback:String, finishedCallback:String, failedCallback:String) { this.startCallback = startCallback; this.finishedCallback = finishedCallback; this.failedCallback = failedCallback; } public function started():void { External.call(startCallback); } public function finished():void { External.call(finishedCallback); } public function failed(error:Error):void { External.call(failedCallback, error.message); } } }
10sexcoil-gmail
src/edu/mit/csail/wami/client/WamiListener.as
ActionScript
mit
2,051
/* * Copyright (c) 2011 * Spoken Language Systems Group * MIT Computer Science and Artificial Intelligence Laboratory * Massachusetts Institute of Technology * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package edu.mit.csail.wami.client { import edu.mit.csail.wami.play.IPlayer; import edu.mit.csail.wami.play.WamiPlayer; import edu.mit.csail.wami.record.IRecorder; import edu.mit.csail.wami.record.WamiRecorder; import edu.mit.csail.wami.utils.External; import flash.display.MovieClip; public class WamiAudio extends MovieClip { private var recorder:IRecorder; private var player:IPlayer; private var checkSettingsIntervalID:int = 0; private var checkSettingsInterval:int = 1000; function WamiAudio(params:WamiParams) { recorder = new WamiRecorder(params.getMicrophone(), params); player = new WamiPlayer(); External.addCallback("startListening", startListening); External.addCallback("stopListening", stopListening); External.addCallback("startRecording", startRecording); External.addCallback("stopRecording",stopRecording); External.addCallback("getRecordingLevel", getRecordingLevel); External.addCallback("startPlaying",startPlaying); External.addCallback("stopPlaying",stopPlaying); External.addCallback("getPlayingLevel", getPlayingLevel); } internal function startPlaying(url:String, startedCallback:String = null, finishedCallback:String = null, failedCallback:String = null):void { recorder.stop(true); player.start(url, new WamiListener(startedCallback, finishedCallback, failedCallback)); } internal function stopPlaying():void { player.stop(); } internal function getPlayingLevel():int { return player.level(); } private function startListening(paddingMillis:uint = 200):void { recorder.listen(paddingMillis); } private function stopListening():void { recorder.unlisten(); } internal function startRecording(url:String, startedCallback:String = null, finishedCallback:String = null, failedCallback:String = null):void { recorder.start(url, new WamiListener(startedCallback, finishedCallback, failedCallback)); } internal function stopRecording():void { recorder.stop(); } internal function getRecordingLevel():int { return recorder.level(); } } }
10sexcoil-gmail
src/edu/mit/csail/wami/client/WamiAudio.as
ActionScript
mit
3,423
/* * Copyright (c) 2011 * Spoken Language Systems Group * MIT Computer Science and Artificial Intelligence Laboratory * Massachusetts Institute of Technology * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package edu.mit.csail.wami.play { import edu.mit.csail.wami.audio.AuContainer; import edu.mit.csail.wami.audio.DecodePipe; import edu.mit.csail.wami.audio.IAudioContainer; import edu.mit.csail.wami.audio.WaveContainer; import edu.mit.csail.wami.utils.BytePipe; import edu.mit.csail.wami.utils.External; import edu.mit.csail.wami.utils.Pipe; import edu.mit.csail.wami.utils.StateListener; import flash.events.Event; import flash.events.HTTPStatusEvent; import flash.events.IOErrorEvent; import flash.events.ProgressEvent; import flash.events.SampleDataEvent; import flash.events.SecurityErrorEvent; import flash.media.Sound; import flash.media.SoundChannel; import flash.net.URLLoader; import flash.net.URLLoaderDataFormat; import flash.net.URLRequest; import flash.net.URLRequestMethod; import flash.utils.ByteArray; public class WamiPlayer implements IPlayer { private var currentChannel:SoundChannel = null; private var currentAudio:ByteArray; private var listener:StateListener; public function start(url:String, listener:StateListener):void { this.listener = listener; var loader:URLLoader = new URLLoader(); loader.dataFormat = URLLoaderDataFormat.BINARY; loader.addEventListener(Event.COMPLETE, completeHandler); loader.addEventListener(Event.OPEN, openHandler); loader.addEventListener(ProgressEvent.PROGRESS, progressHandler); loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler); loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler); loader.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler); var request:URLRequest = new URLRequest(url); request.method = URLRequestMethod.GET; try { loader.load(request); } catch (error:Error) { listener.failed(error); } function completeHandler(event:Event):void { listener.started(); loader.removeEventListener(Event.COMPLETE, completeHandler); loader.removeEventListener(Event.OPEN, openHandler); loader.removeEventListener(ProgressEvent.PROGRESS, progressHandler); loader.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler); loader.removeEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler); loader.removeEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler) play(loader.data); } function openHandler(event:Event):void { External.debug("openHandler: " + event); } function progressHandler(event:ProgressEvent):void { //External.debug("progressHandler loaded:" + event.bytesLoaded + " total: " + event.bytesTotal); } function securityErrorHandler(event:SecurityErrorEvent):void { listener.failed(new Error("Security error while playing: " + event.errorID)); } function httpStatusHandler(event:HTTPStatusEvent):void { External.debug("httpStatusHandler: " + event); } function ioErrorHandler(event:IOErrorEvent):void { listener.failed(new Error("IO error while playing: " + event.errorID)); } } public function stop():void { if (currentChannel != null) { External.debug("Stop playing."); currentChannel.removeEventListener(Event.SOUND_COMPLETE, stop); currentChannel.stop(); External.debug("Listener finished."); listener.finished(); currentChannel = null; } } public function level():int { if (currentChannel != null) { return 100 * ((currentChannel.leftPeak + currentChannel.rightPeak) / 2.0); } return 0; } protected function play(audio:ByteArray):void { stop(); // Make sure we're stopped var containers:Vector.<IAudioContainer> = new Vector.<IAudioContainer>(); containers.push(new WaveContainer()); containers.push(new AuContainer()); External.debug("Playing audio of " + audio.length + " bytes."); var decoder:Pipe = new DecodePipe(containers); var pipe:BytePipe = new BytePipe(); decoder.setSink(pipe); decoder.write(audio); decoder.close(); currentAudio = pipe.getByteArray(); External.debug("Playing audio with " + currentAudio.length/4 + " samples."); var sound:Sound = new Sound(); sound.addEventListener(SampleDataEvent.SAMPLE_DATA, handleSampleEvent); currentChannel = sound.play(); currentChannel.addEventListener(Event.SOUND_COMPLETE, function(event:Event):void { sound.removeEventListener(SampleDataEvent.SAMPLE_DATA, handleSampleEvent); stop(); }); } private function handleSampleEvent(event:SampleDataEvent):void { if (currentAudio == null) return; var MAX_SAMPLES_PER_EVENT:uint = 4000; var count:uint = 0; // External.debug("Audio " + currentAudio.bytesAvailable + " " + event.data.endian); while (currentAudio.bytesAvailable && count < MAX_SAMPLES_PER_EVENT) { event.data.writeFloat(currentAudio.readFloat()); event.data.writeFloat(currentAudio.readFloat()); count += 1; } } } }
10sexcoil-gmail
src/edu/mit/csail/wami/play/WamiPlayer.as
ActionScript
mit
6,181
/* * Copyright (c) 2011 * Spoken Language Systems Group * MIT Computer Science and Artificial Intelligence Laboratory * Massachusetts Institute of Technology * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package edu.mit.csail.wami.play { import edu.mit.csail.wami.utils.StateListener; public interface IPlayer { function start(url:String, listener:StateListener):void; function stop():void; // Audio level (between 0 and 100) function level():int; } }
10sexcoil-gmail
src/edu/mit/csail/wami/play/IPlayer.as
ActionScript
mit
1,488
/* * Copyright (c) 2011 * Spoken Language Systems Group * MIT Computer Science and Artificial Intelligence Laboratory * Massachusetts Institute of Technology * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package edu.mit.csail.wami.utils { public interface StateListener { function started():void; function finished():void; function failed(error:Error):void; } }
10sexcoil-gmail
src/edu/mit/csail/wami/utils/StateListener.as
ActionScript
mit
1,390
/* * Copyright (c) 2011 * Spoken Language Systems Group * MIT Computer Science and Artificial Intelligence Laboratory * Massachusetts Institute of Technology * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package edu.mit.csail.wami.utils { import flash.utils.ByteArray; /** * Accumulates the written bytes into an array. If a max number of bytes * is specified this will act as a circular buffer. */ public class BytePipe extends Pipe { private var buffer:ByteArray = new ByteArray(); private var done:Boolean = false; private var maxBytes:uint; private var start:uint = 0; function BytePipe(maxBytes:uint = uint.MAX_VALUE):void { this.maxBytes = maxBytes; } override public function write(bytes:ByteArray):void { if (maxBytes <= 0) return; // no room! var available:uint = Math.min(maxBytes - buffer.length, bytes.bytesAvailable); if (available > 0) { bytes.readBytes(buffer, buffer.length, available); } while (bytes.bytesAvailable) { // Read bytes into the circular buffer. available = Math.min(buffer.length - start, bytes.bytesAvailable); bytes.readBytes(buffer, start, available); start = (start + available) % maxBytes; } buffer.position = 0; } override public function close():void { super.close(); done = true; } public function getByteArray():ByteArray { if (!done) { throw new Error("BytePipe should be done before accessing byte array."); } var array:ByteArray = new ByteArray(); buffer.position = start; buffer.readBytes(array); buffer.position = 0; if (start > 0) { buffer.readBytes(array, array.length, start); } array.position = 0; return array; } } }
10sexcoil-gmail
src/edu/mit/csail/wami/utils/BytePipe.as
ActionScript
mit
2,763
/* * Copyright (c) 2011 * Spoken Language Systems Group * MIT Computer Science and Artificial Intelligence Laboratory * Massachusetts Institute of Technology * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package edu.mit.csail.wami.utils { import flash.external.ExternalInterface; import flash.utils.ByteArray; /** * Make external calls only if available. */ public class External { public static var debugToConsole:Boolean = false; public static function call(functionName:String, ... arguments):void { if (ExternalInterface.available && functionName) { try { trace("External.call: " + functionName + "(" + arguments + ")"); ExternalInterface.call(functionName, arguments); } catch (e:Error) { trace("Error calling external function: " + e.message); } } else { trace("No ExternalInterface - External.call: " + functionName + "(" + arguments + ")"); } } public static function addCallback(functionName:String, closure:Function):void { if (ExternalInterface.available && functionName) { try { External.debug("External.addCallback: " + functionName); ExternalInterface.addCallback(functionName, closure); } catch (e:Error) { External.debug("Error calling external function: " + e.message); } } else { External.debug("No ExternalInterface - External.addCallback: " + functionName); } } public static function debug(msg:String):void { if (debugToConsole) { ExternalInterface.call("console.log", "FLASH: " + msg); } else { trace(msg); } } public static function debugBytes(bytes:ByteArray):void { debug(bytesToHex(bytes)); } public static function bytesToHex(bytes:ByteArray):String { var position:int = bytes.position; var count:int = 0; var str:String = "<"; while (bytes.bytesAvailable) { if (count%4 == 0) { str += " 0x"; } var byte:uint = bytes.readUnsignedByte(); var nib1:uint = byte/16; var nib2:uint = byte%16; str += getHex(nib1) + getHex(nib2); count++; } str += " >"; // Reset position bytes.position = position; return str; } private static function getHex(nibble:uint):String { switch(nibble) { case 0: return '0'; case 1: return '1'; case 2: return '2'; case 3: return '3'; case 4: return '4'; case 5: return '5'; case 6: return '6'; case 7: return '7'; case 8: return '8'; case 9: return '9'; case 10: return 'a'; case 11: return 'b'; case 12: return 'c'; case 13: return 'd'; case 14: return 'e'; case 15: return 'f'; } return "ERROR(" + nibble + ")"; } } }
10sexcoil-gmail
src/edu/mit/csail/wami/utils/External.as
ActionScript
mit
3,768
/* * Copyright (c) 2011 * Spoken Language Systems Group * MIT Computer Science and Artificial Intelligence Laboratory * Massachusetts Institute of Technology * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package edu.mit.csail.wami.audio { import flash.utils.Endian; /** * This class keeps track of all the information that defines the * audio format independent of the actual audio container * (e.g. .wav or .au) */ public class AudioFormat { // Allow 8 and 16 kHz as well. public static var allrates:Boolean = false; public var channels:uint; public var rate:uint; public var bits:uint; public var endian:String; public function AudioFormat(rate:uint, channels:uint, bits:uint, endian:String) { this.rate = rate; this.channels = channels; this.endian = endian; this.bits = bits; validate(); } // flash.media.Microphone quasi-rounds sample rates in kHz public static function toRoundedRate(rate:uint):uint { if (rate == 5512) { return 5; } else if (rate == 8000) { return 8; } else if (rate == 11025) { return 11; } else if (rate == 16000) { return 16; } else if (rate == 22050) { return 22; } else if (rate == 44100) { return 44; } throw new Error("Unsupported sample rate in Hz: " + rate); } public static function fromRoundedRate(rate:uint):uint { if (rate == 5) { return 5512; } else if (rate == 8) { return 8000; } else if (rate == 11) { return 11025; } else if (rate == 16) { return 16000; } else if (rate == 22) { return 22050; } else if (rate == 44) { return 44100; } throw new Error("Unsupported sample rate rounded in kHz: " + rate); } public function validate():void { if (bits != 8 && bits != 16 && bits != 32) { throw new Error("Unsupported number of bits per sample: " + bits); } if (channels != 1 && channels != 2) { throw new Error("Unsupported number of channels: " + channels); } if (endian != Endian.BIG_ENDIAN && endian != Endian.LITTLE_ENDIAN) { throw new Error("Unsupported endian type: " + endian); } var msg:String = ""; if (rate < 100) { throw new Error("Rate should be in Hz"); } else if (rate != 5512 && rate != 8000 && rate != 11025 && rate != 16000 && rate != 22050 && rate != 44100) { msg = "Sample rate of " + rate + " is not supported."; msg += " See flash.media.Microphone documentation." throw new Error(msg); } else if (!allrates && (rate == 8000 || rate == 16000 || rate == 11025)) { msg = "8kHz and 16kHz are supported for recording but not playback. 11kHz doesn't work in Ubuntu."; msg += " Enable all rates via a parameter passed into the Flash." throw new Error(msg); } } public function toString():String { return "Rate: " + rate + " Channels " + channels + " Bits: " + bits + " Endian: " + endian; } } }
10sexcoil-gmail
src/edu/mit/csail/wami/audio/AudioFormat.as
ActionScript
mit
4,046
/* * Copyright (c) 2011 * Spoken Language Systems Group * MIT Computer Science and Artificial Intelligence Laboratory * Massachusetts Institute of Technology * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package edu.mit.csail.wami.audio { import edu.mit.csail.wami.audio.AudioFormat; import edu.mit.csail.wami.audio.IAudioContainer; import edu.mit.csail.wami.utils.External; import edu.mit.csail.wami.utils.Pipe; import flash.utils.ByteArray; import flash.utils.Endian; /** * Convert WAVE data coming in to the float-based format flash uses. */ public class DecodePipe extends Pipe { private var format:AudioFormat; private var header:ByteArray = new ByteArray(); private var containers:Vector.<IAudioContainer>; public function DecodePipe(containers:Vector.<IAudioContainer>) { if (containers.length == 0) { throw new Error("Must have at least one container."); } this.containers = containers; } override public function write(bytes:ByteArray):void { if (format == null) { // Try to get header by parsing from each container bytes.readBytes(header, header.length, bytes.length); for each (var container:IAudioContainer in containers) { format = container.fromByteArray(header); if (format != null) { // Put the leftover bytes back bytes = new ByteArray(); header.readBytes(bytes); External.debug("Format: " + format); break; } } } if (format != null && bytes.bytesAvailable) { bytes.endian = format.endian; super.write(decode(bytes)); } } private function decode(bytes:ByteArray):ByteArray { var decoded:ByteArray = new ByteArray(); while (bytes.bytesAvailable) { var sample1:Number = getSample(bytes); var sample2:Number = sample1; if (format.channels == 2) { sample2 = getSample(bytes); } // cheap way to upsample var repeat:uint = 44100 / format.rate; while (repeat-- > 0) { decoded.writeFloat(sample1); decoded.writeFloat(sample2); } } decoded.position = 0; return decoded; } private function getSample(bytes:ByteArray):Number { var sample:Number; if (format.bits == 8) { sample = bytes.readByte()/0x7f; } else if (format.bits == 16) { sample = bytes.readShort()/0x7fff; } else if (format.bits == 32) { sample = bytes.readInt()/0x7fffffff; } else { throw new Error("Unsupported bits per sample: " + format.bits); } return sample; } } }
10sexcoil-gmail
src/edu/mit/csail/wami/audio/DecodePipe.as
ActionScript
mit
3,565
/* * Copyright (c) 2011 * Spoken Language Systems Group * MIT Computer Science and Artificial Intelligence Laboratory * Massachusetts Institute of Technology * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package edu.mit.csail.wami.audio { import edu.mit.csail.wami.utils.External; import flash.utils.ByteArray; import flash.utils.Endian; /** * This container is better for streaming, because it explicitly * says what to do when the length of the audio is unknown. It's typically * associated with mu-law compression (which wouldn't be too hard too implement) * but here we're using linear PCM. */ public class AuContainer implements IAudioContainer { public function isLengthRequired():Boolean { return false; } public function toByteArray(format:AudioFormat, length:int = -1):ByteArray { var dataLength:uint = 0xffffffff; if (length > -1) { dataLength = length; } if (format.endian != Endian.BIG_ENDIAN) { throw new Error("AU is a container for big endian data"); } // http://en.wikipedia.org/wiki/Au_file_format var header:ByteArray = new ByteArray(); header.endian = format.endian; header.writeUTFBytes(".snd"); header.writeInt(24); // Data offset header.writeInt(dataLength); var bits:uint = getEncodingFromBits(format); header.writeInt(bits); header.writeInt(format.rate); header.writeInt(format.channels); header.position = 0; External.debugBytes(header); return header; } private function getEncodingFromBits(format:AudioFormat):uint { if (format.bits == 16) { return 3; } else if (format.bits == 24) { return 4; } else if (format.bits == 32) { return 5; } throw new Error("Bits not supported"); } private function getBitsFromEncoding(encoding:uint):uint { if (encoding == 3) { return 16; } else if (encoding == 4) { return 24; } else if (encoding == 5) { return 32; } throw new Error("Encoding not supported: " + encoding); } public function fromByteArray(header:ByteArray):AudioFormat { if (header.bytesAvailable < 24) { return notAu(header, "Header not yet long enough for Au"); } var b:ByteArray = new ByteArray(); header.readBytes(b, 0, 24); External.debugBytes(b); header.position = 0; header.endian = Endian.BIG_ENDIAN; // Header is big-endian var magic:String = header.readUTFBytes(4); if (magic != ".snd") { return notAu(header, "Not an AU header, first bytes should be .snd"); } var dataOffset:uint = header.readInt(); var dataLength:uint = header.readInt(); if (header.bytesAvailable < dataOffset - 12) { return notAu(header, "Header of length " + header.bytesAvailable + " not long enough yet to include offset of length " + dataOffset); } var encoding:uint = header.readInt(); var bits:uint; try { bits = getBitsFromEncoding(encoding); } catch (e:Error) { return notAu(header, e.message); } var rate:uint = header.readInt(); var channels:uint = header.readInt(); header.position = dataOffset; var format:AudioFormat; try { format = new AudioFormat(rate, channels, bits, Endian.BIG_ENDIAN); } catch (e:Error) { return notAu(header, e.message); } return format; } private function notAu(header:ByteArray, msg:String):AudioFormat { External.debug("Not Au: " + msg); header.position = 0; return null; } } }
10sexcoil-gmail
src/edu/mit/csail/wami/audio/AuContainer.as
ActionScript
mit
4,588
/* * Copyright (c) 2011 * Spoken Language Systems Group * MIT Computer Science and Artificial Intelligence Laboratory * Massachusetts Institute of Technology * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package edu.mit.csail.wami.audio { import edu.mit.csail.wami.audio.AudioFormat; import edu.mit.csail.wami.audio.IAudioContainer; import edu.mit.csail.wami.utils.Pipe; import flash.utils.ByteArray; /** * Convert float format to raw audio accoring to the audio format passed in. */ public class EncodePipe extends Pipe { private var format:AudioFormat; private var container:IAudioContainer; // Buffer if container requires length. In this case, // we cannot write the data to the sink until the very end. private var buffer:ByteArray; private var headerWritten:Boolean; function EncodePipe(format:AudioFormat, container:IAudioContainer) { this.format = format; this.container = container; this.buffer = new ByteArray(); headerWritten = false; } override public function write(bytes:ByteArray):void { var transcoded:ByteArray = new ByteArray(); transcoded.endian = format.endian; while (bytes.bytesAvailable >= 4) { var sample:int; if (format.bits == 16) { sample = bytes.readFloat()*0x7fff; transcoded.writeShort(sample); if (format.channels == 2) { transcoded.writeShort(sample); } } else if (format.bits == 32) { sample = bytes.readFloat()*0x7fffffff; transcoded.writeInt(sample); if (format.channels == 2) { transcoded.writeInt(sample); } } else { throw new Error("Unsupported bits per sample: " + format.bits); } } transcoded.position = 0; handleEncoded(transcoded); } private function handleEncoded(bytes:ByteArray):void { if (container == null) { // No container, just stream it on super.write(bytes); return; } if (container.isLengthRequired()) { buffer.writeBytes(bytes, bytes.position, bytes.bytesAvailable); return; } if (!headerWritten) { var header:ByteArray = container.toByteArray(format); super.write(header); headerWritten = true; } super.write(bytes); } override public function close():void { if (container != null && container.isLengthRequired()) { // Write the audio (including the header). buffer.position = 0; super.write(container.toByteArray(format, buffer.length)); super.write(buffer); } super.close(); } } }
10sexcoil-gmail
src/edu/mit/csail/wami/audio/EncodePipe.as
ActionScript
mit
3,572
/* * Copyright (c) 2011 * Spoken Language Systems Group * MIT Computer Science and Artificial Intelligence Laboratory * Massachusetts Institute of Technology * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package edu.mit.csail.wami.audio { import edu.mit.csail.wami.utils.External; import flash.utils.ByteArray; import flash.utils.Endian; /** * This class builds a WAVE header formt the audio format. */ public class WaveContainer implements IAudioContainer { public function isLengthRequired():Boolean { return true; } public function toByteArray(audioFormat:AudioFormat, length:int = -1):ByteArray { // https://ccrma.stanford.edu/courses/422/projects/WaveFormat/ var id:String = (audioFormat.endian == Endian.LITTLE_ENDIAN) ? "RIFF" : "RIFX"; var bytesPerSample:uint = audioFormat.channels*audioFormat.bits/8; var header:ByteArray = new ByteArray(); // Little-endian is generally the way to go for WAVs header.endian = Endian.LITTLE_ENDIAN; header.writeUTFBytes(id); header.writeInt(length > 0 ? 36 + length : 0); header.writeUTFBytes("WAVE"); header.writeUTFBytes("fmt "); header.writeInt(16); header.writeShort(1); header.writeShort(audioFormat.channels); header.writeInt(audioFormat.rate); header.writeInt(audioFormat.rate*bytesPerSample); header.writeShort(bytesPerSample); header.writeShort(audioFormat.bits); header.writeUTFBytes('data'); header.writeInt(length); header.position = 0; return header; } public function fromByteArray(header:ByteArray):AudioFormat { if (header.bytesAvailable < 44) { var msg:String = "This header is not yet long enough "; msg += "(need 44 bytes only have " + header.bytesAvailable + ")." return notWav(header, msg); } var endian:String = Endian.LITTLE_ENDIAN; var chunkID:String = header.readUTFBytes(4); if (chunkID == "RIFX") { endian = Endian.BIG_ENDIAN; } else if (chunkID != "RIFF") { return notWav(header, "Does not look like a WAVE header: " + chunkID); } header.endian = Endian.LITTLE_ENDIAN; // Header is little-endian var totalLength:uint = header.readInt() + 8; var waveFmtStr:String = header.readUTFBytes(8); // "WAVEfmt " if (waveFmtStr != "WAVEfmt ") { return notWav(header, "RIFF header, but not a WAV."); } var subchunkSize:uint = header.readUnsignedInt(); // 16 var audioFormat:uint = header.readShort(); // 1 if (audioFormat != 1) { return notWav(header, "Currently we only support linear PCM"); } var channels:uint = header.readShort(); var rate:uint = header.readInt(); var bps:uint = header.readInt(); var bytesPerSample:uint = header.readShort(); var bits:uint = header.readShort(); var dataStr:String = header.readUTFBytes(4); // "data" var length:uint = header.readInt(); var format:AudioFormat; try { format = new AudioFormat(rate, channels, bits, endian); } catch (e:Error) { return notWav(header, e.message); } return format; } /** * Emit error message for debugging, reset the ByteArray and * return null. */ private function notWav(header:ByteArray, msg:String):AudioFormat { External.debug("Not WAV: " + msg); header.position = 0; return null; } } }
10sexcoil-gmail
src/edu/mit/csail/wami/audio/WaveContainer.as
ActionScript
mit
4,385
/* * Copyright (c) 2011 * Spoken Language Systems Group * MIT Computer Science and Artificial Intelligence Laboratory * Massachusetts Institute of Technology * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package edu.mit.csail.wami.audio { import flash.utils.ByteArray; /** * There are a number of ways to store raw audio. WAV is a container from * Microsoft. AU is a container from Sun Microsystems. This interface * helps us separate the container format from the audio format itself. */ public interface IAudioContainer { function toByteArray(format:AudioFormat, length:int = -1):ByteArray; /** * If successful, the position is left at the first byte after * the header. If the bytes do not represent the expected container * header null is returned and the position is returned to 0. */ function fromByteArray(bytes:ByteArray):AudioFormat; /** * Some containers (e.g. WAV) require the length of the data to be specified, * and thus are not amenable to streaming. Others (e.g. AU) have well * defined ways of dealing with data of unknown length. */ function isLengthRequired():Boolean; } }
10sexcoil-gmail
src/edu/mit/csail/wami/audio/IAudioContainer.as
ActionScript
mit
2,168
/* * Copyright (c) 2011 * Spoken Language Systems Group * MIT Computer Science and Artificial Intelligence Laboratory * Massachusetts Institute of Technology * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package edu.mit.csail.wami.record { import edu.mit.csail.wami.audio.AuContainer; import edu.mit.csail.wami.audio.AudioFormat; import edu.mit.csail.wami.audio.EncodePipe; import edu.mit.csail.wami.audio.IAudioContainer; import edu.mit.csail.wami.audio.WaveContainer; import edu.mit.csail.wami.client.WamiParams; import edu.mit.csail.wami.utils.BytePipe; import edu.mit.csail.wami.utils.External; import edu.mit.csail.wami.utils.Pipe; import edu.mit.csail.wami.utils.StateListener; import flash.events.SampleDataEvent; import flash.events.StatusEvent; import flash.media.Microphone; import flash.media.SoundCodec; import flash.utils.Endian; import flash.utils.clearInterval; import flash.utils.setInterval; public class WamiRecorder implements IRecorder { private static var CHUNK_DURATION_MILLIS:Number = 200; private var mic:Microphone = null; private var params:WamiParams; private var audioPipe:Pipe; // For adding some audio padding to start and stop. private var circularBuffer:BytePipe; private var stopInterval:uint; private var paddingMillis:uint = 0; // initially 0, but listen changes it. private var listening:Boolean = false; // To determine if the amount of audio recorded matches up with // the length of time we've recorded (i.e. not dropping any frames) private var handled:uint; private var startTime:Date; private var stopTime:Date; private var listener:StateListener; public function WamiRecorder(mic:Microphone, params:WamiParams) { this.params = params; this.circularBuffer = new BytePipe(getPaddingBufferSize()); this.mic = mic; mic.addEventListener(StatusEvent.STATUS, onMicStatus); if (getChunkSize() <= 0) { throw new Error("Desired duration is too small, even for streaming chunks: " + getChunkSize()); } } /** * The WAMI recorder can listen constantly, keeping a buffer of the last * few milliseconds of audio. Often people start talking before they click the * button, so we prepend paddingMillis milliseconds to the audio. */ public function listen(paddingMillis:uint):void { if (!listening) { this.paddingMillis = paddingMillis; mic.rate = AudioFormat.toRoundedRate(params.format.rate); mic.codec = SoundCodec.NELLYMOSER; // Just to clarify 5, 8, 11, 16, 22 and 44 kHz mic.setSilenceLevel(0, 10000); mic.addEventListener(SampleDataEvent.SAMPLE_DATA, sampleHandler); External.debug("Listening..."); listening = true; } } public function unlisten():void { if (listening) { mic.removeEventListener(SampleDataEvent.SAMPLE_DATA, sampleHandler); listening = false; if (paddingMillis > 0) { circularBuffer = new BytePipe(getPaddingBufferSize()); } External.debug("Unlistening."); } } protected function onMicStatus(event:StatusEvent):void { External.debug("status: " + event.code); if (event.code == "Microphone.Unmuted") { listen(this.paddingMillis); } else if (event.code == "Microphone.Muted") { unlisten(); } } public function start(url:String, listener:StateListener):void { // Forces security if mic is still muted in debugging mode. listen(this.paddingMillis); // Flash might be able to decide on a different sample rate // than the one you suggest depending on your audio card... params.format.rate = AudioFormat.fromRoundedRate(mic.rate); External.debug("Recording at rate: " + params.format.rate); stop(true); audioPipe = createAudioPipe(url, listener); if (paddingMillis > 0) { // Prepend a small amount of audio we've already recorded. circularBuffer.close(); audioPipe.write(circularBuffer.getByteArray()); circularBuffer = new BytePipe(getPaddingBufferSize()); } listener.started(); handled = 0; startTime = new Date(); } public function createAudioPipe(url:String, listener:StateListener):Pipe { this.listener = listener; var post:Pipe; var container:IAudioContainer; if (params.stream) { // The chunk parameter is something I made up. It would need // to be handled on the server-side to piece all the chunks together. post = new MultiPost(url, "audio/basic; chunk=%s", 3*1000, listener); params.format.endian = Endian.BIG_ENDIAN; container = new AuContainer(); } else { post = new SinglePost(url, "audio/x-wav", 30*1000, listener); container = new WaveContainer(); } // Setup the audio pipes. A transcoding pipe converts floats // to shorts and passes them on to a chunking pipe, which spits // out chunks to a pipe that possibly adds a WAVE header // before passing the chunks on to a pipe that does HTTP posts. var pipe:Pipe = new EncodePipe(params.format, container); pipe.setSink(new ChunkPipe(getChunkSize())) .setSink(post); return pipe; } internal function sampleHandler(evt:SampleDataEvent):void { evt.data.position = 0; try { if (audioPipe) { audioPipe.write(evt.data); handled += evt.data.length / 4; } else if (paddingMillis > 0) { circularBuffer.write(evt.data); } } catch (error:Error) { audioPipe = null; stop(true); listener.failed(error); } } public function stop(force:Boolean = false):void { clearInterval(stopInterval); if (force) { reallyStop(); } else { stopInterval = setInterval(function():void { clearInterval(stopInterval); reallyStop(); }, paddingMillis); } } public function level():int { if (!audioPipe) return 0; return mic.activityLevel; } private function reallyStop():void { if (!audioPipe) return; try { audioPipe.close(); } catch(error:Error) { listener.failed(error); } audioPipe = null; validateAudioLength(); if (this.paddingMillis == 0) { // No need if we're not padding the audio unlisten(); } } private function validateAudioLength():void { stopTime = new Date(); var seconds:Number = ((stopTime.time - startTime.time + paddingMillis) / 1000.0); var expectedSamples:uint = uint(seconds*params.format.rate); External.debug("Expected Samples: " + expectedSamples + " Actual Samples: " + handled); startTime = null; stopTime = null; } private function getBytesPerSecond():uint { return params.format.channels * (params.format.bits/8) * params.format.rate; } private function getChunkSize():uint { return params.stream ? getBytesPerSecond() * CHUNK_DURATION_MILLIS / 1000.0 : int.MAX_VALUE; } private function getPaddingBufferSize():uint { return uint(getBytesPerSecond()*params.paddingMillis/1000.0); } } }
10sexcoil-gmail
src/edu/mit/csail/wami/record/WamiRecorder.as
ActionScript
mit
7,995
/* * Copyright (c) 2011 * Spoken Language Systems Group * MIT Computer Science and Artificial Intelligence Laboratory * Massachusetts Institute of Technology * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package edu.mit.csail.wami.record { import edu.mit.csail.wami.utils.External; import edu.mit.csail.wami.utils.Pipe; import edu.mit.csail.wami.utils.StateListener; import flash.utils.ByteArray; public class MultiPost extends Pipe implements StateListener { private var url:String; private var contentType:String = null; private var partIndex:int = 0; private var timeoutMillis:int; private var totalBytes:int = 0; private var totalPostsMade:int = 0; private var totalPostsDone:int = 0; private var error:Error = null; private var listener:StateListener; /** * Does of POST of the data passed in to every call to "write" */ public function MultiPost(url:String, type:String, timeoutMillis:int, listener:StateListener) { this.url = url; this.contentType = type; this.timeoutMillis = timeoutMillis; this.listener = listener; } override public function write(bytes:ByteArray):void { if (getError() != null) { throw getError(); } var type:String = contentType.replace("%s", partIndex++); var post:Pipe = new SinglePost(url, type, timeoutMillis, this); post.write(bytes); post.close(); totalBytes += bytes.length; totalPostsMade++; } // A final POST containing a -1 signifies the end of the MultiPost stream. override public function close():void { External.debug("Total multi-posted bytes: " + totalBytes); var arr:ByteArray = new ByteArray(); arr.writeInt(-1); arr.position = 0; write(arr); super.close(); } public function started():void { // nothing to do } public function finished():void { totalPostsDone++; checkFinished(); } public function failed(error:Error):void { this.error = error; } public function getError():Error { return error; } private function checkFinished():void { if (totalPostsDone == totalPostsMade && super.isClosed()) { listener.finished(); } } } }
10sexcoil-gmail
src/edu/mit/csail/wami/record/MultiPost.as
ActionScript
mit
3,196
/* * Copyright (c) 2011 * Spoken Language Systems Group * MIT Computer Science and Artificial Intelligence Laboratory * Massachusetts Institute of Technology * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package edu.mit.csail.wami.record { import edu.mit.csail.wami.utils.StateListener; public interface IRecorder { // Start and stop recording. Calling start while recording // or calling stop when not recording should have no effect. function start(url:String, listener:StateListener):void; function stop(force:Boolean = false):void; // It can be helpful to buffer a certain amount of audio to // prepend (and append) to the audio collected between start // and stop. This means, Flash needs to constantly listen. // There are other times when it's obvious no recording will // be done, and so listening is unnecesary. function listen(paddingMillis:uint):void; function unlisten():void; // Audio level (between 0 and 100) function level():int; } }
10sexcoil-gmail
src/edu/mit/csail/wami/record/IRecorder.as
ActionScript
mit
2,010
/* * Copyright (c) 2011 * Spoken Language Systems Group * MIT Computer Science and Artificial Intelligence Laboratory * Massachusetts Institute of Technology * * Permission is hereby granted, free of charge, to any person * obtaining a copy of this software and associated documentation * files (the "Software"), to deal in the Software without * restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies * of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS * BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN * ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ package edu.mit.csail.wami.record { import edu.mit.csail.wami.utils.External; import edu.mit.csail.wami.utils.Pipe; import edu.mit.csail.wami.utils.StateListener; import flash.events.Event; import flash.events.HTTPStatusEvent; import flash.events.IOErrorEvent; import flash.events.ProgressEvent; import flash.events.SecurityErrorEvent; import flash.net.URLLoader; import flash.net.URLRequest; import flash.net.URLRequestMethod; import flash.utils.ByteArray; import flash.utils.setInterval; /** * Write data and POST on close. */ public class SinglePost extends Pipe { private var url:String; private var contentType:String = null; private var listener:StateListener; private var finished:Boolean = false; private var buffer:ByteArray = new ByteArray(); private var timeoutMillis:int; public function SinglePost(url:String, type:String, timeoutMillis:int, listener:StateListener) { this.url = url; this.contentType = type; this.listener = listener; this.timeoutMillis = timeoutMillis; } override public function write(bytes:ByteArray):void { bytes.readBytes(buffer, buffer.length, bytes.bytesAvailable); } override public function close():void { buffer.position = 0; External.debug("POST " + buffer.length + " bytes of type " + contentType); buffer.position = 0; var loader:URLLoader = new URLLoader(); loader.addEventListener(Event.COMPLETE, completeHandler); loader.addEventListener(Event.OPEN, openHandler); loader.addEventListener(ProgressEvent.PROGRESS, progressHandler); loader.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler); loader.addEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler); loader.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler); var request:URLRequest = new URLRequest(url); request.method = URLRequestMethod.POST; request.contentType = contentType; request.data = buffer; if (buffer.bytesAvailable == 0) { External.debug("Note that flash does a GET request if bytes.length == 0"); } try { loader.load(request); } catch (error:Error) { if (listener) { listener.failed(error); } } super.close(); } private function completeHandler(event:Event):void { External.debug("POST: completeHandler"); var loader:URLLoader = URLLoader(event.target); loader.removeEventListener(Event.COMPLETE, completeHandler); loader.removeEventListener(Event.OPEN, openHandler); loader.removeEventListener(ProgressEvent.PROGRESS, progressHandler); loader.removeEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler); loader.removeEventListener(HTTPStatusEvent.HTTP_STATUS, httpStatusHandler); loader.removeEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler); listener.finished(); finished = true; } private function openHandler(event:Event):void { External.debug("POST openHandler: " + event); setInterval(checkFinished, timeoutMillis); } private function checkFinished():void { if (!finished && listener) { listener.failed(new Error("POST is taking too long.")); } finished = true; } private function progressHandler(event:ProgressEvent):void { External.debug("POST progressHandler loaded:" + event.bytesLoaded + " total: " + event.bytesTotal); } private function securityErrorHandler(event:SecurityErrorEvent):void { if (!finished && listener) { listener.failed(new Error("Record security error: " + event.errorID)); } finished = true; } private function httpStatusHandler(event:HTTPStatusEvent):void { // Apparently the event.status can be zero in some environments where nothing is wrong: // http://johncblandii.com/2008/04/flex-3-firefox-beta-3-returns-0-for-http-status-codes.html if (!finished && listener && event.status != 200 && event.status != 0) { listener.failed(new Error("HTTP status error: " + event.status)); } finished = true; } private function ioErrorHandler(event:IOErrorEvent):void { if (!finished && listener) { listener.failed(new Error("Record IO error: " + event.errorID)); } finished = true; } } }
10sexcoil-gmail
src/edu/mit/csail/wami/record/SinglePost.as
ActionScript
mit
5,447
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html> <head> <!-- swfobject is a commonly used library to embed Flash content --> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js"></script> <!-- Setup the recorder interface --> <script type="text/javascript" src="recorder.js"></script> <script> function setup() { Wami.setup("wami"); } function record() { status("Recording..."); Wami.startRecording("https://wami-recorder.appspot.com/audio"); } function play() { Wami.startPlaying("https://wami-recorder.appspot.com/audio"); } function stop() { status(""); Wami.stopRecording(); Wami.stopPlaying(); } function status(msg) { document.getElementById('status').innerHTML = msg; } </script> </head> <body onload="setup()"> <input type="button" value="Record" onclick="record()"></input> <input type="button" value="Stop" onclick="stop()"></input> <input type="button" value="Play" onclick="play()"></input> <div id="status"></div> <div id="wami"></div> </body> </html>
10sexcoil-gmail
example/client/basic.html
HTML
mit
1,110
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html> <head> <!-- swfobject is a commonly used library to embed Flash content --> <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js"></script> <!-- Setup the recorder interface --> <script type="text/javascript" src="recorder.js"></script> <!-- GUI code... take it or leave it --> <script type="text/javascript" src="gui.js"></script> <script> function setupRecorder() { Wami.setup({ id : "wami", onReady : setupGUI }); } function setupGUI() { var gui = new Wami.GUI({ id : "wami", recordUrl : "https://wami-recorder.appspot.com/audio", playUrl : "https://wami-recorder.appspot.com/audio" }); gui.setPlayEnabled(false); } </script> </head> <body onload="setupRecorder()"> <div id="wami" style="margin-left: 100px;"></div> <noscript>WAMI requires Javascript</noscript> <div style="position: absolute; left: 400px; top: 20px; font-family: arial, sans-serif; font-size: 82%"> Right-click to Download<br /> <br /> <a href="https://wami-recorder.googlecode.com/hg/example/client/index.html">index.html</a><br /> <a href="https://wami-recorder.googlecode.com/hg/example/client/Wami.swf">Wami.swf</a><br /> <a href="https://wami-recorder.googlecode.com/hg/example/client/buttons.png">buttons.png</a><br /> <a href="https://wami-recorder.googlecode.com/hg/example/client/recorder.js">recorder.js</a><br /> <a href="https://wami-recorder.googlecode.com/hg/example/client/gui.js">gui.js</a><br /> </div> </body> </html>
10sexcoil-gmail
example/client/index.html
HTML
mit
1,628
var Wami = window.Wami || {}; // Upon a creation of a new Wami.GUI(options), we assume that a WAMI recorder // has been initialized. Wami.GUI = function(options) { var RECORD_BUTTON = 1; var PLAY_BUTTON = 2; setOptions(options); setupDOM(); var recordButton, playButton; var recordInterval, playInterval; function createDiv(id, style) { var div = document.createElement("div"); if (id) { div.setAttribute('id', id); } if (style) { div.style.cssText = style; } return div; } function setOptions(options) { if (!options.buttonUrl) { options.buttonUrl = "buttons.png"; } if (typeof options.listen == 'undefined' || options.listen) { listen(); } } function setupDOM() { var guidiv = createDiv(null, "position: absolute; width: 214px; height: 137px;"); document.getElementById(options.id).appendChild(guidiv); var rid = Wami.createID(); var recordDiv = createDiv(rid, "position: absolute; left: 40px; top: 25px"); guidiv.appendChild(recordDiv); recordButton = new Button(rid, RECORD_BUTTON, options.buttonUrl); recordButton.onstart = startRecording; recordButton.onstop = stopRecording; recordButton.setEnabled(true); if (!options.singleButton) { var pid = Wami.createID(); var playDiv = createDiv(pid, "position: absolute; right: 40px; top: 25px"); guidiv.appendChild(playDiv); playButton = new Button(pid, PLAY_BUTTON, options.buttonUrl); playButton.onstart = startPlaying; playButton.onstop = stopPlaying; } } /** * These methods are called on clicks from the GUI. */ function startRecording() { if (!options.recordUrl) { alert("No record Url specified!"); } recordButton.setActivity(0); playButton.setEnabled(false); Wami.startRecording(options.recordUrl, Wami.nameCallback(onRecordStart), Wami .nameCallback(onRecordFinish), Wami .nameCallback(onError)); } function stopRecording() { Wami.stopRecording(); clearInterval(recordInterval); recordButton.setEnabled(true); } function startPlaying() { if (!options.playUrl) { alert('No play URL specified!'); } playButton.setActivity(0); recordButton.setEnabled(false); Wami.startPlaying(options.playUrl, Wami.nameCallback(onPlayStart), Wami .nameCallback(onPlayFinish), Wami.nameCallback(onError)); } function stopPlaying() { Wami.stopPlaying(); } this.setPlayUrl = function(url) { options.playUrl = url; } this.setRecordUrl = function(url) { options.recordUrl = url; } this.setPlayEnabled = function(val) { playButton.setEnabled(val); } this.setRecordEnabled = function(val) { recordButton.setEnabled(val); } /** * Callbacks from the flash indicating certain events */ function onError(e) { alert(e); } function onRecordStart() { recordInterval = setInterval(function() { if (recordButton.isActive()) { var level = Wami.getRecordingLevel(); recordButton.setActivity(level); } }, 200); if (options.onRecordStart) { options.onRecordStart(); } } function onRecordFinish() { playButton.setEnabled(true); if (options.onRecordFinish) { options.onRecordFinish(); } } function onPlayStart() { playInterval = setInterval(function() { if (playButton.isActive()) { var level = Wami.getPlayingLevel(); playButton.setActivity(level); } }, 200); if (options.onPlayStart) { options.onPlayStart(); } } function onPlayFinish() { clearInterval(playInterval); recordButton.setEnabled(true); playButton.setEnabled(true); if (options.onPlayFinish) { options.onPlayFinish(); } } function listen() { Wami.startListening(); // Continually listening when the window is in focus allows us to // buffer a little audio before the users clicks, since sometimes // people talk too soon. Without "listening", the audio would record // exactly when startRecording() is called. window.onfocus = function() { Wami.startListening(); }; // Note that the use of onfocus and onblur should probably be replaced // with a more robust solution (e.g. jQuery's $(window).focus(...) window.onblur = function() { Wami.stopListening(); }; } function Button(buttonid, type, url) { var self = this; self.active = false; self.type = type; init(); // Get the background button image position // Index: 1) normal 2) pressed 3) mouse-over function background(index) { if (index == 1) return "-56px 0px"; if (index == 2) return "0px 0px"; if (index == 3) return "-112px 0"; alert("Background not found: " + index); } // Get the type of meter and its state // Index: 1) enabled 2) meter 3) disabled function meter(index, offset) { var top = 5; if (offset) top += offset; if (self.type == RECORD_BUTTON) { if (index == 1) return "-169px " + top + "px"; if (index == 2) return "-189px " + top + "px"; if (index == 3) return "-249px " + top + "px"; } else { if (index == 1) return "-269px " + top + "px"; if (index == 2) return "-298px " + top + "px"; if (index == 3) return "-327px " + top + "px"; } alert("Meter not found: " + self.type + " " + index); } function silhouetteWidth() { if (self.type == RECORD_BUTTON) { return "20px"; } else { return "29px"; } } function mouseHandler(e) { var rightclick; if (!e) var e = window.event; if (e.which) rightclick = (e.which == 3); else if (e.button) rightclick = (e.button == 2); if (!rightclick) { if (self.active && self.onstop) { self.active = false; self.onstop(); } else if (!self.active && self.onstart) { self.active = true; self.onstart(); } } } function init() { var div = document.createElement("div"); var elem = document.getElementById(buttonid); if (elem) { elem.appendChild(div); } else { alert('Could not find element on page named ' + buttonid); } self.guidiv = document.createElement("div"); self.guidiv.style.width = '56px'; self.guidiv.style.height = '63px'; self.guidiv.style.cursor = 'pointer'; self.guidiv.style.background = "url(" + url + ") no-repeat"; self.guidiv.style.backgroundPosition = background(1); div.appendChild(self.guidiv); // margin auto doesn't work in IE quirks mode // http://stackoverflow.com/questions/816343/why-will-this-div-img-not-center-in-ie8 // text-align is a hack to force it to work even if you forget the // doctype. self.guidiv.style.textAlign = 'center'; self.meterDiv = document.createElement("div"); self.meterDiv.style.width = silhouetteWidth(); self.meterDiv.style.height = '63px'; self.meterDiv.style.margin = 'auto'; self.meterDiv.style.cursor = 'pointer'; self.meterDiv.style.position = 'relative'; self.meterDiv.style.background = "url(" + url + ") no-repeat"; self.meterDiv.style.backgroundPosition = meter(2); self.guidiv.appendChild(self.meterDiv); self.coverDiv = document.createElement("div"); self.coverDiv.style.width = silhouetteWidth(); self.coverDiv.style.height = '63px'; self.coverDiv.style.margin = 'auto'; self.coverDiv.style.cursor = 'pointer'; self.coverDiv.style.position = 'relative'; self.coverDiv.style.background = "url(" + url + ") no-repeat"; self.coverDiv.style.backgroundPosition = meter(1); self.meterDiv.appendChild(self.coverDiv); self.active = false; self.guidiv.onmousedown = mouseHandler; } self.isActive = function() { return self.active; } self.setActivity = function(level) { self.guidiv.onmouseout = function() { }; self.guidiv.onmouseover = function() { }; self.guidiv.style.backgroundPosition = background(2); self.coverDiv.style.backgroundPosition = meter(1, 5); self.meterDiv.style.backgroundPosition = meter(2, 5); var totalHeight = 31; var maxHeight = 9; // When volume goes up, the black image loses height, // creating the perception of the colored one increasing. var height = (maxHeight + totalHeight - Math.floor(level / 100 * totalHeight)); self.coverDiv.style.height = height + "px"; } self.setEnabled = function(enable) { var guidiv = self.guidiv; self.active = false; if (enable) { self.coverDiv.style.backgroundPosition = meter(1); self.meterDiv.style.backgroundPosition = meter(1); guidiv.style.backgroundPosition = background(1); guidiv.onmousedown = mouseHandler; guidiv.onmouseover = function() { guidiv.style.backgroundPosition = background(3); }; guidiv.onmouseout = function() { guidiv.style.backgroundPosition = background(1); }; } else { self.coverDiv.style.backgroundPosition = meter(3); self.meterDiv.style.backgroundPosition = meter(3); guidiv.style.backgroundPosition = background(1); guidiv.onmousedown = null; guidiv.onmouseout = function() { }; guidiv.onmouseover = function() { }; } } } }
10sexcoil-gmail
example/client/gui.js
JavaScript
mit
8,988
var Wami = window.Wami || {}; // Returns a (very likely) unique string with of random letters and numbers Wami.createID = function() { return "wid" + ("" + 1e10).replace(/[018]/g, function(a) { return (a ^ Math.random() * 16 >> a / 4).toString(16) }); } // Creates a named callback in WAMI and returns the name as a string. Wami.nameCallback = function(cb, cleanup) { Wami._callbacks = Wami._callbacks || {}; var id = Wami.createID(); Wami._callbacks[id] = function() { if (cleanup) { Wami._callbacks[id] = null; } cb.apply(null, arguments); }; var named = "Wami._callbacks['" + id + "']"; return named; } // This method ensures that a WAMI recorder is operational, and that // the following API is available in the Wami namespace. All functions // must be named (i.e. cannot be anonymous). // // Wami.startPlaying(url, startfn = null, finishedfn = null, failedfn = null); // Wami.stopPlaying() // // Wami.startRecording(url, startfn = null, finishedfn = null, failedfn = null); // Wami.stopRecording() // // Wami.getRecordingLevel() // Returns a number between 0 and 100 // Wami.getPlayingLevel() // Returns a number between 0 and 100 // // Wami.hide() // Wami.show() // // Manipulate the WAMI recorder's settings. In Flash // we need to check if the microphone permission has been granted. // We might also set/return sample rate here, etc. // // Wami.getSettings(); // Wami.setSettings(options); // // Optional way to set up browser so that it's constantly listening // This is to prepend audio in case the user starts talking before // they click-to-talk. // // Wami.startListening() // Wami.setup = function(options) { if (Wami.startRecording) { // Wami's already defined. if (options.onReady) { options.onReady(); } return; } // Assumes that swfobject.js is included if Wami.swfobject isn't // already defined. Wami.swfobject = Wami.swfobject || swfobject; if (!Wami.swfobject) { alert("Unable to find swfobject to help embed the SWF."); } var _options; setOptions(options); embedWamiSWF(_options.id, Wami.nameCallback(delegateWamiAPI)); function supportsTransparency() { // Detecting the OS is a big no-no in Javascript programming, but // I can't think of a better way to know if wmode is supported or // not... since NOT supporting it (like Flash on Ubuntu) is a bug. return (navigator.platform.indexOf("Linux") == -1); } function setOptions(options) { // Start with default options _options = { swfUrl : "Wami.swf", onReady : function() { Wami.hide(); }, onSecurity : checkSecurity, onError : function(error) { alert(error); } }; if (typeof options == 'undefined') { alert('Need at least an element ID to place the Flash object.'); } if (typeof options == 'string') { _options.id = options; } else { _options.id = options.id; } if (options.swfUrl) { _options.swfUrl = options.swfUrl; } if (options.onReady) { _options.onReady = options.onReady; } if (options.onLoaded) { _options.onLoaded = options.onLoaded; } if (options.onSecurity) { _options.onSecurity = options.onSecurity; } if (options.onError) { _options.onError = options.onError; } // Create a DIV for the SWF under _options.id var container = document.createElement('div'); container.style.position = 'absolute'; _options.cid = Wami.createID(); container.setAttribute('id', _options.cid); var swfdiv = document.createElement('div'); var id = Wami.createID(); swfdiv.setAttribute('id', id); container.appendChild(swfdiv); document.getElementById(_options.id).appendChild(container); _options.id = id; } function checkSecurity() { var settings = Wami.getSettings(); if (settings.microphone.granted) { _options.onReady(); } else { // Show any Flash settings panel you want: // http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/flash/system/SecurityPanel.html Wami.showSecurity("privacy", "Wami.show", Wami .nameCallback(_options.onSecurity), Wami .nameCallback(_options.onError)); } } // Embed the WAMI SWF and call the named callback function when loaded. function embedWamiSWF(id, initfn) { var flashVars = { visible : false, loadedCallback : initfn } var params = { allowScriptAccess : "always" } if (supportsTransparency()) { params.wmode = "transparent"; } if (typeof console !== 'undefined') { flashVars.console = true; } var version = '10.0.0'; document.getElementById(id).innerHTML = "WAMI requires Flash " + version + " or greater<br />https://get.adobe.com/flashplayer/"; // This is the minimum size due to the microphone security panel Wami.swfobject.embedSWF(_options.swfUrl, id, 214, 137, version, null, flashVars, params); // Without this line, Firefox has a dotted outline of the flash Wami.swfobject.createCSS("#" + id, "outline:none"); } // To check if the microphone settings were 'remembered', we // must actually embed an entirely new Wami client and check // whether its microphone is granted. If it is, it was remembered. function checkRemembered(finishedfn) { var id = Wami.createID(); var div = document.createElement('div'); div.style.top = '-999px'; div.style.left = '-999px'; div.setAttribute('id', id); var body = document.getElementsByTagName('body').item(0); body.appendChild(div); var fn = Wami.nameCallback(function() { var swf = document.getElementById(id); Wami._remembered = swf.getSettings().microphone.granted; Wami.swfobject.removeSWF(id); eval(finishedfn + "()"); }); embedWamiSWF(id, fn); } // Attach all the audio methods to the Wami namespace in the callback. function delegateWamiAPI() { var recorder = document.getElementById(_options.id); function delegate(name) { Wami[name] = function() { return recorder[name].apply(recorder, arguments); } } delegate('startPlaying'); delegate('stopPlaying'); delegate('startRecording'); delegate('stopRecording'); delegate('startListening'); delegate('stopListening'); delegate('getRecordingLevel'); delegate('getPlayingLevel'); delegate('setSettings'); // Append extra information about whether mic settings are sticky Wami.getSettings = function() { var settings = recorder.getSettings(); settings.microphone.remembered = Wami._remembered; return settings; } Wami.showSecurity = function(panel, startfn, finishedfn, failfn) { // Flash must be on top for this. var container = document.getElementById(_options.cid); var augmentedfn = Wami.nameCallback(function() { checkRemembered(finishedfn); container.style.cssText = "position: absolute;"; }); container.style.cssText = "position: absolute; z-index: 99999"; recorder.showSecurity(panel, startfn, augmentedfn, failfn); } Wami.show = function() { if (!supportsTransparency()) { recorder.style.visibility = "visible"; } } Wami.hide = function() { // Hiding flash in all the browsers is tricky. Please read: // https://code.google.com/p/wami-recorder/wiki/HidingFlash if (!supportsTransparency()) { recorder.style.visibility = "hidden"; } } // If we already have permissions, they were previously 'remembered' Wami._remembered = recorder.getSettings().microphone.granted; if (_options.onLoaded) { _options.onLoaded(); } if (!_options.noSecurityCheck) { checkSecurity(); } } }
10sexcoil-gmail
example/client/recorder.js
JavaScript
mit
7,459
<?php # Save the audio to a URL-accessible directory for playback. parse_str($_SERVER['QUERY_STRING'], $params); $name = isset($params['name']) ? $params['name'] : 'output.wav'; $content = file_get_contents('php://input'); $fh = fopen($name, 'w') or die("can't open file"); fwrite($fh, $content); fclose($fh); ?>
10sexcoil-gmail
example/server/php/record.php
PHP
mit
312
# Run from the commandline: # # python server.py # POST audio to http://localhost:9000 # GET audio from http://localhost:9000 # # A simple server to collect audio using python. To be more secure, # you might want to check the file names and place size restrictions # on the incoming data. import cgi from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer class WamiHandler(BaseHTTPRequestHandler): dirname = "/tmp/" def do_GET(self): f = open(self.get_name()) self.send_response(200) self.send_header('content-type','audio/x-wav') self.end_headers() self.wfile.write(f.read()) f.close() def do_POST(self): f = open(self.get_name(), "wb") # Note that python's HTTPServer doesn't support chunked transfer. # Thus, it requires a content-length. length = int(self.headers.getheader('content-length')) print "POST of length " + str(length) f.write(self.rfile.read(length)) f.close(); def get_name(self): filename = 'output.wav'; qs = self.path.split('?',1); if len(qs) == 2: params = cgi.parse_qs(qs[1]) if params['name']: filename = params['name'][0]; return WamiHandler.dirname + filename def main(): try: server = HTTPServer(('', 9000), WamiHandler) print 'Started server...' server.serve_forever() except KeyboardInterrupt: print 'Stopping server' server.socket.close() if __name__ == '__main__': main()
10sexcoil-gmail
example/server/python/server.py
Python
mit
1,569
<?php //require section require_once dirname(__FILE__) . '/shared/config/config.php'; require_once DOCUMENT_ROOT . DIR_SHARED_LIBRARIES . 'lib_date.php'; require_once DOCUMENT_ROOT . DIR_SHARED_API . '/api_contact.php'; $title = 'Hỏi Đáp'; $contact = api_contact::get_contact(); $email = ""; if (!empty($contact['email'])) { $email = $contact['email']; } $phone = ""; if (!empty($contact['phone'])) { $phone = $contact['phone']; } $email_sent_to = $email; if (!empty($_POST)) { $txt_full_name = $_POST['txt_full_name']; $txt_email = $_POST['txt_email']; $txt_phone = $_POST['txt_phone']; $txt_question = $_POST['txt_question']; //echo $txt_full_name. " ".$txt_email." ".$txt_phone." ".$txt_question." "; $message = "Họ tên: " . $txt_full_name . " || Email: " . $txt_email . " || SĐT: " . $txt_phone . " || Câu hỏi: " . $txt_question; if (mail($email_sent_to, "huanluyenviencanhan.com.vn - Hỏi đáp", $message)) { ?> <script type="text/javascript"> alert('Hệ thống đã gửi email yêu cầu của bạn cho quản trị viên.'); </script> <?php } } ?> <!DOCTYPE html> <html> <head> <?php require_once DOCUMENT_ROOT . DIR_INCLUDE . 'head.php'; ?> </head> <body> <div class="uk-container uk-container-center uk-margin-top"> <?php require_once DOCUMENT_ROOT . DIR_INCLUDE . 'menu.php'; require_once DOCUMENT_ROOT . DIR_INCLUDE . 'slider.php'; ?> <!-- Changable content --> <section id="main-content" class="ts-body-container uk-panel uk-panel-box ts-padding-large"> <article class="uk-article"> <h1 class="uk-article-title ts-color-primary">Liên Hệ Hỏi Đáp</h1> <p class="uk-article-meta">Ngày: <?php echo lib_date::get_now(); ?></p> <p class="uk-article-lead">Email: <?php echo $email; ?></p> <p class="uk-article-lead">SĐT: <?php echo $phone; ?></p> <p class="uk-article-lead">Điền thông tin vào mẫu dưới dây để hệ thống gửi email câu hỏi của bạn cho chúng tôi</p> <hr class="uk-article-divider"> <div> <form name="form_data" id="form_data" class="uk-form" method="POST" enctype="multipart/form-data" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>"> <!-- Hidden Value Section --> <!-- End Hidden Value Section --> <table class="ts-table"> <tr> <th><label for="txt_full_name">Tên đầy đủ:<span class="ts-alert">*</span></label></th> <td><input name="txt_full_name" class="uk-form-width-large" type="text" placeholder="Họ & Tên" required></td> </tr> <tr> <th><label for="txt_email">Email:<span class="ts-alert">*</span></label></th> <td><input name="txt_email" class="uk-form-width-large" type="text" placeholder="Email" required></td> </tr> <tr> <th><label for="txt_phone">Số điện thoại:<span class="ts-alert">*</span></label></th> <td><input name="txt_phone" class="uk-form-width-large" type="text" placeholder="Số điện thoại" required></td> </tr> <tr> <th><label for="txt_question">Nội dung thắc mắc:<span class="ts-alert">*</span></label></th> <td><textarea name="txt_question" class="uk-form-width-large" cols="21" rows="5" required></textarea></td> </tr> <tr> <th></th> <td><input type="submit" name="btn_submit" value="Gửi Yêu Cầu" class="uk-button uk-button-large uk-button-primary"></td> </tr> </table> </form> </div> </article> </section> <!-- End changable content --> <?php require_once DOCUMENT_ROOT . DIR_INCLUDE . 'footer.php'; ?> </div> </body> </html>
04-huanluyenviencanhan
trunk/master/contact.php
PHP
gpl3
4,528
<?php //require section require_once dirname(__FILE__) . '/shared/config/config.php'; require_once DOCUMENT_ROOT . DIR_SHARED_API . 'api_document_manage.php'; require_once DOCUMENT_ROOT . DIR_SHARED_LIBRARIES . 'lib_redirect.php'; require_once DOCUMENT_ROOT . DIR_SHARED_API . 'api_user.php'; require_once DOCUMENT_ROOT . DIR_SHARED_API . 'api_document.php'; $title = 'Quản lý bài tập'; ?> <!DOCTYPE html> <html> <head> <?php require_once DOCUMENT_ROOT . DIR_INCLUDE . 'head.php'; ?> </head> <body> <div class="uk-container uk-container-center uk-margin-top"> <?php require_once DOCUMENT_ROOT . DIR_INCLUDE . 'menu.php'; require_once DOCUMENT_ROOT . DIR_INCLUDE . 'slider.php'; if (empty($_SESSION['user_info'])) { lib_redirect::Redirect('/login.php'); } else { $user = $_SESSION['user_info']; } $paid_list = api_document_manage::get_paid_document($user['user_id']); $unpaid_list = api_document_manage::get_unpaid_document($user['user_id']); ?> <section id="main-content" class="ts-body-container"> <div> <div class="uk-panel uk-margin-bottom"> <h3 class="ts-category-title uk-text-center" data-uk-tooltip title="Danh sách <b style='color: #fff'> bài tập đã mua và được xử lý</b>"> <i class="uk-icon-folder-open"></i> Các bài tập đã mua <span>(<?php echo api_document_manage::count_paid_document($user['user_id']); ?> bài)</span> </h3> <div class="ts-category-content"> <?php if (empty($paid_list)) { echo 'Bạn chưa mua bài tập nào'; } foreach ($paid_list as $doc_id): $doc = api_document::get_document_by_id($doc_id); ?> <div class="ts-item"> <table> <tr> <td> <a href="doc_bought_detail.php?doc_id=<?php echo $doc['doc_id'] ?>"> <img alt="Document" src="<?php echo LINK_ROOT . DIR_SHARED_UPLOAD_IMAGES_DOCUMENT . $doc['doc_img_url']; ?>"> </a> </td> <td rowspan="2"> <div class="ts-item-title"> <a href="doc_bought_detail.php?doc_id=<?php echo $doc['doc_id'] ?>"><?php echo $doc['doc_name']; ?></a> </div> <?php $date = date_create($doc["doc_added_date"]); $date_str = date_format($date, "d/m/Y H:i"); ?> <div class="ts-item-date">Ngày gửi: <?php echo $date_str; ?></div> </td> </tr> </table> </div> <?php endforeach; ?> </div> </div> <div class="uk-panel uk-margin-bottom"> <h3 class="ts-category-title uk-text-center" data-uk-tooltip title="Danh sách <b style='color: #fff'> bài tập đã đặt mua nhưng chưa được xử lí</b>"> <i class="uk-icon-folder-open"></i> Các bài tập chờ xử lí <span>(<?php echo api_document_manage::count_unpaid_document($user['user_id']); ?> bài)</span> </h3> <div class="ts-category-content"> <?php if (empty($unpaid_list)) { echo 'Bạn không có bài tập nào chờ xử lí'; } foreach ($unpaid_list as $doc_id): $doc = api_document::get_document_by_id($doc_id); ?> <div class="ts-item"> <table> <tr> <td> <a href="doc_bought_detail.php?doc_id=<?php echo $doc['doc_id'] ?>"> <img alt="Document" src="<?php echo LINK_ROOT . DIR_SHARED_UPLOAD_IMAGES_DOCUMENT . $doc['doc_img_url']; ?>"> </a> </td> <td rowspan="2"> <div class="ts-item-title"> <a href="doc_bought_detail.php?doc_id=<?php echo $doc['doc_id'] ?>"><?php echo $doc['doc_name']; ?></a> </div> <?php $date = date_create($doc["doc_added_date"]); $date_str = date_format($date, "d/m/Y H:i"); ?> <div class="ts-item-date">Ngày gửi: <?php echo $date_str; ?></div> </td> </tr> </table> </div> <?php endforeach; ?> </div> </div> </div> </section> <?php require_once DOCUMENT_ROOT . DIR_INCLUDE . 'footer.php'; ?> </div> </body> </html>
04-huanluyenviencanhan
trunk/master/document_manage.php
PHP
gpl3
6,473
<?php require_once dirname(dirname(__FILE__)) . '/shared/config/config.php'; require_once DOCUMENT_ROOT . DIR_SHARED_API . 'api_multi_level.php'; if (!empty($_GET['category_choosen_id'])) { $category_chosen_id = $_GET['category_choosen_id']; // echo $category_chosen_id; $expand_id_list = api_multi_level::get_expand_id_list_news_category($category_chosen_id); } $root_list = api_multi_level::get_root_news_categories(); function multi_categories($expand_id_list) { // var_dump($expand_id_list); if (sizeof($expand_id_list) == 0) { return; } $list = api_multi_level::get_news_categories_by_parent_id($expand_id_list[count($expand_id_list) - 1]); unset($expand_id_list[count($expand_id_list) - 1]); ?> <ul> <?php foreach ($list as $item) { // var_dump($expand_id_list); if (in_array($item['cat_news_id'], $expand_id_list)) { ?> <li> <a href="javascript:void(0)"> <i class="uk-icon-minus" onclick="filldata('<?php echo $item['parent_cat_news']; ?>');"></i> </a> <a href="news.php?cat_id=<?php echo $item['cat_news_id']; ?>"><i class="uk-icon-folder-open"></i> <?php echo $item['cate_news_name']; ?></a> <?php multi_categories($expand_id_list); ?> </li> <?php } else { ?> <li> <a href="javascript:void(0)"> <i class="uk-icon-plus" onclick="filldata('<?php echo $item['cat_news_id']; ?>');"></i> </a> <a href="news.php?cat_id=<?php echo $item['cat_news_id']; ?>"><i class="uk-icon-folder"></i> <?php echo $item['cate_news_name']; ?></a> </li> <?php } } ?> </ul> <?php } if (empty($expand_id_list)) { $expand_id_list = array(); } foreach ($root_list as $root_item) { if (in_array($root_item['cat_news_id'], $expand_id_list)){ ?> <li> <a href="javascript:void(0)"> <i class="uk-icon-minus" onclick="filldata('0');"></i> </a> <a href="news.php?cat_id=<?php echo $root_item['cat_news_id']; ?>"><i class="uk-icon-folder-open"></i> <?php echo $root_item['cate_news_name']; ?></a> <?php if (!empty($expand_id_list)) { multi_categories($expand_id_list); } ?> </li> <?php } else { ?> <li> <a href="javascript:void(0)"> <i class="uk-icon-plus" onclick="filldata('<?php echo $root_item['cat_news_id']; ?>');"></i> </a> <a href="news.php?cat_id=<?php echo $root_item['cat_news_id']; ?>"><i class="uk-icon-folder"></i> <?php echo $root_item['cate_news_name']; ?></a> </li> <?php } } ?>
04-huanluyenviencanhan
trunk/master/ajax/news_folder_category.php
PHP
gpl3
3,496
<?php require_once dirname(dirname(__FILE__)) . '/shared/config/config.php'; require_once DOCUMENT_ROOT . DIR_SHARED_API . 'api_multi_level.php'; if (!empty($_GET['category_choosen_id'])) { $category_chosen_id = $_GET['category_choosen_id']; $expand_id_list = api_multi_level::get_expand_id_list_document_category($category_chosen_id); // var_dump($expand_id_list); } $root_list = api_multi_level::get_root_document_categories(); function multi_categories($expand_id_list) { // var_dump($expand_id_list); if (sizeof($expand_id_list) == 0) { return; } $list = api_multi_level::get_document_categories_by_parent_id($expand_id_list[count($expand_id_list) - 1]); unset($expand_id_list[count($expand_id_list) - 1]); ?> <ul> <?php foreach ($list as $item) { // var_dump($expand_id_list); if (in_array($item['cat_id'], $expand_id_list)) { ?> <li> <a href="javascript:void(0)"> <i class="uk-icon-minus" onclick="filldata('<?php echo $item['cat_parent_id']; ?>');"></i> </a> <a href="document.php?cat_id=<?php echo $item['cat_id']; ?>"><i class="uk-icon-folder-open"></i> <?php echo $item['cat_name']; ?></a> <?php multi_categories($expand_id_list); ?> </li> <?php } else { ?> <li> <a href="javascript:void(0)"> <i class="uk-icon-plus" onclick="filldata('<?php echo $item['cat_id']; ?>');"></i> </a> <a href="document.php?cat_id=<?php echo $item['cat_id']; ?>"><i class="uk-icon-folder"></i> <?php echo $item['cat_name']; ?></a> </li> <?php } } ?> </ul> <?php } if (empty($expand_id_list)) { $expand_id_list = array(); } foreach ($root_list as $root_item) { if (in_array($root_item['cat_id'], $expand_id_list)){ ?> <li> <a href="javascript:void(0)"> <i class="uk-icon-minus" onclick="filldata('0');"></i> </a> <a href="document.php?cat_id=<?php echo $root_item['cat_id']; ?>"><i class="uk-icon-folder-open"></i> <?php echo $root_item['cat_name']; ?></a> <?php if (!empty($expand_id_list)) { multi_categories($expand_id_list); } ?> </li> <?php } else { ?> <li> <a href="javascript:void(0)"> <i class="uk-icon-plus" onclick="filldata('<?php echo $root_item['cat_id']; ?>');"></i> </a> <a href="document.php?cat_id=<?php echo $root_item['cat_id']; ?>"><i class="uk-icon-folder"></i> <?php echo $root_item['cat_name']; ?></a> </li> <?php } } ?>
04-huanluyenviencanhan
trunk/master/ajax/document_folder_category.php
PHP
gpl3
3,459
<?php //require section require_once dirname(__FILE__) . '/shared/config/config.php'; require_once DOCUMENT_ROOT . DIR_SHARED_API . 'api_multi_level.php'; require_once DOCUMENT_ROOT . DIR_SHARED_API . 'api_news.php'; require_once DOCUMENT_ROOT . DIR_INCLUDE . 'usable_functions.php'; $title = 'Tin Tức'; ?> <!DOCTYPE html> <html> <head> <?php require_once DOCUMENT_ROOT . DIR_INCLUDE . 'head.php'; ?> </head> <body> <div class="uk-container uk-container-center uk-margin-top"> <?php require_once DOCUMENT_ROOT . DIR_INCLUDE . 'menu.php'; require_once DOCUMENT_ROOT . DIR_INCLUDE . 'slider.php'; ?> <section id="main-content" class="ts-body-container"> <div class="ts-left-wrapper"> <?php if (!empty($_GET['cat_id'])) { $cat_id = $_GET['cat_id']; $category = api_news::get_news_category_by_id($cat_id); show_news_category_group($category); } else { $category_groups = api_news::get_all_news_categories(); foreach ($category_groups as $group) { show_news_category_group($group); } } ?> </div> <script type="text/javascript"> function filldata(value) { $.ajax({ type: "GET", url: "<?php echo LINK_ROOT . DIR_AJAX; ?>news_folder_category.php", data: "category_choosen_id=" + value, success: function(result) { $("#category-list").html(result); } }); } $( document ).ready(function() { filldata('<?php echo $cat_id; ?>'); }); </script> <div class="ts-right-wrapper"> <div class="uk-panel uk-margin-bottom"> <div class="ts-category-title"><i class="uk-icon-list-ul"></i> Danh mục tin tức</div> <ul id="category-list" class="ts-category-list"> <?php show_news_root_list(); ?> </ul> </div> <div class="uk-panel uk-margin-bottom"> <div class="ts-category-title"><i class="uk-icon-bolt"></i> Tin tức mới nhất</div> <div class="ts-category-content"> <?php latest_news(5); ?> </div> </div> </div> </section> <?php require_once DOCUMENT_ROOT . DIR_INCLUDE . 'footer.php'; ?> </div> </body> </html>
04-huanluyenviencanhan
trunk/master/news.php
PHP
gpl3
3,229
<?php require_once dirname(__FILE__) . '/shared/config/config.php'; require_once DOCUMENT_ROOT . DIR_SHARED_API . 'api_security.php'; api_security::logout();
04-huanluyenviencanhan
trunk/master/logout.php
PHP
gpl3
162
<?php //require section require_once dirname(__FILE__) . '/shared/config/config.php'; require_once DOCUMENT_ROOT . DIR_SHARED_API . 'api_news.php'; require_once DOCUMENT_ROOT . DIR_SHARED_API . 'api_multi_level.php'; require_once DOCUMENT_ROOT . DIR_INCLUDE . 'usable_functions.php'; $title = 'Chi tiết tin Tức'; if (!empty($_GET['news_id'])) { $news_id = $_GET['news_id']; $news = api_news::get_news_by_id($news_id); } ?> <!DOCTYPE html> <html> <head> <?php require_once DOCUMENT_ROOT . DIR_INCLUDE . 'head.php'; ?> </head> <body> <div class="uk-container uk-container-center uk-margin-top"> <?php require_once DOCUMENT_ROOT . DIR_INCLUDE . 'menu.php'; require_once DOCUMENT_ROOT . DIR_INCLUDE . 'slider.php'; ?> <section id="main-content" class="ts-body-container"> <div class="ts-left-wrapper"> <section class="uk-panel uk-panel-box ts-padding-large"> <?php if (empty($_GET['news_id'])) { echo "<h2>Không tìm thấy tin tức này.</h2>"; } else { $news_id = $_GET['news_id']; $news = api_news::get_news_by_id($news_id); ?> <article class="uk-article"> <h1 class="uk-article-title ts-color-primary"><?php echo $news['news_title']; ?></h1> <?php $date = date_create($news["news_added_date"]); $date_str = date_format($date, "d/m/Y H:i"); ?> <p class="uk-article-meta">Ngày viết: <?php echo $date_str; ?></p> <hr class="uk-article-divider"> <div> <?php echo $news['news_content']; ?> </div> </article> <?php } ?> </section> </div> <script type="text/javascript"> function filldata(value) { $.ajax({ type: "GET", url: "<?php echo LINK_ROOT . DIR_AJAX; ?>news_folder_category.php", data: "category_choosen_id=" + value, success: function(result) { $("#category-list").html(result); } }); } </script> <div class="ts-right-wrapper"> <div class="uk-panel uk-margin-bottom"> <div class="ts-category-title"><i class="uk-icon-list-ul"></i> Danh mục tin tức</div> <ul id="category-list" class="ts-category-list"> <?php show_news_root_list(); ?> </ul> </div> <div class="uk-panel uk-margin-bottom"> <div class="ts-category-title"><i class="uk-icon-bolt"></i> Tin tức mới nhất</div> <div class="ts-category-content"> <?php latest_news(5); ?> </div> </div> </div> </section> <?php require_once DOCUMENT_ROOT . DIR_INCLUDE . 'footer.php'; ?> </div> </body> </html>
04-huanluyenviencanhan
trunk/master/news_detail.php
PHP
gpl3
3,927
<?php //require section require_once dirname(__FILE__) . '/shared/config/config.php'; require_once DOCUMENT_ROOT . DIR_SHARED_API . 'api_document.php'; require_once DOCUMENT_ROOT . DIR_SHARED_API . 'api_invoice.php'; require_once DOCUMENT_ROOT . DIR_SHARED_LIBRARIES . 'lib_redirect.php'; $title = 'Xác Nhận Tạo Đơn Hàng'; ?> <!DOCTYPE html> <html> <head> <?php require_once DOCUMENT_ROOT . DIR_INCLUDE . 'head.php'; ?> </head> <body> <div class="uk-container uk-container-center uk-margin-top"> <?php require_once DOCUMENT_ROOT . DIR_INCLUDE . 'menu.php'; require_once DOCUMENT_ROOT . DIR_INCLUDE . 'slider.php'; if (!empty($_POST['destroy'])) { $_SESSION['cart'][$_SESSION['user']] = array(); lib_redirect::Redirect('/index.php'); } if (!empty($_POST['create_invoice'])) { $list = $_SESSION['cart'][$_SESSION['user']]; api_invoice::create_invoice($list, $_SESSION['user']); $_SESSION['cart'][$_SESSION['user']] = array(); lib_redirect::Redirect('/index.php'); } ?> <section id="main-content" class="ts-body-container uk-panel uk-panel-box ts-padding-large"> <form action="?" method="POST" id="form_destroy_cart"> <input type="hidden" name="destroy" value="1"/> </form> <form action="?" method="POST" id="form_create_invoice"> <input type="hidden" name="create_invoice" value="1"/> </form> <div class="uk-text-center uk-text-bold">Danh Sách Bài Tập Muốn Mua</div> <table id="cart_table" class="uk-table uk-table-hover"> <thead> <tr> <th>STT</th> <th>Mã bài tập</th> <th>Tên bài tập</th> <th>Giá</th> </tr> </thead> <tbody> <?php $list = array(); if (!empty($_SESSION['cart'][$_SESSION['user']])) { $list = $_SESSION['cart'][$_SESSION['user']]; } $total_money = 0; foreach ($list as $num => $item_id) { $item = api_document::get_document_by_id($item_id); $total_money += $item['doc_price']; ?> <tr> <td><?php echo $num + 1; ?></td> <td><?php echo $item['doc_id']; ?></td> <td><?php echo $item['doc_name']; ?></td> <td class="uk-text-bold"><?php echo number_format($item['doc_price'], 0, '.', ','); ?> vnđ</td> </tr> <?php }?> </tbody> <tfoot> <tr> <td colspan="3" class="uk-text-large">Tổng cộng:</td> <td class="uk-text-bold uk-text-large"><?php echo number_format($total_money, 0, '.', ','); ?> vnđ</td> </tr> </tfoot> </table> <div class="uk-text-center"> <a href="cart.php#cart_table" class="uk-button">Quay lại giỏ hàng</a> <input type="submit" onclick="confirmDestroyCart();" name="btn_destroy" class="uk-button uk-button-danger" value="Hủy"> <input type="submit" name="btn_submit" onclick="confirmCreateInvoice();" class="uk-button uk-button-primary" value="Tạo đơn hàng"> </div> </section> <?php require_once DOCUMENT_ROOT . DIR_INCLUDE . 'footer.php'; ?> </div> </body> </html>
04-huanluyenviencanhan
trunk/master/checkout.php
PHP
gpl3
3,650
<?php //require section require_once dirname(__FILE__) . '/shared/config/config.php'; require_once DOCUMENT_ROOT . DIR_SHARED_API . 'api_security.php'; require_once DOCUMENT_ROOT . DIR_SHARED_API . 'api_news.php'; require_once DOCUMENT_ROOT . DIR_SHARED_API . 'api_invoice.php'; require_once DOCUMENT_ROOT . DIR_SHARED_API . 'api_document.php'; require_once DOCUMENT_ROOT . DIR_SHARED_API . 'api_buy.php'; require_once DOCUMENT_ROOT . DIR_SHARED_API . 'api_multi_level.php'; require_once DOCUMENT_ROOT . DIR_SHARED_API . 'api_statistics.php'; $category_groups = api_document::get_all_document_categories(); require_once DOCUMENT_ROOT . DIR_INCLUDE . 'usable_functions.php'; $title = 'Index'; ?> <!DOCTYPE html> <html> <head> <?php require_once DOCUMENT_ROOT . DIR_INCLUDE . 'head.php'; ?> </head> <body> <div class="uk-container uk-container-center uk-margin-top"> <?php require_once DOCUMENT_ROOT . DIR_INCLUDE . 'menu.php'; require_once DOCUMENT_ROOT . DIR_INCLUDE . 'slider.php'; ?> <section id="main-content" class="ts-body-container"> <div class="ts-left-wrapper"> <?php $newses = api_news::get_all_latest_news(4); $category = api_news::get_news_category_by_id($newses[0]['cat_news_id']); if (!empty($category) && count($category) > 0) { ?> <div class="uk-panel uk-margin-bottom"> <h3 class="ts-category-title"> <a href="<?php echo LINK_ROOT ?>/news.php?cat_id=<?php echo $category['cat_news_id']; ?>" data-uk-tooltip title="Xem tin tức thuộc <b style='color: #fff;'><?php echo $category['cate_news_name']; ?></b>"> <i class="uk-icon-folder-open"></i> <?php echo $category['cate_news_name']; ?> </a> </h3> <div class="ts-category-content"> <div class="entrygroup"> <div class="content"> <h3><b><a href="<?php echo LINK_ROOT ?>/news_detail.php?news_id=<?php echo $newses[0]['news_id']; ?>"><?php echo $newses[0]['news_title']; ?></a></b></h3> <div class="left-image"> <a href="<?php echo LINK_ROOT ?>/news_detail.php?news_id=<?php echo $newses[0]['news_id']; ?>"> <img class="thumb" style="padding-right:5px" src="<?php echo LINK_ROOT . DIR_SHARED_UPLOAD_IMAGES_NEWS . $newses[0]['news_img_url']; ?>" alt="<?php echo $newses[0]['news_img_url']; ?>"> </a> </div> <div class="right-content"> <p> <?php echo substr(strip_tags($newses[0]['news_content']), 0, 320); ?>... </p> </div> </div> <div class="clear"></div> <div class="relative"> <ul> <?php for ($index = 1; $index < count($newses); $index++) { ?> <li> <a href="<?php echo LINK_ROOT ?>/news_detail.php?news_id=<?php echo $newses[$index]['news_id']; ?>"> <?php echo $newses[$index]['news_title']; ?></a></li> <?php } ?> </ul> </div> </div> </div> </div> <?php } ?> <?php if (!empty($category_groups) && count($category_groups) > 0) { foreach ($category_groups as $group) { show_category_group($group, 6); } } ?> </div> <script type="text/javascript"> function filldata(value) { $.ajax({ type: "GET", url: "<?php echo LINK_ROOT . DIR_AJAX; ?>document_folder_category.php", data: "category_choosen_id=" + value, success: function (result) { $("#category-list").html(result); } }); } </script> <div class="ts-right-wrapper"> <div class="uk-panel uk-margin-bottom"> <div class="ts-category-title"><i class="uk-icon-list-ul"></i> Danh mục bài tập</div> <ul id="category-list" class="ts-category-list"> <!-- ajax loading --> <?php show_root_list(); ?> </ul> </div> <div class="uk-panel uk-margin-bottom"> <div class="ts-category-title"><i class="uk-icon-users"></i> Thống kê truy cập</div> <div class="ts-category-content">Tổng số lượt truy cập: <b><?php echo api_statistics::get_access_number(); ?></b></div> </div> </div> </section> <?php require_once DOCUMENT_ROOT . DIR_INCLUDE . 'footer.php'; ?> </div> </body> </html>
04-huanluyenviencanhan
trunk/master/index.php
PHP
gpl3
5,480
<?php // Initialize require_once dirname(__FILE__) . '/shared/config/config.php'; $title = 'Giới Thiệu'; // End Initialize require_once DOCUMENT_ROOT . DIR_SHARED_API . 'api_about_us.php'; $about_us = api_about_us::get_about_us(); require_once DOCUMENT_ROOT . DIR_SHARED_LIBRARIES . 'lib_date.php'; ?> <!DOCTYPE html> <html> <head> <?php require_once DOCUMENT_ROOT . DIR_INCLUDE . 'head.php'; ?> </head> <body> <div class="uk-container uk-container-center uk-margin-top"> <?php require_once DOCUMENT_ROOT . DIR_INCLUDE . 'menu.php'; require_once DOCUMENT_ROOT . DIR_INCLUDE . 'slider.php'; ?> <section id="main-content" class="ts-body-container uk-panel uk-panel-box ts-padding-large"> <article class="uk-article"> <h1 class="uk-article-title ts-color-primary"><?php echo $about_us['title']; ?></h1> <p class="uk-article-meta">Ngày viết: <?php echo date('d-m-Y', strtotime($about_us['date'])); ?></p> <hr class="uk-article-divider"> <div> <?php echo $about_us['content']; ?> </div> </article> </section> <?php require_once DOCUMENT_ROOT . DIR_INCLUDE . 'footer.php'; ?> </div> </body> </html>
04-huanluyenviencanhan
trunk/master/about_us.php
PHP
gpl3
1,339
<?php //require section require_once dirname(__FILE__) . '/shared/config/config.php'; require_once DOCUMENT_ROOT . DIR_SHARED_API . 'api_security.php'; $title = 'Đăng Kí'; ?> <!DOCTYPE html> <html> <head> <?php require_once DOCUMENT_ROOT . DIR_INCLUDE . 'head.php'; ?> </head> <body> <?php $email = ""; $password = ""; $password_confirm = ""; $first_name = ""; $last_name = ""; $address = ""; $phone = ""; if (!empty($_POST)) { if (!empty($_POST['txt_first_name'])) { $first_name = $_POST['txt_first_name']; } if (!empty($_POST['txt_last_name'])) { $last_name = $_POST['txt_last_name']; } if (!empty($_POST['txt_address'])) { $address = $_POST['txt_address']; } if (!empty($_POST['txt_phone'])) { $phone = $_POST['txt_phone']; } if (!empty($_POST['txt_email'])) { $email = $_POST['txt_email']; } if (!empty($_POST['txt_password'])) { $password = $_POST['txt_password']; } if (!empty($_POST['txt_password_confirm'])) { $password_confirm = $_POST['txt_password_confirm']; } $error_show = api_security::validate_user_info($email, $password, $password_confirm, $first_name, $last_name, $address, $phone); if (empty($error_show)) { if (api_security::register($email, $password, $first_name, $last_name, $address, $phone)) { $success_info = "Chúc mừng, bạn đã là thành viên."; $email = ""; $password = ""; $password_confirm = ""; $first_name = ""; $last_name = ""; $address = ""; $phone = ""; } } else { $password = ""; $password_confirm = ""; } } ?> <div class="uk-container uk-container-center uk-margin-top"> <?php require_once DOCUMENT_ROOT . DIR_INCLUDE . 'menu.php'; require_once DOCUMENT_ROOT . DIR_INCLUDE . 'slider.php'; ?> <!-- Changable content --> <section id="main-content" class="ts-body-container uk-panel uk-panel-box ts-padding-large"> <article class="uk-article"> <h1 class="uk-article-title ts-color-primary">Đăng Kí Thành Viên</h1> <hr class="uk-article-divider"> <div> <form name="form_data" id="form_data" class="uk-form" method="POST" enctype="multipart/form-data" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>"> <!-- Hidden Value Section --> <!-- End Hidden Value Section --> <?php if (!empty($error_show)) {?> <div class="error">Lỗi: <?php echo $error_show; ?></div> <?php } else if (!empty($success_info)) {?> <div class="success"><?php echo $success_info; ?></div> <?php }?> <table class="ts-table"> <tr> <th><label for="txt_first_name">Họ:<span class="ts-alert">*</span></label></th> <td><input name="txt_first_name" class="uk-form-width-large" value="<?php echo $first_name; ?>" type="text" placeholder="Họ" required></td> </tr> <tr> <th><label for="txt_last_name">Tên:<span class="ts-alert">*</span></label></th> <td><input name="txt_last_name" class="uk-form-width-large" value="<?php echo $last_name; ?>" type="text" placeholder="Tên" required></td> </tr> <tr> <th><label for="txt_address">Địa Chỉ:<span class="ts-alert">*</span></label></th> <td><input name="txt_address" class="uk-form-width-large" value="<?php echo $address; ?>" type="text" placeholder="Địa chỉ" required></td> </tr> <tr> <th><label for="txt_phone">Số Điện Thoại:<span class="ts-alert">*</span></label></th> <td><input name="txt_phone" class="uk-form-width-large" value="<?php echo $phone; ?>" type="text" placeholder="Số điện thoại" required></td> </tr> <tr> <th><label for="txt_email">Email:<span class="ts-alert">*</span></label></th> <td><input name="txt_email" class="uk-form-width-large" value="<?php echo $email; ?>" type="text" placeholder="Email" required></td> </tr> <tr> <th><label for="txt_password">Mật Mã:<span class="ts-alert">*</span></label></th> <td><input name="txt_password" class="uk-form-width-large" value="<?php echo $password; ?>" type="password" placeholder="Mật mã" required></td> </tr> <tr> <th><label for="txt_password_confirm">Xác Nhận Mật Mã:<span class="ts-alert">*</span></label></th> <td><input name="txt_password_confirm" class="uk-form-width-large" value="<?php echo $password_confirm; ?>" type="password" placeholder="Xác nhận mật mã" required></td> </tr> <tr> <th></th> <td><input type="submit" name="btn_submit" value="Đăng Kí" class="uk-button uk-button-large uk-button-primary"></td> </tr> </table> </form> </div> </article> </section> <!-- End changable content --> <?php require_once DOCUMENT_ROOT . DIR_INCLUDE . 'footer.php'; ?> </div> </body> </html>
04-huanluyenviencanhan
trunk/master/register.php
PHP
gpl3
6,823
<?php //define('LINK_ROOT', 'http://'. $_SERVER['HTTP_HOST']); //define('DOCUMENT_ROOT', $_SERVER['DOCUMENT_ROOT']); define('LINK_ROOT', 'http://' . $_SERVER['HTTP_HOST'] . '/04_huanluyenviencanhan'); define('DOCUMENT_ROOT', $_SERVER['DOCUMENT_ROOT'] . '/04_huanluyenviencanhan'); define('DIR_ADMIN', '/admin/'); define('DIR_ADMIN_INCLUDE', '/admin/include/'); define('DIR_INCLUDE', '/include/'); define('DIR_AJAX', '/ajax/'); define('DIR_SHARED_LAYOUT', '/shared/layout/'); define('DIR_SHARED_LAYOUT_CSS', '/shared/layout/css/'); define('DIR_SHARED_LAYOUT_JS', '/shared/layout/js/'); define('DIR_SHARED_LAYOUT_IMAGES', '/shared/layout/images/'); define('DIR_SHARED_LAYOUT_IMAGES_ICONS', '/shared/layout/images/icons/'); define('DIR_SHARED_LAYOUT_IMAGES_SLIDESHOW', '/shared/layout/images/slideshow/'); define('DIR_SHARED_LAYOUT_UIKIT', '/shared/layout/uikit/'); define('DIR_SHARED_LAYOUT_UIKIT_CSS', '/shared/layout/uikit/css/'); define('DIR_SHARED_LAYOUT_UIKIT_JS', '/shared/layout/uikit/js/'); define('DIR_SHARED_PLUGIN_WOWSLIDER', '/shared/plugin/wowslider/'); define('DIR_SHARED_PLUGIN_WOWSLIDER_CSS', '/shared/plugin/wowslider/css/'); define('DIR_SHARED_PLUGIN_WOWSLIDER_JS', '/shared/plugin/wowslider/js/'); define('DIR_SHARED', '/shared/'); define('DIR_SHARED_CONFIG', '/shared/config/'); define('DIR_SHARED_API', '/shared/api/'); define('DIR_SHARED_DAO', '/shared/dao/'); define('DIR_SHARED_LIBRARIES', '/shared/libraries/'); define('DIR_SHARED_PLUGIN', '/shared/plugin/'); define('DIR_SHARED_UPLOAD', '/shared/upload/'); define('DIR_SHARED_UPLOAD_DOCUMENTS', '/shared/upload/documents/'); define('DIR_SHARED_UPLOAD_IMAGES', '/shared/upload/images/'); define('DIR_SHARED_UPLOAD_IMAGES_DOCUMENT', '/shared/upload/images/document/'); define('DIR_SHARED_UPLOAD_IMAGES_NEWS', '/shared/upload/images/news/'); class config { // private $db_name = 'huanluye_db'; // private $db_host = 'localhost'; // private $db_user = 'huanluye_dbuser'; // private $db_pass = 'dbuser'; private $db_name = 'huanluye_db'; private $db_host = 'localhost'; private $db_user = 'root'; private $db_pass = ''; public function get_db_name() { return $this->db_name; } public function get_db_host() { return $this->db_host; } public function get_db_user() { return $this->db_user; } public function get_db_pass() { return $this->db_pass; } }
04-huanluyenviencanhan
trunk/master/shared/config/config.php
PHP
gpl3
2,493
<?php require_once dirname(__FILE__) . '/config.php'; class connection { public $con; public function __construct() { } public function open_connect() { $config = new config(); $db_host = $config->get_db_host(); $db_user = $config->get_db_user(); $db_pass = $config->get_db_pass(); $db_name = $config->get_db_name(); $this->con = new mysqli($db_host, $db_user, $db_pass, $db_name) or die("Can't connect to database"); $this->con->set_charset("utf8"); return $this->con; } public function close_connect() { mysqli_close($this->con); } }
04-huanluyenviencanhan
trunk/master/shared/config/connection.php
PHP
gpl3
674
<?php require_once dirname(dirname(__FILE__)) . '/config/config.php'; require_once DOCUMENT_ROOT . DIR_SHARED_CONFIG . 'connection.php'; class dao_invoice_line { //Methods public function __construct() { } public function get_all() { $db = new connection(); $con = $db->open_connect(); $query = "SELECT * FROM tbl_invoice_line"; /** @noinspection PhpParamsInspection */ $result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error()); $list = array(); while ($row = mysqli_fetch_array($result)) { array_push($list, $row); } $db->close_connect(); return $list; } public function save($invoice_line_id, $invoice_id, $doc_id, $money, $quantity) { $db = new connection(); $con = $db->open_connect(); if ($invoice_line_id == 0) { $query = "INSERT INTO tbl_invoice_line(invoice_id, doc_id, money, quantity) VALUES ( " . $invoice_id . "," . $doc_id . "," . $money . "," . $quantity . ")"; } else { $query = "UPDATE tbl_invoice_line SET " . "invoice_id = " . $invoice_id . "," . "doc_id = " . $doc_id . "," . "money = " . $money . "," . "quantity = " . $quantity . " " . "WHERE invoice_line_id = " . $invoice_line_id; } // echo $query; /** @noinspection PhpParamsInspection */ $result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error()); $db->close_connect(); return TRUE; } public function get_by_id($id) { $db = new connection(); $con = $db->open_connect(); $query = "SELECT * FROM tbl_invoice_line WHERE invoice_line_id = " . $id; /** @noinspection PhpParamsInspection */ $result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error()); $row = mysqli_fetch_array($result); $db->close_connect(); return $row; } public function delete($id) { $db = new connection(); $con = $db->open_connect(); $query = "DELETE FROM tbl_invoice_line WHERE invoice_line_id = " . $id; /** @noinspection PhpParamsInspection */ mysqli_query($con, $query) or die("Query fail: " . mysqli_error()); $db->close_connect(); return TRUE; } public function get_all_by_invoice_id($invoice_id) { $db = new connection(); $con = $db->open_connect(); $query = "SELECT * FROM tbl_invoice_line inl LEFT JOIN tbl_document d ON inl.doc_id = d.doc_id WHERE invoice_id = ".$invoice_id; /** @noinspection PhpParamsInspection */ $result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error()); $list = array(); while ($row = mysqli_fetch_array($result)) { array_push($list, $row); } $db->close_connect(); return $list; } }
04-huanluyenviencanhan
trunk/master/shared/dao/dao_invoice_line.php
PHP
gpl3
3,178
<?php require_once dirname(dirname(__FILE__)) . '/config/config.php'; require_once DOCUMENT_ROOT . DIR_SHARED_CONFIG . 'connection.php'; class dao_invoice { //Methods public function __construct() { } public function get_all() { $db = new connection(); $con = $db->open_connect(); $query = "SELECT * FROM tbl_invoice inv LEFT JOIN tbl_user u ON inv.user_id = u.user_id " . "LEFT JOIN tbl_inv_status ins ON inv.inv_status_id = ins.inv_status_id"; /** @noinspection PhpParamsInspection */ $result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error()); $list = array(); while ($row = mysqli_fetch_array($result)) { array_push($list, $row); } $db->close_connect(); return $list; } public function get_all_unpaid() { $db = new connection(); $con = $db->open_connect(); $query = "SELECT * FROM tbl_invoice inv LEFT JOIN tbl_user u ON inv.user_id = u.user_id " . "LEFT JOIN tbl_inv_status ins ON inv.inv_status_id = ins.inv_status_id WHERE ins.inv_status_id = 1"; /** @noinspection PhpParamsInspection */ $result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error()); $list = array(); while ($row = mysqli_fetch_array($result)) { array_push($list, $row); } $db->close_connect(); return $list; } public function get_all_paid() { $db = new connection(); $con = $db->open_connect(); $query = "SELECT * FROM tbl_invoice inv LEFT JOIN tbl_user u ON inv.user_id = u.user_id " . "LEFT JOIN tbl_inv_status ins ON inv.inv_status_id = ins.inv_status_id WHERE ins.inv_status_id = 2"; /** @noinspection PhpParamsInspection */ $result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error()); $list = array(); while ($row = mysqli_fetch_array($result)) { array_push($list, $row); } $db->close_connect(); return $list; } public function save($invoice_id, $user_id, $created_date, $inv_status_id, $total_money, $total_quantity) { $db = new connection(); $con = $db->open_connect(); if ($invoice_id == 0) { $query = "INSERT INTO tbl_invoice(user_id, created_date, inv_status_id, total_money, total_quantity) VALUES ( '" . $user_id . "','" . $created_date . "'," . $inv_status_id . "," . $total_money . "," . $total_quantity . ")"; } else { $query = "UPDATE tbl_invoice SET " . "user_id = '" . $user_id . "'," . "created_date = '" . $created_date . "'," . "inv_status_id = " . $inv_status_id . "," . "total_money = " . $total_money . "," . "total_quantity = " . $total_quantity . " " . "WHERE invoice_id = " . $invoice_id; } /** @noinspection PhpParamsInspection */ $result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error()); $inserted_id = mysqli_insert_id($db->con); $db->close_connect(); return $inserted_id; } public function get_by_id($id) { $db = new connection(); $con = $db->open_connect(); $query = "SELECT inv.*,u.first_name AS customer_name, u.email AS customer_email," . "u.phone AS customer_phone, ins.inv_status_name AS status_name " . "FROM tbl_invoice inv LEFT JOIN tbl_user u ON inv.user_id = u.user_id " . "LEFT JOIN tbl_inv_status ins ON inv.inv_status_id = ins.inv_status_id " . "WHERE invoice_id = " . $id; /** @noinspection PhpParamsInspection */ $result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error()); $row = mysqli_fetch_array($result); $db->close_connect(); return $row; } public function delete($id) { $db = new connection(); $con = $db->open_connect(); $query = "DELETE FROM tbl_invoice WHERE invoice_id = " . $id; /** @noinspection PhpParamsInspection */ mysqli_query($con, $query) or die("Query fail: " . mysqli_error()); $db->close_connect(); return TRUE; } }
04-huanluyenviencanhan
trunk/master/shared/dao/dao_invoice.php
PHP
gpl3
4,523
<?php require_once dirname(dirname(__FILE__)) . '/config/config.php'; require_once DOCUMENT_ROOT . DIR_SHARED_CONFIG . 'connection.php'; require_once DOCUMENT_ROOT . DIR_SHARED_LIBRARIES . 'lib_date.php'; class dao_news { //Methods public function __construct() { } public function get_all() { $db = new connection(); $con = $db->open_connect(); $query = "SELECT nc.cate_news_name AS news_cat_name, n.* FROM tbl_news n LEFT JOIN tbl_news_category nc ON n.cat_news_id = nc.cat_news_id"; /** @noinspection PhpParamsInspection */ $result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error()); $list = array(); while ($row = mysqli_fetch_array($result)) { array_push($list, $row); } $db->close_connect(); return $list; } public function save($news_id, $news_title, $news_content, $cat_news_id, $image) { $db = new connection(); $con = $db->open_connect(); if ($news_id == 0) { $query = "INSERT INTO tbl_news(news_title, news_content, cat_news_id, news_added_date, news_img_url) VALUES ( '" . $news_title . "','" . $news_content . "'," . $cat_news_id . ",'" . lib_date::get_now() . "','" . $image . "')"; } else { $query = "UPDATE tbl_news SET " . "news_title = '" . $news_title . "'," . "news_content = '" . $news_content . "'," . "cat_news_id = " . $cat_news_id . "," . "news_added_date = '" . lib_date::get_now() . "'," . "news_img_url = '" . $image . "' " . "WHERE news_id = " . $news_id; } /** @noinspection PhpParamsInspection */ $result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error()); $db->close_connect(); return TRUE; } public function get_by_id($id) { $db = new connection(); $con = $db->open_connect(); $query = "SELECT * FROM tbl_news WHERE news_id = " . $id; /** @noinspection PhpParamsInspection */ $result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error()); $row = mysqli_fetch_array($result); $db->close_connect(); return $row; } public function delete($id) { $db = new connection(); $con = $db->open_connect(); $query = "DELETE FROM tbl_news WHERE news_id = " . $id; /** @noinspection PhpParamsInspection */ mysqli_query($con, $query) or die("Query fail: " . mysqli_error()); $db->close_connect(); return TRUE; } public function count_by_category_id($category_id) { $db = new connection(); $con = $db->open_connect(); $query = "SELECT * FROM tbl_news WHERE cat_news_id = " . $category_id; /** @noinspection PhpParamsInspection */ $result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error()); $list = array(); while ($row = mysqli_fetch_array($result)) { array_push($list, $row); } $db->close_connect(); return count($list); } public function get_all_by_category_id($category_id) { $db = new connection(); $con = $db->open_connect(); $query = "SELECT * FROM tbl_news WHERE cat_news_id = " . $category_id; /** @noinspection PhpParamsInspection */ $result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error()); $list = array(); while ($row = mysqli_fetch_array($result)) { array_push($list, $row); } $db->close_connect(); return $list; } public function get_all_latest($num_news) { $db = new connection(); $con = $db->open_connect(); $query = "SELECT * FROM tbl_news ORDER BY news_added_date DESC LIMIT 0, " . $num_news; /** @noinspection PhpParamsInspection */ $result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error()); $list = array(); while ($row = mysqli_fetch_array($result)) { array_push($list, $row); } $db->close_connect(); return $list; } }
04-huanluyenviencanhan
trunk/master/shared/dao/dao_news.php
PHP
gpl3
4,502
<?php require_once dirname(dirname(__FILE__)) . '/config/config.php'; require_once DOCUMENT_ROOT . DIR_SHARED_CONFIG . 'connection.php'; require_once DOCUMENT_ROOT . DIR_SHARED_LIBRARIES . 'lib_date.php'; class dao_news_category { //Methods public function __construct() { } public function get_all() { $db = new connection(); $con = $db->open_connect(); $query = "SELECT c2.cate_news_name AS parent_cat_name, c1.* FROM tbl_news_category c1 LEFT JOIN tbl_news_category c2 ON c1.parent_cat_news = c2.cat_news_id"; /** @noinspection PhpParamsInspection */ $result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error()); $list = array(); while ($row = mysqli_fetch_array($result)) { array_push($list, $row); } $db->close_connect(); return $list; } public function save($cat_news_id, $cate_news_name, $parent_cat_news) { $db = new connection(); $con = $db->open_connect(); if (empty($parent_cat_news)) { $parent_cat_news = "NULL"; } if ($cat_news_id == 0) { $query = "INSERT INTO tbl_news_category(cate_news_name, parent_cat_news) VALUES ( '" . $cate_news_name . "'," . $parent_cat_news . ")"; } else { $query = "UPDATE tbl_news_category SET " . "cate_news_name = '" . $cate_news_name . "'," . "parent_cat_news = '" . $parent_cat_news . "' " . "WHERE cat_news_id = " . $cat_news_id; } /** @noinspection PhpParamsInspection */ $result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error()); $db->close_connect(); return TRUE; } public function get_by_id($id) { $db = new connection(); $con = $db->open_connect(); $query = "SELECT * FROM tbl_news_category WHERE cat_news_id = " . $id; /** @noinspection PhpParamsInspection */ $result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error()); $row = mysqli_fetch_array($result); $db->close_connect(); return $row; } public function delete($id) { $db = new connection(); $con = $db->open_connect(); $query = "DELETE FROM tbl_news_category WHERE cat_news_id = " . $id; /** @noinspection PhpParamsInspection */ mysqli_query($con, $query) or die("Query fail: " . mysqli_error()); $db->close_connect(); return TRUE; } public function get_root_categories() { $db = new connection(); $con = $db->open_connect(); $query = "SELECT * FROM tbl_news_category WHERE parent_cat_news is NULL OR parent_cat_news = 0"; /** @noinspection PhpParamsInspection */ $result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error()); $list = array(); while ($row = mysqli_fetch_array($result)) { array_push($list, $row); } $db->close_connect(); return $list; } public function get_all_children_by_parent_id($parent_id) { $db = new connection(); $con = $db->open_connect(); $query = "SELECT * FROM tbl_news_category where parent_cat_news = ".$parent_id; /** @noinspection PhpParamsInspection */ $result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error()); $list = array(); while ($row = mysqli_fetch_array($result)) { array_push($list, $row); } $db->close_connect(); return $list; } }
04-huanluyenviencanhan
trunk/master/shared/dao/dao_news_category.php
PHP
gpl3
3,855
<?php require_once dirname(dirname(__FILE__)) . '/config/config.php'; require_once DOCUMENT_ROOT . DIR_SHARED_CONFIG . 'connection.php'; class dao_buy_status { //Methods public function __construct() { } public function get_all() { $db = new connection(); $con = $db->open_connect(); $query = "SELECT * FROM tbl_buy_status"; /** @noinspection PhpParamsInspection */ $result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error()); $list = array(); while ($row = mysqli_fetch_array($result)) { array_push($list, $row); } $db->close_connect(); return $list; } public function save($buy_status_id, $buy_status_name, $buy_status_detail) { $db = new connection(); $con = $db->open_connect(); if ($buy_status_id == 0) { $query = "INSERT INTO tbl_buy_status(buy_status_name, buy_status_detail) VALUES ( '" . $buy_status_name . "','" . $buy_status_detail . "')"; } else { $query = "UPDATE tbl_buy_status SET " . "buy_status_name = '" . $buy_status_name . "'," . "buy_status_detail = '" . $buy_status_detail . "' " . "WHERE buy_status_id = " . $buy_status_id; } echo $query; /** @noinspection PhpParamsInspection */ $result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error()); $db->close_connect(); return TRUE; } public function get_by_id($id) { $db = new connection(); $con = $db->open_connect(); $query = "SELECT * FROM tbl_buy_status WHERE buy_status_id = " . $id; /** @noinspection PhpParamsInspection */ $result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error()); $row = mysqli_fetch_array($result); $db->close_connect(); return $row; } public function delete($id) { $db = new connection(); $con = $db->open_connect(); $query = "DELETE FROM tbl_buy_status WHERE buy_status_id = " . $id; /** @noinspection PhpParamsInspection */ mysqli_query($con, $query) or die("Query fail: " . mysqli_error()); $db->close_connect(); return TRUE; } }
04-huanluyenviencanhan
trunk/master/shared/dao/dao_buy_status.php
PHP
gpl3
2,441
<?php require_once dirname(dirname(__FILE__)) . '/config/config.php'; require_once DOCUMENT_ROOT . DIR_SHARED_CONFIG . 'connection.php'; class dao_inv_status { //Methods public function __construct() { } public function get_all() { $db = new connection(); $con = $db->open_connect(); $query = "SELECT * FROM tbl_inv_status"; /** @noinspection PhpParamsInspection */ $result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error()); $list = array(); while ($row = mysqli_fetch_array($result)) { array_push($list, $row); } $db->close_connect(); return $list; } public function save($inv_status_id, $inv_status_name, $inv_status_detail) { $db = new connection(); $con = $db->open_connect(); if ($inv_status_id == 0) { $query = "INSERT INTO tbl_inv_status(inv_status_name, inv_status_detail) VALUES ( '" . $inv_status_name . "','" . $inv_status_detail . "')"; } else { $query = "UPDATE tbl_inv_status SET " . "inv_status_name = '" . $inv_status_name . "'," . "inv_status_detail = '" . $inv_status_detail . "'" . "WHERE inv_status_id = " . $inv_status_id; } echo $query; /** @noinspection PhpParamsInspection */ $result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error()); $db->close_connect(); return TRUE; } public function get_by_id($id) { $db = new connection(); $con = $db->open_connect(); $query = "SELECT * FROM tbl_inv_status WHERE inv_status_id = " . $id; /** @noinspection PhpParamsInspection */ $result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error()); $row = mysqli_fetch_array($result); $db->close_connect(); return $row; } public function delete($id) { $db = new connection(); $con = $db->open_connect(); $query = "DELETE FROM tbl_inv_status WHERE inv_status_id = " . $id; /** @noinspection PhpParamsInspection */ mysqli_query($con, $query) or die("Query fail: " . mysqli_error()); $db->close_connect(); return TRUE; } }
04-huanluyenviencanhan
trunk/master/shared/dao/dao_inv_status.php
PHP
gpl3
2,420
<?php require_once dirname(dirname(__FILE__)) . '/config/config.php'; require_once DOCUMENT_ROOT . DIR_SHARED_CONFIG . 'connection.php'; require_once DOCUMENT_ROOT . DIR_SHARED_LIBRARIES . 'lib_date.php'; class dao_document { //Methods public function __construct() { } public function get_all() { $db = new connection(); $con = $db->open_connect(); $query = "SELECT dc.cat_name AS doc_cat_name,d.* FROM tbl_document d LEFT JOIN tbl_document_category dc ON d.doc_cat_id = dc.cat_id"; /** @noinspection PhpParamsInspection */ $result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error()); $list = array(); while ($row = mysqli_fetch_array($result)) { array_push($list, $row); } $db->close_connect(); return $list; } public function save($doc_id, $doc_name, $doc_detail, $doc_cat_id, $doc_price, $doc_img_url, $doc_file) { $db = new connection(); $con = $db->open_connect(); if ($doc_id == 0) { $query = "INSERT INTO tbl_document(doc_name, doc_detail, doc_cat_id, doc_price, doc_img_url, doc_file, doc_added_date) VALUES ( '" . $doc_name . "','" . $doc_detail . "'," . $doc_cat_id . "," . $doc_price . ",'" . $doc_img_url . "','" . $doc_file . "','" . lib_date::get_now() . "')"; } else { $query = "UPDATE tbl_document SET " . "doc_name = '" . $doc_name . "'," . "doc_detail = '" . $doc_detail . "'," . "doc_cat_id = " . $doc_cat_id . "," . "doc_price = " . $doc_price . "," . "doc_img_url = '" . $doc_img_url . "'," . "doc_added_date = '" . lib_date::get_now() . "'," . "doc_file = '" . $doc_file . "' " . "WHERE doc_id = " . $doc_id; } /** @noinspection PhpParamsInspection */ $result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error()); $db->close_connect(); return TRUE; } public function get_by_id($id) { $db = new connection(); $con = $db->open_connect(); $query = "SELECT dc.cat_name AS doc_cat_name,d.* FROM tbl_document d LEFT JOIN tbl_document_category dc ON d.doc_cat_id = dc.cat_id WHERE doc_id = " . $id; /** @noinspection PhpParamsInspection */ $result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error()); $row = mysqli_fetch_array($result); $db->close_connect(); return $row; } public function delete($id) { $db = new connection(); $con = $db->open_connect(); $query = "DELETE FROM tbl_document WHERE doc_id = " . $id; /** @noinspection PhpParamsInspection */ mysqli_query($con, $query) or die("Query fail: " . mysqli_error()); $db->close_connect(); return TRUE; } public function count_document_by_category_id($category_id) { $db = new connection(); $con = $db->open_connect(); $query = "SELECT * FROM tbl_document WHERE doc_cat_id = " . $category_id; /** @noinspection PhpParamsInspection */ $result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error()); $list = array(); while ($row = mysqli_fetch_array($result)) { array_push($list, $row); } $db->close_connect(); return count($list); } public function count_all() { $db = new connection(); $con = $db->open_connect(); $query = "SELECT * FROM tbl_document"; /** @noinspection PhpParamsInspection */ $result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error()); $list = array(); while ($row = mysqli_fetch_array($result)) { array_push($list, $row); } $db->close_connect(); return count($list); } public function get_all_documents_by_category_id($category_id) { $db = new connection(); $con = $db->open_connect(); $query = "SELECT * FROM tbl_document WHERE doc_cat_id = " . $category_id; /** @noinspection PhpParamsInspection */ $result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error()); $list = array(); while ($row = mysqli_fetch_array($result)) { array_push($list, $row); } $db->close_connect(); return $list; } }
04-huanluyenviencanhan
trunk/master/shared/dao/dao_document.php
PHP
gpl3
4,723
<?php require_once dirname(dirname(__FILE__)) . '/config/config.php'; require_once DOCUMENT_ROOT . DIR_SHARED_CONFIG . 'connection.php'; class dao_user { //Methods public function __construct() { } public function get_all() { $db = new connection(); $con = $db->open_connect(); $query = "SELECT * FROM tbl_user WHERE user_type = 2"; /** @noinspection PhpParamsInspection */ $result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error()); $list = array(); while ($row = mysqli_fetch_array($result)) { array_push($list, $row); } $db->close_connect(); return $list; } public function save($user_id, $email, $password, $user_type, $first_name, $last_name, $address, $phone) { $db = new connection(); $con = $db->open_connect(); if ($user_id == 0) { $query = "INSERT INTO tbl_user(email, password, user_type, first_name, last_name, address, phone) VALUES ( '" . $email . "','" . md5($password) . "'," . $user_type . ",'" . $first_name . "','" . $last_name . "','" . $address . "','" . $phone . "')"; } else { $query = "UPDATE tbl_user SET " . "email = '" . $email . "'," . "password = '" . $password . "'," . "user_type = " . $user_type . "," . "first_name = '" . $first_name . "'," . "last_name = '" . $last_name . "'," . "address = '" . $address . "'," . "phone = '" . $phone . "' " . "WHERE user_id = " . $user_id; } /** @noinspection PhpParamsInspection */ $result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error()); $db->close_connect(); return TRUE; } public function get_by_id($id) { $db = new connection(); $con = $db->open_connect(); $query = "SELECT * FROM tbl_user WHERE user_type = 2 AND user_id = " . $id; /** @noinspection PhpParamsInspection */ $result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error()); $row = mysqli_fetch_array($result); $db->close_connect(); return $row; } public function delete($id) { $db = new connection(); $con = $db->open_connect(); $query = "DELETE FROM tbl_user WHERE user_id = " . $id; /** @noinspection PhpParamsInspection */ mysqli_query($con, $query) or die("Query fail: " . mysqli_error()); $db->close_connect(); return TRUE; } public function get_by_login_info($email, $password) { $db = new connection(); $con = $db->open_connect(); $query = "SELECT * FROM tbl_user JOIN tbl_user_type on user_type = user_type_id " . "WHERE email = '" . $email . "' " . "AND password = '" . md5($password) . "'"; $result = mysqli_query($con, $query); if (!$result) { printf("Error: %s\n", mysqli_error($con)); exit(); } return mysqli_fetch_array($result); } public function get_by_email($email) { $db = new connection(); $con = $db->open_connect(); $query = "SELECT * FROM tbl_user WHERE user_type = 2 AND email = '".$email."'"; $result = mysqli_query($con, $query); if (!$result) { printf("Error: %s\n", mysqli_error($con)); exit(); } return mysqli_fetch_array($result); } public function update_password($email, $password_new) { $db = new connection(); $con = $db->open_connect(); $query = "UPDATE tbl_user SET " . "password = '" . md5($password_new) . "' " . "WHERE email = '" . $email . "'"; mysqli_query($con, $query) or die("Query fail: " . mysqli_error()); $db->close_connect(); return TRUE; } }
04-huanluyenviencanhan
trunk/master/shared/dao/dao_user.php
PHP
gpl3
4,195
<?php require_once dirname(dirname(__FILE__)) . '/config/config.php'; require_once DOCUMENT_ROOT . DIR_SHARED_CONFIG . 'connection.php'; class dao_document_category { //Methods public function __construct() { } public function get_all() { $db = new connection(); $con = $db->open_connect(); $query = "SELECT c2.cat_name AS cat_parent_name, c1.* FROM tbl_document_category c1 LEFT JOIN tbl_document_category c2 ON c1.cat_parent_id = c2.cat_id"; /** @noinspection PhpParamsInspection */ $result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error()); $list = array(); while ($row = mysqli_fetch_array($result)) { array_push($list, $row); } $db->close_connect(); return $list; } public function save($cat_id, $cat_name, $cat_parent_id) { $db = new connection(); $con = $db->open_connect(); if (empty($cat_parent_id)) { $cat_parent_id = "NULL"; } if ($cat_id == 0) { $query = "INSERT INTO tbl_document_category(cat_name, cat_parent_id) VALUES ( '" . $cat_name . "'," . $cat_parent_id . ")"; } else { $query = "UPDATE tbl_document_category SET " . "cat_name = '" . $cat_name . "'," . "cat_parent_id = '" . $cat_parent_id . "'" . "WHERE cat_id = " . $cat_id; } /** @noinspection PhpParamsInspection */ $result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error()); $db->close_connect(); return TRUE; } public function get_by_id($id) { $db = new connection(); $con = $db->open_connect(); $query = "SELECT * FROM tbl_document_category WHERE cat_id = " . $id; /** @noinspection PhpParamsInspection */ $result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error()); $row = mysqli_fetch_array($result); $db->close_connect(); return $row; } public function delete($id) { $db = new connection(); $con = $db->open_connect(); $query = "DELETE FROM tbl_document_category WHERE cat_id = " . $id; /** @noinspection PhpParamsInspection */ mysqli_query($con, $query) or die("Query fail: " . mysqli_error()); $db->close_connect(); return TRUE; } public function get_all_children_by_parent_id($parent_id) { $db = new connection(); $con = $db->open_connect(); $query = "SELECT * FROM tbl_document_category where cat_parent_id = ".$parent_id; /** @noinspection PhpParamsInspection */ $result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error()); $list = array(); while ($row = mysqli_fetch_array($result)) { array_push($list, $row); } $db->close_connect(); return $list; } public function get_root_categories() { $db = new connection(); $con = $db->open_connect(); $query = "SELECT * FROM tbl_document_category WHERE cat_parent_id is NULL OR cat_parent_id = 0"; /** @noinspection PhpParamsInspection */ $result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error()); $list = array(); while ($row = mysqli_fetch_array($result)) { array_push($list, $row); } $db->close_connect(); return $list; } }
04-huanluyenviencanhan
trunk/master/shared/dao/dao_document_category.php
PHP
gpl3
3,754
<?php require_once dirname(dirname(__FILE__)) . '/config/config.php'; require_once DOCUMENT_ROOT . DIR_SHARED_CONFIG . 'connection.php'; /** * Description of dao_general * @author Viet Anh */ class dao_general { public function __construct() { } public function check_option($option_name) { $db = new connection(); $con = $db->open_connect(); $query = "SELECT 1 FROM tbl_options WHERE name = '" . $option_name . "' LIMIT 1"; /** @noinspection PhpParamsInspection */ $result = mysqli_query($con, $query) or die('Query Failed' . mysqli_error()); if (mysqli_fetch_row($result)) { $db->close_connect(); return TRUE; } else { $db->close_connect(); return FALSE; } } public function set_option_value($option_name, $option_value) { $db = new connection(); $con = $db->open_connect(); if ($this->check_option($option_name)) { $query = "UPDATE tbl_options SET value = '" . $option_value . "' WHERE name = '" . $option_name . "'"; } else { $query = "INSERT INTO tbl_options(name, value) VALUES ('" . $option_name . "', '" . $option_value . "')"; } $result = mysqli_query($con, $query) or die('Failed'); $db->close_connect(); return TRUE; } public function get_option_value($option_name) { $db = new connection(); $con = $db->open_connect(); $query = "SELECT value FROM tbl_options WHERE name = '" . $option_name . "'"; $result = mysqli_query($con, $query) or die("Failed"); $row = mysqli_fetch_array($result); $db->close_connect(); return $row['value']; } } ?>
04-huanluyenviencanhan
trunk/master/shared/dao/dao_general.php
PHP
gpl3
1,977
<?php /** * User: Viet Anh * Date: 30/05/2014 * Time: 16:46 */ require_once dirname(dirname(__FILE__)) . '/config/config.php'; require_once DOCUMENT_ROOT . DIR_SHARED_CONFIG . 'connection.php'; class dao_document_manage { public function __construct() { } /** * @param $user_id * * @return array invoices of user */ public function get_invoice_by_user_id($user_id) { $db = new connection(); $con = $db->open_connect(); $query = "SELECT * FROM tbl_invoice WHERE user_id = " . $user_id; $result = mysqli_query($con, $query) or die('Failed to get invoices by user id!' . mysqli_error()); $list = array(); while ($row = mysqli_fetch_array($result)) { array_push($list, $row); } $db->close_connect(); return $list; } /** * @param $user_id * * @return array of paid invoices by user */ public function get_paid_invoice_by_user_id($user_id) { $all_invoice = $this->get_invoice_by_user_id($user_id); $paid_invoices = array(); foreach ($all_invoice as $invoice) { if ($invoice['inv_status_id'] == 2) { array_push($paid_invoices, $invoice); } } return $paid_invoices; } /** * @param $user_id * * @return array of unpaid invoices by user */ public function get_unpaid_invoice_by_user_id($user_id) { $all_invoice = $this->get_invoice_by_user_id($user_id); $paid_invoices = array(); foreach ($all_invoice as $invoice) { if ($invoice['inv_status_id'] == 1) { array_push($paid_invoices, $invoice); } } return $paid_invoices; } /** * @param $invoice_id * * @return array of invoice lines by invoice */ public function get_invoice_lines_by_inv_id($invoice_id) { $db = new connection(); $con = $db->open_connect(); $query = "SELECT * FROM tbl_invoice_line WHERE invoice_id = " . $invoice_id; $result = mysqli_query($con, $query) or die('Failed to get invoice lines by invoice id!' . mysqli_error()); $list = array(); while ($row = mysqli_fetch_array($result)) { array_push($list, $row); } $db->close_connect(); return $list; } public function get_list_all_docs_by_user($user_id) { $all_invoices = $this->get_invoice_by_user_id($user_id); $all_docs = array(); foreach ($all_invoices as $invoice) { $invoice_lines = $this->get_invoice_lines_by_inv_id($invoice['invoice_id']); foreach($invoice_lines as $line){ array_push($all_docs, $line['doc_id']); } } return $all_docs; } /** * @param $user_id * * @return array of documents id user bought */ public function get_list_processed($user_id) { $paid_invoices = $this->get_paid_invoice_by_user_id($user_id); $bought_docs = array(); foreach ($paid_invoices as $invoice) { $invoice_lines = $this->get_invoice_lines_by_inv_id($invoice['invoice_id']); foreach ($invoice_lines as $line) { array_push($bought_docs, $line['doc_id']); } } return $bought_docs; } /** * @param $user_id * * @return array of documents user unpaid */ public function get_list_processing($user_id) { $unpaid_invoices = $this->get_unpaid_invoice_by_user_id($user_id); $not_available_docs = array(); foreach ($unpaid_invoices as $invoice) { $invoice_lines = $this->get_invoice_lines_by_inv_id($invoice['invoice_id']); foreach ($invoice_lines as $line) { array_push($not_available_docs, $line['doc_id']); } } return $not_available_docs; } }
04-huanluyenviencanhan
trunk/master/shared/dao/dao_document_manage.php
PHP
gpl3
4,678
<?php require_once dirname(dirname(__FILE__)) . '/config/config.php'; require_once DOCUMENT_ROOT . DIR_SHARED_CONFIG . 'connection.php'; require_once DOCUMENT_ROOT . DIR_SHARED_LIBRARIES . 'lib_date.php'; class dao_buy_doc { //Methods public function __construct() { } public function get_all() { $db = new connection(); $con = $db->open_connect(); $query = "SELECT * FROM tbl_buy_doc"; /** @noinspection PhpParamsInspection */ $result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error()); $list = array(); while ($row = mysqli_fetch_array($result)) { array_push($list, $row); } $db->close_connect(); return $list; } public function save($buy_doc_id, $user_id, $doc_id, $buy_status_id) { $db = new connection(); $con = $db->open_connect(); if (empty($buy_status_id)) { $buy_status_id = "NULL"; } if ($buy_doc_id == 0) { $query = "INSERT INTO tbl_buy_doc(user_id, doc_id, buy_date, buy_status_id) VALUES ( " . $user_id . "," . $doc_id . ",'" . lib_date::get_now() . "'," . $buy_status_id . ")"; } else { $query = "UPDATE tbl_buy_doc SET " . "user_id = " . $user_id . "," . "doc_id = " . $doc_id . "," . "buy_date = '" . lib_date::get_now() . "'," . "buy_status_id = " . $buy_status_id . " " . "WHERE buy_doc_id = " . $buy_doc_id; } // echo $query; /** @noinspection PhpParamsInspection */ $result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error()); $db->close_connect(); return TRUE; } public function get_by_id($id) { $db = new connection(); $con = $db->open_connect(); $query = "SELECT * FROM tbl_buy_doc WHERE buy_doc_id = " . $id; /** @noinspection PhpParamsInspection */ $result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error()); $row = mysqli_fetch_array($result); $db->close_connect(); return $row; } public function delete($id) { $db = new connection(); $con = $db->open_connect(); $query = "DELETE FROM tbl_buy_doc WHERE buy_doc_id = " . $id; /** @noinspection PhpParamsInspection */ mysqli_query($con, $query) or die("Query fail: " . mysqli_error()); $db->close_connect(); return TRUE; } }
04-huanluyenviencanhan
trunk/master/shared/dao/dao_buy_doc.php
PHP
gpl3
2,694
<?php require_once dirname(dirname(__FILE__)) . '/config/config.php'; require_once DOCUMENT_ROOT . DIR_SHARED_CONFIG . 'connection.php'; class dao_super { protected $table_name = ""; protected $primary_key_column_name = ""; public function __construct() { } public function get_all() { $db = new connection(); $con = $db->open_connect(); $query = "SELECT * FROM " . $table_name; /** @noinspection PhpParamsInspection */ /** @noinspection PhpParamsInspection */ $result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error()); $list = array(); while ($row = mysqli_fetch_array($result)) { array_push($list, $row); } $db->close_connect(); return $list; } public function get_by_id($id) { $db = new connection(); $con = $db->open_connect(); $query = "SELECT * FROM ".$table_name." WHERE ".$primary_key_column_name." = " . $id; /** @noinspection PhpParamsInspection */ $result = mysqli_query($con, $query) or die("Query fail: " . mysqli_error()); $row = mysqli_fetch_array($result); $db->close_connect(); return $row; } public function delete($id) { $db = new connection(); $con = $db->open_connect(); $query = "DELETE FROM ".$table_name." WHERE ".$primary_key_column_name." = " . $id; /** @noinspection PhpParamsInspection */ mysqli_query($con, $query) or die("Query fail: " . mysqli_error()); $db->close_connect(); return TRUE; } }
04-huanluyenviencanhan
trunk/master/shared/dao/dao_super.php
PHP
gpl3
1,700
<?php require_once dirname(dirname(__FILE__)) . '/config/config.php'; class lib_redirect { // public static function Redirect($redirect_link, $permanent = false) { // if (headers_sent() === false) { // header('Location: ' . LINK_ROOT . $redirect_link, true, ($permanent === true) ? 301 : 302); // } // exit(); // } // // public static function redirect_with_html($redirect_link) { // $redirect = "<script type='text/javascript'>window.location='" . LINK_ROOT . $redirect_link . "'</script>"; // echo $redirect; // } public static function Redirect($url) { if (!headers_sent()) { header('Location: ' . LINK_ROOT . $url); exit; } else { echo '<script type="text/javascript">'; echo 'window.location.href="' . LINK_ROOT . $url . '";'; echo '</script>'; echo '<noscript>'; echo '<meta http-equiv="refresh" content="0;url=' . LINK_ROOT . $url . '" />'; echo '</noscript>'; exit; } } }
04-huanluyenviencanhan
trunk/master/shared/libraries/lib_redirect.php
PHP
gpl3
1,117
<?php class lib_upload { public $input_control_name; public $upload_location; public function __construct() { } public function upload_file($input_control_name, $upload_location) { $name = $_FILES[$input_control_name]['name']; $tmp_name = $_FILES[$input_control_name]['tmp_name']; $upload_location .= $name; move_uploaded_file($tmp_name, $upload_location) or die('Upload file failed!'); return true; } }
04-huanluyenviencanhan
trunk/master/shared/libraries/lib_upload.php
PHP
gpl3
502
<?php class lib_pager { public $total_page; public $current_page; public $page_size; public $total_list; public $current_list; public function __construct() { } public function get_total_page($list_total, $page_size) { return ceil((count($list_total) / $page_size)); } public function get_current_page_list($page_size, $current_page, $list_total) { $skip = ($current_page - 1) * $page_size; // skip = 0 $current_list = array_slice($list_total, $skip, $page_size); return $current_list; } }
04-huanluyenviencanhan
trunk/master/shared/libraries/lib_pager.php
PHP
gpl3
604
<?php class lib_data_input { public $data; public function __construct() { } public function data_input($data) { $data1 = trim($data); $data2 = stripslashes($data1); $data3 = htmlspecialchars($data2); return $data3; } }
04-huanluyenviencanhan
trunk/master/shared/libraries/lib_data_input.php
PHP
gpl3
304
<?php class lib_date { public function __construct() { } public static function get_now() { return date("Y-m-d H:i:s"); } }
04-huanluyenviencanhan
trunk/master/shared/libraries/lib_date.php
PHP
gpl3
164
<?php require_once dirname(dirname(__FILE__)) . '/config/config.php'; require_once DOCUMENT_ROOT . DIR_SHARED_DAO . "dao_news.php"; require_once DOCUMENT_ROOT . DIR_SHARED_DAO . "dao_news_category.php"; require_once DOCUMENT_ROOT . DIR_SHARED_LIBRARIES . 'lib_redirect.php'; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * Description of api_security * * @author Thien */ class api_news { public static function get_all_news() { $news_access = new dao_news(); $newses = $news_access->get_all(); return $newses; } public static function get_all_news_categories() { $news_category_access = new dao_news_category(); return $news_category_access->get_all(); } public static function delete_news($id) { $news_access = new dao_news(); $news_access->delete($id); return TRUE; } public static function delete_news_category($id) { $news_category_access = new dao_news_category(); $news_category_access->delete($id); return TRUE; } public static function save_news($news_id, $news_title, $news_content, $cat_news_id, $image) { $news_access = new dao_news(); $news_access->save($news_id,$news_title,$news_content,$cat_news_id, $image); return TRUE; } public static function save_news_category($cat_id, $cate_news_name, $parent_cat_news) { $news_category_access = new dao_news_category(); $news_category_access->save($cat_id,$cate_news_name,$parent_cat_news); return TRUE; } public static function get_news_by_id($id) { $news_access = new dao_news(); return $news_access->get_by_id($id); } public static function get_news_category_by_id($id) { $news_category_access = new dao_news_category(); return $news_category_access->get_by_id($id); } public static function count_news_by_category_id($category_id) { $news_access = new dao_news(); return $news_access->count_by_category_id($category_id); } public static function get_all_news_by_category_id($category_id) { $news_access = new dao_news(); return $news_access->get_all_by_category_id($category_id); } public static function get_all_latest_news($num_news) { $news_access = new dao_news(); return $news_access->get_all_latest($num_news); } public static function validate_news_fields($title, $content, $cat_id, $image) { $error_show = ""; if (empty($title)) { $error_show .= "Bạn quên nhập tên tiều đề."; } else if (empty($content)) { $error_show .= "Bạn quên nhập nội dung."; } else if (empty($cat_id)) { $error_show .= "Bạn chưa chọn loại tài liệu."; } else if (empty($image)) { $error_show .= "Bạn chưa chọn hình ảnh minh họa."; } // } else if (empty($price)) { // $error_show .= "Bạn quên nhập giá."; // } else if (!is_numeric($price)) { // $error_show .= "Giá phải là số."; // } else if (empty($image)) { // $error_show .= "Bạn chưa tải hình ảnh lên."; // } else if (empty($file)) { // $error_show .= "Bạn chưa tải tập tin lên."; // } return $error_show; } public static function validate_category_fields($name) { $error_show = ""; if (empty($name)) { $error_show .= "Bạn quên nhập tên loại."; } return $error_show; } }
04-huanluyenviencanhan
trunk/master/shared/api/api_news.php
PHP
gpl3
3,920
<?php /** * User: Viet Anh * Date: 30/05/2014 * Time: 16:41 */ require_once dirname(dirname(__FILE__)) . '/config/config.php'; require_once DOCUMENT_ROOT . DIR_SHARED_DAO . 'dao_document_manage.php'; class api_document_manage { public function __construct() { } public static function get_paid_document($user_id) { $dao_document_manage = new dao_document_manage(); return $dao_document_manage->get_list_processed($user_id); } public static function get_unpaid_document($user_id) { $dao_document_manage = new dao_document_manage(); return $dao_document_manage->get_list_processing($user_id); } public static function count_paid_document($user_id) { $paid_documents = self::get_paid_document($user_id); return sizeof($paid_documents); } public static function count_unpaid_document($user_id) { $unpaid_documents = self::get_unpaid_document($user_id); return sizeof($unpaid_documents); } public static function check_if_doc_paid($user_id, $doc_id) { $paid_documents = self::get_paid_document($user_id); foreach ($paid_documents as $document) { if ($document == $doc_id) { return TRUE; } } return FALSE; } public static function check_if_doc_wait($user_id, $doc_id) { $unpaid_documents = self::get_unpaid_document($user_id); foreach ($unpaid_documents as $document) { if ($document == $doc_id) { return TRUE; } } return FALSE; } }
04-huanluyenviencanhan
trunk/master/shared/api/api_document_manage.php
PHP
gpl3
1,919
<?php require_once dirname(dirname(__FILE__)) . '/config/config.php'; require_once DOCUMENT_ROOT . DIR_SHARED_DAO . "dao_user.php"; require_once DOCUMENT_ROOT . DIR_SHARED_LIBRARIES . 'lib_redirect.php'; require_once DOCUMENT_ROOT . DIR_SHARED_API . 'api_security.php'; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * Description of api_security * * @author Thien */ class api_user { public static function get_all_user() { $user_access = new dao_user(); $useres = $user_access->get_all(); return $useres; } public static function get_all_user_categories() { $user_category_access = new dao_user_category(); return $user_category_access->get_all(); } public static function delete_user($id) { $user_access = new dao_user(); $user_access->delete($id); return TRUE; } public static function delete_user_category($id) { $user_category_access = new dao_user_category(); $user_category_access->delete($id); return TRUE; } public static function save_user($user_id, $email, $first_name, $last_name, $address, $phone) { $user_access = new dao_user(); if ($user_id == 0) { $password = "123456"; } else { $user = self::get_user_by_id($user_id); $password = $user['password']; } $user_access->save($user_id,$email,$password,2,$first_name,$last_name,$address,$phone); return TRUE; } public static function add_user_category($cate_user_name, $parent_cat_user) { $user_category_access = new dao_user_category(); $user_category_access->save(0,$cate_user_name,$parent_cat_user); return TRUE; } public static function get_user_by_id($id) { $user_access = new dao_user(); return $user_access->get_by_id($id); } public static function get_user_category_by_id($id) { $user_category_access = new dao_user_category(); return $user_category_access->get_by_id($id); } public static function count_user_by_category_id($category_id) { $user_access = new dao_user(); return $user_access->count_by_category_id($category_id); } public static function get_all_user_by_category_id($category_id) { $user_access = new dao_user(); return $user_access->get_all_by_category_id($category_id); } public static function get_all_latest_user($num_user) { $user_access = new dao_user(); return $user_access->get_all_latest($num_user); } public static function email_exists($email) { $dao_user = new dao_user(); $list = $dao_user->get_by_email($email); if (!empty($list) && count($list) > 0) { return TRUE; } return FALSE; } public static function get_user_by_email($email) { $dao_user = new dao_user(); $user = $dao_user->get_by_email($email); return $user; } public static function validate_user_fields($user_id, $email_save, $first_name_save, $last_name_save, $address_save, $phone_save) { $error_show = ""; if (empty($email_save)) { $error_show .= "Bạn quên nhập email."; } else if (!filter_var($email_save, FILTER_VALIDATE_EMAIL)) { $error_show .= "Email không hợp lệ."; } else if (self::email_exists($email_save) && $user_id == 0) { $error_show .= "Email đã tồn tại. Vui lòng chọn email khác."; } else if (empty($first_name_save)) { $error_show .= "Bạn quên nhập họ."; } else if (empty($last_name_save)) { $error_show .= "Bạn quên nhập tên."; } else if (empty($address_save)) { $error_show .= "Bạn quên nhập địa chỉ."; } else if (empty($phone_save)) { $error_show .= "Bạn quên nhập số điện thoại."; } else if (!is_numeric($phone_save)) { $error_show .= "Số điện thoại chỉ được nhập số."; } return $error_show; } }
04-huanluyenviencanhan
trunk/master/shared/api/api_user.php
PHP
gpl3
4,472
<?php require_once dirname(dirname(__FILE__)) . '/config/config.php'; require_once DOCUMENT_ROOT . DIR_SHARED_API . 'api_general.php'; require_once DOCUMENT_ROOT . DIR_SHARED_LIBRARIES . 'lib_date.php'; /** * Class api_about_us * @author Viet Anh */ class api_contact { public static function get_contact() { $dao_general = new dao_general(); $email = $dao_general->get_option_value('contact_email'); $phone = $dao_general->get_option_value('contact_phone'); $about_us = array('email' => $email, 'phone' => $phone); return $about_us; } public static function set_contact($email, $phone) { $dao_general = new dao_general(); $dao_general->set_option_value('contact_email', $email); $dao_general->set_option_value('contact_phone', $phone); return TRUE; } public static function validate_contact($email, $phone) { $error_show = ""; if (empty($email)) { $error_show .= "Vui lòng điền Email"; } else if (empty($email)) { $error_show .= "Vui lòng điền Số điện thoại"; } else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $error_show .= "Email không hợp lệ."; } return $error_show; } }
04-huanluyenviencanhan
trunk/master/shared/api/api_contact.php
PHP
gpl3
1,498
<?php require_once dirname(dirname(__FILE__)) . '/config/config.php'; require_once DOCUMENT_ROOT . DIR_SHARED_API . 'api_document.php'; require_once DOCUMENT_ROOT . DIR_SHARED_API . 'api_user.php'; require_once DOCUMENT_ROOT . DIR_SHARED_DAO . "dao_invoice.php"; require_once DOCUMENT_ROOT . DIR_SHARED_DAO . "dao_invoice_line.php"; require_once DOCUMENT_ROOT . DIR_SHARED_DAO . "dao_inv_status.php"; require_once DOCUMENT_ROOT . DIR_SHARED_LIBRARIES . 'lib_redirect.php'; require_once DOCUMENT_ROOT . DIR_SHARED_LIBRARIES . 'lib_date.php'; class api_invoice { public static function get_all_invoice_statuses() { $inv_status_access = new dao_inv_status(); return $inv_status_access->get_all(); } public static function get_all_invoices() { $invoice_access = new dao_invoice(); return $invoice_access->get_all(); } public static function get_all_unpaid_invoices() { $invoice_access = new dao_invoice(); return $invoice_access->get_all_unpaid(); } public static function get_all_paid_invoices() { $invoice_access = new dao_invoice(); return $invoice_access->get_all_paid(); } public static function get_all_lines_by_invoice_id($invoice_id) { $invoice_line_access = new dao_invoice_line(); return $invoice_line_access->get_all_by_invoice_id($invoice_id); } public static function delete_invoice_status($id) { $inv_status_access = new dao_inv_status(); $inv_status_access->delete($id); return TRUE; } public static function delete_invoice($invoice_id) { $invoice_access = new dao_invoice(); $invoice_access->delete($invoice_id); return TRUE; } public static function delete_invoice_line($id) { $invoice_line_access = new dao_invoice_line(); $invoice_line_access->delete($id); return TRUE; } public static function save_invoice_line($invoice_line_id, $invoice_id, $doc_id, $money, $quantity) { $invoice_line_access = new dao_invoice_line(); $invoice_line_access->save($invoice_line_id,$invoice_id,$doc_id,$money,$quantity); return TRUE; } public static function save_invoice($invoice_id, $user_id, $created_date, $inv_status_id, $total_money, $total_quantity) { $invoice_access = new dao_invoice(); return $invoice_access->save($invoice_id, $user_id, $created_date, $inv_status_id, $total_money, $total_quantity); } public static function save_invoice_status($inv_status_id, $inv_status_name, $inv_status_detail) { $inv_status_access = new dao_inv_status(); $inv_status_access->save($inv_status_id,$inv_status_name,$inv_status_detail); return TRUE; } public static function get_invoice_status_by_id($id) { $inv_status_access = new dao_inv_status(); return $inv_status_access->get_by_id($id); } public static function get_invoice_by_id($id) { $invoice_access = new dao_invoice(); return $invoice_access->get_by_id($id); } public static function get_invoice_line_by_id($id) { $invoice_line_access = new dao_invoice_line(); return $invoice_line_access->get_by_id($id); } public static function process_invoice($id) { $invoice_access = new dao_invoice(); $invoice = $invoice_access->get_by_id($id); return $invoice_access->save($invoice['invoice_id'], $invoice['user_id'], $invoice['created_date'], 2, $invoice['total_money'], $invoice['total_quantity']); } public static function create_invoice($doc_ids, $user_email) { $total_money = 0; $total_quantity = 0; $user = api_user::get_user_by_email($user_email); $invoice_id = self::save_invoice(0, $user['user_id'], lib_date::get_now(), 1, $total_money, $total_quantity); foreach ($doc_ids as $doc_id) { $document = api_document::get_document_by_id($doc_id); self::save_invoice_line(0, $invoice_id, $doc_id, $document['doc_price'], 1); $total_money += $document['doc_price']; $total_quantity += 1; } self::save_invoice($invoice_id, $user['user_id'], lib_date::get_now(), 1, $total_money, $total_quantity); } }
04-huanluyenviencanhan
trunk/master/shared/api/api_invoice.php
PHP
gpl3
4,440
<?php require_once dirname(dirname(__FILE__)) . '/config/config.php'; require_once DOCUMENT_ROOT . DIR_SHARED_DAO . "dao_document.php"; require_once DOCUMENT_ROOT . DIR_SHARED_DAO . "dao_document_category.php"; require_once DOCUMENT_ROOT . DIR_SHARED_LIBRARIES . 'lib_redirect.php'; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * Description of api_security * * @author Thien */ class api_document { public static function get_all_documents() { $document_access = new dao_document(); return $document_access->get_all(); } public static function get_all_document_categories() { $document_category_access = new dao_document_category(); return $document_category_access->get_all(); } public static function delete_document($id) { $document_access = new dao_document(); $document_access->delete($id); return TRUE; } public static function delete_document_category($id) { $document_category_access = new dao_document_category(); $document_category_access->delete($id); return TRUE; } public static function save_document($doc_id, $doc_name, $doc_detail, $doc_cat_id, $doc_price, $doc_img_url, $doc_file) { $document_access = new dao_document(); $document_access->save($doc_id,$doc_name,$doc_detail,$doc_cat_id,$doc_price,$doc_img_url,$doc_file); return TRUE; } public static function save_document_category($cat_id, $cat_name, $cat_parent_id) { $document_category_access = new dao_document_category(); $document_category_access->save($cat_id,$cat_name,$cat_parent_id); return TRUE; } public static function get_document_by_id($id) { $user_access = new dao_document(); return $user_access->get_by_id($id); } public static function get_document_category_by_id($id) { $document_category_access = new dao_document_category(); return $document_category_access->get_by_id($id); } public static function count_document_by_category_id($category_id) { $document_access = new dao_document(); return $document_access->count_document_by_category_id($category_id); } public static function count_all_documents() { $document_access = new dao_document(); return $document_access->count_all(); } public static function get_all_documents_by_category_id($category_id) { $document_access = new dao_document(); return $document_access->get_all_documents_by_category_id($category_id); } public static function validate_document_fields($name, $detail, $cat_id, $price, $image, $file) { $error_show = ""; if (empty($name)) { $error_show .= "Bạn quên nhập tên tài liệu."; } else if (empty($detail)) { $error_show .= "Bạn quên nhập chi tiết."; } else if (empty($cat_id)) { $error_show .= "Bạn chưa chọn loại tài liệu."; } else if (empty($price)) { $error_show .= "Bạn quên nhập giá."; } else if (!is_numeric($price)) { $error_show .= "Giá phải là số."; } else if (empty($image)) { $error_show .= "Bạn chưa tải hình ảnh lên."; } else if (empty($file)) { $error_show .= "Bạn chưa tải tập tin lên."; } return $error_show; } public static function validate_category_fields($name) { $error_show = ""; if (empty($name)) { $error_show .= "Bạn quên nhập tên loại."; } return $error_show; } }
04-huanluyenviencanhan
trunk/master/shared/api/api_document.php
PHP
gpl3
3,965
<?php require_once dirname(dirname(__FILE__)) . '/config/config.php'; require_once DOCUMENT_ROOT . DIR_SHARED_API . 'api_general.php'; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * Description of api_security * * @author Thien */ class api_statistics { public static function get_access_number() { $access_number = 0; $dao_general = new dao_general(); if (!$dao_general->check_option("access_number")) { $dao_general->set_option_value("access_number", "0"); } else { $access_number = $dao_general->get_option_value("access_number"); } return $access_number; } public static function increase_access_number() { $dao_general = new dao_general(); if (!$dao_general->check_option("access_number")) { $dao_general->set_option_value("access_number", "1"); } else { $access_number = $dao_general->get_option_value("access_number"); $dao_general->set_option_value("access_number", $access_number + 1); } } }
04-huanluyenviencanhan
trunk/master/shared/api/api_statistics.php
PHP
gpl3
1,261
<?php require_once dirname(dirname(__FILE__)) . '/config/config.php'; require_once DOCUMENT_ROOT . DIR_SHARED_DAO . 'dao_general.php'; /** * Description of api_general * @author Viet Anh */ class api_general { public static function check_option($option_name) { $dao_general = new dao_general(); return $dao_general->check_option($option_name); } public static function set_option($option_name, $option_value) { $dao_general = new dao_general(); return $dao_general->set_option_value($option_name, $option_value); } public static function get_option($option_name) { $dao_general = new dao_general(); return $dao_general->get_option_value($option_name); } }
04-huanluyenviencanhan
trunk/master/shared/api/api_general.php
PHP
gpl3
847
<?php require_once dirname(dirname(__FILE__)) . '/config/config.php'; require_once DOCUMENT_ROOT . DIR_SHARED_DAO . "dao_document_category.php"; require_once DOCUMENT_ROOT . DIR_SHARED_DAO . "dao_news_category.php"; class api_multi_level { public static function get_expand_id_list($chosen_category_id, $dao, $parent_key, $get_value_key) { $list = array(); $category = $dao->get_by_id($chosen_category_id); $list[sizeof($list)] = $chosen_category_id; // var_dump($category); // var_dump($list); while (!empty($category[$parent_key])) { $category = $dao->get_by_id($category[$parent_key]); $list[sizeof($list)] = $category[$get_value_key]; } return $list; } public static function get_root_document_categories() { $document_category_access = new dao_document_category(); return $document_category_access->get_root_categories(); } public static function get_root_news_categories() { $news_category_access = new dao_news_category(); return $news_category_access->get_root_categories(); } public static function get_expand_id_list_document_category($chosen_category_id) { $document_category_access = new dao_document_category(); $expand_id_list = self::get_expand_id_list($chosen_category_id, $document_category_access, 'cat_parent_id', 'cat_id'); return $expand_id_list; } public static function get_expand_id_list_news_category($chosen_category_id) { $news_category_access = new dao_news_category(); $expand_id_list = self::get_expand_id_list($chosen_category_id, $news_category_access, 'parent_cat_news', 'cat_news_id'); return $expand_id_list; } public static function get_document_categories_by_parent_id($parent_id) { $document_category_access = new dao_document_category(); return $document_category_access->get_all_children_by_parent_id($parent_id); } public static function get_news_categories_by_parent_id($parent_id) { $news_category_access = new dao_news_category(); return $news_category_access->get_all_children_by_parent_id($parent_id); } }
04-huanluyenviencanhan
trunk/master/shared/api/api_multi_level.php
PHP
gpl3
2,318
<?php require_once dirname(dirname(__FILE__)) . '/config/config.php'; require_once DOCUMENT_ROOT . DIR_SHARED_DAO . "dao_buy_doc.php"; require_once DOCUMENT_ROOT . DIR_SHARED_DAO . "dao_buy_status.php"; require_once DOCUMENT_ROOT . DIR_SHARED_LIBRARIES . 'lib_redirect.php'; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * Description of api_security * * @author Thien */ class api_buy { public static function get_all_buy_docs() { $buy_doc_access = new dao_buy_doc(); return $buy_doc_access->get_all(); } public static function get_all_buy_statuses() { $buy_status_access = new dao_buy_status(); return $buy_status_access->get_all(); } public static function delete_buy_doc($id) { $buy_doc_access = new dao_buy_doc(); $buy_doc_access->delete($id); return TRUE; } public static function delete_buy_status($id) { $buy_status_access = new dao_buy_status(); $buy_status_access->delete($id); return TRUE; } public static function save_buy_doc($buy_doc_id, $user_id, $doc_id, $buy_status_id) { $buy_doc_access = new dao_buy_doc(); $buy_doc_access->save($buy_doc_id,$user_id,$doc_id,$buy_status_id); return TRUE; } public static function save_buy_status($buy_status_id, $buy_status_name, $buy_status_detail) { $buy_status_access = new dao_buy_status(); $buy_status_access->save($buy_status_id,$buy_status_name,$buy_status_detail); return TRUE; } public static function get_buy_doc_by_id($id) { $buy_doc_access = new dao_buy_doc(); return $buy_doc_access->get_by_id($id); } public static function get_buy_status_by_id($id) { $buy_status_access = new dao_buy_status(); return $buy_status_access->get_by_id($id); } }
04-huanluyenviencanhan
trunk/master/shared/api/api_buy.php
PHP
gpl3
2,091
<?php require_once dirname(dirname(__FILE__)) . '/config/config.php'; require_once DOCUMENT_ROOT . DIR_SHARED_API . 'api_general.php'; require_once DOCUMENT_ROOT . DIR_SHARED_LIBRARIES . 'lib_date.php'; /** * Class api_about_us * @author Viet Anh */ class api_about_us { public static function get_about_us() { $dao_general = new dao_general(); $title = $dao_general->get_option_value('about_us_title'); $content = $dao_general->get_option_value('about_us_content'); $date = $dao_general->get_option_value('about_us_date'); $about_us = array('title' => $title, 'content' => $content, 'date' => $date); return $about_us; } public static function set_about_us($title, $content) { $dao_general = new dao_general(); $dao_general->set_option_value('about_us_title', $title); $dao_general->set_option_value('about_us_content', $content); $dao_general->set_option_value('about_us_date', lib_date::get_now()); return TRUE; } }
04-huanluyenviencanhan
trunk/master/shared/api/api_about_us.php
PHP
gpl3
1,187
<?php require_once dirname(dirname(__FILE__)) . '/config/config.php'; require_once DOCUMENT_ROOT . DIR_SHARED_DAO . "dao_buy_doc.php"; require_once DOCUMENT_ROOT . DIR_SHARED_DAO . "dao_buy_status.php"; require_once DOCUMENT_ROOT . DIR_SHARED_LIBRARIES . 'lib_redirect.php'; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * Description of api_security * * @author Thien */ class api_cart { public static function remove_doc_id_from_cart($doc_id, $cart_key) { if (!empty($_SESSION[$cart_key]) && count($_SESSION[$cart_key]) > 0) { $list = $_SESSION[$cart_key]; foreach ($list as $num => $item) { if ($item == $doc_id) { unset($list[$num]); } } $_SESSION[$cart_key] = $list; } return TRUE; } }
04-huanluyenviencanhan
trunk/master/shared/api/api_cart.php
PHP
gpl3
1,015
<?php require_once dirname(dirname(__FILE__)) . '/config/config.php'; require_once DOCUMENT_ROOT . DIR_SHARED_DAO . "dao_user.php"; require_once DOCUMENT_ROOT . DIR_SHARED_API . "api_user.php"; require_once DOCUMENT_ROOT . DIR_SHARED_LIBRARIES . 'lib_redirect.php'; /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ /** * Description of api_security * * @author Thien */ class api_security { public static function login($email, $password) { $result = array(); $result['user_login'] = 'failed'; $user_access = new dao_user(); $user = $user_access->get_by_login_info($email, $password); if (!empty($user)) { $result = $user; $result['user_login'] = 'success'; } return $result; } public static function can_login($email, $password) { $user_access = new dao_user(); $user = $user_access->get_by_login_info($email, $password); if (!empty($user)) { return TRUE; } else { return FALSE; } } public static function logout() { session_start(); $_SESSION['user_login'] = ''; lib_redirect::Redirect('/index.php'); } public static function validate_user_info($email, $password, $password_confirm, $first_name, $last_name, $address, $phone) { $error_show = ""; if (empty($first_name)) { $error_show .= "Vui lòng nhập Họ."; } else if (empty($last_name)) { $error_show .= "Vui lòng nhập Tên."; } else if (empty($address)) { $error_show .= "Vui lòng nhập Địa Chỉ."; } else if (empty($phone)) { $error_show .= "Vui lòng nhập Số Điện Thoại."; } else if (!is_numeric($phone)) { $error_show .= "Số điện thoại chỉ được nhập số."; } else if (empty($email)) { $error_show .= "Vui lòng nhập Email."; } else if (!filter_var($email, FILTER_VALIDATE_EMAIL)) { $error_show .= "Email không hợp lệ."; } else if (api_user::email_exists($email)) { $error_show .= "Email đã tồn tại. Vui lòng chọn email khác."; } else if (empty($password)) { $error_show .= "Vui lòng nhập Mật Mã."; } else if (empty($password_confirm)) { $error_show .= "Vui lòng nhập Mật Mã Xác Nhận."; } else if ($password !== $password_confirm) { $error_show .= "Mật khẩu xác nhận không khớp."; } return $error_show; } public static function validate_change_password($email, $password_old, $password, $password_confirm) { $error_show = ""; if (empty($password_old)) { $error_show .= "Vui lòng nhập Mật Mã Cũ."; } else if (empty($password)) { $error_show .= "Vui lòng nhập Mật Mã Mới."; } else if (empty($password_confirm)) { $error_show .= "Vui lòng nhập Mật Mã Xác Nhận Mới."; } else if (!self::can_login($email, $password_old)) { $error_show .= "Sai mật khẩu cũ."; } else if ($password !== $password_confirm) { $error_show .= "Mật khẩu xác nhận không khớp."; } return $error_show; } public static function register($email, $password, $first_name, $last_name, $address, $phone) { $user_access = new dao_user(); $user_access->save(0,$email,$password,2, $first_name,$last_name,$address,$phone); return TRUE; } public static function get_all_users() { $user_access = new dao_user(); return $user_access->get_all(); } public static function change_password($email, $password_new) { $user_access = new dao_user(); return $user_access->update_password($email, $password_new); } }
04-huanluyenviencanhan
trunk/master/shared/api/api_security.php
PHP
gpl3
4,210
/* Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ body { /* Font */ font-family: sans-serif, Arial, Verdana, "Trebuchet MS"; font-size: 12px; /* Text color */ color: #333; /* Remove the background color to make it transparent */ background-color: #fff; margin: 20px; } .cke_editable { font-size: 13px; line-height: 1.6; } blockquote { font-style: italic; font-family: Georgia, Times, "Times New Roman", serif; padding: 2px 0; border-style: solid; border-color: #ccc; border-width: 0; } .cke_contents_ltr blockquote { padding-left: 20px; padding-right: 8px; border-left-width: 5px; } .cke_contents_rtl blockquote { padding-left: 8px; padding-right: 20px; border-right-width: 5px; } a { color: #0782C1; } ol,ul,dl { /* IE7: reset rtl list margin. (#7334) */ *margin-right: 0px; /* preserved spaces for list items with text direction other than the list. (#6249,#8049)*/ padding: 0 40px; } h1,h2,h3,h4,h5,h6 { font-weight: normal; line-height: 1.2; } hr { border: 0px; border-top: 1px solid #ccc; } img.right { border: 1px solid #ccc; float: right; margin-left: 15px; padding: 5px; } img.left { border: 1px solid #ccc; float: left; margin-right: 15px; padding: 5px; } pre { white-space: pre-wrap; /* CSS 2.1 */ word-wrap: break-word; /* IE7 */ } .marker { background-color: Yellow; } span[lang] { font-style: italic; } figure { text-align: center; border: solid 1px #ccc; border-radius: 2px; background: rgba(0,0,0,0.05); padding: 10px; margin: 10px 20px; display: inline-block; } figure > figcaption { text-align: center; display: block; /* For IE8 */ } a > img { padding: 1px; margin: 1px; outline: 1px solid #0782C1; }
04-huanluyenviencanhan
trunk/master/shared/plugin/ckeditor/contents.css
CSS
gpl3
1,918
/** * @license Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.md or http://ckeditor.com/license */ /** * This file was added automatically by CKEditor builder. * You may re-use it at any time to build CKEditor again. * * If you would like to build CKEditor online again * (for example to upgrade), visit one the following links: * * (1) http://ckeditor.com/builder * Visit online builder to build CKEditor from scratch. * * (2) http://ckeditor.com/builder/0ebaeed5189874e28f9af28caed38f94 * Visit online builder to build CKEditor, starting with the same setup as before. * * (3) http://ckeditor.com/builder/download/0ebaeed5189874e28f9af28caed38f94 * Straight download link to the latest version of CKEditor (Optimized) with the same setup as before. * * NOTE: * This file is not used by CKEditor, you may remove it. * Changing this file will not change your CKEditor configuration. */ var CKBUILDER_CONFIG = { skin: 'moonocolor', preset: 'standard', ignore: [ 'dev', '.gitignore', '.gitattributes', 'README.md', '.mailmap' ], plugins : { 'basicstyles' : 1, 'blockquote' : 1, 'clipboard' : 1, 'contextmenu' : 1, 'elementspath' : 1, 'enterkey' : 1, 'entities' : 1, 'filebrowser' : 1, 'floatingspace' : 1, 'format' : 1, 'horizontalrule' : 1, 'htmlwriter' : 1, 'image' : 1, 'indentlist' : 1, 'link' : 1, 'list' : 1, 'magicline' : 1, 'maximize' : 1, 'pastefromword' : 1, 'pastetext' : 1, 'removeformat' : 1, 'resize' : 1, 'scayt' : 1, 'showborders' : 1, 'sourcearea' : 1, 'specialchar' : 1, 'stylescombo' : 1, 'tab' : 1, 'table' : 1, 'tabletools' : 1, 'toolbar' : 1, 'undo' : 1, 'wsc' : 1, 'wysiwygarea' : 1 }, languages : { 'en' : 1 } };
04-huanluyenviencanhan
trunk/master/shared/plugin/ckeditor/build-config.js
JavaScript
gpl3
1,861
/** * @license Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.editorConfig = function( config ) { // Define changes to default configuration here. // For complete reference see: // http://docs.ckeditor.com/#!/api/CKEDITOR.config // The toolbar groups arrangement, optimized for two toolbar rows. config.toolbarGroups = [ { name: 'clipboard', groups: [ 'clipboard', 'undo' ] }, { name: 'editing', groups: [ 'find', 'selection', 'spellchecker' ] }, { name: 'links' }, { name: 'insert' }, { name: 'forms' }, { name: 'tools' }, { name: 'document', groups: [ 'mode', 'document', 'doctools' ] }, { name: 'others' }, '/', { name: 'basicstyles', groups: [ 'basicstyles', 'cleanup' ] }, { name: 'paragraph', groups: [ 'list', 'indent', 'blocks', 'align', 'bidi' ] }, { name: 'styles' }, { name: 'colors' }, { name: 'about' } ]; // Remove some buttons provided by the standard plugins, which are // not needed in the Standard(s) toolbar. config.removeButtons = 'Underline,Subscript,Superscript'; // Set the most common block elements. config.format_tags = 'p;h1;h2;h3;pre'; // Simplify the dialog windows. config.removeDialogTabs = 'image:advanced;link:advanced'; };
04-huanluyenviencanhan
trunk/master/shared/plugin/ckeditor/config.js
JavaScript
gpl3
1,323
/* Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */
04-huanluyenviencanhan
trunk/master/shared/plugin/ckeditor/plugins/dialog/dialogDefinition.js
JavaScript
gpl3
148
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd"> <!-- Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license --> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <script type="text/javascript"> function doLoadScript( url ) { if ( !url ) return false ; var s = document.createElement( "script" ) ; s.type = "text/javascript" ; s.src = url ; document.getElementsByTagName( "head" )[ 0 ].appendChild( s ) ; return true ; } var opener; function tryLoad() { opener = window.parent; // get access to global parameters var oParams = window.opener.oldFramesetPageParams; // make frameset rows string prepare var sFramesetRows = ( parseInt( oParams.firstframeh, 10 ) || '30') + ",*," + ( parseInt( oParams.thirdframeh, 10 ) || '150' ) + ',0' ; document.getElementById( 'itFrameset' ).rows = sFramesetRows ; // dynamic including init frames and crossdomain transport code // from config sproxy_js_frameset url var addScriptUrl = oParams.sproxy_js_frameset ; doLoadScript( addScriptUrl ) ; } </script> </head> <frameset id="itFrameset" onload="tryLoad();" border="0" rows="30,*,*,0"> <frame scrolling="no" framespacing="0" frameborder="0" noresize="noresize" marginheight="0" marginwidth="2" src="" name="navbar"></frame> <frame scrolling="auto" framespacing="0" frameborder="0" noresize="noresize" marginheight="0" marginwidth="0" src="" name="mid"></frame> <frame scrolling="no" framespacing="0" frameborder="0" noresize="noresize" marginheight="1" marginwidth="1" src="" name="bot"></frame> <frame scrolling="no" framespacing="0" frameborder="0" noresize="noresize" marginheight="1" marginwidth="1" src="" name="spellsuggestall"></frame> </frameset> </html>
04-huanluyenviencanhan
trunk/master/shared/plugin/ckeditor/plugins/wsc/dialogs/tmpFrameset.html
HTML
gpl3
1,935
/* Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ html, body { background-color: transparent; margin: 0px; padding: 0px; } body { padding: 10px; } body, td, input, select, textarea { font-size: 11px; font-family: 'Microsoft Sans Serif' , Arial, Helvetica, Verdana; } .midtext { padding:0px; margin:10px; } .midtext p { padding:0px; margin:10px; } .Button { border: #737357 1px solid; color: #3b3b1f; background-color: #c7c78f; } .PopupTabArea { color: #737357; background-color: #e3e3c7; } .PopupTitleBorder { border-bottom: #d5d59d 1px solid; } .PopupTabEmptyArea { padding-left: 10px; border-bottom: #d5d59d 1px solid; } .PopupTab, .PopupTabSelected { border-right: #d5d59d 1px solid; border-top: #d5d59d 1px solid; border-left: #d5d59d 1px solid; padding: 3px 5px 3px 5px; color: #737357; } .PopupTab { margin-top: 1px; border-bottom: #d5d59d 1px solid; cursor: pointer; } .PopupTabSelected { font-weight: bold; cursor: default; padding-top: 4px; border-bottom: #f1f1e3 1px solid; background-color: #f1f1e3; }
04-huanluyenviencanhan
trunk/master/shared/plugin/ckeditor/plugins/wsc/dialogs/wsc.css
CSS
gpl3
1,232
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <!-- Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license --> <html> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <script type="text/javascript"> function gup( name ) { name = name.replace( /[\[]/, '\\\[' ).replace( /[\]]/, '\\\]' ) ; var regexS = '[\\?&]' + name + '=([^&#]*)' ; var regex = new RegExp( regexS ) ; var results = regex.exec( window.location.href ) ; if ( results ) return results[ 1 ] ; else return '' ; } var interval; function sendData2Master() { var destination = window.parent.parent ; try { if ( destination.XDTMaster ) { var t = destination.XDTMaster.read( [ gup( 'cmd' ), gup( 'data' ) ] ) ; window.clearInterval( interval ) ; } } catch (e) {} } function OnMessage (event) { var message = event.data; var destination = window.parent.parent; destination.XDTMaster.read( [ 'end', message, 'fpm' ] ) ; } function listenPostMessage() { if (window.addEventListener) { // all browsers except IE before version 9 window.addEventListener ("message", OnMessage, false); }else { if (window.attachEvent) { // IE before version 9 window.attachEvent("onmessage", OnMessage); } } } function onLoad() { interval = window.setInterval( sendData2Master, 100 ); listenPostMessage(); } </script> </head> <body onload="onLoad()"><p></p></body> </html>
04-huanluyenviencanhan
trunk/master/shared/plugin/ckeditor/plugins/wsc/dialogs/ciframe.html
HTML
gpl3
1,690
a { text-decoration:none; padding: 2px 4px 4px 6px; display : block; border-width: 1px; border-style: solid; margin : 0px; } a.cke_scayt_toogle:hover, a.cke_scayt_toogle:focus, a.cke_scayt_toogle:active { border-color: #316ac5; background-color: #dff1ff; color : #000; cursor: pointer; margin : 0px; } a.cke_scayt_toogle { color : #316ac5; border-color: #fff; } .scayt_enabled a.cke_scayt_item { color : #316ac5; border-color: #fff; margin : 0px; } .scayt_disabled a.cke_scayt_item { color : gray; border-color : #fff; } .scayt_enabled a.cke_scayt_item:hover, .scayt_enabled a.cke_scayt_item:focus, .scayt_enabled a.cke_scayt_item:active { border-color: #316ac5; background-color: #dff1ff; color : #000; cursor: pointer; } .scayt_disabled a.cke_scayt_item:hover, .scayt_disabled a.cke_scayt_item:focus, .scayt_disabled a.cke_scayt_item:active { border-color: gray; background-color: #dff1ff; color : gray; cursor: no-drop; } .cke_scayt_set_on, .cke_scayt_set_off { display: none; } .scayt_enabled .cke_scayt_set_on { display: none; } .scayt_disabled .cke_scayt_set_on { display: inline; } .scayt_disabled .cke_scayt_set_off { display: none; } .scayt_enabled .cke_scayt_set_off { display: inline; }
04-huanluyenviencanhan
trunk/master/shared/plugin/ckeditor/plugins/scayt/dialogs/toolbar.css
CSS
gpl3
1,302
/** * Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.md or http://ckeditor.com/license */ // This file contains style definitions that can be used by CKEditor plugins. // // The most common use for it is the "stylescombo" plugin, which shows a combo // in the editor toolbar, containing all styles. Other plugins instead, like // the div plugin, use a subset of the styles on their feature. // // If you don't have plugins that depend on this file, you can simply ignore it. // Otherwise it is strongly recommended to customize this file to match your // website requirements and design properly. CKEDITOR.stylesSet.add( 'default', [ /* Block Styles */ // These styles are already available in the "Format" combo ("format" plugin), // so they are not needed here by default. You may enable them to avoid // placing the "Format" combo in the toolbar, maintaining the same features. /* { name: 'Paragraph', element: 'p' }, { name: 'Heading 1', element: 'h1' }, { name: 'Heading 2', element: 'h2' }, { name: 'Heading 3', element: 'h3' }, { name: 'Heading 4', element: 'h4' }, { name: 'Heading 5', element: 'h5' }, { name: 'Heading 6', element: 'h6' }, { name: 'Preformatted Text',element: 'pre' }, { name: 'Address', element: 'address' }, */ { name: 'Italic Title', element: 'h2', styles: { 'font-style': 'italic' } }, { name: 'Subtitle', element: 'h3', styles: { 'color': '#aaa', 'font-style': 'italic' } }, { name: 'Special Container', element: 'div', styles: { padding: '5px 10px', background: '#eee', border: '1px solid #ccc' } }, /* Inline Styles */ // These are core styles available as toolbar buttons. You may opt enabling // some of them in the Styles combo, removing them from the toolbar. // (This requires the "stylescombo" plugin) /* { name: 'Strong', element: 'strong', overrides: 'b' }, { name: 'Emphasis', element: 'em' , overrides: 'i' }, { name: 'Underline', element: 'u' }, { name: 'Strikethrough', element: 'strike' }, { name: 'Subscript', element: 'sub' }, { name: 'Superscript', element: 'sup' }, */ { name: 'Marker', element: 'span', attributes: { 'class': 'marker' } }, { name: 'Big', element: 'big' }, { name: 'Small', element: 'small' }, { name: 'Typewriter', element: 'tt' }, { name: 'Computer Code', element: 'code' }, { name: 'Keyboard Phrase', element: 'kbd' }, { name: 'Sample Text', element: 'samp' }, { name: 'Variable', element: 'var' }, { name: 'Deleted Text', element: 'del' }, { name: 'Inserted Text', element: 'ins' }, { name: 'Cited Work', element: 'cite' }, { name: 'Inline Quotation', element: 'q' }, { name: 'Language: RTL', element: 'span', attributes: { 'dir': 'rtl' } }, { name: 'Language: LTR', element: 'span', attributes: { 'dir': 'ltr' } }, /* Object Styles */ { name: 'Styled image (left)', element: 'img', attributes: { 'class': 'left' } }, { name: 'Styled image (right)', element: 'img', attributes: { 'class': 'right' } }, { name: 'Compact table', element: 'table', attributes: { cellpadding: '5', cellspacing: '0', border: '1', bordercolor: '#ccc' }, styles: { 'border-collapse': 'collapse' } }, { name: 'Borderless Table', element: 'table', styles: { 'border-style': 'hidden', 'background-color': '#E6E6FA' } }, { name: 'Square Bulleted List', element: 'ul', styles: { 'list-style-type': 'square' } } ] );
04-huanluyenviencanhan
trunk/master/shared/plugin/ckeditor/styles.js
JavaScript
gpl3
3,595
<!DOCTYPE html> <!-- Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license --> <html> <head> <meta charset="utf-8"> <title>CKEditor Samples</title> <link rel="stylesheet" href="sample.css"> </head> <body> <h1 class="samples"> CKEditor Samples </h1> <div class="twoColumns"> <div class="twoColumnsLeft"> <h2 class="samples"> Basic Samples </h2> <dl class="samples"> <dt><a class="samples" href="replacebyclass.html">Replace textarea elements by class name</a></dt> <dd>Automatic replacement of all textarea elements of a given class with a CKEditor instance.</dd> <dt><a class="samples" href="replacebycode.html">Replace textarea elements by code</a></dt> <dd>Replacement of textarea elements with CKEditor instances by using a JavaScript call.</dd> <dt><a class="samples" href="jquery.html">Create editors with jQuery</a></dt> <dd>Creating standard and inline CKEditor instances with jQuery adapter.</dd> </dl> <h2 class="samples"> Basic Customization </h2> <dl class="samples"> <dt><a class="samples" href="uicolor.html">User Interface color</a></dt> <dd>Changing CKEditor User Interface color and adding a toolbar button that lets the user set the UI color.</dd> <dt><a class="samples" href="uilanguages.html">User Interface languages</a></dt> <dd>Changing CKEditor User Interface language and adding a drop-down list that lets the user choose the UI language.</dd> </dl> <h2 class="samples">Plugins</h2> <dl class="samples"> <dt><a class="samples" href="plugins/magicline/magicline.html">Magicline plugin</a></dt> <dd>Using the Magicline plugin to access difficult focus spaces.</dd> <dt><a class="samples" href="plugins/wysiwygarea/fullpage.html">Full page support</a></dt> <dd>CKEditor inserted with a JavaScript call and used to edit the whole page from &lt;html&gt; to &lt;/html&gt;.</dd> </dl> </div> <div class="twoColumnsRight"> <h2 class="samples"> Inline Editing </h2> <dl class="samples"> <dt><a class="samples" href="inlineall.html">Massive inline editor creation</a></dt> <dd>Turn all elements with <code>contentEditable = true</code> attribute into inline editors.</dd> <dt><a class="samples" href="inlinebycode.html">Convert element into an inline editor by code</a></dt> <dd>Conversion of DOM elements into inline CKEditor instances by using a JavaScript call.</dd> <dt><a class="samples" href="inlinetextarea.html">Replace textarea with inline editor</a> <span class="new">New!</span></dt> <dd>A form with a textarea that is replaced by an inline editor at runtime.</dd> </dl> <h2 class="samples"> Advanced Samples </h2> <dl class="samples"> <dt><a class="samples" href="datafiltering.html">Data filtering and features activation</a> <span class="new">New!</span></dt> <dd>Data filtering and automatic features activation basing on configuration.</dd> <dt><a class="samples" href="divreplace.html">Replace DIV elements on the fly</a></dt> <dd>Transforming a <code>div</code> element into an instance of CKEditor with a mouse click.</dd> <dt><a class="samples" href="appendto.html">Append editor instances</a></dt> <dd>Appending editor instances to existing DOM elements.</dd> <dt><a class="samples" href="ajax.html">Create and destroy editor instances for Ajax applications</a></dt> <dd>Creating and destroying CKEditor instances on the fly and saving the contents entered into the editor window.</dd> <dt><a class="samples" href="api.html">Basic usage of the API</a></dt> <dd>Using the CKEditor JavaScript API to interact with the editor at runtime.</dd> <dt><a class="samples" href="xhtmlstyle.html">XHTML-compliant style</a></dt> <dd>Configuring CKEditor to produce XHTML 1.1 compliant attributes and styles.</dd> <dt><a class="samples" href="readonly.html">Read-only mode</a></dt> <dd>Using the readOnly API to block introducing changes to the editor contents.</dd> <dt><a class="samples" href="tabindex.html">"Tab" key-based navigation</a></dt> <dd>Navigating among editor instances with tab key.</dd> <dt><a class="samples" href="plugins/dialog/dialog.html">Using the JavaScript API to customize dialog windows</a></dt> <dd>Using the dialog windows API to customize dialog windows without changing the original editor code.</dd> <dt><a class="samples" href="plugins/enterkey/enterkey.html">Using the &quot;Enter&quot; key in CKEditor</a></dt> <dd>Configuring the behavior of <em>Enter</em> and <em>Shift+Enter</em> keys.</dd> <dt><a class="samples" href="plugins/htmlwriter/outputforflash.html">Output for Flash</a></dt> <dd>Configuring CKEditor to produce HTML code that can be used with Adobe Flash.</dd> <dt><a class="samples" href="plugins/htmlwriter/outputhtml.html">Output HTML</a></dt> <dd>Configuring CKEditor to produce legacy HTML 4 code.</dd> <dt><a class="samples" href="plugins/toolbar/toolbar.html">Toolbar Configurations</a></dt> <dd>Configuring CKEditor to display full or custom toolbar layout.</dd> </dl> </div> </div> <div id="footer"> <hr> <p> CKEditor - The text editor for the Internet - <a class="samples" href="http://ckeditor.com/">http://ckeditor.com</a> </p> <p id="copy"> Copyright &copy; 2003-2014, <a class="samples" href="http://cksource.com/">CKSource</a> - Frederico Knabben. All rights reserved. </p> </div> </body> </html>
04-huanluyenviencanhan
trunk/master/shared/plugin/ckeditor/samples/index.html
HTML
gpl3
5,637
<!DOCTYPE html> <!-- Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license --> <html> <head> <meta charset="utf-8"> <title>Replace Textareas by Class Name &mdash; CKEditor Sample</title> <script src="../ckeditor.js"></script> <link rel="stylesheet" href="sample.css"> </head> <body> <h1 class="samples"> <a href="index.html">CKEditor Samples</a> &raquo; Replace Textarea Elements by Class Name </h1> <div class="description"> <p> This sample shows how to automatically replace all <code>&lt;textarea&gt;</code> elements of a given class with a CKEditor instance. </p> <p> To replace a <code>&lt;textarea&gt;</code> element, simply assign it the <code>ckeditor</code> class, as in the code below: </p> <pre class="samples"> &lt;textarea <strong>class="ckeditor</strong>" name="editor1"&gt;&lt;/textarea&gt; </pre> <p> Note that other <code>&lt;textarea&gt;</code> attributes (like <code>id</code> or <code>name</code>) need to be adjusted to your document. </p> </div> <form action="sample_posteddata.php" method="post"> <p> <label for="editor1"> Editor 1: </label> <textarea class="ckeditor" cols="80" id="editor1" name="editor1" rows="10"> &lt;h1&gt;&lt;img alt=&quot;Saturn V carrying Apollo 11&quot; class=&quot;right&quot; src=&quot;assets/sample.jpg&quot;/&gt; Apollo 11&lt;/h1&gt; &lt;p&gt;&lt;b&gt;Apollo 11&lt;/b&gt; was the spaceflight that landed the first humans, Americans &lt;a href=&quot;http://en.wikipedia.org/wiki/Neil_Armstrong&quot; title=&quot;Neil Armstrong&quot;&gt;Neil Armstrong&lt;/a&gt; and &lt;a href=&quot;http://en.wikipedia.org/wiki/Buzz_Aldrin&quot; title=&quot;Buzz Aldrin&quot;&gt;Buzz Aldrin&lt;/a&gt;, on the Moon on July 20, 1969, at 20:18 UTC. Armstrong became the first to step onto the lunar surface 6 hours later on July 21 at 02:56 UTC.&lt;/p&gt; &lt;p&gt;Armstrong spent about &lt;s&gt;three and a half&lt;/s&gt; two and a half hours outside the spacecraft, Aldrin slightly less; and together they collected 47.5 pounds (21.5&amp;nbsp;kg) of lunar material for return to Earth. A third member of the mission, &lt;a href=&quot;http://en.wikipedia.org/wiki/Michael_Collins_(astronaut)&quot; title=&quot;Michael Collins (astronaut)&quot;&gt;Michael Collins&lt;/a&gt;, piloted the &lt;a href=&quot;http://en.wikipedia.org/wiki/Apollo_Command/Service_Module&quot; title=&quot;Apollo Command/Service Module&quot;&gt;command&lt;/a&gt; spacecraft alone in lunar orbit until Armstrong and Aldrin returned to it for the trip back to Earth.&lt;/p&gt; &lt;h2&gt;Broadcasting and &lt;em&gt;quotes&lt;/em&gt; &lt;a id=&quot;quotes&quot; name=&quot;quotes&quot;&gt;&lt;/a&gt;&lt;/h2&gt; &lt;p&gt;Broadcast on live TV to a world-wide audience, Armstrong stepped onto the lunar surface and described the event as:&lt;/p&gt; &lt;blockquote&gt;&lt;p&gt;One small step for [a] man, one giant leap for mankind.&lt;/p&gt;&lt;/blockquote&gt; &lt;p&gt;Apollo 11 effectively ended the &lt;a href=&quot;http://en.wikipedia.org/wiki/Space_Race&quot; title=&quot;Space Race&quot;&gt;Space Race&lt;/a&gt; and fulfilled a national goal proposed in 1961 by the late U.S. President &lt;a href=&quot;http://en.wikipedia.org/wiki/John_F._Kennedy&quot; title=&quot;John F. Kennedy&quot;&gt;John F. Kennedy&lt;/a&gt; in a speech before the United States Congress:&lt;/p&gt; &lt;blockquote&gt;&lt;p&gt;[...] before this decade is out, of landing a man on the Moon and returning him safely to the Earth.&lt;/p&gt;&lt;/blockquote&gt; &lt;h2&gt;Technical details &lt;a id=&quot;tech-details&quot; name=&quot;tech-details&quot;&gt;&lt;/a&gt;&lt;/h2&gt; &lt;table align=&quot;right&quot; border=&quot;1&quot; bordercolor=&quot;#ccc&quot; cellpadding=&quot;5&quot; cellspacing=&quot;0&quot; style=&quot;border-collapse:collapse;margin:10px 0 10px 15px;&quot;&gt; &lt;caption&gt;&lt;strong&gt;Mission crew&lt;/strong&gt;&lt;/caption&gt; &lt;thead&gt; &lt;tr&gt; &lt;th scope=&quot;col&quot;&gt;Position&lt;/th&gt; &lt;th scope=&quot;col&quot;&gt;Astronaut&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt;Commander&lt;/td&gt; &lt;td&gt;Neil A. Armstrong&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Command Module Pilot&lt;/td&gt; &lt;td&gt;Michael Collins&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Lunar Module Pilot&lt;/td&gt; &lt;td&gt;Edwin &amp;quot;Buzz&amp;quot; E. Aldrin, Jr.&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;p&gt;Launched by a &lt;strong&gt;Saturn V&lt;/strong&gt; rocket from &lt;a href=&quot;http://en.wikipedia.org/wiki/Kennedy_Space_Center&quot; title=&quot;Kennedy Space Center&quot;&gt;Kennedy Space Center&lt;/a&gt; in Merritt Island, Florida on July 16, Apollo 11 was the fifth manned mission of &lt;a href=&quot;http://en.wikipedia.org/wiki/NASA&quot; title=&quot;NASA&quot;&gt;NASA&lt;/a&gt;&amp;#39;s Apollo program. The Apollo spacecraft had three parts:&lt;/p&gt; &lt;ol&gt; &lt;li&gt;&lt;strong&gt;Command Module&lt;/strong&gt; with a cabin for the three astronauts which was the only part which landed back on Earth&lt;/li&gt; &lt;li&gt;&lt;strong&gt;Service Module&lt;/strong&gt; which supported the Command Module with propulsion, electrical power, oxygen and water&lt;/li&gt; &lt;li&gt;&lt;strong&gt;Lunar Module&lt;/strong&gt; for landing on the Moon.&lt;/li&gt; &lt;/ol&gt; &lt;p&gt;After being sent to the Moon by the Saturn V&amp;#39;s upper stage, the astronauts separated the spacecraft from it and travelled for three days until they entered into lunar orbit. Armstrong and Aldrin then moved into the Lunar Module and landed in the &lt;a href=&quot;http://en.wikipedia.org/wiki/Mare_Tranquillitatis&quot; title=&quot;Mare Tranquillitatis&quot;&gt;Sea of Tranquility&lt;/a&gt;. They stayed a total of about 21 and a half hours on the lunar surface. After lifting off in the upper part of the Lunar Module and rejoining Collins in the Command Module, they returned to Earth and landed in the &lt;a href=&quot;http://en.wikipedia.org/wiki/Pacific_Ocean&quot; title=&quot;Pacific Ocean&quot;&gt;Pacific Ocean&lt;/a&gt; on July 24.&lt;/p&gt; &lt;hr/&gt; &lt;p style=&quot;text-align: right;&quot;&gt;&lt;small&gt;Source: &lt;a href=&quot;http://en.wikipedia.org/wiki/Apollo_11&quot;&gt;Wikipedia.org&lt;/a&gt;&lt;/small&gt;&lt;/p&gt; </textarea> </p> <p> <input type="submit" value="Submit"> </p> </form> <div id="footer"> <hr> <p> CKEditor - The text editor for the Internet - <a class="samples" href="http://ckeditor.com/">http://ckeditor.com</a> </p> <p id="copy"> Copyright &copy; 2003-2014, <a class="samples" href="http://cksource.com/">CKSource</a> - Frederico Knabben. All rights reserved. </p> </div> </body> </html>
04-huanluyenviencanhan
trunk/master/shared/plugin/ckeditor/samples/replacebyclass.html
HTML
gpl3
6,834
<!DOCTYPE html> <!-- Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license --> <html> <head> <meta charset="utf-8"> <title>Replace Textarea with Inline Editor &mdash; CKEditor Sample</title> <script src="../ckeditor.js"></script> <link href="sample.css" rel="stylesheet"> <style> /* Style the CKEditor element to look like a textfield */ .cke_textarea_inline { padding: 10px; height: 200px; overflow: auto; border: 1px solid gray; -webkit-appearance: textfield; } </style> </head> <body> <h1 class="samples"> <a href="index.html">CKEditor Samples</a> &raquo; Replace Textarea with Inline Editor </h1> <div class="description"> <p> You can also create an inline editor from a <code>textarea</code> element. In this case the <code>textarea</code> will be replaced by a <code>div</code> element with inline editing enabled. </p> <pre class="samples"> // "article-body" is the name of a textarea element. var editor = CKEDITOR.inline( 'article-body' ); </pre> </div> <form action="sample_posteddata.php" method="post"> <h2>This is a sample form with some fields</h2> <p> Title:<br> <input type="text" name="title" value="Sample Form"></p> <p> Article Body (Textarea converted to CKEditor):<br> <textarea name="article-body" style="height: 200px"> &lt;h2&gt;Technical details &lt;a id="tech-details" name="tech-details"&gt;&lt;/a&gt;&lt;/h2&gt; &lt;table align="right" border="1" bordercolor="#ccc" cellpadding="5" cellspacing="0" style="border-collapse:collapse;margin:10px 0 10px 15px;"&gt; &lt;caption&gt;&lt;strong&gt;Mission crew&lt;/strong&gt;&lt;/caption&gt; &lt;thead&gt; &lt;tr&gt; &lt;th scope="col"&gt;Position&lt;/th&gt; &lt;th scope="col"&gt;Astronaut&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;tr&gt; &lt;td&gt;Commander&lt;/td&gt; &lt;td&gt;Neil A. Armstrong&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Command Module Pilot&lt;/td&gt; &lt;td&gt;Michael Collins&lt;/td&gt; &lt;/tr&gt; &lt;tr&gt; &lt;td&gt;Lunar Module Pilot&lt;/td&gt; &lt;td&gt;Edwin &quot;Buzz&quot; E. Aldrin, Jr.&lt;/td&gt; &lt;/tr&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;p&gt;Launched by a &lt;strong&gt;Saturn V&lt;/strong&gt; rocket from &lt;a href="http://en.wikipedia.org/wiki/Kennedy_Space_Center" title="Kennedy Space Center"&gt;Kennedy Space Center&lt;/a&gt; in Merritt Island, Florida on July 16, Apollo 11 was the fifth manned mission of &lt;a href="http://en.wikipedia.org/wiki/NASA" title="NASA"&gt;NASA&lt;/a&gt;&#39;s Apollo program. The Apollo spacecraft had three parts:&lt;/p&gt; &lt;ol&gt; &lt;li&gt;&lt;strong&gt;Command Module&lt;/strong&gt; with a cabin for the three astronauts which was the only part which landed back on Earth&lt;/li&gt; &lt;li&gt;&lt;strong&gt;Service Module&lt;/strong&gt; which supported the Command Module with propulsion, electrical power, oxygen and water&lt;/li&gt; &lt;li&gt;&lt;strong&gt;Lunar Module&lt;/strong&gt; for landing on the Moon.&lt;/li&gt; &lt;/ol&gt; &lt;p&gt;After being sent to the Moon by the Saturn V&#39;s upper stage, the astronauts separated the spacecraft from it and travelled for three days until they entered into lunar orbit. Armstrong and Aldrin then moved into the Lunar Module and landed in the &lt;a href="http://en.wikipedia.org/wiki/Mare_Tranquillitatis" title="Mare Tranquillitatis"&gt;Sea of Tranquility&lt;/a&gt;. They stayed a total of about 21 and a half hours on the lunar surface. After lifting off in the upper part of the Lunar Module and rejoining Collins in the Command Module, they returned to Earth and landed in the &lt;a href="http://en.wikipedia.org/wiki/Pacific_Ocean" title="Pacific Ocean"&gt;Pacific Ocean&lt;/a&gt; on July 24.&lt;/p&gt; &lt;hr /&gt; &lt;p style="text-align: right;"&gt;&lt;small&gt;Source: &lt;a href="http://en.wikipedia.org/wiki/Apollo_11"&gt;Wikipedia.org&lt;/a&gt;&lt;/small&gt;&lt;/p&gt; </textarea> </p> <p> <input type="submit" value="Submit"> </p> </form> <script> CKEDITOR.inline( 'article-body' ); </script> <div id="footer"> <hr> <p contenteditable="true"> CKEditor - The text editor for the Internet - <a class="samples" href="http://ckeditor.com/"> http://ckeditor.com</a> </p> <p id="copy"> Copyright &copy; 2003-2014, <a class="samples" href="http://cksource.com/">CKSource</a> - Frederico Knabben. All rights reserved. </p> </div> </body> </html>
04-huanluyenviencanhan
trunk/master/shared/plugin/ckeditor/samples/inlinetextarea.html
HTML
gpl3
4,747
<!DOCTYPE html> <!-- Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license --> <html> <head> <meta charset="utf-8"> <title>Inline Editing by Code &mdash; CKEditor Sample</title> <script src="../ckeditor.js"></script> <link href="sample.css" rel="stylesheet"> <style> #editable { padding: 10px; float: left; } </style> </head> <body> <h1 class="samples"> <a href="index.html">CKEditor Samples</a> &raquo; Inline Editing by Code </h1> <div class="description"> <p> This sample shows how to create an inline editor instance of CKEditor. It is created with a JavaScript call using the following code: </p> <pre class="samples"> // This property tells CKEditor to not activate every element with contenteditable=true element. CKEDITOR.disableAutoInline = true; var editor = CKEDITOR.inline( document.getElementById( 'editable' ) ); </pre> <p> Note that <code>editable</code> in the code above is the <code>id</code> attribute of the <code>&lt;div&gt;</code> element to be converted into an inline instance. </p> </div> <div id="editable" contenteditable="true"> <h1><img alt="Saturn V carrying Apollo 11" class="right" src="assets/sample.jpg" /> Apollo 11</h1> <p><b>Apollo 11</b> was the spaceflight that landed the first humans, Americans <a href="http://en.wikipedia.org/wiki/Neil_Armstrong" title="Neil Armstrong">Neil Armstrong</a> and <a href="http://en.wikipedia.org/wiki/Buzz_Aldrin" title="Buzz Aldrin">Buzz Aldrin</a>, on the Moon on July 20, 1969, at 20:18 UTC. Armstrong became the first to step onto the lunar surface 6 hours later on July 21 at 02:56 UTC.</p> <p>Armstrong spent about <s>three and a half</s> two and a half hours outside the spacecraft, Aldrin slightly less; and together they collected 47.5 pounds (21.5&nbsp;kg) of lunar material for return to Earth. A third member of the mission, <a href="http://en.wikipedia.org/wiki/Michael_Collins_(astronaut)" title="Michael Collins (astronaut)">Michael Collins</a>, piloted the <a href="http://en.wikipedia.org/wiki/Apollo_Command/Service_Module" title="Apollo Command/Service Module">command</a> spacecraft alone in lunar orbit until Armstrong and Aldrin returned to it for the trip back to Earth.</p> <h2>Broadcasting and <em>quotes</em> <a id="quotes" name="quotes"></a></h2> <p>Broadcast on live TV to a world-wide audience, Armstrong stepped onto the lunar surface and described the event as:</p> <blockquote> <p>One small step for [a] man, one giant leap for mankind.</p> </blockquote> <p>Apollo 11 effectively ended the <a href="http://en.wikipedia.org/wiki/Space_Race" title="Space Race">Space Race</a> and fulfilled a national goal proposed in 1961 by the late U.S. President <a href="http://en.wikipedia.org/wiki/John_F._Kennedy" title="John F. Kennedy">John F. Kennedy</a> in a speech before the United States Congress:</p> <blockquote> <p>[...] before this decade is out, of landing a man on the Moon and returning him safely to the Earth.</p> </blockquote> <h2>Technical details <a id="tech-details" name="tech-details"></a></h2> <table align="right" border="1" bordercolor="#ccc" cellpadding="5" cellspacing="0" style="border-collapse:collapse;margin:10px 0 10px 15px;"> <caption><strong>Mission crew</strong></caption> <thead> <tr> <th scope="col">Position</th> <th scope="col">Astronaut</th> </tr> </thead> <tbody> <tr> <td>Commander</td> <td>Neil A. Armstrong</td> </tr> <tr> <td>Command Module Pilot</td> <td>Michael Collins</td> </tr> <tr> <td>Lunar Module Pilot</td> <td>Edwin &quot;Buzz&quot; E. Aldrin, Jr.</td> </tr> </tbody> </table> <p>Launched by a <strong>Saturn V</strong> rocket from <a href="http://en.wikipedia.org/wiki/Kennedy_Space_Center" title="Kennedy Space Center">Kennedy Space Center</a> in Merritt Island, Florida on July 16, Apollo 11 was the fifth manned mission of <a href="http://en.wikipedia.org/wiki/NASA" title="NASA">NASA</a>&#39;s Apollo program. The Apollo spacecraft had three parts:</p> <ol> <li><strong>Command Module</strong> with a cabin for the three astronauts which was the only part which landed back on Earth</li> <li><strong>Service Module</strong> which supported the Command Module with propulsion, electrical power, oxygen and water</li> <li><strong>Lunar Module</strong> for landing on the Moon.</li> </ol> <p>After being sent to the Moon by the Saturn V&#39;s upper stage, the astronauts separated the spacecraft from it and travelled for three days until they entered into lunar orbit. Armstrong and Aldrin then moved into the Lunar Module and landed in the <a href="http://en.wikipedia.org/wiki/Mare_Tranquillitatis" title="Mare Tranquillitatis">Sea of Tranquility</a>. They stayed a total of about 21 and a half hours on the lunar surface. After lifting off in the upper part of the Lunar Module and rejoining Collins in the Command Module, they returned to Earth and landed in the <a href="http://en.wikipedia.org/wiki/Pacific_Ocean" title="Pacific Ocean">Pacific Ocean</a> on July 24.</p> <hr /> <p style="text-align: right;"><small>Source: <a href="http://en.wikipedia.org/wiki/Apollo_11">Wikipedia.org</a></small></p> </div> <script> // We need to turn off the automatic editor creation first. CKEDITOR.disableAutoInline = true; var editor = CKEDITOR.inline( 'editable' ); </script> <div id="footer"> <hr> <p contenteditable="true"> CKEditor - The text editor for the Internet - <a class="samples" href="http://ckeditor.com/"> http://ckeditor.com</a> </p> <p id="copy"> Copyright &copy; 2003-2014, <a class="samples" href="http://cksource.com/">CKSource</a> - Frederico Knabben. All rights reserved. </p> </div> </body> </html>
04-huanluyenviencanhan
trunk/master/shared/plugin/ckeditor/samples/inlinebycode.html
HTML
gpl3
5,994