code stringlengths 1 2.01M | repo_name stringlengths 3 62 | path stringlengths 1 267 | language stringclasses 231 values | license stringclasses 13 values | size int64 1 2.01M |
|---|---|---|---|---|---|
/*
* copyright (c) 2007 Michael Niedermayer <michaelni@gmx.at>
*
* some optimization ideas from aes128.c by Reimar Doeffinger
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "common.h"
#include "aes.h"
typedef struct AVAES{
// Note: round_key[16] is accessed in the init code, but this only
// overwrites state, which does not matter (see also r7471).
uint8_t round_key[15][4][4];
uint8_t state[2][4][4];
int rounds;
}AVAES;
const int av_aes_size= sizeof(AVAES);
static const uint8_t rcon[10] = {
0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36
};
static uint8_t sbox[256];
static uint8_t inv_sbox[256];
#if CONFIG_SMALL
static uint32_t enc_multbl[1][256];
static uint32_t dec_multbl[1][256];
#else
static uint32_t enc_multbl[4][256];
static uint32_t dec_multbl[4][256];
#endif
static inline void addkey(uint64_t dst[2], const uint64_t src[2], const uint64_t round_key[2]){
dst[0] = src[0] ^ round_key[0];
dst[1] = src[1] ^ round_key[1];
}
static void subshift(uint8_t s0[2][16], int s, const uint8_t *box){
uint8_t (*s1)[16]= s0[0] - s;
uint8_t (*s3)[16]= s0[0] + s;
s0[0][0]=box[s0[1][ 0]]; s0[0][ 4]=box[s0[1][ 4]]; s0[0][ 8]=box[s0[1][ 8]]; s0[0][12]=box[s0[1][12]];
s1[0][3]=box[s1[1][ 7]]; s1[0][ 7]=box[s1[1][11]]; s1[0][11]=box[s1[1][15]]; s1[0][15]=box[s1[1][ 3]];
s0[0][2]=box[s0[1][10]]; s0[0][10]=box[s0[1][ 2]]; s0[0][ 6]=box[s0[1][14]]; s0[0][14]=box[s0[1][ 6]];
s3[0][1]=box[s3[1][13]]; s3[0][13]=box[s3[1][ 9]]; s3[0][ 9]=box[s3[1][ 5]]; s3[0][ 5]=box[s3[1][ 1]];
}
static inline int mix_core(uint32_t multbl[4][256], int a, int b, int c, int d){
#if CONFIG_SMALL
#define ROT(x,s) ((x<<s)|(x>>(32-s)))
return multbl[0][a] ^ ROT(multbl[0][b], 8) ^ ROT(multbl[0][c], 16) ^ ROT(multbl[0][d], 24);
#else
return multbl[0][a] ^ multbl[1][b] ^ multbl[2][c] ^ multbl[3][d];
#endif
}
static inline void mix(uint8_t state[2][4][4], uint32_t multbl[4][256], int s1, int s3){
((uint32_t *)(state))[0] = mix_core(multbl, state[1][0][0], state[1][s1 ][1], state[1][2][2], state[1][s3 ][3]);
((uint32_t *)(state))[1] = mix_core(multbl, state[1][1][0], state[1][s3-1][1], state[1][3][2], state[1][s1-1][3]);
((uint32_t *)(state))[2] = mix_core(multbl, state[1][2][0], state[1][s3 ][1], state[1][0][2], state[1][s1 ][3]);
((uint32_t *)(state))[3] = mix_core(multbl, state[1][3][0], state[1][s1-1][1], state[1][1][2], state[1][s3-1][3]);
}
static inline void crypt(AVAES *a, int s, const uint8_t *sbox, const uint32_t *multbl){
int r;
for(r=a->rounds-1; r>0; r--){
mix(a->state, multbl, 3-s, 1+s);
addkey(a->state[1], a->state[0], a->round_key[r]);
}
subshift(a->state[0][0], s, sbox);
}
void av_aes_crypt(AVAES *a, uint8_t *dst, const uint8_t *src, int count, uint8_t *iv, int decrypt){
while(count--){
addkey(a->state[1], src, a->round_key[a->rounds]);
if(decrypt) {
crypt(a, 0, inv_sbox, dec_multbl);
if(iv){
addkey(a->state[0], a->state[0], iv);
memcpy(iv, src, 16);
}
addkey(dst, a->state[0], a->round_key[0]);
}else{
if(iv) addkey(a->state[1], a->state[1], iv);
crypt(a, 2, sbox, enc_multbl);
addkey(dst, a->state[0], a->round_key[0]);
if(iv) memcpy(iv, dst, 16);
}
src+=16;
dst+=16;
}
}
static void init_multbl2(uint8_t tbl[1024], const int c[4], const uint8_t *log8, const uint8_t *alog8, const uint8_t *sbox){
int i, j;
for(i=0; i<1024; i++){
int x= sbox[i>>2];
if(x) tbl[i]= alog8[ log8[x] + log8[c[i&3]] ];
}
#if !CONFIG_SMALL
for(j=256; j<1024; j++)
for(i=0; i<4; i++)
tbl[4*j+i]= tbl[4*j + ((i-1)&3) - 1024];
#endif
}
// this is based on the reference AES code by Paulo Barreto and Vincent Rijmen
int av_aes_init(AVAES *a, const uint8_t *key, int key_bits, int decrypt) {
int i, j, t, rconpointer = 0;
uint8_t tk[8][4];
int KC= key_bits>>5;
int rounds= KC + 6;
uint8_t log8[256];
uint8_t alog8[512];
if(!enc_multbl[0][sizeof(enc_multbl)/sizeof(enc_multbl[0][0])-1]){
j=1;
for(i=0; i<255; i++){
alog8[i]=
alog8[i+255]= j;
log8[j]= i;
j^= j+j;
if(j>255) j^= 0x11B;
}
for(i=0; i<256; i++){
j= i ? alog8[255-log8[i]] : 0;
j ^= (j<<1) ^ (j<<2) ^ (j<<3) ^ (j<<4);
j = (j ^ (j>>8) ^ 99) & 255;
inv_sbox[j]= i;
sbox [i]= j;
}
init_multbl2(dec_multbl[0], (const int[4]){0xe, 0x9, 0xd, 0xb}, log8, alog8, inv_sbox);
init_multbl2(enc_multbl[0], (const int[4]){0x2, 0x1, 0x1, 0x3}, log8, alog8, sbox);
}
if(key_bits!=128 && key_bits!=192 && key_bits!=256)
return -1;
a->rounds= rounds;
memcpy(tk, key, KC*4);
for(t= 0; t < (rounds+1)*16;) {
memcpy(a->round_key[0][0]+t, tk, KC*4);
t+= KC*4;
for(i = 0; i < 4; i++)
tk[0][i] ^= sbox[tk[KC-1][(i+1)&3]];
tk[0][0] ^= rcon[rconpointer++];
for(j = 1; j < KC; j++){
if(KC != 8 || j != KC>>1)
for(i = 0; i < 4; i++) tk[j][i] ^= tk[j-1][i];
else
for(i = 0; i < 4; i++) tk[j][i] ^= sbox[tk[j-1][i]];
}
}
if(decrypt){
for(i=1; i<rounds; i++){
uint8_t tmp[3][16];
memcpy(tmp[2], a->round_key[i][0], 16);
subshift(tmp[1], 0, sbox);
mix(tmp, dec_multbl, 1, 3);
memcpy(a->round_key[i][0], tmp[0], 16);
}
}else{
for(i=0; i<(rounds+1)>>1; i++){
for(j=0; j<16; j++)
FFSWAP(int, a->round_key[i][0][j], a->round_key[rounds-i][0][j]);
}
}
return 0;
}
#ifdef TEST
#include "lfg.h"
#include "log.h"
int main(void){
int i,j;
AVAES ae, ad, b;
uint8_t rkey[2][16]= {
{0},
{0x10, 0xa5, 0x88, 0x69, 0xd7, 0x4b, 0xe5, 0xa3, 0x74, 0xcf, 0x86, 0x7c, 0xfb, 0x47, 0x38, 0x59}};
uint8_t pt[16], rpt[2][16]= {
{0x6a, 0x84, 0x86, 0x7c, 0xd7, 0x7e, 0x12, 0xad, 0x07, 0xea, 0x1b, 0xe8, 0x95, 0xc5, 0x3f, 0xa3},
{0}};
uint8_t rct[2][16]= {
{0x73, 0x22, 0x81, 0xc0, 0xa0, 0xaa, 0xb8, 0xf7, 0xa5, 0x4a, 0x0c, 0x67, 0xa0, 0xc4, 0x5e, 0xcf},
{0x6d, 0x25, 0x1e, 0x69, 0x44, 0xb0, 0x51, 0xe0, 0x4e, 0xaa, 0x6f, 0xb4, 0xdb, 0xf7, 0x84, 0x65}};
uint8_t temp[16];
AVLFG prng;
av_aes_init(&ae, "PI=3.141592654..", 128, 0);
av_aes_init(&ad, "PI=3.141592654..", 128, 1);
av_log_set_level(AV_LOG_DEBUG);
av_lfg_init(&prng, 1);
for(i=0; i<2; i++){
av_aes_init(&b, rkey[i], 128, 1);
av_aes_crypt(&b, temp, rct[i], 1, NULL, 1);
for(j=0; j<16; j++)
if(rpt[i][j] != temp[j])
av_log(NULL, AV_LOG_ERROR, "%d %02X %02X\n", j, rpt[i][j], temp[j]);
}
for(i=0; i<10000; i++){
for(j=0; j<16; j++){
pt[j] = av_lfg_get(&prng);
}
{START_TIMER
av_aes_crypt(&ae, temp, pt, 1, NULL, 0);
if(!(i&(i-1)))
av_log(NULL, AV_LOG_ERROR, "%02X %02X %02X %02X\n", temp[0], temp[5], temp[10], temp[15]);
av_aes_crypt(&ad, temp, temp, 1, NULL, 1);
STOP_TIMER("aes")}
for(j=0; j<16; j++){
if(pt[j] != temp[j]){
av_log(NULL, AV_LOG_ERROR, "%d %d %02X %02X\n", i,j, pt[j], temp[j]);
}
}
}
return 0;
}
#endif
| 123linslouis-android-video-cutter | jni/libavutil/aes.c | C | asf20 | 8,277 |
/*
* principal component analysis (PCA)
* Copyright (c) 2004 Michael Niedermayer <michaelni@gmx.at>
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* @file
* principal component analysis (PCA)
*/
#include "common.h"
#include "pca.h"
typedef struct PCA{
int count;
int n;
double *covariance;
double *mean;
}PCA;
PCA *ff_pca_init(int n){
PCA *pca;
if(n<=0)
return NULL;
pca= av_mallocz(sizeof(PCA));
pca->n= n;
pca->count=0;
pca->covariance= av_mallocz(sizeof(double)*n*n);
pca->mean= av_mallocz(sizeof(double)*n);
return pca;
}
void ff_pca_free(PCA *pca){
av_freep(&pca->covariance);
av_freep(&pca->mean);
av_free(pca);
}
void ff_pca_add(PCA *pca, double *v){
int i, j;
const int n= pca->n;
for(i=0; i<n; i++){
pca->mean[i] += v[i];
for(j=i; j<n; j++)
pca->covariance[j + i*n] += v[i]*v[j];
}
pca->count++;
}
int ff_pca(PCA *pca, double *eigenvector, double *eigenvalue){
int i, j, pass;
int k=0;
const int n= pca->n;
double z[n];
memset(eigenvector, 0, sizeof(double)*n*n);
for(j=0; j<n; j++){
pca->mean[j] /= pca->count;
eigenvector[j + j*n] = 1.0;
for(i=0; i<=j; i++){
pca->covariance[j + i*n] /= pca->count;
pca->covariance[j + i*n] -= pca->mean[i] * pca->mean[j];
pca->covariance[i + j*n] = pca->covariance[j + i*n];
}
eigenvalue[j]= pca->covariance[j + j*n];
z[j]= 0;
}
for(pass=0; pass < 50; pass++){
double sum=0;
for(i=0; i<n; i++)
for(j=i+1; j<n; j++)
sum += fabs(pca->covariance[j + i*n]);
if(sum == 0){
for(i=0; i<n; i++){
double maxvalue= -1;
for(j=i; j<n; j++){
if(eigenvalue[j] > maxvalue){
maxvalue= eigenvalue[j];
k= j;
}
}
eigenvalue[k]= eigenvalue[i];
eigenvalue[i]= maxvalue;
for(j=0; j<n; j++){
double tmp= eigenvector[k + j*n];
eigenvector[k + j*n]= eigenvector[i + j*n];
eigenvector[i + j*n]= tmp;
}
}
return pass;
}
for(i=0; i<n; i++){
for(j=i+1; j<n; j++){
double covar= pca->covariance[j + i*n];
double t,c,s,tau,theta, h;
if(pass < 3 && fabs(covar) < sum / (5*n*n)) //FIXME why pass < 3
continue;
if(fabs(covar) == 0.0) //FIXME should not be needed
continue;
if(pass >=3 && fabs((eigenvalue[j]+z[j])/covar) > (1LL<<32) && fabs((eigenvalue[i]+z[i])/covar) > (1LL<<32)){
pca->covariance[j + i*n]=0.0;
continue;
}
h= (eigenvalue[j]+z[j]) - (eigenvalue[i]+z[i]);
theta=0.5*h/covar;
t=1.0/(fabs(theta)+sqrt(1.0+theta*theta));
if(theta < 0.0) t = -t;
c=1.0/sqrt(1+t*t);
s=t*c;
tau=s/(1.0+c);
z[i] -= t*covar;
z[j] += t*covar;
#define ROTATE(a,i,j,k,l) {\
double g=a[j + i*n];\
double h=a[l + k*n];\
a[j + i*n]=g-s*(h+g*tau);\
a[l + k*n]=h+s*(g-h*tau); }
for(k=0; k<n; k++) {
if(k!=i && k!=j){
ROTATE(pca->covariance,FFMIN(k,i),FFMAX(k,i),FFMIN(k,j),FFMAX(k,j))
}
ROTATE(eigenvector,k,i,k,j)
}
pca->covariance[j + i*n]=0.0;
}
}
for (i=0; i<n; i++) {
eigenvalue[i] += z[i];
z[i]=0.0;
}
}
return -1;
}
#ifdef TEST
#undef printf
#include <stdio.h>
#include <stdlib.h>
#include "lfg.h"
int main(void){
PCA *pca;
int i, j, k;
#define LEN 8
double eigenvector[LEN*LEN];
double eigenvalue[LEN];
AVLFG prng;
av_lfg_init(&prng, 1);
pca= ff_pca_init(LEN);
for(i=0; i<9000000; i++){
double v[2*LEN+100];
double sum=0;
int pos = av_lfg_get(&prng) % LEN;
int v2 = av_lfg_get(&prng) % 101 - 50;
v[0] = av_lfg_get(&prng) % 101 - 50;
for(j=1; j<8; j++){
if(j<=pos) v[j]= v[0];
else v[j]= v2;
sum += v[j];
}
/* for(j=0; j<LEN; j++){
v[j] -= v[pos];
}*/
// sum += av_lfg_get(&prng) % 10;
/* for(j=0; j<LEN; j++){
v[j] -= sum/LEN;
}*/
// lbt1(v+100,v+100,LEN);
ff_pca_add(pca, v);
}
ff_pca(pca, eigenvector, eigenvalue);
for(i=0; i<LEN; i++){
pca->count= 1;
pca->mean[i]= 0;
// (0.5^|x|)^2 = 0.5^2|x| = 0.25^|x|
// pca.covariance[i + i*LEN]= pow(0.5, fabs
for(j=i; j<LEN; j++){
printf("%f ", pca->covariance[i + j*LEN]);
}
printf("\n");
}
#if 1
for(i=0; i<LEN; i++){
double v[LEN];
double error=0;
memset(v, 0, sizeof(v));
for(j=0; j<LEN; j++){
for(k=0; k<LEN; k++){
v[j] += pca->covariance[FFMIN(k,j) + FFMAX(k,j)*LEN] * eigenvector[i + k*LEN];
}
v[j] /= eigenvalue[i];
error += fabs(v[j] - eigenvector[i + j*LEN]);
}
printf("%f ", error);
}
printf("\n");
#endif
for(i=0; i<LEN; i++){
for(j=0; j<LEN; j++){
printf("%9.6f ", eigenvector[i + j*LEN]);
}
printf(" %9.1f %f\n", eigenvalue[i], eigenvalue[i]/eigenvalue[0]);
}
return 0;
}
#endif
| 123linslouis-android-video-cutter | jni/libavutil/pca.c | C | asf20 | 6,507 |
/*
* Copyright (c) 2005 Michael Niedermayer <michaelni@gmx.at>
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* @file
* miscellaneous math routines and tables
*/
#include <assert.h>
#include <stdint.h>
#include <limits.h>
#include "mathematics.h"
const uint8_t ff_sqrt_tab[256]={
0, 16, 23, 28, 32, 36, 40, 43, 46, 48, 51, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 77, 79, 80, 82, 84, 85, 87, 88, 90,
91, 92, 94, 95, 96, 98, 99,100,102,103,104,105,107,108,109,110,111,112,114,115,116,117,118,119,120,121,122,123,124,125,126,127,
128,129,130,131,132,133,134,135,136,137,138,139,140,141,142,143,144,144,145,146,147,148,149,150,151,151,152,153,154,155,156,156,
157,158,159,160,160,161,162,163,164,164,165,166,167,168,168,169,170,171,171,172,173,174,174,175,176,176,177,178,179,179,180,181,
182,182,183,184,184,185,186,186,187,188,188,189,190,190,191,192,192,193,194,194,195,196,196,197,198,198,199,200,200,201,202,202,
203,204,204,205,205,206,207,207,208,208,209,210,210,211,212,212,213,213,214,215,215,216,216,217,218,218,219,219,220,220,221,222,
222,223,223,224,224,225,226,226,227,227,228,228,229,230,230,231,231,232,232,233,233,234,235,235,236,236,237,237,238,238,239,239,
240,240,241,242,242,243,243,244,244,245,245,246,246,247,247,248,248,249,249,250,250,251,251,252,252,253,253,254,254,255,255,255
};
const uint8_t ff_log2_tab[256]={
0,0,1,1,2,2,2,2,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,
5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,
6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,
7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7
};
const uint8_t av_reverse[256]={
0x00,0x80,0x40,0xC0,0x20,0xA0,0x60,0xE0,0x10,0x90,0x50,0xD0,0x30,0xB0,0x70,0xF0,
0x08,0x88,0x48,0xC8,0x28,0xA8,0x68,0xE8,0x18,0x98,0x58,0xD8,0x38,0xB8,0x78,0xF8,
0x04,0x84,0x44,0xC4,0x24,0xA4,0x64,0xE4,0x14,0x94,0x54,0xD4,0x34,0xB4,0x74,0xF4,
0x0C,0x8C,0x4C,0xCC,0x2C,0xAC,0x6C,0xEC,0x1C,0x9C,0x5C,0xDC,0x3C,0xBC,0x7C,0xFC,
0x02,0x82,0x42,0xC2,0x22,0xA2,0x62,0xE2,0x12,0x92,0x52,0xD2,0x32,0xB2,0x72,0xF2,
0x0A,0x8A,0x4A,0xCA,0x2A,0xAA,0x6A,0xEA,0x1A,0x9A,0x5A,0xDA,0x3A,0xBA,0x7A,0xFA,
0x06,0x86,0x46,0xC6,0x26,0xA6,0x66,0xE6,0x16,0x96,0x56,0xD6,0x36,0xB6,0x76,0xF6,
0x0E,0x8E,0x4E,0xCE,0x2E,0xAE,0x6E,0xEE,0x1E,0x9E,0x5E,0xDE,0x3E,0xBE,0x7E,0xFE,
0x01,0x81,0x41,0xC1,0x21,0xA1,0x61,0xE1,0x11,0x91,0x51,0xD1,0x31,0xB1,0x71,0xF1,
0x09,0x89,0x49,0xC9,0x29,0xA9,0x69,0xE9,0x19,0x99,0x59,0xD9,0x39,0xB9,0x79,0xF9,
0x05,0x85,0x45,0xC5,0x25,0xA5,0x65,0xE5,0x15,0x95,0x55,0xD5,0x35,0xB5,0x75,0xF5,
0x0D,0x8D,0x4D,0xCD,0x2D,0xAD,0x6D,0xED,0x1D,0x9D,0x5D,0xDD,0x3D,0xBD,0x7D,0xFD,
0x03,0x83,0x43,0xC3,0x23,0xA3,0x63,0xE3,0x13,0x93,0x53,0xD3,0x33,0xB3,0x73,0xF3,
0x0B,0x8B,0x4B,0xCB,0x2B,0xAB,0x6B,0xEB,0x1B,0x9B,0x5B,0xDB,0x3B,0xBB,0x7B,0xFB,
0x07,0x87,0x47,0xC7,0x27,0xA7,0x67,0xE7,0x17,0x97,0x57,0xD7,0x37,0xB7,0x77,0xF7,
0x0F,0x8F,0x4F,0xCF,0x2F,0xAF,0x6F,0xEF,0x1F,0x9F,0x5F,0xDF,0x3F,0xBF,0x7F,0xFF,
};
int64_t av_gcd(int64_t a, int64_t b){
if(b) return av_gcd(b, a%b);
else return a;
}
int64_t av_rescale_rnd(int64_t a, int64_t b, int64_t c, enum AVRounding rnd){
int64_t r=0;
assert(c > 0);
assert(b >=0);
assert(rnd >=0 && rnd<=5 && rnd!=4);
if(a<0 && a != INT64_MIN) return -av_rescale_rnd(-a, b, c, rnd ^ ((rnd>>1)&1));
if(rnd==AV_ROUND_NEAR_INF) r= c/2;
else if(rnd&1) r= c-1;
if(b<=INT_MAX && c<=INT_MAX){
if(a<=INT_MAX)
return (a * b + r)/c;
else
return a/c*b + (a%c*b + r)/c;
}else{
#if 1
uint64_t a0= a&0xFFFFFFFF;
uint64_t a1= a>>32;
uint64_t b0= b&0xFFFFFFFF;
uint64_t b1= b>>32;
uint64_t t1= a0*b1 + a1*b0;
uint64_t t1a= t1<<32;
int i;
a0 = a0*b0 + t1a;
a1 = a1*b1 + (t1>>32) + (a0<t1a);
a0 += r;
a1 += a0<r;
for(i=63; i>=0; i--){
// int o= a1 & 0x8000000000000000ULL;
a1+= a1 + ((a0>>i)&1);
t1+=t1;
if(/*o || */c <= a1){
a1 -= c;
t1++;
}
}
return t1;
}
#else
AVInteger ai;
ai= av_mul_i(av_int2i(a), av_int2i(b));
ai= av_add_i(ai, av_int2i(r));
return av_i2int(av_div_i(ai, av_int2i(c)));
}
#endif
}
int64_t av_rescale(int64_t a, int64_t b, int64_t c){
return av_rescale_rnd(a, b, c, AV_ROUND_NEAR_INF);
}
int64_t av_rescale_q(int64_t a, AVRational bq, AVRational cq){
int64_t b= bq.num * (int64_t)cq.den;
int64_t c= cq.num * (int64_t)bq.den;
return av_rescale_rnd(a, b, c, AV_ROUND_NEAR_INF);
}
int av_compare_ts(int64_t ts_a, AVRational tb_a, int64_t ts_b, AVRational tb_b){
int64_t a= tb_a.num * (int64_t)tb_b.den;
int64_t b= tb_b.num * (int64_t)tb_a.den;
if (av_rescale_rnd(ts_a, a, b, AV_ROUND_DOWN) < ts_b) return -1;
if (av_rescale_rnd(ts_b, b, a, AV_ROUND_DOWN) < ts_a) return 1;
return 0;
}
#ifdef TEST
#include "integer.h"
#undef printf
int main(void){
int64_t a,b,c,d,e;
for(a=7; a<(1LL<<62); a+=a/3+1){
for(b=3; b<(1LL<<62); b+=b/4+1){
for(c=9; c<(1LL<<62); c+=(c*2)/5+3){
int64_t r= c/2;
AVInteger ai;
ai= av_mul_i(av_int2i(a), av_int2i(b));
ai= av_add_i(ai, av_int2i(r));
d= av_i2int(av_div_i(ai, av_int2i(c)));
e= av_rescale(a,b,c);
if((double)a * (double)b / (double)c > (1LL<<63))
continue;
if(d!=e) printf("%"PRId64"*%"PRId64"/%"PRId64"= %"PRId64"=%"PRId64"\n", a, b, c, d, e);
}
}
}
return 0;
}
#endif
| 123linslouis-android-video-cutter | jni/libavutil/mathematics.c | C | asf20 | 6,722 |
LOCAL_PATH := $(call my-dir)
include $(CLEAR_VARS)
include $(LOCAL_PATH)/../av.mk
LOCAL_SRC_FILES := $(FFFILES)
LOCAL_C_INCLUDES := \
$(LOCAL_PATH) \
$(LOCAL_PATH)/..
LOCAL_CFLAGS += $(FFCFLAGS)
LOCAL_STATIC_LIBRARIES := $(FFLIBS)
LOCAL_MODULE := $(FFNAME)
include $(BUILD_STATIC_LIBRARY) | 123linslouis-android-video-cutter | jni/libavutil/Android.mk | Makefile | asf20 | 292 |
/*
* copyright (c) 2006 Michael Niedermayer <michaelni@gmx.at>
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef AVUTIL_LOG_H
#define AVUTIL_LOG_H
#include <stdarg.h>
#include "avutil.h"
/**
* Describes the class of an AVClass context structure. That is an
* arbitrary struct of which the first field is a pointer to an
* AVClass struct (e.g. AVCodecContext, AVFormatContext etc.).
*/
typedef struct {
/**
* The name of the class; usually it is the same name as the
* context structure type to which the AVClass is associated.
*/
const char* class_name;
/**
* A pointer to a function which returns the name of a context
* instance ctx associated with the class.
*/
const char* (*item_name)(void* ctx);
/**
* a pointer to the first option specified in the class if any or NULL
*
* @see av_set_default_options()
*/
const struct AVOption *option;
/**
* LIBAVUTIL_VERSION with which this structure was created.
* This is used to allow fields to be added without requiring major
* version bumps everywhere.
*/
int version;
} AVClass;
/* av_log API */
#define AV_LOG_QUIET -8
/**
* Something went really wrong and we will crash now.
*/
#define AV_LOG_PANIC 0
/**
* Something went wrong and recovery is not possible.
* For example, no header was found for a format which depends
* on headers or an illegal combination of parameters is used.
*/
#define AV_LOG_FATAL 8
/**
* Something went wrong and cannot losslessly be recovered.
* However, not all future data is affected.
*/
#define AV_LOG_ERROR 16
/**
* Something somehow does not look correct. This may or may not
* lead to problems. An example would be the use of '-vstrict -2'.
*/
#define AV_LOG_WARNING 24
#define AV_LOG_INFO 32
#define AV_LOG_VERBOSE 40
/**
* Stuff which is only useful for libav* developers.
*/
#define AV_LOG_DEBUG 48
/**
* Sends the specified message to the log if the level is less than or equal
* to the current av_log_level. By default, all logging messages are sent to
* stderr. This behavior can be altered by setting a different av_vlog callback
* function.
*
* @param avcl A pointer to an arbitrary struct of which the first field is a
* pointer to an AVClass struct.
* @param level The importance level of the message, lower values signifying
* higher importance.
* @param fmt The format string (printf-compatible) that specifies how
* subsequent arguments are converted to output.
* @see av_vlog
*/
#ifdef __GNUC__
void av_log(void*, int level, const char *fmt, ...) __attribute__ ((__format__ (__printf__, 3, 4)));
#else
void av_log(void*, int level, const char *fmt, ...);
#endif
void av_vlog(void*, int level, const char *fmt, va_list);
int av_log_get_level(void);
void av_log_set_level(int);
void av_log_set_callback(void (*)(void*, int, const char*, va_list));
void av_log_default_callback(void* ptr, int level, const char* fmt, va_list vl);
#endif /* AVUTIL_LOG_H */
| 123linslouis-android-video-cutter | jni/libavutil/log.h | C | asf20 | 3,749 |
/*
* Copyright (c) 2009 Baptiste Coudurier <baptiste.coudurier@gmail.com>
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef AVUTIL_RANDOM_SEED_H
#define AVUTIL_RANDOM_SEED_H
#include <stdint.h>
/**
* Gets a seed to use in conjunction with random functions.
*/
uint32_t ff_random_get_seed(void);
#endif /* AVUTIL_RANDOM_SEED_H */
| 123linslouis-android-video-cutter | jni/libavutil/random_seed.h | C | asf20 | 1,057 |
/*
* linear least squares model
*
* Copyright (c) 2006 Michael Niedermayer <michaelni@gmx.at>
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* @file
* linear least squares model
*/
#include <math.h>
#include <string.h>
#include "lls.h"
void av_init_lls(LLSModel *m, int indep_count){
memset(m, 0, sizeof(LLSModel));
m->indep_count= indep_count;
}
void av_update_lls(LLSModel *m, double *var, double decay){
int i,j;
for(i=0; i<=m->indep_count; i++){
for(j=i; j<=m->indep_count; j++){
m->covariance[i][j] *= decay;
m->covariance[i][j] += var[i]*var[j];
}
}
}
void av_solve_lls(LLSModel *m, double threshold, int min_order){
int i,j,k;
double (*factor)[MAX_VARS+1]= (void*)&m->covariance[1][0];
double (*covar )[MAX_VARS+1]= (void*)&m->covariance[1][1];
double *covar_y = m->covariance[0];
int count= m->indep_count;
for(i=0; i<count; i++){
for(j=i; j<count; j++){
double sum= covar[i][j];
for(k=i-1; k>=0; k--)
sum -= factor[i][k]*factor[j][k];
if(i==j){
if(sum < threshold)
sum= 1.0;
factor[i][i]= sqrt(sum);
}else
factor[j][i]= sum / factor[i][i];
}
}
for(i=0; i<count; i++){
double sum= covar_y[i+1];
for(k=i-1; k>=0; k--)
sum -= factor[i][k]*m->coeff[0][k];
m->coeff[0][i]= sum / factor[i][i];
}
for(j=count-1; j>=min_order; j--){
for(i=j; i>=0; i--){
double sum= m->coeff[0][i];
for(k=i+1; k<=j; k++)
sum -= factor[k][i]*m->coeff[j][k];
m->coeff[j][i]= sum / factor[i][i];
}
m->variance[j]= covar_y[0];
for(i=0; i<=j; i++){
double sum= m->coeff[j][i]*covar[i][i] - 2*covar_y[i+1];
for(k=0; k<i; k++)
sum += 2*m->coeff[j][k]*covar[k][i];
m->variance[j] += m->coeff[j][i]*sum;
}
}
}
double av_evaluate_lls(LLSModel *m, double *param, int order){
int i;
double out= 0;
for(i=0; i<=order; i++)
out+= param[i]*m->coeff[order][i];
return out;
}
#ifdef TEST
#include <stdlib.h>
#include <stdio.h>
int main(void){
LLSModel m;
int i, order;
av_init_lls(&m, 3);
for(i=0; i<100; i++){
double var[4];
double eval;
var[0] = (rand() / (double)RAND_MAX - 0.5)*2;
var[1] = var[0] + rand() / (double)RAND_MAX - 0.5;
var[2] = var[1] + rand() / (double)RAND_MAX - 0.5;
var[3] = var[2] + rand() / (double)RAND_MAX - 0.5;
av_update_lls(&m, var, 0.99);
av_solve_lls(&m, 0.001, 0);
for(order=0; order<3; order++){
eval= av_evaluate_lls(&m, var+1, order);
printf("real:%9f order:%d pred:%9f var:%f coeffs:%f %9f %9f\n",
var[0], order, eval, sqrt(m.variance[order] / (i+1)),
m.coeff[order][0], m.coeff[order][1], m.coeff[order][2]);
}
}
return 0;
}
#endif
| 123linslouis-android-video-cutter | jni/libavutil/lls.c | C | asf20 | 3,812 |
/*
* copyright (c) 2005 Michael Niedermayer <michaelni@gmx.at>
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef AVUTIL_MATHEMATICS_H
#define AVUTIL_MATHEMATICS_H
#include <stdint.h>
#include <math.h>
#include "attributes.h"
#include "rational.h"
#ifndef M_E
#define M_E 2.7182818284590452354 /* e */
#endif
#ifndef M_LN2
#define M_LN2 0.69314718055994530942 /* log_e 2 */
#endif
#ifndef M_LN10
#define M_LN10 2.30258509299404568402 /* log_e 10 */
#endif
#ifndef M_LOG2_10
#define M_LOG2_10 3.32192809488736234787 /* log_2 10 */
#endif
#ifndef M_PI
#define M_PI 3.14159265358979323846 /* pi */
#endif
#ifndef M_SQRT1_2
#define M_SQRT1_2 0.70710678118654752440 /* 1/sqrt(2) */
#endif
#ifndef M_SQRT2
#define M_SQRT2 1.41421356237309504880 /* sqrt(2) */
#endif
#ifndef NAN
#define NAN (0.0/0.0)
#endif
#ifndef INFINITY
#define INFINITY (1.0/0.0)
#endif
enum AVRounding {
AV_ROUND_ZERO = 0, ///< Round toward zero.
AV_ROUND_INF = 1, ///< Round away from zero.
AV_ROUND_DOWN = 2, ///< Round toward -infinity.
AV_ROUND_UP = 3, ///< Round toward +infinity.
AV_ROUND_NEAR_INF = 5, ///< Round to nearest and halfway cases away from zero.
};
/**
* Returns the greatest common divisor of a and b.
* If both a and b are 0 or either or both are <0 then behavior is
* undefined.
*/
int64_t av_const av_gcd(int64_t a, int64_t b);
/**
* Rescales a 64-bit integer with rounding to nearest.
* A simple a*b/c isn't possible as it can overflow.
*/
int64_t av_rescale(int64_t a, int64_t b, int64_t c) av_const;
/**
* Rescales a 64-bit integer with specified rounding.
* A simple a*b/c isn't possible as it can overflow.
*/
int64_t av_rescale_rnd(int64_t a, int64_t b, int64_t c, enum AVRounding) av_const;
/**
* Rescales a 64-bit integer by 2 rational numbers.
*/
int64_t av_rescale_q(int64_t a, AVRational bq, AVRational cq) av_const;
/**
* Compares 2 timestamps each in its own timebases.
* The result of the function is undefined if one of the timestamps
* is outside the int64_t range when represented in the others timebase.
* @return -1 if ts_a is before ts_b, 1 if ts_a is after ts_b or 0 if they represent the same position
*/
int av_compare_ts(int64_t ts_a, AVRational tb_a, int64_t ts_b, AVRational tb_b);
#endif /* AVUTIL_MATHEMATICS_H */
| 123linslouis-android-video-cutter | jni/libavutil/mathematics.h | C | asf20 | 3,099 |
/*
* a very simple circular buffer FIFO implementation
* Copyright (c) 2000, 2001, 2002 Fabrice Bellard
* Copyright (c) 2006 Roman Shaposhnik
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "common.h"
#include "fifo.h"
AVFifoBuffer *av_fifo_alloc(unsigned int size)
{
AVFifoBuffer *f= av_mallocz(sizeof(AVFifoBuffer));
if(!f)
return NULL;
f->buffer = av_malloc(size);
f->end = f->buffer + size;
av_fifo_reset(f);
if (!f->buffer)
av_freep(&f);
return f;
}
void av_fifo_free(AVFifoBuffer *f)
{
if(f){
av_free(f->buffer);
av_free(f);
}
}
void av_fifo_reset(AVFifoBuffer *f)
{
f->wptr = f->rptr = f->buffer;
f->wndx = f->rndx = 0;
}
int av_fifo_size(AVFifoBuffer *f)
{
return (uint32_t)(f->wndx - f->rndx);
}
int av_fifo_space(AVFifoBuffer *f)
{
return f->end - f->buffer - av_fifo_size(f);
}
int av_fifo_realloc2(AVFifoBuffer *f, unsigned int new_size) {
unsigned int old_size= f->end - f->buffer;
if(old_size < new_size){
int len= av_fifo_size(f);
AVFifoBuffer *f2= av_fifo_alloc(new_size);
if (!f2)
return -1;
av_fifo_generic_read(f, f2->buffer, len, NULL);
f2->wptr += len;
f2->wndx += len;
av_free(f->buffer);
*f= *f2;
av_free(f2);
}
return 0;
}
// src must NOT be const as it can be a context for func that may need updating (like a pointer or byte counter)
int av_fifo_generic_write(AVFifoBuffer *f, void *src, int size, int (*func)(void*, void*, int))
{
int total = size;
do {
int len = FFMIN(f->end - f->wptr, size);
if(func) {
if(func(src, f->wptr, len) <= 0)
break;
} else {
memcpy(f->wptr, src, len);
src = (uint8_t*)src + len;
}
// Write memory barrier needed for SMP here in theory
f->wptr += len;
if (f->wptr >= f->end)
f->wptr = f->buffer;
f->wndx += len;
size -= len;
} while (size > 0);
return total - size;
}
int av_fifo_generic_read(AVFifoBuffer *f, void *dest, int buf_size, void (*func)(void*, void*, int))
{
// Read memory barrier needed for SMP here in theory
do {
int len = FFMIN(f->end - f->rptr, buf_size);
if(func) func(dest, f->rptr, len);
else{
memcpy(dest, f->rptr, len);
dest = (uint8_t*)dest + len;
}
// memory barrier needed for SMP here in theory
av_fifo_drain(f, len);
buf_size -= len;
} while (buf_size > 0);
return 0;
}
/** Discard data from the FIFO. */
void av_fifo_drain(AVFifoBuffer *f, int size)
{
f->rptr += size;
if (f->rptr >= f->end)
f->rptr -= f->end - f->buffer;
f->rndx += size;
}
| 123linslouis-android-video-cutter | jni/libavutil/fifo.c | C | asf20 | 3,498 |
/*
* Lagged Fibonacci PRNG
* Copyright (c) 2008 Michael Niedermayer
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include <inttypes.h>
#include "lfg.h"
#include "md5.h"
#include "intreadwrite.h"
#include "attributes.h"
void av_cold av_lfg_init(AVLFG *c, unsigned int seed){
uint8_t tmp[16]={0};
int i;
for(i=8; i<64; i+=4){
AV_WL32(tmp, seed); tmp[4]=i;
av_md5_sum(tmp, tmp, 16);
c->state[i ]= AV_RL32(tmp);
c->state[i+1]= AV_RL32(tmp+4);
c->state[i+2]= AV_RL32(tmp+8);
c->state[i+3]= AV_RL32(tmp+12);
}
c->index=0;
}
void av_bmg_get(AVLFG *lfg, double out[2])
{
double x1, x2, w;
do {
x1 = 2.0/UINT_MAX*av_lfg_get(lfg) - 1.0;
x2 = 2.0/UINT_MAX*av_lfg_get(lfg) - 1.0;
w = x1*x1 + x2*x2;
} while (w >= 1.0);
w = sqrt((-2.0 * log(w)) / w);
out[0] = x1 * w;
out[1] = x2 * w;
}
#ifdef TEST
#include "log.h"
#include "timer.h"
int main(void)
{
int x=0;
int i, j;
AVLFG state;
av_lfg_init(&state, 0xdeadbeef);
for (j = 0; j < 10000; j++) {
START_TIMER
for (i = 0; i < 624; i++) {
// av_log(NULL,AV_LOG_ERROR, "%X\n", av_lfg_get(&state));
x+=av_lfg_get(&state);
}
STOP_TIMER("624 calls of av_lfg_get");
}
av_log(NULL, AV_LOG_ERROR, "final value:%X\n", x);
/* BMG usage example */
{
double mean = 1000;
double stddev = 53;
av_lfg_init(&state, 42);
for (i = 0; i < 1000; i += 2) {
double bmg_out[2];
av_bmg_get(&state, bmg_out);
av_log(NULL, AV_LOG_INFO,
"%f\n%f\n",
bmg_out[0] * stddev + mean,
bmg_out[1] * stddev + mean);
}
}
return 0;
}
#endif
| 123linslouis-android-video-cutter | jni/libavutil/lfg.c | C | asf20 | 2,523 |
/*
* Copyright (C) 2007 Marc Hoffman
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* @file
* byte swapping routines
*/
#ifndef AVUTIL_BFIN_BSWAP_H
#define AVUTIL_BFIN_BSWAP_H
#include <stdint.h>
#include "config.h"
#include "libavutil/attributes.h"
#define bswap_32 bswap_32
static av_always_inline av_const uint32_t bswap_32(uint32_t x)
{
unsigned tmp;
__asm__("%1 = %0 >> 8 (V); \n\t"
"%0 = %0 << 8 (V); \n\t"
"%0 = %0 | %1; \n\t"
"%0 = PACK(%0.L, %0.H); \n\t"
: "+d"(x), "=&d"(tmp));
return x;
}
#endif /* AVUTIL_BFIN_BSWAP_H */
| 123linslouis-android-video-cutter | jni/libavutil/bfin/bswap.h | C | asf20 | 1,341 |
/*
* Copyright (C) 2007 Marc Hoffman
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef AVUTIL_BFIN_TIMER_H
#define AVUTIL_BFIN_TIMER_H
#include <stdint.h>
#define AV_READ_TIME read_time
static inline uint64_t read_time(void)
{
union {
struct {
unsigned lo;
unsigned hi;
} p;
unsigned long long c;
} t;
__asm__ volatile ("%0=cycles; %1=cycles2;" : "=d" (t.p.lo), "=d" (t.p.hi));
return t.c;
}
#endif /* AVUTIL_BFIN_TIMER_H */
| 123linslouis-android-video-cutter | jni/libavutil/bfin/timer.h | C | asf20 | 1,216 |
/*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#ifndef AVUTIL_INTREADWRITE_H
#define AVUTIL_INTREADWRITE_H
#include <stdint.h>
#include "config.h"
#include "bswap.h"
#include "common.h"
typedef union {
uint64_t u64;
uint32_t u32[2];
uint16_t u16[4];
uint8_t u8 [8];
double f64;
float f32[2];
} av_alias av_alias64;
typedef union {
uint32_t u32;
uint16_t u16[2];
uint8_t u8 [4];
float f32;
} av_alias av_alias32;
typedef union {
uint16_t u16;
uint8_t u8 [2];
} av_alias av_alias16;
/*
* Arch-specific headers can provide any combination of
* AV_[RW][BLN](16|24|32|64) and AV_(COPY|SWAP|ZERO)(64|128) macros.
* Preprocessor symbols must be defined, even if these are implemented
* as inline functions.
*/
#if ARCH_ARM
# include "arm/intreadwrite.h"
#elif ARCH_AVR32
# include "avr32/intreadwrite.h"
#elif ARCH_MIPS
# include "mips/intreadwrite.h"
#elif ARCH_PPC
# include "ppc/intreadwrite.h"
#elif ARCH_TOMI
# include "tomi/intreadwrite.h"
#elif ARCH_X86
# include "x86/intreadwrite.h"
#endif
/*
* Map AV_RNXX <-> AV_R[BL]XX for all variants provided by per-arch headers.
*/
#if HAVE_BIGENDIAN
# if defined(AV_RN16) && !defined(AV_RB16)
# define AV_RB16(p) AV_RN16(p)
# elif !defined(AV_RN16) && defined(AV_RB16)
# define AV_RN16(p) AV_RB16(p)
# endif
# if defined(AV_WN16) && !defined(AV_WB16)
# define AV_WB16(p, v) AV_WN16(p, v)
# elif !defined(AV_WN16) && defined(AV_WB16)
# define AV_WN16(p, v) AV_WB16(p, v)
# endif
# if defined(AV_RN24) && !defined(AV_RB24)
# define AV_RB24(p) AV_RN24(p)
# elif !defined(AV_RN24) && defined(AV_RB24)
# define AV_RN24(p) AV_RB24(p)
# endif
# if defined(AV_WN24) && !defined(AV_WB24)
# define AV_WB24(p, v) AV_WN24(p, v)
# elif !defined(AV_WN24) && defined(AV_WB24)
# define AV_WN24(p, v) AV_WB24(p, v)
# endif
# if defined(AV_RN32) && !defined(AV_RB32)
# define AV_RB32(p) AV_RN32(p)
# elif !defined(AV_RN32) && defined(AV_RB32)
# define AV_RN32(p) AV_RB32(p)
# endif
# if defined(AV_WN32) && !defined(AV_WB32)
# define AV_WB32(p, v) AV_WN32(p, v)
# elif !defined(AV_WN32) && defined(AV_WB32)
# define AV_WN32(p, v) AV_WB32(p, v)
# endif
# if defined(AV_RN64) && !defined(AV_RB64)
# define AV_RB64(p) AV_RN64(p)
# elif !defined(AV_RN64) && defined(AV_RB64)
# define AV_RN64(p) AV_RB64(p)
# endif
# if defined(AV_WN64) && !defined(AV_WB64)
# define AV_WB64(p, v) AV_WN64(p, v)
# elif !defined(AV_WN64) && defined(AV_WB64)
# define AV_WN64(p, v) AV_WB64(p, v)
# endif
#else /* HAVE_BIGENDIAN */
# if defined(AV_RN16) && !defined(AV_RL16)
# define AV_RL16(p) AV_RN16(p)
# elif !defined(AV_RN16) && defined(AV_RL16)
# define AV_RN16(p) AV_RL16(p)
# endif
# if defined(AV_WN16) && !defined(AV_WL16)
# define AV_WL16(p, v) AV_WN16(p, v)
# elif !defined(AV_WN16) && defined(AV_WL16)
# define AV_WN16(p, v) AV_WL16(p, v)
# endif
# if defined(AV_RN24) && !defined(AV_RL24)
# define AV_RL24(p) AV_RN24(p)
# elif !defined(AV_RN24) && defined(AV_RL24)
# define AV_RN24(p) AV_RL24(p)
# endif
# if defined(AV_WN24) && !defined(AV_WL24)
# define AV_WL24(p, v) AV_WN24(p, v)
# elif !defined(AV_WN24) && defined(AV_WL24)
# define AV_WN24(p, v) AV_WL24(p, v)
# endif
# if defined(AV_RN32) && !defined(AV_RL32)
# define AV_RL32(p) AV_RN32(p)
# elif !defined(AV_RN32) && defined(AV_RL32)
# define AV_RN32(p) AV_RL32(p)
# endif
# if defined(AV_WN32) && !defined(AV_WL32)
# define AV_WL32(p, v) AV_WN32(p, v)
# elif !defined(AV_WN32) && defined(AV_WL32)
# define AV_WN32(p, v) AV_WL32(p, v)
# endif
# if defined(AV_RN64) && !defined(AV_RL64)
# define AV_RL64(p) AV_RN64(p)
# elif !defined(AV_RN64) && defined(AV_RL64)
# define AV_RN64(p) AV_RL64(p)
# endif
# if defined(AV_WN64) && !defined(AV_WL64)
# define AV_WL64(p, v) AV_WN64(p, v)
# elif !defined(AV_WN64) && defined(AV_WL64)
# define AV_WN64(p, v) AV_WL64(p, v)
# endif
#endif /* !HAVE_BIGENDIAN */
/*
* Define AV_[RW]N helper macros to simplify definitions not provided
* by per-arch headers.
*/
#if HAVE_ATTRIBUTE_PACKED
union unaligned_64 { uint64_t l; } __attribute__((packed)) av_alias;
union unaligned_32 { uint32_t l; } __attribute__((packed)) av_alias;
union unaligned_16 { uint16_t l; } __attribute__((packed)) av_alias;
# define AV_RN(s, p) (((const union unaligned_##s *) (p))->l)
# define AV_WN(s, p, v) ((((union unaligned_##s *) (p))->l) = (v))
#elif defined(__DECC)
# define AV_RN(s, p) (*((const __unaligned uint##s##_t*)(p)))
# define AV_WN(s, p, v) (*((__unaligned uint##s##_t*)(p)) = (v))
#elif HAVE_FAST_UNALIGNED
# define AV_RN(s, p) (((const av_alias##s*)(p))->u##s)
# define AV_WN(s, p, v) (((av_alias##s*)(p))->u##s = (v))
#else
#ifndef AV_RB16
# define AV_RB16(x) \
((((const uint8_t*)(x))[0] << 8) | \
((const uint8_t*)(x))[1])
#endif
#ifndef AV_WB16
# define AV_WB16(p, d) do { \
((uint8_t*)(p))[1] = (d); \
((uint8_t*)(p))[0] = (d)>>8; \
} while(0)
#endif
#ifndef AV_RL16
# define AV_RL16(x) \
((((const uint8_t*)(x))[1] << 8) | \
((const uint8_t*)(x))[0])
#endif
#ifndef AV_WL16
# define AV_WL16(p, d) do { \
((uint8_t*)(p))[0] = (d); \
((uint8_t*)(p))[1] = (d)>>8; \
} while(0)
#endif
#ifndef AV_RB32
# define AV_RB32(x) \
((((const uint8_t*)(x))[0] << 24) | \
(((const uint8_t*)(x))[1] << 16) | \
(((const uint8_t*)(x))[2] << 8) | \
((const uint8_t*)(x))[3])
#endif
#ifndef AV_WB32
# define AV_WB32(p, d) do { \
((uint8_t*)(p))[3] = (d); \
((uint8_t*)(p))[2] = (d)>>8; \
((uint8_t*)(p))[1] = (d)>>16; \
((uint8_t*)(p))[0] = (d)>>24; \
} while(0)
#endif
#ifndef AV_RL32
# define AV_RL32(x) \
((((const uint8_t*)(x))[3] << 24) | \
(((const uint8_t*)(x))[2] << 16) | \
(((const uint8_t*)(x))[1] << 8) | \
((const uint8_t*)(x))[0])
#endif
#ifndef AV_WL32
# define AV_WL32(p, d) do { \
((uint8_t*)(p))[0] = (d); \
((uint8_t*)(p))[1] = (d)>>8; \
((uint8_t*)(p))[2] = (d)>>16; \
((uint8_t*)(p))[3] = (d)>>24; \
} while(0)
#endif
#ifndef AV_RB64
# define AV_RB64(x) \
(((uint64_t)((const uint8_t*)(x))[0] << 56) | \
((uint64_t)((const uint8_t*)(x))[1] << 48) | \
((uint64_t)((const uint8_t*)(x))[2] << 40) | \
((uint64_t)((const uint8_t*)(x))[3] << 32) | \
((uint64_t)((const uint8_t*)(x))[4] << 24) | \
((uint64_t)((const uint8_t*)(x))[5] << 16) | \
((uint64_t)((const uint8_t*)(x))[6] << 8) | \
(uint64_t)((const uint8_t*)(x))[7])
#endif
#ifndef AV_WB64
# define AV_WB64(p, d) do { \
((uint8_t*)(p))[7] = (d); \
((uint8_t*)(p))[6] = (d)>>8; \
((uint8_t*)(p))[5] = (d)>>16; \
((uint8_t*)(p))[4] = (d)>>24; \
((uint8_t*)(p))[3] = (d)>>32; \
((uint8_t*)(p))[2] = (d)>>40; \
((uint8_t*)(p))[1] = (d)>>48; \
((uint8_t*)(p))[0] = (d)>>56; \
} while(0)
#endif
#ifndef AV_RL64
# define AV_RL64(x) \
(((uint64_t)((const uint8_t*)(x))[7] << 56) | \
((uint64_t)((const uint8_t*)(x))[6] << 48) | \
((uint64_t)((const uint8_t*)(x))[5] << 40) | \
((uint64_t)((const uint8_t*)(x))[4] << 32) | \
((uint64_t)((const uint8_t*)(x))[3] << 24) | \
((uint64_t)((const uint8_t*)(x))[2] << 16) | \
((uint64_t)((const uint8_t*)(x))[1] << 8) | \
(uint64_t)((const uint8_t*)(x))[0])
#endif
#ifndef AV_WL64
# define AV_WL64(p, d) do { \
((uint8_t*)(p))[0] = (d); \
((uint8_t*)(p))[1] = (d)>>8; \
((uint8_t*)(p))[2] = (d)>>16; \
((uint8_t*)(p))[3] = (d)>>24; \
((uint8_t*)(p))[4] = (d)>>32; \
((uint8_t*)(p))[5] = (d)>>40; \
((uint8_t*)(p))[6] = (d)>>48; \
((uint8_t*)(p))[7] = (d)>>56; \
} while(0)
#endif
#if HAVE_BIGENDIAN
# define AV_RN(s, p) AV_RB##s(p)
# define AV_WN(s, p, v) AV_WB##s(p, v)
#else
# define AV_RN(s, p) AV_RL##s(p)
# define AV_WN(s, p, v) AV_WL##s(p, v)
#endif
#endif /* HAVE_FAST_UNALIGNED */
#ifndef AV_RN16
# define AV_RN16(p) AV_RN(16, p)
#endif
#ifndef AV_RN32
# define AV_RN32(p) AV_RN(32, p)
#endif
#ifndef AV_RN64
# define AV_RN64(p) AV_RN(64, p)
#endif
#ifndef AV_WN16
# define AV_WN16(p, v) AV_WN(16, p, v)
#endif
#ifndef AV_WN32
# define AV_WN32(p, v) AV_WN(32, p, v)
#endif
#ifndef AV_WN64
# define AV_WN64(p, v) AV_WN(64, p, v)
#endif
#if HAVE_BIGENDIAN
# define AV_RB(s, p) AV_RN##s(p)
# define AV_WB(s, p, v) AV_WN##s(p, v)
# define AV_RL(s, p) bswap_##s(AV_RN##s(p))
# define AV_WL(s, p, v) AV_WN##s(p, bswap_##s(v))
#else
# define AV_RB(s, p) bswap_##s(AV_RN##s(p))
# define AV_WB(s, p, v) AV_WN##s(p, bswap_##s(v))
# define AV_RL(s, p) AV_RN##s(p)
# define AV_WL(s, p, v) AV_WN##s(p, v)
#endif
#define AV_RB8(x) (((const uint8_t*)(x))[0])
#define AV_WB8(p, d) do { ((uint8_t*)(p))[0] = (d); } while(0)
#define AV_RL8(x) AV_RB8(x)
#define AV_WL8(p, d) AV_WB8(p, d)
#ifndef AV_RB16
# define AV_RB16(p) AV_RB(16, p)
#endif
#ifndef AV_WB16
# define AV_WB16(p, v) AV_WB(16, p, v)
#endif
#ifndef AV_RL16
# define AV_RL16(p) AV_RL(16, p)
#endif
#ifndef AV_WL16
# define AV_WL16(p, v) AV_WL(16, p, v)
#endif
#ifndef AV_RB32
# define AV_RB32(p) AV_RB(32, p)
#endif
#ifndef AV_WB32
# define AV_WB32(p, v) AV_WB(32, p, v)
#endif
#ifndef AV_RL32
# define AV_RL32(p) AV_RL(32, p)
#endif
#ifndef AV_WL32
# define AV_WL32(p, v) AV_WL(32, p, v)
#endif
#ifndef AV_RB64
# define AV_RB64(p) AV_RB(64, p)
#endif
#ifndef AV_WB64
# define AV_WB64(p, v) AV_WB(64, p, v)
#endif
#ifndef AV_RL64
# define AV_RL64(p) AV_RL(64, p)
#endif
#ifndef AV_WL64
# define AV_WL64(p, v) AV_WL(64, p, v)
#endif
#ifndef AV_RB24
# define AV_RB24(x) \
((((const uint8_t*)(x))[0] << 16) | \
(((const uint8_t*)(x))[1] << 8) | \
((const uint8_t*)(x))[2])
#endif
#ifndef AV_WB24
# define AV_WB24(p, d) do { \
((uint8_t*)(p))[2] = (d); \
((uint8_t*)(p))[1] = (d)>>8; \
((uint8_t*)(p))[0] = (d)>>16; \
} while(0)
#endif
#ifndef AV_RL24
# define AV_RL24(x) \
((((const uint8_t*)(x))[2] << 16) | \
(((const uint8_t*)(x))[1] << 8) | \
((const uint8_t*)(x))[0])
#endif
#ifndef AV_WL24
# define AV_WL24(p, d) do { \
((uint8_t*)(p))[0] = (d); \
((uint8_t*)(p))[1] = (d)>>8; \
((uint8_t*)(p))[2] = (d)>>16; \
} while(0)
#endif
/*
* The AV_[RW]NA macros access naturally aligned data
* in a type-safe way.
*/
#define AV_RNA(s, p) (((const av_alias##s*)(p))->u##s)
#define AV_WNA(s, p, v) (((av_alias##s*)(p))->u##s = (v))
#ifndef AV_RN16A
# define AV_RN16A(p) AV_RNA(16, p)
#endif
#ifndef AV_RN32A
# define AV_RN32A(p) AV_RNA(32, p)
#endif
#ifndef AV_RN64A
# define AV_RN64A(p) AV_RNA(64, p)
#endif
#ifndef AV_WN16A
# define AV_WN16A(p, v) AV_WNA(16, p, v)
#endif
#ifndef AV_WN32A
# define AV_WN32A(p, v) AV_WNA(32, p, v)
#endif
#ifndef AV_WN64A
# define AV_WN64A(p, v) AV_WNA(64, p, v)
#endif
/* Parameters for AV_COPY*, AV_SWAP*, AV_ZERO* must be
* naturally aligned. They may be implemented using MMX,
* so emms_c() must be called before using any float code
* afterwards.
*/
#define AV_COPY(n, d, s) \
(((av_alias##n*)(d))->u##n = ((const av_alias##n*)(s))->u##n)
#ifndef AV_COPY16
# define AV_COPY16(d, s) AV_COPY(16, d, s)
#endif
#ifndef AV_COPY32
# define AV_COPY32(d, s) AV_COPY(32, d, s)
#endif
#ifndef AV_COPY64
# define AV_COPY64(d, s) AV_COPY(64, d, s)
#endif
#ifndef AV_COPY128
# define AV_COPY128(d, s) \
do { \
AV_COPY64(d, s); \
AV_COPY64((char*)(d)+8, (char*)(s)+8); \
} while(0)
#endif
#define AV_SWAP(n, a, b) FFSWAP(av_alias##n, *(av_alias##n*)(a), *(av_alias##n*)(b))
#ifndef AV_SWAP64
# define AV_SWAP64(a, b) AV_SWAP(64, a, b)
#endif
#define AV_ZERO(n, d) (((av_alias##n*)(d))->u##n = 0)
#ifndef AV_ZERO16
# define AV_ZERO16(d) AV_ZERO(16, d)
#endif
#ifndef AV_ZERO32
# define AV_ZERO32(d) AV_ZERO(32, d)
#endif
#ifndef AV_ZERO64
# define AV_ZERO64(d) AV_ZERO(64, d)
#endif
#ifndef AV_ZERO128
# define AV_ZERO128(d) \
do { \
AV_ZERO64(d); \
AV_ZERO64((char*)(d)+8); \
} while(0)
#endif
#endif /* AVUTIL_INTREADWRITE_H */
| 123linslouis-android-video-cutter | jni/libavutil/intreadwrite.h | C | asf20 | 14,308 |
/*
* portable IEEE float/double read/write functions
*
* Copyright (c) 2005 Michael Niedermayer <michaelni@gmx.at>
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* @file
* portable IEEE float/double read/write functions
*/
#include <stdint.h>
#include <math.h>
#include "intfloat_readwrite.h"
double av_int2dbl(int64_t v){
if(v+v > 0xFFEULL<<52)
return 0.0/0.0;
return ldexp(((v&((1LL<<52)-1)) + (1LL<<52)) * (v>>63|1), (v>>52&0x7FF)-1075);
}
float av_int2flt(int32_t v){
if(v+v > 0xFF000000U)
return 0.0/0.0;
return ldexp(((v&0x7FFFFF) + (1<<23)) * (v>>31|1), (v>>23&0xFF)-150);
}
double av_ext2dbl(const AVExtFloat ext){
uint64_t m = 0;
int e, i;
for (i = 0; i < 8; i++)
m = (m<<8) + ext.mantissa[i];
e = (((int)ext.exponent[0]&0x7f)<<8) | ext.exponent[1];
if (e == 0x7fff && m)
return 0.0/0.0;
e -= 16383 + 63; /* In IEEE 80 bits, the whole (i.e. 1.xxxx)
* mantissa bit is written as opposed to the
* single and double precision formats. */
if (ext.exponent[0]&0x80)
m= -m;
return ldexp(m, e);
}
int64_t av_dbl2int(double d){
int e;
if ( !d) return 0;
else if(d-d) return 0x7FF0000000000000LL + ((int64_t)(d<0)<<63) + (d!=d);
d= frexp(d, &e);
return (int64_t)(d<0)<<63 | (e+1022LL)<<52 | (int64_t)((fabs(d)-0.5)*(1LL<<53));
}
int32_t av_flt2int(float d){
int e;
if ( !d) return 0;
else if(d-d) return 0x7F800000 + ((d<0)<<31) + (d!=d);
d= frexp(d, &e);
return (d<0)<<31 | (e+126)<<23 | (int64_t)((fabs(d)-0.5)*(1<<24));
}
AVExtFloat av_dbl2ext(double d){
struct AVExtFloat ext= {{0}};
int e, i; double f; uint64_t m;
f = fabs(frexp(d, &e));
if (f >= 0.5 && f < 1) {
e += 16382;
ext.exponent[0] = e>>8;
ext.exponent[1] = e;
m = (uint64_t)ldexp(f, 64);
for (i=0; i < 8; i++)
ext.mantissa[i] = m>>(56-(i<<3));
} else if (f != 0.0) {
ext.exponent[0] = 0x7f; ext.exponent[1] = 0xff;
if (f != 1/0.0)
ext.mantissa[0] = ~0;
}
if (d < 0)
ext.exponent[0] |= 0x80;
return ext;
}
| 123linslouis-android-video-cutter | jni/libavutil/intfloat_readwrite.c | C | asf20 | 2,929 |
APP_MODULES := takepics avformat
| 123linslouis-android-video-cutter | jni/Application.mk | Makefile | asf20 | 38 |
#include <jni.h>
#include "include/net_avc_video_cutter_natives_Natives.h"
#include "libavcodec/avcodec.h"
#include "libavformat/avformat.h"
void log_message(char* message) {
FILE *pFile;
char szFilename[32];
int y;
// Open file
sprintf(szFilename, "/sdcard/log.txt");
pFile = fopen(szFilename, "a");
if (pFile == NULL)
return;
// Write header
fprintf(pFile, message);
// Close file
fclose(pFile);
}
void SaveFrame(AVFrame *pFrame, int width, int height, int iFrame) {
FILE *pFile;
char szFilename[32];
int y;
log_message("Saving Frame\n");
// Open file
sprintf(szFilename, "/sdcard/frame%d.bmp", iFrame);
pFile = fopen(szFilename, "wb");
if (pFile == NULL)
return;
// Write header
fprintf(pFile, "P6\n%d %d\n255\n", width, height);
// Write pixel data
for (y = 0; y < height; y++)
fwrite(pFrame->data[0] + y * pFrame->linesize[0], 1, width * 3, pFile);
// Close file
fclose(pFile);
}
JNIEXPORT jint JNICALL Java_net_avc_video_cutter_natives_Natives_takePics(
JNIEnv *env, jclass someclass) {
av_register_all();
AVFormatContext *pFormatCtx;
log_message("I am in Main...Just started!!\n");
char* filename = "/sdcard/video-2010-12-09-19-17-44.3gp";
log_message("After File name");
// Open video file
if (av_open_input_file(&pFormatCtx, filename, NULL, 0, NULL) != 0)
return -1; // Couldn't open file
// Retrieve stream information
if (av_find_stream_info(pFormatCtx) < 0)
return -1; // Couldn't find stream information
int i;
AVCodecContext *pCodecCtx;
// Find the first video stream
int videoStream = -1;
for (i = 0; i < pFormatCtx->nb_streams; i++)
if (pFormatCtx->streams[i]->codec->codec_type == CODEC_TYPE_VIDEO) {
videoStream = i;
break;
}
if (videoStream == -1)
return -1; // Didn't find a video stream
// Get a pointer to the codec context for the video stream
pCodecCtx = pFormatCtx->streams[videoStream]->codec;
AVCodec *pCodec;
// Find the decoder for the video stream
pCodec = avcodec_find_decoder(pCodecCtx->codec_id);
if (pCodec == NULL) {
log_message("Unsupported codec!\n");
return -1; // Codec not found
}
// Open codec
if (avcodec_open(pCodecCtx, pCodec) < 0)
return -1; // Could not open codec
AVFrame *pFrame;
// Allocate video frame
pFrame = avcodec_alloc_frame();
int frameFinished;
AVPacket packet;
i = 0;
while (av_read_frame(pFormatCtx, &packet) >= 0) {
// Is this a packet from the video stream?
if (packet.stream_index == videoStream) {
// Decode video frame
avcodec_decode_video(pCodecCtx, pFrame, &frameFinished,
packet.data, packet.size);
// Did we get a video frame?
if (frameFinished) {
// Save the frame to disk
if (++i <= 5)
SaveFrame(pFrame, pCodecCtx->width, pCodecCtx->height, i);
}
}
}
// Free the packet that was allocated by av_read_frame
av_free_packet(&packet);
// Free the YUV frame
av_free(pFrame);
// Close the codec
avcodec_close(pCodecCtx);
// Close the video file
av_close_input_file(pFormatCtx);
return 0;
}
| 123linslouis-android-video-cutter | jni/takepics.c | C | asf20 | 3,017 |
MY_PATH:=$(call my-dir)
LOCAL_PATH:= $(MY_PATH)/libavutil
include $(CLEAR_VARS)
LOCAL_MODULE := libavutil
include $(LOCAL_PATH)/../av.mk
LOCAL_SRC_FILES := $(FFFILES)
LOCAL_C_INCLUDES := $(LOCAL_PATH) $(LOCAL_PATH)/..
LOCAL_CFLAGS += $(FFCFLAGS)
include $(BUILD_STATIC_LIBRARY)
LOCAL_PATH:= $(MY_PATH)/libavcodec
include $(CLEAR_VARS)
LOCAL_MODULE := libavcodec
include $(LOCAL_PATH)/../av.mk
LOCAL_SRC_FILES := $(FFFILES)
LOCAL_C_INCLUDES := $(LOCAL_PATH) $(LOCAL_PATH)/..
LOCAL_CFLAGS += $(FFCFLAGS)
LOCAL_LDLIBS += -lz
LOCAL_STATIC_LIBRARIES := libavutil
include $(BUILD_STATIC_LIBRARY)
LOCAL_PATH:= $(MY_PATH)/libavformat
include $(CLEAR_VARS)
LOCAL_MODULE := libavformat
include $(LOCAL_PATH)/../av.mk
LOCAL_SRC_FILES := $(FFFILES)
LOCAL_C_INCLUDES := $(LOCAL_PATH) $(LOCAL_PATH)/..
LOCAL_CFLAGS += $(FFCFLAGS)
LOCAL_LDLIBS += -lz
LOCAL_STATIC_LIBRARIES := libavcodec libavutil
include $(BUILD_SHARED_LIBRARY)
LOCAL_PATH := $(MY_PATH)
include $(CLEAR_VARS)
LOCAL_MODULE := takepics
LOCAL_SRC_FILES := takepics.c
LOCAL_SHARED_LIBRARIES := libavformat
LOCAL_LDLIBS += -lz
include $(BUILD_SHARED_LIBRARY)
| 123linslouis-android-video-cutter | jni/Android.mk | Makefile | asf20 | 1,115 |
#!/bin/sh
#http://developer.apple.com/library/mac/#documentation/Java/Conceptual/Java14Development/03-JavaDeployment/JavaDeployment.html
#http://stackoverflow.com/questions/96882/how-do-i-create-a-nice-looking-dmg-for-mac-os-x-using-command-line-tools
set -o verbose #echo onset +o verbose #echo off
# Note: this must run on a Mac
myDir="`dirname "$0"`"
cd $myDir
APP_NAME="Android Design Preview"
OUT_MAC=../out/mac
DMG_PATH=${OUT_MAC}/AndroidDesignPreview.dmg
DMG_CONTENT_PATH=${OUT_MAC}/contents
BUNDLE_PATH="${DMG_CONTENT_PATH}/${APP_NAME}.app"
if [ ! -f ../desktop/out/ProoferDesktop.jar ]; then
echo "Desktop JAR doesn't exist. Did you compile with ant yet?" >&1
exit
fi
rm -rf ${OUT_MAC}
mkdir -p ${DMG_CONTENT_PATH}
mkdir -p "${BUNDLE_PATH}"
SetFile -a B "${BUNDLE_PATH}"
mkdir -p "${BUNDLE_PATH}/Contents/MacOS/"
mkdir -p "${BUNDLE_PATH}/Contents/Resources/Java/"
cp /System/Library/Frameworks/JavaVM.framework/Versions/Current/Resources/MacOS/JavaApplicationStub "${BUNDLE_PATH}/Contents/MacOS/JavaApplicationStub"
cp ../art/icon.icns "${BUNDLE_PATH}/Contents/Resources/Icon.icns"
cp ../desktop/out/ProoferDesktop.jar "${BUNDLE_PATH}/Contents/Resources/Java/ProoferDesktop.jar"
cp Info.plist "${BUNDLE_PATH}/Contents/"
cp PkgInfo "${BUNDLE_PATH}/Contents/"
hdiutil create -srcfolder ${DMG_CONTENT_PATH} -volname "${APP_NAME}" -fs HFS+ \
-fsargs "-c c=64,a=16,e=16" -format UDRW -size 10m ${DMG_PATH}.temp.dmg
device=$(hdiutil attach -readwrite -noverify -noautoopen ${DMG_PATH}.temp.dmg | \
egrep '^/dev/' | sed 1q | awk '{print $1}')
osascript <<EOT
tell application "Finder"
tell disk "${APP_NAME}"
open
set current view of container window to icon view
set toolbar visible of container window to false
set statusbar visible of container window to false
set the bounds of container window to {400, 100, 885, 430}
set theViewOptions to the icon view options of container window
set arrangement of theViewOptions to snap to grid
set icon size of theViewOptions to 96
-- set background picture of theViewOptions to file ".background:${backgroundPictureName}"
make new alias file at container window to POSIX file "/Applications" with properties {name:"Applications"}
delay 1
set position of item "${APP_NAME}" of container window to {100, 100}
set position of item "Applications" of container window to {375, 100}
-- update without registering applications
delay 5
-- eject
end tell
end tell
EOT
chmod -Rf go-w "/Volumes/${APP_NAME}"
sync
sync
hdiutil detach ${device}
sync
hdiutil convert ${DMG_PATH}.temp.dmg -format UDZO -imagekey zlib-level=9 -o ${DMG_PATH}
rm -rf ${DMG_PATH}.temp.dmg | 07pratik-androidui | design-preview/mac/package_mac.sh | Shell | asf20 | 2,768 |
/*
* Copyright 2011 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.apps.proofer;
import android.os.Handler;
import android.view.View;
public class SystemUiHider {
private int HIDE_DELAY_MILLIS = 2000;
private Handler mHandler;
private View mView;
public SystemUiHider(View view) {
mView = view;
}
public void setup() {
hideSystemUi();
mHandler = new Handler();
mView.setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() {
@Override
public void onSystemUiVisibilityChange(int visibility) {
if (visibility != View.SYSTEM_UI_FLAG_HIDE_NAVIGATION) {
delay();
}
}
});
}
private void hideSystemUi() {
mView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
}
private Runnable mHideRunnable = new Runnable() {
public void run() {
hideSystemUi();
}
};
public void delay() {
mHandler.removeCallbacks(mHideRunnable);
mHandler.postDelayed(mHideRunnable, HIDE_DELAY_MILLIS);
}
}
| 07pratik-androidui | design-preview/android/src/com/google/android/apps/proofer/SystemUiHider.java | Java | asf20 | 1,706 |
/*
* Copyright 2011 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.apps.proofer;
import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewTreeObserver;
import android.widget.TextView;
import java.io.BufferedInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
public class DesktopViewerActivity extends Activity implements
ViewTreeObserver.OnGlobalLayoutListener {
private static final String TAG = "DesktopViewerActivity";
private static final int PORT_DEVICE = 7800;
private View mTargetView;
private TextView mStatusTextView;
private boolean mKillServer;
private int mOffsetX;
private int mOffsetY;
private int mWidth;
private int mHeight;
private final Object mDataSyncObject = new Object();
private byte[] mImageData;
private SystemUiHider mSystemUiHider;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mStatusTextView = (TextView) findViewById(R.id.status_text);
mTargetView = findViewById(R.id.target);
mTargetView.setOnTouchListener(mTouchListener);
mTargetView.getViewTreeObserver().addOnGlobalLayoutListener(this);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
mSystemUiHider = new SystemUiHider(mTargetView);
mSystemUiHider.setup();
}
}
@Override
public void onResume() {
super.onResume();
mKillServer = false;
new Thread(mSocketThreadRunnable).start();
}
public void onPause() {
super.onPause();
mKillServer = true;
}
private OnTouchListener mTouchListener = new OnTouchListener() {
float mDownX;
float mDownY;
float mDownOffsetX;
float mDownOffsetY;
@Override
public boolean onTouch(View v, MotionEvent event) {
if (mSystemUiHider != null) {
mSystemUiHider.delay();
}
int action = event.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
mDownX = event.getX();
mDownY = event.getY();
mDownOffsetX = mOffsetX;
mDownOffsetY = mOffsetY;
break;
case MotionEvent.ACTION_MOVE:
mOffsetX = (int) (mDownOffsetX + (mDownX - event.getX()));
mOffsetY = (int) (mDownOffsetY + (mDownY - event.getY()));
if (mOffsetX < 0) {
mOffsetX = 0;
}
if (mOffsetY < 0) {
mOffsetY = 0;
}
break;
}
return true;
}
};
private Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
Bitmap bm = (Bitmap) msg.obj;
mTargetView.setBackgroundDrawable(new BitmapDrawable(bm));
if (bm != null) {
mStatusTextView.setVisibility(View.GONE);
} else {
mStatusTextView.setVisibility(View.VISIBLE);
}
}
};
public void onGlobalLayout() {
updateDimensions();
}
private void updateDimensions() {
synchronized (mDataSyncObject) {
mWidth = mTargetView.getWidth();
mHeight = mTargetView.getHeight();
mImageData = new byte[mWidth * mHeight * 3];
}
}
private int readFully(BufferedInputStream bis, byte[] data, int offset, int len)
throws IOException {
int count = 0;
int got = 0;
while (count < len) {
got = bis.read(data, count, len - count);
if (got >= 0) {
count += got;
} else {
break;
}
}
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "Got " + got + " bytes");
}
return got;
}
private Runnable mSocketThreadRunnable = new Runnable() {
public void run() {
while (true) {
ServerSocket server = null;
try {
Thread.sleep(1000);
server = new ServerSocket(PORT_DEVICE);
} catch (Exception e) {
Log.e(TAG, "Error creating server socket", e);
continue;
}
while (true) {
try {
Socket socket = server.accept();
Log.i(TAG, "Got connection request");
BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());
DataOutputStream dos = new DataOutputStream(socket.getOutputStream());
while (!mKillServer) {
Thread.sleep(50);
synchronized (mDataSyncObject) {
dos.writeInt(mOffsetX);
dos.writeInt(mOffsetY);
dos.writeInt(mWidth);
dos.writeInt(mHeight);
dos.flush();
if (Log.isLoggable(TAG, Log.DEBUG)) {
Log.d(TAG, "Wrote request");
}
byte[] inlen = new byte[4];
readFully(bis, inlen, 0, 4);
int len = ((inlen[0] & 0xFF) << 24) | ((inlen[1] & 0xFF) << 16)
| ((inlen[2] & 0xFF) << 8) | (inlen[3] & 0xFF);
readFully(bis, mImageData, 0, len);
Bitmap bm = BitmapFactory.decodeByteArray(mImageData, 0, len);
mHandler.sendMessage(mHandler.obtainMessage(1, bm));
}
}
bis.close();
dos.close();
socket.close();
server.close();
return;
} catch (Exception e) {
Log.e(TAG, "Exception transferring data", e);
mHandler.sendMessage(mHandler.obtainMessage(1, null));
}
}
}
}
};
}
| 07pratik-androidui | design-preview/android/src/com/google/android/apps/proofer/DesktopViewerActivity.java | Java | asf20 | 7,493 |
/*
* Copyright 2011 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.desktop.proofer;
public class Config {
public static final String ANDROID_APP_PACKAGE_NAME = "com.google.android.apps.proofer";
public static final int PORT_LOCAL = 6800;
public static final int PORT_DEVICE = 7800;
}
| 07pratik-androidui | design-preview/desktop/src/com/google/android/desktop/proofer/Config.java | Java | asf20 | 854 |
/*
* Copyright 2011 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.desktop.proofer;
import com.google.android.desktop.proofer.os.OSBinder;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowEvent;
import java.awt.event.WindowListener;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.Properties;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
public class ControllerForm
implements WindowListener, OSBinder.Callbacks, Proofer.ProoferCallbacks,
RegionSelector.RegionChangeCallback {
private JFrame frame;
private JPanel contentPanel;
private JButton reinstallButton;
private JLabel statusLabel;
private JButton regionButton;
private OSBinder osBinder = OSBinder.getBinder(this);
private RegionSelector regionSelector;
private Proofer proofer;
public ControllerForm() {
setupUI();
setupProofer();
}
public static void main(String[] args) {
// OSX only
//System.setProperty("com.apple.mrj.application.apple.menu.about.name",
// "Android Design Preview");
new ControllerForm();
}
private void setupProofer() {
proofer = new Proofer(this);
try {
proofer.setupPortForwarding();
} catch (ProoferException e) {
// JOptionPane.showMessageDialog(frame,
// e.getMessage(),
// "Android Design Preview",
// JOptionPane.ERROR_MESSAGE);
e.printStackTrace();
}
try {
proofer.installAndroidApp(false);
proofer.runAndroidApp();
} catch (ProoferException e) {
e.printStackTrace();
}
proofer.startConnectionLoop();
proofer.setRequestedRegion(regionSelector.getRegion());
}
private void setupUI() {
frame = new JFrame(ControllerForm.class.getName());
frame.setTitle("Android Design Preview");
frame.setIconImages(Arrays.asList(Util.getAppIconMipmap()));
frame.setAlwaysOnTop(true);
frame.setMinimumSize(new Dimension(250, 150));
frame.setLocationByPlatform(true);
tryLoadFrameConfig();
frame.setContentPane(contentPanel);
frame.setResizable(false);
frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
frame.setVisible(true);
frame.addWindowListener(this);
reinstallButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
try {
proofer.installAndroidApp(true);
proofer.runAndroidApp();
} catch (ProoferException e) {
JOptionPane.showMessageDialog(frame,
"Couldn't install the app: " + e.getMessage()
+ "\n"
+ "\nPlease make sure your device is connected over USB and "
+ "\nthat USB debugging is enabled on your device under "
+ "\nSettings > Applications > Development or"
+ "\nSettings > Developer options.",
"Android Design Preview",
JOptionPane.ERROR_MESSAGE);
e.printStackTrace();
}
}
});
regionSelector = new RegionSelector(this);
regionButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent actionEvent) {
regionSelector.toggleWindow();
}
});
}
void trySaveFrameConfig() {
try {
Properties props = new Properties();
props.setProperty("x", String.valueOf(frame.getX()));
props.setProperty("y", String.valueOf(frame.getY()));
props.storeToXML(new FileOutputStream(
new File(Util.getCacheDirectory(), "config.xml")), null);
} catch (IOException e) {
e.printStackTrace();
}
}
void tryLoadFrameConfig() {
try {
Properties props = new Properties();
props.loadFromXML(
new FileInputStream(new File(Util.getCacheDirectory(), "config.xml")));
frame.setLocation(
Integer.parseInt(props.getProperty("x", String.valueOf(frame.getX()))),
Integer.parseInt(props.getProperty("y", String.valueOf(frame.getY()))));
} catch (FileNotFoundException e) {
} catch (IOException e) {
e.printStackTrace();
}
}
public void windowClosing(WindowEvent windowEvent) {
onQuit();
}
public void onQuit() {
try {
proofer.killAndroidApp();
} catch (ProoferException e) {
e.printStackTrace();
}
trySaveFrameConfig();
frame.dispose();
System.exit(0);
}
public void windowOpened(WindowEvent windowEvent) {
}
public void windowClosed(WindowEvent windowEvent) {
}
public void windowIconified(WindowEvent windowEvent) {
}
public void windowDeiconified(WindowEvent windowEvent) {
}
public void windowActivated(WindowEvent windowEvent) {
}
public void windowDeactivated(WindowEvent windowEvent) {
}
public void onStateChange(Proofer.State newState) {
switch (newState) {
case ConnectedActive:
statusLabel.setText("Connected, active");
break;
case ConnectedIdle:
statusLabel.setText("Connected, inactive");
break;
case Disconnected:
statusLabel.setText("Disconnected");
break;
case Unknown:
statusLabel.setText("N/A");
break;
}
}
public void onRequestedSizeChanged(int width, int height) {
regionSelector.requestSize(width, height);
}
public void onRegionChanged(Rectangle region) {
if (proofer != null) {
proofer.setRequestedRegion(region);
}
}
{
// GUI initializer generated by IntelliJ IDEA GUI Designer
// >>> IMPORTANT!! <<<
// DO NOT EDIT OR ADD ANY CODE HERE!
$$$setupUI$$$();
}
/**
* Method generated by IntelliJ IDEA GUI Designer >>> IMPORTANT!! <<< DO NOT edit this method OR
* call it in your code!
*
* @noinspection ALL
*/
private void $$$setupUI$$$() {
contentPanel = new JPanel();
contentPanel.setLayout(new GridBagLayout());
reinstallButton = new JButton();
reinstallButton.setText("Re-install App");
reinstallButton.setMnemonic('R');
reinstallButton.setDisplayedMnemonicIndex(0);
GridBagConstraints gbc;
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 2;
gbc.weightx = 1.0;
gbc.weighty = 1.0;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(8, 8, 8, 8);
contentPanel.add(reinstallButton, gbc);
final JPanel panel1 = new JPanel();
panel1.setLayout(new FlowLayout(FlowLayout.CENTER, 5, 5));
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 0;
gbc.fill = GridBagConstraints.BOTH;
gbc.insets = new Insets(8, 8, 8, 8);
contentPanel.add(panel1, gbc);
final JLabel label1 = new JLabel();
label1.setText("Status:");
panel1.add(label1);
statusLabel = new JLabel();
statusLabel.setFont(new Font(statusLabel.getFont().getName(), Font.BOLD,
statusLabel.getFont().getSize()));
statusLabel.setText("N/A");
panel1.add(statusLabel);
regionButton = new JButton();
regionButton.setText("Select Mirror Region");
regionButton.setMnemonic('M');
regionButton.setDisplayedMnemonicIndex(7);
gbc = new GridBagConstraints();
gbc.gridx = 0;
gbc.gridy = 1;
gbc.fill = GridBagConstraints.HORIZONTAL;
gbc.insets = new Insets(8, 8, 8, 8);
contentPanel.add(regionButton, gbc);
}
/**
* @noinspection ALL
*/
public JComponent $$$getRootComponent$$$() {
return contentPanel;
}
}
| 07pratik-androidui | design-preview/desktop/src/com/google/android/desktop/proofer/ControllerForm.java | Java | asf20 | 9,438 |
/*
* Copyright 2011 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.desktop.proofer;
import java.awt.*;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.IOException;
import java.net.Socket;
import javax.imageio.ImageIO;
public class Proofer {
private boolean debug = Util.isDebug();
private AdbRunner adbRunner;
private ProoferClient client;
private State state = State.Unknown;
private ProoferCallbacks prooferCallbacks;
public static interface ProoferCallbacks {
public void onStateChange(State newState);
public void onRequestedSizeChanged(int width, int height);
}
public static enum State {
ConnectedActive,
ConnectedIdle,
Disconnected,
Unknown,
}
public Proofer(ProoferCallbacks prooferCallbacks) {
this.adbRunner = new AdbRunner();
this.client = new ProoferClient();
this.prooferCallbacks = prooferCallbacks;
}
public void startConnectionLoop() {
new Thread(new Runnable() {
public void run() {
while (true) {
try {
client.connectAndWaitForRequests();
} catch (CannotConnectException e) {
// Can't connect to device, try re-setting up port forwarding.
// If no devices are connected, this will fail.
try {
setupPortForwarding();
} catch (ProoferException e2) {
// If we get an error here, we're disconnected.
updateState(State.Disconnected);
}
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
break;
}
}
}
}).start();
}
public void runAndroidApp() throws ProoferException {
adbRunner.adb(new String[]{
"shell", "am", "start",
"-a", "android.intent.action.MAIN",
"-c", "android.intent.category.LAUNCHER",
"-n", Config.ANDROID_APP_PACKAGE_NAME + "/.DesktopViewerActivity"
});
}
public void killAndroidApp() throws ProoferException {
adbRunner.adb(new String[]{
"shell", "am", "force-stop",
Config.ANDROID_APP_PACKAGE_NAME
});
}
public void uninstallAndroidApp() throws ProoferException {
adbRunner.adb(new String[]{
"uninstall", Config.ANDROID_APP_PACKAGE_NAME
});
}
public void installAndroidApp(boolean force) throws ProoferException {
if (force || !isAndroidAppInstalled()) {
File apkPath = new File(Util.getCacheDirectory(), "Proofer.apk");
if (Util.extractResource("assets/Proofer.apk", apkPath)) {
adbRunner.adb(new String[]{
"install", "-r", apkPath.toString()
});
} else {
throw new ProoferException("Error extracting Android APK.");
}
}
}
public void setupPortForwarding() throws ProoferException {
try {
adbRunner.adb(new String[]{
"forward", "tcp:" + Config.PORT_LOCAL, "tcp:" + Config.PORT_DEVICE
});
} catch (ProoferException e) {
throw new ProoferException("Couldn't automatically setup port forwarding. "
+ "You'll need to "
+ "manually run "
+ "\"adb forward tcp:" + Config.PORT_LOCAL + " "
+ "tcp:" + Config.PORT_DEVICE + "\" "
+ "on the command line.", e);
}
}
public boolean isAndroidAppInstalled() throws ProoferException {
String out = adbRunner.adb(new String[]{
"shell", "pm", "list", "packages"
});
return out.contains(Config.ANDROID_APP_PACKAGE_NAME);
}
public void setRequestedRegion(Rectangle region) {
client.setRequestedRegion(region);
}
public State getState() {
return state;
}
private void updateState(State newState) {
if (this.state != newState && debug) {
switch (newState) {
case ConnectedActive:
System.out.println("State: Connected and active");
break;
case ConnectedIdle:
System.out.println("State: Connected and idle");
break;
case Disconnected:
System.out.println("State: Disconnected");
break;
}
}
if (this.state != newState && prooferCallbacks != null) {
prooferCallbacks.onStateChange(newState);
}
this.state = newState;
}
public static class CannotConnectException extends ProoferException {
public CannotConnectException(Throwable throwable) {
super(throwable);
}
}
public class ProoferClient {
private Rectangle requestedRegion = new Rectangle(0, 0, 0, 0);
private Robot robot;
private Rectangle screenBounds;
private int curWidth = 0;
private int curHeight = 0;
public ProoferClient() {
try {
this.robot = new Robot();
} catch (AWTException e) {
System.err.println("Error getting robot.");
e.printStackTrace();
System.exit(1);
}
GraphicsEnvironment environment = GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] screenDevices = environment.getScreenDevices();
Rectangle2D tempBounds = new Rectangle();
for (GraphicsDevice screenDevice : screenDevices) {
tempBounds = tempBounds.createUnion(
screenDevice.getDefaultConfiguration().getBounds());
}
screenBounds = tempBounds.getBounds();
}
public void setRequestedRegion(Rectangle region) {
requestedRegion = region;
}
public void connectAndWaitForRequests() throws CannotConnectException {
Socket socket;
// Establish the connection.
try {
socket = new Socket("localhost", Config.PORT_LOCAL);
} catch (IOException e) {
throw new CannotConnectException(e);
}
if (debug) {
System.out.println(
"Local socket established " + socket.getRemoteSocketAddress().toString());
}
// Wait for requests.
try {
DataInputStream dis = new DataInputStream(socket.getInputStream());
BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());
while (true) {
// Try processing a request.
int x = dis.readInt();
int y = dis.readInt();
int width = dis.readInt();
int height = dis.readInt();
// If we reach this point, we didn't hit an IOException and we've received
// a request from the device.
x = requestedRegion.x;
y = requestedRegion.y;
if ((width != curWidth || height != curHeight) && prooferCallbacks != null) {
prooferCallbacks.onRequestedSizeChanged(width, height);
}
curWidth = width;
curHeight = height;
updateState(State.ConnectedActive);
if (debug) {
System.out.println(
"Got request: [" + x + ", " + y + ", " + width + ", " + height
+ "]");
}
if (width > 1 && height > 1) {
BufferedImage bi = capture(x, y, width, height);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(bi, "PNG", baos);
byte[] out = baos.toByteArray();
int len = out.length;
byte[] outlen = new byte[4];
outlen[0] = (byte) ((len >> 24) & 0xFF);
outlen[1] = (byte) ((len >> 16) & 0xFF);
outlen[2] = (byte) ((len >> 8) & 0xFF);
outlen[3] = (byte) (len & 0xFF);
if (debug) {
System.out.println("Writing " + len + " bytes.");
}
bos.write(outlen, 0, 4);
bos.write(out, 0, len);
bos.flush();
}
// This loop will exit only when an IOException is thrown, indicating there's
// nothing further to read.
}
} catch (IOException e) {
// If we're not "connected", this just means we haven't received any requests yet
// on the socket, so there's no error to log.
if (debug) {
System.out.println("No activity.");
}
}
// No (or no more) requests.
updateState(State.ConnectedIdle);
}
private BufferedImage capture(int x, int y, int width, int height) {
x = Math.max(screenBounds.x, x);
y = Math.max(screenBounds.y, y);
if (x + width > screenBounds.x + screenBounds.width) {
x = screenBounds.x + screenBounds.width - width;
}
if (y + height > screenBounds.y + screenBounds.height) {
y = screenBounds.y + screenBounds.height - height;
}
Rectangle rect = new Rectangle(x, y, width, height);
long before = System.currentTimeMillis();
BufferedImage bi = robot.createScreenCapture(rect);
long after = System.currentTimeMillis();
if (debug) {
System.out.println("Capture time: " + (after - before) + " msec");
}
return bi;
}
}
}
| 07pratik-androidui | design-preview/desktop/src/com/google/android/desktop/proofer/Proofer.java | Java | asf20 | 11,218 |
/*
* Copyright 2011 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.desktop.proofer;
import java.awt.Image;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import javax.imageio.ImageIO;
public class Util {
public static boolean isDebug() {
return "1".equals(System.getenv("PROOFER_DEBUG"));
}
public static boolean extractResource(String path, File to) {
try {
InputStream in = Util.class.getClassLoader().getResourceAsStream(path);
if (in == null) {
throw new FileNotFoundException(path);
}
OutputStream out = new FileOutputStream(to);
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
in.close();
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
public static Image[] getAppIconMipmap() {
try {
return new Image[]{
ImageIO.read(
Util.class.getClassLoader().getResourceAsStream("assets/icon_16.png")),
ImageIO.read(
Util.class.getClassLoader().getResourceAsStream("assets/icon_32.png")),
ImageIO.read(
Util.class.getClassLoader().getResourceAsStream("assets/icon_128.png")),
ImageIO.read(
Util.class.getClassLoader().getResourceAsStream("assets/icon_512.png")),
};
} catch (IOException e) {
return new Image[]{};
}
}
// Cache directory code
private static File cacheDirectory;
static {
// Determine/create cache directory
// Default to root in user's home directory
File rootDir = new File(System.getProperty("user.home"));
if (!rootDir.exists() && rootDir.canWrite()) {
// If not writable, root in current working directory
rootDir = new File(System.getProperty("user.dir"));
if (!rootDir.exists() && rootDir.canWrite()) {
// TODO: create temporary directory somewhere if this fails
System.err.println("No home directory and can't write to current directory.");
System.exit(1);
}
}
// The actual cache directory will be ${ROOT}/.android/proofer
cacheDirectory = new File(new File(rootDir, ".android"), "proofer");
if (!cacheDirectory.exists()) {
cacheDirectory.mkdirs();
}
cacheDirectory.setWritable(true);
}
public static File getCacheDirectory() {
return cacheDirectory;
}
// Which OS are we running on? (used to unpack different ADB binaries)
public enum OS {
Windows("windows"),
Linux("linux"),
Mac("mac"),
Other(null);
public String id;
OS(String id) {
this.id = id;
}
}
private static OS currentOS;
static {
String osName = System.getProperty("os.name", "").toLowerCase();
if (osName.contains("windows")) {
currentOS = OS.Windows;
} else if (osName.contains("linux")) {
currentOS = OS.Linux;
} else if (osName.contains("mac") || osName.contains("darwin")) {
currentOS = OS.Mac;
} else {
currentOS = OS.Other;
}
}
public static OS getCurrentOS() {
return currentOS;
}
}
| 07pratik-androidui | design-preview/desktop/src/com/google/android/desktop/proofer/Util.java | Java | asf20 | 4,401 |
/*
* Copyright 2011 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.desktop.proofer;
public class ProoferException extends Exception {
public ProoferException() {
super();
}
public ProoferException(String s) {
super(s);
}
public ProoferException(String s, Throwable throwable) {
super(s, throwable);
}
public ProoferException(Throwable throwable) {
super(throwable);
}
}
| 07pratik-androidui | design-preview/desktop/src/com/google/android/desktop/proofer/ProoferException.java | Java | asf20 | 995 |
/*
* Copyright 2011 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.desktop.proofer.os;
import com.google.android.desktop.proofer.Util;
import java.lang.reflect.InvocationTargetException;
public abstract class OSBinder {
protected Callbacks callbacks;
public static interface Callbacks {
public void onQuit();
}
public static OSBinder getBinder(Callbacks callbacks) {
try {
switch (Util.getCurrentOS()) {
case Mac:
return (OSBinder) MacBinder.class.getConstructor(Callbacks.class)
.newInstance(callbacks);
}
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
return new DefaultBinder(callbacks);
}
protected OSBinder(Callbacks callbacks) {
this.callbacks = callbacks;
}
private static class DummyBinder extends OSBinder {
private DummyBinder(Callbacks callbacks) {
super(callbacks);
}
}
}
| 07pratik-androidui | design-preview/desktop/src/com/google/android/desktop/proofer/os/OSBinder.java | Java | asf20 | 1,810 |
/*
* Copyright 2011 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.desktop.proofer.os;
import com.apple.eawt.AppEvent;
import com.apple.eawt.Application;
import com.apple.eawt.QuitHandler;
import com.apple.eawt.QuitResponse;
import com.apple.eawt.QuitStrategy;
public class MacBinder extends OSBinder implements QuitHandler {
Application application;
public MacBinder(Callbacks callbacks) {
super(callbacks);
application = Application.getApplication();
application.setQuitStrategy(QuitStrategy.SYSTEM_EXIT_0);
application.setQuitHandler(this);
}
public void handleQuitRequestWith(AppEvent.QuitEvent quitEvent, QuitResponse quitResponse) {
callbacks.onQuit();
}
}
| 07pratik-androidui | design-preview/desktop/src/com/google/android/desktop/proofer/os/MacBinder.java | Java | asf20 | 1,285 |
/*
* Copyright 2011 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.desktop.proofer.os;
public class DefaultBinder extends OSBinder {
protected DefaultBinder(Callbacks callbacks) {
super(callbacks);
}
}
| 07pratik-androidui | design-preview/desktop/src/com/google/android/desktop/proofer/os/DefaultBinder.java | Java | asf20 | 776 |
/*
* Copyright 2011 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.desktop.proofer;
import com.sun.awt.AWTUtilities;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Font;
import java.awt.Frame;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.GraphicsConfiguration;
import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.Paint;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.Stroke;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.font.LineMetrics;
import java.awt.geom.Rectangle2D;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import javax.swing.JFrame;
public class RegionSelector {
private JFrame parentFrame;
private JRegionSelectorFrame frame;
private Rectangle region = new Rectangle(100, 100, 480, 800);
private RegionChangeCallback regionChangeCallback;
public static interface RegionChangeCallback {
public void onRegionChanged(Rectangle region);
}
public RegionSelector(RegionChangeCallback regionChangeCallback) {
this.regionChangeCallback = regionChangeCallback;
setupUI();
}
private void setupUI() {
// http://java.sun.com/developer/technicalArticles/GUI/translucent_shaped_windows/
if (AWTUtilities.isTranslucencySupported(AWTUtilities.Translucency.TRANSLUCENT)) {
//perform translucency operations here
GraphicsEnvironment env =
GraphicsEnvironment.getLocalGraphicsEnvironment();
GraphicsDevice[] devices = env.getScreenDevices();
GraphicsConfiguration translucencyCapableGC = null;
for (int i = 0; i < devices.length && translucencyCapableGC == null; i++) {
GraphicsConfiguration[] configs = devices[i].getConfigurations();
for (int j = 0; j < configs.length && translucencyCapableGC == null; j++) {
if (AWTUtilities.isTranslucencyCapable(configs[j])) {
translucencyCapableGC = configs[j];
}
}
}
frame = new JRegionSelectorFrame(translucencyCapableGC);
frame.setUndecorated(true);
AWTUtilities.setWindowOpaque(frame, false);
} else {
frame = new JRegionSelectorFrame(null);
frame.setUndecorated(true);
}
frame.setAlwaysOnTop(true);
frame.setBounds(region);
tryLoadFrameConfig();
frame.setResizable(true);
setRegion(frame.getBounds());
}
public void showWindow(boolean show) {
frame.setVisible(show);
}
public void toggleWindow() {
frame.setVisible(!frame.isVisible());
}
public Rectangle getRegion() {
return region;
}
private void setRegion(Rectangle region) {
this.region = region;
if (regionChangeCallback != null) {
regionChangeCallback.onRegionChanged(this.region);
}
}
public void requestSize(int width, int height) {
this.region.width = width;
this.region.height = height;
frame.setSize(width, height);
}
void trySaveFrameConfig() {
try {
Properties props = new Properties();
props.setProperty("x", String.valueOf(frame.getX()));
props.setProperty("y", String.valueOf(frame.getY()));
props.storeToXML(new FileOutputStream(
new File(Util.getCacheDirectory(), "region.xml")), null);
} catch (IOException e) {
e.printStackTrace();
}
}
private final ScheduledExecutorService worker = Executors.newSingleThreadScheduledExecutor();
private Runnable saveFrameConfigRunnable = new Runnable() {
@Override
public void run() {
trySaveFrameConfig();
}
};
private ScheduledFuture<?> saveFrameConfigScheduleHandle;
void delayedTrySaveFrameConfig() {
if (saveFrameConfigScheduleHandle != null) {
saveFrameConfigScheduleHandle.cancel(false);
}
saveFrameConfigScheduleHandle = worker
.schedule(saveFrameConfigRunnable, 1, TimeUnit.SECONDS);
}
void tryLoadFrameConfig() {
try {
Properties props = new Properties();
props.loadFromXML(
new FileInputStream(new File(Util.getCacheDirectory(), "region.xml")));
frame.setLocation(
Integer.parseInt(props.getProperty("x", String.valueOf(frame.getX()))),
Integer.parseInt(props.getProperty("y", String.valueOf(frame.getY()))));
} catch (FileNotFoundException e) {
} catch (IOException e) {
e.printStackTrace();
}
}
private class JRegionSelectorFrame extends Frame implements MouseListener, MouseMotionListener,
KeyListener {
private Paint strokePaint;
private Paint fillPaint;
private Stroke stroke;
private Font font;
private Point startDragPoint;
private Point startLocation;
private JRegionSelectorFrame(GraphicsConfiguration graphicsConfiguration) {
super(graphicsConfiguration);
fillPaint = new Color(0, 0, 0, 32);
strokePaint = new Color(255, 0, 0, 128);
stroke = new BasicStroke(5, BasicStroke.CAP_SQUARE, BasicStroke.JOIN_MITER);
font = new Font(Font.DIALOG, Font.BOLD, 30);
addMouseListener(this);
addMouseMotionListener(this);
addKeyListener(this);
}
@Override
public void paint(Graphics graphics) {
if (graphics instanceof Graphics2D) {
Graphics2D g2d = (Graphics2D) graphics;
g2d.setPaint(fillPaint);
g2d.fillRect(0, 0, getWidth(), getHeight());
g2d.setPaint(strokePaint);
g2d.setStroke(stroke);
g2d.drawRect(0, 0, getWidth() - 1, getHeight() - 1);
g2d.setFont(font);
String s = getWidth() + " x " + getHeight();
Rectangle2D r = font.getStringBounds(s, g2d.getFontRenderContext());
g2d.drawString(s, (int) (getWidth() - r.getWidth()) / 2, getHeight() / 2);
int offsY = (int) r.getHeight();
s = "(Double-click or ESC to hide)";
r = font.getStringBounds(s, g2d.getFontRenderContext());
g2d.drawString(s, (int) (getWidth() - r.getWidth()) / 2, getHeight() / 2 + offsY);
} else {
super.paint(graphics);
}
}
// http://www.java2s.com/Tutorial/Java/0240__Swing/Dragandmoveaframefromitscontentarea.htm
public void mousePressed(MouseEvent mouseEvent) {
startDragPoint = getScreenLocation(mouseEvent);
startLocation = getLocation();
if (mouseEvent.getClickCount() == 2) {
showWindow(false);
}
}
public void mouseDragged(MouseEvent mouseEvent) {
Point current = getScreenLocation(mouseEvent);
Point offset = new Point(
(int) current.getX() - (int) startDragPoint.getX(),
(int) current.getY() - (int) startDragPoint.getY());
Point newLocation = new Point(
(int) (startLocation.getX() + offset.getX()),
(int) (startLocation.getY() + offset.getY()));
setLocation(newLocation);
setRegion(getBounds());
delayedTrySaveFrameConfig();
}
private Point getScreenLocation(MouseEvent e) {
Point cursor = e.getPoint();
Point targetLocation = getLocationOnScreen();
return new Point(
(int) (targetLocation.getX() + cursor.getX()),
(int) (targetLocation.getY() + cursor.getY()));
}
public void mouseMoved(MouseEvent mouseEvent) {
}
public void mouseClicked(MouseEvent mouseEvent) {
}
public void mouseReleased(MouseEvent mouseEvent) {
}
public void mouseEntered(MouseEvent mouseEvent) {
}
public void mouseExited(MouseEvent mouseEvent) {
}
public void keyTyped(KeyEvent keyEvent) {
}
public void keyPressed(KeyEvent keyEvent) {
if (keyEvent.getKeyCode() == KeyEvent.VK_ESCAPE) {
showWindow(false);
return;
}
Point newLocation = getLocation();
int val = keyEvent.isShiftDown() ? 10 : 1;
switch (keyEvent.getKeyCode()) {
case KeyEvent.VK_UP:
newLocation.y -= val;
break;
case KeyEvent.VK_LEFT:
newLocation.x -= val;
break;
case KeyEvent.VK_DOWN:
newLocation.y += val;
break;
case KeyEvent.VK_RIGHT:
newLocation.x += val;
break;
default:
return;
}
setLocation(newLocation);
setRegion(getBounds());
delayedTrySaveFrameConfig();
}
public void keyReleased(KeyEvent keyEvent) {
}
}
}
| 07pratik-androidui | design-preview/desktop/src/com/google/android/desktop/proofer/RegionSelector.java | Java | asf20 | 10,422 |
/*
* Copyright 2011 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.desktop.proofer;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class AdbRunner {
private boolean debug = Util.isDebug();
private File adbPath;
private boolean ready = false;
public AdbRunner() {
try {
prepareAdb();
} catch (ProoferException e) {
e.printStackTrace();
}
}
private void prepareAdb() throws ProoferException {
if (debug) {
System.out.println("Preparing ADB");
}
Util.OS currentOS = Util.getCurrentOS();
if (currentOS == Util.OS.Other) {
throw new ProoferException("Unknown operating system, cannot run ADB.");
}
switch (currentOS) {
case Mac:
case Linux:
adbPath = extractAssetToCacheDirectory(currentOS.id + "/adb", "adb");
break;
case Windows:
adbPath = extractAssetToCacheDirectory("windows/adb.exe", "adb.exe");
extractAssetToCacheDirectory("windows/AdbWinApi.dll", "AdbWinApi.dll");
extractAssetToCacheDirectory("windows/AdbWinUsbApi.dll", "AdbWinUsbApi.dll");
break;
}
if (!adbPath.setExecutable(true)) {
throw new ProoferException("Error setting ADB binary as executable.");
}
ready = true;
}
private File extractAssetToCacheDirectory(String assetPath, String filename) throws ProoferException {
File outFile = new File(Util.getCacheDirectory(), filename);
if (!outFile.exists()) {
if (!Util.extractResource("assets/" + assetPath, outFile)) {
throw new ProoferException("Error extracting to " + outFile.toString());
}
}
return outFile;
}
public String adb(String[] args) throws ProoferException {
if (debug) {
StringBuilder sb = new StringBuilder();
sb.append("Calling ADB: adb");
for (String arg : args) {
sb.append(" ");
sb.append(arg);
}
System.out.println(sb.toString());
}
List<String> argList = new ArrayList<String>();
argList.add(0, adbPath.getAbsolutePath());
Collections.addAll(argList, args);
int returnCode;
Runtime runtime = Runtime.getRuntime();
Process pr;
StringBuilder sb = new StringBuilder(0);
try {
pr = runtime.exec(argList.toArray(new String[argList.size()]));
// TODO: do something with pr.getErrorStream if needed.
BufferedReader reader = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line = "";
while ((line = reader.readLine()) != null) {
sb.append(line);
sb.append("\n");
}
returnCode = pr.waitFor();
} catch (InterruptedException e) {
throw new ProoferException(e);
} catch (IOException e) {
throw new ProoferException(e);
}
String out = sb.toString();
if (debug) {
System.out.println("Output:" + out);
}
if (returnCode != 0) {
throw new ProoferException("ADB returned error code " + returnCode);
}
return out;
}
}
| 07pratik-androidui | design-preview/desktop/src/com/google/android/desktop/proofer/AdbRunner.java | Java | asf20 | 4,113 |
#!/usr/bin/env python
# Copyright 2010 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.
import sys
import os
from StringIO import StringIO
from PIL import Image
import datauri
RGBA_BLACK = (0, 0, 0, 255)
sign_ = lambda n: -1 if n < 0 else (1 if n > 0 else 0)
def find_black_region_(im, sx, sy, ex, ey):
dx = sign_(ex - sx)
dy = sign_(ey - sy)
if abs(dx) == abs(dy):
raise 'findRegion_ can\'t look both horizontally and vertically at once.'
pixel_changes = []
pixel_on = False
x = sx
y = sy
while True:
if not pixel_on and im.getpixel((x, y)) == RGBA_BLACK:
pixel_changes.append((x, y))
pixel_on = True
elif pixel_on and im.getpixel((x, y)) != RGBA_BLACK:
pixel_changes.append((x, y))
pixel_on = False
x += dx
y += dy
if x == ex and y == ey:
break
return (pixel_changes[0][0 if dx else 1] - (sx if dx else sy),
pixel_changes[1][0 if dx else 1] - (sx if dx else sy))
def image_to_data_uri_(im):
f = StringIO()
im.save(f, 'PNG')
uri = datauri.to_data_uri(f.getvalue(), 'foo.png')
f.close()
return uri
def main():
src_im = Image.open(sys.argv[1])
# read and parse 9-patch stretch and padding regions
stretch_l, stretch_r = find_black_region_(src_im, 0, 0, src_im.size[0], 0)
stretch_t, stretch_b = find_black_region_(src_im, 0, 0, 0, src_im.size[1])
pad_l, pad_r = find_black_region_(src_im, 0, src_im.size[1] - 1, src_im.size[0], src_im.size[1] - 1)
pad_t, pad_b = find_black_region_(src_im, src_im.size[0] - 1, 0, src_im.size[0] - 1, src_im.size[1])
#padding_box = {}
template_params = {}
template_params['id'] = sys.argv[1]
template_params['icon_uri'] = image_to_data_uri_(src_im)
template_params['dim_constraint_attributes'] = '' # p:lockHeight="true"
template_params['image_uri'] = image_to_data_uri_(src_im.crop((1, 1, src_im.size[0] - 1, src_im.size[1] - 1)))
template_params['width_l'] = stretch_l - 1
template_params['width_r'] = src_im.size[0] - stretch_r - 1
template_params['height_t'] = stretch_t - 1
template_params['height_b'] = src_im.size[1] - stretch_b - 1
template_params['pad_l'] = pad_l - 1
template_params['pad_t'] = pad_t - 1
template_params['pad_r'] = src_im.size[0] - pad_r - 1
template_params['pad_b'] = src_im.size[1] - pad_b - 1
print open('res/shape_9patch_template.xml').read() % template_params
if __name__ == '__main__':
main() | 07pratik-androidui | stencils/pencil/stengen/shape_from_9patch.py | Python | asf20 | 2,932 |
#!/usr/bin/env python
# Copyright 2010 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.
import sys
import os
from StringIO import StringIO
from PIL import Image
import datauri
def image_to_data_uri_(im):
f = StringIO()
im.save(f, 'PNG')
uri = datauri.to_data_uri(f.getvalue(), 'foo.png')
f.close()
return uri
def main():
src_im = Image.open(sys.argv[1])
template_params = {}
template_params['id'] = sys.argv[1]
template_params['image_uri'] = image_to_data_uri_(src_im)
template_params['icon_uri'] = image_to_data_uri_(src_im)
template_params['width'] = src_im.size[0]
template_params['height'] = src_im.size[1]
print open('res/shape_png_template.xml').read() % template_params
if __name__ == '__main__':
main() | 07pratik-androidui | stencils/pencil/stengen/shape_from_png.py | Python | asf20 | 1,265 |
#!/usr/bin/env python
# Copyright 2010 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.
import sys
import os
import os.path
import shutil
import zipfile
def main():
params = {}
params['id'] = sys.argv[1]
params['displayname'] = sys.argv[2]
params['description'] = sys.argv[3]
zip_file = zipfile.ZipFile('dist/stencil-%s.zip' % params['id'], 'w',
zipfile.ZIP_DEFLATED)
# save stencil XML
shapes_xml = ''
shapes_folder = 'res/sets/%s/shapes' % params['id']
for shape_file in os.listdir(shapes_folder):
if not shape_file.endswith('.xml'):
continue
shape_xml = open(os.path.join(shapes_folder, shape_file)).read()
shapes_xml += shape_xml
params['shapes'] = shapes_xml
final_xml = open('res/stencil_template.xml').read() % params
zip_file.writestr('Definition.xml', final_xml)
# save icons
icons_folder = 'res/sets/%s/icons' % params['id']
for icon_file in os.listdir(icons_folder):
if not icon_file.endswith('.png'):
continue
zip_file.writestr(
'icons/%s' % icon_file,
open(os.path.join(icons_folder, icon_file), 'rb').read())
zip_file.close()
if __name__ == '__main__':
main() | 07pratik-androidui | stencils/pencil/stengen/stencil_generator.py | Python | asf20 | 1,691 |
#!/usr/bin/env python
# Copyright 2010 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.
import base64
import sys
import mimetypes
def to_data_uri(data, file_name):
'''Takes a file object and returns its data: string.'''
mime_type = mimetypes.guess_type(file_name)
return 'data:%(mimetype)s;base64,%(data)s' % dict(mimetype=mime_type[0],
data=base64.b64encode(data))
def main():
print to_data_uri(open(sys.argv[1], 'rb').read(), sys.argv[1])
if __name__ == '__main__':
main() | 07pratik-androidui | stencils/pencil/stengen/datauri.py | Python | asf20 | 1,011 |
#!/bin/sh
# Copyright 2010 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.
mkdir -p _sandbox/rawshapes
for shpfl in `ls res/raw`; do
echo $shpfl
if [[ "$shpfl" =~ ".9.png" ]]; then
python stengen/shape_from_9patch.py res/raw/$shpfl > _sandbox/rawshapes/$shpfl.xml
else
python stengen/shape_from_png.py res/raw/$shpfl > _sandbox/rawshapes/$shpfl.xml
fi
done
| 07pratik-androidui | stencils/pencil/make-rawshapes.sh | Shell | asf20 | 889 |
#!/bin/sh
# Copyright 2010 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.
mkdir -p dist
python stengen/stencil_generator.py frame "Frames" "Device frames"
python stengen/stencil_generator.py basic "Basic Controls" "Basic UI elements"
python stengen/stencil_generator.py launcher "Launcher and Widgets" "Home screen (Launcher) and app widgets"
python stengen/stencil_generator.py patterns "UI Patterns" "User interface patterns" | 07pratik-androidui | stencils/pencil/make.sh | Shell | asf20 | 944 |
/*
Copyright 2010 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.
*/
//#INSERTFILE "../../lib/filter.js"
//#INSERTFILE "../../lib/glfx.js" | 07pratik-androidui | asset-studio/src/js/src/imagelib/includes.js | JavaScript | asf20 | 629 |
/*
Copyright 2010 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.
*/
//#ECHO (function() {
var imagelib = {};
| 07pratik-androidui | asset-studio/src/js/src/imagelib/_header.js | JavaScript | asf20 | 602 |
/*
Copyright 2010 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.
*/
//#REQUIRE "includes.js"
imagelib.drawing = {};
imagelib.drawing.context = function(size) {
var canvas = document.createElement('canvas');
canvas.width = size.w;
canvas.height = size.h;
canvas.style.setProperty('image-rendering', 'optimizeQuality', null);
return canvas.getContext('2d');
};
imagelib.drawing.copy = function(dstCtx, src, size) {
dstCtx.drawImage(src.canvas || src, 0, 0, size.w, size.h);
};
imagelib.drawing.clear = function(ctx, size) {
ctx.clearRect(0, 0, size.w, size.h);
};
imagelib.drawing.drawCenterInside = function(dstCtx, src, dstRect, srcRect) {
if (srcRect.w / srcRect.h > dstRect.w / dstRect.h) {
var h = srcRect.h * dstRect.w / srcRect.w;
imagelib.drawing.drawImageScaled(dstCtx, src,
srcRect.x, srcRect.y,
srcRect.w, srcRect.h,
dstRect.x, dstRect.y + (dstRect.h - h) / 2,
dstRect.w, h);
} else {
var w = srcRect.w * dstRect.h / srcRect.h;
imagelib.drawing.drawImageScaled(dstCtx, src,
srcRect.x, srcRect.y,
srcRect.w, srcRect.h,
dstRect.x + (dstRect.w - w) / 2, dstRect.y,
w, dstRect.h);
}
};
imagelib.drawing.drawCenterCrop = function(dstCtx, src, dstRect, srcRect) {
if (srcRect.w / srcRect.h > dstRect.w / dstRect.h) {
var w = srcRect.h * dstRect.w / dstRect.h;
imagelib.drawing.drawImageScaled(dstCtx, src,
srcRect.x + (srcRect.w - w) / 2, srcRect.y,
w, srcRect.h,
dstRect.x, dstRect.y,
dstRect.w, dstRect.h);
} else {
var h = srcRect.w * dstRect.h / dstRect.w;
imagelib.drawing.drawImageScaled(dstCtx, src,
srcRect.x, srcRect.y + (srcRect.h - h) / 2,
srcRect.w, h,
dstRect.x, dstRect.y,
dstRect.w, dstRect.h);
}
};
imagelib.drawing.drawImageScaled = function(dstCtx, src, sx, sy, sw, sh, dx, dy, dw, dh) {
if ((dw < sw && dh < sh) && imagelib.ALLOW_MANUAL_RESCALE) {
sx = Math.floor(sx);
sy = Math.floor(sy);
sw = Math.ceil(sw);
sh = Math.ceil(sh);
dx = Math.floor(dx);
dy = Math.floor(dy);
dw = Math.ceil(dw);
dh = Math.ceil(dh);
// scaling down, use an averaging algorithm since canvas.drawImage doesn't do a good
// job in all browsers.
var tmpCtx = imagelib.drawing.context({ w: sw, h: sh });
tmpCtx.drawImage(src.canvas || src, 0, 0);
var srcData = tmpCtx.getImageData(0, 0, sw, sh);
var outCtx = imagelib.drawing.context({ w: dw, h: dh });
var outData = outCtx.createImageData(dw, dh);
var tr, tg, tb, ta; // R/G/B/A totals
var numOpaquePixels;
var numPixels;
for (var y = 0; y < dh; y++) {
for (var x = 0; x < dw; x++) {
tr = tg = tb = ta = 0;
numOpaquePixels = numPixels = 0;
// Average the relevant region from source image
for (var j = Math.floor(y * sh / dh); j < (y + 1) * sh / dh; j++) {
for (var i = Math.floor(x * sw / dw); i < (x + 1) * sw / dw; i++) {
++numPixels;
ta += srcData.data[(j * sw + i) * 4 + 3];
if (srcData.data[(j * sw + i) * 4 + 3] == 0) {
// disregard transparent pixels when computing average for R/G/B
continue;
}
++numOpaquePixels;
tr += srcData.data[(j * sw + i) * 4 + 0];
tg += srcData.data[(j * sw + i) * 4 + 1];
tb += srcData.data[(j * sw + i) * 4 + 2];
}
}
outData.data[(y * dw + x) * 4 + 0] = tr / numOpaquePixels;
outData.data[(y * dw + x) * 4 + 1] = tg / numOpaquePixels;
outData.data[(y * dw + x) * 4 + 2] = tb / numOpaquePixels;
outData.data[(y * dw + x) * 4 + 3] = ta / numPixels;
}
}
outCtx.putImageData(outData, 0, 0);
dstCtx.drawImage(outCtx.canvas, dx, dy);
} else {
// scaling up, use canvas.drawImage
dstCtx.drawImage(src.canvas || src, sx, sy, sw, sh, dx, dy, dw, dh);
}
};
imagelib.drawing.trimRectWorkerJS_ = [
"self['onmessage'] = function(event) { ",
" var l = event.data.size.w, t = event.data.size.h, r = 0, b = 0; ",
" ",
" var alpha; ",
" for (var y = 0; y < event.data.size.h; y++) { ",
" for (var x = 0; x < event.data.size.w; x++) { ",
" alpha = event.data.imageData.data[ ",
" ((y * event.data.size.w + x) << 2) + 3]; ",
" if (alpha >= event.data.minAlpha) { ",
" l = Math.min(x, l); ",
" t = Math.min(y, t); ",
" r = Math.max(x, r); ",
" b = Math.max(y, b); ",
" } ",
" } ",
" } ",
" ",
" if (l > r) { ",
" // no pixels, couldn't trim ",
" postMessage({ x: 0, y: 0, w: event.data.size.w, h: event.data.size.h });",
" return; ",
" } ",
" ",
" postMessage({ x: l, y: t, w: r - l + 1, h: b - t + 1 }); ",
"}; ",
""].join('\n');
imagelib.drawing.getTrimRect = function(ctx, size, minAlpha, callback) {
callback = callback || function(){};
if (!ctx.canvas) {
// Likely an image
var src = ctx;
ctx = imagelib.drawing.context(size);
imagelib.drawing.copy(ctx, src, size);
}
if (minAlpha == 0)
callback({ x: 0, y: 0, w: size.w, h: size.h });
minAlpha = minAlpha || 1;
var worker = imagelib.util.runWorkerJs(
imagelib.drawing.trimRectWorkerJS_,
{
imageData: ctx.getImageData(0, 0, size.w, size.h),
size: size,
minAlpha: minAlpha
},
callback);
return worker;
};
imagelib.drawing.getCenterOfMass = function(ctx, size, minAlpha, callback) {
callback = callback || function(){};
if (!ctx.canvas) {
// Likely an image
var src = ctx;
ctx = imagelib.drawing.context(size);
imagelib.drawing.copy(ctx, src, size);
}
if (minAlpha == 0)
callback({ x: size.w / 2, y: size.h / 2 });
minAlpha = minAlpha || 1;
var l = size.w, t = size.h, r = 0, b = 0;
var imageData = ctx.getImageData(0, 0, size.w, size.h);
var sumX = 0;
var sumY = 0;
var n = 0; // number of pixels > minAlpha
var alpha;
for (var y = 0; y < size.h; y++) {
for (var x = 0; x < size.w; x++) {
alpha = imageData.data[((y * size.w + x) << 2) + 3];
if (alpha >= minAlpha) {
sumX += x;
sumY += y;
++n;
}
}
}
if (n <= 0) {
// no pixels > minAlpha, just use center
callback({ x: size.w / 2, h: size.h / 2 });
}
callback({ x: Math.round(sumX / n), y: Math.round(sumY / n) });
};
imagelib.drawing.copyAsAlpha = function(dstCtx, src, size, onColor, offColor) {
onColor = onColor || '#fff';
offColor = offColor || '#000';
dstCtx.save();
dstCtx.clearRect(0, 0, size.w, size.h);
dstCtx.globalCompositeOperation = 'source-over';
imagelib.drawing.copy(dstCtx, src, size);
dstCtx.globalCompositeOperation = 'source-atop';
dstCtx.fillStyle = onColor;
dstCtx.fillRect(0, 0, size.w, size.h);
dstCtx.globalCompositeOperation = 'destination-atop';
dstCtx.fillStyle = offColor;
dstCtx.fillRect(0, 0, size.w, size.h);
dstCtx.restore();
};
imagelib.drawing.makeAlphaMask = function(ctx, size, fillColor) {
var src = ctx.getImageData(0, 0, size.w, size.h);
var dst = ctx.createImageData(size.w, size.h);
var srcData = src.data;
var dstData = dst.data;
var i, g;
for (var y = 0; y < size.h; y++) {
for (var x = 0; x < size.w; x++) {
i = (y * size.w + x) << 2;
g = 0.30 * srcData[i] +
0.59 * srcData[i + 1] +
0.11 * srcData[i + 2];
dstData[i] = dstData[i + 1] = dstData[i + 2] = 255;
dstData[i + 3] = g;
}
}
ctx.putImageData(dst, 0, 0);
if (fillColor) {
ctx.save();
ctx.globalCompositeOperation = 'source-atop';
ctx.fillStyle = fillColor;
ctx.fillRect(0, 0, size.w, size.h);
ctx.restore();
}
};
imagelib.drawing.applyFilter = function(filter, ctx, size) {
var src = ctx.getImageData(0, 0, size.w, size.h);
var dst = ctx.createImageData(size.w, size.h);
filter.apply(src, dst);
ctx.putImageData(dst, 0, 0);
};
(function() {
function slowblur_(radius, ctx, size) {
var rows = Math.ceil(radius);
var r = rows * 2 + 1;
var matrix = new Array(r * r);
var sigma = radius / 3;
var sigma22 = 2 * sigma * sigma;
var sqrtPiSigma22 = Math.sqrt(Math.PI * sigma22);
var radius2 = radius * radius;
var total = 0;
var index = 0;
var distance2;
for (var y = -rows; y <= rows; y++) {
for (var x = -rows; x <= rows; x++) {
distance2 = 1.0*x*x + 1.0*y*y;
if (distance2 > radius2)
matrix[index] = 0;
else
matrix[index] = Math.exp(-distance2 / sigma22) / sqrtPiSigma22;
total += matrix[index];
index++;
}
}
imagelib.drawing.applyFilter(
new ConvolutionFilter(matrix, total, 0, true),
ctx, size);
}
function glfxblur_(radius, ctx, size) {
var canvas = fx.canvas();
var texture = canvas.texture(ctx.canvas);
canvas.draw(texture).triangleBlur(radius).update();
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(canvas, 0, 0);
}
imagelib.drawing.blur = function(radius, ctx, size) {
try {
if (size.w > 128 || size.h > 128) {
glfxblur_(radius, ctx, size);
} else {
slowblur_(radius, ctx, size);
}
} catch (e) {
// WebGL unavailable, use the slower blur
slowblur_(radius, ctx, size);
}
};
})();
imagelib.drawing.fx = function(effects, dstCtx, src, size) {
effects = effects || [];
var outerEffects = [];
var innerEffects = [];
var fillEffects = [];
for (var i = 0; i < effects.length; i++) {
if (/^outer/.test(effects[i].effect)) outerEffects.push(effects[i]);
else if (/^inner/.test(effects[i].effect)) innerEffects.push(effects[i]);
else if (/^fill/.test(effects[i].effect)) fillEffects.push(effects[i]);
}
var padLeft = 0, padTop, padRight, padBottom;
var paddedSize;
var tmpCtx, tmpCtx2;
// Render outer effects
for (var i = 0; i < outerEffects.length; i++) {
padLeft = Math.max(padLeft, outerEffects[i].blur || 0); // blur radius
}
padTop = padRight = padBottom = padLeft;
paddedSize = {
w: size.w + padLeft + padRight,
h: size.h + padTop + padBottom
};
tmpCtx = imagelib.drawing.context(paddedSize);
for (var i = 0; i < outerEffects.length; i++) {
var effect = outerEffects[i];
dstCtx.save(); // D1
tmpCtx.save(); // T1
switch (effect.effect) {
case 'outer-shadow':
// The below method (faster) fails in Safari and other browsers, for some reason. Likely
// something to do with the source-atop blending mode.
// TODO: investigate why it fails in Safari
// imagelib.drawing.clear(tmpCtx, size);
// imagelib.drawing.copy(tmpCtx, src.canvas || src, size);
// if (effect.blur)
// imagelib.drawing.blur(effect.blur, tmpCtx, size);
// tmpCtx.globalCompositeOperation = 'source-atop';
// tmpCtx.fillStyle = effect.color || '#000';
// tmpCtx.fillRect(0, 0, size.w, size.h);
// if (effect.translate)
// dstCtx.translate(effect.translate.x || 0, effect.translate.y || 0);
//
// dstCtx.globalAlpha = Math.max(0, Math.min(1, effect.opacity || 1));
// imagelib.drawing.copy(dstCtx, tmpCtx, size);
imagelib.drawing.clear(tmpCtx, paddedSize);
tmpCtx.save(); // T2
tmpCtx.translate(padLeft, padTop);
imagelib.drawing.copyAsAlpha(tmpCtx, src.canvas || src, size);
tmpCtx.restore(); // T2
if (effect.blur)
imagelib.drawing.blur(effect.blur, tmpCtx, paddedSize);
imagelib.drawing.makeAlphaMask(tmpCtx, paddedSize, effect.color || '#000');
if (effect.translate)
dstCtx.translate(effect.translate.x || 0, effect.translate.y || 0);
dstCtx.globalAlpha = Math.max(0, Math.min(1, effect.opacity || 1));
dstCtx.translate(-padLeft, -padTop);
imagelib.drawing.copy(dstCtx, tmpCtx, paddedSize);
break;
}
dstCtx.restore(); // D1
tmpCtx.restore(); // T1
}
dstCtx.save(); // D1
// Render object with optional fill effects (only take first fill effect)
tmpCtx = imagelib.drawing.context(size);
imagelib.drawing.clear(tmpCtx, size);
imagelib.drawing.copy(tmpCtx, src.canvas || src, size);
var fillOpacity = 1.0;
if (fillEffects.length) {
var effect = fillEffects[0];
tmpCtx.save(); // T1
tmpCtx.globalCompositeOperation = 'source-atop';
switch (effect.effect) {
case 'fill-color':
tmpCtx.fillStyle = effect.color;
break;
case 'fill-lineargradient':
var gradient = tmpCtx.createLinearGradient(
effect.from.x, effect.from.y, effect.to.x, effect.to.y);
for (var i = 0; i < effect.colors.length; i++) {
gradient.addColorStop(effect.colors[i].offset, effect.colors[i].color);
}
tmpCtx.fillStyle = gradient;
break;
}
fillOpacity = Math.max(0, Math.min(1, effect.opacity || 1));
tmpCtx.fillRect(0, 0, size.w, size.h);
tmpCtx.restore(); // T1
}
dstCtx.globalAlpha = fillOpacity;
imagelib.drawing.copy(dstCtx, tmpCtx, size);
dstCtx.globalAlpha = 1.0;
// Render inner effects
var translate;
padLeft = padTop = padRight = padBottom = 0;
for (var i = 0; i < innerEffects.length; i++) {
translate = effect.translate || {};
padLeft = Math.max(padLeft, (innerEffects[i].blur || 0) + Math.max(0, translate.x || 0));
padTop = Math.max(padTop, (innerEffects[i].blur || 0) + Math.max(0, translate.y || 0));
padRight = Math.max(padRight, (innerEffects[i].blur || 0) + Math.max(0, -translate.x || 0));
padBottom = Math.max(padBottom, (innerEffects[i].blur || 0) + Math.max(0, -translate.y || 0));
}
paddedSize = {
w: size.w + padLeft + padRight,
h: size.h + padTop + padBottom
};
tmpCtx = imagelib.drawing.context(paddedSize);
tmpCtx2 = imagelib.drawing.context(paddedSize);
for (var i = 0; i < innerEffects.length; i++) {
var effect = innerEffects[i];
dstCtx.save(); // D2
tmpCtx.save(); // T1
switch (effect.effect) {
case 'inner-shadow':
imagelib.drawing.clear(tmpCtx, paddedSize);
tmpCtx.save(); // T2
tmpCtx.translate(padLeft, padTop);
imagelib.drawing.copyAsAlpha(tmpCtx, src.canvas || src, size, '#fff', '#000');
tmpCtx.restore(); // T2
tmpCtx2.save(); // T2
tmpCtx2.translate(padLeft, padTop);
imagelib.drawing.copyAsAlpha(tmpCtx2, src.canvas || src, size);
tmpCtx2.restore(); // T2
if (effect.blur)
imagelib.drawing.blur(effect.blur, tmpCtx2, paddedSize);
imagelib.drawing.makeAlphaMask(tmpCtx2, paddedSize, '#000');
if (effect.translate)
tmpCtx.translate(effect.translate.x || 0, effect.translate.y || 0);
tmpCtx.globalCompositeOperation = 'source-over';
imagelib.drawing.copy(tmpCtx, tmpCtx2, paddedSize);
imagelib.drawing.makeAlphaMask(tmpCtx, paddedSize, effect.color);
dstCtx.globalAlpha = Math.max(0, Math.min(1, effect.opacity || 1));
dstCtx.translate(-padLeft, -padTop);
imagelib.drawing.copy(dstCtx, tmpCtx, paddedSize);
break;
}
tmpCtx.restore(); // T1
dstCtx.restore(); // D2
}
dstCtx.restore(); // D1
};
| 07pratik-androidui | asset-studio/src/js/src/imagelib/drawing.js | JavaScript | asf20 | 17,043 |
/*
Copyright 2010 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.
*/
imagelib.util = {};
/**
* Helper method for running inline Web Workers, if the browser can support
* them. If the browser doesn't support inline Web Workers, run the script
* on the main thread, with this function body's scope, using eval. Browsers
* must provide BlobBuilder, URL.createObjectURL, and Worker support to use
* inline Web Workers. Most features such as importScripts() are not
* currently supported, so this only works for basic workers.
* @param {String} js The inline Web Worker Javascript code to run. This code
* must use 'self' and not 'this' as the global context variable.
* @param {Object} params The parameters object to pass to the worker.
* Equivalent to calling Worker.postMessage(params);
* @param {Function} callback The callback to run when the worker calls
* postMessage. Equivalent to adding a 'message' event listener on a
* Worker object and running callback(event.data);
*/
imagelib.util.runWorkerJs = function(js, params, callback) {
var BlobBuilder = (window.BlobBuilder || window.WebKitBlobBuilder);
var URL = (window.URL || window.webkitURL);
var Worker = window.Worker;
if (URL && BlobBuilder && Worker) {
// BlobBuilder, Worker, and window.URL.createObjectURL are all available,
// so we can use inline workers.
var bb = new BlobBuilder();
bb.append(js);
var worker = new Worker(URL.createObjectURL(bb.getBlob()));
worker.onmessage = function(event) {
callback(event.data);
};
worker.postMessage(params);
return worker;
} else {
// We can't use inline workers, so run the worker JS on the main thread.
(function() {
var __DUMMY_OBJECT__ = {};
// Proxy to Worker.onmessage
var postMessage = function(result) {
callback(result);
};
// Bind the worker to this dummy object. The worker will run
// in this scope.
eval('var self=__DUMMY_OBJECT__;\n' + js);
// Proxy to Worker.postMessage
__DUMMY_OBJECT__.onmessage({
data: params
});
})();
// Return a dummy Worker.
return {
terminate: function(){}
};
}
};
| 07pratik-androidui | asset-studio/src/js/src/imagelib/util.js | JavaScript | asf20 | 2,697 |
/*
Copyright 2010 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.
*/
window.imagelib = imagelib;
//#ECHO })();
| 07pratik-androidui | asset-studio/src/js/src/imagelib/_footer.js | JavaScript | asf20 | 603 |
/*
Copyright 2010 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.
*/
imagelib.loadImageResources = function(images, callback) {
var imageResources = {};
var checkForCompletion = function() {
for (var id in images) {
if (!(id in imageResources))
return;
}
(callback || function(){})(imageResources);
callback = null;
};
for (var id in images) {
var img = document.createElement('img');
img.src = images[id];
(function(img, id) {
img.onload = function() {
imageResources[id] = img;
checkForCompletion();
};
img.onerror = function() {
imageResources[id] = null;
checkForCompletion();
}
})(img, id);
}
};
imagelib.loadFromUri = function(uri, callback) {
callback = callback || function(){};
var img = document.createElement('img');
img.src = uri;
img.onload = function() {
callback(img);
};
img.onerror = function() {
callback(null);
}
};
imagelib.toDataUri = function(img) {
var canvas = document.createElement('canvas');
canvas.width = img.naturalWidth;
canvas.height = img.naturalHeight;
var ctx = canvas.getContext('2d');
ctx.drawImage(img, 0, 0);
return canvas.toDataURL();
}; | 07pratik-androidui | asset-studio/src/js/src/imagelib/imagelib.js | JavaScript | asf20 | 1,721 |
/*
Copyright 2010 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.
*/
studio.checkBrowser = function() {
var chromeMatch = navigator.userAgent.match(/Chrome\/(\d+)/);
var browserSupported = false;
if (chromeMatch) {
var chromeVersion = parseInt(chromeMatch[1], 10);
if (chromeVersion >= 6) {
browserSupported = true;
}
}
if (!browserSupported) {
$('<div>')
.addClass('browser-unsupported-note ui-state-highlight')
.attr('title', 'Your browser is not supported.')
.append($('<span class="ui-icon ui-icon-alert" ' +
'style="float:left; margin:0 7px 50px 0;">'))
.append($('<p>')
.html('Currently only ' +
'<a href="http://www.google.com/chrome">Google Chrome</a> ' +
'is recommended and supported. Your mileage may vary with ' +
'other browsers.'))
.prependTo('body');
}
};
| 07pratik-androidui | asset-studio/src/js/src/studio/browsersupport.js | JavaScript | asf20 | 1,393 |
/*
Copyright 2010 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.
*/
//#INSERTFILE "../../lib/jquery.ui.combobox.js"
//#INSERTFILE "../../lib/jquery.ui.autocompletewithbutton.js"
| 07pratik-androidui | asset-studio/src/js/src/studio/includes.js | JavaScript | asf20 | 670 |
/*
Copyright 2010 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.
*/
//#ECHO (function() {
var studio = {};
| 07pratik-androidui | asset-studio/src/js/src/studio/_header.js | JavaScript | asf20 | 600 |
/*
Copyright 2010 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.
*/
//#REQUIRE "fields.js"
/**
* This is needed due to what seems like a bug in Chrome where using drawImage
* with any SVG, regardless of origin (even if it was loaded from a data URI),
* marks the canvas's origin dirty flag, precluding us from accessing its pixel
* data.
*/
var USE_CANVG = window.canvg && true;
/**
* Represents a form field for image values.
*/
studio.forms.ImageField = studio.forms.Field.extend({
constructor: function(id, params) {
this.valueType_ = null;
this.textParams_ = {};
this.imageParams_ = {};
this.spaceFormValues_ = {}; // cache
this.base(id, params);
},
createUI: function(container) {
var fieldUI = this.base(container);
var fieldContainer = $('.form-field-container', fieldUI);
var me = this;
// Set up drag+drop on the entire field container
fieldUI.addClass('form-field-drop-target');
fieldUI.get(0).ondragenter = studio.forms.ImageField.makeDragenterHandler_(
fieldUI);
fieldUI.get(0).ondragleave = studio.forms.ImageField.makeDragleaveHandler_(
fieldUI);
fieldUI.get(0).ondragover = studio.forms.ImageField.makeDragoverHandler_(
fieldUI);
fieldUI.get(0).ondrop = studio.forms.ImageField.makeDropHandler_(fieldUI,
function(evt) {
studio.forms.ImageField.loadImageFromFileList(evt.dataTransfer.files, function(ret) {
if (!ret)
return;
me.setValueType_('image');
me.imageParams_ = ret;
me.valueFilename_ = ret.name;
me.renderValueAndNotifyChanged_();
});
});
// Create radio buttons
this.el_ = $('<div>')
.attr('id', this.getHtmlId())
.addClass('.form-field-buttonset')
.appendTo(fieldContainer);
var types;
if (this.params_.imageOnly) {
types = [
'image', 'Select Image'
];
} else {
types = [
'image', 'Image',
'clipart', 'Clipart',
'text', 'Text'
];
}
var typeEls = {};
for (var i = 0; i < types.length / 2; i++) {
$('<input>')
.attr({
type: 'radio',
name: this.getHtmlId(),
id: this.getHtmlId() + '-' + types[i * 2],
value: types[i * 2]
})
.appendTo(this.el_);
typeEls[types[i * 2]] = $('<label>')
.attr('for', this.getHtmlId() + '-' + types[i * 2])
.text(types[i * 2 + 1])
.appendTo(this.el_);
}
this.el_.buttonset();
// Prepare UI for the 'image' type
this.fileEl_ = $('<input>')
.addClass('form-image-hidden-file-field')
.attr({
id: this.getHtmlId(),
type: 'file',
accept: 'image/*'
})
.change(function() {
studio.forms.ImageField.loadImageFromFileList(me.fileEl_.get(0).files, function(ret) {
if (!ret)
return;
me.setValueType_('image');
me.imageParams_ = ret;
me.valueFilename_ = ret.name;
me.renderValueAndNotifyChanged_();
});
})
.appendTo(this.el_);
typeEls.image.click(function(evt) {
me.fileEl_.trigger('click');
me.setValueType_(null);
me.renderValueAndNotifyChanged_();
evt.preventDefault();
return false;
});
// Prepare UI for the 'clipart' type
if (!this.params_.imageOnly) {
var clipartParamsEl = $('<div>')
.addClass('form-image-type-params form-image-type-params-clipart')
.hide()
.appendTo(this.el_);
var clipartListEl = $('<div>')
.addClass('form-image-clipart-list')
.appendTo(clipartParamsEl);
for (var i = 0; i < studio.forms.ImageField.clipartList_.length; i++) {
var clipartSrc = 'res/clipart/' + studio.forms.ImageField.clipartList_[i];
$('<img>')
.addClass('form-image-clipart-item')
.attr('src', clipartSrc)
.click(function(clipartSrc) {
return function() {
me.loadClipart_(clipartSrc);
};
}(clipartSrc))
.appendTo(clipartListEl);
}
var clipartAttributionEl = $('<div>')
.addClass('form-image-clipart-attribution')
.html([
'Clipart courtesy of ',
'<a href="http://www.yay.se/2011/02/',
'native-android-icons-in-vector-format/"',
' target="_blank">Olof Brickarp</a>.'
].join(''))
.appendTo(clipartParamsEl);
typeEls.clipart.click(function(evt) {
me.setValueType_('clipart');
me.renderValueAndNotifyChanged_();
});
// Prepare UI for the 'text' type
var textParamsEl = $('<div>')
.addClass(
'form-subform ' +
'form-image-type-params ' +
'form-image-type-params-text')
.hide()
.appendTo(this.el_);
this.textForm_ = new studio.forms.Form(
this.form_.id_ + '-' + this.id_ + '-textform', {
onChange: function() {
var values = me.textForm_.getValues();
me.textParams_.text = values['text'];
me.textParams_.fontStack = values['font']
? values['font'] : 'sans-serif';
me.valueFilename_ = values['text'];
me.tryLoadWebFont_();
me.renderValueAndNotifyChanged_();
},
fields: [
new studio.forms.TextField('text', {
title: 'Text',
}),
new studio.forms.AutocompleteTextField('font', {
title: 'Font',
items: studio.forms.ImageField.fontList_
})
]
});
this.textForm_.createUI(textParamsEl);
typeEls.text.click(function(evt) {
me.setValueType_('text');
me.renderValueAndNotifyChanged_();
});
}
// Create spacing subform
if (!this.params_.noTrimForm) {
this.spaceFormValues_ = {};
this.spaceForm_ = new studio.forms.Form(
this.form_.id_ + '-' + this.id_ + '-spaceform', {
onChange: function() {
me.spaceFormValues_ = me.spaceForm_.getValues();
me.renderValueAndNotifyChanged_();
},
fields: [
new studio.forms.BooleanField('trim', {
title: 'Trim',
defaultValue: this.params_.defaultValueTrim || false,
offText: 'Don\'t Trim',
onText: 'Trim'
}),
new studio.forms.RangeField('pad', {
title: 'Padding',
defaultValue: 0,
min: -0.1,
max: 0.5, // 1/2 of min(width, height)
step: 0.05,
textFn: function(v) {
return (v * 100) + '%';
}
}),
]
});
this.spaceForm_.createUI($('<div>')
.addClass('form-subform')
.appendTo(fieldContainer));
this.spaceFormValues_ = this.spaceForm_.getValues();
} else {
this.spaceFormValues_ = {};
}
// Create image preview element
if (!this.params_.noPreview) {
this.imagePreview_ = $('<canvas>')
.addClass('form-image-preview')
.hide()
.appendTo(fieldContainer.parent());
}
},
tryLoadWebFont_: function(force) {
var desiredFont = this.textForm_.getValues()['font'];
if (this.loadedWebFont_ == desiredFont) {
return;
}
var me = this;
if (!force) {
if (this.tryLoadWebFont_.timeout_) {
clearTimeout(this.tryLoadWebFont_.timeout_);
}
this.tryLoadWebFont_.timeout_ = setTimeout(function() {
me.tryLoadWebFont_(true);
}, 100);
return;
}
this.loadedWebFont_ = desiredFont;
var webFontNodeId = this.form_.id_ + '-' + this.id_ + '-__webfont-stylesheet__';
var $webFontNode = $('#' + webFontNodeId);
if (!$webFontNode.length) {
$webFontNode = $('<link>')
.attr('id', webFontNodeId)
.attr('rel', 'stylesheet')
.appendTo('head');
}
$webFontNode.attr(
'href', 'http://fonts.googleapis.com/css?family='
+ encodeURIComponent(desiredFont));
},
setValueType_: function(type) {
this.valueType_ = type;
$('label', this.el_).removeClass('ui-state-active');
$('.form-image-type-params', this.el_).hide();
if (type) {
$('label[for=' + this.getHtmlId() + '-' + type + ']').addClass('ui-state-active');
$('.form-image-type-params-' + type, this.el_).show();
}
},
loadClipart_: function(clipartSrc) {
var useCanvg = USE_CANVG && clipartSrc.match(/\.svg$/);
$('img.form-image-clipart-item', this.el_).removeClass('selected');
$('img[src="' + clipartSrc + '"]').addClass('selected');
this.imageParams_ = {
canvgSvgUri: useCanvg ? clipartSrc : null,
uri: useCanvg ? null : clipartSrc
};
this.clipartSrc_ = clipartSrc;
this.valueFilename_ = clipartSrc.match(/[^/]+$/)[0];
this.renderValueAndNotifyChanged_();
},
clearValue: function() {
this.valueType_ = null;
this.valueFilename_ = null;
this.valueCtx_ = null;
this.fileEl_.val('');
if (this.imagePreview_) {
this.imagePreview_.hide();
}
},
getValue: function() {
return {
ctx: this.valueCtx_,
name: this.valueFilename_
};
},
// this function is asynchronous
renderValueAndNotifyChanged_: function() {
if (!this.valueType_) {
this.valueCtx_ = null;
}
var me = this;
// Render the base image (text, clipart, or image)
switch (this.valueType_) {
case 'image':
case 'clipart':
if (this.imageParams_.canvgSvgText || this.imageParams_.canvgSvgUri) {
var canvas = document.createElement('canvas');
var size = { w: 800, h: 800 };
canvas.className = 'offscreen';
canvas.width = size.w;
canvas.height = size.h;
document.body.appendChild(canvas);
canvg(
canvas,
this.imageParams_.canvgSvgText ||
this.imageParams_.canvgSvgUri,
{
scaleWidth: size.w,
scaleHeight: size.h,
ignoreMouse: true,
ignoreAnimation: true,
ignoreDimensions: true,
ignoreClear: true
}
);
continue_(canvas.getContext('2d'), size);
document.body.removeChild(canvas);
} else if (this.imageParams_.uri) {
imagelib.loadFromUri(this.imageParams_.uri, function(img) {
var size = {
w: img.naturalWidth,
h: img.naturalHeight
};
var ctx = imagelib.drawing.context(size);
imagelib.drawing.copy(ctx, img, size);
continue_(ctx, size);
});
}
break;
case 'text':
var size = { w: 4800, h: 1600 };
var textHeight = size.h * 0.75;
var ctx = imagelib.drawing.context(size);
var text = this.textParams_.text || '';
text = ' ' + text + ' ';
ctx.fillStyle = '#000';
ctx.font = 'bold ' + textHeight + 'px/' + size.h + 'px ' +
(this.textParams_.fontStack || 'sans-serif');
ctx.textBaseline = 'alphabetic';
ctx.fillText(text, 0, textHeight);
size.w = Math.ceil(Math.min(ctx.measureText(text).width, size.w) || size.w);
continue_(ctx, size);
break;
default:
me.form_.notifyChanged_(me);
}
function continue_(srcCtx, srcSize) {
// Apply trimming
if (me.spaceFormValues_['trim']) {
if (me.trimWorker_) {
me.trimWorker_.terminate();
}
me.trimWorker_ = imagelib.drawing.getTrimRect(srcCtx, srcSize, 1,
function(trimRect) {
continue2_(srcCtx, srcSize, trimRect);
});
} else {
continue2_(srcCtx, srcSize,
/*trimRect*/{ x: 0, y: 0, w: srcSize.w, h: srcSize.h });
}
}
function continue2_(srcCtx, srcSize, trimRect) {
// If trimming, add a tiny bit of padding to fix artifacts around the
// edges.
var extraPadding = me.spaceFormValues_['trim'] ? 0.001 : 0;
if (trimRect.x == 0 && trimRect.y == 0 &&
trimRect.w == srcSize.w && trimRect.h == srcSize.h) {
extraPadding = 0;
}
var padPx = Math.round(((me.spaceFormValues_['pad'] || 0) + extraPadding) *
Math.min(trimRect.w, trimRect.h));
var targetRect = { x: padPx, y: padPx, w: trimRect.w, h: trimRect.h };
var outCtx = imagelib.drawing.context({
w: trimRect.w + padPx * 2,
h: trimRect.h + padPx * 2
});
// TODO: replace with a simple draw() as the centering is useless
imagelib.drawing.drawCenterInside(outCtx, srcCtx, targetRect, trimRect);
// Set the final URI value and show a preview
me.valueCtx_ = outCtx;
if (me.imagePreview_) {
me.imagePreview_.attr('width', outCtx.canvas.width);
me.imagePreview_.attr('height', outCtx.canvas.height);
var previewCtx = me.imagePreview_.get(0).getContext('2d');
previewCtx.drawImage(outCtx.canvas, 0, 0);
me.imagePreview_.show();
}
me.form_.notifyChanged_(me);
}
},
serializeValue: function() {
return {
type: this.valueType_,
space: this.spaceForm_.getValuesSerialized(),
clipart: (this.valueType_ == 'clipart') ? this.clipartSrc_ : null,
text: (this.valueType_ == 'text') ? this.textForm_.getValuesSerialized()
: null
};
},
deserializeValue: function(o) {
if (o.type) {
this.setValueType_(o.type);
}
if (o.space) {
this.spaceForm_.setValuesSerialized(o.space);
this.spaceFormValues_ = this.spaceForm_.getValues();
}
if (o.clipart && this.valueType_ == 'clipart') {
this.loadClipart_(o.clipart);
}
if (o.text && this.valueType_ == 'text') {
this.textForm_.setValuesSerialized(o.text);
this.tryLoadWebFont_();
}
}
});
studio.forms.ImageField.clipartList_ = [
'icons/accounts.svg',
'icons/add.svg',
'icons/agenda.svg',
'icons/all_friends.svg',
'icons/attachment.svg',
'icons/back.svg',
'icons/backspace.svg',
'icons/barcode.svg',
'icons/battery_charging.svg',
'icons/bell.svg',
'icons/block.svg',
'icons/block_user.svg',
'icons/bookmarks.svg',
'icons/camera.svg',
'icons/circle_arrow.svg',
'icons/clock.svg',
'icons/compass.svg',
'icons/cross.svg',
'icons/cross2.svg',
'icons/directions.svg',
'icons/down_arrow.svg',
'icons/edit.svg',
'icons/expand_arrows.svg',
'icons/export.svg',
'icons/eye.svg',
'icons/gallery.svg',
'icons/group.svg',
'icons/happy_droid.svg',
'icons/help.svg',
'icons/home.svg',
'icons/info.svg',
'icons/key.svg',
'icons/list.svg',
'icons/lock.svg',
'icons/mail.svg',
'icons/map.svg',
'icons/map_pin.svg',
'icons/mic.svg',
'icons/notification.svg',
'icons/phone.svg',
'icons/play_clip.svg',
'icons/plus.svg',
'icons/position.svg',
'icons/power.svg',
'icons/refresh.svg',
'icons/search.svg',
'icons/settings.svg',
'icons/share.svg',
'icons/slideshow.svg',
'icons/sort_by_size.svg',
'icons/sound_full.svg',
'icons/sound_off.svg',
'icons/star.svg',
'icons/stars_grade.svg',
'icons/stop.svg',
'icons/trashcan.svg',
'icons/usb.svg',
'icons/user.svg',
'icons/warning.svg'
];
studio.forms.ImageField.fontList_ = [
'Helvetica',
'Arial',
'Georgia',
'Book Antiqua',
'Palatino',
'Courier',
'Courier New',
'Webdings',
'Wingdings'
];
/**
* Loads the first valid image from a FileList (e.g. drag + drop source), as a data URI. This method
* will throw an alert() in case of errors and call back with null.
* @param {FileList} fileList The FileList to load.
* @param {Function} callback The callback to fire once image loading is done (or fails).
* @return Returns an object containing 'uri' or 'canvgSvgText' fields representing
* the loaded image. There will also be a 'name' field indicating the file name, if one
* is available.
*/
studio.forms.ImageField.loadImageFromFileList = function(fileList, callback) {
fileList = fileList || [];
var file = null;
for (var i = 0; i < fileList.length; i++) {
if (studio.forms.ImageField.isValidFile_(fileList[i])) {
file = fileList[i];
break;
}
}
if (!file) {
alert('Please choose a valid image file (PNG, JPG, GIF, SVG, etc.)');
callback(null);
return;
}
var useCanvg = USE_CANVG && file.type == 'image/svg+xml';
var fileReader = new FileReader();
// Closure to capture the file information.
fileReader.onload = function(e) {
callback({
uri: useCanvg ? null : e.target.result,
canvgSvgText: useCanvg ? e.target.result : null,
name: file.name
});
};
fileReader.onerror = function(e) {
switch(e.target.error.code) {
case e.target.error.NOT_FOUND_ERR:
alert('File not found!');
break;
case e.target.error.NOT_READABLE_ERR:
alert('File is not readable');
break;
case e.target.error.ABORT_ERR:
break; // noop
default:
alert('An error occurred reading this file.');
}
callback(null);
};
/*fileReader.onprogress = function(e) {
$('#read-progress').css('visibility', 'visible');
// evt is an ProgressEvent.
if (e.lengthComputable) {
$('#read-progress').val(Math.round((e.loaded / e.total) * 100));
} else {
$('#read-progress').removeAttr('value');
}
};*/
fileReader.onabort = function(e) {
alert('File read cancelled');
callback(null);
};
/*fileReader.onloadstart = function(e) {
$('#read-progress').css('visibility', 'visible');
};*/
if (useCanvg)
fileReader.readAsText(file);
else
fileReader.readAsDataURL(file);
};
/**
* Determines whether or not the given File is a valid value for the image.
* 'File' here is a File using the W3C File API.
* @private
* @param {File} file Describe this parameter
*/
studio.forms.ImageField.isValidFile_ = function(file) {
return !!file.type.toLowerCase().match(/^image\//);
};
/*studio.forms.ImageField.isValidFile_.allowedTypes = {
'image/png': true,
'image/jpeg': true,
'image/svg+xml': true,
'image/gif': true,
'image/vnd.adobe.photoshop': true
};*/
studio.forms.ImageField.makeDropHandler_ = function(el, handler) {
return function(evt) {
$(el).removeClass('drag-hover');
handler(evt);
};
};
studio.forms.ImageField.makeDragoverHandler_ = function(el) {
return function(evt) {
el = $(el).get(0);
if (el._studio_frm_dragtimeout_) {
window.clearTimeout(el._studio_frm_dragtimeout_);
el._studio_frm_dragtimeout_ = null;
}
evt.dataTransfer.dropEffect = 'link';
evt.preventDefault();
};
};
studio.forms.ImageField.makeDragenterHandler_ = function(el) {
return function(evt) {
el = $(el).get(0);
if (el._studio_frm_dragtimeout_) {
window.clearTimeout(el._studio_frm_dragtimeout_);
el._studio_frm_dragtimeout_ = null;
}
$(el).addClass('drag-hover');
evt.preventDefault();
};
};
studio.forms.ImageField.makeDragleaveHandler_ = function(el) {
return function(evt) {
el = $(el).get(0);
if (el._studio_frm_dragtimeout_)
window.clearTimeout(el._studio_frm_dragtimeout_);
el._studio_frm_dragtimeout_ = window.setTimeout(function() {
$(el).removeClass('drag-hover');
}, 100);
};
};
| 07pratik-androidui | asset-studio/src/js/src/studio/imagefield.js | JavaScript | asf20 | 20,069 |
/*
Copyright 2010 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.
*/
studio.hash = {};
studio.hash.boundFormOldOnChange_ = null;
studio.hash.boundForm_ = null;
studio.hash.currentParams_ = {};
studio.hash.currentHash_ = null; // The URI encoded, currently loaded state.
studio.hash.bindFormToDocumentHash = function(form) {
if (!studio.hash.boundForm_) {
// Checks for changes in the document hash
// and reloads the form if necessary.
var hashChecker_ = function() {
// Don't use document.location.hash because it automatically
// resolves URI-escaped entities.
var docHash = studio.hash.paramsToHash(studio.hash.hashToParams(
(document.location.href.match(/#.*/) || [''])[0]));
if (docHash != studio.hash.currentHash_) {
var newHash = docHash;
var newParams = studio.hash.hashToParams(newHash);
studio.hash.onHashParamsChanged_(newParams);
studio.hash.currentParams_ = newParams;
studio.hash.currentHash_ = newHash;
};
window.setTimeout(hashChecker_, 100);
}
window.setTimeout(hashChecker_, 0);
}
if (studio.hash.boundFormOldOnChange_ && studio.hash.boundForm_) {
studio.hash.boundForm_.onChange = studio.hash.boundFormOldOnChange_;
}
studio.hash.boundFormOldOnChange_ = form.onChange;
studio.hash.boundForm_ = form;
var formChangeTimeout = null;
studio.hash.boundForm_.onChange = function() {
if (formChangeTimeout) {
window.clearTimeout(formChangeTimeout);
}
formChangeTimeout = window.setTimeout(function() {
studio.hash.onFormChanged_();
}, 500);
(studio.hash.boundFormOldOnChange_ || function(){}).apply(form, arguments);
};
};
studio.hash.onHashParamsChanged_ = function(newParams) {
if (studio.hash.boundForm_) {
studio.hash.boundForm_.setValuesSerialized(newParams);
}
};
studio.hash.onFormChanged_ = function() {
if (studio.hash.boundForm_) {
// We set this to prevent feedback in the hash checker.
studio.hash.currentParams_ = studio.hash.boundForm_.getValuesSerialized();
studio.hash.currentHash_ = studio.hash.paramsToHash(
studio.hash.currentParams_);
document.location.hash = studio.hash.currentHash_;
}
};
studio.hash.hashToParams = function(hash) {
var params = {};
hash = hash.replace(/^[?#]/, '');
var pairs = hash.split('&');
for (var i = 0; i < pairs.length; i++) {
var parts = pairs[i].split('=', 2);
// Most of the time path == key, but for objects like a.b=1, we need to
// descend into the hierachy.
var path = parts[0] ? decodeURIComponent(parts[0]) : parts[0];
var val = parts[1] ? decodeURIComponent(parts[1]) : parts[1];
var pathArr = path.split('.');
var obj = params;
for (var j = 0; j < pathArr.length - 1; j++) {
obj[pathArr[j]] = obj[pathArr[j]] || {};
obj = obj[pathArr[j]];
}
var key = pathArr[pathArr.length - 1];
if (key in obj) {
// Handle array values.
if (obj[key] && obj[key].splice) {
obj[key].push(val);
} else {
obj[key] = [obj[key], val];
}
} else {
obj[key] = val;
}
}
return params;
};
studio.hash.paramsToHash = function(params, prefix) {
var hashArr = [];
var keyPath_ = function(k) {
return encodeURIComponent((prefix ? prefix + '.' : '') + k);
};
var pushKeyValue_ = function(k, v) {
if (v === false) v = 0;
if (v === true) v = 1;
hashArr.push(keyPath_(k) + '=' +
encodeURIComponent(v.toString()));
};
for (var key in params) {
var val = params[key];
if (val === undefined || val === null) {
continue;
}
if (typeof val == 'object') {
if (val.splice && val.length) {
// Arrays
for (var i = 0; i < val.length; i++) {
pushKeyValue_(key, val[i]);
}
} else {
// Objects
hashArr.push(studio.hash.paramsToHash(val, keyPath_(key)));
}
} else {
// All other values
pushKeyValue_(key, val);
}
}
return hashArr.join('&');
}; | 07pratik-androidui | asset-studio/src/js/src/studio/hash.js | JavaScript | asf20 | 4,556 |
/*
Copyright 2010 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.
*/
//#REQUIRE "includes.js"
//#REQUIRE "forms.js"
/**
* Represents a form field and its associated UI elements. This should be
* broken out into a more MVC-like architecture in the future.
*/
studio.forms.Field = Base.extend({
/**
* Instantiates a new field with the given ID and parameters.
* @constructor
*/
constructor: function(id, params) {
this.id_ = id;
this.params_ = params;
},
/**
* Sets the form owner of the field. Internally called by
* {@link studio.forms.Form}.
* @private
* @param {studio.forms.Form} form The owner form.
*/
setForm_: function(form) {
this.form_ = form;
},
/**
* Returns a complete ID.
* @type String
*/
getLongId: function() {
return this.form_.id_ + '-' + this.id_;
},
/**
* Returns the ID for the form's UI element (or container).
* @type String
*/
getHtmlId: function() {
return '_frm-' + this.getLongId();
},
/**
* Generates the UI elements for a form field container. Not very portable
* outside the Asset Studio UI. Intended to be overriden by descendents.
* @private
* @param {HTMLElement} container The destination element to contain the
* field.
*/
createUI: function(container) {
container = $(container);
return $('<div>')
.addClass('form-field-outer')
.append(
$('<label>')
.attr('for', this.getHtmlId())
.text(this.params_.title)
.append($('<div>')
.addClass('form-field-help-text')
.css('display', this.params_.helpText ? '' : 'none')
.html(this.params_.helpText))
)
.append(
$('<div>')
.addClass('form-field-container')
)
.appendTo(container);
}
});
studio.forms.TextField = studio.forms.Field.extend({
createUI: function(container) {
var fieldContainer = $('.form-field-container', this.base(container));
var me = this;
this.el_ = $('<input>')
.addClass('form-text ui-widget ui-widget-content ' +
'ui-autocomplete-input ui-corner-all')
.attr('type', 'text')
.val(this.getValue())
.bind('change', function() {
me.setValue($(this).val(), true);
})
.bind('keydown change', function() {
var inputEl = this;
var oldVal = me.getValue();
window.setTimeout(function() {
var newVal = $(inputEl).val();
if (oldVal != newVal) {
me.setValue(newVal, true);
}
}, 0);
})
.appendTo(fieldContainer);
},
getValue: function() {
var value = this.value_;
if (typeof value != 'string') {
value = this.params_.defaultValue || '';
}
return value;
},
setValue: function(val, pauseUi) {
this.value_ = val;
if (!pauseUi) {
$(this.el_).val(val);
}
this.form_.notifyChanged_(this);
},
serializeValue: function() {
return this.getValue();
},
deserializeValue: function(s) {
this.setValue(s);
}
});
studio.forms.AutocompleteTextField = studio.forms.Field.extend({
createUI: function(container) {
var fieldContainer = $('.form-field-container', this.base(container));
var me = this;
this.el_ = $('<input>')
.attr('type', 'text')
.val(this.getValue())
.bind('keydown change', function() {
var inputEl = this;
window.setTimeout(function() {
me.setValue($(inputEl).val(), true);
}, 0);
})
.appendTo(fieldContainer);
this.el_.autocompletewithbutton({
source: this.params_.items || [],
delay: 0,
minLength: 0,
selected: function(evt, val) {
me.setValue(val, true);
}
});
},
getValue: function() {
var value = this.value_;
if (typeof value != 'string') {
value = this.params_.defaultValue || '';
}
return value;
},
setValue: function(val, pauseUi) {
this.value_ = val;
if (!pauseUi) {
$(this.el_).val(val);
}
this.form_.notifyChanged_(this);
},
serializeValue: function() {
return this.getValue();
},
deserializeValue: function(s) {
this.setValue(s);
}
});
studio.forms.ColorField = studio.forms.Field.extend({
createUI: function(container) {
var fieldContainer = $('.form-field-container', this.base(container));
var me = this;
this.el_ = $('<div>')
.addClass('form-color')
.attr('id', this.getHtmlId())
.append($('<div>')
.addClass('form-color-preview')
.css('background-color', this.getValue().color)
)
.button({ label: null, icons: { secondary: 'ui-icon-carat-1-s' }})
.appendTo(fieldContainer);
this.el_.ColorPicker({
color: this.getValue().color,
onChange: function(hsb, hex, rgb) {
me.setValue({ color:'#' + hex }, true);
}
});
if (this.params_.alpha) {
this.alphaEl_ = $('<div>')
.addClass('form-color-alpha')
.slider({
min: 0,
max: 100,
range: 'min',
value: this.getValue().alpha,
slide: function(evt, ui) {
me.setValue({ alpha: ui.value }, true);
}
})
.appendTo(fieldContainer);
}
},
getValue: function() {
var color = this.value_ || this.params_.defaultValue || '#000000';
if (/^([0-9a-f]{6}|[0-9a-f]{3})$/i.test(color)) {
color = '#' + color;
}
var alpha = this.alpha_;
if (typeof alpha != 'number') {
alpha = this.params_.defaultAlpha;
if (typeof alpha != 'number')
alpha = 100;
}
return { color: color, alpha: alpha };
},
setValue: function(val, pauseUi) {
val = val || {};
if ('color' in val) {
this.value_ = val.color;
}
if ('alpha' in val) {
this.alpha_ = val.alpha;
}
var computedValue = this.getValue();
$('.form-color-preview', this.el_)
.css('background-color', computedValue.color);
if (!pauseUi) {
$(this.el_).ColorPickerSetColor(computedValue.color);
if (this.alphaEl_) {
$(this.alphaEl_).slider('value', computedValue.alpha);
}
}
this.form_.notifyChanged_(this);
},
serializeValue: function() {
var computedValue = this.getValue();
return computedValue.color.replace(/^#/, '') + ',' + computedValue.alpha;
},
deserializeValue: function(s) {
var val = {};
var arr = s.split(',', 2);
if (arr.length >= 1) {
val.color = arr[0];
}
if (arr.length >= 2) {
val.alpha = parseInt(arr[1], 10);
}
this.setValue(val);
}
});
studio.forms.EnumField = studio.forms.Field.extend({
createUI: function(container) {
var fieldContainer = $('.form-field-container', this.base(container));
var me = this;
if (this.params_.buttons) {
this.el_ = $('<div>')
.attr('id', this.getHtmlId())
.addClass('.form-field-buttonset')
.appendTo(fieldContainer);
for (var i = 0; i < this.params_.options.length; i++) {
var option = this.params_.options[i];
$('<input>')
.attr({
type: 'radio',
name: this.getHtmlId(),
id: this.getHtmlId() + '-' + option.id,
value: option.id
})
.change(function() {
me.setValueInternal_($(this).val(), true);
})
.appendTo(this.el_);
$('<label>')
.attr('for', this.getHtmlId() + '-' + option.id)
.html(option.title)
.appendTo(this.el_);
}
this.setValueInternal_(this.getValue());
this.el_.buttonset();
} else {
this.el_ = $('<select>')
.attr('id', this.getHtmlId())
.change(function() {
me.setValueInternal_($(this).val(), true);
})
.appendTo(fieldContainer);
for (var i = 0; i < this.params_.options.length; i++) {
var option = this.params_.options[i];
$('<option>')
.attr('value', option.id)
.text(option.title)
.appendTo(this.el_);
}
this.el_.combobox({
selected: function(evt, data) {
me.setValueInternal_(data.item.value, true);
me.form_.notifyChanged_(me);
}
});
this.setValueInternal_(this.getValue());
}
},
getValue: function() {
var value = this.value_;
if (value === undefined) {
value = this.params_.defaultValue || this.params_.options[0].id;
}
return value;
},
setValue: function(val, pauseUi) {
this.setValueInternal_(val, pauseUi);
},
setValueInternal_: function(val, pauseUi) {
// Note, this needs to be its own function because setValue gets
// overridden in BooleanField and we need access to this method
// from createUI.
this.value_ = val;
if (!pauseUi) {
if (this.params_.buttons) {
$('input', this.el_).each(function(i, el) {
$(el).attr('checked', $(el).val() == val);
});
$(this.el_).buttonset('refresh');
} else {
this.el_.val(val);
}
}
this.form_.notifyChanged_(this);
},
serializeValue: function() {
return this.getValue();
},
deserializeValue: function(s) {
this.setValue(s);
}
});
studio.forms.BooleanField = studio.forms.EnumField.extend({
constructor: function(id, params) {
params.options = [
{ id: '1', title: params.onText || 'Yes' },
{ id: '0', title: params.offText || 'No' }
];
params.defaultValue = params.defaultValue ? '1' : '0';
params.buttons = true;
this.base(id, params);
},
getValue: function() {
return this.base() == '1';
},
setValue: function(val, pauseUi) {
this.base(val ? '1' : '0', pauseUi);
},
serializeValue: function() {
return this.getValue() ? '1' : '0';
},
deserializeValue: function(s) {
this.setValue(s == '1');
}
});
studio.forms.RangeField = studio.forms.Field.extend({
createUI: function(container) {
var fieldContainer = $('.form-field-container', this.base(container));
var me = this;
this.el_ = $('<div>')
.addClass('form-range')
.slider({
min: this.params_.min || 0,
max: this.params_.max || 100,
step: this.params_.step || 1,
range: 'min',
value: this.getValue(),
slide: function(evt, ui) {
me.setValue(ui.value, true);
}
})
.appendTo(fieldContainer);
if (this.params_.textFn || this.params_.showText) {
this.params_.textFn = this.params_.textFn || function(d){ return d; };
this.textEl_ = $('<div>')
.addClass('form-range-text')
.text(this.params_.textFn(this.getValue()))
.appendTo(fieldContainer);
}
},
getValue: function() {
var value = this.value_;
if (typeof value != 'number') {
value = this.params_.defaultValue;
if (typeof value != 'number')
value = 0;
}
return value;
},
setValue: function(val, pauseUi) {
this.value_ = val;
if (!pauseUi) {
$(this.el_).slider('value', val);
}
if (this.textEl_) {
this.textEl_.text(this.params_.textFn(val));
}
this.form_.notifyChanged_(this);
},
serializeValue: function() {
return this.getValue().toString();
},
deserializeValue: function(s) {
this.setValue(Number(s)); // don't use parseInt nor parseFloat
}
});
| 07pratik-androidui | asset-studio/src/js/src/studio/fields.js | JavaScript | asf20 | 11,888 |
/*
Copyright 2010 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.
*/
studio.util = {};
studio.util.getMultBaseMdpi = function(density) {
switch (density) {
case 'xhdpi': return 2.00;
case 'hdpi': return 1.50;
case 'mdpi': return 1.00;
case 'ldpi': return 0.75;
}
return 1.0;
};
studio.util.mult = function(s, mult) {
var d = {};
for (k in s) {
d[k] = s[k] * mult;
}
return d;
};
studio.util.multRound = function(s, mult) {
var d = {};
for (k in s) {
d[k] = Math.round(s[k] * mult);
}
return d;
}; | 07pratik-androidui | asset-studio/src/js/src/studio/util.js | JavaScript | asf20 | 1,039 |
/*
Copyright 2010 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.
*/
window.studio = studio;
//#ECHO })();
| 07pratik-androidui | asset-studio/src/js/src/studio/_footer.js | JavaScript | asf20 | 599 |
/*
Copyright 2010 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.
*/
studio.ui = {};
studio.ui.createImageOutputGroup = function(params) {
return $('<div>')
.addClass('out-image-group')
.append($('<div>')
.addClass('label')
.text(params.label))
.appendTo(params.container);
};
studio.ui.createImageOutputSlot = function(params) {
return $('<div>')
.addClass('out-image-block')
.append($('<div>')
.addClass('label')
.text(params.label))
.append($('<img>')
.addClass('out-image')
.attr('id', params.id))
.appendTo(params.container);
};
studio.ui.drawImageGuideRects = function(ctx, size, guides) {
guides = guides || [];
ctx.save();
ctx.globalAlpha = 0.5;
ctx.fillStyle = '#fff';
ctx.fillRect(0, 0, size.w, size.h);
ctx.globalAlpha = 1.0;
var guideColors = studio.ui.drawImageGuideRects.guideColors_;
for (var i = 0; i < guides.length; i++) {
ctx.strokeStyle = guideColors[(i - 1) % guideColors.length];
ctx.strokeRect(guides[i].x + 0.5, guides[i].y + 0.5, guides[i].w - 1, guides[i].h - 1);
}
ctx.restore();
};
studio.ui.drawImageGuideRects.guideColors_ = [
'#f00'
];
| 07pratik-androidui | asset-studio/src/js/src/studio/ui.js | JavaScript | asf20 | 1,665 |
/*
Copyright 2010 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.
*/
studio.zip = {};
studio.zip.createDownloadifyZipButton = function(element, options) {
// TODO: badly needs to be documented :-)
var zipperHandle = {
fileSpecs_: []
};
options = options || {};
options.swf = options.swf || 'lib/downloadify/media/downloadify.swf';
options.downloadImage = options.downloadImage ||
'images/download-zip-button.png';
options.width = options.width || 133;
options.height = options.height || 30;
options.dataType = 'base64';
options.onError = options.onError || function() {
if (zipperHandle.fileSpecs_.length)
alert('There was an error downloading the .zip');
};
// Zip file data and filename generator functions.
options.filename = function() {
return zipperHandle.zipFilename_ || 'output.zip';
};
options.data = function() {
if (!zipperHandle.fileSpecs_.length)
return '';
var zip = new JSZip();
for (var i = 0; i < zipperHandle.fileSpecs_.length; i++) {
var fileSpec = zipperHandle.fileSpecs_[i];
if (fileSpec.base64data)
zip.add(fileSpec.name, fileSpec.base64data, {base64:true});
else if (fileSpec.textData)
zip.add(fileSpec.name, fileSpec.textData);
}
return zip.generate();
};
var downloadifyHandle;
if (window.Downloadify) {
downloadifyHandle = Downloadify.create($(element).get(0), options);
}
//downloadifyHandle.disable();
// Set up zipper control functions
zipperHandle.setZipFilename = function(zipFilename) {
zipperHandle.zipFilename_ = zipFilename;
};
zipperHandle.clear = function() {
zipperHandle.fileSpecs_ = [];
//downloadifyHandle.disable();
};
zipperHandle.add = function(spec) {
zipperHandle.fileSpecs_.push(spec);
//downloadifyHandle.enable();
};
return zipperHandle;
};
| 07pratik-androidui | asset-studio/src/js/src/studio/zip.js | JavaScript | asf20 | 2,353 |
/*
Copyright 2010 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.
*/
studio.forms = {};
/**
* Class defining a data entry form for use in the Asset Studio.
*/
studio.forms.Form = Base.extend({
/**
* Creates a new form with the given parameters.
* @constructor
* @param {Function} [params.onChange] A function
* @param {Array} [params.inputs] A list of inputs
*/
constructor: function(id, params) {
this.id_ = id;
this.params_ = params;
this.fields_ = params.fields;
this.pauseNotify_ = false;
for (var i = 0; i < this.fields_.length; i++) {
this.fields_[i].setForm_(this);
}
this.onChange = this.params_.onChange || function(){};
},
/**
* Creates the user interface for the form in the given container.
* @private
* @param {HTMLElement} container The container node for the form UI.
*/
createUI: function(container) {
for (var i = 0; i < this.fields_.length; i++) {
var field = this.fields_[i];
field.createUI(container);
}
},
/**
* Notifies that the form contents have changed;
* @private
*/
notifyChanged_: function(field) {
if (this.pauseNotify_) {
return;
}
this.onChange(field);
},
/**
* Returns the current values of the form fields, as an object.
* @type Object
*/
getValues: function() {
var values = {};
for (var i = 0; i < this.fields_.length; i++) {
var field = this.fields_[i];
values[field.id_] = field.getValue();
}
return values;
},
/**
* Returns all available serialized values of the form fields, as an object.
* All values in the returned object are either strings or objects.
* @type Object
*/
getValuesSerialized: function() {
var values = {};
for (var i = 0; i < this.fields_.length; i++) {
var field = this.fields_[i];
var value = field.serializeValue ? field.serializeValue() : undefined;
if (value !== undefined) {
values[field.id_] = field.serializeValue();
}
}
return values;
},
/**
* Sets the form field values for the key/value pairs in the given object.
* Values must be serialized forms of the form values. The form must be
* initialized before calling this method.
*/
setValuesSerialized: function(serializedValues) {
this.pauseNotify_ = true;
for (var i = 0; i < this.fields_.length; i++) {
var field = this.fields_[i];
if (field.id_ in serializedValues && field.deserializeValue) {
field.deserializeValue(serializedValues[field.id_]);
}
}
this.pauseNotify_ = false;
this.notifyChanged_(null);
}
}); | 07pratik-androidui | asset-studio/src/js/src/studio/forms.js | JavaScript | asf20 | 3,135 |
/*
Copyright 2010 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.
*/
//#INSERTFILE "../lib/base.js"
| 07pratik-androidui | asset-studio/src/js/src/globals.js | JavaScript | asf20 | 591 |
// A modified version of bitmap.js from http://rest-term.com/archives/2566/
var Class = {
create : function() {
var properties = arguments[0];
function self() {
this.initialize.apply(this, arguments);
}
for(var i in properties) {
self.prototype[i] = properties[i];
}
if(!self.prototype.initialize) {
self.prototype.initialize = function() {};
}
return self;
}
};
var ConvolutionFilter = Class.create({
initialize : function(matrix, divisor, bias, separable) {
this.r = (Math.sqrt(matrix.length) - 1) / 2;
this.matrix = matrix;
this.divisor = divisor;
this.bias = bias;
this.separable = separable;
},
apply : function(src, dst) {
var w = src.width, h = src.height;
var srcData = src.data;
var dstData = dst.data;
var di, si, idx;
var r, g, b;
//if (this.separable) {
// TODO: optimize if linearly separable ... may need changes to divisor
// and bias calculations
//} else {
// Not linearly separable
for(var y=0;y<h;++y) {
for(var x=0;x<w;++x) {
idx = r = g = b = 0;
di = (y*w + x) << 2;
for(var ky=-this.r;ky<=this.r;++ky) {
for(var kx=-this.r;kx<=this.r;++kx) {
si = (Math.max(0, Math.min(h - 1, y + ky)) * w +
Math.max(0, Math.min(w - 1, x + kx))) << 2;
r += srcData[si]*this.matrix[idx];
g += srcData[si + 1]*this.matrix[idx];
b += srcData[si + 2]*this.matrix[idx];
//a += srcData[si + 3]*this.matrix[idx];
idx++;
}
}
dstData[di] = r/this.divisor + this.bias;
dstData[di + 1] = g/this.divisor + this.bias;
dstData[di + 2] = b/this.divisor + this.bias;
//dstData[di + 3] = a/this.divisor + this.bias;
dstData[di + 3] = 255;
}
}
//}
// for Firefox
//dstData.forEach(function(n, i, arr) { arr[i] = n<0 ? 0 : n>255 ? 255 : n; });
}
}); | 07pratik-androidui | asset-studio/src/js/lib/filter.js | JavaScript | asf20 | 2,024 |
/*
Base.js, version 1.1
Copyright 2006-2007, Dean Edwards
License: http://www.opensource.org/licenses/mit-license.php
*/
var Base = function() {
// dummy
};
Base.extend = function(_instance, _static) { // subclass
var extend = Base.prototype.extend;
// build the prototype
Base._prototyping = true;
var proto = new this;
extend.call(proto, _instance);
delete Base._prototyping;
// create the wrapper for the constructor function
//var constructor = proto.constructor.valueOf(); //-dean
var constructor = proto.constructor;
var klass = proto.constructor = function() {
if (!Base._prototyping) {
if (this._constructing || this.constructor == klass) { // instantiation
this._constructing = true;
constructor.apply(this, arguments);
delete this._constructing;
} else if (arguments[0] != null) { // casting
return (arguments[0].extend || extend).call(arguments[0], proto);
}
}
};
// build the class interface
klass.ancestor = this;
klass.extend = this.extend;
klass.forEach = this.forEach;
klass.implement = this.implement;
klass.prototype = proto;
klass.toString = this.toString;
klass.valueOf = function(type) {
//return (type == "object") ? klass : constructor; //-dean
return (type == "object") ? klass : constructor.valueOf();
};
extend.call(klass, _static);
// class initialisation
if (typeof klass.init == "function") klass.init();
return klass;
};
Base.prototype = {
extend: function(source, value) {
if (arguments.length > 1) { // extending with a name/value pair
var ancestor = this[source];
if (ancestor && (typeof value == "function") && // overriding a method?
// the valueOf() comparison is to avoid circular references
(!ancestor.valueOf || ancestor.valueOf() != value.valueOf()) &&
/\bbase\b/.test(value)) {
// get the underlying method
var method = value.valueOf();
// override
value = function() {
var previous = this.base || Base.prototype.base;
this.base = ancestor;
var returnValue = method.apply(this, arguments);
this.base = previous;
return returnValue;
};
// point to the underlying method
value.valueOf = function(type) {
return (type == "object") ? value : method;
};
value.toString = Base.toString;
}
this[source] = value;
} else if (source) { // extending with an object literal
var extend = Base.prototype.extend;
// if this object has a customised extend method then use it
if (!Base._prototyping && typeof this != "function") {
extend = this.extend || extend;
}
var proto = {toSource: null};
// do the "toString" and other methods manually
var hidden = ["constructor", "toString", "valueOf"];
// if we are prototyping then include the constructor
var i = Base._prototyping ? 0 : 1;
while (key = hidden[i++]) {
if (source[key] != proto[key]) {
extend.call(this, key, source[key]);
}
}
// copy each of the source object's properties to this object
for (var key in source) {
if (!proto[key]) extend.call(this, key, source[key]);
}
}
return this;
},
base: function() {
// call this method from any other method to invoke that method's ancestor
}
};
// initialise
Base = Base.extend({
constructor: function() {
this.extend(arguments[0]);
}
}, {
ancestor: Object,
version: "1.1",
forEach: function(object, block, context) {
for (var key in object) {
if (this.prototype[key] === undefined) {
block.call(context, object[key], key, object);
}
}
},
implement: function() {
for (var i = 0; i < arguments.length; i++) {
if (typeof arguments[i] == "function") {
// if it's a function, call it
arguments[i](this.prototype);
} else {
// add the interface using the extend method
this.prototype.extend(arguments[i]);
}
}
return this;
},
toString: function() {
return String(this.valueOf());
}
}); | 07pratik-androidui | asset-studio/src/js/lib/base.js | JavaScript | asf20 | 3,914 |
/*
Copyright 2010 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.
*/
| 07pratik-androidui | asset-studio/src/js/lib/license-header.js | JavaScript | asf20 | 559 |
<html>
<head>
<!--
Copyright 2010 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.
-->
<title>asset-studio Test Runner</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" type="text/javascript"></script>
<script src="jsUnitCore.js" type="text/javascript"></script>
<script src="geoTestCore.js" type="text/javascript"></script>
<script src="geo.js" type="text/javascript"></script>
<script src="geo.tests.js" type="text/javascript"></script>
<link href="test-runner.css" rel="stylesheet" type="text/css"/>
<script src="test-runner.js" type="text/javascript"></script>
</head>
<body onload="init()">
<h1><code>asset-studio</code> Test Runner</h1>
<div id="run-buttons">
<input type="checkbox" id="passexceptions"/>
<label for="passexceptions">Debugging: Pass exceptions to browser?</label>
</div>
<table id="test-table">
<tr>
<th>#</th>
<th>Test Name</th>
<th>Status</th>
<th>Actions<br>
<input type="button" onclick="runTests(TESTS_ALL)" value="Run All Tests"/></th>
<th>Notes</th>
</tr>
</table>
</body>
</html>
| 07pratik-androidui | asset-studio/src/js/lib/test/test-runner.html | HTML | asf20 | 1,623 |
/*
Copyright 2010 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.
*/
var TESTS_INTERACTIVE = 0x01;
var TESTS_AUTOMATED = 0x02;
var TESTS_ALL = TESTS_INTERACTIVE | TESTS_AUTOMATED;
var g_tests = [];
var g_testsByName = {};
function init() {
discoverTests();
buildTestTable();
}
function discoverTests() {
g_testsByName = {};
if (navigator.userAgent.toLowerCase().indexOf('msie') >= 0) {
// IE doesn't support enumerating custom members of window
for (var i = 0; i < document.scripts.length; i++) {
var scriptNode = document.scripts[i];
var scriptBody = '';
if (scriptNode.innerHTML) {
scriptBody += scriptNode.innerHTML;
}
if (scriptNode.src) {
try {
var xhr = new ActiveXObject('Msxml2.XMLHTTP');
xhr.open('get', scriptNode.src, false); // false -- not async
xhr.send();
scriptBody += xhr.responseText;
} catch (e) {}
}
// parse script body for test_xx functions
var possibleTests = scriptBody.match(/test_\w+/g);
if (possibleTests) {
for (var j = 0; j < possibleTests.length; j++) {
if (possibleTests[j] in window &&
typeof window[possibleTests[j]] === 'function')
g_testsByName[possibleTests[j]] = true;
}
}
}
} else {
for (var f in window) {
if (f.substr(0, 5) == 'test_' &&
typeof window[f] === 'function')
g_testsByName[f] = true;
}
}
// convert into an array
g_tests = [];
for (var test in g_testsByName) {
g_tests.push(test);
}
g_tests.sort();
}
function buildTestTable() {
var testTable = jQuery('#test-table');
for (var i = 0; i < g_tests.length; i++) {
var row = jQuery('<tr id="testrow_' + g_tests[i] + '" "class="test">');
row.append(jQuery('<td class="test-number">' + (i + 1) + '</tr>'));
row.append(jQuery('<td class="test-name">' + g_tests[i] + '</td>'));
row.append(jQuery('<td class="test-status"> </td>'));
var runTestButton = jQuery('<input type="button" value="Run">')
.click(function(testName) {
return function() {
enableUI(false);
runSingleTest(testName, function() {
enableUI(true);
});
};
}(g_tests[i]));
row.append(jQuery('<td class="test-actions"></td>').append(runTestButton));
var notes = [];
if (window[g_tests[i]].interactive) notes.push('Interactive');
if (window[g_tests[i]].async) notes.push('Async');
row.append(jQuery('<td class="test-notes">' +
(notes.join(', ') || ' ') + '</td>'));
testTable.append(row);
}
}
function clearResults() {
jQuery('tr.test').removeClass('pass').removeClass('fail');
jQuery('.test-status').html(' ');
}
function isEmptyObjectLiteral(o) {
if (!o)
return true;
for (var k in o)
return false;
return true;
}
function logResult(testName, pass, message, otherInfo) {
var testRow = jQuery('#testrow_' + testName);
if (!testRow || !testRow.length)
return;
testRow.removeClass('pass').removeClass('fail');
testRow.addClass(pass ? 'pass' : 'fail');
var testStatusCell = jQuery('.test-status', testRow);
message = message ? message.toString() : (pass ? 'pass' : 'fail')
testStatusCell.text(message);
if (!isEmptyObjectLiteral(otherInfo)) {
testStatusCell.append(jQuery('<div><a href="#">[More Info]</a></div>')
.click(function() {
jQuery('.other-info', testStatusCell).toggle();
return false;
}));
var otherInfoHtml = ['<ul class="other-info" style="display: none">'];
for (var k in otherInfo) {
otherInfoHtml.push('<li><span>' + (k || ' ') + '</span>');
otherInfoHtml.push((otherInfo[k] || ' ') + '</li>');
}
otherInfoHtml.push('</ul>');
testStatusCell.append(jQuery(otherInfoHtml.join('')));
}
}
function enableUI(enable) {
if (enable)
jQuery('input').removeAttr('disabled');
else
jQuery('input').attr('disabled', true);
}
function runSingleTest(testName, completeFn) {
completeFn = completeFn || function(){};
var testFn = window[testName];
var successFn = function() {
// log result and run next test
logResult(testName, true);
completeFn();
};
var errorFn = function(e) {
var message = '';
var otherInfo = {};
if (e.jsUnitMessage) {
message = new String(e.jsUnitMessage);
} else if (e.message) {
message = new String(e.message);
} else if (e.comment) {
message = new String(e.comment);
} else if (e.description) {
message = new String(e.description);
}
// log result and run next test
for (var k in e) {
var val = e[k];
if (val === null)
val = '<null>';
else if (typeof(e[k]) == 'undefined')
val = '<undefined>';
val = val.toString();
if (k == 'stackTrace') {
var MAX_LENGTH = 500;
if (val.length >= MAX_LENGTH)
val = val.substr(0, MAX_LENGTH - 3) + '...';
}
otherInfo[k] = val;
}
logResult(testName, false, message, otherInfo);
completeFn();
};
var runFunc = function() {
if (testFn.interactive || testFn.async) {
testFn.call(null, successFn, errorFn);
} else {
testFn.call(null);
successFn();
}
};
var passExceptions = document.getElementById('passexceptions').checked;
if (passExceptions) {
runFunc.call();
} else {
try {
runFunc.call();
} catch (e) {
errorFn(e);
}
}
}
function runTests(type) {
if (!type)
type = TESTS_ALL;
enableUI(false);
clearResults();
var i = -1;
var runNextTest = function() {
i++;
if (i >= g_tests.length) {
enableUI(true);
return;
}
var testName = g_tests[i];
var testFn = window[testName];
if (testFn.interactive) {
if (!(type & TESTS_INTERACTIVE)) {
runNextTest();
return;
}
} else {
if (!(type & TESTS_AUTOMATED)) {
runNextTest();
return;
}
}
runSingleTest(testName, runNextTest);
}
runNextTest();
}
| 07pratik-androidui | asset-studio/src/js/lib/test/test-runner.js | JavaScript | asf20 | 6,968 |
/*
Copyright 2010 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.
*/
#test-table {
margin-top: 40px;
border: 0;
border-collapse: collapse;
border-spacing: 0;
padding: 0;
}
#test-table th,
#test-table td {
margin: 0;
padding: 3px 8px;
vertical-align: top;
font-family: helvetica, arial, sans-serif;
font-size: 10pt;
}
#test-table th {
border-bottom: 2px solid #000;
}
#test-table td {
border-bottom: 1px solid #888;
border-left: 1px dotted #ccc;
border-right: 1px dotted #ccc;
}
#test-table .test-number {
text-align: center;
}
#test-table .pass {
background-color: #cfc;
}
#test-table .fail {
background-color: #fcc;
}
.test-status {
width: 400px;
}
.test-status .other-info {
border: 1px solid #000;
background-color: #eee;
padding: 3px;
margin: 0;
list-style: none;
}
.test-status .other-info li {
padding: 0;
margin: 0;
list-style: none;
}
.test-status .other-info li {
color: #000;
margin-bottom: 5px;
}
.test-status .other-info li span {
color: #888;
font-weight: normal;
padding-right: 10px;
}
.test-status .other-info li span:after {
content: ':';
}
.pass td {
font-weight: bold;
color: #888;
}
.fail td {
font-weight: bold;
color: #f00;
} | 07pratik-androidui | asset-studio/src/js/lib/test/test-runner.css | CSS | asf20 | 1,723 |
<!DOCTYPE html>
<html>
<!--
Copyright 2010 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.
-->
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta http-equiv="X-UA-Compatible" content="chrome=1">
<title>Android Asset Studio - Icon Generator - Action bar icons (Android 3.0+)</title>
<link rel="stylesheet" href="lib/cssreset-3.4.1.min.css">
<link rel="stylesheet" href="lib/jquery-ui/css/android/jquery-ui-1.8.16.custom.css">
<link rel="stylesheet" href="css/studio.css">
<script src="lib/jquery-ui/js/jquery-1.6.2.min.js"></script>
<script src="lib/jquery-ui/js/jquery-ui-1.8.16.custom.min.js"></script>
<!-- canvg used to overcome <img src=SVG> toDataURL security issues -->
<!-- see code.google.com/p/chromium/issues/detail?id=54204 -->
<script src="lib/canvg/rgbcolor.js"></script>
<script src="lib/canvg/canvg.js"></script>
<!-- prereq. for asset studio lib -->
<link rel="stylesheet" href="lib/colorpicker/css/colorpicker.css">
<script src="lib/colorpicker/js/colorpicker.js"></script>
<!-- for .ZIP downloads -->
<script src="lib/swfobject-2.2.js"></script>
<script src="lib/downloadify/js/downloadify.min.js"></script>
<script src="lib/jszip/jszip.js"></script>
<script src="js/asset-studio.pack.js"></script>
<!-- TODO: remove Analytics tracking if you're building the tools locally! -->
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-18671401-1']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</head>
<body>
<div id="main-container">
<div id="header">
<h1><a href="index.html">Android Asset Studio</a></h1>
</div>
<div id="page-header">
<div id="breadcrumb">
<a href="index.html">Android Asset Studio</a> »
<a href="index.html#group-icon-generators">Icon generators</a> »
<em>Action bar icons (Android 3.0+)</em>
</div>
<p id="page-intro">
The <strong>action bar icon generator</strong> will create icons that you
can use in your Android application, from a variety of source images.
To begin, simply enter the input details below. Output will be shown
below.
</p>
</div>
<div id="inputs">
<div id="inputs-form"></div>
<!--
<input type="checkbox" id="output-try-system" checked="checked">
<label for="output-try-system">Use framework asset where possible</label>
-->
<input type="checkbox" id="output-show-guides">
<label for="output-show-guides">Show Guides</label>
<input type="checkbox" id="output-better-scaling">
<label for="output-better-scaling">Better Smoothing (slow)</label>
</div>
<div id="outputs">
<h3>
Output images
<div id="zip-button"></div>
</h3>
</div>
<div id="footer">
<p>See the source at the <a href="http://code.google.com/p/android-ui-utils">android-ui-utils</a> Google Code project.</p>
<p>All generated art is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by/3.0/">Creative Commons Attribution 3.0 Unported License</a>. <a href="attribution.html">Attribution info</a></p>
</div>
</div>
<script>
$(studio.checkBrowser);
$('#output-show-guides').button().click(regenerate);
$('#output-better-scaling').button().click(function() {
imagelib.ALLOW_MANUAL_RESCALE = $(this).is(':checked');
regenerate();
});
var zipper = studio.zip.createDownloadifyZipButton($('#zip-button'));
// $('#output-try-system')
// .button()
// .change(regenerate);
// Create image output slots
var group = studio.ui.createImageOutputGroup({
container: $('#outputs')
});
for (var density in {'xhdpi':1, 'hdpi':1, 'mdpi':1, 'ldpi':1})
studio.ui.createImageOutputSlot({
container: group,
id: 'out-icon-' + density,
label: density
});
var PARAM_RESOURCES = {
'mdpi-iconSize': { w: 24, h: 24 },
'mdpi-guideRect': { x: 0, y: 0, w: 24, h: 24 },
'mdpi-targetRect': { x: 0, y: 0, w: 24, h: 24 }
};
/**
* Main image generation routine.
*/
function regenerate() {
var values = form.getValues();
var sourceName = values['source'].name;
var showGuides = $('#output-show-guides').is(':checked');
var iconName = 'ic_action_' + values['name'];
zipper.clear();
zipper.setZipFilename(iconName + '.zip');
if (
false && // short circuit framework asset replacement while
// android.git.kernel.org gitweb image serving is broken
$('#output-try-system').is(':checked') &&
sourceName &&
sysReplacements.hasOwnProperty(sourceName)) {
var replacement = sysReplacements[sourceName];
$('#out-icon-hdpi').attr('src',
'http://android.git.kernel.org/?p=platform/frameworks/base.git;' +
'a=blob_plain;f=core/res/res/drawable-hdpi/ic_menu_' + replacement
+ '.png;hb=master');
$('#out-icon-mdpi').attr('src',
'http://android.git.kernel.org/?p=platform/frameworks/base.git;' +
'a=blob_plain;f=core/res/res/drawable-mdpi/ic_menu_' + replacement
+ '.png;hb=master');
$('#out-icon-ldpi').attr('src', '');
return;
}
if (!values['source'].ctx) {
return;
}
var srcCtx = values['source'].ctx;
var srcSize = { w: srcCtx.canvas.width, h: srcCtx.canvas.height };
var srcRect = { x: 0, y: 0, w: srcSize.w, h: srcSize.h };
for (var density in {'xhdpi':1, 'hdpi':1, 'mdpi':1, 'ldpi':1}) {
var mult = studio.util.getMultBaseMdpi(density);
var iconSize = studio.util.multRound(
PARAM_RESOURCES['mdpi-iconSize'], mult);
var guideRect = studio.util.multRound(
PARAM_RESOURCES['mdpi-guideRect'], mult);
var targetRect = studio.util.multRound(
PARAM_RESOURCES['mdpi-targetRect'], mult);
var outCtx = imagelib.drawing.context(iconSize);
var tmpCtx = imagelib.drawing.context(iconSize);
imagelib.drawing.drawCenterInside(tmpCtx, srcCtx, targetRect, srcRect);
if (values['theme'] == 'light') {
imagelib.drawing.fx([
{
effect: 'fill-color',
color: '#333333',
opacity: 0.6
}
], outCtx, tmpCtx, iconSize);
} else {
imagelib.drawing.fx([
{
effect: 'fill-color',
color: '#ffffff',
opacity: 0.8
}
], outCtx, tmpCtx, iconSize);
}
zipper.add({
name: 'res/drawable-' + density + '/' + iconName + '.png',
base64data: outCtx.canvas.toDataURL().match(/;base64,(.+)/)[1]
});
if (showGuides)
studio.ui.drawImageGuideRects(outCtx, iconSize, [
guideRect
]);
imagelib.loadFromUri(outCtx.canvas.toDataURL(), function(density) {
return function(img) {
$('#out-icon-' + density).attr('src', img.src);
};
}(density));
}
}
var form = new studio.forms.Form('iconform', {
onChange: regenerate,
fields: [
new studio.forms.ImageField('source', {
title: 'Source',
helpText: 'Must be alpha-transparent',
defaultValueTrim: 1
}),
new studio.forms.TextField('name', {
title: 'Icon name',
helpText: 'Used when generating ZIP files. Becomes <code>ic_action_<name></code>.',
defaultValue: 'example'
}),
new studio.forms.EnumField('theme', {
title: 'Theme',
buttons: true,
options: [
{ id: 'light', title: 'Holo Light' },
{ id: 'dark', title: 'Holo Dark' }
],
defaultValue: 'light'
})
]
});
form.createUI($('#inputs-form').get(0));
studio.hash.bindFormToDocumentHash(form);
</script>
</body>
</html> | 07pratik-androidui | asset-studio/src/html/icons-actionbar.html | HTML | asf20 | 9,358 |
<!DOCTYPE html>
<html>
<!--
Copyright 2010 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.
-->
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta http-equiv="X-UA-Compatible" content="chrome=1">
<title>Android Asset Studio</title>
<link rel="stylesheet" href="lib/cssreset-3.4.1.min.css">
<link rel="stylesheet" href="lib/jquery-ui/css/android/jquery-ui-1.8.16.custom.css">
<link rel="stylesheet" href="css/studio.css">
<!-- TODO: remove Analytics tracking if you're building the tools locally! -->
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-18671401-1']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</head>
<body>
<div id="main-container">
<div id="header">
<h1><a href="index.html">Android Asset Studio</a></h1>
</div>
<div id="page-links">
<h2 id="group-icon-generators">Icon generators <span>— Make icons for your app</span></h2>
<p>
Icon generators allow you to quickly and easily generate icons
from existing source images, clipart, or text.
</p>
<ul>
<li><a href="icons-launcher.html">Launcher icons</a></li>
<li><a href="icons-menu.html">Menu icons</a></li>
<li><a href="icons-actionbar.html">Action bar icons (Android 3.0+)</a></li>
<li><a href="icons-tab.html">Tab icons</a></li>
<li><a href="icons-notification.html">Notification icons</a></li>
</ul>
<h2 id="group-device-frames">Device frame generators <span>— Frame your screenshots inside device photos</span></h2>
<p>
Device frame generators allow you to quickly wrap your app screenshots in real device
artwork, providing better context for your screenshots.
</p>
<ul>
<li><a href="device-frames.html">Device frame generator</a></li>
</ul>
</div>
<div id="footer">
<p>See the source at the <a href="http://code.google.com/p/android-ui-utils">android-ui-utils</a> Google Code project.</p>
</div>
</div>
</body>
</html>
| 07pratik-androidui | asset-studio/src/html/index.html | HTML | asf20 | 3,050 |
<!DOCTYPE html>
<html>
<!--
Copyright 2010 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.
-->
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta http-equiv="X-UA-Compatible" content="chrome=1">
<title>Android Asset Studio - Icon Generator - Notification icons</title>
<link rel="stylesheet" href="lib/cssreset-3.4.1.min.css">
<link rel="stylesheet" href="lib/jquery-ui/css/android/jquery-ui-1.8.16.custom.css">
<link rel="stylesheet" href="css/studio.css">
<script src="lib/jquery-ui/js/jquery-1.6.2.min.js"></script>
<script src="lib/jquery-ui/js/jquery-ui-1.8.16.custom.min.js"></script>
<!-- canvg used to overcome <img src=SVG> toDataURL security issues -->
<!-- see code.google.com/p/chromium/issues/detail?id=54204 -->
<script src="lib/canvg/rgbcolor.js"></script>
<script src="lib/canvg/canvg.js"></script>
<!-- prereq. for asset studio lib -->
<link rel="stylesheet" href="lib/colorpicker/css/colorpicker.css">
<script src="lib/colorpicker/js/colorpicker.js"></script>
<!-- for .ZIP downloads -->
<script src="lib/swfobject-2.2.js"></script>
<script src="lib/downloadify/js/downloadify.min.js"></script>
<script src="lib/jszip/jszip.js"></script>
<script src="js/asset-studio.pack.js"></script>
<!-- TODO: remove Analytics tracking if you're building the tools locally! -->
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-18671401-1']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</head>
<body>
<div id="main-container">
<div id="header">
<h1><a href="index.html">Android Asset Studio</a></h1>
</div>
<div id="page-header">
<div id="breadcrumb">
<a href="index.html">Android Asset Studio</a> »
<a href="index.html#group-icon-generators">Icon generators</a> »
<em>Notification icons</em>
</div>
<p id="page-intro">
The <strong>notification icon generator</strong> will create icons that you
can use in your Android application, from a variety of source images.
To begin, simply enter the input details below. Output will be shown
below.
</p>
</div>
<div id="inputs">
<div id="inputs-form"></div>
<input type="checkbox" id="output-show-guides">
<label for="output-show-guides">Show Guides</label>
<input type="checkbox" id="output-better-scaling">
<label for="output-better-scaling">Better Image Smoothing (slow)</label>
</div>
<div id="outputs">
<h3>
Output images
<div id="zip-button"></div>
</h3>
</div>
<div id="footer">
<p>See the source at the <a href="http://code.google.com/p/android-ui-utils">android-ui-utils</a> Google Code project.</p>
<p>All generated art is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by/3.0/">Creative Commons Attribution 3.0 Unported License</a>. <a href="attribution.html">Attribution info</a></p>
</div>
</div>
<script>
$(studio.checkBrowser);
$('#output-show-guides').button().click(regenerate);
$('#output-better-scaling').button().click(function() {
imagelib.ALLOW_MANUAL_RESCALE = $(this).is(':checked');
regenerate();
});
var zipper = studio.zip.createDownloadifyZipButton($('#zip-button'));
// Create image output slots
for (var version in {'X':1, '11':1, '9':1}) {
var versionStr = (version == 'X') ? '' : ('-v' + version);
var group = studio.ui.createImageOutputGroup({
container: $('#outputs'),
label: ((version == 'X') ? 'Older versions' : 'API ' + version)
});
for (var density in {'xhdpi':1, 'hdpi':1, 'mdpi':1, 'ldpi':1})
studio.ui.createImageOutputSlot({
container: group,
id: 'out-icon-' + version + '-' + density,
label: density
});
}
// Load image resources (stencils)
var resList = {};
for (var version in {'X':1})
for (var shape in {'square':1, 'circle':1})
for (var density in {'xhdpi':1, 'hdpi':1, 'mdpi':1, 'ldpi':1})
resList[version + '-' + shape + '-' + density] = (
'res/notification-stencil/' + shape + '/' + density + '.png');
var IMAGE_RESOURCES = {};
imagelib.loadImageResources(resList, function(r) {
IMAGE_RESOURCES = r;
IMAGE_RESOURCES._loaded = true;
regenerate();
studio.hash.bindFormToDocumentHash(form);
});
var PARAM_RESOURCES = {
'X-mdpi-iconSize': { w: 25, h: 25 },
'X-square-mdpi-targetRect': { x: 4, y: 4, w: 17, h: 17 },
'X-circle-mdpi-targetRect': { x: 4, y: 4, w: 17, h: 17 },
'11-mdpi-iconSize': { w: 24, h: 24 },
'11-square-mdpi-targetRect': { x: 1, y: 1, w: 22, h: 22 },
'11-circle-mdpi-targetRect': { x: 1, y: 1, w: 22, h: 22 },
'9-mdpi-iconSize': { w: 16, h: 25 },
'9-square-mdpi-targetRect': { x: 0, y: 5, w: 16, h: 16 },
'9-circle-mdpi-targetRect': { x: 0, y: 5, w: 16, h: 16 }
};
/**
* Main image generation routine.
*/
function regenerate() {
if (!IMAGE_RESOURCES._loaded)
return;
var values = form.getValues();
var showGuides = $('#output-show-guides').is(':checked');
var iconName = 'ic_stat_' + values['name'];
zipper.clear();
zipper.setZipFilename(iconName + '.zip');
// TODO: just add support for required inputs
if (!values['source'].ctx) {
return;
}
var srcCtx = values['source'].ctx;
var srcSize = { w: srcCtx.canvas.width, h: srcCtx.canvas.height };
var srcRect = { x: 0, y: 0, w: srcSize.w, h: srcSize.h };
var shape = values['shape'];
for (var version in {'X':1, '11':1, '9':1}) {
for (var density in {'xhdpi':1, 'hdpi':1, 'mdpi':1, 'ldpi':1}) {
var versionStr = (version == 'X') ? '' : ('-v' + version);
var mult = studio.util.getMultBaseMdpi(density);
var iconSize = studio.util.multRound(
PARAM_RESOURCES[version + '-mdpi-iconSize'], mult);
var targetRect = studio.util.multRound(
PARAM_RESOURCES[version + '-' + shape + '-mdpi-targetRect'], mult);
var outCtx = imagelib.drawing.context(iconSize);
var tmpCtx = imagelib.drawing.context(iconSize);
if (version == 'X') {
tmpCtx.save();
imagelib.drawing.drawCenterInside(tmpCtx, srcCtx, targetRect, srcRect);
tmpCtx.globalCompositeOperation = 'source-atop';
tmpCtx.fillStyle = '#fff';
tmpCtx.fillRect(0, 0, iconSize.w, iconSize.h);
tmpCtx.restore();
imagelib.drawing.copy(outCtx, IMAGE_RESOURCES[version + '-' + shape + '-' + density], iconSize);
imagelib.drawing.copy(outCtx, tmpCtx, iconSize);
} else if (version == '11') {
imagelib.drawing.drawCenterInside(tmpCtx, srcCtx, targetRect, srcRect);
imagelib.drawing.fx([
{
effect: 'fill-color',
color: '#fff'
}
], outCtx, tmpCtx, iconSize);
} else if (version == '9') {
imagelib.drawing.drawCenterInside(tmpCtx, srcCtx, targetRect, srcRect);
imagelib.drawing.fx([
{
effect: 'inner-shadow',
color: '#fff',
opacity: 0.10,
translate: { y: 1 }
},
{
effect: 'fill-lineargradient',
from: { x: 0, y: 0 },
to: { x: 0, y: iconSize.h },
colors: [
{ offset: 0, color: '#919191' },
{ offset: 1.0, color: '#828282' }
]
}
], outCtx, tmpCtx, iconSize);
}
zipper.add({
name: 'res/drawable-' + density + versionStr + '/' + iconName + '.png',
base64data: outCtx.canvas.toDataURL().match(/;base64,(.+)/)[1]
});
if (showGuides)
studio.ui.drawImageGuideRects(outCtx, iconSize, [
targetRect
]);
imagelib.loadFromUri(outCtx.canvas.toDataURL(), function(version, density) {
return function(img) {
$('#out-icon-' + version + '-' + density).attr('src', img.src);
};
}(version, density));
}
}
}
var form = new studio.forms.Form('iconform', {
onChange: regenerate,
fields: [
new studio.forms.ImageField('source', {
title: 'Source',
helpText: 'Must be alpha-transparent',
defaultValueTrim: 1
}),
new studio.forms.EnumField('shape', {
title: 'Shape',
buttons: true,
options: [
{ id: 'square', title: 'Square' },
{ id: 'circle', title: 'Circle' }
],
defaultValue: 'square'
}),
new studio.forms.TextField('name', {
title: 'Icon name',
helpText: 'Used when generating ZIP files. Becomes <code>ic_stat_<name></code>.',
defaultValue: 'example'
})
]
});
form.createUI($('#inputs-form').get(0));
</script>
</body>
</html> | 07pratik-androidui | asset-studio/src/html/icons-notification.html | HTML | asf20 | 10,593 |
<!DOCTYPE html>
<html>
<!--
Copyright 2010 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.
-->
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta http-equiv="X-UA-Compatible" content="chrome=1">
<title>Android Asset Studio - Icon Generator - Launcher icons</title>
<link rel="stylesheet" href="lib/cssreset-3.4.1.min.css">
<link rel="stylesheet" href="lib/jquery-ui/css/android/jquery-ui-1.8.16.custom.css">
<link rel="stylesheet" href="css/studio.css">
<script src="lib/jquery-ui/js/jquery-1.6.2.min.js"></script>
<script src="lib/jquery-ui/js/jquery-ui-1.8.16.custom.min.js"></script>
<!-- canvg used to overcome <img src=SVG> toDataURL security issues -->
<!-- see code.google.com/p/chromium/issues/detail?id=54204 -->
<script src="lib/canvg/rgbcolor.js"></script>
<script src="lib/canvg/canvg.js"></script>
<!-- prereq. for asset studio lib -->
<link rel="stylesheet" href="lib/colorpicker/css/colorpicker.css">
<script src="lib/colorpicker/js/colorpicker.js"></script>
<!-- for .ZIP downloads -->
<script src="lib/swfobject-2.2.js"></script>
<script src="lib/downloadify/js/downloadify.min.js"></script>
<script src="lib/jszip/jszip.js"></script>
<script src="js/asset-studio.pack.js"></script>
<!-- TODO: remove Analytics tracking if you're building the tools locally! -->
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-18671401-1']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</head>
<body>
<div id="main-container">
<div id="header">
<h1><a href="index.html">Android Asset Studio</a></h1>
</div>
<div id="page-header">
<div id="breadcrumb">
<a href="index.html">Android Asset Studio</a> »
<a href="index.html#group-icon-generators">Icon generators</a> »
<em>Launcher icons</em>
</div>
<p id="page-intro">
The <strong>launcher icon generator</strong> will create icons that you
can use in your Android application, from a variety of source images.
To begin, simply enter the input details below. Output will be shown
below.
</p>
</div>
<div id="inputs">
<div id="inputs-form"></div>
<input type="checkbox" id="output-show-guides">
<label for="output-show-guides">Show Guides</label>
<input type="checkbox" id="output-better-scaling">
<label for="output-better-scaling">Better Image Smoothing (slow)</label>
</div>
<div id="outputs">
<h3>
Output images
<div id="zip-button"></div>
<div id="generate-web-button" style="vertical-align:top">Generate Web Icon</div>
</h3>
</div>
<div id="footer">
<p>See the source at the <a href="http://code.google.com/p/android-ui-utils">android-ui-utils</a> Google Code project.</p>
<p>All generated art is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by/3.0/">Creative Commons Attribution 3.0 Unported License</a>. <a href="attribution.html">Attribution info</a></p>
</div>
</div>
<script>
$(studio.checkBrowser);
$('#output-show-guides').button().click(regenerate);
$('#output-better-scaling').button().click(function() {
imagelib.ALLOW_MANUAL_RESCALE = $(this).is(':checked');
regenerate();
});
$('#generate-web-button').button().click(function() {
regenerate(true, true);
});
var zipper = studio.zip.createDownloadifyZipButton($('#zip-button'));
// Create image output slots
var group = studio.ui.createImageOutputGroup({
container: $('#outputs')
});
for (var density in {'xhdpi':1, 'hdpi':1, 'mdpi':1, 'ldpi':1, 'web':1})
studio.ui.createImageOutputSlot({
container: group,
id: 'out-icon-' + density,
label: (density == 'web') ? 'web, hi-res' : density
});
// Load image resources (stencils)
var resList = {};
for (var density in {'xhdpi':1, 'hdpi':1, 'mdpi':1, 'ldpi':1, 'web':1})
for (var backgroundShape in {'square':1, 'circle':1})
for (var type in {'back':1, 'fore1':1, 'mask':1})
resList[backgroundShape + '-' + density + '-' + type] = (
'res/launcher-stencil/' + backgroundShape + '/' + density + '/' + type + '.png');
var IMAGE_RESOURCES = {};
imagelib.loadImageResources(resList, function(r) {
IMAGE_RESOURCES = r;
IMAGE_RESOURCES._loaded = true;
regenerate();
studio.hash.bindFormToDocumentHash(form);
});
var PARAM_RESOURCES = {
'web-iconSize': { w: 512, h: 512 },
'xhdpi-iconSize': { w: 96, h: 96 },
'hdpi-iconSize': { w: 72, h: 72 },
'mdpi-iconSize': { w: 48, h: 48 },
'ldpi-iconSize': { w: 36, h: 36 },
'web-targetRect': { x: 21, y: 21, w: 470, h: 470 },
'xhdpi-targetRect': { x: 4, y: 4, w: 88, h: 88 },
'hdpi-targetRect': { x: 3, y: 3, w: 66, h: 66 },
'mdpi-targetRect': { x: 2, y: 2, w: 44, h: 44 },
'ldpi-targetRect': { x: 1, y: 1, w: 34, h: 34 }
};
/**
* Main image generation routine.
*/
function regenerate(force, generateWebIcon) {
if (!force) {
if (regenerate.timeout_) {
clearTimeout(regenerate.timeout_);
}
regenerate.timeout_ = setTimeout(function() {
regenerate(true);
}, 1000);
return;
}
if (!IMAGE_RESOURCES._loaded)
return;
var values = form.getValues();
var showGuides = $('#output-show-guides').is(':checked');
var iconName = 'ic_launcher';
zipper.clear();
zipper.setZipFilename(iconName + '.zip');
var continue_ = function(foreCtx) {
var backgroundShape = values['backgroundShape'];
for (var density in {'xhdpi':1, 'hdpi':1, 'mdpi':1, 'ldpi':1, 'web':1}) {
var mult = studio.util.getMultBaseMdpi(density);
if (density == 'web') {
mult = 1;
if (!generateWebIcon) {
continue;
}
}
var iconSize = PARAM_RESOURCES[density + '-iconSize'];
var targetRect = PARAM_RESOURCES[density + '-targetRect'];
var outCtx = imagelib.drawing.context(iconSize);
var tmpCtx = imagelib.drawing.context(iconSize);
if (backgroundShape == 'none') {
tmpCtx.save();
tmpCtx.globalCompositeOperation = 'source-over';
if (foreCtx) {
var copyFrom = foreCtx;
var foreSize = {
w: foreCtx.canvas.width,
h: foreCtx.canvas.height
};
if (values['foreColor'].alpha) {
var tmpCtx2 = imagelib.drawing.context(foreSize);
imagelib.drawing.copy(tmpCtx2, foreCtx, foreSize);
tmpCtx2.globalCompositeOperation = 'source-atop';
tmpCtx2.fillStyle = values['foreColor'].color;
tmpCtx2.fillRect(0, 0, foreSize.w, foreSize.h);
copyFrom = tmpCtx2;
tmpCtx.globalAlpha = values['foreColor'].alpha / 100;
}
imagelib.drawing[values['crop'] ? 'drawCenterCrop' : 'drawCenterInside']
(tmpCtx, copyFrom, targetRect, {
x: 0, y: 0,
w: foreSize.w, h: foreSize.h
});
}
tmpCtx.restore();
var foreEffect = 1; //values['foreEffect'];
if (density == 'web') {
imagelib.drawing.fx([
{
effect: 'inner-shadow',
color: '#fff',
opacity: 0.25,
blur: 0,
translate: { y: 5 }
},
{
effect: 'inner-shadow',
color: '#000',
opacity: 0.4,
blur: 5,
translate: { y: -5 }
},
{
effect: 'outer-shadow',
color: '#000',
opacity: 0.4,
blur: 8,
translate: { y: 3 }
}
], outCtx, tmpCtx, iconSize);
} else {
imagelib.drawing.fx([
{
effect: 'inner-shadow',
color: '#fff',
opacity: 0.25,
blur: 0,
translate: { y: Math.ceil(0.5 * mult) }
},
{
effect: 'inner-shadow',
color: '#000',
opacity: 0.6,
blur: Math.ceil(1 * mult),
translate: { y: -Math.ceil(0.5 * mult) }
},
{
effect: 'outer-shadow',
color: '#000',
opacity: 0.3,
blur: Math.ceil(2 * mult),
translate: { y: Math.ceil(0.5 * mult) }
}
], outCtx, tmpCtx, iconSize);
}
} else {
tmpCtx.save();
tmpCtx.globalCompositeOperation = 'source-over';
imagelib.drawing.copy(tmpCtx, IMAGE_RESOURCES[backgroundShape + '-' + density + '-mask'], iconSize);
tmpCtx.globalCompositeOperation = 'source-atop';
tmpCtx.fillStyle = values['backColor'].color;
tmpCtx.fillRect(0, 0, iconSize.w, iconSize.h);
if (foreCtx) {
var copyFrom = foreCtx;
var foreSize = {
w: foreCtx.canvas.width,
h: foreCtx.canvas.height
};
if (values['foreColor'].alpha) {
var tmpCtx2 = imagelib.drawing.context(foreSize);
imagelib.drawing.copy(tmpCtx2, foreCtx, foreSize);
tmpCtx2.globalCompositeOperation = 'source-atop';
tmpCtx2.fillStyle = values['foreColor'].color;
tmpCtx2.fillRect(0, 0, foreSize.w, foreSize.h);
copyFrom = tmpCtx2;
tmpCtx.globalAlpha = values['foreColor'].alpha / 100;
}
imagelib.drawing[values['crop'] ? 'drawCenterCrop' : 'drawCenterInside']
(tmpCtx, copyFrom, targetRect, {
x: 0, y: 0,
w: foreSize.w, h: foreSize.h
});
}
tmpCtx.restore();
var foreEffect = 1; //values['foreEffect'];
imagelib.drawing.copy(outCtx, IMAGE_RESOURCES[backgroundShape + '-' + density + '-back'], iconSize);
imagelib.drawing.copy(outCtx, tmpCtx, iconSize);
imagelib.drawing.copy(outCtx, IMAGE_RESOURCES[backgroundShape + '-' + density + '-fore' + foreEffect], iconSize);
}
zipper.add({
name: (density == 'web') ?
('web_hi_res_512.png') :
('res/drawable-' + density + '/ic_launcher.png'),
base64data: outCtx.canvas.toDataURL().match(/;base64,(.+)/)[1]
});
if (showGuides)
studio.ui.drawImageGuideRects(outCtx, iconSize, [
targetRect
]);
imagelib.loadFromUri(outCtx.canvas.toDataURL(), function(density) {
return function(img) {
$('#out-icon-' + density).attr('src', img.src);
};
}(density));
}
};
if (values['foreground']) {
continue_(values['foreground'].ctx);
} else {
continue_(null);
}
}
var form = new studio.forms.Form('iconform', {
onChange: function(field) {
regenerate();
},
fields: [
new studio.forms.ImageField('foreground', {
title: 'Foreground',
defaultValueTrim: 1
}),
new studio.forms.BooleanField('crop', {
title: 'Foreground scaling',
defaultValue: false,
offText: 'Center',
onText: 'Crop'
}),
new studio.forms.EnumField('backgroundShape', {
title: 'Background Shape',
buttons: true,
options: [
{ id: 'none', title: 'None' },
{ id: 'square', title: 'Square' },
{ id: 'circle', title: 'Circle' }
],
defaultValue: 'none'
}),
new studio.forms.ColorField('backColor', {
title: 'Background color',
defaultValue: '#ff0000'
}),
new studio.forms.ColorField('foreColor', {
title: 'Foreground color',
helpText: 'Only for alpha-transparent foregrounds',
defaultValue: '#000000',
alpha: true,
defaultAlpha: 0
})/*,
new studio.forms.EnumField('foreEffect', {
title: 'Foreground effects',
buttons: true,
options: [
{ id: '1', title: 'Simple' },
{ id: '2', title: 'Fancy' },
{ id: '3', title: 'Glossy' }
],
defaultValue: '1'
})*/
]
});
form.createUI($('#inputs-form').get(0));
</script>
</body>
</html>
| 07pratik-androidui | asset-studio/src/html/icons-launcher.html | HTML | asf20 | 14,665 |
<!DOCTYPE html>
<html>
<!--
Copyright 2011 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.
-->
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta http-equiv="X-UA-Compatible" content="chrome=1">
<title>Android Asset Studio - Nine-patch Generator</title>
<link rel="stylesheet" href="lib/cssreset-3.4.1.min.css">
<link rel="stylesheet" href="lib/jquery-ui/css/android/jquery-ui-1.8.16.custom.css">
<link rel="stylesheet" href="css/studio.css">
<script src="lib/jquery-ui/js/jquery-1.6.2.min.js"></script>
<script src="lib/jquery-ui/js/jquery-ui-1.8.16.custom.min.js"></script>
<!-- for .ZIP downloads -->
<script src="lib/swfobject-2.2.js"></script>
<script src="lib/downloadify/js/downloadify.min.js"></script>
<script src="lib/jszip/jszip.js"></script>
<script src="js/asset-studio.pack.js"></script>
<style>
#main-container {
width: 1000px;
}
#instage-container {
width: 100%;
display: box;
box-orient: horizontal;
box-pack: justify;
box-align: justify;
display: -webkit-box;
-webkit-box-orient: horizontal;
-webkit-box-pack: justify;
-webkit-box-align: justify;
display: -moz-box;
-moz-box-orient: horizontal;
-moz-box-pack: justify;
-moz-box-align: justify;
}
#inputs {
box-flex: 1;
-webkit-box-flex: 1;
-moz-box-flex: 1;
}
#stage {
padding: 24px;
border-left: 2px solid #ccc;
width: 500px;
background-color: #eee;
}
#stage-which,
#stage-grid-color {
display: inline-block;
}
#stage canvas {
margin: 16px 0 16px 0;
border: 1px solid #ccc;
image-rendering: optimizeSpeed;
image-rendering: -webkit-optimize-contrast;
image-rendering: -moz-crisp-edges;
-ms-interpolation-mode: nearest-neighbor;
}
</style>
<!-- TODO: remove Analytics tracking if you're building the tools locally! -->
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-18671401-1']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</head>
<body>
<div id="main-container">
<div id="header">
<h1><a href="index.html">Android Asset Studio</a></h1>
</div>
<div id="page-header">
<div id="breadcrumb">
<a href="index.html">Android Asset Studio</a> »
<a href="index.html#group-other-drawables">Other drawables</a> »
<em>Nine-patch generator</em>
</div>
<p id="page-intro">
The <strong>nine-patch generator</strong> allows you to quickly generate nine-patches
at different screen densities, based on some source artwork.
</p>
</div>
<div id="instage-container">
<div id="inputs">
<div id="inputs-form"></div>
</div>
<div id="stage">
<strong>Edit Mode </strong>
<div id="stage-which">
<input id="stage-stretch" name="stage-which" type="radio" value="stretch" checked><label for="stage-stretch">Stretch Regions</label>
<input id="stage-padding" name="stage-which" type="radio" value="padding"><label for="stage-padding">Content Padding</label>
</div>
<div id="stage-canvas-container">
<div class="ui-state-highlight" style="margin: 24px 0; padding: 12px">
Select a <strong>Source Graphic</strong> to the left to get started. You can also drag
a source image in from your desktop into the Source Graphic box.
</div>
</div>
<strong>Grid Color </strong>
<div id="stage-grid-color">
<input id="grid-light" name="stage-grid-color" type="radio" value="light" checked><label for="grid-light">Light</label>
<input id="grid-dark" name="stage-grid-color" type="radio" value="dark"><label for="grid-dark">Dark</label>
</div>
<div id="stage-examples-container">
<!--p><strong>Examples</strong></p-->
</div>
</div>
</div>
<div id="outputs">
<h3>Output images <div id="zip-button"></div></h3>
</div>
<div id="footer">
<p>See the source at the <a href="http://code.google.com/p/android-ui-utils">android-ui-utils</a> Google Code project.</p>
<p>All generated art is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by/3.0/">Creative Commons Attribution 3.0 Unported License</a>. <a href="attribution.html">Attribution info</a></p>
</div>
</div>
<script>
$(studio.checkBrowser);
var GRID_SIZE_PIXELS = 4;
var SLOP_PIXELS = 10;
var stage = {
zoom: 1,
gridColor: 'light',
editMode: 'stretch',
stretchRect: {
x: 0,
y: 0,
w: 0,
h: 0
},
contentRect: {
x: 0,
y: 0,
w: 0,
h: 0
}
};
// Stage code
$('#stage-which').buttonset();
$('#stage-which input').change(function() {
stage.editMode = $(this).val();
redrawStage();
});
$('#stage-grid-color').buttonset();
$('#stage-grid-color input').change(function() {
stage.gridColor = $(this).val();
redrawStage();
});
function resetStage(srcCtx) {
$('#stage-canvas-container').empty();
if (!srcCtx) {
return;
}
stage.srcCtx = srcCtx;
stage.srcSize = { w: stage.srcCtx.canvas.width, h: stage.srcCtx.canvas.height };
// Compute a zoom level that'll show the stage as large as possible
stage.zoom = Math.max(1, Math.floor(500 / Math.max(stage.srcSize.w, stage.srcSize.h)));
stage.size = {
w: stage.srcSize.w * stage.zoom,
h: stage.srcSize.h * stage.zoom
};
// Create a nearest-neighbor scaled-up copy of the source image for the stage
stage.previewCtx = imagelib.drawing.context(stage.size);
var srcData = stage.srcCtx.getImageData(0, 0, stage.srcSize.w, stage.srcSize.h);
var previewData = stage.previewCtx.createImageData(stage.size.w, stage.size.h);
var sx, sy;
for (var y = 0; y < stage.size.h; y++) {
for (var x = 0; x < stage.size.w; x++) {
sx = Math.floor(x * stage.srcSize.w / stage.size.w);
sy = Math.floor(y * stage.srcSize.h / stage.size.h);
previewData.data[(y * stage.size.w + x) * 4 + 0] =
srcData.data[(sy * stage.srcSize.w + sx) * 4 + 0];
previewData.data[(y * stage.size.w + x) * 4 + 1] =
srcData.data[(sy * stage.srcSize.w + sx) * 4 + 1];
previewData.data[(y * stage.size.w + x) * 4 + 2] =
srcData.data[(sy * stage.srcSize.w + sx) * 4 + 2];
previewData.data[(y * stage.size.w + x) * 4 + 3] =
srcData.data[(sy * stage.srcSize.w + sx) * 4 + 3];
}
}
stage.previewCtx.putImageData(previewData, 0, 0);
// Reset the stretch and padding/content regions
stage.stretchRect = {
x: Math.floor(stage.srcSize.w / 3),
y: Math.floor(stage.srcSize.h / 3),
w: Math.ceil(stage.srcSize.w / 3),
h: Math.ceil(stage.srcSize.h / 3)
};
stage.contentRect = { x: 0, y: 0, w: stage.srcSize.w, h: stage.srcSize.h };
// Create the stage canvas
stage.canvas = $('<canvas>')
.attr('width', stage.size.w)
.attr('height', stage.size.h)
.get(0);
$('#stage-canvas-container').append(stage.canvas);
// Set up events on the stage
$(stage.canvas)
.bind('mousedown', function(evt) {
stage.dragging = true;
})
.bind('mouseup', function(evt) {
stage.dragging = false;
})
.bind('mousemove', function(evt) {
var editRect = (stage.editMode == 'stretch') ? stage.stretchRect : stage.contentRect;
var offs = $(this).offset();
var offsetX = evt.pageX - offs.left;
var offsetY = evt.pageY - offs.top;
if (!stage.dragging) {
stage.editLeft = stage.editRight = stage.editTop = stage.editBottom = false;
if (offsetX >= editRect.x * stage.zoom - SLOP_PIXELS &&
offsetX <= editRect.x * stage.zoom + SLOP_PIXELS) {
stage.editLeft = true;
} else if (offsetX >= (editRect.x + editRect.w) * stage.zoom - SLOP_PIXELS &&
offsetX <= (editRect.x + editRect.w) * stage.zoom + SLOP_PIXELS) {
stage.editRight = true;
}
if (offsetY >= editRect.y * stage.zoom - SLOP_PIXELS &&
offsetY <= editRect.y * stage.zoom + SLOP_PIXELS) {
stage.editTop = true;
} else if (offsetY >= (editRect.y + editRect.h) * stage.zoom - SLOP_PIXELS &&
offsetY <= (editRect.y + editRect.h) * stage.zoom + SLOP_PIXELS) {
stage.editBottom = true;
}
var cursor = 'default';
if (stage.editLeft) {
if (stage.editTop) {
cursor = 'nw-resize';
} else if (stage.editBottom) {
cursor = 'sw-resize';
} else {
cursor = 'w-resize';
}
} else if (stage.editRight) {
if (stage.editTop) {
cursor = 'ne-resize';
} else if (stage.editBottom) {
cursor = 'se-resize';
} else {
cursor = 'e-resize';
}
} else if (stage.editTop) {
cursor = 'n-resize';
} else if (stage.editBottom) {
cursor = 's-resize';
}
$(stage.canvas).css('cursor', cursor);
} else {
if (stage.editLeft) {
var newX = Math.min(editRect.x + editRect.w - 1, Math.round(offsetX / stage.zoom));
editRect.w = editRect.w + editRect.x - newX;
editRect.x = newX;
}
if (stage.editTop) {
var newY = Math.min(editRect.y + editRect.h - 1, Math.round(offsetY / stage.zoom));
editRect.h = editRect.h + editRect.y - newY;
editRect.y = newY;
}
if (stage.editRight) {
editRect.w = Math.max(1, Math.round(offsetX / stage.zoom) - editRect.x);
}
if (stage.editBottom) {
editRect.h = Math.max(1, Math.round(offsetY / stage.zoom) - editRect.y);
}
redrawStage();
regenerate();
}
})
redrawStage();
regenerate();
}
function redrawStage() {
var editingStretch = (stage.editMode == 'stretch');
var editRect = (stage.editMode == 'stretch') ? stage.stretchRect : stage.contentRect;
var ctx = stage.canvas.getContext('2d');
ctx.clearRect(0, 0, stage.size.w, stage.size.h);
// draw grid
var cellSize = GRID_SIZE_PIXELS * stage.zoom;
var gridColorEven = (stage.gridColor == 'light') ? '#eee' : '#555';
var gridColorOdd = (stage.gridColor == 'light') ? '#ddd' : '#444';
for (var y = 0; y < stage.srcSize.h / GRID_SIZE_PIXELS; y++) {
for (var x = 0; x < stage.srcSize.w / GRID_SIZE_PIXELS; x++) {
ctx.fillStyle = ((x + y) % 2 == 0) ? gridColorEven : gridColorOdd;
ctx.fillRect(x * cellSize, y * cellSize, (x + 1) * cellSize, (y + 1) * cellSize);
}
}
// draw source graphic
ctx.drawImage(stage.previewCtx.canvas, 0, 0);
// draw current edit region
ctx.fillStyle = 'rgba(0,0,0,0.25)';
if (editingStretch) {
ctx.fillRect(0, editRect.y * stage.zoom,
stage.size.w, editRect.h * stage.zoom);
ctx.fillRect(editRect.x * stage.zoom, 0,
editRect.w * stage.zoom, stage.size.h);
}
ctx.fillRect(editRect.x * stage.zoom, editRect.y * stage.zoom,
editRect.w * stage.zoom, editRect.h * stage.zoom);
ctx.strokeStyle = 'rgba(255,255,255,0.5)';
ctx.lineWidth = 1;
if (editingStretch) {
ctx.strokeRect(0, 0.5 + editRect.y * stage.zoom,
stage.size.w, editRect.h * stage.zoom - 1);
ctx.strokeRect(0.5 + editRect.x * stage.zoom, 0,
editRect.w * stage.zoom - 1, stage.size.h);
}
ctx.strokeStyle = 'rgba(255,255,255,0.75)';
ctx.lineWidth = 1;
ctx.strokeRect(0.5 + editRect.x * stage.zoom, 0.5 + editRect.y * stage.zoom,
editRect.w * stage.zoom - 1, editRect.h * stage.zoom - 1);
}
// Generator
var zipper = studio.zip.createDownloadifyZipButton($('#zip-button'));
var group = studio.ui.createImageOutputGroup({ container: $('#outputs') });
for (var density in {'xhdpi':1, 'hdpi':1, 'mdpi':1, 'ldpi':1})
studio.ui.createImageOutputSlot({
container: group,
id: 'out-patch-' + density,
label: density
});
/**
* Main nine patch generation routine.
*/
function regenerate() {
if (!stage.srcCtx) {
return;
}
var values = form.getValues();
var resourceName = values['name'];
var sourceDensity = values['sourceDensity'];
zipper.clear();
zipper.setZipFilename(resourceName + '.9.zip');
for (var densityStr in {'xhdpi':1, 'hdpi':1, 'mdpi':1, 'ldpi':1}) {
var density;
switch (densityStr) {
case 'xhdpi': density = 320; break;
case 'hdpi': density = 240; break;
case 'mdpi': density = 160; break;
case 'ldpi': density = 120; break;
}
// scale source graphic
// TODO: support better-smoothing option
var scale = density / sourceDensity;
var outSize = {
w: Math.ceil(stage.srcSize.w * scale) + 2,
h: Math.ceil(stage.srcSize.h * scale) + 2
};
var outCtx = imagelib.drawing.context(outSize);
outCtx.drawImage(stage.srcCtx.canvas,
0, 0, stage.srcSize.w, stage.srcSize.h,
1, 1, outSize.w - 2, outSize.h - 2);
// draw nine-patch tick marks
outCtx.strokeStyle = '#000';
outCtx.lineWidth = 1;
outCtx.moveTo(1 + Math.floor(scale * stage.stretchRect.x), 0.5);
outCtx.lineTo(1 + Math.ceil(scale * (stage.stretchRect.x + stage.stretchRect.w)), 0.5);
outCtx.stroke();
outCtx.moveTo(0.5, 1 + Math.floor(scale * stage.stretchRect.y));
outCtx.lineTo(0.5, 1 + Math.ceil(scale * (stage.stretchRect.y + stage.stretchRect.h)));
outCtx.stroke();
outCtx.moveTo(1 + Math.floor(scale * stage.contentRect.x), outSize.h - 0.5);
outCtx.lineTo(1 + Math.ceil(scale * (stage.contentRect.x + stage.contentRect.w)), outSize.h - 0.5);
outCtx.stroke();
outCtx.moveTo(outSize.w - 0.5, 1 + Math.floor(scale * stage.contentRect.y));
outCtx.lineTo(outSize.w - 0.5, 1 + Math.ceil(scale * (stage.contentRect.y + stage.contentRect.h)));
outCtx.stroke();
// add to zip and show preview
zipper.add({
name: 'res/drawable-' + densityStr + '/' + resourceName + '.9.png',
base64data: outCtx.canvas.toDataURL().match(/;base64,(.+)/)[1]
});
imagelib.loadFromUri(outCtx.canvas.toDataURL(), function(densityStr) {
return function(img) {
$('#out-patch-' + densityStr).attr('src', img.src);
};
}(densityStr));
}
}
// Input form code
var form = new studio.forms.Form('ninepatchform', {
onChange: function(field) {
var values = form.getValues();
if (!field || field.id_ == 'source') {
if (values['source']) {
resetStage(values['source'].ctx);
} else {
resetStage(null);
}
} else {
regenerate();
}
},
fields: [
new studio.forms.ImageField('source', {
title: 'Source graphic',
imageOnly: true,
noTrimForm: true,
noPreview: true
}),
new studio.forms.EnumField('sourceDensity', {
title: 'Source density',
buttons: true,
options: [
{ id: '120', title: 'ldpi<br><small>(120)</small>' },
{ id: '160', title: 'mdpi<br><small>(160)</small>' },
{ id: '240', title: 'hdpi<br><small>(240)</small>' },
{ id: '320', title: 'xhdpi<br><small>(320)</small>' }
],
defaultValue: '320'
}),
new studio.forms.TextField('name', {
title: 'Drawable name',
helpText: 'Used when generating ZIP files. Becomes <code><name>.9.png</code>.',
defaultValue: 'example'
})
]
});
form.createUI($('#inputs-form').get(0));
</script>
</body>
</html>
| 07pratik-androidui | asset-studio/src/html/nine-patches.html | HTML | asf20 | 18,086 |
<!DOCTYPE html>
<html>
<!--
Copyright 2010 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.
-->
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta http-equiv="X-UA-Compatible" content="chrome=1">
<title>Android Asset Studio - Icon Generator - Menu icons</title>
<link rel="stylesheet" href="lib/cssreset-3.4.1.min.css">
<link rel="stylesheet" href="lib/jquery-ui/css/android/jquery-ui-1.8.16.custom.css">
<link rel="stylesheet" href="css/studio.css">
<script src="lib/jquery-ui/js/jquery-1.6.2.min.js"></script>
<script src="lib/jquery-ui/js/jquery-ui-1.8.16.custom.min.js"></script>
<!-- canvg used to overcome <img src=SVG> toDataURL security issues -->
<!-- see code.google.com/p/chromium/issues/detail?id=54204 -->
<script src="lib/canvg/rgbcolor.js"></script>
<script src="lib/canvg/canvg.js"></script>
<!-- prereq. for asset studio lib -->
<link rel="stylesheet" href="lib/colorpicker/css/colorpicker.css">
<script src="lib/colorpicker/js/colorpicker.js"></script>
<!-- for .ZIP downloads -->
<script src="lib/swfobject-2.2.js"></script>
<script src="lib/downloadify/js/downloadify.min.js"></script>
<script src="lib/jszip/jszip.js"></script>
<script src="js/asset-studio.pack.js"></script>
<!-- TODO: remove Analytics tracking if you're building the tools locally! -->
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-18671401-1']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</head>
<body>
<div id="main-container">
<div id="header">
<h1><a href="index.html">Android Asset Studio</a></h1>
</div>
<div id="page-header">
<div id="breadcrumb">
<a href="index.html">Android Asset Studio</a> »
<a href="index.html#group-icon-generators">Icon generators</a> »
<em>Menu icons</em>
</div>
<p id="page-intro">
The <strong>menu icon generator</strong> will create icons that you
can use in your Android application, from a variety of source images.
To begin, simply enter the input details below. Output will be shown
below.
</p>
</div>
<div id="inputs">
<div id="inputs-form"></div>
<!--
<input type="checkbox" id="output-try-system" checked="checked">
<label for="output-try-system">Use framework asset where possible</label>
-->
<input type="checkbox" id="output-show-guides">
<label for="output-show-guides">Show Guides</label>
<input type="checkbox" id="output-better-scaling">
<label for="output-better-scaling">Better Image Smoothing (slow)</label>
</div>
<div id="outputs">
<h3>
Output images
<div id="zip-button"></div>
</h3>
</div>
<div id="footer">
<p>See the source at the <a href="http://code.google.com/p/android-ui-utils">android-ui-utils</a> Google Code project.</p>
<p>All generated art is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by/3.0/">Creative Commons Attribution 3.0 Unported License</a>. <a href="attribution.html">Attribution info</a></p>
</div>
</div>
<script>
$(studio.checkBrowser);
$('#output-show-guides').button().click(regenerate);
$('#output-better-scaling').button().click(function() {
imagelib.ALLOW_MANUAL_RESCALE = $(this).is(':checked');
regenerate();
});
var zipper = studio.zip.createDownloadifyZipButton($('#zip-button'));
// $('#output-try-system')
// .button()
// .change(regenerate);
// Create image output slots
var group = studio.ui.createImageOutputGroup({
container: $('#outputs')
});
for (var density in {'xhdpi':1, 'hdpi':1, 'mdpi':1, 'ldpi':1})
studio.ui.createImageOutputSlot({
container: group,
id: 'out-icon-' + density,
label: density
});
var PARAM_RESOURCES = {
'mdpi-iconSize': { w: 48, h: 48 },
'mdpi-guideRect': { x: 8, y: 8, w: 32, h: 32 }, // 38 pre-Gingerbread
'mdpi-targetRect': { x: 8, y: 8, w: 32, h: 32 },
};
var sysReplacements = {
'add.svg': 'add',
'back.svg': 'back',
'block.svg': 'block',
'camera.svg': 'camera',
'edit.svg': 'edit',
'home.svg': 'home',
'mylocation.svg': 'mylocation',
'play_clip.svg': 'play_clip',
'refresh.svg': 'refresh',
'search.svg': 'search',
'share.svg': 'share',
'sort_by_size.svg': 'sort_by_size',
'star.svg': 'star',
'stop.svg': 'stop'
};
/**
* Main image generation routine.
*/
function regenerate() {
var values = form.getValues();
var sourceName = values['source'].name;
var showGuides = $('#output-show-guides').is(':checked');
var iconName = 'ic_menu_' + values['name'];
zipper.clear();
zipper.setZipFilename(iconName + '.zip');
if (
false && // short circuit framework asset replacement while
// android.git.kernel.org gitweb image serving is broken
$('#output-try-system').is(':checked') &&
sourceName &&
sysReplacements.hasOwnProperty(sourceName)) {
var replacement = sysReplacements[sourceName];
$('#out-icon-hdpi').attr('src',
'http://android.git.kernel.org/?p=platform/frameworks/base.git;' +
'a=blob_plain;f=core/res/res/drawable-hdpi/ic_menu_' + replacement
+ '.png;hb=master');
$('#out-icon-mdpi').attr('src',
'http://android.git.kernel.org/?p=platform/frameworks/base.git;' +
'a=blob_plain;f=core/res/res/drawable-mdpi/ic_menu_' + replacement
+ '.png;hb=master');
$('#out-icon-ldpi').attr('src', '');
return;
}
if (!values['source'].ctx) {
return;
}
var srcCtx = values['source'].ctx;
var srcSize = { w: srcCtx.canvas.width, h: srcCtx.canvas.height };
var srcRect = { x: 0, y: 0, w: srcSize.w, h: srcSize.h };
for (var density in {'xhdpi':1, 'hdpi':1, 'mdpi':1, 'ldpi':1}) {
var mult = studio.util.getMultBaseMdpi(density);
var iconSize = studio.util.multRound(
PARAM_RESOURCES['mdpi-iconSize'], mult);
var guideRect = studio.util.multRound(
PARAM_RESOURCES['mdpi-guideRect'], mult);
var targetRect = studio.util.multRound(
PARAM_RESOURCES['mdpi-targetRect'], mult);
var outCtx = imagelib.drawing.context(iconSize);
var tmpCtx = imagelib.drawing.context(iconSize);
imagelib.drawing.drawCenterInside(tmpCtx, srcCtx, targetRect, srcRect);
imagelib.drawing.fx([
{
effect: 'inner-shadow',
color: '#000',
opacity: 0.2,
blur: 3 * mult,
translate: { y: 3 * mult }
},
{
effect: 'inner-shadow',
color: '#000',
opacity: 0.35,
translate: { y: 1 }
},
{
effect: 'inner-shadow',
color: '#fff',
opacity: 0.35,
translate: { y: -1 }
},
{
effect: 'fill-lineargradient',
from: { x: 0, y: 0 },
to: { x: 0, y: iconSize.h },
colors: [
{ offset: 0, color: '#a3a3a3' },
{ offset: 1.0, color: '#787878' }
]
}
], outCtx, tmpCtx, iconSize);
var continue_ = function(outCtx) {
zipper.add({
name: 'res/drawable-' + density + '/' + iconName + '.png',
base64data: outCtx.canvas.toDataURL().match(/;base64,(.+)/)[1]
});
if (showGuides)
studio.ui.drawImageGuideRects(outCtx, iconSize, [
guideRect
]);
imagelib.loadFromUri(outCtx.canvas.toDataURL(), function(density) {
return function(img) {
$('#out-icon-' + density).attr('src', img.src);
};
}(density));
};
if (values['recenter'] != 'none') {
imagelib.drawing.getCenterOfMass(outCtx, iconSize, 1, function(massCenter) {
var recenteredOutCtx = imagelib.drawing.context(iconSize);
recenteredOutCtx.drawImage(outCtx.canvas, 0, 0, iconSize.w, iconSize.h,
(values['recenter'] == 'horz' || values['recenter'] == 'both')
? (iconSize.w / 2 - massCenter.x) : 0,
(values['recenter'] == 'vert' || values['recenter'] == 'both')
? (iconSize.h / 2 - massCenter.y) : 0,
iconSize.w, iconSize.h);
continue_(recenteredOutCtx);
});
} else {
continue_(outCtx);
}
}
}
var form = new studio.forms.Form('iconform', {
onChange: regenerate,
fields: [
new studio.forms.ImageField('source', {
title: 'Source',
helpText: 'Must be alpha-transparent',
defaultValueTrim: 1
}),
// new studio.forms.EnumField('recenter', {
// title: 'Recentering',
// helpText: 'Recenters the icon based on its mass',
// buttons: true,
// options: [
// { id: 'none', title: 'None' },
// { id: 'horz', title: 'Horizontal' },
// { id: 'vert', title: 'Vertical' },
// { id: 'both', title: 'Both' }
// ],
// defaultValue: 'none'
// }),
new studio.forms.TextField('name', {
title: 'Icon name',
helpText: 'Used when generating ZIP files. Becomes <code>ic_menu_<name></code>.',
defaultValue: 'example'
})
]
});
form.createUI($('#inputs-form').get(0));
studio.hash.bindFormToDocumentHash(form);
</script>
</body>
</html> | 07pratik-androidui | asset-studio/src/html/icons-menu.html | HTML | asf20 | 11,226 |
<!DOCTYPE html>
<html>
<!--
Copyright 2011 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.
-->
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta http-equiv="X-UA-Compatible" content="chrome=1">
<title>Android Asset Studio - Device Frame Generator</title>
<link rel="stylesheet" href="lib/cssreset-3.4.1.min.css">
<link rel="stylesheet" href="lib/jquery-ui/css/android/jquery-ui-1.8.16.custom.css">
<link rel="stylesheet" href="css/studio.css">
<script src="lib/jquery-ui/js/jquery-1.6.2.min.js"></script>
<script src="lib/jquery-ui/js/jquery-ui-1.8.16.custom.min.js"></script>
<script src="js/asset-studio.pack.js"></script>
<style>
#main-container {
width: 1000px;
}
#inout-container {
width: 100%;
display: box;
box-orient: horizontal;
box-pack: justify;
box-align: justify;
display: -webkit-box;
-webkit-box-orient: horizontal;
-webkit-box-pack: justify;
-webkit-box-align: justify;
display: -moz-box;
-moz-box-orient: horizontal;
-moz-box-pack: justify;
-moz-box-align: justify;
}
#inputs {
box-flex: 1;
-webkit-box-flex: 1;
-moz-box-flex: 1;
}
#device-list li {
display: inline-block;
vertical-align: top;
background: #eee;
padding: 8px;
margin: 0 16px 16px 0;
text-align: center;
border: 1px dashed rgba(0,0,0,0.4);
}
#device-list li img {
opacity: 0.5;
}
#device-list li.drag-hover {
background: #fff;
box-shadow: 0 0 40px #a4c639;
}
#device-list li.drag-hover img {
opacity: 1;
}
#outputs {
width: 400px;
}
#outputs img {
width: 400px;
}
</style>
<!-- TODO: remove Analytics tracking if you're building the tools locally! -->
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-18671401-1']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</head>
<body>
<div id="main-container">
<div id="header">
<h1><a href="index.html">Android Asset Studio</a></h1>
</div>
<div id="page-header">
<div id="breadcrumb">
<a href="index.html">Android Asset Studio</a> »
<a href="index.html#group-device-frames">Device frame generators</a> »
<em>Device frame generator</em>
</div>
<p id="page-intro">
The <strong>Device frame generator</strong> allows you to quickly wrap your app
screenshots in real device artwork, providing better context for your screenshots.
</p>
</div>
<div id="inout-container">
<div id="inputs">
<h3>1. Choose a device: <small style="font-weight:normal">(Drag a screenshot from your desktop onto a device.)</small></h3>
<p></p>
<ul id="device-list"></ul>
<p><strong>Attention, Device Manufacturers! </strong> To get your device(s) listed here,
please <a href="http://code.google.com/p/android-ui-utils/issues/entry?template=Feature%20request">
file a feature request</a>, and include hi-res, transparent or on-white photos of your device.</p>
</div>
<div id="outputs">
<h3>2. Save your output <small style="font-weight:normal">(Drag out to your desktop to save.)</small></h3>
<div id="output">No input image.</div>
</div>
</div>
<div id="footer">
<p>See the source at the <a href="http://code.google.com/p/android-ui-utils">android-ui-utils</a> Google Code project.</p>
<p>All generated art is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by/3.0/">Creative Commons Attribution 3.0 Unported License</a>. <a href="attribution.html">Attribution info</a></p>
</div>
</div>
<script>
$(studio.checkBrowser);
$.event.props.push("dataTransfer");
var DEVICES = [
{
id: 'nexus_one',
title: 'Nexus One',
url: 'http://www.google.com/phone/detail/nexus-one',
landRes: ['back'],
landOffset: [200,130],
portRes: ['back'],
portOffset: [141,191],
portSize: [480,800],
},
{
id: 'nexus_s',
title: 'Nexus S',
url: 'http://www.google.com/phone/detail/nexus-s',
landRes: ['back', 'fore'],
landOffset: [247,135],
portRes: ['back', 'fore'],
portOffset: [134,247],
portSize: [480,800],
},
{
id: 'galaxy_nexus',
title: 'Galaxy Nexus',
landRes: ['back', 'fore'],
landOffset: [371,199],
portRes: ['back', 'fore'],
portOffset: [216,353],
portSize: [720,1280],
},
{
id: 'xoom',
title: 'Motorola XOOM',
url: 'http://www.google.com/phone/detail/motorola-xoom',
landRes: ['back'],
landOffset: [218,191],
portRes: ['back'],
portOffset: [199,200],
portSize: [800,1280],
}
];
function getDeviceById(id) {
for (var i = 0; i < DEVICES.length; i++) {
if (DEVICES[i].id == id)
return DEVICES[i];
}
return;
}
$.each(DEVICES, function() {
$('<li>')
.append($('<img>')
.attr('src', 'res/device-frames/' + this.id + '/thumb.png'))
.append($('<div>')
.html('<strong>' +
(this.url ?
('<a href="' + this.url + '">' + this.title + '</a>') :
this.title) +
'</strong><br>' + this.portSize[0] + 'x' + this.portSize[1]))
.data('deviceId', this.id)
.appendTo('#device-list');
});
$('#device-list li')
.live('dragover', function(evt) {
$(this).addClass('drag-hover');
evt.dataTransfer.dropEffect = 'link';
evt.preventDefault();
})
.live('dragleave', function(evt) {
$(this).removeClass('drag-hover');
})
.live('drop', function(evt) {
$('#output').empty().text('Loading...');
$(this).removeClass('drag-hover');
var device = getDeviceById($(this).closest('li').data('deviceId'));
evt.preventDefault();
studio.forms.ImageField.loadImageFromFileList(evt.dataTransfer.files, function(data) {
if (data == null) {
$('#output').text('Invalid input image.');
return;
}
imagelib.loadFromUri(data.uri, function(img) {
createFrame(device, img);
});
});
});
function createFrame(device, screenshot) {
var port;
if (screenshot.naturalWidth == device.portSize[0] &&
screenshot.naturalHeight == device.portSize[1]) {
if (!device.portRes) {
alert('We don\'t have a portrait frame for this device yet.');
$('#output').text('No input image.');
return;
}
port = true;
} else if (screenshot.naturalWidth == device.portSize[1] &&
screenshot.naturalHeight == device.portSize[0]) {
if (!device.landRes) {
alert('We don\'t have a landscape frame for this device yet.');
$('#output').text('No input image.');
return;
}
port = false;
} else {
alert('The screenshot must be ' +
device.portSize[0] + 'x' + device.portSize[1] +
' or ' +
device.portSize[1] + 'x' + device.portSize[0]);
$('#output').text('Invalid input image.');
return;
}
// Load image resources
var res = port ? device.portRes : device.landRes;
var resList = {};
for (var i = 0; i < res.length; i++) {
resList[res[i]] = 'res/device-frames/' + device.id + '/' +
(port ? 'port_' : 'land_') + res[i] + '.png'
}
var resourceImages = {};
imagelib.loadImageResources(resList, function(r) {
resourceImages = r;
continuation_();
});
function continuation_() {
var width = resourceImages['back'].naturalWidth;
var height = resourceImages['back'].naturalHeight;
var offset = port ? device.portOffset : device.landOffset;
var canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext('2d');
ctx.drawImage(resourceImages['back'], 0, 0);
ctx.drawImage(screenshot, offset[0], offset[1]);
if (resourceImages['fore']) {
ctx.drawImage(resourceImages['fore'], 0, 0);
}
$('<img>')
.attr('src', canvas.toDataURL())
.appendTo($('#output').empty());
}
}
</script>
</body>
</html>
| 07pratik-androidui | asset-studio/src/html/device-frames.html | HTML | asf20 | 10,151 |
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta http-equiv="X-UA-Compatible" content="chrome=1">
<title>Android Asset Studio - Icon Generator - Launcher icons</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.4/jquery-ui.min.js"></script>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.4/themes/base/jquery.ui.all.css">
<script src="lib/canvg/rgbcolor.js"></script>
<script src="lib/canvg/canvg.js"></script>
<script src="js/asset-studio.pack.js"></script>
</head>
<body style="background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAAACXBIWXMAAAsTAAALEwEAmpwYAAAKT2lDQ1BQaG90b3Nob3AgSUNDIHByb2ZpbGUAAHjanVNnVFPpFj333vRCS4iAlEtvUhUIIFJCi4AUkSYqIQkQSoghodkVUcERRUUEG8igiAOOjoCMFVEsDIoK2AfkIaKOg6OIisr74Xuja9a89+bN/rXXPues852zzwfACAyWSDNRNYAMqUIeEeCDx8TG4eQuQIEKJHAAEAizZCFz/SMBAPh+PDwrIsAHvgABeNMLCADATZvAMByH/w/qQplcAYCEAcB0kThLCIAUAEB6jkKmAEBGAYCdmCZTAKAEAGDLY2LjAFAtAGAnf+bTAICd+Jl7AQBblCEVAaCRACATZYhEAGg7AKzPVopFAFgwABRmS8Q5ANgtADBJV2ZIALC3AMDOEAuyAAgMADBRiIUpAAR7AGDIIyN4AISZABRG8lc88SuuEOcqAAB4mbI8uSQ5RYFbCC1xB1dXLh4ozkkXKxQ2YQJhmkAuwnmZGTKBNA/g88wAAKCRFRHgg/P9eM4Ors7ONo62Dl8t6r8G/yJiYuP+5c+rcEAAAOF0ftH+LC+zGoA7BoBt/qIl7gRoXgugdfeLZrIPQLUAoOnaV/Nw+H48PEWhkLnZ2eXk5NhKxEJbYcpXff5nwl/AV/1s+X48/Pf14L7iJIEyXYFHBPjgwsz0TKUcz5IJhGLc5o9H/LcL//wd0yLESWK5WCoU41EScY5EmozzMqUiiUKSKcUl0v9k4t8s+wM+3zUAsGo+AXuRLahdYwP2SycQWHTA4vcAAPK7b8HUKAgDgGiD4c93/+8//UegJQCAZkmScQAAXkQkLlTKsz/HCAAARKCBKrBBG/TBGCzABhzBBdzBC/xgNoRCJMTCQhBCCmSAHHJgKayCQiiGzbAdKmAv1EAdNMBRaIaTcA4uwlW4Dj1wD/phCJ7BKLyBCQRByAgTYSHaiAFiilgjjggXmYX4IcFIBBKLJCDJiBRRIkuRNUgxUopUIFVIHfI9cgI5h1xGupE7yAAygvyGvEcxlIGyUT3UDLVDuag3GoRGogvQZHQxmo8WoJvQcrQaPYw2oefQq2gP2o8+Q8cwwOgYBzPEbDAuxsNCsTgsCZNjy7EirAyrxhqwVqwDu4n1Y8+xdwQSgUXACTYEd0IgYR5BSFhMWE7YSKggHCQ0EdoJNwkDhFHCJyKTqEu0JroR+cQYYjIxh1hILCPWEo8TLxB7iEPENyQSiUMyJ7mQAkmxpFTSEtJG0m5SI+ksqZs0SBojk8naZGuyBzmULCAryIXkneTD5DPkG+Qh8lsKnWJAcaT4U+IoUspqShnlEOU05QZlmDJBVaOaUt2ooVQRNY9aQq2htlKvUYeoEzR1mjnNgxZJS6WtopXTGmgXaPdpr+h0uhHdlR5Ol9BX0svpR+iX6AP0dwwNhhWDx4hnKBmbGAcYZxl3GK+YTKYZ04sZx1QwNzHrmOeZD5lvVVgqtip8FZHKCpVKlSaVGyovVKmqpqreqgtV81XLVI+pXlN9rkZVM1PjqQnUlqtVqp1Q61MbU2epO6iHqmeob1Q/pH5Z/YkGWcNMw09DpFGgsV/jvMYgC2MZs3gsIWsNq4Z1gTXEJrHN2Xx2KruY/R27iz2qqaE5QzNKM1ezUvOUZj8H45hx+Jx0TgnnKKeX836K3hTvKeIpG6Y0TLkxZVxrqpaXllirSKtRq0frvTau7aedpr1Fu1n7gQ5Bx0onXCdHZ4/OBZ3nU9lT3acKpxZNPTr1ri6qa6UbobtEd79up+6Ynr5egJ5Mb6feeb3n+hx9L/1U/W36p/VHDFgGswwkBtsMzhg8xTVxbzwdL8fb8VFDXcNAQ6VhlWGX4YSRudE8o9VGjUYPjGnGXOMk423GbcajJgYmISZLTepN7ppSTbmmKaY7TDtMx83MzaLN1pk1mz0x1zLnm+eb15vft2BaeFostqi2uGVJsuRaplnutrxuhVo5WaVYVVpds0atna0l1rutu6cRp7lOk06rntZnw7Dxtsm2qbcZsOXYBtuutm22fWFnYhdnt8Wuw+6TvZN9un2N/T0HDYfZDqsdWh1+c7RyFDpWOt6azpzuP33F9JbpL2dYzxDP2DPjthPLKcRpnVOb00dnF2e5c4PziIuJS4LLLpc+Lpsbxt3IveRKdPVxXeF60vWdm7Obwu2o26/uNu5p7ofcn8w0nymeWTNz0MPIQ+BR5dE/C5+VMGvfrH5PQ0+BZ7XnIy9jL5FXrdewt6V3qvdh7xc+9j5yn+M+4zw33jLeWV/MN8C3yLfLT8Nvnl+F30N/I/9k/3r/0QCngCUBZwOJgUGBWwL7+Hp8Ib+OPzrbZfay2e1BjKC5QRVBj4KtguXBrSFoyOyQrSH355jOkc5pDoVQfujW0Adh5mGLw34MJ4WHhVeGP45wiFga0TGXNXfR3ENz30T6RJZE3ptnMU85ry1KNSo+qi5qPNo3ujS6P8YuZlnM1VidWElsSxw5LiquNm5svt/87fOH4p3iC+N7F5gvyF1weaHOwvSFpxapLhIsOpZATIhOOJTwQRAqqBaMJfITdyWOCnnCHcJnIi/RNtGI2ENcKh5O8kgqTXqS7JG8NXkkxTOlLOW5hCepkLxMDUzdmzqeFpp2IG0yPTq9MYOSkZBxQqohTZO2Z+pn5mZ2y6xlhbL+xW6Lty8elQfJa7OQrAVZLQq2QqboVFoo1yoHsmdlV2a/zYnKOZarnivN7cyzytuQN5zvn//tEsIS4ZK2pYZLVy0dWOa9rGo5sjxxedsK4xUFK4ZWBqw8uIq2Km3VT6vtV5eufr0mek1rgV7ByoLBtQFr6wtVCuWFfevc1+1dT1gvWd+1YfqGnRs+FYmKrhTbF5cVf9go3HjlG4dvyr+Z3JS0qavEuWTPZtJm6ebeLZ5bDpaql+aXDm4N2dq0Dd9WtO319kXbL5fNKNu7g7ZDuaO/PLi8ZafJzs07P1SkVPRU+lQ27tLdtWHX+G7R7ht7vPY07NXbW7z3/T7JvttVAVVN1WbVZftJ+7P3P66Jqun4lvttXa1ObXHtxwPSA/0HIw6217nU1R3SPVRSj9Yr60cOxx++/p3vdy0NNg1VjZzG4iNwRHnk6fcJ3/ceDTradox7rOEH0x92HWcdL2pCmvKaRptTmvtbYlu6T8w+0dbq3nr8R9sfD5w0PFl5SvNUyWna6YLTk2fyz4ydlZ19fi753GDborZ752PO32oPb++6EHTh0kX/i+c7vDvOXPK4dPKy2+UTV7hXmq86X23qdOo8/pPTT8e7nLuarrlca7nuer21e2b36RueN87d9L158Rb/1tWeOT3dvfN6b/fF9/XfFt1+cif9zsu72Xcn7q28T7xf9EDtQdlD3YfVP1v+3Njv3H9qwHeg89HcR/cGhYPP/pH1jw9DBY+Zj8uGDYbrnjg+OTniP3L96fynQ89kzyaeF/6i/suuFxYvfvjV69fO0ZjRoZfyl5O/bXyl/erA6xmv28bCxh6+yXgzMV70VvvtwXfcdx3vo98PT+R8IH8o/2j5sfVT0Kf7kxmTk/8EA5jz/GMzLdsAAAAgY0hSTQAAeiUAAICDAAD5/wAAgOkAAHUwAADqYAAAOpgAABdvkl/FRgAAADJJREFUeNpi/P///38GPODy5cv4pBmYGCgEowYMBgNYCMWzrq7uaCAOfwMAAAAA//8DACloCZduMbIUAAAAAElFTkSuQmCC)">
<input id="in" value="a">
<div id="output"></div>
<div id="status"></div>
<button>Redraw</button>
<script>
$('button').live('click', redraw);
$('input').live('change, keyup', redraw);
$(redraw);
var SZ = 512;
function redraw2() {
var startTime = new Date();
var size = { w: SZ, h: SZ };
var tmpCtx = imagelib.drawing.context(size);
var outCtx = imagelib.drawing.context(size);
tmpCtx.font = 'bold 880px Helvetica';
tmpCtx.textAlign = 'center';
tmpCtx.textBaseline = 'baseline';
var lingrad2 = tmpCtx.createLinearGradient(0,0,0,SZ);
lingrad2.addColorStop(0, 'red');
lingrad2.addColorStop(1, 'blue');
tmpCtx.fillStyle = lingrad2;
tmpCtx.fillText($('#in').val(), SZ / 2, 490 * SZ / 512);
imagelib.drawing.blur(15 * SZ / 512, tmpCtx, size);
imagelib.drawing.copy(outCtx, tmpCtx, size);
outCtx.save();
outCtx.globalCompositeOperation = 'source-atop';
outCtx.fillStyle = 'red';
outCtx.fillRect(0, 0, SZ / 2, SZ);
outCtx.restore();
//imagelib.drawing.copyAsAlpha(outCtx, tmpCtx, size, '#fff', '#000');
//imagelib.drawing.makeAlphaMask(outCtx, size, '#000');
$('#output').empty().append(outCtx.canvas);
$('#status').text(((new Date()) - startTime) + " ms");
// var canvas = fx.canvas();
// var texture = canvas.texture(ctx.canvas);
// canvas.draw(texture).triangleBlur(radius).update();
// ctx.clearRect(0, 0, canvas.width, canvas.height);
// ctx.drawImage(canvas, 0, 0);
}
function redraw() {
var startTime = new Date();
var size = { w: SZ, h: SZ };
var tmpCtx = imagelib.drawing.context(size);
var outCtx = imagelib.drawing.context(size);
tmpCtx.font = 'bold ' + (400 * SZ / 512) + 'px Helvetica';
tmpCtx.textAlign = 'center';
tmpCtx.textBaseline = 'baseline';
tmpCtx.fillStyle = 'red';
tmpCtx.fillText($('#in').val(), SZ / 2, 490 * SZ / 512, SZ);
tmpCtx.canvas.style.border = '1px solid #ccc';
imagelib.drawing.fx([
{
effect: 'inner-shadow',
color: '#fff',
opacity: 0.75,
blur: 5 * SZ / 512,
translate: { y: 5 * SZ / 512 }
},
{
effect: 'inner-shadow',
color: '#000',
opacity: 0.4,
blur: 20 * SZ / 512,
translate: { y: -5 * SZ / 512 }
},
{
effect: 'outer-shadow',
color: '#00ccff',
blur: 20 * SZ / 512,
translate: { x: 10 * SZ / 512 }
},
{
effect: 'outer-shadow',
color: '#ffcc00',
blur: 20 * SZ / 512,
translate: { x: -10 * SZ / 512 }
}
], outCtx, tmpCtx, size);
$('#output').empty().append(outCtx.canvas);
$('#status').text(((new Date()) - startTime) + " ms");
}
</script>
</body>
</html>
| 07pratik-androidui | asset-studio/src/html/_fxtest.html | HTML | asf20 | 7,639 |
<!DOCTYPE html>
<html>
<!--
Copyright 2010 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.
-->
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta http-equiv="X-UA-Compatible" content="chrome=1">
<title>Android Asset Studio - Icon Generator - Tab icons</title>
<link rel="stylesheet" href="lib/cssreset-3.4.1.min.css">
<link rel="stylesheet" href="lib/jquery-ui/css/android/jquery-ui-1.8.16.custom.css">
<link rel="stylesheet" href="css/studio.css">
<script src="lib/jquery-ui/js/jquery-1.6.2.min.js"></script>
<script src="lib/jquery-ui/js/jquery-ui-1.8.16.custom.min.js"></script>
<!-- canvg used to overcome <img src=SVG> toDataURL security issues -->
<!-- see code.google.com/p/chromium/issues/detail?id=54204 -->
<script src="lib/canvg/rgbcolor.js"></script>
<script src="lib/canvg/canvg.js"></script>
<!-- prereq. for asset studio lib -->
<link rel="stylesheet" href="lib/colorpicker/css/colorpicker.css">
<script src="lib/colorpicker/js/colorpicker.js"></script>
<!-- for .ZIP downloads -->
<script src="lib/swfobject-2.2.js"></script>
<script src="lib/downloadify/js/downloadify.min.js"></script>
<script src="lib/jszip/jszip.js"></script>
<script src="js/asset-studio.pack.js"></script>
<!-- TODO: remove Analytics tracking if you're building the tools locally! -->
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-18671401-1']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</head>
<body>
<div id="main-container">
<div id="header">
<h1><a href="index.html">Android Asset Studio</a></h1>
</div>
<div id="page-header">
<div id="breadcrumb">
<a href="index.html">Android Asset Studio</a> »
<a href="index.html#group-icon-generators">Icon generators</a> »
<em>Tab icons</em>
</div>
<p id="page-intro">
The <strong>tab icon generator</strong> will create icons that you
can use in your Android application, from a variety of source images.
To begin, simply enter the input details below. Output will be shown
below.
</p>
</div>
<div id="inputs">
<div id="inputs-form"></div>
<input type="checkbox" id="output-show-guides">
<label for="output-show-guides">Show Guides</label>
<input type="checkbox" id="output-better-scaling">
<label for="output-better-scaling">Better Image Smoothing (slow)</label>
</div>
<div id="outputs">
<h3>
Output images
<div id="zip-button"></div>
</h3>
</div>
<div id="footer">
<p>See the source at the <a href="http://code.google.com/p/android-ui-utils">android-ui-utils</a> Google Code project.</p>
<p>All generated art is licensed under a <a rel="license" href="http://creativecommons.org/licenses/by/3.0/">Creative Commons Attribution 3.0 Unported License</a>. <a href="attribution.html">Attribution info</a></p>
</div>
</div>
<script>
$(studio.checkBrowser);
$('#output-show-guides').button().click(regenerate);
$('#output-better-scaling').button().click(function() {
imagelib.ALLOW_MANUAL_RESCALE = $(this).is(':checked');
regenerate();
});
var zipper = studio.zip.createDownloadifyZipButton($('#zip-button'));
// Create image output slots
for (var version in {'X':1, '5':1}) {
var versionStr = (version == 'X') ? '' : ('-v' + version);
for (var type in {'selected':1, 'unselected':1 }) {
var group = studio.ui.createImageOutputGroup({
container: $('#outputs'),
label: type + ((version == 'X') ? '' : ', API ' + version)
});
for (var density in {'xhdpi':1, 'hdpi':1, 'mdpi':1, 'ldpi':1})
studio.ui.createImageOutputSlot({
container: group,
id: 'out-icon-' + version + '-' + type + '-' + density,
label: density
});
}
}
var PARAM_RESOURCES = {
'mdpi-iconSize': { w: 32, h: 32 },
'mdpi-targetRect': { x: 2, y: 2, w: 28, h: 28 }
};
var drawableXmlTemplate = [
'<?xml version="1.0" encoding="utf-8"?>',
'<selector xmlns:android="http://schemas.android.com/apk/res/android">',
' <item android:drawable="@drawable/%s_selected" android:state_selected="true" android:state_pressed="false" />',
' <item android:drawable="@drawable/%s_unselected" />',
'</selector>',
''
].join('\n');
/**
* Main image generation routine.
*/
function regenerate() {
var values = form.getValues();
var showGuides = $('#output-show-guides').is(':checked');
var iconName = 'ic_tab_' + values['name'];
zipper.clear();
zipper.setZipFilename(iconName + '.zip');
if (!values['source'].ctx) {
return;
}
var srcCtx = values['source'].ctx;
var srcSize = { w: srcCtx.canvas.width, h: srcCtx.canvas.height };
var srcRect = { x: 0, y: 0, w: srcSize.w, h: srcSize.h };
for (var version in {'X':1, '5':1}) {
for (var type in {'selected':1, 'unselected':1}) {
for (var density in {'xhdpi':1, 'hdpi':1, 'mdpi':1, 'ldpi':1}) {
var versionStr = (version == 'X') ? '' : ('-v' + version);
var mult = studio.util.getMultBaseMdpi(density);
var iconSize = studio.util.multRound(
PARAM_RESOURCES['mdpi-iconSize'], mult);
var targetRect = studio.util.multRound(
PARAM_RESOURCES['mdpi-targetRect'], mult);
var outCtx = imagelib.drawing.context(iconSize);
var tmpCtx = imagelib.drawing.context(iconSize);
imagelib.drawing.drawCenterInside(tmpCtx, srcCtx, targetRect, srcRect);
var effects = [];
if (version == 'X') {
if (type == 'selected') {
effects = [
{
effect: 'inner-shadow',
color: '#000',
opacity: 0.2,
blur: 3 * mult,
translate: { y: 3 * mult }
},
{
effect: 'inner-shadow',
color: '#000',
opacity: 0.35,
translate: { y: 1 }
},
{
effect: 'inner-shadow',
color: '#fff',
opacity: 0.35,
translate: { y: -1 }
},
{
effect: 'fill-lineargradient',
from: { x: 0, y: 0 },
to: { x: 0, y: iconSize.h },
colors: [
{ offset: 0, color: '#a3a3a3' },
{ offset: 1.0, color: '#787878' }
]
}
];
} else {
effects = [
{
effect: 'inner-shadow',
color: '#000',
opacity: 0.1,
blur: 3 * mult,
translate: { y: 3 * mult }
},
{
effect: 'inner-shadow',
color: '#000',
opacity: 0.35,
translate: { y: 1 }
},
{
effect: 'inner-shadow',
color: '#fff',
opacity: 0.35,
translate: { y: -1 }
},
{
effect: 'fill-lineargradient',
from: { x: 0, y: 0 },
to: { x: 0, y: iconSize.h },
colors: [
{ offset: 0.25, color: '#f9f9f9' },
{ offset: 1.0, color: '#dfdfdf' }
]
}
];
}
} else if (version == '5') {
if (type == 'selected') {
effects = [
{
effect: 'outer-shadow',
color: '#000',
opacity: 0.25,
blur: 5 * mult
},
{
effect: 'fill-color',
color: '#fff'
}
];
} else {
effects = [
{
effect: 'fill-color',
color: '#808080'
}
];
}
}
imagelib.drawing.fx(effects, outCtx, tmpCtx, iconSize);
/*imagelib.drawing.applyFilter(
new ConvolutionFilter(
[-1, -1, 0,
-1, 1, 1,
0, 1, 1], 2, -128),
outCtx, iconSize);*/
zipper.add({
name: 'res/drawable-' + density + versionStr + '/' +
iconName + '_' + type + '.png',
base64data: outCtx.canvas.toDataURL().match(/;base64,(.+)/)[1]
});
if (showGuides)
studio.ui.drawImageGuideRects(outCtx, iconSize, [
targetRect
]);
imagelib.loadFromUri(outCtx.canvas.toDataURL(), function(version, type, density) {
return function(img) {
$('#out-icon-' + version + '-' + type + '-' + density).attr('src', img.src);
};
}(version, type, density));
}
}
}
// Add drawable XML to the zip file
zipper.add({
name: 'res/drawable/' + iconName + '.xml',
textData: drawableXmlTemplate.replace(/%s/g, iconName)
});
}
var form = new studio.forms.Form('iconform', {
onChange: regenerate,
fields: [
new studio.forms.ImageField('source', {
title: 'Source',
helpText: 'Must be alpha-transparent',
defaultValueTrim: 1
}),
new studio.forms.TextField('name', {
title: 'Icon name',
helpText: 'Used when generating ZIP files. Becomes <code>ic_tab_<name></code>.',
defaultValue: 'example'
})
]
});
form.createUI($('#inputs-form').get(0));
studio.hash.bindFormToDocumentHash(form);
</script>
</body>
</html>
| 07pratik-androidui | asset-studio/src/html/icons-tab.html | HTML | asf20 | 11,794 |
<!DOCTYPE html>
<html>
<!--
Copyright 2011 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.
-->
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8">
<meta http-equiv="X-UA-Compatible" content="chrome=1">
<title>Android Asset Studio</title>
<link rel="stylesheet" href="lib/cssreset-3.4.1.min.css">
<link rel="stylesheet" href="lib/jquery-ui/css/android/jquery-ui-1.8.16.custom.css">
<link rel="stylesheet" href="css/studio.css">
<!-- TODO: remove Analytics tracking if you're building the tools locally! -->
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-18671401-1']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
</script>
</head>
<body>
<div id="main-container">
<div id="header">
<h1><a href="index.html">Android Asset Studio</a></h1>
</div>
<div id="page-links">
<h2>Attribution</h2>
<p>All art generated by the Android Asset Studio is licensed under a
<a rel="license" href="http://creativecommons.org/licenses/by/3.0/">
Creative Commons Attribution 3.0 Unported License</a>.</p><br><br>
<p>No particular form of attribution is required, but please follow
<a href="http://wiki.creativecommons.org/Marking/Users">best practices
for attribution</a>. A minimal form of attribution would be to mention
in your application's source project that some assets were created with
the Android Asset Studio.</p>
</div>
<div id="footer">
<p>See the source at the <a href="http://code.google.com/p/android-ui-utils">android-ui-utils</a> Google Code project.</p>
</div>
</div>
</body>
</html>
| 07pratik-androidui | asset-studio/src/html/attribution.html | HTML | asf20 | 2,607 |
/*
Copyright 2010 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.
*/
/* common patterns */
.offscreen {
position: absolute;
left: -10000px;
top: 0;
}
/* main styles + layout */
html, body {
font-family: helvetica, arial, sans-serif;
font-size: 13px;
line-height: 16px;
background-color: #ccc;
color: #333;
}
strong {
font-weight: bold;
}
a {
color: #30577c;
}
#main-container {
background-color: #fff;
width: 800px;
margin: 24px auto;
border-radius: 4px;
padding: 4px;
box-shadow: 0 3px 15px rgba(0,0,0,0.25);
-webkit-box-shadow: 0 3px 15px rgba(0,0,0,0.25);
-moz-box-shadow: 0 3px 15px rgba(0,0,0,0.25);
}
#header, #page-header, #page-links, #inputs, #outputs, #footer {
padding: 24px;
}
#header {
background-color: #a4c639;
color: #fff;
}
#header h1 {
font-weight: bold;
font-size: 48px;
line-height: 48px;
}
#header h1 a {
text-decoration: none;
color: #fff;
}
#page-header, #page-links {}
#page-header p,
#page-links p {
width: 40em;
}
#page-header h2,
#page-links h2 {
color: #a4c639;
font-weight: bold;
font-size: 16px;
line-height: 20px;
margin-bottom: 8px;
}
#page-header h2 span,
#page-links h2 span {
color: #888;
font-weight: normal;
}
#breadcrumb {
color: #888;
font-weight: normal;
font-size: 16px;
line-height: 20px;
margin-bottom: 8px;
}
#breadcrumb a {
text-decoration: none;
color: #888;
}
#breadcrumb em {
color: #a4c639;
font-weight: bold;
}
#page-links ul {
margin: 12px 24px;
}
#page-links li {
font-size: 13px;
line-height: 16px;
margin-bottom: 4px;
font-weight: bold;
}
#inputs {
background-color: #eee;
}
#outputs {
background-color: #ccc;
}
#inputs h3, #outputs h3 {
font-weight: bold;
font-size: 16px;
line-height: 20px;
margin-bottom: 8px;
}
/* forms */
.form-field-outer {
margin-bottom: 24px;
}
.form-field-outer > label {
font-weight: bold;
display: inline-block;
vertical-align: top;
margin-top: 6px;
width: 148px;
margin-right: 12px;
}
.form-field-outer > label .form-field-help-text {
font-weight: normal;
font-size: 11px;
line-height: 12px;
color: #888;
}
.form-field-container {
display: inline-block;
vertical-align: top;
}
.form-text,
.ui-autocomplete-input {
margin: 0;
padding: 3px 6px;
}
.ui-autocomplete-input + .ui-button {
margin-left: -1px;
}
.ui-autocomplete {
z-index: 3 !important; /* to show above slider handles */
}
.form-text,
.ui-autocomplete-input,
.ui-autocomplete-input + .ui-button {
vertical-align: top;
box-sizing: border-box;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
height: 22px;
}
.form-image-hidden-file-field {
position: absolute;
left: -10000px;
opacity: 0;
}
.form-image-clipart-attribution {
font-weight: normal;
font-size: 11px;
line-height: 12px;
color: #888;
margin-top: 4px;
}
.form-image-clipart-list {
background-color: #fff;
width: 250px;
height: 200px;
border: 1px solid #ccc;
overflow-y: scroll;
}
.form-image-clipart-list img {
border: 3px solid #fff;
width: 48px;
height: 48px;
cursor: pointer;
}
.form-image-clipart-list img:hover {
border: 3px solid #ccc;
}
.form-image-clipart-list img.selected {
border: 3px solid #a4c639;
}
.form-image-preview {
background-color: #fff;
display: inline-block;
max-height: 100px;
max-width: 250px;
border: 1px solid #ccc;
}
.form-color-preview {
border: 1px solid #bbb;
width: 36px;
height: 16px;
margin-left: -8px;
}
.ui-state-hover .form-color-preview {
border: 1px solid #999;
}
.ui-state-active .form-color-preview {
border: 1px solid #617524;
}
.form-color-alpha,
.form-range {
margin-top: 6px;
width: 200px;
}
.form-range {
display: inline-block;
vertical-align: bottom;
}
.form-range-text {
display: inline-block;
vertical-align: bottom;
padding-left: 6px;
font-size: 11px;
line-height: 11px;
}
.form-field-drop-target.drag-hover {
outline: 2px solid #a4c639;
outline-offset: 5px;
}
/* subforms */
.form-subform {
margin-top: 24px;
}
.form-subform .form-field-outer {
margin-bottom: 6px;
}
.form-subform .form-field-outer > label {
display: inline-block;
padding-right: 12px;
width: auto;
font-weight: normal;
}
/* output images */
.out-image-group {
display: inline-block;
background-color: #eee;
padding: 8px 10px;
margin-right: 12px;
margin-bottom: 12px;
border-radius: 12px;
}
.out-image-group > .label {
font-weight: bold;
margin-bottom: 6px;
}
.out-image-block {
display: inline-block;
vertical-align: top;
margin-right: 6px;
margin-bottom: 6px;
font-size: 11px;
line-height: 12px;
text-align: center;
}
.out-image {
border: 1px solid #ccc;
margin-top: 4px;
display: inline-block;
position: relative;
}
#outputs hr {
border: 0;
margin: 4px 0;
height: 1px;
}
#zip-button {
display: inline-block;
margin-left: 12px;
vertical-align: middle;
}
/* alternative state styles */
.browser-unsupported-note {
padding: 6px 12px;
border: 0 !important;
box-shadow: 0 3px 15px rgba(0,0,0,0.25);
-webkit-box-shadow: 0 3px 15px rgba(0,0,0,0.25);
-moz-box-shadow: 0 3px 15px rgba(0,0,0,0.25);
}
/* bug fixes */
.colorpicker {
z-index: 10000; /* bugfix for jQuery UI sliders appearing above colorpicker */
}
| 07pratik-androidui | asset-studio/src/css/studio.css | CSS | asf20 | 5,992 |
/**
*
* Color picker
* Author: Stefan Petre www.eyecon.ro
*
* Dual licensed under the MIT and GPL licenses
*
*/
(function ($) {
var ColorPicker = function () {
var
ids = {},
inAction,
charMin = 65,
visible,
tpl = '<div class="colorpicker"><div class="colorpicker_color"><div><div></div></div></div><div class="colorpicker_hue"><div></div></div><div class="colorpicker_new_color"></div><div class="colorpicker_current_color"></div><div class="colorpicker_hex"><input type="text" maxlength="6" size="6" /></div><div class="colorpicker_rgb_r colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_rgb_g colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_rgb_b colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_hsb_h colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_hsb_s colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_hsb_b colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_submit"></div></div>',
defaults = {
eventName: 'click',
onShow: function () {},
onBeforeShow: function(){},
onHide: function () {},
onChange: function () {},
onSubmit: function () {},
color: 'ff0000',
livePreview: true,
flat: false
},
fillRGBFields = function (hsb, cal) {
var rgb = HSBToRGB(hsb);
$(cal).data('colorpicker').fields
.eq(1).val(rgb.r).end()
.eq(2).val(rgb.g).end()
.eq(3).val(rgb.b).end();
},
fillHSBFields = function (hsb, cal) {
$(cal).data('colorpicker').fields
.eq(4).val(hsb.h).end()
.eq(5).val(hsb.s).end()
.eq(6).val(hsb.b).end();
},
fillHexFields = function (hsb, cal) {
$(cal).data('colorpicker').fields
.eq(0).val(HSBToHex(hsb)).end();
},
setSelector = function (hsb, cal) {
$(cal).data('colorpicker').selector.css('backgroundColor', '#' + HSBToHex({h: hsb.h, s: 100, b: 100}));
$(cal).data('colorpicker').selectorIndic.css({
left: parseInt(150 * hsb.s/100, 10),
top: parseInt(150 * (100-hsb.b)/100, 10)
});
},
setHue = function (hsb, cal) {
$(cal).data('colorpicker').hue.css('top', parseInt(150 - 150 * hsb.h/360, 10));
},
setCurrentColor = function (hsb, cal) {
$(cal).data('colorpicker').currentColor.css('backgroundColor', '#' + HSBToHex(hsb));
},
setNewColor = function (hsb, cal) {
$(cal).data('colorpicker').newColor.css('backgroundColor', '#' + HSBToHex(hsb));
},
keyDown = function (ev) {
var pressedKey = ev.charCode || ev.keyCode || -1;
if ((pressedKey > charMin && pressedKey <= 90) || pressedKey == 32) {
return false;
}
var cal = $(this).parent().parent();
if (cal.data('colorpicker').livePreview === true) {
change.apply(this);
}
},
change = function (ev) {
var cal = $(this).parent().parent(), col;
if (this.parentNode.className.indexOf('_hex') > 0) {
cal.data('colorpicker').color = col = HexToHSB(fixHex(this.value));
} else if (this.parentNode.className.indexOf('_hsb') > 0) {
cal.data('colorpicker').color = col = fixHSB({
h: parseInt(cal.data('colorpicker').fields.eq(4).val(), 10),
s: parseInt(cal.data('colorpicker').fields.eq(5).val(), 10),
b: parseInt(cal.data('colorpicker').fields.eq(6).val(), 10)
});
} else {
cal.data('colorpicker').color = col = RGBToHSB(fixRGB({
r: parseInt(cal.data('colorpicker').fields.eq(1).val(), 10),
g: parseInt(cal.data('colorpicker').fields.eq(2).val(), 10),
b: parseInt(cal.data('colorpicker').fields.eq(3).val(), 10)
}));
}
if (ev) {
fillRGBFields(col, cal.get(0));
fillHexFields(col, cal.get(0));
fillHSBFields(col, cal.get(0));
}
setSelector(col, cal.get(0));
setHue(col, cal.get(0));
setNewColor(col, cal.get(0));
cal.data('colorpicker').onChange.apply(cal, [col, HSBToHex(col), HSBToRGB(col)]);
},
blur = function (ev) {
var cal = $(this).parent().parent();
cal.data('colorpicker').fields.parent().removeClass('colorpicker_focus');
},
focus = function () {
charMin = this.parentNode.className.indexOf('_hex') > 0 ? 70 : 65;
$(this).parent().parent().data('colorpicker').fields.parent().removeClass('colorpicker_focus');
$(this).parent().addClass('colorpicker_focus');
},
downIncrement = function (ev) {
var field = $(this).parent().find('input').focus();
var current = {
el: $(this).parent().addClass('colorpicker_slider'),
max: this.parentNode.className.indexOf('_hsb_h') > 0 ? 360 : (this.parentNode.className.indexOf('_hsb') > 0 ? 100 : 255),
y: ev.pageY,
field: field,
val: parseInt(field.val(), 10),
preview: $(this).parent().parent().data('colorpicker').livePreview
};
$(document).bind('mouseup', current, upIncrement);
$(document).bind('mousemove', current, moveIncrement);
},
moveIncrement = function (ev) {
ev.data.field.val(Math.max(0, Math.min(ev.data.max, parseInt(ev.data.val + ev.pageY - ev.data.y, 10))));
if (ev.data.preview) {
change.apply(ev.data.field.get(0), [true]);
}
return false;
},
upIncrement = function (ev) {
change.apply(ev.data.field.get(0), [true]);
ev.data.el.removeClass('colorpicker_slider').find('input').focus();
$(document).unbind('mouseup', upIncrement);
$(document).unbind('mousemove', moveIncrement);
return false;
},
downHue = function (ev) {
var current = {
cal: $(this).parent(),
y: $(this).offset().top
};
current.preview = current.cal.data('colorpicker').livePreview;
$(document).bind('mouseup', current, upHue);
$(document).bind('mousemove', current, moveHue);
},
moveHue = function (ev) {
change.apply(
ev.data.cal.data('colorpicker')
.fields
.eq(4)
.val(parseInt(360*(150 - Math.max(0,Math.min(150,(ev.pageY - ev.data.y))))/150, 10))
.get(0),
[ev.data.preview]
);
return false;
},
upHue = function (ev) {
fillRGBFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0));
fillHexFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0));
$(document).unbind('mouseup', upHue);
$(document).unbind('mousemove', moveHue);
return false;
},
downSelector = function (ev) {
var current = {
cal: $(this).parent(),
pos: $(this).offset()
};
current.preview = current.cal.data('colorpicker').livePreview;
$(document).bind('mouseup', current, upSelector);
$(document).bind('mousemove', current, moveSelector);
},
moveSelector = function (ev) {
change.apply(
ev.data.cal.data('colorpicker')
.fields
.eq(6)
.val(parseInt(100*(150 - Math.max(0,Math.min(150,(ev.pageY - ev.data.pos.top))))/150, 10))
.end()
.eq(5)
.val(parseInt(100*(Math.max(0,Math.min(150,(ev.pageX - ev.data.pos.left))))/150, 10))
.get(0),
[ev.data.preview]
);
return false;
},
upSelector = function (ev) {
fillRGBFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0));
fillHexFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0));
$(document).unbind('mouseup', upSelector);
$(document).unbind('mousemove', moveSelector);
return false;
},
enterSubmit = function (ev) {
$(this).addClass('colorpicker_focus');
},
leaveSubmit = function (ev) {
$(this).removeClass('colorpicker_focus');
},
clickSubmit = function (ev) {
var cal = $(this).parent();
var col = cal.data('colorpicker').color;
cal.data('colorpicker').origColor = col;
setCurrentColor(col, cal.get(0));
cal.data('colorpicker').onSubmit(col, HSBToHex(col), HSBToRGB(col), cal.data('colorpicker').el);
},
show = function (ev) {
var cal = $('#' + $(this).data('colorpickerId'));
cal.data('colorpicker').onBeforeShow.apply(this, [cal.get(0)]);
var pos = $(this).offset();
var viewPort = getViewport();
var top = pos.top + this.offsetHeight;
var left = pos.left;
if (top + 176 > viewPort.t + viewPort.h) {
top -= this.offsetHeight + 176;
}
if (left + 356 > viewPort.l + viewPort.w) {
left -= 356;
}
cal.css({left: left + 'px', top: top + 'px'});
if (cal.data('colorpicker').onShow.apply(this, [cal.get(0)]) != false) {
cal.show();
}
$(document).bind('mousedown', {cal: cal}, hide);
return false;
},
hide = function (ev) {
if (!isChildOf(ev.data.cal.get(0), ev.target, ev.data.cal.get(0))) {
if (ev.data.cal.data('colorpicker').onHide.apply(this, [ev.data.cal.get(0)]) != false) {
ev.data.cal.hide();
}
$(document).unbind('mousedown', hide);
}
},
isChildOf = function(parentEl, el, container) {
if (parentEl == el) {
return true;
}
if (parentEl.contains) {
return parentEl.contains(el);
}
if ( parentEl.compareDocumentPosition ) {
return !!(parentEl.compareDocumentPosition(el) & 16);
}
var prEl = el.parentNode;
while(prEl && prEl != container) {
if (prEl == parentEl)
return true;
prEl = prEl.parentNode;
}
return false;
},
getViewport = function () {
var m = document.compatMode == 'CSS1Compat';
return {
l : window.pageXOffset || (m ? document.documentElement.scrollLeft : document.body.scrollLeft),
t : window.pageYOffset || (m ? document.documentElement.scrollTop : document.body.scrollTop),
w : window.innerWidth || (m ? document.documentElement.clientWidth : document.body.clientWidth),
h : window.innerHeight || (m ? document.documentElement.clientHeight : document.body.clientHeight)
};
},
fixHSB = function (hsb) {
return {
h: Math.min(360, Math.max(0, hsb.h)),
s: Math.min(100, Math.max(0, hsb.s)),
b: Math.min(100, Math.max(0, hsb.b))
};
},
fixRGB = function (rgb) {
return {
r: Math.min(255, Math.max(0, rgb.r)),
g: Math.min(255, Math.max(0, rgb.g)),
b: Math.min(255, Math.max(0, rgb.b))
};
},
fixHex = function (hex) {
var len = 6 - hex.length;
if (len > 0) {
var o = [];
for (var i=0; i<len; i++) {
o.push('0');
}
o.push(hex);
hex = o.join('');
}
return hex;
},
HexToRGB = function (hex) {
var hex = parseInt(((hex.indexOf('#') > -1) ? hex.substring(1) : hex), 16);
return {r: hex >> 16, g: (hex & 0x00FF00) >> 8, b: (hex & 0x0000FF)};
},
HexToHSB = function (hex) {
return RGBToHSB(HexToRGB(hex));
},
RGBToHSB = function (rgb) {
var hsb = {
h: 0,
s: 0,
b: 0
};
var min = Math.min(rgb.r, rgb.g, rgb.b);
var max = Math.max(rgb.r, rgb.g, rgb.b);
var delta = max - min;
hsb.b = max;
if (max != 0) {
}
hsb.s = max != 0 ? 255 * delta / max : 0;
if (hsb.s != 0) {
if (rgb.r == max) {
hsb.h = (rgb.g - rgb.b) / delta;
} else if (rgb.g == max) {
hsb.h = 2 + (rgb.b - rgb.r) / delta;
} else {
hsb.h = 4 + (rgb.r - rgb.g) / delta;
}
} else {
hsb.h = -1;
}
hsb.h *= 60;
if (hsb.h < 0) {
hsb.h += 360;
}
hsb.s *= 100/255;
hsb.b *= 100/255;
return hsb;
},
HSBToRGB = function (hsb) {
var rgb = {};
var h = Math.round(hsb.h);
var s = Math.round(hsb.s*255/100);
var v = Math.round(hsb.b*255/100);
if(s == 0) {
rgb.r = rgb.g = rgb.b = v;
} else {
var t1 = v;
var t2 = (255-s)*v/255;
var t3 = (t1-t2)*(h%60)/60;
if(h==360) h = 0;
if(h<60) {rgb.r=t1; rgb.b=t2; rgb.g=t2+t3}
else if(h<120) {rgb.g=t1; rgb.b=t2; rgb.r=t1-t3}
else if(h<180) {rgb.g=t1; rgb.r=t2; rgb.b=t2+t3}
else if(h<240) {rgb.b=t1; rgb.r=t2; rgb.g=t1-t3}
else if(h<300) {rgb.b=t1; rgb.g=t2; rgb.r=t2+t3}
else if(h<360) {rgb.r=t1; rgb.g=t2; rgb.b=t1-t3}
else {rgb.r=0; rgb.g=0; rgb.b=0}
}
return {r:Math.round(rgb.r), g:Math.round(rgb.g), b:Math.round(rgb.b)};
},
RGBToHex = function (rgb) {
var hex = [
rgb.r.toString(16),
rgb.g.toString(16),
rgb.b.toString(16)
];
$.each(hex, function (nr, val) {
if (val.length == 1) {
hex[nr] = '0' + val;
}
});
return hex.join('');
},
HSBToHex = function (hsb) {
return RGBToHex(HSBToRGB(hsb));
},
restoreOriginal = function () {
var cal = $(this).parent();
var col = cal.data('colorpicker').origColor;
cal.data('colorpicker').color = col;
fillRGBFields(col, cal.get(0));
fillHexFields(col, cal.get(0));
fillHSBFields(col, cal.get(0));
setSelector(col, cal.get(0));
setHue(col, cal.get(0));
setNewColor(col, cal.get(0));
};
return {
init: function (opt) {
opt = $.extend({}, defaults, opt||{});
if (typeof opt.color == 'string') {
opt.color = HexToHSB(opt.color);
} else if (opt.color.r != undefined && opt.color.g != undefined && opt.color.b != undefined) {
opt.color = RGBToHSB(opt.color);
} else if (opt.color.h != undefined && opt.color.s != undefined && opt.color.b != undefined) {
opt.color = fixHSB(opt.color);
} else {
return this;
}
return this.each(function () {
if (!$(this).data('colorpickerId')) {
var options = $.extend({}, opt);
options.origColor = opt.color;
var id = 'collorpicker_' + parseInt(Math.random() * 1000);
$(this).data('colorpickerId', id);
var cal = $(tpl).attr('id', id);
if (options.flat) {
cal.appendTo(this).show();
} else {
cal.appendTo(document.body);
}
options.fields = cal
.find('input')
.bind('keyup', keyDown)
.bind('change', change)
.bind('blur', blur)
.bind('focus', focus);
cal
.find('span').bind('mousedown', downIncrement).end()
.find('>div.colorpicker_current_color').bind('click', restoreOriginal);
options.selector = cal.find('div.colorpicker_color').bind('mousedown', downSelector);
options.selectorIndic = options.selector.find('div div');
options.el = this;
options.hue = cal.find('div.colorpicker_hue div');
cal.find('div.colorpicker_hue').bind('mousedown', downHue);
options.newColor = cal.find('div.colorpicker_new_color');
options.currentColor = cal.find('div.colorpicker_current_color');
cal.data('colorpicker', options);
cal.find('div.colorpicker_submit')
.bind('mouseenter', enterSubmit)
.bind('mouseleave', leaveSubmit)
.bind('click', clickSubmit);
fillRGBFields(options.color, cal.get(0));
fillHSBFields(options.color, cal.get(0));
fillHexFields(options.color, cal.get(0));
setHue(options.color, cal.get(0));
setSelector(options.color, cal.get(0));
setCurrentColor(options.color, cal.get(0));
setNewColor(options.color, cal.get(0));
if (options.flat) {
cal.css({
position: 'relative',
display: 'block'
});
} else {
$(this).bind(options.eventName, show);
}
}
});
},
showPicker: function() {
return this.each( function () {
if ($(this).data('colorpickerId')) {
show.apply(this);
}
});
},
hidePicker: function() {
return this.each( function () {
if ($(this).data('colorpickerId')) {
$('#' + $(this).data('colorpickerId')).hide();
}
});
},
setColor: function(col) {
if (typeof col == 'string') {
col = HexToHSB(col);
} else if (col.r != undefined && col.g != undefined && col.b != undefined) {
col = RGBToHSB(col);
} else if (col.h != undefined && col.s != undefined && col.b != undefined) {
col = fixHSB(col);
} else {
return this;
}
return this.each(function(){
if ($(this).data('colorpickerId')) {
var cal = $('#' + $(this).data('colorpickerId'));
cal.data('colorpicker').color = col;
cal.data('colorpicker').origColor = col;
fillRGBFields(col, cal.get(0));
fillHSBFields(col, cal.get(0));
fillHexFields(col, cal.get(0));
setHue(col, cal.get(0));
setSelector(col, cal.get(0));
setCurrentColor(col, cal.get(0));
setNewColor(col, cal.get(0));
}
});
}
};
}();
$.fn.extend({
ColorPicker: ColorPicker.init,
ColorPickerHide: ColorPicker.hidePicker,
ColorPickerShow: ColorPicker.showPicker,
ColorPickerSetColor: ColorPicker.setColor
});
})(jQuery) | 07pratik-androidui | asset-studio/src/lib/colorpicker/js/colorpicker.js | JavaScript | asf20 | 17,175 |
.colorpicker {
width: 356px;
height: 176px;
overflow: hidden;
position: absolute;
background: url(../images/colorpicker_background.png);
font-family: Arial, Helvetica, sans-serif;
display: none;
}
.colorpicker_color {
width: 150px;
height: 150px;
left: 14px;
top: 13px;
position: absolute;
background: #f00;
overflow: hidden;
cursor: crosshair;
}
.colorpicker_color div {
position: absolute;
top: 0;
left: 0;
width: 150px;
height: 150px;
background: url(../images/colorpicker_overlay.png);
}
.colorpicker_color div div {
position: absolute;
top: 0;
left: 0;
width: 11px;
height: 11px;
overflow: hidden;
background: url(../images/colorpicker_select.gif);
margin: -5px 0 0 -5px;
}
.colorpicker_hue {
position: absolute;
top: 13px;
left: 171px;
width: 35px;
height: 150px;
cursor: n-resize;
}
.colorpicker_hue div {
position: absolute;
width: 35px;
height: 9px;
overflow: hidden;
background: url(../images/colorpicker_indic.gif) left top;
margin: -4px 0 0 0;
left: 0px;
}
.colorpicker_new_color {
position: absolute;
width: 60px;
height: 30px;
left: 213px;
top: 13px;
background: #f00;
}
.colorpicker_current_color {
position: absolute;
width: 60px;
height: 30px;
left: 283px;
top: 13px;
background: #f00;
}
.colorpicker input {
background-color: transparent;
border: 1px solid transparent;
position: absolute;
font-size: 10px;
font-family: Arial, Helvetica, sans-serif;
color: #898989;
top: 4px;
right: 11px;
text-align: right;
margin: 0;
padding: 0;
height: 11px;
}
.colorpicker_hex {
position: absolute;
width: 72px;
height: 22px;
background: url(../images/colorpicker_hex.png) top;
left: 212px;
top: 142px;
}
.colorpicker_hex input {
right: 6px;
}
.colorpicker_field {
height: 22px;
width: 62px;
background-position: top;
position: absolute;
}
.colorpicker_field span {
position: absolute;
width: 12px;
height: 22px;
overflow: hidden;
top: 0;
right: 0;
cursor: n-resize;
}
.colorpicker_rgb_r {
background-image: url(../images/colorpicker_rgb_r.png);
top: 52px;
left: 212px;
}
.colorpicker_rgb_g {
background-image: url(../images/colorpicker_rgb_g.png);
top: 82px;
left: 212px;
}
.colorpicker_rgb_b {
background-image: url(../images/colorpicker_rgb_b.png);
top: 112px;
left: 212px;
}
.colorpicker_hsb_h {
background-image: url(../images/colorpicker_hsb_h.png);
top: 52px;
left: 282px;
}
.colorpicker_hsb_s {
background-image: url(../images/colorpicker_hsb_s.png);
top: 82px;
left: 282px;
}
.colorpicker_hsb_b {
background-image: url(../images/colorpicker_hsb_b.png);
top: 112px;
left: 282px;
}
.colorpicker_submit {
position: absolute;
width: 22px;
height: 22px;
background: url(../images/colorpicker_submit.png) top;
left: 322px;
top: 142px;
overflow: hidden;
}
.colorpicker_focus {
background-position: center;
}
.colorpicker_hex.colorpicker_focus {
background-position: bottom;
}
.colorpicker_submit.colorpicker_focus {
background-position: bottom;
}
.colorpicker_slider {
background-position: bottom;
}
| 07pratik-androidui | asset-studio/src/lib/colorpicker/css/colorpicker.css | CSS | asf20 | 3,181 |
/**
* A class to parse color values
* @author Stoyan Stefanov <sstoo@gmail.com>
* @link http://www.phpied.com/rgb-color-parser-in-javascript/
* @license Use it if you like it
*/
function RGBColor(color_string)
{
this.ok = false;
// strip any leading #
if (color_string.charAt(0) == '#') { // remove # if any
color_string = color_string.substr(1,6);
}
color_string = color_string.replace(/ /g,'');
color_string = color_string.toLowerCase();
// before getting into regexps, try simple matches
// and overwrite the input
var simple_colors = {
aliceblue: 'f0f8ff',
antiquewhite: 'faebd7',
aqua: '00ffff',
aquamarine: '7fffd4',
azure: 'f0ffff',
beige: 'f5f5dc',
bisque: 'ffe4c4',
black: '000000',
blanchedalmond: 'ffebcd',
blue: '0000ff',
blueviolet: '8a2be2',
brown: 'a52a2a',
burlywood: 'deb887',
cadetblue: '5f9ea0',
chartreuse: '7fff00',
chocolate: 'd2691e',
coral: 'ff7f50',
cornflowerblue: '6495ed',
cornsilk: 'fff8dc',
crimson: 'dc143c',
cyan: '00ffff',
darkblue: '00008b',
darkcyan: '008b8b',
darkgoldenrod: 'b8860b',
darkgray: 'a9a9a9',
darkgreen: '006400',
darkkhaki: 'bdb76b',
darkmagenta: '8b008b',
darkolivegreen: '556b2f',
darkorange: 'ff8c00',
darkorchid: '9932cc',
darkred: '8b0000',
darksalmon: 'e9967a',
darkseagreen: '8fbc8f',
darkslateblue: '483d8b',
darkslategray: '2f4f4f',
darkturquoise: '00ced1',
darkviolet: '9400d3',
deeppink: 'ff1493',
deepskyblue: '00bfff',
dimgray: '696969',
dodgerblue: '1e90ff',
feldspar: 'd19275',
firebrick: 'b22222',
floralwhite: 'fffaf0',
forestgreen: '228b22',
fuchsia: 'ff00ff',
gainsboro: 'dcdcdc',
ghostwhite: 'f8f8ff',
gold: 'ffd700',
goldenrod: 'daa520',
gray: '808080',
green: '008000',
greenyellow: 'adff2f',
honeydew: 'f0fff0',
hotpink: 'ff69b4',
indianred : 'cd5c5c',
indigo : '4b0082',
ivory: 'fffff0',
khaki: 'f0e68c',
lavender: 'e6e6fa',
lavenderblush: 'fff0f5',
lawngreen: '7cfc00',
lemonchiffon: 'fffacd',
lightblue: 'add8e6',
lightcoral: 'f08080',
lightcyan: 'e0ffff',
lightgoldenrodyellow: 'fafad2',
lightgrey: 'd3d3d3',
lightgreen: '90ee90',
lightpink: 'ffb6c1',
lightsalmon: 'ffa07a',
lightseagreen: '20b2aa',
lightskyblue: '87cefa',
lightslateblue: '8470ff',
lightslategray: '778899',
lightsteelblue: 'b0c4de',
lightyellow: 'ffffe0',
lime: '00ff00',
limegreen: '32cd32',
linen: 'faf0e6',
magenta: 'ff00ff',
maroon: '800000',
mediumaquamarine: '66cdaa',
mediumblue: '0000cd',
mediumorchid: 'ba55d3',
mediumpurple: '9370d8',
mediumseagreen: '3cb371',
mediumslateblue: '7b68ee',
mediumspringgreen: '00fa9a',
mediumturquoise: '48d1cc',
mediumvioletred: 'c71585',
midnightblue: '191970',
mintcream: 'f5fffa',
mistyrose: 'ffe4e1',
moccasin: 'ffe4b5',
navajowhite: 'ffdead',
navy: '000080',
oldlace: 'fdf5e6',
olive: '808000',
olivedrab: '6b8e23',
orange: 'ffa500',
orangered: 'ff4500',
orchid: 'da70d6',
palegoldenrod: 'eee8aa',
palegreen: '98fb98',
paleturquoise: 'afeeee',
palevioletred: 'd87093',
papayawhip: 'ffefd5',
peachpuff: 'ffdab9',
peru: 'cd853f',
pink: 'ffc0cb',
plum: 'dda0dd',
powderblue: 'b0e0e6',
purple: '800080',
red: 'ff0000',
rosybrown: 'bc8f8f',
royalblue: '4169e1',
saddlebrown: '8b4513',
salmon: 'fa8072',
sandybrown: 'f4a460',
seagreen: '2e8b57',
seashell: 'fff5ee',
sienna: 'a0522d',
silver: 'c0c0c0',
skyblue: '87ceeb',
slateblue: '6a5acd',
slategray: '708090',
snow: 'fffafa',
springgreen: '00ff7f',
steelblue: '4682b4',
tan: 'd2b48c',
teal: '008080',
thistle: 'd8bfd8',
tomato: 'ff6347',
turquoise: '40e0d0',
violet: 'ee82ee',
violetred: 'd02090',
wheat: 'f5deb3',
white: 'ffffff',
whitesmoke: 'f5f5f5',
yellow: 'ffff00',
yellowgreen: '9acd32'
};
for (var key in simple_colors) {
if (color_string == key) {
color_string = simple_colors[key];
}
}
// emd of simple type-in colors
// array of color definition objects
var color_defs = [
{
re: /^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/,
example: ['rgb(123, 234, 45)', 'rgb(255,234,245)'],
process: function (bits){
return [
parseInt(bits[1]),
parseInt(bits[2]),
parseInt(bits[3])
];
}
},
{
re: /^(\w{2})(\w{2})(\w{2})$/,
example: ['#00ff00', '336699'],
process: function (bits){
return [
parseInt(bits[1], 16),
parseInt(bits[2], 16),
parseInt(bits[3], 16)
];
}
},
{
re: /^(\w{1})(\w{1})(\w{1})$/,
example: ['#fb0', 'f0f'],
process: function (bits){
return [
parseInt(bits[1] + bits[1], 16),
parseInt(bits[2] + bits[2], 16),
parseInt(bits[3] + bits[3], 16)
];
}
}
];
// search through the definitions to find a match
for (var i = 0; i < color_defs.length; i++) {
var re = color_defs[i].re;
var processor = color_defs[i].process;
var bits = re.exec(color_string);
if (bits) {
channels = processor(bits);
this.r = channels[0];
this.g = channels[1];
this.b = channels[2];
this.ok = true;
}
}
// validate/cleanup values
this.r = (this.r < 0 || isNaN(this.r)) ? 0 : ((this.r > 255) ? 255 : this.r);
this.g = (this.g < 0 || isNaN(this.g)) ? 0 : ((this.g > 255) ? 255 : this.g);
this.b = (this.b < 0 || isNaN(this.b)) ? 0 : ((this.b > 255) ? 255 : this.b);
// some getters
this.toRGB = function () {
return 'rgb(' + this.r + ', ' + this.g + ', ' + this.b + ')';
}
this.toHex = function () {
var r = this.r.toString(16);
var g = this.g.toString(16);
var b = this.b.toString(16);
if (r.length == 1) r = '0' + r;
if (g.length == 1) g = '0' + g;
if (b.length == 1) b = '0' + b;
return '#' + r + g + b;
}
// help
this.getHelpXML = function () {
var examples = new Array();
// add regexps
for (var i = 0; i < color_defs.length; i++) {
var example = color_defs[i].example;
for (var j = 0; j < example.length; j++) {
examples[examples.length] = example[j];
}
}
// add type-in colors
for (var sc in simple_colors) {
examples[examples.length] = sc;
}
var xml = document.createElement('ul');
xml.setAttribute('id', 'rgbcolor-examples');
for (var i = 0; i < examples.length; i++) {
try {
var list_item = document.createElement('li');
var list_color = new RGBColor(examples[i]);
var example_div = document.createElement('div');
example_div.style.cssText =
'margin: 3px; '
+ 'border: 1px solid black; '
+ 'background:' + list_color.toHex() + '; '
+ 'color:' + list_color.toHex()
;
example_div.appendChild(document.createTextNode('test'));
var list_item_value = document.createTextNode(
' ' + examples[i] + ' -> ' + list_color.toRGB() + ' -> ' + list_color.toHex()
);
list_item.appendChild(example_div);
list_item.appendChild(list_item_value);
xml.appendChild(list_item);
} catch(e){}
}
return xml;
}
}
| 07pratik-androidui | asset-studio/src/lib/canvg/rgbcolor.js | JavaScript | asf20 | 9,042 |
/*
* canvg.js - Javascript SVG parser and renderer on Canvas
* MIT Licensed
* Gabe Lerner (gabelerner@gmail.com)
* http://code.google.com/p/canvg/
*
* Requires: rgbcolor.js - http://www.phpied.com/rgb-color-parser-in-javascript/
*/
if(!window.console) {
window.console = {};
window.console.log = function(str) {};
window.console.dir = function(str) {};
}
// <3 IE
if(!Array.indexOf){
Array.prototype.indexOf = function(obj){
for(var i=0; i<this.length; i++){
if(this[i]==obj){
return i;
}
}
return -1;
}
}
(function(){
// canvg(target, s)
// target: canvas element or the id of a canvas element
// s: svg string or url to svg file
// opts: optional hash of options
// ignoreMouse: true => ignore mouse events
// ignoreAnimation: true => ignore animations
// ignoreDimensions: true => does not try to resize canvas
// ignoreClear: true => does not clear canvas
// offsetX: int => draws at a x offset
// offsetY: int => draws at a y offset
// scaleWidth: int => scales horizontally to width
// scaleHeight: int => scales vertically to height
// renderCallback: function => will call the function after the first render is completed
// forceRedraw: function => will call the function on every frame, if it returns true, will redraw
this.canvg = function (target, s, opts) {
if (typeof target == 'string') {
target = document.getElementById(target);
}
// reuse class per canvas
var svg;
if (target.svg == null) {
svg = build();
target.svg = svg;
}
else {
svg = target.svg;
svg.stop();
}
svg.opts = opts;
var ctx = target.getContext('2d');
if (s.substr(0,1) == '<') {
// load from xml string
svg.loadXml(ctx, s);
}
else {
// load from url
svg.load(ctx, s);
}
}
function build() {
var svg = { };
svg.FRAMERATE = 30;
// globals
svg.init = function(ctx) {
svg.Definitions = {};
svg.Styles = {};
svg.Animations = [];
svg.Images = [];
svg.ctx = ctx;
svg.ViewPort = new (function () {
this.viewPorts = [];
this.SetCurrent = function(width, height) { this.viewPorts.push({ width: width, height: height }); }
this.RemoveCurrent = function() { this.viewPorts.pop(); }
this.Current = function() { return this.viewPorts[this.viewPorts.length - 1]; }
this.width = function() { return this.Current().width; }
this.height = function() { return this.Current().height; }
this.ComputeSize = function(d) {
if (d != null && typeof(d) == 'number') return d;
if (d == 'x') return this.width();
if (d == 'y') return this.height();
return Math.sqrt(Math.pow(this.width(), 2) + Math.pow(this.height(), 2)) / Math.sqrt(2);
}
});
}
svg.init();
// images loaded
svg.ImagesLoaded = function() {
for (var i=0; i<svg.Images.length; i++) {
if (!svg.Images[i].loaded) return false;
}
return true;
}
// trim
svg.trim = function(s) { return s.replace(/^\s+|\s+$/g, ''); }
// compress spaces
svg.compressSpaces = function(s) { return s.replace(/[\s\r\t\n]+/gm,' '); }
// ajax
svg.ajax = function(url) {
var AJAX;
if(window.XMLHttpRequest){AJAX=new XMLHttpRequest();}
else{AJAX=new ActiveXObject('Microsoft.XMLHTTP');}
if(AJAX){
AJAX.open('GET',url,false);
AJAX.send(null);
return AJAX.responseText;
}
return null;
}
// parse xml
svg.parseXml = function(xml) {
if (window.DOMParser)
{
var parser = new DOMParser();
return parser.parseFromString(xml, 'text/xml');
}
else
{
xml = xml.replace(/<!DOCTYPE svg[^>]*>/, '');
var xmlDoc = new ActiveXObject('Microsoft.XMLDOM');
xmlDoc.async = 'false';
xmlDoc.loadXML(xml);
return xmlDoc;
}
}
svg.Property = function(name, value) {
this.name = name;
this.value = value;
this.hasValue = function() {
return (this.value != null && this.value != '');
}
// return the numerical value of the property
this.numValue = function() {
if (!this.hasValue()) return 0;
var n = parseFloat(this.value);
if ((this.value + '').match(/%$/)) {
n = n / 100.0;
}
return n;
}
this.valueOrDefault = function(def) {
if (this.hasValue()) return this.value;
return def;
}
this.numValueOrDefault = function(def) {
if (this.hasValue()) return this.numValue();
return def;
}
/* EXTENSIONS */
var that = this;
// color extensions
this.Color = {
// augment the current color value with the opacity
addOpacity: function(opacity) {
var newValue = that.value;
if (opacity != null && opacity != '') {
var color = new RGBColor(that.value);
if (color.ok) {
newValue = 'rgba(' + color.r + ', ' + color.g + ', ' + color.b + ', ' + opacity + ')';
}
}
return new svg.Property(that.name, newValue);
}
}
// definition extensions
this.Definition = {
// get the definition from the definitions table
getDefinition: function() {
var name = that.value.replace(/^(url\()?#([^\)]+)\)?$/, '$2');
return svg.Definitions[name];
},
isUrl: function() {
return that.value.indexOf('url(') == 0
},
getFillStyle: function(e) {
var def = this.getDefinition();
// gradient
if (def != null && def.createGradient) {
return def.createGradient(svg.ctx, e);
}
// pattern
if (def != null && def.createPattern) {
return def.createPattern(svg.ctx, e);
}
return null;
}
}
// length extensions
this.Length = {
DPI: function(viewPort) {
return 96.0; // TODO: compute?
},
EM: function(viewPort) {
var em = 12;
var fontSize = new svg.Property('fontSize', svg.Font.Parse(svg.ctx.font).fontSize);
if (fontSize.hasValue()) em = fontSize.Length.toPixels(viewPort);
return em;
},
// get the length as pixels
toPixels: function(viewPort) {
if (!that.hasValue()) return 0;
var s = that.value+'';
if (s.match(/em$/)) return that.numValue() * this.EM(viewPort);
if (s.match(/ex$/)) return that.numValue() * this.EM(viewPort) / 2.0;
if (s.match(/px$/)) return that.numValue();
if (s.match(/pt$/)) return that.numValue() * 1.25;
if (s.match(/pc$/)) return that.numValue() * 15;
if (s.match(/cm$/)) return that.numValue() * this.DPI(viewPort) / 2.54;
if (s.match(/mm$/)) return that.numValue() * this.DPI(viewPort) / 25.4;
if (s.match(/in$/)) return that.numValue() * this.DPI(viewPort);
if (s.match(/%$/)) return that.numValue() * svg.ViewPort.ComputeSize(viewPort);
return that.numValue();
}
}
// time extensions
this.Time = {
// get the time as milliseconds
toMilliseconds: function() {
if (!that.hasValue()) return 0;
var s = that.value+'';
if (s.match(/s$/)) return that.numValue() * 1000;
if (s.match(/ms$/)) return that.numValue();
return that.numValue();
}
}
// angle extensions
this.Angle = {
// get the angle as radians
toRadians: function() {
if (!that.hasValue()) return 0;
var s = that.value+'';
if (s.match(/deg$/)) return that.numValue() * (Math.PI / 180.0);
if (s.match(/grad$/)) return that.numValue() * (Math.PI / 200.0);
if (s.match(/rad$/)) return that.numValue();
return that.numValue() * (Math.PI / 180.0);
}
}
}
// fonts
svg.Font = new (function() {
this.Styles = ['normal','italic','oblique','inherit'];
this.Variants = ['normal','small-caps','inherit'];
this.Weights = ['normal','bold','bolder','lighter','100','200','300','400','500','600','700','800','900','inherit'];
this.CreateFont = function(fontStyle, fontVariant, fontWeight, fontSize, fontFamily, inherit) {
var f = inherit != null ? this.Parse(inherit) : this.CreateFont('', '', '', '', '', svg.ctx.font);
return {
fontFamily: fontFamily || f.fontFamily,
fontSize: fontSize || f.fontSize,
fontStyle: fontStyle || f.fontStyle,
fontWeight: fontWeight || f.fontWeight,
fontVariant: fontVariant || f.fontVariant,
toString: function () { return [this.fontStyle, this.fontVariant, this.fontWeight, this.fontSize, this.fontFamily].join(' ') }
}
}
var that = this;
this.Parse = function(s) {
var f = {};
var d = svg.trim(svg.compressSpaces(s || '')).split(' ');
var set = { fontSize: false, fontStyle: false, fontWeight: false, fontVariant: false }
var ff = '';
for (var i=0; i<d.length; i++) {
if (!set.fontStyle && that.Styles.indexOf(d[i]) != -1) { if (d[i] != 'inherit') f.fontStyle = d[i]; set.fontStyle = true; }
else if (!set.fontVariant && that.Variants.indexOf(d[i]) != -1) { if (d[i] != 'inherit') f.fontVariant = d[i]; set.fontStyle = set.fontVariant = true; }
else if (!set.fontWeight && that.Weights.indexOf(d[i]) != -1) { if (d[i] != 'inherit') f.fontWeight = d[i]; set.fontStyle = set.fontVariant = set.fontWeight = true; }
else if (!set.fontSize) { if (d[i] != 'inherit') f.fontSize = d[i].split('/')[0]; set.fontStyle = set.fontVariant = set.fontWeight = set.fontSize = true; }
else { if (d[i] != 'inherit') ff += d[i]; }
} if (ff != '') f.fontFamily = ff;
return f;
}
});
// points and paths
svg.ToNumberArray = function(s) {
var a = svg.trim(svg.compressSpaces((s || '').replace(/,/g, ' '))).split(' ');
for (var i=0; i<a.length; i++) {
a[i] = parseFloat(a[i]);
}
return a;
}
svg.Point = function(x, y) {
this.x = x;
this.y = y;
this.angleTo = function(p) {
return Math.atan2(p.y - this.y, p.x - this.x);
}
this.applyTransform = function(v) {
var xp = this.x * v[0] + this.y * v[2] + v[4];
var yp = this.x * v[1] + this.y * v[3] + v[5];
this.x = xp;
this.y = yp;
}
}
svg.CreatePoint = function(s) {
var a = svg.ToNumberArray(s);
return new svg.Point(a[0], a[1]);
}
svg.CreatePath = function(s) {
var a = svg.ToNumberArray(s);
var path = [];
for (var i=0; i<a.length; i+=2) {
path.push(new svg.Point(a[i], a[i+1]));
}
return path;
}
// bounding box
svg.BoundingBox = function(x1, y1, x2, y2) { // pass in initial points if you want
this.x1 = Number.NaN;
this.y1 = Number.NaN;
this.x2 = Number.NaN;
this.y2 = Number.NaN;
this.x = function() { return this.x1; }
this.y = function() { return this.y1; }
this.width = function() { return this.x2 - this.x1; }
this.height = function() { return this.y2 - this.y1; }
this.addPoint = function(x, y) {
if (x != null) {
if (isNaN(this.x1) || isNaN(this.x2)) {
this.x1 = x;
this.x2 = x;
}
if (x < this.x1) this.x1 = x;
if (x > this.x2) this.x2 = x;
}
if (y != null) {
if (isNaN(this.y1) || isNaN(this.y2)) {
this.y1 = y;
this.y2 = y;
}
if (y < this.y1) this.y1 = y;
if (y > this.y2) this.y2 = y;
}
}
this.addX = function(x) { this.addPoint(x, null); }
this.addY = function(y) { this.addPoint(null, y); }
this.addBoundingBox = function(bb) {
this.addPoint(bb.x1, bb.y1);
this.addPoint(bb.x2, bb.y2);
}
this.addQuadraticCurve = function(p0x, p0y, p1x, p1y, p2x, p2y) {
var cp1x = p0x + 2/3 * (p1x - p0x); // CP1 = QP0 + 2/3 *(QP1-QP0)
var cp1y = p0y + 2/3 * (p1y - p0y); // CP1 = QP0 + 2/3 *(QP1-QP0)
var cp2x = cp1x + 1/3 * (p2x - p0x); // CP2 = CP1 + 1/3 *(QP2-QP0)
var cp2y = cp1y + 1/3 * (p2y - p0y); // CP2 = CP1 + 1/3 *(QP2-QP0)
this.addBezierCurve(p0x, p0y, cp1x, cp2x, cp1y, cp2y, p2x, p2y);
}
this.addBezierCurve = function(p0x, p0y, p1x, p1y, p2x, p2y, p3x, p3y) {
// from http://blog.hackers-cafe.net/2009/06/how-to-calculate-bezier-curves-bounding.html
var p0 = [p0x, p0y], p1 = [p1x, p1y], p2 = [p2x, p2y], p3 = [p3x, p3y];
this.addPoint(p0[0], p0[1]);
this.addPoint(p3[0], p3[1]);
for (i=0; i<=1; i++) {
var f = function(t) {
return Math.pow(1-t, 3) * p0[i]
+ 3 * Math.pow(1-t, 2) * t * p1[i]
+ 3 * (1-t) * Math.pow(t, 2) * p2[i]
+ Math.pow(t, 3) * p3[i];
}
var b = 6 * p0[i] - 12 * p1[i] + 6 * p2[i];
var a = -3 * p0[i] + 9 * p1[i] - 9 * p2[i] + 3 * p3[i];
var c = 3 * p1[i] - 3 * p0[i];
if (a == 0) {
if (b == 0) continue;
var t = -c / b;
if (0 < t && t < 1) {
if (i == 0) this.addX(f(t));
if (i == 1) this.addY(f(t));
}
continue;
}
var b2ac = Math.pow(b, 2) - 4 * c * a;
if (b2ac < 0) continue;
var t1 = (-b + Math.sqrt(b2ac)) / (2 * a);
if (0 < t1 && t1 < 1) {
if (i == 0) this.addX(f(t1));
if (i == 1) this.addY(f(t1));
}
var t2 = (-b - Math.sqrt(b2ac)) / (2 * a);
if (0 < t2 && t2 < 1) {
if (i == 0) this.addX(f(t2));
if (i == 1) this.addY(f(t2));
}
}
}
this.isPointInBox = function(x, y) {
return (this.x1 <= x && x <= this.x2 && this.y1 <= y && y <= this.y2);
}
this.addPoint(x1, y1);
this.addPoint(x2, y2);
}
// transforms
svg.Transform = function(v) {
var that = this;
this.Type = {}
// translate
this.Type.translate = function(s) {
this.p = svg.CreatePoint(s);
this.apply = function(ctx) {
ctx.translate(this.p.x || 0.0, this.p.y || 0.0);
}
this.applyToPoint = function(p) {
p.applyTransform([1, 0, 0, 1, this.p.x || 0.0, this.p.y || 0.0]);
}
}
// rotate
this.Type.rotate = function(s) {
var a = svg.ToNumberArray(s);
this.angle = new svg.Property('angle', a[0]);
this.cx = a[1] || 0;
this.cy = a[2] || 0;
this.apply = function(ctx) {
ctx.translate(this.cx, this.cy);
ctx.rotate(this.angle.Angle.toRadians());
ctx.translate(-this.cx, -this.cy);
}
this.applyToPoint = function(p) {
var a = this.angle.Angle.toRadians();
p.applyTransform([1, 0, 0, 1, this.p.x || 0.0, this.p.y || 0.0]);
p.applyTransform([Math.cos(a), Math.sin(a), -Math.sin(a), Math.cos(a), 0, 0]);
p.applyTransform([1, 0, 0, 1, -this.p.x || 0.0, -this.p.y || 0.0]);
}
}
this.Type.scale = function(s) {
this.p = svg.CreatePoint(s);
this.apply = function(ctx) {
ctx.scale(this.p.x || 1.0, this.p.y || this.p.x || 1.0);
}
this.applyToPoint = function(p) {
p.applyTransform([this.p.x || 0.0, 0, 0, this.p.y || 0.0, 0, 0]);
}
}
this.Type.matrix = function(s) {
this.m = svg.ToNumberArray(s);
this.apply = function(ctx) {
ctx.transform(this.m[0], this.m[1], this.m[2], this.m[3], this.m[4], this.m[5]);
}
this.applyToPoint = function(p) {
p.applyTransform(this.m);
}
}
this.Type.SkewBase = function(s) {
this.base = that.Type.matrix;
this.base(s);
this.angle = new svg.Property('angle', s);
}
this.Type.SkewBase.prototype = new this.Type.matrix;
this.Type.skewX = function(s) {
this.base = that.Type.SkewBase;
this.base(s);
this.m = [1, 0, Math.tan(this.angle.Angle.toRadians()), 1, 0, 0];
}
this.Type.skewX.prototype = new this.Type.SkewBase;
this.Type.skewY = function(s) {
this.base = that.Type.SkewBase;
this.base(s);
this.m = [1, Math.tan(this.angle.Angle.toRadians()), 0, 1, 0, 0];
}
this.Type.skewY.prototype = new this.Type.SkewBase;
this.transforms = [];
this.apply = function(ctx) {
for (var i=0; i<this.transforms.length; i++) {
this.transforms[i].apply(ctx);
}
}
this.applyToPoint = function(p) {
for (var i=0; i<this.transforms.length; i++) {
this.transforms[i].applyToPoint(p);
}
}
var data = v.split(/\s(?=[a-z])/);
for (var i=0; i<data.length; i++) {
var type = data[i].split('(')[0];
var s = data[i].split('(')[1].replace(')','');
var transform = eval('new this.Type.' + type + '(s)');
this.transforms.push(transform);
}
}
// aspect ratio
svg.AspectRatio = function(ctx, aspectRatio, width, desiredWidth, height, desiredHeight, minX, minY, refX, refY) {
// aspect ratio - http://www.w3.org/TR/SVG/coords.html#PreserveAspectRatioAttribute
aspectRatio = svg.compressSpaces(aspectRatio);
aspectRatio = aspectRatio.replace(/^defer\s/,''); // ignore defer
var align = aspectRatio.split(' ')[0] || 'xMidYMid';
var meetOrSlice = aspectRatio.split(' ')[1] || 'meet';
// calculate scale
var scaleX = width / desiredWidth;
var scaleY = height / desiredHeight;
var scaleMin = Math.min(scaleX, scaleY);
var scaleMax = Math.max(scaleX, scaleY);
if (meetOrSlice == 'meet') { desiredWidth *= scaleMin; desiredHeight *= scaleMin; }
if (meetOrSlice == 'slice') { desiredWidth *= scaleMax; desiredHeight *= scaleMax; }
refX = new svg.Property('refX', refX);
refY = new svg.Property('refY', refY);
if (refX.hasValue() && refY.hasValue()) {
ctx.translate(-scaleMin * refX.Length.toPixels('x'), -scaleMin * refY.Length.toPixels('y'));
}
else {
// align
if (align.match(/^xMid/) && ((meetOrSlice == 'meet' && scaleMin == scaleY) || (meetOrSlice == 'slice' && scaleMax == scaleY))) ctx.translate(width / 2.0 - desiredWidth / 2.0, 0);
if (align.match(/YMid$/) && ((meetOrSlice == 'meet' && scaleMin == scaleX) || (meetOrSlice == 'slice' && scaleMax == scaleX))) ctx.translate(0, height / 2.0 - desiredHeight / 2.0);
if (align.match(/^xMax/) && ((meetOrSlice == 'meet' && scaleMin == scaleY) || (meetOrSlice == 'slice' && scaleMax == scaleY))) ctx.translate(width - desiredWidth, 0);
if (align.match(/YMax$/) && ((meetOrSlice == 'meet' && scaleMin == scaleX) || (meetOrSlice == 'slice' && scaleMax == scaleX))) ctx.translate(0, height - desiredHeight);
}
// scale
if (align == 'none') ctx.scale(scaleX, scaleY);
else if (meetOrSlice == 'meet') ctx.scale(scaleMin, scaleMin);
else if (meetOrSlice == 'slice') ctx.scale(scaleMax, scaleMax);
// translate
ctx.translate(minX == null ? 0 : -minX, minY == null ? 0 : -minY);
}
// elements
svg.Element = {}
svg.Element.ElementBase = function(node) {
this.attributes = {};
this.styles = {};
this.children = [];
// get or create attribute
this.attribute = function(name, createIfNotExists) {
var a = this.attributes[name];
if (a != null) return a;
a = new svg.Property(name, '');
if (createIfNotExists == true) this.attributes[name] = a;
return a;
}
// get or create style
this.style = function(name, createIfNotExists) {
var s = this.styles[name];
if (s != null) return s;
var a = this.attribute(name);
if (a != null && a.hasValue()) {
return a;
}
s = new svg.Property(name, '');
if (createIfNotExists == true) this.styles[name] = s;
return s;
}
// base render
this.render = function(ctx) {
// don't render display=none
if (this.attribute('display').value == 'none') return;
ctx.save();
this.setContext(ctx);
this.renderChildren(ctx);
this.clearContext(ctx);
ctx.restore();
}
// base set context
this.setContext = function(ctx) {
// OVERRIDE ME!
}
// base clear context
this.clearContext = function(ctx) {
// OVERRIDE ME!
}
// base render children
this.renderChildren = function(ctx) {
for (var i=0; i<this.children.length; i++) {
this.children[i].render(ctx);
}
}
this.addChild = function(childNode, create) {
var child = childNode;
if (create) child = svg.CreateElement(childNode);
child.parent = this;
this.children.push(child);
}
if (node != null && node.nodeType == 1) { //ELEMENT_NODE
// add children
for (var i=0; i<node.childNodes.length; i++) {
var childNode = node.childNodes[i];
if (childNode.nodeType == 1) this.addChild(childNode, true); //ELEMENT_NODE
}
// add attributes
for (var i=0; i<node.attributes.length; i++) {
var attribute = node.attributes[i];
this.attributes[attribute.nodeName] = new svg.Property(attribute.nodeName, attribute.nodeValue);
}
// add tag styles
var styles = svg.Styles[this.type];
if (styles != null) {
for (var name in styles) {
this.styles[name] = styles[name];
}
}
// add class styles
if (this.attribute('class').hasValue()) {
var classes = svg.compressSpaces(this.attribute('class').value).split(' ');
for (var j=0; j<classes.length; j++) {
styles = svg.Styles['.'+classes[j]];
if (styles != null) {
for (var name in styles) {
this.styles[name] = styles[name];
}
}
}
}
// add inline styles
if (this.attribute('style').hasValue()) {
var styles = this.attribute('style').value.split(';');
for (var i=0; i<styles.length; i++) {
if (svg.trim(styles[i]) != '') {
var style = styles[i].split(':');
var name = svg.trim(style[0]);
var value = svg.trim(style[1]);
this.styles[name] = new svg.Property(name, value);
}
}
}
// add id
if (this.attribute('id').hasValue()) {
if (svg.Definitions[this.attribute('id').value] == null) {
svg.Definitions[this.attribute('id').value] = this;
}
}
}
}
svg.Element.RenderedElementBase = function(node) {
this.base = svg.Element.ElementBase;
this.base(node);
this.setContext = function(ctx) {
// fill
if (this.style('fill').Definition.isUrl()) {
var fs = this.style('fill').Definition.getFillStyle(this);
if (fs != null) ctx.fillStyle = fs;
}
else if (this.style('fill').hasValue()) {
var fillStyle = this.style('fill');
if (this.style('fill-opacity').hasValue()) fillStyle = fillStyle.Color.addOpacity(this.style('fill-opacity').value);
ctx.fillStyle = (fillStyle.value == 'none' ? 'rgba(0,0,0,0)' : fillStyle.value);
}
// stroke
if (this.style('stroke').Definition.isUrl()) {
var fs = this.style('stroke').Definition.getFillStyle(this);
if (fs != null) ctx.strokeStyle = fs;
}
else if (this.style('stroke').hasValue()) {
var strokeStyle = this.style('stroke');
if (this.style('stroke-opacity').hasValue()) strokeStyle = strokeStyle.Color.addOpacity(this.style('stroke-opacity').value);
ctx.strokeStyle = (strokeStyle.value == 'none' ? 'rgba(0,0,0,0)' : strokeStyle.value);
}
if (this.style('stroke-width').hasValue()) ctx.lineWidth = this.style('stroke-width').Length.toPixels();
if (this.style('stroke-linecap').hasValue()) ctx.lineCap = this.style('stroke-linecap').value;
if (this.style('stroke-linejoin').hasValue()) ctx.lineJoin = this.style('stroke-linejoin').value;
if (this.style('stroke-miterlimit').hasValue()) ctx.miterLimit = this.style('stroke-miterlimit').value;
// font
if (typeof(ctx.font) != 'undefined') {
ctx.font = svg.Font.CreateFont(
this.style('font-style').value,
this.style('font-variant').value,
this.style('font-weight').value,
this.style('font-size').hasValue() ? this.style('font-size').Length.toPixels() + 'px' : '',
this.style('font-family').value).toString();
}
// transform
if (this.attribute('transform').hasValue()) {
var transform = new svg.Transform(this.attribute('transform').value);
transform.apply(ctx);
}
// clip
if (this.attribute('clip-path').hasValue()) {
var clip = this.attribute('clip-path').Definition.getDefinition();
if (clip != null) clip.apply(ctx);
}
// opacity
if (this.style('opacity').hasValue()) {
ctx.globalAlpha = this.style('opacity').numValue();
}
}
}
svg.Element.RenderedElementBase.prototype = new svg.Element.ElementBase;
svg.Element.PathElementBase = function(node) {
this.base = svg.Element.RenderedElementBase;
this.base(node);
this.path = function(ctx) {
if (ctx != null) ctx.beginPath();
return new svg.BoundingBox();
}
this.renderChildren = function(ctx) {
this.path(ctx);
svg.Mouse.checkPath(this, ctx);
if (ctx.fillStyle != '') ctx.fill();
if (ctx.strokeStyle != '') ctx.stroke();
var markers = this.getMarkers();
if (markers != null) {
if (this.attribute('marker-start').Definition.isUrl()) {
var marker = this.attribute('marker-start').Definition.getDefinition();
marker.render(ctx, markers[0][0], markers[0][1]);
}
if (this.attribute('marker-mid').Definition.isUrl()) {
var marker = this.attribute('marker-mid').Definition.getDefinition();
for (var i=1;i<markers.length-1;i++) {
marker.render(ctx, markers[i][0], markers[i][1]);
}
}
if (this.attribute('marker-end').Definition.isUrl()) {
var marker = this.attribute('marker-end').Definition.getDefinition();
marker.render(ctx, markers[markers.length-1][0], markers[markers.length-1][1]);
}
}
}
this.getBoundingBox = function() {
return this.path();
}
this.getMarkers = function() {
return null;
}
}
svg.Element.PathElementBase.prototype = new svg.Element.RenderedElementBase;
// svg element
svg.Element.svg = function(node) {
this.base = svg.Element.RenderedElementBase;
this.base(node);
this.baseClearContext = this.clearContext;
this.clearContext = function(ctx) {
this.baseClearContext(ctx);
svg.ViewPort.RemoveCurrent();
}
this.baseSetContext = this.setContext;
this.setContext = function(ctx) {
this.baseSetContext(ctx);
// create new view port
if (this.attribute('x').hasValue() && this.attribute('y').hasValue()) {
ctx.translate(this.attribute('x').Length.toPixels('x'), this.attribute('y').Length.toPixels('y'));
}
var width = svg.ViewPort.width();
var height = svg.ViewPort.height();
if (this.attribute('width').hasValue() && this.attribute('height').hasValue()) {
width = this.attribute('width').Length.toPixels('x');
height = this.attribute('height').Length.toPixels('y');
var x = 0;
var y = 0;
if (this.attribute('refX').hasValue() && this.attribute('refY').hasValue()) {
x = -this.attribute('refX').Length.toPixels('x');
y = -this.attribute('refY').Length.toPixels('y');
}
ctx.beginPath();
ctx.moveTo(x, y);
ctx.lineTo(width, y);
ctx.lineTo(width, height);
ctx.lineTo(x, height);
ctx.closePath();
ctx.clip();
}
svg.ViewPort.SetCurrent(width, height);
// viewbox
if (this.attribute('viewBox').hasValue()) {
var viewBox = svg.ToNumberArray(this.attribute('viewBox').value);
var minX = viewBox[0];
var minY = viewBox[1];
width = viewBox[2];
height = viewBox[3];
svg.AspectRatio(ctx,
this.attribute('preserveAspectRatio').value,
svg.ViewPort.width(),
width,
svg.ViewPort.height(),
height,
minX,
minY,
this.attribute('refX').value,
this.attribute('refY').value);
svg.ViewPort.RemoveCurrent();
svg.ViewPort.SetCurrent(viewBox[2], viewBox[3]);
}
// initial values
ctx.strokeStyle = 'rgba(0,0,0,0)';
ctx.lineCap = 'butt';
ctx.lineJoin = 'miter';
ctx.miterLimit = 4;
}
}
svg.Element.svg.prototype = new svg.Element.RenderedElementBase;
// rect element
svg.Element.rect = function(node) {
this.base = svg.Element.PathElementBase;
this.base(node);
this.path = function(ctx) {
var x = this.attribute('x').Length.toPixels('x');
var y = this.attribute('y').Length.toPixels('y');
var width = this.attribute('width').Length.toPixels('x');
var height = this.attribute('height').Length.toPixels('y');
var rx = this.attribute('rx').Length.toPixels('x');
var ry = this.attribute('ry').Length.toPixels('y');
if (this.attribute('rx').hasValue() && !this.attribute('ry').hasValue()) ry = rx;
if (this.attribute('ry').hasValue() && !this.attribute('rx').hasValue()) rx = ry;
if (ctx != null) {
ctx.beginPath();
ctx.moveTo(x + rx, y);
ctx.lineTo(x + width - rx, y);
ctx.quadraticCurveTo(x + width, y, x + width, y + ry)
ctx.lineTo(x + width, y + height - ry);
ctx.quadraticCurveTo(x + width, y + height, x + width - rx, y + height)
ctx.lineTo(x + rx, y + height);
ctx.quadraticCurveTo(x, y + height, x, y + height - ry)
ctx.lineTo(x, y + ry);
ctx.quadraticCurveTo(x, y, x + rx, y)
ctx.closePath();
}
return new svg.BoundingBox(x, y, x + width, y + height);
}
}
svg.Element.rect.prototype = new svg.Element.PathElementBase;
// circle element
svg.Element.circle = function(node) {
this.base = svg.Element.PathElementBase;
this.base(node);
this.path = function(ctx) {
var cx = this.attribute('cx').Length.toPixels('x');
var cy = this.attribute('cy').Length.toPixels('y');
var r = this.attribute('r').Length.toPixels();
if (ctx != null) {
ctx.beginPath();
ctx.arc(cx, cy, r, 0, Math.PI * 2, true);
ctx.closePath();
}
return new svg.BoundingBox(cx - r, cy - r, cx + r, cy + r);
}
}
svg.Element.circle.prototype = new svg.Element.PathElementBase;
// ellipse element
svg.Element.ellipse = function(node) {
this.base = svg.Element.PathElementBase;
this.base(node);
this.path = function(ctx) {
var KAPPA = 4 * ((Math.sqrt(2) - 1) / 3);
var rx = this.attribute('rx').Length.toPixels('x');
var ry = this.attribute('ry').Length.toPixels('y');
var cx = this.attribute('cx').Length.toPixels('x');
var cy = this.attribute('cy').Length.toPixels('y');
if (ctx != null) {
ctx.beginPath();
ctx.moveTo(cx, cy - ry);
ctx.bezierCurveTo(cx + (KAPPA * rx), cy - ry, cx + rx, cy - (KAPPA * ry), cx + rx, cy);
ctx.bezierCurveTo(cx + rx, cy + (KAPPA * ry), cx + (KAPPA * rx), cy + ry, cx, cy + ry);
ctx.bezierCurveTo(cx - (KAPPA * rx), cy + ry, cx - rx, cy + (KAPPA * ry), cx - rx, cy);
ctx.bezierCurveTo(cx - rx, cy - (KAPPA * ry), cx - (KAPPA * rx), cy - ry, cx, cy - ry);
ctx.closePath();
}
return new svg.BoundingBox(cx - rx, cy - ry, cx + rx, cy + ry);
}
}
svg.Element.ellipse.prototype = new svg.Element.PathElementBase;
// line element
svg.Element.line = function(node) {
this.base = svg.Element.PathElementBase;
this.base(node);
this.getPoints = function() {
return [
new svg.Point(this.attribute('x1').Length.toPixels('x'), this.attribute('y1').Length.toPixels('y')),
new svg.Point(this.attribute('x2').Length.toPixels('x'), this.attribute('y2').Length.toPixels('y'))];
}
this.path = function(ctx) {
var points = this.getPoints();
if (ctx != null) {
ctx.beginPath();
ctx.moveTo(points[0].x, points[0].y);
ctx.lineTo(points[1].x, points[1].y);
}
return new svg.BoundingBox(points[0].x, points[0].y, points[1].x, points[1].y);
}
this.getMarkers = function() {
var points = this.getPoints();
var a = points[0].angleTo(points[1]);
return [[points[0], a], [points[1], a]];
}
}
svg.Element.line.prototype = new svg.Element.PathElementBase;
// polyline element
svg.Element.polyline = function(node) {
this.base = svg.Element.PathElementBase;
this.base(node);
this.points = svg.CreatePath(this.attribute('points').value);
this.path = function(ctx) {
var bb = new svg.BoundingBox(this.points[0].x, this.points[0].y);
if (ctx != null) {
ctx.beginPath();
ctx.moveTo(this.points[0].x, this.points[0].y);
}
for (var i=1; i<this.points.length; i++) {
bb.addPoint(this.points[i].x, this.points[i].y);
if (ctx != null) ctx.lineTo(this.points[i].x, this.points[i].y);
}
return bb;
}
this.getMarkers = function() {
var markers = [];
for (var i=0; i<this.points.length - 1; i++) {
markers.push([this.points[i], this.points[i].angleTo(this.points[i+1])]);
}
markers.push([this.points[this.points.length-1], markers[markers.length-1][1]]);
return markers;
}
}
svg.Element.polyline.prototype = new svg.Element.PathElementBase;
// polygon element
svg.Element.polygon = function(node) {
this.base = svg.Element.polyline;
this.base(node);
this.basePath = this.path;
this.path = function(ctx) {
var bb = this.basePath(ctx);
if (ctx != null) {
ctx.lineTo(this.points[0].x, this.points[0].y);
ctx.closePath();
}
return bb;
}
}
svg.Element.polygon.prototype = new svg.Element.polyline;
// path element
svg.Element.path = function(node) {
this.base = svg.Element.PathElementBase;
this.base(node);
var d = this.attribute('d').value;
// TODO: floating points, convert to real lexer based on http://www.w3.org/TR/SVG11/paths.html#PathDataBNF
d = d.replace(/,/gm,' '); // get rid of all commas
d = d.replace(/([MmZzLlHhVvCcSsQqTtAa])([MmZzLlHhVvCcSsQqTtAa])/gm,'$1 $2'); // separate commands from commands
d = d.replace(/([MmZzLlHhVvCcSsQqTtAa])([MmZzLlHhVvCcSsQqTtAa])/gm,'$1 $2'); // separate commands from commands
d = d.replace(/([MmZzLlHhVvCcSsQqTtAa])([^\s])/gm,'$1 $2'); // separate commands from points
d = d.replace(/([^\s])([MmZzLlHhVvCcSsQqTtAa])/gm,'$1 $2'); // separate commands from points
d = d.replace(/([0-9])([+\-])/gm,'$1 $2'); // separate digits when no comma
d = d.replace(/(\.[0-9]*)(\.)/gm,'$1 $2'); // separate digits when no comma
d = d.replace(/([Aa](\s+[0-9]+){3})\s+([01])\s*([01])/gm,'$1 $3 $4 '); // shorthand elliptical arc path syntax
d = svg.compressSpaces(d); // compress multiple spaces
d = svg.trim(d);
this.PathParser = new (function(d) {
this.tokens = d.split(' ');
this.reset = function() {
this.i = -1;
this.command = '';
this.previousCommand = '';
this.start = new svg.Point(0, 0);
this.control = new svg.Point(0, 0);
this.current = new svg.Point(0, 0);
this.points = [];
this.angles = [];
}
this.isEnd = function() {
return this.i >= this.tokens.length - 1;
}
this.isCommandOrEnd = function() {
if (this.isEnd()) return true;
return this.tokens[this.i + 1].match(/[A-Za-z]/) != null;
}
this.isRelativeCommand = function() {
return this.command == this.command.toLowerCase();
}
this.getToken = function() {
this.i = this.i + 1;
return this.tokens[this.i];
}
this.getScalar = function() {
return parseFloat(this.getToken());
}
this.nextCommand = function() {
this.previousCommand = this.command;
this.command = this.getToken();
}
this.getPoint = function() {
var p = new svg.Point(this.getScalar(), this.getScalar());
return this.makeAbsolute(p);
}
this.getAsControlPoint = function() {
var p = this.getPoint();
this.control = p;
return p;
}
this.getAsCurrentPoint = function() {
var p = this.getPoint();
this.current = p;
return p;
}
this.getReflectedControlPoint = function() {
if (this.previousCommand.toLowerCase() != 'c' && this.previousCommand.toLowerCase() != 's') {
return this.current;
}
// reflect point
var p = new svg.Point(2 * this.current.x - this.control.x, 2 * this.current.y - this.control.y);
return p;
}
this.makeAbsolute = function(p) {
if (this.isRelativeCommand()) {
p.x = this.current.x + p.x;
p.y = this.current.y + p.y;
}
return p;
}
this.addMarker = function(p, from) {
this.addMarkerAngle(p, from == null ? null : from.angleTo(p));
}
this.addMarkerAngle = function(p, a) {
this.points.push(p);
this.angles.push(a);
}
this.getMarkerPoints = function() { return this.points; }
this.getMarkerAngles = function() {
for (var i=0; i<this.angles.length; i++) {
if (this.angles[i] == null) {
for (var j=i+1; j<this.angles.length; j++) {
if (this.angles[j] != null) {
this.angles[i] = this.angles[j];
break;
}
}
}
}
return this.angles;
}
})(d);
this.path = function(ctx) {
var pp = this.PathParser;
pp.reset();
var bb = new svg.BoundingBox();
if (ctx != null) ctx.beginPath();
while (!pp.isEnd()) {
pp.nextCommand();
switch (pp.command.toUpperCase()) {
case 'M':
var p = pp.getAsCurrentPoint();
pp.addMarker(p);
bb.addPoint(p.x, p.y);
if (ctx != null) ctx.moveTo(p.x, p.y);
pp.start = pp.current;
while (!pp.isCommandOrEnd()) {
var p = pp.getAsCurrentPoint();
pp.addMarker(p);
bb.addPoint(p.x, p.y);
if (ctx != null) ctx.lineTo(p.x, p.y);
}
break;
case 'L':
while (!pp.isCommandOrEnd()) {
var c = pp.current;
var p = pp.getAsCurrentPoint();
pp.addMarker(p, c);
bb.addPoint(p.x, p.y);
if (ctx != null) ctx.lineTo(p.x, p.y);
}
break;
case 'H':
while (!pp.isCommandOrEnd()) {
var newP = new svg.Point((pp.isRelativeCommand() ? pp.current.x : 0) + pp.getScalar(), pp.current.y);
pp.addMarker(newP, pp.current);
pp.current = newP;
bb.addPoint(pp.current.x, pp.current.y);
if (ctx != null) ctx.lineTo(pp.current.x, pp.current.y);
}
break;
case 'V':
while (!pp.isCommandOrEnd()) {
var newP = new svg.Point(pp.current.x, (pp.isRelativeCommand() ? pp.current.y : 0) + pp.getScalar());
pp.addMarker(newP, pp.current);
pp.current = newP;
bb.addPoint(pp.current.x, pp.current.y);
if (ctx != null) ctx.lineTo(pp.current.x, pp.current.y);
}
break;
case 'C':
while (!pp.isCommandOrEnd()) {
var curr = pp.current;
var p1 = pp.getPoint();
var cntrl = pp.getAsControlPoint();
var cp = pp.getAsCurrentPoint();
pp.addMarker(cp, cntrl);
bb.addBezierCurve(curr.x, curr.y, p1.x, p1.y, cntrl.x, cntrl.y, cp.x, cp.y);
if (ctx != null) ctx.bezierCurveTo(p1.x, p1.y, cntrl.x, cntrl.y, cp.x, cp.y);
}
break;
case 'S':
while (!pp.isCommandOrEnd()) {
var curr = pp.current;
var p1 = pp.getReflectedControlPoint();
var cntrl = pp.getAsControlPoint();
var cp = pp.getAsCurrentPoint();
pp.addMarker(cp, cntrl);
bb.addBezierCurve(curr.x, curr.y, p1.x, p1.y, cntrl.x, cntrl.y, cp.x, cp.y);
if (ctx != null) ctx.bezierCurveTo(p1.x, p1.y, cntrl.x, cntrl.y, cp.x, cp.y);
}
break;
case 'Q':
while (!pp.isCommandOrEnd()) {
var curr = pp.current;
var cntrl = pp.getAsControlPoint();
var cp = pp.getAsCurrentPoint();
pp.addMarker(cp, cntrl);
bb.addQuadraticCurve(curr.x, curr.y, cntrl.x, cntrl.y, cp.x, cp.y);
if (ctx != null) ctx.quadraticCurveTo(cntrl.x, cntrl.y, cp.x, cp.y);
}
break;
case 'T':
while (!pp.isCommandOrEnd()) {
var curr = pp.current;
var cntrl = pp.getReflectedControlPoint();
pp.control = cntrl;
var cp = pp.getAsCurrentPoint();
pp.addMarker(cp, cntrl);
bb.addQuadraticCurve(curr.x, curr.y, cntrl.x, cntrl.y, cp.x, cp.y);
if (ctx != null) ctx.quadraticCurveTo(cntrl.x, cntrl.y, cp.x, cp.y);
}
break;
case 'A':
while (!pp.isCommandOrEnd()) {
var curr = pp.current;
var rx = pp.getScalar();
var ry = pp.getScalar();
var xAxisRotation = pp.getScalar() * (Math.PI / 180.0);
var largeArcFlag = pp.getScalar();
var sweepFlag = pp.getScalar();
var cp = pp.getAsCurrentPoint();
// Conversion from endpoint to center parameterization
// http://www.w3.org/TR/SVG11/implnote.html#ArcImplementationNotes
// x1', y1'
var currp = new svg.Point(
Math.cos(xAxisRotation) * (curr.x - cp.x) / 2.0 + Math.sin(xAxisRotation) * (curr.y - cp.y) / 2.0,
-Math.sin(xAxisRotation) * (curr.x - cp.x) / 2.0 + Math.cos(xAxisRotation) * (curr.y - cp.y) / 2.0
);
// adjust radii
var l = Math.pow(currp.x,2)/Math.pow(rx,2)+Math.pow(currp.y,2)/Math.pow(ry,2);
if (l > 1) {
rx *= Math.sqrt(l);
ry *= Math.sqrt(l);
}
// cx', cy'
var s = (largeArcFlag == sweepFlag ? -1 : 1) * Math.sqrt(
((Math.pow(rx,2)*Math.pow(ry,2))-(Math.pow(rx,2)*Math.pow(currp.y,2))-(Math.pow(ry,2)*Math.pow(currp.x,2))) /
(Math.pow(rx,2)*Math.pow(currp.y,2)+Math.pow(ry,2)*Math.pow(currp.x,2))
);
if (isNaN(s)) s = 0;
var cpp = new svg.Point(s * rx * currp.y / ry, s * -ry * currp.x / rx);
// cx, cy
var centp = new svg.Point(
(curr.x + cp.x) / 2.0 + Math.cos(xAxisRotation) * cpp.x - Math.sin(xAxisRotation) * cpp.y,
(curr.y + cp.y) / 2.0 + Math.sin(xAxisRotation) * cpp.x + Math.cos(xAxisRotation) * cpp.y
);
// vector magnitude
var m = function(v) { return Math.sqrt(Math.pow(v[0],2) + Math.pow(v[1],2)); }
// ratio between two vectors
var r = function(u, v) { return (u[0]*v[0]+u[1]*v[1]) / (m(u)*m(v)) }
// angle between two vectors
var a = function(u, v) { return (u[0]*v[1] < u[1]*v[0] ? -1 : 1) * Math.acos(r(u,v)); }
// initial angle
var a1 = a([1,0], [(currp.x-cpp.x)/rx,(currp.y-cpp.y)/ry]);
// angle delta
var u = [(currp.x-cpp.x)/rx,(currp.y-cpp.y)/ry];
var v = [(-currp.x-cpp.x)/rx,(-currp.y-cpp.y)/ry];
var ad = a(u, v);
if (r(u,v) <= -1) ad = Math.PI;
if (r(u,v) >= 1) ad = 0;
if (sweepFlag == 0 && ad > 0) ad = ad - 2 * Math.PI;
if (sweepFlag == 1 && ad < 0) ad = ad + 2 * Math.PI;
// for markers
var halfWay = new svg.Point(
centp.x - rx * Math.cos((a1 + ad) / 2),
centp.y - ry * Math.sin((a1 + ad) / 2)
);
pp.addMarkerAngle(halfWay, (a1 + ad) / 2 + (sweepFlag == 0 ? 1 : -1) * Math.PI / 2);
pp.addMarkerAngle(cp, ad + (sweepFlag == 0 ? 1 : -1) * Math.PI / 2);
bb.addPoint(cp.x, cp.y); // TODO: this is too naive, make it better
if (ctx != null) {
var r = rx > ry ? rx : ry;
var sx = rx > ry ? 1 : rx / ry;
var sy = rx > ry ? ry / rx : 1;
ctx.translate(centp.x, centp.y);
ctx.rotate(xAxisRotation);
ctx.scale(sx, sy);
ctx.arc(0, 0, r, a1, a1 + ad, 1 - sweepFlag);
ctx.scale(1/sx, 1/sy);
ctx.rotate(-xAxisRotation);
ctx.translate(-centp.x, -centp.y);
}
}
break;
case 'Z':
if (ctx != null) ctx.closePath();
pp.current = pp.start;
}
}
return bb;
}
this.getMarkers = function() {
var points = this.PathParser.getMarkerPoints();
var angles = this.PathParser.getMarkerAngles();
var markers = [];
for (var i=0; i<points.length; i++) {
markers.push([points[i], angles[i]]);
}
return markers;
}
}
svg.Element.path.prototype = new svg.Element.PathElementBase;
// pattern element
svg.Element.pattern = function(node) {
this.base = svg.Element.ElementBase;
this.base(node);
this.createPattern = function(ctx, element) {
// render me using a temporary svg element
var tempSvg = new svg.Element.svg();
tempSvg.attributes['viewBox'] = new svg.Property('viewBox', this.attribute('viewBox').value);
tempSvg.attributes['x'] = new svg.Property('x', this.attribute('x').value);
tempSvg.attributes['y'] = new svg.Property('y', this.attribute('y').value);
tempSvg.attributes['width'] = new svg.Property('width', this.attribute('width').value);
tempSvg.attributes['height'] = new svg.Property('height', this.attribute('height').value);
tempSvg.children = this.children;
var c = document.createElement('canvas');
c.width = this.attribute('width').Length.toPixels();
c.height = this.attribute('height').Length.toPixels();
tempSvg.render(c.getContext('2d'));
return ctx.createPattern(c, 'repeat');
}
}
svg.Element.pattern.prototype = new svg.Element.ElementBase;
// marker element
svg.Element.marker = function(node) {
this.base = svg.Element.ElementBase;
this.base(node);
this.baseRender = this.render;
this.render = function(ctx, point, angle) {
ctx.translate(point.x, point.y);
if (this.attribute('orient').valueOrDefault('auto') == 'auto') ctx.rotate(angle);
if (this.attribute('markerUnits').valueOrDefault('strokeWidth') == 'strokeWidth') ctx.scale(ctx.lineWidth, ctx.lineWidth);
ctx.save();
// render me using a temporary svg element
var tempSvg = new svg.Element.svg();
tempSvg.attributes['viewBox'] = new svg.Property('viewBox', this.attribute('viewBox').value);
tempSvg.attributes['refX'] = new svg.Property('refX', this.attribute('refX').value);
tempSvg.attributes['refY'] = new svg.Property('refY', this.attribute('refY').value);
tempSvg.attributes['width'] = new svg.Property('width', this.attribute('markerWidth').value);
tempSvg.attributes['height'] = new svg.Property('height', this.attribute('markerHeight').value);
tempSvg.attributes['fill'] = new svg.Property('fill', this.attribute('fill').valueOrDefault('black'));
tempSvg.attributes['stroke'] = new svg.Property('stroke', this.attribute('stroke').valueOrDefault('none'));
tempSvg.children = this.children;
tempSvg.render(ctx);
ctx.restore();
if (this.attribute('markerUnits').valueOrDefault('strokeWidth') == 'strokeWidth') ctx.scale(1/ctx.lineWidth, 1/ctx.lineWidth);
if (this.attribute('orient').valueOrDefault('auto') == 'auto') ctx.rotate(-angle);
ctx.translate(-point.x, -point.y);
}
}
svg.Element.marker.prototype = new svg.Element.ElementBase;
// definitions element
svg.Element.defs = function(node) {
this.base = svg.Element.ElementBase;
this.base(node);
this.render = function(ctx) {
// NOOP
}
}
svg.Element.defs.prototype = new svg.Element.ElementBase;
// base for gradients
svg.Element.GradientBase = function(node) {
this.base = svg.Element.ElementBase;
this.base(node);
this.gradientUnits = this.attribute('gradientUnits').valueOrDefault('objectBoundingBox');
this.stops = [];
for (var i=0; i<this.children.length; i++) {
var child = this.children[i];
this.stops.push(child);
}
this.getGradient = function() {
// OVERRIDE ME!
}
this.createGradient = function(ctx, element) {
var stopsContainer = this;
if (this.attribute('xlink:href').hasValue()) {
stopsContainer = this.attribute('xlink:href').Definition.getDefinition();
}
var g = this.getGradient(ctx, element);
for (var i=0; i<stopsContainer.stops.length; i++) {
g.addColorStop(stopsContainer.stops[i].offset, stopsContainer.stops[i].color);
}
return g;
}
}
svg.Element.GradientBase.prototype = new svg.Element.ElementBase;
// linear gradient element
svg.Element.linearGradient = function(node) {
this.base = svg.Element.GradientBase;
this.base(node);
this.getGradient = function(ctx, element) {
var bb = element.getBoundingBox();
var x1 = (this.gradientUnits == 'objectBoundingBox'
? bb.x() + bb.width() * this.attribute('x1').numValue()
: this.attribute('x1').Length.toPixels('x'));
var y1 = (this.gradientUnits == 'objectBoundingBox'
? bb.y() + bb.height() * this.attribute('y1').numValue()
: this.attribute('y1').Length.toPixels('y'));
var x2 = (this.gradientUnits == 'objectBoundingBox'
? bb.x() + bb.width() * this.attribute('x2').numValue()
: this.attribute('x2').Length.toPixels('x'));
var y2 = (this.gradientUnits == 'objectBoundingBox'
? bb.y() + bb.height() * this.attribute('y2').numValue()
: this.attribute('y2').Length.toPixels('y'));
var p1 = new svg.Point(x1, y1);
var p2 = new svg.Point(x2, y2);
if (this.attribute('gradientTransform').hasValue()) {
var transform = new svg.Transform(this.attribute('gradientTransform').value);
transform.applyToPoint(p1);
transform.applyToPoint(p2);
}
return ctx.createLinearGradient(p1.x, p1.y, p2.x, p2.y);
}
}
svg.Element.linearGradient.prototype = new svg.Element.GradientBase;
// radial gradient element
svg.Element.radialGradient = function(node) {
this.base = svg.Element.GradientBase;
this.base(node);
this.getGradient = function(ctx, element) {
var bb = element.getBoundingBox();
var cx = (this.gradientUnits == 'objectBoundingBox'
? bb.x() + bb.width() * this.attribute('cx').numValue()
: this.attribute('cx').Length.toPixels('x'));
var cy = (this.gradientUnits == 'objectBoundingBox'
? bb.y() + bb.height() * this.attribute('cy').numValue()
: this.attribute('cy').Length.toPixels('y'));
var fx = cx;
var fy = cy;
if (this.attribute('fx').hasValue()) {
fx = (this.gradientUnits == 'objectBoundingBox'
? bb.x() + bb.width() * this.attribute('fx').numValue()
: this.attribute('fx').Length.toPixels('x'));
}
if (this.attribute('fy').hasValue()) {
fy = (this.gradientUnits == 'objectBoundingBox'
? bb.y() + bb.height() * this.attribute('fy').numValue()
: this.attribute('fy').Length.toPixels('y'));
}
var r = (this.gradientUnits == 'objectBoundingBox'
? (bb.width() + bb.height()) / 2.0 * this.attribute('r').numValue()
: this.attribute('r').Length.toPixels());
var c = new svg.Point(cx, cy);
var f = new svg.Point(fx, fy);
if (this.attribute('gradientTransform').hasValue()) {
var transform = new svg.Transform(this.attribute('gradientTransform').value);
transform.applyToPoint(c);
transform.applyToPoint(f);
}
return ctx.createRadialGradient(f.x, f.y, 0, c.x, c.y, r);
}
}
svg.Element.radialGradient.prototype = new svg.Element.GradientBase;
// gradient stop element
svg.Element.stop = function(node) {
this.base = svg.Element.ElementBase;
this.base(node);
this.offset = this.attribute('offset').numValue();
var stopColor = this.style('stop-color');
if (this.style('stop-opacity').hasValue()) stopColor = stopColor.Color.addOpacity(this.style('stop-opacity').value);
this.color = stopColor.value;
}
svg.Element.stop.prototype = new svg.Element.ElementBase;
// animation base element
svg.Element.AnimateBase = function(node) {
this.base = svg.Element.ElementBase;
this.base(node);
svg.Animations.push(this);
this.duration = 0.0;
this.begin = this.attribute('begin').Time.toMilliseconds();
this.maxDuration = this.begin + this.attribute('dur').Time.toMilliseconds();
this.getProperty = function() {
var attributeType = this.attribute('attributeType').value;
var attributeName = this.attribute('attributeName').value;
if (attributeType == 'CSS') {
return this.parent.style(attributeName, true);
}
return this.parent.attribute(attributeName, true);
};
this.initialValue = null;
this.removed = false;
this.calcValue = function() {
// OVERRIDE ME!
return '';
}
this.update = function(delta) {
// set initial value
if (this.initialValue == null) {
this.initialValue = this.getProperty().value;
}
// if we're past the end time
if (this.duration > this.maxDuration) {
// loop for indefinitely repeating animations
if (this.attribute('repeatCount').value == 'indefinite') {
this.duration = 0.0
}
else if (this.attribute('fill').valueOrDefault('remove') == 'remove' && !this.removed) {
this.removed = true;
this.getProperty().value = this.initialValue;
return true;
}
else {
return false; // no updates made
}
}
this.duration = this.duration + delta;
// if we're past the begin time
var updated = false;
if (this.begin < this.duration) {
var newValue = this.calcValue(); // tween
if (this.attribute('type').hasValue()) {
// for transform, etc.
var type = this.attribute('type').value;
newValue = type + '(' + newValue + ')';
}
this.getProperty().value = newValue;
updated = true;
}
return updated;
}
// fraction of duration we've covered
this.progress = function() {
return ((this.duration - this.begin) / (this.maxDuration - this.begin));
}
}
svg.Element.AnimateBase.prototype = new svg.Element.ElementBase;
// animate element
svg.Element.animate = function(node) {
this.base = svg.Element.AnimateBase;
this.base(node);
this.calcValue = function() {
var from = this.attribute('from').numValue();
var to = this.attribute('to').numValue();
// tween value linearly
return from + (to - from) * this.progress();
};
}
svg.Element.animate.prototype = new svg.Element.AnimateBase;
// animate color element
svg.Element.animateColor = function(node) {
this.base = svg.Element.AnimateBase;
this.base(node);
this.calcValue = function() {
var from = new RGBColor(this.attribute('from').value);
var to = new RGBColor(this.attribute('to').value);
if (from.ok && to.ok) {
// tween color linearly
var r = from.r + (to.r - from.r) * this.progress();
var g = from.g + (to.g - from.g) * this.progress();
var b = from.b + (to.b - from.b) * this.progress();
return 'rgb('+parseInt(r,10)+','+parseInt(g,10)+','+parseInt(b,10)+')';
}
return this.attribute('from').value;
};
}
svg.Element.animateColor.prototype = new svg.Element.AnimateBase;
// animate transform element
svg.Element.animateTransform = function(node) {
this.base = svg.Element.animate;
this.base(node);
}
svg.Element.animateTransform.prototype = new svg.Element.animate;
// text element
svg.Element.text = function(node) {
this.base = svg.Element.RenderedElementBase;
this.base(node);
if (node != null) {
// add children
this.children = [];
for (var i=0; i<node.childNodes.length; i++) {
var childNode = node.childNodes[i];
if (childNode.nodeType == 1) { // capture tspan and tref nodes
this.addChild(childNode, true);
}
else if (childNode.nodeType == 3) { // capture text
this.addChild(new svg.Element.tspan(childNode), false);
}
}
}
this.baseSetContext = this.setContext;
this.setContext = function(ctx) {
this.baseSetContext(ctx);
if (this.attribute('text-anchor').hasValue()) {
var textAnchor = this.attribute('text-anchor').value;
ctx.textAlign = textAnchor == 'middle' ? 'center' : textAnchor;
}
if (this.attribute('alignment-baseline').hasValue()) ctx.textBaseline = this.attribute('alignment-baseline').value;
}
this.renderChildren = function(ctx) {
var x = this.attribute('x').Length.toPixels('x');
var y = this.attribute('y').Length.toPixels('y');
for (var i=0; i<this.children.length; i++) {
var child = this.children[i];
if (child.attribute('x').hasValue()) {
child.x = child.attribute('x').Length.toPixels('x');
}
else {
if (child.attribute('dx').hasValue()) x += child.attribute('dx').Length.toPixels('x');
child.x = x;
x += child.measureText(ctx);
}
if (child.attribute('y').hasValue()) {
child.y = child.attribute('y').Length.toPixels('y');
}
else {
if (child.attribute('dy').hasValue()) y += child.attribute('dy').Length.toPixels('y');
child.y = y;
}
child.render(ctx);
}
}
}
svg.Element.text.prototype = new svg.Element.RenderedElementBase;
// text base
svg.Element.TextElementBase = function(node) {
this.base = svg.Element.RenderedElementBase;
this.base(node);
this.renderChildren = function(ctx) {
ctx.fillText(svg.compressSpaces(this.getText()), this.x, this.y);
}
this.getText = function() {
// OVERRIDE ME
}
this.measureText = function(ctx) {
var textToMeasure = svg.compressSpaces(this.getText());
if (!ctx.measureText) return textToMeasure.length * 10;
return ctx.measureText(textToMeasure).width;
}
}
svg.Element.TextElementBase.prototype = new svg.Element.RenderedElementBase;
// tspan
svg.Element.tspan = function(node) {
this.base = svg.Element.TextElementBase;
this.base(node);
// TEXT ELEMENT
this.text = node.nodeType == 3 ? node.nodeValue : node.childNodes[0].nodeValue;
this.getText = function() {
return this.text;
}
}
svg.Element.tspan.prototype = new svg.Element.TextElementBase;
// tref
svg.Element.tref = function(node) {
this.base = svg.Element.TextElementBase;
this.base(node);
this.getText = function() {
var element = this.attribute('xlink:href').Definition.getDefinition();
if (element != null) return element.children[0].getText();
}
}
svg.Element.tref.prototype = new svg.Element.TextElementBase;
// a element
svg.Element.a = function(node) {
this.base = svg.Element.TextElementBase;
this.base(node);
this.hasText = true;
for (var i=0; i<node.childNodes.length; i++) {
if (node.childNodes[i].nodeType != 3) this.hasText = false;
}
// this might contain text
this.text = this.hasText ? node.childNodes[0].nodeValue : '';
this.getText = function() {
return this.text;
}
this.baseRenderChildren = this.renderChildren;
this.renderChildren = function(ctx) {
if (this.hasText) {
// render as text element
this.baseRenderChildren(ctx);
var fontSize = new svg.Property('fontSize', svg.Font.Parse(svg.ctx.font).fontSize);
svg.Mouse.checkBoundingBox(this, new svg.BoundingBox(this.x, this.y - fontSize.Length.toPixels('y'), this.x + this.measureText(ctx), this.y));
}
else {
// render as temporary group
var g = new svg.Element.g();
g.children = this.children;
g.parent = this;
g.render(ctx);
}
}
this.onclick = function() {
window.open(this.attribute('xlink:href').value);
}
this.onmousemove = function() {
svg.ctx.canvas.style.cursor = 'pointer';
}
}
svg.Element.a.prototype = new svg.Element.TextElementBase;
// image element
svg.Element.image = function(node) {
this.base = svg.Element.RenderedElementBase;
this.base(node);
svg.Images.push(this);
this.img = document.createElement('img');
this.loaded = false;
var that = this;
this.img.onload = function() { that.loaded = true; }
this.img.src = this.attribute('xlink:href').value;
this.renderChildren = function(ctx) {
var x = this.attribute('x').Length.toPixels('x');
var y = this.attribute('y').Length.toPixels('y');
var width = this.attribute('width').Length.toPixels('x');
var height = this.attribute('height').Length.toPixels('y');
if (width == 0 || height == 0) return;
ctx.save();
ctx.translate(x, y);
svg.AspectRatio(ctx,
this.attribute('preserveAspectRatio').value,
width,
this.img.width,
height,
this.img.height,
0,
0);
ctx.drawImage(this.img, 0, 0);
ctx.restore();
}
}
svg.Element.image.prototype = new svg.Element.RenderedElementBase;
// group element
svg.Element.g = function(node) {
this.base = svg.Element.RenderedElementBase;
this.base(node);
this.getBoundingBox = function() {
var bb = new svg.BoundingBox();
for (var i=0; i<this.children.length; i++) {
bb.addBoundingBox(this.children[i].getBoundingBox());
}
return bb;
};
}
svg.Element.g.prototype = new svg.Element.RenderedElementBase;
// symbol element
svg.Element.symbol = function(node) {
this.base = svg.Element.RenderedElementBase;
this.base(node);
}
svg.Element.symbol.prototype = new svg.Element.RenderedElementBase;
// style element
svg.Element.style = function(node) {
this.base = svg.Element.ElementBase;
this.base(node);
var css = node.childNodes[0].nodeValue;
css = css.replace(/(\/\*([^*]|[\r\n]|(\*+([^*\/]|[\r\n])))*\*+\/)|(\/\/.*)/gm, ''); // remove comments
css = svg.compressSpaces(css); // replace whitespace
var cssDefs = css.split('}');
for (var i=0; i<cssDefs.length; i++) {
if (svg.trim(cssDefs[i]) != '') {
var cssDef = cssDefs[i].split('{');
var cssClasses = cssDef[0].split(',');
var cssProps = cssDef[1].split(';');
for (var j=0; j<cssClasses.length; j++) {
var cssClass = svg.trim(cssClasses[j]);
if (cssClass != '') {
var props = {};
for (var k=0; k<cssProps.length; k++) {
var prop = cssProps[k].split(':');
var name = prop[0];
var value = prop[1];
if (name != null && value != null) {
props[svg.trim(prop[0])] = new svg.Property(svg.trim(prop[0]), svg.trim(prop[1]));
}
}
svg.Styles[cssClass] = props;
}
}
}
}
}
svg.Element.style.prototype = new svg.Element.ElementBase;
// use element
svg.Element.use = function(node) {
this.base = svg.Element.RenderedElementBase;
this.base(node);
this.baseSetContext = this.setContext;
this.setContext = function(ctx) {
this.baseSetContext(ctx);
if (this.attribute('x').hasValue()) ctx.translate(this.attribute('x').Length.toPixels('x'), 0);
if (this.attribute('y').hasValue()) ctx.translate(0, this.attribute('y').Length.toPixels('y'));
}
this.getDefinition = function() {
return this.attribute('xlink:href').Definition.getDefinition();
}
this.path = function(ctx) {
var element = this.getDefinition();
if (element != null) element.path(ctx);
}
this.renderChildren = function(ctx) {
var element = this.getDefinition();
if (element != null) element.render(ctx);
}
}
svg.Element.use.prototype = new svg.Element.RenderedElementBase;
// clip element
svg.Element.clipPath = function(node) {
this.base = svg.Element.ElementBase;
this.base(node);
this.apply = function(ctx) {
for (var i=0; i<this.children.length; i++) {
if (this.children[i].path) {
this.children[i].path(ctx);
ctx.clip();
}
}
}
}
svg.Element.clipPath.prototype = new svg.Element.ElementBase;
// title element, do nothing
svg.Element.title = function(node) {
}
svg.Element.title.prototype = new svg.Element.ElementBase;
// desc element, do nothing
svg.Element.desc = function(node) {
}
svg.Element.desc.prototype = new svg.Element.ElementBase;
svg.Element.MISSING = function(node) {
console.log('ERROR: Element \'' + node.nodeName + '\' not yet implemented.');
}
svg.Element.MISSING.prototype = new svg.Element.ElementBase;
// element factory
svg.CreateElement = function(node) {
var className = 'svg.Element.' + node.nodeName.replace(/^[^:]+:/,'');
if (!eval(className)) className = 'svg.Element.MISSING';
var e = eval('new ' + className + '(node)');
e.type = node.nodeName;
return e;
}
// load from url
svg.load = function(ctx, url) {
svg.loadXml(ctx, svg.ajax(url));
}
// load from xml
svg.loadXml = function(ctx, xml) {
svg.init(ctx);
var mapXY = function(p) {
var e = ctx.canvas;
while (e) {
p.x -= e.offsetLeft;
p.y -= e.offsetTop;
e = e.offsetParent;
}
if (window.scrollX) p.x += window.scrollX;
if (window.scrollY) p.y += window.scrollY;
return p;
}
// bind mouse
if (svg.opts == null || svg.opts['ignoreMouse'] != true) {
ctx.canvas.onclick = function(e) {
var p = mapXY(new svg.Point(e != null ? e.clientX : event.clientX, e != null ? e.clientY : event.clientY));
svg.Mouse.onclick(p.x, p.y);
};
ctx.canvas.onmousemove = function(e) {
var p = mapXY(new svg.Point(e != null ? e.clientX : event.clientX, e != null ? e.clientY : event.clientY));
svg.Mouse.onmousemove(p.x, p.y);
};
}
var dom = svg.parseXml(xml);
var e = svg.CreateElement(dom.documentElement);
// render loop
var isFirstRender = true;
var draw = function() {
if (svg.opts == null || svg.opts['ignoreDimensions'] != true) {
// set canvas size
if (e.style('width').hasValue()) {
ctx.canvas.width = e.style('width').Length.toPixels(ctx.canvas.parentNode.clientWidth);
}
if (e.style('height').hasValue()) {
ctx.canvas.height = e.style('height').Length.toPixels(ctx.canvas.parentNode.clientHeight);
}
}
svg.ViewPort.SetCurrent(ctx.canvas.clientWidth, ctx.canvas.clientHeight);
if (svg.opts != null && svg.opts['offsetX'] != null) e.attribute('x', true).value = svg.opts['offsetX'];
if (svg.opts != null && svg.opts['offsetY'] != null) e.attribute('y', true).value = svg.opts['offsetY'];
if (svg.opts != null && svg.opts['scaleWidth'] != null && svg.opts['scaleHeight'] != null) {
e.attribute('width', true).value = svg.opts['scaleWidth'];
e.attribute('height', true).value = svg.opts['scaleHeight'];
// REMOVED FOR android-ui-utils
// e.attribute('viewBox', true).value = '0 0 ' + ctx.canvas.clientWidth + ' ' + ctx.canvas.clientHeight;
e.attribute('preserveAspectRatio', true).value = 'none';
}
// clear and render
if (svg.opts == null || svg.opts['ignoreClear'] != true) {
ctx.clearRect(0, 0, ctx.canvas.clientWidth, ctx.canvas.clientHeight);
}
e.render(ctx);
if (isFirstRender) {
isFirstRender = false;
if (svg.opts != null && typeof(svg.opts['renderCallback']) == 'function') svg.opts['renderCallback']();
}
}
var waitingForImages = true;
if (svg.ImagesLoaded()) {
waitingForImages = false;
draw();
}
svg.intervalID = setInterval(function() {
var needUpdate = false;
if (waitingForImages && svg.ImagesLoaded()) {
waitingForImages = false;
needUpdate = true;
}
// need update from mouse events?
if (svg.opts == null || svg.opts['ignoreMouse'] != true) {
needUpdate = needUpdate | svg.Mouse.hasEvents();
}
// need update from animations?
if (svg.opts == null || svg.opts['ignoreAnimation'] != true) {
for (var i=0; i<svg.Animations.length; i++) {
needUpdate = needUpdate | svg.Animations[i].update(1000 / svg.FRAMERATE);
}
}
// need update from redraw?
if (svg.opts != null && typeof(svg.opts['forceRedraw']) == 'function') {
if (svg.opts['forceRedraw']() == true) needUpdate = true;
}
// render if needed
if (needUpdate) {
draw();
svg.Mouse.runEvents(); // run and clear our events
}
}, 1000 / svg.FRAMERATE);
}
svg.stop = function() {
if (svg.intervalID) {
clearInterval(svg.intervalID);
}
}
svg.Mouse = new (function() {
this.events = [];
this.hasEvents = function() { return this.events.length != 0; }
this.onclick = function(x, y) {
this.events.push({ type: 'onclick', x: x, y: y,
run: function(e) { if (e.onclick) e.onclick(); }
});
}
this.onmousemove = function(x, y) {
this.events.push({ type: 'onmousemove', x: x, y: y,
run: function(e) { if (e.onmousemove) e.onmousemove(); }
});
}
this.eventElements = [];
this.checkPath = function(element, ctx) {
for (var i=0; i<this.events.length; i++) {
var e = this.events[i];
if (ctx.isPointInPath && ctx.isPointInPath(e.x, e.y)) this.eventElements[i] = element;
}
}
this.checkBoundingBox = function(element, bb) {
for (var i=0; i<this.events.length; i++) {
var e = this.events[i];
if (bb.isPointInBox(e.x, e.y)) this.eventElements[i] = element;
}
}
this.runEvents = function() {
svg.ctx.canvas.style.cursor = '';
for (var i=0; i<this.events.length; i++) {
var e = this.events[i];
var element = this.eventElements[i];
while (element) {
e.run(element);
element = element.parent;
}
}
// done running, clear
this.events = [];
this.eventElements = [];
}
});
return svg;
}
})();
if (CanvasRenderingContext2D) {
CanvasRenderingContext2D.prototype.drawSvg = function(s, dx, dy, dw, dh) {
canvg(this.canvas, s, {
ignoreMouse: true,
ignoreAnimation: true,
ignoreDimensions: true,
ignoreClear: true,
offsetX: dx,
offsetY: dy,
scaleWidth: dw,
scaleHeight: dh
});
}
} | 07pratik-androidui | asset-studio/src/lib/canvg/canvg.js | JavaScript | asf20 | 71,341 |
/*
Downloadify: Client Side File Creation
JavaScript + Flash Library
Version: 0.2
Copyright (c) 2009 Douglas C. Neiner
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.
*/
(function(){
Downloadify = window.Downloadify = {
queue: {},
uid: new Date().getTime(),
getTextForSave: function(queue){
var obj = Downloadify.queue[queue];
if(obj) return obj.getData();
return "";
},
getFileNameForSave: function(queue){
var obj = Downloadify.queue[queue];
if(obj) return obj.getFilename();
return "";
},
getDataTypeForSave: function(queue){
var obj = Downloadify.queue[queue];
if(obj) return obj.getDataType();
return "";
},
saveComplete: function(queue){
var obj = Downloadify.queue[queue];
if(obj) obj.complete();
return true;
},
saveCancel: function(queue){
var obj = Downloadify.queue[queue];
if(obj) obj.cancel();
return true;
},
saveError: function(queue){
var obj = Downloadify.queue[queue];
if(obj) obj.error();
return true;
},
addToQueue: function(container){
Downloadify.queue[container.queue_name] = container;
},
// Concept adapted from: http://tinyurl.com/yzsyfto
// SWF object runs off of ID's, so this is the good way to get a unique ID
getUID: function(el){
if(el.id == "") el.id = 'downloadify_' + Downloadify.uid++;
return el.id;
}
};
Downloadify.create = function( idOrDOM, options ){
var el = (typeof(idOrDOM) == "string" ? document.getElementById(idOrDOM) : idOrDOM );
return new Downloadify.Container(el, options);
};
Downloadify.Container = function(el, options){
var base = this;
base.el = el;
base.enabled = true;
base.dataCallback = null;
base.filenameCallback = null;
base.data = null;
base.filename = null;
var init = function(){
base.options = options;
if( !base.options.append ) base.el.innerHTML = "";
base.flashContainer = document.createElement('span');
base.el.appendChild(base.flashContainer);
base.queue_name = Downloadify.getUID( base.flashContainer );
if( typeof(base.options.filename) === "function" )
base.filenameCallback = base.options.filename;
else if (base.options.filename)
base.filename = base.options.filename;
if( typeof(base.options.data) === "function" )
base.dataCallback = base.options.data;
else if (base.options.data)
base.data = base.options.data;
var flashVars = {
queue_name: base.queue_name,
width: base.options.width,
height: base.options.height
};
var params = {
allowScriptAccess: 'always'
};
var attributes = {
id: base.flashContainer.id,
name: base.flashContainer.id
};
if(base.options.enabled === false) base.enabled = false;
if(base.options.transparent === true) params.wmode = "transparent";
if(base.options.downloadImage) flashVars.downloadImage = base.options.downloadImage;
swfobject.embedSWF(base.options.swf, base.flashContainer.id, base.options.width, base.options.height, "10", null, flashVars, params, attributes );
Downloadify.addToQueue( base );
};
base.enable = function(){
var swf = document.getElementById(base.flashContainer.id);
swf.setEnabled(true);
base.enabled = true;
};
base.disable = function(){
var swf = document.getElementById(base.flashContainer.id);
swf.setEnabled(false);
base.enabled = false;
};
base.getData = function(){
if( !base.enabled ) return "";
if( base.dataCallback ) return base.dataCallback();
else if (base.data) return base.data;
else return "";
};
base.getFilename = function(){
if( base.filenameCallback ) return base.filenameCallback();
else if (base.filename) return base.filename;
else return "";
};
base.getDataType = function(){
if (base.options.dataType) return base.options.dataType;
return "string";
};
base.complete = function(){
if( typeof(base.options.onComplete) === "function" ) base.options.onComplete();
};
base.cancel = function(){
if( typeof(base.options.onCancel) === "function" ) base.options.onCancel();
};
base.error = function(){
if( typeof(base.options.onError) === "function" ) base.options.onError();
};
init();
};
Downloadify.defaultOptions = {
swf: 'media/downloadify.swf',
downloadImage: 'images/download.png',
width: 100,
height: 30,
transparent: true,
append: false,
dataType: "string"
};
})();
// Support for jQuery
if(typeof(jQuery) != "undefined"){
(function($){
$.fn.downloadify = function(options){
return this.each(function(){
options = $.extend({}, Downloadify.defaultOptions, options);
var dl = Downloadify.create( this, options);
$(this).data('Downloadify', dl);
});
};
})(jQuery);
};
/* mootools helper */
if(typeof(MooTools) != 'undefined'){
Element.implement({
downloadify: function(options) {
options = $extend(Downloadify.defaultOptions,options);
return this.store('Downloadify',Downloadify.create(this,options));
}
});
}; | 07pratik-androidui | asset-studio/src/lib/downloadify/src/downloadify.js | JavaScript | asf20 | 6,460 |
/*
Copyright (c) 2006 Steve Webster
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 com.dynamicflash.util.tests {
import flexunit.framework.TestCase;
import flexunit.framework.TestSuite;
import flash.utils.ByteArray;
import com.dynamicflash.util.Base64;
public class Base64Test extends TestCase {
public function Base64Test(methodName:String = null) {
super(methodName);
}
public function testEncode():void {
assertEquals("VGhpcyBpcyBhIHRlc3Q=",Base64.encode("This is a test"));
}
public function testEncodeDecodeBytes():void {
var obj:Object = {name:"Dynamic Flash", url:"http://dynamicflash.com"};
var source:ByteArray = new ByteArray();
source.writeObject(obj);
var encoded:String = Base64.encodeByteArray(source);
var decoded:ByteArray = Base64.decodeToByteArray(encoded);
var obj2:Object = decoded.readObject();
assertEquals(obj.name, obj2.name);
assertEquals(obj.url, obj2.url);
}
public function testDecode():void {
assertEquals("This is a test",Base64.decode("VGhpcyBpcyBhIHRlc3Q="));
}
public function testEncodeDecode():void {
var string:String = "The quick brown fox jumped over the lazy dogs";
assertEquals(string, Base64.decode(Base64.encode(string)));
}
}
} | 07pratik-androidui | asset-studio/src/lib/downloadify/src/com/dynamicflash/util/tests/Base64Test.as | ActionScript | asf20 | 2,400 |
/*
Base64 - 1.1.0
Copyright (c) 2006 Steve Webster
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 com.dynamicflash.util {
import flash.utils.ByteArray;
public class Base64 {
private static const BASE64_CHARS:String = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
public static const version:String = "1.1.0";
public static function encode(data:String):String {
// Convert string to ByteArray
var bytes:ByteArray = new ByteArray();
bytes.writeUTFBytes(data);
// Return encoded ByteArray
return encodeByteArray(bytes);
}
public static function encodeByteArray(data:ByteArray):String {
// Initialise output
var output:String = "";
// Create data and output buffers
var dataBuffer:Array;
var outputBuffer:Array = new Array(4);
// Rewind ByteArray
data.position = 0;
// while there are still bytes to be processed
while (data.bytesAvailable > 0) {
// Create new data buffer and populate next 3 bytes from data
dataBuffer = new Array();
for (var i:uint = 0; i < 3 && data.bytesAvailable > 0; i++) {
dataBuffer[i] = data.readUnsignedByte();
}
// Convert to data buffer Base64 character positions and
// store in output buffer
outputBuffer[0] = (dataBuffer[0] & 0xfc) >> 2;
outputBuffer[1] = ((dataBuffer[0] & 0x03) << 4) | ((dataBuffer[1]) >> 4);
outputBuffer[2] = ((dataBuffer[1] & 0x0f) << 2) | ((dataBuffer[2]) >> 6);
outputBuffer[3] = dataBuffer[2] & 0x3f;
// If data buffer was short (i.e not 3 characters) then set
// end character indexes in data buffer to index of '=' symbol.
// This is necessary because Base64 data is always a multiple of
// 4 bytes and is basses with '=' symbols.
for (var j:uint = dataBuffer.length; j < 3; j++) {
outputBuffer[j + 1] = 64;
}
// Loop through output buffer and add Base64 characters to
// encoded data string for each character.
for (var k:uint = 0; k < outputBuffer.length; k++) {
output += BASE64_CHARS.charAt(outputBuffer[k]);
}
}
// Return encoded data
return output;
}
public static function decode(data:String):String {
// Decode data to ByteArray
var bytes:ByteArray = decodeToByteArray(data);
// Convert to string and return
return bytes.readUTFBytes(bytes.length);
}
public static function decodeToByteArray(data:String):ByteArray {
// Initialise output ByteArray for decoded data
var output:ByteArray = new ByteArray();
// Create data and output buffers
var dataBuffer:Array = new Array(4);
var outputBuffer:Array = new Array(3);
// While there are data bytes left to be processed
for (var i:uint = 0; i < data.length; i += 4) {
// Populate data buffer with position of Base64 characters for
// next 4 bytes from encoded data
for (var j:uint = 0; j < 4 && i + j < data.length; j++) {
dataBuffer[j] = BASE64_CHARS.indexOf(data.charAt(i + j));
}
// Decode data buffer back into bytes
outputBuffer[0] = (dataBuffer[0] << 2) + ((dataBuffer[1] & 0x30) >> 4);
outputBuffer[1] = ((dataBuffer[1] & 0x0f) << 4) + ((dataBuffer[2] & 0x3c) >> 2);
outputBuffer[2] = ((dataBuffer[2] & 0x03) << 6) + dataBuffer[3];
// Add all non-padded bytes in output buffer to decoded data
for (var k:uint = 0; k < outputBuffer.length; k++) {
if (dataBuffer[k+1] == 64) break;
output.writeByte(outputBuffer[k]);
}
}
// Rewind decoded data ByteArray
output.position = 0;
// Return decoded data
return output;
}
public function Base64() {
throw new Error("Base64 class is static container only");
}
}
} | 07pratik-androidui | asset-studio/src/lib/downloadify/src/com/dynamicflash/util/Base64.as | AngelScript | asf20 | 4,715 |
/*
Downloadify: Client Side File Creation
JavaScript + Flash Library
Version: 0.2
Copyright (c) 2009 Douglas C. Neiner
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 {
import flash.system.Security;
import flash.events.Event;
import flash.events.MouseEvent;
import flash.net.FileReference;
import flash.net.FileFilter;
import flash.net.URLRequest;
import flash.display.*;
import flash.utils.ByteArray;
import flash.external.ExternalInterface;
import com.dynamicflash.util.Base64;
[SWF(backgroundColor="#CCCCCC")]
[SWF(backgroundAlpha=0)]
public class Downloadify extends Sprite {
private var options:Object,
file:FileReference = new FileReference(),
queue_name:String = "",
_width:Number = 0,
_height:Number = 0,
enabled:Boolean = true,
over:Boolean = false,
down:Boolean = false,
buttonImage:String = "images/download.png",
button:Loader;
public function Downloadify() {
Security.allowDomain('*');
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;
options = this.root.loaderInfo.parameters;
queue_name = options.queue_name.toString();
_width = options.width;
_height = options.height;
if(options.downloadImage){
buttonImage = options.downloadImage;
}
setupDefaultButton();
addChild(button);
this.buttonMode = true;
this.addEventListener(MouseEvent.CLICK, onMouseClickEvent);
this.addEventListener(MouseEvent.ROLL_OVER , onMouseEnter);
this.addEventListener(MouseEvent.ROLL_OUT , onMouseLeave);
this.addEventListener(MouseEvent.MOUSE_DOWN , onMouseDown);
this.addEventListener(MouseEvent.MOUSE_UP , onMouseUp);
ExternalInterface.addCallback('setEnabled', setEnabled);
file.addEventListener(Event.COMPLETE, onSaveComplete);
file.addEventListener(Event.CANCEL, onSaveCancel);
}
private function setEnabled(isEnabled:Boolean):Boolean {
enabled = isEnabled;
if(enabled === true){
button.y = 0;
this.buttonMode = true;
} else {
button.y = (-3 * _height);
this.buttonMode = false;
}
return enabled;
}
private function setupDefaultButton():void {
button = new Loader();
var urlReq:URLRequest = new URLRequest(buttonImage);
button.load(urlReq);
button.x = 0;
button.y = 0;
}
protected function onMouseEnter(event:Event):void {
if(enabled === true){
if(down === false) button.y = (-1 * _height);
over = true;
}
}
protected function onMouseLeave(event:Event):void {
if(enabled === true){
if(down === false) button.y = 0;
over = false;
}
}
protected function onMouseDown(event:Event):void {
if(enabled === true){
button.y = button.y = (-2 * _height);
down = true;
}
}
protected function onMouseUp(event:Event):void {
if(enabled === true){
if(over === false){
button.y = 0;
} else {
button.y = (-1 * _height);
}
down = false;
}
}
protected function onMouseClickEvent(event:Event):void{
var theData:String = ExternalInterface.call('Downloadify.getTextForSave',queue_name),
filename:String = ExternalInterface.call('Downloadify.getFileNameForSave',queue_name),
dataType:String = ExternalInterface.call('Downloadify.getDataTypeForSave',queue_name);
if (dataType == "string" && theData != "") {
file.save(theData, filename);
} else if (dataType == "base64" && theData){
file.save(Base64.decodeToByteArray(theData), filename);
} else {
onSaveError();
}
}
protected function onSaveComplete(event:Event):void{
trace('Save Complete');
ExternalInterface.call('Downloadify.saveComplete',queue_name);
}
protected function onSaveCancel(event:Event):void{
trace('Save Cancel');
ExternalInterface.call('Downloadify.saveCancel',queue_name);
}
protected function onSaveError():void{
trace('Save Error');
ExternalInterface.call('Downloadify.saveError',queue_name);
}
}
} | 07pratik-androidui | asset-studio/src/lib/downloadify/src/Downloadify.as | ActionScript | asf20 | 5,588 |
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">
<head>
<title>Downloadify</title>
<style type="text/css" media="screen">
body {background: #fff; width: 500px; margin: 20px auto;}
label, input, textarea, h1, h2, p { font-family: Arial, sans-serif; font-size: 12pt;}
input, textarea { border: solid 1px #aaa; padding: 4px; width: 98%;}
label { font-weight: bold;}
h1 { font-size: 30pt; font-weight: bold; letter-spacing: -1px;}
h2 { font-size: 14pt;}
pre { overflow: auto; padding: 10px; background: #222; color: #ccc;}
</style>
<script type="text/javascript" src="js/swfobject.js"></script>
<script type="text/javascript" src="js/downloadify.min.js"></script>
</head>
<body onload="load();">
<h1>Downloadify Example</h1>
<p>More info available at the <a href="http://github.com/dcneiner/Downloadify">Github Project Page</a></p>
<form>
<p>
<label for="filename">Filename</label><br />
<input type="text" name="filename" value="testfile.txt" id="filename" />
</p>
<p>
<label for="data">File Contents</label><br />
<textarea cols="60" rows="10" name="data" id="data">
Whatever you put in this text box will be downloaded and saved in the file. If you leave it blank, no file will be downloaded</textarea>
</p>
<p id="downloadify">
You must have Flash 10 installed to download this file.
</p>
</form>
<script type="text/javascript">
function load(){
Downloadify.create('downloadify',{
filename: function(){
return document.getElementById('filename').value;
},
data: function(){
return document.getElementById('data').value;
},
onComplete: function(){ alert('Your File Has Been Saved!'); },
onCancel: function(){ alert('You have cancelled the saving of this file.'); },
onError: function(){ alert('You must put something in the File Contents or there will be nothing to save!'); },
swf: 'media/downloadify.swf',
downloadImage: 'images/download.png',
width: 100,
height: 30,
transparent: true,
append: false
});
}
</script>
<h2>Downloadify Invoke Script For This Page</h2>
<pre>
Downloadify.create('downloadify',{
filename: function(){
return document.getElementById('filename').value;
},
data: function(){
return document.getElementById('data').value;
},
onComplete: function(){
alert('Your File Has Been Saved!');
},
onCancel: function(){
alert('You have cancelled the saving of this file.');
},
onError: function(){
alert('You must put something in the File Contents or there will be nothing to save!');
},
swf: 'media/downloadify.swf',
downloadImage: 'images/download.png',
width: 100,
height: 30,
transparent: true,
append: false
});
</pre>
</body>
</html>
| 07pratik-androidui | asset-studio/src/lib/downloadify/test.html | HTML | asf20 | 3,001 |
/**
JSZip - A Javascript class for generating Zip files
<http://jszip.stuartk.co.uk>
(c) 2009 Stuart Knightley <stuart [at] stuartk.co.uk>
Licenced under the GPLv3 and the MIT licences
Usage:
zip = new JSZip();
zip.add("hello.txt", "Hello, World!").add("tempfile", "nothing");
zip.folder("images").add("smile.gif", base64Data, {base64: true});
zip.add("Xmas.txt", "Ho ho ho !", {date : new Date("December 25, 2007 00:00:01")});
zip.remove("tempfile");
base64zip = zip.generate();
**/
function JSZip(compression)
{
// default : no compression
this.compression = (compression || "STORE").toUpperCase();
this.files = [];
// Where we are in the hierarchy
this.root = "";
// Default properties for a new file
this.d = {
base64: false,
binary: false,
dir: false,
date: null
};
if (!JSZip.compressions[this.compression]) {
throw compression + " is not a valid compression method !";
}
}
/**
* Add a file to the zip file
* @param name The name of the file
* @param data The file data, either raw or base64 encoded
* @param o File options
* @return this JSZip object
*/
JSZip.prototype.add = function(name, data, o)
{
o = o || {};
name = this.root+name;
if (o.base64 === true && o.binary == null) o.binary = true;
for (var opt in this.d)
{
o[opt] = o[opt] || this.d[opt];
}
// date
// @see http://www.delorie.com/djgpp/doc/rbinter/it/52/13.html
// @see http://www.delorie.com/djgpp/doc/rbinter/it/65/16.html
// @see http://www.delorie.com/djgpp/doc/rbinter/it/66/16.html
o.date = o.date || new Date();
var dosTime, dosDate;
dosTime = o.date.getHours();
dosTime = dosTime << 6;
dosTime = dosTime | o.date.getMinutes();
dosTime = dosTime << 5;
dosTime = dosTime | o.date.getSeconds() / 2;
dosDate = o.date.getFullYear() - 1980;
dosDate = dosDate << 4;
dosDate = dosDate | (o.date.getMonth() + 1);
dosDate = dosDate << 5;
dosDate = dosDate | o.date.getDate();
if (o.base64 === true) data = JSZipBase64.decode(data);
// decode UTF-8 strings if we are dealing with text data
if(o.binary === false) data = this.utf8encode(data);
var compression = JSZip.compressions[this.compression];
var compressedData = compression.compress(data);
var header = "";
// version needed to extract
header += "\x0A\x00";
// general purpose bit flag
header += "\x00\x00";
// compression method
header += compression.magic;
// last mod file time
header += this.decToHex(dosTime, 2);
// last mod file date
header += this.decToHex(dosDate, 2);
// crc-32
header += this.decToHex(this.crc32(data), 4);
// compressed size
header += this.decToHex(compressedData.length, 4);
// uncompressed size
header += this.decToHex(data.length, 4);
// file name length
header += this.decToHex(name.length, 2);
// extra field length
header += "\x00\x00";
// file name
this.files[name] = {header: header, data: compressedData, dir: o.dir};
return this;
};
/**
* Add a directory to the zip file
* @param name The name of the directory to add
* @return JSZip object with the new directory as the root
*/
JSZip.prototype.folder = function(name)
{
// Check the name ends with a /
if (name.substr(-1) != "/") name += "/";
// Does this folder already exist?
if (typeof this.files[name] === "undefined") this.add(name, '', {dir:true});
// Allow chaining by returning a new object with this folder as the root
var ret = this.clone();
ret.root = this.root+name;
return ret;
};
/**
* Compare a string or regular expression against all of the filenames and
* return an informational object for each that matches.
* @param string/regex The regular expression to test against
* @return An array of objects representing the matched files. In the form
* {name: "filename", data: "file data", dir: true/false}
*/
JSZip.prototype.find = function(needle)
{
var result = [], re;
if (typeof needle === "string")
{
re = new RegExp("^"+needle+"$");
}
else
{
re = needle;
}
for (var filename in this.files)
{
if (re.test(filename))
{
var file = this.files[filename];
result.push({name: filename, data: file.data, dir: !!file.dir});
}
}
return result;
};
/**
* Delete a file, or a directory and all sub-files, from the zip
* @param name the name of the file to delete
* @return this JSZip object
*/
JSZip.prototype.remove = function(name)
{
var file = this.files[name];
if (!file)
{
// Look for any folders
if (name.substr(-1) != "/") name += "/";
file = this.files[name];
}
if (file)
{
if (name.match("/") === null)
{
// file
delete this.files[name];
}
else
{
// folder
var kids = this.find(new RegExp("^"+name));
for (var i = 0; i < kids.length; i++)
{
if (kids[i].name == name)
{
// Delete this folder
delete this.files[name];
}
else
{
// Remove a child of this folder
this.remove(kids[i].name);
}
}
}
}
return this;
};
/**
* Generate the complete zip file
* @return A base64 encoded string of the zip file
*/
JSZip.prototype.generate = function(asBytes)
{
asBytes = asBytes || false;
// The central directory, and files data
var directory = [], files = [], fileOffset = 0;
for (var name in this.files)
{
if( !this.files.hasOwnProperty(name) ) { continue; }
var fileRecord = "", dirRecord = "";
fileRecord = "\x50\x4b\x03\x04" + this.files[name].header + name + this.files[name].data;
dirRecord = "\x50\x4b\x01\x02" +
// version made by (00: DOS)
"\x14\x00" +
// file header (common to file and central directory)
this.files[name].header +
// file comment length
"\x00\x00" +
// disk number start
"\x00\x00" +
// internal file attributes TODO
"\x00\x00" +
// external file attributes
(this.files[name].dir===true?"\x10\x00\x00\x00":"\x00\x00\x00\x00")+
// relative offset of local header
this.decToHex(fileOffset, 4) +
// file name
name;
fileOffset += fileRecord.length;
files.push(fileRecord);
directory.push(dirRecord);
}
var fileData = files.join("");
var dirData = directory.join("");
var dirEnd = "";
// end of central dir signature
dirEnd = "\x50\x4b\x05\x06" +
// number of this disk
"\x00\x00" +
// number of the disk with the start of the central directory
"\x00\x00" +
// total number of entries in the central directory on this disk
this.decToHex(files.length, 2) +
// total number of entries in the central directory
this.decToHex(files.length, 2) +
// size of the central directory 4 bytes
this.decToHex(dirData.length, 4) +
// offset of start of central directory with respect to the starting disk number
this.decToHex(fileData.length, 4) +
// .ZIP file comment length
"\x00\x00";
var zip = fileData + dirData + dirEnd;
return (asBytes) ? zip : JSZipBase64.encode(zip);
};
/*
* Compression methods
* This object is filled in as follow :
* name : {
* magic // the 2 bytes indentifying the compression method
* compress // function, take the uncompressed content and return it compressed.
* }
*
* STORE is the default compression method, so it's included in this file.
* Other methods should go to separated files : the user wants modularity.
*/
JSZip.compressions = {
"STORE" : {
magic : "\x00\x00",
compress : function (content) {
return content; // no compression
}
}
};
// Utility functions
JSZip.prototype.decToHex = function(dec, bytes)
{
var hex = "";
for(var i=0;i<bytes;i++) {
hex += String.fromCharCode(dec&0xff);
dec=dec>>>8;
}
return hex;
};
/**
*
* Javascript crc32
* http://www.webtoolkit.info/
*
**/
JSZip.prototype.crc32 = function(str, crc)
{
if (str === "") return "\x00\x00\x00\x00";
var table = "00000000 77073096 EE0E612C 990951BA 076DC419 706AF48F E963A535 9E6495A3 0EDB8832 79DCB8A4 E0D5E91E 97D2D988 09B64C2B 7EB17CBD E7B82D07 90BF1D91 1DB71064 6AB020F2 F3B97148 84BE41DE 1ADAD47D 6DDDE4EB F4D4B551 83D385C7 136C9856 646BA8C0 FD62F97A 8A65C9EC 14015C4F 63066CD9 FA0F3D63 8D080DF5 3B6E20C8 4C69105E D56041E4 A2677172 3C03E4D1 4B04D447 D20D85FD A50AB56B 35B5A8FA 42B2986C DBBBC9D6 ACBCF940 32D86CE3 45DF5C75 DCD60DCF ABD13D59 26D930AC 51DE003A C8D75180 BFD06116 21B4F4B5 56B3C423 CFBA9599 B8BDA50F 2802B89E 5F058808 C60CD9B2 B10BE924 2F6F7C87 58684C11 C1611DAB B6662D3D 76DC4190 01DB7106 98D220BC EFD5102A 71B18589 06B6B51F 9FBFE4A5 E8B8D433 7807C9A2 0F00F934 9609A88E E10E9818 7F6A0DBB 086D3D2D 91646C97 E6635C01 6B6B51F4 1C6C6162 856530D8 F262004E 6C0695ED 1B01A57B 8208F4C1 F50FC457 65B0D9C6 12B7E950 8BBEB8EA FCB9887C 62DD1DDF 15DA2D49 8CD37CF3 FBD44C65 4DB26158 3AB551CE A3BC0074 D4BB30E2 4ADFA541 3DD895D7 A4D1C46D D3D6F4FB 4369E96A 346ED9FC AD678846 DA60B8D0 44042D73 33031DE5 AA0A4C5F DD0D7CC9 5005713C 270241AA BE0B1010 C90C2086 5768B525 206F85B3 B966D409 CE61E49F 5EDEF90E 29D9C998 B0D09822 C7D7A8B4 59B33D17 2EB40D81 B7BD5C3B C0BA6CAD EDB88320 9ABFB3B6 03B6E20C 74B1D29A EAD54739 9DD277AF 04DB2615 73DC1683 E3630B12 94643B84 0D6D6A3E 7A6A5AA8 E40ECF0B 9309FF9D 0A00AE27 7D079EB1 F00F9344 8708A3D2 1E01F268 6906C2FE F762575D 806567CB 196C3671 6E6B06E7 FED41B76 89D32BE0 10DA7A5A 67DD4ACC F9B9DF6F 8EBEEFF9 17B7BE43 60B08ED5 D6D6A3E8 A1D1937E 38D8C2C4 4FDFF252 D1BB67F1 A6BC5767 3FB506DD 48B2364B D80D2BDA AF0A1B4C 36034AF6 41047A60 DF60EFC3 A867DF55 316E8EEF 4669BE79 CB61B38C BC66831A 256FD2A0 5268E236 CC0C7795 BB0B4703 220216B9 5505262F C5BA3BBE B2BD0B28 2BB45A92 5CB36A04 C2D7FFA7 B5D0CF31 2CD99E8B 5BDEAE1D 9B64C2B0 EC63F226 756AA39C 026D930A 9C0906A9 EB0E363F 72076785 05005713 95BF4A82 E2B87A14 7BB12BAE 0CB61B38 92D28E9B E5D5BE0D 7CDCEFB7 0BDBDF21 86D3D2D4 F1D4E242 68DDB3F8 1FDA836E 81BE16CD F6B9265B 6FB077E1 18B74777 88085AE6 FF0F6A70 66063BCA 11010B5C 8F659EFF F862AE69 616BFFD3 166CCF45 A00AE278 D70DD2EE 4E048354 3903B3C2 A7672661 D06016F7 4969474D 3E6E77DB AED16A4A D9D65ADC 40DF0B66 37D83BF0 A9BCAE53 DEBB9EC5 47B2CF7F 30B5FFE9 BDBDF21C CABAC28A 53B39330 24B4A3A6 BAD03605 CDD70693 54DE5729 23D967BF B3667A2E C4614AB8 5D681B02 2A6F2B94 B40BBE37 C30C8EA1 5A05DF1B 2D02EF8D";
if (typeof(crc) == "undefined") { crc = 0; }
var x = 0;
var y = 0;
crc = crc ^ (-1);
for( var i = 0, iTop = str.length; i < iTop; i++ ) {
y = ( crc ^ str.charCodeAt( i ) ) & 0xFF;
x = "0x" + table.substr( y * 9, 8 );
crc = ( crc >>> 8 ) ^ x;
}
return crc ^ (-1);
};
// Inspired by http://my.opera.com/GreyWyvern/blog/show.dml/1725165
JSZip.prototype.clone = function()
{
var newObj = new JSZip();
for (var i in this)
{
if (typeof this[i] !== "function")
{
newObj[i] = this[i];
}
}
return newObj;
};
JSZip.prototype.utf8encode = function(input)
{
input = encodeURIComponent(input);
input = input.replace(/%.{2,2}/g, function(m) {
var hex = m.substring(1);
return String.fromCharCode(parseInt(hex,16));
});
return input;
};
/**
*
* Base64 encode / decode
* http://www.webtoolkit.info/
*
* Hacked so that it doesn't utf8 en/decode everything
**/
var JSZipBase64 = function() {
// private property
var _keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
return {
// public method for encoding
encode : function(input, utf8) {
var output = "";
var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
var i = 0;
while (i < input.length) {
chr1 = input.charCodeAt(i++);
chr2 = input.charCodeAt(i++);
chr3 = input.charCodeAt(i++);
enc1 = chr1 >> 2;
enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
enc4 = chr3 & 63;
if (isNaN(chr2)) {
enc3 = enc4 = 64;
} else if (isNaN(chr3)) {
enc4 = 64;
}
output = output +
_keyStr.charAt(enc1) + _keyStr.charAt(enc2) +
_keyStr.charAt(enc3) + _keyStr.charAt(enc4);
}
return output;
},
// public method for decoding
decode : function(input, utf8) {
var output = "";
var chr1, chr2, chr3;
var enc1, enc2, enc3, enc4;
var i = 0;
input = input.replace(/[^A-Za-z0-9\+\/\=]/g, "");
while (i < input.length) {
enc1 = _keyStr.indexOf(input.charAt(i++));
enc2 = _keyStr.indexOf(input.charAt(i++));
enc3 = _keyStr.indexOf(input.charAt(i++));
enc4 = _keyStr.indexOf(input.charAt(i++));
chr1 = (enc1 << 2) | (enc2 >> 4);
chr2 = ((enc2 & 15) << 4) | (enc3 >> 2);
chr3 = ((enc3 & 3) << 6) | enc4;
output = output + String.fromCharCode(chr1);
if (enc3 != 64) {
output = output + String.fromCharCode(chr2);
}
if (enc4 != 64) {
output = output + String.fromCharCode(chr3);
}
}
return output;
}
};
}();
| 07pratik-androidui | asset-studio/src/lib/jszip/jszip.js | JavaScript | asf20 | 13,515 |
/*
* Port of a script by Masanao Izumo.
*
* Only changes : wrap all the variables in a function and add the
* main function to JSZip (DEFLATE compression method).
* Everything else was written by M. Izumo.
*
* Original code can be found here: http://www.onicos.com/staff/iz/amuse/javascript/expert/inflate.txt
*/
if(!JSZip)
{
throw "JSZip not defined";
}
/*
* Original:
* http://www.onicos.com/staff/iz/amuse/javascript/expert/deflate.txt
*/
(function(){
/* Copyright (C) 1999 Masanao Izumo <iz@onicos.co.jp>
* Version: 1.0.1
* LastModified: Dec 25 1999
*/
/* Interface:
* data = zip_deflate(src);
*/
/* constant parameters */
var zip_WSIZE = 32768; // Sliding Window size
var zip_STORED_BLOCK = 0;
var zip_STATIC_TREES = 1;
var zip_DYN_TREES = 2;
/* for deflate */
var zip_DEFAULT_LEVEL = 6;
var zip_FULL_SEARCH = true;
var zip_INBUFSIZ = 32768; // Input buffer size
var zip_INBUF_EXTRA = 64; // Extra buffer
var zip_OUTBUFSIZ = 1024 * 8;
var zip_window_size = 2 * zip_WSIZE;
var zip_MIN_MATCH = 3;
var zip_MAX_MATCH = 258;
var zip_BITS = 16;
// for SMALL_MEM
var zip_LIT_BUFSIZE = 0x2000;
var zip_HASH_BITS = 13;
// for MEDIUM_MEM
// var zip_LIT_BUFSIZE = 0x4000;
// var zip_HASH_BITS = 14;
// for BIG_MEM
// var zip_LIT_BUFSIZE = 0x8000;
// var zip_HASH_BITS = 15;
if(zip_LIT_BUFSIZE > zip_INBUFSIZ)
alert("error: zip_INBUFSIZ is too small");
if((zip_WSIZE<<1) > (1<<zip_BITS))
alert("error: zip_WSIZE is too large");
if(zip_HASH_BITS > zip_BITS-1)
alert("error: zip_HASH_BITS is too large");
if(zip_HASH_BITS < 8 || zip_MAX_MATCH != 258)
alert("error: Code too clever");
var zip_DIST_BUFSIZE = zip_LIT_BUFSIZE;
var zip_HASH_SIZE = 1 << zip_HASH_BITS;
var zip_HASH_MASK = zip_HASH_SIZE - 1;
var zip_WMASK = zip_WSIZE - 1;
var zip_NIL = 0; // Tail of hash chains
var zip_TOO_FAR = 4096;
var zip_MIN_LOOKAHEAD = zip_MAX_MATCH + zip_MIN_MATCH + 1;
var zip_MAX_DIST = zip_WSIZE - zip_MIN_LOOKAHEAD;
var zip_SMALLEST = 1;
var zip_MAX_BITS = 15;
var zip_MAX_BL_BITS = 7;
var zip_LENGTH_CODES = 29;
var zip_LITERALS =256;
var zip_END_BLOCK = 256;
var zip_L_CODES = zip_LITERALS + 1 + zip_LENGTH_CODES;
var zip_D_CODES = 30;
var zip_BL_CODES = 19;
var zip_REP_3_6 = 16;
var zip_REPZ_3_10 = 17;
var zip_REPZ_11_138 = 18;
var zip_HEAP_SIZE = 2 * zip_L_CODES + 1;
var zip_H_SHIFT = parseInt((zip_HASH_BITS + zip_MIN_MATCH - 1) /
zip_MIN_MATCH);
/* variables */
var zip_free_queue;
var zip_qhead, zip_qtail;
var zip_initflag;
var zip_outbuf = null;
var zip_outcnt, zip_outoff;
var zip_complete;
var zip_window;
var zip_d_buf;
var zip_l_buf;
var zip_prev;
var zip_bi_buf;
var zip_bi_valid;
var zip_block_start;
var zip_ins_h;
var zip_hash_head;
var zip_prev_match;
var zip_match_available;
var zip_match_length;
var zip_prev_length;
var zip_strstart;
var zip_match_start;
var zip_eofile;
var zip_lookahead;
var zip_max_chain_length;
var zip_max_lazy_match;
var zip_compr_level;
var zip_good_match;
var zip_nice_match;
var zip_dyn_ltree;
var zip_dyn_dtree;
var zip_static_ltree;
var zip_static_dtree;
var zip_bl_tree;
var zip_l_desc;
var zip_d_desc;
var zip_bl_desc;
var zip_bl_count;
var zip_heap;
var zip_heap_len;
var zip_heap_max;
var zip_depth;
var zip_length_code;
var zip_dist_code;
var zip_base_length;
var zip_base_dist;
var zip_flag_buf;
var zip_last_lit;
var zip_last_dist;
var zip_last_flags;
var zip_flags;
var zip_flag_bit;
var zip_opt_len;
var zip_static_len;
var zip_deflate_data;
var zip_deflate_pos;
/* objects (deflate) */
var zip_DeflateCT = function() {
this.fc = 0; // frequency count or bit string
this.dl = 0; // father node in Huffman tree or length of bit string
}
var zip_DeflateTreeDesc = function() {
this.dyn_tree = null; // the dynamic tree
this.static_tree = null; // corresponding static tree or NULL
this.extra_bits = null; // extra bits for each code or NULL
this.extra_base = 0; // base index for extra_bits
this.elems = 0; // max number of elements in the tree
this.max_length = 0; // max bit length for the codes
this.max_code = 0; // largest code with non zero frequency
}
/* Values for max_lazy_match, good_match and max_chain_length, depending on
* the desired pack level (0..9). The values given below have been tuned to
* exclude worst case performance for pathological files. Better values may be
* found for specific files.
*/
var zip_DeflateConfiguration = function(a, b, c, d) {
this.good_length = a; // reduce lazy search above this match length
this.max_lazy = b; // do not perform lazy search above this match length
this.nice_length = c; // quit search above this match length
this.max_chain = d;
}
var zip_DeflateBuffer = function() {
this.next = null;
this.len = 0;
this.ptr = new Array(zip_OUTBUFSIZ);
this.off = 0;
}
/* constant tables */
var zip_extra_lbits = new Array(
0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0);
var zip_extra_dbits = new Array(
0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13);
var zip_extra_blbits = new Array(
0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7);
var zip_bl_order = new Array(
16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15);
var zip_configuration_table = new Array(
new zip_DeflateConfiguration(0, 0, 0, 0),
new zip_DeflateConfiguration(4, 4, 8, 4),
new zip_DeflateConfiguration(4, 5, 16, 8),
new zip_DeflateConfiguration(4, 6, 32, 32),
new zip_DeflateConfiguration(4, 4, 16, 16),
new zip_DeflateConfiguration(8, 16, 32, 32),
new zip_DeflateConfiguration(8, 16, 128, 128),
new zip_DeflateConfiguration(8, 32, 128, 256),
new zip_DeflateConfiguration(32, 128, 258, 1024),
new zip_DeflateConfiguration(32, 258, 258, 4096));
/* routines (deflate) */
var zip_deflate_start = function(level) {
var i;
if(!level)
level = zip_DEFAULT_LEVEL;
else if(level < 1)
level = 1;
else if(level > 9)
level = 9;
zip_compr_level = level;
zip_initflag = false;
zip_eofile = false;
if(zip_outbuf != null)
return;
zip_free_queue = zip_qhead = zip_qtail = null;
zip_outbuf = new Array(zip_OUTBUFSIZ);
zip_window = new Array(zip_window_size);
zip_d_buf = new Array(zip_DIST_BUFSIZE);
zip_l_buf = new Array(zip_INBUFSIZ + zip_INBUF_EXTRA);
zip_prev = new Array(1 << zip_BITS);
zip_dyn_ltree = new Array(zip_HEAP_SIZE);
for(i = 0; i < zip_HEAP_SIZE; i++)
zip_dyn_ltree[i] = new zip_DeflateCT();
zip_dyn_dtree = new Array(2*zip_D_CODES+1);
for(i = 0; i < 2*zip_D_CODES+1; i++)
zip_dyn_dtree[i] = new zip_DeflateCT();
zip_static_ltree = new Array(zip_L_CODES+2);
for(i = 0; i < zip_L_CODES+2; i++)
zip_static_ltree[i] = new zip_DeflateCT();
zip_static_dtree = new Array(zip_D_CODES);
for(i = 0; i < zip_D_CODES; i++)
zip_static_dtree[i] = new zip_DeflateCT();
zip_bl_tree = new Array(2*zip_BL_CODES+1);
for(i = 0; i < 2*zip_BL_CODES+1; i++)
zip_bl_tree[i] = new zip_DeflateCT();
zip_l_desc = new zip_DeflateTreeDesc();
zip_d_desc = new zip_DeflateTreeDesc();
zip_bl_desc = new zip_DeflateTreeDesc();
zip_bl_count = new Array(zip_MAX_BITS+1);
zip_heap = new Array(2*zip_L_CODES+1);
zip_depth = new Array(2*zip_L_CODES+1);
zip_length_code = new Array(zip_MAX_MATCH-zip_MIN_MATCH+1);
zip_dist_code = new Array(512);
zip_base_length = new Array(zip_LENGTH_CODES);
zip_base_dist = new Array(zip_D_CODES);
zip_flag_buf = new Array(parseInt(zip_LIT_BUFSIZE / 8));
}
var zip_deflate_end = function() {
zip_free_queue = zip_qhead = zip_qtail = null;
zip_outbuf = null;
zip_window = null;
zip_d_buf = null;
zip_l_buf = null;
zip_prev = null;
zip_dyn_ltree = null;
zip_dyn_dtree = null;
zip_static_ltree = null;
zip_static_dtree = null;
zip_bl_tree = null;
zip_l_desc = null;
zip_d_desc = null;
zip_bl_desc = null;
zip_bl_count = null;
zip_heap = null;
zip_depth = null;
zip_length_code = null;
zip_dist_code = null;
zip_base_length = null;
zip_base_dist = null;
zip_flag_buf = null;
}
var zip_reuse_queue = function(p) {
p.next = zip_free_queue;
zip_free_queue = p;
}
var zip_new_queue = function() {
var p;
if(zip_free_queue != null)
{
p = zip_free_queue;
zip_free_queue = zip_free_queue.next;
}
else
p = new zip_DeflateBuffer();
p.next = null;
p.len = p.off = 0;
return p;
}
var zip_head1 = function(i) {
return zip_prev[zip_WSIZE + i];
}
var zip_head2 = function(i, val) {
return zip_prev[zip_WSIZE + i] = val;
}
/* put_byte is used for the compressed output, put_ubyte for the
* uncompressed output. However unlzw() uses window for its
* suffix table instead of its output buffer, so it does not use put_ubyte
* (to be cleaned up).
*/
var zip_put_byte = function(c) {
zip_outbuf[zip_outoff + zip_outcnt++] = c;
if(zip_outoff + zip_outcnt == zip_OUTBUFSIZ)
zip_qoutbuf();
}
/* Output a 16 bit value, lsb first */
var zip_put_short = function(w) {
w &= 0xffff;
if(zip_outoff + zip_outcnt < zip_OUTBUFSIZ - 2) {
zip_outbuf[zip_outoff + zip_outcnt++] = (w & 0xff);
zip_outbuf[zip_outoff + zip_outcnt++] = (w >>> 8);
} else {
zip_put_byte(w & 0xff);
zip_put_byte(w >>> 8);
}
}
/* ==========================================================================
* Insert string s in the dictionary and set match_head to the previous head
* of the hash chain (the most recent string with same hash key). Return
* the previous length of the hash chain.
* IN assertion: all calls to to INSERT_STRING are made with consecutive
* input characters and the first MIN_MATCH bytes of s are valid
* (except for the last MIN_MATCH-1 bytes of the input file).
*/
var zip_INSERT_STRING = function() {
zip_ins_h = ((zip_ins_h << zip_H_SHIFT)
^ (zip_window[zip_strstart + zip_MIN_MATCH - 1] & 0xff))
& zip_HASH_MASK;
zip_hash_head = zip_head1(zip_ins_h);
zip_prev[zip_strstart & zip_WMASK] = zip_hash_head;
zip_head2(zip_ins_h, zip_strstart);
}
/* Send a code of the given tree. c and tree must not have side effects */
var zip_SEND_CODE = function(c, tree) {
zip_send_bits(tree[c].fc, tree[c].dl);
}
/* Mapping from a distance to a distance code. dist is the distance - 1 and
* must not have side effects. dist_code[256] and dist_code[257] are never
* used.
*/
var zip_D_CODE = function(dist) {
return (dist < 256 ? zip_dist_code[dist]
: zip_dist_code[256 + (dist>>7)]) & 0xff;
}
/* ==========================================================================
* Compares to subtrees, using the tree depth as tie breaker when
* the subtrees have equal frequency. This minimizes the worst case length.
*/
var zip_SMALLER = function(tree, n, m) {
return tree[n].fc < tree[m].fc ||
(tree[n].fc == tree[m].fc && zip_depth[n] <= zip_depth[m]);
}
/* ==========================================================================
* read string data
*/
var zip_read_buff = function(buff, offset, n) {
var i;
for(i = 0; i < n && zip_deflate_pos < zip_deflate_data.length; i++)
buff[offset + i] =
zip_deflate_data.charCodeAt(zip_deflate_pos++) & 0xff;
return i;
}
/* ==========================================================================
* Initialize the "longest match" routines for a new file
*/
var zip_lm_init = function() {
var j;
/* Initialize the hash table. */
for(j = 0; j < zip_HASH_SIZE; j++)
// zip_head2(j, zip_NIL);
zip_prev[zip_WSIZE + j] = 0;
/* prev will be initialized on the fly */
/* Set the default configuration parameters:
*/
zip_max_lazy_match = zip_configuration_table[zip_compr_level].max_lazy;
zip_good_match = zip_configuration_table[zip_compr_level].good_length;
if(!zip_FULL_SEARCH)
zip_nice_match = zip_configuration_table[zip_compr_level].nice_length;
zip_max_chain_length = zip_configuration_table[zip_compr_level].max_chain;
zip_strstart = 0;
zip_block_start = 0;
zip_lookahead = zip_read_buff(zip_window, 0, 2 * zip_WSIZE);
if(zip_lookahead <= 0) {
zip_eofile = true;
zip_lookahead = 0;
return;
}
zip_eofile = false;
/* Make sure that we always have enough lookahead. This is important
* if input comes from a device such as a tty.
*/
while(zip_lookahead < zip_MIN_LOOKAHEAD && !zip_eofile)
zip_fill_window();
/* If lookahead < MIN_MATCH, ins_h is garbage, but this is
* not important since only literal bytes will be emitted.
*/
zip_ins_h = 0;
for(j = 0; j < zip_MIN_MATCH - 1; j++) {
// UPDATE_HASH(ins_h, window[j]);
zip_ins_h = ((zip_ins_h << zip_H_SHIFT) ^ (zip_window[j] & 0xff)) & zip_HASH_MASK;
}
}
/* ==========================================================================
* Set match_start to the longest match starting at the given string and
* return its length. Matches shorter or equal to prev_length are discarded,
* in which case the result is equal to prev_length and match_start is
* garbage.
* IN assertions: cur_match is the head of the hash chain for the current
* string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
*/
var zip_longest_match = function(cur_match) {
var chain_length = zip_max_chain_length; // max hash chain length
var scanp = zip_strstart; // current string
var matchp; // matched string
var len; // length of current match
var best_len = zip_prev_length; // best match length so far
/* Stop when cur_match becomes <= limit. To simplify the code,
* we prevent matches with the string of window index 0.
*/
var limit = (zip_strstart > zip_MAX_DIST ? zip_strstart - zip_MAX_DIST : zip_NIL);
var strendp = zip_strstart + zip_MAX_MATCH;
var scan_end1 = zip_window[scanp + best_len - 1];
var scan_end = zip_window[scanp + best_len];
/* Do not waste too much time if we already have a good match: */
if(zip_prev_length >= zip_good_match)
chain_length >>= 2;
// Assert(encoder->strstart <= window_size-MIN_LOOKAHEAD, "insufficient lookahead");
do {
// Assert(cur_match < encoder->strstart, "no future");
matchp = cur_match;
/* Skip to next match if the match length cannot increase
* or if the match length is less than 2:
*/
if(zip_window[matchp + best_len] != scan_end ||
zip_window[matchp + best_len - 1] != scan_end1 ||
zip_window[matchp] != zip_window[scanp] ||
zip_window[++matchp] != zip_window[scanp + 1]) {
continue;
}
/* The check at best_len-1 can be removed because it will be made
* again later. (This heuristic is not always a win.)
* It is not necessary to compare scan[2] and match[2] since they
* are always equal when the other bytes match, given that
* the hash keys are equal and that HASH_BITS >= 8.
*/
scanp += 2;
matchp++;
/* We check for insufficient lookahead only every 8th comparison;
* the 256th check will be made at strstart+258.
*/
do {
} while(zip_window[++scanp] == zip_window[++matchp] &&
zip_window[++scanp] == zip_window[++matchp] &&
zip_window[++scanp] == zip_window[++matchp] &&
zip_window[++scanp] == zip_window[++matchp] &&
zip_window[++scanp] == zip_window[++matchp] &&
zip_window[++scanp] == zip_window[++matchp] &&
zip_window[++scanp] == zip_window[++matchp] &&
zip_window[++scanp] == zip_window[++matchp] &&
scanp < strendp);
len = zip_MAX_MATCH - (strendp - scanp);
scanp = strendp - zip_MAX_MATCH;
if(len > best_len) {
zip_match_start = cur_match;
best_len = len;
if(zip_FULL_SEARCH) {
if(len >= zip_MAX_MATCH) break;
} else {
if(len >= zip_nice_match) break;
}
scan_end1 = zip_window[scanp + best_len-1];
scan_end = zip_window[scanp + best_len];
}
} while((cur_match = zip_prev[cur_match & zip_WMASK]) > limit
&& --chain_length != 0);
return best_len;
}
/* ==========================================================================
* Fill the window when the lookahead becomes insufficient.
* Updates strstart and lookahead, and sets eofile if end of input file.
* IN assertion: lookahead < MIN_LOOKAHEAD && strstart + lookahead > 0
* OUT assertions: at least one byte has been read, or eofile is set;
* file reads are performed for at least two bytes (required for the
* translate_eol option).
*/
var zip_fill_window = function() {
var n, m;
// Amount of free space at the end of the window.
var more = zip_window_size - zip_lookahead - zip_strstart;
/* If the window is almost full and there is insufficient lookahead,
* move the upper half to the lower one to make room in the upper half.
*/
if(more == -1) {
/* Very unlikely, but possible on 16 bit machine if strstart == 0
* and lookahead == 1 (input done one byte at time)
*/
more--;
} else if(zip_strstart >= zip_WSIZE + zip_MAX_DIST) {
/* By the IN assertion, the window is not empty so we can't confuse
* more == 0 with more == 64K on a 16 bit machine.
*/
// Assert(window_size == (ulg)2*WSIZE, "no sliding with BIG_MEM");
// System.arraycopy(window, WSIZE, window, 0, WSIZE);
for(n = 0; n < zip_WSIZE; n++)
zip_window[n] = zip_window[n + zip_WSIZE];
zip_match_start -= zip_WSIZE;
zip_strstart -= zip_WSIZE; /* we now have strstart >= MAX_DIST: */
zip_block_start -= zip_WSIZE;
for(n = 0; n < zip_HASH_SIZE; n++) {
m = zip_head1(n);
zip_head2(n, m >= zip_WSIZE ? m - zip_WSIZE : zip_NIL);
}
for(n = 0; n < zip_WSIZE; n++) {
/* If n is not on any hash chain, prev[n] is garbage but
* its value will never be used.
*/
m = zip_prev[n];
zip_prev[n] = (m >= zip_WSIZE ? m - zip_WSIZE : zip_NIL);
}
more += zip_WSIZE;
}
// At this point, more >= 2
if(!zip_eofile) {
n = zip_read_buff(zip_window, zip_strstart + zip_lookahead, more);
if(n <= 0)
zip_eofile = true;
else
zip_lookahead += n;
}
}
/* ==========================================================================
* Processes a new input file and return its compressed length. This
* function does not perform lazy evaluationof matches and inserts
* new strings in the dictionary only for unmatched strings or for short
* matches. It is used only for the fast compression options.
*/
var zip_deflate_fast = function() {
while(zip_lookahead != 0 && zip_qhead == null) {
var flush; // set if current block must be flushed
/* Insert the string window[strstart .. strstart+2] in the
* dictionary, and set hash_head to the head of the hash chain:
*/
zip_INSERT_STRING();
/* Find the longest match, discarding those <= prev_length.
* At this point we have always match_length < MIN_MATCH
*/
if(zip_hash_head != zip_NIL &&
zip_strstart - zip_hash_head <= zip_MAX_DIST) {
/* To simplify the code, we prevent matches with the string
* of window index 0 (in particular we have to avoid a match
* of the string with itself at the start of the input file).
*/
zip_match_length = zip_longest_match(zip_hash_head);
/* longest_match() sets match_start */
if(zip_match_length > zip_lookahead)
zip_match_length = zip_lookahead;
}
if(zip_match_length >= zip_MIN_MATCH) {
// check_match(strstart, match_start, match_length);
flush = zip_ct_tally(zip_strstart - zip_match_start,
zip_match_length - zip_MIN_MATCH);
zip_lookahead -= zip_match_length;
/* Insert new strings in the hash table only if the match length
* is not too large. This saves time but degrades compression.
*/
if(zip_match_length <= zip_max_lazy_match) {
zip_match_length--; // string at strstart already in hash table
do {
zip_strstart++;
zip_INSERT_STRING();
/* strstart never exceeds WSIZE-MAX_MATCH, so there are
* always MIN_MATCH bytes ahead. If lookahead < MIN_MATCH
* these bytes are garbage, but it does not matter since
* the next lookahead bytes will be emitted as literals.
*/
} while(--zip_match_length != 0);
zip_strstart++;
} else {
zip_strstart += zip_match_length;
zip_match_length = 0;
zip_ins_h = zip_window[zip_strstart] & 0xff;
// UPDATE_HASH(ins_h, window[strstart + 1]);
zip_ins_h = ((zip_ins_h<<zip_H_SHIFT) ^ (zip_window[zip_strstart + 1] & 0xff)) & zip_HASH_MASK;
//#if MIN_MATCH != 3
// Call UPDATE_HASH() MIN_MATCH-3 more times
//#endif
}
} else {
/* No match, output a literal byte */
flush = zip_ct_tally(0, zip_window[zip_strstart] & 0xff);
zip_lookahead--;
zip_strstart++;
}
if(flush) {
zip_flush_block(0);
zip_block_start = zip_strstart;
}
/* Make sure that we always have enough lookahead, except
* at the end of the input file. We need MAX_MATCH bytes
* for the next match, plus MIN_MATCH bytes to insert the
* string following the next match.
*/
while(zip_lookahead < zip_MIN_LOOKAHEAD && !zip_eofile)
zip_fill_window();
}
}
var zip_deflate_better = function() {
/* Process the input block. */
while(zip_lookahead != 0 && zip_qhead == null) {
/* Insert the string window[strstart .. strstart+2] in the
* dictionary, and set hash_head to the head of the hash chain:
*/
zip_INSERT_STRING();
/* Find the longest match, discarding those <= prev_length.
*/
zip_prev_length = zip_match_length;
zip_prev_match = zip_match_start;
zip_match_length = zip_MIN_MATCH - 1;
if(zip_hash_head != zip_NIL &&
zip_prev_length < zip_max_lazy_match &&
zip_strstart - zip_hash_head <= zip_MAX_DIST) {
/* To simplify the code, we prevent matches with the string
* of window index 0 (in particular we have to avoid a match
* of the string with itself at the start of the input file).
*/
zip_match_length = zip_longest_match(zip_hash_head);
/* longest_match() sets match_start */
if(zip_match_length > zip_lookahead)
zip_match_length = zip_lookahead;
/* Ignore a length 3 match if it is too distant: */
if(zip_match_length == zip_MIN_MATCH &&
zip_strstart - zip_match_start > zip_TOO_FAR) {
/* If prev_match is also MIN_MATCH, match_start is garbage
* but we will ignore the current match anyway.
*/
zip_match_length--;
}
}
/* If there was a match at the previous step and the current
* match is not better, output the previous match:
*/
if(zip_prev_length >= zip_MIN_MATCH &&
zip_match_length <= zip_prev_length) {
var flush; // set if current block must be flushed
// check_match(strstart - 1, prev_match, prev_length);
flush = zip_ct_tally(zip_strstart - 1 - zip_prev_match,
zip_prev_length - zip_MIN_MATCH);
/* Insert in hash table all strings up to the end of the match.
* strstart-1 and strstart are already inserted.
*/
zip_lookahead -= zip_prev_length - 1;
zip_prev_length -= 2;
do {
zip_strstart++;
zip_INSERT_STRING();
/* strstart never exceeds WSIZE-MAX_MATCH, so there are
* always MIN_MATCH bytes ahead. If lookahead < MIN_MATCH
* these bytes are garbage, but it does not matter since the
* next lookahead bytes will always be emitted as literals.
*/
} while(--zip_prev_length != 0);
zip_match_available = 0;
zip_match_length = zip_MIN_MATCH - 1;
zip_strstart++;
if(flush) {
zip_flush_block(0);
zip_block_start = zip_strstart;
}
} else if(zip_match_available != 0) {
/* If there was no match at the previous position, output a
* single literal. If there was a match but the current match
* is longer, truncate the previous match to a single literal.
*/
if(zip_ct_tally(0, zip_window[zip_strstart - 1] & 0xff)) {
zip_flush_block(0);
zip_block_start = zip_strstart;
}
zip_strstart++;
zip_lookahead--;
} else {
/* There is no previous match to compare with, wait for
* the next step to decide.
*/
zip_match_available = 1;
zip_strstart++;
zip_lookahead--;
}
/* Make sure that we always have enough lookahead, except
* at the end of the input file. We need MAX_MATCH bytes
* for the next match, plus MIN_MATCH bytes to insert the
* string following the next match.
*/
while(zip_lookahead < zip_MIN_LOOKAHEAD && !zip_eofile)
zip_fill_window();
}
}
var zip_init_deflate = function() {
if(zip_eofile)
return;
zip_bi_buf = 0;
zip_bi_valid = 0;
zip_ct_init();
zip_lm_init();
zip_qhead = null;
zip_outcnt = 0;
zip_outoff = 0;
if(zip_compr_level <= 3)
{
zip_prev_length = zip_MIN_MATCH - 1;
zip_match_length = 0;
}
else
{
zip_match_length = zip_MIN_MATCH - 1;
zip_match_available = 0;
}
zip_complete = false;
}
/* ==========================================================================
* Same as above, but achieves better compression. We use a lazy
* evaluation for matches: a match is finally adopted only if there is
* no better match at the next window position.
*/
var zip_deflate_internal = function(buff, off, buff_size) {
var n;
if(!zip_initflag)
{
zip_init_deflate();
zip_initflag = true;
if(zip_lookahead == 0) { // empty
zip_complete = true;
return 0;
}
}
if((n = zip_qcopy(buff, off, buff_size)) == buff_size)
return buff_size;
if(zip_complete)
return n;
if(zip_compr_level <= 3) // optimized for speed
zip_deflate_fast();
else
zip_deflate_better();
if(zip_lookahead == 0) {
if(zip_match_available != 0)
zip_ct_tally(0, zip_window[zip_strstart - 1] & 0xff);
zip_flush_block(1);
zip_complete = true;
}
return n + zip_qcopy(buff, n + off, buff_size - n);
}
var zip_qcopy = function(buff, off, buff_size) {
var n, i, j;
n = 0;
while(zip_qhead != null && n < buff_size)
{
i = buff_size - n;
if(i > zip_qhead.len)
i = zip_qhead.len;
// System.arraycopy(qhead.ptr, qhead.off, buff, off + n, i);
for(j = 0; j < i; j++)
buff[off + n + j] = zip_qhead.ptr[zip_qhead.off + j];
zip_qhead.off += i;
zip_qhead.len -= i;
n += i;
if(zip_qhead.len == 0) {
var p;
p = zip_qhead;
zip_qhead = zip_qhead.next;
zip_reuse_queue(p);
}
}
if(n == buff_size)
return n;
if(zip_outoff < zip_outcnt) {
i = buff_size - n;
if(i > zip_outcnt - zip_outoff)
i = zip_outcnt - zip_outoff;
// System.arraycopy(outbuf, outoff, buff, off + n, i);
for(j = 0; j < i; j++)
buff[off + n + j] = zip_outbuf[zip_outoff + j];
zip_outoff += i;
n += i;
if(zip_outcnt == zip_outoff)
zip_outcnt = zip_outoff = 0;
}
return n;
}
/* ==========================================================================
* Allocate the match buffer, initialize the various tables and save the
* location of the internal file attribute (ascii/binary) and method
* (DEFLATE/STORE).
*/
var zip_ct_init = function() {
var n; // iterates over tree elements
var bits; // bit counter
var length; // length value
var code; // code value
var dist; // distance index
if(zip_static_dtree[0].dl != 0) return; // ct_init already called
zip_l_desc.dyn_tree = zip_dyn_ltree;
zip_l_desc.static_tree = zip_static_ltree;
zip_l_desc.extra_bits = zip_extra_lbits;
zip_l_desc.extra_base = zip_LITERALS + 1;
zip_l_desc.elems = zip_L_CODES;
zip_l_desc.max_length = zip_MAX_BITS;
zip_l_desc.max_code = 0;
zip_d_desc.dyn_tree = zip_dyn_dtree;
zip_d_desc.static_tree = zip_static_dtree;
zip_d_desc.extra_bits = zip_extra_dbits;
zip_d_desc.extra_base = 0;
zip_d_desc.elems = zip_D_CODES;
zip_d_desc.max_length = zip_MAX_BITS;
zip_d_desc.max_code = 0;
zip_bl_desc.dyn_tree = zip_bl_tree;
zip_bl_desc.static_tree = null;
zip_bl_desc.extra_bits = zip_extra_blbits;
zip_bl_desc.extra_base = 0;
zip_bl_desc.elems = zip_BL_CODES;
zip_bl_desc.max_length = zip_MAX_BL_BITS;
zip_bl_desc.max_code = 0;
// Initialize the mapping length (0..255) -> length code (0..28)
length = 0;
for(code = 0; code < zip_LENGTH_CODES-1; code++) {
zip_base_length[code] = length;
for(n = 0; n < (1<<zip_extra_lbits[code]); n++)
zip_length_code[length++] = code;
}
// Assert (length == 256, "ct_init: length != 256");
/* Note that the length 255 (match length 258) can be represented
* in two different ways: code 284 + 5 bits or code 285, so we
* overwrite length_code[255] to use the best encoding:
*/
zip_length_code[length-1] = code;
/* Initialize the mapping dist (0..32K) -> dist code (0..29) */
dist = 0;
for(code = 0 ; code < 16; code++) {
zip_base_dist[code] = dist;
for(n = 0; n < (1<<zip_extra_dbits[code]); n++) {
zip_dist_code[dist++] = code;
}
}
// Assert (dist == 256, "ct_init: dist != 256");
dist >>= 7; // from now on, all distances are divided by 128
for( ; code < zip_D_CODES; code++) {
zip_base_dist[code] = dist << 7;
for(n = 0; n < (1<<(zip_extra_dbits[code]-7)); n++)
zip_dist_code[256 + dist++] = code;
}
// Assert (dist == 256, "ct_init: 256+dist != 512");
// Construct the codes of the static literal tree
for(bits = 0; bits <= zip_MAX_BITS; bits++)
zip_bl_count[bits] = 0;
n = 0;
while(n <= 143) { zip_static_ltree[n++].dl = 8; zip_bl_count[8]++; }
while(n <= 255) { zip_static_ltree[n++].dl = 9; zip_bl_count[9]++; }
while(n <= 279) { zip_static_ltree[n++].dl = 7; zip_bl_count[7]++; }
while(n <= 287) { zip_static_ltree[n++].dl = 8; zip_bl_count[8]++; }
/* Codes 286 and 287 do not exist, but we must include them in the
* tree construction to get a canonical Huffman tree (longest code
* all ones)
*/
zip_gen_codes(zip_static_ltree, zip_L_CODES + 1);
/* The static distance tree is trivial: */
for(n = 0; n < zip_D_CODES; n++) {
zip_static_dtree[n].dl = 5;
zip_static_dtree[n].fc = zip_bi_reverse(n, 5);
}
// Initialize the first block of the first file:
zip_init_block();
}
/* ==========================================================================
* Initialize a new block.
*/
var zip_init_block = function() {
var n; // iterates over tree elements
// Initialize the trees.
for(n = 0; n < zip_L_CODES; n++) zip_dyn_ltree[n].fc = 0;
for(n = 0; n < zip_D_CODES; n++) zip_dyn_dtree[n].fc = 0;
for(n = 0; n < zip_BL_CODES; n++) zip_bl_tree[n].fc = 0;
zip_dyn_ltree[zip_END_BLOCK].fc = 1;
zip_opt_len = zip_static_len = 0;
zip_last_lit = zip_last_dist = zip_last_flags = 0;
zip_flags = 0;
zip_flag_bit = 1;
}
/* ==========================================================================
* Restore the heap property by moving down the tree starting at node k,
* exchanging a node with the smallest of its two sons if necessary, stopping
* when the heap property is re-established (each father smaller than its
* two sons).
*/
var zip_pqdownheap = function(
tree, // the tree to restore
k) { // node to move down
var v = zip_heap[k];
var j = k << 1; // left son of k
while(j <= zip_heap_len) {
// Set j to the smallest of the two sons:
if(j < zip_heap_len &&
zip_SMALLER(tree, zip_heap[j + 1], zip_heap[j]))
j++;
// Exit if v is smaller than both sons
if(zip_SMALLER(tree, v, zip_heap[j]))
break;
// Exchange v with the smallest son
zip_heap[k] = zip_heap[j];
k = j;
// And continue down the tree, setting j to the left son of k
j <<= 1;
}
zip_heap[k] = v;
}
/* ==========================================================================
* Compute the optimal bit lengths for a tree and update the total bit length
* for the current block.
* IN assertion: the fields freq and dad are set, heap[heap_max] and
* above are the tree nodes sorted by increasing frequency.
* OUT assertions: the field len is set to the optimal bit length, the
* array bl_count contains the frequencies for each bit length.
* The length opt_len is updated; static_len is also updated if stree is
* not null.
*/
var zip_gen_bitlen = function(desc) { // the tree descriptor
var tree = desc.dyn_tree;
var extra = desc.extra_bits;
var base = desc.extra_base;
var max_code = desc.max_code;
var max_length = desc.max_length;
var stree = desc.static_tree;
var h; // heap index
var n, m; // iterate over the tree elements
var bits; // bit length
var xbits; // extra bits
var f; // frequency
var overflow = 0; // number of elements with bit length too large
for(bits = 0; bits <= zip_MAX_BITS; bits++)
zip_bl_count[bits] = 0;
/* In a first pass, compute the optimal bit lengths (which may
* overflow in the case of the bit length tree).
*/
tree[zip_heap[zip_heap_max]].dl = 0; // root of the heap
for(h = zip_heap_max + 1; h < zip_HEAP_SIZE; h++) {
n = zip_heap[h];
bits = tree[tree[n].dl].dl + 1;
if(bits > max_length) {
bits = max_length;
overflow++;
}
tree[n].dl = bits;
// We overwrite tree[n].dl which is no longer needed
if(n > max_code)
continue; // not a leaf node
zip_bl_count[bits]++;
xbits = 0;
if(n >= base)
xbits = extra[n - base];
f = tree[n].fc;
zip_opt_len += f * (bits + xbits);
if(stree != null)
zip_static_len += f * (stree[n].dl + xbits);
}
if(overflow == 0)
return;
// This happens for example on obj2 and pic of the Calgary corpus
// Find the first bit length which could increase:
do {
bits = max_length - 1;
while(zip_bl_count[bits] == 0)
bits--;
zip_bl_count[bits]--; // move one leaf down the tree
zip_bl_count[bits + 1] += 2; // move one overflow item as its brother
zip_bl_count[max_length]--;
/* The brother of the overflow item also moves one step up,
* but this does not affect bl_count[max_length]
*/
overflow -= 2;
} while(overflow > 0);
/* Now recompute all bit lengths, scanning in increasing frequency.
* h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
* lengths instead of fixing only the wrong ones. This idea is taken
* from 'ar' written by Haruhiko Okumura.)
*/
for(bits = max_length; bits != 0; bits--) {
n = zip_bl_count[bits];
while(n != 0) {
m = zip_heap[--h];
if(m > max_code)
continue;
if(tree[m].dl != bits) {
zip_opt_len += (bits - tree[m].dl) * tree[m].fc;
tree[m].fc = bits;
}
n--;
}
}
}
/* ==========================================================================
* Generate the codes for a given tree and bit counts (which need not be
* optimal).
* IN assertion: the array bl_count contains the bit length statistics for
* the given tree and the field len is set for all tree elements.
* OUT assertion: the field code is set for all tree elements of non
* zero code length.
*/
var zip_gen_codes = function(tree, // the tree to decorate
max_code) { // largest code with non zero frequency
var next_code = new Array(zip_MAX_BITS+1); // next code value for each bit length
var code = 0; // running code value
var bits; // bit index
var n; // code index
/* The distribution counts are first used to generate the code values
* without bit reversal.
*/
for(bits = 1; bits <= zip_MAX_BITS; bits++) {
code = ((code + zip_bl_count[bits-1]) << 1);
next_code[bits] = code;
}
/* Check that the bit counts in bl_count are consistent. The last code
* must be all ones.
*/
// Assert (code + encoder->bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
// "inconsistent bit counts");
// Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
for(n = 0; n <= max_code; n++) {
var len = tree[n].dl;
if(len == 0)
continue;
// Now reverse the bits
tree[n].fc = zip_bi_reverse(next_code[len]++, len);
// Tracec(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
// n, (isgraph(n) ? n : ' '), len, tree[n].fc, next_code[len]-1));
}
}
/* ==========================================================================
* Construct one Huffman tree and assigns the code bit strings and lengths.
* Update the total bit length for the current block.
* IN assertion: the field freq is set for all tree elements.
* OUT assertions: the fields len and code are set to the optimal bit length
* and corresponding code. The length opt_len is updated; static_len is
* also updated if stree is not null. The field max_code is set.
*/
var zip_build_tree = function(desc) { // the tree descriptor
var tree = desc.dyn_tree;
var stree = desc.static_tree;
var elems = desc.elems;
var n, m; // iterate over heap elements
var max_code = -1; // largest code with non zero frequency
var node = elems; // next internal node of the tree
/* Construct the initial heap, with least frequent element in
* heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
* heap[0] is not used.
*/
zip_heap_len = 0;
zip_heap_max = zip_HEAP_SIZE;
for(n = 0; n < elems; n++) {
if(tree[n].fc != 0) {
zip_heap[++zip_heap_len] = max_code = n;
zip_depth[n] = 0;
} else
tree[n].dl = 0;
}
/* The pkzip format requires that at least one distance code exists,
* and that at least one bit should be sent even if there is only one
* possible code. So to avoid special checks later on we force at least
* two codes of non zero frequency.
*/
while(zip_heap_len < 2) {
var xnew = zip_heap[++zip_heap_len] = (max_code < 2 ? ++max_code : 0);
tree[xnew].fc = 1;
zip_depth[xnew] = 0;
zip_opt_len--;
if(stree != null)
zip_static_len -= stree[xnew].dl;
// new is 0 or 1 so it does not have extra bits
}
desc.max_code = max_code;
/* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
* establish sub-heaps of increasing lengths:
*/
for(n = zip_heap_len >> 1; n >= 1; n--)
zip_pqdownheap(tree, n);
/* Construct the Huffman tree by repeatedly combining the least two
* frequent nodes.
*/
do {
n = zip_heap[zip_SMALLEST];
zip_heap[zip_SMALLEST] = zip_heap[zip_heap_len--];
zip_pqdownheap(tree, zip_SMALLEST);
m = zip_heap[zip_SMALLEST]; // m = node of next least frequency
// keep the nodes sorted by frequency
zip_heap[--zip_heap_max] = n;
zip_heap[--zip_heap_max] = m;
// Create a new node father of n and m
tree[node].fc = tree[n].fc + tree[m].fc;
// depth[node] = (char)(MAX(depth[n], depth[m]) + 1);
if(zip_depth[n] > zip_depth[m] + 1)
zip_depth[node] = zip_depth[n];
else
zip_depth[node] = zip_depth[m] + 1;
tree[n].dl = tree[m].dl = node;
// and insert the new node in the heap
zip_heap[zip_SMALLEST] = node++;
zip_pqdownheap(tree, zip_SMALLEST);
} while(zip_heap_len >= 2);
zip_heap[--zip_heap_max] = zip_heap[zip_SMALLEST];
/* At this point, the fields freq and dad are set. We can now
* generate the bit lengths.
*/
zip_gen_bitlen(desc);
// The field len is now set, we can generate the bit codes
zip_gen_codes(tree, max_code);
}
/* ==========================================================================
* Scan a literal or distance tree to determine the frequencies of the codes
* in the bit length tree. Updates opt_len to take into account the repeat
* counts. (The contribution of the bit length codes will be added later
* during the construction of bl_tree.)
*/
var zip_scan_tree = function(tree,// the tree to be scanned
max_code) { // and its largest code of non zero frequency
var n; // iterates over all tree elements
var prevlen = -1; // last emitted length
var curlen; // length of current code
var nextlen = tree[0].dl; // length of next code
var count = 0; // repeat count of the current code
var max_count = 7; // max repeat count
var min_count = 4; // min repeat count
if(nextlen == 0) {
max_count = 138;
min_count = 3;
}
tree[max_code + 1].dl = 0xffff; // guard
for(n = 0; n <= max_code; n++) {
curlen = nextlen;
nextlen = tree[n + 1].dl;
if(++count < max_count && curlen == nextlen)
continue;
else if(count < min_count)
zip_bl_tree[curlen].fc += count;
else if(curlen != 0) {
if(curlen != prevlen)
zip_bl_tree[curlen].fc++;
zip_bl_tree[zip_REP_3_6].fc++;
} else if(count <= 10)
zip_bl_tree[zip_REPZ_3_10].fc++;
else
zip_bl_tree[zip_REPZ_11_138].fc++;
count = 0; prevlen = curlen;
if(nextlen == 0) {
max_count = 138;
min_count = 3;
} else if(curlen == nextlen) {
max_count = 6;
min_count = 3;
} else {
max_count = 7;
min_count = 4;
}
}
}
/* ==========================================================================
* Send a literal or distance tree in compressed form, using the codes in
* bl_tree.
*/
var zip_send_tree = function(tree, // the tree to be scanned
max_code) { // and its largest code of non zero frequency
var n; // iterates over all tree elements
var prevlen = -1; // last emitted length
var curlen; // length of current code
var nextlen = tree[0].dl; // length of next code
var count = 0; // repeat count of the current code
var max_count = 7; // max repeat count
var min_count = 4; // min repeat count
/* tree[max_code+1].dl = -1; */ /* guard already set */
if(nextlen == 0) {
max_count = 138;
min_count = 3;
}
for(n = 0; n <= max_code; n++) {
curlen = nextlen;
nextlen = tree[n+1].dl;
if(++count < max_count && curlen == nextlen) {
continue;
} else if(count < min_count) {
do { zip_SEND_CODE(curlen, zip_bl_tree); } while(--count != 0);
} else if(curlen != 0) {
if(curlen != prevlen) {
zip_SEND_CODE(curlen, zip_bl_tree);
count--;
}
// Assert(count >= 3 && count <= 6, " 3_6?");
zip_SEND_CODE(zip_REP_3_6, zip_bl_tree);
zip_send_bits(count - 3, 2);
} else if(count <= 10) {
zip_SEND_CODE(zip_REPZ_3_10, zip_bl_tree);
zip_send_bits(count-3, 3);
} else {
zip_SEND_CODE(zip_REPZ_11_138, zip_bl_tree);
zip_send_bits(count-11, 7);
}
count = 0;
prevlen = curlen;
if(nextlen == 0) {
max_count = 138;
min_count = 3;
} else if(curlen == nextlen) {
max_count = 6;
min_count = 3;
} else {
max_count = 7;
min_count = 4;
}
}
}
/* ==========================================================================
* Construct the Huffman tree for the bit lengths and return the index in
* bl_order of the last bit length code to send.
*/
var zip_build_bl_tree = function() {
var max_blindex; // index of last bit length code of non zero freq
// Determine the bit length frequencies for literal and distance trees
zip_scan_tree(zip_dyn_ltree, zip_l_desc.max_code);
zip_scan_tree(zip_dyn_dtree, zip_d_desc.max_code);
// Build the bit length tree:
zip_build_tree(zip_bl_desc);
/* opt_len now includes the length of the tree representations, except
* the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
*/
/* Determine the number of bit length codes to send. The pkzip format
* requires that at least 4 bit length codes be sent. (appnote.txt says
* 3 but the actual value used is 4.)
*/
for(max_blindex = zip_BL_CODES-1; max_blindex >= 3; max_blindex--) {
if(zip_bl_tree[zip_bl_order[max_blindex]].dl != 0) break;
}
/* Update opt_len to include the bit length tree and counts */
zip_opt_len += 3*(max_blindex+1) + 5+5+4;
// Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
// encoder->opt_len, encoder->static_len));
return max_blindex;
}
/* ==========================================================================
* Send the header for a block using dynamic Huffman trees: the counts, the
* lengths of the bit length codes, the literal tree and the distance tree.
* IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
*/
var zip_send_all_trees = function(lcodes, dcodes, blcodes) { // number of codes for each tree
var rank; // index in bl_order
// Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
// Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
// "too many codes");
// Tracev((stderr, "\nbl counts: "));
zip_send_bits(lcodes-257, 5); // not +255 as stated in appnote.txt
zip_send_bits(dcodes-1, 5);
zip_send_bits(blcodes-4, 4); // not -3 as stated in appnote.txt
for(rank = 0; rank < blcodes; rank++) {
// Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
zip_send_bits(zip_bl_tree[zip_bl_order[rank]].dl, 3);
}
// send the literal tree
zip_send_tree(zip_dyn_ltree,lcodes-1);
// send the distance tree
zip_send_tree(zip_dyn_dtree,dcodes-1);
}
/* ==========================================================================
* Determine the best encoding for the current block: dynamic trees, static
* trees or store, and output the encoded block to the zip file.
*/
var zip_flush_block = function(eof) { // true if this is the last block for a file
var opt_lenb, static_lenb; // opt_len and static_len in bytes
var max_blindex; // index of last bit length code of non zero freq
var stored_len; // length of input block
stored_len = zip_strstart - zip_block_start;
zip_flag_buf[zip_last_flags] = zip_flags; // Save the flags for the last 8 items
// Construct the literal and distance trees
zip_build_tree(zip_l_desc);
// Tracev((stderr, "\nlit data: dyn %ld, stat %ld",
// encoder->opt_len, encoder->static_len));
zip_build_tree(zip_d_desc);
// Tracev((stderr, "\ndist data: dyn %ld, stat %ld",
// encoder->opt_len, encoder->static_len));
/* At this point, opt_len and static_len are the total bit lengths of
* the compressed block data, excluding the tree representations.
*/
/* Build the bit length tree for the above two trees, and get the index
* in bl_order of the last bit length code to send.
*/
max_blindex = zip_build_bl_tree();
// Determine the best encoding. Compute first the block length in bytes
opt_lenb = (zip_opt_len +3+7)>>3;
static_lenb = (zip_static_len+3+7)>>3;
// Trace((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u dist %u ",
// opt_lenb, encoder->opt_len,
// static_lenb, encoder->static_len, stored_len,
// encoder->last_lit, encoder->last_dist));
if(static_lenb <= opt_lenb)
opt_lenb = static_lenb;
if(stored_len + 4 <= opt_lenb // 4: two words for the lengths
&& zip_block_start >= 0) {
var i;
/* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
* Otherwise we can't have processed more than WSIZE input bytes since
* the last block flush, because compression would have been
* successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
* transform a block into a stored block.
*/
zip_send_bits((zip_STORED_BLOCK<<1)+eof, 3); /* send block type */
zip_bi_windup(); /* align on byte boundary */
zip_put_short(stored_len);
zip_put_short(~stored_len);
// copy block
/*
p = &window[block_start];
for(i = 0; i < stored_len; i++)
put_byte(p[i]);
*/
for(i = 0; i < stored_len; i++)
zip_put_byte(zip_window[zip_block_start + i]);
} else if(static_lenb == opt_lenb) {
zip_send_bits((zip_STATIC_TREES<<1)+eof, 3);
zip_compress_block(zip_static_ltree, zip_static_dtree);
} else {
zip_send_bits((zip_DYN_TREES<<1)+eof, 3);
zip_send_all_trees(zip_l_desc.max_code+1,
zip_d_desc.max_code+1,
max_blindex+1);
zip_compress_block(zip_dyn_ltree, zip_dyn_dtree);
}
zip_init_block();
if(eof != 0)
zip_bi_windup();
}
/* ==========================================================================
* Save the match info and tally the frequency counts. Return true if
* the current block must be flushed.
*/
var zip_ct_tally = function(
dist, // distance of matched string
lc) { // match length-MIN_MATCH or unmatched char (if dist==0)
zip_l_buf[zip_last_lit++] = lc;
if(dist == 0) {
// lc is the unmatched char
zip_dyn_ltree[lc].fc++;
} else {
// Here, lc is the match length - MIN_MATCH
dist--; // dist = match distance - 1
// Assert((ush)dist < (ush)MAX_DIST &&
// (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
// (ush)D_CODE(dist) < (ush)D_CODES, "ct_tally: bad match");
zip_dyn_ltree[zip_length_code[lc]+zip_LITERALS+1].fc++;
zip_dyn_dtree[zip_D_CODE(dist)].fc++;
zip_d_buf[zip_last_dist++] = dist;
zip_flags |= zip_flag_bit;
}
zip_flag_bit <<= 1;
// Output the flags if they fill a byte
if((zip_last_lit & 7) == 0) {
zip_flag_buf[zip_last_flags++] = zip_flags;
zip_flags = 0;
zip_flag_bit = 1;
}
// Try to guess if it is profitable to stop the current block here
if(zip_compr_level > 2 && (zip_last_lit & 0xfff) == 0) {
// Compute an upper bound for the compressed length
var out_length = zip_last_lit * 8;
var in_length = zip_strstart - zip_block_start;
var dcode;
for(dcode = 0; dcode < zip_D_CODES; dcode++) {
out_length += zip_dyn_dtree[dcode].fc * (5 + zip_extra_dbits[dcode]);
}
out_length >>= 3;
// Trace((stderr,"\nlast_lit %u, last_dist %u, in %ld, out ~%ld(%ld%%) ",
// encoder->last_lit, encoder->last_dist, in_length, out_length,
// 100L - out_length*100L/in_length));
if(zip_last_dist < parseInt(zip_last_lit/2) &&
out_length < parseInt(in_length/2))
return true;
}
return (zip_last_lit == zip_LIT_BUFSIZE-1 ||
zip_last_dist == zip_DIST_BUFSIZE);
/* We avoid equality with LIT_BUFSIZE because of wraparound at 64K
* on 16 bit machines and because stored blocks are restricted to
* 64K-1 bytes.
*/
}
/* ==========================================================================
* Send the block data compressed using the given Huffman trees
*/
var zip_compress_block = function(
ltree, // literal tree
dtree) { // distance tree
var dist; // distance of matched string
var lc; // match length or unmatched char (if dist == 0)
var lx = 0; // running index in l_buf
var dx = 0; // running index in d_buf
var fx = 0; // running index in flag_buf
var flag = 0; // current flags
var code; // the code to send
var extra; // number of extra bits to send
if(zip_last_lit != 0) do {
if((lx & 7) == 0)
flag = zip_flag_buf[fx++];
lc = zip_l_buf[lx++] & 0xff;
if((flag & 1) == 0) {
zip_SEND_CODE(lc, ltree); /* send a literal byte */
// Tracecv(isgraph(lc), (stderr," '%c' ", lc));
} else {
// Here, lc is the match length - MIN_MATCH
code = zip_length_code[lc];
zip_SEND_CODE(code+zip_LITERALS+1, ltree); // send the length code
extra = zip_extra_lbits[code];
if(extra != 0) {
lc -= zip_base_length[code];
zip_send_bits(lc, extra); // send the extra length bits
}
dist = zip_d_buf[dx++];
// Here, dist is the match distance - 1
code = zip_D_CODE(dist);
// Assert (code < D_CODES, "bad d_code");
zip_SEND_CODE(code, dtree); // send the distance code
extra = zip_extra_dbits[code];
if(extra != 0) {
dist -= zip_base_dist[code];
zip_send_bits(dist, extra); // send the extra distance bits
}
} // literal or match pair ?
flag >>= 1;
} while(lx < zip_last_lit);
zip_SEND_CODE(zip_END_BLOCK, ltree);
}
/* ==========================================================================
* Send a value on a given number of bits.
* IN assertion: length <= 16 and value fits in length bits.
*/
var zip_Buf_size = 16; // bit size of bi_buf
var zip_send_bits = function(
value, // value to send
length) { // number of bits
/* If not enough room in bi_buf, use (valid) bits from bi_buf and
* (16 - bi_valid) bits from value, leaving (width - (16-bi_valid))
* unused bits in value.
*/
if(zip_bi_valid > zip_Buf_size - length) {
zip_bi_buf |= (value << zip_bi_valid);
zip_put_short(zip_bi_buf);
zip_bi_buf = (value >> (zip_Buf_size - zip_bi_valid));
zip_bi_valid += length - zip_Buf_size;
} else {
zip_bi_buf |= value << zip_bi_valid;
zip_bi_valid += length;
}
}
/* ==========================================================================
* Reverse the first len bits of a code, using straightforward code (a faster
* method would use a table)
* IN assertion: 1 <= len <= 15
*/
var zip_bi_reverse = function(
code, // the value to invert
len) { // its bit length
var res = 0;
do {
res |= code & 1;
code >>= 1;
res <<= 1;
} while(--len > 0);
return res >> 1;
}
/* ==========================================================================
* Write out any remaining bits in an incomplete byte.
*/
var zip_bi_windup = function() {
if(zip_bi_valid > 8) {
zip_put_short(zip_bi_buf);
} else if(zip_bi_valid > 0) {
zip_put_byte(zip_bi_buf);
}
zip_bi_buf = 0;
zip_bi_valid = 0;
}
var zip_qoutbuf = function() {
if(zip_outcnt != 0) {
var q, i;
q = zip_new_queue();
if(zip_qhead == null)
zip_qhead = zip_qtail = q;
else
zip_qtail = zip_qtail.next = q;
q.len = zip_outcnt - zip_outoff;
// System.arraycopy(zip_outbuf, zip_outoff, q.ptr, 0, q.len);
for(i = 0; i < q.len; i++)
q.ptr[i] = zip_outbuf[zip_outoff + i];
zip_outcnt = zip_outoff = 0;
}
}
var zip_deflate = function(str, level) {
var i, j;
zip_deflate_data = str;
zip_deflate_pos = 0;
if(typeof level == "undefined")
level = zip_DEFAULT_LEVEL;
zip_deflate_start(level);
var buff = new Array(1024);
var aout = [];
while((i = zip_deflate_internal(buff, 0, buff.length)) > 0) {
var cbuf = new Array(i);
for(j = 0; j < i; j++){
cbuf[j] = String.fromCharCode(buff[j]);
}
aout[aout.length] = cbuf.join("");
}
zip_deflate_data = null; // G.C.
return aout.join("");
}
//
// end of the script of Masanao Izumo.
//
// we add the compression method for JSZip
JSZip.compressions["DEFLATE"] = {
magic : "\x08\x00",
compress : function (content) {
return zip_deflate(content);
}
}
})();
| 07pratik-androidui | asset-studio/src/lib/jszip/jszip-deflate.js | JavaScript | asf20 | 54,215 |
<!DOCTYPE html>
<html>
<head>
<title>JavaScript Zip Testing</title>
<link media="screen" href="qunit.css" type="text/css" rel="stylesheet">
<script type="text/javascript" src="../jszip.js"></script>
<script type="text/javascript" src="../jszip-deflate.js"></script>
<script type="text/javascript" src="qunit.js"></script>
<script type="text/javascript">
function similar(actual, expected, mistakes)
{
if (actual.length !== expected.length) mistakes--;
for (var i = 0; i < Math.min(actual.length, expected.length); i++)
{
if (actual[i] !== expected[i]) mistakes--;
}
if (mistakes < 0)
return false;
else
return true;
}
var refZips = [];
refZips["text"]=JSZipBase64.decode("UEsDBAoDAAAAAJx08Trj5ZWwDAAAAAwAAAAJAAAASGVsbG8udHh0SGVsbG8gV29ybGQKUEsBAhQDCgMAAAAAnHTxOuPllbAMAAAADAAAAAkAAAAAAAAAAAAggKSBAAAAAEhlbGxvLnR4dFBLBQYAAAAAAQABADcAAAAzAAAAAAA=");
refZips["utf8"]=JSZipBase64.decode("UEsDBAoAAAAAAJp95Tx8M2u8CgAAAAoAAAAKAAAAYW1vdW50LnR4dMOi4oCawqwxNQpQSwECFAAKAAAAAACafeU8fDNrvAoAAAAKAAAACgAAAAAAAAAAAAAAAAAAAAAAYW1vdW50LnR4dFBLBQYAAAAAAQABADgAAAAyAAAAAAA=");
refZips["image"]=JSZipBase64.decode("UEsDBAoDAAAAABVv6jo8P+uKKQAAACkAAAAJAAAAc21pbGUuZ2lmR0lGODdhBQAFAIACAAAAAP/eACwAAAAABQAFAAACCIwPkWerClIBADtQSwECFAMKAwAAAAAVb+o6PD/riikAAAApAAAACQAAAAAAAAAAACCApIEAAAAAc21pbGUuZ2lmUEsFBgAAAAABAAEANwAAAFAAAAAAAA==");
refZips["folder"]=JSZipBase64.decode("UEsDBAoDAAAAAANt8zoAAAAAAAAAAAAAAAAHAAAAZm9sZGVyL1BLAQIUAwoDAAAAAANt8zoAAAAAAAAAAAAAAAAHAAAAAAAAAAAAEIDtQQAAAABmb2xkZXIvUEsFBgAAAAABAAEANQAAACUAAAAAAA==");
refZips["all"]=JSZipBase64.decode("UEsDBAoDAAAAAJxs8Trj5ZWwDAAAAAwAAAAJAAAASGVsbG8udHh0SGVsbG8gV29ybGQKUEsDBAoDAAAAALFs8ToAAAAAAAAAAAAAAAAHAAAAaW1hZ2VzL1BLAwQKAwAAAAAVZ+o6PD/riikAAAApAAAAEAAAAGltYWdlcy9zbWlsZS5naWZHSUY4N2EFAAUAgAIAAAAA/94ALAAAAAAFAAUAAAIIjA+RZ6sKUgEAO1BLAQIUAwoDAAAAAJxs8Trj5ZWwDAAAAAwAAAAJAAAAAAAAAAAAIICkgQAAAABIZWxsby50eHRQSwECFAMKAwAAAACxbPE6AAAAAAAAAAAAAAAABwAAAAAAAAAAABCA7UEzAAAAaW1hZ2VzL1BLAQIUAwoDAAAAABVn6jo8P+uKKQAAACkAAAAQAAAAAAAAAAAAIICkgVgAAABpbWFnZXMvc21pbGUuZ2lmUEsFBgAAAAADAAMAqgAAAK8AAAAAAA==");
refZips["STORE-text"]=JSZipBase64.decode("UEsDBAoAAAAAANRxmDyTTw7hXgAAAF4AAAAJAAAASGVsbG8udHh0VGhpcyBhIGxvb29uZyBmaWxlIDogd2UgbmVlZCB0byBzZWUgdGhlIGRpZmZlcmVuY2UgYmV0d2VlbiB0aGUgZGlmZmVyZW50IGNvbXByZXNzaW9uIG1ldGhvZHMuClBLAQIeAwoAAAAAANRxmDyTTw7hXgAAAF4AAAAJAAAAAAAAAAAAAACkgQAAAABIZWxsby50eHRQSwUGAAAAAAEAAQA3AAAAhQAAAAAA");
refZips["DEFLATE-text"]=JSZipBase64.decode("UEsDBBQAAAAIANRxmDyTTw7hSQAAAF4AAAAJAAAASGVsbG8udHh0VcixDYAwDATAnil+AgZgDhaA+EMsJTaKLWV9aq68s2ngQnd3e1C1EwcWYaQgHUEiGyFaKyetEDdzkfbrRPHxTkaoGwazucS+fVBLAQIeAxQAAAAIANRxmDyTTw7hSQAAAF4AAAAJAAAAAAAAAAEAAACkgQAAAABIZWxsby50eHRQSwUGAAAAAAEAAQA3AAAAcAAAAAAA");
test("JSZip", function(){
ok(JSZip, "JSZip exists");
var zip = new JSZip();
ok(zip, "Constructor works");
});
module("Essential");
test("Zip text file", function()
{
// If anyone can work out how to get binary data over AJAX without it
// being mangled by UTF-8 transforms, I would be very grateful
var expected = refZips["text"];
var zip = new JSZip();
zip.add("Hello.txt", "Hello World\n");
content = zip.generate();
var actual = JSZipBase64.decode(content);
/*
Expected differing bytes:
2 version number
4 date/time
4 central dir version numbers
4 central dir date/time
4 external file attributes
18 Total
*/
ok(similar(actual, expected, 18) , "Generated ZIP matches reference ZIP");
});
test("Zip text file with UTF-8 characters", function()
{
var expected = refZips["utf8"];
var zip = new JSZip();
zip.add("amount.txt", "€15\n");
content = zip.generate();
var actual = JSZipBase64.decode(content);
ok(similar(actual, expected, 18) , "Generated ZIP matches reference ZIP");
});
test("Zip text file with date", function()
{
var expected = refZips["text"];
var zip = new JSZip();
zip.add("Hello.txt", "Hello World\n", {date : new Date("July 17, 2009 14:36:57")});
content = zip.generate();
var actual = JSZipBase64.decode(content);
/*
Expected differing bytes:
2 version number
4 central dir version numbers
4 external file attributes
10 Total
*/
ok(similar(actual, expected, 10) , "Generated ZIP matches reference ZIP");
});
test("Zip image file", function()
{
var expected = refZips["image"];
var zip = new JSZip();
zip.add("smile.gif", "R0lGODdhBQAFAIACAAAAAP/eACwAAAAABQAFAAACCIwPkWerClIBADs=", {base64: true});
content = zip.generate();
actual = JSZipBase64.decode(content);
ok(similar(actual, expected, 18) , "Generated ZIP matches reference ZIP");
});
test("Zip empty folder", function()
{
var expected = refZips["folder"];
var zip = new JSZip();
zip.folder("folder");
content = zip.generate();
actual = JSZipBase64.decode(content);
ok(similar(actual, expected, 18) , "Generated ZIP matches reference ZIP");
});
test("Zip text, folder and image", function()
{
var expected = refZips["all"];
var zip = new JSZip();
zip.add("Hello.txt", "Hello World\n");
zip.folder("images").add("smile.gif", "R0lGODdhBQAFAIACAAAAAP/eACwAAAAABQAFAAACCIwPkWerClIBADs=", {base64: true});
content = zip.generate();
actual = JSZipBase64.decode(content);
/*
Expected differing bytes:
2 version number
4 date/time
4 central dir version numbers
4 central dir date/time
4 external file attributes
18 * 3 files
54 Total
*/
//console.log("data:application/zip;base64,"+content);
ok(similar(actual, expected, 54) , "Generated ZIP matches reference ZIP");
});
test("Finding a file", function()
{
var zip = new JSZip();
zip.add("Readme", "Hello World!\n");
zip.add("Readme.French", "Bonjour tout le monde!\n");
zip.add("Readme.Pirate", "Ahoy m'hearty!\n");
ok(1 === zip.find("Readme").length, "Exact match found");
ok(0 === zip.find("French").length, "Match exactly nothing");
ok(2 === zip.find(/Readme\../).length, "Match regex free text");
});
module("More advanced");
test("Delete file", function()
{
var expected = refZips["text"];
var zip = new JSZip();
zip.add("Remove.txt", "This file should be deleted\n");
zip.add("Hello.txt", "Hello World\n");
zip.remove("Remove.txt");
content = zip.generate();
actual = JSZipBase64.decode(content);
ok(similar(actual, expected, 18) , "Generated ZIP matches reference ZIP");
});
test("Delete folder", function()
{
var expected = refZips["text"];
var zip = new JSZip();
zip.folder("remove").add("Remove.txt", "This folder and file should be deleted\n");
zip.add("Hello.txt", "Hello World\n");
zip.remove("remove");
content = zip.generate();
actual = JSZipBase64.decode(content);
ok(similar(actual, expected, 18) , "Generated ZIP matches reference ZIP");
});
test("Delete nested folders", function()
{
var expected = refZips["text"];
var zip = new JSZip();
zip.folder("remove").add("Remove.txt", "This folder and file should be deleted\n");
zip.folder("remove/second").add("Sub.txt", "This should be removed");
zip.add("remove/second/another.txt", "Another file");
zip.add("Hello.txt", "Hello World\n");
zip.remove("remove");
content = zip.generate();
actual = JSZipBase64.decode(content);
ok(similar(actual, expected, 18) , "Generated ZIP matches reference ZIP");
});
test("Byte string output", function()
{
var expected = refZips["text"];
var zip = new JSZip();
zip.add("Hello.txt", "Hello World\n");
content = zip.generate(true);
var actual = content;
ok(similar(actual, expected, 18) , "Generated ZIP matches reference ZIP");
});
test("STORE is the default method", function()
{
var expected = refZips["text"];
var zip = new JSZip("STORE");
zip.add("Hello.txt", "Hello World\n");
content = zip.generate();
actual = JSZipBase64.decode(content);
// no difference with the "Zip text file" test.
ok(similar(actual, expected, 18) , "Generated ZIP matches reference ZIP");
});
test("STORE doesn't compress", function()
{
var expected = refZips["STORE-text"]; // zip -0 -X store.zip Hello.txt
var zip = new JSZip("STORE");
zip.add("Hello.txt", "This a looong file : we need to see the difference between the different compression methods.\n");
content = zip.generate();
actual = JSZipBase64.decode(content);
ok(similar(actual, expected, 18) , "Generated ZIP matches reference ZIP");
});
test("DEFLATE compress", function()
{
var expected = refZips["DEFLATE-text"]; // zip -6 -X deflate.zip Hello.txt
var zip = new JSZip("DEFLATE");
zip.add("Hello.txt", "This a looong file : we need to see the difference between the different compression methods.\n");
content = zip.generate();
actual = JSZipBase64.decode(content);
ok(similar(actual, expected, 18) , "Generated ZIP matches reference ZIP");
});
</script>
</head>
<body>
<h1 id="qunit-header">JSZip Testing</h1>
<h2 id="qunit-banner"></h2>
<div id="qunit-testrunner-toolbar"></div>
<h2 id="qunit-userAgent"></h2>
<ol id="qunit-tests"></ol>
</body>
</html>
| 07pratik-androidui | asset-studio/src/lib/jszip/test/index.html | HTML | asf20 | 9,640 |
/*
* QUnit - A JavaScript Unit Testing Framework
*
* http://docs.jquery.com/QUnit
*
* Copyright (c) 2009 John Resig, Jörn Zaefferer
* Dual licensed under the MIT (MIT-LICENSE.txt)
* and GPL (GPL-LICENSE.txt) licenses.
*/
(function(window) {
var QUnit = {
// Initialize the configuration options
init: function init() {
config = {
stats: { all: 0, bad: 0 },
moduleStats: { all: 0, bad: 0 },
started: +new Date,
blocking: false,
autorun: false,
assertions: [],
filters: [],
queue: []
};
var tests = id("qunit-tests"),
banner = id("qunit-banner"),
result = id("qunit-testresult");
if ( tests ) {
tests.innerHTML = "";
}
if ( banner ) {
banner.className = "";
}
if ( result ) {
result.parentNode.removeChild( result );
}
},
// call on start of module test to prepend name to all tests
module: function module(name, testEnvironment) {
synchronize(function() {
if ( config.currentModule ) {
QUnit.moduleDone( config.currentModule, config.moduleStats.bad, config.moduleStats.all );
}
config.currentModule = name;
config.moduleTestEnvironment = testEnvironment;
config.moduleStats = { all: 0, bad: 0 };
QUnit.moduleStart( name );
});
},
asyncTest: function asyncTest(testName, expected, callback) {
if ( arguments.length === 2 ) {
callback = expected;
expected = 0;
}
QUnit.test(testName, expected, callback, true);
},
test: function test(testName, expected, callback, async) {
var name = testName, testEnvironment = {};
if ( arguments.length === 2 ) {
callback = expected;
expected = null;
}
if ( config.currentModule ) {
name = config.currentModule + " module: " + name;
}
if ( !validTest(name) ) {
return;
}
synchronize(function() {
QUnit.testStart( testName );
testEnvironment = extend({
setup: function() {},
teardown: function() {}
}, config.moduleTestEnvironment);
config.assertions = [];
config.expected = null;
if ( arguments.length >= 3 ) {
config.expected = callback;
callback = arguments[2];
}
try {
if ( !config.pollution ) {
saveGlobal();
}
testEnvironment.setup.call(testEnvironment);
} catch(e) {
QUnit.ok( false, "Setup failed on " + name + ": " + e.message );
}
if ( async ) {
QUnit.stop();
}
try {
callback.call(testEnvironment);
} catch(e) {
fail("Test " + name + " died, exception and test follows", e, callback);
QUnit.ok( false, "Died on test #" + (config.assertions.length + 1) + ": " + e.message );
// else next test will carry the responsibility
saveGlobal();
// Restart the tests if they're blocking
if ( config.blocking ) {
start();
}
}
});
synchronize(function() {
try {
checkPollution();
testEnvironment.teardown.call(testEnvironment);
} catch(e) {
QUnit.ok( false, "Teardown failed on " + name + ": " + e.message );
}
try {
reset();
} catch(e) {
fail("reset() failed, following Test " + name + ", exception and reset fn follows", e, reset);
}
if ( config.expected && config.expected != config.assertions.length ) {
QUnit.ok( false, "Expected " + config.expected + " assertions, but " + config.assertions.length + " were run" );
}
var good = 0, bad = 0,
tests = id("qunit-tests");
config.stats.all += config.assertions.length;
config.moduleStats.all += config.assertions.length;
if ( tests ) {
var ol = document.createElement("ol");
ol.style.display = "none";
for ( var i = 0; i < config.assertions.length; i++ ) {
var assertion = config.assertions[i];
var li = document.createElement("li");
li.className = assertion.result ? "pass" : "fail";
li.innerHTML = assertion.message || "(no message)";
ol.appendChild( li );
if ( assertion.result ) {
good++;
} else {
bad++;
config.stats.bad++;
config.moduleStats.bad++;
}
}
var b = document.createElement("strong");
b.innerHTML = name + " <b style='color:black;'>(<b class='fail'>" + bad + "</b>, <b class='pass'>" + good + "</b>, " + config.assertions.length + ")</b>";
addEvent(b, "click", function() {
var next = b.nextSibling, display = next.style.display;
next.style.display = display === "none" ? "block" : "none";
});
addEvent(b, "dblclick", function(e) {
var target = (e || window.event).target;
if ( target.nodeName.toLowerCase() === "strong" ) {
var text = "", node = target.firstChild;
while ( node.nodeType === 3 ) {
text += node.nodeValue;
node = node.nextSibling;
}
text = text.replace(/(^\s*|\s*$)/g, "");
if ( window.location ) {
window.location.href = window.location.href.match(/^(.+?)(\?.*)?$/)[1] + "?" + encodeURIComponent(text);
}
}
});
var li = document.createElement("li");
li.className = bad ? "fail" : "pass";
li.appendChild( b );
li.appendChild( ol );
tests.appendChild( li );
if ( bad ) {
var toolbar = id("qunit-testrunner-toolbar");
if ( toolbar ) {
toolbar.style.display = "block";
id("qunit-filter-pass").disabled = null;
id("qunit-filter-missing").disabled = null;
}
}
} else {
for ( var i = 0; i < config.assertions.length; i++ ) {
if ( !config.assertions[i].result ) {
bad++;
config.stats.bad++;
config.moduleStats.bad++;
}
}
}
QUnit.testDone( testName, bad, config.assertions.length );
if ( !window.setTimeout && !config.queue.length ) {
done();
}
});
if ( window.setTimeout && !config.doneTimer ) {
config.doneTimer = window.setTimeout(function(){
if ( !config.queue.length ) {
done();
} else {
synchronize( done );
}
}, 13);
}
},
/**
* Specify the number of expected assertions to gurantee that failed test (no assertions are run at all) don't slip through.
*/
expect: function expect(asserts) {
config.expected = asserts;
},
/**
* Asserts true.
* @example ok( "asdfasdf".length > 5, "There must be at least 5 chars" );
*/
ok: function ok(a, msg) {
QUnit.log(a, msg);
config.assertions.push({
result: !!a,
message: msg
});
},
/**
* Checks that the first two arguments are equal, with an optional message.
* Prints out both actual and expected values.
*
* Prefered to ok( actual == expected, message )
*
* @example equals( format("Received {0} bytes.", 2), "Received 2 bytes." );
*
* @param Object actual
* @param Object expected
* @param String message (optional)
*/
equals: function equals(actual, expected, message) {
push(expected == actual, actual, expected, message);
},
same: function(a, b, message) {
push(QUnit.equiv(a, b), a, b, message);
},
start: function start() {
// A slight delay, to avoid any current callbacks
if ( window.setTimeout ) {
window.setTimeout(function() {
if ( config.timeout ) {
clearTimeout(config.timeout);
}
config.blocking = false;
process();
}, 13);
} else {
config.blocking = false;
process();
}
},
stop: function stop(timeout) {
config.blocking = true;
if ( timeout && window.setTimeout ) {
config.timeout = window.setTimeout(function() {
QUnit.ok( false, "Test timed out" );
start();
}, timeout);
}
},
/**
* Resets the test setup. Useful for tests that modify the DOM.
*/
reset: function reset() {
if ( window.jQuery ) {
jQuery("#main").html( config.fixture );
jQuery.event.global = {};
jQuery.ajaxSettings = extend({}, config.ajaxSettings);
}
},
/**
* Trigger an event on an element.
*
* @example triggerEvent( document.body, "click" );
*
* @param DOMElement elem
* @param String type
*/
triggerEvent: function triggerEvent( elem, type, event ) {
if ( document.createEvent ) {
event = document.createEvent("MouseEvents");
event.initMouseEvent(type, true, true, elem.ownerDocument.defaultView,
0, 0, 0, 0, 0, false, false, false, false, 0, null);
elem.dispatchEvent( event );
} else if ( elem.fireEvent ) {
elem.fireEvent("on"+type);
}
},
// Logging callbacks
done: function done(failures, total) {},
log: function log(result, message) {},
testStart: function testStart(name) {},
testDone: function testDone(name, failures, total) {},
moduleStart: function moduleStart(name) {},
moduleDone: function moduleDone(name, failures, total) {}
};
// Maintain internal state
var config = {
// The queue of tests to run
queue: [],
// block until document ready
blocking: true
};
// Load paramaters
(function() {
var location = window.location || { search: "", protocol: "file:" },
GETParams = location.search.slice(1).split('&');
for ( var i = 0; i < GETParams.length; i++ ) {
GETParams[i] = decodeURIComponent( GETParams[i] );
if ( GETParams[i] === "noglobals" ) {
GETParams.splice( i, 1 );
i--;
config.noglobals = true;
}
}
// restrict modules/tests by get parameters
config.filters = GETParams;
// Figure out if we're running the tests from a server or not
QUnit.isLocal = !!(location.protocol === 'file:');
})();
// Expose the API as global variables, unless an 'exports'
// object exists, in that case we assume we're in CommonJS
if ( typeof exports === "undefined" || typeof require === "undefined" ) {
extend(window, QUnit);
window.QUnit = QUnit;
} else {
extend(exports, QUnit);
exports.QUnit = QUnit;
}
if ( typeof document === "undefined" || document.readyState === "complete" ) {
config.autorun = true;
}
addEvent(window, "load", function() {
// Initialize the config, saving the execution queue
var oldconfig = extend({}, config);
QUnit.init();
extend(config, oldconfig);
config.blocking = false;
var userAgent = id("qunit-userAgent");
if ( userAgent ) {
userAgent.innerHTML = navigator.userAgent;
}
var toolbar = id("qunit-testrunner-toolbar");
if ( toolbar ) {
toolbar.style.display = "none";
var filter = document.createElement("input");
filter.type = "checkbox";
filter.id = "qunit-filter-pass";
filter.disabled = true;
addEvent( filter, "click", function() {
var li = document.getElementsByTagName("li");
for ( var i = 0; i < li.length; i++ ) {
if ( li[i].className.indexOf("pass") > -1 ) {
li[i].style.display = filter.checked ? "none" : "block";
}
}
});
toolbar.appendChild( filter );
var label = document.createElement("label");
label.setAttribute("for", "filter-pass");
label.innerHTML = "Hide passed tests";
toolbar.appendChild( label );
var missing = document.createElement("input");
missing.type = "checkbox";
missing.id = "qunit-filter-missing";
missing.disabled = true;
addEvent( missing, "click", function() {
var li = document.getElementsByTagName("li");
for ( var i = 0; i < li.length; i++ ) {
if ( li[i].className.indexOf("fail") > -1 && li[i].innerHTML.indexOf('missing test - untested code is broken code') > - 1 ) {
li[i].parentNode.parentNode.style.display = missing.checked ? "none" : "block";
}
}
});
toolbar.appendChild( missing );
label = document.createElement("label");
label.setAttribute("for", "filter-missing");
label.innerHTML = "Hide missing tests (untested code is broken code)";
toolbar.appendChild( label );
}
var main = id('main');
if ( main ) {
config.fixture = main.innerHTML;
}
if ( window.jQuery ) {
config.ajaxSettings = window.jQuery.ajaxSettings;
}
start();
});
function done() {
if ( config.doneTimer && window.clearTimeout ) {
window.clearTimeout( config.doneTimer );
config.doneTimer = null;
}
if ( config.queue.length ) {
config.doneTimer = window.setTimeout(function(){
if ( !config.queue.length ) {
done();
} else {
synchronize( done );
}
}, 13);
return;
}
config.autorun = true;
// Log the last module results
if ( config.currentModule ) {
QUnit.moduleDone( config.currentModule, config.moduleStats.bad, config.moduleStats.all );
}
var banner = id("qunit-banner"),
tests = id("qunit-tests"),
html = ['Tests completed in ',
+new Date - config.started, ' milliseconds.<br/>',
'<span class="bad">', config.stats.all - config.stats.bad, '</span> tests of <span class="all">', config.stats.all, '</span> passed, ', config.stats.bad,' failed.'].join('');
if ( banner ) {
banner.className += " " + (config.stats.bad ? "fail" : "pass");
}
if ( tests ) {
var result = id("qunit-testresult");
if ( !result ) {
result = document.createElement("p");
result.id = "qunit-testresult";
result.className = "result";
tests.parentNode.insertBefore( result, tests.nextSibling );
}
result.innerHTML = html;
}
QUnit.done( config.stats.bad, config.stats.all );
}
function validTest( name ) {
var i = config.filters.length,
run = false;
if ( !i ) {
return true;
}
while ( i-- ) {
var filter = config.filters[i],
not = filter.charAt(0) == '!';
if ( not ) {
filter = filter.slice(1);
}
if ( name.indexOf(filter) !== -1 ) {
return !not;
}
if ( not ) {
run = true;
}
}
return run;
}
function push(result, actual, expected, message) {
message = message || (result ? "okay" : "failed");
QUnit.ok( result, result ? message + ": " + expected : message + ", expected: " + QUnit.jsDump.parse(expected) + " result: " + QUnit.jsDump.parse(actual) );
}
function synchronize( callback ) {
config.queue.push( callback );
if ( config.autorun && !config.blocking ) {
process();
}
}
function process() {
while ( config.queue.length && !config.blocking ) {
config.queue.shift()();
}
}
function saveGlobal() {
config.pollution = [];
if ( config.noglobals ) {
for ( var key in window ) {
config.pollution.push( key );
}
}
}
function checkPollution( name ) {
var old = config.pollution;
saveGlobal();
var newGlobals = diff( old, config.pollution );
if ( newGlobals.length > 0 ) {
ok( false, "Introduced global variable(s): " + newGlobals.join(", ") );
config.expected++;
}
var deletedGlobals = diff( config.pollution, old );
if ( deletedGlobals.length > 0 ) {
ok( false, "Deleted global variable(s): " + deletedGlobals.join(", ") );
config.expected++;
}
}
// returns a new Array with the elements that are in a but not in b
function diff( a, b ) {
var result = a.slice();
for ( var i = 0; i < result.length; i++ ) {
for ( var j = 0; j < b.length; j++ ) {
if ( result[i] === b[j] ) {
result.splice(i, 1);
i--;
break;
}
}
}
return result;
}
function fail(message, exception, callback) {
if ( typeof console !== "undefined" && console.error && console.warn ) {
console.error(message);
console.error(exception);
console.warn(callback.toString());
} else if ( window.opera && opera.postError ) {
opera.postError(message, exception, callback.toString);
}
}
function extend(a, b) {
for ( var prop in b ) {
a[prop] = b[prop];
}
return a;
}
function addEvent(elem, type, fn) {
if ( elem.addEventListener ) {
elem.addEventListener( type, fn, false );
} else if ( elem.attachEvent ) {
elem.attachEvent( "on" + type, fn );
} else {
fn();
}
}
function id(name) {
return !!(typeof document !== "undefined" && document && document.getElementById) &&
document.getElementById( name );
}
// Test for equality any JavaScript type.
// Discussions and reference: http://philrathe.com/articles/equiv
// Test suites: http://philrathe.com/tests/equiv
// Author: Philippe Rathé <prathe@gmail.com>
QUnit.equiv = function () {
var innerEquiv; // the real equiv function
var callers = []; // stack to decide between skip/abort functions
// Determine what is o.
function hoozit(o) {
if (o.constructor === String) {
return "string";
} else if (o.constructor === Boolean) {
return "boolean";
} else if (o.constructor === Number) {
if (isNaN(o)) {
return "nan";
} else {
return "number";
}
} else if (typeof o === "undefined") {
return "undefined";
// consider: typeof null === object
} else if (o === null) {
return "null";
// consider: typeof [] === object
} else if (o instanceof Array) {
return "array";
// consider: typeof new Date() === object
} else if (o instanceof Date) {
return "date";
// consider: /./ instanceof Object;
// /./ instanceof RegExp;
// typeof /./ === "function"; // => false in IE and Opera,
// true in FF and Safari
} else if (o instanceof RegExp) {
return "regexp";
} else if (typeof o === "object") {
return "object";
} else if (o instanceof Function) {
return "function";
} else {
return undefined;
}
}
// Call the o related callback with the given arguments.
function bindCallbacks(o, callbacks, args) {
var prop = hoozit(o);
if (prop) {
if (hoozit(callbacks[prop]) === "function") {
return callbacks[prop].apply(callbacks, args);
} else {
return callbacks[prop]; // or undefined
}
}
}
var callbacks = function () {
// for string, boolean, number and null
function useStrictEquality(b, a) {
if (b instanceof a.constructor || a instanceof b.constructor) {
// to catch short annotaion VS 'new' annotation of a declaration
// e.g. var i = 1;
// var j = new Number(1);
return a == b;
} else {
return a === b;
}
}
return {
"string": useStrictEquality,
"boolean": useStrictEquality,
"number": useStrictEquality,
"null": useStrictEquality,
"undefined": useStrictEquality,
"nan": function (b) {
return isNaN(b);
},
"date": function (b, a) {
return hoozit(b) === "date" && a.valueOf() === b.valueOf();
},
"regexp": function (b, a) {
return hoozit(b) === "regexp" &&
a.source === b.source && // the regex itself
a.global === b.global && // and its modifers (gmi) ...
a.ignoreCase === b.ignoreCase &&
a.multiline === b.multiline;
},
// - skip when the property is a method of an instance (OOP)
// - abort otherwise,
// initial === would have catch identical references anyway
"function": function () {
var caller = callers[callers.length - 1];
return caller !== Object &&
typeof caller !== "undefined";
},
"array": function (b, a) {
var i;
var len;
// b could be an object literal here
if ( ! (hoozit(b) === "array")) {
return false;
}
len = a.length;
if (len !== b.length) { // safe and faster
return false;
}
for (i = 0; i < len; i++) {
if ( ! innerEquiv(a[i], b[i])) {
return false;
}
}
return true;
},
"object": function (b, a) {
var i;
var eq = true; // unless we can proove it
var aProperties = [], bProperties = []; // collection of strings
// comparing constructors is more strict than using instanceof
if ( a.constructor !== b.constructor) {
return false;
}
// stack constructor before traversing properties
callers.push(a.constructor);
for (i in a) { // be strict: don't ensures hasOwnProperty and go deep
aProperties.push(i); // collect a's properties
if ( ! innerEquiv(a[i], b[i])) {
eq = false;
}
}
callers.pop(); // unstack, we are done
for (i in b) {
bProperties.push(i); // collect b's properties
}
// Ensures identical properties name
return eq && innerEquiv(aProperties.sort(), bProperties.sort());
}
};
}();
innerEquiv = function () { // can take multiple arguments
var args = Array.prototype.slice.apply(arguments);
if (args.length < 2) {
return true; // end transition
}
return (function (a, b) {
if (a === b) {
return true; // catch the most you can
} else if (a === null || b === null || typeof a === "undefined" || typeof b === "undefined" || hoozit(a) !== hoozit(b)) {
return false; // don't lose time with error prone cases
} else {
return bindCallbacks(a, callbacks, [b, a]);
}
// apply transition with (1..n) arguments
})(args[0], args[1]) && arguments.callee.apply(this, args.splice(1, args.length -1));
};
return innerEquiv;
}();
/**
* jsDump
* Copyright (c) 2008 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
* Licensed under BSD (http://www.opensource.org/licenses/bsd-license.php)
* Date: 5/15/2008
* @projectDescription Advanced and extensible data dumping for Javascript.
* @version 1.0.0
* @author Ariel Flesler
* @link {http://flesler.blogspot.com/2008/05/jsdump-pretty-dump-of-any-javascript.html}
*/
QUnit.jsDump = (function() {
function quote( str ) {
return '"' + str.toString().replace(/"/g, '\\"') + '"';
};
function literal( o ) {
return o + '';
};
function join( pre, arr, post ) {
var s = jsDump.separator(),
base = jsDump.indent(),
inner = jsDump.indent(1);
if ( arr.join )
arr = arr.join( ',' + s + inner );
if ( !arr )
return pre + post;
return [ pre, inner + arr, base + post ].join(s);
};
function array( arr ) {
var i = arr.length, ret = Array(i);
this.up();
while ( i-- )
ret[i] = this.parse( arr[i] );
this.down();
return join( '[', ret, ']' );
};
var reName = /^function (\w+)/;
var jsDump = {
parse:function( obj, type ) { //type is used mostly internally, you can fix a (custom)type in advance
var parser = this.parsers[ type || this.typeOf(obj) ];
type = typeof parser;
return type == 'function' ? parser.call( this, obj ) :
type == 'string' ? parser :
this.parsers.error;
},
typeOf:function( obj ) {
var type = typeof obj,
f = 'function';//we'll use it 3 times, save it
return type != 'object' && type != f ? type :
!obj ? 'null' :
obj.exec ? 'regexp' :// some browsers (FF) consider regexps functions
obj.getHours ? 'date' :
obj.scrollBy ? 'window' :
obj.nodeName == '#document' ? 'document' :
obj.nodeName ? 'node' :
obj.item ? 'nodelist' : // Safari reports nodelists as functions
obj.callee ? 'arguments' :
obj.call || obj.constructor != Array && //an array would also fall on this hack
(obj+'').indexOf(f) != -1 ? f : //IE reports functions like alert, as objects
'length' in obj ? 'array' :
type;
},
separator:function() {
return this.multiline ? this.HTML ? '<br />' : '\n' : this.HTML ? ' ' : ' ';
},
indent:function( extra ) {// extra can be a number, shortcut for increasing-calling-decreasing
if ( !this.multiline )
return '';
var chr = this.indentChar;
if ( this.HTML )
chr = chr.replace(/\t/g,' ').replace(/ /g,' ');
return Array( this._depth_ + (extra||0) ).join(chr);
},
up:function( a ) {
this._depth_ += a || 1;
},
down:function( a ) {
this._depth_ -= a || 1;
},
setParser:function( name, parser ) {
this.parsers[name] = parser;
},
// The next 3 are exposed so you can use them
quote:quote,
literal:literal,
join:join,
//
_depth_: 1,
// This is the list of parsers, to modify them, use jsDump.setParser
parsers:{
window: '[Window]',
document: '[Document]',
error:'[ERROR]', //when no parser is found, shouldn't happen
unknown: '[Unknown]',
'null':'null',
undefined:'undefined',
'function':function( fn ) {
var ret = 'function',
name = 'name' in fn ? fn.name : (reName.exec(fn)||[])[1];//functions never have name in IE
if ( name )
ret += ' ' + name;
ret += '(';
ret = [ ret, this.parse( fn, 'functionArgs' ), '){'].join('');
return join( ret, this.parse(fn,'functionCode'), '}' );
},
array: array,
nodelist: array,
arguments: array,
object:function( map ) {
var ret = [ ];
this.up();
for ( var key in map )
ret.push( this.parse(key,'key') + ': ' + this.parse(map[key]) );
this.down();
return join( '{', ret, '}' );
},
node:function( node ) {
var open = this.HTML ? '<' : '<',
close = this.HTML ? '>' : '>';
var tag = node.nodeName.toLowerCase(),
ret = open + tag;
for ( var a in this.DOMAttrs ) {
var val = node[this.DOMAttrs[a]];
if ( val )
ret += ' ' + a + '=' + this.parse( val, 'attribute' );
}
return ret + close + open + '/' + tag + close;
},
functionArgs:function( fn ) {//function calls it internally, it's the arguments part of the function
var l = fn.length;
if ( !l ) return '';
var args = Array(l);
while ( l-- )
args[l] = String.fromCharCode(97+l);//97 is 'a'
return ' ' + args.join(', ') + ' ';
},
key:quote, //object calls it internally, the key part of an item in a map
functionCode:'[code]', //function calls it internally, it's the content of the function
attribute:quote, //node calls it internally, it's an html attribute value
string:quote,
date:quote,
regexp:literal, //regex
number:literal,
'boolean':literal
},
DOMAttrs:{//attributes to dump from nodes, name=>realName
id:'id',
name:'name',
'class':'className'
},
HTML:true,//if true, entities are escaped ( <, >, \t, space and \n )
indentChar:' ',//indentation unit
multiline:true //if true, items in a collection, are separated by a \n, else just a space.
};
return jsDump;
})();
})(this);
| 07pratik-androidui | asset-studio/src/lib/jszip/test/qunit.js | JavaScript | asf20 | 26,759 |
h1#qunit-header { padding: 15px; font-size: large; background-color: #06b; color: white; font-family: 'trebuchet ms', verdana, arial; margin: 0; }
h1#qunit-header a { color: white; }
h2#qunit-banner { height: 2em; border-bottom: 1px solid white; background-color: #eee; margin: 0; font-family: 'trebuchet ms', verdana, arial; }
h2#qunit-banner.pass { background-color: green; }
h2#qunit-banner.fail { background-color: red; }
h2#qunit-userAgent { padding: 10px; background-color: #eee; color: black; margin: 0; font-size: small; font-weight: normal; font-family: 'trebuchet ms', verdana, arial; font-size: 10pt; }
div#qunit-testrunner-toolbar { background: #eee; border-top: 1px solid black; padding: 10px; font-family: 'trebuchet ms', verdana, arial; margin: 0; font-size: 10pt; }
ol#qunit-tests { font-family: 'trebuchet ms', verdana, arial; font-size: 10pt; }
ol#qunit-tests li strong { cursor:pointer; }
ol#qunit-tests .pass { color: green; }
ol#qunit-tests .fail { color: red; }
p#qunit-testresult { margin-left: 1em; font-size: 10pt; font-family: 'trebuchet ms', verdana, arial; }
| 07pratik-androidui | asset-studio/src/lib/jszip/test/qunit.css | CSS | asf20 | 1,094 |
#!/bin/sh
# Copyright 2010 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.
rm -rf dist
mkdir -p dist
mkdir -p dist/js
mkdir -p dist/images
mkdir -p dist/css
cd src/
find images -iname \*.png -exec pngcrush {} ../dist/{} \;
cd js/
ant clean
ant dist
cd ..
find css -iname \*.css -exec java -jar ../lib/yuicompressor-2.4.2.jar -o ../dist/{} {} \;
cp -rf lib/ ../dist/lib/
cp -rf res/ ../dist/res/
cd html
#find . -iname \*.html -exec java -jar ../../lib/htmlcompressor-0.9.jar --remove-intertag-spaces --remove-quotes -o ../out/{} {} \;
find . -iname \*.html -exec cp {} ../../dist/{} \;
#find . -iname \*.manifest -exec cp {} ../../dist/{} \;
#find . -iname .htaccess -exec cp {} ../../dist/{} \;
cd ..
cd ..
| 07pratik-androidui | asset-studio/make.sh | Shell | asf20 | 1,230 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DAO;
using System.Data;
namespace BUS
{
public class QUAYBUS
{
public DataTable LoadDsQuay()
{
QUAYDAO quayDAO = new QUAYDAO();
DataTable dt = new DataTable();
dt = quayDAO.LoadQuay();
return dt;
}
}
}
| 10650931065130doan | trunk/1065093_1065130_1065120_DoAn/BUS/QUAYBUS.cs | C# | asf20 | 402 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using DAO;
namespace BUS
{
public class LOAISPBUS
{
public DataTable LoadDsLoaiSP()
{
LOAISPDAO LoaispDao = new LOAISPDAO();
DataTable dt = new DataTable();
dt = LoaispDao.LoadLoaiSP();
return dt;
}
}
}
| 10650931065130doan | trunk/1065093_1065130_1065120_DoAn/BUS/LOAISPBUS.cs | C# | asf20 | 416 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using DAO;
using DTO;
namespace BUS
{
public class THAMSOBUS
{
public DataTable LoadThamSo()
{
THAMSODAO tsDAO = new THAMSODAO();
DataTable dt = new DataTable();
dt = tsDAO.LoadThamSo();
return dt;
}
public void SuaThamSo(int ma, int giatri, string kieu)
{
THAMSODAO tsDao = new THAMSODAO();
tsDao.SuaThamSo(ma,giatri,kieu);
}
public DataTable LoadKhuyenMai()
{
THAMSODAO tsDAO = new THAMSODAO();
DataTable dt = new DataTable();
dt = tsDAO.LoadKhuyenMai();
return dt;
}
public void ThemKhuyenMai(THAMSODTO tsDTO)
{
THAMSODAO tsDao = new THAMSODAO();
tsDao.ThemKhuyenMai(tsDTO);
}
public void XoaKhuyenMai(int ma)
{
THAMSODAO tsDao = new THAMSODAO();
tsDao.XoaKhuyenMai(ma);
}
public void SuaKhuyenMai(THAMSODTO tsDto)
{
THAMSODAO tsDao = new THAMSODAO();
tsDao.SuaKhuyenMai(tsDto);
}
}
}
| 10650931065130doan | trunk/1065093_1065130_1065120_DoAn/BUS/THAMSOBUS.cs | C# | asf20 | 1,303 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using DAO;
using DTO;
namespace BUS
{
public class SANPHAMBUS
{
public DataTable LoadDsSanPham()
{
SANPHAMDAO spDAO = new SANPHAMDAO();
DataTable dt = new DataTable();
dt = spDAO.LoadSanPham();
return dt;
}
public void ThemSP(SANPHAMDTO spDTO)
{
SANPHAMDAO spDao = new SANPHAMDAO();
spDao.ThemSanPham(spDTO);
}
public void XoaSP(int ma)
{
SANPHAMDAO spDao = new SANPHAMDAO();
spDao.XoaSanPham(ma);
}
public void SuaSP(SANPHAMDTO spDto)
{
SANPHAMDAO spDao = new SANPHAMDAO();
spDao.SuaSanPham(spDto);
}
public DataTable LoadDsTimKiem(string tukhoa)
{
SANPHAMDAO spDao = new SANPHAMDAO();
DataTable dt = new DataTable();
dt = spDao.LoadTimKiem(tukhoa);
return dt;
}
public DataTable LoadDsTim(string tukhoa)
{
SANPHAMDAO spDao = new SANPHAMDAO();
DataTable dt = new DataTable();
dt = spDao.LoadTim(tukhoa);
return dt;
}
public void SuaSL(int ma, int ghkho, int ghquay, int slhtkho, int slhtquay)
{
SANPHAMDAO spDao = new SANPHAMDAO();
spDao.SuaSoLuong(ma,ghkho,ghquay,slhtkho,slhtquay);
}
}
}
| 10650931065130doan | trunk/1065093_1065130_1065120_DoAn/BUS/SANPHAMBUS.cs | C# | asf20 | 1,587 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using DAO;
using DTO;
namespace BUS
{
public class KHACHHANGBUS
{
KHACHHANGDAO khDAO= new KHACHHANGDAO();
KHACHHANGDTO khDTO= new KHACHHANGDTO();
public DataTable GET_KHACHHANG()
{
KHACHHANGDAO DAO = new KHACHHANGDAO();
DataTable dt = new DataTable();
dt = DAO.GET_KHACHHANG();
return dt;
}
public void THEM_KHACHHANG(string tenkh, string sdtkh, int diemtichluy)
{
khDTO.TenKH = tenkh;
khDTO.SDTKH = sdtkh;
khDTO.DiemTichKuy = diemtichluy;
khDAO.THEM_KHACHHANG(khDTO);
}
public void CAPNHAT_KHACHHANG( string tenkh, string sdtkh, int diemtichluy)
{
//khDTO.MaKH = makh;
khDTO.TenKH = tenkh;
khDTO.SDTKH = sdtkh;
khDTO.DiemTichKuy = diemtichluy;
khDAO.CAPNHAT_KHACHHANG(khDTO);
}
public void XoaDoAn(int makh)
{
khDTO.MaKH = makh;
khDAO.XOA_KHACHHANG(khDTO);
}
}
}
| 10650931065130doan | trunk/1065093_1065130_1065120_DoAn/BUS/KHACHHANGBUS.cs | C# | asf20 | 1,252 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using DAO;
using DTO;
namespace BUS
{
public class TAIKHOANBUS
{
public DataTable LoadDSTaiKhoan()
{
TAIKHOANDAO DAO = new TAIKHOANDAO();
DataTable dt = new DataTable();
dt = DAO.LoadTaiKhoan();
return dt;
}
public void ThemTK(TAIKHOANDTO tkDto)
{
TAIKHOANDAO tkDao = new TAIKHOANDAO();
tkDao.ThemTaiKhoan(tkDto);
}
public void XoaTK(int id)
{
TAIKHOANDAO tkDao = new TAIKHOANDAO();
tkDao.XoaTaiKhoan(id);
}
public void SuaTK(TAIKHOANDTO tkDto)
{
TAIKHOANDAO tkDao = new TAIKHOANDAO();
tkDao.SuaTaiKhoan(tkDto);
}
public DataTable LoadDSTimKiem(string tukhoa)
{
TAIKHOANDAO tkDao = new TAIKHOANDAO();
DataTable dt = new DataTable();
dt = tkDao.LoadTimKiem(tukhoa);
return dt;
}
}
}
| 10650931065130doan | trunk/1065093_1065130_1065120_DoAn/BUS/TAIKHOANBUS.cs | C# | asf20 | 1,172 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using DAO;
namespace BUS
{
public class XUATXUBUS
{
public DataTable LoadDsXuatXu()
{
XUATXUDAO xxDAO = new XUATXUDAO();
DataTable dt = new DataTable();
dt = xxDAO.LoadXuatXu();
return dt;
}
}
}
| 10650931065130doan | trunk/1065093_1065130_1065120_DoAn/BUS/XUATXUBUS.cs | C# | asf20 | 408 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using DAO;
namespace BUS
{
public class LOAINHANVIENBUS
{
public DataTable LoadDSLoaiNV()
{
LOAINHANVIENDAO lnvDao = new LOAINHANVIENDAO();
DataTable dt = new DataTable();
dt = lnvDao.LoadLoaiNV();
return dt;
}
}
}
| 10650931065130doan | trunk/1065093_1065130_1065120_DoAn/BUS/LOAINHANVIENBUS.cs | C# | asf20 | 428 |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("BUS")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("BUS")]
[assembly: AssemblyCopyright("Copyright © 2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("f6b88f7c-e999-46a2-8a8d-6e021300ecf1")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 10650931065130doan | trunk/1065093_1065130_1065120_DoAn/BUS/Properties/AssemblyInfo.cs | C# | asf20 | 1,418 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using DAO;
namespace BUS
{
public class KHOBUS
{
public DataTable LoadDsKho()
{
KHODAO khoDAO = new KHODAO();
DataTable dt = new DataTable();
dt = khoDAO.LoadKho();
return dt;
}
}
}
| 10650931065130doan | trunk/1065093_1065130_1065120_DoAn/BUS/KHOBUS.cs | C# | asf20 | 395 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace BUS
{
public class Class1
{
}
}
| 10650931065130doan | trunk/1065093_1065130_1065120_DoAn/BUS/Class1.cs | C# | asf20 | 155 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using DAO;
using DTO;
namespace BUS
{
public class NHANVIENBUS
{
public DataTable LoadDSNhanVien()
{
NHANVIENDAO nvDao = new NHANVIENDAO();
DataTable dt = new DataTable();
dt = nvDao.LoadNhanVien();
return dt;
}
}
}
| 10650931065130doan | trunk/1065093_1065130_1065120_DoAn/BUS/NHANVIENBUS.cs | C# | asf20 | 460 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DTO
{
class LOAINHANVIENDTO
{
private int _maloainv;
public int MaLoaiNV
{
get { return _maloainv; }
set { _maloainv = value; }
}
private string _tenloainv;
public string TenLoaiNV
{
get { return _tenloainv; }
set { _tenloainv = value; }
}
}
}
| 10650931065130doan | trunk/1065093_1065130_1065120_DoAn/DTO/LOAINHANVIENDTO.cs | C# | asf20 | 495 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DTO
{
class CHITIETHOADONDTO
{
private int _mahd;
public int MaHD
{
get { return _mahd; }
set { _mahd = value; }
}
private int _masp;
public int MaSP
{
get { return _masp; }
set { _masp = value; }
}
private int _soluong;
public int SoLuong
{
get { return _soluong; }
set { _soluong = value; }
}
private int _thanhtien;
public int ThanhTien
{
get { return _thanhtien; }
set { _thanhtien = value; }
}
}
}
| 10650931065130doan | trunk/1065093_1065130_1065120_DoAn/DTO/CHITIETHOADONDTO.cs | C# | asf20 | 782 |