repo_name stringlengths 4 116 | path stringlengths 4 379 | size stringlengths 1 7 | content stringlengths 3 1.05M | license stringclasses 15
values |
|---|---|---|---|---|
youtube/cobalt | third_party/llvm-project/clang/test/OpenMP/parallel_firstprivate_codegen.cpp | 29411 | // RUN: %clang_cc1 -verify -fopenmp -x c++ -triple i386-pc-linux-gnu -emit-llvm %s -o - | FileCheck %s -check-prefix=CHECK -check-prefix=CHECK-32
// RUN: %clang_cc1 -fopenmp -x c++ -std=c++11 -triple i386-pc-linux-gnu -emit-pch -o %t %s
// RUN: %clang_cc1 -fopenmp -x c++ -triple i386-pc-linux-gnu -std=c++11 -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s -check-prefix=CHECK -check-prefix=CHECK-32
// RUN: %clang_cc1 -verify -fopenmp -x c++ -std=c++11 -DLAMBDA -triple i386-pc-linux-gnu -emit-llvm %s -o - | FileCheck -check-prefix=LAMBDA -check-prefix=LAMBDA-32 %s
// RUN: %clang_cc1 -verify -fopenmp -x c++ -fblocks -DBLOCKS -triple i386-pc-linux-gnu -emit-llvm %s -o - | FileCheck -check-prefix=BLOCKS -check-prefix=BLOCKS-32 %s
// RUN: %clang_cc1 -verify -fopenmp-simd -x c++ -triple i386-pc-linux-gnu -emit-llvm %s -o - | FileCheck --check-prefix SIMD-ONLY0 %s
// RUN: %clang_cc1 -fopenmp-simd -x c++ -std=c++11 -triple i386-pc-linux-gnu -emit-pch -o %t %s
// RUN: %clang_cc1 -fopenmp-simd -x c++ -triple i386-pc-linux-gnu -std=c++11 -include-pch %t -verify %s -emit-llvm -o - | FileCheck --check-prefix SIMD-ONLY0 %s
// RUN: %clang_cc1 -verify -fopenmp-simd -x c++ -std=c++11 -DLAMBDA -triple i386-pc-linux-gnu -emit-llvm %s -o - | FileCheck --check-prefix SIMD-ONLY0 %s
// RUN: %clang_cc1 -verify -fopenmp-simd -x c++ -fblocks -DBLOCKS -triple i386-pc-linux-gnu -emit-llvm %s -o - | FileCheck --check-prefix SIMD-ONLY0 %s
// SIMD-ONLY0-NOT: {{__kmpc|__tgt}}
// RUN: %clang_cc1 -verify -fopenmp -x c++ -triple x86_64-pc-linux-gnu -emit-llvm %s -o - | FileCheck %s -check-prefix=CHECK -check-prefix=CHECK-64
// RUN: %clang_cc1 -fopenmp -x c++ -std=c++11 -triple x86_64-pc-linux-gnu -emit-pch -o %t %s
// RUN: %clang_cc1 -fopenmp -x c++ -triple x86_64-pc-linux-gnu -std=c++11 -include-pch %t -verify %s -emit-llvm -o - | FileCheck %s -check-prefix=CHECK -check-prefix=CHECK-64
// RUN: %clang_cc1 -verify -fopenmp -x c++ -std=c++11 -DLAMBDA -triple x86_64-pc-linux-gnu -emit-llvm %s -o - | FileCheck -check-prefix=LAMBDA -check-prefix=LAMBDA-64 %s
// RUN: %clang_cc1 -verify -fopenmp -x c++ -fblocks -DBLOCKS -triple x86_64-pc-linux-gnu -emit-llvm %s -o - | FileCheck -check-prefix=BLOCKS -check-prefix=BLOCKS-64 %s
// RUN: %clang_cc1 -verify -fopenmp-simd -x c++ -triple x86_64-pc-linux-gnu -emit-llvm %s -o - | FileCheck --check-prefix SIMD-ONLY1 %s
// RUN: %clang_cc1 -fopenmp-simd -x c++ -std=c++11 -triple x86_64-pc-linux-gnu -emit-pch -o %t %s
// RUN: %clang_cc1 -fopenmp-simd -x c++ -triple x86_64-pc-linux-gnu -std=c++11 -include-pch %t -verify %s -emit-llvm -o - | FileCheck --check-prefix SIMD-ONLY1 %s
// RUN: %clang_cc1 -verify -fopenmp-simd -x c++ -std=c++11 -DLAMBDA -triple x86_64-pc-linux-gnu -emit-llvm %s -o - | FileCheck --check-prefix SIMD-ONLY1 %s
// RUN: %clang_cc1 -verify -fopenmp-simd -x c++ -fblocks -DBLOCKS -triple x86_64-pc-linux-gnu -emit-llvm %s -o - | FileCheck --check-prefix SIMD-ONLY1 %s
// SIMD-ONLY1-NOT: {{__kmpc|__tgt}}
// RUN: %clang_cc1 -verify -fopenmp -x c++ -std=c++11 -DARRAY -triple x86_64-apple-darwin10 -emit-llvm %s -o - | FileCheck -check-prefix=ARRAY %s
// RUN: %clang_cc1 -verify -fopenmp-simd -x c++ -std=c++11 -DARRAY -triple x86_64-apple-darwin10 -emit-llvm %s -o - | FileCheck --check-prefix SIMD-ONLY2 %s
// SIMD-ONLY2-NOT: {{__kmpc|__tgt}}
// expected-no-diagnostics
#ifndef ARRAY
#ifndef HEADER
#define HEADER
struct St {
int a, b;
St() : a(0), b(0) {}
St(const St &st) : a(st.a + st.b), b(0) {}
~St() {}
};
volatile int g __attribute__((aligned(128))) = 1212;
struct SS {
int a;
int b : 4;
int &c;
int e[4];
SS(int &d) : a(0), b(0), c(d) {
#pragma omp parallel firstprivate(a, b, c, e)
#ifdef LAMBDA
[&]() {
++this->a, --b, (this)->c /= 1;
#pragma omp parallel firstprivate(a, b, c)
++(this)->a, --b, this->c /= 1;
}();
#elif defined(BLOCKS)
^{
++a;
--this->b;
(this)->c /= 1;
#pragma omp parallel firstprivate(a, b, c)
++(this)->a, --b, this->c /= 1;
}();
#else
++this->a, --b, c /= 1, e[2] = 1111;
#endif
}
};
template<typename T>
struct SST {
T a;
SST() : a(T()) {
#pragma omp parallel firstprivate(a)
#ifdef LAMBDA
[&]() {
[&]() {
++this->a;
#pragma omp parallel firstprivate(a)
++(this)->a;
}();
}();
#elif defined(BLOCKS)
^{
^{
++a;
#pragma omp parallel firstprivate(a)
++(this)->a;
}();
}();
#else
++(this)->a;
#endif
}
};
template <class T>
struct S {
T f;
S(T a) : f(a + g) {}
S() : f(g) {}
S(const S &s, St t = St()) : f(s.f + t.a) {}
operator T() { return T(); }
~S() {}
};
// CHECK: [[SS_TY:%.+]] = type { i{{[0-9]+}}, i8
// LAMBDA: [[SS_TY:%.+]] = type { i{{[0-9]+}}, i8
// BLOCKS: [[SS_TY:%.+]] = type { i{{[0-9]+}}, i8
// CHECK-DAG: [[S_FLOAT_TY:%.+]] = type { float }
// CHECK-DAG: [[S_INT_TY:%.+]] = type { i{{[0-9]+}} }
// CHECK-DAG: [[ST_TY:%.+]] = type { i{{[0-9]+}}, i{{[0-9]+}} }
template <typename T>
T tmain() {
S<T> test;
SST<T> sst;
T t_var __attribute__((aligned(128))) = T();
T vec[] __attribute__((aligned(128))) = {1, 2};
S<T> s_arr[] __attribute__((aligned(128))) = {1, 2};
S<T> var __attribute__((aligned(128))) (3);
#pragma omp parallel firstprivate(t_var, vec, s_arr, var)
{
vec[0] = t_var;
s_arr[0] = var;
}
#pragma omp parallel firstprivate(t_var)
{}
return T();
}
int main() {
static int sivar;
SS ss(sivar);
#ifdef LAMBDA
// LAMBDA: [[G:@.+]] = global i{{[0-9]+}} 1212,
// LAMBDA-LABEL: @main
// LAMBDA: alloca [[SS_TY]],
// LAMBDA: alloca [[CAP_TY:%.+]],
// LAMBDA: call{{.*}} void [[OUTER_LAMBDA:@[^(]+]]([[CAP_TY]]*
[&]() {
// LAMBDA: define{{.*}} internal{{.*}} void [[OUTER_LAMBDA]](
// LAMBDA: call {{.*}}void {{.+}} @__kmpc_fork_call({{.+}}, i32 2, {{.+}}* [[OMP_REGION:@.+]] to {{.+}}, i32* [[G]], {{.+}})
#pragma omp parallel firstprivate(g, sivar)
{
// LAMBDA: define {{.+}} @{{.+}}([[SS_TY]]*
// LAMBDA: getelementptr inbounds [[SS_TY]], [[SS_TY]]* %{{.+}}, i32 0, i32 0
// LAMBDA: store i{{[0-9]+}} 0, i{{[0-9]+}}* %
// LAMBDA: getelementptr inbounds [[SS_TY]], [[SS_TY]]* %{{.+}}, i32 0, i32 1
// LAMBDA: store i8
// LAMBDA: getelementptr inbounds [[SS_TY]], [[SS_TY]]* %{{.+}}, i32 0, i32 2
// LAMBDA: getelementptr inbounds [[SS_TY]], [[SS_TY]]* %{{.+}}, i32 0, i32 0
// LAMBDA: getelementptr inbounds [[SS_TY]], [[SS_TY]]* %{{.+}}, i32 0, i32 1
// LAMBDA: getelementptr inbounds [[SS_TY]], [[SS_TY]]* %{{.+}}, i32 0, i32 2
// LAMBDA: call void (%{{.+}}*, i{{[0-9]+}}, void (i{{[0-9]+}}*, i{{[0-9]+}}*, ...)*, ...) @__kmpc_fork_call(%{{.+}}* @{{.+}}, i{{[0-9]+}} 5, void (i{{[0-9]+}}*, i{{[0-9]+}}*, ...)* bitcast (void (i{{[0-9]+}}*, i{{[0-9]+}}*, [[SS_TY]]*, [[iz:i64|i32]], {{i64|i32}}, {{i64|i32}}, [4 x i{{[0-9]+}}]*)* [[SS_MICROTASK:@.+]] to void
// LAMBDA: ret
// LAMBDA: define internal void [[SS_MICROTASK]](i{{[0-9]+}}* noalias [[GTID_ADDR:%.+]], i{{[0-9]+}}* noalias %{{.+}}, [[SS_TY]]* %{{.+}}, [[iz]] {{.+}}, [[iz]] {{.+}}, [[iz]] {{.+}}, [4 x i{{[0-9]+}}]* {{.+}})
// LAMBDA-NOT: getelementptr {{.*}}[[SS_TY]], [[SS_TY]]* %
// LAMBDA: call{{.*}} void
// LAMBDA: ret void
// LAMBDA: define internal void @{{.+}}(i{{[0-9]+}}* noalias [[GTID_ADDR:%.+]], i{{[0-9]+}}* noalias %{{.+}}, [[SS_TY]]* %{{.+}}, [[iz]] {{.+}}, [[iz]] {{.+}}, [[iz]] {{.+}})
// LAMBDA: [[A_PRIV:%.+]] = alloca i{{[0-9]+}},
// LAMBDA: [[B_PRIV:%.+]] = alloca i{{[0-9]+}},
// LAMBDA: [[C_PRIV:%.+]] = alloca i{{[0-9]+}},
// LAMBDA-64: [[A_CONV:%.+]] = bitcast i64* [[A_PRIV]] to i32*
// LAMBDA-64: store i32* [[A_CONV]], i32** [[REFA:%.+]],
// LAMBDA-32: store i32* [[A_PRIV]], i32** [[REFA:%.+]],
// LAMBDA-64: [[B_CONV:%.+]] = bitcast i64* [[B_PRIV]] to i32*
// LAMBDA-64: [[C_CONV:%.+]] = bitcast i64* [[C_PRIV]] to i32*
// LAMBDA-64: store i32* [[C_CONV]], i32** [[REFC:%.+]],
// LAMBDA-32: store i32* [[C_PRIV]], i32** [[REFC:%.+]],
// LAMBDA-NEXT: [[A_PRIV:%.+]] = load i{{[0-9]+}}*, i{{[0-9]+}}** [[REFA]],
// LAMBDA-NEXT: [[A_VAL:%.+]] = load i{{[0-9]+}}, i{{[0-9]+}}* [[A_PRIV]],
// LAMBDA-NEXT: [[INC:%.+]] = add nsw i{{[0-9]+}} [[A_VAL]], 1
// LAMBDA-NEXT: store i{{[0-9]+}} [[INC]], i{{[0-9]+}}* [[A_PRIV]],
// LAMBDA-64-NEXT: [[B_VAL:%.+]] = load i{{[0-9]+}}, i{{[0-9]+}}* [[B_CONV]],
// LAMBDA-32-NEXT: [[B_VAL:%.+]] = load i{{[0-9]+}}, i{{[0-9]+}}* [[B_PRIV]],
// LAMBDA-NEXT: [[DEC:%.+]] = add nsw i{{[0-9]+}} [[B_VAL]], -1
// LAMBDA-64-NEXT: store i{{[0-9]+}} [[DEC]], i{{[0-9]+}}* [[B_CONV]],
// LAMBDA-32-NEXT: store i{{[0-9]+}} [[DEC]], i{{[0-9]+}}* [[B_PRIV]],
// LAMBDA-NEXT: [[C_PRIV:%.+]] = load i{{[0-9]+}}*, i{{[0-9]+}}** [[REFC]],
// LAMBDA-NEXT: [[C_VAL:%.+]] = load i{{[0-9]+}}, i{{[0-9]+}}* [[C_PRIV]],
// LAMBDA-NEXT: [[DIV:%.+]] = sdiv i{{[0-9]+}} [[C_VAL]], 1
// LAMBDA-NEXT: store i{{[0-9]+}} [[DIV]], i{{[0-9]+}}* [[C_PRIV]],
// LAMBDA-NEXT: ret void
// LAMBDA: define{{.*}} internal{{.*}} void [[OMP_REGION]](i32* noalias %{{.+}}, i32* noalias %{{.+}}, i32* dereferenceable(4) %{{.+}}, [[iz]] {{.*}}%{{.+}})
// LAMBDA: [[SIVAR_PRIVATE_ADDR:%.+]] = alloca i{{[0-9]+}},
// LAMBDA: [[G_PRIVATE_ADDR:%.+]] = alloca i{{[0-9]+}}, align 128
// LAMBDA: [[G_REF:%.+]] = load i{{[0-9]+}}*, i{{[0-9]+}}** [[G_REF_ADDR:%.+]]
// LAMBDA-64: [[SIVAR_PRIVATE_CONV:%.+]] = bitcast i64* [[SIVAR_PRIVATE_ADDR]] to i32*
// LAMBDA: [[G_VAL:%.+]] = load volatile i{{[0-9]+}}, i{{[0-9]+}}* [[G_REF]], align 128
// LAMBDA: store i{{[0-9]+}} [[G_VAL]], i{{[0-9]+}}* [[G_PRIVATE_ADDR]], align 128
// LAMBDA-NOT: call {{.*}}void @__kmpc_barrier(
g = 1;
sivar = 2;
// LAMBDA: store i{{[0-9]+}} 1, i{{[0-9]+}}* [[G_PRIVATE_ADDR]],
// LAMBDA-64: store i{{[0-9]+}} 2, i{{[0-9]+}}* [[SIVAR_PRIVATE_CONV]],
// LAMBDA-32: store i{{[0-9]+}} 2, i{{[0-9]+}}* [[SIVAR_PRIVATE_ADDR]],
// LAMBDA: [[G_PRIVATE_ADDR_REF:%.+]] = getelementptr inbounds %{{.+}}, %{{.+}}* [[ARG:%.+]], i{{[0-9]+}} 0, i{{[0-9]+}} 0
// LAMBDA: store i{{[0-9]+}}* [[G_PRIVATE_ADDR]], i{{[0-9]+}}** [[G_PRIVATE_ADDR_REF]]
// LAMBDA: [[SIVAR_PRIVATE_ADDR_REF:%.+]] = getelementptr inbounds %{{.+}}, %{{.+}}* [[ARG:%.+]], i{{[0-9]+}} 0, i{{[0-9]+}} 1
// LAMBDA-64: store i{{[0-9]+}}* [[SIVAR_PRIVATE_CONV]], i{{[0-9]+}}** [[SIVAR_PRIVATE_ADDR_REF]]
// LAMBDA-32: store i{{[0-9]+}}* [[SIVAR_PRIVATE_ADDR]], i{{[0-9]+}}** [[SIVAR_PRIVATE_ADDR_REF]]
// LAMBDA: call{{.*}} void [[INNER_LAMBDA:@.+]](%{{.+}}* [[ARG]])
[&]() {
// LAMBDA: define {{.+}} void [[INNER_LAMBDA]](%{{.+}}* [[ARG_PTR:%.+]])
// LAMBDA: store %{{.+}}* [[ARG_PTR]], %{{.+}}** [[ARG_PTR_REF:%.+]],
g = 2;
sivar = 4;
// LAMBDA: [[ARG_PTR:%.+]] = load %{{.+}}*, %{{.+}}** [[ARG_PTR_REF]]
// LAMBDA: [[G_PTR_REF:%.+]] = getelementptr inbounds %{{.+}}, %{{.+}}* [[ARG_PTR]], i{{[0-9]+}} 0, i{{[0-9]+}} 0
// LAMBDA: [[G_REF:%.+]] = load i{{[0-9]+}}*, i{{[0-9]+}}** [[G_PTR_REF]]
// LAMBDA: [[SIVAR_PTR_REF:%.+]] = getelementptr inbounds %{{.+}}, %{{.+}}* [[ARG_PTR]], i{{[0-9]+}} 0, i{{[0-9]+}} 1
// LAMBDA: [[SIVAR_REF:%.+]] = load i{{[0-9]+}}*, i{{[0-9]+}}** [[SIVAR_PTR_REF]]
// LAMBDA: store i{{[0-9]+}} 4, i{{[0-9]+}}* [[SIVAR_REF]]
}();
}
}();
return 0;
#elif defined(BLOCKS)
// BLOCKS: [[G:@.+]] = global i{{[0-9]+}} 1212,
// BLOCKS-LABEL: @main
// BLOCKS: call
// BLOCKS: call {{.*}}void {{%.+}}(i8
^{
// BLOCKS: define{{.*}} internal{{.*}} void {{.+}}(i8*
// BLOCKS: call {{.*}}void {{.+}} @__kmpc_fork_call({{.+}}, i32 2, {{.+}}* [[OMP_REGION:@.+]] to {{.+}}, i32* [[G]], {{.+}})
#pragma omp parallel firstprivate(g, sivar)
{
// BLOCKS: define{{.*}} internal{{.*}} void [[OMP_REGION]](i32* noalias %{{.+}}, i32* noalias %{{.+}}, i32* dereferenceable(4) %{{.+}}, [[iz:i64|i32]] {{.*}}%{{.+}})
// BLOCKS: [[SIVAR_PRIVATE_ADDR:%.+]] = alloca i{{[0-9]+}},
// BLOCKS: [[G_PRIVATE_ADDR:%.+]] = alloca i{{[0-9]+}}, align 128
// BLOCKS: [[G_REF:%.+]] = load i{{[0-9]+}}*, i{{[0-9]+}}** [[G_REF_ADDR:%.+]]
// BLOCKS-64: [[SIVAR_PRIVATE_CONV:%.+]] = bitcast i64* [[SIVAR_PRIVATE_ADDR]] to i32*
// BLOCKS: [[G_VAL:%.+]] = load volatile i{{[0-9]+}}, i{{[0-9]+}}* [[G_REF]], align 128
// BLOCKS: store i{{[0-9]+}} [[G_VAL]], i{{[0-9]+}}* [[G_PRIVATE_ADDR]], align 128
// BLOCKS-NOT: call {{.*}}void @__kmpc_barrier(
g = 1;
sivar = 2;
// BLOCKS: store i{{[0-9]+}} 1, i{{[0-9]+}}* [[G_PRIVATE_ADDR]],
// BLOCKS-64: store i{{[0-9]+}} 2, i{{[0-9]+}}* [[SIVAR_PRIVATE_CONV]],
// BLOCKS-32: store i{{[0-9]+}} 2, i{{[0-9]+}}* [[SIVAR_PRIVATE_ADDR]],
// BLOCKS-NOT: [[G]]{{[[^:word:]]}}
// BLOCKS: i{{[0-9]+}}* [[G_PRIVATE_ADDR]]
// BLOCKS-NOT: [[G]]{{[[^:word:]]}}
// BLOCKS-NOT: [[SIVAR]]{{[[^:word:]]}}
// BLOCKS-64: i{{[0-9]+}}* [[SIVAR_PRIVATE_CONV]]
// BLOCKS-32: i{{[0-9]+}}* [[SIVAR_PRIVATE_ADDR]]
// BLOCKS-NOT: [[SIVAR]]{{[[^:word:]]}}
// BLOCKS: call {{.*}}void {{%.+}}(i8
^{
// BLOCKS: define {{.+}} void {{@.+}}(i8*
g = 2;
sivar = 4;
// BLOCKS-NOT: [[G]]{{[[^:word:]]}}
// BLOCKS: store i{{[0-9]+}} 2, i{{[0-9]+}}*
// BLOCKS-NOT: [[G]]{{[[^:word:]]}}
// BLOCKS-NOT: [[SIVAR]]{{[[^:word:]]}}
// BLOCKS: store i{{[0-9]+}} 4, i{{[0-9]+}}*
// BLOCKS-NOT: [[SIVAR]]{{[[^:word:]]}}
// BLOCKS: ret
}();
}
}();
return 0;
// BLOCKS: define {{.+}} @{{.+}}([[SS_TY]]*
// BLOCKS: getelementptr inbounds [[SS_TY]], [[SS_TY]]* %{{.+}}, i32 0, i32 0
// BLOCKS: store i{{[0-9]+}} 0, i{{[0-9]+}}* %
// BLOCKS: getelementptr inbounds [[SS_TY]], [[SS_TY]]* %{{.+}}, i32 0, i32 1
// BLOCKS: store i8
// BLOCKS: getelementptr inbounds [[SS_TY]], [[SS_TY]]* %{{.+}}, i32 0, i32 2
// BLOCKS: getelementptr inbounds [[SS_TY]], [[SS_TY]]* %{{.+}}, i32 0, i32 0
// BLOCKS: getelementptr inbounds [[SS_TY]], [[SS_TY]]* %{{.+}}, i32 0, i32 1
// BLOCKS: getelementptr inbounds [[SS_TY]], [[SS_TY]]* %{{.+}}, i32 0, i32 2
// BLOCKS: call void (%{{.+}}*, i{{[0-9]+}}, void (i{{[0-9]+}}*, i{{[0-9]+}}*, ...)*, ...) @__kmpc_fork_call(%{{.+}}* @{{.+}}, i{{[0-9]+}} 5, void (i{{[0-9]+}}*, i{{[0-9]+}}*, ...)* bitcast (void (i{{[0-9]+}}*, i{{[0-9]+}}*, [[SS_TY]]*, [[iz]], [[iz]], [[iz]], [4 x i{{[0-9]+}}]*)* [[SS_MICROTASK:@.+]] to void
// BLOCKS: ret
// BLOCKS: define internal void [[SS_MICROTASK]](i{{[0-9]+}}* noalias [[GTID_ADDR:%.+]], i{{[0-9]+}}* noalias %{{.+}}, [[SS_TY]]* %{{.+}}, [[iz]] {{.+}}, [[iz]] {{.+}}, [[iz]] {{.+}}, [4 x i{{[0-9]+}}]* {{.+}})
// BLOCKS-NOT: getelementptr {{.*}}[[SS_TY]], [[SS_TY]]* %
// BLOCKS: call{{.*}} void
// BLOCKS: ret void
// BLOCKS: define internal void @{{.+}}(i{{[0-9]+}}* noalias [[GTID_ADDR:%.+]], i{{[0-9]+}}* noalias %{{.+}}, [[SS_TY]]* %{{.+}}, [[iz]] {{.+}}, [[iz]] {{.+}}, [[iz]] {{.+}})
// BLOCKS: [[A_PRIV:%.+]] = alloca i{{[0-9]+}},
// BLOCKS: [[B_PRIV:%.+]] = alloca i{{[0-9]+}},
// BLOCKS: [[C_PRIV:%.+]] = alloca i{{[0-9]+}},
// BLOCKS-64: [[A_CONV:%.+]] = bitcast i64* [[A_PRIV]] to i32*
// BLOCKS-64: store i32* [[A_CONV]], i32** [[REFA:%.+]],
// BLOCKS-32: store i32* [[A_PRIV]], i32** [[REFA:%.+]],
// BLOCKS-64: [[B_CONV:%.+]] = bitcast i64* [[B_PRIV]] to i32*
// BLOCKS-64: [[C_CONV:%.+]] = bitcast i64* [[C_PRIV]] to i32*
// BLOCKS-64: store i32* [[C_CONV]], i32** [[REFC:%.+]],
// BLOCKS-32: store i32* [[C_PRIV]], i32** [[REFC:%.+]],
// BLOCKS-NEXT: [[A_PRIV:%.+]] = load i{{[0-9]+}}*, i{{[0-9]+}}** [[REFA]],
// BLOCKS-NEXT: [[A_VAL:%.+]] = load i{{[0-9]+}}, i{{[0-9]+}}* [[A_PRIV]],
// BLOCKS-NEXT: [[INC:%.+]] = add nsw i{{[0-9]+}} [[A_VAL]], 1
// BLOCKS-NEXT: store i{{[0-9]+}} [[INC]], i{{[0-9]+}}* [[A_PRIV]],
// BLOCKS-64-NEXT: [[B_VAL:%.+]] = load i{{[0-9]+}}, i{{[0-9]+}}* [[B_CONV]],
// BLOCKS-32-NEXT: [[B_VAL:%.+]] = load i{{[0-9]+}}, i{{[0-9]+}}* [[B_PRIV]],
// BLOCKS-NEXT: [[DEC:%.+]] = add nsw i{{[0-9]+}} [[B_VAL]], -1
// BLOCKS-64-NEXT: store i{{[0-9]+}} [[DEC]], i{{[0-9]+}}* [[B_CONV]],
// BLOCKS-32-NEXT: store i{{[0-9]+}} [[DEC]], i{{[0-9]+}}* [[B_PRIV]],
// BLOCKS-NEXT: [[C_PRIV:%.+]] = load i{{[0-9]+}}*, i{{[0-9]+}}** [[REFC]],
// BLOCKS-NEXT: [[C_VAL:%.+]] = load i{{[0-9]+}}, i{{[0-9]+}}* [[C_PRIV]],
// BLOCKS-NEXT: [[DIV:%.+]] = sdiv i{{[0-9]+}} [[C_VAL]], 1
// BLOCKS-NEXT: store i{{[0-9]+}} [[DIV]], i{{[0-9]+}}* [[C_PRIV]],
// BLOCKS-NEXT: ret void
#else
S<float> test;
int t_var = 0;
int vec[] = {1, 2};
S<float> s_arr[] = {1, 2};
S<float> var(3);
#pragma omp parallel firstprivate(t_var, vec, s_arr, var, sivar)
{
vec[0] = t_var;
s_arr[0] = var;
sivar = 2;
}
#pragma omp parallel firstprivate(t_var)
{}
return tmain<int>();
#endif
}
// CHECK: define {{.*}}i{{[0-9]+}} @main()
// CHECK: [[TEST:%.+]] = alloca [[S_FLOAT_TY]],
// CHECK: [[T_VAR:%.+]] = alloca i32,
// CHECK: [[T_VARCAST:%.+]] = alloca [[iz:i64|i32]],
// CHECK: [[SIVARCAST:%.+]] = alloca [[iz]],
// CHECK: call {{.*}} [[S_FLOAT_TY_DEF_CONSTR:@.+]]([[S_FLOAT_TY]]* [[TEST]])
// CHECK: [[T_VARVAL:%.+]] = load i32, i32* [[T_VAR]],
// CHECK-64: [[T_VARCONV:%.+]] = bitcast i64* [[T_VARCAST]] to i32*
// CHECK-64: store i32 [[T_VARVAL]], i32* [[T_VARCONV]],
// CHECK-32: store i32 [[T_VARVAL]], i32* [[T_VARCAST]],
// CHECK: [[T_VARPVT:%.+]] = load [[iz]], [[iz]]* [[T_VARCAST]],
// CHECK: [[SIVARVAL:%.+]] = load i32, i32* @{{.+}},
// CHECK-64: [[SIVARCONV:%.+]] = bitcast i64* [[SIVARCAST]] to i32*
// CHECK-64: store i32 [[SIVARVAL]], i32* [[SIVARCONV]],
// CHECK-32: store i32 [[SIVARVAL]], i32* [[SIVARCAST]],
// CHECK: [[SIVARPVT:%.+]] = load [[iz]], [[iz]]* [[SIVARCAST]],
// CHECK: call {{.*}}void (%{{.+}}*, i{{[0-9]+}}, void (i{{[0-9]+}}*, i{{[0-9]+}}*, ...)*, ...) @__kmpc_fork_call(%{{.+}}* @{{.+}}, i{{[0-9]+}} 5, void (i{{[0-9]+}}*, i{{[0-9]+}}*, ...)* bitcast (void (i{{[0-9]+}}*, i{{[0-9]+}}*, [2 x i32]*, [[iz]], [2 x [[S_FLOAT_TY]]]*, [[S_FLOAT_TY]]*, i{{[0-9]+}})* [[MAIN_MICROTASK:@.+]] to void {{.*}}[[iz]] [[T_VARPVT]],{{.*}}[[iz]] [[SIVARPVT]]
// CHECK: = call {{.*}}i{{.+}} [[TMAIN_INT:@.+]]()
// CHECK: call {{.*}} [[S_FLOAT_TY_DESTR:@.+]]([[S_FLOAT_TY]]*
// CHECK: ret
//
// CHECK: define internal {{.*}}void [[MAIN_MICROTASK]](i{{[0-9]+}}* noalias [[GTID_ADDR:%.+]], i{{[0-9]+}}* noalias %{{.+}}, [2 x i32]* dereferenceable(8) %{{.+}}, [[iz]] {{.*}}%{{.+}}, [2 x [[S_FLOAT_TY]]]* dereferenceable(8) %{{.+}}, [[S_FLOAT_TY]]* dereferenceable(4) %{{.+}}, [[iz]] {{.*}}[[SIVAR:%.+]])
// CHECK: [[T_VAR_PRIV:%.+]] = alloca i{{[0-9]+}},
// CHECK: [[SIVAR7_PRIV:%.+]] = alloca i{{[0-9]+}},
// CHECK: [[VEC_PRIV:%.+]] = alloca [2 x i{{[0-9]+}}],
// CHECK: [[S_ARR_PRIV:%.+]] = alloca [2 x [[S_FLOAT_TY]]],
// CHECK: [[VAR_PRIV:%.+]] = alloca [[S_FLOAT_TY]],
// CHECK: store i{{[0-9]+}}* [[GTID_ADDR]], i{{[0-9]+}}** [[GTID_ADDR_ADDR:%.+]],
// CHECK: [[VEC_REF:%.+]] = load [2 x i{{[0-9]+}}]*, [2 x i{{[0-9]+}}]** %
// CHECK-NOT: load i{{[0-9]+}}*, i{{[0-9]+}}** %
// CHECK-64: [[T_VAR_CONV:%.+]] = bitcast i64* [[T_VAR_PRIV]] to i32*
// CHECK: [[S_ARR_REF:%.+]] = load [2 x [[S_FLOAT_TY]]]*, [2 x [[S_FLOAT_TY]]]** %
// CHECK: [[VAR_REF:%.+]] = load [[S_FLOAT_TY]]*, [[S_FLOAT_TY]]** %
// CHECK-NOT: load i{{[0-9]+}}*, i{{[0-9]+}}** %
// CHECK-64: [[SIVAR7_CONV:%.+]] = bitcast i64* [[SIVAR7_PRIV]] to i32*
// CHECK: [[VEC_DEST:%.+]] = bitcast [2 x i{{[0-9]+}}]* [[VEC_PRIV]] to i8*
// CHECK: [[VEC_SRC:%.+]] = bitcast [2 x i{{[0-9]+}}]* [[VEC_REF]] to i8*
// CHECK: call void @llvm.memcpy.{{.+}}(i8* align {{[0-9]+}} [[VEC_DEST]], i8* align {{[0-9]+}} [[VEC_SRC]],
// CHECK: [[S_ARR_PRIV_BEGIN:%.+]] = getelementptr inbounds [2 x [[S_FLOAT_TY]]], [2 x [[S_FLOAT_TY]]]* [[S_ARR_PRIV]], i{{[0-9]+}} 0, i{{[0-9]+}} 0
// CHECK: [[S_ARR_BEGIN:%.+]] = bitcast [2 x [[S_FLOAT_TY]]]* [[S_ARR_REF]] to [[S_FLOAT_TY]]*
// CHECK: [[S_ARR_PRIV_END:%.+]] = getelementptr [[S_FLOAT_TY]], [[S_FLOAT_TY]]* [[S_ARR_PRIV_BEGIN]], i{{[0-9]+}} 2
// CHECK: [[IS_EMPTY:%.+]] = icmp eq [[S_FLOAT_TY]]* [[S_ARR_PRIV_BEGIN]], [[S_ARR_PRIV_END]]
// CHECK: br i1 [[IS_EMPTY]], label %[[S_ARR_BODY_DONE:.+]], label %[[S_ARR_BODY:.+]]
// CHECK: [[S_ARR_BODY]]
// CHECK: call {{.*}} [[ST_TY_DEFAULT_CONSTR:@.+]]([[ST_TY]]* [[ST_TY_TEMP:%.+]])
// CHECK: call {{.*}} [[S_FLOAT_TY_COPY_CONSTR:@.+]]([[S_FLOAT_TY]]* {{.+}}, [[S_FLOAT_TY]]* {{.+}}, [[ST_TY]]* [[ST_TY_TEMP]])
// CHECK: call {{.*}} [[ST_TY_DESTR:@.+]]([[ST_TY]]* [[ST_TY_TEMP]])
// CHECK: br i1 {{.+}}, label %{{.+}}, label %[[S_ARR_BODY]]
// CHECK: call {{.*}} [[ST_TY_DEFAULT_CONSTR]]([[ST_TY]]* [[ST_TY_TEMP:%.+]])
// CHECK: call {{.*}} [[S_FLOAT_TY_COPY_CONSTR]]([[S_FLOAT_TY]]* [[VAR_PRIV]], [[S_FLOAT_TY]]* {{.*}} [[VAR_REF]], [[ST_TY]]* [[ST_TY_TEMP]])
// CHECK: call {{.*}} [[ST_TY_DESTR]]([[ST_TY]]* [[ST_TY_TEMP]])
// CHECK-64: store i{{[0-9]+}} 2, i{{[0-9]+}}* [[SIVAR7_CONV]],
// CHECK-32: store i{{[0-9]+}} 2, i{{[0-9]+}}* [[SIVAR7_PRIV]],
// CHECK-DAG: call {{.*}} [[S_FLOAT_TY_DESTR]]([[S_FLOAT_TY]]* [[VAR_PRIV]])
// CHECK-DAG: call {{.*}} [[S_FLOAT_TY_DESTR]]([[S_FLOAT_TY]]*
// CHECK: ret void
// CHECK: define {{.*}} i{{[0-9]+}} [[TMAIN_INT]]()
// CHECK: [[TEST:%.+]] = alloca [[S_INT_TY]],
// CHECK: call {{.*}} [[S_INT_TY_DEF_CONSTR:@.+]]([[S_INT_TY]]* [[TEST]])
// CHECK: call {{.*}}void (%{{.+}}*, i{{[0-9]+}}, void (i{{[0-9]+}}*, i{{[0-9]+}}*, ...)*, ...) @__kmpc_fork_call(%{{.+}}* @{{.+}}, i{{[0-9]+}} 4, void (i{{[0-9]+}}*, i{{[0-9]+}}*, ...)* bitcast (void (i{{[0-9]+}}*, i{{[0-9]+}}*, [2 x i32]*, i32*, [2 x [[S_INT_TY]]]*, [[S_INT_TY]]*)* [[TMAIN_MICROTASK:@.+]] to void
// CHECK: call {{.*}} [[S_INT_TY_DESTR:@.+]]([[S_INT_TY]]*
// CHECK: ret
//
// CHECK: define {{.+}} @{{.+}}([[SS_TY]]*
// CHECK: getelementptr inbounds [[SS_TY]], [[SS_TY]]* %{{.+}}, i32 0, i32 0
// CHECK: store i{{[0-9]+}} 0, i{{[0-9]+}}* %
// CHECK: getelementptr inbounds [[SS_TY]], [[SS_TY]]* %{{.+}}, i32 0, i32 1
// CHECK: store i8
// CHECK: getelementptr inbounds [[SS_TY]], [[SS_TY]]* %{{.+}}, i32 0, i32 2
// CHECK: getelementptr inbounds [[SS_TY]], [[SS_TY]]* %{{.+}}, i32 0, i32 0
// CHECK: getelementptr inbounds [[SS_TY]], [[SS_TY]]* %{{.+}}, i32 0, i32 1
// CHECK: getelementptr inbounds [[SS_TY]], [[SS_TY]]* %{{.+}}, i32 0, i32 2
// CHECK: call void (%{{.+}}*, i{{[0-9]+}}, void (i{{[0-9]+}}*, i{{[0-9]+}}*, ...)*, ...) @__kmpc_fork_call(%{{.+}}* @{{.+}}, i{{[0-9]+}} 5, void (i{{[0-9]+}}*, i{{[0-9]+}}*, ...)* bitcast (void (i{{[0-9]+}}*, i{{[0-9]+}}*, [[SS_TY]]*, [[iz]], [[iz]], [[iz]], [4 x i32]*)* [[SS_MICROTASK:@.+]] to void
// CHECK: ret
// CHECK: define internal void [[SS_MICROTASK]](i{{[0-9]+}}* noalias [[GTID_ADDR:%.+]], i{{[0-9]+}}* noalias %{{.+}}, [[SS_TY]]* %{{.+}}, [[iz]] {{.+}}, [[iz]] {{.+}}, [[iz]] {{.+}}, [4 x i{{[0-9]+}}]* {{.+}})
// CHECK: [[A_PRIV:%.+]] = alloca i{{[0-9]+}},
// CHECK: [[B_PRIV:%.+]] = alloca i{{[0-9]+}},
// CHECK: [[C_PRIV:%.+]] = alloca i{{[0-9]+}},
// CHECK: [[E_PRIV:%.+]] = alloca [4 x i{{[0-9]+}}],
// CHECK: store i{{[0-9]+}} {{.+}}, i{{[0-9]+}}* [[A_PRIV]]
// CHECK: store i{{[0-9]+}} {{.+}}, i{{[0-9]+}}* [[B_PRIV]]
// CHECK: store i{{[0-9]+}} {{.+}}, i{{[0-9]+}}* [[C_PRIV]]
// CHECK-64: [[A_CONV:%.+]] = bitcast i64* [[A_PRIV:%.+]] to i32*
// CHECK-64: store i32* [[A_CONV]], i32** [[REFA:%.+]],
// CHECK-32: store i32* [[A_PRIV]], i32** [[REFA:%.+]],
// CHECK-64: [[B_CONV:%.+]] = bitcast i64* [[B_PRIV:%.+]] to i32*
// CHECK-64: [[C_CONV:%.+]] = bitcast i64* [[C_PRIV:%.+]] to i32*
// CHECK-64: store i32* [[C_CONV]], i32** [[REFC:%.+]],
// CHECK-32: store i32* [[C_PRIV]], i32** [[REFC:%.+]],
// CHECK: bitcast [4 x i{{[0-9]+}}]* [[E_PRIV]] to i8*
// CHECK: bitcast [4 x i{{[0-9]+}}]* %{{.+}} to i8*
// CHECK: call void @llvm.memcpy
// CHECK: store [4 x i{{[0-9]+}}]* [[E_PRIV]], [4 x i{{[0-9]+}}]** [[REFE:%.+]],
// CHECK-NEXT: [[A_PRIV:%.+]] = load i{{[0-9]+}}*, i{{[0-9]+}}** [[REFA]],
// CHECK-NEXT: [[A_VAL:%.+]] = load i{{[0-9]+}}, i{{[0-9]+}}* [[A_PRIV]],
// CHECK-NEXT: [[INC:%.+]] = add nsw i{{[0-9]+}} [[A_VAL]], 1
// CHECK-NEXT: store i{{[0-9]+}} [[INC]], i{{[0-9]+}}* [[A_PRIV]],
// CHECK-64-NEXT: [[B_VAL:%.+]] = load i{{[0-9]+}}, i{{[0-9]+}}* [[B_CONV]],
// CHECK-32-NEXT: [[B_VAL:%.+]] = load i{{[0-9]+}}, i{{[0-9]+}}* [[B_PRIV]],
// CHECK-NEXT: [[DEC:%.+]] = add nsw i{{[0-9]+}} [[B_VAL]], -1
// CHECK-64-NEXT: store i{{[0-9]+}} [[DEC]], i{{[0-9]+}}* [[B_CONV]],
// CHECK-32-NEXT: store i{{[0-9]+}} [[DEC]], i{{[0-9]+}}* [[B_PRIV]],
// CHECK-NEXT: [[C_PRIV:%.+]] = load i{{[0-9]+}}*, i{{[0-9]+}}** [[REFC]],
// CHECK-NEXT: [[C_VAL:%.+]] = load i{{[0-9]+}}, i{{[0-9]+}}* [[C_PRIV]],
// CHECK-NEXT: [[DIV:%.+]] = sdiv i{{[0-9]+}} [[C_VAL]], 1
// CHECK-NEXT: store i{{[0-9]+}} [[DIV]], i{{[0-9]+}}* [[C_PRIV]],
// CHECK-NEXT: [[E_PRIV:%.+]] = load [4 x i{{[0-9]+}}]*, [4 x i{{[0-9]+}}]** [[REFE]],
// CHECK-NEXT: [[E_PRIV_2:%.+]] = getelementptr inbounds [4 x i{{[0-9]+}}], [4 x i{{[0-9]+}}]* [[E_PRIV]], i{{[0-9]+}} 0, i{{[0-9]+}} 2
// CHECK-NEXT: store i32 1111, i32* [[E_PRIV_2]],
// CHECK-NEXT: ret void
// CHECK: define internal {{.*}}void [[TMAIN_MICROTASK]](i{{[0-9]+}}* noalias [[GTID_ADDR:%.+]], i{{[0-9]+}}* noalias %{{.+}}, [2 x i32]* dereferenceable(8) %{{.+}}, i32* dereferenceable(4) %{{.+}}, [2 x [[S_INT_TY]]]* dereferenceable(8) %{{.+}}, [[S_INT_TY]]* dereferenceable(4) %{{.+}})
// CHECK: [[T_VAR_PRIV:%.+]] = alloca i{{[0-9]+}}, align 128
// CHECK: [[VEC_PRIV:%.+]] = alloca [2 x i{{[0-9]+}}], align 128
// CHECK: [[S_ARR_PRIV:%.+]] = alloca [2 x [[S_INT_TY]]], align 128
// CHECK: [[VAR_PRIV:%.+]] = alloca [[S_INT_TY]], align 128
// CHECK: store i{{[0-9]+}}* [[GTID_ADDR]], i{{[0-9]+}}** [[GTID_ADDR_ADDR:%.+]],
// CHECK: [[VEC_REF:%.+]] = load [2 x i{{[0-9]+}}]*, [2 x i{{[0-9]+}}]** %
// CHECK: [[T_VAR_REF:%.+]] = load i{{[0-9]+}}*, i{{[0-9]+}}** %
// CHECK: [[S_ARR_REF:%.+]] = load [2 x [[S_INT_TY]]]*, [2 x [[S_INT_TY]]]** %
// CHECK: [[VAR_REF:%.+]] = load [[S_INT_TY]]*, [[S_INT_TY]]** %
// CHECK: [[T_VAR_VAL:%.+]] = load i{{[0-9]+}}, i{{[0-9]+}}* [[T_VAR_REF]], align 128
// CHECK: store i{{[0-9]+}} [[T_VAR_VAL]], i{{[0-9]+}}* [[T_VAR_PRIV]], align 128
// CHECK: [[VEC_DEST:%.+]] = bitcast [2 x i{{[0-9]+}}]* [[VEC_PRIV]] to i8*
// CHECK: [[VEC_SRC:%.+]] = bitcast [2 x i{{[0-9]+}}]* [[VEC_REF]] to i8*
// CHECK: call void @llvm.memcpy.{{.+}}(i8* align 128 [[VEC_DEST]], i8* align 128 [[VEC_SRC]], i{{[0-9]+}} {{[0-9]+}}, i1
// CHECK: [[S_ARR_PRIV_BEGIN:%.+]] = getelementptr inbounds [2 x [[S_INT_TY]]], [2 x [[S_INT_TY]]]* [[S_ARR_PRIV]], i{{[0-9]+}} 0, i{{[0-9]+}} 0
// CHECK: [[S_ARR_BEGIN:%.+]] = bitcast [2 x [[S_INT_TY]]]* [[S_ARR_REF]] to [[S_INT_TY]]*
// CHECK: [[S_ARR_PRIV_END:%.+]] = getelementptr [[S_INT_TY]], [[S_INT_TY]]* [[S_ARR_PRIV_BEGIN]], i{{[0-9]+}} 2
// CHECK: [[IS_EMPTY:%.+]] = icmp eq [[S_INT_TY]]* [[S_ARR_PRIV_BEGIN]], [[S_ARR_PRIV_END]]
// CHECK: br i1 [[IS_EMPTY]], label %[[S_ARR_BODY_DONE:.+]], label %[[S_ARR_BODY:.+]]
// CHECK: [[S_ARR_BODY]]
// CHECK: call {{.*}} [[ST_TY_DEFAULT_CONSTR]]([[ST_TY]]* [[ST_TY_TEMP:%.+]])
// CHECK: call {{.*}} [[S_INT_TY_COPY_CONSTR:@.+]]([[S_INT_TY]]* {{.+}}, [[S_INT_TY]]* {{.+}}, [[ST_TY]]* [[ST_TY_TEMP]])
// CHECK: call {{.*}} [[ST_TY_DESTR]]([[ST_TY]]* [[ST_TY_TEMP]])
// CHECK: br i1 {{.+}}, label %{{.+}}, label %[[S_ARR_BODY]]
// CHECK: call {{.*}} [[ST_TY_DEFAULT_CONSTR]]([[ST_TY]]* [[ST_TY_TEMP:%.+]])
// CHECK: call {{.*}} [[S_INT_TY_COPY_CONSTR]]([[S_INT_TY]]* [[VAR_PRIV]], [[S_INT_TY]]* {{.*}} [[VAR_REF]], [[ST_TY]]* [[ST_TY_TEMP]])
// CHECK: call {{.*}} [[ST_TY_DESTR]]([[ST_TY]]* [[ST_TY_TEMP]])
// CHECK-NOT: call {{.*}}void @__kmpc_barrier(
// CHECK-DAG: call {{.*}} [[S_INT_TY_DESTR]]([[S_INT_TY]]* [[VAR_PRIV]])
// CHECK-DAG: call {{.*}} [[S_INT_TY_DESTR]]([[S_INT_TY]]*
// CHECK: ret void
#endif
#else
struct St {
int a, b;
St() : a(0), b(0) {}
St(const St &) { }
~St() {}
void St_func(St s[2], int n, long double vla1[n]) {
double vla2[n][n] __attribute__((aligned(128)));
a = b;
#pragma omp parallel firstprivate(s, vla1, vla2)
vla1[b] = vla2[1][n - 1] = a = b;
}
};
// ARRAY-LABEL: array_func
void array_func(float a[3], St s[2], int n, long double vla1[n]) {
double vla2[n][n] __attribute__((aligned(128)));
// ARRAY: @__kmpc_fork_call(
// ARRAY-DAG: [[PRIV_S:%.+]] = alloca %struct.St*,
// ARRAY-DAG: [[PRIV_VLA1:%.+]] = alloca x86_fp80*,
// ARRAY-DAG: [[PRIV_A:%.+]] = alloca float*,
// ARRAY-DAG: [[PRIV_VLA2:%.+]] = alloca double*,
// ARRAY-DAG: store %struct.St* %{{.+}}, %struct.St** [[PRIV_S]],
// ARRAY-DAG: store x86_fp80* %{{.+}}, x86_fp80** [[PRIV_VLA1]],
// ARRAY-DAG: store float* %{{.+}}, float** [[PRIV_A]],
// ARRAY-DAG: store double* %{{.+}}, double** [[PRIV_VLA2]],
// ARRAY: call i8* @llvm.stacksave()
// ARRAY: [[SIZE:%.+]] = mul nuw i64 %{{.+}}, 8
// ARRAY: call void @llvm.memcpy.p0i8.p0i8.i64(i8* align 128 %{{.+}}, i8* align 128 %{{.+}}, i64 [[SIZE]], i1 false)
#pragma omp parallel firstprivate(a, s, vla1, vla2)
s[0].St_func(s, n, vla1);
;
}
// ARRAY-LABEL: St_func
// ARRAY: @__kmpc_fork_call(
// ARRAY-DAG: [[PRIV_VLA1:%.+]] = alloca x86_fp80*,
// ARRAY-DAG: [[PRIV_S:%.+]] = alloca %struct.St*,
// ARRAY-DAG: [[PRIV_VLA2:%.+]] = alloca double*,
// ARRAY-DAG: store %struct.St* %{{.+}}, %struct.St** [[PRIV_S]],
// ARRAY-DAG: store x86_fp80* %{{.+}}, x86_fp80** [[PRIV_VLA1]],
// ARRAY-DAG: store double* %{{.+}}, double** [[PRIV_VLA2]],
// ARRAY: call i8* @llvm.stacksave()
// ARRAY: [[SIZE:%.+]] = mul nuw i64 %{{.+}}, 8
// ARRAY: call void @llvm.memcpy.p0i8.p0i8.i64(i8* align 128 %{{.+}}, i8* align 128 %{{.+}}, i64 [[SIZE]], i1 false)
#endif
| bsd-3-clause |
wuhengzhi/chromium-crosswalk | chrome/browser/chrome_browser_main.cc | 84736 | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chrome_browser_main.h"
#include <stddef.h>
#include <stdint.h>
#include <set>
#include <string>
#include <utility>
#include <vector>
#include "base/at_exit.h"
#include "base/base_switches.h"
#include "base/bind.h"
#include "base/command_line.h"
#include "base/debug/crash_logging.h"
#include "base/debug/debugger.h"
#include "base/feature_list.h"
#include "base/files/file_path.h"
#include "base/files/file_util.h"
#include "base/memory/ptr_util.h"
#include "base/metrics/field_trial.h"
#include "base/metrics/histogram_macros.h"
#include "base/path_service.h"
#include "base/profiler/scoped_profile.h"
#include "base/profiler/scoped_tracker.h"
#include "base/run_loop.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_piece.h"
#include "base/strings/string_split.h"
#include "base/strings/sys_string_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "base/sys_info.h"
#include "base/threading/platform_thread.h"
#include "base/time/default_tick_clock.h"
#include "base/time/time.h"
#include "base/trace_event/trace_event.h"
#include "base/values.h"
#include "build/build_config.h"
#include "cc/base/switches.h"
#include "chrome/browser/about_flags.h"
#include "chrome/browser/after_startup_task_utils.h"
#include "chrome/browser/browser_process.h"
#include "chrome/browser/browser_process_impl.h"
#include "chrome/browser/browser_process_platform_part.h"
#include "chrome/browser/browser_shutdown.h"
#include "chrome/browser/chrome_browser_main_extra_parts.h"
#include "chrome/browser/component_updater/cld_component_installer.h"
#include "chrome/browser/component_updater/ev_whitelist_component_installer.h"
#include "chrome/browser/component_updater/file_type_policies_component_installer.h"
#include "chrome/browser/component_updater/origin_trials_component_installer.h"
#include "chrome/browser/component_updater/pepper_flash_component_installer.h"
#include "chrome/browser/component_updater/recovery_component_installer.h"
#include "chrome/browser/component_updater/sth_set_component_installer.h"
#include "chrome/browser/component_updater/supervised_user_whitelist_installer.h"
#include "chrome/browser/component_updater/swiftshader_component_installer.h"
#include "chrome/browser/component_updater/widevine_cdm_component_installer.h"
#include "chrome/browser/defaults.h"
#include "chrome/browser/first_run/first_run.h"
#include "chrome/browser/gpu/gl_string_manager.h"
#include "chrome/browser/gpu/three_d_api_observer.h"
#include "chrome/browser/media/media_capture_devices_dispatcher.h"
#include "chrome/browser/memory/tab_manager.h"
#include "chrome/browser/metrics/field_trial_synchronizer.h"
#include "chrome/browser/metrics/thread_watcher.h"
#include "chrome/browser/nacl_host/nacl_browser_delegate_impl.h"
#include "chrome/browser/net/crl_set_fetcher.h"
#include "chrome/browser/performance_monitor/performance_monitor.h"
#include "chrome/browser/plugins/plugin_prefs.h"
#include "chrome/browser/power/process_power_collector.h"
#include "chrome/browser/prefs/chrome_pref_service_factory.h"
#include "chrome/browser/prefs/command_line_pref_store.h"
#include "chrome/browser/prefs/incognito_mode_prefs.h"
#include "chrome/browser/prefs/pref_metrics_service.h"
#include "chrome/browser/printing/cloud_print/cloud_print_proxy_service.h"
#include "chrome/browser/printing/cloud_print/cloud_print_proxy_service_factory.h"
#include "chrome/browser/process_singleton.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/browser/profiles/profile_attributes_entry.h"
#include "chrome/browser/profiles/profile_attributes_storage.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/browser/profiles/profiles_state.h"
#include "chrome/browser/shell_integration.h"
#include "chrome/browser/tracing/navigation_tracing.h"
#include "chrome/browser/translate/translate_service.h"
#include "chrome/browser/ui/app_list/app_list_service.h"
#include "chrome/browser/ui/app_modal/chrome_javascript_native_dialog_factory.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_finder.h"
#include "chrome/browser/ui/startup/bad_flags_prompt.h"
#include "chrome/browser/ui/startup/default_browser_prompt.h"
#include "chrome/browser/ui/startup/startup_browser_creator.h"
#include "chrome/browser/ui/uma_browsing_activity_observer.h"
#include "chrome/browser/ui/webui/chrome_web_ui_controller_factory.h"
#include "chrome/common/channel_info.h"
#include "chrome/common/chrome_constants.h"
#include "chrome/common/chrome_features.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/chrome_result_codes.h"
#include "chrome/common/chrome_switches.h"
#include "chrome/common/crash_keys.h"
#include "chrome/common/env_vars.h"
#include "chrome/common/features.h"
#include "chrome/common/logging_chrome.h"
#include "chrome/common/media/media_resource_provider.h"
#include "chrome/common/net/net_resource_provider.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/profiling.h"
#include "chrome/common/variations/variations_util.h"
#include "chrome/grit/generated_resources.h"
#include "chrome/installer/util/google_update_settings.h"
#include "components/component_updater/component_updater_service.h"
#include "components/device_event_log/device_event_log.h"
#include "components/flags_ui/pref_service_flags_storage.h"
#include "components/google/core/browser/google_util.h"
#include "components/language_usage_metrics/language_usage_metrics.h"
#include "components/metrics/call_stack_profile_metrics_provider.h"
#include "components/metrics/metrics_service.h"
#include "components/metrics/profiler/content/content_tracking_synchronizer_delegate.h"
#include "components/metrics/profiler/tracking_synchronizer.h"
#include "components/metrics_services_manager/metrics_services_manager.h"
#include "components/nacl/browser/nacl_browser.h"
#include "components/prefs/json_pref_store.h"
#include "components/prefs/pref_registry_simple.h"
#include "components/prefs/pref_service.h"
#include "components/prefs/pref_value_store.h"
#include "components/prefs/scoped_user_pref_update.h"
#include "components/rappor/rappor_service.h"
#include "components/signin/core/common/profile_management_switches.h"
#include "components/startup_metric_utils/browser/startup_metric_utils.h"
#include "components/tracing/tracing_switches.h"
#include "components/translate/content/browser/browser_cld_utils.h"
#include "components/translate/content/common/cld_data_source.h"
#include "components/translate/core/browser/translate_download_manager.h"
#include "components/variations/pref_names.h"
#include "components/variations/service/variations_service.h"
#include "components/variations/variations_associated_data.h"
#include "components/variations/variations_http_header_provider.h"
#include "components/variations/variations_switches.h"
#include "components/version_info/version_info.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/notification_observer.h"
#include "content/public/browser/notification_registrar.h"
#include "content/public/browser/notification_service.h"
#include "content/public/browser/notification_types.h"
#include "content/public/browser/power_usage_monitor.h"
#include "content/public/browser/site_instance.h"
#include "content/public/common/content_client.h"
#include "content/public/common/content_features.h"
#include "content/public/common/content_switches.h"
#include "content/public/common/main_function_params.h"
#include "grit/platform_locale_settings.h"
#include "media/base/media_resources.h"
#include "net/base/net_module.h"
#include "net/cookies/cookie_monster.h"
#include "net/http/http_network_layer.h"
#include "net/http/http_stream_factory.h"
#include "net/url_request/url_request.h"
#include "ui/base/l10n/l10n_util.h"
#include "ui/base/layout.h"
#include "ui/base/material_design/material_design_controller.h"
#include "ui/base/resource/resource_bundle.h"
#include "ui/strings/grit/app_locale_settings.h"
#if BUILDFLAG(ANDROID_JAVA_UI)
#include "chrome/browser/android/dev_tools_discovery_provider_android.h"
#else
#include "chrome/browser/devtools/chrome_devtools_discovery_provider.h"
#endif
#if defined(OS_ANDROID)
#include "chrome/browser/metrics/thread_watcher_android.h"
#include "ui/base/resource/resource_bundle_android.h"
#else
#include "chrome/browser/feedback/feedback_profile_observer.h"
#endif // defined(OS_ANDROID)
#if defined(OS_LINUX) && !defined(OS_CHROMEOS)
#include "chrome/browser/first_run/upgrade_util_linux.h"
#endif // defined(OS_LINUX) && !defined(OS_CHROMEOS)
#if defined(OS_CHROMEOS)
#include "ash/material_design/material_design_controller.h"
#include "chrome/browser/chromeos/settings/cros_settings.h"
#include "chromeos/chromeos_switches.h"
#include "chromeos/settings/cros_settings_names.h"
#endif // defined(OS_CHROMEOS)
// TODO(port): several win-only methods have been pulled out of this, but
// BrowserMain() as a whole needs to be broken apart so that it's usable by
// other platforms. For now, it's just a stub. This is a serious work in
// progress and should not be taken as an indication of a real refactoring.
#if defined(OS_WIN)
#include "base/trace_event/trace_event_etw_export_win.h"
#include "base/win/windows_version.h"
#include "chrome/app/file_pre_reader_win.h"
#include "chrome/browser/browser_util_win.h"
#include "chrome/browser/chrome_browser_main_win.h"
#include "chrome/browser/chrome_select_file_dialog_factory_win.h"
#include "chrome/browser/component_updater/caps_installer_win.h"
#include "chrome/browser/component_updater/sw_reporter_installer_win.h"
#include "chrome/browser/first_run/try_chrome_dialog_view.h"
#include "chrome/browser/first_run/upgrade_util_win.h"
#include "chrome/browser/metrics/chrome_metrics_service_accessor.h"
#include "chrome/browser/ui/network_profile_bubble.h"
#include "chrome/installer/util/browser_distribution.h"
#include "chrome/installer/util/helper.h"
#include "chrome/installer/util/install_util.h"
#include "chrome/installer/util/module_util_win.h"
#include "chrome/installer/util/shell_util.h"
#include "components/startup_metric_utils/common/pre_read_field_trial_utils_win.h"
#include "ui/base/l10n/l10n_util_win.h"
#include "ui/shell_dialogs/select_file_dialog.h"
#endif // defined(OS_WIN)
#if defined(OS_MACOSX)
#include <Security/Security.h>
#include "base/mac/scoped_nsautorelease_pool.h"
#include "chrome/browser/mac/keystone_glue.h"
#endif // defined(OS_MACOSX)
#if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
#include "chrome/browser/first_run/upgrade_util.h"
#endif
#if !defined(DISABLE_NACL)
#include "chrome/browser/component_updater/pnacl_component_installer.h"
#include "components/nacl/browser/nacl_process_host.h"
#endif // !defined(DISABLE_NACL)
#if defined(ENABLE_EXTENSIONS)
#include "chrome/browser/extensions/startup_helper.h"
#include "extensions/browser/extension_protocols.h"
#include "extensions/common/features/feature_provider.h"
#include "extensions/components/javascript_dialog_extensions_client/javascript_dialog_extension_client_impl.h"
#endif // defined(ENABLE_EXTENSIONS)
#if defined(ENABLE_PRINT_PREVIEW) && !defined(OFFICIAL_BUILD)
#include "printing/printed_document.h"
#endif // defined(ENABLE_PRINT_PREVIEW) && !defined(OFFICIAL_BUILD)
#if defined(ENABLE_RLZ)
#include "chrome/browser/rlz/chrome_rlz_tracker_delegate.h"
#include "components/rlz/rlz_tracker.h"
#endif // defined(ENABLE_RLZ)
#if defined(ENABLE_WEBRTC)
#include "chrome/browser/media/webrtc_log_util.h"
#endif // defined(ENABLE_WEBRTC)
#if defined(USE_AURA)
#include "ui/aura/env.h"
#endif // defined(USE_AURA)
#if !defined(OS_ANDROID)
#include "chrome/browser/chrome_webusb_browser_client.h"
#include "components/webusb/webusb_detector.h"
#endif
#if defined(MOJO_SHELL_CLIENT)
#include "chrome/browser/lifetime/application_lifetime.h"
#include "content/public/common/mojo_shell_connection.h"
#endif
using content::BrowserThread;
namespace {
// This function provides some ways to test crash and assertion handling
// behavior of the program.
void HandleTestParameters(const base::CommandLine& command_line) {
// This parameter causes a null pointer crash (crash reporter trigger).
if (command_line.HasSwitch(switches::kBrowserCrashTest)) {
int* bad_pointer = NULL;
*bad_pointer = 0;
}
}
#if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
void AddFirstRunNewTabs(StartupBrowserCreator* browser_creator,
const std::vector<GURL>& new_tabs) {
for (std::vector<GURL>::const_iterator it = new_tabs.begin();
it != new_tabs.end(); ++it) {
if (it->is_valid())
browser_creator->AddFirstRunTab(*it);
}
}
#endif // !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
// Returns the new local state object, guaranteed non-NULL.
// |local_state_task_runner| must be a shutdown-blocking task runner.
PrefService* InitializeLocalState(
base::SequencedTaskRunner* local_state_task_runner,
const base::CommandLine& parsed_command_line) {
TRACE_EVENT0("startup", "ChromeBrowserMainParts::InitializeLocalState")
// Load local state. This includes the application locale so we know which
// locale dll to load. This also causes local state prefs to be registered.
PrefService* local_state = g_browser_process->local_state();
DCHECK(local_state);
#if defined(OS_WIN)
if (first_run::IsChromeFirstRun()) {
// During first run we read the google_update registry key to find what
// language the user selected when downloading the installer. This
// becomes our default language in the prefs.
// Other platforms obey the system locale.
base::string16 install_lang;
if (GoogleUpdateSettings::GetLanguage(&install_lang)) {
local_state->SetString(prefs::kApplicationLocale,
base::UTF16ToASCII(install_lang));
}
}
#endif // defined(OS_WIN)
// If the local state file for the current profile doesn't exist and the
// parent profile command line flag is present, then we should inherit some
// local state from the parent profile.
// Checking that the local state file for the current profile doesn't exist
// is the most robust way to determine whether we need to inherit or not
// since the parent profile command line flag can be present even when the
// current profile is not a new one, and in that case we do not want to
// inherit and reset the user's setting.
//
// TODO(mnissler): We should probably just instantiate a
// JSONPrefStore here instead of an entire PrefService. Once this is
// addressed, the call to browser_prefs::RegisterLocalState can move
// to chrome_prefs::CreateLocalState.
if (parsed_command_line.HasSwitch(switches::kParentProfile)) {
base::FilePath local_state_path;
PathService::Get(chrome::FILE_LOCAL_STATE, &local_state_path);
bool local_state_file_exists = base::PathExists(local_state_path);
if (!local_state_file_exists) {
base::FilePath parent_profile =
parsed_command_line.GetSwitchValuePath(switches::kParentProfile);
scoped_refptr<PrefRegistrySimple> registry = new PrefRegistrySimple();
std::unique_ptr<PrefService> parent_local_state(
chrome_prefs::CreateLocalState(
parent_profile, local_state_task_runner,
g_browser_process->policy_service(), registry, false));
registry->RegisterStringPref(prefs::kApplicationLocale, std::string());
// Right now, we only inherit the locale setting from the parent profile.
local_state->SetString(
prefs::kApplicationLocale,
parent_local_state->GetString(prefs::kApplicationLocale));
}
}
#if defined(OS_CHROMEOS)
if (parsed_command_line.HasSwitch(chromeos::switches::kLoginManager)) {
std::string owner_locale = local_state->GetString(prefs::kOwnerLocale);
// Ensure that we start with owner's locale.
if (!owner_locale.empty() &&
local_state->GetString(prefs::kApplicationLocale) != owner_locale &&
!local_state->IsManagedPreference(prefs::kApplicationLocale)) {
local_state->SetString(prefs::kApplicationLocale, owner_locale);
}
}
#endif // defined(OS_CHROMEOS)
return local_state;
}
// Initializes the primary profile, possibly doing some user prompting to pick
// a fallback profile. Returns the newly created profile, or NULL if startup
// should not continue.
Profile* CreatePrimaryProfile(const content::MainFunctionParams& parameters,
const base::FilePath& user_data_dir,
const base::CommandLine& parsed_command_line) {
TRACE_EVENT0("startup", "ChromeBrowserMainParts::CreateProfile")
TRACK_SCOPED_REGION(
"Startup", "ChromeBrowserMainParts::CreatePrimaryProfile");
base::Time start = base::Time::Now();
if (profiles::IsMultipleProfilesEnabled() &&
parsed_command_line.HasSwitch(switches::kProfileDirectory)) {
profiles::SetLastUsedProfile(
parsed_command_line.GetSwitchValueASCII(switches::kProfileDirectory));
// Clear kProfilesLastActive since the user only wants to launch a specific
// profile.
ListPrefUpdate update(g_browser_process->local_state(),
prefs::kProfilesLastActive);
base::ListValue* profile_list = update.Get();
profile_list->Clear();
}
Profile* profile = NULL;
#if defined(OS_CHROMEOS) || defined(OS_ANDROID)
// On ChromeOS and Android the ProfileManager will use the same path as the
// one we got passed. GetActiveUserProfile will therefore use the correct path
// automatically.
DCHECK_EQ(user_data_dir.value(),
g_browser_process->profile_manager()->user_data_dir().value());
profile = ProfileManager::GetActiveUserProfile();
#else
base::FilePath profile_path =
GetStartupProfilePath(user_data_dir, parsed_command_line);
profile = g_browser_process->profile_manager()->GetProfile(
profile_path);
// If we're using the --new-profile-management flag and this profile is
// signed out, then we should show the user manager instead. By switching
// the active profile to the guest profile we ensure that no
// browser windows will be opened for the guest profile.
if (switches::IsNewProfileManagement() &&
profile &&
!profile->IsGuestSession()) {
ProfileAttributesEntry* entry;
bool has_entry = g_browser_process->profile_manager()->
GetProfileAttributesStorage().
GetProfileAttributesWithPath(profile_path, &entry);
if (has_entry && entry->IsSigninRequired()) {
profile = g_browser_process->profile_manager()->GetProfile(
ProfileManager::GetGuestProfilePath());
}
}
#endif // defined(OS_CHROMEOS) || defined(OS_ANDROID)
if (profile) {
UMA_HISTOGRAM_LONG_TIMES(
"Startup.CreateFirstProfile", base::Time::Now() - start);
return profile;
}
#if !defined(OS_WIN)
// TODO(port): fix this. See comments near the definition of
// user_data_dir. It is better to CHECK-fail here than it is to
// silently exit because of missing code in the above test.
CHECK(profile) << "Cannot get default profile.";
#endif // !defined(OS_WIN)
return NULL;
}
#if defined(OS_MACOSX)
OSStatus KeychainCallback(SecKeychainEvent keychain_event,
SecKeychainCallbackInfo* info, void* context) {
return noErr;
}
#endif // defined(OS_MACOSX)
void RegisterComponentsForUpdate() {
component_updater::ComponentUpdateService* cus =
g_browser_process->component_updater();
// Registration can be before or after cus->Start() so it is ok to post
// a task to the UI thread to do registration once you done the necessary
// file IO to know you existing component version.
#if !defined(OS_CHROMEOS) && !defined(OS_ANDROID)
RegisterRecoveryComponent(cus, g_browser_process->local_state());
RegisterPepperFlashComponent(cus);
RegisterSwiftShaderComponent(cus);
RegisterWidevineCdmComponent(cus);
#endif // !defined(OS_CHROMEOS) && !defined(OS_ANDROID)
#if !defined(DISABLE_NACL) && !defined(OS_ANDROID)
#if defined(OS_CHROMEOS)
// PNaCl on Chrome OS is on rootfs and there is no need to download it. But
// Chrome4ChromeOS on Linux doesn't contain PNaCl so enable component
// installer when running on Linux. See crbug.com/422121 for more details.
if (!base::SysInfo::IsRunningOnChromeOS())
#endif // defined(OS_CHROMEOS)
g_browser_process->pnacl_component_installer()->RegisterPnaclComponent(cus);
#endif // !defined(DISABLE_NACL) && !defined(OS_ANDROID)
// Registration of the CLD Component is a no-op unless the CLD data source has
// been configured to be the "Component" data source.
RegisterCldComponent(cus);
component_updater::SupervisedUserWhitelistInstaller* whitelist_installer =
g_browser_process->supervised_user_whitelist_installer();
whitelist_installer->RegisterComponents();
base::FilePath path;
if (PathService::Get(chrome::DIR_USER_DATA, &path)) {
#if defined(OS_ANDROID)
// The CRLSet component was enabled for some releases. This code attempts to
// delete it from the local disk of those how may have downloaded it.
g_browser_process->crl_set_fetcher()->DeleteFromDisk(path);
#elif !defined(OS_CHROMEOS)
// CRLSetFetcher attempts to load a CRL set from either the local disk or
// network.
// For Chrome OS this registration is delayed until user login.
g_browser_process->crl_set_fetcher()->StartInitialLoad(cus, path);
// Registration of the EV Whitelist component here is not necessary for:
// 1. Android: Because it currently does not have the EV indicator.
// 2. Chrome OS: On Chrome OS this registration is delayed until user login.
RegisterEVWhitelistComponent(cus, path);
// Registration of the STH set fetcher here is not done for:
// Android: Because the story around CT on Mobile is not finalized yet.
// Chrome OS: On Chrome OS this registration is delayed until user login.
RegisterSTHSetComponent(cus, path);
#endif // defined(OS_ANDROID)
RegisterOriginTrialsComponent(cus, path);
RegisterFileTypePoliciesComponent(cus, path);
}
#if defined(OS_WIN)
#if defined(GOOGLE_CHROME_BUILD)
RegisterSwReporterComponent(cus);
#endif // defined(GOOGLE_CHROME_BUILD)
RegisterCAPSComponent(cus);
#endif // defined(OS_WIN)
}
#if !defined(OS_ANDROID)
bool ProcessSingletonNotificationCallback(
const base::CommandLine& command_line,
const base::FilePath& current_directory) {
// Drop the request if the browser process is already in shutdown path.
if (!g_browser_process || g_browser_process->IsShuttingDown())
return false;
if (command_line.HasSwitch(switches::kOriginalProcessStartTime)) {
std::string start_time_string =
command_line.GetSwitchValueASCII(switches::kOriginalProcessStartTime);
int64_t remote_start_time;
if (base::StringToInt64(start_time_string, &remote_start_time)) {
base::TimeDelta elapsed =
base::Time::Now() - base::Time::FromInternalValue(remote_start_time);
if (command_line.HasSwitch(switches::kFastStart)) {
UMA_HISTOGRAM_LONG_TIMES(
"Startup.WarmStartTimeFromRemoteProcessStartFast", elapsed);
} else {
UMA_HISTOGRAM_LONG_TIMES(
"Startup.WarmStartTimeFromRemoteProcessStart", elapsed);
}
}
}
g_browser_process->platform_part()->PlatformSpecificCommandLineProcessing(
command_line);
base::FilePath user_data_dir =
g_browser_process->profile_manager()->user_data_dir();
base::FilePath startup_profile_dir =
GetStartupProfilePath(user_data_dir, command_line);
StartupBrowserCreator::ProcessCommandLineAlreadyRunning(
command_line, current_directory, startup_profile_dir);
return true;
}
#endif // !defined(OS_ANDROID)
void LaunchDevToolsHandlerIfNeeded(const base::CommandLine& command_line) {
if (command_line.HasSwitch(::switches::kRemoteDebuggingPort)) {
std::string port_str =
command_line.GetSwitchValueASCII(::switches::kRemoteDebuggingPort);
int port;
if (base::StringToInt(port_str, &port) && port >= 0 && port < 65535) {
g_browser_process->CreateDevToolsHttpProtocolHandler(
"", static_cast<uint16_t>(port));
} else {
DLOG(WARNING) << "Invalid http debugger port number " << port;
}
}
}
class ScopedMainMessageLoopRunEvent {
public:
ScopedMainMessageLoopRunEvent() {
TRACE_EVENT_ASYNC_BEGIN0(
"toplevel", "ChromeBrowserMainParts::MainMessageLoopRun", this);
}
~ScopedMainMessageLoopRunEvent() {
TRACE_EVENT_ASYNC_END0("toplevel",
"ChromeBrowserMainParts::MainMessageLoopRun", this);
}
};
} // namespace
namespace chrome_browser {
#if defined(OS_WIN)
// Helper function to setup the pre-read field trial. This function is defined
// outside of the anonymous namespace to allow it to be friend with
// ChromeMetricsServiceAccessor.
void SetupPreReadFieldTrial() {
const base::string16 registry_path =
BrowserDistribution::GetDistribution()->GetRegistryPath();
// Register a synthetic field trial with the PreRead group used during the
// current startup. This must be done before the first metric log
// (metrics::MetricLog) is created. Otherwise, UMA metrics generated during
// startup won't be correctly annotated. The current function is always called
// before the first metric log is created, as part of
// ChromeBrowserMainParts::PreMainMessageLoopRun().
startup_metric_utils::RegisterPreReadSyntheticFieldTrial(
registry_path,
base::Bind(&ChromeMetricsServiceAccessor::RegisterSyntheticFieldTrial));
// Initialize the PreRead options for the current process.
startup_metric_utils::InitializePreReadOptions(registry_path);
// After startup is complete, update the PreRead group in the registry. The
// group written in the registry will be used for the next startup.
BrowserThread::PostAfterStartupTask(
FROM_HERE, content::BrowserThread::GetBlockingPool(),
base::Bind(&startup_metric_utils::UpdatePreReadOptions, registry_path));
}
#endif // defined(OS_WIN)
// This error message is not localized because we failed to load the
// localization data files.
#if defined(OS_WIN)
const char kMissingLocaleDataTitle[] = "Missing File Error";
#endif // defined(OS_WIN)
#if defined(OS_WIN)
// TODO(port) This should be used on Linux Aura as well. http://crbug.com/338969
const char kMissingLocaleDataMessage[] =
"Unable to find locale data files. Please reinstall.";
#endif // defined(OS_WIN)
} // namespace chrome_browser
// BrowserMainParts ------------------------------------------------------------
ChromeBrowserMainParts::ChromeBrowserMainParts(
const content::MainFunctionParams& parameters)
: parameters_(parameters),
parsed_command_line_(parameters.command_line),
result_code_(content::RESULT_CODE_NORMAL_EXIT),
startup_watcher_(new StartupTimeBomb()),
shutdown_watcher_(new ShutdownWatcherHelper()),
browser_field_trials_(parameters.command_line),
sampling_profiler_(
base::PlatformThread::CurrentId(),
sampling_profiler_config_.GetSamplingParams(),
metrics::CallStackProfileMetricsProvider::GetProfilerCallback(
metrics::CallStackProfileMetricsProvider::Params(
metrics::CallStackProfileMetricsProvider::PROCESS_STARTUP,
false))),
profile_(NULL),
run_message_loop_(true),
notify_result_(ProcessSingleton::PROCESS_NONE),
local_state_(NULL),
restart_last_session_(false) {
if (sampling_profiler_config_.IsProfilerEnabled())
sampling_profiler_.Start();
// If we're running tests (ui_task is non-null).
if (parameters.ui_task)
browser_defaults::enable_help_app = false;
// Chrome disallows cookies by default. All code paths that want to use
// cookies need to go through one of Chrome's URLRequestContexts which have
// a ChromeNetworkDelegate attached that selectively allows cookies again.
net::URLRequest::SetDefaultCookiePolicyToBlock();
}
ChromeBrowserMainParts::~ChromeBrowserMainParts() {
for (int i = static_cast<int>(chrome_extra_parts_.size())-1; i >= 0; --i)
delete chrome_extra_parts_[i];
chrome_extra_parts_.clear();
}
// This will be called after the command-line has been mutated by about:flags
void ChromeBrowserMainParts::SetupMetricsAndFieldTrials() {
TRACE_EVENT0("startup", "ChromeBrowserMainParts::SetupMetricsAndFieldTrials");
// Must initialize metrics after labs have been converted into switches,
// but before field trials are set up (so that client ID is available for
// one-time randomized field trials).
// Initialize FieldTrialList to support FieldTrials that use one-time
// randomization.
metrics::MetricsService* metrics = browser_process_->metrics_service();
// TODO(asvitkine): Turn into a DCHECK after http://crbug.com/359406 is fixed.
CHECK(!field_trial_list_);
// TODO(asvitkine): Remove this after http://crbug.com/359406 is fixed.
base::FieldTrialList::EnableGlobalStateChecks();
field_trial_list_.reset(
new base::FieldTrialList(metrics->CreateEntropyProvider().release()));
const base::CommandLine* command_line =
base::CommandLine::ForCurrentProcess();
if (command_line->HasSwitch(switches::kEnableBenchmarking) ||
command_line->HasSwitch(cc::switches::kEnableGpuBenchmarking)) {
base::FieldTrial::EnableBenchmarking();
}
if (command_line->HasSwitch(switches::kForceFieldTrialParams)) {
bool result = chrome_variations::AssociateParamsFromString(
command_line->GetSwitchValueASCII(switches::kForceFieldTrialParams));
CHECK(result) << "Invalid --" << switches::kForceFieldTrialParams
<< " list specified.";
}
// Ensure any field trials specified on the command line are initialized.
if (command_line->HasSwitch(switches::kForceFieldTrials)) {
std::set<std::string> unforceable_field_trials;
#if defined(OFFICIAL_BUILD)
unforceable_field_trials.insert("SettingsEnforcement");
#endif // defined(OFFICIAL_BUILD)
// Create field trials without activating them, so that this behaves in a
// consistent manner with field trials created from the server.
bool result = base::FieldTrialList::CreateTrialsFromString(
command_line->GetSwitchValueASCII(switches::kForceFieldTrials),
unforceable_field_trials);
CHECK(result) << "Invalid --" << switches::kForceFieldTrials
<< " list specified.";
}
if (command_line->HasSwitch(switches::kForceVariationIds)) {
// Create default variation ids which will always be included in the
// X-Client-Data request header.
variations::VariationsHttpHeaderProvider* provider =
variations::VariationsHttpHeaderProvider::GetInstance();
bool result = provider->SetDefaultVariationIds(
command_line->GetSwitchValueASCII(switches::kForceVariationIds));
CHECK(result) << "Invalid --" << switches::kForceVariationIds
<< " list specified.";
metrics->AddSyntheticTrialObserver(provider);
}
std::unique_ptr<base::FeatureList> feature_list(new base::FeatureList);
feature_list->InitializeFromCommandLine(
command_line->GetSwitchValueASCII(switches::kEnableFeatures),
command_line->GetSwitchValueASCII(switches::kDisableFeatures));
#if defined(FIELDTRIAL_TESTING_ENABLED)
if (!command_line->HasSwitch(switches::kDisableFieldTrialTestingConfig) &&
!command_line->HasSwitch(switches::kForceFieldTrials) &&
!command_line->HasSwitch(variations::switches::kVariationsServerURL)) {
chrome_variations::AssociateDefaultFieldTrialConfig(feature_list.get());
}
#endif // defined(FIELDTRIAL_TESTING_ENABLED)
variations::VariationsService* variations_service =
browser_process_->variations_service();
if (variations_service)
variations_service->CreateTrialsFromSeed(feature_list.get());
base::FeatureList::SetInstance(std::move(feature_list));
// This must be called after |local_state_| is initialized.
browser_field_trials_.SetupFieldTrials();
// Enable Navigation Tracing only if a trace upload url is specified.
if (command_line->HasSwitch(switches::kEnableNavigationTracing) &&
command_line->HasSwitch(switches::kTraceUploadURL)) {
tracing::SetupNavigationTracing();
}
// Initialize FieldTrialSynchronizer system. This is a singleton and is used
// for posting tasks via base::Bind. Its deleted when it goes out of scope.
// Even though base::Bind does AddRef and Release, the object will not be
// deleted after the Task is executed.
field_trial_synchronizer_ = new FieldTrialSynchronizer();
// Now that field trials have been created, initializes metrics recording.
metrics->InitializeMetricsRecordingState();
const version_info::Channel channel = chrome::GetChannel();
// Enable profiler instrumentation depending on the channel.
switch (channel) {
case version_info::Channel::UNKNOWN:
case version_info::Channel::CANARY:
tracked_objects::ScopedTracker::Enable();
break;
case version_info::Channel::DEV:
case version_info::Channel::BETA:
case version_info::Channel::STABLE:
// Don't enable instrumentation.
break;
}
// Register a synthetic field trial for the sampling profiler configuration
// that was already chosen.
sampling_profiler_config_.RegisterSyntheticFieldTrial();
#if defined(OS_WIN)
chrome_browser::SetupPreReadFieldTrial();
#endif // defined(OS_WIN)
}
// ChromeBrowserMainParts: |SetupMetricsAndFieldTrials()| related --------------
void ChromeBrowserMainParts::StartMetricsRecording() {
TRACE_EVENT0("startup", "ChromeBrowserMainParts::StartMetricsRecording");
g_browser_process->metrics_service()->CheckForClonedInstall(
BrowserThread::GetMessageLoopProxyForThread(BrowserThread::FILE));
g_browser_process->GetMetricsServicesManager()->UpdateUploadPermissions(true);
}
void ChromeBrowserMainParts::RecordBrowserStartupTime() {
// Don't record any metrics if UI was displayed before this point e.g.
// warning dialogs.
if (startup_metric_utils::WasNonBrowserUIDisplayed())
return;
bool is_first_run = false;
#if !defined(OS_ANDROID)
// On Android, first run is handled in Java code, and the C++ side of Chrome
// doesn't know if this is the first run. This will cause some inaccuracy in
// the UMA statistics, but this should be minor (first runs are rare).
is_first_run = first_run::IsChromeFirstRun();
#endif // defined(OS_ANDROID)
// Record collected startup metrics.
startup_metric_utils::RecordBrowserMainMessageLoopStart(
base::TimeTicks::Now(), is_first_run, g_browser_process->local_state());
}
// -----------------------------------------------------------------------------
// TODO(viettrungluu): move more/rest of BrowserMain() into BrowserMainParts.
#if defined(OS_WIN)
#define DLLEXPORT __declspec(dllexport)
// We use extern C for the prototype DLLEXPORT to avoid C++ name mangling.
extern "C" {
DLLEXPORT void __cdecl RelaunchChromeBrowserWithNewCommandLineIfNeeded();
}
DLLEXPORT void __cdecl RelaunchChromeBrowserWithNewCommandLineIfNeeded() {
// Need an instance of AtExitManager to handle singleton creations and
// deletions. We need this new instance because, the old instance created
// in ChromeMain() got destructed when the function returned.
base::AtExitManager exit_manager;
upgrade_util::RelaunchChromeBrowserWithNewCommandLineIfNeeded();
}
#endif
// content::BrowserMainParts implementation ------------------------------------
void ChromeBrowserMainParts::PreEarlyInitialization() {
TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreEarlyInitialization");
for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
chrome_extra_parts_[i]->PreEarlyInitialization();
}
void ChromeBrowserMainParts::PostEarlyInitialization() {
TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostEarlyInitialization");
for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
chrome_extra_parts_[i]->PostEarlyInitialization();
}
void ChromeBrowserMainParts::ToolkitInitialized() {
TRACE_EVENT0("startup", "ChromeBrowserMainParts::ToolkitInitialized");
for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
chrome_extra_parts_[i]->ToolkitInitialized();
}
void ChromeBrowserMainParts::PreMainMessageLoopStart() {
TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopStart");
for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
chrome_extra_parts_[i]->PreMainMessageLoopStart();
}
void ChromeBrowserMainParts::PostMainMessageLoopStart() {
TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostMainMessageLoopStart");
// device_event_log must be initialized after the message loop. Calls to
// {DEVICE}_LOG prior to here will only be logged with VLOG. Some
// platforms (e.g. chromeos) may have already initialized this.
if (!device_event_log::IsInitialized())
device_event_log::Initialize(0 /* default max entries */);
for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
chrome_extra_parts_[i]->PostMainMessageLoopStart();
}
int ChromeBrowserMainParts::PreCreateThreads() {
TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreCreateThreads");
result_code_ = PreCreateThreadsImpl();
if (result_code_ == content::RESULT_CODE_NORMAL_EXIT) {
#if !defined(OS_ANDROID)
// These members must be initialized before exiting this function normally.
DCHECK(master_prefs_.get());
DCHECK(browser_creator_.get());
#endif // !defined(OS_ANDROID)
for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
chrome_extra_parts_[i]->PreCreateThreads();
}
// It is important to call gl_string_manager()->Initialize() before starting
// the gpu process. Internally it properly setup the black listed features.
// Which it is used to decide whether to start or not the gpu process from
// BrowserMainLoop::BrowserThreadsStarted.
// Retrieve cached GL strings from local state and use them for GPU
// blacklist decisions.
if (g_browser_process->gl_string_manager())
g_browser_process->gl_string_manager()->Initialize();
// Create an instance of GpuModeManager to watch gpu mode pref change.
g_browser_process->gpu_mode_manager();
return result_code_;
}
int ChromeBrowserMainParts::PreCreateThreadsImpl() {
TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreCreateThreadsImpl")
run_message_loop_ = false;
#if !defined(OS_ANDROID)
chrome::MaybeShowInvalidUserDataDirWarningDialog();
#endif // !defined(OS_ANDROID)
if (!PathService::Get(chrome::DIR_USER_DATA, &user_data_dir_))
return chrome::RESULT_CODE_MISSING_DATA;
// Force MediaCaptureDevicesDispatcher to be created on UI thread.
MediaCaptureDevicesDispatcher::GetInstance();
// Android's first run is done in Java instead of native.
#if !defined(OS_ANDROID)
process_singleton_.reset(new ChromeProcessSingleton(
user_data_dir_, base::Bind(&ProcessSingletonNotificationCallback)));
// Cache first run state early.
first_run::IsChromeFirstRun();
#endif // !defined(OS_ANDROID)
scoped_refptr<base::SequencedTaskRunner> local_state_task_runner =
JsonPrefStore::GetTaskRunnerForFile(
base::FilePath(chrome::kLocalStorePoolName),
BrowserThread::GetBlockingPool());
{
TRACE_EVENT0("startup",
"ChromeBrowserMainParts::PreCreateThreadsImpl:InitBrowswerProcessImpl");
browser_process_.reset(new BrowserProcessImpl(local_state_task_runner.get(),
parsed_command_line()));
}
if (parsed_command_line().HasSwitch(switches::kEnableProfiling)) {
TRACE_EVENT0("startup",
"ChromeBrowserMainParts::PreCreateThreadsImpl:InitProfiling");
// User wants to override default tracking status.
std::string flag =
parsed_command_line().GetSwitchValueASCII(switches::kEnableProfiling);
// Default to basic profiling (no parent child support).
tracked_objects::ThreadData::Status status =
tracked_objects::ThreadData::PROFILING_ACTIVE;
if (flag.compare("0") != 0)
status = tracked_objects::ThreadData::DEACTIVATED;
tracked_objects::ThreadData::InitializeAndSetTrackingStatus(status);
}
local_state_ = InitializeLocalState(
local_state_task_runner.get(), parsed_command_line());
#if !defined(OS_ANDROID)
// These members must be initialized before returning from this function.
master_prefs_.reset(new first_run::MasterPrefs);
// Android doesn't use StartupBrowserCreator.
browser_creator_.reset(new StartupBrowserCreator);
// TODO(yfriedman): Refactor Android to re-use UMABrowsingActivityObserver
chrome::UMABrowsingActivityObserver::Init();
#endif // !defined(OS_ANDROID)
#if !defined(OS_CHROMEOS)
// Convert active labs into switches. This needs to be done before
// ResourceBundle::InitSharedInstanceWithLocale as some loaded resources are
// affected by experiment flags (--touch-optimized-ui in particular).
// On ChromeOS system level flags are applied from the device settings from
// the session manager.
{
TRACE_EVENT0("startup",
"ChromeBrowserMainParts::PreCreateThreadsImpl:ConvertFlags");
flags_ui::PrefServiceFlagsStorage flags_storage_(
g_browser_process->local_state());
about_flags::ConvertFlagsToSwitches(&flags_storage_,
base::CommandLine::ForCurrentProcess(),
flags_ui::kAddSentinels);
}
#endif // !defined(OS_CHROMEOS)
// The MaterialDesignController needs to look at command line flags, which
// are not available until this point. Now that they are, proceed with
// initializing the MaterialDesignController.
ui::MaterialDesignController::Initialize();
#if defined(OS_CHROMEOS)
ash::MaterialDesignController::Initialize();
#endif // !defined(OS_CHROMEOS)
#if defined(OS_MACOSX)
// Material Design resource packs can be loaded now that command line flags
// are set. See https://crbug.com/585290 .
ui::ResourceBundle::GetSharedInstance().LoadMaterialDesignResources();
#endif
#if defined(OS_WIN)
// This is needed to enable ETW exporting when requested in about:flags.
// Normally, we enable it in ContentMainRunnerImpl::Initialize when the flag
// is present on the command line but flags in about:flags are converted only
// after this function runs. Note that this starts exporting later which
// affects tracing the browser startup. Also, this is only relevant for the
// browser process, as other processes will get all the flags on their command
// line regardless of the origin (command line or about:flags).
if (parsed_command_line().HasSwitch(switches::kTraceExportEventsToETW))
base::trace_event::TraceEventETWExport::EnableETWExport();
#endif // OS_WIN
local_state_->UpdateCommandLinePrefStore(
new CommandLinePrefStore(base::CommandLine::ForCurrentProcess()));
// Reset the command line in the crash report details, since we may have
// just changed it to include experiments.
crash_keys::SetCrashKeysFromCommandLine(
*base::CommandLine::ForCurrentProcess());
// Mac starts it earlier in |PreMainMessageLoopStart()| (because it is
// needed when loading the MainMenu.nib and the language doesn't depend on
// anything since it comes from Cocoa.
#if defined(OS_MACOSX)
std::string locale =
parameters().ui_task ? "en-US" : l10n_util::GetLocaleOverride();
browser_process_->SetApplicationLocale(locale);
#else
const std::string locale =
local_state_->GetString(prefs::kApplicationLocale);
// On a POSIX OS other than ChromeOS, the parameter that is passed to the
// method InitSharedInstance is ignored.
TRACE_EVENT_BEGIN0("startup",
"ChromeBrowserMainParts::PreCreateThreadsImpl:InitResourceBundle");
const std::string loaded_locale =
ui::ResourceBundle::InitSharedInstanceWithLocale(
locale, NULL, ui::ResourceBundle::LOAD_COMMON_RESOURCES);
TRACE_EVENT_END0("startup",
"ChromeBrowserMainParts::PreCreateThreadsImpl:InitResourceBundle");
if (loaded_locale.empty() &&
!parsed_command_line().HasSwitch(switches::kNoErrorDialogs)) {
ShowMissingLocaleMessageBox();
return chrome::RESULT_CODE_MISSING_DATA;
}
CHECK(!loaded_locale.empty()) << "Locale could not be found for " << locale;
browser_process_->SetApplicationLocale(loaded_locale);
{
TRACE_EVENT0("startup",
"ChromeBrowserMainParts::PreCreateThreadsImpl:AddDataPack");
base::FilePath resources_pack_path;
PathService::Get(chrome::FILE_RESOURCES_PACK, &resources_pack_path);
#if defined(OS_ANDROID)
ui::LoadMainAndroidPackFile("assets/resources.pak", resources_pack_path);
#else
ResourceBundle::GetSharedInstance().AddDataPackFromPath(
resources_pack_path, ui::SCALE_FACTOR_NONE);
#endif // defined(OS_ANDROID)
}
#endif // defined(OS_MACOSX)
// Android does first run in Java instead of native.
// Chrome OS has its own out-of-box-experience code.
#if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
// On first run, we need to process the predictor preferences before the
// browser's profile_manager object is created, but after ResourceBundle
// is initialized.
if (first_run::IsChromeFirstRun()) {
first_run::ProcessMasterPreferencesResult pmp_result =
first_run::ProcessMasterPreferences(user_data_dir_,
master_prefs_.get());
if (pmp_result == first_run::EULA_EXIT_NOW)
return chrome::RESULT_CODE_EULA_REFUSED;
if (!parsed_command_line().HasSwitch(switches::kApp) &&
!parsed_command_line().HasSwitch(switches::kAppId) &&
!parsed_command_line().HasSwitch(switches::kShowAppList)) {
AddFirstRunNewTabs(browser_creator_.get(), master_prefs_->new_tabs);
}
// TODO(macourteau): refactor preferences that are copied from
// master_preferences into local_state, as a "local_state" section in
// master preferences. If possible, a generic solution would be preferred
// over a copy one-by-one of specific preferences. Also see related TODO
// in first_run.h.
// Store the initial VariationsService seed in local state, if it exists
// in master prefs.
if (!master_prefs_->variations_seed.empty() ||
!master_prefs_->compressed_variations_seed.empty()) {
if (!master_prefs_->variations_seed.empty()) {
local_state_->SetString(variations::prefs::kVariationsSeed,
master_prefs_->variations_seed);
}
if (!master_prefs_->compressed_variations_seed.empty()) {
local_state_->SetString(variations::prefs::kVariationsCompressedSeed,
master_prefs_->compressed_variations_seed);
}
if (!master_prefs_->variations_seed_signature.empty()) {
local_state_->SetString(variations::prefs::kVariationsSeedSignature,
master_prefs_->variations_seed_signature);
}
// Set the variation seed date to the current system time. If the user's
// clock is incorrect, this may cause some field trial expiry checks to
// not do the right thing until the next seed update from the server,
// when this value will be updated.
local_state_->SetInt64(variations::prefs::kVariationsSeedDate,
base::Time::Now().ToInternalValue());
}
if (!master_prefs_->suppress_default_browser_prompt_for_version.empty()) {
local_state_->SetString(
prefs::kBrowserSuppressDefaultBrowserPrompt,
master_prefs_->suppress_default_browser_prompt_for_version);
}
#if defined(OS_WIN)
if (!master_prefs_->welcome_page_on_os_upgrade_enabled)
local_state_->SetBoolean(prefs::kWelcomePageOnOSUpgradeEnabled, false);
#endif
}
#endif // !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
#if defined(OS_LINUX) || defined(OS_OPENBSD)
// Set the product channel for crash reports.
base::debug::SetCrashKeyValue(crash_keys::kChannel,
chrome::GetChannelString());
#endif // defined(OS_LINUX) || defined(OS_OPENBSD)
// Initialize tracking synchronizer system.
tracking_synchronizer_ = new metrics::TrackingSynchronizer(
base::WrapUnique(new base::DefaultTickClock()),
base::Bind(&metrics::ContentTrackingSynchronizerDelegate::Create));
#if defined(OS_MACOSX)
// Get the Keychain API to register for distributed notifications on the main
// thread, which has a proper CFRunloop, instead of later on the I/O thread,
// which doesn't. This ensures those notifications will get delivered
// properly. See issue 37766.
// (Note that the callback mask here is empty. I don't want to register for
// any callbacks, I just want to initialize the mechanism.)
SecKeychainAddCallback(&KeychainCallback, 0, NULL);
#endif // defined(OS_MACOSX)
#if defined(OS_CHROMEOS)
// Must be done after g_browser_process is constructed, before
// SetupMetricsAndFieldTrials().
chromeos::CrosSettings::Initialize();
#endif // defined(OS_CHROMEOS)
// Now the command line has been mutated based on about:flags, we can setup
// metrics and initialize field trials. The field trials are needed by
// IOThread's initialization which happens in BrowserProcess:PreCreateThreads.
SetupMetricsAndFieldTrials();
// ChromeOS needs ResourceBundle::InitSharedInstance to be called before this.
browser_process_->PreCreateThreads();
return content::RESULT_CODE_NORMAL_EXIT;
}
void ChromeBrowserMainParts::PreMainMessageLoopRun() {
#if defined(MOJO_SHELL_CLIENT)
if (content::MojoShellConnection::Get() &&
content::MojoShellConnection::Get()->UsingExternalShell()) {
content::MojoShellConnection::Get()->SetConnectionLostClosure(
base::Bind(&chrome::SessionEnding));
}
#endif
TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopRun");
TRACK_SCOPED_REGION(
"Startup", "ChromeBrowserMainParts::PreMainMessageLoopRun");
result_code_ = PreMainMessageLoopRunImpl();
for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
chrome_extra_parts_[i]->PreMainMessageLoopRun();
}
// PreMainMessageLoopRun calls these extra stages in the following order:
// PreMainMessageLoopRunImpl()
// ... initial setup, including browser_process_ setup.
// PreProfileInit()
// ... additional setup, including CreateProfile()
// PostProfileInit()
// ... additional setup
// PreBrowserStart()
// ... browser_creator_->Start (OR parameters().ui_task->Run())
// PostBrowserStart()
void ChromeBrowserMainParts::PreProfileInit() {
TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreProfileInit");
for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
chrome_extra_parts_[i]->PreProfileInit();
#if !defined(OS_ANDROID)
// Initialize the feedback uploader so it can setup notifications for profile
// creation.
feedback::FeedbackProfileObserver::Initialize();
// Ephemeral profiles may have been left behind if the browser crashed.
g_browser_process->profile_manager()->CleanUpEphemeralProfiles();
#endif // !defined(OS_ANDROID)
#if defined(ENABLE_EXTENSIONS)
javascript_dialog_extensions_client::InstallClient();
#endif // defined(ENABLE_EXTENSIONS)
InstallChromeJavaScriptNativeDialogFactory();
}
void ChromeBrowserMainParts::PostProfileInit() {
TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostProfileInit");
#if BUILDFLAG(ANDROID_JAVA_UI)
DevToolsDiscoveryProviderAndroid::Install();
#else
ChromeDevToolsDiscoveryProvider::Install();
#endif // BUILDFLAG(ANDROID_JAVA_UI)
LaunchDevToolsHandlerIfNeeded(parsed_command_line());
if (parsed_command_line().HasSwitch(::switches::kAutoOpenDevToolsForTabs))
g_browser_process->CreateDevToolsAutoOpener();
for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
chrome_extra_parts_[i]->PostProfileInit();
}
#if defined(SYZYASAN)
// This function must be in the global namespace as it needs to be friended
// by ChromeMetricsServiceAccessor.
void SyzyASANRegisterExperiment(const char* name, const char* group) {
ChromeMetricsServiceAccessor::RegisterSyntheticFieldTrial(name, group);
}
namespace {
void WINAPI SyzyASANExperimentCallback(const char* name, const char* group) {
// Indirect through the function above, so that the friend declaration doesn't
// need the ugly calling convention.
SyzyASANRegisterExperiment(name, group);
}
void SetupSyzyASAN() {
typedef VOID(WINAPI* SyzyASANExperimentCallbackFn)(const char* name,
const char* group);
typedef VOID(WINAPI* SyzyASANEnumExperimentsFn)(SyzyASANExperimentCallbackFn);
HMODULE syzyasan_handle = ::GetModuleHandle(L"syzyasan_rtl.dll");
if (!syzyasan_handle)
return;
// Export the SyzyASAN experiments as synthetic field trials.
SyzyASANEnumExperimentsFn syzyasan_enum_experiments =
reinterpret_cast<SyzyASANEnumExperimentsFn>(
::GetProcAddress(syzyasan_handle, "asan_EnumExperiments"));
if (syzyasan_enum_experiments) {
syzyasan_enum_experiments(&SyzyASANExperimentCallback);
}
// Enable the deferred free mechanism in the syzyasan module, which helps the
// performance by deferring some work on the critical path to a background
// thread.
if (base::FeatureList::IsEnabled(features::kSyzyasanDeferredFree)) {
typedef VOID(WINAPI * SyzyasanEnableDeferredFreeThreadFunc)(VOID);
bool success = false;
SyzyasanEnableDeferredFreeThreadFunc syzyasan_enable_deferred_free =
reinterpret_cast<SyzyasanEnableDeferredFreeThreadFunc>(
::GetProcAddress(syzyasan_handle,
"asan_EnableDeferredFreeThread"));
if (syzyasan_enable_deferred_free) {
syzyasan_enable_deferred_free();
success = true;
}
UMA_HISTOGRAM_BOOLEAN("Syzyasan.DeferredFreeWasEnabled", success);
}
}
} // namespace
#endif // SYZYASAN
void ChromeBrowserMainParts::PreBrowserStart() {
TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreBrowserStart");
for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
chrome_extra_parts_[i]->PreBrowserStart();
three_d_observer_.reset(new ThreeDAPIObserver());
#if defined(SYZYASAN)
SetupSyzyASAN();
#endif
// Start the tab manager here so that we give the most amount of time for the
// other services to start up before we start adjusting the oom priority.
#if defined(OS_WIN) || defined(OS_MACOSX) || defined(OS_LINUX)
g_browser_process->GetTabManager()->Start();
#endif
}
void ChromeBrowserMainParts::PostBrowserStart() {
TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostBrowserStart");
for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
chrome_extra_parts_[i]->PostBrowserStart();
#if !defined(OS_ANDROID)
// Allow ProcessSingleton to process messages.
process_singleton_->Unlock();
#endif // !defined(OS_ANDROID)
#if defined(ENABLE_WEBRTC)
// Set up a task to delete old WebRTC log files for all profiles. Use a delay
// to reduce the impact on startup time.
BrowserThread::PostDelayedTask(
BrowserThread::UI,
FROM_HERE,
base::Bind(&WebRtcLogUtil::DeleteOldWebRtcLogFilesForAllProfiles),
base::TimeDelta::FromMinutes(1));
#endif // defined(ENABLE_WEBRTC)
#if !defined(OS_ANDROID)
// WebUSB is an experimental web API. The sites these notifications will link
// to will only work if the experiment is enabled and WebUSB feature is
// enabled.
if (base::CommandLine::ForCurrentProcess()->HasSwitch(
switches::kEnableExperimentalWebPlatformFeatures) &&
base::FeatureList::IsEnabled(features::kWebUsb)) {
webusb_browser_client_.reset(new ChromeWebUsbBrowserClient());
webusb_detector_.reset(
new webusb::WebUsbDetector(webusb_browser_client_.get()));
}
#endif
// At this point, StartupBrowserCreator::Start has run creating initial
// browser windows and tabs, but no progress has been made in loading
// content as the main message loop hasn't started processing tasks yet.
// We setup to observe to the initial page load here to defer running
// task posted via PostAfterStartupTask until its complete.
AfterStartupTaskUtils::StartMonitoringStartup();
}
int ChromeBrowserMainParts::PreMainMessageLoopRunImpl() {
TRACE_EVENT0("startup", "ChromeBrowserMainParts::PreMainMessageLoopRunImpl");
TRACK_SCOPED_REGION(
"Startup", "ChromeBrowserMainParts::PreMainMessageLoopRunImpl");
SCOPED_UMA_HISTOGRAM_LONG_TIMER("Startup.PreMainMessageLoopRunImplLongTime");
const base::TimeTicks start_time_step1 = base::TimeTicks::Now();
#if defined(OS_WIN)
// Pre-read chrome_child.dll.
const startup_metric_utils::PreReadOptions pre_read_options =
startup_metric_utils::GetPreReadOptions();
if (pre_read_options.pre_read &&
pre_read_options.pre_read_chrome_child_in_browser) {
BrowserThread::PostTask(
BrowserThread::FILE_USER_BLOCKING, FROM_HERE,
base::Bind(&PreReadFile,
installer::GetModulePath(installer::kChromeChildDll),
pre_read_options));
}
// Windows parental controls calls can be slow, so we do an early init here
// that calculates this value off of the UI thread.
IncognitoModePrefs::InitializePlatformParentalControls();
#endif
#if defined(ENABLE_EXTENSIONS)
if (!variations::GetVariationParamValue(
"LightSpeed", "EarlyInitStartup").empty()) {
// Try to compute this early on another thread so that we don't spend time
// during profile load initializing the extensions APIs.
BrowserThread::PostTask(
BrowserThread::FILE_USER_BLOCKING,
FROM_HERE,
base::Bind(
base::IgnoreResult(&extensions::FeatureProvider::GetAPIFeatures)));
}
#endif
// Android updates the metrics service dynamically depending on whether the
// application is in the foreground or not. Do not start here.
#if !defined(OS_ANDROID)
// Now that the file thread has been started, start recording.
StartMetricsRecording();
#endif // !defined(OS_ANDROID)
if (!base::debug::BeingDebugged()) {
// Create watchdog thread after creating all other threads because it will
// watch the other threads and they must be running.
browser_process_->watchdog_thread();
}
// Do any initializating in the browser process that requires all threads
// running.
browser_process_->PreMainMessageLoopRun();
// Record last shutdown time into a histogram.
browser_shutdown::ReadLastShutdownInfo();
#if defined(OS_WIN)
// On Windows, we use our startup as an opportunity to do upgrade/uninstall
// tasks. Those care whether the browser is already running. On Linux/Mac,
// upgrade/uninstall happen separately.
bool already_running = browser_util::IsBrowserAlreadyRunning();
// If the command line specifies 'uninstall' then we need to work here
// unless we detect another chrome browser running.
if (parsed_command_line().HasSwitch(switches::kUninstall)) {
return DoUninstallTasks(already_running);
}
if (parsed_command_line().HasSwitch(switches::kHideIcons) ||
parsed_command_line().HasSwitch(switches::kShowIcons)) {
return ChromeBrowserMainPartsWin::HandleIconsCommands(
parsed_command_line_);
}
ui::SelectFileDialog::SetFactory(new ChromeSelectFileDialogFactory(
BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO)));
#endif // defined(OS_WIN)
if (parsed_command_line().HasSwitch(switches::kMakeDefaultBrowser)) {
bool is_managed = g_browser_process->local_state()->IsManagedPreference(
prefs::kDefaultBrowserSettingEnabled);
if (is_managed && !g_browser_process->local_state()->GetBoolean(
prefs::kDefaultBrowserSettingEnabled)) {
return static_cast<int>(chrome::RESULT_CODE_ACTION_DISALLOWED_BY_POLICY);
}
return shell_integration::SetAsDefaultBrowser()
? static_cast<int>(content::RESULT_CODE_NORMAL_EXIT)
: static_cast<int>(chrome::RESULT_CODE_SHELL_INTEGRATION_FAILED);
}
#if defined(USE_AURA)
// Make sure aura::Env has been initialized.
CHECK(aura::Env::GetInstance());
#endif // defined(USE_AURA)
// Android doesn't support extensions and doesn't implement ProcessSingleton.
#if !defined(OS_ANDROID)
// If the command line specifies --pack-extension, attempt the pack extension
// startup action and exit.
if (parsed_command_line().HasSwitch(switches::kPackExtension)) {
extensions::StartupHelper extension_startup_helper;
if (extension_startup_helper.PackExtension(parsed_command_line()))
return content::RESULT_CODE_NORMAL_EXIT;
return chrome::RESULT_CODE_PACK_EXTENSION_ERROR;
}
// When another process is running, use that process instead of starting a
// new one. NotifyOtherProcess will currently give the other process up to
// 20 seconds to respond. Note that this needs to be done before we attempt
// to read the profile.
notify_result_ = process_singleton_->NotifyOtherProcessOrCreate();
switch (notify_result_) {
case ProcessSingleton::PROCESS_NONE:
// No process already running, fall through to starting a new one.
break;
case ProcessSingleton::PROCESS_NOTIFIED:
#if defined(OS_POSIX) && !defined(OS_MACOSX)
// On POSIX systems, print a message notifying the process is running.
printf("%s\n", base::SysWideToNativeMB(base::UTF16ToWide(
l10n_util::GetStringUTF16(IDS_USED_EXISTING_BROWSER))).c_str());
#endif // defined(OS_POSIX) && !defined(OS_MACOSX)
// Having a differentiated return type for testing allows for tests to
// verify proper handling of some switches. When not testing, stick to
// the standard Unix convention of returning zero when things went as
// expected.
if (parsed_command_line().HasSwitch(switches::kTestType))
return chrome::RESULT_CODE_NORMAL_EXIT_PROCESS_NOTIFIED;
return content::RESULT_CODE_NORMAL_EXIT;
case ProcessSingleton::PROFILE_IN_USE:
return chrome::RESULT_CODE_PROFILE_IN_USE;
case ProcessSingleton::LOCK_ERROR:
LOG(ERROR) << "Failed to create a ProcessSingleton for your profile "
"directory. This means that running multiple instances "
"would start multiple browser processes rather than "
"opening a new window in the existing process. Aborting "
"now to avoid profile corruption.";
return chrome::RESULT_CODE_PROFILE_IN_USE;
default:
NOTREACHED();
}
#endif // !defined(OS_ANDROID)
// Handle special early return paths (which couldn't be processed even earlier
// as they require the process singleton to be held) first.
std::string try_chrome =
parsed_command_line().GetSwitchValueASCII(switches::kTryChromeAgain);
if (!try_chrome.empty()) {
#if defined(OS_WIN)
// Setup.exe has determined that we need to run a retention experiment
// and has lauched chrome to show the experiment UI. It is guaranteed that
// no other Chrome is currently running as the process singleton was
// successfully grabbed above.
int try_chrome_int;
base::StringToInt(try_chrome, &try_chrome_int);
TryChromeDialogView::Result answer = TryChromeDialogView::Show(
try_chrome_int,
base::Bind(&ChromeProcessSingleton::SetActiveModalDialog,
base::Unretained(process_singleton_.get())));
if (answer == TryChromeDialogView::NOT_NOW)
return chrome::RESULT_CODE_NORMAL_EXIT_CANCEL;
if (answer == TryChromeDialogView::UNINSTALL_CHROME)
return chrome::RESULT_CODE_NORMAL_EXIT_EXP2;
// At this point the user is willing to try chrome again.
if (answer == TryChromeDialogView::TRY_CHROME_AS_DEFAULT) {
// Only set in the unattended case. This is not true on Windows 8+.
if (shell_integration::GetDefaultWebClientSetPermission() ==
shell_integration::SET_DEFAULT_UNATTENDED) {
shell_integration::SetAsDefaultBrowser();
}
}
#else
// We don't support retention experiments on Mac or Linux.
return content::RESULT_CODE_NORMAL_EXIT;
#endif // defined(OS_WIN)
}
#if defined(OS_WIN)
// Do the tasks if chrome has been upgraded while it was last running.
if (!already_running && upgrade_util::DoUpgradeTasks(parsed_command_line()))
return content::RESULT_CODE_NORMAL_EXIT;
// Check if there is any machine level Chrome installed on the current
// machine. If yes and the current Chrome process is user level, we do not
// allow the user level Chrome to run. So we notify the user and uninstall
// user level Chrome.
// Note this check needs to happen here (after the process singleton was
// obtained but before potentially creating the first run sentinel).
if (ChromeBrowserMainPartsWin::CheckMachineLevelInstall())
return chrome::RESULT_CODE_MACHINE_LEVEL_INSTALL_EXISTS;
#endif // defined(OS_WIN)
// Desktop construction occurs here, (required before profile creation).
PreProfileInit();
// Profile creation ----------------------------------------------------------
metrics::MetricsService::SetExecutionPhase(
metrics::MetricsService::CREATE_PROFILE,
g_browser_process->local_state());
UMA_HISTOGRAM_TIMES("Startup.PreMainMessageLoopRunImplStep1Time",
base::TimeTicks::Now() - start_time_step1);
// This step is costly and is already measured in Startup.CreateFirstProfile
// and more directly Profile.CreateAndInitializeProfile.
profile_ = CreatePrimaryProfile(parameters(),
user_data_dir_,
parsed_command_line());
if (!profile_)
return content::RESULT_CODE_NORMAL_EXIT;
#if !defined(OS_ANDROID)
const base::TimeTicks start_time_step2 = base::TimeTicks::Now();
// The first run sentinel must be created after the process singleton was
// grabbed and no early return paths were otherwise hit above.
first_run::CreateSentinelIfNeeded();
#endif // !defined(OS_ANDROID)
#if BUILDFLAG(ENABLE_BACKGROUND)
// Autoload any profiles which are running background apps.
// TODO(rlp): Do this on a separate thread. See http://crbug.com/99075.
browser_process_->profile_manager()->AutoloadProfiles();
#endif // BUILDFLAG(ENABLE_BACKGROUND)
// Post-profile init ---------------------------------------------------------
TranslateService::Initialize();
// Needs to be done before PostProfileInit, since login manager on CrOS is
// called inside PostProfileInit.
content::WebUIControllerFactory::RegisterFactory(
ChromeWebUIControllerFactory::GetInstance());
// NaClBrowserDelegateImpl is accessed inside PostProfileInit().
// So make sure to create it before that.
#if !defined(DISABLE_NACL)
NaClBrowserDelegateImpl* delegate =
new NaClBrowserDelegateImpl(browser_process_->profile_manager());
nacl::NaClBrowser::SetDelegate(delegate);
#endif // !defined(DISABLE_NACL)
// TODO(stevenjb): Move WIN and MACOSX specific code to appropriate Parts.
// (requires supporting early exit).
PostProfileInit();
#if !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
// Show the First Run UI if this is the first time Chrome has been run on
// this computer, or we're being compelled to do so by a command line flag.
// Note that this be done _after_ the PrefService is initialized and all
// preferences are registered, since some of the code that the importer
// touches reads preferences.
if (first_run::IsChromeFirstRun()) {
first_run::AutoImport(profile_,
master_prefs_->homepage_defined,
master_prefs_->do_import_items,
master_prefs_->dont_import_items,
master_prefs_->import_bookmarks_path);
// Note: this can pop the first run consent dialog on linux.
first_run::DoPostImportTasks(profile_,
master_prefs_->make_chrome_default_for_user);
if (!master_prefs_->suppress_first_run_default_browser_prompt) {
browser_creator_->set_show_main_browser_window(
!chrome::ShowFirstRunDefaultBrowserPrompt(profile_));
} else {
browser_creator_->set_is_default_browser_dialog_suppressed(true);
}
}
#endif // !defined(OS_ANDROID) && !defined(OS_CHROMEOS)
#if defined(OS_WIN)
// Sets things up so that if we crash from this point on, a dialog will
// popup asking the user to restart chrome. It is done this late to avoid
// testing against a bunch of special cases that are taken care early on.
ChromeBrowserMainPartsWin::PrepareRestartOnCrashEnviroment(
parsed_command_line());
// Registers Chrome with the Windows Restart Manager, which will restore the
// Chrome session when the computer is restarted after a system update.
// This could be run as late as WM_QUERYENDSESSION for system update reboots,
// but should run on startup if extended to handle crashes/hangs/patches.
// Also, better to run once here than once for each HWND's WM_QUERYENDSESSION.
if (base::win::GetVersion() >= base::win::VERSION_VISTA) {
ChromeBrowserMainPartsWin::RegisterApplicationRestart(
parsed_command_line());
}
// Verify that the profile is not on a network share and if so prepare to show
// notification to the user.
if (NetworkProfileBubble::ShouldCheckNetworkProfile(profile_)) {
BrowserThread::PostTask(BrowserThread::FILE, FROM_HERE,
base::Bind(&NetworkProfileBubble::CheckNetworkProfile,
profile_->GetPath()));
}
#endif // defined(OS_WIN)
#if defined(ENABLE_RLZ) && !defined(OS_CHROMEOS)
// Init the RLZ library. This just binds the dll and schedules a task on the
// file thread to be run sometime later. If this is the first run we record
// the installation event.
PrefService* pref_service = profile_->GetPrefs();
int ping_delay = first_run::IsChromeFirstRun() ? master_prefs_->ping_delay :
pref_service->GetInteger(first_run::GetPingDelayPrefName().c_str());
// Negative ping delay means to send ping immediately after a first search is
// recorded.
rlz::RLZTracker::SetRlzDelegate(
base::WrapUnique(new ChromeRLZTrackerDelegate));
rlz::RLZTracker::InitRlzDelayed(
first_run::IsChromeFirstRun(), ping_delay < 0,
base::TimeDelta::FromMilliseconds(abs(ping_delay)),
ChromeRLZTrackerDelegate::IsGoogleDefaultSearch(profile_),
ChromeRLZTrackerDelegate::IsGoogleHomepage(profile_),
ChromeRLZTrackerDelegate::IsGoogleInStartpages(profile_));
#endif // defined(ENABLE_RLZ) && !defined(OS_CHROMEOS)
// Configure modules that need access to resources.
net::NetModule::SetResourceProvider(chrome_common_net::NetResourceProvider);
media::SetLocalizedStringProvider(
chrome_common_media::LocalizedStringProvider);
// In unittest mode, this will do nothing. In normal mode, this will create
// the global IntranetRedirectDetector instance, which will promptly go to
// sleep for seven seconds (to avoid slowing startup), and wake up afterwards
// to see if it should do anything else.
//
// A simpler way of doing all this would be to have some function which could
// give the time elapsed since startup, and simply have this object check that
// when asked to initialize itself, but this doesn't seem to exist.
//
// This can't be created in the BrowserProcessImpl constructor because it
// needs to read prefs that get set after that runs.
browser_process_->intranet_redirect_detector();
#if defined(ENABLE_PRINT_PREVIEW) && !defined(OFFICIAL_BUILD)
if (parsed_command_line().HasSwitch(switches::kDebugPrint)) {
base::FilePath path =
parsed_command_line().GetSwitchValuePath(switches::kDebugPrint);
printing::PrintedDocument::set_debug_dump_path(path);
}
#endif // defined(ENABLE_PRINT_PREVIEW) && !defined(OFFICIAL_BUILD)
HandleTestParameters(parsed_command_line());
browser_process_->metrics_service()->RecordBreakpadHasDebugger(
base::debug::BeingDebugged());
language_usage_metrics::LanguageUsageMetrics::RecordAcceptLanguages(
profile_->GetPrefs()->GetString(prefs::kAcceptLanguages));
language_usage_metrics::LanguageUsageMetrics::RecordApplicationLanguage(
browser_process_->GetApplicationLocale());
// Start watching for hangs during startup. We disarm this hang detector when
// ThreadWatcher takes over or when browser is shutdown or when
// startup_watcher_ is deleted.
metrics::MetricsService::SetExecutionPhase(
metrics::MetricsService::STARTUP_TIMEBOMB_ARM,
g_browser_process->local_state());
startup_watcher_->Arm(base::TimeDelta::FromSeconds(600));
// On mobile, need for clean shutdown arises only when the application comes
// to foreground (i.e. MetricsService::OnAppEnterForeground is called).
// http://crbug.com/179143
#if !defined(OS_ANDROID)
// Start watching for a hang.
browser_process_->metrics_service()->LogNeedForCleanShutdown();
#endif // !defined(OS_ANDROID)
#if defined(ENABLE_PRINT_PREVIEW)
// Create the instance of the cloud print proxy service so that it can launch
// the service process if needed. This is needed because the service process
// might have shutdown because an update was available.
// TODO(torne): this should maybe be done with
// BrowserContextKeyedServiceFactory::ServiceIsCreatedWithBrowserContext()
// instead?
CloudPrintProxyServiceFactory::GetForProfile(profile_);
#endif // defined(ENABLE_PRINT_PREVIEW)
// Start watching all browser threads for responsiveness.
metrics::MetricsService::SetExecutionPhase(
metrics::MetricsService::THREAD_WATCHER_START,
g_browser_process->local_state());
ThreadWatcherList::StartWatchingAll(parsed_command_line());
#if defined(OS_ANDROID)
ThreadWatcherAndroid::RegisterApplicationStatusListener();
#endif // defined(OS_ANDROID)
#if !defined(DISABLE_NACL)
BrowserThread::PostTask(
BrowserThread::IO,
FROM_HERE,
base::Bind(nacl::NaClProcessHost::EarlyStartup));
#endif // !defined(DISABLE_NACL)
// Make sure initial prefs are recorded
PrefMetricsService::Factory::GetForProfile(profile_);
PreBrowserStart();
// Instantiate the notification UI manager, as this triggers a perf timer
// used to measure startup time. TODO(stevenjb): Figure out what is actually
// triggering the timer and call that explicitly in the approprate place.
// http://crbug.com/105065.
browser_process_->notification_ui_manager();
// This must be called prior to RegisterComponentsForUpdate, in case the CLD
// data source is based on the Component Updater.
translate::BrowserCldUtils::ConfigureDefaultDataProvider();
if (!parsed_command_line().HasSwitch(switches::kDisableComponentUpdate))
RegisterComponentsForUpdate();
#if defined(OS_ANDROID)
variations::VariationsService* variations_service =
browser_process_->variations_service();
if (variations_service) {
// Just initialize the policy prefs service here. Variations seed fetching
// will be initialized when the app enters foreground mode.
variations_service->set_policy_pref_service(profile_->GetPrefs());
}
translate::TranslateDownloadManager::RequestLanguageList(
profile_->GetPrefs());
#else
// Most general initialization is behind us, but opening a
// tab and/or session restore and such is still to be done.
base::TimeTicks browser_open_start = base::TimeTicks::Now();
// We are in regular browser boot sequence. Open initial tabs and enter the
// main message loop.
std::vector<Profile*> last_opened_profiles;
#if !defined(OS_CHROMEOS)
// On ChromeOS multiple profiles doesn't apply, and will break if we load
// them this early as the cryptohome hasn't yet been mounted (which happens
// only once we log in).
last_opened_profiles =
g_browser_process->profile_manager()->GetLastOpenedProfiles();
#endif // defined(OS_CHROMEOS)
UMA_HISTOGRAM_TIMES("Startup.PreMainMessageLoopRunImplStep2Time",
base::TimeTicks::Now() - start_time_step2);
// This step is costly and is already measured in
// Startup.StartupBrowserCreator_Start.
const bool started = browser_creator_->Start(
parsed_command_line(), base::FilePath(), profile_, last_opened_profiles);
const base::TimeTicks start_time_step3 = base::TimeTicks::Now();
if (started) {
#if defined(OS_WIN) || (defined(OS_LINUX) && !defined(OS_CHROMEOS))
// Initialize autoupdate timer. Timer callback costs basically nothing
// when browser is not in persistent mode, so it's OK to let it ride on
// the main thread. This needs to be done here because we don't want
// to start the timer when Chrome is run inside a test harness.
browser_process_->StartAutoupdateTimer();
#endif // defined(OS_WIN) || (defined(OS_LINUX) && !defined(OS_CHROMEOS))
#if defined(OS_LINUX) && !defined(OS_CHROMEOS)
// On Linux, the running exe will be updated if an upgrade becomes
// available while the browser is running. We need to save the last
// modified time of the exe, so we can compare to determine if there is
// an upgrade while the browser is kept alive by a persistent extension.
upgrade_util::SaveLastModifiedTimeOfExe();
#endif // defined(OS_LINUX) && !defined(OS_CHROMEOS)
// Record now as the last successful chrome start.
GoogleUpdateSettings::SetLastRunTime();
#if defined(OS_MACOSX)
// Call Recycle() here as late as possible, before going into the loop
// because Start() will add things to it while creating the main window.
if (parameters().autorelease_pool)
parameters().autorelease_pool->Recycle();
#endif // defined(OS_MACOSX)
const base::TimeDelta delta = base::TimeTicks::Now() - browser_open_start;
startup_metric_utils::RecordBrowserOpenTabsDelta(delta);
// If we're running tests (ui_task is non-null), then we don't want to
// call RequestLanguageList or StartRepeatedVariationsSeedFetch or
// RequestLanguageList
if (parameters().ui_task == NULL) {
// Request new variations seed information from server.
variations::VariationsService* variations_service =
browser_process_->variations_service();
if (variations_service)
variations_service->PerformPreMainMessageLoopStartup();
translate::TranslateDownloadManager::RequestLanguageList(
profile_->GetPrefs());
}
}
run_message_loop_ = started;
browser_creator_.reset();
#if !defined(OS_LINUX) || defined(OS_CHROMEOS) // http://crbug.com/426393
content::StartPowerUsageMonitor();
#endif // !defined(OS_LINUX) || defined(OS_CHROMEOS)
process_power_collector_.reset(new ProcessPowerCollector);
process_power_collector_->Initialize();
#endif // !defined(OS_ANDROID)
PostBrowserStart();
if (parameters().ui_task) {
parameters().ui_task->Run();
delete parameters().ui_task;
run_message_loop_ = false;
}
#if defined(OS_ANDROID)
// We never run the C++ main loop on Android, since the UI thread message
// loop is controlled by the OS, so this is as close as we can get to
// the start of the main loop.
if (result_code_ <= 0) {
RecordBrowserStartupTime();
}
#endif // defined(OS_ANDROID)
#if !defined(OS_ANDROID)
UMA_HISTOGRAM_TIMES("Startup.PreMainMessageLoopRunImplStep3Time",
base::TimeTicks::Now() - start_time_step3);
#endif // !defined(OS_ANDROID)
return result_code_;
}
bool ChromeBrowserMainParts::MainMessageLoopRun(int* result_code) {
// Trace the entry and exit of this method. We don't use the TRACE_EVENT0
// macro because the tracing infrastructure doesn't expect a synchronous event
// around the main loop of a thread.
ScopedMainMessageLoopRunEvent scoped_main_message_loop_run_event;
#if defined(OS_ANDROID)
// Chrome on Android does not use default MessageLoop. It has its own
// Android specific MessageLoop
NOTREACHED();
return true;
#else
// Set the result code set in PreMainMessageLoopRun or set above.
*result_code = result_code_;
if (!run_message_loop_)
return true; // Don't run the default message loop.
// These should be invoked as close to the start of the browser's
// UI thread message loop as possible to get a stable measurement
// across versions.
RecordBrowserStartupTime();
DCHECK(base::MessageLoopForUI::IsCurrent());
base::RunLoop run_loop;
performance_monitor::PerformanceMonitor::GetInstance()->StartGatherCycle();
metrics::MetricsService::SetExecutionPhase(
metrics::MetricsService::MAIN_MESSAGE_LOOP_RUN,
g_browser_process->local_state());
run_loop.Run();
return true;
#endif // defined(OS_ANDROID)
}
void ChromeBrowserMainParts::PostMainMessageLoopRun() {
TRACE_EVENT0("startup", "ChromeBrowserMainParts::PostMainMessageLoopRun");
#if defined(OS_ANDROID)
// Chrome on Android does not use default MessageLoop. It has its own
// Android specific MessageLoop
NOTREACHED();
#else
// Start watching for jank during shutdown. It gets disarmed when
// |shutdown_watcher_| object is destructed.
metrics::MetricsService::SetExecutionPhase(
metrics::MetricsService::SHUTDOWN_TIMEBOMB_ARM,
g_browser_process->local_state());
shutdown_watcher_->Arm(base::TimeDelta::FromSeconds(300));
// Disarm the startup hang detector time bomb if it is still Arm'ed.
startup_watcher_->Disarm();
// Remove observers attached to D-Bus clients before DbusThreadManager is
// shut down.
process_power_collector_.reset();
webusb_detector_.reset();
webusb_browser_client_.reset();
for (size_t i = 0; i < chrome_extra_parts_.size(); ++i)
chrome_extra_parts_[i]->PostMainMessageLoopRun();
// Some tests don't set parameters.ui_task, so they started translate
// language fetch that was never completed so we need to cleanup here
// otherwise it will be done by the destructor in a wrong thread.
TranslateService::Shutdown(parameters().ui_task == NULL);
if (notify_result_ == ProcessSingleton::PROCESS_NONE)
process_singleton_->Cleanup();
// Stop all tasks that might run on WatchDogThread.
ThreadWatcherList::StopWatchingAll();
browser_process_->metrics_service()->Stop();
restart_last_session_ = browser_shutdown::ShutdownPreThreadsStop();
browser_process_->StartTearDown();
#if defined(SYZYASAN)
// Disable the deferred free mechanism in the syzyasan module. This is needed
// to avoid a potential crash when the syzyasan module is unloaded.
if (base::FeatureList::IsEnabled(features::kSyzyasanDeferredFree)) {
typedef VOID(WINAPI * SyzyasanDisableDeferredFreeThreadFunc)(VOID);
HMODULE syzyasan_handle = ::GetModuleHandle(L"syzyasan_rtl.dll");
if (syzyasan_handle) {
SyzyasanDisableDeferredFreeThreadFunc syzyasan_disable_deferred_free =
reinterpret_cast<SyzyasanDisableDeferredFreeThreadFunc>(
::GetProcAddress(syzyasan_handle,
"asan_DisableDeferredFreeThread"));
if (syzyasan_disable_deferred_free)
syzyasan_disable_deferred_free();
}
}
#endif // defined(SYZYASAN)
#endif // defined(OS_ANDROID)
}
void ChromeBrowserMainParts::PostDestroyThreads() {
#if defined(OS_ANDROID)
// On Android, there is no quit/exit. So the browser's main message loop will
// not finish.
NOTREACHED();
#else
browser_process_->PostDestroyThreads();
// browser_shutdown takes care of deleting browser_process, so we need to
// release it.
ignore_result(browser_process_.release());
browser_shutdown::ShutdownPostThreadsStop(restart_last_session_);
master_prefs_.reset();
process_singleton_.reset();
device_event_log::Shutdown();
// We need to do this check as late as possible, but due to modularity, this
// may be the last point in Chrome. This would be more effective if done at
// a higher level on the stack, so that it is impossible for an early return
// to bypass this code. Perhaps we need a *final* hook that is called on all
// paths from content/browser/browser_main.
CHECK(metrics::MetricsService::UmaMetricsProperlyShutdown());
#if defined(OS_CHROMEOS)
chromeos::CrosSettings::Shutdown();
#endif // defined(OS_CHROMEOS)
#endif // defined(OS_ANDROID)
}
// Public members:
void ChromeBrowserMainParts::AddParts(ChromeBrowserMainExtraParts* parts) {
chrome_extra_parts_.push_back(parts);
}
| bsd-3-clause |
crosswalk-project/chromium-crosswalk-efl | cc/scheduler/scheduler_unittest.cc | 74227 | // Copyright 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "cc/scheduler/scheduler.h"
#include <string>
#include <vector>
#include "base/debug/trace_event.h"
#include "base/logging.h"
#include "base/memory/scoped_vector.h"
#include "base/message_loop/message_loop.h"
#include "base/run_loop.h"
#include "base/time/time.h"
#include "cc/test/begin_frame_args_test.h"
#include "cc/test/ordered_simple_task_runner.h"
#include "cc/test/scheduler_test_common.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#define EXPECT_ACTION(action, client, action_index, expected_num_actions) \
do { \
EXPECT_EQ(expected_num_actions, client.num_actions_()); \
if (action_index >= 0) { \
ASSERT_LT(action_index, client.num_actions_()) << scheduler; \
EXPECT_STREQ(action, client.Action(action_index)); \
} \
for (int i = expected_num_actions; i < client.num_actions_(); ++i) \
ADD_FAILURE() << "Unexpected action: " << client.Action(i) \
<< " with state:\n" << client.StateForAction(i); \
} while (false)
#define EXPECT_NO_ACTION(client) EXPECT_ACTION("", client, -1, 0)
#define EXPECT_SINGLE_ACTION(action, client) \
EXPECT_ACTION(action, client, 0, 1)
namespace cc {
namespace {
class FakeSchedulerClient;
void InitializeOutputSurfaceAndFirstCommit(Scheduler* scheduler,
FakeSchedulerClient* client);
class FakeSchedulerClient : public SchedulerClient {
public:
FakeSchedulerClient()
: needs_begin_frame_(false),
automatic_swap_ack_(true),
swap_contains_incomplete_tile_(false),
redraw_will_happen_if_update_visible_tiles_happens_(false),
now_src_(TestNowSource::Create()) {
Reset();
}
void Reset() {
actions_.clear();
states_.clear();
draw_will_happen_ = true;
swap_will_happen_if_draw_happens_ = true;
num_draws_ = 0;
log_anticipated_draw_time_change_ = false;
}
TestScheduler* CreateScheduler(const SchedulerSettings& settings) {
scheduler_ = TestScheduler::Create(now_src_, this, settings, 0);
// Fail if we need to run 100 tasks in a row.
task_runner().SetRunTaskLimit(100);
return scheduler_.get();
}
// Most tests don't care about DidAnticipatedDrawTimeChange, so only record it
// for tests that do.
void set_log_anticipated_draw_time_change(bool log) {
log_anticipated_draw_time_change_ = log;
}
bool needs_begin_frame() { return needs_begin_frame_; }
int num_draws() const { return num_draws_; }
int num_actions_() const { return static_cast<int>(actions_.size()); }
const char* Action(int i) const { return actions_[i]; }
std::string StateForAction(int i) const { return states_[i]->ToString(); }
base::TimeTicks posted_begin_impl_frame_deadline() const {
return posted_begin_impl_frame_deadline_;
}
void AdvanceFrame() {
bool external_begin_frame =
scheduler_->settings().begin_frame_scheduling_enabled &&
scheduler_->settings().throttle_frame_production;
if (external_begin_frame) {
scheduler_->BeginFrame(CreateBeginFrameArgsForTesting(now_src_));
}
EXPECT_TRUE(task_runner().RunTasksWhile(ImplFrameDeadlinePending(false)));
EXPECT_TRUE(scheduler_->BeginImplFrameDeadlinePending());
}
OrderedSimpleTaskRunner& task_runner() { return scheduler_->task_runner(); }
TestNowSource* now_src() { return now_src_.get(); }
int ActionIndex(const char* action) const {
for (size_t i = 0; i < actions_.size(); i++)
if (!strcmp(actions_[i], action))
return i;
return -1;
}
void SetSwapContainsIncompleteTile(bool contain) {
swap_contains_incomplete_tile_ = contain;
}
bool HasAction(const char* action) const {
return ActionIndex(action) >= 0;
}
void SetDrawWillHappen(bool draw_will_happen) {
draw_will_happen_ = draw_will_happen;
}
void SetSwapWillHappenIfDrawHappens(bool swap_will_happen_if_draw_happens) {
swap_will_happen_if_draw_happens_ = swap_will_happen_if_draw_happens;
}
void SetAutomaticSwapAck(bool automatic_swap_ack) {
automatic_swap_ack_ = automatic_swap_ack;
}
void SetRedrawWillHappenIfUpdateVisibleTilesHappens(bool redraw) {
redraw_will_happen_if_update_visible_tiles_happens_ = redraw;
}
// SchedulerClient implementation.
virtual void SetNeedsBeginFrame(bool enable) OVERRIDE {
actions_.push_back("SetNeedsBeginFrame");
states_.push_back(scheduler_->AsValue());
needs_begin_frame_ = enable;
}
virtual void WillBeginImplFrame(const BeginFrameArgs& args) OVERRIDE {
actions_.push_back("WillBeginImplFrame");
states_.push_back(scheduler_->AsValue());
}
virtual void ScheduledActionSendBeginMainFrame() OVERRIDE {
actions_.push_back("ScheduledActionSendBeginMainFrame");
states_.push_back(scheduler_->AsValue());
}
virtual void ScheduledActionAnimate() OVERRIDE {
actions_.push_back("ScheduledActionAnimate");
states_.push_back(scheduler_->AsValue());
}
virtual DrawResult ScheduledActionDrawAndSwapIfPossible() OVERRIDE {
actions_.push_back("ScheduledActionDrawAndSwapIfPossible");
states_.push_back(scheduler_->AsValue());
num_draws_++;
DrawResult result =
draw_will_happen_ ? DRAW_SUCCESS : DRAW_ABORTED_CHECKERBOARD_ANIMATIONS;
bool swap_will_happen =
draw_will_happen_ && swap_will_happen_if_draw_happens_;
if (swap_will_happen) {
scheduler_->DidSwapBuffers();
if (swap_contains_incomplete_tile_) {
scheduler_->SetSwapUsedIncompleteTile(true);
swap_contains_incomplete_tile_ = false;
} else {
scheduler_->SetSwapUsedIncompleteTile(false);
}
if (automatic_swap_ack_)
scheduler_->DidSwapBuffersComplete();
}
return result;
}
virtual DrawResult ScheduledActionDrawAndSwapForced() OVERRIDE {
actions_.push_back("ScheduledActionDrawAndSwapForced");
states_.push_back(scheduler_->AsValue());
return DRAW_SUCCESS;
}
virtual void ScheduledActionCommit() OVERRIDE {
actions_.push_back("ScheduledActionCommit");
states_.push_back(scheduler_->AsValue());
}
virtual void ScheduledActionUpdateVisibleTiles() OVERRIDE {
actions_.push_back("ScheduledActionUpdateVisibleTiles");
states_.push_back(scheduler_->AsValue());
if (redraw_will_happen_if_update_visible_tiles_happens_)
scheduler_->SetNeedsRedraw();
}
virtual void ScheduledActionActivateSyncTree() OVERRIDE {
actions_.push_back("ScheduledActionActivateSyncTree");
states_.push_back(scheduler_->AsValue());
}
virtual void ScheduledActionBeginOutputSurfaceCreation() OVERRIDE {
actions_.push_back("ScheduledActionBeginOutputSurfaceCreation");
states_.push_back(scheduler_->AsValue());
}
virtual void ScheduledActionManageTiles() OVERRIDE {
actions_.push_back("ScheduledActionManageTiles");
states_.push_back(scheduler_->AsValue());
}
virtual void DidAnticipatedDrawTimeChange(base::TimeTicks) OVERRIDE {
if (log_anticipated_draw_time_change_)
actions_.push_back("DidAnticipatedDrawTimeChange");
}
virtual base::TimeDelta DrawDurationEstimate() OVERRIDE {
return base::TimeDelta();
}
virtual base::TimeDelta BeginMainFrameToCommitDurationEstimate() OVERRIDE {
return base::TimeDelta();
}
virtual base::TimeDelta CommitToActivateDurationEstimate() OVERRIDE {
return base::TimeDelta();
}
virtual void DidBeginImplFrameDeadline() OVERRIDE {}
base::Callback<bool(void)> ImplFrameDeadlinePending(bool state) {
return base::Bind(&FakeSchedulerClient::ImplFrameDeadlinePendingCallback,
base::Unretained(this),
state);
}
protected:
bool ImplFrameDeadlinePendingCallback(bool state) {
return scheduler_->BeginImplFrameDeadlinePending() == state;
}
bool needs_begin_frame_;
bool draw_will_happen_;
bool swap_will_happen_if_draw_happens_;
bool automatic_swap_ack_;
int num_draws_;
bool log_anticipated_draw_time_change_;
bool swap_contains_incomplete_tile_;
bool redraw_will_happen_if_update_visible_tiles_happens_;
base::TimeTicks posted_begin_impl_frame_deadline_;
std::vector<const char*> actions_;
std::vector<scoped_refptr<base::debug::ConvertableToTraceFormat> > states_;
scoped_ptr<TestScheduler> scheduler_;
scoped_refptr<TestNowSource> now_src_;
};
void InitializeOutputSurfaceAndFirstCommit(Scheduler* scheduler,
FakeSchedulerClient* client) {
TRACE_EVENT0("cc",
"SchedulerUnitTest::InitializeOutputSurfaceAndFirstCommit");
scheduler->DidCreateAndInitializeOutputSurface();
scheduler->SetNeedsCommit();
scheduler->NotifyBeginMainFrameStarted();
scheduler->NotifyReadyToCommit();
if (scheduler->settings().impl_side_painting)
scheduler->NotifyReadyToActivate();
// Go through the motions to draw the commit.
client->AdvanceFrame();
// Run the posted deadline task.
EXPECT_TRUE(scheduler->BeginImplFrameDeadlinePending());
client->task_runner().RunTasksWhile(client->ImplFrameDeadlinePending(true));
EXPECT_FALSE(scheduler->BeginImplFrameDeadlinePending());
// We need another BeginImplFrame so Scheduler calls
// SetNeedsBeginFrame(false).
client->AdvanceFrame();
// Run the posted deadline task.
EXPECT_TRUE(scheduler->BeginImplFrameDeadlinePending());
client->task_runner().RunTasksWhile(client->ImplFrameDeadlinePending(true));
EXPECT_FALSE(scheduler->BeginImplFrameDeadlinePending());
}
TEST(SchedulerTest, InitializeOutputSurfaceDoesNotBeginImplFrame) {
FakeSchedulerClient client;
SchedulerSettings default_scheduler_settings;
TestScheduler* scheduler = client.CreateScheduler(default_scheduler_settings);
scheduler->SetCanStart();
scheduler->SetVisible(true);
scheduler->SetCanDraw(true);
EXPECT_SINGLE_ACTION("ScheduledActionBeginOutputSurfaceCreation", client);
client.Reset();
scheduler->DidCreateAndInitializeOutputSurface();
EXPECT_NO_ACTION(client);
}
TEST(SchedulerTest, RequestCommit) {
FakeSchedulerClient client;
SchedulerSettings scheduler_settings;
TestScheduler* scheduler = client.CreateScheduler(scheduler_settings);
scheduler->SetCanStart();
scheduler->SetVisible(true);
scheduler->SetCanDraw(true);
EXPECT_SINGLE_ACTION("ScheduledActionBeginOutputSurfaceCreation", client);
InitializeOutputSurfaceAndFirstCommit(scheduler, &client);
// SetNeedsCommit should begin the frame on the next BeginImplFrame.
client.Reset();
scheduler->SetNeedsCommit();
EXPECT_TRUE(client.needs_begin_frame());
EXPECT_SINGLE_ACTION("SetNeedsBeginFrame", client);
client.Reset();
client.AdvanceFrame();
EXPECT_ACTION("WillBeginImplFrame", client, 0, 2);
EXPECT_ACTION("ScheduledActionSendBeginMainFrame", client, 1, 2);
EXPECT_TRUE(scheduler->BeginImplFrameDeadlinePending());
EXPECT_TRUE(client.needs_begin_frame());
client.Reset();
// If we don't swap on the deadline, we wait for the next BeginFrame.
client.task_runner().RunPendingTasks(); // Run posted deadline.
EXPECT_NO_ACTION(client);
EXPECT_FALSE(scheduler->BeginImplFrameDeadlinePending());
EXPECT_TRUE(client.needs_begin_frame());
client.Reset();
// NotifyReadyToCommit should trigger the commit.
scheduler->NotifyBeginMainFrameStarted();
scheduler->NotifyReadyToCommit();
EXPECT_SINGLE_ACTION("ScheduledActionCommit", client);
EXPECT_TRUE(client.needs_begin_frame());
client.Reset();
// BeginImplFrame should prepare the draw.
client.AdvanceFrame();
EXPECT_ACTION("WillBeginImplFrame", client, 0, 2);
EXPECT_ACTION("ScheduledActionAnimate", client, 1, 2);
EXPECT_TRUE(scheduler->BeginImplFrameDeadlinePending());
EXPECT_TRUE(client.needs_begin_frame());
client.Reset();
// BeginImplFrame deadline should draw.
client.task_runner().RunPendingTasks(); // Run posted deadline.
EXPECT_ACTION("ScheduledActionDrawAndSwapIfPossible", client, 0, 1);
EXPECT_FALSE(scheduler->BeginImplFrameDeadlinePending());
EXPECT_TRUE(client.needs_begin_frame());
client.Reset();
// The following BeginImplFrame deadline should SetNeedsBeginFrame(false)
// to avoid excessive toggles.
client.AdvanceFrame();
EXPECT_SINGLE_ACTION("WillBeginImplFrame", client);
EXPECT_TRUE(scheduler->BeginImplFrameDeadlinePending());
client.Reset();
client.task_runner().RunPendingTasks(); // Run posted deadline.
EXPECT_SINGLE_ACTION("SetNeedsBeginFrame", client);
EXPECT_FALSE(client.needs_begin_frame());
client.Reset();
}
TEST(SchedulerTest, RequestCommitAfterBeginMainFrameSent) {
FakeSchedulerClient client;
SchedulerSettings scheduler_settings;
TestScheduler* scheduler = client.CreateScheduler(scheduler_settings);
scheduler->SetCanStart();
scheduler->SetVisible(true);
scheduler->SetCanDraw(true);
EXPECT_SINGLE_ACTION("ScheduledActionBeginOutputSurfaceCreation", client);
InitializeOutputSurfaceAndFirstCommit(scheduler, &client);
client.Reset();
// SetNeedsCommit should begin the frame.
scheduler->SetNeedsCommit();
EXPECT_SINGLE_ACTION("SetNeedsBeginFrame", client);
client.Reset();
client.AdvanceFrame();
EXPECT_ACTION("WillBeginImplFrame", client, 0, 2);
EXPECT_ACTION("ScheduledActionSendBeginMainFrame", client, 1, 2);
EXPECT_TRUE(scheduler->BeginImplFrameDeadlinePending());
EXPECT_TRUE(client.needs_begin_frame());
client.Reset();
// Now SetNeedsCommit again. Calling here means we need a second commit.
scheduler->SetNeedsCommit();
EXPECT_EQ(client.num_actions_(), 0);
client.Reset();
// Finish the first commit.
scheduler->NotifyBeginMainFrameStarted();
scheduler->NotifyReadyToCommit();
EXPECT_SINGLE_ACTION("ScheduledActionCommit", client);
EXPECT_TRUE(scheduler->BeginImplFrameDeadlinePending());
client.Reset();
client.task_runner().RunPendingTasks(); // Run posted deadline.
EXPECT_ACTION("ScheduledActionAnimate", client, 0, 2);
EXPECT_ACTION("ScheduledActionDrawAndSwapIfPossible", client, 1, 2);
EXPECT_FALSE(scheduler->BeginImplFrameDeadlinePending());
// Because we just swapped, the Scheduler should also request the next
// BeginImplFrame from the OutputSurface.
EXPECT_TRUE(client.needs_begin_frame());
client.Reset();
// Since another commit is needed, the next BeginImplFrame should initiate
// the second commit.
client.AdvanceFrame();
EXPECT_ACTION("WillBeginImplFrame", client, 0, 2);
EXPECT_ACTION("ScheduledActionSendBeginMainFrame", client, 1, 2);
EXPECT_TRUE(scheduler->BeginImplFrameDeadlinePending());
client.Reset();
// Finishing the commit before the deadline should post a new deadline task
// to trigger the deadline early.
scheduler->NotifyBeginMainFrameStarted();
scheduler->NotifyReadyToCommit();
EXPECT_SINGLE_ACTION("ScheduledActionCommit", client);
EXPECT_TRUE(scheduler->BeginImplFrameDeadlinePending());
client.Reset();
client.task_runner().RunPendingTasks(); // Run posted deadline.
EXPECT_ACTION("ScheduledActionAnimate", client, 0, 2);
EXPECT_ACTION("ScheduledActionDrawAndSwapIfPossible", client, 1, 2);
EXPECT_FALSE(scheduler->BeginImplFrameDeadlinePending());
EXPECT_TRUE(client.needs_begin_frame());
client.Reset();
// On the next BeginImplFrame, verify we go back to a quiescent state and
// no longer request BeginImplFrames.
client.AdvanceFrame();
client.task_runner().RunPendingTasks(); // Run posted deadline.
EXPECT_FALSE(client.needs_begin_frame());
client.Reset();
}
class SchedulerClientThatsetNeedsDrawInsideDraw : public FakeSchedulerClient {
public:
virtual void ScheduledActionSendBeginMainFrame() OVERRIDE {}
virtual DrawResult ScheduledActionDrawAndSwapIfPossible()
OVERRIDE {
// Only SetNeedsRedraw the first time this is called
if (!num_draws_)
scheduler_->SetNeedsRedraw();
return FakeSchedulerClient::ScheduledActionDrawAndSwapIfPossible();
}
virtual DrawResult ScheduledActionDrawAndSwapForced() OVERRIDE {
NOTREACHED();
return DRAW_SUCCESS;
}
virtual void ScheduledActionCommit() OVERRIDE {}
virtual void ScheduledActionBeginOutputSurfaceCreation() OVERRIDE {}
virtual void DidAnticipatedDrawTimeChange(base::TimeTicks) OVERRIDE {}
};
// Tests for two different situations:
// 1. the scheduler dropping SetNeedsRedraw requests that happen inside
// a ScheduledActionDrawAndSwap
// 2. the scheduler drawing twice inside a single tick
TEST(SchedulerTest, RequestRedrawInsideDraw) {
SchedulerClientThatsetNeedsDrawInsideDraw client;
SchedulerSettings default_scheduler_settings;
TestScheduler* scheduler = client.CreateScheduler(default_scheduler_settings);
scheduler->SetCanStart();
scheduler->SetVisible(true);
scheduler->SetCanDraw(true);
InitializeOutputSurfaceAndFirstCommit(scheduler, &client);
client.Reset();
scheduler->SetNeedsRedraw();
EXPECT_TRUE(scheduler->RedrawPending());
EXPECT_TRUE(client.needs_begin_frame());
EXPECT_EQ(0, client.num_draws());
client.AdvanceFrame();
client.task_runner().RunPendingTasks(); // Run posted deadline.
EXPECT_EQ(1, client.num_draws());
EXPECT_TRUE(scheduler->RedrawPending());
EXPECT_TRUE(client.needs_begin_frame());
client.AdvanceFrame();
client.task_runner().RunPendingTasks(); // Run posted deadline.
EXPECT_EQ(2, client.num_draws());
EXPECT_FALSE(scheduler->RedrawPending());
EXPECT_TRUE(client.needs_begin_frame());
// We stop requesting BeginImplFrames after a BeginImplFrame where we don't
// swap.
client.AdvanceFrame();
client.task_runner().RunPendingTasks(); // Run posted deadline.
EXPECT_EQ(2, client.num_draws());
EXPECT_FALSE(scheduler->RedrawPending());
EXPECT_FALSE(client.needs_begin_frame());
}
// Test that requesting redraw inside a failed draw doesn't lose the request.
TEST(SchedulerTest, RequestRedrawInsideFailedDraw) {
SchedulerClientThatsetNeedsDrawInsideDraw client;
SchedulerSettings default_scheduler_settings;
TestScheduler* scheduler = client.CreateScheduler(default_scheduler_settings);
scheduler->SetCanStart();
scheduler->SetVisible(true);
scheduler->SetCanDraw(true);
InitializeOutputSurfaceAndFirstCommit(scheduler, &client);
client.Reset();
client.SetDrawWillHappen(false);
scheduler->SetNeedsRedraw();
EXPECT_TRUE(scheduler->RedrawPending());
EXPECT_TRUE(client.needs_begin_frame());
EXPECT_EQ(0, client.num_draws());
// Fail the draw.
client.AdvanceFrame();
client.task_runner().RunPendingTasks(); // Run posted deadline.
EXPECT_EQ(1, client.num_draws());
// We have a commit pending and the draw failed, and we didn't lose the redraw
// request.
EXPECT_TRUE(scheduler->CommitPending());
EXPECT_TRUE(scheduler->RedrawPending());
EXPECT_TRUE(client.needs_begin_frame());
// Fail the draw again.
client.AdvanceFrame();
client.task_runner().RunPendingTasks(); // Run posted deadline.
EXPECT_EQ(2, client.num_draws());
EXPECT_TRUE(scheduler->CommitPending());
EXPECT_TRUE(scheduler->RedrawPending());
EXPECT_TRUE(client.needs_begin_frame());
// Draw successfully.
client.SetDrawWillHappen(true);
client.AdvanceFrame();
client.task_runner().RunPendingTasks(); // Run posted deadline.
EXPECT_EQ(3, client.num_draws());
EXPECT_TRUE(scheduler->CommitPending());
EXPECT_FALSE(scheduler->RedrawPending());
EXPECT_TRUE(client.needs_begin_frame());
}
class SchedulerClientThatSetNeedsCommitInsideDraw : public FakeSchedulerClient {
public:
SchedulerClientThatSetNeedsCommitInsideDraw()
: set_needs_commit_on_next_draw_(false) {}
virtual void ScheduledActionSendBeginMainFrame() OVERRIDE {}
virtual DrawResult ScheduledActionDrawAndSwapIfPossible()
OVERRIDE {
// Only SetNeedsCommit the first time this is called
if (set_needs_commit_on_next_draw_) {
scheduler_->SetNeedsCommit();
set_needs_commit_on_next_draw_ = false;
}
return FakeSchedulerClient::ScheduledActionDrawAndSwapIfPossible();
}
virtual DrawResult ScheduledActionDrawAndSwapForced() OVERRIDE {
NOTREACHED();
return DRAW_SUCCESS;
}
virtual void ScheduledActionCommit() OVERRIDE {}
virtual void ScheduledActionBeginOutputSurfaceCreation() OVERRIDE {}
virtual void DidAnticipatedDrawTimeChange(base::TimeTicks) OVERRIDE {}
void SetNeedsCommitOnNextDraw() { set_needs_commit_on_next_draw_ = true; }
private:
bool set_needs_commit_on_next_draw_;
};
// Tests for the scheduler infinite-looping on SetNeedsCommit requests that
// happen inside a ScheduledActionDrawAndSwap
TEST(SchedulerTest, RequestCommitInsideDraw) {
SchedulerClientThatSetNeedsCommitInsideDraw client;
SchedulerSettings default_scheduler_settings;
TestScheduler* scheduler = client.CreateScheduler(default_scheduler_settings);
scheduler->SetCanStart();
scheduler->SetVisible(true);
scheduler->SetCanDraw(true);
InitializeOutputSurfaceAndFirstCommit(scheduler, &client);
client.Reset();
EXPECT_FALSE(client.needs_begin_frame());
scheduler->SetNeedsRedraw();
EXPECT_TRUE(scheduler->RedrawPending());
EXPECT_EQ(0, client.num_draws());
EXPECT_TRUE(client.needs_begin_frame());
client.SetNeedsCommitOnNextDraw();
client.AdvanceFrame();
client.SetNeedsCommitOnNextDraw();
client.task_runner().RunPendingTasks(); // Run posted deadline.
EXPECT_EQ(1, client.num_draws());
EXPECT_TRUE(scheduler->CommitPending());
EXPECT_TRUE(client.needs_begin_frame());
scheduler->NotifyBeginMainFrameStarted();
scheduler->NotifyReadyToCommit();
client.AdvanceFrame();
client.task_runner().RunPendingTasks(); // Run posted deadline.
EXPECT_EQ(2, client.num_draws());
EXPECT_FALSE(scheduler->RedrawPending());
EXPECT_FALSE(scheduler->CommitPending());
EXPECT_TRUE(client.needs_begin_frame());
// We stop requesting BeginImplFrames after a BeginImplFrame where we don't
// swap.
client.AdvanceFrame();
client.task_runner().RunPendingTasks(); // Run posted deadline.
EXPECT_EQ(2, client.num_draws());
EXPECT_FALSE(scheduler->RedrawPending());
EXPECT_FALSE(scheduler->CommitPending());
EXPECT_FALSE(client.needs_begin_frame());
}
// Tests that when a draw fails then the pending commit should not be dropped.
TEST(SchedulerTest, RequestCommitInsideFailedDraw) {
SchedulerClientThatsetNeedsDrawInsideDraw client;
SchedulerSettings default_scheduler_settings;
TestScheduler* scheduler = client.CreateScheduler(default_scheduler_settings);
scheduler->SetCanStart();
scheduler->SetVisible(true);
scheduler->SetCanDraw(true);
InitializeOutputSurfaceAndFirstCommit(scheduler, &client);
client.Reset();
client.SetDrawWillHappen(false);
scheduler->SetNeedsRedraw();
EXPECT_TRUE(scheduler->RedrawPending());
EXPECT_TRUE(client.needs_begin_frame());
EXPECT_EQ(0, client.num_draws());
// Fail the draw.
client.AdvanceFrame();
client.task_runner().RunPendingTasks(); // Run posted deadline.
EXPECT_EQ(1, client.num_draws());
// We have a commit pending and the draw failed, and we didn't lose the commit
// request.
EXPECT_TRUE(scheduler->CommitPending());
EXPECT_TRUE(scheduler->RedrawPending());
EXPECT_TRUE(client.needs_begin_frame());
// Fail the draw again.
client.AdvanceFrame();
client.task_runner().RunPendingTasks(); // Run posted deadline.
EXPECT_EQ(2, client.num_draws());
EXPECT_TRUE(scheduler->CommitPending());
EXPECT_TRUE(scheduler->RedrawPending());
EXPECT_TRUE(client.needs_begin_frame());
// Draw successfully.
client.SetDrawWillHappen(true);
client.AdvanceFrame();
client.task_runner().RunPendingTasks(); // Run posted deadline.
EXPECT_EQ(3, client.num_draws());
EXPECT_TRUE(scheduler->CommitPending());
EXPECT_FALSE(scheduler->RedrawPending());
EXPECT_TRUE(client.needs_begin_frame());
}
TEST(SchedulerTest, NoSwapWhenDrawFails) {
SchedulerClientThatSetNeedsCommitInsideDraw client;
SchedulerSettings default_scheduler_settings;
TestScheduler* scheduler = client.CreateScheduler(default_scheduler_settings);
scheduler->SetCanStart();
scheduler->SetVisible(true);
scheduler->SetCanDraw(true);
InitializeOutputSurfaceAndFirstCommit(scheduler, &client);
client.Reset();
scheduler->SetNeedsRedraw();
EXPECT_TRUE(scheduler->RedrawPending());
EXPECT_TRUE(client.needs_begin_frame());
EXPECT_EQ(0, client.num_draws());
// Draw successfully, this starts a new frame.
client.SetNeedsCommitOnNextDraw();
client.AdvanceFrame();
client.task_runner().RunPendingTasks(); // Run posted deadline.
EXPECT_EQ(1, client.num_draws());
scheduler->SetNeedsRedraw();
EXPECT_TRUE(scheduler->RedrawPending());
EXPECT_TRUE(client.needs_begin_frame());
// Fail to draw, this should not start a frame.
client.SetDrawWillHappen(false);
client.SetNeedsCommitOnNextDraw();
client.AdvanceFrame();
client.task_runner().RunPendingTasks(); // Run posted deadline.
EXPECT_EQ(2, client.num_draws());
}
class SchedulerClientNeedsManageTilesInDraw : public FakeSchedulerClient {
public:
virtual DrawResult ScheduledActionDrawAndSwapIfPossible()
OVERRIDE {
scheduler_->SetNeedsManageTiles();
return FakeSchedulerClient::ScheduledActionDrawAndSwapIfPossible();
}
};
// Test manage tiles is independant of draws.
TEST(SchedulerTest, ManageTiles) {
SchedulerClientNeedsManageTilesInDraw client;
SchedulerSettings default_scheduler_settings;
TestScheduler* scheduler = client.CreateScheduler(default_scheduler_settings);
scheduler->SetCanStart();
scheduler->SetVisible(true);
scheduler->SetCanDraw(true);
InitializeOutputSurfaceAndFirstCommit(scheduler, &client);
// Request both draw and manage tiles. ManageTiles shouldn't
// be trigged until BeginImplFrame.
client.Reset();
scheduler->SetNeedsManageTiles();
scheduler->SetNeedsRedraw();
EXPECT_TRUE(scheduler->RedrawPending());
EXPECT_TRUE(scheduler->ManageTilesPending());
EXPECT_TRUE(client.needs_begin_frame());
EXPECT_EQ(0, client.num_draws());
EXPECT_FALSE(client.HasAction("ScheduledActionManageTiles"));
EXPECT_FALSE(client.HasAction("ScheduledActionDrawAndSwapIfPossible"));
// We have no immediate actions to perform, so the BeginImplFrame should post
// the deadline task.
client.Reset();
client.AdvanceFrame();
EXPECT_ACTION("WillBeginImplFrame", client, 0, 2);
EXPECT_ACTION("ScheduledActionAnimate", client, 1, 2);
EXPECT_TRUE(scheduler->BeginImplFrameDeadlinePending());
// On the deadline, he actions should have occured in the right order.
client.Reset();
client.task_runner().RunPendingTasks(); // Run posted deadline.
EXPECT_EQ(1, client.num_draws());
EXPECT_TRUE(client.HasAction("ScheduledActionDrawAndSwapIfPossible"));
EXPECT_TRUE(client.HasAction("ScheduledActionManageTiles"));
EXPECT_LT(client.ActionIndex("ScheduledActionDrawAndSwapIfPossible"),
client.ActionIndex("ScheduledActionManageTiles"));
EXPECT_FALSE(scheduler->RedrawPending());
EXPECT_FALSE(scheduler->ManageTilesPending());
EXPECT_FALSE(scheduler->BeginImplFrameDeadlinePending());
// Request a draw. We don't need a ManageTiles yet.
client.Reset();
scheduler->SetNeedsRedraw();
EXPECT_TRUE(scheduler->RedrawPending());
EXPECT_FALSE(scheduler->ManageTilesPending());
EXPECT_TRUE(client.needs_begin_frame());
EXPECT_EQ(0, client.num_draws());
// We have no immediate actions to perform, so the BeginImplFrame should post
// the deadline task.
client.Reset();
client.AdvanceFrame();
EXPECT_ACTION("WillBeginImplFrame", client, 0, 2);
EXPECT_ACTION("ScheduledActionAnimate", client, 1, 2);
EXPECT_TRUE(scheduler->BeginImplFrameDeadlinePending());
// Draw. The draw will trigger SetNeedsManageTiles, and
// then the ManageTiles action will be triggered after the Draw.
// Afterwards, neither a draw nor ManageTiles are pending.
client.Reset();
client.task_runner().RunPendingTasks(); // Run posted deadline.
EXPECT_EQ(1, client.num_draws());
EXPECT_TRUE(client.HasAction("ScheduledActionDrawAndSwapIfPossible"));
EXPECT_TRUE(client.HasAction("ScheduledActionManageTiles"));
EXPECT_LT(client.ActionIndex("ScheduledActionDrawAndSwapIfPossible"),
client.ActionIndex("ScheduledActionManageTiles"));
EXPECT_FALSE(scheduler->RedrawPending());
EXPECT_FALSE(scheduler->ManageTilesPending());
EXPECT_FALSE(scheduler->BeginImplFrameDeadlinePending());
// We need a BeginImplFrame where we don't swap to go idle.
client.Reset();
client.AdvanceFrame();
EXPECT_SINGLE_ACTION("WillBeginImplFrame", client);
EXPECT_TRUE(scheduler->BeginImplFrameDeadlinePending());
client.Reset();
client.task_runner().RunPendingTasks(); // Run posted deadline.
EXPECT_SINGLE_ACTION("SetNeedsBeginFrame", client);
EXPECT_FALSE(client.needs_begin_frame());
EXPECT_FALSE(scheduler->BeginImplFrameDeadlinePending());
EXPECT_EQ(0, client.num_draws());
// Now trigger a ManageTiles outside of a draw. We will then need
// a begin-frame for the ManageTiles, but we don't need a draw.
client.Reset();
EXPECT_FALSE(client.needs_begin_frame());
scheduler->SetNeedsManageTiles();
EXPECT_TRUE(client.needs_begin_frame());
EXPECT_TRUE(scheduler->ManageTilesPending());
EXPECT_FALSE(scheduler->RedrawPending());
// BeginImplFrame. There will be no draw, only ManageTiles.
client.Reset();
client.AdvanceFrame();
EXPECT_SINGLE_ACTION("WillBeginImplFrame", client);
EXPECT_TRUE(scheduler->BeginImplFrameDeadlinePending());
client.Reset();
client.task_runner().RunPendingTasks(); // Run posted deadline.
EXPECT_EQ(0, client.num_draws());
EXPECT_FALSE(client.HasAction("ScheduledActionDrawAndSwapIfPossible"));
EXPECT_TRUE(client.HasAction("ScheduledActionManageTiles"));
EXPECT_FALSE(scheduler->BeginImplFrameDeadlinePending());
}
// Test that ManageTiles only happens once per frame. If an external caller
// initiates it, then the state machine should not ManageTiles on that frame.
TEST(SchedulerTest, ManageTilesOncePerFrame) {
FakeSchedulerClient client;
SchedulerSettings default_scheduler_settings;
TestScheduler* scheduler = client.CreateScheduler(default_scheduler_settings);
scheduler->SetCanStart();
scheduler->SetVisible(true);
scheduler->SetCanDraw(true);
InitializeOutputSurfaceAndFirstCommit(scheduler, &client);
// If DidManageTiles during a frame, then ManageTiles should not occur again.
scheduler->SetNeedsManageTiles();
scheduler->SetNeedsRedraw();
client.Reset();
client.AdvanceFrame();
EXPECT_ACTION("WillBeginImplFrame", client, 0, 2);
EXPECT_ACTION("ScheduledActionAnimate", client, 1, 2);
EXPECT_TRUE(scheduler->BeginImplFrameDeadlinePending());
EXPECT_TRUE(scheduler->ManageTilesPending());
scheduler->DidManageTiles(); // An explicit ManageTiles.
EXPECT_FALSE(scheduler->ManageTilesPending());
client.Reset();
client.task_runner().RunPendingTasks(); // Run posted deadline.
EXPECT_EQ(1, client.num_draws());
EXPECT_TRUE(client.HasAction("ScheduledActionDrawAndSwapIfPossible"));
EXPECT_FALSE(client.HasAction("ScheduledActionManageTiles"));
EXPECT_FALSE(scheduler->RedrawPending());
EXPECT_FALSE(scheduler->ManageTilesPending());
EXPECT_FALSE(scheduler->BeginImplFrameDeadlinePending());
// Next frame without DidManageTiles should ManageTiles with draw.
scheduler->SetNeedsManageTiles();
scheduler->SetNeedsRedraw();
client.Reset();
client.AdvanceFrame();
EXPECT_ACTION("WillBeginImplFrame", client, 0, 2);
EXPECT_ACTION("ScheduledActionAnimate", client, 1, 2);
EXPECT_TRUE(scheduler->BeginImplFrameDeadlinePending());
client.Reset();
client.task_runner().RunPendingTasks(); // Run posted deadline.
EXPECT_EQ(1, client.num_draws());
EXPECT_TRUE(client.HasAction("ScheduledActionDrawAndSwapIfPossible"));
EXPECT_TRUE(client.HasAction("ScheduledActionManageTiles"));
EXPECT_LT(client.ActionIndex("ScheduledActionDrawAndSwapIfPossible"),
client.ActionIndex("ScheduledActionManageTiles"));
EXPECT_FALSE(scheduler->RedrawPending());
EXPECT_FALSE(scheduler->ManageTilesPending());
EXPECT_FALSE(scheduler->BeginImplFrameDeadlinePending());
scheduler->DidManageTiles(); // Corresponds to ScheduledActionManageTiles
// If we get another DidManageTiles within the same frame, we should
// not ManageTiles on the next frame.
scheduler->DidManageTiles(); // An explicit ManageTiles.
scheduler->SetNeedsManageTiles();
scheduler->SetNeedsRedraw();
client.Reset();
client.AdvanceFrame();
EXPECT_ACTION("WillBeginImplFrame", client, 0, 2);
EXPECT_ACTION("ScheduledActionAnimate", client, 1, 2);
EXPECT_TRUE(scheduler->BeginImplFrameDeadlinePending());
EXPECT_TRUE(scheduler->ManageTilesPending());
client.Reset();
client.task_runner().RunPendingTasks(); // Run posted deadline.
EXPECT_EQ(1, client.num_draws());
EXPECT_TRUE(client.HasAction("ScheduledActionDrawAndSwapIfPossible"));
EXPECT_FALSE(client.HasAction("ScheduledActionManageTiles"));
EXPECT_FALSE(scheduler->RedrawPending());
EXPECT_FALSE(scheduler->BeginImplFrameDeadlinePending());
// If we get another DidManageTiles, we should not ManageTiles on the next
// frame. This verifies we don't alternate calling ManageTiles once and twice.
EXPECT_TRUE(scheduler->ManageTilesPending());
scheduler->DidManageTiles(); // An explicit ManageTiles.
EXPECT_FALSE(scheduler->ManageTilesPending());
scheduler->SetNeedsManageTiles();
scheduler->SetNeedsRedraw();
client.Reset();
client.AdvanceFrame();
EXPECT_ACTION("WillBeginImplFrame", client, 0, 2);
EXPECT_ACTION("ScheduledActionAnimate", client, 1, 2);
EXPECT_TRUE(scheduler->BeginImplFrameDeadlinePending());
EXPECT_TRUE(scheduler->ManageTilesPending());
client.Reset();
client.task_runner().RunPendingTasks(); // Run posted deadline.
EXPECT_EQ(1, client.num_draws());
EXPECT_TRUE(client.HasAction("ScheduledActionDrawAndSwapIfPossible"));
EXPECT_FALSE(client.HasAction("ScheduledActionManageTiles"));
EXPECT_FALSE(scheduler->RedrawPending());
EXPECT_FALSE(scheduler->BeginImplFrameDeadlinePending());
// Next frame without DidManageTiles should ManageTiles with draw.
scheduler->SetNeedsManageTiles();
scheduler->SetNeedsRedraw();
client.Reset();
client.AdvanceFrame();
EXPECT_ACTION("WillBeginImplFrame", client, 0, 2);
EXPECT_ACTION("ScheduledActionAnimate", client, 1, 2);
EXPECT_TRUE(scheduler->BeginImplFrameDeadlinePending());
client.Reset();
client.task_runner().RunPendingTasks(); // Run posted deadline.
EXPECT_EQ(1, client.num_draws());
EXPECT_TRUE(client.HasAction("ScheduledActionDrawAndSwapIfPossible"));
EXPECT_TRUE(client.HasAction("ScheduledActionManageTiles"));
EXPECT_LT(client.ActionIndex("ScheduledActionDrawAndSwapIfPossible"),
client.ActionIndex("ScheduledActionManageTiles"));
EXPECT_FALSE(scheduler->RedrawPending());
EXPECT_FALSE(scheduler->ManageTilesPending());
EXPECT_FALSE(scheduler->BeginImplFrameDeadlinePending());
scheduler->DidManageTiles(); // Corresponds to ScheduledActionManageTiles
}
TEST(SchedulerTest, ShouldUpdateVisibleTiles) {
FakeSchedulerClient client;
SchedulerSettings scheduler_settings;
scheduler_settings.impl_side_painting = true;
TestScheduler* scheduler = client.CreateScheduler(scheduler_settings);
scheduler->SetCanStart();
scheduler->SetVisible(true);
scheduler->SetCanDraw(true);
InitializeOutputSurfaceAndFirstCommit(scheduler, &client);
client.SetRedrawWillHappenIfUpdateVisibleTilesHappens(true);
// SetNeedsCommit should begin the frame.
client.Reset();
scheduler->SetNeedsCommit();
EXPECT_SINGLE_ACTION("SetNeedsBeginFrame", client);
client.Reset();
client.AdvanceFrame();
EXPECT_ACTION("WillBeginImplFrame", client, 0, 2);
EXPECT_ACTION("ScheduledActionSendBeginMainFrame", client, 1, 2);
EXPECT_TRUE(scheduler->BeginImplFrameDeadlinePending());
client.Reset();
scheduler->NotifyBeginMainFrameStarted();
scheduler->NotifyReadyToCommit();
EXPECT_SINGLE_ACTION("ScheduledActionCommit", client);
client.Reset();
scheduler->NotifyReadyToActivate();
EXPECT_SINGLE_ACTION("ScheduledActionActivateSyncTree", client);
client.Reset();
client.SetSwapContainsIncompleteTile(true);
client.task_runner().RunPendingTasks(); // Run posted deadline.
EXPECT_ACTION("ScheduledActionAnimate", client, 0, 2);
EXPECT_ACTION("ScheduledActionDrawAndSwapIfPossible", client, 1, 2);
EXPECT_FALSE(scheduler->RedrawPending());
client.Reset();
client.AdvanceFrame();
EXPECT_SINGLE_ACTION("WillBeginImplFrame", client);
EXPECT_TRUE(scheduler->BeginImplFrameDeadlinePending());
client.Reset();
client.task_runner().RunPendingTasks(); // Run posted deadline.
EXPECT_ACTION("ScheduledActionUpdateVisibleTiles", client, 0, 3);
EXPECT_ACTION("ScheduledActionAnimate", client, 1, 3);
EXPECT_ACTION("ScheduledActionDrawAndSwapIfPossible", client, 2, 3);
client.Reset();
client.AdvanceFrame();
EXPECT_SINGLE_ACTION("WillBeginImplFrame", client);
EXPECT_TRUE(scheduler->BeginImplFrameDeadlinePending());
// No more UpdateVisibleTiles().
client.Reset();
client.task_runner().RunPendingTasks(); // Run posted deadline.
EXPECT_SINGLE_ACTION("SetNeedsBeginFrame", client);
EXPECT_FALSE(client.needs_begin_frame());
}
TEST(SchedulerTest, TriggerBeginFrameDeadlineEarly) {
SchedulerClientNeedsManageTilesInDraw client;
SchedulerSettings default_scheduler_settings;
TestScheduler* scheduler = client.CreateScheduler(default_scheduler_settings);
scheduler->SetCanStart();
scheduler->SetVisible(true);
scheduler->SetCanDraw(true);
InitializeOutputSurfaceAndFirstCommit(scheduler, &client);
client.Reset();
scheduler->SetNeedsRedraw();
client.AdvanceFrame();
// The deadline should be zero since there is no work other than drawing
// pending.
EXPECT_EQ(base::TimeTicks(), client.posted_begin_impl_frame_deadline());
}
class SchedulerClientWithFixedEstimates : public FakeSchedulerClient {
public:
SchedulerClientWithFixedEstimates(
base::TimeDelta draw_duration,
base::TimeDelta begin_main_frame_to_commit_duration,
base::TimeDelta commit_to_activate_duration)
: draw_duration_(draw_duration),
begin_main_frame_to_commit_duration_(
begin_main_frame_to_commit_duration),
commit_to_activate_duration_(commit_to_activate_duration) {}
virtual base::TimeDelta DrawDurationEstimate() OVERRIDE {
return draw_duration_;
}
virtual base::TimeDelta BeginMainFrameToCommitDurationEstimate() OVERRIDE {
return begin_main_frame_to_commit_duration_;
}
virtual base::TimeDelta CommitToActivateDurationEstimate() OVERRIDE {
return commit_to_activate_duration_;
}
private:
base::TimeDelta draw_duration_;
base::TimeDelta begin_main_frame_to_commit_duration_;
base::TimeDelta commit_to_activate_duration_;
};
void MainFrameInHighLatencyMode(int64 begin_main_frame_to_commit_estimate_in_ms,
int64 commit_to_activate_estimate_in_ms,
bool impl_latency_takes_priority,
bool should_send_begin_main_frame) {
// Set up client with specified estimates (draw duration is set to 1).
SchedulerClientWithFixedEstimates client(
base::TimeDelta::FromMilliseconds(1),
base::TimeDelta::FromMilliseconds(
begin_main_frame_to_commit_estimate_in_ms),
base::TimeDelta::FromMilliseconds(commit_to_activate_estimate_in_ms));
SchedulerSettings default_scheduler_settings;
TestScheduler* scheduler = client.CreateScheduler(default_scheduler_settings);
scheduler->SetCanStart();
scheduler->SetVisible(true);
scheduler->SetCanDraw(true);
scheduler->SetImplLatencyTakesPriority(impl_latency_takes_priority);
InitializeOutputSurfaceAndFirstCommit(scheduler, &client);
// Impl thread hits deadline before commit finishes.
client.Reset();
scheduler->SetNeedsCommit();
EXPECT_FALSE(scheduler->MainThreadIsInHighLatencyMode());
client.AdvanceFrame();
EXPECT_FALSE(scheduler->MainThreadIsInHighLatencyMode());
client.task_runner().RunPendingTasks(); // Run posted deadline.
EXPECT_TRUE(scheduler->MainThreadIsInHighLatencyMode());
scheduler->NotifyBeginMainFrameStarted();
scheduler->NotifyReadyToCommit();
EXPECT_TRUE(scheduler->MainThreadIsInHighLatencyMode());
EXPECT_TRUE(client.HasAction("ScheduledActionSendBeginMainFrame"));
client.Reset();
scheduler->SetNeedsCommit();
EXPECT_TRUE(scheduler->MainThreadIsInHighLatencyMode());
client.AdvanceFrame();
EXPECT_TRUE(scheduler->MainThreadIsInHighLatencyMode());
client.task_runner().RunPendingTasks(); // Run posted deadline.
EXPECT_EQ(scheduler->MainThreadIsInHighLatencyMode(),
should_send_begin_main_frame);
EXPECT_EQ(client.HasAction("ScheduledActionSendBeginMainFrame"),
should_send_begin_main_frame);
}
TEST(SchedulerTest,
SkipMainFrameIfHighLatencyAndCanCommitAndActivateBeforeDeadline) {
// Set up client so that estimates indicate that we can commit and activate
// before the deadline (~8ms by default).
MainFrameInHighLatencyMode(1, 1, false, false);
}
TEST(SchedulerTest, NotSkipMainFrameIfHighLatencyAndCanCommitTooLong) {
// Set up client so that estimates indicate that the commit cannot finish
// before the deadline (~8ms by default).
MainFrameInHighLatencyMode(10, 1, false, true);
}
TEST(SchedulerTest, NotSkipMainFrameIfHighLatencyAndCanActivateTooLong) {
// Set up client so that estimates indicate that the activate cannot finish
// before the deadline (~8ms by default).
MainFrameInHighLatencyMode(1, 10, false, true);
}
TEST(SchedulerTest, NotSkipMainFrameInPreferImplLatencyMode) {
// Set up client so that estimates indicate that we can commit and activate
// before the deadline (~8ms by default), but also enable impl latency takes
// priority mode.
MainFrameInHighLatencyMode(1, 1, true, true);
}
TEST(SchedulerTest, PollForCommitCompletion) {
// Since we are simulating a long commit, set up a client with draw duration
// estimates that prevent skipping main frames to get to low latency mode.
SchedulerClientWithFixedEstimates client(
base::TimeDelta::FromMilliseconds(1),
base::TimeDelta::FromMilliseconds(32),
base::TimeDelta::FromMilliseconds(32));
client.set_log_anticipated_draw_time_change(true);
SchedulerSettings default_scheduler_settings;
TestScheduler* scheduler = client.CreateScheduler(default_scheduler_settings);
scheduler->SetCanDraw(true);
scheduler->SetCanStart();
scheduler->SetVisible(true);
scheduler->DidCreateAndInitializeOutputSurface();
scheduler->SetNeedsCommit();
EXPECT_TRUE(scheduler->CommitPending());
scheduler->NotifyBeginMainFrameStarted();
scheduler->NotifyReadyToCommit();
scheduler->SetNeedsRedraw();
BeginFrameArgs frame_args = CreateBeginFrameArgsForTesting(client.now_src());
frame_args.interval = base::TimeDelta::FromMilliseconds(1000);
scheduler->BeginFrame(frame_args);
EXPECT_TRUE(scheduler->BeginImplFrameDeadlinePending());
client.task_runner().RunPendingTasks(); // Run posted deadline.
EXPECT_FALSE(scheduler->BeginImplFrameDeadlinePending());
scheduler->DidSwapBuffers();
scheduler->DidSwapBuffersComplete();
// At this point, we've drawn a frame. Start another commit, but hold off on
// the NotifyReadyToCommit for now.
EXPECT_FALSE(scheduler->CommitPending());
scheduler->SetNeedsCommit();
scheduler->BeginFrame(frame_args);
EXPECT_TRUE(scheduler->CommitPending());
// Draw and swap the frame, but don't ack the swap to simulate the Browser
// blocking on the renderer.
EXPECT_TRUE(scheduler->BeginImplFrameDeadlinePending());
client.task_runner().RunPendingTasks(); // Run posted deadline.
EXPECT_FALSE(scheduler->BeginImplFrameDeadlinePending());
scheduler->DidSwapBuffers();
// Spin the event loop a few times and make sure we get more
// DidAnticipateDrawTimeChange calls every time.
int actions_so_far = client.num_actions_();
// Does three iterations to make sure that the timer is properly repeating.
for (int i = 0; i < 3; ++i) {
EXPECT_EQ((frame_args.interval * 2).InMicroseconds(),
client.task_runner().DelayToNextTaskTime().InMicroseconds())
<< scheduler->AsValue()->ToString();
client.task_runner().RunPendingTasks();
EXPECT_GT(client.num_actions_(), actions_so_far);
EXPECT_STREQ(client.Action(client.num_actions_() - 1),
"DidAnticipatedDrawTimeChange");
actions_so_far = client.num_actions_();
}
// Do the same thing after BeginMainFrame starts but still before activation.
scheduler->NotifyBeginMainFrameStarted();
for (int i = 0; i < 3; ++i) {
EXPECT_EQ((frame_args.interval * 2).InMicroseconds(),
client.task_runner().DelayToNextTaskTime().InMicroseconds())
<< scheduler->AsValue()->ToString();
client.task_runner().RunPendingTasks();
EXPECT_GT(client.num_actions_(), actions_so_far);
EXPECT_STREQ(client.Action(client.num_actions_() - 1),
"DidAnticipatedDrawTimeChange");
actions_so_far = client.num_actions_();
}
}
TEST(SchedulerTest, BeginRetroFrame) {
FakeSchedulerClient client;
SchedulerSettings scheduler_settings;
TestScheduler* scheduler = client.CreateScheduler(scheduler_settings);
scheduler->SetCanStart();
scheduler->SetVisible(true);
scheduler->SetCanDraw(true);
InitializeOutputSurfaceAndFirstCommit(scheduler, &client);
// SetNeedsCommit should begin the frame on the next BeginImplFrame.
client.Reset();
scheduler->SetNeedsCommit();
EXPECT_TRUE(client.needs_begin_frame());
EXPECT_SINGLE_ACTION("SetNeedsBeginFrame", client);
client.Reset();
// Create a BeginFrame with a long deadline to avoid race conditions.
// This is the first BeginFrame, which will be handled immediately.
BeginFrameArgs args = CreateBeginFrameArgsForTesting(client.now_src());
args.deadline += base::TimeDelta::FromHours(1);
scheduler->BeginFrame(args);
EXPECT_ACTION("WillBeginImplFrame", client, 0, 2);
EXPECT_ACTION("ScheduledActionSendBeginMainFrame", client, 1, 2);
EXPECT_TRUE(scheduler->BeginImplFrameDeadlinePending());
EXPECT_TRUE(client.needs_begin_frame());
client.Reset();
// Queue BeginFrames while we are still handling the previous BeginFrame.
args.frame_time += base::TimeDelta::FromSeconds(1);
scheduler->BeginFrame(args);
args.frame_time += base::TimeDelta::FromSeconds(1);
scheduler->BeginFrame(args);
// If we don't swap on the deadline, we wait for the next BeginImplFrame.
client.task_runner().RunPendingTasks(); // Run posted deadline.
EXPECT_NO_ACTION(client);
EXPECT_FALSE(scheduler->BeginImplFrameDeadlinePending());
EXPECT_TRUE(client.needs_begin_frame());
client.Reset();
// NotifyReadyToCommit should trigger the commit.
scheduler->NotifyBeginMainFrameStarted();
scheduler->NotifyReadyToCommit();
EXPECT_SINGLE_ACTION("ScheduledActionCommit", client);
EXPECT_TRUE(client.needs_begin_frame());
client.Reset();
// BeginImplFrame should prepare the draw.
client.task_runner().RunPendingTasks(); // Run posted BeginRetroFrame.
EXPECT_ACTION("WillBeginImplFrame", client, 0, 2);
EXPECT_ACTION("ScheduledActionAnimate", client, 1, 2);
EXPECT_TRUE(scheduler->BeginImplFrameDeadlinePending());
EXPECT_TRUE(client.needs_begin_frame());
client.Reset();
// BeginImplFrame deadline should draw.
client.task_runner().RunPendingTasks(); // Run posted deadline.
EXPECT_ACTION("ScheduledActionDrawAndSwapIfPossible", client, 0, 1);
EXPECT_FALSE(scheduler->BeginImplFrameDeadlinePending());
EXPECT_TRUE(client.needs_begin_frame());
client.Reset();
// The following BeginImplFrame deadline should SetNeedsBeginFrame(false)
// to avoid excessive toggles.
client.task_runner().RunPendingTasks(); // Run posted BeginRetroFrame.
EXPECT_SINGLE_ACTION("WillBeginImplFrame", client);
EXPECT_TRUE(scheduler->BeginImplFrameDeadlinePending());
client.Reset();
client.task_runner().RunPendingTasks(); // Run posted deadline.
EXPECT_SINGLE_ACTION("SetNeedsBeginFrame", client);
EXPECT_FALSE(client.needs_begin_frame());
client.Reset();
}
TEST(SchedulerTest, BeginRetroFrame_SwapThrottled) {
FakeSchedulerClient client;
SchedulerSettings scheduler_settings;
TestScheduler* scheduler = client.CreateScheduler(scheduler_settings);
scheduler->SetCanStart();
scheduler->SetVisible(true);
scheduler->SetCanDraw(true);
InitializeOutputSurfaceAndFirstCommit(scheduler, &client);
// To test swap ack throttling, this test disables automatic swap acks.
scheduler->SetMaxSwapsPending(1);
client.SetAutomaticSwapAck(false);
// SetNeedsCommit should begin the frame on the next BeginImplFrame.
client.Reset();
scheduler->SetNeedsCommit();
EXPECT_TRUE(client.needs_begin_frame());
EXPECT_SINGLE_ACTION("SetNeedsBeginFrame", client);
client.Reset();
// Create a BeginFrame with a long deadline to avoid race conditions.
// This is the first BeginFrame, which will be handled immediately.
BeginFrameArgs args = CreateBeginFrameArgsForTesting(client.now_src());
args.deadline += base::TimeDelta::FromHours(1);
scheduler->BeginFrame(args);
EXPECT_ACTION("WillBeginImplFrame", client, 0, 2);
EXPECT_ACTION("ScheduledActionSendBeginMainFrame", client, 1, 2);
EXPECT_TRUE(scheduler->BeginImplFrameDeadlinePending());
EXPECT_TRUE(client.needs_begin_frame());
client.Reset();
// Queue BeginFrame while we are still handling the previous BeginFrame.
EXPECT_TRUE(scheduler->BeginImplFrameDeadlinePending());
args.frame_time += base::TimeDelta::FromSeconds(1);
scheduler->BeginFrame(args);
EXPECT_NO_ACTION(client);
EXPECT_TRUE(scheduler->BeginImplFrameDeadlinePending());
client.Reset();
// NotifyReadyToCommit should trigger the pending commit and draw.
scheduler->NotifyBeginMainFrameStarted();
scheduler->NotifyReadyToCommit();
EXPECT_SINGLE_ACTION("ScheduledActionCommit", client);
EXPECT_TRUE(client.needs_begin_frame());
client.Reset();
// Swapping will put us into a swap throttled state.
client.task_runner().RunPendingTasks(); // Run posted deadline.
EXPECT_ACTION("ScheduledActionAnimate", client, 0, 2);
EXPECT_ACTION("ScheduledActionDrawAndSwapIfPossible", client, 1, 2);
EXPECT_FALSE(scheduler->BeginImplFrameDeadlinePending());
EXPECT_TRUE(client.needs_begin_frame());
client.Reset();
// While swap throttled, BeginRetroFrames should trigger BeginImplFrames
// but not a BeginMainFrame or draw.
scheduler->SetNeedsCommit();
client.task_runner().RunPendingTasks(); // Run posted BeginRetroFrame.
EXPECT_ACTION("WillBeginImplFrame", client, 0, 1);
EXPECT_TRUE(scheduler->BeginImplFrameDeadlinePending());
EXPECT_TRUE(client.needs_begin_frame());
client.Reset();
// Queue BeginFrame while we are still handling the previous BeginFrame.
args.frame_time += base::TimeDelta::FromSeconds(1);
scheduler->BeginFrame(args);
EXPECT_NO_ACTION(client);
EXPECT_TRUE(scheduler->BeginImplFrameDeadlinePending());
EXPECT_TRUE(client.needs_begin_frame());
client.Reset();
// Take us out of a swap throttled state.
scheduler->DidSwapBuffersComplete();
EXPECT_ACTION("ScheduledActionSendBeginMainFrame", client, 0, 1);
EXPECT_TRUE(scheduler->BeginImplFrameDeadlinePending());
EXPECT_TRUE(client.needs_begin_frame());
client.Reset();
// BeginImplFrame deadline should draw.
scheduler->SetNeedsRedraw();
EXPECT_TRUE(client.task_runner().RunTasksWhile(
client.ImplFrameDeadlinePending(true)));
EXPECT_ACTION("ScheduledActionAnimate", client, 0, 2);
EXPECT_ACTION("ScheduledActionDrawAndSwapIfPossible", client, 1, 2);
EXPECT_FALSE(scheduler->BeginImplFrameDeadlinePending());
EXPECT_TRUE(client.needs_begin_frame());
client.Reset();
}
void BeginFramesNotFromClient(bool begin_frame_scheduling_enabled,
bool throttle_frame_production) {
FakeSchedulerClient client;
SchedulerSettings scheduler_settings;
scheduler_settings.begin_frame_scheduling_enabled =
begin_frame_scheduling_enabled;
scheduler_settings.throttle_frame_production = throttle_frame_production;
TestScheduler* scheduler = client.CreateScheduler(scheduler_settings);
scheduler->SetCanStart();
scheduler->SetVisible(true);
scheduler->SetCanDraw(true);
InitializeOutputSurfaceAndFirstCommit(scheduler, &client);
// SetNeedsCommit should begin the frame on the next BeginImplFrame
// without calling SetNeedsBeginFrame.
client.Reset();
scheduler->SetNeedsCommit();
EXPECT_FALSE(client.needs_begin_frame());
EXPECT_NO_ACTION(client);
client.Reset();
// When the client-driven BeginFrame are disabled, the scheduler posts it's
// own BeginFrame tasks.
client.task_runner().RunPendingTasks(); // Run posted BeginFrame.
EXPECT_ACTION("WillBeginImplFrame", client, 0, 2);
EXPECT_ACTION("ScheduledActionSendBeginMainFrame", client, 1, 2);
EXPECT_TRUE(scheduler->BeginImplFrameDeadlinePending());
EXPECT_FALSE(client.needs_begin_frame());
client.Reset();
// If we don't swap on the deadline, we wait for the next BeginFrame.
client.task_runner().RunPendingTasks(); // Run posted deadline.
EXPECT_NO_ACTION(client);
EXPECT_FALSE(scheduler->BeginImplFrameDeadlinePending());
EXPECT_FALSE(client.needs_begin_frame());
client.Reset();
// NotifyReadyToCommit should trigger the commit.
scheduler->NotifyBeginMainFrameStarted();
scheduler->NotifyReadyToCommit();
EXPECT_SINGLE_ACTION("ScheduledActionCommit", client);
EXPECT_FALSE(client.needs_begin_frame());
client.Reset();
// BeginImplFrame should prepare the draw.
client.task_runner().RunPendingTasks(); // Run posted BeginFrame.
EXPECT_ACTION("WillBeginImplFrame", client, 0, 2);
EXPECT_ACTION("ScheduledActionAnimate", client, 1, 2);
EXPECT_TRUE(scheduler->BeginImplFrameDeadlinePending());
EXPECT_FALSE(client.needs_begin_frame());
client.Reset();
// BeginImplFrame deadline should draw.
client.task_runner().RunTasksWhile(client.ImplFrameDeadlinePending(true));
EXPECT_ACTION("ScheduledActionDrawAndSwapIfPossible", client, 0, 1);
EXPECT_FALSE(scheduler->BeginImplFrameDeadlinePending());
EXPECT_FALSE(client.needs_begin_frame());
client.Reset();
// The following BeginImplFrame deadline should SetNeedsBeginFrame(false)
// to avoid excessive toggles.
client.task_runner().RunPendingTasks(); // Run posted BeginFrame.
EXPECT_SINGLE_ACTION("WillBeginImplFrame", client);
EXPECT_TRUE(scheduler->BeginImplFrameDeadlinePending());
client.Reset();
// Make sure SetNeedsBeginFrame isn't called on the client
// when the BeginFrame is no longer needed.
client.task_runner().RunPendingTasks(); // Run posted deadline.
EXPECT_NO_ACTION(client);
EXPECT_FALSE(client.needs_begin_frame());
client.Reset();
}
TEST(SchedulerTest, SyntheticBeginFrames) {
bool begin_frame_scheduling_enabled = false;
bool throttle_frame_production = true;
BeginFramesNotFromClient(begin_frame_scheduling_enabled,
throttle_frame_production);
}
TEST(SchedulerTest, VSyncThrottlingDisabled) {
bool begin_frame_scheduling_enabled = true;
bool throttle_frame_production = false;
BeginFramesNotFromClient(begin_frame_scheduling_enabled,
throttle_frame_production);
}
TEST(SchedulerTest, SyntheticBeginFrames_And_VSyncThrottlingDisabled) {
bool begin_frame_scheduling_enabled = false;
bool throttle_frame_production = false;
BeginFramesNotFromClient(begin_frame_scheduling_enabled,
throttle_frame_production);
}
void BeginFramesNotFromClient_SwapThrottled(bool begin_frame_scheduling_enabled,
bool throttle_frame_production) {
FakeSchedulerClient client;
SchedulerSettings scheduler_settings;
scheduler_settings.begin_frame_scheduling_enabled =
begin_frame_scheduling_enabled;
scheduler_settings.throttle_frame_production = throttle_frame_production;
TestScheduler* scheduler = client.CreateScheduler(scheduler_settings);
scheduler->SetCanStart();
scheduler->SetVisible(true);
scheduler->SetCanDraw(true);
InitializeOutputSurfaceAndFirstCommit(scheduler, &client);
// To test swap ack throttling, this test disables automatic swap acks.
scheduler->SetMaxSwapsPending(1);
client.SetAutomaticSwapAck(false);
// SetNeedsCommit should begin the frame on the next BeginImplFrame.
client.Reset();
scheduler->SetNeedsCommit();
EXPECT_FALSE(client.needs_begin_frame());
EXPECT_NO_ACTION(client);
client.Reset();
// Trigger the first BeginImplFrame and BeginMainFrame
client.task_runner().RunPendingTasks(); // Run posted BeginFrame.
EXPECT_ACTION("WillBeginImplFrame", client, 0, 2);
EXPECT_ACTION("ScheduledActionSendBeginMainFrame", client, 1, 2);
EXPECT_TRUE(scheduler->BeginImplFrameDeadlinePending());
EXPECT_FALSE(client.needs_begin_frame());
client.Reset();
// NotifyReadyToCommit should trigger the pending commit and draw.
scheduler->NotifyBeginMainFrameStarted();
scheduler->NotifyReadyToCommit();
EXPECT_SINGLE_ACTION("ScheduledActionCommit", client);
EXPECT_FALSE(client.needs_begin_frame());
client.Reset();
// Swapping will put us into a swap throttled state.
client.task_runner().RunPendingTasks(); // Run posted deadline.
EXPECT_ACTION("ScheduledActionAnimate", client, 0, 2);
EXPECT_ACTION("ScheduledActionDrawAndSwapIfPossible", client, 1, 2);
EXPECT_FALSE(scheduler->BeginImplFrameDeadlinePending());
EXPECT_FALSE(client.needs_begin_frame());
client.Reset();
// While swap throttled, BeginFrames should trigger BeginImplFrames,
// but not a BeginMainFrame or draw.
scheduler->SetNeedsCommit();
client.task_runner().RunPendingTasks(); // Run posted BeginFrame.
EXPECT_ACTION("WillBeginImplFrame", client, 0, 1);
EXPECT_TRUE(scheduler->BeginImplFrameDeadlinePending());
EXPECT_FALSE(client.needs_begin_frame());
client.Reset();
// Take us out of a swap throttled state.
scheduler->DidSwapBuffersComplete();
EXPECT_ACTION("ScheduledActionSendBeginMainFrame", client, 0, 1);
EXPECT_TRUE(scheduler->BeginImplFrameDeadlinePending());
EXPECT_FALSE(client.needs_begin_frame());
client.Reset();
// BeginImplFrame deadline should draw.
scheduler->SetNeedsRedraw();
client.task_runner().RunPendingTasks(); // Run posted deadline.
EXPECT_ACTION("ScheduledActionAnimate", client, 0, 2);
EXPECT_ACTION("ScheduledActionDrawAndSwapIfPossible", client, 1, 2);
EXPECT_FALSE(scheduler->BeginImplFrameDeadlinePending());
EXPECT_FALSE(client.needs_begin_frame());
client.Reset();
}
TEST(SchedulerTest, SyntheticBeginFrames_SwapThrottled) {
bool begin_frame_scheduling_enabled = false;
bool throttle_frame_production = true;
BeginFramesNotFromClient_SwapThrottled(begin_frame_scheduling_enabled,
throttle_frame_production);
}
TEST(SchedulerTest, VSyncThrottlingDisabled_SwapThrottled) {
bool begin_frame_scheduling_enabled = true;
bool throttle_frame_production = false;
BeginFramesNotFromClient_SwapThrottled(begin_frame_scheduling_enabled,
throttle_frame_production);
}
TEST(SchedulerTest,
SyntheticBeginFrames_And_VSyncThrottlingDisabled_SwapThrottled) {
bool begin_frame_scheduling_enabled = false;
bool throttle_frame_production = false;
BeginFramesNotFromClient_SwapThrottled(begin_frame_scheduling_enabled,
throttle_frame_production);
}
TEST(SchedulerTest, DidLoseOutputSurfaceAfterOutputSurfaceIsInitialized) {
FakeSchedulerClient client;
SchedulerSettings scheduler_settings;
TestScheduler* scheduler = client.CreateScheduler(scheduler_settings);
scheduler->SetCanStart();
scheduler->SetVisible(true);
scheduler->SetCanDraw(true);
EXPECT_SINGLE_ACTION("ScheduledActionBeginOutputSurfaceCreation", client);
client.Reset();
scheduler->DidCreateAndInitializeOutputSurface();
EXPECT_NO_ACTION(client);
scheduler->DidLoseOutputSurface();
EXPECT_SINGLE_ACTION("ScheduledActionBeginOutputSurfaceCreation", client);
}
TEST(SchedulerTest, DidLoseOutputSurfaceAfterBeginFrameStarted) {
FakeSchedulerClient client;
SchedulerSettings scheduler_settings;
TestScheduler* scheduler = client.CreateScheduler(scheduler_settings);
scheduler->SetCanStart();
scheduler->SetVisible(true);
scheduler->SetCanDraw(true);
EXPECT_SINGLE_ACTION("ScheduledActionBeginOutputSurfaceCreation", client);
InitializeOutputSurfaceAndFirstCommit(scheduler, &client);
// SetNeedsCommit should begin the frame.
client.Reset();
scheduler->SetNeedsCommit();
EXPECT_SINGLE_ACTION("SetNeedsBeginFrame", client);
client.Reset();
client.AdvanceFrame();
EXPECT_ACTION("WillBeginImplFrame", client, 0, 2);
EXPECT_ACTION("ScheduledActionSendBeginMainFrame", client, 1, 2);
EXPECT_TRUE(scheduler->BeginImplFrameDeadlinePending());
client.Reset();
scheduler->DidLoseOutputSurface();
// Do nothing when impl frame is in deadine pending state.
EXPECT_NO_ACTION(client);
client.Reset();
scheduler->NotifyBeginMainFrameStarted();
scheduler->NotifyReadyToCommit();
EXPECT_ACTION("ScheduledActionCommit", client, 0, 1);
client.Reset();
client.task_runner().RunPendingTasks(); // Run posted deadline.
EXPECT_SINGLE_ACTION("ScheduledActionBeginOutputSurfaceCreation", client);
}
void DidLoseOutputSurfaceAfterBeginFrameStartedWithHighLatency(
bool impl_side_painting) {
FakeSchedulerClient client;
SchedulerSettings scheduler_settings;
scheduler_settings.impl_side_painting = impl_side_painting;
TestScheduler* scheduler = client.CreateScheduler(scheduler_settings);
scheduler->SetCanStart();
scheduler->SetVisible(true);
scheduler->SetCanDraw(true);
EXPECT_SINGLE_ACTION("ScheduledActionBeginOutputSurfaceCreation", client);
InitializeOutputSurfaceAndFirstCommit(scheduler, &client);
// SetNeedsCommit should begin the frame.
client.Reset();
scheduler->SetNeedsCommit();
EXPECT_SINGLE_ACTION("SetNeedsBeginFrame", client);
client.Reset();
client.AdvanceFrame();
EXPECT_ACTION("WillBeginImplFrame", client, 0, 2);
EXPECT_ACTION("ScheduledActionSendBeginMainFrame", client, 1, 2);
EXPECT_TRUE(scheduler->BeginImplFrameDeadlinePending());
client.Reset();
scheduler->DidLoseOutputSurface();
// Do nothing when impl frame is in deadine pending state.
EXPECT_NO_ACTION(client);
client.Reset();
// Run posted deadline.
EXPECT_TRUE(scheduler->BeginImplFrameDeadlinePending());
client.task_runner().RunTasksWhile(client.ImplFrameDeadlinePending(true));
// OnBeginImplFrameDeadline didn't schedule any actions because main frame is
// not yet completed.
EXPECT_NO_ACTION(client);
EXPECT_FALSE(scheduler->BeginImplFrameDeadlinePending());
// BeginImplFrame is not started.
client.task_runner().RunUntilTime(client.now_src()->Now() +
base::TimeDelta::FromMilliseconds(10));
EXPECT_NO_ACTION(client);
EXPECT_FALSE(scheduler->BeginImplFrameDeadlinePending());
client.Reset();
scheduler->NotifyBeginMainFrameStarted();
scheduler->NotifyReadyToCommit();
if (impl_side_painting) {
EXPECT_ACTION("ScheduledActionCommit", client, 0, 3);
EXPECT_ACTION("ScheduledActionActivateSyncTree", client, 1, 3);
EXPECT_ACTION("ScheduledActionBeginOutputSurfaceCreation", client, 2, 3);
} else {
EXPECT_ACTION("ScheduledActionCommit", client, 0, 2);
EXPECT_ACTION("ScheduledActionBeginOutputSurfaceCreation", client, 1, 2);
}
}
TEST(SchedulerTest, DidLoseOutputSurfaceAfterBeginFrameStartedWithHighLatency) {
bool impl_side_painting = false;
DidLoseOutputSurfaceAfterBeginFrameStartedWithHighLatency(impl_side_painting);
}
TEST(SchedulerTest,
DidLoseOutputSurfaceAfterBeginFrameStartedWithHighLatencyWithImplPaint) {
bool impl_side_painting = true;
DidLoseOutputSurfaceAfterBeginFrameStartedWithHighLatency(impl_side_painting);
}
void DidLoseOutputSurfaceAfterReadyToCommit(bool impl_side_painting) {
FakeSchedulerClient client;
SchedulerSettings scheduler_settings;
scheduler_settings.impl_side_painting = impl_side_painting;
TestScheduler* scheduler = client.CreateScheduler(scheduler_settings);
scheduler->SetCanStart();
scheduler->SetVisible(true);
scheduler->SetCanDraw(true);
EXPECT_SINGLE_ACTION("ScheduledActionBeginOutputSurfaceCreation", client);
InitializeOutputSurfaceAndFirstCommit(scheduler, &client);
// SetNeedsCommit should begin the frame.
client.Reset();
scheduler->SetNeedsCommit();
EXPECT_SINGLE_ACTION("SetNeedsBeginFrame", client);
client.Reset();
client.AdvanceFrame();
EXPECT_ACTION("WillBeginImplFrame", client, 0, 2);
EXPECT_ACTION("ScheduledActionSendBeginMainFrame", client, 1, 2);
EXPECT_TRUE(scheduler->BeginImplFrameDeadlinePending());
client.Reset();
scheduler->NotifyBeginMainFrameStarted();
scheduler->NotifyReadyToCommit();
EXPECT_SINGLE_ACTION("ScheduledActionCommit", client);
client.Reset();
scheduler->DidLoseOutputSurface();
if (impl_side_painting) {
// Sync tree should be forced to activate.
EXPECT_SINGLE_ACTION("ScheduledActionActivateSyncTree", client);
} else {
// Do nothing when impl frame is in deadine pending state.
EXPECT_NO_ACTION(client);
}
client.Reset();
client.task_runner().RunPendingTasks(); // Run posted deadline.
EXPECT_SINGLE_ACTION("ScheduledActionBeginOutputSurfaceCreation", client);
}
TEST(SchedulerTest, DidLoseOutputSurfaceAfterReadyToCommit) {
DidLoseOutputSurfaceAfterReadyToCommit(false);
}
TEST(SchedulerTest, DidLoseOutputSurfaceAfterReadyToCommitWithImplPainting) {
DidLoseOutputSurfaceAfterReadyToCommit(true);
}
TEST(SchedulerTest, DidLoseOutputSurfaceAfterSetNeedsManageTiles) {
FakeSchedulerClient client;
SchedulerSettings scheduler_settings;
TestScheduler* scheduler = client.CreateScheduler(scheduler_settings);
scheduler->SetCanStart();
scheduler->SetVisible(true);
scheduler->SetCanDraw(true);
InitializeOutputSurfaceAndFirstCommit(scheduler, &client);
client.Reset();
scheduler->SetNeedsManageTiles();
scheduler->SetNeedsRedraw();
EXPECT_SINGLE_ACTION("SetNeedsBeginFrame", client);
EXPECT_TRUE(client.needs_begin_frame());
client.Reset();
client.AdvanceFrame();
EXPECT_ACTION("WillBeginImplFrame", client, 0, 2);
EXPECT_ACTION("ScheduledActionAnimate", client, 1, 2);
EXPECT_TRUE(scheduler->BeginImplFrameDeadlinePending());
client.Reset();
scheduler->DidLoseOutputSurface();
EXPECT_NO_ACTION(client);
client.Reset();
client.task_runner().RunPendingTasks(); // Run posted deadline.
EXPECT_ACTION("ScheduledActionManageTiles", client, 0, 2);
EXPECT_ACTION("ScheduledActionBeginOutputSurfaceCreation", client, 1, 2);
}
TEST(SchedulerTest, DidLoseOutputSurfaceAfterBeginRetroFramePosted) {
FakeSchedulerClient client;
SchedulerSettings scheduler_settings;
TestScheduler* scheduler = client.CreateScheduler(scheduler_settings);
scheduler->SetCanStart();
scheduler->SetVisible(true);
scheduler->SetCanDraw(true);
InitializeOutputSurfaceAndFirstCommit(scheduler, &client);
// SetNeedsCommit should begin the frame on the next BeginImplFrame.
client.Reset();
scheduler->SetNeedsCommit();
EXPECT_TRUE(client.needs_begin_frame());
EXPECT_SINGLE_ACTION("SetNeedsBeginFrame", client);
// Create a BeginFrame with a long deadline to avoid race conditions.
// This is the first BeginFrame, which will be handled immediately.
client.Reset();
BeginFrameArgs args = CreateBeginFrameArgsForTesting(client.now_src());
args.deadline += base::TimeDelta::FromHours(1);
scheduler->BeginFrame(args);
EXPECT_ACTION("WillBeginImplFrame", client, 0, 2);
EXPECT_ACTION("ScheduledActionSendBeginMainFrame", client, 1, 2);
EXPECT_TRUE(scheduler->BeginImplFrameDeadlinePending());
EXPECT_TRUE(client.needs_begin_frame());
// Queue BeginFrames while we are still handling the previous BeginFrame.
args.frame_time += base::TimeDelta::FromSeconds(1);
scheduler->BeginFrame(args);
args.frame_time += base::TimeDelta::FromSeconds(1);
scheduler->BeginFrame(args);
// If we don't swap on the deadline, we wait for the next BeginImplFrame.
client.Reset();
client.task_runner().RunPendingTasks(); // Run posted deadline.
EXPECT_NO_ACTION(client);
EXPECT_FALSE(scheduler->BeginImplFrameDeadlinePending());
EXPECT_TRUE(client.needs_begin_frame());
// NotifyReadyToCommit should trigger the commit.
client.Reset();
scheduler->NotifyBeginMainFrameStarted();
scheduler->NotifyReadyToCommit();
EXPECT_SINGLE_ACTION("ScheduledActionCommit", client);
EXPECT_TRUE(client.needs_begin_frame());
client.Reset();
EXPECT_FALSE(scheduler->IsBeginRetroFrameArgsEmpty());
scheduler->DidLoseOutputSurface();
EXPECT_SINGLE_ACTION("ScheduledActionBeginOutputSurfaceCreation", client);
EXPECT_TRUE(client.needs_begin_frame());
EXPECT_TRUE(scheduler->IsBeginRetroFrameArgsEmpty());
// Posted BeginRetroFrame is aborted.
client.Reset();
client.task_runner().RunPendingTasks();
EXPECT_NO_ACTION(client);
}
TEST(SchedulerTest, DidLoseOutputSurfaceDuringBeginRetroFrameRunning) {
FakeSchedulerClient client;
SchedulerSettings scheduler_settings;
TestScheduler* scheduler = client.CreateScheduler(scheduler_settings);
scheduler->SetCanStart();
scheduler->SetVisible(true);
scheduler->SetCanDraw(true);
InitializeOutputSurfaceAndFirstCommit(scheduler, &client);
// SetNeedsCommit should begin the frame on the next BeginImplFrame.
client.Reset();
scheduler->SetNeedsCommit();
EXPECT_TRUE(client.needs_begin_frame());
EXPECT_SINGLE_ACTION("SetNeedsBeginFrame", client);
// Create a BeginFrame with a long deadline to avoid race conditions.
// This is the first BeginFrame, which will be handled immediately.
client.Reset();
BeginFrameArgs args = CreateBeginFrameArgsForTesting(client.now_src());
args.deadline += base::TimeDelta::FromHours(1);
scheduler->BeginFrame(args);
EXPECT_ACTION("WillBeginImplFrame", client, 0, 2);
EXPECT_ACTION("ScheduledActionSendBeginMainFrame", client, 1, 2);
EXPECT_TRUE(scheduler->BeginImplFrameDeadlinePending());
EXPECT_TRUE(client.needs_begin_frame());
// Queue BeginFrames while we are still handling the previous BeginFrame.
args.frame_time += base::TimeDelta::FromSeconds(1);
scheduler->BeginFrame(args);
args.frame_time += base::TimeDelta::FromSeconds(1);
scheduler->BeginFrame(args);
// If we don't swap on the deadline, we wait for the next BeginImplFrame.
client.Reset();
client.task_runner().RunPendingTasks(); // Run posted deadline.
EXPECT_NO_ACTION(client);
EXPECT_FALSE(scheduler->BeginImplFrameDeadlinePending());
EXPECT_TRUE(client.needs_begin_frame());
// NotifyReadyToCommit should trigger the commit.
client.Reset();
scheduler->NotifyBeginMainFrameStarted();
scheduler->NotifyReadyToCommit();
EXPECT_SINGLE_ACTION("ScheduledActionCommit", client);
EXPECT_TRUE(client.needs_begin_frame());
// BeginImplFrame should prepare the draw.
client.Reset();
client.task_runner().RunPendingTasks(); // Run posted BeginRetroFrame.
EXPECT_ACTION("WillBeginImplFrame", client, 0, 2);
EXPECT_ACTION("ScheduledActionAnimate", client, 1, 2);
EXPECT_TRUE(scheduler->BeginImplFrameDeadlinePending());
EXPECT_TRUE(client.needs_begin_frame());
client.Reset();
EXPECT_FALSE(scheduler->IsBeginRetroFrameArgsEmpty());
scheduler->DidLoseOutputSurface();
EXPECT_NO_ACTION(client);
EXPECT_TRUE(scheduler->IsBeginRetroFrameArgsEmpty());
// BeginImplFrame deadline should abort drawing.
client.Reset();
client.task_runner().RunPendingTasks(); // Run posted deadline.
EXPECT_SINGLE_ACTION("ScheduledActionBeginOutputSurfaceCreation", client);
EXPECT_FALSE(scheduler->BeginImplFrameDeadlinePending());
EXPECT_TRUE(client.needs_begin_frame());
// No more BeginRetroFrame because BeginRetroFrame queue is cleared.
client.Reset();
client.task_runner().RunPendingTasks();
EXPECT_NO_ACTION(client);
}
TEST(SchedulerTest,
StopBeginFrameAfterDidLoseOutputSurfaceWithSyntheticBeginFrameSource) {
FakeSchedulerClient client;
SchedulerSettings scheduler_settings;
scheduler_settings.begin_frame_scheduling_enabled = false;
TestScheduler* scheduler = client.CreateScheduler(scheduler_settings);
scheduler->SetCanStart();
scheduler->SetVisible(true);
scheduler->SetCanDraw(true);
InitializeOutputSurfaceAndFirstCommit(scheduler, &client);
// SetNeedsCommit should begin the frame on the next BeginImplFrame.
client.Reset();
EXPECT_FALSE(scheduler->IsSyntheticBeginFrameSourceActive());
scheduler->SetNeedsCommit();
EXPECT_TRUE(scheduler->IsSyntheticBeginFrameSourceActive());
client.Reset();
client.task_runner().RunPendingTasks(); // Run posted Tick.
EXPECT_ACTION("WillBeginImplFrame", client, 0, 2);
EXPECT_ACTION("ScheduledActionSendBeginMainFrame", client, 1, 2);
EXPECT_TRUE(scheduler->BeginImplFrameDeadlinePending());
EXPECT_TRUE(scheduler->IsSyntheticBeginFrameSourceActive());
// NotifyReadyToCommit should trigger the commit.
client.Reset();
scheduler->NotifyBeginMainFrameStarted();
scheduler->NotifyReadyToCommit();
EXPECT_SINGLE_ACTION("ScheduledActionCommit", client);
EXPECT_TRUE(scheduler->IsSyntheticBeginFrameSourceActive());
client.Reset();
scheduler->DidLoseOutputSurface();
EXPECT_EQ(0, client.num_actions_());
EXPECT_FALSE(scheduler->IsSyntheticBeginFrameSourceActive());
client.Reset();
client.task_runner().RunPendingTasks(); // Run posted deadline.
EXPECT_SINGLE_ACTION("ScheduledActionBeginOutputSurfaceCreation", client);
EXPECT_FALSE(scheduler->IsSyntheticBeginFrameSourceActive());
}
} // namespace
} // namespace cc
| bsd-3-clause |
ourochan/candescantNUI | CCT.NUI.Samples/ImageManipulation/ImageOperations.cs | 4502 | using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Drawing.Drawing2D;
namespace CCT.NUI.Samples.ImageManipulation
{
public class ImageOperations
{
public static decimal ProportionalScaleRatio(int actualWidth, int actualHeight, int targetWidth, int targetHeight)
{
decimal ratioX = (decimal)targetWidth / actualWidth;
decimal ratioY = (decimal)targetHeight / actualHeight;
return Math.Min(ratioX, ratioY);
}
public static Size ProportionalScale(int actualWidth, int actualHeight, int targetWidth, int targetHeight)
{
var ratio = ProportionalScaleRatio(actualWidth, actualHeight, targetWidth, targetHeight);
return new Size((int)Math.Round(actualWidth * ratio), (int)Math.Round(actualHeight * ratio));
}
private static Image Resize(Image originalImage, int newWidth, int newHeight, CompositingQuality compositingQuality, SmoothingMode smoothingMode, InterpolationMode interpolationMode, PixelOffsetMode pixelOffsetmode)
{
Image result = new Bitmap(newWidth, newHeight);
using (var graphic = Graphics.FromImage(result))
{
graphic.CompositingQuality = compositingQuality;
graphic.SmoothingMode = smoothingMode;
graphic.InterpolationMode = interpolationMode;
graphic.PixelOffsetMode = pixelOffsetmode;
Rectangle rectangle = new Rectangle(0, 0, newWidth, newHeight);
graphic.DrawImage(originalImage, rectangle);
return result;
}
}
public static Image QualityResize(Image originalImage, int newWidth, int newHeight)
{
return Resize(originalImage, newWidth, newHeight, CompositingQuality.HighQuality, SmoothingMode.HighQuality, InterpolationMode.HighQualityBicubic, PixelOffsetMode.HighQuality);
}
public static Image FastResize(Image originalImage, int newWidth, int newHeight)
{
return Resize(originalImage, newWidth, newHeight, CompositingQuality.HighSpeed, SmoothingMode.HighSpeed, InterpolationMode.Low, PixelOffsetMode.HighSpeed);
}
public static Image FastProportionalScale(Image image, int targetWidth, int targetHeight)
{
var newSize = ProportionalScale(image.Width, image.Height, targetWidth, targetHeight);
return FastResize(image, newSize.Width, newSize.Height);
}
public static Image QualityProportionalScale(Image image, int targetWidth, int targetHeight)
{
var newSize = ProportionalScale(image.Width, image.Height, targetWidth, targetHeight);
return QualityResize(image, newSize.Width, newSize.Height);
}
public static Image Crop(Image image, Rectangle area)
{
var newImage = new Bitmap(area.Width, area.Height);
using (var graphics = Graphics.FromImage(newImage))
{
graphics.DrawImage(image, new Rectangle(0, 0, area.Width, area.Height), area, GraphicsUnit.Pixel);
}
return newImage;
}
public static Rectangle ZoomArea(Point startDragLocation, Point endDragLocation, Size originalSize, Size targetSize, Size border)
{
var screenArea = GetRectangle(startDragLocation, endDragLocation);
screenArea.X -= border.Width;
screenArea.Y -= border.Height;
var factor = 1m / ProportionalScaleRatio(originalSize.Width, originalSize.Height, targetSize.Width, targetSize.Height);
if (screenArea.Width > 0 && screenArea.Height > 0)
{
return Multiply(screenArea, factor);
}
return Rectangle.Empty;
}
public static Rectangle Multiply(Rectangle rectangle, decimal factor)
{
return new Rectangle((int) (rectangle.X * factor), (int) (rectangle.Y * factor), (int) (rectangle.Width * factor), (int) (rectangle.Height * factor));
}
public static Rectangle GetRectangle(Point point1, Point point2)
{
int x = Math.Min(point1.X, point2.X);
int y = Math.Min(point1.Y, point2.Y);
int w = Math.Max(point1.X, point2.X) - x;
int h = Math.Max(point1.Y, point2.Y) - y;
return new Rectangle(x, y, w, h);
}
}
}
| bsd-3-clause |
scottstephens/boo | src/Boo.Lang.Compiler/Steps/Generators/GeneratorItemTypeInferrer.cs | 2330 | #region license
// Copyright (c) 2009 Rodrigo B. de Oliveira (rbo@acm.org)
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without modification,
// are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// * Neither the name of Rodrigo B. de Oliveira nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
// THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion
using Boo.Lang.Compiler.Ast;
using Boo.Lang.Compiler.TypeSystem;
using Boo.Lang.Compiler.TypeSystem.Internal;
namespace Boo.Lang.Compiler.Steps.Generators
{
public class GeneratorItemTypeInferrer : AbstractCompilerComponent
{
public virtual IType GeneratorItemTypeFor(InternalMethod generator)
{
if (TypeSystemServices.IsGenericGeneratorReturnType(generator.ReturnType))
return generator.ReturnType.ConstructedInfo.GenericArguments[0];
ExpressionCollection yieldExpressions = generator.YieldExpressions;
return yieldExpressions.Count > 0
? TypeSystemServices.GetMostGenericType(yieldExpressions)
: TypeSystemServices.ObjectType;
}
}
}
| bsd-3-clause |
gregorschatz/pymodbus3 | pymodbus3/server/__init__.py | 33 | # -*- coding: utf-8 -*-
"""
"""
| bsd-3-clause |
darkrsw/safe | tests/typing_tests/TAJS_micro/test112.js | 910 | var g = new Array(1,2,3,4,5,6)
//dumpObject(g)
var __result1 = g[0]; // for SAFE
var __expect1 = 1; // for SAFE
var __result2 = g[1]; // for SAFE
var __expect2 = 2; // for SAFE
var __result3 = g[2]; // for SAFE
var __expect3 = 3; // for SAFE
var __result4 = g[3]; // for SAFE
var __expect4 = 4; // for SAFE
var __result5 = g[4]; // for SAFE
var __expect5 = 5; // for SAFE
var __result6 = g[5]; // for SAFE
var __expect6 = 6; // for SAFE
var __result7 = g.length; // for SAFE
var __expect7 = 6; // for SAFE
var g = [1,2,4,6]
//dumpObject(g)
var __result8 = g[0]; // for SAFE
var __expect8 = 1; // for SAFE
var __result9 = g[1]; // for SAFE
var __expect9 = 2; // for SAFE
var __result10 = g[2]; // for SAFE
var __expect10 = 4; // for SAFE
var __result11 = g[3]; // for SAFE
var __expect11 = 6; // for SAFE
var __result12 = g.length; // for SAFE
var __expect12 = 4; // for SAFE
| bsd-3-clause |
pwz3n0/xenia | src/xenia/hid/input_system.cc | 4575 | /**
******************************************************************************
* Xenia : Xbox 360 Emulator Research Project *
******************************************************************************
* Copyright 2013 Ben Vanik. All rights reserved. *
* Released under the BSD license - see LICENSE in the root for more details. *
******************************************************************************
*/
#include "xenia/hid/input_system.h"
#include "xenia/cpu/processor.h"
#include "xenia/emulator.h"
#include "xenia/hid/hid_flags.h"
#include "xenia/hid/input_driver.h"
#include "xenia/profiling.h"
#include "xenia/hid/nop/nop_hid.h"
#if XE_PLATFORM_WIN32
#include "xenia/hid/winkey/winkey_hid.h"
#include "xenia/hid/xinput/xinput_hid.h"
#endif // WIN32
namespace xe {
namespace hid {
std::unique_ptr<InputSystem> InputSystem::Create(Emulator* emulator) {
auto input_system = std::make_unique<InputSystem>(emulator);
if (FLAGS_hid.compare("nop") == 0) {
input_system->AddDriver(xe::hid::nop::Create(input_system.get()));
#if XE_PLATFORM_WIN32
} else if (FLAGS_hid.compare("winkey") == 0) {
input_system->AddDriver(xe::hid::winkey::Create(input_system.get()));
} else if (FLAGS_hid.compare("xinput") == 0) {
input_system->AddDriver(xe::hid::xinput::Create(input_system.get()));
#endif // WIN32
} else {
// Create all available.
bool any_created = false;
// NOTE: in any mode we create as many as we can, falling back to nop.
#if XE_PLATFORM_WIN32
auto xinput_driver = xe::hid::xinput::Create(input_system.get());
if (xinput_driver) {
input_system->AddDriver(std::move(xinput_driver));
any_created = true;
}
auto winkey_driver = xe::hid::winkey::Create(input_system.get());
if (winkey_driver) {
input_system->AddDriver(std::move(winkey_driver));
any_created = true;
}
#endif // WIN32
// Fallback to nop if none created.
if (!any_created) {
input_system->AddDriver(xe::hid::nop::Create(input_system.get()));
}
}
return input_system;
}
InputSystem::InputSystem(Emulator* emulator)
: emulator_(emulator), memory_(emulator->memory()) {}
InputSystem::~InputSystem() = default;
X_STATUS InputSystem::Setup() {
processor_ = emulator_->processor();
return X_STATUS_SUCCESS;
}
void InputSystem::AddDriver(std::unique_ptr<InputDriver> driver) {
drivers_.push_back(std::move(driver));
}
X_RESULT InputSystem::GetCapabilities(uint32_t user_index, uint32_t flags,
X_INPUT_CAPABILITIES* out_caps) {
SCOPE_profile_cpu_f("hid");
bool any_connected = false;
for (auto& driver : drivers_) {
X_RESULT result = driver->GetCapabilities(user_index, flags, out_caps);
if (result != X_ERROR_DEVICE_NOT_CONNECTED) {
any_connected = true;
}
if (result == X_ERROR_SUCCESS) {
return result;
}
}
return any_connected ? X_ERROR_EMPTY : X_ERROR_DEVICE_NOT_CONNECTED;
}
X_RESULT InputSystem::GetState(uint32_t user_index, X_INPUT_STATE* out_state) {
SCOPE_profile_cpu_f("hid");
bool any_connected = false;
for (auto& driver : drivers_) {
X_RESULT result = driver->GetState(user_index, out_state);
if (result != X_ERROR_DEVICE_NOT_CONNECTED) {
any_connected = true;
}
if (result == X_ERROR_SUCCESS) {
return result;
}
}
return any_connected ? X_ERROR_EMPTY : X_ERROR_DEVICE_NOT_CONNECTED;
}
X_RESULT InputSystem::SetState(uint32_t user_index,
X_INPUT_VIBRATION* vibration) {
SCOPE_profile_cpu_f("hid");
bool any_connected = false;
for (auto& driver : drivers_) {
X_RESULT result = driver->SetState(user_index, vibration);
if (result != X_ERROR_DEVICE_NOT_CONNECTED) {
any_connected = true;
}
if (result == X_ERROR_SUCCESS) {
return result;
}
}
return any_connected ? X_ERROR_EMPTY : X_ERROR_DEVICE_NOT_CONNECTED;
}
X_RESULT InputSystem::GetKeystroke(uint32_t user_index, uint32_t flags,
X_INPUT_KEYSTROKE* out_keystroke) {
SCOPE_profile_cpu_f("hid");
bool any_connected = false;
for (auto& driver : drivers_) {
X_RESULT result = driver->GetKeystroke(user_index, flags, out_keystroke);
if (result != X_ERROR_DEVICE_NOT_CONNECTED) {
any_connected = true;
}
if (result == X_ERROR_SUCCESS) {
return result;
}
}
return any_connected ? X_ERROR_EMPTY : X_ERROR_DEVICE_NOT_CONNECTED;
}
} // namespace hid
} // namespace xe
| bsd-3-clause |
ChromeDevTools/devtools-frontend | node_modules/ramda/es/of.js | 587 | import _curry1 from "./internal/_curry1.js";
import _of from "./internal/_of.js";
/**
* Returns a singleton array containing the value provided.
*
* Note this `of` is different from the ES6 `of`; See
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/of
*
* @func
* @memberOf R
* @since v0.3.0
* @category Function
* @sig a -> [a]
* @param {*} x any value
* @return {Array} An array wrapping `x`.
* @example
*
* R.of(null); //=> [null]
* R.of([42]); //=> [[42]]
*/
var of =
/*#__PURE__*/
_curry1(_of);
export default of; | bsd-3-clause |
endlessm/chromium-browser | v8/src/builtins/x64/builtins-x64.cc | 133194 | // Copyright 2012 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#if V8_TARGET_ARCH_X64
#include "src/api/api-arguments.h"
#include "src/base/bits-iterator.h"
#include "src/base/iterator.h"
#include "src/codegen/code-factory.h"
// For interpreter_entry_return_pc_offset. TODO(jkummerow): Drop.
#include "src/codegen/macro-assembler-inl.h"
#include "src/codegen/register-configuration.h"
#include "src/codegen/x64/assembler-x64.h"
#include "src/deoptimizer/deoptimizer.h"
#include "src/execution/frame-constants.h"
#include "src/execution/frames.h"
#include "src/heap/heap-inl.h"
#include "src/logging/counters.h"
#include "src/objects/cell.h"
#include "src/objects/debug-objects.h"
#include "src/objects/foreign.h"
#include "src/objects/heap-number.h"
#include "src/objects/js-generator.h"
#include "src/objects/objects-inl.h"
#include "src/objects/smi.h"
#include "src/wasm/baseline/liftoff-assembler-defs.h"
#include "src/wasm/wasm-linkage.h"
#include "src/wasm/wasm-objects.h"
namespace v8 {
namespace internal {
#define __ ACCESS_MASM(masm)
void Builtins::Generate_Adaptor(MacroAssembler* masm, Address address) {
__ LoadAddress(kJavaScriptCallExtraArg1Register,
ExternalReference::Create(address));
__ Jump(BUILTIN_CODE(masm->isolate(), AdaptorWithBuiltinExitFrame),
RelocInfo::CODE_TARGET);
}
static void GenerateTailCallToReturnedCode(MacroAssembler* masm,
Runtime::FunctionId function_id) {
// ----------- S t a t e -------------
// -- rdx : new target (preserved for callee)
// -- rdi : target function (preserved for callee)
// -----------------------------------
{
FrameScope scope(masm, StackFrame::INTERNAL);
// Push a copy of the target function and the new target.
__ Push(rdi);
__ Push(rdx);
// Function is also the parameter to the runtime call.
__ Push(rdi);
__ CallRuntime(function_id, 1);
__ movq(rcx, rax);
// Restore target function and new target.
__ Pop(rdx);
__ Pop(rdi);
}
static_assert(kJavaScriptCallCodeStartRegister == rcx, "ABI mismatch");
__ JumpCodeObject(rcx);
}
namespace {
enum StackLimitKind { kInterruptStackLimit, kRealStackLimit };
Operand StackLimitAsOperand(MacroAssembler* masm, StackLimitKind kind) {
DCHECK(masm->root_array_available());
Isolate* isolate = masm->isolate();
ExternalReference limit =
kind == StackLimitKind::kRealStackLimit
? ExternalReference::address_of_real_jslimit(isolate)
: ExternalReference::address_of_jslimit(isolate);
DCHECK(TurboAssembler::IsAddressableThroughRootRegister(isolate, limit));
intptr_t offset =
TurboAssembler::RootRegisterOffsetForExternalReference(isolate, limit);
CHECK(is_int32(offset));
return Operand(kRootRegister, static_cast<int32_t>(offset));
}
void Generate_StackOverflowCheck(
MacroAssembler* masm, Register num_args, Register scratch,
Label* stack_overflow,
Label::Distance stack_overflow_distance = Label::kFar) {
// Check the stack for overflow. We are not trying to catch
// interruptions (e.g. debug break and preemption) here, so the "real stack
// limit" is checked.
__ movq(kScratchRegister,
StackLimitAsOperand(masm, StackLimitKind::kRealStackLimit));
__ movq(scratch, rsp);
// Make scratch the space we have left. The stack might already be overflowed
// here which will cause scratch to become negative.
__ subq(scratch, kScratchRegister);
__ sarq(scratch, Immediate(kSystemPointerSizeLog2));
// Check if the arguments will overflow the stack.
__ cmpq(scratch, num_args);
// Signed comparison.
__ j(less_equal, stack_overflow, stack_overflow_distance);
}
void Generate_JSBuiltinsConstructStubHelper(MacroAssembler* masm) {
// ----------- S t a t e -------------
// -- rax: number of arguments
// -- rdi: constructor function
// -- rdx: new target
// -- rsi: context
// -----------------------------------
Label stack_overflow;
Generate_StackOverflowCheck(masm, rax, rcx, &stack_overflow, Label::kFar);
// Enter a construct frame.
{
FrameScope scope(masm, StackFrame::CONSTRUCT);
// Preserve the incoming parameters on the stack.
__ SmiTag(rcx, rax);
__ Push(rsi);
__ Push(rcx);
#ifdef V8_REVERSE_JSARGS
// Set up pointer to first argument (skip receiver).
__ leaq(rbx, Operand(rbp, StandardFrameConstants::kCallerSPOffset +
kSystemPointerSize));
// Copy arguments to the expression stack.
__ PushArray(rbx, rax, rcx);
// The receiver for the builtin/api call.
__ PushRoot(RootIndex::kTheHoleValue);
#else
// The receiver for the builtin/api call.
__ PushRoot(RootIndex::kTheHoleValue);
// Set up pointer to last argument.
__ leaq(rbx, Operand(rbp, StandardFrameConstants::kCallerSPOffset));
// Copy arguments to the expression stack.
__ PushArray(rbx, rax, rcx);
#endif
// Call the function.
// rax: number of arguments (untagged)
// rdi: constructor function
// rdx: new target
__ InvokeFunction(rdi, rdx, rax, CALL_FUNCTION);
// Restore context from the frame.
__ movq(rsi, Operand(rbp, ConstructFrameConstants::kContextOffset));
// Restore smi-tagged arguments count from the frame.
__ movq(rbx, Operand(rbp, ConstructFrameConstants::kLengthOffset));
// Leave construct frame.
}
// Remove caller arguments from the stack and return.
__ PopReturnAddressTo(rcx);
SmiIndex index = masm->SmiToIndex(rbx, rbx, kSystemPointerSizeLog2);
__ leaq(rsp, Operand(rsp, index.reg, index.scale, 1 * kSystemPointerSize));
__ PushReturnAddressFrom(rcx);
__ ret(0);
__ bind(&stack_overflow);
{
FrameScope scope(masm, StackFrame::INTERNAL);
__ CallRuntime(Runtime::kThrowStackOverflow);
__ int3(); // This should be unreachable.
}
}
} // namespace
// The construct stub for ES5 constructor functions and ES6 class constructors.
void Builtins::Generate_JSConstructStubGeneric(MacroAssembler* masm) {
// ----------- S t a t e -------------
// -- rax: number of arguments (untagged)
// -- rdi: constructor function
// -- rdx: new target
// -- rsi: context
// -- sp[...]: constructor arguments
// -----------------------------------
// Enter a construct frame.
{
FrameScope scope(masm, StackFrame::CONSTRUCT);
Label post_instantiation_deopt_entry, not_create_implicit_receiver;
// Preserve the incoming parameters on the stack.
__ SmiTag(rcx, rax);
__ Push(rsi);
__ Push(rcx);
__ Push(rdi);
__ PushRoot(RootIndex::kTheHoleValue);
__ Push(rdx);
// ----------- S t a t e -------------
// -- sp[0*kSystemPointerSize]: new target
// -- sp[1*kSystemPointerSize]: padding
// -- rdi and sp[2*kSystemPointerSize]: constructor function
// -- sp[3*kSystemPointerSize]: argument count
// -- sp[4*kSystemPointerSize]: context
// -----------------------------------
__ LoadTaggedPointerField(
rbx, FieldOperand(rdi, JSFunction::kSharedFunctionInfoOffset));
__ movl(rbx, FieldOperand(rbx, SharedFunctionInfo::kFlagsOffset));
__ DecodeField<SharedFunctionInfo::FunctionKindBits>(rbx);
__ JumpIfIsInRange(rbx, kDefaultDerivedConstructor, kDerivedConstructor,
¬_create_implicit_receiver, Label::kNear);
// If not derived class constructor: Allocate the new receiver object.
__ IncrementCounter(masm->isolate()->counters()->constructed_objects(), 1);
__ Call(BUILTIN_CODE(masm->isolate(), FastNewObject),
RelocInfo::CODE_TARGET);
__ jmp(&post_instantiation_deopt_entry, Label::kNear);
// Else: use TheHoleValue as receiver for constructor call
__ bind(¬_create_implicit_receiver);
__ LoadRoot(rax, RootIndex::kTheHoleValue);
// ----------- S t a t e -------------
// -- rax implicit receiver
// -- Slot 4 / sp[0*kSystemPointerSize] new target
// -- Slot 3 / sp[1*kSystemPointerSize] padding
// -- Slot 2 / sp[2*kSystemPointerSize] constructor function
// -- Slot 1 / sp[3*kSystemPointerSize] number of arguments (tagged)
// -- Slot 0 / sp[4*kSystemPointerSize] context
// -----------------------------------
// Deoptimizer enters here.
masm->isolate()->heap()->SetConstructStubCreateDeoptPCOffset(
masm->pc_offset());
__ bind(&post_instantiation_deopt_entry);
// Restore new target.
__ Pop(rdx);
// Push the allocated receiver to the stack.
__ Push(rax);
#ifdef V8_REVERSE_JSARGS
// We need two copies because we may have to return the original one
// and the calling conventions dictate that the called function pops the
// receiver. The second copy is pushed after the arguments, we saved in r8
// since rax needs to store the number of arguments before
// InvokingFunction.
__ movq(r8, rax);
// Set up pointer to first argument (skip receiver).
__ leaq(rbx, Operand(rbp, StandardFrameConstants::kCallerSPOffset +
kSystemPointerSize));
#else
// We need two copies because we may have to return the original one
// and the calling conventions dictate that the called function pops the
// receiver.
__ Push(rax);
// Set up pointer to last argument.
__ leaq(rbx, Operand(rbp, StandardFrameConstants::kCallerSPOffset));
#endif
// Restore constructor function and argument count.
__ movq(rdi, Operand(rbp, ConstructFrameConstants::kConstructorOffset));
__ SmiUntag(rax, Operand(rbp, ConstructFrameConstants::kLengthOffset));
// Check if we have enough stack space to push all arguments.
// Argument count in rax. Clobbers rcx.
Label enough_stack_space, stack_overflow;
Generate_StackOverflowCheck(masm, rax, rcx, &stack_overflow, Label::kNear);
__ jmp(&enough_stack_space, Label::kNear);
__ bind(&stack_overflow);
// Restore context from the frame.
__ movq(rsi, Operand(rbp, ConstructFrameConstants::kContextOffset));
__ CallRuntime(Runtime::kThrowStackOverflow);
// This should be unreachable.
__ int3();
__ bind(&enough_stack_space);
// Copy arguments to the expression stack.
__ PushArray(rbx, rax, rcx);
#ifdef V8_REVERSE_JSARGS
// Push implicit receiver.
__ Push(r8);
#endif
// Call the function.
__ InvokeFunction(rdi, rdx, rax, CALL_FUNCTION);
// ----------- S t a t e -------------
// -- rax constructor result
// -- sp[0*kSystemPointerSize] implicit receiver
// -- sp[1*kSystemPointerSize] padding
// -- sp[2*kSystemPointerSize] constructor function
// -- sp[3*kSystemPointerSize] number of arguments
// -- sp[4*kSystemPointerSize] context
// -----------------------------------
// Store offset of return address for deoptimizer.
masm->isolate()->heap()->SetConstructStubInvokeDeoptPCOffset(
masm->pc_offset());
// Restore context from the frame.
__ movq(rsi, Operand(rbp, ConstructFrameConstants::kContextOffset));
// If the result is an object (in the ECMA sense), we should get rid
// of the receiver and use the result; see ECMA-262 section 13.2.2-7
// on page 74.
Label use_receiver, do_throw, leave_frame;
// If the result is undefined, we jump out to using the implicit receiver.
__ JumpIfRoot(rax, RootIndex::kUndefinedValue, &use_receiver, Label::kNear);
// Otherwise we do a smi check and fall through to check if the return value
// is a valid receiver.
// If the result is a smi, it is *not* an object in the ECMA sense.
__ JumpIfSmi(rax, &use_receiver, Label::kNear);
// If the type of the result (stored in its map) is less than
// FIRST_JS_RECEIVER_TYPE, it is not an object in the ECMA sense.
STATIC_ASSERT(LAST_JS_RECEIVER_TYPE == LAST_TYPE);
__ CmpObjectType(rax, FIRST_JS_RECEIVER_TYPE, rcx);
__ j(above_equal, &leave_frame, Label::kNear);
__ jmp(&use_receiver, Label::kNear);
__ bind(&do_throw);
__ CallRuntime(Runtime::kThrowConstructorReturnedNonObject);
// Throw away the result of the constructor invocation and use the
// on-stack receiver as the result.
__ bind(&use_receiver);
__ movq(rax, Operand(rsp, 0 * kSystemPointerSize));
__ JumpIfRoot(rax, RootIndex::kTheHoleValue, &do_throw, Label::kNear);
__ bind(&leave_frame);
// Restore the arguments count.
__ movq(rbx, Operand(rbp, ConstructFrameConstants::kLengthOffset));
// Leave construct frame.
}
// Remove caller arguments from the stack and return.
__ PopReturnAddressTo(rcx);
SmiIndex index = masm->SmiToIndex(rbx, rbx, kSystemPointerSizeLog2);
__ leaq(rsp, Operand(rsp, index.reg, index.scale, 1 * kSystemPointerSize));
__ PushReturnAddressFrom(rcx);
__ ret(0);
}
void Builtins::Generate_JSBuiltinsConstructStub(MacroAssembler* masm) {
Generate_JSBuiltinsConstructStubHelper(masm);
}
void Builtins::Generate_ConstructedNonConstructable(MacroAssembler* masm) {
FrameScope scope(masm, StackFrame::INTERNAL);
__ Push(rdi);
__ CallRuntime(Runtime::kThrowConstructedNonConstructable);
}
namespace {
// Called with the native C calling convention. The corresponding function
// signature is either:
// using JSEntryFunction = GeneratedCode<Address(
// Address root_register_value, Address new_target, Address target,
// Address receiver, intptr_t argc, Address** argv)>;
// or
// using JSEntryFunction = GeneratedCode<Address(
// Address root_register_value, MicrotaskQueue* microtask_queue)>;
void Generate_JSEntryVariant(MacroAssembler* masm, StackFrame::Type type,
Builtins::Name entry_trampoline) {
Label invoke, handler_entry, exit;
Label not_outermost_js, not_outermost_js_2;
{ // NOLINT. Scope block confuses linter.
NoRootArrayScope uninitialized_root_register(masm);
// Set up frame.
__ pushq(rbp);
__ movq(rbp, rsp);
// Push the stack frame type.
__ Push(Immediate(StackFrame::TypeToMarker(type)));
// Reserve a slot for the context. It is filled after the root register has
// been set up.
__ AllocateStackSpace(kSystemPointerSize);
// Save callee-saved registers (X64/X32/Win64 calling conventions).
__ pushq(r12);
__ pushq(r13);
__ pushq(r14);
__ pushq(r15);
#ifdef V8_TARGET_OS_WIN
__ pushq(rdi); // Only callee save in Win64 ABI, argument in AMD64 ABI.
__ pushq(rsi); // Only callee save in Win64 ABI, argument in AMD64 ABI.
#endif
__ pushq(rbx);
#ifdef V8_TARGET_OS_WIN
// On Win64 XMM6-XMM15 are callee-save.
__ AllocateStackSpace(EntryFrameConstants::kXMMRegistersBlockSize);
__ movdqu(Operand(rsp, EntryFrameConstants::kXMMRegisterSize * 0), xmm6);
__ movdqu(Operand(rsp, EntryFrameConstants::kXMMRegisterSize * 1), xmm7);
__ movdqu(Operand(rsp, EntryFrameConstants::kXMMRegisterSize * 2), xmm8);
__ movdqu(Operand(rsp, EntryFrameConstants::kXMMRegisterSize * 3), xmm9);
__ movdqu(Operand(rsp, EntryFrameConstants::kXMMRegisterSize * 4), xmm10);
__ movdqu(Operand(rsp, EntryFrameConstants::kXMMRegisterSize * 5), xmm11);
__ movdqu(Operand(rsp, EntryFrameConstants::kXMMRegisterSize * 6), xmm12);
__ movdqu(Operand(rsp, EntryFrameConstants::kXMMRegisterSize * 7), xmm13);
__ movdqu(Operand(rsp, EntryFrameConstants::kXMMRegisterSize * 8), xmm14);
__ movdqu(Operand(rsp, EntryFrameConstants::kXMMRegisterSize * 9), xmm15);
STATIC_ASSERT(EntryFrameConstants::kCalleeSaveXMMRegisters == 10);
STATIC_ASSERT(EntryFrameConstants::kXMMRegistersBlockSize ==
EntryFrameConstants::kXMMRegisterSize *
EntryFrameConstants::kCalleeSaveXMMRegisters);
#endif
// Initialize the root register.
// C calling convention. The first argument is passed in arg_reg_1.
__ movq(kRootRegister, arg_reg_1);
}
// Save copies of the top frame descriptor on the stack.
ExternalReference c_entry_fp = ExternalReference::Create(
IsolateAddressId::kCEntryFPAddress, masm->isolate());
{
Operand c_entry_fp_operand = masm->ExternalReferenceAsOperand(c_entry_fp);
__ Push(c_entry_fp_operand);
}
// Store the context address in the previously-reserved slot.
ExternalReference context_address = ExternalReference::Create(
IsolateAddressId::kContextAddress, masm->isolate());
__ Load(kScratchRegister, context_address);
static constexpr int kOffsetToContextSlot = -2 * kSystemPointerSize;
__ movq(Operand(rbp, kOffsetToContextSlot), kScratchRegister);
// If this is the outermost JS call, set js_entry_sp value.
ExternalReference js_entry_sp = ExternalReference::Create(
IsolateAddressId::kJSEntrySPAddress, masm->isolate());
__ Load(rax, js_entry_sp);
__ testq(rax, rax);
__ j(not_zero, ¬_outermost_js);
__ Push(Immediate(StackFrame::OUTERMOST_JSENTRY_FRAME));
__ movq(rax, rbp);
__ Store(js_entry_sp, rax);
Label cont;
__ jmp(&cont);
__ bind(¬_outermost_js);
__ Push(Immediate(StackFrame::INNER_JSENTRY_FRAME));
__ bind(&cont);
// Jump to a faked try block that does the invoke, with a faked catch
// block that sets the pending exception.
__ jmp(&invoke);
__ bind(&handler_entry);
// Store the current pc as the handler offset. It's used later to create the
// handler table.
masm->isolate()->builtins()->SetJSEntryHandlerOffset(handler_entry.pos());
// Caught exception: Store result (exception) in the pending exception
// field in the JSEnv and return a failure sentinel.
ExternalReference pending_exception = ExternalReference::Create(
IsolateAddressId::kPendingExceptionAddress, masm->isolate());
__ Store(pending_exception, rax);
__ LoadRoot(rax, RootIndex::kException);
__ jmp(&exit);
// Invoke: Link this frame into the handler chain.
__ bind(&invoke);
__ PushStackHandler();
// Invoke the function by calling through JS entry trampoline builtin and
// pop the faked function when we return.
Handle<Code> trampoline_code =
masm->isolate()->builtins()->builtin_handle(entry_trampoline);
__ Call(trampoline_code, RelocInfo::CODE_TARGET);
// Unlink this frame from the handler chain.
__ PopStackHandler();
__ bind(&exit);
// Check if the current stack frame is marked as the outermost JS frame.
__ Pop(rbx);
__ cmpq(rbx, Immediate(StackFrame::OUTERMOST_JSENTRY_FRAME));
__ j(not_equal, ¬_outermost_js_2);
__ Move(kScratchRegister, js_entry_sp);
__ movq(Operand(kScratchRegister, 0), Immediate(0));
__ bind(¬_outermost_js_2);
// Restore the top frame descriptor from the stack.
{
Operand c_entry_fp_operand = masm->ExternalReferenceAsOperand(c_entry_fp);
__ Pop(c_entry_fp_operand);
}
// Restore callee-saved registers (X64 conventions).
#ifdef V8_TARGET_OS_WIN
// On Win64 XMM6-XMM15 are callee-save
__ movdqu(xmm6, Operand(rsp, EntryFrameConstants::kXMMRegisterSize * 0));
__ movdqu(xmm7, Operand(rsp, EntryFrameConstants::kXMMRegisterSize * 1));
__ movdqu(xmm8, Operand(rsp, EntryFrameConstants::kXMMRegisterSize * 2));
__ movdqu(xmm9, Operand(rsp, EntryFrameConstants::kXMMRegisterSize * 3));
__ movdqu(xmm10, Operand(rsp, EntryFrameConstants::kXMMRegisterSize * 4));
__ movdqu(xmm11, Operand(rsp, EntryFrameConstants::kXMMRegisterSize * 5));
__ movdqu(xmm12, Operand(rsp, EntryFrameConstants::kXMMRegisterSize * 6));
__ movdqu(xmm13, Operand(rsp, EntryFrameConstants::kXMMRegisterSize * 7));
__ movdqu(xmm14, Operand(rsp, EntryFrameConstants::kXMMRegisterSize * 8));
__ movdqu(xmm15, Operand(rsp, EntryFrameConstants::kXMMRegisterSize * 9));
__ addq(rsp, Immediate(EntryFrameConstants::kXMMRegistersBlockSize));
#endif
__ popq(rbx);
#ifdef V8_TARGET_OS_WIN
// Callee save on in Win64 ABI, arguments/volatile in AMD64 ABI.
__ popq(rsi);
__ popq(rdi);
#endif
__ popq(r15);
__ popq(r14);
__ popq(r13);
__ popq(r12);
__ addq(rsp, Immediate(2 * kSystemPointerSize)); // remove markers
// Restore frame pointer and return.
__ popq(rbp);
__ ret(0);
}
} // namespace
void Builtins::Generate_JSEntry(MacroAssembler* masm) {
Generate_JSEntryVariant(masm, StackFrame::ENTRY,
Builtins::kJSEntryTrampoline);
}
void Builtins::Generate_JSConstructEntry(MacroAssembler* masm) {
Generate_JSEntryVariant(masm, StackFrame::CONSTRUCT_ENTRY,
Builtins::kJSConstructEntryTrampoline);
}
void Builtins::Generate_JSRunMicrotasksEntry(MacroAssembler* masm) {
Generate_JSEntryVariant(masm, StackFrame::ENTRY,
Builtins::kRunMicrotasksTrampoline);
}
static void Generate_JSEntryTrampolineHelper(MacroAssembler* masm,
bool is_construct) {
// Expects six C++ function parameters.
// - Address root_register_value
// - Address new_target (tagged Object pointer)
// - Address function (tagged JSFunction pointer)
// - Address receiver (tagged Object pointer)
// - intptr_t argc
// - Address** argv (pointer to array of tagged Object pointers)
// (see Handle::Invoke in execution.cc).
// Open a C++ scope for the FrameScope.
{
// Platform specific argument handling. After this, the stack contains
// an internal frame and the pushed function and receiver, and
// register rax and rbx holds the argument count and argument array,
// while rdi holds the function pointer, rsi the context, and rdx the
// new.target.
// MSVC parameters in:
// rcx : root_register_value
// rdx : new_target
// r8 : function
// r9 : receiver
// [rsp+0x20] : argc
// [rsp+0x28] : argv
//
// GCC parameters in:
// rdi : root_register_value
// rsi : new_target
// rdx : function
// rcx : receiver
// r8 : argc
// r9 : argv
__ movq(rdi, arg_reg_3);
__ Move(rdx, arg_reg_2);
// rdi : function
// rdx : new_target
// Clear the context before we push it when entering the internal frame.
__ Set(rsi, 0);
// Enter an internal frame.
FrameScope scope(masm, StackFrame::INTERNAL);
// Setup the context (we need to use the caller context from the isolate).
ExternalReference context_address = ExternalReference::Create(
IsolateAddressId::kContextAddress, masm->isolate());
__ movq(rsi, masm->ExternalReferenceAsOperand(context_address));
// Push the function onto the stack.
__ Push(rdi);
#ifndef V8_REVERSE_JSARGS
// Push the receiver onto the stack.
__ Push(arg_reg_4);
#endif
#ifdef V8_TARGET_OS_WIN
// Load the previous frame pointer to access C arguments on stack
__ movq(kScratchRegister, Operand(rbp, 0));
// Load the number of arguments and setup pointer to the arguments.
__ movq(rax, Operand(kScratchRegister, EntryFrameConstants::kArgcOffset));
__ movq(rbx, Operand(kScratchRegister, EntryFrameConstants::kArgvOffset));
#else // V8_TARGET_OS_WIN
// Load the number of arguments and setup pointer to the arguments.
__ movq(rax, r8);
__ movq(rbx, r9);
#ifdef V8_REVERSE_JSARGS
__ movq(r9, arg_reg_4); // Temporarily saving the receiver.
#endif
#endif // V8_TARGET_OS_WIN
// Current stack contents if V8_REVERSE_JSARGS:
// [rsp + kSystemPointerSize] : Internal frame
// [rsp] : function
// Current stack contents if not V8_REVERSE_JSARGS:
// [rsp + 2 * kSystemPointerSize] : Internal frame
// [rsp + kSystemPointerSize] : function
// [rsp] : receiver
// Current register contents:
// rax : argc
// rbx : argv
// rsi : context
// rdi : function
// rdx : new.target
// r9 : receiver, if V8_REVERSE_JSARGS
// Check if we have enough stack space to push all arguments.
// Argument count in rax. Clobbers rcx.
Label enough_stack_space, stack_overflow;
Generate_StackOverflowCheck(masm, rax, rcx, &stack_overflow, Label::kNear);
__ jmp(&enough_stack_space, Label::kNear);
__ bind(&stack_overflow);
__ CallRuntime(Runtime::kThrowStackOverflow);
// This should be unreachable.
__ int3();
__ bind(&enough_stack_space);
// Copy arguments to the stack in a loop.
// Register rbx points to array of pointers to handle locations.
// Push the values of these handles.
#ifdef V8_REVERSE_JSARGS
Label loop, entry;
__ movq(rcx, rax);
__ jmp(&entry, Label::kNear);
__ bind(&loop);
__ movq(kScratchRegister, Operand(rbx, rcx, times_system_pointer_size, 0));
__ Push(Operand(kScratchRegister, 0)); // dereference handle
__ bind(&entry);
__ decq(rcx);
__ j(greater_equal, &loop, Label::kNear);
// Push the receiver.
__ Push(r9);
#else
Label loop, entry;
__ Set(rcx, 0); // Set loop variable to 0.
__ jmp(&entry, Label::kNear);
__ bind(&loop);
__ movq(kScratchRegister, Operand(rbx, rcx, times_system_pointer_size, 0));
__ Push(Operand(kScratchRegister, 0)); // dereference handle
__ addq(rcx, Immediate(1));
__ bind(&entry);
__ cmpq(rcx, rax);
__ j(not_equal, &loop, Label::kNear);
#endif
// Invoke the builtin code.
Handle<Code> builtin = is_construct
? BUILTIN_CODE(masm->isolate(), Construct)
: masm->isolate()->builtins()->Call();
__ Call(builtin, RelocInfo::CODE_TARGET);
// Exit the internal frame. Notice that this also removes the empty
// context and the function left on the stack by the code
// invocation.
}
__ ret(0);
}
void Builtins::Generate_JSEntryTrampoline(MacroAssembler* masm) {
Generate_JSEntryTrampolineHelper(masm, false);
}
void Builtins::Generate_JSConstructEntryTrampoline(MacroAssembler* masm) {
Generate_JSEntryTrampolineHelper(masm, true);
}
void Builtins::Generate_RunMicrotasksTrampoline(MacroAssembler* masm) {
// arg_reg_2: microtask_queue
__ movq(RunMicrotasksDescriptor::MicrotaskQueueRegister(), arg_reg_2);
__ Jump(BUILTIN_CODE(masm->isolate(), RunMicrotasks), RelocInfo::CODE_TARGET);
}
static void GetSharedFunctionInfoBytecode(MacroAssembler* masm,
Register sfi_data,
Register scratch1) {
Label done;
__ CmpObjectType(sfi_data, INTERPRETER_DATA_TYPE, scratch1);
__ j(not_equal, &done, Label::kNear);
__ LoadTaggedPointerField(
sfi_data, FieldOperand(sfi_data, InterpreterData::kBytecodeArrayOffset));
__ bind(&done);
}
// static
void Builtins::Generate_ResumeGeneratorTrampoline(MacroAssembler* masm) {
// ----------- S t a t e -------------
// -- rax : the value to pass to the generator
// -- rdx : the JSGeneratorObject to resume
// -- rsp[0] : return address
// -----------------------------------
__ AssertGeneratorObject(rdx);
// Store input value into generator object.
__ StoreTaggedField(
FieldOperand(rdx, JSGeneratorObject::kInputOrDebugPosOffset), rax);
__ RecordWriteField(rdx, JSGeneratorObject::kInputOrDebugPosOffset, rax, rcx,
kDontSaveFPRegs);
Register decompr_scratch1 = COMPRESS_POINTERS_BOOL ? r11 : no_reg;
// Load suspended function and context.
__ LoadTaggedPointerField(
rdi, FieldOperand(rdx, JSGeneratorObject::kFunctionOffset));
__ LoadTaggedPointerField(rsi, FieldOperand(rdi, JSFunction::kContextOffset));
// Flood function if we are stepping.
Label prepare_step_in_if_stepping, prepare_step_in_suspended_generator;
Label stepping_prepared;
ExternalReference debug_hook =
ExternalReference::debug_hook_on_function_call_address(masm->isolate());
Operand debug_hook_operand = masm->ExternalReferenceAsOperand(debug_hook);
__ cmpb(debug_hook_operand, Immediate(0));
__ j(not_equal, &prepare_step_in_if_stepping);
// Flood function if we need to continue stepping in the suspended generator.
ExternalReference debug_suspended_generator =
ExternalReference::debug_suspended_generator_address(masm->isolate());
Operand debug_suspended_generator_operand =
masm->ExternalReferenceAsOperand(debug_suspended_generator);
__ cmpq(rdx, debug_suspended_generator_operand);
__ j(equal, &prepare_step_in_suspended_generator);
__ bind(&stepping_prepared);
// Check the stack for overflow. We are not trying to catch interruptions
// (i.e. debug break and preemption) here, so check the "real stack limit".
Label stack_overflow;
__ cmpq(rsp, StackLimitAsOperand(masm, StackLimitKind::kRealStackLimit));
__ j(below, &stack_overflow);
// Pop return address.
__ PopReturnAddressTo(rax);
#ifndef V8_REVERSE_JSARGS
// Push receiver.
__ PushTaggedPointerField(
FieldOperand(rdx, JSGeneratorObject::kReceiverOffset), decompr_scratch1);
#endif
// ----------- S t a t e -------------
// -- rax : return address
// -- rdx : the JSGeneratorObject to resume
// -- rdi : generator function
// -- rsi : generator context
// -- rsp[0] : generator receiver, if V8_REVERSE_JSARGS is not set
// -----------------------------------
// Copy the function arguments from the generator object's register file.
__ LoadTaggedPointerField(
rcx, FieldOperand(rdi, JSFunction::kSharedFunctionInfoOffset));
__ movzxwq(
rcx, FieldOperand(rcx, SharedFunctionInfo::kFormalParameterCountOffset));
__ LoadTaggedPointerField(
rbx, FieldOperand(rdx, JSGeneratorObject::kParametersAndRegistersOffset));
{
#ifdef V8_REVERSE_JSARGS
{
Label done_loop, loop;
__ movq(r9, rcx);
__ bind(&loop);
__ decq(r9);
__ j(less, &done_loop, Label::kNear);
__ PushTaggedAnyField(
FieldOperand(rbx, r9, times_tagged_size, FixedArray::kHeaderSize),
decompr_scratch1);
__ jmp(&loop);
__ bind(&done_loop);
}
// Push the receiver.
__ PushTaggedPointerField(
FieldOperand(rdx, JSGeneratorObject::kReceiverOffset),
decompr_scratch1);
#else
Label done_loop, loop;
__ Set(r9, 0);
__ bind(&loop);
__ cmpl(r9, rcx);
__ j(greater_equal, &done_loop, Label::kNear);
__ PushTaggedAnyField(
FieldOperand(rbx, r9, times_tagged_size, FixedArray::kHeaderSize),
decompr_scratch1);
__ addl(r9, Immediate(1));
__ jmp(&loop);
__ bind(&done_loop);
#endif
}
// Underlying function needs to have bytecode available.
if (FLAG_debug_code) {
__ LoadTaggedPointerField(
rcx, FieldOperand(rdi, JSFunction::kSharedFunctionInfoOffset));
__ LoadTaggedPointerField(
rcx, FieldOperand(rcx, SharedFunctionInfo::kFunctionDataOffset));
GetSharedFunctionInfoBytecode(masm, rcx, kScratchRegister);
__ CmpObjectType(rcx, BYTECODE_ARRAY_TYPE, rcx);
__ Assert(equal, AbortReason::kMissingBytecodeArray);
}
// Resume (Ignition/TurboFan) generator object.
{
__ PushReturnAddressFrom(rax);
__ LoadTaggedPointerField(
rax, FieldOperand(rdi, JSFunction::kSharedFunctionInfoOffset));
__ movzxwq(rax, FieldOperand(
rax, SharedFunctionInfo::kFormalParameterCountOffset));
// We abuse new.target both to indicate that this is a resume call and to
// pass in the generator object. In ordinary calls, new.target is always
// undefined because generator functions are non-constructable.
static_assert(kJavaScriptCallCodeStartRegister == rcx, "ABI mismatch");
__ LoadTaggedPointerField(rcx, FieldOperand(rdi, JSFunction::kCodeOffset));
__ JumpCodeObject(rcx);
}
__ bind(&prepare_step_in_if_stepping);
{
FrameScope scope(masm, StackFrame::INTERNAL);
__ Push(rdx);
__ Push(rdi);
// Push hole as receiver since we do not use it for stepping.
__ PushRoot(RootIndex::kTheHoleValue);
__ CallRuntime(Runtime::kDebugOnFunctionCall);
__ Pop(rdx);
__ LoadTaggedPointerField(
rdi, FieldOperand(rdx, JSGeneratorObject::kFunctionOffset));
}
__ jmp(&stepping_prepared);
__ bind(&prepare_step_in_suspended_generator);
{
FrameScope scope(masm, StackFrame::INTERNAL);
__ Push(rdx);
__ CallRuntime(Runtime::kDebugPrepareStepInSuspendedGenerator);
__ Pop(rdx);
__ LoadTaggedPointerField(
rdi, FieldOperand(rdx, JSGeneratorObject::kFunctionOffset));
}
__ jmp(&stepping_prepared);
__ bind(&stack_overflow);
{
FrameScope scope(masm, StackFrame::INTERNAL);
__ CallRuntime(Runtime::kThrowStackOverflow);
__ int3(); // This should be unreachable.
}
}
// TODO(juliana): if we remove the code below then we don't need all
// the parameters.
static void ReplaceClosureCodeWithOptimizedCode(MacroAssembler* masm,
Register optimized_code,
Register closure,
Register scratch1,
Register scratch2) {
// Store the optimized code in the closure.
__ StoreTaggedField(FieldOperand(closure, JSFunction::kCodeOffset),
optimized_code);
__ movq(scratch1, optimized_code); // Write barrier clobbers scratch1 below.
__ RecordWriteField(closure, JSFunction::kCodeOffset, scratch1, scratch2,
kDontSaveFPRegs, OMIT_REMEMBERED_SET, OMIT_SMI_CHECK);
}
static void LeaveInterpreterFrame(MacroAssembler* masm, Register scratch1,
Register scratch2) {
Register args_count = scratch1;
Register return_pc = scratch2;
// Get the arguments + receiver count.
__ movq(args_count,
Operand(rbp, InterpreterFrameConstants::kBytecodeArrayFromFp));
__ movl(args_count,
FieldOperand(args_count, BytecodeArray::kParameterSizeOffset));
// Leave the frame (also dropping the register file).
__ leave();
// Drop receiver + arguments.
__ PopReturnAddressTo(return_pc);
__ addq(rsp, args_count);
__ PushReturnAddressFrom(return_pc);
}
// Tail-call |function_id| if |smi_entry| == |marker|
static void TailCallRuntimeIfMarkerEquals(MacroAssembler* masm,
Register smi_entry,
OptimizationMarker marker,
Runtime::FunctionId function_id) {
Label no_match;
__ SmiCompare(smi_entry, Smi::FromEnum(marker));
__ j(not_equal, &no_match);
GenerateTailCallToReturnedCode(masm, function_id);
__ bind(&no_match);
}
static void MaybeOptimizeCode(MacroAssembler* masm, Register feedback_vector,
Register optimization_marker) {
// ----------- S t a t e -------------
// -- rdx : new target (preserved for callee if needed, and caller)
// -- rdi : target function (preserved for callee if needed, and caller)
// -- feedback vector (preserved for caller if needed)
// -- optimization_marker : a Smi containing a non-zero optimization marker.
// -----------------------------------
DCHECK(!AreAliased(feedback_vector, rdx, rdi, optimization_marker));
// TODO(v8:8394): The logging of first execution will break if
// feedback vectors are not allocated. We need to find a different way of
// logging these events if required.
TailCallRuntimeIfMarkerEquals(masm, optimization_marker,
OptimizationMarker::kLogFirstExecution,
Runtime::kFunctionFirstExecution);
TailCallRuntimeIfMarkerEquals(masm, optimization_marker,
OptimizationMarker::kCompileOptimized,
Runtime::kCompileOptimized_NotConcurrent);
TailCallRuntimeIfMarkerEquals(masm, optimization_marker,
OptimizationMarker::kCompileOptimizedConcurrent,
Runtime::kCompileOptimized_Concurrent);
// Otherwise, the marker is InOptimizationQueue, so fall through hoping
// that an interrupt will eventually update the slot with optimized code.
if (FLAG_debug_code) {
__ SmiCompare(optimization_marker,
Smi::FromEnum(OptimizationMarker::kInOptimizationQueue));
__ Assert(equal, AbortReason::kExpectedOptimizationSentinel);
}
}
static void TailCallOptimizedCodeSlot(MacroAssembler* masm,
Register optimized_code_entry,
Register scratch1, Register scratch2) {
// ----------- S t a t e -------------
// -- rdx : new target (preserved for callee if needed, and caller)
// -- rdi : target function (preserved for callee if needed, and caller)
// -----------------------------------
Register closure = rdi;
// Check if the optimized code is marked for deopt. If it is, call the
// runtime to clear it.
Label found_deoptimized_code;
__ LoadTaggedPointerField(
scratch1,
FieldOperand(optimized_code_entry, Code::kCodeDataContainerOffset));
__ testl(FieldOperand(scratch1, CodeDataContainer::kKindSpecificFlagsOffset),
Immediate(1 << Code::kMarkedForDeoptimizationBit));
__ j(not_zero, &found_deoptimized_code);
// Optimized code is good, get it into the closure and link the closure into
// the optimized functions list, then tail call the optimized code.
ReplaceClosureCodeWithOptimizedCode(masm, optimized_code_entry, closure,
scratch1, scratch2);
static_assert(kJavaScriptCallCodeStartRegister == rcx, "ABI mismatch");
__ Move(rcx, optimized_code_entry);
__ JumpCodeObject(rcx);
// Optimized code slot contains deoptimized code, evict it and re-enter the
// closure's code.
__ bind(&found_deoptimized_code);
GenerateTailCallToReturnedCode(masm, Runtime::kEvictOptimizedCodeSlot);
}
// Advance the current bytecode offset. This simulates what all bytecode
// handlers do upon completion of the underlying operation. Will bail out to a
// label if the bytecode (without prefix) is a return bytecode. Will not advance
// the bytecode offset if the current bytecode is a JumpLoop, instead just
// re-executing the JumpLoop to jump to the correct bytecode.
static void AdvanceBytecodeOffsetOrReturn(MacroAssembler* masm,
Register bytecode_array,
Register bytecode_offset,
Register bytecode, Register scratch1,
Register scratch2, Label* if_return) {
Register bytecode_size_table = scratch1;
// The bytecode offset value will be increased by one in wide and extra wide
// cases. In the case of having a wide or extra wide JumpLoop bytecode, we
// will restore the original bytecode. In order to simplify the code, we have
// a backup of it.
Register original_bytecode_offset = scratch2;
DCHECK(!AreAliased(bytecode_array, bytecode_offset, bytecode,
bytecode_size_table, original_bytecode_offset));
__ movq(original_bytecode_offset, bytecode_offset);
__ Move(bytecode_size_table,
ExternalReference::bytecode_size_table_address());
// Check if the bytecode is a Wide or ExtraWide prefix bytecode.
Label process_bytecode, extra_wide;
STATIC_ASSERT(0 == static_cast<int>(interpreter::Bytecode::kWide));
STATIC_ASSERT(1 == static_cast<int>(interpreter::Bytecode::kExtraWide));
STATIC_ASSERT(2 == static_cast<int>(interpreter::Bytecode::kDebugBreakWide));
STATIC_ASSERT(3 ==
static_cast<int>(interpreter::Bytecode::kDebugBreakExtraWide));
__ cmpb(bytecode, Immediate(0x3));
__ j(above, &process_bytecode, Label::kNear);
// The code to load the next bytecode is common to both wide and extra wide.
// We can hoist them up here. incl has to happen before testb since it
// modifies the ZF flag.
__ incl(bytecode_offset);
__ testb(bytecode, Immediate(0x1));
__ movzxbq(bytecode, Operand(bytecode_array, bytecode_offset, times_1, 0));
__ j(not_equal, &extra_wide, Label::kNear);
// Update table to the wide scaled table.
__ addq(bytecode_size_table,
Immediate(kIntSize * interpreter::Bytecodes::kBytecodeCount));
__ jmp(&process_bytecode, Label::kNear);
__ bind(&extra_wide);
// Update table to the extra wide scaled table.
__ addq(bytecode_size_table,
Immediate(2 * kIntSize * interpreter::Bytecodes::kBytecodeCount));
__ bind(&process_bytecode);
// Bailout to the return label if this is a return bytecode.
#define JUMP_IF_EQUAL(NAME) \
__ cmpb(bytecode, \
Immediate(static_cast<int>(interpreter::Bytecode::k##NAME))); \
__ j(equal, if_return, Label::kFar);
RETURN_BYTECODE_LIST(JUMP_IF_EQUAL)
#undef JUMP_IF_EQUAL
// If this is a JumpLoop, re-execute it to perform the jump to the beginning
// of the loop.
Label end, not_jump_loop;
__ cmpb(bytecode,
Immediate(static_cast<int>(interpreter::Bytecode::kJumpLoop)));
__ j(not_equal, ¬_jump_loop, Label::kNear);
// We need to restore the original bytecode_offset since we might have
// increased it to skip the wide / extra-wide prefix bytecode.
__ movq(bytecode_offset, original_bytecode_offset);
__ jmp(&end, Label::kNear);
__ bind(¬_jump_loop);
// Otherwise, load the size of the current bytecode and advance the offset.
__ addl(bytecode_offset,
Operand(bytecode_size_table, bytecode, times_int_size, 0));
__ bind(&end);
}
// Generate code for entering a JS function with the interpreter.
// On entry to the function the receiver and arguments have been pushed on the
// stack left to right. The actual argument count matches the formal parameter
// count expected by the function.
//
// The live registers are:
// o rdi: the JS function object being called
// o rdx: the incoming new target or generator object
// o rsi: our context
// o rbp: the caller's frame pointer
// o rsp: stack pointer (pointing to return address)
//
// The function builds an interpreter frame. See InterpreterFrameConstants in
// frames.h for its layout.
void Builtins::Generate_InterpreterEntryTrampoline(MacroAssembler* masm) {
Register closure = rdi;
Register feedback_vector = rbx;
// Get the bytecode array from the function object and load it into
// kInterpreterBytecodeArrayRegister.
__ LoadTaggedPointerField(
rax, FieldOperand(closure, JSFunction::kSharedFunctionInfoOffset));
__ LoadTaggedPointerField(
kInterpreterBytecodeArrayRegister,
FieldOperand(rax, SharedFunctionInfo::kFunctionDataOffset));
GetSharedFunctionInfoBytecode(masm, kInterpreterBytecodeArrayRegister,
kScratchRegister);
// The bytecode array could have been flushed from the shared function info,
// if so, call into CompileLazy.
Label compile_lazy;
__ CmpObjectType(kInterpreterBytecodeArrayRegister, BYTECODE_ARRAY_TYPE, rax);
__ j(not_equal, &compile_lazy);
// Load the feedback vector from the closure.
__ LoadTaggedPointerField(
feedback_vector, FieldOperand(closure, JSFunction::kFeedbackCellOffset));
__ LoadTaggedPointerField(feedback_vector,
FieldOperand(feedback_vector, Cell::kValueOffset));
Label push_stack_frame;
// Check if feedback vector is valid. If valid, check for optimized code
// and update invocation count. Otherwise, setup the stack frame.
__ LoadTaggedPointerField(
rcx, FieldOperand(feedback_vector, HeapObject::kMapOffset));
__ CmpInstanceType(rcx, FEEDBACK_VECTOR_TYPE);
__ j(not_equal, &push_stack_frame);
// Read off the optimized code slot in the feedback vector, and if there
// is optimized code or an optimization marker, call that instead.
Register optimized_code_entry = rcx;
__ LoadAnyTaggedField(
optimized_code_entry,
FieldOperand(feedback_vector,
FeedbackVector::kOptimizedCodeWeakOrSmiOffset));
// Check if the optimized code slot is not empty.
Label optimized_code_slot_not_empty;
__ Cmp(optimized_code_entry, Smi::FromEnum(OptimizationMarker::kNone));
__ j(not_equal, &optimized_code_slot_not_empty);
Label not_optimized;
__ bind(¬_optimized);
// Increment invocation count for the function.
__ incl(
FieldOperand(feedback_vector, FeedbackVector::kInvocationCountOffset));
// Open a frame scope to indicate that there is a frame on the stack. The
// MANUAL indicates that the scope shouldn't actually generate code to set up
// the frame (that is done below).
__ bind(&push_stack_frame);
FrameScope frame_scope(masm, StackFrame::MANUAL);
__ pushq(rbp); // Caller's frame pointer.
__ movq(rbp, rsp);
__ Push(rsi); // Callee's context.
__ Push(rdi); // Callee's JS function.
// Reset code age and the OSR arming. The OSR field and BytecodeAgeOffset are
// 8-bit fields next to each other, so we could just optimize by writing a
// 16-bit. These static asserts guard our assumption is valid.
STATIC_ASSERT(BytecodeArray::kBytecodeAgeOffset ==
BytecodeArray::kOsrNestingLevelOffset + kCharSize);
STATIC_ASSERT(BytecodeArray::kNoAgeBytecodeAge == 0);
__ movw(FieldOperand(kInterpreterBytecodeArrayRegister,
BytecodeArray::kOsrNestingLevelOffset),
Immediate(0));
// Load initial bytecode offset.
__ movq(kInterpreterBytecodeOffsetRegister,
Immediate(BytecodeArray::kHeaderSize - kHeapObjectTag));
// Push bytecode array and Smi tagged bytecode offset.
__ Push(kInterpreterBytecodeArrayRegister);
__ SmiTag(rcx, kInterpreterBytecodeOffsetRegister);
__ Push(rcx);
// Allocate the local and temporary register file on the stack.
Label stack_overflow;
{
// Load frame size from the BytecodeArray object.
__ movl(rcx, FieldOperand(kInterpreterBytecodeArrayRegister,
BytecodeArray::kFrameSizeOffset));
// Do a stack check to ensure we don't go over the limit.
__ movq(rax, rsp);
__ subq(rax, rcx);
__ cmpq(rax, StackLimitAsOperand(masm, StackLimitKind::kRealStackLimit));
__ j(below, &stack_overflow);
// If ok, push undefined as the initial value for all register file entries.
Label loop_header;
Label loop_check;
__ LoadRoot(kInterpreterAccumulatorRegister, RootIndex::kUndefinedValue);
__ j(always, &loop_check, Label::kNear);
__ bind(&loop_header);
// TODO(rmcilroy): Consider doing more than one push per loop iteration.
__ Push(kInterpreterAccumulatorRegister);
// Continue loop if not done.
__ bind(&loop_check);
__ subq(rcx, Immediate(kSystemPointerSize));
__ j(greater_equal, &loop_header, Label::kNear);
}
// If the bytecode array has a valid incoming new target or generator object
// register, initialize it with incoming value which was passed in rdx.
Label no_incoming_new_target_or_generator_register;
__ movsxlq(
rcx,
FieldOperand(kInterpreterBytecodeArrayRegister,
BytecodeArray::kIncomingNewTargetOrGeneratorRegisterOffset));
__ testl(rcx, rcx);
__ j(zero, &no_incoming_new_target_or_generator_register, Label::kNear);
__ movq(Operand(rbp, rcx, times_system_pointer_size, 0), rdx);
__ bind(&no_incoming_new_target_or_generator_register);
// Perform interrupt stack check.
// TODO(solanes): Merge with the real stack limit check above.
Label stack_check_interrupt, after_stack_check_interrupt;
__ cmpq(rsp, StackLimitAsOperand(masm, StackLimitKind::kInterruptStackLimit));
__ j(below, &stack_check_interrupt);
__ bind(&after_stack_check_interrupt);
// The accumulator is already loaded with undefined.
// Load the dispatch table into a register and dispatch to the bytecode
// handler at the current bytecode offset.
Label do_dispatch;
__ bind(&do_dispatch);
__ Move(
kInterpreterDispatchTableRegister,
ExternalReference::interpreter_dispatch_table_address(masm->isolate()));
__ movzxbq(r11, Operand(kInterpreterBytecodeArrayRegister,
kInterpreterBytecodeOffsetRegister, times_1, 0));
__ movq(kJavaScriptCallCodeStartRegister,
Operand(kInterpreterDispatchTableRegister, r11,
times_system_pointer_size, 0));
__ call(kJavaScriptCallCodeStartRegister);
masm->isolate()->heap()->SetInterpreterEntryReturnPCOffset(masm->pc_offset());
// Any returns to the entry trampoline are either due to the return bytecode
// or the interpreter tail calling a builtin and then a dispatch.
// Get bytecode array and bytecode offset from the stack frame.
__ movq(kInterpreterBytecodeArrayRegister,
Operand(rbp, InterpreterFrameConstants::kBytecodeArrayFromFp));
__ SmiUntag(kInterpreterBytecodeOffsetRegister,
Operand(rbp, InterpreterFrameConstants::kBytecodeOffsetFromFp));
// Either return, or advance to the next bytecode and dispatch.
Label do_return;
__ movzxbq(rbx, Operand(kInterpreterBytecodeArrayRegister,
kInterpreterBytecodeOffsetRegister, times_1, 0));
AdvanceBytecodeOffsetOrReturn(masm, kInterpreterBytecodeArrayRegister,
kInterpreterBytecodeOffsetRegister, rbx, rcx,
r11, &do_return);
__ jmp(&do_dispatch);
__ bind(&do_return);
// The return value is in rax.
LeaveInterpreterFrame(masm, rbx, rcx);
__ ret(0);
__ bind(&stack_check_interrupt);
// Modify the bytecode offset in the stack to be kFunctionEntryBytecodeOffset
// for the call to the StackGuard.
__ Move(Operand(rbp, InterpreterFrameConstants::kBytecodeOffsetFromFp),
Smi::FromInt(BytecodeArray::kHeaderSize - kHeapObjectTag +
kFunctionEntryBytecodeOffset));
__ CallRuntime(Runtime::kStackGuard);
// After the call, restore the bytecode array, bytecode offset and accumulator
// registers again. Also, restore the bytecode offset in the stack to its
// previous value.
__ movq(kInterpreterBytecodeArrayRegister,
Operand(rbp, InterpreterFrameConstants::kBytecodeArrayFromFp));
__ movq(kInterpreterBytecodeOffsetRegister,
Immediate(BytecodeArray::kHeaderSize - kHeapObjectTag));
__ LoadRoot(kInterpreterAccumulatorRegister, RootIndex::kUndefinedValue);
__ SmiTag(rcx, kInterpreterBytecodeArrayRegister);
__ movq(Operand(rbp, InterpreterFrameConstants::kBytecodeOffsetFromFp), rcx);
__ jmp(&after_stack_check_interrupt);
__ bind(&compile_lazy);
GenerateTailCallToReturnedCode(masm, Runtime::kCompileLazy);
__ int3(); // Should not return.
__ bind(&optimized_code_slot_not_empty);
Label maybe_has_optimized_code;
// Check if optimized code marker is actually a weak reference to the
// optimized code as opposed to an optimization marker.
__ JumpIfNotSmi(optimized_code_entry, &maybe_has_optimized_code);
MaybeOptimizeCode(masm, feedback_vector, optimized_code_entry);
// Fall through if there's no runnable optimized code.
__ jmp(¬_optimized);
__ bind(&maybe_has_optimized_code);
// Load code entry from the weak reference, if it was cleared, resume
// execution of unoptimized code.
__ LoadWeakValue(optimized_code_entry, ¬_optimized);
TailCallOptimizedCodeSlot(masm, optimized_code_entry, r11, r15);
__ bind(&stack_overflow);
__ CallRuntime(Runtime::kThrowStackOverflow);
__ int3(); // Should not return.
}
static void Generate_InterpreterPushArgs(MacroAssembler* masm,
Register num_args,
Register start_address,
Register scratch) {
// Find the argument with lowest address.
__ movq(scratch, num_args);
__ negq(scratch);
__ leaq(start_address,
Operand(start_address, scratch, times_system_pointer_size,
kSystemPointerSize));
// Push the arguments.
#ifdef V8_REVERSE_JSARGS
__ PushArray(start_address, num_args, scratch,
TurboAssembler::PushArrayOrder::kReverse);
#else
__ PushArray(start_address, num_args, scratch);
#endif
}
// static
void Builtins::Generate_InterpreterPushArgsThenCallImpl(
MacroAssembler* masm, ConvertReceiverMode receiver_mode,
InterpreterPushArgsMode mode) {
DCHECK(mode != InterpreterPushArgsMode::kArrayFunction);
// ----------- S t a t e -------------
// -- rax : the number of arguments (not including the receiver)
// -- rbx : the address of the first argument to be pushed. Subsequent
// arguments should be consecutive above this, in the same order as
// they are to be pushed onto the stack.
// -- rdi : the target to call (can be any Object).
// -----------------------------------
Label stack_overflow;
#ifdef V8_REVERSE_JSARGS
if (mode == InterpreterPushArgsMode::kWithFinalSpread) {
// The spread argument should not be pushed.
__ decl(rax);
}
#endif
__ leal(rcx, Operand(rax, 1)); // Add one for receiver.
// Add a stack check before pushing arguments.
Generate_StackOverflowCheck(masm, rcx, rdx, &stack_overflow);
// Pop return address to allow tail-call after pushing arguments.
__ PopReturnAddressTo(kScratchRegister);
#ifdef V8_REVERSE_JSARGS
if (receiver_mode == ConvertReceiverMode::kNullOrUndefined) {
// Don't copy receiver.
__ decq(rcx);
}
// rbx and rdx will be modified.
Generate_InterpreterPushArgs(masm, rcx, rbx, rdx);
// Push "undefined" as the receiver arg if we need to.
if (receiver_mode == ConvertReceiverMode::kNullOrUndefined) {
__ PushRoot(RootIndex::kUndefinedValue);
}
if (mode == InterpreterPushArgsMode::kWithFinalSpread) {
// Pass the spread in the register rbx.
// rbx already points to the penultime argument, the spread
// is below that.
__ movq(rbx, Operand(rbx, -kSystemPointerSize));
}
#else
// Push "undefined" as the receiver arg if we need to.
if (receiver_mode == ConvertReceiverMode::kNullOrUndefined) {
__ PushRoot(RootIndex::kUndefinedValue);
__ decl(rcx); // Subtract one for receiver.
}
// rbx and rdx will be modified.
Generate_InterpreterPushArgs(masm, rcx, rbx, rdx);
if (mode == InterpreterPushArgsMode::kWithFinalSpread) {
__ Pop(rbx); // Pass the spread in a register
__ decl(rax); // Subtract one for spread
}
#endif
// Call the target.
__ PushReturnAddressFrom(kScratchRegister); // Re-push return address.
if (mode == InterpreterPushArgsMode::kWithFinalSpread) {
__ Jump(BUILTIN_CODE(masm->isolate(), CallWithSpread),
RelocInfo::CODE_TARGET);
} else {
__ Jump(masm->isolate()->builtins()->Call(receiver_mode),
RelocInfo::CODE_TARGET);
}
// Throw stack overflow exception.
__ bind(&stack_overflow);
{
__ TailCallRuntime(Runtime::kThrowStackOverflow);
// This should be unreachable.
__ int3();
}
}
// static
void Builtins::Generate_InterpreterPushArgsThenConstructImpl(
MacroAssembler* masm, InterpreterPushArgsMode mode) {
// ----------- S t a t e -------------
// -- rax : the number of arguments (not including the receiver)
// -- rdx : the new target (either the same as the constructor or
// the JSFunction on which new was invoked initially)
// -- rdi : the constructor to call (can be any Object)
// -- rbx : the allocation site feedback if available, undefined otherwise
// -- rcx : the address of the first argument to be pushed. Subsequent
// arguments should be consecutive above this, in the same order as
// they are to be pushed onto the stack.
// -----------------------------------
Label stack_overflow;
// Add a stack check before pushing arguments.
Generate_StackOverflowCheck(masm, rax, r8, &stack_overflow);
// Pop return address to allow tail-call after pushing arguments.
__ PopReturnAddressTo(kScratchRegister);
#ifdef V8_REVERSE_JSARGS
if (mode == InterpreterPushArgsMode::kWithFinalSpread) {
// The spread argument should not be pushed.
__ decl(rax);
}
// rcx and r8 will be modified.
Generate_InterpreterPushArgs(masm, rax, rcx, r8);
// Push slot for the receiver to be constructed.
__ Push(Immediate(0));
#else
// Push slot for the receiver to be constructed.
__ Push(Immediate(0));
// rcx and r8 will be modified.
Generate_InterpreterPushArgs(masm, rax, rcx, r8);
#endif
if (mode == InterpreterPushArgsMode::kWithFinalSpread) {
#ifdef V8_REVERSE_JSARGS
// Pass the spread in the register rbx.
__ movq(rbx, Operand(rcx, -kSystemPointerSize));
#else
__ Pop(rbx); // Pass the spread in a register
__ decl(rax); // Subtract one for spread
#endif
// Push return address in preparation for the tail-call.
__ PushReturnAddressFrom(kScratchRegister);
} else {
__ PushReturnAddressFrom(kScratchRegister);
__ AssertUndefinedOrAllocationSite(rbx);
}
if (mode == InterpreterPushArgsMode::kArrayFunction) {
// Tail call to the array construct stub (still in the caller
// context at this point).
__ AssertFunction(rdi);
// Jump to the constructor function (rax, rbx, rdx passed on).
Handle<Code> code = BUILTIN_CODE(masm->isolate(), ArrayConstructorImpl);
__ Jump(code, RelocInfo::CODE_TARGET);
} else if (mode == InterpreterPushArgsMode::kWithFinalSpread) {
// Call the constructor (rax, rdx, rdi passed on).
__ Jump(BUILTIN_CODE(masm->isolate(), ConstructWithSpread),
RelocInfo::CODE_TARGET);
} else {
DCHECK_EQ(InterpreterPushArgsMode::kOther, mode);
// Call the constructor (rax, rdx, rdi passed on).
__ Jump(BUILTIN_CODE(masm->isolate(), Construct), RelocInfo::CODE_TARGET);
}
// Throw stack overflow exception.
__ bind(&stack_overflow);
{
__ TailCallRuntime(Runtime::kThrowStackOverflow);
// This should be unreachable.
__ int3();
}
}
static void Generate_InterpreterEnterBytecode(MacroAssembler* masm) {
// Set the return address to the correct point in the interpreter entry
// trampoline.
Label builtin_trampoline, trampoline_loaded;
Smi interpreter_entry_return_pc_offset(
masm->isolate()->heap()->interpreter_entry_return_pc_offset());
DCHECK_NE(interpreter_entry_return_pc_offset, Smi::zero());
// If the SFI function_data is an InterpreterData, the function will have a
// custom copy of the interpreter entry trampoline for profiling. If so,
// get the custom trampoline, otherwise grab the entry address of the global
// trampoline.
__ movq(rbx, Operand(rbp, StandardFrameConstants::kFunctionOffset));
__ LoadTaggedPointerField(
rbx, FieldOperand(rbx, JSFunction::kSharedFunctionInfoOffset));
__ LoadTaggedPointerField(
rbx, FieldOperand(rbx, SharedFunctionInfo::kFunctionDataOffset));
__ CmpObjectType(rbx, INTERPRETER_DATA_TYPE, kScratchRegister);
__ j(not_equal, &builtin_trampoline, Label::kNear);
__ LoadTaggedPointerField(
rbx, FieldOperand(rbx, InterpreterData::kInterpreterTrampolineOffset));
__ addq(rbx, Immediate(Code::kHeaderSize - kHeapObjectTag));
__ jmp(&trampoline_loaded, Label::kNear);
__ bind(&builtin_trampoline);
// TODO(jgruber): Replace this by a lookup in the builtin entry table.
__ movq(rbx,
__ ExternalReferenceAsOperand(
ExternalReference::
address_of_interpreter_entry_trampoline_instruction_start(
masm->isolate()),
kScratchRegister));
__ bind(&trampoline_loaded);
__ addq(rbx, Immediate(interpreter_entry_return_pc_offset.value()));
__ Push(rbx);
// Initialize dispatch table register.
__ Move(
kInterpreterDispatchTableRegister,
ExternalReference::interpreter_dispatch_table_address(masm->isolate()));
// Get the bytecode array pointer from the frame.
__ movq(kInterpreterBytecodeArrayRegister,
Operand(rbp, InterpreterFrameConstants::kBytecodeArrayFromFp));
if (FLAG_debug_code) {
// Check function data field is actually a BytecodeArray object.
__ AssertNotSmi(kInterpreterBytecodeArrayRegister);
__ CmpObjectType(kInterpreterBytecodeArrayRegister, BYTECODE_ARRAY_TYPE,
rbx);
__ Assert(
equal,
AbortReason::kFunctionDataShouldBeBytecodeArrayOnInterpreterEntry);
}
// Get the target bytecode offset from the frame.
__ SmiUntag(kInterpreterBytecodeOffsetRegister,
Operand(rbp, InterpreterFrameConstants::kBytecodeOffsetFromFp));
if (FLAG_debug_code) {
Label okay;
__ cmpq(kInterpreterBytecodeOffsetRegister,
Immediate(BytecodeArray::kHeaderSize - kHeapObjectTag));
__ j(greater_equal, &okay, Label::kNear);
__ int3();
__ bind(&okay);
}
// Dispatch to the target bytecode.
__ movzxbq(r11, Operand(kInterpreterBytecodeArrayRegister,
kInterpreterBytecodeOffsetRegister, times_1, 0));
__ movq(kJavaScriptCallCodeStartRegister,
Operand(kInterpreterDispatchTableRegister, r11,
times_system_pointer_size, 0));
__ jmp(kJavaScriptCallCodeStartRegister);
}
void Builtins::Generate_InterpreterEnterBytecodeAdvance(MacroAssembler* masm) {
// Get bytecode array and bytecode offset from the stack frame.
__ movq(kInterpreterBytecodeArrayRegister,
Operand(rbp, InterpreterFrameConstants::kBytecodeArrayFromFp));
__ SmiUntag(kInterpreterBytecodeOffsetRegister,
Operand(rbp, InterpreterFrameConstants::kBytecodeOffsetFromFp));
Label enter_bytecode, function_entry_bytecode;
__ cmpq(kInterpreterBytecodeOffsetRegister,
Immediate(BytecodeArray::kHeaderSize - kHeapObjectTag +
kFunctionEntryBytecodeOffset));
__ j(equal, &function_entry_bytecode);
// Load the current bytecode.
__ movzxbq(rbx, Operand(kInterpreterBytecodeArrayRegister,
kInterpreterBytecodeOffsetRegister, times_1, 0));
// Advance to the next bytecode.
Label if_return;
AdvanceBytecodeOffsetOrReturn(masm, kInterpreterBytecodeArrayRegister,
kInterpreterBytecodeOffsetRegister, rbx, rcx,
r11, &if_return);
__ bind(&enter_bytecode);
// Convert new bytecode offset to a Smi and save in the stackframe.
__ SmiTag(kInterpreterBytecodeOffsetRegister);
__ movq(Operand(rbp, InterpreterFrameConstants::kBytecodeOffsetFromFp),
kInterpreterBytecodeOffsetRegister);
Generate_InterpreterEnterBytecode(masm);
__ bind(&function_entry_bytecode);
// If the code deoptimizes during the implicit function entry stack interrupt
// check, it will have a bailout ID of kFunctionEntryBytecodeOffset, which is
// not a valid bytecode offset. Detect this case and advance to the first
// actual bytecode.
__ movq(kInterpreterBytecodeOffsetRegister,
Immediate(BytecodeArray::kHeaderSize - kHeapObjectTag));
__ jmp(&enter_bytecode);
// We should never take the if_return path.
__ bind(&if_return);
__ Abort(AbortReason::kInvalidBytecodeAdvance);
}
void Builtins::Generate_InterpreterEnterBytecodeDispatch(MacroAssembler* masm) {
Generate_InterpreterEnterBytecode(masm);
}
namespace {
void Generate_ContinueToBuiltinHelper(MacroAssembler* masm,
bool java_script_builtin,
bool with_result) {
const RegisterConfiguration* config(RegisterConfiguration::Default());
int allocatable_register_count = config->num_allocatable_general_registers();
if (with_result) {
// Overwrite the hole inserted by the deoptimizer with the return value from
// the LAZY deopt point.
__ movq(
Operand(rsp, config->num_allocatable_general_registers() *
kSystemPointerSize +
BuiltinContinuationFrameConstants::kFixedFrameSize),
rax);
}
for (int i = allocatable_register_count - 1; i >= 0; --i) {
int code = config->GetAllocatableGeneralCode(i);
__ popq(Register::from_code(code));
if (java_script_builtin && code == kJavaScriptCallArgCountRegister.code()) {
__ SmiUntag(Register::from_code(code));
}
}
__ movq(
rbp,
Operand(rsp, BuiltinContinuationFrameConstants::kFixedFrameSizeFromFp));
const int offsetToPC =
BuiltinContinuationFrameConstants::kFixedFrameSizeFromFp -
kSystemPointerSize;
__ popq(Operand(rsp, offsetToPC));
__ Drop(offsetToPC / kSystemPointerSize);
// Replace the builtin index Smi on the stack with the instruction start
// address of the builtin from the builtins table, and then Ret to this
// address
__ movq(kScratchRegister, Operand(rsp, 0));
__ movq(kScratchRegister,
__ EntryFromBuiltinIndexAsOperand(kScratchRegister));
__ movq(Operand(rsp, 0), kScratchRegister);
__ Ret();
}
} // namespace
void Builtins::Generate_ContinueToCodeStubBuiltin(MacroAssembler* masm) {
Generate_ContinueToBuiltinHelper(masm, false, false);
}
void Builtins::Generate_ContinueToCodeStubBuiltinWithResult(
MacroAssembler* masm) {
Generate_ContinueToBuiltinHelper(masm, false, true);
}
void Builtins::Generate_ContinueToJavaScriptBuiltin(MacroAssembler* masm) {
Generate_ContinueToBuiltinHelper(masm, true, false);
}
void Builtins::Generate_ContinueToJavaScriptBuiltinWithResult(
MacroAssembler* masm) {
Generate_ContinueToBuiltinHelper(masm, true, true);
}
void Builtins::Generate_NotifyDeoptimized(MacroAssembler* masm) {
// Enter an internal frame.
{
FrameScope scope(masm, StackFrame::INTERNAL);
__ CallRuntime(Runtime::kNotifyDeoptimized);
// Tear down internal frame.
}
DCHECK_EQ(kInterpreterAccumulatorRegister.code(), rax.code());
__ movq(rax, Operand(rsp, kPCOnStackSize));
__ ret(1 * kSystemPointerSize); // Remove rax.
}
// static
void Builtins::Generate_FunctionPrototypeApply(MacroAssembler* masm) {
// ----------- S t a t e -------------
// -- rax : argc
// -- rsp[0] : return address
// The order of args depends on V8_REVERSE_JSARGS
// -- args[0] : receiver
// -- args[1] : thisArg
// -- args[2] : argArray
// -----------------------------------
// 1. Load receiver into rdi, argArray into rbx (if present), remove all
// arguments from the stack (including the receiver), and push thisArg (if
// present) instead.
{
Label no_arg_array, no_this_arg;
StackArgumentsAccessor args(rax);
__ LoadRoot(rdx, RootIndex::kUndefinedValue);
__ movq(rbx, rdx);
__ movq(rdi, args[0]);
__ testq(rax, rax);
__ j(zero, &no_this_arg, Label::kNear);
{
__ movq(rdx, args[1]);
__ cmpq(rax, Immediate(1));
__ j(equal, &no_arg_array, Label::kNear);
__ movq(rbx, args[2]);
__ bind(&no_arg_array);
}
__ bind(&no_this_arg);
__ PopReturnAddressTo(rcx);
__ leaq(rsp,
Operand(rsp, rax, times_system_pointer_size, kSystemPointerSize));
__ Push(rdx);
__ PushReturnAddressFrom(rcx);
}
// ----------- S t a t e -------------
// -- rbx : argArray
// -- rdi : receiver
// -- rsp[0] : return address
// -- rsp[8] : thisArg
// -----------------------------------
// 2. We don't need to check explicitly for callable receiver here,
// since that's the first thing the Call/CallWithArrayLike builtins
// will do.
// 3. Tail call with no arguments if argArray is null or undefined.
Label no_arguments;
__ JumpIfRoot(rbx, RootIndex::kNullValue, &no_arguments, Label::kNear);
__ JumpIfRoot(rbx, RootIndex::kUndefinedValue, &no_arguments, Label::kNear);
// 4a. Apply the receiver to the given argArray.
__ Jump(BUILTIN_CODE(masm->isolate(), CallWithArrayLike),
RelocInfo::CODE_TARGET);
// 4b. The argArray is either null or undefined, so we tail call without any
// arguments to the receiver. Since we did not create a frame for
// Function.prototype.apply() yet, we use a normal Call builtin here.
__ bind(&no_arguments);
{
__ Set(rax, 0);
__ Jump(masm->isolate()->builtins()->Call(), RelocInfo::CODE_TARGET);
}
}
// static
void Builtins::Generate_FunctionPrototypeCall(MacroAssembler* masm) {
// Stack Layout:
// rsp[0] : Return address
// rsp[8] : Argument n
// rsp[16] : Argument n-1
// ...
// rsp[8 * n] : Argument 1
// rsp[8 * (n + 1)] : Argument 0 (receiver: callable to call)
// NOTE: The order of args are reversed if V8_REVERSE_JSARGS
// rax contains the number of arguments, n, not counting the receiver.
#ifdef V8_REVERSE_JSARGS
// 1. Get the callable to call (passed as receiver) from the stack.
{
StackArgumentsAccessor args(rax);
__ movq(rdi, args.GetReceiverOperand());
}
// 2. Save the return address and drop the callable.
__ PopReturnAddressTo(rbx);
__ Pop(kScratchRegister);
// 3. Make sure we have at least one argument.
{
Label done;
__ testq(rax, rax);
__ j(not_zero, &done, Label::kNear);
__ PushRoot(RootIndex::kUndefinedValue);
__ incq(rax);
__ bind(&done);
}
// 4. Push back the return address one slot down on the stack (overwriting the
// original callable), making the original first argument the new receiver.
__ PushReturnAddressFrom(rbx);
__ decq(rax); // One fewer argument (first argument is new receiver).
#else
// 1. Make sure we have at least one argument.
{
Label done;
__ testq(rax, rax);
__ j(not_zero, &done, Label::kNear);
__ PopReturnAddressTo(rbx);
__ PushRoot(RootIndex::kUndefinedValue);
__ PushReturnAddressFrom(rbx);
__ incq(rax);
__ bind(&done);
}
// 2. Get the callable to call (passed as receiver) from the stack.
{
StackArgumentsAccessor args(rax);
__ movq(rdi, args.GetReceiverOperand());
}
// 3. Shift arguments and return address one slot down on the stack
// (overwriting the original receiver). Adjust argument count to make
// the original first argument the new receiver.
{
Label loop;
__ movq(rcx, rax);
StackArgumentsAccessor args(rcx);
__ bind(&loop);
__ movq(rbx, args[1]);
__ movq(args[0], rbx);
__ decq(rcx);
__ j(not_zero, &loop); // While non-zero.
__ DropUnderReturnAddress(1, rbx); // Drop one slot under return address.
__ decq(rax); // One fewer argument (first argument is new receiver).
}
#endif
// 4. Call the callable.
// Since we did not create a frame for Function.prototype.call() yet,
// we use a normal Call builtin here.
__ Jump(masm->isolate()->builtins()->Call(), RelocInfo::CODE_TARGET);
}
void Builtins::Generate_ReflectApply(MacroAssembler* masm) {
// ----------- S t a t e -------------
// -- rax : argc
// -- rsp[0] : return address
// The order of args depends on V8_REVERSE_JSARGS
// -- args[0] : receiver
// -- args[1] : target
// -- args[2] : thisArgument
// -- args[3] : argumentsList
// -----------------------------------
// 1. Load target into rdi (if present), argumentsList into rbx (if present),
// remove all arguments from the stack (including the receiver), and push
// thisArgument (if present) instead.
{
Label done;
StackArgumentsAccessor args(rax);
__ LoadRoot(rdi, RootIndex::kUndefinedValue);
__ movq(rdx, rdi);
__ movq(rbx, rdi);
__ cmpq(rax, Immediate(1));
__ j(below, &done, Label::kNear);
__ movq(rdi, args[1]); // target
__ j(equal, &done, Label::kNear);
__ movq(rdx, args[2]); // thisArgument
__ cmpq(rax, Immediate(3));
__ j(below, &done, Label::kNear);
__ movq(rbx, args[3]); // argumentsList
__ bind(&done);
__ PopReturnAddressTo(rcx);
__ leaq(rsp,
Operand(rsp, rax, times_system_pointer_size, kSystemPointerSize));
__ Push(rdx);
__ PushReturnAddressFrom(rcx);
}
// ----------- S t a t e -------------
// -- rbx : argumentsList
// -- rdi : target
// -- rsp[0] : return address
// -- rsp[8] : thisArgument
// -----------------------------------
// 2. We don't need to check explicitly for callable target here,
// since that's the first thing the Call/CallWithArrayLike builtins
// will do.
// 3. Apply the target to the given argumentsList.
__ Jump(BUILTIN_CODE(masm->isolate(), CallWithArrayLike),
RelocInfo::CODE_TARGET);
}
void Builtins::Generate_ReflectConstruct(MacroAssembler* masm) {
// ----------- S t a t e -------------
// -- rax : argc
// -- rsp[0] : return address
// The order of args depends on V8_REVERSE_JSARGS
// -- args[0] : receiver
// -- args[1] : target
// -- args[2] : argumentsList
// -- args[3] : new.target (optional)
// -----------------------------------
// 1. Load target into rdi (if present), argumentsList into rbx (if present),
// new.target into rdx (if present, otherwise use target), remove all
// arguments from the stack (including the receiver), and push thisArgument
// (if present) instead.
{
Label done;
StackArgumentsAccessor args(rax);
__ LoadRoot(rdi, RootIndex::kUndefinedValue);
__ movq(rdx, rdi);
__ movq(rbx, rdi);
__ cmpq(rax, Immediate(1));
__ j(below, &done, Label::kNear);
__ movq(rdi, args[1]); // target
__ movq(rdx, rdi); // new.target defaults to target
__ j(equal, &done, Label::kNear);
__ movq(rbx, args[2]); // argumentsList
__ cmpq(rax, Immediate(3));
__ j(below, &done, Label::kNear);
__ movq(rdx, args[3]); // new.target
__ bind(&done);
__ PopReturnAddressTo(rcx);
__ leaq(rsp,
Operand(rsp, rax, times_system_pointer_size, kSystemPointerSize));
__ PushRoot(RootIndex::kUndefinedValue);
__ PushReturnAddressFrom(rcx);
}
// ----------- S t a t e -------------
// -- rbx : argumentsList
// -- rdx : new.target
// -- rdi : target
// -- rsp[0] : return address
// -- rsp[8] : receiver (undefined)
// -----------------------------------
// 2. We don't need to check explicitly for constructor target here,
// since that's the first thing the Construct/ConstructWithArrayLike
// builtins will do.
// 3. We don't need to check explicitly for constructor new.target here,
// since that's the second thing the Construct/ConstructWithArrayLike
// builtins will do.
// 4. Construct the target with the given new.target and argumentsList.
__ Jump(BUILTIN_CODE(masm->isolate(), ConstructWithArrayLike),
RelocInfo::CODE_TARGET);
}
static void EnterArgumentsAdaptorFrame(MacroAssembler* masm) {
__ pushq(rbp);
__ movq(rbp, rsp);
// Store the arguments adaptor context sentinel.
__ Push(Immediate(StackFrame::TypeToMarker(StackFrame::ARGUMENTS_ADAPTOR)));
// Push the function on the stack.
__ Push(rdi);
// Preserve the number of arguments on the stack. Must preserve rax,
// rbx and rcx because these registers are used when copying the
// arguments and the receiver.
__ SmiTag(r8, rax);
__ Push(r8);
__ Push(Immediate(0)); // Padding.
}
static void LeaveArgumentsAdaptorFrame(MacroAssembler* masm) {
// Retrieve the number of arguments from the stack. Number is a Smi.
__ movq(rbx, Operand(rbp, ArgumentsAdaptorFrameConstants::kLengthOffset));
// Leave the frame.
__ movq(rsp, rbp);
__ popq(rbp);
// Remove caller arguments from the stack.
__ PopReturnAddressTo(rcx);
SmiIndex index = masm->SmiToIndex(rbx, rbx, kSystemPointerSizeLog2);
__ leaq(rsp, Operand(rsp, index.reg, index.scale, 1 * kSystemPointerSize));
__ PushReturnAddressFrom(rcx);
}
void Builtins::Generate_ArgumentsAdaptorTrampoline(MacroAssembler* masm) {
// ----------- S t a t e -------------
// -- rax : actual number of arguments
// -- rbx : expected number of arguments
// -- rdx : new target (passed through to callee)
// -- rdi : function (passed through to callee)
// -----------------------------------
Label dont_adapt_arguments, stack_overflow, skip_adapt_arguments;
__ cmpq(rbx, Immediate(kDontAdaptArgumentsSentinel));
__ j(equal, &dont_adapt_arguments);
__ LoadTaggedPointerField(
rcx, FieldOperand(rdi, JSFunction::kSharedFunctionInfoOffset));
#ifndef V8_REVERSE_JSARGS
// This optimization is disabled when the arguments are reversed.
__ testl(
FieldOperand(rcx, SharedFunctionInfo::kFlagsOffset),
Immediate(SharedFunctionInfo::IsSafeToSkipArgumentsAdaptorBit::kMask));
__ j(not_zero, &skip_adapt_arguments);
#endif
// -------------------------------------------
// Adapt arguments.
// -------------------------------------------
{
EnterArgumentsAdaptorFrame(masm);
Generate_StackOverflowCheck(masm, rbx, rcx, &stack_overflow);
Label under_application, over_application, invoke;
__ cmpq(rax, rbx);
__ j(less, &under_application, Label::kNear);
// Enough parameters: Actual >= expected.
__ bind(&over_application);
{
// Copy receiver and all expected arguments.
const int offset = StandardFrameConstants::kCallerSPOffset;
#ifdef V8_REVERSE_JSARGS
__ leaq(r8, Operand(rbp, rbx, times_system_pointer_size, offset));
#else
__ leaq(r8, Operand(rbp, rax, times_system_pointer_size, offset));
#endif
__ Set(rax, -1); // account for receiver
Label copy;
__ bind(©);
__ incq(rax);
__ Push(Operand(r8, 0));
__ subq(r8, Immediate(kSystemPointerSize));
__ cmpq(rax, rbx);
__ j(less, ©);
__ jmp(&invoke, Label::kNear);
}
// Too few parameters: Actual < expected.
__ bind(&under_application);
{
#ifdef V8_REVERSE_JSARGS
// Fill remaining expected arguments with undefined values.
Label fill;
__ LoadRoot(kScratchRegister, RootIndex::kUndefinedValue);
__ movq(r8, rbx);
__ subq(r8, rax);
__ bind(&fill);
__ Push(kScratchRegister);
__ decq(r8);
__ j(greater, &fill);
// Copy receiver and all actual arguments.
const int offset = StandardFrameConstants::kCallerSPOffset;
__ leaq(r9, Operand(rbp, rax, times_system_pointer_size, offset));
__ Set(r8, -1); // account for receiver
Label copy;
__ bind(©);
__ incq(r8);
__ Push(Operand(r9, 0));
__ subq(r9, Immediate(kSystemPointerSize));
__ cmpq(r8, rax);
__ j(less, ©);
// Update actual number of arguments.
__ movq(rax, rbx);
#else // !V8_REVERSE_JSARGS
// Copy receiver and all actual arguments.
const int offset = StandardFrameConstants::kCallerSPOffset;
__ leaq(r9, Operand(rbp, rax, times_system_pointer_size, offset));
__ Set(r8, -1); // account for receiver
Label copy;
__ bind(©);
__ incq(r8);
__ Push(Operand(r9, 0));
__ subq(r9, Immediate(kSystemPointerSize));
__ cmpq(r8, rax);
__ j(less, ©);
// Fill remaining expected arguments with undefined values.
Label fill;
__ LoadRoot(kScratchRegister, RootIndex::kUndefinedValue);
__ bind(&fill);
__ incq(rax);
__ Push(kScratchRegister);
__ cmpq(rax, rbx);
__ j(less, &fill);
#endif // !V8_REVERSE_JSARGS
}
// Call the entry point.
__ bind(&invoke);
// rax : expected number of arguments
// rdx : new target (passed through to callee)
// rdi : function (passed through to callee)
static_assert(kJavaScriptCallCodeStartRegister == rcx, "ABI mismatch");
__ LoadTaggedPointerField(rcx, FieldOperand(rdi, JSFunction::kCodeOffset));
__ CallCodeObject(rcx);
// Store offset of return address for deoptimizer.
masm->isolate()->heap()->SetArgumentsAdaptorDeoptPCOffset(
masm->pc_offset());
// Leave frame and return.
LeaveArgumentsAdaptorFrame(masm);
__ ret(0);
}
// -------------------------------------------
// Skip adapt arguments.
// -------------------------------------------
__ bind(&skip_adapt_arguments);
{
// The callee cannot observe the actual arguments, so it's safe to just
// pass the expected arguments by massaging the stack appropriately. See
// http://bit.ly/v8-faster-calls-with-arguments-mismatch for details.
Label under_application, over_application, invoke;
__ PopReturnAddressTo(rcx);
__ cmpq(rax, rbx);
__ j(less, &under_application, Label::kNear);
__ bind(&over_application);
{
// Remove superfluous parameters from the stack.
__ xchgq(rax, rbx);
__ subq(rbx, rax);
__ leaq(rsp, Operand(rsp, rbx, times_system_pointer_size, 0));
__ jmp(&invoke, Label::kNear);
}
__ bind(&under_application);
{
// Fill remaining expected arguments with undefined values.
Label fill;
__ LoadRoot(kScratchRegister, RootIndex::kUndefinedValue);
__ bind(&fill);
__ incq(rax);
__ Push(kScratchRegister);
__ cmpq(rax, rbx);
__ j(less, &fill);
}
__ bind(&invoke);
__ PushReturnAddressFrom(rcx);
}
// -------------------------------------------
// Don't adapt arguments.
// -------------------------------------------
__ bind(&dont_adapt_arguments);
static_assert(kJavaScriptCallCodeStartRegister == rcx, "ABI mismatch");
__ LoadTaggedPointerField(rcx, FieldOperand(rdi, JSFunction::kCodeOffset));
__ JumpCodeObject(rcx);
__ bind(&stack_overflow);
{
FrameScope frame(masm, StackFrame::MANUAL);
__ CallRuntime(Runtime::kThrowStackOverflow);
__ int3();
}
}
// static
void Builtins::Generate_CallOrConstructVarargs(MacroAssembler* masm,
Handle<Code> code) {
// ----------- S t a t e -------------
// -- rdi : target
// -- rax : number of parameters on the stack (not including the receiver)
// -- rbx : arguments list (a FixedArray)
// -- rcx : len (number of elements to push from args)
// -- rdx : new.target (for [[Construct]])
// -- rsp[0] : return address
// -----------------------------------
Register scratch = r11;
if (masm->emit_debug_code()) {
// Allow rbx to be a FixedArray, or a FixedDoubleArray if rcx == 0.
Label ok, fail;
__ AssertNotSmi(rbx);
Register map = r9;
__ LoadTaggedPointerField(map, FieldOperand(rbx, HeapObject::kMapOffset));
__ CmpInstanceType(map, FIXED_ARRAY_TYPE);
__ j(equal, &ok);
__ CmpInstanceType(map, FIXED_DOUBLE_ARRAY_TYPE);
__ j(not_equal, &fail);
__ cmpl(rcx, Immediate(0));
__ j(equal, &ok);
// Fall through.
__ bind(&fail);
__ Abort(AbortReason::kOperandIsNotAFixedArray);
__ bind(&ok);
}
Label stack_overflow;
Generate_StackOverflowCheck(masm, rcx, r8, &stack_overflow, Label::kNear);
// Push additional arguments onto the stack.
#ifdef V8_REVERSE_JSARGS
// Move the arguments already in the stack,
// including the receiver and the return address.
{
Label copy, check;
Register src = r8, dest = rsp, num = r9, current = r11;
__ movq(src, rsp);
__ leaq(kScratchRegister, Operand(rcx, times_system_pointer_size, 0));
__ AllocateStackSpace(kScratchRegister);
__ leaq(num, Operand(rax, 2)); // Number of words to copy.
// +2 for receiver and return address.
__ Set(current, 0);
__ jmp(&check);
__ bind(©);
__ movq(kScratchRegister,
Operand(src, current, times_system_pointer_size, 0));
__ movq(Operand(dest, current, times_system_pointer_size, 0),
kScratchRegister);
__ incq(current);
__ bind(&check);
__ cmpq(current, num);
__ j(less, ©);
__ leaq(r8, Operand(rsp, num, times_system_pointer_size, 0));
}
// Copy the additional arguments onto the stack.
{
Register value = scratch;
Register src = rbx, dest = r8, num = rcx, current = r9;
__ Set(current, 0);
Label done, push, loop;
__ bind(&loop);
__ cmpl(current, num);
__ j(equal, &done, Label::kNear);
// Turn the hole into undefined as we go.
__ LoadAnyTaggedField(value, FieldOperand(src, current, times_tagged_size,
FixedArray::kHeaderSize));
__ CompareRoot(value, RootIndex::kTheHoleValue);
__ j(not_equal, &push, Label::kNear);
__ LoadRoot(value, RootIndex::kUndefinedValue);
__ bind(&push);
__ movq(Operand(dest, current, times_system_pointer_size, 0), value);
__ incl(current);
__ jmp(&loop);
__ bind(&done);
__ addq(rax, current);
}
#else // !V8_REVERSE_JSARGS
{
Register value = scratch;
__ PopReturnAddressTo(r8);
__ Set(r9, 0);
Label done, push, loop;
__ bind(&loop);
__ cmpl(r9, rcx);
__ j(equal, &done, Label::kNear);
// Turn the hole into undefined as we go.
__ LoadAnyTaggedField(value, FieldOperand(rbx, r9, times_tagged_size,
FixedArray::kHeaderSize));
__ CompareRoot(value, RootIndex::kTheHoleValue);
__ j(not_equal, &push, Label::kNear);
__ LoadRoot(value, RootIndex::kUndefinedValue);
__ bind(&push);
__ Push(value);
__ incl(r9);
__ jmp(&loop);
__ bind(&done);
__ PushReturnAddressFrom(r8);
__ addq(rax, r9);
}
#endif
// Tail-call to the actual Call or Construct builtin.
__ Jump(code, RelocInfo::CODE_TARGET);
__ bind(&stack_overflow);
__ TailCallRuntime(Runtime::kThrowStackOverflow);
}
// static
void Builtins::Generate_CallOrConstructForwardVarargs(MacroAssembler* masm,
CallOrConstructMode mode,
Handle<Code> code) {
// ----------- S t a t e -------------
// -- rax : the number of arguments (not including the receiver)
// -- rdx : the new target (for [[Construct]] calls)
// -- rdi : the target to call (can be any Object)
// -- rcx : start index (to support rest parameters)
// -----------------------------------
// Check if new.target has a [[Construct]] internal method.
if (mode == CallOrConstructMode::kConstruct) {
Label new_target_constructor, new_target_not_constructor;
__ JumpIfSmi(rdx, &new_target_not_constructor, Label::kNear);
__ LoadTaggedPointerField(rbx, FieldOperand(rdx, HeapObject::kMapOffset));
__ testb(FieldOperand(rbx, Map::kBitFieldOffset),
Immediate(Map::Bits1::IsConstructorBit::kMask));
__ j(not_zero, &new_target_constructor, Label::kNear);
__ bind(&new_target_not_constructor);
{
FrameScope scope(masm, StackFrame::MANUAL);
__ EnterFrame(StackFrame::INTERNAL);
__ Push(rdx);
__ CallRuntime(Runtime::kThrowNotConstructor);
}
__ bind(&new_target_constructor);
}
// Check if we have an arguments adaptor frame below the function frame.
Label arguments_adaptor, arguments_done;
__ movq(rbx, Operand(rbp, StandardFrameConstants::kCallerFPOffset));
__ cmpq(Operand(rbx, CommonFrameConstants::kContextOrFrameTypeOffset),
Immediate(StackFrame::TypeToMarker(StackFrame::ARGUMENTS_ADAPTOR)));
__ j(equal, &arguments_adaptor, Label::kNear);
{
__ movq(r8, Operand(rbp, StandardFrameConstants::kFunctionOffset));
__ LoadTaggedPointerField(
r8, FieldOperand(r8, JSFunction::kSharedFunctionInfoOffset));
__ movzxwq(
r8, FieldOperand(r8, SharedFunctionInfo::kFormalParameterCountOffset));
__ movq(rbx, rbp);
}
__ jmp(&arguments_done, Label::kNear);
__ bind(&arguments_adaptor);
{
__ SmiUntag(r8,
Operand(rbx, ArgumentsAdaptorFrameConstants::kLengthOffset));
}
__ bind(&arguments_done);
Label stack_done, stack_overflow;
__ subl(r8, rcx);
__ j(less_equal, &stack_done);
{
// Check for stack overflow.
Generate_StackOverflowCheck(masm, r8, rcx, &stack_overflow, Label::kNear);
// Forward the arguments from the caller frame.
{
Label loop;
__ addl(rax, r8);
__ PopReturnAddressTo(rcx);
__ bind(&loop);
{
__ decl(r8);
__ Push(Operand(rbx, r8, times_system_pointer_size,
kFPOnStackSize + kPCOnStackSize));
__ j(not_zero, &loop);
}
__ PushReturnAddressFrom(rcx);
}
}
__ jmp(&stack_done, Label::kNear);
__ bind(&stack_overflow);
__ TailCallRuntime(Runtime::kThrowStackOverflow);
__ bind(&stack_done);
// Tail-call to the {code} handler.
__ Jump(code, RelocInfo::CODE_TARGET);
}
// static
void Builtins::Generate_CallFunction(MacroAssembler* masm,
ConvertReceiverMode mode) {
// ----------- S t a t e -------------
// -- rax : the number of arguments (not including the receiver)
// -- rdi : the function to call (checked to be a JSFunction)
// -----------------------------------
StackArgumentsAccessor args(rax);
__ AssertFunction(rdi);
// ES6 section 9.2.1 [[Call]] ( thisArgument, argumentsList)
// Check that the function is not a "classConstructor".
Label class_constructor;
__ LoadTaggedPointerField(
rdx, FieldOperand(rdi, JSFunction::kSharedFunctionInfoOffset));
__ testl(FieldOperand(rdx, SharedFunctionInfo::kFlagsOffset),
Immediate(SharedFunctionInfo::IsClassConstructorBit::kMask));
__ j(not_zero, &class_constructor);
// ----------- S t a t e -------------
// -- rax : the number of arguments (not including the receiver)
// -- rdx : the shared function info.
// -- rdi : the function to call (checked to be a JSFunction)
// -----------------------------------
// Enter the context of the function; ToObject has to run in the function
// context, and we also need to take the global proxy from the function
// context in case of conversion.
__ LoadTaggedPointerField(rsi, FieldOperand(rdi, JSFunction::kContextOffset));
// We need to convert the receiver for non-native sloppy mode functions.
Label done_convert;
__ testl(FieldOperand(rdx, SharedFunctionInfo::kFlagsOffset),
Immediate(SharedFunctionInfo::IsNativeBit::kMask |
SharedFunctionInfo::IsStrictBit::kMask));
__ j(not_zero, &done_convert);
{
// ----------- S t a t e -------------
// -- rax : the number of arguments (not including the receiver)
// -- rdx : the shared function info.
// -- rdi : the function to call (checked to be a JSFunction)
// -- rsi : the function context.
// -----------------------------------
if (mode == ConvertReceiverMode::kNullOrUndefined) {
// Patch receiver to global proxy.
__ LoadGlobalProxy(rcx);
} else {
Label convert_to_object, convert_receiver;
__ movq(rcx, args.GetReceiverOperand());
__ JumpIfSmi(rcx, &convert_to_object, Label::kNear);
STATIC_ASSERT(LAST_JS_RECEIVER_TYPE == LAST_TYPE);
__ CmpObjectType(rcx, FIRST_JS_RECEIVER_TYPE, rbx);
__ j(above_equal, &done_convert);
if (mode != ConvertReceiverMode::kNotNullOrUndefined) {
Label convert_global_proxy;
__ JumpIfRoot(rcx, RootIndex::kUndefinedValue, &convert_global_proxy,
Label::kNear);
__ JumpIfNotRoot(rcx, RootIndex::kNullValue, &convert_to_object,
Label::kNear);
__ bind(&convert_global_proxy);
{
// Patch receiver to global proxy.
__ LoadGlobalProxy(rcx);
}
__ jmp(&convert_receiver);
}
__ bind(&convert_to_object);
{
// Convert receiver using ToObject.
// TODO(bmeurer): Inline the allocation here to avoid building the frame
// in the fast case? (fall back to AllocateInNewSpace?)
FrameScope scope(masm, StackFrame::INTERNAL);
__ SmiTag(rax);
__ Push(rax);
__ Push(rdi);
__ movq(rax, rcx);
__ Push(rsi);
__ Call(BUILTIN_CODE(masm->isolate(), ToObject),
RelocInfo::CODE_TARGET);
__ Pop(rsi);
__ movq(rcx, rax);
__ Pop(rdi);
__ Pop(rax);
__ SmiUntag(rax);
}
__ LoadTaggedPointerField(
rdx, FieldOperand(rdi, JSFunction::kSharedFunctionInfoOffset));
__ bind(&convert_receiver);
}
__ movq(args.GetReceiverOperand(), rcx);
}
__ bind(&done_convert);
// ----------- S t a t e -------------
// -- rax : the number of arguments (not including the receiver)
// -- rdx : the shared function info.
// -- rdi : the function to call (checked to be a JSFunction)
// -- rsi : the function context.
// -----------------------------------
__ movzxwq(
rbx, FieldOperand(rdx, SharedFunctionInfo::kFormalParameterCountOffset));
__ InvokeFunctionCode(rdi, no_reg, rbx, rax, JUMP_FUNCTION);
// The function is a "classConstructor", need to raise an exception.
__ bind(&class_constructor);
{
FrameScope frame(masm, StackFrame::INTERNAL);
__ Push(rdi);
__ CallRuntime(Runtime::kThrowConstructorNonCallableError);
}
}
namespace {
void Generate_PushBoundArguments(MacroAssembler* masm) {
// ----------- S t a t e -------------
// -- rax : the number of arguments (not including the receiver)
// -- rdx : new.target (only in case of [[Construct]])
// -- rdi : target (checked to be a JSBoundFunction)
// -----------------------------------
// Load [[BoundArguments]] into rcx and length of that into rbx.
Label no_bound_arguments;
__ LoadTaggedPointerField(
rcx, FieldOperand(rdi, JSBoundFunction::kBoundArgumentsOffset));
__ SmiUntagField(rbx, FieldOperand(rcx, FixedArray::kLengthOffset));
__ testl(rbx, rbx);
__ j(zero, &no_bound_arguments);
{
// ----------- S t a t e -------------
// -- rax : the number of arguments (not including the receiver)
// -- rdx : new.target (only in case of [[Construct]])
// -- rdi : target (checked to be a JSBoundFunction)
// -- rcx : the [[BoundArguments]] (implemented as FixedArray)
// -- rbx : the number of [[BoundArguments]] (checked to be non-zero)
// -----------------------------------
// TODO(victor): Use Generate_StackOverflowCheck here.
// Check the stack for overflow.
{
Label done;
__ shlq(rbx, Immediate(kSystemPointerSizeLog2));
__ movq(kScratchRegister, rsp);
__ subq(kScratchRegister, rbx);
// We are not trying to catch interruptions (i.e. debug break and
// preemption) here, so check the "real stack limit".
__ cmpq(kScratchRegister,
StackLimitAsOperand(masm, StackLimitKind::kRealStackLimit));
__ j(above_equal, &done, Label::kNear);
{
FrameScope scope(masm, StackFrame::MANUAL);
__ EnterFrame(StackFrame::INTERNAL);
__ CallRuntime(Runtime::kThrowStackOverflow);
}
__ bind(&done);
}
#ifdef V8_REVERSE_JSARGS
// Save Return Address and Receiver into registers.
__ Pop(r8);
__ Pop(r10);
// Push [[BoundArguments]] to the stack.
{
Label loop;
__ LoadTaggedPointerField(
rcx, FieldOperand(rdi, JSBoundFunction::kBoundArgumentsOffset));
__ SmiUntagField(rbx, FieldOperand(rcx, FixedArray::kLengthOffset));
__ addq(rax, rbx); // Adjust effective number of arguments.
__ bind(&loop);
// Instead of doing decl(rbx) here subtract kTaggedSize from the header
// offset in order to be able to move decl(rbx) right before the loop
// condition. This is necessary in order to avoid flags corruption by
// pointer decompression code.
__ LoadAnyTaggedField(
r12, FieldOperand(rcx, rbx, times_tagged_size,
FixedArray::kHeaderSize - kTaggedSize));
__ Push(r12);
__ decl(rbx);
__ j(greater, &loop);
}
// Recover Receiver and Return Address.
__ Push(r10);
__ Push(r8);
#else // !V8_REVERSE_JSARGS
// Reserve stack space for the [[BoundArguments]].
__ movq(kScratchRegister, rbx);
__ AllocateStackSpace(kScratchRegister);
// Adjust effective number of arguments to include return address.
__ incl(rax);
// Relocate arguments and return address down the stack.
{
Label loop;
__ Set(rcx, 0);
__ addq(rbx, rsp);
__ bind(&loop);
__ movq(kScratchRegister,
Operand(rbx, rcx, times_system_pointer_size, 0));
__ movq(Operand(rsp, rcx, times_system_pointer_size, 0),
kScratchRegister);
__ incl(rcx);
__ cmpl(rcx, rax);
__ j(less, &loop);
}
// Copy [[BoundArguments]] to the stack (below the arguments).
{
Label loop;
__ LoadTaggedPointerField(
rcx, FieldOperand(rdi, JSBoundFunction::kBoundArgumentsOffset));
__ SmiUntagField(rbx, FieldOperand(rcx, FixedArray::kLengthOffset));
__ bind(&loop);
// Instead of doing decl(rbx) here subtract kTaggedSize from the header
// offset in order be able to move decl(rbx) right before the loop
// condition. This is necessary in order to avoid flags corruption by
// pointer decompression code.
__ LoadAnyTaggedField(
r12, FieldOperand(rcx, rbx, times_tagged_size,
FixedArray::kHeaderSize - kTaggedSize));
__ movq(Operand(rsp, rax, times_system_pointer_size, 0), r12);
__ leal(rax, Operand(rax, 1));
__ decl(rbx);
__ j(greater, &loop);
}
// Adjust effective number of arguments (rax contains the number of
// arguments from the call plus return address plus the number of
// [[BoundArguments]]), so we need to subtract one for the return address.
__ decl(rax);
#endif // !V8_REVERSE_JSARGS
}
__ bind(&no_bound_arguments);
}
} // namespace
// static
void Builtins::Generate_CallBoundFunctionImpl(MacroAssembler* masm) {
// ----------- S t a t e -------------
// -- rax : the number of arguments (not including the receiver)
// -- rdi : the function to call (checked to be a JSBoundFunction)
// -----------------------------------
__ AssertBoundFunction(rdi);
// Patch the receiver to [[BoundThis]].
StackArgumentsAccessor args(rax);
__ LoadAnyTaggedField(rbx,
FieldOperand(rdi, JSBoundFunction::kBoundThisOffset));
__ movq(args.GetReceiverOperand(), rbx);
// Push the [[BoundArguments]] onto the stack.
Generate_PushBoundArguments(masm);
// Call the [[BoundTargetFunction]] via the Call builtin.
__ LoadTaggedPointerField(
rdi, FieldOperand(rdi, JSBoundFunction::kBoundTargetFunctionOffset));
__ Jump(BUILTIN_CODE(masm->isolate(), Call_ReceiverIsAny),
RelocInfo::CODE_TARGET);
}
// static
void Builtins::Generate_Call(MacroAssembler* masm, ConvertReceiverMode mode) {
// ----------- S t a t e -------------
// -- rax : the number of arguments (not including the receiver)
// -- rdi : the target to call (can be any Object)
// -----------------------------------
StackArgumentsAccessor args(rax);
Label non_callable;
__ JumpIfSmi(rdi, &non_callable);
__ CmpObjectType(rdi, JS_FUNCTION_TYPE, rcx);
__ Jump(masm->isolate()->builtins()->CallFunction(mode),
RelocInfo::CODE_TARGET, equal);
__ CmpInstanceType(rcx, JS_BOUND_FUNCTION_TYPE);
__ Jump(BUILTIN_CODE(masm->isolate(), CallBoundFunction),
RelocInfo::CODE_TARGET, equal);
// Check if target has a [[Call]] internal method.
__ testb(FieldOperand(rcx, Map::kBitFieldOffset),
Immediate(Map::Bits1::IsCallableBit::kMask));
__ j(zero, &non_callable, Label::kNear);
// Check if target is a proxy and call CallProxy external builtin
__ CmpInstanceType(rcx, JS_PROXY_TYPE);
__ Jump(BUILTIN_CODE(masm->isolate(), CallProxy), RelocInfo::CODE_TARGET,
equal);
// 2. Call to something else, which might have a [[Call]] internal method (if
// not we raise an exception).
// Overwrite the original receiver with the (original) target.
__ movq(args.GetReceiverOperand(), rdi);
// Let the "call_as_function_delegate" take care of the rest.
__ LoadNativeContextSlot(Context::CALL_AS_FUNCTION_DELEGATE_INDEX, rdi);
__ Jump(masm->isolate()->builtins()->CallFunction(
ConvertReceiverMode::kNotNullOrUndefined),
RelocInfo::CODE_TARGET);
// 3. Call to something that is not callable.
__ bind(&non_callable);
{
FrameScope scope(masm, StackFrame::INTERNAL);
__ Push(rdi);
__ CallRuntime(Runtime::kThrowCalledNonCallable);
}
}
// static
void Builtins::Generate_ConstructFunction(MacroAssembler* masm) {
// ----------- S t a t e -------------
// -- rax : the number of arguments (not including the receiver)
// -- rdx : the new target (checked to be a constructor)
// -- rdi : the constructor to call (checked to be a JSFunction)
// -----------------------------------
__ AssertConstructor(rdi);
__ AssertFunction(rdi);
// Calling convention for function specific ConstructStubs require
// rbx to contain either an AllocationSite or undefined.
__ LoadRoot(rbx, RootIndex::kUndefinedValue);
// Jump to JSBuiltinsConstructStub or JSConstructStubGeneric.
__ LoadTaggedPointerField(
rcx, FieldOperand(rdi, JSFunction::kSharedFunctionInfoOffset));
__ testl(FieldOperand(rcx, SharedFunctionInfo::kFlagsOffset),
Immediate(SharedFunctionInfo::ConstructAsBuiltinBit::kMask));
__ Jump(BUILTIN_CODE(masm->isolate(), JSBuiltinsConstructStub),
RelocInfo::CODE_TARGET, not_zero);
__ Jump(BUILTIN_CODE(masm->isolate(), JSConstructStubGeneric),
RelocInfo::CODE_TARGET);
}
// static
void Builtins::Generate_ConstructBoundFunction(MacroAssembler* masm) {
// ----------- S t a t e -------------
// -- rax : the number of arguments (not including the receiver)
// -- rdx : the new target (checked to be a constructor)
// -- rdi : the constructor to call (checked to be a JSBoundFunction)
// -----------------------------------
__ AssertConstructor(rdi);
__ AssertBoundFunction(rdi);
// Push the [[BoundArguments]] onto the stack.
Generate_PushBoundArguments(masm);
// Patch new.target to [[BoundTargetFunction]] if new.target equals target.
{
Label done;
__ cmpq(rdi, rdx);
__ j(not_equal, &done, Label::kNear);
__ LoadTaggedPointerField(
rdx, FieldOperand(rdi, JSBoundFunction::kBoundTargetFunctionOffset));
__ bind(&done);
}
// Construct the [[BoundTargetFunction]] via the Construct builtin.
__ LoadTaggedPointerField(
rdi, FieldOperand(rdi, JSBoundFunction::kBoundTargetFunctionOffset));
__ Jump(BUILTIN_CODE(masm->isolate(), Construct), RelocInfo::CODE_TARGET);
}
// static
void Builtins::Generate_Construct(MacroAssembler* masm) {
// ----------- S t a t e -------------
// -- rax : the number of arguments (not including the receiver)
// -- rdx : the new target (either the same as the constructor or
// the JSFunction on which new was invoked initially)
// -- rdi : the constructor to call (can be any Object)
// -----------------------------------
StackArgumentsAccessor args(rax);
// Check if target is a Smi.
Label non_constructor;
__ JumpIfSmi(rdi, &non_constructor);
// Check if target has a [[Construct]] internal method.
__ LoadTaggedPointerField(rcx, FieldOperand(rdi, HeapObject::kMapOffset));
__ testb(FieldOperand(rcx, Map::kBitFieldOffset),
Immediate(Map::Bits1::IsConstructorBit::kMask));
__ j(zero, &non_constructor);
// Dispatch based on instance type.
__ CmpInstanceType(rcx, JS_FUNCTION_TYPE);
__ Jump(BUILTIN_CODE(masm->isolate(), ConstructFunction),
RelocInfo::CODE_TARGET, equal);
// Only dispatch to bound functions after checking whether they are
// constructors.
__ CmpInstanceType(rcx, JS_BOUND_FUNCTION_TYPE);
__ Jump(BUILTIN_CODE(masm->isolate(), ConstructBoundFunction),
RelocInfo::CODE_TARGET, equal);
// Only dispatch to proxies after checking whether they are constructors.
__ CmpInstanceType(rcx, JS_PROXY_TYPE);
__ Jump(BUILTIN_CODE(masm->isolate(), ConstructProxy), RelocInfo::CODE_TARGET,
equal);
// Called Construct on an exotic Object with a [[Construct]] internal method.
{
// Overwrite the original receiver with the (original) target.
__ movq(args.GetReceiverOperand(), rdi);
// Let the "call_as_constructor_delegate" take care of the rest.
__ LoadNativeContextSlot(Context::CALL_AS_CONSTRUCTOR_DELEGATE_INDEX, rdi);
__ Jump(masm->isolate()->builtins()->CallFunction(),
RelocInfo::CODE_TARGET);
}
// Called Construct on an Object that doesn't have a [[Construct]] internal
// method.
__ bind(&non_constructor);
__ Jump(BUILTIN_CODE(masm->isolate(), ConstructedNonConstructable),
RelocInfo::CODE_TARGET);
}
void Builtins::Generate_InterpreterOnStackReplacement(MacroAssembler* masm) {
{
FrameScope scope(masm, StackFrame::INTERNAL);
__ CallRuntime(Runtime::kCompileForOnStackReplacement);
}
Label skip;
// If the code object is null, just return to the caller.
__ testq(rax, rax);
__ j(not_equal, &skip, Label::kNear);
__ ret(0);
__ bind(&skip);
// Drop the handler frame that is be sitting on top of the actual
// JavaScript frame. This is the case then OSR is triggered from bytecode.
__ leave();
// Load deoptimization data from the code object.
__ LoadTaggedPointerField(rbx,
FieldOperand(rax, Code::kDeoptimizationDataOffset));
// Load the OSR entrypoint offset from the deoptimization data.
__ SmiUntagField(
rbx, FieldOperand(rbx, FixedArray::OffsetOfElementAt(
DeoptimizationData::kOsrPcOffsetIndex)));
// Compute the target address = code_obj + header_size + osr_offset
__ leaq(rax, FieldOperand(rax, rbx, times_1, Code::kHeaderSize));
// Overwrite the return address on the stack.
__ movq(StackOperandForReturnAddress(0), rax);
// And "return" to the OSR entry point of the function.
__ ret(0);
}
void Builtins::Generate_WasmCompileLazy(MacroAssembler* masm) {
// The function index was pushed to the stack by the caller as int32.
__ Pop(r11);
// Convert to Smi for the runtime call.
__ SmiTag(r11);
{
HardAbortScope hard_abort(masm); // Avoid calls to Abort.
FrameScope scope(masm, StackFrame::WASM_COMPILE_LAZY);
// Save all parameter registers (see wasm-linkage.cc). They might be
// overwritten in the runtime call below. We don't have any callee-saved
// registers in wasm, so no need to store anything else.
static_assert(WasmCompileLazyFrameConstants::kNumberOfSavedGpParamRegs ==
arraysize(wasm::kGpParamRegisters),
"frame size mismatch");
for (Register reg : wasm::kGpParamRegisters) {
__ Push(reg);
}
static_assert(WasmCompileLazyFrameConstants::kNumberOfSavedFpParamRegs ==
arraysize(wasm::kFpParamRegisters),
"frame size mismatch");
__ AllocateStackSpace(kSimd128Size * arraysize(wasm::kFpParamRegisters));
int offset = 0;
for (DoubleRegister reg : wasm::kFpParamRegisters) {
__ movdqu(Operand(rsp, offset), reg);
offset += kSimd128Size;
}
// Push the Wasm instance as an explicit argument to WasmCompileLazy.
__ Push(kWasmInstanceRegister);
// Push the function index as second argument.
__ Push(r11);
// Initialize the JavaScript context with 0. CEntry will use it to
// set the current context on the isolate.
__ Move(kContextRegister, Smi::zero());
__ CallRuntime(Runtime::kWasmCompileLazy, 2);
// The entrypoint address is the return value.
__ movq(r11, kReturnRegister0);
// Restore registers.
for (DoubleRegister reg : base::Reversed(wasm::kFpParamRegisters)) {
offset -= kSimd128Size;
__ movdqu(reg, Operand(rsp, offset));
}
DCHECK_EQ(0, offset);
__ addq(rsp, Immediate(kSimd128Size * arraysize(wasm::kFpParamRegisters)));
for (Register reg : base::Reversed(wasm::kGpParamRegisters)) {
__ Pop(reg);
}
}
// Finally, jump to the entrypoint.
__ jmp(r11);
}
void Builtins::Generate_WasmDebugBreak(MacroAssembler* masm) {
HardAbortScope hard_abort(masm); // Avoid calls to Abort.
{
FrameScope scope(masm, StackFrame::WASM_DEBUG_BREAK);
// Save all parameter registers. They might hold live values, we restore
// them after the runtime call.
for (int reg_code : base::bits::IterateBitsBackwards(
WasmDebugBreakFrameConstants::kPushedGpRegs)) {
__ Push(Register::from_code(reg_code));
}
constexpr int kFpStackSize =
kSimd128Size * WasmDebugBreakFrameConstants::kNumPushedFpRegisters;
__ AllocateStackSpace(kFpStackSize);
int offset = kFpStackSize;
for (int reg_code : base::bits::IterateBitsBackwards(
WasmDebugBreakFrameConstants::kPushedFpRegs)) {
offset -= kSimd128Size;
__ movdqu(Operand(rsp, offset), DoubleRegister::from_code(reg_code));
}
// Initialize the JavaScript context with 0. CEntry will use it to
// set the current context on the isolate.
__ Move(kContextRegister, Smi::zero());
__ CallRuntime(Runtime::kWasmDebugBreak, 0);
// Restore registers.
for (int reg_code :
base::bits::IterateBits(WasmDebugBreakFrameConstants::kPushedFpRegs)) {
__ movdqu(DoubleRegister::from_code(reg_code), Operand(rsp, offset));
offset += kSimd128Size;
}
__ addq(rsp, Immediate(kFpStackSize));
for (int reg_code :
base::bits::IterateBits(WasmDebugBreakFrameConstants::kPushedGpRegs)) {
__ Pop(Register::from_code(reg_code));
}
}
__ ret(0);
}
void Builtins::Generate_CEntry(MacroAssembler* masm, int result_size,
SaveFPRegsMode save_doubles, ArgvMode argv_mode,
bool builtin_exit_frame) {
// rax: number of arguments including receiver
// rbx: pointer to C function (C callee-saved)
// rbp: frame pointer of calling JS frame (restored after C call)
// rsp: stack pointer (restored after C call)
// rsi: current context (restored)
//
// If argv_mode == kArgvInRegister:
// r15: pointer to the first argument
#ifdef V8_TARGET_OS_WIN
// Windows 64-bit ABI passes arguments in rcx, rdx, r8, r9. It requires the
// stack to be aligned to 16 bytes. It only allows a single-word to be
// returned in register rax. Larger return sizes must be written to an address
// passed as a hidden first argument.
const Register kCCallArg0 = rcx;
const Register kCCallArg1 = rdx;
const Register kCCallArg2 = r8;
const Register kCCallArg3 = r9;
const int kArgExtraStackSpace = 2;
const int kMaxRegisterResultSize = 1;
#else
// GCC / Clang passes arguments in rdi, rsi, rdx, rcx, r8, r9. Simple results
// are returned in rax, and a struct of two pointers are returned in rax+rdx.
// Larger return sizes must be written to an address passed as a hidden first
// argument.
const Register kCCallArg0 = rdi;
const Register kCCallArg1 = rsi;
const Register kCCallArg2 = rdx;
const Register kCCallArg3 = rcx;
const int kArgExtraStackSpace = 0;
const int kMaxRegisterResultSize = 2;
#endif // V8_TARGET_OS_WIN
// Enter the exit frame that transitions from JavaScript to C++.
int arg_stack_space =
kArgExtraStackSpace +
(result_size <= kMaxRegisterResultSize ? 0 : result_size);
if (argv_mode == kArgvInRegister) {
DCHECK(save_doubles == kDontSaveFPRegs);
DCHECK(!builtin_exit_frame);
__ EnterApiExitFrame(arg_stack_space);
// Move argc into r14 (argv is already in r15).
__ movq(r14, rax);
} else {
__ EnterExitFrame(
arg_stack_space, save_doubles == kSaveFPRegs,
builtin_exit_frame ? StackFrame::BUILTIN_EXIT : StackFrame::EXIT);
}
// rbx: pointer to builtin function (C callee-saved).
// rbp: frame pointer of exit frame (restored after C call).
// rsp: stack pointer (restored after C call).
// r14: number of arguments including receiver (C callee-saved).
// r15: argv pointer (C callee-saved).
// Check stack alignment.
if (FLAG_debug_code) {
__ CheckStackAlignment();
}
// Call C function. The arguments object will be created by stubs declared by
// DECLARE_RUNTIME_FUNCTION().
if (result_size <= kMaxRegisterResultSize) {
// Pass a pointer to the Arguments object as the first argument.
// Return result in single register (rax), or a register pair (rax, rdx).
__ movq(kCCallArg0, r14); // argc.
__ movq(kCCallArg1, r15); // argv.
__ Move(kCCallArg2, ExternalReference::isolate_address(masm->isolate()));
} else {
DCHECK_LE(result_size, 2);
// Pass a pointer to the result location as the first argument.
__ leaq(kCCallArg0, StackSpaceOperand(kArgExtraStackSpace));
// Pass a pointer to the Arguments object as the second argument.
__ movq(kCCallArg1, r14); // argc.
__ movq(kCCallArg2, r15); // argv.
__ Move(kCCallArg3, ExternalReference::isolate_address(masm->isolate()));
}
__ call(rbx);
if (result_size > kMaxRegisterResultSize) {
// Read result values stored on stack. Result is stored
// above the the two Arguments object slots on Win64.
DCHECK_LE(result_size, 2);
__ movq(kReturnRegister0, StackSpaceOperand(kArgExtraStackSpace + 0));
__ movq(kReturnRegister1, StackSpaceOperand(kArgExtraStackSpace + 1));
}
// Result is in rax or rdx:rax - do not destroy these registers!
// Check result for exception sentinel.
Label exception_returned;
__ CompareRoot(rax, RootIndex::kException);
__ j(equal, &exception_returned);
// Check that there is no pending exception, otherwise we
// should have returned the exception sentinel.
if (FLAG_debug_code) {
Label okay;
__ LoadRoot(r14, RootIndex::kTheHoleValue);
ExternalReference pending_exception_address = ExternalReference::Create(
IsolateAddressId::kPendingExceptionAddress, masm->isolate());
Operand pending_exception_operand =
masm->ExternalReferenceAsOperand(pending_exception_address);
__ cmp_tagged(r14, pending_exception_operand);
__ j(equal, &okay, Label::kNear);
__ int3();
__ bind(&okay);
}
// Exit the JavaScript to C++ exit frame.
__ LeaveExitFrame(save_doubles == kSaveFPRegs, argv_mode == kArgvOnStack);
__ ret(0);
// Handling of exception.
__ bind(&exception_returned);
ExternalReference pending_handler_context_address = ExternalReference::Create(
IsolateAddressId::kPendingHandlerContextAddress, masm->isolate());
ExternalReference pending_handler_entrypoint_address =
ExternalReference::Create(
IsolateAddressId::kPendingHandlerEntrypointAddress, masm->isolate());
ExternalReference pending_handler_fp_address = ExternalReference::Create(
IsolateAddressId::kPendingHandlerFPAddress, masm->isolate());
ExternalReference pending_handler_sp_address = ExternalReference::Create(
IsolateAddressId::kPendingHandlerSPAddress, masm->isolate());
// Ask the runtime for help to determine the handler. This will set rax to
// contain the current pending exception, don't clobber it.
ExternalReference find_handler =
ExternalReference::Create(Runtime::kUnwindAndFindExceptionHandler);
{
FrameScope scope(masm, StackFrame::MANUAL);
__ movq(arg_reg_1, Immediate(0)); // argc.
__ movq(arg_reg_2, Immediate(0)); // argv.
__ Move(arg_reg_3, ExternalReference::isolate_address(masm->isolate()));
__ PrepareCallCFunction(3);
__ CallCFunction(find_handler, 3);
}
// Retrieve the handler context, SP and FP.
__ movq(rsi,
masm->ExternalReferenceAsOperand(pending_handler_context_address));
__ movq(rsp, masm->ExternalReferenceAsOperand(pending_handler_sp_address));
__ movq(rbp, masm->ExternalReferenceAsOperand(pending_handler_fp_address));
// If the handler is a JS frame, restore the context to the frame. Note that
// the context will be set to (rsi == 0) for non-JS frames.
Label skip;
__ testq(rsi, rsi);
__ j(zero, &skip, Label::kNear);
__ movq(Operand(rbp, StandardFrameConstants::kContextOffset), rsi);
__ bind(&skip);
// Reset the masking register. This is done independent of the underlying
// feature flag {FLAG_untrusted_code_mitigations} to make the snapshot work
// with both configurations. It is safe to always do this, because the
// underlying register is caller-saved and can be arbitrarily clobbered.
__ ResetSpeculationPoisonRegister();
// Compute the handler entry address and jump to it.
__ movq(rdi,
masm->ExternalReferenceAsOperand(pending_handler_entrypoint_address));
__ jmp(rdi);
}
void Builtins::Generate_DoubleToI(MacroAssembler* masm) {
Label check_negative, process_64_bits, done;
// Account for return address and saved regs.
const int kArgumentOffset = 4 * kSystemPointerSize;
MemOperand mantissa_operand(MemOperand(rsp, kArgumentOffset));
MemOperand exponent_operand(
MemOperand(rsp, kArgumentOffset + kDoubleSize / 2));
// The result is returned on the stack.
MemOperand return_operand = mantissa_operand;
Register scratch1 = rbx;
// Since we must use rcx for shifts below, use some other register (rax)
// to calculate the result if ecx is the requested return register.
Register result_reg = rax;
// Save ecx if it isn't the return register and therefore volatile, or if it
// is the return register, then save the temp register we use in its stead
// for the result.
Register save_reg = rax;
__ pushq(rcx);
__ pushq(scratch1);
__ pushq(save_reg);
__ movl(scratch1, mantissa_operand);
__ Movsd(kScratchDoubleReg, mantissa_operand);
__ movl(rcx, exponent_operand);
__ andl(rcx, Immediate(HeapNumber::kExponentMask));
__ shrl(rcx, Immediate(HeapNumber::kExponentShift));
__ leal(result_reg, MemOperand(rcx, -HeapNumber::kExponentBias));
__ cmpl(result_reg, Immediate(HeapNumber::kMantissaBits));
__ j(below, &process_64_bits, Label::kNear);
// Result is entirely in lower 32-bits of mantissa
int delta = HeapNumber::kExponentBias + Double::kPhysicalSignificandSize;
__ subl(rcx, Immediate(delta));
__ xorl(result_reg, result_reg);
__ cmpl(rcx, Immediate(31));
__ j(above, &done, Label::kNear);
__ shll_cl(scratch1);
__ jmp(&check_negative, Label::kNear);
__ bind(&process_64_bits);
__ Cvttsd2siq(result_reg, kScratchDoubleReg);
__ jmp(&done, Label::kNear);
// If the double was negative, negate the integer result.
__ bind(&check_negative);
__ movl(result_reg, scratch1);
__ negl(result_reg);
__ cmpl(exponent_operand, Immediate(0));
__ cmovl(greater, result_reg, scratch1);
// Restore registers
__ bind(&done);
__ movl(return_operand, result_reg);
__ popq(save_reg);
__ popq(scratch1);
__ popq(rcx);
__ ret(0);
}
namespace {
int Offset(ExternalReference ref0, ExternalReference ref1) {
int64_t offset = (ref0.address() - ref1.address());
// Check that fits into int.
DCHECK(static_cast<int>(offset) == offset);
return static_cast<int>(offset);
}
// Calls an API function. Allocates HandleScope, extracts returned value
// from handle and propagates exceptions. Clobbers r14, r15, rbx and
// caller-save registers. Restores context. On return removes
// stack_space * kSystemPointerSize (GCed).
void CallApiFunctionAndReturn(MacroAssembler* masm, Register function_address,
ExternalReference thunk_ref,
Register thunk_last_arg, int stack_space,
Operand* stack_space_operand,
Operand return_value_operand) {
Label prologue;
Label promote_scheduled_exception;
Label delete_allocated_handles;
Label leave_exit_frame;
Isolate* isolate = masm->isolate();
Factory* factory = isolate->factory();
ExternalReference next_address =
ExternalReference::handle_scope_next_address(isolate);
const int kNextOffset = 0;
const int kLimitOffset = Offset(
ExternalReference::handle_scope_limit_address(isolate), next_address);
const int kLevelOffset = Offset(
ExternalReference::handle_scope_level_address(isolate), next_address);
ExternalReference scheduled_exception_address =
ExternalReference::scheduled_exception_address(isolate);
DCHECK(rdx == function_address || r8 == function_address);
// Allocate HandleScope in callee-save registers.
Register prev_next_address_reg = r14;
Register prev_limit_reg = rbx;
Register base_reg = r15;
__ Move(base_reg, next_address);
__ movq(prev_next_address_reg, Operand(base_reg, kNextOffset));
__ movq(prev_limit_reg, Operand(base_reg, kLimitOffset));
__ addl(Operand(base_reg, kLevelOffset), Immediate(1));
Label profiler_enabled, end_profiler_check;
__ Move(rax, ExternalReference::is_profiling_address(isolate));
__ cmpb(Operand(rax, 0), Immediate(0));
__ j(not_zero, &profiler_enabled);
__ Move(rax, ExternalReference::address_of_runtime_stats_flag());
__ cmpl(Operand(rax, 0), Immediate(0));
__ j(not_zero, &profiler_enabled);
{
// Call the api function directly.
__ Move(rax, function_address);
__ jmp(&end_profiler_check);
}
__ bind(&profiler_enabled);
{
// Third parameter is the address of the actual getter function.
__ Move(thunk_last_arg, function_address);
__ Move(rax, thunk_ref);
}
__ bind(&end_profiler_check);
// Call the api function!
__ call(rax);
// Load the value from ReturnValue
__ movq(rax, return_value_operand);
__ bind(&prologue);
// No more valid handles (the result handle was the last one). Restore
// previous handle scope.
__ subl(Operand(base_reg, kLevelOffset), Immediate(1));
__ movq(Operand(base_reg, kNextOffset), prev_next_address_reg);
__ cmpq(prev_limit_reg, Operand(base_reg, kLimitOffset));
__ j(not_equal, &delete_allocated_handles);
// Leave the API exit frame.
__ bind(&leave_exit_frame);
if (stack_space_operand != nullptr) {
DCHECK_EQ(stack_space, 0);
__ movq(rbx, *stack_space_operand);
}
__ LeaveApiExitFrame();
// Check if the function scheduled an exception.
__ Move(rdi, scheduled_exception_address);
__ Cmp(Operand(rdi, 0), factory->the_hole_value());
__ j(not_equal, &promote_scheduled_exception);
#if DEBUG
// Check if the function returned a valid JavaScript value.
Label ok;
Register return_value = rax;
Register map = rcx;
__ JumpIfSmi(return_value, &ok, Label::kNear);
__ LoadTaggedPointerField(map,
FieldOperand(return_value, HeapObject::kMapOffset));
__ CmpInstanceType(map, LAST_NAME_TYPE);
__ j(below_equal, &ok, Label::kNear);
__ CmpInstanceType(map, FIRST_JS_RECEIVER_TYPE);
__ j(above_equal, &ok, Label::kNear);
__ CompareRoot(map, RootIndex::kHeapNumberMap);
__ j(equal, &ok, Label::kNear);
__ CompareRoot(map, RootIndex::kBigIntMap);
__ j(equal, &ok, Label::kNear);
__ CompareRoot(return_value, RootIndex::kUndefinedValue);
__ j(equal, &ok, Label::kNear);
__ CompareRoot(return_value, RootIndex::kTrueValue);
__ j(equal, &ok, Label::kNear);
__ CompareRoot(return_value, RootIndex::kFalseValue);
__ j(equal, &ok, Label::kNear);
__ CompareRoot(return_value, RootIndex::kNullValue);
__ j(equal, &ok, Label::kNear);
__ Abort(AbortReason::kAPICallReturnedInvalidObject);
__ bind(&ok);
#endif
if (stack_space_operand == nullptr) {
DCHECK_NE(stack_space, 0);
__ ret(stack_space * kSystemPointerSize);
} else {
DCHECK_EQ(stack_space, 0);
__ PopReturnAddressTo(rcx);
__ addq(rsp, rbx);
__ jmp(rcx);
}
// Re-throw by promoting a scheduled exception.
__ bind(&promote_scheduled_exception);
__ TailCallRuntime(Runtime::kPromoteScheduledException);
// HandleScope limit has changed. Delete allocated extensions.
__ bind(&delete_allocated_handles);
__ movq(Operand(base_reg, kLimitOffset), prev_limit_reg);
__ movq(prev_limit_reg, rax);
__ LoadAddress(arg_reg_1, ExternalReference::isolate_address(isolate));
__ LoadAddress(rax, ExternalReference::delete_handle_scope_extensions());
__ call(rax);
__ movq(rax, prev_limit_reg);
__ jmp(&leave_exit_frame);
}
} // namespace
// TODO(jgruber): Instead of explicitly setting up implicit_args_ on the stack
// in CallApiCallback, we could use the calling convention to set up the stack
// correctly in the first place.
//
// TODO(jgruber): I suspect that most of CallApiCallback could be implemented
// as a C++ trampoline, vastly simplifying the assembly implementation.
void Builtins::Generate_CallApiCallback(MacroAssembler* masm) {
// ----------- S t a t e -------------
// -- rsi : context
// -- rdx : api function address
// -- rcx : arguments count (not including the receiver)
// -- rbx : call data
// -- rdi : holder
// -- rsp[0] : return address
// -- rsp[8] : argument argc
// -- ...
// -- rsp[argc * 8] : argument 1
// -- rsp[(argc + 1) * 8] : argument 0 (receiver)
// -----------------------------------
// NOTE: The order of args are reversed if V8_REVERSE_JSARGS
Register api_function_address = rdx;
Register argc = rcx;
Register call_data = rbx;
Register holder = rdi;
DCHECK(!AreAliased(api_function_address, argc, holder, call_data,
kScratchRegister));
using FCA = FunctionCallbackArguments;
STATIC_ASSERT(FCA::kArgsLength == 6);
STATIC_ASSERT(FCA::kNewTargetIndex == 5);
STATIC_ASSERT(FCA::kDataIndex == 4);
STATIC_ASSERT(FCA::kReturnValueOffset == 3);
STATIC_ASSERT(FCA::kReturnValueDefaultValueIndex == 2);
STATIC_ASSERT(FCA::kIsolateIndex == 1);
STATIC_ASSERT(FCA::kHolderIndex == 0);
// Set up FunctionCallbackInfo's implicit_args on the stack as follows:
//
// Current state:
// rsp[0]: return address
//
// Target state:
// rsp[0 * kSystemPointerSize]: return address
// rsp[1 * kSystemPointerSize]: kHolder
// rsp[2 * kSystemPointerSize]: kIsolate
// rsp[3 * kSystemPointerSize]: undefined (kReturnValueDefaultValue)
// rsp[4 * kSystemPointerSize]: undefined (kReturnValue)
// rsp[5 * kSystemPointerSize]: kData
// rsp[6 * kSystemPointerSize]: undefined (kNewTarget)
__ PopReturnAddressTo(rax);
__ LoadRoot(kScratchRegister, RootIndex::kUndefinedValue);
__ Push(kScratchRegister);
__ Push(call_data);
__ Push(kScratchRegister);
__ Push(kScratchRegister);
__ PushAddress(ExternalReference::isolate_address(masm->isolate()));
__ Push(holder);
__ PushReturnAddressFrom(rax);
// Keep a pointer to kHolder (= implicit_args) in a scratch register.
// We use it below to set up the FunctionCallbackInfo object.
Register scratch = rbx;
__ leaq(scratch, Operand(rsp, 1 * kSystemPointerSize));
// Allocate the v8::Arguments structure in the arguments' space since
// it's not controlled by GC.
static constexpr int kApiStackSpace = 4;
__ EnterApiExitFrame(kApiStackSpace);
// FunctionCallbackInfo::implicit_args_ (points at kHolder as set up above).
__ movq(StackSpaceOperand(0), scratch);
// FunctionCallbackInfo::values_ (points at the first varargs argument passed
// on the stack).
#ifdef V8_REVERSE_JSARGS
__ leaq(scratch,
Operand(scratch, (FCA::kArgsLength + 1) * kSystemPointerSize));
#else
__ leaq(scratch, Operand(scratch, argc, times_system_pointer_size,
(FCA::kArgsLength - 1) * kSystemPointerSize));
#endif
__ movq(StackSpaceOperand(1), scratch);
// FunctionCallbackInfo::length_.
__ movq(StackSpaceOperand(2), argc);
// We also store the number of bytes to drop from the stack after returning
// from the API function here.
__ leaq(kScratchRegister,
Operand(argc, times_system_pointer_size,
(FCA::kArgsLength + 1 /* receiver */) * kSystemPointerSize));
__ movq(StackSpaceOperand(3), kScratchRegister);
Register arguments_arg = arg_reg_1;
Register callback_arg = arg_reg_2;
// It's okay if api_function_address == callback_arg
// but not arguments_arg
DCHECK(api_function_address != arguments_arg);
// v8::InvocationCallback's argument.
__ leaq(arguments_arg, StackSpaceOperand(0));
ExternalReference thunk_ref = ExternalReference::invoke_function_callback();
// There are two stack slots above the arguments we constructed on the stack:
// the stored ebp (pushed by EnterApiExitFrame), and the return address.
static constexpr int kStackSlotsAboveFCA = 2;
Operand return_value_operand(
rbp,
(kStackSlotsAboveFCA + FCA::kReturnValueOffset) * kSystemPointerSize);
static constexpr int kUseStackSpaceOperand = 0;
Operand stack_space_operand = StackSpaceOperand(3);
CallApiFunctionAndReturn(masm, api_function_address, thunk_ref, callback_arg,
kUseStackSpaceOperand, &stack_space_operand,
return_value_operand);
}
void Builtins::Generate_CallApiGetter(MacroAssembler* masm) {
Register name_arg = arg_reg_1;
Register accessor_info_arg = arg_reg_2;
Register getter_arg = arg_reg_3;
Register api_function_address = r8;
Register receiver = ApiGetterDescriptor::ReceiverRegister();
Register holder = ApiGetterDescriptor::HolderRegister();
Register callback = ApiGetterDescriptor::CallbackRegister();
Register scratch = rax;
Register decompr_scratch1 = COMPRESS_POINTERS_BOOL ? r11 : no_reg;
DCHECK(!AreAliased(receiver, holder, callback, scratch, decompr_scratch1));
// Build v8::PropertyCallbackInfo::args_ array on the stack and push property
// name below the exit frame to make GC aware of them.
STATIC_ASSERT(PropertyCallbackArguments::kShouldThrowOnErrorIndex == 0);
STATIC_ASSERT(PropertyCallbackArguments::kHolderIndex == 1);
STATIC_ASSERT(PropertyCallbackArguments::kIsolateIndex == 2);
STATIC_ASSERT(PropertyCallbackArguments::kReturnValueDefaultValueIndex == 3);
STATIC_ASSERT(PropertyCallbackArguments::kReturnValueOffset == 4);
STATIC_ASSERT(PropertyCallbackArguments::kDataIndex == 5);
STATIC_ASSERT(PropertyCallbackArguments::kThisIndex == 6);
STATIC_ASSERT(PropertyCallbackArguments::kArgsLength == 7);
// Insert additional parameters into the stack frame above return address.
__ PopReturnAddressTo(scratch);
__ Push(receiver);
__ PushTaggedAnyField(FieldOperand(callback, AccessorInfo::kDataOffset),
decompr_scratch1);
__ LoadRoot(kScratchRegister, RootIndex::kUndefinedValue);
__ Push(kScratchRegister); // return value
__ Push(kScratchRegister); // return value default
__ PushAddress(ExternalReference::isolate_address(masm->isolate()));
__ Push(holder);
__ Push(Smi::zero()); // should_throw_on_error -> false
__ PushTaggedPointerField(FieldOperand(callback, AccessorInfo::kNameOffset),
decompr_scratch1);
__ PushReturnAddressFrom(scratch);
// v8::PropertyCallbackInfo::args_ array and name handle.
const int kStackUnwindSpace = PropertyCallbackArguments::kArgsLength + 1;
// Allocate v8::PropertyCallbackInfo in non-GCed stack space.
const int kArgStackSpace = 1;
// Load address of v8::PropertyAccessorInfo::args_ array.
__ leaq(scratch, Operand(rsp, 2 * kSystemPointerSize));
__ EnterApiExitFrame(kArgStackSpace);
// Create v8::PropertyCallbackInfo object on the stack and initialize
// it's args_ field.
Operand info_object = StackSpaceOperand(0);
__ movq(info_object, scratch);
__ leaq(name_arg, Operand(scratch, -kSystemPointerSize));
// The context register (rsi) has been saved in EnterApiExitFrame and
// could be used to pass arguments.
__ leaq(accessor_info_arg, info_object);
ExternalReference thunk_ref =
ExternalReference::invoke_accessor_getter_callback();
// It's okay if api_function_address == getter_arg
// but not accessor_info_arg or name_arg
DCHECK(api_function_address != accessor_info_arg);
DCHECK(api_function_address != name_arg);
__ LoadTaggedPointerField(
scratch, FieldOperand(callback, AccessorInfo::kJsGetterOffset));
__ LoadExternalPointerField(
api_function_address,
FieldOperand(scratch, Foreign::kForeignAddressOffset));
// +3 is to skip prolog, return address and name handle.
Operand return_value_operand(
rbp,
(PropertyCallbackArguments::kReturnValueOffset + 3) * kSystemPointerSize);
Operand* const kUseStackSpaceConstant = nullptr;
CallApiFunctionAndReturn(masm, api_function_address, thunk_ref, getter_arg,
kStackUnwindSpace, kUseStackSpaceConstant,
return_value_operand);
}
void Builtins::Generate_DirectCEntry(MacroAssembler* masm) {
__ int3(); // Unused on this architecture.
}
#undef __
} // namespace internal
} // namespace v8
#endif // V8_TARGET_ARCH_X64
| bsd-3-clause |
justinpotts/mozillians | mozillians/users/migrations/0039_auto__add_externalaccount.py | 12687 | # -*- coding: utf-8 -*-
import datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Adding model 'ExternalAccount'
db.create_table('users_externalaccount', (
('id', self.gf('django.db.models.fields.AutoField')(primary_key=True)),
('user', self.gf('django.db.models.fields.related.ForeignKey')(to=orm['users.UserProfile'])),
('username', self.gf('django.db.models.fields.CharField')(default='', max_length=255, blank=True)),
('type', self.gf('django.db.models.fields.PositiveIntegerField')(default=0)),
('privacy', self.gf('django.db.models.fields.PositiveIntegerField')(default=3)),
))
db.send_create_signal('users', ['ExternalAccount'])
def backwards(self, orm):
# Deleting model 'ExternalAccount'
db.delete_table('users_externalaccount')
models = {
'auth.group': {
'Meta': {'object_name': 'Group'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '80'}),
'permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'})
},
'auth.permission': {
'Meta': {'ordering': "('content_type__app_label', 'content_type__model', 'codename')", 'unique_together': "(('content_type', 'codename'),)", 'object_name': 'Permission'},
'codename': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'content_type': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['contenttypes.ContentType']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '50'})
},
'auth.user': {
'Meta': {'object_name': 'User'},
'date_joined': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'email': ('django.db.models.fields.EmailField', [], {'max_length': '75', 'blank': 'True'}),
'first_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Group']", 'symmetrical': 'False', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_active': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'is_staff': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'is_superuser': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'last_login': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now'}),
'last_name': ('django.db.models.fields.CharField', [], {'max_length': '30', 'blank': 'True'}),
'password': ('django.db.models.fields.CharField', [], {'max_length': '128'}),
'user_permissions': ('django.db.models.fields.related.ManyToManyField', [], {'to': "orm['auth.Permission']", 'symmetrical': 'False', 'blank': 'True'}),
'username': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'contenttypes.contenttype': {
'Meta': {'ordering': "('name',)", 'unique_together': "(('app_label', 'model'),)", 'object_name': 'ContentType', 'db_table': "'django_content_type'"},
'app_label': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'model': ('django.db.models.fields.CharField', [], {'max_length': '100'}),
'name': ('django.db.models.fields.CharField', [], {'max_length': '100'})
},
'groups.group': {
'Meta': {'ordering': "['name']", 'object_name': 'Group'},
'always_auto_complete': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'auto_complete': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'db_index': 'True'}),
'description': ('django.db.models.fields.TextField', [], {'default': "''", 'max_length': '255', 'blank': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'irc_channel': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '63', 'blank': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '50', 'db_index': 'True'}),
'steward': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['users.UserProfile']", 'null': 'True', 'on_delete': 'models.SET_NULL', 'blank': 'True'}),
'system': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'db_index': 'True'}),
'url': ('django.db.models.fields.SlugField', [], {'max_length': '50', 'blank': 'True'}),
'website': ('django.db.models.fields.URLField', [], {'default': "''", 'max_length': '200', 'blank': 'True'}),
'wiki': ('django.db.models.fields.URLField', [], {'default': "''", 'max_length': '200', 'blank': 'True'})
},
'groups.language': {
'Meta': {'ordering': "['name']", 'object_name': 'Language'},
'always_auto_complete': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'auto_complete': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'db_index': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '50', 'db_index': 'True'}),
'url': ('django.db.models.fields.SlugField', [], {'max_length': '50', 'blank': 'True'})
},
'groups.skill': {
'Meta': {'ordering': "['name']", 'object_name': 'Skill'},
'always_auto_complete': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'auto_complete': ('django.db.models.fields.BooleanField', [], {'default': 'False', 'db_index': 'True'}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'name': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '50', 'db_index': 'True'}),
'url': ('django.db.models.fields.SlugField', [], {'max_length': '50', 'blank': 'True'})
},
'users.externalaccount': {
'Meta': {'object_name': 'ExternalAccount'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'privacy': ('django.db.models.fields.PositiveIntegerField', [], {'default': '3'}),
'type': ('django.db.models.fields.PositiveIntegerField', [], {'default': '0'}),
'user': ('django.db.models.fields.related.ForeignKey', [], {'to': "orm['users.UserProfile']"}),
'username': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '255', 'blank': 'True'})
},
'users.usernameblacklist': {
'Meta': {'ordering': "['value']", 'object_name': 'UsernameBlacklist'},
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'is_regex': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'value': ('django.db.models.fields.CharField', [], {'unique': 'True', 'max_length': '30'})
},
'users.userprofile': {
'Meta': {'ordering': "['full_name']", 'object_name': 'UserProfile', 'db_table': "'profile'"},
'allows_community_sites': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'allows_mozilla_sites': ('django.db.models.fields.BooleanField', [], {'default': 'True'}),
'basket_token': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '1024', 'blank': 'True'}),
'bio': ('django.db.models.fields.TextField', [], {'default': "''", 'blank': 'True'}),
'city': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '255', 'blank': 'True'}),
'country': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '50'}),
'date_mozillian': ('django.db.models.fields.DateField', [], {'default': 'None', 'null': 'True', 'blank': 'True'}),
'date_vouched': ('django.db.models.fields.DateTimeField', [], {'default': 'None', 'null': 'True', 'blank': 'True'}),
'full_name': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '255'}),
'groups': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "'members'", 'blank': 'True', 'to': "orm['groups.Group']"}),
'id': ('django.db.models.fields.AutoField', [], {'primary_key': 'True'}),
'ircname': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '63', 'blank': 'True'}),
'is_vouched': ('django.db.models.fields.BooleanField', [], {'default': 'False'}),
'languages': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "'members'", 'blank': 'True', 'to': "orm['groups.Language']"}),
'last_updated': ('django.db.models.fields.DateTimeField', [], {'default': 'datetime.datetime.now', 'auto_now': 'True', 'blank': 'True'}),
'photo': ('sorl.thumbnail.fields.ImageField', [], {'default': "''", 'max_length': '100', 'blank': 'True'}),
'privacy_bio': ('mozillians.users.models.PrivacyField', [], {'default': '3'}),
'privacy_city': ('mozillians.users.models.PrivacyField', [], {'default': '3'}),
'privacy_country': ('mozillians.users.models.PrivacyField', [], {'default': '3'}),
'privacy_date_mozillian': ('mozillians.users.models.PrivacyField', [], {'default': '3'}),
'privacy_email': ('mozillians.users.models.PrivacyField', [], {'default': '3'}),
'privacy_full_name': ('mozillians.users.models.PrivacyField', [], {'default': '3'}),
'privacy_groups': ('mozillians.users.models.PrivacyField', [], {'default': '3'}),
'privacy_ircname': ('mozillians.users.models.PrivacyField', [], {'default': '3'}),
'privacy_languages': ('mozillians.users.models.PrivacyField', [], {'default': '3'}),
'privacy_photo': ('mozillians.users.models.PrivacyField', [], {'default': '3'}),
'privacy_region': ('mozillians.users.models.PrivacyField', [], {'default': '3'}),
'privacy_skills': ('mozillians.users.models.PrivacyField', [], {'default': '3'}),
'privacy_timezone': ('mozillians.users.models.PrivacyField', [], {'default': '3'}),
'privacy_title': ('mozillians.users.models.PrivacyField', [], {'default': '3'}),
'privacy_tshirt': ('mozillians.users.models.PrivacyField', [], {'default': '1'}),
'privacy_vouched_by': ('mozillians.users.models.PrivacyField', [], {'default': '3'}),
'privacy_website': ('mozillians.users.models.PrivacyField', [], {'default': '3'}),
'region': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '255', 'blank': 'True'}),
'skills': ('django.db.models.fields.related.ManyToManyField', [], {'symmetrical': 'False', 'related_name': "'members'", 'blank': 'True', 'to': "orm['groups.Skill']"}),
'timezone': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '100', 'blank': 'True'}),
'tshirt': ('django.db.models.fields.IntegerField', [], {'default': 'None', 'null': 'True', 'blank': 'True'}),
'title': ('django.db.models.fields.CharField', [], {'default': "''", 'max_length': '70', 'blank': 'True'}),
'user': ('django.db.models.fields.related.OneToOneField', [], {'to': "orm['auth.User']", 'unique': 'True'}),
'vouched_by': ('django.db.models.fields.related.ForeignKey', [], {'related_name': "'vouchees'", 'on_delete': 'models.SET_NULL', 'default': 'None', 'to': "orm['users.UserProfile']", 'blank': 'True', 'null': 'True'}),
'website': ('django.db.models.fields.URLField', [], {'default': "''", 'max_length': '200', 'blank': 'True'})
}
}
complete_apps = ['users']
| bsd-3-clause |
collin/spree_core | lib/spree_core/theme_support.rb | 181 | require 'spree_core/theme_support/hook'
require 'spree_core/theme_support/hook_listener'
require 'spree_core/theme_support/hook_modifier'
#require 'spree/theme_support/more_patches' | bsd-3-clause |
zhukaixy/ourjs | node_modules/cssshrink/node_modules/prettyugly/examples/ugly.js | 204 | var prettyugly = require('../index.js');
var read = require('fs').readFileSync;
var gonzo = require('gonzales-ast');
var css = read('example.css', 'utf8').toString();
console.log(prettyugly.ugly(css));
| bsd-3-clause |
pongad/api-client-staging | generated/php/google-cloud-oslogin-v1beta/src/OsLogin/V1beta/resources/os_login_service_descriptor_config.php | 117 | <?php
return [
'interfaces' => [
'google.cloud.oslogin.v1beta.OsLoginService' => [
],
],
];
| bsd-3-clause |
bit-it-krayina/bit | plugins/i18n/i18n.page.tags.php | 2563 | <?php
/* ====================
[BEGIN_COT_EXT]
Hooks=page.tags
Tags=page.tpl:{I18N_LANG_ROW_URL},{I18N_LANG_ROW_CODE},{I18N_LANG_ROW_TITLE},{I18N_LANG_ROW_CLASS},{I18N_LANG_ROW_SELECTED},{PAGE_I18N_TRANSLATE},{PAGE_I18N_DELETE}
[END_COT_EXT]
==================== */
/**
* Assigns i18n control tags for a page
*
* @package i18n
* @version 0.7.0
* @author Cotonti Team
* @copyright Copyright (c) Cotonti Team 2010-2014
* @license BSD License
*/
defined('COT_CODE') or die('Wrong URL');
if ($i18n_enabled)
{
$id = (empty($id)) ? $pag['page_id'] : $id;
// Render language selection
$pag_i18n_locales = cot_i18n_list_page_locales($id);
if (count($pag_i18n_locales) > 0)
{
array_unshift($pag_i18n_locales, $cfg['defaultlang']);
foreach ($pag_i18n_locales as $lc)
{
if ($lc == $i18n_locale)
{
$lc_class = 'selected';
$lc_selected = 'selected="selected"';
}
else
{
$lc_class = '';
$lc_selected = '';
}
$urlparams = empty($pag['page_alias']) ? array('c' => $pag['page_cat'], 'id' => $id) : array('c' => $pag['page_cat'], 'al' => $al);
if (!$cfg['plugin']['i18n']['omitmain'] || $lc != $i18n_fallback)
{
$urlparams += array('l' => $lc);
}
$t->assign(array(
'I18N_LANG_ROW_URL' => cot_url('page', $urlparams, '', false, true),
'I18N_LANG_ROW_CODE' => $lc,
'I18N_LANG_ROW_TITLE' => $i18n_locales[$lc],
'I18N_LANG_ROW_CLASS' => $lc_class,
'I18N_LANG_ROW_SELECTED' => $lc_selected
));
$t->parse('MAIN.I18N_LANG.I18N_LANG_ROW');
}
$t->parse('MAIN.I18N_LANG');
}
if ($i18n_write)
{
// Translation tags
if ($pag_i18n)
{
if ($i18n_admin || $pag_i18n['ipage_translatorid'] == $usr['id'])
{
// Edit translation
$url_i18n = cot_url('plug', "e=i18n&m=page&a=edit&id=$id&l=$i18n_locale");
$t->assign(array(
'PAGE_ADMIN_EDIT' => cot_rc_link($url_i18n, $L['Edit']),
'PAGE_ADMIN_EDIT_URL' => $url_i18n
));
}
}
else
{
if (count($pag_i18n_locales) < count($i18n_locales))
{
// Translate button
$url_i18n = cot_url('plug', "e=i18n&m=page&a=add&id=$id");
$t->assign(array(
'PAGE_I18N_TRANSLATE' => cot_rc_link($url_i18n, $L['i18n_translate']),
'PAGE_I18N_TRANSLATE_URL' => $url_i18n
));
}
}
}
if ($i18n_admin)
{
// Control tags
if ($pag_i18n)
{
// Delete translation
$url_i18n = cot_url('plug', "e=i18n&m=page&a=delete&id=$id&l=$i18n_locale");
$t->assign(array(
'PAGE_I18N_DELETE' => cot_rc_link($url_i18n, $L['Delete']),
'PAGE_I18N_DELETE_URL' => $url_i18n
));
}
}
}
| bsd-3-clause |
Hasimir/brython | www/tests/test_rmethods.py | 1796 | class Foo(object):
def __init__(self): self.value = 10
def __rsub__(self, other): return 55
def __rlshift__(self, other): return other * self.value
def __rmul__(self, other): return 77
assert 1.5 << Foo() == 15.0
assert 2 << Foo() == 20
assert 'a' << Foo() == 'aaaaaaaaaa'
try:
print(Foo()*Foo())
except TypeError:
pass
except:
raise
d={'a':1,'b':2}
try:
d+1
except TypeError:
pass
except:
raise
assert d*Foo()==77
t = [1, 2, 'a']
try:
d*3.5
except TypeError:
pass
except:
raise
assert t-Foo()==55
# infix operator : recipe on the ActiveState cookbook
# http://code.activestate.com/recipes/384122-infix-operators/
# definition of an Infix operator class
# this recipe also works in jython
# calling sequence for the infix is either:
# x |op| y
# or:
# x <<op>> y
class Infix:
def __init__(self, function):
self.function = function
def __ror__(self, other):
return Infix(lambda x, self=self, other=other: self.function(other, x))
def __or__(self, other):
return self.function(other)
def __call__(self, value1, value2):
return self.function(value1, value2)
# Examples
# simple multiplication
x=Infix(lambda x,y: x*y)
assert 2 |x| 4 == 8
# class checking
isa=Infix(lambda x,y: x.__class__==y.__class__)
assert [1,2,3] |isa| []
# inclusion checking
is_in=Infix(lambda x,y: x in y)
assert 1 |is_in| {1:'one'}
# an infix div operator
import operator
div=Infix(operator.floordiv)
assert (10 |div| (4 |div| 2)) == 5
# functional programming (not working in jython, use the "curry" recipe! )
def curry(f,x):
def curried_function(*args, **kw):
return f(*((x,)+args),**kw)
return curried_function
curry=Infix(curry)
add5= operator.add |curry| 5
assert add5(6) == 11
| bsd-3-clause |
stephens2424/php | testdata/fuzzdir/corpus/Zend_tests_add_005.php | 120 | <?php
$i = 75636;
$d = 2834681123.123123;
$c = $i + $d;
var_dump($c);
$c = $d + $i;
var_dump($c);
echo "Done\n";
?>
| bsd-3-clause |
davidx3601/ric | ric_mc/Arduino/libraries/CmdMessenger/CSharp/SendAndReceive/SendAndReceive.cs | 3772 | // *** SendandReceive ***
// This example expands the previous Receive example. The Arduino will now send back a status.
// It adds a demonstration of how to:
// - Handle received commands that do not have a function attached
// - Receive a command with a parameter from the Arduino
using System;
using System.Threading;
using CommandMessenger;
using CommandMessenger.TransportLayer;
namespace SendAndReceive
{
// This is the list of recognized commands. These can be commands that can either be sent or received.
// In order to receive, attach a callback function to these events
enum Command
{
SetLed,
Status,
};
public class SendAndReceive
{
public bool RunLoop { get; set; }
private SerialTransport _serialTransport;
private CmdMessenger _cmdMessenger;
private bool _ledState;
private int _count;
// Setup function
public void Setup()
{
_ledState = false;
// Create Serial Port object
// Note that for some boards (e.g. Sparkfun Pro Micro) DtrEnable may need to be true.
_serialTransport = new SerialTransport
{
CurrentSerialSettings = { PortName = "COM6", BaudRate = 115200, DtrEnable = false } // object initializer
};
// Initialize the command messenger with the Serial Port transport layer
_cmdMessenger = new CmdMessenger(_serialTransport)
{
BoardType = BoardType.Bit16 // Set if it is communicating with a 16- or 32-bit Arduino board
};
// Tell CmdMessenger if it is communicating with a 16 or 32 bit Arduino board
// Attach the callbacks to the Command Messenger
AttachCommandCallBacks();
// Start listening
_cmdMessenger.StartListening();
}
// Loop function
public void Loop()
{
_count++;
// Create command
var command = new SendCommand((int)Command.SetLed,_ledState);
// Send command
_cmdMessenger.SendCommand(command);
// Wait for 1 second and repeat
Thread.Sleep(1000);
_ledState = !_ledState; // Toggle led state
if (_count > 100) RunLoop = false; // Stop loop after 100 rounds
}
// Exit function
public void Exit()
{
// Stop listening
_cmdMessenger.StopListening();
// Dispose Command Messenger
_cmdMessenger.Dispose();
// Dispose Serial Port object
_serialTransport.Dispose();
// Pause before stop
Console.WriteLine("Press any key to stop...");
Console.ReadKey();
}
/// Attach command call backs.
private void AttachCommandCallBacks()
{
_cmdMessenger.Attach(OnUnknownCommand);
_cmdMessenger.Attach((int)Command.Status, OnStatus);
}
/// Executes when an unknown command has been received.
void OnUnknownCommand(ReceivedCommand arguments)
{
Console.WriteLine("Command without attached callback received");
}
// Callback function that prints the Arduino status to the console
void OnStatus(ReceivedCommand arguments)
{
Console.Write("Arduino status: ");
Console.WriteLine(arguments.ReadStringArg());
}
}
}
| bsd-3-clause |
Klaudit/inbox2_desktop | Code/Utils/Scraper/HtmlAgilityPack/NameValuePair.cs | 597 | // HtmlAgilityPack V1.0 - Simon Mourier <simon underscore mourier at hotmail dot com>
using System;
namespace HtmlAgilityPack
{
internal class NameValuePair
{
internal readonly string Name;
internal string Value;
internal NameValuePair()
{
}
internal NameValuePair(string name)
:
this()
{
Name = name;
}
internal NameValuePair(string name, string value)
:
this(name)
{
Value = value;
}
}
}
| bsd-3-clause |
JoKaWare/GViews | third_party/skia/src/core/SkBitmap.cpp | 49523 |
/*
* Copyright 2008 The Android Open Source Project
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkBitmap.h"
#include "SkColorPriv.h"
#include "SkDither.h"
#include "SkFlattenable.h"
#include "SkMallocPixelRef.h"
#include "SkMask.h"
#include "SkOrderedReadBuffer.h"
#include "SkOrderedWriteBuffer.h"
#include "SkPixelRef.h"
#include "SkThread.h"
#include "SkUnPreMultiply.h"
#include "SkUtils.h"
#include "SkPackBits.h"
#include <new>
SK_DEFINE_INST_COUNT(SkBitmap::Allocator)
static bool isPos32Bits(const Sk64& value) {
return !value.isNeg() && value.is32();
}
struct MipLevel {
void* fPixels;
uint32_t fRowBytes;
uint32_t fWidth, fHeight;
};
struct SkBitmap::MipMap : SkNoncopyable {
int32_t fRefCnt;
int fLevelCount;
// MipLevel fLevel[fLevelCount];
// Pixels[]
static MipMap* Alloc(int levelCount, size_t pixelSize) {
if (levelCount < 0) {
return NULL;
}
Sk64 size;
size.setMul(levelCount + 1, sizeof(MipLevel));
size.add(sizeof(MipMap));
size.add(SkToS32(pixelSize));
if (!isPos32Bits(size)) {
return NULL;
}
MipMap* mm = (MipMap*)sk_malloc_throw(size.get32());
mm->fRefCnt = 1;
mm->fLevelCount = levelCount;
return mm;
}
const MipLevel* levels() const { return (const MipLevel*)(this + 1); }
MipLevel* levels() { return (MipLevel*)(this + 1); }
const void* pixels() const { return levels() + fLevelCount; }
void* pixels() { return levels() + fLevelCount; }
void ref() {
if (SK_MaxS32 == sk_atomic_inc(&fRefCnt)) {
sk_throw();
}
}
void unref() {
SkASSERT(fRefCnt > 0);
if (sk_atomic_dec(&fRefCnt) == 1) {
sk_free(this);
}
}
};
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
SkBitmap::SkBitmap() {
sk_bzero(this, sizeof(*this));
}
SkBitmap::SkBitmap(const SkBitmap& src) {
SkDEBUGCODE(src.validate();)
sk_bzero(this, sizeof(*this));
*this = src;
SkDEBUGCODE(this->validate();)
}
SkBitmap::~SkBitmap() {
SkDEBUGCODE(this->validate();)
this->freePixels();
}
SkBitmap& SkBitmap::operator=(const SkBitmap& src) {
if (this != &src) {
this->freePixels();
memcpy(this, &src, sizeof(src));
// inc src reference counts
SkSafeRef(src.fPixelRef);
SkSafeRef(src.fMipMap);
// we reset our locks if we get blown away
fPixelLockCount = 0;
/* The src could be in 3 states
1. no pixelref, in which case we just copy/ref the pixels/ctable
2. unlocked pixelref, pixels/ctable should be null
3. locked pixelref, we should lock the ref again ourselves
*/
if (NULL == fPixelRef) {
// leave fPixels as it is
SkSafeRef(fColorTable); // ref the user's ctable if present
} else { // we have a pixelref, so pixels/ctable reflect it
// ignore the values from the memcpy
fPixels = NULL;
fColorTable = NULL;
// Note that what to for genID is somewhat arbitrary. We have no
// way to track changes to raw pixels across multiple SkBitmaps.
// Would benefit from an SkRawPixelRef type created by
// setPixels.
// Just leave the memcpy'ed one but they'll get out of sync
// as soon either is modified.
}
}
SkDEBUGCODE(this->validate();)
return *this;
}
void SkBitmap::swap(SkBitmap& other) {
SkTSwap(fColorTable, other.fColorTable);
SkTSwap(fPixelRef, other.fPixelRef);
SkTSwap(fPixelRefOffset, other.fPixelRefOffset);
SkTSwap(fPixelLockCount, other.fPixelLockCount);
SkTSwap(fMipMap, other.fMipMap);
SkTSwap(fPixels, other.fPixels);
SkTSwap(fRowBytes, other.fRowBytes);
SkTSwap(fWidth, other.fWidth);
SkTSwap(fHeight, other.fHeight);
SkTSwap(fConfig, other.fConfig);
SkTSwap(fFlags, other.fFlags);
SkTSwap(fBytesPerPixel, other.fBytesPerPixel);
SkDEBUGCODE(this->validate();)
}
void SkBitmap::reset() {
this->freePixels();
sk_bzero(this, sizeof(*this));
}
int SkBitmap::ComputeBytesPerPixel(SkBitmap::Config config) {
int bpp;
switch (config) {
case kNo_Config:
case kA1_Config:
bpp = 0; // not applicable
break;
case kRLE_Index8_Config:
case kA8_Config:
case kIndex8_Config:
bpp = 1;
break;
case kRGB_565_Config:
case kARGB_4444_Config:
bpp = 2;
break;
case kARGB_8888_Config:
bpp = 4;
break;
default:
SkDEBUGFAIL("unknown config");
bpp = 0; // error
break;
}
return bpp;
}
size_t SkBitmap::ComputeRowBytes(Config c, int width) {
if (width < 0) {
return 0;
}
Sk64 rowBytes;
rowBytes.setZero();
switch (c) {
case kNo_Config:
case kRLE_Index8_Config:
break;
case kA1_Config:
rowBytes.set(width);
rowBytes.add(7);
rowBytes.shiftRight(3);
break;
case kA8_Config:
case kIndex8_Config:
rowBytes.set(width);
break;
case kRGB_565_Config:
case kARGB_4444_Config:
rowBytes.set(width);
rowBytes.shiftLeft(1);
break;
case kARGB_8888_Config:
rowBytes.set(width);
rowBytes.shiftLeft(2);
break;
default:
SkDEBUGFAIL("unknown config");
break;
}
return isPos32Bits(rowBytes) ? rowBytes.get32() : 0;
}
Sk64 SkBitmap::ComputeSize64(Config c, int width, int height) {
Sk64 size;
size.setMul(SkToS32(SkBitmap::ComputeRowBytes(c, width)), height);
return size;
}
size_t SkBitmap::ComputeSize(Config c, int width, int height) {
Sk64 size = SkBitmap::ComputeSize64(c, width, height);
return isPos32Bits(size) ? size.get32() : 0;
}
Sk64 SkBitmap::ComputeSafeSize64(Config config,
uint32_t width,
uint32_t height,
size_t rowBytes) {
Sk64 safeSize;
safeSize.setZero();
if (height > 0) {
// TODO: Handle the case where the return value from
// ComputeRowBytes is more than 31 bits.
safeSize.set(SkToS32(ComputeRowBytes(config, width)));
Sk64 sizeAllButLastRow;
sizeAllButLastRow.setMul(height - 1, SkToS32(rowBytes));
safeSize.add(sizeAllButLastRow);
}
SkASSERT(!safeSize.isNeg());
return safeSize;
}
size_t SkBitmap::ComputeSafeSize(Config config,
uint32_t width,
uint32_t height,
size_t rowBytes) {
Sk64 safeSize = ComputeSafeSize64(config, width, height, rowBytes);
return (safeSize.is32() ? safeSize.get32() : 0);
}
void SkBitmap::getBounds(SkRect* bounds) const {
SkASSERT(bounds);
bounds->set(0, 0,
SkIntToScalar(fWidth), SkIntToScalar(fHeight));
}
void SkBitmap::getBounds(SkIRect* bounds) const {
SkASSERT(bounds);
bounds->set(0, 0, fWidth, fHeight);
}
///////////////////////////////////////////////////////////////////////////////
void SkBitmap::setConfig(Config c, int width, int height, size_t rowBytes) {
this->freePixels();
if ((width | height) < 0) {
goto err;
}
if (rowBytes == 0) {
rowBytes = SkBitmap::ComputeRowBytes(c, width);
if (0 == rowBytes && kNo_Config != c) {
goto err;
}
}
fConfig = SkToU8(c);
fWidth = width;
fHeight = height;
fRowBytes = SkToU32(rowBytes);
fBytesPerPixel = (uint8_t)ComputeBytesPerPixel(c);
SkDEBUGCODE(this->validate();)
return;
// if we got here, we had an error, so we reset the bitmap to empty
err:
this->reset();
}
void SkBitmap::updatePixelsFromRef() const {
if (NULL != fPixelRef) {
if (fPixelLockCount > 0) {
SkASSERT(fPixelRef->isLocked());
void* p = fPixelRef->pixels();
if (NULL != p) {
p = (char*)p + fPixelRefOffset;
}
fPixels = p;
SkRefCnt_SafeAssign(fColorTable, fPixelRef->colorTable());
} else {
SkASSERT(0 == fPixelLockCount);
fPixels = NULL;
if (fColorTable) {
fColorTable->unref();
fColorTable = NULL;
}
}
}
}
SkPixelRef* SkBitmap::setPixelRef(SkPixelRef* pr, size_t offset) {
// do this first, we that we never have a non-zero offset with a null ref
if (NULL == pr) {
offset = 0;
}
if (fPixelRef != pr || fPixelRefOffset != offset) {
if (fPixelRef != pr) {
this->freePixels();
SkASSERT(NULL == fPixelRef);
SkSafeRef(pr);
fPixelRef = pr;
}
fPixelRefOffset = offset;
this->updatePixelsFromRef();
}
SkDEBUGCODE(this->validate();)
return pr;
}
void SkBitmap::lockPixels() const {
if (NULL != fPixelRef && 1 == ++fPixelLockCount) {
fPixelRef->lockPixels();
this->updatePixelsFromRef();
}
SkDEBUGCODE(this->validate();)
}
void SkBitmap::unlockPixels() const {
SkASSERT(NULL == fPixelRef || fPixelLockCount > 0);
if (NULL != fPixelRef && 0 == --fPixelLockCount) {
fPixelRef->unlockPixels();
this->updatePixelsFromRef();
}
SkDEBUGCODE(this->validate();)
}
bool SkBitmap::lockPixelsAreWritable() const {
return (fPixelRef) ? fPixelRef->lockPixelsAreWritable() : false;
}
void SkBitmap::setPixels(void* p, SkColorTable* ctable) {
if (NULL == p) {
this->setPixelRef(NULL, 0);
return;
}
Sk64 size = this->getSize64();
SkASSERT(!size.isNeg() && size.is32());
this->setPixelRef(new SkMallocPixelRef(p, size.get32(), ctable, false))->unref();
// since we're already allocated, we lockPixels right away
this->lockPixels();
SkDEBUGCODE(this->validate();)
}
bool SkBitmap::allocPixels(Allocator* allocator, SkColorTable* ctable) {
HeapAllocator stdalloc;
if (NULL == allocator) {
allocator = &stdalloc;
}
return allocator->allocPixelRef(this, ctable);
}
void SkBitmap::freePixels() {
// if we're gonna free the pixels, we certainly need to free the mipmap
this->freeMipMap();
if (fColorTable) {
fColorTable->unref();
fColorTable = NULL;
}
if (NULL != fPixelRef) {
if (fPixelLockCount > 0) {
fPixelRef->unlockPixels();
}
fPixelRef->unref();
fPixelRef = NULL;
fPixelRefOffset = 0;
}
fPixelLockCount = 0;
fPixels = NULL;
}
void SkBitmap::freeMipMap() {
if (fMipMap) {
fMipMap->unref();
fMipMap = NULL;
}
}
uint32_t SkBitmap::getGenerationID() const {
return (fPixelRef) ? fPixelRef->getGenerationID() : 0;
}
void SkBitmap::notifyPixelsChanged() const {
SkASSERT(!this->isImmutable());
if (fPixelRef) {
fPixelRef->notifyPixelsChanged();
}
}
SkGpuTexture* SkBitmap::getTexture() const {
return fPixelRef ? fPixelRef->getTexture() : NULL;
}
///////////////////////////////////////////////////////////////////////////////
/** We explicitly use the same allocator for our pixels that SkMask does,
so that we can freely assign memory allocated by one class to the other.
*/
bool SkBitmap::HeapAllocator::allocPixelRef(SkBitmap* dst,
SkColorTable* ctable) {
Sk64 size = dst->getSize64();
if (size.isNeg() || !size.is32()) {
return false;
}
void* addr = sk_malloc_flags(size.get32(), 0); // returns NULL on failure
if (NULL == addr) {
return false;
}
dst->setPixelRef(new SkMallocPixelRef(addr, size.get32(), ctable))->unref();
// since we're already allocated, we lockPixels right away
dst->lockPixels();
return true;
}
///////////////////////////////////////////////////////////////////////////////
size_t SkBitmap::getSafeSize() const {
// This is intended to be a size_t version of ComputeSafeSize64(), just
// faster. The computation is meant to be identical.
return (fHeight ? ((fHeight - 1) * fRowBytes) +
ComputeRowBytes(getConfig(), fWidth): 0);
}
Sk64 SkBitmap::getSafeSize64() const {
return ComputeSafeSize64(getConfig(), fWidth, fHeight, fRowBytes);
}
bool SkBitmap::copyPixelsTo(void* const dst, size_t dstSize,
size_t dstRowBytes, bool preserveDstPad) const {
if (0 == dstRowBytes) {
dstRowBytes = fRowBytes;
}
if (getConfig() == kRLE_Index8_Config ||
dstRowBytes < ComputeRowBytes(getConfig(), fWidth) ||
dst == NULL || (getPixels() == NULL && pixelRef() == NULL))
return false;
if (!preserveDstPad && static_cast<uint32_t>(dstRowBytes) == fRowBytes) {
size_t safeSize = getSafeSize();
if (safeSize > dstSize || safeSize == 0)
return false;
else {
SkAutoLockPixels lock(*this);
// This implementation will write bytes beyond the end of each row,
// excluding the last row, if the bitmap's stride is greater than
// strictly required by the current config.
memcpy(dst, getPixels(), safeSize);
return true;
}
} else {
// If destination has different stride than us, then copy line by line.
if (ComputeSafeSize(getConfig(), fWidth, fHeight, dstRowBytes) >
dstSize)
return false;
else {
// Just copy what we need on each line.
size_t rowBytes = ComputeRowBytes(getConfig(), fWidth);
SkAutoLockPixels lock(*this);
const uint8_t* srcP = reinterpret_cast<const uint8_t*>(getPixels());
uint8_t* dstP = reinterpret_cast<uint8_t*>(dst);
for (uint32_t row = 0; row < fHeight;
row++, srcP += fRowBytes, dstP += dstRowBytes) {
memcpy(dstP, srcP, rowBytes);
}
return true;
}
}
}
///////////////////////////////////////////////////////////////////////////////
bool SkBitmap::isImmutable() const {
return fPixelRef ? fPixelRef->isImmutable() :
fFlags & kImageIsImmutable_Flag;
}
void SkBitmap::setImmutable() {
if (fPixelRef) {
fPixelRef->setImmutable();
} else {
fFlags |= kImageIsImmutable_Flag;
}
}
bool SkBitmap::isOpaque() const {
switch (fConfig) {
case kNo_Config:
return true;
case kA1_Config:
case kA8_Config:
case kARGB_4444_Config:
case kARGB_8888_Config:
return (fFlags & kImageIsOpaque_Flag) != 0;
case kIndex8_Config:
case kRLE_Index8_Config: {
uint32_t flags = 0;
this->lockPixels();
// if lockPixels failed, we may not have a ctable ptr
if (fColorTable) {
flags = fColorTable->getFlags();
}
this->unlockPixels();
return (flags & SkColorTable::kColorsAreOpaque_Flag) != 0;
}
case kRGB_565_Config:
return true;
default:
SkDEBUGFAIL("unknown bitmap config pased to isOpaque");
return false;
}
}
void SkBitmap::setIsOpaque(bool isOpaque) {
/* we record this regardless of fConfig, though it is ignored in
isOpaque() for configs that can't support per-pixel alpha.
*/
if (isOpaque) {
fFlags |= kImageIsOpaque_Flag;
} else {
fFlags &= ~kImageIsOpaque_Flag;
}
}
bool SkBitmap::isVolatile() const {
return (fFlags & kImageIsVolatile_Flag) != 0;
}
void SkBitmap::setIsVolatile(bool isVolatile) {
if (isVolatile) {
fFlags |= kImageIsVolatile_Flag;
} else {
fFlags &= ~kImageIsVolatile_Flag;
}
}
void* SkBitmap::getAddr(int x, int y) const {
SkASSERT((unsigned)x < (unsigned)this->width());
SkASSERT((unsigned)y < (unsigned)this->height());
char* base = (char*)this->getPixels();
if (base) {
base += y * this->rowBytes();
switch (this->config()) {
case SkBitmap::kARGB_8888_Config:
base += x << 2;
break;
case SkBitmap::kARGB_4444_Config:
case SkBitmap::kRGB_565_Config:
base += x << 1;
break;
case SkBitmap::kA8_Config:
case SkBitmap::kIndex8_Config:
base += x;
break;
case SkBitmap::kA1_Config:
base += x >> 3;
break;
case kRLE_Index8_Config:
SkDEBUGFAIL("Can't return addr for kRLE_Index8_Config");
base = NULL;
break;
default:
SkDEBUGFAIL("Can't return addr for config");
base = NULL;
break;
}
}
return base;
}
SkColor SkBitmap::getColor(int x, int y) const {
SkASSERT((unsigned)x < (unsigned)this->width());
SkASSERT((unsigned)y < (unsigned)this->height());
switch (this->config()) {
case SkBitmap::kA1_Config: {
uint8_t* addr = this->getAddr1(x, y);
uint8_t mask = 1 << (7 - (x % 8));
if (addr[0] & mask) {
return SK_ColorBLACK;
} else {
return 0;
}
}
case SkBitmap::kA8_Config: {
uint8_t* addr = this->getAddr8(x, y);
return SkColorSetA(0, addr[0]);
}
case SkBitmap::kIndex8_Config: {
SkPMColor c = this->getIndex8Color(x, y);
return SkUnPreMultiply::PMColorToColor(c);
}
case SkBitmap::kRGB_565_Config: {
uint16_t* addr = this->getAddr16(x, y);
return SkPixel16ToColor(addr[0]);
}
case SkBitmap::kARGB_4444_Config: {
uint16_t* addr = this->getAddr16(x, y);
SkPMColor c = SkPixel4444ToPixel32(addr[0]);
return SkUnPreMultiply::PMColorToColor(c);
}
case SkBitmap::kARGB_8888_Config: {
uint32_t* addr = this->getAddr32(x, y);
return SkUnPreMultiply::PMColorToColor(addr[0]);
}
case kRLE_Index8_Config: {
uint8_t dst;
const SkBitmap::RLEPixels* rle =
(const SkBitmap::RLEPixels*)this->getPixels();
SkPackBits::Unpack8(&dst, x, 1, rle->packedAtY(y));
return SkUnPreMultiply::PMColorToColor((*fColorTable)[dst]);
}
case kNo_Config:
case kConfigCount:
SkASSERT(false);
return 0;
}
SkASSERT(false); // Not reached.
return 0;
}
bool SkBitmap::ComputeIsOpaque(const SkBitmap& bm) {
SkAutoLockPixels alp(bm);
if (!bm.getPixels()) {
return false;
}
const int height = bm.height();
const int width = bm.width();
switch (bm.config()) {
case SkBitmap::kA1_Config: {
// TODO
} break;
case SkBitmap::kA8_Config: {
unsigned a = 0xFF;
for (int y = 0; y < height; ++y) {
const uint8_t* row = bm.getAddr8(0, y);
for (int x = 0; x < width; ++x) {
a &= row[x];
}
if (0xFF != a) {
return false;
}
}
return true;
} break;
case kRLE_Index8_Config:
case SkBitmap::kIndex8_Config: {
SkAutoLockColors alc(bm);
const SkPMColor* table = alc.colors();
if (!table) {
return false;
}
SkPMColor c = (SkPMColor)~0;
for (int i = bm.getColorTable()->count() - 1; i >= 0; --i) {
c &= table[i];
}
return 0xFF == SkGetPackedA32(c);
} break;
case SkBitmap::kRGB_565_Config:
return true;
break;
case SkBitmap::kARGB_4444_Config: {
unsigned c = 0xFFFF;
for (int y = 0; y < height; ++y) {
const SkPMColor16* row = bm.getAddr16(0, y);
for (int x = 0; x < width; ++x) {
c &= row[x];
}
if (0xF != SkGetPackedA4444(c)) {
return false;
}
}
return true;
} break;
case SkBitmap::kARGB_8888_Config: {
SkPMColor c = (SkPMColor)~0;
for (int y = 0; y < height; ++y) {
const SkPMColor* row = bm.getAddr32(0, y);
for (int x = 0; x < width; ++x) {
c &= row[x];
}
if (0xFF != SkGetPackedA32(c)) {
return false;
}
}
return true;
}
default:
break;
}
return false;
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
void SkBitmap::eraseARGB(U8CPU a, U8CPU r, U8CPU g, U8CPU b) const {
SkDEBUGCODE(this->validate();)
if (0 == fWidth || 0 == fHeight ||
kNo_Config == fConfig || kIndex8_Config == fConfig) {
return;
}
SkAutoLockPixels alp(*this);
// perform this check after the lock call
if (!this->readyToDraw()) {
return;
}
int height = fHeight;
const int width = fWidth;
const int rowBytes = fRowBytes;
// make rgb premultiplied
if (255 != a) {
r = SkAlphaMul(r, a);
g = SkAlphaMul(g, a);
b = SkAlphaMul(b, a);
}
switch (fConfig) {
case kA1_Config: {
uint8_t* p = (uint8_t*)fPixels;
const int count = (width + 7) >> 3;
a = (a >> 7) ? 0xFF : 0;
SkASSERT(count <= rowBytes);
while (--height >= 0) {
memset(p, a, count);
p += rowBytes;
}
break;
}
case kA8_Config: {
uint8_t* p = (uint8_t*)fPixels;
while (--height >= 0) {
memset(p, a, width);
p += rowBytes;
}
break;
}
case kARGB_4444_Config:
case kRGB_565_Config: {
uint16_t* p = (uint16_t*)fPixels;
uint16_t v;
if (kARGB_4444_Config == fConfig) {
v = SkPackARGB4444(a >> 4, r >> 4, g >> 4, b >> 4);
} else { // kRGB_565_Config
v = SkPackRGB16(r >> (8 - SK_R16_BITS), g >> (8 - SK_G16_BITS),
b >> (8 - SK_B16_BITS));
}
while (--height >= 0) {
sk_memset16(p, v, width);
p = (uint16_t*)((char*)p + rowBytes);
}
break;
}
case kARGB_8888_Config: {
uint32_t* p = (uint32_t*)fPixels;
uint32_t v = SkPackARGB32(a, r, g, b);
while (--height >= 0) {
sk_memset32(p, v, width);
p = (uint32_t*)((char*)p + rowBytes);
}
break;
}
}
this->notifyPixelsChanged();
}
//////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////////////////
#define SUB_OFFSET_FAILURE ((size_t)-1)
/**
* Based on the Config and rowBytes() of bm, return the offset into an SkPixelRef of the pixel at
* (x, y).
* Note that the SkPixelRef does not need to be set yet. deepCopyTo takes advantage of this fact.
* Also note that (x, y) may be outside the range of (0 - width(), 0 - height()), so long as it is
* within the bounds of the SkPixelRef being used.
*/
static size_t getSubOffset(const SkBitmap& bm, int x, int y) {
switch (bm.getConfig()) {
case SkBitmap::kA8_Config:
case SkBitmap:: kIndex8_Config:
// x is fine as is for the calculation
break;
case SkBitmap::kRGB_565_Config:
case SkBitmap::kARGB_4444_Config:
x <<= 1;
break;
case SkBitmap::kARGB_8888_Config:
x <<= 2;
break;
case SkBitmap::kNo_Config:
case SkBitmap::kA1_Config:
default:
return SUB_OFFSET_FAILURE;
}
return y * bm.rowBytes() + x;
}
/**
* Using the pixelRefOffset(), rowBytes(), and Config of bm, determine the (x, y) coordinate of the
* upper left corner of bm relative to its SkPixelRef.
* x and y must be non-NULL.
*/
static bool getUpperLeftFromOffset(const SkBitmap& bm, int32_t* x, int32_t* y) {
SkASSERT(x != NULL && y != NULL);
const size_t offset = bm.pixelRefOffset();
if (0 == offset) {
*x = *y = 0;
return true;
}
// Use integer division to find the correct y position.
*y = SkToS32(offset / bm.rowBytes());
// The remainder will be the x position, after we reverse getSubOffset.
*x = SkToS32(offset % bm.rowBytes());
switch (bm.getConfig()) {
case SkBitmap::kA8_Config:
// Fall through.
case SkBitmap::kIndex8_Config:
// x is unmodified
break;
case SkBitmap::kRGB_565_Config:
// Fall through.
case SkBitmap::kARGB_4444_Config:
*x >>= 1;
break;
case SkBitmap::kARGB_8888_Config:
*x >>= 2;
break;
case SkBitmap::kNo_Config:
// Fall through.
case SkBitmap::kA1_Config:
// Fall through.
default:
return false;
}
return true;
}
bool SkBitmap::extractSubset(SkBitmap* result, const SkIRect& subset) const {
SkDEBUGCODE(this->validate();)
if (NULL == result || NULL == fPixelRef) {
return false; // no src pixels
}
SkIRect srcRect, r;
srcRect.set(0, 0, this->width(), this->height());
if (!r.intersect(srcRect, subset)) {
return false; // r is empty (i.e. no intersection)
}
if (fPixelRef->getTexture() != NULL) {
// Do a deep copy
SkPixelRef* pixelRef = fPixelRef->deepCopy(this->config(), &subset);
if (pixelRef != NULL) {
SkBitmap dst;
dst.setConfig(this->config(), subset.width(), subset.height());
dst.setIsVolatile(this->isVolatile());
dst.setIsOpaque(this->isOpaque());
dst.setPixelRef(pixelRef)->unref();
SkDEBUGCODE(dst.validate());
result->swap(dst);
return true;
}
}
if (kRLE_Index8_Config == fConfig) {
SkAutoLockPixels alp(*this);
// don't call readyToDraw(), since we can operate w/o a colortable
// at this stage
if (this->getPixels() == NULL) {
return false;
}
SkBitmap bm;
bm.setConfig(kIndex8_Config, r.width(), r.height());
bm.allocPixels(this->getColorTable());
if (NULL == bm.getPixels()) {
return false;
}
const RLEPixels* rle = (const RLEPixels*)this->getPixels();
uint8_t* dst = bm.getAddr8(0, 0);
const int width = bm.width();
const size_t rowBytes = bm.rowBytes();
for (int y = r.fTop; y < r.fBottom; y++) {
SkPackBits::Unpack8(dst, r.fLeft, width, rle->packedAtY(y));
dst += rowBytes;
}
result->swap(bm);
return true;
}
// If the upper left of the rectangle was outside the bounds of this SkBitmap, we should have
// exited above.
SkASSERT(static_cast<unsigned>(r.fLeft) < static_cast<unsigned>(this->width()));
SkASSERT(static_cast<unsigned>(r.fTop) < static_cast<unsigned>(this->height()));
size_t offset = getSubOffset(*this, r.fLeft, r.fTop);
if (SUB_OFFSET_FAILURE == offset) {
return false; // config not supported
}
SkBitmap dst;
dst.setConfig(this->config(), r.width(), r.height(), this->rowBytes());
dst.setIsVolatile(this->isVolatile());
dst.setIsOpaque(this->isOpaque());
if (fPixelRef) {
// share the pixelref with a custom offset
dst.setPixelRef(fPixelRef, fPixelRefOffset + offset);
}
SkDEBUGCODE(dst.validate();)
// we know we're good, so commit to result
result->swap(dst);
return true;
}
///////////////////////////////////////////////////////////////////////////////
#include "SkCanvas.h"
#include "SkPaint.h"
bool SkBitmap::canCopyTo(Config dstConfig) const {
if (this->getConfig() == kNo_Config) {
return false;
}
bool sameConfigs = (this->config() == dstConfig);
switch (dstConfig) {
case kA8_Config:
case kARGB_4444_Config:
case kRGB_565_Config:
case kARGB_8888_Config:
break;
case kA1_Config:
case kIndex8_Config:
if (!sameConfigs) {
return false;
}
break;
default:
return false;
}
// do not copy src if srcConfig == kA1_Config while dstConfig != kA1_Config
if (this->getConfig() == kA1_Config && !sameConfigs) {
return false;
}
return true;
}
bool SkBitmap::copyTo(SkBitmap* dst, Config dstConfig, Allocator* alloc) const {
if (!this->canCopyTo(dstConfig)) {
return false;
}
// if we have a texture, first get those pixels
SkBitmap tmpSrc;
const SkBitmap* src = this;
if (fPixelRef) {
SkIRect subset;
if (getUpperLeftFromOffset(*this, &subset.fLeft, &subset.fTop)) {
subset.fRight = subset.fLeft + fWidth;
subset.fBottom = subset.fTop + fHeight;
if (fPixelRef->readPixels(&tmpSrc, &subset)) {
SkASSERT(tmpSrc.width() == this->width());
SkASSERT(tmpSrc.height() == this->height());
// did we get lucky and we can just return tmpSrc?
if (tmpSrc.config() == dstConfig && NULL == alloc) {
dst->swap(tmpSrc);
if (dst->pixelRef() && this->config() == dstConfig) {
dst->pixelRef()->fGenerationID = fPixelRef->getGenerationID();
}
return true;
}
// fall through to the raster case
src = &tmpSrc;
}
}
}
// we lock this now, since we may need its colortable
SkAutoLockPixels srclock(*src);
if (!src->readyToDraw()) {
return false;
}
SkBitmap tmpDst;
tmpDst.setConfig(dstConfig, src->width(), src->height());
// allocate colortable if srcConfig == kIndex8_Config
SkColorTable* ctable = (dstConfig == kIndex8_Config) ?
new SkColorTable(*src->getColorTable()) : NULL;
SkAutoUnref au(ctable);
if (!tmpDst.allocPixels(alloc, ctable)) {
return false;
}
if (!tmpDst.readyToDraw()) {
// allocator/lock failed
return false;
}
/* do memcpy for the same configs cases, else use drawing
*/
if (src->config() == dstConfig) {
if (tmpDst.getSize() == src->getSize()) {
memcpy(tmpDst.getPixels(), src->getPixels(), src->getSafeSize());
SkPixelRef* pixelRef = tmpDst.pixelRef();
if (pixelRef != NULL) {
pixelRef->fGenerationID = this->getGenerationID();
}
} else {
const char* srcP = reinterpret_cast<const char*>(src->getPixels());
char* dstP = reinterpret_cast<char*>(tmpDst.getPixels());
// to be sure we don't read too much, only copy our logical pixels
size_t bytesToCopy = tmpDst.width() * tmpDst.bytesPerPixel();
for (int y = 0; y < tmpDst.height(); y++) {
memcpy(dstP, srcP, bytesToCopy);
srcP += src->rowBytes();
dstP += tmpDst.rowBytes();
}
}
} else {
// if the src has alpha, we have to clear the dst first
if (!src->isOpaque()) {
tmpDst.eraseColor(SK_ColorTRANSPARENT);
}
SkCanvas canvas(tmpDst);
SkPaint paint;
paint.setDither(true);
canvas.drawBitmap(*src, 0, 0, &paint);
}
tmpDst.setIsOpaque(src->isOpaque());
dst->swap(tmpDst);
return true;
}
bool SkBitmap::deepCopyTo(SkBitmap* dst, Config dstConfig) const {
if (!this->canCopyTo(dstConfig)) {
return false;
}
// If we have a PixelRef, and it supports deep copy, use it.
// Currently supported only by texture-backed bitmaps.
if (fPixelRef) {
SkPixelRef* pixelRef = fPixelRef->deepCopy(dstConfig);
if (pixelRef) {
uint32_t rowBytes;
if (dstConfig == fConfig) {
pixelRef->fGenerationID = fPixelRef->getGenerationID();
// Use the same rowBytes as the original.
rowBytes = fRowBytes;
} else {
// With the new config, an appropriate fRowBytes will be computed by setConfig.
rowBytes = 0;
}
dst->setConfig(dstConfig, fWidth, fHeight, rowBytes);
size_t pixelRefOffset;
if (0 == fPixelRefOffset || dstConfig == fConfig) {
// Use the same offset as the original.
pixelRefOffset = fPixelRefOffset;
} else {
// Find the correct offset in the new config. This needs to be done after calling
// setConfig so dst's fConfig and fRowBytes have been set properly.
int32_t x, y;
if (!getUpperLeftFromOffset(*this, &x, &y)) {
return false;
}
pixelRefOffset = getSubOffset(*dst, x, y);
if (SUB_OFFSET_FAILURE == pixelRefOffset) {
return false;
}
}
dst->setPixelRef(pixelRef, pixelRefOffset)->unref();
return true;
}
}
if (this->getTexture()) {
return false;
} else {
return this->copyTo(dst, dstConfig, NULL);
}
}
///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////
static void downsampleby2_proc32(SkBitmap* dst, int x, int y,
const SkBitmap& src) {
x <<= 1;
y <<= 1;
const SkPMColor* p = src.getAddr32(x, y);
const SkPMColor* baseP = p;
SkPMColor c, ag, rb;
c = *p; ag = (c >> 8) & 0xFF00FF; rb = c & 0xFF00FF;
if (x < src.width() - 1) {
p += 1;
}
c = *p; ag += (c >> 8) & 0xFF00FF; rb += c & 0xFF00FF;
p = baseP;
if (y < src.height() - 1) {
p += src.rowBytes() >> 2;
}
c = *p; ag += (c >> 8) & 0xFF00FF; rb += c & 0xFF00FF;
if (x < src.width() - 1) {
p += 1;
}
c = *p; ag += (c >> 8) & 0xFF00FF; rb += c & 0xFF00FF;
*dst->getAddr32(x >> 1, y >> 1) =
((rb >> 2) & 0xFF00FF) | ((ag << 6) & 0xFF00FF00);
}
static inline uint32_t expand16(U16CPU c) {
return (c & ~SK_G16_MASK_IN_PLACE) | ((c & SK_G16_MASK_IN_PLACE) << 16);
}
// returns dirt in the top 16bits, but we don't care, since we only
// store the low 16bits.
static inline U16CPU pack16(uint32_t c) {
return (c & ~SK_G16_MASK_IN_PLACE) | ((c >> 16) & SK_G16_MASK_IN_PLACE);
}
static void downsampleby2_proc16(SkBitmap* dst, int x, int y,
const SkBitmap& src) {
x <<= 1;
y <<= 1;
const uint16_t* p = src.getAddr16(x, y);
const uint16_t* baseP = p;
SkPMColor c;
c = expand16(*p);
if (x < src.width() - 1) {
p += 1;
}
c += expand16(*p);
p = baseP;
if (y < src.height() - 1) {
p += src.rowBytes() >> 1;
}
c += expand16(*p);
if (x < src.width() - 1) {
p += 1;
}
c += expand16(*p);
*dst->getAddr16(x >> 1, y >> 1) = (uint16_t)pack16(c >> 2);
}
static uint32_t expand4444(U16CPU c) {
return (c & 0xF0F) | ((c & ~0xF0F) << 12);
}
static U16CPU collaps4444(uint32_t c) {
return (c & 0xF0F) | ((c >> 12) & ~0xF0F);
}
static void downsampleby2_proc4444(SkBitmap* dst, int x, int y,
const SkBitmap& src) {
x <<= 1;
y <<= 1;
const uint16_t* p = src.getAddr16(x, y);
const uint16_t* baseP = p;
uint32_t c;
c = expand4444(*p);
if (x < src.width() - 1) {
p += 1;
}
c += expand4444(*p);
p = baseP;
if (y < src.height() - 1) {
p += src.rowBytes() >> 1;
}
c += expand4444(*p);
if (x < src.width() - 1) {
p += 1;
}
c += expand4444(*p);
*dst->getAddr16(x >> 1, y >> 1) = (uint16_t)collaps4444(c >> 2);
}
void SkBitmap::buildMipMap(bool forceRebuild) {
if (forceRebuild)
this->freeMipMap();
else if (fMipMap)
return; // we're already built
SkASSERT(NULL == fMipMap);
void (*proc)(SkBitmap* dst, int x, int y, const SkBitmap& src);
const SkBitmap::Config config = this->getConfig();
switch (config) {
case kARGB_8888_Config:
proc = downsampleby2_proc32;
break;
case kRGB_565_Config:
proc = downsampleby2_proc16;
break;
case kARGB_4444_Config:
proc = downsampleby2_proc4444;
break;
case kIndex8_Config:
case kA8_Config:
default:
return; // don't build mipmaps for these configs
}
SkAutoLockPixels alp(*this);
if (!this->readyToDraw()) {
return;
}
// whip through our loop to compute the exact size needed
size_t size = 0;
int maxLevels = 0;
{
int width = this->width();
int height = this->height();
for (;;) {
width >>= 1;
height >>= 1;
if (0 == width || 0 == height) {
break;
}
size += ComputeRowBytes(config, width) * height;
maxLevels += 1;
}
}
// nothing to build
if (0 == maxLevels) {
return;
}
SkBitmap srcBM(*this);
srcBM.lockPixels();
if (!srcBM.readyToDraw()) {
return;
}
MipMap* mm = MipMap::Alloc(maxLevels, size);
if (NULL == mm) {
return;
}
MipLevel* level = mm->levels();
uint8_t* addr = (uint8_t*)mm->pixels();
int width = this->width();
int height = this->height();
uint32_t rowBytes;
SkBitmap dstBM;
for (int i = 0; i < maxLevels; i++) {
width >>= 1;
height >>= 1;
rowBytes = SkToU32(ComputeRowBytes(config, width));
level[i].fPixels = addr;
level[i].fWidth = width;
level[i].fHeight = height;
level[i].fRowBytes = rowBytes;
dstBM.setConfig(config, width, height, rowBytes);
dstBM.setPixels(addr);
srcBM.lockPixels();
for (int y = 0; y < height; y++) {
for (int x = 0; x < width; x++) {
proc(&dstBM, x, y, srcBM);
}
}
srcBM.unlockPixels();
srcBM = dstBM;
addr += height * rowBytes;
}
SkASSERT(addr == (uint8_t*)mm->pixels() + size);
fMipMap = mm;
}
bool SkBitmap::hasMipMap() const {
return fMipMap != NULL;
}
int SkBitmap::extractMipLevel(SkBitmap* dst, SkFixed sx, SkFixed sy) {
if (NULL == fMipMap) {
return 0;
}
int level = ComputeMipLevel(sx, sy) >> 16;
SkASSERT(level >= 0);
if (level <= 0) {
return 0;
}
if (level >= fMipMap->fLevelCount) {
level = fMipMap->fLevelCount - 1;
}
if (dst) {
const MipLevel& mip = fMipMap->levels()[level - 1];
dst->setConfig((SkBitmap::Config)this->config(),
mip.fWidth, mip.fHeight, mip.fRowBytes);
dst->setPixels(mip.fPixels);
}
return level;
}
SkFixed SkBitmap::ComputeMipLevel(SkFixed sx, SkFixed sy) {
sx = SkAbs32(sx);
sy = SkAbs32(sy);
if (sx < sy) {
sx = sy;
}
if (sx < SK_Fixed1) {
return 0;
}
int clz = SkCLZ(sx);
SkASSERT(clz >= 1 && clz <= 15);
return SkIntToFixed(15 - clz) + ((unsigned)(sx << (clz + 1)) >> 16);
}
///////////////////////////////////////////////////////////////////////////////
static bool GetBitmapAlpha(const SkBitmap& src, uint8_t* SK_RESTRICT alpha,
int alphaRowBytes) {
SkASSERT(alpha != NULL);
SkASSERT(alphaRowBytes >= src.width());
SkBitmap::Config config = src.getConfig();
int w = src.width();
int h = src.height();
size_t rb = src.rowBytes();
SkAutoLockPixels alp(src);
if (!src.readyToDraw()) {
// zero out the alpha buffer and return
while (--h >= 0) {
memset(alpha, 0, w);
alpha += alphaRowBytes;
}
return false;
}
if (SkBitmap::kA8_Config == config && !src.isOpaque()) {
const uint8_t* s = src.getAddr8(0, 0);
while (--h >= 0) {
memcpy(alpha, s, w);
s += rb;
alpha += alphaRowBytes;
}
} else if (SkBitmap::kARGB_8888_Config == config && !src.isOpaque()) {
const SkPMColor* SK_RESTRICT s = src.getAddr32(0, 0);
while (--h >= 0) {
for (int x = 0; x < w; x++) {
alpha[x] = SkGetPackedA32(s[x]);
}
s = (const SkPMColor*)((const char*)s + rb);
alpha += alphaRowBytes;
}
} else if (SkBitmap::kARGB_4444_Config == config && !src.isOpaque()) {
const SkPMColor16* SK_RESTRICT s = src.getAddr16(0, 0);
while (--h >= 0) {
for (int x = 0; x < w; x++) {
alpha[x] = SkPacked4444ToA32(s[x]);
}
s = (const SkPMColor16*)((const char*)s + rb);
alpha += alphaRowBytes;
}
} else if (SkBitmap::kIndex8_Config == config && !src.isOpaque()) {
SkColorTable* ct = src.getColorTable();
if (ct) {
const SkPMColor* SK_RESTRICT table = ct->lockColors();
const uint8_t* SK_RESTRICT s = src.getAddr8(0, 0);
while (--h >= 0) {
for (int x = 0; x < w; x++) {
alpha[x] = SkGetPackedA32(table[s[x]]);
}
s += rb;
alpha += alphaRowBytes;
}
ct->unlockColors(false);
}
} else { // src is opaque, so just fill alpha[] with 0xFF
memset(alpha, 0xFF, h * alphaRowBytes);
}
return true;
}
#include "SkPaint.h"
#include "SkMaskFilter.h"
#include "SkMatrix.h"
bool SkBitmap::extractAlpha(SkBitmap* dst, const SkPaint* paint,
Allocator *allocator, SkIPoint* offset) const {
SkDEBUGCODE(this->validate();)
SkBitmap tmpBitmap;
SkMatrix identity;
SkMask srcM, dstM;
srcM.fBounds.set(0, 0, this->width(), this->height());
srcM.fRowBytes = SkAlign4(this->width());
srcM.fFormat = SkMask::kA8_Format;
SkMaskFilter* filter = paint ? paint->getMaskFilter() : NULL;
// compute our (larger?) dst bounds if we have a filter
if (NULL != filter) {
identity.reset();
srcM.fImage = NULL;
if (!filter->filterMask(&dstM, srcM, identity, NULL)) {
goto NO_FILTER_CASE;
}
dstM.fRowBytes = SkAlign4(dstM.fBounds.width());
} else {
NO_FILTER_CASE:
tmpBitmap.setConfig(SkBitmap::kA8_Config, this->width(), this->height(),
srcM.fRowBytes);
if (!tmpBitmap.allocPixels(allocator, NULL)) {
// Allocation of pixels for alpha bitmap failed.
SkDebugf("extractAlpha failed to allocate (%d,%d) alpha bitmap\n",
tmpBitmap.width(), tmpBitmap.height());
return false;
}
GetBitmapAlpha(*this, tmpBitmap.getAddr8(0, 0), srcM.fRowBytes);
if (offset) {
offset->set(0, 0);
}
tmpBitmap.swap(*dst);
return true;
}
srcM.fImage = SkMask::AllocImage(srcM.computeImageSize());
SkAutoMaskFreeImage srcCleanup(srcM.fImage);
GetBitmapAlpha(*this, srcM.fImage, srcM.fRowBytes);
if (!filter->filterMask(&dstM, srcM, identity, NULL)) {
goto NO_FILTER_CASE;
}
SkAutoMaskFreeImage dstCleanup(dstM.fImage);
tmpBitmap.setConfig(SkBitmap::kA8_Config, dstM.fBounds.width(),
dstM.fBounds.height(), dstM.fRowBytes);
if (!tmpBitmap.allocPixels(allocator, NULL)) {
// Allocation of pixels for alpha bitmap failed.
SkDebugf("extractAlpha failed to allocate (%d,%d) alpha bitmap\n",
tmpBitmap.width(), tmpBitmap.height());
return false;
}
memcpy(tmpBitmap.getPixels(), dstM.fImage, dstM.computeImageSize());
if (offset) {
offset->set(dstM.fBounds.fLeft, dstM.fBounds.fTop);
}
SkDEBUGCODE(tmpBitmap.validate();)
tmpBitmap.swap(*dst);
return true;
}
///////////////////////////////////////////////////////////////////////////////
enum {
SERIALIZE_PIXELTYPE_NONE,
SERIALIZE_PIXELTYPE_REF_DATA
};
void SkBitmap::flatten(SkFlattenableWriteBuffer& buffer) const {
buffer.writeInt(fWidth);
buffer.writeInt(fHeight);
buffer.writeInt(fRowBytes);
buffer.writeInt(fConfig);
buffer.writeBool(this->isOpaque());
if (fPixelRef) {
if (fPixelRef->getFactory()) {
buffer.writeInt(SERIALIZE_PIXELTYPE_REF_DATA);
buffer.writeUInt(SkToU32(fPixelRefOffset));
buffer.writeFlattenable(fPixelRef);
return;
}
// if we get here, we can't record the pixels
buffer.writeInt(SERIALIZE_PIXELTYPE_NONE);
} else {
buffer.writeInt(SERIALIZE_PIXELTYPE_NONE);
}
}
void SkBitmap::unflatten(SkFlattenableReadBuffer& buffer) {
this->reset();
int width = buffer.readInt();
int height = buffer.readInt();
int rowBytes = buffer.readInt();
int config = buffer.readInt();
this->setConfig((Config)config, width, height, rowBytes);
this->setIsOpaque(buffer.readBool());
int reftype = buffer.readInt();
switch (reftype) {
case SERIALIZE_PIXELTYPE_REF_DATA: {
size_t offset = buffer.readUInt();
SkPixelRef* pr = buffer.readFlattenableT<SkPixelRef>();
SkSafeUnref(this->setPixelRef(pr, offset));
break;
}
case SERIALIZE_PIXELTYPE_NONE:
break;
default:
SkDEBUGFAIL("unrecognized pixeltype in serialized data");
sk_throw();
}
}
///////////////////////////////////////////////////////////////////////////////
SkBitmap::RLEPixels::RLEPixels(int width, int height) {
fHeight = height;
fYPtrs = (uint8_t**)sk_malloc_throw(height * sizeof(uint8_t*));
sk_bzero(fYPtrs, height * sizeof(uint8_t*));
}
SkBitmap::RLEPixels::~RLEPixels() {
sk_free(fYPtrs);
}
///////////////////////////////////////////////////////////////////////////////
#ifdef SK_DEBUG
void SkBitmap::validate() const {
SkASSERT(fConfig < kConfigCount);
SkASSERT(fRowBytes >= (unsigned)ComputeRowBytes((Config)fConfig, fWidth));
SkASSERT(fFlags <= (kImageIsOpaque_Flag | kImageIsVolatile_Flag | kImageIsImmutable_Flag));
SkASSERT(fPixelLockCount >= 0);
SkASSERT(NULL == fColorTable || (unsigned)fColorTable->getRefCnt() < 10000);
SkASSERT((uint8_t)ComputeBytesPerPixel((Config)fConfig) == fBytesPerPixel);
#if 0 // these asserts are not thread-correct, so disable for now
if (fPixelRef) {
if (fPixelLockCount > 0) {
SkASSERT(fPixelRef->isLocked());
} else {
SkASSERT(NULL == fPixels);
SkASSERT(NULL == fColorTable);
}
}
#endif
}
#endif
#ifdef SK_DEVELOPER
void SkBitmap::toString(SkString* str) const {
static const char* gConfigNames[kConfigCount] = {
"NONE", "A1", "A8", "INDEX8", "565", "4444", "8888", "RLE"
};
str->appendf("bitmap: ((%d, %d) %s", this->width(), this->height(),
gConfigNames[this->config()]);
str->append(" (");
if (this->isOpaque()) {
str->append("opaque");
} else {
str->append("transparent");
}
if (this->isImmutable()) {
str->append(", immutable");
} else {
str->append(", not-immutable");
}
str->append(")");
SkPixelRef* pr = this->pixelRef();
if (NULL == pr) {
// show null or the explicit pixel address (rare)
str->appendf(" pixels:%p", this->getPixels());
} else {
const char* uri = pr->getURI();
if (NULL != uri) {
str->appendf(" uri:\"%s\"", uri);
} else {
str->appendf(" pixelref:%p", pr);
}
}
str->append(")");
}
#endif
| bsd-3-clause |
stephens2424/php | testdata/fuzzdir/corpus/tests_lang_foreachLoop.010.php | 956 | <?php
$a = array(1,2,3);
$container = array(&$a);
// From php.net:
// "Unless the array is referenced, foreach operates on a copy of
// the specified array and not the array itself."
// At this point, the array $a is referenced.
// The following line ensures $a is no longer references as a consequence
// of running the 'destructor' on $container.
$container = null;
// At this point the array $a is no longer referenced, so foreach should operate on a copy of the array.
// However, P8 does not invoke 'destructors' when refcount is decremented to 0.
// Consequently, $a thinks it is still referenced, and foreach will operate on the array itself.
// This provokes a difference in behaviour when changing the number of elements in the array while
// iterating over it.
$i=0;
foreach ($a as $v) {
array_push($a, 'new');
var_dump($v);
if (++$i>10) {
echo "Infinite loop detected\n";
break;
}
}
?>
| bsd-3-clause |
aam/engine | shell/platform/windows/keyboard_key_channel_handler_unittests.cc | 6603 | // Copyright 2013 The Flutter Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "flutter/shell/platform/windows/keyboard_key_channel_handler.h"
#include <memory>
#include "flutter/shell/platform/common/json_message_codec.h"
#include "flutter/shell/platform/windows/flutter_windows_view.h"
#include "flutter/shell/platform/windows/testing/test_binary_messenger.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
namespace flutter {
namespace testing {
namespace {
static constexpr char kScanCodeKey[] = "scanCode";
static constexpr char kCharacterCodePointKey[] = "characterCodePoint";
static constexpr int kHandledScanCode = 0x14;
static constexpr int kUnhandledScanCode = 0x15;
static constexpr int kUnhandledScanCodeExtended = 0xe015;
static std::unique_ptr<std::vector<uint8_t>> CreateResponse(bool handled) {
auto response_doc =
std::make_unique<rapidjson::Document>(rapidjson::kObjectType);
auto& allocator = response_doc->GetAllocator();
response_doc->AddMember("handled", handled, allocator);
return JsonMessageCodec::GetInstance().EncodeMessage(*response_doc);
}
} // namespace
TEST(KeyboardKeyChannelHandlerTest, KeyboardHookHandling) {
auto handled_message = CreateResponse(true);
auto unhandled_message = CreateResponse(false);
int received_scancode = 0;
TestBinaryMessenger messenger(
[&received_scancode, &handled_message, &unhandled_message](
const std::string& channel, const uint8_t* message,
size_t message_size, BinaryReply reply) {
if (channel == "flutter/keyevent") {
auto message_doc = JsonMessageCodec::GetInstance().DecodeMessage(
message, message_size);
received_scancode = (*message_doc)[kScanCodeKey].GetInt();
if (received_scancode == kHandledScanCode) {
reply(handled_message->data(), handled_message->size());
} else {
reply(unhandled_message->data(), unhandled_message->size());
}
}
});
KeyboardKeyChannelHandler handler(&messenger);
bool last_handled = false;
handler.KeyboardHook(
64, kHandledScanCode, WM_KEYDOWN, L'a', false, false,
[&last_handled](bool handled) { last_handled = handled; });
EXPECT_EQ(received_scancode, kHandledScanCode);
EXPECT_EQ(last_handled, true);
received_scancode = 0;
handler.KeyboardHook(
64, kUnhandledScanCode, WM_KEYDOWN, L'b', false, false,
[&last_handled](bool handled) { last_handled = handled; });
EXPECT_EQ(received_scancode, kUnhandledScanCode);
EXPECT_EQ(last_handled, false);
received_scancode = 0;
handler.KeyboardHook(
64, kHandledScanCode, WM_SYSKEYDOWN, L'a', false, false,
[&last_handled](bool handled) { last_handled = handled; });
EXPECT_EQ(received_scancode, kHandledScanCode);
EXPECT_EQ(last_handled, true);
received_scancode = 0;
handler.KeyboardHook(
64, kUnhandledScanCode, WM_SYSKEYDOWN, L'c', false, false,
[&last_handled](bool handled) { last_handled = handled; });
EXPECT_EQ(received_scancode, kUnhandledScanCode);
EXPECT_EQ(last_handled, false);
}
TEST(KeyboardKeyChannelHandlerTest, ExtendedKeysAreSentToRedispatch) {
auto handled_message = CreateResponse(true);
auto unhandled_message = CreateResponse(false);
int received_scancode = 0;
TestBinaryMessenger messenger(
[&received_scancode, &handled_message, &unhandled_message](
const std::string& channel, const uint8_t* message,
size_t message_size, BinaryReply reply) {
if (channel == "flutter/keyevent") {
auto message_doc = JsonMessageCodec::GetInstance().DecodeMessage(
message, message_size);
received_scancode = (*message_doc)[kScanCodeKey].GetInt();
if (received_scancode == kHandledScanCode) {
reply(handled_message->data(), handled_message->size());
} else {
reply(unhandled_message->data(), unhandled_message->size());
}
}
});
KeyboardKeyChannelHandler handler(&messenger);
bool last_handled = true;
// Extended key flag is passed to redispatched events if set.
handler.KeyboardHook(
64, kUnhandledScanCode, WM_KEYDOWN, L'b', true, false,
[&last_handled](bool handled) { last_handled = handled; });
EXPECT_EQ(last_handled, false);
EXPECT_EQ(received_scancode, kUnhandledScanCodeExtended);
last_handled = true;
// Extended key flag is not passed to redispatched events if not set.
handler.KeyboardHook(
64, kUnhandledScanCode, WM_KEYDOWN, L'b', false, false,
[&last_handled](bool handled) { last_handled = handled; });
EXPECT_EQ(last_handled, false);
EXPECT_EQ(received_scancode, kUnhandledScanCode);
}
TEST(KeyboardKeyChannelHandlerTest, DeadKeysDoNotCrash) {
bool received = false;
TestBinaryMessenger messenger(
[&received](const std::string& channel, const uint8_t* message,
size_t message_size, BinaryReply reply) {
if (channel == "flutter/keyevent") {
auto message_doc = JsonMessageCodec::GetInstance().DecodeMessage(
message, message_size);
uint32_t character = (*message_doc)[kCharacterCodePointKey].GetUint();
EXPECT_EQ(character, (uint32_t)'^');
received = true;
}
return true;
});
KeyboardKeyChannelHandler handler(&messenger);
// Extended key flag is passed to redispatched events if set.
handler.KeyboardHook(0xDD, 0x1a, WM_KEYDOWN, 0x8000005E, false, false,
[](bool handled) {});
// EXPECT is done during the callback above.
EXPECT_TRUE(received);
}
TEST(KeyboardKeyChannelHandlerTest, EmptyResponsesDoNotCrash) {
bool received = false;
TestBinaryMessenger messenger(
[&received](const std::string& channel, const uint8_t* message,
size_t message_size, BinaryReply reply) {
if (channel == "flutter/keyevent") {
std::string empty_message = "";
std::vector<uint8_t> empty_response(empty_message.begin(),
empty_message.end());
reply(empty_response.data(), empty_response.size());
received = true;
}
return true;
});
KeyboardKeyChannelHandler handler(&messenger);
handler.KeyboardHook(64, kUnhandledScanCode, WM_KEYDOWN, L'b', false, false,
[](bool handled) {});
// Passes if it does not crash.
EXPECT_TRUE(received);
}
} // namespace testing
} // namespace flutter
| bsd-3-clause |
djrosl/travel | forum/language/ru/acp/email.php | 4533 | <?php
/**
*
* This file is part of the phpBB Forum Software package.
*
* @copyright (c) phpBB Limited <https://www.phpbb.com>
* @license GNU General Public License, version 2 (GPL-2.0)
*
* For full copyright and license information, please see
* the docs/CREDITS.txt file.
*
*/
/**
* DO NOT CHANGE
*/
if (!defined('IN_PHPBB'))
{
exit;
}
if (empty($lang) || !is_array($lang))
{
$lang = array();
}
// DEVELOPERS PLEASE NOTE
//
// All language files should use UTF-8 as their encoding and the files must not contain a BOM.
//
// Placeholders can now contain order information, e.g. instead of
// 'Page %s of %s' you can (and should) write 'Page %1$s of %2$s', this allows
// translators to re-order the output of data while ensuring it remains correct
//
// You do not need this where single placeholders are used, e.g. 'Message %d' is fine
// equally where a string contains only two placeholders which are used to wrap text
// in a url you again do not need to specify an order e.g., 'Click %sHERE%s' is fine
// Email settings
$lang = array_merge($lang, array(
'ACP_MASS_EMAIL_EXPLAIN' => 'С помощью этой формы вы можете отправить электронное сообщение всем пользователям или пользователям определённой группы, <strong>имеющим включённую опцию получения электронных сообщений</strong>. Для достижения этого сообщение будет отправлено с электронного адреса администратора и будет снабжено скрытой копией для всех получателей. По умолчанию такое сообщение включает максимум 20 получателей. Если получателей больше, то будет отправлено несколько сообщений. Если вы отправляете сообщение большой группе людей, то это действие может занять некоторое время. Пожалуйста, будьте терпеливы и не останавливайте загрузку страницы после отправки сообщения. Вы будете уведомлены об успешном завершении отправки.',
'ALL_USERS' => 'Всем пользователям',
'COMPOSE' => 'Сообщение',
'EMAIL_SEND_ERROR' => 'Произошли ошибки во время отправки сообщения. Посмотрите %sлог ошибок%s для получения более подробных сведений об ошибках.',
'EMAIL_SENT' => 'Сообщение отправлено.',
'EMAIL_SENT_QUEUE' => 'Сообщение поставлено в очередь для последующей отправки.',
'LOG_SESSION' => 'Вести лог критических ошибок сеанса рассылки',
'SEND_IMMEDIATELY' => 'Немедленная отправка',
'SEND_TO_GROUP' => 'Отправить участникам группы',
'SEND_TO_USERS' => 'Отправить пользователям',
'SEND_TO_USERS_EXPLAIN' => 'Сообщение будет отправлено указанным пользователям вместо выбранной выше группы. Вводите каждое имя пользователя на новой строке.',
'MAIL_BANNED' => 'Отправить заблокированным пользователям',
'MAIL_BANNED_EXPLAIN' => 'При массовой рассылке группе данная настройка определяет, будут ли email-сообщения отправлены заблокированным пользователям.',
'MAIL_HIGH_PRIORITY' => 'Высокий',
'MAIL_LOW_PRIORITY' => 'Низкий',
'MAIL_NORMAL_PRIORITY' => 'Обычный',
'MAIL_PRIORITY' => 'Приоритет рассылки',
'MASS_MESSAGE' => 'Текст сообщения',
'MASS_MESSAGE_EXPLAIN' => 'Можно использовать только обычный текст. Вся разметка будет удалена перед отправкой.',
'NO_EMAIL_MESSAGE' => 'Необходимо ввести текст сообщения',
'NO_EMAIL_SUBJECT' => 'Необходимо указать заголовок сообщения',
));
| bsd-3-clause |
alexis-roche/nireg | scripts/scripting.py | 6418 | #!/usr/bin/env python
# emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*-
# vi: set ft=python sts=4 ts=4 sw=4 et:
"""
A scripting wrapper around 4D registration (SpaceTimeRealign)
"""
from __future__ import absolute_import
import os
import os.path as op
import numpy as np
import numpy.linalg as npl
import nibabel as nib
from nibabel.filename_parser import splitext_addext
import nibabel.eulerangles as euler
from nibabel.optpkg import optional_package
matplotlib, HAVE_MPL, _ = optional_package('matplotlib')
if HAVE_MPL:
import matplotlib.pyplot as plt
from .groupwise_registration import SpaceTimeRealign
import nipy.algorithms.slicetiming as st
from nipy.io.api import save_image
timefuncs = st.timefuncs.SLICETIME_FUNCTIONS
__all__ = ["space_time_realign", "aff2euler"]
def aff2euler(affine):
"""
Compute Euler angles from 4 x 4 `affine`
Parameters
----------
affine : 4 by 4 array
An affine transformation matrix
Returns
-------
The Euler angles associated with the affine
"""
return euler.mat2euler(aff2rot_zooms(affine)[0])
def aff2rot_zooms(affine):
"""
Compute a rotation matrix and zooms from 4 x 4 `affine`
Parameters
----------
affine : 4 by 4 array
An affine transformation matrix
Returns
-------
R: 3 by 3 array
A rotation matrix in 3D
zooms: length 3 1-d array
Vector with voxel sizes.
"""
RZS = affine[:3, :3]
zooms = np.sqrt(np.sum(RZS * RZS, axis=0))
RS = RZS / zooms
# Adjust zooms to make RS correspond (below) to a true
# rotation matrix.
if npl.det(RS) < 0:
zooms[0] *= -1
RS[:,0] *= -1
# retrieve rotation matrix from RS with polar decomposition.
# Discard shears
P, S, Qs = npl.svd(RS)
R = np.dot(P, Qs)
return R, zooms
def space_time_realign(input, tr, slice_order='descending', slice_dim=2,
slice_dir=1, apply=True, make_figure=False,
out_name=None):
"""
This is a scripting interface to `nipy.algorithms.registration.SpaceTimeRealign`
Parameters
----------
input : str or list
A full path to a file-name (4D nifti time-series) , or to a directory
containing 4D nifti time-series, or a list of full-paths to files.
tr : float
The repetition time
slice_order : str (optional)
This is the order of slice-times in the acquisition. This is used as a
key into the ``SLICETIME_FUNCTIONS`` dictionary from
:mod:`nipy.algorithms.slicetiming.timefuncs`. Default: 'descending'.
slice_dim : int (optional)
Denotes the axis in `images` that is the slice axis. In a 4D image,
this will often be axis = 2 (default).
slice_dir : int (optional)
1 if the slices were acquired slice 0 first (default), slice -1 last,
or -1 if acquire slice -1 first, slice 0 last.
apply : bool (optional)
Whether to apply the transformation and produce an output. Default:
True.
make_figure : bool (optional)
Whether to generate a .png figure with the parameters across scans.
out_name : bool (optional)
Specify an output location (full path) for the files that are
generated. Default: generate files in the path of the inputs (with an
`_mc` suffix added to the file-names.
Returns
-------
transforms : ndarray
An (n_times_points,) shaped array containing
`nipy.algorithms.registration.affine.Rigid` class instances for each time
point in the time-series. These can be used as affine transforms by
referring to their `.as_affine` attribute.
"""
if make_figure:
if not HAVE_MPL:
e_s ="You need to have matplotlib installed to run this function"
e_s += " with `make_figure` set to `True`"
raise RuntimeError(e_s)
# If we got only a single file, we motion correct that one:
if op.isfile(input):
if not (input.endswith('.nii') or input.endswith('.nii.gz')):
e_s = "Input needs to be a nifti file ('.nii' or '.nii.gz'"
raise ValueError(e_s)
fnames = [input]
input = nib.load(input)
# If this is a full-path to a directory containing files, it's still a
# string:
elif isinstance(input, str):
list_of_files = os.listdir(input)
fnames = [op.join(input, f) for f in np.sort(list_of_files)
if (f.endswith('.nii') or f.endswith('.nii.gz')) ]
input = [nib.load(x) for x in fnames]
# Assume that it's a list of full-paths to files:
else:
input = [nib.load(x) for x in input]
slice_times = timefuncs[slice_order]
slice_info = [slice_dim,
slice_dir]
reggy = SpaceTimeRealign(input,
tr,
slice_times,
slice_info)
reggy.estimate(align_runs=True)
# We now have the transformation parameters in here:
transforms = np.squeeze(np.array(reggy._transforms))
rot = np.array([t.rotation for t in transforms])
trans = np.array([t.translation for t in transforms])
if apply:
new_reggy = reggy.resample(align_runs=True)
for run_idx, new_im in enumerate(new_reggy):
# Fix output TR - it was probably lost in the image realign step
assert new_im.affine.shape == (5, 5)
new_im.affine[:] = new_im.affine.dot(np.diag([1, 1, 1, tr, 1]))
# Save it out to a '.nii.gz' file:
froot, ext, trail_ext = splitext_addext(fnames[run_idx])
path, fname = op.split(froot)
# We retain the file-name adding '_mc' regardless of where it's
# saved
new_path = path if out_name is None else out_name
save_image(new_im, op.join(new_path, fname + '_mc.nii.gz'))
if make_figure:
figure, ax = plt.subplots(2)
figure.set_size_inches([8, 6])
ax[0].plot(rot)
ax[0].set_xlabel('Time (TR)')
ax[0].set_ylabel('Translation (mm)')
ax[1].plot(trans)
ax[1].set_xlabel('Time (TR)')
ax[1].set_ylabel('Rotation (radians)')
figure.savefig(op.join(os.path.split(fnames[0])[0],
'mc_params.png'))
return transforms
| bsd-3-clause |
rsadhu/phantomjs | src/qt/src/gui/painting/qdrawutil.cpp | 49362 | /****************************************************************************
**
** Copyright (C) 2011 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the QtGui module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** GNU Lesser General Public License Usage
** This file may be used under the terms of the GNU Lesser General Public
** License version 2.1 as published by the Free Software Foundation and
** appearing in the file LICENSE.LGPL included in the packaging of this
** file. Please review the following information to ensure the GNU Lesser
** General Public License version 2.1 requirements will be met:
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights. These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU General
** Public License version 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of this
** file. Please review the following information to ensure the GNU General
** Public License version 3.0 requirements will be met:
** http://www.gnu.org/copyleft/gpl.html.
**
** Other Usage
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qdrawutil.h"
#include "qbitmap.h"
#include "qpixmapcache.h"
#include "qapplication.h"
#include "qpainter.h"
#include "qpalette.h"
#include <private/qpaintengineex_p.h>
#include <qvarlengtharray.h>
#include <qmath.h>
#include <private/qstylehelper_p.h>
QT_BEGIN_NAMESPACE
/*!
\headerfile <qdrawutil.h>
\title Drawing Utility Functions
\sa QPainter
*/
/*!
\fn void qDrawShadeLine(QPainter *painter, int x1, int y1, int x2, int y2,
const QPalette &palette, bool sunken,
int lineWidth, int midLineWidth)
\relates <qdrawutil.h>
Draws a horizontal (\a y1 == \a y2) or vertical (\a x1 == \a x2)
shaded line using the given \a painter. Note that nothing is
drawn if \a y1 != \a y2 and \a x1 != \a x2 (i.e. the line is
neither horizontal nor vertical).
The provided \a palette specifies the shading colors (\l
{QPalette::light()}{light}, \l {QPalette::dark()}{dark} and \l
{QPalette::mid()}{middle} colors). The given \a lineWidth
specifies the line width for each of the lines; it is not the
total line width. The given \a midLineWidth specifies the width of
a middle line drawn in the QPalette::mid() color.
The line appears sunken if \a sunken is true, otherwise raised.
\warning This function does not look at QWidget::style() or
QApplication::style(). Use the drawing functions in QStyle to
make widgets that follow the current GUI style.
Alternatively you can use a QFrame widget and apply the
QFrame::setFrameStyle() function to display a shaded line:
\snippet doc/src/snippets/code/src_gui_painting_qdrawutil.cpp 0
\sa qDrawShadeRect(), qDrawShadePanel(), QStyle
*/
void qDrawShadeLine(QPainter *p, int x1, int y1, int x2, int y2,
const QPalette &pal, bool sunken,
int lineWidth, int midLineWidth)
{
if (!(p && lineWidth >= 0 && midLineWidth >= 0)) {
qWarning("qDrawShadeLine: Invalid parameters");
return;
}
int tlw = lineWidth*2 + midLineWidth; // total line width
QPen oldPen = p->pen(); // save pen
if (sunken)
p->setPen(pal.color(QPalette::Dark));
else
p->setPen(pal.light().color());
QPolygon a;
int i;
if (y1 == y2) { // horizontal line
int y = y1 - tlw/2;
if (x1 > x2) { // swap x1 and x2
int t = x1;
x1 = x2;
x2 = t;
}
x2--;
for (i=0; i<lineWidth; i++) { // draw top shadow
a.setPoints(3, x1+i, y+tlw-1-i,
x1+i, y+i,
x2-i, y+i);
p->drawPolyline(a);
}
if (midLineWidth > 0) {
p->setPen(pal.mid().color());
for (i=0; i<midLineWidth; i++) // draw lines in the middle
p->drawLine(x1+lineWidth, y+lineWidth+i,
x2-lineWidth, y+lineWidth+i);
}
if (sunken)
p->setPen(pal.light().color());
else
p->setPen(pal.dark().color());
for (i=0; i<lineWidth; i++) { // draw bottom shadow
a.setPoints(3, x1+i, y+tlw-i-1,
x2-i, y+tlw-i-1,
x2-i, y+i+1);
p->drawPolyline(a);
}
}
else if (x1 == x2) { // vertical line
int x = x1 - tlw/2;
if (y1 > y2) { // swap y1 and y2
int t = y1;
y1 = y2;
y2 = t;
}
y2--;
for (i=0; i<lineWidth; i++) { // draw left shadow
a.setPoints(3, x+i, y2,
x+i, y1+i,
x+tlw-1, y1+i);
p->drawPolyline(a);
}
if (midLineWidth > 0) {
p->setPen(pal.mid().color());
for (i=0; i<midLineWidth; i++) // draw lines in the middle
p->drawLine(x+lineWidth+i, y1+lineWidth, x+lineWidth+i, y2);
}
if (sunken)
p->setPen(pal.light().color());
else
p->setPen(pal.dark().color());
for (i=0; i<lineWidth; i++) { // draw right shadow
a.setPoints(3, x+lineWidth, y2-i,
x+tlw-i-1, y2-i,
x+tlw-i-1, y1+lineWidth);
p->drawPolyline(a);
}
}
p->setPen(oldPen);
}
/*!
\fn void qDrawShadeRect(QPainter *painter, int x, int y, int width, int height,
const QPalette &palette, bool sunken,
int lineWidth, int midLineWidth,
const QBrush *fill)
\relates <qdrawutil.h>
Draws the shaded rectangle beginning at (\a x, \a y) with the
given \a width and \a height using the provided \a painter.
The provide \a palette specifies the shading colors (\l
{QPalette::light()}{light}, \l {QPalette::dark()}{dark} and \l
{QPalette::mid()}{middle} colors. The given \a lineWidth
specifies the line width for each of the lines; it is not the
total line width. The \a midLineWidth specifies the width of a
middle line drawn in the QPalette::mid() color. The rectangle's
interior is filled with the \a fill brush unless \a fill is 0.
The rectangle appears sunken if \a sunken is true, otherwise
raised.
\warning This function does not look at QWidget::style() or
QApplication::style(). Use the drawing functions in QStyle to make
widgets that follow the current GUI style.
Alternatively you can use a QFrame widget and apply the
QFrame::setFrameStyle() function to display a shaded rectangle:
\snippet doc/src/snippets/code/src_gui_painting_qdrawutil.cpp 1
\sa qDrawShadeLine(), qDrawShadePanel(), qDrawPlainRect(), QStyle
*/
void qDrawShadeRect(QPainter *p, int x, int y, int w, int h,
const QPalette &pal, bool sunken,
int lineWidth, int midLineWidth,
const QBrush *fill)
{
if (w == 0 || h == 0)
return;
if (! (w > 0 && h > 0 && lineWidth >= 0 && midLineWidth >= 0)) {
qWarning("qDrawShadeRect: Invalid parameters");
return;
}
QPen oldPen = p->pen();
if (sunken)
p->setPen(pal.dark().color());
else
p->setPen(pal.light().color());
int x1=x, y1=y, x2=x+w-1, y2=y+h-1;
if (lineWidth == 1 && midLineWidth == 0) {// standard shade rectangle
p->drawRect(x1, y1, w-2, h-2);
if (sunken)
p->setPen(pal.light().color());
else
p->setPen(pal.dark().color());
QLineF lines[4] = { QLineF(x1+1, y1+1, x2-2, y1+1),
QLineF(x1+1, y1+2, x1+1, y2-2),
QLineF(x1, y2, x2, y2),
QLineF(x2,y1, x2,y2-1) };
p->drawLines(lines, 4); // draw bottom/right lines
} else { // more complicated
int m = lineWidth+midLineWidth;
int i, j=0, k=m;
for (i=0; i<lineWidth; i++) { // draw top shadow
QLineF lines[4] = { QLineF(x1+i, y2-i, x1+i, y1+i),
QLineF(x1+i, y1+i, x2-i, y1+i),
QLineF(x1+k, y2-k, x2-k, y2-k),
QLineF(x2-k, y2-k, x2-k, y1+k) };
p->drawLines(lines, 4);
k++;
}
p->setPen(pal.mid().color());
j = lineWidth*2;
for (i=0; i<midLineWidth; i++) { // draw lines in the middle
p->drawRect(x1+lineWidth+i, y1+lineWidth+i, w-j-1, h-j-1);
j += 2;
}
if (sunken)
p->setPen(pal.light().color());
else
p->setPen(pal.dark().color());
k = m;
for (i=0; i<lineWidth; i++) { // draw bottom shadow
QLineF lines[4] = { QLineF(x1+1+i, y2-i, x2-i, y2-i),
QLineF(x2-i, y2-i, x2-i, y1+i+1),
QLineF(x1+k, y2-k, x1+k, y1+k),
QLineF(x1+k, y1+k, x2-k, y1+k) };
p->drawLines(lines, 4);
k++;
}
}
if (fill) {
QBrush oldBrush = p->brush();
int tlw = lineWidth + midLineWidth;
p->setPen(Qt::NoPen);
p->setBrush(*fill);
p->drawRect(x+tlw, y+tlw, w-2*tlw, h-2*tlw);
p->setBrush(oldBrush);
}
p->setPen(oldPen); // restore pen
}
/*!
\fn void qDrawShadePanel(QPainter *painter, int x, int y, int width, int height,
const QPalette &palette, bool sunken,
int lineWidth, const QBrush *fill)
\relates <qdrawutil.h>
Draws the shaded panel beginning at (\a x, \a y) with the given \a
width and \a height using the provided \a painter and the given \a
lineWidth.
The given \a palette specifies the shading colors (\l
{QPalette::light()}{light}, \l {QPalette::dark()}{dark} and \l
{QPalette::mid()}{middle} colors). The panel's interior is filled
with the \a fill brush unless \a fill is 0.
The panel appears sunken if \a sunken is true, otherwise raised.
\warning This function does not look at QWidget::style() or
QApplication::style(). Use the drawing functions in QStyle to make
widgets that follow the current GUI style.
Alternatively you can use a QFrame widget and apply the
QFrame::setFrameStyle() function to display a shaded panel:
\snippet doc/src/snippets/code/src_gui_painting_qdrawutil.cpp 2
\sa qDrawWinPanel(), qDrawShadeLine(), qDrawShadeRect(), QStyle
*/
void qDrawShadePanel(QPainter *p, int x, int y, int w, int h,
const QPalette &pal, bool sunken,
int lineWidth, const QBrush *fill)
{
if (w == 0 || h == 0)
return;
if (!(w > 0 && h > 0 && lineWidth >= 0)) {
qWarning("qDrawShadePanel: Invalid parameters");
}
QColor shade = pal.dark().color();
QColor light = pal.light().color();
if (fill) {
if (fill->color() == shade)
shade = pal.shadow().color();
if (fill->color() == light)
light = pal.midlight().color();
}
QPen oldPen = p->pen(); // save pen
QVector<QLineF> lines;
lines.reserve(2*lineWidth);
if (sunken)
p->setPen(shade);
else
p->setPen(light);
int x1, y1, x2, y2;
int i;
x1 = x;
y1 = y2 = y;
x2 = x+w-2;
for (i=0; i<lineWidth; i++) { // top shadow
lines << QLineF(x1, y1++, x2--, y2++);
}
x2 = x1;
y1 = y+h-2;
for (i=0; i<lineWidth; i++) { // left shado
lines << QLineF(x1++, y1, x2++, y2--);
}
p->drawLines(lines);
lines.clear();
if (sunken)
p->setPen(light);
else
p->setPen(shade);
x1 = x;
y1 = y2 = y+h-1;
x2 = x+w-1;
for (i=0; i<lineWidth; i++) { // bottom shadow
lines << QLineF(x1++, y1--, x2, y2--);
}
x1 = x2;
y1 = y;
y2 = y+h-lineWidth-1;
for (i=0; i<lineWidth; i++) { // right shadow
lines << QLineF(x1--, y1++, x2--, y2);
}
p->drawLines(lines);
if (fill) // fill with fill color
p->fillRect(x+lineWidth, y+lineWidth, w-lineWidth*2, h-lineWidth*2, *fill);
p->setPen(oldPen); // restore pen
}
/*!
\internal
This function draws a rectangle with two pixel line width.
It is called from qDrawWinButton() and qDrawWinPanel().
c1..c4 and fill are used:
1 1 1 1 1 2
1 3 3 3 4 2
1 3 F F 4 2
1 3 F F 4 2
1 4 4 4 4 2
2 2 2 2 2 2
*/
static void qDrawWinShades(QPainter *p,
int x, int y, int w, int h,
const QColor &c1, const QColor &c2,
const QColor &c3, const QColor &c4,
const QBrush *fill)
{
if (w < 2 || h < 2) // can't do anything with that
return;
QPen oldPen = p->pen();
QPoint a[3] = { QPoint(x, y+h-2), QPoint(x, y), QPoint(x+w-2, y) };
p->setPen(c1);
p->drawPolyline(a, 3);
QPoint b[3] = { QPoint(x, y+h-1), QPoint(x+w-1, y+h-1), QPoint(x+w-1, y) };
p->setPen(c2);
p->drawPolyline(b, 3);
if (w > 4 && h > 4) {
QPoint c[3] = { QPoint(x+1, y+h-3), QPoint(x+1, y+1), QPoint(x+w-3, y+1) };
p->setPen(c3);
p->drawPolyline(c, 3);
QPoint d[3] = { QPoint(x+1, y+h-2), QPoint(x+w-2, y+h-2), QPoint(x+w-2, y+1) };
p->setPen(c4);
p->drawPolyline(d, 3);
if (fill)
p->fillRect(QRect(x+2, y+2, w-4, h-4), *fill);
}
p->setPen(oldPen);
}
/*!
\fn void qDrawWinButton(QPainter *painter, int x, int y, int width, int height,
const QPalette &palette, bool sunken,
const QBrush *fill)
\relates <qdrawutil.h>
Draws the Windows-style button specified by the given point (\a x,
\a y}, \a width and \a height using the provided \a painter with a
line width of 2 pixels. The button's interior is filled with the
\a{fill} brush unless \a fill is 0.
The given \a palette specifies the shading colors (\l
{QPalette::light()}{light}, \l {QPalette::dark()}{dark} and \l
{QPalette::mid()}{middle} colors).
The button appears sunken if \a sunken is true, otherwise raised.
\warning This function does not look at QWidget::style() or
QApplication::style()-> Use the drawing functions in QStyle to make
widgets that follow the current GUI style.
\sa qDrawWinPanel(), QStyle
*/
void qDrawWinButton(QPainter *p, int x, int y, int w, int h,
const QPalette &pal, bool sunken,
const QBrush *fill)
{
if (sunken)
qDrawWinShades(p, x, y, w, h,
pal.shadow().color(), pal.light().color(), pal.dark().color(),
pal.button().color(), fill);
else
qDrawWinShades(p, x, y, w, h,
pal.light().color(), pal.shadow().color(), pal.button().color(),
pal.dark().color(), fill);
}
/*!
\fn void qDrawWinPanel(QPainter *painter, int x, int y, int width, int height,
const QPalette &palette, bool sunken,
const QBrush *fill)
\relates <qdrawutil.h>
Draws the Windows-style panel specified by the given point(\a x,
\a y), \a width and \a height using the provided \a painter with a
line width of 2 pixels. The button's interior is filled with the
\a fill brush unless \a fill is 0.
The given \a palette specifies the shading colors. The panel
appears sunken if \a sunken is true, otherwise raised.
\warning This function does not look at QWidget::style() or
QApplication::style(). Use the drawing functions in QStyle to make
widgets that follow the current GUI style.
Alternatively you can use a QFrame widget and apply the
QFrame::setFrameStyle() function to display a shaded panel:
\snippet doc/src/snippets/code/src_gui_painting_qdrawutil.cpp 3
\sa qDrawShadePanel(), qDrawWinButton(), QStyle
*/
void qDrawWinPanel(QPainter *p, int x, int y, int w, int h,
const QPalette &pal, bool sunken,
const QBrush *fill)
{
if (sunken)
qDrawWinShades(p, x, y, w, h,
pal.dark().color(), pal.light().color(), pal.shadow().color(),
pal.midlight().color(), fill);
else
qDrawWinShades(p, x, y, w, h,
pal.light().color(), pal.shadow().color(), pal.midlight().color(),
pal.dark().color(), fill);
}
/*!
\fn void qDrawPlainRect(QPainter *painter, int x, int y, int width, int height, const QColor &lineColor,
int lineWidth, const QBrush *fill)
\relates <qdrawutil.h>
Draws the plain rectangle beginning at (\a x, \a y) with the given
\a width and \a height, using the specified \a painter, \a lineColor
and \a lineWidth. The rectangle's interior is filled with the \a
fill brush unless \a fill is 0.
\warning This function does not look at QWidget::style() or
QApplication::style(). Use the drawing functions in QStyle to make
widgets that follow the current GUI style.
Alternatively you can use a QFrame widget and apply the
QFrame::setFrameStyle() function to display a plain rectangle:
\snippet doc/src/snippets/code/src_gui_painting_qdrawutil.cpp 4
\sa qDrawShadeRect(), QStyle
*/
void qDrawPlainRect(QPainter *p, int x, int y, int w, int h, const QColor &c,
int lineWidth, const QBrush *fill)
{
if (w == 0 || h == 0)
return;
if (!(w > 0 && h > 0 && lineWidth >= 0)) {
qWarning("qDrawPlainRect: Invalid parameters");
}
QPen oldPen = p->pen();
QBrush oldBrush = p->brush();
p->setPen(c);
p->setBrush(Qt::NoBrush);
for (int i=0; i<lineWidth; i++)
p->drawRect(x+i, y+i, w-i*2 - 1, h-i*2 - 1);
if (fill) { // fill with fill color
p->setPen(Qt::NoPen);
p->setBrush(*fill);
p->drawRect(x+lineWidth, y+lineWidth, w-lineWidth*2, h-lineWidth*2);
}
p->setPen(oldPen);
p->setBrush(oldBrush);
}
/*****************************************************************************
Overloaded functions.
*****************************************************************************/
/*!
\fn void qDrawShadeLine(QPainter *painter, const QPoint &p1, const QPoint &p2,
const QPalette &palette, bool sunken, int lineWidth, int midLineWidth)
\relates <qdrawutil.h>
\overload
Draws a horizontal or vertical shaded line between \a p1 and \a p2
using the given \a painter. Note that nothing is drawn if the line
between the points would be neither horizontal nor vertical.
The provided \a palette specifies the shading colors (\l
{QPalette::light()}{light}, \l {QPalette::dark()}{dark} and \l
{QPalette::mid()}{middle} colors). The given \a lineWidth
specifies the line width for each of the lines; it is not the
total line width. The given \a midLineWidth specifies the width of
a middle line drawn in the QPalette::mid() color.
The line appears sunken if \a sunken is true, otherwise raised.
\warning This function does not look at QWidget::style() or
QApplication::style(). Use the drawing functions in QStyle to
make widgets that follow the current GUI style.
Alternatively you can use a QFrame widget and apply the
QFrame::setFrameStyle() function to display a shaded line:
\snippet doc/src/snippets/code/src_gui_painting_qdrawutil.cpp 5
\sa qDrawShadeRect(), qDrawShadePanel(), QStyle
*/
void qDrawShadeLine(QPainter *p, const QPoint &p1, const QPoint &p2,
const QPalette &pal, bool sunken,
int lineWidth, int midLineWidth)
{
qDrawShadeLine(p, p1.x(), p1.y(), p2.x(), p2.y(), pal, sunken,
lineWidth, midLineWidth);
}
/*!
\fn void qDrawShadeRect(QPainter *painter, const QRect &rect, const QPalette &palette,
bool sunken, int lineWidth, int midLineWidth, const QBrush *fill)
\relates <qdrawutil.h>
\overload
Draws the shaded rectangle specified by \a rect using the given \a painter.
The provide \a palette specifies the shading colors (\l
{QPalette::light()}{light}, \l {QPalette::dark()}{dark} and \l
{QPalette::mid()}{middle} colors. The given \a lineWidth
specifies the line width for each of the lines; it is not the
total line width. The \a midLineWidth specifies the width of a
middle line drawn in the QPalette::mid() color. The rectangle's
interior is filled with the \a fill brush unless \a fill is 0.
The rectangle appears sunken if \a sunken is true, otherwise
raised.
\warning This function does not look at QWidget::style() or
QApplication::style(). Use the drawing functions in QStyle to make
widgets that follow the current GUI style.
Alternatively you can use a QFrame widget and apply the
QFrame::setFrameStyle() function to display a shaded rectangle:
\snippet doc/src/snippets/code/src_gui_painting_qdrawutil.cpp 6
\sa qDrawShadeLine(), qDrawShadePanel(), qDrawPlainRect(), QStyle
*/
void qDrawShadeRect(QPainter *p, const QRect &r,
const QPalette &pal, bool sunken,
int lineWidth, int midLineWidth,
const QBrush *fill)
{
qDrawShadeRect(p, r.x(), r.y(), r.width(), r.height(), pal, sunken,
lineWidth, midLineWidth, fill);
}
/*!
\fn void qDrawShadePanel(QPainter *painter, const QRect &rect, const QPalette &palette,
bool sunken, int lineWidth, const QBrush *fill)
\relates <qdrawutil.h>
\overload
Draws the shaded panel at the rectangle specified by \a rect using the
given \a painter and the given \a lineWidth.
The given \a palette specifies the shading colors (\l
{QPalette::light()}{light}, \l {QPalette::dark()}{dark} and \l
{QPalette::mid()}{middle} colors). The panel's interior is filled
with the \a fill brush unless \a fill is 0.
The panel appears sunken if \a sunken is true, otherwise raised.
\warning This function does not look at QWidget::style() or
QApplication::style(). Use the drawing functions in QStyle to make
widgets that follow the current GUI style.
Alternatively you can use a QFrame widget and apply the
QFrame::setFrameStyle() function to display a shaded panel:
\snippet doc/src/snippets/code/src_gui_painting_qdrawutil.cpp 7
\sa qDrawWinPanel(), qDrawShadeLine(), qDrawShadeRect(), QStyle
*/
void qDrawShadePanel(QPainter *p, const QRect &r,
const QPalette &pal, bool sunken,
int lineWidth, const QBrush *fill)
{
qDrawShadePanel(p, r.x(), r.y(), r.width(), r.height(), pal, sunken,
lineWidth, fill);
}
/*!
\fn void qDrawWinButton(QPainter *painter, const QRect &rect, const QPalette &palette,
bool sunken, const QBrush *fill)
\relates <qdrawutil.h>
\overload
Draws the Windows-style button at the rectangle specified by \a rect using
the given \a painter with a line width of 2 pixels. The button's interior
is filled with the \a{fill} brush unless \a fill is 0.
The given \a palette specifies the shading colors (\l
{QPalette::light()}{light}, \l {QPalette::dark()}{dark} and \l
{QPalette::mid()}{middle} colors).
The button appears sunken if \a sunken is true, otherwise raised.
\warning This function does not look at QWidget::style() or
QApplication::style()-> Use the drawing functions in QStyle to make
widgets that follow the current GUI style.
\sa qDrawWinPanel(), QStyle
*/
void qDrawWinButton(QPainter *p, const QRect &r,
const QPalette &pal, bool sunken, const QBrush *fill)
{
qDrawWinButton(p, r.x(), r.y(), r.width(), r.height(), pal, sunken, fill);
}
/*!
\fn void qDrawWinPanel(QPainter *painter, const QRect &rect, const QPalette &palette,
bool sunken, const QBrush *fill)
\overload
Draws the Windows-style panel at the rectangle specified by \a rect using
the given \a painter with a line width of 2 pixels. The button's interior
is filled with the \a fill brush unless \a fill is 0.
The given \a palette specifies the shading colors. The panel
appears sunken if \a sunken is true, otherwise raised.
\warning This function does not look at QWidget::style() or
QApplication::style(). Use the drawing functions in QStyle to make
widgets that follow the current GUI style.
Alternatively you can use a QFrame widget and apply the
QFrame::setFrameStyle() function to display a shaded panel:
\snippet doc/src/snippets/code/src_gui_painting_qdrawutil.cpp 8
\sa qDrawShadePanel(), qDrawWinButton(), QStyle
*/
void qDrawWinPanel(QPainter *p, const QRect &r,
const QPalette &pal, bool sunken, const QBrush *fill)
{
qDrawWinPanel(p, r.x(), r.y(), r.width(), r.height(), pal, sunken, fill);
}
/*!
\fn void qDrawPlainRect(QPainter *painter, const QRect &rect, const QColor &lineColor, int lineWidth, const QBrush *fill)
\relates <qdrawutil.h>
\overload
Draws the plain rectangle specified by \a rect using the given \a painter,
\a lineColor and \a lineWidth. The rectangle's interior is filled with the
\a fill brush unless \a fill is 0.
\warning This function does not look at QWidget::style() or
QApplication::style(). Use the drawing functions in QStyle to make
widgets that follow the current GUI style.
Alternatively you can use a QFrame widget and apply the
QFrame::setFrameStyle() function to display a plain rectangle:
\snippet doc/src/snippets/code/src_gui_painting_qdrawutil.cpp 9
\sa qDrawShadeRect(), QStyle
*/
void qDrawPlainRect(QPainter *p, const QRect &r, const QColor &c,
int lineWidth, const QBrush *fill)
{
qDrawPlainRect(p, r.x(), r.y(), r.width(), r.height(), c,
lineWidth, fill);
}
#ifdef QT3_SUPPORT
static void qDrawWinArrow(QPainter *p, Qt::ArrowType type, bool down,
int x, int y, int w, int h,
const QPalette &pal, bool enabled)
{
QPolygon a; // arrow polygon
switch (type) {
case Qt::UpArrow:
a.setPoints(7, -3,1, 3,1, -2,0, 2,0, -1,-1, 1,-1, 0,-2);
break;
case Qt::DownArrow:
a.setPoints(7, -3,-1, 3,-1, -2,0, 2,0, -1,1, 1,1, 0,2);
break;
case Qt::LeftArrow:
a.setPoints(7, 1,-3, 1,3, 0,-2, 0,2, -1,-1, -1,1, -2,0);
break;
case Qt::RightArrow:
a.setPoints(7, -1,-3, -1,3, 0,-2, 0,2, 1,-1, 1,1, 2,0);
break;
default:
break;
}
if (a.isEmpty())
return;
if (down) {
x++;
y++;
}
QPen savePen = p->pen(); // save current pen
if (down)
p->setBrushOrigin(p->brushOrigin() + QPoint(1,1));
p->fillRect(x, y, w, h, pal.brush(QPalette::Button));
if (down)
p->setBrushOrigin(p->brushOrigin() - QPoint(1,1));
if (enabled) {
a.translate(x+w/2, y+h/2);
p->setPen(pal.foreground().color());
p->drawLine(a.at(0), a.at(1));
p->drawLine(a.at(2), a.at(2));
p->drawPoint(a[6]);
} else {
a.translate(x+w/2+1, y+h/2+1);
p->setPen(pal.light().color());
p->drawLine(a.at(0), a.at(1));
p->drawLine(a.at(2), a.at(2));
p->drawPoint(a[6]);
a.translate(-1, -1);
p->setPen(pal.mid().color());
p->drawLine(a.at(0), a.at(1));
p->drawLine(a.at(2), a.at(2));
p->drawPoint(a[6]);
}
p->setPen(savePen); // restore pen
}
#endif // QT3_SUPPORT
#if defined(Q_CC_MSVC)
#pragma warning(disable: 4244)
#endif
#ifdef QT3_SUPPORT
#ifndef QT_NO_STYLE_MOTIF
// motif arrows look the same whether they are used or not
// is this correct?
static void qDrawMotifArrow(QPainter *p, Qt::ArrowType type, bool down,
int x, int y, int w, int h,
const QPalette &pal, bool)
{
QPolygon bFill; // fill polygon
QPolygon bTop; // top shadow.
QPolygon bBot; // bottom shadow.
QPolygon bLeft; // left shadow.
QTransform matrix; // xform matrix
bool vertical = type == Qt::UpArrow || type == Qt::DownArrow;
bool horizontal = !vertical;
int dim = w < h ? w : h;
int colspec = 0x0000; // color specification array
if (dim < 2) // too small arrow
return;
if (dim > 3) {
if (dim > 6)
bFill.resize(dim & 1 ? 3 : 4);
bTop.resize((dim/2)*2);
bBot.resize(dim & 1 ? dim + 1 : dim);
bLeft.resize(dim > 4 ? 4 : 2);
bLeft.putPoints(0, 2, 0,0, 0,dim-1);
if (dim > 4)
bLeft.putPoints(2, 2, 1,2, 1,dim-3);
bTop.putPoints(0, 4, 1,0, 1,1, 2,1, 3,1);
bBot.putPoints(0, 4, 1,dim-1, 1,dim-2, 2,dim-2, 3,dim-2);
for(int i=0; i<dim/2-2 ; i++) {
bTop.putPoints(i*2+4, 2, 2+i*2,2+i, 5+i*2, 2+i);
bBot.putPoints(i*2+4, 2, 2+i*2,dim-3-i, 5+i*2,dim-3-i);
}
if (dim & 1) // odd number size: extra line
bBot.putPoints(dim-1, 2, dim-3,dim/2, dim-1,dim/2);
if (dim > 6) { // dim>6: must fill interior
bFill.putPoints(0, 2, 1,dim-3, 1,2);
if (dim & 1) // if size is an odd number
bFill.setPoint(2, dim - 3, dim / 2);
else
bFill.putPoints(2, 2, dim-4,dim/2-1, dim-4,dim/2);
}
}
else {
if (dim == 3) { // 3x3 arrow pattern
bLeft.setPoints(4, 0,0, 0,2, 1,1, 1,1);
bTop .setPoints(2, 1,0, 1,0);
bBot .setPoints(2, 1,2, 2,1);
}
else { // 2x2 arrow pattern
bLeft.setPoints(2, 0,0, 0,1);
bTop .setPoints(2, 1,0, 1,0);
bBot .setPoints(2, 1,1, 1,1);
}
}
if (type == Qt::UpArrow || type == Qt::LeftArrow) {
matrix.translate(x, y);
if (vertical) {
matrix.translate(0, h - 1);
matrix.rotate(-90);
} else {
matrix.translate(w - 1, h - 1);
matrix.rotate(180);
}
if (down)
colspec = horizontal ? 0x2334 : 0x2343;
else
colspec = horizontal ? 0x1443 : 0x1434;
}
else if (type == Qt::DownArrow || type == Qt::RightArrow) {
matrix.translate(x, y);
if (vertical) {
matrix.translate(w-1, 0);
matrix.rotate(90);
}
if (down)
colspec = horizontal ? 0x2443 : 0x2434;
else
colspec = horizontal ? 0x1334 : 0x1343;
}
const QColor *cols[5];
cols[0] = 0;
cols[1] = &pal.button().color();
cols[2] = &pal.mid().color();
cols[3] = &pal.light().color();
cols[4] = &pal.dark().color();
#define CMID *cols[(colspec>>12) & 0xf]
#define CLEFT *cols[(colspec>>8) & 0xf]
#define CTOP *cols[(colspec>>4) & 0xf]
#define CBOT *cols[colspec & 0xf]
QPen savePen = p->pen(); // save current pen
QBrush saveBrush = p->brush(); // save current brush
QTransform wxm = p->transform();
QPen pen(Qt::NoPen);
const QBrush &brush = pal.brush(QPalette::Button);
p->setPen(pen);
p->setBrush(brush);
p->setTransform(matrix, true); // set transformation matrix
p->drawPolygon(bFill); // fill arrow
p->setBrush(Qt::NoBrush); // don't fill
p->setPen(CLEFT);
p->drawLines(bLeft);
p->setPen(CTOP);
p->drawLines(bTop);
p->setPen(CBOT);
p->drawLines(bBot);
p->setTransform(wxm);
p->setBrush(saveBrush); // restore brush
p->setPen(savePen); // restore pen
#undef CMID
#undef CLEFT
#undef CTOP
#undef CBOT
}
#endif // QT_NO_STYLE_MOTIF
QRect qItemRect(QPainter *p, Qt::GUIStyle gs,
int x, int y, int w, int h,
int flags,
bool enabled,
const QPixmap *pixmap,
const QString& text, int len)
{
QRect result;
if (pixmap) {
if ((flags & Qt::AlignVCenter) == Qt::AlignVCenter)
y += h/2 - pixmap->height()/2;
else if ((flags & Qt::AlignBottom) == Qt::AlignBottom)
y += h - pixmap->height();
if ((flags & Qt::AlignRight) == Qt::AlignRight)
x += w - pixmap->width();
else if ((flags & Qt::AlignHCenter) == Qt::AlignHCenter)
x += w/2 - pixmap->width()/2;
else if ((flags & Qt::AlignLeft) != Qt::AlignLeft && QApplication::isRightToLeft())
x += w - pixmap->width();
result = QRect(x, y, pixmap->width(), pixmap->height());
} else if (!text.isNull() && p) {
result = p->boundingRect(QRect(x, y, w, h), flags, text.left(len));
if (gs == Qt::WindowsStyle && !enabled) {
result.setWidth(result.width()+1);
result.setHeight(result.height()+1);
}
} else {
result = QRect(x, y, w, h);
}
return result;
}
void qDrawArrow(QPainter *p, Qt::ArrowType type, Qt::GUIStyle style, bool down,
int x, int y, int w, int h,
const QPalette &pal, bool enabled)
{
switch (style) {
case Qt::WindowsStyle:
qDrawWinArrow(p, type, down, x, y, w, h, pal, enabled);
break;
#ifndef QT_NO_STYLE_MOTIF
case Qt::MotifStyle:
qDrawMotifArrow(p, type, down, x, y, w, h, pal, enabled);
break;
#endif
default:
qWarning("qDrawArrow: Requested unsupported GUI style");
}
}
void qDrawItem(QPainter *p, Qt::GUIStyle gs,
int x, int y, int w, int h,
int flags,
const QPalette &pal, bool enabled,
const QPixmap *pixmap,
const QString& text, int len , const QColor* penColor)
{
p->setPen(penColor?*penColor:pal.foreground().color());
if (pixmap) {
QPixmap pm(*pixmap);
bool clip = (flags & Qt::TextDontClip) == 0;
if (clip) {
if (pm.width() < w && pm.height() < h)
clip = false;
else
p->setClipRect(x, y, w, h);
}
if ((flags & Qt::AlignVCenter) == Qt::AlignVCenter)
y += h/2 - pm.height()/2;
else if ((flags & Qt::AlignBottom) == Qt::AlignBottom)
y += h - pm.height();
if ((flags & Qt::AlignRight) == Qt::AlignRight)
x += w - pm.width();
else if ((flags & Qt::AlignHCenter) == Qt::AlignHCenter)
x += w/2 - pm.width()/2;
else if (((flags & Qt::AlignLeft) != Qt::AlignLeft) && QApplication::isRightToLeft()) // Qt::AlignAuto && rightToLeft
x += w - pm.width();
if (!enabled) {
if (pm.hasAlphaChannel()) { // pixmap with a mask
pm = pm.mask();
} else if (pm.depth() == 1) { // monochrome pixmap, no mask
;
#ifndef QT_NO_IMAGE_HEURISTIC_MASK
} else { // color pixmap, no mask
QString k = QLatin1Literal("$qt-drawitem")
% HexString<qint64>(pm.cacheKey());
if (!QPixmapCache::find(k, pm)) {
pm = pm.createHeuristicMask();
pm.setMask((QBitmap&)pm);
QPixmapCache::insert(k, pm);
}
#endif
}
if (gs == Qt::WindowsStyle) {
p->setPen(pal.light().color());
p->drawPixmap(x+1, y+1, pm);
p->setPen(pal.text().color());
}
}
p->drawPixmap(x, y, pm);
if (clip)
p->setClipping(false);
} else if (!text.isNull()) {
if (gs == Qt::WindowsStyle && !enabled) {
p->setPen(pal.light().color());
p->drawText(x+1, y+1, w, h, flags, text.left(len));
p->setPen(pal.text().color());
}
p->drawText(x, y, w, h, flags, text.left(len));
}
}
#endif
/*!
\class QTileRules
\since 4.6
Holds the rules used to draw a pixmap or image split into nine segments,
similar to \l{http://www.w3.org/TR/css3-background/}{CSS3 border-images}.
\sa Qt::TileRule, QMargins
*/
/*! \fn QTileRules::QTileRules(Qt::TileRule horizontalRule, Qt::TileRule verticalRule)
Constructs a QTileRules with the given \a horizontalRule and
\a verticalRule.
*/
/*! \fn QTileRules::QTileRules(Qt::TileRule rule)
Constructs a QTileRules with the given \a rule used for both
the horizontal rule and the vertical rule.
*/
/*!
\fn void qDrawBorderPixmap(QPainter *painter, const QRect &target, const QMargins &margins, const QPixmap &pixmap)
\relates <qdrawutil.h>
\since 4.6
\overload
\brief The qDrawBorderPixmap function is for drawing a pixmap into
the margins of a rectangle.
Draws the given \a pixmap into the given \a target rectangle, using the
given \a painter. The pixmap will be split into nine segments and drawn
according to the \a margins structure.
*/
typedef QVarLengthArray<QRectF, 16> QRectFArray;
/*!
\since 4.6
Draws the indicated \a sourceRect rectangle from the given \a pixmap into
the given \a targetRect rectangle, using the given \a painter. The pixmap
will be split into nine segments according to the given \a targetMargins
and \a sourceMargins structures. Finally, the pixmap will be drawn
according to the given \a rules.
This function is used to draw a scaled pixmap, similar to
\l{http://www.w3.org/TR/css3-background/}{CSS3 border-images}
\sa Qt::TileRule, QTileRules, QMargins
*/
void qDrawBorderPixmap(QPainter *painter, const QRect &targetRect, const QMargins &targetMargins,
const QPixmap &pixmap, const QRect &sourceRect,const QMargins &sourceMargins,
const QTileRules &rules, QDrawBorderPixmap::DrawingHints hints)
{
QRectFArray sourceData[2];
QRectFArray targetData[2];
// source center
const int sourceCenterTop = sourceRect.top() + sourceMargins.top();
const int sourceCenterLeft = sourceRect.left() + sourceMargins.left();
const int sourceCenterBottom = sourceRect.bottom() - sourceMargins.bottom() + 1;
const int sourceCenterRight = sourceRect.right() - sourceMargins.right() + 1;
const int sourceCenterWidth = sourceCenterRight - sourceCenterLeft;
const int sourceCenterHeight = sourceCenterBottom - sourceCenterTop;
// target center
const int targetCenterTop = targetRect.top() + targetMargins.top();
const int targetCenterLeft = targetRect.left() + targetMargins.left();
const int targetCenterBottom = targetRect.bottom() - targetMargins.bottom() + 1;
const int targetCenterRight = targetRect.right() - targetMargins.right() + 1;
const int targetCenterWidth = targetCenterRight - targetCenterLeft;
const int targetCenterHeight = targetCenterBottom - targetCenterTop;
QVarLengthArray<qreal, 16> xTarget; // x-coordinates of target rectangles
QVarLengthArray<qreal, 16> yTarget; // y-coordinates of target rectangles
int columns = 3;
int rows = 3;
if (rules.horizontal != Qt::StretchTile && sourceCenterWidth != 0)
columns = qMax(3, 2 + qCeil(targetCenterWidth / qreal(sourceCenterWidth)));
if (rules.vertical != Qt::StretchTile && sourceCenterHeight != 0)
rows = qMax(3, 2 + qCeil(targetCenterHeight / qreal(sourceCenterHeight)));
xTarget.resize(columns + 1);
yTarget.resize(rows + 1);
bool oldAA = painter->testRenderHint(QPainter::Antialiasing);
if (painter->paintEngine()->type() != QPaintEngine::OpenGL
&& painter->paintEngine()->type() != QPaintEngine::OpenGL2
&& oldAA && painter->combinedTransform().type() != QTransform::TxNone) {
painter->setRenderHint(QPainter::Antialiasing, false);
}
xTarget[0] = targetRect.left();
xTarget[1] = targetCenterLeft;
xTarget[columns - 1] = targetCenterRight;
xTarget[columns] = targetRect.left() + targetRect.width();
yTarget[0] = targetRect.top();
yTarget[1] = targetCenterTop;
yTarget[rows - 1] = targetCenterBottom;
yTarget[rows] = targetRect.top() + targetRect.height();
qreal dx = targetCenterWidth;
qreal dy = targetCenterHeight;
switch (rules.horizontal) {
case Qt::StretchTile:
dx = targetCenterWidth;
break;
case Qt::RepeatTile:
dx = sourceCenterWidth;
break;
case Qt::RoundTile:
dx = targetCenterWidth / qreal(columns - 2);
break;
}
for (int i = 2; i < columns - 1; ++i)
xTarget[i] = xTarget[i - 1] + dx;
switch (rules.vertical) {
case Qt::StretchTile:
dy = targetCenterHeight;
break;
case Qt::RepeatTile:
dy = sourceCenterHeight;
break;
case Qt::RoundTile:
dy = targetCenterHeight / qreal(rows - 2);
break;
}
for (int i = 2; i < rows - 1; ++i)
yTarget[i] = yTarget[i - 1] + dy;
// corners
if (targetMargins.top() > 0 && targetMargins.left() > 0 && sourceMargins.top() > 0 && sourceMargins.left() > 0) { // top left
int index = bool(hints & QDrawBorderPixmap::OpaqueTopLeft);
sourceData[index].append(QRectF(sourceRect.topLeft(), QSizeF(sourceMargins.left(), sourceMargins.top())));
targetData[index].append(QRectF(QPointF(xTarget[0], yTarget[0]), QPointF(xTarget[1], yTarget[1])));
}
if (targetMargins.top() > 0 && targetMargins.right() > 0 && sourceMargins.top() > 0 && sourceMargins.right() > 0) { // top right
int index = bool(hints & QDrawBorderPixmap::OpaqueTopRight);
sourceData[index].append(QRectF(QPointF(sourceCenterRight, sourceRect.top()), QSizeF(sourceMargins.right(), sourceMargins.top())));
targetData[index].append(QRectF(QPointF(xTarget[columns-1], yTarget[0]), QPointF(xTarget[columns], yTarget[1])));
}
if (targetMargins.bottom() > 0 && targetMargins.left() > 0 && sourceMargins.bottom() > 0 && sourceMargins.left() > 0) { // bottom left
int index = bool(hints & QDrawBorderPixmap::OpaqueBottomLeft);
sourceData[index].append(QRectF(QPointF(sourceRect.left(), sourceCenterBottom), QSizeF(sourceMargins.left(), sourceMargins.bottom())));
targetData[index].append(QRectF(QPointF(xTarget[0], yTarget[rows - 1]), QPointF(xTarget[1], yTarget[rows])));
}
if (targetMargins.bottom() > 0 && targetMargins.right() > 0 && sourceMargins.bottom() > 0 && sourceMargins.right() > 0) { // bottom right
int index = bool(hints & QDrawBorderPixmap::OpaqueBottomRight);
sourceData[index].append(QRectF(QPointF(sourceCenterRight, sourceCenterBottom), QSizeF(sourceMargins.right(), sourceMargins.bottom())));
targetData[index].append(QRectF(QPointF(xTarget[columns - 1], yTarget[rows - 1]), QPointF(xTarget[columns], yTarget[rows])));
}
// horizontal edges
if (targetCenterWidth > 0 && sourceCenterWidth > 0) {
if (targetMargins.top() > 0 && sourceMargins.top() > 0) { // top
int index = bool(hints & QDrawBorderPixmap::OpaqueTop);
for (int i = 1; i < columns - 1; ++i) {
if (rules.horizontal == Qt::RepeatTile && i == columns - 2) {
sourceData[index].append(QRectF(QPointF(sourceCenterLeft, sourceRect.top()), QSizeF(xTarget[i + 1] - xTarget[i], sourceMargins.top())));
} else {
sourceData[index].append(QRectF(QPointF(sourceCenterLeft, sourceRect.top()), QSizeF(sourceCenterWidth, sourceMargins.top())));
}
targetData[index].append(QRectF(QPointF(xTarget[i], yTarget[0]), QPointF(xTarget[i + 1], yTarget[1])));
}
}
if (targetMargins.bottom() > 0 && sourceMargins.bottom() > 0) { // bottom
int index = bool(hints & QDrawBorderPixmap::OpaqueBottom);
for (int i = 1; i < columns - 1; ++i) {
if (rules.horizontal == Qt::RepeatTile && i == columns - 2) {
sourceData[index].append(QRectF(QPointF(sourceCenterLeft, sourceCenterBottom), QSizeF(xTarget[i + 1] - xTarget[i], sourceMargins.bottom())));
} else {
sourceData[index].append(QRectF(QPointF(sourceCenterLeft, sourceCenterBottom), QSizeF(sourceCenterWidth, sourceMargins.bottom())));
}
targetData[index].append(QRectF(QPointF(xTarget[i], yTarget[rows - 1]), QPointF(xTarget[i + 1], yTarget[rows])));
}
}
}
// vertical edges
if (targetCenterHeight > 0 && sourceCenterHeight > 0) {
if (targetMargins.left() > 0 && sourceMargins.left() > 0) { // left
int index = bool(hints & QDrawBorderPixmap::OpaqueLeft);
for (int i = 1; i < rows - 1; ++i) {
if (rules.vertical == Qt::RepeatTile && i == rows - 2) {
sourceData[index].append(QRectF(QPointF(sourceRect.left(), sourceCenterTop), QSizeF(sourceMargins.left(), yTarget[i + 1] - yTarget[i])));
} else {
sourceData[index].append(QRectF(QPointF(sourceRect.left(), sourceCenterTop), QSizeF(sourceMargins.left(), sourceCenterHeight)));
}
targetData[index].append(QRectF(QPointF(xTarget[0], yTarget[i]), QPointF(xTarget[1], yTarget[i + 1])));
}
}
if (targetMargins.right() > 0 && sourceMargins.right() > 0) { // right
int index = bool(hints & QDrawBorderPixmap::OpaqueRight);
for (int i = 1; i < rows - 1; ++i) {
if (rules.vertical == Qt::RepeatTile && i == rows - 2) {
sourceData[index].append(QRectF(QPointF(sourceCenterRight, sourceCenterTop), QSizeF(sourceMargins.right(), yTarget[i + 1] - yTarget[i])));
} else {
sourceData[index].append(QRectF(QPointF(sourceCenterRight, sourceCenterTop), QSizeF(sourceMargins.right(), sourceCenterHeight)));
}
targetData[index].append(QRectF(QPointF(xTarget[columns - 1], yTarget[i]), QPointF(xTarget[columns], yTarget[i + 1])));
}
}
}
// center
if (targetCenterWidth > 0 && targetCenterHeight > 0 && sourceCenterWidth > 0 && sourceCenterHeight > 0) {
int index = bool(hints & QDrawBorderPixmap::OpaqueCenter);
for (int j = 1; j < rows - 1; ++j) {
qreal sourceHeight = (rules.vertical == Qt::RepeatTile && j == rows - 2) ? yTarget[j + 1] - yTarget[j] : sourceCenterHeight;
for (int i = 1; i < columns - 1; ++i) {
qreal sourceWidth = (rules.horizontal == Qt::RepeatTile && i == columns - 2) ? xTarget[i + 1] - xTarget[i] : sourceCenterWidth;
sourceData[index].append(QRectF(QPointF(sourceCenterLeft, sourceCenterTop), QSizeF(sourceWidth, sourceHeight)));
targetData[index].append(QRectF(QPointF(xTarget[i], yTarget[j]), QPointF(xTarget[i + 1], yTarget[j + 1])));
}
}
}
for (int i = 0; i < 2; ++i) {
if (sourceData[i].size())
painter->drawPixmapFragments(targetData[i].data(), sourceData[i].data(), sourceData[i].size(), pixmap, i == 1 ? QPainter::OpaqueHint : QPainter::PixmapFragmentHint(0));
}
if (oldAA)
painter->setRenderHint(QPainter::Antialiasing, true);
}
QT_END_NAMESPACE
| bsd-3-clause |
thesocialstation/jcabi-http | src/test/java/com/jcabi/http/response/package-info.java | 1642 | /*
* Copyright (c) 2011-2017, jcabi.com
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met: 1) Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer. 2) Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials provided
* with the distribution. 3) Neither the name of the jcabi.com nor
* the names of its contributors may be used to endorse or promote
* products derived from this software without specific prior written
* permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT
* NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL
* THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
/**
* Responses, tests.
*
* @since 0.10
*/
package com.jcabi.http.response;
| bsd-3-clause |
heiglandreas/zf2 | tests/Zend/Db/Adapter/MysqliTest.php | 9235 | <?php
/**
* Zend Framework
*
* LICENSE
*
* This source file is subject to the new BSD license that is bundled
* with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://framework.zend.com/license/new-bsd
* If you did not receive a copy of the license and are unable to
* obtain it through the world-wide-web, please send an email
* to license@zend.com so we can send you a copy immediately.
*
* @category Zend
* @package Zend_Db
* @subpackage UnitTests
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @version $Id$
*/
/**
* @namespace
*/
namespace ZendTest\Db\Adapter;
use Zend\Db;
/**
* @category Zend
* @package Zend_Db
* @subpackage UnitTests
* @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @group Zend_Db
* @group Zend_Db_Adapter
*/
class MysqliTest extends AbstractTest
{
protected $_numericDataTypes = array(
Db\Db::INT_TYPE => Db\Db::INT_TYPE,
Db\Db::BIGINT_TYPE => Db\Db::BIGINT_TYPE,
Db\Db::FLOAT_TYPE => Db\Db::FLOAT_TYPE,
'INT' => Db\Db::INT_TYPE,
'INTEGER' => Db\Db::INT_TYPE,
'MEDIUMINT' => Db\Db::INT_TYPE,
'SMALLINT' => Db\Db::INT_TYPE,
'TINYINT' => Db\Db::INT_TYPE,
'BIGINT' => Db\Db::BIGINT_TYPE,
'SERIAL' => Db\Db::BIGINT_TYPE,
'DEC' => Db\Db::FLOAT_TYPE,
'DECIMAL' => Db\Db::FLOAT_TYPE,
'DOUBLE' => Db\Db::FLOAT_TYPE,
'DOUBLE PRECISION' => Db\Db::FLOAT_TYPE,
'FIXED' => Db\Db::FLOAT_TYPE,
'FLOAT' => Db\Db::FLOAT_TYPE
);
public function setup()
{
$this->markTestSkipped('This suite is skipped until Zend\Db can be refactored.');
}
/**
* Test AUTO_QUOTE_IDENTIFIERS option
* Case: Zend_Db::AUTO_QUOTE_IDENTIFIERS = true
*
* MySQL actually allows delimited identifiers to remain
* case-insensitive, so this test overrides its parent.
*/
public function testAdapterAutoQuoteIdentifiersTrue()
{
$params = $this->_util->getParams();
$params['options'] = array(
Db\Db::AUTO_QUOTE_IDENTIFIERS => true
);
$db = Db\Db::factory($this->getDriver(), $params);
$db->getConnection();
$select = $this->_db->select();
$select->from('zfproducts');
$stmt = $this->_db->query($select);
$result1 = $stmt->fetchAll();
$this->assertEquals(3, count($result1), 'Expected 3 rows in first query result');
$this->assertEquals(1, $result1[0]['product_id']);
$select = $this->_db->select();
$select->from('zfproducts');
try {
$stmt = $this->_db->query($select);
$result2 = $stmt->fetchAll();
$this->assertEquals(3, count($result2), 'Expected 3 rows in second query result');
$this->assertEquals($result1, $result2);
} catch (\Zend\Exception $e) {
$this->fail('exception caught where none was expected.');
}
}
public function testAdapterInsertSequence()
{
$this->markTestSkipped($this->getDriver() . ' does not support sequences');
}
/**
* test that quoteColumnAs() accepts a string
* and an alias, and returns each as delimited
* identifiers, with 'AS' in between.
*/
public function testAdapterQuoteColumnAs()
{
$string = "foo";
$alias = "bar";
$value = $this->_db->quoteColumnAs($string, $alias);
$this->assertEquals('`foo` AS `bar`', $value);
}
/**
* test that quoteColumnAs() accepts a string
* and an alias, but ignores the alias if it is
* the same as the base identifier in the string.
*/
public function testAdapterQuoteColumnAsSameString()
{
$string = 'foo.bar';
$alias = 'bar';
$value = $this->_db->quoteColumnAs($string, $alias);
$this->assertEquals('`foo`.`bar`', $value);
}
/**
* test that quoteIdentifier() accepts a string
* and returns a delimited identifier.
*/
public function testAdapterQuoteIdentifier()
{
$value = $this->_db->quoteIdentifier('table_name');
$this->assertEquals('`table_name`', $value);
}
/**
* test that quoteIdentifier() accepts an array
* and returns a qualified delimited identifier.
*/
public function testAdapterQuoteIdentifierArray()
{
$array = array('foo', 'bar');
$value = $this->_db->quoteIdentifier($array);
$this->assertEquals('`foo`.`bar`', $value);
}
/**
* test that quoteIdentifier() accepts an array
* containing a Zend_Db_Expr, and returns strings
* as delimited identifiers, and Exprs as unquoted.
*/
public function testAdapterQuoteIdentifierArrayDbExpr()
{
$expr = new Db\Expr('*');
$array = array('foo', $expr);
$value = $this->_db->quoteIdentifier($array);
$this->assertEquals('`foo`.*', $value);
}
/**
* test that quoteIdentifer() escapes a double-quote
* character in a string.
*/
public function testAdapterQuoteIdentifierDoubleQuote()
{
$string = 'table_"_name';
$value = $this->_db->quoteIdentifier($string);
$this->assertEquals('`table_"_name`', $value);
}
/**
* test that quoteIdentifer() accepts an integer
* and returns a delimited identifier as with a string.
*/
public function testAdapterQuoteIdentifierInteger()
{
$int = 123;
$value = $this->_db->quoteIdentifier($int);
$this->assertEquals('`123`', $value);
}
/**
* test that quoteIdentifier() accepts a string
* containing a dot (".") character, splits the
* string, quotes each segment individually as
* delimited identifers, and returns the imploded
* string.
*/
public function testAdapterQuoteIdentifierQualified()
{
$string = 'table.column';
$value = $this->_db->quoteIdentifier($string);
$this->assertEquals('`table`.`column`', $value);
}
/**
* test that quoteIdentifer() escapes a single-quote
* character in a string.
*/
public function testAdapterQuoteIdentifierSingleQuote()
{
$string = "table_'_name";
$value = $this->_db->quoteIdentifier($string);
$this->assertEquals('`table_\'_name`', $value);
}
/**
* test that quoteTableAs() accepts a string and an alias,
* and returns each as delimited identifiers.
* Most RDBMS want an 'AS' in between.
*/
public function testAdapterQuoteTableAs()
{
$string = "foo";
$alias = "bar";
$value = $this->_db->quoteTableAs($string, $alias);
$this->assertEquals('`foo` AS `bar`', $value);
}
/**
* test that describeTable() returns correct types
* @group ZF-3624
*
*/
public function testAdapterDescribeTableAttributeColumnFloat()
{
$desc = $this->_db->describeTable('zfprice');
$this->assertEquals('zfprice', $desc['price']['TABLE_NAME']);
$this->assertRegExp('/float/i', $desc['price']['DATA_TYPE']);
}
/**
* Ensures that the PDO Buffered Query does not throw the error
* 2014 General error
*
* @group ZF-2101
* @link http://framework.zend.com/issues/browse/ZF-2101
* @return void
*/
public function testAdapterToEnsurePdoBufferedQueryThrowsNoError()
{
$params = $this->_util->getParams();
$db = Db\Db::factory($this->getDriver(), $params);
// Set default bound value
$customerId = 1;
// Stored procedure returns a single row
$stmt = $db->prepare('CALL zf_test_procedure(?)');
$stmt->bindParam(1, $customerId);
$stmt->execute();
$result = $stmt->fetchAll();
$this->assertEquals(1, $result[0]['product_id']);
// Reset statement
$stmt->closeCursor();
// Stored procedure returns a single row
$stmt = $db->prepare('CALL zf_test_procedure(?)');
$stmt->bindParam(1, $customerId);
$stmt->execute();
$this->assertEquals(1, $result[0]['product_id']);
}
public function testAdapterAlternateStatement()
{
$this->_testAdapterAlternateStatement('Test_MysqliStatement');
}
public function testMySqliInitCommand()
{
$params = $this->_util->getParams();
$params['driver_options'] = array(
'mysqli_init_command' => 'SET AUTOCOMMIT=0;'
);
$db = Db\Db::factory($this->getDriver(), $params);
$sql = 'SELECT @@AUTOCOMMIT as autocommit';
$row = $db->fetchRow($sql);
$this->assertEquals(0, $row['autocommit']);
}
public function getDriver()
{
return 'Mysqli';
}
}
| bsd-3-clause |
rimbalinux/LMD3 | django/conf/locale/th/formats.py | 767 | # -*- encoding: utf-8 -*-
# This file is distributed under the same license as the Django package.
#
# The *_FORMAT strings use the Django date format syntax,
# see http://docs.djangoproject.com/en/dev/ref/templates/builtins/#date
DATE_FORMAT = 'j F Y'
TIME_FORMAT = 'G:i:s'
DATETIME_FORMAT = 'j F Y, G:i:s'
YEAR_MONTH_FORMAT = 'F Y'
MONTH_DAY_FORMAT = 'j F'
SHORT_DATE_FORMAT = 'j M Y'
SHORT_DATETIME_FORMAT = 'j M Y, G:i:s'
# FIRST_DAY_OF_WEEK =
# The *_INPUT_FORMATS strings use the Python strftime format syntax,
# see http://docs.python.org/library/datetime.html#strftime-strptime-behavior
# DATE_INPUT_FORMATS =
# TIME_INPUT_FORMATS =
# DATETIME_INPUT_FORMATS =
DECIMAL_SEPARATOR = '.'
THOUSAND_SEPARATOR = ','
# NUMBER_GROUPING =
| bsd-3-clause |
axinging/chromium-crosswalk | chrome/browser/ui/views/tabs/window_finder_ash.cc | 2205 | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/views/tabs/window_finder.h"
#include "ash/shell_window_ids.h"
#include "ash/wm/aura/wm_window_aura.h"
#include "ash/wm/common/root_window_finder.h"
#include "ui/aura/client/screen_position_client.h"
#include "ui/aura/window.h"
#include "ui/aura/window_event_dispatcher.h"
#include "ui/wm/core/window_util.h"
namespace {
gfx::NativeWindow GetLocalProcessWindowAtPointImpl(
const gfx::Point& screen_point,
const std::set<gfx::NativeWindow>& ignore,
gfx::NativeWindow window) {
if (ignore.find(window) != ignore.end())
return NULL;
if (!window->IsVisible())
return NULL;
if (window->id() == ash::kShellWindowId_PhantomWindow ||
window->id() == ash::kShellWindowId_OverlayContainer ||
window->id() == ash::kShellWindowId_MouseCursorContainer)
return NULL;
if (window->layer()->type() == ui::LAYER_TEXTURED) {
// Returns the window that has visible layer and can hit the
// |screen_point|, because we want to detach the tab as soon as
// the dragging mouse moved over to the window that can hide the
// moving tab.
aura::client::ScreenPositionClient* client =
aura::client::GetScreenPositionClient(window->GetRootWindow());
gfx::Point local_point = screen_point;
client->ConvertPointFromScreen(window, &local_point);
return window->GetEventHandlerForPoint(local_point) ? window : nullptr;
}
for (aura::Window::Windows::const_reverse_iterator i =
window->children().rbegin(); i != window->children().rend(); ++i) {
gfx::NativeWindow result =
GetLocalProcessWindowAtPointImpl(screen_point, ignore, *i);
if (result)
return result;
}
return NULL;
}
} // namespace
gfx::NativeWindow GetLocalProcessWindowAtPointAsh(
const gfx::Point& screen_point,
const std::set<gfx::NativeWindow>& ignore) {
return GetLocalProcessWindowAtPointImpl(
screen_point, ignore, ash::wm::WmWindowAura::GetAuraWindow(
ash::wm::GetRootWindowAt(screen_point)));
}
| bsd-3-clause |
Umisoft/umi.framework-dev | library/hmvc/component/AccessRestrictedComponent.php | 807 | <?php
/**
* UMI.Framework (http://umi-framework.ru/)
*
* @link http://github.com/Umisoft/framework for the canonical source repository
* @copyright Copyright (c) 2007-2013 Umisoft ltd. (http://umisoft.ru/)
* @license http://umi-framework.ru/license/bsd-3 BSD-3 License
*/
namespace umi\hmvc\component;
use umi\acl\IAclResource;
/**
* Класс компонента, доступ к которому контролируется через ACL.
*/
class AccessRestrictedComponent extends Component implements IAclResource
{
/**
* Префикс имени ACL-ресурса
*/
const ACL_RESOURCE_PREFIX = 'component:';
/**
* {@inheritdoc}
*/
public function getAclResourceName()
{
return self::ACL_RESOURCE_PREFIX . $this->name;
}
}
| bsd-3-clause |
drorweiss/petri | sample-extended-filters/src/main/java/dynamic/filters/SomeCustomFilter.java | 530 | package dynamic.filters;
import com.wixpress.petri.experiments.domain.EligibilityCriteria;
import com.wixpress.petri.experiments.domain.Filter;
import com.wixpress.petri.experiments.domain.FilterTypeName;
/**
* Created by talyas on 2/1/15.
*/
@FilterTypeName("SomeCustomFilter")
public class SomeCustomFilter implements Filter {
@Override
public boolean isEligible(EligibilityCriteria eligibilityCriteria) {
throw new UnsupportedOperationException("this filter is only used for testing type loading");
}
}
| bsd-3-clause |
rbaindourov/v8-inspector | Source/chrome/v8/src/mips64/macro-assembler-mips64.cc | 193115 | // Copyright 2012 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <limits.h> // For LONG_MIN, LONG_MAX.
#include "src/v8.h"
#if V8_TARGET_ARCH_MIPS64
#include "src/base/division-by-constant.h"
#include "src/bootstrapper.h"
#include "src/codegen.h"
#include "src/cpu-profiler.h"
#include "src/debug.h"
#include "src/runtime/runtime.h"
namespace v8 {
namespace internal {
MacroAssembler::MacroAssembler(Isolate* arg_isolate, void* buffer, int size)
: Assembler(arg_isolate, buffer, size),
generating_stub_(false),
has_frame_(false),
has_double_zero_reg_set_(false) {
if (isolate() != NULL) {
code_object_ = Handle<Object>(isolate()->heap()->undefined_value(),
isolate());
}
}
void MacroAssembler::Load(Register dst,
const MemOperand& src,
Representation r) {
DCHECK(!r.IsDouble());
if (r.IsInteger8()) {
lb(dst, src);
} else if (r.IsUInteger8()) {
lbu(dst, src);
} else if (r.IsInteger16()) {
lh(dst, src);
} else if (r.IsUInteger16()) {
lhu(dst, src);
} else if (r.IsInteger32()) {
lw(dst, src);
} else {
ld(dst, src);
}
}
void MacroAssembler::Store(Register src,
const MemOperand& dst,
Representation r) {
DCHECK(!r.IsDouble());
if (r.IsInteger8() || r.IsUInteger8()) {
sb(src, dst);
} else if (r.IsInteger16() || r.IsUInteger16()) {
sh(src, dst);
} else if (r.IsInteger32()) {
sw(src, dst);
} else {
if (r.IsHeapObject()) {
AssertNotSmi(src);
} else if (r.IsSmi()) {
AssertSmi(src);
}
sd(src, dst);
}
}
void MacroAssembler::LoadRoot(Register destination,
Heap::RootListIndex index) {
ld(destination, MemOperand(s6, index << kPointerSizeLog2));
}
void MacroAssembler::LoadRoot(Register destination,
Heap::RootListIndex index,
Condition cond,
Register src1, const Operand& src2) {
Branch(2, NegateCondition(cond), src1, src2);
ld(destination, MemOperand(s6, index << kPointerSizeLog2));
}
void MacroAssembler::StoreRoot(Register source,
Heap::RootListIndex index) {
DCHECK(Heap::RootCanBeWrittenAfterInitialization(index));
sd(source, MemOperand(s6, index << kPointerSizeLog2));
}
void MacroAssembler::StoreRoot(Register source,
Heap::RootListIndex index,
Condition cond,
Register src1, const Operand& src2) {
DCHECK(Heap::RootCanBeWrittenAfterInitialization(index));
Branch(2, NegateCondition(cond), src1, src2);
sd(source, MemOperand(s6, index << kPointerSizeLog2));
}
// Push and pop all registers that can hold pointers.
void MacroAssembler::PushSafepointRegisters() {
// Safepoints expect a block of kNumSafepointRegisters values on the
// stack, so adjust the stack for unsaved registers.
const int num_unsaved = kNumSafepointRegisters - kNumSafepointSavedRegisters;
DCHECK(num_unsaved >= 0);
if (num_unsaved > 0) {
Dsubu(sp, sp, Operand(num_unsaved * kPointerSize));
}
MultiPush(kSafepointSavedRegisters);
}
void MacroAssembler::PopSafepointRegisters() {
const int num_unsaved = kNumSafepointRegisters - kNumSafepointSavedRegisters;
MultiPop(kSafepointSavedRegisters);
if (num_unsaved > 0) {
Daddu(sp, sp, Operand(num_unsaved * kPointerSize));
}
}
void MacroAssembler::StoreToSafepointRegisterSlot(Register src, Register dst) {
sd(src, SafepointRegisterSlot(dst));
}
void MacroAssembler::LoadFromSafepointRegisterSlot(Register dst, Register src) {
ld(dst, SafepointRegisterSlot(src));
}
int MacroAssembler::SafepointRegisterStackIndex(int reg_code) {
// The registers are pushed starting with the highest encoding,
// which means that lowest encodings are closest to the stack pointer.
return kSafepointRegisterStackIndexMap[reg_code];
}
MemOperand MacroAssembler::SafepointRegisterSlot(Register reg) {
return MemOperand(sp, SafepointRegisterStackIndex(reg.code()) * kPointerSize);
}
MemOperand MacroAssembler::SafepointRegistersAndDoublesSlot(Register reg) {
UNIMPLEMENTED_MIPS();
// General purpose registers are pushed last on the stack.
int doubles_size = FPURegister::NumAllocatableRegisters() * kDoubleSize;
int register_offset = SafepointRegisterStackIndex(reg.code()) * kPointerSize;
return MemOperand(sp, doubles_size + register_offset);
}
void MacroAssembler::InNewSpace(Register object,
Register scratch,
Condition cc,
Label* branch) {
DCHECK(cc == eq || cc == ne);
And(scratch, object, Operand(ExternalReference::new_space_mask(isolate())));
Branch(branch, cc, scratch,
Operand(ExternalReference::new_space_start(isolate())));
}
void MacroAssembler::RecordWriteField(
Register object,
int offset,
Register value,
Register dst,
RAStatus ra_status,
SaveFPRegsMode save_fp,
RememberedSetAction remembered_set_action,
SmiCheck smi_check,
PointersToHereCheck pointers_to_here_check_for_value) {
DCHECK(!AreAliased(value, dst, t8, object));
// First, check if a write barrier is even needed. The tests below
// catch stores of Smis.
Label done;
// Skip barrier if writing a smi.
if (smi_check == INLINE_SMI_CHECK) {
JumpIfSmi(value, &done);
}
// Although the object register is tagged, the offset is relative to the start
// of the object, so so offset must be a multiple of kPointerSize.
DCHECK(IsAligned(offset, kPointerSize));
Daddu(dst, object, Operand(offset - kHeapObjectTag));
if (emit_debug_code()) {
Label ok;
And(t8, dst, Operand((1 << kPointerSizeLog2) - 1));
Branch(&ok, eq, t8, Operand(zero_reg));
stop("Unaligned cell in write barrier");
bind(&ok);
}
RecordWrite(object,
dst,
value,
ra_status,
save_fp,
remembered_set_action,
OMIT_SMI_CHECK,
pointers_to_here_check_for_value);
bind(&done);
// Clobber clobbered input registers when running with the debug-code flag
// turned on to provoke errors.
if (emit_debug_code()) {
li(value, Operand(bit_cast<int64_t>(kZapValue + 4)));
li(dst, Operand(bit_cast<int64_t>(kZapValue + 8)));
}
}
// Will clobber 4 registers: object, map, dst, ip. The
// register 'object' contains a heap object pointer.
void MacroAssembler::RecordWriteForMap(Register object,
Register map,
Register dst,
RAStatus ra_status,
SaveFPRegsMode fp_mode) {
if (emit_debug_code()) {
DCHECK(!dst.is(at));
ld(dst, FieldMemOperand(map, HeapObject::kMapOffset));
Check(eq,
kWrongAddressOrValuePassedToRecordWrite,
dst,
Operand(isolate()->factory()->meta_map()));
}
if (!FLAG_incremental_marking) {
return;
}
if (emit_debug_code()) {
ld(at, FieldMemOperand(object, HeapObject::kMapOffset));
Check(eq,
kWrongAddressOrValuePassedToRecordWrite,
map,
Operand(at));
}
Label done;
// A single check of the map's pages interesting flag suffices, since it is
// only set during incremental collection, and then it's also guaranteed that
// the from object's page's interesting flag is also set. This optimization
// relies on the fact that maps can never be in new space.
CheckPageFlag(map,
map, // Used as scratch.
MemoryChunk::kPointersToHereAreInterestingMask,
eq,
&done);
Daddu(dst, object, Operand(HeapObject::kMapOffset - kHeapObjectTag));
if (emit_debug_code()) {
Label ok;
And(at, dst, Operand((1 << kPointerSizeLog2) - 1));
Branch(&ok, eq, at, Operand(zero_reg));
stop("Unaligned cell in write barrier");
bind(&ok);
}
// Record the actual write.
if (ra_status == kRAHasNotBeenSaved) {
push(ra);
}
RecordWriteStub stub(isolate(), object, map, dst, OMIT_REMEMBERED_SET,
fp_mode);
CallStub(&stub);
if (ra_status == kRAHasNotBeenSaved) {
pop(ra);
}
bind(&done);
// Count number of write barriers in generated code.
isolate()->counters()->write_barriers_static()->Increment();
IncrementCounter(isolate()->counters()->write_barriers_dynamic(), 1, at, dst);
// Clobber clobbered registers when running with the debug-code flag
// turned on to provoke errors.
if (emit_debug_code()) {
li(dst, Operand(bit_cast<int64_t>(kZapValue + 12)));
li(map, Operand(bit_cast<int64_t>(kZapValue + 16)));
}
}
// Will clobber 4 registers: object, address, scratch, ip. The
// register 'object' contains a heap object pointer. The heap object
// tag is shifted away.
void MacroAssembler::RecordWrite(
Register object,
Register address,
Register value,
RAStatus ra_status,
SaveFPRegsMode fp_mode,
RememberedSetAction remembered_set_action,
SmiCheck smi_check,
PointersToHereCheck pointers_to_here_check_for_value) {
DCHECK(!AreAliased(object, address, value, t8));
DCHECK(!AreAliased(object, address, value, t9));
if (emit_debug_code()) {
ld(at, MemOperand(address));
Assert(
eq, kWrongAddressOrValuePassedToRecordWrite, at, Operand(value));
}
if (remembered_set_action == OMIT_REMEMBERED_SET &&
!FLAG_incremental_marking) {
return;
}
// First, check if a write barrier is even needed. The tests below
// catch stores of smis and stores into the young generation.
Label done;
if (smi_check == INLINE_SMI_CHECK) {
DCHECK_EQ(0, kSmiTag);
JumpIfSmi(value, &done);
}
if (pointers_to_here_check_for_value != kPointersToHereAreAlwaysInteresting) {
CheckPageFlag(value,
value, // Used as scratch.
MemoryChunk::kPointersToHereAreInterestingMask,
eq,
&done);
}
CheckPageFlag(object,
value, // Used as scratch.
MemoryChunk::kPointersFromHereAreInterestingMask,
eq,
&done);
// Record the actual write.
if (ra_status == kRAHasNotBeenSaved) {
push(ra);
}
RecordWriteStub stub(isolate(), object, value, address, remembered_set_action,
fp_mode);
CallStub(&stub);
if (ra_status == kRAHasNotBeenSaved) {
pop(ra);
}
bind(&done);
// Count number of write barriers in generated code.
isolate()->counters()->write_barriers_static()->Increment();
IncrementCounter(isolate()->counters()->write_barriers_dynamic(), 1, at,
value);
// Clobber clobbered registers when running with the debug-code flag
// turned on to provoke errors.
if (emit_debug_code()) {
li(address, Operand(bit_cast<int64_t>(kZapValue + 12)));
li(value, Operand(bit_cast<int64_t>(kZapValue + 16)));
}
}
void MacroAssembler::RememberedSetHelper(Register object, // For debug tests.
Register address,
Register scratch,
SaveFPRegsMode fp_mode,
RememberedSetFinalAction and_then) {
Label done;
if (emit_debug_code()) {
Label ok;
JumpIfNotInNewSpace(object, scratch, &ok);
stop("Remembered set pointer is in new space");
bind(&ok);
}
// Load store buffer top.
ExternalReference store_buffer =
ExternalReference::store_buffer_top(isolate());
li(t8, Operand(store_buffer));
ld(scratch, MemOperand(t8));
// Store pointer to buffer and increment buffer top.
sd(address, MemOperand(scratch));
Daddu(scratch, scratch, kPointerSize);
// Write back new top of buffer.
sd(scratch, MemOperand(t8));
// Call stub on end of buffer.
// Check for end of buffer.
And(t8, scratch, Operand(StoreBuffer::kStoreBufferOverflowBit));
DCHECK(!scratch.is(t8));
if (and_then == kFallThroughAtEnd) {
Branch(&done, eq, t8, Operand(zero_reg));
} else {
DCHECK(and_then == kReturnAtEnd);
Ret(eq, t8, Operand(zero_reg));
}
push(ra);
StoreBufferOverflowStub store_buffer_overflow(isolate(), fp_mode);
CallStub(&store_buffer_overflow);
pop(ra);
bind(&done);
if (and_then == kReturnAtEnd) {
Ret();
}
}
// -----------------------------------------------------------------------------
// Allocation support.
void MacroAssembler::CheckAccessGlobalProxy(Register holder_reg,
Register scratch,
Label* miss) {
Label same_contexts;
DCHECK(!holder_reg.is(scratch));
DCHECK(!holder_reg.is(at));
DCHECK(!scratch.is(at));
// Load current lexical context from the stack frame.
ld(scratch, MemOperand(fp, StandardFrameConstants::kContextOffset));
// In debug mode, make sure the lexical context is set.
#ifdef DEBUG
Check(ne, kWeShouldNotHaveAnEmptyLexicalContext,
scratch, Operand(zero_reg));
#endif
// Load the native context of the current context.
int offset =
Context::kHeaderSize + Context::GLOBAL_OBJECT_INDEX * kPointerSize;
ld(scratch, FieldMemOperand(scratch, offset));
ld(scratch, FieldMemOperand(scratch, GlobalObject::kNativeContextOffset));
// Check the context is a native context.
if (emit_debug_code()) {
push(holder_reg); // Temporarily save holder on the stack.
// Read the first word and compare to the native_context_map.
ld(holder_reg, FieldMemOperand(scratch, HeapObject::kMapOffset));
LoadRoot(at, Heap::kNativeContextMapRootIndex);
Check(eq, kJSGlobalObjectNativeContextShouldBeANativeContext,
holder_reg, Operand(at));
pop(holder_reg); // Restore holder.
}
// Check if both contexts are the same.
ld(at, FieldMemOperand(holder_reg, JSGlobalProxy::kNativeContextOffset));
Branch(&same_contexts, eq, scratch, Operand(at));
// Check the context is a native context.
if (emit_debug_code()) {
push(holder_reg); // Temporarily save holder on the stack.
mov(holder_reg, at); // Move at to its holding place.
LoadRoot(at, Heap::kNullValueRootIndex);
Check(ne, kJSGlobalProxyContextShouldNotBeNull,
holder_reg, Operand(at));
ld(holder_reg, FieldMemOperand(holder_reg, HeapObject::kMapOffset));
LoadRoot(at, Heap::kNativeContextMapRootIndex);
Check(eq, kJSGlobalObjectNativeContextShouldBeANativeContext,
holder_reg, Operand(at));
// Restore at is not needed. at is reloaded below.
pop(holder_reg); // Restore holder.
// Restore at to holder's context.
ld(at, FieldMemOperand(holder_reg, JSGlobalProxy::kNativeContextOffset));
}
// Check that the security token in the calling global object is
// compatible with the security token in the receiving global
// object.
int token_offset = Context::kHeaderSize +
Context::SECURITY_TOKEN_INDEX * kPointerSize;
ld(scratch, FieldMemOperand(scratch, token_offset));
ld(at, FieldMemOperand(at, token_offset));
Branch(miss, ne, scratch, Operand(at));
bind(&same_contexts);
}
// Compute the hash code from the untagged key. This must be kept in sync with
// ComputeIntegerHash in utils.h and KeyedLoadGenericStub in
// code-stub-hydrogen.cc
void MacroAssembler::GetNumberHash(Register reg0, Register scratch) {
// First of all we assign the hash seed to scratch.
LoadRoot(scratch, Heap::kHashSeedRootIndex);
SmiUntag(scratch);
// Xor original key with a seed.
xor_(reg0, reg0, scratch);
// Compute the hash code from the untagged key. This must be kept in sync
// with ComputeIntegerHash in utils.h.
//
// hash = ~hash + (hash << 15);
// The algorithm uses 32-bit integer values.
nor(scratch, reg0, zero_reg);
sll(at, reg0, 15);
addu(reg0, scratch, at);
// hash = hash ^ (hash >> 12);
srl(at, reg0, 12);
xor_(reg0, reg0, at);
// hash = hash + (hash << 2);
sll(at, reg0, 2);
addu(reg0, reg0, at);
// hash = hash ^ (hash >> 4);
srl(at, reg0, 4);
xor_(reg0, reg0, at);
// hash = hash * 2057;
sll(scratch, reg0, 11);
sll(at, reg0, 3);
addu(reg0, reg0, at);
addu(reg0, reg0, scratch);
// hash = hash ^ (hash >> 16);
srl(at, reg0, 16);
xor_(reg0, reg0, at);
}
void MacroAssembler::LoadFromNumberDictionary(Label* miss,
Register elements,
Register key,
Register result,
Register reg0,
Register reg1,
Register reg2) {
// Register use:
//
// elements - holds the slow-case elements of the receiver on entry.
// Unchanged unless 'result' is the same register.
//
// key - holds the smi key on entry.
// Unchanged unless 'result' is the same register.
//
//
// result - holds the result on exit if the load succeeded.
// Allowed to be the same as 'key' or 'result'.
// Unchanged on bailout so 'key' or 'result' can be used
// in further computation.
//
// Scratch registers:
//
// reg0 - holds the untagged key on entry and holds the hash once computed.
//
// reg1 - Used to hold the capacity mask of the dictionary.
//
// reg2 - Used for the index into the dictionary.
// at - Temporary (avoid MacroAssembler instructions also using 'at').
Label done;
GetNumberHash(reg0, reg1);
// Compute the capacity mask.
ld(reg1, FieldMemOperand(elements, SeededNumberDictionary::kCapacityOffset));
SmiUntag(reg1, reg1);
Dsubu(reg1, reg1, Operand(1));
// Generate an unrolled loop that performs a few probes before giving up.
for (int i = 0; i < kNumberDictionaryProbes; i++) {
// Use reg2 for index calculations and keep the hash intact in reg0.
mov(reg2, reg0);
// Compute the masked index: (hash + i + i * i) & mask.
if (i > 0) {
Daddu(reg2, reg2, Operand(SeededNumberDictionary::GetProbeOffset(i)));
}
and_(reg2, reg2, reg1);
// Scale the index by multiplying by the element size.
DCHECK(SeededNumberDictionary::kEntrySize == 3);
dsll(at, reg2, 1); // 2x.
daddu(reg2, reg2, at); // reg2 = reg2 * 3.
// Check if the key is identical to the name.
dsll(at, reg2, kPointerSizeLog2);
daddu(reg2, elements, at);
ld(at, FieldMemOperand(reg2, SeededNumberDictionary::kElementsStartOffset));
if (i != kNumberDictionaryProbes - 1) {
Branch(&done, eq, key, Operand(at));
} else {
Branch(miss, ne, key, Operand(at));
}
}
bind(&done);
// Check that the value is a field property.
// reg2: elements + (index * kPointerSize).
const int kDetailsOffset =
SeededNumberDictionary::kElementsStartOffset + 2 * kPointerSize;
ld(reg1, FieldMemOperand(reg2, kDetailsOffset));
DCHECK_EQ(DATA, 0);
And(at, reg1, Operand(Smi::FromInt(PropertyDetails::TypeField::kMask)));
Branch(miss, ne, at, Operand(zero_reg));
// Get the value at the masked, scaled index and return.
const int kValueOffset =
SeededNumberDictionary::kElementsStartOffset + kPointerSize;
ld(result, FieldMemOperand(reg2, kValueOffset));
}
// ---------------------------------------------------------------------------
// Instruction macros.
void MacroAssembler::Addu(Register rd, Register rs, const Operand& rt) {
if (rt.is_reg()) {
addu(rd, rs, rt.rm());
} else {
if (is_int16(rt.imm64_) && !MustUseReg(rt.rmode_)) {
addiu(rd, rs, rt.imm64_);
} else {
// li handles the relocation.
DCHECK(!rs.is(at));
li(at, rt);
addu(rd, rs, at);
}
}
}
void MacroAssembler::Daddu(Register rd, Register rs, const Operand& rt) {
if (rt.is_reg()) {
daddu(rd, rs, rt.rm());
} else {
if (is_int16(rt.imm64_) && !MustUseReg(rt.rmode_)) {
daddiu(rd, rs, rt.imm64_);
} else {
// li handles the relocation.
DCHECK(!rs.is(at));
li(at, rt);
daddu(rd, rs, at);
}
}
}
void MacroAssembler::Subu(Register rd, Register rs, const Operand& rt) {
if (rt.is_reg()) {
subu(rd, rs, rt.rm());
} else {
if (is_int16(rt.imm64_) && !MustUseReg(rt.rmode_)) {
addiu(rd, rs, -rt.imm64_); // No subiu instr, use addiu(x, y, -imm).
} else {
// li handles the relocation.
DCHECK(!rs.is(at));
li(at, rt);
subu(rd, rs, at);
}
}
}
void MacroAssembler::Dsubu(Register rd, Register rs, const Operand& rt) {
if (rt.is_reg()) {
dsubu(rd, rs, rt.rm());
} else {
if (is_int16(rt.imm64_) && !MustUseReg(rt.rmode_)) {
daddiu(rd, rs, -rt.imm64_); // No subiu instr, use addiu(x, y, -imm).
} else {
// li handles the relocation.
DCHECK(!rs.is(at));
li(at, rt);
dsubu(rd, rs, at);
}
}
}
void MacroAssembler::Mul(Register rd, Register rs, const Operand& rt) {
if (rt.is_reg()) {
mul(rd, rs, rt.rm());
} else {
// li handles the relocation.
DCHECK(!rs.is(at));
li(at, rt);
mul(rd, rs, at);
}
}
void MacroAssembler::Mulh(Register rd, Register rs, const Operand& rt) {
if (rt.is_reg()) {
if (kArchVariant != kMips64r6) {
mult(rs, rt.rm());
mfhi(rd);
} else {
muh(rd, rs, rt.rm());
}
} else {
// li handles the relocation.
DCHECK(!rs.is(at));
li(at, rt);
if (kArchVariant != kMips64r6) {
mult(rs, at);
mfhi(rd);
} else {
muh(rd, rs, at);
}
}
}
void MacroAssembler::Mulhu(Register rd, Register rs, const Operand& rt) {
if (rt.is_reg()) {
if (kArchVariant != kMips64r6) {
multu(rs, rt.rm());
mfhi(rd);
} else {
muhu(rd, rs, rt.rm());
}
} else {
// li handles the relocation.
DCHECK(!rs.is(at));
li(at, rt);
if (kArchVariant != kMips64r6) {
multu(rs, at);
mfhi(rd);
} else {
muhu(rd, rs, at);
}
}
}
void MacroAssembler::Dmul(Register rd, Register rs, const Operand& rt) {
if (rt.is_reg()) {
if (kArchVariant == kMips64r6) {
dmul(rd, rs, rt.rm());
} else {
dmult(rs, rt.rm());
mflo(rd);
}
} else {
// li handles the relocation.
DCHECK(!rs.is(at));
li(at, rt);
if (kArchVariant == kMips64r6) {
dmul(rd, rs, at);
} else {
dmult(rs, at);
mflo(rd);
}
}
}
void MacroAssembler::Dmulh(Register rd, Register rs, const Operand& rt) {
if (rt.is_reg()) {
if (kArchVariant == kMips64r6) {
dmuh(rd, rs, rt.rm());
} else {
dmult(rs, rt.rm());
mfhi(rd);
}
} else {
// li handles the relocation.
DCHECK(!rs.is(at));
li(at, rt);
if (kArchVariant == kMips64r6) {
dmuh(rd, rs, at);
} else {
dmult(rs, at);
mfhi(rd);
}
}
}
void MacroAssembler::Mult(Register rs, const Operand& rt) {
if (rt.is_reg()) {
mult(rs, rt.rm());
} else {
// li handles the relocation.
DCHECK(!rs.is(at));
li(at, rt);
mult(rs, at);
}
}
void MacroAssembler::Dmult(Register rs, const Operand& rt) {
if (rt.is_reg()) {
dmult(rs, rt.rm());
} else {
// li handles the relocation.
DCHECK(!rs.is(at));
li(at, rt);
dmult(rs, at);
}
}
void MacroAssembler::Multu(Register rs, const Operand& rt) {
if (rt.is_reg()) {
multu(rs, rt.rm());
} else {
// li handles the relocation.
DCHECK(!rs.is(at));
li(at, rt);
multu(rs, at);
}
}
void MacroAssembler::Dmultu(Register rs, const Operand& rt) {
if (rt.is_reg()) {
dmultu(rs, rt.rm());
} else {
// li handles the relocation.
DCHECK(!rs.is(at));
li(at, rt);
dmultu(rs, at);
}
}
void MacroAssembler::Div(Register rs, const Operand& rt) {
if (rt.is_reg()) {
div(rs, rt.rm());
} else {
// li handles the relocation.
DCHECK(!rs.is(at));
li(at, rt);
div(rs, at);
}
}
void MacroAssembler::Div(Register res, Register rs, const Operand& rt) {
if (rt.is_reg()) {
if (kArchVariant != kMips64r6) {
div(rs, rt.rm());
mflo(res);
} else {
div(res, rs, rt.rm());
}
} else {
// li handles the relocation.
DCHECK(!rs.is(at));
li(at, rt);
if (kArchVariant != kMips64r6) {
div(rs, at);
mflo(res);
} else {
div(res, rs, at);
}
}
}
void MacroAssembler::Mod(Register rd, Register rs, const Operand& rt) {
if (rt.is_reg()) {
if (kArchVariant != kMips64r6) {
div(rs, rt.rm());
mfhi(rd);
} else {
mod(rd, rs, rt.rm());
}
} else {
// li handles the relocation.
DCHECK(!rs.is(at));
li(at, rt);
if (kArchVariant != kMips64r6) {
div(rs, at);
mfhi(rd);
} else {
mod(rd, rs, at);
}
}
}
void MacroAssembler::Modu(Register rd, Register rs, const Operand& rt) {
if (rt.is_reg()) {
if (kArchVariant != kMips64r6) {
divu(rs, rt.rm());
mfhi(rd);
} else {
modu(rd, rs, rt.rm());
}
} else {
// li handles the relocation.
DCHECK(!rs.is(at));
li(at, rt);
if (kArchVariant != kMips64r6) {
divu(rs, at);
mfhi(rd);
} else {
modu(rd, rs, at);
}
}
}
void MacroAssembler::Ddiv(Register rs, const Operand& rt) {
if (rt.is_reg()) {
ddiv(rs, rt.rm());
} else {
// li handles the relocation.
DCHECK(!rs.is(at));
li(at, rt);
ddiv(rs, at);
}
}
void MacroAssembler::Ddiv(Register rd, Register rs, const Operand& rt) {
if (kArchVariant != kMips64r6) {
if (rt.is_reg()) {
ddiv(rs, rt.rm());
mflo(rd);
} else {
// li handles the relocation.
DCHECK(!rs.is(at));
li(at, rt);
ddiv(rs, at);
mflo(rd);
}
} else {
if (rt.is_reg()) {
ddiv(rd, rs, rt.rm());
} else {
// li handles the relocation.
DCHECK(!rs.is(at));
li(at, rt);
ddiv(rd, rs, at);
}
}
}
void MacroAssembler::Divu(Register rs, const Operand& rt) {
if (rt.is_reg()) {
divu(rs, rt.rm());
} else {
// li handles the relocation.
DCHECK(!rs.is(at));
li(at, rt);
divu(rs, at);
}
}
void MacroAssembler::Divu(Register res, Register rs, const Operand& rt) {
if (rt.is_reg()) {
if (kArchVariant != kMips64r6) {
divu(rs, rt.rm());
mflo(res);
} else {
divu(res, rs, rt.rm());
}
} else {
// li handles the relocation.
DCHECK(!rs.is(at));
li(at, rt);
if (kArchVariant != kMips64r6) {
divu(rs, at);
mflo(res);
} else {
divu(res, rs, at);
}
}
}
void MacroAssembler::Ddivu(Register rs, const Operand& rt) {
if (rt.is_reg()) {
ddivu(rs, rt.rm());
} else {
// li handles the relocation.
DCHECK(!rs.is(at));
li(at, rt);
ddivu(rs, at);
}
}
void MacroAssembler::Ddivu(Register res, Register rs, const Operand& rt) {
if (rt.is_reg()) {
if (kArchVariant != kMips64r6) {
ddivu(rs, rt.rm());
mflo(res);
} else {
ddivu(res, rs, rt.rm());
}
} else {
// li handles the relocation.
DCHECK(!rs.is(at));
li(at, rt);
if (kArchVariant != kMips64r6) {
ddivu(rs, at);
mflo(res);
} else {
ddivu(res, rs, at);
}
}
}
void MacroAssembler::Dmod(Register rd, Register rs, const Operand& rt) {
if (kArchVariant != kMips64r6) {
if (rt.is_reg()) {
ddiv(rs, rt.rm());
mfhi(rd);
} else {
// li handles the relocation.
DCHECK(!rs.is(at));
li(at, rt);
ddiv(rs, at);
mfhi(rd);
}
} else {
if (rt.is_reg()) {
dmod(rd, rs, rt.rm());
} else {
// li handles the relocation.
DCHECK(!rs.is(at));
li(at, rt);
dmod(rd, rs, at);
}
}
}
void MacroAssembler::Dmodu(Register rd, Register rs, const Operand& rt) {
if (kArchVariant != kMips64r6) {
if (rt.is_reg()) {
ddivu(rs, rt.rm());
mfhi(rd);
} else {
// li handles the relocation.
DCHECK(!rs.is(at));
li(at, rt);
ddivu(rs, at);
mfhi(rd);
}
} else {
if (rt.is_reg()) {
dmodu(rd, rs, rt.rm());
} else {
// li handles the relocation.
DCHECK(!rs.is(at));
li(at, rt);
dmodu(rd, rs, at);
}
}
}
void MacroAssembler::And(Register rd, Register rs, const Operand& rt) {
if (rt.is_reg()) {
and_(rd, rs, rt.rm());
} else {
if (is_uint16(rt.imm64_) && !MustUseReg(rt.rmode_)) {
andi(rd, rs, rt.imm64_);
} else {
// li handles the relocation.
DCHECK(!rs.is(at));
li(at, rt);
and_(rd, rs, at);
}
}
}
void MacroAssembler::Or(Register rd, Register rs, const Operand& rt) {
if (rt.is_reg()) {
or_(rd, rs, rt.rm());
} else {
if (is_uint16(rt.imm64_) && !MustUseReg(rt.rmode_)) {
ori(rd, rs, rt.imm64_);
} else {
// li handles the relocation.
DCHECK(!rs.is(at));
li(at, rt);
or_(rd, rs, at);
}
}
}
void MacroAssembler::Xor(Register rd, Register rs, const Operand& rt) {
if (rt.is_reg()) {
xor_(rd, rs, rt.rm());
} else {
if (is_uint16(rt.imm64_) && !MustUseReg(rt.rmode_)) {
xori(rd, rs, rt.imm64_);
} else {
// li handles the relocation.
DCHECK(!rs.is(at));
li(at, rt);
xor_(rd, rs, at);
}
}
}
void MacroAssembler::Nor(Register rd, Register rs, const Operand& rt) {
if (rt.is_reg()) {
nor(rd, rs, rt.rm());
} else {
// li handles the relocation.
DCHECK(!rs.is(at));
li(at, rt);
nor(rd, rs, at);
}
}
void MacroAssembler::Neg(Register rs, const Operand& rt) {
DCHECK(rt.is_reg());
DCHECK(!at.is(rs));
DCHECK(!at.is(rt.rm()));
li(at, -1);
xor_(rs, rt.rm(), at);
}
void MacroAssembler::Slt(Register rd, Register rs, const Operand& rt) {
if (rt.is_reg()) {
slt(rd, rs, rt.rm());
} else {
if (is_int16(rt.imm64_) && !MustUseReg(rt.rmode_)) {
slti(rd, rs, rt.imm64_);
} else {
// li handles the relocation.
DCHECK(!rs.is(at));
li(at, rt);
slt(rd, rs, at);
}
}
}
void MacroAssembler::Sltu(Register rd, Register rs, const Operand& rt) {
if (rt.is_reg()) {
sltu(rd, rs, rt.rm());
} else {
if (is_int16(rt.imm64_) && !MustUseReg(rt.rmode_)) {
sltiu(rd, rs, rt.imm64_);
} else {
// li handles the relocation.
DCHECK(!rs.is(at));
li(at, rt);
sltu(rd, rs, at);
}
}
}
void MacroAssembler::Ror(Register rd, Register rs, const Operand& rt) {
if (rt.is_reg()) {
rotrv(rd, rs, rt.rm());
} else {
rotr(rd, rs, rt.imm64_);
}
}
void MacroAssembler::Dror(Register rd, Register rs, const Operand& rt) {
if (rt.is_reg()) {
drotrv(rd, rs, rt.rm());
} else {
drotr(rd, rs, rt.imm64_);
}
}
void MacroAssembler::Pref(int32_t hint, const MemOperand& rs) {
pref(hint, rs);
}
// ------------Pseudo-instructions-------------
void MacroAssembler::Ulw(Register rd, const MemOperand& rs) {
lwr(rd, rs);
lwl(rd, MemOperand(rs.rm(), rs.offset() + 3));
}
void MacroAssembler::Usw(Register rd, const MemOperand& rs) {
swr(rd, rs);
swl(rd, MemOperand(rs.rm(), rs.offset() + 3));
}
// Do 64-bit load from unaligned address. Note this only handles
// the specific case of 32-bit aligned, but not 64-bit aligned.
void MacroAssembler::Uld(Register rd, const MemOperand& rs, Register scratch) {
// Assert fail if the offset from start of object IS actually aligned.
// ONLY use with known misalignment, since there is performance cost.
DCHECK((rs.offset() + kHeapObjectTag) & (kPointerSize - 1));
// TODO(plind): endian dependency.
lwu(rd, rs);
lw(scratch, MemOperand(rs.rm(), rs.offset() + kPointerSize / 2));
dsll32(scratch, scratch, 0);
Daddu(rd, rd, scratch);
}
// Do 64-bit store to unaligned address. Note this only handles
// the specific case of 32-bit aligned, but not 64-bit aligned.
void MacroAssembler::Usd(Register rd, const MemOperand& rs, Register scratch) {
// Assert fail if the offset from start of object IS actually aligned.
// ONLY use with known misalignment, since there is performance cost.
DCHECK((rs.offset() + kHeapObjectTag) & (kPointerSize - 1));
// TODO(plind): endian dependency.
sw(rd, rs);
dsrl32(scratch, rd, 0);
sw(scratch, MemOperand(rs.rm(), rs.offset() + kPointerSize / 2));
}
void MacroAssembler::li(Register dst, Handle<Object> value, LiFlags mode) {
AllowDeferredHandleDereference smi_check;
if (value->IsSmi()) {
li(dst, Operand(value), mode);
} else {
DCHECK(value->IsHeapObject());
if (isolate()->heap()->InNewSpace(*value)) {
Handle<Cell> cell = isolate()->factory()->NewCell(value);
li(dst, Operand(cell));
ld(dst, FieldMemOperand(dst, Cell::kValueOffset));
} else {
li(dst, Operand(value));
}
}
}
void MacroAssembler::li(Register rd, Operand j, LiFlags mode) {
DCHECK(!j.is_reg());
BlockTrampolinePoolScope block_trampoline_pool(this);
if (!MustUseReg(j.rmode_) && mode == OPTIMIZE_SIZE) {
// Normal load of an immediate value which does not need Relocation Info.
if (is_int32(j.imm64_)) {
if (is_int16(j.imm64_)) {
daddiu(rd, zero_reg, (j.imm64_ & kImm16Mask));
} else if (!(j.imm64_ & kHiMask)) {
ori(rd, zero_reg, (j.imm64_ & kImm16Mask));
} else if (!(j.imm64_ & kImm16Mask)) {
lui(rd, (j.imm64_ >> kLuiShift) & kImm16Mask);
} else {
lui(rd, (j.imm64_ >> kLuiShift) & kImm16Mask);
ori(rd, rd, (j.imm64_ & kImm16Mask));
}
} else {
if (is_int48(j.imm64_)) {
if ((j.imm64_ >> 32) & kImm16Mask) {
lui(rd, (j.imm64_ >> 32) & kImm16Mask);
if ((j.imm64_ >> 16) & kImm16Mask) {
ori(rd, rd, (j.imm64_ >> 16) & kImm16Mask);
}
} else {
ori(rd, zero_reg, (j.imm64_ >> 16) & kImm16Mask);
}
dsll(rd, rd, 16);
if (j.imm64_ & kImm16Mask) {
ori(rd, rd, j.imm64_ & kImm16Mask);
}
} else {
lui(rd, (j.imm64_ >> 48) & kImm16Mask);
if ((j.imm64_ >> 32) & kImm16Mask) {
ori(rd, rd, (j.imm64_ >> 32) & kImm16Mask);
}
if ((j.imm64_ >> 16) & kImm16Mask) {
dsll(rd, rd, 16);
ori(rd, rd, (j.imm64_ >> 16) & kImm16Mask);
if (j.imm64_ & kImm16Mask) {
dsll(rd, rd, 16);
ori(rd, rd, j.imm64_ & kImm16Mask);
} else {
dsll(rd, rd, 16);
}
} else {
if (j.imm64_ & kImm16Mask) {
dsll32(rd, rd, 0);
ori(rd, rd, j.imm64_ & kImm16Mask);
} else {
dsll32(rd, rd, 0);
}
}
}
}
} else if (MustUseReg(j.rmode_)) {
RecordRelocInfo(j.rmode_, j.imm64_);
lui(rd, (j.imm64_ >> 32) & kImm16Mask);
ori(rd, rd, (j.imm64_ >> 16) & kImm16Mask);
dsll(rd, rd, 16);
ori(rd, rd, j.imm64_ & kImm16Mask);
} else if (mode == ADDRESS_LOAD) {
// We always need the same number of instructions as we may need to patch
// this code to load another value which may need all 4 instructions.
lui(rd, (j.imm64_ >> 32) & kImm16Mask);
ori(rd, rd, (j.imm64_ >> 16) & kImm16Mask);
dsll(rd, rd, 16);
ori(rd, rd, j.imm64_ & kImm16Mask);
} else {
lui(rd, (j.imm64_ >> 48) & kImm16Mask);
ori(rd, rd, (j.imm64_ >> 32) & kImm16Mask);
dsll(rd, rd, 16);
ori(rd, rd, (j.imm64_ >> 16) & kImm16Mask);
dsll(rd, rd, 16);
ori(rd, rd, j.imm64_ & kImm16Mask);
}
}
void MacroAssembler::MultiPush(RegList regs) {
int16_t num_to_push = NumberOfBitsSet(regs);
int16_t stack_offset = num_to_push * kPointerSize;
Dsubu(sp, sp, Operand(stack_offset));
for (int16_t i = kNumRegisters - 1; i >= 0; i--) {
if ((regs & (1 << i)) != 0) {
stack_offset -= kPointerSize;
sd(ToRegister(i), MemOperand(sp, stack_offset));
}
}
}
void MacroAssembler::MultiPushReversed(RegList regs) {
int16_t num_to_push = NumberOfBitsSet(regs);
int16_t stack_offset = num_to_push * kPointerSize;
Dsubu(sp, sp, Operand(stack_offset));
for (int16_t i = 0; i < kNumRegisters; i++) {
if ((regs & (1 << i)) != 0) {
stack_offset -= kPointerSize;
sd(ToRegister(i), MemOperand(sp, stack_offset));
}
}
}
void MacroAssembler::MultiPop(RegList regs) {
int16_t stack_offset = 0;
for (int16_t i = 0; i < kNumRegisters; i++) {
if ((regs & (1 << i)) != 0) {
ld(ToRegister(i), MemOperand(sp, stack_offset));
stack_offset += kPointerSize;
}
}
daddiu(sp, sp, stack_offset);
}
void MacroAssembler::MultiPopReversed(RegList regs) {
int16_t stack_offset = 0;
for (int16_t i = kNumRegisters - 1; i >= 0; i--) {
if ((regs & (1 << i)) != 0) {
ld(ToRegister(i), MemOperand(sp, stack_offset));
stack_offset += kPointerSize;
}
}
daddiu(sp, sp, stack_offset);
}
void MacroAssembler::MultiPushFPU(RegList regs) {
int16_t num_to_push = NumberOfBitsSet(regs);
int16_t stack_offset = num_to_push * kDoubleSize;
Dsubu(sp, sp, Operand(stack_offset));
for (int16_t i = kNumRegisters - 1; i >= 0; i--) {
if ((regs & (1 << i)) != 0) {
stack_offset -= kDoubleSize;
sdc1(FPURegister::from_code(i), MemOperand(sp, stack_offset));
}
}
}
void MacroAssembler::MultiPushReversedFPU(RegList regs) {
int16_t num_to_push = NumberOfBitsSet(regs);
int16_t stack_offset = num_to_push * kDoubleSize;
Dsubu(sp, sp, Operand(stack_offset));
for (int16_t i = 0; i < kNumRegisters; i++) {
if ((regs & (1 << i)) != 0) {
stack_offset -= kDoubleSize;
sdc1(FPURegister::from_code(i), MemOperand(sp, stack_offset));
}
}
}
void MacroAssembler::MultiPopFPU(RegList regs) {
int16_t stack_offset = 0;
for (int16_t i = 0; i < kNumRegisters; i++) {
if ((regs & (1 << i)) != 0) {
ldc1(FPURegister::from_code(i), MemOperand(sp, stack_offset));
stack_offset += kDoubleSize;
}
}
daddiu(sp, sp, stack_offset);
}
void MacroAssembler::MultiPopReversedFPU(RegList regs) {
int16_t stack_offset = 0;
for (int16_t i = kNumRegisters - 1; i >= 0; i--) {
if ((regs & (1 << i)) != 0) {
ldc1(FPURegister::from_code(i), MemOperand(sp, stack_offset));
stack_offset += kDoubleSize;
}
}
daddiu(sp, sp, stack_offset);
}
void MacroAssembler::FlushICache(Register address, unsigned instructions) {
RegList saved_regs = kJSCallerSaved | ra.bit();
MultiPush(saved_regs);
AllowExternalCallThatCantCauseGC scope(this);
// Save to a0 in case address == a4.
Move(a0, address);
PrepareCallCFunction(2, a4);
li(a1, instructions * kInstrSize);
CallCFunction(ExternalReference::flush_icache_function(isolate()), 2);
MultiPop(saved_regs);
}
void MacroAssembler::Ext(Register rt,
Register rs,
uint16_t pos,
uint16_t size) {
DCHECK(pos < 32);
DCHECK(pos + size < 33);
ext_(rt, rs, pos, size);
}
void MacroAssembler::Dext(Register rt, Register rs, uint16_t pos,
uint16_t size) {
DCHECK(pos < 32);
DCHECK(pos + size < 33);
dext_(rt, rs, pos, size);
}
void MacroAssembler::Ins(Register rt,
Register rs,
uint16_t pos,
uint16_t size) {
DCHECK(pos < 32);
DCHECK(pos + size <= 32);
DCHECK(size != 0);
ins_(rt, rs, pos, size);
}
void MacroAssembler::Cvt_d_uw(FPURegister fd,
FPURegister fs,
FPURegister scratch) {
// Move the data from fs to t8.
mfc1(t8, fs);
Cvt_d_uw(fd, t8, scratch);
}
void MacroAssembler::Cvt_d_uw(FPURegister fd,
Register rs,
FPURegister scratch) {
// Convert rs to a FP value in fd (and fd + 1).
// We do this by converting rs minus the MSB to avoid sign conversion,
// then adding 2^31 to the result (if needed).
DCHECK(!fd.is(scratch));
DCHECK(!rs.is(t9));
DCHECK(!rs.is(at));
// Save rs's MSB to t9.
Ext(t9, rs, 31, 1);
// Remove rs's MSB.
Ext(at, rs, 0, 31);
// Move the result to fd.
mtc1(at, fd);
mthc1(zero_reg, fd);
// Convert fd to a real FP value.
cvt_d_w(fd, fd);
Label conversion_done;
// If rs's MSB was 0, it's done.
// Otherwise we need to add that to the FP register.
Branch(&conversion_done, eq, t9, Operand(zero_reg));
// Load 2^31 into f20 as its float representation.
li(at, 0x41E00000);
mtc1(zero_reg, scratch);
mthc1(at, scratch);
// Add it to fd.
add_d(fd, fd, scratch);
bind(&conversion_done);
}
void MacroAssembler::Round_l_d(FPURegister fd, FPURegister fs) {
round_l_d(fd, fs);
}
void MacroAssembler::Floor_l_d(FPURegister fd, FPURegister fs) {
floor_l_d(fd, fs);
}
void MacroAssembler::Ceil_l_d(FPURegister fd, FPURegister fs) {
ceil_l_d(fd, fs);
}
void MacroAssembler::Trunc_l_d(FPURegister fd, FPURegister fs) {
trunc_l_d(fd, fs);
}
void MacroAssembler::Trunc_l_ud(FPURegister fd,
FPURegister fs,
FPURegister scratch) {
// Load to GPR.
dmfc1(t8, fs);
// Reset sign bit.
li(at, 0x7fffffffffffffff);
and_(t8, t8, at);
dmtc1(t8, fs);
trunc_l_d(fd, fs);
}
void MacroAssembler::Trunc_uw_d(FPURegister fd,
FPURegister fs,
FPURegister scratch) {
Trunc_uw_d(fs, t8, scratch);
mtc1(t8, fd);
}
void MacroAssembler::Trunc_w_d(FPURegister fd, FPURegister fs) {
trunc_w_d(fd, fs);
}
void MacroAssembler::Round_w_d(FPURegister fd, FPURegister fs) {
round_w_d(fd, fs);
}
void MacroAssembler::Floor_w_d(FPURegister fd, FPURegister fs) {
floor_w_d(fd, fs);
}
void MacroAssembler::Ceil_w_d(FPURegister fd, FPURegister fs) {
ceil_w_d(fd, fs);
}
void MacroAssembler::Trunc_uw_d(FPURegister fd,
Register rs,
FPURegister scratch) {
DCHECK(!fd.is(scratch));
DCHECK(!rs.is(at));
// Load 2^31 into scratch as its float representation.
li(at, 0x41E00000);
mtc1(zero_reg, scratch);
mthc1(at, scratch);
// Test if scratch > fd.
// If fd < 2^31 we can convert it normally.
Label simple_convert;
BranchF(&simple_convert, NULL, lt, fd, scratch);
// First we subtract 2^31 from fd, then trunc it to rs
// and add 2^31 to rs.
sub_d(scratch, fd, scratch);
trunc_w_d(scratch, scratch);
mfc1(rs, scratch);
Or(rs, rs, 1 << 31);
Label done;
Branch(&done);
// Simple conversion.
bind(&simple_convert);
trunc_w_d(scratch, fd);
mfc1(rs, scratch);
bind(&done);
}
void MacroAssembler::Madd_d(FPURegister fd, FPURegister fr, FPURegister fs,
FPURegister ft, FPURegister scratch) {
if (0) { // TODO(plind): find reasonable arch-variant symbol names.
madd_d(fd, fr, fs, ft);
} else {
// Can not change source regs's value.
DCHECK(!fr.is(scratch) && !fs.is(scratch) && !ft.is(scratch));
mul_d(scratch, fs, ft);
add_d(fd, fr, scratch);
}
}
void MacroAssembler::BranchFCommon(SecondaryField sizeField, Label* target,
Label* nan, Condition cond, FPURegister cmp1,
FPURegister cmp2, BranchDelaySlot bd) {
BlockTrampolinePoolScope block_trampoline_pool(this);
if (cond == al) {
Branch(bd, target);
return;
}
if (kArchVariant == kMips64r6) {
sizeField = sizeField == D ? L : W;
}
DCHECK(nan || target);
// Check for unordered (NaN) cases.
if (nan) {
bool long_branch = nan->is_bound() ? is_near(nan) : is_trampoline_emitted();
if (kArchVariant != kMips64r6) {
if (long_branch) {
Label skip;
c(UN, D, cmp1, cmp2);
bc1f(&skip);
nop();
Jr(nan, bd);
bind(&skip);
} else {
c(UN, D, cmp1, cmp2);
bc1t(nan);
if (bd == PROTECT) {
nop();
}
}
} else {
// Use kDoubleCompareReg for comparison result. It has to be unavailable
// to lithium
// register allocator.
DCHECK(!cmp1.is(kDoubleCompareReg) && !cmp2.is(kDoubleCompareReg));
if (long_branch) {
Label skip;
cmp(UN, L, kDoubleCompareReg, cmp1, cmp2);
bc1eqz(&skip, kDoubleCompareReg);
nop();
Jr(nan, bd);
bind(&skip);
} else {
cmp(UN, L, kDoubleCompareReg, cmp1, cmp2);
bc1nez(nan, kDoubleCompareReg);
if (bd == PROTECT) {
nop();
}
}
}
}
if (target) {
bool long_branch =
target->is_bound() ? is_near(target) : is_trampoline_emitted();
if (long_branch) {
Label skip;
Condition neg_cond = NegateFpuCondition(cond);
BranchShortF(sizeField, &skip, neg_cond, cmp1, cmp2, bd);
Jr(target, bd);
bind(&skip);
} else {
BranchShortF(sizeField, target, cond, cmp1, cmp2, bd);
}
}
}
void MacroAssembler::BranchShortF(SecondaryField sizeField, Label* target,
Condition cc, FPURegister cmp1,
FPURegister cmp2, BranchDelaySlot bd) {
if (kArchVariant != kMips64r6) {
BlockTrampolinePoolScope block_trampoline_pool(this);
if (target) {
// Here NaN cases were either handled by this function or are assumed to
// have been handled by the caller.
switch (cc) {
case lt:
c(OLT, sizeField, cmp1, cmp2);
bc1t(target);
break;
case ult:
c(ULT, sizeField, cmp1, cmp2);
bc1t(target);
break;
case gt:
c(ULE, sizeField, cmp1, cmp2);
bc1f(target);
break;
case ugt:
c(OLE, sizeField, cmp1, cmp2);
bc1f(target);
break;
case ge:
c(ULT, sizeField, cmp1, cmp2);
bc1f(target);
break;
case uge:
c(OLT, sizeField, cmp1, cmp2);
bc1f(target);
break;
case le:
c(OLE, sizeField, cmp1, cmp2);
bc1t(target);
break;
case ule:
c(ULE, sizeField, cmp1, cmp2);
bc1t(target);
break;
case eq:
c(EQ, sizeField, cmp1, cmp2);
bc1t(target);
break;
case ueq:
c(UEQ, sizeField, cmp1, cmp2);
bc1t(target);
break;
case ne: // Unordered or not equal.
c(EQ, sizeField, cmp1, cmp2);
bc1f(target);
break;
case ogl:
c(UEQ, sizeField, cmp1, cmp2);
bc1f(target);
break;
default:
CHECK(0);
}
}
} else {
BlockTrampolinePoolScope block_trampoline_pool(this);
if (target) {
// Here NaN cases were either handled by this function or are assumed to
// have been handled by the caller.
// Unsigned conditions are treated as their signed counterpart.
// Use kDoubleCompareReg for comparison result, it is valid in fp64 (FR =
// 1) mode.
DCHECK(!cmp1.is(kDoubleCompareReg) && !cmp2.is(kDoubleCompareReg));
switch (cc) {
case lt:
cmp(OLT, sizeField, kDoubleCompareReg, cmp1, cmp2);
bc1nez(target, kDoubleCompareReg);
break;
case ult:
cmp(ULT, sizeField, kDoubleCompareReg, cmp1, cmp2);
bc1nez(target, kDoubleCompareReg);
break;
case gt:
cmp(ULE, sizeField, kDoubleCompareReg, cmp1, cmp2);
bc1eqz(target, kDoubleCompareReg);
break;
case ugt:
cmp(OLE, sizeField, kDoubleCompareReg, cmp1, cmp2);
bc1eqz(target, kDoubleCompareReg);
break;
case ge:
cmp(ULT, sizeField, kDoubleCompareReg, cmp1, cmp2);
bc1eqz(target, kDoubleCompareReg);
break;
case uge:
cmp(OLT, sizeField, kDoubleCompareReg, cmp1, cmp2);
bc1eqz(target, kDoubleCompareReg);
break;
case le:
cmp(OLE, sizeField, kDoubleCompareReg, cmp1, cmp2);
bc1nez(target, kDoubleCompareReg);
break;
case ule:
cmp(ULE, sizeField, kDoubleCompareReg, cmp1, cmp2);
bc1nez(target, kDoubleCompareReg);
break;
case eq:
cmp(EQ, sizeField, kDoubleCompareReg, cmp1, cmp2);
bc1nez(target, kDoubleCompareReg);
break;
case ueq:
cmp(UEQ, sizeField, kDoubleCompareReg, cmp1, cmp2);
bc1nez(target, kDoubleCompareReg);
break;
case ne:
cmp(EQ, sizeField, kDoubleCompareReg, cmp1, cmp2);
bc1eqz(target, kDoubleCompareReg);
break;
case ogl:
cmp(UEQ, sizeField, kDoubleCompareReg, cmp1, cmp2);
bc1eqz(target, kDoubleCompareReg);
break;
default:
CHECK(0);
}
}
}
if (bd == PROTECT) {
nop();
}
}
void MacroAssembler::FmoveLow(FPURegister dst, Register src_low) {
DCHECK(!src_low.is(at));
mfhc1(at, dst);
mtc1(src_low, dst);
mthc1(at, dst);
}
void MacroAssembler::Move(FPURegister dst, float imm) {
li(at, Operand(bit_cast<int32_t>(imm)));
mtc1(at, dst);
}
void MacroAssembler::Move(FPURegister dst, double imm) {
static const DoubleRepresentation minus_zero(-0.0);
static const DoubleRepresentation zero(0.0);
DoubleRepresentation value_rep(imm);
// Handle special values first.
if (value_rep == zero && has_double_zero_reg_set_) {
mov_d(dst, kDoubleRegZero);
} else if (value_rep == minus_zero && has_double_zero_reg_set_) {
neg_d(dst, kDoubleRegZero);
} else {
uint32_t lo, hi;
DoubleAsTwoUInt32(imm, &lo, &hi);
// Move the low part of the double into the lower bits of the corresponding
// FPU register.
if (lo != 0) {
if (!(lo & kImm16Mask)) {
lui(at, (lo >> kLuiShift) & kImm16Mask);
mtc1(at, dst);
} else if (!(lo & kHiMask)) {
ori(at, zero_reg, lo & kImm16Mask);
mtc1(at, dst);
} else {
lui(at, (lo >> kLuiShift) & kImm16Mask);
ori(at, at, lo & kImm16Mask);
mtc1(at, dst);
}
} else {
mtc1(zero_reg, dst);
}
// Move the high part of the double into the high bits of the corresponding
// FPU register.
if (hi != 0) {
if (!(hi & kImm16Mask)) {
lui(at, (hi >> kLuiShift) & kImm16Mask);
mthc1(at, dst);
} else if (!(hi & kHiMask)) {
ori(at, zero_reg, hi & kImm16Mask);
mthc1(at, dst);
} else {
lui(at, (hi >> kLuiShift) & kImm16Mask);
ori(at, at, hi & kImm16Mask);
mthc1(at, dst);
}
} else {
mthc1(zero_reg, dst);
}
if (dst.is(kDoubleRegZero)) has_double_zero_reg_set_ = true;
}
}
void MacroAssembler::Movz(Register rd, Register rs, Register rt) {
if (kArchVariant == kMips64r6) {
Label done;
Branch(&done, ne, rt, Operand(zero_reg));
mov(rd, rs);
bind(&done);
} else {
movz(rd, rs, rt);
}
}
void MacroAssembler::Movn(Register rd, Register rs, Register rt) {
if (kArchVariant == kMips64r6) {
Label done;
Branch(&done, eq, rt, Operand(zero_reg));
mov(rd, rs);
bind(&done);
} else {
movn(rd, rs, rt);
}
}
void MacroAssembler::Movt(Register rd, Register rs, uint16_t cc) {
movt(rd, rs, cc);
}
void MacroAssembler::Movf(Register rd, Register rs, uint16_t cc) {
movf(rd, rs, cc);
}
void MacroAssembler::Clz(Register rd, Register rs) {
clz(rd, rs);
}
void MacroAssembler::EmitFPUTruncate(FPURoundingMode rounding_mode,
Register result,
DoubleRegister double_input,
Register scratch,
DoubleRegister double_scratch,
Register except_flag,
CheckForInexactConversion check_inexact) {
DCHECK(!result.is(scratch));
DCHECK(!double_input.is(double_scratch));
DCHECK(!except_flag.is(scratch));
Label done;
// Clear the except flag (0 = no exception)
mov(except_flag, zero_reg);
// Test for values that can be exactly represented as a signed 32-bit integer.
cvt_w_d(double_scratch, double_input);
mfc1(result, double_scratch);
cvt_d_w(double_scratch, double_scratch);
BranchF(&done, NULL, eq, double_input, double_scratch);
int32_t except_mask = kFCSRFlagMask; // Assume interested in all exceptions.
if (check_inexact == kDontCheckForInexactConversion) {
// Ignore inexact exceptions.
except_mask &= ~kFCSRInexactFlagMask;
}
// Save FCSR.
cfc1(scratch, FCSR);
// Disable FPU exceptions.
ctc1(zero_reg, FCSR);
// Do operation based on rounding mode.
switch (rounding_mode) {
case kRoundToNearest:
Round_w_d(double_scratch, double_input);
break;
case kRoundToZero:
Trunc_w_d(double_scratch, double_input);
break;
case kRoundToPlusInf:
Ceil_w_d(double_scratch, double_input);
break;
case kRoundToMinusInf:
Floor_w_d(double_scratch, double_input);
break;
} // End of switch-statement.
// Retrieve FCSR.
cfc1(except_flag, FCSR);
// Restore FCSR.
ctc1(scratch, FCSR);
// Move the converted value into the result register.
mfc1(result, double_scratch);
// Check for fpu exceptions.
And(except_flag, except_flag, Operand(except_mask));
bind(&done);
}
void MacroAssembler::TryInlineTruncateDoubleToI(Register result,
DoubleRegister double_input,
Label* done) {
DoubleRegister single_scratch = kLithiumScratchDouble.low();
Register scratch = at;
Register scratch2 = t9;
// Clear cumulative exception flags and save the FCSR.
cfc1(scratch2, FCSR);
ctc1(zero_reg, FCSR);
// Try a conversion to a signed integer.
trunc_w_d(single_scratch, double_input);
mfc1(result, single_scratch);
// Retrieve and restore the FCSR.
cfc1(scratch, FCSR);
ctc1(scratch2, FCSR);
// Check for overflow and NaNs.
And(scratch,
scratch,
kFCSROverflowFlagMask | kFCSRUnderflowFlagMask | kFCSRInvalidOpFlagMask);
// If we had no exceptions we are done.
Branch(done, eq, scratch, Operand(zero_reg));
}
void MacroAssembler::TruncateDoubleToI(Register result,
DoubleRegister double_input) {
Label done;
TryInlineTruncateDoubleToI(result, double_input, &done);
// If we fell through then inline version didn't succeed - call stub instead.
push(ra);
Dsubu(sp, sp, Operand(kDoubleSize)); // Put input on stack.
sdc1(double_input, MemOperand(sp, 0));
DoubleToIStub stub(isolate(), sp, result, 0, true, true);
CallStub(&stub);
Daddu(sp, sp, Operand(kDoubleSize));
pop(ra);
bind(&done);
}
void MacroAssembler::TruncateHeapNumberToI(Register result, Register object) {
Label done;
DoubleRegister double_scratch = f12;
DCHECK(!result.is(object));
ldc1(double_scratch,
MemOperand(object, HeapNumber::kValueOffset - kHeapObjectTag));
TryInlineTruncateDoubleToI(result, double_scratch, &done);
// If we fell through then inline version didn't succeed - call stub instead.
push(ra);
DoubleToIStub stub(isolate(),
object,
result,
HeapNumber::kValueOffset - kHeapObjectTag,
true,
true);
CallStub(&stub);
pop(ra);
bind(&done);
}
void MacroAssembler::TruncateNumberToI(Register object,
Register result,
Register heap_number_map,
Register scratch,
Label* not_number) {
Label done;
DCHECK(!result.is(object));
UntagAndJumpIfSmi(result, object, &done);
JumpIfNotHeapNumber(object, heap_number_map, scratch, not_number);
TruncateHeapNumberToI(result, object);
bind(&done);
}
void MacroAssembler::GetLeastBitsFromSmi(Register dst,
Register src,
int num_least_bits) {
// Ext(dst, src, kSmiTagSize, num_least_bits);
SmiUntag(dst, src);
And(dst, dst, Operand((1 << num_least_bits) - 1));
}
void MacroAssembler::GetLeastBitsFromInt32(Register dst,
Register src,
int num_least_bits) {
DCHECK(!src.is(dst));
And(dst, src, Operand((1 << num_least_bits) - 1));
}
// Emulated condtional branches do not emit a nop in the branch delay slot.
//
// BRANCH_ARGS_CHECK checks that conditional jump arguments are correct.
#define BRANCH_ARGS_CHECK(cond, rs, rt) DCHECK( \
(cond == cc_always && rs.is(zero_reg) && rt.rm().is(zero_reg)) || \
(cond != cc_always && (!rs.is(zero_reg) || !rt.rm().is(zero_reg))))
void MacroAssembler::Branch(int16_t offset, BranchDelaySlot bdslot) {
BranchShort(offset, bdslot);
}
void MacroAssembler::Branch(int16_t offset, Condition cond, Register rs,
const Operand& rt,
BranchDelaySlot bdslot) {
BranchShort(offset, cond, rs, rt, bdslot);
}
void MacroAssembler::Branch(Label* L, BranchDelaySlot bdslot) {
if (L->is_bound()) {
if (is_near(L)) {
BranchShort(L, bdslot);
} else {
Jr(L, bdslot);
}
} else {
if (is_trampoline_emitted()) {
Jr(L, bdslot);
} else {
BranchShort(L, bdslot);
}
}
}
void MacroAssembler::Branch(Label* L, Condition cond, Register rs,
const Operand& rt,
BranchDelaySlot bdslot) {
if (L->is_bound()) {
if (is_near(L)) {
BranchShort(L, cond, rs, rt, bdslot);
} else {
if (cond != cc_always) {
Label skip;
Condition neg_cond = NegateCondition(cond);
BranchShort(&skip, neg_cond, rs, rt);
Jr(L, bdslot);
bind(&skip);
} else {
Jr(L, bdslot);
}
}
} else {
if (is_trampoline_emitted()) {
if (cond != cc_always) {
Label skip;
Condition neg_cond = NegateCondition(cond);
BranchShort(&skip, neg_cond, rs, rt);
Jr(L, bdslot);
bind(&skip);
} else {
Jr(L, bdslot);
}
} else {
BranchShort(L, cond, rs, rt, bdslot);
}
}
}
void MacroAssembler::Branch(Label* L,
Condition cond,
Register rs,
Heap::RootListIndex index,
BranchDelaySlot bdslot) {
LoadRoot(at, index);
Branch(L, cond, rs, Operand(at), bdslot);
}
void MacroAssembler::BranchShort(int16_t offset, BranchDelaySlot bdslot) {
b(offset);
// Emit a nop in the branch delay slot if required.
if (bdslot == PROTECT)
nop();
}
void MacroAssembler::BranchShort(int16_t offset, Condition cond, Register rs,
const Operand& rt,
BranchDelaySlot bdslot) {
BRANCH_ARGS_CHECK(cond, rs, rt);
DCHECK(!rs.is(zero_reg));
Register r2 = no_reg;
Register scratch = at;
if (rt.is_reg()) {
// NOTE: 'at' can be clobbered by Branch but it is legal to use it as rs or
// rt.
BlockTrampolinePoolScope block_trampoline_pool(this);
r2 = rt.rm_;
switch (cond) {
case cc_always:
b(offset);
break;
case eq:
beq(rs, r2, offset);
break;
case ne:
bne(rs, r2, offset);
break;
// Signed comparison.
case greater:
if (r2.is(zero_reg)) {
bgtz(rs, offset);
} else {
slt(scratch, r2, rs);
bne(scratch, zero_reg, offset);
}
break;
case greater_equal:
if (r2.is(zero_reg)) {
bgez(rs, offset);
} else {
slt(scratch, rs, r2);
beq(scratch, zero_reg, offset);
}
break;
case less:
if (r2.is(zero_reg)) {
bltz(rs, offset);
} else {
slt(scratch, rs, r2);
bne(scratch, zero_reg, offset);
}
break;
case less_equal:
if (r2.is(zero_reg)) {
blez(rs, offset);
} else {
slt(scratch, r2, rs);
beq(scratch, zero_reg, offset);
}
break;
// Unsigned comparison.
case Ugreater:
if (r2.is(zero_reg)) {
bne(rs, zero_reg, offset);
} else {
sltu(scratch, r2, rs);
bne(scratch, zero_reg, offset);
}
break;
case Ugreater_equal:
if (r2.is(zero_reg)) {
b(offset);
} else {
sltu(scratch, rs, r2);
beq(scratch, zero_reg, offset);
}
break;
case Uless:
if (r2.is(zero_reg)) {
// No code needs to be emitted.
return;
} else {
sltu(scratch, rs, r2);
bne(scratch, zero_reg, offset);
}
break;
case Uless_equal:
if (r2.is(zero_reg)) {
beq(rs, zero_reg, offset);
} else {
sltu(scratch, r2, rs);
beq(scratch, zero_reg, offset);
}
break;
default:
UNREACHABLE();
}
} else {
// Be careful to always use shifted_branch_offset only just before the
// branch instruction, as the location will be remember for patching the
// target.
BlockTrampolinePoolScope block_trampoline_pool(this);
switch (cond) {
case cc_always:
b(offset);
break;
case eq:
if (rt.imm64_ == 0) {
beq(rs, zero_reg, offset);
} else {
// We don't want any other register but scratch clobbered.
DCHECK(!scratch.is(rs));
r2 = scratch;
li(r2, rt);
beq(rs, r2, offset);
}
break;
case ne:
if (rt.imm64_ == 0) {
bne(rs, zero_reg, offset);
} else {
// We don't want any other register but scratch clobbered.
DCHECK(!scratch.is(rs));
r2 = scratch;
li(r2, rt);
bne(rs, r2, offset);
}
break;
// Signed comparison.
case greater:
if (rt.imm64_ == 0) {
bgtz(rs, offset);
} else {
r2 = scratch;
li(r2, rt);
slt(scratch, r2, rs);
bne(scratch, zero_reg, offset);
}
break;
case greater_equal:
if (rt.imm64_ == 0) {
bgez(rs, offset);
} else if (is_int16(rt.imm64_)) {
slti(scratch, rs, rt.imm64_);
beq(scratch, zero_reg, offset);
} else {
r2 = scratch;
li(r2, rt);
slt(scratch, rs, r2);
beq(scratch, zero_reg, offset);
}
break;
case less:
if (rt.imm64_ == 0) {
bltz(rs, offset);
} else if (is_int16(rt.imm64_)) {
slti(scratch, rs, rt.imm64_);
bne(scratch, zero_reg, offset);
} else {
r2 = scratch;
li(r2, rt);
slt(scratch, rs, r2);
bne(scratch, zero_reg, offset);
}
break;
case less_equal:
if (rt.imm64_ == 0) {
blez(rs, offset);
} else {
r2 = scratch;
li(r2, rt);
slt(scratch, r2, rs);
beq(scratch, zero_reg, offset);
}
break;
// Unsigned comparison.
case Ugreater:
if (rt.imm64_ == 0) {
bne(rs, zero_reg, offset);
} else {
r2 = scratch;
li(r2, rt);
sltu(scratch, r2, rs);
bne(scratch, zero_reg, offset);
}
break;
case Ugreater_equal:
if (rt.imm64_ == 0) {
b(offset);
} else if (is_int16(rt.imm64_)) {
sltiu(scratch, rs, rt.imm64_);
beq(scratch, zero_reg, offset);
} else {
r2 = scratch;
li(r2, rt);
sltu(scratch, rs, r2);
beq(scratch, zero_reg, offset);
}
break;
case Uless:
if (rt.imm64_ == 0) {
// No code needs to be emitted.
return;
} else if (is_int16(rt.imm64_)) {
sltiu(scratch, rs, rt.imm64_);
bne(scratch, zero_reg, offset);
} else {
r2 = scratch;
li(r2, rt);
sltu(scratch, rs, r2);
bne(scratch, zero_reg, offset);
}
break;
case Uless_equal:
if (rt.imm64_ == 0) {
beq(rs, zero_reg, offset);
} else {
r2 = scratch;
li(r2, rt);
sltu(scratch, r2, rs);
beq(scratch, zero_reg, offset);
}
break;
default:
UNREACHABLE();
}
}
// Emit a nop in the branch delay slot if required.
if (bdslot == PROTECT)
nop();
}
void MacroAssembler::BranchShort(Label* L, BranchDelaySlot bdslot) {
// We use branch_offset as an argument for the branch instructions to be sure
// it is called just before generating the branch instruction, as needed.
b(shifted_branch_offset(L, false));
// Emit a nop in the branch delay slot if required.
if (bdslot == PROTECT)
nop();
}
void MacroAssembler::BranchShort(Label* L, Condition cond, Register rs,
const Operand& rt,
BranchDelaySlot bdslot) {
BRANCH_ARGS_CHECK(cond, rs, rt);
int32_t offset = 0;
Register r2 = no_reg;
Register scratch = at;
if (rt.is_reg()) {
BlockTrampolinePoolScope block_trampoline_pool(this);
r2 = rt.rm_;
// Be careful to always use shifted_branch_offset only just before the
// branch instruction, as the location will be remember for patching the
// target.
switch (cond) {
case cc_always:
offset = shifted_branch_offset(L, false);
b(offset);
break;
case eq:
offset = shifted_branch_offset(L, false);
beq(rs, r2, offset);
break;
case ne:
offset = shifted_branch_offset(L, false);
bne(rs, r2, offset);
break;
// Signed comparison.
case greater:
if (r2.is(zero_reg)) {
offset = shifted_branch_offset(L, false);
bgtz(rs, offset);
} else {
slt(scratch, r2, rs);
offset = shifted_branch_offset(L, false);
bne(scratch, zero_reg, offset);
}
break;
case greater_equal:
if (r2.is(zero_reg)) {
offset = shifted_branch_offset(L, false);
bgez(rs, offset);
} else {
slt(scratch, rs, r2);
offset = shifted_branch_offset(L, false);
beq(scratch, zero_reg, offset);
}
break;
case less:
if (r2.is(zero_reg)) {
offset = shifted_branch_offset(L, false);
bltz(rs, offset);
} else {
slt(scratch, rs, r2);
offset = shifted_branch_offset(L, false);
bne(scratch, zero_reg, offset);
}
break;
case less_equal:
if (r2.is(zero_reg)) {
offset = shifted_branch_offset(L, false);
blez(rs, offset);
} else {
slt(scratch, r2, rs);
offset = shifted_branch_offset(L, false);
beq(scratch, zero_reg, offset);
}
break;
// Unsigned comparison.
case Ugreater:
if (r2.is(zero_reg)) {
offset = shifted_branch_offset(L, false);
bne(rs, zero_reg, offset);
} else {
sltu(scratch, r2, rs);
offset = shifted_branch_offset(L, false);
bne(scratch, zero_reg, offset);
}
break;
case Ugreater_equal:
if (r2.is(zero_reg)) {
offset = shifted_branch_offset(L, false);
b(offset);
} else {
sltu(scratch, rs, r2);
offset = shifted_branch_offset(L, false);
beq(scratch, zero_reg, offset);
}
break;
case Uless:
if (r2.is(zero_reg)) {
// No code needs to be emitted.
return;
} else {
sltu(scratch, rs, r2);
offset = shifted_branch_offset(L, false);
bne(scratch, zero_reg, offset);
}
break;
case Uless_equal:
if (r2.is(zero_reg)) {
offset = shifted_branch_offset(L, false);
beq(rs, zero_reg, offset);
} else {
sltu(scratch, r2, rs);
offset = shifted_branch_offset(L, false);
beq(scratch, zero_reg, offset);
}
break;
default:
UNREACHABLE();
}
} else {
// Be careful to always use shifted_branch_offset only just before the
// branch instruction, as the location will be remember for patching the
// target.
BlockTrampolinePoolScope block_trampoline_pool(this);
switch (cond) {
case cc_always:
offset = shifted_branch_offset(L, false);
b(offset);
break;
case eq:
if (rt.imm64_ == 0) {
offset = shifted_branch_offset(L, false);
beq(rs, zero_reg, offset);
} else {
DCHECK(!scratch.is(rs));
r2 = scratch;
li(r2, rt);
offset = shifted_branch_offset(L, false);
beq(rs, r2, offset);
}
break;
case ne:
if (rt.imm64_ == 0) {
offset = shifted_branch_offset(L, false);
bne(rs, zero_reg, offset);
} else {
DCHECK(!scratch.is(rs));
r2 = scratch;
li(r2, rt);
offset = shifted_branch_offset(L, false);
bne(rs, r2, offset);
}
break;
// Signed comparison.
case greater:
if (rt.imm64_ == 0) {
offset = shifted_branch_offset(L, false);
bgtz(rs, offset);
} else {
DCHECK(!scratch.is(rs));
r2 = scratch;
li(r2, rt);
slt(scratch, r2, rs);
offset = shifted_branch_offset(L, false);
bne(scratch, zero_reg, offset);
}
break;
case greater_equal:
if (rt.imm64_ == 0) {
offset = shifted_branch_offset(L, false);
bgez(rs, offset);
} else if (is_int16(rt.imm64_)) {
slti(scratch, rs, rt.imm64_);
offset = shifted_branch_offset(L, false);
beq(scratch, zero_reg, offset);
} else {
DCHECK(!scratch.is(rs));
r2 = scratch;
li(r2, rt);
slt(scratch, rs, r2);
offset = shifted_branch_offset(L, false);
beq(scratch, zero_reg, offset);
}
break;
case less:
if (rt.imm64_ == 0) {
offset = shifted_branch_offset(L, false);
bltz(rs, offset);
} else if (is_int16(rt.imm64_)) {
slti(scratch, rs, rt.imm64_);
offset = shifted_branch_offset(L, false);
bne(scratch, zero_reg, offset);
} else {
DCHECK(!scratch.is(rs));
r2 = scratch;
li(r2, rt);
slt(scratch, rs, r2);
offset = shifted_branch_offset(L, false);
bne(scratch, zero_reg, offset);
}
break;
case less_equal:
if (rt.imm64_ == 0) {
offset = shifted_branch_offset(L, false);
blez(rs, offset);
} else {
DCHECK(!scratch.is(rs));
r2 = scratch;
li(r2, rt);
slt(scratch, r2, rs);
offset = shifted_branch_offset(L, false);
beq(scratch, zero_reg, offset);
}
break;
// Unsigned comparison.
case Ugreater:
if (rt.imm64_ == 0) {
offset = shifted_branch_offset(L, false);
bne(rs, zero_reg, offset);
} else {
DCHECK(!scratch.is(rs));
r2 = scratch;
li(r2, rt);
sltu(scratch, r2, rs);
offset = shifted_branch_offset(L, false);
bne(scratch, zero_reg, offset);
}
break;
case Ugreater_equal:
if (rt.imm64_ == 0) {
offset = shifted_branch_offset(L, false);
b(offset);
} else if (is_int16(rt.imm64_)) {
sltiu(scratch, rs, rt.imm64_);
offset = shifted_branch_offset(L, false);
beq(scratch, zero_reg, offset);
} else {
DCHECK(!scratch.is(rs));
r2 = scratch;
li(r2, rt);
sltu(scratch, rs, r2);
offset = shifted_branch_offset(L, false);
beq(scratch, zero_reg, offset);
}
break;
case Uless:
if (rt.imm64_ == 0) {
// No code needs to be emitted.
return;
} else if (is_int16(rt.imm64_)) {
sltiu(scratch, rs, rt.imm64_);
offset = shifted_branch_offset(L, false);
bne(scratch, zero_reg, offset);
} else {
DCHECK(!scratch.is(rs));
r2 = scratch;
li(r2, rt);
sltu(scratch, rs, r2);
offset = shifted_branch_offset(L, false);
bne(scratch, zero_reg, offset);
}
break;
case Uless_equal:
if (rt.imm64_ == 0) {
offset = shifted_branch_offset(L, false);
beq(rs, zero_reg, offset);
} else {
DCHECK(!scratch.is(rs));
r2 = scratch;
li(r2, rt);
sltu(scratch, r2, rs);
offset = shifted_branch_offset(L, false);
beq(scratch, zero_reg, offset);
}
break;
default:
UNREACHABLE();
}
}
// Check that offset could actually hold on an int16_t.
DCHECK(is_int16(offset));
// Emit a nop in the branch delay slot if required.
if (bdslot == PROTECT)
nop();
}
void MacroAssembler::BranchAndLink(int16_t offset, BranchDelaySlot bdslot) {
BranchAndLinkShort(offset, bdslot);
}
void MacroAssembler::BranchAndLink(int16_t offset, Condition cond, Register rs,
const Operand& rt,
BranchDelaySlot bdslot) {
BranchAndLinkShort(offset, cond, rs, rt, bdslot);
}
void MacroAssembler::BranchAndLink(Label* L, BranchDelaySlot bdslot) {
if (L->is_bound()) {
if (is_near(L)) {
BranchAndLinkShort(L, bdslot);
} else {
Jalr(L, bdslot);
}
} else {
if (is_trampoline_emitted()) {
Jalr(L, bdslot);
} else {
BranchAndLinkShort(L, bdslot);
}
}
}
void MacroAssembler::BranchAndLink(Label* L, Condition cond, Register rs,
const Operand& rt,
BranchDelaySlot bdslot) {
if (L->is_bound()) {
if (is_near(L)) {
BranchAndLinkShort(L, cond, rs, rt, bdslot);
} else {
Label skip;
Condition neg_cond = NegateCondition(cond);
BranchShort(&skip, neg_cond, rs, rt);
Jalr(L, bdslot);
bind(&skip);
}
} else {
if (is_trampoline_emitted()) {
Label skip;
Condition neg_cond = NegateCondition(cond);
BranchShort(&skip, neg_cond, rs, rt);
Jalr(L, bdslot);
bind(&skip);
} else {
BranchAndLinkShort(L, cond, rs, rt, bdslot);
}
}
}
// We need to use a bgezal or bltzal, but they can't be used directly with the
// slt instructions. We could use sub or add instead but we would miss overflow
// cases, so we keep slt and add an intermediate third instruction.
void MacroAssembler::BranchAndLinkShort(int16_t offset,
BranchDelaySlot bdslot) {
bal(offset);
// Emit a nop in the branch delay slot if required.
if (bdslot == PROTECT)
nop();
}
void MacroAssembler::BranchAndLinkShort(int16_t offset, Condition cond,
Register rs, const Operand& rt,
BranchDelaySlot bdslot) {
BRANCH_ARGS_CHECK(cond, rs, rt);
Register r2 = no_reg;
Register scratch = at;
if (rt.is_reg()) {
r2 = rt.rm_;
} else if (cond != cc_always) {
r2 = scratch;
li(r2, rt);
}
{
BlockTrampolinePoolScope block_trampoline_pool(this);
switch (cond) {
case cc_always:
bal(offset);
break;
case eq:
bne(rs, r2, 2);
nop();
bal(offset);
break;
case ne:
beq(rs, r2, 2);
nop();
bal(offset);
break;
// Signed comparison.
case greater:
// rs > rt
slt(scratch, r2, rs);
beq(scratch, zero_reg, 2);
nop();
bal(offset);
break;
case greater_equal:
// rs >= rt
slt(scratch, rs, r2);
bne(scratch, zero_reg, 2);
nop();
bal(offset);
break;
case less:
// rs < r2
slt(scratch, rs, r2);
bne(scratch, zero_reg, 2);
nop();
bal(offset);
break;
case less_equal:
// rs <= r2
slt(scratch, r2, rs);
bne(scratch, zero_reg, 2);
nop();
bal(offset);
break;
// Unsigned comparison.
case Ugreater:
// rs > rt
sltu(scratch, r2, rs);
beq(scratch, zero_reg, 2);
nop();
bal(offset);
break;
case Ugreater_equal:
// rs >= rt
sltu(scratch, rs, r2);
bne(scratch, zero_reg, 2);
nop();
bal(offset);
break;
case Uless:
// rs < r2
sltu(scratch, rs, r2);
bne(scratch, zero_reg, 2);
nop();
bal(offset);
break;
case Uless_equal:
// rs <= r2
sltu(scratch, r2, rs);
bne(scratch, zero_reg, 2);
nop();
bal(offset);
break;
default:
UNREACHABLE();
}
}
// Emit a nop in the branch delay slot if required.
if (bdslot == PROTECT)
nop();
}
void MacroAssembler::BranchAndLinkShort(Label* L, BranchDelaySlot bdslot) {
bal(shifted_branch_offset(L, false));
// Emit a nop in the branch delay slot if required.
if (bdslot == PROTECT)
nop();
}
void MacroAssembler::BranchAndLinkShort(Label* L, Condition cond, Register rs,
const Operand& rt,
BranchDelaySlot bdslot) {
BRANCH_ARGS_CHECK(cond, rs, rt);
int32_t offset = 0;
Register r2 = no_reg;
Register scratch = at;
if (rt.is_reg()) {
r2 = rt.rm_;
} else if (cond != cc_always) {
r2 = scratch;
li(r2, rt);
}
{
BlockTrampolinePoolScope block_trampoline_pool(this);
switch (cond) {
case cc_always:
offset = shifted_branch_offset(L, false);
bal(offset);
break;
case eq:
bne(rs, r2, 2);
nop();
offset = shifted_branch_offset(L, false);
bal(offset);
break;
case ne:
beq(rs, r2, 2);
nop();
offset = shifted_branch_offset(L, false);
bal(offset);
break;
// Signed comparison.
case greater:
// rs > rt
slt(scratch, r2, rs);
beq(scratch, zero_reg, 2);
nop();
offset = shifted_branch_offset(L, false);
bal(offset);
break;
case greater_equal:
// rs >= rt
slt(scratch, rs, r2);
bne(scratch, zero_reg, 2);
nop();
offset = shifted_branch_offset(L, false);
bal(offset);
break;
case less:
// rs < r2
slt(scratch, rs, r2);
bne(scratch, zero_reg, 2);
nop();
offset = shifted_branch_offset(L, false);
bal(offset);
break;
case less_equal:
// rs <= r2
slt(scratch, r2, rs);
bne(scratch, zero_reg, 2);
nop();
offset = shifted_branch_offset(L, false);
bal(offset);
break;
// Unsigned comparison.
case Ugreater:
// rs > rt
sltu(scratch, r2, rs);
beq(scratch, zero_reg, 2);
nop();
offset = shifted_branch_offset(L, false);
bal(offset);
break;
case Ugreater_equal:
// rs >= rt
sltu(scratch, rs, r2);
bne(scratch, zero_reg, 2);
nop();
offset = shifted_branch_offset(L, false);
bal(offset);
break;
case Uless:
// rs < r2
sltu(scratch, rs, r2);
bne(scratch, zero_reg, 2);
nop();
offset = shifted_branch_offset(L, false);
bal(offset);
break;
case Uless_equal:
// rs <= r2
sltu(scratch, r2, rs);
bne(scratch, zero_reg, 2);
nop();
offset = shifted_branch_offset(L, false);
bal(offset);
break;
default:
UNREACHABLE();
}
}
// Check that offset could actually hold on an int16_t.
DCHECK(is_int16(offset));
// Emit a nop in the branch delay slot if required.
if (bdslot == PROTECT)
nop();
}
void MacroAssembler::Jump(Register target,
Condition cond,
Register rs,
const Operand& rt,
BranchDelaySlot bd) {
BlockTrampolinePoolScope block_trampoline_pool(this);
if (cond == cc_always) {
jr(target);
} else {
BRANCH_ARGS_CHECK(cond, rs, rt);
Branch(2, NegateCondition(cond), rs, rt);
jr(target);
}
// Emit a nop in the branch delay slot if required.
if (bd == PROTECT)
nop();
}
void MacroAssembler::Jump(intptr_t target,
RelocInfo::Mode rmode,
Condition cond,
Register rs,
const Operand& rt,
BranchDelaySlot bd) {
Label skip;
if (cond != cc_always) {
Branch(USE_DELAY_SLOT, &skip, NegateCondition(cond), rs, rt);
}
// The first instruction of 'li' may be placed in the delay slot.
// This is not an issue, t9 is expected to be clobbered anyway.
li(t9, Operand(target, rmode));
Jump(t9, al, zero_reg, Operand(zero_reg), bd);
bind(&skip);
}
void MacroAssembler::Jump(Address target,
RelocInfo::Mode rmode,
Condition cond,
Register rs,
const Operand& rt,
BranchDelaySlot bd) {
DCHECK(!RelocInfo::IsCodeTarget(rmode));
Jump(reinterpret_cast<intptr_t>(target), rmode, cond, rs, rt, bd);
}
void MacroAssembler::Jump(Handle<Code> code,
RelocInfo::Mode rmode,
Condition cond,
Register rs,
const Operand& rt,
BranchDelaySlot bd) {
DCHECK(RelocInfo::IsCodeTarget(rmode));
AllowDeferredHandleDereference embedding_raw_address;
Jump(reinterpret_cast<intptr_t>(code.location()), rmode, cond, rs, rt, bd);
}
int MacroAssembler::CallSize(Register target,
Condition cond,
Register rs,
const Operand& rt,
BranchDelaySlot bd) {
int size = 0;
if (cond == cc_always) {
size += 1;
} else {
size += 3;
}
if (bd == PROTECT)
size += 1;
return size * kInstrSize;
}
// Note: To call gcc-compiled C code on mips, you must call thru t9.
void MacroAssembler::Call(Register target,
Condition cond,
Register rs,
const Operand& rt,
BranchDelaySlot bd) {
BlockTrampolinePoolScope block_trampoline_pool(this);
Label start;
bind(&start);
if (cond == cc_always) {
jalr(target);
} else {
BRANCH_ARGS_CHECK(cond, rs, rt);
Branch(2, NegateCondition(cond), rs, rt);
jalr(target);
}
// Emit a nop in the branch delay slot if required.
if (bd == PROTECT)
nop();
DCHECK_EQ(CallSize(target, cond, rs, rt, bd),
SizeOfCodeGeneratedSince(&start));
}
int MacroAssembler::CallSize(Address target,
RelocInfo::Mode rmode,
Condition cond,
Register rs,
const Operand& rt,
BranchDelaySlot bd) {
int size = CallSize(t9, cond, rs, rt, bd);
return size + 4 * kInstrSize;
}
void MacroAssembler::Call(Address target,
RelocInfo::Mode rmode,
Condition cond,
Register rs,
const Operand& rt,
BranchDelaySlot bd) {
BlockTrampolinePoolScope block_trampoline_pool(this);
Label start;
bind(&start);
int64_t target_int = reinterpret_cast<int64_t>(target);
// Must record previous source positions before the
// li() generates a new code target.
positions_recorder()->WriteRecordedPositions();
li(t9, Operand(target_int, rmode), ADDRESS_LOAD);
Call(t9, cond, rs, rt, bd);
DCHECK_EQ(CallSize(target, rmode, cond, rs, rt, bd),
SizeOfCodeGeneratedSince(&start));
}
int MacroAssembler::CallSize(Handle<Code> code,
RelocInfo::Mode rmode,
TypeFeedbackId ast_id,
Condition cond,
Register rs,
const Operand& rt,
BranchDelaySlot bd) {
AllowDeferredHandleDereference using_raw_address;
return CallSize(reinterpret_cast<Address>(code.location()),
rmode, cond, rs, rt, bd);
}
void MacroAssembler::Call(Handle<Code> code,
RelocInfo::Mode rmode,
TypeFeedbackId ast_id,
Condition cond,
Register rs,
const Operand& rt,
BranchDelaySlot bd) {
BlockTrampolinePoolScope block_trampoline_pool(this);
Label start;
bind(&start);
DCHECK(RelocInfo::IsCodeTarget(rmode));
if (rmode == RelocInfo::CODE_TARGET && !ast_id.IsNone()) {
SetRecordedAstId(ast_id);
rmode = RelocInfo::CODE_TARGET_WITH_ID;
}
AllowDeferredHandleDereference embedding_raw_address;
Call(reinterpret_cast<Address>(code.location()), rmode, cond, rs, rt, bd);
DCHECK_EQ(CallSize(code, rmode, ast_id, cond, rs, rt, bd),
SizeOfCodeGeneratedSince(&start));
}
void MacroAssembler::Ret(Condition cond,
Register rs,
const Operand& rt,
BranchDelaySlot bd) {
Jump(ra, cond, rs, rt, bd);
}
void MacroAssembler::Jr(Label* L, BranchDelaySlot bdslot) {
BlockTrampolinePoolScope block_trampoline_pool(this);
uint64_t imm64;
imm64 = jump_address(L);
{ BlockGrowBufferScope block_buf_growth(this);
// Buffer growth (and relocation) must be blocked for internal references
// until associated instructions are emitted and available to be patched.
RecordRelocInfo(RelocInfo::INTERNAL_REFERENCE_ENCODED);
li(at, Operand(imm64), ADDRESS_LOAD);
}
jr(at);
// Emit a nop in the branch delay slot if required.
if (bdslot == PROTECT)
nop();
}
void MacroAssembler::Jalr(Label* L, BranchDelaySlot bdslot) {
BlockTrampolinePoolScope block_trampoline_pool(this);
uint64_t imm64;
imm64 = jump_address(L);
{ BlockGrowBufferScope block_buf_growth(this);
// Buffer growth (and relocation) must be blocked for internal references
// until associated instructions are emitted and available to be patched.
RecordRelocInfo(RelocInfo::INTERNAL_REFERENCE_ENCODED);
li(at, Operand(imm64), ADDRESS_LOAD);
}
jalr(at);
// Emit a nop in the branch delay slot if required.
if (bdslot == PROTECT)
nop();
}
void MacroAssembler::DropAndRet(int drop) {
DCHECK(is_int16(drop * kPointerSize));
Ret(USE_DELAY_SLOT);
daddiu(sp, sp, drop * kPointerSize);
}
void MacroAssembler::DropAndRet(int drop,
Condition cond,
Register r1,
const Operand& r2) {
// Both Drop and Ret need to be conditional.
Label skip;
if (cond != cc_always) {
Branch(&skip, NegateCondition(cond), r1, r2);
}
Drop(drop);
Ret();
if (cond != cc_always) {
bind(&skip);
}
}
void MacroAssembler::Drop(int count,
Condition cond,
Register reg,
const Operand& op) {
if (count <= 0) {
return;
}
Label skip;
if (cond != al) {
Branch(&skip, NegateCondition(cond), reg, op);
}
Daddu(sp, sp, Operand(count * kPointerSize));
if (cond != al) {
bind(&skip);
}
}
void MacroAssembler::Swap(Register reg1,
Register reg2,
Register scratch) {
if (scratch.is(no_reg)) {
Xor(reg1, reg1, Operand(reg2));
Xor(reg2, reg2, Operand(reg1));
Xor(reg1, reg1, Operand(reg2));
} else {
mov(scratch, reg1);
mov(reg1, reg2);
mov(reg2, scratch);
}
}
void MacroAssembler::Call(Label* target) {
BranchAndLink(target);
}
void MacroAssembler::Push(Handle<Object> handle) {
li(at, Operand(handle));
push(at);
}
void MacroAssembler::PushRegisterAsTwoSmis(Register src, Register scratch) {
DCHECK(!src.is(scratch));
mov(scratch, src);
dsrl32(src, src, 0);
dsll32(src, src, 0);
push(src);
dsll32(scratch, scratch, 0);
push(scratch);
}
void MacroAssembler::PopRegisterAsTwoSmis(Register dst, Register scratch) {
DCHECK(!dst.is(scratch));
pop(scratch);
dsrl32(scratch, scratch, 0);
pop(dst);
dsrl32(dst, dst, 0);
dsll32(dst, dst, 0);
or_(dst, dst, scratch);
}
void MacroAssembler::DebugBreak() {
PrepareCEntryArgs(0);
PrepareCEntryFunction(ExternalReference(Runtime::kDebugBreak, isolate()));
CEntryStub ces(isolate(), 1);
DCHECK(AllowThisStubCall(&ces));
Call(ces.GetCode(), RelocInfo::DEBUG_BREAK);
}
// ---------------------------------------------------------------------------
// Exception handling.
void MacroAssembler::PushStackHandler() {
// Adjust this code if not the case.
STATIC_ASSERT(StackHandlerConstants::kSize == 1 * kPointerSize);
STATIC_ASSERT(StackHandlerConstants::kNextOffset == 0 * kPointerSize);
// Link the current handler as the next handler.
li(a6, Operand(ExternalReference(Isolate::kHandlerAddress, isolate())));
ld(a5, MemOperand(a6));
push(a5);
// Set this new handler as the current one.
sd(sp, MemOperand(a6));
}
void MacroAssembler::PopStackHandler() {
STATIC_ASSERT(StackHandlerConstants::kNextOffset == 0);
pop(a1);
Daddu(sp, sp, Operand(static_cast<int64_t>(StackHandlerConstants::kSize -
kPointerSize)));
li(at, Operand(ExternalReference(Isolate::kHandlerAddress, isolate())));
sd(a1, MemOperand(at));
}
void MacroAssembler::Allocate(int object_size,
Register result,
Register scratch1,
Register scratch2,
Label* gc_required,
AllocationFlags flags) {
DCHECK(object_size <= Page::kMaxRegularHeapObjectSize);
if (!FLAG_inline_new) {
if (emit_debug_code()) {
// Trash the registers to simulate an allocation failure.
li(result, 0x7091);
li(scratch1, 0x7191);
li(scratch2, 0x7291);
}
jmp(gc_required);
return;
}
DCHECK(!result.is(scratch1));
DCHECK(!result.is(scratch2));
DCHECK(!scratch1.is(scratch2));
DCHECK(!scratch1.is(t9));
DCHECK(!scratch2.is(t9));
DCHECK(!result.is(t9));
// Make object size into bytes.
if ((flags & SIZE_IN_WORDS) != 0) {
object_size *= kPointerSize;
}
DCHECK(0 == (object_size & kObjectAlignmentMask));
// Check relative positions of allocation top and limit addresses.
// ARM adds additional checks to make sure the ldm instruction can be
// used. On MIPS we don't have ldm so we don't need additional checks either.
ExternalReference allocation_top =
AllocationUtils::GetAllocationTopReference(isolate(), flags);
ExternalReference allocation_limit =
AllocationUtils::GetAllocationLimitReference(isolate(), flags);
intptr_t top =
reinterpret_cast<intptr_t>(allocation_top.address());
intptr_t limit =
reinterpret_cast<intptr_t>(allocation_limit.address());
DCHECK((limit - top) == kPointerSize);
// Set up allocation top address and object size registers.
Register topaddr = scratch1;
li(topaddr, Operand(allocation_top));
// This code stores a temporary value in t9.
if ((flags & RESULT_CONTAINS_TOP) == 0) {
// Load allocation top into result and allocation limit into t9.
ld(result, MemOperand(topaddr));
ld(t9, MemOperand(topaddr, kPointerSize));
} else {
if (emit_debug_code()) {
// Assert that result actually contains top on entry. t9 is used
// immediately below so this use of t9 does not cause difference with
// respect to register content between debug and release mode.
ld(t9, MemOperand(topaddr));
Check(eq, kUnexpectedAllocationTop, result, Operand(t9));
}
// Load allocation limit into t9. Result already contains allocation top.
ld(t9, MemOperand(topaddr, limit - top));
}
DCHECK(kPointerSize == kDoubleSize);
if (emit_debug_code()) {
And(at, result, Operand(kDoubleAlignmentMask));
Check(eq, kAllocationIsNotDoubleAligned, at, Operand(zero_reg));
}
// Calculate new top and bail out if new space is exhausted. Use result
// to calculate the new top.
Daddu(scratch2, result, Operand(object_size));
Branch(gc_required, Ugreater, scratch2, Operand(t9));
sd(scratch2, MemOperand(topaddr));
// Tag object if requested.
if ((flags & TAG_OBJECT) != 0) {
Daddu(result, result, Operand(kHeapObjectTag));
}
}
void MacroAssembler::Allocate(Register object_size,
Register result,
Register scratch1,
Register scratch2,
Label* gc_required,
AllocationFlags flags) {
if (!FLAG_inline_new) {
if (emit_debug_code()) {
// Trash the registers to simulate an allocation failure.
li(result, 0x7091);
li(scratch1, 0x7191);
li(scratch2, 0x7291);
}
jmp(gc_required);
return;
}
DCHECK(!result.is(scratch1));
DCHECK(!result.is(scratch2));
DCHECK(!scratch1.is(scratch2));
DCHECK(!object_size.is(t9));
DCHECK(!scratch1.is(t9) && !scratch2.is(t9) && !result.is(t9));
// Check relative positions of allocation top and limit addresses.
// ARM adds additional checks to make sure the ldm instruction can be
// used. On MIPS we don't have ldm so we don't need additional checks either.
ExternalReference allocation_top =
AllocationUtils::GetAllocationTopReference(isolate(), flags);
ExternalReference allocation_limit =
AllocationUtils::GetAllocationLimitReference(isolate(), flags);
intptr_t top =
reinterpret_cast<intptr_t>(allocation_top.address());
intptr_t limit =
reinterpret_cast<intptr_t>(allocation_limit.address());
DCHECK((limit - top) == kPointerSize);
// Set up allocation top address and object size registers.
Register topaddr = scratch1;
li(topaddr, Operand(allocation_top));
// This code stores a temporary value in t9.
if ((flags & RESULT_CONTAINS_TOP) == 0) {
// Load allocation top into result and allocation limit into t9.
ld(result, MemOperand(topaddr));
ld(t9, MemOperand(topaddr, kPointerSize));
} else {
if (emit_debug_code()) {
// Assert that result actually contains top on entry. t9 is used
// immediately below so this use of t9 does not cause difference with
// respect to register content between debug and release mode.
ld(t9, MemOperand(topaddr));
Check(eq, kUnexpectedAllocationTop, result, Operand(t9));
}
// Load allocation limit into t9. Result already contains allocation top.
ld(t9, MemOperand(topaddr, limit - top));
}
DCHECK(kPointerSize == kDoubleSize);
if (emit_debug_code()) {
And(at, result, Operand(kDoubleAlignmentMask));
Check(eq, kAllocationIsNotDoubleAligned, at, Operand(zero_reg));
}
// Calculate new top and bail out if new space is exhausted. Use result
// to calculate the new top. Object size may be in words so a shift is
// required to get the number of bytes.
if ((flags & SIZE_IN_WORDS) != 0) {
dsll(scratch2, object_size, kPointerSizeLog2);
Daddu(scratch2, result, scratch2);
} else {
Daddu(scratch2, result, Operand(object_size));
}
Branch(gc_required, Ugreater, scratch2, Operand(t9));
// Update allocation top. result temporarily holds the new top.
if (emit_debug_code()) {
And(t9, scratch2, Operand(kObjectAlignmentMask));
Check(eq, kUnalignedAllocationInNewSpace, t9, Operand(zero_reg));
}
sd(scratch2, MemOperand(topaddr));
// Tag object if requested.
if ((flags & TAG_OBJECT) != 0) {
Daddu(result, result, Operand(kHeapObjectTag));
}
}
void MacroAssembler::UndoAllocationInNewSpace(Register object,
Register scratch) {
ExternalReference new_space_allocation_top =
ExternalReference::new_space_allocation_top_address(isolate());
// Make sure the object has no tag before resetting top.
And(object, object, Operand(~kHeapObjectTagMask));
#ifdef DEBUG
// Check that the object un-allocated is below the current top.
li(scratch, Operand(new_space_allocation_top));
ld(scratch, MemOperand(scratch));
Check(less, kUndoAllocationOfNonAllocatedMemory,
object, Operand(scratch));
#endif
// Write the address of the object to un-allocate as the current top.
li(scratch, Operand(new_space_allocation_top));
sd(object, MemOperand(scratch));
}
void MacroAssembler::AllocateTwoByteString(Register result,
Register length,
Register scratch1,
Register scratch2,
Register scratch3,
Label* gc_required) {
// Calculate the number of bytes needed for the characters in the string while
// observing object alignment.
DCHECK((SeqTwoByteString::kHeaderSize & kObjectAlignmentMask) == 0);
dsll(scratch1, length, 1); // Length in bytes, not chars.
daddiu(scratch1, scratch1,
kObjectAlignmentMask + SeqTwoByteString::kHeaderSize);
And(scratch1, scratch1, Operand(~kObjectAlignmentMask));
// Allocate two-byte string in new space.
Allocate(scratch1,
result,
scratch2,
scratch3,
gc_required,
TAG_OBJECT);
// Set the map, length and hash field.
InitializeNewString(result,
length,
Heap::kStringMapRootIndex,
scratch1,
scratch2);
}
void MacroAssembler::AllocateOneByteString(Register result, Register length,
Register scratch1, Register scratch2,
Register scratch3,
Label* gc_required) {
// Calculate the number of bytes needed for the characters in the string
// while observing object alignment.
DCHECK((SeqOneByteString::kHeaderSize & kObjectAlignmentMask) == 0);
DCHECK(kCharSize == 1);
daddiu(scratch1, length,
kObjectAlignmentMask + SeqOneByteString::kHeaderSize);
And(scratch1, scratch1, Operand(~kObjectAlignmentMask));
// Allocate one-byte string in new space.
Allocate(scratch1,
result,
scratch2,
scratch3,
gc_required,
TAG_OBJECT);
// Set the map, length and hash field.
InitializeNewString(result, length, Heap::kOneByteStringMapRootIndex,
scratch1, scratch2);
}
void MacroAssembler::AllocateTwoByteConsString(Register result,
Register length,
Register scratch1,
Register scratch2,
Label* gc_required) {
Allocate(ConsString::kSize, result, scratch1, scratch2, gc_required,
TAG_OBJECT);
InitializeNewString(result,
length,
Heap::kConsStringMapRootIndex,
scratch1,
scratch2);
}
void MacroAssembler::AllocateOneByteConsString(Register result, Register length,
Register scratch1,
Register scratch2,
Label* gc_required) {
Allocate(ConsString::kSize,
result,
scratch1,
scratch2,
gc_required,
TAG_OBJECT);
InitializeNewString(result, length, Heap::kConsOneByteStringMapRootIndex,
scratch1, scratch2);
}
void MacroAssembler::AllocateTwoByteSlicedString(Register result,
Register length,
Register scratch1,
Register scratch2,
Label* gc_required) {
Allocate(SlicedString::kSize, result, scratch1, scratch2, gc_required,
TAG_OBJECT);
InitializeNewString(result,
length,
Heap::kSlicedStringMapRootIndex,
scratch1,
scratch2);
}
void MacroAssembler::AllocateOneByteSlicedString(Register result,
Register length,
Register scratch1,
Register scratch2,
Label* gc_required) {
Allocate(SlicedString::kSize, result, scratch1, scratch2, gc_required,
TAG_OBJECT);
InitializeNewString(result, length, Heap::kSlicedOneByteStringMapRootIndex,
scratch1, scratch2);
}
void MacroAssembler::JumpIfNotUniqueNameInstanceType(Register reg,
Label* not_unique_name) {
STATIC_ASSERT(kInternalizedTag == 0 && kStringTag == 0);
Label succeed;
And(at, reg, Operand(kIsNotStringMask | kIsNotInternalizedMask));
Branch(&succeed, eq, at, Operand(zero_reg));
Branch(not_unique_name, ne, reg, Operand(SYMBOL_TYPE));
bind(&succeed);
}
// Allocates a heap number or jumps to the label if the young space is full and
// a scavenge is needed.
void MacroAssembler::AllocateHeapNumber(Register result,
Register scratch1,
Register scratch2,
Register heap_number_map,
Label* need_gc,
TaggingMode tagging_mode,
MutableMode mode) {
// Allocate an object in the heap for the heap number and tag it as a heap
// object.
Allocate(HeapNumber::kSize, result, scratch1, scratch2, need_gc,
tagging_mode == TAG_RESULT ? TAG_OBJECT : NO_ALLOCATION_FLAGS);
Heap::RootListIndex map_index = mode == MUTABLE
? Heap::kMutableHeapNumberMapRootIndex
: Heap::kHeapNumberMapRootIndex;
AssertIsRoot(heap_number_map, map_index);
// Store heap number map in the allocated object.
if (tagging_mode == TAG_RESULT) {
sd(heap_number_map, FieldMemOperand(result, HeapObject::kMapOffset));
} else {
sd(heap_number_map, MemOperand(result, HeapObject::kMapOffset));
}
}
void MacroAssembler::AllocateHeapNumberWithValue(Register result,
FPURegister value,
Register scratch1,
Register scratch2,
Label* gc_required) {
LoadRoot(t8, Heap::kHeapNumberMapRootIndex);
AllocateHeapNumber(result, scratch1, scratch2, t8, gc_required);
sdc1(value, FieldMemOperand(result, HeapNumber::kValueOffset));
}
// Copies a fixed number of fields of heap objects from src to dst.
void MacroAssembler::CopyFields(Register dst,
Register src,
RegList temps,
int field_count) {
DCHECK((temps & dst.bit()) == 0);
DCHECK((temps & src.bit()) == 0);
// Primitive implementation using only one temporary register.
Register tmp = no_reg;
// Find a temp register in temps list.
for (int i = 0; i < kNumRegisters; i++) {
if ((temps & (1 << i)) != 0) {
tmp.code_ = i;
break;
}
}
DCHECK(!tmp.is(no_reg));
for (int i = 0; i < field_count; i++) {
ld(tmp, FieldMemOperand(src, i * kPointerSize));
sd(tmp, FieldMemOperand(dst, i * kPointerSize));
}
}
void MacroAssembler::CopyBytes(Register src,
Register dst,
Register length,
Register scratch) {
Label align_loop_1, word_loop, byte_loop, byte_loop_1, done;
// Align src before copying in word size chunks.
Branch(&byte_loop, le, length, Operand(kPointerSize));
bind(&align_loop_1);
And(scratch, src, kPointerSize - 1);
Branch(&word_loop, eq, scratch, Operand(zero_reg));
lbu(scratch, MemOperand(src));
Daddu(src, src, 1);
sb(scratch, MemOperand(dst));
Daddu(dst, dst, 1);
Dsubu(length, length, Operand(1));
Branch(&align_loop_1, ne, length, Operand(zero_reg));
// Copy bytes in word size chunks.
bind(&word_loop);
if (emit_debug_code()) {
And(scratch, src, kPointerSize - 1);
Assert(eq, kExpectingAlignmentForCopyBytes,
scratch, Operand(zero_reg));
}
Branch(&byte_loop, lt, length, Operand(kPointerSize));
ld(scratch, MemOperand(src));
Daddu(src, src, kPointerSize);
// TODO(kalmard) check if this can be optimized to use sw in most cases.
// Can't use unaligned access - copy byte by byte.
sb(scratch, MemOperand(dst, 0));
dsrl(scratch, scratch, 8);
sb(scratch, MemOperand(dst, 1));
dsrl(scratch, scratch, 8);
sb(scratch, MemOperand(dst, 2));
dsrl(scratch, scratch, 8);
sb(scratch, MemOperand(dst, 3));
dsrl(scratch, scratch, 8);
sb(scratch, MemOperand(dst, 4));
dsrl(scratch, scratch, 8);
sb(scratch, MemOperand(dst, 5));
dsrl(scratch, scratch, 8);
sb(scratch, MemOperand(dst, 6));
dsrl(scratch, scratch, 8);
sb(scratch, MemOperand(dst, 7));
Daddu(dst, dst, 8);
Dsubu(length, length, Operand(kPointerSize));
Branch(&word_loop);
// Copy the last bytes if any left.
bind(&byte_loop);
Branch(&done, eq, length, Operand(zero_reg));
bind(&byte_loop_1);
lbu(scratch, MemOperand(src));
Daddu(src, src, 1);
sb(scratch, MemOperand(dst));
Daddu(dst, dst, 1);
Dsubu(length, length, Operand(1));
Branch(&byte_loop_1, ne, length, Operand(zero_reg));
bind(&done);
}
void MacroAssembler::InitializeFieldsWithFiller(Register start_offset,
Register end_offset,
Register filler) {
Label loop, entry;
Branch(&entry);
bind(&loop);
sd(filler, MemOperand(start_offset));
Daddu(start_offset, start_offset, kPointerSize);
bind(&entry);
Branch(&loop, lt, start_offset, Operand(end_offset));
}
void MacroAssembler::CheckFastElements(Register map,
Register scratch,
Label* fail) {
STATIC_ASSERT(FAST_SMI_ELEMENTS == 0);
STATIC_ASSERT(FAST_HOLEY_SMI_ELEMENTS == 1);
STATIC_ASSERT(FAST_ELEMENTS == 2);
STATIC_ASSERT(FAST_HOLEY_ELEMENTS == 3);
lbu(scratch, FieldMemOperand(map, Map::kBitField2Offset));
Branch(fail, hi, scratch,
Operand(Map::kMaximumBitField2FastHoleyElementValue));
}
void MacroAssembler::CheckFastObjectElements(Register map,
Register scratch,
Label* fail) {
STATIC_ASSERT(FAST_SMI_ELEMENTS == 0);
STATIC_ASSERT(FAST_HOLEY_SMI_ELEMENTS == 1);
STATIC_ASSERT(FAST_ELEMENTS == 2);
STATIC_ASSERT(FAST_HOLEY_ELEMENTS == 3);
lbu(scratch, FieldMemOperand(map, Map::kBitField2Offset));
Branch(fail, ls, scratch,
Operand(Map::kMaximumBitField2FastHoleySmiElementValue));
Branch(fail, hi, scratch,
Operand(Map::kMaximumBitField2FastHoleyElementValue));
}
void MacroAssembler::CheckFastSmiElements(Register map,
Register scratch,
Label* fail) {
STATIC_ASSERT(FAST_SMI_ELEMENTS == 0);
STATIC_ASSERT(FAST_HOLEY_SMI_ELEMENTS == 1);
lbu(scratch, FieldMemOperand(map, Map::kBitField2Offset));
Branch(fail, hi, scratch,
Operand(Map::kMaximumBitField2FastHoleySmiElementValue));
}
void MacroAssembler::StoreNumberToDoubleElements(Register value_reg,
Register key_reg,
Register elements_reg,
Register scratch1,
Register scratch2,
Label* fail,
int elements_offset) {
Label smi_value, done;
// Handle smi values specially.
JumpIfSmi(value_reg, &smi_value);
// Ensure that the object is a heap number.
CheckMap(value_reg,
scratch1,
Heap::kHeapNumberMapRootIndex,
fail,
DONT_DO_SMI_CHECK);
// Double value, turn potential sNaN into qNan.
DoubleRegister double_result = f0;
DoubleRegister double_scratch = f2;
ldc1(double_result, FieldMemOperand(value_reg, HeapNumber::kValueOffset));
Branch(USE_DELAY_SLOT, &done); // Canonicalization is one instruction.
FPUCanonicalizeNaN(double_result, double_result);
bind(&smi_value);
// scratch1 is now effective address of the double element.
// Untag and transfer.
dsrl32(at, value_reg, 0);
mtc1(at, double_scratch);
cvt_d_w(double_result, double_scratch);
bind(&done);
Daddu(scratch1, elements_reg,
Operand(FixedDoubleArray::kHeaderSize - kHeapObjectTag -
elements_offset));
dsra(scratch2, key_reg, 32 - kDoubleSizeLog2);
Daddu(scratch1, scratch1, scratch2);
sdc1(double_result, MemOperand(scratch1, 0));
}
void MacroAssembler::CompareMapAndBranch(Register obj,
Register scratch,
Handle<Map> map,
Label* early_success,
Condition cond,
Label* branch_to) {
ld(scratch, FieldMemOperand(obj, HeapObject::kMapOffset));
CompareMapAndBranch(scratch, map, early_success, cond, branch_to);
}
void MacroAssembler::CompareMapAndBranch(Register obj_map,
Handle<Map> map,
Label* early_success,
Condition cond,
Label* branch_to) {
Branch(branch_to, cond, obj_map, Operand(map));
}
void MacroAssembler::CheckMap(Register obj,
Register scratch,
Handle<Map> map,
Label* fail,
SmiCheckType smi_check_type) {
if (smi_check_type == DO_SMI_CHECK) {
JumpIfSmi(obj, fail);
}
Label success;
CompareMapAndBranch(obj, scratch, map, &success, ne, fail);
bind(&success);
}
void MacroAssembler::DispatchWeakMap(Register obj, Register scratch1,
Register scratch2, Handle<WeakCell> cell,
Handle<Code> success,
SmiCheckType smi_check_type) {
Label fail;
if (smi_check_type == DO_SMI_CHECK) {
JumpIfSmi(obj, &fail);
}
ld(scratch1, FieldMemOperand(obj, HeapObject::kMapOffset));
GetWeakValue(scratch2, cell);
Jump(success, RelocInfo::CODE_TARGET, eq, scratch1, Operand(scratch2));
bind(&fail);
}
void MacroAssembler::CheckMap(Register obj,
Register scratch,
Heap::RootListIndex index,
Label* fail,
SmiCheckType smi_check_type) {
if (smi_check_type == DO_SMI_CHECK) {
JumpIfSmi(obj, fail);
}
ld(scratch, FieldMemOperand(obj, HeapObject::kMapOffset));
LoadRoot(at, index);
Branch(fail, ne, scratch, Operand(at));
}
void MacroAssembler::GetWeakValue(Register value, Handle<WeakCell> cell) {
li(value, Operand(cell));
ld(value, FieldMemOperand(value, WeakCell::kValueOffset));
}
void MacroAssembler::FPUCanonicalizeNaN(const DoubleRegister dst,
const DoubleRegister src) {
sub_d(dst, src, kDoubleRegZero);
}
void MacroAssembler::LoadWeakValue(Register value, Handle<WeakCell> cell,
Label* miss) {
GetWeakValue(value, cell);
JumpIfSmi(value, miss);
}
void MacroAssembler::MovFromFloatResult(const DoubleRegister dst) {
if (IsMipsSoftFloatABI) {
Move(dst, v0, v1);
} else {
Move(dst, f0); // Reg f0 is o32 ABI FP return value.
}
}
void MacroAssembler::MovFromFloatParameter(const DoubleRegister dst) {
if (IsMipsSoftFloatABI) {
Move(dst, a0, a1);
} else {
Move(dst, f12); // Reg f12 is o32 ABI FP first argument value.
}
}
void MacroAssembler::MovToFloatParameter(DoubleRegister src) {
if (!IsMipsSoftFloatABI) {
Move(f12, src);
} else {
Move(a0, a1, src);
}
}
void MacroAssembler::MovToFloatResult(DoubleRegister src) {
if (!IsMipsSoftFloatABI) {
Move(f0, src);
} else {
Move(v0, v1, src);
}
}
void MacroAssembler::MovToFloatParameters(DoubleRegister src1,
DoubleRegister src2) {
if (!IsMipsSoftFloatABI) {
const DoubleRegister fparg2 = (kMipsAbi == kN64) ? f13 : f14;
if (src2.is(f12)) {
DCHECK(!src1.is(fparg2));
Move(fparg2, src2);
Move(f12, src1);
} else {
Move(f12, src1);
Move(fparg2, src2);
}
} else {
Move(a0, a1, src1);
Move(a2, a3, src2);
}
}
// -----------------------------------------------------------------------------
// JavaScript invokes.
void MacroAssembler::InvokePrologue(const ParameterCount& expected,
const ParameterCount& actual,
Handle<Code> code_constant,
Register code_reg,
Label* done,
bool* definitely_mismatches,
InvokeFlag flag,
const CallWrapper& call_wrapper) {
bool definitely_matches = false;
*definitely_mismatches = false;
Label regular_invoke;
// Check whether the expected and actual arguments count match. If not,
// setup registers according to contract with ArgumentsAdaptorTrampoline:
// a0: actual arguments count
// a1: function (passed through to callee)
// a2: expected arguments count
// The code below is made a lot easier because the calling code already sets
// up actual and expected registers according to the contract if values are
// passed in registers.
DCHECK(actual.is_immediate() || actual.reg().is(a0));
DCHECK(expected.is_immediate() || expected.reg().is(a2));
DCHECK((!code_constant.is_null() && code_reg.is(no_reg)) || code_reg.is(a3));
if (expected.is_immediate()) {
DCHECK(actual.is_immediate());
if (expected.immediate() == actual.immediate()) {
definitely_matches = true;
} else {
li(a0, Operand(actual.immediate()));
const int sentinel = SharedFunctionInfo::kDontAdaptArgumentsSentinel;
if (expected.immediate() == sentinel) {
// Don't worry about adapting arguments for builtins that
// don't want that done. Skip adaption code by making it look
// like we have a match between expected and actual number of
// arguments.
definitely_matches = true;
} else {
*definitely_mismatches = true;
li(a2, Operand(expected.immediate()));
}
}
} else if (actual.is_immediate()) {
Branch(®ular_invoke, eq, expected.reg(), Operand(actual.immediate()));
li(a0, Operand(actual.immediate()));
} else {
Branch(®ular_invoke, eq, expected.reg(), Operand(actual.reg()));
}
if (!definitely_matches) {
if (!code_constant.is_null()) {
li(a3, Operand(code_constant));
daddiu(a3, a3, Code::kHeaderSize - kHeapObjectTag);
}
Handle<Code> adaptor =
isolate()->builtins()->ArgumentsAdaptorTrampoline();
if (flag == CALL_FUNCTION) {
call_wrapper.BeforeCall(CallSize(adaptor));
Call(adaptor);
call_wrapper.AfterCall();
if (!*definitely_mismatches) {
Branch(done);
}
} else {
Jump(adaptor, RelocInfo::CODE_TARGET);
}
bind(®ular_invoke);
}
}
void MacroAssembler::InvokeCode(Register code,
const ParameterCount& expected,
const ParameterCount& actual,
InvokeFlag flag,
const CallWrapper& call_wrapper) {
// You can't call a function without a valid frame.
DCHECK(flag == JUMP_FUNCTION || has_frame());
Label done;
bool definitely_mismatches = false;
InvokePrologue(expected, actual, Handle<Code>::null(), code,
&done, &definitely_mismatches, flag,
call_wrapper);
if (!definitely_mismatches) {
if (flag == CALL_FUNCTION) {
call_wrapper.BeforeCall(CallSize(code));
Call(code);
call_wrapper.AfterCall();
} else {
DCHECK(flag == JUMP_FUNCTION);
Jump(code);
}
// Continue here if InvokePrologue does handle the invocation due to
// mismatched parameter counts.
bind(&done);
}
}
void MacroAssembler::InvokeFunction(Register function,
const ParameterCount& actual,
InvokeFlag flag,
const CallWrapper& call_wrapper) {
// You can't call a function without a valid frame.
DCHECK(flag == JUMP_FUNCTION || has_frame());
// Contract with called JS functions requires that function is passed in a1.
DCHECK(function.is(a1));
Register expected_reg = a2;
Register code_reg = a3;
ld(code_reg, FieldMemOperand(a1, JSFunction::kSharedFunctionInfoOffset));
ld(cp, FieldMemOperand(a1, JSFunction::kContextOffset));
// The argument count is stored as int32_t on 64-bit platforms.
// TODO(plind): Smi on 32-bit platforms.
lw(expected_reg,
FieldMemOperand(code_reg,
SharedFunctionInfo::kFormalParameterCountOffset));
ld(code_reg, FieldMemOperand(a1, JSFunction::kCodeEntryOffset));
ParameterCount expected(expected_reg);
InvokeCode(code_reg, expected, actual, flag, call_wrapper);
}
void MacroAssembler::InvokeFunction(Register function,
const ParameterCount& expected,
const ParameterCount& actual,
InvokeFlag flag,
const CallWrapper& call_wrapper) {
// You can't call a function without a valid frame.
DCHECK(flag == JUMP_FUNCTION || has_frame());
// Contract with called JS functions requires that function is passed in a1.
DCHECK(function.is(a1));
// Get the function and setup the context.
ld(cp, FieldMemOperand(a1, JSFunction::kContextOffset));
// We call indirectly through the code field in the function to
// allow recompilation to take effect without changing any of the
// call sites.
ld(a3, FieldMemOperand(a1, JSFunction::kCodeEntryOffset));
InvokeCode(a3, expected, actual, flag, call_wrapper);
}
void MacroAssembler::InvokeFunction(Handle<JSFunction> function,
const ParameterCount& expected,
const ParameterCount& actual,
InvokeFlag flag,
const CallWrapper& call_wrapper) {
li(a1, function);
InvokeFunction(a1, expected, actual, flag, call_wrapper);
}
void MacroAssembler::IsObjectJSObjectType(Register heap_object,
Register map,
Register scratch,
Label* fail) {
ld(map, FieldMemOperand(heap_object, HeapObject::kMapOffset));
IsInstanceJSObjectType(map, scratch, fail);
}
void MacroAssembler::IsInstanceJSObjectType(Register map,
Register scratch,
Label* fail) {
lbu(scratch, FieldMemOperand(map, Map::kInstanceTypeOffset));
Branch(fail, lt, scratch, Operand(FIRST_NONCALLABLE_SPEC_OBJECT_TYPE));
Branch(fail, gt, scratch, Operand(LAST_NONCALLABLE_SPEC_OBJECT_TYPE));
}
void MacroAssembler::IsObjectJSStringType(Register object,
Register scratch,
Label* fail) {
DCHECK(kNotStringTag != 0);
ld(scratch, FieldMemOperand(object, HeapObject::kMapOffset));
lbu(scratch, FieldMemOperand(scratch, Map::kInstanceTypeOffset));
And(scratch, scratch, Operand(kIsNotStringMask));
Branch(fail, ne, scratch, Operand(zero_reg));
}
void MacroAssembler::IsObjectNameType(Register object,
Register scratch,
Label* fail) {
ld(scratch, FieldMemOperand(object, HeapObject::kMapOffset));
lbu(scratch, FieldMemOperand(scratch, Map::kInstanceTypeOffset));
Branch(fail, hi, scratch, Operand(LAST_NAME_TYPE));
}
// ---------------------------------------------------------------------------
// Support functions.
void MacroAssembler::GetMapConstructor(Register result, Register map,
Register temp, Register temp2) {
Label done, loop;
ld(result, FieldMemOperand(map, Map::kConstructorOrBackPointerOffset));
bind(&loop);
JumpIfSmi(result, &done);
GetObjectType(result, temp, temp2);
Branch(&done, ne, temp2, Operand(MAP_TYPE));
ld(result, FieldMemOperand(result, Map::kConstructorOrBackPointerOffset));
Branch(&loop);
bind(&done);
}
void MacroAssembler::TryGetFunctionPrototype(Register function,
Register result,
Register scratch,
Label* miss,
bool miss_on_bound_function) {
Label non_instance;
if (miss_on_bound_function) {
// Check that the receiver isn't a smi.
JumpIfSmi(function, miss);
// Check that the function really is a function. Load map into result reg.
GetObjectType(function, result, scratch);
Branch(miss, ne, scratch, Operand(JS_FUNCTION_TYPE));
ld(scratch,
FieldMemOperand(function, JSFunction::kSharedFunctionInfoOffset));
lwu(scratch,
FieldMemOperand(scratch, SharedFunctionInfo::kCompilerHintsOffset));
And(scratch, scratch,
Operand(1 << SharedFunctionInfo::kBoundFunction));
Branch(miss, ne, scratch, Operand(zero_reg));
// Make sure that the function has an instance prototype.
lbu(scratch, FieldMemOperand(result, Map::kBitFieldOffset));
And(scratch, scratch, Operand(1 << Map::kHasNonInstancePrototype));
Branch(&non_instance, ne, scratch, Operand(zero_reg));
}
// Get the prototype or initial map from the function.
ld(result,
FieldMemOperand(function, JSFunction::kPrototypeOrInitialMapOffset));
// If the prototype or initial map is the hole, don't return it and
// simply miss the cache instead. This will allow us to allocate a
// prototype object on-demand in the runtime system.
LoadRoot(t8, Heap::kTheHoleValueRootIndex);
Branch(miss, eq, result, Operand(t8));
// If the function does not have an initial map, we're done.
Label done;
GetObjectType(result, scratch, scratch);
Branch(&done, ne, scratch, Operand(MAP_TYPE));
// Get the prototype from the initial map.
ld(result, FieldMemOperand(result, Map::kPrototypeOffset));
if (miss_on_bound_function) {
jmp(&done);
// Non-instance prototype: Fetch prototype from constructor field
// in initial map.
bind(&non_instance);
GetMapConstructor(result, result, scratch, scratch);
}
// All done.
bind(&done);
}
void MacroAssembler::GetObjectType(Register object,
Register map,
Register type_reg) {
ld(map, FieldMemOperand(object, HeapObject::kMapOffset));
lbu(type_reg, FieldMemOperand(map, Map::kInstanceTypeOffset));
}
// -----------------------------------------------------------------------------
// Runtime calls.
void MacroAssembler::CallStub(CodeStub* stub,
TypeFeedbackId ast_id,
Condition cond,
Register r1,
const Operand& r2,
BranchDelaySlot bd) {
DCHECK(AllowThisStubCall(stub)); // Stub calls are not allowed in some stubs.
Call(stub->GetCode(), RelocInfo::CODE_TARGET, ast_id,
cond, r1, r2, bd);
}
void MacroAssembler::TailCallStub(CodeStub* stub,
Condition cond,
Register r1,
const Operand& r2,
BranchDelaySlot bd) {
Jump(stub->GetCode(), RelocInfo::CODE_TARGET, cond, r1, r2, bd);
}
bool MacroAssembler::AllowThisStubCall(CodeStub* stub) {
return has_frame_ || !stub->SometimesSetsUpAFrame();
}
void MacroAssembler::IndexFromHash(Register hash, Register index) {
// If the hash field contains an array index pick it out. The assert checks
// that the constants for the maximum number of digits for an array index
// cached in the hash field and the number of bits reserved for it does not
// conflict.
DCHECK(TenToThe(String::kMaxCachedArrayIndexLength) <
(1 << String::kArrayIndexValueBits));
DecodeFieldToSmi<String::ArrayIndexValueBits>(index, hash);
}
void MacroAssembler::ObjectToDoubleFPURegister(Register object,
FPURegister result,
Register scratch1,
Register scratch2,
Register heap_number_map,
Label* not_number,
ObjectToDoubleFlags flags) {
Label done;
if ((flags & OBJECT_NOT_SMI) == 0) {
Label not_smi;
JumpIfNotSmi(object, ¬_smi);
// Remove smi tag and convert to double.
// dsra(scratch1, object, kSmiTagSize);
dsra32(scratch1, object, 0);
mtc1(scratch1, result);
cvt_d_w(result, result);
Branch(&done);
bind(¬_smi);
}
// Check for heap number and load double value from it.
ld(scratch1, FieldMemOperand(object, HeapObject::kMapOffset));
Branch(not_number, ne, scratch1, Operand(heap_number_map));
if ((flags & AVOID_NANS_AND_INFINITIES) != 0) {
// If exponent is all ones the number is either a NaN or +/-Infinity.
Register exponent = scratch1;
Register mask_reg = scratch2;
lwu(exponent, FieldMemOperand(object, HeapNumber::kExponentOffset));
li(mask_reg, HeapNumber::kExponentMask);
And(exponent, exponent, mask_reg);
Branch(not_number, eq, exponent, Operand(mask_reg));
}
ldc1(result, FieldMemOperand(object, HeapNumber::kValueOffset));
bind(&done);
}
void MacroAssembler::SmiToDoubleFPURegister(Register smi,
FPURegister value,
Register scratch1) {
// dsra(scratch1, smi, kSmiTagSize);
dsra32(scratch1, smi, 0);
mtc1(scratch1, value);
cvt_d_w(value, value);
}
void MacroAssembler::AdduAndCheckForOverflow(Register dst, Register left,
const Operand& right,
Register overflow_dst,
Register scratch) {
if (right.is_reg()) {
AdduAndCheckForOverflow(dst, left, right.rm(), overflow_dst, scratch);
} else {
if (dst.is(left)) {
mov(scratch, left); // Preserve left.
daddiu(dst, left, right.immediate()); // Left is overwritten.
xor_(scratch, dst, scratch); // Original left.
// Load right since xori takes uint16 as immediate.
daddiu(t9, zero_reg, right.immediate());
xor_(overflow_dst, dst, t9);
and_(overflow_dst, overflow_dst, scratch);
} else {
daddiu(dst, left, right.immediate());
xor_(overflow_dst, dst, left);
// Load right since xori takes uint16 as immediate.
daddiu(t9, zero_reg, right.immediate());
xor_(scratch, dst, t9);
and_(overflow_dst, scratch, overflow_dst);
}
}
}
void MacroAssembler::AdduAndCheckForOverflow(Register dst,
Register left,
Register right,
Register overflow_dst,
Register scratch) {
DCHECK(!dst.is(overflow_dst));
DCHECK(!dst.is(scratch));
DCHECK(!overflow_dst.is(scratch));
DCHECK(!overflow_dst.is(left));
DCHECK(!overflow_dst.is(right));
if (left.is(right) && dst.is(left)) {
DCHECK(!dst.is(t9));
DCHECK(!scratch.is(t9));
DCHECK(!left.is(t9));
DCHECK(!right.is(t9));
DCHECK(!overflow_dst.is(t9));
mov(t9, right);
right = t9;
}
if (dst.is(left)) {
mov(scratch, left); // Preserve left.
daddu(dst, left, right); // Left is overwritten.
xor_(scratch, dst, scratch); // Original left.
xor_(overflow_dst, dst, right);
and_(overflow_dst, overflow_dst, scratch);
} else if (dst.is(right)) {
mov(scratch, right); // Preserve right.
daddu(dst, left, right); // Right is overwritten.
xor_(scratch, dst, scratch); // Original right.
xor_(overflow_dst, dst, left);
and_(overflow_dst, overflow_dst, scratch);
} else {
daddu(dst, left, right);
xor_(overflow_dst, dst, left);
xor_(scratch, dst, right);
and_(overflow_dst, scratch, overflow_dst);
}
}
void MacroAssembler::SubuAndCheckForOverflow(Register dst, Register left,
const Operand& right,
Register overflow_dst,
Register scratch) {
if (right.is_reg()) {
SubuAndCheckForOverflow(dst, left, right.rm(), overflow_dst, scratch);
} else {
if (dst.is(left)) {
mov(scratch, left); // Preserve left.
daddiu(dst, left, -(right.immediate())); // Left is overwritten.
xor_(overflow_dst, dst, scratch); // scratch is original left.
// Load right since xori takes uint16 as immediate.
daddiu(t9, zero_reg, right.immediate());
xor_(scratch, scratch, t9); // scratch is original left.
and_(overflow_dst, scratch, overflow_dst);
} else {
daddiu(dst, left, -(right.immediate()));
xor_(overflow_dst, dst, left);
// Load right since xori takes uint16 as immediate.
daddiu(t9, zero_reg, right.immediate());
xor_(scratch, left, t9);
and_(overflow_dst, scratch, overflow_dst);
}
}
}
void MacroAssembler::SubuAndCheckForOverflow(Register dst,
Register left,
Register right,
Register overflow_dst,
Register scratch) {
DCHECK(!dst.is(overflow_dst));
DCHECK(!dst.is(scratch));
DCHECK(!overflow_dst.is(scratch));
DCHECK(!overflow_dst.is(left));
DCHECK(!overflow_dst.is(right));
DCHECK(!scratch.is(left));
DCHECK(!scratch.is(right));
// This happens with some crankshaft code. Since Subu works fine if
// left == right, let's not make that restriction here.
if (left.is(right)) {
mov(dst, zero_reg);
mov(overflow_dst, zero_reg);
return;
}
if (dst.is(left)) {
mov(scratch, left); // Preserve left.
dsubu(dst, left, right); // Left is overwritten.
xor_(overflow_dst, dst, scratch); // scratch is original left.
xor_(scratch, scratch, right); // scratch is original left.
and_(overflow_dst, scratch, overflow_dst);
} else if (dst.is(right)) {
mov(scratch, right); // Preserve right.
dsubu(dst, left, right); // Right is overwritten.
xor_(overflow_dst, dst, left);
xor_(scratch, left, scratch); // Original right.
and_(overflow_dst, scratch, overflow_dst);
} else {
dsubu(dst, left, right);
xor_(overflow_dst, dst, left);
xor_(scratch, left, right);
and_(overflow_dst, scratch, overflow_dst);
}
}
void MacroAssembler::CallRuntime(const Runtime::Function* f,
int num_arguments,
SaveFPRegsMode save_doubles) {
// All parameters are on the stack. v0 has the return value after call.
// If the expected number of arguments of the runtime function is
// constant, we check that the actual number of arguments match the
// expectation.
CHECK(f->nargs < 0 || f->nargs == num_arguments);
// TODO(1236192): Most runtime routines don't need the number of
// arguments passed in because it is constant. At some point we
// should remove this need and make the runtime routine entry code
// smarter.
PrepareCEntryArgs(num_arguments);
PrepareCEntryFunction(ExternalReference(f, isolate()));
CEntryStub stub(isolate(), 1, save_doubles);
CallStub(&stub);
}
void MacroAssembler::CallExternalReference(const ExternalReference& ext,
int num_arguments,
BranchDelaySlot bd) {
PrepareCEntryArgs(num_arguments);
PrepareCEntryFunction(ext);
CEntryStub stub(isolate(), 1);
CallStub(&stub, TypeFeedbackId::None(), al, zero_reg, Operand(zero_reg), bd);
}
void MacroAssembler::TailCallExternalReference(const ExternalReference& ext,
int num_arguments,
int result_size) {
// TODO(1236192): Most runtime routines don't need the number of
// arguments passed in because it is constant. At some point we
// should remove this need and make the runtime routine entry code
// smarter.
PrepareCEntryArgs(num_arguments);
JumpToExternalReference(ext);
}
void MacroAssembler::TailCallRuntime(Runtime::FunctionId fid,
int num_arguments,
int result_size) {
TailCallExternalReference(ExternalReference(fid, isolate()),
num_arguments,
result_size);
}
void MacroAssembler::JumpToExternalReference(const ExternalReference& builtin,
BranchDelaySlot bd) {
PrepareCEntryFunction(builtin);
CEntryStub stub(isolate(), 1);
Jump(stub.GetCode(),
RelocInfo::CODE_TARGET,
al,
zero_reg,
Operand(zero_reg),
bd);
}
void MacroAssembler::InvokeBuiltin(Builtins::JavaScript id,
InvokeFlag flag,
const CallWrapper& call_wrapper) {
// You can't call a builtin without a valid frame.
DCHECK(flag == JUMP_FUNCTION || has_frame());
GetBuiltinEntry(t9, id);
if (flag == CALL_FUNCTION) {
call_wrapper.BeforeCall(CallSize(t9));
Call(t9);
call_wrapper.AfterCall();
} else {
DCHECK(flag == JUMP_FUNCTION);
Jump(t9);
}
}
void MacroAssembler::GetBuiltinFunction(Register target,
Builtins::JavaScript id) {
// Load the builtins object into target register.
ld(target, MemOperand(cp, Context::SlotOffset(Context::GLOBAL_OBJECT_INDEX)));
ld(target, FieldMemOperand(target, GlobalObject::kBuiltinsOffset));
// Load the JavaScript builtin function from the builtins object.
ld(target, FieldMemOperand(target,
JSBuiltinsObject::OffsetOfFunctionWithId(id)));
}
void MacroAssembler::GetBuiltinEntry(Register target, Builtins::JavaScript id) {
DCHECK(!target.is(a1));
GetBuiltinFunction(a1, id);
// Load the code entry point from the builtins object.
ld(target, FieldMemOperand(a1, JSFunction::kCodeEntryOffset));
}
void MacroAssembler::SetCounter(StatsCounter* counter, int value,
Register scratch1, Register scratch2) {
if (FLAG_native_code_counters && counter->Enabled()) {
li(scratch1, Operand(value));
li(scratch2, Operand(ExternalReference(counter)));
sd(scratch1, MemOperand(scratch2));
}
}
void MacroAssembler::IncrementCounter(StatsCounter* counter, int value,
Register scratch1, Register scratch2) {
DCHECK(value > 0);
if (FLAG_native_code_counters && counter->Enabled()) {
li(scratch2, Operand(ExternalReference(counter)));
ld(scratch1, MemOperand(scratch2));
Daddu(scratch1, scratch1, Operand(value));
sd(scratch1, MemOperand(scratch2));
}
}
void MacroAssembler::DecrementCounter(StatsCounter* counter, int value,
Register scratch1, Register scratch2) {
DCHECK(value > 0);
if (FLAG_native_code_counters && counter->Enabled()) {
li(scratch2, Operand(ExternalReference(counter)));
ld(scratch1, MemOperand(scratch2));
Dsubu(scratch1, scratch1, Operand(value));
sd(scratch1, MemOperand(scratch2));
}
}
// -----------------------------------------------------------------------------
// Debugging.
void MacroAssembler::Assert(Condition cc, BailoutReason reason,
Register rs, Operand rt) {
if (emit_debug_code())
Check(cc, reason, rs, rt);
}
void MacroAssembler::AssertFastElements(Register elements) {
if (emit_debug_code()) {
DCHECK(!elements.is(at));
Label ok;
push(elements);
ld(elements, FieldMemOperand(elements, HeapObject::kMapOffset));
LoadRoot(at, Heap::kFixedArrayMapRootIndex);
Branch(&ok, eq, elements, Operand(at));
LoadRoot(at, Heap::kFixedDoubleArrayMapRootIndex);
Branch(&ok, eq, elements, Operand(at));
LoadRoot(at, Heap::kFixedCOWArrayMapRootIndex);
Branch(&ok, eq, elements, Operand(at));
Abort(kJSObjectWithFastElementsMapHasSlowElements);
bind(&ok);
pop(elements);
}
}
void MacroAssembler::Check(Condition cc, BailoutReason reason,
Register rs, Operand rt) {
Label L;
Branch(&L, cc, rs, rt);
Abort(reason);
// Will not return here.
bind(&L);
}
void MacroAssembler::Abort(BailoutReason reason) {
Label abort_start;
bind(&abort_start);
#ifdef DEBUG
const char* msg = GetBailoutReason(reason);
if (msg != NULL) {
RecordComment("Abort message: ");
RecordComment(msg);
}
if (FLAG_trap_on_abort) {
stop(msg);
return;
}
#endif
li(a0, Operand(Smi::FromInt(reason)));
push(a0);
// Disable stub call restrictions to always allow calls to abort.
if (!has_frame_) {
// We don't actually want to generate a pile of code for this, so just
// claim there is a stack frame, without generating one.
FrameScope scope(this, StackFrame::NONE);
CallRuntime(Runtime::kAbort, 1);
} else {
CallRuntime(Runtime::kAbort, 1);
}
// Will not return here.
if (is_trampoline_pool_blocked()) {
// If the calling code cares about the exact number of
// instructions generated, we insert padding here to keep the size
// of the Abort macro constant.
// Currently in debug mode with debug_code enabled the number of
// generated instructions is 10, so we use this as a maximum value.
static const int kExpectedAbortInstructions = 10;
int abort_instructions = InstructionsGeneratedSince(&abort_start);
DCHECK(abort_instructions <= kExpectedAbortInstructions);
while (abort_instructions++ < kExpectedAbortInstructions) {
nop();
}
}
}
void MacroAssembler::LoadContext(Register dst, int context_chain_length) {
if (context_chain_length > 0) {
// Move up the chain of contexts to the context containing the slot.
ld(dst, MemOperand(cp, Context::SlotOffset(Context::PREVIOUS_INDEX)));
for (int i = 1; i < context_chain_length; i++) {
ld(dst, MemOperand(dst, Context::SlotOffset(Context::PREVIOUS_INDEX)));
}
} else {
// Slot is in the current function context. Move it into the
// destination register in case we store into it (the write barrier
// cannot be allowed to destroy the context in esi).
Move(dst, cp);
}
}
void MacroAssembler::LoadTransitionedArrayMapConditional(
ElementsKind expected_kind,
ElementsKind transitioned_kind,
Register map_in_out,
Register scratch,
Label* no_map_match) {
// Load the global or builtins object from the current context.
ld(scratch,
MemOperand(cp, Context::SlotOffset(Context::GLOBAL_OBJECT_INDEX)));
ld(scratch, FieldMemOperand(scratch, GlobalObject::kNativeContextOffset));
// Check that the function's map is the same as the expected cached map.
ld(scratch,
MemOperand(scratch,
Context::SlotOffset(Context::JS_ARRAY_MAPS_INDEX)));
size_t offset = expected_kind * kPointerSize +
FixedArrayBase::kHeaderSize;
ld(at, FieldMemOperand(scratch, offset));
Branch(no_map_match, ne, map_in_out, Operand(at));
// Use the transitioned cached map.
offset = transitioned_kind * kPointerSize +
FixedArrayBase::kHeaderSize;
ld(map_in_out, FieldMemOperand(scratch, offset));
}
void MacroAssembler::LoadGlobalFunction(int index, Register function) {
// Load the global or builtins object from the current context.
ld(function,
MemOperand(cp, Context::SlotOffset(Context::GLOBAL_OBJECT_INDEX)));
// Load the native context from the global or builtins object.
ld(function, FieldMemOperand(function,
GlobalObject::kNativeContextOffset));
// Load the function from the native context.
ld(function, MemOperand(function, Context::SlotOffset(index)));
}
void MacroAssembler::LoadGlobalFunctionInitialMap(Register function,
Register map,
Register scratch) {
// Load the initial map. The global functions all have initial maps.
ld(map, FieldMemOperand(function, JSFunction::kPrototypeOrInitialMapOffset));
if (emit_debug_code()) {
Label ok, fail;
CheckMap(map, scratch, Heap::kMetaMapRootIndex, &fail, DO_SMI_CHECK);
Branch(&ok);
bind(&fail);
Abort(kGlobalFunctionsMustHaveInitialMap);
bind(&ok);
}
}
void MacroAssembler::StubPrologue() {
Push(ra, fp, cp);
Push(Smi::FromInt(StackFrame::STUB));
// Adjust FP to point to saved FP.
Daddu(fp, sp, Operand(StandardFrameConstants::kFixedFrameSizeFromFp));
}
void MacroAssembler::Prologue(bool code_pre_aging) {
PredictableCodeSizeScope predictible_code_size_scope(
this, kNoCodeAgeSequenceLength);
// The following three instructions must remain together and unmodified
// for code aging to work properly.
if (code_pre_aging) {
// Pre-age the code.
Code* stub = Code::GetPreAgedCodeAgeStub(isolate());
nop(Assembler::CODE_AGE_MARKER_NOP);
// Load the stub address to t9 and call it,
// GetCodeAgeAndParity() extracts the stub address from this instruction.
li(t9,
Operand(reinterpret_cast<uint64_t>(stub->instruction_start())),
ADDRESS_LOAD);
nop(); // Prevent jalr to jal optimization.
jalr(t9, a0);
nop(); // Branch delay slot nop.
nop(); // Pad the empty space.
} else {
Push(ra, fp, cp, a1);
nop(Assembler::CODE_AGE_SEQUENCE_NOP);
nop(Assembler::CODE_AGE_SEQUENCE_NOP);
nop(Assembler::CODE_AGE_SEQUENCE_NOP);
// Adjust fp to point to caller's fp.
Daddu(fp, sp, Operand(StandardFrameConstants::kFixedFrameSizeFromFp));
}
}
void MacroAssembler::EnterFrame(StackFrame::Type type,
bool load_constant_pool_pointer_reg) {
// Out-of-line constant pool not implemented on mips64.
UNREACHABLE();
}
void MacroAssembler::EnterFrame(StackFrame::Type type) {
daddiu(sp, sp, -5 * kPointerSize);
li(t8, Operand(Smi::FromInt(type)));
li(t9, Operand(CodeObject()), CONSTANT_SIZE);
sd(ra, MemOperand(sp, 4 * kPointerSize));
sd(fp, MemOperand(sp, 3 * kPointerSize));
sd(cp, MemOperand(sp, 2 * kPointerSize));
sd(t8, MemOperand(sp, 1 * kPointerSize));
sd(t9, MemOperand(sp, 0 * kPointerSize));
// Adjust FP to point to saved FP.
Daddu(fp, sp,
Operand(StandardFrameConstants::kFixedFrameSizeFromFp + kPointerSize));
}
void MacroAssembler::LeaveFrame(StackFrame::Type type) {
mov(sp, fp);
ld(fp, MemOperand(sp, 0 * kPointerSize));
ld(ra, MemOperand(sp, 1 * kPointerSize));
daddiu(sp, sp, 2 * kPointerSize);
}
void MacroAssembler::EnterExitFrame(bool save_doubles,
int stack_space) {
// Set up the frame structure on the stack.
STATIC_ASSERT(2 * kPointerSize == ExitFrameConstants::kCallerSPDisplacement);
STATIC_ASSERT(1 * kPointerSize == ExitFrameConstants::kCallerPCOffset);
STATIC_ASSERT(0 * kPointerSize == ExitFrameConstants::kCallerFPOffset);
// This is how the stack will look:
// fp + 2 (==kCallerSPDisplacement) - old stack's end
// [fp + 1 (==kCallerPCOffset)] - saved old ra
// [fp + 0 (==kCallerFPOffset)] - saved old fp
// [fp - 1 (==kSPOffset)] - sp of the called function
// [fp - 2 (==kCodeOffset)] - CodeObject
// fp - (2 + stack_space + alignment) == sp == [fp - kSPOffset] - top of the
// new stack (will contain saved ra)
// Save registers.
daddiu(sp, sp, -4 * kPointerSize);
sd(ra, MemOperand(sp, 3 * kPointerSize));
sd(fp, MemOperand(sp, 2 * kPointerSize));
daddiu(fp, sp, 2 * kPointerSize); // Set up new frame pointer.
if (emit_debug_code()) {
sd(zero_reg, MemOperand(fp, ExitFrameConstants::kSPOffset));
}
// Accessed from ExitFrame::code_slot.
li(t8, Operand(CodeObject()), CONSTANT_SIZE);
sd(t8, MemOperand(fp, ExitFrameConstants::kCodeOffset));
// Save the frame pointer and the context in top.
li(t8, Operand(ExternalReference(Isolate::kCEntryFPAddress, isolate())));
sd(fp, MemOperand(t8));
li(t8, Operand(ExternalReference(Isolate::kContextAddress, isolate())));
sd(cp, MemOperand(t8));
const int frame_alignment = MacroAssembler::ActivationFrameAlignment();
if (save_doubles) {
// The stack is already aligned to 0 modulo 8 for stores with sdc1.
int kNumOfSavedRegisters = FPURegister::kMaxNumRegisters / 2;
int space = kNumOfSavedRegisters * kDoubleSize ;
Dsubu(sp, sp, Operand(space));
// Remember: we only need to save every 2nd double FPU value.
for (int i = 0; i < kNumOfSavedRegisters; i++) {
FPURegister reg = FPURegister::from_code(2 * i);
sdc1(reg, MemOperand(sp, i * kDoubleSize));
}
}
// Reserve place for the return address, stack space and an optional slot
// (used by the DirectCEntryStub to hold the return value if a struct is
// returned) and align the frame preparing for calling the runtime function.
DCHECK(stack_space >= 0);
Dsubu(sp, sp, Operand((stack_space + 2) * kPointerSize));
if (frame_alignment > 0) {
DCHECK(base::bits::IsPowerOfTwo32(frame_alignment));
And(sp, sp, Operand(-frame_alignment)); // Align stack.
}
// Set the exit frame sp value to point just before the return address
// location.
daddiu(at, sp, kPointerSize);
sd(at, MemOperand(fp, ExitFrameConstants::kSPOffset));
}
void MacroAssembler::LeaveExitFrame(bool save_doubles, Register argument_count,
bool restore_context, bool do_return,
bool argument_count_is_length) {
// Optionally restore all double registers.
if (save_doubles) {
// Remember: we only need to restore every 2nd double FPU value.
int kNumOfSavedRegisters = FPURegister::kMaxNumRegisters / 2;
Dsubu(t8, fp, Operand(ExitFrameConstants::kFrameSize +
kNumOfSavedRegisters * kDoubleSize));
for (int i = 0; i < kNumOfSavedRegisters; i++) {
FPURegister reg = FPURegister::from_code(2 * i);
ldc1(reg, MemOperand(t8, i * kDoubleSize));
}
}
// Clear top frame.
li(t8, Operand(ExternalReference(Isolate::kCEntryFPAddress, isolate())));
sd(zero_reg, MemOperand(t8));
// Restore current context from top and clear it in debug mode.
if (restore_context) {
li(t8, Operand(ExternalReference(Isolate::kContextAddress, isolate())));
ld(cp, MemOperand(t8));
}
#ifdef DEBUG
li(t8, Operand(ExternalReference(Isolate::kContextAddress, isolate())));
sd(a3, MemOperand(t8));
#endif
// Pop the arguments, restore registers, and return.
mov(sp, fp); // Respect ABI stack constraint.
ld(fp, MemOperand(sp, ExitFrameConstants::kCallerFPOffset));
ld(ra, MemOperand(sp, ExitFrameConstants::kCallerPCOffset));
if (argument_count.is_valid()) {
if (argument_count_is_length) {
daddu(sp, sp, argument_count);
} else {
dsll(t8, argument_count, kPointerSizeLog2);
daddu(sp, sp, t8);
}
}
if (do_return) {
Ret(USE_DELAY_SLOT);
// If returning, the instruction in the delay slot will be the addiu below.
}
daddiu(sp, sp, 2 * kPointerSize);
}
void MacroAssembler::InitializeNewString(Register string,
Register length,
Heap::RootListIndex map_index,
Register scratch1,
Register scratch2) {
// dsll(scratch1, length, kSmiTagSize);
dsll32(scratch1, length, 0);
LoadRoot(scratch2, map_index);
sd(scratch1, FieldMemOperand(string, String::kLengthOffset));
li(scratch1, Operand(String::kEmptyHashField));
sd(scratch2, FieldMemOperand(string, HeapObject::kMapOffset));
sd(scratch1, FieldMemOperand(string, String::kHashFieldOffset));
}
int MacroAssembler::ActivationFrameAlignment() {
#if V8_HOST_ARCH_MIPS || V8_HOST_ARCH_MIPS64
// Running on the real platform. Use the alignment as mandated by the local
// environment.
// Note: This will break if we ever start generating snapshots on one Mips
// platform for another Mips platform with a different alignment.
return base::OS::ActivationFrameAlignment();
#else // V8_HOST_ARCH_MIPS
// If we are using the simulator then we should always align to the expected
// alignment. As the simulator is used to generate snapshots we do not know
// if the target platform will need alignment, so this is controlled from a
// flag.
return FLAG_sim_stack_alignment;
#endif // V8_HOST_ARCH_MIPS
}
void MacroAssembler::AssertStackIsAligned() {
if (emit_debug_code()) {
const int frame_alignment = ActivationFrameAlignment();
const int frame_alignment_mask = frame_alignment - 1;
if (frame_alignment > kPointerSize) {
Label alignment_as_expected;
DCHECK(base::bits::IsPowerOfTwo32(frame_alignment));
andi(at, sp, frame_alignment_mask);
Branch(&alignment_as_expected, eq, at, Operand(zero_reg));
// Don't use Check here, as it will call Runtime_Abort re-entering here.
stop("Unexpected stack alignment");
bind(&alignment_as_expected);
}
}
}
void MacroAssembler::JumpIfNotPowerOfTwoOrZero(
Register reg,
Register scratch,
Label* not_power_of_two_or_zero) {
Dsubu(scratch, reg, Operand(1));
Branch(USE_DELAY_SLOT, not_power_of_two_or_zero, lt,
scratch, Operand(zero_reg));
and_(at, scratch, reg); // In the delay slot.
Branch(not_power_of_two_or_zero, ne, at, Operand(zero_reg));
}
void MacroAssembler::SmiTagCheckOverflow(Register reg, Register overflow) {
DCHECK(!reg.is(overflow));
mov(overflow, reg); // Save original value.
SmiTag(reg);
xor_(overflow, overflow, reg); // Overflow if (value ^ 2 * value) < 0.
}
void MacroAssembler::SmiTagCheckOverflow(Register dst,
Register src,
Register overflow) {
if (dst.is(src)) {
// Fall back to slower case.
SmiTagCheckOverflow(dst, overflow);
} else {
DCHECK(!dst.is(src));
DCHECK(!dst.is(overflow));
DCHECK(!src.is(overflow));
SmiTag(dst, src);
xor_(overflow, dst, src); // Overflow if (value ^ 2 * value) < 0.
}
}
void MacroAssembler::SmiLoadUntag(Register dst, MemOperand src) {
if (SmiValuesAre32Bits()) {
lw(dst, UntagSmiMemOperand(src.rm(), src.offset()));
} else {
lw(dst, src);
SmiUntag(dst);
}
}
void MacroAssembler::SmiLoadScale(Register dst, MemOperand src, int scale) {
if (SmiValuesAre32Bits()) {
// TODO(plind): not clear if lw or ld faster here, need micro-benchmark.
lw(dst, UntagSmiMemOperand(src.rm(), src.offset()));
dsll(dst, dst, scale);
} else {
lw(dst, src);
DCHECK(scale >= kSmiTagSize);
sll(dst, dst, scale - kSmiTagSize);
}
}
// Returns 2 values: the Smi and a scaled version of the int within the Smi.
void MacroAssembler::SmiLoadWithScale(Register d_smi,
Register d_scaled,
MemOperand src,
int scale) {
if (SmiValuesAre32Bits()) {
ld(d_smi, src);
dsra(d_scaled, d_smi, kSmiShift - scale);
} else {
lw(d_smi, src);
DCHECK(scale >= kSmiTagSize);
sll(d_scaled, d_smi, scale - kSmiTagSize);
}
}
// Returns 2 values: the untagged Smi (int32) and scaled version of that int.
void MacroAssembler::SmiLoadUntagWithScale(Register d_int,
Register d_scaled,
MemOperand src,
int scale) {
if (SmiValuesAre32Bits()) {
lw(d_int, UntagSmiMemOperand(src.rm(), src.offset()));
dsll(d_scaled, d_int, scale);
} else {
lw(d_int, src);
// Need both the int and the scaled in, so use two instructions.
SmiUntag(d_int);
sll(d_scaled, d_int, scale);
}
}
void MacroAssembler::UntagAndJumpIfSmi(Register dst,
Register src,
Label* smi_case) {
// DCHECK(!dst.is(src));
JumpIfSmi(src, smi_case, at, USE_DELAY_SLOT);
SmiUntag(dst, src);
}
void MacroAssembler::UntagAndJumpIfNotSmi(Register dst,
Register src,
Label* non_smi_case) {
// DCHECK(!dst.is(src));
JumpIfNotSmi(src, non_smi_case, at, USE_DELAY_SLOT);
SmiUntag(dst, src);
}
void MacroAssembler::JumpIfSmi(Register value,
Label* smi_label,
Register scratch,
BranchDelaySlot bd) {
DCHECK_EQ(0, kSmiTag);
andi(scratch, value, kSmiTagMask);
Branch(bd, smi_label, eq, scratch, Operand(zero_reg));
}
void MacroAssembler::JumpIfNotSmi(Register value,
Label* not_smi_label,
Register scratch,
BranchDelaySlot bd) {
DCHECK_EQ(0, kSmiTag);
andi(scratch, value, kSmiTagMask);
Branch(bd, not_smi_label, ne, scratch, Operand(zero_reg));
}
void MacroAssembler::JumpIfNotBothSmi(Register reg1,
Register reg2,
Label* on_not_both_smi) {
STATIC_ASSERT(kSmiTag == 0);
// TODO(plind): Find some better to fix this assert issue.
#if defined(__APPLE__)
DCHECK_EQ(1, kSmiTagMask);
#else
DCHECK_EQ((int64_t)1, kSmiTagMask);
#endif
or_(at, reg1, reg2);
JumpIfNotSmi(at, on_not_both_smi);
}
void MacroAssembler::JumpIfEitherSmi(Register reg1,
Register reg2,
Label* on_either_smi) {
STATIC_ASSERT(kSmiTag == 0);
// TODO(plind): Find some better to fix this assert issue.
#if defined(__APPLE__)
DCHECK_EQ(1, kSmiTagMask);
#else
DCHECK_EQ((int64_t)1, kSmiTagMask);
#endif
// Both Smi tags must be 1 (not Smi).
and_(at, reg1, reg2);
JumpIfSmi(at, on_either_smi);
}
void MacroAssembler::AssertNotSmi(Register object) {
if (emit_debug_code()) {
STATIC_ASSERT(kSmiTag == 0);
andi(at, object, kSmiTagMask);
Check(ne, kOperandIsASmi, at, Operand(zero_reg));
}
}
void MacroAssembler::AssertSmi(Register object) {
if (emit_debug_code()) {
STATIC_ASSERT(kSmiTag == 0);
andi(at, object, kSmiTagMask);
Check(eq, kOperandIsASmi, at, Operand(zero_reg));
}
}
void MacroAssembler::AssertString(Register object) {
if (emit_debug_code()) {
STATIC_ASSERT(kSmiTag == 0);
SmiTst(object, a4);
Check(ne, kOperandIsASmiAndNotAString, a4, Operand(zero_reg));
push(object);
ld(object, FieldMemOperand(object, HeapObject::kMapOffset));
lbu(object, FieldMemOperand(object, Map::kInstanceTypeOffset));
Check(lo, kOperandIsNotAString, object, Operand(FIRST_NONSTRING_TYPE));
pop(object);
}
}
void MacroAssembler::AssertName(Register object) {
if (emit_debug_code()) {
STATIC_ASSERT(kSmiTag == 0);
SmiTst(object, a4);
Check(ne, kOperandIsASmiAndNotAName, a4, Operand(zero_reg));
push(object);
ld(object, FieldMemOperand(object, HeapObject::kMapOffset));
lbu(object, FieldMemOperand(object, Map::kInstanceTypeOffset));
Check(le, kOperandIsNotAName, object, Operand(LAST_NAME_TYPE));
pop(object);
}
}
void MacroAssembler::AssertUndefinedOrAllocationSite(Register object,
Register scratch) {
if (emit_debug_code()) {
Label done_checking;
AssertNotSmi(object);
LoadRoot(scratch, Heap::kUndefinedValueRootIndex);
Branch(&done_checking, eq, object, Operand(scratch));
push(object);
ld(object, FieldMemOperand(object, HeapObject::kMapOffset));
LoadRoot(scratch, Heap::kAllocationSiteMapRootIndex);
Assert(eq, kExpectedUndefinedOrCell, object, Operand(scratch));
pop(object);
bind(&done_checking);
}
}
void MacroAssembler::AssertIsRoot(Register reg, Heap::RootListIndex index) {
if (emit_debug_code()) {
DCHECK(!reg.is(at));
LoadRoot(at, index);
Check(eq, kHeapNumberMapRegisterClobbered, reg, Operand(at));
}
}
void MacroAssembler::JumpIfNotHeapNumber(Register object,
Register heap_number_map,
Register scratch,
Label* on_not_heap_number) {
ld(scratch, FieldMemOperand(object, HeapObject::kMapOffset));
AssertIsRoot(heap_number_map, Heap::kHeapNumberMapRootIndex);
Branch(on_not_heap_number, ne, scratch, Operand(heap_number_map));
}
void MacroAssembler::LookupNumberStringCache(Register object,
Register result,
Register scratch1,
Register scratch2,
Register scratch3,
Label* not_found) {
// Use of registers. Register result is used as a temporary.
Register number_string_cache = result;
Register mask = scratch3;
// Load the number string cache.
LoadRoot(number_string_cache, Heap::kNumberStringCacheRootIndex);
// Make the hash mask from the length of the number string cache. It
// contains two elements (number and string) for each cache entry.
ld(mask, FieldMemOperand(number_string_cache, FixedArray::kLengthOffset));
// Divide length by two (length is a smi).
// dsra(mask, mask, kSmiTagSize + 1);
dsra32(mask, mask, 1);
Daddu(mask, mask, -1); // Make mask.
// Calculate the entry in the number string cache. The hash value in the
// number string cache for smis is just the smi value, and the hash for
// doubles is the xor of the upper and lower words. See
// Heap::GetNumberStringCache.
Label is_smi;
Label load_result_from_cache;
JumpIfSmi(object, &is_smi);
CheckMap(object,
scratch1,
Heap::kHeapNumberMapRootIndex,
not_found,
DONT_DO_SMI_CHECK);
STATIC_ASSERT(8 == kDoubleSize);
Daddu(scratch1,
object,
Operand(HeapNumber::kValueOffset - kHeapObjectTag));
ld(scratch2, MemOperand(scratch1, kPointerSize));
ld(scratch1, MemOperand(scratch1, 0));
Xor(scratch1, scratch1, Operand(scratch2));
And(scratch1, scratch1, Operand(mask));
// Calculate address of entry in string cache: each entry consists
// of two pointer sized fields.
dsll(scratch1, scratch1, kPointerSizeLog2 + 1);
Daddu(scratch1, number_string_cache, scratch1);
Register probe = mask;
ld(probe, FieldMemOperand(scratch1, FixedArray::kHeaderSize));
JumpIfSmi(probe, not_found);
ldc1(f12, FieldMemOperand(object, HeapNumber::kValueOffset));
ldc1(f14, FieldMemOperand(probe, HeapNumber::kValueOffset));
BranchF(&load_result_from_cache, NULL, eq, f12, f14);
Branch(not_found);
bind(&is_smi);
Register scratch = scratch1;
// dsra(scratch, object, 1); // Shift away the tag.
dsra32(scratch, scratch, 0);
And(scratch, mask, Operand(scratch));
// Calculate address of entry in string cache: each entry consists
// of two pointer sized fields.
dsll(scratch, scratch, kPointerSizeLog2 + 1);
Daddu(scratch, number_string_cache, scratch);
// Check if the entry is the smi we are looking for.
ld(probe, FieldMemOperand(scratch, FixedArray::kHeaderSize));
Branch(not_found, ne, object, Operand(probe));
// Get the result from the cache.
bind(&load_result_from_cache);
ld(result, FieldMemOperand(scratch, FixedArray::kHeaderSize + kPointerSize));
IncrementCounter(isolate()->counters()->number_to_string_native(),
1,
scratch1,
scratch2);
}
void MacroAssembler::JumpIfNonSmisNotBothSequentialOneByteStrings(
Register first, Register second, Register scratch1, Register scratch2,
Label* failure) {
// Test that both first and second are sequential one-byte strings.
// Assume that they are non-smis.
ld(scratch1, FieldMemOperand(first, HeapObject::kMapOffset));
ld(scratch2, FieldMemOperand(second, HeapObject::kMapOffset));
lbu(scratch1, FieldMemOperand(scratch1, Map::kInstanceTypeOffset));
lbu(scratch2, FieldMemOperand(scratch2, Map::kInstanceTypeOffset));
JumpIfBothInstanceTypesAreNotSequentialOneByte(scratch1, scratch2, scratch1,
scratch2, failure);
}
void MacroAssembler::JumpIfNotBothSequentialOneByteStrings(Register first,
Register second,
Register scratch1,
Register scratch2,
Label* failure) {
// Check that neither is a smi.
STATIC_ASSERT(kSmiTag == 0);
And(scratch1, first, Operand(second));
JumpIfSmi(scratch1, failure);
JumpIfNonSmisNotBothSequentialOneByteStrings(first, second, scratch1,
scratch2, failure);
}
void MacroAssembler::JumpIfBothInstanceTypesAreNotSequentialOneByte(
Register first, Register second, Register scratch1, Register scratch2,
Label* failure) {
const int kFlatOneByteStringMask =
kIsNotStringMask | kStringEncodingMask | kStringRepresentationMask;
const int kFlatOneByteStringTag =
kStringTag | kOneByteStringTag | kSeqStringTag;
DCHECK(kFlatOneByteStringTag <= 0xffff); // Ensure this fits 16-bit immed.
andi(scratch1, first, kFlatOneByteStringMask);
Branch(failure, ne, scratch1, Operand(kFlatOneByteStringTag));
andi(scratch2, second, kFlatOneByteStringMask);
Branch(failure, ne, scratch2, Operand(kFlatOneByteStringTag));
}
void MacroAssembler::JumpIfInstanceTypeIsNotSequentialOneByte(Register type,
Register scratch,
Label* failure) {
const int kFlatOneByteStringMask =
kIsNotStringMask | kStringEncodingMask | kStringRepresentationMask;
const int kFlatOneByteStringTag =
kStringTag | kOneByteStringTag | kSeqStringTag;
And(scratch, type, Operand(kFlatOneByteStringMask));
Branch(failure, ne, scratch, Operand(kFlatOneByteStringTag));
}
static const int kRegisterPassedArguments = (kMipsAbi == kN64) ? 8 : 4;
int MacroAssembler::CalculateStackPassedWords(int num_reg_arguments,
int num_double_arguments) {
int stack_passed_words = 0;
num_reg_arguments += 2 * num_double_arguments;
// O32: Up to four simple arguments are passed in registers a0..a3.
// N64: Up to eight simple arguments are passed in registers a0..a7.
if (num_reg_arguments > kRegisterPassedArguments) {
stack_passed_words += num_reg_arguments - kRegisterPassedArguments;
}
stack_passed_words += kCArgSlotCount;
return stack_passed_words;
}
void MacroAssembler::EmitSeqStringSetCharCheck(Register string,
Register index,
Register value,
Register scratch,
uint32_t encoding_mask) {
Label is_object;
SmiTst(string, at);
Check(ne, kNonObject, at, Operand(zero_reg));
ld(at, FieldMemOperand(string, HeapObject::kMapOffset));
lbu(at, FieldMemOperand(at, Map::kInstanceTypeOffset));
andi(at, at, kStringRepresentationMask | kStringEncodingMask);
li(scratch, Operand(encoding_mask));
Check(eq, kUnexpectedStringType, at, Operand(scratch));
// TODO(plind): requires Smi size check code for mips32.
ld(at, FieldMemOperand(string, String::kLengthOffset));
Check(lt, kIndexIsTooLarge, index, Operand(at));
DCHECK(Smi::FromInt(0) == 0);
Check(ge, kIndexIsNegative, index, Operand(zero_reg));
}
void MacroAssembler::PrepareCallCFunction(int num_reg_arguments,
int num_double_arguments,
Register scratch) {
int frame_alignment = ActivationFrameAlignment();
// n64: Up to eight simple arguments in a0..a3, a4..a7, No argument slots.
// O32: Up to four simple arguments are passed in registers a0..a3.
// Those four arguments must have reserved argument slots on the stack for
// mips, even though those argument slots are not normally used.
// Both ABIs: Remaining arguments are pushed on the stack, above (higher
// address than) the (O32) argument slots. (arg slot calculation handled by
// CalculateStackPassedWords()).
int stack_passed_arguments = CalculateStackPassedWords(
num_reg_arguments, num_double_arguments);
if (frame_alignment > kPointerSize) {
// Make stack end at alignment and make room for num_arguments - 4 words
// and the original value of sp.
mov(scratch, sp);
Dsubu(sp, sp, Operand((stack_passed_arguments + 1) * kPointerSize));
DCHECK(base::bits::IsPowerOfTwo32(frame_alignment));
And(sp, sp, Operand(-frame_alignment));
sd(scratch, MemOperand(sp, stack_passed_arguments * kPointerSize));
} else {
Dsubu(sp, sp, Operand(stack_passed_arguments * kPointerSize));
}
}
void MacroAssembler::PrepareCallCFunction(int num_reg_arguments,
Register scratch) {
PrepareCallCFunction(num_reg_arguments, 0, scratch);
}
void MacroAssembler::CallCFunction(ExternalReference function,
int num_reg_arguments,
int num_double_arguments) {
li(t8, Operand(function));
CallCFunctionHelper(t8, num_reg_arguments, num_double_arguments);
}
void MacroAssembler::CallCFunction(Register function,
int num_reg_arguments,
int num_double_arguments) {
CallCFunctionHelper(function, num_reg_arguments, num_double_arguments);
}
void MacroAssembler::CallCFunction(ExternalReference function,
int num_arguments) {
CallCFunction(function, num_arguments, 0);
}
void MacroAssembler::CallCFunction(Register function,
int num_arguments) {
CallCFunction(function, num_arguments, 0);
}
void MacroAssembler::CallCFunctionHelper(Register function,
int num_reg_arguments,
int num_double_arguments) {
DCHECK(has_frame());
// Make sure that the stack is aligned before calling a C function unless
// running in the simulator. The simulator has its own alignment check which
// provides more information.
// The argument stots are presumed to have been set up by
// PrepareCallCFunction. The C function must be called via t9, for mips ABI.
#if V8_HOST_ARCH_MIPS || V8_HOST_ARCH_MIPS64
if (emit_debug_code()) {
int frame_alignment = base::OS::ActivationFrameAlignment();
int frame_alignment_mask = frame_alignment - 1;
if (frame_alignment > kPointerSize) {
DCHECK(base::bits::IsPowerOfTwo32(frame_alignment));
Label alignment_as_expected;
And(at, sp, Operand(frame_alignment_mask));
Branch(&alignment_as_expected, eq, at, Operand(zero_reg));
// Don't use Check here, as it will call Runtime_Abort possibly
// re-entering here.
stop("Unexpected alignment in CallCFunction");
bind(&alignment_as_expected);
}
}
#endif // V8_HOST_ARCH_MIPS
// Just call directly. The function called cannot cause a GC, or
// allow preemption, so the return address in the link register
// stays correct.
if (!function.is(t9)) {
mov(t9, function);
function = t9;
}
Call(function);
int stack_passed_arguments = CalculateStackPassedWords(
num_reg_arguments, num_double_arguments);
if (base::OS::ActivationFrameAlignment() > kPointerSize) {
ld(sp, MemOperand(sp, stack_passed_arguments * kPointerSize));
} else {
Daddu(sp, sp, Operand(stack_passed_arguments * kPointerSize));
}
}
#undef BRANCH_ARGS_CHECK
void MacroAssembler::PatchRelocatedValue(Register li_location,
Register scratch,
Register new_value) {
lwu(scratch, MemOperand(li_location));
// At this point scratch is a lui(at, ...) instruction.
if (emit_debug_code()) {
And(scratch, scratch, kOpcodeMask);
Check(eq, kTheInstructionToPatchShouldBeALui,
scratch, Operand(LUI));
lwu(scratch, MemOperand(li_location));
}
dsrl32(t9, new_value, 0);
Ins(scratch, t9, 0, kImm16Bits);
sw(scratch, MemOperand(li_location));
lwu(scratch, MemOperand(li_location, kInstrSize));
// scratch is now ori(at, ...).
if (emit_debug_code()) {
And(scratch, scratch, kOpcodeMask);
Check(eq, kTheInstructionToPatchShouldBeAnOri,
scratch, Operand(ORI));
lwu(scratch, MemOperand(li_location, kInstrSize));
}
dsrl(t9, new_value, kImm16Bits);
Ins(scratch, t9, 0, kImm16Bits);
sw(scratch, MemOperand(li_location, kInstrSize));
lwu(scratch, MemOperand(li_location, kInstrSize * 3));
// scratch is now ori(at, ...).
if (emit_debug_code()) {
And(scratch, scratch, kOpcodeMask);
Check(eq, kTheInstructionToPatchShouldBeAnOri,
scratch, Operand(ORI));
lwu(scratch, MemOperand(li_location, kInstrSize * 3));
}
Ins(scratch, new_value, 0, kImm16Bits);
sw(scratch, MemOperand(li_location, kInstrSize * 3));
// Update the I-cache so the new lui and ori can be executed.
FlushICache(li_location, 4);
}
void MacroAssembler::GetRelocatedValue(Register li_location,
Register value,
Register scratch) {
lwu(value, MemOperand(li_location));
if (emit_debug_code()) {
And(value, value, kOpcodeMask);
Check(eq, kTheInstructionShouldBeALui,
value, Operand(LUI));
lwu(value, MemOperand(li_location));
}
// value now holds a lui instruction. Extract the immediate.
andi(value, value, kImm16Mask);
dsll32(value, value, kImm16Bits);
lwu(scratch, MemOperand(li_location, kInstrSize));
if (emit_debug_code()) {
And(scratch, scratch, kOpcodeMask);
Check(eq, kTheInstructionShouldBeAnOri,
scratch, Operand(ORI));
lwu(scratch, MemOperand(li_location, kInstrSize));
}
// "scratch" now holds an ori instruction. Extract the immediate.
andi(scratch, scratch, kImm16Mask);
dsll32(scratch, scratch, 0);
or_(value, value, scratch);
lwu(scratch, MemOperand(li_location, kInstrSize * 3));
if (emit_debug_code()) {
And(scratch, scratch, kOpcodeMask);
Check(eq, kTheInstructionShouldBeAnOri,
scratch, Operand(ORI));
lwu(scratch, MemOperand(li_location, kInstrSize * 3));
}
// "scratch" now holds an ori instruction. Extract the immediate.
andi(scratch, scratch, kImm16Mask);
dsll(scratch, scratch, kImm16Bits);
or_(value, value, scratch);
// Sign extend extracted address.
dsra(value, value, kImm16Bits);
}
void MacroAssembler::CheckPageFlag(
Register object,
Register scratch,
int mask,
Condition cc,
Label* condition_met) {
And(scratch, object, Operand(~Page::kPageAlignmentMask));
ld(scratch, MemOperand(scratch, MemoryChunk::kFlagsOffset));
And(scratch, scratch, Operand(mask));
Branch(condition_met, cc, scratch, Operand(zero_reg));
}
void MacroAssembler::JumpIfBlack(Register object,
Register scratch0,
Register scratch1,
Label* on_black) {
HasColor(object, scratch0, scratch1, on_black, 1, 0); // kBlackBitPattern.
DCHECK(strcmp(Marking::kBlackBitPattern, "10") == 0);
}
void MacroAssembler::HasColor(Register object,
Register bitmap_scratch,
Register mask_scratch,
Label* has_color,
int first_bit,
int second_bit) {
DCHECK(!AreAliased(object, bitmap_scratch, mask_scratch, t8));
DCHECK(!AreAliased(object, bitmap_scratch, mask_scratch, t9));
GetMarkBits(object, bitmap_scratch, mask_scratch);
Label other_color;
// Note that we are using a 4-byte aligned 8-byte load.
Uld(t9, MemOperand(bitmap_scratch, MemoryChunk::kHeaderSize));
And(t8, t9, Operand(mask_scratch));
Branch(&other_color, first_bit == 1 ? eq : ne, t8, Operand(zero_reg));
// Shift left 1 by adding.
Daddu(mask_scratch, mask_scratch, Operand(mask_scratch));
And(t8, t9, Operand(mask_scratch));
Branch(has_color, second_bit == 1 ? ne : eq, t8, Operand(zero_reg));
bind(&other_color);
}
// Detect some, but not all, common pointer-free objects. This is used by the
// incremental write barrier which doesn't care about oddballs (they are always
// marked black immediately so this code is not hit).
void MacroAssembler::JumpIfDataObject(Register value,
Register scratch,
Label* not_data_object) {
DCHECK(!AreAliased(value, scratch, t8, no_reg));
Label is_data_object;
ld(scratch, FieldMemOperand(value, HeapObject::kMapOffset));
LoadRoot(t8, Heap::kHeapNumberMapRootIndex);
Branch(&is_data_object, eq, t8, Operand(scratch));
DCHECK(kIsIndirectStringTag == 1 && kIsIndirectStringMask == 1);
DCHECK(kNotStringTag == 0x80 && kIsNotStringMask == 0x80);
// If it's a string and it's not a cons string then it's an object containing
// no GC pointers.
lbu(scratch, FieldMemOperand(scratch, Map::kInstanceTypeOffset));
And(t8, scratch, Operand(kIsIndirectStringMask | kIsNotStringMask));
Branch(not_data_object, ne, t8, Operand(zero_reg));
bind(&is_data_object);
}
void MacroAssembler::GetMarkBits(Register addr_reg,
Register bitmap_reg,
Register mask_reg) {
DCHECK(!AreAliased(addr_reg, bitmap_reg, mask_reg, no_reg));
// addr_reg is divided into fields:
// |63 page base 20|19 high 8|7 shift 3|2 0|
// 'high' gives the index of the cell holding color bits for the object.
// 'shift' gives the offset in the cell for this object's color.
And(bitmap_reg, addr_reg, Operand(~Page::kPageAlignmentMask));
Ext(mask_reg, addr_reg, kPointerSizeLog2, Bitmap::kBitsPerCellLog2);
const int kLowBits = kPointerSizeLog2 + Bitmap::kBitsPerCellLog2;
Ext(t8, addr_reg, kLowBits, kPageSizeBits - kLowBits);
dsll(t8, t8, Bitmap::kBytesPerCellLog2);
Daddu(bitmap_reg, bitmap_reg, t8);
li(t8, Operand(1));
dsllv(mask_reg, t8, mask_reg);
}
void MacroAssembler::EnsureNotWhite(
Register value,
Register bitmap_scratch,
Register mask_scratch,
Register load_scratch,
Label* value_is_white_and_not_data) {
DCHECK(!AreAliased(value, bitmap_scratch, mask_scratch, t8));
GetMarkBits(value, bitmap_scratch, mask_scratch);
// If the value is black or grey we don't need to do anything.
DCHECK(strcmp(Marking::kWhiteBitPattern, "00") == 0);
DCHECK(strcmp(Marking::kBlackBitPattern, "10") == 0);
DCHECK(strcmp(Marking::kGreyBitPattern, "11") == 0);
DCHECK(strcmp(Marking::kImpossibleBitPattern, "01") == 0);
Label done;
// Since both black and grey have a 1 in the first position and white does
// not have a 1 there we only need to check one bit.
// Note that we are using a 4-byte aligned 8-byte load.
Uld(load_scratch, MemOperand(bitmap_scratch, MemoryChunk::kHeaderSize));
And(t8, mask_scratch, load_scratch);
Branch(&done, ne, t8, Operand(zero_reg));
if (emit_debug_code()) {
// Check for impossible bit pattern.
Label ok;
// sll may overflow, making the check conservative.
dsll(t8, mask_scratch, 1);
And(t8, load_scratch, t8);
Branch(&ok, eq, t8, Operand(zero_reg));
stop("Impossible marking bit pattern");
bind(&ok);
}
// Value is white. We check whether it is data that doesn't need scanning.
// Currently only checks for HeapNumber and non-cons strings.
Register map = load_scratch; // Holds map while checking type.
Register length = load_scratch; // Holds length of object after testing type.
Label is_data_object;
// Check for heap-number
ld(map, FieldMemOperand(value, HeapObject::kMapOffset));
LoadRoot(t8, Heap::kHeapNumberMapRootIndex);
{
Label skip;
Branch(&skip, ne, t8, Operand(map));
li(length, HeapNumber::kSize);
Branch(&is_data_object);
bind(&skip);
}
// Check for strings.
DCHECK(kIsIndirectStringTag == 1 && kIsIndirectStringMask == 1);
DCHECK(kNotStringTag == 0x80 && kIsNotStringMask == 0x80);
// If it's a string and it's not a cons string then it's an object containing
// no GC pointers.
Register instance_type = load_scratch;
lbu(instance_type, FieldMemOperand(map, Map::kInstanceTypeOffset));
And(t8, instance_type, Operand(kIsIndirectStringMask | kIsNotStringMask));
Branch(value_is_white_and_not_data, ne, t8, Operand(zero_reg));
// It's a non-indirect (non-cons and non-slice) string.
// If it's external, the length is just ExternalString::kSize.
// Otherwise it's String::kHeaderSize + string->length() * (1 or 2).
// External strings are the only ones with the kExternalStringTag bit
// set.
DCHECK_EQ(0, kSeqStringTag & kExternalStringTag);
DCHECK_EQ(0, kConsStringTag & kExternalStringTag);
And(t8, instance_type, Operand(kExternalStringTag));
{
Label skip;
Branch(&skip, eq, t8, Operand(zero_reg));
li(length, ExternalString::kSize);
Branch(&is_data_object);
bind(&skip);
}
// Sequential string, either Latin1 or UC16.
// For Latin1 (char-size of 1) we shift the smi tag away to get the length.
// For UC16 (char-size of 2) we just leave the smi tag in place, thereby
// getting the length multiplied by 2.
DCHECK(kOneByteStringTag == 4 && kStringEncodingMask == 4);
DCHECK(kSmiTag == 0 && kSmiTagSize == 1);
lw(t9, UntagSmiFieldMemOperand(value, String::kLengthOffset));
And(t8, instance_type, Operand(kStringEncodingMask));
{
Label skip;
Branch(&skip, ne, t8, Operand(zero_reg));
// Adjust length for UC16.
dsll(t9, t9, 1);
bind(&skip);
}
Daddu(length, t9, Operand(SeqString::kHeaderSize + kObjectAlignmentMask));
DCHECK(!length.is(t8));
And(length, length, Operand(~kObjectAlignmentMask));
bind(&is_data_object);
// Value is a data object, and it is white. Mark it black. Since we know
// that the object is white we can make it black by flipping one bit.
Uld(t8, MemOperand(bitmap_scratch, MemoryChunk::kHeaderSize));
Or(t8, t8, Operand(mask_scratch));
Usd(t8, MemOperand(bitmap_scratch, MemoryChunk::kHeaderSize));
And(bitmap_scratch, bitmap_scratch, Operand(~Page::kPageAlignmentMask));
Uld(t8, MemOperand(bitmap_scratch, MemoryChunk::kLiveBytesOffset));
Daddu(t8, t8, Operand(length));
Usd(t8, MemOperand(bitmap_scratch, MemoryChunk::kLiveBytesOffset));
bind(&done);
}
void MacroAssembler::LoadInstanceDescriptors(Register map,
Register descriptors) {
ld(descriptors, FieldMemOperand(map, Map::kDescriptorsOffset));
}
void MacroAssembler::NumberOfOwnDescriptors(Register dst, Register map) {
ld(dst, FieldMemOperand(map, Map::kBitField3Offset));
DecodeField<Map::NumberOfOwnDescriptorsBits>(dst);
}
void MacroAssembler::EnumLength(Register dst, Register map) {
STATIC_ASSERT(Map::EnumLengthBits::kShift == 0);
ld(dst, FieldMemOperand(map, Map::kBitField3Offset));
And(dst, dst, Operand(Map::EnumLengthBits::kMask));
SmiTag(dst);
}
void MacroAssembler::LoadAccessor(Register dst, Register holder,
int accessor_index,
AccessorComponent accessor) {
ld(dst, FieldMemOperand(holder, HeapObject::kMapOffset));
LoadInstanceDescriptors(dst, dst);
ld(dst,
FieldMemOperand(dst, DescriptorArray::GetValueOffset(accessor_index)));
int offset = accessor == ACCESSOR_GETTER ? AccessorPair::kGetterOffset
: AccessorPair::kSetterOffset;
ld(dst, FieldMemOperand(dst, offset));
}
void MacroAssembler::CheckEnumCache(Register null_value, Label* call_runtime) {
Register empty_fixed_array_value = a6;
LoadRoot(empty_fixed_array_value, Heap::kEmptyFixedArrayRootIndex);
Label next, start;
mov(a2, a0);
// Check if the enum length field is properly initialized, indicating that
// there is an enum cache.
ld(a1, FieldMemOperand(a2, HeapObject::kMapOffset));
EnumLength(a3, a1);
Branch(
call_runtime, eq, a3, Operand(Smi::FromInt(kInvalidEnumCacheSentinel)));
jmp(&start);
bind(&next);
ld(a1, FieldMemOperand(a2, HeapObject::kMapOffset));
// For all objects but the receiver, check that the cache is empty.
EnumLength(a3, a1);
Branch(call_runtime, ne, a3, Operand(Smi::FromInt(0)));
bind(&start);
// Check that there are no elements. Register a2 contains the current JS
// object we've reached through the prototype chain.
Label no_elements;
ld(a2, FieldMemOperand(a2, JSObject::kElementsOffset));
Branch(&no_elements, eq, a2, Operand(empty_fixed_array_value));
// Second chance, the object may be using the empty slow element dictionary.
LoadRoot(at, Heap::kEmptySlowElementDictionaryRootIndex);
Branch(call_runtime, ne, a2, Operand(at));
bind(&no_elements);
ld(a2, FieldMemOperand(a1, Map::kPrototypeOffset));
Branch(&next, ne, a2, Operand(null_value));
}
void MacroAssembler::ClampUint8(Register output_reg, Register input_reg) {
DCHECK(!output_reg.is(input_reg));
Label done;
li(output_reg, Operand(255));
// Normal branch: nop in delay slot.
Branch(&done, gt, input_reg, Operand(output_reg));
// Use delay slot in this branch.
Branch(USE_DELAY_SLOT, &done, lt, input_reg, Operand(zero_reg));
mov(output_reg, zero_reg); // In delay slot.
mov(output_reg, input_reg); // Value is in range 0..255.
bind(&done);
}
void MacroAssembler::ClampDoubleToUint8(Register result_reg,
DoubleRegister input_reg,
DoubleRegister temp_double_reg) {
Label above_zero;
Label done;
Label in_bounds;
Move(temp_double_reg, 0.0);
BranchF(&above_zero, NULL, gt, input_reg, temp_double_reg);
// Double value is less than zero, NaN or Inf, return 0.
mov(result_reg, zero_reg);
Branch(&done);
// Double value is >= 255, return 255.
bind(&above_zero);
Move(temp_double_reg, 255.0);
BranchF(&in_bounds, NULL, le, input_reg, temp_double_reg);
li(result_reg, Operand(255));
Branch(&done);
// In 0-255 range, round and truncate.
bind(&in_bounds);
cvt_w_d(temp_double_reg, input_reg);
mfc1(result_reg, temp_double_reg);
bind(&done);
}
void MacroAssembler::TestJSArrayForAllocationMemento(
Register receiver_reg,
Register scratch_reg,
Label* no_memento_found,
Condition cond,
Label* allocation_memento_present) {
ExternalReference new_space_start =
ExternalReference::new_space_start(isolate());
ExternalReference new_space_allocation_top =
ExternalReference::new_space_allocation_top_address(isolate());
Daddu(scratch_reg, receiver_reg,
Operand(JSArray::kSize + AllocationMemento::kSize - kHeapObjectTag));
Branch(no_memento_found, lt, scratch_reg, Operand(new_space_start));
li(at, Operand(new_space_allocation_top));
ld(at, MemOperand(at));
Branch(no_memento_found, gt, scratch_reg, Operand(at));
ld(scratch_reg, MemOperand(scratch_reg, -AllocationMemento::kSize));
if (allocation_memento_present) {
Branch(allocation_memento_present, cond, scratch_reg,
Operand(isolate()->factory()->allocation_memento_map()));
}
}
Register GetRegisterThatIsNotOneOf(Register reg1,
Register reg2,
Register reg3,
Register reg4,
Register reg5,
Register reg6) {
RegList regs = 0;
if (reg1.is_valid()) regs |= reg1.bit();
if (reg2.is_valid()) regs |= reg2.bit();
if (reg3.is_valid()) regs |= reg3.bit();
if (reg4.is_valid()) regs |= reg4.bit();
if (reg5.is_valid()) regs |= reg5.bit();
if (reg6.is_valid()) regs |= reg6.bit();
for (int i = 0; i < Register::NumAllocatableRegisters(); i++) {
Register candidate = Register::FromAllocationIndex(i);
if (regs & candidate.bit()) continue;
return candidate;
}
UNREACHABLE();
return no_reg;
}
void MacroAssembler::JumpIfDictionaryInPrototypeChain(
Register object,
Register scratch0,
Register scratch1,
Label* found) {
DCHECK(!scratch1.is(scratch0));
Factory* factory = isolate()->factory();
Register current = scratch0;
Label loop_again;
// Scratch contained elements pointer.
Move(current, object);
// Loop based on the map going up the prototype chain.
bind(&loop_again);
ld(current, FieldMemOperand(current, HeapObject::kMapOffset));
lb(scratch1, FieldMemOperand(current, Map::kBitField2Offset));
DecodeField<Map::ElementsKindBits>(scratch1);
Branch(found, eq, scratch1, Operand(DICTIONARY_ELEMENTS));
ld(current, FieldMemOperand(current, Map::kPrototypeOffset));
Branch(&loop_again, ne, current, Operand(factory->null_value()));
}
bool AreAliased(Register reg1,
Register reg2,
Register reg3,
Register reg4,
Register reg5,
Register reg6,
Register reg7,
Register reg8) {
int n_of_valid_regs = reg1.is_valid() + reg2.is_valid() +
reg3.is_valid() + reg4.is_valid() + reg5.is_valid() + reg6.is_valid() +
reg7.is_valid() + reg8.is_valid();
RegList regs = 0;
if (reg1.is_valid()) regs |= reg1.bit();
if (reg2.is_valid()) regs |= reg2.bit();
if (reg3.is_valid()) regs |= reg3.bit();
if (reg4.is_valid()) regs |= reg4.bit();
if (reg5.is_valid()) regs |= reg5.bit();
if (reg6.is_valid()) regs |= reg6.bit();
if (reg7.is_valid()) regs |= reg7.bit();
if (reg8.is_valid()) regs |= reg8.bit();
int n_of_non_aliasing_regs = NumRegs(regs);
return n_of_valid_regs != n_of_non_aliasing_regs;
}
CodePatcher::CodePatcher(byte* address,
int instructions,
FlushICache flush_cache)
: address_(address),
size_(instructions * Assembler::kInstrSize),
masm_(NULL, address, size_ + Assembler::kGap),
flush_cache_(flush_cache) {
// Create a new macro assembler pointing to the address of the code to patch.
// The size is adjusted with kGap on order for the assembler to generate size
// bytes of instructions without failing with buffer size constraints.
DCHECK(masm_.reloc_info_writer.pos() == address_ + size_ + Assembler::kGap);
}
CodePatcher::~CodePatcher() {
// Indicate that code has changed.
if (flush_cache_ == FLUSH) {
CpuFeatures::FlushICache(address_, size_);
}
// Check that the code was patched as expected.
DCHECK(masm_.pc_ == address_ + size_);
DCHECK(masm_.reloc_info_writer.pos() == address_ + size_ + Assembler::kGap);
}
void CodePatcher::Emit(Instr instr) {
masm()->emit(instr);
}
void CodePatcher::Emit(Address addr) {
// masm()->emit(reinterpret_cast<Instr>(addr));
}
void CodePatcher::ChangeBranchCondition(Condition cond) {
Instr instr = Assembler::instr_at(masm_.pc_);
DCHECK(Assembler::IsBranch(instr));
uint32_t opcode = Assembler::GetOpcodeField(instr);
// Currently only the 'eq' and 'ne' cond values are supported and the simple
// branch instructions (with opcode being the branch type).
// There are some special cases (see Assembler::IsBranch()) so extending this
// would be tricky.
DCHECK(opcode == BEQ ||
opcode == BNE ||
opcode == BLEZ ||
opcode == BGTZ ||
opcode == BEQL ||
opcode == BNEL ||
opcode == BLEZL ||
opcode == BGTZL);
opcode = (cond == eq) ? BEQ : BNE;
instr = (instr & ~kOpcodeMask) | opcode;
masm_.emit(instr);
}
void MacroAssembler::TruncatingDiv(Register result,
Register dividend,
int32_t divisor) {
DCHECK(!dividend.is(result));
DCHECK(!dividend.is(at));
DCHECK(!result.is(at));
base::MagicNumbersForDivision<uint32_t> mag =
base::SignedDivisionByConstant(static_cast<uint32_t>(divisor));
li(at, Operand(static_cast<int32_t>(mag.multiplier)));
Mulh(result, dividend, Operand(at));
bool neg = (mag.multiplier & (static_cast<uint32_t>(1) << 31)) != 0;
if (divisor > 0 && neg) {
Addu(result, result, Operand(dividend));
}
if (divisor < 0 && !neg && mag.multiplier > 0) {
Subu(result, result, Operand(dividend));
}
if (mag.shift > 0) sra(result, result, mag.shift);
srl(at, dividend, 31);
Addu(result, result, Operand(at));
}
} } // namespace v8::internal
#endif // V8_TARGET_ARCH_MIPS64
| bsd-3-clause |
SmallAiTT/egret-core | src/egret/player/RenderContext.ts | 17432 | //////////////////////////////////////////////////////////////////////////////////////
//
// Copyright (c) 2014-2015, Egret Technology Inc.
// All rights reserved.
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of the Egret nor the
// names of its contributors may be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY EGRET AND CONTRIBUTORS "AS IS" AND ANY EXPRESS
// OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
// OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
// IN NO EVENT SHALL EGRET AND CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
// INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;LOSS OF USE, DATA,
// OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
// LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
// NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
// EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//////////////////////////////////////////////////////////////////////////////////////
module egret.sys {
/**
* @private
* 绘图上下文
*/
export interface RenderContext {
/**
* @private
* 与绘图上线文关联的画布实例
*/
surface:Surface;
/**
* @private
* 设置新图像如何绘制到已有的图像上的规制
*/
globalCompositeOperation: string;
/**
* @private
* 设置接下来绘图填充的整体透明度
*/
globalAlpha: number;
/**
* @private
* 用于表示剪切斜接的极限值的数字。
* @default 10
*/
miterLimit: number;
/**
* @private
* 指定如何绘制每一条线段末端的属性。有3个可能的值,分别是:<br/>
* <ul>
* <li>"butt": 线段末端以方形结束。</li>
* <li>"round": 线段末端以圆形结束。</li>
* <li>"square": 线段末端以方形结束,但是增加了一个宽度和线段相同,高度是线段厚度一半的矩形区域。</li>
* </ul>
* @default "butt"
*/
lineCap: string;
/**
* @private
* 指定用于拐角的连接外观的类型,有3个可能的值,分别是:<br/>
* <ul>
* <li>"round": 圆角连接</li>
* <li>"bevel": 斜角连接。</li>
* <li>"miter": 尖角连接。当使用尖角模式时,还可以同时使用 miterLimit 参数限制尖角的长度。</li>
* </ul>
* @default "miter"
*/
lineJoin: string;
/**
* @private
* 设置线条粗细,以像素为单位。设置为0,负数,Infinity 或 NaN 将会被忽略。
* @default 1
*/
lineWidth: number;
/**
* @private
* 设置要在图形边线填充的颜色或样式
* @default "#000000"
*/
strokeStyle: any;
/**
* @private
* 设置要在图形内部填充的颜色或样式
* @default "#000000"
*/
fillStyle: any;
/**
* @private
* 控制在缩放时是否对位图进行平滑处理。
* @default true
*/
imageSmoothingEnabled: boolean;
/**
* @private
* 文本的对齐方式的属性,有5个可能的值,分别是:<br/>
* <ul>
* <li>"left" 文本左对齐。</li>
* <li>"right" 文本右对齐。</li>
* <li>"center" 文本居中对齐。</li>
* <li>"start" 文本对齐界线开始的地方 (对于从左向右阅读的语言使用左对齐,对从右向左的阅读的语言使用右对齐)。</li>
* <li>"end" 文本对齐界线结束的地方 (对于从左向右阅读的语言使用右对齐,对从右向左的阅读的语言使用左对齐)。</li>
* </ul>
* @default "start"
*/
textAlign: string;
/**
* @private
* 决定文字垂直方向的对齐方式。有6个可能的值,分别是:<br/>
* <ul>
* <li>"top" 文本基线在文本块的顶部。</li>
* <li>"hanging" 文本基线是悬挂基线。</li>
* <li>"middle" 文本基线在文本块的中间。</li>
* <li>"alphabetic" 文本基线是标准的字母基线。</li>
* <li>"ideographic" 文字基线是表意字基线;如果字符本身超出了alphabetic 基线,那么ideograhpic基线位置在字符本身的底部。</li>
* <li>"bottom" 文本基线在文本块的底部。 与 ideographic 基线的区别在于 ideographic 基线不需要考虑下行字母。</li>
* </ul>
* @default "alphabetic"
*/
textBaseline: string;
/**
* @private
* 当前的字体样式
*/
font: string;
/**
* @private
*
* @param text
* @param x
* @param y
* @param maxWidth
*/
strokeText(text, x, y, maxWidth);
/**
* @private
* 绘制一段圆弧路径。圆弧路径的圆心在 (x, y) 位置,半径为 r ,根据anticlockwise (默认为顺时针)指定的方向从 startAngle 开始绘制,到 endAngle 结束。
* @param x 圆弧中心(圆心)的 x 轴坐标。
* @param y 圆弧中心(圆心)的 y 轴坐标。
* @param radius 圆弧的半径。
* @param startAngle 圆弧的起始点, x轴方向开始计算,单位以弧度表示。
* @param endAngle 圆弧的重点, 单位以弧度表示。
* @param anticlockwise 如果为 true,逆时针绘制圆弧,反之,顺时针绘制。
*/
arc(x:number, y:number, radius:number, startAngle:number, endAngle:number, anticlockwise?:boolean): void;
/**
* @private
* 绘制一段二次贝塞尔曲线路径。它需要2个点。 第一个点是控制点,第二个点是终点。 起始点是当前路径最新的点,当创建二次贝赛尔曲线之前,可以使用 moveTo() 方法进行改变。
* @param cpx 控制点的 x 轴坐标。
* @param cpy 控制点的 y 轴坐标。
* @param x 终点的 x 轴坐标。
* @param y 终点的 y 轴坐标。
*/
quadraticCurveTo(cpx:number, cpy:number, x:number, y:number): void;
/**
* @private
* 使用直线连接子路径的终点到x,y坐标。
* @param x 直线终点的 x 轴坐标。
* @param y 直线终点的 y 轴坐标。
*/
lineTo(x:number, y:number): void;
/**
* @private
* 根据当前的填充样式,填充当前或已存在的路径的方法。采取非零环绕或者奇偶环绕规则。
* @param fillRule 一种算法,决定点是在路径内还是在路径外。允许的值:
* "nonzero": 非零环绕规则, 默认的规则。
* "evenodd": 奇偶环绕规则。
*/
fill(fillRule?:string): void;
/**
* @private
* 使笔点返回到当前子路径的起始点。它尝试从当前点到起始点绘制一条直线。如果图形已经是封闭的或者只有一个点,那么此方法不会做任何操作。
*/
closePath(): void;
/**
* @private
* 创建一段矩形路径,矩形的起点位置是 (x, y) ,尺寸为 width 和 height。矩形的4个点通过直线连接,子路径做为闭合的标记,所以你可以填充或者描边矩形。
* @param x 矩形起点的 x 轴坐标。
* @param y 矩形起点的 y 轴坐标。
* @param width 矩形的宽度。
* @param height 矩形的高度。
*/
rect(x:number, y:number, w:number, h:number): void;
/**
* @private
* 将一个新的子路径的起始点移动到(x,y)坐标
* @param x 点的 x 轴
* @param y 点的 y 轴
*/
moveTo(x:number, y:number): void;
/**
* @private
* 绘制一个填充矩形。矩形的起点在 (x, y) 位置,矩形的尺寸是 width 和 height ,fillStyle 属性决定矩形的样式。
* @param x 矩形起始点的 x 轴坐标。
* @param y 矩形起始点的 y 轴坐标。
* @param width 矩形的宽度。
* @param height 矩形的高度。
*/
fillRect(x:number, y:number, w:number, h:number): void;
/**
* @private
* 绘制一段三次贝赛尔曲线路径。该方法需要三个点。 第一、第二个点是控制点,第三个点是结束点。起始点是当前路径的最后一个点,
* 绘制贝赛尔曲线前,可以通过调用 moveTo() 进行修改。
* @param cp1x 第一个控制点的 x 轴坐标。
* @param cp1y 第一个控制点的 y 轴坐标。
* @param cp2x 第二个控制点的 x 轴坐标。
* @param cp2y 第二个控制点的 y 轴坐标。
* @param x 结束点的 x 轴坐标。
* @param y 结束点的 y 轴坐标。
*/
bezierCurveTo(cp1x:number, cp1y:number, cp2x:number, cp2y:number, x:number, y:number): void;
/**
* @private
* 根据当前的画线样式,绘制当前或已经存在的路径的方法。
*/
stroke(): void;
/**
* @private
* 使用当前的绘画样式,描绘一个起点在 (x, y) 、宽度为 w 、高度为 h 的矩形的方法。
* @param x 矩形起点的 x 轴坐标。
* @param y 矩形起点的 y 轴坐标。
* @param width 矩形的宽度。
* @param height 矩形的高度。
*/
strokeRect(x:number, y:number, w:number, h:number): void;
/**
* @private
* 清空子路径列表开始一个新路径。 当你想创建一个新的路径时,调用此方法。
*/
beginPath(): void;
/**
* @private
* 根据控制点和半径绘制一段圆弧路径,使用直线连接前一个点。
* @param x1 第一个控制点的 x 轴坐标。
* @param y1 第一个控制点的 y 轴坐标。
* @param x2 第二个控制点的 x 轴坐标。
* @param y2 第二个控制点的 y 轴坐标。
* @param radius 圆弧的半径。
*/
arcTo(x1:number, y1:number, x2:number, y2:number, radius:number): void;
/**
* @private
* 使用方法参数描述的矩阵多次叠加当前的变换矩阵。
* @param a 水平缩放。
* @param b 水平倾斜。
* @param c 垂直倾斜。
* @param d 垂直缩放。
* @param tx 水平移动。
* @param ty 垂直移动。
*/
transform(a:number, b:number, c:number, d:number, tx:number, ty:number): void;
/**
* @private
* 通过在网格中移动 surface 和 surface 原点 x 水平方向、原点 y 垂直方向,添加平移变换
* @param x 水平移动。
* @param y 垂直移动。
*/
translate(x:number, y:number): void;
/**
* @private
* 根据 x 水平方向和 y 垂直方向,为 surface 单位添加缩放变换。
* @param x 水平方向的缩放因子。
* @param y 垂直方向的缩放因子。
*/
scale(x:number, y:number): void;
/**
* @private
* 在变换矩阵中增加旋转,角度变量表示一个顺时针旋转角度并且用弧度表示。
* @param angle 顺时针旋转的弧度。
*/
rotate(angle:number): void;
/**
* @private
* 恢复到最近的绘制样式状态,此状态是通过 save() 保存到”状态栈“中最新的元素。
*/
restore(): void;
/**
* @private
* 使用栈保存当前的绘画样式状态,你可以使用 restore() 恢复任何改变。
*/
save(): void;
/**
* @private
* 从当前路径创建一个剪切路径。在 clip() 调用之后,绘制的所有信息只会出现在剪切路径内部。
*/
clip(fillRule?:string): void;
/**
* @private
* 设置指定矩形区域内(以 点 (x, y) 为起点,范围是(width, height) )所有像素变成透明,并擦除之前绘制的所有内容。
* @param x 矩形起点的 x 轴坐标。
* @param y 矩形起点的 y 轴坐标。
* @param width 矩形的宽度。
* @param height 矩形的高度。
*/
clearRect(x:number, y:number, width:number, height:number): void;
/**
* @private
* 重新设置当前的变换为单位矩阵,并使用同样的变量调用 transform() 方法。
* @param a 水平缩放。
* @param b 水平倾斜。
* @param c 垂直倾斜。
* @param d 垂直缩放。
* @param tx 水平移动。
* @param ty 垂直移动。
*/
setTransform(a:number, b:number, c:number, d:number, tx:number, ty:number): void;
/**
* @private
* 创建一个沿参数坐标指定的直线的渐变。该方法返回一个线性的 GraphicsGradient 对象。
* @param x0 起点的 x 轴坐标。
* @param y0 起点的 y 轴坐标。
* @param x1 终点的 x 轴坐标。
* @param y1 终点的 y 轴坐标。
*/
createLinearGradient(x0:number, y0:number, x1:number, y1:number): GraphicsGradient;
/**
* @private
* 根据参数确定的两个圆的坐标,创建一个放射性渐变。该方法返回一个放射性的 GraphicsGradient。
* @param x0 开始圆形的 x 轴坐标。
* @param y0 开始圆形的 y 轴坐标。
* @param r0 开始圆形的半径。
* @param x1 结束圆形的 x 轴坐标。
* @param y1 结束圆形的 y 轴坐标。
* @param r1 结束圆形的半径。
*/
createRadialGradient(x0:number, y0:number, r0:number, x1:number, y1:number, r1:number): GraphicsGradient;
/**
* @private
* 在(x,y)位置绘制(填充)文本。
*/
fillText(text:string, x:number, y:number, maxWidth?:number): void;
/**
* @private
* 测量指定文本宽度,返回 TextMetrics 对象。
*/
measureText(text:string): TextMetrics;
/**
* @private
* 注意:如果要对绘制的图片进行缩放,出于性能优化考虑,系统不会主动去每次重置imageSmoothingEnabled属性,因此您在调用drawImage()方法前请务必
* 确保 imageSmoothingEnabled 已被重置为正常的值,否则有可能沿用上个显示对象绘制过程留下的值。
*/
drawImage(image:BitmapData, offsetX:number, offsetY:number, width?:number, height?:number,
surfaceOffsetX?:number, surfaceOffsetY?:number, surfaceImageWidth?:number, surfaceImageHeight?:number):void;
/**
* @private
* 基于指定的源图象(BitmapData)创建一个模板,通过repetition参数指定源图像在什么方向上进行重复,返回一个GraphicsPattern对象。
* @param bitmapData 做为重复图像源的 BitmapData 对象。
* @param repetition 指定如何重复图像。
* 可能的值有:"repeat" (两个方向重复),"repeat-x" (仅水平方向重复),"repeat-y" (仅垂直方向重复),"no-repeat" (不重复).
*/
createPattern(image:BitmapData, repetition:string): GraphicsPattern;
/**
* @private
* 返回一个 ImageData 对象,用来描述canvas区域隐含的像素数据,这个区域通过矩形表示,起始点为(sx, sy)、宽为sw、高为sh。
*/
getImageData(sx:number, sy:number, sw:number, sh:number): ImageData;
}
/**
* @private
*/
export interface TextMetrics {
/**
* @private
*/
width: number;
}
/**
* @private
*/
export interface ImageData {
/**
* @private
*/
width: number;
/**
* @private
*/
data: Uint8Array;
/**
* @private
*/
height: number;
}
} | bsd-3-clause |
zzuegg/jmonkeyengine | jme3-android/src/main/java/com/jme3/input/android/AndroidInputHandler14.java | 6272 | /*
* Copyright (c) 2009-2012 jMonkeyEngine
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* * Neither the name of 'jMonkeyEngine' nor the names of its contributors
* may be used to endorse or promote products derived from this software
* without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package com.jme3.input.android;
import android.opengl.GLSurfaceView;
import android.view.InputDevice;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import java.util.logging.Logger;
/**
* <code>AndroidInputHandler14</code> extends <code>AndroidInputHandler</code> to
* add the onHover and onGenericMotion events that where added in Android rev 14 (Android 4.0).</br>
* The onGenericMotion events are the main interface to Joystick axes. They
* were actually released in Android rev 12.
*
* @author iwgeric
*/
public class AndroidInputHandler14 extends AndroidInputHandler implements View.OnHoverListener,
View.OnGenericMotionListener {
private static final Logger logger = Logger.getLogger(AndroidInputHandler14.class.getName());
public AndroidInputHandler14() {
touchInput = new AndroidTouchInput14(this);
joyInput = new AndroidJoyInput14(this);
}
@Override
protected void removeListeners(GLSurfaceView view) {
super.removeListeners(view);
view.setOnHoverListener(null);
view.setOnGenericMotionListener(null);
}
@Override
protected void addListeners(GLSurfaceView view) {
super.addListeners(view);
view.setOnHoverListener(this);
view.setOnGenericMotionListener(this);
}
@Override
public boolean onHover(View view, MotionEvent event) {
if (view != getView()) {
return false;
}
boolean consumed = false;
int source = event.getSource();
// logger.log(Level.INFO, "onTouch source: {0}", source);
boolean isTouch = ((source & InputDevice.SOURCE_TOUCHSCREEN) == InputDevice.SOURCE_TOUCHSCREEN);
// logger.log(Level.INFO, "onTouch source: {0}, isTouch: {1}",
// new Object[]{source, isTouch});
if (isTouch && touchInput != null) {
// send the event to the touch processor
consumed = ((AndroidTouchInput14)touchInput).onHover(event);
}
return consumed;
}
@Override
public boolean onGenericMotion(View view, MotionEvent event) {
if (view != getView()) {
return false;
}
boolean consumed = false;
int source = event.getSource();
// logger.log(Level.INFO, "onGenericMotion source: {0}", source);
boolean isJoystick =
((source & InputDevice.SOURCE_GAMEPAD) == InputDevice.SOURCE_GAMEPAD) ||
((source & InputDevice.SOURCE_JOYSTICK) == InputDevice.SOURCE_JOYSTICK);
if (isJoystick && joyInput != null) {
// logger.log(Level.INFO, "onGenericMotion source: {0}, isJoystick: {1}",
// new Object[]{source, isJoystick});
// send the event to the touch processor
consumed = consumed || ((AndroidJoyInput14)joyInput).onGenericMotion(event);
}
return consumed;
}
@Override
public boolean onKey(View view, int keyCode, KeyEvent event) {
if (view != getView()) {
return false;
}
boolean consumed = false;
// logger.log(Level.INFO, "onKey keyCode: {0}, action: {1}, event: {2}",
// new Object[]{KeyEvent.keyCodeToString(keyCode), event.getAction(), event});
int source = event.getSource();
// logger.log(Level.INFO, "onKey source: {0}", source);
boolean isTouch =
((source & InputDevice.SOURCE_TOUCHSCREEN) == InputDevice.SOURCE_TOUCHSCREEN) ||
((source & InputDevice.SOURCE_KEYBOARD) == InputDevice.SOURCE_KEYBOARD);
boolean isJoystick =
((source & InputDevice.SOURCE_GAMEPAD) == InputDevice.SOURCE_GAMEPAD) ||
((source & InputDevice.SOURCE_JOYSTICK) == InputDevice.SOURCE_JOYSTICK);
boolean isUnknown =
(source & android.view.InputDevice.SOURCE_UNKNOWN) == android.view.InputDevice.SOURCE_UNKNOWN;
if (touchInput != null && (isTouch || (isUnknown && this.touchInput.isSimulateKeyboard()))) {
// logger.log(Level.INFO, "onKey source: {0}, isTouch: {1}",
// new Object[]{source, isTouch});
consumed = touchInput.onKey(event);
}
if (isJoystick && joyInput != null) {
// logger.log(Level.INFO, "onKey source: {0}, isJoystick: {1}",
// new Object[]{source, isJoystick});
// use inclusive OR to make sure the onKey method is called.
consumed = consumed | ((AndroidJoyInput14)joyInput).onKey(event);
}
return consumed;
}
}
| bsd-3-clause |
furore-fhir/spark | src/Spark.Engine/Core/LocalhostExtensions.cs | 4107 | using Hl7.Fhir.Model;
using Hl7.Fhir.Rest;
using System;
using Spark.Engine.Extensions;
namespace Spark.Engine.Core
{
public static class ILocalhostExtensions
{
public static bool IsLocal(this ILocalhost localhost, IKey key)
{
if (key.Base == null) return true;
return localhost.IsBaseOf(key.Base);
}
public static bool IsForeign(this ILocalhost localhost, IKey key)
{
return !localhost.IsLocal(key);
}
public static Uri RemoveBase(this ILocalhost localhost, Uri uri)
{
string _base = localhost.GetBaseOf(uri)?.ToString();
if (_base == null)
{
return uri;
}
else
{
string s = uri.ToString();
string path = s.Remove(0, _base.Length);
return new Uri(path, UriKind.Relative);
}
}
public static Key LocalUriToKey(this ILocalhost localhost, Uri uri)
{
string s = uri.ToString();
string _base = localhost.GetBaseOf(uri)?.ToString();
string path = s.Remove(0, _base == null ? 0 : _base.Length);
return Key.ParseOperationPath(path).WithBase(_base);
}
public static Key UriToKey(this ILocalhost localhost, Uri uri)
{
if (uri.IsAbsoluteUri && (uri.IsTemporaryUri() == false))
{
if (localhost.IsBaseOf(uri))
{
return localhost.LocalUriToKey(uri);
}
else
{
throw new ArgumentException("Cannot create a key from a foreign Uri");
}
}
else if (uri.IsTemporaryUri())
{
return Key.Create(null, uri.ToString());
}
else
{
string path = uri.ToString();
return Key.ParseOperationPath(path);
}
}
public static Key UriToKey(this ILocalhost localhost, string uristring)
{
Uri uri = new Uri(uristring, UriKind.RelativeOrAbsolute);
return localhost.UriToKey(uri);
}
public static Uri GetAbsoluteUri(this ILocalhost localhost, IKey key)
{
return key.ToUri(localhost.DefaultBase);
}
public static KeyKind GetKeyKind(this ILocalhost localhost, IKey key)
{
if (key.IsTemporary())
{
return KeyKind.Temporary;
}
else if (!key.HasBase())
{
return KeyKind.Internal;
}
else if (localhost.IsLocal(key))
{
return KeyKind.Local;
}
else
{
return KeyKind.Foreign;
}
}
public static bool IsBaseOf(this ILocalhost localhost, string uristring)
{
Uri uri = new Uri(uristring, UriKind.RelativeOrAbsolute);
return localhost.IsBaseOf(uri);
}
//public static string GetOperationPath(this ILocalhost localhost, Uri uri)
//{
// Key key = localhost.AnyUriToKey(uri).WithoutBase();
// return key.ToOperationPath();
// //Uri endpoint = localhost.GetBaseOf(uri);
// //string _base = endpoint.ToString();
// //string path = uri.ToString().Remove(0, _base.Length);
// //return path;
//}
public static Uri Uri(this ILocalhost localhost, params string[] segments)
{
return new RestUrl(localhost.DefaultBase).AddPath(segments).Uri;
}
public static Uri Uri(this ILocalhost localhost, IKey key)
{
return key.ToUri(localhost.DefaultBase);
}
public static Bundle CreateBundle(this ILocalhost localhost, Bundle.BundleType type)
{
Bundle bundle = new Bundle();
bundle.Type = type;
return bundle;
}
}
}
| bsd-3-clause |
mvaled/sentry | src/sentry/api/endpoints/organization_incident_activity_index.py | 829 | from __future__ import absolute_import
from sentry.api.bases.incident import IncidentPermission, IncidentEndpoint
from sentry.api.paginator import OffsetPaginator
from sentry.api.serializers import serialize
from sentry.incidents.logic import get_incident_activity
class OrganizationIncidentActivityIndexEndpoint(IncidentEndpoint):
permission_classes = (IncidentPermission,)
def get(self, request, organization, incident):
if request.GET.get("desc", "1") == "1":
order_by = "-date_added"
else:
order_by = "date_added"
return self.paginate(
request=request,
queryset=get_incident_activity(incident),
order_by=order_by,
paginator_cls=OffsetPaginator,
on_results=lambda x: serialize(x, request.user),
)
| bsd-3-clause |
tesserakt/cs_spree_fork | core/spec/models/spree/order/state_machine_spec.rb | 6278 | require 'spec_helper'
describe Spree::Order do
let(:order) { Spree::Order.new }
before do
# Ensure state machine has been re-defined correctly
Spree::Order.define_state_machine!
# We don't care about this validation here
order.stub(:require_email)
end
context "#next!" do
context "when current state is confirm" do
before do
order.state = "confirm"
order.run_callbacks(:create)
order.stub :payment_required? => true
order.stub :process_payments! => true
order.stub :has_available_shipment
end
context "when payment processing succeeds" do
before do
order.stub payments: [1]
order.stub process_payments: true
end
it "should finalize order when transitioning to complete state" do
order.should_receive(:finalize!)
order.next!
end
context "when credit card processing fails" do
before { order.stub :process_payments! => false }
it "should not complete the order" do
order.next
order.state.should == "confirm"
end
end
end
context "when payment processing fails" do
before { order.stub :process_payments! => false }
it "cannot transition to complete" do
order.next
order.state.should == "confirm"
end
end
end
context "when current state is delivery" do
before do
order.stub :payment_required? => true
order.stub :apply_free_shipping_promotions
order.state = "delivery"
end
it "adjusts tax rates when transitioning to delivery" do
# Once for the line items
Spree::TaxRate.should_receive(:adjust).once
order.stub :set_shipments_cost
order.next!
end
it "adjusts tax rates twice if there are any shipments" do
# Once for the line items, once for the shipments
order.shipments.build
Spree::TaxRate.should_receive(:adjust).twice
order.stub :set_shipments_cost
order.next!
end
end
end
context "#can_cancel?" do
%w(pending backorder ready).each do |shipment_state|
it "should be true if shipment_state is #{shipment_state}" do
order.stub :completed? => true
order.shipment_state = shipment_state
order.can_cancel?.should be_true
end
end
(Spree::Shipment.state_machine.states.keys - %w(pending backorder ready)).each do |shipment_state|
it "should be false if shipment_state is #{shipment_state}" do
order.stub :completed? => true
order.shipment_state = shipment_state
order.can_cancel?.should be_false
end
end
end
context "#cancel" do
let!(:variant) { stub_model(Spree::Variant) }
let!(:inventory_units) { [stub_model(Spree::InventoryUnit, :variant => variant),
stub_model(Spree::InventoryUnit, :variant => variant) ]}
let!(:shipment) do
shipment = stub_model(Spree::Shipment)
shipment.stub :inventory_units => inventory_units
order.stub :shipments => [shipment]
shipment
end
before do
2.times do
create(:line_item, :order => order, price: 10)
end
order.line_items.stub :find_by_variant_id => order.line_items.first
order.stub :completed? => true
order.stub :allow_cancel? => true
shipments = [shipment]
order.stub :shipments => shipments
shipments.stub :states => []
shipments.stub :ready => []
shipments.stub :pending => []
shipments.stub :shipped => []
Spree::OrderUpdater.any_instance.stub(:update_adjustment_total) { 10 }
end
it "should send a cancel email" do
# Stub methods that cause side-effects in this test
shipment.stub(:cancel!)
order.stub :has_available_shipment
order.stub :restock_items!
mail_message = double "Mail::Message"
order_id = nil
Spree::OrderMailer.should_receive(:cancel_email) { |*args|
order_id = args[0]
mail_message
}
mail_message.should_receive :deliver
order.cancel!
order_id.should == order.id
end
context "restocking inventory" do
before do
shipment.stub(:ensure_correct_adjustment)
shipment.stub(:update_order)
Spree::OrderMailer.stub(:cancel_email).and_return(mail_message = double)
mail_message.stub :deliver
order.stub :has_available_shipment
end
end
context "resets payment state" do
before do
# TODO: This is ugly :(
# Stubs methods that cause unwanted side effects in this test
Spree::OrderMailer.stub(:cancel_email).and_return(mail_message = double)
mail_message.stub :deliver
order.stub :has_available_shipment
order.stub :restock_items!
shipment.stub(:cancel!)
end
context "without shipped items" do
it "should set payment state to 'credit owed'" do
# Regression test for #3711
order.should_receive(:update_column).with(:payment_state, 'credit_owed')
order.cancel!
end
end
context "with shipped items" do
before do
order.stub :shipment_state => 'partial'
order.stub :outstanding_balance? => false
order.stub :payment_state => "paid"
end
it "should not alter the payment state" do
order.cancel!
expect(order.payment_state).to eql "paid"
end
end
context "with payments" do
let(:payment) { create(:payment) }
it "should automatically refund all payments" do
order.stub_chain(:payments, :completed).and_return([payment])
order.stub_chain(:payments, :last).and_return(payment)
payment.should_receive(:cancel!)
order.cancel!
end
end
end
end
# Another regression test for #729
context "#resume" do
before do
order.stub :email => "user@spreecommerce.com"
order.stub :state => "canceled"
order.stub :allow_resume? => true
# Stubs method that cause unwanted side effects in this test
order.stub :has_available_shipment
end
end
end
| bsd-3-clause |
alexbocharov/Orchard2 | src/Orchard.DependencyInjection/Attributes/OrchardSuppressDependencyAttribute.cs | 387 | using System;
namespace Orchard.DependencyInjection
{
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true, Inherited = false)]
public class OrchardSuppressDependencyAttribute : Attribute
{
public OrchardSuppressDependencyAttribute(string fullName)
{
FullName = fullName;
}
public string FullName { get; set; }
}
} | bsd-3-clause |
stephens2424/php | testdata/fuzzdir/corpus/ext_standard_tests_strings_bug53319.php | 248 | <?php
$str = '<br /><br />USD<input type="text"/><br/>CDN<br><input type="text" />';
var_dump(strip_tags($str, '<input>'));
var_dump(strip_tags($str, '<br><input>') === $str);
var_dump(strip_tags($str));
var_dump(strip_tags('<a/b>', '<a>'));
?>
| bsd-3-clause |
XuanYeah/aurous-app | aurous-app/src/me/aurous/ui/widgets/SearchWidget.java | 10132 | package me.aurous.ui.widgets;
import java.awt.Color;
import java.awt.Component;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Window.Type;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.io.File;
import javax.swing.BorderFactory;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.WindowConstants;
import javax.swing.border.EtchedBorder;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumn;
import me.aurous.apis.impl.vkapi.VKAuth;
import me.aurous.player.Settings;
import me.aurous.searchengines.impl.VKEngine;
import me.aurous.searchengines.impl.YouTubeEngine;
import me.aurous.ui.UISession;
import me.aurous.ui.models.ForcedListSelectionModel;
import me.aurous.utils.Constants;
import me.aurous.utils.ModelUtils;
import me.aurous.utils.Utils;
import me.aurous.utils.media.MediaUtils;
import me.aurous.utils.playlist.PlayListUtils;
import com.alee.extended.image.WebImage;
import com.alee.laf.text.WebTextField;
public class SearchWidget implements ActionListener {
public static JTable getSearchTable() {
return searchTable;
}
public static DefaultTableModel getTableModel() {
return tableModel;
}
/**
* Launch the application.
*/
public static void openSearch() {
final String[] args = {};
if ((UISession.getSearchWidget() != null)
&& UISession.getSearchWidget().isOpen()) {
UISession.getSearchWidget().getWidget().toFront();
UISession.getSearchWidget().getWidget().repaint();
return;
}
final File f = new File(Constants.DATA_PATH + "settings/vkauth.dat");
if (!f.exists() && !f.isDirectory()) {
final int dialogButton = JOptionPane.YES_NO_OPTION;
final int dialogResult = JOptionPane
.showConfirmDialog(
null,
"<html>Aurous search feature is powered by <strong>vk.com</strong><br> to use this feature you must connect your account<br> if you do not have one you will be prompted to register. Continue?</html>",
"No Key Detected", dialogButton);
if (dialogResult == JOptionPane.YES_OPTION) {
VKAuth.main(args);
} else {
return;
}
}
EventQueue.invokeLater(() -> {
try {
final SearchWidget window = new SearchWidget();
UISession.setSearchWidget(window);
UISession.getSearchWidget().getWidget().setVisible(true);
} catch (final Exception e) {
e.printStackTrace();
}
});
}
private JFrame searchWidget;
private boolean isValidAuth;
private JComboBox<String> comboBox;
private WebTextField searchBar;
private static JTable searchTable;
private static DefaultTableModel tableModel;
protected JScrollPane scroller;
JPopupMenu popup;
private final String[] options = { "by title", "by artist" };
/**
* Create the application.
*/
public SearchWidget() {
initialize();
}
@Override
public void actionPerformed(final ActionEvent e) {
final Component c = (Component) e.getSource();
final JPopupMenu popup = (JPopupMenu) c.getParent();
final JTable table = (JTable) popup.getInvoker();
switch (e.getActionCommand()) {
case "Play":
MediaUtils.switchMedia(table);
break;
case "Add":
if ((Utils.isNull(Settings.getLastPlayList()))
|| Settings.getLastPlayList().isEmpty()) {
JOptionPane.showMessageDialog(new JFrame(),
"You do not have any playlist loaded!", "Uh oh",
JOptionPane.ERROR_MESSAGE);
return;
}
final int row = table.getSelectedRow();
if (table.getValueAt(row, 3).toString().contains("youtube")) {
PlayListUtils.addUrlToPlayList(table.getValueAt(row, 3)
.toString());
} else {
final String date = Utils.getDate();
final String playListAddition = String.format(
"%s, %s, %s, %s, %s, %s, %s, %s",
table.getValueAt(row, 0), table.getValueAt(row, 1),
table.getValueAt(row, 2), date, Settings.getUserName(),
"", "https://aurous.me/bad.png",
table.getValueAt(row, 4));
PlayListUtils.addUrlToPlayList(playListAddition);
}
case "Copy URL":
MediaUtils.copyMediaURL(table);
break;
}
}
public JComboBox<String> getComboBox() {
return this.comboBox;
}
public WebTextField getSearchBar() {
return this.searchBar;
}
public JFrame getWidget() {
return this.searchWidget;
}
/**
* Initialize the contents of the searchWidget.
*
* @wbp.parser.entryPoint
*/
private void initialize() {
this.searchWidget = new JFrame();
this.searchWidget.setResizable(false);
this.searchWidget.setType(Type.UTILITY);
this.searchWidget.getContentPane().setBackground(new Color(35, 35, 35));
this.searchWidget
.setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
this.searchWidget.setTitle(String.format("Search - Powered by %s",
Settings.getSearchEngine()));
this.searchWidget.setSize(451, 382);
this.searchWidget.getContentPane().setLayout(null);
this.searchBar = new WebTextField(0);
this.searchBar.setInputPrompt("Lana Del Ray...");
this.searchBar.setBackground(new Color(35, 35, 35));
this.searchBar.setForeground(Color.GRAY);
this.searchBar.setFont(new Font("Calibri", Font.PLAIN, 16));
this.searchBar.setLocation(0, 0);
this.searchBar.setMargin(0, 0, 0, 2);
final WebImage webImage = new WebImage(Utils.loadIcon("search.png"));
this.searchBar.setTrailingComponent(webImage);
this.searchBar.setSize(302, 25);
this.searchWidget.getContentPane().add(this.searchBar);
this.comboBox = new JComboBox<String>();
this.comboBox.getEditor().getEditorComponent()
.setBackground(Color.YELLOW);
((JTextField) this.comboBox.getEditor().getEditorComponent())
.setBackground(Color.YELLOW);
this.comboBox.setBackground(Color.YELLOW);
this.comboBox.setBounds(303, 1, 130, 25);
for (final String option : this.options) {
this.comboBox.addItem(option);
}
this.searchWidget.getContentPane().add(this.comboBox);
searchTable = new JTable();
searchTable.setName("search");
searchTable.setBackground(new Color(35, 35, 35));
searchTable.setForeground(Color.GRAY);
searchTable.setOpaque(true);
final JTableHeader header = searchTable.getTableHeader();
header.setOpaque(false);
header.setBorder(BorderFactory.createRaisedSoftBevelBorder());
header.setForeground(Color.GRAY);
header.setAutoscrolls(true);
header.setFont(new Font("Calibri", Font.PLAIN, 14));
header.setBorder(BorderFactory.createEmptyBorder());
searchTable.addKeyListener(new KeyAdapter() {
@Override
public void keyReleased(final KeyEvent e) {
final int c = e.getKeyCode();
e.getSource();
if (c == KeyEvent.VK_DELETE) {
} else if (c == KeyEvent.VK_ADD) {
} else if (c == KeyEvent.VK_LEFT) {
} else if (c == KeyEvent.VK_RIGHT) {
} else if (c == KeyEvent.VK_ENTER) {
}
}
});
searchTable.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(final MouseEvent e) {
if (e.getClickCount() == 2) {
final JTable target = (JTable) e.getSource();
target.getSelectedRow();
MediaUtils.switchMedia(target);
}
}
@Override
public void mouseReleased(final MouseEvent e) {
if (e.isPopupTrigger()) {
final JTable source = (JTable) e.getSource();
final int row = source.rowAtPoint(e.getPoint());
final int column = source.columnAtPoint(e.getPoint());
if (!source.isRowSelected(row)) {
source.changeSelection(row, column, false, false);
}
SearchWidget.this.popup.show(e.getComponent(), e.getX(),
e.getY());
}
}
});
searchTable.setSelectionModel(new ForcedListSelectionModel());
this.scroller = new javax.swing.JScrollPane(searchTable);
this.scroller.setSize(445, 320);
this.scroller.setLocation(0, 33);
ModelUtils.loadSearchResults(Constants.DATA_PATH
+ "settings/search.blank");
final TableColumn hiddenLink = searchTable.getColumnModel()
.getColumn(3);
hiddenLink.setMinWidth(2);
hiddenLink.setPreferredWidth(2);
hiddenLink.setMaxWidth(2);
hiddenLink.setCellRenderer(new ModelUtils.InteractiveRenderer(3));
this.popup = new JPopupMenu();
final JMenuItem addItem = new JMenuItem("Add");
addItem.addActionListener(this);
this.popup.add(addItem);
final JMenuItem copyItem = new JMenuItem("Copy URL");
copyItem.addActionListener(this);
this.popup.add(copyItem);
final JMenuItem playItem = new JMenuItem("Play");
playItem.addActionListener(this);
this.popup.add(playItem);
searchTable.setAutoCreateRowSorter(true);
this.scroller.setBorder(BorderFactory.createEmptyBorder());
this.searchWidget.getContentPane().add(this.scroller);
searchTable.setFillsViewportHeight(true);
searchTable.setSelectionBackground(searchTable.getBackground());
searchTable.setSelectionForeground(new Color(213, 163, 0));
searchTable.setGridColor(new Color(44, 44, 44));
searchTable.setShowVerticalLines(false);
searchTable.setBorder(new EtchedBorder());
searchTable.setFont(new Font("Calibri", Font.PLAIN, 14));
this.searchWidget.setLocationRelativeTo(UISession.getPresenter()
.getAurousFrame());
setSearchEngine();
}
private void setSearchEngine() {
if (Settings.getSearchEngine().equals("VK")) {
final VKEngine vkEngine = new VKEngine(100);
this.searchBar.addActionListener(e -> vkEngine.search());
} else if (Settings.getSearchEngine().equals("YouTube")) {
final YouTubeEngine searchEngine = new YouTubeEngine();
this.searchBar.addActionListener(e -> searchEngine.search());
}
}
public boolean isOpen() {
return this.searchWidget.isVisible();
}
public boolean isValidAuth() {
return this.isValidAuth;
}
public void setComboBox(final JComboBox<String> comboBox) {
this.comboBox = comboBox;
}
public void setValidAuth(final boolean isValidAuth) {
this.isValidAuth = isValidAuth;
}
}
| bsd-3-clause |
OrchardCMS/Orchard | src/Orchard.Web/Modules/Orchard.Localization/Properties/AssemblyInfo.cs | 1325 | using System.Reflection;
using System.Runtime.InteropServices;
using System.Security;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Orchard.Localization")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("Orchard")]
[assembly: AssemblyCopyright("Copyright © .NET Foundation")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("9ed42012-3a6e-4fdc-af6f-ceb7f8b48687")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.10.3")]
[assembly: AssemblyFileVersion("1.10.3")]
| bsd-3-clause |
Anak1nSkywalker/zf2angularjs | module/Application/config/module.config.php | 4409 | <?php
namespace Application;
return array(
'router' => array(
'routes' => array(
'home' => array(
'type' => 'Zend\Mvc\Router\Http\Literal',
'options' => array(
'route' => '/',
'defaults' => array(
'controller' => 'Application\Controller\Index',
'action' => 'index',
),
),
),
// The following is a route to simplify getting started creating
// new controllers and actions without needing to create a new
// module. Simply drop new controllers in, and you can access them
// using the path /application/:controller/:action
'application' => array(
'type' => 'Literal',
'options' => array(
'route' => '/application',
'defaults' => array(
'__NAMESPACE__' => 'Application\Controller',
'controller' => 'Index',
'action' => 'index',
),
),
'may_terminate' => true,
'child_routes' => array(
'default' => array(
'type' => 'Segment',
'options' => array(
'route' => '/[:controller[/:action]]',
'constraints' => array(
'controller' => '[a-zA-Z][a-zA-Z0-9_-]*',
'action' => '[a-zA-Z][a-zA-Z0-9_-]*',
),
'defaults' => array(
),
),
),
),
),
),
),
'service_manager' => array(
'abstract_factories' => array(
'Zend\Cache\Service\StorageCacheAbstractServiceFactory',
'Zend\Log\LoggerAbstractServiceFactory',
),
'aliases' => array(
'translator' => 'MvcTranslator',
),
),
'translator' => array(
'locale' => 'en_US',
'translation_file_patterns' => array(
array(
'type' => 'gettext',
'base_dir' => __DIR__ . '/../language',
'pattern' => '%s.mo',
),
),
),
'controllers' => array(
'invokables' => array(
'Application\Controller\Index' => 'Application\Controller\IndexController'
),
),
'view_manager' => array(
'display_not_found_reason' => true,
'display_exceptions' => true,
'doctype' => 'HTML5',
'not_found_template' => 'error/404',
'exception_template' => 'error/index',
'template_map' => array(
'layout/layout' => __DIR__ . '/../view/layout/layout.phtml',
'application/index/index' => __DIR__ . '/../view/application/index/index.phtml',
'error/404' => __DIR__ . '/../view/error/404.phtml',
'error/index' => __DIR__ . '/../view/error/index.phtml',
),
'template_path_stack' => array(
__DIR__ . '/../view',
),
),
// Placeholder for console routes
'console' => array(
'router' => array(
'routes' => array(
),
),
),
'doctrine' => array(
'driver' => array(
__NAMESPACE__ . '_driver' => array(
'class' => 'Doctrine\ORM\Mapping\Driver\AnnotationDriver',
'cache' => 'array',
'paths' => array(__DIR__ . '/../src/' . __NAMESPACE__ . '/Entity'),
),
'orm_default' => array(
'drivers' => array(
__NAMESPACE__ . '\Entity' => __NAMESPACE__ . '_driver'
),
),
// 'fixture' => array(
// 'Application_fixture' => __DIR__ . '/../src/Application/Fixture',
// ),
),
),
// 'data-fixtures' => array(
// 'Application_fixture' => __DIR__ . '/../src/Application/Fixture'
// ),
'data-fixture' => array(
'location' => __DIR__ . '/../src/Application/Fixture',
),
);
| bsd-3-clause |
surge-/libwebrtc | modules/video_coding/codecs/vp8/test/vp8_impl_unittest.cc | 9962 | /*
* Copyright (c) 2012 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree. An additional intellectual property rights grant can be found
* in the file PATENTS. All contributing project authors may
* be found in the AUTHORS file in the root of the source tree.
*/
#include "testing/gtest/include/gtest/gtest.h"
#include "webrtc/modules/video_coding/codecs/test_framework/unit_test.h"
#include "webrtc/modules/video_coding/codecs/test_framework/video_source.h"
#include "webrtc/modules/video_coding/codecs/vp8/include/vp8.h"
#include "webrtc/system_wrappers/interface/scoped_ptr.h"
#include "webrtc/system_wrappers/interface/tick_util.h"
#include "webrtc/test/testsupport/fileutils.h"
#include "webrtc/test/testsupport/gtest_disable.h"
namespace webrtc {
enum { kMaxWaitEncTimeMs = 100 };
enum { kMaxWaitDecTimeMs = 25 };
// TODO(mikhal): Replace these with mocks.
class Vp8UnitTestEncodeCompleteCallback : public webrtc::EncodedImageCallback {
public:
Vp8UnitTestEncodeCompleteCallback(VideoFrame* frame,
unsigned int decoderSpecificSize,
void* decoderSpecificInfo)
: encoded_video_frame_(frame),
encode_complete_(false) {}
int Encoded(EncodedImage& encodedImage,
const CodecSpecificInfo* codecSpecificInfo,
const RTPFragmentationHeader*);
bool EncodeComplete();
// Note that this only makes sense if an encode has been completed
VideoFrameType EncodedFrameType() const {return encoded_frame_type_;}
private:
VideoFrame* encoded_video_frame_;
bool encode_complete_;
VideoFrameType encoded_frame_type_;
};
int Vp8UnitTestEncodeCompleteCallback::Encoded(EncodedImage& encodedImage,
const CodecSpecificInfo* codecSpecificInfo,
const RTPFragmentationHeader* fragmentation) {
encoded_video_frame_->VerifyAndAllocate(encodedImage._size);
encoded_video_frame_->CopyFrame(encodedImage._size, encodedImage._buffer);
encoded_video_frame_->SetLength(encodedImage._length);
// TODO(mikhal): Update frame type API.
// encoded_video_frame_->SetFrameType(encodedImage._frameType);
encoded_video_frame_->SetWidth(encodedImage._encodedWidth);
encoded_video_frame_->SetHeight(encodedImage._encodedHeight);
encoded_video_frame_->SetTimeStamp(encodedImage._timeStamp);
encode_complete_ = true;
encoded_frame_type_ = encodedImage._frameType;
return 0;
}
bool Vp8UnitTestEncodeCompleteCallback::EncodeComplete() {
if (encode_complete_) {
encode_complete_ = false;
return true;
}
return false;
}
class Vp8UnitTestDecodeCompleteCallback : public webrtc::DecodedImageCallback {
public:
explicit Vp8UnitTestDecodeCompleteCallback(I420VideoFrame* frame)
: decoded_video_frame_(frame),
decode_complete(false) {}
int Decoded(webrtc::I420VideoFrame& frame);
bool DecodeComplete();
private:
I420VideoFrame* decoded_video_frame_;
bool decode_complete;
};
bool Vp8UnitTestDecodeCompleteCallback::DecodeComplete() {
if (decode_complete) {
decode_complete = false;
return true;
}
return false;
}
int Vp8UnitTestDecodeCompleteCallback::Decoded(I420VideoFrame& image) {
decoded_video_frame_->CopyFrame(image);
decode_complete = true;
return 0;
}
class TestVp8Impl : public ::testing::Test {
protected:
virtual void SetUp() {
encoder_.reset(VP8Encoder::Create());
decoder_.reset(VP8Decoder::Create());
memset(&codec_inst_, 0, sizeof(codec_inst_));
encode_complete_callback_.reset(new
Vp8UnitTestEncodeCompleteCallback(&encoded_video_frame_, 0, NULL));
decode_complete_callback_.reset(new
Vp8UnitTestDecodeCompleteCallback(&decoded_video_frame_));
encoder_->RegisterEncodeCompleteCallback(encode_complete_callback_.get());
decoder_->RegisterDecodeCompleteCallback(decode_complete_callback_.get());
// Using a QCIF image (aligned stride (u,v planes) > width).
// Processing only one frame.
const VideoSource source(test::ResourcePath("paris_qcif", "yuv"), kQCIF);
length_source_frame_ = source.GetFrameLength();
source_buffer_.reset(new uint8_t[length_source_frame_]);
source_file_ = fopen(source.GetFileName().c_str(), "rb");
ASSERT_TRUE(source_file_ != NULL);
// Set input frame.
ASSERT_EQ(fread(source_buffer_.get(), 1, length_source_frame_,
source_file_), length_source_frame_);
codec_inst_.width = source.GetWidth();
codec_inst_.height = source.GetHeight();
codec_inst_.maxFramerate = source.GetFrameRate();
// Setting aligned stride values.
int stride_uv = 0;
int stride_y = 0;
Calc16ByteAlignedStride(codec_inst_.width, &stride_y, &stride_uv);
EXPECT_EQ(stride_y, 176);
EXPECT_EQ(stride_uv, 96);
input_frame_.CreateEmptyFrame(codec_inst_.width, codec_inst_.height,
stride_y, stride_uv, stride_uv);
// Using ConvertToI420 to add stride to the image.
EXPECT_EQ(0, ConvertToI420(kI420, source_buffer_.get(), 0, 0,
codec_inst_.width, codec_inst_.height,
0, kRotateNone, &input_frame_));
}
void SetUpEncodeDecode() {
codec_inst_.startBitrate = 300;
codec_inst_.maxBitrate = 4000;
codec_inst_.qpMax = 56;
codec_inst_.codecSpecific.VP8.denoisingOn = true;
EXPECT_EQ(WEBRTC_VIDEO_CODEC_OK,
encoder_->InitEncode(&codec_inst_, 1, 1440));
EXPECT_EQ(WEBRTC_VIDEO_CODEC_OK, decoder_->InitDecode(&codec_inst_, 1));
}
int WaitForEncodedFrame() const {
int64_t startTime = TickTime::MillisecondTimestamp();
while (TickTime::MillisecondTimestamp() - startTime < kMaxWaitEncTimeMs) {
if (encode_complete_callback_->EncodeComplete()) {
return encoded_video_frame_.Length();
}
}
return 0;
}
int WaitForDecodedFrame() const {
int64_t startTime = TickTime::MillisecondTimestamp();
while (TickTime::MillisecondTimestamp() - startTime < kMaxWaitDecTimeMs) {
if (decode_complete_callback_->DecodeComplete()) {
return CalcBufferSize(kI420, decoded_video_frame_.width(),
decoded_video_frame_.height());
}
}
return 0;
}
void VideoFrameToEncodedImage(VideoFrame& frame, EncodedImage &image) {
image._buffer = frame.Buffer();
image._length = frame.Length();
image._size = frame.Size();
image._timeStamp = frame.TimeStamp();
image._encodedWidth = frame.Width();
image._encodedHeight = frame.Height();
image._completeFrame = true;
}
scoped_ptr<Vp8UnitTestEncodeCompleteCallback> encode_complete_callback_;
scoped_ptr<Vp8UnitTestDecodeCompleteCallback> decode_complete_callback_;
scoped_array<uint8_t> source_buffer_;
FILE* source_file_;
I420VideoFrame input_frame_;
scoped_ptr<VideoEncoder> encoder_;
scoped_ptr<VideoDecoder> decoder_;
VideoFrame encoded_video_frame_;
I420VideoFrame decoded_video_frame_;
unsigned int length_source_frame_;
VideoCodec codec_inst_;
};
TEST_F(TestVp8Impl, DISABLED_ON_ANDROID(BaseUnitTest)) {
// TODO(mikhal): Remove dependency. Move all test code here.
EXPECT_EQ(WEBRTC_VIDEO_CODEC_OK, encoder_->Release());
UnitTest unittest;
unittest.SetEncoder(encoder_.get());
unittest.SetDecoder(decoder_.get());
unittest.Setup();
unittest.Perform();
unittest.Print();
}
TEST_F(TestVp8Impl, EncoderParameterTest) {
strncpy(codec_inst_.plName, "VP8", 31);
codec_inst_.plType = 126;
codec_inst_.maxBitrate = 0;
codec_inst_.minBitrate = 0;
codec_inst_.width = 1440;
codec_inst_.height = 1080;
codec_inst_.maxFramerate = 30;
codec_inst_.startBitrate = 300;
codec_inst_.qpMax = 56;
codec_inst_.codecSpecific.VP8.complexity = kComplexityNormal;
codec_inst_.codecSpecific.VP8.numberOfTemporalLayers = 1;
// Calls before InitEncode().
EXPECT_EQ(WEBRTC_VIDEO_CODEC_OK, encoder_->Release());
int bit_rate = 300;
EXPECT_EQ(WEBRTC_VIDEO_CODEC_UNINITIALIZED,
encoder_->SetRates(bit_rate, codec_inst_.maxFramerate));
EXPECT_EQ(WEBRTC_VIDEO_CODEC_OK,
encoder_->InitEncode(&codec_inst_, 1, 1440));
// Decoder parameter tests.
// Calls before InitDecode().
EXPECT_EQ(WEBRTC_VIDEO_CODEC_OK, decoder_->Release());
EXPECT_EQ(WEBRTC_VIDEO_CODEC_OK, decoder_->InitDecode(&codec_inst_, 1));
}
TEST_F(TestVp8Impl, DISABLED_ON_ANDROID(AlignedStrideEncodeDecode)) {
SetUpEncodeDecode();
encoder_->Encode(input_frame_, NULL, NULL);
EXPECT_GT(WaitForEncodedFrame(), 0);
EncodedImage encodedImage;
VideoFrameToEncodedImage(encoded_video_frame_, encodedImage);
// First frame should be a key frame.
encodedImage._frameType = kKeyFrame;
EXPECT_EQ(WEBRTC_VIDEO_CODEC_OK, decoder_->Decode(encodedImage, false, NULL));
EXPECT_GT(WaitForDecodedFrame(), 0);
// Compute PSNR on all planes (faster than SSIM).
EXPECT_GT(I420PSNR(&input_frame_, &decoded_video_frame_), 36);
}
TEST_F(TestVp8Impl, DISABLED_ON_ANDROID(DecodeWithACompleteKeyFrame)) {
SetUpEncodeDecode();
encoder_->Encode(input_frame_, NULL, NULL);
EXPECT_GT(WaitForEncodedFrame(), 0);
EncodedImage encodedImage;
VideoFrameToEncodedImage(encoded_video_frame_, encodedImage);
// Setting complete to false -> should return an error.
encodedImage._completeFrame = false;
EXPECT_EQ(WEBRTC_VIDEO_CODEC_ERROR,
decoder_->Decode(encodedImage, false, NULL));
// Setting complete back to true. Forcing a delta frame.
encodedImage._frameType = kDeltaFrame;
encodedImage._completeFrame = true;
EXPECT_EQ(WEBRTC_VIDEO_CODEC_ERROR,
decoder_->Decode(encodedImage, false, NULL));
// Now setting a key frame.
encodedImage._frameType = kKeyFrame;
EXPECT_EQ(WEBRTC_VIDEO_CODEC_OK,
decoder_->Decode(encodedImage, false, NULL));
EXPECT_GT(I420PSNR(&input_frame_, &decoded_video_frame_), 36);
}
} // namespace webrtc
| bsd-3-clause |
anirudhSK/chromium | tools/telemetry/telemetry/core/backends/chrome/chrome_browser_options.py | 1175 | # Copyright 2013 The Chromium Authors. All rights reserved.
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.
from telemetry.core import browser_options
from telemetry.core.backends.chrome import cros_interface
def CreateChromeBrowserOptions(br_options):
browser_type = br_options.browser_type
# Unit tests.
if not browser_type:
return br_options
if (cros_interface.IsRunningOnCrosDevice() or
browser_type.startswith('cros')):
return CrosBrowserOptions(br_options)
return br_options
class ChromeBrowserOptions(browser_options.BrowserOptions):
"""Chrome-specific browser options."""
def __init__(self, br_options):
super(ChromeBrowserOptions, self).__init__()
# Copy to self.
self.__dict__.update(br_options.__dict__)
class CrosBrowserOptions(ChromeBrowserOptions):
"""ChromeOS-specific browser options."""
def __init__(self, br_options):
super(CrosBrowserOptions, self).__init__(br_options)
# Create a browser with oobe property.
self.create_browser_with_oobe = False
self.auto_login = True
self.username = 'test@test.test'
self.password = ''
| bsd-3-clause |
meego-tablet-ux/meego-app-browser | media/audio/win/audio_manager_win.cc | 9741 | // Copyright (c) 2011 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "media/audio/audio_io.h"
#include <windows.h>
#include <objbase.h> // This has to be before initguid.h
#include <initguid.h>
#include <mmsystem.h>
#include <setupapi.h>
#include "base/basictypes.h"
#include "base/command_line.h"
#include "base/file_path.h"
#include "base/memory/scoped_ptr.h"
#include "base/path_service.h"
#include "base/process_util.h"
#include "base/string_number_conversions.h"
#include "base/string_util.h"
#include "base/win/windows_version.h"
#include "media/audio/fake_audio_input_stream.h"
#include "media/audio/fake_audio_output_stream.h"
#include "media/audio/win/audio_manager_win.h"
#include "media/audio/win/wavein_input_win.h"
#include "media/audio/win/waveout_output_win.h"
#include "media/base/limits.h"
// Libraries required for the SetupAPI and Wbem APIs used here.
#pragma comment(lib, "setupapi.lib")
// The following are defined in various DDK headers, and we (re)define them
// here to avoid adding the DDK as a chrome dependency.
#define DRV_QUERYDEVICEINTERFACE 0x80c
#define DRVM_MAPPER_PREFERRED_GET 0x2015
#define DRV_QUERYDEVICEINTERFACESIZE 0x80d
DEFINE_GUID(AM_KSCATEGORY_AUDIO, 0x6994ad04, 0x93ef, 0x11d0,
0xa3, 0xcc, 0x00, 0xa0, 0xc9, 0x22, 0x31, 0x96);
// Maximum number of output streams that can be open simultaneously.
static const size_t kMaxOutputStreams = 50;
// Up to 8 channels can be passed to the driver.
// This should work, given the right drivers, but graceful error handling is
// needed.
static const int kWinMaxChannels = 8;
static const int kWinMaxInputChannels = 2;
// We use 3 buffers for recording audio so that if a recording callback takes
// some time to return we won't lose audio. More buffers while recording are
// ok because they don't introduce any delay in recording, unlike in playback
// where you first need to fill in that number of buffers before starting to
// play.
static const int kNumInputBuffers = 3;
static int GetVersionPartAsInt(DWORDLONG num) {
return static_cast<int>(num & 0xffff);
}
// Returns a string containing the given device's description and installed
// driver version.
static string16 GetDeviceAndDriverInfo(HDEVINFO device_info,
SP_DEVINFO_DATA* device_data) {
// Save the old install params setting and set a flag for the
// SetupDiBuildDriverInfoList below to return only the installed drivers.
SP_DEVINSTALL_PARAMS old_device_install_params;
old_device_install_params.cbSize = sizeof(old_device_install_params);
SetupDiGetDeviceInstallParams(device_info, device_data,
&old_device_install_params);
SP_DEVINSTALL_PARAMS device_install_params = old_device_install_params;
device_install_params.FlagsEx |= DI_FLAGSEX_INSTALLEDDRIVER;
SetupDiSetDeviceInstallParams(device_info, device_data,
&device_install_params);
SP_DRVINFO_DATA driver_data;
driver_data.cbSize = sizeof(driver_data);
string16 device_and_driver_info;
if (SetupDiBuildDriverInfoList(device_info, device_data,
SPDIT_COMPATDRIVER)) {
if (SetupDiEnumDriverInfo(device_info, device_data, SPDIT_COMPATDRIVER, 0,
&driver_data)) {
DWORDLONG version = driver_data.DriverVersion;
device_and_driver_info = string16(driver_data.Description) + L" v" +
base::IntToString16(GetVersionPartAsInt((version >> 48))) + L"." +
base::IntToString16(GetVersionPartAsInt((version >> 32))) + L"." +
base::IntToString16(GetVersionPartAsInt((version >> 16))) + L"." +
base::IntToString16(GetVersionPartAsInt(version));
}
SetupDiDestroyDriverInfoList(device_info, device_data, SPDIT_COMPATDRIVER);
}
SetupDiSetDeviceInstallParams(device_info, device_data,
&old_device_install_params);
return device_and_driver_info;
}
AudioManagerWin::AudioManagerWin()
: num_output_streams_(0) {
}
AudioManagerWin::~AudioManagerWin() {
}
bool AudioManagerWin::HasAudioOutputDevices() {
return (::waveOutGetNumDevs() != 0);
}
bool AudioManagerWin::HasAudioInputDevices() {
return (::waveInGetNumDevs() != 0);
}
// Factory for the implementations of AudioOutputStream. Two implementations
// should suffice most windows user's needs.
// - PCMWaveOutAudioOutputStream: Based on the waveOutWrite API (in progress)
// - PCMDXSoundAudioOutputStream: Based on DirectSound or XAudio (future work).
AudioOutputStream* AudioManagerWin::MakeAudioOutputStream(
AudioParameters params) {
if (!params.IsValid() || (params.channels > kWinMaxChannels))
return NULL;
// Limit the number of audio streams opened.
if (num_output_streams_ >= kMaxOutputStreams) {
return NULL;
}
if (params.format == AudioParameters::AUDIO_MOCK) {
return FakeAudioOutputStream::MakeFakeStream(params);
} else if (params.format == AudioParameters::AUDIO_PCM_LINEAR) {
num_output_streams_++;
return new PCMWaveOutAudioOutputStream(this, params, 3, WAVE_MAPPER);
} else if (params.format == AudioParameters::AUDIO_PCM_LOW_LATENCY) {
num_output_streams_++;
// TODO(cpu): waveout cannot hit 20ms latency. Use other method.
return new PCMWaveOutAudioOutputStream(this, params, 2, WAVE_MAPPER);
}
return NULL;
}
// Factory for the implementations of AudioInputStream.
AudioInputStream* AudioManagerWin::MakeAudioInputStream(
AudioParameters params) {
if (!params.IsValid() || (params.channels > kWinMaxInputChannels))
return NULL;
if (params.format == AudioParameters::AUDIO_MOCK) {
return FakeAudioInputStream::MakeFakeStream(params);
} else if (params.format == AudioParameters::AUDIO_PCM_LINEAR) {
return new PCMWaveInAudioInputStream(this, params, kNumInputBuffers,
WAVE_MAPPER);
}
return NULL;
}
void AudioManagerWin::ReleaseOutputStream(PCMWaveOutAudioOutputStream* stream) {
DCHECK(stream);
num_output_streams_--;
delete stream;
}
void AudioManagerWin::ReleaseInputStream(PCMWaveInAudioInputStream* stream) {
delete stream;
}
void AudioManagerWin::MuteAll() {
}
void AudioManagerWin::UnMuteAll() {
}
string16 AudioManagerWin::GetAudioInputDeviceModel() {
// Get the default audio capture device and its device interface name.
DWORD device_id = 0;
waveInMessage(reinterpret_cast<HWAVEIN>(WAVE_MAPPER),
DRVM_MAPPER_PREFERRED_GET,
reinterpret_cast<DWORD_PTR>(&device_id), NULL);
ULONG device_interface_name_size = 0;
waveInMessage(reinterpret_cast<HWAVEIN>(device_id),
DRV_QUERYDEVICEINTERFACESIZE,
reinterpret_cast<DWORD_PTR>(&device_interface_name_size), 0);
if (device_interface_name_size == 0) // No audio capture device?
return string16();
string16 device_interface_name;
string16::value_type* name_ptr = WriteInto(&device_interface_name,
device_interface_name_size / sizeof(string16::value_type));
waveInMessage(reinterpret_cast<HWAVEIN>(device_id),
DRV_QUERYDEVICEINTERFACE,
reinterpret_cast<DWORD_PTR>(name_ptr),
static_cast<DWORD_PTR>(device_interface_name_size));
// Enumerate all audio devices and find the one matching the above device
// interface name.
HDEVINFO device_info = SetupDiGetClassDevs(
&AM_KSCATEGORY_AUDIO, 0, 0, DIGCF_DEVICEINTERFACE | DIGCF_PRESENT);
if (device_info == INVALID_HANDLE_VALUE)
return string16();
DWORD interface_index = 0;
SP_DEVICE_INTERFACE_DATA interface_data;
interface_data.cbSize = sizeof(interface_data);
while (SetupDiEnumDeviceInterfaces(device_info, 0, &AM_KSCATEGORY_AUDIO,
interface_index++, &interface_data)) {
// Query the size of the struct, allocate it and then query the data.
SP_DEVINFO_DATA device_data;
device_data.cbSize = sizeof(device_data);
DWORD interface_detail_size = 0;
SetupDiGetDeviceInterfaceDetail(device_info, &interface_data, 0, 0,
&interface_detail_size, &device_data);
if (!interface_detail_size)
continue;
scoped_array<char> interface_detail_buffer(new char[interface_detail_size]);
SP_DEVICE_INTERFACE_DETAIL_DATA* interface_detail =
reinterpret_cast<SP_DEVICE_INTERFACE_DETAIL_DATA*>(
interface_detail_buffer.get());
interface_detail->cbSize = interface_detail_size;
if (!SetupDiGetDeviceInterfaceDetail(device_info, &interface_data,
interface_detail,
interface_detail_size, NULL,
&device_data))
return string16();
bool device_found = (device_interface_name == interface_detail->DevicePath);
if (device_found)
return GetDeviceAndDriverInfo(device_info, &device_data);
}
return string16();
}
bool AudioManagerWin::CanShowAudioInputSettings() {
return true;
}
void AudioManagerWin::ShowAudioInputSettings() {
std::wstring program;
std::string argument;
if (base::win::GetVersion() <= base::win::VERSION_XP) {
program = L"sndvol32.exe";
argument = "-R";
} else {
program = L"control.exe";
argument = "mmsys.cpl,,1";
}
FilePath path;
PathService::Get(base::DIR_SYSTEM, &path);
path = path.Append(program);
CommandLine command_line(path);
command_line.AppendArg(argument);
base::LaunchApp(command_line, false, false, NULL);
}
// static
AudioManager* AudioManager::CreateAudioManager() {
return new AudioManagerWin();
}
| bsd-3-clause |
rvraghav93/scikit-learn | sklearn/tests/test_multiclass.py | 29070 | import numpy as np
import scipy.sparse as sp
from re import escape
from sklearn.utils.testing import assert_array_equal
from sklearn.utils.testing import assert_equal
from sklearn.utils.testing import assert_almost_equal
from sklearn.utils.testing import assert_true
from sklearn.utils.testing import assert_false
from sklearn.utils.testing import assert_raises
from sklearn.utils.testing import assert_warns
from sklearn.utils.testing import assert_greater
from sklearn.utils.testing import assert_raise_message
from sklearn.utils.testing import assert_raises_regexp
from sklearn.multiclass import OneVsRestClassifier
from sklearn.multiclass import OneVsOneClassifier
from sklearn.multiclass import OutputCodeClassifier
from sklearn.utils.multiclass import (check_classification_targets,
type_of_target)
from sklearn.utils import shuffle
from sklearn.metrics import precision_score
from sklearn.metrics import recall_score
from sklearn.svm import LinearSVC, SVC
from sklearn.naive_bayes import MultinomialNB
from sklearn.linear_model import (LinearRegression, Lasso, ElasticNet, Ridge,
Perceptron, LogisticRegression,
SGDClassifier)
from sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor
from sklearn.model_selection import GridSearchCV, cross_val_score
from sklearn.pipeline import Pipeline
from sklearn import svm
from sklearn import datasets
from sklearn.externals.six.moves import zip
iris = datasets.load_iris()
rng = np.random.RandomState(0)
perm = rng.permutation(iris.target.size)
iris.data = iris.data[perm]
iris.target = iris.target[perm]
n_classes = 3
def test_ovr_exceptions():
ovr = OneVsRestClassifier(LinearSVC(random_state=0))
assert_raises(ValueError, ovr.predict, [])
# Fail on multioutput data
assert_raises(ValueError, OneVsRestClassifier(MultinomialNB()).fit,
np.array([[1, 0], [0, 1]]),
np.array([[1, 2], [3, 1]]))
assert_raises(ValueError, OneVsRestClassifier(MultinomialNB()).fit,
np.array([[1, 0], [0, 1]]),
np.array([[1.5, 2.4], [3.1, 0.8]]))
def test_check_classification_targets():
# Test that check_classification_target return correct type. #5782
y = np.array([0.0, 1.1, 2.0, 3.0])
msg = type_of_target(y)
assert_raise_message(ValueError, msg, check_classification_targets, y)
def test_ovr_fit_predict():
# A classifier which implements decision_function.
ovr = OneVsRestClassifier(LinearSVC(random_state=0))
pred = ovr.fit(iris.data, iris.target).predict(iris.data)
assert_equal(len(ovr.estimators_), n_classes)
clf = LinearSVC(random_state=0)
pred2 = clf.fit(iris.data, iris.target).predict(iris.data)
assert_equal(np.mean(iris.target == pred), np.mean(iris.target == pred2))
# A classifier which implements predict_proba.
ovr = OneVsRestClassifier(MultinomialNB())
pred = ovr.fit(iris.data, iris.target).predict(iris.data)
assert_greater(np.mean(iris.target == pred), 0.65)
def test_ovr_partial_fit():
# Test if partial_fit is working as intented
X, y = shuffle(iris.data, iris.target, random_state=0)
ovr = OneVsRestClassifier(MultinomialNB())
ovr.partial_fit(X[:100], y[:100], np.unique(y))
ovr.partial_fit(X[100:], y[100:])
pred = ovr.predict(X)
ovr2 = OneVsRestClassifier(MultinomialNB())
pred2 = ovr2.fit(X, y).predict(X)
assert_almost_equal(pred, pred2)
assert_equal(len(ovr.estimators_), len(np.unique(y)))
assert_greater(np.mean(y == pred), 0.65)
# Test when mini batches doesn't have all classes
# with SGDClassifier
X = np.abs(np.random.randn(14, 2))
y = [1, 1, 1, 1, 2, 3, 3, 0, 0, 2, 3, 1, 2, 3]
ovr = OneVsRestClassifier(SGDClassifier(max_iter=1, tol=None,
shuffle=False, random_state=0))
ovr.partial_fit(X[:7], y[:7], np.unique(y))
ovr.partial_fit(X[7:], y[7:])
pred = ovr.predict(X)
ovr1 = OneVsRestClassifier(SGDClassifier(max_iter=1, tol=None,
shuffle=False, random_state=0))
pred1 = ovr1.fit(X, y).predict(X)
assert_equal(np.mean(pred == y), np.mean(pred1 == y))
# test partial_fit only exists if estimator has it:
ovr = OneVsRestClassifier(SVC())
assert_false(hasattr(ovr, "partial_fit"))
def test_ovr_partial_fit_exceptions():
ovr = OneVsRestClassifier(MultinomialNB())
X = np.abs(np.random.randn(14, 2))
y = [1, 1, 1, 1, 2, 3, 3, 0, 0, 2, 3, 1, 2, 3]
ovr.partial_fit(X[:7], y[:7], np.unique(y))
# A new class value which was not in the first call of partial_fit
# It should raise ValueError
y1 = [5] + y[7:-1]
assert_raises_regexp(ValueError, "Mini-batch contains \[.+\] while classes"
" must be subset of \[.+\]",
ovr.partial_fit, X=X[7:], y=y1)
def test_ovr_ovo_regressor():
# test that ovr and ovo work on regressors which don't have a decision_
# function
ovr = OneVsRestClassifier(DecisionTreeRegressor())
pred = ovr.fit(iris.data, iris.target).predict(iris.data)
assert_equal(len(ovr.estimators_), n_classes)
assert_array_equal(np.unique(pred), [0, 1, 2])
# we are doing something sensible
assert_greater(np.mean(pred == iris.target), .9)
ovr = OneVsOneClassifier(DecisionTreeRegressor())
pred = ovr.fit(iris.data, iris.target).predict(iris.data)
assert_equal(len(ovr.estimators_), n_classes * (n_classes - 1) / 2)
assert_array_equal(np.unique(pred), [0, 1, 2])
# we are doing something sensible
assert_greater(np.mean(pred == iris.target), .9)
def test_ovr_fit_predict_sparse():
for sparse in [sp.csr_matrix, sp.csc_matrix, sp.coo_matrix, sp.dok_matrix,
sp.lil_matrix]:
base_clf = MultinomialNB(alpha=1)
X, Y = datasets.make_multilabel_classification(n_samples=100,
n_features=20,
n_classes=5,
n_labels=3,
length=50,
allow_unlabeled=True,
random_state=0)
X_train, Y_train = X[:80], Y[:80]
X_test = X[80:]
clf = OneVsRestClassifier(base_clf).fit(X_train, Y_train)
Y_pred = clf.predict(X_test)
clf_sprs = OneVsRestClassifier(base_clf).fit(X_train, sparse(Y_train))
Y_pred_sprs = clf_sprs.predict(X_test)
assert_true(clf.multilabel_)
assert_true(sp.issparse(Y_pred_sprs))
assert_array_equal(Y_pred_sprs.toarray(), Y_pred)
# Test predict_proba
Y_proba = clf_sprs.predict_proba(X_test)
# predict assigns a label if the probability that the
# sample has the label is greater than 0.5.
pred = Y_proba > .5
assert_array_equal(pred, Y_pred_sprs.toarray())
# Test decision_function
clf_sprs = OneVsRestClassifier(svm.SVC()).fit(X_train, sparse(Y_train))
dec_pred = (clf_sprs.decision_function(X_test) > 0).astype(int)
assert_array_equal(dec_pred, clf_sprs.predict(X_test).toarray())
def test_ovr_always_present():
# Test that ovr works with classes that are always present or absent.
# Note: tests is the case where _ConstantPredictor is utilised
X = np.ones((10, 2))
X[:5, :] = 0
# Build an indicator matrix where two features are always on.
# As list of lists, it would be: [[int(i >= 5), 2, 3] for i in range(10)]
y = np.zeros((10, 3))
y[5:, 0] = 1
y[:, 1] = 1
y[:, 2] = 1
ovr = OneVsRestClassifier(LogisticRegression())
assert_warns(UserWarning, ovr.fit, X, y)
y_pred = ovr.predict(X)
assert_array_equal(np.array(y_pred), np.array(y))
y_pred = ovr.decision_function(X)
assert_equal(np.unique(y_pred[:, -2:]), 1)
y_pred = ovr.predict_proba(X)
assert_array_equal(y_pred[:, -1], np.ones(X.shape[0]))
# y has a constantly absent label
y = np.zeros((10, 2))
y[5:, 0] = 1 # variable label
ovr = OneVsRestClassifier(LogisticRegression())
assert_warns(UserWarning, ovr.fit, X, y)
y_pred = ovr.predict_proba(X)
assert_array_equal(y_pred[:, -1], np.zeros(X.shape[0]))
def test_ovr_multiclass():
# Toy dataset where features correspond directly to labels.
X = np.array([[0, 0, 5], [0, 5, 0], [3, 0, 0], [0, 0, 6], [6, 0, 0]])
y = ["eggs", "spam", "ham", "eggs", "ham"]
Y = np.array([[0, 0, 1],
[0, 1, 0],
[1, 0, 0],
[0, 0, 1],
[1, 0, 0]])
classes = set("ham eggs spam".split())
for base_clf in (MultinomialNB(), LinearSVC(random_state=0),
LinearRegression(), Ridge(),
ElasticNet()):
clf = OneVsRestClassifier(base_clf).fit(X, y)
assert_equal(set(clf.classes_), classes)
y_pred = clf.predict(np.array([[0, 0, 4]]))[0]
assert_equal(set(y_pred), set("eggs"))
# test input as label indicator matrix
clf = OneVsRestClassifier(base_clf).fit(X, Y)
y_pred = clf.predict([[0, 0, 4]])[0]
assert_array_equal(y_pred, [0, 0, 1])
def test_ovr_binary():
# Toy dataset where features correspond directly to labels.
X = np.array([[0, 0, 5], [0, 5, 0], [3, 0, 0], [0, 0, 6], [6, 0, 0]])
y = ["eggs", "spam", "spam", "eggs", "spam"]
Y = np.array([[0, 1, 1, 0, 1]]).T
classes = set("eggs spam".split())
def conduct_test(base_clf, test_predict_proba=False):
clf = OneVsRestClassifier(base_clf).fit(X, y)
assert_equal(set(clf.classes_), classes)
y_pred = clf.predict(np.array([[0, 0, 4]]))[0]
assert_equal(set(y_pred), set("eggs"))
if hasattr(base_clf, 'decision_function'):
dec = clf.decision_function(X)
assert_equal(dec.shape, (5,))
if test_predict_proba:
X_test = np.array([[0, 0, 4]])
probabilities = clf.predict_proba(X_test)
assert_equal(2, len(probabilities[0]))
assert_equal(clf.classes_[np.argmax(probabilities, axis=1)],
clf.predict(X_test))
# test input as label indicator matrix
clf = OneVsRestClassifier(base_clf).fit(X, Y)
y_pred = clf.predict([[3, 0, 0]])[0]
assert_equal(y_pred, 1)
for base_clf in (LinearSVC(random_state=0), LinearRegression(),
Ridge(), ElasticNet()):
conduct_test(base_clf)
for base_clf in (MultinomialNB(), SVC(probability=True),
LogisticRegression()):
conduct_test(base_clf, test_predict_proba=True)
def test_ovr_multilabel():
# Toy dataset where features correspond directly to labels.
X = np.array([[0, 4, 5], [0, 5, 0], [3, 3, 3], [4, 0, 6], [6, 0, 0]])
y = np.array([[0, 1, 1],
[0, 1, 0],
[1, 1, 1],
[1, 0, 1],
[1, 0, 0]])
for base_clf in (MultinomialNB(), LinearSVC(random_state=0),
LinearRegression(), Ridge(),
ElasticNet(), Lasso(alpha=0.5)):
clf = OneVsRestClassifier(base_clf).fit(X, y)
y_pred = clf.predict([[0, 4, 4]])[0]
assert_array_equal(y_pred, [0, 1, 1])
assert_true(clf.multilabel_)
def test_ovr_fit_predict_svc():
ovr = OneVsRestClassifier(svm.SVC())
ovr.fit(iris.data, iris.target)
assert_equal(len(ovr.estimators_), 3)
assert_greater(ovr.score(iris.data, iris.target), .9)
def test_ovr_multilabel_dataset():
base_clf = MultinomialNB(alpha=1)
for au, prec, recall in zip((True, False), (0.51, 0.66), (0.51, 0.80)):
X, Y = datasets.make_multilabel_classification(n_samples=100,
n_features=20,
n_classes=5,
n_labels=2,
length=50,
allow_unlabeled=au,
random_state=0)
X_train, Y_train = X[:80], Y[:80]
X_test, Y_test = X[80:], Y[80:]
clf = OneVsRestClassifier(base_clf).fit(X_train, Y_train)
Y_pred = clf.predict(X_test)
assert_true(clf.multilabel_)
assert_almost_equal(precision_score(Y_test, Y_pred, average="micro"),
prec,
decimal=2)
assert_almost_equal(recall_score(Y_test, Y_pred, average="micro"),
recall,
decimal=2)
def test_ovr_multilabel_predict_proba():
base_clf = MultinomialNB(alpha=1)
for au in (False, True):
X, Y = datasets.make_multilabel_classification(n_samples=100,
n_features=20,
n_classes=5,
n_labels=3,
length=50,
allow_unlabeled=au,
random_state=0)
X_train, Y_train = X[:80], Y[:80]
X_test = X[80:]
clf = OneVsRestClassifier(base_clf).fit(X_train, Y_train)
# Decision function only estimator.
decision_only = OneVsRestClassifier(svm.SVR()).fit(X_train, Y_train)
assert_false(hasattr(decision_only, 'predict_proba'))
# Estimator with predict_proba disabled, depending on parameters.
decision_only = OneVsRestClassifier(svm.SVC(probability=False))
assert_false(hasattr(decision_only, 'predict_proba'))
decision_only.fit(X_train, Y_train)
assert_false(hasattr(decision_only, 'predict_proba'))
assert_true(hasattr(decision_only, 'decision_function'))
# Estimator which can get predict_proba enabled after fitting
gs = GridSearchCV(svm.SVC(probability=False),
param_grid={'probability': [True]})
proba_after_fit = OneVsRestClassifier(gs)
assert_false(hasattr(proba_after_fit, 'predict_proba'))
proba_after_fit.fit(X_train, Y_train)
assert_true(hasattr(proba_after_fit, 'predict_proba'))
Y_pred = clf.predict(X_test)
Y_proba = clf.predict_proba(X_test)
# predict assigns a label if the probability that the
# sample has the label is greater than 0.5.
pred = Y_proba > .5
assert_array_equal(pred, Y_pred)
def test_ovr_single_label_predict_proba():
base_clf = MultinomialNB(alpha=1)
X, Y = iris.data, iris.target
X_train, Y_train = X[:80], Y[:80]
X_test = X[80:]
clf = OneVsRestClassifier(base_clf).fit(X_train, Y_train)
# Decision function only estimator.
decision_only = OneVsRestClassifier(svm.SVR()).fit(X_train, Y_train)
assert_false(hasattr(decision_only, 'predict_proba'))
Y_pred = clf.predict(X_test)
Y_proba = clf.predict_proba(X_test)
assert_almost_equal(Y_proba.sum(axis=1), 1.0)
# predict assigns a label if the probability that the
# sample has the label is greater than 0.5.
pred = np.array([l.argmax() for l in Y_proba])
assert_false((pred - Y_pred).any())
def test_ovr_multilabel_decision_function():
X, Y = datasets.make_multilabel_classification(n_samples=100,
n_features=20,
n_classes=5,
n_labels=3,
length=50,
allow_unlabeled=True,
random_state=0)
X_train, Y_train = X[:80], Y[:80]
X_test = X[80:]
clf = OneVsRestClassifier(svm.SVC()).fit(X_train, Y_train)
assert_array_equal((clf.decision_function(X_test) > 0).astype(int),
clf.predict(X_test))
def test_ovr_single_label_decision_function():
X, Y = datasets.make_classification(n_samples=100,
n_features=20,
random_state=0)
X_train, Y_train = X[:80], Y[:80]
X_test = X[80:]
clf = OneVsRestClassifier(svm.SVC()).fit(X_train, Y_train)
assert_array_equal(clf.decision_function(X_test).ravel() > 0,
clf.predict(X_test))
def test_ovr_gridsearch():
ovr = OneVsRestClassifier(LinearSVC(random_state=0))
Cs = [0.1, 0.5, 0.8]
cv = GridSearchCV(ovr, {'estimator__C': Cs})
cv.fit(iris.data, iris.target)
best_C = cv.best_estimator_.estimators_[0].C
assert_true(best_C in Cs)
def test_ovr_pipeline():
# Test with pipeline of length one
# This test is needed because the multiclass estimators may fail to detect
# the presence of predict_proba or decision_function.
clf = Pipeline([("tree", DecisionTreeClassifier())])
ovr_pipe = OneVsRestClassifier(clf)
ovr_pipe.fit(iris.data, iris.target)
ovr = OneVsRestClassifier(DecisionTreeClassifier())
ovr.fit(iris.data, iris.target)
assert_array_equal(ovr.predict(iris.data), ovr_pipe.predict(iris.data))
def test_ovr_coef_():
for base_classifier in [SVC(kernel='linear', random_state=0),
LinearSVC(random_state=0)]:
# SVC has sparse coef with sparse input data
ovr = OneVsRestClassifier(base_classifier)
for X in [iris.data, sp.csr_matrix(iris.data)]:
# test with dense and sparse coef
ovr.fit(X, iris.target)
shape = ovr.coef_.shape
assert_equal(shape[0], n_classes)
assert_equal(shape[1], iris.data.shape[1])
# don't densify sparse coefficients
assert_equal(sp.issparse(ovr.estimators_[0].coef_),
sp.issparse(ovr.coef_))
def test_ovr_coef_exceptions():
# Not fitted exception!
ovr = OneVsRestClassifier(LinearSVC(random_state=0))
# lambda is needed because we don't want coef_ to be evaluated right away
assert_raises(ValueError, lambda x: ovr.coef_, None)
# Doesn't have coef_ exception!
ovr = OneVsRestClassifier(DecisionTreeClassifier())
ovr.fit(iris.data, iris.target)
assert_raises(AttributeError, lambda x: ovr.coef_, None)
def test_ovo_exceptions():
ovo = OneVsOneClassifier(LinearSVC(random_state=0))
assert_raises(ValueError, ovo.predict, [])
def test_ovo_fit_on_list():
# Test that OneVsOne fitting works with a list of targets and yields the
# same output as predict from an array
ovo = OneVsOneClassifier(LinearSVC(random_state=0))
prediction_from_array = ovo.fit(iris.data, iris.target).predict(iris.data)
iris_data_list = [list(a) for a in iris.data]
prediction_from_list = ovo.fit(iris_data_list,
list(iris.target)).predict(iris_data_list)
assert_array_equal(prediction_from_array, prediction_from_list)
def test_ovo_fit_predict():
# A classifier which implements decision_function.
ovo = OneVsOneClassifier(LinearSVC(random_state=0))
ovo.fit(iris.data, iris.target).predict(iris.data)
assert_equal(len(ovo.estimators_), n_classes * (n_classes - 1) / 2)
# A classifier which implements predict_proba.
ovo = OneVsOneClassifier(MultinomialNB())
ovo.fit(iris.data, iris.target).predict(iris.data)
assert_equal(len(ovo.estimators_), n_classes * (n_classes - 1) / 2)
def test_ovo_partial_fit_predict():
temp = datasets.load_iris()
X, y = temp.data, temp.target
ovo1 = OneVsOneClassifier(MultinomialNB())
ovo1.partial_fit(X[:100], y[:100], np.unique(y))
ovo1.partial_fit(X[100:], y[100:])
pred1 = ovo1.predict(X)
ovo2 = OneVsOneClassifier(MultinomialNB())
ovo2.fit(X, y)
pred2 = ovo2.predict(X)
assert_equal(len(ovo1.estimators_), n_classes * (n_classes - 1) / 2)
assert_greater(np.mean(y == pred1), 0.65)
assert_almost_equal(pred1, pred2)
# Test when mini-batches have binary target classes
ovo1 = OneVsOneClassifier(MultinomialNB())
ovo1.partial_fit(X[:60], y[:60], np.unique(y))
ovo1.partial_fit(X[60:], y[60:])
pred1 = ovo1.predict(X)
ovo2 = OneVsOneClassifier(MultinomialNB())
pred2 = ovo2.fit(X, y).predict(X)
assert_almost_equal(pred1, pred2)
assert_equal(len(ovo1.estimators_), len(np.unique(y)))
assert_greater(np.mean(y == pred1), 0.65)
ovo = OneVsOneClassifier(MultinomialNB())
X = np.random.rand(14, 2)
y = [1, 1, 2, 3, 3, 0, 0, 4, 4, 4, 4, 4, 2, 2]
ovo.partial_fit(X[:7], y[:7], [0, 1, 2, 3, 4])
ovo.partial_fit(X[7:], y[7:])
pred = ovo.predict(X)
ovo2 = OneVsOneClassifier(MultinomialNB())
pred2 = ovo2.fit(X, y).predict(X)
assert_almost_equal(pred, pred2)
# raises error when mini-batch does not have classes from all_classes
ovo = OneVsOneClassifier(MultinomialNB())
error_y = [0, 1, 2, 3, 4, 5, 2]
message_re = escape("Mini-batch contains {0} while "
"it must be subset of {1}".format(np.unique(error_y),
np.unique(y)))
assert_raises_regexp(ValueError, message_re, ovo.partial_fit, X[:7],
error_y, np.unique(y))
# test partial_fit only exists if estimator has it:
ovr = OneVsOneClassifier(SVC())
assert_false(hasattr(ovr, "partial_fit"))
def test_ovo_decision_function():
n_samples = iris.data.shape[0]
ovo_clf = OneVsOneClassifier(LinearSVC(random_state=0))
# first binary
ovo_clf.fit(iris.data, iris.target == 0)
decisions = ovo_clf.decision_function(iris.data)
assert_equal(decisions.shape, (n_samples,))
# then multi-class
ovo_clf.fit(iris.data, iris.target)
decisions = ovo_clf.decision_function(iris.data)
assert_equal(decisions.shape, (n_samples, n_classes))
assert_array_equal(decisions.argmax(axis=1), ovo_clf.predict(iris.data))
# Compute the votes
votes = np.zeros((n_samples, n_classes))
k = 0
for i in range(n_classes):
for j in range(i + 1, n_classes):
pred = ovo_clf.estimators_[k].predict(iris.data)
votes[pred == 0, i] += 1
votes[pred == 1, j] += 1
k += 1
# Extract votes and verify
assert_array_equal(votes, np.round(decisions))
for class_idx in range(n_classes):
# For each sample and each class, there only 3 possible vote levels
# because they are only 3 distinct class pairs thus 3 distinct
# binary classifiers.
# Therefore, sorting predictions based on votes would yield
# mostly tied predictions:
assert_true(set(votes[:, class_idx]).issubset(set([0., 1., 2.])))
# The OVO decision function on the other hand is able to resolve
# most of the ties on this data as it combines both the vote counts
# and the aggregated confidence levels of the binary classifiers
# to compute the aggregate decision function. The iris dataset
# has 150 samples with a couple of duplicates. The OvO decisions
# can resolve most of the ties:
assert_greater(len(np.unique(decisions[:, class_idx])), 146)
def test_ovo_gridsearch():
ovo = OneVsOneClassifier(LinearSVC(random_state=0))
Cs = [0.1, 0.5, 0.8]
cv = GridSearchCV(ovo, {'estimator__C': Cs})
cv.fit(iris.data, iris.target)
best_C = cv.best_estimator_.estimators_[0].C
assert_true(best_C in Cs)
def test_ovo_ties():
# Test that ties are broken using the decision function,
# not defaulting to the smallest label
X = np.array([[1, 2], [2, 1], [-2, 1], [-2, -1]])
y = np.array([2, 0, 1, 2])
multi_clf = OneVsOneClassifier(Perceptron(shuffle=False, max_iter=4,
tol=None))
ovo_prediction = multi_clf.fit(X, y).predict(X)
ovo_decision = multi_clf.decision_function(X)
# Classifiers are in order 0-1, 0-2, 1-2
# Use decision_function to compute the votes and the normalized
# sum_of_confidences, which is used to disambiguate when there is a tie in
# votes.
votes = np.round(ovo_decision)
normalized_confidences = ovo_decision - votes
# For the first point, there is one vote per class
assert_array_equal(votes[0, :], 1)
# For the rest, there is no tie and the prediction is the argmax
assert_array_equal(np.argmax(votes[1:], axis=1), ovo_prediction[1:])
# For the tie, the prediction is the class with the highest score
assert_equal(ovo_prediction[0], normalized_confidences[0].argmax())
def test_ovo_ties2():
# test that ties can not only be won by the first two labels
X = np.array([[1, 2], [2, 1], [-2, 1], [-2, -1]])
y_ref = np.array([2, 0, 1, 2])
# cycle through labels so that each label wins once
for i in range(3):
y = (y_ref + i) % 3
multi_clf = OneVsOneClassifier(Perceptron(shuffle=False, max_iter=4,
tol=None))
ovo_prediction = multi_clf.fit(X, y).predict(X)
assert_equal(ovo_prediction[0], i % 3)
def test_ovo_string_y():
# Test that the OvO doesn't mess up the encoding of string labels
X = np.eye(4)
y = np.array(['a', 'b', 'c', 'd'])
ovo = OneVsOneClassifier(LinearSVC())
ovo.fit(X, y)
assert_array_equal(y, ovo.predict(X))
def test_ovo_one_class():
# Test error for OvO with one class
X = np.eye(4)
y = np.array(['a'] * 4)
ovo = OneVsOneClassifier(LinearSVC())
assert_raise_message(ValueError, "when only one class", ovo.fit, X, y)
def test_ovo_float_y():
# Test that the OvO errors on float targets
X = iris.data
y = iris.data[:, 0]
ovo = OneVsOneClassifier(LinearSVC())
assert_raise_message(ValueError, "Unknown label type", ovo.fit, X, y)
def test_ecoc_exceptions():
ecoc = OutputCodeClassifier(LinearSVC(random_state=0))
assert_raises(ValueError, ecoc.predict, [])
def test_ecoc_fit_predict():
# A classifier which implements decision_function.
ecoc = OutputCodeClassifier(LinearSVC(random_state=0),
code_size=2, random_state=0)
ecoc.fit(iris.data, iris.target).predict(iris.data)
assert_equal(len(ecoc.estimators_), n_classes * 2)
# A classifier which implements predict_proba.
ecoc = OutputCodeClassifier(MultinomialNB(), code_size=2, random_state=0)
ecoc.fit(iris.data, iris.target).predict(iris.data)
assert_equal(len(ecoc.estimators_), n_classes * 2)
def test_ecoc_gridsearch():
ecoc = OutputCodeClassifier(LinearSVC(random_state=0),
random_state=0)
Cs = [0.1, 0.5, 0.8]
cv = GridSearchCV(ecoc, {'estimator__C': Cs})
cv.fit(iris.data, iris.target)
best_C = cv.best_estimator_.estimators_[0].C
assert_true(best_C in Cs)
def test_ecoc_float_y():
# Test that the OCC errors on float targets
X = iris.data
y = iris.data[:, 0]
ovo = OutputCodeClassifier(LinearSVC())
assert_raise_message(ValueError, "Unknown label type", ovo.fit, X, y)
def test_pairwise_indices():
clf_precomputed = svm.SVC(kernel='precomputed')
X, y = iris.data, iris.target
ovr_false = OneVsOneClassifier(clf_precomputed)
linear_kernel = np.dot(X, X.T)
ovr_false.fit(linear_kernel, y)
n_estimators = len(ovr_false.estimators_)
precomputed_indices = ovr_false.pairwise_indices_
for idx in precomputed_indices:
assert_equal(idx.shape[0] * n_estimators / (n_estimators - 1),
linear_kernel.shape[0])
def test_pairwise_attribute():
clf_precomputed = svm.SVC(kernel='precomputed')
clf_notprecomputed = svm.SVC()
for MultiClassClassifier in [OneVsRestClassifier, OneVsOneClassifier]:
ovr_false = MultiClassClassifier(clf_notprecomputed)
assert_false(ovr_false._pairwise)
ovr_true = MultiClassClassifier(clf_precomputed)
assert_true(ovr_true._pairwise)
def test_pairwise_cross_val_score():
clf_precomputed = svm.SVC(kernel='precomputed')
clf_notprecomputed = svm.SVC(kernel='linear')
X, y = iris.data, iris.target
for MultiClassClassifier in [OneVsRestClassifier, OneVsOneClassifier]:
ovr_false = MultiClassClassifier(clf_notprecomputed)
ovr_true = MultiClassClassifier(clf_precomputed)
linear_kernel = np.dot(X, X.T)
score_precomputed = cross_val_score(ovr_true, linear_kernel, y)
score_linear = cross_val_score(ovr_false, X, y)
assert_array_equal(score_precomputed, score_linear)
| bsd-3-clause |
keishi/chromium | gpu/command_buffer/service/query_manager.cc | 10030 | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "gpu/command_buffer/service/query_manager.h"
#include "base/atomicops.h"
#include "base/logging.h"
#include "base/time.h"
#include "gpu/command_buffer/common/gles2_cmd_format.h"
#include "gpu/command_buffer/service/gles2_cmd_decoder.h"
#include "gpu/command_buffer/service/feature_info.h"
namespace gpu {
namespace gles2 {
class AllSamplesPassedQuery : public QueryManager::Query {
public:
AllSamplesPassedQuery(
QueryManager* manager, GLenum target, int32 shm_id, uint32 shm_offset,
GLuint service_id);
virtual bool Begin() OVERRIDE;
virtual bool End(uint32 submit_count) OVERRIDE;
virtual bool Process() OVERRIDE;
virtual void Destroy(bool have_context) OVERRIDE;
protected:
virtual ~AllSamplesPassedQuery();
private:
// Service side query id.
GLuint service_id_;
};
AllSamplesPassedQuery::AllSamplesPassedQuery(
QueryManager* manager, GLenum target, int32 shm_id, uint32 shm_offset,
GLuint service_id)
: Query(manager, target, shm_id, shm_offset),
service_id_(service_id) {
}
bool AllSamplesPassedQuery::Begin() {
BeginQueryHelper(target(), service_id_);
return true;
}
bool AllSamplesPassedQuery::End(uint32 submit_count) {
EndQueryHelper(target());
return AddToPendingQueue(submit_count);
}
bool AllSamplesPassedQuery::Process() {
GLuint available = 0;
glGetQueryObjectuivARB(
service_id_, GL_QUERY_RESULT_AVAILABLE_EXT, &available);
if (!available) {
return true;
}
GLuint result = 0;
glGetQueryObjectuivARB(
service_id_, GL_QUERY_RESULT_EXT, &result);
return MarkAsCompleted(result != 0);
}
void AllSamplesPassedQuery::Destroy(bool have_context) {
if (have_context && !IsDeleted()) {
glDeleteQueriesARB(1, &service_id_);
MarkAsDeleted();
}
}
AllSamplesPassedQuery::~AllSamplesPassedQuery() {
}
class CommandsIssuedQuery : public QueryManager::Query {
public:
CommandsIssuedQuery(
QueryManager* manager, GLenum target, int32 shm_id, uint32 shm_offset);
virtual bool Begin() OVERRIDE;
virtual bool End(uint32 submit_count) OVERRIDE;
virtual bool Process() OVERRIDE;
virtual void Destroy(bool have_context) OVERRIDE;
protected:
virtual ~CommandsIssuedQuery();
private:
base::TimeTicks begin_time_;
};
CommandsIssuedQuery::CommandsIssuedQuery(
QueryManager* manager, GLenum target, int32 shm_id, uint32 shm_offset)
: Query(manager, target, shm_id, shm_offset) {
}
bool CommandsIssuedQuery::Begin() {
begin_time_ = base::TimeTicks::HighResNow();
return true;
}
bool CommandsIssuedQuery::End(uint32 submit_count) {
base::TimeDelta elapsed = base::TimeTicks::HighResNow() - begin_time_;
MarkAsPending(submit_count);
return MarkAsCompleted(
std::min(elapsed.InMicroseconds(), static_cast<int64>(0xFFFFFFFFL)));
}
bool CommandsIssuedQuery::Process() {
NOTREACHED();
return true;
}
void CommandsIssuedQuery::Destroy(bool /* have_context */) {
if (!IsDeleted()) {
MarkAsDeleted();
}
}
CommandsIssuedQuery::~CommandsIssuedQuery() {
}
class GetErrorQuery : public QueryManager::Query {
public:
GetErrorQuery(
QueryManager* manager, GLenum target, int32 shm_id, uint32 shm_offset);
virtual bool Begin() OVERRIDE;
virtual bool End(uint32 submit_count) OVERRIDE;
virtual bool Process() OVERRIDE;
virtual void Destroy(bool have_context) OVERRIDE;
protected:
virtual ~GetErrorQuery();
private:
};
GetErrorQuery::GetErrorQuery(
QueryManager* manager, GLenum target, int32 shm_id, uint32 shm_offset)
: Query(manager, target, shm_id, shm_offset) {
}
bool GetErrorQuery::Begin() {
return true;
}
bool GetErrorQuery::End(uint32 submit_count) {
MarkAsPending(submit_count);
return MarkAsCompleted(manager()->decoder()->GetGLError());
}
bool GetErrorQuery::Process() {
NOTREACHED();
return true;
}
void GetErrorQuery::Destroy(bool /* have_context */) {
if (!IsDeleted()) {
MarkAsDeleted();
}
}
GetErrorQuery::~GetErrorQuery() {
}
QueryManager::QueryManager(
GLES2Decoder* decoder,
FeatureInfo* feature_info)
: decoder_(decoder),
use_arb_occlusion_query2_for_occlusion_query_boolean_(
feature_info->feature_flags(
).use_arb_occlusion_query2_for_occlusion_query_boolean),
use_arb_occlusion_query_for_occlusion_query_boolean_(
feature_info->feature_flags(
).use_arb_occlusion_query_for_occlusion_query_boolean),
query_count_(0) {
DCHECK(!(use_arb_occlusion_query_for_occlusion_query_boolean_ &&
use_arb_occlusion_query2_for_occlusion_query_boolean_));
}
QueryManager::~QueryManager() {
DCHECK(queries_.empty());
// If this triggers, that means something is keeping a reference to
// a Query belonging to this.
CHECK_EQ(query_count_, 0u);
}
void QueryManager::Destroy(bool have_context) {
pending_queries_.clear();
while (!queries_.empty()) {
Query* query = queries_.begin()->second;
query->Destroy(have_context);
queries_.erase(queries_.begin());
}
}
QueryManager::Query* QueryManager::CreateQuery(
GLenum target, GLuint client_id, int32 shm_id, uint32 shm_offset) {
Query::Ref query;
switch (target) {
case GL_COMMANDS_ISSUED_CHROMIUM:
query = new CommandsIssuedQuery(this, target, shm_id, shm_offset);
break;
case GL_GET_ERROR_QUERY_CHROMIUM:
query = new GetErrorQuery(this, target, shm_id, shm_offset);
break;
default: {
GLuint service_id = 0;
glGenQueriesARB(1, &service_id);
DCHECK_NE(0u, service_id);
query = new AllSamplesPassedQuery(
this, target, shm_id, shm_offset, service_id);
break;
}
}
std::pair<QueryMap::iterator, bool> result =
queries_.insert(std::make_pair(client_id, query));
DCHECK(result.second);
return query.get();
}
QueryManager::Query* QueryManager::GetQuery(
GLuint client_id) {
QueryMap::iterator it = queries_.find(client_id);
return it != queries_.end() ? it->second : NULL;
}
void QueryManager::RemoveQuery(GLuint client_id) {
QueryMap::iterator it = queries_.find(client_id);
if (it != queries_.end()) {
Query* query = it->second;
RemovePendingQuery(query);
query->MarkAsDeleted();
queries_.erase(it);
}
}
void QueryManager::StartTracking(QueryManager::Query* /* query */) {
++query_count_;
}
void QueryManager::StopTracking(QueryManager::Query* /* query */) {
--query_count_;
}
GLenum QueryManager::AdjustTargetForEmulation(GLenum target) {
switch (target) {
case GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT:
case GL_ANY_SAMPLES_PASSED_EXT:
if (use_arb_occlusion_query2_for_occlusion_query_boolean_) {
// ARB_occlusion_query2 does not have a
// GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT
// target.
target = GL_ANY_SAMPLES_PASSED_EXT;
} else if (use_arb_occlusion_query_for_occlusion_query_boolean_) {
// ARB_occlusion_query does not have a
// GL_ANY_SAMPLES_PASSED_EXT
// target.
target = GL_SAMPLES_PASSED_ARB;
}
break;
default:
break;
}
return target;
}
void QueryManager::BeginQueryHelper(GLenum target, GLuint id) {
target = AdjustTargetForEmulation(target);
glBeginQueryARB(target, id);
}
void QueryManager::EndQueryHelper(GLenum target) {
target = AdjustTargetForEmulation(target);
glEndQueryARB(target);
}
QueryManager::Query::Query(
QueryManager* manager, GLenum target, int32 shm_id, uint32 shm_offset)
: manager_(manager),
target_(target),
shm_id_(shm_id),
shm_offset_(shm_offset),
submit_count_(0),
pending_(false),
deleted_(false) {
DCHECK(manager);
manager_->StartTracking(this);
}
QueryManager::Query::~Query() {
if (manager_) {
manager_->StopTracking(this);
manager_ = NULL;
}
}
bool QueryManager::Query::MarkAsCompleted(GLuint result) {
DCHECK(pending_);
QuerySync* sync = manager_->decoder_->GetSharedMemoryAs<QuerySync*>(
shm_id_, shm_offset_, sizeof(*sync));
if (!sync) {
return false;
}
pending_ = false;
sync->result = result;
// Need a MemoryBarrier here so that sync->result is written before
// sync->process_count.
base::subtle::MemoryBarrier();
sync->process_count = submit_count_;
return true;
}
bool QueryManager::ProcessPendingQueries() {
while (!pending_queries_.empty()) {
Query* query = pending_queries_.front().get();
if (!query->Process()) {
return false;
}
if (query->pending()) {
return true;
}
pending_queries_.pop_front();
}
return true;
}
bool QueryManager::HavePendingQueries() {
return !pending_queries_.empty();
}
bool QueryManager::AddPendingQuery(Query* query, uint32 submit_count) {
DCHECK(query);
DCHECK(!query->IsDeleted());
if (!RemovePendingQuery(query)) {
return false;
}
query->MarkAsPending(submit_count);
pending_queries_.push_back(query);
return true;
}
bool QueryManager::RemovePendingQuery(Query* query) {
DCHECK(query);
if (query->pending()) {
// TODO(gman): Speed this up if this is a common operation. This would only
// happen if you do being/end begin/end on the same query without waiting
// for the first one to finish.
for (QueryQueue::iterator it = pending_queries_.begin();
it != pending_queries_.end(); ++it) {
if (it->get() == query) {
pending_queries_.erase(it);
break;
}
}
if (!query->MarkAsCompleted(0)) {
return false;
}
}
return true;
}
bool QueryManager::BeginQuery(Query* query) {
DCHECK(query);
if (!RemovePendingQuery(query)) {
return false;
}
return query->Begin();
}
bool QueryManager::EndQuery(Query* query, uint32 submit_count) {
DCHECK(query);
if (!RemovePendingQuery(query)) {
return false;
}
return query->End(submit_count);
}
} // namespace gles2
} // namespace gpu
| bsd-3-clause |
LWJGL-CI/lwjgl3 | modules/lwjgl/opencl/src/generated/java/org/lwjgl/opencl/KHRILProgram.java | 4463 | /*
* Copyright LWJGL. All rights reserved.
* License terms: https://www.lwjgl.org/license
* MACHINE GENERATED FILE, DO NOT EDIT
*/
package org.lwjgl.opencl;
import javax.annotation.*;
import java.nio.*;
import org.lwjgl.system.*;
import static org.lwjgl.system.Checks.*;
import static org.lwjgl.system.JNI.*;
import static org.lwjgl.system.MemoryUtil.*;
/**
* Native bindings to the <strong>khr_il_program</strong> extension.
*
* <p>This extension adds the ability to create programs with intermediate language (IL), usually SPIR-V. Further information about the format and contents
* of SPIR-V may be found in the SPIR-V Specification. Information about how SPIR-V modules behave in the OpenCL environment may be found in the OpenCL
* SPIR-V Environment Specification.</p>
*
* <p>This functionality described by this extension is a core feature in OpenCL 2.1.</p>
*/
public class KHRILProgram {
/**
* Accepted as a new {@code param_name} argument to {@link CL10#clGetDeviceInfo GetDeviceInfo}. ({@code char[]})
*
* <p>The intermediate languages that are be supported by {@link #clCreateProgramWithILKHR CreateProgramWithILKHR} for this device.</p>
*
* <p>Returns a space separated list of IL version strings of the form:</p>
*
* <pre><code>
* <IL_Prefix>_<Major_version>.<Minor_version></code></pre>
*
* <p>A device that supports the {@code cl_khr_il_program} extension must support the “SPIR-V” IL prefix.</p>
*/
public static final int CL_DEVICE_IL_VERSION_KHR = 0x105B;
/**
* Accepted as a new {@code param_name} argument to {@link CL10#clGetProgramInfo GetProgramInfo}. ({@code unsigned char[]})
*
* <p>Returns the program IL for programs created with {@link #clCreateProgramWithILKHR CreateProgramWithILKHR}.</p>
*
* <p>If program is created with {@link CL10#clCreateProgramWithSource CreateProgramWithSource}, {@link CL10#clCreateProgramWithBinary CreateProgramWithBinary}, or {@link CL12#clCreateProgramWithBuiltInKernels CreateProgramWithBuiltInKernels}, the memory pointed to by
* {@code param_value} will be unchanged and {@code param_value_size_ret} will be set to zero.</p>
*/
public static final int CL_PROGRAM_IL_KHR = 0x1169;
protected KHRILProgram() {
throw new UnsupportedOperationException();
}
// --- [ clCreateProgramWithILKHR ] ---
/**
* Unsafe version of: {@link #clCreateProgramWithILKHR CreateProgramWithILKHR}
*
* @param length the length of the block of memory pointed to by {@code il}
*/
public static long nclCreateProgramWithILKHR(long context, long il, long length, long errcode_ret) {
long __functionAddress = CL.getICD().clCreateProgramWithILKHR;
if (CHECKS) {
check(__functionAddress);
check(context);
}
return callPPPPP(context, il, length, errcode_ret, __functionAddress);
}
/**
* Creates a new program object for context using the {@code length} bytes of intermediate language pointed to by {@code il}.
*
* @param context must be a valid OpenCL context
* @param il a pointer to a {@code length}-byte block of memory containing intermediate language
* @param errcode_ret will return an appropriate error code. If {@code errcode_ret} is {@code NULL}, no error code is returned.
*/
@NativeType("cl_program")
public static long clCreateProgramWithILKHR(@NativeType("cl_context") long context, @NativeType("void const *") ByteBuffer il, @Nullable @NativeType("cl_int *") IntBuffer errcode_ret) {
if (CHECKS) {
checkSafe(errcode_ret, 1);
}
return nclCreateProgramWithILKHR(context, memAddress(il), il.remaining(), memAddressSafe(errcode_ret));
}
/** Array version of: {@link #clCreateProgramWithILKHR CreateProgramWithILKHR} */
@NativeType("cl_program")
public static long clCreateProgramWithILKHR(@NativeType("cl_context") long context, @NativeType("void const *") ByteBuffer il, @Nullable @NativeType("cl_int *") int[] errcode_ret) {
long __functionAddress = CL.getICD().clCreateProgramWithILKHR;
if (CHECKS) {
check(__functionAddress);
check(context);
checkSafe(errcode_ret, 1);
}
return callPPPPP(context, memAddress(il), (long)il.remaining(), errcode_ret, __functionAddress);
}
} | bsd-3-clause |
axinging/chromium-crosswalk | chrome/browser/ui/webui/chromeos/keyboard_overlay_ui.cc | 20348 | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/ui/webui/chromeos/keyboard_overlay_ui.h"
#include <stddef.h>
#include "ash/display/display_manager.h"
#include "ash/shell.h"
#include "base/bind.h"
#include "base/bind_helpers.h"
#include "base/command_line.h"
#include "base/macros.h"
#include "base/memory/weak_ptr.h"
#include "base/strings/utf_string_conversions.h"
#include "base/values.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/url_constants.h"
#include "chrome/grit/chromium_strings.h"
#include "chrome/grit/generated_resources.h"
#include "chromeos/chromeos_switches.h"
#include "components/prefs/pref_service.h"
#include "content/public/browser/page_navigator.h"
#include "content/public/browser/web_contents.h"
#include "content/public/browser/web_contents_delegate.h"
#include "content/public/browser/web_ui.h"
#include "content/public/browser/web_ui_data_source.h"
#include "content/public/browser/web_ui_message_handler.h"
#include "grit/browser_resources.h"
#include "ui/base/ime/chromeos/ime_keyboard.h"
#include "ui/base/ime/chromeos/input_method_manager.h"
using chromeos::input_method::ModifierKey;
using content::WebUIMessageHandler;
using ui::WebDialogUI;
namespace {
const char kLearnMoreURL[] =
#if defined(OFFICIAL_BUILD)
"chrome-extension://honijodknafkokifofgiaalefdiedpko/"
"main.html?answer=1047364";
#else
"https://support.google.com/chromebook/answer/183101";
#endif
struct ModifierToLabel {
const ModifierKey modifier;
const char* label;
} kModifierToLabels[] = {
{chromeos::input_method::kSearchKey, "search"},
{chromeos::input_method::kControlKey, "ctrl"},
{chromeos::input_method::kAltKey, "alt"},
{chromeos::input_method::kVoidKey, "disabled"},
{chromeos::input_method::kCapsLockKey, "caps lock"},
{chromeos::input_method::kEscapeKey, "esc"},
};
struct I18nContentToMessage {
const char* i18n_content;
int message;
} kI18nContentToMessage[] = {
{ "keyboardOverlayLearnMore", IDS_KEYBOARD_OVERLAY_LEARN_MORE },
{ "keyboardOverlayTitle", IDS_KEYBOARD_OVERLAY_TITLE },
{ "keyboardOverlayEscKeyLabel", IDS_KEYBOARD_OVERLAY_ESC_KEY_LABEL },
{ "keyboardOverlayBackKeyLabel", IDS_KEYBOARD_OVERLAY_BACK_KEY_LABEL },
{ "keyboardOverlayForwardKeyLabel", IDS_KEYBOARD_OVERLAY_FORWARD_KEY_LABEL },
{ "keyboardOverlayReloadKeyLabel", IDS_KEYBOARD_OVERLAY_RELOAD_KEY_LABEL },
{ "keyboardOverlayFullScreenKeyLabel",
IDS_KEYBOARD_OVERLAY_FULL_SCREEN_KEY_LABEL },
{ "keyboardOverlaySwitchWinKeyLabel",
IDS_KEYBOARD_OVERLAY_SWITCH_WIN_KEY_LABEL },
{ "keyboardOverlayBrightDownKeyLabel",
IDS_KEYBOARD_OVERLAY_BRIGHT_DOWN_KEY_LABEL },
{ "keyboardOverlayBrightUpKeyLabel",
IDS_KEYBOARD_OVERLAY_BRIGHT_UP_KEY_LABEL },
{ "keyboardOverlayMuteKeyLabel", IDS_KEYBOARD_OVERLAY_MUTE_KEY_LABEL },
{ "keyboardOverlayVolDownKeyLabel", IDS_KEYBOARD_OVERLAY_VOL_DOWN_KEY_LABEL },
{ "keyboardOverlayVolUpKeyLabel", IDS_KEYBOARD_OVERLAY_VOL_UP_KEY_LABEL },
{ "keyboardOverlayPowerKeyLabel", IDS_KEYBOARD_OVERLAY_POWER_KEY_LABEL },
{ "keyboardOverlayBackspaceKeyLabel",
IDS_KEYBOARD_OVERLAY_BACKSPACE_KEY_LABEL },
{ "keyboardOverlayTabKeyLabel", IDS_KEYBOARD_OVERLAY_TAB_KEY_LABEL },
{ "keyboardOverlaySearchKeyLabel", IDS_KEYBOARD_OVERLAY_SEARCH_KEY_LABEL },
{ "keyboardOverlayEnterKeyLabel", IDS_KEYBOARD_OVERLAY_ENTER_KEY_LABEL },
{ "keyboardOverlayShiftKeyLabel", IDS_KEYBOARD_OVERLAY_SHIFT_KEY_LABEL },
{ "keyboardOverlayCtrlKeyLabel", IDS_KEYBOARD_OVERLAY_CTRL_KEY_LABEL },
{ "keyboardOverlayAltKeyLabel", IDS_KEYBOARD_OVERLAY_ALT_KEY_LABEL },
{ "keyboardOverlayLeftKeyLabel", IDS_KEYBOARD_OVERLAY_LEFT_KEY_LABEL },
{ "keyboardOverlayRightKeyLabel", IDS_KEYBOARD_OVERLAY_RIGHT_KEY_LABEL },
{ "keyboardOverlayUpKeyLabel", IDS_KEYBOARD_OVERLAY_UP_KEY_LABEL },
{ "keyboardOverlayDownKeyLabel", IDS_KEYBOARD_OVERLAY_DOWN_KEY_LABEL },
{ "keyboardOverlayInstructions", IDS_KEYBOARD_OVERLAY_INSTRUCTIONS },
{ "keyboardOverlayInstructionsHide", IDS_KEYBOARD_OVERLAY_INSTRUCTIONS_HIDE },
{ "keyboardOverlayActivateLastShelfItem",
IDS_KEYBOARD_OVERLAY_ACTIVATE_LAST_SHELF_ITEM },
{ "keyboardOverlayActivateLastTab", IDS_KEYBOARD_OVERLAY_ACTIVATE_LAST_TAB },
{ "keyboardOverlayActivateShelfItem1",
IDS_KEYBOARD_OVERLAY_ACTIVATE_SHELF_ITEM_1 },
{ "keyboardOverlayActivateShelfItem2",
IDS_KEYBOARD_OVERLAY_ACTIVATE_SHELF_ITEM_2 },
{ "keyboardOverlayActivateShelfItem3",
IDS_KEYBOARD_OVERLAY_ACTIVATE_SHELF_ITEM_3 },
{ "keyboardOverlayActivateShelfItem4",
IDS_KEYBOARD_OVERLAY_ACTIVATE_SHELF_ITEM_4 },
{ "keyboardOverlayActivateShelfItem5",
IDS_KEYBOARD_OVERLAY_ACTIVATE_SHELF_ITEM_5 },
{ "keyboardOverlayActivateShelfItem6",
IDS_KEYBOARD_OVERLAY_ACTIVATE_SHELF_ITEM_6 },
{ "keyboardOverlayActivateShelfItem7",
IDS_KEYBOARD_OVERLAY_ACTIVATE_SHELF_ITEM_7 },
{ "keyboardOverlayActivateShelfItem8",
IDS_KEYBOARD_OVERLAY_ACTIVATE_SHELF_ITEM_8 },
{ "keyboardOverlayActivateNextTab", IDS_KEYBOARD_OVERLAY_ACTIVATE_NEXT_TAB },
{ "keyboardOverlayActivatePreviousTab",
IDS_KEYBOARD_OVERLAY_ACTIVATE_PREVIOUS_TAB },
{ "keyboardOverlayActivateTab1", IDS_KEYBOARD_OVERLAY_ACTIVATE_TAB_1 },
{ "keyboardOverlayActivateTab2", IDS_KEYBOARD_OVERLAY_ACTIVATE_TAB_2 },
{ "keyboardOverlayActivateTab3", IDS_KEYBOARD_OVERLAY_ACTIVATE_TAB_3 },
{ "keyboardOverlayActivateTab4", IDS_KEYBOARD_OVERLAY_ACTIVATE_TAB_4 },
{ "keyboardOverlayActivateTab5", IDS_KEYBOARD_OVERLAY_ACTIVATE_TAB_5 },
{ "keyboardOverlayActivateTab6", IDS_KEYBOARD_OVERLAY_ACTIVATE_TAB_6 },
{ "keyboardOverlayActivateTab7", IDS_KEYBOARD_OVERLAY_ACTIVATE_TAB_7 },
{ "keyboardOverlayActivateTab8", IDS_KEYBOARD_OVERLAY_ACTIVATE_TAB_8 },
{ "keyboardOverlayAddWwwAndComAndOpenAddress",
IDS_KEYBOARD_OVERLAY_ADD_WWW_AND_COM_AND_OPEN_ADDRESS },
{ "keyboardOverlayBookmarkAllTabs", IDS_KEYBOARD_OVERLAY_BOOKMARK_ALL_TABS },
{ "keyboardOverlayBookmarkCurrentPage",
IDS_KEYBOARD_OVERLAY_BOOKMARK_CURRENT_PAGE },
{ "keyboardOverlayBookmarkManager", IDS_KEYBOARD_OVERLAY_BOOKMARK_MANAGER },
{ "keyboardOverlayCenterWindow", IDS_KEYBOARD_OVERLAY_CENTER_WINDOW },
{ "keyboardOverlayClearBrowsingDataDialog",
IDS_KEYBOARD_OVERLAY_CLEAR_BROWSING_DATA_DIALOG },
{ "keyboardOverlayCloseTab", IDS_KEYBOARD_OVERLAY_CLOSE_TAB },
{ "keyboardOverlayCloseWindow", IDS_KEYBOARD_OVERLAY_CLOSE_WINDOW },
{ "keyboardOverlayContextMenu", IDS_KEYBOARD_OVERLAY_CONTEXT_MENU },
{ "keyboardOverlayCopy", IDS_KEYBOARD_OVERLAY_COPY },
{ "keyboardOverlayCut", IDS_KEYBOARD_OVERLAY_CUT },
{ "keyboardOverlayCycleThroughInputMethods",
IDS_KEYBOARD_OVERLAY_CYCLE_THROUGH_INPUT_METHODS },
{ "keyboardOverlayDecreaseKeyBrightness",
IDS_KEYBOARD_OVERLAY_DECREASE_KEY_BRIGHTNESS },
{ "keyboardOverlayDelete", IDS_KEYBOARD_OVERLAY_DELETE },
{ "keyboardOverlayDeleteWord", IDS_KEYBOARD_OVERLAY_DELETE_WORD },
{ "keyboardOverlayDeveloperTools", IDS_KEYBOARD_OVERLAY_DEVELOPER_TOOLS },
{ "keyboardOverlayDockWindowLeft", IDS_KEYBOARD_OVERLAY_DOCK_WINDOW_LEFT },
{ "keyboardOverlayDockWindowRight", IDS_KEYBOARD_OVERLAY_DOCK_WINDOW_RIGHT },
{ "keyboardOverlayDomInspector", IDS_KEYBOARD_OVERLAY_DOM_INSPECTOR },
{ "keyboardOverlayDownloads", IDS_KEYBOARD_OVERLAY_DOWNLOADS },
{ "keyboardOverlayEnd", IDS_KEYBOARD_OVERLAY_END },
{ "keyboardOverlayF1", IDS_KEYBOARD_OVERLAY_F1 },
{ "keyboardOverlayF10", IDS_KEYBOARD_OVERLAY_F10 },
{ "keyboardOverlayF11", IDS_KEYBOARD_OVERLAY_F11 },
{ "keyboardOverlayF12", IDS_KEYBOARD_OVERLAY_F12 },
{ "keyboardOverlayF2", IDS_KEYBOARD_OVERLAY_F2 },
{ "keyboardOverlayF3", IDS_KEYBOARD_OVERLAY_F3 },
{ "keyboardOverlayF4", IDS_KEYBOARD_OVERLAY_F4 },
{ "keyboardOverlayF5", IDS_KEYBOARD_OVERLAY_F5 },
{ "keyboardOverlayF6", IDS_KEYBOARD_OVERLAY_F6 },
{ "keyboardOverlayF7", IDS_KEYBOARD_OVERLAY_F7 },
{ "keyboardOverlayF8", IDS_KEYBOARD_OVERLAY_F8 },
{ "keyboardOverlayF9", IDS_KEYBOARD_OVERLAY_F9 },
{ "keyboardOverlayFindPreviousText",
IDS_KEYBOARD_OVERLAY_FIND_PREVIOUS_TEXT },
{ "keyboardOverlayFindText", IDS_KEYBOARD_OVERLAY_FIND_TEXT },
{ "keyboardOverlayFindTextAgain", IDS_KEYBOARD_OVERLAY_FIND_TEXT_AGAIN },
{ "keyboardOverlayFocusAddressBar", IDS_KEYBOARD_OVERLAY_FOCUS_ADDRESS_BAR },
{ "keyboardOverlayFocusAddressBarInSearchMode",
IDS_KEYBOARD_OVERLAY_FOCUS_ADDRESS_BAR_IN_SEARCH_MODE },
{ "keyboardOverlayFocusBookmarks", IDS_KEYBOARD_OVERLAY_FOCUS_BOOKMARKS },
{ "keyboardOverlayFocusShelf", IDS_KEYBOARD_OVERLAY_FOCUS_SHELF },
{ "keyboardOverlayFocusNextPane", IDS_KEYBOARD_OVERLAY_FOCUS_NEXT_PANE },
{ "keyboardOverlayFocusPreviousPane",
IDS_KEYBOARD_OVERLAY_FOCUS_PREVIOUS_PANE },
{ "keyboardOverlayFocusToolbar", IDS_KEYBOARD_OVERLAY_FOCUS_TOOLBAR },
{ "keyboardOverlayGoBack", IDS_KEYBOARD_OVERLAY_GO_BACK },
{ "keyboardOverlayGoForward", IDS_KEYBOARD_OVERLAY_GO_FORWARD },
{ "keyboardOverlayHelp", IDS_KEYBOARD_OVERLAY_HELP },
{ "keyboardOverlayHistory", IDS_KEYBOARD_OVERLAY_HISTORY },
{ "keyboardOverlayHome", IDS_KEYBOARD_OVERLAY_HOME },
{ "keyboardOverlayIncreaseKeyBrightness",
IDS_KEYBOARD_OVERLAY_INCREASE_KEY_BRIGHTNESS },
{ "keyboardOverlayInputUnicodeCharacters",
IDS_KEYBOARD_OVERLAY_INPUT_UNICODE_CHARACTERS },
{ "keyboardOverlayInsert", IDS_KEYBOARD_OVERLAY_INSERT },
{ "keyboardOverlayJavascriptConsole",
IDS_KEYBOARD_OVERLAY_JAVASCRIPT_CONSOLE },
{ "keyboardOverlayLockScreen", IDS_KEYBOARD_OVERLAY_LOCK_SCREEN },
{ "keyboardOverlayLockScreenOrPowerOff",
IDS_KEYBOARD_OVERLAY_LOCK_SCREEN_OR_POWER_OFF },
{ "keyboardOverlayMagnifierDecreaseZoom",
IDS_KEYBOARD_OVERLAY_MAGNIFIER_DECREASE_ZOOM },
{ "keyboardOverlayMagnifierIncreaseZoom",
IDS_KEYBOARD_OVERLAY_MAGNIFIER_INCREASE_ZOOM },
{ "keyboardOverlayMaximizeWindow", IDS_KEYBOARD_OVERLAY_MAXIMIZE_WINDOW },
{ "keyboardOverlayMinimizeWindow", IDS_KEYBOARD_OVERLAY_MINIMIZE_WINDOW },
{ "keyboardOverlayMirrorMonitors", IDS_KEYBOARD_OVERLAY_MIRROR_MONITORS },
{ "keyboardOverlayNewIncognitoWindow",
IDS_KEYBOARD_OVERLAY_NEW_INCOGNITO_WINDOW },
{ "keyboardOverlayNewTab", IDS_KEYBOARD_OVERLAY_NEW_TAB },
{ "keyboardOverlayNewTerminal", IDS_KEYBOARD_OVERLAY_NEW_TERMINAL },
{ "keyboardOverlayNewWindow", IDS_KEYBOARD_OVERLAY_NEW_WINDOW },
{ "keyboardOverlayNextUser", IDS_KEYBOARD_OVERLAY_NEXT_USER },
{ "keyboardOverlayNextWindow", IDS_KEYBOARD_OVERLAY_NEXT_WINDOW },
{ "keyboardOverlayNextWord", IDS_KEYBOARD_OVERLAY_NEXT_WORD },
{ "keyboardOverlayOpen", IDS_KEYBOARD_OVERLAY_OPEN },
{ "keyboardOverlayOpenAddressInNewTab",
IDS_KEYBOARD_OVERLAY_OPEN_ADDRESS_IN_NEW_TAB },
{ "keyboardOverlayOpenFileManager", IDS_KEYBOARD_OVERLAY_OPEN_FILE_MANAGER },
{ "keyboardOverlayOpenGoogleCloudPrint",
IDS_KEYBOARD_OVERLAY_OPEN_GOOGLE_CLOUD_PRINT },
{ "keyboardOverlayPageDown", IDS_KEYBOARD_OVERLAY_PAGE_DOWN },
{ "keyboardOverlayPageUp", IDS_KEYBOARD_OVERLAY_PAGE_UP },
{ "keyboardOverlayPaste", IDS_KEYBOARD_OVERLAY_PASTE },
{ "keyboardOverlayPasteAsPlainText",
IDS_KEYBOARD_OVERLAY_PASTE_AS_PLAIN_TEXT },
{ "keyboardOverlayPreviousUser", IDS_KEYBOARD_OVERLAY_PREVIOUS_USER },
{ "keyboardOverlayPreviousWindow", IDS_KEYBOARD_OVERLAY_PREVIOUS_WINDOW },
{ "keyboardOverlayPreviousWord", IDS_KEYBOARD_OVERLAY_PREVIOUS_WORD },
{ "keyboardOverlayPrint", IDS_KEYBOARD_OVERLAY_PRINT },
{ "keyboardOverlayReloadCurrentPage",
IDS_KEYBOARD_OVERLAY_RELOAD_CURRENT_PAGE },
{ "keyboardOverlayReloadBypassingCache",
IDS_KEYBOARD_OVERLAY_RELOAD_BYPASSING_CACHE },
{ "keyboardOverlayReopenLastClosedTab",
IDS_KEYBOARD_OVERLAY_REOPEN_LAST_CLOSED_TAB },
{ "keyboardOverlayReportIssue", IDS_KEYBOARD_OVERLAY_REPORT_ISSUE },
{ "keyboardOverlayResetScreenZoom", IDS_KEYBOARD_OVERLAY_RESET_SCREEN_ZOOM },
{ "keyboardOverlayResetZoom", IDS_KEYBOARD_OVERLAY_RESET_ZOOM },
{ "keyboardOverlayRotateScreen", IDS_KEYBOARD_OVERLAY_ROTATE_SCREEN },
{ "keyboardOverlaySave", IDS_KEYBOARD_OVERLAY_SAVE },
{ "keyboardOverlayScreenshotRegion",
IDS_KEYBOARD_OVERLAY_SCREENSHOT_REGION },
{ "keyboardOverlayScreenshotWindow",
IDS_KEYBOARD_OVERLAY_SCREENSHOT_WINDOW },
{ "keyboardOverlayScrollUpOnePage",
IDS_KEYBOARD_OVERLAY_SCROLL_UP_ONE_PAGE },
{ "keyboardOverlaySelectAll", IDS_KEYBOARD_OVERLAY_SELECT_ALL },
{ "keyboardOverlaySelectPreviousInputMethod",
IDS_KEYBOARD_OVERLAY_SELECT_PREVIOUS_INPUT_METHOD },
{ "keyboardOverlaySelectWordAtATime",
IDS_KEYBOARD_OVERLAY_SELECT_WORD_AT_A_TIME },
{ "keyboardOverlayShowMessageCenter",
IDS_KEYBOARD_OVERLAY_SHOW_MESSAGE_CENTER },
{ "keyboardOverlayShowStatusMenu", IDS_KEYBOARD_OVERLAY_SHOW_STATUS_MENU },
{ "keyboardOverlayShowWrenchMenu", IDS_KEYBOARD_OVERLAY_SHOW_WRENCH_MENU },
{ "keyboardOverlaySignOut", IDS_KEYBOARD_OVERLAY_SIGN_OUT },
{ "keyboardOverlaySuspend", IDS_KEYBOARD_OVERLAY_SUSPEND },
{ "keyboardOverlaySwapPrimaryMonitor",
IDS_KEYBOARD_OVERLAY_SWAP_PRIMARY_MONITOR },
{ "keyboardOverlayTakeScreenshot", IDS_KEYBOARD_OVERLAY_TAKE_SCREENSHOT },
{ "keyboardOverlayTaskManager", IDS_KEYBOARD_OVERLAY_TASK_MANAGER },
{ "keyboardOverlayToggleBookmarkBar",
IDS_KEYBOARD_OVERLAY_TOGGLE_BOOKMARK_BAR },
{ "keyboardOverlayToggleCapsLock", IDS_KEYBOARD_OVERLAY_TOGGLE_CAPS_LOCK },
{ "keyboardOverlayDisableCapsLock", IDS_KEYBOARD_OVERLAY_DISABLE_CAPS_LOCK },
{ "keyboardOverlayToggleChromevoxSpokenFeedback",
IDS_KEYBOARD_OVERLAY_TOGGLE_CHROMEVOX_SPOKEN_FEEDBACK },
{ "keyboardOverlayToggleProjectionTouchHud",
IDS_KEYBOARD_OVERLAY_TOGGLE_PROJECTION_TOUCH_HUD },
{ "keyboardOverlayUndo", IDS_KEYBOARD_OVERLAY_UNDO },
{ "keyboardOverlayViewKeyboardOverlay",
IDS_KEYBOARD_OVERLAY_VIEW_KEYBOARD_OVERLAY },
{ "keyboardOverlayViewSource", IDS_KEYBOARD_OVERLAY_VIEW_SOURCE },
{ "keyboardOverlayWordMove", IDS_KEYBOARD_OVERLAY_WORD_MOVE },
{ "keyboardOverlayZoomIn", IDS_KEYBOARD_OVERLAY_ZOOM_IN },
{ "keyboardOverlayZoomOut", IDS_KEYBOARD_OVERLAY_ZOOM_OUT },
{ "keyboardOverlayZoomScreenIn", IDS_KEYBOARD_OVERLAY_ZOOM_SCREEN_IN },
{ "keyboardOverlayZoomScreenOut", IDS_KEYBOARD_OVERLAY_ZOOM_SCREEN_OUT },
};
bool TopRowKeysAreFunctionKeys(Profile* profile) {
if (!profile)
return false;
const PrefService* prefs = profile->GetPrefs();
return prefs ? prefs->GetBoolean(prefs::kLanguageSendFunctionKeys) : false;
}
std::string ModifierKeyToLabel(ModifierKey modifier) {
for (size_t i = 0; i < arraysize(kModifierToLabels); ++i) {
if (modifier == kModifierToLabels[i].modifier) {
return kModifierToLabels[i].label;
}
}
return "";
}
content::WebUIDataSource* CreateKeyboardOverlayUIHTMLSource(Profile* profile) {
content::WebUIDataSource* source =
content::WebUIDataSource::Create(chrome::kChromeUIKeyboardOverlayHost);
for (size_t i = 0; i < arraysize(kI18nContentToMessage); ++i) {
source->AddLocalizedString(kI18nContentToMessage[i].i18n_content,
kI18nContentToMessage[i].message);
}
source->AddString("keyboardOverlayLearnMoreURL",
base::UTF8ToUTF16(kLearnMoreURL));
source->AddBoolean("keyboardOverlayHasChromeOSDiamondKey",
base::CommandLine::ForCurrentProcess()->HasSwitch(
chromeos::switches::kHasChromeOSDiamondKey));
source->AddBoolean("keyboardOverlayTopRowKeysAreFunctionKeys",
TopRowKeysAreFunctionKeys(profile));
ash::Shell* shell = ash::Shell::GetInstance();
ash::DisplayManager* display_manager = shell->display_manager();
source->AddBoolean("keyboardOverlayIsDisplayUIScalingEnabled",
display_manager->IsDisplayUIScalingEnabled());
source->SetJsonPath("strings.js");
source->AddResourcePath("keyboard_overlay.js", IDR_KEYBOARD_OVERLAY_JS);
source->SetDefaultResource(IDR_KEYBOARD_OVERLAY_HTML);
return source;
}
} // namespace
// The handler for Javascript messages related to the "keyboardoverlay" view.
class KeyboardOverlayHandler
: public WebUIMessageHandler,
public base::SupportsWeakPtr<KeyboardOverlayHandler> {
public:
explicit KeyboardOverlayHandler(Profile* profile);
~KeyboardOverlayHandler() override;
// WebUIMessageHandler implementation.
void RegisterMessages() override;
private:
// Called when the page requires the input method ID corresponding to the
// current input method or keyboard layout during initialization.
void GetInputMethodId(const base::ListValue* args);
// Called when the page requres the information of modifier key remapping
// during the initialization.
void GetLabelMap(const base::ListValue* args);
// Called when the learn more link is clicked.
void OpenLearnMorePage(const base::ListValue* args);
Profile* profile_;
DISALLOW_COPY_AND_ASSIGN(KeyboardOverlayHandler);
};
////////////////////////////////////////////////////////////////////////////////
//
// KeyboardOverlayHandler
//
////////////////////////////////////////////////////////////////////////////////
KeyboardOverlayHandler::KeyboardOverlayHandler(Profile* profile)
: profile_(profile) {
}
KeyboardOverlayHandler::~KeyboardOverlayHandler() {
}
void KeyboardOverlayHandler::RegisterMessages() {
web_ui()->RegisterMessageCallback("getInputMethodId",
base::Bind(&KeyboardOverlayHandler::GetInputMethodId,
base::Unretained(this)));
web_ui()->RegisterMessageCallback("getLabelMap",
base::Bind(&KeyboardOverlayHandler::GetLabelMap,
base::Unretained(this)));
web_ui()->RegisterMessageCallback("openLearnMorePage",
base::Bind(&KeyboardOverlayHandler::OpenLearnMorePage,
base::Unretained(this)));
}
void KeyboardOverlayHandler::GetInputMethodId(const base::ListValue* args) {
chromeos::input_method::InputMethodManager* manager =
chromeos::input_method::InputMethodManager::Get();
const chromeos::input_method::InputMethodDescriptor& descriptor =
manager->GetActiveIMEState()->GetCurrentInputMethod();
base::StringValue param(descriptor.id());
web_ui()->CallJavascriptFunction("initKeyboardOverlayId", param);
}
void KeyboardOverlayHandler::GetLabelMap(const base::ListValue* args) {
DCHECK(profile_);
PrefService* pref_service = profile_->GetPrefs();
typedef std::map<ModifierKey, ModifierKey> ModifierMap;
ModifierMap modifier_map;
modifier_map[chromeos::input_method::kSearchKey] = static_cast<ModifierKey>(
pref_service->GetInteger(prefs::kLanguageRemapSearchKeyTo));
modifier_map[chromeos::input_method::kControlKey] = static_cast<ModifierKey>(
pref_service->GetInteger(prefs::kLanguageRemapControlKeyTo));
modifier_map[chromeos::input_method::kAltKey] = static_cast<ModifierKey>(
pref_service->GetInteger(prefs::kLanguageRemapAltKeyTo));
// TODO(mazda): Support prefs::kLanguageRemapCapsLockKeyTo once Caps Lock is
// added to the overlay UI.
base::DictionaryValue dict;
for (ModifierMap::const_iterator i = modifier_map.begin();
i != modifier_map.end(); ++i) {
dict.SetString(ModifierKeyToLabel(i->first), ModifierKeyToLabel(i->second));
}
web_ui()->CallJavascriptFunction("initIdentifierMap", dict);
}
void KeyboardOverlayHandler::OpenLearnMorePage(const base::ListValue* args) {
web_ui()->GetWebContents()->GetDelegate()->OpenURLFromTab(
web_ui()->GetWebContents(),
content::OpenURLParams(GURL(kLearnMoreURL),
content::Referrer(),
NEW_FOREGROUND_TAB,
ui::PAGE_TRANSITION_LINK,
false));
}
////////////////////////////////////////////////////////////////////////////////
//
// KeyboardOverlayUI
//
////////////////////////////////////////////////////////////////////////////////
KeyboardOverlayUI::KeyboardOverlayUI(content::WebUI* web_ui)
: WebDialogUI(web_ui) {
Profile* profile = Profile::FromWebUI(web_ui);
KeyboardOverlayHandler* handler = new KeyboardOverlayHandler(profile);
web_ui->AddMessageHandler(handler);
// Set up the chrome://keyboardoverlay/ source.
content::WebUIDataSource::Add(profile,
CreateKeyboardOverlayUIHTMLSource(profile));
}
| bsd-3-clause |
hzhao/galago-git | eval/src/main/java/org/lemurproject/galago/core/eval/metric/Recall.java | 1563 | /*
* BSD License (http://www.galagosearch.org/license)
*/
package org.lemurproject.galago.core.eval.metric;
import org.lemurproject.galago.core.eval.QueryJudgments;
import org.lemurproject.galago.core.eval.QueryResults;
/**
* Returns the recall of the retrieval at a given number of documents retrieved.
* The recall is the number of relevant documents retrieved
* divided by the total number of relevant documents for the query.
*
* @param documentsRetrieved The evaluation rank.
* @author trevor, sjh
*/
public class Recall extends QueryEvaluator {
CountRelevantRetrieved relevantRetrieved;
int documentsRetrieved;
public Recall(String metric, int documentsRetrieved) {
super(metric);
this.documentsRetrieved = documentsRetrieved;
this.relevantRetrieved = new CountRelevantRetrieved(documentsRetrieved);
}
public Recall(String metric) {
super(metric);
documentsRetrieved = Integer.MAX_VALUE;
this.relevantRetrieved = new CountRelevantRetrieved(documentsRetrieved);
}
public Recall(int documentsRetrieved) {
super("R" + documentsRetrieved);
this.documentsRetrieved = documentsRetrieved;
this.relevantRetrieved = new CountRelevantRetrieved(documentsRetrieved);
}
@Override
public double evaluate(QueryResults resultList, QueryJudgments judgments) {
if(judgments.getRelevantJudgmentCount() == 0) {
throw new RuntimeException("No judgments for " +judgments.queryName);
}
return relevantRetrieved.evaluate(resultList, judgments) / judgments.getRelevantJudgmentCount();
}
}
| bsd-3-clause |
glemaitre/scikit-learn | sklearn/mixture/tests/test_bayesian_mixture.py | 20177 | # Author: Wei Xue <xuewei4d@gmail.com>
# Thierry Guillemot <thierry.guillemot.work@gmail.com>
# License: BSD 3 clause
import copy
import re
import numpy as np
from scipy.special import gammaln
import pytest
from sklearn.utils._testing import assert_almost_equal
from sklearn.utils._testing import assert_array_equal
from sklearn.metrics.cluster import adjusted_rand_score
from sklearn.mixture._bayesian_mixture import _log_dirichlet_norm
from sklearn.mixture._bayesian_mixture import _log_wishart_norm
from sklearn.mixture import BayesianGaussianMixture
from sklearn.mixture.tests.test_gaussian_mixture import RandomData
from sklearn.exceptions import ConvergenceWarning, NotFittedError
from sklearn.utils._testing import ignore_warnings
COVARIANCE_TYPE = ['full', 'tied', 'diag', 'spherical']
PRIOR_TYPE = ['dirichlet_process', 'dirichlet_distribution']
def test_log_dirichlet_norm():
rng = np.random.RandomState(0)
weight_concentration = rng.rand(2)
expected_norm = (gammaln(np.sum(weight_concentration)) -
np.sum(gammaln(weight_concentration)))
predected_norm = _log_dirichlet_norm(weight_concentration)
assert_almost_equal(expected_norm, predected_norm)
def test_log_wishart_norm():
rng = np.random.RandomState(0)
n_components, n_features = 5, 2
degrees_of_freedom = np.abs(rng.rand(n_components)) + 1.
log_det_precisions_chol = n_features * np.log(range(2, 2 + n_components))
expected_norm = np.empty(5)
for k, (degrees_of_freedom_k, log_det_k) in enumerate(
zip(degrees_of_freedom, log_det_precisions_chol)):
expected_norm[k] = -(
degrees_of_freedom_k * (log_det_k + .5 * n_features * np.log(2.)) +
np.sum(gammaln(.5 * (degrees_of_freedom_k -
np.arange(0, n_features)[:, np.newaxis])), 0))
predected_norm = _log_wishart_norm(degrees_of_freedom,
log_det_precisions_chol, n_features)
assert_almost_equal(expected_norm, predected_norm)
def test_bayesian_mixture_covariance_type():
rng = np.random.RandomState(0)
n_samples, n_features = 10, 2
X = rng.rand(n_samples, n_features)
covariance_type = 'bad_covariance_type'
bgmm = BayesianGaussianMixture(covariance_type=covariance_type,
random_state=rng)
msg = re.escape(
f"Invalid value for 'covariance_type': {covariance_type} "
"'covariance_type' should be in ['spherical', 'tied', 'diag', 'full']"
)
with pytest.raises(ValueError, match=msg):
bgmm.fit(X)
def test_bayesian_mixture_weight_concentration_prior_type():
rng = np.random.RandomState(0)
n_samples, n_features = 10, 2
X = rng.rand(n_samples, n_features)
bad_prior_type = 'bad_prior_type'
bgmm = BayesianGaussianMixture(
weight_concentration_prior_type=bad_prior_type, random_state=rng)
msg = re.escape(
"Invalid value for 'weight_concentration_prior_type':"
f" {bad_prior_type} 'weight_concentration_prior_type' should be in "
"['dirichlet_process', 'dirichlet_distribution']"
)
with pytest.raises(ValueError, match=msg):
bgmm.fit(X)
def test_bayesian_mixture_weights_prior_initialisation():
rng = np.random.RandomState(0)
n_samples, n_components, n_features = 10, 5, 2
X = rng.rand(n_samples, n_features)
# Check raise message for a bad value of weight_concentration_prior
bad_weight_concentration_prior_ = 0.
bgmm = BayesianGaussianMixture(
weight_concentration_prior=bad_weight_concentration_prior_,
random_state=0)
msg = (
"The parameter 'weight_concentration_prior' should be greater "
f"than 0., but got {bad_weight_concentration_prior_:.3f}."
)
with pytest.raises(ValueError, match=msg):
bgmm.fit(X)
# Check correct init for a given value of weight_concentration_prior
weight_concentration_prior = rng.rand()
bgmm = BayesianGaussianMixture(
weight_concentration_prior=weight_concentration_prior,
random_state=rng).fit(X)
assert_almost_equal(weight_concentration_prior,
bgmm.weight_concentration_prior_)
# Check correct init for the default value of weight_concentration_prior
bgmm = BayesianGaussianMixture(n_components=n_components,
random_state=rng).fit(X)
assert_almost_equal(1. / n_components, bgmm.weight_concentration_prior_)
def test_bayesian_mixture_mean_prior_initialisation():
rng = np.random.RandomState(0)
n_samples, n_components, n_features = 10, 3, 2
X = rng.rand(n_samples, n_features)
# Check raise message for a bad value of mean_precision_prior
bad_mean_precision_prior_ = 0.
bgmm = BayesianGaussianMixture(
mean_precision_prior=bad_mean_precision_prior_,
random_state=rng)
msg = (
"The parameter 'mean_precision_prior' "
f"should be greater than 0., but got {bad_mean_precision_prior_:.3f}."
)
with pytest.raises(ValueError, match=msg):
bgmm.fit(X)
# Check correct init for a given value of mean_precision_prior
mean_precision_prior = rng.rand()
bgmm = BayesianGaussianMixture(
mean_precision_prior=mean_precision_prior,
random_state=rng).fit(X)
assert_almost_equal(mean_precision_prior, bgmm.mean_precision_prior_)
# Check correct init for the default value of mean_precision_prior
bgmm = BayesianGaussianMixture(random_state=rng).fit(X)
assert_almost_equal(1., bgmm.mean_precision_prior_)
# Check raise message for a bad shape of mean_prior
mean_prior = rng.rand(n_features + 1)
bgmm = BayesianGaussianMixture(n_components=n_components,
mean_prior=mean_prior,
random_state=rng)
msg = "The parameter 'means' should have the shape of "
with pytest.raises(ValueError, match=msg):
bgmm.fit(X)
# Check correct init for a given value of mean_prior
mean_prior = rng.rand(n_features)
bgmm = BayesianGaussianMixture(n_components=n_components,
mean_prior=mean_prior,
random_state=rng).fit(X)
assert_almost_equal(mean_prior, bgmm.mean_prior_)
# Check correct init for the default value of bemean_priorta
bgmm = BayesianGaussianMixture(n_components=n_components,
random_state=rng).fit(X)
assert_almost_equal(X.mean(axis=0), bgmm.mean_prior_)
def test_bayesian_mixture_precisions_prior_initialisation():
rng = np.random.RandomState(0)
n_samples, n_features = 10, 2
X = rng.rand(n_samples, n_features)
# Check raise message for a bad value of degrees_of_freedom_prior
bad_degrees_of_freedom_prior_ = n_features - 1.
bgmm = BayesianGaussianMixture(
degrees_of_freedom_prior=bad_degrees_of_freedom_prior_,
random_state=rng)
msg = (
"The parameter 'degrees_of_freedom_prior' should be greater than"
f" {n_features -1}, but got {bad_degrees_of_freedom_prior_:.3f}."
)
with pytest.raises(ValueError, match=msg):
bgmm.fit(X)
# Check correct init for a given value of degrees_of_freedom_prior
degrees_of_freedom_prior = rng.rand() + n_features - 1.
bgmm = BayesianGaussianMixture(
degrees_of_freedom_prior=degrees_of_freedom_prior,
random_state=rng).fit(X)
assert_almost_equal(degrees_of_freedom_prior,
bgmm.degrees_of_freedom_prior_)
# Check correct init for the default value of degrees_of_freedom_prior
degrees_of_freedom_prior_default = n_features
bgmm = BayesianGaussianMixture(
degrees_of_freedom_prior=degrees_of_freedom_prior_default,
random_state=rng).fit(X)
assert_almost_equal(degrees_of_freedom_prior_default,
bgmm.degrees_of_freedom_prior_)
# Check correct init for a given value of covariance_prior
covariance_prior = {
'full': np.cov(X.T, bias=1) + 10,
'tied': np.cov(X.T, bias=1) + 5,
'diag': np.diag(np.atleast_2d(np.cov(X.T, bias=1))) + 3,
'spherical': rng.rand()}
bgmm = BayesianGaussianMixture(random_state=rng)
for cov_type in ['full', 'tied', 'diag', 'spherical']:
bgmm.covariance_type = cov_type
bgmm.covariance_prior = covariance_prior[cov_type]
bgmm.fit(X)
assert_almost_equal(covariance_prior[cov_type],
bgmm.covariance_prior_)
# Check raise message for a bad spherical value of covariance_prior
bad_covariance_prior_ = -1.
bgmm = BayesianGaussianMixture(covariance_type='spherical',
covariance_prior=bad_covariance_prior_,
random_state=rng)
msg = (
"The parameter 'spherical covariance_prior' "
f"should be greater than 0., but got {bad_covariance_prior_:.3f}."
)
with pytest.raises(ValueError, match=msg):
bgmm.fit(X)
# Check correct init for the default value of covariance_prior
covariance_prior_default = {
'full': np.atleast_2d(np.cov(X.T)),
'tied': np.atleast_2d(np.cov(X.T)),
'diag': np.var(X, axis=0, ddof=1),
'spherical': np.var(X, axis=0, ddof=1).mean()}
bgmm = BayesianGaussianMixture(random_state=0)
for cov_type in ['full', 'tied', 'diag', 'spherical']:
bgmm.covariance_type = cov_type
bgmm.fit(X)
assert_almost_equal(covariance_prior_default[cov_type],
bgmm.covariance_prior_)
def test_bayesian_mixture_check_is_fitted():
rng = np.random.RandomState(0)
n_samples, n_features = 10, 2
# Check raise message
bgmm = BayesianGaussianMixture(random_state=rng)
X = rng.rand(n_samples, n_features)
msg = "This BayesianGaussianMixture instance is not fitted yet."
with pytest.raises(ValueError, match=msg):
bgmm.score(X)
def test_bayesian_mixture_weights():
rng = np.random.RandomState(0)
n_samples, n_features = 10, 2
X = rng.rand(n_samples, n_features)
# Case Dirichlet distribution for the weight concentration prior type
bgmm = BayesianGaussianMixture(
weight_concentration_prior_type="dirichlet_distribution",
n_components=3, random_state=rng).fit(X)
expected_weights = (bgmm.weight_concentration_ /
np.sum(bgmm.weight_concentration_))
assert_almost_equal(expected_weights, bgmm.weights_)
assert_almost_equal(np.sum(bgmm.weights_), 1.0)
# Case Dirichlet process for the weight concentration prior type
dpgmm = BayesianGaussianMixture(
weight_concentration_prior_type="dirichlet_process",
n_components=3, random_state=rng).fit(X)
weight_dirichlet_sum = (dpgmm.weight_concentration_[0] +
dpgmm.weight_concentration_[1])
tmp = dpgmm.weight_concentration_[1] / weight_dirichlet_sum
expected_weights = (dpgmm.weight_concentration_[0] / weight_dirichlet_sum *
np.hstack((1, np.cumprod(tmp[:-1]))))
expected_weights /= np.sum(expected_weights)
assert_almost_equal(expected_weights, dpgmm.weights_)
assert_almost_equal(np.sum(dpgmm.weights_), 1.0)
@ignore_warnings(category=ConvergenceWarning)
def test_monotonic_likelihood():
# We check that each step of the each step of variational inference without
# regularization improve monotonically the training set of the bound
rng = np.random.RandomState(0)
rand_data = RandomData(rng, scale=20)
n_components = rand_data.n_components
for prior_type in PRIOR_TYPE:
for covar_type in COVARIANCE_TYPE:
X = rand_data.X[covar_type]
bgmm = BayesianGaussianMixture(
weight_concentration_prior_type=prior_type,
n_components=2 * n_components, covariance_type=covar_type,
warm_start=True, max_iter=1, random_state=rng, tol=1e-3)
current_lower_bound = -np.infty
# Do one training iteration at a time so we can make sure that the
# training log likelihood increases after each iteration.
for _ in range(600):
prev_lower_bound = current_lower_bound
current_lower_bound = bgmm.fit(X).lower_bound_
assert current_lower_bound >= prev_lower_bound
if bgmm.converged_:
break
assert(bgmm.converged_)
def test_compare_covar_type():
# We can compare the 'full' precision with the other cov_type if we apply
# 1 iter of the M-step (done during _initialize_parameters).
rng = np.random.RandomState(0)
rand_data = RandomData(rng, scale=7)
X = rand_data.X['full']
n_components = rand_data.n_components
for prior_type in PRIOR_TYPE:
# Computation of the full_covariance
bgmm = BayesianGaussianMixture(
weight_concentration_prior_type=prior_type,
n_components=2 * n_components, covariance_type='full',
max_iter=1, random_state=0, tol=1e-7)
bgmm._check_initial_parameters(X)
bgmm._initialize_parameters(X, np.random.RandomState(0))
full_covariances = (
bgmm.covariances_ *
bgmm.degrees_of_freedom_[:, np.newaxis, np.newaxis])
# Check tied_covariance = mean(full_covariances, 0)
bgmm = BayesianGaussianMixture(
weight_concentration_prior_type=prior_type,
n_components=2 * n_components, covariance_type='tied',
max_iter=1, random_state=0, tol=1e-7)
bgmm._check_initial_parameters(X)
bgmm._initialize_parameters(X, np.random.RandomState(0))
tied_covariance = bgmm.covariances_ * bgmm.degrees_of_freedom_
assert_almost_equal(tied_covariance, np.mean(full_covariances, 0))
# Check diag_covariance = diag(full_covariances)
bgmm = BayesianGaussianMixture(
weight_concentration_prior_type=prior_type,
n_components=2 * n_components, covariance_type='diag',
max_iter=1, random_state=0, tol=1e-7)
bgmm._check_initial_parameters(X)
bgmm._initialize_parameters(X, np.random.RandomState(0))
diag_covariances = (bgmm.covariances_ *
bgmm.degrees_of_freedom_[:, np.newaxis])
assert_almost_equal(diag_covariances,
np.array([np.diag(cov)
for cov in full_covariances]))
# Check spherical_covariance = np.mean(diag_covariances, 0)
bgmm = BayesianGaussianMixture(
weight_concentration_prior_type=prior_type,
n_components=2 * n_components, covariance_type='spherical',
max_iter=1, random_state=0, tol=1e-7)
bgmm._check_initial_parameters(X)
bgmm._initialize_parameters(X, np.random.RandomState(0))
spherical_covariances = bgmm.covariances_ * bgmm.degrees_of_freedom_
assert_almost_equal(
spherical_covariances, np.mean(diag_covariances, 1))
@ignore_warnings(category=ConvergenceWarning)
def test_check_covariance_precision():
# We check that the dot product of the covariance and the precision
# matrices is identity.
rng = np.random.RandomState(0)
rand_data = RandomData(rng, scale=7)
n_components, n_features = 2 * rand_data.n_components, 2
# Computation of the full_covariance
bgmm = BayesianGaussianMixture(n_components=n_components,
max_iter=100, random_state=rng, tol=1e-3,
reg_covar=0)
for covar_type in COVARIANCE_TYPE:
bgmm.covariance_type = covar_type
bgmm.fit(rand_data.X[covar_type])
if covar_type == 'full':
for covar, precision in zip(bgmm.covariances_, bgmm.precisions_):
assert_almost_equal(np.dot(covar, precision),
np.eye(n_features))
elif covar_type == 'tied':
assert_almost_equal(np.dot(bgmm.covariances_, bgmm.precisions_),
np.eye(n_features))
elif covar_type == 'diag':
assert_almost_equal(bgmm.covariances_ * bgmm.precisions_,
np.ones((n_components, n_features)))
else:
assert_almost_equal(bgmm.covariances_ * bgmm.precisions_,
np.ones(n_components))
@ignore_warnings(category=ConvergenceWarning)
def test_invariant_translation():
# We check here that adding a constant in the data change correctly the
# parameters of the mixture
rng = np.random.RandomState(0)
rand_data = RandomData(rng, scale=100)
n_components = 2 * rand_data.n_components
for prior_type in PRIOR_TYPE:
for covar_type in COVARIANCE_TYPE:
X = rand_data.X[covar_type]
bgmm1 = BayesianGaussianMixture(
weight_concentration_prior_type=prior_type,
n_components=n_components, max_iter=100, random_state=0,
tol=1e-3, reg_covar=0).fit(X)
bgmm2 = BayesianGaussianMixture(
weight_concentration_prior_type=prior_type,
n_components=n_components, max_iter=100, random_state=0,
tol=1e-3, reg_covar=0).fit(X + 100)
assert_almost_equal(bgmm1.means_, bgmm2.means_ - 100)
assert_almost_equal(bgmm1.weights_, bgmm2.weights_)
assert_almost_equal(bgmm1.covariances_, bgmm2.covariances_)
@pytest.mark.filterwarnings("ignore:.*did not converge.*")
@pytest.mark.parametrize('seed, max_iter, tol', [
(0, 2, 1e-7), # strict non-convergence
(1, 2, 1e-1), # loose non-convergence
(3, 300, 1e-7), # strict convergence
(4, 300, 1e-1), # loose convergence
])
def test_bayesian_mixture_fit_predict(seed, max_iter, tol):
rng = np.random.RandomState(seed)
rand_data = RandomData(rng, n_samples=50, scale=7)
n_components = 2 * rand_data.n_components
for covar_type in COVARIANCE_TYPE:
bgmm1 = BayesianGaussianMixture(n_components=n_components,
max_iter=max_iter, random_state=rng,
tol=tol, reg_covar=0)
bgmm1.covariance_type = covar_type
bgmm2 = copy.deepcopy(bgmm1)
X = rand_data.X[covar_type]
Y_pred1 = bgmm1.fit(X).predict(X)
Y_pred2 = bgmm2.fit_predict(X)
assert_array_equal(Y_pred1, Y_pred2)
def test_bayesian_mixture_fit_predict_n_init():
# Check that fit_predict is equivalent to fit.predict, when n_init > 1
X = np.random.RandomState(0).randn(50, 5)
gm = BayesianGaussianMixture(n_components=5, n_init=10, random_state=0)
y_pred1 = gm.fit_predict(X)
y_pred2 = gm.predict(X)
assert_array_equal(y_pred1, y_pred2)
def test_bayesian_mixture_predict_predict_proba():
# this is the same test as test_gaussian_mixture_predict_predict_proba()
rng = np.random.RandomState(0)
rand_data = RandomData(rng)
for prior_type in PRIOR_TYPE:
for covar_type in COVARIANCE_TYPE:
X = rand_data.X[covar_type]
Y = rand_data.Y
bgmm = BayesianGaussianMixture(
n_components=rand_data.n_components,
random_state=rng,
weight_concentration_prior_type=prior_type,
covariance_type=covar_type)
# Check a warning message arrive if we don't do fit
msg = (
"This BayesianGaussianMixture instance is not fitted yet. "
"Call 'fit' with appropriate arguments before using this "
"estimator."
)
with pytest.raises(NotFittedError, match=msg):
bgmm.predict(X)
bgmm.fit(X)
Y_pred = bgmm.predict(X)
Y_pred_proba = bgmm.predict_proba(X).argmax(axis=1)
assert_array_equal(Y_pred, Y_pred_proba)
assert adjusted_rand_score(Y, Y_pred) >= .95
| bsd-3-clause |
Spuds/elkarte.net | elk/community/themes/default/scripts/register.js | 12102 | /**
* @name ElkArte Forum
* @copyright ElkArte Forum contributors
* @license BSD http://opensource.org/licenses/BSD-3-Clause
*
* This software is a derived product, based on:
*
* Simple Machines Forum (SMF)
* copyright: 2011 Simple Machines (http://www.simplemachines.org)
* license: BSD, See included LICENSE.TXT for terms and conditions.
*
* @version 1.0 Beta
*
* This file contains javascript associated with the registration screen
*/
/**
* Elk Registration class
*
* @param {string} name of the registration form
* @param {int} passwordDifficultyLevel
* @param {array} regTextStrings
*/
function elkRegister(formID, passwordDifficultyLevel, regTextStrings)
{
this.verificationFields = [];
this.verificationFieldLength = 0;
this.textStrings = regTextStrings ? regTextStrings : [];
this.passwordLevel = passwordDifficultyLevel ? passwordDifficultyLevel : 0;
// Setup all the fields!
this.autoSetup(formID);
}
// This is a field which requires some form of verification check.
elkRegister.prototype.addVerificationField = function(fieldType, fieldID)
{
// Check the field exists.
if (!document.getElementById(fieldID))
return;
// Get the handles.
var inputHandle = document.getElementById(fieldID),
imageHandle = document.getElementById(fieldID + '_img') ? document.getElementById(fieldID + '_img') : false,
divHandle = document.getElementById(fieldID + '_div') ? document.getElementById(fieldID + '_div') : false;
// What is the event handler?
var eventHandler = false;
if (fieldType === 'pwmain')
eventHandler = 'refreshMainPassword';
else if (fieldType === 'pwverify')
eventHandler = 'refreshVerifyPassword';
else if (fieldType === 'username')
eventHandler = 'refreshUsername';
else if (fieldType === 'reserved')
eventHandler = 'refreshMainPassword';
// Store this field.
var vFieldIndex = fieldType === 'reserved' ? fieldType + this.verificationFieldLength : fieldType;
this.verificationFields[vFieldIndex] = Array(6);
this.verificationFields[vFieldIndex][0] = fieldID;
this.verificationFields[vFieldIndex][1] = inputHandle;
this.verificationFields[vFieldIndex][2] = imageHandle;
this.verificationFields[vFieldIndex][3] = divHandle;
this.verificationFields[vFieldIndex][4] = fieldType;
this.verificationFields[vFieldIndex][5] = inputHandle.className;
// Keep a count to it!
this.verificationFieldLength++;
// Step to it!
if (eventHandler)
{
var _self = this;
createEventListener(inputHandle);
inputHandle.addEventListener('keyup', function(event) {_self[eventHandler].call(_self, event);}, false);
this[eventHandler]();
// Username will auto check on blur!
inputHandle.addEventListener('blur', function(event) {_self.autoCheckUsername.call(_self, event);}, false);
}
// Make the div visible!
if (divHandle)
divHandle.style.display = '';
};
// A button to trigger a username search
elkRegister.prototype.addUsernameSearchTrigger = function(elementID)
{
var buttonHandle = document.getElementById(elementID),
_self = this;
// Attach the event to this element.
createEventListener(buttonHandle);
buttonHandle.addEventListener('click', function(event) {_self.checkUsername.call(_self, event);}, false);
};
// This function will automatically pick up all the necessary verification fields and initialise their visual status.
elkRegister.prototype.autoSetup = function(formID)
{
if (!document.getElementById(formID))
return false;
var curElement,
curType;
for (var i = 0, n = document.getElementById(formID).elements.length; i < n; i++)
{
curElement = document.getElementById(formID).elements[i];
// Does the ID contain the keyword 'autov'?
if (curElement.id.indexOf('autov') !== -1 && (curElement.type === 'text' || curElement.type === 'password'))
{
// This is probably it - but does it contain a field type?
curType = 0;
// Username can only be done with XML.
if (curElement.id.indexOf('username') !== -1)
curType = 'username';
else if (curElement.id.indexOf('pwmain') !== -1)
curType = 'pwmain';
else if (curElement.id.indexOf('pwverify') !== -1)
curType = 'pwverify';
// This means this field is reserved and cannot be contained in the password!
else if (curElement.id.indexOf('reserve') !== -1)
curType = 'reserved';
// If we're happy let's add this element!
if (curType)
this.addVerificationField(curType, curElement.id);
// If this is the username do we also have a button to find the user?
if (curType === 'username' && document.getElementById(curElement.id + '_link'))
this.addUsernameSearchTrigger(curElement.id + '_link');
}
}
return true;
};
// What is the password state?
elkRegister.prototype.refreshMainPassword = function(called_from_verify)
{
if (!this.verificationFields.pwmain)
return false;
var curPass = this.verificationFields.pwmain[1].value,
stringIndex = '';
// Is it a valid length?
if ((curPass.length < 8 && this.passwordLevel >= 1) || curPass.length < 4)
stringIndex = 'password_short';
// More than basic?
if (this.passwordLevel >= 1)
{
// If there is a username check it's not in the password!
if (this.verificationFields.username && this.verificationFields.username[1].value && curPass.indexOf(this.verificationFields.username[1].value) !== -1)
stringIndex = 'password_reserved';
// Any reserved fields?
for (var i in this.verificationFields)
{
if (this.verificationFields.i[4] === 'reserved' && this.verificationFields.i[1].value && curPass.indexOf(this.verificationFields.i[1].value) !== -1)
stringIndex = 'password_reserved';
}
// Finally - is it hard and as such requiring mixed cases and numbers?
if (this.passwordLevel > 1)
{
if (curPass === curPass.toLowerCase())
stringIndex = 'password_numbercase';
if (!curPass.match(/(\D\d|\d\D)/))
stringIndex = 'password_numbercase';
}
}
var isValid = stringIndex === '' ? true : false;
if (stringIndex === '')
stringIndex = 'password_valid';
// Set the image.
this.setVerificationImage(this.verificationFields.pwmain[2], isValid, this.textStrings[stringIndex] ? this.textStrings[stringIndex] : '');
this.verificationFields.pwmain[1].className = this.verificationFields.pwmain[5] + ' ' + (isValid ? 'valid_input' : 'invalid_input');
// As this has changed the verification one may have too!
if (this.verificationFields.pwverify && !called_from_verify)
this.refreshVerifyPassword();
return isValid;
};
// Check that the verification password matches the main one!
elkRegister.prototype.refreshVerifyPassword = function()
{
// Can't do anything without something to check again!
if (!this.verificationFields.pwmain)
return false;
// Check and set valid status!
var isValid = this.verificationFields.pwmain[1].value === this.verificationFields.pwverify[1].value && this.refreshMainPassword(true),
alt = this.textStrings[isValid === 1 ? 'password_valid' : 'password_no_match'] ? this.textStrings[isValid === 1 ? 'password_valid' : 'password_no_match'] : '';
this.setVerificationImage(this.verificationFields.pwverify[2], isValid, alt);
this.verificationFields.pwverify[1].className = this.verificationFields.pwverify[5] + ' ' + (isValid ? 'valid_input' : 'invalid_input');
return true;
};
// If the username is changed just revert the status of whether it's valid!
elkRegister.prototype.refreshUsername = function()
{
if (!this.verificationFields.username)
return false;
// Restore the class name.
if (this.verificationFields.username[1].className)
this.verificationFields.username[1].className = this.verificationFields.username[5];
// Check the image is correct.
var alt = this.textStrings.username_check ? this.textStrings.username_check : '';
this.setVerificationImage(this.verificationFields.username[2], 'check', alt);
// Check the password is still OK.
this.refreshMainPassword();
return true;
};
// This is a pass through function that ensures we don't do any of the AJAX notification stuff.
elkRegister.prototype.autoCheckUsername = function()
{
this.checkUsername(true);
};
// Check whether the username exists?
elkRegister.prototype.checkUsername = function(is_auto)
{
if (!this.verificationFields.username)
return false;
// Get the username and do nothing without one!
var curUsername = this.verificationFields.username[1].value;
if (!curUsername)
return false;
if (!is_auto)
ajax_indicator(true);
// Request a search on that username.
checkName = curUsername.php_to8bit().php_urlencode();
sendXMLDocument.call(this, elk_prepareScriptUrl(elk_scripturl) + 'action=register;sa=usernamecheck;xml;username=' + checkName, null, this.checkUsernameCallback);
return true;
};
// Callback for getting the username data.
elkRegister.prototype.checkUsernameCallback = function(XMLDoc)
{
if (XMLDoc.getElementsByTagName("username"))
isValid = parseInt(XMLDoc.getElementsByTagName("username")[0].getAttribute("valid"));
else
isValid = true;
// What to alt?
var alt = this.textStrings[isValid === 1 ? 'username_valid' : 'username_invalid'] ? this.textStrings[isValid === 1 ? 'username_valid' : 'username_invalid'] : '';
this.verificationFields.username[1].className = this.verificationFields.username[5] + ' ' + (isValid === 1 ? 'valid_input' : 'invalid_input');
this.setVerificationImage(this.verificationFields.username[2], isValid === 1, alt);
ajax_indicator(false);
};
// Set the image to be the correct type.
elkRegister.prototype.setVerificationImage = function(imageHandle, imageIcon, alt)
{
if (!imageHandle)
return false;
if (!alt)
alt = '*';
var curImage = imageIcon ? (imageIcon === 'check' ? 'field_check.png' : 'field_valid.png') : 'field_invalid.png';
imageHandle.src = elk_images_url + '/icons/' + curImage;
imageHandle.alt = alt;
imageHandle.title = alt;
return true;
};
/**
* Sets up the form fields based on the chosen authentication method, openID or password
*/
function updateAuthMethod()
{
// What authentication method is being used?
if (!document.getElementById('auth_openid') || !document.getElementById('auth_openid').checked)
currentAuthMethod = 'passwd';
else
currentAuthMethod = 'openid';
// No openID?
if (!document.getElementById('auth_openid'))
return true;
currentForm = document.getElementById('auth_openid').form.id;
document.forms[currentForm].openid_url.disabled = currentAuthMethod === 'openid' ? false : true;
document.forms[currentForm].elk_autov_pwmain.disabled = currentAuthMethod === 'passwd' ? false : true;
document.forms[currentForm].elk_autov_pwverify.disabled = currentAuthMethod === 'passwd' ? false : true;
document.getElementById('elk_autov_pwmain_div').style.display = currentAuthMethod === 'passwd' ? '' : 'none';
document.getElementById('elk_autov_pwverify_div').style.display = currentAuthMethod === 'passwd' ? '' : 'none';
if (currentAuthMethod === 'passwd')
{
verificationHandle.refreshMainPassword();
verificationHandle.refreshVerifyPassword();
document.forms[currentForm].openid_url.style.backgroundColor = '';
document.getElementById('password1_group').style.display = '';
document.getElementById('password2_group').style.display = '';
document.getElementById('openid_group').style.display = 'none';
}
else
{
document.forms[currentForm].elk_autov_pwmain.style.backgroundColor = '';
document.forms[currentForm].elk_autov_pwverify.style.backgroundColor = '';
document.forms[currentForm].openid_url.style.backgroundColor = '#FFF0F0';
document.getElementById('password1_group').style.display = 'none';
document.getElementById('password2_group').style.display = 'none';
document.getElementById('openid_group').style.display = '';
}
return true;
}
/**
* Used when the admin registers a new member, enable or disables the email activation
*/
function onCheckChange()
{
if (document.forms.postForm.emailActivate.checked || document.forms.postForm.password.value === '')
{
document.forms.postForm.emailPassword.disabled = true;
document.forms.postForm.emailPassword.checked = true;
}
else
document.forms.postForm.emailPassword.disabled = false;
} | bsd-3-clause |
fsimkovic/conkit | docs/examples/code/plot_mat_simple.py | 785 | """
Simple contact cmap plotting 1
=============================
This script contains a simple example of how you can plot
contact cmaps using ConKit
"""
import conkit.io
import conkit.plot
# Define the input variables
sequence_file = "toxd/toxd.fasta"
sequence_format = "fasta"
contact_file = "toxd/toxd.mat"
contact_format = "ccmpred"
# Create ConKit hierarchies
# Note, we only need the first Sequence/ContactMap
# from each file
seq = conkit.io.read(sequence_file, sequence_format).top
conpred = conkit.io.read(contact_file, contact_format).top
# Assign the sequence register to your contact prediction
conpred.sequence = seq
conpred.set_sequence_register()
# Then we can plot the cmap
fig = conkit.plot.ContactMapMatrixFigure(cmap)
fig.savefig("toxd/toxd.png")
| bsd-3-clause |
nwsw/Elkarte | themes/default/GenericControls.template.php | 8044 | <?php
/**
* @name ElkArte Forum
* @copyright ElkArte Forum contributors
* @license BSD http://opensource.org/licenses/BSD-3-Clause
*
* This file contains code covered by:
* copyright: 2011 Simple Machines (http://www.simplemachines.org)
* license: BSD, See included LICENSE.TXT for terms and conditions.
*
* @version 1.1
*
*/
/**
* This function displays all the goodies you get with a richedit box - BBC, smileys etc.
*
* @param string $editor_id
* @param string|null $smileyContainer if set show the smiley container id
* @param string|null $bbcContainer show the bbc container id
*
* @return string as echo output
*/
function template_control_richedit($editor_id, $smileyContainer = null, $bbcContainer = null)
{
global $context, $settings;
$editor_context = &$context['controls']['richedit'][$editor_id];
$plugins = array_filter(array('bbcode', 'splittag', 'undo', (!empty($context['mentions_enabled']) ? 'mention' : '')));
// Allow addons to insert additional editor plugin scripts
if (!empty($editor_context['plugin_addons']) && is_array($editor_context['plugin_addons']))
$plugins = array_filter(array_merge($plugins, $editor_context['plugin_addons']));
// Add in special config objects to the editor, typically for plugin use
$plugin_options = array();
$plugin_options[] = '
parserOptions: {
quoteType: $.sceditor.BBCodeParser.QuoteType.auto
}';
if (!empty($context['mentions_enabled']))
$plugin_options[] = '
mentionOptions: {
editor_id: \'' . $editor_id . '\',
cache: {
mentions: [],
queries: [],
names: []
}
}';
// Allow addons to insert additional editor objects
if (!empty($editor_context['plugin_options']) && is_array($editor_context['plugin_options']))
$plugin_options = array_merge($plugin_options, $editor_context['plugin_options']);
echo '
<div id="editor_toolbar_container"></div>
<label for="', $editor_id, '">
<textarea class="editor', isset($context['post_error']['errors']['no_message']) || isset($context['post_error']['errors']['long_message']) ? ' border_error' : '', '" name="', $editor_id, '" id="', $editor_id, '" tabindex="', $context['tabindex']++, '" style="width:', $editor_context['width'], ';height: ', $editor_context['height'], ';" required="required">', $editor_context['value'], '</textarea>
</label>
<input type="hidden" name="', $editor_id, '_mode" id="', $editor_id, '_mode" value="0" />
<script>
var $editor_data = {},
$editor_container = {};
function elk_editor() {',
!empty($context['bbcodes_handlers']) ? $context['bbcodes_handlers'] : '', '
$("#', $editor_id, '").sceditor({
style: "', $settings['theme_url'], '/css/', $context['theme_variant_url'], 'jquery.sceditor.elk_wiz', $context['theme_variant'], '.css', CACHE_STALE, '",
width: "100%",
startInSourceMode: ', $editor_context['rich_active'] ? 'false' : 'true', ',
toolbarContainer: $("#editor_toolbar_container"),
resizeWidth: false,
resizeMaxHeight: -1,
emoticonsCompat: true,
locale: "', !empty($editor_context['locale']) ? $editor_context['locale'] : 'en_US', '",
rtl: ', empty($context['right_to_left']) ? 'false' : 'true', ',
colors: "black,red,yellow,pink,green,orange,purple,blue,beige,brown,teal,navy,maroon,limegreen,white",
enablePasteFiltering: true,
plugins: "', implode(',', $plugins), '",
', trim(implode(',', $plugin_options));
// Show the smileys.
if ((!empty($context['smileys']['postform']) || !empty($context['smileys']['popup'])) && !$editor_context['disable_smiley_box'] && $smileyContainer !== null)
{
echo ',
emoticons:
{';
$countLocations = count($context['smileys']);
foreach ($context['smileys'] as $location => $smileyRows)
{
$countLocations--;
if ($location === 'postform')
echo '
dropdown:
{';
elseif ($location === 'popup')
echo '
popup:
{';
$numRows = count($smileyRows);
// This is needed because otherwise the editor will remove all the duplicate (empty) keys and leave only 1 additional line
$emptyPlaceholder = 0;
foreach ($smileyRows as $smileyRow)
{
foreach ($smileyRow['smileys'] as $smiley)
{
echo '
', JavaScriptEscape($smiley['code']), ': {url: ', JavaScriptEscape($settings['smileys_url'] . '/' . $smiley['filename']), ', tooltip: ', JavaScriptEscape($smiley['description']), '}', empty($smiley['isLast']) ? ',' : '';
}
if (empty($smileyRow['isLast']) && $numRows !== 1)
echo ',
\'-', $emptyPlaceholder++, '\': \'\',';
}
echo '
}', $countLocations != 0 ? ',' : '';
}
echo '
}';
}
else
echo ',
emoticons:
{}';
// Show all the editor command buttons
if ($bbcContainer !== null)
{
echo ',
toolbar: "';
// Create the tooltag rows to display the buttons in the editor
foreach ($context['bbc_toolbar'] as $i => $buttonRow)
echo $buttonRow[0], '||';
echo ',emoticon",';
}
else
echo ',
toolbar: "source,emoticon",';
echo '
});
$editor_data["', $editor_id, '"] = $("#', $editor_id, '").data("sceditor");
$editor_container["', $editor_id, '"] = $(".sceditor-container");
$editor_data["', $editor_id, '"].css("code {white-space: pre;}").createPermanentDropDown();
if (!(is_ie || is_ff || is_opera || is_safari || is_chrome))
$(".sceditor-button-source").hide();
', isset($context['post_error']['errors']['no_message']) || isset($context['post_error']['errors']['long_message']) ? '
$editor_container["' . $editor_id . '"].find("textarea, iframe").addClass("border_error");' : '', '
}
$(function() {
elk_editor();
});
</script>';
}
/**
* Shows the buttons that the user can see .. preview, spellchecker, etc
*
* @param string $editor_id
*
* @return string as echo output
*/
function template_control_richedit_buttons($editor_id)
{
global $context, $options, $txt;
$editor_context = &$context['controls']['richedit'][$editor_id];
echo '
<span class="shortcuts">';
// If this message has been edited in the past - display when it was.
if (isset($context['last_modified']))
echo '
<p class="lastedit">', $context['last_modified_text'], '</p>';
// Show the helpful shortcut text
echo '
', $context['shortcuts_text'], '
</span>
<input type="submit" name="', isset($editor_context['labels']['post_name']) ? $editor_context['labels']['post_name'] : 'post', '" value="', isset($editor_context['labels']['post_button']) ? $editor_context['labels']['post_button'] : $txt['post'], '" tabindex="', $context['tabindex']++, '" onclick="return submitThisOnce(this);" accesskey="s" />';
if ($editor_context['preview_type'])
echo '
<input type="submit" name="preview" value="', isset($editor_context['labels']['preview_button']) ? $editor_context['labels']['preview_button'] : $txt['preview'], '" tabindex="', $context['tabindex']++, '" onclick="', $editor_context['preview_type'] == 2 ? 'return event.ctrlKey || previewControl();' : 'return submitThisOnce(this);', '" accesskey="p" />';
// Show the spellcheck button?
if ($context['show_spellchecking'])
echo '
<input type="button" value="', $txt['spell_check'], '" tabindex="', $context['tabindex']++, '" onclick="spellCheckStart();" />';
foreach ($editor_context['buttons'] as $button)
{
echo '
<input type="submit" name="', $button['name'], '" value="', $button['value'], '" tabindex="', $context['tabindex']++, '" ', $button['options'], ' />';
}
foreach ($editor_context['hidden_fields'] as $hidden)
{
echo '
<input type="hidden" id="', $hidden['name'], '" name="', $hidden['name'], '" value="', $hidden['value'], '" />';
}
// Create an area to show the draft last saved on text
if (!empty($context['drafts_autosave']) && !empty($options['drafts_autosave_enabled']))
echo '
<div class="draftautosave">
<span id="throbber" class="hide"><i class="icon icon-spin i-spinner"></i> </span>
<span id="draft_lastautosave"></span>
</div>';
}
| bsd-3-clause |
lobo12/ormlite-core | src/main/java/com/j256/ormlite/field/ForeignCollectionField.java | 4059 | package com.j256.ormlite.field;
import static java.lang.annotation.ElementType.FIELD;
import static java.lang.annotation.RetentionPolicy.RUNTIME;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;
import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.dao.ForeignCollection;
import com.j256.ormlite.dao.LazyForeignCollection;
import com.j256.ormlite.stmt.QueryBuilder;
/**
* Annotation that identifies a {@link ForeignCollection} field in a class that corresponds to objects in a foreign
* table that match the foreign-id of the current class.
*
* <pre>
* @ForeignCollection(id = true)
* private ForeignCollection<Order> orders;
* </pre>
*
* @author graywatson
*/
@Target(FIELD)
@Retention(RUNTIME)
public @interface ForeignCollectionField {
/**
* @see #maxEagerForeignCollectionLevel()
*/
public static final int DEFAULT_MAX_EAGER_LEVEL = 1;
/**
* <p>
* Set to true if the collection is a an eager collection where all of the results should be retrieved when the
* parent object is retrieved. Default is false (lazy) when the results will not be retrieved until you ask for the
* iterator from the collection.
* </p>
*
* <p>
* <b>NOTE:</b> If this is false (i.e. we have a lazy collection) then a connection is held open to the database as
* you iterate through the collection. This means that you need to make sure it is closed when you finish. See
* {@link LazyForeignCollection#iterator()} for more information.
* </p>
*
* <p>
* <b>WARNING:</b> By default, if you have eager collections of objects that themselves have eager collections, the
* inner collection will be created as lazy for performance reasons. If you need change this see the
* {@link #maxEagerLevel()} setting below.
* </p>
*/
boolean eager() default false;
/**
* @deprecated Should use {@link #maxEagerLevel()}
*/
@Deprecated
int maxEagerForeignCollectionLevel() default DEFAULT_MAX_EAGER_LEVEL;
/**
* Set this to be the number of times to expand an eager foreign collection's foreign collection. If you query for A
* and it has an eager foreign-collection of field B which has an eager foreign-collection of field C ..., then a
* lot of database operations are going to happen whenever you query for A. By default this value is 1 meaning that
* if you query for A, the collection of B will be eager fetched but each of the B objects will have a lazy
* collection instead of an eager collection of C. It should be increased only if you know what you are doing.
*/
int maxEagerLevel() default DEFAULT_MAX_EAGER_LEVEL;
/**
* The name of the column. This is only used when you want to match the string passed to
* {@link Dao#getEmptyForeignCollection(String)} or when you want to specify it in
* {@link QueryBuilder#selectColumns(String...)}.
*/
String columnName() default "";
/**
* The name of the column in the object that we should order by.
*/
String orderColumnName() default "";
/**
* If an order column has been defined with {@link #orderColumnName()}, this sets the order as ascending (true, the
* default) or descending (false).
*/
boolean orderAscending() default true;
/**
* @deprecated This has been renamed as {@link #foreignFieldName()} to make it more consistent to how it works.
*/
@Deprecated
String foreignColumnName() default "";
/**
* Name of the _field_ (not the column name) in the class that the collection is holding that corresponds to the
* collection. This is needed if there are two foreign fields in the class in the collection (such as a tree
* structure) and you want to identify which column you want in this collection.
*
* <p>
* <b>WARNING:</b> Due to some internal complexities, this it field/member name in the class and _not_ the
* column-name.
* </p>
*/
String foreignFieldName() default "";
/*
* NOTE to developers: if you add fields here you have to add them to the DatabaseFieldConfigLoader,
* DatabaseFieldConfigLoaderTest, and DatabaseTableConfigUtil.
*/
}
| isc |
PaulHigin/PowerShell | src/Microsoft.PowerShell.Security/security/ExecutionPolicyCommands.cs | 12935 | // Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
#region Using directives
using System;
// System.Management.Automation is the namespace which contains the types and
// methods pertaining to the Microsoft Command Shell
using System.Management.Automation;
using System.Management.Automation.Internal;
using System.Management.Automation.Tracing;
#endregion
namespace Microsoft.PowerShell.Commands
{
/// <summary>
/// Defines the implementation of the 'Get-ExecutionPolicy' cmdlet.
/// This cmdlet gets the effective execution policy of the shell.
///
/// In priority-order (highest priority first,) these come from:
/// - Machine-wide Group Policy
/// - Current-user Group Policy
/// - Current session preference
/// - Current user machine preference
/// - Local machine preference.
/// </summary>
[Cmdlet(VerbsCommon.Get, "ExecutionPolicy", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096594")]
[OutputType(typeof(ExecutionPolicy))]
public class GetExecutionPolicyCommand : PSCmdlet
{
/// <summary>
/// Gets or sets the scope of the execution policy.
/// </summary>
[Parameter(Position = 0, Mandatory = false, ValueFromPipelineByPropertyName = true)]
public ExecutionPolicyScope Scope
{
get { return _executionPolicyScope; }
set { _executionPolicyScope = value; _scopeSpecified = true; }
}
private ExecutionPolicyScope _executionPolicyScope = ExecutionPolicyScope.LocalMachine;
private bool _scopeSpecified = false;
/// <summary>
/// Gets or sets the List parameter, which lists all scopes and their execution
/// policies.
/// </summary>
[Parameter(Mandatory = false)]
public SwitchParameter List
{
get { return _list; }
set { _list = value; }
}
private bool _list;
/// <summary>
/// Outputs the execution policy.
/// </summary>
protected override void BeginProcessing()
{
if (_list && _scopeSpecified)
{
string message = ExecutionPolicyCommands.ListAndScopeSpecified;
ErrorRecord errorRecord = new(
new InvalidOperationException(),
"ListAndScopeSpecified",
ErrorCategory.InvalidOperation,
targetObject: null);
errorRecord.ErrorDetails = new ErrorDetails(message);
ThrowTerminatingError(errorRecord);
return;
}
string shellId = base.Context.ShellID;
if (_list)
{
foreach (ExecutionPolicyScope scope in SecuritySupport.ExecutionPolicyScopePreferences)
{
PSObject outputObject = new();
ExecutionPolicy policy = SecuritySupport.GetExecutionPolicy(shellId, scope);
PSNoteProperty inputNote = new("Scope", scope);
outputObject.Properties.Add(inputNote);
inputNote = new PSNoteProperty(
"ExecutionPolicy", policy);
outputObject.Properties.Add(inputNote);
WriteObject(outputObject);
}
}
else if (_scopeSpecified)
{
WriteObject(SecuritySupport.GetExecutionPolicy(shellId, _executionPolicyScope));
}
else
{
WriteObject(SecuritySupport.GetExecutionPolicy(shellId));
}
}
}
/// <summary>
/// Defines the implementation of the 'Set-ExecutionPolicy' cmdlet.
/// This cmdlet sets the local preference for the execution policy of the
/// shell.
///
/// The execution policy may be overridden by settings in Group Policy.
/// If the Group Policy setting overrides the desired behaviour, the Cmdlet
/// generates a terminating error.
/// </summary>
[Cmdlet(VerbsCommon.Set, "ExecutionPolicy", SupportsShouldProcess = true, HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2096612")]
public class SetExecutionPolicyCommand : PSCmdlet
{
/// <summary>
/// Gets or sets the execution policy that the user requests.
/// </summary>
[Parameter(Position = 0, Mandatory = true, ValueFromPipeline = true)]
public ExecutionPolicy ExecutionPolicy
{
get { return _executionPolicy; }
set { _executionPolicy = value; }
}
private ExecutionPolicy _executionPolicy;
/// <summary>
/// Gets or sets the scope of the execution policy.
/// </summary>
[Parameter(Position = 1, Mandatory = false, ValueFromPipelineByPropertyName = true)]
public ExecutionPolicyScope Scope
{
get { return _executionPolicyScope; }
set { _executionPolicyScope = value; }
}
private ExecutionPolicyScope _executionPolicyScope = ExecutionPolicyScope.LocalMachine;
/// <summary>
/// Specifies whether to force the execution policy change.
/// </summary>
/// <value></value>
[Parameter]
public SwitchParameter Force
{
get
{
return _force;
}
set
{
_force = value;
}
}
private SwitchParameter _force;
/// <summary>
/// Sets the execution policy (validation).
/// </summary>
protected override void BeginProcessing()
{
// Verify they've specified a valid scope
if ((_executionPolicyScope == ExecutionPolicyScope.UserPolicy) ||
(_executionPolicyScope == ExecutionPolicyScope.MachinePolicy))
{
string message = ExecutionPolicyCommands.CantSetGroupPolicy;
ErrorRecord errorRecord = new(
new InvalidOperationException(),
"CantSetGroupPolicy",
ErrorCategory.InvalidOperation,
targetObject: null);
errorRecord.ErrorDetails = new ErrorDetails(message);
ThrowTerminatingError(errorRecord);
return;
}
}
/// <summary>
/// Set the desired execution policy.
/// </summary>
protected override void ProcessRecord()
{
string shellId = base.Context.ShellID;
string executionPolicy = SecuritySupport.GetExecutionPolicy(ExecutionPolicy);
if (ShouldProcessPolicyChange(executionPolicy))
{
try
{
SecuritySupport.SetExecutionPolicy(_executionPolicyScope, ExecutionPolicy, shellId);
}
catch (UnauthorizedAccessException exception)
{
OnAccessDeniedError(exception);
}
catch (System.Security.SecurityException exception)
{
OnAccessDeniedError(exception);
}
// Ensure it is now the effective execution policy
if (ExecutionPolicy != ExecutionPolicy.Undefined)
{
string effectiveExecutionPolicy = SecuritySupport.GetExecutionPolicy(shellId).ToString();
if (!string.Equals(effectiveExecutionPolicy, executionPolicy, StringComparison.OrdinalIgnoreCase))
{
string message = StringUtil.Format(ExecutionPolicyCommands.ExecutionPolicyOverridden, effectiveExecutionPolicy);
string recommendedAction = ExecutionPolicyCommands.ExecutionPolicyOverriddenRecommendedAction;
ErrorRecord errorRecord = new(
new System.Security.SecurityException(),
"ExecutionPolicyOverride",
ErrorCategory.PermissionDenied,
targetObject: null);
errorRecord.ErrorDetails = new ErrorDetails(message);
errorRecord.ErrorDetails.RecommendedAction = recommendedAction;
ThrowTerminatingError(errorRecord);
}
}
PSEtwLog.LogSettingsEvent(MshLog.GetLogContext(Context, MyInvocation),
EtwLoggingStrings.ExecutionPolicyName, executionPolicy, null);
}
}
// Determine if we should process this policy change
#if CORECLR // Seems that we cannot find if the cmdlet is executed interactive or through a script on CoreCLR
private bool ShouldProcessPolicyChange(string localPreference)
{
return ShouldProcess(localPreference);
}
#else
private bool ShouldProcessPolicyChange(string localPreference)
{
if (ShouldProcess(localPreference))
{
// See if we're being invoked directly at the
// command line. In that case, give a warning.
if (!Force)
{
// We don't give this warning if we're in a script, or
// if we don't have a window handle
// (i.e.: PowerShell -command Set-ExecutionPolicy Unrestricted)
if (IsProcessInteractive())
{
string query = ExecutionPolicyCommands.SetExecutionPolicyQuery;
string caption = ExecutionPolicyCommands.SetExecutionPolicyCaption;
try
{
bool yesToAllNoToAllDefault = false;
if (!ShouldContinue(query, caption, true, ref yesToAllNoToAllDefault, ref yesToAllNoToAllDefault))
{
return false;
}
}
catch (InvalidOperationException)
{
// Host is non-interactive. This should
// return false, but must return true due
// to backward compatibility.
return true;
}
catch (System.Management.Automation.Host.HostException)
{
// Host doesn't implement ShouldContinue. This should
// return false, but must return true due
// to backward compatibility.
return true;
}
}
}
return true;
}
return false;
}
private bool IsProcessInteractive()
{
// CommandOrigin != Runspace means it is in a script
if (MyInvocation.CommandOrigin != CommandOrigin.Runspace)
return false;
// If we don't own the window handle, we've been invoked
// from another process that just calls "PowerShell -Command"
if (System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle == IntPtr.Zero)
return false;
// If the window has been idle for less than a second,
// they're probably still calling "PowerShell -Command"
// but from Start-Process, or the StartProcess API
try
{
System.Diagnostics.Process currentProcess = System.Diagnostics.Process.GetCurrentProcess();
TimeSpan timeSinceStart = DateTime.Now - currentProcess.StartTime;
TimeSpan idleTime = timeSinceStart - currentProcess.TotalProcessorTime;
if (idleTime.TotalSeconds > 1)
return true;
}
catch (System.ComponentModel.Win32Exception)
{
// Don't have access to the properties
return false;
}
return false;
}
#endif
// Throw terminating error when the access to the registry is denied
private void OnAccessDeniedError(Exception exception)
{
string message = StringUtil.Format(ExecutionPolicyCommands.SetExecutionPolicyAccessDeniedError, exception.Message);
ErrorRecord errorRecord = new(
exception,
exception.GetType().FullName,
ErrorCategory.PermissionDenied,
targetObject: null);
errorRecord.ErrorDetails = new ErrorDetails(message);
ThrowTerminatingError(errorRecord);
}
}
}
| mit |
cfoxleyevans/RainfallAnalyzer | jfreechart-1.0.14/source/org/jfree/chart/renderer/xy/StackedXYAreaRenderer2.java | 21861 | /* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2011, by Object Refinery Limited and Contributors.
*
* Project Info: http://www.jfree.org/jfreechart/index.html
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
* [Oracle and Java are registered trademarks of Oracle and/or its affiliates.
* Other names may be trademarks of their respective owners.]
*
* ---------------------------
* StackedXYAreaRenderer2.java
* ---------------------------
* (C) Copyright 2004-2008, by Object Refinery Limited and Contributors.
*
* Original Author: David Gilbert (for Object Refinery Limited), based on
* the StackedXYAreaRenderer class by Richard Atkinson;
* Contributor(s): -;
*
* Changes:
* --------
* 30-Apr-2004 : Version 1 (DG);
* 15-Jul-2004 : Switched getX() with getXValue() and getY() with
* getYValue() (DG);
* 10-Sep-2004 : Removed getRangeType() method (DG);
* 06-Jan-2004 : Renamed getRangeExtent() --> findRangeBounds (DG);
* 28-Mar-2005 : Use getXValue() and getYValue() from dataset (DG);
* 03-Oct-2005 : Add entity generation to drawItem() method (DG);
* ------------- JFREECHART 1.0.x ---------------------------------------------
* 22-Aug-2006 : Handle null and empty datasets correctly in the
* findRangeBounds() method (DG);
* 22-Sep-2006 : Added a flag to allow rounding of x-coordinates (after
* translation to Java2D space) in order to avoid the striping
* that can result from anti-aliasing (thanks to Doug
* Clayton) (DG);
* 30-Nov-2006 : Added accessor methods for the roundXCoordinates flag (DG);
* 02-Jun-2008 : Fixed bug with PlotOrientation.HORIZONTAL (DG);
*
*/
package org.jfree.chart.renderer.xy;
import java.awt.Graphics2D;
import java.awt.Paint;
import java.awt.Shape;
import java.awt.geom.GeneralPath;
import java.awt.geom.Rectangle2D;
import java.io.Serializable;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.entity.EntityCollection;
import org.jfree.chart.event.RendererChangeEvent;
import org.jfree.chart.labels.XYToolTipGenerator;
import org.jfree.chart.plot.CrosshairState;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.plot.PlotRenderingInfo;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.urls.XYURLGenerator;
import org.jfree.data.Range;
import org.jfree.data.xy.TableXYDataset;
import org.jfree.data.xy.XYDataset;
import org.jfree.ui.RectangleEdge;
import org.jfree.util.PublicCloneable;
/**
* A stacked area renderer for the {@link XYPlot} class.
* The example shown here is generated by the
* <code>StackedXYAreaChartDemo2.java</code> program included in the
* JFreeChart demo collection:
* <br><br>
* <img src="../../../../../images/StackedXYAreaRenderer2Sample.png"
* alt="StackedXYAreaRenderer2Sample.png" />
*/
public class StackedXYAreaRenderer2 extends XYAreaRenderer2
implements Cloneable, PublicCloneable, Serializable {
/** For serialization. */
private static final long serialVersionUID = 7752676509764539182L;
/**
* This flag controls whether or not the x-coordinates (in Java2D space)
* are rounded to integers. When set to true, this can avoid the vertical
* striping that anti-aliasing can generate. However, the rounding may not
* be appropriate for output in high resolution formats (for example,
* vector graphics formats such as SVG and PDF).
*
* @since 1.0.3
*/
private boolean roundXCoordinates;
/**
* Creates a new renderer.
*/
public StackedXYAreaRenderer2() {
this(null, null);
}
/**
* Constructs a new renderer.
*
* @param labelGenerator the tool tip generator to use. <code>null</code>
* is none.
* @param urlGenerator the URL generator (<code>null</code> permitted).
*/
public StackedXYAreaRenderer2(XYToolTipGenerator labelGenerator,
XYURLGenerator urlGenerator) {
super(labelGenerator, urlGenerator);
this.roundXCoordinates = true;
}
/**
* Returns the flag that controls whether or not the x-coordinates (in
* Java2D space) are rounded to integer values.
*
* @return The flag.
*
* @since 1.0.4
*
* @see #setRoundXCoordinates(boolean)
*/
public boolean getRoundXCoordinates() {
return this.roundXCoordinates;
}
/**
* Sets the flag that controls whether or not the x-coordinates (in
* Java2D space) are rounded to integer values, and sends a
* {@link RendererChangeEvent} to all registered listeners.
*
* @param round the new flag value.
*
* @since 1.0.4
*
* @see #getRoundXCoordinates()
*/
public void setRoundXCoordinates(boolean round) {
this.roundXCoordinates = round;
fireChangeEvent();
}
/**
* Returns the range of values the renderer requires to display all the
* items from the specified dataset.
*
* @param dataset the dataset (<code>null</code> permitted).
*
* @return The range (or <code>null</code> if the dataset is
* <code>null</code> or empty).
*/
public Range findRangeBounds(XYDataset dataset) {
if (dataset == null) {
return null;
}
double min = Double.POSITIVE_INFINITY;
double max = Double.NEGATIVE_INFINITY;
TableXYDataset d = (TableXYDataset) dataset;
int itemCount = d.getItemCount();
for (int i = 0; i < itemCount; i++) {
double[] stackValues = getStackValues((TableXYDataset) dataset,
d.getSeriesCount(), i);
min = Math.min(min, stackValues[0]);
max = Math.max(max, stackValues[1]);
}
if (min == Double.POSITIVE_INFINITY) {
return null;
}
return new Range(min, max);
}
/**
* Returns the number of passes required by the renderer.
*
* @return 1.
*/
public int getPassCount() {
return 1;
}
/**
* Draws the visual representation of a single data item.
*
* @param g2 the graphics device.
* @param state the renderer state.
* @param dataArea the area within which the data is being drawn.
* @param info collects information about the drawing.
* @param plot the plot (can be used to obtain standard color information
* etc).
* @param domainAxis the domain axis.
* @param rangeAxis the range axis.
* @param dataset the dataset.
* @param series the series index (zero-based).
* @param item the item index (zero-based).
* @param crosshairState information about crosshairs on a plot.
* @param pass the pass index.
*/
public void drawItem(Graphics2D g2,
XYItemRendererState state,
Rectangle2D dataArea,
PlotRenderingInfo info,
XYPlot plot,
ValueAxis domainAxis,
ValueAxis rangeAxis,
XYDataset dataset,
int series,
int item,
CrosshairState crosshairState,
int pass) {
// setup for collecting optional entity info...
Shape entityArea = null;
EntityCollection entities = null;
if (info != null) {
entities = info.getOwner().getEntityCollection();
}
TableXYDataset tdataset = (TableXYDataset) dataset;
PlotOrientation orientation = plot.getOrientation();
// get the data point...
double x1 = dataset.getXValue(series, item);
double y1 = dataset.getYValue(series, item);
if (Double.isNaN(y1)) {
y1 = 0.0;
}
double[] stack1 = getStackValues(tdataset, series, item);
// get the previous point and the next point so we can calculate a
// "hot spot" for the area (used by the chart entity)...
double x0 = dataset.getXValue(series, Math.max(item - 1, 0));
double y0 = dataset.getYValue(series, Math.max(item - 1, 0));
if (Double.isNaN(y0)) {
y0 = 0.0;
}
double[] stack0 = getStackValues(tdataset, series, Math.max(item - 1,
0));
int itemCount = dataset.getItemCount(series);
double x2 = dataset.getXValue(series, Math.min(item + 1,
itemCount - 1));
double y2 = dataset.getYValue(series, Math.min(item + 1,
itemCount - 1));
if (Double.isNaN(y2)) {
y2 = 0.0;
}
double[] stack2 = getStackValues(tdataset, series, Math.min(item + 1,
itemCount - 1));
double xleft = (x0 + x1) / 2.0;
double xright = (x1 + x2) / 2.0;
double[] stackLeft = averageStackValues(stack0, stack1);
double[] stackRight = averageStackValues(stack1, stack2);
double[] adjStackLeft = adjustedStackValues(stack0, stack1);
double[] adjStackRight = adjustedStackValues(stack1, stack2);
RectangleEdge edge0 = plot.getDomainAxisEdge();
float transX1 = (float) domainAxis.valueToJava2D(x1, dataArea, edge0);
float transXLeft = (float) domainAxis.valueToJava2D(xleft, dataArea,
edge0);
float transXRight = (float) domainAxis.valueToJava2D(xright, dataArea,
edge0);
if (this.roundXCoordinates) {
transX1 = Math.round(transX1);
transXLeft = Math.round(transXLeft);
transXRight = Math.round(transXRight);
}
float transY1;
RectangleEdge edge1 = plot.getRangeAxisEdge();
GeneralPath left = new GeneralPath();
GeneralPath right = new GeneralPath();
if (y1 >= 0.0) { // handle positive value
transY1 = (float) rangeAxis.valueToJava2D(y1 + stack1[1], dataArea,
edge1);
float transStack1 = (float) rangeAxis.valueToJava2D(stack1[1],
dataArea, edge1);
float transStackLeft = (float) rangeAxis.valueToJava2D(
adjStackLeft[1], dataArea, edge1);
// LEFT POLYGON
if (y0 >= 0.0) {
double yleft = (y0 + y1) / 2.0 + stackLeft[1];
float transYLeft
= (float) rangeAxis.valueToJava2D(yleft, dataArea, edge1);
if (orientation == PlotOrientation.VERTICAL) {
left.moveTo(transX1, transY1);
left.lineTo(transX1, transStack1);
left.lineTo(transXLeft, transStackLeft);
left.lineTo(transXLeft, transYLeft);
}
else {
left.moveTo(transY1, transX1);
left.lineTo(transStack1, transX1);
left.lineTo(transStackLeft, transXLeft);
left.lineTo(transYLeft, transXLeft);
}
left.closePath();
}
else {
if (orientation == PlotOrientation.VERTICAL) {
left.moveTo(transX1, transStack1);
left.lineTo(transX1, transY1);
left.lineTo(transXLeft, transStackLeft);
}
else {
left.moveTo(transStack1, transX1);
left.lineTo(transY1, transX1);
left.lineTo(transStackLeft, transXLeft);
}
left.closePath();
}
float transStackRight = (float) rangeAxis.valueToJava2D(
adjStackRight[1], dataArea, edge1);
// RIGHT POLYGON
if (y2 >= 0.0) {
double yright = (y1 + y2) / 2.0 + stackRight[1];
float transYRight
= (float) rangeAxis.valueToJava2D(yright, dataArea, edge1);
if (orientation == PlotOrientation.VERTICAL) {
right.moveTo(transX1, transStack1);
right.lineTo(transX1, transY1);
right.lineTo(transXRight, transYRight);
right.lineTo(transXRight, transStackRight);
}
else {
right.moveTo(transStack1, transX1);
right.lineTo(transY1, transX1);
right.lineTo(transYRight, transXRight);
right.lineTo(transStackRight, transXRight);
}
right.closePath();
}
else {
if (orientation == PlotOrientation.VERTICAL) {
right.moveTo(transX1, transStack1);
right.lineTo(transX1, transY1);
right.lineTo(transXRight, transStackRight);
}
else {
right.moveTo(transStack1, transX1);
right.lineTo(transY1, transX1);
right.lineTo(transStackRight, transXRight);
}
right.closePath();
}
}
else { // handle negative value
transY1 = (float) rangeAxis.valueToJava2D(y1 + stack1[0], dataArea,
edge1);
float transStack1 = (float) rangeAxis.valueToJava2D(stack1[0],
dataArea, edge1);
float transStackLeft = (float) rangeAxis.valueToJava2D(
adjStackLeft[0], dataArea, edge1);
// LEFT POLYGON
if (y0 >= 0.0) {
if (orientation == PlotOrientation.VERTICAL) {
left.moveTo(transX1, transStack1);
left.lineTo(transX1, transY1);
left.lineTo(transXLeft, transStackLeft);
}
else {
left.moveTo(transStack1, transX1);
left.lineTo(transY1, transX1);
left.lineTo(transStackLeft, transXLeft);
}
left.clone();
}
else {
double yleft = (y0 + y1) / 2.0 + stackLeft[0];
float transYLeft = (float) rangeAxis.valueToJava2D(yleft,
dataArea, edge1);
if (orientation == PlotOrientation.VERTICAL) {
left.moveTo(transX1, transY1);
left.lineTo(transX1, transStack1);
left.lineTo(transXLeft, transStackLeft);
left.lineTo(transXLeft, transYLeft);
}
else {
left.moveTo(transY1, transX1);
left.lineTo(transStack1, transX1);
left.lineTo(transStackLeft, transXLeft);
left.lineTo(transYLeft, transXLeft);
}
left.closePath();
}
float transStackRight = (float) rangeAxis.valueToJava2D(
adjStackRight[0], dataArea, edge1);
// RIGHT POLYGON
if (y2 >= 0.0) {
if (orientation == PlotOrientation.VERTICAL) {
right.moveTo(transX1, transStack1);
right.lineTo(transX1, transY1);
right.lineTo(transXRight, transStackRight);
}
else {
right.moveTo(transStack1, transX1);
right.lineTo(transY1, transX1);
right.lineTo(transStackRight, transXRight);
}
right.closePath();
}
else {
double yright = (y1 + y2) / 2.0 + stackRight[0];
float transYRight = (float) rangeAxis.valueToJava2D(yright,
dataArea, edge1);
if (orientation == PlotOrientation.VERTICAL) {
right.moveTo(transX1, transStack1);
right.lineTo(transX1, transY1);
right.lineTo(transXRight, transYRight);
right.lineTo(transXRight, transStackRight);
}
else {
right.moveTo(transStack1, transX1);
right.lineTo(transY1, transX1);
right.lineTo(transYRight, transXRight);
right.lineTo(transStackRight, transXRight);
}
right.closePath();
}
}
// Get series Paint and Stroke
Paint itemPaint = getItemPaint(series, item);
if (pass == 0) {
g2.setPaint(itemPaint);
g2.fill(left);
g2.fill(right);
}
// add an entity for the item...
if (entities != null) {
GeneralPath gp = new GeneralPath(left);
gp.append(right, false);
entityArea = gp;
addEntity(entities, entityArea, dataset, series, item,
transX1, transY1);
}
}
/**
* Calculates the stacked values (one positive and one negative) of all
* series up to, but not including, <code>series</code> for the specified
* item. It returns [0.0, 0.0] if <code>series</code> is the first series.
*
* @param dataset the dataset (<code>null</code> not permitted).
* @param series the series index.
* @param index the item index.
*
* @return An array containing the cumulative negative and positive values
* for all series values up to but excluding <code>series</code>
* for <code>index</code>.
*/
private double[] getStackValues(TableXYDataset dataset,
int series, int index) {
double[] result = new double[2];
for (int i = 0; i < series; i++) {
double v = dataset.getYValue(i, index);
if (!Double.isNaN(v)) {
if (v >= 0.0) {
result[1] += v;
}
else {
result[0] += v;
}
}
}
return result;
}
/**
* Returns a pair of "stack" values calculated as the mean of the two
* specified stack value pairs.
*
* @param stack1 the first stack pair.
* @param stack2 the second stack pair.
*
* @return A pair of average stack values.
*/
private double[] averageStackValues(double[] stack1, double[] stack2) {
double[] result = new double[2];
result[0] = (stack1[0] + stack2[0]) / 2.0;
result[1] = (stack1[1] + stack2[1]) / 2.0;
return result;
}
/**
* Calculates adjusted stack values from the supplied values. The value is
* the mean of the supplied values, unless either of the supplied values
* is zero, in which case the adjusted value is zero also.
*
* @param stack1 the first stack pair.
* @param stack2 the second stack pair.
*
* @return A pair of average stack values.
*/
private double[] adjustedStackValues(double[] stack1, double[] stack2) {
double[] result = new double[2];
if (stack1[0] == 0.0 || stack2[0] == 0.0) {
result[0] = 0.0;
}
else {
result[0] = (stack1[0] + stack2[0]) / 2.0;
}
if (stack1[1] == 0.0 || stack2[1] == 0.0) {
result[1] = 0.0;
}
else {
result[1] = (stack1[1] + stack2[1]) / 2.0;
}
return result;
}
/**
* Tests this renderer for equality with an arbitrary object.
*
* @param obj the object (<code>null</code> permitted).
*
* @return A boolean.
*/
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof StackedXYAreaRenderer2)) {
return false;
}
StackedXYAreaRenderer2 that = (StackedXYAreaRenderer2) obj;
if (this.roundXCoordinates != that.roundXCoordinates) {
return false;
}
return super.equals(obj);
}
/**
* Returns a clone of the renderer.
*
* @return A clone.
*
* @throws CloneNotSupportedException if the renderer cannot be cloned.
*/
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
| mit |
closemarketing/mute-screamer | libraries/mscr/Text_Diff_Render.php | 7050 | <?php if ( ! defined( 'ABSPATH' ) ) exit;
class MSCR_Text_Diff_Renderer_Table extends WP_Text_Diff_Renderer_Table {
/**
* Number of context lines before
*
* @var int
*/
public $_leading_context_lines = 3;
/**
* Number of context lines after
*
* @var int
*/
public $_trailing_context_lines = 3;
/**
* @ignore
*
* @param string $line HTML-escape the value.
* @return string
*/
function addedLine( $line ) {
return "<td class='diff-addedline first'>+</td><td class='diff-addedline'>{$line}</td>";
}
/**
* @ignore
*
* @param string $line HTML-escape the value.
* @return string
*/
function deletedLine( $line ) {
return "<td class='diff-deletedline first'>-</td><td class='diff-deletedline'>{$line}</td>";
}
/**
* @ignore
*
* @param string $line HTML-escape the value.
* @return string
*/
function contextLine( $line ) {
return "<td class='diff-context first'> </td><td class='diff-context'>{$line}</td>";
}
/**
* @ignore
*
* @param string $header
* @return string
*/
function _startBlock( $header ) {
return '<tr><td colspan="2" class="start-block"> ' . $header . "</td></tr>\n";
}
function _blockHeader( $xbeg, $xlen, $ybeg, $ylen ) {
if ( $xlen > 1 ) {
$xbeg .= ',' . ($xbeg + $xlen - 1);
}
if ( $ylen > 1 ) {
$ybeg .= ',' . ($ybeg + $ylen - 1);
}
// this matches the GNU Diff behaviour
if ( $xlen && ! $ylen ) {
$ybeg--;
} elseif ( ! $xlen ) {
$xbeg--;
}
return $xbeg . ($xlen ? ($ylen ? 'c' : 'd') : 'a') . $ybeg;
}
/**
* Render block
*
* @return string
*/
function _block( $xbeg, $xlen, $ybeg, $ylen, &$edits ) {
$output = $this->_startBlock( $this->_blockHeader( $xbeg, $xlen, $ybeg, $ylen ) );
foreach ( $edits as $edit ) {
switch ( strtolower( get_class( $edit ) ) ) {
case 'text_diff_op_copy':
$output .= $this->_context( $edit->orig );
break;
case 'text_diff_op_add':
$output .= $this->_added( $edit->final );
break;
case 'text_diff_op_delete':
$output .= $this->_deleted( $edit->orig );
break;
case 'text_diff_op_change':
$output .= $this->_changed( $edit->orig, $edit->final );
break;
}
}
return $output . $this->_endBlock();
}
/**
* @ignore
* @access private
*
* @param array $lines
* @param bool $encode
* @return string
*/
function _added( $lines, $encode = true ) {
$r = '';
foreach ( $lines as $line ) {
if ( $encode )
$line = htmlspecialchars( $line );
$r .= '<tr>' . $this->addedLine( $line ) . "</tr>\n";
}
return $r;
}
/**
* @ignore
* @access private
*
* @param array $lines
* @param bool $encode
* @return string
*/
function _deleted( $lines, $encode = true ) {
$r = '';
foreach ( $lines as $line ) {
if ( $encode )
$line = htmlspecialchars( $line );
$r .= '<tr>' . $this->deletedLine( $line ) . "</tr>\n";
}
return $r;
}
/**
* @ignore
* @access private
*
* @param array $lines
* @param bool $encode
* @return string
*/
function _context( $lines, $encode = true ) {
$r = '';
foreach ( $lines as $line ) {
if ( $encode )
$line = htmlspecialchars( $line );
$r .= '<tr>' . $this->contextLine( $line ) . "</tr>\n";
}
return $r;
}
/**
* Process changed lines to do word-by-word diffs for extra highlighting.
*
* (TRAC style) sometimes these lines can actually be deleted or added rows.
* We do additional processing to figure that out
*
* @access private
* @since 2.6.0
*
* @param array $orig
* @param array $final
* @return string
*/
function _changed( $orig, $final ) {
$r = '';
// Does the aforementioned additional processing
// *_matches tell what rows are "the same" in orig and final. Those pairs will be diffed to get word changes
// match is numeric: an index in other column
// match is 'X': no match. It is a new row
// *_rows are column vectors for the orig column and the final column.
// row >= 0: an indix of the $orig or $final array
// row < 0: a blank row for that column
list($orig_matches, $final_matches, $orig_rows, $final_rows) = $this->interleave_changed_lines( $orig, $final );
// These will hold the word changes as determined by an inline diff
$orig_diffs = array();
$final_diffs = array();
// Compute word diffs for each matched pair using the inline diff
foreach ( $orig_matches as $o => $f ) {
if ( is_numeric( $o ) && is_numeric( $f ) ) {
$text_diff = new Text_Diff( 'auto', array( array( $orig[$o] ), array( $final[$f] ) ) );
$renderer = new $this->inline_diff_renderer;
$diff = $renderer->render( $text_diff );
// If they're too different, don't include any <ins> or <dels>
if ( $diff_count = preg_match_all( '!(<ins>.*?</ins>|<del>.*?</del>)!', $diff, $diff_matches ) ) {
// length of all text between <ins> or <del>
$stripped_matches = strlen( strip_tags( join( ' ', $diff_matches[0] ) ) );
// since we count lengith of text between <ins> or <del> (instead of picking just one),
// we double the length of chars not in those tags.
$stripped_diff = strlen( strip_tags( $diff ) ) * 2 - $stripped_matches;
$diff_ratio = $stripped_matches / $stripped_diff;
if ( $diff_ratio > $this->_diff_threshold )
continue; // Too different. Don't save diffs.
}
// Un-inline the diffs by removing del or ins
$orig_diffs[$o] = preg_replace( '|<ins>.*?</ins>|', '', $diff );
$final_diffs[$f] = preg_replace( '|<del>.*?</del>|', '', $diff );
}
}
foreach ( array_keys( $orig_rows ) as $row ) {
// Both columns have blanks. Ignore them.
if ( $orig_rows[$row] < 0 && $final_rows[$row] < 0 )
continue;
// If we have a word based diff, use it. Otherwise, use the normal line.
if ( isset( $orig_diffs[$orig_rows[$row]] ) ) {
$orig_line = $orig_diffs[$orig_rows[$row]];
}
elseif ( isset( $orig[$orig_rows[$row]] ) ) {
$orig_line = htmlspecialchars( $orig[$orig_rows[$row]] );
}
else
$orig_line = '';
if ( isset( $final_diffs[$final_rows[$row]] ) ) {
$final_line = $final_diffs[$final_rows[$row]];
}
elseif ( isset( $final[$final_rows[$row]] ) ) {
$final_line = htmlspecialchars( $final[$final_rows[$row]] );
}
else
$final_line = '';
if ( $orig_rows[$row] < 0 ) { // Orig is blank. This is really an added row.
$r .= $this->_added( array( $final_line ), false );
} elseif ( $final_rows[$row] < 0 ) { // Final is blank. This is really a deleted row.
$r .= $this->_deleted( array( $orig_line ), false );
} else { // A true changed row.
$r .= '<tr>' . $this->deletedLine( $orig_line ) . "</tr>\n";
$r .= '<tr>' . $this->addedLine( $final_line ) . "</tr>\n";
}
}
return $r;
}
} | mit |
mi1980/projecthadoop3 | udacity/ud036-python-foundations/code/lesson2/square.py | 338 | import turtle
def draw_square():
window = turtle.Screen()
window.bgcolor('red')
joe = turtle.Turtle()
joe.shape('turtle')
joe.color('green')
joe.speed(1) # on a scale of 1 to 10, where 10 is fastest
for i in range(0,4):
joe.forward(100)
joe.right(90)
window.exitonclick()
draw_square() | mit |
kakashidinho/HQEngine | ThirdParty-mod/java2cpp/dalvik/system/VMRuntime.hpp | 5026 | /*================================================================================
code generated by: java2cpp
author: Zoran Angelov, mailto://baldzar@gmail.com
class: dalvik.system.VMRuntime
================================================================================*/
#ifndef J2CPP_INCLUDE_IMPLEMENTATION
#ifndef J2CPP_DALVIK_SYSTEM_VMRUNTIME_HPP_DECL
#define J2CPP_DALVIK_SYSTEM_VMRUNTIME_HPP_DECL
namespace j2cpp { namespace java { namespace lang { class Object; } } }
#include <java/lang/Object.hpp>
namespace j2cpp {
namespace dalvik { namespace system {
class VMRuntime;
class VMRuntime
: public object<VMRuntime>
{
public:
J2CPP_DECLARE_CLASS
J2CPP_DECLARE_METHOD(0)
J2CPP_DECLARE_METHOD(1)
J2CPP_DECLARE_METHOD(2)
J2CPP_DECLARE_METHOD(3)
J2CPP_DECLARE_METHOD(4)
J2CPP_DECLARE_METHOD(5)
J2CPP_DECLARE_METHOD(6)
J2CPP_DECLARE_METHOD(7)
J2CPP_DECLARE_METHOD(8)
explicit VMRuntime(jobject jobj)
: object<VMRuntime>(jobj)
{
}
operator local_ref<java::lang::Object>() const;
static local_ref< dalvik::system::VMRuntime > getRuntime();
jfloat getTargetHeapUtilization();
jfloat setTargetHeapUtilization(jfloat);
jlong getMinimumHeapSize();
jlong setMinimumHeapSize(jlong);
void gcSoftReferences();
void runFinalizationSync();
jlong getExternalBytesAllocated();
}; //class VMRuntime
} //namespace system
} //namespace dalvik
} //namespace j2cpp
#endif //J2CPP_DALVIK_SYSTEM_VMRUNTIME_HPP_DECL
#else //J2CPP_INCLUDE_IMPLEMENTATION
#ifndef J2CPP_DALVIK_SYSTEM_VMRUNTIME_HPP_IMPL
#define J2CPP_DALVIK_SYSTEM_VMRUNTIME_HPP_IMPL
namespace j2cpp {
dalvik::system::VMRuntime::operator local_ref<java::lang::Object>() const
{
return local_ref<java::lang::Object>(get_jobject());
}
local_ref< dalvik::system::VMRuntime > dalvik::system::VMRuntime::getRuntime()
{
return call_static_method<
dalvik::system::VMRuntime::J2CPP_CLASS_NAME,
dalvik::system::VMRuntime::J2CPP_METHOD_NAME(1),
dalvik::system::VMRuntime::J2CPP_METHOD_SIGNATURE(1),
local_ref< dalvik::system::VMRuntime >
>();
}
jfloat dalvik::system::VMRuntime::getTargetHeapUtilization()
{
return call_method<
dalvik::system::VMRuntime::J2CPP_CLASS_NAME,
dalvik::system::VMRuntime::J2CPP_METHOD_NAME(2),
dalvik::system::VMRuntime::J2CPP_METHOD_SIGNATURE(2),
jfloat
>(get_jobject());
}
jfloat dalvik::system::VMRuntime::setTargetHeapUtilization(jfloat a0)
{
return call_method<
dalvik::system::VMRuntime::J2CPP_CLASS_NAME,
dalvik::system::VMRuntime::J2CPP_METHOD_NAME(3),
dalvik::system::VMRuntime::J2CPP_METHOD_SIGNATURE(3),
jfloat
>(get_jobject(), a0);
}
jlong dalvik::system::VMRuntime::getMinimumHeapSize()
{
return call_method<
dalvik::system::VMRuntime::J2CPP_CLASS_NAME,
dalvik::system::VMRuntime::J2CPP_METHOD_NAME(4),
dalvik::system::VMRuntime::J2CPP_METHOD_SIGNATURE(4),
jlong
>(get_jobject());
}
jlong dalvik::system::VMRuntime::setMinimumHeapSize(jlong a0)
{
return call_method<
dalvik::system::VMRuntime::J2CPP_CLASS_NAME,
dalvik::system::VMRuntime::J2CPP_METHOD_NAME(5),
dalvik::system::VMRuntime::J2CPP_METHOD_SIGNATURE(5),
jlong
>(get_jobject(), a0);
}
void dalvik::system::VMRuntime::gcSoftReferences()
{
return call_method<
dalvik::system::VMRuntime::J2CPP_CLASS_NAME,
dalvik::system::VMRuntime::J2CPP_METHOD_NAME(6),
dalvik::system::VMRuntime::J2CPP_METHOD_SIGNATURE(6),
void
>(get_jobject());
}
void dalvik::system::VMRuntime::runFinalizationSync()
{
return call_method<
dalvik::system::VMRuntime::J2CPP_CLASS_NAME,
dalvik::system::VMRuntime::J2CPP_METHOD_NAME(7),
dalvik::system::VMRuntime::J2CPP_METHOD_SIGNATURE(7),
void
>(get_jobject());
}
jlong dalvik::system::VMRuntime::getExternalBytesAllocated()
{
return call_method<
dalvik::system::VMRuntime::J2CPP_CLASS_NAME,
dalvik::system::VMRuntime::J2CPP_METHOD_NAME(8),
dalvik::system::VMRuntime::J2CPP_METHOD_SIGNATURE(8),
jlong
>(get_jobject());
}
J2CPP_DEFINE_CLASS(dalvik::system::VMRuntime,"dalvik/system/VMRuntime")
J2CPP_DEFINE_METHOD(dalvik::system::VMRuntime,0,"<init>","()V")
J2CPP_DEFINE_METHOD(dalvik::system::VMRuntime,1,"getRuntime","()Ldalvik/system/VMRuntime;")
J2CPP_DEFINE_METHOD(dalvik::system::VMRuntime,2,"getTargetHeapUtilization","()F")
J2CPP_DEFINE_METHOD(dalvik::system::VMRuntime,3,"setTargetHeapUtilization","(F)F")
J2CPP_DEFINE_METHOD(dalvik::system::VMRuntime,4,"getMinimumHeapSize","()J")
J2CPP_DEFINE_METHOD(dalvik::system::VMRuntime,5,"setMinimumHeapSize","(J)J")
J2CPP_DEFINE_METHOD(dalvik::system::VMRuntime,6,"gcSoftReferences","()V")
J2CPP_DEFINE_METHOD(dalvik::system::VMRuntime,7,"runFinalizationSync","()V")
J2CPP_DEFINE_METHOD(dalvik::system::VMRuntime,8,"getExternalBytesAllocated","()J")
} //namespace j2cpp
#endif //J2CPP_DALVIK_SYSTEM_VMRUNTIME_HPP_IMPL
#endif //J2CPP_INCLUDE_IMPLEMENTATION
| mit |
codemon66/Urho3D | Source/Urho3D/Graphics/Direct3D9/D3D9GraphicsImpl.cpp | 2218 | //
// Copyright (c) 2008-2017 the Urho3D project.
//
// 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.
//
#include "../../Precompiled.h"
#include "../../Graphics/Graphics.h"
#include "../../Graphics/GraphicsImpl.h"
#include "../../DebugNew.h"
namespace Urho3D
{
GraphicsImpl::GraphicsImpl() :
interface_(nullptr),
device_(nullptr),
defaultColorSurface_(nullptr),
defaultDepthStencilSurface_(nullptr),
frameQuery_(nullptr),
adapter_(D3DADAPTER_DEFAULT),
deviceType_(D3DDEVTYPE_HAL),
shaderProgram_(nullptr),
deviceLost_(false),
queryIssued_(false)
{
memset(&presentParams_, 0, sizeof presentParams_);
}
bool GraphicsImpl::CheckFormatSupport(D3DFORMAT format, DWORD usage, D3DRESOURCETYPE type)
{
return interface_ ? SUCCEEDED(interface_->CheckDeviceFormat(adapter_, deviceType_, D3DFMT_X8R8G8B8, usage, type, format)) :
false;
}
bool GraphicsImpl::CheckMultiSampleSupport(D3DFORMAT format, int level)
{
return interface_ ? SUCCEEDED(interface_->CheckDeviceMultiSampleType(adapter_, deviceType_, format, FALSE,
(D3DMULTISAMPLE_TYPE)level, nullptr)) : false;
}
}
| mit |
OfficeDev/PnP-Tools | Solutions/SharePoint.Visio.Scanner/SharePoint.Visio.Scanner/Options.cs | 5372 | using CommandLine;
using SharePoint.Scanning.Framework;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SharePoint.Visio.Scanner
{
/// <summary>
/// Possible scanning modes
/// </summary>
public enum Mode
{
Full = 0,
VdwOnly
}
/// <summary>
/// Commandline options
/// </summary>
public class Options : BaseOptions
{
// Important:
// Following chars are already used as shorthand in the base options class: i, s, u, p, f, x, a, t, e, r, v, o, h, z
[Option('m', "mode", HelpText = "Execution mode. Use following modes: full, VdwOnly. Omit or use full for a full scan", DefaultValue = Mode.Full, Required = false)]
public Mode Mode { get; set; }
/// <summary>
/// Validate the provided commandline options, will exit the program when not valid
/// </summary>
/// <param name="args">Command line arguments</param>
public override void ValidateOptions(string[] args)
{
if (args.Length == 0)
{
Console.WriteLine(this.GetUsage());
Environment.Exit(CommandLine.Parser.DefaultExitCodeFail);
}
// Perform base validation
base.ValidateOptions(args);
}
/// <summary>
/// Shows the usage information of the scanner
/// </summary>
/// <returns>String with the usage information</returns>
[HelpOption]
public string GetUsage()
{
var help = this.GetUsage("SharePoint Visio scanner");
help.AddPreOptionsLine("");
help.AddPreOptionsLine("==========================================================");
help.AddPreOptionsLine("");
help.AddPreOptionsLine("See the PnP-Tools repo for more information at:");
help.AddPreOptionsLine("https://github.com/SharePoint/PnP-Tools/tree/master/Solutions/SharePoint.Visio.Scanner");
help.AddPreOptionsLine("");
help.AddPreOptionsLine("Let the tool figure out your urls (works only for SPO MT):");
help.AddPreOptionsLine("==========================================================");
help.AddPreOptionsLine("Using Azure AD app-only:");
help.AddPreOptionsLine("SharePoint.Visio.Scanner.exe -t <tenant> -i <your client id> -z <Azure AD domain> -f <PFX file> -x <PFX file password>");
help.AddPreOptionsLine("e.g. SharePoint.Visio.Scanner.exe -t contoso -i e5808e8b-6119-44a9-b9d8-9003db04a882 -z contoso.onmicrosoft.com -f apponlycert.pfx -x pwd");
help.AddPreOptionsLine("");
help.AddPreOptionsLine("Using app-only:");
help.AddPreOptionsLine("SharePoint.Visio.Scanner.exe -t <tenant> -i <your client id> -s <your client secret>");
help.AddPreOptionsLine("e.g. SharePoint.Visio.Scanner.exe -t contoso -i 7a5c1615-997a-4059-a784-db2245ec7cc1 -s eOb6h+s805O/V3DOpd0dalec33Q6ShrHlSKkSra1FFw=");
help.AddPreOptionsLine("");
help.AddPreOptionsLine("Using credentials:");
help.AddPreOptionsLine("SharePoint.Visio.Scanner.exe -t <tenant> -u <your user id> -p <your user password>");
help.AddPreOptionsLine("");
help.AddPreOptionsLine("e.g. SharePoint.Visio.Scanner.exe -t contoso -u spadmin@contoso.onmicrosoft.com -p pwd");
help.AddPreOptionsLine("");
help.AddPreOptionsLine("Specifying url to your sites and tenant admin (needed for SPO Dedicated):");
help.AddPreOptionsLine("=========================================================================");
help.AddPreOptionsLine("Using Azure AD app-only:");
help.AddPreOptionsLine("SharePoint.Visio.Scanner.exe -r <wildcard urls> -a <tenant admin site> -i <your client id> -z <Azure AD domain> -f <PFX file> -x <PFX file password>");
help.AddPreOptionsLine("e.g. SharePoint.Visio.Scanner.exe -r \"https://teams.contoso.com/sites/*,https://my.contoso.com/personal/*\" -a https://contoso-admin.contoso.com -i e5808e8b-6119-44a9-b9d8-9003db04a882 -z conto.onmicrosoft.com -f apponlycert.pfx -x pwd");
help.AddPreOptionsLine("");
help.AddPreOptionsLine("Using app-only:");
help.AddPreOptionsLine("SharePoint.Visio.Scanner.exe -r <wildcard urls> -a <tenant admin site> -i <your client id> -s <your client secret>");
help.AddPreOptionsLine("e.g. SharePoint.Visio.Scanner.exe -r \"https://teams.contoso.com/sites/*,https://my.contoso.com/personal/*\" -a https://contoso-admin.contoso.com -i 7a5c1615-997a-4059-a784-db2245ec7cc1 -s eOb6h+s805O/V3DOpd0dalec33Q6ShrHlSKkSra1FFw=");
help.AddPreOptionsLine("");
help.AddPreOptionsLine("Using credentials:");
help.AddPreOptionsLine("SharePoint.Visio.Scanner.exe -r <wildcard urls> -a <tenant admin site> -u <your user id> -p <your user password>");
help.AddPreOptionsLine("e.g. SharePoint.Visio.Scanner.exe -r \"https://teams.contoso.com/sites/*,https://my.contoso.com/personal/*\" -a https://contoso-admin.contoso.com -u spadmin@contoso.com -p pwd");
help.AddPreOptionsLine("");
help.AddOptions(this);
return help;
}
}
}
| mit |
dbolkensteyn/sonar-msbuild-runner | SonarQube.Common/VerbosityCalculator.cs | 4143 | //-----------------------------------------------------------------------
// <copyright file="VerbosityCalculator.cs" company="SonarSource SA and Microsoft Corporation">
// Copyright (c) SonarSource SA and Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// </copyright>
//-----------------------------------------------------------------------
using System;
using System.Linq;
namespace SonarQube.Common
{
/// <summary>
/// The integration assemblies use the SonarQube log specific settings to determine verbosity. These settings are:
/// sonar.log.level is a flag enum with the values INFO, DEBUG and TRACE - and a valid value is INFO|DEBUG
/// sonar.verbosity can be true or false and will override sonar.log.level by setting it to INFO|DEBUG or to INFO
/// All values are case-sensitive. The calculator ignores invalid values.
/// </summary>
public static class VerbosityCalculator
{
/// <summary>
/// The initial verbosity of loggers
/// </summary>
/// <remarks>
/// Each of the executables (bootstrapper, pre/post processor) have to parse their command line and config files before
/// being able to deduce the correct verbosity. In doing that it makes sense to set the logger to be more verbose before
/// a value can be set so as not to miss out on messages.
/// </remarks>
public const LoggerVerbosity InitialLoggingVerbosity = LoggerVerbosity.Debug;
/// <summary>
/// The verbosity of loggers if no settings have been specified
/// </summary>
public const LoggerVerbosity DefaultLoggingVerbosity = LoggerVerbosity.Info;
private const string SonarLogDebugValue = "DEBUG";
/// <summary>
/// Computes verbosity based on the available properties.
/// </summary>
/// <remarks>If no verbosity setting is present, the default verbosity (info) is used</remarks>
public static LoggerVerbosity ComputeVerbosity(IAnalysisPropertyProvider properties, ILogger logger)
{
if (properties == null)
{
throw new ArgumentNullException("properties");
}
if (logger == null)
{
throw new ArgumentNullException("logger");
}
string sonarVerboseValue;
properties.TryGetValue(SonarProperties.Verbose, out sonarVerboseValue);
string sonarLogLevelValue;
properties.TryGetValue(SonarProperties.LogLevel, out sonarLogLevelValue);
return ComputeVerbosity(sonarVerboseValue, sonarLogLevelValue, logger);
}
private static LoggerVerbosity ComputeVerbosity(string sonarVerboseValue, string sonarLogValue, ILogger logger)
{
if (!String.IsNullOrWhiteSpace(sonarVerboseValue))
{
if (sonarVerboseValue.Equals("true", StringComparison.Ordinal))
{
logger.LogDebug(Resources.MSG_SonarVerboseWasSpecified, sonarVerboseValue, LoggerVerbosity.Debug);
return LoggerVerbosity.Debug;
}
else if (sonarVerboseValue.Equals("false", StringComparison.Ordinal))
{
logger.LogDebug(Resources.MSG_SonarVerboseWasSpecified, sonarVerboseValue, LoggerVerbosity.Info);
return LoggerVerbosity.Info;
}
else
{
logger.LogWarning(Resources.WARN_SonarVerboseNotBool, sonarVerboseValue);
}
}
if (!String.IsNullOrWhiteSpace(sonarLogValue))
{
if (sonarLogValue.Split('|').Any(s => s.Equals(SonarLogDebugValue, StringComparison.Ordinal)))
{
logger.LogDebug(Resources.MSG_SonarLogLevelWasSpecified, sonarLogValue);
return LoggerVerbosity.Debug;
}
}
return DefaultLoggingVerbosity;
}
}
} | mit |
donid/QuantityTypes | Source/QuantityTypes/Quantities/RadiationAbsorbedDose.cs | 22673 | // --------------------------------------------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a T4 template.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
// <copyright file="RadiationAbsorbedDose.cs" company="QuantityTypes">
// Copyright (c) 2014 QuantityTypes contributors
// </copyright>
// <summary>
// Represents the radiation absorbed dose quantity.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace QuantityTypes
{
using System;
#if !PCL
using System.ComponentModel;
#endif
using System.Globalization;
using System.Runtime.Serialization;
using System.Xml.Serialization;
/// <summary>
/// Represents the radiation absorbed dose quantity.
/// </summary>
[DataContract]
#if !PCL
[Serializable]
[TypeConverter(typeof(QuantityTypeConverter<RadiationAbsorbedDose>))]
#endif
public partial struct RadiationAbsorbedDose : IQuantity<RadiationAbsorbedDose>
{
/// <summary>
/// The backing field for the <see cref="Gray" /> property.
/// </summary>
private static readonly RadiationAbsorbedDose GrayField = new RadiationAbsorbedDose(1);
/// <summary>
/// The value.
/// </summary>
private double value;
/// <summary>
/// Initializes a new instance of the <see cref="RadiationAbsorbedDose"/> struct.
/// </summary>
/// <param name="value">
/// The value.
/// </param>
public RadiationAbsorbedDose(double value)
{
this.value = value;
}
/// <summary>
/// Initializes a new instance of the <see cref="RadiationAbsorbedDose"/> struct.
/// </summary>
/// <param name="value">
/// The value.
/// </param>
/// <param name="unitProvider">
/// The unit provider.
/// </param>
public RadiationAbsorbedDose(string value, IUnitProvider unitProvider = null)
{
this.value = Parse(value, unitProvider ?? UnitProvider.Default).value;
}
/// <summary>
/// Gets the "Gy" unit.
/// </summary>
[Unit("Gy", true)]
public static RadiationAbsorbedDose Gray
{
get { return GrayField; }
}
/// <summary>
/// Gets or sets the radiation absorbed dose as a string.
/// </summary>
/// <value>The string.</value>
/// <remarks>
/// This property is used for XML serialization.
/// </remarks>
[XmlText]
[DataMember]
public string XmlValue
{
get
{
// Use round-trip format
return this.ToString("R", CultureInfo.InvariantCulture);
}
set
{
this.value = Parse(value, CultureInfo.InvariantCulture).value;
}
}
/// <summary>
/// Gets the value of the radiation absorbed dose in the base unit.
/// </summary>
public double Value
{
get
{
return this.value;
}
}
/// <summary>
/// Converts a string representation of a quantity in a specific culture-specific format with a specific unit provider.
/// </summary>
/// <param name="input">
/// A string that contains the quantity to convert.
/// </param>
/// <param name="provider">
/// An object that supplies culture-specific formatting information about <paramref name="input" />. If not specified, the culture of the default <see cref="UnitProvider" /> is used.
/// </param>
/// <param name="unitProvider">
/// The unit provider. If not specified, the default <see cref="UnitProvider" /> is used.
/// </param>
/// <returns>
/// A <see cref="RadiationAbsorbedDose"/> that represents the quantity in <paramref name="input" />.
/// </returns>
public static RadiationAbsorbedDose Parse(string input, IFormatProvider provider, IUnitProvider unitProvider)
{
if (unitProvider == null)
{
unitProvider = provider as IUnitProvider ?? UnitProvider.Default;
}
RadiationAbsorbedDose value;
if (!unitProvider.TryParse(input, provider, out value))
{
throw new FormatException("Invalid format.");
}
return value;
}
/// <summary>
/// Converts a string representation of a quantity in a specific culture-specific format.
/// </summary>
/// <param name="input">
/// A string that contains the quantity to convert.
/// </param>
/// <param name="provider">
/// An object that supplies culture-specific formatting information about <paramref name="input" />. If not specified, the culture of the default <see cref="UnitProvider" /> is used.
/// </param>
/// <returns>
/// A <see cref="RadiationAbsorbedDose"/> that represents the quantity in <paramref name="input" />.
/// </returns>
public static RadiationAbsorbedDose Parse(string input, IFormatProvider provider = null)
{
var unitProvider = provider as IUnitProvider ?? UnitProvider.Default;
RadiationAbsorbedDose value;
if (!unitProvider.TryParse(input, provider, out value))
{
throw new FormatException("Invalid format.");
}
return value;
}
/// <summary>
/// Converts a string representation of a quantity with a specific unit provider.
/// </summary>
/// <param name="input">
/// A string that contains the quantity to convert.
/// </param>
/// <param name="unitProvider">
/// The unit provider. If not specified, the default <see cref="UnitProvider" /> is used.
/// </param>
/// <returns>
/// A <see cref="RadiationAbsorbedDose"/> that represents the quantity in <paramref name="input" />.
/// </returns>
public static RadiationAbsorbedDose Parse(string input, IUnitProvider unitProvider)
{
if (unitProvider == null)
{
unitProvider = UnitProvider.Default;
}
RadiationAbsorbedDose value;
if (!unitProvider.TryParse(input, unitProvider.Culture, out value))
{
throw new FormatException("Invalid format.");
}
return value;
}
/// <summary>
/// Tries to parse the specified string.
/// </summary>
/// <param name="input">The input string.</param>
/// <param name="provider">The format provider.</param>
/// <param name="unitProvider">The unit provider.</param>
/// <param name="result">The result.</param>
/// <returns><c>true</c> if the string was parsed, <c>false</c> otherwise.</returns>
public static bool TryParse(string input, IFormatProvider provider, IUnitProvider unitProvider, out RadiationAbsorbedDose result)
{
if (unitProvider == null)
{
unitProvider = provider as IUnitProvider ?? UnitProvider.Default;
}
return unitProvider.TryParse(input, provider, out result);
}
/// <summary>
/// Parses the specified JSON string.
/// </summary>
/// <param name="input">The JSON input.</param>
/// <returns>
/// The <see cref="RadiationAbsorbedDose"/> .
/// </returns>
public static RadiationAbsorbedDose ParseJson(string input)
{
return Parse(input, CultureInfo.InvariantCulture);
}
/// <summary>
/// Implements the operator +.
/// </summary>
/// <param name="x">
/// The first value.
/// </param>
/// <param name="y">
/// The second value.
/// </param>
/// <returns>
/// The result of the operator.
/// </returns>
public static RadiationAbsorbedDose operator +(RadiationAbsorbedDose x, RadiationAbsorbedDose y)
{
return new RadiationAbsorbedDose(x.value + y.value);
}
/// <summary>
/// Implements the operator /.
/// </summary>
/// <param name="x">
/// The x.
/// </param>
/// <param name="y">
/// The y.
/// </param>
/// <returns>
/// The result of the operator.
/// </returns>
public static RadiationAbsorbedDose operator /(RadiationAbsorbedDose x, double y)
{
return new RadiationAbsorbedDose(x.value / y);
}
/// <summary>
/// Implements the operator /.
/// </summary>
/// <param name="x">
/// The x.
/// </param>
/// <param name="y">
/// The y.
/// </param>
/// <returns>
/// The result of the operator.
/// </returns>
public static double operator /(RadiationAbsorbedDose x, RadiationAbsorbedDose y)
{
return x.value / y.value;
}
/// <summary>
/// Implements the operator ==.
/// </summary>
/// <param name="x">
/// The x.
/// </param>
/// <param name="y">
/// The y.
/// </param>
/// <returns>
/// The result of the operator.
/// </returns>
public static bool operator ==(RadiationAbsorbedDose x, RadiationAbsorbedDose y)
{
return x.value.Equals(y.value);
}
/// <summary>
/// Implements the operator >.
/// </summary>
/// <param name="x">
/// The x.
/// </param>
/// <param name="y">
/// The y.
/// </param>
/// <returns>
/// The result of the operator.
/// </returns>
public static bool operator >(RadiationAbsorbedDose x, RadiationAbsorbedDose y)
{
return x.value > y.value;
}
/// <summary>
/// Implements the operator >=.
/// </summary>
/// <param name="x">
/// The x.
/// </param>
/// <param name="y">
/// The y.
/// </param>
/// <returns>
/// The result of the operator.
/// </returns>
public static bool operator >=(RadiationAbsorbedDose x, RadiationAbsorbedDose y)
{
return x.value >= y.value;
}
/// <summary>
/// Implements the operator !=.
/// </summary>
/// <param name="x">
/// The x.
/// </param>
/// <param name="y">
/// The y.
/// </param>
/// <returns>
/// The result of the operator.
/// </returns>
public static bool operator !=(RadiationAbsorbedDose x, RadiationAbsorbedDose y)
{
return !x.value.Equals(y.value);
}
/// <summary>
/// Implements the operator <.
/// </summary>
/// <param name="x">
/// The x.
/// </param>
/// <param name="y">
/// The y.
/// </param>
/// <returns>
/// The result of the operator.
/// </returns>
public static bool operator <(RadiationAbsorbedDose x, RadiationAbsorbedDose y)
{
return x.value < y.value;
}
/// <summary>
/// Implements the operator <=.
/// </summary>
/// <param name="x">
/// The x.
/// </param>
/// <param name="y">
/// The y.
/// </param>
/// <returns>
/// The result of the operator.
/// </returns>
public static bool operator <=(RadiationAbsorbedDose x, RadiationAbsorbedDose y)
{
return x.value <= y.value;
}
/// <summary>
/// Implements the operator *.
/// </summary>
/// <param name="x">
/// The x.
/// </param>
/// <param name="y">
/// The y.
/// </param>
/// <returns>
/// The result of the operator.
/// </returns>
public static RadiationAbsorbedDose operator *(double x, RadiationAbsorbedDose y)
{
return new RadiationAbsorbedDose(x * y.value);
}
/// <summary>
/// Implements the operator *.
/// </summary>
/// <param name="x">
/// The x.
/// </param>
/// <param name="y">
/// The y.
/// </param>
/// <returns>
/// The result of the operator.
/// </returns>
public static RadiationAbsorbedDose operator *(RadiationAbsorbedDose x, double y)
{
return new RadiationAbsorbedDose(x.value * y);
}
/// <summary>
/// Implements the operator -.
/// </summary>
/// <param name="x">
/// The x.
/// </param>
/// <param name="y">
/// The y.
/// </param>
/// <returns>
/// The result of the operator.
/// </returns>
public static RadiationAbsorbedDose operator -(RadiationAbsorbedDose x, RadiationAbsorbedDose y)
{
return new RadiationAbsorbedDose(x.value - y.value);
}
/// <summary>
/// Implements the unary plus operator.
/// </summary>
/// <param name="x">
/// The x.
/// </param>
/// <returns>
/// The result of the operator.
/// </returns>
public static RadiationAbsorbedDose operator +(RadiationAbsorbedDose x)
{
return new RadiationAbsorbedDose(x.value);
}
/// <summary>
/// Implements the unary minus operator.
/// </summary>
/// <param name="x">
/// The x.
/// </param>
/// <returns>
/// The result of the operator.
/// </returns>
public static RadiationAbsorbedDose operator -(RadiationAbsorbedDose x)
{
return new RadiationAbsorbedDose(-x.value);
}
/// <summary>
/// Compares this instance to the specified <see cref="RadiationAbsorbedDose"/> and returns an indication of their relative values.
/// </summary>
/// <param name="other">
/// The other <see cref="RadiationAbsorbedDose"/> .
/// </param>
/// <returns>
/// A signed number indicating the relative values of this instance and the other value.
/// </returns>
public int CompareTo(RadiationAbsorbedDose other)
{
return this.value.CompareTo(other.value);
}
/// <summary>
/// Compares the current instance with another object of the same type and returns an integer that indicates whether the
/// current instance precedes, follows, or occurs in the same position in the sort order as the other object.
/// </summary>
/// <param name="obj">An object to compare with this instance.</param>
/// <returns>
/// A value that indicates the relative order of the objects being compared. The return value has these meanings:
/// Value Meaning Less than zero This instance is less than <paramref name="obj" />. Zero This instance is equal to
/// <paramref name="obj" />. Greater than zero This instance is greater than <paramref name="obj" />.
/// </returns>
public int CompareTo(object obj)
{
return this.CompareTo((RadiationAbsorbedDose)obj);
}
/// <summary>
/// Converts the quantity to the specified unit.
/// </summary>
/// <param name="unit">The unit.</param>
/// <returns>The amount of the specified unit.</returns>
double IQuantity.ConvertTo(IQuantity unit)
{
return this.ConvertTo((RadiationAbsorbedDose)unit);
}
/// <summary>
/// Converts to the specified unit.
/// </summary>
/// <param name="unit">
/// The unit.
/// </param>
/// <returns>
/// The value in the specified unit.
/// </returns>
public double ConvertTo(RadiationAbsorbedDose unit)
{
return this.value / unit.Value;
}
/// <summary>
/// Determines whether the specified <see cref="System.Object"/> is equal to this instance.
/// </summary>
/// <param name="obj">
/// The <see cref="System.Object"/> to compare with this instance.
/// </param>
/// <returns>
/// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c> .
/// </returns>
public override bool Equals(object obj)
{
if (obj is RadiationAbsorbedDose)
{
return this.Equals((RadiationAbsorbedDose)obj);
}
return false;
}
/// <summary>
/// Determines if the specified <see cref="RadiationAbsorbedDose"/> is equal to this instance.
/// </summary>
/// <param name="other">
/// The other <see cref="RadiationAbsorbedDose"/> .
/// </param>
/// <returns>
/// True if the values are equal.
/// </returns>
public bool Equals(RadiationAbsorbedDose other)
{
return this.value.Equals(other.value);
}
/// <summary>
/// Returns a hash code for this instance.
/// </summary>
/// <returns>
/// A hash code for this instance, suitable for use in hashing algorithms and data structures like a hash table.
/// </returns>
public override int GetHashCode()
{
return this.Value.GetHashCode();
}
/// <summary>
/// Multiplies by the specified number.
/// </summary>
/// <param name="x">The number.</param>
/// <returns>The new quantity.</returns>
public IQuantity MultiplyBy(double x)
{
return this * x;
}
/// <summary>
/// Adds the specified quantity.
/// </summary>
/// <param name="x">The quantity to add.</param>
/// <returns>The sum.</returns>
public IQuantity Add(IQuantity x)
{
if (!(x is RadiationAbsorbedDose))
{
throw new InvalidOperationException("Can only add quantities of the same types.");
}
return new RadiationAbsorbedDose(this.value + x.Value);
}
/// <summary>
/// Sets the value from the specified string.
/// </summary>
/// <param name="s">
/// The s.
/// </param>
/// <param name="provider">
/// The provider.
/// </param>
public void SetFromString(string s, IUnitProvider provider)
{
this.value = Parse(s, provider).value;
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="System.String"/> that represents this instance.
/// </returns>
public override string ToString()
{
return this.ToString(null, UnitProvider.Default);
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
/// <param name="formatProvider">
/// The format provider.
/// </param>
/// <returns>
/// A <see cref="System.String"/> that represents this instance.
/// </returns>
public string ToString(IFormatProvider formatProvider)
{
var unitProvider = formatProvider as IUnitProvider ?? UnitProvider.Default;
return this.ToString(null, formatProvider, unitProvider);
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
/// <param name="format">
/// The format.
/// </param>
/// <param name="formatProvider">
/// The format provider.
/// </param>
/// <returns>
/// A <see cref="System.String"/> that represents this instance.
/// </returns>
public string ToString(string format, IFormatProvider formatProvider = null)
{
var unitProvider = formatProvider as IUnitProvider ?? UnitProvider.Default;
return this.ToString(format, formatProvider, unitProvider);
}
/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
/// <param name="format">
/// The format.
/// </param>
/// <param name="formatProvider">
/// The format provider.
/// </param>
/// <param name="unitProvider">
/// The unit provider.
/// </param>
/// <returns>
/// A <see cref="System.String"/> that represents this instance.
/// </returns>
public string ToString(string format, IFormatProvider formatProvider, IUnitProvider unitProvider)
{
if (unitProvider == null)
{
unitProvider = formatProvider as IUnitProvider ?? UnitProvider.Default;
}
return unitProvider.Format(format, formatProvider, this);
}
}
}
| mit |
henry-gobiernoabierto/geomoose | htdocs/libs/dojo/dojox/charting/action2d/Tooltip.js | 5428 | dojo.provide("dojox.charting.action2d.Tooltip");
dojo.require("dijit.Tooltip");
dojo.require("dojox.charting.action2d.Base");
dojo.require("dojox.gfx.matrix");
dojo.require("dojox.lang.functional");
dojo.require("dojox.lang.functional.scan");
dojo.require("dojox.lang.functional.fold");
/*=====
dojo.declare("dojox.charting.action2d.__TooltipCtorArgs", dojox.charting.action2d.__BaseCtorArgs, {
// summary:
// Additional arguments for tooltip actions.
// text: Function?
// The function that produces the text to be shown within a tooltip. By default this will be
// set by the plot in question, by returning the value of the element.
text: null
});
=====*/
(function(){
var DEFAULT_TEXT = function(o){
var t = o.run && o.run.data && o.run.data[o.index];
if(t && typeof t != "number" && (t.tooltip || t.text)){
return t.tooltip || t.text;
}
if(o.element == "candlestick"){
return '<table cellpadding="1" cellspacing="0" border="0" style="font-size:0.9em;">'
+ '<tr><td>Open:</td><td align="right"><strong>' + o.data.open + '</strong></td></tr>'
+ '<tr><td>High:</td><td align="right"><strong>' + o.data.high + '</strong></td></tr>'
+ '<tr><td>Low:</td><td align="right"><strong>' + o.data.low + '</strong></td></tr>'
+ '<tr><td>Close:</td><td align="right"><strong>' + o.data.close + '</strong></td></tr>'
+ (o.data.mid !== undefined ? '<tr><td>Mid:</td><td align="right"><strong>' + o.data.mid + '</strong></td></tr>' : '')
+ '</table>';
}
return o.element == "bar" ? o.x : o.y;
};
var df = dojox.lang.functional, m = dojox.gfx.matrix, pi4 = Math.PI / 4, pi2 = Math.PI / 2;
dojo.declare("dojox.charting.action2d.Tooltip", dojox.charting.action2d.Base, {
// summary:
// Create an action on a plot where a tooltip is shown when hovering over an element.
// the data description block for the widget parser
defaultParams: {
text: DEFAULT_TEXT // the function to produce a tooltip from the object
},
optionalParams: {}, // no optional parameters
constructor: function(chart, plot, kwArgs){
// summary:
// Create the tooltip action and connect it to the plot.
// chart: dojox.charting.Chart2D
// The chart this action belongs to.
// plot: String?
// The plot this action is attached to. If not passed, "default" is assumed.
// kwArgs: dojox.charting.action2d.__TooltipCtorArgs?
// Optional keyword arguments object for setting parameters.
this.text = kwArgs && kwArgs.text ? kwArgs.text : DEFAULT_TEXT;
this.connect();
},
process: function(o){
// summary:
// Process the action on the given object.
// o: dojox.gfx.Shape
// The object on which to process the highlighting action.
if(o.type === "onplotreset" || o.type === "onmouseout"){
dijit.hideTooltip(this.aroundRect);
this.aroundRect = null;
if(o.type === "onplotreset"){
delete this.angles;
}
return;
}
if(!o.shape || o.type !== "onmouseover"){ return; }
// calculate relative coordinates and the position
var aroundRect = {type: "rect"}, position = ["after", "before"];
switch(o.element){
case "marker":
aroundRect.x = o.cx;
aroundRect.y = o.cy;
aroundRect.width = aroundRect.height = 1;
break;
case "circle":
aroundRect.x = o.cx - o.cr;
aroundRect.y = o.cy - o.cr;
aroundRect.width = aroundRect.height = 2 * o.cr;
break;
case "column":
position = ["above", "below"];
// intentional fall down
case "bar":
aroundRect = dojo.clone(o.shape.getShape());
break;
case "candlestick":
aroundRect.x = o.x;
aroundRect.y = o.y;
aroundRect.width = o.width;
aroundRect.height = o.height;
break;
default:
//case "slice":
if(!this.angles){
// calculate the running total of slice angles
if(typeof o.run.data[0] == "number"){
this.angles = df.map(df.scanl(o.run.data, "+", 0),
"* 2 * Math.PI / this", df.foldl(o.run.data, "+", 0));
}else{
this.angles = df.map(df.scanl(o.run.data, "a + b.y", 0),
"* 2 * Math.PI / this", df.foldl(o.run.data, "a + b.y", 0));
}
}
var startAngle = m._degToRad(o.plot.opt.startAngle),
angle = (this.angles[o.index] + this.angles[o.index + 1]) / 2 + startAngle;
aroundRect.x = o.cx + o.cr * Math.cos(angle);
aroundRect.y = o.cy + o.cr * Math.sin(angle);
aroundRect.width = aroundRect.height = 1;
// calculate the position
if(angle < pi4){
// do nothing: the position is right
}else if(angle < pi2 + pi4){
position = ["below", "above"];
}else if(angle < Math.PI + pi4){
position = ["before", "after"];
}else if(angle < 2 * Math.PI - pi4){
position = ["above", "below"];
}
/*
else{
// do nothing: the position is right
}
*/
break;
}
// adjust relative coordinates to absolute, and remove fractions
var lt = dojo.coords(this.chart.node, true);
aroundRect.x += lt.x;
aroundRect.y += lt.y;
aroundRect.x = Math.round(aroundRect.x);
aroundRect.y = Math.round(aroundRect.y);
aroundRect.width = Math.ceil(aroundRect.width);
aroundRect.height = Math.ceil(aroundRect.height);
this.aroundRect = aroundRect;
var tooltip = this.text(o);
if(tooltip){
dijit.showTooltip(tooltip, this.aroundRect, position);
}
}
});
})();
| mit |
seryl/traefik | middlewares/accesslog/logger.go | 4016 | package accesslog
import (
"context"
"fmt"
"net"
"net/http"
"net/url"
"sync/atomic"
"time"
)
type key string
const (
// DataTableKey is the key within the request context used to
// store the Log Data Table
DataTableKey key = "LogDataTable"
)
// LogHandler will write each request and its response to the access log.
// It gets some information from the logInfoResponseWriter set up by previous middleware.
// Note: Current implementation collects log data but does not have the facility to
// write anywhere.
type LogHandler struct {
}
// NewLogHandler creates a new LogHandler
func NewLogHandler() *LogHandler {
return &LogHandler{}
}
// GetLogDataTable gets the request context object that contains logging data. This accretes
// data as the request passes through the middleware chain.
func GetLogDataTable(req *http.Request) *LogData {
return req.Context().Value(DataTableKey).(*LogData)
}
func (l *LogHandler) ServeHTTP(rw http.ResponseWriter, req *http.Request, next http.HandlerFunc) {
now := time.Now().UTC()
core := make(CoreLogData)
logDataTable := &LogData{Core: core, Request: req.Header}
core[StartUTC] = now
core[StartLocal] = now.Local()
reqWithDataTable := req.WithContext(context.WithValue(req.Context(), DataTableKey, logDataTable))
var crr *captureRequestReader
if req.Body != nil {
crr = &captureRequestReader{source: req.Body, count: 0}
reqWithDataTable.Body = crr
}
core[RequestCount] = nextRequestCount()
if req.Host != "" {
core[RequestAddr] = req.Host
core[RequestHost], core[RequestPort] = silentSplitHostPort(req.Host)
}
// copy the URL without the scheme, hostname etc
urlCopy := &url.URL{
Path: req.URL.Path,
RawPath: req.URL.RawPath,
RawQuery: req.URL.RawQuery,
ForceQuery: req.URL.ForceQuery,
Fragment: req.URL.Fragment,
}
urlCopyString := urlCopy.String()
core[RequestMethod] = req.Method
core[RequestPath] = urlCopyString
core[RequestProtocol] = req.Proto
core[RequestLine] = fmt.Sprintf("%s %s %s", req.Method, urlCopyString, req.Proto)
core[ClientAddr] = req.RemoteAddr
core[ClientHost], core[ClientPort] = silentSplitHostPort(req.RemoteAddr)
core[ClientUsername] = usernameIfPresent(req.URL)
crw := &captureResponseWriter{rw: rw}
next.ServeHTTP(crw, reqWithDataTable)
logDataTable.DownstreamResponse = crw.Header()
l.logTheRoundTrip(logDataTable, crr, crw)
}
// Close closes the Logger (i.e. the file etc).
func (l *LogHandler) Close() error {
return nil
}
func silentSplitHostPort(value string) (host string, port string) {
host, port, err := net.SplitHostPort(value)
if err != nil {
return value, "-"
}
return host, port
}
func usernameIfPresent(theURL *url.URL) string {
username := "-"
if theURL.User != nil {
if name := theURL.User.Username(); name != "" {
username = name
}
}
return username
}
// Logging handler to log frontend name, backend name, and elapsed time
func (l *LogHandler) logTheRoundTrip(logDataTable *LogData, crr *captureRequestReader, crw *captureResponseWriter) {
core := logDataTable.Core
if crr != nil {
core[RequestContentSize] = crr.count
}
core[DownstreamStatus] = crw.Status()
core[DownstreamStatusLine] = fmt.Sprintf("%03d %s", crw.Status(), http.StatusText(crw.Status()))
core[DownstreamContentSize] = crw.Size()
if original, ok := core[OriginContentSize]; ok {
o64 := original.(int64)
if o64 != crw.Size() && 0 != crw.Size() {
core[GzipRatio] = float64(o64) / float64(crw.Size())
}
}
// n.b. take care to perform time arithmetic using UTC to avoid errors at DST boundaries
total := time.Now().UTC().Sub(core[StartUTC].(time.Time))
core[Duration] = total
if origin, ok := core[OriginDuration]; ok {
core[Overhead] = total - origin.(time.Duration)
} else {
core[Overhead] = total
}
}
//-------------------------------------------------------------------------------------------------
var requestCounter uint64 // Request ID
func nextRequestCount() uint64 {
return atomic.AddUint64(&requestCounter, 1)
}
| mit |
unaio/una | upgrade/files/9.0.0.B5-9.0.0.RC1/files/inc/classes/BxDolSearchExtendedQuery.php | 3323 | <?php defined('BX_DOL') or die('hack attempt');
/**
* Copyright (c) UNA, Inc - https://una.io
* MIT License - https://opensource.org/licenses/MIT
*
* @defgroup UnaCore UNA Core
* @{
*/
class BxDolSearchExtendedQuery extends BxDolDb
{
public function __construct($aObject = array())
{
parent::__construct();
}
static public function getSearchObject($sObject)
{
$oDb = BxDolDb::getInstance();
$sQuery = $oDb->prepare("SELECT * FROM `sys_objects_search_extended` WHERE `object` = ?", $sObject);
$aObject = $oDb->getRow($sQuery);
if(!$aObject || !is_array($aObject))
return false;
$aObject['fields'] = self::getSearchFields($aObject);
return $aObject;
}
static public function getSearchFields($aObject)
{
$oDb = BxDolDb::getInstance();
$sQueryFields = "SELECT * FROM `sys_search_extended_fields` WHERE `object` = :object ORDER BY `order`";
$aQueryFieldsBindings = array('object' => $aObject['object']);
$aFields = $oDb->getAll($sQueryFields, $aQueryFieldsBindings);
//--- Get fields
if(empty($aFields) || !is_array($aFields)) {
$aFields = BxDolContentInfo::getObjectInstance($aObject['object_content_info'])->getSearchableFieldsExtended();
if(empty($aFields) || !is_array($aFields))
return array();
$iOrder = 0;
foreach($aFields as $sField => $aField)
$oDb->query("INSERT INTO `sys_search_extended_fields`(`object`, `name`, `type`, `caption`, `values`, `search_type`, `search_operator`, `active`, `order`) VALUES(:object, :name, :type, :caption, :values, :search_type, :search_operator, '1', :order)", array(
'object' => $aObject['object'],
'name' => $sField,
'type' => $aField['type'],
'caption' => $aField['caption'],
'values' => $aField['values'],
'search_type' => reset(BxDolSearchExtended::$TYPE_TO_TYPE_SEARCH[$aField['type']]),
'search_operator' => reset(BxDolSearchExtended::$TYPE_TO_OPERATOR[$aField['type']]),
'order' => $iOrder++
));
$aFields = $oDb->getAll($sQueryFields, $aQueryFieldsBindings);
}
//--- Process fields
foreach ($aFields as $iIndex => $aField) {
//--- Process field Values
if(!empty($aField['values'])) {
if(strncmp(BX_DATA_LISTS_KEY_PREFIX, $aField['values'], 2) === 0) {
$sList = trim($aField['values'], BX_DATA_LISTS_KEY_PREFIX . ' ');
$aFields[$iIndex] = array_merge($aField, array(
'values' => BxDolFormQuery::getDataItems($sList),
'values_list_name' => $sList,
));
}
else
$aFields[$iIndex]['values'] = unserialize($aField['values']);
}
}
return $aFields;
}
public function deleteFields($aWhere)
{
if(empty($aWhere))
return false;
return $this->query("DELETE FROM `sys_search_extended_fields` WHERE " . $this->arrayToSQL($aWhere, ' AND '));
}
}
/** @} */
| mit |
MadManRises/Madgine | shared/assimp/port/PyAssimp/gen/materialgen.py | 3618 | #!/usr/bin/env python
# -*- Coding: UTF-8 -*-
# ---------------------------------------------------------------------------
# Open Asset Import Library (ASSIMP)
# ---------------------------------------------------------------------------
#
# Copyright (c) 2006-2010, ASSIMP Development Team
#
# All rights reserved.
#
# Redistribution and use of this software in source and binary forms,
# with or without modification, are permitted provided that the following
# conditions are met:
#
# * Redistributions of source code must retain the above
# copyright notice, this list of conditions and the
# following disclaimer.
#
# * Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the
# following disclaimer in the documentation and/or other
# materials provided with the distribution.
#
# * Neither the name of the ASSIMP team, nor the names of its
# contributors may be used to endorse or promote products
# derived from this software without specific prior
# written permission of the ASSIMP Development Team.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# ---------------------------------------------------------------------------
"""Update PyAssimp's texture type constants C/C++ headers.
This script is meant to be executed in the source tree, directly from
port/PyAssimp/gen
"""
import os
import re
REenumTextureType = re.compile(r''
r'enum\saiTextureType' # enum aiTextureType
r'[^{]*?\{' # {
r'(?P<code>.*?)' # code
r'\};' # };
, re.IGNORECASE + re.DOTALL + re.MULTILINE)
# Replace comments
RErpcom = re.compile(r''
r'\s*(/\*+\s|\*+/|\B\*\s?|///?!?)' # /**
r'(?P<line>.*?)' # * line
, re.IGNORECASE + re.DOTALL)
# Remove trailing commas
RErmtrailcom = re.compile(r',$', re.IGNORECASE + re.DOTALL)
# Remove #ifdef __cplusplus
RErmifdef = re.compile(r''
r'#ifndef SWIG' # #ifndef SWIG
r'(?P<code>.*)' # code
r'#endif(\s*//\s*!?\s*SWIG)*' # #endif
, re.IGNORECASE + re.DOTALL)
path = '../../../include/assimp'
files = os.listdir (path)
enumText = ''
for fileName in files:
if fileName.endswith('.h'):
text = open(os.path.join(path, fileName)).read()
for enum in REenumTextureType.findall(text):
enumText = enum
text = ''
for line in enumText.split('\n'):
line = line.lstrip().rstrip()
line = RErmtrailcom.sub('', line)
text += RErpcom.sub('# \g<line>', line) + '\n'
text = RErmifdef.sub('', text)
file = open('material.py', 'w')
file.write(text)
file.close()
print("Generation done. You can now review the file 'material.py' and merge it.")
| mit |
trantorLiu/carrierwave-base64 | lib/carrierwave/base64/version.rb | 65 | module Carrierwave
module Base64
VERSION = "1.8"
end
end
| mit |
moonlitangel/moonlit_admin | src/app/shared/breadcrumb.component.ts | 1524 | import { Component } from '@angular/core';
import { Router, ActivatedRoute, NavigationEnd } from '@angular/router';
import 'rxjs/add/operator/filter';
@Component({
selector: 'breadcrumbs',
template: `
<template ngFor let-breadcrumb [ngForOf]="breadcrumbs" let-last = last>
<li class="breadcrumb-item" *ngIf="breadcrumb.label.title&&breadcrumb.url.substring(breadcrumb.url.length-1) == '/' || breadcrumb.label.title&&last" [ngClass]="{active: last}">
<a *ngIf="!last" [routerLink]="breadcrumb.url">{{breadcrumb.label.title}}</a>
<span *ngIf="last" [routerLink]="breadcrumb.url">{{breadcrumb.label.title}}</span>
</li>
</template>`
})
export class BreadcrumbsComponent {
breadcrumbs: Array<Object>;
constructor(private router:Router, private route:ActivatedRoute) {}
ngOnInit(): void {
this.router.events.filter(event => event instanceof NavigationEnd).subscribe(event => {
this.breadcrumbs = [];
let currentRoute = this.route.root,
url = '';
do {
let childrenRoutes = currentRoute.children;
currentRoute = null;
childrenRoutes.forEach(route => {
if(route.outlet === 'primary') {
let routeSnapshot = route.snapshot;
url += '/' + routeSnapshot.url.map(segment => segment.path).join('/');
this.breadcrumbs.push({
label: route.snapshot.data,
url: url
});
currentRoute = route;
}
})
} while(currentRoute);
})
}
}
| mit |
ist-dresden/composum | jslibs/src/main/resources/root/libs/jslibs/highlight/9.15.6/languages/java.js | 3400 | /*
Language: Java
Author: Vsevolod Solovyov <vsevolod.solovyov@gmail.com>
Category: common, enterprise
*/
function(hljs) {
var JAVA_IDENT_RE = '[\u00C0-\u02B8a-zA-Z_$][\u00C0-\u02B8a-zA-Z_$0-9]*';
var GENERIC_IDENT_RE = JAVA_IDENT_RE + '(<' + JAVA_IDENT_RE + '(\\s*,\\s*' + JAVA_IDENT_RE + ')*>)?';
var KEYWORDS =
'false synchronized int abstract float private char boolean var static null if const ' +
'for true while long strictfp finally protected import native final void ' +
'enum else break transient catch instanceof byte super volatile case assert short ' +
'package default double public try this switch continue throws protected public private ' +
'module requires exports do';
// https://docs.oracle.com/javase/7/docs/technotes/guides/language/underscores-literals.html
var JAVA_NUMBER_RE = '\\b' +
'(' +
'0[bB]([01]+[01_]+[01]+|[01]+)' + // 0b...
'|' +
'0[xX]([a-fA-F0-9]+[a-fA-F0-9_]+[a-fA-F0-9]+|[a-fA-F0-9]+)' + // 0x...
'|' +
'(' +
'([\\d]+[\\d_]+[\\d]+|[\\d]+)(\\.([\\d]+[\\d_]+[\\d]+|[\\d]+))?' +
'|' +
'\\.([\\d]+[\\d_]+[\\d]+|[\\d]+)' +
')' +
'([eE][-+]?\\d+)?' + // octal, decimal, float
')' +
'[lLfF]?';
var JAVA_NUMBER_MODE = {
className: 'number',
begin: JAVA_NUMBER_RE,
relevance: 0
};
return {
aliases: ['jsp'],
keywords: KEYWORDS,
illegal: /<\/|#/,
contains: [
hljs.COMMENT(
'/\\*\\*',
'\\*/',
{
relevance : 0,
contains : [
{
// eat up @'s in emails to prevent them to be recognized as doctags
begin: /\w+@/, relevance: 0
},
{
className : 'doctag',
begin : '@[A-Za-z]+'
}
]
}
),
hljs.C_LINE_COMMENT_MODE,
hljs.C_BLOCK_COMMENT_MODE,
hljs.APOS_STRING_MODE,
hljs.QUOTE_STRING_MODE,
{
className: 'class',
beginKeywords: 'class interface', end: /[{;=]/, excludeEnd: true,
keywords: 'class interface',
illegal: /[:"\[\]]/,
contains: [
{beginKeywords: 'extends implements'},
hljs.UNDERSCORE_TITLE_MODE
]
},
{
// Expression keywords prevent 'keyword Name(...)' from being
// recognized as a function definition
beginKeywords: 'new throw return else',
relevance: 0
},
{
className: 'function',
begin: '(' + GENERIC_IDENT_RE + '\\s+)+' + hljs.UNDERSCORE_IDENT_RE + '\\s*\\(', returnBegin: true, end: /[{;=]/,
excludeEnd: true,
keywords: KEYWORDS,
contains: [
{
begin: hljs.UNDERSCORE_IDENT_RE + '\\s*\\(', returnBegin: true,
relevance: 0,
contains: [hljs.UNDERSCORE_TITLE_MODE]
},
{
className: 'params',
begin: /\(/, end: /\)/,
keywords: KEYWORDS,
relevance: 0,
contains: [
hljs.APOS_STRING_MODE,
hljs.QUOTE_STRING_MODE,
hljs.C_NUMBER_MODE,
hljs.C_BLOCK_COMMENT_MODE
]
},
hljs.C_LINE_COMMENT_MODE,
hljs.C_BLOCK_COMMENT_MODE
]
},
JAVA_NUMBER_MODE,
{
className: 'meta', begin: '@[A-Za-z]+'
}
]
};
}
| mit |
adadesions/ohmysocial | node_modules/react-mounter/dist/index.js | 1161 | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _toConsumableArray2 = require('babel-runtime/helpers/toConsumableArray');
var _toConsumableArray3 = _interopRequireDefault(_toConsumableArray2);
exports.mount = mount;
exports.withOptions = withOptions;
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var mounter = null;
if (typeof window !== 'undefined') {
// now we are in the server
mounter = require('./client').mounter;
} else {
mounter = require('./server').mounter;
}
function mount(layoutClass, regions) {
var options = arguments.length <= 2 || arguments[2] === undefined ? {} : arguments[2];
options.rootId = options.rootId || 'react-root';
options.rootProps = options.rootProps || {};
mounter(layoutClass, regions, options);
}
function withOptions(options, fn) {
return function () {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
var newArgs = [].concat(args, [options]);
return fn.apply(undefined, (0, _toConsumableArray3.default)(newArgs));
};
} | mit |
enclose-io/compiler | lts/test/parallel/test-whatwg-url-custom-properties.js | 7500 | // Flags: --expose-internals
'use strict';
// Tests below are not from WPT.
require('../common');
const URL = require('url').URL;
const assert = require('assert');
const urlToOptions = require('internal/url').urlToOptions;
const url = new URL('http://user:pass@foo.bar.com:21/aaa/zzz?l=24#test');
const oldParams = url.searchParams; // For test of [SameObject]
// To retrieve enumerable but not necessarily own properties,
// we need to use the for-in loop.
const props = [];
for (const prop in url) {
props.push(prop);
}
// See: https://url.spec.whatwg.org/#api
// https://heycam.github.io/webidl/#es-attributes
// https://heycam.github.io/webidl/#es-stringifier
const expected = ['toString',
'href', 'origin', 'protocol',
'username', 'password', 'host', 'hostname', 'port',
'pathname', 'search', 'searchParams', 'hash', 'toJSON'];
assert.deepStrictEqual(props, expected);
// `href` is writable (not readonly) and is stringifier
assert.strictEqual(url.toString(), url.href);
url.href = 'http://user:pass@foo.bar.com:21/aaa/zzz?l=25#test';
assert.strictEqual(url.href,
'http://user:pass@foo.bar.com:21/aaa/zzz?l=25#test');
assert.strictEqual(url.toString(), url.href);
// Return true because it's configurable, but because the properties
// are defined on the prototype per the spec, the deletion has no effect
assert.strictEqual((delete url.href), true);
assert.strictEqual(url.href,
'http://user:pass@foo.bar.com:21/aaa/zzz?l=25#test');
assert.strictEqual(url.searchParams, oldParams); // [SameObject]
// searchParams is readonly. Under strict mode setting a
// non-writable property should throw.
// Note: this error message is subject to change in V8 updates
assert.throws(
() => url.origin = 'http://foo.bar.com:22',
/^TypeError: Cannot set property origin of \[object URL\] which has only a getter$/
);
assert.strictEqual(url.origin, 'http://foo.bar.com:21');
assert.strictEqual(url.toString(),
'http://user:pass@foo.bar.com:21/aaa/zzz?l=25#test');
assert.strictEqual((delete url.origin), true);
assert.strictEqual(url.origin, 'http://foo.bar.com:21');
// The following properties should be writable (not readonly)
url.protocol = 'https:';
assert.strictEqual(url.protocol, 'https:');
assert.strictEqual(url.toString(),
'https://user:pass@foo.bar.com:21/aaa/zzz?l=25#test');
assert.strictEqual((delete url.protocol), true);
assert.strictEqual(url.protocol, 'https:');
url.username = 'user2';
assert.strictEqual(url.username, 'user2');
assert.strictEqual(url.toString(),
'https://user2:pass@foo.bar.com:21/aaa/zzz?l=25#test');
assert.strictEqual((delete url.username), true);
assert.strictEqual(url.username, 'user2');
url.password = 'pass2';
assert.strictEqual(url.password, 'pass2');
assert.strictEqual(url.toString(),
'https://user2:pass2@foo.bar.com:21/aaa/zzz?l=25#test');
assert.strictEqual((delete url.password), true);
assert.strictEqual(url.password, 'pass2');
url.host = 'foo.bar.net:22';
assert.strictEqual(url.host, 'foo.bar.net:22');
assert.strictEqual(url.toString(),
'https://user2:pass2@foo.bar.net:22/aaa/zzz?l=25#test');
assert.strictEqual((delete url.host), true);
assert.strictEqual(url.host, 'foo.bar.net:22');
url.hostname = 'foo.bar.org';
assert.strictEqual(url.hostname, 'foo.bar.org');
assert.strictEqual(url.toString(),
'https://user2:pass2@foo.bar.org:22/aaa/zzz?l=25#test');
assert.strictEqual((delete url.hostname), true);
assert.strictEqual(url.hostname, 'foo.bar.org');
url.port = '23';
assert.strictEqual(url.port, '23');
assert.strictEqual(url.toString(),
'https://user2:pass2@foo.bar.org:23/aaa/zzz?l=25#test');
assert.strictEqual((delete url.port), true);
assert.strictEqual(url.port, '23');
url.pathname = '/aaa/bbb';
assert.strictEqual(url.pathname, '/aaa/bbb');
assert.strictEqual(url.toString(),
'https://user2:pass2@foo.bar.org:23/aaa/bbb?l=25#test');
assert.strictEqual((delete url.pathname), true);
assert.strictEqual(url.pathname, '/aaa/bbb');
url.search = '?k=99';
assert.strictEqual(url.search, '?k=99');
assert.strictEqual(url.toString(),
'https://user2:pass2@foo.bar.org:23/aaa/bbb?k=99#test');
assert.strictEqual((delete url.search), true);
assert.strictEqual(url.search, '?k=99');
url.hash = '#abcd';
assert.strictEqual(url.hash, '#abcd');
assert.strictEqual(url.toString(),
'https://user2:pass2@foo.bar.org:23/aaa/bbb?k=99#abcd');
assert.strictEqual((delete url.hash), true);
assert.strictEqual(url.hash, '#abcd');
// searchParams is readonly. Under strict mode setting a
// non-writable property should throw.
// Note: this error message is subject to change in V8 updates
assert.throws(
() => url.searchParams = '?k=88',
/^TypeError: Cannot set property searchParams of \[object URL\] which has only a getter$/
);
assert.strictEqual(url.searchParams, oldParams);
assert.strictEqual(url.toString(),
'https://user2:pass2@foo.bar.org:23/aaa/bbb?k=99#abcd');
assert.strictEqual((delete url.searchParams), true);
assert.strictEqual(url.searchParams, oldParams);
// Test urlToOptions
{
const urlObj = new URL('http://user:pass@foo.bar.com:21/aaa/zzz?l=24#test');
const opts = urlToOptions(urlObj);
assert.strictEqual(opts instanceof URL, false);
assert.strictEqual(opts.protocol, 'http:');
assert.strictEqual(opts.auth, 'user:pass');
assert.strictEqual(opts.hostname, 'foo.bar.com');
assert.strictEqual(opts.port, 21);
assert.strictEqual(opts.path, '/aaa/zzz?l=24');
assert.strictEqual(opts.pathname, '/aaa/zzz');
assert.strictEqual(opts.search, '?l=24');
assert.strictEqual(opts.hash, '#test');
const { hostname } = urlToOptions(new URL('http://[::1]:21'));
assert.strictEqual(hostname, '::1');
// If a WHATWG URL object is copied, it is possible that the resulting copy
// contains the Symbols that Node uses for brand checking, but not the data
// properties, which are getters. Verify that urlToOptions() can handle such
// a case.
const copiedUrlObj = { ...urlObj };
const copiedOpts = urlToOptions(copiedUrlObj);
assert.strictEqual(copiedOpts instanceof URL, false);
assert.strictEqual(copiedOpts.protocol, undefined);
assert.strictEqual(copiedOpts.auth, undefined);
assert.strictEqual(copiedOpts.hostname, undefined);
assert.strictEqual(copiedOpts.port, NaN);
assert.strictEqual(copiedOpts.path, '');
assert.strictEqual(copiedOpts.pathname, undefined);
assert.strictEqual(copiedOpts.search, undefined);
assert.strictEqual(copiedOpts.hash, undefined);
assert.strictEqual(copiedOpts.href, undefined);
}
// Test special origins
[
{ expected: 'https://whatwg.org',
url: 'blob:https://whatwg.org/d0360e2f-caee-469f-9a2f-87d5b0456f6f' },
{ expected: 'ftp://example.org', url: 'ftp://example.org/foo' },
{ expected: 'gopher://gopher.quux.org', url: 'gopher://gopher.quux.org/1/' },
{ expected: 'http://example.org', url: 'http://example.org/foo' },
{ expected: 'https://example.org', url: 'https://example.org/foo' },
{ expected: 'ws://example.org', url: 'ws://example.org/foo' },
{ expected: 'wss://example.org', url: 'wss://example.org/foo' },
{ expected: 'null', url: 'file:///tmp/mock/path' },
{ expected: 'null', url: 'npm://nodejs/rules' }
].forEach((test) => {
assert.strictEqual(new URL(test.url).origin, test.expected);
});
| mit |
disik69/codeigniter-migration | application/config/config.php | 17476 | <?php
defined('BASEPATH') OR exit('No direct script access allowed');
/*
|--------------------------------------------------------------------------
| Base Site URL
|--------------------------------------------------------------------------
|
| URL to your CodeIgniter root. Typically this will be your base URL,
| WITH a trailing slash:
|
| http://example.com/
|
| If this is not set then CodeIgniter will try guess the protocol, domain
| and path to your installation. However, you should always configure this
| explicitly and never rely on auto-guessing, especially in production
| environments.
|
*/
$config['base_url'] = '';
/*
|--------------------------------------------------------------------------
| Index File
|--------------------------------------------------------------------------
|
| Typically this will be your index.php file, unless you've renamed it to
| something else. If you are using mod_rewrite to remove the page set this
| variable so that it is blank.
|
*/
$config['index_page'] = '';
/*
|--------------------------------------------------------------------------
| URI PROTOCOL
|--------------------------------------------------------------------------
|
| This item determines which server global should be used to retrieve the
| URI string. The default setting of 'REQUEST_URI' works for most servers.
| If your links do not seem to work, try one of the other delicious flavors:
|
| 'REQUEST_URI' Uses $_SERVER['REQUEST_URI']
| 'QUERY_STRING' Uses $_SERVER['QUERY_STRING']
| 'PATH_INFO' Uses $_SERVER['PATH_INFO']
|
| WARNING: If you set this to 'PATH_INFO', URIs will always be URL-decoded!
*/
$config['uri_protocol'] = 'REQUEST_URI';
/*
|--------------------------------------------------------------------------
| URL suffix
|--------------------------------------------------------------------------
|
| This option allows you to add a suffix to all URLs generated by CodeIgniter.
| For more information please see the user guide:
|
| http://codeigniter.com/user_guide/general/urls.html
*/
$config['url_suffix'] = '';
/*
|--------------------------------------------------------------------------
| Default Language
|--------------------------------------------------------------------------
|
| This determines which set of language files should be used. Make sure
| there is an available translation if you intend to use something other
| than english.
|
*/
$config['language'] = 'english';
/*
|--------------------------------------------------------------------------
| Default Character Set
|--------------------------------------------------------------------------
|
| This determines which character set is used by default in various methods
| that require a character set to be provided.
|
| See http://php.net/htmlspecialchars for a list of supported charsets.
|
*/
$config['charset'] = 'UTF-8';
/*
|--------------------------------------------------------------------------
| Enable/Disable System Hooks
|--------------------------------------------------------------------------
|
| If you would like to use the 'hooks' feature you must enable it by
| setting this variable to TRUE (boolean). See the user guide for details.
|
*/
$config['enable_hooks'] = FALSE;
/*
|--------------------------------------------------------------------------
| Class Extension Prefix
|--------------------------------------------------------------------------
|
| This item allows you to set the filename/classname prefix when extending
| native libraries. For more information please see the user guide:
|
| http://codeigniter.com/user_guide/general/core_classes.html
| http://codeigniter.com/user_guide/general/creating_libraries.html
|
*/
$config['subclass_prefix'] = 'MY_';
/*
|--------------------------------------------------------------------------
| Composer auto-loading
|--------------------------------------------------------------------------
|
| Enabling this setting will tell CodeIgniter to look for a Composer
| package auto-loader script in application/vendor/autoload.php.
|
| $config['composer_autoload'] = TRUE;
|
| Or if you have your vendor/ directory located somewhere else, you
| can opt to set a specific path as well:
|
| $config['composer_autoload'] = '/path/to/vendor/autoload.php';
|
| For more information about Composer, please visit http://getcomposer.org/
|
| Note: This will NOT disable or override the CodeIgniter-specific
| autoloading (application/config/autoload.php)
*/
$config['composer_autoload'] = FALSE;
/*
|--------------------------------------------------------------------------
| Allowed URL Characters
|--------------------------------------------------------------------------
|
| This lets you specify which characters are permitted within your URLs.
| When someone tries to submit a URL with disallowed characters they will
| get a warning message.
|
| As a security measure you are STRONGLY encouraged to restrict URLs to
| as few characters as possible. By default only these are allowed: a-z 0-9~%.:_-
|
| Leave blank to allow all characters -- but only if you are insane.
|
| The configured value is actually a regular expression character group
| and it will be executed as: ! preg_match('/^[<permitted_uri_chars>]+$/i
|
| DO NOT CHANGE THIS UNLESS YOU FULLY UNDERSTAND THE REPERCUSSIONS!!
|
*/
$config['permitted_uri_chars'] = 'a-z 0-9~%.:_\-';
/*
|--------------------------------------------------------------------------
| Enable Query Strings
|--------------------------------------------------------------------------
|
| By default CodeIgniter uses search-engine friendly segment based URLs:
| example.com/who/what/where/
|
| By default CodeIgniter enables access to the $_GET array. If for some
| reason you would like to disable it, set 'allow_get_array' to FALSE.
|
| You can optionally enable standard query string based URLs:
| example.com?who=me&what=something&where=here
|
| Options are: TRUE or FALSE (boolean)
|
| The other items let you set the query string 'words' that will
| invoke your controllers and its functions:
| example.com/index.php?c=controller&m=function
|
| Please note that some of the helpers won't work as expected when
| this feature is enabled, since CodeIgniter is designed primarily to
| use segment based URLs.
|
*/
$config['allow_get_array'] = TRUE;
$config['enable_query_strings'] = FALSE;
$config['controller_trigger'] = 'c';
$config['function_trigger'] = 'm';
$config['directory_trigger'] = 'd';
/*
|--------------------------------------------------------------------------
| Error Logging Threshold
|--------------------------------------------------------------------------
|
| If you have enabled error logging, you can set an error threshold to
| determine what gets logged. Threshold options are:
| You can enable error logging by setting a threshold over zero. The
| threshold determines what gets logged. Threshold options are:
|
| 0 = Disables logging, Error logging TURNED OFF
| 1 = Error Messages (including PHP errors)
| 2 = Debug Messages
| 3 = Informational Messages
| 4 = All Messages
|
| You can also pass an array with threshold levels to show individual error types
|
| array(2) = Debug Messages, without Error Messages
|
| For a live site you'll usually only enable Errors (1) to be logged otherwise
| your log files will fill up very fast.
|
*/
$config['log_threshold'] = 1;
/*
|--------------------------------------------------------------------------
| Error Logging Directory Path
|--------------------------------------------------------------------------
|
| Leave this BLANK unless you would like to set something other than the default
| application/logs/ directory. Use a full server path with trailing slash.
|
*/
$config['log_path'] = '';
/*
|--------------------------------------------------------------------------
| Log File Extension
|--------------------------------------------------------------------------
|
| The default filename extension for log files. The default 'php' allows for
| protecting the log files via basic scripting, when they are to be stored
| under a publicly accessible directory.
|
| Note: Leaving it blank will default to 'php'.
|
*/
$config['log_file_extension'] = '';
/*
|--------------------------------------------------------------------------
| Log File Permissions
|--------------------------------------------------------------------------
|
| The file system permissions to be applied on newly created log files.
|
| IMPORTANT: This MUST be an integer (no quotes) and you MUST use octal
| integer notation (i.e. 0700, 0644, etc.)
*/
$config['log_file_permissions'] = 0644;
/*
|--------------------------------------------------------------------------
| Date Format for Logs
|--------------------------------------------------------------------------
|
| Each item that is logged has an associated date. You can use PHP date
| codes to set your own date formatting
|
*/
$config['log_date_format'] = 'Y-m-d H:i:s';
/*
|--------------------------------------------------------------------------
| Error Views Directory Path
|--------------------------------------------------------------------------
|
| Leave this BLANK unless you would like to set something other than the default
| application/views/errors/ directory. Use a full server path with trailing slash.
|
*/
$config['error_views_path'] = '';
/*
|--------------------------------------------------------------------------
| Cache Directory Path
|--------------------------------------------------------------------------
|
| Leave this BLANK unless you would like to set something other than the default
| application/cache/ directory. Use a full server path with trailing slash.
|
*/
$config['cache_path'] = '';
/*
|--------------------------------------------------------------------------
| Cache Include Query String
|--------------------------------------------------------------------------
|
| Set this to TRUE if you want to use different cache files depending on the
| URL query string. Please be aware this might result in numerous cache files.
|
*/
$config['cache_query_string'] = FALSE;
/*
|--------------------------------------------------------------------------
| Encryption Key
|--------------------------------------------------------------------------
|
| If you use the Encryption class, you must set an encryption key.
| See the user guide for more info.
|
| http://codeigniter.com/user_guide/libraries/encryption.html
|
*/
$config['encryption_key'] = '';
/*
|--------------------------------------------------------------------------
| Session Variables
|--------------------------------------------------------------------------
|
| 'sess_driver'
|
| The storage driver to use: files, database, redis, memcached
|
| 'sess_cookie_name'
|
| The session cookie name, must contain only [0-9a-z_-] characters
|
| 'sess_expiration'
|
| The number of SECONDS you want the session to last.
| Setting to 0 (zero) means expire when the browser is closed.
|
| 'sess_save_path'
|
| The location to save sessions to, driver dependant.
|
| For the 'files' driver, it's a path to a writable directory.
| WARNING: Only absolute paths are supported!
|
| For the 'database' driver, it's a table name.
| Please read up the manual for the format with other session drivers.
|
| IMPORTANT: You are REQUIRED to set a valid save path!
|
| 'sess_match_ip'
|
| Whether to match the user's IP address when reading the session data.
|
| 'sess_time_to_update'
|
| How many seconds between CI regenerating the session ID.
|
| 'sess_regenerate_destroy'
|
| Whether to destroy session data associated with the old session ID
| when auto-regenerating the session ID. When set to FALSE, the data
| will be later deleted by the garbage collector.
|
| Other session cookie settings are shared with the rest of the application,
| except for 'cookie_prefix' and 'cookie_httponly', which are ignored here.
|
*/
$config['sess_driver'] = 'files';
$config['sess_cookie_name'] = 'ci_session';
$config['sess_expiration'] = 7200;
$config['sess_save_path'] = NULL;
$config['sess_match_ip'] = FALSE;
$config['sess_time_to_update'] = 300;
$config['sess_regenerate_destroy'] = FALSE;
/*
|--------------------------------------------------------------------------
| Cookie Related Variables
|--------------------------------------------------------------------------
|
| 'cookie_prefix' = Set a cookie name prefix if you need to avoid collisions
| 'cookie_domain' = Set to .your-domain.com for site-wide cookies
| 'cookie_path' = Typically will be a forward slash
| 'cookie_secure' = Cookie will only be set if a secure HTTPS connection exists.
| 'cookie_httponly' = Cookie will only be accessible via HTTP(S) (no javascript)
|
| Note: These settings (with the exception of 'cookie_prefix' and
| 'cookie_httponly') will also affect sessions.
|
*/
$config['cookie_prefix'] = '';
$config['cookie_domain'] = '';
$config['cookie_path'] = '/';
$config['cookie_secure'] = FALSE;
$config['cookie_httponly'] = FALSE;
/*
|--------------------------------------------------------------------------
| Standardize newlines
|--------------------------------------------------------------------------
|
| Determines whether to standardize newline characters in input data,
| meaning to replace \r\n, \r, \n occurences with the PHP_EOL value.
|
| This is particularly useful for portability between UNIX-based OSes,
| (usually \n) and Windows (\r\n).
|
*/
$config['standardize_newlines'] = FALSE;
/*
|--------------------------------------------------------------------------
| Global XSS Filtering
|--------------------------------------------------------------------------
|
| Determines whether the XSS filter is always active when GET, POST or
| COOKIE data is encountered
|
| WARNING: This feature is DEPRECATED and currently available only
| for backwards compatibility purposes!
|
*/
$config['global_xss_filtering'] = FALSE;
/*
|--------------------------------------------------------------------------
| Cross Site Request Forgery
|--------------------------------------------------------------------------
| Enables a CSRF cookie token to be set. When set to TRUE, token will be
| checked on a submitted form. If you are accepting user data, it is strongly
| recommended CSRF protection be enabled.
|
| 'csrf_token_name' = The token name
| 'csrf_cookie_name' = The cookie name
| 'csrf_expire' = The number in seconds the token should expire.
| 'csrf_regenerate' = Regenerate token on every submission
| 'csrf_exclude_uris' = Array of URIs which ignore CSRF checks
*/
$config['csrf_protection'] = FALSE;
$config['csrf_token_name'] = 'csrf_test_name';
$config['csrf_cookie_name'] = 'csrf_cookie_name';
$config['csrf_expire'] = 7200;
$config['csrf_regenerate'] = TRUE;
$config['csrf_exclude_uris'] = array();
/*
|--------------------------------------------------------------------------
| Output Compression
|--------------------------------------------------------------------------
|
| Enables Gzip output compression for faster page loads. When enabled,
| the output class will test whether your server supports Gzip.
| Even if it does, however, not all browsers support compression
| so enable only if you are reasonably sure your visitors can handle it.
|
| Only used if zlib.output_compression is turned off in your php.ini.
| Please do not use it together with httpd-level output compression.
|
| VERY IMPORTANT: If you are getting a blank page when compression is enabled it
| means you are prematurely outputting something to your browser. It could
| even be a line of whitespace at the end of one of your scripts. For
| compression to work, nothing can be sent before the output buffer is called
| by the output class. Do not 'echo' any values with compression enabled.
|
*/
$config['compress_output'] = FALSE;
/*
|--------------------------------------------------------------------------
| Master Time Reference
|--------------------------------------------------------------------------
|
| Options are 'local' or any PHP supported timezone. This preference tells
| the system whether to use your server's local time as the master 'now'
| reference, or convert it to the configured one timezone. See the 'date
| helper' page of the user guide for information regarding date handling.
|
*/
$config['time_reference'] = 'local';
/*
|--------------------------------------------------------------------------
| Rewrite PHP Short Tags
|--------------------------------------------------------------------------
|
| If your PHP installation does not have short tag support enabled CI
| can rewrite the tags on-the-fly, enabling you to utilize that syntax
| in your view files. Options are TRUE or FALSE (boolean)
|
*/
$config['rewrite_short_tags'] = FALSE;
/*
|--------------------------------------------------------------------------
| Reverse Proxy IPs
|--------------------------------------------------------------------------
|
| If your server is behind a reverse proxy, you must whitelist the proxy
| IP addresses from which CodeIgniter should trust headers such as
| HTTP_X_FORWARDED_FOR and HTTP_CLIENT_IP in order to properly identify
| the visitor's IP address.
|
| You can use both an array or a comma-separated list of proxy addresses,
| as well as specifying whole subnets. Here are a few examples:
|
| Comma-separated: '10.0.1.200,192.168.5.0/24'
| Array: array('10.0.1.200', '192.168.5.0/24')
*/
$config['proxy_ips'] = '';
| mit |
Cmcwebb/imagemat | markup/locale/lang.cy.js | 9567 | [
{"id": "align_relative_to", "title": "Alinio perthynas i ..."},
{"id": "bkgnd_color", "title": "Newid lliw cefndir / Didreiddiad"},
{"id": "circle_cx", "title": "CX Newid cylch yn cydlynu"},
{"id": "circle_cy", "title": "Newid cylch's cy gydgysylltu"},
{"id": "circle_r", "title": "Newid radiws cylch yn"},
{"id": "connector_no_arrow", "textContent": "No arrow"},
{"id": "copyrightLabel", "textContent": "Powered by"},
{"id": "cornerRadiusLabel", "title": "Newid Hirsgwâr Corner Radiws"},
{"id": "curve_segments", "textContent": "Curve"},
{"id": "ellipse_cx", "title": "Newid Ellipse yn CX gydgysylltu"},
{"id": "ellipse_cy", "title": "Newid Ellipse yn cydlynu cy"},
{"id": "ellipse_rx", "title": "Radiws Newid Ellipse's x"},
{"id": "ellipse_ry", "title": "Radiws Newid Ellipse yn y"},
{"id": "fill_color", "title": "Newid lliw llenwi"},
{"id": "fitToContent", "textContent": "Ffit i Cynnwys"},
{"id": "fit_to_all", "textContent": "Yn addas i bawb content"},
{"id": "fit_to_canvas", "textContent": "Ffit i ofyn"},
{"id": "fit_to_layer_content", "textContent": "Ffit cynnwys haen i"},
{"id": "fit_to_sel", "textContent": "Yn addas at ddewis"},
{"id": "font_family", "title": "Newid Font Teulu"},
{"id": "icon_large", "textContent": "Large"},
{"id": "icon_medium", "textContent": "Medium"},
{"id": "icon_small", "textContent": "Small"},
{"id": "icon_xlarge", "textContent": "Extra Large"},
{"id": "image_height", "title": "Uchder delwedd Newid"},
{"id": "image_opt_embed", "textContent": "Embed data (local files)"},
{"id": "image_opt_ref", "textContent": "Use file reference"},
{"id": "image_url", "title": "Newid URL"},
{"id": "image_width", "title": "Lled delwedd Newid"},
{"id": "includedImages", "textContent": "Included Images"},
{"id": "largest_object", "textContent": "gwrthrych mwyaf"},
{"id": "layer_delete", "title": "Dileu Haen"},
{"id": "layer_down", "title": "Symud Haen i Lawr"},
{"id": "layer_new", "title": "Haen Newydd"},
{"id": "layer_rename", "title": "Ail-enwi Haen"},
{"id": "layer_up", "title": "Symud Haen Up"},
{"id": "layersLable", "textContent": "Haen:"},
{"id": "line_x1", "title": "Newid llinell yn cychwyn x gydgysylltu"},
{"id": "line_x2", "title": "Newid llinell yn diweddu x gydgysylltu"},
{"id": "line_y1", "title": "Newid llinell ar y cychwyn yn cydlynu"},
{"id": "line_y2", "title": "Newid llinell yn dod i ben y gydgysylltu"},
{"id": "linecap_butt", "title": "Linecap: Butt"},
{"id": "linecap_round", "title": "Linecap: Round"},
{"id": "linecap_square", "title": "Linecap: Square"},
{"id": "linejoin_bevel", "title": "Linejoin: Bevel"},
{"id": "linejoin_miter", "title": "Linejoin: Miter"},
{"id": "linejoin_round", "title": "Linejoin: Round"},
{"id": "main_icon", "title": "Main Menu"},
{"id": "mode_connect", "title": "Connect two objects"},
{"id": "page", "textContent": "tudalen"},
{"id": "palette", "title": "Cliciwch yma i lenwi newid lliw, sifft-cliciwch i newid lliw strôc"},
{"id": "path_node_x", "title": "Change node's x coordinate"},
{"id": "path_node_y", "title": "Change node's y coordinate"},
{"id": "rect_height_tool", "title": "Uchder petryal Newid"},
{"id": "rect_width_tool", "title": "Lled petryal Newid"},
{"id": "relativeToLabel", "textContent": "cymharol i:"},
{"id": "seg_type", "title": "Change Segment type"},
{"id": "selLayerLabel", "textContent": "Move elements to:"},
{"id": "selLayerNames", "title": "Move selected elements to a different layer"},
{"id": "selectedPredefined", "textContent": "Rhagosodol Dewis:"},
{"id": "selected_objects", "textContent": "gwrthrychau etholedig"},
{"id": "selected_x", "title": "Change X coordinate"},
{"id": "selected_y", "title": "Change Y coordinate"},
{"id": "smallest_object", "textContent": "lleiaf gwrthrych"},
{"id": "straight_segments", "textContent": "Straight"},
{"id": "stroke_color", "title": "Newid lliw strôc"},
{"id": "stroke_style", "title": "Newid arddull strôc diferyn"},
{"id": "stroke_width", "title": "Lled strôc Newid"},
{"id": "svginfo_bg_note", "textContent": "Note: Background will not be saved with image."},
{"id": "svginfo_change_background", "textContent": "Editor Background"},
{"id": "svginfo_dim", "textContent": "Canvas Dimensions"},
{"id": "svginfo_editor_prefs", "textContent": "Editor Preferences"},
{"id": "svginfo_height", "textContent": "Uchder:"},
{"id": "svginfo_icons", "textContent": "Icon size"},
{"id": "svginfo_image_props", "textContent": "Image Properties"},
{"id": "svginfo_lang", "textContent": "Language"},
{"id": "svginfo_title", "textContent": "Title"},
{"id": "svginfo_width", "textContent": "Lled:"},
{"id": "text", "title": "Cynnwys testun Newid"},
{"id": "toggle_stroke_tools", "title": "Show/hide more stroke tools"},
{"id": "tool_add_subpath", "title": "Add sub-path"},
{"id": "tool_alignbottom", "title": "Alinio Gwaelod"},
{"id": "tool_aligncenter", "title": "Alinio Center"},
{"id": "tool_alignleft", "title": "Alinio Chwith"},
{"id": "tool_alignmiddle", "title": "Alinio Canol"},
{"id": "tool_alignright", "title": "Alinio Hawl"},
{"id": "tool_aligntop", "title": "Alinio Top"},
{"id": "tool_angle", "title": "Ongl cylchdro Newid"},
{"id": "tool_blur", "title": "Change gaussian blur value"},
{"id": "tool_bold", "title": "Testun Bras"},
{"id": "tool_circle", "title": "Cylch"},
{"id": "tool_clear", "textContent": "Newydd Delwedd"},
{"id": "tool_clone", "title": "Clone Elfen"},
{"id": "tool_clone_multi", "title": "Elfennau Clone "},
{"id": "tool_delete", "title": "Dileu Elfen"},
{"id": "tool_delete_multi", "title": "Elfennau Selected Dileu"},
{"id": "tool_docprops", "textContent": "Document Eiddo"},
{"id": "tool_docprops_cancel", "textContent": "Canslo"},
{"id": "tool_docprops_save", "textContent": "Cadw"},
{"id": "tool_ellipse", "title": "Ellipse"},
{"id": "tool_export", "textContent": "Export as PNG"},
{"id": "tool_eyedropper", "title": "Eye Dropper Tool"},
{"id": "tool_fhellipse", "title": "Rhad ac am ddim Hand Ellipse"},
{"id": "tool_fhpath", "title": "Teclyn pensil"},
{"id": "tool_fhrect", "title": "Hand rhad ac am ddim Hirsgwâr"},
{"id": "tool_font_size", "title": "Newid Maint Ffont"},
{"id": "tool_group", "title": "Elfennau Grŵp"},
{"id": "tool_image", "title": "Offer Delwedd"},
{"id": "tool_import", "textContent": "Import SVG"},
{"id": "tool_italic", "title": "Italig Testun"},
{"id": "tool_line", "title": "Llinell Offer"},
{"id": "tool_move_bottom", "title": "Symud i'r Gwaelod"},
{"id": "tool_move_top", "title": "Symud i'r Top"},
{"id": "tool_node_clone", "title": "Clone Node"},
{"id": "tool_node_delete", "title": "Delete Node"},
{"id": "tool_node_link", "title": "Link Control Points"},
{"id": "tool_opacity", "title": "Newid dewis Didreiddiad eitem"},
{"id": "tool_open", "textContent": "Delwedd Agored"},
{"id": "tool_path", "title": "Offer poly"},
{"id": "tool_rect", "title": "Petryal"},
{"id": "tool_redo", "title": "Ail-wneud"},
{"id": "tool_reorient", "title": "Reorient path"},
{"id": "tool_save", "textContent": "Cadw Delwedd"},
{"id": "tool_select", "title": "Dewiswch Offer"},
{"id": "tool_source", "title": "Golygu Ffynhonnell"},
{"id": "tool_source_cancel", "textContent": "Canslo"},
{"id": "tool_source_save", "textContent": "Cadw"},
{"id": "tool_square", "title": "Sgwâr"},
{"id": "tool_text", "title": "Testun Offer"},
{"id": "tool_topath", "title": "Convert to Path"},
{"id": "tool_undo", "title": "Dadwneud"},
{"id": "tool_ungroup", "title": "Elfennau Ungroup"},
{"id": "tool_wireframe", "title": "Wireframe Mode"},
{"id": "tool_zoom", "title": "Offer Chwyddo"},
{"id": "url_notice", "title": "NOTE: This image cannot be embedded. It will depend on this path to be displayed"},
{"id": "zoom_panel", "title": "Newid lefel chwyddo"},
{"id": "sidepanel_handle", "textContent": "L a y e r s", "title": "Drag left/right to resize side panel"},
{
"js_strings": {
"QerrorsRevertToSource": "There were parsing errors in your SVG source.\nRevert back to original SVG source?",
"QignoreSourceChanges": "Ignore changes made to SVG source?",
"QmoveElemsToLayer": "Move selected elements to layer '%s'?",
"QwantToClear": "Do you want to clear the drawing?\nThis will also erase your undo history!",
"cancel": "Cancel",
"defsFailOnSave": "NOTE: Due to a bug in your browser, this image may appear wrong (missing gradients or elements). It will however appear correct once actually saved.",
"dupeLayerName": "There is already a layer named that!",
"enterNewImgURL": "Enter the new image URL",
"enterNewLayerName": "Please enter the new layer name",
"enterUniqueLayerName": "Please enter a unique layer name",
"exportNoBlur": "Blurred elements will appear as un-blurred",
"exportNoDashArray": "Strokes will appear filled",
"exportNoImage": "Image elements will not appear",
"exportNoText": "Text may not appear as expected",
"exportNoforeignObject": "foreignObject elements will not appear",
"featNotSupported": "Feature not supported",
"invalidAttrValGiven": "Invalid value given",
"key_backspace": "backspace",
"key_del": "delete",
"key_down": "down",
"key_up": "up",
"layer": "Layer",
"layerHasThatName": "Layer already has that name",
"loadingImage": "Loading image, please wait...",
"noContentToFitTo": "No content to fit to",
"noteTheseIssues": "Also note the following issues: ",
"ok": "OK",
"pathCtrlPtTooltip": "Drag control point to adjust curve properties",
"pathNodeTooltip": "Drag node to move it. Double-click node to change segment type",
"saveFromBrowser": "Select \"Save As...\" in your browser to save this image as a %s file."
}
}
] | mit |
lf2941270/Ghost | core/test/integration/model/model_users_spec.js | 26933 | var testUtils = require('../../utils'),
should = require('should'),
Promise = require('bluebird'),
sinon = require('sinon'),
uuid = require('node-uuid'),
_ = require('lodash'),
// Stuff we are testing
utils = require('../../../server/utils'),
gravatar = require('../../../server/utils/gravatar'),
UserModel = require('../../../server/models/user').User,
RoleModel = require('../../../server/models/role').Role,
events = require('../../../server/events'),
context = testUtils.context.admin,
sandbox = sinon.sandbox.create();
describe('User Model', function run() {
var eventSpy;
// Keep the DB clean
before(testUtils.teardown);
afterEach(testUtils.teardown);
afterEach(function () {
sandbox.restore();
});
before(function () {
should.exist(UserModel);
});
beforeEach(function () {
eventSpy = sandbox.spy(events, 'emit');
});
describe('Registration', function runRegistration() {
beforeEach(testUtils.setup('roles'));
it('can add first', function (done) {
var userData = testUtils.DataGenerator.forModel.users[0];
UserModel.add(userData, context).then(function (createdUser) {
should.exist(createdUser);
createdUser.has('uuid').should.equal(true);
createdUser.attributes.password.should.not.equal(userData.password, 'password was hashed');
createdUser.attributes.email.should.eql(userData.email, 'email address correct');
done();
}).catch(done);
});
it('shortens slug if possible', function (done) {
var userData = testUtils.DataGenerator.forModel.users[2];
UserModel.add(userData, context).then(function (createdUser) {
should.exist(createdUser);
createdUser.has('slug').should.equal(true);
createdUser.attributes.slug.should.equal('jimothy');
done();
}).catch(done);
});
it('does not short slug if not possible', function (done) {
var userData = testUtils.DataGenerator.forModel.users[2];
UserModel.add(userData, context).then(function (createdUser) {
should.exist(createdUser);
createdUser.has('slug').should.equal(true);
createdUser.attributes.slug.should.equal('jimothy');
}).then(function () {
userData.email = 'newmail@mail.com';
UserModel.add(userData, context).then(function (createdUser) {
should.exist(createdUser);
createdUser.has('slug').should.equal(true);
createdUser.attributes.slug.should.equal('jimothy-bogendath');
}).then(function () {
userData.email = 'newmail2@mail.com';
UserModel.add(userData, context).then(function (createdUser) {
should.exist(createdUser);
createdUser.has('slug').should.equal(true);
createdUser.attributes.slug.should.equal('jimothy-bogendath-2');
done();
});
});
}).catch(done);
});
it('does NOT lowercase email', function (done) {
var userData = testUtils.DataGenerator.forModel.users[2];
UserModel.add(userData, context).then(function (createdUser) {
should.exist(createdUser);
createdUser.has('uuid').should.equal(true);
createdUser.attributes.email.should.eql(userData.email, 'email address correct');
done();
}).catch(done);
});
it('can find gravatar', function (done) {
var userData = testUtils.DataGenerator.forModel.users[4];
sandbox.stub(gravatar, 'lookup', function (userData) {
userData.image = 'http://www.gravatar.com/avatar/2fab21a4c4ed88e76add10650c73bae1?d=404';
return Promise.resolve(userData);
});
UserModel.add(userData, context).then(function (createdUser) {
should.exist(createdUser);
createdUser.has('uuid').should.equal(true);
createdUser.attributes.image.should.eql(
'http://www.gravatar.com/avatar/2fab21a4c4ed88e76add10650c73bae1?d=404', 'Gravatar found'
);
done();
}).catch(done);
});
it('can handle no gravatar', function (done) {
var userData = testUtils.DataGenerator.forModel.users[0];
sandbox.stub(gravatar, 'lookup', function (userData) {
return Promise.resolve(userData);
});
UserModel.add(userData, context).then(function (createdUser) {
should.exist(createdUser);
createdUser.has('uuid').should.equal(true);
should.not.exist(createdUser.image);
done();
}).catch(done);
});
it('can set password of only numbers', function () {
var userData = testUtils.DataGenerator.forModel.users[0];
// avoid side-effects!
userData = _.cloneDeep(userData);
userData.password = 12345678;
// mocha supports promises
return UserModel.add(userData, context).then(function (createdUser) {
should.exist(createdUser);
// cannot validate password
});
});
it('can find by email and is case insensitive', function (done) {
var userData = testUtils.DataGenerator.forModel.users[2],
email = testUtils.DataGenerator.forModel.users[2].email;
UserModel.add(userData, context).then(function () {
// Test same case
return UserModel.getByEmail(email).then(function (user) {
should.exist(user);
user.attributes.email.should.eql(email);
});
}).then(function () {
// Test entered in lowercase
return UserModel.getByEmail(email.toLowerCase()).then(function (user) {
should.exist(user);
user.attributes.email.should.eql(email);
});
}).then(function () {
// Test entered in uppercase
return UserModel.getByEmail(email.toUpperCase()).then(function (user) {
should.exist(user);
user.attributes.email.should.eql(email);
});
}).then(function () {
// Test incorrect email address - swapped capital O for number 0
return UserModel.getByEmail('jb0gendAth@example.com').then(null, function (error) {
should.exist(error);
error.message.should.eql('NotFound');
});
}).then(function () {
done();
}).catch(done);
});
});
describe('Basic Operations', function () {
beforeEach(testUtils.setup('users:roles'));
it('sets last login time on successful login', function (done) {
var userData = testUtils.DataGenerator.forModel.users[0];
UserModel.check({email: userData.email, password: userData.password}).then(function (activeUser) {
should.exist(activeUser.get('last_login'));
done();
}).catch(done);
});
it('converts fetched dateTime fields to Date objects', function (done) {
var userData = testUtils.DataGenerator.forModel.users[0];
UserModel.check({email: userData.email, password: userData.password}).then(function (user) {
return UserModel.findOne({id: user.id});
}).then(function (user) {
var lastLogin,
createdAt,
updatedAt;
should.exist(user);
lastLogin = user.get('last_login');
createdAt = user.get('created_at');
updatedAt = user.get('updated_at');
lastLogin.should.be.an.instanceof(Date);
createdAt.should.be.an.instanceof(Date);
updatedAt.should.be.an.instanceof(Date);
done();
}).catch(done);
});
it('can findAll', function (done) {
UserModel.findAll().then(function (results) {
should.exist(results);
results.length.should.equal(4);
done();
}).catch(done);
});
it('can findPage (default)', function (done) {
UserModel.findPage().then(function (results) {
should.exist(results);
results.meta.pagination.page.should.equal(1);
results.meta.pagination.limit.should.equal(15);
results.meta.pagination.pages.should.equal(1);
results.users.length.should.equal(4);
done();
}).catch(done);
});
/**
* Removed in favour of filters, but this relation hasn't been re-added yet
*/
it.skip('can findPage by role', function (done) {
return testUtils.fixtures.createExtraUsers().then(function () {
return UserModel.findPage({role: 'Administrator'});
}).then(function (results) {
results.meta.pagination.page.should.equal(1);
results.meta.pagination.limit.should.equal(15);
results.meta.pagination.pages.should.equal(1);
results.meta.pagination.total.should.equal(2);
results.users.length.should.equal(2);
return UserModel.findPage({role: 'Owner'});
}).then(function (results) {
results.meta.pagination.page.should.equal(1);
results.meta.pagination.limit.should.equal(15);
results.meta.pagination.pages.should.equal(1);
results.meta.pagination.total.should.equal(1);
results.users.length.should.equal(1);
return UserModel.findPage({role: 'Editor', limit: 1});
}).then(function (results) {
results.meta.pagination.page.should.equal(1);
results.meta.pagination.limit.should.equal(1);
results.meta.pagination.pages.should.equal(2);
results.meta.pagination.total.should.equal(2);
results.users.length.should.equal(1);
done();
}).catch(done);
});
it('can findPage with limit all', function () {
return testUtils.fixtures.createExtraUsers().then(function () {
return UserModel.findPage({limit: 'all'});
}).then(function (results) {
results.meta.pagination.page.should.equal(1);
results.meta.pagination.limit.should.equal('all');
results.meta.pagination.pages.should.equal(1);
results.users.length.should.equal(7);
});
});
it('can NOT findPage for a page that overflows the datatype', function (done) {
UserModel.findPage({page: 5700000000055345439587894375457849375284932759842375894372589243758947325894375894275894275894725897432859724309})
.then(function (paginationResult) {
should.exist(paginationResult.meta);
paginationResult.meta.pagination.page.should.be.a.Number();
done();
}).catch(done);
});
it('can findOne', function (done) {
var firstUser;
UserModel.findAll().then(function (results) {
should.exist(results);
results.length.should.be.above(0);
firstUser = results.models[0];
return UserModel.findOne({email: firstUser.attributes.email});
}).then(function (found) {
should.exist(found);
found.attributes.name.should.equal(firstUser.attributes.name);
done();
}).catch(done);
});
it('can findOne by role name', function () {
return testUtils.fixtures.createExtraUsers().then(function () {
return Promise.join(UserModel.findOne({role: 'Owner'}), UserModel.findOne({role: 'Editor'}));
}).then(function (results) {
var owner = results[0],
editor = results[1];
should.exist(owner);
should.exist(editor);
owner = owner.toJSON();
editor = editor.toJSON();
should.exist(owner.roles);
should.exist(editor.roles);
owner.roles[0].name.should.equal('Owner');
editor.roles[0].name.should.equal('Editor');
});
});
it('can invite user', function (done) {
var userData = testUtils.DataGenerator.forModel.users[4];
UserModel.add(_.extend({}, userData, {status: 'invited'}), context).then(function (createdUser) {
should.exist(createdUser);
createdUser.has('uuid').should.equal(true);
createdUser.attributes.password.should.not.equal(userData.password, 'password was hashed');
createdUser.attributes.email.should.eql(userData.email, 'email address correct');
eventSpy.calledOnce.should.be.true();
eventSpy.firstCall.calledWith('user.added').should.be.true();
done();
}).catch(done);
});
it('can add active user', function (done) {
var userData = testUtils.DataGenerator.forModel.users[4];
RoleModel.findOne().then(function (role) {
userData.roles = [role.toJSON()];
return UserModel.add(userData, _.extend({}, context, {include: ['roles']}));
}).then(function (createdUser) {
should.exist(createdUser);
createdUser.has('uuid').should.equal(true);
createdUser.get('password').should.not.equal(userData.password, 'password was hashed');
createdUser.get('email').should.eql(userData.email, 'email address correct');
createdUser.related('roles').toJSON()[0].name.should.eql('Administrator', 'role set correctly');
eventSpy.calledTwice.should.be.true();
eventSpy.firstCall.calledWith('user.added').should.be.true();
eventSpy.secondCall.calledWith('user.activated').should.be.true();
done();
}).catch(done);
});
it('can NOT add active user with invalid email address', function (done) {
var userData = _.clone(testUtils.DataGenerator.forModel.users[4]);
userData.email = 'invalidemailaddress';
RoleModel.findOne().then(function (role) {
userData.roles = [role.toJSON()];
return UserModel.add(userData, _.extend({}, context, {include: ['roles']}));
}).then(function () {
done(new Error('User was created with an invalid email address'));
}).catch(function () {
done();
});
});
it('can edit active user', function (done) {
var firstUser = 1;
UserModel.findOne({id: firstUser}).then(function (results) {
var user;
should.exist(results);
user = results.toJSON();
user.id.should.equal(firstUser);
should.equal(user.website, null);
return UserModel.edit({website: 'http://some.newurl.com'}, {id: firstUser});
}).then(function (edited) {
should.exist(edited);
edited.attributes.website.should.equal('http://some.newurl.com');
eventSpy.calledTwice.should.be.true();
eventSpy.firstCall.calledWith('user.activated.edited').should.be.true();
eventSpy.secondCall.calledWith('user.edited').should.be.true();
done();
}).catch(done);
});
it('can NOT set an invalid email address', function (done) {
var firstUser = 1;
UserModel.findOne({id: firstUser}).then(function (user) {
return user.edit({email: 'notanemailaddress'});
}).then(function () {
done(new Error('Invalid email address was accepted'));
}).catch(function () {
done();
});
});
it('can edit invited user', function (done) {
var userData = testUtils.DataGenerator.forModel.users[4],
userId;
UserModel.add(_.extend({}, userData, {status: 'invited'}), context).then(function (createdUser) {
should.exist(createdUser);
createdUser.has('uuid').should.equal(true);
createdUser.attributes.password.should.not.equal(userData.password, 'password was hashed');
createdUser.attributes.email.should.eql(userData.email, 'email address correct');
createdUser.attributes.status.should.equal('invited');
userId = createdUser.attributes.id;
eventSpy.calledOnce.should.be.true();
eventSpy.firstCall.calledWith('user.added').should.be.true();
return UserModel.edit({website: 'http://some.newurl.com'}, {id: userId});
}).then(function (createdUser) {
createdUser.attributes.status.should.equal('invited');
eventSpy.calledTwice.should.be.true();
eventSpy.secondCall.calledWith('user.edited').should.be.true();
done();
}).catch(done);
});
it('can activate invited user', function (done) {
var userData = testUtils.DataGenerator.forModel.users[4],
userId;
UserModel.add(_.extend({}, userData, {status: 'invited'}), context).then(function (createdUser) {
should.exist(createdUser);
createdUser.has('uuid').should.equal(true);
createdUser.attributes.password.should.not.equal(userData.password, 'password was hashed');
createdUser.attributes.email.should.eql(userData.email, 'email address correct');
createdUser.attributes.status.should.equal('invited');
userId = createdUser.attributes.id;
eventSpy.calledOnce.should.be.true();
eventSpy.firstCall.calledWith('user.added').should.be.true();
return UserModel.edit({status: 'active'}, {id: userId});
}).then(function (createdUser) {
createdUser.attributes.status.should.equal('active');
eventSpy.calledThrice.should.be.true();
eventSpy.secondCall.calledWith('user.activated').should.be.true();
eventSpy.thirdCall.calledWith('user.edited').should.be.true();
done();
}).catch(done);
});
it('can destroy active user', function (done) {
var firstUser = {id: 1};
// Test that we have the user we expect
UserModel.findOne(firstUser).then(function (results) {
var user;
should.exist(results);
user = results.toJSON();
user.id.should.equal(firstUser.id);
// Destroy the user
return UserModel.destroy(firstUser);
}).then(function (response) {
response.toJSON().should.be.empty();
eventSpy.calledTwice.should.be.true();
eventSpy.firstCall.calledWith('user.deactivated').should.be.true();
eventSpy.secondCall.calledWith('user.deleted').should.be.true();
// Double check we can't find the user again
return UserModel.findOne(firstUser);
}).then(function (newResults) {
should.equal(newResults, null);
done();
}).catch(done);
});
it('can destroy invited user', function (done) {
var userData = testUtils.DataGenerator.forModel.users[4],
userId;
UserModel.add(_.extend({}, userData, {status: 'invited'}), context).then(function (createdUser) {
should.exist(createdUser);
createdUser.has('uuid').should.equal(true);
createdUser.attributes.password.should.not.equal(userData.password, 'password was hashed');
createdUser.attributes.email.should.eql(userData.email, 'email address correct');
createdUser.attributes.status.should.equal('invited');
userId = {id: createdUser.attributes.id};
eventSpy.calledOnce.should.be.true();
eventSpy.firstCall.calledWith('user.added').should.be.true();
// Destroy the user
return UserModel.destroy(userId);
}).then(function (response) {
response.toJSON().should.be.empty();
eventSpy.calledTwice.should.be.true();
eventSpy.secondCall.calledWith('user.deleted').should.be.true();
// Double check we can't find the user again
return UserModel.findOne(userId);
}).then(function (newResults) {
should.equal(newResults, null);
done();
}).catch(done);
});
});
describe('Password Reset', function () {
beforeEach(testUtils.setup('users:roles'));
it('can generate reset token', function (done) {
// Expires in one minute
var expires = Date.now() + 60000,
dbHash = uuid.v4();
UserModel.findAll().then(function (results) {
return UserModel.generateResetToken(results.models[0].attributes.email, expires, dbHash);
}).then(function (token) {
should.exist(token);
token.length.should.be.above(0);
done();
}).catch(done);
});
it('can validate a reset token', function (done) {
// Expires in one minute
var expires = Date.now() + 60000,
dbHash = uuid.v4();
UserModel.findAll().then(function (results) {
return UserModel.generateResetToken(results.models[1].attributes.email, expires, dbHash);
}).then(function (token) {
return UserModel.validateToken(token, dbHash);
}).then(function () {
done();
}).catch(done);
});
it('can validate an URI encoded reset token', function (done) {
// Expires in one minute
var expires = Date.now() + 60000,
dbHash = uuid.v4();
UserModel.findAll().then(function (results) {
return UserModel.generateResetToken(results.models[1].attributes.email, expires, dbHash);
}).then(function (token) {
token = utils.encodeBase64URLsafe(token);
token = encodeURIComponent(token);
token = decodeURIComponent(token);
token = utils.decodeBase64URLsafe(token);
return UserModel.validateToken(token, dbHash);
}).then(function () {
done();
}).catch(done);
});
it('can reset a password with a valid token', function (done) {
// Expires in one minute
var origPassword,
expires = Date.now() + 60000,
dbHash = uuid.v4();
UserModel.findAll().then(function (results) {
var firstUser = results.models[0],
origPassword = firstUser.attributes.password;
should.exist(origPassword);
return UserModel.generateResetToken(firstUser.attributes.email, expires, dbHash);
}).then(function (token) {
token = utils.encodeBase64URLsafe(token);
return UserModel.resetPassword({token: token, newPassword: 'newpassword', ne2Password: 'newpassword', dbHash: dbHash});
}).then(function (resetUser) {
var resetPassword = resetUser.get('password');
should.exist(resetPassword);
resetPassword.should.not.equal(origPassword);
done();
}).catch(done);
});
it('doesn\'t allow expired timestamp tokens', function (done) {
var email,
// Expired one minute ago
expires = Date.now() - 60000,
dbHash = uuid.v4();
UserModel.findAll().then(function (results) {
// Store email for later
email = results.models[0].attributes.email;
return UserModel.generateResetToken(email, expires, dbHash);
}).then(function (token) {
return UserModel.validateToken(token, dbHash);
}).then(function () {
throw new Error('Allowed expired token');
}).catch(function (err) {
should.exist(err);
err.message.should.equal('Expired token');
done();
});
});
it('doesn\'t allow tampered timestamp tokens', function (done) {
// Expired one minute ago
var expires = Date.now() - 60000,
dbHash = uuid.v4();
UserModel.findAll().then(function (results) {
return UserModel.generateResetToken(results.models[0].attributes.email, expires, dbHash);
}).then(function (token) {
var tokenText = new Buffer(token, 'base64').toString('ascii'),
parts = tokenText.split('|'),
fakeExpires,
fakeToken;
fakeExpires = Date.now() + 60000;
fakeToken = [String(fakeExpires), parts[1], parts[2]].join('|');
fakeToken = new Buffer(fakeToken).toString('base64');
return UserModel.validateToken(fakeToken, dbHash);
}).then(function () {
throw new Error('allowed invalid token');
}).catch(function (err) {
should.exist(err);
err.message.should.equal('Invalid token');
done();
});
});
});
});
| mit |
jeffthemaximum/jeffline | templates/rubix/meteor/meteor-example/imports/plugins.js | 133 | module.exports = [
'/bower_components/PACE/pace.min.js',
'/js/jquery.js',
'/js/modernizr.js',
'/js/perfect-scrollbar.js',
];
| mit |
karthiick/ember.js | blueprints/controller-test/index.js | 556 | 'use strict';
const stringUtil = require('ember-cli-string-utils');
const useTestFrameworkDetector = require('../test-framework-detector');
module.exports = useTestFrameworkDetector({
description: 'Generates a controller unit test.',
locals: function(options) {
let dasherizedModuleName = stringUtil.dasherize(options.entity.name);
let controllerPathName = dasherizedModuleName;
return {
controllerPathName: controllerPathName,
friendlyTestDescription: ['Unit', 'Controller', dasherizedModuleName].join(' | ')
};
}
});
| mit |
inab/TeBactEn | web/javascripts/autocomplete.php | 988 | <?php
include("config.php");
$term = $_GET['term'];
$searchfor = $_GET['searchfor'];
switch ($searchfor) {
case "enzymes":
$searchfor="enzyme";
break;
case "compounds":
$searchfor="compound";
break;
case "species":
$searchfor="organism";
break;
}
$conn = mysql_connect ($database, $db_user, $db_password);
mysql_select_db("EtoxMicromeTebacten", $conn);
mysql_query("SET NAMES 'utf8'");
$selectSQL="select distinct(textmining_".$searchfor."_name) from ".$searchfor."s where textmining_".$searchfor."_name like '%$term%'";
#print $selectSQL;
$result= mysql_query($selectSQL);
$arr=array();
while ($row = mysql_fetch_row($result)){
#$idEnzyme=$row[0];
$textminingEnzymeName=$row[0];
$arrayTmp=array("label"=>$textminingEnzymeName,"value"=>$textminingEnzymeName);
$arr[]=$arrayTmp;
}
$jsonString = json_encode($arr);
print $jsonString;
exit();
#$jsonString=implode(",",$arr);
#jsonString="[$jsonString];";
#print $jsonString
?> | mit |
FabianLiebl/enhavo | src/Enhavo/Bundle/TaxonomyBundle/DependencyInjection/EnhavoTaxonomyExtension.php | 1829 | <?php
namespace Enhavo\Bundle\TaxonomyBundle\DependencyInjection;
use Sylius\Bundle\ResourceBundle\DependencyInjection\Extension\AbstractResourceExtension;
use Sylius\Component\Resource\Factory;
use Symfony\Component\Config\FileLocator;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Extension\PrependExtensionInterface;
use Symfony\Component\DependencyInjection\Loader\YamlFileLoader;
use Symfony\Component\Yaml\Yaml;
/**
* This is the class that loads and manages your bundle configuration
*
* To learn more see {@link http://symfony.com/doc/current/cookbook/bundles/extension.html}
*/
class EnhavoTaxonomyExtension extends AbstractResourceExtension implements PrependExtensionInterface
{
/**
* {@inheritdoc}
*/
public function load(array $config, ContainerBuilder $container)
{
$config = $this->processConfiguration(new Configuration(), $config);
$loader = new YamlFileLoader($container, new FileLocator(__DIR__.'/../Resources/config'));
$this->registerResources('enhavo_taxonomy', $config['driver'], $config['resources'], $container);
$container->setParameter('enhavo_taxonomy.taxonomies', isset($config['taxonomies']) ? $config['taxonomies'] : []);
$configFiles = array(
'services.yaml',
);
foreach ($configFiles as $configFile) {
$loader->load($configFile);
}
}
/**
* @inheritDoc
*/
public function prepend(ContainerBuilder $container)
{
$configs = Yaml::parse(file_get_contents(__DIR__.'/../Resources/config/app/config.yaml'));
foreach($configs as $name => $config) {
if (is_array($config)) {
$container->prependExtensionConfig($name, $config);
}
}
}
}
| mit |
harshich/automateallthings | Code/EndSolution/static/js/main.js | 135 | (function ( $ ) {
'use strict';
$(document).ready( function () {
sayThatThisIsAJavascriptApplication();
});
}(jQuery)); | mit |
jmks/rubocop | lib/rubocop/cop/layout/indentation_width.rb | 11135 | # frozen_string_literal: true
module RuboCop
module Cop
module Layout
# This cop checks for indentation that doesn't use the specified number
# of spaces.
#
# See also the IndentationConsistency cop which is the companion to this
# one.
#
# @example
# # bad
# class A
# def test
# puts 'hello'
# end
# end
#
# # good
# class A
# def test
# puts 'hello'
# end
# end
#
# @example IgnoredPatterns: ['^\s*module']
# # bad
# module A
# class B
# def test
# puts 'hello'
# end
# end
# end
#
# # good
# module A
# class B
# def test
# puts 'hello'
# end
# end
# end
class IndentationWidth < Cop # rubocop:disable Metrics/ClassLength
include EndKeywordAlignment
include Alignment
include CheckAssignment
include IgnoredPattern
include RangeHelp
MSG = 'Use %<configured_indentation_width>d (not %<indentation>d) ' \
'spaces for%<name>s indentation.'
def_node_matcher :access_modifier?, <<~PATTERN
[(send ...) access_modifier?]
PATTERN
def on_rescue(node)
_begin_node, *_rescue_nodes, else_node = *node
check_indentation(node.loc.else, else_node)
end
def on_ensure(node)
check_indentation(node.loc.keyword, node.body)
end
alias on_resbody on_ensure
alias on_for on_ensure
def on_kwbegin(node)
# Check indentation against end keyword but only if it's first on its
# line.
return unless begins_its_line?(node.loc.end)
check_indentation(node.loc.end, node.children.first)
end
def on_block(node)
end_loc = node.loc.end
return unless begins_its_line?(end_loc)
check_indentation(end_loc, node.body)
return unless indented_internal_methods_style?
check_members(end_loc, [node.body])
end
def on_class(node)
check_members(node.loc.keyword, [node.body])
end
alias on_sclass on_class
alias on_module on_class
def on_send(node)
super
return unless node.adjacent_def_modifier?
def_end_config = config.for_cop('Layout/DefEndAlignment')
style = def_end_config['EnforcedStyleAlignWith'] || 'start_of_line'
base = if style == 'def'
node.first_argument
else
leftmost_modifier_of(node) || node
end
check_indentation(base.source_range, node.first_argument.body)
ignore_node(node.first_argument)
end
alias on_csend on_send
def on_def(node)
return if ignored_node?(node)
check_indentation(node.loc.keyword, node.body)
end
alias on_defs on_def
def on_while(node, base = node)
return if ignored_node?(node)
return unless node.single_line_condition?
check_indentation(base.loc, node.body)
end
alias on_until on_while
def on_case(case_node)
case_node.each_when do |when_node|
check_indentation(when_node.loc.keyword, when_node.body)
end
check_indentation(case_node.when_branches.last.loc.keyword,
case_node.else_branch)
end
def on_if(node, base = node)
return if ignored_node?(node)
return if node.ternary? || node.modifier_form?
check_if(node, node.body, node.else_branch, base.loc)
end
def autocorrect(node)
AlignmentCorrector.correct(processed_source, node, @column_delta)
end
private
def check_members(base, members)
check_indentation(base, select_check_member(members.first))
return unless members.any? && members.first.begin_type?
if indentation_consistency_style == 'indented_internal_methods'
check_members_for_indented_internal_methods_style(members)
else
check_members_for_normal_style(base, members)
end
end
def select_check_member(member)
return unless member
if access_modifier?(member.children.first)
return if access_modifier_indentation_style == 'outdent'
member.children.first
else
member
end
end
def check_members_for_indented_internal_methods_style(members)
each_member(members) do |member, previous_modifier|
check_indentation(previous_modifier, member,
indentation_consistency_style)
end
end
def check_members_for_normal_style(base, members)
members.first.children.each do |member|
next if member.send_type? && member.access_modifier?
check_indentation(base, member)
end
end
def each_member(members)
previous_modifier = nil
members.first.children.each do |member|
if member.send_type? && member.special_modifier?
previous_modifier = member
elsif previous_modifier
yield member, previous_modifier.source_range
previous_modifier = nil
end
end
end
def indented_internal_methods_style?
indentation_consistency_style == 'indented_internal_methods'
end
def special_modifier?(node)
node.bare_access_modifier? && SPECIAL_MODIFIERS.include?(node.source)
end
def access_modifier_indentation_style
config.for_cop('Layout/AccessModifierIndentation')['EnforcedStyle']
end
def indentation_consistency_style
config.for_cop('Layout/IndentationConsistency')['EnforcedStyle']
end
def check_assignment(node, rhs)
# If there are method calls chained to the right hand side of the
# assignment, we let rhs be the receiver of those method calls before
# we check its indentation.
rhs = first_part_of_call_chain(rhs)
return unless rhs
end_config = config.for_cop('Layout/EndAlignment')
style = end_config['EnforcedStyleAlignWith'] || 'keyword'
base = variable_alignment?(node.loc, rhs, style.to_sym) ? node : rhs
case rhs.type
when :if then on_if(rhs, base)
when :while, :until then on_while(rhs, base)
else return
end
ignore_node(rhs)
end
def check_if(node, body, else_clause, base_loc)
return if node.ternary?
check_indentation(base_loc, body)
return unless else_clause
# If the else clause is an elsif, it will get its own on_if call so
# we don't need to process it here.
return if else_clause.if_type? && else_clause.elsif?
check_indentation(node.loc.else, else_clause)
end
def check_indentation(base_loc, body_node, style = 'normal')
return unless indentation_to_check?(base_loc, body_node)
indentation = column_offset_between(body_node.loc, base_loc)
@column_delta = configured_indentation_width - indentation
return if @column_delta.zero?
offense(body_node, indentation, style)
end
def offense(body_node, indentation, style)
# This cop only auto-corrects the first statement in a def body, for
# example.
body_node = body_node.children.first if body_node.begin_type? && !parentheses?(body_node)
# Since autocorrect changes a number of lines, and not only the line
# where the reported offending range is, we avoid auto-correction if
# this cop has already found other offenses is the same
# range. Otherwise, two corrections can interfere with each other,
# resulting in corrupted code.
node = if autocorrect? && other_offense_in_same_range?(body_node)
nil
else
body_node
end
name = style == 'normal' ? '' : " #{style}"
message = message(configured_indentation_width, indentation, name)
add_offense(node, location: offending_range(body_node, indentation),
message: message)
end
def message(configured_indentation_width, indentation, name)
format(
MSG,
configured_indentation_width: configured_indentation_width,
indentation: indentation,
name: name
)
end
# Returns true if the given node is within another node that has
# already been marked for auto-correction by this cop.
def other_offense_in_same_range?(node)
expr = node.source_range
@offense_ranges ||= []
return true if @offense_ranges.any? { |r| within?(expr, r) }
@offense_ranges << expr
false
end
def indentation_to_check?(base_loc, body_node)
return false if skip_check?(base_loc, body_node)
if %i[rescue ensure].include?(body_node.type)
block_body, = *body_node
return unless block_body
end
true
end
def skip_check?(base_loc, body_node)
return true if ignored_line?(base_loc)
return true unless body_node
# Don't check if expression is on same line as "then" keyword, etc.
return true if body_node.loc.line == base_loc.line
return true if starts_with_access_modifier?(body_node)
# Don't check indentation if the line doesn't start with the body.
# For example, lines like "else do_something".
first_char_pos_on_line = body_node.source_range.source_line =~ /\S/
return true unless body_node.loc.column == first_char_pos_on_line
end
def offending_range(body_node, indentation)
expr = body_node.source_range
begin_pos = expr.begin_pos
ind = expr.begin_pos - indentation
pos = indentation >= 0 ? ind..begin_pos : begin_pos..ind
range_between(pos.begin, pos.end)
end
def starts_with_access_modifier?(body_node)
return unless body_node.begin_type?
starting_node = body_node.children.first
return unless starting_node
starting_node.send_type? && starting_node.bare_access_modifier?
end
def configured_indentation_width
cop_config['Width']
end
def leftmost_modifier_of(node)
return node unless node.parent&.send_type?
leftmost_modifier_of(node.parent)
end
end
end
end
end
| mit |
katharosada/botchallenge | client/google/protobuf/internal/test_bad_identifiers_pb2.py | 5702 | # Generated by the protocol buffer compiler. DO NOT EDIT!
# source: google/protobuf/internal/test_bad_identifiers.proto
import sys
_b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1'))
from google.protobuf import descriptor as _descriptor
from google.protobuf import message as _message
from google.protobuf import reflection as _reflection
from google.protobuf import symbol_database as _symbol_database
from google.protobuf import service as _service
from google.protobuf import service_reflection
from google.protobuf import descriptor_pb2
# @@protoc_insertion_point(imports)
_sym_db = _symbol_database.Default()
DESCRIPTOR = _descriptor.FileDescriptor(
name='google/protobuf/internal/test_bad_identifiers.proto',
package='protobuf_unittest',
serialized_pb=_b('\n3google/protobuf/internal/test_bad_identifiers.proto\x12\x11protobuf_unittest\"\x1e\n\x12TestBadIdentifiers*\x08\x08\x64\x10\x80\x80\x80\x80\x02\"\x10\n\x0e\x41notherMessage2\x10\n\x0e\x41notherService:;\n\x07message\x12%.protobuf_unittest.TestBadIdentifiers\x18\x64 \x01(\t:\x03\x66oo:>\n\ndescriptor\x12%.protobuf_unittest.TestBadIdentifiers\x18\x65 \x01(\t:\x03\x62\x61r:>\n\nreflection\x12%.protobuf_unittest.TestBadIdentifiers\x18\x66 \x01(\t:\x03\x62\x61z:;\n\x07service\x12%.protobuf_unittest.TestBadIdentifiers\x18g \x01(\t:\x03quxB\x03\x90\x01\x01')
)
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
MESSAGE_FIELD_NUMBER = 100
message = _descriptor.FieldDescriptor(
name='message', full_name='protobuf_unittest.message', index=0,
number=100, type=9, cpp_type=9, label=1,
has_default_value=True, default_value=_b("foo").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=True, extension_scope=None,
options=None)
DESCRIPTOR_FIELD_NUMBER = 101
descriptor = _descriptor.FieldDescriptor(
name='descriptor', full_name='protobuf_unittest.descriptor', index=1,
number=101, type=9, cpp_type=9, label=1,
has_default_value=True, default_value=_b("bar").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=True, extension_scope=None,
options=None)
REFLECTION_FIELD_NUMBER = 102
reflection = _descriptor.FieldDescriptor(
name='reflection', full_name='protobuf_unittest.reflection', index=2,
number=102, type=9, cpp_type=9, label=1,
has_default_value=True, default_value=_b("baz").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=True, extension_scope=None,
options=None)
SERVICE_FIELD_NUMBER = 103
service = _descriptor.FieldDescriptor(
name='service', full_name='protobuf_unittest.service', index=3,
number=103, type=9, cpp_type=9, label=1,
has_default_value=True, default_value=_b("qux").decode('utf-8'),
message_type=None, enum_type=None, containing_type=None,
is_extension=True, extension_scope=None,
options=None)
_TESTBADIDENTIFIERS = _descriptor.Descriptor(
name='TestBadIdentifiers',
full_name='protobuf_unittest.TestBadIdentifiers',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=True,
extension_ranges=[(100, 536870912), ],
oneofs=[
],
serialized_start=74,
serialized_end=104,
)
_ANOTHERMESSAGE = _descriptor.Descriptor(
name='AnotherMessage',
full_name='protobuf_unittest.AnotherMessage',
filename=None,
file=DESCRIPTOR,
containing_type=None,
fields=[
],
extensions=[
],
nested_types=[],
enum_types=[
],
options=None,
is_extendable=False,
extension_ranges=[],
oneofs=[
],
serialized_start=106,
serialized_end=122,
)
DESCRIPTOR.message_types_by_name['TestBadIdentifiers'] = _TESTBADIDENTIFIERS
DESCRIPTOR.message_types_by_name['AnotherMessage'] = _ANOTHERMESSAGE
DESCRIPTOR.extensions_by_name['message'] = message
DESCRIPTOR.extensions_by_name['descriptor'] = descriptor
DESCRIPTOR.extensions_by_name['reflection'] = reflection
DESCRIPTOR.extensions_by_name['service'] = service
TestBadIdentifiers = _reflection.GeneratedProtocolMessageType('TestBadIdentifiers', (_message.Message,), dict(
DESCRIPTOR = _TESTBADIDENTIFIERS,
__module__ = 'google.protobuf.internal.test_bad_identifiers_pb2'
# @@protoc_insertion_point(class_scope:protobuf_unittest.TestBadIdentifiers)
))
_sym_db.RegisterMessage(TestBadIdentifiers)
AnotherMessage = _reflection.GeneratedProtocolMessageType('AnotherMessage', (_message.Message,), dict(
DESCRIPTOR = _ANOTHERMESSAGE,
__module__ = 'google.protobuf.internal.test_bad_identifiers_pb2'
# @@protoc_insertion_point(class_scope:protobuf_unittest.AnotherMessage)
))
_sym_db.RegisterMessage(AnotherMessage)
TestBadIdentifiers.RegisterExtension(message)
TestBadIdentifiers.RegisterExtension(descriptor)
TestBadIdentifiers.RegisterExtension(reflection)
TestBadIdentifiers.RegisterExtension(service)
DESCRIPTOR.has_options = True
DESCRIPTOR._options = _descriptor._ParseOptions(descriptor_pb2.FileOptions(), _b('\220\001\001'))
_ANOTHERSERVICE = _descriptor.ServiceDescriptor(
name='AnotherService',
full_name='protobuf_unittest.AnotherService',
file=DESCRIPTOR,
index=0,
options=None,
serialized_start=124,
serialized_end=140,
methods=[
])
AnotherService = service_reflection.GeneratedServiceType('AnotherService', (_service.Service,), dict(
DESCRIPTOR = _ANOTHERSERVICE,
__module__ = 'google.protobuf.internal.test_bad_identifiers_pb2'
))
AnotherService_Stub = service_reflection.GeneratedServiceStubType('AnotherService_Stub', (AnotherService,), dict(
DESCRIPTOR = _ANOTHERSERVICE,
__module__ = 'google.protobuf.internal.test_bad_identifiers_pb2'
))
# @@protoc_insertion_point(module_scope)
| mit |
artivilla/desktop | app/src/ui/banners/update-available.tsx | 2023 | import * as React from 'react'
import { Dispatcher } from '../dispatcher/index'
import { LinkButton } from '../lib/link-button'
import { updateStore } from '../lib/update-store'
import { Octicon } from '../octicons'
import * as OcticonSymbol from '../octicons/octicons.generated'
import { PopupType } from '../../models/popup'
import { shell } from '../../lib/app-shell'
import { ReleaseSummary } from '../../models/release-notes'
import { Banner } from './banner'
import { ReleaseNotesUri } from '../lib/releases'
interface IUpdateAvailableProps {
readonly dispatcher: Dispatcher
readonly newRelease: ReleaseSummary | null
readonly onDismissed: () => void
}
/**
* A component which tells the user an update is available and gives them the
* option of moving into the future or being a luddite.
*/
export class UpdateAvailable extends React.Component<
IUpdateAvailableProps,
{}
> {
public render() {
return (
<Banner id="update-available" onDismissed={this.props.onDismissed}>
<Octicon
className="download-icon"
symbol={OcticonSymbol.desktopDownload}
/>
<span onSubmit={this.updateNow}>
An updated version of GitHub Desktop is available and will be
installed at the next launch. See{' '}
<LinkButton onClick={this.showReleaseNotes}>what's new</LinkButton> or{' '}
<LinkButton onClick={this.updateNow}>
restart GitHub Desktop
</LinkButton>
.
</span>
</Banner>
)
}
private showReleaseNotes = () => {
if (this.props.newRelease == null) {
// if, for some reason we're not able to render the release notes we
// should redirect the user to the website so we do _something_
shell.openExternal(ReleaseNotesUri)
} else {
this.props.dispatcher.showPopup({
type: PopupType.ReleaseNotes,
newRelease: this.props.newRelease,
})
}
}
private updateNow = () => {
updateStore.quitAndInstallUpdate()
}
}
| mit |
darkrasid/gitlabhq | spec/lib/gitlab/import_export/wiki_repo_saver_spec.rb | 948 | require 'spec_helper'
describe Gitlab::ImportExport::WikiRepoSaver, services: true do
describe 'bundle a wiki Git repo' do
let(:user) { create(:user) }
let!(:project) { create(:empty_project, :public, name: 'searchable_project') }
let(:export_path) { "#{Dir.tmpdir}/project_tree_saver_spec" }
let(:shared) { Gitlab::ImportExport::Shared.new(relative_path: project.path_with_namespace) }
let(:wiki_bundler) { described_class.new(project: project, shared: shared) }
let!(:project_wiki) { ProjectWiki.new(project, user) }
before do
project.team << [user, :master]
allow_any_instance_of(Gitlab::ImportExport).to receive(:storage_path).and_return(export_path)
project_wiki.wiki
project_wiki.create_page("index", "test content")
end
after do
FileUtils.rm_rf(export_path)
end
it 'bundles the repo successfully' do
expect(wiki_bundler.save).to be true
end
end
end
| mit |
aspose-cells/Aspose.Cells-for-Cloud | SDKs/Aspose.Cells-Cloud-SDK-for-Ruby/lib/aspose_cells_cloud/models/cell.rb | 3914 | module AsposeCellsCloud
#
class Cell < BaseObject
attr_accessor :name, :row, :column, :value, :type, :formula, :is_formula, :is_merged, :is_array_header, :is_in_array, :is_error_value, :is_in_table, :is_style_set, :html_string, :style, :worksheet, :link
# attribute mapping from ruby-style variable name to JSON key
def self.attribute_map
{
#
:'name' => :'Name',
#
:'row' => :'Row',
#
:'column' => :'Column',
#
:'value' => :'Value',
#
:'type' => :'Type',
#
:'formula' => :'Formula',
#
:'is_formula' => :'IsFormula',
#
:'is_merged' => :'IsMerged',
#
:'is_array_header' => :'IsArrayHeader',
#
:'is_in_array' => :'IsInArray',
#
:'is_error_value' => :'IsErrorValue',
#
:'is_in_table' => :'IsInTable',
#
:'is_style_set' => :'IsStyleSet',
#
:'html_string' => :'HtmlString',
#
:'style' => :'Style',
#
:'worksheet' => :'Worksheet',
#
:'link' => :'link'
}
end
# attribute type
def self.swagger_types
{
:'name' => :'String',
:'row' => :'Integer',
:'column' => :'Integer',
:'value' => :'String',
:'type' => :'String',
:'formula' => :'String',
:'is_formula' => :'BOOLEAN',
:'is_merged' => :'BOOLEAN',
:'is_array_header' => :'BOOLEAN',
:'is_in_array' => :'BOOLEAN',
:'is_error_value' => :'BOOLEAN',
:'is_in_table' => :'BOOLEAN',
:'is_style_set' => :'BOOLEAN',
:'html_string' => :'String',
:'style' => :'LinkElement',
:'worksheet' => :'String',
:'link' => :'Link'
}
end
def initialize(attributes = {})
return if !attributes.is_a?(Hash) || attributes.empty?
# convert string to symbol for hash key
attributes = attributes.inject({}){|memo,(k,v)| memo[k.to_sym] = v; memo}
if attributes[:'Name']
self.name = attributes[:'Name']
end
if attributes[:'Row']
self.row = attributes[:'Row']
end
if attributes[:'Column']
self.column = attributes[:'Column']
end
if attributes[:'Value']
self.value = attributes[:'Value']
end
if attributes[:'Type']
self.type = attributes[:'Type']
end
if attributes[:'Formula']
self.formula = attributes[:'Formula']
end
if attributes[:'IsFormula']
self.is_formula = attributes[:'IsFormula']
end
if attributes[:'IsMerged']
self.is_merged = attributes[:'IsMerged']
end
if attributes[:'IsArrayHeader']
self.is_array_header = attributes[:'IsArrayHeader']
end
if attributes[:'IsInArray']
self.is_in_array = attributes[:'IsInArray']
end
if attributes[:'IsErrorValue']
self.is_error_value = attributes[:'IsErrorValue']
end
if attributes[:'IsInTable']
self.is_in_table = attributes[:'IsInTable']
end
if attributes[:'IsStyleSet']
self.is_style_set = attributes[:'IsStyleSet']
end
if attributes[:'HtmlString']
self.html_string = attributes[:'HtmlString']
end
if attributes[:'Style']
self.style = attributes[:'Style']
end
if attributes[:'Worksheet']
self.worksheet = attributes[:'Worksheet']
end
if attributes[:'link']
self.link = attributes[:'link']
end
end
end
end
| mit |
moneta-project/moneta-2.0.1.0 | src/qt/locale/moneta_hu.ts | 84689 | <TS language="hu" version="2.1">
<context>
<name>AddressBookPage</name>
<message>
<source>Right-click to edit address or label</source>
<translation>A cím vagy címke szerkeszteséhez kattintson a jobb gombbal</translation>
</message>
<message>
<source>Create a new address</source>
<translation>Új cím létrehozása</translation>
</message>
<message>
<source>&New</source>
<translation>&Új</translation>
</message>
<message>
<source>Copy the currently selected address to the system clipboard</source>
<translation>A kiválasztott cím másolása a vágólapra</translation>
</message>
<message>
<source>&Copy</source>
<translation>&Másolás</translation>
</message>
<message>
<source>C&lose</source>
<translation>&Bezárás</translation>
</message>
<message>
<source>&Copy Address</source>
<translation>&Cím másolása</translation>
</message>
<message>
<source>Delete the currently selected address from the list</source>
<translation>Kiválasztott cím törlése a listából</translation>
</message>
<message>
<source>Export the data in the current tab to a file</source>
<translation>Jelenlegi nézet exportálása fájlba</translation>
</message>
<message>
<source>&Export</source>
<translation>&Exportálás</translation>
</message>
<message>
<source>&Delete</source>
<translation>&Törlés</translation>
</message>
<message>
<source>Choose the address to send coins to</source>
<translation>Válaszd ki a címet, ahová küldesz</translation>
</message>
<message>
<source>Choose the address to receive coins with</source>
<translation>Válaszd ki a címet, amivel fogadsz</translation>
</message>
<message>
<source>C&hoose</source>
<translation>&Kiválaszt</translation>
</message>
<message>
<source>Sending addresses</source>
<translation>Küldési címek</translation>
</message>
<message>
<source>Receiving addresses</source>
<translation>Fogadó címek</translation>
</message>
<message>
<source>These are your Moneta addresses for sending payments. Always check the amount and the receiving address before sending coins.</source>
<translation>Ezekről a címekről küldhetsz monetat. Mindig ellenőrizd a fogadó címet és a fizetendő összeget, mielőtt elküldöd.</translation>
</message>
<message>
<source>These are your Moneta addresses for receiving payments. It is recommended to use a new receiving address for each transaction.</source>
<translation>Ezekkel a címekkel fogadhatsz monetat. Ajánlott minden tranzakcióhoz egy új fogadó címet használni.</translation>
</message>
<message>
<source>Copy &Label</source>
<translation>&Címke másolása</translation>
</message>
<message>
<source>&Edit</source>
<translation>Sz&erkesztés</translation>
</message>
<message>
<source>Export Address List</source>
<translation>Címjegyzék exportálása</translation>
</message>
<message>
<source>Comma separated file (*.csv)</source>
<translation>Vesszővel elválasztott fájl (*. csv)</translation>
</message>
<message>
<source>Exporting Failed</source>
<translation>Az exportálás sikertelen volt</translation>
</message>
<message>
<source>There was an error trying to save the address list to %1. Please try again.</source>
<translation>Hiba történt a címjegyzék %1 helyre való mentésekor. Kérlek próbáld újra.</translation>
</message>
</context>
<context>
<name>AddressTableModel</name>
<message>
<source>Label</source>
<translation>Címke</translation>
</message>
<message>
<source>Address</source>
<translation>Cím</translation>
</message>
<message>
<source>(no label)</source>
<translation>(nincs címke)</translation>
</message>
</context>
<context>
<name>AskPassphraseDialog</name>
<message>
<source>Passphrase Dialog</source>
<translation>Jelszó párbeszédablak</translation>
</message>
<message>
<source>Enter passphrase</source>
<translation>Add meg a jelszót</translation>
</message>
<message>
<source>New passphrase</source>
<translation>Új jelszó</translation>
</message>
<message>
<source>Repeat new passphrase</source>
<translation>Új jelszó újra</translation>
</message>
<message>
<source>Encrypt wallet</source>
<translation>Tárca titkosítása</translation>
</message>
<message>
<source>This operation needs your wallet passphrase to unlock the wallet.</source>
<translation>A tárca megnyitásához a műveletnek szüksége van a tárcád jelszavára.</translation>
</message>
<message>
<source>Unlock wallet</source>
<translation>Tárca megnyitása</translation>
</message>
<message>
<source>This operation needs your wallet passphrase to decrypt the wallet.</source>
<translation>A tárca dekódolásához a műveletnek szüksége van a tárcád jelszavára.</translation>
</message>
<message>
<source>Decrypt wallet</source>
<translation>Tárca dekódolása</translation>
</message>
<message>
<source>Change passphrase</source>
<translation>Jelszó megváltoztatása</translation>
</message>
<message>
<source>Enter the old and new passphrase to the wallet.</source>
<translation>Írd be a tárca régi és új jelszavát.</translation>
</message>
<message>
<source>Confirm wallet encryption</source>
<translation>Biztosan titkosítani akarod a tárcát?</translation>
</message>
<message>
<source>Warning: If you encrypt your wallet and lose your passphrase, you will <b>LOSE ALL OF YOUR MONETAS</b>!</source>
<translation>Figyelem: ha titkosítod a tárcát és elveszted a jelszavad, akkor <b>AZ ÖSSZES MONETAOD ELVESZIK!</b></translation>
</message>
<message>
<source>Are you sure you wish to encrypt your wallet?</source>
<translation>Biztosan titkosítani akarod a tárcád?</translation>
</message>
<message>
<source>IMPORTANT: Any previous backups you have made of your wallet file should be replaced with the newly generated, encrypted wallet file. For security reasons, previous backups of the unencrypted wallet file will become useless as soon as you start using the new, encrypted wallet.</source>
<translation>FONTOS: A tárca-fájl minden korábbi mentését cseréld le ezzel az új, titkosított tárca-fájllal. Biztonsági okokból a tárca-fájl korábbi, titkosítás nélküli mentései használhatatlanná válnak, amint elkezded használni az új, titkosított tárcát.</translation>
</message>
<message>
<source>Warning: The Caps Lock key is on!</source>
<translation>Vigyázat: a Caps Lock be van kapcsolva!</translation>
</message>
<message>
<source>Wallet encrypted</source>
<translation>Tárca titkosítva</translation>
</message>
<message>
<source>Enter the new passphrase to the wallet.<br/>Please use a passphrase of <b>ten or more random characters</b>, or <b>eight or more words</b>.</source>
<translation>Add meg a tárca új jelszavát.<br/>Olyan jelszót válassz, ami <b>legalább tíz véletlenszerű karakterből</b> vagy <b>legalább 8 véletlenszerű szóból</b> áll.</translation>
</message>
<message>
<source>Moneta will close now to finish the encryption process. Remember that encrypting your wallet cannot fully protect your monetas from being stolen by malware infecting your computer.</source>
<translation>A Moneta Core most bezár, hogy befejezze a titkosítást. Ne feledd: a tárca titkosítása nem nyújt teljes védelmet azzal szemben, hogy adathalász programok megfertőzzék a számítógéped és ellopják a monetajaid.</translation>
</message>
<message>
<source>Wallet encryption failed</source>
<translation>A tárca titkosítása sikertelen.</translation>
</message>
<message>
<source>Wallet encryption failed due to an internal error. Your wallet was not encrypted.</source>
<translation>Tárca titkosítása belső hiba miatt sikertelen. A tárcád nem lett titkosítva.</translation>
</message>
<message>
<source>The supplied passphrases do not match.</source>
<translation>A megadott jelszavak nem egyeznek.</translation>
</message>
<message>
<source>Wallet unlock failed</source>
<translation>Tárca megnyitása sikertelen</translation>
</message>
<message>
<source>The passphrase entered for the wallet decryption was incorrect.</source>
<translation>Hibás jelszó.</translation>
</message>
<message>
<source>Wallet decryption failed</source>
<translation>Dekódolás sikertelen.</translation>
</message>
<message>
<source>Wallet passphrase was successfully changed.</source>
<translation>Jelszó megváltoztatva.</translation>
</message>
</context>
<context>
<name>MonetaGUI</name>
<message>
<source>Sign &message...</source>
<translation>Üzenet aláírása...</translation>
</message>
<message>
<source>Synchronizing with network...</source>
<translation>Szinkronizálás a hálózattal...</translation>
</message>
<message>
<source>&Overview</source>
<translation>&Áttekintés</translation>
</message>
<message>
<source>Node</source>
<translation>Csomópont</translation>
</message>
<message>
<source>Show general overview of wallet</source>
<translation>Tárca általános áttekintése</translation>
</message>
<message>
<source>&Transactions</source>
<translation>&Tranzakciók</translation>
</message>
<message>
<source>Browse transaction history</source>
<translation>Tranzakciós előzmények megtekintése</translation>
</message>
<message>
<source>E&xit</source>
<translation>&Kilépés</translation>
</message>
<message>
<source>Quit application</source>
<translation>Kilépés az alkalmazásból</translation>
</message>
<message>
<source>About &Qt</source>
<translation>A &Qt-ról</translation>
</message>
<message>
<source>Show information about Qt</source>
<translation>Információk a Qt-ról</translation>
</message>
<message>
<source>&Options...</source>
<translation>&Opciók...</translation>
</message>
<message>
<source>&Encrypt Wallet...</source>
<translation>Tárca &titkosítása...</translation>
</message>
<message>
<source>&Backup Wallet...</source>
<translation>&Bisztonsági másolat készítése a Tárcáról</translation>
</message>
<message>
<source>&Change Passphrase...</source>
<translation>Jelszó &megváltoztatása...</translation>
</message>
<message>
<source>&Sending addresses...</source>
<translation>&Küldési címek...</translation>
</message>
<message>
<source>&Receiving addresses...</source>
<translation>&Fogadó címek...</translation>
</message>
<message>
<source>Open &URI...</source>
<translation>&URI azonosító megnyitása...</translation>
</message>
<message>
<source>Moneta Core client</source>
<translation>Moneta Core kliens</translation>
</message>
<message>
<source>Importing blocks from disk...</source>
<translation>A blokkok importálása lemezről...</translation>
</message>
<message>
<source>Reindexing blocks on disk...</source>
<translation>Lemezen lévő blokkok újraindexelése...</translation>
</message>
<message>
<source>Send coins to a Moneta address</source>
<translation>Moneta küldése megadott címre</translation>
</message>
<message>
<source>Modify configuration options for Moneta</source>
<translation>Moneta konfigurációs opciók</translation>
</message>
<message>
<source>Backup wallet to another location</source>
<translation>Biztonsági másolat készítése a tárcáról egy másik helyre</translation>
</message>
<message>
<source>Change the passphrase used for wallet encryption</source>
<translation>Tárca-titkosító jelszó megváltoztatása</translation>
</message>
<message>
<source>&Debug window</source>
<translation>&Debug ablak</translation>
</message>
<message>
<source>Open debugging and diagnostic console</source>
<translation>Hibakereső és diagnosztikai konzol megnyitása</translation>
</message>
<message>
<source>&Verify message...</source>
<translation>Üzenet &valódiságának ellenőrzése</translation>
</message>
<message>
<source>Moneta</source>
<translation>Moneta</translation>
</message>
<message>
<source>Wallet</source>
<translation>Tárca</translation>
</message>
<message>
<source>&Send</source>
<translation>&Küldés</translation>
</message>
<message>
<source>&Receive</source>
<translation>&Fogadás</translation>
</message>
<message>
<source>Show information about Moneta Core</source>
<translation>Moneta Core információ megjelenítése</translation>
</message>
<message>
<source>&Show / Hide</source>
<translation>&Mutat / Elrejt</translation>
</message>
<message>
<source>Show or hide the main Window</source>
<translation>Főablakot mutat/elrejt</translation>
</message>
<message>
<source>Encrypt the private keys that belong to your wallet</source>
<translation>A tárcádhoz tartozó privát kulcsok titkosítása</translation>
</message>
<message>
<source>Sign messages with your Moneta addresses to prove you own them</source>
<translation>Üzenetek aláírása a Moneta-címmeiddel, amivel bizonyítod, hogy a cím a sajátod</translation>
</message>
<message>
<source>Verify messages to ensure they were signed with specified Moneta addresses</source>
<translation>Üzenetek ellenőrzése, hogy valóban a megjelölt Moneta-címekkel vannak-e aláírva</translation>
</message>
<message>
<source>&File</source>
<translation>&Fájl</translation>
</message>
<message>
<source>&Settings</source>
<translation>&Beállítások</translation>
</message>
<message>
<source>&Help</source>
<translation>&Súgó</translation>
</message>
<message>
<source>Tabs toolbar</source>
<translation>Fül eszköztár</translation>
</message>
<message>
<source>Moneta Core</source>
<translation>Moneta Core</translation>
</message>
<message>
<source>Request payments (generates QR codes and moneta: URIs)</source>
<translation>Fizetési kérelem (QR-kódot és "moneta:" URI azonosítót hoz létre)</translation>
</message>
<message>
<source>&About Moneta Core</source>
<translation>&A Moneta Core-ról</translation>
</message>
<message>
<source>Show the list of used sending addresses and labels</source>
<translation>A használt küldési címek és címkék megtekintése</translation>
</message>
<message>
<source>Show the list of used receiving addresses and labels</source>
<translation>A használt fogadó címek és címkék megtekintése</translation>
</message>
<message>
<source>Open a moneta: URI or payment request</source>
<translation>"moneta:" URI azonosító vagy fizetési kérelem megnyitása</translation>
</message>
<message>
<source>&Command-line options</source>
<translation>Paran&cssor kapcsolók</translation>
</message>
<message>
<source>Show the Moneta Core help message to get a list with possible Moneta command-line options</source>
<translation>A Moneta Core súgóüzenet megjelenítése a Moneta lehetséges parancssori kapcsolóival.</translation>
</message>
<message numerus="yes">
<source>%n active connection(s) to Moneta network</source>
<translation><numerusform>%n aktív kapcsolat a Moneta-hálózattal</numerusform><numerusform>%n aktív kapcsolat a Moneta-hálózattal</numerusform></translation>
</message>
<message>
<source>No block source available...</source>
<translation>Blokk forrása ismeretlen...</translation>
</message>
<message numerus="yes">
<source>%n hour(s)</source>
<translation><numerusform>%n óra</numerusform><numerusform>%n óra</numerusform></translation>
</message>
<message numerus="yes">
<source>%n day(s)</source>
<translation><numerusform>%n nap</numerusform><numerusform>%n nap</numerusform></translation>
</message>
<message numerus="yes">
<source>%n week(s)</source>
<translation><numerusform>%n hét</numerusform><numerusform>%n hét</numerusform></translation>
</message>
<message>
<source>%1 and %2</source>
<translation>%1 és %2</translation>
</message>
<message numerus="yes">
<source>%n year(s)</source>
<translation><numerusform>%n év</numerusform><numerusform>%n év</numerusform></translation>
</message>
<message>
<source>%1 behind</source>
<translation>%1 lemaradás</translation>
</message>
<message>
<source>Last received block was generated %1 ago.</source>
<translation>Az utolsóként kapott blokk kora: %1.</translation>
</message>
<message>
<source>Transactions after this will not yet be visible.</source>
<translation>Ez utáni tranzakciók még nem lesznek láthatóak. </translation>
</message>
<message>
<source>Error</source>
<translation>Hiba</translation>
</message>
<message>
<source>Warning</source>
<translation>Figyelem</translation>
</message>
<message>
<source>Information</source>
<translation>Információ</translation>
</message>
<message>
<source>Up to date</source>
<translation>Naprakész</translation>
</message>
<message>
<source>Catching up...</source>
<translation>Frissítés...</translation>
</message>
<message>
<source>Sent transaction</source>
<translation>Tranzakció elküldve.</translation>
</message>
<message>
<source>Incoming transaction</source>
<translation>Beérkező tranzakció</translation>
</message>
<message>
<source>Date: %1
Amount: %2
Type: %3
Address: %4
</source>
<translation>Dátum: %1
Összeg: %2
Típus: %3
Cím: %4
</translation>
</message>
<message>
<source>Wallet is <b>encrypted</b> and currently <b>unlocked</b></source>
<translation>A tárca <b>titkosítva</b> és jelenleg <b>nyitva</b>.</translation>
</message>
<message>
<source>Wallet is <b>encrypted</b> and currently <b>locked</b></source>
<translation>Tárca <b>kódolva</b> és jelenleg <b>zárva</b>.</translation>
</message>
</context>
<context>
<name>ClientModel</name>
<message>
<source>Network Alert</source>
<translation>Hálózati figyelmeztetés</translation>
</message>
</context>
<context>
<name>CoinControlDialog</name>
<message>
<source>Quantity:</source>
<translation>Mennyiség:</translation>
</message>
<message>
<source>Bytes:</source>
<translation>Bájtok:</translation>
</message>
<message>
<source>Amount:</source>
<translation>Összeg:</translation>
</message>
<message>
<source>Priority:</source>
<translation>Prioritás:</translation>
</message>
<message>
<source>Fee:</source>
<translation>Díjak:</translation>
</message>
<message>
<source>Dust:</source>
<translation>Por-határ:</translation>
</message>
<message>
<source>After Fee:</source>
<translation>Utólagos díj:</translation>
</message>
<message>
<source>Change:</source>
<translation>Visszajáró:</translation>
</message>
<message>
<source>(un)select all</source>
<translation>mindent kiválaszt/elvet</translation>
</message>
<message>
<source>Tree mode</source>
<translation>Fa nézet</translation>
</message>
<message>
<source>List mode</source>
<translation>Lista nézet</translation>
</message>
<message>
<source>Amount</source>
<translation>Összeg</translation>
</message>
<message>
<source>Date</source>
<translation>Dátum</translation>
</message>
<message>
<source>Confirmations</source>
<translation>Megerősítések</translation>
</message>
<message>
<source>Confirmed</source>
<translation>Megerősítve</translation>
</message>
<message>
<source>Priority</source>
<translation>Prioritás</translation>
</message>
<message>
<source>Copy address</source>
<translation>Cím másolása</translation>
</message>
<message>
<source>Copy label</source>
<translation>Címke másolása</translation>
</message>
<message>
<source>Copy amount</source>
<translation>Összeg másolása</translation>
</message>
<message>
<source>Copy transaction ID</source>
<translation>Tranzakcióazonosító másolása</translation>
</message>
<message>
<source>Lock unspent</source>
<translation>Megmaradt zárolása</translation>
</message>
<message>
<source>Unlock unspent</source>
<translation>Zárolás feloldása</translation>
</message>
<message>
<source>Copy quantity</source>
<translation>Mennyiség másolása</translation>
</message>
<message>
<source>Copy fee</source>
<translation>Díj másolása</translation>
</message>
<message>
<source>Copy after fee</source>
<translation>Utólagos díj másolása</translation>
</message>
<message>
<source>Copy bytes</source>
<translation>Byte-ok másolása </translation>
</message>
<message>
<source>Copy priority</source>
<translation>Prioritás másolása</translation>
</message>
<message>
<source>Copy dust</source>
<translation>Por-határ másolása</translation>
</message>
<message>
<source>Copy change</source>
<translation>Visszajáró másolása</translation>
</message>
<message>
<source>highest</source>
<translation>legmagasabb</translation>
</message>
<message>
<source>higher</source>
<translation>magasabb</translation>
</message>
<message>
<source>high</source>
<translation>magas</translation>
</message>
<message>
<source>medium-high</source>
<translation>közepesen-magas</translation>
</message>
<message>
<source>medium</source>
<translation>közepes</translation>
</message>
<message>
<source>low-medium</source>
<translation>alacsony-közepes</translation>
</message>
<message>
<source>low</source>
<translation>alacsony</translation>
</message>
<message>
<source>lower</source>
<translation>alacsonyabb</translation>
</message>
<message>
<source>lowest</source>
<translation>legalacsonyabb</translation>
</message>
<message>
<source>(%1 locked)</source>
<translation>(%1 zárolva)</translation>
</message>
<message>
<source>none</source>
<translation>semmi</translation>
</message>
<message>
<source>Can vary +/- %1 satoshi(s) per input.</source>
<translation>Bemenetenként +/- %1 satoshi-val változhat</translation>
</message>
<message>
<source>yes</source>
<translation>igen</translation>
</message>
<message>
<source>no</source>
<translation>nem</translation>
</message>
<message>
<source>This label turns red, if the transaction size is greater than 1000 bytes.</source>
<translation>Ez a címke piros lesz, ha tranzakció mérete nagyobb 1000 byte-nál.</translation>
</message>
<message>
<source>This means a fee of at least %1 per kB is required.</source>
<translation>Legalább %1 díj szüksége kB-onként.</translation>
</message>
<message>
<source>Can vary +/- 1 byte per input.</source>
<translation>Bemenetenként +/- 1 byte-al változhat.</translation>
</message>
<message>
<source>Transactions with higher priority are more likely to get included into a block.</source>
<translation>Nagyobb prioritású tranzakciók nagyobb valószínűséggel kerülnek be egy blokkba.</translation>
</message>
<message>
<source>This label turns red, if the priority is smaller than "medium".</source>
<translation>Ez a címke piros lesz, ha a prioritás közepesnél alacsonyabb.</translation>
</message>
<message>
<source>This label turns red, if any recipient receives an amount smaller than %1.</source>
<translation>Ez a címke piros lesz, ha valamelyik elfogadó kevesebbet kap mint %1.</translation>
</message>
<message>
<source>(no label)</source>
<translation>(nincs címke)</translation>
</message>
<message>
<source>change from %1 (%2)</source>
<translation>visszajáró %1-ből (%2)</translation>
</message>
<message>
<source>(change)</source>
<translation>(visszajáró)</translation>
</message>
</context>
<context>
<name>EditAddressDialog</name>
<message>
<source>Edit Address</source>
<translation>Cím szerkesztése</translation>
</message>
<message>
<source>&Label</source>
<translation>Cím&ke</translation>
</message>
<message>
<source>The label associated with this address list entry</source>
<translation>Ehhez a listaelemhez rendelt címke </translation>
</message>
<message>
<source>The address associated with this address list entry. This can only be modified for sending addresses.</source>
<translation>Ehhez a címlistaelemhez rendelt cím. Csak a küldő címek módosíthatók.</translation>
</message>
<message>
<source>&Address</source>
<translation>&Cím</translation>
</message>
<message>
<source>New receiving address</source>
<translation>Új fogadó cím</translation>
</message>
<message>
<source>New sending address</source>
<translation>Új küldő cím</translation>
</message>
<message>
<source>Edit receiving address</source>
<translation>Fogadó cím szerkesztése</translation>
</message>
<message>
<source>Edit sending address</source>
<translation>Küldő cím szerkesztése</translation>
</message>
<message>
<source>The entered address "%1" is already in the address book.</source>
<translation>A megadott "%1" cím már szerepel a címjegyzékben.</translation>
</message>
<message>
<source>The entered address "%1" is not a valid Moneta address.</source>
<translation>A megadott "%1" cím nem egy érvényes Moneta-cím.</translation>
</message>
<message>
<source>Could not unlock wallet.</source>
<translation>Tárca feloldása sikertelen</translation>
</message>
<message>
<source>New key generation failed.</source>
<translation>Új kulcs generálása sikertelen</translation>
</message>
</context>
<context>
<name>FreespaceChecker</name>
<message>
<source>A new data directory will be created.</source>
<translation>Új adatkönyvtár lesz létrehozva.</translation>
</message>
<message>
<source>name</source>
<translation>Név</translation>
</message>
<message>
<source>Path already exists, and is not a directory.</source>
<translation>Az elérési út létezik, de nem egy könyvtáré.</translation>
</message>
<message>
<source>Cannot create data directory here.</source>
<translation>Adatkönyvtár nem hozható itt létre.</translation>
</message>
</context>
<context>
<name>HelpMessageDialog</name>
<message>
<source>Moneta Core</source>
<translation>Moneta Core</translation>
</message>
<message>
<source>version</source>
<translation>verzió</translation>
</message>
<message>
<source>(%1-bit)</source>
<translation>(%1-bit)</translation>
</message>
<message>
<source>About Moneta Core</source>
<translation>A Moneta Core-ról</translation>
</message>
<message>
<source>Command-line options</source>
<translation>Parancssoros opciók</translation>
</message>
<message>
<source>Usage:</source>
<translation>Használat:</translation>
</message>
<message>
<source>command-line options</source>
<translation>parancssoros opciók</translation>
</message>
<message>
<source>UI options</source>
<translation>UI opciók</translation>
</message>
<message>
<source>Set language, for example "de_DE" (default: system locale)</source>
<translation>Nyelvbeállítás, például "de_DE" (alapértelmezett: rendszer nyelve)</translation>
</message>
<message>
<source>Start minimized</source>
<translation>Indítás lekicsinyítve
</translation>
</message>
<message>
<source>Set SSL root certificates for payment request (default: -system-)</source>
<translation>SLL gyökér-igazolások megadása fizetési kérelmekhez (alapértelmezett: -system-)</translation>
</message>
<message>
<source>Show splash screen on startup (default: 1)</source>
<translation>Indítóképernyő mutatása induláskor (alapértelmezett: 1)</translation>
</message>
<message>
<source>Choose data directory on startup (default: 0)</source>
<translation>Adatkönyvtár kiválasztása induláskor (alapbeállítás: 0)</translation>
</message>
</context>
<context>
<name>Intro</name>
<message>
<source>Welcome</source>
<translation>Üdvözlünk</translation>
</message>
<message>
<source>Welcome to Moneta Core.</source>
<translation>Üdvözlünk a Moneta Core-ban.</translation>
</message>
<message>
<source>Use the default data directory</source>
<translation>Az alapértelmezett adat könyvtár használata</translation>
</message>
<message>
<source>Use a custom data directory:</source>
<translation>Saját adatkönyvtár használata:</translation>
</message>
<message>
<source>Moneta Core</source>
<translation>Moneta Core</translation>
</message>
<message>
<source>Error: Specified data directory "%1" cannot be created.</source>
<translation>Hiba: A megadott "%1" adatkönyvtár nem hozható létre. </translation>
</message>
<message>
<source>Error</source>
<translation>Hiba</translation>
</message>
</context>
<context>
<name>OpenURIDialog</name>
<message>
<source>Open URI</source>
<translation>URI megnyitása</translation>
</message>
<message>
<source>Open payment request from URI or file</source>
<translation>Fizetési kérelem megnyitása URI azonosítóból vagy fájlból</translation>
</message>
<message>
<source>URI:</source>
<translation>URI:</translation>
</message>
<message>
<source>Select payment request file</source>
<translation>Fizetési kérelmi fájl kiválasztása</translation>
</message>
<message>
<source>Select payment request file to open</source>
<translation>Fizetés kérelmi fájl kiválasztása</translation>
</message>
</context>
<context>
<name>OptionsDialog</name>
<message>
<source>Options</source>
<translation>Opciók</translation>
</message>
<message>
<source>&Main</source>
<translation>&Fő</translation>
</message>
<message>
<source>Automatically start Moneta after logging in to the system.</source>
<translation>Induljon el a Moneta a számítógép bekapcsolásakor</translation>
</message>
<message>
<source>&Start Moneta on system login</source>
<translation>&Induljon el a számítógép bekapcsolásakor</translation>
</message>
<message>
<source>MB</source>
<translation>MB</translation>
</message>
<message>
<source>Accept connections from outside</source>
<translation>Külső kapcsolatok elfogadása</translation>
</message>
<message>
<source>Allow incoming connections</source>
<translation>Bejövő kapcsolatok engedélyezése</translation>
</message>
<message>
<source>IP address of the proxy (e.g. IPv4: 127.0.0.1 / IPv6: ::1)</source>
<translation>A proxy IP címe (pl.: IPv4: 127.0.0.1 / IPv6: ::1)</translation>
</message>
<message>
<source>Reset all client options to default.</source>
<translation>Minden kliensbeállítás alapértelmezettre állítása.</translation>
</message>
<message>
<source>&Reset Options</source>
<translation>Beállítások tö&rlése</translation>
</message>
<message>
<source>&Network</source>
<translation>&Hálózat</translation>
</message>
<message>
<source>Automatically open the Moneta client port on the router. This only works when your router supports UPnP and it is enabled.</source>
<translation>A Moneta-kliens portjának automatikus megnyitása a routeren. Ez csak akkor működik, ha a routered támogatja az UPnP-t és az engedélyezve is van rajta.</translation>
</message>
<message>
<source>Map port using &UPnP</source>
<translation>&UPnP port-feltérképezés</translation>
</message>
<message>
<source>Proxy &IP:</source>
<translation>Proxy &IP:</translation>
</message>
<message>
<source>&Port:</source>
<translation>&Port:</translation>
</message>
<message>
<source>Port of the proxy (e.g. 9050)</source>
<translation>Proxy portja (pl.: 9050)</translation>
</message>
<message>
<source>&Window</source>
<translation>&Ablak</translation>
</message>
<message>
<source>Show only a tray icon after minimizing the window.</source>
<translation>Kicsinyítés után csak eszköztár-ikont mutass</translation>
</message>
<message>
<source>&Minimize to the tray instead of the taskbar</source>
<translation>&Kicsinyítés a tálcára az eszköztár helyett</translation>
</message>
<message>
<source>Minimize instead of exit the application when the window is closed. When this option is enabled, the application will be closed only after selecting Quit in the menu.</source>
<translation>Az alkalmazásból való kilépés helyett az eszköztárba kicsinyíti az alkalmazást az ablak bezárásakor. Ez esetben az alkalmazás csak a Kilépés menüponttal zárható be.</translation>
</message>
<message>
<source>M&inimize on close</source>
<translation>K&icsinyítés záráskor</translation>
</message>
<message>
<source>&Display</source>
<translation>&Megjelenítés</translation>
</message>
<message>
<source>User Interface &language:</source>
<translation>Felhasználófelület nye&lve:</translation>
</message>
<message>
<source>The user interface language can be set here. This setting will take effect after restarting Moneta.</source>
<translation>Itt beállíthatod a felhasználófelület nyelvét. Ez a beállítás a Moneta ujraindítása után lép érvénybe.</translation>
</message>
<message>
<source>&Unit to show amounts in:</source>
<translation>&Mértékegység:</translation>
</message>
<message>
<source>Choose the default subdivision unit to show in the interface and when sending coins.</source>
<translation>Válaszd ki az interfészen és érmék küldésekor megjelenítendő alapértelmezett alegységet.</translation>
</message>
<message>
<source>&OK</source>
<translation>&OK</translation>
</message>
<message>
<source>&Cancel</source>
<translation>Megszakítás</translation>
</message>
<message>
<source>default</source>
<translation>alapértelmezett</translation>
</message>
<message>
<source>none</source>
<translation>semmi</translation>
</message>
<message>
<source>Confirm options reset</source>
<translation>Beállítások törlésének jóváhagyása.</translation>
</message>
<message>
<source>Client restart required to activate changes.</source>
<translation>A változtatások aktiválásahoz újra kell indítani a klienst.</translation>
</message>
<message>
<source>The supplied proxy address is invalid.</source>
<translation>A megadott proxy cím nem érvényes.</translation>
</message>
</context>
<context>
<name>OverviewPage</name>
<message>
<source>Form</source>
<translation>Űrlap</translation>
</message>
<message>
<source>The displayed information may be out of date. Your wallet automatically synchronizes with the Moneta network after a connection is established, but this process has not completed yet.</source>
<translation>A kijelzett információ lehet, hogy elavult. A pénztárcája automatikusan szinkronizálja magát a Moneta hálózattal miután a kapcsolat létrejön, de ez e folyamat még nem fejeződött be.</translation>
</message>
<message>
<source>Available:</source>
<translation>Elérhető:</translation>
</message>
<message>
<source>Your current spendable balance</source>
<translation>Jelenlegi egyenleg</translation>
</message>
<message>
<source>Pending:</source>
<translation>Küldés:</translation>
</message>
<message>
<source>Total of transactions that have yet to be confirmed, and do not yet count toward the spendable balance</source>
<translation>Még megerősítésre váró, a jelenlegi egyenlegbe be nem számított tranzakciók</translation>
</message>
<message>
<source>Immature:</source>
<translation>Éretlen:</translation>
</message>
<message>
<source>Mined balance that has not yet matured</source>
<translation>Bányászott egyenleg amely még nem érett be.</translation>
</message>
<message>
<source>Total:</source>
<translation>Összesen:</translation>
</message>
<message>
<source>Your current total balance</source>
<translation>Aktuális egyenleged</translation>
</message>
<message>
<source>Spendable:</source>
<translation>Elkölthető:</translation>
</message>
<message>
<source>Recent transactions</source>
<translation>A legutóbbi tranzakciók</translation>
</message>
<message>
<source>out of sync</source>
<translation>Nincs szinkronban.</translation>
</message>
</context>
<context>
<name>PaymentServer</name>
<message>
<source>URI handling</source>
<translation>URI kezelés</translation>
</message>
<message>
<source>Cannot start moneta: click-to-pay handler</source>
<translation>A monetat nem lehet elindítani: click-to-pay handler</translation>
</message>
</context>
<context>
<name>PeerTableModel</name>
<message>
<source>Ping Time</source>
<translation>Ping idő</translation>
</message>
</context>
<context>
<name>QObject</name>
<message>
<source>Amount</source>
<translation>Összeg</translation>
</message>
<message>
<source>%1 d</source>
<translation>%1 n</translation>
</message>
<message>
<source>%1 h</source>
<translation>%1 ó</translation>
</message>
<message>
<source>%1 m</source>
<translation>%1 p</translation>
</message>
<message>
<source>%1 s</source>
<translation>%1 mp</translation>
</message>
<message>
<source>NETWORK</source>
<translation>HÁLÓZAT</translation>
</message>
<message>
<source>N/A</source>
<translation>Nem elérhető</translation>
</message>
</context>
<context>
<name>QRImageWidget</name>
<message>
<source>&Save Image...</source>
<translation>&Kép mentése</translation>
</message>
<message>
<source>&Copy Image</source>
<translation>&Kép másolása</translation>
</message>
<message>
<source>Save QR Code</source>
<translation>QR kód mentése</translation>
</message>
<message>
<source>PNG Image (*.png)</source>
<translation>PNG kép (*.png)</translation>
</message>
</context>
<context>
<name>RPCConsole</name>
<message>
<source>Client name</source>
<translation>Kliens néve</translation>
</message>
<message>
<source>N/A</source>
<translation>Nem elérhető</translation>
</message>
<message>
<source>Client version</source>
<translation>Kliens verzió</translation>
</message>
<message>
<source>&Information</source>
<translation>&Információ</translation>
</message>
<message>
<source>Debug window</source>
<translation>Debug ablak</translation>
</message>
<message>
<source>General</source>
<translation>Általános</translation>
</message>
<message>
<source>Using OpenSSL version</source>
<translation>Használt OpenSSL verzió</translation>
</message>
<message>
<source>Startup time</source>
<translation>Bekapcsolás ideje</translation>
</message>
<message>
<source>Network</source>
<translation>Hálózat</translation>
</message>
<message>
<source>Name</source>
<translation>Név</translation>
</message>
<message>
<source>Number of connections</source>
<translation>Kapcsolatok száma</translation>
</message>
<message>
<source>Block chain</source>
<translation>Blokklánc</translation>
</message>
<message>
<source>Current number of blocks</source>
<translation>Aktuális blokkok száma</translation>
</message>
<message>
<source>Received</source>
<translation>Fogadott</translation>
</message>
<message>
<source>Sent</source>
<translation>Küldött</translation>
</message>
<message>
<source>&Peers</source>
<translation>&Peerek</translation>
</message>
<message>
<source>Version</source>
<translation>Verzió</translation>
</message>
<message>
<source>Services</source>
<translation>Szolgáltatások</translation>
</message>
<message>
<source>Ping Time</source>
<translation>Ping idő</translation>
</message>
<message>
<source>Last block time</source>
<translation>Utolsó blokk ideje</translation>
</message>
<message>
<source>&Open</source>
<translation>&Megnyitás</translation>
</message>
<message>
<source>&Console</source>
<translation>&Konzol</translation>
</message>
<message>
<source>&Network Traffic</source>
<translation>&Hálózati forgalom</translation>
</message>
<message>
<source>Totals</source>
<translation>Összesen:</translation>
</message>
<message>
<source>In:</source>
<translation>Be:</translation>
</message>
<message>
<source>Out:</source>
<translation>Ki:</translation>
</message>
<message>
<source>Build date</source>
<translation>Fordítás dátuma</translation>
</message>
<message>
<source>Debug log file</source>
<translation>Debug naplófájl</translation>
</message>
<message>
<source>Clear console</source>
<translation>Konzol törlése</translation>
</message>
<message>
<source>Welcome to the Moneta RPC console.</source>
<translation>Üdv a Moneta RPC konzoljában!</translation>
</message>
<message>
<source>Use up and down arrows to navigate history, and <b>Ctrl-L</b> to clear screen.</source>
<translation>Navigálhat a fel és le nyilakkal, és <b>Ctrl-L</b> -vel törölheti a képernyőt.</translation>
</message>
<message>
<source>Type <b>help</b> for an overview of available commands.</source>
<translation>Írd be azt, hogy <b>help</b> az elérhető parancsok áttekintéséhez.</translation>
</message>
<message>
<source>%1 B</source>
<translation>%1 B</translation>
</message>
<message>
<source>%1 KB</source>
<translation>%1 KB</translation>
</message>
<message>
<source>%1 MB</source>
<translation>%1 MB</translation>
</message>
<message>
<source>%1 GB</source>
<translation>%1 GB</translation>
</message>
<message>
<source>never</source>
<translation>soha</translation>
</message>
</context>
<context>
<name>ReceiveCoinsDialog</name>
<message>
<source>&Label:</source>
<translation>Címke:</translation>
</message>
<message>
<source>Clear</source>
<translation>Törlés</translation>
</message>
<message>
<source>Show</source>
<translation>Mutat</translation>
</message>
<message>
<source>Remove</source>
<translation>Eltávolítás</translation>
</message>
<message>
<source>Copy label</source>
<translation>Címke másolása</translation>
</message>
<message>
<source>Copy message</source>
<translation>Üzenet másolása</translation>
</message>
<message>
<source>Copy amount</source>
<translation>Összeg másolása</translation>
</message>
</context>
<context>
<name>ReceiveRequestDialog</name>
<message>
<source>QR Code</source>
<translation>QR kód</translation>
</message>
<message>
<source>Copy &URI</source>
<translation>&URI másolása</translation>
</message>
<message>
<source>Copy &Address</source>
<translation>&Cím másolása</translation>
</message>
<message>
<source>&Save Image...</source>
<translation>&Kép mentése</translation>
</message>
<message>
<source>URI</source>
<translation>URI:</translation>
</message>
<message>
<source>Address</source>
<translation>Cím</translation>
</message>
<message>
<source>Amount</source>
<translation>Összeg</translation>
</message>
<message>
<source>Label</source>
<translation>Címke</translation>
</message>
<message>
<source>Message</source>
<translation>Üzenet</translation>
</message>
<message>
<source>Resulting URI too long, try to reduce the text for label / message.</source>
<translation>A keletkezett URI túl hosszú, próbálja meg csökkenteni a cimkeszöveg / üzenet méretét.</translation>
</message>
<message>
<source>Error encoding URI into QR Code.</source>
<translation>Hiba lépett fel az URI QR kóddá alakításakor</translation>
</message>
</context>
<context>
<name>RecentRequestsTableModel</name>
<message>
<source>Date</source>
<translation>Dátum</translation>
</message>
<message>
<source>Label</source>
<translation>Címke</translation>
</message>
<message>
<source>Message</source>
<translation>Üzenet</translation>
</message>
<message>
<source>Amount</source>
<translation>Összeg</translation>
</message>
<message>
<source>(no label)</source>
<translation>(nincs címke)</translation>
</message>
</context>
<context>
<name>SendCoinsDialog</name>
<message>
<source>Send Coins</source>
<translation>Érmék küldése</translation>
</message>
<message>
<source>Inputs...</source>
<translation>Bemenetek...</translation>
</message>
<message>
<source>Quantity:</source>
<translation>Mennyiség:</translation>
</message>
<message>
<source>Bytes:</source>
<translation>Bájtok:</translation>
</message>
<message>
<source>Amount:</source>
<translation>Összeg:</translation>
</message>
<message>
<source>Priority:</source>
<translation>Prioritás:</translation>
</message>
<message>
<source>Fee:</source>
<translation>Díjak:</translation>
</message>
<message>
<source>After Fee:</source>
<translation>Utólagos díj:</translation>
</message>
<message>
<source>Change:</source>
<translation>Visszajáró:</translation>
</message>
<message>
<source>Send to multiple recipients at once</source>
<translation>Küldés több címzettnek egyszerre</translation>
</message>
<message>
<source>Add &Recipient</source>
<translation>&Címzett hozzáadása</translation>
</message>
<message>
<source>Dust:</source>
<translation>Por-határ:</translation>
</message>
<message>
<source>Clear &All</source>
<translation>Mindent &töröl</translation>
</message>
<message>
<source>Balance:</source>
<translation>Egyenleg:</translation>
</message>
<message>
<source>Confirm the send action</source>
<translation>Küldés megerősítése</translation>
</message>
<message>
<source>S&end</source>
<translation>&Küldés</translation>
</message>
<message>
<source>Confirm send coins</source>
<translation>Küldés megerősítése</translation>
</message>
<message>
<source>Copy quantity</source>
<translation>Mennyiség másolása</translation>
</message>
<message>
<source>Copy amount</source>
<translation>Összeg másolása</translation>
</message>
<message>
<source>Copy fee</source>
<translation>Díj másolása</translation>
</message>
<message>
<source>Copy after fee</source>
<translation>Utólagos díj másolása</translation>
</message>
<message>
<source>Copy bytes</source>
<translation>Byte-ok másolása </translation>
</message>
<message>
<source>Copy priority</source>
<translation>Prioritás másolása</translation>
</message>
<message>
<source>Copy change</source>
<translation>Visszajáró másolása</translation>
</message>
<message>
<source>or</source>
<translation>vagy</translation>
</message>
<message>
<source>The recipient address is not valid, please recheck.</source>
<translation>A címzett címe érvénytelen, kérlek, ellenőrizd.</translation>
</message>
<message>
<source>The amount to pay must be larger than 0.</source>
<translation>A fizetendő összegnek nagyobbnak kell lennie 0-nál.</translation>
</message>
<message>
<source>The amount exceeds your balance.</source>
<translation>Nincs ennyi moneta az egyenlegeden.</translation>
</message>
<message>
<source>The total exceeds your balance when the %1 transaction fee is included.</source>
<translation>A küldeni kívánt összeg és a %1 tranzakciós díj együtt meghaladja az egyenlegeden rendelkezésedre álló összeget.</translation>
</message>
<message>
<source>Duplicate address found, can only send to each address once per send operation.</source>
<translation>Többször szerepel ugyanaz a cím. Egy küldési műveletben egy címre csak egyszer lehet küldeni.</translation>
</message>
<message>
<source>(no label)</source>
<translation>(nincs címke)</translation>
</message>
<message>
<source>Copy dust</source>
<translation>Visszajáró másolása</translation>
</message>
</context>
<context>
<name>SendCoinsEntry</name>
<message>
<source>A&mount:</source>
<translation>Összeg:</translation>
</message>
<message>
<source>Pay &To:</source>
<translation>Címzett:</translation>
</message>
<message>
<source>Enter a label for this address to add it to your address book</source>
<translation>Milyen címkével kerüljön be ez a cím a címtáradba?
</translation>
</message>
<message>
<source>&Label:</source>
<translation>Címke:</translation>
</message>
<message>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<source>Paste address from clipboard</source>
<translation>Cím beillesztése a vágólapról</translation>
</message>
<message>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<source>Message:</source>
<translation>Üzenet:</translation>
</message>
<message>
<source>Memo:</source>
<translation>Jegyzet:</translation>
</message>
</context>
<context>
<name>ShutdownWindow</name>
<message>
<source>Moneta Core is shutting down...</source>
<translation>A Moneta Core leáll...</translation>
</message>
</context>
<context>
<name>SignVerifyMessageDialog</name>
<message>
<source>Signatures - Sign / Verify a Message</source>
<translation>Aláírások - üzenet aláírása/ellenőrzése</translation>
</message>
<message>
<source>&Sign Message</source>
<translation>Üzenet aláírása...</translation>
</message>
<message>
<source>You can sign messages with your addresses to prove you own them. Be careful not to sign anything vague, as phishing attacks may try to trick you into signing your identity over to them. Only sign fully-detailed statements you agree to.</source>
<translation>Aláírhat a címeivel üzeneteket, amivel bizonyíthatja, hogy a címek az önéi. Vigyázzon, hogy ne írjon alá semmi félreérthetőt, mivel a phising támadásokkal megpróbálhatják becsapni, hogy az azonosságát átírja másokra. Csak olyan részletes állításokat írjon alá, amivel egyetért.</translation>
</message>
<message>
<source>Alt+A</source>
<translation>Alt+A</translation>
</message>
<message>
<source>Paste address from clipboard</source>
<translation>Cím beillesztése a vágólapról</translation>
</message>
<message>
<source>Alt+P</source>
<translation>Alt+P</translation>
</message>
<message>
<source>Enter the message you want to sign here</source>
<translation>Ide írja az aláírandó üzenetet</translation>
</message>
<message>
<source>Signature</source>
<translation>Aláírás</translation>
</message>
<message>
<source>Copy the current signature to the system clipboard</source>
<translation>A jelenleg kiválasztott aláírás másolása a rendszer-vágólapra</translation>
</message>
<message>
<source>Sign the message to prove you own this Moneta address</source>
<translation>Üzenet </translation>
</message>
<message>
<source>Sign &Message</source>
<translation>Üzenet &aláírása</translation>
</message>
<message>
<source>Clear &All</source>
<translation>Mindent &töröl</translation>
</message>
<message>
<source>&Verify Message</source>
<translation>Üzenet ellenőrzése</translation>
</message>
<message>
<source>Enter the signing address, message (ensure you copy line breaks, spaces, tabs, etc. exactly) and signature below to verify the message. Be careful not to read more into the signature than what is in the signed message itself, to avoid being tricked by a man-in-the-middle attack.</source>
<translation>Írja be az aláírás címét, az üzenetet (ügyelve arra, hogy az új-sor, szóköz, tab, stb. karaktereket is pontosan) és az aláírást az üzenet ellenőrzéséhez. Ügyeljen arra, ne gondoljon többet az aláírásról, mint amennyi az aláírt szövegben ténylegesen áll, hogy elkerülje a köztes-ember (man-in-the-middle) támadást.</translation>
</message>
<message>
<source>The entered address is invalid.</source>
<translation>A megadott cím nem érvényes.</translation>
</message>
<message>
<source>Please check the address and try again.</source>
<translation>Ellenőrizze a címet és próbálja meg újra.</translation>
</message>
<message>
<source>Private key for the entered address is not available.</source>
<translation>A megadott cím privát kulcsa nem található.</translation>
</message>
<message>
<source>Message signing failed.</source>
<translation>Üzenet aláírása nem sikerült.</translation>
</message>
<message>
<source>Message signed.</source>
<translation>Üzenet aláírva.</translation>
</message>
<message>
<source>The signature could not be decoded.</source>
<translation>Az aláírást nem sikerült dekódolni.</translation>
</message>
<message>
<source>Please check the signature and try again.</source>
<translation>Ellenőrizd az aláírást és próbáld újra.</translation>
</message>
<message>
<source>Message verification failed.</source>
<translation>Az üzenet ellenőrzése nem sikerült.</translation>
</message>
<message>
<source>Message verified.</source>
<translation>Üzenet ellenőrizve.</translation>
</message>
</context>
<context>
<name>SplashScreen</name>
<message>
<source>Moneta Core</source>
<translation>Moneta Core</translation>
</message>
<message>
<source>The Moneta Core developers</source>
<translation>A Moneta fejlesztői</translation>
</message>
<message>
<source>[testnet]</source>
<translation>[teszthálózat]</translation>
</message>
</context>
<context>
<name>TrafficGraphWidget</name>
<message>
<source>KB/s</source>
<translation>KB/s</translation>
</message>
</context>
<context>
<name>TransactionDesc</name>
<message>
<source>Open until %1</source>
<translation>Megnyitva %1-ig</translation>
</message>
<message>
<source>%1/unconfirmed</source>
<translation>%1/megerősítetlen</translation>
</message>
<message>
<source>%1 confirmations</source>
<translation>%1 megerősítés</translation>
</message>
<message>
<source>Status</source>
<translation>Állapot</translation>
</message>
<message>
<source>Date</source>
<translation>Dátum</translation>
</message>
<message>
<source>Source</source>
<translation>Forrás</translation>
</message>
<message>
<source>Generated</source>
<translation>Legenerálva</translation>
</message>
<message>
<source>From</source>
<translation>Űrlap</translation>
</message>
<message>
<source>To</source>
<translation>Címzett</translation>
</message>
<message>
<source>own address</source>
<translation>saját cím</translation>
</message>
<message>
<source>label</source>
<translation>címke</translation>
</message>
<message>
<source>Credit</source>
<translation>Jóváírás</translation>
</message>
<message numerus="yes">
<source>matures in %n more block(s)</source>
<translation><numerusform>beérik %n blokk múlva</numerusform><numerusform>beérik %n blokk múlva</numerusform></translation>
</message>
<message>
<source>not accepted</source>
<translation>elutasítva</translation>
</message>
<message>
<source>Debit</source>
<translation>Terhelés</translation>
</message>
<message>
<source>Transaction fee</source>
<translation>Tranzakciós díj</translation>
</message>
<message>
<source>Net amount</source>
<translation>Nettó összeg</translation>
</message>
<message>
<source>Message</source>
<translation>Üzenet</translation>
</message>
<message>
<source>Comment</source>
<translation>Megjegyzés</translation>
</message>
<message>
<source>Transaction ID</source>
<translation>Tranzakcióazonosító</translation>
</message>
<message>
<source>Debug information</source>
<translation>Debug információ</translation>
</message>
<message>
<source>Transaction</source>
<translation>Tranzakció</translation>
</message>
<message>
<source>Inputs</source>
<translation>Bemenetek</translation>
</message>
<message>
<source>Amount</source>
<translation>Összeg</translation>
</message>
<message>
<source>true</source>
<translation>igaz</translation>
</message>
<message>
<source>false</source>
<translation>hamis</translation>
</message>
<message>
<source>, has not been successfully broadcast yet</source>
<translation>, még nem sikerült elküldeni.</translation>
</message>
<message numerus="yes">
<source>Open for %n more block(s)</source>
<translation><numerusform>%n további blokkra megnyitva</numerusform><numerusform>%n további blokkra megnyitva</numerusform></translation>
</message>
<message>
<source>unknown</source>
<translation>ismeretlen</translation>
</message>
</context>
<context>
<name>TransactionDescDialog</name>
<message>
<source>Transaction details</source>
<translation>Tranzakció részletei</translation>
</message>
<message>
<source>This pane shows a detailed description of the transaction</source>
<translation>Ez a mező a tranzakció részleteit mutatja</translation>
</message>
</context>
<context>
<name>TransactionTableModel</name>
<message>
<source>Date</source>
<translation>Dátum</translation>
</message>
<message>
<source>Type</source>
<translation>Típus</translation>
</message>
<message>
<source>Address</source>
<translation>Cím</translation>
</message>
<message numerus="yes">
<source>Open for %n more block(s)</source>
<translation><numerusform>%n további blokkra megnyitva</numerusform><numerusform>%n további blokkra megnyitva</numerusform></translation>
</message>
<message>
<source>Open until %1</source>
<translation>%1-ig megnyitva</translation>
</message>
<message>
<source>Confirmed (%1 confirmations)</source>
<translation>Megerősítve (%1 megerősítés)</translation>
</message>
<message>
<source>This block was not received by any other nodes and will probably not be accepted!</source>
<translation>Ezt a blokkot egyetlen másik csomópont sem kapta meg, így valószínűleg nem lesz elfogadva!</translation>
</message>
<message>
<source>Generated but not accepted</source>
<translation>Legenerálva, de még el nem fogadva.</translation>
</message>
<message>
<source>Offline</source>
<translation>Offline</translation>
</message>
<message>
<source>Received with</source>
<translation>Erre a címre</translation>
</message>
<message>
<source>Received from</source>
<translation>Erről az</translation>
</message>
<message>
<source>Sent to</source>
<translation>Erre a címre</translation>
</message>
<message>
<source>Payment to yourself</source>
<translation>Magadnak kifizetve</translation>
</message>
<message>
<source>Mined</source>
<translation>Kibányászva</translation>
</message>
<message>
<source>(n/a)</source>
<translation>(nincs)</translation>
</message>
<message>
<source>Transaction status. Hover over this field to show number of confirmations.</source>
<translation>Tranzakció állapota. Húzd ide a kurzort, hogy lásd a megerősítések számát.</translation>
</message>
<message>
<source>Date and time that the transaction was received.</source>
<translation>Tranzakció fogadásának dátuma és időpontja.</translation>
</message>
<message>
<source>Type of transaction.</source>
<translation>Tranzakció típusa.</translation>
</message>
<message>
<source>Destination address of transaction.</source>
<translation>A tranzakció címzettjének címe.</translation>
</message>
<message>
<source>Amount removed from or added to balance.</source>
<translation>Az egyenleghez jóváírt vagy ráterhelt összeg.</translation>
</message>
</context>
<context>
<name>TransactionView</name>
<message>
<source>All</source>
<translation>Mind</translation>
</message>
<message>
<source>Today</source>
<translation>Mai</translation>
</message>
<message>
<source>This week</source>
<translation>Ezen a héten</translation>
</message>
<message>
<source>This month</source>
<translation>Ebben a hónapban</translation>
</message>
<message>
<source>Last month</source>
<translation>Múlt hónapban</translation>
</message>
<message>
<source>This year</source>
<translation>Ebben az évben</translation>
</message>
<message>
<source>Range...</source>
<translation>Tartomány ...</translation>
</message>
<message>
<source>Received with</source>
<translation>Erre a címre</translation>
</message>
<message>
<source>Sent to</source>
<translation>Erre a címre</translation>
</message>
<message>
<source>To yourself</source>
<translation>Magadnak</translation>
</message>
<message>
<source>Mined</source>
<translation>Kibányászva</translation>
</message>
<message>
<source>Other</source>
<translation>Más</translation>
</message>
<message>
<source>Enter address or label to search</source>
<translation>Írd be a keresendő címet vagy címkét</translation>
</message>
<message>
<source>Min amount</source>
<translation>Minimális összeg</translation>
</message>
<message>
<source>Copy address</source>
<translation>Cím másolása</translation>
</message>
<message>
<source>Copy label</source>
<translation>Címke másolása</translation>
</message>
<message>
<source>Copy amount</source>
<translation>Összeg másolása</translation>
</message>
<message>
<source>Copy transaction ID</source>
<translation>Tranzakcióazonosító másolása</translation>
</message>
<message>
<source>Edit label</source>
<translation>Címke szerkesztése</translation>
</message>
<message>
<source>Show transaction details</source>
<translation>Tranzakciós részletek megjelenítése</translation>
</message>
<message>
<source>Exporting Failed</source>
<translation>Az exportálás sikertelen volt</translation>
</message>
<message>
<source>Comma separated file (*.csv)</source>
<translation>Vesszővel elválasztott fájl (*.csv)</translation>
</message>
<message>
<source>Confirmed</source>
<translation>Megerősítve</translation>
</message>
<message>
<source>Date</source>
<translation>Dátum</translation>
</message>
<message>
<source>Type</source>
<translation>Típus</translation>
</message>
<message>
<source>Label</source>
<translation>Címke</translation>
</message>
<message>
<source>Address</source>
<translation>Cím</translation>
</message>
<message>
<source>ID</source>
<translation>Azonosító</translation>
</message>
<message>
<source>Range:</source>
<translation>Tartomány:</translation>
</message>
<message>
<source>to</source>
<translation>meddig</translation>
</message>
</context>
<context>
<name>UnitDisplayStatusBarControl</name>
</context>
<context>
<name>WalletFrame</name>
</context>
<context>
<name>WalletModel</name>
<message>
<source>Send Coins</source>
<translation>Érmék küldése</translation>
</message>
</context>
<context>
<name>WalletView</name>
<message>
<source>&Export</source>
<translation>&Exportálás...</translation>
</message>
<message>
<source>Export the data in the current tab to a file</source>
<translation>Jelenlegi nézet exportálása fájlba</translation>
</message>
<message>
<source>Backup Wallet</source>
<translation>Biztonsági másolat készítése a Tárcáról</translation>
</message>
<message>
<source>Wallet Data (*.dat)</source>
<translation>Tárca fájl (*.dat)</translation>
</message>
<message>
<source>Backup Failed</source>
<translation>Biztonsági másolat készítése sikertelen</translation>
</message>
<message>
<source>Backup Successful</source>
<translation>Sikeres biztonsági mentés</translation>
</message>
</context>
<context>
<name>moneta-core</name>
<message>
<source>Options:</source>
<translation>Opciók
</translation>
</message>
<message>
<source>Specify data directory</source>
<translation>Adatkönyvtár
</translation>
</message>
<message>
<source>Connect to a node to retrieve peer addresses, and disconnect</source>
<translation>Kapcsolódás egy csomóponthoz a peerek címeinek megszerzése miatt, majd szétkapcsolás</translation>
</message>
<message>
<source>Specify your own public address</source>
<translation>Adja meg az Ön saját nyilvános címét</translation>
</message>
<message>
<source>Accept command line and JSON-RPC commands</source>
<translation>Parancssoros és JSON-RPC parancsok elfogadása
</translation>
</message>
<message>
<source>Run in the background as a daemon and accept commands</source>
<translation>Háttérben futtatás daemonként és parancsok elfogadása
</translation>
</message>
<message>
<source>Use the test network</source>
<translation>Teszthálózat használata
</translation>
</message>
<message>
<source>Accept connections from outside (default: 1 if no -proxy or -connect)</source>
<translation>Kívülről érkező kapcsolatok elfogadása (alapértelmezett: 1, ha nem használt a -proxy vagy a -connect)</translation>
</message>
<message>
<source>Execute command when a wallet transaction changes (%s in cmd is replaced by TxID)</source>
<translation>Parancs, amit akkor hajt végre, amikor egy tárca-tranzakció megváltozik (%s a parancsban lecserélődik a blokk TxID-re)</translation>
</message>
<message>
<source>Warning: -paytxfee is set very high! This is the transaction fee you will pay if you send a transaction.</source>
<translation>Figyelem: a -paytxfee nagyon magas. Ennyi tranzakciós díjat fogsz fizetni, ha elküldöd a tranzakciót.</translation>
</message>
<message>
<source>Connect only to the specified node(s)</source>
<translation>Csatlakozás csak a megadott csomóponthoz</translation>
</message>
<message>
<source>Corrupted block database detected</source>
<translation>Sérült blokk-adatbázis észlelve</translation>
</message>
<message>
<source>Discover own IP address (default: 1 when listening and no -externalip)</source>
<translation>Saját IP-cím felfedezése (alapértelmezett: 1, amikor figyel és nem használt a -externalip)</translation>
</message>
<message>
<source>Do you want to rebuild the block database now?</source>
<translation>Újra akarod építeni a blokk adatbázist most?</translation>
</message>
<message>
<source>Error initializing block database</source>
<translation>A blokkadatbázis inicializálása nem sikerült</translation>
</message>
<message>
<source>Error initializing wallet database environment %s!</source>
<translation>A tárca-adatbázis inicializálása nem sikerült: %s!</translation>
</message>
<message>
<source>Error loading block database</source>
<translation>Hiba a blokk adatbázis betöltése közben.</translation>
</message>
<message>
<source>Error opening block database</source>
<translation>Hiba a blokk adatbázis megnyitása közben.</translation>
</message>
<message>
<source>Error: Disk space is low!</source>
<translation>Hiba: kevés a hely a lemezen!</translation>
</message>
<message>
<source>Failed to listen on any port. Use -listen=0 if you want this.</source>
<translation>Egyik hálózati porton sem sikerül hallgatni. Használja a -listen=0 kapcsolót, ha ezt szeretné.</translation>
</message>
<message>
<source>Importing...</source>
<translation>Importálás</translation>
</message>
<message>
<source>Incorrect or no genesis block found. Wrong datadir for network?</source>
<translation>Helytelen vagy nemlétező genézis blokk. Helytelen hálózati adatkönyvtár?</translation>
</message>
<message>
<source>Not enough file descriptors available.</source>
<translation>Nincs elég fájlleíró. </translation>
</message>
<message>
<source>Rebuild block chain index from current blk000??.dat files</source>
<translation>Blokklánc index újraalkotása az alábbi blk000??.dat fájlokból</translation>
</message>
<message>
<source>Verifying blocks...</source>
<translation>Blokkok ellenőrzése...</translation>
</message>
<message>
<source>Verifying wallet...</source>
<translation>Tárca ellenőrzése...</translation>
</message>
<message>
<source>You need to rebuild the database using -reindex to change -txindex</source>
<translation>Az adatbázist újra kell építeni -reindex használatával (módosítás -tindex).</translation>
</message>
<message>
<source>Information</source>
<translation>Információ</translation>
</message>
<message>
<source>Invalid amount for -minrelaytxfee=<amount>: '%s'</source>
<translation>Érvénytelen -minrelaytxfee=<amount>: '%s' összeg</translation>
</message>
<message>
<source>Invalid amount for -mintxfee=<amount>: '%s'</source>
<translation>Érvénytelen -mintxfee=<amount>: '%s' összeg</translation>
</message>
<message>
<source>Send trace/debug info to console instead of debug.log file</source>
<translation>trace/debug információ küldése a konzolra a debog.log fájl helyett</translation>
</message>
<message>
<source>Signing transaction failed</source>
<translation>Tranzakció aláírása sikertelen</translation>
</message>
<message>
<source>This is experimental software.</source>
<translation>Ez egy kísérleti szoftver.</translation>
</message>
<message>
<source>Transaction amount too small</source>
<translation>Tranzakció összege túl alacsony</translation>
</message>
<message>
<source>Transaction amounts must be positive</source>
<translation>Tranzakció összege pozitív kell legyen</translation>
</message>
<message>
<source>Transaction too large</source>
<translation>Túl nagy tranzakció</translation>
</message>
<message>
<source>Use UPnP to map the listening port (default: 1 when listening)</source>
<translation>UPnP-használat engedélyezése a figyelő port feltérképezésénél (default: 1 when listening)</translation>
</message>
<message>
<source>Username for JSON-RPC connections</source>
<translation>Felhasználói név JSON-RPC csatlakozásokhoz
</translation>
</message>
<message>
<source>Warning</source>
<translation>Figyelem</translation>
</message>
<message>
<source>Password for JSON-RPC connections</source>
<translation>Jelszó JSON-RPC csatlakozásokhoz
</translation>
</message>
<message>
<source>Execute command when the best block changes (%s in cmd is replaced by block hash)</source>
<translation>Parancs, amit akkor hajt végre, amikor a legjobb blokk megváltozik (%s a cmd-ban lecserélődik a blokk hash-re)</translation>
</message>
<message>
<source>Upgrade wallet to latest format</source>
<translation>A Tárca frissítése a legfrissebb formátumra</translation>
</message>
<message>
<source>Rescan the block chain for missing wallet transactions</source>
<translation>Blokklánc újraszkennelése hiányzó tárca-tranzakciók után
</translation>
</message>
<message>
<source>Use OpenSSL (https) for JSON-RPC connections</source>
<translation>OpenSSL (https) használata JSON-RPC csatalkozásokhoz
</translation>
</message>
<message>
<source>This help message</source>
<translation>Ez a súgó-üzenet
</translation>
</message>
<message>
<source>Allow DNS lookups for -addnode, -seednode and -connect</source>
<translation>DNS-kikeresés engedélyezése az addnode-nál és a connect-nél</translation>
</message>
<message>
<source>Loading addresses...</source>
<translation>Címek betöltése...</translation>
</message>
<message>
<source>Error loading wallet.dat: Wallet corrupted</source>
<translation>Hiba a wallet.dat betöltése közben: meghibásodott tárca</translation>
</message>
<message>
<source>Error loading wallet.dat</source>
<translation>Hiba az wallet.dat betöltése közben</translation>
</message>
<message>
<source>Invalid -proxy address: '%s'</source>
<translation>Érvénytelen -proxy cím: '%s'</translation>
</message>
<message>
<source>Unknown network specified in -onlynet: '%s'</source>
<translation>Ismeretlen hálózat lett megadva -onlynet: '%s'</translation>
</message>
<message>
<source>Cannot resolve -bind address: '%s'</source>
<translation>Csatlakozási cím (-bind address) feloldása nem sikerült: '%s'</translation>
</message>
<message>
<source>Cannot resolve -externalip address: '%s'</source>
<translation>Külső cím (-externalip address) feloldása nem sikerült: '%s'</translation>
</message>
<message>
<source>Invalid amount for -paytxfee=<amount>: '%s'</source>
<translation>Étvénytelen -paytxfee=<összeg> összeg: '%s'</translation>
</message>
<message>
<source>Insufficient funds</source>
<translation>Nincs elég monetaod.</translation>
</message>
<message>
<source>Loading block index...</source>
<translation>Blokkindex betöltése...</translation>
</message>
<message>
<source>Add a node to connect to and attempt to keep the connection open</source>
<translation>Elérendő csomópont megadása and attempt to keep the connection open</translation>
</message>
<message>
<source>Loading wallet...</source>
<translation>Tárca betöltése...</translation>
</message>
<message>
<source>Cannot downgrade wallet</source>
<translation>Nem sikerült a Tárca visszaállítása a korábbi verzióra</translation>
</message>
<message>
<source>Cannot write default address</source>
<translation>Nem sikerült az alapértelmezett címet írni.</translation>
</message>
<message>
<source>Rescanning...</source>
<translation>Újraszkennelés...</translation>
</message>
<message>
<source>Done loading</source>
<translation>Betöltés befejezve.</translation>
</message>
<message>
<source>Error</source>
<translation>Hiba</translation>
</message>
</context>
</TS> | mit |
steve600/JSON-RPC.NET | TestServer_Console/Properties/AssemblyInfo.cs | 1412 | using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("TestServer_Console")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("TestServer_Console")]
[assembly: AssemblyCopyright("Copyright © 2012")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("5e7696bc-52cc-48f8-a575-40b17165ee20")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| mit |
MadushikaPerera/Coupley | public/js/components/chat/ChatPrevious.react.js | 3645 | import React from 'react';
import List from 'material-ui/lib/lists/list';
import ListItem from 'material-ui/lib/lists/list-item';
import Divider from 'material-ui/lib/divider';
import Avatar from 'material-ui/lib/avatar';
import Colors from 'material-ui/lib/styles/colors';
import IconButton from 'material-ui/lib/icon-button';
import MoreVertIcon from 'material-ui/lib/svg-icons/navigation/more-vert';
import IconMenu from 'material-ui/lib/menus/icon-menu';
import MenuItem from 'material-ui/lib/menus/menu-item';
import ThreadActions from '../../actions/Thread/ThreadActions';
import ThreadStore from '../../stores/ThreadStore';
import FlatButton from 'material-ui/lib/flat-button';
import Dialog from 'material-ui/lib/dialog';
import PaperExampleSimple from './Messages.react';
const iconButtonElement = (
<IconButton
touch={true}
tooltip="more"
tooltipPosition="bottom-left"
>
<MoreVertIcon color={Colors.grey400} />
</IconButton>
);
const ListStyle = {
width: 300,
};
const PreviousChat = React.createClass({
handleOpen: function () {
this.setState({ open: true });
},
handleClose: function () {
this.setState({ open: false });
},
getInitialState: function () {
return {
results:ThreadStore.getThreadMessage(),
open: false,
};
},
componentDidMount: function () {
ThreadStore.addChangeListener(this._onChange);
},
_onChange: function () {
this.setState({results:ThreadStore.getThreadMessage()});
},
deleteconvo:function () {
var user2 = this.props.thread_id;
let deleteM = {
user2:user2,
user1:localStorage.getItem('username'),
};
ThreadActions.deleteM(deleteM);
console.log('Done deleting!');
},
getMessage:function () {
let threadData = {
threadId: this.props.id,
};
ThreadActions.getMessage(threadData);
return this.state.results.map((result) => {
return (<Paper ExampleSimple key={result.thread_id} id={result.thread_id} firstname={result.firstname} message={result.message} created_at={result.created_at}/>);
});
},
render:function () {
const actions = [
<FlatButton
label="No"
secondary={true}
onTouchTap={this.handleClose}
/>,
<FlatButton
label="Yes"
primary={true}
keyboardFocused={true}
onTouchTap={this.deleteconvo}
/>,
];
return (
<List style={ListStyle}>
<ListItem leftAvatar={<Avatar src={'img/profilepics/'+this.props.username} /> }
rightIconButton={<IconMenu iconButtonElement={iconButtonElement}>
<MenuItem onTouchTap={this.handleOpen}>Delete</MenuItem>
</IconMenu>
}
onTouchTap={this.getMessage}
primaryText={this.props.firstname}
secondaryText={
<p>
<span style={ { color: Colors.darkBlack } }>{this.props.message}</span><br/>
{ this.props.created_at }
</p>
}
secondaryTextLines={2}/>
<Divider inset={false} />
<Dialog
title="Delete Conversation"
actions={actions}
modal={false}
open={this.state.open}
onRequestClose={this.handleClose}>
Are you sure you want to delete this conversation?.
</Dialog>
</List>
);
},
});
export default PreviousChat;
| mit |
SekulKamberov/Telerik-Academy | PHP Web Development/01. Creating an address book/01. Expenditure Monitoring System/functions.php | 1580 | <?php
# Съдържа колоните на таблицата, типовете разходи, продуктите и тяхната информация и общата сума
# Методи за четене съдържанието на файла и изчисляване на общата сума
$tableColumns = array("Name", "Price", "Type", "Date");
define("TYPE_INDEX", array_search("Type", $tableColumns));
define("PRICE_INDEX", array_search("Price", $tableColumns));
$types = array(0 => "Food", 1 => "Transport", 2 => "Clothing", 3 => "Medicament", 4 => "Other");
$products = array(); // Съдържа отделните продукти и тяхната информация (взема ги от файла)
$filterBy = -1; // Подразбиращата се стойност за показване на всички разходи
$totalSum = 0.0;
$deleteMode = FALSE;
ReadFileContent();
GetTotalSum($filterBy);
function ReadFileContent()
{
global $products;
$fileContent = file("list-records.txt");
foreach ($fileContent as $value)
{
$products[] = explode(" ~ ", $value);
}
}
function GetTotalSum($filter)
{
global $totalSum, $products;
$totalSum = 0.0;
foreach ($products as $value)
{
// TODO
if ($value[TYPE_INDEX] == (int)$filter || $filter == -1)
{
for ($i = 0; $i < count($value); $i++)
{
if ($i == PRICE_INDEX)
{
$totalSum += (float)$value[$i];
}
}
}
}
} | mit |
lizlove/sm_nyc | app/helpers/nyc_noise_helper.rb | 26 | module NycNoiseHelper
end
| mit |
Behat/SahiClient | src/Behat/SahiClient/Accessor/DivAccessor.php | 525 | <?php
/*
* This file is part of the Behat\SahiClient.
* (c) 2010 Konstantin Kudryashov <ever.zet@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Behat\SahiClient\Accessor;
/**
* Div Element Accessor.
*
* @author Konstantin Kudryashov <ever.zet@gmail.com>
*/
class DivAccessor extends AbstractDomAccessor
{
/**
* {@inheritdoc}
*/
public function getType()
{
return 'div';
}
}
| mit |
DorianCMore/Sylius | src/Sylius/Bundle/ThemeBundle/spec/Templating/Locator/TemplateFileLocatorSpec.php | 4022 | <?php
/*
* This file is part of the Sylius package.
*
* (c) Paweł Jędrzejewski
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace spec\Sylius\Bundle\ThemeBundle\Templating\Locator;
use PhpSpec\ObjectBehavior;
use Prophecy\Argument;
use Sylius\Bundle\ThemeBundle\Context\ThemeContextInterface;
use Sylius\Bundle\ThemeBundle\HierarchyProvider\ThemeHierarchyProviderInterface;
use Sylius\Bundle\ThemeBundle\Locator\ResourceNotFoundException;
use Sylius\Bundle\ThemeBundle\Model\ThemeInterface;
use Sylius\Bundle\ThemeBundle\Templating\Locator\TemplateFileLocator;
use Sylius\Bundle\ThemeBundle\Templating\Locator\TemplateLocatorInterface;
use Symfony\Component\Config\FileLocatorInterface;
use Symfony\Component\Templating\TemplateReferenceInterface;
/**
* @author Kamil Kokot <kamil@kokot.me>
*/
final class TemplateFileLocatorSpec extends ObjectBehavior
{
function let(
FileLocatorInterface $decoratedFileLocator,
ThemeContextInterface $themeContext,
ThemeHierarchyProviderInterface $themeHierarchyProvider,
TemplateLocatorInterface $templateLocator
) {
$this->beConstructedWith($decoratedFileLocator, $themeContext, $themeHierarchyProvider, $templateLocator);
}
function it_is_initializable()
{
$this->shouldHaveType(TemplateFileLocator::class);
}
function it_implements_file_locator_interface()
{
$this->shouldImplement(FileLocatorInterface::class);
}
function it_throws_an_exception_if_located_thing_is_not_an_instance_of_template_reference_interface()
{
$this->shouldThrow(\InvalidArgumentException::class)->during('locate', ['not an instance']);
}
function it_returns_first_possible_theme_resource(
ThemeContextInterface $themeContext,
ThemeHierarchyProviderInterface $themeHierarchyProvider,
TemplateLocatorInterface $templateLocator,
TemplateReferenceInterface $template,
ThemeInterface $firstTheme,
ThemeInterface $secondTheme
) {
$themeContext->getTheme()->willReturn($firstTheme);
$themeHierarchyProvider->getThemeHierarchy($firstTheme)->willReturn([$firstTheme, $secondTheme]);
$templateLocator->locateTemplate($template, $firstTheme)->willThrow(ResourceNotFoundException::class);
$templateLocator->locateTemplate($template, $secondTheme)->willReturn('/second/theme/template/path');
$this->locate($template)->shouldReturn('/second/theme/template/path');
}
function it_falls_back_to_decorated_template_locator_if_themed_tempaltes_can_not_be_found(
FileLocatorInterface $decoratedFileLocator,
ThemeContextInterface $themeContext,
ThemeHierarchyProviderInterface $themeHierarchyProvider,
TemplateLocatorInterface $templateLocator,
TemplateReferenceInterface $template,
ThemeInterface $theme
) {
$themeContext->getTheme()->willReturn($theme);
$themeHierarchyProvider->getThemeHierarchy($theme)->willReturn([$theme]);
$templateLocator->locateTemplate($template, $theme)->willThrow(ResourceNotFoundException::class);
$decoratedFileLocator->locate($template, Argument::cetera())->willReturn('/app/template/path');
$this->locate($template)->shouldReturn('/app/template/path');
}
function it_falls_back_to_decorated_template_locator_if_there_are_no_themes_active(
FileLocatorInterface $decoratedFileLocator,
ThemeContextInterface $themeContext,
ThemeHierarchyProviderInterface $themeHierarchyProvider,
TemplateReferenceInterface $template
) {
$themeContext->getTheme()->willReturn(null);
$themeHierarchyProvider->getThemeHierarchy(null)->willReturn([]);
$decoratedFileLocator->locate($template, Argument::cetera())->willReturn('/app/template/path');
$this->locate($template)->shouldReturn('/app/template/path');
}
}
| mit |
pkozlowski-opensource/angular | aio/content/examples/i18n/src/app/i18n-providers.ts | 1524 | // #docplaster
// #docregion without-missing-translation
import { TRANSLATIONS, TRANSLATIONS_FORMAT, LOCALE_ID, MissingTranslationStrategy } from '@angular/core';
import { CompilerConfig } from '@angular/compiler';
export function getTranslationProviders(): Promise<Object[]> {
// Get the locale id from the global
const locale = document['locale'] as string;
// return no providers if fail to get translation file for locale
const noProviders: Object[] = [];
// No locale or U.S. English: no translation providers
if (!locale || locale === 'en-US') {
return Promise.resolve(noProviders);
}
// Ex: 'locale/messages.es.xlf`
const translationFile = `./locale/messages.${locale}.xlf`;
// #docregion missing-translation
return getTranslationsWithSystemJs(translationFile)
.then( (translations: string ) => [
{ provide: TRANSLATIONS, useValue: translations },
{ provide: TRANSLATIONS_FORMAT, useValue: 'xlf' },
{ provide: LOCALE_ID, useValue: locale },
// #enddocregion without-missing-translation
{ provide: CompilerConfig, useValue: new CompilerConfig({ missingTranslation: MissingTranslationStrategy.Error }) }
// #docregion without-missing-translation
])
.catch(() => noProviders); // ignore if file not found
// #enddocregion missing-translation
}
declare var System: any;
function getTranslationsWithSystemJs(file: string) {
return System.import(file + '!text'); // relies on text plugin
}
// #enddocregion without-missing-translation
| mit |
ddo/crypto-js | enc-latin1.js | 198 | (function(e,r){"object"==typeof exports?module.exports=exports=r(require("./core")):"function"==typeof define&&define.amd?define(["./core"],r):r(e.CryptoJS)})(this,function(e){return e.enc.Latin1}); | mit |
mans0954/f-spot | src/Clients/FSpot/FSpot.Filters/WhiteListFilter.cs | 2100 | //
// WhiteListFilter.cs
//
// Author:
// Stephane Delcroix <stephane@delcroix.org>
// Stephen Shaw <sshaw@decriptor.com>
//
// Copyright (C) 2006-2007 Novell, Inc.
// Copyright (C) 2006-2007 Stephane Delcroix
//
// 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.
//
using System.Collections.Generic;
using System.IO;
namespace FSpot.Filters
{
public class WhiteListFilter : IFilter
{
readonly List<string> valid_extensions;
public WhiteListFilter (string [] valid_extensions)
{
this.valid_extensions = new List<string> ();
foreach (string extension in valid_extensions)
this.valid_extensions.Add (extension.ToLower ());
}
public bool Convert (FilterRequest req)
{
if (valid_extensions.Contains (Path.GetExtension (req.Current.LocalPath).ToLower ()))
return false;
// FIXME: Should we add the other jpeg extensions?
if (!valid_extensions.Contains (".jpg") &&
!valid_extensions.Contains (".jpeg"))
throw new System.NotImplementedException ("can only save jpeg :(");
return (new JpegFilter ()).Convert (req);
}
}
}
| mit |
oturpe/barcode-agent-client | plugins/com.phonegap.plugins.barcodescanner/plugin.xml.generate.php | 6999 | <?php
class PluginHelper {
public $basePath = 'src/android/LibraryProject/';
private function perror($msg)
{
file_put_contents('php://stderr', $msg, FILE_APPEND);
}
/**
* Get contents of an XML file.
*
* @param string $xmlFilePath The XML file path relative to $this->basePath.
* @param string $parent Parent element from which to get children.
* @param array $options
* <li>ident - ident chanracters.
* <li>ignorePattern - pattern that will be matched to XML.
* @return string
*/
public function getXml($xmlFilePath, $parent, $options=array())
{
if (!isset($options['indent']))
{
$options['indent'] = "";
}
$contents = "";
$filePath = $this->basePath . $xmlFilePath;
if (!file_exists($filePath))
{
$this->perror("File $filePath does not exist");
return $contents;
}
$xml = file_get_contents($this->basePath . $xmlFilePath);
$document = new SimpleXMLElement($xml);
$els = $document->xpath($parent);
if (!empty($els))
{
$rootNode = $els[0];
foreach ($rootNode->children() as $child)
{
$childContent = $child->asXML();
if (isset($options['ignorePattern']) && preg_match($options['ignorePattern'], $childContent))
{
$this->perror("\nignored $childContent");
continue;
}
$contents .= "\n" . $options['indent'] . $childContent;
}
$contents = ltrim ($contents) . "\n";
return $contents;
}
else
{
$this->perror("Path $parent not found in $xmlFilePath");
return $contents;
}
}
/**
* Generate source-file tags to copy all resources from given dir.
*
* @param type $dir Dir path relative to $this->basePath.
* @param array $options
* <li>ident - ident chanracters.
*/
public function sourceFiles($dir, $options=array())
{
//ob_end_clean();
if (!isset($options['indent']))
{
$options['indent'] = "";
}
$path = $this->basePath . $dir;
$it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path));
while($it->valid())
{
if (!$it->isDot())
{
$filename = strtr($it->key(), '\\', '/');
if (isset($options['ignorePattern']) && preg_match($options['ignorePattern'], $filename))
{
$this->perror("\nignored $filename");
$it->next();
continue;
}
$targetDir = preg_replace('#.+LibraryProject/(.+?)/[^/]+$#', '$1', $filename);
echo "\n{$options['indent']}<source-file src=\"$filename\" target-dir=\"$targetDir\"/>";
}
$it->next();
}
echo "\n";
//exit;
}
}
// init
$pluginHelper = new PluginHelper();
ob_start();
echo '<?xml version="1.0" encoding="UTF-8"?>';
?>
<plugin xmlns="http://www.phonegap.com/ns/plugins/1.0"
xmlns:android="http://schemas.android.com/apk/res/android"
id="com.phonegap.plugins.barcodescanner"
version="0.5.3">
<name>BarcodeScanner</name>
<description>Scans Barcodes.</description>
<engines>
<engine name="cordova" version=">=2.0.0" />
</engines>
<asset src="www/barcodescanner.js" target="barcodescanner.js" />
<!-- ios -->
<platform name="ios">
<plugins-plist key="BarcodeScanner" string="CDVBarcodeScanner" />
<!-- Cordova >= 2.3 -->
<config-file target="config.xml" parent="plugins">
<plugin name="BarcodeScanner" value="CDVBarcodeScanner"/>
</config-file>
<resource-file src="src/ios/scannerOverlay.xib" />
<header-file src="src/ios/zxing-all-in-one.h" />
<source-file src="src/ios/CDVBarcodeScanner.mm" />
<source-file src="src/ios/zxing-all-in-one.cpp" />
<framework src="libiconv.dylib" />
<framework src="AVFoundation.framework" />
<framework src="AssetsLibrary.framework" />
<framework src="CoreVideo.framework" />
</platform>
<!-- android -->
<platform name="android">
<source-file src="src/android/com/phonegap/plugins/barcodescanner/BarcodeScanner.java" target-dir="src/com/phonegap/plugins/barcodescanner" />
<!--
<source-file src="R.java" target-dir="src/com/google/zxing/client/android" />
-->
<config-file target="res/xml/plugins.xml" parent="/plugins">
<plugin name="BarcodeScanner" value="com.phonegap.plugins.barcodescanner.BarcodeScanner"/>
</config-file>
<config-file target="res/xml/config.xml" parent="plugins">
<plugin name="BarcodeScanner" value="com.phonegap.plugins.barcodescanner.BarcodeScanner"/>
</config-file>
<config-file target="AndroidManifest.xml" parent="/manifest/application">
<activity
android:name="com.google.zxing.client.android.CaptureActivity"
android:screenOrientation="landscape"
android:clearTaskOnLaunch="true"
android:configChanges="orientation|keyboardHidden"
android:theme="@android:style/Theme.NoTitleBar.Fullscreen"
android:windowSoftInputMode="stateAlwaysHidden"
android:exported="false">
<intent-filter>
<action android:name="com.phonegap.plugins.barcodescanner.SCAN"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</activity>
<activity android:name="com.google.zxing.client.android.encode.EncodeActivity" android:label="@string/share_name">
<intent-filter>
<action android:name="com.phonegap.plugins.barcodescanner.ENCODE"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</activity>
<activity android:name="com.google.zxing.client.android.HelpActivity" android:label="@string/share_name">
<intent-filter>
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</activity>
</config-file>
<config-file target="AndroidManifest.xml" parent="/manifest">
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.FLASHLIGHT" />
<!-- Not required to allow users to work around this -->
<uses-feature android:name="android.hardware.camera" android:required="false" />
</config-file>
<source-file src="src/android/com.google.zxing.client.android.captureactivity.jar" target-dir="libs"/>
<!--
LibraryProject/res/*.*
search: (src/android/LibraryProject/(.+?)/[^/]+)$
replace: <source-file src="$1" target-dir="$2"/>
-->
<?
$pluginHelper->sourceFiles("res", array('indent'=>"\t\t", 'ignorePattern' => '#values/strings.xml#'));
?>
<!-- plugman cannot merge - prepare manual merge -->
<config-file target="res/values/strings.xml" parent="/resources">
<?=$pluginHelper->getXml('res/values/strings.xml', "/resources", array('ignorePattern' => '/name="(app_name|menu_settings)"/', 'indent' => "\t\t\t"))?>
</config-file>
</platform>
</plugin>
<?php
$pluginText = ob_get_clean();
file_put_contents("plugin.xml", $pluginText);
?> | mit |
ndardenne/pymatgen | pymatgen/analysis/energy_models.py | 5624 | # coding: utf-8
# Copyright (c) Pymatgen Development Team.
# Distributed under the terms of the MIT License.
from __future__ import division, unicode_literals
"""
This module implements a EnergyModel abstract class and some basic
implementations. Basically, an EnergyModel is any model that returns an
"energy" for any given structure.
"""
__author__ = "Shyue Ping Ong"
__copyright__ = "Copyright 2012, The Materials Project"
__version__ = "0.1"
__maintainer__ = "Shyue Ping Ong"
__email__ = "shyuep@gmail.com"
__date__ = "11/19/13"
import abc
import six
from monty.json import MSONable
from pymatgen.analysis.ewald import EwaldSummation
from pymatgen.symmetry.analyzer import SpacegroupAnalyzer
class EnergyModel(six.with_metaclass(abc.ABCMeta, MSONable)):
"""
Abstract structure filter class.
"""
@abc.abstractmethod
def get_energy(self, structure):
"""
Returns a boolean for any structure. Structures that return true are
kept in the Transmuter object during filtering.
"""
return
@classmethod
def from_dict(cls, d):
return cls(**d['init_args'])
class EwaldElectrostaticModel(EnergyModel):
"""
Wrapper around EwaldSum to calculate the electrostatic energy.
"""
def __init__(self, real_space_cut=None, recip_space_cut=None,
eta=None, acc_factor=8.0):
"""
Initializes the model. Args have the same definitions as in
:class:`pymatgen.analysis.ewald.EwaldSummation`.
Args:
real_space_cut (float): Real space cutoff radius dictating how
many terms are used in the real space sum. Defaults to None,
which means determine automagically using the formula given
in gulp 3.1 documentation.
recip_space_cut (float): Reciprocal space cutoff radius.
Defaults to None, which means determine automagically using
the formula given in gulp 3.1 documentation.
eta (float): Screening parameter. Defaults to None, which means
determine automatically.
acc_factor (float): No. of significant figures each sum is
converged to.
"""
self.real_space_cut = real_space_cut
self.recip_space_cut = recip_space_cut
self.eta = eta
self.acc_factor = acc_factor
def get_energy(self, structure):
e = EwaldSummation(structure, real_space_cut=self.real_space_cut,
recip_space_cut=self.recip_space_cut,
eta=self.eta,
acc_factor=self.acc_factor)
return e.total_energy
def as_dict(self):
return {"version": __version__,
"@module": self.__class__.__module__,
"@class": self.__class__.__name__,
"init_args": {"real_space_cut": self.real_space_cut,
"recip_space_cut": self.recip_space_cut,
"eta": self.eta,
"acc_factor": self.acc_factor}}
class SymmetryModel(EnergyModel):
"""
Sets the energy to the -ve of the spacegroup number. Higher symmetry =>
lower "energy".
Args have same meaning as in
:class:`pymatgen.symmetry.finder.SpacegroupAnalyzer`.
Args:
symprec (float): Symmetry tolerance. Defaults to 0.1.
angle_tolerance (float): Tolerance for angles. Defaults to 5 degrees.
"""
def __init__(self, symprec=0.1, angle_tolerance=5):
self.symprec = symprec
self.angle_tolerance = angle_tolerance
def get_energy(self, structure):
f = SpacegroupAnalyzer(structure, symprec=self.symprec,
angle_tolerance=self.angle_tolerance)
return -f.get_space_group_number()
def as_dict(self):
return {"version": __version__,
"@module": self.__class__.__module__,
"@class": self.__class__.__name__,
"init_args": {"symprec": self.symprec,
"angle_tolerance": self.angle_tolerance}}
class IsingModel(EnergyModel):
"""
A very simple Ising model, with r^2 decay.
Args:
j (float): The interaction parameter. E = J * spin1 * spin2.
radius (float): max_radius for the interaction.
"""
def __init__(self, j, max_radius):
self.j = j
self.max_radius = max_radius
def get_energy(self, structure):
all_nn = structure.get_all_neighbors(r=self.max_radius)
energy = 0
for i, nn in enumerate(all_nn):
s1 = getattr(structure[i].specie, "spin", 0)
for site, dist in nn:
energy += self.j * s1 * getattr(site.specie, "spin",
0) / (dist ** 2)
return energy
def as_dict(self):
return {"version": __version__,
"@module": self.__class__.__module__,
"@class": self.__class__.__name__,
"init_args": {"j": self.j, "max_radius": self.max_radius}}
class NsitesModel(EnergyModel):
"""
Sets the energy to the number of sites. More sites => higher "energy".
Used to rank structures from smallest number of sites to largest number
of sites after enumeration.
"""
def get_energy(self, structure):
return len(structure)
def as_dict(self):
return {"version": __version__,
"@module": self.__class__.__module__,
"@class": self.__class__.__name__,
"init_args": {}}
| mit |
amirlionor/admin | vendor/sonata-project/block-bundle/Tests/Block/BlockContextManagerTest.php | 5416 | <?php
/*
* This file is part of the Sonata Project package.
*
* (c) Thomas Rabaix <thomas.rabaix@sonata-project.org>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Sonata\BlockBundle\Tests\Block;
use Doctrine\Common\Util\ClassUtils;
use Sonata\BlockBundle\Block\BlockContextManager;
class BlockContextManagerTest extends \PHPUnit_Framework_TestCase
{
public function testGetWithValidData()
{
$service = $this->getMock('Sonata\BlockBundle\Block\AbstractBlockService');
$service->expects($this->once())->method('configureSettings');
$blockLoader = $this->getMock('Sonata\BlockBundle\Block\BlockLoaderInterface');
$serviceManager = $this->getMock('Sonata\BlockBundle\Block\BlockServiceManagerInterface');
$serviceManager->expects($this->once())->method('get')->will($this->returnValue($service));
$block = $this->getMock('Sonata\BlockBundle\Model\BlockInterface');
$block->expects($this->once())->method('getSettings')->will($this->returnValue(array()));
$manager = new BlockContextManager($blockLoader, $serviceManager);
$blockContext = $manager->get($block);
$this->assertInstanceOf('Sonata\BlockBundle\Block\BlockContextInterface', $blockContext);
$this->assertEquals(array(
'use_cache' => true,
'extra_cache_keys' => array(),
'attr' => array(),
'template' => false,
'ttl' => 0,
), $blockContext->getSettings());
}
public function testGetWithSettings()
{
$service = $this->getMock('Sonata\BlockBundle\Block\AbstractBlockService');
$service->expects($this->once())->method('configureSettings');
$blockLoader = $this->getMock('Sonata\BlockBundle\Block\BlockLoaderInterface');
$serviceManager = $this->getMock('Sonata\BlockBundle\Block\BlockServiceManagerInterface');
$serviceManager->expects($this->once())->method('get')->will($this->returnValue($service));
$block = $this->getMock('Sonata\BlockBundle\Model\BlockInterface');
$block->expects($this->once())->method('getSettings')->will($this->returnValue(array()));
$blocksCache = array(
'by_class' => array(ClassUtils::getClass($block) => 'my_cache.service.id'),
);
$manager = new BlockContextManager($blockLoader, $serviceManager, $blocksCache);
$settings = array('ttl' => 1, 'template' => 'custom.html.twig');
$blockContext = $manager->get($block, $settings);
$this->assertInstanceOf('Sonata\BlockBundle\Block\BlockContextInterface', $blockContext);
$this->assertEquals(array(
'use_cache' => true,
'extra_cache_keys' => array(
BlockContextManager::CACHE_KEY => array(
'template' => 'custom.html.twig',
),
),
'attr' => array(),
'template' => 'custom.html.twig',
'ttl' => 1,
), $blockContext->getSettings());
}
public function testWithInvalidSettings()
{
$logger = $this->getMock('Psr\Log\LoggerInterface');
$logger->expects($this->exactly(1))->method('error');
$service = $this->getMock('Sonata\BlockBundle\Block\AbstractBlockService');
$service->expects($this->exactly(2))->method('configureSettings');
$blockLoader = $this->getMock('Sonata\BlockBundle\Block\BlockLoaderInterface');
$serviceManager = $this->getMock('Sonata\BlockBundle\Block\BlockServiceManagerInterface');
$serviceManager->expects($this->exactly(2))->method('get')->will($this->returnValue($service));
$block = $this->getMock('Sonata\BlockBundle\Model\BlockInterface');
$block->expects($this->once())->method('getSettings')->will($this->returnValue(array(
'template' => array(),
)));
$manager = new BlockContextManager($blockLoader, $serviceManager, array(), $logger);
$blockContext = $manager->get($block);
$this->assertInstanceOf('Sonata\BlockBundle\Block\BlockContextInterface', $blockContext);
}
// @TODO: Think if the BlockContextManager should throw an exception if the resolver throw an exception
// /**
// * @expectedException \Sonata\BlockBundle\Exception\BlockOptionsException
// */
// public function testGetWithException()
// {
// $service = $this->getMock('Sonata\BlockBundle\Block\BlockServiceInterface');
// $service->expects($this->exactly(2))->method('setDefaultSettings');
//
// $blockLoader = $this->getMock('Sonata\BlockBundle\Block\BlockLoaderInterface');
//
// $serviceManager = $this->getMock('Sonata\BlockBundle\Block\BlockServiceManagerInterface');
// $serviceManager->expects($this->exactly(2))->method('get')->will($this->returnValue($service));
//
// $block = $this->getMock('Sonata\BlockBundle\Model\BlockInterface');
// $block->expects($this->once())->method('getSettings')->will($this->returnValue(array(
// 'template' => array()
// )));
//
// $manager = new BlockContextManager($blockLoader, $serviceManager);
//
// $blockContext = $manager->get($block);
//
// $this->assertInstanceOf('Sonata\BlockBundle\Block\BlockContextInterface', $blockContext);
// }
}
| mit |
redwoodfavorite/engine | renderers/test/UIManager.js | 5409 | /**
* The MIT License (MIT)
*
* Copyright (c) 2015 Famous Industries Inc.
*
* 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.
*/
'use strict';
var test = require('tape');
var UIManager = require('../UIManager');
function noop() {}
test('UIManager', function(t) {
t.test('constructor', function(t) {
t.plan(3);
t.equal(typeof UIManager, 'function', 'UIManager should be a function');
var registeredUpdateables = [];
var uiManager = new UIManager({
onmessage: null,
onerror: null,
postMessage: noop
}, {
receiveCommands: noop,
drawCommands: noop,
clearCommands: noop
}, {
update: function (updateable) {
registeredUpdateables.push(updateable);
}
});
t.equal(
registeredUpdateables.length,
1,
'uimanager should register exactly one updateable on the engine'
);
t.equal(
registeredUpdateables[0],
uiManager,
'uiManager should register itself as an updateable on ' +
'the passed in engine'
);
});
t.test('update method', function(t) {
var actions = [];
var thread = {
postMessage: function(message) {
actions.push(['postMessage', message]);
}
};
var compositor = {
drawCommands: function() {
actions.push(['drawCommands']);
},
clearCommands: function() {
actions.push(['clearCommands']);
}
};
var uiManager = new UIManager(thread, compositor, {
update: noop
});
t.equal(typeof uiManager.update, 'function', 'uiManager.update should be a function');
uiManager.update(123);
uiManager.update(124);
t.deepEqual(actions, [
['postMessage', ['FRAME', 123]],
['drawCommands'],
['postMessage', undefined],
['clearCommands'],
['postMessage', ['FRAME', 124]],
['drawCommands'],
['postMessage', undefined],
['clearCommands']
]);
t.end();
});
t.test('getCompositor/ getThread method', function(t) {
var thread = {};
var compositor = {};
var engine = {update: noop};
var uiManager = new UIManager(thread, compositor, engine);
t.equal(typeof uiManager.getThread, 'function', 'uiManager.getThread should be a function');
t.equal(typeof uiManager.getCompositor, 'function', 'uiManager.getCompositor should be a function');
t.equal(uiManager.getThread(), thread, 'uiManager.getThread should return used thread');
t.equal(uiManager.getCompositor(), compositor, 'uiManager.getCompositor should return used thread');
t.end();
});
t.test('integration', function(t) {
t.plan(8);
var commands = ['SOME', 'COMMANDS'];
var postedMessages = [];
var clearedCommands = false;
var thread = {
onmessage: null,
onerror: null,
postMessage: function(receivedMessage) {
postedMessages.push(receivedMessage);
}
};
var compositor = {
receiveCommands: function(receivedCommands) {
t.equal(commands, receivedCommands);
},
drawCommands: function() {
return ['DRAW', 'COMMANDS'];
},
clearCommands: function() {
clearedCommands = true;
}
};
var engine = {
update: noop
};
var uiManager = new UIManager(thread, compositor, engine);
t.equal(typeof thread.onmessage, 'function', 'uiManager should decorate thread#onmessage');
t.equal(typeof thread.onerror, 'function', 'uiManager should decorate thread#onerror');
thread.onmessage(commands);
thread.onmessage({
data: commands
});
t.equal(clearedCommands, false);
t.deepEqual(postedMessages, []);
uiManager.update(123);
t.deepEqual(postedMessages, [
['FRAME', 123],
['DRAW', 'COMMANDS']
]);
t.equal(clearedCommands, true);
});
});
| mit |