Compare commits
2 Commits
v1
...
tags/Makef
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c5dd088d6c | ||
|
|
ca7ae759eb |
539
mozilla/security/nss/lib/freebl/GF2m_ecl.c
Normal file
539
mozilla/security/nss/lib/freebl/GF2m_ecl.c
Normal file
@@ -0,0 +1,539 @@
|
||||
/*
|
||||
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
|
||||
*
|
||||
* The contents of this file are subject to the Mozilla Public License Version
|
||||
* 1.1 (the "License"); you may not use this file except in compliance with
|
||||
* the License. You may obtain a copy of the License at
|
||||
* http://www.mozilla.org/MPL/
|
||||
*
|
||||
* Software distributed under the License is distributed on an "AS IS" basis,
|
||||
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
|
||||
* for the specific language governing rights and limitations under the
|
||||
* License.
|
||||
*
|
||||
* The Original Code is the elliptic curve math library for binary polynomial
|
||||
* field curves.
|
||||
*
|
||||
* The Initial Developer of the Original Code is Sun Microsystems, Inc.
|
||||
* Portions created by Sun Microsystems, Inc. are Copyright (C) 2003
|
||||
* Sun Microsystems, Inc. All Rights Reserved.
|
||||
*
|
||||
* Contributor(s):
|
||||
* Douglas Stebila <douglas@stebila.ca>
|
||||
*
|
||||
* Alternatively, the contents of this file may be used under the terms of
|
||||
* either the GNU General Public License Version 2 or later (the "GPL"), or
|
||||
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
|
||||
* in which case the provisions of the GPL or the LGPL are applicable instead
|
||||
* of those above. If you wish to allow use of your version of this file only
|
||||
* under the terms of either the GPL or the LGPL, and not to allow others to
|
||||
* use your version of this file under the terms of the MPL, indicate your
|
||||
* decision by deleting the provisions above and replace them with the notice
|
||||
* and other provisions required by the GPL or the LGPL. If you do not delete
|
||||
* the provisions above, a recipient may use your version of this file under
|
||||
* the terms of any one of the MPL, the GPL or the LGPL.
|
||||
*
|
||||
*/
|
||||
|
||||
#ifdef NSS_ENABLE_ECC
|
||||
/*
|
||||
* GF2m_ecl.c: Contains an implementation of elliptic curve math library
|
||||
* for curves over GF2m.
|
||||
*
|
||||
* XXX Can be moved to a separate subdirectory later.
|
||||
*
|
||||
*/
|
||||
|
||||
#include "GF2m_ecl.h"
|
||||
#include "mpi/mplogic.h"
|
||||
#include "mpi/mp_gf2m.h"
|
||||
#include <stdlib.h>
|
||||
|
||||
/* Checks if point P(px, py) is at infinity. Uses affine coordinates. */
|
||||
mp_err
|
||||
GF2m_ec_pt_is_inf_aff(const mp_int *px, const mp_int *py)
|
||||
{
|
||||
|
||||
if ((mp_cmp_z(px) == 0) && (mp_cmp_z(py) == 0)) {
|
||||
return MP_YES;
|
||||
} else {
|
||||
return MP_NO;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/* Sets P(px, py) to be the point at infinity. Uses affine coordinates. */
|
||||
mp_err
|
||||
GF2m_ec_pt_set_inf_aff(mp_int *px, mp_int *py)
|
||||
{
|
||||
mp_zero(px);
|
||||
mp_zero(py);
|
||||
return MP_OKAY;
|
||||
}
|
||||
|
||||
/* Computes R = P + Q based on IEEE P1363 A.10.2.
|
||||
* Elliptic curve points P, Q, and R can all be identical.
|
||||
* Uses affine coordinates.
|
||||
*/
|
||||
mp_err
|
||||
GF2m_ec_pt_add_aff(const mp_int *pp, const mp_int *a, const mp_int *px,
|
||||
const mp_int *py, const mp_int *qx, const mp_int *qy,
|
||||
mp_int *rx, mp_int *ry)
|
||||
{
|
||||
mp_err err = MP_OKAY;
|
||||
mp_int lambda, xtemp, ytemp;
|
||||
unsigned int *p;
|
||||
int p_size;
|
||||
|
||||
p_size = mp_bpoly2arr(pp, p, 0) + 1;
|
||||
p = (unsigned int *) (malloc(sizeof(unsigned int) * p_size));
|
||||
if (p == NULL) goto cleanup;
|
||||
mp_bpoly2arr(pp, p, p_size);
|
||||
|
||||
CHECK_MPI_OK( mp_init(&lambda) );
|
||||
CHECK_MPI_OK( mp_init(&xtemp) );
|
||||
CHECK_MPI_OK( mp_init(&ytemp) );
|
||||
/* if P = inf, then R = Q */
|
||||
if (GF2m_ec_pt_is_inf_aff(px, py) == 0) {
|
||||
CHECK_MPI_OK( mp_copy(qx, rx) );
|
||||
CHECK_MPI_OK( mp_copy(qy, ry) );
|
||||
err = MP_OKAY;
|
||||
goto cleanup;
|
||||
}
|
||||
/* if Q = inf, then R = P */
|
||||
if (GF2m_ec_pt_is_inf_aff(qx, qy) == 0) {
|
||||
CHECK_MPI_OK( mp_copy(px, rx) );
|
||||
CHECK_MPI_OK( mp_copy(py, ry) );
|
||||
err = MP_OKAY;
|
||||
goto cleanup;
|
||||
}
|
||||
/* if px != qx, then lambda = (py+qy) / (px+qx),
|
||||
* xtemp = a + lambda^2 + lambda + px + qx
|
||||
*/
|
||||
if (mp_cmp(px, qx) != 0) {
|
||||
CHECK_MPI_OK( mp_badd(py, qy, &ytemp) );
|
||||
CHECK_MPI_OK( mp_badd(px, qx, &xtemp) );
|
||||
CHECK_MPI_OK( mp_bdivmod(&ytemp, &xtemp, pp, p, &lambda) );
|
||||
CHECK_MPI_OK( mp_bsqrmod(&lambda, p, &xtemp) );
|
||||
CHECK_MPI_OK( mp_badd(&xtemp, &lambda, &xtemp) );
|
||||
CHECK_MPI_OK( mp_badd(&xtemp, a, &xtemp) );
|
||||
CHECK_MPI_OK( mp_badd(&xtemp, px, &xtemp) );
|
||||
CHECK_MPI_OK( mp_badd(&xtemp, qx, &xtemp) );
|
||||
} else {
|
||||
/* if py != qy or qx = 0, then R = inf */
|
||||
if (((mp_cmp(py, qy) != 0)) || (mp_cmp_z(qx) == 0)) {
|
||||
mp_zero(rx);
|
||||
mp_zero(ry);
|
||||
err = MP_OKAY;
|
||||
goto cleanup;
|
||||
}
|
||||
/* lambda = qx + qy / qx */
|
||||
CHECK_MPI_OK( mp_bdivmod(qy, qx, pp, p, &lambda) );
|
||||
CHECK_MPI_OK( mp_badd(&lambda, qx, &lambda) );
|
||||
/* xtemp = a + lambda^2 + lambda */
|
||||
CHECK_MPI_OK( mp_bsqrmod(&lambda, p, &xtemp) );
|
||||
CHECK_MPI_OK( mp_badd(&xtemp, &lambda, &xtemp) );
|
||||
CHECK_MPI_OK( mp_badd(&xtemp, a, &xtemp) );
|
||||
}
|
||||
/* ry = (qx + xtemp) * lambda + xtemp + qy */
|
||||
CHECK_MPI_OK( mp_badd(qx, &xtemp, &ytemp) );
|
||||
CHECK_MPI_OK( mp_bmulmod(&ytemp, &lambda, p, &ytemp) );
|
||||
CHECK_MPI_OK( mp_badd(&ytemp, &xtemp, &ytemp) );
|
||||
CHECK_MPI_OK( mp_badd(&ytemp, qy, ry) );
|
||||
/* rx = xtemp */
|
||||
CHECK_MPI_OK( mp_copy(&xtemp, rx) );
|
||||
|
||||
cleanup:
|
||||
mp_clear(&lambda);
|
||||
mp_clear(&xtemp);
|
||||
mp_clear(&ytemp);
|
||||
free(p);
|
||||
return err;
|
||||
}
|
||||
|
||||
/* Computes R = P - Q.
|
||||
* Elliptic curve points P, Q, and R can all be identical.
|
||||
* Uses affine coordinates.
|
||||
*/
|
||||
mp_err
|
||||
GF2m_ec_pt_sub_aff(const mp_int *pp, const mp_int *a, const mp_int *px,
|
||||
const mp_int *py, const mp_int *qx, const mp_int *qy,
|
||||
mp_int *rx, mp_int *ry)
|
||||
{
|
||||
mp_err err = MP_OKAY;
|
||||
mp_int nqy;
|
||||
MP_DIGITS(&nqy) = 0;
|
||||
CHECK_MPI_OK( mp_init(&nqy) );
|
||||
/* nqy = qx+qy */
|
||||
CHECK_MPI_OK( mp_badd(qx, qy, &nqy) );
|
||||
err = GF2m_ec_pt_add_aff(pp, a, px, py, qx, &nqy, rx, ry);
|
||||
cleanup:
|
||||
mp_clear(&nqy);
|
||||
return err;
|
||||
}
|
||||
|
||||
/* Computes R = 2P.
|
||||
* Elliptic curve points P and R can be identical.
|
||||
* Uses affine coordinates.
|
||||
*/
|
||||
mp_err
|
||||
GF2m_ec_pt_dbl_aff(const mp_int *pp, const mp_int *a, const mp_int *px,
|
||||
const mp_int *py, mp_int *rx, mp_int *ry)
|
||||
{
|
||||
return GF2m_ec_pt_add_aff(pp, a, px, py, px, py, rx, ry);
|
||||
}
|
||||
|
||||
/* Gets the i'th bit in the binary representation of a.
|
||||
* If i >= length(a), then return 0.
|
||||
* (The above behaviour differs from mpl_get_bit, which
|
||||
* causes an error if i >= length(a).)
|
||||
*/
|
||||
#define MP_GET_BIT(a, i) \
|
||||
((i) >= mpl_significant_bits((a))) ? 0 : mpl_get_bit((a), (i))
|
||||
|
||||
/* Computes R = nP based on IEEE P1363 A.10.3.
|
||||
* Elliptic curve points P and R can be identical.
|
||||
* Uses affine coordinates.
|
||||
*/
|
||||
mp_err
|
||||
GF2m_ec_pt_mul_aff(const mp_int *pp, const mp_int *a, const mp_int *b,
|
||||
const mp_int *px, const mp_int *py, const mp_int *n,
|
||||
mp_int *rx, mp_int *ry)
|
||||
{
|
||||
mp_err err = MP_OKAY;
|
||||
mp_int k, k3, qx, qy, sx, sy;
|
||||
int b1, b3, i, l;
|
||||
unsigned int *p;
|
||||
int p_size;
|
||||
|
||||
MP_DIGITS(&k) = 0;
|
||||
MP_DIGITS(&k3) = 0;
|
||||
MP_DIGITS(&qx) = 0;
|
||||
MP_DIGITS(&qy) = 0;
|
||||
MP_DIGITS(&sx) = 0;
|
||||
MP_DIGITS(&sy) = 0;
|
||||
CHECK_MPI_OK( mp_init(&k) );
|
||||
CHECK_MPI_OK( mp_init(&k3) );
|
||||
CHECK_MPI_OK( mp_init(&qx) );
|
||||
CHECK_MPI_OK( mp_init(&qy) );
|
||||
CHECK_MPI_OK( mp_init(&sx) );
|
||||
CHECK_MPI_OK( mp_init(&sy) );
|
||||
|
||||
p_size = mp_bpoly2arr(pp, p, 0) + 1;
|
||||
p = (unsigned int *) (malloc(sizeof(unsigned int) * p_size));
|
||||
if (p == NULL) goto cleanup;
|
||||
mp_bpoly2arr(pp, p, p_size);
|
||||
|
||||
/* if n = 0 then r = inf */
|
||||
if (mp_cmp_z(n) == 0) {
|
||||
mp_zero(rx);
|
||||
mp_zero(ry);
|
||||
err = MP_OKAY;
|
||||
goto cleanup;
|
||||
}
|
||||
/* Q = P, k = n */
|
||||
CHECK_MPI_OK( mp_copy(px, &qx) );
|
||||
CHECK_MPI_OK( mp_copy(py, &qy) );
|
||||
CHECK_MPI_OK( mp_copy(n, &k) );
|
||||
/* if n < 0 then Q = -Q, k = -k */
|
||||
if (mp_cmp_z(n) < 0) {
|
||||
CHECK_MPI_OK( mp_badd(&qx, &qy, &qy) );
|
||||
CHECK_MPI_OK( mp_neg(&k, &k) );
|
||||
}
|
||||
#ifdef EC_DEBUG /* basic double and add method */
|
||||
l = mpl_significant_bits(&k) - 1;
|
||||
mp_zero(&sx);
|
||||
mp_zero(&sy);
|
||||
for (i = l; i >= 0; i--) {
|
||||
/* if k_i = 1, then S = S + Q */
|
||||
if (mpl_get_bit(&k, i) != 0) {
|
||||
CHECK_MPI_OK( GF2m_ec_pt_add_aff(pp, a, &sx, &sy, &qx, &qy, &sx, &sy) );
|
||||
}
|
||||
if (i > 0) {
|
||||
/* S = 2S */
|
||||
CHECK_MPI_OK( GF2m_ec_pt_dbl_aff(pp, a, &sx, &sy, &sx, &sy) );
|
||||
}
|
||||
}
|
||||
#else /* double and add/subtract method from standard */
|
||||
/* k3 = 3 * k */
|
||||
mp_set(&k3, 0x3);
|
||||
CHECK_MPI_OK( mp_mul(&k, &k3, &k3) );
|
||||
/* S = Q */
|
||||
CHECK_MPI_OK( mp_copy(&qx, &sx) );
|
||||
CHECK_MPI_OK( mp_copy(&qy, &sy) );
|
||||
/* l = index of high order bit in binary representation of 3*k */
|
||||
l = mpl_significant_bits(&k3) - 1;
|
||||
/* for i = l-1 downto 1 */
|
||||
for (i = l - 1; i >= 1; i--) {
|
||||
/* S = 2S */
|
||||
CHECK_MPI_OK( GF2m_ec_pt_dbl_aff(pp, a, &sx, &sy, &sx, &sy) );
|
||||
b3 = MP_GET_BIT(&k3, i);
|
||||
b1 = MP_GET_BIT(&k, i);
|
||||
/* if k3_i = 1 and k_i = 0, then S = S + Q */
|
||||
if ((b3 == 1) && (b1 == 0)) {
|
||||
CHECK_MPI_OK( GF2m_ec_pt_add_aff(pp, a, &sx, &sy, &qx, &qy, &sx, &sy) );
|
||||
/* if k3_i = 0 and k_i = 1, then S = S - Q */
|
||||
} else if ((b3 == 0) && (b1 == 1)) {
|
||||
CHECK_MPI_OK( GF2m_ec_pt_sub_aff(pp, a, &sx, &sy, &qx, &qy, &sx, &sy) );
|
||||
}
|
||||
}
|
||||
#endif
|
||||
/* output S */
|
||||
CHECK_MPI_OK( mp_copy(&sx, rx) );
|
||||
CHECK_MPI_OK( mp_copy(&sy, ry) );
|
||||
|
||||
cleanup:
|
||||
mp_clear(&k);
|
||||
mp_clear(&k3);
|
||||
mp_clear(&qx);
|
||||
mp_clear(&qy);
|
||||
mp_clear(&sx);
|
||||
mp_clear(&sy);
|
||||
free(p);
|
||||
return err;
|
||||
}
|
||||
|
||||
/* Compute the x-coordinate x/z for the point 2*(x/z) in Montgomery projective
|
||||
* coordinates.
|
||||
* Uses algorithm Mdouble in appendix of
|
||||
* Lopez, J. and Dahab, R. "Fast multiplication on elliptic curves over
|
||||
* GF(2^m) without precomputation".
|
||||
* modified to not require precomputation of c=b^{2^{m-1}}.
|
||||
*/
|
||||
static mp_err
|
||||
gf2m_Mdouble(const mp_int *pp, const unsigned int p[], const mp_int *a,
|
||||
const mp_int *b, mp_int *x, mp_int *z)
|
||||
{
|
||||
mp_err err = MP_OKAY;
|
||||
mp_int t1;
|
||||
|
||||
MP_DIGITS(&t1) = 0;
|
||||
CHECK_MPI_OK( mp_init(&t1) );
|
||||
|
||||
CHECK_MPI_OK( mp_bsqrmod(x, p, x) );
|
||||
CHECK_MPI_OK( mp_bsqrmod(z, p, &t1) );
|
||||
CHECK_MPI_OK( mp_bmulmod(x, &t1, p, z) );
|
||||
CHECK_MPI_OK( mp_bsqrmod(x, p, x) );
|
||||
CHECK_MPI_OK( mp_bsqrmod(&t1, p, &t1) );
|
||||
CHECK_MPI_OK( mp_bmulmod(b, &t1, p, &t1) );
|
||||
CHECK_MPI_OK( mp_badd(x, &t1, x) );
|
||||
|
||||
cleanup:
|
||||
mp_clear(&t1);
|
||||
return err;
|
||||
}
|
||||
|
||||
/* Compute the x-coordinate x1/z1 for the point (x1/z1)+(x2/x2) in Montgomery
|
||||
* projective coordinates.
|
||||
* Uses algorithm Madd in appendix of
|
||||
* Lopex, J. and Dahab, R. "Fast multiplication on elliptic curves over
|
||||
* GF(2^m) without precomputation".
|
||||
*/
|
||||
static mp_err
|
||||
gf2m_Madd(const mp_int *pp, const unsigned int p[], const mp_int *a,
|
||||
const mp_int *b, const mp_int *x, mp_int *x1, mp_int *z1, mp_int *x2,
|
||||
mp_int *z2)
|
||||
{
|
||||
mp_err err = MP_OKAY;
|
||||
mp_int t1, t2;
|
||||
|
||||
MP_DIGITS(&t1) = 0;
|
||||
MP_DIGITS(&t2) = 0;
|
||||
CHECK_MPI_OK( mp_init(&t1) );
|
||||
CHECK_MPI_OK( mp_init(&t2) );
|
||||
|
||||
CHECK_MPI_OK( mp_copy(x, &t1) );
|
||||
CHECK_MPI_OK( mp_bmulmod(x1, z2, p, x1) );
|
||||
CHECK_MPI_OK( mp_bmulmod(z1, x2, p, z1) );
|
||||
CHECK_MPI_OK( mp_bmulmod(x1, z1, p, &t2) );
|
||||
CHECK_MPI_OK( mp_badd(z1, x1, z1) );
|
||||
CHECK_MPI_OK( mp_bsqrmod(z1, p, z1) );
|
||||
CHECK_MPI_OK( mp_bmulmod(z1, &t1, p, x1) );
|
||||
CHECK_MPI_OK( mp_badd(x1, &t2, x1) );
|
||||
|
||||
cleanup:
|
||||
mp_clear(&t1);
|
||||
mp_clear(&t2);
|
||||
return err;
|
||||
}
|
||||
|
||||
/* Compute the x, y affine coordinates from the point (x1, z1) (x2, z2)
|
||||
* using Montgomery point multiplication algorithm Mxy() in appendix of
|
||||
* Lopex, J. and Dahab, R. "Fast multiplication on elliptic curves over
|
||||
* GF(2^m) without precomputation".
|
||||
* Returns:
|
||||
* 0 on error
|
||||
* 1 if return value should be the point at infinity
|
||||
* 2 otherwise
|
||||
*/
|
||||
static int
|
||||
gf2m_Mxy(const mp_int *pp, const unsigned int p[], const mp_int *a,
|
||||
const mp_int *b, const mp_int *x, const mp_int *y, mp_int *x1, mp_int *z1,
|
||||
mp_int *x2, mp_int *z2)
|
||||
{
|
||||
mp_err err = MP_OKAY;
|
||||
int ret;
|
||||
mp_int t3, t4, t5;
|
||||
|
||||
MP_DIGITS(&t3) = 0;
|
||||
MP_DIGITS(&t4) = 0;
|
||||
MP_DIGITS(&t5) = 0;
|
||||
CHECK_MPI_OK( mp_init(&t3) );
|
||||
CHECK_MPI_OK( mp_init(&t4) );
|
||||
CHECK_MPI_OK( mp_init(&t5) );
|
||||
|
||||
if (mp_cmp_z(z1) == 0) {
|
||||
mp_zero(x2);
|
||||
mp_zero(z2);
|
||||
ret = 1;
|
||||
goto cleanup;
|
||||
}
|
||||
|
||||
if (mp_cmp_z(z2) == 0) {
|
||||
CHECK_MPI_OK( mp_copy(x, x2) );
|
||||
CHECK_MPI_OK( mp_badd(x, y, z2) );
|
||||
ret = 2;
|
||||
goto cleanup;
|
||||
}
|
||||
|
||||
mp_set(&t5, 0x1);
|
||||
|
||||
CHECK_MPI_OK( mp_bmulmod(z1, z2, p, &t3) );
|
||||
|
||||
CHECK_MPI_OK( mp_bmulmod(z1, x, p, z1) );
|
||||
CHECK_MPI_OK( mp_badd(z1, x1, z1) );
|
||||
CHECK_MPI_OK( mp_bmulmod(z2, x, p, z2) );
|
||||
CHECK_MPI_OK( mp_bmulmod(z2, x1, p, x1) );
|
||||
CHECK_MPI_OK( mp_badd(z2, x2, z2) );
|
||||
|
||||
CHECK_MPI_OK( mp_bmulmod(z2, z1, p, z2) );
|
||||
CHECK_MPI_OK( mp_bsqrmod(x, p, &t4) );
|
||||
CHECK_MPI_OK( mp_badd(&t4, y, &t4) );
|
||||
CHECK_MPI_OK( mp_bmulmod(&t4, &t3, p, &t4) );
|
||||
CHECK_MPI_OK( mp_badd(&t4, z2, &t4) );
|
||||
|
||||
CHECK_MPI_OK( mp_bmulmod(&t3, x, p, &t3) );
|
||||
CHECK_MPI_OK( mp_bdivmod(&t5, &t3, pp, p, &t3) );
|
||||
CHECK_MPI_OK( mp_bmulmod(&t3, &t4, p, &t4) );
|
||||
CHECK_MPI_OK( mp_bmulmod(x1, &t3, p, x2) );
|
||||
CHECK_MPI_OK( mp_badd(x2, x, z2) );
|
||||
|
||||
CHECK_MPI_OK( mp_bmulmod(z2, &t4, p, z2) );
|
||||
CHECK_MPI_OK( mp_badd(z2, y, z2) );
|
||||
|
||||
ret = 2;
|
||||
|
||||
cleanup:
|
||||
mp_clear(&t3);
|
||||
mp_clear(&t4);
|
||||
mp_clear(&t5);
|
||||
if (err == MP_OKAY) {
|
||||
return ret;
|
||||
} else {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/* Computes R = nP based on algorithm 2P of
|
||||
* Lopex, J. and Dahab, R. "Fast multiplication on elliptic curves over
|
||||
* GF(2^m) without precomputation".
|
||||
* Elliptic curve points P and R can be identical.
|
||||
* Uses Montgomery projective coordinates.
|
||||
*/
|
||||
mp_err
|
||||
GF2m_ec_pt_mul_mont(const mp_int *pp, const mp_int *a, const mp_int *b,
|
||||
const mp_int *px, const mp_int *py, const mp_int *n,
|
||||
mp_int *rx, mp_int *ry)
|
||||
{
|
||||
mp_err err = MP_OKAY;
|
||||
mp_int x1, x2, z1, z2;
|
||||
int i, j;
|
||||
mp_digit top_bit, mask;
|
||||
unsigned int *p;
|
||||
int p_size;
|
||||
|
||||
MP_DIGITS(&x1) = 0;
|
||||
MP_DIGITS(&x2) = 0;
|
||||
MP_DIGITS(&z1) = 0;
|
||||
MP_DIGITS(&z2) = 0;
|
||||
CHECK_MPI_OK( mp_init(&x1) );
|
||||
CHECK_MPI_OK( mp_init(&x2) );
|
||||
CHECK_MPI_OK( mp_init(&z1) );
|
||||
CHECK_MPI_OK( mp_init(&z2) );
|
||||
|
||||
p_size = mp_bpoly2arr(pp, p, 0) + 1;
|
||||
p = (unsigned int *) (malloc(sizeof(unsigned int) * p_size));
|
||||
if (p == NULL) goto cleanup;
|
||||
mp_bpoly2arr(pp, p, p_size);
|
||||
|
||||
/* if result should be point at infinity */
|
||||
if ((mp_cmp_z(n) == 0) || (GF2m_ec_pt_is_inf_aff(px, py) == MP_YES)) {
|
||||
CHECK_MPI_OK( GF2m_ec_pt_set_inf_aff(rx, ry) );
|
||||
goto cleanup;
|
||||
}
|
||||
|
||||
CHECK_MPI_OK( mp_copy(rx, &x2) ); /* x2 = rx */
|
||||
CHECK_MPI_OK( mp_copy(ry, &z2) ); /* z2 = ry */
|
||||
|
||||
CHECK_MPI_OK( mp_copy(px, &x1) ); /* x1 = px */
|
||||
mp_set(&z1, 0x1); /* z1 = 1 */
|
||||
CHECK_MPI_OK( mp_bsqrmod(&x1, p, &z2) ); /* z2 = x1^2 = x2^2 */
|
||||
CHECK_MPI_OK( mp_bsqrmod(&z2, p, &x2) );
|
||||
CHECK_MPI_OK( mp_badd(&x2, b, &x2) ); /* x2 = px^4 + b */
|
||||
|
||||
/* find top-most bit and go one past it */
|
||||
i = MP_USED(n) - 1;
|
||||
j = MP_DIGIT_BIT - 1;
|
||||
top_bit = 1;
|
||||
top_bit <<= MP_DIGIT_BIT - 1;
|
||||
mask = top_bit;
|
||||
while (!(MP_DIGITS(n)[i] & mask)) {
|
||||
mask >>= 1;
|
||||
j--;
|
||||
}
|
||||
mask >>= 1; j--;
|
||||
|
||||
/* if top most bit was at word break, go to next word */
|
||||
if (!mask) {
|
||||
i--;
|
||||
j = MP_DIGIT_BIT - 1;
|
||||
mask = top_bit;
|
||||
}
|
||||
|
||||
for (; i >= 0; i--) {
|
||||
for (; j >= 0; j--) {
|
||||
if (MP_DIGITS(n)[i] & mask) {
|
||||
CHECK_MPI_OK( gf2m_Madd(pp, p, a, b, px, &x1, &z1, &x2, &z2) );
|
||||
CHECK_MPI_OK( gf2m_Mdouble(pp, p, a, b, &x2, &z2) );
|
||||
} else {
|
||||
CHECK_MPI_OK( gf2m_Madd(pp, p, a, b, px, &x2, &z2, &x1, &z1) );
|
||||
CHECK_MPI_OK( gf2m_Mdouble(pp, p, a, b, &x1, &z1) );
|
||||
}
|
||||
mask >>= 1;
|
||||
}
|
||||
j = MP_DIGIT_BIT - 1;
|
||||
mask = top_bit;
|
||||
}
|
||||
|
||||
/* convert out of "projective" coordinates */
|
||||
i = gf2m_Mxy(pp, p, a, b, px, py, &x1, &z1, &x2, &z2);
|
||||
if (i == 0) {
|
||||
err = MP_BADARG;
|
||||
goto cleanup;
|
||||
} else if (i == 1) {
|
||||
CHECK_MPI_OK( GF2m_ec_pt_set_inf_aff(rx, ry) );
|
||||
} else {
|
||||
CHECK_MPI_OK( mp_copy(&x2, rx) );
|
||||
CHECK_MPI_OK( mp_copy(&z2, ry) );
|
||||
}
|
||||
|
||||
cleanup:
|
||||
mp_clear(&x1);
|
||||
mp_clear(&x2);
|
||||
mp_clear(&z1);
|
||||
mp_clear(&z2);
|
||||
free(p);
|
||||
return err;
|
||||
}
|
||||
|
||||
#endif /* NSS_ENABLE_ECC */
|
||||
96
mozilla/security/nss/lib/freebl/GF2m_ecl.h
Normal file
96
mozilla/security/nss/lib/freebl/GF2m_ecl.h
Normal file
@@ -0,0 +1,96 @@
|
||||
/*
|
||||
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
|
||||
*
|
||||
* The contents of this file are subject to the Mozilla Public License Version
|
||||
* 1.1 (the "License"); you may not use this file except in compliance with
|
||||
* the License. You may obtain a copy of the License at
|
||||
* http://www.mozilla.org/MPL/
|
||||
*
|
||||
* Software distributed under the License is distributed on an "AS IS" basis,
|
||||
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
|
||||
* for the specific language governing rights and limitations under the
|
||||
* License.
|
||||
*
|
||||
* The Original Code is the elliptic curve math library for binary polynomial
|
||||
* field curves.
|
||||
*
|
||||
* The Initial Developer of the Original Code is Sun Microsystems, Inc.
|
||||
* Portions created by Sun Microsystems, Inc. are Copyright (C) 2003
|
||||
* Sun Microsystems, Inc. All Rights Reserved.
|
||||
*
|
||||
* Contributor(s):
|
||||
* Douglas Stebila <douglas@stebila.ca>
|
||||
*
|
||||
* Alternatively, the contents of this file may be used under the terms of
|
||||
* either the GNU General Public License Version 2 or later (the "GPL"), or
|
||||
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
|
||||
* in which case the provisions of the GPL or the LGPL are applicable instead
|
||||
* of those above. If you wish to allow use of your version of this file only
|
||||
* under the terms of either the GPL or the LGPL, and not to allow others to
|
||||
* use your version of this file under the terms of the MPL, indicate your
|
||||
* decision by deleting the provisions above and replace them with the notice
|
||||
* and other provisions required by the GPL or the LGPL. If you do not delete
|
||||
* the provisions above, a recipient may use your version of this file under
|
||||
* the terms of any one of the MPL, the GPL or the LGPL.
|
||||
*
|
||||
*/
|
||||
|
||||
#ifndef __gf2m_ecl_h_
|
||||
#define __gf2m_ecl_h_
|
||||
#ifdef NSS_ENABLE_ECC
|
||||
|
||||
#include "secmpi.h"
|
||||
|
||||
/* Checks if point P(px, py) is at infinity. Uses affine coordinates. */
|
||||
mp_err GF2m_ec_pt_is_inf_aff(const mp_int *px, const mp_int *py);
|
||||
|
||||
/* Sets P(px, py) to be the point at infinity. Uses affine coordinates. */
|
||||
mp_err GF2m_ec_pt_set_inf_aff(mp_int *px, mp_int *py);
|
||||
|
||||
/* Computes R = P + Q where R is (rx, ry), P is (px, py) and Q is (qx, qy).
|
||||
* Uses affine coordinates.
|
||||
*/
|
||||
mp_err GF2m_ec_pt_add_aff(const mp_int *pp, const mp_int *a,
|
||||
const mp_int *px, const mp_int *py, const mp_int *qx, const mp_int *qy,
|
||||
mp_int *rx, mp_int *ry);
|
||||
|
||||
/* Computes R = P - Q. Uses affine coordinates. */
|
||||
mp_err GF2m_ec_pt_sub_aff(const mp_int *pp, const mp_int *a,
|
||||
const mp_int *px, const mp_int *py, const mp_int *qx, const mp_int *qy,
|
||||
mp_int *rx, mp_int *ry);
|
||||
|
||||
/* Computes R = 2P. Uses affine coordinates. */
|
||||
mp_err GF2m_ec_pt_dbl_aff(const mp_int *pp, const mp_int *a,
|
||||
const mp_int *px, const mp_int *py, mp_int *rx, mp_int *ry);
|
||||
|
||||
/* Computes R = nP where R is (rx, ry) and P is (px, py). The parameters
|
||||
* a, b and p are the elliptic curve coefficients and the irreducible that
|
||||
* determines the field GF2m. Uses affine coordinates.
|
||||
*/
|
||||
mp_err GF2m_ec_pt_mul_aff(const mp_int *pp, const mp_int *a, const mp_int *b,
|
||||
const mp_int *px, const mp_int *py, const mp_int *n,
|
||||
mp_int *rx, mp_int *ry);
|
||||
|
||||
/* Computes R = nP where R is (rx, ry) and P is (px, py). The parameters
|
||||
* a, b and p are the elliptic curve coefficients and the irreducible that
|
||||
* determines the field GF2m. Uses Montgomery projective coordinates.
|
||||
*/
|
||||
mp_err GF2m_ec_pt_mul_mont(const mp_int *pp, const mp_int *a,
|
||||
const mp_int *b, const mp_int *px, const mp_int *py,
|
||||
const mp_int *n, mp_int *rx, mp_int *ry);
|
||||
|
||||
#define GF2m_ec_pt_is_inf(px, py) GF2m_ec_pt_is_inf_aff((px), (py))
|
||||
#define GF2m_ec_pt_add(p, a, px, py, qx, qy, rx, ry) \
|
||||
GF2m_ec_pt_add_aff((p), (a), (px), (py), (qx), (qy), (rx), (ry))
|
||||
|
||||
#define GF2m_ECL_MONTGOMERY
|
||||
#ifdef GF2m_ECL_AFFINE
|
||||
#define GF2m_ec_pt_mul(pp, a, b, px, py, n, rx, ry) \
|
||||
GF2m_ec_pt_mul_aff((pp), (a), (b), (px), (py), (n), (rx), (ry))
|
||||
#elif defined(GF2m_ECL_MONTGOMERY)
|
||||
#define GF2m_ec_pt_mul(pp, a, b, px, py, n, rx, ry) \
|
||||
GF2m_ec_pt_mul_mont((pp), (a), (b), (px), (py), (n), (rx), (ry))
|
||||
#endif /* GF2m_ECL_AFFINE or GF2m_ECL_MONTGOMERY */
|
||||
|
||||
#endif /* NSS_ENABLE_ECC */
|
||||
#endif /* __gf2m_ecl_h_ */
|
||||
647
mozilla/security/nss/lib/freebl/GFp_ecl.c
Normal file
647
mozilla/security/nss/lib/freebl/GFp_ecl.c
Normal file
@@ -0,0 +1,647 @@
|
||||
/*
|
||||
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
|
||||
*
|
||||
* The contents of this file are subject to the Mozilla Public License Version
|
||||
* 1.1 (the "License"); you may not use this file except in compliance with
|
||||
* the License. You may obtain a copy of the License at
|
||||
* http://www.mozilla.org/MPL/
|
||||
*
|
||||
* Software distributed under the License is distributed on an "AS IS" basis,
|
||||
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
|
||||
* for the specific language governing rights and limitations under the
|
||||
* License.
|
||||
*
|
||||
* The Original Code is the elliptic curve math library for prime
|
||||
* field curves.
|
||||
*
|
||||
* The Initial Developer of the Original Code is Sun Microsystems, Inc.
|
||||
* Portions created by Sun Microsystems, Inc. are Copyright (C) 2003
|
||||
* Sun Microsystems, Inc. All Rights Reserved.
|
||||
*
|
||||
* Contributor(s):
|
||||
* Sheueling Chang Shantz <sheueling.chang@sun.com> and
|
||||
* Douglas Stebila <douglas@stebila.ca>, Sun Microsystems Laboratories
|
||||
*
|
||||
* Bodo Moeller <moeller@cdc.informatik.tu-darmstadt.de>,
|
||||
* Nils Larsch <nla@trustcenter.de>, and
|
||||
* Lenka Fibikova <fibikova@exp-math.uni-essen.de>, the OpenSSL Project.
|
||||
*
|
||||
* Alternatively, the contents of this file may be used under the terms of
|
||||
* either the GNU General Public License Version 2 or later (the "GPL"), or
|
||||
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
|
||||
* in which case the provisions of the GPL or the LGPL are applicable instead
|
||||
* of those above. If you wish to allow use of your version of this file only
|
||||
* under the terms of either the GPL or the LGPL, and not to allow others to
|
||||
* use your version of this file under the terms of the MPL, indicate your
|
||||
* decision by deleting the provisions above and replace them with the notice
|
||||
* and other provisions required by the GPL or the LGPL. If you do not delete
|
||||
* the provisions above, a recipient may use your version of this file under
|
||||
* the terms of any one of the MPL, the GPL or the LGPL.
|
||||
*
|
||||
*/
|
||||
#ifdef NSS_ENABLE_ECC
|
||||
/*
|
||||
* GFp_ecl.c: Contains an implementation of elliptic curve math library
|
||||
* for curves over GFp.
|
||||
*
|
||||
* XXX Can be moved to a separate subdirectory later.
|
||||
*
|
||||
*/
|
||||
|
||||
#include "GFp_ecl.h"
|
||||
#include "mpi/mplogic.h"
|
||||
|
||||
/* Checks if point P(px, py) is at infinity. Uses affine coordinates. */
|
||||
mp_err
|
||||
GFp_ec_pt_is_inf_aff(const mp_int *px, const mp_int *py)
|
||||
{
|
||||
|
||||
if ((mp_cmp_z(px) == 0) && (mp_cmp_z(py) == 0)) {
|
||||
return MP_YES;
|
||||
} else {
|
||||
return MP_NO;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
/* Sets P(px, py) to be the point at infinity. Uses affine coordinates. */
|
||||
mp_err
|
||||
GFp_ec_pt_set_inf_aff(mp_int *px, mp_int *py)
|
||||
{
|
||||
mp_zero(px);
|
||||
mp_zero(py);
|
||||
return MP_OKAY;
|
||||
}
|
||||
|
||||
/* Computes R = P + Q based on IEEE P1363 A.10.1.
|
||||
* Elliptic curve points P, Q, and R can all be identical.
|
||||
* Uses affine coordinates.
|
||||
*/
|
||||
mp_err
|
||||
GFp_ec_pt_add_aff(const mp_int *p, const mp_int *a, const mp_int *px,
|
||||
const mp_int *py, const mp_int *qx, const mp_int *qy,
|
||||
mp_int *rx, mp_int *ry)
|
||||
{
|
||||
mp_err err = MP_OKAY;
|
||||
mp_int lambda, temp, xtemp, ytemp;
|
||||
|
||||
CHECK_MPI_OK( mp_init(&lambda) );
|
||||
CHECK_MPI_OK( mp_init(&temp) );
|
||||
CHECK_MPI_OK( mp_init(&xtemp) );
|
||||
CHECK_MPI_OK( mp_init(&ytemp) );
|
||||
/* if P = inf, then R = Q */
|
||||
if (GFp_ec_pt_is_inf_aff(px, py) == 0) {
|
||||
CHECK_MPI_OK( mp_copy(qx, rx) );
|
||||
CHECK_MPI_OK( mp_copy(qy, ry) );
|
||||
err = MP_OKAY;
|
||||
goto cleanup;
|
||||
}
|
||||
/* if Q = inf, then R = P */
|
||||
if (GFp_ec_pt_is_inf_aff(qx, qy) == 0) {
|
||||
CHECK_MPI_OK( mp_copy(px, rx) );
|
||||
CHECK_MPI_OK( mp_copy(py, ry) );
|
||||
err = MP_OKAY;
|
||||
goto cleanup;
|
||||
}
|
||||
/* if px != qx, then lambda = (py-qy) / (px-qx) */
|
||||
if (mp_cmp(px, qx) != 0) {
|
||||
CHECK_MPI_OK( mp_submod(py, qy, p, &ytemp) );
|
||||
CHECK_MPI_OK( mp_submod(px, qx, p, &xtemp) );
|
||||
CHECK_MPI_OK( mp_invmod(&xtemp, p, &xtemp) );
|
||||
CHECK_MPI_OK( mp_mulmod(&ytemp, &xtemp, p, &lambda) );
|
||||
} else {
|
||||
/* if py != qy or qy = 0, then R = inf */
|
||||
if (((mp_cmp(py, qy) != 0)) || (mp_cmp_z(qy) == 0)) {
|
||||
mp_zero(rx);
|
||||
mp_zero(ry);
|
||||
err = MP_OKAY;
|
||||
goto cleanup;
|
||||
}
|
||||
/* lambda = (3qx^2+a) / (2qy) */
|
||||
CHECK_MPI_OK( mp_sqrmod(qx, p, &xtemp) );
|
||||
mp_set(&temp, 0x3);
|
||||
CHECK_MPI_OK( mp_mulmod(&xtemp, &temp, p, &xtemp) );
|
||||
CHECK_MPI_OK( mp_addmod(&xtemp, a, p, &xtemp) );
|
||||
mp_set(&temp, 0x2);
|
||||
CHECK_MPI_OK( mp_mulmod(qy, &temp, p, &ytemp) );
|
||||
CHECK_MPI_OK( mp_invmod(&ytemp, p, &ytemp) );
|
||||
CHECK_MPI_OK( mp_mulmod(&xtemp, &ytemp, p, &lambda) );
|
||||
}
|
||||
/* rx = lambda^2 - px - qx */
|
||||
CHECK_MPI_OK( mp_sqrmod(&lambda, p, &xtemp) );
|
||||
CHECK_MPI_OK( mp_submod(&xtemp, px, p, &xtemp) );
|
||||
CHECK_MPI_OK( mp_submod(&xtemp, qx, p, &xtemp) );
|
||||
/* ry = (x1-x2) * lambda - y1 */
|
||||
CHECK_MPI_OK( mp_submod(qx, &xtemp, p, &ytemp) );
|
||||
CHECK_MPI_OK( mp_mulmod(&ytemp, &lambda, p, &ytemp) );
|
||||
CHECK_MPI_OK( mp_submod(&ytemp, qy, p, &ytemp) );
|
||||
CHECK_MPI_OK( mp_copy(&xtemp, rx) );
|
||||
CHECK_MPI_OK( mp_copy(&ytemp, ry) );
|
||||
|
||||
cleanup:
|
||||
mp_clear(&lambda);
|
||||
mp_clear(&temp);
|
||||
mp_clear(&xtemp);
|
||||
mp_clear(&ytemp);
|
||||
return err;
|
||||
}
|
||||
|
||||
/* Computes R = P - Q.
|
||||
* Elliptic curve points P, Q, and R can all be identical.
|
||||
* Uses affine coordinates.
|
||||
*/
|
||||
mp_err
|
||||
GFp_ec_pt_sub_aff(const mp_int *p, const mp_int *a, const mp_int *px,
|
||||
const mp_int *py, const mp_int *qx, const mp_int *qy,
|
||||
mp_int *rx, mp_int *ry)
|
||||
{
|
||||
mp_err err = MP_OKAY;
|
||||
mp_int nqy;
|
||||
MP_DIGITS(&nqy) = 0;
|
||||
CHECK_MPI_OK( mp_init(&nqy) );
|
||||
/* nqy = -qy */
|
||||
CHECK_MPI_OK( mp_neg(qy, &nqy) );
|
||||
err = GFp_ec_pt_add_aff(p, a, px, py, qx, &nqy, rx, ry);
|
||||
cleanup:
|
||||
mp_clear(&nqy);
|
||||
return err;
|
||||
}
|
||||
|
||||
/* Computes R = 2P.
|
||||
* Elliptic curve points P and R can be identical.
|
||||
* Uses affine coordinates.
|
||||
*/
|
||||
mp_err
|
||||
GFp_ec_pt_dbl_aff(const mp_int *p, const mp_int *a, const mp_int *px,
|
||||
const mp_int *py, mp_int *rx, mp_int *ry)
|
||||
{
|
||||
return GFp_ec_pt_add_aff(p, a, px, py, px, py, rx, ry);
|
||||
}
|
||||
|
||||
/* Gets the i'th bit in the binary representation of a.
|
||||
* If i >= length(a), then return 0.
|
||||
* (The above behaviour differs from mpl_get_bit, which
|
||||
* causes an error if i >= length(a).)
|
||||
*/
|
||||
#define MP_GET_BIT(a, i) \
|
||||
((i) >= mpl_significant_bits((a))) ? 0 : mpl_get_bit((a), (i))
|
||||
|
||||
/* Computes R = nP based on IEEE P1363 A.10.3.
|
||||
* Elliptic curve points P and R can be identical.
|
||||
* Uses affine coordinates.
|
||||
*/
|
||||
mp_err
|
||||
GFp_ec_pt_mul_aff(const mp_int *p, const mp_int *a, const mp_int *b,
|
||||
const mp_int *px, const mp_int *py, const mp_int *n, mp_int *rx,
|
||||
mp_int *ry)
|
||||
{
|
||||
mp_err err = MP_OKAY;
|
||||
mp_int k, k3, qx, qy, sx, sy;
|
||||
int b1, b3, i, l;
|
||||
|
||||
MP_DIGITS(&k) = 0;
|
||||
MP_DIGITS(&k3) = 0;
|
||||
MP_DIGITS(&qx) = 0;
|
||||
MP_DIGITS(&qy) = 0;
|
||||
MP_DIGITS(&sx) = 0;
|
||||
MP_DIGITS(&sy) = 0;
|
||||
CHECK_MPI_OK( mp_init(&k) );
|
||||
CHECK_MPI_OK( mp_init(&k3) );
|
||||
CHECK_MPI_OK( mp_init(&qx) );
|
||||
CHECK_MPI_OK( mp_init(&qy) );
|
||||
CHECK_MPI_OK( mp_init(&sx) );
|
||||
CHECK_MPI_OK( mp_init(&sy) );
|
||||
|
||||
/* if n = 0 then r = inf */
|
||||
if (mp_cmp_z(n) == 0) {
|
||||
mp_zero(rx);
|
||||
mp_zero(ry);
|
||||
err = MP_OKAY;
|
||||
goto cleanup;
|
||||
}
|
||||
/* Q = P, k = n */
|
||||
CHECK_MPI_OK( mp_copy(px, &qx) );
|
||||
CHECK_MPI_OK( mp_copy(py, &qy) );
|
||||
CHECK_MPI_OK( mp_copy(n, &k) );
|
||||
/* if n < 0 Q = -Q, k = -k */
|
||||
if (mp_cmp_z(n) < 0) {
|
||||
CHECK_MPI_OK( mp_neg(&qy, &qy) );
|
||||
CHECK_MPI_OK( mp_mod(&qy, p, &qy) );
|
||||
CHECK_MPI_OK( mp_neg(&k, &k) );
|
||||
CHECK_MPI_OK( mp_mod(&k, p, &k) );
|
||||
}
|
||||
#ifdef EC_DEBUG /* basic double and add method */
|
||||
l = mpl_significant_bits(&k) - 1;
|
||||
mp_zero(&sx);
|
||||
mp_zero(&sy);
|
||||
for (i = l; i >= 0; i--) {
|
||||
/* if k_i = 1, then S = S + Q */
|
||||
if (mpl_get_bit(&k, i) != 0) {
|
||||
CHECK_MPI_OK( GFp_ec_pt_add_aff(p, a, &sx, &sy,
|
||||
&qx, &qy, &sx, &sy) );
|
||||
}
|
||||
if (i > 0) {
|
||||
/* S = 2S */
|
||||
CHECK_MPI_OK( GFp_ec_pt_dbl_aff(p, a, &sx, &sy, &sx, &sy) );
|
||||
}
|
||||
}
|
||||
#else /* double and add/subtract method from standard */
|
||||
/* k3 = 3 * k */
|
||||
mp_set(&k3, 0x3);
|
||||
CHECK_MPI_OK( mp_mul(&k, &k3, &k3) );
|
||||
/* S = Q */
|
||||
CHECK_MPI_OK( mp_copy(&qx, &sx) );
|
||||
CHECK_MPI_OK( mp_copy(&qy, &sy) );
|
||||
/* l = index of high order bit in binary representation of 3*k */
|
||||
l = mpl_significant_bits(&k3) - 1;
|
||||
/* for i = l-1 downto 1 */
|
||||
for (i = l - 1; i >= 1; i--) {
|
||||
/* S = 2S */
|
||||
CHECK_MPI_OK( GFp_ec_pt_dbl_aff(p, a, &sx, &sy, &sx, &sy) );
|
||||
b3 = MP_GET_BIT(&k3, i);
|
||||
b1 = MP_GET_BIT(&k, i);
|
||||
/* if k3_i = 1 and k_i = 0, then S = S + Q */
|
||||
if ((b3 == 1) && (b1 == 0)) {
|
||||
CHECK_MPI_OK( GFp_ec_pt_add_aff(p, a, &sx, &sy,
|
||||
&qx, &qy, &sx, &sy) );
|
||||
/* if k3_i = 0 and k_i = 1, then S = S - Q */
|
||||
} else if ((b3 == 0) && (b1 == 1)) {
|
||||
CHECK_MPI_OK( GFp_ec_pt_sub_aff(p, a, &sx, &sy,
|
||||
&qx, &qy, &sx, &sy) );
|
||||
}
|
||||
}
|
||||
#endif
|
||||
/* output S */
|
||||
CHECK_MPI_OK( mp_copy(&sx, rx) );
|
||||
CHECK_MPI_OK( mp_copy(&sy, ry) );
|
||||
|
||||
cleanup:
|
||||
mp_clear(&k);
|
||||
mp_clear(&k3);
|
||||
mp_clear(&qx);
|
||||
mp_clear(&qy);
|
||||
mp_clear(&sx);
|
||||
mp_clear(&sy);
|
||||
return err;
|
||||
}
|
||||
|
||||
/* Converts a point P(px, py, pz) from Jacobian projective coordinates to
|
||||
* affine coordinates R(rx, ry). P and R can share x and y coordinates.
|
||||
*/
|
||||
mp_err
|
||||
GFp_ec_pt_jac2aff(const mp_int *px, const mp_int *py, const mp_int *pz,
|
||||
const mp_int *p, mp_int *rx, mp_int *ry)
|
||||
{
|
||||
mp_err err = MP_OKAY;
|
||||
mp_int z1, z2, z3;
|
||||
MP_DIGITS(&z1) = 0;
|
||||
MP_DIGITS(&z2) = 0;
|
||||
MP_DIGITS(&z3) = 0;
|
||||
CHECK_MPI_OK( mp_init(&z1) );
|
||||
CHECK_MPI_OK( mp_init(&z2) );
|
||||
CHECK_MPI_OK( mp_init(&z3) );
|
||||
|
||||
/* if point at infinity, then set point at infinity and exit */
|
||||
if (GFp_ec_pt_is_inf_jac(px, py, pz) == MP_YES) {
|
||||
CHECK_MPI_OK( GFp_ec_pt_set_inf_aff(rx, ry) );
|
||||
goto cleanup;
|
||||
}
|
||||
|
||||
/* transform (px, py, pz) into (px / pz^2, py / pz^3) */
|
||||
if (mp_cmp_d(pz, 1) == 0) {
|
||||
CHECK_MPI_OK( mp_copy(px, rx) );
|
||||
CHECK_MPI_OK( mp_copy(py, ry) );
|
||||
} else {
|
||||
CHECK_MPI_OK( mp_invmod(pz, p, &z1) );
|
||||
CHECK_MPI_OK( mp_sqrmod(&z1, p, &z2) );
|
||||
CHECK_MPI_OK( mp_mulmod(&z1, &z2, p, &z3) );
|
||||
CHECK_MPI_OK( mp_mulmod(px, &z2, p, rx) );
|
||||
CHECK_MPI_OK( mp_mulmod(py, &z3, p, ry) );
|
||||
}
|
||||
|
||||
cleanup:
|
||||
mp_clear(&z1);
|
||||
mp_clear(&z2);
|
||||
mp_clear(&z3);
|
||||
return err;
|
||||
}
|
||||
|
||||
/* Checks if point P(px, py, pz) is at infinity.
|
||||
* Uses Jacobian coordinates.
|
||||
*/
|
||||
mp_err
|
||||
GFp_ec_pt_is_inf_jac(const mp_int *px, const mp_int *py, const mp_int *pz)
|
||||
{
|
||||
return mp_cmp_z(pz);
|
||||
}
|
||||
|
||||
/* Sets P(px, py, pz) to be the point at infinity. Uses Jacobian
|
||||
* coordinates.
|
||||
*/
|
||||
mp_err
|
||||
GFp_ec_pt_set_inf_jac(mp_int *px, mp_int *py, mp_int *pz)
|
||||
{
|
||||
mp_zero(pz);
|
||||
return MP_OKAY;
|
||||
}
|
||||
|
||||
/* Computes R = P + Q where R is (rx, ry, rz), P is (px, py, pz) and
|
||||
* Q is (qx, qy, qz). Elliptic curve points P, Q, and R can all be
|
||||
* identical. Uses Jacobian coordinates.
|
||||
*
|
||||
* This routine implements Point Addition in the Jacobian Projective
|
||||
* space as described in the paper "Efficient elliptic curve exponentiation
|
||||
* using mixed coordinates", by H. Cohen, A Miyaji, T. Ono.
|
||||
*/
|
||||
mp_err
|
||||
GFp_ec_pt_add_jac(const mp_int *p, const mp_int *a, const mp_int *px,
|
||||
const mp_int *py, const mp_int *pz, const mp_int *qx,
|
||||
const mp_int *qy, const mp_int *qz, mp_int *rx, mp_int *ry, mp_int *rz)
|
||||
{
|
||||
mp_err err = MP_OKAY;
|
||||
mp_int n0, u1, u2, s1, s2, H, G;
|
||||
MP_DIGITS(&n0) = 0;
|
||||
MP_DIGITS(&u1) = 0;
|
||||
MP_DIGITS(&u2) = 0;
|
||||
MP_DIGITS(&s1) = 0;
|
||||
MP_DIGITS(&s2) = 0;
|
||||
MP_DIGITS(&H) = 0;
|
||||
MP_DIGITS(&G) = 0;
|
||||
CHECK_MPI_OK( mp_init(&n0) );
|
||||
CHECK_MPI_OK( mp_init(&u1) );
|
||||
CHECK_MPI_OK( mp_init(&u2) );
|
||||
CHECK_MPI_OK( mp_init(&s1) );
|
||||
CHECK_MPI_OK( mp_init(&s2) );
|
||||
CHECK_MPI_OK( mp_init(&H) );
|
||||
CHECK_MPI_OK( mp_init(&G) );
|
||||
|
||||
/* Use point double if pointers are equal. */
|
||||
if ((px == qx) && (py == qy) && (pz == qz)) {
|
||||
err = GFp_ec_pt_dbl_jac(p, a, px, py, pz, rx, ry, rz);
|
||||
goto cleanup;
|
||||
}
|
||||
|
||||
/* If either P or Q is the point at infinity, then return
|
||||
* the other point
|
||||
*/
|
||||
if (GFp_ec_pt_is_inf_jac(px, py, pz) == MP_YES) {
|
||||
CHECK_MPI_OK( mp_copy(qx, rx) );
|
||||
CHECK_MPI_OK( mp_copy(qy, ry) );
|
||||
CHECK_MPI_OK( mp_copy(qz, rz) );
|
||||
goto cleanup;
|
||||
}
|
||||
if (GFp_ec_pt_is_inf_jac(qx, qy, qz) == MP_YES) {
|
||||
CHECK_MPI_OK( mp_copy(px, rx) );
|
||||
CHECK_MPI_OK( mp_copy(py, ry) );
|
||||
CHECK_MPI_OK( mp_copy(pz, rz) );
|
||||
goto cleanup;
|
||||
}
|
||||
|
||||
/* Compute u1 = px * qz^2, s1 = py * qz^3 */
|
||||
if (mp_cmp_d(qz, 1) == 0) {
|
||||
CHECK_MPI_OK( mp_copy(px, &u1) );
|
||||
CHECK_MPI_OK( mp_copy(py, &s1) );
|
||||
} else {
|
||||
CHECK_MPI_OK( mp_sqrmod(qz, p, &n0) );
|
||||
CHECK_MPI_OK( mp_mulmod(px, &n0, p, &u1) );
|
||||
CHECK_MPI_OK( mp_mulmod(&n0, qz, p, &n0) );
|
||||
CHECK_MPI_OK( mp_mulmod(py, &n0, p, &s1) );
|
||||
}
|
||||
|
||||
/* Compute u2 = qx * pz^2, s2 = qy * pz^3 */
|
||||
if (mp_cmp_d(pz, 1) == 0) {
|
||||
CHECK_MPI_OK( mp_copy(qx, &u2) );
|
||||
CHECK_MPI_OK( mp_copy(qy, &s2) );
|
||||
} else {
|
||||
CHECK_MPI_OK( mp_sqrmod(pz, p, &n0) );
|
||||
CHECK_MPI_OK( mp_mulmod(qx, &n0, p, &u2) );
|
||||
CHECK_MPI_OK( mp_mulmod(&n0, pz, p, &n0) );
|
||||
CHECK_MPI_OK( mp_mulmod(qy, &n0, p, &s2) );
|
||||
}
|
||||
|
||||
/* Compute H = u2 - u1 ; G = s2 - s1 */
|
||||
CHECK_MPI_OK( mp_submod(&u2, &u1, p, &H) );
|
||||
CHECK_MPI_OK( mp_submod(&s2, &s1, p, &G) );
|
||||
|
||||
if (mp_cmp_z(&H) == 0) {
|
||||
if (mp_cmp_z(&G) == 0) {
|
||||
/* P = Q; double */
|
||||
err = GFp_ec_pt_dbl_jac(p, a, px, py, pz,
|
||||
rx, ry, rz);
|
||||
goto cleanup;
|
||||
} else {
|
||||
/* P = -Q; return point at infinity */
|
||||
CHECK_MPI_OK( GFp_ec_pt_set_inf_jac(rx, ry, rz) );
|
||||
goto cleanup;
|
||||
}
|
||||
}
|
||||
|
||||
/* rz = pz * qz * H */
|
||||
if (mp_cmp_d(pz, 1) == 0) {
|
||||
if (mp_cmp_d(qz, 1) == 0) {
|
||||
/* if pz == qz == 1, then rz = H */
|
||||
CHECK_MPI_OK( mp_copy(&H, rz) );
|
||||
} else {
|
||||
CHECK_MPI_OK( mp_mulmod(qz, &H, p, rz) );
|
||||
}
|
||||
} else {
|
||||
if (mp_cmp_d(qz, 1) == 0) {
|
||||
CHECK_MPI_OK( mp_mulmod(pz, &H, p, rz) );
|
||||
} else {
|
||||
CHECK_MPI_OK( mp_mulmod(pz, qz, p, &n0) );
|
||||
CHECK_MPI_OK( mp_mulmod(&n0, &H, p, rz) );
|
||||
}
|
||||
}
|
||||
|
||||
/* rx = G^2 - H^3 - 2 * u1 * H^2 */
|
||||
CHECK_MPI_OK( mp_sqrmod(&G, p, rx) );
|
||||
CHECK_MPI_OK( mp_sqrmod(&H, p, &n0) );
|
||||
CHECK_MPI_OK( mp_mulmod(&n0, &u1, p, &u1) );
|
||||
CHECK_MPI_OK( mp_addmod(&u1, &u1, p, &u2) );
|
||||
CHECK_MPI_OK( mp_mulmod(&H, &n0, p, &H) );
|
||||
CHECK_MPI_OK( mp_submod(rx, &H, p, rx) );
|
||||
CHECK_MPI_OK( mp_submod(rx, &u2, p, rx) );
|
||||
|
||||
/* ry = - s1 * H^3 + G * (u1 * H^2 - rx) */
|
||||
/* (formula based on values of variables before block above) */
|
||||
CHECK_MPI_OK( mp_submod(&u1, rx, p, &u1) );
|
||||
CHECK_MPI_OK( mp_mulmod(&G, &u1, p, ry) );
|
||||
CHECK_MPI_OK( mp_mulmod(&s1, &H, p, &s1) );
|
||||
CHECK_MPI_OK( mp_submod(ry, &s1, p, ry) );
|
||||
|
||||
cleanup:
|
||||
mp_clear(&n0);
|
||||
mp_clear(&u1);
|
||||
mp_clear(&u2);
|
||||
mp_clear(&s1);
|
||||
mp_clear(&s2);
|
||||
mp_clear(&H);
|
||||
mp_clear(&G);
|
||||
return err;
|
||||
}
|
||||
|
||||
/* Computes R = 2P. Elliptic curve points P and R can be identical. Uses
|
||||
* Jacobian coordinates.
|
||||
*
|
||||
* This routine implements Point Doubling in the Jacobian Projective
|
||||
* space as described in the paper "Efficient elliptic curve exponentiation
|
||||
* using mixed coordinates", by H. Cohen, A Miyaji, T. Ono.
|
||||
*/
|
||||
mp_err
|
||||
GFp_ec_pt_dbl_jac(const mp_int *p, const mp_int *a, const mp_int *px,
|
||||
const mp_int *py, const mp_int *pz, mp_int *rx, mp_int *ry, mp_int *rz)
|
||||
{
|
||||
mp_err err = MP_OKAY;
|
||||
mp_int t0, t1, M, S;
|
||||
MP_DIGITS(&t0) = 0;
|
||||
MP_DIGITS(&t1) = 0;
|
||||
MP_DIGITS(&M) = 0;
|
||||
MP_DIGITS(&S) = 0;
|
||||
CHECK_MPI_OK( mp_init(&t0) );
|
||||
CHECK_MPI_OK( mp_init(&t1) );
|
||||
CHECK_MPI_OK( mp_init(&M) );
|
||||
CHECK_MPI_OK( mp_init(&S) );
|
||||
|
||||
if (GFp_ec_pt_is_inf_jac(px, py, pz) == MP_YES) {
|
||||
CHECK_MPI_OK( GFp_ec_pt_set_inf_jac(rx, ry, rz) );
|
||||
goto cleanup;
|
||||
}
|
||||
|
||||
if (mp_cmp_d(pz, 1) == 0) {
|
||||
/* M = 3 * px^2 + a */
|
||||
CHECK_MPI_OK( mp_sqrmod(px, p, &t0) );
|
||||
CHECK_MPI_OK( mp_addmod(&t0, &t0, p, &M) );
|
||||
CHECK_MPI_OK( mp_addmod(&t0, &M, p, &t0) );
|
||||
CHECK_MPI_OK( mp_addmod(&t0, a, p, &M) );
|
||||
} else if (mp_cmp_int(a, -3) == 0) {
|
||||
/* M = 3 * (px + pz^2) * (px - pz) */
|
||||
CHECK_MPI_OK( mp_sqrmod(pz, p, &M) );
|
||||
CHECK_MPI_OK( mp_addmod(px, &M, p, &t0) );
|
||||
CHECK_MPI_OK( mp_submod(px, &M, p, &t1) );
|
||||
CHECK_MPI_OK( mp_mulmod(&t0, &t1, p, &M) );
|
||||
CHECK_MPI_OK( mp_addmod(&M, &M, p, &t0) );
|
||||
CHECK_MPI_OK( mp_addmod(&t0, &M, p, &M) );
|
||||
} else {
|
||||
CHECK_MPI_OK( mp_sqrmod(px, p, &t0) );
|
||||
CHECK_MPI_OK( mp_addmod(&t0, &t0, p, &M) );
|
||||
CHECK_MPI_OK( mp_addmod(&t0, &M, p, &t0) );
|
||||
CHECK_MPI_OK( mp_sqrmod(pz, p, &M) );
|
||||
CHECK_MPI_OK( mp_sqrmod(&M, p, &M) );
|
||||
CHECK_MPI_OK( mp_mulmod(&M, a, p, &M) );
|
||||
CHECK_MPI_OK( mp_addmod(&M, &t0, p, &M) );
|
||||
}
|
||||
|
||||
/* rz = 2 * py * pz */
|
||||
if (mp_cmp_d(pz, 1) == 0) {
|
||||
CHECK_MPI_OK( mp_addmod(py, py, p, rz) );
|
||||
CHECK_MPI_OK( mp_sqrmod(rz, p, &t0) );
|
||||
} else {
|
||||
CHECK_MPI_OK( mp_addmod(py, py, p, &t0) );
|
||||
CHECK_MPI_OK( mp_mulmod(&t0, pz, p, rz) );
|
||||
CHECK_MPI_OK( mp_sqrmod(&t0, p, &t0) );
|
||||
}
|
||||
|
||||
/* S = 4 * px * py^2 = pz * (2 * py)^2 */
|
||||
CHECK_MPI_OK( mp_mulmod(px, &t0, p, &S) );
|
||||
|
||||
/* rx = M^2 - 2 * S */
|
||||
CHECK_MPI_OK( mp_addmod(&S, &S, p, &t1) );
|
||||
CHECK_MPI_OK( mp_sqrmod(&M, p, rx) );
|
||||
CHECK_MPI_OK( mp_submod(rx, &t1, p, rx) );
|
||||
|
||||
/* ry = M * (S - rx) - 8 * py^4 */
|
||||
CHECK_MPI_OK( mp_sqrmod(&t0, p, &t1) );
|
||||
if (mp_isodd(&t1)) {
|
||||
CHECK_MPI_OK( mp_add(&t1, p, &t1) );
|
||||
}
|
||||
CHECK_MPI_OK( mp_div_2(&t1, &t1) );
|
||||
CHECK_MPI_OK( mp_submod(&S, rx, p, &S) );
|
||||
CHECK_MPI_OK( mp_mulmod(&M, &S, p, &M) );
|
||||
CHECK_MPI_OK( mp_submod(&M, &t1, p, ry) );
|
||||
|
||||
cleanup:
|
||||
mp_clear(&t0);
|
||||
mp_clear(&t1);
|
||||
mp_clear(&M);
|
||||
mp_clear(&S);
|
||||
return err;
|
||||
}
|
||||
|
||||
/* Computes R = nP where R is (rx, ry) and P is (px, py). The parameters
|
||||
* a, b and p are the elliptic curve coefficients and the prime that
|
||||
* determines the field GFp. Elliptic curve points P and R can be
|
||||
* identical. Uses Jacobian coordinates.
|
||||
*/
|
||||
mp_err
|
||||
GFp_ec_pt_mul_jac(const mp_int *p, const mp_int *a, const mp_int *b,
|
||||
const mp_int *px, const mp_int *py, const mp_int *n,
|
||||
mp_int *rx, mp_int *ry)
|
||||
{
|
||||
mp_err err = MP_OKAY;
|
||||
mp_int k, qx, qy, qz, sx, sy, sz;
|
||||
int i, l;
|
||||
|
||||
MP_DIGITS(&k) = 0;
|
||||
MP_DIGITS(&qx) = 0;
|
||||
MP_DIGITS(&qy) = 0;
|
||||
MP_DIGITS(&qz) = 0;
|
||||
MP_DIGITS(&sx) = 0;
|
||||
MP_DIGITS(&sy) = 0;
|
||||
MP_DIGITS(&sz) = 0;
|
||||
CHECK_MPI_OK( mp_init(&k) );
|
||||
CHECK_MPI_OK( mp_init(&qx) );
|
||||
CHECK_MPI_OK( mp_init(&qy) );
|
||||
CHECK_MPI_OK( mp_init(&qz) );
|
||||
CHECK_MPI_OK( mp_init(&sx) );
|
||||
CHECK_MPI_OK( mp_init(&sy) );
|
||||
CHECK_MPI_OK( mp_init(&sz) );
|
||||
|
||||
/* if n = 0 then r = inf */
|
||||
if (mp_cmp_z(n) == 0) {
|
||||
mp_zero(rx);
|
||||
mp_zero(ry);
|
||||
err = MP_OKAY;
|
||||
goto cleanup;
|
||||
/* if n < 0 then out of range error */
|
||||
} else if (mp_cmp_z(n) < 0) {
|
||||
err = MP_RANGE;
|
||||
goto cleanup;
|
||||
}
|
||||
/* Q = P, k = n */
|
||||
CHECK_MPI_OK( mp_copy(px, &qx) );
|
||||
CHECK_MPI_OK( mp_copy(py, &qy) );
|
||||
CHECK_MPI_OK( mp_set_int(&qz, 1) );
|
||||
CHECK_MPI_OK( mp_copy(n, &k) );
|
||||
|
||||
/* double and add method */
|
||||
l = mpl_significant_bits(&k) - 1;
|
||||
mp_zero(&sx);
|
||||
mp_zero(&sy);
|
||||
mp_zero(&sz);
|
||||
for (i = l; i >= 0; i--) {
|
||||
/* if k_i = 1, then S = S + Q */
|
||||
if (MP_GET_BIT(&k, i) != 0) {
|
||||
CHECK_MPI_OK( GFp_ec_pt_add_jac(p, a, &sx, &sy, &sz,
|
||||
&qx, &qy, &qz, &sx, &sy, &sz) );
|
||||
}
|
||||
if (i > 0) {
|
||||
/* S = 2S */
|
||||
CHECK_MPI_OK( GFp_ec_pt_dbl_jac(p, a, &sx, &sy, &sz,
|
||||
&sx, &sy, &sz) );
|
||||
}
|
||||
}
|
||||
|
||||
/* convert result S to affine coordinates */
|
||||
CHECK_MPI_OK( GFp_ec_pt_jac2aff(&sx, &sy, &sz, p, rx, ry) );
|
||||
|
||||
cleanup:
|
||||
mp_clear(&k);
|
||||
mp_clear(&qx);
|
||||
mp_clear(&qy);
|
||||
mp_clear(&qz);
|
||||
mp_clear(&sx);
|
||||
mp_clear(&sy);
|
||||
mp_clear(&sz);
|
||||
return err;
|
||||
}
|
||||
#endif /* NSS_ENABLE_ECC */
|
||||
126
mozilla/security/nss/lib/freebl/GFp_ecl.h
Normal file
126
mozilla/security/nss/lib/freebl/GFp_ecl.h
Normal file
@@ -0,0 +1,126 @@
|
||||
/*
|
||||
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
|
||||
*
|
||||
* The contents of this file are subject to the Mozilla Public License Version
|
||||
* 1.1 (the "License"); you may not use this file except in compliance with
|
||||
* the License. You may obtain a copy of the License at
|
||||
* http://www.mozilla.org/MPL/
|
||||
*
|
||||
* Software distributed under the License is distributed on an "AS IS" basis,
|
||||
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
|
||||
* for the specific language governing rights and limitations under the
|
||||
* License.
|
||||
*
|
||||
* The Original Code is the elliptic curve math library for prime
|
||||
* field curves.
|
||||
*
|
||||
* The Initial Developer of the Original Code is Sun Microsystems, Inc.
|
||||
* Portions created by Sun Microsystems, Inc. are Copyright (C) 2003
|
||||
* Sun Microsystems, Inc. All Rights Reserved.
|
||||
*
|
||||
* Contributor(s):
|
||||
* Douglas Stebila <douglas@stebila.ca>, Sun Microsystems Laboratories
|
||||
*
|
||||
* Alternatively, the contents of this file may be used under the terms of
|
||||
* either the GNU General Public License Version 2 or later (the "GPL"), or
|
||||
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
|
||||
* in which case the provisions of the GPL or the LGPL are applicable instead
|
||||
* of those above. If you wish to allow use of your version of this file only
|
||||
* under the terms of either the GPL or the LGPL, and not to allow others to
|
||||
* use your version of this file under the terms of the MPL, indicate your
|
||||
* decision by deleting the provisions above and replace them with the notice
|
||||
* and other provisions required by the GPL or the LGPL. If you do not delete
|
||||
* the provisions above, a recipient may use your version of this file under
|
||||
* the terms of any one of the MPL, the GPL or the LGPL.
|
||||
*
|
||||
*/
|
||||
|
||||
#ifndef __gfp_ecl_h_
|
||||
#define __gfp_ecl_h_
|
||||
#ifdef NSS_ENABLE_ECC
|
||||
|
||||
#include "secmpi.h"
|
||||
|
||||
/* Checks if point P(px, py) is at infinity. Uses affine coordinates. */
|
||||
extern mp_err GFp_ec_pt_is_inf_aff(const mp_int *px, const mp_int *py);
|
||||
|
||||
/* Sets P(px, py) to be the point at infinity. Uses affine coordinates. */
|
||||
extern mp_err GFp_ec_pt_set_inf_aff(mp_int *px, mp_int *py);
|
||||
|
||||
/* Computes R = P + Q where R is (rx, ry), P is (px, py) and Q is (qx, qy).
|
||||
* Uses affine coordinates.
|
||||
*/
|
||||
extern mp_err GFp_ec_pt_add_aff(const mp_int *p, const mp_int *a,
|
||||
const mp_int *px, const mp_int *py, const mp_int *qx, const mp_int *qy,
|
||||
mp_int *rx, mp_int *ry);
|
||||
|
||||
/* Computes R = P - Q. Uses affine coordinates. */
|
||||
extern mp_err GFp_ec_pt_sub_aff(const mp_int *p, const mp_int *a,
|
||||
const mp_int *px, const mp_int *py, const mp_int *qx, const mp_int *qy,
|
||||
mp_int *rx, mp_int *ry);
|
||||
|
||||
/* Computes R = 2P. Uses affine coordinates. */
|
||||
extern mp_err GFp_ec_pt_dbl_aff(const mp_int *p, const mp_int *a,
|
||||
const mp_int *px, const mp_int *py, mp_int *rx, mp_int *ry);
|
||||
|
||||
/* Computes R = nP where R is (rx, ry) and P is (px, py). The parameters
|
||||
* a, b and p are the elliptic curve coefficients and the prime that
|
||||
* determines the field GFp. Uses affine coordinates.
|
||||
*/
|
||||
extern mp_err GFp_ec_pt_mul_aff(const mp_int *p, const mp_int *a,
|
||||
const mp_int *b, const mp_int *px, const mp_int *py, const mp_int *n,
|
||||
mp_int *rx, mp_int *ry);
|
||||
|
||||
/* Converts a point P(px, py, pz) from Jacobian projective coordinates to
|
||||
* affine coordinates R(rx, ry).
|
||||
*/
|
||||
extern mp_err GFp_ec_pt_jac2aff(const mp_int *px, const mp_int *py,
|
||||
const mp_int *pz, const mp_int *p, mp_int *rx, mp_int *ry);
|
||||
|
||||
/* Checks if point P(px, py, pz) is at infinity. Uses Jacobian
|
||||
* coordinates.
|
||||
*/
|
||||
extern mp_err GFp_ec_pt_is_inf_jac(const mp_int *px, const mp_int *py,
|
||||
const mp_int *pz);
|
||||
|
||||
/* Sets P(px, py, pz) to be the point at infinity. Uses Jacobian
|
||||
* coordinates.
|
||||
*/
|
||||
extern mp_err GFp_ec_pt_set_inf_jac(mp_int *px, mp_int *py, mp_int *pz);
|
||||
|
||||
/* Computes R = P + Q where R is (rx, ry, rz), P is (px, py, pz) and
|
||||
* Q is (qx, qy, qz). Uses Jacobian coordinates.
|
||||
*/
|
||||
extern mp_err GFp_ec_pt_add_jac(const mp_int *p, const mp_int *a,
|
||||
const mp_int *px, const mp_int *py, const mp_int *pz,
|
||||
const mp_int *qx, const mp_int *qy, const mp_int *qz,
|
||||
mp_int *rx, mp_int *ry, mp_int *rz);
|
||||
|
||||
/* Computes R = 2P. Uses Jacobian coordinates. */
|
||||
extern mp_err GFp_ec_pt_dbl_jac(const mp_int *p, const mp_int *a,
|
||||
const mp_int *px, const mp_int *py, const mp_int *pz,
|
||||
mp_int *rx, mp_int *ry, mp_int *rz);
|
||||
|
||||
/* Computes R = nP where R is (rx, ry) and P is (px, py). The parameters
|
||||
* a, b and p are the elliptic curve coefficients and the prime that
|
||||
* determines the field GFp. Uses Jacobian coordinates.
|
||||
*/
|
||||
mp_err GFp_ec_pt_mul_jac(const mp_int *p, const mp_int *a, const mp_int *b,
|
||||
const mp_int *px, const mp_int *py, const mp_int *n,
|
||||
mp_int *rx, mp_int *ry);
|
||||
|
||||
#define GFp_ec_pt_is_inf(px, py) GFp_ec_pt_is_inf_aff((px), (py))
|
||||
#define GFp_ec_pt_add(p, a, px, py, qx, qy, rx, ry) \
|
||||
GFp_ec_pt_add_aff((p), (a), (px), (py), (qx), (qy), (rx), (ry))
|
||||
|
||||
#define GFp_ECL_JACOBIAN
|
||||
#ifdef GFp_ECL_AFFINE
|
||||
#define GFp_ec_pt_mul(p, a, b, px, py, n, rx, ry) \
|
||||
GFp_ec_pt_mul_aff((p), (a), (b), (px), (py), (n), (rx), (ry))
|
||||
#elif defined(GFp_ECL_JACOBIAN)
|
||||
#define GFp_ec_pt_mul(p, a, b, px, py, n, rx, ry) \
|
||||
GFp_ec_pt_mul_jac((p), (a), (b), (px), (py), (n), (rx), (ry))
|
||||
#endif /* GFp_ECL_AFFINE or GFp_ECL_JACOBIAN*/
|
||||
|
||||
#endif /* NSS_ENABLE_ECC */
|
||||
#endif /* __gfp_ecl_h_ */
|
||||
339
mozilla/security/nss/lib/freebl/Makefile
Normal file
339
mozilla/security/nss/lib/freebl/Makefile
Normal file
@@ -0,0 +1,339 @@
|
||||
#! gmake
|
||||
#
|
||||
# The contents of this file are subject to the Mozilla Public
|
||||
# License Version 1.1 (the "License"); you may not use this file
|
||||
# except in compliance with the License. You may obtain a copy of
|
||||
# the License at http://www.mozilla.org/MPL/
|
||||
#
|
||||
# Software distributed under the License is distributed on an "AS
|
||||
# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
|
||||
# implied. See the License for the specific language governing
|
||||
# rights and limitations under the License.
|
||||
#
|
||||
# The Original Code is the Netscape security libraries.
|
||||
#
|
||||
# The Initial Developer of the Original Code is Netscape
|
||||
# Communications Corporation. Portions created by Netscape are
|
||||
# Copyright (C) 1994-2000 Netscape Communications Corporation. All
|
||||
# Rights Reserved.
|
||||
#
|
||||
# Contributor(s):
|
||||
#
|
||||
# Alternatively, the contents of this file may be used under the
|
||||
# terms of the GNU General Public License Version 2 or later (the
|
||||
# "GPL"), in which case the provisions of the GPL are applicable
|
||||
# instead of those above. If you wish to allow use of your
|
||||
# version of this file only under the terms of the GPL and not to
|
||||
# allow others to use your version of this file under the MPL,
|
||||
# indicate your decision by deleting the provisions above and
|
||||
# replace them with the notice and other provisions required by
|
||||
# the GPL. If you do not delete the provisions above, a recipient
|
||||
# may use your version of this file under either the MPL or the
|
||||
# GPL.
|
||||
#
|
||||
|
||||
#######################################################################
|
||||
# (1) Include initial platform-independent assignments (MANDATORY). #
|
||||
#######################################################################
|
||||
|
||||
include manifest.mn
|
||||
|
||||
#######################################################################
|
||||
# (2) Include "global" configuration information. (OPTIONAL) #
|
||||
#######################################################################
|
||||
|
||||
include $(CORE_DEPTH)/coreconf/config.mk
|
||||
|
||||
#######################################################################
|
||||
# (3) Include "component" configuration information. (OPTIONAL) #
|
||||
#######################################################################
|
||||
|
||||
|
||||
|
||||
#######################################################################
|
||||
# (4) Include "local" platform-dependent assignments (OPTIONAL). #
|
||||
#######################################################################
|
||||
|
||||
-include config.mk
|
||||
|
||||
ifdef USE_64
|
||||
DEFINES += -DNSS_USE_64
|
||||
endif
|
||||
|
||||
ifdef USE_HYBRID
|
||||
DEFINES += -DNSS_USE_HYBRID
|
||||
endif
|
||||
|
||||
# des.c wants _X86_ defined for intel CPUs.
|
||||
# coreconf does this for windows, but not for Linux, FreeBSD, etc.
|
||||
ifeq ($(CPU_ARCH),x86)
|
||||
ifneq (,$(filter-out WIN%,$(OS_TARGET)))
|
||||
OS_REL_CFLAGS += -D_X86_
|
||||
endif
|
||||
endif
|
||||
|
||||
ifeq ($(OS_TARGET),OSF1)
|
||||
DEFINES += -DMP_ASSEMBLY_MULTIPLY -DMP_NO_MP_WORD
|
||||
MPI_SRCS += mpvalpha.c
|
||||
endif
|
||||
|
||||
ifeq (,$(filter-out WINNT WIN95,$(OS_TARGET))) #omits WIN16 and WINCE
|
||||
ifdef NS_USE_GCC
|
||||
# Ideally, we want to use assembler
|
||||
# ASFILES = mpi_x86.s
|
||||
# DEFINES += -DMP_ASSEMBLY_MULTIPLY -DMP_ASSEMBLY_SQUARE \
|
||||
# -DMP_ASSEMBLY_DIV_2DX1D
|
||||
# but we haven't figured out how to make it work, so we are not
|
||||
# using assembler right now.
|
||||
ASFILES =
|
||||
DEFINES += -DMP_NO_MP_WORD -DMP_USE_UINT_DIGIT
|
||||
else
|
||||
ASFILES = mpi_x86.asm
|
||||
DEFINES += -DMP_ASSEMBLY_MULTIPLY -DMP_ASSEMBLY_SQUARE -DMP_ASSEMBLY_DIV_2DX1D
|
||||
endif
|
||||
ifdef BUILD_OPT
|
||||
ifndef NS_USE_GCC
|
||||
OPTIMIZER += -Ox # maximum optimization for freebl
|
||||
endif
|
||||
endif
|
||||
endif
|
||||
|
||||
ifeq ($(OS_TARGET),WINCE)
|
||||
DEFINES += -DMP_ARGCHK=0 # no assert in WinCE
|
||||
DEFINES += -DSHA_NO_LONG_LONG # avoid 64-bit arithmetic in SHA512
|
||||
endif
|
||||
|
||||
ifdef XP_OS2_VACPP
|
||||
ASFILES = mpi_x86.asm
|
||||
DEFINES += -DMP_ASSEMBLY_MULTIPLY -DMP_ASSEMBLY_SQUARE -DMP_ASSEMBLY_DIV_2DX1D -DMP_USE_UINT_DIGIT -DMP_NO_MP_WORD
|
||||
endif
|
||||
|
||||
ifeq ($(OS_TARGET),IRIX)
|
||||
ifeq ($(USE_N32),1)
|
||||
ASFILES = mpi_mips.s
|
||||
ifeq ($(NS_USE_GCC),1)
|
||||
ASFLAGS = -Wp,-P -Wp,-traditional -O -mips3
|
||||
else
|
||||
ASFLAGS = -O -OPT:Olimit=4000 -dollar -fullwarn -xansi -n32 -mips3
|
||||
endif
|
||||
DEFINES += -DMP_ASSEMBLY_MULTIPLY -DMP_ASSEMBLY_SQUARE
|
||||
DEFINES += -DMP_USE_UINT_DIGIT
|
||||
else
|
||||
endif
|
||||
endif
|
||||
|
||||
ifeq ($(OS_TARGET),Linux)
|
||||
ifeq ($(CPU_ARCH),x86)
|
||||
ASFILES = mpi_x86.s
|
||||
DEFINES += -DMP_ASSEMBLY_MULTIPLY -DMP_ASSEMBLY_SQUARE -DMP_ASSEMBLY_DIV_2DX1D
|
||||
endif
|
||||
endif
|
||||
|
||||
ifeq ($(OS_TARGET),AIX)
|
||||
DEFINES += -DMP_USE_UINT_DIGIT
|
||||
ifndef USE_64
|
||||
DEFINES += -DMP_NO_DIV_WORD -DMP_NO_ADD_WORD -DMP_NO_SUB_WORD
|
||||
endif
|
||||
endif
|
||||
|
||||
ifeq ($(OS_TARGET), HP-UX)
|
||||
ifneq ($(OS_TEST), ia64)
|
||||
MKSHLIB += +k +vshlibunsats -u FREEBL_GetVector +e FREEBL_GetVector
|
||||
ifndef FREEBL_EXTENDED_BUILD
|
||||
ifdef USE_PURE_32
|
||||
# build for DA1.1 (HP PA 1.1) pure 32 bit model
|
||||
DEFINES += -DMP_USE_UINT_DIGIT -DMP_NO_MP_WORD
|
||||
DEFINES += -DSHA_NO_LONG_LONG # avoid 64-bit arithmetic in SHA512
|
||||
else
|
||||
ifdef USE_64
|
||||
# this builds for DA2.0W (HP PA 2.0 Wide), the LP64 ABI, using 32-bit digits
|
||||
MPI_SRCS += mpi_hp.c
|
||||
ASFILES += hpma512.s hppa20.s
|
||||
DEFINES += -DMP_ASSEMBLY_MULTIPLY -DMP_ASSEMBLY_SQUARE
|
||||
else
|
||||
# this builds for DA2.0 (HP PA 2.0 Narrow) hybrid model
|
||||
# (the 32-bit ABI with 64-bit registers) using 32-bit digits
|
||||
MPI_SRCS += mpi_hp.c
|
||||
ASFILES += hpma512.s hppa20.s
|
||||
DEFINES += -DMP_ASSEMBLY_MULTIPLY -DMP_ASSEMBLY_SQUARE
|
||||
# This is done in coreconf by defining USE_LONG_LONGS
|
||||
# OS_CFLAGS += -Aa +e +DA2.0 +DS2.0
|
||||
endif
|
||||
endif
|
||||
endif
|
||||
endif
|
||||
endif
|
||||
|
||||
# Note: -xarch=v8 or v9 is now done in coreconf
|
||||
ifeq ($(OS_TARGET),SunOS)
|
||||
ifeq ($(CPU_ARCH),sparc)
|
||||
ifndef NS_USE_GCC
|
||||
ifdef USE_HYBRID
|
||||
OS_CFLAGS += -xchip=ultra2
|
||||
endif
|
||||
endif
|
||||
ifeq (5.5.1,$(firstword $(sort 5.5.1 $(OS_RELEASE))))
|
||||
SYSV_SPARC = 1
|
||||
endif
|
||||
ifeq ($(SYSV_SPARC),1)
|
||||
SOLARIS_AS = /usr/ccs/bin/as
|
||||
ifdef NS_USE_GCC
|
||||
ifdef GCC_USE_GNU_LD
|
||||
MKSHLIB += -Wl,-Bsymbolic,-z,defs,-z,now,-z,text,--version-script,mapfile.Solaris
|
||||
else
|
||||
MKSHLIB += -Wl,-B,symbolic,-z,defs,-z,now,-z,text,-M,mapfile.Solaris
|
||||
endif
|
||||
else
|
||||
MKSHLIB += -B symbolic -z defs -z now -z text -M mapfile.Solaris
|
||||
endif
|
||||
ifdef USE_PURE_32
|
||||
# this builds for Sparc v8 pure 32-bit architecture
|
||||
DEFINES += -DMP_USE_LONG_LONG_MULTIPLY -DMP_USE_UINT_DIGIT -DMP_NO_MP_WORD
|
||||
DEFINES += -DSHA_NO_LONG_LONG # avoid 64-bit arithmetic in SHA512
|
||||
else
|
||||
ifdef USE_64
|
||||
# this builds for Sparc v9a pure 64-bit architecture
|
||||
MPI_SRCS += mpi_sparc.c
|
||||
ASFILES = mpv_sparcv9.s montmulfv9.s
|
||||
DEFINES += -DMP_ASSEMBLY_MULTIPLY -DMP_USING_MONT_MULF
|
||||
DEFINES += -DMP_USE_UINT_DIGIT
|
||||
# MPI_SRCS += mpv_sparc.c
|
||||
# removed -xdepend from the following line
|
||||
SOLARIS_FLAGS = -fast -xO5 -xrestrict=%all -xchip=ultra -xarch=v9a -KPIC -mt
|
||||
SOLARIS_AS_FLAGS = -xarch=v9a -K PIC
|
||||
else
|
||||
# this builds for Sparc v8+a hybrid architecture, 64-bit registers, 32-bit ABI
|
||||
MPI_SRCS += mpi_sparc.c
|
||||
ASFILES = mpv_sparcv8.s montmulfv8.s
|
||||
DEFINES += -DMP_NO_MP_WORD -DMP_ASSEMBLY_MULTIPLY -DMP_USING_MONT_MULF
|
||||
DEFINES += -DMP_USE_UINT_DIGIT
|
||||
SOLARIS_AS_FLAGS = -xarch=v8plusa -K PIC
|
||||
# ASM_SUFFIX = .S
|
||||
endif
|
||||
endif
|
||||
endif
|
||||
else
|
||||
# Solaris x86
|
||||
DEFINES += -D_X86_
|
||||
DEFINES += -DMP_USE_UINT_DIGIT
|
||||
DEFINES += -DMP_ASSEMBLY_MULTIPLY -DMP_ASSEMBLY_SQUARE -DMP_ASSEMBLY_DIV_2DX1D
|
||||
ASFILES = mpi_i86pc.s
|
||||
ifdef NS_USE_GCC
|
||||
LD = gcc
|
||||
AS = gcc
|
||||
ASFLAGS =
|
||||
endif
|
||||
|
||||
endif
|
||||
endif
|
||||
|
||||
$(OBJDIR)/sysrand$(OBJ_SUFFIX): sysrand.c unix_rand.c win_rand.c mac_rand.c os2_rand.c
|
||||
|
||||
#######################################################################
|
||||
# (5) Execute "global" rules. (OPTIONAL) #
|
||||
#######################################################################
|
||||
|
||||
include $(CORE_DEPTH)/coreconf/rules.mk
|
||||
|
||||
#######################################################################
|
||||
# (6) Execute "component" rules. (OPTIONAL) #
|
||||
#######################################################################
|
||||
|
||||
|
||||
|
||||
#######################################################################
|
||||
# (7) Execute "local" rules. (OPTIONAL). #
|
||||
#######################################################################
|
||||
|
||||
export:: private_export
|
||||
|
||||
rijndael_tables:
|
||||
$(CC) -o $(OBJDIR)/make_rijndael_tab rijndael_tables.c \
|
||||
$(DEFINES) $(INCLUDES) $(OBJDIR)/libfreebl.a
|
||||
$(OBJDIR)/make_rijndael_tab
|
||||
|
||||
ifdef MOZILLA_BSAFE_BUILD
|
||||
|
||||
private_export::
|
||||
ifeq (,$(filter-out WIN%,$(OS_TARGET)))
|
||||
rm -f $(DIST)/lib/bsafe$(BSAFEVER).lib
|
||||
endif
|
||||
$(NSINSTALL) -R $(BSAFEPATH) $(DIST)/lib
|
||||
endif
|
||||
|
||||
ifdef USE_PURE_32
|
||||
vpath %.h $(FREEBL_PARENT)/mpi:$(FREEBL_PARENT)
|
||||
vpath %.c $(FREEBL_PARENT)/mpi:$(FREEBL_PARENT)
|
||||
vpath %.S $(FREEBL_PARENT)/mpi:$(FREEBL_PARENT)
|
||||
vpath %.s $(FREEBL_PARENT)/mpi:$(FREEBL_PARENT)
|
||||
vpath %.asm $(FREEBL_PARENT)/mpi:$(FREEBL_PARENT)
|
||||
INCLUDES += -I$(FREEBL_PARENT) -I$(FREEBL_PARENT)/mpi
|
||||
else
|
||||
vpath %.h mpi
|
||||
vpath %.c mpi
|
||||
vpath %.S mpi
|
||||
vpath %.s mpi
|
||||
vpath %.asm mpi
|
||||
INCLUDES += -Impi
|
||||
endif
|
||||
|
||||
|
||||
DEFINES += -DMP_API_COMPATIBLE
|
||||
|
||||
MPI_USERS = dh.c pqg.c dsa.c rsa.c ec.c GFp_ecl.c
|
||||
|
||||
MPI_OBJS = $(addprefix $(OBJDIR)/$(PROG_PREFIX), $(MPI_SRCS:.c=$(OBJ_SUFFIX)))
|
||||
MPI_OBJS += $(addprefix $(OBJDIR)/$(PROG_PREFIX), $(MPI_USERS:.c=$(OBJ_SUFFIX)))
|
||||
|
||||
$(MPI_OBJS): $(MPI_HDRS)
|
||||
|
||||
$(OBJDIR)/$(PROG_PREFIX)mpprime$(OBJ_SUFFIX): primes.c
|
||||
|
||||
$(OBJDIR)/ldvector$(OBJ_SUFFIX) $(OBJDIR)/loader$(OBJ_SUFFIX) : loader.h
|
||||
|
||||
ifeq ($(SYSV_SPARC),1)
|
||||
|
||||
$(OBJDIR)/mpv_sparcv8.o $(OBJDIR)/montmulfv8.o : $(OBJDIR)/%.o : %.s
|
||||
@$(MAKE_OBJDIR)
|
||||
$(SOLARIS_AS) -o $@ $(SOLARIS_AS_FLAGS) $<
|
||||
|
||||
$(OBJDIR)/mpv_sparcv9.o $(OBJDIR)/montmulfv9.o : $(OBJDIR)/%.o : %.s
|
||||
@$(MAKE_OBJDIR)
|
||||
$(SOLARIS_AS) -o $@ $(SOLARIS_AS_FLAGS) $<
|
||||
|
||||
$(OBJDIR)/mpmontg.o: mpmontg.c montmulf.h
|
||||
|
||||
endif
|
||||
|
||||
ifdef FREEBL_EXTENDED_BUILD
|
||||
|
||||
PURE32DIR = $(OBJDIR)/$(OS_TARGET)pure32
|
||||
ALL_TRASH += $(PURE32DIR)
|
||||
|
||||
FILES2LN = \
|
||||
$(wildcard *.tab) \
|
||||
$(wildcard mapfile.*) \
|
||||
Makefile manifest.mn config.mk
|
||||
|
||||
LINKEDFILES = $(addprefix $(PURE32DIR)/, $(FILES2LN))
|
||||
|
||||
CDDIR := $(shell pwd)
|
||||
|
||||
$(PURE32DIR):
|
||||
-mkdir $(PURE32DIR)
|
||||
-ln -s $(CDDIR)/mpi $(PURE32DIR)
|
||||
|
||||
$(LINKEDFILES) : $(PURE32DIR)/% : %
|
||||
ln -s $(CDDIR)/$* $(PURE32DIR)
|
||||
|
||||
libs::
|
||||
$(MAKE) FREEBL_RECURSIVE_BUILD=1 USE_HYBRID=1 libs
|
||||
|
||||
libs:: $(PURE32DIR) $(LINKEDFILES)
|
||||
cd $(PURE32DIR) && $(MAKE) FREEBL_RECURSIVE_BUILD=1 USE_PURE_32=1 FREEBL_PARENT=$(CDDIR) CORE_DEPTH=$(CDDIR)/$(CORE_DEPTH) libs
|
||||
|
||||
release_md::
|
||||
$(MAKE) FREEBL_RECURSIVE_BUILD=1 USE_HYBRID=1 $@
|
||||
cd $(PURE32DIR) && $(MAKE) FREEBL_RECURSIVE_BUILD=1 USE_PURE_32=1 FREEBL_PARENT=$(CDDIR) CORE_DEPTH=$(CDDIR)/$(CORE_DEPTH) $@
|
||||
|
||||
endif
|
||||
383
mozilla/security/nss/lib/freebl/aeskeywrap.c
Normal file
383
mozilla/security/nss/lib/freebl/aeskeywrap.c
Normal file
@@ -0,0 +1,383 @@
|
||||
/*
|
||||
* aeskeywrap.c - implement AES Key Wrap algorithm from RFC 3394
|
||||
*
|
||||
* The contents of this file are subject to the Mozilla Public
|
||||
* License Version 1.1 (the "License"); you may not use this file
|
||||
* except in compliance with the License. You may obtain a copy of
|
||||
* the License at http://www.mozilla.org/MPL/
|
||||
*
|
||||
* Software distributed under the License is distributed on an "AS
|
||||
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
|
||||
* implied. See the License for the specific language governing
|
||||
* rights and limitations under the License.
|
||||
*
|
||||
* The Original Code is the Netscape security libraries.
|
||||
*
|
||||
* The Initial Developer of the Original Code is Netscape
|
||||
* Communications Corporation. Portions created by Netscape are
|
||||
* Copyright (C) 2002, 2003 Netscape Communications Corporation. All
|
||||
* Rights Reserved.
|
||||
*
|
||||
* Contributor(s):
|
||||
*
|
||||
* Alternatively, the contents of this file may be used under the
|
||||
* terms of the GNU General Public License Version 2 or later (the
|
||||
* "GPL"), in which case the provisions of the GPL are applicable
|
||||
* instead of those above. If you wish to allow use of your
|
||||
* version of this file only under the terms of the GPL and not to
|
||||
* allow others to use your version of this file under the MPL,
|
||||
* indicate your decision by deleting the provisions above and
|
||||
* replace them with the notice and other provisions required by
|
||||
* the GPL. If you do not delete the provisions above, a recipient
|
||||
* may use your version of this file under either the MPL or the
|
||||
* GPL.
|
||||
*
|
||||
* $Id: aeskeywrap.c,v 1.1 2003-01-14 22:16:04 nelsonb%netscape.com Exp $
|
||||
*/
|
||||
|
||||
#include "prcpucfg.h"
|
||||
#if defined(IS_LITTLE_ENDIAN) || defined(SHA_NO_LONG_LONG)
|
||||
#define BIG_ENDIAN_WITH_64_BIT_REGISTERS 0
|
||||
#else
|
||||
#define BIG_ENDIAN_WITH_64_BIT_REGISTERS 1
|
||||
#endif
|
||||
#include "prtypes.h" /* for PRUintXX */
|
||||
#include "secport.h" /* for PORT_XXX */
|
||||
#include "secerr.h"
|
||||
#include "blapi.h" /* for AES_ functions */
|
||||
|
||||
|
||||
struct AESKeyWrapContextStr {
|
||||
AESContext * aescx;
|
||||
unsigned char iv[AES_KEY_WRAP_IV_BYTES];
|
||||
};
|
||||
|
||||
/******************************************/
|
||||
/*
|
||||
** AES key wrap algorithm, RFC 3394
|
||||
*/
|
||||
|
||||
/*
|
||||
** Create a new AES context suitable for AES encryption/decryption.
|
||||
** "key" raw key data
|
||||
** "keylen" the number of bytes of key data (16, 24, or 32)
|
||||
*/
|
||||
extern AESKeyWrapContext *
|
||||
AESKeyWrap_CreateContext(const unsigned char *key, const unsigned char *iv,
|
||||
int encrypt, unsigned int keylen)
|
||||
{
|
||||
AESKeyWrapContext * cx = PORT_ZNew(AESKeyWrapContext);
|
||||
if (!cx)
|
||||
return NULL; /* error is already set */
|
||||
cx->aescx = AES_CreateContext(key, NULL, NSS_AES, encrypt, keylen,
|
||||
AES_BLOCK_SIZE);
|
||||
if (!cx->aescx) {
|
||||
PORT_Free(cx);
|
||||
return NULL; /* error should already be set */
|
||||
}
|
||||
if (iv) {
|
||||
memcpy(cx->iv, iv, AES_KEY_WRAP_IV_BYTES);
|
||||
} else {
|
||||
memset(cx->iv, 0xA6, AES_KEY_WRAP_IV_BYTES);
|
||||
}
|
||||
return cx;
|
||||
}
|
||||
|
||||
/*
|
||||
** Destroy a AES KeyWrap context.
|
||||
** "cx" the context
|
||||
** "freeit" if PR_TRUE then free the object as well as its sub-objects
|
||||
*/
|
||||
extern void
|
||||
AESKeyWrap_DestroyContext(AESKeyWrapContext *cx, PRBool freeit)
|
||||
{
|
||||
if (cx) {
|
||||
if (cx->aescx)
|
||||
AES_DestroyContext(cx->aescx, PR_TRUE);
|
||||
memset(cx, 0, sizeof *cx);
|
||||
if (freeit)
|
||||
PORT_Free(cx);
|
||||
}
|
||||
}
|
||||
|
||||
#if !BIG_ENDIAN_WITH_64_BIT_REGISTERS
|
||||
|
||||
/* The AES Key Wrap algorithm has 64-bit values that are ALWAYS big-endian
|
||||
** (Most significant byte first) in memory. The only ALU operations done
|
||||
** on them are increment, decrement, and XOR. So, on little-endian CPUs,
|
||||
** and on CPUs that lack 64-bit registers, these big-endian 64-bit operations
|
||||
** are simulated in the following code. This is thought to be faster and
|
||||
** simpler than trying to convert the data to little-endian and back.
|
||||
*/
|
||||
|
||||
/* A and T point to two 64-bit values stored most signficant byte first
|
||||
** (big endian). This function increments the 64-bit value T, and then
|
||||
** XORs it with A, changing A.
|
||||
*/
|
||||
static void
|
||||
increment_and_xor(unsigned char *A, unsigned char *T)
|
||||
{
|
||||
if (!++T[7])
|
||||
if (!++T[6])
|
||||
if (!++T[5])
|
||||
if (!++T[4])
|
||||
if (!++T[3])
|
||||
if (!++T[2])
|
||||
if (!++T[1])
|
||||
++T[0];
|
||||
|
||||
A[0] ^= T[0];
|
||||
A[1] ^= T[1];
|
||||
A[2] ^= T[2];
|
||||
A[3] ^= T[3];
|
||||
A[4] ^= T[4];
|
||||
A[5] ^= T[5];
|
||||
A[6] ^= T[6];
|
||||
A[7] ^= T[7];
|
||||
}
|
||||
|
||||
/* A and T point to two 64-bit values stored most signficant byte first
|
||||
** (big endian). This function XORs T with A, giving a new A, then
|
||||
** decrements the 64-bit value T.
|
||||
*/
|
||||
static void
|
||||
xor_and_decrement(unsigned char *A, unsigned char *T)
|
||||
{
|
||||
A[0] ^= T[0];
|
||||
A[1] ^= T[1];
|
||||
A[2] ^= T[2];
|
||||
A[3] ^= T[3];
|
||||
A[4] ^= T[4];
|
||||
A[5] ^= T[5];
|
||||
A[6] ^= T[6];
|
||||
A[7] ^= T[7];
|
||||
|
||||
if (!T[7]--)
|
||||
if (!T[6]--)
|
||||
if (!T[5]--)
|
||||
if (!T[4]--)
|
||||
if (!T[3]--)
|
||||
if (!T[2]--)
|
||||
if (!T[1]--)
|
||||
T[0]--;
|
||||
|
||||
}
|
||||
|
||||
/* Given an unsigned long t (in host byte order), store this value as a
|
||||
** 64-bit big-endian value (MSB first) in *pt.
|
||||
*/
|
||||
static void
|
||||
set_t(unsigned char *pt, unsigned long t)
|
||||
{
|
||||
pt[7] = (unsigned char)t; t >>= 8;
|
||||
pt[6] = (unsigned char)t; t >>= 8;
|
||||
pt[5] = (unsigned char)t; t >>= 8;
|
||||
pt[4] = (unsigned char)t; t >>= 8;
|
||||
pt[3] = (unsigned char)t; t >>= 8;
|
||||
pt[2] = (unsigned char)t; t >>= 8;
|
||||
pt[1] = (unsigned char)t; t >>= 8;
|
||||
pt[0] = (unsigned char)t;
|
||||
}
|
||||
|
||||
#endif
|
||||
|
||||
/*
|
||||
** Perform AES key wrap.
|
||||
** "cx" the context
|
||||
** "output" the output buffer to store the encrypted data.
|
||||
** "outputLen" how much data is stored in "output". Set by the routine
|
||||
** after some data is stored in output.
|
||||
** "maxOutputLen" the maximum amount of data that can ever be
|
||||
** stored in "output"
|
||||
** "input" the input data
|
||||
** "inputLen" the amount of input data
|
||||
*/
|
||||
extern SECStatus
|
||||
AESKeyWrap_Encrypt(AESKeyWrapContext *cx, unsigned char *output,
|
||||
unsigned int *pOutputLen, unsigned int maxOutputLen,
|
||||
const unsigned char *input, unsigned int inputLen)
|
||||
{
|
||||
PRUint64 * R = NULL;
|
||||
unsigned int nBlocks;
|
||||
unsigned int i, j;
|
||||
unsigned int aesLen = AES_BLOCK_SIZE;
|
||||
unsigned int outLen = inputLen + AES_KEY_WRAP_BLOCK_SIZE;
|
||||
SECStatus s = SECFailure;
|
||||
/* These PRUint64s are ALWAYS big endian, regardless of CPU orientation. */
|
||||
PRUint64 t;
|
||||
PRUint64 B[2];
|
||||
|
||||
#define A B[0]
|
||||
|
||||
/* Check args */
|
||||
if (!inputLen || 0 != inputLen % AES_KEY_WRAP_BLOCK_SIZE) {
|
||||
PORT_SetError(SEC_ERROR_INPUT_LEN);
|
||||
return s;
|
||||
}
|
||||
#ifdef maybe
|
||||
if (!output && pOutputLen) { /* caller is asking for output size */
|
||||
*pOutputLen = outLen;
|
||||
return SECSuccess;
|
||||
}
|
||||
#endif
|
||||
if (maxOutputLen < outLen) {
|
||||
PORT_SetError(SEC_ERROR_OUTPUT_LEN);
|
||||
return s;
|
||||
}
|
||||
if (cx == NULL || output == NULL || input == NULL) {
|
||||
PORT_SetError(SEC_ERROR_INVALID_ARGS);
|
||||
return s;
|
||||
}
|
||||
nBlocks = inputLen / AES_KEY_WRAP_BLOCK_SIZE;
|
||||
R = PORT_NewArray(PRUint64, nBlocks + 1);
|
||||
if (!R)
|
||||
return s; /* error is already set. */
|
||||
/*
|
||||
** 1) Initialize variables.
|
||||
*/
|
||||
memcpy(&A, cx->iv, AES_KEY_WRAP_IV_BYTES);
|
||||
memcpy(&R[1], input, inputLen);
|
||||
#if BIG_ENDIAN_WITH_64_BIT_REGISTERS
|
||||
t = 0;
|
||||
#else
|
||||
memset(&t, 0, sizeof t);
|
||||
#endif
|
||||
/*
|
||||
** 2) Calculate intermediate values.
|
||||
*/
|
||||
for (j = 0; j < 6; ++j) {
|
||||
for (i = 1; i <= nBlocks; ++i) {
|
||||
B[1] = R[i];
|
||||
s = AES_Encrypt(cx->aescx, (unsigned char *)B, &aesLen,
|
||||
sizeof B, (unsigned char *)B, sizeof B);
|
||||
if (s != SECSuccess)
|
||||
break;
|
||||
R[i] = B[1];
|
||||
/* here, increment t and XOR A with t (in big endian order); */
|
||||
#if BIG_ENDIAN_WITH_64_BIT_REGISTERS
|
||||
A ^= ++t;
|
||||
#else
|
||||
increment_and_xor((unsigned char *)&A, (unsigned char *)&t);
|
||||
#endif
|
||||
}
|
||||
}
|
||||
/*
|
||||
** 3) Output the results.
|
||||
*/
|
||||
if (s == SECSuccess) {
|
||||
R[0] = A;
|
||||
memcpy(output, &R[0], outLen);
|
||||
if (pOutputLen)
|
||||
*pOutputLen = outLen;
|
||||
} else if (pOutputLen) {
|
||||
*pOutputLen = 0;
|
||||
}
|
||||
PORT_ZFree(R, outLen);
|
||||
return s;
|
||||
}
|
||||
#undef A
|
||||
|
||||
/*
|
||||
** Perform AES key unwrap.
|
||||
** "cx" the context
|
||||
** "output" the output buffer to store the decrypted data.
|
||||
** "outputLen" how much data is stored in "output". Set by the routine
|
||||
** after some data is stored in output.
|
||||
** "maxOutputLen" the maximum amount of data that can ever be
|
||||
** stored in "output"
|
||||
** "input" the input data
|
||||
** "inputLen" the amount of input data
|
||||
*/
|
||||
extern SECStatus
|
||||
AESKeyWrap_Decrypt(AESKeyWrapContext *cx, unsigned char *output,
|
||||
unsigned int *pOutputLen, unsigned int maxOutputLen,
|
||||
const unsigned char *input, unsigned int inputLen)
|
||||
{
|
||||
PRUint64 * R = NULL;
|
||||
unsigned int nBlocks;
|
||||
unsigned int i, j;
|
||||
unsigned int aesLen = AES_BLOCK_SIZE;
|
||||
unsigned int outLen;
|
||||
SECStatus s = SECFailure;
|
||||
/* These PRUint64s are ALWAYS big endian, regardless of CPU orientation. */
|
||||
PRUint64 t;
|
||||
PRUint64 B[2];
|
||||
|
||||
#define A B[0]
|
||||
|
||||
/* Check args */
|
||||
if (inputLen < 3 * AES_KEY_WRAP_BLOCK_SIZE ||
|
||||
0 != inputLen % AES_KEY_WRAP_BLOCK_SIZE) {
|
||||
PORT_SetError(SEC_ERROR_INPUT_LEN);
|
||||
return s;
|
||||
}
|
||||
outLen = inputLen - AES_KEY_WRAP_BLOCK_SIZE;
|
||||
#ifdef maybe
|
||||
if (!output && pOutputLen) { /* caller is asking for output size */
|
||||
*pOutputLen = outLen;
|
||||
return SECSuccess;
|
||||
}
|
||||
#endif
|
||||
if (maxOutputLen < outLen) {
|
||||
PORT_SetError(SEC_ERROR_OUTPUT_LEN);
|
||||
return s;
|
||||
}
|
||||
if (cx == NULL || output == NULL || input == NULL) {
|
||||
PORT_SetError(SEC_ERROR_INVALID_ARGS);
|
||||
return s;
|
||||
}
|
||||
nBlocks = inputLen / AES_KEY_WRAP_BLOCK_SIZE;
|
||||
R = PORT_NewArray(PRUint64, nBlocks);
|
||||
if (!R)
|
||||
return s; /* error is already set. */
|
||||
nBlocks--;
|
||||
/*
|
||||
** 1) Initialize variables.
|
||||
*/
|
||||
memcpy(&R[0], input, inputLen);
|
||||
A = R[0];
|
||||
#if BIG_ENDIAN_WITH_64_BIT_REGISTERS
|
||||
t = 6UL * nBlocks;
|
||||
#else
|
||||
set_t((unsigned char *)&t, 6UL * nBlocks);
|
||||
#endif
|
||||
/*
|
||||
** 2) Calculate intermediate values.
|
||||
*/
|
||||
for (j = 0; j < 6; ++j) {
|
||||
for (i = nBlocks; i; --i) {
|
||||
/* here, XOR A with t (in big endian order) and decrement t; */
|
||||
#if BIG_ENDIAN_WITH_64_BIT_REGISTERS
|
||||
A ^= t--;
|
||||
#else
|
||||
xor_and_decrement((unsigned char *)&A, (unsigned char *)&t);
|
||||
#endif
|
||||
B[1] = R[i];
|
||||
s = AES_Decrypt(cx->aescx, (unsigned char *)B, &aesLen,
|
||||
sizeof B, (unsigned char *)B, sizeof B);
|
||||
if (s != SECSuccess)
|
||||
break;
|
||||
R[i] = B[1];
|
||||
}
|
||||
}
|
||||
/*
|
||||
** 3) Output the results.
|
||||
*/
|
||||
if (s == SECSuccess) {
|
||||
int bad = memcmp(&A, cx->iv, AES_KEY_WRAP_IV_BYTES);
|
||||
if (!bad) {
|
||||
memcpy(output, &R[1], outLen);
|
||||
if (pOutputLen)
|
||||
*pOutputLen = outLen;
|
||||
} else {
|
||||
PORT_SetError(SEC_ERROR_BAD_DATA);
|
||||
if (pOutputLen)
|
||||
*pOutputLen = 0;
|
||||
}
|
||||
} else if (pOutputLen) {
|
||||
*pOutputLen = 0;
|
||||
}
|
||||
PORT_ZFree(R, inputLen);
|
||||
return s;
|
||||
}
|
||||
#undef A
|
||||
493
mozilla/security/nss/lib/freebl/alg2268.c
Normal file
493
mozilla/security/nss/lib/freebl/alg2268.c
Normal file
@@ -0,0 +1,493 @@
|
||||
/*
|
||||
* alg2268.c - implementation of the algorithm in RFC 2268
|
||||
*
|
||||
* The contents of this file are subject to the Mozilla Public
|
||||
* License Version 1.1 (the "License"); you may not use this file
|
||||
* except in compliance with the License. You may obtain a copy of
|
||||
* the License at http://www.mozilla.org/MPL/
|
||||
*
|
||||
* Software distributed under the License is distributed on an "AS
|
||||
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
|
||||
* implied. See the License for the specific language governing
|
||||
* rights and limitations under the License.
|
||||
*
|
||||
* The Original Code is the Netscape security libraries.
|
||||
*
|
||||
* The Initial Developer of the Original Code is Netscape
|
||||
* Communications Corporation. Portions created by Netscape are
|
||||
* Copyright (C) 1994-2000 Netscape Communications Corporation. All
|
||||
* Rights Reserved.
|
||||
*
|
||||
* Contributor(s):
|
||||
*
|
||||
* Alternatively, the contents of this file may be used under the
|
||||
* terms of the GNU General Public License Version 2 or later (the
|
||||
* "GPL"), in which case the provisions of the GPL are applicable
|
||||
* instead of those above. If you wish to allow use of your
|
||||
* version of this file only under the terms of the GPL and not to
|
||||
* allow others to use your version of this file under the MPL,
|
||||
* indicate your decision by deleting the provisions above and
|
||||
* replace them with the notice and other provisions required by
|
||||
* the GPL. If you do not delete the provisions above, a recipient
|
||||
* may use your version of this file under either the MPL or the
|
||||
* GPL.
|
||||
*
|
||||
* $Id: alg2268.c,v 1.4 2002-11-16 06:09:57 nelsonb%netscape.com Exp $
|
||||
*/
|
||||
|
||||
|
||||
#include "blapi.h"
|
||||
#include "secerr.h"
|
||||
#ifdef XP_UNIX_XXX
|
||||
#include <stddef.h> /* for ptrdiff_t */
|
||||
#endif
|
||||
|
||||
/*
|
||||
** RC2 symmetric block cypher
|
||||
*/
|
||||
|
||||
typedef SECStatus (rc2Func)(RC2Context *cx, unsigned char *output,
|
||||
const unsigned char *input, unsigned int inputLen);
|
||||
|
||||
/* forward declarations */
|
||||
static rc2Func rc2_EncryptECB;
|
||||
static rc2Func rc2_DecryptECB;
|
||||
static rc2Func rc2_EncryptCBC;
|
||||
static rc2Func rc2_DecryptCBC;
|
||||
|
||||
typedef union {
|
||||
PRUint32 l[2];
|
||||
PRUint16 s[4];
|
||||
PRUint8 b[8];
|
||||
} RC2Block;
|
||||
|
||||
struct RC2ContextStr {
|
||||
union {
|
||||
PRUint8 Kb[128];
|
||||
PRUint16 Kw[64];
|
||||
} u;
|
||||
RC2Block iv;
|
||||
rc2Func *enc;
|
||||
rc2Func *dec;
|
||||
};
|
||||
|
||||
#define B u.Kb
|
||||
#define K u.Kw
|
||||
#define BYTESWAP(x) ((x) << 8 | (x) >> 8)
|
||||
#define SWAPK(i) cx->K[i] = (tmpS = cx->K[i], BYTESWAP(tmpS))
|
||||
#define RC2_BLOCK_SIZE 8
|
||||
|
||||
#define LOAD_HARD(R) \
|
||||
R[0] = (PRUint16)input[1] << 8 | input[0]; \
|
||||
R[1] = (PRUint16)input[3] << 8 | input[2]; \
|
||||
R[2] = (PRUint16)input[5] << 8 | input[4]; \
|
||||
R[3] = (PRUint16)input[7] << 8 | input[6];
|
||||
#define LOAD_EASY(R) \
|
||||
R[0] = ((PRUint16 *)input)[0]; \
|
||||
R[1] = ((PRUint16 *)input)[1]; \
|
||||
R[2] = ((PRUint16 *)input)[2]; \
|
||||
R[3] = ((PRUint16 *)input)[3];
|
||||
#define STORE_HARD(R) \
|
||||
output[0] = (PRUint8)(R[0]); output[1] = (PRUint8)(R[0] >> 8); \
|
||||
output[2] = (PRUint8)(R[1]); output[3] = (PRUint8)(R[1] >> 8); \
|
||||
output[4] = (PRUint8)(R[2]); output[5] = (PRUint8)(R[2] >> 8); \
|
||||
output[6] = (PRUint8)(R[3]); output[7] = (PRUint8)(R[3] >> 8);
|
||||
#define STORE_EASY(R) \
|
||||
((PRUint16 *)output)[0] = R[0]; \
|
||||
((PRUint16 *)output)[1] = R[1]; \
|
||||
((PRUint16 *)output)[2] = R[2]; \
|
||||
((PRUint16 *)output)[3] = R[3];
|
||||
|
||||
#if defined (_X86_)
|
||||
#define LOAD(R) LOAD_EASY(R)
|
||||
#define STORE(R) STORE_EASY(R)
|
||||
#elif !defined(IS_LITTLE_ENDIAN)
|
||||
#define LOAD(R) LOAD_HARD(R)
|
||||
#define STORE(R) STORE_HARD(R)
|
||||
#else
|
||||
#define LOAD(R) if ((ptrdiff_t)input & 1) { LOAD_HARD(R) } else { LOAD_EASY(R) }
|
||||
#define STORE(R) if ((ptrdiff_t)input & 1) { STORE_HARD(R) } else { STORE_EASY(R) }
|
||||
#endif
|
||||
|
||||
static const PRUint8 S[256] = {
|
||||
0331,0170,0371,0304,0031,0335,0265,0355,0050,0351,0375,0171,0112,0240,0330,0235,
|
||||
0306,0176,0067,0203,0053,0166,0123,0216,0142,0114,0144,0210,0104,0213,0373,0242,
|
||||
0027,0232,0131,0365,0207,0263,0117,0023,0141,0105,0155,0215,0011,0201,0175,0062,
|
||||
0275,0217,0100,0353,0206,0267,0173,0013,0360,0225,0041,0042,0134,0153,0116,0202,
|
||||
0124,0326,0145,0223,0316,0140,0262,0034,0163,0126,0300,0024,0247,0214,0361,0334,
|
||||
0022,0165,0312,0037,0073,0276,0344,0321,0102,0075,0324,0060,0243,0074,0266,0046,
|
||||
0157,0277,0016,0332,0106,0151,0007,0127,0047,0362,0035,0233,0274,0224,0103,0003,
|
||||
0370,0021,0307,0366,0220,0357,0076,0347,0006,0303,0325,0057,0310,0146,0036,0327,
|
||||
0010,0350,0352,0336,0200,0122,0356,0367,0204,0252,0162,0254,0065,0115,0152,0052,
|
||||
0226,0032,0322,0161,0132,0025,0111,0164,0113,0237,0320,0136,0004,0030,0244,0354,
|
||||
0302,0340,0101,0156,0017,0121,0313,0314,0044,0221,0257,0120,0241,0364,0160,0071,
|
||||
0231,0174,0072,0205,0043,0270,0264,0172,0374,0002,0066,0133,0045,0125,0227,0061,
|
||||
0055,0135,0372,0230,0343,0212,0222,0256,0005,0337,0051,0020,0147,0154,0272,0311,
|
||||
0323,0000,0346,0317,0341,0236,0250,0054,0143,0026,0001,0077,0130,0342,0211,0251,
|
||||
0015,0070,0064,0033,0253,0063,0377,0260,0273,0110,0014,0137,0271,0261,0315,0056,
|
||||
0305,0363,0333,0107,0345,0245,0234,0167,0012,0246,0040,0150,0376,0177,0301,0255
|
||||
};
|
||||
|
||||
/*
|
||||
** Create a new RC2 context suitable for RC2 encryption/decryption.
|
||||
** "key" raw key data
|
||||
** "len" the number of bytes of key data
|
||||
** "iv" is the CBC initialization vector (if mode is NSS_RC2_CBC)
|
||||
** "mode" one of NSS_RC2 or NSS_RC2_CBC
|
||||
** "effectiveKeyLen" in bytes, not bits.
|
||||
**
|
||||
** When mode is set to NSS_RC2_CBC the RC2 cipher is run in "cipher block
|
||||
** chaining" mode.
|
||||
*/
|
||||
RC2Context *
|
||||
RC2_CreateContext(const unsigned char *key, unsigned int len,
|
||||
const unsigned char *input, int mode, unsigned efLen8)
|
||||
{
|
||||
RC2Context *cx;
|
||||
PRUint8 *L,*L2;
|
||||
int i;
|
||||
#if !defined(IS_LITTLE_ENDIAN)
|
||||
PRUint16 tmpS;
|
||||
#endif
|
||||
PRUint8 tmpB;
|
||||
|
||||
if (!key || len == 0 || len > (sizeof cx->B) || efLen8 > (sizeof cx->B)) {
|
||||
return NULL;
|
||||
}
|
||||
if (mode == NSS_RC2) {
|
||||
/* groovy */
|
||||
} else if (mode == NSS_RC2_CBC) {
|
||||
if (!input) {
|
||||
return NULL; /* not groovy */
|
||||
}
|
||||
} else {
|
||||
return NULL;
|
||||
}
|
||||
|
||||
cx = PORT_ZNew(RC2Context);
|
||||
if (!cx)
|
||||
return cx;
|
||||
|
||||
if (mode == NSS_RC2_CBC) {
|
||||
cx->enc = & rc2_EncryptCBC;
|
||||
cx->dec = & rc2_DecryptCBC;
|
||||
LOAD(cx->iv.s);
|
||||
} else {
|
||||
cx->enc = & rc2_EncryptECB;
|
||||
cx->dec = & rc2_DecryptECB;
|
||||
}
|
||||
|
||||
/* Step 0. Copy key into table. */
|
||||
memcpy(cx->B, key, len);
|
||||
|
||||
/* Step 1. Compute all values to the right of the key. */
|
||||
L2 = cx->B;
|
||||
L = L2 + len;
|
||||
tmpB = L[-1];
|
||||
for (i = (sizeof cx->B) - len; i > 0; --i) {
|
||||
*L++ = tmpB = S[ (PRUint8)(tmpB + *L2++) ];
|
||||
}
|
||||
|
||||
/* step 2. Adjust left most byte of effective key. */
|
||||
i = (sizeof cx->B) - efLen8;
|
||||
L = cx->B + i;
|
||||
*L = tmpB = S[*L]; /* mask is always 0xff */
|
||||
|
||||
/* step 3. Recompute all values to the left of effective key. */
|
||||
L2 = --L + efLen8;
|
||||
while(L >= cx->B) {
|
||||
*L-- = tmpB = S[ tmpB ^ *L2-- ];
|
||||
}
|
||||
|
||||
#if !defined(IS_LITTLE_ENDIAN)
|
||||
for (i = 63; i >= 0; --i) {
|
||||
SWAPK(i); /* candidate for unrolling */
|
||||
}
|
||||
#endif
|
||||
return cx;
|
||||
}
|
||||
|
||||
/*
|
||||
** Destroy an RC2 encryption/decryption context.
|
||||
** "cx" the context
|
||||
** "freeit" if PR_TRUE then free the object as well as its sub-objects
|
||||
*/
|
||||
void
|
||||
RC2_DestroyContext(RC2Context *cx, PRBool freeit)
|
||||
{
|
||||
if (cx) {
|
||||
memset(cx, 0, sizeof *cx);
|
||||
if (freeit) {
|
||||
PORT_Free(cx);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#define ROL(x,k) (x << k | x >> (16-k))
|
||||
#define MIX(j) \
|
||||
R0 = R0 + cx->K[ 4*j+0] + (R3 & R2) + (~R3 & R1); R0 = ROL(R0,1);\
|
||||
R1 = R1 + cx->K[ 4*j+1] + (R0 & R3) + (~R0 & R2); R1 = ROL(R1,2);\
|
||||
R2 = R2 + cx->K[ 4*j+2] + (R1 & R0) + (~R1 & R3); R2 = ROL(R2,3);\
|
||||
R3 = R3 + cx->K[ 4*j+3] + (R2 & R1) + (~R2 & R0); R3 = ROL(R3,5)
|
||||
#define MASH \
|
||||
R0 = R0 + cx->K[R3 & 63];\
|
||||
R1 = R1 + cx->K[R0 & 63];\
|
||||
R2 = R2 + cx->K[R1 & 63];\
|
||||
R3 = R3 + cx->K[R2 & 63]
|
||||
|
||||
/* Encrypt one block */
|
||||
static void
|
||||
rc2_Encrypt1Block(RC2Context *cx, RC2Block *output, RC2Block *input)
|
||||
{
|
||||
register PRUint16 R0, R1, R2, R3;
|
||||
|
||||
/* step 1. Initialize input. */
|
||||
R0 = input->s[0];
|
||||
R1 = input->s[1];
|
||||
R2 = input->s[2];
|
||||
R3 = input->s[3];
|
||||
|
||||
/* step 2. Expand Key (already done, in context) */
|
||||
/* step 3. j = 0 */
|
||||
/* step 4. Perform 5 mixing rounds. */
|
||||
|
||||
MIX(0);
|
||||
MIX(1);
|
||||
MIX(2);
|
||||
MIX(3);
|
||||
MIX(4);
|
||||
|
||||
/* step 5. Perform 1 mashing round. */
|
||||
MASH;
|
||||
|
||||
/* step 6. Perform 6 mixing rounds. */
|
||||
|
||||
MIX(5);
|
||||
MIX(6);
|
||||
MIX(7);
|
||||
MIX(8);
|
||||
MIX(9);
|
||||
MIX(10);
|
||||
|
||||
/* step 7. Perform 1 mashing round. */
|
||||
MASH;
|
||||
|
||||
/* step 8. Perform 5 mixing rounds. */
|
||||
|
||||
MIX(11);
|
||||
MIX(12);
|
||||
MIX(13);
|
||||
MIX(14);
|
||||
MIX(15);
|
||||
|
||||
/* output results */
|
||||
output->s[0] = R0;
|
||||
output->s[1] = R1;
|
||||
output->s[2] = R2;
|
||||
output->s[3] = R3;
|
||||
}
|
||||
|
||||
#define ROR(x,k) (x >> k | x << (16-k))
|
||||
#define R_MIX(j) \
|
||||
R3 = ROR(R3,5); R3 = R3 - cx->K[ 4*j+3] - (R2 & R1) - (~R2 & R0); \
|
||||
R2 = ROR(R2,3); R2 = R2 - cx->K[ 4*j+2] - (R1 & R0) - (~R1 & R3); \
|
||||
R1 = ROR(R1,2); R1 = R1 - cx->K[ 4*j+1] - (R0 & R3) - (~R0 & R2); \
|
||||
R0 = ROR(R0,1); R0 = R0 - cx->K[ 4*j+0] - (R3 & R2) - (~R3 & R1)
|
||||
#define R_MASH \
|
||||
R3 = R3 - cx->K[R2 & 63];\
|
||||
R2 = R2 - cx->K[R1 & 63];\
|
||||
R1 = R1 - cx->K[R0 & 63];\
|
||||
R0 = R0 - cx->K[R3 & 63]
|
||||
|
||||
/* Encrypt one block */
|
||||
static void
|
||||
rc2_Decrypt1Block(RC2Context *cx, RC2Block *output, RC2Block *input)
|
||||
{
|
||||
register PRUint16 R0, R1, R2, R3;
|
||||
|
||||
/* step 1. Initialize input. */
|
||||
R0 = input->s[0];
|
||||
R1 = input->s[1];
|
||||
R2 = input->s[2];
|
||||
R3 = input->s[3];
|
||||
|
||||
/* step 2. Expand Key (already done, in context) */
|
||||
/* step 3. j = 63 */
|
||||
/* step 4. Perform 5 r_mixing rounds. */
|
||||
R_MIX(15);
|
||||
R_MIX(14);
|
||||
R_MIX(13);
|
||||
R_MIX(12);
|
||||
R_MIX(11);
|
||||
|
||||
/* step 5. Perform 1 r_mashing round. */
|
||||
R_MASH;
|
||||
|
||||
/* step 6. Perform 6 r_mixing rounds. */
|
||||
R_MIX(10);
|
||||
R_MIX(9);
|
||||
R_MIX(8);
|
||||
R_MIX(7);
|
||||
R_MIX(6);
|
||||
R_MIX(5);
|
||||
|
||||
/* step 7. Perform 1 r_mashing round. */
|
||||
R_MASH;
|
||||
|
||||
/* step 8. Perform 5 r_mixing rounds. */
|
||||
R_MIX(4);
|
||||
R_MIX(3);
|
||||
R_MIX(2);
|
||||
R_MIX(1);
|
||||
R_MIX(0);
|
||||
|
||||
/* output results */
|
||||
output->s[0] = R0;
|
||||
output->s[1] = R1;
|
||||
output->s[2] = R2;
|
||||
output->s[3] = R3;
|
||||
}
|
||||
|
||||
static SECStatus
|
||||
rc2_EncryptECB(RC2Context *cx, unsigned char *output,
|
||||
const unsigned char *input, unsigned int inputLen)
|
||||
{
|
||||
RC2Block iBlock;
|
||||
|
||||
while (inputLen > 0) {
|
||||
LOAD(iBlock.s)
|
||||
rc2_Encrypt1Block(cx, &iBlock, &iBlock);
|
||||
STORE(iBlock.s)
|
||||
output += RC2_BLOCK_SIZE;
|
||||
input += RC2_BLOCK_SIZE;
|
||||
inputLen -= RC2_BLOCK_SIZE;
|
||||
}
|
||||
return SECSuccess;
|
||||
}
|
||||
|
||||
static SECStatus
|
||||
rc2_DecryptECB(RC2Context *cx, unsigned char *output,
|
||||
const unsigned char *input, unsigned int inputLen)
|
||||
{
|
||||
RC2Block iBlock;
|
||||
|
||||
while (inputLen > 0) {
|
||||
LOAD(iBlock.s)
|
||||
rc2_Decrypt1Block(cx, &iBlock, &iBlock);
|
||||
STORE(iBlock.s)
|
||||
output += RC2_BLOCK_SIZE;
|
||||
input += RC2_BLOCK_SIZE;
|
||||
inputLen -= RC2_BLOCK_SIZE;
|
||||
}
|
||||
return SECSuccess;
|
||||
}
|
||||
|
||||
static SECStatus
|
||||
rc2_EncryptCBC(RC2Context *cx, unsigned char *output,
|
||||
const unsigned char *input, unsigned int inputLen)
|
||||
{
|
||||
RC2Block iBlock;
|
||||
|
||||
while (inputLen > 0) {
|
||||
|
||||
LOAD(iBlock.s)
|
||||
iBlock.l[0] ^= cx->iv.l[0];
|
||||
iBlock.l[1] ^= cx->iv.l[1];
|
||||
rc2_Encrypt1Block(cx, &iBlock, &iBlock);
|
||||
cx->iv = iBlock;
|
||||
STORE(iBlock.s)
|
||||
output += RC2_BLOCK_SIZE;
|
||||
input += RC2_BLOCK_SIZE;
|
||||
inputLen -= RC2_BLOCK_SIZE;
|
||||
}
|
||||
return SECSuccess;
|
||||
}
|
||||
|
||||
static SECStatus
|
||||
rc2_DecryptCBC(RC2Context *cx, unsigned char *output,
|
||||
const unsigned char *input, unsigned int inputLen)
|
||||
{
|
||||
RC2Block iBlock;
|
||||
RC2Block oBlock;
|
||||
|
||||
while (inputLen > 0) {
|
||||
LOAD(iBlock.s)
|
||||
rc2_Decrypt1Block(cx, &oBlock, &iBlock);
|
||||
oBlock.l[0] ^= cx->iv.l[0];
|
||||
oBlock.l[1] ^= cx->iv.l[1];
|
||||
cx->iv = iBlock;
|
||||
STORE(oBlock.s)
|
||||
output += RC2_BLOCK_SIZE;
|
||||
input += RC2_BLOCK_SIZE;
|
||||
inputLen -= RC2_BLOCK_SIZE;
|
||||
}
|
||||
return SECSuccess;
|
||||
}
|
||||
|
||||
|
||||
/*
|
||||
** Perform RC2 encryption.
|
||||
** "cx" the context
|
||||
** "output" the output buffer to store the encrypted data.
|
||||
** "outputLen" how much data is stored in "output". Set by the routine
|
||||
** after some data is stored in output.
|
||||
** "maxOutputLen" the maximum amount of data that can ever be
|
||||
** stored in "output"
|
||||
** "input" the input data
|
||||
** "inputLen" the amount of input data
|
||||
*/
|
||||
SECStatus RC2_Encrypt(RC2Context *cx, unsigned char *output,
|
||||
unsigned int *outputLen, unsigned int maxOutputLen,
|
||||
const unsigned char *input, unsigned int inputLen)
|
||||
{
|
||||
SECStatus rv = SECSuccess;
|
||||
if (inputLen) {
|
||||
if (inputLen % RC2_BLOCK_SIZE) {
|
||||
PORT_SetError(SEC_ERROR_INPUT_LEN);
|
||||
return SECFailure;
|
||||
}
|
||||
if (maxOutputLen < inputLen) {
|
||||
PORT_SetError(SEC_ERROR_OUTPUT_LEN);
|
||||
return SECFailure;
|
||||
}
|
||||
rv = (*cx->enc)(cx, output, input, inputLen);
|
||||
}
|
||||
if (rv == SECSuccess) {
|
||||
*outputLen = inputLen;
|
||||
}
|
||||
return rv;
|
||||
}
|
||||
|
||||
/*
|
||||
** Perform RC2 decryption.
|
||||
** "cx" the context
|
||||
** "output" the output buffer to store the decrypted data.
|
||||
** "outputLen" how much data is stored in "output". Set by the routine
|
||||
** after some data is stored in output.
|
||||
** "maxOutputLen" the maximum amount of data that can ever be
|
||||
** stored in "output"
|
||||
** "input" the input data
|
||||
** "inputLen" the amount of input data
|
||||
*/
|
||||
SECStatus RC2_Decrypt(RC2Context *cx, unsigned char *output,
|
||||
unsigned int *outputLen, unsigned int maxOutputLen,
|
||||
const unsigned char *input, unsigned int inputLen)
|
||||
{
|
||||
SECStatus rv = SECSuccess;
|
||||
if (inputLen) {
|
||||
if (inputLen % RC2_BLOCK_SIZE) {
|
||||
PORT_SetError(SEC_ERROR_INPUT_LEN);
|
||||
return SECFailure;
|
||||
}
|
||||
if (maxOutputLen < inputLen) {
|
||||
PORT_SetError(SEC_ERROR_OUTPUT_LEN);
|
||||
return SECFailure;
|
||||
}
|
||||
rv = (*cx->dec)(cx, output, input, inputLen);
|
||||
}
|
||||
if (rv == SECSuccess) {
|
||||
*outputLen = inputLen;
|
||||
}
|
||||
return rv;
|
||||
}
|
||||
|
||||
114
mozilla/security/nss/lib/freebl/arcfive.c
Normal file
114
mozilla/security/nss/lib/freebl/arcfive.c
Normal file
@@ -0,0 +1,114 @@
|
||||
/*
|
||||
* arcfive.c - stubs for RC5 - NOT a working implementation!
|
||||
*
|
||||
* The contents of this file are subject to the Mozilla Public
|
||||
* License Version 1.1 (the "License"); you may not use this file
|
||||
* except in compliance with the License. You may obtain a copy of
|
||||
* the License at http://www.mozilla.org/MPL/
|
||||
*
|
||||
* Software distributed under the License is distributed on an "AS
|
||||
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
|
||||
* implied. See the License for the specific language governing
|
||||
* rights and limitations under the License.
|
||||
*
|
||||
* The Original Code is the Netscape security libraries.
|
||||
*
|
||||
* The Initial Developer of the Original Code is Netscape
|
||||
* Communications Corporation. Portions created by Netscape are
|
||||
* Copyright (C) 2000 Netscape Communications Corporation. All
|
||||
* Rights Reserved.
|
||||
*
|
||||
* Contributor(s):
|
||||
*
|
||||
* Alternatively, the contents of this file may be used under the
|
||||
* terms of the GNU General Public License Version 2 or later (the
|
||||
* "GPL"), in which case the provisions of the GPL are applicable
|
||||
* instead of those above. If you wish to allow use of your
|
||||
* version of this file only under the terms of the GPL and not to
|
||||
* allow others to use your version of this file under the MPL,
|
||||
* indicate your decision by deleting the provisions above and
|
||||
* replace them with the notice and other provisions required by
|
||||
* the GPL. If you do not delete the provisions above, a recipient
|
||||
* may use your version of this file under either the MPL or the
|
||||
* GPL.
|
||||
*
|
||||
* $Id: arcfive.c,v 1.3 2002-11-16 06:09:57 nelsonb%netscape.com Exp $
|
||||
*/
|
||||
|
||||
#include "blapi.h"
|
||||
#include "prerror.h"
|
||||
|
||||
/******************************************/
|
||||
/*
|
||||
** RC5 symmetric block cypher -- 64-bit block size
|
||||
*/
|
||||
|
||||
/*
|
||||
** Create a new RC5 context suitable for RC5 encryption/decryption.
|
||||
** "key" raw key data
|
||||
** "len" the number of bytes of key data
|
||||
** "iv" is the CBC initialization vector (if mode is NSS_RC5_CBC)
|
||||
** "mode" one of NSS_RC5 or NSS_RC5_CBC
|
||||
**
|
||||
** When mode is set to NSS_RC5_CBC the RC5 cipher is run in "cipher block
|
||||
** chaining" mode.
|
||||
*/
|
||||
RC5Context *
|
||||
RC5_CreateContext(const SECItem *key, unsigned int rounds,
|
||||
unsigned int wordSize, const unsigned char *iv, int mode)
|
||||
{
|
||||
PORT_SetError(PR_NOT_IMPLEMENTED_ERROR);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
/*
|
||||
** Destroy an RC5 encryption/decryption context.
|
||||
** "cx" the context
|
||||
** "freeit" if PR_TRUE then free the object as well as its sub-objects
|
||||
*/
|
||||
void
|
||||
RC5_DestroyContext(RC5Context *cx, PRBool freeit)
|
||||
{
|
||||
PORT_SetError(PR_NOT_IMPLEMENTED_ERROR);
|
||||
}
|
||||
|
||||
/*
|
||||
** Perform RC5 encryption.
|
||||
** "cx" the context
|
||||
** "output" the output buffer to store the encrypted data.
|
||||
** "outputLen" how much data is stored in "output". Set by the routine
|
||||
** after some data is stored in output.
|
||||
** "maxOutputLen" the maximum amount of data that can ever be
|
||||
** stored in "output"
|
||||
** "input" the input data
|
||||
** "inputLen" the amount of input data
|
||||
*/
|
||||
SECStatus
|
||||
RC5_Encrypt(RC5Context *cx, unsigned char *output, unsigned int *outputLen,
|
||||
unsigned int maxOutputLen,
|
||||
const unsigned char *input, unsigned int inputLen)
|
||||
{
|
||||
PORT_SetError(PR_NOT_IMPLEMENTED_ERROR);
|
||||
return SECFailure;
|
||||
}
|
||||
|
||||
/*
|
||||
** Perform RC5 decryption.
|
||||
** "cx" the context
|
||||
** "output" the output buffer to store the decrypted data.
|
||||
** "outputLen" how much data is stored in "output". Set by the routine
|
||||
** after some data is stored in output.
|
||||
** "maxOutputLen" the maximum amount of data that can ever be
|
||||
** stored in "output"
|
||||
** "input" the input data
|
||||
** "inputLen" the amount of input data
|
||||
*/
|
||||
SECStatus
|
||||
RC5_Decrypt(RC5Context *cx, unsigned char *output, unsigned int *outputLen,
|
||||
unsigned int maxOutputLen,
|
||||
const unsigned char *input, unsigned int inputLen)
|
||||
{
|
||||
PORT_SetError(PR_NOT_IMPLEMENTED_ERROR);
|
||||
return SECFailure;
|
||||
}
|
||||
|
||||
567
mozilla/security/nss/lib/freebl/arcfour.c
Normal file
567
mozilla/security/nss/lib/freebl/arcfour.c
Normal file
@@ -0,0 +1,567 @@
|
||||
/*
|
||||
* The contents of this file are subject to the Mozilla Public
|
||||
* License Version 1.1 (the "License"); you may not use this file
|
||||
* except in compliance with the License. You may obtain a copy of
|
||||
* the License at http://www.mozilla.org/MPL/
|
||||
*
|
||||
* Software distributed under the License is distributed on an "AS
|
||||
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
|
||||
* implied. See the License for the specific language governing
|
||||
* rights and limitations under the License.
|
||||
*
|
||||
* The Original Code is the Netscape security libraries.
|
||||
*
|
||||
* The Initial Developer of the Original Code is Netscape
|
||||
* Communications Corporation. Portions created by Netscape are
|
||||
* Copyright (C) 1994-2000 Netscape Communications Corporation. All
|
||||
* Rights Reserved.
|
||||
*
|
||||
* Contributor(s):
|
||||
*
|
||||
* Alternatively, the contents of this file may be used under the
|
||||
* terms of the GNU General Public License Version 2 or later (the
|
||||
* "GPL"), in which case the provisions of the GPL are applicable
|
||||
* instead of those above. If you wish to allow use of your
|
||||
* version of this file only under the terms of the GPL and not to
|
||||
* allow others to use your version of this file under the MPL,
|
||||
* indicate your decision by deleting the provisions above and
|
||||
* replace them with the notice and other provisions required by
|
||||
* the GPL. If you do not delete the provisions above, a recipient
|
||||
* may use your version of this file under either the MPL or the
|
||||
* GPL.
|
||||
*/
|
||||
|
||||
#include "prerr.h"
|
||||
#include "secerr.h"
|
||||
|
||||
#include "prtypes.h"
|
||||
#include "blapi.h"
|
||||
|
||||
/* Architecture-dependent defines */
|
||||
|
||||
#if defined(SOLARIS) || defined(HPUX) || defined(i386) || defined(IRIX)
|
||||
/* Convert the byte-stream to a word-stream */
|
||||
#define CONVERT_TO_WORDS
|
||||
#endif
|
||||
|
||||
#if defined(AIX) || defined(OSF1)
|
||||
/* Treat array variables as longs, not bytes */
|
||||
#define USE_LONG
|
||||
#endif
|
||||
|
||||
#if defined(_WIN32_WCE)
|
||||
#undef WORD
|
||||
#define WORD ARC4WORD
|
||||
#endif
|
||||
|
||||
#if defined(NSS_USE_HYBRID) && !defined(SOLARIS) && !defined(NSS_USE_64)
|
||||
typedef unsigned long long WORD;
|
||||
#else
|
||||
typedef unsigned long WORD;
|
||||
#endif
|
||||
#define WORDSIZE sizeof(WORD)
|
||||
|
||||
#ifdef USE_LONG
|
||||
typedef unsigned long Stype;
|
||||
#else
|
||||
typedef PRUint8 Stype;
|
||||
#endif
|
||||
|
||||
#define ARCFOUR_STATE_SIZE 256
|
||||
|
||||
#define MASK1BYTE (WORD)(0xff)
|
||||
|
||||
#define SWAP(a, b) \
|
||||
tmp = a; \
|
||||
a = b; \
|
||||
b = tmp;
|
||||
|
||||
/*
|
||||
* State information for stream cipher.
|
||||
*/
|
||||
struct RC4ContextStr
|
||||
{
|
||||
Stype S[ARCFOUR_STATE_SIZE];
|
||||
PRUint8 i;
|
||||
PRUint8 j;
|
||||
};
|
||||
|
||||
/*
|
||||
* array indices [0..255] to initialize cx->S array (faster than loop).
|
||||
*/
|
||||
static const Stype Kinit[256] = {
|
||||
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
|
||||
0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
|
||||
0x10, 0x11, 0x12, 0x13, 0x14, 0x15, 0x16, 0x17,
|
||||
0x18, 0x19, 0x1a, 0x1b, 0x1c, 0x1d, 0x1e, 0x1f,
|
||||
0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27,
|
||||
0x28, 0x29, 0x2a, 0x2b, 0x2c, 0x2d, 0x2e, 0x2f,
|
||||
0x30, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37,
|
||||
0x38, 0x39, 0x3a, 0x3b, 0x3c, 0x3d, 0x3e, 0x3f,
|
||||
0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47,
|
||||
0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e, 0x4f,
|
||||
0x50, 0x51, 0x52, 0x53, 0x54, 0x55, 0x56, 0x57,
|
||||
0x58, 0x59, 0x5a, 0x5b, 0x5c, 0x5d, 0x5e, 0x5f,
|
||||
0x60, 0x61, 0x62, 0x63, 0x64, 0x65, 0x66, 0x67,
|
||||
0x68, 0x69, 0x6a, 0x6b, 0x6c, 0x6d, 0x6e, 0x6f,
|
||||
0x70, 0x71, 0x72, 0x73, 0x74, 0x75, 0x76, 0x77,
|
||||
0x78, 0x79, 0x7a, 0x7b, 0x7c, 0x7d, 0x7e, 0x7f,
|
||||
0x80, 0x81, 0x82, 0x83, 0x84, 0x85, 0x86, 0x87,
|
||||
0x88, 0x89, 0x8a, 0x8b, 0x8c, 0x8d, 0x8e, 0x8f,
|
||||
0x90, 0x91, 0x92, 0x93, 0x94, 0x95, 0x96, 0x97,
|
||||
0x98, 0x99, 0x9a, 0x9b, 0x9c, 0x9d, 0x9e, 0x9f,
|
||||
0xa0, 0xa1, 0xa2, 0xa3, 0xa4, 0xa5, 0xa6, 0xa7,
|
||||
0xa8, 0xa9, 0xaa, 0xab, 0xac, 0xad, 0xae, 0xaf,
|
||||
0xb0, 0xb1, 0xb2, 0xb3, 0xb4, 0xb5, 0xb6, 0xb7,
|
||||
0xb8, 0xb9, 0xba, 0xbb, 0xbc, 0xbd, 0xbe, 0xbf,
|
||||
0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7,
|
||||
0xc8, 0xc9, 0xca, 0xcb, 0xcc, 0xcd, 0xce, 0xcf,
|
||||
0xd0, 0xd1, 0xd2, 0xd3, 0xd4, 0xd5, 0xd6, 0xd7,
|
||||
0xd8, 0xd9, 0xda, 0xdb, 0xdc, 0xdd, 0xde, 0xdf,
|
||||
0xe0, 0xe1, 0xe2, 0xe3, 0xe4, 0xe5, 0xe6, 0xe7,
|
||||
0xe8, 0xe9, 0xea, 0xeb, 0xec, 0xed, 0xee, 0xef,
|
||||
0xf0, 0xf1, 0xf2, 0xf3, 0xf4, 0xf5, 0xf6, 0xf7,
|
||||
0xf8, 0xf9, 0xfa, 0xfb, 0xfc, 0xfd, 0xfe, 0xff
|
||||
};
|
||||
|
||||
/*
|
||||
* Initialize a new generator.
|
||||
*/
|
||||
RC4Context *
|
||||
RC4_CreateContext(const unsigned char *key, int len)
|
||||
{
|
||||
int i;
|
||||
PRUint8 j, tmp;
|
||||
RC4Context *cx;
|
||||
PRUint8 K[256];
|
||||
PRUint8 *L;
|
||||
/* verify the key length. */
|
||||
PORT_Assert(len > 0 && len < ARCFOUR_STATE_SIZE);
|
||||
if (len < 0 || len >= ARCFOUR_STATE_SIZE) {
|
||||
PORT_SetError(SEC_ERROR_INVALID_ARGS);
|
||||
return NULL;
|
||||
}
|
||||
/* Create space for the context. */
|
||||
cx = (RC4Context *)PORT_ZAlloc(sizeof(RC4Context));
|
||||
if (cx == NULL) {
|
||||
PORT_SetError(PR_OUT_OF_MEMORY_ERROR);
|
||||
return NULL;
|
||||
}
|
||||
/* Initialize the state using array indices. */
|
||||
memcpy(cx->S, Kinit, sizeof cx->S);
|
||||
/* Fill in K repeatedly with values from key. */
|
||||
L = K;
|
||||
for (i = sizeof K; i > len; i-= len) {
|
||||
memcpy(L, key, len);
|
||||
L += len;
|
||||
}
|
||||
memcpy(L, key, i);
|
||||
/* Stir the state of the generator. At this point it is assumed
|
||||
* that the key is the size of the state buffer. If this is not
|
||||
* the case, the key bytes are repeated to fill the buffer.
|
||||
*/
|
||||
j = 0;
|
||||
#define ARCFOUR_STATE_STIR(ii) \
|
||||
j = j + cx->S[ii] + K[ii]; \
|
||||
SWAP(cx->S[ii], cx->S[j]);
|
||||
for (i=0; i<ARCFOUR_STATE_SIZE; i++) {
|
||||
ARCFOUR_STATE_STIR(i);
|
||||
}
|
||||
cx->i = 0;
|
||||
cx->j = 0;
|
||||
return cx;
|
||||
}
|
||||
|
||||
void
|
||||
RC4_DestroyContext(RC4Context *cx, PRBool freeit)
|
||||
{
|
||||
if (freeit)
|
||||
PORT_ZFree(cx, sizeof(*cx));
|
||||
}
|
||||
|
||||
/*
|
||||
* Generate the next byte in the stream.
|
||||
*/
|
||||
#define ARCFOUR_NEXT_BYTE() \
|
||||
tmpSi = cx->S[++tmpi]; \
|
||||
tmpj += tmpSi; \
|
||||
tmpSj = cx->S[tmpj]; \
|
||||
cx->S[tmpi] = tmpSj; \
|
||||
cx->S[tmpj] = tmpSi; \
|
||||
t = tmpSi + tmpSj;
|
||||
|
||||
#ifdef CONVERT_TO_WORDS
|
||||
/*
|
||||
* Straight RC4 op. No optimization.
|
||||
*/
|
||||
static SECStatus
|
||||
rc4_no_opt(RC4Context *cx, unsigned char *output,
|
||||
unsigned int *outputLen, unsigned int maxOutputLen,
|
||||
const unsigned char *input, unsigned int inputLen)
|
||||
{
|
||||
PRUint8 t;
|
||||
Stype tmpSi, tmpSj;
|
||||
register PRUint8 tmpi = cx->i;
|
||||
register PRUint8 tmpj = cx->j;
|
||||
unsigned int index;
|
||||
PORT_Assert(maxOutputLen >= inputLen);
|
||||
if (maxOutputLen < inputLen) {
|
||||
PORT_SetError(SEC_ERROR_INVALID_ARGS);
|
||||
return SECFailure;
|
||||
}
|
||||
for (index=0; index < inputLen; index++) {
|
||||
/* Generate next byte from stream. */
|
||||
ARCFOUR_NEXT_BYTE();
|
||||
/* output = next stream byte XOR next input byte */
|
||||
output[index] = cx->S[t] ^ input[index];
|
||||
}
|
||||
*outputLen = inputLen;
|
||||
cx->i = tmpi;
|
||||
cx->j = tmpj;
|
||||
return SECSuccess;
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifndef CONVERT_TO_WORDS
|
||||
/*
|
||||
* Byte-at-a-time RC4, unrolling the loop into 8 pieces.
|
||||
*/
|
||||
static SECStatus
|
||||
rc4_unrolled(RC4Context *cx, unsigned char *output,
|
||||
unsigned int *outputLen, unsigned int maxOutputLen,
|
||||
const unsigned char *input, unsigned int inputLen)
|
||||
{
|
||||
PRUint8 t;
|
||||
Stype tmpSi, tmpSj;
|
||||
register PRUint8 tmpi = cx->i;
|
||||
register PRUint8 tmpj = cx->j;
|
||||
int index;
|
||||
PORT_Assert(maxOutputLen >= inputLen);
|
||||
if (maxOutputLen < inputLen) {
|
||||
PORT_SetError(SEC_ERROR_INVALID_ARGS);
|
||||
return SECFailure;
|
||||
}
|
||||
for (index = inputLen / 8; index-- > 0; input += 8, output += 8) {
|
||||
ARCFOUR_NEXT_BYTE();
|
||||
output[0] = cx->S[t] ^ input[0];
|
||||
ARCFOUR_NEXT_BYTE();
|
||||
output[1] = cx->S[t] ^ input[1];
|
||||
ARCFOUR_NEXT_BYTE();
|
||||
output[2] = cx->S[t] ^ input[2];
|
||||
ARCFOUR_NEXT_BYTE();
|
||||
output[3] = cx->S[t] ^ input[3];
|
||||
ARCFOUR_NEXT_BYTE();
|
||||
output[4] = cx->S[t] ^ input[4];
|
||||
ARCFOUR_NEXT_BYTE();
|
||||
output[5] = cx->S[t] ^ input[5];
|
||||
ARCFOUR_NEXT_BYTE();
|
||||
output[6] = cx->S[t] ^ input[6];
|
||||
ARCFOUR_NEXT_BYTE();
|
||||
output[7] = cx->S[t] ^ input[7];
|
||||
}
|
||||
index = inputLen % 8;
|
||||
if (index) {
|
||||
input += index;
|
||||
output += index;
|
||||
switch (index) {
|
||||
case 7:
|
||||
ARCFOUR_NEXT_BYTE();
|
||||
output[-7] = cx->S[t] ^ input[-7]; /* FALLTHRU */
|
||||
case 6:
|
||||
ARCFOUR_NEXT_BYTE();
|
||||
output[-6] = cx->S[t] ^ input[-6]; /* FALLTHRU */
|
||||
case 5:
|
||||
ARCFOUR_NEXT_BYTE();
|
||||
output[-5] = cx->S[t] ^ input[-5]; /* FALLTHRU */
|
||||
case 4:
|
||||
ARCFOUR_NEXT_BYTE();
|
||||
output[-4] = cx->S[t] ^ input[-4]; /* FALLTHRU */
|
||||
case 3:
|
||||
ARCFOUR_NEXT_BYTE();
|
||||
output[-3] = cx->S[t] ^ input[-3]; /* FALLTHRU */
|
||||
case 2:
|
||||
ARCFOUR_NEXT_BYTE();
|
||||
output[-2] = cx->S[t] ^ input[-2]; /* FALLTHRU */
|
||||
case 1:
|
||||
ARCFOUR_NEXT_BYTE();
|
||||
output[-1] = cx->S[t] ^ input[-1]; /* FALLTHRU */
|
||||
default:
|
||||
/* FALLTHRU */
|
||||
; /* hp-ux build breaks without this */
|
||||
}
|
||||
}
|
||||
cx->i = tmpi;
|
||||
cx->j = tmpj;
|
||||
*outputLen = inputLen;
|
||||
return SECSuccess;
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef IS_LITTLE_ENDIAN
|
||||
#define ARCFOUR_NEXT4BYTES_L(n) \
|
||||
ARCFOUR_NEXT_BYTE(); streamWord |= (WORD)cx->S[t] << (n ); \
|
||||
ARCFOUR_NEXT_BYTE(); streamWord |= (WORD)cx->S[t] << (n + 8); \
|
||||
ARCFOUR_NEXT_BYTE(); streamWord |= (WORD)cx->S[t] << (n + 16); \
|
||||
ARCFOUR_NEXT_BYTE(); streamWord |= (WORD)cx->S[t] << (n + 24);
|
||||
#else
|
||||
#define ARCFOUR_NEXT4BYTES_B(n) \
|
||||
ARCFOUR_NEXT_BYTE(); streamWord |= (WORD)cx->S[t] << (n + 24); \
|
||||
ARCFOUR_NEXT_BYTE(); streamWord |= (WORD)cx->S[t] << (n + 16); \
|
||||
ARCFOUR_NEXT_BYTE(); streamWord |= (WORD)cx->S[t] << (n + 8); \
|
||||
ARCFOUR_NEXT_BYTE(); streamWord |= (WORD)cx->S[t] << (n );
|
||||
#endif
|
||||
|
||||
#if (defined(NSS_USE_HYBRID) && !defined(SOLARIS)) || defined(NSS_USE_64)
|
||||
/* 64-bit wordsize */
|
||||
#ifdef IS_LITTLE_ENDIAN
|
||||
#define ARCFOUR_NEXT_WORD() \
|
||||
{ streamWord = 0; ARCFOUR_NEXT4BYTES_L(0); ARCFOUR_NEXT4BYTES_L(32); }
|
||||
#else
|
||||
#define ARCFOUR_NEXT_WORD() \
|
||||
{ streamWord = 0; ARCFOUR_NEXT4BYTES_B(32); ARCFOUR_NEXT4BYTES_B(0); }
|
||||
#endif
|
||||
#else
|
||||
/* 32-bit wordsize */
|
||||
#ifdef IS_LITTLE_ENDIAN
|
||||
#define ARCFOUR_NEXT_WORD() \
|
||||
{ streamWord = 0; ARCFOUR_NEXT4BYTES_L(0); }
|
||||
#else
|
||||
#define ARCFOUR_NEXT_WORD() \
|
||||
{ streamWord = 0; ARCFOUR_NEXT4BYTES_B(0); }
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#ifdef IS_LITTLE_ENDIAN
|
||||
#define RSH <<
|
||||
#define LSH >>
|
||||
#else
|
||||
#define RSH >>
|
||||
#define LSH <<
|
||||
#endif
|
||||
|
||||
#ifdef CONVERT_TO_WORDS
|
||||
/*
|
||||
* Convert input and output buffers to words before performing
|
||||
* RC4 operations.
|
||||
*/
|
||||
static SECStatus
|
||||
rc4_wordconv(RC4Context *cx, unsigned char *output,
|
||||
unsigned int *outputLen, unsigned int maxOutputLen,
|
||||
const unsigned char *input, unsigned int inputLen)
|
||||
{
|
||||
ptrdiff_t inOffset = (ptrdiff_t)input % WORDSIZE;
|
||||
ptrdiff_t outOffset = (ptrdiff_t)output % WORDSIZE;
|
||||
register WORD streamWord, mask;
|
||||
register WORD *pInWord, *pOutWord;
|
||||
register WORD inWord, nextInWord;
|
||||
PRUint8 t;
|
||||
register Stype tmpSi, tmpSj;
|
||||
register PRUint8 tmpi = cx->i;
|
||||
register PRUint8 tmpj = cx->j;
|
||||
unsigned int byteCount;
|
||||
unsigned int bufShift, invBufShift;
|
||||
int i;
|
||||
|
||||
PORT_Assert(maxOutputLen >= inputLen);
|
||||
if (maxOutputLen < inputLen) {
|
||||
PORT_SetError(SEC_ERROR_INVALID_ARGS);
|
||||
return SECFailure;
|
||||
}
|
||||
if (inputLen < 2*WORDSIZE) {
|
||||
/* Ignore word conversion, do byte-at-a-time */
|
||||
return rc4_no_opt(cx, output, outputLen, maxOutputLen, input, inputLen);
|
||||
}
|
||||
*outputLen = inputLen;
|
||||
pInWord = (WORD *)(input - inOffset);
|
||||
if (inOffset < outOffset) {
|
||||
bufShift = 8*(outOffset - inOffset);
|
||||
invBufShift = 8*WORDSIZE - bufShift;
|
||||
} else {
|
||||
invBufShift = 8*(inOffset - outOffset);
|
||||
bufShift = 8*WORDSIZE - invBufShift;
|
||||
}
|
||||
/*****************************************************************/
|
||||
/* Step 1: */
|
||||
/* If the first output word is partial, consume the bytes in the */
|
||||
/* first partial output word by loading one or two words of */
|
||||
/* input and shifting them accordingly. Otherwise, just load */
|
||||
/* in the first word of input. At the end of this block, at */
|
||||
/* least one partial word of input should ALWAYS be loaded. */
|
||||
/*****************************************************************/
|
||||
if (outOffset) {
|
||||
/* Generate input and stream words aligned relative to the
|
||||
* partial output buffer.
|
||||
*/
|
||||
byteCount = WORDSIZE - outOffset;
|
||||
pOutWord = (WORD *)(output - outOffset);
|
||||
mask = streamWord = 0;
|
||||
#ifdef IS_LITTLE_ENDIAN
|
||||
for (i = WORDSIZE - byteCount; i < WORDSIZE; i++) {
|
||||
#else
|
||||
for (i = byteCount - 1; i >= 0; --i) {
|
||||
#endif
|
||||
ARCFOUR_NEXT_BYTE();
|
||||
streamWord |= (WORD)(cx->S[t]) << 8*i;
|
||||
mask |= MASK1BYTE << 8*i;
|
||||
} /* } */
|
||||
inWord = *pInWord++;
|
||||
/* If buffers are relatively misaligned, shift the bytes in inWord
|
||||
* to be aligned to the output buffer.
|
||||
*/
|
||||
nextInWord = 0;
|
||||
if (inOffset < outOffset) {
|
||||
/* Have more bytes than needed, shift remainder into nextInWord */
|
||||
nextInWord = inWord LSH 8*(inOffset + byteCount);
|
||||
inWord = inWord RSH bufShift;
|
||||
} else if (inOffset > outOffset) {
|
||||
/* Didn't get enough bytes from current input word, load another
|
||||
* word and then shift remainder into nextInWord.
|
||||
*/
|
||||
nextInWord = *pInWord++;
|
||||
inWord = (inWord LSH invBufShift) |
|
||||
(nextInWord RSH bufShift);
|
||||
nextInWord = nextInWord LSH invBufShift;
|
||||
}
|
||||
/* Store output of first partial word */
|
||||
*pOutWord = (*pOutWord & ~mask) | ((inWord ^ streamWord) & mask);
|
||||
/* Consumed byteCount bytes of input */
|
||||
inputLen -= byteCount;
|
||||
/* move to next word of output */
|
||||
pOutWord++;
|
||||
/* inWord has been consumed, but there may be bytes in nextInWord */
|
||||
inWord = nextInWord;
|
||||
} else {
|
||||
/* output is word-aligned */
|
||||
pOutWord = (WORD *)output;
|
||||
if (inOffset) {
|
||||
/* Input is not word-aligned. The first word load of input
|
||||
* will not produce a full word of input bytes, so one word
|
||||
* must be pre-loaded. The main loop below will load in the
|
||||
* next input word and shift some of its bytes into inWord
|
||||
* in order to create a full input word. Note that the main
|
||||
* loop must execute at least once because the input must
|
||||
* be at least two words.
|
||||
*/
|
||||
inWord = *pInWord++;
|
||||
inWord = inWord LSH invBufShift;
|
||||
} else {
|
||||
/* Input is word-aligned. The first word load of input
|
||||
* will produce a full word of input bytes, so nothing
|
||||
* needs to be loaded here.
|
||||
*/
|
||||
inWord = 0;
|
||||
}
|
||||
}
|
||||
/* Output buffer is aligned, inOffset is now measured relative to
|
||||
* outOffset (and not a word boundary).
|
||||
*/
|
||||
inOffset = (inOffset + WORDSIZE - outOffset) % WORDSIZE;
|
||||
/*****************************************************************/
|
||||
/* Step 2: main loop */
|
||||
/* At this point the output buffer is word-aligned. Any unused */
|
||||
/* bytes from above will be in inWord (shifted correctly). If */
|
||||
/* the input buffer is unaligned relative to the output buffer, */
|
||||
/* shifting has to be done. */
|
||||
/*****************************************************************/
|
||||
if (inOffset) {
|
||||
for (; inputLen >= WORDSIZE; inputLen -= WORDSIZE) {
|
||||
nextInWord = *pInWord++;
|
||||
inWord |= nextInWord RSH bufShift;
|
||||
nextInWord = nextInWord LSH invBufShift;
|
||||
ARCFOUR_NEXT_WORD();
|
||||
*pOutWord++ = inWord ^ streamWord;
|
||||
inWord = nextInWord;
|
||||
}
|
||||
if (inputLen == 0) {
|
||||
/* Nothing left to do. */
|
||||
cx->i = tmpi;
|
||||
cx->j = tmpj;
|
||||
return SECSuccess;
|
||||
}
|
||||
/* If the amount of remaining input is greater than the amount
|
||||
* bytes pulled from the current input word, need to do another
|
||||
* word load. What's left in inWord will be consumed in step 3.
|
||||
*/
|
||||
if (inputLen > WORDSIZE - inOffset)
|
||||
inWord |= *pInWord RSH bufShift;
|
||||
} else {
|
||||
for (; inputLen >= WORDSIZE; inputLen -= WORDSIZE) {
|
||||
inWord = *pInWord++;
|
||||
ARCFOUR_NEXT_WORD();
|
||||
*pOutWord++ = inWord ^ streamWord;
|
||||
}
|
||||
if (inputLen == 0) {
|
||||
/* Nothing left to do. */
|
||||
cx->i = tmpi;
|
||||
cx->j = tmpj;
|
||||
return SECSuccess;
|
||||
} else {
|
||||
/* A partial input word remains at the tail. Load it. The
|
||||
* relevant bytes will be consumed in step 3.
|
||||
*/
|
||||
inWord = *pInWord;
|
||||
}
|
||||
}
|
||||
/*****************************************************************/
|
||||
/* Step 3: */
|
||||
/* A partial word of input remains, and it is already loaded */
|
||||
/* into nextInWord. Shift appropriately and consume the bytes */
|
||||
/* used in the partial word. */
|
||||
/*****************************************************************/
|
||||
mask = streamWord = 0;
|
||||
#ifdef IS_LITTLE_ENDIAN
|
||||
for (i = 0; i < inputLen; ++i) {
|
||||
#else
|
||||
for (i = WORDSIZE - 1; i >= WORDSIZE - inputLen; --i) {
|
||||
#endif
|
||||
ARCFOUR_NEXT_BYTE();
|
||||
streamWord |= (WORD)(cx->S[t]) << 8*i;
|
||||
mask |= MASK1BYTE << 8*i;
|
||||
} /* } */
|
||||
*pOutWord = (*pOutWord & ~mask) | ((inWord ^ streamWord) & mask);
|
||||
cx->i = tmpi;
|
||||
cx->j = tmpj;
|
||||
return SECSuccess;
|
||||
}
|
||||
#endif
|
||||
|
||||
SECStatus
|
||||
RC4_Encrypt(RC4Context *cx, unsigned char *output,
|
||||
unsigned int *outputLen, unsigned int maxOutputLen,
|
||||
const unsigned char *input, unsigned int inputLen)
|
||||
{
|
||||
PORT_Assert(maxOutputLen >= inputLen);
|
||||
if (maxOutputLen < inputLen) {
|
||||
PORT_SetError(SEC_ERROR_INVALID_ARGS);
|
||||
return SECFailure;
|
||||
}
|
||||
#ifdef CONVERT_TO_WORDS
|
||||
/* Convert the byte-stream to a word-stream */
|
||||
return rc4_wordconv(cx, output, outputLen, maxOutputLen, input, inputLen);
|
||||
#else
|
||||
/* Operate on bytes, but unroll the main loop */
|
||||
return rc4_unrolled(cx, output, outputLen, maxOutputLen, input, inputLen);
|
||||
#endif
|
||||
}
|
||||
|
||||
SECStatus RC4_Decrypt(RC4Context *cx, unsigned char *output,
|
||||
unsigned int *outputLen, unsigned int maxOutputLen,
|
||||
const unsigned char *input, unsigned int inputLen)
|
||||
{
|
||||
PORT_Assert(maxOutputLen >= inputLen);
|
||||
if (maxOutputLen < inputLen) {
|
||||
PORT_SetError(SEC_ERROR_INVALID_ARGS);
|
||||
return SECFailure;
|
||||
}
|
||||
/* decrypt and encrypt are same operation. */
|
||||
#ifdef CONVERT_TO_WORDS
|
||||
/* Convert the byte-stream to a word-stream */
|
||||
return rc4_wordconv(cx, output, outputLen, maxOutputLen, input, inputLen);
|
||||
#else
|
||||
/* Operate on bytes, but unroll the main loop */
|
||||
return rc4_unrolled(cx, output, outputLen, maxOutputLen, input, inputLen);
|
||||
#endif
|
||||
}
|
||||
|
||||
#undef CONVERT_TO_WORDS
|
||||
#undef USE_LONG
|
||||
1002
mozilla/security/nss/lib/freebl/blapi.h
Normal file
1002
mozilla/security/nss/lib/freebl/blapi.h
Normal file
File diff suppressed because it is too large
Load Diff
2114
mozilla/security/nss/lib/freebl/blapi_bsf.c
Normal file
2114
mozilla/security/nss/lib/freebl/blapi_bsf.c
Normal file
File diff suppressed because it is too large
Load Diff
336
mozilla/security/nss/lib/freebl/blapit.h
Normal file
336
mozilla/security/nss/lib/freebl/blapit.h
Normal file
@@ -0,0 +1,336 @@
|
||||
/*
|
||||
* blapit.h - public data structures for the crypto library
|
||||
*
|
||||
* The contents of this file are subject to the Mozilla Public
|
||||
* License Version 1.1 (the "License"); you may not use this file
|
||||
* except in compliance with the License. You may obtain a copy of
|
||||
* the License at http://www.mozilla.org/MPL/
|
||||
*
|
||||
* Software distributed under the License is distributed on an "AS
|
||||
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
|
||||
* implied. See the License for the specific language governing
|
||||
* rights and limitations under the License.
|
||||
*
|
||||
* The Original Code is the Netscape security libraries.
|
||||
*
|
||||
* The Initial Developer of the Original Code is Netscape
|
||||
* Communications Corporation. Portions created by Netscape are
|
||||
* Copyright (C) 1994-2000 Netscape Communications Corporation. All
|
||||
* Rights Reserved.
|
||||
*
|
||||
* Portions created by Sun Microsystems, Inc. are Copyright (C) 2003
|
||||
* Sun Microsystems, Inc. All Rights Reserved.
|
||||
*
|
||||
* Contributor(s):
|
||||
* Dr Vipul Gupta <vipul.gupta@sun.com>, Sun Microsystems Laboratories
|
||||
*
|
||||
* Alternatively, the contents of this file may be used under the
|
||||
* terms of the GNU General Public License Version 2 or later (the
|
||||
* "GPL"), in which case the provisions of the GPL are applicable
|
||||
* instead of those above. If you wish to allow use of your
|
||||
* version of this file only under the terms of the GPL and not to
|
||||
* allow others to use your version of this file under the MPL,
|
||||
* indicate your decision by deleting the provisions above and
|
||||
* replace them with the notice and other provisions required by
|
||||
* the GPL. If you do not delete the provisions above, a recipient
|
||||
* may use your version of this file under either the MPL or the
|
||||
* GPL.
|
||||
*
|
||||
* $Id: blapit.h,v 1.10 2003-03-29 00:18:18 nelsonb%netscape.com Exp $
|
||||
*/
|
||||
|
||||
#ifndef _BLAPIT_H_
|
||||
#define _BLAPIT_H_
|
||||
|
||||
#include "seccomon.h"
|
||||
#include "prlink.h"
|
||||
#include "plarena.h"
|
||||
|
||||
|
||||
/* RC2 operation modes */
|
||||
#define NSS_RC2 0
|
||||
#define NSS_RC2_CBC 1
|
||||
|
||||
/* RC5 operation modes */
|
||||
#define NSS_RC5 0
|
||||
#define NSS_RC5_CBC 1
|
||||
|
||||
/* DES operation modes */
|
||||
#define NSS_DES 0
|
||||
#define NSS_DES_CBC 1
|
||||
#define NSS_DES_EDE3 2
|
||||
#define NSS_DES_EDE3_CBC 3
|
||||
|
||||
#define DES_KEY_LENGTH 8 /* Bytes */
|
||||
|
||||
/* AES operation modes */
|
||||
#define NSS_AES 0
|
||||
#define NSS_AES_CBC 1
|
||||
|
||||
#define DSA_SIGNATURE_LEN 40 /* Bytes */
|
||||
#define DSA_SUBPRIME_LEN 20 /* Bytes */
|
||||
|
||||
/* XXX We shouldn't have to hard code this limit. For
|
||||
* now, this is the quickest way to support ECDSA signature
|
||||
* processing (ECDSA signature lengths depend on curve
|
||||
* size). This limit is sufficient for curves upto
|
||||
* 576 bits.
|
||||
*/
|
||||
#define MAX_ECKEY_LEN 72 /* Bytes */
|
||||
|
||||
/*
|
||||
* Number of bytes each hash algorithm produces
|
||||
*/
|
||||
#define MD2_LENGTH 16 /* Bytes */
|
||||
#define MD5_LENGTH 16 /* Bytes */
|
||||
#define SHA1_LENGTH 20 /* Bytes */
|
||||
#define SHA256_LENGTH 32 /* bytes */
|
||||
#define SHA384_LENGTH 48 /* bytes */
|
||||
#define SHA512_LENGTH 64 /* bytes */
|
||||
#define HASH_LENGTH_MAX SHA512_LENGTH
|
||||
|
||||
/*
|
||||
* Input block size for each hash algorithm.
|
||||
*/
|
||||
|
||||
#define SHA256_BLOCK_LENGTH 64 /* bytes */
|
||||
#define SHA384_BLOCK_LENGTH 128 /* bytes */
|
||||
#define SHA512_BLOCK_LENGTH 128 /* bytes */
|
||||
|
||||
#define AES_KEY_WRAP_IV_BYTES 8
|
||||
#define AES_KEY_WRAP_BLOCK_SIZE 8 /* bytes */
|
||||
#define AES_BLOCK_SIZE 16 /* bytes */
|
||||
|
||||
#define NSS_FREEBL_DEFAULT_CHUNKSIZE 2048
|
||||
|
||||
/*
|
||||
* The FIPS 186 algorithm for generating primes P and Q allows only 9
|
||||
* distinct values for the length of P, and only one value for the
|
||||
* length of Q.
|
||||
* The algorithm uses a variable j to indicate which of the 9 lengths
|
||||
* of P is to be used.
|
||||
* The following table relates j to the lengths of P and Q in bits.
|
||||
*
|
||||
* j bits in P bits in Q
|
||||
* _ _________ _________
|
||||
* 0 512 160
|
||||
* 1 576 160
|
||||
* 2 640 160
|
||||
* 3 704 160
|
||||
* 4 768 160
|
||||
* 5 832 160
|
||||
* 6 896 160
|
||||
* 7 960 160
|
||||
* 8 1024 160
|
||||
*
|
||||
* The FIPS-186 compliant PQG generator takes j as an input parameter.
|
||||
*/
|
||||
|
||||
#define DSA_Q_BITS 160
|
||||
#define DSA_MAX_P_BITS 1024
|
||||
#define DSA_MIN_P_BITS 512
|
||||
|
||||
/*
|
||||
* function takes desired number of bits in P,
|
||||
* returns index (0..8) or -1 if number of bits is invalid.
|
||||
*/
|
||||
#define PQG_PBITS_TO_INDEX(bits) ((((bits)-512) % 64) ? -1 : (int)((bits)-512)/64)
|
||||
|
||||
/*
|
||||
* function takes index (0-8)
|
||||
* returns number of bits in P for that index, or -1 if index is invalid.
|
||||
*/
|
||||
#define PQG_INDEX_TO_PBITS(j) (((unsigned)(j) > 8) ? -1 : (512 + 64 * (j)))
|
||||
|
||||
|
||||
/***************************************************************************
|
||||
** Opaque objects
|
||||
*/
|
||||
|
||||
struct DESContextStr ;
|
||||
struct RC2ContextStr ;
|
||||
struct RC4ContextStr ;
|
||||
struct RC5ContextStr ;
|
||||
struct AESContextStr ;
|
||||
struct MD2ContextStr ;
|
||||
struct MD5ContextStr ;
|
||||
struct SHA1ContextStr ;
|
||||
struct SHA256ContextStr ;
|
||||
struct SHA512ContextStr ;
|
||||
struct AESKeyWrapContextStr ;
|
||||
|
||||
typedef struct DESContextStr DESContext;
|
||||
typedef struct RC2ContextStr RC2Context;
|
||||
typedef struct RC4ContextStr RC4Context;
|
||||
typedef struct RC5ContextStr RC5Context;
|
||||
typedef struct AESContextStr AESContext;
|
||||
typedef struct MD2ContextStr MD2Context;
|
||||
typedef struct MD5ContextStr MD5Context;
|
||||
typedef struct SHA1ContextStr SHA1Context;
|
||||
typedef struct SHA256ContextStr SHA256Context;
|
||||
typedef struct SHA512ContextStr SHA512Context;
|
||||
/* SHA384Context is really a SHA512ContextStr. This is not a mistake. */
|
||||
typedef struct SHA512ContextStr SHA384Context;
|
||||
typedef struct AESKeyWrapContextStr AESKeyWrapContext;
|
||||
|
||||
/***************************************************************************
|
||||
** RSA Public and Private Key structures
|
||||
*/
|
||||
|
||||
/* member names from PKCS#1, section 7.1 */
|
||||
struct RSAPublicKeyStr {
|
||||
PRArenaPool * arena;
|
||||
SECItem modulus;
|
||||
SECItem publicExponent;
|
||||
};
|
||||
typedef struct RSAPublicKeyStr RSAPublicKey;
|
||||
|
||||
/* member names from PKCS#1, section 7.2 */
|
||||
struct RSAPrivateKeyStr {
|
||||
PRArenaPool * arena;
|
||||
SECItem version;
|
||||
SECItem modulus;
|
||||
SECItem publicExponent;
|
||||
SECItem privateExponent;
|
||||
SECItem prime1;
|
||||
SECItem prime2;
|
||||
SECItem exponent1;
|
||||
SECItem exponent2;
|
||||
SECItem coefficient;
|
||||
};
|
||||
typedef struct RSAPrivateKeyStr RSAPrivateKey;
|
||||
|
||||
|
||||
/***************************************************************************
|
||||
** DSA Public and Private Key and related structures
|
||||
*/
|
||||
|
||||
struct PQGParamsStr {
|
||||
PRArenaPool *arena;
|
||||
SECItem prime; /* p */
|
||||
SECItem subPrime; /* q */
|
||||
SECItem base; /* g */
|
||||
/* XXX chrisk: this needs to be expanded to hold j and validationParms (RFC2459 7.3.2) */
|
||||
};
|
||||
typedef struct PQGParamsStr PQGParams;
|
||||
|
||||
struct PQGVerifyStr {
|
||||
PRArenaPool * arena; /* includes this struct, seed, & h. */
|
||||
unsigned int counter;
|
||||
SECItem seed;
|
||||
SECItem h;
|
||||
};
|
||||
typedef struct PQGVerifyStr PQGVerify;
|
||||
|
||||
struct DSAPublicKeyStr {
|
||||
PQGParams params;
|
||||
SECItem publicValue;
|
||||
};
|
||||
typedef struct DSAPublicKeyStr DSAPublicKey;
|
||||
|
||||
struct DSAPrivateKeyStr {
|
||||
PQGParams params;
|
||||
SECItem publicValue;
|
||||
SECItem privateValue;
|
||||
};
|
||||
typedef struct DSAPrivateKeyStr DSAPrivateKey;
|
||||
|
||||
/***************************************************************************
|
||||
** Diffie-Hellman Public and Private Key and related structures
|
||||
** Structure member names suggested by PKCS#3.
|
||||
*/
|
||||
|
||||
struct DHParamsStr {
|
||||
PRArenaPool * arena;
|
||||
SECItem prime; /* p */
|
||||
SECItem base; /* g */
|
||||
};
|
||||
typedef struct DHParamsStr DHParams;
|
||||
|
||||
struct DHPublicKeyStr {
|
||||
PRArenaPool * arena;
|
||||
SECItem prime;
|
||||
SECItem base;
|
||||
SECItem publicValue;
|
||||
};
|
||||
typedef struct DHPublicKeyStr DHPublicKey;
|
||||
|
||||
struct DHPrivateKeyStr {
|
||||
PRArenaPool * arena;
|
||||
SECItem prime;
|
||||
SECItem base;
|
||||
SECItem publicValue;
|
||||
SECItem privateValue;
|
||||
};
|
||||
typedef struct DHPrivateKeyStr DHPrivateKey;
|
||||
|
||||
/***************************************************************************
|
||||
** Data structures used for elliptic curve parameters and
|
||||
** public and private keys.
|
||||
*/
|
||||
|
||||
/*
|
||||
** The ECParams data structures can encode elliptic curve
|
||||
** parameters for both GFp and GF2m curves.
|
||||
*/
|
||||
|
||||
typedef enum { ec_params_explicit,
|
||||
ec_params_named
|
||||
} ECParamsType;
|
||||
|
||||
typedef enum { ec_field_GFp = 1,
|
||||
ec_field_GF2m
|
||||
} ECFieldType;
|
||||
|
||||
struct ECFieldIDStr {
|
||||
int size; /* field size in bits */
|
||||
ECFieldType type;
|
||||
union {
|
||||
SECItem prime; /* prime p for (GFp) */
|
||||
SECItem poly; /* irreducible binary polynomial for (GF2m) */
|
||||
} u;
|
||||
int k1; /* first coefficient of pentanomial or
|
||||
* the only coefficient of trinomial
|
||||
*/
|
||||
int k2; /* two remaining coefficients of pentanomial */
|
||||
int k3;
|
||||
};
|
||||
typedef struct ECFieldIDStr ECFieldID;
|
||||
|
||||
struct ECCurveStr {
|
||||
SECItem a; /* contains octet stream encoding of
|
||||
* field element (X9.62 section 4.3.3)
|
||||
*/
|
||||
SECItem b;
|
||||
SECItem seed;
|
||||
};
|
||||
typedef struct ECCurveStr ECCurve;
|
||||
|
||||
struct ECParamsStr {
|
||||
PRArenaPool * arena;
|
||||
ECParamsType type;
|
||||
ECFieldID fieldID;
|
||||
ECCurve curve;
|
||||
SECItem base;
|
||||
SECItem order;
|
||||
int cofactor;
|
||||
SECItem DEREncoding;
|
||||
};
|
||||
typedef struct ECParamsStr ECParams;
|
||||
|
||||
struct ECPublicKeyStr {
|
||||
ECParams ecParams;
|
||||
SECItem publicValue; /* elliptic curve point encoded as
|
||||
* octet stream.
|
||||
*/
|
||||
};
|
||||
typedef struct ECPublicKeyStr ECPublicKey;
|
||||
|
||||
struct ECPrivateKeyStr {
|
||||
ECParams ecParams;
|
||||
SECItem publicValue; /* encoded ec point */
|
||||
SECItem privateValue; /* private big integer */
|
||||
};
|
||||
typedef struct ECPrivateKeyStr ECPrivateKey;
|
||||
|
||||
#endif /* _BLAPIT_H_ */
|
||||
103
mozilla/security/nss/lib/freebl/config.mk
Normal file
103
mozilla/security/nss/lib/freebl/config.mk
Normal file
@@ -0,0 +1,103 @@
|
||||
#
|
||||
# The contents of this file are subject to the Mozilla Public
|
||||
# License Version 1.1 (the "License"); you may not use this file
|
||||
# except in compliance with the License. You may obtain a copy of
|
||||
# the License at http://www.mozilla.org/MPL/
|
||||
#
|
||||
# Software distributed under the License is distributed on an "AS
|
||||
# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
|
||||
# implied. See the License for the specific language governing
|
||||
# rights and limitations under the License.
|
||||
#
|
||||
# The Original Code is the Netscape security libraries.
|
||||
#
|
||||
# The Initial Developer of the Original Code is Netscape
|
||||
# Communications Corporation. Portions created by Netscape are
|
||||
# Copyright (C) 1994-2000 Netscape Communications Corporation. All
|
||||
# Rights Reserved.
|
||||
#
|
||||
# Contributor(s):
|
||||
#
|
||||
# Alternatively, the contents of this file may be used under the
|
||||
# terms of the GNU General Public License Version 2 or later (the
|
||||
# "GPL"), in which case the provisions of the GPL are applicable
|
||||
# instead of those above. If you wish to allow use of your
|
||||
# version of this file only under the terms of the GPL and not to
|
||||
# allow others to use your version of this file under the MPL,
|
||||
# indicate your decision by deleting the provisions above and
|
||||
# replace them with the notice and other provisions required by
|
||||
# the GPL. If you do not delete the provisions above, a recipient
|
||||
# may use your version of this file under either the MPL or the
|
||||
# GPL.
|
||||
#
|
||||
|
||||
# only do this in the outermost freebl build.
|
||||
ifndef FREEBL_RECURSIVE_BUILD
|
||||
# we only do this stuff for some of the 32-bit builds, no 64-bit builds
|
||||
ifndef USE_64
|
||||
|
||||
ifeq ($(OS_TARGET), HP-UX)
|
||||
ifneq ($(OS_TEST), ia64)
|
||||
FREEBL_EXTENDED_BUILD = 1
|
||||
endif
|
||||
endif
|
||||
|
||||
ifeq ($(OS_TARGET),SunOS)
|
||||
ifeq ($(CPU_ARCH),sparc)
|
||||
FREEBL_EXTENDED_BUILD = 1
|
||||
endif
|
||||
endif
|
||||
|
||||
ifdef FREEBL_EXTENDED_BUILD
|
||||
# We're going to change this build so that it builds libfreebl.a with
|
||||
# just loader.c. Then we have to build this directory twice again to
|
||||
# build the two DSOs.
|
||||
# To build libfreebl.a with just loader.c, we must now override many
|
||||
# of the make variables setup by the prior inclusion of CORECONF's config.mk
|
||||
|
||||
CSRCS = loader.c sysrand.c
|
||||
SIMPLE_OBJS = $(CSRCS:.c=$(OBJ_SUFFIX))
|
||||
OBJS = $(addprefix $(OBJDIR)/$(PROG_PREFIX), $(SIMPLE_OBJS))
|
||||
ALL_TRASH := $(TARGETS) $(OBJS) $(OBJDIR) LOGS TAGS $(GARBAGE) \
|
||||
$(NOSUCHFILE) so_locations
|
||||
endif
|
||||
|
||||
#end of 32-bit only stuff.
|
||||
endif
|
||||
|
||||
# Override the values defined in coreconf's ruleset.mk.
|
||||
#
|
||||
# - (1) LIBRARY: a static (archival) library
|
||||
# - (2) SHARED_LIBRARY: a shared (dynamic link) library
|
||||
# - (3) IMPORT_LIBRARY: an import library, used only on Windows
|
||||
# - (4) PROGRAM: an executable binary
|
||||
#
|
||||
# override these variables to prevent building a DSO/DLL.
|
||||
TARGETS = $(LIBRARY)
|
||||
SHARED_LIBRARY =
|
||||
IMPORT_LIBRARY =
|
||||
PROGRAM =
|
||||
|
||||
else
|
||||
# This is a recursive build.
|
||||
|
||||
TARGETS = $(SHARED_LIBRARY)
|
||||
LIBRARY =
|
||||
PROGRAM =
|
||||
|
||||
#ifeq ($(OS_TARGET), HP-UX)
|
||||
EXTRA_LIBS += \
|
||||
$(DIST)/lib/libsecutil.$(LIB_SUFFIX) \
|
||||
$(NULL)
|
||||
|
||||
# $(PROGRAM) has NO explicit dependencies on $(EXTRA_SHARED_LIBS)
|
||||
# $(EXTRA_SHARED_LIBS) come before $(OS_LIBS), except on AIX.
|
||||
EXTRA_SHARED_LIBS += \
|
||||
-L$(DIST)/lib/ \
|
||||
-lplc4 \
|
||||
-lplds4 \
|
||||
-lnspr4 \
|
||||
-lc
|
||||
#endif
|
||||
|
||||
endif
|
||||
683
mozilla/security/nss/lib/freebl/des.c
Normal file
683
mozilla/security/nss/lib/freebl/des.c
Normal file
@@ -0,0 +1,683 @@
|
||||
/*
|
||||
* des.c
|
||||
*
|
||||
* core source file for DES-150 library
|
||||
* Make key schedule from DES key.
|
||||
* Encrypt/Decrypt one 8-byte block.
|
||||
*
|
||||
* The contents of this file are subject to the Mozilla Public
|
||||
* License Version 1.1 (the "License"); you may not use this file
|
||||
* except in compliance with the License. You may obtain a copy of
|
||||
* the License at http://www.mozilla.org/MPL/
|
||||
*
|
||||
* Software distributed under the License is distributed on an "AS
|
||||
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
|
||||
* implied. See the License for the specific language governing
|
||||
* rights and limitations under the License.
|
||||
*
|
||||
* The Original Code is the DES-150 library.
|
||||
*
|
||||
* The Initial Developer of the Original Code is Nelson B. Bolyard,
|
||||
* nelsonb@iname.com. Portions created by Nelson B. Bolyard are
|
||||
* Copyright (C) 1990, 2000 Nelson B. Bolyard, All Rights Reserved.
|
||||
*
|
||||
* Contributor(s):
|
||||
*
|
||||
* Alternatively, the contents of this file may be used under the
|
||||
* terms of the GNU General Public License Version 2 or later (the
|
||||
* "GPL"), in which case the provisions of the GPL are applicable
|
||||
* instead of those above. If you wish to allow use of your
|
||||
* version of this file only under the terms of the GPL and not to
|
||||
* allow others to use your version of this file under the MPL,
|
||||
* indicate your decision by deleting the provisions above and
|
||||
* replace them with the notice and other provisions required by
|
||||
* the GPL. If you do not delete the provisions above, a recipient
|
||||
* may use your version of this file under either the MPL or the GPL.
|
||||
*/
|
||||
|
||||
#include "des.h"
|
||||
#include <stddef.h> /* for ptrdiff_t */
|
||||
/* #define USE_INDEXING 1 */
|
||||
|
||||
/*
|
||||
* The tables below are the 8 sbox functions, with the 6-bit input permutation
|
||||
* and the 32-bit output permutation pre-computed.
|
||||
* They are shifted circularly to the left 3 bits, which removes 2 shifts
|
||||
* and an or from each round by reducing the number of sboxes whose
|
||||
* indices cross word broundaries from 2 to 1.
|
||||
*/
|
||||
|
||||
static const HALF SP[8][64] = {
|
||||
/* Box S1 */ {
|
||||
0x04041000, 0x00000000, 0x00040000, 0x04041010,
|
||||
0x04040010, 0x00041010, 0x00000010, 0x00040000,
|
||||
0x00001000, 0x04041000, 0x04041010, 0x00001000,
|
||||
0x04001010, 0x04040010, 0x04000000, 0x00000010,
|
||||
0x00001010, 0x04001000, 0x04001000, 0x00041000,
|
||||
0x00041000, 0x04040000, 0x04040000, 0x04001010,
|
||||
0x00040010, 0x04000010, 0x04000010, 0x00040010,
|
||||
0x00000000, 0x00001010, 0x00041010, 0x04000000,
|
||||
0x00040000, 0x04041010, 0x00000010, 0x04040000,
|
||||
0x04041000, 0x04000000, 0x04000000, 0x00001000,
|
||||
0x04040010, 0x00040000, 0x00041000, 0x04000010,
|
||||
0x00001000, 0x00000010, 0x04001010, 0x00041010,
|
||||
0x04041010, 0x00040010, 0x04040000, 0x04001010,
|
||||
0x04000010, 0x00001010, 0x00041010, 0x04041000,
|
||||
0x00001010, 0x04001000, 0x04001000, 0x00000000,
|
||||
0x00040010, 0x00041000, 0x00000000, 0x04040010
|
||||
},
|
||||
/* Box S2 */ {
|
||||
0x00420082, 0x00020002, 0x00020000, 0x00420080,
|
||||
0x00400000, 0x00000080, 0x00400082, 0x00020082,
|
||||
0x00000082, 0x00420082, 0x00420002, 0x00000002,
|
||||
0x00020002, 0x00400000, 0x00000080, 0x00400082,
|
||||
0x00420000, 0x00400080, 0x00020082, 0x00000000,
|
||||
0x00000002, 0x00020000, 0x00420080, 0x00400002,
|
||||
0x00400080, 0x00000082, 0x00000000, 0x00420000,
|
||||
0x00020080, 0x00420002, 0x00400002, 0x00020080,
|
||||
0x00000000, 0x00420080, 0x00400082, 0x00400000,
|
||||
0x00020082, 0x00400002, 0x00420002, 0x00020000,
|
||||
0x00400002, 0x00020002, 0x00000080, 0x00420082,
|
||||
0x00420080, 0x00000080, 0x00020000, 0x00000002,
|
||||
0x00020080, 0x00420002, 0x00400000, 0x00000082,
|
||||
0x00400080, 0x00020082, 0x00000082, 0x00400080,
|
||||
0x00420000, 0x00000000, 0x00020002, 0x00020080,
|
||||
0x00000002, 0x00400082, 0x00420082, 0x00420000
|
||||
},
|
||||
/* Box S3 */ {
|
||||
0x00000820, 0x20080800, 0x00000000, 0x20080020,
|
||||
0x20000800, 0x00000000, 0x00080820, 0x20000800,
|
||||
0x00080020, 0x20000020, 0x20000020, 0x00080000,
|
||||
0x20080820, 0x00080020, 0x20080000, 0x00000820,
|
||||
0x20000000, 0x00000020, 0x20080800, 0x00000800,
|
||||
0x00080800, 0x20080000, 0x20080020, 0x00080820,
|
||||
0x20000820, 0x00080800, 0x00080000, 0x20000820,
|
||||
0x00000020, 0x20080820, 0x00000800, 0x20000000,
|
||||
0x20080800, 0x20000000, 0x00080020, 0x00000820,
|
||||
0x00080000, 0x20080800, 0x20000800, 0x00000000,
|
||||
0x00000800, 0x00080020, 0x20080820, 0x20000800,
|
||||
0x20000020, 0x00000800, 0x00000000, 0x20080020,
|
||||
0x20000820, 0x00080000, 0x20000000, 0x20080820,
|
||||
0x00000020, 0x00080820, 0x00080800, 0x20000020,
|
||||
0x20080000, 0x20000820, 0x00000820, 0x20080000,
|
||||
0x00080820, 0x00000020, 0x20080020, 0x00080800
|
||||
},
|
||||
/* Box S4 */ {
|
||||
0x02008004, 0x00008204, 0x00008204, 0x00000200,
|
||||
0x02008200, 0x02000204, 0x02000004, 0x00008004,
|
||||
0x00000000, 0x02008000, 0x02008000, 0x02008204,
|
||||
0x00000204, 0x00000000, 0x02000200, 0x02000004,
|
||||
0x00000004, 0x00008000, 0x02000000, 0x02008004,
|
||||
0x00000200, 0x02000000, 0x00008004, 0x00008200,
|
||||
0x02000204, 0x00000004, 0x00008200, 0x02000200,
|
||||
0x00008000, 0x02008200, 0x02008204, 0x00000204,
|
||||
0x02000200, 0x02000004, 0x02008000, 0x02008204,
|
||||
0x00000204, 0x00000000, 0x00000000, 0x02008000,
|
||||
0x00008200, 0x02000200, 0x02000204, 0x00000004,
|
||||
0x02008004, 0x00008204, 0x00008204, 0x00000200,
|
||||
0x02008204, 0x00000204, 0x00000004, 0x00008000,
|
||||
0x02000004, 0x00008004, 0x02008200, 0x02000204,
|
||||
0x00008004, 0x00008200, 0x02000000, 0x02008004,
|
||||
0x00000200, 0x02000000, 0x00008000, 0x02008200
|
||||
},
|
||||
/* Box S5 */ {
|
||||
0x00000400, 0x08200400, 0x08200000, 0x08000401,
|
||||
0x00200000, 0x00000400, 0x00000001, 0x08200000,
|
||||
0x00200401, 0x00200000, 0x08000400, 0x00200401,
|
||||
0x08000401, 0x08200001, 0x00200400, 0x00000001,
|
||||
0x08000000, 0x00200001, 0x00200001, 0x00000000,
|
||||
0x00000401, 0x08200401, 0x08200401, 0x08000400,
|
||||
0x08200001, 0x00000401, 0x00000000, 0x08000001,
|
||||
0x08200400, 0x08000000, 0x08000001, 0x00200400,
|
||||
0x00200000, 0x08000401, 0x00000400, 0x08000000,
|
||||
0x00000001, 0x08200000, 0x08000401, 0x00200401,
|
||||
0x08000400, 0x00000001, 0x08200001, 0x08200400,
|
||||
0x00200401, 0x00000400, 0x08000000, 0x08200001,
|
||||
0x08200401, 0x00200400, 0x08000001, 0x08200401,
|
||||
0x08200000, 0x00000000, 0x00200001, 0x08000001,
|
||||
0x00200400, 0x08000400, 0x00000401, 0x00200000,
|
||||
0x00000000, 0x00200001, 0x08200400, 0x00000401
|
||||
},
|
||||
/* Box S6 */ {
|
||||
0x80000040, 0x81000000, 0x00010000, 0x81010040,
|
||||
0x81000000, 0x00000040, 0x81010040, 0x01000000,
|
||||
0x80010000, 0x01010040, 0x01000000, 0x80000040,
|
||||
0x01000040, 0x80010000, 0x80000000, 0x00010040,
|
||||
0x00000000, 0x01000040, 0x80010040, 0x00010000,
|
||||
0x01010000, 0x80010040, 0x00000040, 0x81000040,
|
||||
0x81000040, 0x00000000, 0x01010040, 0x81010000,
|
||||
0x00010040, 0x01010000, 0x81010000, 0x80000000,
|
||||
0x80010000, 0x00000040, 0x81000040, 0x01010000,
|
||||
0x81010040, 0x01000000, 0x00010040, 0x80000040,
|
||||
0x01000000, 0x80010000, 0x80000000, 0x00010040,
|
||||
0x80000040, 0x81010040, 0x01010000, 0x81000000,
|
||||
0x01010040, 0x81010000, 0x00000000, 0x81000040,
|
||||
0x00000040, 0x00010000, 0x81000000, 0x01010040,
|
||||
0x00010000, 0x01000040, 0x80010040, 0x00000000,
|
||||
0x81010000, 0x80000000, 0x01000040, 0x80010040
|
||||
},
|
||||
/* Box S7 */ {
|
||||
0x00800000, 0x10800008, 0x10002008, 0x00000000,
|
||||
0x00002000, 0x10002008, 0x00802008, 0x10802000,
|
||||
0x10802008, 0x00800000, 0x00000000, 0x10000008,
|
||||
0x00000008, 0x10000000, 0x10800008, 0x00002008,
|
||||
0x10002000, 0x00802008, 0x00800008, 0x10002000,
|
||||
0x10000008, 0x10800000, 0x10802000, 0x00800008,
|
||||
0x10800000, 0x00002000, 0x00002008, 0x10802008,
|
||||
0x00802000, 0x00000008, 0x10000000, 0x00802000,
|
||||
0x10000000, 0x00802000, 0x00800000, 0x10002008,
|
||||
0x10002008, 0x10800008, 0x10800008, 0x00000008,
|
||||
0x00800008, 0x10000000, 0x10002000, 0x00800000,
|
||||
0x10802000, 0x00002008, 0x00802008, 0x10802000,
|
||||
0x00002008, 0x10000008, 0x10802008, 0x10800000,
|
||||
0x00802000, 0x00000000, 0x00000008, 0x10802008,
|
||||
0x00000000, 0x00802008, 0x10800000, 0x00002000,
|
||||
0x10000008, 0x10002000, 0x00002000, 0x00800008
|
||||
},
|
||||
/* Box S8 */ {
|
||||
0x40004100, 0x00004000, 0x00100000, 0x40104100,
|
||||
0x40000000, 0x40004100, 0x00000100, 0x40000000,
|
||||
0x00100100, 0x40100000, 0x40104100, 0x00104000,
|
||||
0x40104000, 0x00104100, 0x00004000, 0x00000100,
|
||||
0x40100000, 0x40000100, 0x40004000, 0x00004100,
|
||||
0x00104000, 0x00100100, 0x40100100, 0x40104000,
|
||||
0x00004100, 0x00000000, 0x00000000, 0x40100100,
|
||||
0x40000100, 0x40004000, 0x00104100, 0x00100000,
|
||||
0x00104100, 0x00100000, 0x40104000, 0x00004000,
|
||||
0x00000100, 0x40100100, 0x00004000, 0x00104100,
|
||||
0x40004000, 0x00000100, 0x40000100, 0x40100000,
|
||||
0x40100100, 0x40000000, 0x00100000, 0x40004100,
|
||||
0x00000000, 0x40104100, 0x00100100, 0x40000100,
|
||||
0x40100000, 0x40004000, 0x40004100, 0x00000000,
|
||||
0x40104100, 0x00104000, 0x00104000, 0x00004100,
|
||||
0x00004100, 0x00100100, 0x40000000, 0x40104000
|
||||
}
|
||||
};
|
||||
|
||||
static const HALF PC2[8][64] = {
|
||||
/* table 0 */ {
|
||||
0x00000000, 0x00001000, 0x04000000, 0x04001000,
|
||||
0x00100000, 0x00101000, 0x04100000, 0x04101000,
|
||||
0x00008000, 0x00009000, 0x04008000, 0x04009000,
|
||||
0x00108000, 0x00109000, 0x04108000, 0x04109000,
|
||||
0x00000004, 0x00001004, 0x04000004, 0x04001004,
|
||||
0x00100004, 0x00101004, 0x04100004, 0x04101004,
|
||||
0x00008004, 0x00009004, 0x04008004, 0x04009004,
|
||||
0x00108004, 0x00109004, 0x04108004, 0x04109004,
|
||||
0x08000000, 0x08001000, 0x0c000000, 0x0c001000,
|
||||
0x08100000, 0x08101000, 0x0c100000, 0x0c101000,
|
||||
0x08008000, 0x08009000, 0x0c008000, 0x0c009000,
|
||||
0x08108000, 0x08109000, 0x0c108000, 0x0c109000,
|
||||
0x08000004, 0x08001004, 0x0c000004, 0x0c001004,
|
||||
0x08100004, 0x08101004, 0x0c100004, 0x0c101004,
|
||||
0x08008004, 0x08009004, 0x0c008004, 0x0c009004,
|
||||
0x08108004, 0x08109004, 0x0c108004, 0x0c109004
|
||||
},
|
||||
/* table 1 */ {
|
||||
0x00000000, 0x00002000, 0x80000000, 0x80002000,
|
||||
0x00000008, 0x00002008, 0x80000008, 0x80002008,
|
||||
0x00200000, 0x00202000, 0x80200000, 0x80202000,
|
||||
0x00200008, 0x00202008, 0x80200008, 0x80202008,
|
||||
0x20000000, 0x20002000, 0xa0000000, 0xa0002000,
|
||||
0x20000008, 0x20002008, 0xa0000008, 0xa0002008,
|
||||
0x20200000, 0x20202000, 0xa0200000, 0xa0202000,
|
||||
0x20200008, 0x20202008, 0xa0200008, 0xa0202008,
|
||||
0x00000400, 0x00002400, 0x80000400, 0x80002400,
|
||||
0x00000408, 0x00002408, 0x80000408, 0x80002408,
|
||||
0x00200400, 0x00202400, 0x80200400, 0x80202400,
|
||||
0x00200408, 0x00202408, 0x80200408, 0x80202408,
|
||||
0x20000400, 0x20002400, 0xa0000400, 0xa0002400,
|
||||
0x20000408, 0x20002408, 0xa0000408, 0xa0002408,
|
||||
0x20200400, 0x20202400, 0xa0200400, 0xa0202400,
|
||||
0x20200408, 0x20202408, 0xa0200408, 0xa0202408
|
||||
},
|
||||
/* table 2 */ {
|
||||
0x00000000, 0x00004000, 0x00000020, 0x00004020,
|
||||
0x00080000, 0x00084000, 0x00080020, 0x00084020,
|
||||
0x00000800, 0x00004800, 0x00000820, 0x00004820,
|
||||
0x00080800, 0x00084800, 0x00080820, 0x00084820,
|
||||
0x00000010, 0x00004010, 0x00000030, 0x00004030,
|
||||
0x00080010, 0x00084010, 0x00080030, 0x00084030,
|
||||
0x00000810, 0x00004810, 0x00000830, 0x00004830,
|
||||
0x00080810, 0x00084810, 0x00080830, 0x00084830,
|
||||
0x00400000, 0x00404000, 0x00400020, 0x00404020,
|
||||
0x00480000, 0x00484000, 0x00480020, 0x00484020,
|
||||
0x00400800, 0x00404800, 0x00400820, 0x00404820,
|
||||
0x00480800, 0x00484800, 0x00480820, 0x00484820,
|
||||
0x00400010, 0x00404010, 0x00400030, 0x00404030,
|
||||
0x00480010, 0x00484010, 0x00480030, 0x00484030,
|
||||
0x00400810, 0x00404810, 0x00400830, 0x00404830,
|
||||
0x00480810, 0x00484810, 0x00480830, 0x00484830
|
||||
},
|
||||
/* table 3 */ {
|
||||
0x00000000, 0x40000000, 0x00000080, 0x40000080,
|
||||
0x00040000, 0x40040000, 0x00040080, 0x40040080,
|
||||
0x00000040, 0x40000040, 0x000000c0, 0x400000c0,
|
||||
0x00040040, 0x40040040, 0x000400c0, 0x400400c0,
|
||||
0x10000000, 0x50000000, 0x10000080, 0x50000080,
|
||||
0x10040000, 0x50040000, 0x10040080, 0x50040080,
|
||||
0x10000040, 0x50000040, 0x100000c0, 0x500000c0,
|
||||
0x10040040, 0x50040040, 0x100400c0, 0x500400c0,
|
||||
0x00800000, 0x40800000, 0x00800080, 0x40800080,
|
||||
0x00840000, 0x40840000, 0x00840080, 0x40840080,
|
||||
0x00800040, 0x40800040, 0x008000c0, 0x408000c0,
|
||||
0x00840040, 0x40840040, 0x008400c0, 0x408400c0,
|
||||
0x10800000, 0x50800000, 0x10800080, 0x50800080,
|
||||
0x10840000, 0x50840000, 0x10840080, 0x50840080,
|
||||
0x10800040, 0x50800040, 0x108000c0, 0x508000c0,
|
||||
0x10840040, 0x50840040, 0x108400c0, 0x508400c0
|
||||
},
|
||||
/* table 4 */ {
|
||||
0x00000000, 0x00000008, 0x08000000, 0x08000008,
|
||||
0x00040000, 0x00040008, 0x08040000, 0x08040008,
|
||||
0x00002000, 0x00002008, 0x08002000, 0x08002008,
|
||||
0x00042000, 0x00042008, 0x08042000, 0x08042008,
|
||||
0x80000000, 0x80000008, 0x88000000, 0x88000008,
|
||||
0x80040000, 0x80040008, 0x88040000, 0x88040008,
|
||||
0x80002000, 0x80002008, 0x88002000, 0x88002008,
|
||||
0x80042000, 0x80042008, 0x88042000, 0x88042008,
|
||||
0x00080000, 0x00080008, 0x08080000, 0x08080008,
|
||||
0x000c0000, 0x000c0008, 0x080c0000, 0x080c0008,
|
||||
0x00082000, 0x00082008, 0x08082000, 0x08082008,
|
||||
0x000c2000, 0x000c2008, 0x080c2000, 0x080c2008,
|
||||
0x80080000, 0x80080008, 0x88080000, 0x88080008,
|
||||
0x800c0000, 0x800c0008, 0x880c0000, 0x880c0008,
|
||||
0x80082000, 0x80082008, 0x88082000, 0x88082008,
|
||||
0x800c2000, 0x800c2008, 0x880c2000, 0x880c2008
|
||||
},
|
||||
/* table 5 */ {
|
||||
0x00000000, 0x00400000, 0x00008000, 0x00408000,
|
||||
0x40000000, 0x40400000, 0x40008000, 0x40408000,
|
||||
0x00000020, 0x00400020, 0x00008020, 0x00408020,
|
||||
0x40000020, 0x40400020, 0x40008020, 0x40408020,
|
||||
0x00001000, 0x00401000, 0x00009000, 0x00409000,
|
||||
0x40001000, 0x40401000, 0x40009000, 0x40409000,
|
||||
0x00001020, 0x00401020, 0x00009020, 0x00409020,
|
||||
0x40001020, 0x40401020, 0x40009020, 0x40409020,
|
||||
0x00100000, 0x00500000, 0x00108000, 0x00508000,
|
||||
0x40100000, 0x40500000, 0x40108000, 0x40508000,
|
||||
0x00100020, 0x00500020, 0x00108020, 0x00508020,
|
||||
0x40100020, 0x40500020, 0x40108020, 0x40508020,
|
||||
0x00101000, 0x00501000, 0x00109000, 0x00509000,
|
||||
0x40101000, 0x40501000, 0x40109000, 0x40509000,
|
||||
0x00101020, 0x00501020, 0x00109020, 0x00509020,
|
||||
0x40101020, 0x40501020, 0x40109020, 0x40509020
|
||||
},
|
||||
/* table 6 */ {
|
||||
0x00000000, 0x00000040, 0x04000000, 0x04000040,
|
||||
0x00000800, 0x00000840, 0x04000800, 0x04000840,
|
||||
0x00800000, 0x00800040, 0x04800000, 0x04800040,
|
||||
0x00800800, 0x00800840, 0x04800800, 0x04800840,
|
||||
0x10000000, 0x10000040, 0x14000000, 0x14000040,
|
||||
0x10000800, 0x10000840, 0x14000800, 0x14000840,
|
||||
0x10800000, 0x10800040, 0x14800000, 0x14800040,
|
||||
0x10800800, 0x10800840, 0x14800800, 0x14800840,
|
||||
0x00000080, 0x000000c0, 0x04000080, 0x040000c0,
|
||||
0x00000880, 0x000008c0, 0x04000880, 0x040008c0,
|
||||
0x00800080, 0x008000c0, 0x04800080, 0x048000c0,
|
||||
0x00800880, 0x008008c0, 0x04800880, 0x048008c0,
|
||||
0x10000080, 0x100000c0, 0x14000080, 0x140000c0,
|
||||
0x10000880, 0x100008c0, 0x14000880, 0x140008c0,
|
||||
0x10800080, 0x108000c0, 0x14800080, 0x148000c0,
|
||||
0x10800880, 0x108008c0, 0x14800880, 0x148008c0
|
||||
},
|
||||
/* table 7 */ {
|
||||
0x00000000, 0x00000010, 0x00000400, 0x00000410,
|
||||
0x00000004, 0x00000014, 0x00000404, 0x00000414,
|
||||
0x00004000, 0x00004010, 0x00004400, 0x00004410,
|
||||
0x00004004, 0x00004014, 0x00004404, 0x00004414,
|
||||
0x20000000, 0x20000010, 0x20000400, 0x20000410,
|
||||
0x20000004, 0x20000014, 0x20000404, 0x20000414,
|
||||
0x20004000, 0x20004010, 0x20004400, 0x20004410,
|
||||
0x20004004, 0x20004014, 0x20004404, 0x20004414,
|
||||
0x00200000, 0x00200010, 0x00200400, 0x00200410,
|
||||
0x00200004, 0x00200014, 0x00200404, 0x00200414,
|
||||
0x00204000, 0x00204010, 0x00204400, 0x00204410,
|
||||
0x00204004, 0x00204014, 0x00204404, 0x00204414,
|
||||
0x20200000, 0x20200010, 0x20200400, 0x20200410,
|
||||
0x20200004, 0x20200014, 0x20200404, 0x20200414,
|
||||
0x20204000, 0x20204010, 0x20204400, 0x20204410,
|
||||
0x20204004, 0x20204014, 0x20204404, 0x20204414
|
||||
}
|
||||
};
|
||||
|
||||
/*
|
||||
* The PC-1 Permutation
|
||||
* If we number the bits of the 8 bytes of key input like this (in octal):
|
||||
* 00 01 02 03 04 05 06 07
|
||||
* 10 11 12 13 14 15 16 17
|
||||
* 20 21 22 23 24 25 26 27
|
||||
* 30 31 32 33 34 35 36 37
|
||||
* 40 41 42 43 44 45 46 47
|
||||
* 50 51 52 53 54 55 56 57
|
||||
* 60 61 62 63 64 65 66 67
|
||||
* 70 71 72 73 74 75 76 77
|
||||
* then after the PC-1 permutation,
|
||||
* C0 is
|
||||
* 70 60 50 40 30 20 10 00
|
||||
* 71 61 51 41 31 21 11 01
|
||||
* 72 62 52 42 32 22 12 02
|
||||
* 73 63 53 43
|
||||
* D0 is
|
||||
* 76 66 56 46 36 26 16 06
|
||||
* 75 65 55 45 35 25 15 05
|
||||
* 74 64 54 44 34 24 14 04
|
||||
* 33 23 13 03
|
||||
* and these parity bits have been discarded:
|
||||
* 77 67 57 47 37 27 17 07
|
||||
*
|
||||
* We achieve this by flipping the input matrix about the diagonal from 70-07,
|
||||
* getting left =
|
||||
* 77 67 57 47 37 27 17 07 (these are the parity bits)
|
||||
* 76 66 56 46 36 26 16 06
|
||||
* 75 65 55 45 35 25 15 05
|
||||
* 74 64 54 44 34 24 14 04
|
||||
* right =
|
||||
* 73 63 53 43 33 23 13 03
|
||||
* 72 62 52 42 32 22 12 02
|
||||
* 71 61 51 41 31 21 11 01
|
||||
* 70 60 50 40 30 20 10 00
|
||||
* then byte swap right, ala htonl() on a little endian machine.
|
||||
* right =
|
||||
* 70 60 50 40 30 20 10 00
|
||||
* 71 67 57 47 37 27 11 07
|
||||
* 72 62 52 42 32 22 12 02
|
||||
* 73 63 53 43 33 23 13 03
|
||||
* then
|
||||
* c0 = right >> 4;
|
||||
* d0 = ((left & 0x00ffffff) << 4) | (right & 0xf);
|
||||
*/
|
||||
|
||||
#define FLIP_RIGHT_DIAGONAL(word, temp) \
|
||||
temp = (word ^ (word >> 18)) & 0x00003333; \
|
||||
word ^= temp | (temp << 18); \
|
||||
temp = (word ^ (word >> 9)) & 0x00550055; \
|
||||
word ^= temp | (temp << 9);
|
||||
|
||||
#define BYTESWAP(word, temp) \
|
||||
word = (word >> 16) | (word << 16); \
|
||||
temp = 0x00ff00ff; \
|
||||
word = ((word & temp) << 8) | ((word >> 8) & temp);
|
||||
|
||||
#define PC1(left, right, c0, d0, temp) \
|
||||
right ^= temp = ((left >> 4) ^ right) & 0x0f0f0f0f; \
|
||||
left ^= temp << 4; \
|
||||
FLIP_RIGHT_DIAGONAL(left, temp); \
|
||||
FLIP_RIGHT_DIAGONAL(right, temp); \
|
||||
BYTESWAP(right, temp); \
|
||||
c0 = right >> 4; \
|
||||
d0 = ((left & 0x00ffffff) << 4) | (right & 0xf);
|
||||
|
||||
#define LEFT_SHIFT_1( reg ) (((reg << 1) | (reg >> 27)) & 0x0FFFFFFF)
|
||||
#define LEFT_SHIFT_2( reg ) (((reg << 2) | (reg >> 26)) & 0x0FFFFFFF)
|
||||
|
||||
/*
|
||||
* setup key schedules from key
|
||||
*/
|
||||
|
||||
void
|
||||
DES_MakeSchedule( HALF * ks, const BYTE * key, DESDirection direction)
|
||||
{
|
||||
register HALF left, right;
|
||||
register HALF c0, d0;
|
||||
register HALF temp;
|
||||
int delta;
|
||||
unsigned int ls;
|
||||
|
||||
#if defined(_X86_)
|
||||
left = HALFPTR(key)[0];
|
||||
right = HALFPTR(key)[1];
|
||||
BYTESWAP(left, temp);
|
||||
BYTESWAP(right, temp);
|
||||
#else
|
||||
if (((ptrdiff_t)key & 0x03) == 0) {
|
||||
left = HALFPTR(key)[0];
|
||||
right = HALFPTR(key)[1];
|
||||
#if defined(IS_LITTLE_ENDIAN)
|
||||
BYTESWAP(left, temp);
|
||||
BYTESWAP(right, temp);
|
||||
#endif
|
||||
} else {
|
||||
left = ((HALF)key[0] << 24) | ((HALF)key[1] << 16) |
|
||||
((HALF)key[2] << 8) | key[3];
|
||||
right = ((HALF)key[4] << 24) | ((HALF)key[5] << 16) |
|
||||
((HALF)key[6] << 8) | key[7];
|
||||
}
|
||||
#endif
|
||||
|
||||
PC1(left, right, c0, d0, temp);
|
||||
|
||||
if (direction == DES_ENCRYPT) {
|
||||
delta = 2 * (int)sizeof(HALF);
|
||||
} else {
|
||||
ks += 30;
|
||||
delta = (-2) * (int)sizeof(HALF);
|
||||
}
|
||||
|
||||
for (ls = 0x8103; ls; ls >>= 1) {
|
||||
if ( ls & 1 ) {
|
||||
c0 = LEFT_SHIFT_1( c0 );
|
||||
d0 = LEFT_SHIFT_1( d0 );
|
||||
} else {
|
||||
c0 = LEFT_SHIFT_2( c0 );
|
||||
d0 = LEFT_SHIFT_2( d0 );
|
||||
}
|
||||
|
||||
#ifdef USE_INDEXING
|
||||
#define PC2LOOKUP(b,c) PC2[b][c]
|
||||
|
||||
left = PC2LOOKUP(0, ((c0 >> 22) & 0x3F) );
|
||||
left |= PC2LOOKUP(1, ((c0 >> 13) & 0x3F) );
|
||||
left |= PC2LOOKUP(2, ((c0 >> 4) & 0x38) | (c0 & 0x7) );
|
||||
left |= PC2LOOKUP(3, ((c0>>18)&0xC) | ((c0>>11)&0x3) | (c0&0x30));
|
||||
|
||||
right = PC2LOOKUP(4, ((d0 >> 22) & 0x3F) );
|
||||
right |= PC2LOOKUP(5, ((d0 >> 15) & 0x30) | ((d0 >> 14) & 0xf) );
|
||||
right |= PC2LOOKUP(6, ((d0 >> 7) & 0x3F) );
|
||||
right |= PC2LOOKUP(7, ((d0 >> 1) & 0x3C) | (d0 & 0x3));
|
||||
#else
|
||||
#define PC2LOOKUP(b,c) *(HALF *)((BYTE *)&PC2[b][0]+(c))
|
||||
|
||||
left = PC2LOOKUP(0, ((c0 >> 20) & 0xFC) );
|
||||
left |= PC2LOOKUP(1, ((c0 >> 11) & 0xFC) );
|
||||
left |= PC2LOOKUP(2, ((c0 >> 2) & 0xE0) | ((c0 << 2) & 0x1C) );
|
||||
left |= PC2LOOKUP(3, ((c0>>16)&0x30)|((c0>>9)&0xC)|((c0<<2)&0xC0));
|
||||
|
||||
right = PC2LOOKUP(4, ((d0 >> 20) & 0xFC) );
|
||||
right |= PC2LOOKUP(5, ((d0 >> 13) & 0xC0) | ((d0 >> 12) & 0x3C) );
|
||||
right |= PC2LOOKUP(6, ((d0 >> 5) & 0xFC) );
|
||||
right |= PC2LOOKUP(7, ((d0 << 1) & 0xF0) | ((d0 << 2) & 0x0C));
|
||||
#endif
|
||||
/* left contains key bits for S1 S3 S2 S4 */
|
||||
/* right contains key bits for S6 S8 S5 S7 */
|
||||
temp = (left << 16) /* S2 S4 XX XX */
|
||||
| (right >> 16); /* XX XX S6 S8 */
|
||||
ks[0] = temp;
|
||||
|
||||
temp = (left & 0xffff0000) /* S1 S3 XX XX */
|
||||
| (right & 0x0000ffff);/* XX XX S5 S7 */
|
||||
ks[1] = temp;
|
||||
|
||||
ks = (HALF*)((BYTE *)ks + delta);
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* The DES Initial Permutation
|
||||
* if we number the bits of the 8 bytes of input like this (in octal):
|
||||
* 00 01 02 03 04 05 06 07
|
||||
* 10 11 12 13 14 15 16 17
|
||||
* 20 21 22 23 24 25 26 27
|
||||
* 30 31 32 33 34 35 36 37
|
||||
* 40 41 42 43 44 45 46 47
|
||||
* 50 51 52 53 54 55 56 57
|
||||
* 60 61 62 63 64 65 66 67
|
||||
* 70 71 72 73 74 75 76 77
|
||||
* then after the initial permutation, they will be in this order.
|
||||
* 71 61 51 41 31 21 11 01
|
||||
* 73 63 53 43 33 23 13 03
|
||||
* 75 65 55 45 35 25 15 05
|
||||
* 77 67 57 47 37 27 17 07
|
||||
* 70 60 50 40 30 20 10 00
|
||||
* 72 62 52 42 32 22 12 02
|
||||
* 74 64 54 44 34 24 14 04
|
||||
* 76 66 56 46 36 26 16 06
|
||||
*
|
||||
* One way to do this is in two steps:
|
||||
* 1. Flip this matrix about the diagonal from 70-07 as done for PC1.
|
||||
* 2. Rearrange the bytes (rows in the matrix above) with the following code.
|
||||
*
|
||||
* #define swapHiLo(word, temp) \
|
||||
* temp = (word ^ (word >> 24)) & 0x000000ff; \
|
||||
* word ^= temp | (temp << 24);
|
||||
*
|
||||
* right ^= temp = ((left << 8) ^ right) & 0xff00ff00;
|
||||
* left ^= temp >> 8;
|
||||
* swapHiLo(left, temp);
|
||||
* swapHiLo(right,temp);
|
||||
*
|
||||
* However, the two steps can be combined, so that the rows are rearranged
|
||||
* while the matrix is being flipped, reducing the number of bit exchange
|
||||
* operations from 8 ot 5.
|
||||
*
|
||||
* Initial Permutation */
|
||||
#define IP(left, right, temp) \
|
||||
right ^= temp = ((left >> 4) ^ right) & 0x0f0f0f0f; \
|
||||
left ^= temp << 4; \
|
||||
right ^= temp = ((left >> 16) ^ right) & 0x0000ffff; \
|
||||
left ^= temp << 16; \
|
||||
right ^= temp = ((left << 2) ^ right) & 0xcccccccc; \
|
||||
left ^= temp >> 2; \
|
||||
right ^= temp = ((left << 8) ^ right) & 0xff00ff00; \
|
||||
left ^= temp >> 8; \
|
||||
right ^= temp = ((left >> 1) ^ right) & 0x55555555; \
|
||||
left ^= temp << 1;
|
||||
|
||||
/* The Final (Inverse Initial) permutation is done by reversing the
|
||||
** steps of the Initital Permutation
|
||||
*/
|
||||
|
||||
#define FP(left, right, temp) \
|
||||
right ^= temp = ((left >> 1) ^ right) & 0x55555555; \
|
||||
left ^= temp << 1; \
|
||||
right ^= temp = ((left << 8) ^ right) & 0xff00ff00; \
|
||||
left ^= temp >> 8; \
|
||||
right ^= temp = ((left << 2) ^ right) & 0xcccccccc; \
|
||||
left ^= temp >> 2; \
|
||||
right ^= temp = ((left >> 16) ^ right) & 0x0000ffff; \
|
||||
left ^= temp << 16; \
|
||||
right ^= temp = ((left >> 4) ^ right) & 0x0f0f0f0f; \
|
||||
left ^= temp << 4;
|
||||
|
||||
void
|
||||
DES_Do1Block(HALF * ks, const BYTE * inbuf, BYTE * outbuf)
|
||||
{
|
||||
register HALF left, right;
|
||||
register HALF temp;
|
||||
|
||||
#if defined(_X86_)
|
||||
left = HALFPTR(inbuf)[0];
|
||||
right = HALFPTR(inbuf)[1];
|
||||
BYTESWAP(left, temp);
|
||||
BYTESWAP(right, temp);
|
||||
#else
|
||||
if (((ptrdiff_t)inbuf & 0x03) == 0) {
|
||||
left = HALFPTR(inbuf)[0];
|
||||
right = HALFPTR(inbuf)[1];
|
||||
#if defined(IS_LITTLE_ENDIAN)
|
||||
BYTESWAP(left, temp);
|
||||
BYTESWAP(right, temp);
|
||||
#endif
|
||||
} else {
|
||||
left = ((HALF)inbuf[0] << 24) | ((HALF)inbuf[1] << 16) |
|
||||
((HALF)inbuf[2] << 8) | inbuf[3];
|
||||
right = ((HALF)inbuf[4] << 24) | ((HALF)inbuf[5] << 16) |
|
||||
((HALF)inbuf[6] << 8) | inbuf[7];
|
||||
}
|
||||
#endif
|
||||
|
||||
IP(left, right, temp);
|
||||
|
||||
/* shift the values left circularly 3 bits. */
|
||||
left = (left << 3) | (left >> 29);
|
||||
right = (right << 3) | (right >> 29);
|
||||
|
||||
#ifdef USE_INDEXING
|
||||
#define KSLOOKUP(s,b) SP[s][((temp >> (b+2)) & 0x3f)]
|
||||
#else
|
||||
#define KSLOOKUP(s,b) *(HALF*)((BYTE*)&SP[s][0]+((temp >> b) & 0xFC))
|
||||
#endif
|
||||
#define ROUND(out, in, r) \
|
||||
temp = in ^ ks[2*r]; \
|
||||
out ^= KSLOOKUP( 1, 24 ); \
|
||||
out ^= KSLOOKUP( 3, 16 ); \
|
||||
out ^= KSLOOKUP( 5, 8 ); \
|
||||
out ^= KSLOOKUP( 7, 0 ); \
|
||||
temp = ((in >> 4) | (in << 28)) ^ ks[2*r+1]; \
|
||||
out ^= KSLOOKUP( 0, 24 ); \
|
||||
out ^= KSLOOKUP( 2, 16 ); \
|
||||
out ^= KSLOOKUP( 4, 8 ); \
|
||||
out ^= KSLOOKUP( 6, 0 );
|
||||
|
||||
/* Do the 16 Feistel rounds */
|
||||
ROUND(left, right, 0)
|
||||
ROUND(right, left, 1)
|
||||
ROUND(left, right, 2)
|
||||
ROUND(right, left, 3)
|
||||
ROUND(left, right, 4)
|
||||
ROUND(right, left, 5)
|
||||
ROUND(left, right, 6)
|
||||
ROUND(right, left, 7)
|
||||
ROUND(left, right, 8)
|
||||
ROUND(right, left, 9)
|
||||
ROUND(left, right, 10)
|
||||
ROUND(right, left, 11)
|
||||
ROUND(left, right, 12)
|
||||
ROUND(right, left, 13)
|
||||
ROUND(left, right, 14)
|
||||
ROUND(right, left, 15)
|
||||
|
||||
/* now shift circularly right 3 bits to undo the shifting done
|
||||
** above. switch left and right here.
|
||||
*/
|
||||
temp = (left >> 3) | (left << 29);
|
||||
left = (right >> 3) | (right << 29);
|
||||
right = temp;
|
||||
|
||||
FP(left, right, temp);
|
||||
|
||||
#if defined(_X86_)
|
||||
BYTESWAP(left, temp);
|
||||
BYTESWAP(right, temp);
|
||||
HALFPTR(outbuf)[0] = left;
|
||||
HALFPTR(outbuf)[1] = right;
|
||||
#else
|
||||
if (((ptrdiff_t)inbuf & 0x03) == 0) {
|
||||
#if defined(IS_LITTLE_ENDIAN)
|
||||
BYTESWAP(left, temp);
|
||||
BYTESWAP(right, temp);
|
||||
#endif
|
||||
HALFPTR(outbuf)[0] = left;
|
||||
HALFPTR(outbuf)[1] = right;
|
||||
} else {
|
||||
outbuf[0] = (BYTE)(left >> 24);
|
||||
outbuf[1] = (BYTE)(left >> 16);
|
||||
outbuf[2] = (BYTE)(left >> 8);
|
||||
outbuf[3] = (BYTE)(left );
|
||||
|
||||
outbuf[4] = (BYTE)(right >> 24);
|
||||
outbuf[5] = (BYTE)(right >> 16);
|
||||
outbuf[6] = (BYTE)(right >> 8);
|
||||
outbuf[7] = (BYTE)(right );
|
||||
}
|
||||
#endif
|
||||
|
||||
}
|
||||
|
||||
/* Ackowledgements:
|
||||
** Two ideas used in this implementation were shown to me by Dennis Ferguson
|
||||
** in 1990. He credits them to Richard Outerbridge and Dan Hoey. They were:
|
||||
** 1. The method of computing the Initial and Final permutations.
|
||||
** 2. Circularly rotating the SP tables and the initial values of left and
|
||||
** right to reduce the number of shifts required during the 16 rounds.
|
||||
*/
|
||||
69
mozilla/security/nss/lib/freebl/des.h
Normal file
69
mozilla/security/nss/lib/freebl/des.h
Normal file
@@ -0,0 +1,69 @@
|
||||
/*
|
||||
* des.h
|
||||
*
|
||||
* header file for DES-150 library
|
||||
*
|
||||
* The contents of this file are subject to the Mozilla Public
|
||||
* License Version 1.1 (the "License"); you may not use this file
|
||||
* except in compliance with the License. You may obtain a copy of
|
||||
* the License at http://www.mozilla.org/MPL/
|
||||
*
|
||||
* Software distributed under the License is distributed on an "AS
|
||||
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
|
||||
* implied. See the License for the specific language governing
|
||||
* rights and limitations under the License.
|
||||
*
|
||||
* The Original Code is the DES-150 library.
|
||||
*
|
||||
* The Initial Developer of the Original Code is Nelson B. Bolyard,
|
||||
* nelsonb@iname.com. Portions created by Nelson B. Bolyard are
|
||||
* Copyright (C) 1990, 2000 Nelson B. Bolyard, All Rights Reserved.
|
||||
*
|
||||
* Contributor(s):
|
||||
*
|
||||
* Alternatively, the contents of this file may be used under the
|
||||
* terms of the GNU General Public License Version 2 or later (the
|
||||
* "GPL"), in which case the provisions of the GPL are applicable
|
||||
* instead of those above. If you wish to allow use of your
|
||||
* version of this file only under the terms of the GPL and not to
|
||||
* allow others to use your version of this file under the MPL,
|
||||
* indicate your decision by deleting the provisions above and
|
||||
* replace them with the notice and other provisions required by
|
||||
* the GPL. If you do not delete the provisions above, a recipient
|
||||
* may use your version of this file under either the MPL or the GPL.
|
||||
*/
|
||||
|
||||
#ifndef _DES_H_
|
||||
#define _DES_H_ 1
|
||||
|
||||
#include "blapi.h"
|
||||
|
||||
typedef unsigned char BYTE;
|
||||
typedef unsigned int HALF;
|
||||
|
||||
#define HALFPTR(x) ((HALF *)(x))
|
||||
#define SHORTPTR(x) ((unsigned short *)(x))
|
||||
#define BYTEPTR(x) ((BYTE *)(x))
|
||||
|
||||
typedef enum {
|
||||
DES_ENCRYPT = 0x5555,
|
||||
DES_DECRYPT = 0xAAAA
|
||||
} DESDirection;
|
||||
|
||||
typedef void DESFunc(struct DESContextStr *cx, BYTE *out, const BYTE *in,
|
||||
unsigned int len);
|
||||
|
||||
struct DESContextStr {
|
||||
/* key schedule, 16 internal keys, each with 8 6-bit parts */
|
||||
HALF ks0 [32];
|
||||
HALF ks1 [32];
|
||||
HALF ks2 [32];
|
||||
HALF iv [2];
|
||||
DESDirection direction;
|
||||
DESFunc *worker;
|
||||
};
|
||||
|
||||
void DES_MakeSchedule( HALF * ks, const BYTE * key, DESDirection direction);
|
||||
void DES_Do1Block( HALF * ks, const BYTE * inbuf, BYTE * outbuf);
|
||||
|
||||
#endif
|
||||
275
mozilla/security/nss/lib/freebl/desblapi.c
Normal file
275
mozilla/security/nss/lib/freebl/desblapi.c
Normal file
@@ -0,0 +1,275 @@
|
||||
/*
|
||||
* desblapi.c
|
||||
*
|
||||
* core source file for DES-150 library
|
||||
* Implement DES Modes of Operation and Triple-DES.
|
||||
* Adapt DES-150 to blapi API.
|
||||
*
|
||||
* The contents of this file are subject to the Mozilla Public
|
||||
* License Version 1.1 (the "License"); you may not use this file
|
||||
* except in compliance with the License. You may obtain a copy of
|
||||
* the License at http://www.mozilla.org/MPL/
|
||||
*
|
||||
* Software distributed under the License is distributed on an "AS
|
||||
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
|
||||
* implied. See the License for the specific language governing
|
||||
* rights and limitations under the License.
|
||||
*
|
||||
* The Original Code is the DES-150 library.
|
||||
*
|
||||
* The Initial Developer of the Original Code is Nelson B. Bolyard,
|
||||
* nelsonb@iname.com. Portions created by Nelson B. Bolyard are
|
||||
* Copyright (C) 1990, 2000 Nelson B. Bolyard, All Rights Reserved.
|
||||
*
|
||||
* Contributor(s):
|
||||
*
|
||||
* Alternatively, the contents of this file may be used under the
|
||||
* terms of the GNU General Public License Version 2 or later (the
|
||||
* "GPL"), in which case the provisions of the GPL are applicable
|
||||
* instead of those above. If you wish to allow use of your
|
||||
* version of this file only under the terms of the GPL and not to
|
||||
* allow others to use your version of this file under the MPL,
|
||||
* indicate your decision by deleting the provisions above and
|
||||
* replace them with the notice and other provisions required by
|
||||
* the GPL. If you do not delete the provisions above, a recipient
|
||||
* may use your version of this file under either the MPL or the GPL.
|
||||
*/
|
||||
|
||||
#include "des.h"
|
||||
#include <stddef.h>
|
||||
#include "secerr.h"
|
||||
|
||||
#if defined(_X86_)
|
||||
/* Intel X86 CPUs do unaligned loads and stores without complaint. */
|
||||
#define COPY8B(to, from, ptr) \
|
||||
HALFPTR(to)[0] = HALFPTR(from)[0]; \
|
||||
HALFPTR(to)[1] = HALFPTR(from)[1];
|
||||
#elif defined(USE_MEMCPY)
|
||||
#define COPY8B(to, from, ptr) memcpy(to, from, 8)
|
||||
#else
|
||||
#define COPY8B(to, from, ptr) \
|
||||
if (((ptrdiff_t)(ptr) & 0x3) == 0) { \
|
||||
HALFPTR(to)[0] = HALFPTR(from)[0]; \
|
||||
HALFPTR(to)[1] = HALFPTR(from)[1]; \
|
||||
} else if (((ptrdiff_t)(ptr) & 0x1) == 0) { \
|
||||
SHORTPTR(to)[0] = SHORTPTR(from)[0]; \
|
||||
SHORTPTR(to)[1] = SHORTPTR(from)[1]; \
|
||||
SHORTPTR(to)[2] = SHORTPTR(from)[2]; \
|
||||
SHORTPTR(to)[3] = SHORTPTR(from)[3]; \
|
||||
} else { \
|
||||
BYTEPTR(to)[0] = BYTEPTR(from)[0]; \
|
||||
BYTEPTR(to)[1] = BYTEPTR(from)[1]; \
|
||||
BYTEPTR(to)[2] = BYTEPTR(from)[2]; \
|
||||
BYTEPTR(to)[3] = BYTEPTR(from)[3]; \
|
||||
BYTEPTR(to)[4] = BYTEPTR(from)[4]; \
|
||||
BYTEPTR(to)[5] = BYTEPTR(from)[5]; \
|
||||
BYTEPTR(to)[6] = BYTEPTR(from)[6]; \
|
||||
BYTEPTR(to)[7] = BYTEPTR(from)[7]; \
|
||||
}
|
||||
#endif
|
||||
#define COPY8BTOHALF(to, from) COPY8B(to, from, from)
|
||||
#define COPY8BFROMHALF(to, from) COPY8B(to, from, to)
|
||||
|
||||
static void
|
||||
DES_ECB(DESContext *cx, BYTE *out, const BYTE *in, unsigned int len)
|
||||
{
|
||||
while (len) {
|
||||
DES_Do1Block(cx->ks0, in, out);
|
||||
len -= 8;
|
||||
in += 8;
|
||||
out += 8;
|
||||
}
|
||||
}
|
||||
|
||||
static void
|
||||
DES_EDE3_ECB(DESContext *cx, BYTE *out, const BYTE *in, unsigned int len)
|
||||
{
|
||||
while (len) {
|
||||
DES_Do1Block(cx->ks0, in, out);
|
||||
len -= 8;
|
||||
in += 8;
|
||||
DES_Do1Block(cx->ks1, out, out);
|
||||
DES_Do1Block(cx->ks2, out, out);
|
||||
out += 8;
|
||||
}
|
||||
}
|
||||
|
||||
static void
|
||||
DES_CBCEn(DESContext *cx, BYTE *out, const BYTE *in, unsigned int len)
|
||||
{
|
||||
const BYTE * bufend = in + len;
|
||||
HALF vec[2];
|
||||
|
||||
while (in != bufend) {
|
||||
COPY8BTOHALF(vec, in);
|
||||
in += 8;
|
||||
vec[0] ^= cx->iv[0];
|
||||
vec[1] ^= cx->iv[1];
|
||||
DES_Do1Block( cx->ks0, (BYTE *)vec, (BYTE *)cx->iv);
|
||||
COPY8BFROMHALF(out, cx->iv);
|
||||
out += 8;
|
||||
}
|
||||
}
|
||||
|
||||
static void
|
||||
DES_CBCDe(DESContext *cx, BYTE *out, const BYTE *in, unsigned int len)
|
||||
{
|
||||
const BYTE * bufend;
|
||||
HALF oldciphertext[2];
|
||||
HALF plaintext [2];
|
||||
|
||||
for (bufend = in + len; in != bufend; ) {
|
||||
oldciphertext[0] = cx->iv[0];
|
||||
oldciphertext[1] = cx->iv[1];
|
||||
COPY8BTOHALF(cx->iv, in);
|
||||
in += 8;
|
||||
DES_Do1Block(cx->ks0, (BYTE *)cx->iv, (BYTE *)plaintext);
|
||||
plaintext[0] ^= oldciphertext[0];
|
||||
plaintext[1] ^= oldciphertext[1];
|
||||
COPY8BFROMHALF(out, plaintext);
|
||||
out += 8;
|
||||
}
|
||||
}
|
||||
|
||||
static void
|
||||
DES_EDE3CBCEn(DESContext *cx, BYTE *out, const BYTE *in, unsigned int len)
|
||||
{
|
||||
const BYTE * bufend = in + len;
|
||||
HALF vec[2];
|
||||
|
||||
while (in != bufend) {
|
||||
COPY8BTOHALF(vec, in);
|
||||
in += 8;
|
||||
vec[0] ^= cx->iv[0];
|
||||
vec[1] ^= cx->iv[1];
|
||||
DES_Do1Block( cx->ks0, (BYTE *)vec, (BYTE *)cx->iv);
|
||||
DES_Do1Block( cx->ks1, (BYTE *)cx->iv, (BYTE *)cx->iv);
|
||||
DES_Do1Block( cx->ks2, (BYTE *)cx->iv, (BYTE *)cx->iv);
|
||||
COPY8BFROMHALF(out, cx->iv);
|
||||
out += 8;
|
||||
}
|
||||
}
|
||||
|
||||
static void
|
||||
DES_EDE3CBCDe(DESContext *cx, BYTE *out, const BYTE *in, unsigned int len)
|
||||
{
|
||||
const BYTE * bufend;
|
||||
HALF oldciphertext[2];
|
||||
HALF plaintext [2];
|
||||
|
||||
for (bufend = in + len; in != bufend; ) {
|
||||
oldciphertext[0] = cx->iv[0];
|
||||
oldciphertext[1] = cx->iv[1];
|
||||
COPY8BTOHALF(cx->iv, in);
|
||||
in += 8;
|
||||
DES_Do1Block(cx->ks0, (BYTE *)cx->iv, (BYTE *)plaintext);
|
||||
DES_Do1Block(cx->ks1, (BYTE *)plaintext, (BYTE *)plaintext);
|
||||
DES_Do1Block(cx->ks2, (BYTE *)plaintext, (BYTE *)plaintext);
|
||||
plaintext[0] ^= oldciphertext[0];
|
||||
plaintext[1] ^= oldciphertext[1];
|
||||
COPY8BFROMHALF(out, plaintext);
|
||||
out += 8;
|
||||
}
|
||||
}
|
||||
|
||||
DESContext *
|
||||
DES_CreateContext(const BYTE * key, const BYTE *iv, int mode, PRBool encrypt)
|
||||
{
|
||||
DESContext *cx = PORT_ZNew(DESContext);
|
||||
DESDirection opposite;
|
||||
if (!cx)
|
||||
return 0;
|
||||
cx->direction = encrypt ? DES_ENCRYPT : DES_DECRYPT;
|
||||
opposite = encrypt ? DES_DECRYPT : DES_ENCRYPT;
|
||||
switch (mode) {
|
||||
case NSS_DES: /* DES ECB */
|
||||
DES_MakeSchedule( cx->ks0, key, cx->direction);
|
||||
cx->worker = &DES_ECB;
|
||||
break;
|
||||
|
||||
case NSS_DES_EDE3: /* DES EDE ECB */
|
||||
cx->worker = &DES_EDE3_ECB;
|
||||
if (encrypt) {
|
||||
DES_MakeSchedule(cx->ks0, key, cx->direction);
|
||||
DES_MakeSchedule(cx->ks1, key + 8, opposite);
|
||||
DES_MakeSchedule(cx->ks2, key + 16, cx->direction);
|
||||
} else {
|
||||
DES_MakeSchedule(cx->ks2, key, cx->direction);
|
||||
DES_MakeSchedule(cx->ks1, key + 8, opposite);
|
||||
DES_MakeSchedule(cx->ks0, key + 16, cx->direction);
|
||||
}
|
||||
break;
|
||||
|
||||
case NSS_DES_CBC: /* DES CBC */
|
||||
COPY8BTOHALF(cx->iv, iv);
|
||||
cx->worker = encrypt ? &DES_CBCEn : &DES_CBCDe;
|
||||
DES_MakeSchedule(cx->ks0, key, cx->direction);
|
||||
break;
|
||||
|
||||
case NSS_DES_EDE3_CBC: /* DES EDE CBC */
|
||||
COPY8BTOHALF(cx->iv, iv);
|
||||
if (encrypt) {
|
||||
cx->worker = &DES_EDE3CBCEn;
|
||||
DES_MakeSchedule(cx->ks0, key, cx->direction);
|
||||
DES_MakeSchedule(cx->ks1, key + 8, opposite);
|
||||
DES_MakeSchedule(cx->ks2, key + 16, cx->direction);
|
||||
} else {
|
||||
cx->worker = &DES_EDE3CBCDe;
|
||||
DES_MakeSchedule(cx->ks2, key, cx->direction);
|
||||
DES_MakeSchedule(cx->ks1, key + 8, opposite);
|
||||
DES_MakeSchedule(cx->ks0, key + 16, cx->direction);
|
||||
}
|
||||
break;
|
||||
|
||||
default:
|
||||
PORT_Free(cx);
|
||||
cx = 0;
|
||||
PORT_SetError(SEC_ERROR_INVALID_ARGS);
|
||||
break;
|
||||
}
|
||||
return cx;
|
||||
}
|
||||
|
||||
void
|
||||
DES_DestroyContext(DESContext *cx, PRBool freeit)
|
||||
{
|
||||
if (cx) {
|
||||
memset(cx, 0, sizeof *cx);
|
||||
if (freeit)
|
||||
PORT_Free(cx);
|
||||
}
|
||||
}
|
||||
|
||||
SECStatus
|
||||
DES_Encrypt(DESContext *cx, BYTE *out, unsigned int *outLen,
|
||||
unsigned int maxOutLen, const BYTE *in, unsigned int inLen)
|
||||
{
|
||||
|
||||
if (inLen < 0 || (inLen % 8) != 0 || maxOutLen < inLen || !cx ||
|
||||
cx->direction != DES_ENCRYPT) {
|
||||
PORT_SetError(SEC_ERROR_INVALID_ARGS);
|
||||
return SECFailure;
|
||||
}
|
||||
|
||||
cx->worker(cx, out, in, inLen);
|
||||
if (outLen)
|
||||
*outLen = inLen;
|
||||
return SECSuccess;
|
||||
}
|
||||
|
||||
SECStatus
|
||||
DES_Decrypt(DESContext *cx, BYTE *out, unsigned int *outLen,
|
||||
unsigned int maxOutLen, const BYTE *in, unsigned int inLen)
|
||||
{
|
||||
|
||||
if (inLen < 0 || (inLen % 8) != 0 || maxOutLen < inLen || !cx ||
|
||||
cx->direction != DES_DECRYPT) {
|
||||
PORT_SetError(SEC_ERROR_INVALID_ARGS);
|
||||
return SECFailure;
|
||||
}
|
||||
|
||||
cx->worker(cx, out, in, inLen);
|
||||
if (outLen)
|
||||
*outLen = inLen;
|
||||
return SECSuccess;
|
||||
}
|
||||
385
mozilla/security/nss/lib/freebl/dh.c
Normal file
385
mozilla/security/nss/lib/freebl/dh.c
Normal file
@@ -0,0 +1,385 @@
|
||||
/*
|
||||
* The contents of this file are subject to the Mozilla Public
|
||||
* License Version 1.1 (the "License"); you may not use this file
|
||||
* except in compliance with the License. You may obtain a copy of
|
||||
* the License at http://www.mozilla.org/MPL/
|
||||
*
|
||||
* Software distributed under the License is distributed on an "AS
|
||||
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
|
||||
* implied. See the License for the specific language governing
|
||||
* rights and limitations under the License.
|
||||
*
|
||||
* The Original Code is the Netscape security libraries.
|
||||
*
|
||||
* The Initial Developer of the Original Code is Netscape
|
||||
* Communications Corporation. Portions created by Netscape are
|
||||
* Copyright (C) 1994-2000 Netscape Communications Corporation. All
|
||||
* Rights Reserved.
|
||||
*
|
||||
* Contributor(s):
|
||||
*
|
||||
* Alternatively, the contents of this file may be used under the
|
||||
* terms of the GNU General Public License Version 2 or later (the
|
||||
* "GPL"), in which case the provisions of the GPL are applicable
|
||||
* instead of those above. If you wish to allow use of your
|
||||
* version of this file only under the terms of the GPL and not to
|
||||
* allow others to use your version of this file under the MPL,
|
||||
* indicate your decision by deleting the provisions above and
|
||||
* replace them with the notice and other provisions required by
|
||||
* the GPL. If you do not delete the provisions above, a recipient
|
||||
* may use your version of this file under either the MPL or the
|
||||
* GPL.
|
||||
*/
|
||||
|
||||
/*
|
||||
* Diffie-Hellman parameter generation, key generation, and secret derivation.
|
||||
* KEA secret generation and verification.
|
||||
*
|
||||
* $Id: dh.c,v 1.6 2001-09-20 22:14:06 relyea%netscape.com Exp $
|
||||
*/
|
||||
|
||||
#include "prerr.h"
|
||||
#include "secerr.h"
|
||||
|
||||
#include "blapi.h"
|
||||
#include "secitem.h"
|
||||
#include "mpi.h"
|
||||
#include "mpprime.h"
|
||||
#include "secmpi.h"
|
||||
|
||||
#define DH_SECRET_KEY_LEN 20
|
||||
#define KEA_DERIVED_SECRET_LEN 128
|
||||
|
||||
SECStatus
|
||||
DH_GenParam(int primeLen, DHParams **params)
|
||||
{
|
||||
PRArenaPool *arena;
|
||||
DHParams *dhparams;
|
||||
unsigned char *pb = NULL;
|
||||
unsigned char *ab = NULL;
|
||||
unsigned long counter = 0;
|
||||
mp_int p, q, a, h, psub1, test;
|
||||
mp_err err = MP_OKAY;
|
||||
SECStatus rv = SECSuccess;
|
||||
if (!params || primeLen < 0) {
|
||||
PORT_SetError(SEC_ERROR_INVALID_ARGS);
|
||||
return SECFailure;
|
||||
}
|
||||
arena = PORT_NewArena(NSS_FREEBL_DEFAULT_CHUNKSIZE);
|
||||
if (!arena) {
|
||||
PORT_SetError(SEC_ERROR_NO_MEMORY);
|
||||
return SECFailure;
|
||||
}
|
||||
dhparams = (DHParams *)PORT_ArenaZAlloc(arena, sizeof(DHParams));
|
||||
if (!dhparams) {
|
||||
PORT_SetError(SEC_ERROR_NO_MEMORY);
|
||||
PORT_FreeArena(arena, PR_TRUE);
|
||||
return SECFailure;
|
||||
}
|
||||
dhparams->arena = arena;
|
||||
MP_DIGITS(&p) = 0;
|
||||
MP_DIGITS(&q) = 0;
|
||||
MP_DIGITS(&a) = 0;
|
||||
MP_DIGITS(&h) = 0;
|
||||
MP_DIGITS(&psub1) = 0;
|
||||
MP_DIGITS(&test) = 0;
|
||||
CHECK_MPI_OK( mp_init(&p) );
|
||||
CHECK_MPI_OK( mp_init(&q) );
|
||||
CHECK_MPI_OK( mp_init(&a) );
|
||||
CHECK_MPI_OK( mp_init(&h) );
|
||||
CHECK_MPI_OK( mp_init(&psub1) );
|
||||
CHECK_MPI_OK( mp_init(&test) );
|
||||
/* generate prime with MPI, uses Miller-Rabin to generate strong prime. */
|
||||
pb = PORT_Alloc(primeLen);
|
||||
CHECK_SEC_OK( RNG_GenerateGlobalRandomBytes(pb, primeLen) );
|
||||
pb[0] |= 0x80; /* set high-order bit */
|
||||
pb[primeLen-1] |= 0x01; /* set low-order bit */
|
||||
CHECK_MPI_OK( mp_read_unsigned_octets(&p, pb, primeLen) );
|
||||
CHECK_MPI_OK( mpp_make_prime(&p, primeLen * 8, PR_TRUE, &counter) );
|
||||
/* construct Sophie-Germain prime q = (p-1)/2. */
|
||||
CHECK_MPI_OK( mp_sub_d(&p, 1, &psub1) );
|
||||
CHECK_MPI_OK( mp_div_2(&psub1, &q) );
|
||||
/* construct a generator from the prime. */
|
||||
ab = PORT_Alloc(primeLen);
|
||||
/* generate a candidate number a in p's field */
|
||||
CHECK_SEC_OK( RNG_GenerateGlobalRandomBytes(ab, primeLen) );
|
||||
CHECK_MPI_OK( mp_read_unsigned_octets(&a, ab, primeLen) );
|
||||
/* force a < p (note that quot(a/p) <= 1) */
|
||||
if ( mp_cmp(&a, &p) > 0 )
|
||||
CHECK_MPI_OK( mp_sub(&a, &p, &a) );
|
||||
do {
|
||||
/* check that a is in the range [2..p-1] */
|
||||
if ( mp_cmp_d(&a, 2) < 0 || mp_cmp(&a, &psub1) >= 0) {
|
||||
/* a is outside of the allowed range. Set a=3 and keep going. */
|
||||
mp_set(&a, 3);
|
||||
}
|
||||
/* if a**q mod p != 1 then a is a generator */
|
||||
CHECK_MPI_OK( mp_exptmod(&a, &q, &p, &test) );
|
||||
if ( mp_cmp_d(&test, 1) != 0 )
|
||||
break;
|
||||
/* increment the candidate and try again. */
|
||||
CHECK_MPI_OK( mp_add_d(&a, 1, &a) );
|
||||
} while (PR_TRUE);
|
||||
MPINT_TO_SECITEM(&p, &dhparams->prime, arena);
|
||||
MPINT_TO_SECITEM(&a, &dhparams->base, arena);
|
||||
*params = dhparams;
|
||||
cleanup:
|
||||
mp_clear(&p);
|
||||
mp_clear(&q);
|
||||
mp_clear(&a);
|
||||
mp_clear(&h);
|
||||
mp_clear(&psub1);
|
||||
mp_clear(&test);
|
||||
if (pb) PORT_ZFree(pb, primeLen);
|
||||
if (ab) PORT_ZFree(ab, primeLen);
|
||||
if (err) {
|
||||
MP_TO_SEC_ERROR(err);
|
||||
rv = SECFailure;
|
||||
}
|
||||
if (rv)
|
||||
PORT_FreeArena(arena, PR_TRUE);
|
||||
return rv;
|
||||
}
|
||||
|
||||
SECStatus
|
||||
DH_NewKey(DHParams *params, DHPrivateKey **privKey)
|
||||
{
|
||||
PRArenaPool *arena;
|
||||
DHPrivateKey *key;
|
||||
mp_int g, xa, p, Ya;
|
||||
mp_err err = MP_OKAY;
|
||||
SECStatus rv = SECSuccess;
|
||||
if (!params || !privKey) {
|
||||
PORT_SetError(SEC_ERROR_INVALID_ARGS);
|
||||
return SECFailure;
|
||||
}
|
||||
arena = PORT_NewArena(NSS_FREEBL_DEFAULT_CHUNKSIZE);
|
||||
if (!arena) {
|
||||
PORT_SetError(SEC_ERROR_NO_MEMORY);
|
||||
return SECFailure;
|
||||
}
|
||||
key = (DHPrivateKey *)PORT_ArenaZAlloc(arena, sizeof(DHPrivateKey));
|
||||
if (!key) {
|
||||
PORT_SetError(SEC_ERROR_NO_MEMORY);
|
||||
PORT_FreeArena(arena, PR_TRUE);
|
||||
return SECFailure;
|
||||
}
|
||||
key->arena = arena;
|
||||
MP_DIGITS(&g) = 0;
|
||||
MP_DIGITS(&xa) = 0;
|
||||
MP_DIGITS(&p) = 0;
|
||||
MP_DIGITS(&Ya) = 0;
|
||||
CHECK_MPI_OK( mp_init(&g) );
|
||||
CHECK_MPI_OK( mp_init(&xa) );
|
||||
CHECK_MPI_OK( mp_init(&p) );
|
||||
CHECK_MPI_OK( mp_init(&Ya) );
|
||||
/* Set private key's p */
|
||||
CHECK_SEC_OK( SECITEM_CopyItem(arena, &key->prime, ¶ms->prime) );
|
||||
SECITEM_TO_MPINT(key->prime, &p);
|
||||
/* Set private key's g */
|
||||
CHECK_SEC_OK( SECITEM_CopyItem(arena, &key->base, ¶ms->base) );
|
||||
SECITEM_TO_MPINT(key->base, &g);
|
||||
/* Generate private key xa */
|
||||
SECITEM_AllocItem(arena, &key->privateValue, DH_SECRET_KEY_LEN);
|
||||
RNG_GenerateGlobalRandomBytes(key->privateValue.data,
|
||||
key->privateValue.len);
|
||||
SECITEM_TO_MPINT( key->privateValue, &xa );
|
||||
/* xa < p */
|
||||
CHECK_MPI_OK( mp_mod(&xa, &p, &xa) );
|
||||
/* Compute public key Ya = g ** xa mod p */
|
||||
CHECK_MPI_OK( mp_exptmod(&g, &xa, &p, &Ya) );
|
||||
MPINT_TO_SECITEM(&Ya, &key->publicValue, key->arena);
|
||||
*privKey = key;
|
||||
cleanup:
|
||||
mp_clear(&g);
|
||||
mp_clear(&xa);
|
||||
mp_clear(&p);
|
||||
mp_clear(&Ya);
|
||||
if (err) {
|
||||
MP_TO_SEC_ERROR(err);
|
||||
rv = SECFailure;
|
||||
}
|
||||
if (rv)
|
||||
PORT_FreeArena(arena, PR_TRUE);
|
||||
return rv;
|
||||
}
|
||||
|
||||
SECStatus
|
||||
DH_Derive(SECItem *publicValue,
|
||||
SECItem *prime,
|
||||
SECItem *privateValue,
|
||||
SECItem *derivedSecret,
|
||||
unsigned int maxOutBytes)
|
||||
{
|
||||
mp_int p, Xa, Yb, ZZ;
|
||||
mp_err err = MP_OKAY;
|
||||
unsigned int len = 0, nb;
|
||||
unsigned char *secret = NULL;
|
||||
if (!publicValue || !prime || !privateValue || !derivedSecret) {
|
||||
PORT_SetError(SEC_ERROR_INVALID_ARGS);
|
||||
return SECFailure;
|
||||
}
|
||||
memset(derivedSecret, 0, sizeof *derivedSecret);
|
||||
MP_DIGITS(&p) = 0;
|
||||
MP_DIGITS(&Xa) = 0;
|
||||
MP_DIGITS(&Yb) = 0;
|
||||
MP_DIGITS(&ZZ) = 0;
|
||||
CHECK_MPI_OK( mp_init(&p) );
|
||||
CHECK_MPI_OK( mp_init(&Xa) );
|
||||
CHECK_MPI_OK( mp_init(&Yb) );
|
||||
CHECK_MPI_OK( mp_init(&ZZ) );
|
||||
SECITEM_TO_MPINT(*publicValue, &Yb);
|
||||
SECITEM_TO_MPINT(*privateValue, &Xa);
|
||||
SECITEM_TO_MPINT(*prime, &p);
|
||||
/* ZZ = (Yb)**Xa mod p */
|
||||
CHECK_MPI_OK( mp_exptmod(&Yb, &Xa, &p, &ZZ) );
|
||||
/* number of bytes in the derived secret */
|
||||
len = mp_unsigned_octet_size(&ZZ);
|
||||
/* allocate a buffer which can hold the entire derived secret. */
|
||||
secret = PORT_Alloc(len);
|
||||
/* grab the derived secret */
|
||||
err = mp_to_unsigned_octets(&ZZ, secret, len);
|
||||
if (err >= 0) err = MP_OKAY;
|
||||
/* Take minimum of bytes requested and bytes in derived secret,
|
||||
** if maxOutBytes is 0 take all of the bytes from the derived secret.
|
||||
*/
|
||||
if (maxOutBytes > 0)
|
||||
nb = PR_MIN(len, maxOutBytes);
|
||||
else
|
||||
nb = len;
|
||||
SECITEM_AllocItem(NULL, derivedSecret, nb);
|
||||
memcpy(derivedSecret->data, secret, nb);
|
||||
cleanup:
|
||||
mp_clear(&p);
|
||||
mp_clear(&Xa);
|
||||
mp_clear(&Yb);
|
||||
mp_clear(&ZZ);
|
||||
if (secret) {
|
||||
/* free the buffer allocated for the full secret. */
|
||||
PORT_ZFree(secret, len);
|
||||
}
|
||||
if (err) {
|
||||
MP_TO_SEC_ERROR(err);
|
||||
if (derivedSecret->data)
|
||||
PORT_ZFree(derivedSecret->data, derivedSecret->len);
|
||||
return SECFailure;
|
||||
}
|
||||
return SECSuccess;
|
||||
}
|
||||
|
||||
SECStatus
|
||||
KEA_Derive(SECItem *prime,
|
||||
SECItem *public1,
|
||||
SECItem *public2,
|
||||
SECItem *private1,
|
||||
SECItem *private2,
|
||||
SECItem *derivedSecret)
|
||||
{
|
||||
mp_int p, Y, R, r, x, t, u, w;
|
||||
mp_err err;
|
||||
unsigned char *secret = NULL;
|
||||
unsigned int len = 0, offset;
|
||||
if (!prime || !public1 || !public2 || !private1 || !private2 ||
|
||||
!derivedSecret) {
|
||||
PORT_SetError(SEC_ERROR_INVALID_ARGS);
|
||||
return SECFailure;
|
||||
}
|
||||
memset(derivedSecret, 0, sizeof *derivedSecret);
|
||||
MP_DIGITS(&p) = 0;
|
||||
MP_DIGITS(&Y) = 0;
|
||||
MP_DIGITS(&R) = 0;
|
||||
MP_DIGITS(&r) = 0;
|
||||
MP_DIGITS(&x) = 0;
|
||||
MP_DIGITS(&t) = 0;
|
||||
MP_DIGITS(&u) = 0;
|
||||
MP_DIGITS(&w) = 0;
|
||||
CHECK_MPI_OK( mp_init(&p) );
|
||||
CHECK_MPI_OK( mp_init(&Y) );
|
||||
CHECK_MPI_OK( mp_init(&R) );
|
||||
CHECK_MPI_OK( mp_init(&r) );
|
||||
CHECK_MPI_OK( mp_init(&x) );
|
||||
CHECK_MPI_OK( mp_init(&t) );
|
||||
CHECK_MPI_OK( mp_init(&u) );
|
||||
CHECK_MPI_OK( mp_init(&w) );
|
||||
SECITEM_TO_MPINT(*prime, &p);
|
||||
SECITEM_TO_MPINT(*public1, &Y);
|
||||
SECITEM_TO_MPINT(*public2, &R);
|
||||
SECITEM_TO_MPINT(*private1, &r);
|
||||
SECITEM_TO_MPINT(*private2, &x);
|
||||
/* t = DH(Y, r, p) = Y ** r mod p */
|
||||
CHECK_MPI_OK( mp_exptmod(&Y, &r, &p, &t) );
|
||||
/* u = DH(R, x, p) = R ** x mod p */
|
||||
CHECK_MPI_OK( mp_exptmod(&R, &x, &p, &u) );
|
||||
/* w = (t + u) mod p */
|
||||
CHECK_MPI_OK( mp_addmod(&t, &u, &p, &w) );
|
||||
/* allocate a buffer for the full derived secret */
|
||||
len = mp_unsigned_octet_size(&w);
|
||||
secret = PORT_Alloc(len);
|
||||
/* grab the secret */
|
||||
err = mp_to_unsigned_octets(&w, secret, len);
|
||||
if (err > 0) err = MP_OKAY;
|
||||
/* allocate output buffer */
|
||||
SECITEM_AllocItem(NULL, derivedSecret, KEA_DERIVED_SECRET_LEN);
|
||||
memset(derivedSecret->data, 0, derivedSecret->len);
|
||||
/* copy in the 128 lsb of the secret */
|
||||
if (len >= KEA_DERIVED_SECRET_LEN) {
|
||||
memcpy(derivedSecret->data, secret + (len - KEA_DERIVED_SECRET_LEN),
|
||||
KEA_DERIVED_SECRET_LEN);
|
||||
} else {
|
||||
offset = KEA_DERIVED_SECRET_LEN - len;
|
||||
memcpy(derivedSecret->data + offset, secret, len);
|
||||
}
|
||||
cleanup:
|
||||
mp_clear(&p);
|
||||
mp_clear(&Y);
|
||||
mp_clear(&R);
|
||||
mp_clear(&r);
|
||||
mp_clear(&x);
|
||||
mp_clear(&t);
|
||||
mp_clear(&u);
|
||||
mp_clear(&w);
|
||||
if (secret)
|
||||
PORT_ZFree(secret, len);
|
||||
if (err) {
|
||||
MP_TO_SEC_ERROR(err);
|
||||
return SECFailure;
|
||||
}
|
||||
return SECSuccess;
|
||||
}
|
||||
|
||||
PRBool
|
||||
KEA_Verify(SECItem *Y, SECItem *prime, SECItem *subPrime)
|
||||
{
|
||||
mp_int p, q, y, r;
|
||||
mp_err err;
|
||||
int cmp = 1; /* default is false */
|
||||
if (!Y || !prime || !subPrime) {
|
||||
PORT_SetError(SEC_ERROR_INVALID_ARGS);
|
||||
return SECFailure;
|
||||
}
|
||||
MP_DIGITS(&p) = 0;
|
||||
MP_DIGITS(&q) = 0;
|
||||
MP_DIGITS(&y) = 0;
|
||||
MP_DIGITS(&r) = 0;
|
||||
CHECK_MPI_OK( mp_init(&p) );
|
||||
CHECK_MPI_OK( mp_init(&q) );
|
||||
CHECK_MPI_OK( mp_init(&y) );
|
||||
CHECK_MPI_OK( mp_init(&r) );
|
||||
SECITEM_TO_MPINT(*prime, &p);
|
||||
SECITEM_TO_MPINT(*subPrime, &q);
|
||||
SECITEM_TO_MPINT(*Y, &y);
|
||||
/* compute r = y**q mod p */
|
||||
CHECK_MPI_OK( mp_exptmod(&y, &q, &p, &r) );
|
||||
/* compare to 1 */
|
||||
cmp = mp_cmp_d(&r, 1);
|
||||
cleanup:
|
||||
mp_clear(&p);
|
||||
mp_clear(&q);
|
||||
mp_clear(&y);
|
||||
mp_clear(&r);
|
||||
if (err) {
|
||||
MP_TO_SEC_ERROR(err);
|
||||
return PR_FALSE;
|
||||
}
|
||||
return (cmp == 0) ? PR_TRUE : PR_FALSE;
|
||||
}
|
||||
82
mozilla/security/nss/lib/freebl/dh_bsf.c
Normal file
82
mozilla/security/nss/lib/freebl/dh_bsf.c
Normal file
@@ -0,0 +1,82 @@
|
||||
/*
|
||||
* The contents of this file are subject to the Mozilla Public
|
||||
* License Version 1.1 (the "License"); you may not use this file
|
||||
* except in compliance with the License. You may obtain a copy of
|
||||
* the License at http://www.mozilla.org/MPL/
|
||||
*
|
||||
* Software distributed under the License is distributed on an "AS
|
||||
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
|
||||
* implied. See the License for the specific language governing
|
||||
* rights and limitations under the License.
|
||||
*
|
||||
* The Original Code is the Netscape security libraries.
|
||||
*
|
||||
* The Initial Developer of the Original Code is Netscape
|
||||
* Communications Corporation. Portions created by Netscape are
|
||||
* Copyright (C) 1994-2000 Netscape Communications Corporation. All
|
||||
* Rights Reserved.
|
||||
*
|
||||
* Contributor(s):
|
||||
*
|
||||
* Alternatively, the contents of this file may be used under the
|
||||
* terms of the GNU General Public License Version 2 or later (the
|
||||
* "GPL"), in which case the provisions of the GPL are applicable
|
||||
* instead of those above. If you wish to allow use of your
|
||||
* version of this file only under the terms of the GPL and not to
|
||||
* allow others to use your version of this file under the MPL,
|
||||
* indicate your decision by deleting the provisions above and
|
||||
* replace them with the notice and other provisions required by
|
||||
* the GPL. If you do not delete the provisions above, a recipient
|
||||
* may use your version of this file under either the MPL or the
|
||||
* GPL.
|
||||
*/
|
||||
|
||||
#include "prerr.h"
|
||||
#include "secerr.h"
|
||||
|
||||
#include "blapi.h"
|
||||
|
||||
SECStatus
|
||||
DH_GenParam(int primeLen, DHParams ** params)
|
||||
{
|
||||
PORT_SetError(PR_NOT_IMPLEMENTED_ERROR);
|
||||
return SECFailure;
|
||||
}
|
||||
|
||||
SECStatus
|
||||
DH_NewKey(DHParams * params,
|
||||
DHPrivateKey ** privKey)
|
||||
{
|
||||
PORT_SetError(PR_NOT_IMPLEMENTED_ERROR);
|
||||
return SECFailure;
|
||||
}
|
||||
|
||||
SECStatus
|
||||
DH_Derive(SECItem * publicValue,
|
||||
SECItem * prime,
|
||||
SECItem * privateValue,
|
||||
SECItem * derivedSecret,
|
||||
unsigned int maxOutBytes)
|
||||
{
|
||||
PORT_SetError(PR_NOT_IMPLEMENTED_ERROR);
|
||||
return SECFailure;
|
||||
}
|
||||
|
||||
SECStatus
|
||||
KEA_Derive(SECItem *prime,
|
||||
SECItem *public1,
|
||||
SECItem *public2,
|
||||
SECItem *private1,
|
||||
SECItem *private2,
|
||||
SECItem *derivedSecret)
|
||||
{
|
||||
PORT_SetError(PR_NOT_IMPLEMENTED_ERROR);
|
||||
return SECFailure;
|
||||
}
|
||||
|
||||
PRBool
|
||||
KEA_Verify(SECItem *Y, SECItem *prime, SECItem *subPrime)
|
||||
{
|
||||
PORT_SetError(PR_NOT_IMPLEMENTED_ERROR);
|
||||
return PR_FALSE;
|
||||
}
|
||||
420
mozilla/security/nss/lib/freebl/dsa.c
Normal file
420
mozilla/security/nss/lib/freebl/dsa.c
Normal file
@@ -0,0 +1,420 @@
|
||||
/*
|
||||
*
|
||||
* The contents of this file are subject to the Mozilla Public
|
||||
* License Version 1.1 (the "License"); you may not use this file
|
||||
* except in compliance with the License. You may obtain a copy of
|
||||
* the License at http://www.mozilla.org/MPL/
|
||||
*
|
||||
* Software distributed under the License is distributed on an "AS
|
||||
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
|
||||
* implied. See the License for the specific language governing
|
||||
* rights and limitations under the License.
|
||||
*
|
||||
* The Original Code is the Netscape security libraries.
|
||||
*
|
||||
* The Initial Developer of the Original Code is Netscape
|
||||
* Communications Corporation. Portions created by Netscape are
|
||||
* Copyright (C) 1994-2000 Netscape Communications Corporation. All
|
||||
* Rights Reserved.
|
||||
*
|
||||
* Contributor(s):
|
||||
*
|
||||
* Alternatively, the contents of this file may be used under the
|
||||
* terms of the GNU General Public License Version 2 or later (the
|
||||
* "GPL"), in which case the provisions of the GPL are applicable
|
||||
* instead of those above. If you wish to allow use of your
|
||||
* version of this file only under the terms of the GPL and not to
|
||||
* allow others to use your version of this file under the MPL,
|
||||
* indicate your decision by deleting the provisions above and
|
||||
* replace them with the notice and other provisions required by
|
||||
* the GPL. If you do not delete the provisions above, a recipient
|
||||
* may use your version of this file under either the MPL or the
|
||||
* GPL.
|
||||
*
|
||||
* $Id: dsa.c,v 1.11 2003-02-25 23:45:23 nelsonb%netscape.com Exp $
|
||||
*/
|
||||
|
||||
#include "secerr.h"
|
||||
|
||||
#include "prtypes.h"
|
||||
#include "prinit.h"
|
||||
#include "blapi.h"
|
||||
#include "nssilock.h"
|
||||
#include "secitem.h"
|
||||
#include "blapi.h"
|
||||
#include "mpi.h"
|
||||
|
||||
/* XXX to be replaced by define in blapit.h */
|
||||
#define NSS_FREEBL_DSA_DEFAULT_CHUNKSIZE 2048
|
||||
|
||||
#define CHECKOK(func) if (MP_OKAY > (err = func)) goto cleanup
|
||||
|
||||
#define SECITEM_TO_MPINT(it, mp) \
|
||||
CHECKOK(mp_read_unsigned_octets((mp), (it).data, (it).len))
|
||||
|
||||
/* DSA-specific random number functions defined in prng_fips1861.c. */
|
||||
extern SECStatus
|
||||
DSA_RandomUpdate(void *data, size_t bytes, unsigned char *q);
|
||||
|
||||
extern SECStatus
|
||||
DSA_GenerateGlobalRandomBytes(void *dest, size_t len, unsigned char *q);
|
||||
|
||||
static void translate_mpi_error(mp_err err)
|
||||
{
|
||||
switch (err) {
|
||||
case MP_MEM: PORT_SetError(SEC_ERROR_NO_MEMORY); break;
|
||||
case MP_RANGE: PORT_SetError(SEC_ERROR_BAD_DATA); break;
|
||||
case MP_BADARG: PORT_SetError(SEC_ERROR_INVALID_ARGS); break;
|
||||
default: PORT_SetError(SEC_ERROR_LIBRARY_FAILURE); break;
|
||||
}
|
||||
}
|
||||
|
||||
SECStatus
|
||||
dsa_NewKey(const PQGParams *params, DSAPrivateKey **privKey,
|
||||
const unsigned char *xb)
|
||||
{
|
||||
unsigned int y_len;
|
||||
mp_int p, g;
|
||||
mp_int x, y;
|
||||
mp_err err;
|
||||
PRArenaPool *arena;
|
||||
DSAPrivateKey *key;
|
||||
/* Check args. */
|
||||
if (!params || !privKey) {
|
||||
PORT_SetError(SEC_ERROR_INVALID_ARGS);
|
||||
return SECFailure;
|
||||
}
|
||||
/* Initialize an arena for the DSA key. */
|
||||
arena = PORT_NewArena(NSS_FREEBL_DSA_DEFAULT_CHUNKSIZE);
|
||||
if (!arena) {
|
||||
PORT_SetError(SEC_ERROR_NO_MEMORY);
|
||||
return SECFailure;
|
||||
}
|
||||
key = (DSAPrivateKey *)PORT_ArenaZAlloc(arena, sizeof(DSAPrivateKey));
|
||||
if (!key) {
|
||||
PORT_SetError(SEC_ERROR_NO_MEMORY);
|
||||
PORT_FreeArena(arena, PR_TRUE);
|
||||
return SECFailure;
|
||||
}
|
||||
key->params.arena = arena;
|
||||
/* Initialize MPI integers. */
|
||||
MP_DIGITS(&p) = 0;
|
||||
MP_DIGITS(&g) = 0;
|
||||
MP_DIGITS(&x) = 0;
|
||||
MP_DIGITS(&y) = 0;
|
||||
CHECKOK( mp_init(&p) );
|
||||
CHECKOK( mp_init(&g) );
|
||||
CHECKOK( mp_init(&x) );
|
||||
CHECKOK( mp_init(&y) );
|
||||
/* Copy over the PQG params */
|
||||
CHECKOK( SECITEM_CopyItem(arena, &key->params.prime, ¶ms->prime) );
|
||||
CHECKOK( SECITEM_CopyItem(arena, &key->params.subPrime, ¶ms->subPrime));
|
||||
CHECKOK( SECITEM_CopyItem(arena, &key->params.base, ¶ms->base) );
|
||||
/* Convert stored p, g, and received x into MPI integers. */
|
||||
SECITEM_TO_MPINT(params->prime, &p);
|
||||
SECITEM_TO_MPINT(params->base, &g);
|
||||
CHECKOK( mp_read_unsigned_octets(&x, xb, DSA_SUBPRIME_LEN) );
|
||||
/* Store x in private key */
|
||||
SECITEM_AllocItem(arena, &key->privateValue, DSA_SUBPRIME_LEN);
|
||||
memcpy(key->privateValue.data, xb, DSA_SUBPRIME_LEN);
|
||||
/* Compute public key y = g**x mod p */
|
||||
CHECKOK( mp_exptmod(&g, &x, &p, &y) );
|
||||
/* Store y in public key */
|
||||
y_len = mp_unsigned_octet_size(&y);
|
||||
SECITEM_AllocItem(arena, &key->publicValue, y_len);
|
||||
err = mp_to_unsigned_octets(&y, key->publicValue.data, y_len);
|
||||
/* mp_to_unsigned_octets returns bytes written (y_len) if okay */
|
||||
if (err < 0) goto cleanup; else err = MP_OKAY;
|
||||
*privKey = key;
|
||||
key = NULL;
|
||||
cleanup:
|
||||
mp_clear(&p);
|
||||
mp_clear(&g);
|
||||
mp_clear(&x);
|
||||
mp_clear(&y);
|
||||
if (key)
|
||||
PORT_FreeArena(key->params.arena, PR_TRUE);
|
||||
if (err) {
|
||||
translate_mpi_error(err);
|
||||
return SECFailure;
|
||||
}
|
||||
return SECSuccess;
|
||||
}
|
||||
|
||||
/*
|
||||
** Generate and return a new DSA public and private key pair,
|
||||
** both of which are encoded into a single DSAPrivateKey struct.
|
||||
** "params" is a pointer to the PQG parameters for the domain
|
||||
** Uses a random seed.
|
||||
*/
|
||||
SECStatus
|
||||
DSA_NewKey(const PQGParams *params, DSAPrivateKey **privKey)
|
||||
{
|
||||
SECStatus rv;
|
||||
unsigned char seed[DSA_SUBPRIME_LEN];
|
||||
/* Generate seed bytes for x according to FIPS 186-1 appendix 3 */
|
||||
if (DSA_GenerateGlobalRandomBytes(seed, DSA_SUBPRIME_LEN,
|
||||
params->subPrime.data))
|
||||
return SECFailure;
|
||||
/* Generate a new DSA key using random seed. */
|
||||
rv = dsa_NewKey(params, privKey, seed);
|
||||
return rv;
|
||||
}
|
||||
|
||||
/* For FIPS compliance testing. Seed must be exactly 20 bytes long */
|
||||
SECStatus
|
||||
DSA_NewKeyFromSeed(const PQGParams *params,
|
||||
const unsigned char *seed,
|
||||
DSAPrivateKey **privKey)
|
||||
{
|
||||
SECStatus rv;
|
||||
rv = dsa_NewKey(params, privKey, seed);
|
||||
return rv;
|
||||
}
|
||||
|
||||
static SECStatus
|
||||
dsa_SignDigest(DSAPrivateKey *key, SECItem *signature, const SECItem *digest,
|
||||
const unsigned char *kb)
|
||||
{
|
||||
mp_int p, q, g; /* PQG parameters */
|
||||
mp_int x, k; /* private key & pseudo-random integer */
|
||||
mp_int r, s; /* tuple (r, s) is signature) */
|
||||
mp_err err = MP_OKAY;
|
||||
SECStatus rv = SECSuccess;
|
||||
|
||||
/* FIPS-compliance dictates that digest is a SHA1 hash. */
|
||||
/* Check args. */
|
||||
if (!key || !signature || !digest ||
|
||||
(signature->len != DSA_SIGNATURE_LEN) ||
|
||||
(digest->len != SHA1_LENGTH)) {
|
||||
PORT_SetError(SEC_ERROR_INVALID_ARGS);
|
||||
return SECFailure;
|
||||
}
|
||||
/* Initialize MPI integers. */
|
||||
MP_DIGITS(&p) = 0;
|
||||
MP_DIGITS(&q) = 0;
|
||||
MP_DIGITS(&g) = 0;
|
||||
MP_DIGITS(&x) = 0;
|
||||
MP_DIGITS(&k) = 0;
|
||||
MP_DIGITS(&r) = 0;
|
||||
MP_DIGITS(&s) = 0;
|
||||
CHECKOK( mp_init(&p) );
|
||||
CHECKOK( mp_init(&q) );
|
||||
CHECKOK( mp_init(&g) );
|
||||
CHECKOK( mp_init(&x) );
|
||||
CHECKOK( mp_init(&k) );
|
||||
CHECKOK( mp_init(&r) );
|
||||
CHECKOK( mp_init(&s) );
|
||||
/*
|
||||
** Convert stored PQG and private key into MPI integers.
|
||||
*/
|
||||
SECITEM_TO_MPINT(key->params.prime, &p);
|
||||
SECITEM_TO_MPINT(key->params.subPrime, &q);
|
||||
SECITEM_TO_MPINT(key->params.base, &g);
|
||||
SECITEM_TO_MPINT(key->privateValue, &x);
|
||||
CHECKOK( mp_read_unsigned_octets(&k, kb, DSA_SUBPRIME_LEN) );
|
||||
/*
|
||||
** FIPS 186-1, Section 5, Step 1
|
||||
**
|
||||
** r = (g**k mod p) mod q
|
||||
*/
|
||||
CHECKOK( mp_exptmod(&g, &k, &p, &r) ); /* r = g**k mod p */
|
||||
CHECKOK( mp_mod(&r, &q, &r) ); /* r = r mod q */
|
||||
/*
|
||||
** FIPS 186-1, Section 5, Step 2
|
||||
**
|
||||
** s = (k**-1 * (SHA1(M) + x*r)) mod q
|
||||
*/
|
||||
SECITEM_TO_MPINT(*digest, &s); /* s = SHA1(M) */
|
||||
CHECKOK( mp_invmod(&k, &q, &k) ); /* k = k**-1 mod q */
|
||||
CHECKOK( mp_mulmod(&x, &r, &q, &x) ); /* x = x * r mod q */
|
||||
CHECKOK( mp_addmod(&s, &x, &q, &s) ); /* s = s + x mod q */
|
||||
CHECKOK( mp_mulmod(&s, &k, &q, &s) ); /* s = s * k mod q */
|
||||
/*
|
||||
** verify r != 0 and s != 0
|
||||
** mentioned as optional in FIPS 186-1.
|
||||
*/
|
||||
if (mp_cmp_z(&r) == 0 || mp_cmp_z(&s) == 0) {
|
||||
PORT_SetError(SEC_ERROR_NEED_RANDOM);
|
||||
rv = SECFailure;
|
||||
goto cleanup;
|
||||
}
|
||||
/*
|
||||
** Step 4
|
||||
**
|
||||
** Signature is tuple (r, s)
|
||||
*/
|
||||
err = mp_to_fixlen_octets(&r, signature->data, DSA_SUBPRIME_LEN);
|
||||
if (err < 0) goto cleanup;
|
||||
err = mp_to_fixlen_octets(&s, signature->data + DSA_SUBPRIME_LEN,
|
||||
DSA_SUBPRIME_LEN);
|
||||
if (err < 0) goto cleanup;
|
||||
err = MP_OKAY;
|
||||
cleanup:
|
||||
mp_clear(&p);
|
||||
mp_clear(&q);
|
||||
mp_clear(&g);
|
||||
mp_clear(&x);
|
||||
mp_clear(&k);
|
||||
mp_clear(&r);
|
||||
mp_clear(&s);
|
||||
if (err) {
|
||||
translate_mpi_error(err);
|
||||
rv = SECFailure;
|
||||
}
|
||||
return rv;
|
||||
}
|
||||
|
||||
/* signature is caller-supplied buffer of at least 20 bytes.
|
||||
** On input, signature->len == size of buffer to hold signature.
|
||||
** digest->len == size of digest.
|
||||
** On output, signature->len == size of signature in buffer.
|
||||
** Uses a random seed.
|
||||
*/
|
||||
SECStatus
|
||||
DSA_SignDigest(DSAPrivateKey *key, SECItem *signature, const SECItem *digest)
|
||||
{
|
||||
SECStatus rv;
|
||||
int retries = 10;
|
||||
unsigned char kSeed[DSA_SUBPRIME_LEN];
|
||||
|
||||
PORT_SetError(0);
|
||||
do {
|
||||
rv = DSA_GenerateGlobalRandomBytes(kSeed, DSA_SUBPRIME_LEN,
|
||||
key->params.subPrime.data);
|
||||
if (rv != SECSuccess)
|
||||
break;
|
||||
rv = dsa_SignDigest(key, signature, digest, kSeed);
|
||||
} while (rv != SECSuccess && PORT_GetError() == SEC_ERROR_NEED_RANDOM &&
|
||||
--retries > 0);
|
||||
return rv;
|
||||
}
|
||||
|
||||
/* For FIPS compliance testing. Seed must be exactly 20 bytes. */
|
||||
SECStatus
|
||||
DSA_SignDigestWithSeed(DSAPrivateKey * key,
|
||||
SECItem * signature,
|
||||
const SECItem * digest,
|
||||
const unsigned char * seed)
|
||||
{
|
||||
SECStatus rv;
|
||||
rv = dsa_SignDigest(key, signature, digest, seed);
|
||||
return rv;
|
||||
}
|
||||
|
||||
/* signature is caller-supplied buffer of at least 20 bytes.
|
||||
** On input, signature->len == size of buffer to hold signature.
|
||||
** digest->len == size of digest.
|
||||
*/
|
||||
SECStatus
|
||||
DSA_VerifyDigest(DSAPublicKey *key, const SECItem *signature,
|
||||
const SECItem *digest)
|
||||
{
|
||||
/* FIPS-compliance dictates that digest is a SHA1 hash. */
|
||||
mp_int p, q, g; /* PQG parameters */
|
||||
mp_int r_, s_; /* tuple (r', s') is received signature) */
|
||||
mp_int u1, u2, v, w; /* intermediate values used in verification */
|
||||
mp_int y; /* public key */
|
||||
mp_err err;
|
||||
SECStatus verified = SECFailure;
|
||||
|
||||
/* Check args. */
|
||||
if (!key || !signature || !digest ||
|
||||
(signature->len != DSA_SIGNATURE_LEN) ||
|
||||
(digest->len != SHA1_LENGTH)) {
|
||||
PORT_SetError(SEC_ERROR_INVALID_ARGS);
|
||||
return SECFailure;
|
||||
}
|
||||
/* Initialize MPI integers. */
|
||||
MP_DIGITS(&p) = 0;
|
||||
MP_DIGITS(&q) = 0;
|
||||
MP_DIGITS(&g) = 0;
|
||||
MP_DIGITS(&y) = 0;
|
||||
MP_DIGITS(&r_) = 0;
|
||||
MP_DIGITS(&s_) = 0;
|
||||
MP_DIGITS(&u1) = 0;
|
||||
MP_DIGITS(&u2) = 0;
|
||||
MP_DIGITS(&v) = 0;
|
||||
MP_DIGITS(&w) = 0;
|
||||
CHECKOK( mp_init(&p) );
|
||||
CHECKOK( mp_init(&q) );
|
||||
CHECKOK( mp_init(&g) );
|
||||
CHECKOK( mp_init(&y) );
|
||||
CHECKOK( mp_init(&r_) );
|
||||
CHECKOK( mp_init(&s_) );
|
||||
CHECKOK( mp_init(&u1) );
|
||||
CHECKOK( mp_init(&u2) );
|
||||
CHECKOK( mp_init(&v) );
|
||||
CHECKOK( mp_init(&w) );
|
||||
/*
|
||||
** Convert stored PQG and public key into MPI integers.
|
||||
*/
|
||||
SECITEM_TO_MPINT(key->params.prime, &p);
|
||||
SECITEM_TO_MPINT(key->params.subPrime, &q);
|
||||
SECITEM_TO_MPINT(key->params.base, &g);
|
||||
SECITEM_TO_MPINT(key->publicValue, &y);
|
||||
/*
|
||||
** Convert received signature (r', s') into MPI integers.
|
||||
*/
|
||||
CHECKOK( mp_read_unsigned_octets(&r_, signature->data, DSA_SUBPRIME_LEN) );
|
||||
CHECKOK( mp_read_unsigned_octets(&s_, signature->data + DSA_SUBPRIME_LEN,
|
||||
DSA_SUBPRIME_LEN) );
|
||||
/*
|
||||
** Verify that 0 < r' < q and 0 < s' < q
|
||||
*/
|
||||
if (mp_cmp_z(&r_) <= 0 || mp_cmp_z(&s_) <= 0 ||
|
||||
mp_cmp(&r_, &q) >= 0 || mp_cmp(&s_, &q) >= 0)
|
||||
goto cleanup; /* will return verified == SECFailure */
|
||||
/*
|
||||
** FIPS 186-1, Section 6, Step 1
|
||||
**
|
||||
** w = (s')**-1 mod q
|
||||
*/
|
||||
CHECKOK( mp_invmod(&s_, &q, &w) ); /* w = (s')**-1 mod q */
|
||||
/*
|
||||
** FIPS 186-1, Section 6, Step 2
|
||||
**
|
||||
** u1 = ((SHA1(M')) * w) mod q
|
||||
*/
|
||||
SECITEM_TO_MPINT(*digest, &u1); /* u1 = SHA1(M') */
|
||||
CHECKOK( mp_mulmod(&u1, &w, &q, &u1) ); /* u1 = u1 * w mod q */
|
||||
/*
|
||||
** FIPS 186-1, Section 6, Step 3
|
||||
**
|
||||
** u2 = ((r') * w) mod q
|
||||
*/
|
||||
CHECKOK( mp_mulmod(&r_, &w, &q, &u2) );
|
||||
/*
|
||||
** FIPS 186-1, Section 6, Step 4
|
||||
**
|
||||
** v = ((g**u1 * y**u2) mod p) mod q
|
||||
*/
|
||||
CHECKOK( mp_exptmod(&g, &u1, &p, &g) ); /* g = g**u1 mod p */
|
||||
CHECKOK( mp_exptmod(&y, &u2, &p, &y) ); /* y = y**u2 mod p */
|
||||
CHECKOK( mp_mulmod(&g, &y, &p, &v) ); /* v = g * y mod p */
|
||||
CHECKOK( mp_mod(&v, &q, &v) ); /* v = v mod q */
|
||||
/*
|
||||
** Verification: v == r'
|
||||
*/
|
||||
if (mp_cmp(&v, &r_)) {
|
||||
PORT_SetError(SEC_ERROR_BAD_SIGNATURE);
|
||||
verified = SECFailure; /* Signature failed to verify. */
|
||||
} else {
|
||||
verified = SECSuccess; /* Signature verified. */
|
||||
}
|
||||
cleanup:
|
||||
mp_clear(&p);
|
||||
mp_clear(&q);
|
||||
mp_clear(&g);
|
||||
mp_clear(&y);
|
||||
mp_clear(&r_);
|
||||
mp_clear(&s_);
|
||||
mp_clear(&u1);
|
||||
mp_clear(&u2);
|
||||
mp_clear(&v);
|
||||
mp_clear(&w);
|
||||
if (err) {
|
||||
translate_mpi_error(err);
|
||||
}
|
||||
return verified;
|
||||
}
|
||||
977
mozilla/security/nss/lib/freebl/ec.c
Normal file
977
mozilla/security/nss/lib/freebl/ec.c
Normal file
@@ -0,0 +1,977 @@
|
||||
/*
|
||||
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
|
||||
*
|
||||
* The contents of this file are subject to the Mozilla Public License Version
|
||||
* 1.1 (the "License"); you may not use this file except in compliance with
|
||||
* the License. You may obtain a copy of the License at
|
||||
* http://www.mozilla.org/MPL/
|
||||
*
|
||||
* Software distributed under the License is distributed on an "AS IS" basis,
|
||||
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
|
||||
* for the specific language governing rights and limitations under the
|
||||
* License.
|
||||
*
|
||||
* The Original Code is the Elliptic Curve Cryptography library.
|
||||
*
|
||||
* The Initial Developer of the Original Code is Sun Microsystems, Inc.
|
||||
* Portions created by Sun Microsystems, Inc. are Copyright (C) 2003
|
||||
* Sun Microsystems, Inc. All Rights Reserved.
|
||||
*
|
||||
* Contributor(s):
|
||||
* Dr Vipul Gupta <vipul.gupta@sun.com>, Sun Microsystems Laboratories
|
||||
*
|
||||
* Alternatively, the contents of this file may be used under the terms of
|
||||
* either the GNU General Public License Version 2 or later (the "GPL"), or
|
||||
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
|
||||
* in which case the provisions of the GPL or the LGPL are applicable instead
|
||||
* of those above. If you wish to allow use of your version of this file only
|
||||
* under the terms of either the GPL or the LGPL, and not to allow others to
|
||||
* use your version of this file under the terms of the MPL, indicate your
|
||||
* decision by deleting the provisions above and replace them with the notice
|
||||
* and other provisions required by the GPL or the LGPL. If you do not delete
|
||||
* the provisions above, a recipient may use your version of this file under
|
||||
* the terms of any one of the MPL, the GPL or the LGPL.
|
||||
*
|
||||
*/
|
||||
|
||||
#include "blapi.h"
|
||||
#include "prerr.h"
|
||||
#include "secerr.h"
|
||||
#include "secmpi.h"
|
||||
#include "secitem.h"
|
||||
#include "ec.h"
|
||||
#include "GFp_ecl.h"
|
||||
#include "GF2m_ecl.h"
|
||||
|
||||
#ifdef NSS_ENABLE_ECC
|
||||
|
||||
/*
|
||||
* Returns true if pointP is the point at infinity, false otherwise
|
||||
*/
|
||||
PRBool
|
||||
ec_point_at_infinity(SECItem *pointP)
|
||||
{
|
||||
int i;
|
||||
|
||||
for (i = 1; i < pointP->len; i++) {
|
||||
if (pointP->data[i] != 0x00) return PR_FALSE;
|
||||
}
|
||||
|
||||
return PR_TRUE;
|
||||
}
|
||||
|
||||
/*
|
||||
* Computes point addition R = P + Q for the curve whose
|
||||
* parameters are encoded in params. Two or more of P, Q,
|
||||
* R may point to the same memory location.
|
||||
*/
|
||||
SECStatus
|
||||
ec_point_add(ECParams *params, SECItem *pointP,
|
||||
SECItem *pointQ, SECItem *pointR)
|
||||
{
|
||||
mp_int Px, Py, Qx, Qy, Rx, Ry;
|
||||
mp_int irreducible, a;
|
||||
SECStatus rv = SECFailure;
|
||||
mp_err err = MP_OKAY;
|
||||
int len;
|
||||
|
||||
#if EC_DEBUG
|
||||
int i;
|
||||
|
||||
printf("ec_point_add: params [len=%d]:", params->DEREncoding.len);
|
||||
for (i = 0; i < params->DEREncoding.len; i++)
|
||||
printf("%02x:", params->DEREncoding.data[i]);
|
||||
printf("\n");
|
||||
|
||||
printf("ec_point_add: pointP [len=%d]:", pointP->len);
|
||||
for (i = 0; i < pointP->len; i++)
|
||||
printf("%02x:", pointP->data[i]);
|
||||
printf("\n");
|
||||
|
||||
printf("ec_point_add: pointQ [len=%d]:", pointQ->len);
|
||||
for (i = 0; i < pointQ->len; i++)
|
||||
printf("%02x:", pointQ->data[i]);
|
||||
printf("\n");
|
||||
#endif
|
||||
|
||||
/* NOTE: We only support prime field curves for now */
|
||||
len = (params->fieldID.size + 7) >> 3;
|
||||
if ((pointP->data[0] != EC_POINT_FORM_UNCOMPRESSED) ||
|
||||
(pointP->len != (2 * len + 1)) ||
|
||||
(pointQ->data[0] != EC_POINT_FORM_UNCOMPRESSED) ||
|
||||
(pointQ->len != (2 * len + 1))) {
|
||||
PORT_SetError(SEC_ERROR_INVALID_ARGS);
|
||||
return SECFailure;
|
||||
}
|
||||
|
||||
MP_DIGITS(&Px) = 0;
|
||||
MP_DIGITS(&Py) = 0;
|
||||
MP_DIGITS(&Qx) = 0;
|
||||
MP_DIGITS(&Qy) = 0;
|
||||
MP_DIGITS(&Rx) = 0;
|
||||
MP_DIGITS(&Ry) = 0;
|
||||
MP_DIGITS(&irreducible) = 0;
|
||||
MP_DIGITS(&a) = 0;
|
||||
CHECK_MPI_OK( mp_init(&Px) );
|
||||
CHECK_MPI_OK( mp_init(&Py) );
|
||||
CHECK_MPI_OK( mp_init(&Qx) );
|
||||
CHECK_MPI_OK( mp_init(&Qy) );
|
||||
CHECK_MPI_OK( mp_init(&Rx) );
|
||||
CHECK_MPI_OK( mp_init(&Ry) );
|
||||
CHECK_MPI_OK( mp_init(&irreducible) );
|
||||
CHECK_MPI_OK( mp_init(&a) );
|
||||
|
||||
/* Initialize Px and Py */
|
||||
CHECK_MPI_OK( mp_read_unsigned_octets(&Px, pointP->data + 1,
|
||||
(mp_size) len) );
|
||||
CHECK_MPI_OK( mp_read_unsigned_octets(&Py, pointP->data + 1 + len,
|
||||
(mp_size) len) );
|
||||
|
||||
/* Initialize Qx and Qy */
|
||||
CHECK_MPI_OK( mp_read_unsigned_octets(&Qx, pointQ->data + 1,
|
||||
(mp_size) len) );
|
||||
CHECK_MPI_OK( mp_read_unsigned_octets(&Qy, pointQ->data + 1 + len,
|
||||
(mp_size) len) );
|
||||
|
||||
/* Set up the curve coefficient */
|
||||
SECITEM_TO_MPINT( params->curve.a, &a );
|
||||
|
||||
/* Compute R = P + Q */
|
||||
if (params->fieldID.type == ec_field_GFp) {
|
||||
SECITEM_TO_MPINT( params->fieldID.u.prime, &irreducible );
|
||||
if (GFp_ec_pt_add(&irreducible, &a, &Px, &Py, &Qx, &Qy,
|
||||
&Rx, &Ry) != SECSuccess)
|
||||
goto cleanup;
|
||||
} else {
|
||||
SECITEM_TO_MPINT( params->fieldID.u.poly, &irreducible );
|
||||
if (GF2m_ec_pt_add(&irreducible, &a, &Px, &Py, &Qx, &Qy, &Rx, &Ry)
|
||||
!= SECSuccess)
|
||||
goto cleanup;
|
||||
}
|
||||
|
||||
/* Construct the SECItem representation of the result */
|
||||
pointR->data[0] = EC_POINT_FORM_UNCOMPRESSED;
|
||||
CHECK_MPI_OK( mp_to_fixlen_octets(&Rx, pointR->data + 1,
|
||||
(mp_size) len) );
|
||||
CHECK_MPI_OK( mp_to_fixlen_octets(&Ry, pointR->data + 1 + len,
|
||||
(mp_size) len) );
|
||||
rv = SECSuccess;
|
||||
|
||||
#if EC_DEBUG
|
||||
printf("ec_point_add: pointR [len=%d]:", pointR->len);
|
||||
for (i = 0; i < pointR->len; i++)
|
||||
printf("%02x:", pointR->data[i]);
|
||||
printf("\n");
|
||||
#endif
|
||||
|
||||
cleanup:
|
||||
mp_clear(&Px);
|
||||
mp_clear(&Py);
|
||||
mp_clear(&Qx);
|
||||
mp_clear(&Qy);
|
||||
mp_clear(&Rx);
|
||||
mp_clear(&Ry);
|
||||
mp_clear(&irreducible);
|
||||
mp_clear(&a);
|
||||
if (err) {
|
||||
MP_TO_SEC_ERROR(err);
|
||||
rv = SECFailure;
|
||||
}
|
||||
|
||||
return rv;
|
||||
}
|
||||
|
||||
/*
|
||||
* Computes scalar point multiplication pointQ = k * pointP for
|
||||
* the curve whose parameters are encoded in params.
|
||||
*/
|
||||
SECStatus
|
||||
ec_point_mul(ECParams *params, mp_int *k,
|
||||
SECItem *pointP, SECItem *pointQ)
|
||||
{
|
||||
mp_int Px, Py, Qx, Qy;
|
||||
mp_int irreducible, a, b;
|
||||
SECStatus rv = SECFailure;
|
||||
mp_err err = MP_OKAY;
|
||||
int len;
|
||||
|
||||
#if EC_DEBUG
|
||||
int i;
|
||||
char mpstr[256];
|
||||
|
||||
printf("ec_point_mul: params [len=%d]:", params->DEREncoding.len);
|
||||
for (i = 0; i < params->DEREncoding.len; i++)
|
||||
printf("%02x:", params->DEREncoding.data[i]);
|
||||
printf("\n");
|
||||
|
||||
mp_tohex(k, mpstr);
|
||||
printf("ec_point_mul: scalar : %s\n", mpstr);
|
||||
mp_todecimal(k, mpstr);
|
||||
printf("ec_point_mul: scalar : %s (dec)\n", mpstr);
|
||||
|
||||
printf("ec_point_mul: pointP [len=%d]:", pointP->len);
|
||||
for (i = 0; i < pointP->len; i++)
|
||||
printf("%02x:", pointP->data[i]);
|
||||
printf("\n");
|
||||
#endif
|
||||
|
||||
/* NOTE: We only support prime field curves for now */
|
||||
len = (params->fieldID.size + 7) >> 3;
|
||||
if ((pointP->data[0] != EC_POINT_FORM_UNCOMPRESSED) ||
|
||||
(pointP->len != (2 * len + 1))) {
|
||||
return SECFailure;
|
||||
};
|
||||
|
||||
MP_DIGITS(&Px) = 0;
|
||||
MP_DIGITS(&Py) = 0;
|
||||
MP_DIGITS(&Qx) = 0;
|
||||
MP_DIGITS(&Qy) = 0;
|
||||
MP_DIGITS(&irreducible) = 0;
|
||||
MP_DIGITS(&a) = 0;
|
||||
MP_DIGITS(&b) = 0;
|
||||
CHECK_MPI_OK( mp_init(&Px) );
|
||||
CHECK_MPI_OK( mp_init(&Py) );
|
||||
CHECK_MPI_OK( mp_init(&Qx) );
|
||||
CHECK_MPI_OK( mp_init(&Qy) );
|
||||
CHECK_MPI_OK( mp_init(&irreducible) );
|
||||
CHECK_MPI_OK( mp_init(&a) );
|
||||
CHECK_MPI_OK( mp_init(&b) );
|
||||
|
||||
/* Initialize Px and Py */
|
||||
CHECK_MPI_OK( mp_read_unsigned_octets(&Px, pointP->data + 1,
|
||||
(mp_size) len) );
|
||||
CHECK_MPI_OK( mp_read_unsigned_octets(&Py, pointP->data + 1 + len,
|
||||
(mp_size) len) );
|
||||
|
||||
/* Set up mp_ints containing the curve coefficients */
|
||||
SECITEM_TO_MPINT( params->curve.a, &a );
|
||||
SECITEM_TO_MPINT( params->curve.b, &b );
|
||||
|
||||
/* Compute Q = k * P */
|
||||
if (params->fieldID.type == ec_field_GFp) {
|
||||
SECITEM_TO_MPINT( params->fieldID.u.prime, &irreducible );
|
||||
if (GFp_ec_pt_mul(&irreducible, &a, &b, &Px, &Py, k, &Qx, &Qy)
|
||||
!= SECSuccess)
|
||||
goto cleanup;
|
||||
} else {
|
||||
SECITEM_TO_MPINT( params->fieldID.u.poly, &irreducible );
|
||||
if (GF2m_ec_pt_mul(&irreducible, &a, &b, &Px, &Py, k, &Qx, &Qy)
|
||||
!= SECSuccess) {
|
||||
goto cleanup;
|
||||
}
|
||||
}
|
||||
|
||||
/* Construct the SECItem representation of point Q */
|
||||
pointQ->data[0] = EC_POINT_FORM_UNCOMPRESSED;
|
||||
CHECK_MPI_OK( mp_to_fixlen_octets(&Qx, pointQ->data + 1,
|
||||
(mp_size) len) );
|
||||
CHECK_MPI_OK( mp_to_fixlen_octets(&Qy, pointQ->data + 1 + len,
|
||||
(mp_size) len) );
|
||||
|
||||
rv = SECSuccess;
|
||||
|
||||
#if EC_DEBUG
|
||||
printf("ec_point_mul: pointQ [len=%d]:", pointQ->len);
|
||||
for (i = 0; i < pointQ->len; i++)
|
||||
printf("%02x:", pointQ->data[i]);
|
||||
printf("\n");
|
||||
#endif
|
||||
|
||||
cleanup:
|
||||
mp_clear(&Px);
|
||||
mp_clear(&Py);
|
||||
mp_clear(&Qx);
|
||||
mp_clear(&Qy);
|
||||
mp_clear(&irreducible);
|
||||
mp_clear(&a);
|
||||
mp_clear(&b);
|
||||
if (err) {
|
||||
MP_TO_SEC_ERROR(err);
|
||||
rv = SECFailure;
|
||||
}
|
||||
|
||||
return rv;
|
||||
}
|
||||
|
||||
static unsigned char bitmask[] = {
|
||||
0xff, 0x7f, 0x3f, 0x1f,
|
||||
0x0f, 0x07, 0x03, 0x01
|
||||
};
|
||||
#endif /* NSS_ENABLE_ECC */
|
||||
|
||||
/* Generates a new EC key pair. The private key is a supplied
|
||||
* random value (in seed) and the public key is the result of
|
||||
* performing a scalar point multiplication of that value with
|
||||
* the curve's base point.
|
||||
*/
|
||||
SECStatus
|
||||
EC_NewKeyFromSeed(ECParams *ecParams, ECPrivateKey **privKey,
|
||||
const unsigned char *seed, int seedlen)
|
||||
{
|
||||
SECStatus rv = SECFailure;
|
||||
#ifdef NSS_ENABLE_ECC
|
||||
PRArenaPool *arena;
|
||||
ECPrivateKey *key;
|
||||
mp_int k;
|
||||
mp_err err = MP_OKAY;
|
||||
int len;
|
||||
|
||||
#if EC_DEBUG
|
||||
printf("EC_NewKeyFromSeed called\n");
|
||||
#endif
|
||||
|
||||
if (!ecParams || !privKey || !seed || (seedlen < 0)) {
|
||||
PORT_SetError(SEC_ERROR_INVALID_ARGS);
|
||||
return SECFailure;
|
||||
}
|
||||
|
||||
/* Initialize an arena for the EC key. */
|
||||
if (!(arena = PORT_NewArena(NSS_FREEBL_DEFAULT_CHUNKSIZE)))
|
||||
return SECFailure;
|
||||
|
||||
key = (ECPrivateKey *)PORT_ArenaZAlloc(arena, sizeof(ECPrivateKey));
|
||||
if (!key) {
|
||||
PORT_FreeArena(arena, PR_TRUE);
|
||||
return SECFailure;
|
||||
}
|
||||
|
||||
|
||||
/* Copy all of the fields from the ECParams argument to the
|
||||
* ECParams structure within the private key.
|
||||
*/
|
||||
key->ecParams.arena = arena;
|
||||
key->ecParams.type = ecParams->type;
|
||||
key->ecParams.fieldID.size = ecParams->fieldID.size;
|
||||
key->ecParams.fieldID.type = ecParams->fieldID.type;
|
||||
if (ecParams->fieldID.type == ec_field_GFp) {
|
||||
CHECK_SEC_OK(SECITEM_CopyItem(arena, &key->ecParams.fieldID.u.prime,
|
||||
&ecParams->fieldID.u.prime));
|
||||
} else {
|
||||
CHECK_SEC_OK(SECITEM_CopyItem(arena, &key->ecParams.fieldID.u.poly,
|
||||
&ecParams->fieldID.u.poly));
|
||||
}
|
||||
key->ecParams.fieldID.k1 = ecParams->fieldID.k1;
|
||||
key->ecParams.fieldID.k2 = ecParams->fieldID.k2;
|
||||
key->ecParams.fieldID.k3 = ecParams->fieldID.k3;
|
||||
CHECK_SEC_OK(SECITEM_CopyItem(arena, &key->ecParams.curve.a,
|
||||
&ecParams->curve.a));
|
||||
CHECK_SEC_OK(SECITEM_CopyItem(arena, &key->ecParams.curve.b,
|
||||
&ecParams->curve.b));
|
||||
CHECK_SEC_OK(SECITEM_CopyItem(arena, &key->ecParams.curve.seed,
|
||||
&ecParams->curve.seed));
|
||||
CHECK_SEC_OK(SECITEM_CopyItem(arena, &key->ecParams.base,
|
||||
&ecParams->base));
|
||||
CHECK_SEC_OK(SECITEM_CopyItem(arena, &key->ecParams.order,
|
||||
&ecParams->order));
|
||||
key->ecParams.cofactor = ecParams->cofactor;
|
||||
CHECK_SEC_OK(SECITEM_CopyItem(arena, &key->ecParams.DEREncoding,
|
||||
&ecParams->DEREncoding));
|
||||
|
||||
len = (ecParams->fieldID.size + 7) >> 3;
|
||||
SECITEM_AllocItem(arena, &key->privateValue, len);
|
||||
SECITEM_AllocItem(arena, &key->publicValue, 2*len + 1);
|
||||
|
||||
/* Copy private key */
|
||||
if (seedlen >= len) {
|
||||
memcpy(key->privateValue.data, seed, len);
|
||||
} else {
|
||||
memset(key->privateValue.data, 0, (len - seedlen));
|
||||
memcpy(key->privateValue.data + (len - seedlen), seed, seedlen);
|
||||
}
|
||||
|
||||
/* Compute corresponding public key */
|
||||
MP_DIGITS(&k) = 0;
|
||||
CHECK_MPI_OK( mp_init(&k) );
|
||||
CHECK_MPI_OK( mp_read_unsigned_octets(&k, key->privateValue.data,
|
||||
(mp_size) len) );
|
||||
|
||||
rv = ec_point_mul(ecParams, &k, &(ecParams->base), &(key->publicValue));
|
||||
if (rv != SECSuccess) goto cleanup;
|
||||
*privKey = key;
|
||||
|
||||
cleanup:
|
||||
mp_clear(&k);
|
||||
if (rv)
|
||||
PORT_FreeArena(arena, PR_TRUE);
|
||||
|
||||
#if EC_DEBUG
|
||||
printf("EC_NewKeyFromSeed returning %s\n",
|
||||
(rv == SECSuccess) ? "success" : "failure");
|
||||
#endif
|
||||
#else
|
||||
PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
|
||||
#endif /* NSS_ENABLE_ECC */
|
||||
|
||||
return rv;
|
||||
|
||||
}
|
||||
|
||||
/* Generates a new EC key pair. The private key is a random value and
|
||||
* the public key is the result of performing a scalar point multiplication
|
||||
* of that value with the curve's base point.
|
||||
*/
|
||||
SECStatus
|
||||
EC_NewKey(ECParams *ecParams, ECPrivateKey **privKey)
|
||||
{
|
||||
SECStatus rv = SECFailure;
|
||||
#ifdef NSS_ENABLE_ECC
|
||||
int len;
|
||||
unsigned char *seed;
|
||||
|
||||
if (!ecParams || !privKey) {
|
||||
PORT_SetError(SEC_ERROR_INVALID_ARGS);
|
||||
return SECFailure;
|
||||
}
|
||||
|
||||
/* Generate random private key */
|
||||
len = (ecParams->fieldID.size + 7) >> 3;
|
||||
if ((seed = PORT_Alloc(len)) == NULL) goto cleanup;
|
||||
if (RNG_GenerateGlobalRandomBytes(seed, len) != SECSuccess) goto cleanup;
|
||||
|
||||
/* Fit private key to the field size */
|
||||
seed[0] &= bitmask[len * 8 - ecParams->fieldID.size];
|
||||
rv = EC_NewKeyFromSeed(ecParams, privKey, seed, len);
|
||||
|
||||
cleanup:
|
||||
if (!seed) {
|
||||
PORT_ZFree(seed, len);
|
||||
}
|
||||
#if EC_DEBUG
|
||||
printf("EC_NewKey returning %s\n",
|
||||
(rv == SECSuccess) ? "success" : "failure");
|
||||
#endif
|
||||
#else
|
||||
PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
|
||||
#endif /* NSS_ENABLE_ECC */
|
||||
|
||||
return rv;
|
||||
}
|
||||
|
||||
/* Validates an EC public key as described in Section 5.2.2 of
|
||||
* X9.63. The ECDH primitive when used without the cofactor does
|
||||
* not address small subgroup attacks, which may occur when the
|
||||
* public key is not valid. These attacks can be prevented by
|
||||
* validating the public key before using ECDH.
|
||||
*/
|
||||
SECStatus
|
||||
EC_ValidatePublicKey(ECParams *ecParams, SECItem *publicValue)
|
||||
{
|
||||
#ifdef NSS_ENABLE_ECC
|
||||
if (!ecParams || !publicValue) {
|
||||
PORT_SetError(SEC_ERROR_INVALID_ARGS);
|
||||
return SECFailure;
|
||||
}
|
||||
|
||||
/* XXX Add actual checks here. */
|
||||
return SECSuccess;
|
||||
#else
|
||||
PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
|
||||
return SECFailure;
|
||||
#endif /* NSS_ENABLE_ECC */
|
||||
}
|
||||
|
||||
/*
|
||||
** Performs an ECDH key derivation by computing the scalar point
|
||||
** multiplication of privateValue and publicValue (with or without the
|
||||
** cofactor) and returns the x-coordinate of the resulting elliptic
|
||||
** curve point in derived secret. If successful, derivedSecret->data
|
||||
** is set to the address of the newly allocated buffer containing the
|
||||
** derived secret, and derivedSecret->len is the size of the secret
|
||||
** produced. It is the caller's responsibility to free the allocated
|
||||
** buffer containing the derived secret.
|
||||
*/
|
||||
SECStatus
|
||||
ECDH_Derive(SECItem *publicValue,
|
||||
ECParams *ecParams,
|
||||
SECItem *privateValue,
|
||||
PRBool withCofactor,
|
||||
SECItem *derivedSecret)
|
||||
{
|
||||
SECStatus rv = SECFailure;
|
||||
#ifdef NSS_ENABLE_ECC
|
||||
unsigned int len = 0;
|
||||
SECItem pointQ = {siBuffer, NULL, 0};
|
||||
mp_int k; /* to hold the private value */
|
||||
mp_int cofactor;
|
||||
mp_err err = MP_OKAY;
|
||||
#if EC_DEBUG
|
||||
int i;
|
||||
#endif
|
||||
|
||||
if (!publicValue || !ecParams || !privateValue ||
|
||||
!derivedSecret) {
|
||||
PORT_SetError(SEC_ERROR_INVALID_ARGS);
|
||||
return SECFailure;
|
||||
}
|
||||
|
||||
memset(derivedSecret, 0, sizeof *derivedSecret);
|
||||
len = (ecParams->fieldID.size + 7) >> 3;
|
||||
pointQ.len = 2*len + 1;
|
||||
if ((pointQ.data = PORT_Alloc(2*len + 1)) == NULL) goto cleanup;
|
||||
|
||||
MP_DIGITS(&k) = 0;
|
||||
CHECK_MPI_OK( mp_init(&k) );
|
||||
CHECK_MPI_OK( mp_read_unsigned_octets(&k, privateValue->data,
|
||||
(mp_size) privateValue->len) );
|
||||
|
||||
if (withCofactor && (ecParams->cofactor != 1)) {
|
||||
/* multiply k with the cofactor */
|
||||
MP_DIGITS(&cofactor) = 0;
|
||||
CHECK_MPI_OK( mp_init(&cofactor) );
|
||||
mp_set(&cofactor, ecParams->cofactor);
|
||||
CHECK_MPI_OK( mp_mul(&k, &cofactor, &k) );
|
||||
}
|
||||
|
||||
/* Multiply our private key and peer's public point */
|
||||
if ((ec_point_mul(ecParams, &k, publicValue, &pointQ) != SECSuccess) ||
|
||||
ec_point_at_infinity(&pointQ))
|
||||
goto cleanup;
|
||||
|
||||
/* Allocate memory for the derived secret and copy
|
||||
* the x co-ordinate of pointQ into it.
|
||||
*/
|
||||
SECITEM_AllocItem(NULL, derivedSecret, len);
|
||||
memcpy(derivedSecret->data, pointQ.data + 1, len);
|
||||
|
||||
rv = SECSuccess;
|
||||
|
||||
#if EC_DEBUG
|
||||
printf("derived_secret:\n");
|
||||
for (i = 0; i < derivedSecret->len; i++)
|
||||
printf("%02x:", derivedSecret->data[i]);
|
||||
printf("\n");
|
||||
#endif
|
||||
|
||||
cleanup:
|
||||
mp_clear(&k);
|
||||
|
||||
if (pointQ.data) {
|
||||
PORT_ZFree(pointQ.data, 2*len + 1);
|
||||
}
|
||||
#else
|
||||
PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
|
||||
#endif /* NSS_ENABLE_ECC */
|
||||
|
||||
return rv;
|
||||
}
|
||||
|
||||
/* Computes the ECDSA signature (a concatenation of two values r and s)
|
||||
* on the digest using the given key and the random value kb (used in
|
||||
* computing s).
|
||||
*/
|
||||
SECStatus
|
||||
ECDSA_SignDigestWithSeed(ECPrivateKey *key, SECItem *signature,
|
||||
const SECItem *digest, const unsigned char *kb, const int kblen)
|
||||
{
|
||||
SECStatus rv = SECFailure;
|
||||
#ifdef NSS_ENABLE_ECC
|
||||
mp_int x1;
|
||||
mp_int d, k; /* private key, random integer */
|
||||
mp_int r, s; /* tuple (r, s) is the signature */
|
||||
mp_int n;
|
||||
mp_err err = MP_OKAY;
|
||||
ECParams *ecParams = NULL;
|
||||
SECItem kGpoint = { siBuffer, NULL, 0};
|
||||
int len = 0;
|
||||
|
||||
#if EC_DEBUG
|
||||
char mpstr[256];
|
||||
#endif
|
||||
|
||||
/* Check args */
|
||||
if (!key || !signature || !digest || !kb || (kblen < 0) ||
|
||||
(digest->len != SHA1_LENGTH)) {
|
||||
PORT_SetError(SEC_ERROR_INVALID_ARGS);
|
||||
goto cleanup;
|
||||
}
|
||||
|
||||
ecParams = &(key->ecParams);
|
||||
len = (ecParams->fieldID.size + 7) >> 3;
|
||||
if (signature->len < 2*len) {
|
||||
PORT_SetError(SEC_ERROR_INVALID_ARGS);
|
||||
goto cleanup;
|
||||
}
|
||||
|
||||
/* Initialize MPI integers. */
|
||||
MP_DIGITS(&x1) = 0;
|
||||
MP_DIGITS(&d) = 0;
|
||||
MP_DIGITS(&k) = 0;
|
||||
MP_DIGITS(&r) = 0;
|
||||
MP_DIGITS(&s) = 0;
|
||||
MP_DIGITS(&n) = 0;
|
||||
CHECK_MPI_OK( mp_init(&x1) );
|
||||
CHECK_MPI_OK( mp_init(&d) );
|
||||
CHECK_MPI_OK( mp_init(&k) );
|
||||
CHECK_MPI_OK( mp_init(&r) );
|
||||
CHECK_MPI_OK( mp_init(&s) );
|
||||
CHECK_MPI_OK( mp_init(&n) );
|
||||
|
||||
SECITEM_TO_MPINT( ecParams->order, &n );
|
||||
SECITEM_TO_MPINT( key->privateValue, &d );
|
||||
CHECK_MPI_OK( mp_read_unsigned_octets(&k, kb, kblen) );
|
||||
/* Make sure k is in the interval [1, n-1] */
|
||||
if ((mp_cmp_z(&k) <= 0) || (mp_cmp(&k, &n) >= 0)) {
|
||||
PORT_SetError(SEC_ERROR_NEED_RANDOM);
|
||||
goto cleanup;
|
||||
}
|
||||
|
||||
/*
|
||||
** ANSI X9.62, Section 5.3.2, Step 2
|
||||
**
|
||||
** Compute kG
|
||||
*/
|
||||
kGpoint.len = 2*len + 1;
|
||||
kGpoint.data = PORT_Alloc(2*len + 1);
|
||||
if ((kGpoint.data == NULL) ||
|
||||
(ec_point_mul(ecParams, &k, &(ecParams->base), &kGpoint)
|
||||
!= SECSuccess))
|
||||
goto cleanup;
|
||||
|
||||
/*
|
||||
** ANSI X9.62, Section 5.3.3, Step 1
|
||||
**
|
||||
** Extract the x co-ordinate of kG into x1
|
||||
*/
|
||||
CHECK_MPI_OK( mp_read_unsigned_octets(&x1, kGpoint.data + 1,
|
||||
(mp_size) len) );
|
||||
|
||||
/*
|
||||
** ANSI X9.62, Section 5.3.3, Step 2
|
||||
**
|
||||
** r = x1 mod n NOTE: n is the order of the curve
|
||||
*/
|
||||
CHECK_MPI_OK( mp_mod(&x1, &n, &r) );
|
||||
|
||||
/*
|
||||
** ANSI X9.62, Section 5.3.3, Step 3
|
||||
**
|
||||
** verify r != 0
|
||||
*/
|
||||
if (mp_cmp_z(&r) == 0) {
|
||||
PORT_SetError(SEC_ERROR_NEED_RANDOM);
|
||||
goto cleanup;
|
||||
}
|
||||
|
||||
/*
|
||||
** ANSI X9.62, Section 5.3.3, Step 4
|
||||
**
|
||||
** s = (k**-1 * (SHA1(M) + d*r)) mod n
|
||||
*/
|
||||
SECITEM_TO_MPINT(*digest, &s); /* s = SHA1(M) */
|
||||
|
||||
#if EC_DEBUG
|
||||
mp_todecimal(&n, mpstr);
|
||||
printf("n : %s (dec)\n", mpstr);
|
||||
mp_todecimal(&d, mpstr);
|
||||
printf("d : %s (dec)\n", mpstr);
|
||||
mp_tohex(&x1, mpstr);
|
||||
printf("x1: %s\n", mpstr);
|
||||
mp_todecimal(&s, mpstr);
|
||||
printf("digest: %s (decimal)\n", mpstr);
|
||||
mp_todecimal(&r, mpstr);
|
||||
printf("r : %s (dec)\n", mpstr);
|
||||
#endif
|
||||
|
||||
CHECK_MPI_OK( mp_invmod(&k, &n, &k) ); /* k = k**-1 mod n */
|
||||
CHECK_MPI_OK( mp_mulmod(&d, &r, &n, &d) ); /* d = d * r mod n */
|
||||
CHECK_MPI_OK( mp_addmod(&s, &d, &n, &s) ); /* s = s + d mod n */
|
||||
CHECK_MPI_OK( mp_mulmod(&s, &k, &n, &s) ); /* s = s * k mod n */
|
||||
|
||||
#if EC_DEBUG
|
||||
mp_todecimal(&s, mpstr);
|
||||
printf("s : %s (dec)\n", mpstr);
|
||||
#endif
|
||||
|
||||
/*
|
||||
** ANSI X9.62, Section 5.3.3, Step 5
|
||||
**
|
||||
** verify s != 0
|
||||
*/
|
||||
if (mp_cmp_z(&s) == 0) {
|
||||
PORT_SetError(SEC_ERROR_NEED_RANDOM);
|
||||
goto cleanup;
|
||||
}
|
||||
|
||||
/*
|
||||
**
|
||||
** Signature is tuple (r, s)
|
||||
*/
|
||||
CHECK_MPI_OK( mp_to_fixlen_octets(&r, signature->data, len) );
|
||||
CHECK_MPI_OK( mp_to_fixlen_octets(&s, signature->data + len, len) );
|
||||
signature->len = 2*len;
|
||||
|
||||
rv = SECSuccess;
|
||||
err = MP_OKAY;
|
||||
cleanup:
|
||||
mp_clear(&x1);
|
||||
mp_clear(&d);
|
||||
mp_clear(&k);
|
||||
mp_clear(&r);
|
||||
mp_clear(&s);
|
||||
mp_clear(&n);
|
||||
|
||||
if (kGpoint.data) {
|
||||
PORT_ZFree(kGpoint.data, 2*len + 1);
|
||||
}
|
||||
|
||||
if (err) {
|
||||
MP_TO_SEC_ERROR(err);
|
||||
rv = SECFailure;
|
||||
}
|
||||
|
||||
#if EC_DEBUG
|
||||
printf("ECDSA signing with seed %s\n",
|
||||
(rv == SECSuccess) ? "succeeded" : "failed");
|
||||
#endif
|
||||
#else
|
||||
PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
|
||||
#endif /* NSS_ENABLE_ECC */
|
||||
|
||||
return rv;
|
||||
}
|
||||
|
||||
/*
|
||||
** Computes the ECDSA signature on the digest using the given key
|
||||
** and a random seed.
|
||||
*/
|
||||
SECStatus
|
||||
ECDSA_SignDigest(ECPrivateKey *key, SECItem *signature, const SECItem *digest)
|
||||
{
|
||||
SECStatus rv = SECFailure;
|
||||
#ifdef NSS_ENABLE_ECC
|
||||
int prerr = 0;
|
||||
int n = (key->ecParams.fieldID.size + 7) >> 3;
|
||||
unsigned char mask = bitmask[n * 8 - key->ecParams.fieldID.size];
|
||||
unsigned char *kseed = NULL;
|
||||
|
||||
/* Generate random seed of appropriate size as dictated
|
||||
* by field size.
|
||||
*/
|
||||
if ((kseed = PORT_Alloc(n)) == NULL) return SECFailure;
|
||||
|
||||
do {
|
||||
if (RNG_GenerateGlobalRandomBytes(kseed, n) != SECSuccess)
|
||||
goto cleanup;
|
||||
*kseed &= mask;
|
||||
rv = ECDSA_SignDigestWithSeed(key, signature, digest, kseed, n);
|
||||
if (rv) prerr = PORT_GetError();
|
||||
} while ((rv != SECSuccess) && (prerr == SEC_ERROR_NEED_RANDOM));
|
||||
|
||||
cleanup:
|
||||
if (kseed) PORT_ZFree(kseed, n);
|
||||
|
||||
#if EC_DEBUG
|
||||
printf("ECDSA signing %s\n",
|
||||
(rv == SECSuccess) ? "succeeded" : "failed");
|
||||
#endif
|
||||
#else
|
||||
PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
|
||||
#endif /* NSS_ENABLE_ECC */
|
||||
|
||||
return rv;
|
||||
}
|
||||
|
||||
/*
|
||||
** Checks the signature on the given digest using the key provided.
|
||||
*/
|
||||
SECStatus
|
||||
ECDSA_VerifyDigest(ECPublicKey *key, const SECItem *signature,
|
||||
const SECItem *digest)
|
||||
{
|
||||
SECStatus rv = SECFailure;
|
||||
#ifdef NSS_ENABLE_ECC
|
||||
mp_int r_, s_; /* tuple (r', s') is received signature) */
|
||||
mp_int c, u1, u2, v; /* intermediate values used in verification */
|
||||
mp_int x1, y1;
|
||||
mp_int x2, y2;
|
||||
mp_int n;
|
||||
mp_err err = MP_OKAY;
|
||||
PRArenaPool *arena = NULL;
|
||||
ECParams *ecParams = NULL;
|
||||
SECItem pointA = { siBuffer, NULL, 0 };
|
||||
SECItem pointB = { siBuffer, NULL, 0 };
|
||||
SECItem pointC = { siBuffer, NULL, 0 };
|
||||
int len;
|
||||
|
||||
#if EC_DEBUG
|
||||
char mpstr[256];
|
||||
printf("ECDSA verification called\n");
|
||||
#endif
|
||||
|
||||
/* Check args */
|
||||
if (!key || !signature || !digest ||
|
||||
(digest->len != SHA1_LENGTH)) {
|
||||
PORT_SetError(SEC_ERROR_INVALID_ARGS);
|
||||
goto cleanup;
|
||||
}
|
||||
|
||||
ecParams = &(key->ecParams);
|
||||
len = (ecParams->fieldID.size + 7) >> 3;
|
||||
if (signature->len < 2*len) {
|
||||
PORT_SetError(SEC_ERROR_INVALID_ARGS);
|
||||
goto cleanup;
|
||||
}
|
||||
|
||||
/* Initialize an arena for pointA, pointB and pointC */
|
||||
if ((arena = PORT_NewArena(NSS_FREEBL_DEFAULT_CHUNKSIZE)) == NULL)
|
||||
goto cleanup;
|
||||
|
||||
SECITEM_AllocItem(arena, &pointA, 2*len + 1);
|
||||
SECITEM_AllocItem(arena, &pointB, 2*len + 1);
|
||||
SECITEM_AllocItem(arena, &pointC, 2*len + 1);
|
||||
if (pointA.data == NULL || pointB.data == NULL || pointC.data == NULL)
|
||||
goto cleanup;
|
||||
|
||||
/* Initialize MPI integers. */
|
||||
MP_DIGITS(&r_) = 0;
|
||||
MP_DIGITS(&s_) = 0;
|
||||
MP_DIGITS(&c) = 0;
|
||||
MP_DIGITS(&u1) = 0;
|
||||
MP_DIGITS(&u2) = 0;
|
||||
MP_DIGITS(&x1) = 0;
|
||||
MP_DIGITS(&y1) = 0;
|
||||
MP_DIGITS(&x2) = 0;
|
||||
MP_DIGITS(&y2) = 0;
|
||||
MP_DIGITS(&v) = 0;
|
||||
MP_DIGITS(&n) = 0;
|
||||
CHECK_MPI_OK( mp_init(&r_) );
|
||||
CHECK_MPI_OK( mp_init(&s_) );
|
||||
CHECK_MPI_OK( mp_init(&c) );
|
||||
CHECK_MPI_OK( mp_init(&u1) );
|
||||
CHECK_MPI_OK( mp_init(&u2) );
|
||||
CHECK_MPI_OK( mp_init(&x1) );
|
||||
CHECK_MPI_OK( mp_init(&y1) );
|
||||
CHECK_MPI_OK( mp_init(&x2) );
|
||||
CHECK_MPI_OK( mp_init(&y2) );
|
||||
CHECK_MPI_OK( mp_init(&v) );
|
||||
CHECK_MPI_OK( mp_init(&n) );
|
||||
|
||||
/*
|
||||
** Convert received signature (r', s') into MPI integers.
|
||||
*/
|
||||
CHECK_MPI_OK( mp_read_unsigned_octets(&r_, signature->data, len) );
|
||||
CHECK_MPI_OK( mp_read_unsigned_octets(&s_, signature->data + len, len) );
|
||||
|
||||
/*
|
||||
** ANSI X9.62, Section 5.4.2, Steps 1 and 2
|
||||
**
|
||||
** Verify that 0 < r' < n and 0 < s' < n
|
||||
*/
|
||||
SECITEM_TO_MPINT(ecParams->order, &n);
|
||||
if (mp_cmp_z(&r_) <= 0 || mp_cmp_z(&s_) <= 0 ||
|
||||
mp_cmp(&r_, &n) >= 0 || mp_cmp(&s_, &n) >= 0)
|
||||
goto cleanup; /* will return rv == SECFailure */
|
||||
|
||||
/*
|
||||
** ANSI X9.62, Section 5.4.2, Step 3
|
||||
**
|
||||
** c = (s')**-1 mod n
|
||||
*/
|
||||
CHECK_MPI_OK( mp_invmod(&s_, &n, &c) ); /* c = (s')**-1 mod n */
|
||||
|
||||
/*
|
||||
** ANSI X9.62, Section 5.4.2, Step 4
|
||||
**
|
||||
** u1 = ((SHA1(M')) * c) mod n
|
||||
*/
|
||||
SECITEM_TO_MPINT(*digest, &u1); /* u1 = SHA1(M') */
|
||||
|
||||
#if EC_DEBUG
|
||||
mp_todecimal(&r_, mpstr);
|
||||
printf("r_: %s (dec)\n", mpstr);
|
||||
mp_todecimal(&s_, mpstr);
|
||||
printf("s_: %s (dec)\n", mpstr);
|
||||
mp_todecimal(&c, mpstr);
|
||||
printf("c : %s (dec)\n", mpstr);
|
||||
mp_todecimal(&u1, mpstr);
|
||||
printf("digest: %s (dec)\n", mpstr);
|
||||
#endif
|
||||
|
||||
CHECK_MPI_OK( mp_mulmod(&u1, &c, &n, &u1) ); /* u1 = u1 * c mod n */
|
||||
|
||||
/*
|
||||
** ANSI X9.62, Section 5.4.2, Step 4
|
||||
**
|
||||
** u2 = ((r') * c) mod n
|
||||
*/
|
||||
CHECK_MPI_OK( mp_mulmod(&r_, &c, &n, &u2) );
|
||||
|
||||
/*
|
||||
** ANSI X9.62, Section 5.4.3, Step 1
|
||||
**
|
||||
** Compute u1*G + u2*Q
|
||||
** Here, A = u1.G B = u2.Q and C = A + B
|
||||
** If the result, C, is the point at infinity, reject the signature
|
||||
*/
|
||||
if ((ec_point_mul(ecParams, &u1, &ecParams->base, &pointA)
|
||||
== SECFailure) ||
|
||||
(ec_point_mul(ecParams, &u2, &key->publicValue, &pointB)
|
||||
== SECFailure) ||
|
||||
(ec_point_add(ecParams, &pointA, &pointB, &pointC) == SECFailure) ||
|
||||
ec_point_at_infinity(&pointC)) {
|
||||
rv = SECFailure;
|
||||
goto cleanup;
|
||||
}
|
||||
|
||||
CHECK_MPI_OK( mp_read_unsigned_octets(&x1, pointC.data + 1, len) );
|
||||
|
||||
/*
|
||||
** ANSI X9.62, Section 5.4.4, Step 2
|
||||
**
|
||||
** v = x1 mod n
|
||||
*/
|
||||
CHECK_MPI_OK( mp_mod(&x1, &n, &v) );
|
||||
|
||||
/*
|
||||
** ANSI X9.62, Section 5.4.4, Step 3
|
||||
**
|
||||
** Verification: v == r'
|
||||
*/
|
||||
if (mp_cmp(&v, &r_)) {
|
||||
PORT_SetError(SEC_ERROR_BAD_SIGNATURE);
|
||||
rv = SECFailure; /* Signature failed to verify. */
|
||||
} else {
|
||||
rv = SECSuccess; /* Signature verified. */
|
||||
}
|
||||
|
||||
#if EC_DEBUG
|
||||
mp_todecimal(&u1, mpstr);
|
||||
printf("u1: %s (dec)\n", mpstr);
|
||||
mp_todecimal(&u2, mpstr);
|
||||
printf("u2: %s (dec)\n", mpstr);
|
||||
mp_tohex(&x1, mpstr);
|
||||
printf("x1: %s\n", mpstr);
|
||||
mp_todecimal(&v, mpstr);
|
||||
printf("v : %s (dec)\n", mpstr);
|
||||
#endif
|
||||
|
||||
cleanup:
|
||||
mp_clear(&r_);
|
||||
mp_clear(&s_);
|
||||
mp_clear(&c);
|
||||
mp_clear(&u1);
|
||||
mp_clear(&u2);
|
||||
mp_clear(&x1);
|
||||
mp_clear(&y1);
|
||||
mp_clear(&x2);
|
||||
mp_clear(&y2);
|
||||
mp_clear(&v);
|
||||
mp_clear(&n);
|
||||
|
||||
if (arena) PORT_FreeArena(arena, PR_TRUE);
|
||||
if (err) {
|
||||
MP_TO_SEC_ERROR(err);
|
||||
rv = SECFailure;
|
||||
}
|
||||
|
||||
#if EC_DEBUG
|
||||
printf("ECDSA verification %s\n",
|
||||
(rv == SECSuccess) ? "succeeded" : "failed");
|
||||
#endif
|
||||
#else
|
||||
PORT_SetError(SEC_ERROR_UNSUPPORTED_KEYALG);
|
||||
#endif /* NSS_ENABLE_ECC */
|
||||
|
||||
return rv;
|
||||
}
|
||||
|
||||
50
mozilla/security/nss/lib/freebl/ec.h
Normal file
50
mozilla/security/nss/lib/freebl/ec.h
Normal file
@@ -0,0 +1,50 @@
|
||||
/*
|
||||
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
|
||||
*
|
||||
* The contents of this file are subject to the Mozilla Public License Version
|
||||
* 1.1 (the "License"); you may not use this file except in compliance with
|
||||
* the License. You may obtain a copy of the License at
|
||||
* http://www.mozilla.org/MPL/
|
||||
*
|
||||
* Software distributed under the License is distributed on an "AS IS" basis,
|
||||
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
|
||||
* for the specific language governing rights and limitations under the
|
||||
* License.
|
||||
*
|
||||
* The Original Code is the Elliptic Curve Cryptography library.
|
||||
*
|
||||
* The Initial Developer of the Original Code is Sun Microsystems, Inc.
|
||||
* Portions created by Sun Microsystems, Inc. are Copyright (C) 2003
|
||||
* Sun Microsystems, Inc. All Rights Reserved.
|
||||
*
|
||||
* Contributor(s):
|
||||
* Dr Vipul Gupta <vipul.gupta@sun.com>, Sun Microsystems Laboratories
|
||||
*
|
||||
* Alternatively, the contents of this file may be used under the terms of
|
||||
* either the GNU General Public License Version 2 or later (the "GPL"), or
|
||||
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
|
||||
* in which case the provisions of the GPL or the LGPL are applicable instead
|
||||
* of those above. If you wish to allow use of your version of this file only
|
||||
* under the terms of either the GPL or the LGPL, and not to allow others to
|
||||
* use your version of this file under the terms of the MPL, indicate your
|
||||
* decision by deleting the provisions above and replace them with the notice
|
||||
* and other provisions required by the GPL or the LGPL. If you do not delete
|
||||
* the provisions above, a recipient may use your version of this file under
|
||||
* the terms of any one of the MPL, the GPL or the LGPL.
|
||||
*
|
||||
*/
|
||||
|
||||
#ifndef __ec_h_
|
||||
#define __ec_h_
|
||||
|
||||
#define EC_DEBUG 0
|
||||
#define EC_POINT_FORM_COMPRESSED_Y0 0x02
|
||||
#define EC_POINT_FORM_COMPRESSED_Y1 0x03
|
||||
#define EC_POINT_FORM_UNCOMPRESSED 0x04
|
||||
#define EC_POINT_FORM_HYBRID_Y0 0x06
|
||||
#define EC_POINT_FORM_HYBRID_Y1 0x07
|
||||
|
||||
#define ANSI_X962_CURVE_OID_TOTAL_LEN 10
|
||||
#define SECG_CURVE_OID_TOTAL_LEN 7
|
||||
|
||||
#endif /* __ec_h_ */
|
||||
120
mozilla/security/nss/lib/freebl/fblstdlib.c
Executable file
120
mozilla/security/nss/lib/freebl/fblstdlib.c
Executable file
@@ -0,0 +1,120 @@
|
||||
/*
|
||||
* The contents of this file are subject to the Mozilla Public
|
||||
* License Version 1.1 (the "License"); you may not use this file
|
||||
* except in compliance with the License. You may obtain a copy of
|
||||
* the License at http://www.mozilla.org/MPL/
|
||||
*
|
||||
* Software distributed under the License is distributed on an "AS
|
||||
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
|
||||
* implied. See the License for the specific language governing
|
||||
* rights and limitations under the License.
|
||||
*
|
||||
* The Original Code is the Netscape security libraries.
|
||||
*
|
||||
* The Initial Developer of the Original Code is Netscape
|
||||
* Communications Corporation. Portions created by Netscape are
|
||||
* Copyright (C) 1994-2000 Netscape Communications Corporation. All
|
||||
* Rights Reserved.
|
||||
*
|
||||
* Contributor(s):
|
||||
*
|
||||
* Alternatively, the contents of this file may be used under the
|
||||
* terms of the GNU General Public License Version 2 or later (the
|
||||
* "GPL"), in which case the provisions of the GPL are applicable
|
||||
* instead of those above. If you wish to allow use of your
|
||||
* version of this file only under the terms of the GPL and not to
|
||||
* allow others to use your version of this file under the MPL,
|
||||
* indicate your decision by deleting the provisions above and
|
||||
* replace them with the notice and other provisions required by
|
||||
* the GPL. If you do not delete the provisions above, a recipient
|
||||
* may use your version of this file under either the MPL or the
|
||||
* GPL.
|
||||
*/
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <plstr.h>
|
||||
#include "aglobal.h"
|
||||
#include "bsafe.h"
|
||||
#include "secport.h"
|
||||
|
||||
void CALL_CONV T_memset (p, c, count)
|
||||
POINTER p;
|
||||
int c;
|
||||
unsigned int count;
|
||||
{
|
||||
if (count >= 0)
|
||||
memset(p, c, count);
|
||||
}
|
||||
|
||||
void CALL_CONV T_memcpy (d, s, count)
|
||||
POINTER d, s;
|
||||
unsigned int count;
|
||||
{
|
||||
if (count >= 0)
|
||||
memcpy(d, s, count);
|
||||
}
|
||||
|
||||
void CALL_CONV T_memmove (d, s, count)
|
||||
POINTER d, s;
|
||||
unsigned int count;
|
||||
{
|
||||
if (count >= 0)
|
||||
PORT_Memmove(d, s, count);
|
||||
}
|
||||
|
||||
int CALL_CONV T_memcmp (s1, s2, count)
|
||||
POINTER s1, s2;
|
||||
unsigned int count;
|
||||
{
|
||||
if (count == 0)
|
||||
return (0);
|
||||
else
|
||||
return(memcmp(s1, s2, count));
|
||||
}
|
||||
|
||||
POINTER CALL_CONV T_malloc (size)
|
||||
unsigned int size;
|
||||
{
|
||||
return((POINTER)PORT_Alloc(size == 0 ? 1 : size));
|
||||
}
|
||||
|
||||
POINTER CALL_CONV T_realloc (p, size)
|
||||
POINTER p;
|
||||
unsigned int size;
|
||||
{
|
||||
POINTER result;
|
||||
|
||||
if (p == NULL_PTR)
|
||||
return (T_malloc(size));
|
||||
|
||||
if ((result = (POINTER)PORT_Realloc(p, size == 0 ? 1 : size)) == NULL_PTR)
|
||||
PORT_Free(p);
|
||||
return (result);
|
||||
}
|
||||
|
||||
void CALL_CONV T_free (p)
|
||||
POINTER p;
|
||||
{
|
||||
if (p != NULL_PTR)
|
||||
PORT_Free(p);
|
||||
}
|
||||
|
||||
unsigned int CALL_CONV T_strlen(p)
|
||||
char *p;
|
||||
{
|
||||
return PL_strlen(p);
|
||||
}
|
||||
|
||||
void CALL_CONV T_strcpy(dest, src)
|
||||
char *dest;
|
||||
char *src;
|
||||
{
|
||||
PL_strcpy(dest, src);
|
||||
}
|
||||
|
||||
int CALL_CONV T_strcmp (a, b)
|
||||
char *a, *b;
|
||||
{
|
||||
return (PL_strcmp (a, b));
|
||||
}
|
||||
196
mozilla/security/nss/lib/freebl/ldvector.c
Normal file
196
mozilla/security/nss/lib/freebl/ldvector.c
Normal file
@@ -0,0 +1,196 @@
|
||||
/*
|
||||
* ldvector.c - platform dependent DSO containing freebl implementation.
|
||||
*
|
||||
* The contents of this file are subject to the Mozilla Public
|
||||
* License Version 1.1 (the "License"); you may not use this file
|
||||
* except in compliance with the License. You may obtain a copy of
|
||||
* the License at http://www.mozilla.org/MPL/
|
||||
*
|
||||
* Software distributed under the License is distributed on an "AS
|
||||
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
|
||||
* implied. See the License for the specific language governing
|
||||
* rights and limitations under the License.
|
||||
*
|
||||
* The Original Code is the Netscape security libraries.
|
||||
*
|
||||
* The Initial Developer of the Original Code is Netscape
|
||||
* Communications Corporation. Portions created by Netscape are
|
||||
* Copyright (C) 2000 Netscape Communications Corporation. All
|
||||
* Rights Reserved.
|
||||
*
|
||||
* Portions created by Sun Microsystems, Inc. are Copyright (C) 2003
|
||||
* Sun Microsystems, Inc. All Rights Reserved.
|
||||
*
|
||||
* Contributor(s):
|
||||
* Dr Vipul Gupta <vipul.gupta@sun.com>, Sun Microsystems Laboratories
|
||||
*
|
||||
* Alternatively, the contents of this file may be used under the
|
||||
* terms of the GNU General Public License Version 2 or later (the
|
||||
* "GPL"), in which case the provisions of the GPL are applicable
|
||||
* instead of those above. If you wish to allow use of your
|
||||
* version of this file only under the terms of the GPL and not to
|
||||
* allow others to use your version of this file under the MPL,
|
||||
* indicate your decision by deleting the provisions above and
|
||||
* replace them with the notice and other provisions required by
|
||||
* the GPL. If you do not delete the provisions above, a recipient
|
||||
* may use your version of this file under either the MPL or the
|
||||
* GPL.
|
||||
*
|
||||
* $Id: ldvector.c,v 1.6 2003-02-27 01:31:13 nelsonb%netscape.com Exp $
|
||||
*/
|
||||
|
||||
#include "loader.h"
|
||||
|
||||
static const struct FREEBLVectorStr vector = {
|
||||
|
||||
sizeof vector,
|
||||
FREEBL_VERSION,
|
||||
|
||||
RSA_NewKey,
|
||||
RSA_PublicKeyOp,
|
||||
RSA_PrivateKeyOp,
|
||||
DSA_NewKey,
|
||||
DSA_SignDigest,
|
||||
DSA_VerifyDigest,
|
||||
DSA_NewKeyFromSeed,
|
||||
DSA_SignDigestWithSeed,
|
||||
DH_GenParam,
|
||||
DH_NewKey,
|
||||
DH_Derive,
|
||||
KEA_Derive,
|
||||
KEA_Verify,
|
||||
RC4_CreateContext,
|
||||
RC4_DestroyContext,
|
||||
RC4_Encrypt,
|
||||
RC4_Decrypt,
|
||||
RC2_CreateContext,
|
||||
RC2_DestroyContext,
|
||||
RC2_Encrypt,
|
||||
RC2_Decrypt,
|
||||
RC5_CreateContext,
|
||||
RC5_DestroyContext,
|
||||
RC5_Encrypt,
|
||||
RC5_Decrypt,
|
||||
DES_CreateContext,
|
||||
DES_DestroyContext,
|
||||
DES_Encrypt,
|
||||
DES_Decrypt,
|
||||
AES_CreateContext,
|
||||
AES_DestroyContext,
|
||||
AES_Encrypt,
|
||||
AES_Decrypt,
|
||||
MD5_Hash,
|
||||
MD5_HashBuf,
|
||||
MD5_NewContext,
|
||||
MD5_DestroyContext,
|
||||
MD5_Begin,
|
||||
MD5_Update,
|
||||
MD5_End,
|
||||
MD5_FlattenSize,
|
||||
MD5_Flatten,
|
||||
MD5_Resurrect,
|
||||
MD5_TraceState,
|
||||
MD2_Hash,
|
||||
MD2_NewContext,
|
||||
MD2_DestroyContext,
|
||||
MD2_Begin,
|
||||
MD2_Update,
|
||||
MD2_End,
|
||||
MD2_FlattenSize,
|
||||
MD2_Flatten,
|
||||
MD2_Resurrect,
|
||||
SHA1_Hash,
|
||||
SHA1_HashBuf,
|
||||
SHA1_NewContext,
|
||||
SHA1_DestroyContext,
|
||||
SHA1_Begin,
|
||||
SHA1_Update,
|
||||
SHA1_End,
|
||||
SHA1_TraceState,
|
||||
SHA1_FlattenSize,
|
||||
SHA1_Flatten,
|
||||
SHA1_Resurrect,
|
||||
RNG_RNGInit,
|
||||
RNG_RandomUpdate,
|
||||
RNG_GenerateGlobalRandomBytes,
|
||||
RNG_RNGShutdown,
|
||||
PQG_ParamGen,
|
||||
PQG_ParamGenSeedLen,
|
||||
PQG_VerifyParams,
|
||||
|
||||
/* End of Version 3.001. */
|
||||
|
||||
RSA_PrivateKeyOpDoubleChecked,
|
||||
RSA_PrivateKeyCheck,
|
||||
BL_Cleanup,
|
||||
|
||||
/* End of Version 3.002. */
|
||||
|
||||
SHA256_NewContext,
|
||||
SHA256_DestroyContext,
|
||||
SHA256_Begin,
|
||||
SHA256_Update,
|
||||
SHA256_End,
|
||||
SHA256_HashBuf,
|
||||
SHA256_Hash,
|
||||
SHA256_TraceState,
|
||||
SHA256_FlattenSize,
|
||||
SHA256_Flatten,
|
||||
SHA256_Resurrect,
|
||||
|
||||
SHA512_NewContext,
|
||||
SHA512_DestroyContext,
|
||||
SHA512_Begin,
|
||||
SHA512_Update,
|
||||
SHA512_End,
|
||||
SHA512_HashBuf,
|
||||
SHA512_Hash,
|
||||
SHA512_TraceState,
|
||||
SHA512_FlattenSize,
|
||||
SHA512_Flatten,
|
||||
SHA512_Resurrect,
|
||||
|
||||
SHA384_NewContext,
|
||||
SHA384_DestroyContext,
|
||||
SHA384_Begin,
|
||||
SHA384_Update,
|
||||
SHA384_End,
|
||||
SHA384_HashBuf,
|
||||
SHA384_Hash,
|
||||
SHA384_TraceState,
|
||||
SHA384_FlattenSize,
|
||||
SHA384_Flatten,
|
||||
SHA384_Resurrect,
|
||||
|
||||
/* End of Version 3.003. */
|
||||
|
||||
AESKeyWrap_CreateContext,
|
||||
AESKeyWrap_DestroyContext,
|
||||
AESKeyWrap_Encrypt,
|
||||
AESKeyWrap_Decrypt,
|
||||
|
||||
/* End of Version 3.004. */
|
||||
|
||||
BLAPI_SHVerify,
|
||||
BLAPI_VerifySelf,
|
||||
|
||||
/* End of Version 3.005. */
|
||||
|
||||
EC_NewKey,
|
||||
EC_NewKeyFromSeed,
|
||||
EC_ValidatePublicKey,
|
||||
ECDH_Derive,
|
||||
ECDSA_SignDigest,
|
||||
ECDSA_VerifyDigest,
|
||||
ECDSA_SignDigestWithSeed,
|
||||
|
||||
/* End of Version 3.006. */
|
||||
};
|
||||
|
||||
|
||||
const FREEBLVector *
|
||||
FREEBL_GetVector(void)
|
||||
{
|
||||
return &vector;
|
||||
}
|
||||
|
||||
1366
mozilla/security/nss/lib/freebl/loader.c
Normal file
1366
mozilla/security/nss/lib/freebl/loader.c
Normal file
File diff suppressed because it is too large
Load Diff
386
mozilla/security/nss/lib/freebl/loader.h
Normal file
386
mozilla/security/nss/lib/freebl/loader.h
Normal file
@@ -0,0 +1,386 @@
|
||||
/*
|
||||
* loader.h - load platform dependent DSO containing freebl implementation.
|
||||
*
|
||||
* The contents of this file are subject to the Mozilla Public
|
||||
* License Version 1.1 (the "License"); you may not use this file
|
||||
* except in compliance with the License. You may obtain a copy of
|
||||
* the License at http://www.mozilla.org/MPL/
|
||||
*
|
||||
* Software distributed under the License is distributed on an "AS
|
||||
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
|
||||
* implied. See the License for the specific language governing
|
||||
* rights and limitations under the License.
|
||||
*
|
||||
* The Original Code is the Netscape security libraries.
|
||||
*
|
||||
* The Initial Developer of the Original Code is Netscape
|
||||
* Communications Corporation. Portions created by Netscape are
|
||||
* Copyright (C) 2000 Netscape Communications Corporation. All
|
||||
* Rights Reserved.
|
||||
*
|
||||
* Portions created by Sun Microsystems, Inc. are Copyright (C) 2003
|
||||
* Sun Microsystems, Inc. All Rights Reserved.
|
||||
*
|
||||
* Contributor(s):
|
||||
* Dr Vipul Gupta <vipul.gupta@sun.com>, Sun Microsystems Laboratories
|
||||
*
|
||||
* Alternatively, the contents of this file may be used under the
|
||||
* terms of the GNU General Public License Version 2 or later (the
|
||||
* "GPL"), in which case the provisions of the GPL are applicable
|
||||
* instead of those above. If you wish to allow use of your
|
||||
* version of this file only under the terms of the GPL and not to
|
||||
* allow others to use your version of this file under the MPL,
|
||||
* indicate your decision by deleting the provisions above and
|
||||
* replace them with the notice and other provisions required by
|
||||
* the GPL. If you do not delete the provisions above, a recipient
|
||||
* may use your version of this file under either the MPL or the
|
||||
* GPL.
|
||||
*
|
||||
* $Id: loader.h,v 1.9 2003-02-27 01:31:14 nelsonb%netscape.com Exp $
|
||||
*/
|
||||
|
||||
#ifndef _LOADER_H_
|
||||
#define _LOADER_H_ 1
|
||||
|
||||
#include "blapi.h"
|
||||
|
||||
#define FREEBL_VERSION 0x0306
|
||||
|
||||
struct FREEBLVectorStr {
|
||||
|
||||
unsigned short length; /* of this struct in bytes */
|
||||
unsigned short version; /* of this struct. */
|
||||
|
||||
RSAPrivateKey * (* p_RSA_NewKey)(int keySizeInBits,
|
||||
SECItem * publicExponent);
|
||||
|
||||
SECStatus (* p_RSA_PublicKeyOp) (RSAPublicKey * key,
|
||||
unsigned char * output,
|
||||
const unsigned char * input);
|
||||
|
||||
SECStatus (* p_RSA_PrivateKeyOp)(RSAPrivateKey * key,
|
||||
unsigned char * output,
|
||||
const unsigned char * input);
|
||||
|
||||
SECStatus (* p_DSA_NewKey)(const PQGParams * params,
|
||||
DSAPrivateKey ** privKey);
|
||||
|
||||
SECStatus (* p_DSA_SignDigest)(DSAPrivateKey * key,
|
||||
SECItem * signature,
|
||||
const SECItem * digest);
|
||||
|
||||
SECStatus (* p_DSA_VerifyDigest)(DSAPublicKey * key,
|
||||
const SECItem * signature,
|
||||
const SECItem * digest);
|
||||
|
||||
SECStatus (* p_DSA_NewKeyFromSeed)(const PQGParams *params,
|
||||
const unsigned char * seed,
|
||||
DSAPrivateKey **privKey);
|
||||
|
||||
SECStatus (* p_DSA_SignDigestWithSeed)(DSAPrivateKey * key,
|
||||
SECItem * signature,
|
||||
const SECItem * digest,
|
||||
const unsigned char * seed);
|
||||
|
||||
SECStatus (* p_DH_GenParam)(int primeLen, DHParams ** params);
|
||||
|
||||
SECStatus (* p_DH_NewKey)(DHParams * params,
|
||||
DHPrivateKey ** privKey);
|
||||
|
||||
SECStatus (* p_DH_Derive)(SECItem * publicValue,
|
||||
SECItem * prime,
|
||||
SECItem * privateValue,
|
||||
SECItem * derivedSecret,
|
||||
unsigned int maxOutBytes);
|
||||
|
||||
SECStatus (* p_KEA_Derive)(SECItem *prime,
|
||||
SECItem *public1,
|
||||
SECItem *public2,
|
||||
SECItem *private1,
|
||||
SECItem *private2,
|
||||
SECItem *derivedSecret);
|
||||
|
||||
PRBool (* p_KEA_Verify)(SECItem *Y, SECItem *prime, SECItem *subPrime);
|
||||
|
||||
RC4Context * (* p_RC4_CreateContext)(const unsigned char *key, int len);
|
||||
|
||||
void (* p_RC4_DestroyContext)(RC4Context *cx, PRBool freeit);
|
||||
|
||||
SECStatus (* p_RC4_Encrypt)(RC4Context *cx, unsigned char *output,
|
||||
unsigned int *outputLen, unsigned int maxOutputLen,
|
||||
const unsigned char *input, unsigned int inputLen);
|
||||
|
||||
SECStatus (* p_RC4_Decrypt)(RC4Context *cx, unsigned char *output,
|
||||
unsigned int *outputLen, unsigned int maxOutputLen,
|
||||
const unsigned char *input, unsigned int inputLen);
|
||||
|
||||
RC2Context * (* p_RC2_CreateContext)(const unsigned char *key,
|
||||
unsigned int len, const unsigned char *iv,
|
||||
int mode, unsigned effectiveKeyLen);
|
||||
|
||||
void (* p_RC2_DestroyContext)(RC2Context *cx, PRBool freeit);
|
||||
|
||||
SECStatus (* p_RC2_Encrypt)(RC2Context *cx, unsigned char *output,
|
||||
unsigned int *outputLen, unsigned int maxOutputLen,
|
||||
const unsigned char *input, unsigned int inputLen);
|
||||
|
||||
SECStatus (* p_RC2_Decrypt)(RC2Context *cx, unsigned char *output,
|
||||
unsigned int *outputLen, unsigned int maxOutputLen,
|
||||
const unsigned char *input, unsigned int inputLen);
|
||||
|
||||
RC5Context *(* p_RC5_CreateContext)(const SECItem *key, unsigned int rounds,
|
||||
unsigned int wordSize, const unsigned char *iv, int mode);
|
||||
|
||||
void (* p_RC5_DestroyContext)(RC5Context *cx, PRBool freeit);
|
||||
|
||||
SECStatus (* p_RC5_Encrypt)(RC5Context *cx, unsigned char *output,
|
||||
unsigned int *outputLen, unsigned int maxOutputLen,
|
||||
const unsigned char *input, unsigned int inputLen);
|
||||
|
||||
SECStatus (* p_RC5_Decrypt)(RC5Context *cx, unsigned char *output,
|
||||
unsigned int *outputLen, unsigned int maxOutputLen,
|
||||
const unsigned char *input, unsigned int inputLen);
|
||||
|
||||
DESContext *(* p_DES_CreateContext)(const unsigned char *key,
|
||||
const unsigned char *iv,
|
||||
int mode, PRBool encrypt);
|
||||
|
||||
void (* p_DES_DestroyContext)(DESContext *cx, PRBool freeit);
|
||||
|
||||
SECStatus (* p_DES_Encrypt)(DESContext *cx, unsigned char *output,
|
||||
unsigned int *outputLen, unsigned int maxOutputLen,
|
||||
const unsigned char *input, unsigned int inputLen);
|
||||
|
||||
SECStatus (* p_DES_Decrypt)(DESContext *cx, unsigned char *output,
|
||||
unsigned int *outputLen, unsigned int maxOutputLen,
|
||||
const unsigned char *input, unsigned int inputLen);
|
||||
|
||||
AESContext * (* p_AES_CreateContext)(const unsigned char *key,
|
||||
const unsigned char *iv,
|
||||
int mode, int encrypt, unsigned int keylen,
|
||||
unsigned int blocklen);
|
||||
|
||||
void (* p_AES_DestroyContext)(AESContext *cx, PRBool freeit);
|
||||
|
||||
SECStatus (* p_AES_Encrypt)(AESContext *cx, unsigned char *output,
|
||||
unsigned int *outputLen, unsigned int maxOutputLen,
|
||||
const unsigned char *input, unsigned int inputLen);
|
||||
|
||||
SECStatus (* p_AES_Decrypt)(AESContext *cx, unsigned char *output,
|
||||
unsigned int *outputLen, unsigned int maxOutputLen,
|
||||
const unsigned char *input, unsigned int inputLen);
|
||||
|
||||
SECStatus (* p_MD5_Hash)(unsigned char *dest, const char *src);
|
||||
|
||||
SECStatus (* p_MD5_HashBuf)(unsigned char *dest, const unsigned char *src,
|
||||
uint32 src_length);
|
||||
|
||||
MD5Context *(* p_MD5_NewContext)(void);
|
||||
|
||||
void (* p_MD5_DestroyContext)(MD5Context *cx, PRBool freeit);
|
||||
|
||||
void (* p_MD5_Begin)(MD5Context *cx);
|
||||
|
||||
void (* p_MD5_Update)(MD5Context *cx,
|
||||
const unsigned char *input, unsigned int inputLen);
|
||||
|
||||
void (* p_MD5_End)(MD5Context *cx, unsigned char *digest,
|
||||
unsigned int *digestLen, unsigned int maxDigestLen);
|
||||
|
||||
unsigned int (* p_MD5_FlattenSize)(MD5Context *cx);
|
||||
|
||||
SECStatus (* p_MD5_Flatten)(MD5Context *cx,unsigned char *space);
|
||||
|
||||
MD5Context * (* p_MD5_Resurrect)(unsigned char *space, void *arg);
|
||||
|
||||
void (* p_MD5_TraceState)(MD5Context *cx);
|
||||
|
||||
SECStatus (* p_MD2_Hash)(unsigned char *dest, const char *src);
|
||||
|
||||
MD2Context *(* p_MD2_NewContext)(void);
|
||||
|
||||
void (* p_MD2_DestroyContext)(MD2Context *cx, PRBool freeit);
|
||||
|
||||
void (* p_MD2_Begin)(MD2Context *cx);
|
||||
|
||||
void (* p_MD2_Update)(MD2Context *cx,
|
||||
const unsigned char *input, unsigned int inputLen);
|
||||
|
||||
void (* p_MD2_End)(MD2Context *cx, unsigned char *digest,
|
||||
unsigned int *digestLen, unsigned int maxDigestLen);
|
||||
|
||||
unsigned int (* p_MD2_FlattenSize)(MD2Context *cx);
|
||||
|
||||
SECStatus (* p_MD2_Flatten)(MD2Context *cx,unsigned char *space);
|
||||
|
||||
MD2Context * (* p_MD2_Resurrect)(unsigned char *space, void *arg);
|
||||
|
||||
SECStatus (* p_SHA1_Hash)(unsigned char *dest, const char *src);
|
||||
|
||||
SECStatus (* p_SHA1_HashBuf)(unsigned char *dest, const unsigned char *src,
|
||||
uint32 src_length);
|
||||
|
||||
SHA1Context *(* p_SHA1_NewContext)(void);
|
||||
|
||||
void (* p_SHA1_DestroyContext)(SHA1Context *cx, PRBool freeit);
|
||||
|
||||
void (* p_SHA1_Begin)(SHA1Context *cx);
|
||||
|
||||
void (* p_SHA1_Update)(SHA1Context *cx, const unsigned char *input,
|
||||
unsigned int inputLen);
|
||||
|
||||
void (* p_SHA1_End)(SHA1Context *cx, unsigned char *digest,
|
||||
unsigned int *digestLen, unsigned int maxDigestLen);
|
||||
|
||||
void (* p_SHA1_TraceState)(SHA1Context *cx);
|
||||
|
||||
unsigned int (* p_SHA1_FlattenSize)(SHA1Context *cx);
|
||||
|
||||
SECStatus (* p_SHA1_Flatten)(SHA1Context *cx,unsigned char *space);
|
||||
|
||||
SHA1Context * (* p_SHA1_Resurrect)(unsigned char *space, void *arg);
|
||||
|
||||
SECStatus (* p_RNG_RNGInit)(void);
|
||||
|
||||
SECStatus (* p_RNG_RandomUpdate)(const void *data, size_t bytes);
|
||||
|
||||
SECStatus (* p_RNG_GenerateGlobalRandomBytes)(void *dest, size_t len);
|
||||
|
||||
void (* p_RNG_RNGShutdown)(void);
|
||||
|
||||
SECStatus (* p_PQG_ParamGen)(unsigned int j, PQGParams **pParams,
|
||||
PQGVerify **pVfy);
|
||||
|
||||
SECStatus (* p_PQG_ParamGenSeedLen)( unsigned int j, unsigned int seedBytes,
|
||||
PQGParams **pParams, PQGVerify **pVfy);
|
||||
|
||||
SECStatus (* p_PQG_VerifyParams)(const PQGParams *params,
|
||||
const PQGVerify *vfy, SECStatus *result);
|
||||
|
||||
/* Version 3.001 came to here */
|
||||
|
||||
SECStatus (* p_RSA_PrivateKeyOpDoubleChecked)(RSAPrivateKey *key,
|
||||
unsigned char *output,
|
||||
const unsigned char *input);
|
||||
|
||||
SECStatus (* p_RSA_PrivateKeyCheck)(RSAPrivateKey *key);
|
||||
|
||||
void (* p_BL_Cleanup)(void);
|
||||
|
||||
/* Version 3.002 came to here */
|
||||
|
||||
SHA256Context *(* p_SHA256_NewContext)(void);
|
||||
void (* p_SHA256_DestroyContext)(SHA256Context *cx, PRBool freeit);
|
||||
void (* p_SHA256_Begin)(SHA256Context *cx);
|
||||
void (* p_SHA256_Update)(SHA256Context *cx, const unsigned char *input,
|
||||
unsigned int inputLen);
|
||||
void (* p_SHA256_End)(SHA256Context *cx, unsigned char *digest,
|
||||
unsigned int *digestLen, unsigned int maxDigestLen);
|
||||
SECStatus (* p_SHA256_HashBuf)(unsigned char *dest, const unsigned char *src,
|
||||
uint32 src_length);
|
||||
SECStatus (* p_SHA256_Hash)(unsigned char *dest, const char *src);
|
||||
void (* p_SHA256_TraceState)(SHA256Context *cx);
|
||||
unsigned int (* p_SHA256_FlattenSize)(SHA256Context *cx);
|
||||
SECStatus (* p_SHA256_Flatten)(SHA256Context *cx,unsigned char *space);
|
||||
SHA256Context * (* p_SHA256_Resurrect)(unsigned char *space, void *arg);
|
||||
|
||||
SHA512Context *(* p_SHA512_NewContext)(void);
|
||||
void (* p_SHA512_DestroyContext)(SHA512Context *cx, PRBool freeit);
|
||||
void (* p_SHA512_Begin)(SHA512Context *cx);
|
||||
void (* p_SHA512_Update)(SHA512Context *cx, const unsigned char *input,
|
||||
unsigned int inputLen);
|
||||
void (* p_SHA512_End)(SHA512Context *cx, unsigned char *digest,
|
||||
unsigned int *digestLen, unsigned int maxDigestLen);
|
||||
SECStatus (* p_SHA512_HashBuf)(unsigned char *dest, const unsigned char *src,
|
||||
uint32 src_length);
|
||||
SECStatus (* p_SHA512_Hash)(unsigned char *dest, const char *src);
|
||||
void (* p_SHA512_TraceState)(SHA512Context *cx);
|
||||
unsigned int (* p_SHA512_FlattenSize)(SHA512Context *cx);
|
||||
SECStatus (* p_SHA512_Flatten)(SHA512Context *cx,unsigned char *space);
|
||||
SHA512Context * (* p_SHA512_Resurrect)(unsigned char *space, void *arg);
|
||||
|
||||
SHA384Context *(* p_SHA384_NewContext)(void);
|
||||
void (* p_SHA384_DestroyContext)(SHA384Context *cx, PRBool freeit);
|
||||
void (* p_SHA384_Begin)(SHA384Context *cx);
|
||||
void (* p_SHA384_Update)(SHA384Context *cx, const unsigned char *input,
|
||||
unsigned int inputLen);
|
||||
void (* p_SHA384_End)(SHA384Context *cx, unsigned char *digest,
|
||||
unsigned int *digestLen, unsigned int maxDigestLen);
|
||||
SECStatus (* p_SHA384_HashBuf)(unsigned char *dest, const unsigned char *src,
|
||||
uint32 src_length);
|
||||
SECStatus (* p_SHA384_Hash)(unsigned char *dest, const char *src);
|
||||
void (* p_SHA384_TraceState)(SHA384Context *cx);
|
||||
unsigned int (* p_SHA384_FlattenSize)(SHA384Context *cx);
|
||||
SECStatus (* p_SHA384_Flatten)(SHA384Context *cx,unsigned char *space);
|
||||
SHA384Context * (* p_SHA384_Resurrect)(unsigned char *space, void *arg);
|
||||
|
||||
/* Version 3.003 came to here */
|
||||
|
||||
AESKeyWrapContext * (* p_AESKeyWrap_CreateContext)(const unsigned char *key,
|
||||
const unsigned char *iv, int encrypt, unsigned int keylen);
|
||||
|
||||
void (* p_AESKeyWrap_DestroyContext)(AESKeyWrapContext *cx, PRBool freeit);
|
||||
|
||||
SECStatus (* p_AESKeyWrap_Encrypt)(AESKeyWrapContext *cx,
|
||||
unsigned char *output,
|
||||
unsigned int *outputLen, unsigned int maxOutputLen,
|
||||
const unsigned char *input, unsigned int inputLen);
|
||||
|
||||
SECStatus (* p_AESKeyWrap_Decrypt)(AESKeyWrapContext *cx,
|
||||
unsigned char *output,
|
||||
unsigned int *outputLen, unsigned int maxOutputLen,
|
||||
const unsigned char *input, unsigned int inputLen);
|
||||
|
||||
/* Version 3.004 came to here */
|
||||
|
||||
PRBool (*p_BLAPI_SHVerify)(const char *name, PRFuncPtr addr);
|
||||
PRBool (*p_BLAPI_VerifySelf)(const char *name);
|
||||
|
||||
/* Version 3.005 came to here */
|
||||
|
||||
SECStatus (* p_EC_NewKey)(ECParams * params,
|
||||
ECPrivateKey ** privKey);
|
||||
|
||||
SECStatus (* p_EC_NewKeyFromSeed)(ECParams * params,
|
||||
ECPrivateKey ** privKey,
|
||||
const unsigned char * seed,
|
||||
int seedlen);
|
||||
|
||||
SECStatus (* p_EC_ValidatePublicKey)(ECParams * params,
|
||||
SECItem * publicValue);
|
||||
|
||||
SECStatus (* p_ECDH_Derive)(SECItem * publicValue,
|
||||
ECParams * params,
|
||||
SECItem * privateValue,
|
||||
PRBool withCofactor,
|
||||
SECItem * derivedSecret);
|
||||
|
||||
SECStatus (* p_ECDSA_SignDigest)(ECPrivateKey * key,
|
||||
SECItem * signature,
|
||||
const SECItem * digest);
|
||||
|
||||
SECStatus (* p_ECDSA_VerifyDigest)(ECPublicKey * key,
|
||||
const SECItem * signature,
|
||||
const SECItem * digest);
|
||||
|
||||
SECStatus (* p_ECDSA_SignDigestWithSeed)(ECPrivateKey * key,
|
||||
SECItem * signature,
|
||||
const SECItem * digest,
|
||||
const unsigned char * seed,
|
||||
const int seedlen);
|
||||
|
||||
/* Version 3.006 came to here */
|
||||
|
||||
};
|
||||
|
||||
typedef struct FREEBLVectorStr FREEBLVector;
|
||||
|
||||
SEC_BEGIN_PROTOS
|
||||
|
||||
typedef const FREEBLVector * FREEBLGetVectorFn(void);
|
||||
|
||||
extern FREEBLGetVectorFn FREEBL_GetVector;
|
||||
|
||||
SEC_END_PROTOS
|
||||
|
||||
#endif
|
||||
315
mozilla/security/nss/lib/freebl/mac_rand.c
Normal file
315
mozilla/security/nss/lib/freebl/mac_rand.c
Normal file
@@ -0,0 +1,315 @@
|
||||
/*
|
||||
* The contents of this file are subject to the Mozilla Public
|
||||
* License Version 1.1 (the "License"); you may not use this file
|
||||
* except in compliance with the License. You may obtain a copy of
|
||||
* the License at http://www.mozilla.org/MPL/
|
||||
*
|
||||
* Software distributed under the License is distributed on an "AS
|
||||
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
|
||||
* implied. See the License for the specific language governing
|
||||
* rights and limitations under the License.
|
||||
*
|
||||
* The Original Code is the Netscape security libraries.
|
||||
*
|
||||
* The Initial Developer of the Original Code is Netscape
|
||||
* Communications Corporation. Portions created by Netscape are
|
||||
* Copyright (C) 1994-2000 Netscape Communications Corporation. All
|
||||
* Rights Reserved.
|
||||
*
|
||||
* Contributor(s):
|
||||
*
|
||||
* Alternatively, the contents of this file may be used under the
|
||||
* terms of the GNU General Public License Version 2 or later (the
|
||||
* "GPL"), in which case the provisions of the GPL are applicable
|
||||
* instead of those above. If you wish to allow use of your
|
||||
* version of this file only under the terms of the GPL and not to
|
||||
* allow others to use your version of this file under the MPL,
|
||||
* indicate your decision by deleting the provisions above and
|
||||
* replace them with the notice and other provisions required by
|
||||
* the GPL. If you do not delete the provisions above, a recipient
|
||||
* may use your version of this file under either the MPL or the
|
||||
* GPL.
|
||||
*/
|
||||
|
||||
#ifdef notdef
|
||||
#include "xp_core.h"
|
||||
#include "xp_file.h"
|
||||
#endif
|
||||
#include "secrng.h"
|
||||
#include "mcom_db.h"
|
||||
#ifdef XP_MAC
|
||||
#include <Events.h>
|
||||
#include <OSUtils.h>
|
||||
#include <QDOffscreen.h>
|
||||
#include <PPCToolbox.h>
|
||||
#include <Processes.h>
|
||||
#include <LowMem.h>
|
||||
#include <Scrap.h>
|
||||
|
||||
/* Static prototypes */
|
||||
static size_t CopyLowBits(void *dst, size_t dstlen, void *src, size_t srclen);
|
||||
void FE_ReadScreen();
|
||||
|
||||
static size_t CopyLowBits(void *dst, size_t dstlen, void *src, size_t srclen)
|
||||
{
|
||||
union endianness {
|
||||
int32 i;
|
||||
char c[4];
|
||||
} u;
|
||||
|
||||
if (srclen <= dstlen) {
|
||||
memcpy(dst, src, srclen);
|
||||
return srclen;
|
||||
}
|
||||
u.i = 0x01020304;
|
||||
if (u.c[0] == 0x01) {
|
||||
/* big-endian case */
|
||||
memcpy(dst, (char*)src + (srclen - dstlen), dstlen);
|
||||
} else {
|
||||
/* little-endian case */
|
||||
memcpy(dst, src, dstlen);
|
||||
}
|
||||
return dstlen;
|
||||
}
|
||||
|
||||
size_t RNG_GetNoise(void *buf, size_t maxbytes)
|
||||
{
|
||||
UnsignedWide microTickCount;
|
||||
Microseconds(µTickCount);
|
||||
return CopyLowBits(buf, maxbytes, µTickCount, sizeof(microTickCount));
|
||||
}
|
||||
|
||||
void RNG_FileForRNG(const char *filename)
|
||||
{
|
||||
unsigned char buffer[BUFSIZ];
|
||||
size_t bytes;
|
||||
#ifdef notdef /*sigh*/
|
||||
XP_File file;
|
||||
unsigned long totalFileBytes = 0;
|
||||
|
||||
if (filename == NULL) /* For now, read in global history if filename is null */
|
||||
file = XP_FileOpen(NULL, xpGlobalHistory,XP_FILE_READ_BIN);
|
||||
else
|
||||
file = XP_FileOpen(NULL, xpURL,XP_FILE_READ_BIN);
|
||||
if (file != NULL) {
|
||||
for (;;) {
|
||||
bytes = XP_FileRead(buffer, sizeof(buffer), file);
|
||||
if (bytes == 0) break;
|
||||
RNG_RandomUpdate( buffer, bytes);
|
||||
totalFileBytes += bytes;
|
||||
if (totalFileBytes > 100*1024) break; /* No more than 100 K */
|
||||
}
|
||||
XP_FileClose(file);
|
||||
}
|
||||
#endif
|
||||
/*
|
||||
* Pass yet another snapshot of our highest resolution clock into
|
||||
* the hash function.
|
||||
*/
|
||||
bytes = RNG_GetNoise(buffer, sizeof(buffer));
|
||||
RNG_RandomUpdate(buffer, sizeof(buffer));
|
||||
}
|
||||
|
||||
void RNG_SystemInfoForRNG()
|
||||
{
|
||||
/* Time */
|
||||
{
|
||||
unsigned long sec;
|
||||
size_t bytes;
|
||||
GetDateTime(&sec); /* Current time since 1970 */
|
||||
RNG_RandomUpdate( &sec, sizeof(sec));
|
||||
bytes = RNG_GetNoise(&sec, sizeof(sec));
|
||||
RNG_RandomUpdate(&sec, bytes);
|
||||
}
|
||||
/* User specific variables */
|
||||
{
|
||||
MachineLocation loc;
|
||||
ReadLocation(&loc);
|
||||
RNG_RandomUpdate( &loc, sizeof(loc));
|
||||
}
|
||||
#if !TARGET_CARBON
|
||||
/* User name */
|
||||
{
|
||||
unsigned long userRef;
|
||||
Str32 userName;
|
||||
GetDefaultUser(&userRef, userName);
|
||||
RNG_RandomUpdate( &userRef, sizeof(userRef));
|
||||
RNG_RandomUpdate( userName, sizeof(userName));
|
||||
}
|
||||
#endif
|
||||
/* Mouse location */
|
||||
{
|
||||
Point mouseLoc;
|
||||
GetMouse(&mouseLoc);
|
||||
RNG_RandomUpdate( &mouseLoc, sizeof(mouseLoc));
|
||||
}
|
||||
/* Keyboard time threshold */
|
||||
{
|
||||
SInt16 keyTresh = LMGetKeyThresh();
|
||||
RNG_RandomUpdate( &keyTresh, sizeof(keyTresh));
|
||||
}
|
||||
/* Last key pressed */
|
||||
{
|
||||
SInt8 keyLast;
|
||||
keyLast = LMGetKbdLast();
|
||||
RNG_RandomUpdate( &keyLast, sizeof(keyLast));
|
||||
}
|
||||
/* Volume */
|
||||
{
|
||||
UInt8 volume = LMGetSdVolume();
|
||||
RNG_RandomUpdate( &volume, sizeof(volume));
|
||||
}
|
||||
#if !TARGET_CARBON
|
||||
/* Current directory */
|
||||
{
|
||||
SInt32 dir = LMGetCurDirStore();
|
||||
RNG_RandomUpdate( &dir, sizeof(dir));
|
||||
}
|
||||
#endif
|
||||
/* Process information about all the processes in the machine */
|
||||
{
|
||||
ProcessSerialNumber process;
|
||||
ProcessInfoRec pi;
|
||||
|
||||
process.highLongOfPSN = process.lowLongOfPSN = kNoProcess;
|
||||
|
||||
while (GetNextProcess(&process) == noErr)
|
||||
{
|
||||
FSSpec fileSpec;
|
||||
pi.processInfoLength = sizeof(ProcessInfoRec);
|
||||
pi.processName = NULL;
|
||||
pi.processAppSpec = &fileSpec;
|
||||
GetProcessInformation(&process, &pi);
|
||||
RNG_RandomUpdate( &pi, sizeof(pi));
|
||||
RNG_RandomUpdate( &fileSpec, sizeof(fileSpec));
|
||||
}
|
||||
}
|
||||
|
||||
#if !TARGET_CARBON
|
||||
/* Heap */
|
||||
{
|
||||
THz zone = LMGetTheZone();
|
||||
RNG_RandomUpdate( &zone, sizeof(zone));
|
||||
}
|
||||
#endif
|
||||
|
||||
/* Screen */
|
||||
{
|
||||
GDHandle h = GetMainDevice(); /* GDHandle is **GDevice */
|
||||
RNG_RandomUpdate( *h, sizeof(GDevice));
|
||||
}
|
||||
|
||||
#if !TARGET_CARBON
|
||||
/* Scrap size */
|
||||
{
|
||||
SInt32 scrapSize = LMGetScrapSize();
|
||||
RNG_RandomUpdate( &scrapSize, sizeof(scrapSize));
|
||||
}
|
||||
/* Scrap count */
|
||||
{
|
||||
SInt16 scrapCount = LMGetScrapCount();
|
||||
RNG_RandomUpdate( &scrapCount, sizeof(scrapCount));
|
||||
}
|
||||
#else
|
||||
{
|
||||
ScrapRef scrap;
|
||||
if (GetCurrentScrap(&scrap) == noErr) {
|
||||
UInt32 flavorCount;
|
||||
if (GetScrapFlavorCount(scrap, &flavorCount) == noErr) {
|
||||
ScrapFlavorInfo* flavorInfo = (ScrapFlavorInfo*) malloc(flavorCount * sizeof(ScrapFlavorInfo));
|
||||
if (flavorInfo != NULL) {
|
||||
if (GetScrapFlavorInfoList(scrap, &flavorCount, flavorInfo) == noErr) {
|
||||
UInt32 i;
|
||||
RNG_RandomUpdate(&flavorCount, sizeof(flavorCount));
|
||||
for (i = 0; i < flavorCount; ++i) {
|
||||
Size flavorSize;
|
||||
if (GetScrapFlavorSize(scrap, flavorInfo[i].flavorType, &flavorSize) == noErr)
|
||||
RNG_RandomUpdate(&flavorSize, sizeof(flavorSize));
|
||||
}
|
||||
}
|
||||
free(flavorInfo);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
/* File stuff, last modified, etc. */
|
||||
{
|
||||
HParamBlockRec pb;
|
||||
GetVolParmsInfoBuffer volInfo;
|
||||
pb.ioParam.ioVRefNum = 0;
|
||||
pb.ioParam.ioNamePtr = nil;
|
||||
pb.ioParam.ioBuffer = (Ptr) &volInfo;
|
||||
pb.ioParam.ioReqCount = sizeof(volInfo);
|
||||
PBHGetVolParmsSync(&pb);
|
||||
RNG_RandomUpdate( &volInfo, sizeof(volInfo));
|
||||
}
|
||||
#if !TARGET_CARBON
|
||||
/* Event queue */
|
||||
{
|
||||
EvQElPtr eventQ;
|
||||
for (eventQ = (EvQElPtr) LMGetEventQueue()->qHead;
|
||||
eventQ;
|
||||
eventQ = (EvQElPtr)eventQ->qLink)
|
||||
RNG_RandomUpdate( &eventQ->evtQWhat, sizeof(EventRecord));
|
||||
}
|
||||
#endif
|
||||
FE_ReadScreen();
|
||||
RNG_FileForRNG(NULL);
|
||||
}
|
||||
|
||||
void FE_ReadScreen()
|
||||
{
|
||||
UInt16 coords[4];
|
||||
PixMapHandle pmap;
|
||||
GDHandle gh;
|
||||
UInt16 screenHeight;
|
||||
UInt16 screenWidth; /* just what they say */
|
||||
UInt32 bytesToRead; /* number of bytes we're giving */
|
||||
UInt32 offset; /* offset into the graphics buffer */
|
||||
UInt16 rowBytes;
|
||||
UInt32 rowsToRead;
|
||||
float bytesPerPixel; /* dependent on buffer depth */
|
||||
Ptr p; /* temporary */
|
||||
UInt16 x, y, w, h;
|
||||
|
||||
gh = LMGetMainDevice();
|
||||
if ( !gh )
|
||||
return;
|
||||
pmap = (**gh).gdPMap;
|
||||
if ( !pmap )
|
||||
return;
|
||||
|
||||
RNG_GenerateGlobalRandomBytes( coords, sizeof( coords ) );
|
||||
|
||||
/* make x and y inside the screen rect */
|
||||
screenHeight = (**pmap).bounds.bottom - (**pmap).bounds.top;
|
||||
screenWidth = (**pmap).bounds.right - (**pmap).bounds.left;
|
||||
x = coords[0] % screenWidth;
|
||||
y = coords[1] % screenHeight;
|
||||
w = ( coords[2] & 0x7F ) | 0x40; /* Make sure that w is in the range 64..128 */
|
||||
h = ( coords[3] & 0x7F ) | 0x40; /* same for h */
|
||||
|
||||
bytesPerPixel = (**pmap).pixelSize / 8;
|
||||
rowBytes = (**pmap).rowBytes & 0x7FFF;
|
||||
|
||||
/* starting address */
|
||||
offset = ( rowBytes * y ) + (UInt32)( (float)x * bytesPerPixel );
|
||||
|
||||
/* don't read past the end of the pixmap's rowbytes */
|
||||
bytesToRead = PR_MIN( (UInt32)( w * bytesPerPixel ),
|
||||
(UInt32)( rowBytes - ( x * bytesPerPixel ) ) );
|
||||
|
||||
/* don't read past the end of the graphics device pixmap */
|
||||
rowsToRead = PR_MIN( h,
|
||||
( screenHeight - y ) );
|
||||
|
||||
p = GetPixBaseAddr( pmap ) + offset;
|
||||
|
||||
while ( rowsToRead-- )
|
||||
{
|
||||
RNG_RandomUpdate( p, bytesToRead );
|
||||
p += rowBytes;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
146
mozilla/security/nss/lib/freebl/manifest.mn
Normal file
146
mozilla/security/nss/lib/freebl/manifest.mn
Normal file
@@ -0,0 +1,146 @@
|
||||
#
|
||||
# The contents of this file are subject to the Mozilla Public
|
||||
# License Version 1.1 (the "License"); you may not use this file
|
||||
# except in compliance with the License. You may obtain a copy of
|
||||
# the License at http://www.mozilla.org/MPL/
|
||||
#
|
||||
# Software distributed under the License is distributed on an "AS
|
||||
# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
|
||||
# implied. See the License for the specific language governing
|
||||
# rights and limitations under the License.
|
||||
#
|
||||
# The Original Code is the Netscape security libraries.
|
||||
#
|
||||
# The Initial Developer of the Original Code is Netscape
|
||||
# Communications Corporation. Portions created by Netscape are
|
||||
# Copyright (C) 1994-2000 Netscape Communications Corporation. All
|
||||
# Rights Reserved.
|
||||
#
|
||||
# Portions created by Sun Microsystems, Inc. are Copyright (C) 2003
|
||||
# Sun Microsystems, Inc. All Rights Reserved.
|
||||
#
|
||||
# Contributor(s):
|
||||
# Dr Vipul Gupta <vipul.gupta@sun.com>, Sun Microsystems Laboratories
|
||||
#
|
||||
# Alternatively, the contents of this file may be used under the
|
||||
# terms of the GNU General Public License Version 2 or later (the
|
||||
# "GPL"), in which case the provisions of the GPL are applicable
|
||||
# instead of those above. If you wish to allow use of your
|
||||
# version of this file only under the terms of the GPL and not to
|
||||
# allow others to use your version of this file under the MPL,
|
||||
# indicate your decision by deleting the provisions above and
|
||||
# replace them with the notice and other provisions required by
|
||||
# the GPL. If you do not delete the provisions above, a recipient
|
||||
# may use your version of this file under either the MPL or the
|
||||
# GPL.
|
||||
#
|
||||
CORE_DEPTH = ../../..
|
||||
|
||||
MODULE = nss
|
||||
|
||||
ifndef FREEBL_RECURSIVE_BUILD
|
||||
LIBRARY_NAME = freebl
|
||||
else
|
||||
ifdef USE_PURE_32
|
||||
CORE_DEPTH = ../../../..
|
||||
LIBRARY_NAME = freebl_pure32
|
||||
else
|
||||
LIBRARY_NAME = freebl_hybrid
|
||||
endif
|
||||
endif
|
||||
|
||||
# same version as rest of freebl
|
||||
LIBRARY_VERSION = _3
|
||||
|
||||
DEFINES += -DSHLIB_SUFFIX=\"$(DLL_SUFFIX)\" -DSHLIB_PREFIX=\"$(DLL_PREFIX)\"
|
||||
|
||||
REQUIRES =
|
||||
|
||||
EXPORTS = \
|
||||
blapi.h \
|
||||
blapit.h \
|
||||
secrng.h \
|
||||
shsign.h \
|
||||
$(NULL)
|
||||
|
||||
PRIVATE_EXPORTS = \
|
||||
secmpi.h \
|
||||
ec.h \
|
||||
$(NULL)
|
||||
|
||||
MPI_HDRS = mpi-config.h mpi.h mpi-priv.h mplogic.h mpprime.h logtab.h mp_gf2m.h
|
||||
MPI_SRCS = mpprime.c mpmontg.c mplogic.c mpi.c mp_gf2m.c
|
||||
|
||||
ifdef MOZILLA_BSAFE_BUILD
|
||||
CSRCS = \
|
||||
fblstdlib.c \
|
||||
sha_fast.c \
|
||||
md2.c \
|
||||
md5.c \
|
||||
blapi_bsf.c \
|
||||
$(MPI_SRCS) \
|
||||
dh.c \
|
||||
$(NULL)
|
||||
else
|
||||
CSRCS = \
|
||||
ldvector.c \
|
||||
prng_fips1861.c \
|
||||
sysrand.c \
|
||||
sha_fast.c \
|
||||
md2.c \
|
||||
md5.c \
|
||||
sha512.c \
|
||||
alg2268.c \
|
||||
arcfour.c \
|
||||
arcfive.c \
|
||||
desblapi.c \
|
||||
des.c \
|
||||
rijndael.c \
|
||||
aeskeywrap.c \
|
||||
dh.c \
|
||||
ec.c \
|
||||
GFp_ecl.c \
|
||||
GF2m_ecl.c \
|
||||
pqg.c \
|
||||
dsa.c \
|
||||
rsa.c \
|
||||
shvfy.c \
|
||||
$(MPI_SRCS) \
|
||||
$(NULL)
|
||||
endif
|
||||
|
||||
ALL_CSRCS := $(CSRCS)
|
||||
|
||||
ALL_HDRS = \
|
||||
blapi.h \
|
||||
blapit.h \
|
||||
des.h \
|
||||
ec.h \
|
||||
GFp_ecl.h \
|
||||
GF2m_ecl.h \
|
||||
loader.h \
|
||||
rijndael.h \
|
||||
secmpi.h \
|
||||
sha.h \
|
||||
sha_fast.h \
|
||||
shsign.h \
|
||||
vis_proto.h \
|
||||
$(NULL)
|
||||
|
||||
ifdef AES_GEN_TBL
|
||||
DEFINES += -DRIJNDAEL_GENERATE_TABLES
|
||||
else
|
||||
ifdef AES_GEN_TBL_M
|
||||
DEFINES += -DRIJNDAEL_GENERATE_TABLES_MACRO
|
||||
else
|
||||
ifdef AES_GEN_VAL
|
||||
DEFINES += -DRIJNDAEL_GENERATE_VALUES
|
||||
else
|
||||
ifdef AES_GEN_VAL_M
|
||||
DEFINES += -DRIJNDAEL_GENERATE_VALUES_MACRO
|
||||
else
|
||||
DEFINES += -DRIJNDAEL_INCLUDE_TABLES
|
||||
endif
|
||||
endif
|
||||
endif
|
||||
endif
|
||||
39
mozilla/security/nss/lib/freebl/mapfile.Solaris
Normal file
39
mozilla/security/nss/lib/freebl/mapfile.Solaris
Normal file
@@ -0,0 +1,39 @@
|
||||
#
|
||||
# The contents of this file are subject to the Mozilla Public
|
||||
# License Version 1.1 (the "License"); you may not use this file
|
||||
# except in compliance with the License. You may obtain a copy of
|
||||
# the License at http://www.mozilla.org/MPL/
|
||||
#
|
||||
# Software distributed under the License is distributed on an "AS
|
||||
# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
|
||||
# implied. See the License for the specific language governing
|
||||
# rights and limitations under the License.
|
||||
#
|
||||
# The Original Code is the Netscape security libraries.
|
||||
#
|
||||
# The Initial Developer of the Original Code is Netscape
|
||||
# Communications Corporation. Portions created by Netscape are
|
||||
# Copyright (C) 2000 Netscape Communications Corporation. All
|
||||
# Rights Reserved.
|
||||
#
|
||||
# Contributor(s):
|
||||
#
|
||||
# Alternatively, the contents of this file may be used under the
|
||||
# terms of the GNU General Public License Version 2 or later (the
|
||||
# "GPL"), in which case the provisions of the GPL are applicable
|
||||
# instead of those above. If you wish to allow use of your
|
||||
# version of this file only under the terms of the GPL and not to
|
||||
# allow others to use your version of this file under the MPL,
|
||||
# indicate your decision by deleting the provisions above and
|
||||
# replace them with the notice and other provisions required by
|
||||
# the GPL. If you do not delete the provisions above, a recipient
|
||||
# may use your version of this file under either the MPL or the
|
||||
# GPL.
|
||||
#
|
||||
|
||||
libfreebl_3.so {
|
||||
global:
|
||||
FREEBL_GetVector;
|
||||
local:
|
||||
*;
|
||||
};
|
||||
@@ -1,5 +0,0 @@
|
||||
<IfModule mod_rewrite.c>
|
||||
RewriteEngine on
|
||||
RewriteRule ^$ webroot/ [L]
|
||||
RewriteRule (.*) webroot/$1 [L]
|
||||
</IfModule>
|
||||
@@ -1,69 +0,0 @@
|
||||
<?php
|
||||
/* SVN FILE: $Id: app_controller.php,v 1.1.1.1 2006-05-24 19:14:24 uid815 Exp $ */
|
||||
|
||||
/**
|
||||
* Short description for file.
|
||||
*
|
||||
* This file is application-wide controller file. You can put all
|
||||
* application-wide controller-related methods here.
|
||||
*
|
||||
* PHP versions 4 and 5
|
||||
*
|
||||
* CakePHP : Rapid Development Framework <http://www.cakephp.org/>
|
||||
* Copyright (c) 2006, Cake Software Foundation, Inc.
|
||||
* 1785 E. Sahara Avenue, Suite 490-204
|
||||
* Las Vegas, Nevada 89104
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @filesource
|
||||
* @copyright Copyright (c) 2006, Cake Software Foundation, Inc.
|
||||
* @link http://www.cakefoundation.org/projects/info/cakephp CakePHP Project
|
||||
* @package cake
|
||||
* @subpackage cake.cake
|
||||
* @since CakePHP v 0.2.9
|
||||
* @version $Revision: 1.1.1.1 $
|
||||
* @modifiedby $LastChangedBy: phpnut $
|
||||
* @lastmodified $Date: 2006-05-24 19:14:24 $
|
||||
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
|
||||
*/
|
||||
|
||||
/**
|
||||
* Short description for class.
|
||||
*
|
||||
* Add your application-wide methods in the class below, your controllers
|
||||
* will inherit them.
|
||||
*
|
||||
* @package cake
|
||||
* @subpackage cake.cake
|
||||
*/
|
||||
|
||||
uses('Sanitize');
|
||||
|
||||
class AppController extends Controller {
|
||||
|
||||
/**
|
||||
* This function is intended to be used with url parameters when passing them to
|
||||
* a view. (This is useful when echoing values out in <input> tags, etc.
|
||||
* Note that the keys to the arrays are escaped as well.
|
||||
*
|
||||
* @param array dirty parameters
|
||||
* @return array cleaned values
|
||||
*/
|
||||
function decodeAndSanitize($params)
|
||||
{
|
||||
$clean = array();
|
||||
|
||||
foreach ($params as $var => $val) {
|
||||
$var = $this->Sanitize->html(urldecode($var));
|
||||
$val = $this->Sanitize->html(urldecode($val));
|
||||
|
||||
$clean[$var] = $val;
|
||||
}
|
||||
|
||||
return $clean;
|
||||
}
|
||||
}
|
||||
|
||||
?>
|
||||
@@ -1,72 +0,0 @@
|
||||
<?php
|
||||
/* SVN FILE: $Id: app_model.php,v 1.1.1.1 2006-05-24 19:14:24 uid815 Exp $ */
|
||||
|
||||
/**
|
||||
* Application model for Cake.
|
||||
*
|
||||
* This file is application-wide model file. You can put all
|
||||
* application-wide model-related methods here.
|
||||
*
|
||||
* PHP versions 4 and 5
|
||||
*
|
||||
* CakePHP : Rapid Development Framework <http://www.cakephp.org/>
|
||||
* Copyright (c) 2006, Cake Software Foundation, Inc.
|
||||
* 1785 E. Sahara Avenue, Suite 490-204
|
||||
* Las Vegas, Nevada 89104
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @filesource
|
||||
* @copyright Copyright (c) 2006, Cake Software Foundation, Inc.
|
||||
* @link http://www.cakefoundation.org/projects/info/cakephp CakePHP Project
|
||||
* @package cake
|
||||
* @subpackage cake.cake
|
||||
* @since CakePHP v 0.2.9
|
||||
* @version $Revision: 1.1.1.1 $
|
||||
* @modifiedby $LastChangedBy: phpnut $
|
||||
* @lastmodified $Date: 2006-05-24 19:14:24 $
|
||||
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
|
||||
*/
|
||||
|
||||
/**
|
||||
* Application model for Cake.
|
||||
*
|
||||
* Add your application-wide methods in the class below, your models
|
||||
* will inherit them.
|
||||
*
|
||||
* @package cake
|
||||
* @subpackage cake.cake
|
||||
*/
|
||||
|
||||
uses('sanitize');
|
||||
|
||||
class AppModel extends Model {
|
||||
|
||||
/**
|
||||
* Will clean arrays for input into SQL.
|
||||
* Note that the array keys are getting cleaned here as well. If you're using strings
|
||||
* (with escapable characters in them) as keys to your array, be extra careful.
|
||||
*
|
||||
* @access public
|
||||
* @param array to be cleaned
|
||||
* @return array with sql escaped
|
||||
*/
|
||||
function cleanArrayForSql($array)
|
||||
{
|
||||
$sanitize = new Sanitize();
|
||||
$clean = array();
|
||||
|
||||
foreach ($array as $var => $val)
|
||||
{
|
||||
$var = $sanitize->sql($var);
|
||||
$val = $sanitize->sql($val);
|
||||
$clean[$var] = $val;
|
||||
}
|
||||
|
||||
return $clean;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
?>
|
||||
@@ -1,76 +0,0 @@
|
||||
;<?php die() ?>
|
||||
; SVN FILE: $Id: acl.ini.php,v 1.1.1.1 2006-05-24 19:14:24 uid815 Exp $
|
||||
;/**
|
||||
; * Short description for file.
|
||||
; *
|
||||
; *
|
||||
; * PHP versions 4 and 5
|
||||
; *
|
||||
; * CakePHP : Rapid Development Framework <http://www.cakephp.org/>
|
||||
; * Copyright (c) 2006, Cake Software Foundation, Inc.
|
||||
; * 1785 E. Sahara Avenue, Suite 490-204
|
||||
; * Las Vegas, Nevada 89104
|
||||
; *
|
||||
; * Licensed under The MIT License
|
||||
; * Redistributions of files must retain the above copyright notice.
|
||||
; *
|
||||
; * @filesource
|
||||
; * @copyright Copyright (c) 2006, Cake Software Foundation, Inc.
|
||||
; * @link http://www.cakefoundation.org/projects/info/cakephp CakePHP Project
|
||||
; * @package cake
|
||||
; * @subpackage cake.app.config
|
||||
; * @since CakePHP v 0.10.0.1076
|
||||
; * @version $Revision: 1.1.1.1 $
|
||||
; * @modifiedby $LastChangedBy: phpnut $
|
||||
; * @lastmodified $Date: 2006-05-24 19:14:24 $
|
||||
; * @license http://www.opensource.org/licenses/mit-license.php The MIT License
|
||||
; */
|
||||
|
||||
; acl.ini.php - Cake ACL Configuration
|
||||
; ---------------------------------------------------------------------
|
||||
; Use this file to specify user permissions.
|
||||
; aco = access control object (something in your application)
|
||||
; aro = access request object (something requesting access)
|
||||
;
|
||||
; User records are added as follows:
|
||||
;
|
||||
; [uid]
|
||||
; groups = group1, group2, group3
|
||||
; allow = aco1, aco2, aco3
|
||||
; deny = aco4, aco5, aco6
|
||||
;
|
||||
; Group records are added in a similar manner:
|
||||
;
|
||||
; [gid]
|
||||
; allow = aco1, aco2, aco3
|
||||
; deny = aco4, aco5, aco6
|
||||
;
|
||||
; The allow, deny, and groups sections are all optional.
|
||||
; NOTE: groups names *cannot* ever be the same as usernames!
|
||||
;
|
||||
; ACL permissions are checked in the following order:
|
||||
; 1. Check for user denies (and DENY if specified)
|
||||
; 2. Check for user allows (and ALLOW if specified)
|
||||
; 3. Gather user's groups
|
||||
; 4. Check group denies (and DENY if specified)
|
||||
; 5. Check group allows (and ALLOW if specified)
|
||||
; 6. If no aro, aco, or group information is found, DENY
|
||||
;
|
||||
; ---------------------------------------------------------------------
|
||||
|
||||
;-------------------------------------
|
||||
;Users
|
||||
;-------------------------------------
|
||||
|
||||
[username-goes-here]
|
||||
groups = group1, group2
|
||||
deny = aco1, aco2
|
||||
allow = aco3, aco4
|
||||
|
||||
;-------------------------------------
|
||||
;Groups
|
||||
;-------------------------------------
|
||||
|
||||
[groupname-goes-here]
|
||||
deny = aco5, aco6
|
||||
allow = aco7, aco8
|
||||
@@ -1,50 +0,0 @@
|
||||
<?php
|
||||
/* SVN FILE: $Id: bootstrap.php,v 1.1.1.1 2006-05-24 19:14:24 uid815 Exp $ */
|
||||
|
||||
/**
|
||||
* Short description for file.
|
||||
*
|
||||
* Long description for file
|
||||
*
|
||||
* PHP versions 4 and 5
|
||||
*
|
||||
* CakePHP : Rapid Development Framework <http://www.cakephp.org/>
|
||||
* Copyright (c) 2006, Cake Software Foundation, Inc.
|
||||
* 1785 E. Sahara Avenue, Suite 490-204
|
||||
* Las Vegas, Nevada 89104
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @filesource
|
||||
* @copyright Copyright (c) 2006, Cake Software Foundation, Inc.
|
||||
* @link http://www.cakefoundation.org/projects/info/cakephp CakePHP Project
|
||||
* @package cake
|
||||
* @subpackage cake.app.config
|
||||
* @since CakePHP v 0.10.8.2117
|
||||
* @version $Revision: 1.1.1.1 $
|
||||
* @modifiedby $LastChangedBy: phpnut $
|
||||
* @lastmodified $Date: 2006-05-24 19:14:24 $
|
||||
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
|
||||
*/
|
||||
|
||||
/**
|
||||
*
|
||||
* This file is loaded automatically by the app/webroot/index.php file after the core bootstrap.php is loaded
|
||||
* This is an application wide file to load any function that is not used within a class define.
|
||||
* You can also use this to include or require any files in your application.
|
||||
*
|
||||
*/
|
||||
|
||||
/**
|
||||
* The settings below can be used to set additional paths to models, views and controllers.
|
||||
* This is related to Ticket #470 (https://trac.cakephp.org/ticket/470)
|
||||
*
|
||||
* $modelPaths = array('full path to models', 'second full path to models', 'etc...');
|
||||
* $viewPaths = array('this path to views', 'second full path to views', 'etc...');
|
||||
* $controllerPaths = array('this path to controllers', 'second full path to controllers', 'etc...');
|
||||
*
|
||||
*/
|
||||
|
||||
//EOF
|
||||
?>
|
||||
@@ -1,153 +0,0 @@
|
||||
<?php
|
||||
/* SVN FILE: $Id: core.php,v 1.1.1.1 2006-05-24 19:14:24 uid815 Exp $ */
|
||||
|
||||
/**
|
||||
* This is core configuration file.
|
||||
*
|
||||
* Use it to configure core behaviour ofCake.
|
||||
*
|
||||
* PHP versions 4 and 5
|
||||
*
|
||||
* CakePHP : Rapid Development Framework <http://www.cakephp.org/>
|
||||
* Copyright (c) 2006, Cake Software Foundation, Inc.
|
||||
* 1785 E. Sahara Avenue, Suite 490-204
|
||||
* Las Vegas, Nevada 89104
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @filesource
|
||||
* @copyright Copyright (c) 2006, Cake Software Foundation, Inc.
|
||||
* @link http://www.cakefoundation.org/projects/info/cakephp CakePHP Project
|
||||
* @package cake
|
||||
* @subpackage cake.app.config
|
||||
* @since CakePHP v 0.2.9
|
||||
* @version $Revision: 1.1.1.1 $
|
||||
* @modifiedby $LastChangedBy: phpnut $
|
||||
* @lastmodified $Date: 2006-05-24 19:14:24 $
|
||||
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
|
||||
*/
|
||||
|
||||
/**
|
||||
* If you do not have mod rewrite on your system
|
||||
* or if you prefer to use CakePHP pretty urls.
|
||||
* uncomment the line below.
|
||||
* Note: If you do have mod rewrite but prefer the
|
||||
* CakePHP pretty urls, you also have to remove the
|
||||
* .htaccess files
|
||||
* release/.htaccess
|
||||
* release/app/.htaccess
|
||||
* release/app/webroot/.htaccess
|
||||
*/
|
||||
//define ('BASE_URL', env('SCRIPT_NAME'));
|
||||
|
||||
/**
|
||||
* Set debug level here:
|
||||
* - 0: production
|
||||
* - 1: development
|
||||
* - 2: full debug with sql
|
||||
* - 3: full debug with sql and dump of the current object
|
||||
*
|
||||
* In production, the "flash messages" redirect after a time interval.
|
||||
* With the other debug levels you get to click the "flash message" to continue.
|
||||
*
|
||||
*/
|
||||
define('DEBUG', 0);
|
||||
/**
|
||||
* Turn of caching checking wide.
|
||||
* You must still use the controller var cacheAction inside you controller class.
|
||||
* You can either set it controller wide, or in each controller method.
|
||||
* use var $cacheAction = true; or in the controller method $this->cacheAction = true;
|
||||
*/
|
||||
define ('CACHE_CHECK', false);
|
||||
/**
|
||||
* Error constant. Used for differentiating error logging and debugging.
|
||||
* Currently PHP supports LOG_DEBUG
|
||||
*/
|
||||
define ('LOG_ERROR', 2);
|
||||
/**
|
||||
* CakePHP includes 3 types of session saves
|
||||
* database or file. Set this to your preferred method.
|
||||
* If you want to use your own save handler place it in
|
||||
* app/config/name.php DO NOT USE file or database as the name.
|
||||
* and use just the name portion below.
|
||||
*
|
||||
* Setting this to cake will save files to /cakedistro/tmp directory
|
||||
* Setting it to php will use the php default save path
|
||||
* Setting it to database will use the database
|
||||
*
|
||||
*
|
||||
*/
|
||||
define('CAKE_SESSION_SAVE', 'php');
|
||||
/**
|
||||
* Set a random string of used in session.
|
||||
*
|
||||
*/
|
||||
define('CAKE_SESSION_STRING', 'DYhG93b0qyJfIxfs2guVoUubWwvniR2G0FgaC9mi');
|
||||
/**
|
||||
* Set the name of session cookie
|
||||
*
|
||||
*/
|
||||
define('CAKE_SESSION_COOKIE', 'CAKEPHP');
|
||||
|
||||
/**
|
||||
* Set level of Cake security.
|
||||
*
|
||||
*/
|
||||
define('CAKE_SECURITY', 'high');
|
||||
|
||||
/**
|
||||
* Set Cake Session time out.
|
||||
* If CAKE_SECURITY define is set
|
||||
* high: multiplied by 10
|
||||
* medium: is multiplied by 100
|
||||
* low is: multiplied by 300
|
||||
*
|
||||
* Number below is seconds.
|
||||
*/
|
||||
define('CAKE_SESSION_TIMEOUT', '120');
|
||||
|
||||
/**
|
||||
* Uncomment the define below to use cake built in admin routes.
|
||||
* You can set this value to anything you want.
|
||||
* All methods related to the admin route should be prefixed with the
|
||||
* name you set CAKE_ADMIN to.
|
||||
* For example: admin_index, admin_edit
|
||||
*/
|
||||
//define('CAKE_ADMIN', 'admin');
|
||||
|
||||
/**
|
||||
* The define below is used to turn cake built webservices
|
||||
* on or off. Default setting is off.
|
||||
*/
|
||||
define('WEBSERVICES', 'off');
|
||||
|
||||
/**
|
||||
* Compress output CSS (removing comments, whitespace, repeating tags etc.)
|
||||
* This requires a/var/cache directory to be writable by the web server (caching).
|
||||
* To use, prefix the CSS link URL with '/ccss/' instead of '/css/' or use Controller::cssTag().
|
||||
*/
|
||||
define('COMPRESS_CSS', false);
|
||||
|
||||
/**
|
||||
* If set to true, helpers would output data instead of returning it.
|
||||
*/
|
||||
define('AUTO_OUTPUT', false);
|
||||
|
||||
/**
|
||||
* If set to false, session would not automatically be started.
|
||||
*/
|
||||
define('AUTO_SESSION', true);
|
||||
|
||||
/**
|
||||
* Set the max size of file to use md5() .
|
||||
*/
|
||||
define('MAX_MD5SIZE', (5*1024)*1024 );
|
||||
|
||||
/**
|
||||
* To use Access Control Lists with Cake...
|
||||
*/
|
||||
define('ACL_CLASSNAME', 'DB_ACL');
|
||||
define('ACL_FILENAME', 'dbacl'.DS.'db_acl');
|
||||
|
||||
?>
|
||||
@@ -1,79 +0,0 @@
|
||||
<?php
|
||||
/* SVN FILE: $Id: database.php.default,v 1.1.1.1 2006-05-24 19:14:24 uid815 Exp $ */
|
||||
|
||||
/**
|
||||
* This is core configuration file.
|
||||
*
|
||||
* Use it to configure core behaviour ofCake.
|
||||
*
|
||||
* PHP versions 4 and 5
|
||||
*
|
||||
* CakePHP : Rapid Development Framework <http://www.cakephp.org/>
|
||||
* Copyright (c) 2006, Cake Software Foundation, Inc.
|
||||
* 1785 E. Sahara Avenue, Suite 490-204
|
||||
* Las Vegas, Nevada 89104
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @filesource
|
||||
* @copyright Copyright (c) 2006, Cake Software Foundation, Inc.
|
||||
* @link http://www.cakefoundation.org/projects/info/cakephp CakePHP Project
|
||||
* @package cake
|
||||
* @subpackage cake.app.config
|
||||
* @since CakePHP v 0.2.9
|
||||
* @version $Revision: 1.1.1.1 $
|
||||
* @modifiedby $LastChangedBy: phpnut $
|
||||
* @lastmodified $Date: 2006-05-24 19:14:24 $
|
||||
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
|
||||
*/
|
||||
|
||||
/**
|
||||
* In this file you set up your database connection details.
|
||||
*
|
||||
* @package cake
|
||||
* @subpackage cake.config
|
||||
*/
|
||||
|
||||
|
||||
/**
|
||||
* Database configuration class.
|
||||
* You can specify multiple configurations for production, development and testing.
|
||||
*
|
||||
* driver =>
|
||||
* mysql, postgres, sqlite, adodb-drivername, pear-drivername
|
||||
*
|
||||
* connect =>
|
||||
* MySQL set the connect to either mysql_pconnect of mysql_connect
|
||||
* PostgreSQL set the connect to either pg_pconnect of pg_connect
|
||||
* SQLite set the connect to sqlite_popen sqlite_open
|
||||
* ADOdb set the connect to one of these
|
||||
* (http://phplens.com/adodb/supported.databases.html) and
|
||||
* append it '|p' for persistent connection. (mssql|p for example, or just mssql for not persistent)
|
||||
*
|
||||
* host =>
|
||||
* the host you connect to the database
|
||||
* MySQL 'localhost' to add a port number use 'localhost:port#'
|
||||
* PostgreSQL 'localhost' to add a port number use 'localhost port=5432'
|
||||
*
|
||||
*/
|
||||
class DATABASE_CONFIG
|
||||
{
|
||||
var $default = array('driver' => 'mysql',
|
||||
'connect' => 'mysql_connect',
|
||||
'host' => 'localhost',
|
||||
'login' => 'user',
|
||||
'password' => 'password',
|
||||
'database' => 'project_name',
|
||||
'prefix' => '');
|
||||
|
||||
var $test = array('driver' => 'mysql',
|
||||
'connect' => 'mysql_connect',
|
||||
'host' => 'localhost',
|
||||
'login' => 'user',
|
||||
'password' => 'password',
|
||||
'database' => 'project_name-test',
|
||||
'prefix' => '');
|
||||
}
|
||||
|
||||
?>
|
||||
@@ -1,74 +0,0 @@
|
||||
<?php
|
||||
/* SVN FILE: $Id: inflections.php,v 1.1.1.1 2006-05-24 19:14:24 uid815 Exp $ */
|
||||
|
||||
/**
|
||||
* Custom Inflected Words.
|
||||
*
|
||||
* This file is used to hold words that are not matched in the normail Inflector::pluralize() and
|
||||
* Inflector::singularize()
|
||||
*
|
||||
* PHP versions 4 and %
|
||||
*
|
||||
* CakePHP : Rapid Development Framework <http://www.cakephp.org/>
|
||||
* Copyright (c) 2006, Cake Software Foundation, Inc.
|
||||
* 1785 E. Sahara Avenue, Suite 490-204
|
||||
* Las Vegas, Nevada 89104
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @filesource
|
||||
* @copyright Copyright (c) 2006, Cake Software Foundation, Inc.
|
||||
* @link http://www.cakefoundation.org/projects/info/cakephp CakePHP Project
|
||||
* @package cake
|
||||
* @subpackage cake.app.config
|
||||
* @since CakePHP v 1.0.0.2312
|
||||
* @version $Revision: 1.1.1.1 $
|
||||
* @modifiedby $LastChangedBy: phpnut $
|
||||
* @lastmodified $Date: 2006-05-24 19:14:24 $
|
||||
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
|
||||
*/
|
||||
|
||||
/**
|
||||
* This is a key => value array of regex used to match words.
|
||||
* If key matches then the value is returned.
|
||||
*
|
||||
* $pluralRules = array('/(s)tatus$/i' => '\1\2tatuses', '/^(ox)$/i' => '\1\2en', '/([m|l])ouse$/i' => '\1ice');
|
||||
*/
|
||||
$pluralRules = array();
|
||||
/**
|
||||
* This is a key only array of plural words that should not be inflected.
|
||||
* Notice the last comma
|
||||
*
|
||||
* $uninflectedPlural = array('.*[nrlm]ese', '.*deer', '.*fish', '.*measles', '.*ois', '.*pox');
|
||||
*/
|
||||
$uninflectedPlural = array();
|
||||
/**
|
||||
* This is a key => value array of plural irregular words.
|
||||
* If key matches then the value is returned.
|
||||
*
|
||||
* $irregularPlural = array('atlas' => 'atlases', 'beef' => 'beefs', 'brother' => 'brothers')
|
||||
*/
|
||||
$irregularPlural = array();
|
||||
/**
|
||||
* This is a key => value array of regex used to match words.
|
||||
* If key matches then the value is returned.
|
||||
*
|
||||
* $singularRules = array('/(s)tatuses$/i' => '\1\2tatus', '/(matr)ices$/i' =>'\1ix','/(vert|ind)ices$/i')
|
||||
*/
|
||||
$singularRules = array();
|
||||
/**
|
||||
* This is a key only array of singular words that should not be inflected.
|
||||
* You should not have to change this value below if you do change it use same format
|
||||
* as the $uninflectedPlural above.
|
||||
*/
|
||||
$uninflectedSingular = $uninflectedPlural;
|
||||
/**
|
||||
* This is a key => value array of singular irregular words.
|
||||
* Most of the time this will be a reverse of the above $irregularPlural array
|
||||
* You should not have to change this value below if you do change it use same format
|
||||
*
|
||||
* $irregularSingular = array('atlases' => 'atlas', 'beefs' => 'beef', 'brothers' => 'brother')
|
||||
*/
|
||||
$irregularSingular = array_flip($irregularPlural);
|
||||
?>
|
||||
@@ -1,51 +0,0 @@
|
||||
<?php
|
||||
/* SVN FILE: $Id: routes.php,v 1.1.1.1 2006-05-24 19:14:24 uid815 Exp $ */
|
||||
|
||||
/**
|
||||
* Short description for file.
|
||||
*
|
||||
* In this file, you set up routes to your controllers and their actions.
|
||||
* Routes are very important mechanism that allows you to freely connect
|
||||
* different urls to chosen controllers and their actions (functions).
|
||||
*
|
||||
* PHP versions 4 and 5
|
||||
*
|
||||
* CakePHP : Rapid Development Framework <http://www.cakephp.org/>
|
||||
* Copyright (c) 2006, Cake Software Foundation, Inc.
|
||||
* 1785 E. Sahara Avenue, Suite 490-204
|
||||
* Las Vegas, Nevada 89104
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @filesource
|
||||
* @copyright Copyright (c) 2006, Cake Software Foundation, Inc.
|
||||
* @link http://www.cakefoundation.org/projects/info/cakephp CakePHP Project
|
||||
* @package cake
|
||||
* @subpackage cake.app.config
|
||||
* @since CakePHP v 0.2.9
|
||||
* @version $Revision: 1.1.1.1 $
|
||||
* @modifiedby $LastChangedBy: phpnut $
|
||||
* @lastmodified $Date: 2006-05-24 19:14:24 $
|
||||
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
|
||||
*/
|
||||
|
||||
/**
|
||||
* Here, we are connecting '/' (base path) to controller called 'Pages',
|
||||
* its action called 'display', and we pass a param to select the view file
|
||||
* to use (in this case, /app/views/pages/home.thtml)...
|
||||
*/
|
||||
$Route->connect ('/', array('controller'=>'results', 'action'=>'', ''));
|
||||
|
||||
/**
|
||||
* ...and connect the rest of 'Pages' controller's urls.
|
||||
*/
|
||||
$Route->connect ('/pages/*', array('controller'=>'pages', 'action'=>'display'));
|
||||
|
||||
/**
|
||||
* Then we connect url '/test' to our test controller. This is helpfull in
|
||||
* developement.
|
||||
*/
|
||||
$Route->connect ('/tests', array('controller'=>'tests', 'action'=>'index'));
|
||||
|
||||
?>
|
||||
@@ -1,30 +0,0 @@
|
||||
CREATE TABLE `acos` (
|
||||
`id` int(11) NOT NULL auto_increment,
|
||||
`model` varchar(255) NOT NULL default '',
|
||||
`object_id` int(11) default NULL,
|
||||
`alias` varchar(255) NOT NULL default '',
|
||||
`lft` int(11) default NULL,
|
||||
`rght` int(11) default NULL,
|
||||
PRIMARY KEY (`id`)
|
||||
);
|
||||
|
||||
CREATE TABLE `aros` (
|
||||
`id` int(11) NOT NULL auto_increment,
|
||||
`model` varchar(255) NOT NULL default '',
|
||||
`user_id` int(11) default NULL,
|
||||
`alias` varchar(255) NOT NULL default '',
|
||||
`lft` int(11) default NULL,
|
||||
`rght` int(11) default NULL,
|
||||
PRIMARY KEY (`id`)
|
||||
);
|
||||
|
||||
CREATE TABLE `aros_acos` (
|
||||
`id` int(11) NOT NULL auto_increment,
|
||||
`aro_id` int(11) default NULL,
|
||||
`aco_id` int(11) default NULL,
|
||||
`_create` int(1) NOT NULL default '0',
|
||||
`_read` int(1) NOT NULL default '0',
|
||||
`_update` int(1) NOT NULL default '0',
|
||||
`_delete` int(11) NOT NULL default '0',
|
||||
PRIMARY KEY (`id`)
|
||||
);
|
||||
@@ -1,11 +0,0 @@
|
||||
-- @copyright Copyright (c) 2006, Cake Software Foundation, Inc.
|
||||
-- @link http://www.cakefoundation.org/projects/info/cakephp CakePHP Project
|
||||
-- @since CakePHP v 0.10.8.1997
|
||||
-- @version $Revision: 1.1.1.1 $
|
||||
|
||||
CREATE TABLE cake_sessions (
|
||||
id varchar(255) NOT NULL default '',
|
||||
data text,
|
||||
expires int(11) default NULL,
|
||||
PRIMARY KEY (id)
|
||||
);
|
||||
@@ -1,7 +0,0 @@
|
||||
<?php
|
||||
class ApplicationsController extends AppController {
|
||||
|
||||
var $name = 'Applications';
|
||||
|
||||
}
|
||||
?>
|
||||
@@ -1,7 +0,0 @@
|
||||
<?php
|
||||
class IntentionsController extends AppController {
|
||||
|
||||
var $name = 'Intentions';
|
||||
|
||||
}
|
||||
?>
|
||||
@@ -1,7 +0,0 @@
|
||||
<?php
|
||||
class IssuesController extends AppController {
|
||||
|
||||
var $name = 'Issues';
|
||||
|
||||
}
|
||||
?>
|
||||
@@ -1,122 +0,0 @@
|
||||
<?php
|
||||
|
||||
/* Include the CSV library. It would be nice to make this OO sometime */
|
||||
vendor('csv/csv');
|
||||
|
||||
class ResultsController extends AppController {
|
||||
|
||||
var $name = 'Results';
|
||||
|
||||
/**
|
||||
* Model's this controller uses
|
||||
* @var array
|
||||
*/
|
||||
var $uses = array('Application','Result');
|
||||
|
||||
/**
|
||||
* Cake Helpers
|
||||
* @var array
|
||||
*/
|
||||
var $helpers = array('Html', 'Javascript', 'Export', 'Pagination','Time');
|
||||
|
||||
/**
|
||||
* Pagination helper variable array
|
||||
* @access public
|
||||
* @var array
|
||||
*/
|
||||
var $pagination_parameters = array();
|
||||
|
||||
/**
|
||||
* Will hold a sanitize object
|
||||
* @var object
|
||||
*/
|
||||
var $Sanitize;
|
||||
|
||||
/**
|
||||
* Constructor - sets up the sanitizer and the pagination
|
||||
*/
|
||||
function ResultsController()
|
||||
{
|
||||
parent::AppController();
|
||||
|
||||
$this->Sanitize = new Sanitize();
|
||||
|
||||
// Pagination Stuff
|
||||
$this->pagination_parameters['show'] = empty($_GET['show'])? '10' : $this->Sanitize->paranoid($_GET['show']);
|
||||
$this->pagination_parameters['sortBy'] = empty($_GET['sort'])? 'created' : $this->Sanitize->paranoid($_GET['sort']);
|
||||
$this->pagination_parameters['direction'] = empty($_GET['direction'])? 'desc': $this->Sanitize->paranoid($_GET['direction']);
|
||||
$this->pagination_parameters['page'] = empty($_GET['page'])? '1': $this->Sanitize->paranoid($_GET['page']);
|
||||
$this->pagination_parameters['order'] = $this->modelClass.'.'.$this->pagination_parameters['sortBy'].' '.strtoupper($this->pagination_parameters['direction']);
|
||||
}
|
||||
|
||||
/**
|
||||
* Front page will show the graph
|
||||
*/
|
||||
function index()
|
||||
{
|
||||
// Products dropdown
|
||||
$this->set('products', $this->Application->getApplications());
|
||||
|
||||
// Fill in all the data passed in $_GET
|
||||
$this->set('url_params',$this->decodeAndSanitize($this->params['url']));
|
||||
|
||||
// We'll need to include the graphing libraries
|
||||
$this->set('include_graph_libraries', true);
|
||||
|
||||
// Core data to show on page
|
||||
$this->set('descriptionAndTotalsData',$this->Result->getDescriptionAndTotalsData($this->params['url']));
|
||||
}
|
||||
|
||||
/**
|
||||
* Display a table of user comments
|
||||
*/
|
||||
function comments()
|
||||
{
|
||||
// Products dropdown
|
||||
$this->set('products', $this->Application->getApplications());
|
||||
|
||||
// Fill in all the data passed in $_GET
|
||||
$this->set('url_params',$this->decodeAndSanitize($this->params['url']));
|
||||
|
||||
// Pagination settings
|
||||
$paging['style'] = 'html';
|
||||
$paging['link'] = "/results/comments/?product=".urlencode($this->params['url']['product'])."&start_date=".urlencode($this->params['url']['start_date'])."&end_date=".urlencode($this->params['url']['end_date'])."&show={$this->pagination_parameters['show']}&sort={$this->pagination_parameters['sortBy']}&direction={$this->pagination_parameters['direction']}&page=";
|
||||
$paging['count'] = $this->Result->getCommentCount($this->params['url']);
|
||||
$paging['page'] = $this->pagination_parameters['page'];
|
||||
$paging['limit'] = $this->pagination_parameters['show'];
|
||||
$paging['show'] = array('10','25','50');
|
||||
|
||||
// No point in showing them an error if they click on "show 50" but they are
|
||||
// already on the last page.
|
||||
if ($paging['count'] < ($this->pagination_parameters['page'] * ($this->pagination_parameters['show']/2))) {
|
||||
$this->pagination_parameters['page'] = $paging['page'] = 1;
|
||||
}
|
||||
|
||||
// Set pagination array
|
||||
$this->set('paging',$paging);
|
||||
|
||||
// Core data to show on page
|
||||
$this->set('commentsData',$this->Result->getComments($this->params['url'], $this->pagination_parameters));
|
||||
|
||||
|
||||
}
|
||||
|
||||
/**
|
||||
* Display a csv
|
||||
*/
|
||||
function csv()
|
||||
{
|
||||
// Get rid of the header/footer/etc.
|
||||
$this->layout = null;
|
||||
|
||||
// Our CSV library sends headers and everything. Keep the view empty!
|
||||
csv_send_csv($this->Result->getCsvExportData($this->params['url']));
|
||||
|
||||
// I'm not exiting here in case someone is going to use post callback stuff.
|
||||
// In development, that means extra lines get added to our CSVs, but in
|
||||
// production it should be clean.
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
?>
|
||||
@@ -1,27 +0,0 @@
|
||||
<?php
|
||||
/* SVN FILE: $Id: index.php,v 1.1.1.1 2006-05-24 19:14:24 uid815 Exp $ */
|
||||
|
||||
/**
|
||||
* PHP versions 4 and 5
|
||||
*
|
||||
* CakePHP : Rapid Development Framework <http://www.cakephp.org/>
|
||||
* Copyright (c) 2006, Cake Software Foundation, Inc.
|
||||
* 1785 E. Sahara Avenue, Suite 490-204
|
||||
* Las Vegas, Nevada 89104
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @filesource
|
||||
* @copyright Copyright (c) 2006, Cake Software Foundation, Inc.
|
||||
* @link http://www.cakefoundation.org/projects/info/cakephp CakePHP Project
|
||||
* @package cake
|
||||
* @subpackage cake.app
|
||||
* @since CakePHP v 0.10.0.1076
|
||||
* @version $Revision: 1.1.1.1 $
|
||||
* @modifiedby $LastChangedBy: phpnut $
|
||||
* @lastmodified $Date: 2006-05-24 19:14:24 $
|
||||
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
|
||||
*/
|
||||
require 'webroot'.DIRECTORY_SEPARATOR.'index.php';
|
||||
?>
|
||||
@@ -1,24 +0,0 @@
|
||||
<?php
|
||||
class Application extends AppModel {
|
||||
var $name = 'Application';
|
||||
|
||||
var $hasOne = array('Result');
|
||||
|
||||
var $hasAndBelongsToMany = array(
|
||||
'Intention' => array('className' => 'Intention'),
|
||||
'Issue' => array('className' => 'Issue')
|
||||
);
|
||||
|
||||
/**
|
||||
* This was added because running findAll() on this model does a left join on the
|
||||
* results table which takes around 10 seconds to grab all the data. All I want
|
||||
* is a list of the applications...
|
||||
*
|
||||
* @return array rows representing each application
|
||||
*/
|
||||
function getApplications()
|
||||
{
|
||||
return $this->query('SELECT * FROM `applications` ORDER BY `id`');
|
||||
}
|
||||
}
|
||||
?>
|
||||
@@ -1,12 +0,0 @@
|
||||
<?php
|
||||
class Intention extends AppModel {
|
||||
var $name = 'Intention';
|
||||
|
||||
var $hasOne = array('Result');
|
||||
|
||||
var $hasAndBelongsToMany = array('Application' =>
|
||||
array('className' => 'Application')
|
||||
);
|
||||
|
||||
}
|
||||
?>
|
||||
@@ -1,10 +0,0 @@
|
||||
<?php
|
||||
class Issue extends AppModel {
|
||||
var $name = 'Issue';
|
||||
|
||||
var $hasAndBelongsToMany = array(
|
||||
'Application' => array('className' => 'Application'),
|
||||
'Result' => array('className' => 'Result')
|
||||
);
|
||||
}
|
||||
?>
|
||||
@@ -1,339 +0,0 @@
|
||||
<?php
|
||||
class Result extends AppModel {
|
||||
var $name = 'Result';
|
||||
|
||||
var $belongsTo = array('Application', 'Intention');
|
||||
|
||||
var $hasAndBelongsToMany = array('Issue' =>
|
||||
array('className' => 'Issue')
|
||||
);
|
||||
|
||||
/**
|
||||
* Count's all the comments, according to the parameters.
|
||||
* @param array URL parameters
|
||||
* @return Cake's findCount() value
|
||||
*/
|
||||
function getCommentCount($params)
|
||||
{
|
||||
// Clean parameters
|
||||
$params = $this->cleanArrayForSql($params);
|
||||
|
||||
// We only want to see rows with comments
|
||||
$_conditions = array("comments NOT LIKE ''");
|
||||
|
||||
if (!empty($params['start_date'])) {
|
||||
$_timestamp = strtotime($params['start_date']);
|
||||
|
||||
if (!($_timestamp == -1) || $_timestamp == false) {
|
||||
$_date = date('Y-m-d H:i:s', $_timestamp);//sql format
|
||||
array_push($_conditions, "`created` >= '{$_date}'");
|
||||
}
|
||||
}
|
||||
if (!empty($params['end_date'])) {
|
||||
$_timestamp = strtotime($params['end_date']);
|
||||
|
||||
if (!($_timestamp == -1) || $_timestamp == false) {
|
||||
$_date = date('Y-m-d H:i:s', $_timestamp);//sql format
|
||||
array_push($_conditions, "`created` <= '{$_date}'");
|
||||
}
|
||||
}
|
||||
|
||||
if (!empty($params['product'])) {
|
||||
// product's come in looking like:
|
||||
// Mozilla Firefox 1.5.0.1
|
||||
$_exp = explode(' ',urldecode($params['product']));
|
||||
|
||||
if(count($_exp) == 3) {
|
||||
$_product = $_exp[0].' '.$_exp[1];
|
||||
|
||||
$_version = $_exp[2];
|
||||
|
||||
/* Note that 'Application' is not the actual name of the table! You can
|
||||
* thank cake for that.*/
|
||||
array_push($_conditions, "`Application`.`name` LIKE '%{$_product}%'");
|
||||
array_push($_conditions, "`Application`.`version` LIKE '%{$_version}%'");
|
||||
} else {
|
||||
// defaults I guess?
|
||||
array_push($_conditions, "`Application`.`name` LIKE 'Mozilla Firefox'");
|
||||
array_push($_conditions, "`Application`.`version` LIKE '1.5'");
|
||||
}
|
||||
|
||||
} else {
|
||||
// I'm providing a default here, because otherwise all results will be
|
||||
// returned (across all applications) and that is not desired
|
||||
array_push($_conditions, "`Application`.`name` LIKE 'Mozilla Firefox'");
|
||||
array_push($_conditions, "`Application`.`version` LIKE '1.5'");
|
||||
}
|
||||
|
||||
// Do the actual query
|
||||
$comments = $this->findCount($_conditions);
|
||||
|
||||
return $comments;
|
||||
}
|
||||
|
||||
/**
|
||||
* Will retrieve all the comments within param's and pagination's parameters
|
||||
* @param array URL parameters
|
||||
* @param array pagination values from the controller
|
||||
* @param boolean if privacy is true phone numbers and email addresses will be
|
||||
* masked
|
||||
* @return cake result set
|
||||
*/
|
||||
function getComments($params, $pagination, $privacy=true)
|
||||
{
|
||||
$params = $this->cleanArrayForSql($params);
|
||||
|
||||
// We only want to see rows with comments
|
||||
$_conditions = array("comments NOT LIKE ''");
|
||||
|
||||
if (!empty($params['start_date'])) {
|
||||
$_timestamp = strtotime($params['start_date']);
|
||||
|
||||
if (!($_timestamp == -1) || $_timestamp == false) {
|
||||
$_date = date('Y-m-d H:i:s', $_timestamp);//sql format
|
||||
array_push($_conditions, "`created` >= '{$_date}'");
|
||||
}
|
||||
}
|
||||
if (!empty($params['end_date'])) {
|
||||
$_timestamp = strtotime($params['end_date']);
|
||||
|
||||
if (!($_timestamp == -1) || $_timestamp == false) {
|
||||
$_date = date('Y-m-d H:i:s', $_timestamp);//sql format
|
||||
array_push($_conditions, "`created` <= '{$_date}'");
|
||||
}
|
||||
}
|
||||
|
||||
if (!empty($params['product'])) {
|
||||
// product's come in looking like:
|
||||
// Mozilla Firefox 1.5.0.1
|
||||
$_exp = explode(' ',urldecode($params['product']));
|
||||
|
||||
if(count($_exp) == 3) {
|
||||
$_product = $_exp[0].' '.$_exp[1];
|
||||
|
||||
$_version = $_exp[2];
|
||||
|
||||
/* Note that 'Application' is not the actual name of the table! You can
|
||||
* thank cake for that.*/
|
||||
array_push($_conditions, "`Application`.`name` LIKE '%{$_product}%'");
|
||||
array_push($_conditions, "`Application`.`version` LIKE '%{$_version}%'");
|
||||
} else {
|
||||
// defaults I guess?
|
||||
array_push($_conditions, "`Application`.`name` LIKE 'Mozilla Firefox'");
|
||||
array_push($_conditions, "`Application`.`version` LIKE '1.5'");
|
||||
}
|
||||
|
||||
} else {
|
||||
// I'm providing a default here, because otherwise all results will be
|
||||
// returned (across all applications) and that is not desired
|
||||
array_push($_conditions, "`Application`.`name` LIKE 'Mozilla Firefox'");
|
||||
array_push($_conditions, "`Application`.`version` LIKE '1.5'");
|
||||
}
|
||||
|
||||
$comments = $this->findAll($_conditions, null, $pagination['order'], $pagination['show'], $pagination['page']);
|
||||
|
||||
if ($privacy) {
|
||||
// Pull out all the email addresses and phone numbers
|
||||
foreach ($comments as $var => $val) {
|
||||
|
||||
// Handle foo@bar.com
|
||||
$_email_regex = '/\ ?(.+)?@(.+)?\.(.+)?\ ?/';
|
||||
$comments[$var]['Result']['comments'] = preg_replace($_email_regex,'$1@****.$3',$comments[$var]['Result']['comments']);
|
||||
$comments[$var]['Result']['intention_text'] = preg_replace($_email_regex,'$1@****.$3',$comments[$var]['Result']['intention_text']);
|
||||
|
||||
// Handle xxx-xxx-xxxx
|
||||
$_phone_regex = '/([0-9]{3})[ .-]?[0-9]{4}/';
|
||||
$comments[$var]['Result']['comments'] = preg_replace($_phone_regex,'$1-****',$comments[$var]['Result']['comments']);
|
||||
$comments[$var]['Result']['intention_text'] = preg_replace($_phone_regex,'$1-****',$comments[$var]['Result']['intention_text']);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
return $comments;
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* This function runs the query to get the export data for the CSV file.
|
||||
*
|
||||
* @param array URL parameters
|
||||
* @param boolean if privacy is true phone numbers and email addresses will be
|
||||
* masked
|
||||
* @return array two dimensional array that should be pretty easy to transform
|
||||
* into a CSV.
|
||||
*/
|
||||
function getCsvExportData($params, $privacy=true)
|
||||
{
|
||||
$params = $this->cleanArrayForSql($params);
|
||||
|
||||
// We have to use a left join here because there isn't always an intention
|
||||
$_query = "
|
||||
SELECT
|
||||
`results`.`id`,
|
||||
`results`.`created`,
|
||||
`results`.`intention_text` as `intention_other`,
|
||||
`results`.`comments`,
|
||||
`intentions`.`description` as `intention`
|
||||
FROM `results`
|
||||
LEFT JOIN `intentions` ON `results`.`intention_id`=`intentions`.`id`
|
||||
INNER JOIN `applications` ON `applications`.`id` = `results`.`application_id`
|
||||
WHERE
|
||||
1=1
|
||||
";
|
||||
|
||||
if (!empty($params['start_date'])) {
|
||||
$_timestamp = strtotime($params['start_date']);
|
||||
|
||||
if (!($_timestamp == -1) || $_timestamp == false) {
|
||||
$_date = date('Y-m-d H:i:s', $_timestamp);//sql format
|
||||
$_query .= " AND `results`.`created` >= '{$_date}'";
|
||||
}
|
||||
}
|
||||
|
||||
if (!empty($params['end_date'])) {
|
||||
$_timestamp = strtotime($params['end_date']);
|
||||
|
||||
if (!($_timestamp == -1) || $_timestamp == false) {
|
||||
$_date = date('Y-m-d H:i:s', $_timestamp);//sql format
|
||||
$_query .= " AND `results`.`created` <= '{$_date}'";
|
||||
}
|
||||
}
|
||||
|
||||
if (!empty($params['product'])) {
|
||||
// product's come in looking like:
|
||||
// Mozilla Firefox 1.5.0.1
|
||||
$_exp = explode(' ',urldecode($params['product']));
|
||||
|
||||
if(count($_exp) == 3) {
|
||||
$_product = $_exp[0].' '.$_exp[1];
|
||||
|
||||
$_version = $_exp[2];
|
||||
|
||||
$_query .= " AND `applications`.`name` LIKE '{$_product}'";
|
||||
$_query .= " AND `applications`.`version` LIKE '{$_version}'";
|
||||
} else {
|
||||
// defaults I guess?
|
||||
$_query .= " AND `applications`.`name` LIKE 'Mozilla Firefox'";
|
||||
$_query .= " AND `applications`.`version` LIKE '1.5'";
|
||||
}
|
||||
} else {
|
||||
// I'm providing a default here, because otherwise all results will be
|
||||
// returned (across all applications) and that is not desired
|
||||
$_query .= " AND `applications`.`name` LIKE 'Mozilla Firefox'";
|
||||
$_query .= " AND `applications`.`version` LIKE '1.5'";
|
||||
}
|
||||
|
||||
$_query .= " ORDER BY `results`.`created` ASC";
|
||||
|
||||
$res = $this->query($_query);
|
||||
|
||||
// Since we're exporting to a CSV, we need to flatten the results into a 2
|
||||
// dimensional table array
|
||||
$newdata = array();
|
||||
|
||||
foreach ($res as $result) {
|
||||
|
||||
$newdata[] = array_merge($result['results'], $result['intentions']);
|
||||
}
|
||||
|
||||
if ($privacy) {
|
||||
// Pull out all the email addresses and phone numbers
|
||||
foreach ($newdata as $var => $val) {
|
||||
|
||||
// Handle foo@bar.com
|
||||
$_email_regex = '/\ ?(.+)?@(.+)?\.(.+)?\ ?/';
|
||||
$newdata[$var]['comments'] = preg_replace($_email_regex,'$1@****.$3',$newdata[$var]['comments']);
|
||||
$newdata[$var]['intention_other'] = preg_replace($_email_regex,'$1@****.$3',$newdata[$var]['intention_other']);
|
||||
|
||||
// Handle xxx-xxx-xxxx
|
||||
$_phone_regex = '/([0-9]{3})[ .-]?[0-9]{4}/';
|
||||
$newdata[$var]['comments'] = preg_replace($_phone_regex,'$1-****',$newdata[$var]['comments']);
|
||||
$newdata[$var]['intention_other'] = preg_replace($_phone_regex,'$1-****',$newdata[$var]['intention_other']);
|
||||
}
|
||||
}
|
||||
|
||||
// Our CSV library just prints out everything in order, so we have to put the
|
||||
// column labels on here ourselves
|
||||
$newdata = array_merge(array(array_keys($newdata[0])), $newdata);
|
||||
|
||||
return $newdata;
|
||||
}
|
||||
|
||||
/**
|
||||
* Will retrieve the information used for graphing.
|
||||
* @param the url parameters (unescaped)
|
||||
* @return a result set
|
||||
*/
|
||||
function getDescriptionAndTotalsData($params)
|
||||
{
|
||||
// Clean parameters for inserting into SQL
|
||||
$params = $this->cleanArrayForSql($params);
|
||||
|
||||
/* It would be nice to drop something like this in the SELECT:
|
||||
*
|
||||
* CONCAT(COUNT(*)/(SELECT COUNT(*) FROM our_giant_query_all_over_again)*100,'%') AS `percentage`
|
||||
*/
|
||||
|
||||
$_query = "
|
||||
SELECT
|
||||
issues.description,
|
||||
COUNT( DISTINCT results.id ) AS total
|
||||
FROM
|
||||
issues
|
||||
LEFT JOIN
|
||||
issues_results ON issues_results.issue_id=issues.id
|
||||
LEFT JOIN results ON results.id=issues_results.result_id AND results.application_id=applications.id
|
||||
JOIN applications_issues ON applications_issues.issue_id=issues.id
|
||||
JOIN applications ON applications.id=applications_issues.application_id
|
||||
WHERE 1=1
|
||||
";
|
||||
|
||||
if (!empty($params['start_date'])) {
|
||||
$_timestamp = strtotime($params['start_date']);
|
||||
|
||||
if (!($_timestamp == -1) || $_timestamp == false) {
|
||||
$_date = date('Y-m-d H:i:s', $_timestamp);//sql format
|
||||
$_query.= " AND `results`.`created` >= '{$_date}'";
|
||||
}
|
||||
}
|
||||
|
||||
if (!empty($params['end_date'])) {
|
||||
$_timestamp = strtotime($params['end_date']);
|
||||
|
||||
if (!($_timestamp == -1) || $_timestamp == false) {
|
||||
$_date = date('Y-m-d H:i:s', $_timestamp);//sql format
|
||||
$_query .= " AND `results`.`created` <= '{$_date}'";
|
||||
}
|
||||
}
|
||||
|
||||
if (!empty($params['product'])) {
|
||||
// product's come in looking like:
|
||||
// Mozilla Firefox 1.5.0.1
|
||||
$_exp = explode(' ',urldecode($params['product']));
|
||||
|
||||
if(count($_exp) == 3) {
|
||||
$_product = $_exp[0].' '.$_exp[1];
|
||||
|
||||
$_version = $_exp[2];
|
||||
|
||||
$_query .= " AND `applications`.`name` LIKE '{$_product}'";
|
||||
$_query .= " AND `applications`.`version` LIKE '{$_version}'";
|
||||
} else {
|
||||
// defaults I guess?
|
||||
$_query .= " AND `applications`.`name` LIKE 'Mozilla Firefox'";
|
||||
$_query .= " AND `applications`.`version` LIKE '1.5'";
|
||||
}
|
||||
} else {
|
||||
// I'm providing a default here, because otherwise all results will be
|
||||
// returned (across all applications) and that is not desired
|
||||
$_query .= " AND `applications`.`name` LIKE 'Mozilla Firefox'";
|
||||
$_query .= " AND `applications`.`version` LIKE '1.5'";
|
||||
}
|
||||
|
||||
$_query .= " GROUP BY `issues`.`description`
|
||||
ORDER BY `issues`.`description` DESC";
|
||||
|
||||
return $this->query($_query);
|
||||
}
|
||||
}
|
||||
?>
|
||||
@@ -1,188 +0,0 @@
|
||||
<?php
|
||||
/**
|
||||
* Functions that take a db result and export it to CSV.
|
||||
* Usage example:
|
||||
* <code>
|
||||
* if ($_GET['csv'])
|
||||
* {
|
||||
* $res=db_query("SELECT * FROM fic_courses");
|
||||
* csv_send_csv($res);
|
||||
* exit;
|
||||
* }
|
||||
* </code>
|
||||
* @package libs
|
||||
* @subpackage csv
|
||||
* @author Richard Faaberg <faabergr@onid.orst.edu>
|
||||
* @author Mike Morgan <mike.morgan@oregonstate.edu>
|
||||
*/
|
||||
|
||||
/**
|
||||
* Use a resource or two dimensional array, then send the CSV results to user.
|
||||
* @param mixed $res MySQL resource / result, or a two dimensional array
|
||||
* @param string $name name of the export file
|
||||
* @return bool true if file sent, false otherwise
|
||||
*/
|
||||
function csv_send_csv($res,$name=null)
|
||||
{
|
||||
// set name of the export file
|
||||
$filename=(is_null($name))?'export-'.date('Y-m-d').'.csv':$name.'.csv';
|
||||
// check for valid resource
|
||||
if ( is_resource($res) )
|
||||
{
|
||||
$csv=csv_export_to_csv($res);
|
||||
}
|
||||
elseif( is_array($res) && !empty($res) )
|
||||
{
|
||||
foreach ($res as $row)
|
||||
{
|
||||
if ( !is_array($row) )
|
||||
;
|
||||
else
|
||||
$csv[] = csv_array_to_csv($row)."\n";
|
||||
}
|
||||
}
|
||||
|
||||
if ( is_array($csv) )
|
||||
{
|
||||
// stream csv to user
|
||||
header("Content-type: application/x-csv");
|
||||
header('Content-disposition: inline; filename="'.$filename.'"');
|
||||
header('Cache-Control: private');
|
||||
header('Pragma: public');
|
||||
foreach ($csv as $row)
|
||||
{
|
||||
echo $row;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace quotes inside of a field with double quotes, which is something CSV requires.
|
||||
* @param string $string unquoted quotes
|
||||
* @return string $string quoted quotes
|
||||
*/
|
||||
function csv_fix_quotes($string)
|
||||
{
|
||||
return preg_replace('/"/','""',$string);
|
||||
}
|
||||
|
||||
/**
|
||||
* Replace line breaks with commas trailed by a space.
|
||||
* @param string $string string containing line breaks
|
||||
* @param string string without line breaks
|
||||
*/
|
||||
function csv_fix_line_breaks($string)
|
||||
{
|
||||
return preg_replace('/(\n\r|\r)/','\n',$string);
|
||||
}
|
||||
|
||||
/**
|
||||
* Replaces instances of double quotes in a string with a single quote.
|
||||
* @param string $string the string to perform the replacement on
|
||||
* @return string the string with "" replaced by "
|
||||
*/
|
||||
function csv_unfix_quotes($string)
|
||||
{
|
||||
return preg_replace('/""/', '"', $string);
|
||||
}
|
||||
|
||||
/**
|
||||
* Place quotes outside of every field, which inherently solves space, line break issues.
|
||||
* @param string $string
|
||||
* @return string $string with quotes around it
|
||||
*/
|
||||
function csv_add_quotes($string)
|
||||
{
|
||||
return '"'.$string.'"';
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes quotes from the beginning and the end of a string.
|
||||
* @param string $string the string to remove the quotes from
|
||||
* @return string the string, sans quotes at the beginning and end
|
||||
*/
|
||||
function csv_remove_quotes($string)
|
||||
{
|
||||
$pattern = "/^\"(.*)\"$/";
|
||||
$replacement = "$1";
|
||||
return preg_replace($pattern, $replacement, $string);
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert an array into a CSV string with quotes around each value.
|
||||
* @param array $array
|
||||
* @return string the values in $array surrounded by quotes and separated by commas
|
||||
*/
|
||||
function csv_array_to_csv($array)
|
||||
{
|
||||
$csv_arr = array();
|
||||
foreach ($array as $value)
|
||||
{
|
||||
$csv_arr[]=csv_add_quotes(csv_fix_quotes(csv_fix_line_breaks($value)));
|
||||
}
|
||||
$csv_string=implode(',',$csv_arr);
|
||||
|
||||
return $csv_string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert a CSV string into an array.
|
||||
* Please use sparingly - this creates temp files
|
||||
* @param string $string the CSV string
|
||||
* @return array the elements from the CSV string in an array
|
||||
*/
|
||||
function csv_csv_to_array($string)
|
||||
{
|
||||
$return = array();
|
||||
$length = strlen($string);
|
||||
|
||||
// create a temp file and write the string to it
|
||||
$tmpfname = tempnam('/tmp', 'csvlib');
|
||||
$fh = fopen($tmpfname, 'w');
|
||||
fwrite($fh, $string);
|
||||
fclose($fh);
|
||||
|
||||
// open the file for csv parsing
|
||||
$csvh = fopen($tmpfname, 'r');
|
||||
while (($arraydata = fgetcsv($csvh, $length, ',')) !== false)
|
||||
{
|
||||
$return = array_merge($return, $arraydata);
|
||||
}
|
||||
|
||||
fclose($csvh);
|
||||
unlink($tmpfname);
|
||||
|
||||
return $return;
|
||||
}
|
||||
|
||||
/**
|
||||
* Read a CSV file into a two dimensional array
|
||||
* It returns all the rows in the file, so if the first row are headers, you'd need to take care of that in the returned array
|
||||
* @param string $filepath the path to the csv file
|
||||
* @param string $delimiter delimiter, default to ','
|
||||
* @param string $enclosure enclosure character, default to '"'
|
||||
* @return &array the two dimensional array with the csv file content, or an empty if an error occured
|
||||
*/
|
||||
function &csv_csv_file_to_array($filepath, $delimiter=',', $enclosure='"')
|
||||
{
|
||||
$return = array();
|
||||
|
||||
if (!file_exists($filepath) || !is_readable($filepath))
|
||||
return $return;
|
||||
|
||||
$fh =& fopen($filepath, 'r');
|
||||
$size = filesize($filepath)+1;
|
||||
|
||||
while ($data =& fgetcsv($fh, $size, $delimiter, $enclosure))
|
||||
{
|
||||
$return[] = $data;
|
||||
}
|
||||
|
||||
fclose($fh);
|
||||
|
||||
return $return;
|
||||
}
|
||||
?>
|
||||
@@ -1,11 +0,0 @@
|
||||
<div id="t_footer">
|
||||
</div>
|
||||
|
||||
<!-- t_wrapper -->
|
||||
</div>
|
||||
|
||||
<!-- t_border -->
|
||||
</div>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,26 +0,0 @@
|
||||
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
|
||||
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
|
||||
<head>
|
||||
<title>Mozilla Uninstall Survey Data</title>
|
||||
<meta name="author" content="Mozilla Corporation" />
|
||||
<meta name="copyright" content="Mozilla Corporation" />
|
||||
<?php echo $html->charset('UTF-8'); ?>
|
||||
<?php echo $html->css('screen'); ?>
|
||||
<?php if (isset($include_graph_libraries) && $include_graph_libraries):
|
||||
echo $javascript->link('mochikit/MochiKit.js');
|
||||
echo $javascript->link('plotkit/Base.js');
|
||||
echo $javascript->link('plotkit/Layout.js');
|
||||
echo $javascript->link('plotkit/Canvas.js');
|
||||
echo $javascript->link('plotkit/SweetCanvas.js');
|
||||
endif; ?>
|
||||
</head>
|
||||
<body>
|
||||
<div id="t_border">
|
||||
<div id="t_wrapper">
|
||||
<a class="skipnav" href="#t_content">Skip Navigation Links</a>
|
||||
<div id="t_header">
|
||||
<div id="t_title">
|
||||
<h1>Mozilla Firefox Uninstall Survey Data</h1>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -1,6 +0,0 @@
|
||||
<div id="t_nav">
|
||||
<ul>
|
||||
<li><?php echo $html->link('Results', '/results'); ?></li>
|
||||
<li><?php echo $html->link('Comments', '/results/comments'); ?></li>
|
||||
</ul>
|
||||
</div>
|
||||
@@ -1,36 +0,0 @@
|
||||
<?php
|
||||
/**
|
||||
* When we're exporting data, we end up having to pass all the parameters
|
||||
* via $_GET. Since we're doing this a few times per page (each graph, and the
|
||||
* export hrefs) this helper should make that easier.
|
||||
*/
|
||||
class ExportHelper
|
||||
{
|
||||
/**
|
||||
* Method to collect the current $_GET parameters and build another string from
|
||||
* them.
|
||||
*
|
||||
* @param string cake URL that you want prepended to the result. eg: reports/graph/
|
||||
* @param array the array of GET variables to add. These need to be
|
||||
* pre-sanitized to print in html! This is designed to
|
||||
* be used from the calling controller like:
|
||||
* $params = $this->sanitize->html($url_parameters);
|
||||
* @param string string to put between url and arguments (probably either '?' or
|
||||
* '&')
|
||||
* @param array array of strings which will be ignored
|
||||
* @return string string with the url variables appeneded to it
|
||||
*/
|
||||
function buildUrlString($url, $params, $seperator='?', $ignore=array('url'))
|
||||
{
|
||||
$arguments = '';
|
||||
|
||||
foreach ($params as $var => $val) {
|
||||
if (!in_array($var, $ignore)) {
|
||||
$arguments .= empty($arguments) ? "{$var}={$val}" : "&{$var}={$val}";
|
||||
}
|
||||
}
|
||||
|
||||
return "{$url}{$seperator}{$arguments}";
|
||||
}
|
||||
}
|
||||
?>
|
||||
@@ -1,196 +0,0 @@
|
||||
<?php
|
||||
class PaginationHelper {
|
||||
|
||||
var $helpers = array('Html','Ajax');
|
||||
var $_pageDetails = array();
|
||||
var $link = '';
|
||||
var $show = array();
|
||||
var $page;
|
||||
var $style;
|
||||
|
||||
/**
|
||||
* Sets the default pagination options.
|
||||
*
|
||||
* @param array $paging an array detailing the page options
|
||||
*/
|
||||
function setPaging($paging)
|
||||
{
|
||||
if(!empty($paging))
|
||||
{
|
||||
|
||||
$this->link = $paging['link'];
|
||||
$this->show = $paging['show'];
|
||||
$this->page = $paging['page'];
|
||||
$this->style = $paging['style'];
|
||||
|
||||
$pageCount = ceil($paging['count'] / $paging['limit'] );
|
||||
|
||||
$this->_pageDetails = array(
|
||||
'page'=>$paging['page'],
|
||||
'recordCount'=>$paging['count'],
|
||||
'pageCount' =>$pageCount,
|
||||
'nextPage'=> ($paging['page'] < $pageCount) ? $paging['page']+1 : '',
|
||||
'previousPage'=> ($paging['page']>1) ? $paging['page']-1 : '',
|
||||
'limit'=>$paging['limit']
|
||||
);
|
||||
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
/**
|
||||
* Displays limits for the query
|
||||
*
|
||||
* @param string $text - text to display before limits
|
||||
* @param string $separator - display a separate between limits
|
||||
*
|
||||
**/
|
||||
function show($text=null, $separator=null)
|
||||
{
|
||||
if (empty($this->_pageDetails)) { return false; }
|
||||
if ( !empty($this->_pageDetails['recordCount']) )
|
||||
{
|
||||
$t = '';
|
||||
if(is_array($this->show))
|
||||
{
|
||||
$t = $text.$separator;
|
||||
foreach($this->show as $value)
|
||||
{
|
||||
$link = preg_replace('/show=(.*?)&/','show='.$value.'&',$this->link);
|
||||
if($this->_pageDetails['limit'] == $value)
|
||||
{
|
||||
$t .= '<em>'.$value.'</em>'.$separator;
|
||||
}
|
||||
else
|
||||
{
|
||||
if($this->style == 'ajax')
|
||||
{
|
||||
$t .= $this->Ajax->linkToRemote($value, array("fallback"=>$this->action."#","url" => $link.$this->_pageDetails['page'],"update" => "ajax_update","method"=>"get")).$separator;
|
||||
}
|
||||
else
|
||||
{
|
||||
$t .= $this->Html->link($value,$link.$this->_pageDetails['page']).$separator;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return $t;
|
||||
}
|
||||
return false;
|
||||
|
||||
}
|
||||
/**
|
||||
* Displays current result information
|
||||
*
|
||||
* @param string $text - text to preceeding the number of results
|
||||
*
|
||||
**/
|
||||
function result($text)
|
||||
{
|
||||
if (empty($this->_pageDetails)) { return false; }
|
||||
if ( !empty($this->_pageDetails['recordCount']) )
|
||||
{
|
||||
if($this->_pageDetails['recordCount'] > $this->_pageDetails['limit'])
|
||||
{
|
||||
$start_row = $this->_pageDetails['page'] > 1 ? (($this->_pageDetails['page']-1)*$this->_pageDetails['limit'])+1:'1';
|
||||
$end_row = ($this->_pageDetails['recordCount'] < ($start_row + $this->_pageDetails['limit']-1)) ? $this->_pageDetails['recordCount'] : ($start_row + $this->_pageDetails['limit']-1);
|
||||
$t = $text.$start_row.'-'.$end_row.' of '.$this->_pageDetails['recordCount'];
|
||||
}
|
||||
else
|
||||
{
|
||||
$t = $text.$this->_pageDetails['recordCount'];
|
||||
}
|
||||
return $t;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
/**
|
||||
* Returns a list of page numbers separated by $separator
|
||||
*
|
||||
* @param string $separator - defaults to null
|
||||
*
|
||||
**/
|
||||
function pageNumbers($separator=null)
|
||||
{
|
||||
if (empty($this->_pageDetails) || $this->_pageDetails['pageCount'] == 1) { return false; }
|
||||
$t = array();
|
||||
$text = '';
|
||||
$pc = 1;
|
||||
do
|
||||
{
|
||||
if($pc == $this->_pageDetails['page'])
|
||||
{
|
||||
$text = '<em>'.$pc.'</em>';
|
||||
}
|
||||
else
|
||||
{
|
||||
if($this->style == 'ajax')
|
||||
{
|
||||
$text = $this->Ajax->linkToRemote($pc, array("fallback"=>$this->action."#","url" =>$this->link.$pc,"update" => "ajax_update","method"=>"get"));
|
||||
}
|
||||
else
|
||||
{
|
||||
$text = $this->Html->link($pc,$this->link.$pc);
|
||||
}
|
||||
}
|
||||
|
||||
$t[] = $text;
|
||||
$pc++;
|
||||
}
|
||||
while ($pc<=$this->_pageDetails['pageCount']);
|
||||
|
||||
$t = implode($separator, $t);
|
||||
|
||||
return $t;
|
||||
}
|
||||
/**
|
||||
* Displays a link to the previous page, where the page doesn't exist then
|
||||
* display the $text
|
||||
*
|
||||
* @param string $text - text display: defaults to next
|
||||
*
|
||||
**/
|
||||
function prevPage($text='prev')
|
||||
{
|
||||
if (empty($this->_pageDetails)) { return false; }
|
||||
if ( !empty($this->_pageDetails['previousPage']) )
|
||||
{
|
||||
if($this->style == 'ajax')
|
||||
{
|
||||
$t = $this->Ajax->linkToRemote($text, array("fallback"=>$this->action."#","url" => $this->link.$this->_pageDetails['previousPage'],"update" => "ajax_update","method"=>"get"));
|
||||
}
|
||||
else
|
||||
{
|
||||
$t = $this->Html->link($text,$this->link.$this->_pageDetails['previousPage']);
|
||||
}
|
||||
return $t;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
/**
|
||||
* Displays a link to the next page, where the page doesn't exist then
|
||||
* display the $text
|
||||
*
|
||||
* @param string $text - text to display: defaults to next
|
||||
*
|
||||
**/
|
||||
function nextPage($text='next')
|
||||
{
|
||||
if (empty($this->_pageDetails)) { return false; }
|
||||
if (!empty($this->_pageDetails['nextPage']))
|
||||
{
|
||||
if($this->style == 'ajax')
|
||||
{
|
||||
$t = $this->Ajax->linkToRemote($text, array("fallback"=>$this->action."#","url" => $this->link.$this->_pageDetails['nextPage'],"update" => "ajax_update","method"=>"get"));
|
||||
}
|
||||
else
|
||||
{
|
||||
$t = $this->Html->link($text,$this->link.$this->_pageDetails['nextPage']);
|
||||
}
|
||||
return $t;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
}
|
||||
?>
|
||||
@@ -1,8 +0,0 @@
|
||||
<?php echo $this->renderElement( 'header' ); ?>
|
||||
<?php echo $this->renderElement( 'nav' ); ?>
|
||||
<div id="t_content_container">
|
||||
<div id="t_content">
|
||||
<?php echo $content_for_layout;?>
|
||||
</div>
|
||||
</div>
|
||||
<?php echo $this->renderElement( 'footer'); ?>
|
||||
@@ -1,51 +0,0 @@
|
||||
<h1><?php echo Inflector::humanize($this->name); ?></h1>
|
||||
|
||||
<div id="queryform">
|
||||
<?php echo $html->formTag('/results/comments/','get'); ?>
|
||||
<span>
|
||||
<label for="start_date">Start Date:</label>
|
||||
<input type="text" name="start_date" id="start_date" value="<? echo isset($url_params['start_date']) ? $url_params['start_date'] : ''; ?>" />
|
||||
<label for="end_date">End Date:</label>
|
||||
<input type="text" name="end_date" id="end_date" value="<? echo isset($url_params['end_date']) ? $url_params['end_date'] : ''; ?>" />
|
||||
</span>
|
||||
|
||||
<label for="product">Product:</label>
|
||||
<select name="product" id="product">
|
||||
<?php
|
||||
foreach ($products as $select) :
|
||||
$product = $select['applications']['name'].' '.$select['applications']['version'];
|
||||
$selected = ($product == trim($url_params['product'])) ? ' selected="selected" ' : '';
|
||||
?>
|
||||
<option<?=$selected?>><?=$product?></option>
|
||||
|
||||
<?php endforeach; ?>
|
||||
</select>
|
||||
|
||||
<input type="submit" name="submit" id="submit" value="Go" />
|
||||
</form>
|
||||
<br />
|
||||
<span><small>Date format is yyyy-mm-dd. A blank date will use the largest possible range.</small></span>
|
||||
</div>
|
||||
|
||||
<?php if (!empty($commentsData)) : ?>
|
||||
|
||||
<table class="comments" summary="User submitted comments.">
|
||||
<tr><th>Date Recorded</th><th>Comment</th></tr>
|
||||
<?php foreach ($commentsData as $var => $val) : ?>
|
||||
<tr><td><?php echo $time->niceShort($val['Result']['created']); ?></td><td><?php echo nl2br(htmlspecialchars($val['Result']['comments'])); ?></td></tr>
|
||||
<?php endforeach; ?>
|
||||
</table>
|
||||
|
||||
<?php if($pagination->setPaging($paging)):?>
|
||||
<ul id="page-numbers">
|
||||
<li><?php echo $pagination->show('Show ', ' '); ?></li>
|
||||
<li><?php echo $pagination->result('Results: '); ?></li>
|
||||
<li><?php echo $pagination->pageNumbers(' '); ?></li>
|
||||
</ul>
|
||||
<?php endif;?>
|
||||
|
||||
<?php else: ?>
|
||||
|
||||
<div id="notice">There is no data available for your parameters. Please review your search criteria.</div>
|
||||
|
||||
<?php endif; ?>
|
||||
@@ -1,91 +0,0 @@
|
||||
<h1><?php echo Inflector::humanize($this->name); ?></h1>
|
||||
|
||||
<div id="queryform">
|
||||
<?php echo $html->formTag('/results/','get'); ?>
|
||||
<span>
|
||||
<label for="start_date">Start Date:</label>
|
||||
<input type="text" name="start_date" id="start_date" value="<? echo isset($url_params['start_date']) ? $url_params['start_date'] : ''; ?>" />
|
||||
<label for="end_date">End Date:</label>
|
||||
<input type="text" name="end_date" id="end_date" value="<? echo isset($url_params['end_date']) ? $url_params['end_date'] : ''; ?>" />
|
||||
</span>
|
||||
|
||||
<label for="product">Product:</label>
|
||||
<select name="product" id="product">
|
||||
<?php
|
||||
foreach ($products as $select) :
|
||||
$product = $select['applications']['name'].' '.$select['applications']['version'];
|
||||
$selected = ($product == trim($url_params['product'])) ? ' selected="selected" ' : '';
|
||||
?>
|
||||
<option<?=$selected?>><?=$product?></option>
|
||||
|
||||
<?php endforeach; ?>
|
||||
</select>
|
||||
|
||||
<input type="submit" name="submit" id="submit" value="Go" />
|
||||
</form>
|
||||
<br />
|
||||
<span><small>Date format is yyyy-mm-dd. A blank date will use the largest possible range.</small></span>
|
||||
</div>
|
||||
|
||||
<?php if (!empty($descriptionAndTotalsData)) : ?>
|
||||
<?php
|
||||
/* Prepare data for graphing */
|
||||
$_dataset = '';
|
||||
$_count = 0;
|
||||
$_total = 0;
|
||||
/* We've got to do 2 loops here because I need the totals to calculate
|
||||
* percentages.
|
||||
*/
|
||||
foreach ($descriptionAndTotalsData as $var => $val) {
|
||||
$_total += $val[0]['total'];
|
||||
}
|
||||
foreach ($descriptionAndTotalsData as $var => $val) {
|
||||
// We're putting this in a js string, so escape the double quotes
|
||||
$_description = str_replace('"','\"',$val['issues']['description']);
|
||||
$_percentage = intval(($val[0]['total'] / $_total)*100);
|
||||
|
||||
$_dataset .= "[{$_count}, {$val[0]['total']}, \"{$_description} (n={$val[0]['total']}, {$_percentage}%)\"], ";
|
||||
$_count++;
|
||||
}
|
||||
$_dataset = "[{$_dataset}]";
|
||||
?>
|
||||
<div id="graphcontainer">
|
||||
<canvas id="graph" height="400" width="800">
|
||||
<table class="results" summary="Firefox Uninstallation results.">
|
||||
<tr><th>Reason for uninstalling</th><th>Total</th></tr>
|
||||
<?php foreach ($descriptionAndTotalsData as $var => $val) : ?>
|
||||
<tr><td><?=$val['issues']['description']?></td><td><?=$val[0]['total']?></td></tr>
|
||||
<?php endforeach; ?>
|
||||
</table>
|
||||
</canvas>
|
||||
</div>
|
||||
<script type="text/javascript">
|
||||
var layout = new PlotKit.Layout("bar", {"barOrientation":"horizontal"});
|
||||
layout.addDataset("results", <?=$_dataset?>);
|
||||
layout.evaluate();
|
||||
|
||||
var canvas = MochiKit.DOM.getElement("graph");
|
||||
var plotter = new PlotKit.SweetCanvasRenderer(canvas, layout,
|
||||
{
|
||||
"drawYAxis" : false,
|
||||
"drawXAxis" : false,
|
||||
"backgroundColor" : Color.fromHexString('#78c'),
|
||||
"strokeColor" : Color.fromHexString('#777'),
|
||||
"strokeWidth" : 1.0,
|
||||
"enableEvents" : false
|
||||
});
|
||||
|
||||
plotter.render();
|
||||
</script>
|
||||
|
||||
|
||||
<div id="exportbox">
|
||||
<a href="<?php echo $export->buildUrlString('results/comments/',$url_params); ?>">View Any Associated Comments»</a><br />
|
||||
<a href="<?php echo $export->buildUrlString('results/csv/',$url_params); ?>">Download this Data»</a>
|
||||
</div>
|
||||
|
||||
<?php else: ?>
|
||||
|
||||
<div id="notice">There is no data available for your parameters. Please review your search criteria.</div>
|
||||
|
||||
<?php endif; ?>
|
||||
@@ -1,6 +0,0 @@
|
||||
<IfModule mod_rewrite.c>
|
||||
RewriteEngine On
|
||||
RewriteCond %{REQUEST_FILENAME} !-d
|
||||
RewriteCond %{REQUEST_FILENAME} !-f
|
||||
RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]
|
||||
</IfModule>
|
||||
@@ -1,116 +0,0 @@
|
||||
<?php
|
||||
/* SVN FILE: $Id: css.php,v 1.1.1.1 2006-05-24 19:14:24 uid815 Exp $ */
|
||||
|
||||
/**
|
||||
* Short description for file.
|
||||
*
|
||||
* Long description for file
|
||||
*
|
||||
* PHP versions 4 and 5
|
||||
*
|
||||
* CakePHP : Rapid Development Framework <http://www.cakephp.org/>
|
||||
* Copyright (c) 2006, Cake Software Foundation, Inc.
|
||||
* 1785 E. Sahara Avenue, Suite 490-204
|
||||
* Las Vegas, Nevada 89104
|
||||
*
|
||||
* Licensed under The MIT License
|
||||
* Redistributions of files must retain the above copyright notice.
|
||||
*
|
||||
* @filesource
|
||||
* @copyright Copyright (c) 2006, Cake Software Foundation, Inc.
|
||||
* @link http://www.cakefoundation.org/projects/info/cakephp CakePHP Project
|
||||
* @package cake
|
||||
* @subpackage cake.app.webroot
|
||||
* @since CakePHP v 0.2.9
|
||||
* @version $Revision: 1.1.1.1 $
|
||||
* @modifiedby $LastChangedBy: phpnut $
|
||||
* @lastmodified $Date: 2006-05-24 19:14:24 $
|
||||
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
|
||||
*/
|
||||
|
||||
/**
|
||||
* Enter description here...
|
||||
*/
|
||||
require(CONFIGS.'paths.php');
|
||||
require(CAKE.'basics.php');
|
||||
require(LIBS.'folder.php');
|
||||
require(LIBS.'file.php');
|
||||
require(LIBS.'legacy.php');
|
||||
|
||||
/**
|
||||
* Enter description here...
|
||||
*
|
||||
* @param unknown_type $path
|
||||
* @param unknown_type $name
|
||||
* @return unknown
|
||||
*/
|
||||
function make_clean_css ($path, $name)
|
||||
{
|
||||
require(VENDORS.'csspp'.DS.'csspp.php');
|
||||
|
||||
$data = file_get_contents($path);
|
||||
$csspp = new csspp();
|
||||
$output = $csspp->compress($data);
|
||||
|
||||
$ratio = 100-(round(strlen($output)/strlen($data), 3)*100);
|
||||
$output = " /* file: $name, ratio: $ratio% */ " . $output;
|
||||
|
||||
return $output;
|
||||
}
|
||||
|
||||
/**
|
||||
* Enter description here...
|
||||
*
|
||||
* @param unknown_type $path
|
||||
* @param unknown_type $content
|
||||
* @return unknown
|
||||
*/
|
||||
function write_css_cache ($path, $content)
|
||||
{
|
||||
if (!is_dir(dirname($path)))
|
||||
mkdir(dirname($path));
|
||||
|
||||
$cache = new File($path);
|
||||
return $cache->write($content);
|
||||
}
|
||||
|
||||
if (preg_match('|\.\.|', $url) || !preg_match('|^ccss/(.+)$|i', $url, $regs))
|
||||
die('Wrong file name.');
|
||||
|
||||
$filename = 'css/'.$regs[1];
|
||||
$filepath = CSS.$regs[1];
|
||||
$cachepath = CACHE.'css'.DS.str_replace(array('/','\\'), '-', $regs[1]);
|
||||
|
||||
if (!file_exists($filepath))
|
||||
die('Wrong file name.');
|
||||
|
||||
|
||||
if (file_exists($cachepath))
|
||||
{
|
||||
$templateModified = filemtime($filepath);
|
||||
$cacheModified = filemtime($cachepath);
|
||||
|
||||
if ($templateModified > $cacheModified)
|
||||
{
|
||||
$output = make_clean_css ($filepath, $filename);
|
||||
write_css_cache ($cachepath, $output);
|
||||
}
|
||||
else
|
||||
{
|
||||
$output = file_get_contents($cachepath);
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
$output = make_clean_css ($filepath, $filename);
|
||||
write_css_cache ($cachepath, $output);
|
||||
}
|
||||
|
||||
header("Date: ".date("D, j M Y G:i:s ", $templateModified).'GMT');
|
||||
header("Content-Type: text/css");
|
||||
header("Expires: ".gmdate("D, j M Y H:i:s", time()+DAY)." GMT");
|
||||
header("Cache-Control: cache");// HTTP/1.1
|
||||
header("Pragma: cache");// HTTP/1.0
|
||||
print $output;
|
||||
|
||||
?>
|
||||
@@ -1,195 +0,0 @@
|
||||
/* CSS Document */
|
||||
@import url("cake.forms.css");
|
||||
|
||||
* {
|
||||
padding:0;
|
||||
margin:0;
|
||||
}
|
||||
body {
|
||||
font: 76% Verdana, Arial, Sans-serif;
|
||||
color: #333;
|
||||
}
|
||||
img {
|
||||
border:0;
|
||||
}
|
||||
#wrapper {
|
||||
text-align:left;
|
||||
}
|
||||
#header {
|
||||
height: 101px;
|
||||
background: #0D5087 url(../img/cake.header_bg.png) repeat-x left top;
|
||||
border-bottom: 1px solid #000;
|
||||
}
|
||||
#content {
|
||||
min-height:400px;
|
||||
background-color: #fff;
|
||||
padding:2em 4em;
|
||||
}
|
||||
#footer {
|
||||
text-align:center;
|
||||
padding:1em 0;
|
||||
font-size:smaller;
|
||||
border-top:1px solid #333;
|
||||
background-color: #063260;
|
||||
color:#fff;
|
||||
line-height:1.5;
|
||||
}
|
||||
#footer a {
|
||||
color:#fff;
|
||||
}
|
||||
|
||||
h1, h2, h3, h4 {
|
||||
padding-bottom:0.5em;
|
||||
}
|
||||
h1 {
|
||||
font-family:"Trebuchet MS",Verdana,Arial,Sans-serif;
|
||||
}
|
||||
h1, a {
|
||||
color:#DB8101;
|
||||
}
|
||||
h1 em, a em {
|
||||
color:#008BCC;
|
||||
font-style: normal;
|
||||
}
|
||||
ul.colored a em
|
||||
h2 {
|
||||
font-style: italic;
|
||||
font-weight: bold;
|
||||
color:#666;
|
||||
}
|
||||
a:hover, a:hover em {
|
||||
color:#A22424;
|
||||
text-decoration:none;
|
||||
}
|
||||
#content p, #content ul, #content ol {
|
||||
line-height:1.5;
|
||||
padding-bottom:1em;
|
||||
}
|
||||
ul, ol {
|
||||
margin-left:3em;
|
||||
}
|
||||
|
||||
/* tables */
|
||||
|
||||
table {
|
||||
width: 100%;
|
||||
background-color: #fff;
|
||||
border: 1px solid #333;
|
||||
clear:both;
|
||||
margin: 0 0 2em 0;
|
||||
white-space: normal;
|
||||
}
|
||||
th {
|
||||
background-color: #ccc;
|
||||
border-top: 1px solid #fff;
|
||||
border-right: 1px solid #666;
|
||||
border-bottom: 1px solid #666;
|
||||
text-align: center;
|
||||
padding:3px;
|
||||
}
|
||||
table tr td {
|
||||
border-right: 1px solid #ccc;
|
||||
padding:4px 4px;
|
||||
vertical-align:top;
|
||||
text-align: center;
|
||||
}
|
||||
table tr.altRow td {
|
||||
background: #f4f4f4;
|
||||
}
|
||||
|
||||
/* scaffold show */
|
||||
|
||||
|
||||
div.related {
|
||||
clear:both;
|
||||
display:block;
|
||||
}
|
||||
dl {
|
||||
line-height:2em;
|
||||
margin:1em;
|
||||
}
|
||||
dt {
|
||||
font-weight: bold;
|
||||
vertical-align:top;
|
||||
}
|
||||
dd {
|
||||
margin-left:10em;
|
||||
margin-top:-2em;
|
||||
vertical-align:top;
|
||||
}
|
||||
|
||||
/* scaffold buttons */
|
||||
|
||||
|
||||
.notice {
|
||||
color: #DB8101;
|
||||
background-color: #ddd;
|
||||
display: block;
|
||||
padding: 1em;
|
||||
}
|
||||
.tip {
|
||||
color: #DB8101;
|
||||
background-color: #ddd;
|
||||
display: block;
|
||||
padding: 1em;
|
||||
}
|
||||
|
||||
ul.actions {
|
||||
list-style: none;
|
||||
text-align:left;
|
||||
margin:2em 0;
|
||||
padding: 0;
|
||||
}
|
||||
ul.actions li {
|
||||
margin-left:1em;
|
||||
list-style: none;
|
||||
display: inline;
|
||||
}
|
||||
ul.actions li a, ul.actions li input {
|
||||
padding: 2px 12px;
|
||||
color: #DB8101;
|
||||
background-color:#ccc;
|
||||
text-decoration: none;
|
||||
border: 1px solid #666;
|
||||
line-height: 24px;
|
||||
font-weight: bold;
|
||||
text-align:center;
|
||||
text-decoration: none;
|
||||
}
|
||||
ul.actions li a:hover {
|
||||
color: #DB8101;
|
||||
background-color:#fff;
|
||||
text-decoration: none;
|
||||
}
|
||||
td.listactions {
|
||||
width: 14em;
|
||||
text-align: center;
|
||||
white-space: nowrap;
|
||||
}
|
||||
td.listactions a {
|
||||
padding: 0px 8px;
|
||||
text-align:center;
|
||||
font-weight: bold;
|
||||
color: #DB8101;
|
||||
background-color:#ccc;
|
||||
text-decoration: none;
|
||||
border: 1px solid #666;
|
||||
white-space: nowrap;
|
||||
}
|
||||
td.listactions a:hover {
|
||||
color: #fff;
|
||||
background-color:#DB8101;
|
||||
}
|
||||
|
||||
/* index links */
|
||||
|
||||
ul.colored a {
|
||||
|
||||
}
|
||||
ul.colored a em {
|
||||
|
||||
}
|
||||
|
||||
a {
|
||||
font-weight: bold;
|
||||
}
|
||||
@@ -1,279 +0,0 @@
|
||||
/* form.css */
|
||||
|
||||
form {
|
||||
margin: 0 4px;
|
||||
font-size: 120%;
|
||||
border-width: 0px 0px 0px 0px;
|
||||
border-style: solid;
|
||||
border-color: #DB8101;
|
||||
}
|
||||
|
||||
form fieldset {
|
||||
font-size: 100%;
|
||||
border-color: #000000;
|
||||
border-width: 1px 0px 0px 0px;
|
||||
border-style: solid none none none;
|
||||
padding: 10px;
|
||||
}
|
||||
|
||||
form fieldset legend {
|
||||
font-size: 150%;
|
||||
font-weight: normal;
|
||||
color: #000;
|
||||
padding: 0px 5px;
|
||||
}
|
||||
|
||||
label {
|
||||
font-size: 150%;
|
||||
}
|
||||
|
||||
label u {
|
||||
font-style: normal;
|
||||
text-decoration: underline;
|
||||
}
|
||||
|
||||
input, select, textarea {
|
||||
font-family: Tahoma, Arial, sans-serif;
|
||||
font-size: 100%;
|
||||
color: #000;
|
||||
}
|
||||
|
||||
textarea {
|
||||
overflow: auto;
|
||||
}
|
||||
|
||||
form div {
|
||||
clear: left;
|
||||
display: block;
|
||||
margin: 5px 0px 0px 0px;
|
||||
padding: 1px 3px;
|
||||
}
|
||||
|
||||
form fieldset div.notes {
|
||||
float: right;
|
||||
width: 158px;
|
||||
height: auto;
|
||||
margin: 0px 0px 10px 10px;
|
||||
padding: 5px;
|
||||
border: 1px solid #666;
|
||||
background-color: #ffffe1;
|
||||
color: #666;
|
||||
font-size: 88%;
|
||||
}
|
||||
|
||||
form fieldset div.notes h4 {
|
||||
background-image: url(/images/icon_info.gif);
|
||||
background-repeat: no-repeat;
|
||||
background-position: top left;
|
||||
padding: 3px 0px 3px 27px;
|
||||
border-width: 0px 0px 1px 0px;
|
||||
border-style: solid;
|
||||
border-color: #666;
|
||||
color: #666;
|
||||
font-size: 110%;
|
||||
}
|
||||
|
||||
form fieldset div.notes p {
|
||||
margin: 0em 0em 1.2em 0em;
|
||||
color: #666;
|
||||
}
|
||||
|
||||
form fieldset div.notes p.last {
|
||||
margin: 0em;
|
||||
}
|
||||
|
||||
form div fieldset {
|
||||
clear: none;
|
||||
border-width: 0px 1px 0px 1px;
|
||||
border-style: solid;
|
||||
border-color: #666;
|
||||
margin: 0px 0px 0px 142px;
|
||||
padding: 0px 5px 5px 5px;
|
||||
}
|
||||
|
||||
form div fieldset legend {
|
||||
font-size: 100%;
|
||||
padding: 0px 3px 0px 9px;
|
||||
}
|
||||
|
||||
form div.required fieldset legend {
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
form div label {
|
||||
display: block;
|
||||
float: left;
|
||||
width: 200px;
|
||||
background-color: #f4f4f4;
|
||||
font-size: 16px;
|
||||
padding: 3px 5px;
|
||||
margin: 0px 0px 5px 0px;
|
||||
text-align: right;
|
||||
}
|
||||
|
||||
form div.optional label, label.optional {
|
||||
font-weight: normal;
|
||||
}
|
||||
|
||||
form div.required label, label.required {
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
form div label.labelCheckbox, form div label.labelRadio {
|
||||
float: none;
|
||||
display: block;
|
||||
margin: 0px 0px 5px 142px;
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
form div fieldset label.labelCheckbox, form div fieldset label.labelRadio {
|
||||
margin: 0px 0px 5px 0px;
|
||||
}
|
||||
p.error {
|
||||
color: #DB8101;
|
||||
background-color: #DBA941;
|
||||
font-size: 14px;
|
||||
padding: 1em;
|
||||
}
|
||||
|
||||
form div input, form div select, form div textarea {
|
||||
padding: 1px 3px;
|
||||
margin: 0px 0px 0px 0px;
|
||||
}
|
||||
|
||||
form div input.inputFile {
|
||||
width: 211px;
|
||||
}
|
||||
|
||||
form div select.selectOne, form div select.selectMultiple {
|
||||
width: 211px;
|
||||
padding: 1px 3px;
|
||||
}
|
||||
|
||||
form div input.inputCheckbox, form div input.inputRadio, input.inputCheckbox, input.inputRadio {
|
||||
display: inline;
|
||||
height: 14px;
|
||||
width: 14px;
|
||||
background-color: transparent;
|
||||
border-width: 0px;
|
||||
}
|
||||
|
||||
form div.submit {
|
||||
padding: 0px 0px 0px 140px;
|
||||
clear:both;
|
||||
display:block;
|
||||
}
|
||||
|
||||
div.submit input {
|
||||
padding: 2px 12px;
|
||||
color: #DB8101;
|
||||
background-color:#ccc;
|
||||
text-decoration: none;
|
||||
border: 1px solid #666;
|
||||
font-size: 14px;
|
||||
font-weight: bold;
|
||||
text-align:center;
|
||||
text-decoration: none;
|
||||
width: auto;
|
||||
}
|
||||
div.submit input:hover {
|
||||
padding: 2px 12px;
|
||||
color: #fff;
|
||||
background-color:#DB8101;
|
||||
text-decoration: none;
|
||||
border: 1px solid #666;
|
||||
font-size: 14px;
|
||||
font-weight: bold;
|
||||
text-align:center;
|
||||
text-decoration: none;
|
||||
width: auto;
|
||||
}
|
||||
|
||||
form div.submit div input.inputSubmit, form div.submit div input.inputButton {
|
||||
float: right;
|
||||
margin: 0px 0px 0px 5px;
|
||||
}
|
||||
|
||||
form div small {
|
||||
display: block;
|
||||
margin: 0px 0px 5px 142px;
|
||||
padding: 1px 3px;
|
||||
font-size: 88%;
|
||||
}
|
||||
|
||||
/* form.import.css */
|
||||
|
||||
form fieldset legend {
|
||||
line-height: 150%;
|
||||
}
|
||||
|
||||
form input, form select, form textarea {
|
||||
background-color: #fff;
|
||||
}
|
||||
|
||||
div.optional label:before {
|
||||
content: '';
|
||||
}
|
||||
|
||||
div.required label:before {
|
||||
content: '';
|
||||
}
|
||||
|
||||
form div label.labelCheckbox, form div label.labelRadio, label.labelCheckbox, label.labelRadio {
|
||||
display: block;
|
||||
width: 190px;
|
||||
padding: 4px 0px 0px 18px;
|
||||
text-indent: -18px;
|
||||
line-height: 120%;
|
||||
}
|
||||
|
||||
form div label.labelCheckbox input.inputCheckbox, form div label.labelRadio input.inputRadio, label.labelCheckbox input.inputCheckbox, label.labelRadio input.inputRadio {
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
form div fieldset input.inputText, form div fieldset input.inputPassword, form div fieldset input.inputFile, form div fieldset textarea.inputTextarea {
|
||||
width: 160px;
|
||||
margin: 0px 0px 0px 18px;
|
||||
}
|
||||
|
||||
form div label.compact {
|
||||
display: inline;
|
||||
width: auto;
|
||||
padding: 4px 10px 0px 0px;
|
||||
text-indent: 0px;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
form div.wide label {
|
||||
float: none;
|
||||
display: block;
|
||||
}
|
||||
|
||||
form div label.wide {
|
||||
width: 348px;
|
||||
}
|
||||
|
||||
form div.wide input.inputText, form div.wide input.inputPassword, form div.wide input.inputFile, form div.wide select, form div.wide textarea {
|
||||
width: 344px;
|
||||
margin: 0;
|
||||
}
|
||||
|
||||
form div.notes p, form div small {
|
||||
line-height: 125%;
|
||||
}
|
||||
|
||||
form div.wide small {
|
||||
margin: 0px 0px 5px 0px;
|
||||
}
|
||||
|
||||
div.date select {
|
||||
width:auto;
|
||||
}
|
||||
|
||||
select.autoWidth {
|
||||
width:auto;
|
||||
}
|
||||
|
||||
option {
|
||||
padding-left:1em;
|
||||
}
|
||||
@@ -1,9 +0,0 @@
|
||||
form div,
|
||||
form div label.labelCheckbox, form div label.labelRadio,
|
||||
form div small,
|
||||
form div label.labelCheckbox, form div label.labelRadio, label.labelCheckbox, label.labelRadio {
|
||||
height: expression('1%');
|
||||
}
|
||||
form div fieldset input.inputText, form div fieldset input.inputPassword, form div fieldset input.inputFile, form div fieldset textarea.inputTextarea {
|
||||
margin: expression('0px 0px 0px -124px');
|
||||
}
|
||||
@@ -1,133 +0,0 @@
|
||||
/* Screen Stylesheet */
|
||||
|
||||
/* This is temporary while we use the scaffolding */
|
||||
@import url("cake.default.css");
|
||||
table { clear:none; }
|
||||
|
||||
/* CORE STYLES */
|
||||
|
||||
body{
|
||||
background-color:#788;
|
||||
}
|
||||
div#t_title{
|
||||
background-color:#ddd;
|
||||
height:50px;
|
||||
padding-left:8px;
|
||||
}
|
||||
div#t_title h1{
|
||||
font-size:1.7em;
|
||||
padding-top:10px;
|
||||
color:#677;
|
||||
}
|
||||
div#t_content_container{
|
||||
}
|
||||
div#t_content{
|
||||
padding: 20px 10px 100px 10px;
|
||||
margin-left:151px;
|
||||
background-image:url('../img/bg.jpg');
|
||||
background-position:bottom right;
|
||||
background-repeat:no-repeat;
|
||||
min-height:200px;
|
||||
}
|
||||
div#t_wrapper{
|
||||
margin:0px;
|
||||
padding:0px;
|
||||
background-color:#fff;
|
||||
}
|
||||
|
||||
div#t_border{
|
||||
border-left:1px solid #111;
|
||||
border-right:1px solid #111;
|
||||
border-bottom:1px solid #111;
|
||||
margin:0px 30px 0px 30px;
|
||||
}
|
||||
|
||||
div#t_nav {
|
||||
padding:20px 0px 50px 0px;
|
||||
float:left;
|
||||
width:151px;
|
||||
}
|
||||
div#t_nav ul {
|
||||
list-style-type:none;
|
||||
padding:2px 0px 0px 0px;
|
||||
margin:0px;
|
||||
}
|
||||
div#t_nav ul li{
|
||||
padding:2px 0px 2px 0px;
|
||||
}
|
||||
div#t_nav ul li a{
|
||||
text-decoration:none;
|
||||
font-size:.8em;
|
||||
padding:6px 0px 6px 8px;
|
||||
margin:0px 0px 0px 0px;
|
||||
color:#566;
|
||||
border:none;
|
||||
}
|
||||
div#t_nav ul li a:hover{
|
||||
color:#f80;
|
||||
}
|
||||
div#t_nav h3 {
|
||||
padding:5px 0px 0px 5px;
|
||||
font-size:.9em;
|
||||
}
|
||||
div#t_footer {
|
||||
clear:both;
|
||||
border-top:1px solid #111;
|
||||
}
|
||||
|
||||
div#t_content h1 {
|
||||
margin-bottom:100px;
|
||||
font-size:1.6em;
|
||||
}
|
||||
|
||||
a.skipnav {
|
||||
position:absolute;
|
||||
visibility:hidden;
|
||||
}
|
||||
|
||||
div#queryform {
|
||||
margin: 5px 20px 5px 20px;
|
||||
padding-bottom:20px;
|
||||
width:700px;
|
||||
}
|
||||
div#queryform label {
|
||||
font-size:.8em;
|
||||
font-weight:bold;
|
||||
}
|
||||
div#queryform input[type="text"]{
|
||||
width:7em;
|
||||
}
|
||||
|
||||
div#exportbox {
|
||||
}
|
||||
|
||||
/* Classes for graph/table data. (Generally just padding) */
|
||||
.results {
|
||||
padding: 5px 5px 5px 5px;
|
||||
margin: 5px 5px 5px 5px;
|
||||
}
|
||||
|
||||
div#notice {
|
||||
background-color:#ecc;
|
||||
border:1px dashed #daa;
|
||||
text-align:center;
|
||||
padding:6px 6px 6px 6px;
|
||||
margin:6px 20px 6px 20px;
|
||||
}
|
||||
|
||||
table.comments tr {
|
||||
}
|
||||
|
||||
table.comments tr td{
|
||||
text-align:left;
|
||||
border-bottom: 1px solid #222;
|
||||
}
|
||||
|
||||
div.bar_chart_label {
|
||||
position: absolute;
|
||||
text-align: left;
|
||||
font-size: small;
|
||||
color: #fff;
|
||||
overflow: hidden;
|
||||
z-index: 10;
|
||||
}
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 4.2 KiB |
Binary file not shown.
|
Before Width: | Height: | Size: 6.2 KiB |
@@ -1 +0,0 @@
|
||||
deny from all
|
||||
@@ -1,244 +0,0 @@
|
||||
2006-04-29 v1.3.1 (bug fix release)
|
||||
|
||||
- Fix sendXMLHttpRequest sendContent regression
|
||||
- Internet Explorer fix in MochiKit.Logging (printfire exception)
|
||||
- Internet Explorer XMLHttpRequest object leak fixed in MochiKit.Async
|
||||
|
||||
2006-04-26 v1.3 "warp zone"
|
||||
|
||||
- IMPORTANT: Renamed MochiKit.Base.forward to forwardCall (for export)
|
||||
- IMPORTANT: Renamed MochiKit.Base.find to findValue (for export)
|
||||
- New MochiKit.Base.method as a convenience form of bind that takes the
|
||||
object before the method
|
||||
- New MochiKit.Base.flattenArguments for flattening a list of arguments to
|
||||
a single Array
|
||||
- Refactored MochiRegExp example to use MochiKit.Signal
|
||||
- New key_events example demonstrating use of MochiKit.Signal's key handling
|
||||
capabilities.
|
||||
- MochiKit.DOM.createDOM API change for convenience: if attrs is a string,
|
||||
null is used and the string will be considered the first node. This
|
||||
allows for the more natural P("foo") rather than P(null, "foo").
|
||||
- MochiKit Interpreter example refactored to use MochiKit.Signal and now
|
||||
provides multi-line input and a help() function to get MochiKit function
|
||||
signature from the documentation.
|
||||
- Native Console Logging for the default MochiKit.Logging logger
|
||||
- New MochiKit.Async.DeferredList, gatherResults, maybeDeferred
|
||||
- New MochiKit.Signal example: draggable
|
||||
- Added sanity checking to Deferred to ensure that errors happen when chaining
|
||||
is used incorrectly
|
||||
- Opera sendXMLHttpRequest fix (sends empty string instead of null by default)
|
||||
- Fix a bug in MochiKit.Color that incorrectly generated hex colors for
|
||||
component values smaller than 16/255.
|
||||
- Fix a bug in MochiKit.Logging that prevented logs from being capped at a
|
||||
maximum size
|
||||
- MochiKit.Async.Deferred will now wrap thrown objects that are not instanceof
|
||||
Error, so that the errback chain is used instead of the callback chain.
|
||||
- MochiKit.DOM.appendChildNodes and associated functions now append iterables
|
||||
in the correct order.
|
||||
- New MochiKit-based SimpleTest test runner as a replacement for Test.Simple
|
||||
- MochiKit.Base.isNull no longer matches undefined
|
||||
- example doctypes changed to HTML4
|
||||
- isDateLike no longer throws error on null
|
||||
- New MochiKit.Signal module, modeled after the slot/signal mechanism in Qt
|
||||
- updated elementDimensions to calculate width from offsetWidth instead
|
||||
of clientWidth
|
||||
- formContents now works with FORM tags that have a name attribute
|
||||
- Documentation now uses MochiKit to generate a function index
|
||||
|
||||
2006-01-26 v1.2 "the ocho"
|
||||
|
||||
- Fixed MochiKit.Color.Color.lighterColorWithLevel
|
||||
- Added new MochiKit.Base.findIdentical function to find the index of an
|
||||
element in an Array-like object. Uses === for identity comparison.
|
||||
- Added new MochiKit.Base.find function to find the index of an element in
|
||||
an Array-like object. Uses compare for rich comparison.
|
||||
- MochiKit.Base.bind will accept a string for func, which will be immediately
|
||||
looked up as self[func].
|
||||
- MochiKit.DOM.formContents no longer skips empty form elements for Zope
|
||||
compatibility
|
||||
- MochiKit.Iter.forEach will now catch StopIteration to break
|
||||
- New MochiKit.DOM.elementDimensions(element) for determining the width and
|
||||
height of an element in the document
|
||||
- MochiKit.DOM's initialization is now compatible with
|
||||
HTMLUnit + JWebUnit + Rhino
|
||||
- MochiKit.LoggingPane will now re-use a ``_MochiKit_LoggingPane`` DIV element
|
||||
currently in the document instead of always creating one.
|
||||
- MochiKit.Base now has operator.mul
|
||||
- MochiKit.DOM.formContents correctly handles unchecked checkboxes that have
|
||||
a custom value attribute
|
||||
- Added new MochiKit.Color constructors fromComputedStyle and fromText
|
||||
- MochiKit.DOM.setNodeAttribute should work now
|
||||
- MochiKit.DOM now has a workaround for an IE bug when setting the style
|
||||
property to a string
|
||||
- MochiKit.DOM.createDOM now has workarounds for IE bugs when setting the
|
||||
name and for properties
|
||||
- MochiKit.DOM.scrapeText now walks the DOM tree in-order
|
||||
- MochiKit.LoggingPane now sanitizes the window name to work around IE bug
|
||||
- MochiKit.DOM now translates usemap to useMap to work around IE bug
|
||||
- MochiKit.Logging is now resistant to Prototype's dumb Object.prototype hacks
|
||||
- Added new MochiKit.DOM documentation on element visibility
|
||||
- New MochiKit.DOM.elementPosition(element[, relativeTo={x: 0, y: 0}])
|
||||
for determining the position of an element in the document
|
||||
- Added new MochiKit.DOM createDOMFunc aliases: CANVAS, STRONG
|
||||
|
||||
2005-11-14 v1.1
|
||||
|
||||
- Fixed a bug in numberFormatter with large numbers
|
||||
- Massively overhauled documentation
|
||||
- Fast-path for primitives in MochiKit.Base.compare
|
||||
- New groupby and groupby_as_array in MochiKit.Iter
|
||||
- Added iterator factory adapter for objects that implement iterateNext()
|
||||
- Fixed isoTimestamp to handle timestamps with time zone correctly
|
||||
- Added new MochiKit.DOM createDOMFunc aliases: SELECT, OPTION, OPTGROUP,
|
||||
LEGEND, FIELDSET
|
||||
- New MochiKit.DOM formContents and enhancement to queryString to support it
|
||||
- Updated view_source example to use dp.SyntaxHighlighter 1.3.0
|
||||
- MochiKit.LoggingPane now uses named windows based on the URL so that
|
||||
a given URL will get the same LoggingPane window after a reload
|
||||
(at the same position, etc.)
|
||||
- MochiKit.DOM now has currentWindow() and currentDocument() context
|
||||
variables that are set with withWindow() and withDocument(). These
|
||||
context variables affect all MochiKit.DOM functionality (getElement,
|
||||
createDOM, etc.)
|
||||
- MochiKit.Base.items will now catch and ignore exceptions for properties
|
||||
that are enumerable but not accessible (e.g. permission denied)
|
||||
- MochiKit.Async.Deferred's addCallback/addErrback/addBoth
|
||||
now accept additional arguments that are used to create a partially
|
||||
applied function. This differs from Twisted in that the callback/errback
|
||||
result becomes the *last* argument, not the first when this feature
|
||||
is used.
|
||||
- MochiKit.Async's doSimpleXMLHttpRequest will now accept additional
|
||||
arguments which are used to create a GET query string
|
||||
- Did some refactoring to reduce the footprint of MochiKit by a few
|
||||
kilobytes
|
||||
- escapeHTML to longer escapes ' (apos) and now uses
|
||||
String.replace instead of iterating over every char.
|
||||
- Added DeferredLock to Async
|
||||
- Renamed getElementsComputedStyle to computedStyle and moved
|
||||
it from MochiKit.Visual to MochiKit.DOM
|
||||
- Moved all color support out of MochiKit.Visual and into MochiKit.Color
|
||||
- Fixed range() to accept a negative step
|
||||
- New alias to MochiKit.swapDOM called removeElement
|
||||
- New MochiKit.DOM.setNodeAttribute(node, attr, value) which sets
|
||||
an attribute on a node without raising, roughly equivalent to:
|
||||
updateNodeAttributes(node, {attr: value})
|
||||
- New MochiKit.DOM.getNodeAttribute(node, attr) which gets the value of
|
||||
a node's attribute or returns null without raising
|
||||
- Fixed a potential IE memory leak if using MochiKit.DOM.addToCallStack
|
||||
directly (addLoadEvent did not leak, since it clears the handler)
|
||||
|
||||
2005-10-24 v1.0
|
||||
|
||||
- New interpreter example that shows usage of MochiKit.DOM to make
|
||||
an interactive JavaScript interpreter
|
||||
- New MochiKit.LoggingPane for use with the MochiKit.Logging
|
||||
debuggingBookmarklet, with logging_pane example to show its usage
|
||||
- New mochiregexp example that demonstrates MochiKit.DOM and MochiKit.Async
|
||||
in order to provide a live regular expression matching tool
|
||||
- Added advanced number formatting capabilities to MochiKit.Format:
|
||||
numberFormatter(pattern, placeholder="", locale="default") and
|
||||
formatLocale(locale="default")
|
||||
- Added updatetree(self, obj[, ...]) to MochiKit.Base, and changed
|
||||
MochiKit.DOM's updateNodeAttributes(node, attrs) to use it when appropiate.
|
||||
- Added new MochiKit.DOM createDOMFunc aliases: BUTTON, TT, PRE
|
||||
- Added truncToFixed(aNumber, precision) and roundToFixed(aNumber, precision)
|
||||
to MochiKit.Format
|
||||
- MochiKit.DateTime can now handle full ISO 8601 timestamps, specifically
|
||||
isoTimestamp(isoString) will convert them to Date objects, and
|
||||
toISOTimestamp(date, true) will return an ISO 8601 timestamp in UTC
|
||||
- Fixed missing errback for sendXMLHttpRequest when the server does not
|
||||
respond
|
||||
- Fixed infinite recusion bug when using roundClass("DIV", ...)
|
||||
- Fixed a bug in MochiKit.Async wait (and callLater) that prevented them
|
||||
from being cancelled properly
|
||||
- Workaround in MochiKit.Base bind (and partial) for functions that don't
|
||||
have an apply method, such as alert
|
||||
- Reliably return null from the string parsing/manipulation functions if
|
||||
the input can't be coerced to a string (s + "") or the input makes no sense;
|
||||
e.g. isoTimestamp(null) and isoTimestamp("") return null
|
||||
|
||||
2005-10-08 v0.90
|
||||
|
||||
- Fixed ISO compliance with toISODate
|
||||
- Added missing operator.sub
|
||||
- Placated Mozilla's strict warnings a bit
|
||||
- Added JSON serialization and unserialization support to MochiKit.Base:
|
||||
serializeJSON, evalJSON, registerJSON. This is very similar to the repr
|
||||
API.
|
||||
- Fixed a bug in the script loader that failed in some scenarios when a script
|
||||
tag did not have a "src" attribute (thanks Ian!)
|
||||
- Added new MochiKit.DOM createDOMFunc aliases: H1, H2, H3, BR, HR, TEXTAREA,
|
||||
P, FORM
|
||||
- Use encodeURIComponent / decodeURIComponent for MochiKit.Base urlEncode
|
||||
and parseQueryString, when available.
|
||||
|
||||
2005-08-12 v0.80
|
||||
|
||||
- Source highlighting in all examples, moved to a view-source example
|
||||
- Added some experimental syntax highlighting for the Rounded Corners example,
|
||||
via the LGPL dp.SyntaxHighlighter 1.2.0 now included in examples/common/lib
|
||||
- Use an indirect binding for the logger conveniences, so that the global
|
||||
logger could be replaced by setting MochiKit.Logger.logger to something else
|
||||
(though an observer is probably a better choice).
|
||||
- Allow MochiKit.DOM.getElementsByTagAndClassName to take a string for parent,
|
||||
which will be looked up with getElement
|
||||
- Fixed bug in MochiKit.Color.fromBackground (was using node.parent instead of
|
||||
node.parentNode)
|
||||
- Consider a 304 (NOT_MODIFIED) response from XMLHttpRequest to be success
|
||||
- Disabled Mozilla map(...) fast-path due to Deer Park compatibility issues
|
||||
- Possible workaround for Safari issue with swapDOM, where it would get
|
||||
confused because two elements were in the DOM at the same time with the
|
||||
same id
|
||||
- Added missing THEAD convenience function to MochiKit.DOM
|
||||
- Added lstrip, rstrip, strip to MochiKit.Format
|
||||
- Added updateNodeAttributes, appendChildNodes, replaceChildNodes to
|
||||
MochiKit.DOM
|
||||
- MochiKit.Iter.iextend now has a fast-path for array-like objects
|
||||
- Added HSV color space support to MochiKit.Visual
|
||||
- Fixed a bug in the sortable_tables example, it now converts types
|
||||
correctly
|
||||
- Fixed a bug where MochiKit.DOM referenced MochiKit.Iter.next from global
|
||||
scope
|
||||
|
||||
2005-08-04 v0.70
|
||||
|
||||
- New ajax_tables example, which shows off XMLHttpRequest, ajax, json, and
|
||||
a little TAL-ish DOM templating attribute language.
|
||||
- sendXMLHttpRequest and functions that use it (loadJSONDoc, etc.) no longer
|
||||
ignore requests with status == 0, which seems to happen for cached or local
|
||||
requests
|
||||
- Added sendXMLHttpRequest to MochiKit.Async.EXPORT, d'oh.
|
||||
- Changed scrapeText API to return a string by default. This is API-breaking!
|
||||
It was dumb to have the default return value be the form you almost never
|
||||
want. Sorry.
|
||||
- Added special form to swapDOM(dest, src). If src is null, dest is removed
|
||||
(where previously you'd likely get a DOM exception).
|
||||
- Added three new functions to MochiKit.Base for dealing with URL query
|
||||
strings: urlEncode, queryString, parseQueryString
|
||||
- MochiKit.DOM.createDOM will now use attr[k] = v for all browsers if the name
|
||||
starts with "on" (e.g. "onclick"). If v is a string, it will set it to
|
||||
new Function(v).
|
||||
- Another workaround for Internet "worst browser ever" Explorer's setAttribute
|
||||
usage in MochiKit.DOM.createDOM (checked -> defaultChecked).
|
||||
- Added UL, OL, LI convenience createDOM aliases to MochiKit.DOM
|
||||
- Packing is now done by Dojo's custom Rhino interpreter, so it's much smaller
|
||||
now!
|
||||
|
||||
2005-07-29 v0.60
|
||||
|
||||
- Beefed up the MochiKit.DOM test suite
|
||||
- Fixed return value for MochiKit.DOM.swapElementClass, could return
|
||||
false unexpectedly before
|
||||
- Added an optional "parent" argument to
|
||||
MochiKit.DOM.getElementsByTagAndClassName
|
||||
- Added a "packed" version in packed/MochiKit/MochiKit.js
|
||||
- Changed build script to rewrite the URLs in tests to account for the
|
||||
JSAN-required reorganization
|
||||
- MochiKit.Compat to potentially work around IE 5.5 issues
|
||||
(5.0 still not supported). Test.Simple doesn't seem to work there,
|
||||
though.
|
||||
- Several minor documentation corrections
|
||||
|
||||
2005-07-27 v0.50
|
||||
|
||||
- Initial Release
|
||||
@@ -1,69 +0,0 @@
|
||||
MochiKit is dual-licensed software. It is available under the terms of the
|
||||
MIT License, or the Academic Free License version 2.1. The full text of
|
||||
each license is included below.
|
||||
|
||||
MIT License
|
||||
===========
|
||||
|
||||
Copyright (c) 2005 Bob Ippolito. All rights reserved.
|
||||
|
||||
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.
|
||||
|
||||
|
||||
Academic Free License v. 2.1
|
||||
============================
|
||||
|
||||
Copyright (c) 2005 Bob Ippolito. All rights reserved.
|
||||
|
||||
This Academic Free License (the "License") applies to any original work of authorship (the "Original Work") whose owner (the "Licensor") has placed the following notice immediately following the copyright notice for the Original Work:
|
||||
|
||||
Licensed under the Academic Free License version 2.1
|
||||
|
||||
1) Grant of Copyright License. Licensor hereby grants You a world-wide, royalty-free, non-exclusive, perpetual, sublicenseable license to do the following:
|
||||
|
||||
a) to reproduce the Original Work in copies;
|
||||
|
||||
b) to prepare derivative works ("Derivative Works") based upon the Original Work;
|
||||
|
||||
c) to distribute copies of the Original Work and Derivative Works to the public;
|
||||
|
||||
d) to perform the Original Work publicly; and
|
||||
|
||||
e) to display the Original Work publicly.
|
||||
|
||||
2) Grant of Patent License. Licensor hereby grants You a world-wide, royalty-free, non-exclusive, perpetual, sublicenseable license, under patent claims owned or controlled by the Licensor that are embodied in the Original Work as furnished by the Licensor, to make, use, sell and offer for sale the Original Work and Derivative Works.
|
||||
|
||||
3) Grant of Source Code License. The term "Source Code" means the preferred form of the Original Work for making modifications to it and all available documentation describing how to modify the Original Work. Licensor hereby agrees to provide a machine-readable copy of the Source Code of the Original Work along with each copy of the Original Work that Licensor distributes. Licensor reserves the right to satisfy this obligation by placing a machine-readable copy of the Source Code in an information repository reasonably calculated to permit inexpensive and convenient access by You for as long as Licensor continues to distribute the Original Work, and by publishing the address of that information repository in a notice immediately following the copyright notice that applies to the Original Work.
|
||||
|
||||
4) Exclusions From License Grant. Neither the names of Licensor, nor the names of any contributors to the Original Work, nor any of their trademarks or service marks, may be used to endorse or promote products derived from this Original Work without express prior written permission of the Licensor. Nothing in this License shall be deemed to grant any rights to trademarks, copyrights, patents, trade secrets or any other intellectual property of Licensor except as expressly stated herein. No patent license is granted to make, use, sell or offer to sell embodiments of any patent claims other than the licensed claims defined in Section 2. No right is granted to the trademarks of Licensor even if such marks are included in the Original Work. Nothing in this License shall be interpreted to prohibit Licensor from licensing under different terms from this License any Original Work that Licensor otherwise would have a right to license.
|
||||
|
||||
5) This section intentionally omitted.
|
||||
|
||||
6) Attribution Rights. You must retain, in the Source Code of any Derivative Works that You create, all copyright, patent or trademark notices from the Source Code of the Original Work, as well as any notices of licensing and any descriptive text identified therein as an "Attribution Notice." You must cause the Source Code for any Derivative Works that You create to carry a prominent Attribution Notice reasonably calculated to inform recipients that You have modified the Original Work.
|
||||
|
||||
7) Warranty of Provenance and Disclaimer of Warranty. Licensor warrants that the copyright in and to the Original Work and the patent rights granted herein by Licensor are owned by the Licensor or are sublicensed to You under the terms of this License with the permission of the contributor(s) of those copyrights and patent rights. Except as expressly stated in the immediately proceeding sentence, the Original Work is provided under this License on an "AS IS" BASIS and WITHOUT WARRANTY, either express or implied, including, without limitation, the warranties of NON-INFRINGEMENT, MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY OF THE ORIGINAL WORK IS WITH YOU. This DISCLAIMER OF WARRANTY constitutes an essential part of this License. No license to Original Work is granted hereunder except under this disclaimer.
|
||||
|
||||
8) Limitation of Liability. Under no circumstances and under no legal theory, whether in tort (including negligence), contract, or otherwise, shall the Licensor be liable to any person for any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or the use of the Original Work including, without limitation, damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses. This limitation of liability shall not apply to liability for death or personal injury resulting from Licensor's negligence to the extent applicable law prohibits such limitation. Some jurisdictions do not allow the exclusion or limitation of incidental or consequential damages, so this exclusion and limitation may not apply to You.
|
||||
|
||||
9) Acceptance and Termination. If You distribute copies of the Original Work or a Derivative Work, You must make a reasonable effort under the circumstances to obtain the express assent of recipients to the terms of this License. Nothing else but this License (or another written agreement between Licensor and You) grants You permission to create Derivative Works based upon the Original Work or to exercise any of the rights granted in Section 1 herein, and any attempt to do so except under the terms of this License (or another written agreement between Licensor and You) is expressly prohibited by U.S. copyright law, the equivalent laws of other countries, and by international treaty. Therefore, by exercising any of the rights granted to You in Section 1 herein, You indicate Your acceptance of this License and all of its terms and conditions.
|
||||
|
||||
10) Termination for Patent Action. This License shall terminate automatically and You may no longer exercise any of the rights granted to You by this License as of the date You commence an action, including a cross-claim or counterclaim, against Licensor or any licensee alleging that the Original Work infringes a patent. This termination provision shall not apply for an action alleging patent infringement by combinations of the Original Work with other software or hardware.
|
||||
|
||||
11) Jurisdiction, Venue and Governing Law. Any action or suit relating to this License may be brought only in the courts of a jurisdiction wherein the Licensor resides or in which Licensor conducts its primary business, and under the laws of that jurisdiction excluding its conflict-of-law provisions. The application of the United Nations Convention on Contracts for the International Sale of Goods is expressly excluded. Any use of the Original Work outside the scope of this License or after its termination shall be subject to the requirements and penalties of the U.S. Copyright Act, 17 U.S.C. § 101 et seq., the equivalent laws of other countries, and international treaty. This section shall survive the termination of this License.
|
||||
|
||||
12) Attorneys Fees. In any action to enforce the terms of this License or seeking damages relating thereto, the prevailing party shall be entitled to recover its costs and expenses, including, without limitation, reasonable attorneys' fees and costs incurred in connection with such action, including any appeal of such action. This section shall survive the termination of this License.
|
||||
|
||||
13) Miscellaneous. This License represents the complete agreement concerning the subject matter hereof. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable.
|
||||
|
||||
14) Definition of "You" in This License. "You" throughout this License, whether in upper or lower case, means an individual or a legal entity exercising rights under, and complying with all of the terms of, this License. For legal entities, "You" includes any entity that controls, is controlled by, or is under common control with you. For purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
15) Right to Use. You may use the Original Work in all ways not otherwise restricted or conditioned by this License or by law, and Licensor promises not to interfere with or be responsible for such uses by You.
|
||||
|
||||
This license is Copyright (C) 2003-2004 Lawrence E. Rosen. All rights reserved. Permission is hereby granted to copy and distribute this license without modification. This license may not be modified without the express written permission of its copyright owner.
|
||||
|
||||
|
||||
|
||||
@@ -1,115 +0,0 @@
|
||||
Changes
|
||||
META.json
|
||||
MANIFEST This list of files
|
||||
LICENSE.txt
|
||||
doc/html/MochiKit/Async.html
|
||||
doc/html/MochiKit/Base.html
|
||||
doc/html/MochiKit/Color.html
|
||||
doc/html/MochiKit/DateTime.html
|
||||
doc/html/MochiKit/DOM.html
|
||||
doc/html/MochiKit/Format.html
|
||||
doc/html/MochiKit/index.html
|
||||
doc/html/MochiKit/Iter.html
|
||||
doc/html/MochiKit/Logging.html
|
||||
doc/html/MochiKit/LoggingPane.html
|
||||
doc/html/MochiKit/Signal.html
|
||||
doc/html/MochiKit/VersionHistory.html
|
||||
doc/html/MochiKit/Visual.html
|
||||
doc/js/toc.js
|
||||
doc/rst/MochiKit/Async.rst
|
||||
doc/rst/MochiKit/Base.rst
|
||||
doc/rst/MochiKit/Color.rst
|
||||
doc/rst/MochiKit/DateTime.rst
|
||||
doc/rst/MochiKit/DOM.rst
|
||||
doc/rst/MochiKit/Format.rst
|
||||
doc/rst/MochiKit/index.rst
|
||||
doc/rst/MochiKit/Iter.rst
|
||||
doc/rst/MochiKit/Logging.rst
|
||||
doc/rst/MochiKit/LoggingPane.rst
|
||||
doc/rst/MochiKit/Signal.rst
|
||||
doc/rst/MochiKit/VersionHistory.rst
|
||||
doc/rst/MochiKit/Visual.rst
|
||||
examples/ajax_tables/ajax_tables.css
|
||||
examples/ajax_tables/ajax_tables.js
|
||||
examples/ajax_tables/domains.json
|
||||
examples/ajax_tables/domains.xml
|
||||
examples/ajax_tables/index.html
|
||||
examples/color_wheel/color_wheel.css
|
||||
examples/color_wheel/color_wheel.js
|
||||
examples/color_wheel/index.html
|
||||
examples/draggable/draggable.css
|
||||
examples/draggable/draggable.js
|
||||
examples/draggable/index.html
|
||||
examples/interpreter/index.html
|
||||
examples/interpreter/interpreter.css
|
||||
examples/interpreter/interpreter.js
|
||||
examples/key_events/index.html
|
||||
examples/key_events/key_events.css
|
||||
examples/key_events/key_events.js
|
||||
examples/logging_pane/index.html
|
||||
examples/logging_pane/logging_pane.css
|
||||
examples/logging_pane/logging_pane.js
|
||||
examples/mochiregexp/index.html
|
||||
examples/mochiregexp/mochiregexp.css
|
||||
examples/mochiregexp/mochiregexp.js
|
||||
examples/rounded_corners/index.html
|
||||
examples/rounded_corners/rounded_corners.css
|
||||
examples/rounded_corners/rounded_corners.js
|
||||
examples/sortable_tables/index.html
|
||||
examples/sortable_tables/sortable_tables.css
|
||||
examples/sortable_tables/sortable_tables.js
|
||||
examples/view-source/view-source.css
|
||||
examples/view-source/view-source.html
|
||||
examples/view-source/view-source.js
|
||||
examples/view-source/lib/SyntaxHighlighter/shBrushCSharp.js
|
||||
examples/view-source/lib/SyntaxHighlighter/shBrushDelphi.js
|
||||
examples/view-source/lib/SyntaxHighlighter/shBrushJScript.js
|
||||
examples/view-source/lib/SyntaxHighlighter/shBrushPhp.js
|
||||
examples/view-source/lib/SyntaxHighlighter/shBrushPython.js
|
||||
examples/view-source/lib/SyntaxHighlighter/shBrushSql.js
|
||||
examples/view-source/lib/SyntaxHighlighter/shBrushVb.js
|
||||
examples/view-source/lib/SyntaxHighlighter/shBrushXml.js
|
||||
examples/view-source/lib/SyntaxHighlighter/shCore.js
|
||||
examples/view-source/lib/SyntaxHighlighter/SyntaxHighlighter.css
|
||||
examples/view-source/lib/SyntaxHighlighter/Tests.html
|
||||
include/css/documentation.css
|
||||
include/css/general.css
|
||||
MochiKit/__package__.js
|
||||
MochiKit/Async.js
|
||||
MochiKit/Base.js
|
||||
MochiKit/Color.js
|
||||
MochiKit/DateTime.js
|
||||
MochiKit/DOM.js
|
||||
MochiKit/Format.js
|
||||
MochiKit/Iter.js
|
||||
MochiKit/Logging.js
|
||||
MochiKit/LoggingPane.js
|
||||
MochiKit/MochiKit.js
|
||||
MochiKit/MockDOM.js
|
||||
MochiKit/Signal.js
|
||||
MochiKit/Test.js
|
||||
MochiKit/Visual.js
|
||||
packed/MochiKit/__package__.js
|
||||
packed/MochiKit/MochiKit.js
|
||||
tests/index.html
|
||||
tests/test_Base.js
|
||||
tests/test_Color.js
|
||||
tests/test_DateTime.js
|
||||
tests/test_Format.js
|
||||
tests/test_Iter.js
|
||||
tests/test_Logging.js
|
||||
tests/test_MochiKit-Async.html
|
||||
tests/test_MochiKit-Base.html
|
||||
tests/test_MochiKit-Color.html
|
||||
tests/test_MochiKit-DateTime.html
|
||||
tests/test_MochiKit-DOM.html
|
||||
tests/test_MochiKit-Format.html
|
||||
tests/test_MochiKit-Iter.html
|
||||
tests/test_MochiKit-JSAN.html
|
||||
tests/test_MochiKit-Logging.html
|
||||
tests/test_MochiKit-MochiKit.html
|
||||
tests/test_MochiKit-Signal.html
|
||||
tests/test_Signal.js
|
||||
tests/SimpleTest/SimpleTest.js
|
||||
tests/SimpleTest/test.css
|
||||
tests/SimpleTest/TestRunner.js
|
||||
@@ -1,17 +0,0 @@
|
||||
{
|
||||
"recommends": {
|
||||
"JSAN": "0.10"
|
||||
},
|
||||
"name": "MochiKit",
|
||||
"license": "mit",
|
||||
"author": [
|
||||
"Bob Ippolito <bob@redivi.com>"
|
||||
],
|
||||
"abstract": "Python-inspired JavaScript kit",
|
||||
"generated_by": "MochiKit's build script",
|
||||
"build_requires": {
|
||||
"Test.Simple": "0.11"
|
||||
},
|
||||
"version": "1.3.1",
|
||||
"provides": {}
|
||||
}
|
||||
@@ -1,606 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8" ?>
|
||||
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
|
||||
|
||||
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
|
||||
<meta name="generator" content="Docutils 0.4: http://docutils.sourceforge.net/" />
|
||||
<title>MochiKit.Async - manage asynchronous tasks</title>
|
||||
|
||||
<link rel="stylesheet" href="../../../include/css/documentation.css" type="text/css" />
|
||||
<script type="text/javascript" src="../../../packed/lib/MochiKit/MochiKit.js"></script>
|
||||
<script type="text/javascript" src="../../js/toc.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div class="document">
|
||||
<div class="section">
|
||||
<h1><a id="name" name="name">Name</a></h1>
|
||||
<p>MochiKit.Async - manage asynchronous tasks</p>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h1><a id="synopsis" name="synopsis">Synopsis</a></h1>
|
||||
<pre class="literal-block">
|
||||
var url = "/src/b/bo/bob/MochiKit.Async/META.json";
|
||||
/*
|
||||
|
||||
META.json looks something like this:
|
||||
|
||||
{"name": "MochiKit", "version": "0.5"}
|
||||
|
||||
*/
|
||||
var d = loadJSONDoc(url);
|
||||
var gotMetadata = function (meta) {
|
||||
if (MochiKit.Async.VERSION == meta.version) {
|
||||
alert("You have the newest MochiKit.Async!");
|
||||
} else {
|
||||
alert("MochiKit.Async "
|
||||
+ meta.version
|
||||
+ " is available, upgrade!");
|
||||
}
|
||||
};
|
||||
var metadataFetchFailed = function (err) {
|
||||
alert("The metadata for MochiKit.Async could not be fetched :(");
|
||||
};
|
||||
d.addCallbacks(gotMetadata, metadataFetchFailed);
|
||||
</pre>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h1><a id="description" name="description">Description</a></h1>
|
||||
<p>MochiKit.Async provides facilities to manage asynchronous
|
||||
(as in AJAX <a class="footnote-reference" href="#id7" id="id1" name="id1">[1]</a>) tasks. The model for asynchronous computation
|
||||
used in this module is heavily inspired by Twisted <a class="footnote-reference" href="#id8" id="id2" name="id2">[2]</a>.</p>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h1><a id="dependencies" name="dependencies">Dependencies</a></h1>
|
||||
<ul class="simple">
|
||||
<li><a class="mochiref reference" href="Base.html">MochiKit.Base</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h1><a id="overview" name="overview">Overview</a></h1>
|
||||
<div class="section">
|
||||
<h2><a id="deferred" name="deferred">Deferred</a></h2>
|
||||
<p>The Deferred constructor encapsulates a single value that
|
||||
is not available yet. The most important example of this
|
||||
in the context of a web browser would be an <tt class="docutils literal"><span class="pre">XMLHttpRequest</span></tt>
|
||||
to a server. The importance of the Deferred is that it
|
||||
allows a consistent API to be exposed for all asynchronous
|
||||
computations that occur exactly once.</p>
|
||||
<p>The producer of the Deferred is responsible for doing all
|
||||
of the complicated work behind the scenes. This often
|
||||
means waiting for a timer to fire, or waiting for an event
|
||||
(e.g. <tt class="docutils literal"><span class="pre">onreadystatechange</span></tt> of <tt class="docutils literal"><span class="pre">XMLHttpRequest</span></tt>).
|
||||
It could also be coordinating several events (e.g.
|
||||
<tt class="docutils literal"><span class="pre">XMLHttpRequest</span></tt> with a timeout, or several Deferreds
|
||||
(e.g. fetching a set of XML documents that should be
|
||||
processed at the same time).</p>
|
||||
<p>Since these sorts of tasks do not respond immediately, the
|
||||
producer of the Deferred does the following steps before
|
||||
returning to the consumer:</p>
|
||||
<ol class="arabic simple">
|
||||
<li>Create a <tt class="docutils literal"><span class="pre">new</span></tt> <a class="mochiref reference" href="#fn-deferred">Deferred();</a> object and keep a reference
|
||||
to it, because it will be needed later when the value is
|
||||
ready.</li>
|
||||
<li>Setup the conditions to create the value requested (e.g.
|
||||
create a new <tt class="docutils literal"><span class="pre">XMLHttpRequest</span></tt>, set its
|
||||
<tt class="docutils literal"><span class="pre">onreadystatechange</span></tt>).</li>
|
||||
<li>Return the <a class="mochiref reference" href="#fn-deferred">Deferred</a> object.</li>
|
||||
</ol>
|
||||
<p>Since the value is not yet ready, the consumer attaches
|
||||
a function to the Deferred that will be called when the
|
||||
value is ready. This is not unlike <tt class="docutils literal"><span class="pre">setTimeout</span></tt>, or
|
||||
other similar facilities you may already be familiar with.
|
||||
The consumer can also attach an "errback" to the
|
||||
<a class="mochiref reference" href="#fn-deferred">Deferred</a>, which is a callback for error handling.</p>
|
||||
<p>When the value is ready, the producer simply calls
|
||||
<tt class="docutils literal"><span class="pre">myDeferred.callback(theValue)</span></tt>. If an error occurred,
|
||||
it should call <tt class="docutils literal"><span class="pre">myDeferred.errback(theValue)</span></tt> instead.
|
||||
As soon as this happens, the callback that the consumer
|
||||
attached to the <a class="mochiref reference" href="#fn-deferred">Deferred</a> is called with <tt class="docutils literal"><span class="pre">theValue</span></tt>
|
||||
as the only argument.</p>
|
||||
<p>There are quite a few additional "advanced" features
|
||||
baked into <a class="mochiref reference" href="#fn-deferred">Deferred</a>, such as cancellation and
|
||||
callback chains, so take a look at the API
|
||||
reference if you would like to know more!</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h1><a id="api-reference" name="api-reference">API Reference</a></h1>
|
||||
<div class="section">
|
||||
<h2><a id="errors" name="errors">Errors</a></h2>
|
||||
<p>
|
||||
<a name="fn-alreadycallederror"></a>
|
||||
<a class="mochidef reference" href="#fn-alreadycallederror">AlreadyCalledError</a>:</p>
|
||||
<blockquote>
|
||||
Thrown by a <a class="mochiref reference" href="#fn-deferred">Deferred</a> if <tt class="docutils literal"><span class="pre">.callback</span></tt> or
|
||||
<tt class="docutils literal"><span class="pre">.errback</span></tt> are called more than once.</blockquote>
|
||||
<p>
|
||||
<a name="fn-browsercomplianceerror"></a>
|
||||
<a class="mochidef reference" href="#fn-browsercomplianceerror">BrowserComplianceError</a>:</p>
|
||||
<blockquote>
|
||||
Thrown when the JavaScript runtime is not capable of performing
|
||||
the given function. Currently, this happens if the browser
|
||||
does not support <tt class="docutils literal"><span class="pre">XMLHttpRequest</span></tt>.</blockquote>
|
||||
<p>
|
||||
<a name="fn-cancellederror"></a>
|
||||
<a class="mochidef reference" href="#fn-cancellederror">CancelledError</a>:</p>
|
||||
<blockquote>
|
||||
Thrown by a <a class="mochiref reference" href="#fn-deferred">Deferred</a> when it is cancelled,
|
||||
unless a canceller is present and throws something else.</blockquote>
|
||||
<p>
|
||||
<a name="fn-genericerror"></a>
|
||||
<a class="mochidef reference" href="#fn-genericerror">GenericError</a>:</p>
|
||||
<blockquote>
|
||||
Results passed to <tt class="docutils literal"><span class="pre">.fail</span></tt> or <tt class="docutils literal"><span class="pre">.errback</span></tt> of a <a class="mochiref reference" href="#fn-deferred">Deferred</a>
|
||||
are wrapped by this <tt class="docutils literal"><span class="pre">Error</span></tt> if <tt class="docutils literal"><span class="pre">!(result</span> <span class="pre">instanceof</span> <span class="pre">Error)</span></tt>.</blockquote>
|
||||
<p>
|
||||
<a name="fn-xmlhttprequesterror"></a>
|
||||
<a class="mochidef reference" href="#fn-xmlhttprequesterror">XMLHttpRequestError</a>:</p>
|
||||
<blockquote>
|
||||
Thrown when an <tt class="docutils literal"><span class="pre">XMLHttpRequest</span></tt> does not complete successfully
|
||||
for any reason. The <tt class="docutils literal"><span class="pre">req</span></tt> property of the error is the failed
|
||||
<tt class="docutils literal"><span class="pre">XMLHttpRequest</span></tt> object, and for convenience the <tt class="docutils literal"><span class="pre">number</span></tt>
|
||||
property corresponds to <tt class="docutils literal"><span class="pre">req.status</span></tt>.</blockquote>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h2><a id="constructors" name="constructors">Constructors</a></h2>
|
||||
<p>
|
||||
<a name="fn-deferred"></a>
|
||||
<a class="mochidef reference" href="#fn-deferred">Deferred()</a>:</p>
|
||||
<blockquote>
|
||||
Encapsulates a sequence of callbacks in response to a value that
|
||||
may not yet be available. This is modeled after the Deferred class
|
||||
from Twisted <a class="footnote-reference" href="#id9" id="id3" name="id3">[3]</a>.</blockquote>
|
||||
<blockquote>
|
||||
<p>Why do we want this? JavaScript has no threads, and even if it did,
|
||||
threads are hard. Deferreds are a way of abstracting non-blocking
|
||||
events, such as the final response to an <tt class="docutils literal"><span class="pre">XMLHttpRequest</span></tt>.</p>
|
||||
<p>The sequence of callbacks is internally represented as a list
|
||||
of 2-tuples containing the callback/errback pair. For example,
|
||||
the following call sequence:</p>
|
||||
<pre class="literal-block">
|
||||
var d = new Deferred();
|
||||
d.addCallback(myCallback);
|
||||
d.addErrback(myErrback);
|
||||
d.addBoth(myBoth);
|
||||
d.addCallbacks(myCallback, myErrback);
|
||||
</pre>
|
||||
<p>is translated into a <a class="mochiref reference" href="#fn-deferred">Deferred</a> with the following internal
|
||||
representation:</p>
|
||||
<pre class="literal-block">
|
||||
[
|
||||
[myCallback, null],
|
||||
[null, myErrback],
|
||||
[myBoth, myBoth],
|
||||
[myCallback, myErrback]
|
||||
]
|
||||
</pre>
|
||||
<p>The <a class="mochiref reference" href="#fn-deferred">Deferred</a> also keeps track of its current status (fired).
|
||||
Its status may be one of the following three values:</p>
|
||||
<blockquote>
|
||||
<table border="1" class="docutils">
|
||||
<colgroup>
|
||||
<col width="14%" />
|
||||
<col width="86%" />
|
||||
</colgroup>
|
||||
<thead valign="bottom">
|
||||
<tr><th class="head">Value</th>
|
||||
<th class="head">Condition</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody valign="top">
|
||||
<tr><td>-1</td>
|
||||
<td>no value yet (initial condition)</td>
|
||||
</tr>
|
||||
<tr><td>0</td>
|
||||
<td>success</td>
|
||||
</tr>
|
||||
<tr><td>1</td>
|
||||
<td>error</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</blockquote>
|
||||
<p>A <a class="mochiref reference" href="#fn-deferred">Deferred</a> will be in the error state if one of the following
|
||||
conditions are met:</p>
|
||||
<ol class="arabic simple">
|
||||
<li>The result given to callback or errback is "<tt class="docutils literal"><span class="pre">instanceof</span> <span class="pre">Error</span></tt>"</li>
|
||||
<li>The callback or errback threw while executing. If the thrown object
|
||||
is not <tt class="docutils literal"><span class="pre">instanceof</span> <span class="pre">Error</span></tt>, it will be wrapped with
|
||||
<a class="mochiref reference" href="#fn-genericerror">GenericError</a>.</li>
|
||||
</ol>
|
||||
<p>Otherwise, the <a class="mochiref reference" href="#fn-deferred">Deferred</a> will be in the success state. The state
|
||||
of the <a class="mochiref reference" href="#fn-deferred">Deferred</a> determines the next element in the callback
|
||||
sequence to run.</p>
|
||||
<p>When a callback or errback occurs with the example deferred chain, something
|
||||
equivalent to the following will happen (imagine that exceptions are caught
|
||||
and returned as-is):</p>
|
||||
<pre class="literal-block">
|
||||
// d.callback(result) or d.errback(result)
|
||||
if (!(result instanceof Error)) {
|
||||
result = myCallback(result);
|
||||
}
|
||||
if (result instanceof Error) {
|
||||
result = myErrback(result);
|
||||
}
|
||||
result = myBoth(result);
|
||||
if (result instanceof Error) {
|
||||
result = myErrback(result);
|
||||
} else {
|
||||
result = myCallback(result);
|
||||
}
|
||||
</pre>
|
||||
<p>The result is then stored away in case another step is added to the
|
||||
callback sequence. Since the <a class="mochiref reference" href="#fn-deferred">Deferred</a> already has a value
|
||||
available, any new callbacks added will be called immediately.</p>
|
||||
<p>There are two other "advanced" details about this implementation that are
|
||||
useful:</p>
|
||||
<p>Callbacks are allowed to return <a class="mochiref reference" href="#fn-deferred">Deferred</a> instances,
|
||||
so you can build complicated sequences of events with (relative) ease.</p>
|
||||
<p>The creator of the <a class="mochiref reference" href="#fn-deferred">Deferred</a> may specify a canceller. The
|
||||
canceller is a function that will be called if
|
||||
<a class="mochiref reference" href="#fn-deferred.prototype.cancel">Deferred.prototype.cancel</a> is called before the
|
||||
<a class="mochiref reference" href="#fn-deferred">Deferred</a> fires. You can use this to allow an
|
||||
<tt class="docutils literal"><span class="pre">XMLHttpRequest</span></tt> to be cleanly cancelled, for example. Note that
|
||||
cancel will fire the <a class="mochiref reference" href="#fn-deferred">Deferred</a> with a
|
||||
<a class="mochiref reference" href="#fn-cancellederror">CancelledError</a> (unless your canceller throws or returns
|
||||
a different <tt class="docutils literal"><span class="pre">Error</span></tt>), so errbacks should be prepared to handle that
|
||||
<tt class="docutils literal"><span class="pre">Error</span></tt> gracefully for cancellable <a class="mochiref reference" href="#fn-deferred">Deferred</a> instances.</p>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-deferred.prototype.addboth"></a>
|
||||
<a class="mochidef reference" href="#fn-deferred.prototype.addboth">Deferred.prototype.addBoth(func)</a>:</p>
|
||||
<blockquote>
|
||||
<p>Add the same function as both a callback and an errback as the
|
||||
next element on the callback sequence. This is useful for code
|
||||
that you want to guarantee to run, e.g. a finalizer.</p>
|
||||
<p>If additional arguments are given, then <tt class="docutils literal"><span class="pre">func</span></tt> will be replaced
|
||||
with <a class="mochiref reference" href="Base.html#fn-partial">MochiKit.Base.partial.apply(null, arguments)</a>. This
|
||||
differs from <a class="reference" href="http://twistedmatrix.com/">Twisted</a>, because the result of the callback or
|
||||
errback will be the <em>last</em> argument passed to <tt class="docutils literal"><span class="pre">func</span></tt>.</p>
|
||||
<p>If <tt class="docutils literal"><span class="pre">func</span></tt> returns a <a class="mochiref reference" href="#fn-deferred">Deferred</a>, then it will be chained
|
||||
(its value or error will be passed to the next callback). Note that
|
||||
once the returned <tt class="docutils literal"><span class="pre">Deferred</span></tt> is chained, it can no longer accept new
|
||||
callbacks.</p>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-deferred.prototype.addcallback"></a>
|
||||
<a class="mochidef reference" href="#fn-deferred.prototype.addcallback">Deferred.prototype.addCallback(func[, ...])</a>:</p>
|
||||
<blockquote>
|
||||
<p>Add a single callback to the end of the callback sequence.</p>
|
||||
<p>If additional arguments are given, then <tt class="docutils literal"><span class="pre">func</span></tt> will be replaced
|
||||
with <a class="mochiref reference" href="Base.html#fn-partial">MochiKit.Base.partial.apply(null, arguments)</a>. This
|
||||
differs from <a class="reference" href="http://twistedmatrix.com/">Twisted</a>, because the result of the callback will
|
||||
be the <em>last</em> argument passed to <tt class="docutils literal"><span class="pre">func</span></tt>.</p>
|
||||
<p>If <tt class="docutils literal"><span class="pre">func</span></tt> returns a <a class="mochiref reference" href="#fn-deferred">Deferred</a>, then it will be chained
|
||||
(its value or error will be passed to the next callback). Note that
|
||||
once the returned <tt class="docutils literal"><span class="pre">Deferred</span></tt> is chained, it can no longer accept new
|
||||
callbacks.</p>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-deferred.prototype.addcallbacks"></a>
|
||||
<a class="mochidef reference" href="#fn-deferred.prototype.addcallbacks">Deferred.prototype.addCallbacks(callback, errback)</a>:</p>
|
||||
<blockquote>
|
||||
<p>Add separate callback and errback to the end of the callback
|
||||
sequence. Either callback or errback may be <tt class="docutils literal"><span class="pre">null</span></tt>,
|
||||
but not both.</p>
|
||||
<p>If <tt class="docutils literal"><span class="pre">callback</span></tt> or <tt class="docutils literal"><span class="pre">errback</span></tt> returns a <a class="mochiref reference" href="#fn-deferred">Deferred</a>,
|
||||
then it will be chained (its value or error will be passed to the
|
||||
next callback). Note that once the returned <tt class="docutils literal"><span class="pre">Deferred</span></tt> is chained,
|
||||
it can no longer accept new callbacks.</p>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-deferred.prototype.adderrback"></a>
|
||||
<a class="mochidef reference" href="#fn-deferred.prototype.adderrback">Deferred.prototype.addErrback(func)</a>:</p>
|
||||
<blockquote>
|
||||
<p>Add a single errback to the end of the callback sequence.</p>
|
||||
<p>If additional arguments are given, then <tt class="docutils literal"><span class="pre">func</span></tt> will be replaced
|
||||
with <a class="mochiref reference" href="Base.html#fn-partial">MochiKit.Base.partial.apply(null, arguments)</a>. This
|
||||
differs from <a class="reference" href="http://twistedmatrix.com/">Twisted</a>, because the result of the errback will
|
||||
be the <em>last</em> argument passed to <tt class="docutils literal"><span class="pre">func</span></tt>.</p>
|
||||
<p>If <tt class="docutils literal"><span class="pre">func</span></tt> returns a <a class="mochiref reference" href="#fn-deferred">Deferred</a>, then it will be chained
|
||||
(its value or error will be passed to the next callback). Note that
|
||||
once the returned <tt class="docutils literal"><span class="pre">Deferred</span></tt> is chained, it can no longer accept new
|
||||
callbacks.</p>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-deferred.prototype.callback"></a>
|
||||
<a class="mochidef reference" href="#fn-deferred.prototype.callback">Deferred.prototype.callback([result])</a>:</p>
|
||||
<blockquote>
|
||||
<p>Begin the callback sequence with a non-<tt class="docutils literal"><span class="pre">Error</span></tt> result. Result
|
||||
may be any value except for a <a class="mochiref reference" href="#fn-deferred">Deferred</a>.</p>
|
||||
<p>Either <tt class="docutils literal"><span class="pre">.callback</span></tt> or <tt class="docutils literal"><span class="pre">.errback</span></tt> should
|
||||
be called exactly once on a <a class="mochiref reference" href="#fn-deferred">Deferred</a>.</p>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-deferred.prototype.cancel"></a>
|
||||
<a class="mochidef reference" href="#fn-deferred.prototype.cancel">Deferred.prototype.cancel()</a>:</p>
|
||||
<blockquote>
|
||||
<p>Cancels a <a class="mochiref reference" href="#fn-deferred">Deferred</a> that has not yet received a value,
|
||||
or is waiting on another <a class="mochiref reference" href="#fn-deferred">Deferred</a> as its value.</p>
|
||||
<p>If a canceller is defined, the canceller is called.
|
||||
If the canceller did not return an <tt class="docutils literal"><span class="pre">Error</span></tt>, or there
|
||||
was no canceller, then the errback chain is started
|
||||
with <a class="mochiref reference" href="#fn-cancellederror">CancelledError</a>.</p>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-deferred.prototype.errback"></a>
|
||||
<a class="mochidef reference" href="#fn-deferred.prototype.errback">Deferred.prototype.errback([result])</a>:</p>
|
||||
<blockquote>
|
||||
<p>Begin the callback sequence with an error result.
|
||||
Result may be any value except for a <a class="mochiref reference" href="#fn-deferred">Deferred</a>,
|
||||
but if <tt class="docutils literal"><span class="pre">!(result</span> <span class="pre">instanceof</span> <span class="pre">Error)</span></tt>, it will be wrapped
|
||||
with <a class="mochiref reference" href="#fn-genericerror">GenericError</a>.</p>
|
||||
<p>Either <tt class="docutils literal"><span class="pre">.callback</span></tt> or <tt class="docutils literal"><span class="pre">.errback</span></tt> should
|
||||
be called exactly once on a
|
||||
<a name="fn-deferred"></a>
|
||||
<a class="mochidef reference" href="#fn-deferred">Deferred</a>.</p>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-deferredlock"></a>
|
||||
<a class="mochidef reference" href="#fn-deferredlock">DeferredLock()</a>:</p>
|
||||
<blockquote>
|
||||
<p>A lock for asynchronous systems.</p>
|
||||
<p>The <tt class="docutils literal"><span class="pre">locked</span></tt> property of a <a class="mochiref reference" href="#fn-deferredlock">DeferredLock</a> will be <tt class="docutils literal"><span class="pre">true</span></tt> if
|
||||
it locked, <tt class="docutils literal"><span class="pre">false</span></tt> otherwise. Do not change this property.</p>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-deferredlock.prototype.acquire"></a>
|
||||
<a class="mochidef reference" href="#fn-deferredlock.prototype.acquire">DeferredLock.prototype.acquire()</a>:</p>
|
||||
<blockquote>
|
||||
Attempt to acquire the lock. Returns a <a class="mochiref reference" href="#fn-deferred">Deferred</a> that fires on
|
||||
lock acquisition with the <a class="mochiref reference" href="#fn-deferredlock">DeferredLock</a> as the value.
|
||||
If the lock is locked, then the <a class="mochiref reference" href="#fn-deferred">Deferred</a> goes into a waiting
|
||||
list.</blockquote>
|
||||
<p>
|
||||
<a name="fn-deferredlock.prototype.release"></a>
|
||||
<a class="mochidef reference" href="#fn-deferredlock.prototype.release">DeferredLock.prototype.release()</a>:</p>
|
||||
<blockquote>
|
||||
Release the lock. If there is a waiting list, then the first
|
||||
<a class="mochiref reference" href="#fn-deferred">Deferred</a> in that waiting list will be called back.</blockquote>
|
||||
<p>
|
||||
<a name="fn-deferredlist"></a>
|
||||
<a class="mochidef reference" href="#fn-deferredlist">DeferredList(list, [fireOnOneCallback, fireOnOneErrback, consumeErrors, canceller])</a>:</p>
|
||||
<blockquote>
|
||||
<p>Combine a list of <a class="mochiref reference" href="#fn-deferred">Deferred</a> into one. Track the callbacks and
|
||||
return a list of (success, result) tuples, 'success' being a boolean
|
||||
indicating whether result is a normal result or an error.</p>
|
||||
<p>Once created, you have access to all <a class="mochiref reference" href="#fn-deferred">Deferred</a> methods, like
|
||||
addCallback, addErrback, addBoth. The behaviour can be changed by the
|
||||
following options:</p>
|
||||
<dl class="docutils">
|
||||
<dt><tt class="docutils literal"><span class="pre">fireOnOneCallback</span></tt>:</dt>
|
||||
<dd>Flag for launching the callback once the first Deferred of the list
|
||||
has returned.</dd>
|
||||
<dt><tt class="docutils literal"><span class="pre">fireOnOneErrback</span></tt>:</dt>
|
||||
<dd>Flag for calling the errback at the first error of a Deferred.</dd>
|
||||
<dt><tt class="docutils literal"><span class="pre">consumeErrors</span></tt>:</dt>
|
||||
<dd>Flag indicating that any errors raised in the Deferreds should be
|
||||
consumed by the DeferredList.</dd>
|
||||
</dl>
|
||||
<p>Example:</p>
|
||||
<pre class="literal-block">
|
||||
// We need to fetch data from 2 different urls
|
||||
var d1 = loadJSONDoc(url1);
|
||||
var d2 = loadJSONDoc(url2);
|
||||
var l1 = new DeferredList([d1, d2], false, false, true);
|
||||
l1.addCallback(function (resultList) {
|
||||
MochiKit.Base.map(function (result) {
|
||||
if (result[0]) {
|
||||
alert("Data is here: " + result[1]);
|
||||
} else {
|
||||
alert("Got an error: " + result[1]);
|
||||
}
|
||||
}, resultList);
|
||||
});
|
||||
</pre>
|
||||
</blockquote>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h2><a id="functions" name="functions">Functions</a></h2>
|
||||
<p>
|
||||
<a name="fn-calllater"></a>
|
||||
<a class="mochidef reference" href="#fn-calllater">callLater(seconds, func[, args...])</a>:</p>
|
||||
<blockquote>
|
||||
<p>Call <tt class="docutils literal"><span class="pre">func(args...)</span></tt> after at least <tt class="docutils literal"><span class="pre">seconds</span></tt> seconds have elapsed.
|
||||
This is a convenience method for:</p>
|
||||
<pre class="literal-block">
|
||||
func = partial.apply(extend(null, arguments, 1));
|
||||
return wait(seconds).addCallback(function (res) { return func() });
|
||||
</pre>
|
||||
<p>Returns a cancellable <a class="mochiref reference" href="#fn-deferred">Deferred</a>.</p>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-dosimplexmlhttprequest"></a>
|
||||
<a class="mochidef reference" href="#fn-dosimplexmlhttprequest">doSimpleXMLHttpRequest(url[, queryArguments...])</a>:</p>
|
||||
<blockquote>
|
||||
<p>Perform a simple <tt class="docutils literal"><span class="pre">XMLHttpRequest</span></tt> and wrap it with a
|
||||
<a class="mochiref reference" href="#fn-deferred">Deferred</a> that may be cancelled.</p>
|
||||
<p>Note that currently, only <tt class="docutils literal"><span class="pre">200</span></tt> (OK) and <tt class="docutils literal"><span class="pre">304</span></tt>
|
||||
(NOT_MODIFIED) are considered success codes at this time, other
|
||||
status codes will result in an errback with an <tt class="docutils literal"><span class="pre">XMLHttpRequestError</span></tt>.</p>
|
||||
<dl class="docutils">
|
||||
<dt><tt class="docutils literal"><span class="pre">url</span></tt>:</dt>
|
||||
<dd>The URL to GET</dd>
|
||||
<dt><tt class="docutils literal"><span class="pre">queryArguments</span></tt>:</dt>
|
||||
<dd><p class="first">If this function is called with more than one argument, a <tt class="docutils literal"><span class="pre">"?"</span></tt>
|
||||
and the result of <a class="mochiref reference" href="Base.html#fn-querystring">MochiKit.Base.queryString</a> with
|
||||
the rest of the arguments are appended to the URL.</p>
|
||||
<p>For example, this will do a GET request to the URL
|
||||
<tt class="docutils literal"><span class="pre">http://example.com?bar=baz</span></tt>:</p>
|
||||
<pre class="last literal-block">
|
||||
doSimpleXMLHttpRequest("http://example.com", {bar: "baz"});
|
||||
</pre>
|
||||
</dd>
|
||||
<dt><em>returns</em>:</dt>
|
||||
<dd><a class="mochiref reference" href="#fn-deferred">Deferred</a> that will callback with the <tt class="docutils literal"><span class="pre">XMLHttpRequest</span></tt>
|
||||
instance on success</dd>
|
||||
</dl>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-evaljsonrequest"></a>
|
||||
<a class="mochidef reference" href="#fn-evaljsonrequest">evalJSONRequest(req)</a>:</p>
|
||||
<blockquote>
|
||||
<p>Evaluate a JSON <a class="footnote-reference" href="#id10" id="id4" name="id4">[4]</a> <tt class="docutils literal"><span class="pre">XMLHttpRequest</span></tt></p>
|
||||
<dl class="docutils">
|
||||
<dt><tt class="docutils literal"><span class="pre">req</span></tt>:</dt>
|
||||
<dd>The request whose <tt class="docutils literal"><span class="pre">.responseText</span></tt> property is to be evaluated</dd>
|
||||
<dt><em>returns</em>:</dt>
|
||||
<dd>A JavaScript object</dd>
|
||||
</dl>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-fail"></a>
|
||||
<a class="mochidef reference" href="#fn-fail">fail([result])</a>:</p>
|
||||
<blockquote>
|
||||
<p>Return a <a class="mochiref reference" href="#fn-deferred">Deferred</a> that has already had <tt class="docutils literal"><span class="pre">.errback(result)</span></tt>
|
||||
called.</p>
|
||||
<p>See <tt class="docutils literal"><span class="pre">succeed</span></tt> documentation for rationale.</p>
|
||||
<dl class="docutils">
|
||||
<dt><tt class="docutils literal"><span class="pre">result</span></tt>:</dt>
|
||||
<dd>The result to give to <a class="mochiref reference" href="#fn-deferred.prototype.errback">Deferred.prototype.errback(result)</a>.</dd>
|
||||
<dt><em>returns</em>:</dt>
|
||||
<dd>A <tt class="docutils literal"><span class="pre">new</span></tt> <a class="mochiref reference" href="#fn-deferred">Deferred()</a></dd>
|
||||
</dl>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-gatherresults"></a>
|
||||
<a class="mochidef reference" href="#fn-gatherresults">gatherResults(deferreds)</a>:</p>
|
||||
<blockquote>
|
||||
A convenience function that returns a <a class="mochiref reference" href="#fn-deferredlist">DeferredList</a>
|
||||
from the given <tt class="docutils literal"><span class="pre">Array</span></tt> of <a class="mochiref reference" href="#fn-deferred">Deferred</a> instances
|
||||
that will callback with an <tt class="docutils literal"><span class="pre">Array</span></tt> of just results when
|
||||
they're available, or errback on the first array.</blockquote>
|
||||
<p>
|
||||
<a name="fn-getxmlhttprequest"></a>
|
||||
<a class="mochidef reference" href="#fn-getxmlhttprequest">getXMLHttpRequest()</a>:</p>
|
||||
<blockquote>
|
||||
<p>Return an <tt class="docutils literal"><span class="pre">XMLHttpRequest</span></tt> compliant object for the current
|
||||
platform.</p>
|
||||
<p>In order of preference:</p>
|
||||
<ul class="simple">
|
||||
<li><tt class="docutils literal"><span class="pre">new</span> <span class="pre">XMLHttpRequest()</span></tt></li>
|
||||
<li><tt class="docutils literal"><span class="pre">new</span> <span class="pre">ActiveXObject('Msxml2.XMLHTTP')</span></tt></li>
|
||||
<li><tt class="docutils literal"><span class="pre">new</span> <span class="pre">ActiveXObject('Microsoft.XMLHTTP')</span></tt></li>
|
||||
<li><tt class="docutils literal"><span class="pre">new</span> <span class="pre">ActiveXObject('Msxml2.XMLHTTP.4.0')</span></tt></li>
|
||||
</ul>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-maybedeferred"></a>
|
||||
<a class="mochidef reference" href="#fn-maybedeferred">maybeDeferred(func[, argument...])</a>:</p>
|
||||
<blockquote>
|
||||
<p>Call a <tt class="docutils literal"><span class="pre">func</span></tt> with the given arguments and ensure the result is a
|
||||
<a class="mochiref reference" href="#fn-deferred">Deferred</a>.</p>
|
||||
<dl class="docutils">
|
||||
<dt><tt class="docutils literal"><span class="pre">func</span></tt>:</dt>
|
||||
<dd>The function to call.</dd>
|
||||
<dt><em>returns</em>:</dt>
|
||||
<dd>A new <a class="mochiref reference" href="#fn-deferred">Deferred</a> based on the call to <tt class="docutils literal"><span class="pre">func</span></tt>. If <tt class="docutils literal"><span class="pre">func</span></tt>
|
||||
does not naturally return a <a class="mochiref reference" href="#fn-deferred">Deferred</a>, its result or error
|
||||
value will be wrapped by one.</dd>
|
||||
</dl>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-loadjsondoc"></a>
|
||||
<a class="mochidef reference" href="#fn-loadjsondoc">loadJSONDoc(url)</a>:</p>
|
||||
<blockquote>
|
||||
<p>Do a simple <tt class="docutils literal"><span class="pre">XMLHttpRequest</span></tt> to a URL and get the response
|
||||
as a JSON <a class="footnote-reference" href="#id10" id="id5" name="id5">[4]</a> document.</p>
|
||||
<dl class="docutils">
|
||||
<dt><tt class="docutils literal"><span class="pre">url</span></tt>:</dt>
|
||||
<dd>The URL to GET</dd>
|
||||
<dt><em>returns</em>:</dt>
|
||||
<dd><a class="mochiref reference" href="#fn-deferred">Deferred</a> that will callback with the evaluated JSON <a class="footnote-reference" href="#id10" id="id6" name="id6">[4]</a>
|
||||
response upon successful <tt class="docutils literal"><span class="pre">XMLHttpRequest</span></tt></dd>
|
||||
</dl>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-sendxmlhttprequest"></a>
|
||||
<a class="mochidef reference" href="#fn-sendxmlhttprequest">sendXMLHttpRequest(req[, sendContent])</a>:</p>
|
||||
<blockquote>
|
||||
<p>Set an <tt class="docutils literal"><span class="pre">onreadystatechange</span></tt> handler on an <tt class="docutils literal"><span class="pre">XMLHttpRequest</span></tt> object
|
||||
and send it off. Will return a cancellable <a class="mochiref reference" href="#fn-deferred">Deferred</a> that will
|
||||
callback on success.</p>
|
||||
<p>Note that currently, only <tt class="docutils literal"><span class="pre">200</span></tt> (OK) and <tt class="docutils literal"><span class="pre">304</span></tt>
|
||||
(NOT_MODIFIED) are considered success codes at this time, other
|
||||
status codes will result in an errback with an <tt class="docutils literal"><span class="pre">XMLHttpRequestError</span></tt>.</p>
|
||||
<dl class="docutils">
|
||||
<dt><tt class="docutils literal"><span class="pre">req</span></tt>:</dt>
|
||||
<dd>An preconfigured <tt class="docutils literal"><span class="pre">XMLHttpRequest</span></tt> object (open has been called).</dd>
|
||||
<dt><tt class="docutils literal"><span class="pre">sendContent</span></tt>:</dt>
|
||||
<dd>Optional string or DOM content to send over the <tt class="docutils literal"><span class="pre">XMLHttpRequest</span></tt>.</dd>
|
||||
<dt><em>returns</em>:</dt>
|
||||
<dd><a class="mochiref reference" href="#fn-deferred">Deferred</a> that will callback with the <tt class="docutils literal"><span class="pre">XMLHttpRequest</span></tt>
|
||||
instance on success.</dd>
|
||||
</dl>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-succeed"></a>
|
||||
<a class="mochidef reference" href="#fn-succeed">succeed([result])</a>:</p>
|
||||
<blockquote>
|
||||
<p>Return a <a class="mochiref reference" href="#fn-deferred">Deferred</a> that has already had <tt class="docutils literal"><span class="pre">.callback(result)</span></tt>
|
||||
called.</p>
|
||||
<p>This is useful when you're writing synchronous code to an asynchronous
|
||||
interface: i.e., some code is calling you expecting a <a class="mochiref reference" href="#fn-deferred">Deferred</a>
|
||||
result, but you don't actually need to do anything asynchronous. Just
|
||||
return <tt class="docutils literal"><span class="pre">succeed(theResult)</span></tt>.</p>
|
||||
<p>See <tt class="docutils literal"><span class="pre">fail</span></tt> for a version of this function that uses a failing
|
||||
<a class="mochiref reference" href="#fn-deferred">Deferred</a> rather than a successful one.</p>
|
||||
<dl class="docutils">
|
||||
<dt><tt class="docutils literal"><span class="pre">result</span></tt>:</dt>
|
||||
<dd>The result to give to <a class="mochiref reference" href="#fn-deferred.prototype.callback">Deferred.prototype.callback(result)</a></dd>
|
||||
<dt><em>returns</em>:</dt>
|
||||
<dd>a <tt class="docutils literal"><span class="pre">new</span></tt> <a class="mochiref reference" href="#fn-deferred">Deferred</a></dd>
|
||||
</dl>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-wait"></a>
|
||||
<a class="mochidef reference" href="#fn-wait">wait(seconds[, res])</a>:</p>
|
||||
<blockquote>
|
||||
Return a new cancellable <a class="mochiref reference" href="#fn-deferred">Deferred</a> that will <tt class="docutils literal"><span class="pre">.callback(res)</span></tt>
|
||||
after at least <tt class="docutils literal"><span class="pre">seconds</span></tt> seconds have elapsed.</blockquote>
|
||||
</div>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h1><a id="see-also" name="see-also">See Also</a></h1>
|
||||
<table class="docutils footnote" frame="void" id="id7" rules="none">
|
||||
<colgroup><col class="label" /><col /></colgroup>
|
||||
<tbody valign="top">
|
||||
<tr><td class="label"><a class="fn-backref" href="#id1" name="id7">[1]</a></td><td>AJAX, Asynchronous JavaScript and XML: <a class="reference" href="http://en.wikipedia.org/wiki/AJAX">http://en.wikipedia.org/wiki/AJAX</a></td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<table class="docutils footnote" frame="void" id="id8" rules="none">
|
||||
<colgroup><col class="label" /><col /></colgroup>
|
||||
<tbody valign="top">
|
||||
<tr><td class="label"><a class="fn-backref" href="#id2" name="id8">[2]</a></td><td>Twisted, an event-driven networking framework written in Python: <a class="reference" href="http://twistedmatrix.com/">http://twistedmatrix.com/</a></td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<table class="docutils footnote" frame="void" id="id9" rules="none">
|
||||
<colgroup><col class="label" /><col /></colgroup>
|
||||
<tbody valign="top">
|
||||
<tr><td class="label"><a class="fn-backref" href="#id3" name="id9">[3]</a></td><td>Twisted Deferred Reference: <a class="reference" href="http://twistedmatrix.com/projects/core/documentation/howto/defer.html">http://twistedmatrix.com/projects/core/documentation/howto/defer.html</a></td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<table class="docutils footnote" frame="void" id="id10" rules="none">
|
||||
<colgroup><col class="label" /><col /></colgroup>
|
||||
<tbody valign="top">
|
||||
<tr><td class="label"><a name="id10">[4]</a></td><td><em>(<a class="fn-backref" href="#id4">1</a>, <a class="fn-backref" href="#id5">2</a>, <a class="fn-backref" href="#id6">3</a>)</em> JSON, JavaScript Object Notation: <a class="reference" href="http://json.org/">http://json.org/</a></td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h1><a id="authors" name="authors">Authors</a></h1>
|
||||
<ul class="simple">
|
||||
<li>Bob Ippolito <<a class="reference" href="mailto:bob@redivi.com">bob@redivi.com</a>></li>
|
||||
</ul>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h1><a id="copyright" name="copyright">Copyright</a></h1>
|
||||
<p>Copyright 2005 Bob Ippolito <<a class="reference" href="mailto:bob@redivi.com">bob@redivi.com</a>>. This program is dual-licensed
|
||||
free software; you can redistribute it and/or modify it under the terms of the
|
||||
<a class="reference" href="http://www.opensource.org/licenses/mit-license.php">MIT License</a> or the <a class="reference" href="http://www.opensource.org/licenses/afl-2.1.php">Academic Free License v2.1</a>.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,509 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8" ?>
|
||||
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
|
||||
|
||||
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
|
||||
<meta name="generator" content="Docutils 0.4: http://docutils.sourceforge.net/" />
|
||||
<title>MochiKit.Color - color abstraction with CSS3 support</title>
|
||||
|
||||
<link rel="stylesheet" href="../../../include/css/documentation.css" type="text/css" />
|
||||
<script type="text/javascript" src="../../../packed/lib/MochiKit/MochiKit.js"></script>
|
||||
<script type="text/javascript" src="../../js/toc.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div class="document">
|
||||
<div class="section">
|
||||
<h1><a id="name" name="name">Name</a></h1>
|
||||
<p>MochiKit.Color - color abstraction with CSS3 support</p>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h1><a id="synopsis" name="synopsis">Synopsis</a></h1>
|
||||
<pre class="literal-block">
|
||||
// RGB color expressions are supported
|
||||
assert(
|
||||
objEqual(Color.whiteColor(), Color.fromString("rgb(255,100%, 255)"))
|
||||
);
|
||||
|
||||
// So is instantiating directly from HSL or RGB values.
|
||||
// Note that fromRGB and fromHSL take numbers between 0.0 and 1.0!
|
||||
assert( objEqual(Color.fromRGB(1.0, 1.0, 1.0), Color.fromHSL(0.0, 0.0, 1.0) );
|
||||
|
||||
// Or even SVG color keyword names, as per CSS3!
|
||||
assert( Color.fromString("aquamarine"), "#7fffd4" );
|
||||
|
||||
// NSColor-like colors built in
|
||||
assert( Color.whiteColor().toHexString() == "#ffffff" );
|
||||
</pre>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h1><a id="description" name="description">Description</a></h1>
|
||||
<p>MochiKit.Color is an abstraction for handling colors and strings that
|
||||
represent colors.</p>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h1><a id="dependencies" name="dependencies">Dependencies</a></h1>
|
||||
<ul class="simple">
|
||||
<li><a class="mochiref reference" href="Base.html">MochiKit.Base</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h1><a id="overview" name="overview">Overview</a></h1>
|
||||
<p>MochiKit.Color provides an abstraction of RGB, HSL and HSV colors with alpha.
|
||||
It supports parsing and generating of CSS3 colors, and has a full CSS3 (SVG)
|
||||
color table.</p>
|
||||
<p>All of the functionality in this module is exposed through a Color constructor
|
||||
and its prototype, but a few of its internals are available for direct use at
|
||||
module level.</p>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h1><a id="api-reference" name="api-reference">API Reference</a></h1>
|
||||
<div class="section">
|
||||
<h2><a id="constructors" name="constructors">Constructors</a></h2>
|
||||
<p>
|
||||
<a name="fn-color"></a>
|
||||
<a class="mochidef reference" href="#fn-color">Color()</a>:</p>
|
||||
<blockquote>
|
||||
<p>Represents a color. Component values should be integers between <tt class="docutils literal"><span class="pre">0.0</span></tt>
|
||||
and <tt class="docutils literal"><span class="pre">1.0</span></tt>. You should use one of the <a class="mochiref reference" href="#fn-color">Color</a> factory
|
||||
functions such as <a class="mochiref reference" href="#fn-color.fromrgb">Color.fromRGB</a>, <a class="mochiref reference" href="#fn-color.fromhsl">Color.fromHSL</a>,
|
||||
etc. instead of constructing <a class="mochiref reference" href="#fn-color">Color</a> objects directly.</p>
|
||||
<p><a class="mochiref reference" href="#fn-color">Color</a> instances can be compared with
|
||||
<a class="mochiref reference" href="Base.html#fn-compare">MochiKit.Base.compare</a> (though ordering is on RGB, so is not
|
||||
particularly meaningful except for equality), and the default <tt class="docutils literal"><span class="pre">toString</span></tt>
|
||||
implementation returns <a class="mochiref reference" href="#fn-color.prototype.tohexstring">Color.prototype.toHexString()</a>.</p>
|
||||
<p><a class="mochiref reference" href="#fn-color">Color</a> instances are immutable, and much of the architecture is
|
||||
inspired by AppKit's NSColor <a class="footnote-reference" href="#id6" id="id1" name="id1">[1]</a></p>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-color.frombackground"></a>
|
||||
<a class="mochidef reference" href="#fn-color.frombackground">Color.fromBackground(elem)</a>:</p>
|
||||
<blockquote>
|
||||
<p>Returns a <a class="mochiref reference" href="#fn-color">Color</a> object based on the background of the provided
|
||||
element. Equivalent to:</p>
|
||||
<pre class="literal-block">
|
||||
c = Color.fromComputedStyle(
|
||||
elem, "backgroundColor", "background-color") || Color.whiteColor();
|
||||
</pre>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-color.fromcomputedstyle"></a>
|
||||
<a class="mochidef reference" href="#fn-color.fromcomputedstyle">Color.fromComputedStyle(elem, style, mozillaEquivalentCSS)</a>:</p>
|
||||
<blockquote>
|
||||
Returns a <a class="mochiref reference" href="#fn-color">Color</a> object based on the result of
|
||||
<a class="mochiref reference" href="DOM.html#fn-computedstyle">MochiKit.DOM.computedStyle(elem, style, mozillaEquivalentCSS)</a>
|
||||
or <tt class="docutils literal"><span class="pre">null</span></tt> if not found.</blockquote>
|
||||
<p>
|
||||
<a name="fn-color.fromhexstring"></a>
|
||||
<a class="mochidef reference" href="#fn-color.fromhexstring">Color.fromHexString(hexString)</a>:</p>
|
||||
<blockquote>
|
||||
Returns a <a class="mochiref reference" href="#fn-color">Color</a> object from the given hexadecimal color string.
|
||||
For example, <tt class="docutils literal"><span class="pre">"#FFFFFF"</span></tt> would return a <a class="mochiref reference" href="#fn-color">Color</a> with
|
||||
RGB values <tt class="docutils literal"><span class="pre">[255/255,</span> <span class="pre">255/255,</span> <span class="pre">255/255]</span></tt> (white).</blockquote>
|
||||
<p>
|
||||
<a name="fn-color.fromhsl"></a>
|
||||
<a class="mochidef reference" href="#fn-color.fromhsl">Color.fromHSL(hue, saturation, lightness, alpha=1.0)</a>:</p>
|
||||
<blockquote>
|
||||
<p>Return a <a class="mochiref reference" href="#fn-color">Color</a> object from the given <tt class="docutils literal"><span class="pre">hue</span></tt>, <tt class="docutils literal"><span class="pre">saturation</span></tt>,
|
||||
<tt class="docutils literal"><span class="pre">lightness</span></tt> values. Values should be numbers between <tt class="docutils literal"><span class="pre">0.0</span></tt> and
|
||||
<tt class="docutils literal"><span class="pre">1.0</span></tt>.</p>
|
||||
<p>If <tt class="docutils literal"><span class="pre">alpha</span></tt> is not given, then <tt class="docutils literal"><span class="pre">1.0</span></tt> (completely opaque) will be used.</p>
|
||||
<dl class="docutils">
|
||||
<dt>Alternate form:</dt>
|
||||
<dd><a class="mochiref reference" href="#fn-color.fromhsl">Color.fromHSL({h: hue, s: saturation, l: lightness, a: alpha})</a></dd>
|
||||
</dl>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-color.fromhslstring"></a>
|
||||
<a class="mochidef reference" href="#fn-color.fromhslstring">Color.fromHSLString(hslString)</a>:</p>
|
||||
<blockquote>
|
||||
Returns a <a class="mochiref reference" href="#fn-color">Color</a> object from the given decimal hsl color string.
|
||||
For example, <tt class="docutils literal"><span class="pre">"hsl(0,0%,100%)"</span></tt> would return a <a class="mochiref reference" href="#fn-color">Color</a> with
|
||||
HSL values <tt class="docutils literal"><span class="pre">[0/360,</span> <span class="pre">0/360,</span> <span class="pre">360/360]</span></tt> (white).</blockquote>
|
||||
<p>
|
||||
<a name="fn-color.fromhsv"></a>
|
||||
<a class="mochidef reference" href="#fn-color.fromhsv">Color.fromHSV(hue, saturation, value, alpha=1.0)</a>:</p>
|
||||
<blockquote>
|
||||
<p>Return a <a class="mochiref reference" href="#fn-color">Color</a> object from the given <tt class="docutils literal"><span class="pre">hue</span></tt>, <tt class="docutils literal"><span class="pre">saturation</span></tt>,
|
||||
<tt class="docutils literal"><span class="pre">value</span></tt> values. Values should be numbers between <tt class="docutils literal"><span class="pre">0.0</span></tt> and
|
||||
<tt class="docutils literal"><span class="pre">1.0</span></tt>.</p>
|
||||
<p>If <tt class="docutils literal"><span class="pre">alpha</span></tt> is not given, then <tt class="docutils literal"><span class="pre">1.0</span></tt> (completely opaque) will be used.</p>
|
||||
<dl class="docutils">
|
||||
<dt>Alternate form:</dt>
|
||||
<dd><a class="mochiref reference" href="#fn-color.fromhsv">Color.fromHSV({h: hue, s: saturation, v: value, a: alpha})</a></dd>
|
||||
</dl>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-color.fromname"></a>
|
||||
<a class="mochidef reference" href="#fn-color.fromname">Color.fromName(colorName)</a>:</p>
|
||||
<blockquote>
|
||||
Returns a <a class="mochiref reference" href="#fn-color">Color</a> object corresponding to the given
|
||||
SVG 1.0 color keyword name <a class="footnote-reference" href="#id7" id="id2" name="id2">[2]</a> as per the W3C CSS3
|
||||
Color Module <a class="footnote-reference" href="#id8" id="id3" name="id3">[3]</a>. <tt class="docutils literal"><span class="pre">"transparent"</span></tt> is also accepted
|
||||
as a color name, and will return <a class="mochiref reference" href="#fn-color.transparentcolor">Color.transparentColor()</a>.</blockquote>
|
||||
<p>
|
||||
<a name="fn-color.fromrgb"></a>
|
||||
<a class="mochidef reference" href="#fn-color.fromrgb">Color.fromRGB(red, green, blue, alpha=1.0)</a>:</p>
|
||||
<blockquote>
|
||||
<p>Return a <a class="mochiref reference" href="#fn-color">Color</a> object from the given <tt class="docutils literal"><span class="pre">red</span></tt>, <tt class="docutils literal"><span class="pre">green</span></tt>,
|
||||
<tt class="docutils literal"><span class="pre">blue</span></tt>, and <tt class="docutils literal"><span class="pre">alpha</span></tt> values. Values should be numbers between <tt class="docutils literal"><span class="pre">0</span></tt>
|
||||
and <tt class="docutils literal"><span class="pre">1.0</span></tt>.</p>
|
||||
<p>If <tt class="docutils literal"><span class="pre">alpha</span></tt> is not given, then <tt class="docutils literal"><span class="pre">1.0</span></tt> (completely opaque) will be used.</p>
|
||||
<dl class="docutils">
|
||||
<dt>Alternate form:</dt>
|
||||
<dd><a class="mochiref reference" href="#fn-color.fromrgb">Color.fromRGB({r: red, g: green, b: blue, a: alpha})</a></dd>
|
||||
</dl>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-color.fromrgbstring"></a>
|
||||
<a class="mochidef reference" href="#fn-color.fromrgbstring">Color.fromRGBString(rgbString)</a>:</p>
|
||||
<blockquote>
|
||||
Returns a <a class="mochiref reference" href="#fn-color">Color</a> object from the given decimal rgb color string.
|
||||
For example, <tt class="docutils literal"><span class="pre">"rgb(255,255,255)"</span></tt> would return a <a class="mochiref reference" href="#fn-color">Color</a> with
|
||||
RGB values <tt class="docutils literal"><span class="pre">[255/255,</span> <span class="pre">255/255,</span> <span class="pre">255/255]</span></tt> (white).</blockquote>
|
||||
<p>
|
||||
<a name="fn-color.fromtext"></a>
|
||||
<a class="mochidef reference" href="#fn-color.fromtext">Color.fromText(elem)</a>:</p>
|
||||
<blockquote>
|
||||
<p>Returns a <a class="mochiref reference" href="#fn-color">Color</a> object based on the text color of the provided
|
||||
element. Equivalent to:</p>
|
||||
<pre class="literal-block">
|
||||
c = Color.fromComputedStyle(elem, "color") || Color.whiteColor();
|
||||
</pre>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-color.fromstring"></a>
|
||||
<a class="mochidef reference" href="#fn-color.fromstring">Color.fromString(rgbOrHexString)</a>:</p>
|
||||
<blockquote>
|
||||
<p>Returns a <a class="mochiref reference" href="#fn-color">Color</a> object from the given RGB, HSL, hex, or name.
|
||||
Will return <tt class="docutils literal"><span class="pre">null</span></tt> if the string can not be parsed by any of these
|
||||
methods.</p>
|
||||
<p>See <a class="mochiref reference" href="#fn-color.fromhexstring">Color.fromHexString</a>, <a class="mochiref reference" href="#fn-color.fromrgbstring">Color.fromRGBString</a>,
|
||||
<a class="mochiref reference" href="#fn-color.fromhslstring">Color.fromHSLString</a> and <a class="mochiref reference" href="#fn-color.fromname">Color.fromName</a> more
|
||||
information.</p>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-color.namedcolors"></a>
|
||||
<a class="mochidef reference" href="#fn-color.namedcolors">Color.namedColors()</a>:</p>
|
||||
<blockquote>
|
||||
Returns an object with properties for each SVG 1.0 color keyword
|
||||
name <a class="footnote-reference" href="#id7" id="id4" name="id4">[2]</a> supported by CSS3 <a class="footnote-reference" href="#id8" id="id5" name="id5">[3]</a>. Property names are the color keyword
|
||||
name in lowercase, and the value is a string suitable for
|
||||
<a class="mochiref reference" href="#fn-color.fromstring">Color.fromString()</a>.</blockquote>
|
||||
<p>
|
||||
<a name="fn-color.prototype.colorwithalpha"></a>
|
||||
<a class="mochidef reference" href="#fn-color.prototype.colorwithalpha">Color.prototype.colorWithAlpha(alpha)</a>:</p>
|
||||
<blockquote>
|
||||
Return a new <a class="mochiref reference" href="#fn-color">Color</a> based on this color, but with the provided
|
||||
<tt class="docutils literal"><span class="pre">alpha</span></tt> value.</blockquote>
|
||||
<p>
|
||||
<a name="fn-color.prototype.colorwithhue"></a>
|
||||
<a class="mochidef reference" href="#fn-color.prototype.colorwithhue">Color.prototype.colorWithHue(hue)</a>:</p>
|
||||
<blockquote>
|
||||
Return a new <a class="mochiref reference" href="#fn-color">Color</a> based on this color, but with the provided
|
||||
<tt class="docutils literal"><span class="pre">hue</span></tt> value.</blockquote>
|
||||
<p>
|
||||
<a name="fn-color.prototype.colorwithsaturation"></a>
|
||||
<a class="mochidef reference" href="#fn-color.prototype.colorwithsaturation">Color.prototype.colorWithSaturation(saturation)</a>:</p>
|
||||
<blockquote>
|
||||
Return a new <a class="mochiref reference" href="#fn-color">Color</a> based on this color, but with the provided
|
||||
<tt class="docutils literal"><span class="pre">saturation</span></tt> value (using the HSL color model).</blockquote>
|
||||
<p>
|
||||
<a name="fn-color.prototype.colorwithlightness"></a>
|
||||
<a class="mochidef reference" href="#fn-color.prototype.colorwithlightness">Color.prototype.colorWithLightness(lightness)</a>:</p>
|
||||
<blockquote>
|
||||
Return a new <a class="mochiref reference" href="#fn-color">Color</a> based on this color, but with the provided
|
||||
<tt class="docutils literal"><span class="pre">lightness</span></tt> value.</blockquote>
|
||||
<p>
|
||||
<a name="fn-color.prototype.darkercolorwithlevel"></a>
|
||||
<a class="mochidef reference" href="#fn-color.prototype.darkercolorwithlevel">Color.prototype.darkerColorWithLevel(level)</a>:</p>
|
||||
<blockquote>
|
||||
Return a new <a class="mochiref reference" href="#fn-color">Color</a> based on this color, but darker by the given
|
||||
<tt class="docutils literal"><span class="pre">level</span></tt> (between <tt class="docutils literal"><span class="pre">0</span></tt> and <tt class="docutils literal"><span class="pre">1.0</span></tt>).</blockquote>
|
||||
<p>
|
||||
<a name="fn-color.prototype.lightercolorwithlevel"></a>
|
||||
<a class="mochidef reference" href="#fn-color.prototype.lightercolorwithlevel">Color.prototype.lighterColorWithLevel(level)</a>:</p>
|
||||
<blockquote>
|
||||
Return a new <a class="mochiref reference" href="#fn-color">Color</a> based on this color, but lighter by the given
|
||||
<tt class="docutils literal"><span class="pre">level</span></tt> (between <tt class="docutils literal"><span class="pre">0</span></tt> and <tt class="docutils literal"><span class="pre">1.0</span></tt>).</blockquote>
|
||||
<p>
|
||||
<a name="fn-color.prototype.blendedcolor"></a>
|
||||
<a class="mochidef reference" href="#fn-color.prototype.blendedcolor">Color.prototype.blendedColor(other, fraction=0.5)</a>:</p>
|
||||
<blockquote>
|
||||
Return a new <a class="mochiref reference" href="#fn-color">Color</a> whose RGBA component values are a weighted sum
|
||||
of this color and <tt class="docutils literal"><span class="pre">other</span></tt>. Each component of the returned color
|
||||
is the <tt class="docutils literal"><span class="pre">fraction</span></tt> of other's value plus <tt class="docutils literal"><span class="pre">1</span> <span class="pre">-</span> <span class="pre">fraction</span></tt> of this
|
||||
color's.</blockquote>
|
||||
<p>
|
||||
<a name="fn-color.prototype.islight"></a>
|
||||
<a class="mochidef reference" href="#fn-color.prototype.islight">Color.prototype.isLight()</a>:</p>
|
||||
<blockquote>
|
||||
<p>Return <tt class="docutils literal"><span class="pre">true</span></tt> if the lightness value of this color is greater than
|
||||
<tt class="docutils literal"><span class="pre">0.5</span></tt>.</p>
|
||||
<p>Note that <tt class="docutils literal"><span class="pre">alpha</span></tt> is ignored for this calculation (color components
|
||||
are not premultiplied).</p>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-color.prototype.isdark"></a>
|
||||
<a class="mochidef reference" href="#fn-color.prototype.isdark">Color.prototype.isDark()</a>:</p>
|
||||
<blockquote>
|
||||
<p>Return <tt class="docutils literal"><span class="pre">true</span></tt> if the lightness value of this color is less than or
|
||||
equal to <tt class="docutils literal"><span class="pre">0.5</span></tt>.</p>
|
||||
<p>Note that <tt class="docutils literal"><span class="pre">alpha</span></tt> is ignored for this calculation (color components
|
||||
are not premultiplied).</p>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-color.prototype.torgbstring"></a>
|
||||
<a class="mochidef reference" href="#fn-color.prototype.torgbstring">Color.prototype.toRGBString()</a>:</p>
|
||||
<blockquote>
|
||||
<p>Return the decimal <tt class="docutils literal"><span class="pre">"rgb(red,</span> <span class="pre">green,</span> <span class="pre">blue)"</span></tt> string representation of this
|
||||
color.</p>
|
||||
<p>If the alpha component is not <tt class="docutils literal"><span class="pre">1.0</span></tt> (fully opaque), the
|
||||
<tt class="docutils literal"><span class="pre">"rgba(red,</span> <span class="pre">green,</span> <span class="pre">blue,</span> <span class="pre">alpha)"</span></tt> string representation will be used.</p>
|
||||
<p>For example:</p>
|
||||
<pre class="literal-block">
|
||||
assert( Color.whiteColor().toRGBString() == "rgb(255,255,255)" );
|
||||
</pre>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-color.prototype.tohslstring"></a>
|
||||
<a class="mochidef reference" href="#fn-color.prototype.tohslstring">Color.prototype.toHSLString()</a>:</p>
|
||||
<blockquote>
|
||||
<p>Return the decimal <tt class="docutils literal"><span class="pre">"hsl(hue,</span> <span class="pre">saturation,</span> <span class="pre">lightness)"</span></tt>
|
||||
string representation of this color.</p>
|
||||
<p>If the alpha component is not <tt class="docutils literal"><span class="pre">1.0</span></tt> (fully opaque), the
|
||||
<tt class="docutils literal"><span class="pre">"hsla(hue,</span> <span class="pre">saturation,</span> <span class="pre">lightness,</span> <span class="pre">alpha)"</span></tt> string representation
|
||||
will be used.</p>
|
||||
<p>For example:</p>
|
||||
<pre class="literal-block">
|
||||
assert( Color.whiteColor().toHSLString() == "hsl(0,0,360)" );
|
||||
</pre>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-color.prototype.tohexstring"></a>
|
||||
<a class="mochidef reference" href="#fn-color.prototype.tohexstring">Color.prototype.toHexString()</a>:</p>
|
||||
<blockquote>
|
||||
<p>Return the hexadecimal <tt class="docutils literal"><span class="pre">"#RRGGBB"</span></tt> string representation of this color.</p>
|
||||
<p>Note that the alpha component is completely ignored for hexadecimal
|
||||
string representations!</p>
|
||||
<p>For example:</p>
|
||||
<pre class="literal-block">
|
||||
assert( Color.whiteColor().toHexString() == "#FFFFFF" );
|
||||
</pre>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-color.prototype.asrgb"></a>
|
||||
<a class="mochidef reference" href="#fn-color.prototype.asrgb">Color.prototype.asRGB()</a>:</p>
|
||||
<blockquote>
|
||||
Return the RGB (red, green, blue, alpha) components of this color as an
|
||||
object with <tt class="docutils literal"><span class="pre">r</span></tt>, <tt class="docutils literal"><span class="pre">g</span></tt>, <tt class="docutils literal"><span class="pre">b</span></tt>, and <tt class="docutils literal"><span class="pre">a</span></tt> properties that have
|
||||
values between <tt class="docutils literal"><span class="pre">0.0</span></tt> and <tt class="docutils literal"><span class="pre">1.0</span></tt>.</blockquote>
|
||||
<p>
|
||||
<a name="fn-color.prototype.ashsl"></a>
|
||||
<a class="mochidef reference" href="#fn-color.prototype.ashsl">Color.prototype.asHSL()</a>:</p>
|
||||
<blockquote>
|
||||
Return the HSL (hue, saturation, lightness, alpha) components of this
|
||||
color as an object with <tt class="docutils literal"><span class="pre">h</span></tt>, <tt class="docutils literal"><span class="pre">s</span></tt>, <tt class="docutils literal"><span class="pre">l</span></tt> and <tt class="docutils literal"><span class="pre">a</span></tt> properties
|
||||
that have values between <tt class="docutils literal"><span class="pre">0.0</span></tt> and <tt class="docutils literal"><span class="pre">1.0</span></tt>.</blockquote>
|
||||
<p>
|
||||
<a name="fn-color.prototype.ashsv"></a>
|
||||
<a class="mochidef reference" href="#fn-color.prototype.ashsv">Color.prototype.asHSV()</a>:</p>
|
||||
<blockquote>
|
||||
Return the HSV (hue, saturation, value, alpha) components of this
|
||||
color as an object with <tt class="docutils literal"><span class="pre">h</span></tt>, <tt class="docutils literal"><span class="pre">s</span></tt>, <tt class="docutils literal"><span class="pre">v</span></tt> and <tt class="docutils literal"><span class="pre">a</span></tt> properties
|
||||
that have values between <tt class="docutils literal"><span class="pre">0.0</span></tt> and <tt class="docutils literal"><span class="pre">1.0</span></tt>.</blockquote>
|
||||
<p>
|
||||
<a name="fn-color.blackcolor"></a>
|
||||
<a class="mochidef reference" href="#fn-color.blackcolor">Color.blackColor()</a>:</p>
|
||||
<blockquote>
|
||||
Return a <a class="mochiref reference" href="#fn-color">Color</a> object whose RGB values are 0, 0, 0
|
||||
(#000000).</blockquote>
|
||||
<p>
|
||||
<a name="fn-color.bluecolor"></a>
|
||||
<a class="mochidef reference" href="#fn-color.bluecolor">Color.blueColor()</a>:</p>
|
||||
<blockquote>
|
||||
Return a <a class="mochiref reference" href="#fn-color">Color</a> object whose RGB values are 0, 0, 1
|
||||
(#0000ff).</blockquote>
|
||||
<p>
|
||||
<a name="fn-color.browncolor"></a>
|
||||
<a class="mochidef reference" href="#fn-color.browncolor">Color.brownColor()</a>:</p>
|
||||
<blockquote>
|
||||
Return a <a class="mochiref reference" href="#fn-color">Color</a> object whose RGB values are 0.6, 0.4, 0.2
|
||||
(#996633).</blockquote>
|
||||
<p>
|
||||
<a name="fn-color.cyancolor"></a>
|
||||
<a class="mochidef reference" href="#fn-color.cyancolor">Color.cyanColor()</a>:</p>
|
||||
<blockquote>
|
||||
Return a <a class="mochiref reference" href="#fn-color">Color</a> object whose RGB values are 0, 1, 1
|
||||
(#00ffff).</blockquote>
|
||||
<p>
|
||||
<a name="fn-color.darkgraycolor"></a>
|
||||
<a class="mochidef reference" href="#fn-color.darkgraycolor">Color.darkGrayColor()</a>:</p>
|
||||
<blockquote>
|
||||
Return a <a class="mochiref reference" href="#fn-color">Color</a> object whose RGB values are 1/3, 1/3, 1/3
|
||||
(#555555).</blockquote>
|
||||
<p>
|
||||
<a name="fn-color.graycolor"></a>
|
||||
<a class="mochidef reference" href="#fn-color.graycolor">Color.grayColor()</a>:</p>
|
||||
<blockquote>
|
||||
Return a <a class="mochiref reference" href="#fn-color">Color</a> object whose RGB values are 0.5, 0.5, 0.5
|
||||
(#808080).</blockquote>
|
||||
<p>
|
||||
<a name="fn-color.greencolor"></a>
|
||||
<a class="mochidef reference" href="#fn-color.greencolor">Color.greenColor()</a>:</p>
|
||||
<blockquote>
|
||||
Return a <a class="mochiref reference" href="#fn-color">Color</a> object whose RGB values are 0, 1, 0.
|
||||
(#00ff00).</blockquote>
|
||||
<p>
|
||||
<a name="fn-color.lightgraycolor"></a>
|
||||
<a class="mochidef reference" href="#fn-color.lightgraycolor">Color.lightGrayColor()</a>:</p>
|
||||
<blockquote>
|
||||
Return a <a class="mochiref reference" href="#fn-color">Color</a> object whose RGB values are 2/3, 2/3, 2/3
|
||||
(#aaaaaa).</blockquote>
|
||||
<p>
|
||||
<a name="fn-color.magentacolor"></a>
|
||||
<a class="mochidef reference" href="#fn-color.magentacolor">Color.magentaColor()</a>:</p>
|
||||
<blockquote>
|
||||
Return a <a class="mochiref reference" href="#fn-color">Color</a> object whose RGB values are 1, 0, 1
|
||||
(#ff00ff).</blockquote>
|
||||
<p>
|
||||
<a name="fn-color.orangecolor"></a>
|
||||
<a class="mochidef reference" href="#fn-color.orangecolor">Color.orangeColor()</a>:</p>
|
||||
<blockquote>
|
||||
Return a <a class="mochiref reference" href="#fn-color">Color</a> object whose RGB values are 1, 0.5, 0
|
||||
(#ff8000).</blockquote>
|
||||
<p>
|
||||
<a name="fn-color.purplecolor"></a>
|
||||
<a class="mochidef reference" href="#fn-color.purplecolor">Color.purpleColor()</a>:</p>
|
||||
<blockquote>
|
||||
Return a <a class="mochiref reference" href="#fn-color">Color</a> object whose RGB values are 0.5, 0, 0.5
|
||||
(#800080).</blockquote>
|
||||
<p>
|
||||
<a name="fn-color.redcolor"></a>
|
||||
<a class="mochidef reference" href="#fn-color.redcolor">Color.redColor()</a>:</p>
|
||||
<blockquote>
|
||||
Return a <a class="mochiref reference" href="#fn-color">Color</a> object whose RGB values are 1, 0, 0
|
||||
(#ff0000).</blockquote>
|
||||
<p>
|
||||
<a name="fn-color.whitecolor"></a>
|
||||
<a class="mochidef reference" href="#fn-color.whitecolor">Color.whiteColor()</a>:</p>
|
||||
<blockquote>
|
||||
Return a <a class="mochiref reference" href="#fn-color">Color</a> object whose RGB values are 1, 1, 1
|
||||
(#ffffff).</blockquote>
|
||||
<p>
|
||||
<a name="fn-color.yellowcolor"></a>
|
||||
<a class="mochidef reference" href="#fn-color.yellowcolor">Color.yellowColor()</a>:</p>
|
||||
<blockquote>
|
||||
Return a <a class="mochiref reference" href="#fn-color">Color</a> object whose RGB values are 1, 1, 0
|
||||
(#ffff00).</blockquote>
|
||||
<p>
|
||||
<a name="fn-color.transparentcolor"></a>
|
||||
<a class="mochidef reference" href="#fn-color.transparentcolor">Color.transparentColor()</a>:</p>
|
||||
<blockquote>
|
||||
Return a <a class="mochiref reference" href="#fn-color">Color</a> object that is completely transparent
|
||||
(has alpha component of 0).</blockquote>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h2><a id="functions" name="functions">Functions</a></h2>
|
||||
<p>
|
||||
<a name="fn-clampcolorcomponent"></a>
|
||||
<a class="mochidef reference" href="#fn-clampcolorcomponent">clampColorComponent(num, scale)</a>:</p>
|
||||
<blockquote>
|
||||
<p>Returns <tt class="docutils literal"><span class="pre">num</span> <span class="pre">*</span> <span class="pre">scale</span></tt> clamped between <tt class="docutils literal"><span class="pre">0</span></tt> and <tt class="docutils literal"><span class="pre">scale</span></tt>.</p>
|
||||
<p><a class="mochiref reference" href="#fn-clampcolorcomponent">clampColorComponent</a> is not exported by default when using JSAN.</p>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-hsltorgb"></a>
|
||||
<a class="mochidef reference" href="#fn-hsltorgb">hslToRGB(hue, saturation, lightness, alpha)</a>:</p>
|
||||
<blockquote>
|
||||
<p>Computes RGB values from the provided HSL values. The return value is a
|
||||
mapping with <tt class="docutils literal"><span class="pre">"r"</span></tt>, <tt class="docutils literal"><span class="pre">"g"</span></tt>, <tt class="docutils literal"><span class="pre">"b"</span></tt> and <tt class="docutils literal"><span class="pre">"a"</span></tt> keys.</p>
|
||||
<dl class="docutils">
|
||||
<dt>Alternate form:</dt>
|
||||
<dd><a class="mochiref reference" href="#fn-hsltorgb">hslToRGB({h: hue, s: saturation, l: lightness, a: alpha})</a>.</dd>
|
||||
</dl>
|
||||
<p><a class="mochiref reference" href="#fn-hsltorgb">hslToRGB</a> is not exported by default when using JSAN.</p>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-hsvtorgb"></a>
|
||||
<a class="mochidef reference" href="#fn-hsvtorgb">hsvToRGB(hue, saturation, value, alpha)</a>:</p>
|
||||
<blockquote>
|
||||
<p>Computes RGB values from the provided HSV values. The return value is a
|
||||
mapping with <tt class="docutils literal"><span class="pre">"r"</span></tt>, <tt class="docutils literal"><span class="pre">"g"</span></tt>, <tt class="docutils literal"><span class="pre">"b"</span></tt> and <tt class="docutils literal"><span class="pre">"a"</span></tt> keys.</p>
|
||||
<dl class="docutils">
|
||||
<dt>Alternate form:</dt>
|
||||
<dd><a class="mochiref reference" href="#fn-hsvtorgb">hsvToRGB({h: hue, s: saturation, v: value, a: alpha})</a>.</dd>
|
||||
</dl>
|
||||
<p><a class="mochiref reference" href="#fn-hsvtorgb">hsvToRGB</a> is not exported by default when using JSAN.</p>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-tocolorpart"></a>
|
||||
<a class="mochidef reference" href="#fn-tocolorpart">toColorPart(num)</a>:</p>
|
||||
<blockquote>
|
||||
<p>Convert num to a zero padded hexadecimal digit for use in a hexadecimal
|
||||
color string. Num should be an integer between <tt class="docutils literal"><span class="pre">0</span></tt> and <tt class="docutils literal"><span class="pre">255</span></tt>.</p>
|
||||
<p><a class="mochiref reference" href="#fn-tocolorpart">toColorPart</a> is not exported by default when using JSAN.</p>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-rgbtohsl"></a>
|
||||
<a class="mochidef reference" href="#fn-rgbtohsl">rgbToHSL(red, green, blue, alpha)</a>:</p>
|
||||
<blockquote>
|
||||
<p>Computes HSL values based on the provided RGB values. The return value is
|
||||
a mapping with <tt class="docutils literal"><span class="pre">"h"</span></tt>, <tt class="docutils literal"><span class="pre">"s"</span></tt>, <tt class="docutils literal"><span class="pre">"l"</span></tt> and <tt class="docutils literal"><span class="pre">"a"</span></tt> keys.</p>
|
||||
<dl class="docutils">
|
||||
<dt>Alternate form:</dt>
|
||||
<dd><a class="mochiref reference" href="#fn-rgbtohsl">rgbToHSL({r: red, g: green, b: blue, a: alpha})</a>.</dd>
|
||||
</dl>
|
||||
<p><a class="mochiref reference" href="#fn-rgbtohsl">rgbToHSL</a> is not exported by default when using JSAN.</p>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-rgbtohsv"></a>
|
||||
<a class="mochidef reference" href="#fn-rgbtohsv">rgbToHSV(red, green, blue, alpha)</a>:</p>
|
||||
<blockquote>
|
||||
<p>Computes HSV values based on the provided RGB values. The return value is
|
||||
a mapping with <tt class="docutils literal"><span class="pre">"h"</span></tt>, <tt class="docutils literal"><span class="pre">"s"</span></tt>, <tt class="docutils literal"><span class="pre">"v"</span></tt> and <tt class="docutils literal"><span class="pre">"a"</span></tt> keys.</p>
|
||||
<dl class="docutils">
|
||||
<dt>Alternate form:</dt>
|
||||
<dd><a class="mochiref reference" href="#fn-rgbtohsv">rgbToHSV({r: red, g: green, b: blue, a: alpha})</a>.</dd>
|
||||
</dl>
|
||||
<p><a class="mochiref reference" href="#fn-rgbtohsv">rgbToHSV</a> is not exported by default when using JSAN.</p>
|
||||
</blockquote>
|
||||
</div>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h1><a id="see-also" name="see-also">See Also</a></h1>
|
||||
<table class="docutils footnote" frame="void" id="id6" rules="none">
|
||||
<colgroup><col class="label" /><col /></colgroup>
|
||||
<tbody valign="top">
|
||||
<tr><td class="label"><a class="fn-backref" href="#id1" name="id6">[1]</a></td><td>Application Kit Reference - NSColor: <a class="reference" href="http://developer.apple.com/documentation/Cocoa/Reference/ApplicationKit/ObjC_classic/Classes/NSColor.html">http://developer.apple.com/documentation/Cocoa/Reference/ApplicationKit/ObjC_classic/Classes/NSColor.html</a></td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<table class="docutils footnote" frame="void" id="id7" rules="none">
|
||||
<colgroup><col class="label" /><col /></colgroup>
|
||||
<tbody valign="top">
|
||||
<tr><td class="label"><a name="id7">[2]</a></td><td><em>(<a class="fn-backref" href="#id2">1</a>, <a class="fn-backref" href="#id4">2</a>)</em> SVG 1.0 color keywords: <a class="reference" href="http://www.w3.org/TR/SVG/types.html#ColorKeywords">http://www.w3.org/TR/SVG/types.html#ColorKeywords</a></td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<table class="docutils footnote" frame="void" id="id8" rules="none">
|
||||
<colgroup><col class="label" /><col /></colgroup>
|
||||
<tbody valign="top">
|
||||
<tr><td class="label"><a name="id8">[3]</a></td><td><em>(<a class="fn-backref" href="#id3">1</a>, <a class="fn-backref" href="#id5">2</a>)</em> W3C CSS3 Color Module: <a class="reference" href="http://www.w3.org/TR/css3-color/#svg-color">http://www.w3.org/TR/css3-color/#svg-color</a></td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h1><a id="authors" name="authors">Authors</a></h1>
|
||||
<ul class="simple">
|
||||
<li>Bob Ippolito <<a class="reference" href="mailto:bob@redivi.com">bob@redivi.com</a>></li>
|
||||
</ul>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h1><a id="copyright" name="copyright">Copyright</a></h1>
|
||||
<p>Copyright 2005 Bob Ippolito <<a class="reference" href="mailto:bob@redivi.com">bob@redivi.com</a>>. This program is dual-licensed
|
||||
free software; you can redistribute it and/or modify it under the terms of the
|
||||
<a class="reference" href="http://www.opensource.org/licenses/mit-license.php">MIT License</a> or the <a class="reference" href="http://www.opensource.org/licenses/afl-2.1.php">Academic Free License v2.1</a>.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,798 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8" ?>
|
||||
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
|
||||
|
||||
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
|
||||
<meta name="generator" content="Docutils 0.4: http://docutils.sourceforge.net/" />
|
||||
<title>MochiKit.DOM - painless DOM manipulation API</title>
|
||||
|
||||
<link rel="stylesheet" href="../../../include/css/documentation.css" type="text/css" />
|
||||
<script type="text/javascript" src="../../../packed/lib/MochiKit/MochiKit.js"></script>
|
||||
<script type="text/javascript" src="../../js/toc.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div class="document">
|
||||
<div class="section">
|
||||
<h1><a id="name" name="name">Name</a></h1>
|
||||
<p>MochiKit.DOM - painless DOM manipulation API</p>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h1><a id="synopsis" name="synopsis">Synopsis</a></h1>
|
||||
<pre class="literal-block">
|
||||
var rows = [
|
||||
["dataA1", "dataA2", "dataA3"],
|
||||
["dataB1", "dataB2", "dataB3"]
|
||||
];
|
||||
row_display = function (row) {
|
||||
return TR(null, map(partial(TD, null), row));
|
||||
}
|
||||
var newTable = TABLE({'class': 'prettytable'},
|
||||
THEAD(null,
|
||||
row_display(["head1", "head2", "head3"])),
|
||||
TFOOT(null,
|
||||
row_display(["foot1", "foot2", "foot3"])),
|
||||
TBODY(null,
|
||||
map(row_display, rows)));
|
||||
// put that in your document.createElement and smoke it!
|
||||
swapDOM(oldTable, newTable);
|
||||
</pre>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h1><a id="description" name="description">Description</a></h1>
|
||||
<p>As you probably know, the DOM APIs are some of the most painful Java-inspired
|
||||
APIs you'll run across from a highly dynamic language. Don't worry about that
|
||||
though, because they provide a reasonable basis to build something that
|
||||
sucks a lot less.</p>
|
||||
<p>MochiKit.DOM takes much of its inspiration from Nevow's <a class="footnote-reference" href="#id5" id="id1" name="id1">[1]</a> stan <a class="footnote-reference" href="#id6" id="id2" name="id2">[2]</a>.
|
||||
This means you choose a tag, give it some attributes, then stuff it full
|
||||
of <em>whatever objects you want</em>. MochiKit.DOM isn't stupid, it knows that
|
||||
a string should be a text node, and that you want functions to be called,
|
||||
and that <tt class="docutils literal"><span class="pre">Array</span></tt>-like objects should be expanded, and stupid <tt class="docutils literal"><span class="pre">null</span></tt> values
|
||||
should be skipped.</p>
|
||||
<p>Hell, it will let you return strings from functions, and use iterators from
|
||||
<a class="mochiref reference" href="Iter.html">MochiKit.Iter</a>. If that's not enough, just teach it new tricks with
|
||||
<a class="mochiref reference" href="#fn-registerdomconverter">registerDOMConverter</a>. If you have never used an API like this for
|
||||
creating DOM elements, you've been wasting your damn time. Get with it!</p>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h1><a id="dependencies" name="dependencies">Dependencies</a></h1>
|
||||
<ul class="simple">
|
||||
<li><a class="mochiref reference" href="Base.html">MochiKit.Base</a></li>
|
||||
<li><a class="mochiref reference" href="Iter.html">MochiKit.Iter</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h1><a id="overview" name="overview">Overview</a></h1>
|
||||
<div class="section">
|
||||
<h2><a id="dom-coercion-rules" name="dom-coercion-rules">DOM Coercion Rules</a></h2>
|
||||
<p>In order of precedence, <a class="mochiref reference" href="#fn-createdom">createDOM</a> coerces given arguments to DOM
|
||||
nodes using the following rules:</p>
|
||||
<ol class="arabic simple">
|
||||
<li>Functions are called with a <tt class="docutils literal"><span class="pre">this</span></tt> of the parent
|
||||
node and their return value is subject to the
|
||||
following rules (even this one).</li>
|
||||
<li><tt class="docutils literal"><span class="pre">undefined</span></tt> and <tt class="docutils literal"><span class="pre">null</span></tt> are ignored.</li>
|
||||
<li>Iterables (see <a class="mochiref reference" href="Iter.html">MochiKit.Iter</a>) are flattened
|
||||
(as if they were passed in-line as nodes) and each
|
||||
return value is subject to all of these rules.</li>
|
||||
<li>Values that look like DOM nodes (objects with a
|
||||
<tt class="docutils literal"><span class="pre">.nodeType</span> <span class="pre">></span> <span class="pre">0</span></tt>) are <tt class="docutils literal"><span class="pre">.appendChild</span></tt>'ed to the created
|
||||
DOM fragment.</li>
|
||||
<li>Strings are wrapped up with <tt class="docutils literal"><span class="pre">document.createTextNode</span></tt></li>
|
||||
<li>Objects that are not strings are run through the <tt class="docutils literal"><span class="pre">domConverters</span></tt>
|
||||
<a class="mochiref reference" href="Base.html#fn-adapterregistry">MochiKit.Base.AdapterRegistry</a>
|
||||
(see <a class="mochiref reference" href="#fn-registerdomconverter">registerDOMConverter</a>).
|
||||
The value returned by the adapter is subject to these same rules (e.g.
|
||||
adapters are allowed to return a string, which will be coerced into a
|
||||
text node).</li>
|
||||
<li>If no adapter is available, <tt class="docutils literal"><span class="pre">.toString()</span></tt> is used to create a text node.</li>
|
||||
</ol>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h2><a id="creating-dom-element-trees" name="creating-dom-element-trees">Creating DOM Element Trees</a></h2>
|
||||
<p><a class="mochiref reference" href="#fn-createdom">createDOM</a> provides you with an excellent facility for creating DOM trees
|
||||
that is easy on the wrists. One of the best ways to understand how to use
|
||||
it is to take a look at an example:</p>
|
||||
<pre class="literal-block">
|
||||
var rows = [
|
||||
["dataA1", "dataA2", "dataA3"],
|
||||
["dataB1", "dataB2", "dataB3"]
|
||||
];
|
||||
row_display = function (row) {
|
||||
return TR(null, map(partial(TD, null), row));
|
||||
}
|
||||
var newTable = TABLE({'class': 'prettytable'},
|
||||
THEAD(null,
|
||||
row_display(["head1", "head2", "head3"])),
|
||||
TFOOT(null,
|
||||
row_display(["foot1", "foot2", "foot3"])),
|
||||
TBODY(null,
|
||||
map(row_display, rows)));
|
||||
</pre>
|
||||
<p>This will create a table with the following visual layout (if it
|
||||
were inserted into the document DOM):</p>
|
||||
<blockquote>
|
||||
<table border="1" class="docutils">
|
||||
<colgroup>
|
||||
<col width="33%" />
|
||||
<col width="33%" />
|
||||
<col width="33%" />
|
||||
</colgroup>
|
||||
<thead valign="bottom">
|
||||
<tr><th class="head">head1</th>
|
||||
<th class="head">head2</th>
|
||||
<th class="head">head3</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody valign="top">
|
||||
<tr><td>dataA1</td>
|
||||
<td>dataA2</td>
|
||||
<td>dataA3</td>
|
||||
</tr>
|
||||
<tr><td>dataB1</td>
|
||||
<td>dataB2</td>
|
||||
<td>dataB3</td>
|
||||
</tr>
|
||||
<tr><td>foot1</td>
|
||||
<td>foot2</td>
|
||||
<td>foot3</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</blockquote>
|
||||
<p>Corresponding to the following HTML:</p>
|
||||
<pre class="literal-block">
|
||||
<table class="prettytable">
|
||||
<thead>
|
||||
<tr>
|
||||
<td>head1</td>
|
||||
<td>head2</td>
|
||||
<td>head3</td>
|
||||
</tr>
|
||||
</thead>
|
||||
<tfoot>
|
||||
<tr>
|
||||
<td>foot1</td>
|
||||
<td>foot2</td>
|
||||
<td>foot3</td>
|
||||
</tr>
|
||||
</tfoot>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td>dataA1</td>
|
||||
<td>dataA2</td>
|
||||
<td>dataA3</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>dataB1</td>
|
||||
<td>dataB2</td>
|
||||
<td>dataB3</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</pre>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h2><a id="dom-context" name="dom-context">DOM Context</a></h2>
|
||||
<p>In order to prevent having to pass a <tt class="docutils literal"><span class="pre">window</span></tt> and/or <tt class="docutils literal"><span class="pre">document</span></tt>
|
||||
variable to every MochiKit.DOM function (e.g. when working with a
|
||||
child window), MochiKit.DOM maintains a context variable for each
|
||||
of them. They are managed with the <a class="mochiref reference" href="#fn-withwindow">withWindow</a> and
|
||||
<a class="mochiref reference" href="#fn-withdocument">withDocument</a> functions, and can be acquired with
|
||||
<a class="mochiref reference" href="#fn-currentwindow">currentWindow()</a> and <a class="mochiref reference" href="#fn-currentdocument">currentDocument()</a></p>
|
||||
<p>For example, if you are creating DOM nodes in a child window, you
|
||||
could do something like this:</p>
|
||||
<pre class="literal-block">
|
||||
withWindow(child, function () {
|
||||
var doc = currentDocument();
|
||||
appendChildNodes(doc.body, H1(null, "This is in the child!"));
|
||||
});
|
||||
</pre>
|
||||
<p>Note that <a class="mochiref reference" href="#fn-withwindow">withWindow(win, ...)</a> also implies
|
||||
<a class="mochiref reference" href="#fn-withdocument">withDocument(win.document, ...)</a>.</p>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h2><a id="element-visibility" name="element-visibility">Element Visibility</a></h2>
|
||||
<p>The <a class="mochiref reference" href="#fn-hideelement">hideElement</a> and <a class="mochiref reference" href="#fn-showelement">showElement</a> functions are
|
||||
provided as a convenience, but only work for elements that are
|
||||
<tt class="docutils literal"><span class="pre">display:</span> <span class="pre">block</span></tt>. For a general solution to showing, hiding, and checking
|
||||
the explicit visibility of elements, we recommend using a solution that
|
||||
involves a little CSS. Here's an example:</p>
|
||||
<pre class="literal-block">
|
||||
<style type="text/css">
|
||||
.invisible { display: none; }
|
||||
</style>
|
||||
|
||||
<script type="text/javascript">
|
||||
function toggleVisible(elem) {
|
||||
toggleElementClass("invisible", elem);
|
||||
}
|
||||
|
||||
function makeVisible(elem) {
|
||||
removeElementClass(elem, "invisible");
|
||||
}
|
||||
|
||||
function makeInvisible(elem) {
|
||||
addElementClass(elem, "invisible");
|
||||
}
|
||||
|
||||
function isVisible(elem) {
|
||||
// you may also want to check for
|
||||
// getElement(elem).style.display == "none"
|
||||
return !hasElementClass(elem, "invisible");
|
||||
};
|
||||
</script>
|
||||
</pre>
|
||||
<p>MochiKit doesn't ship with such a solution, because there is no reliable and
|
||||
portable method for adding CSS rules on the fly with JavaScript.</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h1><a id="api-reference" name="api-reference">API Reference</a></h1>
|
||||
<div class="section">
|
||||
<h2><a id="functions" name="functions">Functions</a></h2>
|
||||
<p>
|
||||
<a name="fn-$"></a>
|
||||
<a class="mochidef reference" href="#fn-$">$(id[, ...])</a>:</p>
|
||||
<blockquote>
|
||||
An alias for <a class="mochiref reference" href="#fn-getelement">getElement(id[, ...])</a></blockquote>
|
||||
<p>
|
||||
<a name="fn-addelementclass"></a>
|
||||
<a class="mochidef reference" href="#fn-addelementclass">addElementClass(element, className)</a>:</p>
|
||||
<blockquote>
|
||||
Ensure that the given <tt class="docutils literal"><span class="pre">element</span></tt> has <tt class="docutils literal"><span class="pre">className</span></tt> set as part of its
|
||||
class attribute. This will not disturb other class names.
|
||||
<tt class="docutils literal"><span class="pre">element</span></tt> is looked up with <a class="mochiref reference" href="#fn-getelement">getElement</a>, so string identifiers
|
||||
are also acceptable.</blockquote>
|
||||
<p>
|
||||
<a name="fn-addloadevent"></a>
|
||||
<a class="mochidef reference" href="#fn-addloadevent">addLoadEvent(func)</a>:</p>
|
||||
<blockquote>
|
||||
<p>Note that <a class="mochiref reference" href="#fn-addloadevent">addLoadEvent</a> can not be used in combination with
|
||||
<a class="mochiref reference" href="Signal.html">MochiKit.Signal</a> if the <tt class="docutils literal"><span class="pre">onload</span></tt> event is connected.
|
||||
Once an event is connected with <a class="mochiref reference" href="Signal.html">MochiKit.Signal</a>, no other APIs
|
||||
may be used for that same event.</p>
|
||||
<p>This will stack <tt class="docutils literal"><span class="pre">window.onload</span></tt> functions on top of each other.
|
||||
Each function added will be called after <tt class="docutils literal"><span class="pre">onload</span></tt> in the
|
||||
order that they were added.</p>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-addtocallstack"></a>
|
||||
<a class="mochidef reference" href="#fn-addtocallstack">addToCallStack(target, path, func[, once])</a>:</p>
|
||||
<blockquote>
|
||||
<p>Note that <a class="mochiref reference" href="#fn-addtocallstack">addToCallStack</a> is not compatible with
|
||||
<a class="mochiref reference" href="Signal.html">MochiKit.Signal</a>. Once an event is connected with
|
||||
<a class="mochiref reference" href="Signal.html">MochiKit.Signal</a>, no other APIs may be used for that same event.</p>
|
||||
<p>Set the property <tt class="docutils literal"><span class="pre">path</span></tt> of <tt class="docutils literal"><span class="pre">target</span></tt> to a function that calls the
|
||||
existing function at that property (if any), then calls <tt class="docutils literal"><span class="pre">func</span></tt>.</p>
|
||||
<p>If <tt class="docutils literal"><span class="pre">target[path]()</span></tt> returns exactly <tt class="docutils literal"><span class="pre">false</span></tt>, then <tt class="docutils literal"><span class="pre">func</span></tt> will
|
||||
not be called.</p>
|
||||
<p>If <tt class="docutils literal"><span class="pre">once</span></tt> is <tt class="docutils literal"><span class="pre">true</span></tt>, then <tt class="docutils literal"><span class="pre">target[path]</span></tt> is set to <tt class="docutils literal"><span class="pre">null</span></tt> after
|
||||
the function call stack has completed.</p>
|
||||
<p>If called several times for the same <tt class="docutils literal"><span class="pre">target[path]</span></tt>, it will create
|
||||
a stack of functions (instead of just a pair).</p>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-appendchildnodes"></a>
|
||||
<a class="mochidef reference" href="#fn-appendchildnodes">appendChildNodes(node[, childNode[, ...]])</a>:</p>
|
||||
<blockquote>
|
||||
<p>Append children to a DOM element using the <a class="reference" href="#dom-coercion-rules">DOM Coercion Rules</a>.</p>
|
||||
<dl class="docutils">
|
||||
<dt><tt class="docutils literal"><span class="pre">node</span></tt>:</dt>
|
||||
<dd>A reference to the DOM element to add children to
|
||||
(if a string is given, <a class="mochiref reference" href="#fn-getelement">getElement(node)</a>
|
||||
will be used to locate the node)</dd>
|
||||
<dt><tt class="docutils literal"><span class="pre">childNode</span></tt>...:</dt>
|
||||
<dd>All additional arguments, if any, will be coerced into DOM
|
||||
nodes that are appended as children using the
|
||||
<a class="reference" href="#dom-coercion-rules">DOM Coercion Rules</a>.</dd>
|
||||
<dt><em>returns</em>:</dt>
|
||||
<dd>The given DOM element</dd>
|
||||
</dl>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-computedstyle"></a>
|
||||
<a class="mochidef reference" href="#fn-computedstyle">computedStyle(htmlElement, cssProperty, mozillaEquivalentCSS)</a>:</p>
|
||||
<blockquote>
|
||||
Looks up a CSS property for the given element. The element can be
|
||||
specified as either a string with the element's ID or the element
|
||||
object itself.</blockquote>
|
||||
<p>
|
||||
<a name="fn-createdom"></a>
|
||||
<a class="mochidef reference" href="#fn-createdom">createDOM(name[, attrs[, node[, ...]]])</a>:</p>
|
||||
<blockquote>
|
||||
<p>Create a DOM fragment in a really convenient manner, much like
|
||||
Nevow`s <a class="footnote-reference" href="#id5" id="id3" name="id3">[1]</a> stan <a class="footnote-reference" href="#id6" id="id4" name="id4">[2]</a>.</p>
|
||||
<p>Partially applied versions of this function for common tags are
|
||||
available as aliases:</p>
|
||||
<ul class="simple">
|
||||
<li><tt class="docutils literal"><span class="pre">A</span></tt></li>
|
||||
<li><tt class="docutils literal"><span class="pre">BUTTON</span></tt></li>
|
||||
<li><tt class="docutils literal"><span class="pre">BR</span></tt></li>
|
||||
<li><tt class="docutils literal"><span class="pre">CANVAS</span></tt></li>
|
||||
<li><tt class="docutils literal"><span class="pre">DIV</span></tt></li>
|
||||
<li><tt class="docutils literal"><span class="pre">FIELDSET</span></tt></li>
|
||||
<li><tt class="docutils literal"><span class="pre">FORM</span></tt></li>
|
||||
<li><tt class="docutils literal"><span class="pre">H1</span></tt></li>
|
||||
<li><tt class="docutils literal"><span class="pre">H2</span></tt></li>
|
||||
<li><tt class="docutils literal"><span class="pre">H3</span></tt></li>
|
||||
<li><tt class="docutils literal"><span class="pre">HR</span></tt></li>
|
||||
<li><tt class="docutils literal"><span class="pre">IMG</span></tt></li>
|
||||
<li><tt class="docutils literal"><span class="pre">INPUT</span></tt></li>
|
||||
<li><tt class="docutils literal"><span class="pre">LABEL</span></tt></li>
|
||||
<li><tt class="docutils literal"><span class="pre">LEGEND</span></tt></li>
|
||||
<li><tt class="docutils literal"><span class="pre">LI</span></tt></li>
|
||||
<li><tt class="docutils literal"><span class="pre">OL</span></tt></li>
|
||||
<li><tt class="docutils literal"><span class="pre">OPTGROUP</span></tt></li>
|
||||
<li><tt class="docutils literal"><span class="pre">OPTION</span></tt></li>
|
||||
<li><tt class="docutils literal"><span class="pre">P</span></tt></li>
|
||||
<li><tt class="docutils literal"><span class="pre">PRE</span></tt></li>
|
||||
<li><tt class="docutils literal"><span class="pre">SELECT</span></tt></li>
|
||||
<li><tt class="docutils literal"><span class="pre">SPAN</span></tt></li>
|
||||
<li><tt class="docutils literal"><span class="pre">STRONG</span></tt></li>
|
||||
<li><tt class="docutils literal"><span class="pre">TABLE</span></tt></li>
|
||||
<li><tt class="docutils literal"><span class="pre">TBODY</span></tt></li>
|
||||
<li><tt class="docutils literal"><span class="pre">TD</span></tt></li>
|
||||
<li><tt class="docutils literal"><span class="pre">TEXTAREA</span></tt></li>
|
||||
<li><tt class="docutils literal"><span class="pre">TFOOT</span></tt></li>
|
||||
<li><tt class="docutils literal"><span class="pre">TH</span></tt></li>
|
||||
<li><tt class="docutils literal"><span class="pre">THEAD</span></tt></li>
|
||||
<li><tt class="docutils literal"><span class="pre">TR</span></tt></li>
|
||||
<li><tt class="docutils literal"><span class="pre">TT</span></tt></li>
|
||||
<li><tt class="docutils literal"><span class="pre">UL</span></tt></li>
|
||||
</ul>
|
||||
<p>See <a class="reference" href="#creating-dom-element-trees">Creating DOM Element Trees</a> for a comprehensive example.</p>
|
||||
<dl class="docutils">
|
||||
<dt><tt class="docutils literal"><span class="pre">name</span></tt>:</dt>
|
||||
<dd>The kind of fragment to create (e.g. 'span'), such as you would
|
||||
pass to <tt class="docutils literal"><span class="pre">document.createElement</span></tt>.</dd>
|
||||
<dt><tt class="docutils literal"><span class="pre">attrs</span></tt>:</dt>
|
||||
<dd><p class="first">An object whose properties will be used as the attributes
|
||||
(e.g. <tt class="docutils literal"><span class="pre">{'style':</span> <span class="pre">'display:block'}</span></tt>), or <tt class="docutils literal"><span class="pre">null</span></tt> if no
|
||||
attributes need to be set.</p>
|
||||
<p>See <a class="mochiref reference" href="#fn-updatenodeattributes">updateNodeAttributes</a> for more information.</p>
|
||||
<p class="last">For convenience, if <tt class="docutils literal"><span class="pre">attrs</span></tt> is a string, <tt class="docutils literal"><span class="pre">null</span></tt> is used
|
||||
and the string will be considered the first <tt class="docutils literal"><span class="pre">node</span></tt>.</p>
|
||||
</dd>
|
||||
<dt><tt class="docutils literal"><span class="pre">node</span></tt>...:</dt>
|
||||
<dd>All additional arguments, if any, will be coerced into DOM
|
||||
nodes that are appended as children using the
|
||||
<a class="reference" href="#dom-coercion-rules">DOM Coercion Rules</a>.</dd>
|
||||
<dt><em>returns</em>:</dt>
|
||||
<dd>A DOM element</dd>
|
||||
</dl>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-createdomfunc"></a>
|
||||
<a class="mochidef reference" href="#fn-createdomfunc">createDOMFunc(tag[, attrs[, node[, ...]]])</a>:</p>
|
||||
<blockquote>
|
||||
<p>Convenience function to create a partially applied createDOM
|
||||
function. You'd want to use this if you add additional convenience
|
||||
functions for creating tags, or if you find yourself creating
|
||||
a lot of tags with a bunch of the same attributes or contents.</p>
|
||||
<p>See <a class="mochiref reference" href="#fn-createdom">createDOM</a> for more detailed descriptions of the arguments.</p>
|
||||
<dl class="docutils">
|
||||
<dt><tt class="docutils literal"><span class="pre">tag</span></tt>:</dt>
|
||||
<dd>The name of the tag</dd>
|
||||
<dt><tt class="docutils literal"><span class="pre">attrs</span></tt>:</dt>
|
||||
<dd>Optionally specify the attributes to apply</dd>
|
||||
<dt><tt class="docutils literal"><span class="pre">node</span></tt>...:</dt>
|
||||
<dd>Optionally specify any children nodes it should have</dd>
|
||||
<dt><em>returns</em>:</dt>
|
||||
<dd>function that takes additional arguments and calls
|
||||
<a class="mochiref reference" href="#fn-createdom">createDOM</a></dd>
|
||||
</dl>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-currentdocument"></a>
|
||||
<a class="mochidef reference" href="#fn-currentdocument">currentDocument()</a>:</p>
|
||||
<blockquote>
|
||||
Return the current <tt class="docutils literal"><span class="pre">document</span></tt> <a class="reference" href="#dom-context">DOM Context</a>. This will always
|
||||
be the same as the global <tt class="docutils literal"><span class="pre">document</span></tt> unless <a class="mochiref reference" href="#fn-withdocument">withDocument</a> or
|
||||
<a class="mochiref reference" href="#fn-withwindow">withWindow</a> is currently executing.</blockquote>
|
||||
<p>
|
||||
<a name="fn-currentwindow"></a>
|
||||
<a class="mochidef reference" href="#fn-currentwindow">currentWindow()</a>:</p>
|
||||
<blockquote>
|
||||
Return the current <tt class="docutils literal"><span class="pre">window</span></tt> <a class="reference" href="#dom-context">DOM Context</a>. This will always
|
||||
be the same as the global <tt class="docutils literal"><span class="pre">window</span></tt> unless <a class="mochiref reference" href="#fn-withwindow">withWindow</a> is
|
||||
currently executing.</blockquote>
|
||||
<p>
|
||||
<a name="fn-elementdimensions"></a>
|
||||
<a class="mochidef reference" href="#fn-elementdimensions">elementDimensions(element)</a>:</p>
|
||||
<blockquote>
|
||||
Return the absolute pixel width and height of <tt class="docutils literal"><span class="pre">element</span></tt> as an object with
|
||||
<tt class="docutils literal"><span class="pre">w</span></tt> and <tt class="docutils literal"><span class="pre">h</span></tt> properties, or <tt class="docutils literal"><span class="pre">undefined</span></tt> if <tt class="docutils literal"><span class="pre">element</span></tt> is not in the
|
||||
document. <tt class="docutils literal"><span class="pre">element</span></tt> may be specified as a string to be looked up with
|
||||
<a class="mochiref reference" href="#fn-getelement">getElement</a>, a DOM element, or trivially as an object with
|
||||
<tt class="docutils literal"><span class="pre">w</span></tt> and/or <tt class="docutils literal"><span class="pre">h</span></tt> properties.</blockquote>
|
||||
<p>
|
||||
<a name="fn-elementposition"></a>
|
||||
<a class="mochidef reference" href="#fn-elementposition">elementPosition(element[, relativeTo={x: 0, y: 0}])</a>:</p>
|
||||
<blockquote>
|
||||
<p>Return the absolute pixel position of <tt class="docutils literal"><span class="pre">element</span></tt> in the document as an
|
||||
object with <tt class="docutils literal"><span class="pre">x</span></tt> and <tt class="docutils literal"><span class="pre">y</span></tt> properties, or <tt class="docutils literal"><span class="pre">undefined</span></tt> if <tt class="docutils literal"><span class="pre">element</span></tt>
|
||||
is not in the document. <tt class="docutils literal"><span class="pre">element</span></tt> may be specified as a string to
|
||||
be looked up with <a class="mochiref reference" href="#fn-getelement">getElement</a>, a DOM element, or trivially
|
||||
as an object with <tt class="docutils literal"><span class="pre">x</span></tt> and/or <tt class="docutils literal"><span class="pre">y</span></tt> properties.</p>
|
||||
<p>If <tt class="docutils literal"><span class="pre">relativeTo</span></tt> is given, then its coordinates are subtracted from
|
||||
the absolute position of <tt class="docutils literal"><span class="pre">element</span></tt>, e.g.:</p>
|
||||
<pre class="literal-block">
|
||||
var elemPos = elementPosition(elem);
|
||||
var anotherElemPos = elementPosition(anotherElem);
|
||||
var relPos = elementPosition(elem, anotherElem);
|
||||
assert( relPos.x == (elemPos.x - anotherElemPos.x) );
|
||||
assert( relPos.y == (elemPos.y - anotherElemPos.y) );
|
||||
</pre>
|
||||
<p><tt class="docutils literal"><span class="pre">relativeTo</span></tt> may be specified as a string to be looked up with
|
||||
<a class="mochiref reference" href="#fn-getelement">getElement</a>, a DOM element, or trivially as an object
|
||||
with <tt class="docutils literal"><span class="pre">x</span></tt> and/or <tt class="docutils literal"><span class="pre">y</span></tt> properties.</p>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-emithtml"></a>
|
||||
<a class="mochidef reference" href="#fn-emithtml">emitHTML(dom[, lst])</a>:</p>
|
||||
<blockquote>
|
||||
<p>Convert a DOM tree to an <tt class="docutils literal"><span class="pre">Array</span></tt> of HTML string fragments</p>
|
||||
<p>You probably want to use <a class="mochiref reference" href="#fn-tohtml">toHTML</a> instead.</p>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-escapehtml"></a>
|
||||
<a class="mochidef reference" href="#fn-escapehtml">escapeHTML(s)</a>:</p>
|
||||
<blockquote>
|
||||
Make a string safe for HTML, converting the usual suspects (lt,
|
||||
gt, quot, apos, amp)</blockquote>
|
||||
<p>
|
||||
<a name="fn-focusonload"></a>
|
||||
<a class="mochidef reference" href="#fn-focusonload">focusOnLoad(element)</a>:</p>
|
||||
<blockquote>
|
||||
Add an onload event to focus the given element</blockquote>
|
||||
<p>
|
||||
<a name="fn-formcontents"></a>
|
||||
<a class="mochidef reference" href="#fn-formcontents">formContents(elem)</a>:</p>
|
||||
<blockquote>
|
||||
Search the DOM tree, starting at <tt class="docutils literal"><span class="pre">elem</span></tt>, for any elements with a
|
||||
<tt class="docutils literal"><span class="pre">name</span></tt> and <tt class="docutils literal"><span class="pre">value</span></tt> attribute. Return a 2-element <tt class="docutils literal"><span class="pre">Array</span></tt> of
|
||||
<tt class="docutils literal"><span class="pre">names</span></tt> and <tt class="docutils literal"><span class="pre">values</span></tt> suitable for use with
|
||||
<a class="mochiref reference" href="Base.html#fn-querystring">MochiKit.Base.queryString</a>.</blockquote>
|
||||
<p>
|
||||
<a name="fn-getelement"></a>
|
||||
<a class="mochidef reference" href="#fn-getelement">getElement(id[, ...])</a>:</p>
|
||||
<blockquote>
|
||||
<p>A small quick little function to encapsulate the <tt class="docutils literal"><span class="pre">getElementById</span></tt>
|
||||
method. It includes a check to ensure we can use that method.</p>
|
||||
<p>If the id isn't a string, it will be returned as-is.</p>
|
||||
<p>Also available as <a class="mochiref reference" href="#fn-$">$(...)</a> for convenience and compatibility with
|
||||
other JavaScript frameworks.</p>
|
||||
<p>If multiple arguments are given, an <tt class="docutils literal"><span class="pre">Array</span></tt> will be returned.</p>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-getelementsbytagandclassname"></a>
|
||||
<a class="mochidef reference" href="#fn-getelementsbytagandclassname">getElementsByTagAndClassName(tagName, className, parent=document)</a>:</p>
|
||||
<blockquote>
|
||||
<p>Returns an array of elements in <tt class="docutils literal"><span class="pre">parent</span></tt> that match the tag name
|
||||
and class name provided. If <tt class="docutils literal"><span class="pre">parent</span></tt> is a string, it will be looked
|
||||
up with <a class="mochiref reference" href="#fn-getelement">getElement</a>.</p>
|
||||
<p>If <tt class="docutils literal"><span class="pre">tagName</span></tt> is <tt class="docutils literal"><span class="pre">null</span></tt> or <tt class="docutils literal"><span class="pre">"*"</span></tt>, all elements will be searched
|
||||
for the matching class.</p>
|
||||
<p>If <tt class="docutils literal"><span class="pre">className</span></tt> is <tt class="docutils literal"><span class="pre">null</span></tt>, all elements matching the provided tag are
|
||||
returned.</p>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-getnodeattribute"></a>
|
||||
<a class="mochidef reference" href="#fn-getnodeattribute">getNodeAttribute(node, attr)</a>:</p>
|
||||
<blockquote>
|
||||
<p>Get the value of the given attribute for a DOM element without
|
||||
ever raising an exception (will return <tt class="docutils literal"><span class="pre">null</span></tt> on exception).</p>
|
||||
<dl class="docutils">
|
||||
<dt><tt class="docutils literal"><span class="pre">node</span></tt>:</dt>
|
||||
<dd>A reference to the DOM element to update (if a string is given,
|
||||
<a class="mochiref reference" href="#fn-getelement">getElement(node)</a> will be used to locate the node)</dd>
|
||||
<dt><tt class="docutils literal"><span class="pre">attr</span></tt>:</dt>
|
||||
<dd><p class="first">The name of the attribute</p>
|
||||
<p class="last">Note that it will do the right thing for IE, so don't do
|
||||
the <tt class="docutils literal"><span class="pre">class</span></tt> -> <tt class="docutils literal"><span class="pre">className</span></tt> hack yourself.</p>
|
||||
</dd>
|
||||
<dt><em>returns</em>:</dt>
|
||||
<dd>The attribute's value, or <tt class="docutils literal"><span class="pre">null</span></tt></dd>
|
||||
</dl>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-getviewportdimensions"></a>
|
||||
<a class="mochidef reference" href="#fn-getviewportdimensions">getViewportDimensions()</a>:</p>
|
||||
<blockquote>
|
||||
Return the pixel width and height of the viewport as an object with <tt class="docutils literal"><span class="pre">w</span></tt>
|
||||
and <tt class="docutils literal"><span class="pre">h</span></tt> properties. <tt class="docutils literal"><span class="pre">element</span></tt> is looked up with
|
||||
<a class="mochiref reference" href="#fn-getelement">getElement</a>, so string identifiers are also acceptable.</blockquote>
|
||||
<p>
|
||||
<a name="fn-haselementclass"></a>
|
||||
<a class="mochidef reference" href="#fn-haselementclass">hasElementClass(element, className[, ...])</a>:</p>
|
||||
<blockquote>
|
||||
Return <tt class="docutils literal"><span class="pre">true</span></tt> if <tt class="docutils literal"><span class="pre">className</span></tt> is found on the <tt class="docutils literal"><span class="pre">element</span></tt>.
|
||||
<tt class="docutils literal"><span class="pre">element</span></tt> is looked up with <a class="mochiref reference" href="#fn-getelement">getElement</a>, so string identifiers
|
||||
are also acceptable.</blockquote>
|
||||
<p>
|
||||
<a name="fn-hideelement"></a>
|
||||
<a class="mochidef reference" href="#fn-hideelement">hideElement(element, ...)</a>:</p>
|
||||
<blockquote>
|
||||
<p>Partial form of <a class="mochiref reference" href="#fn-setdisplayforelement">setDisplayForElement</a>, specifically:</p>
|
||||
<pre class="literal-block">
|
||||
partial(setDisplayForElement, "none")
|
||||
</pre>
|
||||
<p>For information about the caveats of using a <tt class="docutils literal"><span class="pre">style.display</span></tt> based
|
||||
show/hide mechanism, and a CSS based alternative, see
|
||||
<a class="reference" href="#element-visibility">Element Visibility</a>.</p>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-registerdomconverter"></a>
|
||||
<a class="mochidef reference" href="#fn-registerdomconverter">registerDOMConverter(name, check, wrap[, override])</a>:</p>
|
||||
<blockquote>
|
||||
Register an adapter to convert objects that match <tt class="docutils literal"><span class="pre">check(obj,</span> <span class="pre">ctx)</span></tt>
|
||||
to a DOM element, or something that can be converted to a DOM
|
||||
element (i.e. number, bool, string, function, iterable).</blockquote>
|
||||
<p>
|
||||
<a name="fn-removeelement"></a>
|
||||
<a class="mochidef reference" href="#fn-removeelement">removeElement(node)</a>:</p>
|
||||
<blockquote>
|
||||
<p>Remove and return <tt class="docutils literal"><span class="pre">node</span></tt> from a DOM tree. This is technically
|
||||
just a convenience for <a class="mochiref reference" href="#fn-swapdom">swapDOM(node, null)</a>.</p>
|
||||
<dl class="docutils">
|
||||
<dt><tt class="docutils literal"><span class="pre">node</span></tt>:</dt>
|
||||
<dd>the DOM element (or string id of one) to be removed</dd>
|
||||
<dt><em>returns</em></dt>
|
||||
<dd>The removed element</dd>
|
||||
</dl>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-removeelementclass"></a>
|
||||
<a class="mochidef reference" href="#fn-removeelementclass">removeElementClass(element, className)</a>:</p>
|
||||
<blockquote>
|
||||
Ensure that the given <tt class="docutils literal"><span class="pre">element</span></tt> does not have <tt class="docutils literal"><span class="pre">className</span></tt> set as part
|
||||
of its class attribute. This will not disturb other class names.
|
||||
<tt class="docutils literal"><span class="pre">element</span></tt> is looked up with <a class="mochiref reference" href="#fn-getelement">getElement</a>, so string identifiers
|
||||
are also acceptable.</blockquote>
|
||||
<p>
|
||||
<a name="fn-replacechildnodes"></a>
|
||||
<a class="mochidef reference" href="#fn-replacechildnodes">replaceChildNodes(node[, childNode[, ...]])</a>:</p>
|
||||
<blockquote>
|
||||
<p>Remove all children from the given DOM element, then append any given
|
||||
childNodes to it (by calling <a class="mochiref reference" href="#fn-appendchildnodes">appendChildNodes</a>).</p>
|
||||
<dl class="docutils">
|
||||
<dt><tt class="docutils literal"><span class="pre">node</span></tt>:</dt>
|
||||
<dd>A reference to the DOM element to add children to
|
||||
(if a string is given, <a class="mochiref reference" href="#fn-getelement">getElement(node)</a>
|
||||
will be used to locate the node)</dd>
|
||||
<dt><tt class="docutils literal"><span class="pre">childNode</span></tt>...:</dt>
|
||||
<dd>All additional arguments, if any, will be coerced into DOM
|
||||
nodes that are appended as children using the
|
||||
<a class="reference" href="#dom-coercion-rules">DOM Coercion Rules</a>.</dd>
|
||||
<dt><em>returns</em>:</dt>
|
||||
<dd>The given DOM element</dd>
|
||||
</dl>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-scrapetext"></a>
|
||||
<a class="mochidef reference" href="#fn-scrapetext">scrapeText(node[, asArray=false])</a>:</p>
|
||||
<blockquote>
|
||||
<p>Walk a DOM tree in-order and scrape all of the text out of it as a
|
||||
<tt class="docutils literal"><span class="pre">string</span></tt>.</p>
|
||||
<p>If <tt class="docutils literal"><span class="pre">asArray</span></tt> is <tt class="docutils literal"><span class="pre">true</span></tt>, then an <tt class="docutils literal"><span class="pre">Array</span></tt> will be returned with
|
||||
each individual text node. These two are equivalent:</p>
|
||||
<pre class="literal-block">
|
||||
assert( scrapeText(node) == scrapeText(node, true).join("") );
|
||||
</pre>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-setdisplayforelement"></a>
|
||||
<a class="mochidef reference" href="#fn-setdisplayforelement">setDisplayForElement(display, element[, ...])</a>:</p>
|
||||
<blockquote>
|
||||
<p>Change the <tt class="docutils literal"><span class="pre">style.display</span></tt> for the given element(s). Usually
|
||||
used as the partial forms:</p>
|
||||
<ul class="simple">
|
||||
<li><a class="mochiref reference" href="#fn-showelement">showElement(element, ...)</a></li>
|
||||
<li><a class="mochiref reference" href="#fn-hideelement">hideElement(element, ...)</a></li>
|
||||
</ul>
|
||||
<p>Elements are looked up with <a class="mochiref reference" href="#fn-getelement">getElement</a>, so string identifiers
|
||||
are acceptable.</p>
|
||||
<p>For information about the caveats of using a <tt class="docutils literal"><span class="pre">style.display</span></tt> based
|
||||
show/hide mechanism, and a CSS based alternative, see
|
||||
<a class="reference" href="#element-visibility">Element Visibility</a>.</p>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-setelementclass"></a>
|
||||
<a class="mochidef reference" href="#fn-setelementclass">setElementClass(element, className)</a>:</p>
|
||||
<blockquote>
|
||||
Set the entire class attribute of <tt class="docutils literal"><span class="pre">element</span></tt> to <tt class="docutils literal"><span class="pre">className</span></tt>.
|
||||
<tt class="docutils literal"><span class="pre">element</span></tt> is looked up with <a class="mochiref reference" href="#fn-getelement">getElement</a>, so string identifiers
|
||||
are also acceptable.</blockquote>
|
||||
<p>
|
||||
<a name="fn-setelementdimensions"></a>
|
||||
<a class="mochidef reference" href="#fn-setelementdimensions">setElementDimensions(element, dimensions[, units='px'])</a>:</p>
|
||||
<blockquote>
|
||||
<p>Sets the dimensions of <tt class="docutils literal"><span class="pre">element</span></tt> in the document from an
|
||||
object with <tt class="docutils literal"><span class="pre">w</span></tt> and <tt class="docutils literal"><span class="pre">h</span></tt> properties.</p>
|
||||
<dl class="docutils">
|
||||
<dt><tt class="docutils literal"><span class="pre">node</span></tt>:</dt>
|
||||
<dd>A reference to the DOM element to update (if a string is given,
|
||||
<a class="mochiref reference" href="#fn-getelement">getElement(node)</a> will be used to locate the node)</dd>
|
||||
<dt><tt class="docutils literal"><span class="pre">dimensions</span></tt>:</dt>
|
||||
<dd>An object with <tt class="docutils literal"><span class="pre">w</span></tt> and <tt class="docutils literal"><span class="pre">h</span></tt> properties</dd>
|
||||
<dt><tt class="docutils literal"><span class="pre">units</span></tt>:</dt>
|
||||
<dd>Optionally set the units to use, default is <tt class="docutils literal"><span class="pre">px</span></tt></dd>
|
||||
</dl>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-setelementposition"></a>
|
||||
<a class="mochidef reference" href="#fn-setelementposition">setElementPosition(element, position[, units='px'])</a>:</p>
|
||||
<blockquote>
|
||||
<p>Sets the absolute position of <tt class="docutils literal"><span class="pre">element</span></tt> in the document from an
|
||||
object with <tt class="docutils literal"><span class="pre">x</span></tt> and <tt class="docutils literal"><span class="pre">y</span></tt> properties.</p>
|
||||
<dl class="docutils">
|
||||
<dt><tt class="docutils literal"><span class="pre">node</span></tt>:</dt>
|
||||
<dd>A reference to the DOM element to update (if a string is given,
|
||||
<a class="mochiref reference" href="#fn-getelement">getElement(node)</a> will be used to locate the node)</dd>
|
||||
<dt><tt class="docutils literal"><span class="pre">position</span></tt>:</dt>
|
||||
<dd>An object with <tt class="docutils literal"><span class="pre">x</span></tt> and <tt class="docutils literal"><span class="pre">y</span></tt> properties</dd>
|
||||
<dt><tt class="docutils literal"><span class="pre">units</span></tt>:</dt>
|
||||
<dd>Optionally set the units to use, default is <tt class="docutils literal"><span class="pre">px</span></tt></dd>
|
||||
</dl>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-setnodeattribute"></a>
|
||||
<a class="mochidef reference" href="#fn-setnodeattribute">setNodeAttribute(node, attr, value)</a>:</p>
|
||||
<blockquote>
|
||||
<p>Set the value of the given attribute for a DOM element without
|
||||
ever raising an exception (will return null on exception). If
|
||||
setting more than one attribute, you should use
|
||||
<a class="mochiref reference" href="#fn-updatenodeattributes">updateNodeAttributes</a>.</p>
|
||||
<dl class="docutils">
|
||||
<dt><tt class="docutils literal"><span class="pre">node</span></tt>:</dt>
|
||||
<dd>A reference to the DOM element to update (if a string is given,
|
||||
<a class="mochiref reference" href="#fn-getelement">getElement(node)</a> will be used to locate the node)</dd>
|
||||
<dt><tt class="docutils literal"><span class="pre">attr</span></tt>:</dt>
|
||||
<dd><p class="first">The name of the attribute</p>
|
||||
<p class="last">Note that it will do the right thing for IE, so don't do
|
||||
the <tt class="docutils literal"><span class="pre">class</span></tt> -> <tt class="docutils literal"><span class="pre">className</span></tt> hack yourself.</p>
|
||||
</dd>
|
||||
<dt><tt class="docutils literal"><span class="pre">value</span></tt>:</dt>
|
||||
<dd>The value of the attribute, may be an object to be merged
|
||||
(e.g. for setting style).</dd>
|
||||
<dt><em>returns</em>:</dt>
|
||||
<dd>The given DOM element or <tt class="docutils literal"><span class="pre">null</span></tt> on failure</dd>
|
||||
</dl>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-setopacity"></a>
|
||||
<a class="mochidef reference" href="#fn-setopacity">setOpacity(element, opacity)</a>:</p>
|
||||
<blockquote>
|
||||
Sets <tt class="docutils literal"><span class="pre">opacity</span></tt> for <tt class="docutils literal"><span class="pre">element</span></tt>. Valid <tt class="docutils literal"><span class="pre">opacity</span></tt> values range from 0
|
||||
(invisible) to 1 (opaque). <tt class="docutils literal"><span class="pre">element</span></tt> is looked up with
|
||||
<a class="mochiref reference" href="#fn-getelement">getElement</a>, so string identifiers are also acceptable.</blockquote>
|
||||
<p>
|
||||
<a name="fn-showelement"></a>
|
||||
<a class="mochidef reference" href="#fn-showelement">showElement(element, ...)</a>:</p>
|
||||
<blockquote>
|
||||
<p>Partial form of <a class="mochiref reference" href="#fn-setdisplayforelement">setDisplayForElement</a>, specifically:</p>
|
||||
<pre class="literal-block">
|
||||
partial(setDisplayForElement, "block")
|
||||
</pre>
|
||||
<p>For information about the caveats of using a <tt class="docutils literal"><span class="pre">style.display</span></tt> based
|
||||
show/hide mechanism, and a CSS based alternative, see
|
||||
<a class="reference" href="#element-visibility">Element Visibility</a>.</p>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-swapdom"></a>
|
||||
<a class="mochidef reference" href="#fn-swapdom">swapDOM(dest, src)</a>:</p>
|
||||
<blockquote>
|
||||
<p>Replace <tt class="docutils literal"><span class="pre">dest</span></tt> in a DOM tree with <tt class="docutils literal"><span class="pre">src</span></tt>, returning <tt class="docutils literal"><span class="pre">src</span></tt>.</p>
|
||||
<dl class="docutils">
|
||||
<dt><tt class="docutils literal"><span class="pre">dest</span></tt>:</dt>
|
||||
<dd>a DOM element (or string id of one) to be replaced</dd>
|
||||
<dt><tt class="docutils literal"><span class="pre">src</span></tt>:</dt>
|
||||
<dd>the DOM element (or string id of one) to replace it with, or
|
||||
<tt class="docutils literal"><span class="pre">null</span></tt> if <tt class="docutils literal"><span class="pre">dest</span></tt> is to be removed (replaced with nothing).</dd>
|
||||
<dt><em>returns</em>:</dt>
|
||||
<dd>a DOM element (<tt class="docutils literal"><span class="pre">src</span></tt>)</dd>
|
||||
</dl>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-swapelementclass"></a>
|
||||
<a class="mochidef reference" href="#fn-swapelementclass">swapElementClass(element, fromClass, toClass)</a>:</p>
|
||||
<blockquote>
|
||||
If <tt class="docutils literal"><span class="pre">fromClass</span></tt> is set on <tt class="docutils literal"><span class="pre">element</span></tt>, replace it with <tt class="docutils literal"><span class="pre">toClass</span></tt>.
|
||||
This will not disturb other classes on that element.
|
||||
<tt class="docutils literal"><span class="pre">element</span></tt> is looked up with <a class="mochiref reference" href="#fn-getelement">getElement</a>, so string identifiers
|
||||
are also acceptable.</blockquote>
|
||||
<p>
|
||||
<a name="fn-toggleelementclass"></a>
|
||||
<a class="mochidef reference" href="#fn-toggleelementclass">toggleElementClass(className[, element[, ...]])</a>:</p>
|
||||
<blockquote>
|
||||
Toggle the presence of a given <tt class="docutils literal"><span class="pre">className</span></tt> in the class attribute
|
||||
of all given elements. All elements will be looked up with
|
||||
<a class="mochiref reference" href="#fn-getelement">getElement</a>, so string identifiers are acceptable.</blockquote>
|
||||
<p>
|
||||
<a name="fn-tohtml"></a>
|
||||
<a class="mochidef reference" href="#fn-tohtml">toHTML(dom)</a>:</p>
|
||||
<blockquote>
|
||||
Convert a DOM tree to a HTML string using <a class="mochiref reference" href="#fn-emithtml">emitHTML</a></blockquote>
|
||||
<p>
|
||||
<a name="fn-updatenodeattributes"></a>
|
||||
<a class="mochidef reference" href="#fn-updatenodeattributes">updateNodeAttributes(node, attrs)</a>:</p>
|
||||
<blockquote>
|
||||
<p>Update the attributes of a DOM element from a given object.</p>
|
||||
<dl class="docutils">
|
||||
<dt><tt class="docutils literal"><span class="pre">node</span></tt>:</dt>
|
||||
<dd>A reference to the DOM element to update (if a string is given,
|
||||
<a class="mochiref reference" href="#fn-getelement">getElement(node)</a> will be used to locate the node)</dd>
|
||||
<dt><tt class="docutils literal"><span class="pre">attrs</span></tt>:</dt>
|
||||
<dd><p class="first">An object whose properties will be used to set the attributes
|
||||
(e.g. <tt class="docutils literal"><span class="pre">{'class':</span> <span class="pre">'invisible'}</span></tt>), or <tt class="docutils literal"><span class="pre">null</span></tt> if no
|
||||
attributes need to be set. If an object is given for the
|
||||
attribute value (e.g. <tt class="docutils literal"><span class="pre">{'style':</span> <span class="pre">{'display':</span> <span class="pre">'block'}}</span></tt>)
|
||||
then <a class="mochiref reference" href="Base.html#fn-updatetree">MochiKit.Base.updatetree</a> will be used to set that
|
||||
attribute.</p>
|
||||
<p class="last">Note that it will do the right thing for IE, so don't do
|
||||
the <tt class="docutils literal"><span class="pre">class</span></tt> -> <tt class="docutils literal"><span class="pre">className</span></tt> hack yourself, and it deals with
|
||||
setting "on..." event handlers correctly.</p>
|
||||
</dd>
|
||||
<dt><em>returns</em>:</dt>
|
||||
<dd>The given DOM element</dd>
|
||||
</dl>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-withwindow"></a>
|
||||
<a class="mochidef reference" href="#fn-withwindow">withWindow(win, func)</a>:</p>
|
||||
<blockquote>
|
||||
<p>Call <tt class="docutils literal"><span class="pre">func</span></tt> with the <tt class="docutils literal"><span class="pre">window</span></tt> <a class="reference" href="#dom-context">DOM Context</a> set to <tt class="docutils literal"><span class="pre">win</span></tt> and
|
||||
the <tt class="docutils literal"><span class="pre">document</span></tt> <a class="reference" href="#dom-context">DOM Context</a> set to <tt class="docutils literal"><span class="pre">win.document</span></tt>. When
|
||||
<tt class="docutils literal"><span class="pre">func()</span></tt> returns or throws an error, the <a class="reference" href="#dom-context">DOM Context</a> will be
|
||||
restored to its previous state.</p>
|
||||
<p>The return value of <tt class="docutils literal"><span class="pre">func()</span></tt> is returned by this function.</p>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-withdocument"></a>
|
||||
<a class="mochidef reference" href="#fn-withdocument">withDocument(doc, func)</a>:</p>
|
||||
<blockquote>
|
||||
<p>Call <tt class="docutils literal"><span class="pre">func</span></tt> with the <tt class="docutils literal"><span class="pre">doc</span></tt> <a class="reference" href="#dom-context">DOM Context</a> set to <tt class="docutils literal"><span class="pre">doc</span></tt>.
|
||||
When <tt class="docutils literal"><span class="pre">func()</span></tt> returns or throws an error, the <a class="reference" href="#dom-context">DOM Context</a>
|
||||
will be restored to its previous state.</p>
|
||||
<p>The return value of <tt class="docutils literal"><span class="pre">func()</span></tt> is returned by this function.</p>
|
||||
</blockquote>
|
||||
</div>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h1><a id="see-also" name="see-also">See Also</a></h1>
|
||||
<table class="docutils footnote" frame="void" id="id5" rules="none">
|
||||
<colgroup><col class="label" /><col /></colgroup>
|
||||
<tbody valign="top">
|
||||
<tr><td class="label"><a name="id5">[1]</a></td><td><em>(<a class="fn-backref" href="#id1">1</a>, <a class="fn-backref" href="#id3">2</a>)</em> Nevow, a web application construction kit for Python: <a class="reference" href="http://nevow.com/">http://nevow.com/</a></td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<table class="docutils footnote" frame="void" id="id6" rules="none">
|
||||
<colgroup><col class="label" /><col /></colgroup>
|
||||
<tbody valign="top">
|
||||
<tr><td class="label"><a name="id6">[2]</a></td><td><em>(<a class="fn-backref" href="#id2">1</a>, <a class="fn-backref" href="#id4">2</a>)</em> nevow.stan is a domain specific language for Python
|
||||
(read as "crazy getitem/call overloading abuse") that Donovan and I
|
||||
schemed up at PyCon 2003 at this super ninja Python/C++ programmer's
|
||||
(David Abrahams) hotel room. Donovan later inflicted this upon the
|
||||
masses in Nevow. Check out the Divmod project page for some
|
||||
examples: <a class="reference" href="http://nevow.com/Nevow2004Tutorial.html">http://nevow.com/Nevow2004Tutorial.html</a></td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h1><a id="authors" name="authors">Authors</a></h1>
|
||||
<ul class="simple">
|
||||
<li>Bob Ippolito <<a class="reference" href="mailto:bob@redivi.com">bob@redivi.com</a>></li>
|
||||
</ul>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h1><a id="copyright" name="copyright">Copyright</a></h1>
|
||||
<p>Copyright 2005 Bob Ippolito <<a class="reference" href="mailto:bob@redivi.com">bob@redivi.com</a>>. This program is dual-licensed
|
||||
free software; you can redistribute it and/or modify it under the terms of the
|
||||
<a class="reference" href="http://www.opensource.org/licenses/mit-license.php">MIT License</a> or the <a class="reference" href="http://www.opensource.org/licenses/afl-2.1.php">Academic Free License v2.1</a>.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,125 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8" ?>
|
||||
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
|
||||
|
||||
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
|
||||
<meta name="generator" content="Docutils 0.4: http://docutils.sourceforge.net/" />
|
||||
<title>MochiKit.DateTime - "what time is it anyway?"</title>
|
||||
|
||||
<link rel="stylesheet" href="../../../include/css/documentation.css" type="text/css" />
|
||||
<script type="text/javascript" src="../../../packed/lib/MochiKit/MochiKit.js"></script>
|
||||
<script type="text/javascript" src="../../js/toc.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div class="document">
|
||||
<div class="section">
|
||||
<h1><a id="name" name="name">Name</a></h1>
|
||||
<p>MochiKit.DateTime - "what time is it anyway?"</p>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h1><a id="synopsis" name="synopsis">Synopsis</a></h1>
|
||||
<pre class="literal-block">
|
||||
stringDate = toISOTimestamp(new Date());
|
||||
dateObject = isoTimestamp(stringDate);
|
||||
</pre>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h1><a id="description" name="description">Description</a></h1>
|
||||
<p>Remote servers don't give you JavaScript Date objects, and they certainly
|
||||
don't want them from you, so you need to deal with string representations
|
||||
of dates and timestamps. MochiKit.Date does that.</p>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h1><a id="dependencies" name="dependencies">Dependencies</a></h1>
|
||||
<p>None.</p>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h1><a id="api-reference" name="api-reference">API Reference</a></h1>
|
||||
<div class="section">
|
||||
<h2><a id="functions" name="functions">Functions</a></h2>
|
||||
<p>
|
||||
<a name="fn-isodate"></a>
|
||||
<a class="mochidef reference" href="#fn-isodate">isoDate(str)</a>:</p>
|
||||
<blockquote>
|
||||
Convert an ISO 8601 date (YYYY-MM-DD) to a <tt class="docutils literal"><span class="pre">Date</span></tt> object.</blockquote>
|
||||
<p>
|
||||
<a name="fn-isotimestamp"></a>
|
||||
<a class="mochidef reference" href="#fn-isotimestamp">isoTimestamp(str)</a>:</p>
|
||||
<blockquote>
|
||||
<p>Convert any ISO 8601 <a class="footnote-reference" href="#id3" id="id1" name="id1">[1]</a> timestamp (or something reasonably close to it)
|
||||
to a <tt class="docutils literal"><span class="pre">Date</span></tt> object. Will accept the "de facto" form:</p>
|
||||
<blockquote>
|
||||
YYYY-MM-DD hh:mm:ss</blockquote>
|
||||
<p>or (the proper form):</p>
|
||||
<blockquote>
|
||||
YYYY-MM-DDThh:mm:ssZ</blockquote>
|
||||
<p>If a time zone designator ("Z" or "[+-]HH:MM") is not present, then the
|
||||
local timezone is used.</p>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-toisotime"></a>
|
||||
<a class="mochidef reference" href="#fn-toisotime">toISOTime(date)</a>:</p>
|
||||
<blockquote>
|
||||
Convert a <tt class="docutils literal"><span class="pre">Date</span></tt> object to a string in the form of hh:mm:ss</blockquote>
|
||||
<p>
|
||||
<a name="fn-toisotimestamp"></a>
|
||||
<a class="mochidef reference" href="#fn-toisotimestamp">toISOTimestamp(date, realISO=false)</a>:</p>
|
||||
<blockquote>
|
||||
<p>Convert a <tt class="docutils literal"><span class="pre">Date</span></tt> object to something that's ALMOST but not quite an
|
||||
ISO 8601 [1]_timestamp. If it was a proper ISO timestamp it would be:</p>
|
||||
<blockquote>
|
||||
YYYY-MM-DDThh:mm:ssZ</blockquote>
|
||||
<p>However, we see junk in SQL and other places that looks like this:</p>
|
||||
<blockquote>
|
||||
YYYY-MM-DD hh:mm:ss</blockquote>
|
||||
<p>So, this function returns the latter form, despite its name, unless
|
||||
you pass <tt class="docutils literal"><span class="pre">true</span></tt> for <tt class="docutils literal"><span class="pre">realISO</span></tt>.</p>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-toisodate"></a>
|
||||
<a class="mochidef reference" href="#fn-toisodate">toISODate(date)</a>:</p>
|
||||
<blockquote>
|
||||
Convert a <tt class="docutils literal"><span class="pre">Date</span></tt> object to an ISO 8601 <a class="footnote-reference" href="#id3" id="id2" name="id2">[1]</a> date string (YYYY-MM-DD)</blockquote>
|
||||
<p>
|
||||
<a name="fn-americandate"></a>
|
||||
<a class="mochidef reference" href="#fn-americandate">americanDate(str)</a>:</p>
|
||||
<blockquote>
|
||||
Converts a MM/DD/YYYY date to a <tt class="docutils literal"><span class="pre">Date</span></tt> object</blockquote>
|
||||
<p>
|
||||
<a name="fn-topaddedamericandate"></a>
|
||||
<a class="mochidef reference" href="#fn-topaddedamericandate">toPaddedAmericanDate(date)</a>:</p>
|
||||
<blockquote>
|
||||
Converts a <tt class="docutils literal"><span class="pre">Date</span></tt> object to an MM/DD/YYYY date, e.g. 01/01/2001</blockquote>
|
||||
<p>
|
||||
<a name="fn-toamericandate"></a>
|
||||
<a class="mochidef reference" href="#fn-toamericandate">toAmericanDate(date)</a>:</p>
|
||||
<blockquote>
|
||||
Converts a <tt class="docutils literal"><span class="pre">Date</span></tt> object to an M/D/YYYY date, e.g. 1/1/2001</blockquote>
|
||||
</div>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h1><a id="see-also" name="see-also">See Also</a></h1>
|
||||
<table class="docutils footnote" frame="void" id="id3" rules="none">
|
||||
<colgroup><col class="label" /><col /></colgroup>
|
||||
<tbody valign="top">
|
||||
<tr><td class="label"><a name="id3">[1]</a></td><td><em>(<a class="fn-backref" href="#id1">1</a>, <a class="fn-backref" href="#id2">2</a>)</em> W3C profile of ISO 8601: <a class="reference" href="http://www.w3.org/TR/NOTE-datetime">http://www.w3.org/TR/NOTE-datetime</a></td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h1><a id="authors" name="authors">Authors</a></h1>
|
||||
<ul class="simple">
|
||||
<li>Bob Ippolito <<a class="reference" href="mailto:bob@redivi.com">bob@redivi.com</a>></li>
|
||||
</ul>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h1><a id="copyright" name="copyright">Copyright</a></h1>
|
||||
<p>Copyright 2005 Bob Ippolito <<a class="reference" href="mailto:bob@redivi.com">bob@redivi.com</a>>. This program is dual-licensed
|
||||
free software; you can redistribute it and/or modify it under the terms of the
|
||||
<a class="reference" href="http://www.opensource.org/licenses/mit-license.php">MIT License</a> or the <a class="reference" href="http://www.opensource.org/licenses/afl-2.1.php">Academic Free License v2.1</a>.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,241 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8" ?>
|
||||
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
|
||||
|
||||
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
|
||||
<meta name="generator" content="Docutils 0.4: http://docutils.sourceforge.net/" />
|
||||
<title>MochiKit.Format - string formatting goes here</title>
|
||||
|
||||
<link rel="stylesheet" href="../../../include/css/documentation.css" type="text/css" />
|
||||
<script type="text/javascript" src="../../../packed/lib/MochiKit/MochiKit.js"></script>
|
||||
<script type="text/javascript" src="../../js/toc.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div class="document">
|
||||
<div class="section">
|
||||
<h1><a id="name" name="name">Name</a></h1>
|
||||
<p>MochiKit.Format - string formatting goes here</p>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h1><a id="synopsis" name="synopsis">Synopsis</a></h1>
|
||||
<pre class="literal-block">
|
||||
assert( truncToFixed(0.12345, 4) == "0.1234" );
|
||||
assert( roundToFixed(0.12345, 4) == "0.1235" );
|
||||
assert( twoDigitAverage(1, 0) == "0" );
|
||||
assert( twoDigitFloat(1.2345) == "1.23" );
|
||||
assert( twoDigitFloat(1) == "1" );
|
||||
assert( percentFormat(1.234567) == "123.46%" );
|
||||
assert( numberFormatter("###,###%")(125) == "12,500%" );
|
||||
assert( numberFormatter("##.000")(1.25) == "1.250" );
|
||||
</pre>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h1><a id="description" name="description">Description</a></h1>
|
||||
<p>Formatting strings and stringifying numbers is boring, so a couple useful
|
||||
functions in that domain live here.</p>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h1><a id="dependencies" name="dependencies">Dependencies</a></h1>
|
||||
<p>None.</p>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h1><a id="overview" name="overview">Overview</a></h1>
|
||||
<div class="section">
|
||||
<h2><a id="formatting-numbers" name="formatting-numbers">Formatting Numbers</a></h2>
|
||||
<p>MochiKit provides an extensible number formatting facility, modeled loosely
|
||||
after the Number Format Pattern Syntax <a class="footnote-reference" href="#id2" id="id1" name="id1">[1]</a> from Java.
|
||||
<a class="mochiref reference" href="#fn-numberformatter">numberFormatter(pattern[, placeholder=""[, locale="default"])</a>
|
||||
returns a function that converts Number to string using the given information.
|
||||
<tt class="docutils literal"><span class="pre">pattern</span></tt> is a string consisting of the following symbols:</p>
|
||||
<table border="1" class="docutils">
|
||||
<colgroup>
|
||||
<col width="15%" />
|
||||
<col width="85%" />
|
||||
</colgroup>
|
||||
<thead valign="bottom">
|
||||
<tr><th class="head">Symbol</th>
|
||||
<th class="head">Meaning</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody valign="top">
|
||||
<tr><td><tt class="docutils literal"><span class="pre">-</span></tt></td>
|
||||
<td>If given, used as the position of the minus sign
|
||||
for negative numbers. If not given, the position
|
||||
to the left of the first number placeholder is used.</td>
|
||||
</tr>
|
||||
<tr><td><tt class="docutils literal"><span class="pre">#</span></tt></td>
|
||||
<td>The placeholder for a number that does not imply zero
|
||||
padding.</td>
|
||||
</tr>
|
||||
<tr><td><tt class="docutils literal"><span class="pre">0</span></tt></td>
|
||||
<td>The placeholder for a number that implies zero padding.
|
||||
If it is used to the right of a decimal separator, it
|
||||
implies trailing zeros, otherwise leading zeros.</td>
|
||||
</tr>
|
||||
<tr><td><tt class="docutils literal"><span class="pre">,</span></tt></td>
|
||||
<td>The placeholder for a "thousands separator". May be used
|
||||
at most once, and it must be to the left of a decimal
|
||||
separator. Will be replaced by <tt class="docutils literal"><span class="pre">locale.separator</span></tt> in the
|
||||
result (the default is also <tt class="docutils literal"><span class="pre">,</span></tt>).</td>
|
||||
</tr>
|
||||
<tr><td><tt class="docutils literal"><span class="pre">.</span></tt></td>
|
||||
<td>The decimal separator. The quantity of <tt class="docutils literal"><span class="pre">#</span></tt> or <tt class="docutils literal"><span class="pre">0</span></tt>
|
||||
after the decimal separator will determine the precision of
|
||||
the result. If no decimal separator is present, the
|
||||
fractional precision is <tt class="docutils literal"><span class="pre">0</span></tt> -- meaning that it will be
|
||||
rounded to the nearest integer.</td>
|
||||
</tr>
|
||||
<tr><td><tt class="docutils literal"><span class="pre">%</span></tt></td>
|
||||
<td>If present, the number will be multiplied by <tt class="docutils literal"><span class="pre">100</span></tt> and
|
||||
the <tt class="docutils literal"><span class="pre">%</span></tt> will be replaced by <tt class="docutils literal"><span class="pre">locale.percent</span></tt>.</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h1><a id="api-reference" name="api-reference">API Reference</a></h1>
|
||||
<div class="section">
|
||||
<h2><a id="functions" name="functions">Functions</a></h2>
|
||||
<p>
|
||||
<a name="fn-formatlocale"></a>
|
||||
<a class="mochidef reference" href="#fn-formatlocale">formatLocale(locale="default")</a>:</p>
|
||||
<blockquote>
|
||||
Return a locale object for the given locale. <tt class="docutils literal"><span class="pre">locale</span></tt> may be either a
|
||||
string, which is looked up in the <tt class="docutils literal"><span class="pre">MochiKit.Format.LOCALE</span></tt> object, or
|
||||
a locale object. If no locale is given, <tt class="docutils literal"><span class="pre">LOCALE.default</span></tt> is used
|
||||
(equivalent to <tt class="docutils literal"><span class="pre">LOCALE.en_US</span></tt>).</blockquote>
|
||||
<p>
|
||||
<a name="fn-lstrip"></a>
|
||||
<a class="mochidef reference" href="#fn-lstrip">lstrip(str, chars="\s")</a>:</p>
|
||||
<blockquote>
|
||||
<p>Returns a string based on <tt class="docutils literal"><span class="pre">str</span></tt> with leading whitespace stripped.</p>
|
||||
<p>If <tt class="docutils literal"><span class="pre">chars</span></tt> is given, then that expression will be used instead of
|
||||
whitespace. <tt class="docutils literal"><span class="pre">chars</span></tt> should be a string suitable for use in a <tt class="docutils literal"><span class="pre">RegExp</span></tt>
|
||||
<tt class="docutils literal"><span class="pre">[character</span> <span class="pre">set]</span></tt>.</p>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-numberformatter"></a>
|
||||
<a class="mochidef reference" href="#fn-numberformatter">numberFormatter(pattern, placeholder="", locale="default")</a>:</p>
|
||||
<blockquote>
|
||||
<p>Return a function <tt class="docutils literal"><span class="pre">formatNumber(aNumber)</span></tt> that formats numbers
|
||||
as a string according to the given pattern, placeholder and locale.</p>
|
||||
<p><tt class="docutils literal"><span class="pre">pattern</span></tt> is a string that describes how the numbers should be formatted,
|
||||
for more information see <a class="reference" href="#formatting-numbers">Formatting Numbers</a>.</p>
|
||||
<p><tt class="docutils literal"><span class="pre">locale</span></tt> is a string of a known locale (en_US, de_DE, fr_FR, default) or
|
||||
an object with the following fields:</p>
|
||||
<table border="1" class="docutils">
|
||||
<colgroup>
|
||||
<col width="16%" />
|
||||
<col width="84%" />
|
||||
</colgroup>
|
||||
<tbody valign="top">
|
||||
<tr><td>separator</td>
|
||||
<td>The "thousands" separator for this locale (en_US is ",")</td>
|
||||
</tr>
|
||||
<tr><td>decimal</td>
|
||||
<td>The decimal separator for this locale (en_US is ".")</td>
|
||||
</tr>
|
||||
<tr><td>percent</td>
|
||||
<td>The percent symbol for this locale (en_US is "%")</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-percentformat"></a>
|
||||
<a class="mochidef reference" href="#fn-percentformat">percentFormat(someFloat)</a>:</p>
|
||||
<blockquote>
|
||||
<p>Roughly equivalent to: <tt class="docutils literal"><span class="pre">sprintf("%.2f%%",</span> <span class="pre">someFloat</span> <span class="pre">*</span> <span class="pre">100)</span></tt></p>
|
||||
<p>In new code, you probably want to use:
|
||||
<a class="mochiref reference" href="#fn-numberformatter">numberFormatter("#.##%")(someFloat)</a> instead.</p>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-roundtofixed"></a>
|
||||
<a class="mochidef reference" href="#fn-roundtofixed">roundToFixed(aNumber, precision)</a>:</p>
|
||||
<blockquote>
|
||||
<p>Return a string representation of <tt class="docutils literal"><span class="pre">aNumber</span></tt>, rounded to <tt class="docutils literal"><span class="pre">precision</span></tt>
|
||||
digits with trailing zeros. This is similar to
|
||||
<tt class="docutils literal"><span class="pre">Number.toFixed(aNumber,</span> <span class="pre">precision)</span></tt>, but this has implementation
|
||||
consistent rounding behavior (some versions of Safari round 0.5 down!)
|
||||
and also includes preceding <tt class="docutils literal"><span class="pre">0</span></tt> for numbers less than <tt class="docutils literal"><span class="pre">1</span></tt> (Safari,
|
||||
again).</p>
|
||||
<p>For example, <a class="mochiref reference" href="#fn-roundtofixed">roundToFixed(0.1357, 2)</a> returns <tt class="docutils literal"><span class="pre">0.14</span></tt> on every
|
||||
supported platform, where some return <tt class="docutils literal"><span class="pre">.13</span></tt> for <tt class="docutils literal"><span class="pre">(0.1357).toFixed(2)</span></tt>.</p>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-rstrip"></a>
|
||||
<a class="mochidef reference" href="#fn-rstrip">rstrip(str, chars="\s")</a>:</p>
|
||||
<blockquote>
|
||||
<p>Returns a string based on <tt class="docutils literal"><span class="pre">str</span></tt> with trailing whitespace stripped.</p>
|
||||
<p>If <tt class="docutils literal"><span class="pre">chars</span></tt> is given, then that expression will be used instead of
|
||||
whitespace. <tt class="docutils literal"><span class="pre">chars</span></tt> should be a string suitable for use in a <tt class="docutils literal"><span class="pre">RegExp</span></tt>
|
||||
<tt class="docutils literal"><span class="pre">[character</span> <span class="pre">set]</span></tt>.</p>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-strip"></a>
|
||||
<a class="mochidef reference" href="#fn-strip">strip(str, chars="\s")</a>:</p>
|
||||
<blockquote>
|
||||
<p>Returns a string based on <tt class="docutils literal"><span class="pre">str</span></tt> with leading and trailing whitespace
|
||||
stripped (equivalent to <a class="mochiref reference" href="#fn-lstrip">lstrip(rstrip(str, chars), chars)</a>).</p>
|
||||
<p>If <tt class="docutils literal"><span class="pre">chars</span></tt> is given, then that expression will be used instead of
|
||||
whitespace. <tt class="docutils literal"><span class="pre">chars</span></tt> should be a string suitable for use in a <tt class="docutils literal"><span class="pre">RegExp</span></tt>
|
||||
<tt class="docutils literal"><span class="pre">[character</span> <span class="pre">set]</span></tt>.</p>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-trunctofixed"></a>
|
||||
<a class="mochidef reference" href="#fn-trunctofixed">truncToFixed(aNumber, precision)</a>:</p>
|
||||
<blockquote>
|
||||
<p>Return a string representation of <tt class="docutils literal"><span class="pre">aNumber</span></tt>, truncated to <tt class="docutils literal"><span class="pre">precision</span></tt>
|
||||
digits with trailing zeros. This is similar to
|
||||
<tt class="docutils literal"><span class="pre">aNumber.toFixed(precision)</span></tt>, but this truncates rather than rounds and
|
||||
has implementation consistent behavior for numbers less than 1.
|
||||
Specifically, <a class="mochiref reference" href="#fn-trunctofixed">truncToFixed(aNumber, precision)</a> will always have a
|
||||
preceding <tt class="docutils literal"><span class="pre">0</span></tt> for numbers less than <tt class="docutils literal"><span class="pre">1</span></tt>.</p>
|
||||
<p>For example, <a class="mochiref reference" href="#fn-tofixed">toFixed(0.1357, 2)</a> returns <tt class="docutils literal"><span class="pre">0.13</span></tt>.</p>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-twodigitaverage"></a>
|
||||
<a class="mochidef reference" href="#fn-twodigitaverage">twoDigitAverage(numerator, denominator)</a>:</p>
|
||||
<blockquote>
|
||||
<p>Calculate an average from a numerator and a denominator and return
|
||||
it as a string with two digits of precision (e.g. "1.23").</p>
|
||||
<p>If the denominator is 0, "0" will be returned instead of <tt class="docutils literal"><span class="pre">NaN</span></tt>.</p>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-twodigitfloat"></a>
|
||||
<a class="mochidef reference" href="#fn-twodigitfloat">twoDigitFloat(someFloat)</a>:</p>
|
||||
<blockquote>
|
||||
<p>Roughly equivalent to: <tt class="docutils literal"><span class="pre">sprintf("%.2f",</span> <span class="pre">someFloat)</span></tt></p>
|
||||
<p>In new code, you probably want to use
|
||||
<a class="mochiref reference" href="#fn-numberformatter">numberFormatter("#.##")(someFloat)</a> instead.</p>
|
||||
</blockquote>
|
||||
</div>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h1><a id="see-also" name="see-also">See Also</a></h1>
|
||||
<table class="docutils footnote" frame="void" id="id2" rules="none">
|
||||
<colgroup><col class="label" /><col /></colgroup>
|
||||
<tbody valign="top">
|
||||
<tr><td class="label"><a class="fn-backref" href="#id1" name="id2">[1]</a></td><td>Java Number Format Pattern Syntax:
|
||||
<a class="reference" href="http://java.sun.com/docs/books/tutorial/i18n/format/numberpattern.html">http://java.sun.com/docs/books/tutorial/i18n/format/numberpattern.html</a></td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h1><a id="authors" name="authors">Authors</a></h1>
|
||||
<ul class="simple">
|
||||
<li>Bob Ippolito <<a class="reference" href="mailto:bob@redivi.com">bob@redivi.com</a>></li>
|
||||
</ul>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h1><a id="copyright" name="copyright">Copyright</a></h1>
|
||||
<p>Copyright 2005 Bob Ippolito <<a class="reference" href="mailto:bob@redivi.com">bob@redivi.com</a>>. This program is dual-licensed
|
||||
free software; you can redistribute it and/or modify it under the terms of the
|
||||
<a class="reference" href="http://www.opensource.org/licenses/mit-license.php">MIT License</a> or the <a class="reference" href="http://www.opensource.org/licenses/afl-2.1.php">Academic Free License v2.1</a>.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,372 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8" ?>
|
||||
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
|
||||
|
||||
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
|
||||
<meta name="generator" content="Docutils 0.4: http://docutils.sourceforge.net/" />
|
||||
<title>MochiKit.Iter - itertools for JavaScript; iteration made HARD, and then easy</title>
|
||||
|
||||
<link rel="stylesheet" href="../../../include/css/documentation.css" type="text/css" />
|
||||
<script type="text/javascript" src="../../../packed/lib/MochiKit/MochiKit.js"></script>
|
||||
<script type="text/javascript" src="../../js/toc.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div class="document">
|
||||
<div class="section">
|
||||
<h1><a id="name" name="name">Name</a></h1>
|
||||
<p>MochiKit.Iter - itertools for JavaScript; iteration made HARD, and then easy</p>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h1><a id="synopsis" name="synopsis">Synopsis</a></h1>
|
||||
<pre class="literal-block">
|
||||
theSum = sum(takewhile(
|
||||
partial(operator.gt, 10),
|
||||
imap(
|
||||
partial(operator.mul, 2),
|
||||
count()
|
||||
)
|
||||
)
|
||||
));
|
||||
|
||||
assert( theSum == (0 + 0 + 2 + 4 + 6 + 8) );
|
||||
</pre>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h1><a id="description" name="description">Description</a></h1>
|
||||
<p>All of the functional programming missing from <a class="mochiref reference" href="Base.html">MochiKit.Base</a> lives
|
||||
here. The functionality in this module is largely inspired by Python's iteration
|
||||
protocol <a class="footnote-reference" href="#id4" id="id1" name="id1">[1]</a>, and the itertools module <a class="footnote-reference" href="#id5" id="id2" name="id2">[2]</a>.</p>
|
||||
<p>MochiKit.Iter defines a standard way to iterate over anything, that you can
|
||||
extend with <a class="mochiref reference" href="#fn-registeriterator">registerIterator</a>, or by implementing the <tt class="docutils literal"><span class="pre">.iter()</span></tt>
|
||||
protocol. Iterators are lazy, so it can potentially be cheaper to build a
|
||||
filter chain of iterators than to build lots of intermediate arrays.
|
||||
Especially when the data set is very large, but the result is not.</p>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h1><a id="dependencies" name="dependencies">Dependencies</a></h1>
|
||||
<ul class="simple">
|
||||
<li><a class="mochiref reference" href="Base.html">MochiKit.Base</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h1><a id="overview" name="overview">Overview</a></h1>
|
||||
<div class="section">
|
||||
<h2><a id="iteration-for-javascript" name="iteration-for-javascript">Iteration for JavaScript</a></h2>
|
||||
<p>The best overview right now is in my Iteration for JavaScript <a class="footnote-reference" href="#id6" id="id3" name="id3">[3]</a> blog entry.
|
||||
This information will migrate here eventually.</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h1><a id="api-reference" name="api-reference">API Reference</a></h1>
|
||||
<div class="section">
|
||||
<h2><a id="errors" name="errors">Errors</a></h2>
|
||||
<p>
|
||||
<a name="fn-stopiteration"></a>
|
||||
<a class="mochidef reference" href="#fn-stopiteration">StopIteration</a>:</p>
|
||||
<blockquote>
|
||||
The singleton <a class="mochiref reference" href="Base.html#fn-namederror">MochiKit.Base.NamedError</a> that signifies the end
|
||||
of an iterator</blockquote>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h2><a id="functions" name="functions">Functions</a></h2>
|
||||
<p>
|
||||
<a name="fn-applymap"></a>
|
||||
<a class="mochidef reference" href="#fn-applymap">applymap(fun, seq[, self])</a>:</p>
|
||||
<blockquote>
|
||||
<dl class="docutils">
|
||||
<dt><tt class="docutils literal"><span class="pre">applymap(fun,</span> <span class="pre">seq)</span></tt> --></dt>
|
||||
<dd>fun.apply(self, seq0), fun.apply(self, seq1), ...</dd>
|
||||
</dl>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-chain"></a>
|
||||
<a class="mochidef reference" href="#fn-chain">chain(p, q[, ...])</a>:</p>
|
||||
<blockquote>
|
||||
<tt class="docutils literal"><span class="pre">chain(p,</span> <span class="pre">q,</span> <span class="pre">...)</span></tt> --> p0, p1, ... plast, q0, q1, ...</blockquote>
|
||||
<p>
|
||||
<a name="fn-count"></a>
|
||||
<a class="mochidef reference" href="#fn-count">count(n=0)</a>:</p>
|
||||
<blockquote>
|
||||
<tt class="docutils literal"><span class="pre">count(n=0)</span></tt> --> n, n + 1, n + 2, ...</blockquote>
|
||||
<p>
|
||||
<a name="fn-cycle"></a>
|
||||
<a class="mochidef reference" href="#fn-cycle">cycle(p)</a>:</p>
|
||||
<blockquote>
|
||||
<tt class="docutils literal"><span class="pre">cycle(p)</span></tt> --> p0, p1, ... plast, p0, p1, ...</blockquote>
|
||||
<p>
|
||||
<a name="fn-dropwhile"></a>
|
||||
<a class="mochidef reference" href="#fn-dropwhile">dropwhile(pred, seq)</a>:</p>
|
||||
<blockquote>
|
||||
<dl class="docutils">
|
||||
<dt><tt class="docutils literal"><span class="pre">dropwhile(pred,</span> <span class="pre">seq)</span></tt> --> seq[n], seq[n + 1], starting when</dt>
|
||||
<dd>pred(seq[n]) fails</dd>
|
||||
</dl>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-every"></a>
|
||||
<a class="mochidef reference" href="#fn-every">every(iterable, func)</a>:</p>
|
||||
<blockquote>
|
||||
Return <tt class="docutils literal"><span class="pre">true</span></tt> if <tt class="docutils literal"><span class="pre">func(item)</span></tt> is <tt class="docutils literal"><span class="pre">true</span></tt> for every item in
|
||||
<tt class="docutils literal"><span class="pre">iterable</span></tt>.</blockquote>
|
||||
<p>
|
||||
<a name="fn-exhaust"></a>
|
||||
<a class="mochidef reference" href="#fn-exhaust">exhaust(iterable)</a>:</p>
|
||||
<blockquote>
|
||||
Exhausts an iterable without saving the results anywhere,
|
||||
like <a class="mochiref reference" href="#fn-list">list(iterable)</a> when you don't care what the output is.</blockquote>
|
||||
<p>
|
||||
<a name="fn-foreach"></a>
|
||||
<a class="mochidef reference" href="#fn-foreach">forEach(iterable, func[, self])</a>:</p>
|
||||
<blockquote>
|
||||
Call <tt class="docutils literal"><span class="pre">func</span></tt> for each item in <tt class="docutils literal"><span class="pre">iterable</span></tt>, and don't save the results.</blockquote>
|
||||
<p>
|
||||
<a name="fn-groupby"></a>
|
||||
<a class="mochidef reference" href="#fn-groupby">groupby(iterable[, keyfunc])</a>:</p>
|
||||
<blockquote>
|
||||
<p>Make an iterator that returns consecutive keys and groups from the
|
||||
iterable. The key is a function computing a key value for each element.
|
||||
If not specified or is None, key defaults to an identity function and
|
||||
returns the element unchanged. Generally, the iterable needs to already be
|
||||
sorted on the same key function.</p>
|
||||
<p>The returned group is itself an iterator that shares the underlying
|
||||
iterable with <a class="mochiref reference" href="#fn-groupby">groupby()</a>. Because the source is shared, when the
|
||||
groupby object is advanced, the previous group is no longer visible.
|
||||
So, if that data is needed later, it should be stored as an array:</p>
|
||||
<pre class="literal-block">
|
||||
var groups = [];
|
||||
var uniquekeys = [];
|
||||
forEach(groupby(data, keyfunc), function (key_group) {
|
||||
groups.push(list(key_group[1]));
|
||||
uniquekeys.push(key_group[0]);
|
||||
});
|
||||
</pre>
|
||||
<p>As a convenience, <a class="mochiref reference" href="#fn-groupby_as_array">groupby_as_array()</a> is provided to suit the above
|
||||
use case.</p>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-groupby_as_array"></a>
|
||||
<a class="mochidef reference" href="#fn-groupby_as_array">groupby_as_array(iterable[, keyfunc])</a>:</p>
|
||||
<blockquote>
|
||||
Perform the same task as <a class="mochiref reference" href="#fn-groupby">groupby()</a>, except return an array of
|
||||
arrays instead of an iterator of iterators.</blockquote>
|
||||
<p>
|
||||
<a name="fn-iextend"></a>
|
||||
<a class="mochidef reference" href="#fn-iextend">iextend(lst, iterable)</a>:</p>
|
||||
<blockquote>
|
||||
Just like <a class="mochiref reference" href="#fn-list">list(iterable)</a>, except it pushes results on <tt class="docutils literal"><span class="pre">lst</span></tt>
|
||||
rather than creating a new one.</blockquote>
|
||||
<p>
|
||||
<a name="fn-ifilter"></a>
|
||||
<a class="mochidef reference" href="#fn-ifilter">ifilter(pred, seq)</a>:</p>
|
||||
<blockquote>
|
||||
<tt class="docutils literal"><span class="pre">ifilter(pred,</span> <span class="pre">seq)</span></tt> --> elements of seq where <tt class="docutils literal"><span class="pre">pred(elem)</span></tt> is <tt class="docutils literal"><span class="pre">true</span></tt></blockquote>
|
||||
<p>
|
||||
<a name="fn-ifilterfalse"></a>
|
||||
<a class="mochidef reference" href="#fn-ifilterfalse">ifilterfalse(pred, seq)</a>:</p>
|
||||
<blockquote>
|
||||
<dl class="docutils">
|
||||
<dt><tt class="docutils literal"><span class="pre">ifilterfalse(pred,</span> <span class="pre">seq)</span></tt> --> elements of seq where <tt class="docutils literal"><span class="pre">pred(elem)</span></tt> is</dt>
|
||||
<dd><tt class="docutils literal"><span class="pre">false</span></tt></dd>
|
||||
</dl>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-imap"></a>
|
||||
<a class="mochidef reference" href="#fn-imap">imap(fun, p, q[, ...])</a>:</p>
|
||||
<blockquote>
|
||||
<tt class="docutils literal"><span class="pre">imap(fun,</span> <span class="pre">p,</span> <span class="pre">q,</span> <span class="pre">...)</span></tt> --> fun(p0, q0, ...), fun(p1, q1, ...), ...</blockquote>
|
||||
<p>
|
||||
<a name="fn-islice"></a>
|
||||
<a class="mochidef reference" href="#fn-islice">islice(seq, [start,] stop[, step])</a>:</p>
|
||||
<blockquote>
|
||||
<dl class="docutils">
|
||||
<dt><tt class="docutils literal"><span class="pre">islice(seq,</span> <span class="pre">[start,]</span> <span class="pre">stop[,</span> <span class="pre">step])</span></tt> --> elements from</dt>
|
||||
<dd>seq[start:stop:step] (in Python slice syntax)</dd>
|
||||
</dl>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-iter"></a>
|
||||
<a class="mochidef reference" href="#fn-iter">iter(iterable[, sentinel])</a>:</p>
|
||||
<blockquote>
|
||||
<p>Convert the given argument to an iterator (object implementing
|
||||
<tt class="docutils literal"><span class="pre">.next()</span></tt>).</p>
|
||||
<ol class="arabic simple">
|
||||
<li>If <tt class="docutils literal"><span class="pre">iterable</span></tt> is an iterator (implements <tt class="docutils literal"><span class="pre">.next()</span></tt>), then it will
|
||||
be returned as-is.</li>
|
||||
<li>If <tt class="docutils literal"><span class="pre">iterable</span></tt> is an iterator factory (implements <tt class="docutils literal"><span class="pre">.iter()</span></tt>), then
|
||||
the result of <tt class="docutils literal"><span class="pre">iterable.iter()</span></tt> will be returned.</li>
|
||||
<li>Otherwise, the iterator factory <a class="mochiref reference" href="Base.html#fn-adapterregistry">MochiKit.Base.AdapterRegistry</a>
|
||||
is used to find a match.</li>
|
||||
<li>If no factory is found, it will throw <tt class="docutils literal"><span class="pre">TypeError</span></tt></li>
|
||||
</ol>
|
||||
<p>Built-in iterator factories are present for Array-like objects, and
|
||||
objects that implement the <tt class="docutils literal"><span class="pre">iterateNext</span></tt> protocol (e.g. the result of
|
||||
Mozilla's <tt class="docutils literal"><span class="pre">document.evaluate</span></tt>).</p>
|
||||
<p>When used directly, using an iterator should look like this:</p>
|
||||
<pre class="literal-block">
|
||||
var it = iter(iterable);
|
||||
try {
|
||||
while (var o = it.next()) {
|
||||
// use o
|
||||
}
|
||||
} catch (e) {
|
||||
if (e != StopIteration) {
|
||||
throw e;
|
||||
}
|
||||
// pass
|
||||
}
|
||||
</pre>
|
||||
<p>This is ugly, so you should use the higher order functions to work
|
||||
with iterators whenever possible.</p>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-izip"></a>
|
||||
<a class="mochidef reference" href="#fn-izip">izip(p, q[, ...])</a>:</p>
|
||||
<blockquote>
|
||||
<tt class="docutils literal"><span class="pre">izip(p,</span> <span class="pre">q,</span> <span class="pre">...)</span></tt> --> [p0, q0, ...], [p1, q1, ...], ...</blockquote>
|
||||
<p>
|
||||
<a name="fn-list"></a>
|
||||
<a class="mochidef reference" href="#fn-list">list(iterable)</a>:</p>
|
||||
<blockquote>
|
||||
Convert <tt class="docutils literal"><span class="pre">iterable</span></tt> to a new <tt class="docutils literal"><span class="pre">Array</span></tt></blockquote>
|
||||
<p>
|
||||
<a name="fn-next"></a>
|
||||
<a class="mochidef reference" href="#fn-next">next(iterator)</a>:</p>
|
||||
<blockquote>
|
||||
Return <tt class="docutils literal"><span class="pre">iterator.next()</span></tt></blockquote>
|
||||
<p>
|
||||
<a name="fn-range"></a>
|
||||
<a class="mochidef reference" href="#fn-range">range([start,] stop[, step])</a>:</p>
|
||||
<blockquote>
|
||||
<p>Return an iterator containing an arithmetic progression of integers.</p>
|
||||
<p><tt class="docutils literal"><span class="pre">range(i,</span> <span class="pre">j)</span></tt> returns <a class="mochiref reference" href="#fn-iter">iter([i, i + 1, i + 2, ..., j - 1])</a></p>
|
||||
<p><tt class="docutils literal"><span class="pre">start</span></tt> (!) defaults to <tt class="docutils literal"><span class="pre">0</span></tt>. When <tt class="docutils literal"><span class="pre">step</span></tt> is given, it specifies the
|
||||
increment (or decrement). The end point is omitted!</p>
|
||||
<p>For example, <tt class="docutils literal"><span class="pre">range(4)</span></tt> returns <a class="mochiref reference" href="#fn-iter">iter([0, 1, 2, 3])</a>.
|
||||
This iterates over exactly the valid indexes for an array of 4 elements.</p>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-reduce"></a>
|
||||
<a class="mochidef reference" href="#fn-reduce">reduce(fn, iterable[, initial])</a>:</p>
|
||||
<blockquote>
|
||||
<p>Apply <tt class="docutils literal"><span class="pre">fn(a,</span> <span class="pre">b)</span></tt> cumulatively to the items of an
|
||||
iterable from left to right, so as to reduce the iterable
|
||||
to a single value.</p>
|
||||
<p>For example:</p>
|
||||
<pre class="literal-block">
|
||||
reduce(function (a, b) { return x + y; }, [1, 2, 3, 4, 5])
|
||||
</pre>
|
||||
<p>calculates:</p>
|
||||
<pre class="literal-block">
|
||||
((((1 + 2) + 3) + 4) + 5).
|
||||
</pre>
|
||||
<p>If initial is given, it is placed before the items of the sequence
|
||||
in the calculation, and serves as a default when the sequence is
|
||||
empty.</p>
|
||||
<p>Note that the above example could be written more clearly as:</p>
|
||||
<pre class="literal-block">
|
||||
reduce(operator.add, [1, 2, 3, 4, 5])
|
||||
</pre>
|
||||
<p>Or even simpler:</p>
|
||||
<pre class="literal-block">
|
||||
sum([1, 2, 3, 4, 5])
|
||||
</pre>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-registeriteratorfactory"></a>
|
||||
<a class="mochidef reference" href="#fn-registeriteratorfactory">registerIteratorFactory(name, check, iterfactory[, override])</a>:</p>
|
||||
<blockquote>
|
||||
<p>Register an iterator factory for use with the iter function.</p>
|
||||
<p><tt class="docutils literal"><span class="pre">check</span></tt> is a <tt class="docutils literal"><span class="pre">function(a)</span></tt> that returns <tt class="docutils literal"><span class="pre">true</span></tt> if <tt class="docutils literal"><span class="pre">a</span></tt> can be
|
||||
converted into an iterator with <tt class="docutils literal"><span class="pre">iterfactory</span></tt>.</p>
|
||||
<p><tt class="docutils literal"><span class="pre">iterfactory</span></tt> is a <tt class="docutils literal"><span class="pre">function(a)</span></tt> that returns an object with a
|
||||
<tt class="docutils literal"><span class="pre">.next()</span></tt> method that returns the next value in the sequence.</p>
|
||||
<p><tt class="docutils literal"><span class="pre">iterfactory</span></tt> is guaranteed to only be called if <tt class="docutils literal"><span class="pre">check(a)</span></tt>
|
||||
returns a true value.</p>
|
||||
<p>If <tt class="docutils literal"><span class="pre">override</span></tt> is <tt class="docutils literal"><span class="pre">true</span></tt>, then it will be made the
|
||||
highest precedence iterator factory. Otherwise, the lowest.</p>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-repeat"></a>
|
||||
<a class="mochidef reference" href="#fn-repeat">repeat(elem[, n])</a>:</p>
|
||||
<blockquote>
|
||||
<tt class="docutils literal"><span class="pre">repeat(elem,</span> <span class="pre">[,n])</span></tt> --> elem, elem, elem, ... endlessly or up to n times</blockquote>
|
||||
<p>
|
||||
<a name="fn-reversed"></a>
|
||||
<a class="mochidef reference" href="#fn-reversed">reversed(iterable)</a>:</p>
|
||||
<blockquote>
|
||||
Return a reversed array from iterable.</blockquote>
|
||||
<p>
|
||||
<a name="fn-some"></a>
|
||||
<a class="mochidef reference" href="#fn-some">some(iterable, func)</a>:</p>
|
||||
<blockquote>
|
||||
Return <tt class="docutils literal"><span class="pre">true</span></tt> if <tt class="docutils literal"><span class="pre">func(item)</span></tt> is <tt class="docutils literal"><span class="pre">true</span></tt> for at least one item in
|
||||
<tt class="docutils literal"><span class="pre">iterable</span></tt>.</blockquote>
|
||||
<p>
|
||||
<a name="fn-sorted"></a>
|
||||
<a class="mochidef reference" href="#fn-sorted">sorted(iterable[, cmp])</a>:</p>
|
||||
<blockquote>
|
||||
Return a sorted array from iterable.</blockquote>
|
||||
<p>
|
||||
<a name="fn-sum"></a>
|
||||
<a class="mochidef reference" href="#fn-sum">sum(iterable, start=0)</a>:</p>
|
||||
<blockquote>
|
||||
<p>Returns the sum of a sequence of numbers plus the value
|
||||
of parameter <tt class="docutils literal"><span class="pre">start</span></tt> (with a default of 0). When the sequence is
|
||||
empty, returns start.</p>
|
||||
<p>Equivalent to:</p>
|
||||
<pre class="literal-block">
|
||||
reduce(operator.add, iterable, start);
|
||||
</pre>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-takewhile"></a>
|
||||
<a class="mochidef reference" href="#fn-takewhile">takewhile(pred, seq)</a>:</p>
|
||||
<blockquote>
|
||||
<tt class="docutils literal"><span class="pre">takewhile(pred,</span> <span class="pre">seq)</span></tt> --> seq[0], seq[1], ... until pred(seq[n]) fails</blockquote>
|
||||
<p>
|
||||
<a name="fn-tee"></a>
|
||||
<a class="mochidef reference" href="#fn-tee">tee(iterable, n=2)</a>:</p>
|
||||
<blockquote>
|
||||
<tt class="docutils literal"><span class="pre">tee(it,</span> <span class="pre">n=2)</span></tt> --> [it1, it2, it3, ... itn] splits one iterator into n</blockquote>
|
||||
</div>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h1><a id="see-also" name="see-also">See Also</a></h1>
|
||||
<table class="docutils footnote" frame="void" id="id4" rules="none">
|
||||
<colgroup><col class="label" /><col /></colgroup>
|
||||
<tbody valign="top">
|
||||
<tr><td class="label"><a class="fn-backref" href="#id1" name="id4">[1]</a></td><td>The iteration protocol is described in
|
||||
PEP 234 - Iterators: <a class="reference" href="http://www.python.org/peps/pep-0234.html">http://www.python.org/peps/pep-0234.html</a></td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<table class="docutils footnote" frame="void" id="id5" rules="none">
|
||||
<colgroup><col class="label" /><col /></colgroup>
|
||||
<tbody valign="top">
|
||||
<tr><td class="label"><a class="fn-backref" href="#id2" name="id5">[2]</a></td><td>Python's itertools
|
||||
module: <a class="reference" href="http://docs.python.org/lib/module-itertools.html">http://docs.python.org/lib/module-itertools.html</a></td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<table class="docutils footnote" frame="void" id="id6" rules="none">
|
||||
<colgroup><col class="label" /><col /></colgroup>
|
||||
<tbody valign="top">
|
||||
<tr><td class="label"><a class="fn-backref" href="#id3" name="id6">[3]</a></td><td>Iteration in JavaScript: <a class="reference" href="http://bob.pythonmac.org/archives/2005/07/06/iteration-in-javascript/">http://bob.pythonmac.org/archives/2005/07/06/iteration-in-javascript/</a></td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h1><a id="authors" name="authors">Authors</a></h1>
|
||||
<ul class="simple">
|
||||
<li>Bob Ippolito <<a class="reference" href="mailto:bob@redivi.com">bob@redivi.com</a>></li>
|
||||
</ul>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h1><a id="copyright" name="copyright">Copyright</a></h1>
|
||||
<p>Copyright 2005 Bob Ippolito <<a class="reference" href="mailto:bob@redivi.com">bob@redivi.com</a>>. This program is dual-licensed
|
||||
free software; you can redistribute it and/or modify it under the terms of the
|
||||
<a class="reference" href="http://www.opensource.org/licenses/mit-license.php">MIT License</a> or the <a class="reference" href="http://www.opensource.org/licenses/afl-2.1.php">Academic Free License v2.1</a>.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,310 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8" ?>
|
||||
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
|
||||
|
||||
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
|
||||
<meta name="generator" content="Docutils 0.4: http://docutils.sourceforge.net/" />
|
||||
<title>MochiKit.Logging - we're all tired of alert()</title>
|
||||
|
||||
<link rel="stylesheet" href="../../../include/css/documentation.css" type="text/css" />
|
||||
<script type="text/javascript" src="../../../packed/lib/MochiKit/MochiKit.js"></script>
|
||||
<script type="text/javascript" src="../../js/toc.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div class="document">
|
||||
<div class="section">
|
||||
<h1><a id="name" name="name">Name</a></h1>
|
||||
<p>MochiKit.Logging - we're all tired of alert()</p>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h1><a id="synopsis" name="synopsis">Synopsis</a></h1>
|
||||
<pre class="literal-block">
|
||||
log("INFO messages are so boring");
|
||||
logDebug("DEBUG messages are even worse");
|
||||
log("good thing I can pass", objects, "conveniently");
|
||||
</pre>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h1><a id="description" name="description">Description</a></h1>
|
||||
<p>MochiKit.Logging steals some ideas from Python's logging module <a class="footnote-reference" href="#id6" id="id1" name="id1">[1]</a>, but
|
||||
completely forgot about the Java <a class="footnote-reference" href="#id7" id="id2" name="id2">[2]</a> inspiration. This is a KISS module for
|
||||
logging that provides enough flexibility to do just about anything via
|
||||
listeners, but without all the cruft.</p>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h1><a id="dependencies" name="dependencies">Dependencies</a></h1>
|
||||
<ul class="simple">
|
||||
<li><a class="mochiref reference" href="Base.html">MochiKit.Base</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h1><a id="overview" name="overview">Overview</a></h1>
|
||||
<div class="section">
|
||||
<h2><a id="native-console-logging" name="native-console-logging">Native Console Logging</a></h2>
|
||||
<p>As of MochiKit 1.3, the default logger will log all messages to your browser's
|
||||
native console. This is currently supported in Safari, Opera 9, and Firefox
|
||||
when the <a class="reference" href="http://www.joehewitt.com/software/firebug/">FireBug</a> extension is installed.</p>
|
||||
<p>To disable this behavior:</p>
|
||||
<pre class="literal-block">
|
||||
MochiKit.Logging.logger.useNativeLogging = false;
|
||||
</pre>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h2><a id="bookmarklet-based-debugging" name="bookmarklet-based-debugging">Bookmarklet Based Debugging</a></h2>
|
||||
<p>JavaScript is at a serious disadvantage without a standard console for
|
||||
"print" statements. Everything else has one. The closest thing that
|
||||
you get in a browser environment is the <tt class="docutils literal"><span class="pre">alert</span></tt> function, which is
|
||||
absolutely evil.</p>
|
||||
<p>This leaves you with one reasonable solution: do your logging in the page
|
||||
somehow. The problem here is that you don't want to clutter the page with
|
||||
debugging tools. The solution to that problem is what we call BBD, or
|
||||
Bookmarklet Based Debugging <a class="footnote-reference" href="#id8" id="id4" name="id4">[3]</a>.</p>
|
||||
<p>Simply create a bookmarklet for <a class="reference" href="javascript:MochiKit.Logging.logger.debuggingBookmarklet()">javascript:MochiKit.Logging.logger.debuggingBookmarklet()</a>,
|
||||
and whack it whenever you want to see what's in the logger. Of course, this
|
||||
means you must drink the MochiKit.Logging kool-aid. It's tangy and sweet,
|
||||
don't worry.</p>
|
||||
<p>Currently this is an ugly <tt class="docutils literal"><span class="pre">alert</span></tt>, but we'll have something spiffy
|
||||
Real Soon Now, and when we do, you only have to upgrade MochiKit.Logging,
|
||||
not your bookmarklet!</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h1><a id="api-reference" name="api-reference">API Reference</a></h1>
|
||||
<div class="section">
|
||||
<h2><a id="constructors" name="constructors">Constructors</a></h2>
|
||||
<p>
|
||||
<a name="fn-logmessage"></a>
|
||||
<a class="mochidef reference" href="#fn-logmessage">LogMessage(num, level, info)</a>:</p>
|
||||
<blockquote>
|
||||
<p>Properties:</p>
|
||||
<blockquote>
|
||||
<dl class="docutils">
|
||||
<dt><tt class="docutils literal"><span class="pre">num</span></tt>:</dt>
|
||||
<dd>Identifier for the log message</dd>
|
||||
<dt><tt class="docutils literal"><span class="pre">level</span></tt>:</dt>
|
||||
<dd>Level of the log message (<tt class="docutils literal"><span class="pre">"INFO"</span></tt>, <tt class="docutils literal"><span class="pre">"WARN"</span></tt>, <tt class="docutils literal"><span class="pre">"DEBUG"</span></tt>,
|
||||
etc.)</dd>
|
||||
<dt><tt class="docutils literal"><span class="pre">info</span></tt>:</dt>
|
||||
<dd>All other arguments passed to log function as an <tt class="docutils literal"><span class="pre">Array</span></tt></dd>
|
||||
<dt><tt class="docutils literal"><span class="pre">timestamp</span></tt>:</dt>
|
||||
<dd><tt class="docutils literal"><span class="pre">Date</span></tt> object timestamping the log message</dd>
|
||||
</dl>
|
||||
</blockquote>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-logger"></a>
|
||||
<a class="mochidef reference" href="#fn-logger">Logger([maxSize])</a>:</p>
|
||||
<blockquote>
|
||||
<p>A basic logger object that has a buffer of recent messages
|
||||
plus a listener dispatch mechanism for "real-time" logging
|
||||
of important messages.</p>
|
||||
<p><tt class="docutils literal"><span class="pre">maxSize</span></tt> is the maximum number of entries in the log.
|
||||
If <tt class="docutils literal"><span class="pre">maxSize</span> <span class="pre">>=</span> <span class="pre">0</span></tt>, then the log will not buffer more than that
|
||||
many messages. So if you don't like logging at all, be sure to
|
||||
pass <tt class="docutils literal"><span class="pre">0</span></tt>.</p>
|
||||
<p>There is a default logger available named "logger", and several
|
||||
of its methods are also global functions:</p>
|
||||
<blockquote>
|
||||
<tt class="docutils literal"><span class="pre">logger.log</span></tt> -> <tt class="docutils literal"><span class="pre">log</span></tt>
|
||||
<tt class="docutils literal"><span class="pre">logger.debug</span></tt> -> <tt class="docutils literal"><span class="pre">logDebug</span></tt>
|
||||
<tt class="docutils literal"><span class="pre">logger.warning</span></tt> -> <tt class="docutils literal"><span class="pre">logWarning</span></tt>
|
||||
<tt class="docutils literal"><span class="pre">logger.error</span></tt> -> <tt class="docutils literal"><span class="pre">logError</span></tt>
|
||||
<tt class="docutils literal"><span class="pre">logger.fatal</span></tt> -> <tt class="docutils literal"><span class="pre">logFatal</span></tt></blockquote>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-logger.prototype.addlistener"></a>
|
||||
<a class="mochidef reference" href="#fn-logger.prototype.addlistener">Logger.prototype.addListener(ident, filter, listener)</a>:</p>
|
||||
<blockquote>
|
||||
<p>Add a listener for log messages.</p>
|
||||
<p><tt class="docutils literal"><span class="pre">ident</span></tt> is a unique identifier that may be used to remove the listener
|
||||
later on.</p>
|
||||
<p><tt class="docutils literal"><span class="pre">filter</span></tt> can be one of the following:</p>
|
||||
<blockquote>
|
||||
<dl class="docutils">
|
||||
<dt><tt class="docutils literal"><span class="pre">null</span></tt>:</dt>
|
||||
<dd><tt class="docutils literal"><span class="pre">listener(msg)</span></tt> will be called for every log message
|
||||
received.</dd>
|
||||
<dt><tt class="docutils literal"><span class="pre">string</span></tt>:</dt>
|
||||
<dd><a class="mochiref reference" href="#fn-loglevelatleast">logLevelAtLeast(filter)</a> will be used as the function
|
||||
(see below).</dd>
|
||||
<dt><tt class="docutils literal"><span class="pre">function</span></tt>:</dt>
|
||||
<dd><tt class="docutils literal"><span class="pre">filter(msg)</span></tt> will be called for every msg, if it returns
|
||||
true then <tt class="docutils literal"><span class="pre">listener(msg)</span></tt> will be called.</dd>
|
||||
</dl>
|
||||
</blockquote>
|
||||
<p><tt class="docutils literal"><span class="pre">listener</span></tt> is a function that takes one argument, a log message. A log
|
||||
message is an object (<a class="mochiref reference" href="#fn-logmessage">LogMessage</a> instance) that has at least these
|
||||
properties:</p>
|
||||
<blockquote>
|
||||
<dl class="docutils">
|
||||
<dt><tt class="docutils literal"><span class="pre">num</span></tt>:</dt>
|
||||
<dd>A counter that uniquely identifies a log message (per-logger)</dd>
|
||||
<dt><tt class="docutils literal"><span class="pre">level</span></tt>:</dt>
|
||||
<dd>A string or number representing the log level. If string, you
|
||||
may want to use <tt class="docutils literal"><span class="pre">LogLevel[level]</span></tt> for comparison.</dd>
|
||||
<dt><tt class="docutils literal"><span class="pre">info</span></tt>:</dt>
|
||||
<dd>An Array of objects passed as additional arguments to the <tt class="docutils literal"><span class="pre">log</span></tt>
|
||||
function.</dd>
|
||||
</dl>
|
||||
</blockquote>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-logger.prototype.baselog"></a>
|
||||
<a class="mochidef reference" href="#fn-logger.prototype.baselog">Logger.prototype.baseLog(level, message[, ...])</a>:</p>
|
||||
<blockquote>
|
||||
<p>The base functionality behind all of the log functions.
|
||||
The first argument is the log level as a string or number,
|
||||
and all other arguments are used as the info list.</p>
|
||||
<p>This function is available partially applied as:</p>
|
||||
<blockquote>
|
||||
<table border="1" class="docutils">
|
||||
<colgroup>
|
||||
<col width="61%" />
|
||||
<col width="39%" />
|
||||
</colgroup>
|
||||
<tbody valign="top">
|
||||
<tr><td>Logger.debug</td>
|
||||
<td>'DEBUG'</td>
|
||||
</tr>
|
||||
<tr><td>Logger.log</td>
|
||||
<td>'INFO'</td>
|
||||
</tr>
|
||||
<tr><td>Logger.error</td>
|
||||
<td>'ERROR'</td>
|
||||
</tr>
|
||||
<tr><td>Logger.fatal</td>
|
||||
<td>'FATAL'</td>
|
||||
</tr>
|
||||
<tr><td>Logger.warning</td>
|
||||
<td>'WARNING'</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</blockquote>
|
||||
<p>For the default logger, these are also available as global functions,
|
||||
see the <a class="mochiref reference" href="#fn-logger">Logger</a> constructor documentation for more info.</p>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-logger.prototype.clear"></a>
|
||||
<a class="mochidef reference" href="#fn-logger.prototype.clear">Logger.prototype.clear()</a>:</p>
|
||||
<blockquote>
|
||||
Clear all messages from the message buffer.</blockquote>
|
||||
<p>
|
||||
<a name="fn-logger.prototype.debuggingbookmarklet"></a>
|
||||
<a class="mochidef reference" href="#fn-logger.prototype.debuggingbookmarklet">Logger.prototype.debuggingBookmarklet()</a>:</p>
|
||||
<blockquote>
|
||||
<p>Display the contents of the logger in a useful way for browsers.</p>
|
||||
<p>Currently, if <a class="mochiref reference" href="LoggingPane.html">MochiKit.LoggingPane</a> is loaded, then a pop-up
|
||||
<a class="mochiref reference" href="LoggingPane.html#fn-loggingpane">MochiKit.LoggingPane.LoggingPane</a> will be used. Otherwise,
|
||||
it will be an alert with <a class="mochiref reference" href="#fn-logger.prototype.getmessagetext">Logger.prototype.getMessageText()</a>.</p>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-logger.prototype.dispatchlisteners"></a>
|
||||
<a class="mochidef reference" href="#fn-logger.prototype.dispatchlisteners">Logger.prototype.dispatchListeners(msg)</a>:</p>
|
||||
<blockquote>
|
||||
Dispatch a log message to all listeners.</blockquote>
|
||||
<p>
|
||||
<a name="fn-logger.prototype.getmessages"></a>
|
||||
<a class="mochidef reference" href="#fn-logger.prototype.getmessages">Logger.prototype.getMessages(howMany)</a>:</p>
|
||||
<blockquote>
|
||||
Return a list of up to <tt class="docutils literal"><span class="pre">howMany</span></tt> messages from the message buffer.</blockquote>
|
||||
<p>
|
||||
<a name="fn-logger.prototype.getmessagetext"></a>
|
||||
<a class="mochidef reference" href="#fn-logger.prototype.getmessagetext">Logger.prototype.getMessageText(howMany)</a>:</p>
|
||||
<blockquote>
|
||||
<p>Get a string representing up to the last <tt class="docutils literal"><span class="pre">howMany</span></tt> messages in the
|
||||
message buffer. The default is <tt class="docutils literal"><span class="pre">30</span></tt>.</p>
|
||||
<p>The message looks like this:</p>
|
||||
<pre class="literal-block">
|
||||
LAST {messages.length} MESSAGES:
|
||||
[{msg.num}] {msg.level}: {m.info.join(' ')}
|
||||
[{msg.num}] {msg.level}: {m.info.join(' ')}
|
||||
...
|
||||
</pre>
|
||||
<p>If you want some other format, use
|
||||
<a class="mochiref reference" href="#fn-logger.prototype.getmessages">Logger.prototype.getMessages</a> and do it yourself.</p>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-logger.prototype.removelistener"></a>
|
||||
<a class="mochidef reference" href="#fn-logger.prototype.removelistener">Logger.prototype.removeListener(ident)</a>:</p>
|
||||
<blockquote>
|
||||
Remove a listener using the ident given to <a class="mochiref reference" href="#fn-logger.prototype.addlistener">Logger.prototype.addListener</a></blockquote>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h2><a id="functions" name="functions">Functions</a></h2>
|
||||
<p>
|
||||
<a name="fn-alertlistener"></a>
|
||||
<a class="mochidef reference" href="#fn-alertlistener">alertListener(msg)</a>:</p>
|
||||
<blockquote>
|
||||
Ultra-obnoxious <tt class="docutils literal"><span class="pre">alert(...)</span></tt> listener</blockquote>
|
||||
<p>
|
||||
<a name="fn-logdebug"></a>
|
||||
<a class="mochidef reference" href="#fn-logdebug">logDebug(message[, info[, ...]])</a>:</p>
|
||||
<blockquote>
|
||||
Log an INFO message to the default logger</blockquote>
|
||||
<p>
|
||||
<a name="fn-logdebug"></a>
|
||||
<a class="mochidef reference" href="#fn-logdebug">logDebug(message[, info[, ...]])</a>:</p>
|
||||
<blockquote>
|
||||
Log a DEBUG message to the default logger</blockquote>
|
||||
<p>
|
||||
<a name="fn-logerror"></a>
|
||||
<a class="mochidef reference" href="#fn-logerror">logError(message[, info[, ...]])</a>:</p>
|
||||
<blockquote>
|
||||
Log an ERROR message to the default logger</blockquote>
|
||||
<p>
|
||||
<a name="fn-logfatal"></a>
|
||||
<a class="mochidef reference" href="#fn-logfatal">logFatal(message[, info[, ...]])</a>:</p>
|
||||
<blockquote>
|
||||
Log a FATAL message to the default logger</blockquote>
|
||||
<p>
|
||||
<a name="fn-loglevelatleast"></a>
|
||||
<a class="mochidef reference" href="#fn-loglevelatleast">logLevelAtLeast(minLevel)</a>:</p>
|
||||
<blockquote>
|
||||
Return a function that will match log messages whose level
|
||||
is at least minLevel</blockquote>
|
||||
<p>
|
||||
<a name="fn-logwarning"></a>
|
||||
<a class="mochidef reference" href="#fn-logwarning">logWarning(message[, info[, ...]])</a>:</p>
|
||||
<blockquote>
|
||||
Log a WARNING message to the default logger</blockquote>
|
||||
</div>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h1><a id="see-also" name="see-also">See Also</a></h1>
|
||||
<table class="docutils footnote" frame="void" id="id6" rules="none">
|
||||
<colgroup><col class="label" /><col /></colgroup>
|
||||
<tbody valign="top">
|
||||
<tr><td class="label"><a class="fn-backref" href="#id1" name="id6">[1]</a></td><td>Python's logging module: <a class="reference" href="http://docs.python.org/lib/module-logging.html">http://docs.python.org/lib/module-logging.html</a></td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<table class="docutils footnote" frame="void" id="id7" rules="none">
|
||||
<colgroup><col class="label" /><col /></colgroup>
|
||||
<tbody valign="top">
|
||||
<tr><td class="label"><a class="fn-backref" href="#id2" name="id7">[2]</a></td><td>PEP 282, where they admit all of the Java influence: <a class="reference" href="http://www.python.org/peps/pep-0282.html">http://www.python.org/peps/pep-0282.html</a></td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<table class="docutils footnote" frame="void" id="id8" rules="none">
|
||||
<colgroup><col class="label" /><col /></colgroup>
|
||||
<tbody valign="top">
|
||||
<tr><td class="label"><a class="fn-backref" href="#id4" name="id8">[3]</a></td><td>Original Bookmarklet Based Debugging blather: <a class="reference" href="http://bob.pythonmac.org/archives/2005/07/03/bookmarklet-based-debugging/">http://bob.pythonmac.org/archives/2005/07/03/bookmarklet-based-debugging/</a></td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h1><a id="authors" name="authors">Authors</a></h1>
|
||||
<ul class="simple">
|
||||
<li>Bob Ippolito <<a class="reference" href="mailto:bob@redivi.com">bob@redivi.com</a>></li>
|
||||
</ul>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h1><a id="copyright" name="copyright">Copyright</a></h1>
|
||||
<p>Copyright 2005 Bob Ippolito <<a class="reference" href="mailto:bob@redivi.com">bob@redivi.com</a>>. This program is dual-licensed
|
||||
free software; you can redistribute it and/or modify it under the terms of the
|
||||
<a class="reference" href="http://www.opensource.org/licenses/mit-license.php">MIT License</a> or the <a class="reference" href="http://www.opensource.org/licenses/afl-2.1.php">Academic Free License v2.1</a>.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,121 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8" ?>
|
||||
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
|
||||
|
||||
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
|
||||
<meta name="generator" content="Docutils 0.4: http://docutils.sourceforge.net/" />
|
||||
<title>MochiKit.LoggingPane - Interactive MochiKit.Logging pane</title>
|
||||
|
||||
<link rel="stylesheet" href="../../../include/css/documentation.css" type="text/css" />
|
||||
<script type="text/javascript" src="../../../packed/lib/MochiKit/MochiKit.js"></script>
|
||||
<script type="text/javascript" src="../../js/toc.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div class="document">
|
||||
<div class="section">
|
||||
<h1><a id="name" name="name">Name</a></h1>
|
||||
<p>MochiKit.LoggingPane - Interactive MochiKit.Logging pane</p>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h1><a id="synopsis" name="synopsis">Synopsis</a></h1>
|
||||
<pre class="literal-block">
|
||||
// open a pop-up window
|
||||
createLoggingPane()
|
||||
// use a div at the bottom of the document
|
||||
createLoggingPane(true);
|
||||
</pre>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h1><a id="description" name="description">Description</a></h1>
|
||||
<p>MochiKit.Logging does not have any browser dependencies and is completely
|
||||
unobtrusive. MochiKit.LoggingPane is a browser-based colored viewing pane
|
||||
for your <a class="mochiref reference" href="Logging.html">MochiKit.Logging</a> output that can be used as a pop-up or
|
||||
inline.</p>
|
||||
<p>It also allows for regex and level filtering! MochiKit.LoggingPane is used
|
||||
as the default <a class="mochiref reference" href="Logging.html#fn-debuggingbookmarklet">MochiKit.Logging.debuggingBookmarklet()</a> if it is
|
||||
loaded.</p>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h1><a id="dependencies" name="dependencies">Dependencies</a></h1>
|
||||
<ul class="simple">
|
||||
<li><a class="mochiref reference" href="Base.html">MochiKit.Base</a></li>
|
||||
<li><a class="mochiref reference" href="Logging.html">MochiKit.Logging</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h1><a id="api-reference" name="api-reference">API Reference</a></h1>
|
||||
<div class="section">
|
||||
<h2><a id="constructors" name="constructors">Constructors</a></h2>
|
||||
<p>
|
||||
<a name="fn-loggingpane"></a>
|
||||
<a class="mochidef reference" href="#fn-loggingpane">LoggingPane(inline=false, logger=MochiKit.Logging.logger)</a>:</p>
|
||||
<blockquote>
|
||||
<p>A listener for a <a class="mochiref reference" href="Logging.html">MochiKit.Logging</a> logger with an interactive
|
||||
DOM representation.</p>
|
||||
<p>If <tt class="docutils literal"><span class="pre">inline</span></tt> is <tt class="docutils literal"><span class="pre">true</span></tt>, then the <tt class="docutils literal"><span class="pre">LoggingPane</span></tt> will be a <tt class="docutils literal"><span class="pre">DIV</span></tt>
|
||||
at the bottom of the document. Otherwise, it will be in a pop-up
|
||||
window with a name based on the calling page's URL. If there is an
|
||||
element in the document with an id of <tt class="docutils literal"><span class="pre">_MochiKit_LoggingPane</span></tt>,
|
||||
it will be used instead of appending a new <tt class="docutils literal"><span class="pre">DIV</span></tt> to the body.</p>
|
||||
<p><tt class="docutils literal"><span class="pre">logger</span></tt> is the reference to the <a class="mochiref reference" href="Logging.html#fn-logger">MochiKit.Logging.Logger</a> to
|
||||
listen to. If not specified, the global default logger is used.</p>
|
||||
<p>Properties:</p>
|
||||
<blockquote>
|
||||
<dl class="docutils">
|
||||
<dt><tt class="docutils literal"><span class="pre">win</span></tt>:</dt>
|
||||
<dd>Reference to the pop-up window (<tt class="docutils literal"><span class="pre">undefined</span></tt> if <tt class="docutils literal"><span class="pre">inline</span></tt>)</dd>
|
||||
<dt><tt class="docutils literal"><span class="pre">inline</span></tt>:</dt>
|
||||
<dd><tt class="docutils literal"><span class="pre">true</span></tt> if the <tt class="docutils literal"><span class="pre">LoggingPane</span></tt> is inline</dd>
|
||||
<dt><tt class="docutils literal"><span class="pre">colorTable</span></tt>:</dt>
|
||||
<dd><p class="first">An object with property->value mappings for each log level
|
||||
and its color. May also be mutated on <tt class="docutils literal"><span class="pre">LoggingPane.prototype</span></tt>
|
||||
to affect all instances. For example:</p>
|
||||
<pre class="last literal-block">
|
||||
MochiKit.LoggingPane.LoggingPane.prototype.colorTable = {
|
||||
DEBUG: "green",
|
||||
INFO: "black",
|
||||
WARNING: "blue",
|
||||
ERROR: "red",
|
||||
FATAL: "darkred"
|
||||
};
|
||||
</pre>
|
||||
</dd>
|
||||
</dl>
|
||||
</blockquote>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-loggingpane.prototype.closepane"></a>
|
||||
<a class="mochidef reference" href="#fn-loggingpane.prototype.closepane">LoggingPane.prototype.closePane()</a>:</p>
|
||||
<blockquote>
|
||||
Close the <a class="mochiref reference" href="#fn-loggingpane">LoggingPane</a> (close the child window, or
|
||||
remove the <tt class="docutils literal"><span class="pre">_MochiKit_LoggingPane</span></tt> <tt class="docutils literal"><span class="pre">DIV</span></tt> from the document).</blockquote>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h2><a id="functions" name="functions">Functions</a></h2>
|
||||
<p>
|
||||
<a name="fn-createloggingpane"></a>
|
||||
<a class="mochidef reference" href="#fn-createloggingpane">createLoggingPane(inline=false)</a>:</p>
|
||||
<blockquote>
|
||||
Create or return an existing <a class="mochiref reference" href="#fn-loggingpane">LoggingPane</a> for this document
|
||||
with the given inline setting. This is preferred over using
|
||||
<a class="mochiref reference" href="#fn-loggingpane">LoggingPane</a> directly, as only one <a class="mochiref reference" href="#fn-loggingpane">LoggingPane</a>
|
||||
should be present in a given document.</blockquote>
|
||||
</div>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h1><a id="authors" name="authors">Authors</a></h1>
|
||||
<ul class="simple">
|
||||
<li>Bob Ippolito <<a class="reference" href="mailto:bob@redivi.com">bob@redivi.com</a>></li>
|
||||
</ul>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h1><a id="copyright" name="copyright">Copyright</a></h1>
|
||||
<p>Copyright 2005 Bob Ippolito <<a class="reference" href="mailto:bob@redivi.com">bob@redivi.com</a>>. This program is dual-licensed
|
||||
free software; you can redistribute it and/or modify it under the terms of the
|
||||
<a class="reference" href="http://www.opensource.org/licenses/mit-license.php">MIT License</a> or the <a class="reference" href="http://www.opensource.org/licenses/afl-2.1.php">Academic Free License v2.1</a>.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,331 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8" ?>
|
||||
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
|
||||
|
||||
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
|
||||
<meta name="generator" content="Docutils 0.4: http://docutils.sourceforge.net/" />
|
||||
<title>MochiKit.Signal - Simple universal event handling</title>
|
||||
|
||||
<link rel="stylesheet" href="../../../include/css/documentation.css" type="text/css" />
|
||||
<script type="text/javascript" src="../../../packed/lib/MochiKit/MochiKit.js"></script>
|
||||
<script type="text/javascript" src="../../js/toc.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div class="document">
|
||||
<div class="section">
|
||||
<h1><a id="name" name="name">Name</a></h1>
|
||||
<p>MochiKit.Signal - Simple universal event handling</p>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h1><a id="synopsis" name="synopsis">Synopsis</a></h1>
|
||||
<p>Signal for DOM events:</p>
|
||||
<pre class="literal-block">
|
||||
// DOM events are also signals. Connect freely! The functions will be
|
||||
// called with the custom event as a parameter.
|
||||
|
||||
// calls myClicked.apply(getElement('myID'), event)
|
||||
connect('myID', 'onclick', myClicked);
|
||||
|
||||
// calls wasClicked.apply(myObject, event)
|
||||
connect('myID', 'onclick', myObject, wasClicked);
|
||||
|
||||
// calls myObject.wasClicked(event)
|
||||
connect('myID', 'onclick', myObject, 'wasClicked');
|
||||
|
||||
// the event is normalized, no more e = e || window.event!
|
||||
myObject.wasClicked = function(e) {
|
||||
var crossBrowserCoordinates = e.mouse().page;
|
||||
// e.mouse().page is a MochiKit.DOM.Coordinates object
|
||||
}
|
||||
</pre>
|
||||
<p>Signal for non-DOM events:</p>
|
||||
<pre class="literal-block">
|
||||
// otherObject.gotFlash() will be called when 'flash' signalled.
|
||||
connect(myObject, 'flash', otherObject, 'gotFlash');
|
||||
|
||||
// gotBang.apply(otherObject) will be called when 'bang' signalled.
|
||||
// You can access otherObject from within gotBang as 'this'.
|
||||
connect(myObject, 'bang', otherObject, gotBang);
|
||||
|
||||
// myFunc.apply(myObject) will be called when 'flash' signalled.
|
||||
// You can access myObject from within myFunc as 'this'.
|
||||
var ident = connect(myObject, 'flash', myFunc);
|
||||
|
||||
// You may disconnect with the return value from connect
|
||||
disconnect(ident);
|
||||
|
||||
// Signal can take parameters. These will be passed along to the connected
|
||||
// functions.
|
||||
signal(myObject, 'flash');
|
||||
signal(myObject, 'bang', 'BANG!');
|
||||
</pre>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h1><a id="description" name="description">Description</a></h1>
|
||||
<p>Event handling was never so easy!</p>
|
||||
<p>This module takes care of all the hard work—figuring out which event
|
||||
model to use, trying to retrieve the event object, and handling your own
|
||||
internal events, as well as cleanup when the page is unloaded to clean up IE's
|
||||
nasty memory leakage.</p>
|
||||
<p>This event system is largely based on Qt's signal/slot system. Read more on
|
||||
how that is handled and also how it is used in model/view programming at:
|
||||
<a class="reference" href="http://doc.trolltech.com/">http://doc.trolltech.com/</a></p>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h1><a id="dependencies" name="dependencies">Dependencies</a></h1>
|
||||
<ul class="simple">
|
||||
<li><a class="mochiref reference" href="Base.html">MochiKit.Base</a></li>
|
||||
<li><a class="mochiref reference" href="DOM.html">MochiKit.DOM</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h1><a id="overview" name="overview">Overview</a></h1>
|
||||
<div class="section">
|
||||
<h2><a id="using-signal-for-dom-events" name="using-signal-for-dom-events">Using Signal for DOM Events</a></h2>
|
||||
<p>When using MochiKit.Signal, do not use the browser's native event API. That
|
||||
means, no <tt class="docutils literal"><span class="pre">onclick="blah"</span></tt>, no <tt class="docutils literal"><span class="pre">elem.addEventListener(...)</span></tt>, and certainly
|
||||
no <tt class="docutils literal"><span class="pre">elem.attachEvent(...)</span></tt>. This also means that
|
||||
<a class="mochiref reference" href="DOM.html#fn-addtocallstack">MochiKit.DOM.addToCallStack</a> and
|
||||
<a class="mochiref reference" href="DOM.html#fn-addloadevent">MochiKit.DOM.addLoadEvent</a> should not be used in combination with
|
||||
this module.</p>
|
||||
<p>Signals for DOM objects are named with the <tt class="docutils literal"><span class="pre">'on'</span></tt> prefix, e.g.:
|
||||
<tt class="docutils literal"><span class="pre">'onclick'</span></tt>, <tt class="docutils literal"><span class="pre">'onkeyup'</span></tt>, etc.</p>
|
||||
<p>When the signal fires, your slot will be called with one parameter, the custom
|
||||
event object.</p>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h2><a id="custom-event-objects-for-dom-events" name="custom-event-objects-for-dom-events">Custom Event Objects for DOM events</a></h2>
|
||||
<p>Signals triggered by DOM events are called with a custom event object as a
|
||||
parameter. The custom event object presents a consistent view of the event
|
||||
across all supported platforms and browsers, and provides many conveniences
|
||||
not available even in a correct W3C implementation.</p>
|
||||
<p>See the <a class="reference" href="#dom-custom-event-object-reference">DOM Custom Event Object Reference</a> for a detailed API description
|
||||
of this object.</p>
|
||||
<p>If you find that you're accessing the native event for any reason, create a
|
||||
<a class="reference" href="http://trac.mochikit.com/newticket">new ticket</a> and we'll look into normalizing the behavior you're looking for.</p>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h2><a id="memory-usage" name="memory-usage">Memory Usage</a></h2>
|
||||
<p>Any object that has connected slots (via <a class="mochiref reference" href="#fn-connect">connect()</a>) is referenced
|
||||
by the Signal mechanism until it is disconnected via <a class="mochiref reference" href="#fn-disconnect">disconnect()</a>
|
||||
or <a class="mochiref reference" href="#fn-disconnectall">disconnectAll()</a>.</p>
|
||||
<p>Signal does not leak. It registers an <tt class="docutils literal"><span class="pre">'onunload'</span></tt> event that disconnects all
|
||||
objects on the page when the browser leaves the page. However, memory usage
|
||||
will grow during the page view for every connection made until it is
|
||||
disconnected. Even if the DOM object is removed from the document, it
|
||||
will still be referenced by Signal until it is explicitly disconnected.</p>
|
||||
<p>In order to conserve memory during the page view, <a class="mochiref reference" href="#fn-disconnectall">disconnectAll()</a>
|
||||
any DOM elements that are about to be removed from the document.</p>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h2><a id="using-signal-for-non-dom-objects" name="using-signal-for-non-dom-objects">Using Signal for non-DOM objects</a></h2>
|
||||
<p>Signals are triggered with the <a class="mochiref reference" href="#fn-signal">signal(src, 'signal', ...)</a>
|
||||
function. Additional parameters passed to this are passed onto the
|
||||
connected slots. Explicit signals are not required for DOM events.</p>
|
||||
<p>Slots that are connected to a signal are called in the following manner
|
||||
when that signal is signalled:</p>
|
||||
<ul class="simple">
|
||||
<li>If the slot was a single function, then it is called with <tt class="docutils literal"><span class="pre">this</span></tt> set
|
||||
to the object originating the signal with whatever parameters it was
|
||||
signalled with.</li>
|
||||
<li>If the slot was an object and a function, then it is called with
|
||||
<tt class="docutils literal"><span class="pre">this</span></tt> set to the object, and with whatever parameters it was
|
||||
signalled with.</li>
|
||||
<li>If the slot was an object and a string, then <tt class="docutils literal"><span class="pre">object[string]</span></tt> is
|
||||
called with the parameters to the signal.</li>
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h1><a id="api-reference" name="api-reference">API Reference</a></h1>
|
||||
<div class="section">
|
||||
<h2><a id="signal-api-reference" name="signal-api-reference">Signal API Reference</a></h2>
|
||||
<p>
|
||||
<a name="fn-connect"></a>
|
||||
<a class="mochidef reference" href="#fn-connect">connect(src, signal, dest[, func])</a>:</p>
|
||||
<blockquote>
|
||||
<p>Connects a signal to a slot, and return a unique identifier that can be
|
||||
used to disconnect that signal.</p>
|
||||
<p><tt class="docutils literal"><span class="pre">src</span></tt> is the object that has the signal. You may pass in a string, in
|
||||
which case, it is interpreted as an id for an HTML element.</p>
|
||||
<p><tt class="docutils literal"><span class="pre">signal</span></tt> is a string that represents a signal name. If 'src' is an HTML
|
||||
Element, <tt class="docutils literal"><span class="pre">window</span></tt>, or the <tt class="docutils literal"><span class="pre">document</span></tt>, then it can be one of the
|
||||
'on-XYZ' events. You must include the 'on' prefix, and it must be all
|
||||
lower-case.</p>
|
||||
<p><tt class="docutils literal"><span class="pre">dest</span></tt> and <tt class="docutils literal"><span class="pre">func</span></tt> describe the slot, or the action to take when the
|
||||
signal is triggered.</p>
|
||||
<blockquote>
|
||||
<ul class="simple">
|
||||
<li>If <tt class="docutils literal"><span class="pre">dest</span></tt> is an object and <tt class="docutils literal"><span class="pre">func</span></tt> is a string, then
|
||||
<tt class="docutils literal"><span class="pre">dest[func].apply(dest,</span> <span class="pre">...)</span></tt> will be called when the signal
|
||||
is signalled.</li>
|
||||
<li>If <tt class="docutils literal"><span class="pre">dest</span></tt> is an object and <tt class="docutils literal"><span class="pre">func</span></tt> is a function, then
|
||||
<tt class="docutils literal"><span class="pre">func.apply(dest,</span> <span class="pre">...)</span></tt> will be called when the signal is
|
||||
signalled.</li>
|
||||
<li>If <tt class="docutils literal"><span class="pre">func</span></tt> is undefined and <tt class="docutils literal"><span class="pre">dest</span></tt> is a function, then
|
||||
<tt class="docutils literal"><span class="pre">func.apply(src,</span> <span class="pre">...)</span></tt> will be called when the signal is
|
||||
signalled.</li>
|
||||
</ul>
|
||||
</blockquote>
|
||||
<p>No other combinations are allowed and will raise an exception.</p>
|
||||
<p>The return value can be passed to <a class="mochiref reference" href="#fn-disconnect">disconnect</a> to disconnect
|
||||
the signal.</p>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-disconnect"></a>
|
||||
<a class="mochidef reference" href="#fn-disconnect">disconnect(ident)</a>:</p>
|
||||
<blockquote>
|
||||
To disconnect a signal, pass its ident returned by <a class="mochiref reference" href="#fn-connect">connect()</a>.
|
||||
This is similar to how the browser's <tt class="docutils literal"><span class="pre">setTimeout</span></tt> and <tt class="docutils literal"><span class="pre">clearTimeout</span></tt>
|
||||
works.</blockquote>
|
||||
<p>
|
||||
<a name="fn-disconnectall"></a>
|
||||
<a class="mochidef reference" href="#fn-disconnectall">disconnectAll(src[, signal, ...])</a>:</p>
|
||||
<blockquote>
|
||||
<p><tt class="docutils literal"><span class="pre">disconnectAll(src)</span></tt> removes all signals from src.</p>
|
||||
<p><tt class="docutils literal"><span class="pre">disconnectAll(src,</span> <span class="pre">'onmousedown',</span> <span class="pre">'mySignal')</span></tt> will remove all
|
||||
<tt class="docutils literal"><span class="pre">'onmousedown'</span></tt> and <tt class="docutils literal"><span class="pre">'mySignal'</span></tt> signals from src.</p>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-signal"></a>
|
||||
<a class="mochidef reference" href="#fn-signal">signal(src, signal, ...)</a>:</p>
|
||||
<blockquote>
|
||||
This will signal a signal, passing whatever additional parameters on to
|
||||
the connected slots. <tt class="docutils literal"><span class="pre">src</span></tt> and <tt class="docutils literal"><span class="pre">signal</span></tt> are the same as for
|
||||
<a class="mochiref reference" href="#fn-connect">connect()</a>.</blockquote>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h2><a id="dom-custom-event-object-reference" name="dom-custom-event-object-reference">DOM Custom Event Object Reference</a></h2>
|
||||
<p>
|
||||
<a name="fn-event"></a>
|
||||
<a class="mochidef reference" href="#fn-event">event()</a>:</p>
|
||||
<blockquote>
|
||||
The native event produced by the browser. You should not need to use this.</blockquote>
|
||||
<p>
|
||||
<a name="fn-src"></a>
|
||||
<a class="mochidef reference" href="#fn-src">src()</a>:</p>
|
||||
<blockquote>
|
||||
The element that this signal is connected to.</blockquote>
|
||||
<p>
|
||||
<a name="fn-type"></a>
|
||||
<a class="mochidef reference" href="#fn-type">type()</a>:</p>
|
||||
<blockquote>
|
||||
The event type (<tt class="docutils literal"><span class="pre">'click'</span></tt>, <tt class="docutils literal"><span class="pre">'mouseover'</span></tt>, <tt class="docutils literal"><span class="pre">'keypress'</span></tt>, etc.) as a
|
||||
string. Does not include the <tt class="docutils literal"><span class="pre">'on'</span></tt> prefix.</blockquote>
|
||||
<p>
|
||||
<a name="fn-target"></a>
|
||||
<a class="mochidef reference" href="#fn-target">target()</a>:</p>
|
||||
<blockquote>
|
||||
The element that triggered the event. This may be a child of
|
||||
<a class="mochiref reference" href="#fn-src">src()</a>.</blockquote>
|
||||
<p>
|
||||
<a name="fn-modifier"></a>
|
||||
<a class="mochidef reference" href="#fn-modifier">modifier()</a>:</p>
|
||||
<blockquote>
|
||||
Returns <tt class="docutils literal"><span class="pre">{shift,</span> <span class="pre">ctrl,</span> <span class="pre">meta,</span> <span class="pre">alt,</span> <span class="pre">any}</span></tt>, where each property is <tt class="docutils literal"><span class="pre">true</span></tt>
|
||||
if its respective modifier key was pressed, <tt class="docutils literal"><span class="pre">false</span></tt> otherwise. <tt class="docutils literal"><span class="pre">any</span></tt>
|
||||
is <tt class="docutils literal"><span class="pre">true</span></tt> if any modifier is pressed, <tt class="docutils literal"><span class="pre">false</span></tt> otherwise.</blockquote>
|
||||
<p>
|
||||
<a name="fn-stoppropagation"></a>
|
||||
<a class="mochidef reference" href="#fn-stoppropagation">stopPropagation()</a>:</p>
|
||||
<blockquote>
|
||||
Works like W3C's <tt class="docutils literal"><span class="pre">stopPropagation()</span></tt>.</blockquote>
|
||||
<p>
|
||||
<a name="fn-preventdefault"></a>
|
||||
<a class="mochidef reference" href="#fn-preventdefault">preventDefault()</a>:</p>
|
||||
<blockquote>
|
||||
Works like W3C's <tt class="docutils literal"><span class="pre">preventDefault()</span></tt>.</blockquote>
|
||||
<p>
|
||||
<a name="fn-stop"></a>
|
||||
<a class="mochidef reference" href="#fn-stop">stop()</a>:</p>
|
||||
<blockquote>
|
||||
Shortcut that calls <tt class="docutils literal"><span class="pre">stopPropagation()</span></tt> and <tt class="docutils literal"><span class="pre">preventDefault()</span></tt>.</blockquote>
|
||||
<p>
|
||||
<a name="fn-key"></a>
|
||||
<a class="mochidef reference" href="#fn-key">key()</a>:</p>
|
||||
<blockquote>
|
||||
<p>Returns <tt class="docutils literal"><span class="pre">{code,</span> <span class="pre">string}</span></tt>.</p>
|
||||
<p>Use <tt class="docutils literal"><span class="pre">'onkeydown'</span></tt> and <tt class="docutils literal"><span class="pre">'onkeyup'</span></tt> handlers to detect control
|
||||
characters such as <tt class="docutils literal"><span class="pre">'KEY_F1'</span></tt>. Use the <tt class="docutils literal"><span class="pre">'onkeypressed'</span></tt> handler to
|
||||
detect "printable" characters, such as <tt class="docutils literal"><span class="pre">'é'</span></tt>.</p>
|
||||
<p>When a user presses F1, in <tt class="docutils literal"><span class="pre">'onkeydown'</span></tt> and <tt class="docutils literal"><span class="pre">'onkeyup'</span></tt> this method
|
||||
returns <tt class="docutils literal"><span class="pre">{code:</span> <span class="pre">122,</span> <span class="pre">string:</span> <span class="pre">'KEY_F1'}</span></tt>. In <tt class="docutils literal"><span class="pre">'onkeypress'</span></tt>, it returns
|
||||
<tt class="docutils literal"><span class="pre">{code:</span> <span class="pre">0,</span> <span class="pre">string:</span> <span class="pre">''}</span></tt>.</p>
|
||||
<p>If a user presses Shift+2 on a US keyboard, this method returns
|
||||
<tt class="docutils literal"><span class="pre">{code:</span> <span class="pre">50,</span> <span class="pre">string:</span> <span class="pre">'KEY_2'}</span></tt> in <tt class="docutils literal"><span class="pre">'onkeydown'</span></tt> and <tt class="docutils literal"><span class="pre">'onkeyup'</span></tt>.
|
||||
In <tt class="docutils literal"><span class="pre">'onkeypress'</span></tt>, it returns <tt class="docutils literal"><span class="pre">{code:</span> <span class="pre">64,</span> <span class="pre">string:</span> <span class="pre">'@'}</span></tt>.</p>
|
||||
<p>See <tt class="docutils literal"><span class="pre">_specialKeys</span></tt> in the source code for a comprehensive list of
|
||||
control characters.</p>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-mouse"></a>
|
||||
<a class="mochidef reference" href="#fn-mouse">mouse()</a>:</p>
|
||||
<blockquote>
|
||||
<p>Properties for <tt class="docutils literal"><span class="pre">'onmouse*'</span></tt>, <tt class="docutils literal"><span class="pre">'onclick'</span></tt>, <tt class="docutils literal"><span class="pre">'ondblclick'</span></tt>, and
|
||||
<tt class="docutils literal"><span class="pre">'oncontextmenu'</span></tt>:</p>
|
||||
<blockquote>
|
||||
<ul class="simple">
|
||||
<li><tt class="docutils literal"><span class="pre">page</span></tt> is a <a class="mochiref reference" href="DOM.html#fn-coordinates">MochiKit.DOM.Coordinates</a> object that
|
||||
represents the cursor position relative to the HTML document.
|
||||
Equivalent to <tt class="docutils literal"><span class="pre">pageX</span></tt> and <tt class="docutils literal"><span class="pre">pageY</span></tt> in Safari, Mozilla, and
|
||||
Opera.</li>
|
||||
<li><tt class="docutils literal"><span class="pre">client</span></tt> is a <a class="mochiref reference" href="DOM.html#fn-coordinates">MochiKit.DOM.Coordinates</a> object that
|
||||
represents the cursor position relative to the visible portion of
|
||||
the HTML document. Equivalent to <tt class="docutils literal"><span class="pre">clientX</span></tt> and <tt class="docutils literal"><span class="pre">clientY</span></tt> on
|
||||
all browsers.</li>
|
||||
</ul>
|
||||
</blockquote>
|
||||
<p>Properties for <tt class="docutils literal"><span class="pre">'onmouseup'</span></tt>, <tt class="docutils literal"><span class="pre">'onmousedown'</span></tt>, <tt class="docutils literal"><span class="pre">'onclick'</span></tt>, and
|
||||
<tt class="docutils literal"><span class="pre">'ondblclick'</span></tt>:</p>
|
||||
<blockquote>
|
||||
<ul class="simple">
|
||||
<li><tt class="docutils literal"><span class="pre">mouse().button</span></tt> returns <tt class="docutils literal"><span class="pre">{left,</span> <span class="pre">right,</span> <span class="pre">middle}</span></tt> where each
|
||||
property is <tt class="docutils literal"><span class="pre">true</span></tt> if the mouse button was pressed, <tt class="docutils literal"><span class="pre">false</span></tt>
|
||||
otherwise.</li>
|
||||
</ul>
|
||||
</blockquote>
|
||||
<p>Known browser bugs:</p>
|
||||
<blockquote>
|
||||
<ul>
|
||||
<li><p class="first">Current versions of Safari won't signal <tt class="docutils literal"><span class="pre">'ondblclick'</span></tt> when
|
||||
attached via <tt class="docutils literal"><span class="pre">connect()</span></tt> (<a class="reference" href="http://bugzilla.opendarwin.org/show_bug.cgi?id=7790">Safari Bug 7790</a>).</p>
|
||||
</li>
|
||||
<li><p class="first">Mac browsers don't report right-click consistently. Firefox
|
||||
signals the slot and sets <tt class="docutils literal"><span class="pre">modifier().ctrl</span></tt> to true, Opera
|
||||
signals the slot and sets <tt class="docutils literal"><span class="pre">modifier().meta</span></tt> to <tt class="docutils literal"><span class="pre">true</span></tt>, and
|
||||
Safari doesn't signal the slot at all (<a class="reference" href="http://bugzilla.opendarwin.org/show_bug.cgi?id=6595">Safari Bug 6595</a>).</p>
|
||||
<p>To find a right-click in Safari, Firefox, and IE, you can connect
|
||||
an element to <tt class="docutils literal"><span class="pre">'oncontextmenu'</span></tt>. This doesn't work in Opera.</p>
|
||||
</li>
|
||||
</ul>
|
||||
</blockquote>
|
||||
</blockquote>
|
||||
<p>
|
||||
<a name="fn-relatedtarget"></a>
|
||||
<a class="mochidef reference" href="#fn-relatedtarget">relatedTarget()</a>:</p>
|
||||
<blockquote>
|
||||
Returns the document element that the mouse has moved to. This is
|
||||
generated for <tt class="docutils literal"><span class="pre">'onmouseover'</span></tt> and <tt class="docutils literal"><span class="pre">'onmouseout'</span></tt> events.</blockquote>
|
||||
</div>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h1><a id="authors" name="authors">Authors</a></h1>
|
||||
<ul class="simple">
|
||||
<li>Jonathan Gardner <<a class="reference" href="mailto:jgardner@jonathangardner.net">jgardner@jonathangardner.net</a>></li>
|
||||
<li>Beau Hartshorne <<a class="reference" href="mailto:beau@hartshornesoftware.com">beau@hartshornesoftware.com</a>></li>
|
||||
<li>Bob Ippolito <<a class="reference" href="mailto:bob@redivi.com">bob@redivi.com</a>></li>
|
||||
</ul>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h1><a id="copyright" name="copyright">Copyright</a></h1>
|
||||
<p>Copyright 2006 Jonathan Gardner <<a class="reference" href="mailto:jgardner@jonathangardner.net">jgardner@jonathangardner.net</a>>, Beau
|
||||
Hartshorne <<a class="reference" href="mailto:beau@hartshornesoftware.com">beau@hartshornesoftware.com</a>>, and Bob Ippolito <<a class="reference" href="mailto:bob@redivi.com">bob@redivi.com</a>>.
|
||||
This program is dual-licensed free software; you can redistribute it and/or
|
||||
modify it under the terms of the <a class="reference" href="http://www.opensource.org/licenses/mit-license.php">MIT License</a> or the
|
||||
<a class="reference" href="http://www.opensource.org/licenses/afl-2.1.php">Academic Free License v2.1</a>.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,264 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8" ?>
|
||||
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
|
||||
|
||||
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
|
||||
<meta name="generator" content="Docutils 0.4: http://docutils.sourceforge.net/" />
|
||||
<title></title>
|
||||
|
||||
<link rel="stylesheet" href="../../../include/css/documentation.css" type="text/css" />
|
||||
<script type="text/javascript" src="../../../packed/lib/MochiKit/MochiKit.js"></script>
|
||||
<script type="text/javascript" src="../../js/toc.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div class="document">
|
||||
<p>2006-04-29 v1.3.1 (bug fix release)</p>
|
||||
<ul class="simple">
|
||||
<li>Fix sendXMLHttpRequest sendContent regression</li>
|
||||
<li>Internet Explorer fix in MochiKit.Logging (printfire exception)</li>
|
||||
<li>Internet Explorer XMLHttpRequest object leak fixed in MochiKit.Async</li>
|
||||
</ul>
|
||||
<p>2006-04-26 v1.3 "warp zone"</p>
|
||||
<ul class="simple">
|
||||
<li>IMPORTANT: Renamed MochiKit.Base.forward to forwardCall (for export)</li>
|
||||
<li>IMPORTANT: Renamed MochiKit.Base.find to findValue (for export)</li>
|
||||
<li>New MochiKit.Base.method as a convenience form of bind that takes the
|
||||
object before the method</li>
|
||||
<li>New MochiKit.Base.flattenArguments for flattening a list of arguments to
|
||||
a single Array</li>
|
||||
<li>Refactored MochiRegExp example to use MochiKit.Signal</li>
|
||||
<li>New key_events example demonstrating use of MochiKit.Signal's key handling
|
||||
capabilities.</li>
|
||||
<li>MochiKit.DOM.createDOM API change for convenience: if attrs is a string,
|
||||
null is used and the string will be considered the first node. This
|
||||
allows for the more natural P("foo") rather than P(null, "foo").</li>
|
||||
<li>MochiKit Interpreter example refactored to use MochiKit.Signal and now
|
||||
provides multi-line input and a help() function to get MochiKit function
|
||||
signature from the documentation.</li>
|
||||
<li>Native Console Logging for the default MochiKit.Logging logger</li>
|
||||
<li>New MochiKit.Async.DeferredList, gatherResults, maybeDeferred</li>
|
||||
<li>New MochiKit.Signal example: draggable</li>
|
||||
<li>Added sanity checking to Deferred to ensure that errors happen when chaining
|
||||
is used incorrectly</li>
|
||||
<li>Opera sendXMLHttpRequest fix (sends empty string instead of null by default)</li>
|
||||
<li>Fix a bug in MochiKit.Color that incorrectly generated hex colors for
|
||||
component values smaller than 16/255.</li>
|
||||
<li>Fix a bug in MochiKit.Logging that prevented logs from being capped at a
|
||||
maximum size</li>
|
||||
<li>MochiKit.Async.Deferred will now wrap thrown objects that are not instanceof
|
||||
Error, so that the errback chain is used instead of the callback chain.</li>
|
||||
<li>MochiKit.DOM.appendChildNodes and associated functions now append iterables
|
||||
in the correct order.</li>
|
||||
<li>New MochiKit-based SimpleTest test runner as a replacement for Test.Simple</li>
|
||||
<li>MochiKit.Base.isNull no longer matches undefined</li>
|
||||
<li>example doctypes changed to HTML4</li>
|
||||
<li>isDateLike no longer throws error on null</li>
|
||||
<li>New MochiKit.Signal module, modeled after the slot/signal mechanism in Qt</li>
|
||||
<li>updated elementDimensions to calculate width from offsetWidth instead
|
||||
of clientWidth</li>
|
||||
<li>formContents now works with FORM tags that have a name attribute</li>
|
||||
<li>Documentation now uses MochiKit to generate a function index</li>
|
||||
</ul>
|
||||
<p>2006-01-26 v1.2 "the ocho"</p>
|
||||
<ul class="simple">
|
||||
<li>Fixed MochiKit.Color.Color.lighterColorWithLevel</li>
|
||||
<li>Added new MochiKit.Base.findIdentical function to find the index of an
|
||||
element in an Array-like object. Uses === for identity comparison.</li>
|
||||
<li>Added new MochiKit.Base.find function to find the index of an element in
|
||||
an Array-like object. Uses compare for rich comparison.</li>
|
||||
<li>MochiKit.Base.bind will accept a string for func, which will be immediately
|
||||
looked up as self[func].</li>
|
||||
<li>MochiKit.DOM.formContents no longer skips empty form elements for Zope
|
||||
compatibility</li>
|
||||
<li>MochiKit.Iter.forEach will now catch StopIteration to break</li>
|
||||
<li>New MochiKit.DOM.elementDimensions(element) for determining the width and
|
||||
height of an element in the document</li>
|
||||
<li>MochiKit.DOM's initialization is now compatible with
|
||||
HTMLUnit + JWebUnit + Rhino</li>
|
||||
<li>MochiKit.LoggingPane will now re-use a <tt class="docutils literal"><span class="pre">_MochiKit_LoggingPane</span></tt> DIV element
|
||||
currently in the document instead of always creating one.</li>
|
||||
<li>MochiKit.Base now has operator.mul</li>
|
||||
<li>MochiKit.DOM.formContents correctly handles unchecked checkboxes that have
|
||||
a custom value attribute</li>
|
||||
<li>Added new MochiKit.Color constructors fromComputedStyle and fromText</li>
|
||||
<li>MochiKit.DOM.setNodeAttribute should work now</li>
|
||||
<li>MochiKit.DOM now has a workaround for an IE bug when setting the style
|
||||
property to a string</li>
|
||||
<li>MochiKit.DOM.createDOM now has workarounds for IE bugs when setting the
|
||||
name and for properties</li>
|
||||
<li>MochiKit.DOM.scrapeText now walks the DOM tree in-order</li>
|
||||
<li>MochiKit.LoggingPane now sanitizes the window name to work around IE bug</li>
|
||||
<li>MochiKit.DOM now translates usemap to useMap to work around IE bug</li>
|
||||
<li>MochiKit.Logging is now resistant to Prototype's dumb Object.prototype hacks</li>
|
||||
<li>Added new MochiKit.DOM documentation on element visibility</li>
|
||||
<li>New MochiKit.DOM.elementPosition(element[, relativeTo={x: 0, y: 0}])
|
||||
for determining the position of an element in the document</li>
|
||||
<li>Added new MochiKit.DOM createDOMFunc aliases: CANVAS, STRONG</li>
|
||||
</ul>
|
||||
<p>2005-11-14 v1.1</p>
|
||||
<ul class="simple">
|
||||
<li>Fixed a bug in numberFormatter with large numbers</li>
|
||||
<li>Massively overhauled documentation</li>
|
||||
<li>Fast-path for primitives in MochiKit.Base.compare</li>
|
||||
<li>New groupby and groupby_as_array in MochiKit.Iter</li>
|
||||
<li>Added iterator factory adapter for objects that implement iterateNext()</li>
|
||||
<li>Fixed isoTimestamp to handle timestamps with time zone correctly</li>
|
||||
<li>Added new MochiKit.DOM createDOMFunc aliases: SELECT, OPTION, OPTGROUP,
|
||||
LEGEND, FIELDSET</li>
|
||||
<li>New MochiKit.DOM formContents and enhancement to queryString to support it</li>
|
||||
<li>Updated view_source example to use dp.SyntaxHighlighter 1.3.0</li>
|
||||
<li>MochiKit.LoggingPane now uses named windows based on the URL so that
|
||||
a given URL will get the same LoggingPane window after a reload
|
||||
(at the same position, etc.)</li>
|
||||
<li>MochiKit.DOM now has currentWindow() and currentDocument() context
|
||||
variables that are set with withWindow() and withDocument(). These
|
||||
context variables affect all MochiKit.DOM functionality (getElement,
|
||||
createDOM, etc.)</li>
|
||||
<li>MochiKit.Base.items will now catch and ignore exceptions for properties
|
||||
that are enumerable but not accessible (e.g. permission denied)</li>
|
||||
<li>MochiKit.Async.Deferred's addCallback/addErrback/addBoth
|
||||
now accept additional arguments that are used to create a partially
|
||||
applied function. This differs from Twisted in that the callback/errback
|
||||
result becomes the <em>last</em> argument, not the first when this feature
|
||||
is used.</li>
|
||||
<li>MochiKit.Async's doSimpleXMLHttpRequest will now accept additional
|
||||
arguments which are used to create a GET query string</li>
|
||||
<li>Did some refactoring to reduce the footprint of MochiKit by a few
|
||||
kilobytes</li>
|
||||
<li>escapeHTML to longer escapes ' (apos) and now uses
|
||||
String.replace instead of iterating over every char.</li>
|
||||
<li>Added DeferredLock to Async</li>
|
||||
<li>Renamed getElementsComputedStyle to computedStyle and moved
|
||||
it from MochiKit.Visual to MochiKit.DOM</li>
|
||||
<li>Moved all color support out of MochiKit.Visual and into MochiKit.Color</li>
|
||||
<li>Fixed range() to accept a negative step</li>
|
||||
<li>New alias to MochiKit.swapDOM called removeElement</li>
|
||||
<li>New MochiKit.DOM.setNodeAttribute(node, attr, value) which sets
|
||||
an attribute on a node without raising, roughly equivalent to:
|
||||
updateNodeAttributes(node, {attr: value})</li>
|
||||
<li>New MochiKit.DOM.getNodeAttribute(node, attr) which gets the value of
|
||||
a node's attribute or returns null without raising</li>
|
||||
<li>Fixed a potential IE memory leak if using MochiKit.DOM.addToCallStack
|
||||
directly (addLoadEvent did not leak, since it clears the handler)</li>
|
||||
</ul>
|
||||
<p>2005-10-24 v1.0</p>
|
||||
<ul class="simple">
|
||||
<li>New interpreter example that shows usage of MochiKit.DOM to make
|
||||
an interactive JavaScript interpreter</li>
|
||||
<li>New MochiKit.LoggingPane for use with the MochiKit.Logging
|
||||
debuggingBookmarklet, with logging_pane example to show its usage</li>
|
||||
<li>New mochiregexp example that demonstrates MochiKit.DOM and MochiKit.Async
|
||||
in order to provide a live regular expression matching tool</li>
|
||||
<li>Added advanced number formatting capabilities to MochiKit.Format:
|
||||
numberFormatter(pattern, placeholder="", locale="default") and
|
||||
formatLocale(locale="default")</li>
|
||||
<li>Added updatetree(self, obj[, ...]) to MochiKit.Base, and changed
|
||||
MochiKit.DOM's updateNodeAttributes(node, attrs) to use it when appropiate.</li>
|
||||
<li>Added new MochiKit.DOM createDOMFunc aliases: BUTTON, TT, PRE</li>
|
||||
<li>Added truncToFixed(aNumber, precision) and roundToFixed(aNumber, precision)
|
||||
to MochiKit.Format</li>
|
||||
<li>MochiKit.DateTime can now handle full ISO 8601 timestamps, specifically
|
||||
isoTimestamp(isoString) will convert them to Date objects, and
|
||||
toISOTimestamp(date, true) will return an ISO 8601 timestamp in UTC</li>
|
||||
<li>Fixed missing errback for sendXMLHttpRequest when the server does not
|
||||
respond</li>
|
||||
<li>Fixed infinite recusion bug when using roundClass("DIV", ...)</li>
|
||||
<li>Fixed a bug in MochiKit.Async wait (and callLater) that prevented them
|
||||
from being cancelled properly</li>
|
||||
<li>Workaround in MochiKit.Base bind (and partial) for functions that don't
|
||||
have an apply method, such as alert</li>
|
||||
<li>Reliably return null from the string parsing/manipulation functions if
|
||||
the input can't be coerced to a string (s + "") or the input makes no sense;
|
||||
e.g. isoTimestamp(null) and isoTimestamp("") return null</li>
|
||||
</ul>
|
||||
<p>2005-10-08 v0.90</p>
|
||||
<ul class="simple">
|
||||
<li>Fixed ISO compliance with toISODate</li>
|
||||
<li>Added missing operator.sub</li>
|
||||
<li>Placated Mozilla's strict warnings a bit</li>
|
||||
<li>Added JSON serialization and unserialization support to MochiKit.Base:
|
||||
serializeJSON, evalJSON, registerJSON. This is very similar to the repr
|
||||
API.</li>
|
||||
<li>Fixed a bug in the script loader that failed in some scenarios when a script
|
||||
tag did not have a "src" attribute (thanks Ian!)</li>
|
||||
<li>Added new MochiKit.DOM createDOMFunc aliases: H1, H2, H3, BR, HR, TEXTAREA,
|
||||
P, FORM</li>
|
||||
<li>Use encodeURIComponent / decodeURIComponent for MochiKit.Base urlEncode
|
||||
and parseQueryString, when available.</li>
|
||||
</ul>
|
||||
<p>2005-08-12 v0.80</p>
|
||||
<ul class="simple">
|
||||
<li>Source highlighting in all examples, moved to a view-source example</li>
|
||||
<li>Added some experimental syntax highlighting for the Rounded Corners example,
|
||||
via the LGPL dp.SyntaxHighlighter 1.2.0 now included in examples/common/lib</li>
|
||||
<li>Use an indirect binding for the logger conveniences, so that the global
|
||||
logger could be replaced by setting MochiKit.Logger.logger to something else
|
||||
(though an observer is probably a better choice).</li>
|
||||
<li>Allow MochiKit.DOM.getElementsByTagAndClassName to take a string for parent,
|
||||
which will be looked up with getElement</li>
|
||||
<li>Fixed bug in MochiKit.Color.fromBackground (was using node.parent instead of
|
||||
node.parentNode)</li>
|
||||
<li>Consider a 304 (NOT_MODIFIED) response from XMLHttpRequest to be success</li>
|
||||
<li>Disabled Mozilla map(...) fast-path due to Deer Park compatibility issues</li>
|
||||
<li>Possible workaround for Safari issue with swapDOM, where it would get
|
||||
confused because two elements were in the DOM at the same time with the
|
||||
same id</li>
|
||||
<li>Added missing THEAD convenience function to MochiKit.DOM</li>
|
||||
<li>Added lstrip, rstrip, strip to MochiKit.Format</li>
|
||||
<li>Added updateNodeAttributes, appendChildNodes, replaceChildNodes to
|
||||
MochiKit.DOM</li>
|
||||
<li>MochiKit.Iter.iextend now has a fast-path for array-like objects</li>
|
||||
<li>Added HSV color space support to MochiKit.Visual</li>
|
||||
<li>Fixed a bug in the sortable_tables example, it now converts types
|
||||
correctly</li>
|
||||
<li>Fixed a bug where MochiKit.DOM referenced MochiKit.Iter.next from global
|
||||
scope</li>
|
||||
</ul>
|
||||
<p>2005-08-04 v0.70</p>
|
||||
<ul class="simple">
|
||||
<li>New ajax_tables example, which shows off XMLHttpRequest, ajax, json, and
|
||||
a little TAL-ish DOM templating attribute language.</li>
|
||||
<li>sendXMLHttpRequest and functions that use it (loadJSONDoc, etc.) no longer
|
||||
ignore requests with status == 0, which seems to happen for cached or local
|
||||
requests</li>
|
||||
<li>Added sendXMLHttpRequest to MochiKit.Async.EXPORT, d'oh.</li>
|
||||
<li>Changed scrapeText API to return a string by default. This is API-breaking!
|
||||
It was dumb to have the default return value be the form you almost never
|
||||
want. Sorry.</li>
|
||||
<li>Added special form to swapDOM(dest, src). If src is null, dest is removed
|
||||
(where previously you'd likely get a DOM exception).</li>
|
||||
<li>Added three new functions to MochiKit.Base for dealing with URL query
|
||||
strings: urlEncode, queryString, parseQueryString</li>
|
||||
<li>MochiKit.DOM.createDOM will now use attr[k] = v for all browsers if the name
|
||||
starts with "on" (e.g. "onclick"). If v is a string, it will set it to
|
||||
new Function(v).</li>
|
||||
<li>Another workaround for Internet "worst browser ever" Explorer's setAttribute
|
||||
usage in MochiKit.DOM.createDOM (checked -> defaultChecked).</li>
|
||||
<li>Added UL, OL, LI convenience createDOM aliases to MochiKit.DOM</li>
|
||||
<li>Packing is now done by Dojo's custom Rhino interpreter, so it's much smaller
|
||||
now!</li>
|
||||
</ul>
|
||||
<p>2005-07-29 v0.60</p>
|
||||
<ul class="simple">
|
||||
<li>Beefed up the MochiKit.DOM test suite</li>
|
||||
<li>Fixed return value for MochiKit.DOM.swapElementClass, could return
|
||||
false unexpectedly before</li>
|
||||
<li>Added an optional "parent" argument to
|
||||
MochiKit.DOM.getElementsByTagAndClassName</li>
|
||||
<li>Added a "packed" version in packed/lib/MochiKit/MochiKit.js</li>
|
||||
<li>Changed build script to rewrite the URLs in tests to account for the
|
||||
JSAN-required reorganization</li>
|
||||
<li>MochiKit.Compat to potentially work around IE 5.5 issues
|
||||
(5.0 still not supported). Test.Simple doesn't seem to work there,
|
||||
though.</li>
|
||||
<li>Several minor documentation corrections</li>
|
||||
</ul>
|
||||
<p>2005-07-27 v0.50</p>
|
||||
<ul class="simple">
|
||||
<li>Initial Release</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,162 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8" ?>
|
||||
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
|
||||
|
||||
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
|
||||
<meta name="generator" content="Docutils 0.4: http://docutils.sourceforge.net/" />
|
||||
<title>MochiKit.Visual - visual effects</title>
|
||||
|
||||
<link rel="stylesheet" href="../../../include/css/documentation.css" type="text/css" />
|
||||
<script type="text/javascript" src="../../../packed/lib/MochiKit/MochiKit.js"></script>
|
||||
<script type="text/javascript" src="../../js/toc.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div class="document">
|
||||
<div class="section">
|
||||
<h1><a id="name" name="name">Name</a></h1>
|
||||
<p>MochiKit.Visual - visual effects</p>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h1><a id="synopsis" name="synopsis">Synopsis</a></h1>
|
||||
<pre class="literal-block">
|
||||
// round the corners of all h1 elements
|
||||
roundClass("h1", null);
|
||||
|
||||
// round the top left corner of the element with the id "title"
|
||||
roundElement("title", {corners: "tl"});
|
||||
</pre>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h1><a id="description" name="description">Description</a></h1>
|
||||
<p>MochiKit.Visual provides visual effects and support functions for visuals.</p>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h1><a id="dependencies" name="dependencies">Dependencies</a></h1>
|
||||
<ul class="simple">
|
||||
<li><a class="mochiref reference" href="Base.html">MochiKit.Base</a></li>
|
||||
<li><a class="mochiref reference" href="Iter.html">MochiKit.Iter</a></li>
|
||||
<li><a class="mochiref reference" href="DOM.html">MochiKit.DOM</a></li>
|
||||
<li><a class="mochiref reference" href="Color.html">MochiKit.Color</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h1><a id="overview" name="overview">Overview</a></h1>
|
||||
<p>At this time, MochiKit.Visual provides one visual effect: rounded corners
|
||||
for your HTML elements. These rounded corners are created completely
|
||||
through CSS manipulations and require no external images or style sheets.
|
||||
This implementation was adapted from <a class="reference" href="http://www.openrico.org">Rico</a>.</p>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h1><a id="api-reference" name="api-reference">API Reference</a></h1>
|
||||
<div class="section">
|
||||
<h2><a id="functions" name="functions">Functions</a></h2>
|
||||
<p>
|
||||
<a name="fn-roundclass"></a>
|
||||
<a class="mochidef reference" href="#fn-roundclass">roundClass(tagName[, className[, options]])</a>:</p>
|
||||
<blockquote>
|
||||
Rounds all of the elements that match the <tt class="docutils literal"><span class="pre">tagName</span></tt> and <tt class="docutils literal"><span class="pre">className</span></tt>
|
||||
specifiers, using the options provided. <tt class="docutils literal"><span class="pre">tagName</span></tt> or <tt class="docutils literal"><span class="pre">className</span></tt> can
|
||||
be <tt class="docutils literal"><span class="pre">null</span></tt> to match all tags or classes. For more information about
|
||||
the options, see the <a class="mochiref reference" href="#fn-roundelement">roundElement</a> function.</blockquote>
|
||||
<p>
|
||||
<a name="fn-roundelement"></a>
|
||||
<a class="mochidef reference" href="#fn-roundelement">roundElement(element[, options])</a>:</p>
|
||||
<blockquote>
|
||||
<p>Immediately round the corners of the specified element.
|
||||
The element can be given as either a string
|
||||
with the element ID, or as an element object.</p>
|
||||
<p>The options mapping has the following defaults:</p>
|
||||
<table border="1" class="docutils">
|
||||
<colgroup>
|
||||
<col width="35%" />
|
||||
<col width="65%" />
|
||||
</colgroup>
|
||||
<tbody valign="top">
|
||||
<tr><td>corners</td>
|
||||
<td><tt class="docutils literal"><span class="pre">"all"</span></tt></td>
|
||||
</tr>
|
||||
<tr><td>color</td>
|
||||
<td><tt class="docutils literal"><span class="pre">"fromElement"</span></tt></td>
|
||||
</tr>
|
||||
<tr><td>bgColor</td>
|
||||
<td><tt class="docutils literal"><span class="pre">"fromParent"</span></tt></td>
|
||||
</tr>
|
||||
<tr><td>blend</td>
|
||||
<td><tt class="docutils literal"><span class="pre">true</span></tt></td>
|
||||
</tr>
|
||||
<tr><td>border</td>
|
||||
<td><tt class="docutils literal"><span class="pre">false</span></tt></td>
|
||||
</tr>
|
||||
<tr><td>compact</td>
|
||||
<td><tt class="docutils literal"><span class="pre">false</span></tt></td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<p>corners:</p>
|
||||
<blockquote>
|
||||
<p>specifies which corners of the element should be rounded.
|
||||
Choices are:</p>
|
||||
<ul class="simple">
|
||||
<li>all</li>
|
||||
<li>top</li>
|
||||
<li>bottom</li>
|
||||
<li>tl (top left)</li>
|
||||
<li>bl (bottom left)</li>
|
||||
<li>tr (top right)</li>
|
||||
<li>br (bottom right)</li>
|
||||
</ul>
|
||||
<dl class="docutils">
|
||||
<dt>Example:</dt>
|
||||
<dd><tt class="docutils literal"><span class="pre">"tl</span> <span class="pre">br"</span></tt>: top-left and bottom-right corners are rounded</dd>
|
||||
</dl>
|
||||
</blockquote>
|
||||
<dl class="docutils">
|
||||
<dt>blend:</dt>
|
||||
<dd>specifies whether the color and background color should be blended
|
||||
together to produce the border color.</dd>
|
||||
</dl>
|
||||
</blockquote>
|
||||
</div>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h1><a id="see-also" name="see-also">See Also</a></h1>
|
||||
<table class="docutils footnote" frame="void" id="id1" rules="none">
|
||||
<colgroup><col class="label" /><col /></colgroup>
|
||||
<tbody valign="top">
|
||||
<tr><td class="label"><a name="id1">[1]</a></td><td>Application Kit Reference - NSColor: <a class="reference" href="http://developer.apple.com/documentation/Cocoa/Reference/ApplicationKit/ObjC_classic/Classes/NSColor.html">http://developer.apple.com/documentation/Cocoa/Reference/ApplicationKit/ObjC_classic/Classes/NSColor.html</a></td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<table class="docutils footnote" frame="void" id="id2" rules="none">
|
||||
<colgroup><col class="label" /><col /></colgroup>
|
||||
<tbody valign="top">
|
||||
<tr><td class="label"><a name="id2">[2]</a></td><td>SVG 1.0 color keywords: <a class="reference" href="http://www.w3.org/TR/SVG/types.html#ColorKeywords">http://www.w3.org/TR/SVG/types.html#ColorKeywords</a></td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<table class="docutils footnote" frame="void" id="id3" rules="none">
|
||||
<colgroup><col class="label" /><col /></colgroup>
|
||||
<tbody valign="top">
|
||||
<tr><td class="label"><a name="id3">[3]</a></td><td>W3C CSS3 Color Module: <a class="reference" href="http://www.w3.org/TR/css3-color/#svg-color">http://www.w3.org/TR/css3-color/#svg-color</a></td></tr>
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h1><a id="authors" name="authors">Authors</a></h1>
|
||||
<ul class="simple">
|
||||
<li>Kevin Dangoor <<a class="reference" href="mailto:dangoor@gmail.com">dangoor@gmail.com</a>></li>
|
||||
<li>Bob Ippolito <<a class="reference" href="mailto:bob@redivi.com">bob@redivi.com</a>></li>
|
||||
<li>Originally adapted from Rico <<a class="reference" href="http://openrico.org/">http://openrico.org/</a>> (though little remains)</li>
|
||||
</ul>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h1><a id="copyright" name="copyright">Copyright</a></h1>
|
||||
<p>Copyright 2005 Bob Ippolito <<a class="reference" href="mailto:bob@redivi.com">bob@redivi.com</a>>. This program is dual-licensed
|
||||
free software; you can redistribute it and/or modify it under the terms of the
|
||||
<a class="reference" href="http://www.opensource.org/licenses/mit-license.php">MIT License</a> or the <a class="reference" href="http://www.opensource.org/licenses/afl-2.1.php">Academic Free License v2.1</a>.</p>
|
||||
<p>Portions adapted from <a class="reference" href="http://www.openrico.org">Rico</a> are available under the terms of the
|
||||
<a class="reference" href="http://www.apache.org/licenses/LICENSE-2.0.html">Apache License, Version 2.0</a>.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,319 +0,0 @@
|
||||
<?xml version="1.0" encoding="utf-8" ?>
|
||||
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
|
||||
|
||||
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
|
||||
<head>
|
||||
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
|
||||
<meta name="generator" content="Docutils 0.4: http://docutils.sourceforge.net/" />
|
||||
<title>MochiKit Documentation Index</title>
|
||||
|
||||
<link rel="stylesheet" href="../../../include/css/documentation.css" type="text/css" />
|
||||
<script type="text/javascript" src="../../../packed/lib/MochiKit/MochiKit.js"></script>
|
||||
<script type="text/javascript" src="../../js/toc.js"></script>
|
||||
</head>
|
||||
<body>
|
||||
<div class="document">
|
||||
<div class="section">
|
||||
<h1><a id="distribution" name="distribution">Distribution</a></h1>
|
||||
<p>MochiKit - makes JavaScript suck a bit less</p>
|
||||
<ul class="simple">
|
||||
<li><a class="mochiref reference" href="Async.html">MochiKit.Async</a> - manage asynchronous tasks</li>
|
||||
<li><a class="mochiref reference" href="Base.html">MochiKit.Base</a> - functional programming and useful comparisons</li>
|
||||
<li><a class="mochiref reference" href="DOM.html">MochiKit.DOM</a> - painless DOM manipulation API</li>
|
||||
<li><a class="mochiref reference" href="Color.html">MochiKit.Color</a> - color abstraction with CSS3 support</li>
|
||||
<li><a class="mochiref reference" href="DateTime.html">MochiKit.DateTime</a> - "what time is it anyway?"</li>
|
||||
<li><a class="mochiref reference" href="Format.html">MochiKit.Format</a> - string formatting goes here</li>
|
||||
<li><a class="mochiref reference" href="Iter.html">MochiKit.Iter</a> - itertools for JavaScript; iteration made HARD,
|
||||
and then easy</li>
|
||||
<li><a class="mochiref reference" href="Logging.html">MochiKit.Logging</a> - we're all tired of <tt class="docutils literal"><span class="pre">alert()</span></tt></li>
|
||||
<li><a class="mochiref reference" href="LoggingPane.html">MochiKit.LoggingPane</a> - interactive <a class="mochiref reference" href="Logging.html">MochiKit.Logging</a>
|
||||
pane</li>
|
||||
<li><a class="mochiref reference" href="Signal.html">MochiKit.Signal</a> - simple universal event handling</li>
|
||||
<li><a class="mochiref reference" href="Visual.html">MochiKit.Visual</a> - visual effects</li>
|
||||
</ul>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h1><a id="notes" name="notes">Notes</a></h1>
|
||||
<p>To turn on MochiKit's compatibility mode, do this before loading MochiKit:</p>
|
||||
<pre class="literal-block">
|
||||
<script type="text/javascript">MochiKit = {__compat__: true};</script>
|
||||
</pre>
|
||||
<p>When compatibility mode is on, you must use fully qualified names for all
|
||||
MochiKit functions (e.g. <tt class="docutils literal"><span class="pre">MochiKit.Base.map(...)</span></tt>).</p>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h1><a id="screencasts" name="screencasts">Screencasts</a></h1>
|
||||
<ul class="simple">
|
||||
<li><a class="reference" href="http://mochikit.com/screencasts/MochiKit_Intro-1">MochiKit 1.1 Intro</a></li>
|
||||
</ul>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h1><a id="see-also" name="see-also">See Also</a></h1>
|
||||
<ul class="simple">
|
||||
<li><a class="reference" href="http://groups.google.com/group/mochikit">Google Groups: MochiKit</a>: The official mailing list for discussions
|
||||
related to development of and with MochiKit</li>
|
||||
<li><a class="reference" href="http://mochikit.com/">mochikit.com</a>: MochiKit's home on the web</li>
|
||||
<li><a class="reference" href="http://bob.pythonmac.org/">from __future__ import *</a>: Bob Ippolito's blog</li>
|
||||
<li><a class="reference" href="http://openjsan.org/doc/b/bo/bob/lib/MochiKit/">MochiKit on JSAN</a>: the JSAN distribution page for MochiKit</li>
|
||||
<li><a class="reference" href="http://del.icio.us/tag/mochikit">MochiKit tag on del.icio.us</a>: Recent bookmarks related to MochiKit</li>
|
||||
<li><a class="reference" href="http://technorati.com/tag/mochikit">MochiKit tag on Technorati</a>: Recent blog entries related to MochiKit</li>
|
||||
</ul>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h1><a id="version-history" name="version-history">Version History</a></h1>
|
||||
<p>2006-04-29 v1.3.1 (bug fix release)</p>
|
||||
<ul class="simple">
|
||||
<li>Fix sendXMLHttpRequest sendContent regression</li>
|
||||
<li>Internet Explorer fix in MochiKit.Logging (printfire exception)</li>
|
||||
<li>Internet Explorer XMLHttpRequest object leak fixed in MochiKit.Async</li>
|
||||
</ul>
|
||||
<p>2006-04-26 v1.3 "warp zone"</p>
|
||||
<ul class="simple">
|
||||
<li>IMPORTANT: Renamed MochiKit.Base.forward to forwardCall (for export)</li>
|
||||
<li>IMPORTANT: Renamed MochiKit.Base.find to findValue (for export)</li>
|
||||
<li>New MochiKit.Base.method as a convenience form of bind that takes the
|
||||
object before the method</li>
|
||||
<li>New MochiKit.Base.flattenArguments for flattening a list of arguments to
|
||||
a single Array</li>
|
||||
<li>Refactored MochiRegExp example to use MochiKit.Signal</li>
|
||||
<li>New key_events example demonstrating use of MochiKit.Signal's key handling
|
||||
capabilities.</li>
|
||||
<li>MochiKit.DOM.createDOM API change for convenience: if attrs is a string,
|
||||
null is used and the string will be considered the first node. This
|
||||
allows for the more natural P("foo") rather than P(null, "foo").</li>
|
||||
<li>MochiKit Interpreter example refactored to use MochiKit.Signal and now
|
||||
provides multi-line input and a help() function to get MochiKit function
|
||||
signature from the documentation.</li>
|
||||
<li>Native Console Logging for the default MochiKit.Logging logger</li>
|
||||
<li>New MochiKit.Async.DeferredList, gatherResults, maybeDeferred</li>
|
||||
<li>New MochiKit.Signal example: draggable</li>
|
||||
<li>Added sanity checking to Deferred to ensure that errors happen when chaining
|
||||
is used incorrectly</li>
|
||||
<li>Opera sendXMLHttpRequest fix (sends empty string instead of null by default)</li>
|
||||
<li>Fix a bug in MochiKit.Color that incorrectly generated hex colors for
|
||||
component values smaller than 16/255.</li>
|
||||
<li>Fix a bug in MochiKit.Logging that prevented logs from being capped at a
|
||||
maximum size</li>
|
||||
<li>MochiKit.Async.Deferred will now wrap thrown objects that are not instanceof
|
||||
Error, so that the errback chain is used instead of the callback chain.</li>
|
||||
<li>MochiKit.DOM.appendChildNodes and associated functions now append iterables
|
||||
in the correct order.</li>
|
||||
<li>New MochiKit-based SimpleTest test runner as a replacement for Test.Simple</li>
|
||||
<li>MochiKit.Base.isNull no longer matches undefined</li>
|
||||
<li>example doctypes changed to HTML4</li>
|
||||
<li>isDateLike no longer throws error on null</li>
|
||||
<li>New MochiKit.Signal module, modeled after the slot/signal mechanism in Qt</li>
|
||||
<li>updated elementDimensions to calculate width from offsetWidth instead
|
||||
of clientWidth</li>
|
||||
<li>formContents now works with FORM tags that have a name attribute</li>
|
||||
<li>Documentation now uses MochiKit to generate a function index</li>
|
||||
</ul>
|
||||
<p>2006-01-26 v1.2 "the ocho"</p>
|
||||
<ul class="simple">
|
||||
<li>Fixed MochiKit.Color.Color.lighterColorWithLevel</li>
|
||||
<li>Added new MochiKit.Base.findIdentical function to find the index of an
|
||||
element in an Array-like object. Uses === for identity comparison.</li>
|
||||
<li>Added new MochiKit.Base.find function to find the index of an element in
|
||||
an Array-like object. Uses compare for rich comparison.</li>
|
||||
<li>MochiKit.Base.bind will accept a string for func, which will be immediately
|
||||
looked up as self[func].</li>
|
||||
<li>MochiKit.DOM.formContents no longer skips empty form elements for Zope
|
||||
compatibility</li>
|
||||
<li>MochiKit.Iter.forEach will now catch StopIteration to break</li>
|
||||
<li>New MochiKit.DOM.elementDimensions(element) for determining the width and
|
||||
height of an element in the document</li>
|
||||
<li>MochiKit.DOM's initialization is now compatible with
|
||||
HTMLUnit + JWebUnit + Rhino</li>
|
||||
<li>MochiKit.LoggingPane will now re-use a <tt class="docutils literal"><span class="pre">_MochiKit_LoggingPane</span></tt> DIV element
|
||||
currently in the document instead of always creating one.</li>
|
||||
<li>MochiKit.Base now has operator.mul</li>
|
||||
<li>MochiKit.DOM.formContents correctly handles unchecked checkboxes that have
|
||||
a custom value attribute</li>
|
||||
<li>Added new MochiKit.Color constructors fromComputedStyle and fromText</li>
|
||||
<li>MochiKit.DOM.setNodeAttribute should work now</li>
|
||||
<li>MochiKit.DOM now has a workaround for an IE bug when setting the style
|
||||
property to a string</li>
|
||||
<li>MochiKit.DOM.createDOM now has workarounds for IE bugs when setting the
|
||||
name and for properties</li>
|
||||
<li>MochiKit.DOM.scrapeText now walks the DOM tree in-order</li>
|
||||
<li>MochiKit.LoggingPane now sanitizes the window name to work around IE bug</li>
|
||||
<li>MochiKit.DOM now translates usemap to useMap to work around IE bug</li>
|
||||
<li>MochiKit.Logging is now resistant to Prototype's dumb Object.prototype hacks</li>
|
||||
<li>Added new MochiKit.DOM documentation on element visibility</li>
|
||||
<li>New MochiKit.DOM.elementPosition(element[, relativeTo={x: 0, y: 0}])
|
||||
for determining the position of an element in the document</li>
|
||||
<li>Added new MochiKit.DOM createDOMFunc aliases: CANVAS, STRONG</li>
|
||||
</ul>
|
||||
<p>2005-11-14 v1.1</p>
|
||||
<ul class="simple">
|
||||
<li>Fixed a bug in numberFormatter with large numbers</li>
|
||||
<li>Massively overhauled documentation</li>
|
||||
<li>Fast-path for primitives in MochiKit.Base.compare</li>
|
||||
<li>New groupby and groupby_as_array in MochiKit.Iter</li>
|
||||
<li>Added iterator factory adapter for objects that implement iterateNext()</li>
|
||||
<li>Fixed isoTimestamp to handle timestamps with time zone correctly</li>
|
||||
<li>Added new MochiKit.DOM createDOMFunc aliases: SELECT, OPTION, OPTGROUP,
|
||||
LEGEND, FIELDSET</li>
|
||||
<li>New MochiKit.DOM formContents and enhancement to queryString to support it</li>
|
||||
<li>Updated view_source example to use dp.SyntaxHighlighter 1.3.0</li>
|
||||
<li>MochiKit.LoggingPane now uses named windows based on the URL so that
|
||||
a given URL will get the same LoggingPane window after a reload
|
||||
(at the same position, etc.)</li>
|
||||
<li>MochiKit.DOM now has currentWindow() and currentDocument() context
|
||||
variables that are set with withWindow() and withDocument(). These
|
||||
context variables affect all MochiKit.DOM functionality (getElement,
|
||||
createDOM, etc.)</li>
|
||||
<li>MochiKit.Base.items will now catch and ignore exceptions for properties
|
||||
that are enumerable but not accessible (e.g. permission denied)</li>
|
||||
<li>MochiKit.Async.Deferred's addCallback/addErrback/addBoth
|
||||
now accept additional arguments that are used to create a partially
|
||||
applied function. This differs from Twisted in that the callback/errback
|
||||
result becomes the <em>last</em> argument, not the first when this feature
|
||||
is used.</li>
|
||||
<li>MochiKit.Async's doSimpleXMLHttpRequest will now accept additional
|
||||
arguments which are used to create a GET query string</li>
|
||||
<li>Did some refactoring to reduce the footprint of MochiKit by a few
|
||||
kilobytes</li>
|
||||
<li>escapeHTML to longer escapes ' (apos) and now uses
|
||||
String.replace instead of iterating over every char.</li>
|
||||
<li>Added DeferredLock to Async</li>
|
||||
<li>Renamed getElementsComputedStyle to computedStyle and moved
|
||||
it from MochiKit.Visual to MochiKit.DOM</li>
|
||||
<li>Moved all color support out of MochiKit.Visual and into MochiKit.Color</li>
|
||||
<li>Fixed range() to accept a negative step</li>
|
||||
<li>New alias to MochiKit.swapDOM called removeElement</li>
|
||||
<li>New MochiKit.DOM.setNodeAttribute(node, attr, value) which sets
|
||||
an attribute on a node without raising, roughly equivalent to:
|
||||
updateNodeAttributes(node, {attr: value})</li>
|
||||
<li>New MochiKit.DOM.getNodeAttribute(node, attr) which gets the value of
|
||||
a node's attribute or returns null without raising</li>
|
||||
<li>Fixed a potential IE memory leak if using MochiKit.DOM.addToCallStack
|
||||
directly (addLoadEvent did not leak, since it clears the handler)</li>
|
||||
</ul>
|
||||
<p>2005-10-24 v1.0</p>
|
||||
<ul class="simple">
|
||||
<li>New interpreter example that shows usage of MochiKit.DOM to make
|
||||
an interactive JavaScript interpreter</li>
|
||||
<li>New MochiKit.LoggingPane for use with the MochiKit.Logging
|
||||
debuggingBookmarklet, with logging_pane example to show its usage</li>
|
||||
<li>New mochiregexp example that demonstrates MochiKit.DOM and MochiKit.Async
|
||||
in order to provide a live regular expression matching tool</li>
|
||||
<li>Added advanced number formatting capabilities to MochiKit.Format:
|
||||
numberFormatter(pattern, placeholder="", locale="default") and
|
||||
formatLocale(locale="default")</li>
|
||||
<li>Added updatetree(self, obj[, ...]) to MochiKit.Base, and changed
|
||||
MochiKit.DOM's updateNodeAttributes(node, attrs) to use it when appropiate.</li>
|
||||
<li>Added new MochiKit.DOM createDOMFunc aliases: BUTTON, TT, PRE</li>
|
||||
<li>Added truncToFixed(aNumber, precision) and roundToFixed(aNumber, precision)
|
||||
to MochiKit.Format</li>
|
||||
<li>MochiKit.DateTime can now handle full ISO 8601 timestamps, specifically
|
||||
isoTimestamp(isoString) will convert them to Date objects, and
|
||||
toISOTimestamp(date, true) will return an ISO 8601 timestamp in UTC</li>
|
||||
<li>Fixed missing errback for sendXMLHttpRequest when the server does not
|
||||
respond</li>
|
||||
<li>Fixed infinite recusion bug when using roundClass("DIV", ...)</li>
|
||||
<li>Fixed a bug in MochiKit.Async wait (and callLater) that prevented them
|
||||
from being cancelled properly</li>
|
||||
<li>Workaround in MochiKit.Base bind (and partial) for functions that don't
|
||||
have an apply method, such as alert</li>
|
||||
<li>Reliably return null from the string parsing/manipulation functions if
|
||||
the input can't be coerced to a string (s + "") or the input makes no sense;
|
||||
e.g. isoTimestamp(null) and isoTimestamp("") return null</li>
|
||||
</ul>
|
||||
<p>2005-10-08 v0.90</p>
|
||||
<ul class="simple">
|
||||
<li>Fixed ISO compliance with toISODate</li>
|
||||
<li>Added missing operator.sub</li>
|
||||
<li>Placated Mozilla's strict warnings a bit</li>
|
||||
<li>Added JSON serialization and unserialization support to MochiKit.Base:
|
||||
serializeJSON, evalJSON, registerJSON. This is very similar to the repr
|
||||
API.</li>
|
||||
<li>Fixed a bug in the script loader that failed in some scenarios when a script
|
||||
tag did not have a "src" attribute (thanks Ian!)</li>
|
||||
<li>Added new MochiKit.DOM createDOMFunc aliases: H1, H2, H3, BR, HR, TEXTAREA,
|
||||
P, FORM</li>
|
||||
<li>Use encodeURIComponent / decodeURIComponent for MochiKit.Base urlEncode
|
||||
and parseQueryString, when available.</li>
|
||||
</ul>
|
||||
<p>2005-08-12 v0.80</p>
|
||||
<ul class="simple">
|
||||
<li>Source highlighting in all examples, moved to a view-source example</li>
|
||||
<li>Added some experimental syntax highlighting for the Rounded Corners example,
|
||||
via the LGPL dp.SyntaxHighlighter 1.2.0 now included in examples/common/lib</li>
|
||||
<li>Use an indirect binding for the logger conveniences, so that the global
|
||||
logger could be replaced by setting MochiKit.Logger.logger to something else
|
||||
(though an observer is probably a better choice).</li>
|
||||
<li>Allow MochiKit.DOM.getElementsByTagAndClassName to take a string for parent,
|
||||
which will be looked up with getElement</li>
|
||||
<li>Fixed bug in MochiKit.Color.fromBackground (was using node.parent instead of
|
||||
node.parentNode)</li>
|
||||
<li>Consider a 304 (NOT_MODIFIED) response from XMLHttpRequest to be success</li>
|
||||
<li>Disabled Mozilla map(...) fast-path due to Deer Park compatibility issues</li>
|
||||
<li>Possible workaround for Safari issue with swapDOM, where it would get
|
||||
confused because two elements were in the DOM at the same time with the
|
||||
same id</li>
|
||||
<li>Added missing THEAD convenience function to MochiKit.DOM</li>
|
||||
<li>Added lstrip, rstrip, strip to MochiKit.Format</li>
|
||||
<li>Added updateNodeAttributes, appendChildNodes, replaceChildNodes to
|
||||
MochiKit.DOM</li>
|
||||
<li>MochiKit.Iter.iextend now has a fast-path for array-like objects</li>
|
||||
<li>Added HSV color space support to MochiKit.Visual</li>
|
||||
<li>Fixed a bug in the sortable_tables example, it now converts types
|
||||
correctly</li>
|
||||
<li>Fixed a bug where MochiKit.DOM referenced MochiKit.Iter.next from global
|
||||
scope</li>
|
||||
</ul>
|
||||
<p>2005-08-04 v0.70</p>
|
||||
<ul class="simple">
|
||||
<li>New ajax_tables example, which shows off XMLHttpRequest, ajax, json, and
|
||||
a little TAL-ish DOM templating attribute language.</li>
|
||||
<li>sendXMLHttpRequest and functions that use it (loadJSONDoc, etc.) no longer
|
||||
ignore requests with status == 0, which seems to happen for cached or local
|
||||
requests</li>
|
||||
<li>Added sendXMLHttpRequest to MochiKit.Async.EXPORT, d'oh.</li>
|
||||
<li>Changed scrapeText API to return a string by default. This is API-breaking!
|
||||
It was dumb to have the default return value be the form you almost never
|
||||
want. Sorry.</li>
|
||||
<li>Added special form to swapDOM(dest, src). If src is null, dest is removed
|
||||
(where previously you'd likely get a DOM exception).</li>
|
||||
<li>Added three new functions to MochiKit.Base for dealing with URL query
|
||||
strings: urlEncode, queryString, parseQueryString</li>
|
||||
<li>MochiKit.DOM.createDOM will now use attr[k] = v for all browsers if the name
|
||||
starts with "on" (e.g. "onclick"). If v is a string, it will set it to
|
||||
new Function(v).</li>
|
||||
<li>Another workaround for Internet "worst browser ever" Explorer's setAttribute
|
||||
usage in MochiKit.DOM.createDOM (checked -> defaultChecked).</li>
|
||||
<li>Added UL, OL, LI convenience createDOM aliases to MochiKit.DOM</li>
|
||||
<li>Packing is now done by Dojo's custom Rhino interpreter, so it's much smaller
|
||||
now!</li>
|
||||
</ul>
|
||||
<p>2005-07-29 v0.60</p>
|
||||
<ul class="simple">
|
||||
<li>Beefed up the MochiKit.DOM test suite</li>
|
||||
<li>Fixed return value for MochiKit.DOM.swapElementClass, could return
|
||||
false unexpectedly before</li>
|
||||
<li>Added an optional "parent" argument to
|
||||
MochiKit.DOM.getElementsByTagAndClassName</li>
|
||||
<li>Added a "packed" version in packed/lib/MochiKit/MochiKit.js</li>
|
||||
<li>Changed build script to rewrite the URLs in tests to account for the
|
||||
JSAN-required reorganization</li>
|
||||
<li>MochiKit.Compat to potentially work around IE 5.5 issues
|
||||
(5.0 still not supported). Test.Simple doesn't seem to work there,
|
||||
though.</li>
|
||||
<li>Several minor documentation corrections</li>
|
||||
</ul>
|
||||
<p>2005-07-27 v0.50</p>
|
||||
<ul class="simple">
|
||||
<li>Initial Release</li>
|
||||
</ul>
|
||||
</div>
|
||||
<div class="section">
|
||||
<h1><a id="copyright" name="copyright">Copyright</a></h1>
|
||||
<p>Copyright 2005 Bob Ippolito <<a class="reference" href="mailto:bob@redivi.com">bob@redivi.com</a>>. This program is dual-licensed
|
||||
free software; you can redistribute it and/or modify it under the terms of the
|
||||
<a class="reference" href="http://www.opensource.org/licenses/mit-license.php">MIT License</a> or the <a class="reference" href="http://www.opensource.org/licenses/afl-2.1.php">Academic Free License v2.1</a>.</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,89 +0,0 @@
|
||||
function function_ref(fn) {
|
||||
return A({"href": fn[1], "class": "mochiref reference"}, fn[0], BR());
|
||||
};
|
||||
|
||||
function toggle_docs() {
|
||||
toggleElementClass("invisible", "show_index", "function_index");
|
||||
return false;
|
||||
};
|
||||
|
||||
function create_toc() {
|
||||
if (getElement("distribution")) {
|
||||
return global_index();
|
||||
}
|
||||
if (getElement("api-reference")) {
|
||||
return module_index();
|
||||
}
|
||||
};
|
||||
|
||||
function doXHTMLRequest(url) {
|
||||
var req = getXMLHttpRequest();
|
||||
if (req.overrideMimeType) {
|
||||
req.overrideMimeType("text/xml");
|
||||
}
|
||||
req.open("GET", url, true);
|
||||
return sendXMLHttpRequest(req).addCallback(function (res) {
|
||||
return res.responseXML.documentElement;
|
||||
});
|
||||
};
|
||||
|
||||
function load_request(href, div, doc) {
|
||||
var functions = withDocument(doc, spider_doc);
|
||||
forEach(functions, function (func) {
|
||||
// fix anchors
|
||||
if (func[1].charAt(0) == "#") {
|
||||
func[1] = href + func[1];
|
||||
}
|
||||
});
|
||||
var showLink = A({"class": "force-pointer"}, "[+]");
|
||||
var hideLink = A({"class": "force-pointer"}, "[\u2013]");
|
||||
var functionIndex = DIV({"id": "function_index", "class": "invisible"},
|
||||
hideLink,
|
||||
P(null, map(function_ref, functions))
|
||||
);
|
||||
var toggleFunc = function (e) {
|
||||
toggleElementClass("invisible", showLink, functionIndex);
|
||||
};
|
||||
connect(showLink, "onclick", toggleFunc);
|
||||
connect(hideLink, "onclick", toggleFunc);
|
||||
replaceChildNodes(div,
|
||||
showLink,
|
||||
functionIndex
|
||||
);
|
||||
};
|
||||
|
||||
function global_index() {
|
||||
var distList = getElementsByTagAndClassName("ul")[0];
|
||||
var bullets = getElementsByTagAndClassName("li", null, distList);
|
||||
for (var i = 0; i < bullets.length; i++) {
|
||||
var tag = bullets[i];
|
||||
var firstLink = getElementsByTagAndClassName("a", "mochiref", tag)[0];
|
||||
var href = getNodeAttribute(firstLink, "href");
|
||||
var div = DIV(null, "[\u2026]");
|
||||
appendChildNodes(tag, BR(), div);
|
||||
var d = doXHTMLRequest(href).addCallback(load_request, href, div);
|
||||
}
|
||||
};
|
||||
|
||||
function spider_doc() {
|
||||
return map(
|
||||
function (tag) {
|
||||
return [scrapeText(tag), getNodeAttribute(tag, "href")];
|
||||
},
|
||||
getElementsByTagAndClassName("a", "mochidef")
|
||||
);
|
||||
};
|
||||
|
||||
function module_index() {
|
||||
var sections = getElementsByTagAndClassName("div", "section");
|
||||
var ptr = sections[1];
|
||||
var ref = DIV({"class": "section"},
|
||||
H1(null, "Function Index"),
|
||||
A({"id": "show_index", "href": "#", "onclick": toggle_docs}, "[show]"),
|
||||
DIV({"id": "function_index", "class": "invisible"},
|
||||
A({"href":"#", "onclick": toggle_docs}, "[hide]"),
|
||||
P(null, map(function_ref, spider_doc()))));
|
||||
ptr.parentNode.insertBefore(ref, ptr);
|
||||
};
|
||||
|
||||
addLoadEvent(create_toc);
|
||||
@@ -1,573 +0,0 @@
|
||||
.. title:: MochiKit.Async - manage asynchronous tasks
|
||||
|
||||
Name
|
||||
====
|
||||
|
||||
MochiKit.Async - manage asynchronous tasks
|
||||
|
||||
|
||||
Synopsis
|
||||
========
|
||||
|
||||
::
|
||||
|
||||
var url = "/src/b/bo/bob/MochiKit.Async/META.json";
|
||||
/*
|
||||
|
||||
META.json looks something like this:
|
||||
|
||||
{"name": "MochiKit", "version": "0.5"}
|
||||
|
||||
*/
|
||||
var d = loadJSONDoc(url);
|
||||
var gotMetadata = function (meta) {
|
||||
if (MochiKit.Async.VERSION == meta.version) {
|
||||
alert("You have the newest MochiKit.Async!");
|
||||
} else {
|
||||
alert("MochiKit.Async "
|
||||
+ meta.version
|
||||
+ " is available, upgrade!");
|
||||
}
|
||||
};
|
||||
var metadataFetchFailed = function (err) {
|
||||
alert("The metadata for MochiKit.Async could not be fetched :(");
|
||||
};
|
||||
d.addCallbacks(gotMetadata, metadataFetchFailed);
|
||||
|
||||
|
||||
Description
|
||||
===========
|
||||
|
||||
MochiKit.Async provides facilities to manage asynchronous
|
||||
(as in AJAX [1]_) tasks. The model for asynchronous computation
|
||||
used in this module is heavily inspired by Twisted [2]_.
|
||||
|
||||
|
||||
Dependencies
|
||||
============
|
||||
|
||||
- :mochiref:`MochiKit.Base`
|
||||
|
||||
|
||||
Overview
|
||||
========
|
||||
|
||||
Deferred
|
||||
--------
|
||||
|
||||
The Deferred constructor encapsulates a single value that
|
||||
is not available yet. The most important example of this
|
||||
in the context of a web browser would be an ``XMLHttpRequest``
|
||||
to a server. The importance of the Deferred is that it
|
||||
allows a consistent API to be exposed for all asynchronous
|
||||
computations that occur exactly once.
|
||||
|
||||
The producer of the Deferred is responsible for doing all
|
||||
of the complicated work behind the scenes. This often
|
||||
means waiting for a timer to fire, or waiting for an event
|
||||
(e.g. ``onreadystatechange`` of ``XMLHttpRequest``).
|
||||
It could also be coordinating several events (e.g.
|
||||
``XMLHttpRequest`` with a timeout, or several Deferreds
|
||||
(e.g. fetching a set of XML documents that should be
|
||||
processed at the same time).
|
||||
|
||||
Since these sorts of tasks do not respond immediately, the
|
||||
producer of the Deferred does the following steps before
|
||||
returning to the consumer:
|
||||
|
||||
1. Create a ``new`` :mochiref:`Deferred();` object and keep a reference
|
||||
to it, because it will be needed later when the value is
|
||||
ready.
|
||||
2. Setup the conditions to create the value requested (e.g.
|
||||
create a new ``XMLHttpRequest``, set its
|
||||
``onreadystatechange``).
|
||||
3. Return the :mochiref:`Deferred` object.
|
||||
|
||||
Since the value is not yet ready, the consumer attaches
|
||||
a function to the Deferred that will be called when the
|
||||
value is ready. This is not unlike ``setTimeout``, or
|
||||
other similar facilities you may already be familiar with.
|
||||
The consumer can also attach an "errback" to the
|
||||
:mochiref:`Deferred`, which is a callback for error handling.
|
||||
|
||||
When the value is ready, the producer simply calls
|
||||
``myDeferred.callback(theValue)``. If an error occurred,
|
||||
it should call ``myDeferred.errback(theValue)`` instead.
|
||||
As soon as this happens, the callback that the consumer
|
||||
attached to the :mochiref:`Deferred` is called with ``theValue``
|
||||
as the only argument.
|
||||
|
||||
There are quite a few additional "advanced" features
|
||||
baked into :mochiref:`Deferred`, such as cancellation and
|
||||
callback chains, so take a look at the API
|
||||
reference if you would like to know more!
|
||||
|
||||
API Reference
|
||||
=============
|
||||
|
||||
Errors
|
||||
------
|
||||
|
||||
:mochidef:`AlreadyCalledError`:
|
||||
|
||||
Thrown by a :mochiref:`Deferred` if ``.callback`` or
|
||||
``.errback`` are called more than once.
|
||||
|
||||
|
||||
:mochidef:`BrowserComplianceError`:
|
||||
|
||||
Thrown when the JavaScript runtime is not capable of performing
|
||||
the given function. Currently, this happens if the browser
|
||||
does not support ``XMLHttpRequest``.
|
||||
|
||||
|
||||
:mochidef:`CancelledError`:
|
||||
|
||||
Thrown by a :mochiref:`Deferred` when it is cancelled,
|
||||
unless a canceller is present and throws something else.
|
||||
|
||||
|
||||
:mochidef:`GenericError`:
|
||||
|
||||
Results passed to ``.fail`` or ``.errback`` of a :mochiref:`Deferred`
|
||||
are wrapped by this ``Error`` if ``!(result instanceof Error)``.
|
||||
|
||||
|
||||
:mochidef:`XMLHttpRequestError`:
|
||||
|
||||
Thrown when an ``XMLHttpRequest`` does not complete successfully
|
||||
for any reason. The ``req`` property of the error is the failed
|
||||
``XMLHttpRequest`` object, and for convenience the ``number``
|
||||
property corresponds to ``req.status``.
|
||||
|
||||
|
||||
Constructors
|
||||
------------
|
||||
|
||||
:mochidef:`Deferred()`:
|
||||
|
||||
Encapsulates a sequence of callbacks in response to a value that
|
||||
may not yet be available. This is modeled after the Deferred class
|
||||
from Twisted [3]_.
|
||||
|
||||
.. _`Twisted`: http://twistedmatrix.com/
|
||||
|
||||
Why do we want this? JavaScript has no threads, and even if it did,
|
||||
threads are hard. Deferreds are a way of abstracting non-blocking
|
||||
events, such as the final response to an ``XMLHttpRequest``.
|
||||
|
||||
The sequence of callbacks is internally represented as a list
|
||||
of 2-tuples containing the callback/errback pair. For example,
|
||||
the following call sequence::
|
||||
|
||||
var d = new Deferred();
|
||||
d.addCallback(myCallback);
|
||||
d.addErrback(myErrback);
|
||||
d.addBoth(myBoth);
|
||||
d.addCallbacks(myCallback, myErrback);
|
||||
|
||||
is translated into a :mochiref:`Deferred` with the following internal
|
||||
representation::
|
||||
|
||||
[
|
||||
[myCallback, null],
|
||||
[null, myErrback],
|
||||
[myBoth, myBoth],
|
||||
[myCallback, myErrback]
|
||||
]
|
||||
|
||||
The :mochiref:`Deferred` also keeps track of its current status (fired).
|
||||
Its status may be one of the following three values:
|
||||
|
||||
|
||||
===== ================================
|
||||
Value Condition
|
||||
===== ================================
|
||||
-1 no value yet (initial condition)
|
||||
0 success
|
||||
1 error
|
||||
===== ================================
|
||||
|
||||
A :mochiref:`Deferred` will be in the error state if one of the following
|
||||
conditions are met:
|
||||
|
||||
1. The result given to callback or errback is "``instanceof Error``"
|
||||
2. The callback or errback threw while executing. If the thrown object
|
||||
is not ``instanceof Error``, it will be wrapped with
|
||||
:mochiref:`GenericError`.
|
||||
|
||||
Otherwise, the :mochiref:`Deferred` will be in the success state. The state
|
||||
of the :mochiref:`Deferred` determines the next element in the callback
|
||||
sequence to run.
|
||||
|
||||
When a callback or errback occurs with the example deferred chain, something
|
||||
equivalent to the following will happen (imagine that exceptions are caught
|
||||
and returned as-is)::
|
||||
|
||||
// d.callback(result) or d.errback(result)
|
||||
if (!(result instanceof Error)) {
|
||||
result = myCallback(result);
|
||||
}
|
||||
if (result instanceof Error) {
|
||||
result = myErrback(result);
|
||||
}
|
||||
result = myBoth(result);
|
||||
if (result instanceof Error) {
|
||||
result = myErrback(result);
|
||||
} else {
|
||||
result = myCallback(result);
|
||||
}
|
||||
|
||||
The result is then stored away in case another step is added to the
|
||||
callback sequence. Since the :mochiref:`Deferred` already has a value
|
||||
available, any new callbacks added will be called immediately.
|
||||
|
||||
There are two other "advanced" details about this implementation that are
|
||||
useful:
|
||||
|
||||
Callbacks are allowed to return :mochiref:`Deferred` instances,
|
||||
so you can build complicated sequences of events with (relative) ease.
|
||||
|
||||
The creator of the :mochiref:`Deferred` may specify a canceller. The
|
||||
canceller is a function that will be called if
|
||||
:mochiref:`Deferred.prototype.cancel` is called before the
|
||||
:mochiref:`Deferred` fires. You can use this to allow an
|
||||
``XMLHttpRequest`` to be cleanly cancelled, for example. Note that
|
||||
cancel will fire the :mochiref:`Deferred` with a
|
||||
:mochiref:`CancelledError` (unless your canceller throws or returns
|
||||
a different ``Error``), so errbacks should be prepared to handle that
|
||||
``Error`` gracefully for cancellable :mochiref:`Deferred` instances.
|
||||
|
||||
|
||||
:mochidef:`Deferred.prototype.addBoth(func)`:
|
||||
|
||||
Add the same function as both a callback and an errback as the
|
||||
next element on the callback sequence. This is useful for code
|
||||
that you want to guarantee to run, e.g. a finalizer.
|
||||
|
||||
If additional arguments are given, then ``func`` will be replaced
|
||||
with :mochiref:`MochiKit.Base.partial.apply(null, arguments)`. This
|
||||
differs from `Twisted`_, because the result of the callback or
|
||||
errback will be the *last* argument passed to ``func``.
|
||||
|
||||
If ``func`` returns a :mochiref:`Deferred`, then it will be chained
|
||||
(its value or error will be passed to the next callback). Note that
|
||||
once the returned ``Deferred`` is chained, it can no longer accept new
|
||||
callbacks.
|
||||
|
||||
|
||||
:mochidef:`Deferred.prototype.addCallback(func[, ...])`:
|
||||
|
||||
Add a single callback to the end of the callback sequence.
|
||||
|
||||
If additional arguments are given, then ``func`` will be replaced
|
||||
with :mochiref:`MochiKit.Base.partial.apply(null, arguments)`. This
|
||||
differs from `Twisted`_, because the result of the callback will
|
||||
be the *last* argument passed to ``func``.
|
||||
|
||||
If ``func`` returns a :mochiref:`Deferred`, then it will be chained
|
||||
(its value or error will be passed to the next callback). Note that
|
||||
once the returned ``Deferred`` is chained, it can no longer accept new
|
||||
callbacks.
|
||||
|
||||
:mochidef:`Deferred.prototype.addCallbacks(callback, errback)`:
|
||||
|
||||
Add separate callback and errback to the end of the callback
|
||||
sequence. Either callback or errback may be ``null``,
|
||||
but not both.
|
||||
|
||||
If ``callback`` or ``errback`` returns a :mochiref:`Deferred`,
|
||||
then it will be chained (its value or error will be passed to the
|
||||
next callback). Note that once the returned ``Deferred`` is chained,
|
||||
it can no longer accept new callbacks.
|
||||
|
||||
:mochidef:`Deferred.prototype.addErrback(func)`:
|
||||
|
||||
Add a single errback to the end of the callback sequence.
|
||||
|
||||
If additional arguments are given, then ``func`` will be replaced
|
||||
with :mochiref:`MochiKit.Base.partial.apply(null, arguments)`. This
|
||||
differs from `Twisted`_, because the result of the errback will
|
||||
be the *last* argument passed to ``func``.
|
||||
|
||||
If ``func`` returns a :mochiref:`Deferred`, then it will be chained
|
||||
(its value or error will be passed to the next callback). Note that
|
||||
once the returned ``Deferred`` is chained, it can no longer accept new
|
||||
callbacks.
|
||||
|
||||
:mochidef:`Deferred.prototype.callback([result])`:
|
||||
|
||||
Begin the callback sequence with a non-``Error`` result. Result
|
||||
may be any value except for a :mochiref:`Deferred`.
|
||||
|
||||
Either ``.callback`` or ``.errback`` should
|
||||
be called exactly once on a :mochiref:`Deferred`.
|
||||
|
||||
|
||||
:mochidef:`Deferred.prototype.cancel()`:
|
||||
|
||||
Cancels a :mochiref:`Deferred` that has not yet received a value,
|
||||
or is waiting on another :mochiref:`Deferred` as its value.
|
||||
|
||||
If a canceller is defined, the canceller is called.
|
||||
If the canceller did not return an ``Error``, or there
|
||||
was no canceller, then the errback chain is started
|
||||
with :mochiref:`CancelledError`.
|
||||
|
||||
|
||||
:mochidef:`Deferred.prototype.errback([result])`:
|
||||
|
||||
Begin the callback sequence with an error result.
|
||||
Result may be any value except for a :mochiref:`Deferred`,
|
||||
but if ``!(result instanceof Error)``, it will be wrapped
|
||||
with :mochiref:`GenericError`.
|
||||
|
||||
Either ``.callback`` or ``.errback`` should
|
||||
be called exactly once on a :mochidef:`Deferred`.
|
||||
|
||||
|
||||
:mochidef:`DeferredLock()`:
|
||||
|
||||
A lock for asynchronous systems.
|
||||
|
||||
The ``locked`` property of a :mochiref:`DeferredLock` will be ``true`` if
|
||||
it locked, ``false`` otherwise. Do not change this property.
|
||||
|
||||
|
||||
:mochidef:`DeferredLock.prototype.acquire()`:
|
||||
|
||||
Attempt to acquire the lock. Returns a :mochiref:`Deferred` that fires on
|
||||
lock acquisition with the :mochiref:`DeferredLock` as the value.
|
||||
If the lock is locked, then the :mochiref:`Deferred` goes into a waiting
|
||||
list.
|
||||
|
||||
|
||||
:mochidef:`DeferredLock.prototype.release()`:
|
||||
|
||||
Release the lock. If there is a waiting list, then the first
|
||||
:mochiref:`Deferred` in that waiting list will be called back.
|
||||
|
||||
|
||||
:mochidef:`DeferredList(list, [fireOnOneCallback, fireOnOneErrback, consumeErrors, canceller])`:
|
||||
|
||||
Combine a list of :mochiref:`Deferred` into one. Track the callbacks and
|
||||
return a list of (success, result) tuples, 'success' being a boolean
|
||||
indicating whether result is a normal result or an error.
|
||||
|
||||
Once created, you have access to all :mochiref:`Deferred` methods, like
|
||||
addCallback, addErrback, addBoth. The behaviour can be changed by the
|
||||
following options:
|
||||
|
||||
``fireOnOneCallback``:
|
||||
Flag for launching the callback once the first Deferred of the list
|
||||
has returned.
|
||||
|
||||
``fireOnOneErrback``:
|
||||
Flag for calling the errback at the first error of a Deferred.
|
||||
|
||||
``consumeErrors``:
|
||||
Flag indicating that any errors raised in the Deferreds should be
|
||||
consumed by the DeferredList.
|
||||
|
||||
Example::
|
||||
|
||||
// We need to fetch data from 2 different urls
|
||||
var d1 = loadJSONDoc(url1);
|
||||
var d2 = loadJSONDoc(url2);
|
||||
var l1 = new DeferredList([d1, d2], false, false, true);
|
||||
l1.addCallback(function (resultList) {
|
||||
MochiKit.Base.map(function (result) {
|
||||
if (result[0]) {
|
||||
alert("Data is here: " + result[1]);
|
||||
} else {
|
||||
alert("Got an error: " + result[1]);
|
||||
}
|
||||
}, resultList);
|
||||
});
|
||||
|
||||
|
||||
Functions
|
||||
---------
|
||||
|
||||
:mochidef:`callLater(seconds, func[, args...])`:
|
||||
|
||||
Call ``func(args...)`` after at least ``seconds`` seconds have elapsed.
|
||||
This is a convenience method for::
|
||||
|
||||
func = partial.apply(extend(null, arguments, 1));
|
||||
return wait(seconds).addCallback(function (res) { return func() });
|
||||
|
||||
Returns a cancellable :mochiref:`Deferred`.
|
||||
|
||||
|
||||
:mochidef:`doSimpleXMLHttpRequest(url[, queryArguments...])`:
|
||||
|
||||
Perform a simple ``XMLHttpRequest`` and wrap it with a
|
||||
:mochiref:`Deferred` that may be cancelled.
|
||||
|
||||
Note that currently, only ``200`` (OK) and ``304``
|
||||
(NOT_MODIFIED) are considered success codes at this time, other
|
||||
status codes will result in an errback with an ``XMLHttpRequestError``.
|
||||
|
||||
``url``:
|
||||
The URL to GET
|
||||
|
||||
``queryArguments``:
|
||||
If this function is called with more than one argument, a ``"?"``
|
||||
and the result of :mochiref:`MochiKit.Base.queryString` with
|
||||
the rest of the arguments are appended to the URL.
|
||||
|
||||
For example, this will do a GET request to the URL
|
||||
``http://example.com?bar=baz``::
|
||||
|
||||
doSimpleXMLHttpRequest("http://example.com", {bar: "baz"});
|
||||
|
||||
*returns*:
|
||||
:mochiref:`Deferred` that will callback with the ``XMLHttpRequest``
|
||||
instance on success
|
||||
|
||||
|
||||
:mochidef:`evalJSONRequest(req)`:
|
||||
|
||||
Evaluate a JSON [4]_ ``XMLHttpRequest``
|
||||
|
||||
``req``:
|
||||
The request whose ``.responseText`` property is to be evaluated
|
||||
|
||||
*returns*:
|
||||
A JavaScript object
|
||||
|
||||
|
||||
:mochidef:`fail([result])`:
|
||||
|
||||
Return a :mochiref:`Deferred` that has already had ``.errback(result)``
|
||||
called.
|
||||
|
||||
See ``succeed`` documentation for rationale.
|
||||
|
||||
``result``:
|
||||
The result to give to :mochiref:`Deferred.prototype.errback(result)`.
|
||||
|
||||
*returns*:
|
||||
A ``new`` :mochiref:`Deferred()`
|
||||
|
||||
|
||||
:mochidef:`gatherResults(deferreds)`:
|
||||
|
||||
A convenience function that returns a :mochiref:`DeferredList`
|
||||
from the given ``Array`` of :mochiref:`Deferred` instances
|
||||
that will callback with an ``Array`` of just results when
|
||||
they're available, or errback on the first array.
|
||||
|
||||
|
||||
:mochidef:`getXMLHttpRequest()`:
|
||||
|
||||
Return an ``XMLHttpRequest`` compliant object for the current
|
||||
platform.
|
||||
|
||||
In order of preference:
|
||||
|
||||
- ``new XMLHttpRequest()``
|
||||
- ``new ActiveXObject('Msxml2.XMLHTTP')``
|
||||
- ``new ActiveXObject('Microsoft.XMLHTTP')``
|
||||
- ``new ActiveXObject('Msxml2.XMLHTTP.4.0')``
|
||||
|
||||
|
||||
:mochidef:`maybeDeferred(func[, argument...])`:
|
||||
|
||||
Call a ``func`` with the given arguments and ensure the result is a
|
||||
:mochiref:`Deferred`.
|
||||
|
||||
``func``:
|
||||
The function to call.
|
||||
|
||||
*returns*:
|
||||
A new :mochiref:`Deferred` based on the call to ``func``. If ``func``
|
||||
does not naturally return a :mochiref:`Deferred`, its result or error
|
||||
value will be wrapped by one.
|
||||
|
||||
|
||||
:mochidef:`loadJSONDoc(url)`:
|
||||
|
||||
Do a simple ``XMLHttpRequest`` to a URL and get the response
|
||||
as a JSON [4]_ document.
|
||||
|
||||
``url``:
|
||||
The URL to GET
|
||||
|
||||
*returns*:
|
||||
:mochiref:`Deferred` that will callback with the evaluated JSON [4]_
|
||||
response upon successful ``XMLHttpRequest``
|
||||
|
||||
|
||||
:mochidef:`sendXMLHttpRequest(req[, sendContent])`:
|
||||
|
||||
Set an ``onreadystatechange`` handler on an ``XMLHttpRequest`` object
|
||||
and send it off. Will return a cancellable :mochiref:`Deferred` that will
|
||||
callback on success.
|
||||
|
||||
Note that currently, only ``200`` (OK) and ``304``
|
||||
(NOT_MODIFIED) are considered success codes at this time, other
|
||||
status codes will result in an errback with an ``XMLHttpRequestError``.
|
||||
|
||||
``req``:
|
||||
An preconfigured ``XMLHttpRequest`` object (open has been called).
|
||||
|
||||
``sendContent``:
|
||||
Optional string or DOM content to send over the ``XMLHttpRequest``.
|
||||
|
||||
*returns*:
|
||||
:mochiref:`Deferred` that will callback with the ``XMLHttpRequest``
|
||||
instance on success.
|
||||
|
||||
|
||||
:mochidef:`succeed([result])`:
|
||||
|
||||
Return a :mochiref:`Deferred` that has already had ``.callback(result)``
|
||||
called.
|
||||
|
||||
This is useful when you're writing synchronous code to an asynchronous
|
||||
interface: i.e., some code is calling you expecting a :mochiref:`Deferred`
|
||||
result, but you don't actually need to do anything asynchronous. Just
|
||||
return ``succeed(theResult)``.
|
||||
|
||||
See ``fail`` for a version of this function that uses a failing
|
||||
:mochiref:`Deferred` rather than a successful one.
|
||||
|
||||
``result``:
|
||||
The result to give to :mochiref:`Deferred.prototype.callback(result)`
|
||||
|
||||
*returns*:
|
||||
a ``new`` :mochiref:`Deferred`
|
||||
|
||||
|
||||
:mochidef:`wait(seconds[, res])`:
|
||||
|
||||
Return a new cancellable :mochiref:`Deferred` that will ``.callback(res)``
|
||||
after at least ``seconds`` seconds have elapsed.
|
||||
|
||||
|
||||
See Also
|
||||
========
|
||||
|
||||
.. [1] AJAX, Asynchronous JavaScript and XML: http://en.wikipedia.org/wiki/AJAX
|
||||
.. [2] Twisted, an event-driven networking framework written in Python: http://twistedmatrix.com/
|
||||
.. [3] Twisted Deferred Reference: http://twistedmatrix.com/projects/core/documentation/howto/defer.html
|
||||
.. [4] JSON, JavaScript Object Notation: http://json.org/
|
||||
|
||||
|
||||
Authors
|
||||
=======
|
||||
|
||||
- Bob Ippolito <bob@redivi.com>
|
||||
|
||||
|
||||
Copyright
|
||||
=========
|
||||
|
||||
Copyright 2005 Bob Ippolito <bob@redivi.com>. This program is dual-licensed
|
||||
free software; you can redistribute it and/or modify it under the terms of the
|
||||
`MIT License`_ or the `Academic Free License v2.1`_.
|
||||
|
||||
.. _`MIT License`: http://www.opensource.org/licenses/mit-license.php
|
||||
.. _`Academic Free License v2.1`: http://www.opensource.org/licenses/afl-2.1.php
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,481 +0,0 @@
|
||||
.. title:: MochiKit.Color - color abstraction with CSS3 support
|
||||
|
||||
Name
|
||||
====
|
||||
|
||||
MochiKit.Color - color abstraction with CSS3 support
|
||||
|
||||
|
||||
Synopsis
|
||||
========
|
||||
|
||||
::
|
||||
|
||||
// RGB color expressions are supported
|
||||
assert(
|
||||
objEqual(Color.whiteColor(), Color.fromString("rgb(255,100%, 255)"))
|
||||
);
|
||||
|
||||
// So is instantiating directly from HSL or RGB values.
|
||||
// Note that fromRGB and fromHSL take numbers between 0.0 and 1.0!
|
||||
assert( objEqual(Color.fromRGB(1.0, 1.0, 1.0), Color.fromHSL(0.0, 0.0, 1.0) );
|
||||
|
||||
// Or even SVG color keyword names, as per CSS3!
|
||||
assert( Color.fromString("aquamarine"), "#7fffd4" );
|
||||
|
||||
// NSColor-like colors built in
|
||||
assert( Color.whiteColor().toHexString() == "#ffffff" );
|
||||
|
||||
|
||||
Description
|
||||
===========
|
||||
|
||||
MochiKit.Color is an abstraction for handling colors and strings that
|
||||
represent colors.
|
||||
|
||||
|
||||
Dependencies
|
||||
============
|
||||
|
||||
- :mochiref:`MochiKit.Base`
|
||||
|
||||
|
||||
Overview
|
||||
========
|
||||
|
||||
MochiKit.Color provides an abstraction of RGB, HSL and HSV colors with alpha.
|
||||
It supports parsing and generating of CSS3 colors, and has a full CSS3 (SVG)
|
||||
color table.
|
||||
|
||||
All of the functionality in this module is exposed through a Color constructor
|
||||
and its prototype, but a few of its internals are available for direct use at
|
||||
module level.
|
||||
|
||||
|
||||
API Reference
|
||||
=============
|
||||
|
||||
Constructors
|
||||
------------
|
||||
|
||||
:mochidef:`Color()`:
|
||||
|
||||
Represents a color. Component values should be integers between ``0.0``
|
||||
and ``1.0``. You should use one of the :mochiref:`Color` factory
|
||||
functions such as :mochiref:`Color.fromRGB`, :mochiref:`Color.fromHSL`,
|
||||
etc. instead of constructing :mochiref:`Color` objects directly.
|
||||
|
||||
:mochiref:`Color` instances can be compared with
|
||||
:mochiref:`MochiKit.Base.compare` (though ordering is on RGB, so is not
|
||||
particularly meaningful except for equality), and the default ``toString``
|
||||
implementation returns :mochiref:`Color.prototype.toHexString()`.
|
||||
|
||||
:mochiref:`Color` instances are immutable, and much of the architecture is
|
||||
inspired by AppKit's NSColor [1]_
|
||||
|
||||
|
||||
:mochidef:`Color.fromBackground(elem)`:
|
||||
|
||||
Returns a :mochiref:`Color` object based on the background of the provided
|
||||
element. Equivalent to::
|
||||
|
||||
c = Color.fromComputedStyle(
|
||||
elem, "backgroundColor", "background-color") || Color.whiteColor();
|
||||
|
||||
|
||||
:mochidef:`Color.fromComputedStyle(elem, style, mozillaEquivalentCSS)`:
|
||||
|
||||
Returns a :mochiref:`Color` object based on the result of
|
||||
:mochiref:`MochiKit.DOM.computedStyle(elem, style, mozillaEquivalentCSS)`
|
||||
or ``null`` if not found.
|
||||
|
||||
|
||||
:mochidef:`Color.fromHexString(hexString)`:
|
||||
|
||||
Returns a :mochiref:`Color` object from the given hexadecimal color string.
|
||||
For example, ``"#FFFFFF"`` would return a :mochiref:`Color` with
|
||||
RGB values ``[255/255, 255/255, 255/255]`` (white).
|
||||
|
||||
|
||||
:mochidef:`Color.fromHSL(hue, saturation, lightness, alpha=1.0)`:
|
||||
|
||||
Return a :mochiref:`Color` object from the given ``hue``, ``saturation``,
|
||||
``lightness`` values. Values should be numbers between ``0.0`` and
|
||||
``1.0``.
|
||||
|
||||
If ``alpha`` is not given, then ``1.0`` (completely opaque) will be used.
|
||||
|
||||
Alternate form:
|
||||
:mochiref:`Color.fromHSL({h: hue, s: saturation, l: lightness, a: alpha})`
|
||||
|
||||
|
||||
:mochidef:`Color.fromHSLString(hslString)`:
|
||||
|
||||
Returns a :mochiref:`Color` object from the given decimal hsl color string.
|
||||
For example, ``"hsl(0,0%,100%)"`` would return a :mochiref:`Color` with
|
||||
HSL values ``[0/360, 0/360, 360/360]`` (white).
|
||||
|
||||
|
||||
:mochidef:`Color.fromHSV(hue, saturation, value, alpha=1.0)`:
|
||||
|
||||
Return a :mochiref:`Color` object from the given ``hue``, ``saturation``,
|
||||
``value`` values. Values should be numbers between ``0.0`` and
|
||||
``1.0``.
|
||||
|
||||
If ``alpha`` is not given, then ``1.0`` (completely opaque) will be used.
|
||||
|
||||
Alternate form:
|
||||
:mochiref:`Color.fromHSV({h: hue, s: saturation, v: value, a: alpha})`
|
||||
|
||||
|
||||
:mochidef:`Color.fromName(colorName)`:
|
||||
|
||||
Returns a :mochiref:`Color` object corresponding to the given
|
||||
SVG 1.0 color keyword name [2]_ as per the W3C CSS3
|
||||
Color Module [3]_. ``"transparent"`` is also accepted
|
||||
as a color name, and will return :mochiref:`Color.transparentColor()`.
|
||||
|
||||
|
||||
:mochidef:`Color.fromRGB(red, green, blue, alpha=1.0)`:
|
||||
|
||||
Return a :mochiref:`Color` object from the given ``red``, ``green``,
|
||||
``blue``, and ``alpha`` values. Values should be numbers between ``0``
|
||||
and ``1.0``.
|
||||
|
||||
If ``alpha`` is not given, then ``1.0`` (completely opaque) will be used.
|
||||
|
||||
Alternate form:
|
||||
:mochiref:`Color.fromRGB({r: red, g: green, b: blue, a: alpha})`
|
||||
|
||||
|
||||
:mochidef:`Color.fromRGBString(rgbString)`:
|
||||
|
||||
Returns a :mochiref:`Color` object from the given decimal rgb color string.
|
||||
For example, ``"rgb(255,255,255)"`` would return a :mochiref:`Color` with
|
||||
RGB values ``[255/255, 255/255, 255/255]`` (white).
|
||||
|
||||
|
||||
:mochidef:`Color.fromText(elem)`:
|
||||
|
||||
Returns a :mochiref:`Color` object based on the text color of the provided
|
||||
element. Equivalent to::
|
||||
|
||||
c = Color.fromComputedStyle(elem, "color") || Color.whiteColor();
|
||||
|
||||
|
||||
:mochidef:`Color.fromString(rgbOrHexString)`:
|
||||
|
||||
Returns a :mochiref:`Color` object from the given RGB, HSL, hex, or name.
|
||||
Will return ``null`` if the string can not be parsed by any of these
|
||||
methods.
|
||||
|
||||
See :mochiref:`Color.fromHexString`, :mochiref:`Color.fromRGBString`,
|
||||
:mochiref:`Color.fromHSLString` and :mochiref:`Color.fromName` more
|
||||
information.
|
||||
|
||||
|
||||
:mochidef:`Color.namedColors()`:
|
||||
|
||||
Returns an object with properties for each SVG 1.0 color keyword
|
||||
name [2]_ supported by CSS3 [3]_. Property names are the color keyword
|
||||
name in lowercase, and the value is a string suitable for
|
||||
:mochiref:`Color.fromString()`.
|
||||
|
||||
|
||||
:mochidef:`Color.prototype.colorWithAlpha(alpha)`:
|
||||
|
||||
Return a new :mochiref:`Color` based on this color, but with the provided
|
||||
``alpha`` value.
|
||||
|
||||
|
||||
:mochidef:`Color.prototype.colorWithHue(hue)`:
|
||||
|
||||
Return a new :mochiref:`Color` based on this color, but with the provided
|
||||
``hue`` value.
|
||||
|
||||
|
||||
:mochidef:`Color.prototype.colorWithSaturation(saturation)`:
|
||||
|
||||
Return a new :mochiref:`Color` based on this color, but with the provided
|
||||
``saturation`` value (using the HSL color model).
|
||||
|
||||
|
||||
:mochidef:`Color.prototype.colorWithLightness(lightness)`:
|
||||
|
||||
Return a new :mochiref:`Color` based on this color, but with the provided
|
||||
``lightness`` value.
|
||||
|
||||
|
||||
:mochidef:`Color.prototype.darkerColorWithLevel(level)`:
|
||||
|
||||
Return a new :mochiref:`Color` based on this color, but darker by the given
|
||||
``level`` (between ``0`` and ``1.0``).
|
||||
|
||||
|
||||
:mochidef:`Color.prototype.lighterColorWithLevel(level)`:
|
||||
|
||||
Return a new :mochiref:`Color` based on this color, but lighter by the given
|
||||
``level`` (between ``0`` and ``1.0``).
|
||||
|
||||
|
||||
:mochidef:`Color.prototype.blendedColor(other, fraction=0.5)`:
|
||||
|
||||
Return a new :mochiref:`Color` whose RGBA component values are a weighted sum
|
||||
of this color and ``other``. Each component of the returned color
|
||||
is the ``fraction`` of other's value plus ``1 - fraction`` of this
|
||||
color's.
|
||||
|
||||
|
||||
:mochidef:`Color.prototype.isLight()`:
|
||||
|
||||
Return ``true`` if the lightness value of this color is greater than
|
||||
``0.5``.
|
||||
|
||||
Note that ``alpha`` is ignored for this calculation (color components
|
||||
are not premultiplied).
|
||||
|
||||
|
||||
:mochidef:`Color.prototype.isDark()`:
|
||||
|
||||
Return ``true`` if the lightness value of this color is less than or
|
||||
equal to ``0.5``.
|
||||
|
||||
Note that ``alpha`` is ignored for this calculation (color components
|
||||
are not premultiplied).
|
||||
|
||||
|
||||
:mochidef:`Color.prototype.toRGBString()`:
|
||||
|
||||
Return the decimal ``"rgb(red, green, blue)"`` string representation of this
|
||||
color.
|
||||
|
||||
If the alpha component is not ``1.0`` (fully opaque), the
|
||||
``"rgba(red, green, blue, alpha)"`` string representation will be used.
|
||||
|
||||
For example::
|
||||
|
||||
assert( Color.whiteColor().toRGBString() == "rgb(255,255,255)" );
|
||||
|
||||
|
||||
:mochidef:`Color.prototype.toHSLString()`:
|
||||
|
||||
Return the decimal ``"hsl(hue, saturation, lightness)"``
|
||||
string representation of this color.
|
||||
|
||||
If the alpha component is not ``1.0`` (fully opaque), the
|
||||
``"hsla(hue, saturation, lightness, alpha)"`` string representation
|
||||
will be used.
|
||||
|
||||
For example::
|
||||
|
||||
assert( Color.whiteColor().toHSLString() == "hsl(0,0,360)" );
|
||||
|
||||
|
||||
:mochidef:`Color.prototype.toHexString()`:
|
||||
|
||||
Return the hexadecimal ``"#RRGGBB"`` string representation of this color.
|
||||
|
||||
Note that the alpha component is completely ignored for hexadecimal
|
||||
string representations!
|
||||
|
||||
For example::
|
||||
|
||||
assert( Color.whiteColor().toHexString() == "#FFFFFF" );
|
||||
|
||||
|
||||
:mochidef:`Color.prototype.asRGB()`:
|
||||
|
||||
Return the RGB (red, green, blue, alpha) components of this color as an
|
||||
object with ``r``, ``g``, ``b``, and ``a`` properties that have
|
||||
values between ``0.0`` and ``1.0``.
|
||||
|
||||
|
||||
:mochidef:`Color.prototype.asHSL()`:
|
||||
|
||||
Return the HSL (hue, saturation, lightness, alpha) components of this
|
||||
color as an object with ``h``, ``s``, ``l`` and ``a`` properties
|
||||
that have values between ``0.0`` and ``1.0``.
|
||||
|
||||
|
||||
:mochidef:`Color.prototype.asHSV()`:
|
||||
|
||||
Return the HSV (hue, saturation, value, alpha) components of this
|
||||
color as an object with ``h``, ``s``, ``v`` and ``a`` properties
|
||||
that have values between ``0.0`` and ``1.0``.
|
||||
|
||||
|
||||
:mochidef:`Color.blackColor()`:
|
||||
|
||||
Return a :mochiref:`Color` object whose RGB values are 0, 0, 0
|
||||
(#000000).
|
||||
|
||||
|
||||
:mochidef:`Color.blueColor()`:
|
||||
|
||||
Return a :mochiref:`Color` object whose RGB values are 0, 0, 1
|
||||
(#0000ff).
|
||||
|
||||
|
||||
:mochidef:`Color.brownColor()`:
|
||||
|
||||
Return a :mochiref:`Color` object whose RGB values are 0.6, 0.4, 0.2
|
||||
(#996633).
|
||||
|
||||
|
||||
:mochidef:`Color.cyanColor()`:
|
||||
|
||||
Return a :mochiref:`Color` object whose RGB values are 0, 1, 1
|
||||
(#00ffff).
|
||||
|
||||
|
||||
:mochidef:`Color.darkGrayColor()`:
|
||||
|
||||
Return a :mochiref:`Color` object whose RGB values are 1/3, 1/3, 1/3
|
||||
(#555555).
|
||||
|
||||
|
||||
:mochidef:`Color.grayColor()`:
|
||||
|
||||
Return a :mochiref:`Color` object whose RGB values are 0.5, 0.5, 0.5
|
||||
(#808080).
|
||||
|
||||
|
||||
:mochidef:`Color.greenColor()`:
|
||||
|
||||
Return a :mochiref:`Color` object whose RGB values are 0, 1, 0.
|
||||
(#00ff00).
|
||||
|
||||
|
||||
:mochidef:`Color.lightGrayColor()`:
|
||||
|
||||
Return a :mochiref:`Color` object whose RGB values are 2/3, 2/3, 2/3
|
||||
(#aaaaaa).
|
||||
|
||||
|
||||
:mochidef:`Color.magentaColor()`:
|
||||
|
||||
Return a :mochiref:`Color` object whose RGB values are 1, 0, 1
|
||||
(#ff00ff).
|
||||
|
||||
|
||||
:mochidef:`Color.orangeColor()`:
|
||||
|
||||
Return a :mochiref:`Color` object whose RGB values are 1, 0.5, 0
|
||||
(#ff8000).
|
||||
|
||||
|
||||
:mochidef:`Color.purpleColor()`:
|
||||
|
||||
Return a :mochiref:`Color` object whose RGB values are 0.5, 0, 0.5
|
||||
(#800080).
|
||||
|
||||
|
||||
:mochidef:`Color.redColor()`:
|
||||
|
||||
Return a :mochiref:`Color` object whose RGB values are 1, 0, 0
|
||||
(#ff0000).
|
||||
|
||||
|
||||
:mochidef:`Color.whiteColor()`:
|
||||
|
||||
Return a :mochiref:`Color` object whose RGB values are 1, 1, 1
|
||||
(#ffffff).
|
||||
|
||||
|
||||
:mochidef:`Color.yellowColor()`:
|
||||
|
||||
Return a :mochiref:`Color` object whose RGB values are 1, 1, 0
|
||||
(#ffff00).
|
||||
|
||||
|
||||
:mochidef:`Color.transparentColor()`:
|
||||
|
||||
Return a :mochiref:`Color` object that is completely transparent
|
||||
(has alpha component of 0).
|
||||
|
||||
|
||||
Functions
|
||||
---------
|
||||
|
||||
:mochidef:`clampColorComponent(num, scale)`:
|
||||
|
||||
Returns ``num * scale`` clamped between ``0`` and ``scale``.
|
||||
|
||||
:mochiref:`clampColorComponent` is not exported by default when using JSAN.
|
||||
|
||||
|
||||
:mochidef:`hslToRGB(hue, saturation, lightness, alpha)`:
|
||||
|
||||
Computes RGB values from the provided HSL values. The return value is a
|
||||
mapping with ``"r"``, ``"g"``, ``"b"`` and ``"a"`` keys.
|
||||
|
||||
Alternate form:
|
||||
:mochiref:`hslToRGB({h: hue, s: saturation, l: lightness, a: alpha})`.
|
||||
|
||||
:mochiref:`hslToRGB` is not exported by default when using JSAN.
|
||||
|
||||
|
||||
:mochidef:`hsvToRGB(hue, saturation, value, alpha)`:
|
||||
|
||||
Computes RGB values from the provided HSV values. The return value is a
|
||||
mapping with ``"r"``, ``"g"``, ``"b"`` and ``"a"`` keys.
|
||||
|
||||
Alternate form:
|
||||
:mochiref:`hsvToRGB({h: hue, s: saturation, v: value, a: alpha})`.
|
||||
|
||||
:mochiref:`hsvToRGB` is not exported by default when using JSAN.
|
||||
|
||||
|
||||
:mochidef:`toColorPart(num)`:
|
||||
|
||||
Convert num to a zero padded hexadecimal digit for use in a hexadecimal
|
||||
color string. Num should be an integer between ``0`` and ``255``.
|
||||
|
||||
:mochiref:`toColorPart` is not exported by default when using JSAN.
|
||||
|
||||
|
||||
:mochidef:`rgbToHSL(red, green, blue, alpha)`:
|
||||
|
||||
Computes HSL values based on the provided RGB values. The return value is
|
||||
a mapping with ``"h"``, ``"s"``, ``"l"`` and ``"a"`` keys.
|
||||
|
||||
Alternate form:
|
||||
:mochiref:`rgbToHSL({r: red, g: green, b: blue, a: alpha})`.
|
||||
|
||||
:mochiref:`rgbToHSL` is not exported by default when using JSAN.
|
||||
|
||||
|
||||
:mochidef:`rgbToHSV(red, green, blue, alpha)`:
|
||||
|
||||
Computes HSV values based on the provided RGB values. The return value is
|
||||
a mapping with ``"h"``, ``"s"``, ``"v"`` and ``"a"`` keys.
|
||||
|
||||
Alternate form:
|
||||
:mochiref:`rgbToHSV({r: red, g: green, b: blue, a: alpha})`.
|
||||
|
||||
:mochiref:`rgbToHSV` is not exported by default when using JSAN.
|
||||
|
||||
|
||||
See Also
|
||||
========
|
||||
|
||||
.. [1] Application Kit Reference - NSColor: http://developer.apple.com/documentation/Cocoa/Reference/ApplicationKit/ObjC_classic/Classes/NSColor.html
|
||||
.. [2] SVG 1.0 color keywords: http://www.w3.org/TR/SVG/types.html#ColorKeywords
|
||||
.. [3] W3C CSS3 Color Module: http://www.w3.org/TR/css3-color/#svg-color
|
||||
|
||||
|
||||
Authors
|
||||
=======
|
||||
|
||||
- Bob Ippolito <bob@redivi.com>
|
||||
|
||||
|
||||
Copyright
|
||||
=========
|
||||
|
||||
Copyright 2005 Bob Ippolito <bob@redivi.com>. This program is dual-licensed
|
||||
free software; you can redistribute it and/or modify it under the terms of the
|
||||
`MIT License`_ or the `Academic Free License v2.1`_.
|
||||
|
||||
.. _`MIT License`: http://www.opensource.org/licenses/mit-license.php
|
||||
.. _`Academic Free License v2.1`: http://www.opensource.org/licenses/afl-2.1.php
|
||||
@@ -1,782 +0,0 @@
|
||||
.. title:: MochiKit.DOM - painless DOM manipulation API
|
||||
|
||||
Name
|
||||
====
|
||||
|
||||
MochiKit.DOM - painless DOM manipulation API
|
||||
|
||||
|
||||
Synopsis
|
||||
========
|
||||
|
||||
::
|
||||
|
||||
var rows = [
|
||||
["dataA1", "dataA2", "dataA3"],
|
||||
["dataB1", "dataB2", "dataB3"]
|
||||
];
|
||||
row_display = function (row) {
|
||||
return TR(null, map(partial(TD, null), row));
|
||||
}
|
||||
var newTable = TABLE({'class': 'prettytable'},
|
||||
THEAD(null,
|
||||
row_display(["head1", "head2", "head3"])),
|
||||
TFOOT(null,
|
||||
row_display(["foot1", "foot2", "foot3"])),
|
||||
TBODY(null,
|
||||
map(row_display, rows)));
|
||||
// put that in your document.createElement and smoke it!
|
||||
swapDOM(oldTable, newTable);
|
||||
|
||||
|
||||
Description
|
||||
===========
|
||||
|
||||
As you probably know, the DOM APIs are some of the most painful Java-inspired
|
||||
APIs you'll run across from a highly dynamic language. Don't worry about that
|
||||
though, because they provide a reasonable basis to build something that
|
||||
sucks a lot less.
|
||||
|
||||
MochiKit.DOM takes much of its inspiration from Nevow's [1]_ stan [2]_.
|
||||
This means you choose a tag, give it some attributes, then stuff it full
|
||||
of *whatever objects you want*. MochiKit.DOM isn't stupid, it knows that
|
||||
a string should be a text node, and that you want functions to be called,
|
||||
and that ``Array``-like objects should be expanded, and stupid ``null`` values
|
||||
should be skipped.
|
||||
|
||||
Hell, it will let you return strings from functions, and use iterators from
|
||||
:mochiref:`MochiKit.Iter`. If that's not enough, just teach it new tricks with
|
||||
:mochiref:`registerDOMConverter`. If you have never used an API like this for
|
||||
creating DOM elements, you've been wasting your damn time. Get with it!
|
||||
|
||||
|
||||
Dependencies
|
||||
============
|
||||
|
||||
- :mochiref:`MochiKit.Base`
|
||||
- :mochiref:`MochiKit.Iter`
|
||||
|
||||
|
||||
Overview
|
||||
========
|
||||
|
||||
DOM Coercion Rules
|
||||
------------------
|
||||
|
||||
In order of precedence, :mochiref:`createDOM` coerces given arguments to DOM
|
||||
nodes using the following rules:
|
||||
|
||||
1. Functions are called with a ``this`` of the parent
|
||||
node and their return value is subject to the
|
||||
following rules (even this one).
|
||||
2. ``undefined`` and ``null`` are ignored.
|
||||
3. Iterables (see :mochiref:`MochiKit.Iter`) are flattened
|
||||
(as if they were passed in-line as nodes) and each
|
||||
return value is subject to all of these rules.
|
||||
4. Values that look like DOM nodes (objects with a
|
||||
``.nodeType > 0``) are ``.appendChild``'ed to the created
|
||||
DOM fragment.
|
||||
5. Strings are wrapped up with ``document.createTextNode``
|
||||
6. Objects that are not strings are run through the ``domConverters``
|
||||
:mochiref:`MochiKit.Base.AdapterRegistry`
|
||||
(see :mochiref:`registerDOMConverter`).
|
||||
The value returned by the adapter is subject to these same rules (e.g.
|
||||
adapters are allowed to return a string, which will be coerced into a
|
||||
text node).
|
||||
7. If no adapter is available, ``.toString()`` is used to create a text node.
|
||||
|
||||
|
||||
Creating DOM Element Trees
|
||||
--------------------------
|
||||
|
||||
:mochiref:`createDOM` provides you with an excellent facility for creating DOM trees
|
||||
that is easy on the wrists. One of the best ways to understand how to use
|
||||
it is to take a look at an example::
|
||||
|
||||
var rows = [
|
||||
["dataA1", "dataA2", "dataA3"],
|
||||
["dataB1", "dataB2", "dataB3"]
|
||||
];
|
||||
row_display = function (row) {
|
||||
return TR(null, map(partial(TD, null), row));
|
||||
}
|
||||
var newTable = TABLE({'class': 'prettytable'},
|
||||
THEAD(null,
|
||||
row_display(["head1", "head2", "head3"])),
|
||||
TFOOT(null,
|
||||
row_display(["foot1", "foot2", "foot3"])),
|
||||
TBODY(null,
|
||||
map(row_display, rows)));
|
||||
|
||||
|
||||
This will create a table with the following visual layout (if it
|
||||
were inserted into the document DOM):
|
||||
|
||||
+--------+--------+--------+
|
||||
| head1 | head2 | head3 |
|
||||
+========+========+========+
|
||||
| dataA1 | dataA2 | dataA3 |
|
||||
+--------+--------+--------+
|
||||
| dataB1 | dataB2 | dataB3 |
|
||||
+--------+--------+--------+
|
||||
| foot1 | foot2 | foot3 |
|
||||
+--------+--------+--------+
|
||||
|
||||
Corresponding to the following HTML::
|
||||
|
||||
<table class="prettytable">
|
||||
<thead>
|
||||
<tr>
|
||||
<td>head1</td>
|
||||
<td>head2</td>
|
||||
<td>head3</td>
|
||||
</tr>
|
||||
</thead>
|
||||
<tfoot>
|
||||
<tr>
|
||||
<td>foot1</td>
|
||||
<td>foot2</td>
|
||||
<td>foot3</td>
|
||||
</tr>
|
||||
</tfoot>
|
||||
<tbody>
|
||||
<tr>
|
||||
<td>dataA1</td>
|
||||
<td>dataA2</td>
|
||||
<td>dataA3</td>
|
||||
</tr>
|
||||
<tr>
|
||||
<td>dataB1</td>
|
||||
<td>dataB2</td>
|
||||
<td>dataB3</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
|
||||
|
||||
DOM Context
|
||||
-----------
|
||||
|
||||
In order to prevent having to pass a ``window`` and/or ``document``
|
||||
variable to every MochiKit.DOM function (e.g. when working with a
|
||||
child window), MochiKit.DOM maintains a context variable for each
|
||||
of them. They are managed with the :mochiref:`withWindow` and
|
||||
:mochiref:`withDocument` functions, and can be acquired with
|
||||
:mochiref:`currentWindow()` and :mochiref:`currentDocument()`
|
||||
|
||||
For example, if you are creating DOM nodes in a child window, you
|
||||
could do something like this::
|
||||
|
||||
withWindow(child, function () {
|
||||
var doc = currentDocument();
|
||||
appendChildNodes(doc.body, H1(null, "This is in the child!"));
|
||||
});
|
||||
|
||||
Note that :mochiref:`withWindow(win, ...)` also implies
|
||||
:mochiref:`withDocument(win.document, ...)`.
|
||||
|
||||
|
||||
Element Visibility
|
||||
------------------
|
||||
|
||||
The :mochiref:`hideElement` and :mochiref:`showElement` functions are
|
||||
provided as a convenience, but only work for elements that are
|
||||
``display: block``. For a general solution to showing, hiding, and checking
|
||||
the explicit visibility of elements, we recommend using a solution that
|
||||
involves a little CSS. Here's an example::
|
||||
|
||||
<style type="text/css">
|
||||
.invisible { display: none; }
|
||||
</style>
|
||||
|
||||
<script type="text/javascript">
|
||||
function toggleVisible(elem) {
|
||||
toggleElementClass("invisible", elem);
|
||||
}
|
||||
|
||||
function makeVisible(elem) {
|
||||
removeElementClass(elem, "invisible");
|
||||
}
|
||||
|
||||
function makeInvisible(elem) {
|
||||
addElementClass(elem, "invisible");
|
||||
}
|
||||
|
||||
function isVisible(elem) {
|
||||
// you may also want to check for
|
||||
// getElement(elem).style.display == "none"
|
||||
return !hasElementClass(elem, "invisible");
|
||||
};
|
||||
</script>
|
||||
|
||||
MochiKit doesn't ship with such a solution, because there is no reliable and
|
||||
portable method for adding CSS rules on the fly with JavaScript.
|
||||
|
||||
|
||||
API Reference
|
||||
=============
|
||||
|
||||
Functions
|
||||
---------
|
||||
|
||||
:mochidef:`$(id[, ...])`:
|
||||
|
||||
An alias for :mochiref:`getElement(id[, ...])`
|
||||
|
||||
|
||||
:mochidef:`addElementClass(element, className)`:
|
||||
|
||||
Ensure that the given ``element`` has ``className`` set as part of its
|
||||
class attribute. This will not disturb other class names.
|
||||
``element`` is looked up with :mochiref:`getElement`, so string identifiers
|
||||
are also acceptable.
|
||||
|
||||
|
||||
:mochidef:`addLoadEvent(func)`:
|
||||
|
||||
Note that :mochiref:`addLoadEvent` can not be used in combination with
|
||||
:mochiref:`MochiKit.Signal` if the ``onload`` event is connected.
|
||||
Once an event is connected with :mochiref:`MochiKit.Signal`, no other APIs
|
||||
may be used for that same event.
|
||||
|
||||
This will stack ``window.onload`` functions on top of each other.
|
||||
Each function added will be called after ``onload`` in the
|
||||
order that they were added.
|
||||
|
||||
|
||||
:mochidef:`addToCallStack(target, path, func[, once])`:
|
||||
|
||||
Note that :mochiref:`addToCallStack` is not compatible with
|
||||
:mochiref:`MochiKit.Signal`. Once an event is connected with
|
||||
:mochiref:`MochiKit.Signal`, no other APIs may be used for that same event.
|
||||
|
||||
Set the property ``path`` of ``target`` to a function that calls the
|
||||
existing function at that property (if any), then calls ``func``.
|
||||
|
||||
If ``target[path]()`` returns exactly ``false``, then ``func`` will
|
||||
not be called.
|
||||
|
||||
If ``once`` is ``true``, then ``target[path]`` is set to ``null`` after
|
||||
the function call stack has completed.
|
||||
|
||||
If called several times for the same ``target[path]``, it will create
|
||||
a stack of functions (instead of just a pair).
|
||||
|
||||
|
||||
:mochidef:`appendChildNodes(node[, childNode[, ...]])`:
|
||||
|
||||
Append children to a DOM element using the `DOM Coercion Rules`_.
|
||||
|
||||
``node``:
|
||||
A reference to the DOM element to add children to
|
||||
(if a string is given, :mochiref:`getElement(node)`
|
||||
will be used to locate the node)
|
||||
|
||||
``childNode``...:
|
||||
All additional arguments, if any, will be coerced into DOM
|
||||
nodes that are appended as children using the
|
||||
`DOM Coercion Rules`_.
|
||||
|
||||
*returns*:
|
||||
The given DOM element
|
||||
|
||||
|
||||
:mochidef:`computedStyle(htmlElement, cssProperty, mozillaEquivalentCSS)`:
|
||||
|
||||
Looks up a CSS property for the given element. The element can be
|
||||
specified as either a string with the element's ID or the element
|
||||
object itself.
|
||||
|
||||
|
||||
:mochidef:`createDOM(name[, attrs[, node[, ...]]])`:
|
||||
|
||||
Create a DOM fragment in a really convenient manner, much like
|
||||
Nevow`s [1]_ stan [2]_.
|
||||
|
||||
Partially applied versions of this function for common tags are
|
||||
available as aliases:
|
||||
|
||||
- ``A``
|
||||
- ``BUTTON``
|
||||
- ``BR``
|
||||
- ``CANVAS``
|
||||
- ``DIV``
|
||||
- ``FIELDSET``
|
||||
- ``FORM``
|
||||
- ``H1``
|
||||
- ``H2``
|
||||
- ``H3``
|
||||
- ``HR``
|
||||
- ``IMG``
|
||||
- ``INPUT``
|
||||
- ``LABEL``
|
||||
- ``LEGEND``
|
||||
- ``LI``
|
||||
- ``OL``
|
||||
- ``OPTGROUP``
|
||||
- ``OPTION``
|
||||
- ``P``
|
||||
- ``PRE``
|
||||
- ``SELECT``
|
||||
- ``SPAN``
|
||||
- ``STRONG``
|
||||
- ``TABLE``
|
||||
- ``TBODY``
|
||||
- ``TD``
|
||||
- ``TEXTAREA``
|
||||
- ``TFOOT``
|
||||
- ``TH``
|
||||
- ``THEAD``
|
||||
- ``TR``
|
||||
- ``TT``
|
||||
- ``UL``
|
||||
|
||||
See `Creating DOM Element Trees`_ for a comprehensive example.
|
||||
|
||||
``name``:
|
||||
The kind of fragment to create (e.g. 'span'), such as you would
|
||||
pass to ``document.createElement``.
|
||||
|
||||
``attrs``:
|
||||
An object whose properties will be used as the attributes
|
||||
(e.g. ``{'style': 'display:block'}``), or ``null`` if no
|
||||
attributes need to be set.
|
||||
|
||||
See :mochiref:`updateNodeAttributes` for more information.
|
||||
|
||||
For convenience, if ``attrs`` is a string, ``null`` is used
|
||||
and the string will be considered the first ``node``.
|
||||
|
||||
``node``...:
|
||||
All additional arguments, if any, will be coerced into DOM
|
||||
nodes that are appended as children using the
|
||||
`DOM Coercion Rules`_.
|
||||
|
||||
*returns*:
|
||||
A DOM element
|
||||
|
||||
|
||||
:mochidef:`createDOMFunc(tag[, attrs[, node[, ...]]])`:
|
||||
|
||||
Convenience function to create a partially applied createDOM
|
||||
function. You'd want to use this if you add additional convenience
|
||||
functions for creating tags, or if you find yourself creating
|
||||
a lot of tags with a bunch of the same attributes or contents.
|
||||
|
||||
See :mochiref:`createDOM` for more detailed descriptions of the arguments.
|
||||
|
||||
``tag``:
|
||||
The name of the tag
|
||||
|
||||
``attrs``:
|
||||
Optionally specify the attributes to apply
|
||||
|
||||
``node``...:
|
||||
Optionally specify any children nodes it should have
|
||||
|
||||
*returns*:
|
||||
function that takes additional arguments and calls
|
||||
:mochiref:`createDOM`
|
||||
|
||||
|
||||
:mochidef:`currentDocument()`:
|
||||
|
||||
Return the current ``document`` `DOM Context`_. This will always
|
||||
be the same as the global ``document`` unless :mochiref:`withDocument` or
|
||||
:mochiref:`withWindow` is currently executing.
|
||||
|
||||
|
||||
:mochidef:`currentWindow()`:
|
||||
|
||||
Return the current ``window`` `DOM Context`_. This will always
|
||||
be the same as the global ``window`` unless :mochiref:`withWindow` is
|
||||
currently executing.
|
||||
|
||||
|
||||
:mochidef:`elementDimensions(element)`:
|
||||
|
||||
Return the absolute pixel width and height of ``element`` as an object with
|
||||
``w`` and ``h`` properties, or ``undefined`` if ``element`` is not in the
|
||||
document. ``element`` may be specified as a string to be looked up with
|
||||
:mochiref:`getElement`, a DOM element, or trivially as an object with
|
||||
``w`` and/or ``h`` properties.
|
||||
|
||||
|
||||
:mochidef:`elementPosition(element[, relativeTo={x: 0, y: 0}])`:
|
||||
|
||||
Return the absolute pixel position of ``element`` in the document as an
|
||||
object with ``x`` and ``y`` properties, or ``undefined`` if ``element``
|
||||
is not in the document. ``element`` may be specified as a string to
|
||||
be looked up with :mochiref:`getElement`, a DOM element, or trivially
|
||||
as an object with ``x`` and/or ``y`` properties.
|
||||
|
||||
If ``relativeTo`` is given, then its coordinates are subtracted from
|
||||
the absolute position of ``element``, e.g.::
|
||||
|
||||
var elemPos = elementPosition(elem);
|
||||
var anotherElemPos = elementPosition(anotherElem);
|
||||
var relPos = elementPosition(elem, anotherElem);
|
||||
assert( relPos.x == (elemPos.x - anotherElemPos.x) );
|
||||
assert( relPos.y == (elemPos.y - anotherElemPos.y) );
|
||||
|
||||
``relativeTo`` may be specified as a string to be looked up with
|
||||
:mochiref:`getElement`, a DOM element, or trivially as an object
|
||||
with ``x`` and/or ``y`` properties.
|
||||
|
||||
|
||||
:mochidef:`emitHTML(dom[, lst])`:
|
||||
|
||||
Convert a DOM tree to an ``Array`` of HTML string fragments
|
||||
|
||||
You probably want to use :mochiref:`toHTML` instead.
|
||||
|
||||
|
||||
:mochidef:`escapeHTML(s)`:
|
||||
|
||||
Make a string safe for HTML, converting the usual suspects (lt,
|
||||
gt, quot, apos, amp)
|
||||
|
||||
|
||||
:mochidef:`focusOnLoad(element)`:
|
||||
|
||||
Add an onload event to focus the given element
|
||||
|
||||
|
||||
:mochidef:`formContents(elem)`:
|
||||
|
||||
Search the DOM tree, starting at ``elem``, for any elements with a
|
||||
``name`` and ``value`` attribute. Return a 2-element ``Array`` of
|
||||
``names`` and ``values`` suitable for use with
|
||||
:mochiref:`MochiKit.Base.queryString`.
|
||||
|
||||
|
||||
:mochidef:`getElement(id[, ...])`:
|
||||
|
||||
A small quick little function to encapsulate the ``getElementById``
|
||||
method. It includes a check to ensure we can use that method.
|
||||
|
||||
If the id isn't a string, it will be returned as-is.
|
||||
|
||||
Also available as :mochiref:`$(...)` for convenience and compatibility with
|
||||
other JavaScript frameworks.
|
||||
|
||||
If multiple arguments are given, an ``Array`` will be returned.
|
||||
|
||||
|
||||
:mochidef:`getElementsByTagAndClassName(tagName, className, parent=document)`:
|
||||
|
||||
Returns an array of elements in ``parent`` that match the tag name
|
||||
and class name provided. If ``parent`` is a string, it will be looked
|
||||
up with :mochiref:`getElement`.
|
||||
|
||||
If ``tagName`` is ``null`` or ``"*"``, all elements will be searched
|
||||
for the matching class.
|
||||
|
||||
If ``className`` is ``null``, all elements matching the provided tag are
|
||||
returned.
|
||||
|
||||
|
||||
:mochidef:`getNodeAttribute(node, attr)`:
|
||||
|
||||
Get the value of the given attribute for a DOM element without
|
||||
ever raising an exception (will return ``null`` on exception).
|
||||
|
||||
``node``:
|
||||
A reference to the DOM element to update (if a string is given,
|
||||
:mochiref:`getElement(node)` will be used to locate the node)
|
||||
|
||||
``attr``:
|
||||
The name of the attribute
|
||||
|
||||
Note that it will do the right thing for IE, so don't do
|
||||
the ``class`` -> ``className`` hack yourself.
|
||||
|
||||
*returns*:
|
||||
The attribute's value, or ``null``
|
||||
|
||||
|
||||
:mochidef:`getViewportDimensions()`:
|
||||
|
||||
Return the pixel width and height of the viewport as an object with ``w``
|
||||
and ``h`` properties. ``element`` is looked up with
|
||||
:mochiref:`getElement`, so string identifiers are also acceptable.
|
||||
|
||||
|
||||
:mochidef:`hasElementClass(element, className[, ...])`:
|
||||
|
||||
Return ``true`` if ``className`` is found on the ``element``.
|
||||
``element`` is looked up with :mochiref:`getElement`, so string identifiers
|
||||
are also acceptable.
|
||||
|
||||
|
||||
:mochidef:`hideElement(element, ...)`:
|
||||
|
||||
Partial form of :mochiref:`setDisplayForElement`, specifically::
|
||||
|
||||
partial(setDisplayForElement, "none")
|
||||
|
||||
For information about the caveats of using a ``style.display`` based
|
||||
show/hide mechanism, and a CSS based alternative, see
|
||||
`Element Visibility`_.
|
||||
|
||||
|
||||
:mochidef:`registerDOMConverter(name, check, wrap[, override])`:
|
||||
|
||||
Register an adapter to convert objects that match ``check(obj, ctx)``
|
||||
to a DOM element, or something that can be converted to a DOM
|
||||
element (i.e. number, bool, string, function, iterable).
|
||||
|
||||
|
||||
:mochidef:`removeElement(node)`:
|
||||
|
||||
Remove and return ``node`` from a DOM tree. This is technically
|
||||
just a convenience for :mochiref:`swapDOM(node, null)`.
|
||||
|
||||
``node``:
|
||||
the DOM element (or string id of one) to be removed
|
||||
|
||||
*returns*
|
||||
The removed element
|
||||
|
||||
|
||||
:mochidef:`removeElementClass(element, className)`:
|
||||
|
||||
Ensure that the given ``element`` does not have ``className`` set as part
|
||||
of its class attribute. This will not disturb other class names.
|
||||
``element`` is looked up with :mochiref:`getElement`, so string identifiers
|
||||
are also acceptable.
|
||||
|
||||
|
||||
:mochidef:`replaceChildNodes(node[, childNode[, ...]])`:
|
||||
|
||||
Remove all children from the given DOM element, then append any given
|
||||
childNodes to it (by calling :mochiref:`appendChildNodes`).
|
||||
|
||||
``node``:
|
||||
A reference to the DOM element to add children to
|
||||
(if a string is given, :mochiref:`getElement(node)`
|
||||
will be used to locate the node)
|
||||
|
||||
``childNode``...:
|
||||
All additional arguments, if any, will be coerced into DOM
|
||||
nodes that are appended as children using the
|
||||
`DOM Coercion Rules`_.
|
||||
|
||||
*returns*:
|
||||
The given DOM element
|
||||
|
||||
|
||||
:mochidef:`scrapeText(node[, asArray=false])`:
|
||||
|
||||
Walk a DOM tree in-order and scrape all of the text out of it as a
|
||||
``string``.
|
||||
|
||||
If ``asArray`` is ``true``, then an ``Array`` will be returned with
|
||||
each individual text node. These two are equivalent::
|
||||
|
||||
assert( scrapeText(node) == scrapeText(node, true).join("") );
|
||||
|
||||
|
||||
:mochidef:`setDisplayForElement(display, element[, ...])`:
|
||||
|
||||
Change the ``style.display`` for the given element(s). Usually
|
||||
used as the partial forms:
|
||||
|
||||
- :mochiref:`showElement(element, ...)`
|
||||
- :mochiref:`hideElement(element, ...)`
|
||||
|
||||
Elements are looked up with :mochiref:`getElement`, so string identifiers
|
||||
are acceptable.
|
||||
|
||||
For information about the caveats of using a ``style.display`` based
|
||||
show/hide mechanism, and a CSS based alternative, see
|
||||
`Element Visibility`_.
|
||||
|
||||
|
||||
:mochidef:`setElementClass(element, className)`:
|
||||
|
||||
Set the entire class attribute of ``element`` to ``className``.
|
||||
``element`` is looked up with :mochiref:`getElement`, so string identifiers
|
||||
are also acceptable.
|
||||
|
||||
|
||||
:mochidef:`setElementDimensions(element, dimensions[, units='px'])`:
|
||||
|
||||
Sets the dimensions of ``element`` in the document from an
|
||||
object with ``w`` and ``h`` properties.
|
||||
|
||||
``node``:
|
||||
A reference to the DOM element to update (if a string is given,
|
||||
:mochiref:`getElement(node)` will be used to locate the node)
|
||||
|
||||
``dimensions``:
|
||||
An object with ``w`` and ``h`` properties
|
||||
|
||||
``units``:
|
||||
Optionally set the units to use, default is ``px``
|
||||
|
||||
|
||||
:mochidef:`setElementPosition(element, position[, units='px'])`:
|
||||
|
||||
Sets the absolute position of ``element`` in the document from an
|
||||
object with ``x`` and ``y`` properties.
|
||||
|
||||
``node``:
|
||||
A reference to the DOM element to update (if a string is given,
|
||||
:mochiref:`getElement(node)` will be used to locate the node)
|
||||
|
||||
``position``:
|
||||
An object with ``x`` and ``y`` properties
|
||||
|
||||
``units``:
|
||||
Optionally set the units to use, default is ``px``
|
||||
|
||||
|
||||
:mochidef:`setNodeAttribute(node, attr, value)`:
|
||||
|
||||
Set the value of the given attribute for a DOM element without
|
||||
ever raising an exception (will return null on exception). If
|
||||
setting more than one attribute, you should use
|
||||
:mochiref:`updateNodeAttributes`.
|
||||
|
||||
``node``:
|
||||
A reference to the DOM element to update (if a string is given,
|
||||
:mochiref:`getElement(node)` will be used to locate the node)
|
||||
|
||||
``attr``:
|
||||
The name of the attribute
|
||||
|
||||
Note that it will do the right thing for IE, so don't do
|
||||
the ``class`` -> ``className`` hack yourself.
|
||||
|
||||
``value``:
|
||||
The value of the attribute, may be an object to be merged
|
||||
(e.g. for setting style).
|
||||
|
||||
*returns*:
|
||||
The given DOM element or ``null`` on failure
|
||||
|
||||
|
||||
:mochidef:`setOpacity(element, opacity)`:
|
||||
|
||||
Sets ``opacity`` for ``element``. Valid ``opacity`` values range from 0
|
||||
(invisible) to 1 (opaque). ``element`` is looked up with
|
||||
:mochiref:`getElement`, so string identifiers are also acceptable.
|
||||
|
||||
|
||||
:mochidef:`showElement(element, ...)`:
|
||||
|
||||
Partial form of :mochiref:`setDisplayForElement`, specifically::
|
||||
|
||||
partial(setDisplayForElement, "block")
|
||||
|
||||
For information about the caveats of using a ``style.display`` based
|
||||
show/hide mechanism, and a CSS based alternative, see
|
||||
`Element Visibility`_.
|
||||
|
||||
|
||||
:mochidef:`swapDOM(dest, src)`:
|
||||
|
||||
Replace ``dest`` in a DOM tree with ``src``, returning ``src``.
|
||||
|
||||
``dest``:
|
||||
a DOM element (or string id of one) to be replaced
|
||||
|
||||
``src``:
|
||||
the DOM element (or string id of one) to replace it with, or
|
||||
``null`` if ``dest`` is to be removed (replaced with nothing).
|
||||
|
||||
*returns*:
|
||||
a DOM element (``src``)
|
||||
|
||||
|
||||
:mochidef:`swapElementClass(element, fromClass, toClass)`:
|
||||
|
||||
If ``fromClass`` is set on ``element``, replace it with ``toClass``.
|
||||
This will not disturb other classes on that element.
|
||||
``element`` is looked up with :mochiref:`getElement`, so string identifiers
|
||||
are also acceptable.
|
||||
|
||||
|
||||
:mochidef:`toggleElementClass(className[, element[, ...]])`:
|
||||
|
||||
Toggle the presence of a given ``className`` in the class attribute
|
||||
of all given elements. All elements will be looked up with
|
||||
:mochiref:`getElement`, so string identifiers are acceptable.
|
||||
|
||||
|
||||
:mochidef:`toHTML(dom)`:
|
||||
|
||||
Convert a DOM tree to a HTML string using :mochiref:`emitHTML`
|
||||
|
||||
|
||||
:mochidef:`updateNodeAttributes(node, attrs)`:
|
||||
|
||||
Update the attributes of a DOM element from a given object.
|
||||
|
||||
``node``:
|
||||
A reference to the DOM element to update (if a string is given,
|
||||
:mochiref:`getElement(node)` will be used to locate the node)
|
||||
|
||||
``attrs``:
|
||||
An object whose properties will be used to set the attributes
|
||||
(e.g. ``{'class': 'invisible'}``), or ``null`` if no
|
||||
attributes need to be set. If an object is given for the
|
||||
attribute value (e.g. ``{'style': {'display': 'block'}}``)
|
||||
then :mochiref:`MochiKit.Base.updatetree` will be used to set that
|
||||
attribute.
|
||||
|
||||
Note that it will do the right thing for IE, so don't do
|
||||
the ``class`` -> ``className`` hack yourself, and it deals with
|
||||
setting "on..." event handlers correctly.
|
||||
|
||||
*returns*:
|
||||
The given DOM element
|
||||
|
||||
|
||||
:mochidef:`withWindow(win, func)`:
|
||||
|
||||
Call ``func`` with the ``window`` `DOM Context`_ set to ``win`` and
|
||||
the ``document`` `DOM Context`_ set to ``win.document``. When
|
||||
``func()`` returns or throws an error, the `DOM Context`_ will be
|
||||
restored to its previous state.
|
||||
|
||||
The return value of ``func()`` is returned by this function.
|
||||
|
||||
|
||||
:mochidef:`withDocument(doc, func)`:
|
||||
|
||||
Call ``func`` with the ``doc`` `DOM Context`_ set to ``doc``.
|
||||
When ``func()`` returns or throws an error, the `DOM Context`_
|
||||
will be restored to its previous state.
|
||||
|
||||
The return value of ``func()`` is returned by this function.
|
||||
|
||||
|
||||
See Also
|
||||
========
|
||||
|
||||
.. [1] Nevow, a web application construction kit for Python: http://nevow.com/
|
||||
.. [2] nevow.stan is a domain specific language for Python
|
||||
(read as "crazy getitem/call overloading abuse") that Donovan and I
|
||||
schemed up at PyCon 2003 at this super ninja Python/C++ programmer's
|
||||
(David Abrahams) hotel room. Donovan later inflicted this upon the
|
||||
masses in Nevow. Check out the Divmod project page for some
|
||||
examples: http://nevow.com/Nevow2004Tutorial.html
|
||||
|
||||
|
||||
Authors
|
||||
=======
|
||||
|
||||
- Bob Ippolito <bob@redivi.com>
|
||||
|
||||
|
||||
Copyright
|
||||
=========
|
||||
|
||||
Copyright 2005 Bob Ippolito <bob@redivi.com>. This program is dual-licensed
|
||||
free software; you can redistribute it and/or modify it under the terms of the
|
||||
`MIT License`_ or the `Academic Free License v2.1`_.
|
||||
|
||||
.. _`MIT License`: http://www.opensource.org/licenses/mit-license.php
|
||||
.. _`Academic Free License v2.1`: http://www.opensource.org/licenses/afl-2.1.php
|
||||
@@ -1,118 +0,0 @@
|
||||
.. title:: MochiKit.DateTime - "what time is it anyway?"
|
||||
|
||||
Name
|
||||
====
|
||||
|
||||
MochiKit.DateTime - "what time is it anyway?"
|
||||
|
||||
|
||||
Synopsis
|
||||
========
|
||||
|
||||
::
|
||||
|
||||
stringDate = toISOTimestamp(new Date());
|
||||
dateObject = isoTimestamp(stringDate);
|
||||
|
||||
|
||||
Description
|
||||
===========
|
||||
|
||||
Remote servers don't give you JavaScript Date objects, and they certainly
|
||||
don't want them from you, so you need to deal with string representations
|
||||
of dates and timestamps. MochiKit.Date does that.
|
||||
|
||||
|
||||
Dependencies
|
||||
============
|
||||
|
||||
None.
|
||||
|
||||
|
||||
API Reference
|
||||
=============
|
||||
|
||||
Functions
|
||||
---------
|
||||
|
||||
:mochidef:`isoDate(str)`:
|
||||
|
||||
Convert an ISO 8601 date (YYYY-MM-DD) to a ``Date`` object.
|
||||
|
||||
|
||||
:mochidef:`isoTimestamp(str)`:
|
||||
|
||||
Convert any ISO 8601 [1]_ timestamp (or something reasonably close to it)
|
||||
to a ``Date`` object. Will accept the "de facto" form:
|
||||
|
||||
YYYY-MM-DD hh:mm:ss
|
||||
|
||||
or (the proper form):
|
||||
|
||||
YYYY-MM-DDThh:mm:ssZ
|
||||
|
||||
If a time zone designator ("Z" or "[+-]HH:MM") is not present, then the
|
||||
local timezone is used.
|
||||
|
||||
|
||||
:mochidef:`toISOTime(date)`:
|
||||
|
||||
Convert a ``Date`` object to a string in the form of hh:mm:ss
|
||||
|
||||
|
||||
:mochidef:`toISOTimestamp(date, realISO=false)`:
|
||||
|
||||
Convert a ``Date`` object to something that's ALMOST but not quite an
|
||||
ISO 8601 [1]_timestamp. If it was a proper ISO timestamp it would be:
|
||||
|
||||
YYYY-MM-DDThh:mm:ssZ
|
||||
|
||||
However, we see junk in SQL and other places that looks like this:
|
||||
|
||||
YYYY-MM-DD hh:mm:ss
|
||||
|
||||
So, this function returns the latter form, despite its name, unless
|
||||
you pass ``true`` for ``realISO``.
|
||||
|
||||
|
||||
:mochidef:`toISODate(date)`:
|
||||
|
||||
Convert a ``Date`` object to an ISO 8601 [1]_ date string (YYYY-MM-DD)
|
||||
|
||||
|
||||
:mochidef:`americanDate(str)`:
|
||||
|
||||
Converts a MM/DD/YYYY date to a ``Date`` object
|
||||
|
||||
|
||||
:mochidef:`toPaddedAmericanDate(date)`:
|
||||
|
||||
Converts a ``Date`` object to an MM/DD/YYYY date, e.g. 01/01/2001
|
||||
|
||||
|
||||
:mochidef:`toAmericanDate(date)`:
|
||||
|
||||
Converts a ``Date`` object to an M/D/YYYY date, e.g. 1/1/2001
|
||||
|
||||
|
||||
See Also
|
||||
========
|
||||
|
||||
.. [1] W3C profile of ISO 8601: http://www.w3.org/TR/NOTE-datetime
|
||||
|
||||
|
||||
Authors
|
||||
=======
|
||||
|
||||
- Bob Ippolito <bob@redivi.com>
|
||||
|
||||
|
||||
Copyright
|
||||
=========
|
||||
|
||||
Copyright 2005 Bob Ippolito <bob@redivi.com>. This program is dual-licensed
|
||||
free software; you can redistribute it and/or modify it under the terms of the
|
||||
`MIT License`_ or the `Academic Free License v2.1`_.
|
||||
|
||||
.. _`MIT License`: http://www.opensource.org/licenses/mit-license.php
|
||||
.. _`Academic Free License v2.1`: http://www.opensource.org/licenses/afl-2.1.php
|
||||
@@ -1,211 +0,0 @@
|
||||
.. title:: MochiKit.Format - string formatting goes here
|
||||
|
||||
Name
|
||||
====
|
||||
|
||||
MochiKit.Format - string formatting goes here
|
||||
|
||||
|
||||
Synopsis
|
||||
========
|
||||
|
||||
::
|
||||
|
||||
assert( truncToFixed(0.12345, 4) == "0.1234" );
|
||||
assert( roundToFixed(0.12345, 4) == "0.1235" );
|
||||
assert( twoDigitAverage(1, 0) == "0" );
|
||||
assert( twoDigitFloat(1.2345) == "1.23" );
|
||||
assert( twoDigitFloat(1) == "1" );
|
||||
assert( percentFormat(1.234567) == "123.46%" );
|
||||
assert( numberFormatter("###,###%")(125) == "12,500%" );
|
||||
assert( numberFormatter("##.000")(1.25) == "1.250" );
|
||||
|
||||
|
||||
Description
|
||||
===========
|
||||
|
||||
Formatting strings and stringifying numbers is boring, so a couple useful
|
||||
functions in that domain live here.
|
||||
|
||||
|
||||
Dependencies
|
||||
============
|
||||
|
||||
None.
|
||||
|
||||
|
||||
Overview
|
||||
========
|
||||
|
||||
Formatting Numbers
|
||||
------------------
|
||||
|
||||
MochiKit provides an extensible number formatting facility, modeled loosely
|
||||
after the Number Format Pattern Syntax [1]_ from Java.
|
||||
:mochiref:`numberFormatter(pattern[, placeholder=""[, locale="default"])`
|
||||
returns a function that converts Number to string using the given information.
|
||||
``pattern`` is a string consisting of the following symbols:
|
||||
|
||||
+-----------+---------------------------------------------------------------+
|
||||
| Symbol | Meaning |
|
||||
+===========+===============================================================+
|
||||
| ``-`` | If given, used as the position of the minus sign |
|
||||
| | for negative numbers. If not given, the position |
|
||||
| | to the left of the first number placeholder is used. |
|
||||
+-----------+---------------------------------------------------------------+
|
||||
| ``#`` | The placeholder for a number that does not imply zero |
|
||||
| | padding. |
|
||||
+-----------+---------------------------------------------------------------+
|
||||
| ``0`` | The placeholder for a number that implies zero padding. |
|
||||
| | If it is used to the right of a decimal separator, it |
|
||||
| | implies trailing zeros, otherwise leading zeros. |
|
||||
+-----------+---------------------------------------------------------------+
|
||||
| ``,`` | The placeholder for a "thousands separator". May be used |
|
||||
| | at most once, and it must be to the left of a decimal |
|
||||
| | separator. Will be replaced by ``locale.separator`` in the |
|
||||
| | result (the default is also ``,``). |
|
||||
+-----------+---------------------------------------------------------------+
|
||||
| ``.`` | The decimal separator. The quantity of ``#`` or ``0`` |
|
||||
| | after the decimal separator will determine the precision of |
|
||||
| | the result. If no decimal separator is present, the |
|
||||
| | fractional precision is ``0`` -- meaning that it will be |
|
||||
| | rounded to the nearest integer. |
|
||||
+-----------+---------------------------------------------------------------+
|
||||
| ``%`` | If present, the number will be multiplied by ``100`` and |
|
||||
| | the ``%`` will be replaced by ``locale.percent``. |
|
||||
+-----------+---------------------------------------------------------------+
|
||||
|
||||
|
||||
API Reference
|
||||
=============
|
||||
|
||||
Functions
|
||||
---------
|
||||
|
||||
:mochidef:`formatLocale(locale="default")`:
|
||||
|
||||
Return a locale object for the given locale. ``locale`` may be either a
|
||||
string, which is looked up in the ``MochiKit.Format.LOCALE`` object, or
|
||||
a locale object. If no locale is given, ``LOCALE.default`` is used
|
||||
(equivalent to ``LOCALE.en_US``).
|
||||
|
||||
|
||||
:mochidef:`lstrip(str, chars="\\s")`:
|
||||
|
||||
Returns a string based on ``str`` with leading whitespace stripped.
|
||||
|
||||
If ``chars`` is given, then that expression will be used instead of
|
||||
whitespace. ``chars`` should be a string suitable for use in a ``RegExp``
|
||||
``[character set]``.
|
||||
|
||||
|
||||
:mochidef:`numberFormatter(pattern, placeholder="", locale="default")`:
|
||||
|
||||
Return a function ``formatNumber(aNumber)`` that formats numbers
|
||||
as a string according to the given pattern, placeholder and locale.
|
||||
|
||||
``pattern`` is a string that describes how the numbers should be formatted,
|
||||
for more information see `Formatting Numbers`_.
|
||||
|
||||
``locale`` is a string of a known locale (en_US, de_DE, fr_FR, default) or
|
||||
an object with the following fields:
|
||||
|
||||
+-----------+-----------------------------------------------------------+
|
||||
| separator | The "thousands" separator for this locale (en_US is ",") |
|
||||
+-----------+-----------------------------------------------------------+
|
||||
| decimal | The decimal separator for this locale (en_US is ".") |
|
||||
+-----------+-----------------------------------------------------------+
|
||||
| percent | The percent symbol for this locale (en_US is "%") |
|
||||
+-----------+-----------------------------------------------------------+
|
||||
|
||||
|
||||
:mochidef:`percentFormat(someFloat)`:
|
||||
|
||||
Roughly equivalent to: ``sprintf("%.2f%%", someFloat * 100)``
|
||||
|
||||
In new code, you probably want to use:
|
||||
:mochiref:`numberFormatter("#.##%")(someFloat)` instead.
|
||||
|
||||
|
||||
:mochidef:`roundToFixed(aNumber, precision)`:
|
||||
|
||||
Return a string representation of ``aNumber``, rounded to ``precision``
|
||||
digits with trailing zeros. This is similar to
|
||||
``Number.toFixed(aNumber, precision)``, but this has implementation
|
||||
consistent rounding behavior (some versions of Safari round 0.5 down!)
|
||||
and also includes preceding ``0`` for numbers less than ``1`` (Safari,
|
||||
again).
|
||||
|
||||
For example, :mochiref:`roundToFixed(0.1357, 2)` returns ``0.14`` on every
|
||||
supported platform, where some return ``.13`` for ``(0.1357).toFixed(2)``.
|
||||
|
||||
|
||||
:mochidef:`rstrip(str, chars="\\s")`:
|
||||
|
||||
Returns a string based on ``str`` with trailing whitespace stripped.
|
||||
|
||||
If ``chars`` is given, then that expression will be used instead of
|
||||
whitespace. ``chars`` should be a string suitable for use in a ``RegExp``
|
||||
``[character set]``.
|
||||
|
||||
|
||||
:mochidef:`strip(str, chars="\\s")`:
|
||||
|
||||
Returns a string based on ``str`` with leading and trailing whitespace
|
||||
stripped (equivalent to :mochiref:`lstrip(rstrip(str, chars), chars)`).
|
||||
|
||||
If ``chars`` is given, then that expression will be used instead of
|
||||
whitespace. ``chars`` should be a string suitable for use in a ``RegExp``
|
||||
``[character set]``.
|
||||
|
||||
|
||||
:mochidef:`truncToFixed(aNumber, precision)`:
|
||||
|
||||
Return a string representation of ``aNumber``, truncated to ``precision``
|
||||
digits with trailing zeros. This is similar to
|
||||
``aNumber.toFixed(precision)``, but this truncates rather than rounds and
|
||||
has implementation consistent behavior for numbers less than 1.
|
||||
Specifically, :mochiref:`truncToFixed(aNumber, precision)` will always have a
|
||||
preceding ``0`` for numbers less than ``1``.
|
||||
|
||||
For example, :mochiref:`toFixed(0.1357, 2)` returns ``0.13``.
|
||||
|
||||
|
||||
:mochidef:`twoDigitAverage(numerator, denominator)`:
|
||||
|
||||
Calculate an average from a numerator and a denominator and return
|
||||
it as a string with two digits of precision (e.g. "1.23").
|
||||
|
||||
If the denominator is 0, "0" will be returned instead of ``NaN``.
|
||||
|
||||
|
||||
:mochidef:`twoDigitFloat(someFloat)`:
|
||||
|
||||
Roughly equivalent to: ``sprintf("%.2f", someFloat)``
|
||||
|
||||
In new code, you probably want to use
|
||||
:mochiref:`numberFormatter("#.##")(someFloat)` instead.
|
||||
|
||||
|
||||
See Also
|
||||
========
|
||||
|
||||
.. [1] Java Number Format Pattern Syntax:
|
||||
http://java.sun.com/docs/books/tutorial/i18n/format/numberpattern.html
|
||||
|
||||
|
||||
Authors
|
||||
=======
|
||||
|
||||
- Bob Ippolito <bob@redivi.com>
|
||||
|
||||
|
||||
Copyright
|
||||
=========
|
||||
|
||||
Copyright 2005 Bob Ippolito <bob@redivi.com>. This program is dual-licensed
|
||||
free software; you can redistribute it and/or modify it under the terms of the
|
||||
`MIT License`_ or the `Academic Free License v2.1`_.
|
||||
|
||||
.. _`MIT License`: http://www.opensource.org/licenses/mit-license.php
|
||||
.. _`Academic Free License v2.1`: http://www.opensource.org/licenses/afl-2.1.php
|
||||
@@ -1,345 +0,0 @@
|
||||
.. title:: MochiKit.Iter - itertools for JavaScript; iteration made HARD, and then easy
|
||||
|
||||
Name
|
||||
====
|
||||
|
||||
MochiKit.Iter - itertools for JavaScript; iteration made HARD, and then easy
|
||||
|
||||
|
||||
Synopsis
|
||||
========
|
||||
|
||||
::
|
||||
|
||||
|
||||
theSum = sum(takewhile(
|
||||
partial(operator.gt, 10),
|
||||
imap(
|
||||
partial(operator.mul, 2),
|
||||
count()
|
||||
)
|
||||
)
|
||||
));
|
||||
|
||||
assert( theSum == (0 + 0 + 2 + 4 + 6 + 8) );
|
||||
|
||||
|
||||
Description
|
||||
===========
|
||||
|
||||
All of the functional programming missing from :mochiref:`MochiKit.Base` lives
|
||||
here. The functionality in this module is largely inspired by Python's iteration
|
||||
protocol [1]_, and the itertools module [2]_.
|
||||
|
||||
MochiKit.Iter defines a standard way to iterate over anything, that you can
|
||||
extend with :mochiref:`registerIterator`, or by implementing the ``.iter()``
|
||||
protocol. Iterators are lazy, so it can potentially be cheaper to build a
|
||||
filter chain of iterators than to build lots of intermediate arrays.
|
||||
Especially when the data set is very large, but the result is not.
|
||||
|
||||
|
||||
Dependencies
|
||||
============
|
||||
|
||||
- :mochiref:`MochiKit.Base`
|
||||
|
||||
|
||||
Overview
|
||||
========
|
||||
|
||||
Iteration for JavaScript
|
||||
------------------------
|
||||
|
||||
The best overview right now is in my Iteration for JavaScript [3]_ blog entry.
|
||||
This information will migrate here eventually.
|
||||
|
||||
API Reference
|
||||
=============
|
||||
|
||||
Errors
|
||||
------
|
||||
|
||||
:mochidef:`StopIteration`:
|
||||
|
||||
The singleton :mochiref:`MochiKit.Base.NamedError` that signifies the end
|
||||
of an iterator
|
||||
|
||||
Functions
|
||||
---------
|
||||
|
||||
:mochidef:`applymap(fun, seq[, self])`:
|
||||
|
||||
``applymap(fun, seq)`` -->
|
||||
fun.apply(self, seq0), fun.apply(self, seq1), ...
|
||||
|
||||
|
||||
:mochidef:`chain(p, q[, ...])`:
|
||||
|
||||
``chain(p, q, ...)`` --> p0, p1, ... plast, q0, q1, ...
|
||||
|
||||
|
||||
:mochidef:`count(n=0)`:
|
||||
|
||||
``count(n=0)`` --> n, n + 1, n + 2, ...
|
||||
|
||||
|
||||
:mochidef:`cycle(p)`:
|
||||
|
||||
``cycle(p)`` --> p0, p1, ... plast, p0, p1, ...
|
||||
|
||||
|
||||
:mochidef:`dropwhile(pred, seq)`:
|
||||
|
||||
``dropwhile(pred, seq)`` --> seq[n], seq[n + 1], starting when
|
||||
pred(seq[n]) fails
|
||||
|
||||
|
||||
:mochidef:`every(iterable, func)`:
|
||||
|
||||
Return ``true`` if ``func(item)`` is ``true`` for every item in
|
||||
``iterable``.
|
||||
|
||||
|
||||
:mochidef:`exhaust(iterable)`:
|
||||
|
||||
Exhausts an iterable without saving the results anywhere,
|
||||
like :mochiref:`list(iterable)` when you don't care what the output is.
|
||||
|
||||
|
||||
:mochidef:`forEach(iterable, func[, self])`:
|
||||
|
||||
Call ``func`` for each item in ``iterable``, and don't save the results.
|
||||
|
||||
|
||||
:mochidef:`groupby(iterable[, keyfunc])`:
|
||||
|
||||
Make an iterator that returns consecutive keys and groups from the
|
||||
iterable. The key is a function computing a key value for each element.
|
||||
If not specified or is None, key defaults to an identity function and
|
||||
returns the element unchanged. Generally, the iterable needs to already be
|
||||
sorted on the same key function.
|
||||
|
||||
The returned group is itself an iterator that shares the underlying
|
||||
iterable with :mochiref:`groupby()`. Because the source is shared, when the
|
||||
groupby object is advanced, the previous group is no longer visible.
|
||||
So, if that data is needed later, it should be stored as an array::
|
||||
|
||||
var groups = [];
|
||||
var uniquekeys = [];
|
||||
forEach(groupby(data, keyfunc), function (key_group) {
|
||||
groups.push(list(key_group[1]));
|
||||
uniquekeys.push(key_group[0]);
|
||||
});
|
||||
|
||||
As a convenience, :mochiref:`groupby_as_array()` is provided to suit the above
|
||||
use case.
|
||||
|
||||
|
||||
:mochidef:`groupby_as_array(iterable[, keyfunc])`:
|
||||
|
||||
Perform the same task as :mochiref:`groupby()`, except return an array of
|
||||
arrays instead of an iterator of iterators.
|
||||
|
||||
|
||||
:mochidef:`iextend(lst, iterable)`:
|
||||
|
||||
Just like :mochiref:`list(iterable)`, except it pushes results on ``lst``
|
||||
rather than creating a new one.
|
||||
|
||||
|
||||
:mochidef:`ifilter(pred, seq)`:
|
||||
|
||||
``ifilter(pred, seq)`` --> elements of seq where ``pred(elem)`` is ``true``
|
||||
|
||||
|
||||
:mochidef:`ifilterfalse(pred, seq)`:
|
||||
|
||||
``ifilterfalse(pred, seq)`` --> elements of seq where ``pred(elem)`` is
|
||||
``false``
|
||||
|
||||
|
||||
:mochidef:`imap(fun, p, q[, ...])`:
|
||||
|
||||
``imap(fun, p, q, ...)`` --> fun(p0, q0, ...), fun(p1, q1, ...), ...
|
||||
|
||||
|
||||
:mochidef:`islice(seq, [start,] stop[, step])`:
|
||||
|
||||
``islice(seq, [start,] stop[, step])`` --> elements from
|
||||
seq[start:stop:step] (in Python slice syntax)
|
||||
|
||||
|
||||
:mochidef:`iter(iterable[, sentinel])`:
|
||||
|
||||
Convert the given argument to an iterator (object implementing
|
||||
``.next()``).
|
||||
|
||||
1. If ``iterable`` is an iterator (implements ``.next()``), then it will
|
||||
be returned as-is.
|
||||
2. If ``iterable`` is an iterator factory (implements ``.iter()``), then
|
||||
the result of ``iterable.iter()`` will be returned.
|
||||
3. Otherwise, the iterator factory :mochiref:`MochiKit.Base.AdapterRegistry`
|
||||
is used to find a match.
|
||||
4. If no factory is found, it will throw ``TypeError``
|
||||
|
||||
Built-in iterator factories are present for Array-like objects, and
|
||||
objects that implement the ``iterateNext`` protocol (e.g. the result of
|
||||
Mozilla's ``document.evaluate``).
|
||||
|
||||
When used directly, using an iterator should look like this::
|
||||
|
||||
var it = iter(iterable);
|
||||
try {
|
||||
while (var o = it.next()) {
|
||||
// use o
|
||||
}
|
||||
} catch (e) {
|
||||
if (e != StopIteration) {
|
||||
throw e;
|
||||
}
|
||||
// pass
|
||||
}
|
||||
|
||||
This is ugly, so you should use the higher order functions to work
|
||||
with iterators whenever possible.
|
||||
|
||||
|
||||
:mochidef:`izip(p, q[, ...])`:
|
||||
|
||||
``izip(p, q, ...)`` --> [p0, q0, ...], [p1, q1, ...], ...
|
||||
|
||||
|
||||
:mochidef:`list(iterable)`:
|
||||
|
||||
Convert ``iterable`` to a new ``Array``
|
||||
|
||||
|
||||
:mochidef:`next(iterator)`:
|
||||
|
||||
Return ``iterator.next()``
|
||||
|
||||
|
||||
:mochidef:`range([start,] stop[, step])`:
|
||||
|
||||
Return an iterator containing an arithmetic progression of integers.
|
||||
|
||||
``range(i, j)`` returns :mochiref:`iter([i, i + 1, i + 2, ..., j - 1])`
|
||||
|
||||
``start`` (!) defaults to ``0``. When ``step`` is given, it specifies the
|
||||
increment (or decrement). The end point is omitted!
|
||||
|
||||
For example, ``range(4)`` returns :mochiref:`iter([0, 1, 2, 3])`.
|
||||
This iterates over exactly the valid indexes for an array of 4 elements.
|
||||
|
||||
|
||||
:mochidef:`reduce(fn, iterable[, initial])`:
|
||||
|
||||
Apply ``fn(a, b)`` cumulatively to the items of an
|
||||
iterable from left to right, so as to reduce the iterable
|
||||
to a single value.
|
||||
|
||||
For example::
|
||||
|
||||
reduce(function (a, b) { return x + y; }, [1, 2, 3, 4, 5])
|
||||
|
||||
calculates::
|
||||
|
||||
((((1 + 2) + 3) + 4) + 5).
|
||||
|
||||
If initial is given, it is placed before the items of the sequence
|
||||
in the calculation, and serves as a default when the sequence is
|
||||
empty.
|
||||
|
||||
Note that the above example could be written more clearly as::
|
||||
|
||||
reduce(operator.add, [1, 2, 3, 4, 5])
|
||||
|
||||
Or even simpler::
|
||||
|
||||
sum([1, 2, 3, 4, 5])
|
||||
|
||||
|
||||
:mochidef:`registerIteratorFactory(name, check, iterfactory[, override])`:
|
||||
|
||||
Register an iterator factory for use with the iter function.
|
||||
|
||||
``check`` is a ``function(a)`` that returns ``true`` if ``a`` can be
|
||||
converted into an iterator with ``iterfactory``.
|
||||
|
||||
``iterfactory`` is a ``function(a)`` that returns an object with a
|
||||
``.next()`` method that returns the next value in the sequence.
|
||||
|
||||
``iterfactory`` is guaranteed to only be called if ``check(a)``
|
||||
returns a true value.
|
||||
|
||||
If ``override`` is ``true``, then it will be made the
|
||||
highest precedence iterator factory. Otherwise, the lowest.
|
||||
|
||||
|
||||
:mochidef:`repeat(elem[, n])`:
|
||||
|
||||
``repeat(elem, [,n])`` --> elem, elem, elem, ... endlessly or up to n times
|
||||
|
||||
|
||||
:mochidef:`reversed(iterable)`:
|
||||
|
||||
Return a reversed array from iterable.
|
||||
|
||||
|
||||
:mochidef:`some(iterable, func)`:
|
||||
|
||||
Return ``true`` if ``func(item)`` is ``true`` for at least one item in
|
||||
``iterable``.
|
||||
|
||||
|
||||
:mochidef:`sorted(iterable[, cmp])`:
|
||||
|
||||
Return a sorted array from iterable.
|
||||
|
||||
|
||||
:mochidef:`sum(iterable, start=0)`:
|
||||
|
||||
Returns the sum of a sequence of numbers plus the value
|
||||
of parameter ``start`` (with a default of 0). When the sequence is
|
||||
empty, returns start.
|
||||
|
||||
Equivalent to::
|
||||
|
||||
reduce(operator.add, iterable, start);
|
||||
|
||||
|
||||
:mochidef:`takewhile(pred, seq)`:
|
||||
|
||||
``takewhile(pred, seq)`` --> seq[0], seq[1], ... until pred(seq[n]) fails
|
||||
|
||||
|
||||
:mochidef:`tee(iterable, n=2)`:
|
||||
|
||||
``tee(it, n=2)`` --> [it1, it2, it3, ... itn] splits one iterator into n
|
||||
|
||||
|
||||
See Also
|
||||
========
|
||||
|
||||
.. [1] The iteration protocol is described in
|
||||
PEP 234 - Iterators: http://www.python.org/peps/pep-0234.html
|
||||
.. [2] Python's itertools
|
||||
module: http://docs.python.org/lib/module-itertools.html
|
||||
.. [3] Iteration in JavaScript: http://bob.pythonmac.org/archives/2005/07/06/iteration-in-javascript/
|
||||
|
||||
|
||||
Authors
|
||||
=======
|
||||
|
||||
- Bob Ippolito <bob@redivi.com>
|
||||
|
||||
|
||||
Copyright
|
||||
=========
|
||||
|
||||
Copyright 2005 Bob Ippolito <bob@redivi.com>. This program is dual-licensed
|
||||
free software; you can redistribute it and/or modify it under the terms of the
|
||||
`MIT License`_ or the `Academic Free License v2.1`_.
|
||||
|
||||
.. _`MIT License`: http://www.opensource.org/licenses/mit-license.php
|
||||
.. _`Academic Free License v2.1`: http://www.opensource.org/licenses/afl-2.1.php
|
||||
@@ -1,284 +0,0 @@
|
||||
.. title:: MochiKit.Logging - we're all tired of alert()
|
||||
|
||||
Name
|
||||
====
|
||||
|
||||
MochiKit.Logging - we're all tired of alert()
|
||||
|
||||
|
||||
Synopsis
|
||||
========
|
||||
|
||||
::
|
||||
|
||||
log("INFO messages are so boring");
|
||||
logDebug("DEBUG messages are even worse");
|
||||
log("good thing I can pass", objects, "conveniently");
|
||||
|
||||
|
||||
Description
|
||||
===========
|
||||
|
||||
MochiKit.Logging steals some ideas from Python's logging module [1]_, but
|
||||
completely forgot about the Java [2]_ inspiration. This is a KISS module for
|
||||
logging that provides enough flexibility to do just about anything via
|
||||
listeners, but without all the cruft.
|
||||
|
||||
|
||||
Dependencies
|
||||
============
|
||||
|
||||
- :mochiref:`MochiKit.Base`
|
||||
|
||||
|
||||
Overview
|
||||
========
|
||||
|
||||
Native Console Logging
|
||||
----------------------
|
||||
|
||||
As of MochiKit 1.3, the default logger will log all messages to your browser's
|
||||
native console. This is currently supported in Safari, Opera 9, and Firefox
|
||||
when the FireBug__ extension is installed.
|
||||
|
||||
.. __: http://www.joehewitt.com/software/firebug/
|
||||
|
||||
To disable this behavior::
|
||||
|
||||
MochiKit.Logging.logger.useNativeLogging = false;
|
||||
|
||||
|
||||
Bookmarklet Based Debugging
|
||||
---------------------------
|
||||
|
||||
JavaScript is at a serious disadvantage without a standard console for
|
||||
"print" statements. Everything else has one. The closest thing that
|
||||
you get in a browser environment is the ``alert`` function, which is
|
||||
absolutely evil.
|
||||
|
||||
This leaves you with one reasonable solution: do your logging in the page
|
||||
somehow. The problem here is that you don't want to clutter the page with
|
||||
debugging tools. The solution to that problem is what we call BBD, or
|
||||
Bookmarklet Based Debugging [3]_.
|
||||
|
||||
Simply create a bookmarklet for `javascript:MochiKit.Logging.logger.debuggingBookmarklet()`__,
|
||||
and whack it whenever you want to see what's in the logger. Of course, this
|
||||
means you must drink the MochiKit.Logging kool-aid. It's tangy and sweet,
|
||||
don't worry.
|
||||
|
||||
.. __: javascript:MochiKit.Logging.logger.debuggingBookmarklet()
|
||||
|
||||
Currently this is an ugly ``alert``, but we'll have something spiffy
|
||||
Real Soon Now, and when we do, you only have to upgrade MochiKit.Logging,
|
||||
not your bookmarklet!
|
||||
|
||||
|
||||
API Reference
|
||||
=============
|
||||
|
||||
Constructors
|
||||
------------
|
||||
|
||||
:mochidef:`LogMessage(num, level, info)`:
|
||||
|
||||
Properties:
|
||||
|
||||
``num``:
|
||||
Identifier for the log message
|
||||
|
||||
``level``:
|
||||
Level of the log message (``"INFO"``, ``"WARN"``, ``"DEBUG"``,
|
||||
etc.)
|
||||
|
||||
``info``:
|
||||
All other arguments passed to log function as an ``Array``
|
||||
|
||||
``timestamp``:
|
||||
``Date`` object timestamping the log message
|
||||
|
||||
|
||||
:mochidef:`Logger([maxSize])`:
|
||||
|
||||
A basic logger object that has a buffer of recent messages
|
||||
plus a listener dispatch mechanism for "real-time" logging
|
||||
of important messages.
|
||||
|
||||
``maxSize`` is the maximum number of entries in the log.
|
||||
If ``maxSize >= 0``, then the log will not buffer more than that
|
||||
many messages. So if you don't like logging at all, be sure to
|
||||
pass ``0``.
|
||||
|
||||
There is a default logger available named "logger", and several
|
||||
of its methods are also global functions:
|
||||
|
||||
``logger.log`` -> ``log``
|
||||
``logger.debug`` -> ``logDebug``
|
||||
``logger.warning`` -> ``logWarning``
|
||||
``logger.error`` -> ``logError``
|
||||
``logger.fatal`` -> ``logFatal``
|
||||
|
||||
|
||||
:mochidef:`Logger.prototype.addListener(ident, filter, listener)`:
|
||||
|
||||
Add a listener for log messages.
|
||||
|
||||
``ident`` is a unique identifier that may be used to remove the listener
|
||||
later on.
|
||||
|
||||
``filter`` can be one of the following:
|
||||
|
||||
``null``:
|
||||
``listener(msg)`` will be called for every log message
|
||||
received.
|
||||
|
||||
``string``:
|
||||
:mochiref:`logLevelAtLeast(filter)` will be used as the function
|
||||
(see below).
|
||||
|
||||
``function``:
|
||||
``filter(msg)`` will be called for every msg, if it returns
|
||||
true then ``listener(msg)`` will be called.
|
||||
|
||||
``listener`` is a function that takes one argument, a log message. A log
|
||||
message is an object (:mochiref:`LogMessage` instance) that has at least these
|
||||
properties:
|
||||
|
||||
``num``:
|
||||
A counter that uniquely identifies a log message (per-logger)
|
||||
|
||||
``level``:
|
||||
A string or number representing the log level. If string, you
|
||||
may want to use ``LogLevel[level]`` for comparison.
|
||||
|
||||
``info``:
|
||||
An Array of objects passed as additional arguments to the ``log``
|
||||
function.
|
||||
|
||||
|
||||
:mochidef:`Logger.prototype.baseLog(level, message[, ...])`:
|
||||
|
||||
The base functionality behind all of the log functions.
|
||||
The first argument is the log level as a string or number,
|
||||
and all other arguments are used as the info list.
|
||||
|
||||
This function is available partially applied as:
|
||||
|
||||
============== =========
|
||||
Logger.debug 'DEBUG'
|
||||
Logger.log 'INFO'
|
||||
Logger.error 'ERROR'
|
||||
Logger.fatal 'FATAL'
|
||||
Logger.warning 'WARNING'
|
||||
============== =========
|
||||
|
||||
For the default logger, these are also available as global functions,
|
||||
see the :mochiref:`Logger` constructor documentation for more info.
|
||||
|
||||
|
||||
:mochidef:`Logger.prototype.clear()`:
|
||||
|
||||
Clear all messages from the message buffer.
|
||||
|
||||
|
||||
:mochidef:`Logger.prototype.debuggingBookmarklet()`:
|
||||
|
||||
Display the contents of the logger in a useful way for browsers.
|
||||
|
||||
Currently, if :mochiref:`MochiKit.LoggingPane` is loaded, then a pop-up
|
||||
:mochiref:`MochiKit.LoggingPane.LoggingPane` will be used. Otherwise,
|
||||
it will be an alert with :mochiref:`Logger.prototype.getMessageText()`.
|
||||
|
||||
|
||||
:mochidef:`Logger.prototype.dispatchListeners(msg)`:
|
||||
|
||||
Dispatch a log message to all listeners.
|
||||
|
||||
|
||||
:mochidef:`Logger.prototype.getMessages(howMany)`:
|
||||
|
||||
Return a list of up to ``howMany`` messages from the message buffer.
|
||||
|
||||
|
||||
:mochidef:`Logger.prototype.getMessageText(howMany)`:
|
||||
|
||||
Get a string representing up to the last ``howMany`` messages in the
|
||||
message buffer. The default is ``30``.
|
||||
|
||||
The message looks like this::
|
||||
|
||||
LAST {messages.length} MESSAGES:
|
||||
[{msg.num}] {msg.level}: {m.info.join(' ')}
|
||||
[{msg.num}] {msg.level}: {m.info.join(' ')}
|
||||
...
|
||||
|
||||
If you want some other format, use
|
||||
:mochiref:`Logger.prototype.getMessages` and do it yourself.
|
||||
|
||||
|
||||
:mochidef:`Logger.prototype.removeListener(ident)`:
|
||||
|
||||
Remove a listener using the ident given to :mochiref:`Logger.prototype.addListener`
|
||||
|
||||
|
||||
Functions
|
||||
---------
|
||||
|
||||
:mochidef:`alertListener(msg)`:
|
||||
|
||||
Ultra-obnoxious ``alert(...)`` listener
|
||||
|
||||
|
||||
:mochidef:`logDebug(message[, info[, ...]])`:
|
||||
|
||||
Log an INFO message to the default logger
|
||||
|
||||
|
||||
:mochidef:`logDebug(message[, info[, ...]])`:
|
||||
|
||||
Log a DEBUG message to the default logger
|
||||
|
||||
|
||||
:mochidef:`logError(message[, info[, ...]])`:
|
||||
|
||||
Log an ERROR message to the default logger
|
||||
|
||||
|
||||
:mochidef:`logFatal(message[, info[, ...]])`:
|
||||
|
||||
Log a FATAL message to the default logger
|
||||
|
||||
|
||||
:mochidef:`logLevelAtLeast(minLevel)`:
|
||||
|
||||
Return a function that will match log messages whose level
|
||||
is at least minLevel
|
||||
|
||||
|
||||
:mochidef:`logWarning(message[, info[, ...]])`:
|
||||
|
||||
Log a WARNING message to the default logger
|
||||
|
||||
|
||||
See Also
|
||||
========
|
||||
|
||||
.. [1] Python's logging module: http://docs.python.org/lib/module-logging.html
|
||||
.. [2] PEP 282, where they admit all of the Java influence: http://www.python.org/peps/pep-0282.html
|
||||
.. [3] Original Bookmarklet Based Debugging blather: http://bob.pythonmac.org/archives/2005/07/03/bookmarklet-based-debugging/
|
||||
|
||||
|
||||
Authors
|
||||
=======
|
||||
|
||||
- Bob Ippolito <bob@redivi.com>
|
||||
|
||||
|
||||
Copyright
|
||||
=========
|
||||
|
||||
Copyright 2005 Bob Ippolito <bob@redivi.com>. This program is dual-licensed
|
||||
free software; you can redistribute it and/or modify it under the terms of the
|
||||
`MIT License`_ or the `Academic Free License v2.1`_.
|
||||
|
||||
.. _`MIT License`: http://www.opensource.org/licenses/mit-license.php
|
||||
.. _`Academic Free License v2.1`: http://www.opensource.org/licenses/afl-2.1.php
|
||||
@@ -1,114 +0,0 @@
|
||||
.. title:: MochiKit.LoggingPane - Interactive MochiKit.Logging pane
|
||||
|
||||
Name
|
||||
====
|
||||
|
||||
MochiKit.LoggingPane - Interactive MochiKit.Logging pane
|
||||
|
||||
|
||||
Synopsis
|
||||
========
|
||||
|
||||
::
|
||||
|
||||
// open a pop-up window
|
||||
createLoggingPane()
|
||||
// use a div at the bottom of the document
|
||||
createLoggingPane(true);
|
||||
|
||||
|
||||
Description
|
||||
===========
|
||||
|
||||
MochiKit.Logging does not have any browser dependencies and is completely
|
||||
unobtrusive. MochiKit.LoggingPane is a browser-based colored viewing pane
|
||||
for your :mochiref:`MochiKit.Logging` output that can be used as a pop-up or
|
||||
inline.
|
||||
|
||||
It also allows for regex and level filtering! MochiKit.LoggingPane is used
|
||||
as the default :mochiref:`MochiKit.Logging.debuggingBookmarklet()` if it is
|
||||
loaded.
|
||||
|
||||
|
||||
Dependencies
|
||||
============
|
||||
|
||||
- :mochiref:`MochiKit.Base`
|
||||
- :mochiref:`MochiKit.Logging`
|
||||
|
||||
|
||||
API Reference
|
||||
=============
|
||||
|
||||
Constructors
|
||||
------------
|
||||
|
||||
:mochidef:`LoggingPane(inline=false, logger=MochiKit.Logging.logger)`:
|
||||
|
||||
A listener for a :mochiref:`MochiKit.Logging` logger with an interactive
|
||||
DOM representation.
|
||||
|
||||
If ``inline`` is ``true``, then the ``LoggingPane`` will be a ``DIV``
|
||||
at the bottom of the document. Otherwise, it will be in a pop-up
|
||||
window with a name based on the calling page's URL. If there is an
|
||||
element in the document with an id of ``_MochiKit_LoggingPane``,
|
||||
it will be used instead of appending a new ``DIV`` to the body.
|
||||
|
||||
``logger`` is the reference to the :mochiref:`MochiKit.Logging.Logger` to
|
||||
listen to. If not specified, the global default logger is used.
|
||||
|
||||
Properties:
|
||||
|
||||
``win``:
|
||||
Reference to the pop-up window (``undefined`` if ``inline``)
|
||||
|
||||
``inline``:
|
||||
``true`` if the ``LoggingPane`` is inline
|
||||
|
||||
``colorTable``:
|
||||
An object with property->value mappings for each log level
|
||||
and its color. May also be mutated on ``LoggingPane.prototype``
|
||||
to affect all instances. For example::
|
||||
|
||||
MochiKit.LoggingPane.LoggingPane.prototype.colorTable = {
|
||||
DEBUG: "green",
|
||||
INFO: "black",
|
||||
WARNING: "blue",
|
||||
ERROR: "red",
|
||||
FATAL: "darkred"
|
||||
};
|
||||
|
||||
|
||||
:mochidef:`LoggingPane.prototype.closePane()`:
|
||||
|
||||
Close the :mochiref:`LoggingPane` (close the child window, or
|
||||
remove the ``_MochiKit_LoggingPane`` ``DIV`` from the document).
|
||||
|
||||
|
||||
Functions
|
||||
---------
|
||||
|
||||
|
||||
:mochidef:`createLoggingPane(inline=false)`:
|
||||
|
||||
Create or return an existing :mochiref:`LoggingPane` for this document
|
||||
with the given inline setting. This is preferred over using
|
||||
:mochiref:`LoggingPane` directly, as only one :mochiref:`LoggingPane`
|
||||
should be present in a given document.
|
||||
|
||||
|
||||
Authors
|
||||
=======
|
||||
|
||||
- Bob Ippolito <bob@redivi.com>
|
||||
|
||||
|
||||
Copyright
|
||||
=========
|
||||
|
||||
Copyright 2005 Bob Ippolito <bob@redivi.com>. This program is dual-licensed
|
||||
free software; you can redistribute it and/or modify it under the terms of the
|
||||
`MIT License`_ or the `Academic Free License v2.1`_.
|
||||
|
||||
.. _`MIT License`: http://www.opensource.org/licenses/mit-license.php
|
||||
.. _`Academic Free License v2.1`: http://www.opensource.org/licenses/afl-2.1.php
|
||||
@@ -1,349 +0,0 @@
|
||||
.. title:: MochiKit.Signal - Simple universal event handling
|
||||
.. |---| unicode:: U+2014 .. em dash, trimming surrounding whitespace
|
||||
:trim:
|
||||
|
||||
Name
|
||||
====
|
||||
|
||||
MochiKit.Signal - Simple universal event handling
|
||||
|
||||
|
||||
Synopsis
|
||||
========
|
||||
|
||||
Signal for DOM events::
|
||||
|
||||
// DOM events are also signals. Connect freely! The functions will be
|
||||
// called with the custom event as a parameter.
|
||||
|
||||
// calls myClicked.apply(getElement('myID'), event)
|
||||
connect('myID', 'onclick', myClicked);
|
||||
|
||||
// calls wasClicked.apply(myObject, event)
|
||||
connect('myID', 'onclick', myObject, wasClicked);
|
||||
|
||||
// calls myObject.wasClicked(event)
|
||||
connect('myID', 'onclick', myObject, 'wasClicked');
|
||||
|
||||
// the event is normalized, no more e = e || window.event!
|
||||
myObject.wasClicked = function(e) {
|
||||
var crossBrowserCoordinates = e.mouse().page;
|
||||
// e.mouse().page is a MochiKit.DOM.Coordinates object
|
||||
}
|
||||
|
||||
|
||||
Signal for non-DOM events::
|
||||
|
||||
// otherObject.gotFlash() will be called when 'flash' signalled.
|
||||
connect(myObject, 'flash', otherObject, 'gotFlash');
|
||||
|
||||
// gotBang.apply(otherObject) will be called when 'bang' signalled.
|
||||
// You can access otherObject from within gotBang as 'this'.
|
||||
connect(myObject, 'bang', otherObject, gotBang);
|
||||
|
||||
// myFunc.apply(myObject) will be called when 'flash' signalled.
|
||||
// You can access myObject from within myFunc as 'this'.
|
||||
var ident = connect(myObject, 'flash', myFunc);
|
||||
|
||||
// You may disconnect with the return value from connect
|
||||
disconnect(ident);
|
||||
|
||||
// Signal can take parameters. These will be passed along to the connected
|
||||
// functions.
|
||||
signal(myObject, 'flash');
|
||||
signal(myObject, 'bang', 'BANG!');
|
||||
|
||||
|
||||
Description
|
||||
===========
|
||||
|
||||
Event handling was never so easy!
|
||||
|
||||
This module takes care of all the hard work |---| figuring out which event
|
||||
model to use, trying to retrieve the event object, and handling your own
|
||||
internal events, as well as cleanup when the page is unloaded to clean up IE's
|
||||
nasty memory leakage.
|
||||
|
||||
This event system is largely based on Qt's signal/slot system. Read more on
|
||||
how that is handled and also how it is used in model/view programming at:
|
||||
http://doc.trolltech.com/
|
||||
|
||||
|
||||
Dependencies
|
||||
============
|
||||
|
||||
- :mochiref:`MochiKit.Base`
|
||||
- :mochiref:`MochiKit.DOM`
|
||||
|
||||
|
||||
Overview
|
||||
========
|
||||
|
||||
Using Signal for DOM Events
|
||||
---------------------------
|
||||
|
||||
When using MochiKit.Signal, do not use the browser's native event API. That
|
||||
means, no ``onclick="blah"``, no ``elem.addEventListener(...)``, and certainly
|
||||
no ``elem.attachEvent(...)``. This also means that
|
||||
:mochiref:`MochiKit.DOM.addToCallStack` and
|
||||
:mochiref:`MochiKit.DOM.addLoadEvent` should not be used in combination with
|
||||
this module.
|
||||
|
||||
Signals for DOM objects are named with the ``'on'`` prefix, e.g.:
|
||||
``'onclick'``, ``'onkeyup'``, etc.
|
||||
|
||||
When the signal fires, your slot will be called with one parameter, the custom
|
||||
event object.
|
||||
|
||||
|
||||
Custom Event Objects for DOM events
|
||||
-----------------------------------
|
||||
|
||||
Signals triggered by DOM events are called with a custom event object as a
|
||||
parameter. The custom event object presents a consistent view of the event
|
||||
across all supported platforms and browsers, and provides many conveniences
|
||||
not available even in a correct W3C implementation.
|
||||
|
||||
See the `DOM Custom Event Object Reference`_ for a detailed API description
|
||||
of this object.
|
||||
|
||||
If you find that you're accessing the native event for any reason, create a
|
||||
`new ticket`_ and we'll look into normalizing the behavior you're looking for.
|
||||
|
||||
.. _`new ticket`: http://trac.mochikit.com/newticket
|
||||
.. _`Safari bug 6595`: http://bugzilla.opendarwin.org/show_bug.cgi?id=6595
|
||||
.. _`Safari bug 7790`: http://bugzilla.opendarwin.org/show_bug.cgi?id=7790
|
||||
|
||||
|
||||
Memory Usage
|
||||
------------
|
||||
|
||||
Any object that has connected slots (via :mochiref:`connect()`) is referenced
|
||||
by the Signal mechanism until it is disconnected via :mochiref:`disconnect()`
|
||||
or :mochiref:`disconnectAll()`.
|
||||
|
||||
Signal does not leak. It registers an ``'onunload'`` event that disconnects all
|
||||
objects on the page when the browser leaves the page. However, memory usage
|
||||
will grow during the page view for every connection made until it is
|
||||
disconnected. Even if the DOM object is removed from the document, it
|
||||
will still be referenced by Signal until it is explicitly disconnected.
|
||||
|
||||
In order to conserve memory during the page view, :mochiref:`disconnectAll()`
|
||||
any DOM elements that are about to be removed from the document.
|
||||
|
||||
|
||||
Using Signal for non-DOM objects
|
||||
--------------------------------
|
||||
|
||||
Signals are triggered with the :mochiref:`signal(src, 'signal', ...)`
|
||||
function. Additional parameters passed to this are passed onto the
|
||||
connected slots. Explicit signals are not required for DOM events.
|
||||
|
||||
Slots that are connected to a signal are called in the following manner
|
||||
when that signal is signalled:
|
||||
|
||||
- If the slot was a single function, then it is called with ``this`` set
|
||||
to the object originating the signal with whatever parameters it was
|
||||
signalled with.
|
||||
|
||||
- If the slot was an object and a function, then it is called with
|
||||
``this`` set to the object, and with whatever parameters it was
|
||||
signalled with.
|
||||
|
||||
- If the slot was an object and a string, then ``object[string]`` is
|
||||
called with the parameters to the signal.
|
||||
|
||||
|
||||
API Reference
|
||||
=============
|
||||
|
||||
|
||||
Signal API Reference
|
||||
--------------------
|
||||
|
||||
:mochidef:`connect(src, signal, dest[, func])`:
|
||||
|
||||
Connects a signal to a slot, and return a unique identifier that can be
|
||||
used to disconnect that signal.
|
||||
|
||||
``src`` is the object that has the signal. You may pass in a string, in
|
||||
which case, it is interpreted as an id for an HTML element.
|
||||
|
||||
``signal`` is a string that represents a signal name. If 'src' is an HTML
|
||||
Element, ``window``, or the ``document``, then it can be one of the
|
||||
'on-XYZ' events. You must include the 'on' prefix, and it must be all
|
||||
lower-case.
|
||||
|
||||
``dest`` and ``func`` describe the slot, or the action to take when the
|
||||
signal is triggered.
|
||||
|
||||
- If ``dest`` is an object and ``func`` is a string, then
|
||||
``dest[func].apply(dest, ...)`` will be called when the signal
|
||||
is signalled.
|
||||
|
||||
- If ``dest`` is an object and ``func`` is a function, then
|
||||
``func.apply(dest, ...)`` will be called when the signal is
|
||||
signalled.
|
||||
|
||||
- If ``func`` is undefined and ``dest`` is a function, then
|
||||
``func.apply(src, ...)`` will be called when the signal is
|
||||
signalled.
|
||||
|
||||
No other combinations are allowed and will raise an exception.
|
||||
|
||||
The return value can be passed to :mochiref:`disconnect` to disconnect
|
||||
the signal.
|
||||
|
||||
|
||||
:mochidef:`disconnect(ident)`:
|
||||
|
||||
To disconnect a signal, pass its ident returned by :mochiref:`connect()`.
|
||||
This is similar to how the browser's ``setTimeout`` and ``clearTimeout``
|
||||
works.
|
||||
|
||||
|
||||
:mochidef:`disconnectAll(src[, signal, ...])`:
|
||||
|
||||
``disconnectAll(src)`` removes all signals from src.
|
||||
|
||||
``disconnectAll(src, 'onmousedown', 'mySignal')`` will remove all
|
||||
``'onmousedown'`` and ``'mySignal'`` signals from src.
|
||||
|
||||
|
||||
|
||||
:mochidef:`signal(src, signal, ...)`:
|
||||
|
||||
This will signal a signal, passing whatever additional parameters on to
|
||||
the connected slots. ``src`` and ``signal`` are the same as for
|
||||
:mochiref:`connect()`.
|
||||
|
||||
|
||||
DOM Custom Event Object Reference
|
||||
---------------------------------
|
||||
|
||||
:mochidef:`event()`:
|
||||
|
||||
The native event produced by the browser. You should not need to use this.
|
||||
|
||||
|
||||
:mochidef:`src()`:
|
||||
|
||||
The element that this signal is connected to.
|
||||
|
||||
|
||||
:mochidef:`type()`:
|
||||
|
||||
The event type (``'click'``, ``'mouseover'``, ``'keypress'``, etc.) as a
|
||||
string. Does not include the ``'on'`` prefix.
|
||||
|
||||
|
||||
:mochidef:`target()`:
|
||||
|
||||
The element that triggered the event. This may be a child of
|
||||
:mochiref:`src()`.
|
||||
|
||||
|
||||
:mochidef:`modifier()`:
|
||||
|
||||
Returns ``{shift, ctrl, meta, alt, any}``, where each property is ``true``
|
||||
if its respective modifier key was pressed, ``false`` otherwise. ``any``
|
||||
is ``true`` if any modifier is pressed, ``false`` otherwise.
|
||||
|
||||
|
||||
:mochidef:`stopPropagation()`:
|
||||
|
||||
Works like W3C's ``stopPropagation()``.
|
||||
|
||||
|
||||
:mochidef:`preventDefault()`:
|
||||
|
||||
Works like W3C's ``preventDefault()``.
|
||||
|
||||
|
||||
:mochidef:`stop()`:
|
||||
|
||||
Shortcut that calls ``stopPropagation()`` and ``preventDefault()``.
|
||||
|
||||
|
||||
:mochidef:`key()`:
|
||||
|
||||
Returns ``{code, string}``.
|
||||
|
||||
Use ``'onkeydown'`` and ``'onkeyup'`` handlers to detect control
|
||||
characters such as ``'KEY_F1'``. Use the ``'onkeypressed'`` handler to
|
||||
detect "printable" characters, such as ``'é'``.
|
||||
|
||||
When a user presses F1, in ``'onkeydown'`` and ``'onkeyup'`` this method
|
||||
returns ``{code: 122, string: 'KEY_F1'}``. In ``'onkeypress'``, it returns
|
||||
``{code: 0, string: ''}``.
|
||||
|
||||
If a user presses Shift+2 on a US keyboard, this method returns
|
||||
``{code: 50, string: 'KEY_2'}`` in ``'onkeydown'`` and ``'onkeyup'``.
|
||||
In ``'onkeypress'``, it returns ``{code: 64, string: '@'}``.
|
||||
|
||||
See ``_specialKeys`` in the source code for a comprehensive list of
|
||||
control characters.
|
||||
|
||||
|
||||
:mochidef:`mouse()`:
|
||||
|
||||
Properties for ``'onmouse*'``, ``'onclick'``, ``'ondblclick'``, and
|
||||
``'oncontextmenu'``:
|
||||
|
||||
- ``page`` is a :mochiref:`MochiKit.DOM.Coordinates` object that
|
||||
represents the cursor position relative to the HTML document.
|
||||
Equivalent to ``pageX`` and ``pageY`` in Safari, Mozilla, and
|
||||
Opera.
|
||||
|
||||
- ``client`` is a :mochiref:`MochiKit.DOM.Coordinates` object that
|
||||
represents the cursor position relative to the visible portion of
|
||||
the HTML document. Equivalent to ``clientX`` and ``clientY`` on
|
||||
all browsers.
|
||||
|
||||
Properties for ``'onmouseup'``, ``'onmousedown'``, ``'onclick'``, and
|
||||
``'ondblclick'``:
|
||||
|
||||
- ``mouse().button`` returns ``{left, right, middle}`` where each
|
||||
property is ``true`` if the mouse button was pressed, ``false``
|
||||
otherwise.
|
||||
|
||||
Known browser bugs:
|
||||
|
||||
- Current versions of Safari won't signal ``'ondblclick'`` when
|
||||
attached via ``connect()`` (`Safari Bug 7790`_).
|
||||
|
||||
- Mac browsers don't report right-click consistently. Firefox
|
||||
signals the slot and sets ``modifier().ctrl`` to true, Opera
|
||||
signals the slot and sets ``modifier().meta`` to ``true``, and
|
||||
Safari doesn't signal the slot at all (`Safari Bug 6595`_).
|
||||
|
||||
To find a right-click in Safari, Firefox, and IE, you can connect
|
||||
an element to ``'oncontextmenu'``. This doesn't work in Opera.
|
||||
|
||||
|
||||
:mochidef:`relatedTarget()`:
|
||||
|
||||
Returns the document element that the mouse has moved to. This is
|
||||
generated for ``'onmouseover'`` and ``'onmouseout'`` events.
|
||||
|
||||
|
||||
|
||||
Authors
|
||||
=======
|
||||
|
||||
- Jonathan Gardner <jgardner@jonathangardner.net>
|
||||
- Beau Hartshorne <beau@hartshornesoftware.com>
|
||||
- Bob Ippolito <bob@redivi.com>
|
||||
|
||||
|
||||
Copyright
|
||||
=========
|
||||
|
||||
Copyright 2006 Jonathan Gardner <jgardner@jonathangardner.net>, Beau
|
||||
Hartshorne <beau@hartshornesoftware.com>, and Bob Ippolito <bob@redivi.com>.
|
||||
This program is dual-licensed free software; you can redistribute it and/or
|
||||
modify it under the terms of the `MIT License`_ or the
|
||||
`Academic Free License v2.1`_.
|
||||
|
||||
.. _`MIT License`: http://www.opensource.org/licenses/mit-license.php
|
||||
.. _`Academic Free License v2.1`: http://www.opensource.org/licenses/afl-2.1.php
|
||||
@@ -1,244 +0,0 @@
|
||||
2006-04-29 v1.3.1 (bug fix release)
|
||||
|
||||
- Fix sendXMLHttpRequest sendContent regression
|
||||
- Internet Explorer fix in MochiKit.Logging (printfire exception)
|
||||
- Internet Explorer XMLHttpRequest object leak fixed in MochiKit.Async
|
||||
|
||||
2006-04-26 v1.3 "warp zone"
|
||||
|
||||
- IMPORTANT: Renamed MochiKit.Base.forward to forwardCall (for export)
|
||||
- IMPORTANT: Renamed MochiKit.Base.find to findValue (for export)
|
||||
- New MochiKit.Base.method as a convenience form of bind that takes the
|
||||
object before the method
|
||||
- New MochiKit.Base.flattenArguments for flattening a list of arguments to
|
||||
a single Array
|
||||
- Refactored MochiRegExp example to use MochiKit.Signal
|
||||
- New key_events example demonstrating use of MochiKit.Signal's key handling
|
||||
capabilities.
|
||||
- MochiKit.DOM.createDOM API change for convenience: if attrs is a string,
|
||||
null is used and the string will be considered the first node. This
|
||||
allows for the more natural P("foo") rather than P(null, "foo").
|
||||
- MochiKit Interpreter example refactored to use MochiKit.Signal and now
|
||||
provides multi-line input and a help() function to get MochiKit function
|
||||
signature from the documentation.
|
||||
- Native Console Logging for the default MochiKit.Logging logger
|
||||
- New MochiKit.Async.DeferredList, gatherResults, maybeDeferred
|
||||
- New MochiKit.Signal example: draggable
|
||||
- Added sanity checking to Deferred to ensure that errors happen when chaining
|
||||
is used incorrectly
|
||||
- Opera sendXMLHttpRequest fix (sends empty string instead of null by default)
|
||||
- Fix a bug in MochiKit.Color that incorrectly generated hex colors for
|
||||
component values smaller than 16/255.
|
||||
- Fix a bug in MochiKit.Logging that prevented logs from being capped at a
|
||||
maximum size
|
||||
- MochiKit.Async.Deferred will now wrap thrown objects that are not instanceof
|
||||
Error, so that the errback chain is used instead of the callback chain.
|
||||
- MochiKit.DOM.appendChildNodes and associated functions now append iterables
|
||||
in the correct order.
|
||||
- New MochiKit-based SimpleTest test runner as a replacement for Test.Simple
|
||||
- MochiKit.Base.isNull no longer matches undefined
|
||||
- example doctypes changed to HTML4
|
||||
- isDateLike no longer throws error on null
|
||||
- New MochiKit.Signal module, modeled after the slot/signal mechanism in Qt
|
||||
- updated elementDimensions to calculate width from offsetWidth instead
|
||||
of clientWidth
|
||||
- formContents now works with FORM tags that have a name attribute
|
||||
- Documentation now uses MochiKit to generate a function index
|
||||
|
||||
2006-01-26 v1.2 "the ocho"
|
||||
|
||||
- Fixed MochiKit.Color.Color.lighterColorWithLevel
|
||||
- Added new MochiKit.Base.findIdentical function to find the index of an
|
||||
element in an Array-like object. Uses === for identity comparison.
|
||||
- Added new MochiKit.Base.find function to find the index of an element in
|
||||
an Array-like object. Uses compare for rich comparison.
|
||||
- MochiKit.Base.bind will accept a string for func, which will be immediately
|
||||
looked up as self[func].
|
||||
- MochiKit.DOM.formContents no longer skips empty form elements for Zope
|
||||
compatibility
|
||||
- MochiKit.Iter.forEach will now catch StopIteration to break
|
||||
- New MochiKit.DOM.elementDimensions(element) for determining the width and
|
||||
height of an element in the document
|
||||
- MochiKit.DOM's initialization is now compatible with
|
||||
HTMLUnit + JWebUnit + Rhino
|
||||
- MochiKit.LoggingPane will now re-use a ``_MochiKit_LoggingPane`` DIV element
|
||||
currently in the document instead of always creating one.
|
||||
- MochiKit.Base now has operator.mul
|
||||
- MochiKit.DOM.formContents correctly handles unchecked checkboxes that have
|
||||
a custom value attribute
|
||||
- Added new MochiKit.Color constructors fromComputedStyle and fromText
|
||||
- MochiKit.DOM.setNodeAttribute should work now
|
||||
- MochiKit.DOM now has a workaround for an IE bug when setting the style
|
||||
property to a string
|
||||
- MochiKit.DOM.createDOM now has workarounds for IE bugs when setting the
|
||||
name and for properties
|
||||
- MochiKit.DOM.scrapeText now walks the DOM tree in-order
|
||||
- MochiKit.LoggingPane now sanitizes the window name to work around IE bug
|
||||
- MochiKit.DOM now translates usemap to useMap to work around IE bug
|
||||
- MochiKit.Logging is now resistant to Prototype's dumb Object.prototype hacks
|
||||
- Added new MochiKit.DOM documentation on element visibility
|
||||
- New MochiKit.DOM.elementPosition(element[, relativeTo={x: 0, y: 0}])
|
||||
for determining the position of an element in the document
|
||||
- Added new MochiKit.DOM createDOMFunc aliases: CANVAS, STRONG
|
||||
|
||||
2005-11-14 v1.1
|
||||
|
||||
- Fixed a bug in numberFormatter with large numbers
|
||||
- Massively overhauled documentation
|
||||
- Fast-path for primitives in MochiKit.Base.compare
|
||||
- New groupby and groupby_as_array in MochiKit.Iter
|
||||
- Added iterator factory adapter for objects that implement iterateNext()
|
||||
- Fixed isoTimestamp to handle timestamps with time zone correctly
|
||||
- Added new MochiKit.DOM createDOMFunc aliases: SELECT, OPTION, OPTGROUP,
|
||||
LEGEND, FIELDSET
|
||||
- New MochiKit.DOM formContents and enhancement to queryString to support it
|
||||
- Updated view_source example to use dp.SyntaxHighlighter 1.3.0
|
||||
- MochiKit.LoggingPane now uses named windows based on the URL so that
|
||||
a given URL will get the same LoggingPane window after a reload
|
||||
(at the same position, etc.)
|
||||
- MochiKit.DOM now has currentWindow() and currentDocument() context
|
||||
variables that are set with withWindow() and withDocument(). These
|
||||
context variables affect all MochiKit.DOM functionality (getElement,
|
||||
createDOM, etc.)
|
||||
- MochiKit.Base.items will now catch and ignore exceptions for properties
|
||||
that are enumerable but not accessible (e.g. permission denied)
|
||||
- MochiKit.Async.Deferred's addCallback/addErrback/addBoth
|
||||
now accept additional arguments that are used to create a partially
|
||||
applied function. This differs from Twisted in that the callback/errback
|
||||
result becomes the *last* argument, not the first when this feature
|
||||
is used.
|
||||
- MochiKit.Async's doSimpleXMLHttpRequest will now accept additional
|
||||
arguments which are used to create a GET query string
|
||||
- Did some refactoring to reduce the footprint of MochiKit by a few
|
||||
kilobytes
|
||||
- escapeHTML to longer escapes ' (apos) and now uses
|
||||
String.replace instead of iterating over every char.
|
||||
- Added DeferredLock to Async
|
||||
- Renamed getElementsComputedStyle to computedStyle and moved
|
||||
it from MochiKit.Visual to MochiKit.DOM
|
||||
- Moved all color support out of MochiKit.Visual and into MochiKit.Color
|
||||
- Fixed range() to accept a negative step
|
||||
- New alias to MochiKit.swapDOM called removeElement
|
||||
- New MochiKit.DOM.setNodeAttribute(node, attr, value) which sets
|
||||
an attribute on a node without raising, roughly equivalent to:
|
||||
updateNodeAttributes(node, {attr: value})
|
||||
- New MochiKit.DOM.getNodeAttribute(node, attr) which gets the value of
|
||||
a node's attribute or returns null without raising
|
||||
- Fixed a potential IE memory leak if using MochiKit.DOM.addToCallStack
|
||||
directly (addLoadEvent did not leak, since it clears the handler)
|
||||
|
||||
2005-10-24 v1.0
|
||||
|
||||
- New interpreter example that shows usage of MochiKit.DOM to make
|
||||
an interactive JavaScript interpreter
|
||||
- New MochiKit.LoggingPane for use with the MochiKit.Logging
|
||||
debuggingBookmarklet, with logging_pane example to show its usage
|
||||
- New mochiregexp example that demonstrates MochiKit.DOM and MochiKit.Async
|
||||
in order to provide a live regular expression matching tool
|
||||
- Added advanced number formatting capabilities to MochiKit.Format:
|
||||
numberFormatter(pattern, placeholder="", locale="default") and
|
||||
formatLocale(locale="default")
|
||||
- Added updatetree(self, obj[, ...]) to MochiKit.Base, and changed
|
||||
MochiKit.DOM's updateNodeAttributes(node, attrs) to use it when appropiate.
|
||||
- Added new MochiKit.DOM createDOMFunc aliases: BUTTON, TT, PRE
|
||||
- Added truncToFixed(aNumber, precision) and roundToFixed(aNumber, precision)
|
||||
to MochiKit.Format
|
||||
- MochiKit.DateTime can now handle full ISO 8601 timestamps, specifically
|
||||
isoTimestamp(isoString) will convert them to Date objects, and
|
||||
toISOTimestamp(date, true) will return an ISO 8601 timestamp in UTC
|
||||
- Fixed missing errback for sendXMLHttpRequest when the server does not
|
||||
respond
|
||||
- Fixed infinite recusion bug when using roundClass("DIV", ...)
|
||||
- Fixed a bug in MochiKit.Async wait (and callLater) that prevented them
|
||||
from being cancelled properly
|
||||
- Workaround in MochiKit.Base bind (and partial) for functions that don't
|
||||
have an apply method, such as alert
|
||||
- Reliably return null from the string parsing/manipulation functions if
|
||||
the input can't be coerced to a string (s + "") or the input makes no sense;
|
||||
e.g. isoTimestamp(null) and isoTimestamp("") return null
|
||||
|
||||
2005-10-08 v0.90
|
||||
|
||||
- Fixed ISO compliance with toISODate
|
||||
- Added missing operator.sub
|
||||
- Placated Mozilla's strict warnings a bit
|
||||
- Added JSON serialization and unserialization support to MochiKit.Base:
|
||||
serializeJSON, evalJSON, registerJSON. This is very similar to the repr
|
||||
API.
|
||||
- Fixed a bug in the script loader that failed in some scenarios when a script
|
||||
tag did not have a "src" attribute (thanks Ian!)
|
||||
- Added new MochiKit.DOM createDOMFunc aliases: H1, H2, H3, BR, HR, TEXTAREA,
|
||||
P, FORM
|
||||
- Use encodeURIComponent / decodeURIComponent for MochiKit.Base urlEncode
|
||||
and parseQueryString, when available.
|
||||
|
||||
2005-08-12 v0.80
|
||||
|
||||
- Source highlighting in all examples, moved to a view-source example
|
||||
- Added some experimental syntax highlighting for the Rounded Corners example,
|
||||
via the LGPL dp.SyntaxHighlighter 1.2.0 now included in examples/common/lib
|
||||
- Use an indirect binding for the logger conveniences, so that the global
|
||||
logger could be replaced by setting MochiKit.Logger.logger to something else
|
||||
(though an observer is probably a better choice).
|
||||
- Allow MochiKit.DOM.getElementsByTagAndClassName to take a string for parent,
|
||||
which will be looked up with getElement
|
||||
- Fixed bug in MochiKit.Color.fromBackground (was using node.parent instead of
|
||||
node.parentNode)
|
||||
- Consider a 304 (NOT_MODIFIED) response from XMLHttpRequest to be success
|
||||
- Disabled Mozilla map(...) fast-path due to Deer Park compatibility issues
|
||||
- Possible workaround for Safari issue with swapDOM, where it would get
|
||||
confused because two elements were in the DOM at the same time with the
|
||||
same id
|
||||
- Added missing THEAD convenience function to MochiKit.DOM
|
||||
- Added lstrip, rstrip, strip to MochiKit.Format
|
||||
- Added updateNodeAttributes, appendChildNodes, replaceChildNodes to
|
||||
MochiKit.DOM
|
||||
- MochiKit.Iter.iextend now has a fast-path for array-like objects
|
||||
- Added HSV color space support to MochiKit.Visual
|
||||
- Fixed a bug in the sortable_tables example, it now converts types
|
||||
correctly
|
||||
- Fixed a bug where MochiKit.DOM referenced MochiKit.Iter.next from global
|
||||
scope
|
||||
|
||||
2005-08-04 v0.70
|
||||
|
||||
- New ajax_tables example, which shows off XMLHttpRequest, ajax, json, and
|
||||
a little TAL-ish DOM templating attribute language.
|
||||
- sendXMLHttpRequest and functions that use it (loadJSONDoc, etc.) no longer
|
||||
ignore requests with status == 0, which seems to happen for cached or local
|
||||
requests
|
||||
- Added sendXMLHttpRequest to MochiKit.Async.EXPORT, d'oh.
|
||||
- Changed scrapeText API to return a string by default. This is API-breaking!
|
||||
It was dumb to have the default return value be the form you almost never
|
||||
want. Sorry.
|
||||
- Added special form to swapDOM(dest, src). If src is null, dest is removed
|
||||
(where previously you'd likely get a DOM exception).
|
||||
- Added three new functions to MochiKit.Base for dealing with URL query
|
||||
strings: urlEncode, queryString, parseQueryString
|
||||
- MochiKit.DOM.createDOM will now use attr[k] = v for all browsers if the name
|
||||
starts with "on" (e.g. "onclick"). If v is a string, it will set it to
|
||||
new Function(v).
|
||||
- Another workaround for Internet "worst browser ever" Explorer's setAttribute
|
||||
usage in MochiKit.DOM.createDOM (checked -> defaultChecked).
|
||||
- Added UL, OL, LI convenience createDOM aliases to MochiKit.DOM
|
||||
- Packing is now done by Dojo's custom Rhino interpreter, so it's much smaller
|
||||
now!
|
||||
|
||||
2005-07-29 v0.60
|
||||
|
||||
- Beefed up the MochiKit.DOM test suite
|
||||
- Fixed return value for MochiKit.DOM.swapElementClass, could return
|
||||
false unexpectedly before
|
||||
- Added an optional "parent" argument to
|
||||
MochiKit.DOM.getElementsByTagAndClassName
|
||||
- Added a "packed" version in packed/MochiKit/MochiKit.js
|
||||
- Changed build script to rewrite the URLs in tests to account for the
|
||||
JSAN-required reorganization
|
||||
- MochiKit.Compat to potentially work around IE 5.5 issues
|
||||
(5.0 still not supported). Test.Simple doesn't seem to work there,
|
||||
though.
|
||||
- Several minor documentation corrections
|
||||
|
||||
2005-07-27 v0.50
|
||||
|
||||
- Initial Release
|
||||
@@ -1,127 +0,0 @@
|
||||
.. title:: MochiKit.Visual - visual effects
|
||||
|
||||
Name
|
||||
====
|
||||
|
||||
MochiKit.Visual - visual effects
|
||||
|
||||
|
||||
Synopsis
|
||||
========
|
||||
|
||||
::
|
||||
|
||||
// round the corners of all h1 elements
|
||||
roundClass("h1", null);
|
||||
|
||||
// round the top left corner of the element with the id "title"
|
||||
roundElement("title", {corners: "tl"});
|
||||
|
||||
|
||||
Description
|
||||
===========
|
||||
|
||||
MochiKit.Visual provides visual effects and support functions for visuals.
|
||||
|
||||
|
||||
Dependencies
|
||||
============
|
||||
|
||||
- :mochiref:`MochiKit.Base`
|
||||
- :mochiref:`MochiKit.Iter`
|
||||
- :mochiref:`MochiKit.DOM`
|
||||
- :mochiref:`MochiKit.Color`
|
||||
|
||||
Overview
|
||||
========
|
||||
|
||||
At this time, MochiKit.Visual provides one visual effect: rounded corners
|
||||
for your HTML elements. These rounded corners are created completely
|
||||
through CSS manipulations and require no external images or style sheets.
|
||||
This implementation was adapted from Rico_.
|
||||
|
||||
.. _Rico: http://www.openrico.org
|
||||
|
||||
|
||||
API Reference
|
||||
=============
|
||||
|
||||
Functions
|
||||
---------
|
||||
|
||||
:mochidef:`roundClass(tagName[, className[, options]])`:
|
||||
|
||||
Rounds all of the elements that match the ``tagName`` and ``className``
|
||||
specifiers, using the options provided. ``tagName`` or ``className`` can
|
||||
be ``null`` to match all tags or classes. For more information about
|
||||
the options, see the :mochiref:`roundElement` function.
|
||||
|
||||
|
||||
:mochidef:`roundElement(element[, options])`:
|
||||
|
||||
Immediately round the corners of the specified element.
|
||||
The element can be given as either a string
|
||||
with the element ID, or as an element object.
|
||||
|
||||
The options mapping has the following defaults:
|
||||
|
||||
========= =================
|
||||
corners ``"all"``
|
||||
color ``"fromElement"``
|
||||
bgColor ``"fromParent"``
|
||||
blend ``true``
|
||||
border ``false``
|
||||
compact ``false``
|
||||
========= =================
|
||||
|
||||
corners:
|
||||
|
||||
specifies which corners of the element should be rounded.
|
||||
Choices are:
|
||||
|
||||
- all
|
||||
- top
|
||||
- bottom
|
||||
- tl (top left)
|
||||
- bl (bottom left)
|
||||
- tr (top right)
|
||||
- br (bottom right)
|
||||
|
||||
Example:
|
||||
``"tl br"``: top-left and bottom-right corners are rounded
|
||||
|
||||
blend:
|
||||
specifies whether the color and background color should be blended
|
||||
together to produce the border color.
|
||||
|
||||
|
||||
See Also
|
||||
========
|
||||
|
||||
.. [1] Application Kit Reference - NSColor: http://developer.apple.com/documentation/Cocoa/Reference/ApplicationKit/ObjC_classic/Classes/NSColor.html
|
||||
.. [2] SVG 1.0 color keywords: http://www.w3.org/TR/SVG/types.html#ColorKeywords
|
||||
.. [3] W3C CSS3 Color Module: http://www.w3.org/TR/css3-color/#svg-color
|
||||
|
||||
|
||||
Authors
|
||||
=======
|
||||
|
||||
- Kevin Dangoor <dangoor@gmail.com>
|
||||
- Bob Ippolito <bob@redivi.com>
|
||||
- Originally adapted from Rico <http://openrico.org/> (though little remains)
|
||||
|
||||
|
||||
Copyright
|
||||
=========
|
||||
|
||||
Copyright 2005 Bob Ippolito <bob@redivi.com>. This program is dual-licensed
|
||||
free software; you can redistribute it and/or modify it under the terms of the
|
||||
`MIT License`_ or the `Academic Free License v2.1`_.
|
||||
|
||||
.. _`MIT License`: http://www.opensource.org/licenses/mit-license.php
|
||||
.. _`Academic Free License v2.1`: http://www.opensource.org/licenses/afl-2.1.php
|
||||
|
||||
Portions adapted from `Rico`_ are available under the terms of the
|
||||
`Apache License, Version 2.0`_.
|
||||
|
||||
.. _`Apache License, Version 2.0`: http://www.apache.org/licenses/LICENSE-2.0.html
|
||||
@@ -1,74 +0,0 @@
|
||||
.. title:: MochiKit Documentation Index
|
||||
|
||||
Distribution
|
||||
============
|
||||
|
||||
MochiKit - makes JavaScript suck a bit less
|
||||
|
||||
- :mochiref:`MochiKit.Async` - manage asynchronous tasks
|
||||
- :mochiref:`MochiKit.Base` - functional programming and useful comparisons
|
||||
- :mochiref:`MochiKit.DOM` - painless DOM manipulation API
|
||||
- :mochiref:`MochiKit.Color` - color abstraction with CSS3 support
|
||||
- :mochiref:`MochiKit.DateTime` - "what time is it anyway?"
|
||||
- :mochiref:`MochiKit.Format` - string formatting goes here
|
||||
- :mochiref:`MochiKit.Iter` - itertools for JavaScript; iteration made HARD,
|
||||
and then easy
|
||||
- :mochiref:`MochiKit.Logging` - we're all tired of ``alert()``
|
||||
- :mochiref:`MochiKit.LoggingPane` - interactive :mochiref:`MochiKit.Logging`
|
||||
pane
|
||||
- :mochiref:`MochiKit.Signal` - simple universal event handling
|
||||
- :mochiref:`MochiKit.Visual` - visual effects
|
||||
|
||||
|
||||
Notes
|
||||
=====
|
||||
|
||||
To turn on MochiKit's compatibility mode, do this before loading MochiKit::
|
||||
|
||||
<script type="text/javascript">MochiKit = {__compat__: true};</script>
|
||||
|
||||
When compatibility mode is on, you must use fully qualified names for all
|
||||
MochiKit functions (e.g. ``MochiKit.Base.map(...)``).
|
||||
|
||||
|
||||
Screencasts
|
||||
===========
|
||||
|
||||
- `MochiKit 1.1 Intro`__
|
||||
|
||||
.. __: http://mochikit.com/screencasts/MochiKit_Intro-1
|
||||
|
||||
See Also
|
||||
========
|
||||
|
||||
.. _`mochikit.com`: http://mochikit.com/
|
||||
.. _`from __future__ import *`: http://bob.pythonmac.org/
|
||||
.. _`MochiKit on JSAN`: http://openjsan.org/doc/b/bo/bob/MochiKit/
|
||||
.. _`MochiKit tag on del.icio.us`: http://del.icio.us/tag/mochikit
|
||||
.. _`MochiKit tag on Technorati`: http://technorati.com/tag/mochikit
|
||||
.. _`Google Groups: MochiKit`: http://groups.google.com/group/mochikit
|
||||
|
||||
- `Google Groups: MochiKit`_: The official mailing list for discussions
|
||||
related to development of and with MochiKit
|
||||
- `mochikit.com`_: MochiKit's home on the web
|
||||
- `from __future__ import *`_: Bob Ippolito's blog
|
||||
- `MochiKit on JSAN`_: the JSAN distribution page for MochiKit
|
||||
- `MochiKit tag on del.icio.us`_: Recent bookmarks related to MochiKit
|
||||
- `MochiKit tag on Technorati`_: Recent blog entries related to MochiKit
|
||||
|
||||
|
||||
Version History
|
||||
===============
|
||||
|
||||
.. include:: VersionHistory.rst
|
||||
|
||||
|
||||
Copyright
|
||||
=========
|
||||
|
||||
Copyright 2005 Bob Ippolito <bob@redivi.com>. This program is dual-licensed
|
||||
free software; you can redistribute it and/or modify it under the terms of the
|
||||
`MIT License`_ or the `Academic Free License v2.1`_.
|
||||
|
||||
.. _`MIT License`: http://www.opensource.org/licenses/mit-license.php
|
||||
.. _`Academic Free License v2.1`: http://www.opensource.org/licenses/afl-2.1.php
|
||||
@@ -1,69 +0,0 @@
|
||||
h1 {
|
||||
font-size: 2em;
|
||||
color: #4B4545;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
table.datagrid {
|
||||
width: 100%;
|
||||
border-collapse: collapse;
|
||||
}
|
||||
|
||||
table.datagrid thead th {
|
||||
text-align: left;
|
||||
background-color: #4B4545;
|
||||
background-repeat: no-repeat;
|
||||
background-position: right center;
|
||||
color: white;
|
||||
font-weight: bold;
|
||||
padding: .3em .7em;
|
||||
font-size: .9em;
|
||||
padding-right: 5px;
|
||||
background-repeat: no-repeat;
|
||||
background-position: 95% right;
|
||||
}
|
||||
|
||||
table.datagrid thead th a {
|
||||
color: white;
|
||||
text-decoration: none;
|
||||
font-size: 1.0em;
|
||||
background-repeat: no-repeat;
|
||||
background-position: center right;
|
||||
padding-right: 15px;
|
||||
}
|
||||
|
||||
table.datagrid thead th.over {
|
||||
background-color: #746B6B;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
table.datagrid tbody th {
|
||||
font-weight: bold;
|
||||
}
|
||||
|
||||
table.datagrid tbody td, table.datagrid tbody th {
|
||||
text-align: left;
|
||||
padding: .3em .7em;
|
||||
border-bottom: 1px solid #eee;
|
||||
}
|
||||
|
||||
table.datagrid tbody tr.alternate td, table.datagrid tbody tr.alternate th {
|
||||
background-color: #f1f1f1;
|
||||
}
|
||||
|
||||
table.datagrid tfoot td, table.datagrid tfoot th {
|
||||
background-color: #FFFEE3;
|
||||
color: #4B4545;
|
||||
padding: .5em;
|
||||
font-weight: bold;
|
||||
border-top: 2px solid #4B4545;
|
||||
}
|
||||
|
||||
table.datagrid tfoot th { text-align: left; }
|
||||
|
||||
table.datagrid tfoot td { }
|
||||
|
||||
.invisible { display: none; }
|
||||
|
||||
.mochi-template { display: none; }
|
||||
.mochi-example { display: none; }
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user