repo_name string | path string | copies string | size string | content string | license string |
|---|---|---|---|---|---|
JeffProgrammer/D3D11Test | thirdparty/SDL2/src/libm/k_sin.c | 306 | 2815 | /* @(#)k_sin.c 5.1 93/09/24 */
/*
* ====================================================
* Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved.
*
* Developed at SunPro, a Sun Microsystems, Inc. business.
* Permission to use, copy, modify, and distribute this
* software is freely granted, provided that this notice
* is preserved.
* ====================================================
*/
#if defined(LIBM_SCCS) && !defined(lint)
static const char rcsid[] =
"$NetBSD: k_sin.c,v 1.8 1995/05/10 20:46:31 jtc Exp $";
#endif
/* __kernel_sin( x, y, iy)
* kernel sin function on [-pi/4, pi/4], pi/4 ~ 0.7854
* Input x is assumed to be bounded by ~pi/4 in magnitude.
* Input y is the tail of x.
* Input iy indicates whether y is 0. (if iy=0, y assume to be 0).
*
* Algorithm
* 1. Since sin(-x) = -sin(x), we need only to consider positive x.
* 2. if x < 2^-27 (hx<0x3e400000 0), return x with inexact if x!=0.
* 3. sin(x) is approximated by a polynomial of degree 13 on
* [0,pi/4]
* 3 13
* sin(x) ~ x + S1*x + ... + S6*x
* where
*
* |sin(x) 2 4 6 8 10 12 | -58
* |----- - (1+S1*x +S2*x +S3*x +S4*x +S5*x +S6*x )| <= 2
* | x |
*
* 4. sin(x+y) = sin(x) + sin'(x')*y
* ~ sin(x) + (1-x*x/2)*y
* For better accuracy, let
* 3 2 2 2 2
* r = x *(S2+x *(S3+x *(S4+x *(S5+x *S6))))
* then 3 2
* sin(x) = x + (S1*x + (x *(r-y/2)+y))
*/
#include "math_libm.h"
#include "math_private.h"
#ifdef __STDC__
static const double
#else
static double
#endif
half = 5.00000000000000000000e-01, /* 0x3FE00000, 0x00000000 */
S1 = -1.66666666666666324348e-01, /* 0xBFC55555, 0x55555549 */
S2 = 8.33333333332248946124e-03, /* 0x3F811111, 0x1110F8A6 */
S3 = -1.98412698298579493134e-04, /* 0xBF2A01A0, 0x19C161D5 */
S4 = 2.75573137070700676789e-06, /* 0x3EC71DE3, 0x57B1FE7D */
S5 = -2.50507602534068634195e-08, /* 0xBE5AE5E6, 0x8A2B9CEB */
S6 = 1.58969099521155010221e-10; /* 0x3DE5D93A, 0x5ACFD57C */
#ifdef __STDC__
double attribute_hidden
__kernel_sin(double x, double y, int iy)
#else
double attribute_hidden
__kernel_sin(x, y, iy)
double x, y;
int iy; /* iy=0 if y is zero */
#endif
{
double z, r, v;
int32_t ix;
GET_HIGH_WORD(ix, x);
ix &= 0x7fffffff; /* high word of x */
if (ix < 0x3e400000) { /* |x| < 2**-27 */
if ((int) x == 0)
return x;
} /* generate inexact */
z = x * x;
v = z * x;
r = S2 + z * (S3 + z * (S4 + z * (S5 + z * S6)));
if (iy == 0)
return x + v * (S1 + z * r);
else
return x - ((z * (half * y - v * r) - y) - v * S1);
}
| bsd-3-clause |
thomaslee/hiredis | examples/example.c | 56 | 2236 | #include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <hiredis.h>
int main(int argc, char **argv) {
unsigned int j;
redisContext *c;
redisReply *reply;
const char *hostname = (argc > 1) ? argv[1] : "127.0.0.1";
int port = (argc > 2) ? atoi(argv[2]) : 6379;
struct timeval timeout = { 1, 500000 }; // 1.5 seconds
c = redisConnectWithTimeout(hostname, port, timeout);
if (c == NULL || c->err) {
if (c) {
printf("Connection error: %s\n", c->errstr);
redisFree(c);
} else {
printf("Connection error: can't allocate redis context\n");
}
exit(1);
}
/* PING server */
reply = redisCommand(c,"PING");
printf("PING: %s\n", reply->str);
freeReplyObject(reply);
/* Set a key */
reply = redisCommand(c,"SET %s %s", "foo", "hello world");
printf("SET: %s\n", reply->str);
freeReplyObject(reply);
/* Set a key using binary safe API */
reply = redisCommand(c,"SET %b %b", "bar", (size_t) 3, "hello", (size_t) 5);
printf("SET (binary API): %s\n", reply->str);
freeReplyObject(reply);
/* Try a GET and two INCR */
reply = redisCommand(c,"GET foo");
printf("GET foo: %s\n", reply->str);
freeReplyObject(reply);
reply = redisCommand(c,"INCR counter");
printf("INCR counter: %lld\n", reply->integer);
freeReplyObject(reply);
/* again ... */
reply = redisCommand(c,"INCR counter");
printf("INCR counter: %lld\n", reply->integer);
freeReplyObject(reply);
/* Create a list of numbers, from 0 to 9 */
reply = redisCommand(c,"DEL mylist");
freeReplyObject(reply);
for (j = 0; j < 10; j++) {
char buf[64];
snprintf(buf,64,"%u",j);
reply = redisCommand(c,"LPUSH mylist element-%s", buf);
freeReplyObject(reply);
}
/* Let's check what we have inside the list */
reply = redisCommand(c,"LRANGE mylist 0 -1");
if (reply->type == REDIS_REPLY_ARRAY) {
for (j = 0; j < reply->elements; j++) {
printf("%u) %s\n", j, reply->element[j]->str);
}
}
freeReplyObject(reply);
/* Disconnects and frees the context */
redisFree(c);
return 0;
}
| bsd-3-clause |
ninjin/torch7 | generic/Storage.c | 58 | 7980 | #ifndef TH_GENERIC_FILE
#define TH_GENERIC_FILE "generic/Storage.c"
#else
static int torch_Storage_(new)(lua_State *L)
{
int index = 1;
THStorage *storage;
THAllocator *allocator = luaT_toudata(L, index, "torch.Allocator");
if (allocator) index++;
if(lua_type(L, index) == LUA_TSTRING)
{
if (allocator)
THError("Passing allocator not supported when using file mapping");
const char *fileName = luaL_checkstring(L, index);
int isShared = 0;
if(luaT_optboolean(L, index + 1, 0))
isShared = TH_ALLOCATOR_MAPPED_SHARED;
long size = luaL_optlong(L, index + 2, 0);
if (isShared && luaT_optboolean(L, index + 3, 0))
isShared = TH_ALLOCATOR_MAPPED_SHAREDMEM;
storage = THStorage_(newWithMapping)(fileName, size, isShared);
}
else if(lua_type(L, index) == LUA_TTABLE)
{
long size = lua_objlen(L, index);
long i;
if (allocator)
storage = THStorage_(newWithAllocator)(size, allocator, NULL);
else
storage = THStorage_(newWithSize)(size);
for(i = 1; i <= size; i++)
{
lua_rawgeti(L, index, i);
if(!lua_isnumber(L, -1))
{
THStorage_(free)(storage);
luaL_error(L, "element at index %d is not a number", i);
}
THStorage_(set)(storage, i-1, (real)lua_tonumber(L, -1));
lua_pop(L, 1);
}
}
else if(lua_type(L, index) == LUA_TUSERDATA)
{
if (allocator)
THError("Passing allocator not supported when using storage views");
THStorage *src = luaT_checkudata(L, index, torch_Storage);
real *ptr = src->data;
long offset = luaL_optlong(L, index + 1, 1) - 1;
if (offset < 0 || offset >= src->size) {
luaL_error(L, "offset out of bounds");
}
long size = luaL_optlong(L, index + 2, src->size - offset);
if (size < 1 || size > (src->size - offset)) {
luaL_error(L, "size out of bounds");
}
storage = THStorage_(newWithData)(ptr + offset, size);
storage->flag = TH_STORAGE_REFCOUNTED | TH_STORAGE_VIEW;
storage->view = src;
THStorage_(retain)(storage->view);
}
else if(lua_type(L, index + 1) == LUA_TNUMBER)
{
long size = luaL_optlong(L, index, 0);
real *ptr = (real *)luaL_optlong(L, index + 1, 0);
if (allocator)
storage = THStorage_(newWithDataAndAllocator)(ptr, size, allocator, NULL);
else
storage = THStorage_(newWithData)(ptr, size);
storage->flag = TH_STORAGE_REFCOUNTED;
}
else
{
long size = luaL_optlong(L, index, 0);
if (allocator)
storage = THStorage_(newWithAllocator)(size, allocator, NULL);
else
storage = THStorage_(newWithSize)(size);
}
luaT_pushudata(L, storage, torch_Storage);
return 1;
}
static int torch_Storage_(retain)(lua_State *L)
{
THStorage *storage = luaT_checkudata(L, 1, torch_Storage);
THStorage_(retain)(storage);
return 0;
}
static int torch_Storage_(free)(lua_State *L)
{
THStorage *storage = luaT_checkudata(L, 1, torch_Storage);
THStorage_(free)(storage);
return 0;
}
static int torch_Storage_(resize)(lua_State *L)
{
THStorage *storage = luaT_checkudata(L, 1, torch_Storage);
long size = luaL_checklong(L, 2);
/* int keepContent = luaT_optboolean(L, 3, 0); */
THStorage_(resize)(storage, size);/*, keepContent); */
lua_settop(L, 1);
return 1;
}
static int torch_Storage_(copy)(lua_State *L)
{
THStorage *storage = luaT_checkudata(L, 1, torch_Storage);
void *src;
if( (src = luaT_toudata(L, 2, torch_Storage)) )
THStorage_(copy)(storage, src);
else if( (src = luaT_toudata(L, 2, "torch.ByteStorage")) )
THStorage_(copyByte)(storage, src);
else if( (src = luaT_toudata(L, 2, "torch.CharStorage")) )
THStorage_(copyChar)(storage, src);
else if( (src = luaT_toudata(L, 2, "torch.ShortStorage")) )
THStorage_(copyShort)(storage, src);
else if( (src = luaT_toudata(L, 2, "torch.IntStorage")) )
THStorage_(copyInt)(storage, src);
else if( (src = luaT_toudata(L, 2, "torch.LongStorage")) )
THStorage_(copyLong)(storage, src);
else if( (src = luaT_toudata(L, 2, "torch.FloatStorage")) )
THStorage_(copyFloat)(storage, src);
else if( (src = luaT_toudata(L, 2, "torch.DoubleStorage")) )
THStorage_(copyDouble)(storage, src);
else
luaL_typerror(L, 2, "torch.*Storage");
lua_settop(L, 1);
return 1;
}
static int torch_Storage_(fill)(lua_State *L)
{
THStorage *storage = luaT_checkudata(L, 1, torch_Storage);
double value = luaL_checknumber(L, 2);
THStorage_(fill)(storage, (real)value);
lua_settop(L, 1);
return 1;
}
static int torch_Storage_(elementSize)(lua_State *L)
{
lua_pushnumber(L, THStorage_(elementSize)());
return 1;
}
static int torch_Storage_(__len__)(lua_State *L)
{
THStorage *storage = luaT_checkudata(L, 1, torch_Storage);
lua_pushnumber(L, storage->size);
return 1;
}
static int torch_Storage_(__newindex__)(lua_State *L)
{
if(lua_isnumber(L, 2))
{
THStorage *storage = luaT_checkudata(L, 1, torch_Storage);
long index = luaL_checklong(L, 2) - 1;
double number = luaL_checknumber(L, 3);
THStorage_(set)(storage, index, (real)number);
lua_pushboolean(L, 1);
}
else
lua_pushboolean(L, 0);
return 1;
}
static int torch_Storage_(__index__)(lua_State *L)
{
if(lua_isnumber(L, 2))
{
THStorage *storage = luaT_checkudata(L, 1, torch_Storage);
long index = luaL_checklong(L, 2) - 1;
lua_pushnumber(L, THStorage_(get)(storage, index));
lua_pushboolean(L, 1);
return 2;
}
else
{
lua_pushboolean(L, 0);
return 1;
}
}
#if defined(TH_REAL_IS_CHAR) || defined(TH_REAL_IS_BYTE)
static int torch_Storage_(string)(lua_State *L)
{
THStorage *storage = luaT_checkudata(L, 1, torch_Storage);
if(lua_isstring(L, -1))
{
size_t len = 0;
const char *str = lua_tolstring(L, -1, &len);
THStorage_(resize)(storage, len);
memmove(storage->data, str, len);
lua_settop(L, 1);
}
else
lua_pushlstring(L, (char*)storage->data, storage->size);
return 1; /* either storage or string */
}
#endif
static int torch_Storage_(totable)(lua_State *L)
{
THStorage *storage = luaT_checkudata(L, 1, torch_Storage);
long i;
lua_newtable(L);
for(i = 0; i < storage->size; i++)
{
lua_pushnumber(L, (lua_Number)storage->data[i]);
lua_rawseti(L, -2, i+1);
}
return 1;
}
static int torch_Storage_(factory)(lua_State *L)
{
THStorage *storage = THStorage_(new)();
luaT_pushudata(L, storage, torch_Storage);
return 1;
}
static int torch_Storage_(write)(lua_State *L)
{
THStorage *storage = luaT_checkudata(L, 1, torch_Storage);
THFile *file = luaT_checkudata(L, 2, "torch.File");
THFile_writeLongScalar(file, storage->size);
THFile_writeRealRaw(file, storage->data, storage->size);
return 0;
}
static int torch_Storage_(read)(lua_State *L)
{
THStorage *storage = luaT_checkudata(L, 1, torch_Storage);
THFile *file = luaT_checkudata(L, 2, "torch.File");
long size = THFile_readLongScalar(file);
THStorage_(resize)(storage, size);
THFile_readRealRaw(file, storage->data, storage->size);
return 0;
}
static const struct luaL_Reg torch_Storage_(_) [] = {
{"retain", torch_Storage_(retain)},
{"free", torch_Storage_(free)},
{"size", torch_Storage_(__len__)},
{"elementSize", torch_Storage_(elementSize)},
{"__len__", torch_Storage_(__len__)},
{"__newindex__", torch_Storage_(__newindex__)},
{"__index__", torch_Storage_(__index__)},
{"resize", torch_Storage_(resize)},
{"fill", torch_Storage_(fill)},
{"copy", torch_Storage_(copy)},
{"totable", torch_Storage_(totable)},
{"write", torch_Storage_(write)},
{"read", torch_Storage_(read)},
#if defined(TH_REAL_IS_CHAR) || defined(TH_REAL_IS_BYTE)
{"string", torch_Storage_(string)},
#endif
{NULL, NULL}
};
void torch_Storage_(init)(lua_State *L)
{
luaT_newmetatable(L, torch_Storage, NULL,
torch_Storage_(new), torch_Storage_(free), torch_Storage_(factory));
luaT_setfuncs(L, torch_Storage_(_), 0);
lua_pop(L, 1);
}
#endif
| bsd-3-clause |
RufaelDev/pcc-mp3dg | test/geometry/test_triangle_mesh.cpp | 59 | 22392 | /*
* Software License Agreement (BSD License)
*
* Point Cloud Library (PCL) - www.pointclouds.org
* Copyright (c) 2009-2012, Willow Garage, Inc.
* Copyright (c) 2012-, Open Perception, 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 copyright holder(s) 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.
*
* $Id$
*
*/
#include <vector>
#include <typeinfo>
#include <gtest/gtest.h>
#include <pcl/geometry/triangle_mesh.h>
#include "test_mesh_common_functions.h"
////////////////////////////////////////////////////////////////////////////////
typedef pcl::geometry::VertexIndex VertexIndex;
typedef pcl::geometry::HalfEdgeIndex HalfEdgeIndex;
typedef pcl::geometry::EdgeIndex EdgeIndex;
typedef pcl::geometry::FaceIndex FaceIndex;
typedef std::vector <VertexIndex> VertexIndices;
typedef std::vector <HalfEdgeIndex> HalfEdgeIndices;
typedef std::vector <FaceIndex> FaceIndices;
template <bool IsManifoldT>
struct MeshTraits
{
typedef int VertexData;
typedef pcl::geometry::NoData HalfEdgeData;
typedef pcl::geometry::NoData EdgeData;
typedef pcl::geometry::NoData FaceData;
typedef boost::integral_constant <bool, IsManifoldT> IsManifold;
};
typedef pcl::geometry::TriangleMesh <MeshTraits <true > > ManifoldTriangleMesh;
typedef pcl::geometry::TriangleMesh <MeshTraits <false> > NonManifoldTriangleMesh;
typedef testing::Types <ManifoldTriangleMesh, NonManifoldTriangleMesh> TriangleMeshTypes;
template <class MeshT>
class TestTriangleMesh : public testing::Test
{
protected:
typedef MeshT Mesh;
};
TYPED_TEST_CASE (TestTriangleMesh, TriangleMeshTypes);
////////////////////////////////////////////////////////////////////////////////
TYPED_TEST (TestTriangleMesh, CorrectMeshTag)
{
typedef typename TestFixture::Mesh Mesh;
typedef typename Mesh::MeshTag MeshTag;
ASSERT_EQ (typeid (pcl::geometry::TriangleMeshTag), typeid (MeshTag));
}
////////////////////////////////////////////////////////////////////////////////
TYPED_TEST (TestTriangleMesh, CorrectNumberOfVertices)
{
// Make sure that only quads can be added
typedef typename TestFixture::Mesh Mesh;
for (unsigned int n=1; n<=5; ++n)
{
Mesh mesh;
VertexIndices vi;
for (unsigned int i=0; i<n; ++i)
{
vi.push_back (VertexIndex (i));
mesh.addVertex (i);
}
const FaceIndex index = mesh.addFace (vi);
if (n==3) EXPECT_TRUE (index.isValid ()) << "Number of vertices in the face: " << n;
else EXPECT_FALSE (index.isValid ()) << "Number of vertices in the face: " << n;
}
}
////////////////////////////////////////////////////////////////////////////////
TYPED_TEST (TestTriangleMesh, OneTriangle)
{
typedef typename TestFixture::Mesh Mesh;
// 2 //
// / \ //
// 0 - 1 //
Mesh mesh;
VertexIndices vi;
for (unsigned int i=0; i<3; ++i) vi.push_back (mesh.addVertex (i));
const FaceIndex fi = mesh.addFace (vi);
ASSERT_TRUE (fi.isValid ());
const HalfEdgeIndex he_10 = mesh.getOutgoingHalfEdgeIndex (vi [1]);
const HalfEdgeIndex he_21 = mesh.getOutgoingHalfEdgeIndex (vi [2]);
const HalfEdgeIndex he_02 = mesh.getOutgoingHalfEdgeIndex (vi [0]);
const HalfEdgeIndex he_01 = mesh.getOppositeHalfEdgeIndex (he_10);
const HalfEdgeIndex he_12 = mesh.getOppositeHalfEdgeIndex (he_21);
const HalfEdgeIndex he_20 = mesh.getOppositeHalfEdgeIndex (he_02);
EXPECT_TRUE (checkHalfEdge (mesh, he_10, vi [1], vi[0]));
EXPECT_TRUE (checkHalfEdge (mesh, he_21, vi [2], vi[1]));
EXPECT_TRUE (checkHalfEdge (mesh, he_02, vi [0], vi[2]));
EXPECT_TRUE (checkHalfEdge (mesh, he_01, vi [0], vi[1]));
EXPECT_TRUE (checkHalfEdge (mesh, he_12, vi [1], vi[2]));
EXPECT_TRUE (checkHalfEdge (mesh, he_20, vi [2], vi[0]));
EXPECT_EQ (he_01, mesh.getIncomingHalfEdgeIndex (vi [1]));
EXPECT_EQ (he_12, mesh.getIncomingHalfEdgeIndex (vi [2]));
EXPECT_EQ (he_20, mesh.getIncomingHalfEdgeIndex (vi [0]));
EXPECT_EQ (he_12, mesh.getNextHalfEdgeIndex (he_01));
EXPECT_EQ (he_20, mesh.getNextHalfEdgeIndex (he_12));
EXPECT_EQ (he_01, mesh.getNextHalfEdgeIndex (he_20));
EXPECT_EQ (he_20, mesh.getPrevHalfEdgeIndex (he_01));
EXPECT_EQ (he_01, mesh.getPrevHalfEdgeIndex (he_12));
EXPECT_EQ (he_12, mesh.getPrevHalfEdgeIndex (he_20));
EXPECT_EQ (he_02, mesh.getNextHalfEdgeIndex (he_10));
EXPECT_EQ (he_21, mesh.getNextHalfEdgeIndex (he_02));
EXPECT_EQ (he_10, mesh.getNextHalfEdgeIndex (he_21));
EXPECT_EQ (he_21, mesh.getPrevHalfEdgeIndex (he_10));
EXPECT_EQ (he_10, mesh.getPrevHalfEdgeIndex (he_02));
EXPECT_EQ (he_02, mesh.getPrevHalfEdgeIndex (he_21));
EXPECT_EQ (fi, mesh.getFaceIndex (he_01));
EXPECT_EQ (fi, mesh.getFaceIndex (he_12));
EXPECT_EQ (fi, mesh.getFaceIndex (he_20));
EXPECT_FALSE (mesh.getOppositeFaceIndex (he_01).isValid ());
EXPECT_FALSE (mesh.getOppositeFaceIndex (he_12).isValid ());
EXPECT_FALSE (mesh.getOppositeFaceIndex (he_20).isValid ());
EXPECT_FALSE (mesh.getFaceIndex (he_10).isValid ());
EXPECT_FALSE (mesh.getFaceIndex (he_21).isValid ());
EXPECT_FALSE (mesh.getFaceIndex (he_02).isValid ());
EXPECT_EQ (fi, mesh.getOppositeFaceIndex (he_10));
EXPECT_EQ (fi, mesh.getOppositeFaceIndex (he_21));
EXPECT_EQ (fi, mesh.getOppositeFaceIndex (he_02));
EXPECT_EQ (he_20, mesh.getInnerHalfEdgeIndex (fi));
EXPECT_EQ (he_02, mesh.getOuterHalfEdgeIndex (fi));
EXPECT_FALSE (mesh.isBoundary (he_01));
EXPECT_FALSE (mesh.isBoundary (he_12));
EXPECT_FALSE (mesh.isBoundary (he_20));
EXPECT_TRUE (mesh.isBoundary (he_10));
EXPECT_TRUE (mesh.isBoundary (he_21));
EXPECT_TRUE (mesh.isBoundary (he_02));
EXPECT_TRUE (mesh.isBoundary (vi [0]));
EXPECT_TRUE (mesh.isBoundary (vi [1]));
EXPECT_TRUE (mesh.isBoundary (vi [2]));
EXPECT_TRUE (mesh.isBoundary (fi));
}
////////////////////////////////////////////////////////////////////////////////
TYPED_TEST (TestTriangleMesh, TwoTriangles)
{
typedef typename TestFixture::Mesh Mesh;
// 3 - 2 //
// \ / \ //
// 0 - 1 //
Mesh mesh;
VertexIndex vi_0 = mesh.addVertex (0);
VertexIndex vi_1 = mesh.addVertex (1);
VertexIndex vi_2 = mesh.addVertex (2);
VertexIndex vi_3 = mesh.addVertex (3);
// First face
VertexIndices vi;
vi.push_back (vi_0);
vi.push_back (vi_1);
vi.push_back (vi_2);
const FaceIndex fi_0 = mesh.addFace (vi);
ASSERT_TRUE (fi_0.isValid ());
const HalfEdgeIndex he_10 = mesh.getOutgoingHalfEdgeIndex (vi_1);
const HalfEdgeIndex he_21 = mesh.getOutgoingHalfEdgeIndex (vi_2);
const HalfEdgeIndex he_02 = mesh.getOutgoingHalfEdgeIndex (vi_0);
const HalfEdgeIndex he_01 = mesh.getOppositeHalfEdgeIndex (he_10);
const HalfEdgeIndex he_12 = mesh.getOppositeHalfEdgeIndex (he_21);
const HalfEdgeIndex he_20 = mesh.getOppositeHalfEdgeIndex (he_02);
// Second face
vi.clear ();
vi.push_back (vi_0);
vi.push_back (vi_2);
vi.push_back (vi_3);
const FaceIndex fi_1 = mesh.addFace (vi);
ASSERT_TRUE (fi_1.isValid ());
const HalfEdgeIndex he_03 = mesh.getOutgoingHalfEdgeIndex (vi_0);
const HalfEdgeIndex he_32 = mesh.getOutgoingHalfEdgeIndex (vi_3);
const HalfEdgeIndex he_30 = mesh.getOppositeHalfEdgeIndex (he_03);
const HalfEdgeIndex he_23 = mesh.getOppositeHalfEdgeIndex (he_32);
// Tests
EXPECT_TRUE (checkHalfEdge (mesh, he_01, vi_0, vi_1));
EXPECT_TRUE (checkHalfEdge (mesh, he_12, vi_1, vi_2));
EXPECT_TRUE (checkHalfEdge (mesh, he_20, vi_2, vi_0));
EXPECT_TRUE (checkHalfEdge (mesh, he_02, vi_0, vi_2));
EXPECT_TRUE (checkHalfEdge (mesh, he_23, vi_2, vi_3));
EXPECT_TRUE (checkHalfEdge (mesh, he_30, vi_3, vi_0));
EXPECT_TRUE (checkHalfEdge (mesh, he_03, vi_0, vi_3));
EXPECT_TRUE (checkHalfEdge (mesh, he_32, vi_3, vi_2));
EXPECT_TRUE (checkHalfEdge (mesh, he_21, vi_2, vi_1));
EXPECT_TRUE (checkHalfEdge (mesh, he_10, vi_1, vi_0));
EXPECT_EQ (he_12, mesh.getNextHalfEdgeIndex (he_01));
EXPECT_EQ (he_20, mesh.getNextHalfEdgeIndex (he_12));
EXPECT_EQ (he_01, mesh.getNextHalfEdgeIndex (he_20));
EXPECT_EQ (he_20, mesh.getPrevHalfEdgeIndex (he_01));
EXPECT_EQ (he_01, mesh.getPrevHalfEdgeIndex (he_12));
EXPECT_EQ (he_12, mesh.getPrevHalfEdgeIndex (he_20));
EXPECT_EQ (he_23, mesh.getNextHalfEdgeIndex (he_02));
EXPECT_EQ (he_30, mesh.getNextHalfEdgeIndex (he_23));
EXPECT_EQ (he_02, mesh.getNextHalfEdgeIndex (he_30));
EXPECT_EQ (he_30, mesh.getPrevHalfEdgeIndex (he_02));
EXPECT_EQ (he_02, mesh.getPrevHalfEdgeIndex (he_23));
EXPECT_EQ (he_23, mesh.getPrevHalfEdgeIndex (he_30));
EXPECT_EQ (he_03, mesh.getNextHalfEdgeIndex (he_10));
EXPECT_EQ (he_32, mesh.getNextHalfEdgeIndex (he_03));
EXPECT_EQ (he_21, mesh.getNextHalfEdgeIndex (he_32));
EXPECT_EQ (he_10, mesh.getNextHalfEdgeIndex (he_21));
EXPECT_EQ (he_21, mesh.getPrevHalfEdgeIndex (he_10));
EXPECT_EQ (he_10, mesh.getPrevHalfEdgeIndex (he_03));
EXPECT_EQ (he_03, mesh.getPrevHalfEdgeIndex (he_32));
EXPECT_EQ (he_32, mesh.getPrevHalfEdgeIndex (he_21));
EXPECT_EQ (fi_0, mesh.getFaceIndex (he_01));
EXPECT_EQ (fi_0, mesh.getFaceIndex (he_12));
EXPECT_EQ (fi_0, mesh.getFaceIndex (he_20));
EXPECT_EQ (fi_1, mesh.getFaceIndex (he_02));
EXPECT_EQ (fi_1, mesh.getFaceIndex (he_23));
EXPECT_EQ (fi_1, mesh.getFaceIndex (he_30));
EXPECT_FALSE (mesh.getFaceIndex (he_10).isValid ());
EXPECT_FALSE (mesh.getFaceIndex (he_03).isValid ());
EXPECT_FALSE (mesh.getFaceIndex (he_32).isValid ());
EXPECT_FALSE (mesh.getFaceIndex (he_21).isValid ());
EXPECT_FALSE (mesh.getOppositeFaceIndex (he_01).isValid ());
EXPECT_FALSE (mesh.getOppositeFaceIndex (he_12).isValid ());
EXPECT_FALSE (mesh.getOppositeFaceIndex (he_23).isValid ());
EXPECT_FALSE (mesh.getOppositeFaceIndex (he_30).isValid ());
EXPECT_EQ (fi_0, mesh.getOppositeFaceIndex (he_21));
EXPECT_EQ (fi_0, mesh.getOppositeFaceIndex (he_10));
EXPECT_EQ (fi_1, mesh.getOppositeFaceIndex (he_03));
EXPECT_EQ (fi_1, mesh.getOppositeFaceIndex (he_32));
EXPECT_EQ (he_20, mesh.getInnerHalfEdgeIndex (fi_0));
EXPECT_EQ (he_30, mesh.getInnerHalfEdgeIndex (fi_1));
EXPECT_EQ (he_02, mesh.getOuterHalfEdgeIndex (fi_0));
EXPECT_EQ (he_03, mesh.getOuterHalfEdgeIndex (fi_1));
EXPECT_FALSE (mesh.isBoundary (he_01));
EXPECT_FALSE (mesh.isBoundary (he_12));
EXPECT_FALSE (mesh.isBoundary (he_20));
EXPECT_FALSE (mesh.isBoundary (he_02));
EXPECT_FALSE (mesh.isBoundary (he_23));
EXPECT_FALSE (mesh.isBoundary (he_30));
EXPECT_TRUE (mesh.isBoundary (he_10));
EXPECT_TRUE (mesh.isBoundary (he_03));
EXPECT_TRUE (mesh.isBoundary (he_32));
EXPECT_TRUE (mesh.isBoundary (he_21));
EXPECT_TRUE (mesh.isBoundary (vi_0));
EXPECT_TRUE (mesh.isBoundary (vi_1));
EXPECT_TRUE (mesh.isBoundary (vi_2));
EXPECT_TRUE (mesh.isBoundary (vi_3));
EXPECT_TRUE (mesh.isBoundary (fi_0));
EXPECT_TRUE (mesh.isBoundary (fi_1));
}
////////////////////////////////////////////////////////////////////////////////
TYPED_TEST (TestTriangleMesh, ThreeTriangles)
{
typedef typename TestFixture::Mesh Mesh;
// 1 ----- 3 //
// \ \ / / //
// \ 0 / //
// \ | / //
// 2 //
Mesh mesh;
VertexIndex vi_0 = mesh.addVertex (0);
VertexIndex vi_1 = mesh.addVertex (1);
VertexIndex vi_2 = mesh.addVertex (2);
VertexIndex vi_3 = mesh.addVertex (3);
// First face
VertexIndices vi;
vi.push_back (vi_0);
vi.push_back (vi_1);
vi.push_back (vi_2);
const FaceIndex fi_0 = mesh.addFace (vi);
ASSERT_TRUE (fi_0.isValid ());
const HalfEdgeIndex he_10 = mesh.getOutgoingHalfEdgeIndex (vi_1);
const HalfEdgeIndex he_21 = mesh.getOutgoingHalfEdgeIndex (vi_2);
const HalfEdgeIndex he_02 = mesh.getOutgoingHalfEdgeIndex (vi_0);
const HalfEdgeIndex he_01 = mesh.getOppositeHalfEdgeIndex (he_10);
const HalfEdgeIndex he_12 = mesh.getOppositeHalfEdgeIndex (he_21);
const HalfEdgeIndex he_20 = mesh.getOppositeHalfEdgeIndex (he_02);
// Second face
vi.clear ();
vi.push_back (vi_0);
vi.push_back (vi_2);
vi.push_back (vi_3);
const FaceIndex fi_1 = mesh.addFace (vi);
ASSERT_TRUE (fi_1.isValid ());
const HalfEdgeIndex he_03 = mesh.getOutgoingHalfEdgeIndex (vi_0);
const HalfEdgeIndex he_32 = mesh.getOutgoingHalfEdgeIndex (vi_3);
const HalfEdgeIndex he_30 = mesh.getOppositeHalfEdgeIndex (he_03);
const HalfEdgeIndex he_23 = mesh.getOppositeHalfEdgeIndex (he_32);
// Third face
vi.clear ();
vi.push_back (vi_0);
vi.push_back (vi_3);
vi.push_back (vi_1);
const FaceIndex fi_2 = mesh.addFace (vi);
ASSERT_TRUE (fi_2.isValid ());
const HalfEdgeIndex he_13 = mesh.getOutgoingHalfEdgeIndex (vi_1);
const HalfEdgeIndex he_31 = mesh.getOppositeHalfEdgeIndex (he_13);
// Tests
EXPECT_TRUE (checkHalfEdge (mesh, he_01, vi_0, vi_1));
EXPECT_TRUE (checkHalfEdge (mesh, he_12, vi_1, vi_2));
EXPECT_TRUE (checkHalfEdge (mesh, he_20, vi_2, vi_0));
EXPECT_TRUE (checkHalfEdge (mesh, he_02, vi_0, vi_2));
EXPECT_TRUE (checkHalfEdge (mesh, he_23, vi_2, vi_3));
EXPECT_TRUE (checkHalfEdge (mesh, he_30, vi_3, vi_0));
EXPECT_TRUE (checkHalfEdge (mesh, he_03, vi_0, vi_3));
EXPECT_TRUE (checkHalfEdge (mesh, he_31, vi_3, vi_1));
EXPECT_TRUE (checkHalfEdge (mesh, he_10, vi_1, vi_0));
EXPECT_TRUE (checkHalfEdge (mesh, he_32, vi_3, vi_2));
EXPECT_TRUE (checkHalfEdge (mesh, he_21, vi_2, vi_1));
EXPECT_TRUE (checkHalfEdge (mesh, he_13, vi_1, vi_3));
EXPECT_EQ (he_12, mesh.getNextHalfEdgeIndex (he_01));
EXPECT_EQ (he_20, mesh.getNextHalfEdgeIndex (he_12));
EXPECT_EQ (he_01, mesh.getNextHalfEdgeIndex (he_20));
EXPECT_EQ (he_23, mesh.getNextHalfEdgeIndex (he_02));
EXPECT_EQ (he_30, mesh.getNextHalfEdgeIndex (he_23));
EXPECT_EQ (he_02, mesh.getNextHalfEdgeIndex (he_30));
EXPECT_EQ (he_31, mesh.getNextHalfEdgeIndex (he_03));
EXPECT_EQ (he_10, mesh.getNextHalfEdgeIndex (he_31));
EXPECT_EQ (he_03, mesh.getNextHalfEdgeIndex (he_10));
EXPECT_EQ (he_21, mesh.getNextHalfEdgeIndex (he_32));
EXPECT_EQ (he_13, mesh.getNextHalfEdgeIndex (he_21));
EXPECT_EQ (he_32, mesh.getNextHalfEdgeIndex (he_13));
EXPECT_EQ (he_20, mesh.getPrevHalfEdgeIndex (he_01));
EXPECT_EQ (he_01, mesh.getPrevHalfEdgeIndex (he_12));
EXPECT_EQ (he_12, mesh.getPrevHalfEdgeIndex (he_20));
EXPECT_EQ (he_30, mesh.getPrevHalfEdgeIndex (he_02));
EXPECT_EQ (he_02, mesh.getPrevHalfEdgeIndex (he_23));
EXPECT_EQ (he_23, mesh.getPrevHalfEdgeIndex (he_30));
EXPECT_EQ (he_10, mesh.getPrevHalfEdgeIndex (he_03));
EXPECT_EQ (he_03, mesh.getPrevHalfEdgeIndex (he_31));
EXPECT_EQ (he_31, mesh.getPrevHalfEdgeIndex (he_10));
EXPECT_EQ (he_13, mesh.getPrevHalfEdgeIndex (he_32));
EXPECT_EQ (he_32, mesh.getPrevHalfEdgeIndex (he_21));
EXPECT_EQ (he_21, mesh.getPrevHalfEdgeIndex (he_13));
EXPECT_EQ (fi_0, mesh.getFaceIndex (he_01));
EXPECT_EQ (fi_0, mesh.getFaceIndex (he_12));
EXPECT_EQ (fi_0, mesh.getFaceIndex (he_20));
EXPECT_EQ (fi_1, mesh.getFaceIndex (he_02));
EXPECT_EQ (fi_1, mesh.getFaceIndex (he_23));
EXPECT_EQ (fi_1, mesh.getFaceIndex (he_30));
EXPECT_EQ (fi_2, mesh.getFaceIndex (he_03));
EXPECT_EQ (fi_2, mesh.getFaceIndex (he_31));
EXPECT_EQ (fi_2, mesh.getFaceIndex (he_10));
EXPECT_FALSE (mesh.getFaceIndex (he_32).isValid ());
EXPECT_FALSE (mesh.getFaceIndex (he_21).isValid ());
EXPECT_FALSE (mesh.getFaceIndex (he_13).isValid ());
EXPECT_EQ (fi_2, mesh.getOppositeFaceIndex (he_01));
EXPECT_FALSE (mesh.getOppositeFaceIndex (he_12).isValid ());
EXPECT_EQ (fi_1, mesh.getOppositeFaceIndex (he_20));
EXPECT_EQ (fi_0, mesh.getOppositeFaceIndex (he_02));
EXPECT_FALSE (mesh.getOppositeFaceIndex (he_23).isValid ());
EXPECT_EQ (fi_2, mesh.getOppositeFaceIndex (he_30));
EXPECT_EQ (fi_1, mesh.getOppositeFaceIndex (he_03));
EXPECT_FALSE (mesh.getOppositeFaceIndex (he_31).isValid ());
EXPECT_EQ (fi_0, mesh.getOppositeFaceIndex (he_10));
EXPECT_EQ (fi_1, mesh.getOppositeFaceIndex (he_32));
EXPECT_EQ (fi_0, mesh.getOppositeFaceIndex (he_21));
EXPECT_EQ (fi_2, mesh.getOppositeFaceIndex (he_13));
EXPECT_EQ (he_20, mesh.getInnerHalfEdgeIndex (fi_0));
EXPECT_EQ (he_30, mesh.getInnerHalfEdgeIndex (fi_1));
EXPECT_EQ (he_10, mesh.getInnerHalfEdgeIndex (fi_2));
EXPECT_EQ (he_02, mesh.getOuterHalfEdgeIndex (fi_0));
EXPECT_EQ (he_03, mesh.getOuterHalfEdgeIndex (fi_1));
EXPECT_EQ (he_01, mesh.getOuterHalfEdgeIndex (fi_2));
EXPECT_FALSE (mesh.isBoundary (he_01));
EXPECT_FALSE (mesh.isBoundary (he_12));
EXPECT_FALSE (mesh.isBoundary (he_20));
EXPECT_FALSE (mesh.isBoundary (he_02));
EXPECT_FALSE (mesh.isBoundary (he_23));
EXPECT_FALSE (mesh.isBoundary (he_30));
EXPECT_FALSE (mesh.isBoundary (he_03));
EXPECT_FALSE (mesh.isBoundary (he_31));
EXPECT_FALSE (mesh.isBoundary (he_10));
EXPECT_TRUE (mesh.isBoundary (he_32));
EXPECT_TRUE (mesh.isBoundary (he_21));
EXPECT_TRUE (mesh.isBoundary (he_13));
EXPECT_FALSE (mesh.isBoundary (vi_0));
EXPECT_TRUE (mesh.isBoundary (vi_1));
EXPECT_TRUE (mesh.isBoundary (vi_2));
EXPECT_TRUE (mesh.isBoundary (vi_3));
EXPECT_TRUE (mesh.isBoundary (fi_0));
EXPECT_TRUE (mesh.isBoundary (fi_1));
EXPECT_TRUE (mesh.isBoundary (fi_2));
}
////////////////////////////////////////////////////////////////////////////////
TEST (TestManifoldTriangleMesh, addTrianglePair)
{
ManifoldTriangleMesh mesh;
VertexIndices vi;
for (unsigned int i=0; i<16; ++i)
{
vi.push_back (mesh.addVertex ());
}
// 00 - 01 - 02 - 03 // X means that both connections / and \ are possible.
// | X | X | X | //
// 04 - 05 - 06 - 07 //
// | X | X | X | //
// 08 - 09 - 10 - 11 //
// | X | X | X | //
// 12 - 13 - 14 - 15 //
VertexIndices tmp;
std::vector <VertexIndices> faces;
tmp.push_back (vi [ 0]); tmp.push_back (vi [ 4]); tmp.push_back (vi [ 5]); tmp.push_back (vi [ 1]); faces.push_back (tmp); tmp.clear ();
tmp.push_back (vi [ 2]); tmp.push_back (vi [ 6]); tmp.push_back (vi [ 7]); tmp.push_back (vi [ 3]); faces.push_back (tmp); tmp.clear ();
tmp.push_back (vi [ 1]); tmp.push_back (vi [ 5]); tmp.push_back (vi [ 6]); tmp.push_back (vi [ 2]); faces.push_back (tmp); tmp.clear ();
tmp.push_back (vi [ 8]); tmp.push_back (vi [12]); tmp.push_back (vi [13]); tmp.push_back (vi [ 9]); faces.push_back (tmp); tmp.clear ();
tmp.push_back (vi [10]); tmp.push_back (vi [14]); tmp.push_back (vi [15]); tmp.push_back (vi [11]); faces.push_back (tmp); tmp.clear ();
tmp.push_back (vi [ 9]); tmp.push_back (vi [13]); tmp.push_back (vi [14]); tmp.push_back (vi [10]); faces.push_back (tmp); tmp.clear ();
tmp.push_back (vi [ 4]); tmp.push_back (vi [ 8]); tmp.push_back (vi [ 9]); tmp.push_back (vi [ 5]); faces.push_back (tmp); tmp.clear ();
tmp.push_back (vi [ 6]); tmp.push_back (vi [10]); tmp.push_back (vi [11]); tmp.push_back (vi [ 7]); faces.push_back (tmp); tmp.clear ();
tmp.push_back (vi [ 5]); tmp.push_back (vi [ 9]); tmp.push_back (vi [10]); tmp.push_back (vi [ 6]); faces.push_back (tmp); tmp.clear ();
for (unsigned int i=0; i<faces.size (); ++i)
{
std::pair <FaceIndex, FaceIndex> fip;
fip = mesh.addTrianglePair (faces [i]);
ASSERT_TRUE (fip.first.isValid ());
ASSERT_TRUE (fip.second.isValid ());
}
for (unsigned int i=0; i<faces.size (); ++i)
{
VertexIndices actual_1, actual_2;
ManifoldTriangleMesh::VertexAroundFaceCirculator circ = mesh.getVertexAroundFaceCirculator (FaceIndex (2*i));
ManifoldTriangleMesh::VertexAroundFaceCirculator circ_end = circ;
do
{
actual_1.push_back (circ.getTargetIndex ());
} while (++circ != circ_end);
circ = mesh.getVertexAroundFaceCirculator (FaceIndex (2*i + 1));
circ_end = circ;
do
{
actual_2.push_back (circ.getTargetIndex ());
} while (++circ != circ_end);
VertexIndices expected_1, expected_2, expected_3, expected_4;
tmp = faces [i];
expected_1.push_back (tmp [0]); expected_1.push_back (tmp [1]); expected_1.push_back (tmp [2]);
expected_2.push_back (tmp [0]); expected_2.push_back (tmp [2]); expected_2.push_back (tmp [3]);
expected_3.push_back (tmp [0]); expected_3.push_back (tmp [1]); expected_3.push_back (tmp [3]);
expected_4.push_back (tmp [1]); expected_4.push_back (tmp [2]); expected_4.push_back (tmp [3]);
EXPECT_TRUE ((isCircularPermutation (expected_1, actual_1) && isCircularPermutation (expected_2, actual_2)) ||
(isCircularPermutation (expected_2, actual_1) && isCircularPermutation (expected_1, actual_2)) ||
(isCircularPermutation (expected_3, actual_1) && isCircularPermutation (expected_4, actual_2)) ||
(isCircularPermutation (expected_4, actual_1) && isCircularPermutation (expected_3, actual_2)));
}
}
////////////////////////////////////////////////////////////////////////////////
int
main (int argc, char** argv)
{
testing::InitGoogleTest (&argc, argv);
return (RUN_ALL_TESTS ());
}
| bsd-3-clause |
srbhprajapati/pcl | apps/src/openni_ii_normal_estimation.cpp | 62 | 8740 | /*
* Software License Agreement (BSD License)
*
* Copyright (c) 2011, Willow Garage, 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 Willow Garage, Inc. 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.
*
*/
#include <pcl/point_cloud.h>
#include <pcl/point_types.h>
#include <pcl/io/openni_grabber.h>
#include <pcl/io/pcd_io.h>
#include <pcl/io/openni_camera/openni_driver.h>
#include <pcl/features/integral_image_normal.h>
#include <pcl/console/parse.h>
#include <pcl/common/time.h>
#include <pcl/visualization/cloud_viewer.h>
#define FPS_CALC(_WHAT_) \
do \
{ \
static unsigned count = 0;\
static double last = pcl::getTime ();\
double now = pcl::getTime (); \
++count; \
if (now - last >= 1.0) \
{ \
std::cout << "Average framerate("<< _WHAT_ << "): " << double(count)/double(now - last) << " Hz" << std::endl; \
count = 0; \
last = now; \
} \
}while(false)
template <typename PointType>
class OpenNIIntegralImageNormalEstimation
{
public:
typedef pcl::PointCloud<PointType> Cloud;
typedef typename Cloud::Ptr CloudPtr;
typedef typename Cloud::ConstPtr CloudConstPtr;
OpenNIIntegralImageNormalEstimation (const std::string& device_id = "")
: viewer ("PCL OpenNI NormalEstimation Viewer")
, device_id_(device_id)
{
//ne_.setNormalEstimationMethod (pcl::IntegralImageNormalEstimation<PointType, pcl::Normal>::AVERAGE_3D_GRADIENT);
ne_.setNormalEstimationMethod (pcl::IntegralImageNormalEstimation<PointType, pcl::Normal>::COVARIANCE_MATRIX);
ne_.setNormalSmoothingSize (11.0);
new_cloud_ = false;
viewer.registerKeyboardCallback(&OpenNIIntegralImageNormalEstimation::keyboard_callback, *this);
}
void
cloud_cb (const CloudConstPtr& cloud)
{
boost::mutex::scoped_lock lock (mtx_);
//lock while we set our cloud;
//FPS_CALC ("computation");
// Estimate surface normals
normals_.reset (new pcl::PointCloud<pcl::Normal>);
//double start = pcl::getTime ();
ne_.setInputCloud (cloud);
ne_.compute (*normals_);
//double stop = pcl::getTime ();
//std::cout << "Time for normal estimation: " << (stop - start) * 1000.0 << " ms" << std::endl;
cloud_ = cloud;
new_cloud_ = true;
}
void
viz_cb (pcl::visualization::PCLVisualizer& viz)
{
mtx_.lock ();
if (!cloud_ || !normals_)
{
//boost::this_thread::sleep(boost::posix_time::seconds(1));
mtx_.unlock ();
return;
}
CloudConstPtr temp_cloud;
pcl::PointCloud<pcl::Normal>::Ptr temp_normals;
temp_cloud.swap (cloud_); //here we set cloud_ to null, so that
temp_normals.swap (normals_);
mtx_.unlock ();
if (!viz.updatePointCloud (temp_cloud, "OpenNICloud"))
{
viz.addPointCloud (temp_cloud, "OpenNICloud");
viz.resetCameraViewpoint ("OpenNICloud");
}
// Render the data
if (new_cloud_)
{
viz.removePointCloud ("normalcloud");
viz.addPointCloudNormals<PointType, pcl::Normal> (temp_cloud, temp_normals, 100, 0.05f, "normalcloud");
new_cloud_ = false;
}
}
void
keyboard_callback (const pcl::visualization::KeyboardEvent& event, void*)
{
boost::mutex::scoped_lock lock (mtx_);
switch (event.getKeyCode ())
{
case '1':
ne_.setNormalEstimationMethod (pcl::IntegralImageNormalEstimation<PointType, pcl::Normal>::COVARIANCE_MATRIX);
std::cout << "switched to COVARIANCE_MATRIX method\n";
break;
case '2':
ne_.setNormalEstimationMethod (pcl::IntegralImageNormalEstimation<PointType, pcl::Normal>::AVERAGE_3D_GRADIENT);
std::cout << "switched to AVERAGE_3D_GRADIENT method\n";
break;
case '3':
ne_.setNormalEstimationMethod (pcl::IntegralImageNormalEstimation<PointType, pcl::Normal>::AVERAGE_DEPTH_CHANGE);
std::cout << "switched to AVERAGE_DEPTH_CHANGE method\n";
break;
case '4':
ne_.setNormalEstimationMethod (pcl::IntegralImageNormalEstimation<PointType, pcl::Normal>::SIMPLE_3D_GRADIENT);
std::cout << "switched to SIMPLE_3D_GRADIENT method\n";
break;
}
}
void
run ()
{
pcl::Grabber* interface = new pcl::OpenNIGrabber (device_id_);
boost::function<void (const CloudConstPtr&)> f = boost::bind (&OpenNIIntegralImageNormalEstimation::cloud_cb, this, _1);
boost::signals2::connection c = interface->registerCallback (f);
viewer.runOnVisualizationThread (boost::bind(&OpenNIIntegralImageNormalEstimation::viz_cb, this, _1), "viz_cb");
interface->start ();
while (!viewer.wasStopped ())
{
boost::this_thread::sleep(boost::posix_time::seconds(1));
}
interface->stop ();
}
pcl::IntegralImageNormalEstimation<PointType, pcl::Normal> ne_;
pcl::visualization::CloudViewer viewer;
std::string device_id_;
boost::mutex mtx_;
// Data
pcl::PointCloud<pcl::Normal>::Ptr normals_;
CloudConstPtr cloud_;
bool new_cloud_;
};
void
usage (char ** argv)
{
std::cout << "usage: " << argv[0] << " [<device_id>]\n\n";
openni_wrapper::OpenNIDriver& driver = openni_wrapper::OpenNIDriver::getInstance ();
if (driver.getNumberDevices () > 0)
{
for (unsigned deviceIdx = 0; deviceIdx < driver.getNumberDevices (); ++deviceIdx)
{
cout << "Device: " << deviceIdx + 1 << ", vendor: " << driver.getVendorName (deviceIdx) << ", product: " << driver.getProductName (deviceIdx)
<< ", connected: " << driver.getBus (deviceIdx) << " @ " << driver.getAddress (deviceIdx) << ", serial number: \'" << driver.getSerialNumber (deviceIdx) << "\'" << endl;
cout << "device_id may be #1, #2, ... for the first second etc device in the list or" << endl
<< " bus@address for the device connected to a specific usb-bus / address combination (works only in Linux) or" << endl
<< " <serial-number> (only in Linux and for devices which provide serial numbers)" << endl;
}
}
else
cout << "No devices connected." << endl;
}
int
main (int argc, char ** argv)
{
std::string arg;
if (argc > 1)
arg = std::string (argv[1]);
openni_wrapper::OpenNIDriver& driver = openni_wrapper::OpenNIDriver::getInstance ();
if (arg == "--help" || arg == "-h" || driver.getNumberDevices () == 0)
{
usage (argv);
return 1;
}
std::cout << "Press following keys to switch to the different integral image normal estimation methods:\n";
std::cout << "<1> COVARIANCE_MATRIX method\n";
std::cout << "<2> AVERAGE_3D_GRADIENT method\n";
std::cout << "<3> AVERAGE_DEPTH_CHANGE method\n";
std::cout << "<4> SIMPLE_3D_GRADIENT method\n";
std::cout << "<Q,q> quit\n\n";
pcl::OpenNIGrabber grabber ("");
if (grabber.providesCallback<pcl::OpenNIGrabber::sig_cb_openni_point_cloud_rgba> ())
{
PCL_INFO ("PointXYZRGBA mode enabled.\n");
OpenNIIntegralImageNormalEstimation<pcl::PointXYZRGBA> v ("");
v.run ();
}
else
{
PCL_INFO ("PointXYZ mode enabled.\n");
OpenNIIntegralImageNormalEstimation<pcl::PointXYZ> v ("");
v.run ();
}
return (0);
}
| bsd-3-clause |
Evervolv/android_external_chromium_org | native_client_sdk/src/libraries/third_party/pthreads-win32/pthread.c | 337 | 2167 | /*
* pthread.c
*
* Description:
* This translation unit agregates pthreads-win32 translation units.
* It is used for inline optimisation of the library,
* maximising for speed at the expense of size.
*
* --------------------------------------------------------------------------
*
* Pthreads-win32 - POSIX Threads Library for Win32
* Copyright(C) 1998 John E. Bossom
* Copyright(C) 1999,2005 Pthreads-win32 contributors
*
* Contact Email: rpj@callisto.canberra.edu.au
*
* The current list of contributors is contained
* in the file CONTRIBUTORS included with the source
* code distribution. The list can also be seen at the
* following World Wide Web location:
* http://sources.redhat.com/pthreads-win32/contributors.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 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 in the file COPYING.LIB;
* if not, write to the Free Software Foundation, Inc.,
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA
*/
#include "pthread.h"
#include "implement.h"
/* The following are ordered for inlining */
#include "private.c"
#include "attr.c"
#include "barrier.c"
#include "cancel.c"
#include "cleanup.c"
#include "condvar.c"
#include "create.c"
#include "dll.c"
#include "autostatic.c"
#include "errno.c"
#include "exit.c"
#include "fork.c"
#include "global.c"
#include "misc.c"
#include "mutex.c"
#include "nonportable.c"
#include "rwlock.c"
#include "sched.c"
#include "semaphore.c"
#include "signal.c"
#include "spin.c"
#include "sync.c"
#include "tsd.c"
| bsd-3-clause |
cesarmarinhorj/phantomjs | src/qt/qtbase/src/plugins/sqldrivers/sqlite2/smain.cpp | 84 | 2299 | /****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the plugins of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include <qsqldriverplugin.h>
#include <qstringlist.h>
#include "../../../../src/sql/drivers/sqlite2/qsql_sqlite2_p.h"
QT_BEGIN_NAMESPACE
class QSQLite2DriverPlugin : public QSqlDriverPlugin
{
Q_OBJECT
Q_PLUGIN_METADATA(IID "org.qt-project.Qt.QSqlDriverFactoryInterface" FILE "sqlite2.json")
public:
QSQLite2DriverPlugin();
QSqlDriver* create(const QString &);
};
QSQLite2DriverPlugin::QSQLite2DriverPlugin()
: QSqlDriverPlugin()
{
}
QSqlDriver* QSQLite2DriverPlugin::create(const QString &name)
{
if (name == QLatin1String("QSQLITE2")) {
QSQLite2Driver* driver = new QSQLite2Driver();
return driver;
}
return 0;
}
QT_END_NAMESPACE
#include "smain.moc"
| bsd-3-clause |
yoki/phantomjs | src/qt/qtbase/src/widgets/widgets/qfontcombobox.cpp | 84 | 17949 | /****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtWidgets module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qfontcombobox.h"
#ifndef QT_NO_FONTCOMBOBOX
#include <qstringlistmodel.h>
#include <qitemdelegate.h>
#include <qlistview.h>
#include <qpainter.h>
#include <qevent.h>
#include <qapplication.h>
#include <private/qcombobox_p.h>
#include <QDesktopWidget>
#include <qdebug.h>
#include <QtGui/private/qguiapplication_p.h>
#include <qpa/qplatformintegration.h>
#include <qpa/qplatformfontdatabase.h>
QT_BEGIN_NAMESPACE
static QFontDatabase::WritingSystem writingSystemFromScript(QLocale::Script script)
{
switch (script) {
case QLocale::ArabicScript:
return QFontDatabase::Arabic;
case QLocale::CyrillicScript:
return QFontDatabase::Cyrillic;
case QLocale::GurmukhiScript:
return QFontDatabase::Gurmukhi;
case QLocale::SimplifiedHanScript:
return QFontDatabase::SimplifiedChinese;
case QLocale::TraditionalHanScript:
return QFontDatabase::TraditionalChinese;
case QLocale::LatinScript:
return QFontDatabase::Latin;
case QLocale::ArmenianScript:
return QFontDatabase::Armenian;
case QLocale::BengaliScript:
return QFontDatabase::Bengali;
case QLocale::DevanagariScript:
return QFontDatabase::Devanagari;
case QLocale::GeorgianScript:
return QFontDatabase::Georgian;
case QLocale::GreekScript:
return QFontDatabase::Greek;
case QLocale::GujaratiScript:
return QFontDatabase::Gujarati;
case QLocale::HebrewScript:
return QFontDatabase::Hebrew;
case QLocale::JapaneseScript:
return QFontDatabase::Japanese;
case QLocale::KhmerScript:
return QFontDatabase::Khmer;
case QLocale::KannadaScript:
return QFontDatabase::Kannada;
case QLocale::KoreanScript:
return QFontDatabase::Korean;
case QLocale::LaoScript:
return QFontDatabase::Lao;
case QLocale::MalayalamScript:
return QFontDatabase::Malayalam;
case QLocale::MyanmarScript:
return QFontDatabase::Myanmar;
case QLocale::TamilScript:
return QFontDatabase::Tamil;
case QLocale::TeluguScript:
return QFontDatabase::Telugu;
case QLocale::ThaanaScript:
return QFontDatabase::Thaana;
case QLocale::ThaiScript:
return QFontDatabase::Thai;
case QLocale::TibetanScript:
return QFontDatabase::Tibetan;
case QLocale::SinhalaScript:
return QFontDatabase::Sinhala;
case QLocale::SyriacScript:
return QFontDatabase::Syriac;
case QLocale::OriyaScript:
return QFontDatabase::Oriya;
case QLocale::OghamScript:
return QFontDatabase::Ogham;
case QLocale::RunicScript:
return QFontDatabase::Runic;
case QLocale::NkoScript:
return QFontDatabase::Nko;
default:
return QFontDatabase::Any;
}
}
static QFontDatabase::WritingSystem writingSystemFromLocale()
{
QStringList uiLanguages = QLocale::system().uiLanguages();
QLocale::Script script;
if (!uiLanguages.isEmpty())
script = QLocale(uiLanguages.at(0)).script();
else
script = QLocale::system().script();
return writingSystemFromScript(script);
}
static QFontDatabase::WritingSystem writingSystemForFont(const QFont &font, bool *hasLatin)
{
QList<QFontDatabase::WritingSystem> writingSystems = QFontDatabase().writingSystems(font.family());
// qDebug() << font.family() << writingSystems;
// this just confuses the algorithm below. Vietnamese is Latin with lots of special chars
writingSystems.removeOne(QFontDatabase::Vietnamese);
*hasLatin = writingSystems.removeOne(QFontDatabase::Latin);
if (writingSystems.isEmpty())
return QFontDatabase::Any;
QFontDatabase::WritingSystem system = writingSystemFromLocale();
if (writingSystems.contains(system))
return system;
if (system == QFontDatabase::TraditionalChinese
&& writingSystems.contains(QFontDatabase::SimplifiedChinese)) {
return QFontDatabase::SimplifiedChinese;
}
if (system == QFontDatabase::SimplifiedChinese
&& writingSystems.contains(QFontDatabase::TraditionalChinese)) {
return QFontDatabase::TraditionalChinese;
}
system = writingSystems.last();
if (!*hasLatin) {
// we need to show something
return system;
}
if (writingSystems.count() == 1 && system > QFontDatabase::Cyrillic)
return system;
if (writingSystems.count() <= 2 && system > QFontDatabase::Armenian && system < QFontDatabase::Vietnamese)
return system;
if (writingSystems.count() <= 5 && system >= QFontDatabase::SimplifiedChinese && system <= QFontDatabase::Korean)
return system;
return QFontDatabase::Any;
}
class QFontFamilyDelegate : public QAbstractItemDelegate
{
Q_OBJECT
public:
explicit QFontFamilyDelegate(QObject *parent);
// painting
void paint(QPainter *painter,
const QStyleOptionViewItem &option,
const QModelIndex &index) const;
QSize sizeHint(const QStyleOptionViewItem &option,
const QModelIndex &index) const;
QIcon truetype;
QIcon bitmap;
QFontDatabase::WritingSystem writingSystem;
};
QFontFamilyDelegate::QFontFamilyDelegate(QObject *parent)
: QAbstractItemDelegate(parent)
{
truetype = QIcon(QLatin1String(":/qt-project.org/styles/commonstyle/images/fonttruetype-16.png"));
bitmap = QIcon(QLatin1String(":/qt-project.org/styles/commonstyle/images/fontbitmap-16.png"));
writingSystem = QFontDatabase::Any;
}
void QFontFamilyDelegate::paint(QPainter *painter,
const QStyleOptionViewItem &option,
const QModelIndex &index) const
{
QString text = index.data(Qt::DisplayRole).toString();
QFont font(option.font);
font.setPointSize(QFontInfo(font).pointSize() * 3 / 2);
QFont font2 = font;
font2.setFamily(text);
bool hasLatin;
QFontDatabase::WritingSystem system = writingSystemForFont(font2, &hasLatin);
if (hasLatin)
font = font2;
QRect r = option.rect;
if (option.state & QStyle::State_Selected) {
painter->save();
painter->setBrush(option.palette.highlight());
painter->setPen(Qt::NoPen);
painter->drawRect(option.rect);
painter->setPen(QPen(option.palette.highlightedText(), 0));
}
const QIcon *icon = &bitmap;
if (QFontDatabase().isSmoothlyScalable(text)) {
icon = &truetype;
}
QSize actualSize = icon->actualSize(r.size());
icon->paint(painter, r, Qt::AlignLeft|Qt::AlignVCenter);
if (option.direction == Qt::RightToLeft)
r.setRight(r.right() - actualSize.width() - 4);
else
r.setLeft(r.left() + actualSize.width() + 4);
QFont old = painter->font();
painter->setFont(font);
// If the ascent of the font is larger than the height of the rect,
// we will clip the text, so it's better to align the tight bounding rect in this case
// This is specifically for fonts where the ascent is very large compared to
// the descent, like certain of the Stix family.
QFontMetricsF fontMetrics(font);
if (fontMetrics.ascent() > r.height()) {
QRectF tbr = fontMetrics.tightBoundingRect(text);
painter->drawText(r.x(), r.y() + (r.height() + tbr.height()) / 2.0, text);
} else {
painter->drawText(r, Qt::AlignVCenter|Qt::AlignLeading|Qt::TextSingleLine, text);
}
if (writingSystem != QFontDatabase::Any)
system = writingSystem;
if (system != QFontDatabase::Any) {
int w = painter->fontMetrics().width(text + QLatin1String(" "));
painter->setFont(font2);
QString sample = QFontDatabase().writingSystemSample(system);
if (option.direction == Qt::RightToLeft)
r.setRight(r.right() - w);
else
r.setLeft(r.left() + w);
painter->drawText(r, Qt::AlignVCenter|Qt::AlignLeading|Qt::TextSingleLine, sample);
}
painter->setFont(old);
if (option.state & QStyle::State_Selected)
painter->restore();
}
QSize QFontFamilyDelegate::sizeHint(const QStyleOptionViewItem &option,
const QModelIndex &index) const
{
QString text = index.data(Qt::DisplayRole).toString();
QFont font(option.font);
// font.setFamily(text);
font.setPointSize(QFontInfo(font).pointSize() * 3/2);
QFontMetrics fontMetrics(font);
return QSize(fontMetrics.width(text), fontMetrics.height());
}
class QFontComboBoxPrivate : public QComboBoxPrivate
{
public:
inline QFontComboBoxPrivate() { filters = QFontComboBox::AllFonts; }
QFontComboBox::FontFilters filters;
QFont currentFont;
void _q_updateModel();
void _q_currentChanged(const QString &);
Q_DECLARE_PUBLIC(QFontComboBox)
};
void QFontComboBoxPrivate::_q_updateModel()
{
Q_Q(QFontComboBox);
const int scalableMask = (QFontComboBox::ScalableFonts | QFontComboBox::NonScalableFonts);
const int spacingMask = (QFontComboBox::ProportionalFonts | QFontComboBox::MonospacedFonts);
QStringListModel *m = qobject_cast<QStringListModel *>(q->model());
if (!m)
return;
QFontFamilyDelegate *delegate = qobject_cast<QFontFamilyDelegate *>(q->view()->itemDelegate());
QFontDatabase::WritingSystem system = delegate ? delegate->writingSystem : QFontDatabase::Any;
QFontDatabase fdb;
QStringList list = fdb.families(system);
QStringList result;
int offset = 0;
QFontInfo fi(currentFont);
QPlatformFontDatabase *pfdb = QGuiApplicationPrivate::platformIntegration()->fontDatabase();
for (int i = 0; i < list.size(); ++i) {
if (pfdb->isPrivateFontFamily(list.at(i)))
continue;
if ((filters & scalableMask) && (filters & scalableMask) != scalableMask) {
if (bool(filters & QFontComboBox::ScalableFonts) != fdb.isSmoothlyScalable(list.at(i)))
continue;
}
if ((filters & spacingMask) && (filters & spacingMask) != spacingMask) {
if (bool(filters & QFontComboBox::MonospacedFonts) != fdb.isFixedPitch(list.at(i)))
continue;
}
result += list.at(i);
if (list.at(i) == fi.family() || list.at(i).startsWith(fi.family() + QLatin1String(" [")))
offset = result.count() - 1;
}
list = result;
//we need to block the signals so that the model doesn't emit reset
//this prevents the current index from changing
//it will be updated just after this
///TODO: we should finda way to avoid blocking signals and have a real update of the model
{
const QSignalBlocker blocker(m);
m->setStringList(list);
}
if (list.isEmpty()) {
if (currentFont != QFont()) {
currentFont = QFont();
emit q->currentFontChanged(currentFont);
}
} else {
q->setCurrentIndex(offset);
}
}
void QFontComboBoxPrivate::_q_currentChanged(const QString &text)
{
Q_Q(QFontComboBox);
if (currentFont.family() != text) {
currentFont.setFamily(text);
emit q->currentFontChanged(currentFont);
}
}
/*!
\class QFontComboBox
\brief The QFontComboBox widget is a combobox that lets the user
select a font family.
\since 4.2
\ingroup basicwidgets
\inmodule QtWidgets
The combobox is populated with an alphabetized list of font
family names, such as Arial, Helvetica, and Times New Roman.
Family names are displayed using the actual font when possible.
For fonts such as Symbol, where the name is not representable in
the font itself, a sample of the font is displayed next to the
family name.
QFontComboBox is often used in toolbars, in conjunction with a
QComboBox for controlling the font size and two \l{QToolButton}s
for bold and italic.
When the user selects a new font, the currentFontChanged() signal
is emitted in addition to currentIndexChanged().
Call setWritingSystem() to tell QFontComboBox to show only fonts
that support a given writing system, and setFontFilters() to
filter out certain types of fonts as e.g. non scalable fonts or
monospaced fonts.
\image windowsvista-fontcombobox.png Screenshot of QFontComboBox on Windows Vista
\sa QComboBox, QFont, QFontInfo, QFontMetrics, QFontDatabase, {Character Map Example}
*/
/*!
\fn void QFontComboBox::setWritingSystem(QFontDatabase::WritingSystem script)
*/
/*!
\fn void QFontComboBox::setCurrentFont(const QFont &font);
*/
/*!
Constructs a font combobox with the given \a parent.
*/
QFontComboBox::QFontComboBox(QWidget *parent)
: QComboBox(*new QFontComboBoxPrivate, parent)
{
Q_D(QFontComboBox);
d->currentFont = font();
setEditable(true);
QStringListModel *m = new QStringListModel(this);
setModel(m);
setItemDelegate(new QFontFamilyDelegate(this));
QListView *lview = qobject_cast<QListView*>(view());
if (lview)
lview->setUniformItemSizes(true);
setWritingSystem(QFontDatabase::Any);
connect(this, SIGNAL(currentIndexChanged(QString)),
this, SLOT(_q_currentChanged(QString)));
connect(qApp, SIGNAL(fontDatabaseChanged()),
this, SLOT(_q_updateModel()));
}
/*!
Destroys the combobox.
*/
QFontComboBox::~QFontComboBox()
{
}
/*!
\property QFontComboBox::writingSystem
\brief the writing system that serves as a filter for the combobox
If \a script is QFontDatabase::Any (the default), all fonts are
listed.
\sa fontFilters
*/
void QFontComboBox::setWritingSystem(QFontDatabase::WritingSystem script)
{
Q_D(QFontComboBox);
QFontFamilyDelegate *delegate = qobject_cast<QFontFamilyDelegate *>(view()->itemDelegate());
if (delegate)
delegate->writingSystem = script;
d->_q_updateModel();
}
QFontDatabase::WritingSystem QFontComboBox::writingSystem() const
{
QFontFamilyDelegate *delegate = qobject_cast<QFontFamilyDelegate *>(view()->itemDelegate());
if (delegate)
return delegate->writingSystem;
return QFontDatabase::Any;
}
/*!
\enum QFontComboBox::FontFilter
This enum can be used to only show certain types of fonts in the font combo box.
\value AllFonts Show all fonts
\value ScalableFonts Show scalable fonts
\value NonScalableFonts Show non scalable fonts
\value MonospacedFonts Show monospaced fonts
\value ProportionalFonts Show proportional fonts
*/
/*!
\property QFontComboBox::fontFilters
\brief the filter for the combobox
By default, all fonts are listed.
\sa writingSystem
*/
void QFontComboBox::setFontFilters(FontFilters filters)
{
Q_D(QFontComboBox);
d->filters = filters;
d->_q_updateModel();
}
QFontComboBox::FontFilters QFontComboBox::fontFilters() const
{
Q_D(const QFontComboBox);
return d->filters;
}
/*!
\property QFontComboBox::currentFont
\brief the currently selected font
\sa currentIndex, currentText
*/
QFont QFontComboBox::currentFont() const
{
Q_D(const QFontComboBox);
return d->currentFont;
}
void QFontComboBox::setCurrentFont(const QFont &font)
{
Q_D(QFontComboBox);
if (font != d->currentFont) {
d->currentFont = font;
d->_q_updateModel();
if (d->currentFont == font) { //else the signal has already be emitted by _q_updateModel
emit currentFontChanged(d->currentFont);
}
}
}
/*!
\fn QFontComboBox::currentFontChanged(const QFont &font)
This signal is emitted whenever the current font changes, with
the new \a font.
\sa currentFont
*/
/*!
\reimp
*/
bool QFontComboBox::event(QEvent *e)
{
if (e->type() == QEvent::Resize) {
QListView *lview = qobject_cast<QListView*>(view());
if (lview) {
lview->window()->setFixedWidth(qMin(width() * 5 / 3,
QApplication::desktop()->availableGeometry(lview).width()));
}
}
return QComboBox::event(e);
}
/*!
\reimp
*/
QSize QFontComboBox::sizeHint() const
{
QSize sz = QComboBox::sizeHint();
QFontMetrics fm(font());
sz.setWidth(fm.width(QLatin1Char('m'))*14);
return sz;
}
QT_END_NAMESPACE
#include "qfontcombobox.moc"
#include "moc_qfontcombobox.cpp"
#endif // QT_NO_FONTCOMBOBOX
| bsd-3-clause |
StevenBlack/phantomjs | src/qt/qtbase/src/corelib/tools/qtimeline.cpp | 84 | 23777 | /****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtCore module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qtimeline.h"
#include <private/qobject_p.h>
#include <QtCore/qcoreevent.h>
#include <QtCore/qmath.h>
#include <QtCore/qelapsedtimer.h>
QT_BEGIN_NAMESPACE
class QTimeLinePrivate : public QObjectPrivate
{
Q_DECLARE_PUBLIC(QTimeLine)
public:
inline QTimeLinePrivate()
: easingCurve(QEasingCurve::InOutSine),
startTime(0), duration(1000), startFrame(0), endFrame(0),
updateInterval(1000 / 25),
totalLoopCount(1), currentLoopCount(0), currentTime(0), timerId(0),
direction(QTimeLine::Forward),
state(QTimeLine::NotRunning)
{ }
QElapsedTimer timer;
QEasingCurve easingCurve;
int startTime;
int duration;
int startFrame;
int endFrame;
int updateInterval;
int totalLoopCount;
int currentLoopCount;
int currentTime;
int timerId;
QTimeLine::Direction direction;
QTimeLine::State state;
inline void setState(QTimeLine::State newState)
{
Q_Q(QTimeLine);
if (newState != state)
emit q->stateChanged(state = newState, QTimeLine::QPrivateSignal());
}
void setCurrentTime(int msecs);
};
/*!
\internal
*/
void QTimeLinePrivate::setCurrentTime(int msecs)
{
Q_Q(QTimeLine);
qreal lastValue = q->currentValue();
int lastFrame = q->currentFrame();
// Determine if we are looping.
int elapsed = (direction == QTimeLine::Backward) ? (-msecs + duration) : msecs;
int loopCount = elapsed / duration;
bool looping = (loopCount != currentLoopCount);
#ifdef QTIMELINE_DEBUG
qDebug() << "QTimeLinePrivate::setCurrentTime:" << msecs << duration << "with loopCount" << loopCount
<< "currentLoopCount" << currentLoopCount
<< "looping" << looping;
#endif
if (looping)
currentLoopCount = loopCount;
// Normalize msecs to be between 0 and duration, inclusive.
currentTime = elapsed % duration;
if (direction == QTimeLine::Backward)
currentTime = duration - currentTime;
// Check if we have reached the end of loopcount.
bool finished = false;
if (totalLoopCount && currentLoopCount >= totalLoopCount) {
finished = true;
currentTime = (direction == QTimeLine::Backward) ? 0 : duration;
currentLoopCount = totalLoopCount - 1;
}
int currentFrame = q->frameForTime(currentTime);
#ifdef QTIMELINE_DEBUG
qDebug() << "QTimeLinePrivate::setCurrentTime: frameForTime" << currentTime << currentFrame;
#endif
if (!qFuzzyCompare(lastValue, q->currentValue()))
emit q->valueChanged(q->currentValue(), QTimeLine::QPrivateSignal());
if (lastFrame != currentFrame) {
const int transitionframe = (direction == QTimeLine::Forward ? endFrame : startFrame);
if (looping && !finished && transitionframe != currentFrame) {
#ifdef QTIMELINE_DEBUG
qDebug() << "QTimeLinePrivate::setCurrentTime: transitionframe";
#endif
emit q->frameChanged(transitionframe, QTimeLine::QPrivateSignal());
}
#ifdef QTIMELINE_DEBUG
else {
QByteArray reason;
if (!looping)
reason += " not looping";
if (finished) {
if (!reason.isEmpty())
reason += " and";
reason += " finished";
}
if (transitionframe == currentFrame) {
if (!reason.isEmpty())
reason += " and";
reason += " transitionframe is equal to currentFrame: " + QByteArray::number(currentFrame);
}
qDebug("QTimeLinePrivate::setCurrentTime: not transitionframe because %s", reason.constData());
}
#endif
emit q->frameChanged(currentFrame, QTimeLine::QPrivateSignal());
}
if (finished && state == QTimeLine::Running) {
q->stop();
emit q->finished(QTimeLine::QPrivateSignal());
}
}
/*!
\class QTimeLine
\inmodule QtCore
\brief The QTimeLine class provides a timeline for controlling animations.
\since 4.2
\ingroup animation
It's most commonly used to animate a GUI control by calling a slot
periodically. You can construct a timeline by passing its duration in
milliseconds to QTimeLine's constructor. The timeline's duration describes
for how long the animation will run. Then you set a suitable frame range
by calling setFrameRange(). Finally connect the frameChanged() signal to a
suitable slot in the widget you wish to animate (for example, \l {QProgressBar::}{setValue()}
in QProgressBar). When you proceed to calling start(), QTimeLine will enter
Running state, and start emitting frameChanged() at regular intervals,
causing your widget's connected property's value to grow from the lower
end to the upper and of your frame range, at a steady rate. You can
specify the update interval by calling setUpdateInterval(). When done,
QTimeLine enters NotRunning state, and emits finished().
Example:
\snippet code/src_corelib_tools_qtimeline.cpp 0
By default the timeline runs once, from the beginning and towards the end,
upon which you must call start() again to restart from the beginning. To
make the timeline loop, you can call setLoopCount(), passing the number of
times the timeline should run before finishing. The direction can also be
changed, causing the timeline to run backward, by calling
setDirection(). You can also pause and unpause the timeline while it's
running by calling setPaused(). For interactive control, the
setCurrentTime() function is provided, which sets the time position of the
time line directly. Although most useful in NotRunning state, (e.g.,
connected to a valueChanged() signal in a QSlider,) this function can be
called at any time.
The frame interface is useful for standard widgets, but QTimeLine can be
used to control any type of animation. The heart of QTimeLine lies in the
valueForTime() function, which generates a \e value between 0 and 1 for a
given time. This value is typically used to describe the steps of an
animation, where 0 is the first step of an animation, and 1 is the last
step. When running, QTimeLine generates values between 0 and 1 by calling
valueForTime() and emitting valueChanged(). By default, valueForTime()
applies an interpolation algorithm to generate these value. You can choose
from a set of predefined timeline algorithms by calling
setCurveShape().
Note that by default, QTimeLine uses the EaseInOut curve shape,
which provides a value that grows slowly, then grows steadily, and
finally grows slowly. For a custom timeline, you can reimplement
valueForTime(), in which case QTimeLine's curveShape property is ignored.
\sa QProgressBar, QProgressDialog
*/
/*!
\enum QTimeLine::State
This enum describes the state of the timeline.
\value NotRunning The timeline is not running. This is the initial state
of QTimeLine, and the state QTimeLine reenters when finished. The current
time, frame and value remain unchanged until either setCurrentTime() is
called, or the timeline is started by calling start().
\value Paused The timeline is paused (i.e., temporarily
suspended). Calling setPaused(false) will resume timeline activity.
\value Running The timeline is running. While control is in the event
loop, QTimeLine will update its current time at regular intervals,
emitting valueChanged() and frameChanged() when appropriate.
\sa state(), stateChanged()
*/
/*!
\enum QTimeLine::Direction
This enum describes the direction of the timeline when in \l Running state.
\value Forward The current time of the timeline increases with time (i.e.,
moves from 0 and towards the end / duration).
\value Backward The current time of the timeline decreases with time (i.e.,
moves from the end / duration and towards 0).
\sa setDirection()
*/
/*!
\enum QTimeLine::CurveShape
This enum describes the default shape of QTimeLine's value curve. The
default, shape is EaseInOutCurve. The curve defines the relation
between the value and the timeline.
\value EaseInCurve The value starts growing slowly, then increases in speed.
\value EaseOutCurve The value starts growing steadily, then ends slowly.
\value EaseInOutCurve The value starts growing slowly, then runs steadily, then grows slowly again.
\value LinearCurve The value grows linearly (e.g., if the duration is 1000 ms,
the value at time 500 ms is 0.5).
\value SineCurve The value grows sinusoidally.
\value CosineCurve The value grows cosinusoidally.
\sa setCurveShape()
*/
/*!
\fn QTimeLine::valueChanged(qreal value)
QTimeLine emits this signal at regular intervals when in \l Running state,
but only if the current value changes. \a value is the current value. \a value is
a number between 0.0 and 1.0
\sa QTimeLine::setDuration(), QTimeLine::valueForTime(), QTimeLine::updateInterval
*/
/*!
\fn QTimeLine::frameChanged(int frame)
QTimeLine emits this signal at regular intervals when in \l Running state,
but only if the current frame changes. \a frame is the current frame number.
\sa QTimeLine::setFrameRange(), QTimeLine::updateInterval
*/
/*!
\fn QTimeLine::stateChanged(QTimeLine::State newState)
This signal is emitted whenever QTimeLine's state changes. The new state
is \a newState.
*/
/*!
\fn QTimeLine::finished()
This signal is emitted when QTimeLine finishes (i.e., reaches the end of
its time line), and does not loop.
*/
/*!
Constructs a timeline with a duration of \a duration milliseconds. \a
parent is passed to QObject's constructor. The default duration is 1000
milliseconds.
*/
QTimeLine::QTimeLine(int duration, QObject *parent)
: QObject(*new QTimeLinePrivate, parent)
{
setDuration(duration);
}
/*!
Destroys the timeline.
*/
QTimeLine::~QTimeLine()
{
Q_D(QTimeLine);
if (d->state == Running)
stop();
}
/*!
Returns the state of the timeline.
\sa start(), setPaused(), stop()
*/
QTimeLine::State QTimeLine::state() const
{
Q_D(const QTimeLine);
return d->state;
}
/*!
\property QTimeLine::loopCount
\brief the number of times the timeline should loop before it's finished.
A loop count of of 0 means that the timeline will loop forever.
By default, this property contains a value of 1.
*/
int QTimeLine::loopCount() const
{
Q_D(const QTimeLine);
return d->totalLoopCount;
}
void QTimeLine::setLoopCount(int count)
{
Q_D(QTimeLine);
d->totalLoopCount = count;
}
/*!
\property QTimeLine::direction
\brief the direction of the timeline when QTimeLine is in \l Running
state.
This direction indicates whether the time moves from 0 towards the
timeline duration, or from the value of the duration and towards 0 after
start() has been called.
By default, this property is set to \l Forward.
*/
QTimeLine::Direction QTimeLine::direction() const
{
Q_D(const QTimeLine);
return d->direction;
}
void QTimeLine::setDirection(Direction direction)
{
Q_D(QTimeLine);
d->direction = direction;
d->startTime = d->currentTime;
d->timer.start();
}
/*!
\property QTimeLine::duration
\brief the total duration of the timeline in milliseconds.
By default, this value is 1000 (i.e., 1 second), but you can change this
by either passing a duration to QTimeLine's constructor, or by calling
setDuration(). The duration must be larger than 0.
\note Changing the duration does not cause the current time to be reset
to zero or the new duration. You also need to call setCurrentTime() with
the desired value.
*/
int QTimeLine::duration() const
{
Q_D(const QTimeLine);
return d->duration;
}
void QTimeLine::setDuration(int duration)
{
Q_D(QTimeLine);
if (duration <= 0) {
qWarning("QTimeLine::setDuration: cannot set duration <= 0");
return;
}
d->duration = duration;
}
/*!
Returns the start frame, which is the frame corresponding to the start of
the timeline (i.e., the frame for which the current value is 0).
\sa setStartFrame(), setFrameRange()
*/
int QTimeLine::startFrame() const
{
Q_D(const QTimeLine);
return d->startFrame;
}
/*!
Sets the start frame, which is the frame corresponding to the start of the
timeline (i.e., the frame for which the current value is 0), to \a frame.
\sa startFrame(), endFrame(), setFrameRange()
*/
void QTimeLine::setStartFrame(int frame)
{
Q_D(QTimeLine);
d->startFrame = frame;
}
/*!
Returns the end frame, which is the frame corresponding to the end of the
timeline (i.e., the frame for which the current value is 1).
\sa setEndFrame(), setFrameRange()
*/
int QTimeLine::endFrame() const
{
Q_D(const QTimeLine);
return d->endFrame;
}
/*!
Sets the end frame, which is the frame corresponding to the end of the
timeline (i.e., the frame for which the current value is 1), to \a frame.
\sa endFrame(), startFrame(), setFrameRange()
*/
void QTimeLine::setEndFrame(int frame)
{
Q_D(QTimeLine);
d->endFrame = frame;
}
/*!
Sets the timeline's frame counter to start at \a startFrame, and end and
\a endFrame. For each time value, QTimeLine will find the corresponding
frame when you call currentFrame() or frameForTime() by interpolating,
using the return value of valueForTime().
When in Running state, QTimeLine also emits the frameChanged() signal when
the frame changes.
\sa startFrame(), endFrame(), start(), currentFrame()
*/
void QTimeLine::setFrameRange(int startFrame, int endFrame)
{
Q_D(QTimeLine);
d->startFrame = startFrame;
d->endFrame = endFrame;
}
/*!
\property QTimeLine::updateInterval
\brief the time in milliseconds between each time QTimeLine updates its
current time.
When updating the current time, QTimeLine will emit valueChanged() if the
current value changed, and frameChanged() if the frame changed.
By default, the interval is 40 ms, which corresponds to a rate of 25
updates per second.
*/
int QTimeLine::updateInterval() const
{
Q_D(const QTimeLine);
return d->updateInterval;
}
void QTimeLine::setUpdateInterval(int interval)
{
Q_D(QTimeLine);
d->updateInterval = interval;
}
/*!
\property QTimeLine::curveShape
\brief the shape of the timeline curve.
The curve shape describes the relation between the time and value for the
base implementation of valueForTime().
If you have reimplemented valueForTime(), this value is ignored.
By default, this property is set to \l EaseInOutCurve.
\sa valueForTime()
*/
QTimeLine::CurveShape QTimeLine::curveShape() const
{
Q_D(const QTimeLine);
switch (d->easingCurve.type()) {
default:
case QEasingCurve::InOutSine:
return EaseInOutCurve;
case QEasingCurve::InCurve:
return EaseInCurve;
case QEasingCurve::OutCurve:
return EaseOutCurve;
case QEasingCurve::Linear:
return LinearCurve;
case QEasingCurve::SineCurve:
return SineCurve;
case QEasingCurve::CosineCurve:
return CosineCurve;
}
return EaseInOutCurve;
}
void QTimeLine::setCurveShape(CurveShape shape)
{
switch (shape) {
default:
case EaseInOutCurve:
setEasingCurve(QEasingCurve(QEasingCurve::InOutSine));
break;
case EaseInCurve:
setEasingCurve(QEasingCurve(QEasingCurve::InCurve));
break;
case EaseOutCurve:
setEasingCurve(QEasingCurve(QEasingCurve::OutCurve));
break;
case LinearCurve:
setEasingCurve(QEasingCurve(QEasingCurve::Linear));
break;
case SineCurve:
setEasingCurve(QEasingCurve(QEasingCurve::SineCurve));
break;
case CosineCurve:
setEasingCurve(QEasingCurve(QEasingCurve::CosineCurve));
break;
}
}
/*!
\property QTimeLine::easingCurve
\since 4.6
Specifies the easing curve that the timeline will use.
If both easing curve and curveShape are set, the last set property will
override the previous one. (If valueForTime() is reimplemented it will
override both)
*/
QEasingCurve QTimeLine::easingCurve() const
{
Q_D(const QTimeLine);
return d->easingCurve;
}
void QTimeLine::setEasingCurve(const QEasingCurve& curve)
{
Q_D(QTimeLine);
d->easingCurve = curve;
}
/*!
\property QTimeLine::currentTime
\brief the current time of the time line.
When QTimeLine is in Running state, this value is updated continuously as
a function of the duration and direction of the timeline. Otherwise, it is
value that was current when stop() was called last, or the value set by
setCurrentTime().
By default, this property contains a value of 0.
*/
int QTimeLine::currentTime() const
{
Q_D(const QTimeLine);
return d->currentTime;
}
void QTimeLine::setCurrentTime(int msec)
{
Q_D(QTimeLine);
d->startTime = 0;
d->currentLoopCount = 0;
d->timer.restart();
d->setCurrentTime(msec);
}
/*!
Returns the frame corresponding to the current time.
\sa currentTime(), frameForTime(), setFrameRange()
*/
int QTimeLine::currentFrame() const
{
Q_D(const QTimeLine);
return frameForTime(d->currentTime);
}
/*!
Returns the value corresponding to the current time.
\sa valueForTime(), currentFrame()
*/
qreal QTimeLine::currentValue() const
{
Q_D(const QTimeLine);
return valueForTime(d->currentTime);
}
/*!
Returns the frame corresponding to the time \a msec. This value is
calculated using a linear interpolation of the start and end frame, based
on the value returned by valueForTime().
\sa valueForTime(), setFrameRange()
*/
int QTimeLine::frameForTime(int msec) const
{
Q_D(const QTimeLine);
if (d->direction == Forward)
return d->startFrame + int((d->endFrame - d->startFrame) * valueForTime(msec));
return d->startFrame + qCeil((d->endFrame - d->startFrame) * valueForTime(msec));
}
/*!
Returns the timeline value for the time \a msec. The returned value, which
varies depending on the curve shape, is always between 0 and 1. If \a msec
is 0, the default implementation always returns 0.
Reimplement this function to provide a custom curve shape for your
timeline.
\sa CurveShape, frameForTime()
*/
qreal QTimeLine::valueForTime(int msec) const
{
Q_D(const QTimeLine);
msec = qMin(qMax(msec, 0), d->duration);
qreal value = msec / qreal(d->duration);
return d->easingCurve.valueForProgress(value);
}
/*!
Starts the timeline. QTimeLine will enter Running state, and once it
enters the event loop, it will update its current time, frame and value at
regular intervals. The default interval is 40 ms (i.e., 25 times per
second). You can change the update interval by calling
setUpdateInterval().
The timeline will start from position 0, or the end if going backward.
If you want to resume a stopped timeline without restarting, you can call
resume() instead.
\sa resume(), updateInterval(), frameChanged(), valueChanged()
*/
void QTimeLine::start()
{
Q_D(QTimeLine);
if (d->timerId) {
qWarning("QTimeLine::start: already running");
return;
}
int curTime = 0;
if (d->direction == Backward)
curTime = d->duration;
d->timerId = startTimer(d->updateInterval);
d->startTime = curTime;
d->currentLoopCount = 0;
d->timer.start();
d->setState(Running);
d->setCurrentTime(curTime);
}
/*!
Resumes the timeline from the current time. QTimeLine will reenter Running
state, and once it enters the event loop, it will update its current time,
frame and value at regular intervals.
In contrast to start(), this function does not restart the timeline before
it resumes.
\sa start(), updateInterval(), frameChanged(), valueChanged()
*/
void QTimeLine::resume()
{
Q_D(QTimeLine);
if (d->timerId) {
qWarning("QTimeLine::resume: already running");
return;
}
d->timerId = startTimer(d->updateInterval);
d->startTime = d->currentTime;
d->timer.start();
d->setState(Running);
}
/*!
Stops the timeline, causing QTimeLine to enter NotRunning state.
\sa start()
*/
void QTimeLine::stop()
{
Q_D(QTimeLine);
if (d->timerId)
killTimer(d->timerId);
d->setState(NotRunning);
d->timerId = 0;
}
/*!
If \a paused is true, the timeline is paused, causing QTimeLine to enter
Paused state. No updates will be signaled until either start() or
setPaused(false) is called. If \a paused is false, the timeline is resumed
and continues where it left.
\sa state(), start()
*/
void QTimeLine::setPaused(bool paused)
{
Q_D(QTimeLine);
if (d->state == NotRunning) {
qWarning("QTimeLine::setPaused: Not running");
return;
}
if (paused && d->state != Paused) {
d->startTime = d->currentTime;
killTimer(d->timerId);
d->timerId = 0;
d->setState(Paused);
} else if (!paused && d->state == Paused) {
// Same as resume()
d->timerId = startTimer(d->updateInterval);
d->startTime = d->currentTime;
d->timer.start();
d->setState(Running);
}
}
/*!
Toggles the direction of the timeline. If the direction was Forward, it
becomes Backward, and vice verca.
\sa setDirection()
*/
void QTimeLine::toggleDirection()
{
Q_D(QTimeLine);
setDirection(d->direction == Forward ? Backward : Forward);
}
/*!
\reimp
*/
void QTimeLine::timerEvent(QTimerEvent *event)
{
Q_D(QTimeLine);
if (event->timerId() != d->timerId) {
event->ignore();
return;
}
event->accept();
if (d->direction == Forward) {
d->setCurrentTime(d->startTime + d->timer.elapsed());
} else {
d->setCurrentTime(d->startTime - d->timer.elapsed());
}
}
QT_END_NAMESPACE
| bsd-3-clause |
rishilification/phantomjs | src/qt/qtbase/src/network/access/qnetworkrequest.cpp | 84 | 34861 | /****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtNetwork module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qnetworkrequest.h"
#include "qnetworkrequest_p.h"
#include "qplatformdefs.h"
#include "qnetworkcookie.h"
#include "qsslconfiguration.h"
#include "QtCore/qshareddata.h"
#include "QtCore/qlocale.h"
#include "QtCore/qdatetime.h"
#include <ctype.h>
#ifndef QT_NO_DATESTRING
# include <stdio.h>
#endif
QT_BEGIN_NAMESPACE
/*!
\class QNetworkRequest
\since 4.4
\ingroup network
\ingroup shared
\inmodule QtNetwork
\brief The QNetworkRequest class holds a request to be sent with QNetworkAccessManager.
QNetworkRequest is part of the Network Access API and is the class
holding the information necessary to send a request over the
network. It contains a URL and some ancillary information that can
be used to modify the request.
\sa QNetworkReply, QNetworkAccessManager
*/
/*!
\enum QNetworkRequest::KnownHeaders
List of known header types that QNetworkRequest parses. Each known
header is also represented in raw form with its full HTTP name.
\value ContentDispositionHeader Corresponds to the HTTP
Content-Disposition header and contains a string containing the
disposition type (for instance, attachment) and a parameter (for
instance, filename).
\value ContentTypeHeader Corresponds to the HTTP Content-Type
header and contains a string containing the media (MIME) type and
any auxiliary data (for instance, charset).
\value ContentLengthHeader Corresponds to the HTTP Content-Length
header and contains the length in bytes of the data transmitted.
\value LocationHeader Corresponds to the HTTP Location
header and contains a URL representing the actual location of the
data, including the destination URL in case of redirections.
\value LastModifiedHeader Corresponds to the HTTP Last-Modified
header and contains a QDateTime representing the last modification
date of the contents.
\value CookieHeader Corresponds to the HTTP Cookie header
and contains a QList<QNetworkCookie> representing the cookies to
be sent back to the server.
\value SetCookieHeader Corresponds to the HTTP Set-Cookie
header and contains a QList<QNetworkCookie> representing the
cookies sent by the server to be stored locally.
\value UserAgentHeader The User-Agent header sent by HTTP clients.
\value ServerHeader The Server header received by HTTP clients.
\sa header(), setHeader(), rawHeader(), setRawHeader()
*/
/*!
\enum QNetworkRequest::Attribute
\since 4.7
Attribute codes for the QNetworkRequest and QNetworkReply.
Attributes are extra meta-data that are used to control the
behavior of the request and to pass further information from the
reply back to the application. Attributes are also extensible,
allowing custom implementations to pass custom values.
The following table explains what the default attribute codes are,
the QVariant types associated, the default value if said attribute
is missing and whether it's used in requests or replies.
\value HttpStatusCodeAttribute
Replies only, type: QMetaType::Int (no default)
Indicates the HTTP status code received from the HTTP server
(like 200, 304, 404, 401, etc.). If the connection was not
HTTP-based, this attribute will not be present.
\value HttpReasonPhraseAttribute
Replies only, type: QMetaType::QByteArray (no default)
Indicates the HTTP reason phrase as received from the HTTP
server (like "Ok", "Found", "Not Found", "Access Denied",
etc.) This is the human-readable representation of the status
code (see above). If the connection was not HTTP-based, this
attribute will not be present.
\value RedirectionTargetAttribute
Replies only, type: QMetaType::QUrl (no default)
If present, it indicates that the server is redirecting the
request to a different URL. The Network Access API does not by
default follow redirections: it's up to the application to
determine if the requested redirection should be allowed,
according to its security policies.
The returned URL might be relative. Use QUrl::resolved()
to create an absolute URL out of it.
\value ConnectionEncryptedAttribute
Replies only, type: QMetaType::Bool (default: false)
Indicates whether the data was obtained through an encrypted
(secure) connection.
\value CacheLoadControlAttribute
Requests only, type: QMetaType::Int (default: QNetworkRequest::PreferNetwork)
Controls how the cache should be accessed. The possible values
are those of QNetworkRequest::CacheLoadControl. Note that the
default QNetworkAccessManager implementation does not support
caching. However, this attribute may be used by certain
backends to modify their requests (for example, for caching proxies).
\value CacheSaveControlAttribute
Requests only, type: QMetaType::Bool (default: true)
Controls if the data obtained should be saved to cache for
future uses. If the value is false, the data obtained will not
be automatically cached. If true, data may be cached, provided
it is cacheable (what is cacheable depends on the protocol
being used).
\value SourceIsFromCacheAttribute
Replies only, type: QMetaType::Bool (default: false)
Indicates whether the data was obtained from cache
or not.
\value DoNotBufferUploadDataAttribute
Requests only, type: QMetaType::Bool (default: false)
Indicates whether the QNetworkAccessManager code is
allowed to buffer the upload data, e.g. when doing a HTTP POST.
When using this flag with sequential upload data, the ContentLengthHeader
header must be set.
\value HttpPipeliningAllowedAttribute
Requests only, type: QMetaType::Bool (default: false)
Indicates whether the QNetworkAccessManager code is
allowed to use HTTP pipelining with this request.
\value HttpPipeliningWasUsedAttribute
Replies only, type: QMetaType::Bool
Indicates whether the HTTP pipelining was used for receiving
this reply.
\value CustomVerbAttribute
Requests only, type: QMetaType::QByteArray
Holds the value for the custom HTTP verb to send (destined for usage
of other verbs than GET, POST, PUT and DELETE). This verb is set
when calling QNetworkAccessManager::sendCustomRequest().
\value CookieLoadControlAttribute
Requests only, type: QMetaType::Int (default: QNetworkRequest::Automatic)
Indicates whether to send 'Cookie' headers in the request.
This attribute is set to false by Qt WebKit when creating a cross-origin
XMLHttpRequest where withCredentials has not been set explicitly to true by the
Javascript that created the request.
See \l{http://www.w3.org/TR/XMLHttpRequest2/#credentials-flag}{here} for more information.
(This value was introduced in 4.7.)
\value CookieSaveControlAttribute
Requests only, type: QMetaType::Int (default: QNetworkRequest::Automatic)
Indicates whether to save 'Cookie' headers received from the server in reply
to the request.
This attribute is set to false by Qt WebKit when creating a cross-origin
XMLHttpRequest where withCredentials has not been set explicitly to true by the
Javascript that created the request.
See \l{http://www.w3.org/TR/XMLHttpRequest2/#credentials-flag} {here} for more information.
(This value was introduced in 4.7.)
\value AuthenticationReuseAttribute
Requests only, type: QMetaType::Int (default: QNetworkRequest::Automatic)
Indicates whether to use cached authorization credentials in the request,
if available. If this is set to QNetworkRequest::Manual and the authentication
mechanism is 'Basic' or 'Digest', Qt will not send an an 'Authorization' HTTP
header with any cached credentials it may have for the request's URL.
This attribute is set to QNetworkRequest::Manual by Qt WebKit when creating a cross-origin
XMLHttpRequest where withCredentials has not been set explicitly to true by the
Javascript that created the request.
See \l{http://www.w3.org/TR/XMLHttpRequest2/#credentials-flag} {here} for more information.
(This value was introduced in 4.7.)
\omitvalue MaximumDownloadBufferSizeAttribute
\omitvalue DownloadBufferAttribute
\omitvalue SynchronousRequestAttribute
\value BackgroundRequestAttribute
Type: QMetaType::Bool (default: false)
Indicates that this is a background transfer, rather than a user initiated
transfer. Depending on the platform, background transfers may be subject
to different policies.
The QNetworkSession ConnectInBackground property will be set according to
this attribute.
\value SpdyAllowedAttribute
Requests only, type: QMetaType::Bool (default: false)
Indicates whether the QNetworkAccessManager code is
allowed to use SPDY with this request. This applies only
to SSL requests, and depends on the server supporting SPDY.
\value SpdyWasUsedAttribute
Replies only, type: QMetaType::Bool
Indicates whether SPDY was used for receiving
this reply.
\value User
Special type. Additional information can be passed in
QVariants with types ranging from User to UserMax. The default
implementation of Network Access will ignore any request
attributes in this range and it will not produce any
attributes in this range in replies. The range is reserved for
extensions of QNetworkAccessManager.
\value UserMax
Special type. See User.
*/
/*!
\enum QNetworkRequest::CacheLoadControl
Controls the caching mechanism of QNetworkAccessManager.
\value AlwaysNetwork always load from network and do not
check if the cache has a valid entry (similar to the
"Reload" feature in browsers); in addition, force intermediate
caches to re-validate.
\value PreferNetwork default value; load from the network
if the cached entry is older than the network entry. This will never
return stale data from the cache, but revalidate resources that
have become stale.
\value PreferCache load from cache if available,
otherwise load from network. Note that this can return possibly
stale (but not expired) items from cache.
\value AlwaysCache only load from cache, indicating error
if the item was not cached (i.e., off-line mode)
*/
/*!
\enum QNetworkRequest::LoadControl
\since 4.7
Indicates if an aspect of the request's loading mechanism has been
manually overridden, e.g. by Qt WebKit.
\value Automatic default value: indicates default behaviour.
\value Manual indicates behaviour has been manually overridden.
*/
class QNetworkRequestPrivate: public QSharedData, public QNetworkHeadersPrivate
{
public:
inline QNetworkRequestPrivate()
: priority(QNetworkRequest::NormalPriority)
#ifndef QT_NO_SSL
, sslConfiguration(0)
#endif
{ qRegisterMetaType<QNetworkRequest>(); }
~QNetworkRequestPrivate()
{
#ifndef QT_NO_SSL
delete sslConfiguration;
#endif
}
QNetworkRequestPrivate(const QNetworkRequestPrivate &other)
: QSharedData(other), QNetworkHeadersPrivate(other)
{
url = other.url;
priority = other.priority;
#ifndef QT_NO_SSL
sslConfiguration = 0;
if (other.sslConfiguration)
sslConfiguration = new QSslConfiguration(*other.sslConfiguration);
#endif
}
inline bool operator==(const QNetworkRequestPrivate &other) const
{
return url == other.url &&
priority == other.priority &&
rawHeaders == other.rawHeaders &&
attributes == other.attributes;
// don't compare cookedHeaders
}
QUrl url;
QNetworkRequest::Priority priority;
#ifndef QT_NO_SSL
mutable QSslConfiguration *sslConfiguration;
#endif
};
/*!
Constructs a QNetworkRequest object with \a url as the URL to be
requested.
\sa url(), setUrl()
*/
QNetworkRequest::QNetworkRequest(const QUrl &url)
: d(new QNetworkRequestPrivate)
{
d->url = url;
}
/*!
Creates a copy of \a other.
*/
QNetworkRequest::QNetworkRequest(const QNetworkRequest &other)
: d(other.d)
{
}
/*!
Disposes of the QNetworkRequest object.
*/
QNetworkRequest::~QNetworkRequest()
{
// QSharedDataPointer auto deletes
d = 0;
}
/*!
Returns \c true if this object is the same as \a other (i.e., if they
have the same URL, same headers and same meta-data settings).
\sa operator!=()
*/
bool QNetworkRequest::operator==(const QNetworkRequest &other) const
{
return d == other.d || *d == *other.d;
}
/*!
\fn bool QNetworkRequest::operator!=(const QNetworkRequest &other) const
Returns \c false if this object is not the same as \a other.
\sa operator==()
*/
/*!
Creates a copy of \a other
*/
QNetworkRequest &QNetworkRequest::operator=(const QNetworkRequest &other)
{
d = other.d;
return *this;
}
/*!
\fn void QNetworkRequest::swap(QNetworkRequest &other)
\since 5.0
Swaps this network request with \a other. This function is very
fast and never fails.
*/
/*!
Returns the URL this network request is referring to.
\sa setUrl()
*/
QUrl QNetworkRequest::url() const
{
return d->url;
}
/*!
Sets the URL this network request is referring to be \a url.
\sa url()
*/
void QNetworkRequest::setUrl(const QUrl &url)
{
d->url = url;
}
/*!
Returns the value of the known network header \a header if it is
present in this request. If it is not present, returns QVariant()
(i.e., an invalid variant).
\sa KnownHeaders, rawHeader(), setHeader()
*/
QVariant QNetworkRequest::header(KnownHeaders header) const
{
return d->cookedHeaders.value(header);
}
/*!
Sets the value of the known header \a header to be \a value,
overriding any previously set headers. This operation also sets
the equivalent raw HTTP header.
\sa KnownHeaders, setRawHeader(), header()
*/
void QNetworkRequest::setHeader(KnownHeaders header, const QVariant &value)
{
d->setCookedHeader(header, value);
}
/*!
Returns \c true if the raw header \a headerName is present in this
network request.
\sa rawHeader(), setRawHeader()
*/
bool QNetworkRequest::hasRawHeader(const QByteArray &headerName) const
{
return d->findRawHeader(headerName) != d->rawHeaders.constEnd();
}
/*!
Returns the raw form of header \a headerName. If no such header is
present, an empty QByteArray is returned, which may be
indistinguishable from a header that is present but has no content
(use hasRawHeader() to find out if the header exists or not).
Raw headers can be set with setRawHeader() or with setHeader().
\sa header(), setRawHeader()
*/
QByteArray QNetworkRequest::rawHeader(const QByteArray &headerName) const
{
QNetworkHeadersPrivate::RawHeadersList::ConstIterator it =
d->findRawHeader(headerName);
if (it != d->rawHeaders.constEnd())
return it->second;
return QByteArray();
}
/*!
Returns a list of all raw headers that are set in this network
request. The list is in the order that the headers were set.
\sa hasRawHeader(), rawHeader()
*/
QList<QByteArray> QNetworkRequest::rawHeaderList() const
{
return d->rawHeadersKeys();
}
/*!
Sets the header \a headerName to be of value \a headerValue. If \a
headerName corresponds to a known header (see
QNetworkRequest::KnownHeaders), the raw format will be parsed and
the corresponding "cooked" header will be set as well.
For example:
\snippet code/src_network_access_qnetworkrequest.cpp 0
will also set the known header LastModifiedHeader to be the
QDateTime object of the parsed date.
\note Setting the same header twice overrides the previous
setting. To accomplish the behaviour of multiple HTTP headers of
the same name, you should concatenate the two values, separating
them with a comma (",") and set one single raw header.
\sa KnownHeaders, setHeader(), hasRawHeader(), rawHeader()
*/
void QNetworkRequest::setRawHeader(const QByteArray &headerName, const QByteArray &headerValue)
{
d->setRawHeader(headerName, headerValue);
}
/*!
Returns the attribute associated with the code \a code. If the
attribute has not been set, it returns \a defaultValue.
\note This function does not apply the defaults listed in
QNetworkRequest::Attribute.
\sa setAttribute(), QNetworkRequest::Attribute
*/
QVariant QNetworkRequest::attribute(Attribute code, const QVariant &defaultValue) const
{
return d->attributes.value(code, defaultValue);
}
/*!
Sets the attribute associated with code \a code to be value \a
value. If the attribute is already set, the previous value is
discarded. In special, if \a value is an invalid QVariant, the
attribute is unset.
\sa attribute(), QNetworkRequest::Attribute
*/
void QNetworkRequest::setAttribute(Attribute code, const QVariant &value)
{
if (value.isValid())
d->attributes.insert(code, value);
else
d->attributes.remove(code);
}
#ifndef QT_NO_SSL
/*!
Returns this network request's SSL configuration. By default, no
SSL settings are specified.
\sa setSslConfiguration()
*/
QSslConfiguration QNetworkRequest::sslConfiguration() const
{
if (!d->sslConfiguration)
d->sslConfiguration = new QSslConfiguration(QSslConfiguration::defaultConfiguration());
return *d->sslConfiguration;
}
/*!
Sets this network request's SSL configuration to be \a config. The
settings that apply are the private key, the local certificate,
the SSL protocol (SSLv2, SSLv3, TLSv1.0 where applicable), the CA
certificates and the ciphers that the SSL backend is allowed to
use.
By default, no SSL configuration is set, which allows the backends
to choose freely what configuration is best for them.
\sa sslConfiguration(), QSslConfiguration::defaultConfiguration()
*/
void QNetworkRequest::setSslConfiguration(const QSslConfiguration &config)
{
if (!d->sslConfiguration)
d->sslConfiguration = new QSslConfiguration(config);
else
*d->sslConfiguration = config;
}
#endif
/*!
\since 4.6
Allows setting a reference to the \a object initiating
the request.
For example Qt WebKit sets the originating object to the
QWebFrame that initiated the request.
\sa originatingObject()
*/
void QNetworkRequest::setOriginatingObject(QObject *object)
{
d->originatingObject = object;
}
/*!
\since 4.6
Returns a reference to the object that initiated this
network request; returns 0 if not set or the object has
been destroyed.
\sa setOriginatingObject()
*/
QObject *QNetworkRequest::originatingObject() const
{
return d->originatingObject.data();
}
/*!
\since 4.7
Return the priority of this request.
\sa setPriority()
*/
QNetworkRequest::Priority QNetworkRequest::priority() const
{
return d->priority;
}
/*! \enum QNetworkRequest::Priority
\since 4.7
This enum lists the possible network request priorities.
\value HighPriority High priority
\value NormalPriority Normal priority
\value LowPriority Low priority
*/
/*!
\since 4.7
Set the priority of this request to \a priority.
\note The \a priority is only a hint to the network access
manager. It can use it or not. Currently it is used for HTTP to
decide which request should be sent first to a server.
\sa priority()
*/
void QNetworkRequest::setPriority(Priority priority)
{
d->priority = priority;
}
static QByteArray headerName(QNetworkRequest::KnownHeaders header)
{
switch (header) {
case QNetworkRequest::ContentTypeHeader:
return "Content-Type";
case QNetworkRequest::ContentLengthHeader:
return "Content-Length";
case QNetworkRequest::LocationHeader:
return "Location";
case QNetworkRequest::LastModifiedHeader:
return "Last-Modified";
case QNetworkRequest::CookieHeader:
return "Cookie";
case QNetworkRequest::SetCookieHeader:
return "Set-Cookie";
case QNetworkRequest::ContentDispositionHeader:
return "Content-Disposition";
case QNetworkRequest::UserAgentHeader:
return "User-Agent";
case QNetworkRequest::ServerHeader:
return "Server";
// no default:
// if new values are added, this will generate a compiler warning
}
return QByteArray();
}
static QByteArray headerValue(QNetworkRequest::KnownHeaders header, const QVariant &value)
{
switch (header) {
case QNetworkRequest::ContentTypeHeader:
case QNetworkRequest::ContentLengthHeader:
case QNetworkRequest::ContentDispositionHeader:
case QNetworkRequest::UserAgentHeader:
case QNetworkRequest::ServerHeader:
return value.toByteArray();
case QNetworkRequest::LocationHeader:
switch (value.userType()) {
case QMetaType::QUrl:
return value.toUrl().toEncoded();
default:
return value.toByteArray();
}
case QNetworkRequest::LastModifiedHeader:
switch (value.userType()) {
case QMetaType::QDate:
case QMetaType::QDateTime:
// generate RFC 1123/822 dates:
return QNetworkHeadersPrivate::toHttpDate(value.toDateTime());
default:
return value.toByteArray();
}
case QNetworkRequest::CookieHeader: {
QList<QNetworkCookie> cookies = qvariant_cast<QList<QNetworkCookie> >(value);
if (cookies.isEmpty() && value.userType() == qMetaTypeId<QNetworkCookie>())
cookies << qvariant_cast<QNetworkCookie>(value);
QByteArray result;
bool first = true;
foreach (const QNetworkCookie &cookie, cookies) {
if (!first)
result += "; ";
first = false;
result += cookie.toRawForm(QNetworkCookie::NameAndValueOnly);
}
return result;
}
case QNetworkRequest::SetCookieHeader: {
QList<QNetworkCookie> cookies = qvariant_cast<QList<QNetworkCookie> >(value);
if (cookies.isEmpty() && value.userType() == qMetaTypeId<QNetworkCookie>())
cookies << qvariant_cast<QNetworkCookie>(value);
QByteArray result;
bool first = true;
foreach (const QNetworkCookie &cookie, cookies) {
if (!first)
result += ", ";
first = false;
result += cookie.toRawForm(QNetworkCookie::Full);
}
return result;
}
}
return QByteArray();
}
static QNetworkRequest::KnownHeaders parseHeaderName(const QByteArray &headerName)
{
if (headerName.isEmpty())
return QNetworkRequest::KnownHeaders(-1);
switch (tolower(headerName.at(0))) {
case 'c':
if (qstricmp(headerName.constData(), "content-type") == 0)
return QNetworkRequest::ContentTypeHeader;
else if (qstricmp(headerName.constData(), "content-length") == 0)
return QNetworkRequest::ContentLengthHeader;
else if (qstricmp(headerName.constData(), "cookie") == 0)
return QNetworkRequest::CookieHeader;
break;
case 'l':
if (qstricmp(headerName.constData(), "location") == 0)
return QNetworkRequest::LocationHeader;
else if (qstricmp(headerName.constData(), "last-modified") == 0)
return QNetworkRequest::LastModifiedHeader;
break;
case 's':
if (qstricmp(headerName.constData(), "set-cookie") == 0)
return QNetworkRequest::SetCookieHeader;
else if (qstricmp(headerName.constData(), "server") == 0)
return QNetworkRequest::ServerHeader;
break;
case 'u':
if (qstricmp(headerName.constData(), "user-agent") == 0)
return QNetworkRequest::UserAgentHeader;
break;
}
return QNetworkRequest::KnownHeaders(-1); // nothing found
}
static QVariant parseHttpDate(const QByteArray &raw)
{
QDateTime dt = QNetworkHeadersPrivate::fromHttpDate(raw);
if (dt.isValid())
return dt;
return QVariant(); // transform an invalid QDateTime into a null QVariant
}
static QVariant parseCookieHeader(const QByteArray &raw)
{
QList<QNetworkCookie> result;
QList<QByteArray> cookieList = raw.split(';');
foreach (const QByteArray &cookie, cookieList) {
QList<QNetworkCookie> parsed = QNetworkCookie::parseCookies(cookie.trimmed());
if (parsed.count() != 1)
return QVariant(); // invalid Cookie: header
result += parsed;
}
return QVariant::fromValue(result);
}
static QVariant parseHeaderValue(QNetworkRequest::KnownHeaders header, const QByteArray &value)
{
// header is always a valid value
switch (header) {
case QNetworkRequest::UserAgentHeader:
case QNetworkRequest::ServerHeader:
case QNetworkRequest::ContentTypeHeader:
// copy exactly, convert to QString
return QString::fromLatin1(value);
case QNetworkRequest::ContentLengthHeader: {
bool ok;
qint64 result = value.trimmed().toLongLong(&ok);
if (ok)
return result;
return QVariant();
}
case QNetworkRequest::LocationHeader: {
QUrl result = QUrl::fromEncoded(value, QUrl::StrictMode);
if (result.isValid() && !result.scheme().isEmpty())
return result;
return QVariant();
}
case QNetworkRequest::LastModifiedHeader:
return parseHttpDate(value);
case QNetworkRequest::CookieHeader:
return parseCookieHeader(value);
case QNetworkRequest::SetCookieHeader:
return QVariant::fromValue(QNetworkCookie::parseCookies(value));
default:
Q_ASSERT(0);
}
return QVariant();
}
QNetworkHeadersPrivate::RawHeadersList::ConstIterator
QNetworkHeadersPrivate::findRawHeader(const QByteArray &key) const
{
RawHeadersList::ConstIterator it = rawHeaders.constBegin();
RawHeadersList::ConstIterator end = rawHeaders.constEnd();
for ( ; it != end; ++it)
if (qstricmp(it->first.constData(), key.constData()) == 0)
return it;
return end; // not found
}
QNetworkHeadersPrivate::RawHeadersList QNetworkHeadersPrivate::allRawHeaders() const
{
return rawHeaders;
}
QList<QByteArray> QNetworkHeadersPrivate::rawHeadersKeys() const
{
QList<QByteArray> result;
RawHeadersList::ConstIterator it = rawHeaders.constBegin(),
end = rawHeaders.constEnd();
for ( ; it != end; ++it)
result << it->first;
return result;
}
void QNetworkHeadersPrivate::setRawHeader(const QByteArray &key, const QByteArray &value)
{
if (key.isEmpty())
// refuse to accept an empty raw header
return;
setRawHeaderInternal(key, value);
parseAndSetHeader(key, value);
}
/*!
\internal
Sets the internal raw headers list to match \a list. The cooked headers
will also be updated.
If \a list contains duplicates, they will be stored, but only the first one
is usually accessed.
*/
void QNetworkHeadersPrivate::setAllRawHeaders(const RawHeadersList &list)
{
cookedHeaders.clear();
rawHeaders = list;
RawHeadersList::ConstIterator it = rawHeaders.constBegin();
RawHeadersList::ConstIterator end = rawHeaders.constEnd();
for ( ; it != end; ++it)
parseAndSetHeader(it->first, it->second);
}
void QNetworkHeadersPrivate::setCookedHeader(QNetworkRequest::KnownHeaders header,
const QVariant &value)
{
QByteArray name = headerName(header);
if (name.isEmpty()) {
// headerName verifies that \a header is a known value
qWarning("QNetworkRequest::setHeader: invalid header value KnownHeader(%d) received", header);
return;
}
if (value.isNull()) {
setRawHeaderInternal(name, QByteArray());
cookedHeaders.remove(header);
} else {
QByteArray rawValue = headerValue(header, value);
if (rawValue.isEmpty()) {
qWarning("QNetworkRequest::setHeader: QVariant of type %s cannot be used with header %s",
value.typeName(), name.constData());
return;
}
setRawHeaderInternal(name, rawValue);
cookedHeaders.insert(header, value);
}
}
void QNetworkHeadersPrivate::setRawHeaderInternal(const QByteArray &key, const QByteArray &value)
{
RawHeadersList::Iterator it = rawHeaders.begin();
while (it != rawHeaders.end()) {
if (qstricmp(it->first.constData(), key.constData()) == 0)
it = rawHeaders.erase(it);
else
++it;
}
if (value.isNull())
return; // only wanted to erase key
RawHeaderPair pair;
pair.first = key;
pair.second = value;
rawHeaders.append(pair);
}
void QNetworkHeadersPrivate::parseAndSetHeader(const QByteArray &key, const QByteArray &value)
{
// is it a known header?
QNetworkRequest::KnownHeaders parsedKey = parseHeaderName(key);
if (parsedKey != QNetworkRequest::KnownHeaders(-1)) {
if (value.isNull()) {
cookedHeaders.remove(parsedKey);
} else if (parsedKey == QNetworkRequest::ContentLengthHeader
&& cookedHeaders.contains(QNetworkRequest::ContentLengthHeader)) {
// Only set the cooked header "Content-Length" once.
// See bug QTBUG-15311
} else {
cookedHeaders.insert(parsedKey, parseHeaderValue(parsedKey, value));
}
}
}
// Fast month string to int conversion. This code
// assumes that the Month name is correct and that
// the string is at least three chars long.
static int name_to_month(const char* month_str)
{
switch (month_str[0]) {
case 'J':
switch (month_str[1]) {
case 'a':
return 1;
case 'u':
switch (month_str[2] ) {
case 'n':
return 6;
case 'l':
return 7;
}
}
break;
case 'F':
return 2;
case 'M':
switch (month_str[2] ) {
case 'r':
return 3;
case 'y':
return 5;
}
break;
case 'A':
switch (month_str[1]) {
case 'p':
return 4;
case 'u':
return 8;
}
break;
case 'O':
return 10;
case 'S':
return 9;
case 'N':
return 11;
case 'D':
return 12;
}
return 0;
}
QDateTime QNetworkHeadersPrivate::fromHttpDate(const QByteArray &value)
{
// HTTP dates have three possible formats:
// RFC 1123/822 - ddd, dd MMM yyyy hh:mm:ss "GMT"
// RFC 850 - dddd, dd-MMM-yy hh:mm:ss "GMT"
// ANSI C's asctime - ddd MMM d hh:mm:ss yyyy
// We only handle them exactly. If they deviate, we bail out.
int pos = value.indexOf(',');
QDateTime dt;
#ifndef QT_NO_DATESTRING
if (pos == -1) {
// no comma -> asctime(3) format
dt = QDateTime::fromString(QString::fromLatin1(value), Qt::TextDate);
} else {
// Use sscanf over QLocal/QDateTimeParser for speed reasons. See the
// Qt WebKit performance benchmarks to get an idea.
if (pos == 3) {
char month_name[4];
int day, year, hour, minute, second;
#ifdef Q_CC_MSVC
// Use secure version to avoid compiler warning
if (sscanf_s(value.constData(), "%*3s, %d %3s %d %d:%d:%d 'GMT'", &day, month_name, 4, &year, &hour, &minute, &second) == 6)
#else
// The POSIX secure mode is %ms (which allocates memory), too bleeding edge for now
// In any case this is already safe as field width is specified.
if (sscanf(value.constData(), "%*3s, %d %3s %d %d:%d:%d 'GMT'", &day, month_name, &year, &hour, &minute, &second) == 6)
#endif
dt = QDateTime(QDate(year, name_to_month(month_name), day), QTime(hour, minute, second));
} else {
QLocale c = QLocale::c();
// eat the weekday, the comma and the space following it
QString sansWeekday = QString::fromLatin1(value.constData() + pos + 2);
// must be RFC 850 date
dt = c.toDateTime(sansWeekday, QLatin1String("dd-MMM-yy hh:mm:ss 'GMT'"));
}
}
#endif // QT_NO_DATESTRING
if (dt.isValid())
dt.setTimeSpec(Qt::UTC);
return dt;
}
QByteArray QNetworkHeadersPrivate::toHttpDate(const QDateTime &dt)
{
return QLocale::c().toString(dt, QLatin1String("ddd, dd MMM yyyy hh:mm:ss 'GMT'"))
.toLatin1();
}
QT_END_NAMESPACE
| bsd-3-clause |
zhulin2609/phantomjs | src/qt/qtbase/src/sql/kernel/qsqldatabase.cpp | 84 | 43150 | /****************************************************************************
**
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
** Contact: http://www.qt-project.org/legal
**
** This file is part of the QtSql module of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL21$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia. For licensing terms and
** conditions see http://qt.digia.com/licensing. For further information
** use the contact form at http://qt.digia.com/contact-us.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 or version 3 as published by the Free
** Software Foundation and appearing in the file LICENSE.LGPLv21 and
** LICENSE.LGPLv3 included in the packaging of this file. Please review the
** following information to ensure the GNU Lesser General Public License
** requirements will be met: https://www.gnu.org/licenses/lgpl.html and
** http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights. These rights are described in the Digia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** $QT_END_LICENSE$
**
****************************************************************************/
#include "qsqldatabase.h"
#include "qsqlquery.h"
#ifdef Q_OS_WIN32
// Conflicting declarations of LPCBYTE in sqlfront.h and winscard.h
#define _WINSCARD_H_
#endif
#ifdef QT_SQL_PSQL
#include "../drivers/psql/qsql_psql_p.h"
#endif
#ifdef QT_SQL_MYSQL
#include "../drivers/mysql/qsql_mysql_p.h"
#endif
#ifdef QT_SQL_ODBC
#include "../drivers/odbc/qsql_odbc_p.h"
#endif
#ifdef QT_SQL_OCI
#include "../drivers/oci/qsql_oci_p.h"
#endif
#ifdef QT_SQL_TDS
// conflicting RETCODE typedef between odbc and freetds
#define RETCODE DBRETCODE
#include "../drivers/tds/qsql_tds_p.h"
#undef RETCODE
#endif
#ifdef QT_SQL_DB2
#include "../drivers/db2/qsql_db2_p.h"
#endif
#ifdef QT_SQL_SQLITE
#include "../drivers/sqlite/qsql_sqlite_p.h"
#endif
#ifdef QT_SQL_SQLITE2
#include "../drivers/sqlite2/qsql_sqlite2_p.h"
#endif
#ifdef QT_SQL_IBASE
#undef SQL_FLOAT // avoid clash with ODBC
#undef SQL_DOUBLE
#undef SQL_TIMESTAMP
#undef SQL_TYPE_TIME
#undef SQL_TYPE_DATE
#undef SQL_DATE
#define SCHAR IBASE_SCHAR // avoid clash with ODBC (older versions of ibase.h with Firebird)
#include "../drivers/ibase/qsql_ibase_p.h"
#undef SCHAR
#endif
#include "qdebug.h"
#include "qcoreapplication.h"
#include "qreadwritelock.h"
#include "qsqlresult.h"
#include "qsqldriver.h"
#include "qsqldriverplugin.h"
#include "qsqlindex.h"
#include "private/qfactoryloader_p.h"
#include "private/qsqlnulldriver_p.h"
#include "qmutex.h"
#include "qhash.h"
#include <stdlib.h>
QT_BEGIN_NAMESPACE
#ifndef QT_NO_LIBRARY
Q_GLOBAL_STATIC_WITH_ARGS(QFactoryLoader, loader,
(QSqlDriverFactoryInterface_iid,
QLatin1String("/sqldrivers")))
#endif
#if !defined(Q_CC_MSVC) || _MSC_VER >= 1900
// ### Qt6: remove the #ifdef
const
#endif
char *QSqlDatabase::defaultConnection = const_cast<char *>("qt_sql_default_connection");
typedef QHash<QString, QSqlDriverCreatorBase*> DriverDict;
class QConnectionDict: public QHash<QString, QSqlDatabase>
{
public:
inline bool contains_ts(const QString &key)
{
QReadLocker locker(&lock);
return contains(key);
}
inline QStringList keys_ts() const
{
QReadLocker locker(&lock);
return keys();
}
mutable QReadWriteLock lock;
};
Q_GLOBAL_STATIC(QConnectionDict, dbDict)
class QSqlDatabasePrivate
{
public:
QSqlDatabasePrivate(QSqlDatabase *d, QSqlDriver *dr = 0):
ref(1),
q(d),
driver(dr),
port(-1)
{
precisionPolicy = QSql::LowPrecisionDouble;
}
QSqlDatabasePrivate(const QSqlDatabasePrivate &other);
~QSqlDatabasePrivate();
void init(const QString& type);
void copy(const QSqlDatabasePrivate *other);
void disable();
QAtomicInt ref;
QSqlDatabase *q;
QSqlDriver* driver;
QString dbname;
QString uname;
QString pword;
QString hname;
QString drvName;
int port;
QString connOptions;
QString connName;
QSql::NumericalPrecisionPolicy precisionPolicy;
static QSqlDatabasePrivate *shared_null();
static QSqlDatabase database(const QString& name, bool open);
static void addDatabase(const QSqlDatabase &db, const QString & name);
static void removeDatabase(const QString& name);
static void invalidateDb(const QSqlDatabase &db, const QString &name, bool doWarn = true);
static DriverDict &driverDict();
static void cleanConnections();
};
QSqlDatabasePrivate::QSqlDatabasePrivate(const QSqlDatabasePrivate &other) : ref(1)
{
q = other.q;
dbname = other.dbname;
uname = other.uname;
pword = other.pword;
hname = other.hname;
drvName = other.drvName;
port = other.port;
connOptions = other.connOptions;
driver = other.driver;
precisionPolicy = other.precisionPolicy;
}
QSqlDatabasePrivate::~QSqlDatabasePrivate()
{
if (driver != shared_null()->driver)
delete driver;
}
void QSqlDatabasePrivate::cleanConnections()
{
QConnectionDict *dict = dbDict();
Q_ASSERT(dict);
QWriteLocker locker(&dict->lock);
QConnectionDict::iterator it = dict->begin();
while (it != dict->end()) {
invalidateDb(it.value(), it.key(), false);
++it;
}
dict->clear();
}
static bool qDriverDictInit = false;
static void cleanDriverDict()
{
qDeleteAll(QSqlDatabasePrivate::driverDict());
QSqlDatabasePrivate::driverDict().clear();
QSqlDatabasePrivate::cleanConnections();
qDriverDictInit = false;
}
DriverDict &QSqlDatabasePrivate::driverDict()
{
static DriverDict dict;
if (!qDriverDictInit) {
qDriverDictInit = true;
qAddPostRoutine(cleanDriverDict);
}
return dict;
}
QSqlDatabasePrivate *QSqlDatabasePrivate::shared_null()
{
static QSqlNullDriver dr;
static QSqlDatabasePrivate n(NULL, &dr);
return &n;
}
void QSqlDatabasePrivate::invalidateDb(const QSqlDatabase &db, const QString &name, bool doWarn)
{
if (db.d->ref.load() != 1 && doWarn) {
qWarning("QSqlDatabasePrivate::removeDatabase: connection '%s' is still in use, "
"all queries will cease to work.", name.toLocal8Bit().constData());
db.d->disable();
db.d->connName.clear();
}
}
void QSqlDatabasePrivate::removeDatabase(const QString &name)
{
QConnectionDict *dict = dbDict();
Q_ASSERT(dict);
QWriteLocker locker(&dict->lock);
if (!dict->contains(name))
return;
invalidateDb(dict->take(name), name);
}
void QSqlDatabasePrivate::addDatabase(const QSqlDatabase &db, const QString &name)
{
QConnectionDict *dict = dbDict();
Q_ASSERT(dict);
QWriteLocker locker(&dict->lock);
if (dict->contains(name)) {
invalidateDb(dict->take(name), name);
qWarning("QSqlDatabasePrivate::addDatabase: duplicate connection name '%s', old "
"connection removed.", name.toLocal8Bit().data());
}
dict->insert(name, db);
db.d->connName = name;
}
/*! \internal
*/
QSqlDatabase QSqlDatabasePrivate::database(const QString& name, bool open)
{
const QConnectionDict *dict = dbDict();
Q_ASSERT(dict);
dict->lock.lockForRead();
QSqlDatabase db = dict->value(name);
dict->lock.unlock();
if (db.isValid() && !db.isOpen() && open) {
if (!db.open())
qWarning() << "QSqlDatabasePrivate::database: unable to open database:" << db.lastError().text();
}
return db;
}
/*! \internal
Copies the connection data from \a other.
*/
void QSqlDatabasePrivate::copy(const QSqlDatabasePrivate *other)
{
q = other->q;
dbname = other->dbname;
uname = other->uname;
pword = other->pword;
hname = other->hname;
drvName = other->drvName;
port = other->port;
connOptions = other->connOptions;
precisionPolicy = other->precisionPolicy;
}
void QSqlDatabasePrivate::disable()
{
if (driver != shared_null()->driver) {
delete driver;
driver = shared_null()->driver;
}
}
/*!
\class QSqlDriverCreatorBase
\brief The QSqlDriverCreatorBase class is the base class for
SQL driver factories.
\ingroup database
\inmodule QtSql
Reimplement createObject() to return an instance of the specific
QSqlDriver subclass that you want to provide.
See QSqlDatabase::registerSqlDriver() for details.
\sa QSqlDriverCreator
*/
/*!
\fn QSqlDriverCreatorBase::~QSqlDriverCreatorBase()
Destroys the SQL driver creator object.
*/
/*!
\fn QSqlDriver *QSqlDriverCreatorBase::createObject() const
Reimplement this function to returns a new instance of a
QSqlDriver subclass.
*/
/*!
\class QSqlDriverCreator
\brief The QSqlDriverCreator class is a template class that
provides a SQL driver factory for a specific driver type.
\ingroup database
\inmodule QtSql
QSqlDriverCreator<T> instantiates objects of type T, where T is a
QSqlDriver subclass.
See QSqlDatabase::registerSqlDriver() for details.
*/
/*!
\fn QSqlDriver *QSqlDriverCreator::createObject() const
\reimp
*/
/*!
\class QSqlDatabase
\brief The QSqlDatabase class represents a connection to
a database.
\ingroup database
\inmodule QtSql
The QSqlDatabase class provides an interface for accessing a
database through a connection. An instance of QSqlDatabase
represents the connection. The connection provides access to the
database via one of the \l{SQL Database Drivers#Supported
Databases} {supported database drivers}, which are derived from
QSqlDriver. Alternatively, you can subclass your own database
driver from QSqlDriver. See \l{How to Write Your Own Database
Driver} for more information.
Create a connection (i.e., an instance of QSqlDatabase) by calling
one of the static addDatabase() functions, where you specify
\l{SQL Database Drivers#Supported Databases} {the driver or type
of driver} to use (i.e., what kind of database will you access?)
and a connection name. A connection is known by its own name,
\e{not} by the name of the database it connects to. You can have
multiple connections to one database. QSqlDatabase also supports
the concept of a \e{default} connection, which is the unnamed
connection. To create the default connection, don't pass the
connection name argument when you call addDatabase().
Subsequently, when you call any static member function that takes
the connection name argument, if you don't pass the connection
name argument, the default connection is assumed. The following
snippet shows how to create and open a default connection to a
PostgreSQL database:
\snippet sqldatabase/sqldatabase.cpp 0
Once the QSqlDatabase object has been created, set the connection
parameters with setDatabaseName(), setUserName(), setPassword(),
setHostName(), setPort(), and setConnectOptions(). Then call
open() to activate the physical connection to the database. The
connection is not usable until you open it.
The connection defined above will be the \e{default} connection,
because we didn't give a connection name to \l{QSqlDatabase::}
{addDatabase()}. Subsequently, you can get the default connection
by calling database() without the connection name argument:
\snippet sqldatabase/sqldatabase.cpp 1
QSqlDatabase is a value class. Changes made to a database
connection via one instance of QSqlDatabase will affect other
instances of QSqlDatabase that represent the same connection. Use
cloneDatabase() to create an independent database connection based
on an existing one.
If you create multiple database connections, specify a unique
connection name for each one, when you call addDatabase(). Use
database() with a connection name to get that connection. Use
removeDatabase() with a connection name to remove a connection.
QSqlDatabase outputs a warning if you try to remove a connection
referenced by other QSqlDatabase objects. Use contains() to see if
a given connection name is in the list of connections.
Once a connection is established, you can call tables() to get the
list of tables in the database, call primaryIndex() to get a
table's primary index, and call record() to get meta-information
about a table's fields (e.g., field names).
\note QSqlDatabase::exec() is deprecated. Use QSqlQuery::exec()
instead.
If the driver supports transactions, use transaction() to start a
transaction, and commit() or rollback() to complete it. Use
\l{QSqlDriver::} {hasFeature()} to ask if the driver supports
transactions. \note When using transactions, you must start the
transaction before you create your query.
If an error occurs, lastError() will return information about it.
Get the names of the available SQL drivers with drivers(). Check
for the presence of a particular driver with isDriverAvailable().
If you have created your own custom driver, you must register it
with registerSqlDriver().
\sa QSqlDriver, QSqlQuery, {Qt SQL}, {Threads and the SQL Module}
*/
/*! \fn QSqlDatabase QSqlDatabase::addDatabase(const QString &type, const QString &connectionName)
\threadsafe
Adds a database to the list of database connections using the
driver \a type and the connection name \a connectionName. If
there already exists a database connection called \a
connectionName, that connection is removed.
The database connection is referred to by \a connectionName. The
newly added database connection is returned.
If \a type is not available or could not be loaded, isValid() returns \c false.
If \a connectionName is not specified, the new connection becomes
the default connection for the application, and subsequent calls
to database() without the connection name argument will return the
default connection. If a \a connectionName is provided here, use
database(\a connectionName) to retrieve the connection.
\warning If you add a connection with the same name as an existing
connection, the new connection replaces the old one. If you call
this function more than once without specifying \a connectionName,
the default connection will be the one replaced.
Before using the connection, it must be initialized. e.g., call
some or all of setDatabaseName(), setUserName(), setPassword(),
setHostName(), setPort(), and setConnectOptions(), and, finally,
open().
\sa database(), removeDatabase(), {Threads and the SQL Module}
*/
QSqlDatabase QSqlDatabase::addDatabase(const QString &type, const QString &connectionName)
{
QSqlDatabase db(type);
QSqlDatabasePrivate::addDatabase(db, connectionName);
return db;
}
/*!
\threadsafe
Returns the database connection called \a connectionName. The
database connection must have been previously added with
addDatabase(). If \a open is true (the default) and the database
connection is not already open it is opened now. If no \a
connectionName is specified the default connection is used. If \a
connectionName does not exist in the list of databases, an invalid
connection is returned.
\sa isOpen(), {Threads and the SQL Module}
*/
QSqlDatabase QSqlDatabase::database(const QString& connectionName, bool open)
{
return QSqlDatabasePrivate::database(connectionName, open);
}
/*!
\threadsafe
Removes the database connection \a connectionName from the list of
database connections.
\warning There should be no open queries on the database
connection when this function is called, otherwise a resource leak
will occur.
Example:
\snippet code/src_sql_kernel_qsqldatabase.cpp 0
The correct way to do it:
\snippet code/src_sql_kernel_qsqldatabase.cpp 1
To remove the default connection, which may have been created with a
call to addDatabase() not specifying a connection name, you can
retrieve the default connection name by calling connectionName() on
the database returned by database(). Note that if a default database
hasn't been created an invalid database will be returned.
\sa database(), connectionName(), {Threads and the SQL Module}
*/
void QSqlDatabase::removeDatabase(const QString& connectionName)
{
QSqlDatabasePrivate::removeDatabase(connectionName);
}
/*!
Returns a list of all the available database drivers.
\sa registerSqlDriver()
*/
QStringList QSqlDatabase::drivers()
{
QStringList list;
#ifdef QT_SQL_PSQL
list << QLatin1String("QPSQL7");
list << QLatin1String("QPSQL");
#endif
#ifdef QT_SQL_MYSQL
list << QLatin1String("QMYSQL3");
list << QLatin1String("QMYSQL");
#endif
#ifdef QT_SQL_ODBC
list << QLatin1String("QODBC3");
list << QLatin1String("QODBC");
#endif
#ifdef QT_SQL_OCI
list << QLatin1String("QOCI8");
list << QLatin1String("QOCI");
#endif
#ifdef QT_SQL_TDS
list << QLatin1String("QTDS7");
list << QLatin1String("QTDS");
#endif
#ifdef QT_SQL_DB2
list << QLatin1String("QDB2");
#endif
#ifdef QT_SQL_SQLITE
list << QLatin1String("QSQLITE");
#endif
#ifdef QT_SQL_SQLITE2
list << QLatin1String("QSQLITE2");
#endif
#ifdef QT_SQL_IBASE
list << QLatin1String("QIBASE");
#endif
#ifndef QT_NO_LIBRARY
if (QFactoryLoader *fl = loader()) {
typedef QMultiMap<int, QString> PluginKeyMap;
typedef PluginKeyMap::const_iterator PluginKeyMapConstIterator;
const PluginKeyMap keyMap = fl->keyMap();
const PluginKeyMapConstIterator cend = keyMap.constEnd();
for (PluginKeyMapConstIterator it = keyMap.constBegin(); it != cend; ++it)
if (!list.contains(it.value()))
list << it.value();
}
#endif
DriverDict dict = QSqlDatabasePrivate::driverDict();
for (DriverDict::const_iterator i = dict.constBegin(); i != dict.constEnd(); ++i) {
if (!list.contains(i.key()))
list << i.key();
}
return list;
}
/*!
This function registers a new SQL driver called \a name, within
the SQL framework. This is useful if you have a custom SQL driver
and don't want to compile it as a plugin.
Example:
\snippet code/src_sql_kernel_qsqldatabase.cpp 2
QSqlDatabase takes ownership of the \a creator pointer, so you
mustn't delete it yourself.
\sa drivers()
*/
void QSqlDatabase::registerSqlDriver(const QString& name, QSqlDriverCreatorBase *creator)
{
delete QSqlDatabasePrivate::driverDict().take(name);
if (creator)
QSqlDatabasePrivate::driverDict().insert(name, creator);
}
/*!
\threadsafe
Returns \c true if the list of database connections contains \a
connectionName; otherwise returns \c false.
\sa connectionNames(), database(), {Threads and the SQL Module}
*/
bool QSqlDatabase::contains(const QString& connectionName)
{
return dbDict()->contains_ts(connectionName);
}
/*!
\threadsafe
Returns a list containing the names of all connections.
\sa contains(), database(), {Threads and the SQL Module}
*/
QStringList QSqlDatabase::connectionNames()
{
return dbDict()->keys_ts();
}
/*!
\overload
Creates a QSqlDatabase connection that uses the driver referred
to by \a type. If the \a type is not recognized, the database
connection will have no functionality.
The currently available driver types are:
\table
\header \li Driver Type \li Description
\row \li QDB2 \li IBM DB2
\row \li QIBASE \li Borland InterBase Driver
\row \li QMYSQL \li MySQL Driver
\row \li QOCI \li Oracle Call Interface Driver
\row \li QODBC \li ODBC Driver (includes Microsoft SQL Server)
\row \li QPSQL \li PostgreSQL Driver
\row \li QSQLITE \li SQLite version 3 or above
\row \li QSQLITE2 \li SQLite version 2
\row \li QTDS \li Sybase Adaptive Server
\endtable
Additional third party drivers, including your own custom
drivers, can be loaded dynamically.
\sa {SQL Database Drivers}, registerSqlDriver(), drivers()
*/
QSqlDatabase::QSqlDatabase(const QString &type)
{
d = new QSqlDatabasePrivate(this);
d->init(type);
}
/*!
\overload
Creates a database connection using the given \a driver.
*/
QSqlDatabase::QSqlDatabase(QSqlDriver *driver)
{
d = new QSqlDatabasePrivate(this, driver);
}
/*!
Creates an empty, invalid QSqlDatabase object. Use addDatabase(),
removeDatabase(), and database() to get valid QSqlDatabase
objects.
*/
QSqlDatabase::QSqlDatabase()
{
d = QSqlDatabasePrivate::shared_null();
d->ref.ref();
}
/*!
Creates a copy of \a other.
*/
QSqlDatabase::QSqlDatabase(const QSqlDatabase &other)
{
d = other.d;
d->ref.ref();
}
/*!
Assigns \a other to this object.
*/
QSqlDatabase &QSqlDatabase::operator=(const QSqlDatabase &other)
{
qAtomicAssign(d, other.d);
return *this;
}
/*!
\internal
Create the actual driver instance \a type.
*/
void QSqlDatabasePrivate::init(const QString &type)
{
drvName = type;
if (!driver) {
#ifdef QT_SQL_PSQL
if (type == QLatin1String("QPSQL") || type == QLatin1String("QPSQL7"))
driver = new QPSQLDriver();
#endif
#ifdef QT_SQL_MYSQL
if (type == QLatin1String("QMYSQL") || type == QLatin1String("QMYSQL3"))
driver = new QMYSQLDriver();
#endif
#ifdef QT_SQL_ODBC
if (type == QLatin1String("QODBC") || type == QLatin1String("QODBC3"))
driver = new QODBCDriver();
#endif
#ifdef QT_SQL_OCI
if (type == QLatin1String("QOCI") || type == QLatin1String("QOCI8"))
driver = new QOCIDriver();
#endif
#ifdef QT_SQL_TDS
if (type == QLatin1String("QTDS") || type == QLatin1String("QTDS7"))
driver = new QTDSDriver();
#endif
#ifdef QT_SQL_DB2
if (type == QLatin1String("QDB2"))
driver = new QDB2Driver();
#endif
#ifdef QT_SQL_SQLITE
if (type == QLatin1String("QSQLITE"))
driver = new QSQLiteDriver();
#endif
#ifdef QT_SQL_SQLITE2
if (type == QLatin1String("QSQLITE2"))
driver = new QSQLite2Driver();
#endif
#ifdef QT_SQL_IBASE
if (type == QLatin1String("QIBASE"))
driver = new QIBaseDriver();
#endif
}
if (!driver) {
DriverDict dict = QSqlDatabasePrivate::driverDict();
for (DriverDict::const_iterator it = dict.constBegin();
it != dict.constEnd() && !driver; ++it) {
if (type == it.key()) {
driver = ((QSqlDriverCreatorBase*)(*it))->createObject();
}
}
}
#ifndef QT_NO_LIBRARY
if (!driver && loader())
driver = qLoadPlugin<QSqlDriver, QSqlDriverPlugin>(loader(), type);
#endif // QT_NO_LIBRARY
if (!driver) {
qWarning("QSqlDatabase: %s driver not loaded", type.toLatin1().data());
qWarning("QSqlDatabase: available drivers: %s",
QSqlDatabase::drivers().join(QLatin1Char(' ')).toLatin1().data());
if (QCoreApplication::instance() == 0)
qWarning("QSqlDatabase: an instance of QCoreApplication is required for loading driver plugins");
driver = shared_null()->driver;
}
}
/*!
Destroys the object and frees any allocated resources.
\sa close()
*/
QSqlDatabase::~QSqlDatabase()
{
if (!d->ref.deref()) {
close();
delete d;
}
}
/*!
Executes a SQL statement on the database and returns a QSqlQuery
object. Use lastError() to retrieve error information. If \a
query is empty, an empty, invalid query is returned and
lastError() is not affected.
\sa QSqlQuery, lastError()
*/
QSqlQuery QSqlDatabase::exec(const QString & query) const
{
QSqlQuery r(d->driver->createResult());
if (!query.isEmpty()) {
r.exec(query);
d->driver->setLastError(r.lastError());
}
return r;
}
/*!
Opens the database connection using the current connection
values. Returns \c true on success; otherwise returns \c false. Error
information can be retrieved using lastError().
\sa lastError(), setDatabaseName(), setUserName(), setPassword(),
setHostName(), setPort(), setConnectOptions()
*/
bool QSqlDatabase::open()
{
return d->driver->open(d->dbname, d->uname, d->pword, d->hname,
d->port, d->connOptions);
}
/*!
\overload
Opens the database connection using the given \a user name and \a
password. Returns \c true on success; otherwise returns \c false. Error
information can be retrieved using the lastError() function.
This function does not store the password it is given. Instead,
the password is passed directly to the driver for opening the
connection and it is then discarded.
\sa lastError()
*/
bool QSqlDatabase::open(const QString& user, const QString& password)
{
setUserName(user);
return d->driver->open(d->dbname, user, password, d->hname,
d->port, d->connOptions);
}
/*!
Closes the database connection, freeing any resources acquired, and
invalidating any existing QSqlQuery objects that are used with the
database.
This will also affect copies of this QSqlDatabase object.
\sa removeDatabase()
*/
void QSqlDatabase::close()
{
d->driver->close();
}
/*!
Returns \c true if the database connection is currently open;
otherwise returns \c false.
*/
bool QSqlDatabase::isOpen() const
{
return d->driver->isOpen();
}
/*!
Returns \c true if there was an error opening the database
connection; otherwise returns \c false. Error information can be
retrieved using the lastError() function.
*/
bool QSqlDatabase::isOpenError() const
{
return d->driver->isOpenError();
}
/*!
Begins a transaction on the database if the driver supports
transactions. Returns \c{true} if the operation succeeded.
Otherwise it returns \c{false}.
\sa QSqlDriver::hasFeature(), commit(), rollback()
*/
bool QSqlDatabase::transaction()
{
if (!d->driver->hasFeature(QSqlDriver::Transactions))
return false;
return d->driver->beginTransaction();
}
/*!
Commits a transaction to the database if the driver supports
transactions and a transaction() has been started. Returns \c{true}
if the operation succeeded. Otherwise it returns \c{false}.
\note For some databases, the commit will fail and return \c{false}
if there is an \l{QSqlQuery::isActive()} {active query} using the
database for a \c{SELECT}. Make the query \l{QSqlQuery::isActive()}
{inactive} before doing the commit.
Call lastError() to get information about errors.
\sa QSqlQuery::isActive(), QSqlDriver::hasFeature(), rollback()
*/
bool QSqlDatabase::commit()
{
if (!d->driver->hasFeature(QSqlDriver::Transactions))
return false;
return d->driver->commitTransaction();
}
/*!
Rolls back a transaction on the database, if the driver supports
transactions and a transaction() has been started. Returns \c{true}
if the operation succeeded. Otherwise it returns \c{false}.
\note For some databases, the rollback will fail and return
\c{false} if there is an \l{QSqlQuery::isActive()} {active query}
using the database for a \c{SELECT}. Make the query
\l{QSqlQuery::isActive()} {inactive} before doing the rollback.
Call lastError() to get information about errors.
\sa QSqlQuery::isActive(), QSqlDriver::hasFeature(), commit()
*/
bool QSqlDatabase::rollback()
{
if (!d->driver->hasFeature(QSqlDriver::Transactions))
return false;
return d->driver->rollbackTransaction();
}
/*!
Sets the connection's database name to \a name. To have effect,
the database name must be set \e{before} the connection is
\l{open()} {opened}. Alternatively, you can close() the
connection, set the database name, and call open() again. \note
The \e{database name} is not the \e{connection name}. The
connection name must be passed to addDatabase() at connection
object create time.
For the QOCI (Oracle) driver, the database name is the TNS
Service Name.
For the QODBC driver, the \a name can either be a DSN, a DSN
filename (in which case the file must have a \c .dsn extension),
or a connection string.
For example, Microsoft Access users can use the following
connection string to open an \c .mdb file directly, instead of
having to create a DSN entry in the ODBC manager:
\snippet code/src_sql_kernel_qsqldatabase.cpp 3
There is no default value.
\sa databaseName(), setUserName(), setPassword(), setHostName(),
setPort(), setConnectOptions(), open()
*/
void QSqlDatabase::setDatabaseName(const QString& name)
{
if (isValid())
d->dbname = name;
}
/*!
Sets the connection's user name to \a name. To have effect, the
user name must be set \e{before} the connection is \l{open()}
{opened}. Alternatively, you can close() the connection, set the
user name, and call open() again.
There is no default value.
\sa userName(), setDatabaseName(), setPassword(), setHostName(),
setPort(), setConnectOptions(), open()
*/
void QSqlDatabase::setUserName(const QString& name)
{
if (isValid())
d->uname = name;
}
/*!
Sets the connection's password to \a password. To have effect, the
password must be set \e{before} the connection is \l{open()}
{opened}. Alternatively, you can close() the connection, set the
password, and call open() again.
There is no default value.
\warning This function stores the password in plain text within
Qt. Use the open() call that takes a password as parameter to
avoid this behavior.
\sa password(), setUserName(), setDatabaseName(), setHostName(),
setPort(), setConnectOptions(), open()
*/
void QSqlDatabase::setPassword(const QString& password)
{
if (isValid())
d->pword = password;
}
/*!
Sets the connection's host name to \a host. To have effect, the
host name must be set \e{before} the connection is \l{open()}
{opened}. Alternatively, you can close() the connection, set the
host name, and call open() again.
There is no default value.
\sa hostName(), setUserName(), setPassword(), setDatabaseName(),
setPort(), setConnectOptions(), open()
*/
void QSqlDatabase::setHostName(const QString& host)
{
if (isValid())
d->hname = host;
}
/*!
Sets the connection's port number to \a port. To have effect, the
port number must be set \e{before} the connection is \l{open()}
{opened}. Alternatively, you can close() the connection, set the
port number, and call open() again..
There is no default value.
\sa port(), setUserName(), setPassword(), setHostName(),
setDatabaseName(), setConnectOptions(), open()
*/
void QSqlDatabase::setPort(int port)
{
if (isValid())
d->port = port;
}
/*!
Returns the connection's database name, which may be empty.
\note The database name is not the connection name.
\sa setDatabaseName()
*/
QString QSqlDatabase::databaseName() const
{
return d->dbname;
}
/*!
Returns the connection's user name; it may be empty.
\sa setUserName()
*/
QString QSqlDatabase::userName() const
{
return d->uname;
}
/*!
Returns the connection's password. If the password was not set
with setPassword(), and if the password was given in the open()
call, or if no password was used, an empty string is returned.
*/
QString QSqlDatabase::password() const
{
return d->pword;
}
/*!
Returns the connection's host name; it may be empty.
\sa setHostName()
*/
QString QSqlDatabase::hostName() const
{
return d->hname;
}
/*!
Returns the connection's driver name.
\sa addDatabase(), driver()
*/
QString QSqlDatabase::driverName() const
{
return d->drvName;
}
/*!
Returns the connection's port number. The value is undefined if
the port number has not been set.
\sa setPort()
*/
int QSqlDatabase::port() const
{
return d->port;
}
/*!
Returns the database driver used to access the database
connection.
\sa addDatabase(), drivers()
*/
QSqlDriver* QSqlDatabase::driver() const
{
return d->driver;
}
/*!
Returns information about the last error that occurred on the
database.
Failures that occur in conjunction with an individual query are
reported by QSqlQuery::lastError().
\sa QSqlError, QSqlQuery::lastError()
*/
QSqlError QSqlDatabase::lastError() const
{
return d->driver->lastError();
}
/*!
Returns a list of the database's tables, system tables and views,
as specified by the parameter \a type.
\sa primaryIndex(), record()
*/
QStringList QSqlDatabase::tables(QSql::TableType type) const
{
return d->driver->tables(type);
}
/*!
Returns the primary index for table \a tablename. If no primary
index exists an empty QSqlIndex is returned.
\sa tables(), record()
*/
QSqlIndex QSqlDatabase::primaryIndex(const QString& tablename) const
{
return d->driver->primaryIndex(tablename);
}
/*!
Returns a QSqlRecord populated with the names of all the fields in
the table (or view) called \a tablename. The order in which the
fields appear in the record is undefined. If no such table (or
view) exists, an empty record is returned.
*/
QSqlRecord QSqlDatabase::record(const QString& tablename) const
{
return d->driver->record(tablename);
}
/*!
Sets database-specific \a options. This must be done before the
connection is opened or it has no effect (or you can close() the
connection, call this function and open() the connection again).
The format of the \a options string is a semicolon separated list
of option names or option=value pairs. The options depend on the
database client used:
\table
\header \li ODBC \li MySQL \li PostgreSQL
\row
\li
\list
\li SQL_ATTR_ACCESS_MODE
\li SQL_ATTR_LOGIN_TIMEOUT
\li SQL_ATTR_CONNECTION_TIMEOUT
\li SQL_ATTR_CURRENT_CATALOG
\li SQL_ATTR_METADATA_ID
\li SQL_ATTR_PACKET_SIZE
\li SQL_ATTR_TRACEFILE
\li SQL_ATTR_TRACE
\li SQL_ATTR_CONNECTION_POOLING
\li SQL_ATTR_ODBC_VERSION
\endlist
\li
\list
\li CLIENT_COMPRESS
\li CLIENT_FOUND_ROWS
\li CLIENT_IGNORE_SPACE
\li CLIENT_SSL
\li CLIENT_ODBC
\li CLIENT_NO_SCHEMA
\li CLIENT_INTERACTIVE
\li UNIX_SOCKET
\li MYSQL_OPT_RECONNECT
\endlist
\li
\list
\li connect_timeout
\li options
\li tty
\li requiressl
\li service
\endlist
\header \li DB2 \li OCI \li TDS
\row
\li
\list
\li SQL_ATTR_ACCESS_MODE
\li SQL_ATTR_LOGIN_TIMEOUT
\endlist
\li
\list
\li OCI_ATTR_PREFETCH_ROWS
\li OCI_ATTR_PREFETCH_MEMORY
\endlist
\li
\e none
\header \li SQLite \li Interbase
\row
\li
\list
\li QSQLITE_BUSY_TIMEOUT
\li QSQLITE_OPEN_READONLY
\li QSQLITE_OPEN_URI
\li QSQLITE_ENABLE_SHARED_CACHE
\endlist
\li
\list
\li ISC_DPB_LC_CTYPE
\li ISC_DPB_SQL_ROLE_NAME
\endlist
\endtable
Examples:
\snippet code/src_sql_kernel_qsqldatabase.cpp 4
Refer to the client library documentation for more information
about the different options.
\sa connectOptions()
*/
void QSqlDatabase::setConnectOptions(const QString &options)
{
if (isValid())
d->connOptions = options;
}
/*!
Returns the connection options string used for this connection.
The string may be empty.
\sa setConnectOptions()
*/
QString QSqlDatabase::connectOptions() const
{
return d->connOptions;
}
/*!
Returns \c true if a driver called \a name is available; otherwise
returns \c false.
\sa drivers()
*/
bool QSqlDatabase::isDriverAvailable(const QString& name)
{
return drivers().contains(name);
}
/*! \fn QSqlDatabase QSqlDatabase::addDatabase(QSqlDriver* driver, const QString& connectionName)
This overload is useful when you want to create a database
connection with a \l{QSqlDriver} {driver} you instantiated
yourself. It might be your own database driver, or you might just
need to instantiate one of the Qt drivers yourself. If you do
this, it is recommended that you include the driver code in your
application. For example, you can create a PostgreSQL connection
with your own QPSQL driver like this:
\snippet code/src_sql_kernel_qsqldatabase.cpp 5
\codeline
\snippet code/src_sql_kernel_qsqldatabase.cpp 6
The above code sets up a PostgreSQL connection and instantiates a
QPSQLDriver object. Next, addDatabase() is called to add the
connection to the known connections so that it can be used by the
Qt SQL classes. When a driver is instantiated with a connection
handle (or set of handles), Qt assumes that you have already
opened the database connection.
\note We assume that \c qtdir is the directory where Qt is
installed. This will pull in the code that is needed to use the
PostgreSQL client library and to instantiate a QPSQLDriver object,
assuming that you have the PostgreSQL headers somewhere in your
include search path.
Remember that you must link your application against the database
client library. Make sure the client library is in your linker's
search path, and add lines like these to your \c{.pro} file:
\snippet code/src_sql_kernel_qsqldatabase.cpp 7
The method described works for all the supplied drivers. The only
difference will be in the driver constructor arguments. Here is a
table of the drivers included with Qt, their source code files,
and their constructor arguments:
\table
\header \li Driver \li Class name \li Constructor arguments \li File to include
\row
\li QPSQL
\li QPSQLDriver
\li PGconn *connection
\li \c qsql_psql.cpp
\row
\li QMYSQL
\li QMYSQLDriver
\li MYSQL *connection
\li \c qsql_mysql.cpp
\row
\li QOCI
\li QOCIDriver
\li OCIEnv *environment, OCISvcCtx *serviceContext
\li \c qsql_oci.cpp
\row
\li QODBC
\li QODBCDriver
\li SQLHANDLE environment, SQLHANDLE connection
\li \c qsql_odbc.cpp
\row
\li QDB2
\li QDB2
\li SQLHANDLE environment, SQLHANDLE connection
\li \c qsql_db2.cpp
\row
\li QTDS
\li QTDSDriver
\li LOGINREC *loginRecord, DBPROCESS *dbProcess, const QString &hostName
\li \c qsql_tds.cpp
\row
\li QSQLITE
\li QSQLiteDriver
\li sqlite *connection
\li \c qsql_sqlite.cpp
\row
\li QIBASE
\li QIBaseDriver
\li isc_db_handle connection
\li \c qsql_ibase.cpp
\endtable
The host name (or service name) is needed when constructing the
QTDSDriver for creating new connections for internal queries. This
is to prevent blocking when several QSqlQuery objects are used
simultaneously.
\warning Adding a database connection with the same connection
name as an existing connection, causes the existing connection to
be replaced by the new one.
\warning The SQL framework takes ownership of the \a driver. It
must not be deleted. To remove the connection, use
removeDatabase().
\sa drivers()
*/
QSqlDatabase QSqlDatabase::addDatabase(QSqlDriver* driver, const QString& connectionName)
{
QSqlDatabase db(driver);
QSqlDatabasePrivate::addDatabase(db, connectionName);
return db;
}
/*!
Returns \c true if the QSqlDatabase has a valid driver.
Example:
\snippet code/src_sql_kernel_qsqldatabase.cpp 8
*/
bool QSqlDatabase::isValid() const
{
return d->driver && d->driver != d->shared_null()->driver;
}
/*!
Clones the database connection \a other and stores it as \a
connectionName. All the settings from the original database, e.g.
databaseName(), hostName(), etc., are copied across. Does nothing
if \a other is an invalid database. Returns the newly created
database connection.
\note The new connection has not been opened. Before using the new
connection, you must call open().
*/
QSqlDatabase QSqlDatabase::cloneDatabase(const QSqlDatabase &other, const QString &connectionName)
{
if (!other.isValid())
return QSqlDatabase();
QSqlDatabase db(other.driverName());
db.d->copy(other.d);
QSqlDatabasePrivate::addDatabase(db, connectionName);
return db;
}
/*!
\since 4.4
Returns the connection name, which may be empty. \note The
connection name is not the \l{databaseName()} {database name}.
\sa addDatabase()
*/
QString QSqlDatabase::connectionName() const
{
return d->connName;
}
/*!
\since 4.6
Sets the default numerical precision policy used by queries created
on this database connection to \a precisionPolicy.
Note: Drivers that don't support fetching numerical values with low
precision will ignore the precision policy. You can use
QSqlDriver::hasFeature() to find out whether a driver supports this
feature.
Note: Setting the default precision policy to \a precisionPolicy
doesn't affect any currently active queries.
\sa QSql::NumericalPrecisionPolicy, numericalPrecisionPolicy(),
QSqlQuery::setNumericalPrecisionPolicy(), QSqlQuery::numericalPrecisionPolicy()
*/
void QSqlDatabase::setNumericalPrecisionPolicy(QSql::NumericalPrecisionPolicy precisionPolicy)
{
if(driver())
driver()->setNumericalPrecisionPolicy(precisionPolicy);
d->precisionPolicy = precisionPolicy;
}
/*!
\since 4.6
Returns the current default precision policy for the database connection.
\sa QSql::NumericalPrecisionPolicy, setNumericalPrecisionPolicy(),
QSqlQuery::numericalPrecisionPolicy(), QSqlQuery::setNumericalPrecisionPolicy()
*/
QSql::NumericalPrecisionPolicy QSqlDatabase::numericalPrecisionPolicy() const
{
if(driver())
return driver()->numericalPrecisionPolicy();
else
return d->precisionPolicy;
}
#ifndef QT_NO_DEBUG_STREAM
QDebug operator<<(QDebug dbg, const QSqlDatabase &d)
{
QDebugStateSaver saver(dbg);
dbg.nospace();
dbg.noquote();
if (!d.isValid()) {
dbg << "QSqlDatabase(invalid)";
return dbg;
}
dbg << "QSqlDatabase(driver=\"" << d.driverName() << "\", database=\""
<< d.databaseName() << "\", host=\"" << d.hostName() << "\", port=" << d.port()
<< ", user=\"" << d.userName() << "\", open=" << d.isOpen() << ')';
return dbg;
}
#endif
QT_END_NAMESPACE
| bsd-3-clause |
ambrop72/badvpn-googlecode-export | ncd/modules/valuemetic.c | 360 | 6811 | /**
* @file valuemetic.c
* @author Ambroz Bizjak <ambrop7@gmail.com>
*
* @section LICENSE
*
* 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 author 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 AUTHOR 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.
*
* @section DESCRIPTION
*
* Comparison functions for values.
*
* Synopsis:
* val_lesser(v1, v2)
* val_greater(v1, v2)
* val_lesser_equal(v1, v2)
* val_greater_equal(v1, v2)
* val_equal(v1, v2)
* val_different(v1, v2)
*
* Variables:
* (empty) - "true" or "false", reflecting the value of the relation in question
*
* Description:
* These statements perform comparisons of values. Order of values is defined by the
* following rules:
* 1. Values of different types have the following order: strings, lists, maps.
* 2. String values are ordered lexicographically, with respect to the numeric values
* of their bytes.
* 3. List values are ordered lexicographically, where the order of the elements is
* defined by recursive application of these rules.
* 4. Map values are ordered lexicographically, as if a map was a list of (key, value)
* pairs ordered by key, where the order of both keys and values is defined by
* recursive application of these rules.
*/
#include <stdlib.h>
#include <string.h>
#include <ncd/NCDModule.h>
#include <ncd/static_strings.h>
#include <ncd/extra/value_utils.h>
#include <generated/blog_channel_ncd_valuemetic.h>
#define ModuleLog(i, ...) NCDModuleInst_Backend_Log((i), BLOG_CURRENT_CHANNEL, __VA_ARGS__)
struct instance {
NCDModuleInst *i;
int result;
};
typedef int (*compute_func) (NCDValRef v1, NCDValRef v2);
static int compute_lesser (NCDValRef v1, NCDValRef v2)
{
return NCDVal_Compare(v1, v2) < 0;
}
static int compute_greater (NCDValRef v1, NCDValRef v2)
{
return NCDVal_Compare(v1, v2) > 0;
}
static int compute_lesser_equal (NCDValRef v1, NCDValRef v2)
{
return NCDVal_Compare(v1, v2) <= 0;
}
static int compute_greater_equal (NCDValRef v1, NCDValRef v2)
{
return NCDVal_Compare(v1, v2) >= 0;
}
static int compute_equal (NCDValRef v1, NCDValRef v2)
{
return NCDVal_Compare(v1, v2) == 0;
}
static int compute_different (NCDValRef v1, NCDValRef v2)
{
return NCDVal_Compare(v1, v2) != 0;
}
static void new_templ (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params, compute_func cfunc)
{
struct instance *o = vo;
o->i = i;
NCDValRef v1_arg;
NCDValRef v2_arg;
if (!NCDVal_ListRead(params->args, 2, &v1_arg, &v2_arg)) {
ModuleLog(i, BLOG_ERROR, "wrong arity");
goto fail0;
}
o->result = cfunc(v1_arg, v2_arg);
NCDModuleInst_Backend_Up(i);
return;
fail0:
NCDModuleInst_Backend_DeadError(i);
}
static void func_die (void *vo)
{
struct instance *o = vo;
NCDModuleInst_Backend_Dead(o->i);
}
static int func_getvar2 (void *vo, NCD_string_id_t name, NCDValMem *mem, NCDValRef *out)
{
struct instance *o = vo;
if (name == NCD_STRING_EMPTY) {
*out = ncd_make_boolean(mem, o->result, o->i->params->iparams->string_index);
return 1;
}
return 0;
}
static void func_new_lesser (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
{
new_templ(vo, i, params, compute_lesser);
}
static void func_new_greater (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
{
new_templ(vo, i, params, compute_greater);
}
static void func_new_lesser_equal (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
{
new_templ(vo, i, params, compute_lesser_equal);
}
static void func_new_greater_equal (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
{
new_templ(vo, i, params, compute_greater_equal);
}
static void func_new_equal (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
{
new_templ(vo, i, params, compute_equal);
}
static void func_new_different (void *vo, NCDModuleInst *i, const struct NCDModuleInst_new_params *params)
{
new_templ(vo, i, params, compute_different);
}
static struct NCDModule modules[] = {
{
.type = "val_lesser",
.func_new2 = func_new_lesser,
.func_die = func_die,
.func_getvar2 = func_getvar2,
.alloc_size = sizeof(struct instance)
}, {
.type = "val_greater",
.func_new2 = func_new_greater,
.func_die = func_die,
.func_getvar2 = func_getvar2,
.alloc_size = sizeof(struct instance)
}, {
.type = "val_lesser_equal",
.func_new2 = func_new_lesser_equal,
.func_die = func_die,
.func_getvar2 = func_getvar2,
.alloc_size = sizeof(struct instance)
}, {
.type = "val_greater_equal",
.func_new2 = func_new_greater_equal,
.func_die = func_die,
.func_getvar2 = func_getvar2,
.alloc_size = sizeof(struct instance)
}, {
.type = "val_equal",
.func_new2 = func_new_equal,
.func_die = func_die,
.func_getvar2 = func_getvar2,
.alloc_size = sizeof(struct instance)
}, {
.type = "val_different",
.func_new2 = func_new_different,
.func_die = func_die,
.func_getvar2 = func_getvar2,
.alloc_size = sizeof(struct instance)
}, {
.type = NULL
}
};
const struct NCDModuleGroup ncdmodule_valuemetic = {
.modules = modules
};
| bsd-3-clause |
fentas/phantomjs | src/qt/qtwebkit/Source/WebKit/efl/WebCoreSupport/FrameLoaderClientEfl.cpp | 113 | 32782 | /*
* Copyright (C) 2006 Zack Rusin <zack@kde.org>
* Copyright (C) 2006, 2011 Apple Inc. All rights reserved.
* Copyright (C) 2008 Nokia Corporation and/or its subsidiary(-ies)
* Copyright (C) 2008 Collabora Ltd. All rights reserved.
* Copyright (C) 2008 Holger Hans Peter Freyther
* Copyright (C) 2008 Kenneth Rohde Christiansen
* Copyright (C) 2009-2010 ProFUSION embedded systems
* Copyright (C) 2009-2010 Samsung Electronics
* Copyright (C) 2012 Intel Corporation
*
* 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.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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.
*/
#include "config.h"
#include "FrameLoaderClientEfl.h"
#include "APICast.h"
#include "DocumentLoader.h"
#include "ErrorsEfl.h"
#include "FormState.h"
#include "FrameLoader.h"
#include "FrameNetworkingContextEfl.h"
#include "FrameTree.h"
#include "FrameView.h"
#include "HTMLFormElement.h"
#include "HTTPStatusCodes.h"
#include "MIMETypeRegistry.h"
#include "NotImplemented.h"
#include "Page.h"
#include "PluginDatabase.h"
#include "ProgressTracker.h"
#include "RenderPart.h"
#include "ResourceRequest.h"
#include "ResourceResponse.h"
#include "ScriptController.h"
#include "Settings.h"
#include "WebKitVersion.h"
#include "ewk_frame_private.h"
#include "ewk_private.h"
#include "ewk_settings.h"
#include "ewk_settings_private.h"
#include "ewk_view_private.h"
#include <Ecore_Evas.h>
#include <wtf/text/CString.h>
#include <wtf/text/StringConcatenate.h>
namespace WebCore {
FrameLoaderClientEfl::FrameLoaderClientEfl(Evas_Object* view)
: m_view(view)
, m_frame(0)
, m_userAgent("")
, m_customUserAgent("")
, m_pluginView(0)
, m_hasSentResponseToPlugin(false)
{
}
static String composeUserAgent()
{
return String(ewk_settings_default_user_agent_get());
}
void FrameLoaderClientEfl::setCustomUserAgent(const String& agent)
{
m_customUserAgent = agent;
}
const String& FrameLoaderClientEfl::customUserAgent() const
{
return m_customUserAgent;
}
String FrameLoaderClientEfl::userAgent(const KURL&)
{
if (!m_customUserAgent.isEmpty())
return m_customUserAgent;
if (m_userAgent.isEmpty())
m_userAgent = composeUserAgent();
return m_userAgent;
}
void FrameLoaderClientEfl::callPolicyFunction(FramePolicyFunction function, PolicyAction action)
{
Frame* f = EWKPrivate::coreFrame(m_frame);
ASSERT(f);
(f->loader()->policyChecker()->*function)(action);
}
WTF::PassRefPtr<DocumentLoader> FrameLoaderClientEfl::createDocumentLoader(const ResourceRequest& request, const SubstituteData& substituteData)
{
RefPtr<DocumentLoader> loader = DocumentLoader::create(request, substituteData);
if (substituteData.isValid())
loader->setDeferMainResourceDataLoad(false);
return loader.release();
}
void FrameLoaderClientEfl::dispatchWillSubmitForm(FramePolicyFunction function, PassRefPtr<FormState>)
{
// FIXME: This is surely too simple
ASSERT(function);
callPolicyFunction(function, PolicyUse);
}
void FrameLoaderClientEfl::committedLoad(DocumentLoader* loader, const char* data, int length)
{
if (!m_pluginView) {
loader->commitData(data, length);
// Let the media document handle the rest of loading itself, cancel here.
Frame* coreFrame = loader->frame();
if (coreFrame && coreFrame->document()->isMediaDocument())
loader->cancelMainResourceLoad(pluginWillHandleLoadError(loader->response()));
}
// We re-check here as the plugin can have been created
if (m_pluginView) {
if (!m_hasSentResponseToPlugin) {
m_pluginView->didReceiveResponse(loader->response());
m_hasSentResponseToPlugin = true;
}
m_pluginView->didReceiveData(data, length);
}
}
void FrameLoaderClientEfl::dispatchDidReplaceStateWithinPage()
{
notImplemented();
}
void FrameLoaderClientEfl::dispatchDidPushStateWithinPage()
{
notImplemented();
}
void FrameLoaderClientEfl::dispatchDidPopStateWithinPage()
{
notImplemented();
}
void FrameLoaderClientEfl::dispatchDidReceiveAuthenticationChallenge(DocumentLoader*, unsigned long /*identifier*/, const AuthenticationChallenge&)
{
notImplemented();
}
void FrameLoaderClientEfl::dispatchDidCancelAuthenticationChallenge(DocumentLoader*, unsigned long /*identifier*/, const AuthenticationChallenge&)
{
notImplemented();
}
void FrameLoaderClientEfl::dispatchWillSendRequest(DocumentLoader* loader, unsigned long identifier, ResourceRequest& coreRequest, const ResourceResponse& coreResponse)
{
CString url = coreRequest.url().string().utf8();
CString firstParty = coreRequest.firstPartyForCookies().string().utf8();
CString httpMethod = coreRequest.httpMethod().utf8();
DBG("Resource url=%s, first_party=%s, http_method=%s", url.data(), firstParty.data(), httpMethod.data());
// We want to distinguish between a request for a document to be loaded into
// the main frame, a sub-frame, or the sub-objects in that document.
bool isMainFrameRequest = false;
if (loader) {
const FrameLoader* frameLoader = loader->frameLoader();
isMainFrameRequest = (loader == frameLoader->provisionalDocumentLoader() && frameLoader->isLoadingMainFrame());
}
Ewk_Frame_Resource_Request request = { 0, firstParty.data(), httpMethod.data(), identifier, m_frame, isMainFrameRequest };
Ewk_Frame_Resource_Request orig = request; /* Initialize const fields. */
orig.url = request.url = url.data();
Ewk_Frame_Resource_Response* redirectResponse;
Ewk_Frame_Resource_Response responseBuffer;
CString redirectUrl, mimeType;
if (coreResponse.isNull())
redirectResponse = 0;
else {
redirectUrl = coreResponse.url().string().utf8();
mimeType = coreResponse.mimeType().utf8();
responseBuffer.url = redirectUrl.data();
responseBuffer.status_code = coreResponse.httpStatusCode();
responseBuffer.identifier = identifier;
responseBuffer.mime_type = mimeType.data();
redirectResponse = &responseBuffer;
}
Ewk_Frame_Resource_Messages messages = { &request, redirectResponse };
ewk_frame_request_will_send(m_frame, &messages);
evas_object_smart_callback_call(m_view, "resource,request,willsend", &messages);
if (request.url != orig.url) {
coreRequest.setURL(KURL(KURL(), request.url));
// Calling client might have changed our url pointer.
// Free the new allocated string.
free(const_cast<char*>(request.url));
}
}
bool FrameLoaderClientEfl::shouldUseCredentialStorage(DocumentLoader*, unsigned long)
{
notImplemented();
return false;
}
void FrameLoaderClientEfl::assignIdentifierToInitialRequest(unsigned long identifier, DocumentLoader* loader, const ResourceRequest& coreRequest)
{
CString url = coreRequest.url().string().utf8();
CString firstParty = coreRequest.firstPartyForCookies().string().utf8();
CString httpMethod = coreRequest.httpMethod().utf8();
DBG("Resource url=%s, First party=%s, HTTP method=%s", url.data(), firstParty.data(), httpMethod.data());
bool isMainFrameRequest = false;
if (loader) {
const FrameLoader* frameLoader = loader->frameLoader();
isMainFrameRequest = (loader == frameLoader->provisionalDocumentLoader() && frameLoader->isLoadingMainFrame());
}
Ewk_Frame_Resource_Request request = { url.data(), firstParty.data(), httpMethod.data(), identifier, m_frame, isMainFrameRequest };
ewk_frame_request_assign_identifier(m_frame, &request);
evas_object_smart_callback_call(m_view, "resource,request,new", &request);
}
void FrameLoaderClientEfl::postProgressStartedNotification()
{
ewk_frame_load_started(m_frame);
postProgressEstimateChangedNotification();
}
void FrameLoaderClientEfl::postProgressEstimateChangedNotification()
{
ewk_frame_load_progress_changed(m_frame);
}
void FrameLoaderClientEfl::postProgressFinishedNotification()
{
notImplemented();
}
void FrameLoaderClientEfl::frameLoaderDestroyed()
{
if (m_frame)
ewk_frame_core_gone(m_frame);
m_frame = 0;
delete this;
}
void FrameLoaderClientEfl::dispatchDidReceiveResponse(DocumentLoader* loader, unsigned long identifier, const ResourceResponse& coreResponse)
{
// Update our knowledge of request soup flags - some are only set
// after the request is done.
loader->request().setSoupMessageFlags(coreResponse.soupMessageFlags());
m_response = coreResponse;
CString mimeType = coreResponse.mimeType().utf8();
Ewk_Frame_Resource_Response response = { 0, coreResponse.httpStatusCode(), identifier, mimeType.data() };
CString url = coreResponse.url().string().utf8();
response.url = url.data();
ewk_frame_response_received(m_frame, &response);
evas_object_smart_callback_call(m_view, "resource,response,received", &response);
}
void FrameLoaderClientEfl::dispatchDecidePolicyForResponse(FramePolicyFunction function, const ResourceResponse& response, const ResourceRequest& resourceRequest)
{
// we need to call directly here (currently callPolicyFunction does that!)
ASSERT(function);
if (resourceRequest.isNull()) {
callPolicyFunction(function, PolicyIgnore);
return;
}
// Ignore responses with an HTTP status code of 204 (No Content)
if (response.httpStatusCode() == HTTPNoContent) {
callPolicyFunction(function, PolicyIgnore);
return;
}
if (canShowMIMEType(response.mimeType()))
callPolicyFunction(function, PolicyUse);
else
callPolicyFunction(function, PolicyDownload);
}
void FrameLoaderClientEfl::dispatchDecidePolicyForNewWindowAction(FramePolicyFunction function, const NavigationAction&, const ResourceRequest& resourceRequest, PassRefPtr<FormState>, const String&)
{
ASSERT(function);
ASSERT(m_frame);
if (resourceRequest.isNull()) {
callPolicyFunction(function, PolicyIgnore);
return;
}
// if not acceptNavigationRequest - look at Qt -> PolicyIgnore;
// FIXME: do proper check and only reset forms when on PolicyIgnore
Frame* f = EWKPrivate::coreFrame(m_frame);
f->loader()->resetMultipleFormSubmissionProtection();
callPolicyFunction(function, PolicyUse);
}
void FrameLoaderClientEfl::dispatchDecidePolicyForNavigationAction(FramePolicyFunction function, const NavigationAction& action, const ResourceRequest& resourceRequest, PassRefPtr<FormState>)
{
ASSERT(function);
ASSERT(m_frame);
if (resourceRequest.isNull()) {
callPolicyFunction(function, PolicyIgnore);
return;
}
// if not acceptNavigationRequest - look at Qt -> PolicyIgnore;
// FIXME: do proper check and only reset forms when on PolicyIgnore
CString url = resourceRequest.url().string().utf8();
CString firstParty = resourceRequest.firstPartyForCookies().string().utf8();
CString httpMethod = resourceRequest.httpMethod().utf8();
Ewk_Frame_Resource_Request request = { url.data(), firstParty.data(), httpMethod.data(), 0, m_frame, false };
bool ret = ewk_view_navigation_policy_decision(m_view, &request, static_cast<Ewk_Navigation_Type>(action.type()));
PolicyAction policy;
if (!ret)
policy = PolicyIgnore;
else {
if (action.type() == NavigationTypeFormSubmitted || action.type() == NavigationTypeFormResubmitted) {
Frame* f = EWKPrivate::coreFrame(m_frame);
f->loader()->resetMultipleFormSubmissionProtection();
}
policy = PolicyUse;
}
callPolicyFunction(function, policy);
}
PassRefPtr<Widget> FrameLoaderClientEfl::createPlugin(const IntSize& pluginSize, HTMLPlugInElement* element, const KURL& url, const Vector<String>& paramNames, const Vector<String>& paramValues, const String& mimeType, bool loadManually)
{
ASSERT(m_frame);
ASSERT(m_view);
return ewk_view_plugin_create(m_view, m_frame, pluginSize,
element, url, paramNames, paramValues,
mimeType, loadManually);
}
PassRefPtr<Frame> FrameLoaderClientEfl::createFrame(const KURL& url, const String& name, HTMLFrameOwnerElement* ownerElement, const String& referrer, bool /*allowsScrolling*/, int /*marginWidth*/, int /*marginHeight*/)
{
ASSERT(m_frame);
ASSERT(m_view);
return ewk_view_frame_create(m_view, m_frame, name, ownerElement, url, referrer);
}
void FrameLoaderClientEfl::redirectDataToPlugin(Widget* pluginWidget)
{
m_pluginView = toPluginView(pluginWidget);
if (pluginWidget)
m_hasSentResponseToPlugin = false;
}
PassRefPtr<Widget> FrameLoaderClientEfl::createJavaAppletWidget(const IntSize&, HTMLAppletElement*, const KURL&,
const Vector<String>& /*paramNames*/, const Vector<String>& /*paramValues*/)
{
notImplemented();
return 0;
}
ObjectContentType FrameLoaderClientEfl::objectContentType(const KURL& url, const String& mimeType, bool shouldPreferPlugInsForImages)
{
// FIXME: once plugin support is enabled, this method needs to correctly handle the 'shouldPreferPlugInsForImages' flag. See
// WebCore::FrameLoader::defaultObjectContentType() for an example.
UNUSED_PARAM(shouldPreferPlugInsForImages);
if (url.isEmpty() && mimeType.isEmpty())
return ObjectContentNone;
// We don't use MIMETypeRegistry::getMIMETypeForPath() because it returns "application/octet-stream" upon failure
String type = mimeType;
if (type.isEmpty())
type = MIMETypeRegistry::getMIMETypeForExtension(url.path().substring(url.path().reverseFind('.') + 1));
if (type.isEmpty())
return ObjectContentFrame;
if (MIMETypeRegistry::isSupportedImageMIMEType(type))
return ObjectContentImage;
#if 0 // PluginDatabase is disabled until we have Plugin system done.
if (PluginDatabase::installedPlugins()->isMIMETypeRegistered(mimeType))
return ObjectContentNetscapePlugin;
#endif
if (MIMETypeRegistry::isSupportedNonImageMIMEType(type))
return ObjectContentFrame;
if (url.protocol() == "about")
return ObjectContentFrame;
return ObjectContentNone;
}
String FrameLoaderClientEfl::overrideMediaType() const
{
return String::fromUTF8(ewk_settings_css_media_type_get());
}
void FrameLoaderClientEfl::dispatchDidClearWindowObjectInWorld(DOMWrapperWorld* world)
{
if (world != mainThreadNormalWorld())
return;
Frame* coreFrame = EWKPrivate::coreFrame(m_frame);
ASSERT(coreFrame);
Settings* settings = coreFrame->settings();
if (!settings || !settings->isScriptEnabled())
return;
Ewk_Window_Object_Cleared_Event event;
event.context = toGlobalRef(coreFrame->script()->globalObject(mainThreadNormalWorld())->globalExec());
event.windowObject = toRef(coreFrame->script()->globalObject(mainThreadNormalWorld()));
event.frame = m_frame;
evas_object_smart_callback_call(m_view, "window,object,cleared", &event);
#if ENABLE(NETSCAPE_PLUGIN_API)
ewk_view_js_window_object_clear(m_view, m_frame);
#endif
}
void FrameLoaderClientEfl::documentElementAvailable()
{
return;
}
void FrameLoaderClientEfl::didPerformFirstNavigation() const
{
ewk_frame_did_perform_first_navigation(m_frame);
}
void FrameLoaderClientEfl::registerForIconNotification(bool)
{
notImplemented();
}
void FrameLoaderClientEfl::setMainFrameDocumentReady(bool)
{
// this is only interesting once we provide an external API for the DOM
}
bool FrameLoaderClientEfl::hasWebView() const
{
if (!m_view)
return false;
return true;
}
bool FrameLoaderClientEfl::hasFrameView() const
{
notImplemented();
return true;
}
void FrameLoaderClientEfl::dispatchDidFinishLoad()
{
ewk_frame_load_finished(m_frame, 0, 0, 0, 0, 0);
}
void FrameLoaderClientEfl::frameLoadCompleted()
{
// Note: Can be called multiple times.
}
void FrameLoaderClientEfl::saveViewStateToItem(HistoryItem* item)
{
ewk_frame_view_state_save(m_frame, item);
}
void FrameLoaderClientEfl::restoreViewState()
{
ASSERT(m_frame);
ASSERT(m_view);
ewk_view_restore_state(m_view, m_frame);
}
void FrameLoaderClientEfl::updateGlobalHistoryRedirectLinks()
{
WebCore::Frame* frame = EWKPrivate::coreFrame(m_frame);
if (!frame)
return;
WebCore::DocumentLoader* loader = frame->loader()->documentLoader();
if (!loader)
return;
if (!loader->clientRedirectSourceForHistory().isNull()) {
const CString& sourceURL = loader->clientRedirectSourceForHistory().utf8();
const CString& destinationURL = loader->clientRedirectDestinationForHistory().utf8();
Ewk_View_Redirection_Data data = { sourceURL.data(), destinationURL.data() };
evas_object_smart_callback_call(m_view, "perform,client,redirect", &data);
}
if (!loader->serverRedirectSourceForHistory().isNull()) {
const CString& sourceURL = loader->serverRedirectSourceForHistory().utf8();
const CString& destinationURL = loader->serverRedirectDestinationForHistory().utf8();
Ewk_View_Redirection_Data data = { sourceURL.data(), destinationURL.data() };
evas_object_smart_callback_call(m_view, "perform,server,redirect", &data);
}
}
bool FrameLoaderClientEfl::shouldGoToHistoryItem(HistoryItem* item) const
{
// FIXME: This is a very simple implementation. More sophisticated
// implementation would delegate the decision to a PolicyDelegate.
// See mac implementation for example.
return item;
}
bool FrameLoaderClientEfl::shouldStopLoadingForHistoryItem(HistoryItem*) const
{
return true;
}
void FrameLoaderClientEfl::didDisplayInsecureContent()
{
ewk_frame_mixed_content_displayed_set(m_frame, true);
}
void FrameLoaderClientEfl::didRunInsecureContent(SecurityOrigin*, const KURL&)
{
ewk_frame_mixed_content_run_set(m_frame, true);
}
void FrameLoaderClientEfl::didDetectXSS(const KURL& insecureURL, bool didBlockEntirePage)
{
CString cs = insecureURL.string().utf8();
Ewk_Frame_Xss_Notification xssInfo = { cs.data(), didBlockEntirePage };
ewk_frame_xss_detected(m_frame, &xssInfo);
}
void FrameLoaderClientEfl::forceLayout()
{
ewk_frame_force_layout(m_frame);
}
void FrameLoaderClientEfl::forceLayoutForNonHTML()
{
}
void FrameLoaderClientEfl::setCopiesOnScroll()
{
// apparently mac specific (Qt comment)
}
void FrameLoaderClientEfl::detachedFromParent2()
{
}
void FrameLoaderClientEfl::detachedFromParent3()
{
}
void FrameLoaderClientEfl::loadedFromCachedPage()
{
notImplemented();
}
void FrameLoaderClientEfl::dispatchDidHandleOnloadEvents()
{
ewk_view_onload_event(m_view, m_frame);
}
void FrameLoaderClientEfl::dispatchDidReceiveServerRedirectForProvisionalLoad()
{
ewk_frame_redirect_provisional_load(m_frame);
}
void FrameLoaderClientEfl::dispatchDidCancelClientRedirect()
{
ewk_frame_redirect_cancelled(m_frame);
}
void FrameLoaderClientEfl::dispatchWillPerformClientRedirect(const KURL& url, double, double)
{
ewk_frame_redirect_requested(m_frame, url.string().utf8().data());
}
void FrameLoaderClientEfl::dispatchDidChangeLocationWithinPage()
{
ewk_frame_uri_changed(m_frame);
if (!isLoadingMainFrame())
return;
ewk_view_uri_changed(m_view);
}
void FrameLoaderClientEfl::dispatchWillClose()
{
notImplemented();
}
void FrameLoaderClientEfl::dispatchDidReceiveIcon()
{
// IconController loads icons only for the main frame.
ASSERT(isLoadingMainFrame());
ewk_view_frame_main_icon_received(m_view);
}
void FrameLoaderClientEfl::dispatchDidStartProvisionalLoad()
{
ewk_frame_load_provisional(m_frame);
if (isLoadingMainFrame())
ewk_view_load_provisional(m_view);
}
void FrameLoaderClientEfl::dispatchDidReceiveTitle(const StringWithDirection& title)
{
Ewk_Text_With_Direction ewkTitle;
CString cs = title.string().utf8();
ewkTitle.string = cs.data();
ewkTitle.direction = (title.direction() == LTR) ? EWK_TEXT_DIRECTION_LEFT_TO_RIGHT : EWK_TEXT_DIRECTION_RIGHT_TO_LEFT;
ewk_frame_title_set(m_frame, &ewkTitle);
if (!isLoadingMainFrame())
return;
ewk_view_title_set(m_view, &ewkTitle);
}
void FrameLoaderClientEfl::dispatchDidChangeIcons(WebCore::IconType iconType)
{
// Other touch types are apple-specific
ASSERT_UNUSED(iconType, iconType == WebCore::Favicon);
ewk_frame_icon_changed(m_frame);
}
void FrameLoaderClientEfl::dispatchDidCommitLoad()
{
ewk_frame_uri_changed(m_frame);
ewk_frame_load_committed(m_frame);
if (!isLoadingMainFrame())
return;
ewk_view_title_set(m_view, 0);
ewk_view_uri_changed(m_view);
}
void FrameLoaderClientEfl::dispatchDidFinishDocumentLoad()
{
ewk_frame_load_document_finished(m_frame);
}
void FrameLoaderClientEfl::dispatchDidLayout(LayoutMilestones milestones)
{
if (milestones & DidFirstLayout)
ewk_frame_load_firstlayout_finished(m_frame);
if (milestones & DidFirstVisuallyNonEmptyLayout)
ewk_frame_load_firstlayout_nonempty_finished(m_frame);
}
void FrameLoaderClientEfl::dispatchShow()
{
ewk_view_load_show(m_view);
}
void FrameLoaderClientEfl::cancelPolicyCheck()
{
notImplemented();
}
void FrameLoaderClientEfl::willChangeTitle(DocumentLoader*)
{
// no need for, dispatchDidReceiveTitle is the right callback
}
void FrameLoaderClientEfl::didChangeTitle(DocumentLoader*)
{
// no need for, dispatchDidReceiveTitle is the right callback
}
bool FrameLoaderClientEfl::canHandleRequest(const ResourceRequest&) const
{
notImplemented();
return true;
}
bool FrameLoaderClientEfl::canShowMIMETypeAsHTML(const String& /*MIMEType*/) const
{
notImplemented();
return false;
}
bool FrameLoaderClientEfl::canShowMIMEType(const String& MIMEType) const
{
if (MIMETypeRegistry::canShowMIMEType(MIMEType))
return true;
#if 0 // PluginDatabase is disabled until we have Plugin system done.
if (PluginDatabase::installedPlugins()->isMIMETypeRegistered(MIMEType))
return true;
#endif
return false;
}
bool FrameLoaderClientEfl::representationExistsForURLScheme(const String&) const
{
return false;
}
String FrameLoaderClientEfl::generatedMIMETypeForURLScheme(const String&) const
{
notImplemented();
return String();
}
void FrameLoaderClientEfl::finishedLoading(DocumentLoader*)
{
if (!m_pluginView)
return;
m_pluginView->didFinishLoading();
m_pluginView = 0;
m_hasSentResponseToPlugin = false;
}
void FrameLoaderClientEfl::provisionalLoadStarted()
{
notImplemented();
}
void FrameLoaderClientEfl::didFinishLoad()
{
notImplemented();
}
void FrameLoaderClientEfl::prepareForDataSourceReplacement()
{
notImplemented();
}
void FrameLoaderClientEfl::setTitle(const StringWithDirection&, const KURL&)
{
// no need for, dispatchDidReceiveTitle is the right callback
}
void FrameLoaderClientEfl::dispatchDidReceiveContentLength(DocumentLoader*, unsigned long /*identifier*/, int /*dataLength*/)
{
notImplemented();
}
void FrameLoaderClientEfl::dispatchDidFinishLoading(DocumentLoader*, unsigned long identifier)
{
ewk_frame_load_resource_finished(m_frame, identifier);
evas_object_smart_callback_call(m_view, "load,resource,finished", &identifier);
}
void FrameLoaderClientEfl::dispatchDidFailLoading(DocumentLoader*, unsigned long identifier, const ResourceError& err)
{
Ewk_Frame_Load_Error error;
CString errorDomain = err.domain().utf8();
CString errorDescription = err.localizedDescription().utf8();
CString failingUrl = err.failingURL().utf8();
DBG("ewkFrame=%p, resource=%ld, error=%s (%d, cancellation=%hhu) \"%s\", url=%s",
m_frame, identifier, errorDomain.data(), err.errorCode(), err.isCancellation(),
errorDescription.data(), failingUrl.data());
error.code = err.errorCode();
error.is_cancellation = err.isCancellation();
error.domain = errorDomain.data();
error.description = errorDescription.data();
error.failing_url = failingUrl.data();
error.resource_identifier = identifier;
error.frame = m_frame;
ewk_frame_load_resource_failed(m_frame, &error);
evas_object_smart_callback_call(m_view, "load,resource,failed", &error);
}
bool FrameLoaderClientEfl::dispatchDidLoadResourceFromMemoryCache(DocumentLoader*, const ResourceRequest&, const ResourceResponse&, int /*length*/)
{
notImplemented();
return false;
}
void FrameLoaderClientEfl::dispatchDidLoadResourceByXMLHttpRequest(unsigned long, const String&)
{
notImplemented();
}
void FrameLoaderClientEfl::dispatchDidFailProvisionalLoad(const ResourceError& err)
{
Ewk_Frame_Load_Error error;
CString errorDomain = err.domain().utf8();
CString errorDescription = err.localizedDescription().utf8();
CString failingUrl = err.failingURL().utf8();
DBG("ewkFrame=%p, error=%s (%d, cancellation=%hhu) \"%s\", url=%s",
m_frame, errorDomain.data(), err.errorCode(), err.isCancellation(),
errorDescription.data(), failingUrl.data());
error.code = err.errorCode();
error.is_cancellation = err.isCancellation();
error.domain = errorDomain.data();
error.description = errorDescription.data();
error.failing_url = failingUrl.data();
error.resource_identifier = 0;
error.frame = m_frame;
ewk_frame_load_provisional_failed(m_frame, &error);
if (isLoadingMainFrame())
ewk_view_load_provisional_failed(m_view, &error);
dispatchDidFailLoad(err);
}
void FrameLoaderClientEfl::dispatchDidFailLoad(const ResourceError& err)
{
ewk_frame_load_error(m_frame,
err.domain().utf8().data(),
err.errorCode(), err.isCancellation(),
err.localizedDescription().utf8().data(),
err.failingURL().utf8().data());
ewk_frame_load_finished(m_frame,
err.domain().utf8().data(),
err.errorCode(),
err.isCancellation(),
err.localizedDescription().utf8().data(),
err.failingURL().utf8().data());
}
void FrameLoaderClientEfl::convertMainResourceLoadToDownload(DocumentLoader*, const ResourceRequest& request, const ResourceResponse&)
{
if (!m_view)
return;
CString url = request.url().string().utf8();
Ewk_Download download;
download.url = url.data();
download.suggested_name = 0;
ewk_view_download_request(m_view, &download);
}
ResourceError FrameLoaderClientEfl::cancelledError(const ResourceRequest& request)
{
return WebCore::cancelledError(request);
}
ResourceError FrameLoaderClientEfl::blockedError(const ResourceRequest& request)
{
return WebCore::blockedError(request);
}
ResourceError FrameLoaderClientEfl::cannotShowURLError(const ResourceRequest& request)
{
return WebCore::cannotShowURLError(request);
}
ResourceError FrameLoaderClientEfl::interruptedForPolicyChangeError(const ResourceRequest& request)
{
return WebCore::interruptedForPolicyChangeError(request);
}
ResourceError FrameLoaderClientEfl::cannotShowMIMETypeError(const ResourceResponse& response)
{
return WebCore::cannotShowMIMETypeError(response);
}
ResourceError FrameLoaderClientEfl::fileDoesNotExistError(const ResourceResponse& response)
{
return WebCore::fileDoesNotExistError(response);
}
ResourceError FrameLoaderClientEfl::pluginWillHandleLoadError(const ResourceResponse& response)
{
return WebCore::pluginWillHandleLoadError(response);
}
bool FrameLoaderClientEfl::shouldFallBack(const ResourceError& error)
{
return !(error.isCancellation() || error.errorCode() == PolicyErrorFrameLoadInterruptedByPolicyChange || error.errorCode() == PluginErrorWillHandleLoad);
}
bool FrameLoaderClientEfl::canCachePage() const
{
return true;
}
Frame* FrameLoaderClientEfl::dispatchCreatePage(const NavigationAction&)
{
if (!m_view)
return 0;
Evas_Object* newView = ewk_view_window_create(m_view, EINA_FALSE, 0);
Evas_Object* mainFrame;
if (!newView)
mainFrame = m_frame;
else
mainFrame = ewk_view_frame_main_get(newView);
return EWKPrivate::coreFrame(mainFrame);
}
void FrameLoaderClientEfl::dispatchUnableToImplementPolicy(const ResourceError&)
{
notImplemented();
}
void FrameLoaderClientEfl::setMainDocumentError(DocumentLoader*, const ResourceError& error)
{
if (!m_pluginView)
return;
m_pluginView->didFail(error);
m_pluginView = 0;
m_hasSentResponseToPlugin = false;
}
void FrameLoaderClientEfl::startDownload(const ResourceRequest& request, const String& suggestedName)
{
if (!m_view)
return;
CString url = request.url().string().utf8();
CString suggestedNameString = suggestedName.utf8();
Ewk_Download download;
download.url = url.data();
download.suggested_name = suggestedNameString.data();
ewk_view_download_request(m_view, &download);
}
void FrameLoaderClientEfl::updateGlobalHistory()
{
WebCore::Frame* frame = EWKPrivate::coreFrame(m_frame);
if (!frame)
return;
WebCore::DocumentLoader* loader = frame->loader()->documentLoader();
if (!loader)
return;
const FrameLoader* frameLoader = loader->frameLoader();
const bool isMainFrameRequest = frameLoader && (loader == frameLoader->provisionalDocumentLoader()) && frameLoader->isLoadingMainFrame();
const CString& urlForHistory = loader->urlForHistory().string().utf8();
const CString& title = loader->title().string().utf8();
const CString& firstParty = loader->request().firstPartyForCookies().string().utf8();
const CString& clientRedirectSource = loader->clientRedirectSourceForHistory().utf8();
const CString& originalURL = loader->originalURL().string().utf8();
const CString& httpMethod = loader->request().httpMethod().utf8();
const CString& responseURL = loader->responseURL().string().utf8();
const CString& mimeType = loader->response().mimeType().utf8();
Ewk_Frame_Resource_Request request = { originalURL.data(), firstParty.data(), httpMethod.data(), 0, m_frame, isMainFrameRequest };
Ewk_Frame_Resource_Response response = { responseURL.data(), loader->response().httpStatusCode(), 0, mimeType.data() };
bool hasSubstituteData = loader->substituteData().isValid();
Ewk_View_Navigation_Data data = { urlForHistory.data(), title.data(), &request, &response, hasSubstituteData, clientRedirectSource.data() };
evas_object_smart_callback_call(m_view, "navigate,with,data", &data);
}
void FrameLoaderClientEfl::savePlatformDataToCachedFrame(CachedFrame*)
{
notImplemented();
}
void FrameLoaderClientEfl::transitionToCommittedFromCachedFrame(CachedFrame*)
{
}
void FrameLoaderClientEfl::transitionToCommittedForNewPage()
{
ASSERT(m_frame);
ASSERT(m_view);
ewk_frame_view_create_for_view(m_frame, m_view);
if (isLoadingMainFrame()) {
ewk_view_frame_view_creation_notify(m_view);
ewk_view_frame_main_cleared(m_view);
}
}
void FrameLoaderClientEfl::didSaveToPageCache()
{
}
void FrameLoaderClientEfl::didRestoreFromPageCache()
{
}
void FrameLoaderClientEfl::dispatchDidBecomeFrameset(bool)
{
}
PassRefPtr<FrameNetworkingContext> FrameLoaderClientEfl::createNetworkingContext()
{
return FrameNetworkingContextEfl::create(EWKPrivate::coreFrame(m_frame), m_frame);
}
}
| bsd-3-clause |
jjyycchh/phantomjs | src/qt/qtwebkit/Source/WebCore/bindings/js/ScriptProfiler.cpp | 113 | 3300 | /*
* Copyright (C) 2010 Apple Inc. All rights reserved.
* Copyright (C) 2010 Google 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:
* 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.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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.
*/
#include "config.h"
#if ENABLE(JAVASCRIPT_DEBUGGER)
#include "ScriptProfiler.h"
#include "Frame.h"
#include "GCController.h"
#include "JSDOMBinding.h"
#include "JSDOMWindow.h"
#include "Page.h"
#include "ScriptObject.h"
#include "ScriptState.h"
#include <profiler/LegacyProfiler.h>
#include <wtf/Forward.h>
namespace WebCore {
void ScriptProfiler::collectGarbage()
{
gcController().garbageCollectSoon();
}
ScriptObject ScriptProfiler::objectByHeapObjectId(unsigned)
{
return ScriptObject();
}
unsigned ScriptProfiler::getHeapObjectId(const ScriptValue&)
{
return 0;
}
void ScriptProfiler::start(ScriptState* state, const String& title)
{
JSC::LegacyProfiler::profiler()->startProfiling(state, title);
}
void ScriptProfiler::startForPage(Page* inspectedPage, const String& title)
{
JSC::ExecState* scriptState = toJSDOMWindow(inspectedPage->mainFrame(), debuggerWorld())->globalExec();
start(scriptState, title);
}
#if ENABLE(WORKERS)
void ScriptProfiler::startForWorkerGlobalScope(WorkerGlobalScope* context, const String& title)
{
start(scriptStateFromWorkerGlobalScope(context), title);
}
#endif
PassRefPtr<ScriptProfile> ScriptProfiler::stop(ScriptState* state, const String& title)
{
RefPtr<JSC::Profile> profile = JSC::LegacyProfiler::profiler()->stopProfiling(state, title);
return ScriptProfile::create(profile);
}
PassRefPtr<ScriptProfile> ScriptProfiler::stopForPage(Page* inspectedPage, const String& title)
{
JSC::ExecState* scriptState = toJSDOMWindow(inspectedPage->mainFrame(), debuggerWorld())->globalExec();
return stop(scriptState, title);
}
#if ENABLE(WORKERS)
PassRefPtr<ScriptProfile> ScriptProfiler::stopForWorkerGlobalScope(WorkerGlobalScope* context, const String& title)
{
return stop(scriptStateFromWorkerGlobalScope(context), title);
}
#endif
} // namespace WebCore
#endif // ENABLE(JAVASCRIPT_DEBUGGER)
| bsd-3-clause |
aljscott/phantomjs | src/qt/qtwebkit/Source/WebCore/html/FTPDirectoryDocument.cpp | 113 | 15206 | /*
* Copyright (C) 2007, 2008 Apple 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:
* 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.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* 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.
*/
#include "config.h"
#if ENABLE(FTPDIR)
#include "FTPDirectoryDocument.h"
#include "ExceptionCodePlaceholder.h"
#include "HTMLDocumentParser.h"
#include "HTMLNames.h"
#include "HTMLTableElement.h"
#include "LocalizedStrings.h"
#include "Logging.h"
#include "FTPDirectoryParser.h"
#include "SegmentedString.h"
#include "Settings.h"
#include "SharedBuffer.h"
#include "Text.h"
#include <wtf/CurrentTime.h>
#include <wtf/GregorianDateTime.h>
#include <wtf/StdLibExtras.h>
#include <wtf/text/CString.h>
#include <wtf/text/WTFString.h>
#include <wtf/unicode/CharacterNames.h>
using namespace std;
namespace WebCore {
using namespace HTMLNames;
class FTPDirectoryDocumentParser : public HTMLDocumentParser {
public:
static PassRefPtr<FTPDirectoryDocumentParser> create(HTMLDocument* document)
{
return adoptRef(new FTPDirectoryDocumentParser(document));
}
virtual void append(PassRefPtr<StringImpl>);
virtual void finish();
virtual bool isWaitingForScripts() const { return false; }
inline void checkBuffer(int len = 10)
{
if ((m_dest - m_buffer) > m_size - len) {
// Enlarge buffer
int newSize = max(m_size * 2, m_size + len);
int oldOffset = m_dest - m_buffer;
m_buffer = static_cast<UChar*>(fastRealloc(m_buffer, newSize * sizeof(UChar)));
m_dest = m_buffer + oldOffset;
m_size = newSize;
}
}
private:
FTPDirectoryDocumentParser(HTMLDocument*);
// The parser will attempt to load the document template specified via the preference
// Failing that, it will fall back and create the basic document which will have a minimal
// table for presenting the FTP directory in a useful manner
bool loadDocumentTemplate();
void createBasicDocument();
void parseAndAppendOneLine(const String&);
void appendEntry(const String& name, const String& size, const String& date, bool isDirectory);
PassRefPtr<Element> createTDForFilename(const String&);
RefPtr<HTMLTableElement> m_tableElement;
bool m_skipLF;
int m_size;
UChar* m_buffer;
UChar* m_dest;
String m_carryOver;
ListState m_listState;
};
FTPDirectoryDocumentParser::FTPDirectoryDocumentParser(HTMLDocument* document)
: HTMLDocumentParser(document, false)
, m_skipLF(false)
, m_size(254)
, m_buffer(static_cast<UChar*>(fastMalloc(sizeof(UChar) * m_size)))
, m_dest(m_buffer)
{
}
void FTPDirectoryDocumentParser::appendEntry(const String& filename, const String& size, const String& date, bool isDirectory)
{
RefPtr<Element> rowElement = m_tableElement->insertRow(-1, IGNORE_EXCEPTION);
rowElement->setAttribute("class", "ftpDirectoryEntryRow", IGNORE_EXCEPTION);
RefPtr<Element> element = document()->createElement(tdTag, false);
element->appendChild(Text::create(document(), String(&noBreakSpace, 1)), IGNORE_EXCEPTION);
if (isDirectory)
element->setAttribute("class", "ftpDirectoryIcon ftpDirectoryTypeDirectory", IGNORE_EXCEPTION);
else
element->setAttribute("class", "ftpDirectoryIcon ftpDirectoryTypeFile", IGNORE_EXCEPTION);
rowElement->appendChild(element, IGNORE_EXCEPTION);
element = createTDForFilename(filename);
element->setAttribute("class", "ftpDirectoryFileName", IGNORE_EXCEPTION);
rowElement->appendChild(element, IGNORE_EXCEPTION);
element = document()->createElement(tdTag, false);
element->appendChild(Text::create(document(), date), IGNORE_EXCEPTION);
element->setAttribute("class", "ftpDirectoryFileDate", IGNORE_EXCEPTION);
rowElement->appendChild(element, IGNORE_EXCEPTION);
element = document()->createElement(tdTag, false);
element->appendChild(Text::create(document(), size), IGNORE_EXCEPTION);
element->setAttribute("class", "ftpDirectoryFileSize", IGNORE_EXCEPTION);
rowElement->appendChild(element, IGNORE_EXCEPTION);
}
PassRefPtr<Element> FTPDirectoryDocumentParser::createTDForFilename(const String& filename)
{
String fullURL = document()->baseURL().string();
if (fullURL[fullURL.length() - 1] == '/')
fullURL.append(filename);
else
fullURL.append("/" + filename);
RefPtr<Element> anchorElement = document()->createElement(aTag, false);
anchorElement->setAttribute("href", fullURL, IGNORE_EXCEPTION);
anchorElement->appendChild(Text::create(document(), filename), IGNORE_EXCEPTION);
RefPtr<Element> tdElement = document()->createElement(tdTag, false);
tdElement->appendChild(anchorElement, IGNORE_EXCEPTION);
return tdElement.release();
}
static String processFilesizeString(const String& size, bool isDirectory)
{
if (isDirectory)
return "--";
bool valid;
int64_t bytes = size.toUInt64(&valid);
if (!valid)
return unknownFileSizeText();
if (bytes < 1000000)
return String::format("%.2f KB", static_cast<float>(bytes)/1000);
if (bytes < 1000000000)
return String::format("%.2f MB", static_cast<float>(bytes)/1000000);
return String::format("%.2f GB", static_cast<float>(bytes)/1000000000);
}
static bool wasLastDayOfMonth(int year, int month, int day)
{
static int lastDays[] = { 31, 0, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
if (month < 0 || month > 11)
return false;
if (month == 2) {
if (year % 4 == 0 && (year % 100 || year % 400 == 0)) {
if (day == 29)
return true;
return false;
}
if (day == 28)
return true;
return false;
}
return lastDays[month] == day;
}
static String processFileDateString(const FTPTime& fileTime)
{
// FIXME: Need to localize this string?
String timeOfDay;
if (!(fileTime.tm_hour == 0 && fileTime.tm_min == 0 && fileTime.tm_sec == 0)) {
int hour = fileTime.tm_hour;
ASSERT(hour >= 0 && hour < 24);
if (hour < 12) {
if (hour == 0)
hour = 12;
timeOfDay = String::format(", %i:%02i AM", hour, fileTime.tm_min);
} else {
hour = hour - 12;
if (hour == 0)
hour = 12;
timeOfDay = String::format(", %i:%02i PM", hour, fileTime.tm_min);
}
}
// If it was today or yesterday, lets just do that - but we have to compare to the current time
GregorianDateTime now;
now.setToCurrentLocalTime();
if (fileTime.tm_year == now.year()) {
if (fileTime.tm_mon == now.month()) {
if (fileTime.tm_mday == now.monthDay())
return "Today" + timeOfDay;
if (fileTime.tm_mday == now.monthDay() - 1)
return "Yesterday" + timeOfDay;
}
if (now.monthDay() == 1 && (now.month() == fileTime.tm_mon + 1 || (now.month() == 0 && fileTime.tm_mon == 11)) &&
wasLastDayOfMonth(fileTime.tm_year, fileTime.tm_mon, fileTime.tm_mday))
return "Yesterday" + timeOfDay;
}
if (fileTime.tm_year == now.year() - 1 && fileTime.tm_mon == 12 && fileTime.tm_mday == 31 && now.month() == 1 && now.monthDay() == 1)
return "Yesterday" + timeOfDay;
static const char* months[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", "???" };
int month = fileTime.tm_mon;
if (month < 0 || month > 11)
month = 12;
String dateString;
if (fileTime.tm_year > -1)
dateString = String(months[month]) + " " + String::number(fileTime.tm_mday) + ", " + String::number(fileTime.tm_year);
else
dateString = String(months[month]) + " " + String::number(fileTime.tm_mday) + ", " + String::number(now.year());
return dateString + timeOfDay;
}
void FTPDirectoryDocumentParser::parseAndAppendOneLine(const String& inputLine)
{
ListResult result;
CString latin1Input = inputLine.latin1();
FTPEntryType typeResult = parseOneFTPLine(latin1Input.data(), m_listState, result);
// FTPMiscEntry is a comment or usage statistic which we don't care about, and junk is invalid data - bail in these 2 cases
if (typeResult == FTPMiscEntry || typeResult == FTPJunkEntry)
return;
String filename(result.filename, result.filenameLength);
if (result.type == FTPDirectoryEntry) {
filename.append("/");
// We have no interest in linking to "current directory"
if (filename == "./")
return;
}
LOG(FTP, "Appending entry - %s, %s", filename.ascii().data(), result.fileSize.ascii().data());
appendEntry(filename, processFilesizeString(result.fileSize, result.type == FTPDirectoryEntry), processFileDateString(result.modifiedTime), result.type == FTPDirectoryEntry);
}
static inline PassRefPtr<SharedBuffer> createTemplateDocumentData(Settings* settings)
{
RefPtr<SharedBuffer> buffer = 0;
if (settings)
buffer = SharedBuffer::createWithContentsOfFile(settings->ftpDirectoryTemplatePath());
if (buffer)
LOG(FTP, "Loaded FTPDirectoryTemplate of length %i\n", buffer->size());
return buffer.release();
}
bool FTPDirectoryDocumentParser::loadDocumentTemplate()
{
DEFINE_STATIC_LOCAL(RefPtr<SharedBuffer>, templateDocumentData, (createTemplateDocumentData(document()->settings())));
// FIXME: Instead of storing the data, we'd rather actually parse the template data into the template Document once,
// store that document, then "copy" it whenever we get an FTP directory listing. There are complexities with this
// approach that make it worth putting this off.
if (!templateDocumentData) {
LOG_ERROR("Could not load templateData");
return false;
}
HTMLDocumentParser::insert(String(templateDocumentData->data(), templateDocumentData->size()));
RefPtr<Element> tableElement = document()->getElementById("ftpDirectoryTable");
if (!tableElement)
LOG_ERROR("Unable to find element by id \"ftpDirectoryTable\" in the template document.");
else if (!isHTMLTableElement(tableElement.get()))
LOG_ERROR("Element of id \"ftpDirectoryTable\" is not a table element");
else
m_tableElement = toHTMLTableElement(tableElement.get());
// Bail if we found the table element
if (m_tableElement)
return true;
// Otherwise create one manually
tableElement = document()->createElement(tableTag, false);
m_tableElement = toHTMLTableElement(tableElement.get());
m_tableElement->setAttribute("id", "ftpDirectoryTable", IGNORE_EXCEPTION);
// If we didn't find the table element, lets try to append our own to the body
// If that fails for some reason, cram it on the end of the document as a last
// ditch effort
if (Element* body = document()->body())
body->appendChild(m_tableElement, IGNORE_EXCEPTION);
else
document()->appendChild(m_tableElement, IGNORE_EXCEPTION);
return true;
}
void FTPDirectoryDocumentParser::createBasicDocument()
{
LOG(FTP, "Creating a basic FTP document structure as no template was loaded");
// FIXME: Make this "basic document" more acceptable
RefPtr<Element> bodyElement = document()->createElement(bodyTag, false);
document()->appendChild(bodyElement, IGNORE_EXCEPTION);
RefPtr<Element> tableElement = document()->createElement(tableTag, false);
m_tableElement = toHTMLTableElement(tableElement.get());
m_tableElement->setAttribute("id", "ftpDirectoryTable", IGNORE_EXCEPTION);
bodyElement->appendChild(m_tableElement, IGNORE_EXCEPTION);
}
void FTPDirectoryDocumentParser::append(PassRefPtr<StringImpl> inputSource)
{
String source(inputSource);
// Make sure we have the table element to append to by loading the template set in the pref, or
// creating a very basic document with the appropriate table
if (!m_tableElement) {
if (!loadDocumentTemplate())
createBasicDocument();
ASSERT(m_tableElement);
}
bool foundNewLine = false;
m_dest = m_buffer;
SegmentedString str = source;
while (!str.isEmpty()) {
UChar c = str.currentChar();
if (c == '\r') {
*m_dest++ = '\n';
foundNewLine = true;
// possibly skip an LF in the case of an CRLF sequence
m_skipLF = true;
} else if (c == '\n') {
if (!m_skipLF)
*m_dest++ = c;
else
m_skipLF = false;
} else {
*m_dest++ = c;
m_skipLF = false;
}
str.advance();
// Maybe enlarge the buffer
checkBuffer();
}
if (!foundNewLine) {
m_dest = m_buffer;
return;
}
UChar* start = m_buffer;
UChar* cursor = start;
while (cursor < m_dest) {
if (*cursor == '\n') {
m_carryOver.append(String(start, cursor - start));
LOG(FTP, "%s", m_carryOver.ascii().data());
parseAndAppendOneLine(m_carryOver);
m_carryOver = String();
start = ++cursor;
} else
cursor++;
}
// Copy the partial line we have left to the carryover buffer
if (cursor - start > 1)
m_carryOver.append(String(start, cursor - start - 1));
}
void FTPDirectoryDocumentParser::finish()
{
// Possible the last line in the listing had no newline, so try to parse it now
if (!m_carryOver.isEmpty()) {
parseAndAppendOneLine(m_carryOver);
m_carryOver = String();
}
m_tableElement = 0;
fastFree(m_buffer);
HTMLDocumentParser::finish();
}
FTPDirectoryDocument::FTPDirectoryDocument(Frame* frame, const KURL& url)
: HTMLDocument(frame, url)
{
#if !LOG_DISABLED
LogFTP.state = WTFLogChannelOn;
#endif
}
PassRefPtr<DocumentParser> FTPDirectoryDocument::createParser()
{
return FTPDirectoryDocumentParser::create(this);
}
}
#endif // ENABLE(FTPDIR)
| bsd-3-clause |
wuxianghou/phantomjs | src/qt/qtwebkit/Source/WebCore/svg/SVGTransform.cpp | 114 | 6294 | /*
* Copyright (C) 2004, 2005 Nikolas Zimmermann <zimmermann@kde.org>
* Copyright (C) 2004, 2005 Rob Buis <buis@kde.org>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "config.h"
#if ENABLE(SVG)
#include "SVGTransform.h"
#include "FloatConversion.h"
#include "FloatPoint.h"
#include "FloatSize.h"
#include "SVGAngle.h"
#include "SVGSVGElement.h"
#include <wtf/MathExtras.h>
#include <wtf/text/StringBuilder.h>
#include <wtf/text/WTFString.h>
namespace WebCore {
SVGTransform::SVGTransform()
: m_type(SVG_TRANSFORM_UNKNOWN)
, m_angle(0)
{
}
SVGTransform::SVGTransform(SVGTransformType type, ConstructionMode mode)
: m_type(type)
, m_angle(0)
{
if (mode == ConstructZeroTransform)
m_matrix = AffineTransform(0, 0, 0, 0, 0, 0);
}
SVGTransform::SVGTransform(const AffineTransform& matrix)
: m_type(SVG_TRANSFORM_MATRIX)
, m_angle(0)
, m_matrix(matrix)
{
}
void SVGTransform::setMatrix(const AffineTransform& matrix)
{
m_type = SVG_TRANSFORM_MATRIX;
m_angle = 0;
m_matrix = matrix;
}
void SVGTransform::updateSVGMatrix()
{
// The underlying matrix has been changed, alter the transformation type.
// Spec: In case the matrix object is changed directly (i.e., without using the methods on the SVGTransform interface itself)
// then the type of the SVGTransform changes to SVG_TRANSFORM_MATRIX.
m_type = SVG_TRANSFORM_MATRIX;
m_angle = 0;
}
void SVGTransform::setTranslate(float tx, float ty)
{
m_type = SVG_TRANSFORM_TRANSLATE;
m_angle = 0;
m_matrix.makeIdentity();
m_matrix.translate(tx, ty);
}
FloatPoint SVGTransform::translate() const
{
return FloatPoint::narrowPrecision(m_matrix.e(), m_matrix.f());
}
void SVGTransform::setScale(float sx, float sy)
{
m_type = SVG_TRANSFORM_SCALE;
m_angle = 0;
m_center = FloatPoint();
m_matrix.makeIdentity();
m_matrix.scaleNonUniform(sx, sy);
}
FloatSize SVGTransform::scale() const
{
return FloatSize::narrowPrecision(m_matrix.a(), m_matrix.d());
}
void SVGTransform::setRotate(float angle, float cx, float cy)
{
m_type = SVG_TRANSFORM_ROTATE;
m_angle = angle;
m_center = FloatPoint(cx, cy);
// TODO: toString() implementation, which can show cx, cy (need to be stored?)
m_matrix.makeIdentity();
m_matrix.translate(cx, cy);
m_matrix.rotate(angle);
m_matrix.translate(-cx, -cy);
}
void SVGTransform::setSkewX(float angle)
{
m_type = SVG_TRANSFORM_SKEWX;
m_angle = angle;
m_matrix.makeIdentity();
m_matrix.skewX(angle);
}
void SVGTransform::setSkewY(float angle)
{
m_type = SVG_TRANSFORM_SKEWY;
m_angle = angle;
m_matrix.makeIdentity();
m_matrix.skewY(angle);
}
const String& SVGTransform::transformTypePrefixForParsing(SVGTransformType type)
{
switch (type) {
case SVG_TRANSFORM_UNKNOWN:
return emptyString();
case SVG_TRANSFORM_MATRIX: {
DEFINE_STATIC_LOCAL(String, matrixString, (ASCIILiteral("matrix(")));
return matrixString;
}
case SVG_TRANSFORM_TRANSLATE: {
DEFINE_STATIC_LOCAL(String, translateString, (ASCIILiteral("translate(")));
return translateString;
}
case SVG_TRANSFORM_SCALE: {
DEFINE_STATIC_LOCAL(String, scaleString, (ASCIILiteral("scale(")));
return scaleString;
}
case SVG_TRANSFORM_ROTATE: {
DEFINE_STATIC_LOCAL(String, rotateString, (ASCIILiteral("rotate(")));
return rotateString;
}
case SVG_TRANSFORM_SKEWX: {
DEFINE_STATIC_LOCAL(String, skewXString, (ASCIILiteral("skewX(")));
return skewXString;
}
case SVG_TRANSFORM_SKEWY: {
DEFINE_STATIC_LOCAL(String, skewYString, (ASCIILiteral("skewY(")));
return skewYString;
}
}
ASSERT_NOT_REACHED();
return emptyString();
}
String SVGTransform::valueAsString() const
{
const String& prefix = transformTypePrefixForParsing(m_type);
switch (m_type) {
case SVG_TRANSFORM_UNKNOWN:
return prefix;
case SVG_TRANSFORM_MATRIX: {
StringBuilder builder;
builder.append(prefix + String::number(m_matrix.a()) + ' ' + String::number(m_matrix.b()) + ' ' + String::number(m_matrix.c()) + ' ' +
String::number(m_matrix.d()) + ' ' + String::number(m_matrix.e()) + ' ' + String::number(m_matrix.f()) + ')');
return builder.toString();
}
case SVG_TRANSFORM_TRANSLATE:
return prefix + String::number(m_matrix.e()) + ' ' + String::number(m_matrix.f()) + ')';
case SVG_TRANSFORM_SCALE:
return prefix + String::number(m_matrix.xScale()) + ' ' + String::number(m_matrix.yScale()) + ')';
case SVG_TRANSFORM_ROTATE: {
double angleInRad = deg2rad(m_angle);
double cosAngle = cos(angleInRad);
double sinAngle = sin(angleInRad);
float cx = narrowPrecisionToFloat(cosAngle != 1 ? (m_matrix.e() * (1 - cosAngle) - m_matrix.f() * sinAngle) / (1 - cosAngle) / 2 : 0);
float cy = narrowPrecisionToFloat(cosAngle != 1 ? (m_matrix.e() * sinAngle / (1 - cosAngle) + m_matrix.f()) / 2 : 0);
if (cx || cy)
return prefix + String::number(m_angle) + ' ' + String::number(cx) + ' ' + String::number(cy) + ')';
return prefix + String::number(m_angle) + ')';
}
case SVG_TRANSFORM_SKEWX:
return prefix + String::number(m_angle) + ')';
case SVG_TRANSFORM_SKEWY:
return prefix + String::number(m_angle) + ')';
}
ASSERT_NOT_REACHED();
return emptyString();
}
} // namespace WebCore
#endif // ENABLE(SVG)
| bsd-3-clause |
aljscott/phantomjs | src/qt/qtwebkit/Source/WebCore/platform/win/SharedTimerWin.cpp | 115 | 7804 | /*
* Copyright (C) 2006 Apple Computer, 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:
* 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.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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.
*/
#include "config.h"
#include "SharedTimer.h"
#include "Page.h"
#include "Settings.h"
#include "WebCoreInstanceHandle.h"
#include "Widget.h"
#include <wtf/Assertions.h>
#include <wtf/CurrentTime.h>
#include "WindowsExtras.h"
#include <mmsystem.h>
#if PLATFORM(WIN)
#include "PluginView.h"
#endif
// These aren't in winuser.h with the MSVS 2003 Platform SDK,
// so use default values in that case.
#ifndef USER_TIMER_MINIMUM
#define USER_TIMER_MINIMUM 0x0000000A
#endif
#ifndef USER_TIMER_MAXIMUM
#define USER_TIMER_MAXIMUM 0x7FFFFFFF
#endif
#ifndef QS_RAWINPUT
#define QS_RAWINPUT 0x0400
#endif
namespace WebCore {
static UINT timerID;
static void (*sharedTimerFiredFunction)();
static HANDLE timer;
static HWND timerWindowHandle = 0;
const LPCWSTR kTimerWindowClassName = L"TimerWindowClass";
#if !OS(WINCE)
static UINT timerFiredMessage = 0;
static HANDLE timerQueue;
static bool highResTimerActive;
static bool processingCustomTimerMessage = false;
static LONG pendingTimers;
const int timerResolution = 1; // To improve timer resolution, we call timeBeginPeriod/timeEndPeriod with this value to increase timer resolution to 1ms.
const int highResolutionThresholdMsec = 16; // Only activate high-res timer for sub-16ms timers (Windows can fire timers at 16ms intervals without changing the system resolution).
const int stopHighResTimerInMsec = 300; // Stop high-res timer after 0.3 seconds to lessen power consumption (we don't use a smaller time since oscillating between high and low resolution breaks timer accuracy on XP).
#endif
enum {
sharedTimerID = 1000,
endHighResTimerID = 1001,
};
LRESULT CALLBACK TimerWindowWndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
#if PLATFORM(WIN)
// Windows Media Player has a modal message loop that will deliver messages
// to us at inappropriate times and we will crash if we handle them when
// they are delivered. We repost all messages so that we will get to handle
// them once the modal loop exits.
if (PluginView::isCallingPlugin()) {
PostMessage(hWnd, message, wParam, lParam);
return 0;
}
#endif
if (message == WM_TIMER) {
if (wParam == sharedTimerID) {
KillTimer(timerWindowHandle, sharedTimerID);
sharedTimerFiredFunction();
}
#if !OS(WINCE)
else if (wParam == endHighResTimerID) {
KillTimer(timerWindowHandle, endHighResTimerID);
highResTimerActive = false;
timeEndPeriod(timerResolution);
}
} else if (message == timerFiredMessage) {
InterlockedExchange(&pendingTimers, 0);
processingCustomTimerMessage = true;
sharedTimerFiredFunction();
processingCustomTimerMessage = false;
#endif
} else
return DefWindowProc(hWnd, message, wParam, lParam);
return 0;
}
static void initializeOffScreenTimerWindow()
{
if (timerWindowHandle)
return;
#if OS(WINCE)
WNDCLASS wcex;
memset(&wcex, 0, sizeof(WNDCLASS));
#else
WNDCLASSEX wcex;
memset(&wcex, 0, sizeof(WNDCLASSEX));
wcex.cbSize = sizeof(WNDCLASSEX);
#endif
wcex.lpfnWndProc = TimerWindowWndProc;
wcex.hInstance = WebCore::instanceHandle();
wcex.lpszClassName = kTimerWindowClassName;
#if OS(WINCE)
RegisterClass(&wcex);
#else
RegisterClassEx(&wcex);
#endif
timerWindowHandle = CreateWindow(kTimerWindowClassName, 0, 0,
CW_USEDEFAULT, 0, CW_USEDEFAULT, 0, HWND_MESSAGE, 0, WebCore::instanceHandle(), 0);
#if !OS(WINCE)
timerFiredMessage = RegisterWindowMessage(L"com.apple.WebKit.TimerFired");
#endif
}
void setSharedTimerFiredFunction(void (*f)())
{
sharedTimerFiredFunction = f;
}
#if !OS(WINCE)
static void NTAPI queueTimerProc(PVOID, BOOLEAN)
{
if (InterlockedIncrement(&pendingTimers) == 1)
PostMessage(timerWindowHandle, timerFiredMessage, 0, 0);
}
#endif
void setSharedTimerFireInterval(double interval)
{
ASSERT(sharedTimerFiredFunction);
unsigned intervalInMS;
interval *= 1000;
if (interval > USER_TIMER_MAXIMUM)
intervalInMS = USER_TIMER_MAXIMUM;
else
intervalInMS = static_cast<unsigned>(interval);
initializeOffScreenTimerWindow();
bool timerSet = false;
#if !OS(WINCE)
if (Settings::shouldUseHighResolutionTimers()) {
if (interval < highResolutionThresholdMsec) {
if (!highResTimerActive) {
highResTimerActive = true;
timeBeginPeriod(timerResolution);
}
SetTimer(timerWindowHandle, endHighResTimerID, stopHighResTimerInMsec, 0);
}
DWORD queueStatus = LOWORD(GetQueueStatus(QS_PAINT | QS_MOUSEBUTTON | QS_KEY | QS_RAWINPUT));
// Win32 has a tri-level queue with application messages > user input > WM_PAINT/WM_TIMER.
// If the queue doesn't contains input events, we use a higher priorty timer event posting mechanism.
if (!(queueStatus & (QS_MOUSEBUTTON | QS_KEY | QS_RAWINPUT))) {
if (intervalInMS < USER_TIMER_MINIMUM && !processingCustomTimerMessage && !(queueStatus & QS_PAINT)) {
// Call PostMessage immediately if the timer is already expired, unless a paint is pending.
// (we prioritize paints over timers)
if (InterlockedIncrement(&pendingTimers) == 1)
PostMessage(timerWindowHandle, timerFiredMessage, 0, 0);
timerSet = true;
} else {
// Otherwise, delay the PostMessage via a CreateTimerQueueTimer
if (!timerQueue)
timerQueue = CreateTimerQueue();
if (timer)
DeleteTimerQueueTimer(timerQueue, timer, 0);
timerSet = CreateTimerQueueTimer(&timer, timerQueue, queueTimerProc, 0, intervalInMS, 0, WT_EXECUTEINTIMERTHREAD | WT_EXECUTEONLYONCE);
}
}
}
#endif // !OS(WINCE)
if (timerSet) {
if (timerID) {
KillTimer(timerWindowHandle, timerID);
timerID = 0;
}
} else {
timerID = SetTimer(timerWindowHandle, sharedTimerID, intervalInMS, 0);
timer = 0;
}
}
void stopSharedTimer()
{
#if !OS(WINCE)
if (timerQueue && timer) {
DeleteTimerQueueTimer(timerQueue, timer, 0);
timer = 0;
}
#endif
if (timerID) {
KillTimer(timerWindowHandle, timerID);
timerID = 0;
}
}
}
| bsd-3-clause |
pataquets/phantomjs | src/qt/qtwebkit/Source/JavaScriptCore/runtime/JSActivation.cpp | 115 | 10438 | /*
* Copyright (C) 2008, 2009 Apple 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:
*
* 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 Apple Computer, Inc. ("Apple") 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 APPLE AND ITS 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 APPLE OR ITS 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.
*/
#include "config.h"
#include "JSActivation.h"
#include "Arguments.h"
#include "Interpreter.h"
#include "JSFunction.h"
#include "Operations.h"
using namespace std;
namespace JSC {
const ClassInfo JSActivation::s_info = { "JSActivation", &Base::s_info, 0, 0, CREATE_METHOD_TABLE(JSActivation) };
void JSActivation::visitChildren(JSCell* cell, SlotVisitor& visitor)
{
JSActivation* thisObject = jsCast<JSActivation*>(cell);
ASSERT_GC_OBJECT_INHERITS(thisObject, &s_info);
COMPILE_ASSERT(StructureFlags & OverridesVisitChildren, OverridesVisitChildrenWithoutSettingFlag);
ASSERT(thisObject->structure()->typeInfo().overridesVisitChildren());
Base::visitChildren(thisObject, visitor);
// No need to mark our registers if they're still in the JSStack.
if (!thisObject->isTornOff())
return;
for (int i = 0; i < thisObject->symbolTable()->captureCount(); ++i)
visitor.append(&thisObject->storage()[i]);
}
inline bool JSActivation::symbolTableGet(PropertyName propertyName, PropertySlot& slot)
{
SymbolTableEntry entry = symbolTable()->inlineGet(propertyName.publicName());
if (entry.isNull())
return false;
// Defend against the inspector asking for a var after it has been optimized out.
if (isTornOff() && !isValid(entry))
return false;
slot.setValue(registerAt(entry.getIndex()).get());
return true;
}
inline bool JSActivation::symbolTableGet(PropertyName propertyName, PropertyDescriptor& descriptor)
{
SymbolTableEntry entry = symbolTable()->inlineGet(propertyName.publicName());
if (entry.isNull())
return false;
// Defend against the inspector asking for a var after it has been optimized out.
if (isTornOff() && !isValid(entry))
return false;
descriptor.setDescriptor(registerAt(entry.getIndex()).get(), entry.getAttributes());
return true;
}
inline bool JSActivation::symbolTablePut(ExecState* exec, PropertyName propertyName, JSValue value, bool shouldThrow)
{
VM& vm = exec->vm();
ASSERT(!Heap::heap(value) || Heap::heap(value) == Heap::heap(this));
SymbolTableEntry entry = symbolTable()->inlineGet(propertyName.publicName());
if (entry.isNull())
return false;
if (entry.isReadOnly()) {
if (shouldThrow)
throwTypeError(exec, StrictModeReadonlyPropertyWriteError);
return true;
}
// Defend against the inspector asking for a var after it has been optimized out.
if (isTornOff() && !isValid(entry))
return false;
registerAt(entry.getIndex()).set(vm, this, value);
return true;
}
void JSActivation::getOwnNonIndexPropertyNames(JSObject* object, ExecState* exec, PropertyNameArray& propertyNames, EnumerationMode mode)
{
JSActivation* thisObject = jsCast<JSActivation*>(object);
if (mode == IncludeDontEnumProperties && !thisObject->isTornOff())
propertyNames.add(exec->propertyNames().arguments);
SymbolTable::const_iterator end = thisObject->symbolTable()->end();
for (SymbolTable::const_iterator it = thisObject->symbolTable()->begin(); it != end; ++it) {
if (it->value.getAttributes() & DontEnum && mode != IncludeDontEnumProperties)
continue;
if (!thisObject->isValid(it->value))
continue;
propertyNames.add(Identifier(exec, it->key.get()));
}
// Skip the JSVariableObject implementation of getOwnNonIndexPropertyNames
JSObject::getOwnNonIndexPropertyNames(thisObject, exec, propertyNames, mode);
}
inline bool JSActivation::symbolTablePutWithAttributes(VM& vm, PropertyName propertyName, JSValue value, unsigned attributes)
{
ASSERT(!Heap::heap(value) || Heap::heap(value) == Heap::heap(this));
SymbolTable::iterator iter = symbolTable()->find(propertyName.publicName());
if (iter == symbolTable()->end())
return false;
SymbolTableEntry& entry = iter->value;
ASSERT(!entry.isNull());
if (!isValid(entry))
return false;
entry.setAttributes(attributes);
registerAt(entry.getIndex()).set(vm, this, value);
return true;
}
bool JSActivation::getOwnPropertySlot(JSCell* cell, ExecState* exec, PropertyName propertyName, PropertySlot& slot)
{
JSActivation* thisObject = jsCast<JSActivation*>(cell);
if (propertyName == exec->propertyNames().arguments) {
// Defend against the inspector asking for the arguments object after it has been optimized out.
if (!thisObject->isTornOff()) {
slot.setCustom(thisObject, thisObject->getArgumentsGetter());
return true;
}
}
if (thisObject->symbolTableGet(propertyName, slot))
return true;
if (JSValue value = thisObject->getDirect(exec->vm(), propertyName)) {
slot.setValue(value);
return true;
}
// We don't call through to JSObject because there's no way to give an
// activation object getter properties or a prototype.
ASSERT(!thisObject->hasGetterSetterProperties());
ASSERT(thisObject->prototype().isNull());
return false;
}
bool JSActivation::getOwnPropertyDescriptor(JSObject* object, ExecState* exec, PropertyName propertyName, PropertyDescriptor& descriptor)
{
JSActivation* thisObject = jsCast<JSActivation*>(object);
if (propertyName == exec->propertyNames().arguments) {
// Defend against the inspector asking for the arguments object after it has been optimized out.
if (!thisObject->isTornOff()) {
PropertySlot slot;
JSActivation::getOwnPropertySlot(thisObject, exec, propertyName, slot);
descriptor.setDescriptor(slot.getValue(exec, propertyName), DontEnum);
return true;
}
}
if (thisObject->symbolTableGet(propertyName, descriptor))
return true;
return Base::getOwnPropertyDescriptor(object, exec, propertyName, descriptor);
}
void JSActivation::put(JSCell* cell, ExecState* exec, PropertyName propertyName, JSValue value, PutPropertySlot& slot)
{
JSActivation* thisObject = jsCast<JSActivation*>(cell);
ASSERT(!Heap::heap(value) || Heap::heap(value) == Heap::heap(thisObject));
if (thisObject->symbolTablePut(exec, propertyName, value, slot.isStrictMode()))
return;
// We don't call through to JSObject because __proto__ and getter/setter
// properties are non-standard extensions that other implementations do not
// expose in the activation object.
ASSERT(!thisObject->hasGetterSetterProperties());
thisObject->putOwnDataProperty(exec->vm(), propertyName, value, slot);
}
// FIXME: Make this function honor ReadOnly (const) and DontEnum
void JSActivation::putDirectVirtual(JSObject* object, ExecState* exec, PropertyName propertyName, JSValue value, unsigned attributes)
{
JSActivation* thisObject = jsCast<JSActivation*>(object);
ASSERT(!Heap::heap(value) || Heap::heap(value) == Heap::heap(thisObject));
if (thisObject->symbolTablePutWithAttributes(exec->vm(), propertyName, value, attributes))
return;
// We don't call through to JSObject because __proto__ and getter/setter
// properties are non-standard extensions that other implementations do not
// expose in the activation object.
ASSERT(!thisObject->hasGetterSetterProperties());
JSObject::putDirectVirtual(thisObject, exec, propertyName, value, attributes);
}
bool JSActivation::deleteProperty(JSCell* cell, ExecState* exec, PropertyName propertyName)
{
if (propertyName == exec->propertyNames().arguments)
return false;
return Base::deleteProperty(cell, exec, propertyName);
}
JSObject* JSActivation::toThisObject(JSCell*, ExecState* exec)
{
return exec->globalThisValue();
}
JSValue JSActivation::argumentsGetter(ExecState*, JSValue slotBase, PropertyName)
{
JSActivation* activation = jsCast<JSActivation*>(slotBase);
if (activation->isTornOff())
return jsUndefined();
CallFrame* callFrame = CallFrame::create(reinterpret_cast<Register*>(activation->m_registers));
int argumentsRegister = callFrame->codeBlock()->argumentsRegister();
if (JSValue arguments = callFrame->uncheckedR(argumentsRegister).jsValue())
return arguments;
int realArgumentsRegister = unmodifiedArgumentsRegister(argumentsRegister);
JSValue arguments = JSValue(Arguments::create(callFrame->vm(), callFrame));
callFrame->uncheckedR(argumentsRegister) = arguments;
callFrame->uncheckedR(realArgumentsRegister) = arguments;
ASSERT(callFrame->uncheckedR(realArgumentsRegister).jsValue().inherits(&Arguments::s_info));
return callFrame->uncheckedR(realArgumentsRegister).jsValue();
}
// These two functions serve the purpose of isolating the common case from a
// PIC branch.
PropertySlot::GetValueFunc JSActivation::getArgumentsGetter()
{
return argumentsGetter;
}
} // namespace JSC
| bsd-3-clause |
js0701/chromium-crosswalk | third_party/libjpeg/jdatadst.c | 1395 | 5119 | /*
* jdatadst.c
*
* Copyright (C) 1994-1996, Thomas G. Lane.
* This file is part of the Independent JPEG Group's software.
* For conditions of distribution and use, see the accompanying README file.
*
* This file contains compression data destination routines for the case of
* emitting JPEG data to a file (or any stdio stream). While these routines
* are sufficient for most applications, some will want to use a different
* destination manager.
* IMPORTANT: we assume that fwrite() will correctly transcribe an array of
* JOCTETs into 8-bit-wide elements on external storage. If char is wider
* than 8 bits on your machine, you may need to do some tweaking.
*/
/* this is not a core library module, so it doesn't define JPEG_INTERNALS */
#include "jinclude.h"
#include "jpeglib.h"
#include "jerror.h"
/* Expanded data destination object for stdio output */
typedef struct {
struct jpeg_destination_mgr pub; /* public fields */
FILE * outfile; /* target stream */
JOCTET * buffer; /* start of buffer */
} my_destination_mgr;
typedef my_destination_mgr * my_dest_ptr;
#define OUTPUT_BUF_SIZE 4096 /* choose an efficiently fwrite'able size */
/*
* Initialize destination --- called by jpeg_start_compress
* before any data is actually written.
*/
METHODDEF(void)
init_destination (j_compress_ptr cinfo)
{
my_dest_ptr dest = (my_dest_ptr) cinfo->dest;
/* Allocate the output buffer --- it will be released when done with image */
dest->buffer = (JOCTET *)
(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_IMAGE,
OUTPUT_BUF_SIZE * SIZEOF(JOCTET));
dest->pub.next_output_byte = dest->buffer;
dest->pub.free_in_buffer = OUTPUT_BUF_SIZE;
}
/*
* Empty the output buffer --- called whenever buffer fills up.
*
* In typical applications, this should write the entire output buffer
* (ignoring the current state of next_output_byte & free_in_buffer),
* reset the pointer & count to the start of the buffer, and return TRUE
* indicating that the buffer has been dumped.
*
* In applications that need to be able to suspend compression due to output
* overrun, a FALSE return indicates that the buffer cannot be emptied now.
* In this situation, the compressor will return to its caller (possibly with
* an indication that it has not accepted all the supplied scanlines). The
* application should resume compression after it has made more room in the
* output buffer. Note that there are substantial restrictions on the use of
* suspension --- see the documentation.
*
* When suspending, the compressor will back up to a convenient restart point
* (typically the start of the current MCU). next_output_byte & free_in_buffer
* indicate where the restart point will be if the current call returns FALSE.
* Data beyond this point will be regenerated after resumption, so do not
* write it out when emptying the buffer externally.
*/
METHODDEF(boolean)
empty_output_buffer (j_compress_ptr cinfo)
{
my_dest_ptr dest = (my_dest_ptr) cinfo->dest;
if (JFWRITE(dest->outfile, dest->buffer, OUTPUT_BUF_SIZE) !=
(size_t) OUTPUT_BUF_SIZE)
ERREXIT(cinfo, JERR_FILE_WRITE);
dest->pub.next_output_byte = dest->buffer;
dest->pub.free_in_buffer = OUTPUT_BUF_SIZE;
return TRUE;
}
/*
* Terminate destination --- called by jpeg_finish_compress
* after all data has been written. Usually needs to flush buffer.
*
* NB: *not* called by jpeg_abort or jpeg_destroy; surrounding
* application must deal with any cleanup that should happen even
* for error exit.
*/
METHODDEF(void)
term_destination (j_compress_ptr cinfo)
{
my_dest_ptr dest = (my_dest_ptr) cinfo->dest;
size_t datacount = OUTPUT_BUF_SIZE - dest->pub.free_in_buffer;
/* Write any data remaining in the buffer */
if (datacount > 0) {
if (JFWRITE(dest->outfile, dest->buffer, datacount) != datacount)
ERREXIT(cinfo, JERR_FILE_WRITE);
}
fflush(dest->outfile);
/* Make sure we wrote the output file OK */
if (ferror(dest->outfile))
ERREXIT(cinfo, JERR_FILE_WRITE);
}
/*
* Prepare for output to a stdio stream.
* The caller must have already opened the stream, and is responsible
* for closing it after finishing compression.
*/
GLOBAL(void)
jpeg_stdio_dest (j_compress_ptr cinfo, FILE * outfile)
{
my_dest_ptr dest;
/* The destination object is made permanent so that multiple JPEG images
* can be written to the same file without re-executing jpeg_stdio_dest.
* This makes it dangerous to use this manager and a different destination
* manager serially with the same JPEG object, because their private object
* sizes may be different. Caveat programmer.
*/
if (cinfo->dest == NULL) { /* first time for this JPEG object? */
cinfo->dest = (struct jpeg_destination_mgr *)
(*cinfo->mem->alloc_small) ((j_common_ptr) cinfo, JPOOL_PERMANENT,
SIZEOF(my_destination_mgr));
}
dest = (my_dest_ptr) cinfo->dest;
dest->pub.init_destination = init_destination;
dest->pub.empty_output_buffer = empty_output_buffer;
dest->pub.term_destination = term_destination;
dest->outfile = outfile;
}
| bsd-3-clause |
grevutiu-gabriel/phantomjs | src/qt/qtwebkit/Source/WebCore/platform/network/cf/ResourceRequestCFNet.cpp | 116 | 16188 | /*
* Copyright (C) 2006, 2007, 2008 Apple 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:
* 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.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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.
*/
#include "config.h"
#include "ResourceRequestCFNet.h"
#include "ResourceRequest.h"
#if ENABLE(PUBLIC_SUFFIX_LIST)
#include "PublicSuffix.h"
#endif
#if USE(CFNETWORK)
#include "FormDataStreamCFNet.h"
#include <CFNetwork/CFURLRequestPriv.h>
#include <wtf/text/CString.h>
#endif
#if PLATFORM(MAC)
#include "ResourceLoadPriority.h"
#include "WebCoreSystemInterface.h"
#include <dlfcn.h>
#endif
#if PLATFORM(WIN)
#include <WebKitSystemInterface/WebKitSystemInterface.h>
#endif
namespace WebCore {
bool ResourceRequest::s_httpPipeliningEnabled = false;
#if USE(CFNETWORK)
typedef void (*CFURLRequestSetContentDispositionEncodingFallbackArrayFunction)(CFMutableURLRequestRef, CFArrayRef);
typedef CFArrayRef (*CFURLRequestCopyContentDispositionEncodingFallbackArrayFunction)(CFURLRequestRef);
#if PLATFORM(WIN)
static HMODULE findCFNetworkModule()
{
#ifndef DEBUG_ALL
return GetModuleHandleA("CFNetwork");
#else
return GetModuleHandleA("CFNetwork_debug");
#endif
}
static CFURLRequestSetContentDispositionEncodingFallbackArrayFunction findCFURLRequestSetContentDispositionEncodingFallbackArrayFunction()
{
return reinterpret_cast<CFURLRequestSetContentDispositionEncodingFallbackArrayFunction>(GetProcAddress(findCFNetworkModule(), "_CFURLRequestSetContentDispositionEncodingFallbackArray"));
}
static CFURLRequestCopyContentDispositionEncodingFallbackArrayFunction findCFURLRequestCopyContentDispositionEncodingFallbackArrayFunction()
{
return reinterpret_cast<CFURLRequestCopyContentDispositionEncodingFallbackArrayFunction>(GetProcAddress(findCFNetworkModule(), "_CFURLRequestCopyContentDispositionEncodingFallbackArray"));
}
#elif PLATFORM(MAC)
static CFURLRequestSetContentDispositionEncodingFallbackArrayFunction findCFURLRequestSetContentDispositionEncodingFallbackArrayFunction()
{
return reinterpret_cast<CFURLRequestSetContentDispositionEncodingFallbackArrayFunction>(dlsym(RTLD_DEFAULT, "_CFURLRequestSetContentDispositionEncodingFallbackArray"));
}
static CFURLRequestCopyContentDispositionEncodingFallbackArrayFunction findCFURLRequestCopyContentDispositionEncodingFallbackArrayFunction()
{
return reinterpret_cast<CFURLRequestCopyContentDispositionEncodingFallbackArrayFunction>(dlsym(RTLD_DEFAULT, "_CFURLRequestCopyContentDispositionEncodingFallbackArray"));
}
#endif
static void setContentDispositionEncodingFallbackArray(CFMutableURLRequestRef request, CFArrayRef fallbackArray)
{
static CFURLRequestSetContentDispositionEncodingFallbackArrayFunction function = findCFURLRequestSetContentDispositionEncodingFallbackArrayFunction();
if (function)
function(request, fallbackArray);
}
static CFArrayRef copyContentDispositionEncodingFallbackArray(CFURLRequestRef request)
{
static CFURLRequestCopyContentDispositionEncodingFallbackArrayFunction function = findCFURLRequestCopyContentDispositionEncodingFallbackArrayFunction();
if (!function)
return 0;
return function(request);
}
CFURLRequestRef ResourceRequest::cfURLRequest(HTTPBodyUpdatePolicy bodyPolicy) const
{
updatePlatformRequest(bodyPolicy);
return m_cfRequest.get();
}
static inline void setHeaderFields(CFMutableURLRequestRef request, const HTTPHeaderMap& requestHeaders)
{
// Remove existing headers first, as some of them may no longer be present in the map.
RetainPtr<CFDictionaryRef> oldHeaderFields = adoptCF(CFURLRequestCopyAllHTTPHeaderFields(request));
CFIndex oldHeaderFieldCount = CFDictionaryGetCount(oldHeaderFields.get());
if (oldHeaderFieldCount) {
Vector<CFStringRef> oldHeaderFieldNames(oldHeaderFieldCount);
CFDictionaryGetKeysAndValues(oldHeaderFields.get(), reinterpret_cast<const void**>(&oldHeaderFieldNames[0]), 0);
for (CFIndex i = 0; i < oldHeaderFieldCount; ++i)
CFURLRequestSetHTTPHeaderFieldValue(request, oldHeaderFieldNames[i], 0);
}
for (HTTPHeaderMap::const_iterator it = requestHeaders.begin(), end = requestHeaders.end(); it != end; ++it)
CFURLRequestSetHTTPHeaderFieldValue(request, it->key.string().createCFString().get(), it->value.createCFString().get());
}
void ResourceRequest::doUpdatePlatformRequest()
{
CFMutableURLRequestRef cfRequest;
RetainPtr<CFURLRef> url = ResourceRequest::url().createCFURL();
RetainPtr<CFURLRef> firstPartyForCookies = ResourceRequest::firstPartyForCookies().createCFURL();
if (m_cfRequest) {
cfRequest = CFURLRequestCreateMutableCopy(0, m_cfRequest.get());
CFURLRequestSetURL(cfRequest, url.get());
CFURLRequestSetMainDocumentURL(cfRequest, firstPartyForCookies.get());
CFURLRequestSetCachePolicy(cfRequest, (CFURLRequestCachePolicy)cachePolicy());
CFURLRequestSetTimeoutInterval(cfRequest, timeoutInterval());
} else
cfRequest = CFURLRequestCreateMutable(0, url.get(), (CFURLRequestCachePolicy)cachePolicy(), timeoutInterval(), firstPartyForCookies.get());
CFURLRequestSetHTTPRequestMethod(cfRequest, httpMethod().createCFString().get());
if (httpPipeliningEnabled())
wkSetHTTPPipeliningPriority(cfRequest, toHTTPPipeliningPriority(m_priority));
#if !PLATFORM(WIN)
wkCFURLRequestAllowAllPostCaching(cfRequest);
#endif
setHeaderFields(cfRequest, httpHeaderFields());
CFURLRequestSetShouldHandleHTTPCookies(cfRequest, allowCookies());
unsigned fallbackCount = m_responseContentDispositionEncodingFallbackArray.size();
RetainPtr<CFMutableArrayRef> encodingFallbacks = adoptCF(CFArrayCreateMutable(kCFAllocatorDefault, fallbackCount, 0));
for (unsigned i = 0; i != fallbackCount; ++i) {
RetainPtr<CFStringRef> encodingName = m_responseContentDispositionEncodingFallbackArray[i].createCFString();
CFStringEncoding encoding = CFStringConvertIANACharSetNameToEncoding(encodingName.get());
if (encoding != kCFStringEncodingInvalidId)
CFArrayAppendValue(encodingFallbacks.get(), reinterpret_cast<const void*>(encoding));
}
setContentDispositionEncodingFallbackArray(cfRequest, encodingFallbacks.get());
if (m_cfRequest) {
RetainPtr<CFHTTPCookieStorageRef> cookieStorage = adoptCF(CFURLRequestCopyHTTPCookieStorage(m_cfRequest.get()));
if (cookieStorage)
CFURLRequestSetHTTPCookieStorage(cfRequest, cookieStorage.get());
CFURLRequestSetHTTPCookieStorageAcceptPolicy(cfRequest, CFURLRequestGetHTTPCookieStorageAcceptPolicy(m_cfRequest.get()));
CFURLRequestSetSSLProperties(cfRequest, CFURLRequestGetSSLProperties(m_cfRequest.get()));
}
#if ENABLE(CACHE_PARTITIONING)
String partition = cachePartition();
if (!partition.isNull() && !partition.isEmpty()) {
CString utf8String = partition.utf8();
RetainPtr<CFStringRef> partitionValue = adoptCF(CFStringCreateWithBytes(0, reinterpret_cast<const UInt8*>(utf8String.data()), utf8String.length(), kCFStringEncodingUTF8, false));
_CFURLRequestSetProtocolProperty(cfRequest, wkCachePartitionKey(), partitionValue.get());
}
#endif
m_cfRequest = adoptCF(cfRequest);
#if PLATFORM(MAC)
updateNSURLRequest();
#endif
}
void ResourceRequest::doUpdatePlatformHTTPBody()
{
CFMutableURLRequestRef cfRequest;
RetainPtr<CFURLRef> url = ResourceRequest::url().createCFURL();
RetainPtr<CFURLRef> firstPartyForCookies = ResourceRequest::firstPartyForCookies().createCFURL();
if (m_cfRequest) {
cfRequest = CFURLRequestCreateMutableCopy(0, m_cfRequest.get());
CFURLRequestSetURL(cfRequest, url.get());
CFURLRequestSetMainDocumentURL(cfRequest, firstPartyForCookies.get());
CFURLRequestSetCachePolicy(cfRequest, (CFURLRequestCachePolicy)cachePolicy());
CFURLRequestSetTimeoutInterval(cfRequest, timeoutInterval());
} else
cfRequest = CFURLRequestCreateMutable(0, url.get(), (CFURLRequestCachePolicy)cachePolicy(), timeoutInterval(), firstPartyForCookies.get());
RefPtr<FormData> formData = httpBody();
if (formData && !formData->isEmpty())
WebCore::setHTTPBody(cfRequest, formData);
if (RetainPtr<CFReadStreamRef> bodyStream = adoptCF(CFURLRequestCopyHTTPRequestBodyStream(cfRequest))) {
// For streams, provide a Content-Length to avoid using chunked encoding, and to get accurate total length in callbacks.
RetainPtr<CFStringRef> lengthString = adoptCF(static_cast<CFStringRef>(CFReadStreamCopyProperty(bodyStream.get(), formDataStreamLengthPropertyName())));
if (lengthString) {
CFURLRequestSetHTTPHeaderFieldValue(cfRequest, CFSTR("Content-Length"), lengthString.get());
// Since resource request is already marked updated, we need to keep it up to date too.
ASSERT(m_resourceRequestUpdated);
m_httpHeaderFields.set("Content-Length", lengthString.get());
}
}
m_cfRequest = adoptCF(cfRequest);
#if PLATFORM(MAC)
updateNSURLRequest();
#endif
}
void ResourceRequest::doUpdateResourceRequest()
{
if (!m_cfRequest) {
*this = ResourceRequest();
return;
}
m_url = CFURLRequestGetURL(m_cfRequest.get());
m_cachePolicy = (ResourceRequestCachePolicy)CFURLRequestGetCachePolicy(m_cfRequest.get());
m_timeoutInterval = CFURLRequestGetTimeoutInterval(m_cfRequest.get());
m_firstPartyForCookies = CFURLRequestGetMainDocumentURL(m_cfRequest.get());
if (CFStringRef method = CFURLRequestCopyHTTPRequestMethod(m_cfRequest.get())) {
m_httpMethod = method;
CFRelease(method);
}
m_allowCookies = CFURLRequestShouldHandleHTTPCookies(m_cfRequest.get());
if (httpPipeliningEnabled())
m_priority = toResourceLoadPriority(wkGetHTTPPipeliningPriority(m_cfRequest.get()));
m_httpHeaderFields.clear();
if (CFDictionaryRef headers = CFURLRequestCopyAllHTTPHeaderFields(m_cfRequest.get())) {
CFIndex headerCount = CFDictionaryGetCount(headers);
Vector<const void*, 128> keys(headerCount);
Vector<const void*, 128> values(headerCount);
CFDictionaryGetKeysAndValues(headers, keys.data(), values.data());
for (int i = 0; i < headerCount; ++i)
m_httpHeaderFields.set((CFStringRef)keys[i], (CFStringRef)values[i]);
CFRelease(headers);
}
m_responseContentDispositionEncodingFallbackArray.clear();
RetainPtr<CFArrayRef> encodingFallbacks = adoptCF(copyContentDispositionEncodingFallbackArray(m_cfRequest.get()));
if (encodingFallbacks) {
CFIndex count = CFArrayGetCount(encodingFallbacks.get());
for (CFIndex i = 0; i < count; ++i) {
CFStringEncoding encoding = reinterpret_cast<CFIndex>(CFArrayGetValueAtIndex(encodingFallbacks.get(), i));
if (encoding != kCFStringEncodingInvalidId)
m_responseContentDispositionEncodingFallbackArray.append(CFStringConvertEncodingToIANACharSetName(encoding));
}
}
#if ENABLE(CACHE_PARTITIONING)
RetainPtr<CFStringRef> cachePartition = adoptCF(static_cast<CFStringRef>(_CFURLRequestCopyProtocolPropertyForKey(m_cfRequest.get(), wkCachePartitionKey())));
if (cachePartition)
m_cachePartition = cachePartition.get();
#endif
}
void ResourceRequest::doUpdateResourceHTTPBody()
{
if (!m_cfRequest) {
m_httpBody = 0;
return;
}
if (RetainPtr<CFDataRef> bodyData = adoptCF(CFURLRequestCopyHTTPRequestBody(m_cfRequest.get())))
m_httpBody = FormData::create(CFDataGetBytePtr(bodyData.get()), CFDataGetLength(bodyData.get()));
else if (RetainPtr<CFReadStreamRef> bodyStream = adoptCF(CFURLRequestCopyHTTPRequestBodyStream(m_cfRequest.get()))) {
FormData* formData = httpBodyFromStream(bodyStream.get());
// There is no FormData object if a client provided a custom data stream.
// We shouldn't be looking at http body after client callbacks.
ASSERT(formData);
if (formData)
m_httpBody = formData;
}
}
void ResourceRequest::setStorageSession(CFURLStorageSessionRef storageSession)
{
updatePlatformRequest();
CFMutableURLRequestRef cfRequest = CFURLRequestCreateMutableCopy(0, m_cfRequest.get());
wkSetRequestStorageSession(storageSession, cfRequest);
m_cfRequest = adoptCF(cfRequest);
#if PLATFORM(MAC)
updateNSURLRequest();
#endif
}
#if PLATFORM(MAC)
void ResourceRequest::applyWebArchiveHackForMail()
{
// Hack because Mail checks for this property to detect data / archive loads
_CFURLRequestSetProtocolProperty(cfURLRequest(DoNotUpdateHTTPBody), CFSTR("WebDataRequest"), CFSTR(""));
}
#endif
#endif // USE(CFNETWORK)
bool ResourceRequest::httpPipeliningEnabled()
{
return s_httpPipeliningEnabled;
}
void ResourceRequest::setHTTPPipeliningEnabled(bool flag)
{
s_httpPipeliningEnabled = flag;
}
#if ENABLE(CACHE_PARTITIONING)
String ResourceRequest::partitionName(const String& domain)
{
if (domain.isNull())
return emptyString();
#if ENABLE(PUBLIC_SUFFIX_LIST)
String highLevel = topPrivatelyControlledDomain(domain);
if (highLevel.isNull())
return emptyString();
return highLevel;
#else
return domain;
#endif
}
#endif
PassOwnPtr<CrossThreadResourceRequestData> ResourceRequest::doPlatformCopyData(PassOwnPtr<CrossThreadResourceRequestData> data) const
{
#if ENABLE(CACHE_PARTITIONING)
data->m_cachePartition = m_cachePartition;
#endif
return data;
}
void ResourceRequest::doPlatformAdopt(PassOwnPtr<CrossThreadResourceRequestData> data)
{
#if ENABLE(CACHE_PARTITIONING)
m_cachePartition = data->m_cachePartition;
#else
UNUSED_PARAM(data);
#endif
}
unsigned initializeMaximumHTTPConnectionCountPerHost()
{
static const unsigned preferredConnectionCount = 6;
// Always set the connection count per host, even when pipelining.
unsigned maximumHTTPConnectionCountPerHost = wkInitializeMaximumHTTPConnectionCountPerHost(preferredConnectionCount);
static const unsigned unlimitedConnectionCount = 10000;
Boolean keyExistsAndHasValidFormat = false;
Boolean prefValue = CFPreferencesGetAppBooleanValue(CFSTR("WebKitEnableHTTPPipelining"), kCFPreferencesCurrentApplication, &keyExistsAndHasValidFormat);
if (keyExistsAndHasValidFormat)
ResourceRequest::setHTTPPipeliningEnabled(prefValue);
if (ResourceRequest::httpPipeliningEnabled()) {
wkSetHTTPPipeliningMaximumPriority(toHTTPPipeliningPriority(ResourceLoadPriorityHighest));
#if !PLATFORM(WIN)
// FIXME: <rdar://problem/9375609> Implement minimum fast lane priority setting on Windows
wkSetHTTPPipeliningMinimumFastLanePriority(toHTTPPipeliningPriority(ResourceLoadPriorityMedium));
#endif
// When pipelining do not rate-limit requests sent from WebCore since CFNetwork handles that.
return unlimitedConnectionCount;
}
return maximumHTTPConnectionCountPerHost;
}
} // namespace WebCore
| bsd-3-clause |
youprofit/phantomjs | src/qt/qtwebkit/Source/WebCore/bindings/js/JSIDBDatabaseCustom.cpp | 117 | 2987 | /*
* Copyright (C) 2012 Michael Pruett <michael@68k.org>
*
* 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.
*
* 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.
*/
#include "config.h"
#if ENABLE(INDEXED_DATABASE)
#include "JSIDBDatabase.h"
#include "IDBBindingUtilities.h"
#include "IDBDatabase.h"
#include "IDBKeyPath.h"
#include "IDBObjectStore.h"
#include "JSIDBObjectStore.h"
#include <runtime/Error.h>
#include <runtime/JSString.h>
using namespace JSC;
namespace WebCore {
JSValue JSIDBDatabase::createObjectStore(ExecState* exec)
{
if (exec->argumentCount() < 1)
return throwError(exec, createNotEnoughArgumentsError(exec));
String name = exec->argument(0).toString(exec)->value(exec);
if (exec->hadException())
return jsUndefined();
JSValue optionsValue = exec->argument(1);
if (!optionsValue.isUndefinedOrNull() && !optionsValue.isObject())
return throwTypeError(exec, "Not an object.");
IDBKeyPath keyPath;
bool autoIncrement = false;
if (!optionsValue.isUndefinedOrNull()) {
JSValue keyPathValue = optionsValue.get(exec, Identifier(exec, "keyPath"));
if (exec->hadException())
return jsUndefined();
if (!keyPathValue.isUndefinedOrNull()) {
keyPath = idbKeyPathFromValue(exec, keyPathValue);
if (exec->hadException())
return jsUndefined();
}
autoIncrement = optionsValue.get(exec, Identifier(exec, "autoIncrement")).toBoolean(exec);
if (exec->hadException())
return jsUndefined();
}
ExceptionCode ec = 0;
JSValue result = toJS(exec, globalObject(), impl()->createObjectStore(name, keyPath, autoIncrement, ec).get());
setDOMException(exec, ec);
return result;
}
}
#endif
| bsd-3-clause |
Medium/phantomjs-1 | src/qt/qtwebkit/Source/WebKit2/UIProcess/efl/WebUIPopupMenuClient.cpp | 117 | 2587 | /*
* Copyright (C) 2013 Samsung Electronics. 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.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTAwBILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS 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.
*/
#include "config.h"
#include "WebUIPopupMenuClient.h"
#include "ImmutableArray.h"
#include "WKAPICast.h"
#include "WebPopupItemEfl.h"
#include "WebPopupMenuListenerEfl.h"
using namespace WebCore;
using namespace WebKit;
void WebUIPopupMenuClient::showPopupMenu(WebPageProxy* pageProxy, WebPopupMenuProxy* popupMenuProxy, const IntRect& rect, TextDirection textDirection, double pageScaleFactor, const Vector<WebPopupItem>& items, int32_t selectedIndex)
{
if (!m_client.showPopupMenu)
return;
Vector<RefPtr<APIObject> > webPopupItems;
size_t size = items.size();
for (size_t i = 0; i < size; ++i)
webPopupItems.append(WebPopupItemEfl::create(items[i]));
RefPtr<ImmutableArray> ItemsArray;
if (!webPopupItems.isEmpty())
ItemsArray = ImmutableArray::adopt(webPopupItems);
m_client.showPopupMenu(toAPI(pageProxy), toAPI(static_cast<WebPopupMenuListenerEfl*>(popupMenuProxy)), toAPI(rect), toAPI(textDirection), pageScaleFactor, toAPI(ItemsArray.get()), selectedIndex, m_client.clientInfo);
}
void WebUIPopupMenuClient::hidePopupMenu(WebPageProxy* pageProxy)
{
if (m_client.hidePopupMenu)
m_client.hidePopupMenu(toAPI(pageProxy), m_client.clientInfo);
}
| bsd-3-clause |
Lkhagvadelger/phantomjs | src/qt/qtwebkit/Source/WebCore/dom/DocumentType.cpp | 119 | 2501 | /*
* Copyright (C) 1999 Lars Knoll (knoll@kde.org)
* (C) 1999 Antti Koivisto (koivisto@kde.org)
* (C) 2001 Dirk Mueller (mueller@kde.org)
* Copyright (C) 2004, 2005, 2006, 2008, 2009 Apple Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "config.h"
#include "DocumentType.h"
#include "Document.h"
#include "NamedNodeMap.h"
namespace WebCore {
DocumentType::DocumentType(Document* document, const String& name, const String& publicId, const String& systemId)
: Node(document, CreateOther)
, m_name(name)
, m_publicId(publicId)
, m_systemId(systemId)
{
}
KURL DocumentType::baseURI() const
{
return KURL();
}
String DocumentType::nodeName() const
{
return name();
}
Node::NodeType DocumentType::nodeType() const
{
return DOCUMENT_TYPE_NODE;
}
PassRefPtr<Node> DocumentType::cloneNode(bool /*deep*/)
{
return create(document(), m_name, m_publicId, m_systemId);
}
Node::InsertionNotificationRequest DocumentType::insertedInto(ContainerNode* insertionPoint)
{
Node::insertedInto(insertionPoint);
if (!insertionPoint->inDocument())
return InsertionDone;
// Our document node can be null if we were created by a DOMImplementation. We use the parent() instead.
ASSERT(parentNode() && parentNode()->isDocumentNode());
if (parentNode() && parentNode()->isDocumentNode()) {
Document* doc = toDocument(parentNode());
if (!doc->doctype())
doc->setDocType(this);
}
return InsertionDone;
}
void DocumentType::removedFrom(ContainerNode* insertionPoint)
{
if (insertionPoint->inDocument() && document() && document()->doctype() == this)
document()->setDocType(0);
Node::removedFrom(insertionPoint);
}
}
| bsd-3-clause |
attilahorvath/phantomjs | src/qt/qtwebkit/Source/WebKit/blackberry/WebCoreSupport/AutofillManager.cpp | 119 | 2602 | /*
* Copyright (C) 2012 Research In Motion Limited. All rights reserved.
*
* 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 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
*/
#include "config.h"
#include "AutofillManager.h"
#include "AutofillBackingStore.h"
#include "HTMLCollection.h"
#include "HTMLFormElement.h"
#include "HTMLInputElement.h"
#include "WebPage_p.h"
namespace WebCore {
static bool isAutofillable(HTMLInputElement* element)
{
return element && element->isTextField() && !element->isPasswordField()
&& !element->isAutofilled() && element->shouldAutocomplete();
}
PassRefPtr<AutofillManager> AutofillManager::create(BlackBerry::WebKit::WebPagePrivate* page)
{
return adoptRef(new AutofillManager(page));
}
void AutofillManager::didChangeInTextField(HTMLInputElement* element)
{
if (!isAutofillable(element))
return;
if (m_element != element)
m_element = element;
Vector<String> candidates = autofillBackingStore().get(element->getAttribute(HTMLNames::nameAttr).string(), element->value());
m_webPagePrivate->notifyPopupAutofillDialog(candidates);
}
void AutofillManager::textFieldDidEndEditing(HTMLInputElement*)
{
m_webPagePrivate->notifyDismissAutofillDialog();
}
void AutofillManager::autofillTextField(const String& value)
{
if (!m_element)
return;
m_element->setValue(value);
m_element->setAutofilled();
}
void AutofillManager::saveTextFields(HTMLFormElement* form)
{
RefPtr<HTMLCollection> elements = form->elements();
size_t itemCount = elements->length();
for (size_t i = 0; i < itemCount; ++i) {
HTMLInputElement* element = form->item(i)->toInputElement();
if (!isAutofillable(element))
continue;
autofillBackingStore().add(element->getAttribute(HTMLNames::nameAttr).string(), element->value());
}
}
void AutofillManager::clear()
{
autofillBackingStore().clear();
}
} // namespace WebCore
| bsd-3-clause |
bmotlaghFLT/FLT_PhantomJS | src/qt/qtwebkit/Source/WebCore/html/HTMLTableSectionElement.cpp | 122 | 4320 | /*
* Copyright (C) 1997 Martin Jones (mjones@kde.org)
* (C) 1997 Torben Weis (weis@kde.org)
* (C) 1998 Waldo Bastian (bastian@kde.org)
* (C) 1999 Lars Knoll (knoll@kde.org)
* (C) 1999 Antti Koivisto (koivisto@kde.org)
* Copyright (C) 2003, 2004, 2005, 2006, 2010 Apple Inc. All rights reserved.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Library General Public
* License as published by the Free Software Foundation; either
* version 2 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
* Library General Public License for more details.
*
* You should have received a copy of the GNU Library General Public License
* along with this library; see the file COPYING.LIB. If not, write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
* Boston, MA 02110-1301, USA.
*/
#include "config.h"
#include "HTMLTableSectionElement.h"
#include "ExceptionCode.h"
#include "HTMLCollection.h"
#include "HTMLNames.h"
#include "HTMLTableRowElement.h"
#include "HTMLTableElement.h"
#include "NodeList.h"
#include "Text.h"
namespace WebCore {
using namespace HTMLNames;
inline HTMLTableSectionElement::HTMLTableSectionElement(const QualifiedName& tagName, Document* document)
: HTMLTablePartElement(tagName, document)
{
}
PassRefPtr<HTMLTableSectionElement> HTMLTableSectionElement::create(const QualifiedName& tagName, Document* document)
{
return adoptRef(new HTMLTableSectionElement(tagName, document));
}
const StylePropertySet* HTMLTableSectionElement::additionalPresentationAttributeStyle()
{
if (HTMLTableElement* table = findParentTable())
return table->additionalGroupStyle(true);
return 0;
}
// these functions are rather slow, since we need to get the row at
// the index... but they aren't used during usual HTML parsing anyway
PassRefPtr<HTMLElement> HTMLTableSectionElement::insertRow(int index, ExceptionCode& ec)
{
RefPtr<HTMLTableRowElement> row;
RefPtr<HTMLCollection> children = rows();
int numRows = children ? (int)children->length() : 0;
if (index < -1 || index > numRows)
ec = INDEX_SIZE_ERR; // per the DOM
else {
row = HTMLTableRowElement::create(trTag, document());
if (numRows == index || index == -1)
appendChild(row, ec);
else {
Node* n;
if (index < 1)
n = firstChild();
else
n = children->item(index);
insertBefore(row, n, ec);
}
}
return row.release();
}
void HTMLTableSectionElement::deleteRow(int index, ExceptionCode& ec)
{
RefPtr<HTMLCollection> children = rows();
int numRows = children ? (int)children->length() : 0;
if (index == -1)
index = numRows - 1;
if (index >= 0 && index < numRows) {
RefPtr<Node> row = children->item(index);
HTMLElement::removeChild(row.get(), ec);
} else
ec = INDEX_SIZE_ERR;
}
int HTMLTableSectionElement::numRows() const
{
int rows = 0;
const Node *n = firstChild();
while (n) {
if (n->hasTagName(trTag))
rows++;
n = n->nextSibling();
}
return rows;
}
String HTMLTableSectionElement::align() const
{
return getAttribute(alignAttr);
}
void HTMLTableSectionElement::setAlign(const String &value)
{
setAttribute(alignAttr, value);
}
String HTMLTableSectionElement::ch() const
{
return getAttribute(charAttr);
}
void HTMLTableSectionElement::setCh(const String &value)
{
setAttribute(charAttr, value);
}
String HTMLTableSectionElement::chOff() const
{
return getAttribute(charoffAttr);
}
void HTMLTableSectionElement::setChOff(const String &value)
{
setAttribute(charoffAttr, value);
}
String HTMLTableSectionElement::vAlign() const
{
return getAttribute(valignAttr);
}
void HTMLTableSectionElement::setVAlign(const String &value)
{
setAttribute(valignAttr, value);
}
PassRefPtr<HTMLCollection> HTMLTableSectionElement::rows()
{
return ensureCachedHTMLCollection(TSectionRows);
}
}
| bsd-3-clause |
fredrikw/scipy | scipy/optimize/minpack/r1mpyq.f | 125 | 2861 | subroutine r1mpyq(m,n,a,lda,v,w)
integer m,n,lda
double precision a(lda,n),v(n),w(n)
c **********
c
c subroutine r1mpyq
c
c given an m by n matrix a, this subroutine computes a*q where
c q is the product of 2*(n - 1) transformations
c
c gv(n-1)*...*gv(1)*gw(1)*...*gw(n-1)
c
c and gv(i), gw(i) are givens rotations in the (i,n) plane which
c eliminate elements in the i-th and n-th planes, respectively.
c q itself is not given, rather the information to recover the
c gv, gw rotations is supplied.
c
c the subroutine statement is
c
c subroutine r1mpyq(m,n,a,lda,v,w)
c
c where
c
c m is a positive integer input variable set to the number
c of rows of a.
c
c n is a positive integer input variable set to the number
c of columns of a.
c
c a is an m by n array. on input a must contain the matrix
c to be postmultiplied by the orthogonal matrix q
c described above. on output a*q has replaced a.
c
c lda is a positive integer input variable not less than m
c which specifies the leading dimension of the array a.
c
c v is an input array of length n. v(i) must contain the
c information necessary to recover the givens rotation gv(i)
c described above.
c
c w is an input array of length n. w(i) must contain the
c information necessary to recover the givens rotation gw(i)
c described above.
c
c subroutines called
c
c fortran-supplied ... dabs,dsqrt
c
c argonne national laboratory. minpack project. march 1980.
c burton s. garbow, kenneth e. hillstrom, jorge j. more
c
c **********
integer i,j,nmj,nm1
double precision cos,one,sin,temp
data one /1.0d0/
c
c apply the first set of givens rotations to a.
c
nm1 = n - 1
if (nm1 .lt. 1) go to 50
do 20 nmj = 1, nm1
j = n - nmj
if (dabs(v(j)) .gt. one) cos = one/v(j)
if (dabs(v(j)) .gt. one) sin = dsqrt(one-cos**2)
if (dabs(v(j)) .le. one) sin = v(j)
if (dabs(v(j)) .le. one) cos = dsqrt(one-sin**2)
do 10 i = 1, m
temp = cos*a(i,j) - sin*a(i,n)
a(i,n) = sin*a(i,j) + cos*a(i,n)
a(i,j) = temp
10 continue
20 continue
c
c apply the second set of givens rotations to a.
c
do 40 j = 1, nm1
if (dabs(w(j)) .gt. one) cos = one/w(j)
if (dabs(w(j)) .gt. one) sin = dsqrt(one-cos**2)
if (dabs(w(j)) .le. one) sin = w(j)
if (dabs(w(j)) .le. one) cos = dsqrt(one-sin**2)
do 30 i = 1, m
temp = cos*a(i,j) + sin*a(i,n)
a(i,n) = -sin*a(i,j) + cos*a(i,n)
a(i,j) = temp
30 continue
40 continue
50 continue
return
c
c last card of subroutine r1mpyq.
c
end
| bsd-3-clause |
akiss77/skia | experimental/PdfViewer/pdfparser/native/pdfapi/SkPdfPopUpAnnotationDictionary_autogen.cpp | 127 | 2152 | /*
* Copyright 2013 Google Inc.
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkPdfPopUpAnnotationDictionary_autogen.h"
#include "SkPdfNativeDoc.h"
SkString SkPdfPopUpAnnotationDictionary::Subtype(SkPdfNativeDoc* doc) {
SkPdfNativeObject* ret = get("Subtype", "");
if (doc) {ret = doc->resolveReference(ret);}
if ((ret != NULL && ret->isName()) || (doc == NULL && ret != NULL && ret->isReference())) return ret->nameValue2();
// TODO(edisonn): warn about missing required field, assert for known good pdfs
return SkString();
}
bool SkPdfPopUpAnnotationDictionary::has_Subtype() const {
return get("Subtype", "") != NULL;
}
SkString SkPdfPopUpAnnotationDictionary::Contents(SkPdfNativeDoc* doc) {
SkPdfNativeObject* ret = get("Contents", "");
if (doc) {ret = doc->resolveReference(ret);}
if ((ret != NULL && ret->isAnyString()) || (doc == NULL && ret != NULL && ret->isReference())) return ret->stringValue2();
// TODO(edisonn): warn about missing default value for optional fields
return SkString();
}
bool SkPdfPopUpAnnotationDictionary::has_Contents() const {
return get("Contents", "") != NULL;
}
SkPdfDictionary* SkPdfPopUpAnnotationDictionary::Parent(SkPdfNativeDoc* doc) {
SkPdfNativeObject* ret = get("Parent", "");
if (doc) {ret = doc->resolveReference(ret);}
if ((ret != NULL && ret->isDictionary()) || (doc == NULL && ret != NULL && ret->isReference())) return (SkPdfDictionary*)ret;
// TODO(edisonn): warn about missing default value for optional fields
return NULL;
}
bool SkPdfPopUpAnnotationDictionary::has_Parent() const {
return get("Parent", "") != NULL;
}
bool SkPdfPopUpAnnotationDictionary::Open(SkPdfNativeDoc* doc) {
SkPdfNativeObject* ret = get("Open", "");
if (doc) {ret = doc->resolveReference(ret);}
if ((ret != NULL && ret->isBoolean()) || (doc == NULL && ret != NULL && ret->isReference())) return ret->boolValue();
// TODO(edisonn): warn about missing default value for optional fields
return false;
}
bool SkPdfPopUpAnnotationDictionary::has_Open() const {
return get("Open", "") != NULL;
}
| bsd-3-clause |
AlbandeCrevoisier/ldd-athens | linux-socfpga/drivers/clk/bcm/clk-cygnus.c | 383 | 10526 | /*
* Copyright (C) 2014 Broadcom Corporation
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License as
* published by the Free Software Foundation version 2.
*
* This program is distributed "as is" WITHOUT ANY WARRANTY of any
* kind, whether express or implied; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*/
#include <linux/kernel.h>
#include <linux/err.h>
#include <linux/clk-provider.h>
#include <linux/io.h>
#include <linux/of.h>
#include <linux/clkdev.h>
#include <linux/of_address.h>
#include <linux/delay.h>
#include <dt-bindings/clock/bcm-cygnus.h>
#include "clk-iproc.h"
#define REG_VAL(o, s, w) { .offset = o, .shift = s, .width = w, }
#define AON_VAL(o, pw, ps, is) { .offset = o, .pwr_width = pw, \
.pwr_shift = ps, .iso_shift = is }
#define SW_CTRL_VAL(o, s) { .offset = o, .shift = s, }
#define ASIU_DIV_VAL(o, es, hs, hw, ls, lw) \
{ .offset = o, .en_shift = es, .high_shift = hs, \
.high_width = hw, .low_shift = ls, .low_width = lw }
#define RESET_VAL(o, rs, prs) { .offset = o, .reset_shift = rs, \
.p_reset_shift = prs }
#define DF_VAL(o, kis, kiw, kps, kpw, kas, kaw) { .offset = o, .ki_shift = kis,\
.ki_width = kiw, .kp_shift = kps, .kp_width = kpw, .ka_shift = kas, \
.ka_width = kaw }
#define VCO_CTRL_VAL(uo, lo) { .u_offset = uo, .l_offset = lo }
#define ENABLE_VAL(o, es, hs, bs) { .offset = o, .enable_shift = es, \
.hold_shift = hs, .bypass_shift = bs }
#define ASIU_GATE_VAL(o, es) { .offset = o, .en_shift = es }
static void __init cygnus_armpll_init(struct device_node *node)
{
iproc_armpll_setup(node);
}
CLK_OF_DECLARE(cygnus_armpll, "brcm,cygnus-armpll", cygnus_armpll_init);
static const struct iproc_pll_ctrl genpll = {
.flags = IPROC_CLK_AON | IPROC_CLK_PLL_HAS_NDIV_FRAC |
IPROC_CLK_PLL_NEEDS_SW_CFG,
.aon = AON_VAL(0x0, 2, 1, 0),
.reset = RESET_VAL(0x0, 11, 10),
.dig_filter = DF_VAL(0x0, 4, 3, 0, 4, 7, 3),
.sw_ctrl = SW_CTRL_VAL(0x10, 31),
.ndiv_int = REG_VAL(0x10, 20, 10),
.ndiv_frac = REG_VAL(0x10, 0, 20),
.pdiv = REG_VAL(0x14, 0, 4),
.vco_ctrl = VCO_CTRL_VAL(0x18, 0x1c),
.status = REG_VAL(0x28, 12, 1),
};
static const struct iproc_clk_ctrl genpll_clk[] = {
[BCM_CYGNUS_GENPLL_AXI21_CLK] = {
.channel = BCM_CYGNUS_GENPLL_AXI21_CLK,
.flags = IPROC_CLK_AON,
.enable = ENABLE_VAL(0x4, 6, 0, 12),
.mdiv = REG_VAL(0x20, 0, 8),
},
[BCM_CYGNUS_GENPLL_250MHZ_CLK] = {
.channel = BCM_CYGNUS_GENPLL_250MHZ_CLK,
.flags = IPROC_CLK_AON,
.enable = ENABLE_VAL(0x4, 7, 1, 13),
.mdiv = REG_VAL(0x20, 10, 8),
},
[BCM_CYGNUS_GENPLL_IHOST_SYS_CLK] = {
.channel = BCM_CYGNUS_GENPLL_IHOST_SYS_CLK,
.flags = IPROC_CLK_AON,
.enable = ENABLE_VAL(0x4, 8, 2, 14),
.mdiv = REG_VAL(0x20, 20, 8),
},
[BCM_CYGNUS_GENPLL_ENET_SW_CLK] = {
.channel = BCM_CYGNUS_GENPLL_ENET_SW_CLK,
.flags = IPROC_CLK_AON,
.enable = ENABLE_VAL(0x4, 9, 3, 15),
.mdiv = REG_VAL(0x24, 0, 8),
},
[BCM_CYGNUS_GENPLL_AUDIO_125_CLK] = {
.channel = BCM_CYGNUS_GENPLL_AUDIO_125_CLK,
.flags = IPROC_CLK_AON,
.enable = ENABLE_VAL(0x4, 10, 4, 16),
.mdiv = REG_VAL(0x24, 10, 8),
},
[BCM_CYGNUS_GENPLL_CAN_CLK] = {
.channel = BCM_CYGNUS_GENPLL_CAN_CLK,
.flags = IPROC_CLK_AON,
.enable = ENABLE_VAL(0x4, 11, 5, 17),
.mdiv = REG_VAL(0x24, 20, 8),
},
};
static void __init cygnus_genpll_clk_init(struct device_node *node)
{
iproc_pll_clk_setup(node, &genpll, NULL, 0, genpll_clk,
ARRAY_SIZE(genpll_clk));
}
CLK_OF_DECLARE(cygnus_genpll, "brcm,cygnus-genpll", cygnus_genpll_clk_init);
static const struct iproc_pll_ctrl lcpll0 = {
.flags = IPROC_CLK_AON | IPROC_CLK_PLL_NEEDS_SW_CFG,
.aon = AON_VAL(0x0, 2, 5, 4),
.reset = RESET_VAL(0x0, 31, 30),
.dig_filter = DF_VAL(0x0, 27, 3, 23, 4, 19, 4),
.sw_ctrl = SW_CTRL_VAL(0x4, 31),
.ndiv_int = REG_VAL(0x4, 16, 10),
.pdiv = REG_VAL(0x4, 26, 4),
.vco_ctrl = VCO_CTRL_VAL(0x10, 0x14),
.status = REG_VAL(0x18, 12, 1),
};
static const struct iproc_clk_ctrl lcpll0_clk[] = {
[BCM_CYGNUS_LCPLL0_PCIE_PHY_REF_CLK] = {
.channel = BCM_CYGNUS_LCPLL0_PCIE_PHY_REF_CLK,
.flags = IPROC_CLK_AON,
.enable = ENABLE_VAL(0x0, 7, 1, 13),
.mdiv = REG_VAL(0x8, 0, 8),
},
[BCM_CYGNUS_LCPLL0_DDR_PHY_CLK] = {
.channel = BCM_CYGNUS_LCPLL0_DDR_PHY_CLK,
.flags = IPROC_CLK_AON,
.enable = ENABLE_VAL(0x0, 8, 2, 14),
.mdiv = REG_VAL(0x8, 10, 8),
},
[BCM_CYGNUS_LCPLL0_SDIO_CLK] = {
.channel = BCM_CYGNUS_LCPLL0_SDIO_CLK,
.flags = IPROC_CLK_AON,
.enable = ENABLE_VAL(0x0, 9, 3, 15),
.mdiv = REG_VAL(0x8, 20, 8),
},
[BCM_CYGNUS_LCPLL0_USB_PHY_REF_CLK] = {
.channel = BCM_CYGNUS_LCPLL0_USB_PHY_REF_CLK,
.flags = IPROC_CLK_AON,
.enable = ENABLE_VAL(0x0, 10, 4, 16),
.mdiv = REG_VAL(0xc, 0, 8),
},
[BCM_CYGNUS_LCPLL0_SMART_CARD_CLK] = {
.channel = BCM_CYGNUS_LCPLL0_SMART_CARD_CLK,
.flags = IPROC_CLK_AON,
.enable = ENABLE_VAL(0x0, 11, 5, 17),
.mdiv = REG_VAL(0xc, 10, 8),
},
[BCM_CYGNUS_LCPLL0_CH5_UNUSED] = {
.channel = BCM_CYGNUS_LCPLL0_CH5_UNUSED,
.flags = IPROC_CLK_AON,
.enable = ENABLE_VAL(0x0, 12, 6, 18),
.mdiv = REG_VAL(0xc, 20, 8),
},
};
static void __init cygnus_lcpll0_clk_init(struct device_node *node)
{
iproc_pll_clk_setup(node, &lcpll0, NULL, 0, lcpll0_clk,
ARRAY_SIZE(lcpll0_clk));
}
CLK_OF_DECLARE(cygnus_lcpll0, "brcm,cygnus-lcpll0", cygnus_lcpll0_clk_init);
/*
* MIPI PLL VCO frequency parameter table
*/
static const struct iproc_pll_vco_param mipipll_vco_params[] = {
/* rate (Hz) ndiv_int ndiv_frac pdiv */
{ 750000000UL, 30, 0, 1 },
{ 1000000000UL, 40, 0, 1 },
{ 1350000000ul, 54, 0, 1 },
{ 2000000000UL, 80, 0, 1 },
{ 2100000000UL, 84, 0, 1 },
{ 2250000000UL, 90, 0, 1 },
{ 2500000000UL, 100, 0, 1 },
{ 2700000000UL, 54, 0, 0 },
{ 2975000000UL, 119, 0, 1 },
{ 3100000000UL, 124, 0, 1 },
{ 3150000000UL, 126, 0, 1 },
};
static const struct iproc_pll_ctrl mipipll = {
.flags = IPROC_CLK_PLL_ASIU | IPROC_CLK_PLL_HAS_NDIV_FRAC |
IPROC_CLK_NEEDS_READ_BACK,
.aon = AON_VAL(0x0, 4, 17, 16),
.asiu = ASIU_GATE_VAL(0x0, 3),
.reset = RESET_VAL(0x0, 11, 10),
.dig_filter = DF_VAL(0x0, 4, 3, 0, 4, 7, 4),
.ndiv_int = REG_VAL(0x10, 20, 10),
.ndiv_frac = REG_VAL(0x10, 0, 20),
.pdiv = REG_VAL(0x14, 0, 4),
.vco_ctrl = VCO_CTRL_VAL(0x18, 0x1c),
.status = REG_VAL(0x28, 12, 1),
};
static const struct iproc_clk_ctrl mipipll_clk[] = {
[BCM_CYGNUS_MIPIPLL_CH0_UNUSED] = {
.channel = BCM_CYGNUS_MIPIPLL_CH0_UNUSED,
.flags = IPROC_CLK_NEEDS_READ_BACK,
.enable = ENABLE_VAL(0x4, 12, 6, 18),
.mdiv = REG_VAL(0x20, 0, 8),
},
[BCM_CYGNUS_MIPIPLL_CH1_LCD] = {
.channel = BCM_CYGNUS_MIPIPLL_CH1_LCD,
.flags = IPROC_CLK_NEEDS_READ_BACK,
.enable = ENABLE_VAL(0x4, 13, 7, 19),
.mdiv = REG_VAL(0x20, 10, 8),
},
[BCM_CYGNUS_MIPIPLL_CH2_V3D] = {
.channel = BCM_CYGNUS_MIPIPLL_CH2_V3D,
.flags = IPROC_CLK_NEEDS_READ_BACK,
.enable = ENABLE_VAL(0x4, 14, 8, 20),
.mdiv = REG_VAL(0x20, 20, 8),
},
[BCM_CYGNUS_MIPIPLL_CH3_UNUSED] = {
.channel = BCM_CYGNUS_MIPIPLL_CH3_UNUSED,
.flags = IPROC_CLK_NEEDS_READ_BACK,
.enable = ENABLE_VAL(0x4, 15, 9, 21),
.mdiv = REG_VAL(0x24, 0, 8),
},
[BCM_CYGNUS_MIPIPLL_CH4_UNUSED] = {
.channel = BCM_CYGNUS_MIPIPLL_CH4_UNUSED,
.flags = IPROC_CLK_NEEDS_READ_BACK,
.enable = ENABLE_VAL(0x4, 16, 10, 22),
.mdiv = REG_VAL(0x24, 10, 8),
},
[BCM_CYGNUS_MIPIPLL_CH5_UNUSED] = {
.channel = BCM_CYGNUS_MIPIPLL_CH5_UNUSED,
.flags = IPROC_CLK_NEEDS_READ_BACK,
.enable = ENABLE_VAL(0x4, 17, 11, 23),
.mdiv = REG_VAL(0x24, 20, 8),
},
};
static void __init cygnus_mipipll_clk_init(struct device_node *node)
{
iproc_pll_clk_setup(node, &mipipll, mipipll_vco_params,
ARRAY_SIZE(mipipll_vco_params), mipipll_clk,
ARRAY_SIZE(mipipll_clk));
}
CLK_OF_DECLARE(cygnus_mipipll, "brcm,cygnus-mipipll", cygnus_mipipll_clk_init);
static const struct iproc_asiu_div asiu_div[] = {
[BCM_CYGNUS_ASIU_KEYPAD_CLK] = ASIU_DIV_VAL(0x0, 31, 16, 10, 0, 10),
[BCM_CYGNUS_ASIU_ADC_CLK] = ASIU_DIV_VAL(0x4, 31, 16, 10, 0, 10),
[BCM_CYGNUS_ASIU_PWM_CLK] = ASIU_DIV_VAL(0x8, 31, 16, 10, 0, 10),
};
static const struct iproc_asiu_gate asiu_gate[] = {
[BCM_CYGNUS_ASIU_KEYPAD_CLK] = ASIU_GATE_VAL(0x0, 7),
[BCM_CYGNUS_ASIU_ADC_CLK] = ASIU_GATE_VAL(0x0, 9),
[BCM_CYGNUS_ASIU_PWM_CLK] = ASIU_GATE_VAL(IPROC_CLK_INVALID_OFFSET, 0),
};
static void __init cygnus_asiu_init(struct device_node *node)
{
iproc_asiu_setup(node, asiu_div, asiu_gate, ARRAY_SIZE(asiu_div));
}
CLK_OF_DECLARE(cygnus_asiu_clk, "brcm,cygnus-asiu-clk", cygnus_asiu_init);
/*
* AUDIO PLL VCO frequency parameter table
*
* PLL output frequency = ((ndiv_int + ndiv_frac / 2^20) *
* (parent clock rate / pdiv)
*
* On Cygnus, parent is the 25MHz oscillator
*/
static const struct iproc_pll_vco_param audiopll_vco_params[] = {
/* rate (Hz) ndiv_int ndiv_frac pdiv */
{ 1354750204UL, 54, 199238, 1 },
{ 1769470191UL, 70, 816639, 1 },
};
static const struct iproc_pll_ctrl audiopll = {
.flags = IPROC_CLK_PLL_NEEDS_SW_CFG | IPROC_CLK_PLL_HAS_NDIV_FRAC |
IPROC_CLK_PLL_USER_MODE_ON | IPROC_CLK_PLL_RESET_ACTIVE_LOW,
.reset = RESET_VAL(0x5c, 0, 1),
.dig_filter = DF_VAL(0x48, 0, 3, 6, 4, 3, 3),
.sw_ctrl = SW_CTRL_VAL(0x4, 0),
.ndiv_int = REG_VAL(0x8, 0, 10),
.ndiv_frac = REG_VAL(0x8, 10, 20),
.pdiv = REG_VAL(0x44, 0, 4),
.vco_ctrl = VCO_CTRL_VAL(0x0c, 0x10),
.status = REG_VAL(0x54, 0, 1),
.macro_mode = REG_VAL(0x0, 0, 3),
};
static const struct iproc_clk_ctrl audiopll_clk[] = {
[BCM_CYGNUS_AUDIOPLL_CH0] = {
.channel = BCM_CYGNUS_AUDIOPLL_CH0,
.flags = IPROC_CLK_AON |
IPROC_CLK_MCLK_DIV_BY_2,
.enable = ENABLE_VAL(0x14, 8, 10, 9),
.mdiv = REG_VAL(0x14, 0, 8),
},
[BCM_CYGNUS_AUDIOPLL_CH1] = {
.channel = BCM_CYGNUS_AUDIOPLL_CH1,
.flags = IPROC_CLK_AON,
.enable = ENABLE_VAL(0x18, 8, 10, 9),
.mdiv = REG_VAL(0x18, 0, 8),
},
[BCM_CYGNUS_AUDIOPLL_CH2] = {
.channel = BCM_CYGNUS_AUDIOPLL_CH2,
.flags = IPROC_CLK_AON,
.enable = ENABLE_VAL(0x1c, 8, 10, 9),
.mdiv = REG_VAL(0x1c, 0, 8),
},
};
static void __init cygnus_audiopll_clk_init(struct device_node *node)
{
iproc_pll_clk_setup(node, &audiopll, audiopll_vco_params,
ARRAY_SIZE(audiopll_vco_params), audiopll_clk,
ARRAY_SIZE(audiopll_clk));
}
CLK_OF_DECLARE(cygnus_audiopll, "brcm,cygnus-audiopll",
cygnus_audiopll_clk_init);
| bsd-3-clause |
SmoothKat/external_skia | src/utils/SkNinePatch.cpp | 132 | 11232 |
/*
* Copyright 2006 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 "SkNinePatch.h"
#include "SkCanvas.h"
#include "SkShader.h"
static const uint16_t g3x3Indices[] = {
0, 5, 1, 0, 4, 5,
1, 6, 2, 1, 5, 6,
2, 7, 3, 2, 6, 7,
4, 9, 5, 4, 8, 9,
5, 10, 6, 5, 9, 10,
6, 11, 7, 6, 10, 11,
8, 13, 9, 8, 12, 13,
9, 14, 10, 9, 13, 14,
10, 15, 11, 10, 14, 15
};
static int fillIndices(uint16_t indices[], int xCount, int yCount) {
uint16_t* startIndices = indices;
int n = 0;
for (int y = 0; y < yCount; y++) {
for (int x = 0; x < xCount; x++) {
*indices++ = n;
*indices++ = n + xCount + 2;
*indices++ = n + 1;
*indices++ = n;
*indices++ = n + xCount + 1;
*indices++ = n + xCount + 2;
n += 1;
}
n += 1;
}
return static_cast<int>(indices - startIndices);
}
// Computes the delta between vertices along a single axis
static SkScalar computeVertexDelta(bool isStretchyVertex,
SkScalar currentVertex,
SkScalar prevVertex,
SkScalar stretchFactor) {
// the standard delta between vertices if no stretching is required
SkScalar delta = currentVertex - prevVertex;
// if the stretch factor is negative or zero we need to shrink the 9-patch
// to fit within the target bounds. This means that we will eliminate all
// stretchy areas and scale the fixed areas to fit within the target bounds.
if (stretchFactor <= 0) {
if (isStretchyVertex)
delta = 0; // collapse stretchable areas
else
delta = SkScalarMul(delta, -stretchFactor); // scale fixed areas
// if the stretch factor is positive then we use the standard delta for
// fixed and scale the stretchable areas to fill the target bounds.
} else if (isStretchyVertex) {
delta = SkScalarMul(delta, stretchFactor);
}
return delta;
}
static void fillRow(SkPoint verts[], SkPoint texs[],
const SkScalar vy, const SkScalar ty,
const SkRect& bounds, const int32_t xDivs[], int numXDivs,
const SkScalar stretchX, int width) {
SkScalar vx = bounds.fLeft;
verts->set(vx, vy); verts++;
texs->set(0, ty); texs++;
SkScalar prev = 0;
for (int x = 0; x < numXDivs; x++) {
const SkScalar tx = SkIntToScalar(xDivs[x]);
vx += computeVertexDelta(x & 1, tx, prev, stretchX);
prev = tx;
verts->set(vx, vy); verts++;
texs->set(tx, ty); texs++;
}
verts->set(bounds.fRight, vy); verts++;
texs->set(SkIntToScalar(width), ty); texs++;
}
struct Mesh {
const SkPoint* fVerts;
const SkPoint* fTexs;
const SkColor* fColors;
const uint16_t* fIndices;
};
void SkNinePatch::DrawMesh(SkCanvas* canvas, const SkRect& bounds,
const SkBitmap& bitmap,
const int32_t xDivs[], int numXDivs,
const int32_t yDivs[], int numYDivs,
const SkPaint* paint) {
if (bounds.isEmpty() || bitmap.width() == 0 || bitmap.height() == 0) {
return;
}
// should try a quick-reject test before calling lockPixels
SkAutoLockPixels alp(bitmap);
// after the lock, it is valid to check
if (!bitmap.readyToDraw()) {
return;
}
// check for degenerate divs (just an optimization, not required)
{
int i;
int zeros = 0;
for (i = 0; i < numYDivs && yDivs[i] == 0; i++) {
zeros += 1;
}
numYDivs -= zeros;
yDivs += zeros;
for (i = numYDivs - 1; i >= 0 && yDivs[i] == bitmap.height(); --i) {
numYDivs -= 1;
}
}
Mesh mesh;
const int numXStretch = (numXDivs + 1) >> 1;
const int numYStretch = (numYDivs + 1) >> 1;
if (numXStretch < 1 && numYStretch < 1) {
canvas->drawBitmapRect(bitmap, NULL, bounds, paint);
return;
}
if (false) {
int i;
for (i = 0; i < numXDivs; i++) {
SkDebugf("--- xdivs[%d] %d\n", i, xDivs[i]);
}
for (i = 0; i < numYDivs; i++) {
SkDebugf("--- ydivs[%d] %d\n", i, yDivs[i]);
}
}
SkScalar stretchX = 0, stretchY = 0;
if (numXStretch > 0) {
int stretchSize = 0;
for (int i = 1; i < numXDivs; i += 2) {
stretchSize += xDivs[i] - xDivs[i-1];
}
const SkScalar fixed = SkIntToScalar(bitmap.width() - stretchSize);
if (bounds.width() >= fixed)
stretchX = (bounds.width() - fixed) / stretchSize;
else // reuse stretchX, but keep it negative as a signal
stretchX = SkScalarDiv(-bounds.width(), fixed);
}
if (numYStretch > 0) {
int stretchSize = 0;
for (int i = 1; i < numYDivs; i += 2) {
stretchSize += yDivs[i] - yDivs[i-1];
}
const SkScalar fixed = SkIntToScalar(bitmap.height() - stretchSize);
if (bounds.height() >= fixed)
stretchY = (bounds.height() - fixed) / stretchSize;
else // reuse stretchX, but keep it negative as a signal
stretchY = SkScalarDiv(-bounds.height(), fixed);
}
#if 0
SkDebugf("---- drawasamesh [%d %d] -> [%g %g] <%d %d> (%g %g)\n",
bitmap.width(), bitmap.height(),
SkScalarToFloat(bounds.width()), SkScalarToFloat(bounds.height()),
numXDivs + 1, numYDivs + 1,
SkScalarToFloat(stretchX), SkScalarToFloat(stretchY));
#endif
const int vCount = (numXDivs + 2) * (numYDivs + 2);
// number of celss * 2 (tris per cell) * 3 (verts per tri)
const int indexCount = (numXDivs + 1) * (numYDivs + 1) * 2 * 3;
// allocate 2 times, one for verts, one for texs, plus indices
SkAutoMalloc storage(vCount * sizeof(SkPoint) * 2 +
indexCount * sizeof(uint16_t));
SkPoint* verts = (SkPoint*)storage.get();
SkPoint* texs = verts + vCount;
uint16_t* indices = (uint16_t*)(texs + vCount);
mesh.fVerts = verts;
mesh.fTexs = texs;
mesh.fColors = NULL;
mesh.fIndices = NULL;
// we use <= for YDivs, since the prebuild indices work for 3x2 and 3x1 too
if (numXDivs == 2 && numYDivs <= 2) {
mesh.fIndices = g3x3Indices;
} else {
SkDEBUGCODE(int n =) fillIndices(indices, numXDivs + 1, numYDivs + 1);
SkASSERT(n == indexCount);
mesh.fIndices = indices;
}
SkScalar vy = bounds.fTop;
fillRow(verts, texs, vy, 0, bounds, xDivs, numXDivs,
stretchX, bitmap.width());
verts += numXDivs + 2;
texs += numXDivs + 2;
for (int y = 0; y < numYDivs; y++) {
const SkScalar ty = SkIntToScalar(yDivs[y]);
if (stretchY >= 0) {
if (y & 1) {
vy += stretchY;
} else {
vy += ty;
}
} else { // shrink fixed sections, and collaps stretchy sections
if (y & 1) {
;// do nothing
} else {
vy += SkScalarMul(ty, -stretchY);
}
}
fillRow(verts, texs, vy, ty, bounds, xDivs, numXDivs,
stretchX, bitmap.width());
verts += numXDivs + 2;
texs += numXDivs + 2;
}
fillRow(verts, texs, bounds.fBottom, SkIntToScalar(bitmap.height()),
bounds, xDivs, numXDivs, stretchX, bitmap.width());
SkShader* shader = SkShader::CreateBitmapShader(bitmap,
SkShader::kClamp_TileMode,
SkShader::kClamp_TileMode);
SkPaint p;
if (paint) {
p = *paint;
}
p.setShader(shader)->unref();
canvas->drawVertices(SkCanvas::kTriangles_VertexMode, vCount,
mesh.fVerts, mesh.fTexs, mesh.fColors, NULL,
mesh.fIndices, indexCount, p);
}
///////////////////////////////////////////////////////////////////////////////
static void drawNineViaRects(SkCanvas* canvas, const SkRect& dst,
const SkBitmap& bitmap, const SkIRect& margins,
const SkPaint* paint) {
const int32_t srcX[4] = {
0, margins.fLeft, bitmap.width() - margins.fRight, bitmap.width()
};
const int32_t srcY[4] = {
0, margins.fTop, bitmap.height() - margins.fBottom, bitmap.height()
};
SkScalar dstX[4] = {
dst.fLeft, dst.fLeft + SkIntToScalar(margins.fLeft),
dst.fRight - SkIntToScalar(margins.fRight), dst.fRight
};
SkScalar dstY[4] = {
dst.fTop, dst.fTop + SkIntToScalar(margins.fTop),
dst.fBottom - SkIntToScalar(margins.fBottom), dst.fBottom
};
if (dstX[1] > dstX[2]) {
dstX[1] = dstX[0] + (dstX[3] - dstX[0]) * SkIntToScalar(margins.fLeft) /
(SkIntToScalar(margins.fLeft) + SkIntToScalar(margins.fRight));
dstX[2] = dstX[1];
}
if (dstY[1] > dstY[2]) {
dstY[1] = dstY[0] + (dstY[3] - dstY[0]) * SkIntToScalar(margins.fTop) /
(SkIntToScalar(margins.fTop) + SkIntToScalar(margins.fBottom));
dstY[2] = dstY[1];
}
SkIRect s;
SkRect d;
for (int y = 0; y < 3; y++) {
s.fTop = srcY[y];
s.fBottom = srcY[y+1];
d.fTop = dstY[y];
d.fBottom = dstY[y+1];
for (int x = 0; x < 3; x++) {
s.fLeft = srcX[x];
s.fRight = srcX[x+1];
d.fLeft = dstX[x];
d.fRight = dstX[x+1];
canvas->drawBitmapRect(bitmap, &s, d, paint);
}
}
}
void SkNinePatch::DrawNine(SkCanvas* canvas, const SkRect& bounds,
const SkBitmap& bitmap, const SkIRect& margins,
const SkPaint* paint) {
/** Our vertices code has numerical precision problems if the transformed
coordinates land directly on a 1/2 pixel boundary. To work around that
for now, we only take the vertices case if we are in opengl. Also,
when not in GL, the vertices impl is slower (more math) than calling
the viaRects code.
*/
if (false /* is our canvas backed by a gpu?*/) {
int32_t xDivs[2];
int32_t yDivs[2];
xDivs[0] = margins.fLeft;
xDivs[1] = bitmap.width() - margins.fRight;
yDivs[0] = margins.fTop;
yDivs[1] = bitmap.height() - margins.fBottom;
if (xDivs[0] > xDivs[1]) {
xDivs[0] = bitmap.width() * margins.fLeft /
(margins.fLeft + margins.fRight);
xDivs[1] = xDivs[0];
}
if (yDivs[0] > yDivs[1]) {
yDivs[0] = bitmap.height() * margins.fTop /
(margins.fTop + margins.fBottom);
yDivs[1] = yDivs[0];
}
SkNinePatch::DrawMesh(canvas, bounds, bitmap,
xDivs, 2, yDivs, 2, paint);
} else {
drawNineViaRects(canvas, bounds, bitmap, margins, paint);
}
}
| bsd-3-clause |
iostrovok/js-bratok | node_modules/gulp-sass/node_modules/node-sass/src/libsass/context.cpp | 140 | 17879 | #ifdef _WIN32
#define PATH_SEP ';'
#else
#define PATH_SEP ':'
#endif
#ifndef SASS_AST
#include "ast.hpp"
#endif
#include "context.hpp"
#include "constants.hpp"
#include "parser.hpp"
#include "file.hpp"
#include "inspect.hpp"
#include "output_nested.hpp"
#include "output_compressed.hpp"
#include "expand.hpp"
#include "eval.hpp"
#include "contextualize.hpp"
#include "extend.hpp"
#include "remove_placeholders.hpp"
#include "copy_c_str.hpp"
#include "color_names.hpp"
#include "functions.hpp"
#include "backtrace.hpp"
#include "sass2scss.h"
#ifndef SASS_PRELEXER
#include "prelexer.hpp"
#endif
#include <iomanip>
#include <iostream>
#include <cstring>
#include <sstream>
namespace Sass {
using namespace Constants;
using namespace File;
using std::cerr;
using std::endl;
Sass_Queued::Sass_Queued(const string& load_path, const string& abs_path, const char* source)
{
this->load_path = load_path;
this->abs_path = abs_path;
this->source = source;
}
Context::Context(Context::Data initializers)
: mem(Memory_Manager<AST_Node>()),
source_c_str (initializers.source_c_str()),
sources (vector<const char*>()),
include_paths (initializers.include_paths()),
queue (vector<Sass_Queued>()),
style_sheets (map<string, Block*>()),
source_map (resolve_relative_path(initializers.output_path(), initializers.source_map_file(), get_cwd())),
c_functions (vector<Sass_C_Function_Callback>()),
image_path (initializers.image_path()),
input_path (make_canonical_path(initializers.input_path())),
output_path (make_canonical_path(initializers.output_path())),
source_comments (initializers.source_comments()),
output_style (initializers.output_style()),
source_map_file (make_canonical_path(initializers.source_map_file())),
source_map_embed (initializers.source_map_embed()),
source_map_contents (initializers.source_map_contents()),
omit_source_map_url (initializers.omit_source_map_url()),
is_indented_syntax_src (initializers.is_indented_syntax_src()),
importer (initializers.importer()),
names_to_colors (map<string, Color*>()),
colors_to_names (map<int, string>()),
precision (initializers.precision()),
_skip_source_map_update (initializers._skip_source_map_update()),
subset_map (Subset_Map<string, pair<Complex_Selector*, Compound_Selector*> >())
{
cwd = get_cwd();
// enforce some safe defaults
// used to create relative file links
if (input_path == "") input_path = "stdin";
if (output_path == "") output_path = "stdout";
include_paths.push_back(cwd);
collect_include_paths(initializers.include_paths_c_str());
collect_include_paths(initializers.include_paths_array());
setup_color_map();
string entry_point = initializers.entry_point();
if (!entry_point.empty()) {
string result(add_file(entry_point));
if (result.empty()) {
throw "File to read not found or unreadable: " + entry_point;
}
}
}
Context::~Context()
{
// everything that gets put into sources will be freed by us
for (size_t i = 0; i < sources.size(); ++i) delete[] sources[i];
for (size_t n = 0; n < import_stack.size(); ++n) sass_delete_import(import_stack[n]);
sources.clear(); import_stack.clear();
}
void Context::setup_color_map()
{
size_t i = 0;
while (color_names[i]) {
string name(color_names[i]);
Color* value = new (mem) Color("[COLOR TABLE]", Position(),
color_values[i*4],
color_values[i*4+1],
color_values[i*4+2],
color_values[i*4+3]);
names_to_colors[name] = value;
// only map fully opaque colors
if (color_values[i*4+3] >= 1) {
int numval = color_values[i*4]*0x10000;
numval += color_values[i*4+1]*0x100;
numval += color_values[i*4+2];
colors_to_names[numval] = name;
}
++i;
}
}
void Context::collect_include_paths(const char* paths_str)
{
if (paths_str) {
const char* beg = paths_str;
const char* end = Prelexer::find_first<PATH_SEP>(beg);
while (end) {
string path(beg, end - beg);
if (!path.empty()) {
if (*path.rbegin() != '/') path += '/';
include_paths.push_back(path);
}
beg = end + 1;
end = Prelexer::find_first<PATH_SEP>(beg);
}
string path(beg);
if (!path.empty()) {
if (*path.rbegin() != '/') path += '/';
include_paths.push_back(path);
}
}
}
void Context::collect_include_paths(const char** paths_array)
{
if (*include_paths.back().rbegin() != '/') include_paths.back() += '/';
if (paths_array) {
for (size_t i = 0; paths_array[i]; i++) {
collect_include_paths(paths_array[i]);
}
}
}
void Context::add_source(string load_path, string abs_path, const char* contents)
{
sources.push_back(contents);
included_files.push_back(abs_path);
queue.push_back(Sass_Queued(load_path, abs_path, contents));
source_map.source_index.push_back(sources.size() - 1);
include_links.push_back(resolve_relative_path(abs_path, source_map_file, cwd));
}
string Context::add_file(string path)
{
using namespace File;
char* contents = 0;
string real_path;
path = make_canonical_path(path);
for (size_t i = 0, S = include_paths.size(); i < S; ++i) {
string full_path(join_paths(include_paths[i], path));
if (style_sheets.count(full_path)) return full_path;
contents = resolve_and_load(full_path, real_path);
if (contents) {
add_source(full_path, real_path, contents);
style_sheets[full_path] = 0;
return full_path;
}
}
return string();
}
string Context::add_file(string dir, string rel_filepath)
{
using namespace File;
char* contents = 0;
string real_path;
rel_filepath = make_canonical_path(rel_filepath);
string full_path(join_paths(dir, rel_filepath));
if (style_sheets.count(full_path)) return full_path;
contents = resolve_and_load(full_path, real_path);
if (contents) {
add_source(full_path, real_path, contents);
style_sheets[full_path] = 0;
return full_path;
}
for (size_t i = 0, S = include_paths.size(); i < S; ++i) {
string full_path(join_paths(include_paths[i], rel_filepath));
if (style_sheets.count(full_path)) return full_path;
contents = resolve_and_load(full_path, real_path);
if (contents) {
add_source(full_path, real_path, contents);
style_sheets[full_path] = 0;
return full_path;
}
}
return string();
}
void register_function(Context&, Signature sig, Native_Function f, Env* env);
void register_function(Context&, Signature sig, Native_Function f, size_t arity, Env* env);
void register_overload_stub(Context&, string name, Env* env);
void register_built_in_functions(Context&, Env* env);
void register_c_functions(Context&, Env* env, Sass_C_Function_List);
void register_c_function(Context&, Env* env, Sass_C_Function_Callback);
char* Context::compile_block(Block* root)
{
char* result = 0;
if (!root) return 0;
switch (output_style) {
case COMPRESSED: {
Output_Compressed output_compressed(this);
root->perform(&output_compressed);
string output = output_compressed.get_buffer();
if (source_map_file != "" && !omit_source_map_url) {
output += format_source_mapping_url(source_map_file);
}
result = copy_c_str(output.c_str());
} break;
default: {
Output_Nested output_nested(source_comments, this);
root->perform(&output_nested);
string output = output_nested.get_buffer();
if (source_map_file != "" && !omit_source_map_url) {
output += "\n" + format_source_mapping_url(source_map_file);
}
result = copy_c_str(output.c_str());
} break;
}
return result;
}
Block* Context::parse_file()
{
Block* root = 0;
for (size_t i = 0; i < queue.size(); ++i) {
struct Sass_Import* import = sass_make_import(
queue[i].load_path.c_str(),
queue[i].abs_path.c_str(),
0, 0
);
import_stack.push_back(import);
Parser p(Parser::from_c_str(queue[i].source, *this, queue[i].abs_path, Position(1 + i, 1, 1)));
Block* ast = p.parse();
sass_delete_import(import_stack.back());
import_stack.pop_back();
if (i == 0) root = ast;
style_sheets[queue[i].load_path] = ast;
}
if (root == 0) return 0;
Env tge;
Backtrace backtrace(0, "", Position(), "");
register_built_in_functions(*this, &tge);
for (size_t i = 0, S = c_functions.size(); i < S; ++i) {
register_c_function(*this, &tge, c_functions[i]);
}
Eval eval(*this, &tge, &backtrace);
Contextualize contextualize(*this, &eval, &tge, &backtrace);
Expand expand(*this, &eval, &contextualize, &tge, &backtrace);
// Inspect inspect(this);
// Output_Nested output_nested(*this);
root = root->perform(&expand)->block();
if (!subset_map.empty()) {
Extend extend(*this, subset_map);
root->perform(&extend);
}
Remove_Placeholders remove_placeholders(*this);
root->perform(&remove_placeholders);
return root;
}
Block* Context::parse_string()
{
if (!source_c_str) return 0;
queue.clear();
if(is_indented_syntax_src) {
char * contents = sass2scss(source_c_str, SASS2SCSS_PRETTIFY_1);
add_source(input_path, input_path, contents);
return parse_file();
}
add_source(input_path, input_path, strdup(source_c_str));
return parse_file();
}
char* Context::compile_file()
{
// returns NULL if something fails
return compile_block(parse_file());
}
char* Context::compile_string()
{
// returns NULL if something fails
return compile_block(parse_string());
}
string Context::format_source_mapping_url(const string& file)
{
string url = resolve_relative_path(file, output_path, cwd);
if (source_map_embed) {
string map = source_map.generate_source_map(*this);
istringstream is( map );
ostringstream buffer;
base64::encoder E;
E.encode(is, buffer);
url = "data:application/json;base64," + buffer.str();
url.erase(url.size() - 1);
}
return "/*# sourceMappingURL=" + url + " */";
}
char* Context::generate_source_map()
{
if (source_map_file == "") return 0;
char* result = 0;
string map = source_map.generate_source_map(*this);
result = copy_c_str(map.c_str());
return result;
}
std::vector<std::string> Context::get_included_files(size_t skip)
{
vector<string> includes = included_files;
std::sort( includes.begin() + skip, includes.end() );
includes.erase( std::unique( includes.begin(), includes.end() ), includes.end() );
// the skip solution seems more robust, as we may have real files named stdin
// includes.erase( std::remove( includes.begin(), includes.end(), "stdin" ), includes.end() );
return includes;
}
string Context::get_cwd()
{
return Sass::File::get_cwd();
}
void register_function(Context& ctx, Signature sig, Native_Function f, Env* env)
{
Definition* def = make_native_function(sig, f, ctx);
def->environment(env);
(*env)[def->name() + "[f]"] = def;
}
void register_function(Context& ctx, Signature sig, Native_Function f, size_t arity, Env* env)
{
Definition* def = make_native_function(sig, f, ctx);
stringstream ss;
ss << def->name() << "[f]" << arity;
def->environment(env);
(*env)[ss.str()] = def;
}
void register_overload_stub(Context& ctx, string name, Env* env)
{
Definition* stub = new (ctx.mem) Definition("[built-in function]",
Position(),
0,
name,
0,
0,
true);
(*env)[name + "[f]"] = stub;
}
void register_built_in_functions(Context& ctx, Env* env)
{
using namespace Functions;
// RGB Functions
register_function(ctx, rgb_sig, rgb, env);
register_overload_stub(ctx, "rgba", env);
register_function(ctx, rgba_4_sig, rgba_4, 4, env);
register_function(ctx, rgba_2_sig, rgba_2, 2, env);
register_function(ctx, red_sig, red, env);
register_function(ctx, green_sig, green, env);
register_function(ctx, blue_sig, blue, env);
register_function(ctx, mix_sig, mix, env);
// HSL Functions
register_function(ctx, hsl_sig, hsl, env);
register_function(ctx, hsla_sig, hsla, env);
register_function(ctx, hue_sig, hue, env);
register_function(ctx, saturation_sig, saturation, env);
register_function(ctx, lightness_sig, lightness, env);
register_function(ctx, adjust_hue_sig, adjust_hue, env);
register_function(ctx, lighten_sig, lighten, env);
register_function(ctx, darken_sig, darken, env);
register_function(ctx, saturate_sig, saturate, env);
register_function(ctx, desaturate_sig, desaturate, env);
register_function(ctx, grayscale_sig, grayscale, env);
register_function(ctx, complement_sig, complement, env);
register_function(ctx, invert_sig, invert, env);
// Opacity Functions
register_function(ctx, alpha_sig, alpha, env);
register_function(ctx, opacity_sig, alpha, env);
register_function(ctx, opacify_sig, opacify, env);
register_function(ctx, fade_in_sig, opacify, env);
register_function(ctx, transparentize_sig, transparentize, env);
register_function(ctx, fade_out_sig, transparentize, env);
// Other Color Functions
register_function(ctx, adjust_color_sig, adjust_color, env);
register_function(ctx, scale_color_sig, scale_color, env);
register_function(ctx, change_color_sig, change_color, env);
register_function(ctx, ie_hex_str_sig, ie_hex_str, env);
// String Functions
register_function(ctx, unquote_sig, sass_unquote, env);
register_function(ctx, quote_sig, sass_quote, env);
register_function(ctx, str_length_sig, str_length, env);
register_function(ctx, str_insert_sig, str_insert, env);
register_function(ctx, str_index_sig, str_index, env);
register_function(ctx, str_slice_sig, str_slice, env);
register_function(ctx, to_upper_case_sig, to_upper_case, env);
register_function(ctx, to_lower_case_sig, to_lower_case, env);
// Number Functions
register_function(ctx, percentage_sig, percentage, env);
register_function(ctx, round_sig, round, env);
register_function(ctx, ceil_sig, ceil, env);
register_function(ctx, floor_sig, floor, env);
register_function(ctx, abs_sig, abs, env);
register_function(ctx, min_sig, min, env);
register_function(ctx, max_sig, max, env);
register_function(ctx, random_sig, random, env);
// List Functions
register_function(ctx, length_sig, length, env);
register_function(ctx, nth_sig, nth, env);
register_function(ctx, set_nth_sig, set_nth, env);
register_function(ctx, index_sig, index, env);
register_function(ctx, join_sig, join, env);
register_function(ctx, append_sig, append, env);
register_function(ctx, compact_sig, compact, env);
register_function(ctx, zip_sig, zip, env);
register_function(ctx, list_separator_sig, list_separator, env);
// Map Functions
register_function(ctx, map_get_sig, map_get, env);
register_function(ctx, map_merge_sig, map_merge, env);
register_function(ctx, map_remove_sig, map_remove, env);
register_function(ctx, map_keys_sig, map_keys, env);
register_function(ctx, map_values_sig, map_values, env);
register_function(ctx, map_has_key_sig, map_has_key, env);
register_function(ctx, keywords_sig, keywords, env);
// Introspection Functions
register_function(ctx, type_of_sig, type_of, env);
register_function(ctx, unit_sig, unit, env);
register_function(ctx, unitless_sig, unitless, env);
register_function(ctx, comparable_sig, comparable, env);
register_function(ctx, variable_exists_sig, variable_exists, env);
register_function(ctx, global_variable_exists_sig, global_variable_exists, env);
register_function(ctx, function_exists_sig, function_exists, env);
register_function(ctx, mixin_exists_sig, mixin_exists, env);
register_function(ctx, feature_exists_sig, feature_exists, env);
register_function(ctx, call_sig, call, env);
// Boolean Functions
register_function(ctx, not_sig, sass_not, env);
register_function(ctx, if_sig, sass_if, env);
// Path Functions
register_function(ctx, image_url_sig, image_url, env);
// Misc Functions
register_function(ctx, inspect_sig, inspect, env);
register_function(ctx, unique_id_sig, unique_id, env);
}
void register_c_functions(Context& ctx, Env* env, Sass_C_Function_List descrs)
{
while (descrs && *descrs) {
register_c_function(ctx, env, *descrs);
++descrs;
}
}
void register_c_function(Context& ctx, Env* env, Sass_C_Function_Callback descr)
{
Definition* def = make_c_function(
sass_function_get_signature(descr),
sass_function_get_function(descr),
sass_function_get_cookie(descr),
ctx
);
def->environment(env);
(*env)[def->name() + "[f]"] = def;
}
}
| bsd-3-clause |
Tomtomgo/phantomjs | src/qt/qtwebkit/Source/WebCore/platform/graphics/gtk/GdkCairoUtilities.cpp | 142 | 1737 | /*
* Copyright (C) 2010 Igalia S.L.
*
* 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.
*
* THIS SOFTWARE IS PROVIDED BY APPLE COMPUTER, INC. ``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 APPLE COMPUTER, INC. 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.
*/
#include "config.h"
#include "GdkCairoUtilities.h"
#include "GtkVersioning.h"
#include <cairo.h>
#include <gtk/gtk.h>
GdkPixbuf* cairoImageSurfaceToGdkPixbuf(cairo_surface_t* surface)
{
return gdk_pixbuf_get_from_surface(surface, 0, 0,
cairo_image_surface_get_width(surface),
cairo_image_surface_get_height(surface));
}
| bsd-3-clause |
MIPS/external-chromium_org-third_party-skia | tests/InfRectTest.cpp | 150 | 2470 | /*
* Copyright 2011 Google Inc.
*
* Use of this source code is governed by a BSD-style license that can be
* found in the LICENSE file.
*/
#include "SkRandom.h"
#include "SkRect.h"
#include "Test.h"
static float make_zero() {
return sk_float_sin(0);
}
struct RectCenter {
SkIRect fRect;
SkIPoint fCenter;
};
static void test_center(skiatest::Reporter* reporter) {
static const RectCenter gData[] = {
{ { 0, 0, 0, 0 }, { 0, 0 } },
{ { 0, 0, 1, 1 }, { 0, 0 } },
{ { -1, -1, 0, 0 }, { -1, -1 } },
{ { 0, 0, 10, 7 }, { 5, 3 } },
{ { 0, 0, 11, 6 }, { 5, 3 } },
};
for (size_t index = 0; index < SK_ARRAY_COUNT(gData); ++index) {
REPORTER_ASSERT(reporter,
gData[index].fRect.centerX() == gData[index].fCenter.x());
REPORTER_ASSERT(reporter,
gData[index].fRect.centerY() == gData[index].fCenter.y());
}
SkRandom rand;
for (int i = 0; i < 10000; ++i) {
SkIRect r;
r.set(rand.nextS() >> 2, rand.nextS() >> 2,
rand.nextS() >> 2, rand.nextS() >> 2);
int cx = r.centerX();
int cy = r.centerY();
REPORTER_ASSERT(reporter, ((r.left() + r.right()) >> 1) == cx);
REPORTER_ASSERT(reporter, ((r.top() + r.bottom()) >> 1) == cy);
}
}
static void check_invalid(skiatest::Reporter* reporter,
SkScalar l, SkScalar t, SkScalar r, SkScalar b) {
SkRect rect;
rect.set(l, t, r, b);
REPORTER_ASSERT(reporter, !rect.isFinite());
}
// Tests that isFinite() will reject any rect with +/-inf values
// as one of its coordinates.
DEF_TEST(InfRect, reporter) {
float inf = 1 / make_zero(); // infinity
float nan = inf * 0;
SkASSERT(!(nan == nan));
SkScalar small = SkIntToScalar(10);
SkScalar big = SkIntToScalar(100);
REPORTER_ASSERT(reporter, SkRect::MakeEmpty().isFinite());
SkRect rect = SkRect::MakeXYWH(small, small, big, big);
REPORTER_ASSERT(reporter, rect.isFinite());
const SkScalar invalid[] = { nan, inf, -inf };
for (size_t i = 0; i < SK_ARRAY_COUNT(invalid); ++i) {
check_invalid(reporter, small, small, big, invalid[i]);
check_invalid(reporter, small, small, invalid[i], big);
check_invalid(reporter, small, invalid[i], big, big);
check_invalid(reporter, invalid[i], small, big, big);
}
test_center(reporter);
}
// need tests for SkStrSearch
| bsd-3-clause |
sriki18/scipy | scipy/special/cdflib/cumchi.f | 151 | 1463 | SUBROUTINE cumchi(x,df,cum,ccum)
C**********************************************************************
C
C SUBROUTINE FUNCTION CUMCHI(X,DF,CUM,CCUM)
C CUMulative of the CHi-square distribution
C
C
C Function
C
C
C Calculates the cumulative chi-square distribution.
C
C
C Arguments
C
C
C X --> Upper limit of integration of the
C chi-square distribution.
C X is DOUBLE PRECISION
C
C DF --> Degrees of freedom of the
C chi-square distribution.
C DF is DOUBLE PRECISION
C
C CUM <-- Cumulative chi-square distribution.
C CUM is DOUBLE PRECISIO
C
C CCUM <-- Compliment of Cumulative chi-square distribution.
C CCUM is DOUBLE PRECISI
C
C
C Method
C
C
C Calls incomplete gamma function (CUMGAM)
C
C**********************************************************************
C .. Scalar Arguments ..
DOUBLE PRECISION df,x,cum,ccum
C ..
C .. Local Scalars ..
DOUBLE PRECISION a,xx
C ..
C .. External Subroutines ..
EXTERNAL cumgam
C ..
C .. Executable Statements ..
a = df*0.5D0
xx = x*0.5D0
CALL cumgam(xx,a,cum,ccum)
RETURN
END
| bsd-3-clause |
pcarrier-packaging/deb-phantomjs | src/qt/src/3rdparty/libjpeg/jcomapi.c | 2759 | 3110 | /*
* jcomapi.c
*
* Copyright (C) 1994-1997, Thomas G. Lane.
* This file is part of the Independent JPEG Group's software.
* For conditions of distribution and use, see the accompanying README file.
*
* This file contains application interface routines that are used for both
* compression and decompression.
*/
#define JPEG_INTERNALS
#include "jinclude.h"
#include "jpeglib.h"
/*
* Abort processing of a JPEG compression or decompression operation,
* but don't destroy the object itself.
*
* For this, we merely clean up all the nonpermanent memory pools.
* Note that temp files (virtual arrays) are not allowed to belong to
* the permanent pool, so we will be able to close all temp files here.
* Closing a data source or destination, if necessary, is the application's
* responsibility.
*/
GLOBAL(void)
jpeg_abort (j_common_ptr cinfo)
{
int pool;
/* Do nothing if called on a not-initialized or destroyed JPEG object. */
if (cinfo->mem == NULL)
return;
/* Releasing pools in reverse order might help avoid fragmentation
* with some (brain-damaged) malloc libraries.
*/
for (pool = JPOOL_NUMPOOLS-1; pool > JPOOL_PERMANENT; pool--) {
(*cinfo->mem->free_pool) (cinfo, pool);
}
/* Reset overall state for possible reuse of object */
if (cinfo->is_decompressor) {
cinfo->global_state = DSTATE_START;
/* Try to keep application from accessing now-deleted marker list.
* A bit kludgy to do it here, but this is the most central place.
*/
((j_decompress_ptr) cinfo)->marker_list = NULL;
} else {
cinfo->global_state = CSTATE_START;
}
}
/*
* Destruction of a JPEG object.
*
* Everything gets deallocated except the master jpeg_compress_struct itself
* and the error manager struct. Both of these are supplied by the application
* and must be freed, if necessary, by the application. (Often they are on
* the stack and so don't need to be freed anyway.)
* Closing a data source or destination, if necessary, is the application's
* responsibility.
*/
GLOBAL(void)
jpeg_destroy (j_common_ptr cinfo)
{
/* We need only tell the memory manager to release everything. */
/* NB: mem pointer is NULL if memory mgr failed to initialize. */
if (cinfo->mem != NULL)
(*cinfo->mem->self_destruct) (cinfo);
cinfo->mem = NULL; /* be safe if jpeg_destroy is called twice */
cinfo->global_state = 0; /* mark it destroyed */
}
/*
* Convenience routines for allocating quantization and Huffman tables.
* (Would jutils.c be a more reasonable place to put these?)
*/
GLOBAL(JQUANT_TBL *)
jpeg_alloc_quant_table (j_common_ptr cinfo)
{
JQUANT_TBL *tbl;
tbl = (JQUANT_TBL *)
(*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JQUANT_TBL));
tbl->sent_table = FALSE; /* make sure this is false in any new table */
return tbl;
}
GLOBAL(JHUFF_TBL *)
jpeg_alloc_huff_table (j_common_ptr cinfo)
{
JHUFF_TBL *tbl;
tbl = (JHUFF_TBL *)
(*cinfo->mem->alloc_small) (cinfo, JPOOL_PERMANENT, SIZEOF(JHUFF_TBL));
tbl->sent_table = FALSE; /* make sure this is false in any new table */
return tbl;
}
| bsd-3-clause |
dayuoba/redis | deps/lua/src/lua_cmsgpack.c | 204 | 30285 | #include <math.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <assert.h>
#include "lua.h"
#include "lauxlib.h"
#define LUACMSGPACK_NAME "cmsgpack"
#define LUACMSGPACK_SAFE_NAME "cmsgpack_safe"
#define LUACMSGPACK_VERSION "lua-cmsgpack 0.4.0"
#define LUACMSGPACK_COPYRIGHT "Copyright (C) 2012, Salvatore Sanfilippo"
#define LUACMSGPACK_DESCRIPTION "MessagePack C implementation for Lua"
/* Allows a preprocessor directive to override MAX_NESTING */
#ifndef LUACMSGPACK_MAX_NESTING
#define LUACMSGPACK_MAX_NESTING 16 /* Max tables nesting. */
#endif
/* Check if float or double can be an integer without loss of precision */
#define IS_INT_TYPE_EQUIVALENT(x, T) (!isinf(x) && (T)(x) == (x))
#define IS_INT64_EQUIVALENT(x) IS_INT_TYPE_EQUIVALENT(x, int64_t)
#define IS_INT_EQUIVALENT(x) IS_INT_TYPE_EQUIVALENT(x, int)
/* If size of pointer is equal to a 4 byte integer, we're on 32 bits. */
#if UINTPTR_MAX == UINT_MAX
#define BITS_32 1
#else
#define BITS_32 0
#endif
#if BITS_32
#define lua_pushunsigned(L, n) lua_pushnumber(L, n)
#else
#define lua_pushunsigned(L, n) lua_pushinteger(L, n)
#endif
/* =============================================================================
* MessagePack implementation and bindings for Lua 5.1/5.2.
* Copyright(C) 2012 Salvatore Sanfilippo <antirez@gmail.com>
*
* http://github.com/antirez/lua-cmsgpack
*
* For MessagePack specification check the following web site:
* http://wiki.msgpack.org/display/MSGPACK/Format+specification
*
* See Copyright Notice at the end of this file.
*
* CHANGELOG:
* 19-Feb-2012 (ver 0.1.0): Initial release.
* 20-Feb-2012 (ver 0.2.0): Tables encoding improved.
* 20-Feb-2012 (ver 0.2.1): Minor bug fixing.
* 20-Feb-2012 (ver 0.3.0): Module renamed lua-cmsgpack (was lua-msgpack).
* 04-Apr-2014 (ver 0.3.1): Lua 5.2 support and minor bug fix.
* 07-Apr-2014 (ver 0.4.0): Multiple pack/unpack, lua allocator, efficiency.
* ========================================================================== */
/* -------------------------- Endian conversion --------------------------------
* We use it only for floats and doubles, all the other conversions performed
* in an endian independent fashion. So the only thing we need is a function
* that swaps a binary string if arch is little endian (and left it untouched
* otherwise). */
/* Reverse memory bytes if arch is little endian. Given the conceptual
* simplicity of the Lua build system we prefer check for endianess at runtime.
* The performance difference should be acceptable. */
void memrevifle(void *ptr, size_t len) {
unsigned char *p = (unsigned char *)ptr,
*e = (unsigned char *)p+len-1,
aux;
int test = 1;
unsigned char *testp = (unsigned char*) &test;
if (testp[0] == 0) return; /* Big endian, nothing to do. */
len /= 2;
while(len--) {
aux = *p;
*p = *e;
*e = aux;
p++;
e--;
}
}
/* ---------------------------- String buffer ----------------------------------
* This is a simple implementation of string buffers. The only operation
* supported is creating empty buffers and appending bytes to it.
* The string buffer uses 2x preallocation on every realloc for O(N) append
* behavior. */
typedef struct mp_buf {
lua_State *L;
unsigned char *b;
size_t len, free;
} mp_buf;
void *mp_realloc(lua_State *L, void *target, size_t osize,size_t nsize) {
void *(*local_realloc) (void *, void *, size_t osize, size_t nsize) = NULL;
void *ud;
local_realloc = lua_getallocf(L, &ud);
return local_realloc(ud, target, osize, nsize);
}
mp_buf *mp_buf_new(lua_State *L) {
mp_buf *buf = NULL;
/* Old size = 0; new size = sizeof(*buf) */
buf = (mp_buf*)mp_realloc(L, NULL, 0, sizeof(*buf));
buf->L = L;
buf->b = NULL;
buf->len = buf->free = 0;
return buf;
}
void mp_buf_append(mp_buf *buf, const unsigned char *s, size_t len) {
if (buf->free < len) {
size_t newlen = buf->len+len;
buf->b = (unsigned char*)mp_realloc(buf->L, buf->b, buf->len, newlen*2);
buf->free = newlen;
}
memcpy(buf->b+buf->len,s,len);
buf->len += len;
buf->free -= len;
}
void mp_buf_free(mp_buf *buf) {
mp_realloc(buf->L, buf->b, buf->len, 0); /* realloc to 0 = free */
mp_realloc(buf->L, buf, sizeof(*buf), 0);
}
/* ---------------------------- String cursor ----------------------------------
* This simple data structure is used for parsing. Basically you create a cursor
* using a string pointer and a length, then it is possible to access the
* current string position with cursor->p, check the remaining length
* in cursor->left, and finally consume more string using
* mp_cur_consume(cursor,len), to advance 'p' and subtract 'left'.
* An additional field cursor->error is set to zero on initialization and can
* be used to report errors. */
#define MP_CUR_ERROR_NONE 0
#define MP_CUR_ERROR_EOF 1 /* Not enough data to complete operation. */
#define MP_CUR_ERROR_BADFMT 2 /* Bad data format */
typedef struct mp_cur {
const unsigned char *p;
size_t left;
int err;
} mp_cur;
void mp_cur_init(mp_cur *cursor, const unsigned char *s, size_t len) {
cursor->p = s;
cursor->left = len;
cursor->err = MP_CUR_ERROR_NONE;
}
#define mp_cur_consume(_c,_len) do { _c->p += _len; _c->left -= _len; } while(0)
/* When there is not enough room we set an error in the cursor and return. This
* is very common across the code so we have a macro to make the code look
* a bit simpler. */
#define mp_cur_need(_c,_len) do { \
if (_c->left < _len) { \
_c->err = MP_CUR_ERROR_EOF; \
return; \
} \
} while(0)
/* ------------------------- Low level MP encoding -------------------------- */
void mp_encode_bytes(mp_buf *buf, const unsigned char *s, size_t len) {
unsigned char hdr[5];
int hdrlen;
if (len < 32) {
hdr[0] = 0xa0 | (len&0xff); /* fix raw */
hdrlen = 1;
} else if (len <= 0xff) {
hdr[0] = 0xd9;
hdr[1] = len;
hdrlen = 2;
} else if (len <= 0xffff) {
hdr[0] = 0xda;
hdr[1] = (len&0xff00)>>8;
hdr[2] = len&0xff;
hdrlen = 3;
} else {
hdr[0] = 0xdb;
hdr[1] = (len&0xff000000)>>24;
hdr[2] = (len&0xff0000)>>16;
hdr[3] = (len&0xff00)>>8;
hdr[4] = len&0xff;
hdrlen = 5;
}
mp_buf_append(buf,hdr,hdrlen);
mp_buf_append(buf,s,len);
}
/* we assume IEEE 754 internal format for single and double precision floats. */
void mp_encode_double(mp_buf *buf, double d) {
unsigned char b[9];
float f = d;
assert(sizeof(f) == 4 && sizeof(d) == 8);
if (d == (double)f) {
b[0] = 0xca; /* float IEEE 754 */
memcpy(b+1,&f,4);
memrevifle(b+1,4);
mp_buf_append(buf,b,5);
} else if (sizeof(d) == 8) {
b[0] = 0xcb; /* double IEEE 754 */
memcpy(b+1,&d,8);
memrevifle(b+1,8);
mp_buf_append(buf,b,9);
}
}
void mp_encode_int(mp_buf *buf, int64_t n) {
unsigned char b[9];
int enclen;
if (n >= 0) {
if (n <= 127) {
b[0] = n & 0x7f; /* positive fixnum */
enclen = 1;
} else if (n <= 0xff) {
b[0] = 0xcc; /* uint 8 */
b[1] = n & 0xff;
enclen = 2;
} else if (n <= 0xffff) {
b[0] = 0xcd; /* uint 16 */
b[1] = (n & 0xff00) >> 8;
b[2] = n & 0xff;
enclen = 3;
} else if (n <= 0xffffffffLL) {
b[0] = 0xce; /* uint 32 */
b[1] = (n & 0xff000000) >> 24;
b[2] = (n & 0xff0000) >> 16;
b[3] = (n & 0xff00) >> 8;
b[4] = n & 0xff;
enclen = 5;
} else {
b[0] = 0xcf; /* uint 64 */
b[1] = (n & 0xff00000000000000LL) >> 56;
b[2] = (n & 0xff000000000000LL) >> 48;
b[3] = (n & 0xff0000000000LL) >> 40;
b[4] = (n & 0xff00000000LL) >> 32;
b[5] = (n & 0xff000000) >> 24;
b[6] = (n & 0xff0000) >> 16;
b[7] = (n & 0xff00) >> 8;
b[8] = n & 0xff;
enclen = 9;
}
} else {
if (n >= -32) {
b[0] = ((signed char)n); /* negative fixnum */
enclen = 1;
} else if (n >= -128) {
b[0] = 0xd0; /* int 8 */
b[1] = n & 0xff;
enclen = 2;
} else if (n >= -32768) {
b[0] = 0xd1; /* int 16 */
b[1] = (n & 0xff00) >> 8;
b[2] = n & 0xff;
enclen = 3;
} else if (n >= -2147483648LL) {
b[0] = 0xd2; /* int 32 */
b[1] = (n & 0xff000000) >> 24;
b[2] = (n & 0xff0000) >> 16;
b[3] = (n & 0xff00) >> 8;
b[4] = n & 0xff;
enclen = 5;
} else {
b[0] = 0xd3; /* int 64 */
b[1] = (n & 0xff00000000000000LL) >> 56;
b[2] = (n & 0xff000000000000LL) >> 48;
b[3] = (n & 0xff0000000000LL) >> 40;
b[4] = (n & 0xff00000000LL) >> 32;
b[5] = (n & 0xff000000) >> 24;
b[6] = (n & 0xff0000) >> 16;
b[7] = (n & 0xff00) >> 8;
b[8] = n & 0xff;
enclen = 9;
}
}
mp_buf_append(buf,b,enclen);
}
void mp_encode_array(mp_buf *buf, int64_t n) {
unsigned char b[5];
int enclen;
if (n <= 15) {
b[0] = 0x90 | (n & 0xf); /* fix array */
enclen = 1;
} else if (n <= 65535) {
b[0] = 0xdc; /* array 16 */
b[1] = (n & 0xff00) >> 8;
b[2] = n & 0xff;
enclen = 3;
} else {
b[0] = 0xdd; /* array 32 */
b[1] = (n & 0xff000000) >> 24;
b[2] = (n & 0xff0000) >> 16;
b[3] = (n & 0xff00) >> 8;
b[4] = n & 0xff;
enclen = 5;
}
mp_buf_append(buf,b,enclen);
}
void mp_encode_map(mp_buf *buf, int64_t n) {
unsigned char b[5];
int enclen;
if (n <= 15) {
b[0] = 0x80 | (n & 0xf); /* fix map */
enclen = 1;
} else if (n <= 65535) {
b[0] = 0xde; /* map 16 */
b[1] = (n & 0xff00) >> 8;
b[2] = n & 0xff;
enclen = 3;
} else {
b[0] = 0xdf; /* map 32 */
b[1] = (n & 0xff000000) >> 24;
b[2] = (n & 0xff0000) >> 16;
b[3] = (n & 0xff00) >> 8;
b[4] = n & 0xff;
enclen = 5;
}
mp_buf_append(buf,b,enclen);
}
/* --------------------------- Lua types encoding --------------------------- */
void mp_encode_lua_string(lua_State *L, mp_buf *buf) {
size_t len;
const char *s;
s = lua_tolstring(L,-1,&len);
mp_encode_bytes(buf,(const unsigned char*)s,len);
}
void mp_encode_lua_bool(lua_State *L, mp_buf *buf) {
unsigned char b = lua_toboolean(L,-1) ? 0xc3 : 0xc2;
mp_buf_append(buf,&b,1);
}
/* Lua 5.3 has a built in 64-bit integer type */
void mp_encode_lua_integer(lua_State *L, mp_buf *buf) {
#if (LUA_VERSION_NUM < 503) && BITS_32
lua_Number i = lua_tonumber(L,-1);
#else
lua_Integer i = lua_tointeger(L,-1);
#endif
mp_encode_int(buf, (int64_t)i);
}
/* Lua 5.2 and lower only has 64-bit doubles, so we need to
* detect if the double may be representable as an int
* for Lua < 5.3 */
void mp_encode_lua_number(lua_State *L, mp_buf *buf) {
lua_Number n = lua_tonumber(L,-1);
if (IS_INT64_EQUIVALENT(n)) {
mp_encode_lua_integer(L, buf);
} else {
mp_encode_double(buf,(double)n);
}
}
void mp_encode_lua_type(lua_State *L, mp_buf *buf, int level);
/* Convert a lua table into a message pack list. */
void mp_encode_lua_table_as_array(lua_State *L, mp_buf *buf, int level) {
#if LUA_VERSION_NUM < 502
size_t len = lua_objlen(L,-1), j;
#else
size_t len = lua_rawlen(L,-1), j;
#endif
mp_encode_array(buf,len);
for (j = 1; j <= len; j++) {
lua_pushnumber(L,j);
lua_gettable(L,-2);
mp_encode_lua_type(L,buf,level+1);
}
}
/* Convert a lua table into a message pack key-value map. */
void mp_encode_lua_table_as_map(lua_State *L, mp_buf *buf, int level) {
size_t len = 0;
/* First step: count keys into table. No other way to do it with the
* Lua API, we need to iterate a first time. Note that an alternative
* would be to do a single run, and then hack the buffer to insert the
* map opcodes for message pack. Too hackish for this lib. */
lua_pushnil(L);
while(lua_next(L,-2)) {
lua_pop(L,1); /* remove value, keep key for next iteration. */
len++;
}
/* Step two: actually encoding of the map. */
mp_encode_map(buf,len);
lua_pushnil(L);
while(lua_next(L,-2)) {
/* Stack: ... key value */
lua_pushvalue(L,-2); /* Stack: ... key value key */
mp_encode_lua_type(L,buf,level+1); /* encode key */
mp_encode_lua_type(L,buf,level+1); /* encode val */
}
}
/* Returns true if the Lua table on top of the stack is exclusively composed
* of keys from numerical keys from 1 up to N, with N being the total number
* of elements, without any hole in the middle. */
int table_is_an_array(lua_State *L) {
int count = 0, max = 0;
#if LUA_VERSION_NUM < 503
lua_Number n;
#else
lua_Integer n;
#endif
/* Stack top on function entry */
int stacktop;
stacktop = lua_gettop(L);
lua_pushnil(L);
while(lua_next(L,-2)) {
/* Stack: ... key value */
lua_pop(L,1); /* Stack: ... key */
/* The <= 0 check is valid here because we're comparing indexes. */
#if LUA_VERSION_NUM < 503
if ((LUA_TNUMBER != lua_type(L,-1)) || (n = lua_tonumber(L, -1)) <= 0 ||
!IS_INT_EQUIVALENT(n))
#else
if (!lua_isinteger(L,-1) || (n = lua_tointeger(L, -1)) <= 0)
#endif
{
lua_settop(L, stacktop);
return 0;
}
max = (n > max ? n : max);
count++;
}
/* We have the total number of elements in "count". Also we have
* the max index encountered in "max". We can't reach this code
* if there are indexes <= 0. If you also note that there can not be
* repeated keys into a table, you have that if max==count you are sure
* that there are all the keys form 1 to count (both included). */
lua_settop(L, stacktop);
return max == count;
}
/* If the length operator returns non-zero, that is, there is at least
* an object at key '1', we serialize to message pack list. Otherwise
* we use a map. */
void mp_encode_lua_table(lua_State *L, mp_buf *buf, int level) {
if (table_is_an_array(L))
mp_encode_lua_table_as_array(L,buf,level);
else
mp_encode_lua_table_as_map(L,buf,level);
}
void mp_encode_lua_null(lua_State *L, mp_buf *buf) {
unsigned char b[1];
(void)L;
b[0] = 0xc0;
mp_buf_append(buf,b,1);
}
void mp_encode_lua_type(lua_State *L, mp_buf *buf, int level) {
int t = lua_type(L,-1);
/* Limit the encoding of nested tables to a specified maximum depth, so that
* we survive when called against circular references in tables. */
if (t == LUA_TTABLE && level == LUACMSGPACK_MAX_NESTING) t = LUA_TNIL;
switch(t) {
case LUA_TSTRING: mp_encode_lua_string(L,buf); break;
case LUA_TBOOLEAN: mp_encode_lua_bool(L,buf); break;
case LUA_TNUMBER:
#if LUA_VERSION_NUM < 503
mp_encode_lua_number(L,buf); break;
#else
if (lua_isinteger(L, -1)) {
mp_encode_lua_integer(L, buf);
} else {
mp_encode_lua_number(L, buf);
}
break;
#endif
case LUA_TTABLE: mp_encode_lua_table(L,buf,level); break;
default: mp_encode_lua_null(L,buf); break;
}
lua_pop(L,1);
}
/*
* Packs all arguments as a stream for multiple upacking later.
* Returns error if no arguments provided.
*/
int mp_pack(lua_State *L) {
int nargs = lua_gettop(L);
int i;
mp_buf *buf;
if (nargs == 0)
return luaL_argerror(L, 0, "MessagePack pack needs input.");
buf = mp_buf_new(L);
for(i = 1; i <= nargs; i++) {
/* Copy argument i to top of stack for _encode processing;
* the encode function pops it from the stack when complete. */
lua_pushvalue(L, i);
mp_encode_lua_type(L,buf,0);
lua_pushlstring(L,(char*)buf->b,buf->len);
/* Reuse the buffer for the next operation by
* setting its free count to the total buffer size
* and the current position to zero. */
buf->free += buf->len;
buf->len = 0;
}
mp_buf_free(buf);
/* Concatenate all nargs buffers together */
lua_concat(L, nargs);
return 1;
}
/* ------------------------------- Decoding --------------------------------- */
void mp_decode_to_lua_type(lua_State *L, mp_cur *c);
void mp_decode_to_lua_array(lua_State *L, mp_cur *c, size_t len) {
assert(len <= UINT_MAX);
int index = 1;
lua_newtable(L);
while(len--) {
lua_pushnumber(L,index++);
mp_decode_to_lua_type(L,c);
if (c->err) return;
lua_settable(L,-3);
}
}
void mp_decode_to_lua_hash(lua_State *L, mp_cur *c, size_t len) {
assert(len <= UINT_MAX);
lua_newtable(L);
while(len--) {
mp_decode_to_lua_type(L,c); /* key */
if (c->err) return;
mp_decode_to_lua_type(L,c); /* value */
if (c->err) return;
lua_settable(L,-3);
}
}
/* Decode a Message Pack raw object pointed by the string cursor 'c' to
* a Lua type, that is left as the only result on the stack. */
void mp_decode_to_lua_type(lua_State *L, mp_cur *c) {
mp_cur_need(c,1);
/* If we return more than 18 elements, we must resize the stack to
* fit all our return values. But, there is no way to
* determine how many objects a msgpack will unpack to up front, so
* we request a +1 larger stack on each iteration (noop if stack is
* big enough, and when stack does require resize it doubles in size) */
luaL_checkstack(L, 1,
"too many return values at once; "
"use unpack_one or unpack_limit instead.");
switch(c->p[0]) {
case 0xcc: /* uint 8 */
mp_cur_need(c,2);
lua_pushunsigned(L,c->p[1]);
mp_cur_consume(c,2);
break;
case 0xd0: /* int 8 */
mp_cur_need(c,2);
lua_pushinteger(L,(signed char)c->p[1]);
mp_cur_consume(c,2);
break;
case 0xcd: /* uint 16 */
mp_cur_need(c,3);
lua_pushunsigned(L,
(c->p[1] << 8) |
c->p[2]);
mp_cur_consume(c,3);
break;
case 0xd1: /* int 16 */
mp_cur_need(c,3);
lua_pushinteger(L,(int16_t)
(c->p[1] << 8) |
c->p[2]);
mp_cur_consume(c,3);
break;
case 0xce: /* uint 32 */
mp_cur_need(c,5);
lua_pushunsigned(L,
((uint32_t)c->p[1] << 24) |
((uint32_t)c->p[2] << 16) |
((uint32_t)c->p[3] << 8) |
(uint32_t)c->p[4]);
mp_cur_consume(c,5);
break;
case 0xd2: /* int 32 */
mp_cur_need(c,5);
lua_pushinteger(L,
((int32_t)c->p[1] << 24) |
((int32_t)c->p[2] << 16) |
((int32_t)c->p[3] << 8) |
(int32_t)c->p[4]);
mp_cur_consume(c,5);
break;
case 0xcf: /* uint 64 */
mp_cur_need(c,9);
lua_pushunsigned(L,
((uint64_t)c->p[1] << 56) |
((uint64_t)c->p[2] << 48) |
((uint64_t)c->p[3] << 40) |
((uint64_t)c->p[4] << 32) |
((uint64_t)c->p[5] << 24) |
((uint64_t)c->p[6] << 16) |
((uint64_t)c->p[7] << 8) |
(uint64_t)c->p[8]);
mp_cur_consume(c,9);
break;
case 0xd3: /* int 64 */
mp_cur_need(c,9);
#if LUA_VERSION_NUM < 503
lua_pushnumber(L,
#else
lua_pushinteger(L,
#endif
((int64_t)c->p[1] << 56) |
((int64_t)c->p[2] << 48) |
((int64_t)c->p[3] << 40) |
((int64_t)c->p[4] << 32) |
((int64_t)c->p[5] << 24) |
((int64_t)c->p[6] << 16) |
((int64_t)c->p[7] << 8) |
(int64_t)c->p[8]);
mp_cur_consume(c,9);
break;
case 0xc0: /* nil */
lua_pushnil(L);
mp_cur_consume(c,1);
break;
case 0xc3: /* true */
lua_pushboolean(L,1);
mp_cur_consume(c,1);
break;
case 0xc2: /* false */
lua_pushboolean(L,0);
mp_cur_consume(c,1);
break;
case 0xca: /* float */
mp_cur_need(c,5);
assert(sizeof(float) == 4);
{
float f;
memcpy(&f,c->p+1,4);
memrevifle(&f,4);
lua_pushnumber(L,f);
mp_cur_consume(c,5);
}
break;
case 0xcb: /* double */
mp_cur_need(c,9);
assert(sizeof(double) == 8);
{
double d;
memcpy(&d,c->p+1,8);
memrevifle(&d,8);
lua_pushnumber(L,d);
mp_cur_consume(c,9);
}
break;
case 0xd9: /* raw 8 */
mp_cur_need(c,2);
{
size_t l = c->p[1];
mp_cur_need(c,2+l);
lua_pushlstring(L,(char*)c->p+2,l);
mp_cur_consume(c,2+l);
}
break;
case 0xda: /* raw 16 */
mp_cur_need(c,3);
{
size_t l = (c->p[1] << 8) | c->p[2];
mp_cur_need(c,3+l);
lua_pushlstring(L,(char*)c->p+3,l);
mp_cur_consume(c,3+l);
}
break;
case 0xdb: /* raw 32 */
mp_cur_need(c,5);
{
size_t l = ((size_t)c->p[1] << 24) |
((size_t)c->p[2] << 16) |
((size_t)c->p[3] << 8) |
(size_t)c->p[4];
mp_cur_consume(c,5);
mp_cur_need(c,l);
lua_pushlstring(L,(char*)c->p,l);
mp_cur_consume(c,l);
}
break;
case 0xdc: /* array 16 */
mp_cur_need(c,3);
{
size_t l = (c->p[1] << 8) | c->p[2];
mp_cur_consume(c,3);
mp_decode_to_lua_array(L,c,l);
}
break;
case 0xdd: /* array 32 */
mp_cur_need(c,5);
{
size_t l = ((size_t)c->p[1] << 24) |
((size_t)c->p[2] << 16) |
((size_t)c->p[3] << 8) |
(size_t)c->p[4];
mp_cur_consume(c,5);
mp_decode_to_lua_array(L,c,l);
}
break;
case 0xde: /* map 16 */
mp_cur_need(c,3);
{
size_t l = (c->p[1] << 8) | c->p[2];
mp_cur_consume(c,3);
mp_decode_to_lua_hash(L,c,l);
}
break;
case 0xdf: /* map 32 */
mp_cur_need(c,5);
{
size_t l = ((size_t)c->p[1] << 24) |
((size_t)c->p[2] << 16) |
((size_t)c->p[3] << 8) |
(size_t)c->p[4];
mp_cur_consume(c,5);
mp_decode_to_lua_hash(L,c,l);
}
break;
default: /* types that can't be idenitified by first byte value. */
if ((c->p[0] & 0x80) == 0) { /* positive fixnum */
lua_pushunsigned(L,c->p[0]);
mp_cur_consume(c,1);
} else if ((c->p[0] & 0xe0) == 0xe0) { /* negative fixnum */
lua_pushinteger(L,(signed char)c->p[0]);
mp_cur_consume(c,1);
} else if ((c->p[0] & 0xe0) == 0xa0) { /* fix raw */
size_t l = c->p[0] & 0x1f;
mp_cur_need(c,1+l);
lua_pushlstring(L,(char*)c->p+1,l);
mp_cur_consume(c,1+l);
} else if ((c->p[0] & 0xf0) == 0x90) { /* fix map */
size_t l = c->p[0] & 0xf;
mp_cur_consume(c,1);
mp_decode_to_lua_array(L,c,l);
} else if ((c->p[0] & 0xf0) == 0x80) { /* fix map */
size_t l = c->p[0] & 0xf;
mp_cur_consume(c,1);
mp_decode_to_lua_hash(L,c,l);
} else {
c->err = MP_CUR_ERROR_BADFMT;
}
}
}
int mp_unpack_full(lua_State *L, int limit, int offset) {
size_t len;
const char *s;
mp_cur c;
int cnt; /* Number of objects unpacked */
int decode_all = (!limit && !offset);
s = luaL_checklstring(L,1,&len); /* if no match, exits */
if (offset < 0 || limit < 0) /* requesting negative off or lim is invalid */
return luaL_error(L,
"Invalid request to unpack with offset of %d and limit of %d.",
offset, len);
else if (offset > len)
return luaL_error(L,
"Start offset %d greater than input length %d.", offset, len);
if (decode_all) limit = INT_MAX;
mp_cur_init(&c,(const unsigned char *)s+offset,len-offset);
/* We loop over the decode because this could be a stream
* of multiple top-level values serialized together */
for(cnt = 0; c.left > 0 && cnt < limit; cnt++) {
mp_decode_to_lua_type(L,&c);
if (c.err == MP_CUR_ERROR_EOF) {
return luaL_error(L,"Missing bytes in input.");
} else if (c.err == MP_CUR_ERROR_BADFMT) {
return luaL_error(L,"Bad data format in input.");
}
}
if (!decode_all) {
/* c->left is the remaining size of the input buffer.
* subtract the entire buffer size from the unprocessed size
* to get our next start offset */
int offset = len - c.left;
/* Return offset -1 when we have have processed the entire buffer. */
lua_pushinteger(L, c.left == 0 ? -1 : offset);
/* Results are returned with the arg elements still
* in place. Lua takes care of only returning
* elements above the args for us.
* In this case, we have one arg on the stack
* for this function, so we insert our first return
* value at position 2. */
lua_insert(L, 2);
cnt += 1; /* increase return count by one to make room for offset */
}
return cnt;
}
int mp_unpack(lua_State *L) {
return mp_unpack_full(L, 0, 0);
}
int mp_unpack_one(lua_State *L) {
int offset = luaL_optinteger(L, 2, 0);
/* Variable pop because offset may not exist */
lua_pop(L, lua_gettop(L)-1);
return mp_unpack_full(L, 1, offset);
}
int mp_unpack_limit(lua_State *L) {
int limit = luaL_checkinteger(L, 2);
int offset = luaL_optinteger(L, 3, 0);
/* Variable pop because offset may not exist */
lua_pop(L, lua_gettop(L)-1);
return mp_unpack_full(L, limit, offset);
}
int mp_safe(lua_State *L) {
int argc, err, total_results;
argc = lua_gettop(L);
/* This adds our function to the bottom of the stack
* (the "call this function" position) */
lua_pushvalue(L, lua_upvalueindex(1));
lua_insert(L, 1);
err = lua_pcall(L, argc, LUA_MULTRET, 0);
total_results = lua_gettop(L);
if (!err) {
return total_results;
} else {
lua_pushnil(L);
lua_insert(L,-2);
return 2;
}
}
/* -------------------------------------------------------------------------- */
const struct luaL_Reg cmds[] = {
{"pack", mp_pack},
{"unpack", mp_unpack},
{"unpack_one", mp_unpack_one},
{"unpack_limit", mp_unpack_limit},
{0}
};
int luaopen_create(lua_State *L) {
int i;
/* Manually construct our module table instead of
* relying on _register or _newlib */
lua_newtable(L);
for (i = 0; i < (sizeof(cmds)/sizeof(*cmds) - 1); i++) {
lua_pushcfunction(L, cmds[i].func);
lua_setfield(L, -2, cmds[i].name);
}
/* Add metadata */
lua_pushliteral(L, LUACMSGPACK_NAME);
lua_setfield(L, -2, "_NAME");
lua_pushliteral(L, LUACMSGPACK_VERSION);
lua_setfield(L, -2, "_VERSION");
lua_pushliteral(L, LUACMSGPACK_COPYRIGHT);
lua_setfield(L, -2, "_COPYRIGHT");
lua_pushliteral(L, LUACMSGPACK_DESCRIPTION);
lua_setfield(L, -2, "_DESCRIPTION");
return 1;
}
LUALIB_API int luaopen_cmsgpack(lua_State *L) {
luaopen_create(L);
#if LUA_VERSION_NUM < 502
/* Register name globally for 5.1 */
lua_pushvalue(L, -1);
lua_setglobal(L, LUACMSGPACK_NAME);
#endif
return 1;
}
LUALIB_API int luaopen_cmsgpack_safe(lua_State *L) {
int i;
luaopen_cmsgpack(L);
/* Wrap all functions in the safe handler */
for (i = 0; i < (sizeof(cmds)/sizeof(*cmds) - 1); i++) {
lua_getfield(L, -1, cmds[i].name);
lua_pushcclosure(L, mp_safe, 1);
lua_setfield(L, -2, cmds[i].name);
}
#if LUA_VERSION_NUM < 502
/* Register name globally for 5.1 */
lua_pushvalue(L, -1);
lua_setglobal(L, LUACMSGPACK_SAFE_NAME);
#endif
return 1;
}
/******************************************************************************
* Copyright (C) 2012 Salvatore Sanfilippo. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
******************************************************************************/
| bsd-3-clause |
pythonvietnam/scikit-learn | sklearn/metrics/pairwise_fast.c | 252 | 927355 | /* Generated by Cython 0.20.1 on Mon Mar 10 14:28:31 2014 */
#define PY_SSIZE_T_CLEAN
#ifndef CYTHON_USE_PYLONG_INTERNALS
#ifdef PYLONG_BITS_IN_DIGIT
#define CYTHON_USE_PYLONG_INTERNALS 0
#else
#include "pyconfig.h"
#ifdef PYLONG_BITS_IN_DIGIT
#define CYTHON_USE_PYLONG_INTERNALS 1
#else
#define CYTHON_USE_PYLONG_INTERNALS 0
#endif
#endif
#endif
#include "Python.h"
#ifndef Py_PYTHON_H
#error Python headers needed to compile C extensions, please install development version of Python.
#elif PY_VERSION_HEX < 0x02040000
#error Cython requires Python 2.4+.
#else
#define CYTHON_ABI "0_20_1"
#include <stddef.h> /* For offsetof */
#ifndef offsetof
#define offsetof(type, member) ( (size_t) & ((type*)0) -> member )
#endif
#if !defined(WIN32) && !defined(MS_WINDOWS)
#ifndef __stdcall
#define __stdcall
#endif
#ifndef __cdecl
#define __cdecl
#endif
#ifndef __fastcall
#define __fastcall
#endif
#endif
#ifndef DL_IMPORT
#define DL_IMPORT(t) t
#endif
#ifndef DL_EXPORT
#define DL_EXPORT(t) t
#endif
#ifndef PY_LONG_LONG
#define PY_LONG_LONG LONG_LONG
#endif
#ifndef Py_HUGE_VAL
#define Py_HUGE_VAL HUGE_VAL
#endif
#ifdef PYPY_VERSION
#define CYTHON_COMPILING_IN_PYPY 1
#define CYTHON_COMPILING_IN_CPYTHON 0
#else
#define CYTHON_COMPILING_IN_PYPY 0
#define CYTHON_COMPILING_IN_CPYTHON 1
#endif
#if CYTHON_COMPILING_IN_PYPY
#define Py_OptimizeFlag 0
#endif
#if PY_VERSION_HEX < 0x02050000
typedef int Py_ssize_t;
#define PY_SSIZE_T_MAX INT_MAX
#define PY_SSIZE_T_MIN INT_MIN
#define PY_FORMAT_SIZE_T ""
#define CYTHON_FORMAT_SSIZE_T ""
#define PyInt_FromSsize_t(z) PyInt_FromLong(z)
#define PyInt_AsSsize_t(o) __Pyx_PyInt_As_int(o)
#define PyNumber_Index(o) ((PyNumber_Check(o) && !PyFloat_Check(o)) ? PyNumber_Int(o) : \
(PyErr_Format(PyExc_TypeError, \
"expected index value, got %.200s", Py_TYPE(o)->tp_name), \
(PyObject*)0))
#define __Pyx_PyIndex_Check(o) (PyNumber_Check(o) && !PyFloat_Check(o) && \
!PyComplex_Check(o))
#define PyIndex_Check __Pyx_PyIndex_Check
#define PyErr_WarnEx(category, message, stacklevel) PyErr_Warn(category, message)
#define __PYX_BUILD_PY_SSIZE_T "i"
#else
#define __PYX_BUILD_PY_SSIZE_T "n"
#define CYTHON_FORMAT_SSIZE_T "z"
#define __Pyx_PyIndex_Check PyIndex_Check
#endif
#if PY_VERSION_HEX < 0x02060000
#define Py_REFCNT(ob) (((PyObject*)(ob))->ob_refcnt)
#define Py_TYPE(ob) (((PyObject*)(ob))->ob_type)
#define Py_SIZE(ob) (((PyVarObject*)(ob))->ob_size)
#define PyVarObject_HEAD_INIT(type, size) \
PyObject_HEAD_INIT(type) size,
#define PyType_Modified(t)
typedef struct {
void *buf;
PyObject *obj;
Py_ssize_t len;
Py_ssize_t itemsize;
int readonly;
int ndim;
char *format;
Py_ssize_t *shape;
Py_ssize_t *strides;
Py_ssize_t *suboffsets;
void *internal;
} Py_buffer;
#define PyBUF_SIMPLE 0
#define PyBUF_WRITABLE 0x0001
#define PyBUF_FORMAT 0x0004
#define PyBUF_ND 0x0008
#define PyBUF_STRIDES (0x0010 | PyBUF_ND)
#define PyBUF_C_CONTIGUOUS (0x0020 | PyBUF_STRIDES)
#define PyBUF_F_CONTIGUOUS (0x0040 | PyBUF_STRIDES)
#define PyBUF_ANY_CONTIGUOUS (0x0080 | PyBUF_STRIDES)
#define PyBUF_INDIRECT (0x0100 | PyBUF_STRIDES)
#define PyBUF_RECORDS (PyBUF_STRIDES | PyBUF_FORMAT | PyBUF_WRITABLE)
#define PyBUF_FULL (PyBUF_INDIRECT | PyBUF_FORMAT | PyBUF_WRITABLE)
typedef int (*getbufferproc)(PyObject *, Py_buffer *, int);
typedef void (*releasebufferproc)(PyObject *, Py_buffer *);
#endif
#if PY_MAJOR_VERSION < 3
#define __Pyx_BUILTIN_MODULE_NAME "__builtin__"
#define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) \
PyCode_New(a+k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)
#define __Pyx_DefaultClassType PyClass_Type
#else
#define __Pyx_BUILTIN_MODULE_NAME "builtins"
#define __Pyx_PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos) \
PyCode_New(a, k, l, s, f, code, c, n, v, fv, cell, fn, name, fline, lnos)
#define __Pyx_DefaultClassType PyType_Type
#endif
#if PY_VERSION_HEX < 0x02060000
#define PyUnicode_FromString(s) PyUnicode_Decode(s, strlen(s), "UTF-8", "strict")
#endif
#if PY_MAJOR_VERSION >= 3
#define Py_TPFLAGS_CHECKTYPES 0
#define Py_TPFLAGS_HAVE_INDEX 0
#endif
#if (PY_VERSION_HEX < 0x02060000) || (PY_MAJOR_VERSION >= 3)
#define Py_TPFLAGS_HAVE_NEWBUFFER 0
#endif
#if PY_VERSION_HEX < 0x02060000
#define Py_TPFLAGS_HAVE_VERSION_TAG 0
#endif
#if PY_VERSION_HEX < 0x02060000 && !defined(Py_TPFLAGS_IS_ABSTRACT)
#define Py_TPFLAGS_IS_ABSTRACT 0
#endif
#if PY_VERSION_HEX < 0x030400a1 && !defined(Py_TPFLAGS_HAVE_FINALIZE)
#define Py_TPFLAGS_HAVE_FINALIZE 0
#endif
#if PY_VERSION_HEX > 0x03030000 && defined(PyUnicode_KIND)
#define CYTHON_PEP393_ENABLED 1
#define __Pyx_PyUnicode_READY(op) (likely(PyUnicode_IS_READY(op)) ? \
0 : _PyUnicode_Ready((PyObject *)(op)))
#define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_LENGTH(u)
#define __Pyx_PyUnicode_READ_CHAR(u, i) PyUnicode_READ_CHAR(u, i)
#define __Pyx_PyUnicode_KIND(u) PyUnicode_KIND(u)
#define __Pyx_PyUnicode_DATA(u) PyUnicode_DATA(u)
#define __Pyx_PyUnicode_READ(k, d, i) PyUnicode_READ(k, d, i)
#else
#define CYTHON_PEP393_ENABLED 0
#define __Pyx_PyUnicode_READY(op) (0)
#define __Pyx_PyUnicode_GET_LENGTH(u) PyUnicode_GET_SIZE(u)
#define __Pyx_PyUnicode_READ_CHAR(u, i) ((Py_UCS4)(PyUnicode_AS_UNICODE(u)[i]))
#define __Pyx_PyUnicode_KIND(u) (sizeof(Py_UNICODE))
#define __Pyx_PyUnicode_DATA(u) ((void*)PyUnicode_AS_UNICODE(u))
#define __Pyx_PyUnicode_READ(k, d, i) ((void)(k), (Py_UCS4)(((Py_UNICODE*)d)[i]))
#endif
#if CYTHON_COMPILING_IN_PYPY
#define __Pyx_PyUnicode_Concat(a, b) PyNumber_Add(a, b)
#define __Pyx_PyUnicode_ConcatSafe(a, b) PyNumber_Add(a, b)
#else
#define __Pyx_PyUnicode_Concat(a, b) PyUnicode_Concat(a, b)
#define __Pyx_PyUnicode_ConcatSafe(a, b) ((unlikely((a) == Py_None) || unlikely((b) == Py_None)) ? \
PyNumber_Add(a, b) : __Pyx_PyUnicode_Concat(a, b))
#endif
#define __Pyx_PyString_FormatSafe(a, b) ((unlikely((a) == Py_None)) ? PyNumber_Remainder(a, b) : __Pyx_PyString_Format(a, b))
#define __Pyx_PyUnicode_FormatSafe(a, b) ((unlikely((a) == Py_None)) ? PyNumber_Remainder(a, b) : PyUnicode_Format(a, b))
#if PY_MAJOR_VERSION >= 3
#define __Pyx_PyString_Format(a, b) PyUnicode_Format(a, b)
#else
#define __Pyx_PyString_Format(a, b) PyString_Format(a, b)
#endif
#if PY_MAJOR_VERSION >= 3
#define PyBaseString_Type PyUnicode_Type
#define PyStringObject PyUnicodeObject
#define PyString_Type PyUnicode_Type
#define PyString_Check PyUnicode_Check
#define PyString_CheckExact PyUnicode_CheckExact
#endif
#if PY_VERSION_HEX < 0x02060000
#define PyBytesObject PyStringObject
#define PyBytes_Type PyString_Type
#define PyBytes_Check PyString_Check
#define PyBytes_CheckExact PyString_CheckExact
#define PyBytes_FromString PyString_FromString
#define PyBytes_FromStringAndSize PyString_FromStringAndSize
#define PyBytes_FromFormat PyString_FromFormat
#define PyBytes_DecodeEscape PyString_DecodeEscape
#define PyBytes_AsString PyString_AsString
#define PyBytes_AsStringAndSize PyString_AsStringAndSize
#define PyBytes_Size PyString_Size
#define PyBytes_AS_STRING PyString_AS_STRING
#define PyBytes_GET_SIZE PyString_GET_SIZE
#define PyBytes_Repr PyString_Repr
#define PyBytes_Concat PyString_Concat
#define PyBytes_ConcatAndDel PyString_ConcatAndDel
#endif
#if PY_MAJOR_VERSION >= 3
#define __Pyx_PyBaseString_Check(obj) PyUnicode_Check(obj)
#define __Pyx_PyBaseString_CheckExact(obj) PyUnicode_CheckExact(obj)
#else
#define __Pyx_PyBaseString_Check(obj) (PyString_CheckExact(obj) || PyUnicode_CheckExact(obj) || \
PyString_Check(obj) || PyUnicode_Check(obj))
#define __Pyx_PyBaseString_CheckExact(obj) (PyString_CheckExact(obj) || PyUnicode_CheckExact(obj))
#endif
#if PY_VERSION_HEX < 0x02060000
#define PySet_Check(obj) PyObject_TypeCheck(obj, &PySet_Type)
#define PyFrozenSet_Check(obj) PyObject_TypeCheck(obj, &PyFrozenSet_Type)
#endif
#ifndef PySet_CheckExact
#define PySet_CheckExact(obj) (Py_TYPE(obj) == &PySet_Type)
#endif
#define __Pyx_TypeCheck(obj, type) PyObject_TypeCheck(obj, (PyTypeObject *)type)
#if PY_MAJOR_VERSION >= 3
#define PyIntObject PyLongObject
#define PyInt_Type PyLong_Type
#define PyInt_Check(op) PyLong_Check(op)
#define PyInt_CheckExact(op) PyLong_CheckExact(op)
#define PyInt_FromString PyLong_FromString
#define PyInt_FromUnicode PyLong_FromUnicode
#define PyInt_FromLong PyLong_FromLong
#define PyInt_FromSize_t PyLong_FromSize_t
#define PyInt_FromSsize_t PyLong_FromSsize_t
#define PyInt_AsLong PyLong_AsLong
#define PyInt_AS_LONG PyLong_AS_LONG
#define PyInt_AsSsize_t PyLong_AsSsize_t
#define PyInt_AsUnsignedLongMask PyLong_AsUnsignedLongMask
#define PyInt_AsUnsignedLongLongMask PyLong_AsUnsignedLongLongMask
#define PyNumber_Int PyNumber_Long
#endif
#if PY_MAJOR_VERSION >= 3
#define PyBoolObject PyLongObject
#endif
#if PY_VERSION_HEX < 0x030200A4
typedef long Py_hash_t;
#define __Pyx_PyInt_FromHash_t PyInt_FromLong
#define __Pyx_PyInt_AsHash_t PyInt_AsLong
#else
#define __Pyx_PyInt_FromHash_t PyInt_FromSsize_t
#define __Pyx_PyInt_AsHash_t PyInt_AsSsize_t
#endif
#if (PY_MAJOR_VERSION < 3) || (PY_VERSION_HEX >= 0x03010300)
#define __Pyx_PySequence_GetSlice(obj, a, b) PySequence_GetSlice(obj, a, b)
#define __Pyx_PySequence_SetSlice(obj, a, b, value) PySequence_SetSlice(obj, a, b, value)
#define __Pyx_PySequence_DelSlice(obj, a, b) PySequence_DelSlice(obj, a, b)
#else
#define __Pyx_PySequence_GetSlice(obj, a, b) (unlikely(!(obj)) ? \
(PyErr_SetString(PyExc_SystemError, "null argument to internal routine"), (PyObject*)0) : \
(likely((obj)->ob_type->tp_as_mapping) ? (PySequence_GetSlice(obj, a, b)) : \
(PyErr_Format(PyExc_TypeError, "'%.200s' object is unsliceable", (obj)->ob_type->tp_name), (PyObject*)0)))
#define __Pyx_PySequence_SetSlice(obj, a, b, value) (unlikely(!(obj)) ? \
(PyErr_SetString(PyExc_SystemError, "null argument to internal routine"), -1) : \
(likely((obj)->ob_type->tp_as_mapping) ? (PySequence_SetSlice(obj, a, b, value)) : \
(PyErr_Format(PyExc_TypeError, "'%.200s' object doesn't support slice assignment", (obj)->ob_type->tp_name), -1)))
#define __Pyx_PySequence_DelSlice(obj, a, b) (unlikely(!(obj)) ? \
(PyErr_SetString(PyExc_SystemError, "null argument to internal routine"), -1) : \
(likely((obj)->ob_type->tp_as_mapping) ? (PySequence_DelSlice(obj, a, b)) : \
(PyErr_Format(PyExc_TypeError, "'%.200s' object doesn't support slice deletion", (obj)->ob_type->tp_name), -1)))
#endif
#if PY_MAJOR_VERSION >= 3
#define PyMethod_New(func, self, klass) ((self) ? PyMethod_New(func, self) : PyInstanceMethod_New(func))
#endif
#if PY_VERSION_HEX < 0x02050000
#define __Pyx_GetAttrString(o,n) PyObject_GetAttrString((o),((char *)(n)))
#define __Pyx_SetAttrString(o,n,a) PyObject_SetAttrString((o),((char *)(n)),(a))
#define __Pyx_DelAttrString(o,n) PyObject_DelAttrString((o),((char *)(n)))
#else
#define __Pyx_GetAttrString(o,n) PyObject_GetAttrString((o),(n))
#define __Pyx_SetAttrString(o,n,a) PyObject_SetAttrString((o),(n),(a))
#define __Pyx_DelAttrString(o,n) PyObject_DelAttrString((o),(n))
#endif
#if PY_VERSION_HEX < 0x02050000
#define __Pyx_NAMESTR(n) ((char *)(n))
#define __Pyx_DOCSTR(n) ((char *)(n))
#else
#define __Pyx_NAMESTR(n) (n)
#define __Pyx_DOCSTR(n) (n)
#endif
#ifndef CYTHON_INLINE
#if defined(__GNUC__)
#define CYTHON_INLINE __inline__
#elif defined(_MSC_VER)
#define CYTHON_INLINE __inline
#elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
#define CYTHON_INLINE inline
#else
#define CYTHON_INLINE
#endif
#endif
#ifndef CYTHON_RESTRICT
#if defined(__GNUC__)
#define CYTHON_RESTRICT __restrict__
#elif defined(_MSC_VER) && _MSC_VER >= 1400
#define CYTHON_RESTRICT __restrict
#elif defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L
#define CYTHON_RESTRICT restrict
#else
#define CYTHON_RESTRICT
#endif
#endif
#ifdef NAN
#define __PYX_NAN() ((float) NAN)
#else
static CYTHON_INLINE float __PYX_NAN() {
/* Initialize NaN. The sign is irrelevant, an exponent with all bits 1 and
a nonzero mantissa means NaN. If the first bit in the mantissa is 1, it is
a quiet NaN. */
float value;
memset(&value, 0xFF, sizeof(value));
return value;
}
#endif
#if PY_MAJOR_VERSION >= 3
#define __Pyx_PyNumber_Divide(x,y) PyNumber_TrueDivide(x,y)
#define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceTrueDivide(x,y)
#else
#define __Pyx_PyNumber_Divide(x,y) PyNumber_Divide(x,y)
#define __Pyx_PyNumber_InPlaceDivide(x,y) PyNumber_InPlaceDivide(x,y)
#endif
#ifndef __PYX_EXTERN_C
#ifdef __cplusplus
#define __PYX_EXTERN_C extern "C"
#else
#define __PYX_EXTERN_C extern
#endif
#endif
#if defined(WIN32) || defined(MS_WINDOWS)
#define _USE_MATH_DEFINES
#endif
#include <math.h>
#define __PYX_HAVE__sklearn__metrics__pairwise_fast
#define __PYX_HAVE_API__sklearn__metrics__pairwise_fast
#include "string.h"
#include "stdio.h"
#include "stdlib.h"
#include "numpy/arrayobject.h"
#include "numpy/ufuncobject.h"
#include "cblas.h"
#include "pythread.h"
#include "pystate.h"
#ifdef _OPENMP
#include <omp.h>
#endif /* _OPENMP */
#ifdef PYREX_WITHOUT_ASSERTIONS
#define CYTHON_WITHOUT_ASSERTIONS
#endif
#ifndef CYTHON_UNUSED
# if defined(__GNUC__)
# if !(defined(__cplusplus)) || (__GNUC__ > 3 || (__GNUC__ == 3 && __GNUC_MINOR__ >= 4))
# define CYTHON_UNUSED __attribute__ ((__unused__))
# else
# define CYTHON_UNUSED
# endif
# elif defined(__ICC) || (defined(__INTEL_COMPILER) && !defined(_MSC_VER))
# define CYTHON_UNUSED __attribute__ ((__unused__))
# else
# define CYTHON_UNUSED
# endif
#endif
typedef struct {PyObject **p; char *s; const Py_ssize_t n; const char* encoding;
const char is_unicode; const char is_str; const char intern; } __Pyx_StringTabEntry; /*proto*/
#define __PYX_DEFAULT_STRING_ENCODING_IS_ASCII 0
#define __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT 0
#define __PYX_DEFAULT_STRING_ENCODING ""
#define __Pyx_PyObject_FromString __Pyx_PyBytes_FromString
#define __Pyx_PyObject_FromStringAndSize __Pyx_PyBytes_FromStringAndSize
#define __Pyx_fits_Py_ssize_t(v, type, is_signed) ( \
(sizeof(type) < sizeof(Py_ssize_t)) || \
(sizeof(type) > sizeof(Py_ssize_t) && \
likely(v < (type)PY_SSIZE_T_MAX || \
v == (type)PY_SSIZE_T_MAX) && \
(!is_signed || likely(v > (type)PY_SSIZE_T_MIN || \
v == (type)PY_SSIZE_T_MIN))) || \
(sizeof(type) == sizeof(Py_ssize_t) && \
(is_signed || likely(v < (type)PY_SSIZE_T_MAX || \
v == (type)PY_SSIZE_T_MAX))) )
static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject*);
static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject*, Py_ssize_t* length);
#define __Pyx_PyByteArray_FromString(s) PyByteArray_FromStringAndSize((const char*)s, strlen((const char*)s))
#define __Pyx_PyByteArray_FromStringAndSize(s, l) PyByteArray_FromStringAndSize((const char*)s, l)
#define __Pyx_PyBytes_FromString PyBytes_FromString
#define __Pyx_PyBytes_FromStringAndSize PyBytes_FromStringAndSize
static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(char*);
#if PY_MAJOR_VERSION < 3
#define __Pyx_PyStr_FromString __Pyx_PyBytes_FromString
#define __Pyx_PyStr_FromStringAndSize __Pyx_PyBytes_FromStringAndSize
#else
#define __Pyx_PyStr_FromString __Pyx_PyUnicode_FromString
#define __Pyx_PyStr_FromStringAndSize __Pyx_PyUnicode_FromStringAndSize
#endif
#define __Pyx_PyObject_AsSString(s) ((signed char*) __Pyx_PyObject_AsString(s))
#define __Pyx_PyObject_AsUString(s) ((unsigned char*) __Pyx_PyObject_AsString(s))
#define __Pyx_PyObject_FromUString(s) __Pyx_PyObject_FromString((char*)s)
#define __Pyx_PyBytes_FromUString(s) __Pyx_PyBytes_FromString((char*)s)
#define __Pyx_PyByteArray_FromUString(s) __Pyx_PyByteArray_FromString((char*)s)
#define __Pyx_PyStr_FromUString(s) __Pyx_PyStr_FromString((char*)s)
#define __Pyx_PyUnicode_FromUString(s) __Pyx_PyUnicode_FromString((char*)s)
#if PY_MAJOR_VERSION < 3
static CYTHON_INLINE size_t __Pyx_Py_UNICODE_strlen(const Py_UNICODE *u)
{
const Py_UNICODE *u_end = u;
while (*u_end++) ;
return u_end - u - 1;
}
#else
#define __Pyx_Py_UNICODE_strlen Py_UNICODE_strlen
#endif
#define __Pyx_PyUnicode_FromUnicode(u) PyUnicode_FromUnicode(u, __Pyx_Py_UNICODE_strlen(u))
#define __Pyx_PyUnicode_FromUnicodeAndLength PyUnicode_FromUnicode
#define __Pyx_PyUnicode_AsUnicode PyUnicode_AsUnicode
#define __Pyx_Owned_Py_None(b) (Py_INCREF(Py_None), Py_None)
#define __Pyx_PyBool_FromLong(b) ((b) ? (Py_INCREF(Py_True), Py_True) : (Py_INCREF(Py_False), Py_False))
static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject*);
static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x);
static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject*);
static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t);
#if CYTHON_COMPILING_IN_CPYTHON
#define __pyx_PyFloat_AsDouble(x) (PyFloat_CheckExact(x) ? PyFloat_AS_DOUBLE(x) : PyFloat_AsDouble(x))
#else
#define __pyx_PyFloat_AsDouble(x) PyFloat_AsDouble(x)
#endif
#define __pyx_PyFloat_AsFloat(x) ((float) __pyx_PyFloat_AsDouble(x))
#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII
static int __Pyx_sys_getdefaultencoding_not_ascii;
static int __Pyx_init_sys_getdefaultencoding_params(void) {
PyObject* sys = NULL;
PyObject* default_encoding = NULL;
PyObject* ascii_chars_u = NULL;
PyObject* ascii_chars_b = NULL;
sys = PyImport_ImportModule("sys");
if (sys == NULL) goto bad;
default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL);
if (default_encoding == NULL) goto bad;
if (strcmp(PyBytes_AsString(default_encoding), "ascii") == 0) {
__Pyx_sys_getdefaultencoding_not_ascii = 0;
} else {
const char* default_encoding_c = PyBytes_AS_STRING(default_encoding);
char ascii_chars[128];
int c;
for (c = 0; c < 128; c++) {
ascii_chars[c] = c;
}
__Pyx_sys_getdefaultencoding_not_ascii = 1;
ascii_chars_u = PyUnicode_DecodeASCII(ascii_chars, 128, NULL);
if (ascii_chars_u == NULL) goto bad;
ascii_chars_b = PyUnicode_AsEncodedString(ascii_chars_u, default_encoding_c, NULL);
if (ascii_chars_b == NULL || strncmp(ascii_chars, PyBytes_AS_STRING(ascii_chars_b), 128) != 0) {
PyErr_Format(
PyExc_ValueError,
"This module compiled with c_string_encoding=ascii, but default encoding '%.200s' is not a superset of ascii.",
default_encoding_c);
goto bad;
}
}
Py_XDECREF(sys);
Py_XDECREF(default_encoding);
Py_XDECREF(ascii_chars_u);
Py_XDECREF(ascii_chars_b);
return 0;
bad:
Py_XDECREF(sys);
Py_XDECREF(default_encoding);
Py_XDECREF(ascii_chars_u);
Py_XDECREF(ascii_chars_b);
return -1;
}
#endif
#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT && PY_MAJOR_VERSION >= 3
#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_DecodeUTF8(c_str, size, NULL)
#else
#define __Pyx_PyUnicode_FromStringAndSize(c_str, size) PyUnicode_Decode(c_str, size, __PYX_DEFAULT_STRING_ENCODING, NULL)
#if __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT
static char* __PYX_DEFAULT_STRING_ENCODING;
static int __Pyx_init_sys_getdefaultencoding_params(void) {
PyObject* sys = NULL;
PyObject* default_encoding = NULL;
char* default_encoding_c;
sys = PyImport_ImportModule("sys");
if (sys == NULL) goto bad;
default_encoding = PyObject_CallMethod(sys, (char*) (const char*) "getdefaultencoding", NULL);
if (default_encoding == NULL) goto bad;
default_encoding_c = PyBytes_AS_STRING(default_encoding);
__PYX_DEFAULT_STRING_ENCODING = (char*) malloc(strlen(default_encoding_c));
strcpy(__PYX_DEFAULT_STRING_ENCODING, default_encoding_c);
Py_DECREF(sys);
Py_DECREF(default_encoding);
return 0;
bad:
Py_XDECREF(sys);
Py_XDECREF(default_encoding);
return -1;
}
#endif
#endif
#ifdef __GNUC__
/* Test for GCC > 2.95 */
#if __GNUC__ > 2 || (__GNUC__ == 2 && (__GNUC_MINOR__ > 95))
#define likely(x) __builtin_expect(!!(x), 1)
#define unlikely(x) __builtin_expect(!!(x), 0)
#else /* __GNUC__ > 2 ... */
#define likely(x) (x)
#define unlikely(x) (x)
#endif /* __GNUC__ > 2 ... */
#else /* __GNUC__ */
#define likely(x) (x)
#define unlikely(x) (x)
#endif /* __GNUC__ */
static PyObject *__pyx_m;
static PyObject *__pyx_d;
static PyObject *__pyx_b;
static PyObject *__pyx_empty_tuple;
static PyObject *__pyx_empty_bytes;
static int __pyx_lineno;
static int __pyx_clineno = 0;
static const char * __pyx_cfilenm= __FILE__;
static const char *__pyx_filename;
#if !defined(CYTHON_CCOMPLEX)
#if defined(__cplusplus)
#define CYTHON_CCOMPLEX 1
#elif defined(_Complex_I)
#define CYTHON_CCOMPLEX 1
#else
#define CYTHON_CCOMPLEX 0
#endif
#endif
#if CYTHON_CCOMPLEX
#ifdef __cplusplus
#include <complex>
#else
#include <complex.h>
#endif
#endif
#if CYTHON_CCOMPLEX && !defined(__cplusplus) && defined(__sun__) && defined(__GNUC__)
#undef _Complex_I
#define _Complex_I 1.0fj
#endif
static const char *__pyx_f[] = {
"pairwise_fast.pyx",
"__init__.pxd",
"stringsource",
"type.pxd",
};
struct __pyx_memoryview_obj;
typedef struct {
struct __pyx_memoryview_obj *memview;
char *data;
Py_ssize_t shape[8];
Py_ssize_t strides[8];
Py_ssize_t suboffsets[8];
} __Pyx_memviewslice;
#define IS_UNSIGNED(type) (((type) -1) > 0)
struct __Pyx_StructField_;
#define __PYX_BUF_FLAGS_PACKED_STRUCT (1 << 0)
typedef struct {
const char* name; /* for error messages only */
struct __Pyx_StructField_* fields;
size_t size; /* sizeof(type) */
size_t arraysize[8]; /* length of array in each dimension */
int ndim;
char typegroup; /* _R_eal, _C_omplex, Signed _I_nt, _U_nsigned int, _S_truct, _P_ointer, _O_bject, c_H_ar */
char is_unsigned;
int flags;
} __Pyx_TypeInfo;
typedef struct __Pyx_StructField_ {
__Pyx_TypeInfo* type;
const char* name;
size_t offset;
} __Pyx_StructField;
typedef struct {
__Pyx_StructField* field;
size_t parent_offset;
} __Pyx_BufFmt_StackElem;
typedef struct {
__Pyx_StructField root;
__Pyx_BufFmt_StackElem* head;
size_t fmt_offset;
size_t new_count, enc_count;
size_t struct_alignment;
int is_complex;
char enc_type;
char new_packmode;
char enc_packmode;
char is_valid_array;
} __Pyx_BufFmt_Context;
#include <pythread.h>
#ifndef CYTHON_ATOMICS
#define CYTHON_ATOMICS 1
#endif
#define __pyx_atomic_int_type int
#if CYTHON_ATOMICS && __GNUC__ >= 4 && (__GNUC_MINOR__ > 1 || \
(__GNUC_MINOR__ == 1 && __GNUC_PATCHLEVEL >= 2)) && \
!defined(__i386__)
#define __pyx_atomic_incr_aligned(value, lock) __sync_fetch_and_add(value, 1)
#define __pyx_atomic_decr_aligned(value, lock) __sync_fetch_and_sub(value, 1)
#ifdef __PYX_DEBUG_ATOMICS
#warning "Using GNU atomics"
#endif
#elif CYTHON_ATOMICS && MSC_VER
#include <Windows.h>
#define __pyx_atomic_int_type LONG
#define __pyx_atomic_incr_aligned(value, lock) InterlockedIncrement(value)
#define __pyx_atomic_decr_aligned(value, lock) InterlockedDecrement(value)
#ifdef __PYX_DEBUG_ATOMICS
#warning "Using MSVC atomics"
#endif
#elif CYTHON_ATOMICS && (defined(__ICC) || defined(__INTEL_COMPILER)) && 0
#define __pyx_atomic_incr_aligned(value, lock) _InterlockedIncrement(value)
#define __pyx_atomic_decr_aligned(value, lock) _InterlockedDecrement(value)
#ifdef __PYX_DEBUG_ATOMICS
#warning "Using Intel atomics"
#endif
#else
#undef CYTHON_ATOMICS
#define CYTHON_ATOMICS 0
#ifdef __PYX_DEBUG_ATOMICS
#warning "Not using atomics"
#endif
#endif
typedef volatile __pyx_atomic_int_type __pyx_atomic_int;
#if CYTHON_ATOMICS
#define __pyx_add_acquisition_count(memview) \
__pyx_atomic_incr_aligned(__pyx_get_slice_count_pointer(memview), memview->lock)
#define __pyx_sub_acquisition_count(memview) \
__pyx_atomic_decr_aligned(__pyx_get_slice_count_pointer(memview), memview->lock)
#else
#define __pyx_add_acquisition_count(memview) \
__pyx_add_acquisition_count_locked(__pyx_get_slice_count_pointer(memview), memview->lock)
#define __pyx_sub_acquisition_count(memview) \
__pyx_sub_acquisition_count_locked(__pyx_get_slice_count_pointer(memview), memview->lock)
#endif
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":723
* # in Cython to enable them only on the right systems.
*
* ctypedef npy_int8 int8_t # <<<<<<<<<<<<<<
* ctypedef npy_int16 int16_t
* ctypedef npy_int32 int32_t
*/
typedef npy_int8 __pyx_t_5numpy_int8_t;
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":724
*
* ctypedef npy_int8 int8_t
* ctypedef npy_int16 int16_t # <<<<<<<<<<<<<<
* ctypedef npy_int32 int32_t
* ctypedef npy_int64 int64_t
*/
typedef npy_int16 __pyx_t_5numpy_int16_t;
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":725
* ctypedef npy_int8 int8_t
* ctypedef npy_int16 int16_t
* ctypedef npy_int32 int32_t # <<<<<<<<<<<<<<
* ctypedef npy_int64 int64_t
* #ctypedef npy_int96 int96_t
*/
typedef npy_int32 __pyx_t_5numpy_int32_t;
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":726
* ctypedef npy_int16 int16_t
* ctypedef npy_int32 int32_t
* ctypedef npy_int64 int64_t # <<<<<<<<<<<<<<
* #ctypedef npy_int96 int96_t
* #ctypedef npy_int128 int128_t
*/
typedef npy_int64 __pyx_t_5numpy_int64_t;
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":730
* #ctypedef npy_int128 int128_t
*
* ctypedef npy_uint8 uint8_t # <<<<<<<<<<<<<<
* ctypedef npy_uint16 uint16_t
* ctypedef npy_uint32 uint32_t
*/
typedef npy_uint8 __pyx_t_5numpy_uint8_t;
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":731
*
* ctypedef npy_uint8 uint8_t
* ctypedef npy_uint16 uint16_t # <<<<<<<<<<<<<<
* ctypedef npy_uint32 uint32_t
* ctypedef npy_uint64 uint64_t
*/
typedef npy_uint16 __pyx_t_5numpy_uint16_t;
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":732
* ctypedef npy_uint8 uint8_t
* ctypedef npy_uint16 uint16_t
* ctypedef npy_uint32 uint32_t # <<<<<<<<<<<<<<
* ctypedef npy_uint64 uint64_t
* #ctypedef npy_uint96 uint96_t
*/
typedef npy_uint32 __pyx_t_5numpy_uint32_t;
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":733
* ctypedef npy_uint16 uint16_t
* ctypedef npy_uint32 uint32_t
* ctypedef npy_uint64 uint64_t # <<<<<<<<<<<<<<
* #ctypedef npy_uint96 uint96_t
* #ctypedef npy_uint128 uint128_t
*/
typedef npy_uint64 __pyx_t_5numpy_uint64_t;
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":737
* #ctypedef npy_uint128 uint128_t
*
* ctypedef npy_float32 float32_t # <<<<<<<<<<<<<<
* ctypedef npy_float64 float64_t
* #ctypedef npy_float80 float80_t
*/
typedef npy_float32 __pyx_t_5numpy_float32_t;
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":738
*
* ctypedef npy_float32 float32_t
* ctypedef npy_float64 float64_t # <<<<<<<<<<<<<<
* #ctypedef npy_float80 float80_t
* #ctypedef npy_float128 float128_t
*/
typedef npy_float64 __pyx_t_5numpy_float64_t;
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":747
* # The int types are mapped a bit surprising --
* # numpy.int corresponds to 'l' and numpy.long to 'q'
* ctypedef npy_long int_t # <<<<<<<<<<<<<<
* ctypedef npy_longlong long_t
* ctypedef npy_longlong longlong_t
*/
typedef npy_long __pyx_t_5numpy_int_t;
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":748
* # numpy.int corresponds to 'l' and numpy.long to 'q'
* ctypedef npy_long int_t
* ctypedef npy_longlong long_t # <<<<<<<<<<<<<<
* ctypedef npy_longlong longlong_t
*
*/
typedef npy_longlong __pyx_t_5numpy_long_t;
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":749
* ctypedef npy_long int_t
* ctypedef npy_longlong long_t
* ctypedef npy_longlong longlong_t # <<<<<<<<<<<<<<
*
* ctypedef npy_ulong uint_t
*/
typedef npy_longlong __pyx_t_5numpy_longlong_t;
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":751
* ctypedef npy_longlong longlong_t
*
* ctypedef npy_ulong uint_t # <<<<<<<<<<<<<<
* ctypedef npy_ulonglong ulong_t
* ctypedef npy_ulonglong ulonglong_t
*/
typedef npy_ulong __pyx_t_5numpy_uint_t;
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":752
*
* ctypedef npy_ulong uint_t
* ctypedef npy_ulonglong ulong_t # <<<<<<<<<<<<<<
* ctypedef npy_ulonglong ulonglong_t
*
*/
typedef npy_ulonglong __pyx_t_5numpy_ulong_t;
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":753
* ctypedef npy_ulong uint_t
* ctypedef npy_ulonglong ulong_t
* ctypedef npy_ulonglong ulonglong_t # <<<<<<<<<<<<<<
*
* ctypedef npy_intp intp_t
*/
typedef npy_ulonglong __pyx_t_5numpy_ulonglong_t;
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":755
* ctypedef npy_ulonglong ulonglong_t
*
* ctypedef npy_intp intp_t # <<<<<<<<<<<<<<
* ctypedef npy_uintp uintp_t
*
*/
typedef npy_intp __pyx_t_5numpy_intp_t;
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":756
*
* ctypedef npy_intp intp_t
* ctypedef npy_uintp uintp_t # <<<<<<<<<<<<<<
*
* ctypedef npy_double float_t
*/
typedef npy_uintp __pyx_t_5numpy_uintp_t;
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":758
* ctypedef npy_uintp uintp_t
*
* ctypedef npy_double float_t # <<<<<<<<<<<<<<
* ctypedef npy_double double_t
* ctypedef npy_longdouble longdouble_t
*/
typedef npy_double __pyx_t_5numpy_float_t;
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":759
*
* ctypedef npy_double float_t
* ctypedef npy_double double_t # <<<<<<<<<<<<<<
* ctypedef npy_longdouble longdouble_t
*
*/
typedef npy_double __pyx_t_5numpy_double_t;
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":760
* ctypedef npy_double float_t
* ctypedef npy_double double_t
* ctypedef npy_longdouble longdouble_t # <<<<<<<<<<<<<<
*
* ctypedef npy_cfloat cfloat_t
*/
typedef npy_longdouble __pyx_t_5numpy_longdouble_t;
#if CYTHON_CCOMPLEX
#ifdef __cplusplus
typedef ::std::complex< float > __pyx_t_float_complex;
#else
typedef float _Complex __pyx_t_float_complex;
#endif
#else
typedef struct { float real, imag; } __pyx_t_float_complex;
#endif
#if CYTHON_CCOMPLEX
#ifdef __cplusplus
typedef ::std::complex< double > __pyx_t_double_complex;
#else
typedef double _Complex __pyx_t_double_complex;
#endif
#else
typedef struct { double real, imag; } __pyx_t_double_complex;
#endif
/*--- Type declarations ---*/
struct __pyx_array_obj;
struct __pyx_MemviewEnum_obj;
struct __pyx_memoryview_obj;
struct __pyx_memoryviewslice_obj;
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":762
* ctypedef npy_longdouble longdouble_t
*
* ctypedef npy_cfloat cfloat_t # <<<<<<<<<<<<<<
* ctypedef npy_cdouble cdouble_t
* ctypedef npy_clongdouble clongdouble_t
*/
typedef npy_cfloat __pyx_t_5numpy_cfloat_t;
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":763
*
* ctypedef npy_cfloat cfloat_t
* ctypedef npy_cdouble cdouble_t # <<<<<<<<<<<<<<
* ctypedef npy_clongdouble clongdouble_t
*
*/
typedef npy_cdouble __pyx_t_5numpy_cdouble_t;
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":764
* ctypedef npy_cfloat cfloat_t
* ctypedef npy_cdouble cdouble_t
* ctypedef npy_clongdouble clongdouble_t # <<<<<<<<<<<<<<
*
* ctypedef npy_cdouble complex_t
*/
typedef npy_clongdouble __pyx_t_5numpy_clongdouble_t;
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":766
* ctypedef npy_clongdouble clongdouble_t
*
* ctypedef npy_cdouble complex_t # <<<<<<<<<<<<<<
*
* cdef inline object PyArray_MultiIterNew1(a):
*/
typedef npy_cdouble __pyx_t_5numpy_complex_t;
/* "sklearn/metrics/pairwise_fast.pyx":17
* double cblas_dasum(int, const double *, int) nogil
*
* ctypedef float [:, :] float_array_2d_t # <<<<<<<<<<<<<<
* ctypedef double [:, :] double_array_2d_t
*
*/
typedef __Pyx_memviewslice __pyx_t_7sklearn_7metrics_13pairwise_fast_float_array_2d_t;
/* "sklearn/metrics/pairwise_fast.pyx":18
*
* ctypedef float [:, :] float_array_2d_t
* ctypedef double [:, :] double_array_2d_t # <<<<<<<<<<<<<<
*
* cdef fused floating1d:
*/
typedef __Pyx_memviewslice __pyx_t_7sklearn_7metrics_13pairwise_fast_double_array_2d_t;
/* "View.MemoryView":96
*
* @cname("__pyx_array")
* cdef class array: # <<<<<<<<<<<<<<
*
* cdef:
*/
struct __pyx_array_obj {
PyObject_HEAD
char *data;
Py_ssize_t len;
char *format;
int ndim;
Py_ssize_t *_shape;
Py_ssize_t *_strides;
Py_ssize_t itemsize;
PyObject *mode;
PyObject *_format;
void (*callback_free_data)(void *);
int free_data;
int dtype_is_object;
};
/* "View.MemoryView":275
*
* @cname('__pyx_MemviewEnum')
* cdef class Enum(object): # <<<<<<<<<<<<<<
* cdef object name
* def __init__(self, name):
*/
struct __pyx_MemviewEnum_obj {
PyObject_HEAD
PyObject *name;
};
/* "View.MemoryView":308
*
* @cname('__pyx_memoryview')
* cdef class memoryview(object): # <<<<<<<<<<<<<<
*
* cdef object obj
*/
struct __pyx_memoryview_obj {
PyObject_HEAD
struct __pyx_vtabstruct_memoryview *__pyx_vtab;
PyObject *obj;
PyObject *_size;
PyObject *_array_interface;
PyThread_type_lock lock;
__pyx_atomic_int acquisition_count[2];
__pyx_atomic_int *acquisition_count_aligned_p;
Py_buffer view;
int flags;
int dtype_is_object;
__Pyx_TypeInfo *typeinfo;
};
/* "View.MemoryView":930
*
* @cname('__pyx_memoryviewslice')
* cdef class _memoryviewslice(memoryview): # <<<<<<<<<<<<<<
* "Internal class for passing memoryview slices to Python"
*
*/
struct __pyx_memoryviewslice_obj {
struct __pyx_memoryview_obj __pyx_base;
__Pyx_memviewslice from_slice;
PyObject *from_object;
PyObject *(*to_object_func)(char *);
int (*to_dtype_func)(char *, PyObject *);
};
/* "View.MemoryView":308
*
* @cname('__pyx_memoryview')
* cdef class memoryview(object): # <<<<<<<<<<<<<<
*
* cdef object obj
*/
struct __pyx_vtabstruct_memoryview {
char *(*get_item_pointer)(struct __pyx_memoryview_obj *, PyObject *);
PyObject *(*is_slice)(struct __pyx_memoryview_obj *, PyObject *);
PyObject *(*setitem_slice_assignment)(struct __pyx_memoryview_obj *, PyObject *, PyObject *);
PyObject *(*setitem_slice_assign_scalar)(struct __pyx_memoryview_obj *, struct __pyx_memoryview_obj *, PyObject *);
PyObject *(*setitem_indexed)(struct __pyx_memoryview_obj *, PyObject *, PyObject *);
PyObject *(*convert_item_to_object)(struct __pyx_memoryview_obj *, char *);
PyObject *(*assign_item_from_object)(struct __pyx_memoryview_obj *, char *, PyObject *);
};
static struct __pyx_vtabstruct_memoryview *__pyx_vtabptr_memoryview;
/* "View.MemoryView":930
*
* @cname('__pyx_memoryviewslice')
* cdef class _memoryviewslice(memoryview): # <<<<<<<<<<<<<<
* "Internal class for passing memoryview slices to Python"
*
*/
struct __pyx_vtabstruct__memoryviewslice {
struct __pyx_vtabstruct_memoryview __pyx_base;
};
static struct __pyx_vtabstruct__memoryviewslice *__pyx_vtabptr__memoryviewslice;
#ifndef CYTHON_REFNANNY
#define CYTHON_REFNANNY 0
#endif
#if CYTHON_REFNANNY
typedef struct {
void (*INCREF)(void*, PyObject*, int);
void (*DECREF)(void*, PyObject*, int);
void (*GOTREF)(void*, PyObject*, int);
void (*GIVEREF)(void*, PyObject*, int);
void* (*SetupContext)(const char*, int, const char*);
void (*FinishContext)(void**);
} __Pyx_RefNannyAPIStruct;
static __Pyx_RefNannyAPIStruct *__Pyx_RefNanny = NULL;
static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname); /*proto*/
#define __Pyx_RefNannyDeclarations void *__pyx_refnanny = NULL;
#ifdef WITH_THREAD
#define __Pyx_RefNannySetupContext(name, acquire_gil) \
if (acquire_gil) { \
PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure(); \
__pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__); \
PyGILState_Release(__pyx_gilstate_save); \
} else { \
__pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__); \
}
#else
#define __Pyx_RefNannySetupContext(name, acquire_gil) \
__pyx_refnanny = __Pyx_RefNanny->SetupContext((name), __LINE__, __FILE__)
#endif
#define __Pyx_RefNannyFinishContext() \
__Pyx_RefNanny->FinishContext(&__pyx_refnanny)
#define __Pyx_INCREF(r) __Pyx_RefNanny->INCREF(__pyx_refnanny, (PyObject *)(r), __LINE__)
#define __Pyx_DECREF(r) __Pyx_RefNanny->DECREF(__pyx_refnanny, (PyObject *)(r), __LINE__)
#define __Pyx_GOTREF(r) __Pyx_RefNanny->GOTREF(__pyx_refnanny, (PyObject *)(r), __LINE__)
#define __Pyx_GIVEREF(r) __Pyx_RefNanny->GIVEREF(__pyx_refnanny, (PyObject *)(r), __LINE__)
#define __Pyx_XINCREF(r) do { if((r) != NULL) {__Pyx_INCREF(r); }} while(0)
#define __Pyx_XDECREF(r) do { if((r) != NULL) {__Pyx_DECREF(r); }} while(0)
#define __Pyx_XGOTREF(r) do { if((r) != NULL) {__Pyx_GOTREF(r); }} while(0)
#define __Pyx_XGIVEREF(r) do { if((r) != NULL) {__Pyx_GIVEREF(r);}} while(0)
#else
#define __Pyx_RefNannyDeclarations
#define __Pyx_RefNannySetupContext(name, acquire_gil)
#define __Pyx_RefNannyFinishContext()
#define __Pyx_INCREF(r) Py_INCREF(r)
#define __Pyx_DECREF(r) Py_DECREF(r)
#define __Pyx_GOTREF(r)
#define __Pyx_GIVEREF(r)
#define __Pyx_XINCREF(r) Py_XINCREF(r)
#define __Pyx_XDECREF(r) Py_XDECREF(r)
#define __Pyx_XGOTREF(r)
#define __Pyx_XGIVEREF(r)
#endif /* CYTHON_REFNANNY */
#define __Pyx_XDECREF_SET(r, v) do { \
PyObject *tmp = (PyObject *) r; \
r = v; __Pyx_XDECREF(tmp); \
} while (0)
#define __Pyx_DECREF_SET(r, v) do { \
PyObject *tmp = (PyObject *) r; \
r = v; __Pyx_DECREF(tmp); \
} while (0)
#define __Pyx_CLEAR(r) do { PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);} while(0)
#define __Pyx_XCLEAR(r) do { if((r) != NULL) {PyObject* tmp = ((PyObject*)(r)); r = NULL; __Pyx_DECREF(tmp);}} while(0)
#if CYTHON_COMPILING_IN_CPYTHON
static CYTHON_INLINE PyObject* __Pyx_PyObject_GetAttrStr(PyObject* obj, PyObject* attr_name) {
PyTypeObject* tp = Py_TYPE(obj);
if (likely(tp->tp_getattro))
return tp->tp_getattro(obj, attr_name);
#if PY_MAJOR_VERSION < 3
if (likely(tp->tp_getattr))
return tp->tp_getattr(obj, PyString_AS_STRING(attr_name));
#endif
return PyObject_GetAttr(obj, attr_name);
}
#else
#define __Pyx_PyObject_GetAttrStr(o,n) PyObject_GetAttr(o,n)
#endif
static PyObject *__Pyx_GetBuiltinName(PyObject *name); /*proto*/
static void __Pyx_RaiseArgtupleInvalid(const char* func_name, int exact,
Py_ssize_t num_min, Py_ssize_t num_max, Py_ssize_t num_found); /*proto*/
static void __Pyx_RaiseDoubleKeywordsError(const char* func_name, PyObject* kw_name); /*proto*/
static int __Pyx_ParseOptionalKeywords(PyObject *kwds, PyObject **argnames[], \
PyObject *kwds2, PyObject *values[], Py_ssize_t num_pos_args, \
const char* function_name); /*proto*/
static CYTHON_INLINE void __Pyx_ExceptionSave(PyObject **type, PyObject **value, PyObject **tb); /*proto*/
static void __Pyx_ExceptionReset(PyObject *type, PyObject *value, PyObject *tb); /*proto*/
static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb); /*proto*/
#define __Pyx_GetItemInt(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck) \
(__Pyx_fits_Py_ssize_t(i, type, is_signed) ? \
__Pyx_GetItemInt_Fast(o, (Py_ssize_t)i, is_list, wraparound, boundscheck) : \
(is_list ? (PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL) : \
__Pyx_GetItemInt_Generic(o, to_py_func(i))))
#define __Pyx_GetItemInt_List(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck) \
(__Pyx_fits_Py_ssize_t(i, type, is_signed) ? \
__Pyx_GetItemInt_List_Fast(o, (Py_ssize_t)i, wraparound, boundscheck) : \
(PyErr_SetString(PyExc_IndexError, "list index out of range"), (PyObject*)NULL))
static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i,
int wraparound, int boundscheck);
#define __Pyx_GetItemInt_Tuple(o, i, type, is_signed, to_py_func, is_list, wraparound, boundscheck) \
(__Pyx_fits_Py_ssize_t(i, type, is_signed) ? \
__Pyx_GetItemInt_Tuple_Fast(o, (Py_ssize_t)i, wraparound, boundscheck) : \
(PyErr_SetString(PyExc_IndexError, "tuple index out of range"), (PyObject*)NULL))
static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i,
int wraparound, int boundscheck);
static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j);
static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i,
int is_list, int wraparound, int boundscheck);
static CYTHON_INLINE int __Pyx_PySequence_Contains(PyObject* item, PyObject* seq, int eq) {
int result = PySequence_Contains(seq, item);
return unlikely(result < 0) ? result : (result == (eq == Py_EQ));
}
#if CYTHON_COMPILING_IN_CPYTHON
static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw); /*proto*/
#else
#define __Pyx_PyObject_Call(func, arg, kw) PyObject_Call(func, arg, kw)
#endif
static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb); /*proto*/
static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb); /*proto*/
static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause); /*proto*/
#include <string.h>
static CYTHON_INLINE int __Pyx_PyBytes_Equals(PyObject* s1, PyObject* s2, int equals); /*proto*/
static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals); /*proto*/
#if PY_MAJOR_VERSION >= 3
#define __Pyx_PyString_Equals __Pyx_PyUnicode_Equals
#else
#define __Pyx_PyString_Equals __Pyx_PyBytes_Equals
#endif
#define __Pyx_SetItemInt(o, i, v, type, is_signed, to_py_func, is_list, wraparound, boundscheck) \
(__Pyx_fits_Py_ssize_t(i, type, is_signed) ? \
__Pyx_SetItemInt_Fast(o, (Py_ssize_t)i, v, is_list, wraparound, boundscheck) : \
(is_list ? (PyErr_SetString(PyExc_IndexError, "list assignment index out of range"), -1) : \
__Pyx_SetItemInt_Generic(o, to_py_func(i), v)))
static CYTHON_INLINE int __Pyx_SetItemInt_Generic(PyObject *o, PyObject *j, PyObject *v);
static CYTHON_INLINE int __Pyx_SetItemInt_Fast(PyObject *o, Py_ssize_t i, PyObject *v,
int is_list, int wraparound, int boundscheck);
static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected);
static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index);
static CYTHON_INLINE int __Pyx_IterFinish(void); /*proto*/
static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected); /*proto*/
#if CYTHON_COMPILING_IN_CPYTHON
static CYTHON_INLINE int __Pyx_PyList_Append(PyObject* list, PyObject* x) {
PyListObject* L = (PyListObject*) list;
Py_ssize_t len = Py_SIZE(list);
if (likely(L->allocated > len) & likely(len > (L->allocated >> 1))) {
Py_INCREF(x);
PyList_SET_ITEM(list, len, x);
Py_SIZE(list) = len+1;
return 0;
}
return PyList_Append(list, x);
}
#else
#define __Pyx_PyList_Append(L,x) PyList_Append(L,x)
#endif
static CYTHON_INLINE int __Pyx_GetBufferAndValidate(Py_buffer* buf, PyObject* obj,
__Pyx_TypeInfo* dtype, int flags, int nd, int cast, __Pyx_BufFmt_StackElem* stack);
static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info);
#define __Pyx_BUF_MAX_NDIMS %(BUF_MAX_NDIMS)d
#define __Pyx_MEMVIEW_DIRECT 1
#define __Pyx_MEMVIEW_PTR 2
#define __Pyx_MEMVIEW_FULL 4
#define __Pyx_MEMVIEW_CONTIG 8
#define __Pyx_MEMVIEW_STRIDED 16
#define __Pyx_MEMVIEW_FOLLOW 32
#define __Pyx_IS_C_CONTIG 1
#define __Pyx_IS_F_CONTIG 2
static int __Pyx_init_memviewslice(
struct __pyx_memoryview_obj *memview,
int ndim,
__Pyx_memviewslice *memviewslice,
int memview_is_new_reference);
static CYTHON_INLINE int __pyx_add_acquisition_count_locked(
__pyx_atomic_int *acquisition_count, PyThread_type_lock lock);
static CYTHON_INLINE int __pyx_sub_acquisition_count_locked(
__pyx_atomic_int *acquisition_count, PyThread_type_lock lock);
#define __pyx_get_slice_count_pointer(memview) (memview->acquisition_count_aligned_p)
#define __pyx_get_slice_count(memview) (*__pyx_get_slice_count_pointer(memview))
#define __PYX_INC_MEMVIEW(slice, have_gil) __Pyx_INC_MEMVIEW(slice, have_gil, __LINE__)
#define __PYX_XDEC_MEMVIEW(slice, have_gil) __Pyx_XDEC_MEMVIEW(slice, have_gil, __LINE__)
static CYTHON_INLINE void __Pyx_INC_MEMVIEW(__Pyx_memviewslice *, int, int);
static CYTHON_INLINE void __Pyx_XDEC_MEMVIEW(__Pyx_memviewslice *, int, int);
static CYTHON_INLINE PyObject *__Pyx_GetModuleGlobalName(PyObject *name); /*proto*/
static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void);
static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type); /*proto*/
static CYTHON_INLINE int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed,
const char *name, int exact); /*proto*/
static CYTHON_INLINE PyObject *__Pyx_GetAttr(PyObject *, PyObject *); /*proto*/
static CYTHON_INLINE PyObject *__Pyx_GetAttr3(PyObject *, PyObject *, PyObject *); /*proto*/
#ifndef __PYX_FORCE_INIT_THREADS
#define __PYX_FORCE_INIT_THREADS 0
#endif
#define UNARY_NEG_WOULD_OVERFLOW(x) (((x) < 0) & ((unsigned long)(x) == 0-(unsigned long)(x)))
static CYTHON_UNUSED int __pyx_array_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/
static PyObject *get_memview(PyObject *__pyx_v_self); /*proto*/
static CYTHON_INLINE PyObject* __Pyx_decode_c_string(
const char* cstring, Py_ssize_t start, Py_ssize_t stop,
const char* encoding, const char* errors,
PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors));
static CYTHON_UNUSED int __pyx_memoryview_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/
static PyObject *__pyx_memoryview_transpose(PyObject *__pyx_v_self); /*proto*/
static PyObject *__pyx_memoryview__get__base(PyObject *__pyx_v_self); /*proto*/
static PyObject *__pyx_memoryview_get_shape(PyObject *__pyx_v_self); /*proto*/
#if CYTHON_COMPILING_IN_CPYTHON
static CYTHON_INLINE int __Pyx_ListComp_Append(PyObject* list, PyObject* x) {
PyListObject* L = (PyListObject*) list;
Py_ssize_t len = Py_SIZE(list);
if (likely(L->allocated > len)) {
Py_INCREF(x);
PyList_SET_ITEM(list, len, x);
Py_SIZE(list) = len+1;
return 0;
}
return PyList_Append(list, x);
}
#else
#define __Pyx_ListComp_Append(L,x) PyList_Append(L,x)
#endif
static PyObject *__pyx_memoryview_get_strides(PyObject *__pyx_v_self); /*proto*/
static PyObject *__pyx_memoryview_get_suboffsets(PyObject *__pyx_v_self); /*proto*/
static PyObject *__pyx_memoryview_get_ndim(PyObject *__pyx_v_self); /*proto*/
static PyObject *__pyx_memoryview_get_itemsize(PyObject *__pyx_v_self); /*proto*/
static PyObject *__pyx_memoryview_get_nbytes(PyObject *__pyx_v_self); /*proto*/
static PyObject *__pyx_memoryview_get_size(PyObject *__pyx_v_self); /*proto*/
static CYTHON_INLINE int __Pyx_PyList_Extend(PyObject* L, PyObject* v) {
#if CYTHON_COMPILING_IN_CPYTHON
PyObject* none = _PyList_Extend((PyListObject*)L, v);
if (unlikely(!none))
return -1;
Py_DECREF(none);
return 0;
#else
return PyList_SetSlice(L, PY_SSIZE_T_MAX, PY_SSIZE_T_MAX, v);
#endif
}
static CYTHON_INLINE void __Pyx_RaiseUnboundLocalError(const char *varname);
static PyObject *__pyx_memoryviewslice__get__base(PyObject *__pyx_v_self); /*proto*/
static void __Pyx_WriteUnraisable(const char *name, int clineno,
int lineno, const char *filename,
int full_traceback); /*proto*/
static int __Pyx_SetVtable(PyObject *dict, void *vtable); /*proto*/
static PyTypeObject* __Pyx_FetchCommonType(PyTypeObject* type);
#define __Pyx_CyFunction_USED 1
#include <structmember.h>
#define __Pyx_CYFUNCTION_STATICMETHOD 0x01
#define __Pyx_CYFUNCTION_CLASSMETHOD 0x02
#define __Pyx_CYFUNCTION_CCLASS 0x04
#define __Pyx_CyFunction_GetClosure(f) \
(((__pyx_CyFunctionObject *) (f))->func_closure)
#define __Pyx_CyFunction_GetClassObj(f) \
(((__pyx_CyFunctionObject *) (f))->func_classobj)
#define __Pyx_CyFunction_Defaults(type, f) \
((type *)(((__pyx_CyFunctionObject *) (f))->defaults))
#define __Pyx_CyFunction_SetDefaultsGetter(f, g) \
((__pyx_CyFunctionObject *) (f))->defaults_getter = (g)
typedef struct {
PyCFunctionObject func;
PyObject *func_dict;
PyObject *func_weakreflist;
PyObject *func_name;
PyObject *func_qualname;
PyObject *func_doc;
PyObject *func_globals;
PyObject *func_code;
PyObject *func_closure;
PyObject *func_classobj; /* No-args super() class cell */
void *defaults;
int defaults_pyobjects;
int flags;
PyObject *defaults_tuple; /* Const defaults tuple */
PyObject *defaults_kwdict; /* Const kwonly defaults dict */
PyObject *(*defaults_getter)(PyObject *);
PyObject *func_annotations; /* function annotations dict */
} __pyx_CyFunctionObject;
static PyTypeObject *__pyx_CyFunctionType = 0;
#define __Pyx_CyFunction_NewEx(ml, flags, qualname, self, module, globals, code) \
__Pyx_CyFunction_New(__pyx_CyFunctionType, ml, flags, qualname, self, module, globals, code)
static PyObject *__Pyx_CyFunction_New(PyTypeObject *, PyMethodDef *ml,
int flags, PyObject* qualname,
PyObject *self,
PyObject *module, PyObject *globals,
PyObject* code);
static CYTHON_INLINE void *__Pyx_CyFunction_InitDefaults(PyObject *m,
size_t size,
int pyobjects);
static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsTuple(PyObject *m,
PyObject *tuple);
static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsKwDict(PyObject *m,
PyObject *dict);
static CYTHON_INLINE void __Pyx_CyFunction_SetAnnotationsDict(PyObject *m,
PyObject *dict);
static int __Pyx_CyFunction_init(void);
typedef struct {
__pyx_CyFunctionObject func;
PyObject *__signatures__;
PyObject *type;
PyObject *self;
} __pyx_FusedFunctionObject;
#define __pyx_FusedFunction_NewEx(ml, flags, qualname, self, module, globals, code) \
__pyx_FusedFunction_New(__pyx_FusedFunctionType, ml, flags, qualname, self, module, globals, code)
static PyObject *__pyx_FusedFunction_New(PyTypeObject *type,
PyMethodDef *ml, int flags,
PyObject *qualname, PyObject *self,
PyObject *module, PyObject *globals,
PyObject *code);
static int __pyx_FusedFunction_clear(__pyx_FusedFunctionObject *self);
static PyTypeObject *__pyx_FusedFunctionType = NULL;
static int __pyx_FusedFunction_init(void);
#define __Pyx_FusedFunction_USED
static int __pyx_typeinfo_cmp(__Pyx_TypeInfo *a, __Pyx_TypeInfo *b);
static int __Pyx_ValidateAndInit_memviewslice(
int *axes_specs,
int c_or_f_flag,
int buf_flags,
int ndim,
__Pyx_TypeInfo *dtype,
__Pyx_BufFmt_StackElem stack[],
__Pyx_memviewslice *memviewslice,
PyObject *original_obj);
static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dsds_float(PyObject *);
static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dsds_double(PyObject *);
static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level); /*proto*/
static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dc_float(PyObject *);
static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dc_double(PyObject *);
typedef struct {
Py_ssize_t shape, strides, suboffsets;
} __Pyx_Buf_DimInfo;
typedef struct {
size_t refcount;
Py_buffer pybuffer;
} __Pyx_Buffer;
typedef struct {
__Pyx_Buffer *rcbuffer;
char *data;
__Pyx_Buf_DimInfo diminfo[8];
} __Pyx_LocalBuf_ND;
#if PY_MAJOR_VERSION < 3
static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags);
static void __Pyx_ReleaseBuffer(Py_buffer *view);
#else
#define __Pyx_GetBuffer PyObject_GetBuffer
#define __Pyx_ReleaseBuffer PyBuffer_Release
#endif
static Py_ssize_t __Pyx_zeros[] = {0, 0, 0, 0, 0, 0, 0, 0};
static Py_ssize_t __Pyx_minusones[] = {-1, -1, -1, -1, -1, -1, -1, -1};
static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_ds_int(PyObject *);
static CYTHON_INLINE Py_intptr_t __Pyx_PyInt_As_Py_intptr_t(PyObject *);
static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_d_dc_double(PyObject *);
static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value);
static CYTHON_INLINE char __Pyx_PyInt_As_char(PyObject *);
static CYTHON_INLINE PyObject* __Pyx_PyInt_From_char(char value);
static CYTHON_INLINE PyObject* __Pyx_PyInt_From_Py_intptr_t(Py_intptr_t value);
static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value);
#if CYTHON_CCOMPLEX
#ifdef __cplusplus
#define __Pyx_CREAL(z) ((z).real())
#define __Pyx_CIMAG(z) ((z).imag())
#else
#define __Pyx_CREAL(z) (__real__(z))
#define __Pyx_CIMAG(z) (__imag__(z))
#endif
#else
#define __Pyx_CREAL(z) ((z).real)
#define __Pyx_CIMAG(z) ((z).imag)
#endif
#if (defined(_WIN32) || defined(__clang__)) && defined(__cplusplus) && CYTHON_CCOMPLEX
#define __Pyx_SET_CREAL(z,x) ((z).real(x))
#define __Pyx_SET_CIMAG(z,y) ((z).imag(y))
#else
#define __Pyx_SET_CREAL(z,x) __Pyx_CREAL(z) = (x)
#define __Pyx_SET_CIMAG(z,y) __Pyx_CIMAG(z) = (y)
#endif
static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float, float);
#if CYTHON_CCOMPLEX
#define __Pyx_c_eqf(a, b) ((a)==(b))
#define __Pyx_c_sumf(a, b) ((a)+(b))
#define __Pyx_c_difff(a, b) ((a)-(b))
#define __Pyx_c_prodf(a, b) ((a)*(b))
#define __Pyx_c_quotf(a, b) ((a)/(b))
#define __Pyx_c_negf(a) (-(a))
#ifdef __cplusplus
#define __Pyx_c_is_zerof(z) ((z)==(float)0)
#define __Pyx_c_conjf(z) (::std::conj(z))
#if 1
#define __Pyx_c_absf(z) (::std::abs(z))
#define __Pyx_c_powf(a, b) (::std::pow(a, b))
#endif
#else
#define __Pyx_c_is_zerof(z) ((z)==0)
#define __Pyx_c_conjf(z) (conjf(z))
#if 1
#define __Pyx_c_absf(z) (cabsf(z))
#define __Pyx_c_powf(a, b) (cpowf(a, b))
#endif
#endif
#else
static CYTHON_INLINE int __Pyx_c_eqf(__pyx_t_float_complex, __pyx_t_float_complex);
static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_sumf(__pyx_t_float_complex, __pyx_t_float_complex);
static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_difff(__pyx_t_float_complex, __pyx_t_float_complex);
static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_prodf(__pyx_t_float_complex, __pyx_t_float_complex);
static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_quotf(__pyx_t_float_complex, __pyx_t_float_complex);
static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_negf(__pyx_t_float_complex);
static CYTHON_INLINE int __Pyx_c_is_zerof(__pyx_t_float_complex);
static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_conjf(__pyx_t_float_complex);
#if 1
static CYTHON_INLINE float __Pyx_c_absf(__pyx_t_float_complex);
static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_powf(__pyx_t_float_complex, __pyx_t_float_complex);
#endif
#endif
static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double, double);
#if CYTHON_CCOMPLEX
#define __Pyx_c_eq(a, b) ((a)==(b))
#define __Pyx_c_sum(a, b) ((a)+(b))
#define __Pyx_c_diff(a, b) ((a)-(b))
#define __Pyx_c_prod(a, b) ((a)*(b))
#define __Pyx_c_quot(a, b) ((a)/(b))
#define __Pyx_c_neg(a) (-(a))
#ifdef __cplusplus
#define __Pyx_c_is_zero(z) ((z)==(double)0)
#define __Pyx_c_conj(z) (::std::conj(z))
#if 1
#define __Pyx_c_abs(z) (::std::abs(z))
#define __Pyx_c_pow(a, b) (::std::pow(a, b))
#endif
#else
#define __Pyx_c_is_zero(z) ((z)==0)
#define __Pyx_c_conj(z) (conj(z))
#if 1
#define __Pyx_c_abs(z) (cabs(z))
#define __Pyx_c_pow(a, b) (cpow(a, b))
#endif
#endif
#else
static CYTHON_INLINE int __Pyx_c_eq(__pyx_t_double_complex, __pyx_t_double_complex);
static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_sum(__pyx_t_double_complex, __pyx_t_double_complex);
static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_diff(__pyx_t_double_complex, __pyx_t_double_complex);
static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_prod(__pyx_t_double_complex, __pyx_t_double_complex);
static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_quot(__pyx_t_double_complex, __pyx_t_double_complex);
static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_neg(__pyx_t_double_complex);
static CYTHON_INLINE int __Pyx_c_is_zero(__pyx_t_double_complex);
static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_conj(__pyx_t_double_complex);
#if 1
static CYTHON_INLINE double __Pyx_c_abs(__pyx_t_double_complex);
static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_pow(__pyx_t_double_complex, __pyx_t_double_complex);
#endif
#endif
static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *);
static int __pyx_memviewslice_is_contig(const __Pyx_memviewslice *mvs,
char order, int ndim);
static int __pyx_slices_overlap(__Pyx_memviewslice *slice1,
__Pyx_memviewslice *slice2,
int ndim, size_t itemsize);
static __Pyx_memviewslice
__pyx_memoryview_copy_new_contig(const __Pyx_memviewslice *from_mvs,
const char *mode, int ndim,
size_t sizeof_dtype, int contig_flag,
int dtype_is_object);
static CYTHON_INLINE PyObject *__pyx_capsule_create(void *p, const char *sig);
static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *);
static int __Pyx_check_binary_version(void);
#if !defined(__Pyx_PyIdentifier_FromString)
#if PY_MAJOR_VERSION < 3
#define __Pyx_PyIdentifier_FromString(s) PyString_FromString(s)
#else
#define __Pyx_PyIdentifier_FromString(s) PyUnicode_FromString(s)
#endif
#endif
static PyObject *__Pyx_ImportModule(const char *name); /*proto*/
static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name, size_t size, int strict); /*proto*/
typedef struct {
int code_line;
PyCodeObject* code_object;
} __Pyx_CodeObjectCacheEntry;
struct __Pyx_CodeObjectCache {
int count;
int max_count;
__Pyx_CodeObjectCacheEntry* entries;
};
static struct __Pyx_CodeObjectCache __pyx_code_cache = {0,0,NULL};
static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line);
static PyCodeObject *__pyx_find_code_object(int code_line);
static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object);
static void __Pyx_AddTraceback(const char *funcname, int c_line,
int py_line, const char *filename); /*proto*/
static int __Pyx_InitStrings(__Pyx_StringTabEntry *t); /*proto*/
/* Module declarations from 'libc.string' */
/* Module declarations from 'cpython.buffer' */
/* Module declarations from 'cpython.ref' */
/* Module declarations from 'libc.stdio' */
/* Module declarations from 'cpython.object' */
/* Module declarations from '__builtin__' */
/* Module declarations from 'cpython.type' */
static PyTypeObject *__pyx_ptype_7cpython_4type_type = 0;
/* Module declarations from 'libc.stdlib' */
/* Module declarations from 'numpy' */
/* Module declarations from 'numpy' */
static PyTypeObject *__pyx_ptype_5numpy_dtype = 0;
static PyTypeObject *__pyx_ptype_5numpy_flatiter = 0;
static PyTypeObject *__pyx_ptype_5numpy_broadcast = 0;
static PyTypeObject *__pyx_ptype_5numpy_ndarray = 0;
static PyTypeObject *__pyx_ptype_5numpy_ufunc = 0;
static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *, char *, char *, int *); /*proto*/
/* Module declarations from 'sklearn.metrics.pairwise_fast' */
static PyTypeObject *__pyx_array_type = 0;
static PyTypeObject *__pyx_MemviewEnum_type = 0;
static PyTypeObject *__pyx_memoryview_type = 0;
static PyTypeObject *__pyx_memoryviewslice_type = 0;
static PyObject *generic = 0;
static PyObject *strided = 0;
static PyObject *indirect = 0;
static PyObject *contiguous = 0;
static PyObject *indirect_contiguous = 0;
static struct __pyx_array_obj *__pyx_array_new(PyObject *, Py_ssize_t, char *, char *, char *); /*proto*/
static void *__pyx_align_pointer(void *, size_t); /*proto*/
static PyObject *__pyx_memoryview_new(PyObject *, int, int, __Pyx_TypeInfo *); /*proto*/
static CYTHON_INLINE int __pyx_memoryview_check(PyObject *); /*proto*/
static PyObject *_unellipsify(PyObject *, int); /*proto*/
static PyObject *assert_direct_dimensions(Py_ssize_t *, int); /*proto*/
static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_obj *, PyObject *); /*proto*/
static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *, Py_ssize_t, Py_ssize_t, Py_ssize_t, int, int, int *, Py_ssize_t, Py_ssize_t, Py_ssize_t, int, int, int, int); /*proto*/
static char *__pyx_pybuffer_index(Py_buffer *, char *, Py_ssize_t, Py_ssize_t); /*proto*/
static int __pyx_memslice_transpose(__Pyx_memviewslice *); /*proto*/
static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice, int, PyObject *(*)(char *), int (*)(char *, PyObject *), int); /*proto*/
static __Pyx_memviewslice *__pyx_memoryview_get_slice_from_memoryview(struct __pyx_memoryview_obj *, __Pyx_memviewslice *); /*proto*/
static void __pyx_memoryview_slice_copy(struct __pyx_memoryview_obj *, __Pyx_memviewslice *); /*proto*/
static PyObject *__pyx_memoryview_copy_object(struct __pyx_memoryview_obj *); /*proto*/
static PyObject *__pyx_memoryview_copy_object_from_slice(struct __pyx_memoryview_obj *, __Pyx_memviewslice *); /*proto*/
static Py_ssize_t abs_py_ssize_t(Py_ssize_t); /*proto*/
static char __pyx_get_best_slice_order(__Pyx_memviewslice *, int); /*proto*/
static void _copy_strided_to_strided(char *, Py_ssize_t *, char *, Py_ssize_t *, Py_ssize_t *, Py_ssize_t *, int, size_t); /*proto*/
static void copy_strided_to_strided(__Pyx_memviewslice *, __Pyx_memviewslice *, int, size_t); /*proto*/
static Py_ssize_t __pyx_memoryview_slice_get_size(__Pyx_memviewslice *, int); /*proto*/
static Py_ssize_t __pyx_fill_contig_strides_array(Py_ssize_t *, Py_ssize_t *, Py_ssize_t, int, char); /*proto*/
static void *__pyx_memoryview_copy_data_to_temp(__Pyx_memviewslice *, __Pyx_memviewslice *, char, int); /*proto*/
static int __pyx_memoryview_err_extents(int, Py_ssize_t, Py_ssize_t); /*proto*/
static int __pyx_memoryview_err_dim(PyObject *, char *, int); /*proto*/
static int __pyx_memoryview_err(PyObject *, char *); /*proto*/
static int __pyx_memoryview_copy_contents(__Pyx_memviewslice, __Pyx_memviewslice, int, int, int); /*proto*/
static void __pyx_memoryview_broadcast_leading(__Pyx_memviewslice *, int, int); /*proto*/
static void __pyx_memoryview_refcount_copying(__Pyx_memviewslice *, int, int, int); /*proto*/
static void __pyx_memoryview_refcount_objects_in_slice_with_gil(char *, Py_ssize_t *, Py_ssize_t *, int, int); /*proto*/
static void __pyx_memoryview_refcount_objects_in_slice(char *, Py_ssize_t *, Py_ssize_t *, int, int); /*proto*/
static void __pyx_memoryview_slice_assign_scalar(__Pyx_memviewslice *, int, size_t, void *, int); /*proto*/
static void __pyx_memoryview__slice_assign_scalar(char *, Py_ssize_t *, Py_ssize_t *, int, size_t, void *); /*proto*/
static __Pyx_TypeInfo __Pyx_TypeInfo_float = { "float", NULL, sizeof(float), { 0 }, 0, 'R', 0, 0 };
static __Pyx_TypeInfo __Pyx_TypeInfo_double = { "double", NULL, sizeof(double), { 0 }, 0, 'R', 0, 0 };
static __Pyx_TypeInfo __Pyx_TypeInfo_int = { "int", NULL, sizeof(int), { 0 }, 0, IS_UNSIGNED(int) ? 'U' : 'I', IS_UNSIGNED(int), 0 };
#define __Pyx_MODULE_NAME "sklearn.metrics.pairwise_fast"
int __pyx_module_is_main_sklearn__metrics__pairwise_fast = 0;
/* Implementation of 'sklearn.metrics.pairwise_fast' */
static PyObject *__pyx_builtin_ImportError;
static PyObject *__pyx_builtin_TypeError;
static PyObject *__pyx_builtin_ord;
static PyObject *__pyx_builtin_zip;
static PyObject *__pyx_builtin_range;
static PyObject *__pyx_builtin_ValueError;
static PyObject *__pyx_builtin_RuntimeError;
static PyObject *__pyx_builtin_MemoryError;
static PyObject *__pyx_builtin_enumerate;
static PyObject *__pyx_builtin_Ellipsis;
static PyObject *__pyx_builtin_xrange;
static PyObject *__pyx_builtin_id;
static PyObject *__pyx_builtin_IndexError;
static PyObject *__pyx_pf_7sklearn_7metrics_13pairwise_fast__chi2_kernel_fast(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_signatures, PyObject *__pyx_v_args, PyObject *__pyx_v_kwargs, CYTHON_UNUSED PyObject *__pyx_v_defaults); /* proto */
static PyObject *__pyx_pf_7sklearn_7metrics_13pairwise_fast_4_chi2_kernel_fast(CYTHON_UNUSED PyObject *__pyx_self, __pyx_t_7sklearn_7metrics_13pairwise_fast_float_array_2d_t __pyx_v_X, __pyx_t_7sklearn_7metrics_13pairwise_fast_float_array_2d_t __pyx_v_Y, __pyx_t_7sklearn_7metrics_13pairwise_fast_float_array_2d_t __pyx_v_result); /* proto */
static PyObject *__pyx_pf_7sklearn_7metrics_13pairwise_fast_6_chi2_kernel_fast(CYTHON_UNUSED PyObject *__pyx_self, __pyx_t_7sklearn_7metrics_13pairwise_fast_double_array_2d_t __pyx_v_X, __pyx_t_7sklearn_7metrics_13pairwise_fast_double_array_2d_t __pyx_v_Y, __pyx_t_7sklearn_7metrics_13pairwise_fast_double_array_2d_t __pyx_v_result); /* proto */
static PyObject *__pyx_pf_7sklearn_7metrics_13pairwise_fast_2_sparse_manhattan(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_signatures, PyObject *__pyx_v_args, PyObject *__pyx_v_kwargs, CYTHON_UNUSED PyObject *__pyx_v_defaults); /* proto */
static PyObject *__pyx_pf_7sklearn_7metrics_13pairwise_fast_10_sparse_manhattan(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_X_data, __Pyx_memviewslice __pyx_v_X_indices, __Pyx_memviewslice __pyx_v_X_indptr, __Pyx_memviewslice __pyx_v_Y_data, __Pyx_memviewslice __pyx_v_Y_indices, __Pyx_memviewslice __pyx_v_Y_indptr, npy_intp __pyx_v_n_features, __Pyx_memviewslice __pyx_v_D); /* proto */
static PyObject *__pyx_pf_7sklearn_7metrics_13pairwise_fast_12_sparse_manhattan(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_X_data, __Pyx_memviewslice __pyx_v_X_indices, __Pyx_memviewslice __pyx_v_X_indptr, __Pyx_memviewslice __pyx_v_Y_data, __Pyx_memviewslice __pyx_v_Y_indices, __Pyx_memviewslice __pyx_v_Y_indptr, npy_intp __pyx_v_n_features, __Pyx_memviewslice __pyx_v_D); /* proto */
static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /* proto */
static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info); /* proto */
static int __pyx_array_MemoryView_5array___cinit__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_shape, Py_ssize_t __pyx_v_itemsize, PyObject *__pyx_v_format, PyObject *__pyx_v_mode, int __pyx_v_allocate_buffer); /* proto */
static int __pyx_array_getbuffer_MemoryView_5array_2__getbuffer__(struct __pyx_array_obj *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /* proto */
static void __pyx_array_MemoryView_5array_4__dealloc__(struct __pyx_array_obj *__pyx_v_self); /* proto */
static PyObject *get_memview_MemoryView_5array_7memview___get__(struct __pyx_array_obj *__pyx_v_self); /* proto */
static PyObject *__pyx_array_MemoryView_5array_6__getattr__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_attr); /* proto */
static PyObject *__pyx_array_MemoryView_5array_8__getitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item); /* proto */
static int __pyx_array_MemoryView_5array_10__setitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item, PyObject *__pyx_v_value); /* proto */
static int __pyx_MemviewEnum_MemoryView_4Enum___init__(struct __pyx_MemviewEnum_obj *__pyx_v_self, PyObject *__pyx_v_name); /* proto */
static PyObject *__pyx_MemviewEnum_MemoryView_4Enum_2__repr__(struct __pyx_MemviewEnum_obj *__pyx_v_self); /* proto */
static int __pyx_memoryview_MemoryView_10memoryview___cinit__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_obj, int __pyx_v_flags, int __pyx_v_dtype_is_object); /* proto */
static void __pyx_memoryview_MemoryView_10memoryview_2__dealloc__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */
static PyObject *__pyx_memoryview_MemoryView_10memoryview_4__getitem__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index); /* proto */
static int __pyx_memoryview_MemoryView_10memoryview_6__setitem__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value); /* proto */
static int __pyx_memoryview_getbuffer_MemoryView_10memoryview_8__getbuffer__(struct __pyx_memoryview_obj *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /* proto */
static PyObject *__pyx_memoryview_transpose_MemoryView_10memoryview_1T___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */
static PyObject *__pyx_memoryview__get__base_MemoryView_10memoryview_4base___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */
static PyObject *__pyx_memoryview_get_shape_MemoryView_10memoryview_5shape___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */
static PyObject *__pyx_memoryview_get_strides_MemoryView_10memoryview_7strides___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */
static PyObject *__pyx_memoryview_get_suboffsets_MemoryView_10memoryview_10suboffsets___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */
static PyObject *__pyx_memoryview_get_ndim_MemoryView_10memoryview_4ndim___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */
static PyObject *__pyx_memoryview_get_itemsize_MemoryView_10memoryview_8itemsize___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */
static PyObject *__pyx_memoryview_get_nbytes_MemoryView_10memoryview_6nbytes___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */
static PyObject *__pyx_memoryview_get_size_MemoryView_10memoryview_4size___get__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */
static Py_ssize_t __pyx_memoryview_MemoryView_10memoryview_10__len__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */
static PyObject *__pyx_memoryview_MemoryView_10memoryview_12__repr__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */
static PyObject *__pyx_memoryview_MemoryView_10memoryview_14__str__(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */
static PyObject *__pyx_memoryview_MemoryView_10memoryview_16is_c_contig(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */
static PyObject *__pyx_memoryview_MemoryView_10memoryview_18is_f_contig(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */
static PyObject *__pyx_memoryview_MemoryView_10memoryview_20copy(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */
static PyObject *__pyx_memoryview_MemoryView_10memoryview_22copy_fortran(struct __pyx_memoryview_obj *__pyx_v_self); /* proto */
static void __pyx_memoryviewslice_MemoryView_16_memoryviewslice___dealloc__(struct __pyx_memoryviewslice_obj *__pyx_v_self); /* proto */
static PyObject *__pyx_memoryviewslice__get__base_MemoryView_16_memoryviewslice_4base___get__(struct __pyx_memoryviewslice_obj *__pyx_v_self); /* proto */
static PyObject *__pyx_tp_new_array(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/
static PyObject *__pyx_tp_new_Enum(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/
static PyObject *__pyx_tp_new_memoryview(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/
static PyObject *__pyx_tp_new__memoryviewslice(PyTypeObject *t, PyObject *a, PyObject *k); /*proto*/
static char __pyx_k_B[] = "B";
static char __pyx_k_D[] = "D";
static char __pyx_k_H[] = "H";
static char __pyx_k_I[] = "I";
static char __pyx_k_L[] = "L";
static char __pyx_k_O[] = "O";
static char __pyx_k_Q[] = "Q";
static char __pyx_k_X[] = "X";
static char __pyx_k_Y[] = "Y";
static char __pyx_k_b[] = "b";
static char __pyx_k_c[] = "c";
static char __pyx_k_d[] = "d";
static char __pyx_k_f[] = "f";
static char __pyx_k_g[] = "g";
static char __pyx_k_h[] = "h";
static char __pyx_k_i[] = "i";
static char __pyx_k_j[] = "j";
static char __pyx_k_k[] = "k";
static char __pyx_k_l[] = "l";
static char __pyx_k_q[] = "q";
static char __pyx_k_u[] = "u";
static char __pyx_k_Zd[] = "Zd";
static char __pyx_k_Zf[] = "Zf";
static char __pyx_k_Zg[] = "Zg";
static char __pyx_k__2[] = "()";
static char __pyx_k__4[] = "|";
static char __pyx_k_id[] = "id";
static char __pyx_k_ix[] = "ix";
static char __pyx_k_iy[] = "iy";
static char __pyx_k_np[] = "np";
static char __pyx_k_nom[] = "nom";
static char __pyx_k_obj[] = "obj";
static char __pyx_k_ord[] = "ord";
static char __pyx_k_res[] = "res";
static char __pyx_k_row[] = "row";
static char __pyx_k_zip[] = "zip";
static char __pyx_k_args[] = "args";
static char __pyx_k_base[] = "base";
static char __pyx_k_kind[] = "kind";
static char __pyx_k_main[] = "__main__";
static char __pyx_k_mode[] = "mode";
static char __pyx_k_name[] = "name";
static char __pyx_k_ndim[] = "ndim";
static char __pyx_k_pack[] = "pack";
static char __pyx_k_size[] = "size";
static char __pyx_k_step[] = "step";
static char __pyx_k_stop[] = "stop";
static char __pyx_k_test[] = "__test__";
static char __pyx_k_ASCII[] = "ASCII";
static char __pyx_k_class[] = "__class__";
static char __pyx_k_denom[] = "denom";
static char __pyx_k_dtype[] = "dtype";
static char __pyx_k_empty[] = "empty";
static char __pyx_k_error[] = "error";
static char __pyx_k_flags[] = "flags";
static char __pyx_k_numpy[] = "numpy";
static char __pyx_k_range[] = "range";
static char __pyx_k_shape[] = "shape";
static char __pyx_k_split[] = "split";
static char __pyx_k_start[] = "start";
static char __pyx_k_strip[] = "strip";
static char __pyx_k_X_data[] = "X_data";
static char __pyx_k_Y_data[] = "Y_data";
static char __pyx_k_decode[] = "decode";
static char __pyx_k_encode[] = "encode";
static char __pyx_k_format[] = "format";
static char __pyx_k_import[] = "__import__";
static char __pyx_k_kwargs[] = "kwargs";
static char __pyx_k_name_2[] = "__name__";
static char __pyx_k_result[] = "result";
static char __pyx_k_struct[] = "struct";
static char __pyx_k_unpack[] = "unpack";
static char __pyx_k_xrange[] = "xrange";
static char __pyx_k_float_1[] = "float[::1]";
static char __pyx_k_fortran[] = "fortran";
static char __pyx_k_memview[] = "memview";
static char __pyx_k_ndarray[] = "ndarray";
static char __pyx_k_Ellipsis[] = "Ellipsis";
static char __pyx_k_X_indptr[] = "X_indptr";
static char __pyx_k_Y_indptr[] = "Y_indptr";
static char __pyx_k_defaults[] = "defaults";
static char __pyx_k_double_1[] = "double[::1]";
static char __pyx_k_itemsize[] = "itemsize";
static char __pyx_k_TypeError[] = "TypeError";
static char __pyx_k_X_indices[] = "X_indices";
static char __pyx_k_Y_indices[] = "Y_indices";
static char __pyx_k_enumerate[] = "enumerate";
static char __pyx_k_IndexError[] = "IndexError";
static char __pyx_k_ValueError[] = "ValueError";
static char __pyx_k_n_features[] = "n_features";
static char __pyx_k_pyx_vtable[] = "__pyx_vtable__";
static char __pyx_k_signatures[] = "signatures";
static char __pyx_k_ImportError[] = "ImportError";
static char __pyx_k_MemoryError[] = "MemoryError";
static char __pyx_k_n_samples_X[] = "n_samples_X";
static char __pyx_k_n_samples_Y[] = "n_samples_Y";
static char __pyx_k_RuntimeError[] = "RuntimeError";
static char __pyx_k_pyx_getbuffer[] = "__pyx_getbuffer";
static char __pyx_k_allocate_buffer[] = "allocate_buffer";
static char __pyx_k_dtype_is_object[] = "dtype_is_object";
static char __pyx_k_chi2_kernel_fast[] = "_chi2_kernel_fast";
static char __pyx_k_float_array_2d_t[] = "float_array_2d_t";
static char __pyx_k_sparse_manhattan[] = "_sparse_manhattan";
static char __pyx_k_double_array_2d_t[] = "double_array_2d_t";
static char __pyx_k_pyx_releasebuffer[] = "__pyx_releasebuffer";
static char __pyx_k_strided_and_direct[] = "<strided and direct>";
static char __pyx_k_strided_and_indirect[] = "<strided and indirect>";
static char __pyx_k_contiguous_and_direct[] = "<contiguous and direct>";
static char __pyx_k_MemoryView_of_r_object[] = "<MemoryView of %r object>";
static char __pyx_k_MemoryView_of_r_at_0x_x[] = "<MemoryView of %r at 0x%x>";
static char __pyx_k_contiguous_and_indirect[] = "<contiguous and indirect>";
static char __pyx_k_Cannot_index_with_type_s[] = "Cannot index with type '%s'";
static char __pyx_k_getbuffer_obj_view_flags[] = "getbuffer(obj, view, flags)";
static char __pyx_k_sparse_manhattan_line_53[] = "_sparse_manhattan (line 53)";
static char __pyx_k_Dimension_d_is_not_direct[] = "Dimension %d is not direct";
static char __pyx_k_Invalid_shape_in_axis_d_d[] = "Invalid shape in axis %d: %d.";
static char __pyx_k_Index_out_of_bounds_axis_d[] = "Index out of bounds (axis %d)";
static char __pyx_k_No_matching_signature_found[] = "No matching signature found";
static char __pyx_k_Step_may_not_be_zero_axis_d[] = "Step may not be zero (axis %d)";
static char __pyx_k_itemsize_0_for_cython_array[] = "itemsize <= 0 for cython.array";
static char __pyx_k_ndarray_is_not_C_contiguous[] = "ndarray is not C contiguous";
static char __pyx_k_Expected_at_least_d_arguments[] = "Expected at least %d arguments";
static char __pyx_k_sklearn_metrics_pairwise_fast[] = "sklearn.metrics.pairwise_fast";
static char __pyx_k_unable_to_allocate_array_data[] = "unable to allocate array data.";
static char __pyx_k_strided_and_direct_or_indirect[] = "<strided and direct or indirect>";
static char __pyx_k_home_larsb_src_scikit_learn_skl[] = "/home/larsb/src/scikit-learn/sklearn/metrics/pairwise_fast.pyx";
static char __pyx_k_unknown_dtype_code_in_numpy_pxd[] = "unknown dtype code in numpy.pxd (%d)";
static char __pyx_k_All_dimensions_preceding_dimensi[] = "All dimensions preceding dimension %d must be indexed and not sliced";
static char __pyx_k_Buffer_view_does_not_expose_stri[] = "Buffer view does not expose strides";
static char __pyx_k_Can_only_create_a_buffer_that_is[] = "Can only create a buffer that is contiguous in memory.";
static char __pyx_k_Cannot_transpose_memoryview_with[] = "Cannot transpose memoryview with indirect dimensions";
static char __pyx_k_Empty_shape_tuple_for_cython_arr[] = "Empty shape tuple for cython.array";
static char __pyx_k_Format_string_allocated_too_shor[] = "Format string allocated too short, see comment in numpy.pxd";
static char __pyx_k_Function_call_with_ambiguous_arg[] = "Function call with ambiguous argument types";
static char __pyx_k_Indirect_dimensions_not_supporte[] = "Indirect dimensions not supported";
static char __pyx_k_Invalid_mode_expected_c_or_fortr[] = "Invalid mode, expected 'c' or 'fortran', got %s";
static char __pyx_k_Non_native_byte_order_not_suppor[] = "Non-native byte order not supported";
static char __pyx_k_Out_of_bounds_on_buffer_access_a[] = "Out of bounds on buffer access (axis %d)";
static char __pyx_k_Pairwise_L1_distances_for_CSR_ma[] = "Pairwise L1 distances for CSR matrices.\n\n Usage:\n\n >>> D = np.zeros(X.shape[0], Y.shape[0])\n >>> sparse_manhattan(X.data, X.indices, X.indptr,\n ... Y.data, Y.indices, Y.indptr,\n ... X.shape[1], D)\n ";
static char __pyx_k_Unable_to_convert_item_to_object[] = "Unable to convert item to object";
static char __pyx_k_got_differing_extents_in_dimensi[] = "got differing extents in dimension %d (got %d and %d)";
static char __pyx_k_ndarray_is_not_Fortran_contiguou[] = "ndarray is not Fortran contiguous";
static char __pyx_k_unable_to_allocate_shape_or_stri[] = "unable to allocate shape or strides.";
static char __pyx_k_Format_string_allocated_too_shor_2[] = "Format string allocated too short.";
static PyObject *__pyx_n_s_ASCII;
static PyObject *__pyx_kp_s_Buffer_view_does_not_expose_stri;
static PyObject *__pyx_kp_s_Can_only_create_a_buffer_that_is;
static PyObject *__pyx_kp_s_Cannot_index_with_type_s;
static PyObject *__pyx_n_s_D;
static PyObject *__pyx_n_s_Ellipsis;
static PyObject *__pyx_kp_s_Empty_shape_tuple_for_cython_arr;
static PyObject *__pyx_kp_s_Expected_at_least_d_arguments;
static PyObject *__pyx_kp_u_Format_string_allocated_too_shor;
static PyObject *__pyx_kp_u_Format_string_allocated_too_shor_2;
static PyObject *__pyx_kp_s_Function_call_with_ambiguous_arg;
static PyObject *__pyx_n_s_ImportError;
static PyObject *__pyx_n_s_IndexError;
static PyObject *__pyx_kp_s_Indirect_dimensions_not_supporte;
static PyObject *__pyx_kp_s_Invalid_mode_expected_c_or_fortr;
static PyObject *__pyx_kp_s_Invalid_shape_in_axis_d_d;
static PyObject *__pyx_n_s_MemoryError;
static PyObject *__pyx_kp_s_MemoryView_of_r_at_0x_x;
static PyObject *__pyx_kp_s_MemoryView_of_r_object;
static PyObject *__pyx_kp_s_No_matching_signature_found;
static PyObject *__pyx_kp_u_Non_native_byte_order_not_suppor;
static PyObject *__pyx_n_b_O;
static PyObject *__pyx_n_s_O;
static PyObject *__pyx_kp_s_Out_of_bounds_on_buffer_access_a;
static PyObject *__pyx_kp_u_Pairwise_L1_distances_for_CSR_ma;
static PyObject *__pyx_n_s_RuntimeError;
static PyObject *__pyx_n_s_TypeError;
static PyObject *__pyx_kp_s_Unable_to_convert_item_to_object;
static PyObject *__pyx_n_s_ValueError;
static PyObject *__pyx_n_s_X;
static PyObject *__pyx_n_s_X_data;
static PyObject *__pyx_n_s_X_indices;
static PyObject *__pyx_n_s_X_indptr;
static PyObject *__pyx_n_s_Y;
static PyObject *__pyx_n_s_Y_data;
static PyObject *__pyx_n_s_Y_indices;
static PyObject *__pyx_n_s_Y_indptr;
static PyObject *__pyx_kp_s__2;
static PyObject *__pyx_kp_s__4;
static PyObject *__pyx_n_s_allocate_buffer;
static PyObject *__pyx_n_s_args;
static PyObject *__pyx_n_s_base;
static PyObject *__pyx_n_b_c;
static PyObject *__pyx_n_s_c;
static PyObject *__pyx_n_u_c;
static PyObject *__pyx_n_s_chi2_kernel_fast;
static PyObject *__pyx_n_s_class;
static PyObject *__pyx_kp_s_contiguous_and_direct;
static PyObject *__pyx_kp_s_contiguous_and_indirect;
static PyObject *__pyx_n_s_decode;
static PyObject *__pyx_n_s_defaults;
static PyObject *__pyx_n_s_denom;
static PyObject *__pyx_kp_s_double_1;
static PyObject *__pyx_n_s_double_array_2d_t;
static PyObject *__pyx_n_s_dtype;
static PyObject *__pyx_n_s_dtype_is_object;
static PyObject *__pyx_n_s_empty;
static PyObject *__pyx_n_s_encode;
static PyObject *__pyx_n_s_enumerate;
static PyObject *__pyx_n_s_error;
static PyObject *__pyx_n_s_f;
static PyObject *__pyx_n_s_flags;
static PyObject *__pyx_kp_s_float_1;
static PyObject *__pyx_n_s_float_array_2d_t;
static PyObject *__pyx_n_s_format;
static PyObject *__pyx_n_b_fortran;
static PyObject *__pyx_n_s_fortran;
static PyObject *__pyx_kp_s_got_differing_extents_in_dimensi;
static PyObject *__pyx_kp_s_home_larsb_src_scikit_learn_skl;
static PyObject *__pyx_n_s_i;
static PyObject *__pyx_n_s_id;
static PyObject *__pyx_n_s_import;
static PyObject *__pyx_n_s_itemsize;
static PyObject *__pyx_kp_s_itemsize_0_for_cython_array;
static PyObject *__pyx_n_s_ix;
static PyObject *__pyx_n_s_iy;
static PyObject *__pyx_n_s_j;
static PyObject *__pyx_n_s_k;
static PyObject *__pyx_n_s_kind;
static PyObject *__pyx_n_s_kwargs;
static PyObject *__pyx_n_s_main;
static PyObject *__pyx_n_s_memview;
static PyObject *__pyx_n_s_mode;
static PyObject *__pyx_n_s_n_features;
static PyObject *__pyx_n_s_n_samples_X;
static PyObject *__pyx_n_s_n_samples_Y;
static PyObject *__pyx_n_s_name;
static PyObject *__pyx_n_s_name_2;
static PyObject *__pyx_n_s_ndarray;
static PyObject *__pyx_kp_u_ndarray_is_not_C_contiguous;
static PyObject *__pyx_kp_u_ndarray_is_not_Fortran_contiguou;
static PyObject *__pyx_n_s_ndim;
static PyObject *__pyx_n_s_nom;
static PyObject *__pyx_n_s_np;
static PyObject *__pyx_n_s_numpy;
static PyObject *__pyx_n_s_obj;
static PyObject *__pyx_n_s_ord;
static PyObject *__pyx_n_s_pack;
static PyObject *__pyx_n_s_pyx_getbuffer;
static PyObject *__pyx_n_s_pyx_releasebuffer;
static PyObject *__pyx_n_s_pyx_vtable;
static PyObject *__pyx_n_s_range;
static PyObject *__pyx_n_s_res;
static PyObject *__pyx_n_s_result;
static PyObject *__pyx_n_s_row;
static PyObject *__pyx_n_s_shape;
static PyObject *__pyx_n_s_signatures;
static PyObject *__pyx_n_s_size;
static PyObject *__pyx_n_s_sklearn_metrics_pairwise_fast;
static PyObject *__pyx_n_s_sparse_manhattan;
static PyObject *__pyx_kp_u_sparse_manhattan_line_53;
static PyObject *__pyx_n_s_split;
static PyObject *__pyx_n_s_start;
static PyObject *__pyx_n_s_step;
static PyObject *__pyx_n_s_stop;
static PyObject *__pyx_kp_s_strided_and_direct;
static PyObject *__pyx_kp_s_strided_and_direct_or_indirect;
static PyObject *__pyx_kp_s_strided_and_indirect;
static PyObject *__pyx_n_s_strip;
static PyObject *__pyx_n_s_struct;
static PyObject *__pyx_n_s_test;
static PyObject *__pyx_n_s_u;
static PyObject *__pyx_kp_s_unable_to_allocate_array_data;
static PyObject *__pyx_kp_s_unable_to_allocate_shape_or_stri;
static PyObject *__pyx_kp_u_unknown_dtype_code_in_numpy_pxd;
static PyObject *__pyx_n_s_unpack;
static PyObject *__pyx_n_s_xrange;
static PyObject *__pyx_n_s_zip;
static PyObject *__pyx_int_0;
static PyObject *__pyx_int_1;
static PyObject *__pyx_int_2;
static PyObject *__pyx_int_105;
static PyObject *__pyx_int_neg_1;
static PyObject *__pyx_tuple_;
static PyObject *__pyx_tuple__3;
static PyObject *__pyx_tuple__5;
static PyObject *__pyx_tuple__6;
static PyObject *__pyx_tuple__7;
static PyObject *__pyx_tuple__8;
static PyObject *__pyx_tuple__9;
static PyObject *__pyx_tuple__10;
static PyObject *__pyx_tuple__11;
static PyObject *__pyx_tuple__12;
static PyObject *__pyx_tuple__13;
static PyObject *__pyx_tuple__14;
static PyObject *__pyx_tuple__15;
static PyObject *__pyx_tuple__16;
static PyObject *__pyx_tuple__17;
static PyObject *__pyx_tuple__18;
static PyObject *__pyx_tuple__19;
static PyObject *__pyx_tuple__20;
static PyObject *__pyx_tuple__21;
static PyObject *__pyx_tuple__22;
static PyObject *__pyx_tuple__23;
static PyObject *__pyx_tuple__24;
static PyObject *__pyx_tuple__25;
static PyObject *__pyx_tuple__26;
static PyObject *__pyx_tuple__27;
static PyObject *__pyx_tuple__28;
static PyObject *__pyx_tuple__29;
static PyObject *__pyx_tuple__30;
static PyObject *__pyx_tuple__31;
static PyObject *__pyx_tuple__32;
static PyObject *__pyx_tuple__34;
static PyObject *__pyx_tuple__36;
static PyObject *__pyx_tuple__37;
static PyObject *__pyx_tuple__38;
static PyObject *__pyx_tuple__39;
static PyObject *__pyx_tuple__40;
static PyObject *__pyx_codeobj__33;
static PyObject *__pyx_codeobj__35;
/* "sklearn/metrics/pairwise_fast.pyx":32
*
*
* def _chi2_kernel_fast(floating_array_2d_t X, # <<<<<<<<<<<<<<
* floating_array_2d_t Y,
* floating_array_2d_t result):
*/
/* Python wrapper */
static PyObject *__pyx_pw_7sklearn_7metrics_13pairwise_fast_1_chi2_kernel_fast(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/
static PyMethodDef __pyx_mdef_7sklearn_7metrics_13pairwise_fast_1_chi2_kernel_fast = {__Pyx_NAMESTR("_chi2_kernel_fast"), (PyCFunction)__pyx_pw_7sklearn_7metrics_13pairwise_fast_1_chi2_kernel_fast, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(0)};
static PyObject *__pyx_pw_7sklearn_7metrics_13pairwise_fast_1_chi2_kernel_fast(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) {
PyObject *__pyx_v_signatures = 0;
PyObject *__pyx_v_args = 0;
PyObject *__pyx_v_kwargs = 0;
CYTHON_UNUSED PyObject *__pyx_v_defaults = 0;
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
PyObject *__pyx_r = 0;
__Pyx_RefNannyDeclarations
__Pyx_RefNannySetupContext("__pyx_fused_cpdef (wrapper)", 0);
{
static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_signatures,&__pyx_n_s_args,&__pyx_n_s_kwargs,&__pyx_n_s_defaults,0};
PyObject* values[4] = {0,0,0,0};
if (unlikely(__pyx_kwds)) {
Py_ssize_t kw_args;
const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args);
switch (pos_args) {
case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3);
case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2);
case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1);
case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0);
case 0: break;
default: goto __pyx_L5_argtuple_error;
}
kw_args = PyDict_Size(__pyx_kwds);
switch (pos_args) {
case 0:
if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_signatures)) != 0)) kw_args--;
else goto __pyx_L5_argtuple_error;
case 1:
if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_args)) != 0)) kw_args--;
else {
__Pyx_RaiseArgtupleInvalid("__pyx_fused_cpdef", 1, 4, 4, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
}
case 2:
if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_kwargs)) != 0)) kw_args--;
else {
__Pyx_RaiseArgtupleInvalid("__pyx_fused_cpdef", 1, 4, 4, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
}
case 3:
if (likely((values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_defaults)) != 0)) kw_args--;
else {
__Pyx_RaiseArgtupleInvalid("__pyx_fused_cpdef", 1, 4, 4, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
}
}
if (unlikely(kw_args > 0)) {
if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__pyx_fused_cpdef") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
}
} else if (PyTuple_GET_SIZE(__pyx_args) != 4) {
goto __pyx_L5_argtuple_error;
} else {
values[0] = PyTuple_GET_ITEM(__pyx_args, 0);
values[1] = PyTuple_GET_ITEM(__pyx_args, 1);
values[2] = PyTuple_GET_ITEM(__pyx_args, 2);
values[3] = PyTuple_GET_ITEM(__pyx_args, 3);
}
__pyx_v_signatures = values[0];
__pyx_v_args = values[1];
__pyx_v_kwargs = values[2];
__pyx_v_defaults = values[3];
}
goto __pyx_L4_argument_unpacking_done;
__pyx_L5_argtuple_error:;
__Pyx_RaiseArgtupleInvalid("__pyx_fused_cpdef", 1, 4, 4, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
__pyx_L3_error:;
__Pyx_AddTraceback("sklearn.metrics.pairwise_fast.__pyx_fused_cpdef", __pyx_clineno, __pyx_lineno, __pyx_filename);
__Pyx_RefNannyFinishContext();
return NULL;
__pyx_L4_argument_unpacking_done:;
__pyx_r = __pyx_pf_7sklearn_7metrics_13pairwise_fast__chi2_kernel_fast(__pyx_self, __pyx_v_signatures, __pyx_v_args, __pyx_v_kwargs, __pyx_v_defaults);
/* function exit code */
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
static PyObject *__pyx_pf_7sklearn_7metrics_13pairwise_fast__chi2_kernel_fast(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_signatures, PyObject *__pyx_v_args, PyObject *__pyx_v_kwargs, CYTHON_UNUSED PyObject *__pyx_v_defaults) {
PyObject *__pyx_v_dest_sig = NULL;
PyObject *__pyx_v_numpy = NULL;
__Pyx_memviewslice __pyx_v_memslice;
Py_ssize_t __pyx_v_itemsize;
CYTHON_UNUSED int __pyx_v_dtype_signed;
char __pyx_v_kind;
PyObject *__pyx_v_arg = NULL;
PyObject *__pyx_v_dtype = NULL;
PyObject *__pyx_v_candidates = NULL;
PyObject *__pyx_v_sig = NULL;
int __pyx_v_match_found;
PyObject *__pyx_v_src_type = NULL;
PyObject *__pyx_v_dst_type = NULL;
PyObject *__pyx_r = NULL;
__Pyx_RefNannyDeclarations
PyObject *__pyx_t_1 = NULL;
int __pyx_t_2;
int __pyx_t_3;
PyObject *__pyx_t_4 = NULL;
PyObject *__pyx_t_5 = NULL;
PyObject *__pyx_t_6 = NULL;
int __pyx_t_7;
PyObject *__pyx_t_8 = NULL;
PyObject *__pyx_t_9 = NULL;
Py_ssize_t __pyx_t_10;
int __pyx_t_11;
char __pyx_t_12;
PyObject *(*__pyx_t_13)(PyObject *);
Py_ssize_t __pyx_t_14;
PyObject *(*__pyx_t_15)(PyObject *);
PyObject *__pyx_t_16 = NULL;
PyObject *__pyx_t_17 = NULL;
PyObject *__pyx_t_18 = NULL;
PyObject *(*__pyx_t_19)(PyObject *);
int __pyx_t_20;
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
__Pyx_RefNannySetupContext("_chi2_kernel_fast", 0);
__Pyx_INCREF(__pyx_v_kwargs);
__pyx_t_1 = PyList_New(3); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
__Pyx_INCREF(Py_None);
PyList_SET_ITEM(__pyx_t_1, 0, Py_None);
__Pyx_GIVEREF(Py_None);
__Pyx_INCREF(Py_None);
PyList_SET_ITEM(__pyx_t_1, 1, Py_None);
__Pyx_GIVEREF(Py_None);
__Pyx_INCREF(Py_None);
PyList_SET_ITEM(__pyx_t_1, 2, Py_None);
__Pyx_GIVEREF(Py_None);
__pyx_v_dest_sig = ((PyObject*)__pyx_t_1);
__pyx_t_1 = 0;
__pyx_t_2 = (__pyx_v_kwargs == Py_None);
__pyx_t_3 = (__pyx_t_2 != 0);
if (__pyx_t_3) {
__pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
__Pyx_DECREF_SET(__pyx_v_kwargs, __pyx_t_1);
__pyx_t_1 = 0;
goto __pyx_L3;
}
__pyx_L3:;
{
__Pyx_ExceptionSave(&__pyx_t_4, &__pyx_t_5, &__pyx_t_6);
__Pyx_XGOTREF(__pyx_t_4);
__Pyx_XGOTREF(__pyx_t_5);
__Pyx_XGOTREF(__pyx_t_6);
/*try:*/ {
__pyx_t_1 = __Pyx_Import(__pyx_n_s_numpy, 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L4_error;}
__Pyx_GOTREF(__pyx_t_1);
__pyx_v_numpy = __pyx_t_1;
__pyx_t_1 = 0;
}
__Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0;
__Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0;
__Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0;
goto __pyx_L11_try_end;
__pyx_L4_error:;
__Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0;
__pyx_t_7 = PyErr_ExceptionMatches(__pyx_builtin_ImportError);
if (__pyx_t_7) {
__Pyx_AddTraceback("sklearn.metrics.pairwise_fast.__pyx_fused_cpdef", __pyx_clineno, __pyx_lineno, __pyx_filename);
if (__Pyx_GetException(&__pyx_t_1, &__pyx_t_8, &__pyx_t_9) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L6_except_error;}
__Pyx_GOTREF(__pyx_t_1);
__Pyx_GOTREF(__pyx_t_8);
__Pyx_GOTREF(__pyx_t_9);
__Pyx_INCREF(Py_None);
__Pyx_XDECREF_SET(__pyx_v_numpy, Py_None);
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
__Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0;
__Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0;
goto __pyx_L5_exception_handled;
}
goto __pyx_L6_except_error;
__pyx_L6_except_error:;
__Pyx_XGIVEREF(__pyx_t_4);
__Pyx_XGIVEREF(__pyx_t_5);
__Pyx_XGIVEREF(__pyx_t_6);
__Pyx_ExceptionReset(__pyx_t_4, __pyx_t_5, __pyx_t_6);
goto __pyx_L1_error;
__pyx_L5_exception_handled:;
__Pyx_XGIVEREF(__pyx_t_4);
__Pyx_XGIVEREF(__pyx_t_5);
__Pyx_XGIVEREF(__pyx_t_6);
__Pyx_ExceptionReset(__pyx_t_4, __pyx_t_5, __pyx_t_6);
__pyx_L11_try_end:;
}
__pyx_v_itemsize = -1;
__pyx_t_10 = PyObject_Length(__pyx_v_args); if (unlikely(__pyx_t_10 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_t_3 = ((0 < __pyx_t_10) != 0);
if (__pyx_t_3) {
__pyx_t_9 = __Pyx_GetItemInt(__pyx_v_args, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 0); if (unlikely(__pyx_t_9 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;};
__Pyx_GOTREF(__pyx_t_9);
__pyx_v_arg = __pyx_t_9;
__pyx_t_9 = 0;
goto __pyx_L14;
}
__pyx_t_3 = (__Pyx_PySequence_Contains(__pyx_n_s_X, __pyx_v_kwargs, Py_EQ)); if (unlikely(__pyx_t_3 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_t_2 = (__pyx_t_3 != 0);
if (__pyx_t_2) {
__pyx_t_9 = PyObject_GetItem(__pyx_v_kwargs, __pyx_n_s_X); if (unlikely(__pyx_t_9 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;};
__Pyx_GOTREF(__pyx_t_9);
__pyx_v_arg = __pyx_t_9;
__pyx_t_9 = 0;
goto __pyx_L14;
}
/*else*/ {
__pyx_t_10 = PyObject_Length(__pyx_v_args); if (unlikely(__pyx_t_10 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_t_9 = PyInt_FromSsize_t(__pyx_t_10); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_9);
__pyx_t_8 = __Pyx_PyString_Format(__pyx_kp_s_Expected_at_least_d_arguments, __pyx_t_9); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_8);
__Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0;
__pyx_t_9 = PyTuple_New(1); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_9);
PyTuple_SET_ITEM(__pyx_t_9, 0, __pyx_t_8);
__Pyx_GIVEREF(__pyx_t_8);
__pyx_t_8 = 0;
__pyx_t_8 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_t_9, NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_8);
__Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0;
__Pyx_Raise(__pyx_t_8, 0, 0, 0);
__Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0;
{__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
}
__pyx_L14:;
if (0) {
goto __pyx_L15;
}
/*else*/ {
while (1) {
if (!1) break;
__pyx_t_2 = (__pyx_v_numpy != Py_None);
__pyx_t_3 = (__pyx_t_2 != 0);
if (__pyx_t_3) {
__pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_v_numpy, __pyx_n_s_ndarray); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_8);
__pyx_t_3 = PyObject_IsInstance(__pyx_v_arg, __pyx_t_8); if (unlikely(__pyx_t_3 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0;
__pyx_t_2 = (__pyx_t_3 != 0);
if (__pyx_t_2) {
__pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_v_arg, __pyx_n_s_dtype); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_8);
__pyx_v_dtype = __pyx_t_8;
__pyx_t_8 = 0;
goto __pyx_L19;
}
__pyx_t_2 = (__pyx_memoryview_check(__pyx_v_arg) != 0);
if (__pyx_t_2) {
__pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_v_arg, __pyx_n_s_base); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_8);
__pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_numpy, __pyx_n_s_ndarray); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_9);
__pyx_t_3 = PyObject_IsInstance(__pyx_t_8, __pyx_t_9); if (unlikely(__pyx_t_3 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0;
__Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0;
__pyx_t_11 = (__pyx_t_3 != 0);
} else {
__pyx_t_11 = __pyx_t_2;
}
if (__pyx_t_11) {
__pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_arg, __pyx_n_s_base); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_9);
__pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_t_9, __pyx_n_s_dtype); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_8);
__Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0;
__pyx_v_dtype = __pyx_t_8;
__pyx_t_8 = 0;
goto __pyx_L19;
}
/*else*/ {
__Pyx_INCREF(Py_None);
__pyx_v_dtype = Py_None;
}
__pyx_L19:;
__pyx_v_itemsize = -1;
__pyx_t_11 = (__pyx_v_dtype != Py_None);
__pyx_t_2 = (__pyx_t_11 != 0);
if (__pyx_t_2) {
__pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_v_dtype, __pyx_n_s_itemsize); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_8);
__pyx_t_10 = __Pyx_PyIndex_AsSsize_t(__pyx_t_8); if (unlikely((__pyx_t_10 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0;
__pyx_v_itemsize = __pyx_t_10;
__pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_v_dtype, __pyx_n_s_kind); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_8);
__pyx_t_9 = PyTuple_New(1); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_9);
PyTuple_SET_ITEM(__pyx_t_9, 0, __pyx_t_8);
__Pyx_GIVEREF(__pyx_t_8);
__pyx_t_8 = 0;
__pyx_t_8 = __Pyx_PyObject_Call(__pyx_builtin_ord, __pyx_t_9, NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_8);
__Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0;
__pyx_t_12 = __Pyx_PyInt_As_char(__pyx_t_8); if (unlikely((__pyx_t_12 == (char)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0;
__pyx_v_kind = __pyx_t_12;
__pyx_t_8 = __Pyx_PyInt_From_char(__pyx_v_kind); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_8);
__pyx_t_9 = PyObject_RichCompare(__pyx_t_8, __pyx_int_105, Py_EQ); __Pyx_XGOTREF(__pyx_t_9); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0;
__pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_t_9); if (unlikely((__pyx_t_2 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0;
__pyx_v_dtype_signed = __pyx_t_2;
__pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_dtype, __pyx_n_s_kind); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_9);
__pyx_t_2 = (__Pyx_PySequence_Contains(__pyx_t_9, __pyx_tuple_, Py_EQ)); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0;
__pyx_t_11 = (__pyx_t_2 != 0);
if (__pyx_t_11) {
goto __pyx_L21;
}
__pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_dtype, __pyx_n_s_kind); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_9);
__pyx_t_11 = (__Pyx_PyString_Equals(__pyx_t_9, __pyx_n_s_f, Py_EQ)); if (unlikely(__pyx_t_11 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0;
if (__pyx_t_11) {
__pyx_t_11 = ((sizeof(float)) == __pyx_v_itemsize);
if (__pyx_t_11) {
__pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_arg, __pyx_n_s_ndim); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_9);
__pyx_t_8 = PyObject_RichCompare(__pyx_t_9, __pyx_int_2, Py_EQ); __Pyx_XGOTREF(__pyx_t_8); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0;
__pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_t_8); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0;
__pyx_t_3 = __pyx_t_2;
} else {
__pyx_t_3 = __pyx_t_11;
}
if (__pyx_t_3) {
if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, __pyx_n_s_float_array_2d_t, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
goto __pyx_L17_break;
}
__pyx_t_3 = ((sizeof(double)) == __pyx_v_itemsize);
if (__pyx_t_3) {
__pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_v_arg, __pyx_n_s_ndim); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_8);
__pyx_t_9 = PyObject_RichCompare(__pyx_t_8, __pyx_int_2, Py_EQ); __Pyx_XGOTREF(__pyx_t_9); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0;
__pyx_t_11 = __Pyx_PyObject_IsTrue(__pyx_t_9); if (unlikely(__pyx_t_11 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0;
__pyx_t_2 = __pyx_t_11;
} else {
__pyx_t_2 = __pyx_t_3;
}
if (__pyx_t_2) {
if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, __pyx_n_s_double_array_2d_t, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
goto __pyx_L17_break;
}
goto __pyx_L21;
}
__pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_dtype, __pyx_n_s_kind); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_9);
__pyx_t_2 = (__Pyx_PyString_Equals(__pyx_t_9, __pyx_n_s_c, Py_EQ)); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0;
if (__pyx_t_2) {
goto __pyx_L21;
}
__pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_dtype, __pyx_n_s_kind); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_9);
__pyx_t_2 = (__Pyx_PyString_Equals(__pyx_t_9, __pyx_n_s_O, Py_EQ)); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0;
if (__pyx_t_2) {
goto __pyx_L21;
}
__pyx_L21:;
goto __pyx_L20;
}
__pyx_L20:;
goto __pyx_L18;
}
__pyx_L18:;
__pyx_t_2 = ((__pyx_v_itemsize == -1) != 0);
if (!__pyx_t_2) {
__pyx_t_3 = ((__pyx_v_itemsize == (sizeof(float))) != 0);
__pyx_t_11 = __pyx_t_3;
} else {
__pyx_t_11 = __pyx_t_2;
}
if (__pyx_t_11) {
__pyx_v_memslice = __Pyx_PyObject_to_MemoryviewSlice_dsds_float(__pyx_v_arg);
__pyx_t_11 = (__pyx_v_memslice.memview != 0);
if (__pyx_t_11) {
__PYX_XDEC_MEMVIEW((&__pyx_v_memslice), 1);
if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, __pyx_n_s_float_array_2d_t, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
goto __pyx_L17_break;
}
/*else*/ {
PyErr_Clear();
}
goto __pyx_L24;
}
__pyx_L24:;
__pyx_t_11 = ((__pyx_v_itemsize == -1) != 0);
if (!__pyx_t_11) {
__pyx_t_2 = ((__pyx_v_itemsize == (sizeof(double))) != 0);
__pyx_t_3 = __pyx_t_2;
} else {
__pyx_t_3 = __pyx_t_11;
}
if (__pyx_t_3) {
__pyx_v_memslice = __Pyx_PyObject_to_MemoryviewSlice_dsds_double(__pyx_v_arg);
__pyx_t_3 = (__pyx_v_memslice.memview != 0);
if (__pyx_t_3) {
__PYX_XDEC_MEMVIEW((&__pyx_v_memslice), 1);
if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, __pyx_n_s_double_array_2d_t, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
goto __pyx_L17_break;
}
/*else*/ {
PyErr_Clear();
}
goto __pyx_L26;
}
__pyx_L26:;
if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, Py_None, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
goto __pyx_L17_break;
}
__pyx_L17_break:;
}
__pyx_L15:;
__pyx_t_9 = PyList_New(0); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_9);
__pyx_v_candidates = ((PyObject*)__pyx_t_9);
__pyx_t_9 = 0;
if (PyList_CheckExact(__pyx_v_signatures) || PyTuple_CheckExact(__pyx_v_signatures)) {
__pyx_t_9 = __pyx_v_signatures; __Pyx_INCREF(__pyx_t_9); __pyx_t_10 = 0;
__pyx_t_13 = NULL;
} else {
__pyx_t_10 = -1; __pyx_t_9 = PyObject_GetIter(__pyx_v_signatures); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_9);
__pyx_t_13 = Py_TYPE(__pyx_t_9)->tp_iternext;
}
for (;;) {
if (!__pyx_t_13 && PyList_CheckExact(__pyx_t_9)) {
if (__pyx_t_10 >= PyList_GET_SIZE(__pyx_t_9)) break;
#if CYTHON_COMPILING_IN_CPYTHON
__pyx_t_8 = PyList_GET_ITEM(__pyx_t_9, __pyx_t_10); __Pyx_INCREF(__pyx_t_8); __pyx_t_10++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
#else
__pyx_t_8 = PySequence_ITEM(__pyx_t_9, __pyx_t_10); __pyx_t_10++; if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
#endif
} else if (!__pyx_t_13 && PyTuple_CheckExact(__pyx_t_9)) {
if (__pyx_t_10 >= PyTuple_GET_SIZE(__pyx_t_9)) break;
#if CYTHON_COMPILING_IN_CPYTHON
__pyx_t_8 = PyTuple_GET_ITEM(__pyx_t_9, __pyx_t_10); __Pyx_INCREF(__pyx_t_8); __pyx_t_10++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
#else
__pyx_t_8 = PySequence_ITEM(__pyx_t_9, __pyx_t_10); __pyx_t_10++; if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
#endif
} else {
__pyx_t_8 = __pyx_t_13(__pyx_t_9);
if (unlikely(!__pyx_t_8)) {
PyObject* exc_type = PyErr_Occurred();
if (exc_type) {
if (likely(exc_type == PyExc_StopIteration || PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear();
else {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
}
break;
}
__Pyx_GOTREF(__pyx_t_8);
}
__Pyx_XDECREF_SET(__pyx_v_sig, __pyx_t_8);
__pyx_t_8 = 0;
__pyx_v_match_found = 0;
__pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_v_sig, __pyx_n_s_strip); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_8);
__pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_8, __pyx_tuple__3, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
__Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0;
__pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_split); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_8);
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
__pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_8, __pyx_tuple__5, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
__Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0;
__pyx_t_8 = PyTuple_New(2); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_8);
PyTuple_SET_ITEM(__pyx_t_8, 0, __pyx_t_1);
__Pyx_GIVEREF(__pyx_t_1);
__Pyx_INCREF(__pyx_v_dest_sig);
PyTuple_SET_ITEM(__pyx_t_8, 1, __pyx_v_dest_sig);
__Pyx_GIVEREF(__pyx_v_dest_sig);
__pyx_t_1 = 0;
__pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_zip, __pyx_t_8, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
__Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0;
if (PyList_CheckExact(__pyx_t_1) || PyTuple_CheckExact(__pyx_t_1)) {
__pyx_t_8 = __pyx_t_1; __Pyx_INCREF(__pyx_t_8); __pyx_t_14 = 0;
__pyx_t_15 = NULL;
} else {
__pyx_t_14 = -1; __pyx_t_8 = PyObject_GetIter(__pyx_t_1); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_8);
__pyx_t_15 = Py_TYPE(__pyx_t_8)->tp_iternext;
}
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
for (;;) {
if (!__pyx_t_15 && PyList_CheckExact(__pyx_t_8)) {
if (__pyx_t_14 >= PyList_GET_SIZE(__pyx_t_8)) break;
#if CYTHON_COMPILING_IN_CPYTHON
__pyx_t_1 = PyList_GET_ITEM(__pyx_t_8, __pyx_t_14); __Pyx_INCREF(__pyx_t_1); __pyx_t_14++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
#else
__pyx_t_1 = PySequence_ITEM(__pyx_t_8, __pyx_t_14); __pyx_t_14++; if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
#endif
} else if (!__pyx_t_15 && PyTuple_CheckExact(__pyx_t_8)) {
if (__pyx_t_14 >= PyTuple_GET_SIZE(__pyx_t_8)) break;
#if CYTHON_COMPILING_IN_CPYTHON
__pyx_t_1 = PyTuple_GET_ITEM(__pyx_t_8, __pyx_t_14); __Pyx_INCREF(__pyx_t_1); __pyx_t_14++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
#else
__pyx_t_1 = PySequence_ITEM(__pyx_t_8, __pyx_t_14); __pyx_t_14++; if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
#endif
} else {
__pyx_t_1 = __pyx_t_15(__pyx_t_8);
if (unlikely(!__pyx_t_1)) {
PyObject* exc_type = PyErr_Occurred();
if (exc_type) {
if (likely(exc_type == PyExc_StopIteration || PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear();
else {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
}
break;
}
__Pyx_GOTREF(__pyx_t_1);
}
if ((likely(PyTuple_CheckExact(__pyx_t_1))) || (PyList_CheckExact(__pyx_t_1))) {
PyObject* sequence = __pyx_t_1;
#if CYTHON_COMPILING_IN_CPYTHON
Py_ssize_t size = Py_SIZE(sequence);
#else
Py_ssize_t size = PySequence_Size(sequence);
#endif
if (unlikely(size != 2)) {
if (size > 2) __Pyx_RaiseTooManyValuesError(2);
else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size);
{__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
}
#if CYTHON_COMPILING_IN_CPYTHON
if (likely(PyTuple_CheckExact(sequence))) {
__pyx_t_16 = PyTuple_GET_ITEM(sequence, 0);
__pyx_t_17 = PyTuple_GET_ITEM(sequence, 1);
} else {
__pyx_t_16 = PyList_GET_ITEM(sequence, 0);
__pyx_t_17 = PyList_GET_ITEM(sequence, 1);
}
__Pyx_INCREF(__pyx_t_16);
__Pyx_INCREF(__pyx_t_17);
#else
__pyx_t_16 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_16)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_16);
__pyx_t_17 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_17)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_17);
#endif
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
} else {
Py_ssize_t index = -1;
__pyx_t_18 = PyObject_GetIter(__pyx_t_1); if (unlikely(!__pyx_t_18)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_18);
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
__pyx_t_19 = Py_TYPE(__pyx_t_18)->tp_iternext;
index = 0; __pyx_t_16 = __pyx_t_19(__pyx_t_18); if (unlikely(!__pyx_t_16)) goto __pyx_L32_unpacking_failed;
__Pyx_GOTREF(__pyx_t_16);
index = 1; __pyx_t_17 = __pyx_t_19(__pyx_t_18); if (unlikely(!__pyx_t_17)) goto __pyx_L32_unpacking_failed;
__Pyx_GOTREF(__pyx_t_17);
if (__Pyx_IternextUnpackEndCheck(__pyx_t_19(__pyx_t_18), 2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_t_19 = NULL;
__Pyx_DECREF(__pyx_t_18); __pyx_t_18 = 0;
goto __pyx_L33_unpacking_done;
__pyx_L32_unpacking_failed:;
__Pyx_DECREF(__pyx_t_18); __pyx_t_18 = 0;
__pyx_t_19 = NULL;
if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index);
{__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_L33_unpacking_done:;
}
__Pyx_XDECREF_SET(__pyx_v_src_type, __pyx_t_16);
__pyx_t_16 = 0;
__Pyx_XDECREF_SET(__pyx_v_dst_type, __pyx_t_17);
__pyx_t_17 = 0;
__pyx_t_3 = (__pyx_v_dst_type != Py_None);
__pyx_t_11 = (__pyx_t_3 != 0);
if (__pyx_t_11) {
__pyx_t_1 = PyObject_RichCompare(__pyx_v_src_type, __pyx_v_dst_type, Py_EQ); __Pyx_XGOTREF(__pyx_t_1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_t_11 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_11 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
if (__pyx_t_11) {
__pyx_v_match_found = 1;
goto __pyx_L35;
}
/*else*/ {
__pyx_v_match_found = 0;
goto __pyx_L31_break;
}
__pyx_L35:;
goto __pyx_L34;
}
__pyx_L34:;
}
__pyx_L31_break:;
__Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0;
__pyx_t_11 = (__pyx_v_match_found != 0);
if (__pyx_t_11) {
__pyx_t_20 = __Pyx_PyList_Append(__pyx_v_candidates, __pyx_v_sig); if (unlikely(__pyx_t_20 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
goto __pyx_L36;
}
__pyx_L36:;
}
__Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0;
__pyx_t_11 = (__pyx_v_candidates != Py_None) && (PyList_GET_SIZE(__pyx_v_candidates) != 0);
__pyx_t_3 = ((!__pyx_t_11) != 0);
if (__pyx_t_3) {
__pyx_t_9 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__6, NULL); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_9);
__Pyx_Raise(__pyx_t_9, 0, 0, 0);
__Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0;
{__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
}
__pyx_t_10 = PyList_GET_SIZE(__pyx_v_candidates); if (unlikely(__pyx_t_10 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_t_3 = ((__pyx_t_10 > 1) != 0);
if (__pyx_t_3) {
__pyx_t_9 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__7, NULL); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_9);
__Pyx_Raise(__pyx_t_9, 0, 0, 0);
__Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0;
{__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
}
/*else*/ {
__Pyx_XDECREF(__pyx_r);
__pyx_t_9 = PyObject_GetItem(__pyx_v_signatures, PyList_GET_ITEM(__pyx_v_candidates, 0)); if (unlikely(__pyx_t_9 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;};
__Pyx_GOTREF(__pyx_t_9);
__pyx_r = __pyx_t_9;
__pyx_t_9 = 0;
goto __pyx_L0;
}
/* function exit code */
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_1);
__Pyx_XDECREF(__pyx_t_8);
__Pyx_XDECREF(__pyx_t_9);
__Pyx_XDECREF(__pyx_t_16);
__Pyx_XDECREF(__pyx_t_17);
__Pyx_XDECREF(__pyx_t_18);
__Pyx_AddTraceback("sklearn.metrics.pairwise_fast.__pyx_fused_cpdef", __pyx_clineno, __pyx_lineno, __pyx_filename);
__pyx_r = NULL;
__pyx_L0:;
__Pyx_XDECREF(__pyx_v_dest_sig);
__Pyx_XDECREF(__pyx_v_numpy);
__Pyx_XDECREF(__pyx_v_arg);
__Pyx_XDECREF(__pyx_v_dtype);
__Pyx_XDECREF(__pyx_v_candidates);
__Pyx_XDECREF(__pyx_v_sig);
__Pyx_XDECREF(__pyx_v_src_type);
__Pyx_XDECREF(__pyx_v_dst_type);
__Pyx_XDECREF(__pyx_v_kwargs);
__Pyx_XGIVEREF(__pyx_r);
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* Python wrapper */
static PyObject *__pyx_fuse_0__pyx_pw_7sklearn_7metrics_13pairwise_fast_5_chi2_kernel_fast(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/
static PyMethodDef __pyx_fuse_0__pyx_mdef_7sklearn_7metrics_13pairwise_fast_5_chi2_kernel_fast = {__Pyx_NAMESTR("__pyx_fuse_0_chi2_kernel_fast"), (PyCFunction)__pyx_fuse_0__pyx_pw_7sklearn_7metrics_13pairwise_fast_5_chi2_kernel_fast, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(0)};
static PyObject *__pyx_fuse_0__pyx_pw_7sklearn_7metrics_13pairwise_fast_5_chi2_kernel_fast(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) {
__pyx_t_7sklearn_7metrics_13pairwise_fast_float_array_2d_t __pyx_v_X = { 0, 0, { 0 }, { 0 }, { 0 } };
__pyx_t_7sklearn_7metrics_13pairwise_fast_float_array_2d_t __pyx_v_Y = { 0, 0, { 0 }, { 0 }, { 0 } };
__pyx_t_7sklearn_7metrics_13pairwise_fast_float_array_2d_t __pyx_v_result = { 0, 0, { 0 }, { 0 }, { 0 } };
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
PyObject *__pyx_r = 0;
__Pyx_RefNannyDeclarations
__Pyx_RefNannySetupContext("_chi2_kernel_fast (wrapper)", 0);
{
static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_X,&__pyx_n_s_Y,&__pyx_n_s_result,0};
PyObject* values[3] = {0,0,0};
if (unlikely(__pyx_kwds)) {
Py_ssize_t kw_args;
const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args);
switch (pos_args) {
case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2);
case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1);
case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0);
case 0: break;
default: goto __pyx_L5_argtuple_error;
}
kw_args = PyDict_Size(__pyx_kwds);
switch (pos_args) {
case 0:
if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_X)) != 0)) kw_args--;
else goto __pyx_L5_argtuple_error;
case 1:
if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_Y)) != 0)) kw_args--;
else {
__Pyx_RaiseArgtupleInvalid("_chi2_kernel_fast", 1, 3, 3, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
}
case 2:
if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_result)) != 0)) kw_args--;
else {
__Pyx_RaiseArgtupleInvalid("_chi2_kernel_fast", 1, 3, 3, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
}
}
if (unlikely(kw_args > 0)) {
if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "_chi2_kernel_fast") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
}
} else if (PyTuple_GET_SIZE(__pyx_args) != 3) {
goto __pyx_L5_argtuple_error;
} else {
values[0] = PyTuple_GET_ITEM(__pyx_args, 0);
values[1] = PyTuple_GET_ITEM(__pyx_args, 1);
values[2] = PyTuple_GET_ITEM(__pyx_args, 2);
}
__pyx_v_X = __Pyx_PyObject_to_MemoryviewSlice_dsds_float(values[0]); if (unlikely(!__pyx_v_X.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
__pyx_v_Y = __Pyx_PyObject_to_MemoryviewSlice_dsds_float(values[1]); if (unlikely(!__pyx_v_Y.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
__pyx_v_result = __Pyx_PyObject_to_MemoryviewSlice_dsds_float(values[2]); if (unlikely(!__pyx_v_result.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 34; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
}
goto __pyx_L4_argument_unpacking_done;
__pyx_L5_argtuple_error:;
__Pyx_RaiseArgtupleInvalid("_chi2_kernel_fast", 1, 3, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
__pyx_L3_error:;
__Pyx_AddTraceback("sklearn.metrics.pairwise_fast._chi2_kernel_fast", __pyx_clineno, __pyx_lineno, __pyx_filename);
__Pyx_RefNannyFinishContext();
return NULL;
__pyx_L4_argument_unpacking_done:;
__pyx_r = __pyx_pf_7sklearn_7metrics_13pairwise_fast_4_chi2_kernel_fast(__pyx_self, __pyx_v_X, __pyx_v_Y, __pyx_v_result);
/* function exit code */
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
static PyObject *__pyx_pf_7sklearn_7metrics_13pairwise_fast_4_chi2_kernel_fast(CYTHON_UNUSED PyObject *__pyx_self, __pyx_t_7sklearn_7metrics_13pairwise_fast_float_array_2d_t __pyx_v_X, __pyx_t_7sklearn_7metrics_13pairwise_fast_float_array_2d_t __pyx_v_Y, __pyx_t_7sklearn_7metrics_13pairwise_fast_float_array_2d_t __pyx_v_result) {
npy_intp __pyx_v_i;
npy_intp __pyx_v_j;
npy_intp __pyx_v_k;
npy_intp __pyx_v_n_samples_X;
npy_intp __pyx_v_n_samples_Y;
npy_intp __pyx_v_n_features;
double __pyx_v_res;
double __pyx_v_nom;
double __pyx_v_denom;
PyObject *__pyx_r = NULL;
__Pyx_RefNannyDeclarations
npy_intp __pyx_t_1;
npy_intp __pyx_t_2;
npy_intp __pyx_t_3;
npy_intp __pyx_t_4;
npy_intp __pyx_t_5;
npy_intp __pyx_t_6;
npy_intp __pyx_t_7;
npy_intp __pyx_t_8;
npy_intp __pyx_t_9;
npy_intp __pyx_t_10;
npy_intp __pyx_t_11;
npy_intp __pyx_t_12;
npy_intp __pyx_t_13;
npy_intp __pyx_t_14;
int __pyx_t_15;
__Pyx_RefNannySetupContext("__pyx_fuse_0_chi2_kernel_fast", 0);
/* "sklearn/metrics/pairwise_fast.pyx":36
* floating_array_2d_t result):
* cdef np.npy_intp i, j, k
* cdef np.npy_intp n_samples_X = X.shape[0] # <<<<<<<<<<<<<<
* cdef np.npy_intp n_samples_Y = Y.shape[0]
* cdef np.npy_intp n_features = X.shape[1]
*/
__pyx_v_n_samples_X = (__pyx_v_X.shape[0]);
/* "sklearn/metrics/pairwise_fast.pyx":37
* cdef np.npy_intp i, j, k
* cdef np.npy_intp n_samples_X = X.shape[0]
* cdef np.npy_intp n_samples_Y = Y.shape[0] # <<<<<<<<<<<<<<
* cdef np.npy_intp n_features = X.shape[1]
* cdef double res, nom, denom
*/
__pyx_v_n_samples_Y = (__pyx_v_Y.shape[0]);
/* "sklearn/metrics/pairwise_fast.pyx":38
* cdef np.npy_intp n_samples_X = X.shape[0]
* cdef np.npy_intp n_samples_Y = Y.shape[0]
* cdef np.npy_intp n_features = X.shape[1] # <<<<<<<<<<<<<<
* cdef double res, nom, denom
*
*/
__pyx_v_n_features = (__pyx_v_X.shape[1]);
/* "sklearn/metrics/pairwise_fast.pyx":41
* cdef double res, nom, denom
*
* with nogil: # <<<<<<<<<<<<<<
* for i in range(n_samples_X):
* for j in range(n_samples_Y):
*/
{
#ifdef WITH_THREAD
PyThreadState *_save;
Py_UNBLOCK_THREADS
#endif
/*try:*/ {
/* "sklearn/metrics/pairwise_fast.pyx":42
*
* with nogil:
* for i in range(n_samples_X): # <<<<<<<<<<<<<<
* for j in range(n_samples_Y):
* res = 0
*/
__pyx_t_1 = __pyx_v_n_samples_X;
for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) {
__pyx_v_i = __pyx_t_2;
/* "sklearn/metrics/pairwise_fast.pyx":43
* with nogil:
* for i in range(n_samples_X):
* for j in range(n_samples_Y): # <<<<<<<<<<<<<<
* res = 0
* for k in range(n_features):
*/
__pyx_t_3 = __pyx_v_n_samples_Y;
for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) {
__pyx_v_j = __pyx_t_4;
/* "sklearn/metrics/pairwise_fast.pyx":44
* for i in range(n_samples_X):
* for j in range(n_samples_Y):
* res = 0 # <<<<<<<<<<<<<<
* for k in range(n_features):
* denom = (X[i, k] - Y[j, k])
*/
__pyx_v_res = 0.0;
/* "sklearn/metrics/pairwise_fast.pyx":45
* for j in range(n_samples_Y):
* res = 0
* for k in range(n_features): # <<<<<<<<<<<<<<
* denom = (X[i, k] - Y[j, k])
* nom = (X[i, k] + Y[j, k])
*/
__pyx_t_5 = __pyx_v_n_features;
for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) {
__pyx_v_k = __pyx_t_6;
/* "sklearn/metrics/pairwise_fast.pyx":46
* res = 0
* for k in range(n_features):
* denom = (X[i, k] - Y[j, k]) # <<<<<<<<<<<<<<
* nom = (X[i, k] + Y[j, k])
* if nom != 0:
*/
__pyx_t_7 = __pyx_v_i;
__pyx_t_8 = __pyx_v_k;
__pyx_t_9 = __pyx_v_j;
__pyx_t_10 = __pyx_v_k;
__pyx_v_denom = ((*((float *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_X.data + __pyx_t_7 * __pyx_v_X.strides[0]) ) + __pyx_t_8 * __pyx_v_X.strides[1]) ))) - (*((float *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_Y.data + __pyx_t_9 * __pyx_v_Y.strides[0]) ) + __pyx_t_10 * __pyx_v_Y.strides[1]) ))));
/* "sklearn/metrics/pairwise_fast.pyx":47
* for k in range(n_features):
* denom = (X[i, k] - Y[j, k])
* nom = (X[i, k] + Y[j, k]) # <<<<<<<<<<<<<<
* if nom != 0:
* res += denom * denom / nom
*/
__pyx_t_11 = __pyx_v_i;
__pyx_t_12 = __pyx_v_k;
__pyx_t_13 = __pyx_v_j;
__pyx_t_14 = __pyx_v_k;
__pyx_v_nom = ((*((float *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_X.data + __pyx_t_11 * __pyx_v_X.strides[0]) ) + __pyx_t_12 * __pyx_v_X.strides[1]) ))) + (*((float *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_Y.data + __pyx_t_13 * __pyx_v_Y.strides[0]) ) + __pyx_t_14 * __pyx_v_Y.strides[1]) ))));
/* "sklearn/metrics/pairwise_fast.pyx":48
* denom = (X[i, k] - Y[j, k])
* nom = (X[i, k] + Y[j, k])
* if nom != 0: # <<<<<<<<<<<<<<
* res += denom * denom / nom
* result[i, j] = -res
*/
__pyx_t_15 = ((__pyx_v_nom != 0.0) != 0);
if (__pyx_t_15) {
/* "sklearn/metrics/pairwise_fast.pyx":49
* nom = (X[i, k] + Y[j, k])
* if nom != 0:
* res += denom * denom / nom # <<<<<<<<<<<<<<
* result[i, j] = -res
*
*/
__pyx_v_res = (__pyx_v_res + ((__pyx_v_denom * __pyx_v_denom) / __pyx_v_nom));
goto __pyx_L12;
}
__pyx_L12:;
}
/* "sklearn/metrics/pairwise_fast.pyx":50
* if nom != 0:
* res += denom * denom / nom
* result[i, j] = -res # <<<<<<<<<<<<<<
*
*
*/
__pyx_t_5 = __pyx_v_i;
__pyx_t_6 = __pyx_v_j;
*((float *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_result.data + __pyx_t_5 * __pyx_v_result.strides[0]) ) + __pyx_t_6 * __pyx_v_result.strides[1]) )) = (-__pyx_v_res);
}
}
}
/* "sklearn/metrics/pairwise_fast.pyx":41
* cdef double res, nom, denom
*
* with nogil: # <<<<<<<<<<<<<<
* for i in range(n_samples_X):
* for j in range(n_samples_Y):
*/
/*finally:*/ {
/*normal exit:*/{
#ifdef WITH_THREAD
Py_BLOCK_THREADS
#endif
goto __pyx_L5;
}
__pyx_L5:;
}
}
/* "sklearn/metrics/pairwise_fast.pyx":32
*
*
* def _chi2_kernel_fast(floating_array_2d_t X, # <<<<<<<<<<<<<<
* floating_array_2d_t Y,
* floating_array_2d_t result):
*/
/* function exit code */
__pyx_r = Py_None; __Pyx_INCREF(Py_None);
__PYX_XDEC_MEMVIEW(&__pyx_v_X, 1);
__PYX_XDEC_MEMVIEW(&__pyx_v_Y, 1);
__PYX_XDEC_MEMVIEW(&__pyx_v_result, 1);
__Pyx_XGIVEREF(__pyx_r);
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* Python wrapper */
static PyObject *__pyx_fuse_1__pyx_pw_7sklearn_7metrics_13pairwise_fast_7_chi2_kernel_fast(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/
static PyMethodDef __pyx_fuse_1__pyx_mdef_7sklearn_7metrics_13pairwise_fast_7_chi2_kernel_fast = {__Pyx_NAMESTR("__pyx_fuse_1_chi2_kernel_fast"), (PyCFunction)__pyx_fuse_1__pyx_pw_7sklearn_7metrics_13pairwise_fast_7_chi2_kernel_fast, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(0)};
static PyObject *__pyx_fuse_1__pyx_pw_7sklearn_7metrics_13pairwise_fast_7_chi2_kernel_fast(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) {
__pyx_t_7sklearn_7metrics_13pairwise_fast_double_array_2d_t __pyx_v_X = { 0, 0, { 0 }, { 0 }, { 0 } };
__pyx_t_7sklearn_7metrics_13pairwise_fast_double_array_2d_t __pyx_v_Y = { 0, 0, { 0 }, { 0 }, { 0 } };
__pyx_t_7sklearn_7metrics_13pairwise_fast_double_array_2d_t __pyx_v_result = { 0, 0, { 0 }, { 0 }, { 0 } };
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
PyObject *__pyx_r = 0;
__Pyx_RefNannyDeclarations
__Pyx_RefNannySetupContext("_chi2_kernel_fast (wrapper)", 0);
{
static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_X,&__pyx_n_s_Y,&__pyx_n_s_result,0};
PyObject* values[3] = {0,0,0};
if (unlikely(__pyx_kwds)) {
Py_ssize_t kw_args;
const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args);
switch (pos_args) {
case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2);
case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1);
case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0);
case 0: break;
default: goto __pyx_L5_argtuple_error;
}
kw_args = PyDict_Size(__pyx_kwds);
switch (pos_args) {
case 0:
if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_X)) != 0)) kw_args--;
else goto __pyx_L5_argtuple_error;
case 1:
if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_Y)) != 0)) kw_args--;
else {
__Pyx_RaiseArgtupleInvalid("_chi2_kernel_fast", 1, 3, 3, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
}
case 2:
if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_result)) != 0)) kw_args--;
else {
__Pyx_RaiseArgtupleInvalid("_chi2_kernel_fast", 1, 3, 3, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
}
}
if (unlikely(kw_args > 0)) {
if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "_chi2_kernel_fast") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
}
} else if (PyTuple_GET_SIZE(__pyx_args) != 3) {
goto __pyx_L5_argtuple_error;
} else {
values[0] = PyTuple_GET_ITEM(__pyx_args, 0);
values[1] = PyTuple_GET_ITEM(__pyx_args, 1);
values[2] = PyTuple_GET_ITEM(__pyx_args, 2);
}
__pyx_v_X = __Pyx_PyObject_to_MemoryviewSlice_dsds_double(values[0]); if (unlikely(!__pyx_v_X.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
__pyx_v_Y = __Pyx_PyObject_to_MemoryviewSlice_dsds_double(values[1]); if (unlikely(!__pyx_v_Y.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 33; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
__pyx_v_result = __Pyx_PyObject_to_MemoryviewSlice_dsds_double(values[2]); if (unlikely(!__pyx_v_result.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 34; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
}
goto __pyx_L4_argument_unpacking_done;
__pyx_L5_argtuple_error:;
__Pyx_RaiseArgtupleInvalid("_chi2_kernel_fast", 1, 3, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
__pyx_L3_error:;
__Pyx_AddTraceback("sklearn.metrics.pairwise_fast._chi2_kernel_fast", __pyx_clineno, __pyx_lineno, __pyx_filename);
__Pyx_RefNannyFinishContext();
return NULL;
__pyx_L4_argument_unpacking_done:;
__pyx_r = __pyx_pf_7sklearn_7metrics_13pairwise_fast_6_chi2_kernel_fast(__pyx_self, __pyx_v_X, __pyx_v_Y, __pyx_v_result);
/* function exit code */
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
static PyObject *__pyx_pf_7sklearn_7metrics_13pairwise_fast_6_chi2_kernel_fast(CYTHON_UNUSED PyObject *__pyx_self, __pyx_t_7sklearn_7metrics_13pairwise_fast_double_array_2d_t __pyx_v_X, __pyx_t_7sklearn_7metrics_13pairwise_fast_double_array_2d_t __pyx_v_Y, __pyx_t_7sklearn_7metrics_13pairwise_fast_double_array_2d_t __pyx_v_result) {
npy_intp __pyx_v_i;
npy_intp __pyx_v_j;
npy_intp __pyx_v_k;
npy_intp __pyx_v_n_samples_X;
npy_intp __pyx_v_n_samples_Y;
npy_intp __pyx_v_n_features;
double __pyx_v_res;
double __pyx_v_nom;
double __pyx_v_denom;
PyObject *__pyx_r = NULL;
__Pyx_RefNannyDeclarations
npy_intp __pyx_t_1;
npy_intp __pyx_t_2;
npy_intp __pyx_t_3;
npy_intp __pyx_t_4;
npy_intp __pyx_t_5;
npy_intp __pyx_t_6;
npy_intp __pyx_t_7;
npy_intp __pyx_t_8;
npy_intp __pyx_t_9;
npy_intp __pyx_t_10;
npy_intp __pyx_t_11;
npy_intp __pyx_t_12;
npy_intp __pyx_t_13;
npy_intp __pyx_t_14;
int __pyx_t_15;
__Pyx_RefNannySetupContext("__pyx_fuse_1_chi2_kernel_fast", 0);
/* "sklearn/metrics/pairwise_fast.pyx":36
* floating_array_2d_t result):
* cdef np.npy_intp i, j, k
* cdef np.npy_intp n_samples_X = X.shape[0] # <<<<<<<<<<<<<<
* cdef np.npy_intp n_samples_Y = Y.shape[0]
* cdef np.npy_intp n_features = X.shape[1]
*/
__pyx_v_n_samples_X = (__pyx_v_X.shape[0]);
/* "sklearn/metrics/pairwise_fast.pyx":37
* cdef np.npy_intp i, j, k
* cdef np.npy_intp n_samples_X = X.shape[0]
* cdef np.npy_intp n_samples_Y = Y.shape[0] # <<<<<<<<<<<<<<
* cdef np.npy_intp n_features = X.shape[1]
* cdef double res, nom, denom
*/
__pyx_v_n_samples_Y = (__pyx_v_Y.shape[0]);
/* "sklearn/metrics/pairwise_fast.pyx":38
* cdef np.npy_intp n_samples_X = X.shape[0]
* cdef np.npy_intp n_samples_Y = Y.shape[0]
* cdef np.npy_intp n_features = X.shape[1] # <<<<<<<<<<<<<<
* cdef double res, nom, denom
*
*/
__pyx_v_n_features = (__pyx_v_X.shape[1]);
/* "sklearn/metrics/pairwise_fast.pyx":41
* cdef double res, nom, denom
*
* with nogil: # <<<<<<<<<<<<<<
* for i in range(n_samples_X):
* for j in range(n_samples_Y):
*/
{
#ifdef WITH_THREAD
PyThreadState *_save;
Py_UNBLOCK_THREADS
#endif
/*try:*/ {
/* "sklearn/metrics/pairwise_fast.pyx":42
*
* with nogil:
* for i in range(n_samples_X): # <<<<<<<<<<<<<<
* for j in range(n_samples_Y):
* res = 0
*/
__pyx_t_1 = __pyx_v_n_samples_X;
for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) {
__pyx_v_i = __pyx_t_2;
/* "sklearn/metrics/pairwise_fast.pyx":43
* with nogil:
* for i in range(n_samples_X):
* for j in range(n_samples_Y): # <<<<<<<<<<<<<<
* res = 0
* for k in range(n_features):
*/
__pyx_t_3 = __pyx_v_n_samples_Y;
for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) {
__pyx_v_j = __pyx_t_4;
/* "sklearn/metrics/pairwise_fast.pyx":44
* for i in range(n_samples_X):
* for j in range(n_samples_Y):
* res = 0 # <<<<<<<<<<<<<<
* for k in range(n_features):
* denom = (X[i, k] - Y[j, k])
*/
__pyx_v_res = 0.0;
/* "sklearn/metrics/pairwise_fast.pyx":45
* for j in range(n_samples_Y):
* res = 0
* for k in range(n_features): # <<<<<<<<<<<<<<
* denom = (X[i, k] - Y[j, k])
* nom = (X[i, k] + Y[j, k])
*/
__pyx_t_5 = __pyx_v_n_features;
for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) {
__pyx_v_k = __pyx_t_6;
/* "sklearn/metrics/pairwise_fast.pyx":46
* res = 0
* for k in range(n_features):
* denom = (X[i, k] - Y[j, k]) # <<<<<<<<<<<<<<
* nom = (X[i, k] + Y[j, k])
* if nom != 0:
*/
__pyx_t_7 = __pyx_v_i;
__pyx_t_8 = __pyx_v_k;
__pyx_t_9 = __pyx_v_j;
__pyx_t_10 = __pyx_v_k;
__pyx_v_denom = ((*((double *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_X.data + __pyx_t_7 * __pyx_v_X.strides[0]) ) + __pyx_t_8 * __pyx_v_X.strides[1]) ))) - (*((double *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_Y.data + __pyx_t_9 * __pyx_v_Y.strides[0]) ) + __pyx_t_10 * __pyx_v_Y.strides[1]) ))));
/* "sklearn/metrics/pairwise_fast.pyx":47
* for k in range(n_features):
* denom = (X[i, k] - Y[j, k])
* nom = (X[i, k] + Y[j, k]) # <<<<<<<<<<<<<<
* if nom != 0:
* res += denom * denom / nom
*/
__pyx_t_11 = __pyx_v_i;
__pyx_t_12 = __pyx_v_k;
__pyx_t_13 = __pyx_v_j;
__pyx_t_14 = __pyx_v_k;
__pyx_v_nom = ((*((double *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_X.data + __pyx_t_11 * __pyx_v_X.strides[0]) ) + __pyx_t_12 * __pyx_v_X.strides[1]) ))) + (*((double *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_Y.data + __pyx_t_13 * __pyx_v_Y.strides[0]) ) + __pyx_t_14 * __pyx_v_Y.strides[1]) ))));
/* "sklearn/metrics/pairwise_fast.pyx":48
* denom = (X[i, k] - Y[j, k])
* nom = (X[i, k] + Y[j, k])
* if nom != 0: # <<<<<<<<<<<<<<
* res += denom * denom / nom
* result[i, j] = -res
*/
__pyx_t_15 = ((__pyx_v_nom != 0.0) != 0);
if (__pyx_t_15) {
/* "sklearn/metrics/pairwise_fast.pyx":49
* nom = (X[i, k] + Y[j, k])
* if nom != 0:
* res += denom * denom / nom # <<<<<<<<<<<<<<
* result[i, j] = -res
*
*/
__pyx_v_res = (__pyx_v_res + ((__pyx_v_denom * __pyx_v_denom) / __pyx_v_nom));
goto __pyx_L12;
}
__pyx_L12:;
}
/* "sklearn/metrics/pairwise_fast.pyx":50
* if nom != 0:
* res += denom * denom / nom
* result[i, j] = -res # <<<<<<<<<<<<<<
*
*
*/
__pyx_t_5 = __pyx_v_i;
__pyx_t_6 = __pyx_v_j;
*((double *) ( /* dim=1 */ (( /* dim=0 */ (__pyx_v_result.data + __pyx_t_5 * __pyx_v_result.strides[0]) ) + __pyx_t_6 * __pyx_v_result.strides[1]) )) = (-__pyx_v_res);
}
}
}
/* "sklearn/metrics/pairwise_fast.pyx":41
* cdef double res, nom, denom
*
* with nogil: # <<<<<<<<<<<<<<
* for i in range(n_samples_X):
* for j in range(n_samples_Y):
*/
/*finally:*/ {
/*normal exit:*/{
#ifdef WITH_THREAD
Py_BLOCK_THREADS
#endif
goto __pyx_L5;
}
__pyx_L5:;
}
}
/* "sklearn/metrics/pairwise_fast.pyx":32
*
*
* def _chi2_kernel_fast(floating_array_2d_t X, # <<<<<<<<<<<<<<
* floating_array_2d_t Y,
* floating_array_2d_t result):
*/
/* function exit code */
__pyx_r = Py_None; __Pyx_INCREF(Py_None);
__PYX_XDEC_MEMVIEW(&__pyx_v_X, 1);
__PYX_XDEC_MEMVIEW(&__pyx_v_Y, 1);
__PYX_XDEC_MEMVIEW(&__pyx_v_result, 1);
__Pyx_XGIVEREF(__pyx_r);
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "sklearn/metrics/pairwise_fast.pyx":53
*
*
* def _sparse_manhattan(floating1d X_data, int[:] X_indices, int[:] X_indptr, # <<<<<<<<<<<<<<
* floating1d Y_data, int[:] Y_indices, int[:] Y_indptr,
* np.npy_intp n_features, double[:, ::1] D):
*/
/* Python wrapper */
static PyObject *__pyx_pw_7sklearn_7metrics_13pairwise_fast_3_sparse_manhattan(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/
static char __pyx_doc_7sklearn_7metrics_13pairwise_fast_2_sparse_manhattan[] = "Pairwise L1 distances for CSR matrices.\n\n Usage:\n\n >>> D = np.zeros(X.shape[0], Y.shape[0])\n >>> sparse_manhattan(X.data, X.indices, X.indptr,\n ... Y.data, Y.indices, Y.indptr,\n ... X.shape[1], D)\n ";
static PyMethodDef __pyx_mdef_7sklearn_7metrics_13pairwise_fast_3_sparse_manhattan = {__Pyx_NAMESTR("_sparse_manhattan"), (PyCFunction)__pyx_pw_7sklearn_7metrics_13pairwise_fast_3_sparse_manhattan, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_7metrics_13pairwise_fast_2_sparse_manhattan)};
static PyObject *__pyx_pw_7sklearn_7metrics_13pairwise_fast_3_sparse_manhattan(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) {
PyObject *__pyx_v_signatures = 0;
PyObject *__pyx_v_args = 0;
PyObject *__pyx_v_kwargs = 0;
CYTHON_UNUSED PyObject *__pyx_v_defaults = 0;
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
PyObject *__pyx_r = 0;
__Pyx_RefNannyDeclarations
__Pyx_RefNannySetupContext("__pyx_fused_cpdef (wrapper)", 0);
{
static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_signatures,&__pyx_n_s_args,&__pyx_n_s_kwargs,&__pyx_n_s_defaults,0};
PyObject* values[4] = {0,0,0,0};
if (unlikely(__pyx_kwds)) {
Py_ssize_t kw_args;
const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args);
switch (pos_args) {
case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3);
case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2);
case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1);
case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0);
case 0: break;
default: goto __pyx_L5_argtuple_error;
}
kw_args = PyDict_Size(__pyx_kwds);
switch (pos_args) {
case 0:
if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_signatures)) != 0)) kw_args--;
else goto __pyx_L5_argtuple_error;
case 1:
if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_args)) != 0)) kw_args--;
else {
__Pyx_RaiseArgtupleInvalid("__pyx_fused_cpdef", 1, 4, 4, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
}
case 2:
if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_kwargs)) != 0)) kw_args--;
else {
__Pyx_RaiseArgtupleInvalid("__pyx_fused_cpdef", 1, 4, 4, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
}
case 3:
if (likely((values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_defaults)) != 0)) kw_args--;
else {
__Pyx_RaiseArgtupleInvalid("__pyx_fused_cpdef", 1, 4, 4, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
}
}
if (unlikely(kw_args > 0)) {
if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__pyx_fused_cpdef") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
}
} else if (PyTuple_GET_SIZE(__pyx_args) != 4) {
goto __pyx_L5_argtuple_error;
} else {
values[0] = PyTuple_GET_ITEM(__pyx_args, 0);
values[1] = PyTuple_GET_ITEM(__pyx_args, 1);
values[2] = PyTuple_GET_ITEM(__pyx_args, 2);
values[3] = PyTuple_GET_ITEM(__pyx_args, 3);
}
__pyx_v_signatures = values[0];
__pyx_v_args = values[1];
__pyx_v_kwargs = values[2];
__pyx_v_defaults = values[3];
}
goto __pyx_L4_argument_unpacking_done;
__pyx_L5_argtuple_error:;
__Pyx_RaiseArgtupleInvalid("__pyx_fused_cpdef", 1, 4, 4, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
__pyx_L3_error:;
__Pyx_AddTraceback("sklearn.metrics.pairwise_fast.__pyx_fused_cpdef", __pyx_clineno, __pyx_lineno, __pyx_filename);
__Pyx_RefNannyFinishContext();
return NULL;
__pyx_L4_argument_unpacking_done:;
__pyx_r = __pyx_pf_7sklearn_7metrics_13pairwise_fast_2_sparse_manhattan(__pyx_self, __pyx_v_signatures, __pyx_v_args, __pyx_v_kwargs, __pyx_v_defaults);
/* function exit code */
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
static PyObject *__pyx_pf_7sklearn_7metrics_13pairwise_fast_2_sparse_manhattan(CYTHON_UNUSED PyObject *__pyx_self, PyObject *__pyx_v_signatures, PyObject *__pyx_v_args, PyObject *__pyx_v_kwargs, CYTHON_UNUSED PyObject *__pyx_v_defaults) {
PyObject *__pyx_v_dest_sig = NULL;
PyObject *__pyx_v_numpy = NULL;
__Pyx_memviewslice __pyx_v_memslice;
Py_ssize_t __pyx_v_itemsize;
CYTHON_UNUSED int __pyx_v_dtype_signed;
char __pyx_v_kind;
PyObject *__pyx_v_arg = NULL;
PyObject *__pyx_v_dtype = NULL;
PyObject *__pyx_v_candidates = NULL;
PyObject *__pyx_v_sig = NULL;
int __pyx_v_match_found;
PyObject *__pyx_v_src_type = NULL;
PyObject *__pyx_v_dst_type = NULL;
PyObject *__pyx_r = NULL;
__Pyx_RefNannyDeclarations
PyObject *__pyx_t_1 = NULL;
int __pyx_t_2;
int __pyx_t_3;
PyObject *__pyx_t_4 = NULL;
PyObject *__pyx_t_5 = NULL;
PyObject *__pyx_t_6 = NULL;
int __pyx_t_7;
PyObject *__pyx_t_8 = NULL;
PyObject *__pyx_t_9 = NULL;
Py_ssize_t __pyx_t_10;
int __pyx_t_11;
char __pyx_t_12;
PyObject *(*__pyx_t_13)(PyObject *);
Py_ssize_t __pyx_t_14;
PyObject *(*__pyx_t_15)(PyObject *);
PyObject *__pyx_t_16 = NULL;
PyObject *__pyx_t_17 = NULL;
PyObject *__pyx_t_18 = NULL;
PyObject *(*__pyx_t_19)(PyObject *);
int __pyx_t_20;
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
__Pyx_RefNannySetupContext("_sparse_manhattan", 0);
__Pyx_INCREF(__pyx_v_kwargs);
__pyx_t_1 = PyList_New(8); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
__Pyx_INCREF(Py_None);
PyList_SET_ITEM(__pyx_t_1, 0, Py_None);
__Pyx_GIVEREF(Py_None);
__Pyx_INCREF(Py_None);
PyList_SET_ITEM(__pyx_t_1, 1, Py_None);
__Pyx_GIVEREF(Py_None);
__Pyx_INCREF(Py_None);
PyList_SET_ITEM(__pyx_t_1, 2, Py_None);
__Pyx_GIVEREF(Py_None);
__Pyx_INCREF(Py_None);
PyList_SET_ITEM(__pyx_t_1, 3, Py_None);
__Pyx_GIVEREF(Py_None);
__Pyx_INCREF(Py_None);
PyList_SET_ITEM(__pyx_t_1, 4, Py_None);
__Pyx_GIVEREF(Py_None);
__Pyx_INCREF(Py_None);
PyList_SET_ITEM(__pyx_t_1, 5, Py_None);
__Pyx_GIVEREF(Py_None);
__Pyx_INCREF(Py_None);
PyList_SET_ITEM(__pyx_t_1, 6, Py_None);
__Pyx_GIVEREF(Py_None);
__Pyx_INCREF(Py_None);
PyList_SET_ITEM(__pyx_t_1, 7, Py_None);
__Pyx_GIVEREF(Py_None);
__pyx_v_dest_sig = ((PyObject*)__pyx_t_1);
__pyx_t_1 = 0;
__pyx_t_2 = (__pyx_v_kwargs == Py_None);
__pyx_t_3 = (__pyx_t_2 != 0);
if (__pyx_t_3) {
__pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
__Pyx_DECREF_SET(__pyx_v_kwargs, __pyx_t_1);
__pyx_t_1 = 0;
goto __pyx_L3;
}
__pyx_L3:;
{
__Pyx_ExceptionSave(&__pyx_t_4, &__pyx_t_5, &__pyx_t_6);
__Pyx_XGOTREF(__pyx_t_4);
__Pyx_XGOTREF(__pyx_t_5);
__Pyx_XGOTREF(__pyx_t_6);
/*try:*/ {
__pyx_t_1 = __Pyx_Import(__pyx_n_s_numpy, 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L4_error;}
__Pyx_GOTREF(__pyx_t_1);
__pyx_v_numpy = __pyx_t_1;
__pyx_t_1 = 0;
}
__Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0;
__Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0;
__Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0;
goto __pyx_L11_try_end;
__pyx_L4_error:;
__Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0;
__pyx_t_7 = PyErr_ExceptionMatches(__pyx_builtin_ImportError);
if (__pyx_t_7) {
__Pyx_AddTraceback("sklearn.metrics.pairwise_fast.__pyx_fused_cpdef", __pyx_clineno, __pyx_lineno, __pyx_filename);
if (__Pyx_GetException(&__pyx_t_1, &__pyx_t_8, &__pyx_t_9) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L6_except_error;}
__Pyx_GOTREF(__pyx_t_1);
__Pyx_GOTREF(__pyx_t_8);
__Pyx_GOTREF(__pyx_t_9);
__Pyx_INCREF(Py_None);
__Pyx_XDECREF_SET(__pyx_v_numpy, Py_None);
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
__Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0;
__Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0;
goto __pyx_L5_exception_handled;
}
goto __pyx_L6_except_error;
__pyx_L6_except_error:;
__Pyx_XGIVEREF(__pyx_t_4);
__Pyx_XGIVEREF(__pyx_t_5);
__Pyx_XGIVEREF(__pyx_t_6);
__Pyx_ExceptionReset(__pyx_t_4, __pyx_t_5, __pyx_t_6);
goto __pyx_L1_error;
__pyx_L5_exception_handled:;
__Pyx_XGIVEREF(__pyx_t_4);
__Pyx_XGIVEREF(__pyx_t_5);
__Pyx_XGIVEREF(__pyx_t_6);
__Pyx_ExceptionReset(__pyx_t_4, __pyx_t_5, __pyx_t_6);
__pyx_L11_try_end:;
}
__pyx_v_itemsize = -1;
__pyx_t_10 = PyObject_Length(__pyx_v_args); if (unlikely(__pyx_t_10 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_t_3 = ((0 < __pyx_t_10) != 0);
if (__pyx_t_3) {
__pyx_t_9 = __Pyx_GetItemInt(__pyx_v_args, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 0); if (unlikely(__pyx_t_9 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;};
__Pyx_GOTREF(__pyx_t_9);
__pyx_v_arg = __pyx_t_9;
__pyx_t_9 = 0;
goto __pyx_L14;
}
__pyx_t_3 = (__Pyx_PySequence_Contains(__pyx_n_s_X_data, __pyx_v_kwargs, Py_EQ)); if (unlikely(__pyx_t_3 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_t_2 = (__pyx_t_3 != 0);
if (__pyx_t_2) {
__pyx_t_9 = PyObject_GetItem(__pyx_v_kwargs, __pyx_n_s_X_data); if (unlikely(__pyx_t_9 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;};
__Pyx_GOTREF(__pyx_t_9);
__pyx_v_arg = __pyx_t_9;
__pyx_t_9 = 0;
goto __pyx_L14;
}
/*else*/ {
__pyx_t_10 = PyObject_Length(__pyx_v_args); if (unlikely(__pyx_t_10 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_t_9 = PyInt_FromSsize_t(__pyx_t_10); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_9);
__pyx_t_8 = __Pyx_PyString_Format(__pyx_kp_s_Expected_at_least_d_arguments, __pyx_t_9); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_8);
__Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0;
__pyx_t_9 = PyTuple_New(1); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_9);
PyTuple_SET_ITEM(__pyx_t_9, 0, __pyx_t_8);
__Pyx_GIVEREF(__pyx_t_8);
__pyx_t_8 = 0;
__pyx_t_8 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_t_9, NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_8);
__Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0;
__Pyx_Raise(__pyx_t_8, 0, 0, 0);
__Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0;
{__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
}
__pyx_L14:;
if (0) {
goto __pyx_L15;
}
/*else*/ {
while (1) {
if (!1) break;
__pyx_t_2 = (__pyx_v_numpy != Py_None);
__pyx_t_3 = (__pyx_t_2 != 0);
if (__pyx_t_3) {
__pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_v_numpy, __pyx_n_s_ndarray); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_8);
__pyx_t_3 = PyObject_IsInstance(__pyx_v_arg, __pyx_t_8); if (unlikely(__pyx_t_3 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0;
__pyx_t_2 = (__pyx_t_3 != 0);
if (__pyx_t_2) {
__pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_v_arg, __pyx_n_s_dtype); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_8);
__pyx_v_dtype = __pyx_t_8;
__pyx_t_8 = 0;
goto __pyx_L19;
}
__pyx_t_2 = (__pyx_memoryview_check(__pyx_v_arg) != 0);
if (__pyx_t_2) {
__pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_v_arg, __pyx_n_s_base); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_8);
__pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_numpy, __pyx_n_s_ndarray); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_9);
__pyx_t_3 = PyObject_IsInstance(__pyx_t_8, __pyx_t_9); if (unlikely(__pyx_t_3 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0;
__Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0;
__pyx_t_11 = (__pyx_t_3 != 0);
} else {
__pyx_t_11 = __pyx_t_2;
}
if (__pyx_t_11) {
__pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_arg, __pyx_n_s_base); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_9);
__pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_t_9, __pyx_n_s_dtype); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_8);
__Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0;
__pyx_v_dtype = __pyx_t_8;
__pyx_t_8 = 0;
goto __pyx_L19;
}
/*else*/ {
__Pyx_INCREF(Py_None);
__pyx_v_dtype = Py_None;
}
__pyx_L19:;
__pyx_v_itemsize = -1;
__pyx_t_11 = (__pyx_v_dtype != Py_None);
__pyx_t_2 = (__pyx_t_11 != 0);
if (__pyx_t_2) {
__pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_v_dtype, __pyx_n_s_itemsize); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_8);
__pyx_t_10 = __Pyx_PyIndex_AsSsize_t(__pyx_t_8); if (unlikely((__pyx_t_10 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0;
__pyx_v_itemsize = __pyx_t_10;
__pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_v_dtype, __pyx_n_s_kind); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_8);
__pyx_t_9 = PyTuple_New(1); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_9);
PyTuple_SET_ITEM(__pyx_t_9, 0, __pyx_t_8);
__Pyx_GIVEREF(__pyx_t_8);
__pyx_t_8 = 0;
__pyx_t_8 = __Pyx_PyObject_Call(__pyx_builtin_ord, __pyx_t_9, NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_8);
__Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0;
__pyx_t_12 = __Pyx_PyInt_As_char(__pyx_t_8); if (unlikely((__pyx_t_12 == (char)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0;
__pyx_v_kind = __pyx_t_12;
__pyx_t_8 = __Pyx_PyInt_From_char(__pyx_v_kind); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_8);
__pyx_t_9 = PyObject_RichCompare(__pyx_t_8, __pyx_int_105, Py_EQ); __Pyx_XGOTREF(__pyx_t_9); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0;
__pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_t_9); if (unlikely((__pyx_t_2 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0;
__pyx_v_dtype_signed = __pyx_t_2;
__pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_dtype, __pyx_n_s_kind); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_9);
__pyx_t_2 = (__Pyx_PySequence_Contains(__pyx_t_9, __pyx_tuple__8, Py_EQ)); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0;
__pyx_t_11 = (__pyx_t_2 != 0);
if (__pyx_t_11) {
goto __pyx_L21;
}
__pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_dtype, __pyx_n_s_kind); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_9);
__pyx_t_11 = (__Pyx_PyString_Equals(__pyx_t_9, __pyx_n_s_f, Py_EQ)); if (unlikely(__pyx_t_11 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0;
if (__pyx_t_11) {
__pyx_t_11 = ((sizeof(float)) == __pyx_v_itemsize);
if (__pyx_t_11) {
__pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_arg, __pyx_n_s_ndim); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_9);
__pyx_t_8 = PyObject_RichCompare(__pyx_t_9, __pyx_int_1, Py_EQ); __Pyx_XGOTREF(__pyx_t_8); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0;
__pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_t_8); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0;
__pyx_t_3 = __pyx_t_2;
} else {
__pyx_t_3 = __pyx_t_11;
}
if (__pyx_t_3) {
if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, __pyx_kp_s_float_1, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
goto __pyx_L17_break;
}
__pyx_t_3 = ((sizeof(double)) == __pyx_v_itemsize);
if (__pyx_t_3) {
__pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_v_arg, __pyx_n_s_ndim); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_8);
__pyx_t_9 = PyObject_RichCompare(__pyx_t_8, __pyx_int_1, Py_EQ); __Pyx_XGOTREF(__pyx_t_9); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0;
__pyx_t_11 = __Pyx_PyObject_IsTrue(__pyx_t_9); if (unlikely(__pyx_t_11 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0;
__pyx_t_2 = __pyx_t_11;
} else {
__pyx_t_2 = __pyx_t_3;
}
if (__pyx_t_2) {
if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, __pyx_kp_s_double_1, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
goto __pyx_L17_break;
}
goto __pyx_L21;
}
__pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_dtype, __pyx_n_s_kind); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_9);
__pyx_t_2 = (__Pyx_PyString_Equals(__pyx_t_9, __pyx_n_s_c, Py_EQ)); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0;
if (__pyx_t_2) {
goto __pyx_L21;
}
__pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_dtype, __pyx_n_s_kind); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_9);
__pyx_t_2 = (__Pyx_PyString_Equals(__pyx_t_9, __pyx_n_s_O, Py_EQ)); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0;
if (__pyx_t_2) {
goto __pyx_L21;
}
__pyx_L21:;
goto __pyx_L20;
}
__pyx_L20:;
goto __pyx_L18;
}
__pyx_L18:;
__pyx_t_2 = ((__pyx_v_itemsize == -1) != 0);
if (!__pyx_t_2) {
__pyx_t_3 = ((__pyx_v_itemsize == (sizeof(float))) != 0);
__pyx_t_11 = __pyx_t_3;
} else {
__pyx_t_11 = __pyx_t_2;
}
if (__pyx_t_11) {
__pyx_v_memslice = __Pyx_PyObject_to_MemoryviewSlice_dc_float(__pyx_v_arg);
__pyx_t_11 = (__pyx_v_memslice.memview != 0);
if (__pyx_t_11) {
__PYX_XDEC_MEMVIEW((&__pyx_v_memslice), 1);
if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, __pyx_kp_s_float_1, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
goto __pyx_L17_break;
}
/*else*/ {
PyErr_Clear();
}
goto __pyx_L24;
}
__pyx_L24:;
__pyx_t_11 = ((__pyx_v_itemsize == -1) != 0);
if (!__pyx_t_11) {
__pyx_t_2 = ((__pyx_v_itemsize == (sizeof(double))) != 0);
__pyx_t_3 = __pyx_t_2;
} else {
__pyx_t_3 = __pyx_t_11;
}
if (__pyx_t_3) {
__pyx_v_memslice = __Pyx_PyObject_to_MemoryviewSlice_dc_double(__pyx_v_arg);
__pyx_t_3 = (__pyx_v_memslice.memview != 0);
if (__pyx_t_3) {
__PYX_XDEC_MEMVIEW((&__pyx_v_memslice), 1);
if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, __pyx_kp_s_double_1, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
goto __pyx_L17_break;
}
/*else*/ {
PyErr_Clear();
}
goto __pyx_L26;
}
__pyx_L26:;
if (unlikely(__Pyx_SetItemInt(__pyx_v_dest_sig, 0, Py_None, long, 1, __Pyx_PyInt_From_long, 1, 0, 0) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
goto __pyx_L17_break;
}
__pyx_L17_break:;
}
__pyx_L15:;
__pyx_t_9 = PyList_New(0); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_9);
__pyx_v_candidates = ((PyObject*)__pyx_t_9);
__pyx_t_9 = 0;
if (PyList_CheckExact(__pyx_v_signatures) || PyTuple_CheckExact(__pyx_v_signatures)) {
__pyx_t_9 = __pyx_v_signatures; __Pyx_INCREF(__pyx_t_9); __pyx_t_10 = 0;
__pyx_t_13 = NULL;
} else {
__pyx_t_10 = -1; __pyx_t_9 = PyObject_GetIter(__pyx_v_signatures); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_9);
__pyx_t_13 = Py_TYPE(__pyx_t_9)->tp_iternext;
}
for (;;) {
if (!__pyx_t_13 && PyList_CheckExact(__pyx_t_9)) {
if (__pyx_t_10 >= PyList_GET_SIZE(__pyx_t_9)) break;
#if CYTHON_COMPILING_IN_CPYTHON
__pyx_t_8 = PyList_GET_ITEM(__pyx_t_9, __pyx_t_10); __Pyx_INCREF(__pyx_t_8); __pyx_t_10++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
#else
__pyx_t_8 = PySequence_ITEM(__pyx_t_9, __pyx_t_10); __pyx_t_10++; if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
#endif
} else if (!__pyx_t_13 && PyTuple_CheckExact(__pyx_t_9)) {
if (__pyx_t_10 >= PyTuple_GET_SIZE(__pyx_t_9)) break;
#if CYTHON_COMPILING_IN_CPYTHON
__pyx_t_8 = PyTuple_GET_ITEM(__pyx_t_9, __pyx_t_10); __Pyx_INCREF(__pyx_t_8); __pyx_t_10++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
#else
__pyx_t_8 = PySequence_ITEM(__pyx_t_9, __pyx_t_10); __pyx_t_10++; if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
#endif
} else {
__pyx_t_8 = __pyx_t_13(__pyx_t_9);
if (unlikely(!__pyx_t_8)) {
PyObject* exc_type = PyErr_Occurred();
if (exc_type) {
if (likely(exc_type == PyExc_StopIteration || PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear();
else {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
}
break;
}
__Pyx_GOTREF(__pyx_t_8);
}
__Pyx_XDECREF_SET(__pyx_v_sig, __pyx_t_8);
__pyx_t_8 = 0;
__pyx_v_match_found = 0;
__pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_v_sig, __pyx_n_s_strip); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_8);
__pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_8, __pyx_tuple__9, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
__Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0;
__pyx_t_8 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_split); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_8);
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
__pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_8, __pyx_tuple__10, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
__Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0;
__pyx_t_8 = PyTuple_New(2); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_8);
PyTuple_SET_ITEM(__pyx_t_8, 0, __pyx_t_1);
__Pyx_GIVEREF(__pyx_t_1);
__Pyx_INCREF(__pyx_v_dest_sig);
PyTuple_SET_ITEM(__pyx_t_8, 1, __pyx_v_dest_sig);
__Pyx_GIVEREF(__pyx_v_dest_sig);
__pyx_t_1 = 0;
__pyx_t_1 = __Pyx_PyObject_Call(__pyx_builtin_zip, __pyx_t_8, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
__Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0;
if (PyList_CheckExact(__pyx_t_1) || PyTuple_CheckExact(__pyx_t_1)) {
__pyx_t_8 = __pyx_t_1; __Pyx_INCREF(__pyx_t_8); __pyx_t_14 = 0;
__pyx_t_15 = NULL;
} else {
__pyx_t_14 = -1; __pyx_t_8 = PyObject_GetIter(__pyx_t_1); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_8);
__pyx_t_15 = Py_TYPE(__pyx_t_8)->tp_iternext;
}
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
for (;;) {
if (!__pyx_t_15 && PyList_CheckExact(__pyx_t_8)) {
if (__pyx_t_14 >= PyList_GET_SIZE(__pyx_t_8)) break;
#if CYTHON_COMPILING_IN_CPYTHON
__pyx_t_1 = PyList_GET_ITEM(__pyx_t_8, __pyx_t_14); __Pyx_INCREF(__pyx_t_1); __pyx_t_14++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
#else
__pyx_t_1 = PySequence_ITEM(__pyx_t_8, __pyx_t_14); __pyx_t_14++; if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
#endif
} else if (!__pyx_t_15 && PyTuple_CheckExact(__pyx_t_8)) {
if (__pyx_t_14 >= PyTuple_GET_SIZE(__pyx_t_8)) break;
#if CYTHON_COMPILING_IN_CPYTHON
__pyx_t_1 = PyTuple_GET_ITEM(__pyx_t_8, __pyx_t_14); __Pyx_INCREF(__pyx_t_1); __pyx_t_14++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
#else
__pyx_t_1 = PySequence_ITEM(__pyx_t_8, __pyx_t_14); __pyx_t_14++; if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
#endif
} else {
__pyx_t_1 = __pyx_t_15(__pyx_t_8);
if (unlikely(!__pyx_t_1)) {
PyObject* exc_type = PyErr_Occurred();
if (exc_type) {
if (likely(exc_type == PyExc_StopIteration || PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear();
else {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
}
break;
}
__Pyx_GOTREF(__pyx_t_1);
}
if ((likely(PyTuple_CheckExact(__pyx_t_1))) || (PyList_CheckExact(__pyx_t_1))) {
PyObject* sequence = __pyx_t_1;
#if CYTHON_COMPILING_IN_CPYTHON
Py_ssize_t size = Py_SIZE(sequence);
#else
Py_ssize_t size = PySequence_Size(sequence);
#endif
if (unlikely(size != 2)) {
if (size > 2) __Pyx_RaiseTooManyValuesError(2);
else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size);
{__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
}
#if CYTHON_COMPILING_IN_CPYTHON
if (likely(PyTuple_CheckExact(sequence))) {
__pyx_t_16 = PyTuple_GET_ITEM(sequence, 0);
__pyx_t_17 = PyTuple_GET_ITEM(sequence, 1);
} else {
__pyx_t_16 = PyList_GET_ITEM(sequence, 0);
__pyx_t_17 = PyList_GET_ITEM(sequence, 1);
}
__Pyx_INCREF(__pyx_t_16);
__Pyx_INCREF(__pyx_t_17);
#else
__pyx_t_16 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_16)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_16);
__pyx_t_17 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_17)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_17);
#endif
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
} else {
Py_ssize_t index = -1;
__pyx_t_18 = PyObject_GetIter(__pyx_t_1); if (unlikely(!__pyx_t_18)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_18);
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
__pyx_t_19 = Py_TYPE(__pyx_t_18)->tp_iternext;
index = 0; __pyx_t_16 = __pyx_t_19(__pyx_t_18); if (unlikely(!__pyx_t_16)) goto __pyx_L32_unpacking_failed;
__Pyx_GOTREF(__pyx_t_16);
index = 1; __pyx_t_17 = __pyx_t_19(__pyx_t_18); if (unlikely(!__pyx_t_17)) goto __pyx_L32_unpacking_failed;
__Pyx_GOTREF(__pyx_t_17);
if (__Pyx_IternextUnpackEndCheck(__pyx_t_19(__pyx_t_18), 2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_t_19 = NULL;
__Pyx_DECREF(__pyx_t_18); __pyx_t_18 = 0;
goto __pyx_L33_unpacking_done;
__pyx_L32_unpacking_failed:;
__Pyx_DECREF(__pyx_t_18); __pyx_t_18 = 0;
__pyx_t_19 = NULL;
if (__Pyx_IterFinish() == 0) __Pyx_RaiseNeedMoreValuesError(index);
{__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_L33_unpacking_done:;
}
__Pyx_XDECREF_SET(__pyx_v_src_type, __pyx_t_16);
__pyx_t_16 = 0;
__Pyx_XDECREF_SET(__pyx_v_dst_type, __pyx_t_17);
__pyx_t_17 = 0;
__pyx_t_3 = (__pyx_v_dst_type != Py_None);
__pyx_t_11 = (__pyx_t_3 != 0);
if (__pyx_t_11) {
__pyx_t_1 = PyObject_RichCompare(__pyx_v_src_type, __pyx_v_dst_type, Py_EQ); __Pyx_XGOTREF(__pyx_t_1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_t_11 = __Pyx_PyObject_IsTrue(__pyx_t_1); if (unlikely(__pyx_t_11 < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
if (__pyx_t_11) {
__pyx_v_match_found = 1;
goto __pyx_L35;
}
/*else*/ {
__pyx_v_match_found = 0;
goto __pyx_L31_break;
}
__pyx_L35:;
goto __pyx_L34;
}
__pyx_L34:;
}
__pyx_L31_break:;
__Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0;
__pyx_t_11 = (__pyx_v_match_found != 0);
if (__pyx_t_11) {
__pyx_t_20 = __Pyx_PyList_Append(__pyx_v_candidates, __pyx_v_sig); if (unlikely(__pyx_t_20 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
goto __pyx_L36;
}
__pyx_L36:;
}
__Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0;
__pyx_t_11 = (__pyx_v_candidates != Py_None) && (PyList_GET_SIZE(__pyx_v_candidates) != 0);
__pyx_t_3 = ((!__pyx_t_11) != 0);
if (__pyx_t_3) {
__pyx_t_9 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__11, NULL); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_9);
__Pyx_Raise(__pyx_t_9, 0, 0, 0);
__Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0;
{__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
}
__pyx_t_10 = PyList_GET_SIZE(__pyx_v_candidates); if (unlikely(__pyx_t_10 == -1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_t_3 = ((__pyx_t_10 > 1) != 0);
if (__pyx_t_3) {
__pyx_t_9 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_tuple__12, NULL); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_9);
__Pyx_Raise(__pyx_t_9, 0, 0, 0);
__Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0;
{__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
}
/*else*/ {
__Pyx_XDECREF(__pyx_r);
__pyx_t_9 = PyObject_GetItem(__pyx_v_signatures, PyList_GET_ITEM(__pyx_v_candidates, 0)); if (unlikely(__pyx_t_9 == NULL)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;};
__Pyx_GOTREF(__pyx_t_9);
__pyx_r = __pyx_t_9;
__pyx_t_9 = 0;
goto __pyx_L0;
}
/* function exit code */
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_1);
__Pyx_XDECREF(__pyx_t_8);
__Pyx_XDECREF(__pyx_t_9);
__Pyx_XDECREF(__pyx_t_16);
__Pyx_XDECREF(__pyx_t_17);
__Pyx_XDECREF(__pyx_t_18);
__Pyx_AddTraceback("sklearn.metrics.pairwise_fast.__pyx_fused_cpdef", __pyx_clineno, __pyx_lineno, __pyx_filename);
__pyx_r = NULL;
__pyx_L0:;
__Pyx_XDECREF(__pyx_v_dest_sig);
__Pyx_XDECREF(__pyx_v_numpy);
__Pyx_XDECREF(__pyx_v_arg);
__Pyx_XDECREF(__pyx_v_dtype);
__Pyx_XDECREF(__pyx_v_candidates);
__Pyx_XDECREF(__pyx_v_sig);
__Pyx_XDECREF(__pyx_v_src_type);
__Pyx_XDECREF(__pyx_v_dst_type);
__Pyx_XDECREF(__pyx_v_kwargs);
__Pyx_XGIVEREF(__pyx_r);
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* Python wrapper */
static PyObject *__pyx_fuse_0__pyx_pw_7sklearn_7metrics_13pairwise_fast_11_sparse_manhattan(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/
static PyMethodDef __pyx_fuse_0__pyx_mdef_7sklearn_7metrics_13pairwise_fast_11_sparse_manhattan = {__Pyx_NAMESTR("__pyx_fuse_0_sparse_manhattan"), (PyCFunction)__pyx_fuse_0__pyx_pw_7sklearn_7metrics_13pairwise_fast_11_sparse_manhattan, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_7metrics_13pairwise_fast_2_sparse_manhattan)};
static PyObject *__pyx_fuse_0__pyx_pw_7sklearn_7metrics_13pairwise_fast_11_sparse_manhattan(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) {
__Pyx_memviewslice __pyx_v_X_data = { 0, 0, { 0 }, { 0 }, { 0 } };
__Pyx_memviewslice __pyx_v_X_indices = { 0, 0, { 0 }, { 0 }, { 0 } };
__Pyx_memviewslice __pyx_v_X_indptr = { 0, 0, { 0 }, { 0 }, { 0 } };
__Pyx_memviewslice __pyx_v_Y_data = { 0, 0, { 0 }, { 0 }, { 0 } };
__Pyx_memviewslice __pyx_v_Y_indices = { 0, 0, { 0 }, { 0 }, { 0 } };
__Pyx_memviewslice __pyx_v_Y_indptr = { 0, 0, { 0 }, { 0 }, { 0 } };
npy_intp __pyx_v_n_features;
__Pyx_memviewslice __pyx_v_D = { 0, 0, { 0 }, { 0 }, { 0 } };
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
PyObject *__pyx_r = 0;
__Pyx_RefNannyDeclarations
__Pyx_RefNannySetupContext("_sparse_manhattan (wrapper)", 0);
{
static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_X_data,&__pyx_n_s_X_indices,&__pyx_n_s_X_indptr,&__pyx_n_s_Y_data,&__pyx_n_s_Y_indices,&__pyx_n_s_Y_indptr,&__pyx_n_s_n_features,&__pyx_n_s_D,0};
PyObject* values[8] = {0,0,0,0,0,0,0,0};
if (unlikely(__pyx_kwds)) {
Py_ssize_t kw_args;
const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args);
switch (pos_args) {
case 8: values[7] = PyTuple_GET_ITEM(__pyx_args, 7);
case 7: values[6] = PyTuple_GET_ITEM(__pyx_args, 6);
case 6: values[5] = PyTuple_GET_ITEM(__pyx_args, 5);
case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4);
case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3);
case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2);
case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1);
case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0);
case 0: break;
default: goto __pyx_L5_argtuple_error;
}
kw_args = PyDict_Size(__pyx_kwds);
switch (pos_args) {
case 0:
if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_X_data)) != 0)) kw_args--;
else goto __pyx_L5_argtuple_error;
case 1:
if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_X_indices)) != 0)) kw_args--;
else {
__Pyx_RaiseArgtupleInvalid("_sparse_manhattan", 1, 8, 8, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
}
case 2:
if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_X_indptr)) != 0)) kw_args--;
else {
__Pyx_RaiseArgtupleInvalid("_sparse_manhattan", 1, 8, 8, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
}
case 3:
if (likely((values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_Y_data)) != 0)) kw_args--;
else {
__Pyx_RaiseArgtupleInvalid("_sparse_manhattan", 1, 8, 8, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
}
case 4:
if (likely((values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_Y_indices)) != 0)) kw_args--;
else {
__Pyx_RaiseArgtupleInvalid("_sparse_manhattan", 1, 8, 8, 4); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
}
case 5:
if (likely((values[5] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_Y_indptr)) != 0)) kw_args--;
else {
__Pyx_RaiseArgtupleInvalid("_sparse_manhattan", 1, 8, 8, 5); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
}
case 6:
if (likely((values[6] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_n_features)) != 0)) kw_args--;
else {
__Pyx_RaiseArgtupleInvalid("_sparse_manhattan", 1, 8, 8, 6); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
}
case 7:
if (likely((values[7] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_D)) != 0)) kw_args--;
else {
__Pyx_RaiseArgtupleInvalid("_sparse_manhattan", 1, 8, 8, 7); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
}
}
if (unlikely(kw_args > 0)) {
if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "_sparse_manhattan") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
}
} else if (PyTuple_GET_SIZE(__pyx_args) != 8) {
goto __pyx_L5_argtuple_error;
} else {
values[0] = PyTuple_GET_ITEM(__pyx_args, 0);
values[1] = PyTuple_GET_ITEM(__pyx_args, 1);
values[2] = PyTuple_GET_ITEM(__pyx_args, 2);
values[3] = PyTuple_GET_ITEM(__pyx_args, 3);
values[4] = PyTuple_GET_ITEM(__pyx_args, 4);
values[5] = PyTuple_GET_ITEM(__pyx_args, 5);
values[6] = PyTuple_GET_ITEM(__pyx_args, 6);
values[7] = PyTuple_GET_ITEM(__pyx_args, 7);
}
__pyx_v_X_data = __Pyx_PyObject_to_MemoryviewSlice_dc_float(values[0]); if (unlikely(!__pyx_v_X_data.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
__pyx_v_X_indices = __Pyx_PyObject_to_MemoryviewSlice_ds_int(values[1]); if (unlikely(!__pyx_v_X_indices.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
__pyx_v_X_indptr = __Pyx_PyObject_to_MemoryviewSlice_ds_int(values[2]); if (unlikely(!__pyx_v_X_indptr.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
__pyx_v_Y_data = __Pyx_PyObject_to_MemoryviewSlice_dc_float(values[3]); if (unlikely(!__pyx_v_Y_data.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 54; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
__pyx_v_Y_indices = __Pyx_PyObject_to_MemoryviewSlice_ds_int(values[4]); if (unlikely(!__pyx_v_Y_indices.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 54; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
__pyx_v_Y_indptr = __Pyx_PyObject_to_MemoryviewSlice_ds_int(values[5]); if (unlikely(!__pyx_v_Y_indptr.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 54; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
__pyx_v_n_features = __Pyx_PyInt_As_Py_intptr_t(values[6]); if (unlikely((__pyx_v_n_features == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
__pyx_v_D = __Pyx_PyObject_to_MemoryviewSlice_d_dc_double(values[7]); if (unlikely(!__pyx_v_D.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
}
goto __pyx_L4_argument_unpacking_done;
__pyx_L5_argtuple_error:;
__Pyx_RaiseArgtupleInvalid("_sparse_manhattan", 1, 8, 8, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
__pyx_L3_error:;
__Pyx_AddTraceback("sklearn.metrics.pairwise_fast._sparse_manhattan", __pyx_clineno, __pyx_lineno, __pyx_filename);
__Pyx_RefNannyFinishContext();
return NULL;
__pyx_L4_argument_unpacking_done:;
__pyx_r = __pyx_pf_7sklearn_7metrics_13pairwise_fast_10_sparse_manhattan(__pyx_self, __pyx_v_X_data, __pyx_v_X_indices, __pyx_v_X_indptr, __pyx_v_Y_data, __pyx_v_Y_indices, __pyx_v_Y_indptr, __pyx_v_n_features, __pyx_v_D);
/* function exit code */
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
static PyObject *__pyx_pf_7sklearn_7metrics_13pairwise_fast_10_sparse_manhattan(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_X_data, __Pyx_memviewslice __pyx_v_X_indices, __Pyx_memviewslice __pyx_v_X_indptr, __Pyx_memviewslice __pyx_v_Y_data, __Pyx_memviewslice __pyx_v_Y_indices, __Pyx_memviewslice __pyx_v_Y_indptr, npy_intp __pyx_v_n_features, __Pyx_memviewslice __pyx_v_D) {
__Pyx_memviewslice __pyx_v_row = { 0, 0, { 0 }, { 0 }, { 0 } };
npy_intp __pyx_v_ix;
npy_intp __pyx_v_iy;
npy_intp __pyx_v_j;
PyObject *__pyx_r = NULL;
__Pyx_RefNannyDeclarations
PyObject *__pyx_t_1 = NULL;
PyObject *__pyx_t_2 = NULL;
PyObject *__pyx_t_3 = NULL;
__Pyx_memviewslice __pyx_t_4 = { 0, 0, { 0 }, { 0 }, { 0 } };
Py_ssize_t __pyx_t_5;
npy_intp __pyx_t_6;
Py_ssize_t __pyx_t_7;
npy_intp __pyx_t_8;
Py_ssize_t __pyx_t_9;
long __pyx_t_10;
int __pyx_t_11;
npy_intp __pyx_t_12;
npy_intp __pyx_t_13;
npy_intp __pyx_t_14;
npy_intp __pyx_t_15;
int __pyx_t_16;
long __pyx_t_17;
npy_intp __pyx_t_18;
npy_intp __pyx_t_19;
npy_intp __pyx_t_20;
int __pyx_t_21;
Py_ssize_t __pyx_t_22;
npy_intp __pyx_t_23;
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
__Pyx_RefNannySetupContext("__pyx_fuse_0_sparse_manhattan", 0);
/* "sklearn/metrics/pairwise_fast.pyx":65
* ... X.shape[1], D)
* """
* cdef double[::1] row = np.empty(n_features) # <<<<<<<<<<<<<<
* cdef np.npy_intp ix, iy, j
*
*/
__pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
__pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_empty); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_2);
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
__pyx_t_1 = __Pyx_PyInt_From_Py_intptr_t(__pyx_v_n_features); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
__pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_3);
PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1);
__Pyx_GIVEREF(__pyx_t_1);
__pyx_t_1 = 0;
__pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_3, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
__Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0;
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
__pyx_t_4 = __Pyx_PyObject_to_MemoryviewSlice_dc_double(__pyx_t_1);
if (unlikely(!__pyx_t_4.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
__pyx_v_row = __pyx_t_4;
__pyx_t_4.memview = NULL;
__pyx_t_4.data = NULL;
/* "sklearn/metrics/pairwise_fast.pyx":68
* cdef np.npy_intp ix, iy, j
*
* with nogil: # <<<<<<<<<<<<<<
* for ix in range(D.shape[0]):
* for iy in range(D.shape[1]):
*/
{
#ifdef WITH_THREAD
PyThreadState *_save;
Py_UNBLOCK_THREADS
#endif
/*try:*/ {
/* "sklearn/metrics/pairwise_fast.pyx":69
*
* with nogil:
* for ix in range(D.shape[0]): # <<<<<<<<<<<<<<
* for iy in range(D.shape[1]):
* # Simple strategy: densify current row of X, then subtract the
*/
__pyx_t_5 = (__pyx_v_D.shape[0]);
for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) {
__pyx_v_ix = __pyx_t_6;
/* "sklearn/metrics/pairwise_fast.pyx":70
* with nogil:
* for ix in range(D.shape[0]):
* for iy in range(D.shape[1]): # <<<<<<<<<<<<<<
* # Simple strategy: densify current row of X, then subtract the
* # corresponding row of Y.
*/
__pyx_t_7 = (__pyx_v_D.shape[1]);
for (__pyx_t_8 = 0; __pyx_t_8 < __pyx_t_7; __pyx_t_8+=1) {
__pyx_v_iy = __pyx_t_8;
/* "sklearn/metrics/pairwise_fast.pyx":73
* # Simple strategy: densify current row of X, then subtract the
* # corresponding row of Y.
* memset(&row[0], 0, n_features * sizeof(double)) # <<<<<<<<<<<<<<
* for j in range(X_indptr[ix], X_indptr[ix + 1]):
* row[X_indices[j]] = X_data[j]
*/
__pyx_t_9 = 0;
memset((&(*((double *) ( /* dim=0 */ ((char *) (((double *) __pyx_v_row.data) + __pyx_t_9)) )))), 0, (__pyx_v_n_features * (sizeof(double))));
/* "sklearn/metrics/pairwise_fast.pyx":74
* # corresponding row of Y.
* memset(&row[0], 0, n_features * sizeof(double))
* for j in range(X_indptr[ix], X_indptr[ix + 1]): # <<<<<<<<<<<<<<
* row[X_indices[j]] = X_data[j]
* for j in range(Y_indptr[iy], Y_indptr[iy + 1]):
*/
__pyx_t_10 = (__pyx_v_ix + 1);
__pyx_t_11 = (*((int *) ( /* dim=0 */ (__pyx_v_X_indptr.data + __pyx_t_10 * __pyx_v_X_indptr.strides[0]) )));
__pyx_t_12 = __pyx_v_ix;
for (__pyx_t_13 = (*((int *) ( /* dim=0 */ (__pyx_v_X_indptr.data + __pyx_t_12 * __pyx_v_X_indptr.strides[0]) ))); __pyx_t_13 < __pyx_t_11; __pyx_t_13+=1) {
__pyx_v_j = __pyx_t_13;
/* "sklearn/metrics/pairwise_fast.pyx":75
* memset(&row[0], 0, n_features * sizeof(double))
* for j in range(X_indptr[ix], X_indptr[ix + 1]):
* row[X_indices[j]] = X_data[j] # <<<<<<<<<<<<<<
* for j in range(Y_indptr[iy], Y_indptr[iy + 1]):
* row[Y_indices[j]] -= Y_data[j]
*/
__pyx_t_14 = __pyx_v_j;
__pyx_t_15 = __pyx_v_j;
__pyx_t_16 = (*((int *) ( /* dim=0 */ (__pyx_v_X_indices.data + __pyx_t_15 * __pyx_v_X_indices.strides[0]) )));
*((double *) ( /* dim=0 */ ((char *) (((double *) __pyx_v_row.data) + __pyx_t_16)) )) = (*((float *) ( /* dim=0 */ ((char *) (((float *) __pyx_v_X_data.data) + __pyx_t_14)) )));
}
/* "sklearn/metrics/pairwise_fast.pyx":76
* for j in range(X_indptr[ix], X_indptr[ix + 1]):
* row[X_indices[j]] = X_data[j]
* for j in range(Y_indptr[iy], Y_indptr[iy + 1]): # <<<<<<<<<<<<<<
* row[Y_indices[j]] -= Y_data[j]
*
*/
__pyx_t_17 = (__pyx_v_iy + 1);
__pyx_t_11 = (*((int *) ( /* dim=0 */ (__pyx_v_Y_indptr.data + __pyx_t_17 * __pyx_v_Y_indptr.strides[0]) )));
__pyx_t_13 = __pyx_v_iy;
for (__pyx_t_18 = (*((int *) ( /* dim=0 */ (__pyx_v_Y_indptr.data + __pyx_t_13 * __pyx_v_Y_indptr.strides[0]) ))); __pyx_t_18 < __pyx_t_11; __pyx_t_18+=1) {
__pyx_v_j = __pyx_t_18;
/* "sklearn/metrics/pairwise_fast.pyx":77
* row[X_indices[j]] = X_data[j]
* for j in range(Y_indptr[iy], Y_indptr[iy + 1]):
* row[Y_indices[j]] -= Y_data[j] # <<<<<<<<<<<<<<
*
* D[ix, iy] = cblas_dasum(n_features, &row[0], 1)
*/
__pyx_t_19 = __pyx_v_j;
__pyx_t_20 = __pyx_v_j;
__pyx_t_21 = (*((int *) ( /* dim=0 */ (__pyx_v_Y_indices.data + __pyx_t_20 * __pyx_v_Y_indices.strides[0]) )));
*((double *) ( /* dim=0 */ ((char *) (((double *) __pyx_v_row.data) + __pyx_t_21)) )) -= (*((float *) ( /* dim=0 */ ((char *) (((float *) __pyx_v_Y_data.data) + __pyx_t_19)) )));
}
/* "sklearn/metrics/pairwise_fast.pyx":79
* row[Y_indices[j]] -= Y_data[j]
*
* D[ix, iy] = cblas_dasum(n_features, &row[0], 1) # <<<<<<<<<<<<<<
*/
__pyx_t_22 = 0;
__pyx_t_18 = __pyx_v_ix;
__pyx_t_23 = __pyx_v_iy;
*((double *) ( /* dim=1 */ ((char *) (((double *) ( /* dim=0 */ (__pyx_v_D.data + __pyx_t_18 * __pyx_v_D.strides[0]) )) + __pyx_t_23)) )) = cblas_dasum(__pyx_v_n_features, (&(*((double *) ( /* dim=0 */ ((char *) (((double *) __pyx_v_row.data) + __pyx_t_22)) )))), 1);
}
}
}
/* "sklearn/metrics/pairwise_fast.pyx":68
* cdef np.npy_intp ix, iy, j
*
* with nogil: # <<<<<<<<<<<<<<
* for ix in range(D.shape[0]):
* for iy in range(D.shape[1]):
*/
/*finally:*/ {
/*normal exit:*/{
#ifdef WITH_THREAD
Py_BLOCK_THREADS
#endif
goto __pyx_L5;
}
__pyx_L5:;
}
}
/* "sklearn/metrics/pairwise_fast.pyx":53
*
*
* def _sparse_manhattan(floating1d X_data, int[:] X_indices, int[:] X_indptr, # <<<<<<<<<<<<<<
* floating1d Y_data, int[:] Y_indices, int[:] Y_indptr,
* np.npy_intp n_features, double[:, ::1] D):
*/
/* function exit code */
__pyx_r = Py_None; __Pyx_INCREF(Py_None);
goto __pyx_L0;
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_1);
__Pyx_XDECREF(__pyx_t_2);
__Pyx_XDECREF(__pyx_t_3);
__PYX_XDEC_MEMVIEW(&__pyx_t_4, 1);
__Pyx_AddTraceback("sklearn.metrics.pairwise_fast._sparse_manhattan", __pyx_clineno, __pyx_lineno, __pyx_filename);
__pyx_r = NULL;
__pyx_L0:;
__PYX_XDEC_MEMVIEW(&__pyx_v_row, 1);
__PYX_XDEC_MEMVIEW(&__pyx_v_X_data, 1);
__PYX_XDEC_MEMVIEW(&__pyx_v_X_indices, 1);
__PYX_XDEC_MEMVIEW(&__pyx_v_X_indptr, 1);
__PYX_XDEC_MEMVIEW(&__pyx_v_Y_data, 1);
__PYX_XDEC_MEMVIEW(&__pyx_v_Y_indices, 1);
__PYX_XDEC_MEMVIEW(&__pyx_v_Y_indptr, 1);
__PYX_XDEC_MEMVIEW(&__pyx_v_D, 1);
__Pyx_XGIVEREF(__pyx_r);
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* Python wrapper */
static PyObject *__pyx_fuse_1__pyx_pw_7sklearn_7metrics_13pairwise_fast_13_sparse_manhattan(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/
static PyMethodDef __pyx_fuse_1__pyx_mdef_7sklearn_7metrics_13pairwise_fast_13_sparse_manhattan = {__Pyx_NAMESTR("__pyx_fuse_1_sparse_manhattan"), (PyCFunction)__pyx_fuse_1__pyx_pw_7sklearn_7metrics_13pairwise_fast_13_sparse_manhattan, METH_VARARGS|METH_KEYWORDS, __Pyx_DOCSTR(__pyx_doc_7sklearn_7metrics_13pairwise_fast_2_sparse_manhattan)};
static PyObject *__pyx_fuse_1__pyx_pw_7sklearn_7metrics_13pairwise_fast_13_sparse_manhattan(PyObject *__pyx_self, PyObject *__pyx_args, PyObject *__pyx_kwds) {
__Pyx_memviewslice __pyx_v_X_data = { 0, 0, { 0 }, { 0 }, { 0 } };
__Pyx_memviewslice __pyx_v_X_indices = { 0, 0, { 0 }, { 0 }, { 0 } };
__Pyx_memviewslice __pyx_v_X_indptr = { 0, 0, { 0 }, { 0 }, { 0 } };
__Pyx_memviewslice __pyx_v_Y_data = { 0, 0, { 0 }, { 0 }, { 0 } };
__Pyx_memviewslice __pyx_v_Y_indices = { 0, 0, { 0 }, { 0 }, { 0 } };
__Pyx_memviewslice __pyx_v_Y_indptr = { 0, 0, { 0 }, { 0 }, { 0 } };
npy_intp __pyx_v_n_features;
__Pyx_memviewslice __pyx_v_D = { 0, 0, { 0 }, { 0 }, { 0 } };
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
PyObject *__pyx_r = 0;
__Pyx_RefNannyDeclarations
__Pyx_RefNannySetupContext("_sparse_manhattan (wrapper)", 0);
{
static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_X_data,&__pyx_n_s_X_indices,&__pyx_n_s_X_indptr,&__pyx_n_s_Y_data,&__pyx_n_s_Y_indices,&__pyx_n_s_Y_indptr,&__pyx_n_s_n_features,&__pyx_n_s_D,0};
PyObject* values[8] = {0,0,0,0,0,0,0,0};
if (unlikely(__pyx_kwds)) {
Py_ssize_t kw_args;
const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args);
switch (pos_args) {
case 8: values[7] = PyTuple_GET_ITEM(__pyx_args, 7);
case 7: values[6] = PyTuple_GET_ITEM(__pyx_args, 6);
case 6: values[5] = PyTuple_GET_ITEM(__pyx_args, 5);
case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4);
case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3);
case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2);
case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1);
case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0);
case 0: break;
default: goto __pyx_L5_argtuple_error;
}
kw_args = PyDict_Size(__pyx_kwds);
switch (pos_args) {
case 0:
if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_X_data)) != 0)) kw_args--;
else goto __pyx_L5_argtuple_error;
case 1:
if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_X_indices)) != 0)) kw_args--;
else {
__Pyx_RaiseArgtupleInvalid("_sparse_manhattan", 1, 8, 8, 1); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
}
case 2:
if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_X_indptr)) != 0)) kw_args--;
else {
__Pyx_RaiseArgtupleInvalid("_sparse_manhattan", 1, 8, 8, 2); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
}
case 3:
if (likely((values[3] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_Y_data)) != 0)) kw_args--;
else {
__Pyx_RaiseArgtupleInvalid("_sparse_manhattan", 1, 8, 8, 3); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
}
case 4:
if (likely((values[4] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_Y_indices)) != 0)) kw_args--;
else {
__Pyx_RaiseArgtupleInvalid("_sparse_manhattan", 1, 8, 8, 4); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
}
case 5:
if (likely((values[5] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_Y_indptr)) != 0)) kw_args--;
else {
__Pyx_RaiseArgtupleInvalid("_sparse_manhattan", 1, 8, 8, 5); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
}
case 6:
if (likely((values[6] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_n_features)) != 0)) kw_args--;
else {
__Pyx_RaiseArgtupleInvalid("_sparse_manhattan", 1, 8, 8, 6); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
}
case 7:
if (likely((values[7] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_D)) != 0)) kw_args--;
else {
__Pyx_RaiseArgtupleInvalid("_sparse_manhattan", 1, 8, 8, 7); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
}
}
if (unlikely(kw_args > 0)) {
if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "_sparse_manhattan") < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
}
} else if (PyTuple_GET_SIZE(__pyx_args) != 8) {
goto __pyx_L5_argtuple_error;
} else {
values[0] = PyTuple_GET_ITEM(__pyx_args, 0);
values[1] = PyTuple_GET_ITEM(__pyx_args, 1);
values[2] = PyTuple_GET_ITEM(__pyx_args, 2);
values[3] = PyTuple_GET_ITEM(__pyx_args, 3);
values[4] = PyTuple_GET_ITEM(__pyx_args, 4);
values[5] = PyTuple_GET_ITEM(__pyx_args, 5);
values[6] = PyTuple_GET_ITEM(__pyx_args, 6);
values[7] = PyTuple_GET_ITEM(__pyx_args, 7);
}
__pyx_v_X_data = __Pyx_PyObject_to_MemoryviewSlice_dc_double(values[0]); if (unlikely(!__pyx_v_X_data.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
__pyx_v_X_indices = __Pyx_PyObject_to_MemoryviewSlice_ds_int(values[1]); if (unlikely(!__pyx_v_X_indices.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
__pyx_v_X_indptr = __Pyx_PyObject_to_MemoryviewSlice_ds_int(values[2]); if (unlikely(!__pyx_v_X_indptr.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
__pyx_v_Y_data = __Pyx_PyObject_to_MemoryviewSlice_dc_double(values[3]); if (unlikely(!__pyx_v_Y_data.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 54; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
__pyx_v_Y_indices = __Pyx_PyObject_to_MemoryviewSlice_ds_int(values[4]); if (unlikely(!__pyx_v_Y_indices.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 54; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
__pyx_v_Y_indptr = __Pyx_PyObject_to_MemoryviewSlice_ds_int(values[5]); if (unlikely(!__pyx_v_Y_indptr.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 54; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
__pyx_v_n_features = __Pyx_PyInt_As_Py_intptr_t(values[6]); if (unlikely((__pyx_v_n_features == (npy_intp)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
__pyx_v_D = __Pyx_PyObject_to_MemoryviewSlice_d_dc_double(values[7]); if (unlikely(!__pyx_v_D.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 55; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
}
goto __pyx_L4_argument_unpacking_done;
__pyx_L5_argtuple_error:;
__Pyx_RaiseArgtupleInvalid("_sparse_manhattan", 1, 8, 8, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
__pyx_L3_error:;
__Pyx_AddTraceback("sklearn.metrics.pairwise_fast._sparse_manhattan", __pyx_clineno, __pyx_lineno, __pyx_filename);
__Pyx_RefNannyFinishContext();
return NULL;
__pyx_L4_argument_unpacking_done:;
__pyx_r = __pyx_pf_7sklearn_7metrics_13pairwise_fast_12_sparse_manhattan(__pyx_self, __pyx_v_X_data, __pyx_v_X_indices, __pyx_v_X_indptr, __pyx_v_Y_data, __pyx_v_Y_indices, __pyx_v_Y_indptr, __pyx_v_n_features, __pyx_v_D);
/* function exit code */
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
static PyObject *__pyx_pf_7sklearn_7metrics_13pairwise_fast_12_sparse_manhattan(CYTHON_UNUSED PyObject *__pyx_self, __Pyx_memviewslice __pyx_v_X_data, __Pyx_memviewslice __pyx_v_X_indices, __Pyx_memviewslice __pyx_v_X_indptr, __Pyx_memviewslice __pyx_v_Y_data, __Pyx_memviewslice __pyx_v_Y_indices, __Pyx_memviewslice __pyx_v_Y_indptr, npy_intp __pyx_v_n_features, __Pyx_memviewslice __pyx_v_D) {
__Pyx_memviewslice __pyx_v_row = { 0, 0, { 0 }, { 0 }, { 0 } };
npy_intp __pyx_v_ix;
npy_intp __pyx_v_iy;
npy_intp __pyx_v_j;
PyObject *__pyx_r = NULL;
__Pyx_RefNannyDeclarations
PyObject *__pyx_t_1 = NULL;
PyObject *__pyx_t_2 = NULL;
PyObject *__pyx_t_3 = NULL;
__Pyx_memviewslice __pyx_t_4 = { 0, 0, { 0 }, { 0 }, { 0 } };
Py_ssize_t __pyx_t_5;
npy_intp __pyx_t_6;
Py_ssize_t __pyx_t_7;
npy_intp __pyx_t_8;
Py_ssize_t __pyx_t_9;
long __pyx_t_10;
int __pyx_t_11;
npy_intp __pyx_t_12;
npy_intp __pyx_t_13;
npy_intp __pyx_t_14;
npy_intp __pyx_t_15;
int __pyx_t_16;
long __pyx_t_17;
npy_intp __pyx_t_18;
npy_intp __pyx_t_19;
npy_intp __pyx_t_20;
int __pyx_t_21;
Py_ssize_t __pyx_t_22;
npy_intp __pyx_t_23;
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
__Pyx_RefNannySetupContext("__pyx_fuse_1_sparse_manhattan", 0);
/* "sklearn/metrics/pairwise_fast.pyx":65
* ... X.shape[1], D)
* """
* cdef double[::1] row = np.empty(n_features) # <<<<<<<<<<<<<<
* cdef np.npy_intp ix, iy, j
*
*/
__pyx_t_1 = __Pyx_GetModuleGlobalName(__pyx_n_s_np); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
__pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_empty); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_2);
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
__pyx_t_1 = __Pyx_PyInt_From_Py_intptr_t(__pyx_v_n_features); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
__pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_3);
PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_1);
__Pyx_GIVEREF(__pyx_t_1);
__pyx_t_1 = 0;
__pyx_t_1 = __Pyx_PyObject_Call(__pyx_t_2, __pyx_t_3, NULL); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
__Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0;
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
__pyx_t_4 = __Pyx_PyObject_to_MemoryviewSlice_dc_double(__pyx_t_1);
if (unlikely(!__pyx_t_4.memview)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 65; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
__pyx_v_row = __pyx_t_4;
__pyx_t_4.memview = NULL;
__pyx_t_4.data = NULL;
/* "sklearn/metrics/pairwise_fast.pyx":68
* cdef np.npy_intp ix, iy, j
*
* with nogil: # <<<<<<<<<<<<<<
* for ix in range(D.shape[0]):
* for iy in range(D.shape[1]):
*/
{
#ifdef WITH_THREAD
PyThreadState *_save;
Py_UNBLOCK_THREADS
#endif
/*try:*/ {
/* "sklearn/metrics/pairwise_fast.pyx":69
*
* with nogil:
* for ix in range(D.shape[0]): # <<<<<<<<<<<<<<
* for iy in range(D.shape[1]):
* # Simple strategy: densify current row of X, then subtract the
*/
__pyx_t_5 = (__pyx_v_D.shape[0]);
for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) {
__pyx_v_ix = __pyx_t_6;
/* "sklearn/metrics/pairwise_fast.pyx":70
* with nogil:
* for ix in range(D.shape[0]):
* for iy in range(D.shape[1]): # <<<<<<<<<<<<<<
* # Simple strategy: densify current row of X, then subtract the
* # corresponding row of Y.
*/
__pyx_t_7 = (__pyx_v_D.shape[1]);
for (__pyx_t_8 = 0; __pyx_t_8 < __pyx_t_7; __pyx_t_8+=1) {
__pyx_v_iy = __pyx_t_8;
/* "sklearn/metrics/pairwise_fast.pyx":73
* # Simple strategy: densify current row of X, then subtract the
* # corresponding row of Y.
* memset(&row[0], 0, n_features * sizeof(double)) # <<<<<<<<<<<<<<
* for j in range(X_indptr[ix], X_indptr[ix + 1]):
* row[X_indices[j]] = X_data[j]
*/
__pyx_t_9 = 0;
memset((&(*((double *) ( /* dim=0 */ ((char *) (((double *) __pyx_v_row.data) + __pyx_t_9)) )))), 0, (__pyx_v_n_features * (sizeof(double))));
/* "sklearn/metrics/pairwise_fast.pyx":74
* # corresponding row of Y.
* memset(&row[0], 0, n_features * sizeof(double))
* for j in range(X_indptr[ix], X_indptr[ix + 1]): # <<<<<<<<<<<<<<
* row[X_indices[j]] = X_data[j]
* for j in range(Y_indptr[iy], Y_indptr[iy + 1]):
*/
__pyx_t_10 = (__pyx_v_ix + 1);
__pyx_t_11 = (*((int *) ( /* dim=0 */ (__pyx_v_X_indptr.data + __pyx_t_10 * __pyx_v_X_indptr.strides[0]) )));
__pyx_t_12 = __pyx_v_ix;
for (__pyx_t_13 = (*((int *) ( /* dim=0 */ (__pyx_v_X_indptr.data + __pyx_t_12 * __pyx_v_X_indptr.strides[0]) ))); __pyx_t_13 < __pyx_t_11; __pyx_t_13+=1) {
__pyx_v_j = __pyx_t_13;
/* "sklearn/metrics/pairwise_fast.pyx":75
* memset(&row[0], 0, n_features * sizeof(double))
* for j in range(X_indptr[ix], X_indptr[ix + 1]):
* row[X_indices[j]] = X_data[j] # <<<<<<<<<<<<<<
* for j in range(Y_indptr[iy], Y_indptr[iy + 1]):
* row[Y_indices[j]] -= Y_data[j]
*/
__pyx_t_14 = __pyx_v_j;
__pyx_t_15 = __pyx_v_j;
__pyx_t_16 = (*((int *) ( /* dim=0 */ (__pyx_v_X_indices.data + __pyx_t_15 * __pyx_v_X_indices.strides[0]) )));
*((double *) ( /* dim=0 */ ((char *) (((double *) __pyx_v_row.data) + __pyx_t_16)) )) = (*((double *) ( /* dim=0 */ ((char *) (((double *) __pyx_v_X_data.data) + __pyx_t_14)) )));
}
/* "sklearn/metrics/pairwise_fast.pyx":76
* for j in range(X_indptr[ix], X_indptr[ix + 1]):
* row[X_indices[j]] = X_data[j]
* for j in range(Y_indptr[iy], Y_indptr[iy + 1]): # <<<<<<<<<<<<<<
* row[Y_indices[j]] -= Y_data[j]
*
*/
__pyx_t_17 = (__pyx_v_iy + 1);
__pyx_t_11 = (*((int *) ( /* dim=0 */ (__pyx_v_Y_indptr.data + __pyx_t_17 * __pyx_v_Y_indptr.strides[0]) )));
__pyx_t_13 = __pyx_v_iy;
for (__pyx_t_18 = (*((int *) ( /* dim=0 */ (__pyx_v_Y_indptr.data + __pyx_t_13 * __pyx_v_Y_indptr.strides[0]) ))); __pyx_t_18 < __pyx_t_11; __pyx_t_18+=1) {
__pyx_v_j = __pyx_t_18;
/* "sklearn/metrics/pairwise_fast.pyx":77
* row[X_indices[j]] = X_data[j]
* for j in range(Y_indptr[iy], Y_indptr[iy + 1]):
* row[Y_indices[j]] -= Y_data[j] # <<<<<<<<<<<<<<
*
* D[ix, iy] = cblas_dasum(n_features, &row[0], 1)
*/
__pyx_t_19 = __pyx_v_j;
__pyx_t_20 = __pyx_v_j;
__pyx_t_21 = (*((int *) ( /* dim=0 */ (__pyx_v_Y_indices.data + __pyx_t_20 * __pyx_v_Y_indices.strides[0]) )));
*((double *) ( /* dim=0 */ ((char *) (((double *) __pyx_v_row.data) + __pyx_t_21)) )) -= (*((double *) ( /* dim=0 */ ((char *) (((double *) __pyx_v_Y_data.data) + __pyx_t_19)) )));
}
/* "sklearn/metrics/pairwise_fast.pyx":79
* row[Y_indices[j]] -= Y_data[j]
*
* D[ix, iy] = cblas_dasum(n_features, &row[0], 1) # <<<<<<<<<<<<<<
*/
__pyx_t_22 = 0;
__pyx_t_18 = __pyx_v_ix;
__pyx_t_23 = __pyx_v_iy;
*((double *) ( /* dim=1 */ ((char *) (((double *) ( /* dim=0 */ (__pyx_v_D.data + __pyx_t_18 * __pyx_v_D.strides[0]) )) + __pyx_t_23)) )) = cblas_dasum(__pyx_v_n_features, (&(*((double *) ( /* dim=0 */ ((char *) (((double *) __pyx_v_row.data) + __pyx_t_22)) )))), 1);
}
}
}
/* "sklearn/metrics/pairwise_fast.pyx":68
* cdef np.npy_intp ix, iy, j
*
* with nogil: # <<<<<<<<<<<<<<
* for ix in range(D.shape[0]):
* for iy in range(D.shape[1]):
*/
/*finally:*/ {
/*normal exit:*/{
#ifdef WITH_THREAD
Py_BLOCK_THREADS
#endif
goto __pyx_L5;
}
__pyx_L5:;
}
}
/* "sklearn/metrics/pairwise_fast.pyx":53
*
*
* def _sparse_manhattan(floating1d X_data, int[:] X_indices, int[:] X_indptr, # <<<<<<<<<<<<<<
* floating1d Y_data, int[:] Y_indices, int[:] Y_indptr,
* np.npy_intp n_features, double[:, ::1] D):
*/
/* function exit code */
__pyx_r = Py_None; __Pyx_INCREF(Py_None);
goto __pyx_L0;
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_1);
__Pyx_XDECREF(__pyx_t_2);
__Pyx_XDECREF(__pyx_t_3);
__PYX_XDEC_MEMVIEW(&__pyx_t_4, 1);
__Pyx_AddTraceback("sklearn.metrics.pairwise_fast._sparse_manhattan", __pyx_clineno, __pyx_lineno, __pyx_filename);
__pyx_r = NULL;
__pyx_L0:;
__PYX_XDEC_MEMVIEW(&__pyx_v_row, 1);
__PYX_XDEC_MEMVIEW(&__pyx_v_X_data, 1);
__PYX_XDEC_MEMVIEW(&__pyx_v_X_indices, 1);
__PYX_XDEC_MEMVIEW(&__pyx_v_X_indptr, 1);
__PYX_XDEC_MEMVIEW(&__pyx_v_Y_data, 1);
__PYX_XDEC_MEMVIEW(&__pyx_v_Y_indices, 1);
__PYX_XDEC_MEMVIEW(&__pyx_v_Y_indptr, 1);
__PYX_XDEC_MEMVIEW(&__pyx_v_D, 1);
__Pyx_XGIVEREF(__pyx_r);
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":194
* # experimental exception made for __getbuffer__ and __releasebuffer__
* # -- the details of this may change.
* def __getbuffer__(ndarray self, Py_buffer* info, int flags): # <<<<<<<<<<<<<<
* # This implementation of getbuffer is geared towards Cython
* # requirements, and does not yet fullfill the PEP.
*/
/* Python wrapper */
static CYTHON_UNUSED int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/
static CYTHON_UNUSED int __pyx_pw_5numpy_7ndarray_1__getbuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) {
int __pyx_r;
__Pyx_RefNannyDeclarations
__Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0);
__pyx_r = __pyx_pf_5numpy_7ndarray___getbuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags));
/* function exit code */
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
static int __pyx_pf_5numpy_7ndarray___getbuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) {
int __pyx_v_copy_shape;
int __pyx_v_i;
int __pyx_v_ndim;
int __pyx_v_endian_detector;
int __pyx_v_little_endian;
int __pyx_v_t;
char *__pyx_v_f;
PyArray_Descr *__pyx_v_descr = 0;
int __pyx_v_offset;
int __pyx_v_hasfields;
int __pyx_r;
__Pyx_RefNannyDeclarations
int __pyx_t_1;
int __pyx_t_2;
int __pyx_t_3;
PyObject *__pyx_t_4 = NULL;
int __pyx_t_5;
int __pyx_t_6;
int __pyx_t_7;
PyObject *__pyx_t_8 = NULL;
char *__pyx_t_9;
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
__Pyx_RefNannySetupContext("__getbuffer__", 0);
if (__pyx_v_info != NULL) {
__pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None);
__Pyx_GIVEREF(__pyx_v_info->obj);
}
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":200
* # of flags
*
* if info == NULL: return # <<<<<<<<<<<<<<
*
* cdef int copy_shape, i, ndim
*/
__pyx_t_1 = ((__pyx_v_info == NULL) != 0);
if (__pyx_t_1) {
__pyx_r = 0;
goto __pyx_L0;
}
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":203
*
* cdef int copy_shape, i, ndim
* cdef int endian_detector = 1 # <<<<<<<<<<<<<<
* cdef bint little_endian = ((<char*>&endian_detector)[0] != 0)
*
*/
__pyx_v_endian_detector = 1;
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":204
* cdef int copy_shape, i, ndim
* cdef int endian_detector = 1
* cdef bint little_endian = ((<char*>&endian_detector)[0] != 0) # <<<<<<<<<<<<<<
*
* ndim = PyArray_NDIM(self)
*/
__pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0);
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":206
* cdef bint little_endian = ((<char*>&endian_detector)[0] != 0)
*
* ndim = PyArray_NDIM(self) # <<<<<<<<<<<<<<
*
* if sizeof(npy_intp) != sizeof(Py_ssize_t):
*/
__pyx_v_ndim = PyArray_NDIM(__pyx_v_self);
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":208
* ndim = PyArray_NDIM(self)
*
* if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<<
* copy_shape = 1
* else:
*/
__pyx_t_1 = (((sizeof(npy_intp)) != (sizeof(Py_ssize_t))) != 0);
if (__pyx_t_1) {
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":209
*
* if sizeof(npy_intp) != sizeof(Py_ssize_t):
* copy_shape = 1 # <<<<<<<<<<<<<<
* else:
* copy_shape = 0
*/
__pyx_v_copy_shape = 1;
goto __pyx_L4;
}
/*else*/ {
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":211
* copy_shape = 1
* else:
* copy_shape = 0 # <<<<<<<<<<<<<<
*
* if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS)
*/
__pyx_v_copy_shape = 0;
}
__pyx_L4:;
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":213
* copy_shape = 0
*
* if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS) # <<<<<<<<<<<<<<
* and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)):
* raise ValueError(u"ndarray is not C contiguous")
*/
__pyx_t_1 = (((__pyx_v_flags & PyBUF_C_CONTIGUOUS) == PyBUF_C_CONTIGUOUS) != 0);
if (__pyx_t_1) {
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":214
*
* if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS)
* and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)): # <<<<<<<<<<<<<<
* raise ValueError(u"ndarray is not C contiguous")
*
*/
__pyx_t_2 = ((!(PyArray_CHKFLAGS(__pyx_v_self, NPY_C_CONTIGUOUS) != 0)) != 0);
__pyx_t_3 = __pyx_t_2;
} else {
__pyx_t_3 = __pyx_t_1;
}
if (__pyx_t_3) {
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":215
* if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS)
* and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)):
* raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<<
*
* if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS)
*/
__pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__13, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_4);
__Pyx_Raise(__pyx_t_4, 0, 0, 0);
__Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
{__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
}
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":217
* raise ValueError(u"ndarray is not C contiguous")
*
* if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS) # <<<<<<<<<<<<<<
* and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)):
* raise ValueError(u"ndarray is not Fortran contiguous")
*/
__pyx_t_3 = (((__pyx_v_flags & PyBUF_F_CONTIGUOUS) == PyBUF_F_CONTIGUOUS) != 0);
if (__pyx_t_3) {
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":218
*
* if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS)
* and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)): # <<<<<<<<<<<<<<
* raise ValueError(u"ndarray is not Fortran contiguous")
*
*/
__pyx_t_1 = ((!(PyArray_CHKFLAGS(__pyx_v_self, NPY_F_CONTIGUOUS) != 0)) != 0);
__pyx_t_2 = __pyx_t_1;
} else {
__pyx_t_2 = __pyx_t_3;
}
if (__pyx_t_2) {
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":219
* if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS)
* and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)):
* raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<<
*
* info.buf = PyArray_DATA(self)
*/
__pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__14, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_4);
__Pyx_Raise(__pyx_t_4, 0, 0, 0);
__Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
{__pyx_filename = __pyx_f[1]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
}
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":221
* raise ValueError(u"ndarray is not Fortran contiguous")
*
* info.buf = PyArray_DATA(self) # <<<<<<<<<<<<<<
* info.ndim = ndim
* if copy_shape:
*/
__pyx_v_info->buf = PyArray_DATA(__pyx_v_self);
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":222
*
* info.buf = PyArray_DATA(self)
* info.ndim = ndim # <<<<<<<<<<<<<<
* if copy_shape:
* # Allocate new buffer for strides and shape info.
*/
__pyx_v_info->ndim = __pyx_v_ndim;
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":223
* info.buf = PyArray_DATA(self)
* info.ndim = ndim
* if copy_shape: # <<<<<<<<<<<<<<
* # Allocate new buffer for strides and shape info.
* # This is allocated as one block, strides first.
*/
__pyx_t_2 = (__pyx_v_copy_shape != 0);
if (__pyx_t_2) {
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":226
* # Allocate new buffer for strides and shape info.
* # This is allocated as one block, strides first.
* info.strides = <Py_ssize_t*>stdlib.malloc(sizeof(Py_ssize_t) * <size_t>ndim * 2) # <<<<<<<<<<<<<<
* info.shape = info.strides + ndim
* for i in range(ndim):
*/
__pyx_v_info->strides = ((Py_ssize_t *)malloc((((sizeof(Py_ssize_t)) * ((size_t)__pyx_v_ndim)) * 2)));
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":227
* # This is allocated as one block, strides first.
* info.strides = <Py_ssize_t*>stdlib.malloc(sizeof(Py_ssize_t) * <size_t>ndim * 2)
* info.shape = info.strides + ndim # <<<<<<<<<<<<<<
* for i in range(ndim):
* info.strides[i] = PyArray_STRIDES(self)[i]
*/
__pyx_v_info->shape = (__pyx_v_info->strides + __pyx_v_ndim);
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":228
* info.strides = <Py_ssize_t*>stdlib.malloc(sizeof(Py_ssize_t) * <size_t>ndim * 2)
* info.shape = info.strides + ndim
* for i in range(ndim): # <<<<<<<<<<<<<<
* info.strides[i] = PyArray_STRIDES(self)[i]
* info.shape[i] = PyArray_DIMS(self)[i]
*/
__pyx_t_5 = __pyx_v_ndim;
for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) {
__pyx_v_i = __pyx_t_6;
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":229
* info.shape = info.strides + ndim
* for i in range(ndim):
* info.strides[i] = PyArray_STRIDES(self)[i] # <<<<<<<<<<<<<<
* info.shape[i] = PyArray_DIMS(self)[i]
* else:
*/
(__pyx_v_info->strides[__pyx_v_i]) = (PyArray_STRIDES(__pyx_v_self)[__pyx_v_i]);
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":230
* for i in range(ndim):
* info.strides[i] = PyArray_STRIDES(self)[i]
* info.shape[i] = PyArray_DIMS(self)[i] # <<<<<<<<<<<<<<
* else:
* info.strides = <Py_ssize_t*>PyArray_STRIDES(self)
*/
(__pyx_v_info->shape[__pyx_v_i]) = (PyArray_DIMS(__pyx_v_self)[__pyx_v_i]);
}
goto __pyx_L7;
}
/*else*/ {
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":232
* info.shape[i] = PyArray_DIMS(self)[i]
* else:
* info.strides = <Py_ssize_t*>PyArray_STRIDES(self) # <<<<<<<<<<<<<<
* info.shape = <Py_ssize_t*>PyArray_DIMS(self)
* info.suboffsets = NULL
*/
__pyx_v_info->strides = ((Py_ssize_t *)PyArray_STRIDES(__pyx_v_self));
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":233
* else:
* info.strides = <Py_ssize_t*>PyArray_STRIDES(self)
* info.shape = <Py_ssize_t*>PyArray_DIMS(self) # <<<<<<<<<<<<<<
* info.suboffsets = NULL
* info.itemsize = PyArray_ITEMSIZE(self)
*/
__pyx_v_info->shape = ((Py_ssize_t *)PyArray_DIMS(__pyx_v_self));
}
__pyx_L7:;
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":234
* info.strides = <Py_ssize_t*>PyArray_STRIDES(self)
* info.shape = <Py_ssize_t*>PyArray_DIMS(self)
* info.suboffsets = NULL # <<<<<<<<<<<<<<
* info.itemsize = PyArray_ITEMSIZE(self)
* info.readonly = not PyArray_ISWRITEABLE(self)
*/
__pyx_v_info->suboffsets = NULL;
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":235
* info.shape = <Py_ssize_t*>PyArray_DIMS(self)
* info.suboffsets = NULL
* info.itemsize = PyArray_ITEMSIZE(self) # <<<<<<<<<<<<<<
* info.readonly = not PyArray_ISWRITEABLE(self)
*
*/
__pyx_v_info->itemsize = PyArray_ITEMSIZE(__pyx_v_self);
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":236
* info.suboffsets = NULL
* info.itemsize = PyArray_ITEMSIZE(self)
* info.readonly = not PyArray_ISWRITEABLE(self) # <<<<<<<<<<<<<<
*
* cdef int t
*/
__pyx_v_info->readonly = (!(PyArray_ISWRITEABLE(__pyx_v_self) != 0));
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":239
*
* cdef int t
* cdef char* f = NULL # <<<<<<<<<<<<<<
* cdef dtype descr = self.descr
* cdef list stack
*/
__pyx_v_f = NULL;
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":240
* cdef int t
* cdef char* f = NULL
* cdef dtype descr = self.descr # <<<<<<<<<<<<<<
* cdef list stack
* cdef int offset
*/
__pyx_t_4 = ((PyObject *)__pyx_v_self->descr);
__Pyx_INCREF(__pyx_t_4);
__pyx_v_descr = ((PyArray_Descr *)__pyx_t_4);
__pyx_t_4 = 0;
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":244
* cdef int offset
*
* cdef bint hasfields = PyDataType_HASFIELDS(descr) # <<<<<<<<<<<<<<
*
* if not hasfields and not copy_shape:
*/
__pyx_v_hasfields = PyDataType_HASFIELDS(__pyx_v_descr);
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":246
* cdef bint hasfields = PyDataType_HASFIELDS(descr)
*
* if not hasfields and not copy_shape: # <<<<<<<<<<<<<<
* # do not call releasebuffer
* info.obj = None
*/
__pyx_t_2 = ((!(__pyx_v_hasfields != 0)) != 0);
if (__pyx_t_2) {
__pyx_t_3 = ((!(__pyx_v_copy_shape != 0)) != 0);
__pyx_t_1 = __pyx_t_3;
} else {
__pyx_t_1 = __pyx_t_2;
}
if (__pyx_t_1) {
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":248
* if not hasfields and not copy_shape:
* # do not call releasebuffer
* info.obj = None # <<<<<<<<<<<<<<
* else:
* # need to call releasebuffer
*/
__Pyx_INCREF(Py_None);
__Pyx_GIVEREF(Py_None);
__Pyx_GOTREF(__pyx_v_info->obj);
__Pyx_DECREF(__pyx_v_info->obj);
__pyx_v_info->obj = Py_None;
goto __pyx_L10;
}
/*else*/ {
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":251
* else:
* # need to call releasebuffer
* info.obj = self # <<<<<<<<<<<<<<
*
* if not hasfields:
*/
__Pyx_INCREF(((PyObject *)__pyx_v_self));
__Pyx_GIVEREF(((PyObject *)__pyx_v_self));
__Pyx_GOTREF(__pyx_v_info->obj);
__Pyx_DECREF(__pyx_v_info->obj);
__pyx_v_info->obj = ((PyObject *)__pyx_v_self);
}
__pyx_L10:;
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":253
* info.obj = self
*
* if not hasfields: # <<<<<<<<<<<<<<
* t = descr.type_num
* if ((descr.byteorder == c'>' and little_endian) or
*/
__pyx_t_1 = ((!(__pyx_v_hasfields != 0)) != 0);
if (__pyx_t_1) {
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":254
*
* if not hasfields:
* t = descr.type_num # <<<<<<<<<<<<<<
* if ((descr.byteorder == c'>' and little_endian) or
* (descr.byteorder == c'<' and not little_endian)):
*/
__pyx_t_5 = __pyx_v_descr->type_num;
__pyx_v_t = __pyx_t_5;
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":255
* if not hasfields:
* t = descr.type_num
* if ((descr.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<<
* (descr.byteorder == c'<' and not little_endian)):
* raise ValueError(u"Non-native byte order not supported")
*/
__pyx_t_1 = ((__pyx_v_descr->byteorder == '>') != 0);
if (__pyx_t_1) {
__pyx_t_2 = (__pyx_v_little_endian != 0);
} else {
__pyx_t_2 = __pyx_t_1;
}
if (!__pyx_t_2) {
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":256
* t = descr.type_num
* if ((descr.byteorder == c'>' and little_endian) or
* (descr.byteorder == c'<' and not little_endian)): # <<<<<<<<<<<<<<
* raise ValueError(u"Non-native byte order not supported")
* if t == NPY_BYTE: f = "b"
*/
__pyx_t_1 = ((__pyx_v_descr->byteorder == '<') != 0);
if (__pyx_t_1) {
__pyx_t_3 = ((!(__pyx_v_little_endian != 0)) != 0);
__pyx_t_7 = __pyx_t_3;
} else {
__pyx_t_7 = __pyx_t_1;
}
__pyx_t_1 = __pyx_t_7;
} else {
__pyx_t_1 = __pyx_t_2;
}
if (__pyx_t_1) {
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":257
* if ((descr.byteorder == c'>' and little_endian) or
* (descr.byteorder == c'<' and not little_endian)):
* raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<<
* if t == NPY_BYTE: f = "b"
* elif t == NPY_UBYTE: f = "B"
*/
__pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__15, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_4);
__Pyx_Raise(__pyx_t_4, 0, 0, 0);
__Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
{__pyx_filename = __pyx_f[1]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
}
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":274
* elif t == NPY_CDOUBLE: f = "Zd"
* elif t == NPY_CLONGDOUBLE: f = "Zg"
* elif t == NPY_OBJECT: f = "O" # <<<<<<<<<<<<<<
* else:
* raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t)
*/
switch (__pyx_v_t) {
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":258
* (descr.byteorder == c'<' and not little_endian)):
* raise ValueError(u"Non-native byte order not supported")
* if t == NPY_BYTE: f = "b" # <<<<<<<<<<<<<<
* elif t == NPY_UBYTE: f = "B"
* elif t == NPY_SHORT: f = "h"
*/
case NPY_BYTE:
__pyx_v_f = __pyx_k_b;
break;
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":259
* raise ValueError(u"Non-native byte order not supported")
* if t == NPY_BYTE: f = "b"
* elif t == NPY_UBYTE: f = "B" # <<<<<<<<<<<<<<
* elif t == NPY_SHORT: f = "h"
* elif t == NPY_USHORT: f = "H"
*/
case NPY_UBYTE:
__pyx_v_f = __pyx_k_B;
break;
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":260
* if t == NPY_BYTE: f = "b"
* elif t == NPY_UBYTE: f = "B"
* elif t == NPY_SHORT: f = "h" # <<<<<<<<<<<<<<
* elif t == NPY_USHORT: f = "H"
* elif t == NPY_INT: f = "i"
*/
case NPY_SHORT:
__pyx_v_f = __pyx_k_h;
break;
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":261
* elif t == NPY_UBYTE: f = "B"
* elif t == NPY_SHORT: f = "h"
* elif t == NPY_USHORT: f = "H" # <<<<<<<<<<<<<<
* elif t == NPY_INT: f = "i"
* elif t == NPY_UINT: f = "I"
*/
case NPY_USHORT:
__pyx_v_f = __pyx_k_H;
break;
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":262
* elif t == NPY_SHORT: f = "h"
* elif t == NPY_USHORT: f = "H"
* elif t == NPY_INT: f = "i" # <<<<<<<<<<<<<<
* elif t == NPY_UINT: f = "I"
* elif t == NPY_LONG: f = "l"
*/
case NPY_INT:
__pyx_v_f = __pyx_k_i;
break;
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":263
* elif t == NPY_USHORT: f = "H"
* elif t == NPY_INT: f = "i"
* elif t == NPY_UINT: f = "I" # <<<<<<<<<<<<<<
* elif t == NPY_LONG: f = "l"
* elif t == NPY_ULONG: f = "L"
*/
case NPY_UINT:
__pyx_v_f = __pyx_k_I;
break;
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":264
* elif t == NPY_INT: f = "i"
* elif t == NPY_UINT: f = "I"
* elif t == NPY_LONG: f = "l" # <<<<<<<<<<<<<<
* elif t == NPY_ULONG: f = "L"
* elif t == NPY_LONGLONG: f = "q"
*/
case NPY_LONG:
__pyx_v_f = __pyx_k_l;
break;
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":265
* elif t == NPY_UINT: f = "I"
* elif t == NPY_LONG: f = "l"
* elif t == NPY_ULONG: f = "L" # <<<<<<<<<<<<<<
* elif t == NPY_LONGLONG: f = "q"
* elif t == NPY_ULONGLONG: f = "Q"
*/
case NPY_ULONG:
__pyx_v_f = __pyx_k_L;
break;
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":266
* elif t == NPY_LONG: f = "l"
* elif t == NPY_ULONG: f = "L"
* elif t == NPY_LONGLONG: f = "q" # <<<<<<<<<<<<<<
* elif t == NPY_ULONGLONG: f = "Q"
* elif t == NPY_FLOAT: f = "f"
*/
case NPY_LONGLONG:
__pyx_v_f = __pyx_k_q;
break;
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":267
* elif t == NPY_ULONG: f = "L"
* elif t == NPY_LONGLONG: f = "q"
* elif t == NPY_ULONGLONG: f = "Q" # <<<<<<<<<<<<<<
* elif t == NPY_FLOAT: f = "f"
* elif t == NPY_DOUBLE: f = "d"
*/
case NPY_ULONGLONG:
__pyx_v_f = __pyx_k_Q;
break;
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":268
* elif t == NPY_LONGLONG: f = "q"
* elif t == NPY_ULONGLONG: f = "Q"
* elif t == NPY_FLOAT: f = "f" # <<<<<<<<<<<<<<
* elif t == NPY_DOUBLE: f = "d"
* elif t == NPY_LONGDOUBLE: f = "g"
*/
case NPY_FLOAT:
__pyx_v_f = __pyx_k_f;
break;
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":269
* elif t == NPY_ULONGLONG: f = "Q"
* elif t == NPY_FLOAT: f = "f"
* elif t == NPY_DOUBLE: f = "d" # <<<<<<<<<<<<<<
* elif t == NPY_LONGDOUBLE: f = "g"
* elif t == NPY_CFLOAT: f = "Zf"
*/
case NPY_DOUBLE:
__pyx_v_f = __pyx_k_d;
break;
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":270
* elif t == NPY_FLOAT: f = "f"
* elif t == NPY_DOUBLE: f = "d"
* elif t == NPY_LONGDOUBLE: f = "g" # <<<<<<<<<<<<<<
* elif t == NPY_CFLOAT: f = "Zf"
* elif t == NPY_CDOUBLE: f = "Zd"
*/
case NPY_LONGDOUBLE:
__pyx_v_f = __pyx_k_g;
break;
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":271
* elif t == NPY_DOUBLE: f = "d"
* elif t == NPY_LONGDOUBLE: f = "g"
* elif t == NPY_CFLOAT: f = "Zf" # <<<<<<<<<<<<<<
* elif t == NPY_CDOUBLE: f = "Zd"
* elif t == NPY_CLONGDOUBLE: f = "Zg"
*/
case NPY_CFLOAT:
__pyx_v_f = __pyx_k_Zf;
break;
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":272
* elif t == NPY_LONGDOUBLE: f = "g"
* elif t == NPY_CFLOAT: f = "Zf"
* elif t == NPY_CDOUBLE: f = "Zd" # <<<<<<<<<<<<<<
* elif t == NPY_CLONGDOUBLE: f = "Zg"
* elif t == NPY_OBJECT: f = "O"
*/
case NPY_CDOUBLE:
__pyx_v_f = __pyx_k_Zd;
break;
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":273
* elif t == NPY_CFLOAT: f = "Zf"
* elif t == NPY_CDOUBLE: f = "Zd"
* elif t == NPY_CLONGDOUBLE: f = "Zg" # <<<<<<<<<<<<<<
* elif t == NPY_OBJECT: f = "O"
* else:
*/
case NPY_CLONGDOUBLE:
__pyx_v_f = __pyx_k_Zg;
break;
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":274
* elif t == NPY_CDOUBLE: f = "Zd"
* elif t == NPY_CLONGDOUBLE: f = "Zg"
* elif t == NPY_OBJECT: f = "O" # <<<<<<<<<<<<<<
* else:
* raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t)
*/
case NPY_OBJECT:
__pyx_v_f = __pyx_k_O;
break;
default:
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":276
* elif t == NPY_OBJECT: f = "O"
* else:
* raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<<
* info.format = f
* return
*/
__pyx_t_4 = __Pyx_PyInt_From_int(__pyx_v_t); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_4);
__pyx_t_8 = PyUnicode_Format(__pyx_kp_u_unknown_dtype_code_in_numpy_pxd, __pyx_t_4); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_8);
__Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
__pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_4);
PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_8);
__Pyx_GIVEREF(__pyx_t_8);
__pyx_t_8 = 0;
__pyx_t_8 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_4, NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_8);
__Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
__Pyx_Raise(__pyx_t_8, 0, 0, 0);
__Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0;
{__pyx_filename = __pyx_f[1]; __pyx_lineno = 276; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
break;
}
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":277
* else:
* raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t)
* info.format = f # <<<<<<<<<<<<<<
* return
* else:
*/
__pyx_v_info->format = __pyx_v_f;
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":278
* raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t)
* info.format = f
* return # <<<<<<<<<<<<<<
* else:
* info.format = <char*>stdlib.malloc(_buffer_format_string_len)
*/
__pyx_r = 0;
goto __pyx_L0;
}
/*else*/ {
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":280
* return
* else:
* info.format = <char*>stdlib.malloc(_buffer_format_string_len) # <<<<<<<<<<<<<<
* info.format[0] = c'^' # Native data types, manual alignment
* offset = 0
*/
__pyx_v_info->format = ((char *)malloc(255));
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":281
* else:
* info.format = <char*>stdlib.malloc(_buffer_format_string_len)
* info.format[0] = c'^' # Native data types, manual alignment # <<<<<<<<<<<<<<
* offset = 0
* f = _util_dtypestring(descr, info.format + 1,
*/
(__pyx_v_info->format[0]) = '^';
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":282
* info.format = <char*>stdlib.malloc(_buffer_format_string_len)
* info.format[0] = c'^' # Native data types, manual alignment
* offset = 0 # <<<<<<<<<<<<<<
* f = _util_dtypestring(descr, info.format + 1,
* info.format + _buffer_format_string_len,
*/
__pyx_v_offset = 0;
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":283
* info.format[0] = c'^' # Native data types, manual alignment
* offset = 0
* f = _util_dtypestring(descr, info.format + 1, # <<<<<<<<<<<<<<
* info.format + _buffer_format_string_len,
* &offset)
*/
__pyx_t_9 = __pyx_f_5numpy__util_dtypestring(__pyx_v_descr, (__pyx_v_info->format + 1), (__pyx_v_info->format + 255), (&__pyx_v_offset)); if (unlikely(__pyx_t_9 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 283; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_v_f = __pyx_t_9;
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":286
* info.format + _buffer_format_string_len,
* &offset)
* f[0] = c'\0' # Terminate format string # <<<<<<<<<<<<<<
*
* def __releasebuffer__(ndarray self, Py_buffer* info):
*/
(__pyx_v_f[0]) = '\x00';
}
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":194
* # experimental exception made for __getbuffer__ and __releasebuffer__
* # -- the details of this may change.
* def __getbuffer__(ndarray self, Py_buffer* info, int flags): # <<<<<<<<<<<<<<
* # This implementation of getbuffer is geared towards Cython
* # requirements, and does not yet fullfill the PEP.
*/
/* function exit code */
__pyx_r = 0;
goto __pyx_L0;
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_4);
__Pyx_XDECREF(__pyx_t_8);
__Pyx_AddTraceback("numpy.ndarray.__getbuffer__", __pyx_clineno, __pyx_lineno, __pyx_filename);
__pyx_r = -1;
if (__pyx_v_info != NULL && __pyx_v_info->obj != NULL) {
__Pyx_GOTREF(__pyx_v_info->obj);
__Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = NULL;
}
goto __pyx_L2;
__pyx_L0:;
if (__pyx_v_info != NULL && __pyx_v_info->obj == Py_None) {
__Pyx_GOTREF(Py_None);
__Pyx_DECREF(Py_None); __pyx_v_info->obj = NULL;
}
__pyx_L2:;
__Pyx_XDECREF((PyObject *)__pyx_v_descr);
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":288
* f[0] = c'\0' # Terminate format string
*
* def __releasebuffer__(ndarray self, Py_buffer* info): # <<<<<<<<<<<<<<
* if PyArray_HASFIELDS(self):
* stdlib.free(info.format)
*/
/* Python wrapper */
static CYTHON_UNUSED void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info); /*proto*/
static CYTHON_UNUSED void __pyx_pw_5numpy_7ndarray_3__releasebuffer__(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info) {
__Pyx_RefNannyDeclarations
__Pyx_RefNannySetupContext("__releasebuffer__ (wrapper)", 0);
__pyx_pf_5numpy_7ndarray_2__releasebuffer__(((PyArrayObject *)__pyx_v_self), ((Py_buffer *)__pyx_v_info));
/* function exit code */
__Pyx_RefNannyFinishContext();
}
static void __pyx_pf_5numpy_7ndarray_2__releasebuffer__(PyArrayObject *__pyx_v_self, Py_buffer *__pyx_v_info) {
__Pyx_RefNannyDeclarations
int __pyx_t_1;
__Pyx_RefNannySetupContext("__releasebuffer__", 0);
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":289
*
* def __releasebuffer__(ndarray self, Py_buffer* info):
* if PyArray_HASFIELDS(self): # <<<<<<<<<<<<<<
* stdlib.free(info.format)
* if sizeof(npy_intp) != sizeof(Py_ssize_t):
*/
__pyx_t_1 = (PyArray_HASFIELDS(__pyx_v_self) != 0);
if (__pyx_t_1) {
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":290
* def __releasebuffer__(ndarray self, Py_buffer* info):
* if PyArray_HASFIELDS(self):
* stdlib.free(info.format) # <<<<<<<<<<<<<<
* if sizeof(npy_intp) != sizeof(Py_ssize_t):
* stdlib.free(info.strides)
*/
free(__pyx_v_info->format);
goto __pyx_L3;
}
__pyx_L3:;
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":291
* if PyArray_HASFIELDS(self):
* stdlib.free(info.format)
* if sizeof(npy_intp) != sizeof(Py_ssize_t): # <<<<<<<<<<<<<<
* stdlib.free(info.strides)
* # info.shape was stored after info.strides in the same block
*/
__pyx_t_1 = (((sizeof(npy_intp)) != (sizeof(Py_ssize_t))) != 0);
if (__pyx_t_1) {
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":292
* stdlib.free(info.format)
* if sizeof(npy_intp) != sizeof(Py_ssize_t):
* stdlib.free(info.strides) # <<<<<<<<<<<<<<
* # info.shape was stored after info.strides in the same block
*
*/
free(__pyx_v_info->strides);
goto __pyx_L4;
}
__pyx_L4:;
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":288
* f[0] = c'\0' # Terminate format string
*
* def __releasebuffer__(ndarray self, Py_buffer* info): # <<<<<<<<<<<<<<
* if PyArray_HASFIELDS(self):
* stdlib.free(info.format)
*/
/* function exit code */
__Pyx_RefNannyFinishContext();
}
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":768
* ctypedef npy_cdouble complex_t
*
* cdef inline object PyArray_MultiIterNew1(a): # <<<<<<<<<<<<<<
* return PyArray_MultiIterNew(1, <void*>a)
*
*/
static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew1(PyObject *__pyx_v_a) {
PyObject *__pyx_r = NULL;
__Pyx_RefNannyDeclarations
PyObject *__pyx_t_1 = NULL;
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
__Pyx_RefNannySetupContext("PyArray_MultiIterNew1", 0);
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":769
*
* cdef inline object PyArray_MultiIterNew1(a):
* return PyArray_MultiIterNew(1, <void*>a) # <<<<<<<<<<<<<<
*
* cdef inline object PyArray_MultiIterNew2(a, b):
*/
__Pyx_XDECREF(__pyx_r);
__pyx_t_1 = PyArray_MultiIterNew(1, ((void *)__pyx_v_a)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 769; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
__pyx_r = __pyx_t_1;
__pyx_t_1 = 0;
goto __pyx_L0;
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":768
* ctypedef npy_cdouble complex_t
*
* cdef inline object PyArray_MultiIterNew1(a): # <<<<<<<<<<<<<<
* return PyArray_MultiIterNew(1, <void*>a)
*
*/
/* function exit code */
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_1);
__Pyx_AddTraceback("numpy.PyArray_MultiIterNew1", __pyx_clineno, __pyx_lineno, __pyx_filename);
__pyx_r = 0;
__pyx_L0:;
__Pyx_XGIVEREF(__pyx_r);
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":771
* return PyArray_MultiIterNew(1, <void*>a)
*
* cdef inline object PyArray_MultiIterNew2(a, b): # <<<<<<<<<<<<<<
* return PyArray_MultiIterNew(2, <void*>a, <void*>b)
*
*/
static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew2(PyObject *__pyx_v_a, PyObject *__pyx_v_b) {
PyObject *__pyx_r = NULL;
__Pyx_RefNannyDeclarations
PyObject *__pyx_t_1 = NULL;
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
__Pyx_RefNannySetupContext("PyArray_MultiIterNew2", 0);
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":772
*
* cdef inline object PyArray_MultiIterNew2(a, b):
* return PyArray_MultiIterNew(2, <void*>a, <void*>b) # <<<<<<<<<<<<<<
*
* cdef inline object PyArray_MultiIterNew3(a, b, c):
*/
__Pyx_XDECREF(__pyx_r);
__pyx_t_1 = PyArray_MultiIterNew(2, ((void *)__pyx_v_a), ((void *)__pyx_v_b)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 772; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
__pyx_r = __pyx_t_1;
__pyx_t_1 = 0;
goto __pyx_L0;
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":771
* return PyArray_MultiIterNew(1, <void*>a)
*
* cdef inline object PyArray_MultiIterNew2(a, b): # <<<<<<<<<<<<<<
* return PyArray_MultiIterNew(2, <void*>a, <void*>b)
*
*/
/* function exit code */
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_1);
__Pyx_AddTraceback("numpy.PyArray_MultiIterNew2", __pyx_clineno, __pyx_lineno, __pyx_filename);
__pyx_r = 0;
__pyx_L0:;
__Pyx_XGIVEREF(__pyx_r);
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":774
* return PyArray_MultiIterNew(2, <void*>a, <void*>b)
*
* cdef inline object PyArray_MultiIterNew3(a, b, c): # <<<<<<<<<<<<<<
* return PyArray_MultiIterNew(3, <void*>a, <void*>b, <void*> c)
*
*/
static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew3(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c) {
PyObject *__pyx_r = NULL;
__Pyx_RefNannyDeclarations
PyObject *__pyx_t_1 = NULL;
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
__Pyx_RefNannySetupContext("PyArray_MultiIterNew3", 0);
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":775
*
* cdef inline object PyArray_MultiIterNew3(a, b, c):
* return PyArray_MultiIterNew(3, <void*>a, <void*>b, <void*> c) # <<<<<<<<<<<<<<
*
* cdef inline object PyArray_MultiIterNew4(a, b, c, d):
*/
__Pyx_XDECREF(__pyx_r);
__pyx_t_1 = PyArray_MultiIterNew(3, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 775; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
__pyx_r = __pyx_t_1;
__pyx_t_1 = 0;
goto __pyx_L0;
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":774
* return PyArray_MultiIterNew(2, <void*>a, <void*>b)
*
* cdef inline object PyArray_MultiIterNew3(a, b, c): # <<<<<<<<<<<<<<
* return PyArray_MultiIterNew(3, <void*>a, <void*>b, <void*> c)
*
*/
/* function exit code */
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_1);
__Pyx_AddTraceback("numpy.PyArray_MultiIterNew3", __pyx_clineno, __pyx_lineno, __pyx_filename);
__pyx_r = 0;
__pyx_L0:;
__Pyx_XGIVEREF(__pyx_r);
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":777
* return PyArray_MultiIterNew(3, <void*>a, <void*>b, <void*> c)
*
* cdef inline object PyArray_MultiIterNew4(a, b, c, d): # <<<<<<<<<<<<<<
* return PyArray_MultiIterNew(4, <void*>a, <void*>b, <void*>c, <void*> d)
*
*/
static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew4(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c, PyObject *__pyx_v_d) {
PyObject *__pyx_r = NULL;
__Pyx_RefNannyDeclarations
PyObject *__pyx_t_1 = NULL;
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
__Pyx_RefNannySetupContext("PyArray_MultiIterNew4", 0);
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":778
*
* cdef inline object PyArray_MultiIterNew4(a, b, c, d):
* return PyArray_MultiIterNew(4, <void*>a, <void*>b, <void*>c, <void*> d) # <<<<<<<<<<<<<<
*
* cdef inline object PyArray_MultiIterNew5(a, b, c, d, e):
*/
__Pyx_XDECREF(__pyx_r);
__pyx_t_1 = PyArray_MultiIterNew(4, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 778; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
__pyx_r = __pyx_t_1;
__pyx_t_1 = 0;
goto __pyx_L0;
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":777
* return PyArray_MultiIterNew(3, <void*>a, <void*>b, <void*> c)
*
* cdef inline object PyArray_MultiIterNew4(a, b, c, d): # <<<<<<<<<<<<<<
* return PyArray_MultiIterNew(4, <void*>a, <void*>b, <void*>c, <void*> d)
*
*/
/* function exit code */
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_1);
__Pyx_AddTraceback("numpy.PyArray_MultiIterNew4", __pyx_clineno, __pyx_lineno, __pyx_filename);
__pyx_r = 0;
__pyx_L0:;
__Pyx_XGIVEREF(__pyx_r);
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":780
* return PyArray_MultiIterNew(4, <void*>a, <void*>b, <void*>c, <void*> d)
*
* cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): # <<<<<<<<<<<<<<
* return PyArray_MultiIterNew(5, <void*>a, <void*>b, <void*>c, <void*> d, <void*> e)
*
*/
static CYTHON_INLINE PyObject *__pyx_f_5numpy_PyArray_MultiIterNew5(PyObject *__pyx_v_a, PyObject *__pyx_v_b, PyObject *__pyx_v_c, PyObject *__pyx_v_d, PyObject *__pyx_v_e) {
PyObject *__pyx_r = NULL;
__Pyx_RefNannyDeclarations
PyObject *__pyx_t_1 = NULL;
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
__Pyx_RefNannySetupContext("PyArray_MultiIterNew5", 0);
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":781
*
* cdef inline object PyArray_MultiIterNew5(a, b, c, d, e):
* return PyArray_MultiIterNew(5, <void*>a, <void*>b, <void*>c, <void*> d, <void*> e) # <<<<<<<<<<<<<<
*
* cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL:
*/
__Pyx_XDECREF(__pyx_r);
__pyx_t_1 = PyArray_MultiIterNew(5, ((void *)__pyx_v_a), ((void *)__pyx_v_b), ((void *)__pyx_v_c), ((void *)__pyx_v_d), ((void *)__pyx_v_e)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 781; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
__pyx_r = __pyx_t_1;
__pyx_t_1 = 0;
goto __pyx_L0;
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":780
* return PyArray_MultiIterNew(4, <void*>a, <void*>b, <void*>c, <void*> d)
*
* cdef inline object PyArray_MultiIterNew5(a, b, c, d, e): # <<<<<<<<<<<<<<
* return PyArray_MultiIterNew(5, <void*>a, <void*>b, <void*>c, <void*> d, <void*> e)
*
*/
/* function exit code */
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_1);
__Pyx_AddTraceback("numpy.PyArray_MultiIterNew5", __pyx_clineno, __pyx_lineno, __pyx_filename);
__pyx_r = 0;
__pyx_L0:;
__Pyx_XGIVEREF(__pyx_r);
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":783
* return PyArray_MultiIterNew(5, <void*>a, <void*>b, <void*>c, <void*> d, <void*> e)
*
* cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: # <<<<<<<<<<<<<<
* # Recursive utility function used in __getbuffer__ to get format
* # string. The new location in the format string is returned.
*/
static CYTHON_INLINE char *__pyx_f_5numpy__util_dtypestring(PyArray_Descr *__pyx_v_descr, char *__pyx_v_f, char *__pyx_v_end, int *__pyx_v_offset) {
PyArray_Descr *__pyx_v_child = 0;
int __pyx_v_endian_detector;
int __pyx_v_little_endian;
PyObject *__pyx_v_fields = 0;
PyObject *__pyx_v_childname = NULL;
PyObject *__pyx_v_new_offset = NULL;
PyObject *__pyx_v_t = NULL;
char *__pyx_r;
__Pyx_RefNannyDeclarations
PyObject *__pyx_t_1 = NULL;
Py_ssize_t __pyx_t_2;
PyObject *__pyx_t_3 = NULL;
PyObject *__pyx_t_4 = NULL;
int __pyx_t_5;
int __pyx_t_6;
int __pyx_t_7;
int __pyx_t_8;
int __pyx_t_9;
long __pyx_t_10;
char *__pyx_t_11;
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
__Pyx_RefNannySetupContext("_util_dtypestring", 0);
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":790
* cdef int delta_offset
* cdef tuple i
* cdef int endian_detector = 1 # <<<<<<<<<<<<<<
* cdef bint little_endian = ((<char*>&endian_detector)[0] != 0)
* cdef tuple fields
*/
__pyx_v_endian_detector = 1;
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":791
* cdef tuple i
* cdef int endian_detector = 1
* cdef bint little_endian = ((<char*>&endian_detector)[0] != 0) # <<<<<<<<<<<<<<
* cdef tuple fields
*
*/
__pyx_v_little_endian = ((((char *)(&__pyx_v_endian_detector))[0]) != 0);
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":794
* cdef tuple fields
*
* for childname in descr.names: # <<<<<<<<<<<<<<
* fields = descr.fields[childname]
* child, new_offset = fields
*/
if (unlikely(__pyx_v_descr->names == Py_None)) {
PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable");
{__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
}
__pyx_t_1 = __pyx_v_descr->names; __Pyx_INCREF(__pyx_t_1); __pyx_t_2 = 0;
for (;;) {
if (__pyx_t_2 >= PyTuple_GET_SIZE(__pyx_t_1)) break;
#if CYTHON_COMPILING_IN_CPYTHON
__pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_1, __pyx_t_2); __Pyx_INCREF(__pyx_t_3); __pyx_t_2++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
#else
__pyx_t_3 = PySequence_ITEM(__pyx_t_1, __pyx_t_2); __pyx_t_2++; if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 794; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
#endif
__Pyx_XDECREF_SET(__pyx_v_childname, __pyx_t_3);
__pyx_t_3 = 0;
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":795
*
* for childname in descr.names:
* fields = descr.fields[childname] # <<<<<<<<<<<<<<
* child, new_offset = fields
*
*/
__pyx_t_3 = PyObject_GetItem(__pyx_v_descr->fields, __pyx_v_childname); if (unlikely(__pyx_t_3 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;};
__Pyx_GOTREF(__pyx_t_3);
if (!(likely(PyTuple_CheckExact(__pyx_t_3))||((__pyx_t_3) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "tuple", Py_TYPE(__pyx_t_3)->tp_name), 0))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 795; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_XDECREF_SET(__pyx_v_fields, ((PyObject*)__pyx_t_3));
__pyx_t_3 = 0;
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":796
* for childname in descr.names:
* fields = descr.fields[childname]
* child, new_offset = fields # <<<<<<<<<<<<<<
*
* if (end - f) - <int>(new_offset - offset[0]) < 15:
*/
if (likely(__pyx_v_fields != Py_None)) {
PyObject* sequence = __pyx_v_fields;
#if CYTHON_COMPILING_IN_CPYTHON
Py_ssize_t size = Py_SIZE(sequence);
#else
Py_ssize_t size = PySequence_Size(sequence);
#endif
if (unlikely(size != 2)) {
if (size > 2) __Pyx_RaiseTooManyValuesError(2);
else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size);
{__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
}
#if CYTHON_COMPILING_IN_CPYTHON
__pyx_t_3 = PyTuple_GET_ITEM(sequence, 0);
__pyx_t_4 = PyTuple_GET_ITEM(sequence, 1);
__Pyx_INCREF(__pyx_t_3);
__Pyx_INCREF(__pyx_t_4);
#else
__pyx_t_3 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_3);
__pyx_t_4 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_4);
#endif
} else {
__Pyx_RaiseNoneNotIterableError(); {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
}
if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_ptype_5numpy_dtype))))) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 796; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_XDECREF_SET(__pyx_v_child, ((PyArray_Descr *)__pyx_t_3));
__pyx_t_3 = 0;
__Pyx_XDECREF_SET(__pyx_v_new_offset, __pyx_t_4);
__pyx_t_4 = 0;
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":798
* child, new_offset = fields
*
* if (end - f) - <int>(new_offset - offset[0]) < 15: # <<<<<<<<<<<<<<
* raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd")
*
*/
__pyx_t_4 = __Pyx_PyInt_From_int((__pyx_v_offset[0])); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_4);
__pyx_t_3 = PyNumber_Subtract(__pyx_v_new_offset, __pyx_t_4); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_3);
__Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
__pyx_t_5 = __Pyx_PyInt_As_int(__pyx_t_3); if (unlikely((__pyx_t_5 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 798; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
__pyx_t_6 = ((((__pyx_v_end - __pyx_v_f) - ((int)__pyx_t_5)) < 15) != 0);
if (__pyx_t_6) {
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":799
*
* if (end - f) - <int>(new_offset - offset[0]) < 15:
* raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<<
*
* if ((child.byteorder == c'>' and little_endian) or
*/
__pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_RuntimeError, __pyx_tuple__16, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_3);
__Pyx_Raise(__pyx_t_3, 0, 0, 0);
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
{__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
}
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":801
* raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd")
*
* if ((child.byteorder == c'>' and little_endian) or # <<<<<<<<<<<<<<
* (child.byteorder == c'<' and not little_endian)):
* raise ValueError(u"Non-native byte order not supported")
*/
__pyx_t_6 = ((__pyx_v_child->byteorder == '>') != 0);
if (__pyx_t_6) {
__pyx_t_7 = (__pyx_v_little_endian != 0);
} else {
__pyx_t_7 = __pyx_t_6;
}
if (!__pyx_t_7) {
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":802
*
* if ((child.byteorder == c'>' and little_endian) or
* (child.byteorder == c'<' and not little_endian)): # <<<<<<<<<<<<<<
* raise ValueError(u"Non-native byte order not supported")
* # One could encode it in the format string and have Cython
*/
__pyx_t_6 = ((__pyx_v_child->byteorder == '<') != 0);
if (__pyx_t_6) {
__pyx_t_8 = ((!(__pyx_v_little_endian != 0)) != 0);
__pyx_t_9 = __pyx_t_8;
} else {
__pyx_t_9 = __pyx_t_6;
}
__pyx_t_6 = __pyx_t_9;
} else {
__pyx_t_6 = __pyx_t_7;
}
if (__pyx_t_6) {
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":803
* if ((child.byteorder == c'>' and little_endian) or
* (child.byteorder == c'<' and not little_endian)):
* raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<<
* # One could encode it in the format string and have Cython
* # complain instead, BUT: < and > in format strings also imply
*/
__pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__17, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_3);
__Pyx_Raise(__pyx_t_3, 0, 0, 0);
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
{__pyx_filename = __pyx_f[1]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
}
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":813
*
* # Output padding bytes
* while offset[0] < new_offset: # <<<<<<<<<<<<<<
* f[0] = 120 # "x"; pad byte
* f += 1
*/
while (1) {
__pyx_t_3 = __Pyx_PyInt_From_int((__pyx_v_offset[0])); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_3);
__pyx_t_4 = PyObject_RichCompare(__pyx_t_3, __pyx_v_new_offset, Py_LT); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
__pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 813; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
if (!__pyx_t_6) break;
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":814
* # Output padding bytes
* while offset[0] < new_offset:
* f[0] = 120 # "x"; pad byte # <<<<<<<<<<<<<<
* f += 1
* offset[0] += 1
*/
(__pyx_v_f[0]) = 120;
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":815
* while offset[0] < new_offset:
* f[0] = 120 # "x"; pad byte
* f += 1 # <<<<<<<<<<<<<<
* offset[0] += 1
*
*/
__pyx_v_f = (__pyx_v_f + 1);
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":816
* f[0] = 120 # "x"; pad byte
* f += 1
* offset[0] += 1 # <<<<<<<<<<<<<<
*
* offset[0] += child.itemsize
*/
__pyx_t_10 = 0;
(__pyx_v_offset[__pyx_t_10]) = ((__pyx_v_offset[__pyx_t_10]) + 1);
}
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":818
* offset[0] += 1
*
* offset[0] += child.itemsize # <<<<<<<<<<<<<<
*
* if not PyDataType_HASFIELDS(child):
*/
__pyx_t_10 = 0;
(__pyx_v_offset[__pyx_t_10]) = ((__pyx_v_offset[__pyx_t_10]) + __pyx_v_child->elsize);
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":820
* offset[0] += child.itemsize
*
* if not PyDataType_HASFIELDS(child): # <<<<<<<<<<<<<<
* t = child.type_num
* if end - f < 5:
*/
__pyx_t_6 = ((!(PyDataType_HASFIELDS(__pyx_v_child) != 0)) != 0);
if (__pyx_t_6) {
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":821
*
* if not PyDataType_HASFIELDS(child):
* t = child.type_num # <<<<<<<<<<<<<<
* if end - f < 5:
* raise RuntimeError(u"Format string allocated too short.")
*/
__pyx_t_4 = __Pyx_PyInt_From_int(__pyx_v_child->type_num); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 821; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_4);
__Pyx_XDECREF_SET(__pyx_v_t, __pyx_t_4);
__pyx_t_4 = 0;
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":822
* if not PyDataType_HASFIELDS(child):
* t = child.type_num
* if end - f < 5: # <<<<<<<<<<<<<<
* raise RuntimeError(u"Format string allocated too short.")
*
*/
__pyx_t_6 = (((__pyx_v_end - __pyx_v_f) < 5) != 0);
if (__pyx_t_6) {
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":823
* t = child.type_num
* if end - f < 5:
* raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<<
*
* # Until ticket #99 is fixed, use integers to avoid warnings
*/
__pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_RuntimeError, __pyx_tuple__18, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_4);
__Pyx_Raise(__pyx_t_4, 0, 0, 0);
__Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
{__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
}
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":826
*
* # Until ticket #99 is fixed, use integers to avoid warnings
* if t == NPY_BYTE: f[0] = 98 #"b" # <<<<<<<<<<<<<<
* elif t == NPY_UBYTE: f[0] = 66 #"B"
* elif t == NPY_SHORT: f[0] = 104 #"h"
*/
__pyx_t_4 = PyInt_FromLong(NPY_BYTE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_4);
__pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
__pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 826; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
if (__pyx_t_6) {
(__pyx_v_f[0]) = 98;
goto __pyx_L11;
}
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":827
* # Until ticket #99 is fixed, use integers to avoid warnings
* if t == NPY_BYTE: f[0] = 98 #"b"
* elif t == NPY_UBYTE: f[0] = 66 #"B" # <<<<<<<<<<<<<<
* elif t == NPY_SHORT: f[0] = 104 #"h"
* elif t == NPY_USHORT: f[0] = 72 #"H"
*/
__pyx_t_3 = PyInt_FromLong(NPY_UBYTE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_3);
__pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
__pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 827; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
if (__pyx_t_6) {
(__pyx_v_f[0]) = 66;
goto __pyx_L11;
}
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":828
* if t == NPY_BYTE: f[0] = 98 #"b"
* elif t == NPY_UBYTE: f[0] = 66 #"B"
* elif t == NPY_SHORT: f[0] = 104 #"h" # <<<<<<<<<<<<<<
* elif t == NPY_USHORT: f[0] = 72 #"H"
* elif t == NPY_INT: f[0] = 105 #"i"
*/
__pyx_t_4 = PyInt_FromLong(NPY_SHORT); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_4);
__pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
__pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 828; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
if (__pyx_t_6) {
(__pyx_v_f[0]) = 104;
goto __pyx_L11;
}
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":829
* elif t == NPY_UBYTE: f[0] = 66 #"B"
* elif t == NPY_SHORT: f[0] = 104 #"h"
* elif t == NPY_USHORT: f[0] = 72 #"H" # <<<<<<<<<<<<<<
* elif t == NPY_INT: f[0] = 105 #"i"
* elif t == NPY_UINT: f[0] = 73 #"I"
*/
__pyx_t_3 = PyInt_FromLong(NPY_USHORT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_3);
__pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
__pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 829; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
if (__pyx_t_6) {
(__pyx_v_f[0]) = 72;
goto __pyx_L11;
}
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":830
* elif t == NPY_SHORT: f[0] = 104 #"h"
* elif t == NPY_USHORT: f[0] = 72 #"H"
* elif t == NPY_INT: f[0] = 105 #"i" # <<<<<<<<<<<<<<
* elif t == NPY_UINT: f[0] = 73 #"I"
* elif t == NPY_LONG: f[0] = 108 #"l"
*/
__pyx_t_4 = PyInt_FromLong(NPY_INT); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_4);
__pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
__pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 830; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
if (__pyx_t_6) {
(__pyx_v_f[0]) = 105;
goto __pyx_L11;
}
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":831
* elif t == NPY_USHORT: f[0] = 72 #"H"
* elif t == NPY_INT: f[0] = 105 #"i"
* elif t == NPY_UINT: f[0] = 73 #"I" # <<<<<<<<<<<<<<
* elif t == NPY_LONG: f[0] = 108 #"l"
* elif t == NPY_ULONG: f[0] = 76 #"L"
*/
__pyx_t_3 = PyInt_FromLong(NPY_UINT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_3);
__pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
__pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 831; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
if (__pyx_t_6) {
(__pyx_v_f[0]) = 73;
goto __pyx_L11;
}
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":832
* elif t == NPY_INT: f[0] = 105 #"i"
* elif t == NPY_UINT: f[0] = 73 #"I"
* elif t == NPY_LONG: f[0] = 108 #"l" # <<<<<<<<<<<<<<
* elif t == NPY_ULONG: f[0] = 76 #"L"
* elif t == NPY_LONGLONG: f[0] = 113 #"q"
*/
__pyx_t_4 = PyInt_FromLong(NPY_LONG); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_4);
__pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
__pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 832; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
if (__pyx_t_6) {
(__pyx_v_f[0]) = 108;
goto __pyx_L11;
}
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":833
* elif t == NPY_UINT: f[0] = 73 #"I"
* elif t == NPY_LONG: f[0] = 108 #"l"
* elif t == NPY_ULONG: f[0] = 76 #"L" # <<<<<<<<<<<<<<
* elif t == NPY_LONGLONG: f[0] = 113 #"q"
* elif t == NPY_ULONGLONG: f[0] = 81 #"Q"
*/
__pyx_t_3 = PyInt_FromLong(NPY_ULONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_3);
__pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
__pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 833; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
if (__pyx_t_6) {
(__pyx_v_f[0]) = 76;
goto __pyx_L11;
}
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":834
* elif t == NPY_LONG: f[0] = 108 #"l"
* elif t == NPY_ULONG: f[0] = 76 #"L"
* elif t == NPY_LONGLONG: f[0] = 113 #"q" # <<<<<<<<<<<<<<
* elif t == NPY_ULONGLONG: f[0] = 81 #"Q"
* elif t == NPY_FLOAT: f[0] = 102 #"f"
*/
__pyx_t_4 = PyInt_FromLong(NPY_LONGLONG); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_4);
__pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
__pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 834; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
if (__pyx_t_6) {
(__pyx_v_f[0]) = 113;
goto __pyx_L11;
}
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":835
* elif t == NPY_ULONG: f[0] = 76 #"L"
* elif t == NPY_LONGLONG: f[0] = 113 #"q"
* elif t == NPY_ULONGLONG: f[0] = 81 #"Q" # <<<<<<<<<<<<<<
* elif t == NPY_FLOAT: f[0] = 102 #"f"
* elif t == NPY_DOUBLE: f[0] = 100 #"d"
*/
__pyx_t_3 = PyInt_FromLong(NPY_ULONGLONG); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_3);
__pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
__pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 835; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
if (__pyx_t_6) {
(__pyx_v_f[0]) = 81;
goto __pyx_L11;
}
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":836
* elif t == NPY_LONGLONG: f[0] = 113 #"q"
* elif t == NPY_ULONGLONG: f[0] = 81 #"Q"
* elif t == NPY_FLOAT: f[0] = 102 #"f" # <<<<<<<<<<<<<<
* elif t == NPY_DOUBLE: f[0] = 100 #"d"
* elif t == NPY_LONGDOUBLE: f[0] = 103 #"g"
*/
__pyx_t_4 = PyInt_FromLong(NPY_FLOAT); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_4);
__pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
__pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 836; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
if (__pyx_t_6) {
(__pyx_v_f[0]) = 102;
goto __pyx_L11;
}
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":837
* elif t == NPY_ULONGLONG: f[0] = 81 #"Q"
* elif t == NPY_FLOAT: f[0] = 102 #"f"
* elif t == NPY_DOUBLE: f[0] = 100 #"d" # <<<<<<<<<<<<<<
* elif t == NPY_LONGDOUBLE: f[0] = 103 #"g"
* elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf
*/
__pyx_t_3 = PyInt_FromLong(NPY_DOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_3);
__pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
__pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 837; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
if (__pyx_t_6) {
(__pyx_v_f[0]) = 100;
goto __pyx_L11;
}
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":838
* elif t == NPY_FLOAT: f[0] = 102 #"f"
* elif t == NPY_DOUBLE: f[0] = 100 #"d"
* elif t == NPY_LONGDOUBLE: f[0] = 103 #"g" # <<<<<<<<<<<<<<
* elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf
* elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd
*/
__pyx_t_4 = PyInt_FromLong(NPY_LONGDOUBLE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_4);
__pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
__pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 838; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
if (__pyx_t_6) {
(__pyx_v_f[0]) = 103;
goto __pyx_L11;
}
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":839
* elif t == NPY_DOUBLE: f[0] = 100 #"d"
* elif t == NPY_LONGDOUBLE: f[0] = 103 #"g"
* elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf # <<<<<<<<<<<<<<
* elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd
* elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg
*/
__pyx_t_3 = PyInt_FromLong(NPY_CFLOAT); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_3);
__pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
__pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 839; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
if (__pyx_t_6) {
(__pyx_v_f[0]) = 90;
(__pyx_v_f[1]) = 102;
__pyx_v_f = (__pyx_v_f + 1);
goto __pyx_L11;
}
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":840
* elif t == NPY_LONGDOUBLE: f[0] = 103 #"g"
* elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf
* elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd # <<<<<<<<<<<<<<
* elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg
* elif t == NPY_OBJECT: f[0] = 79 #"O"
*/
__pyx_t_4 = PyInt_FromLong(NPY_CDOUBLE); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_4);
__pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
__pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 840; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
if (__pyx_t_6) {
(__pyx_v_f[0]) = 90;
(__pyx_v_f[1]) = 100;
__pyx_v_f = (__pyx_v_f + 1);
goto __pyx_L11;
}
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":841
* elif t == NPY_CFLOAT: f[0] = 90; f[1] = 102; f += 1 # Zf
* elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd
* elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg # <<<<<<<<<<<<<<
* elif t == NPY_OBJECT: f[0] = 79 #"O"
* else:
*/
__pyx_t_3 = PyInt_FromLong(NPY_CLONGDOUBLE); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_3);
__pyx_t_4 = PyObject_RichCompare(__pyx_v_t, __pyx_t_3, Py_EQ); __Pyx_XGOTREF(__pyx_t_4); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
__pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 841; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
if (__pyx_t_6) {
(__pyx_v_f[0]) = 90;
(__pyx_v_f[1]) = 103;
__pyx_v_f = (__pyx_v_f + 1);
goto __pyx_L11;
}
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":842
* elif t == NPY_CDOUBLE: f[0] = 90; f[1] = 100; f += 1 # Zd
* elif t == NPY_CLONGDOUBLE: f[0] = 90; f[1] = 103; f += 1 # Zg
* elif t == NPY_OBJECT: f[0] = 79 #"O" # <<<<<<<<<<<<<<
* else:
* raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t)
*/
__pyx_t_4 = PyInt_FromLong(NPY_OBJECT); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_4);
__pyx_t_3 = PyObject_RichCompare(__pyx_v_t, __pyx_t_4, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
__pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 842; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
if (__pyx_t_6) {
(__pyx_v_f[0]) = 79;
goto __pyx_L11;
}
/*else*/ {
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":844
* elif t == NPY_OBJECT: f[0] = 79 #"O"
* else:
* raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t) # <<<<<<<<<<<<<<
* f += 1
* else:
*/
__pyx_t_3 = PyUnicode_Format(__pyx_kp_u_unknown_dtype_code_in_numpy_pxd, __pyx_v_t); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_3);
__pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_4);
PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3);
__Pyx_GIVEREF(__pyx_t_3);
__pyx_t_3 = 0;
__pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_4, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_3);
__Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
__Pyx_Raise(__pyx_t_3, 0, 0, 0);
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
{__pyx_filename = __pyx_f[1]; __pyx_lineno = 844; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
}
__pyx_L11:;
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":845
* else:
* raise ValueError(u"unknown dtype code in numpy.pxd (%d)" % t)
* f += 1 # <<<<<<<<<<<<<<
* else:
* # Cython ignores struct boundary information ("T{...}"),
*/
__pyx_v_f = (__pyx_v_f + 1);
goto __pyx_L9;
}
/*else*/ {
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":849
* # Cython ignores struct boundary information ("T{...}"),
* # so don't output it
* f = _util_dtypestring(child, f, end, offset) # <<<<<<<<<<<<<<
* return f
*
*/
__pyx_t_11 = __pyx_f_5numpy__util_dtypestring(__pyx_v_child, __pyx_v_f, __pyx_v_end, __pyx_v_offset); if (unlikely(__pyx_t_11 == NULL)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 849; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_v_f = __pyx_t_11;
}
__pyx_L9:;
}
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":850
* # so don't output it
* f = _util_dtypestring(child, f, end, offset)
* return f # <<<<<<<<<<<<<<
*
*
*/
__pyx_r = __pyx_v_f;
goto __pyx_L0;
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":783
* return PyArray_MultiIterNew(5, <void*>a, <void*>b, <void*>c, <void*> d, <void*> e)
*
* cdef inline char* _util_dtypestring(dtype descr, char* f, char* end, int* offset) except NULL: # <<<<<<<<<<<<<<
* # Recursive utility function used in __getbuffer__ to get format
* # string. The new location in the format string is returned.
*/
/* function exit code */
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_1);
__Pyx_XDECREF(__pyx_t_3);
__Pyx_XDECREF(__pyx_t_4);
__Pyx_AddTraceback("numpy._util_dtypestring", __pyx_clineno, __pyx_lineno, __pyx_filename);
__pyx_r = NULL;
__pyx_L0:;
__Pyx_XDECREF((PyObject *)__pyx_v_child);
__Pyx_XDECREF(__pyx_v_fields);
__Pyx_XDECREF(__pyx_v_childname);
__Pyx_XDECREF(__pyx_v_new_offset);
__Pyx_XDECREF(__pyx_v_t);
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":966
*
*
* cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<<
* cdef PyObject* baseptr
* if base is None:
*/
static CYTHON_INLINE void __pyx_f_5numpy_set_array_base(PyArrayObject *__pyx_v_arr, PyObject *__pyx_v_base) {
PyObject *__pyx_v_baseptr;
__Pyx_RefNannyDeclarations
int __pyx_t_1;
int __pyx_t_2;
__Pyx_RefNannySetupContext("set_array_base", 0);
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":968
* cdef inline void set_array_base(ndarray arr, object base):
* cdef PyObject* baseptr
* if base is None: # <<<<<<<<<<<<<<
* baseptr = NULL
* else:
*/
__pyx_t_1 = (__pyx_v_base == Py_None);
__pyx_t_2 = (__pyx_t_1 != 0);
if (__pyx_t_2) {
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":969
* cdef PyObject* baseptr
* if base is None:
* baseptr = NULL # <<<<<<<<<<<<<<
* else:
* Py_INCREF(base) # important to do this before decref below!
*/
__pyx_v_baseptr = NULL;
goto __pyx_L3;
}
/*else*/ {
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":971
* baseptr = NULL
* else:
* Py_INCREF(base) # important to do this before decref below! # <<<<<<<<<<<<<<
* baseptr = <PyObject*>base
* Py_XDECREF(arr.base)
*/
Py_INCREF(__pyx_v_base);
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":972
* else:
* Py_INCREF(base) # important to do this before decref below!
* baseptr = <PyObject*>base # <<<<<<<<<<<<<<
* Py_XDECREF(arr.base)
* arr.base = baseptr
*/
__pyx_v_baseptr = ((PyObject *)__pyx_v_base);
}
__pyx_L3:;
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":973
* Py_INCREF(base) # important to do this before decref below!
* baseptr = <PyObject*>base
* Py_XDECREF(arr.base) # <<<<<<<<<<<<<<
* arr.base = baseptr
*
*/
Py_XDECREF(__pyx_v_arr->base);
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":974
* baseptr = <PyObject*>base
* Py_XDECREF(arr.base)
* arr.base = baseptr # <<<<<<<<<<<<<<
*
* cdef inline object get_array_base(ndarray arr):
*/
__pyx_v_arr->base = __pyx_v_baseptr;
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":966
*
*
* cdef inline void set_array_base(ndarray arr, object base): # <<<<<<<<<<<<<<
* cdef PyObject* baseptr
* if base is None:
*/
/* function exit code */
__Pyx_RefNannyFinishContext();
}
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":976
* arr.base = baseptr
*
* cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<<
* if arr.base is NULL:
* return None
*/
static CYTHON_INLINE PyObject *__pyx_f_5numpy_get_array_base(PyArrayObject *__pyx_v_arr) {
PyObject *__pyx_r = NULL;
__Pyx_RefNannyDeclarations
int __pyx_t_1;
__Pyx_RefNannySetupContext("get_array_base", 0);
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":977
*
* cdef inline object get_array_base(ndarray arr):
* if arr.base is NULL: # <<<<<<<<<<<<<<
* return None
* else:
*/
__pyx_t_1 = ((__pyx_v_arr->base == NULL) != 0);
if (__pyx_t_1) {
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":978
* cdef inline object get_array_base(ndarray arr):
* if arr.base is NULL:
* return None # <<<<<<<<<<<<<<
* else:
* return <object>arr.base
*/
__Pyx_XDECREF(__pyx_r);
__Pyx_INCREF(Py_None);
__pyx_r = Py_None;
goto __pyx_L0;
}
/*else*/ {
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":980
* return None
* else:
* return <object>arr.base # <<<<<<<<<<<<<<
*/
__Pyx_XDECREF(__pyx_r);
__Pyx_INCREF(((PyObject *)__pyx_v_arr->base));
__pyx_r = ((PyObject *)__pyx_v_arr->base);
goto __pyx_L0;
}
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":976
* arr.base = baseptr
*
* cdef inline object get_array_base(ndarray arr): # <<<<<<<<<<<<<<
* if arr.base is NULL:
* return None
*/
/* function exit code */
__pyx_L0:;
__Pyx_XGIVEREF(__pyx_r);
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "View.MemoryView":113
* cdef bint dtype_is_object
*
* def __cinit__(array self, tuple shape, Py_ssize_t itemsize, format not None, # <<<<<<<<<<<<<<
* mode=u"c", bint allocate_buffer=True):
*
*/
/* Python wrapper */
static int __pyx_array___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/
static int __pyx_array___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) {
PyObject *__pyx_v_shape = 0;
Py_ssize_t __pyx_v_itemsize;
PyObject *__pyx_v_format = 0;
PyObject *__pyx_v_mode = 0;
int __pyx_v_allocate_buffer;
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
int __pyx_r;
__Pyx_RefNannyDeclarations
__Pyx_RefNannySetupContext("__cinit__ (wrapper)", 0);
{
static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_shape,&__pyx_n_s_itemsize,&__pyx_n_s_format,&__pyx_n_s_mode,&__pyx_n_s_allocate_buffer,0};
PyObject* values[5] = {0,0,0,0,0};
values[3] = ((PyObject *)__pyx_n_u_c);
if (unlikely(__pyx_kwds)) {
Py_ssize_t kw_args;
const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args);
switch (pos_args) {
case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4);
case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3);
case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2);
case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1);
case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0);
case 0: break;
default: goto __pyx_L5_argtuple_error;
}
kw_args = PyDict_Size(__pyx_kwds);
switch (pos_args) {
case 0:
if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_shape)) != 0)) kw_args--;
else goto __pyx_L5_argtuple_error;
case 1:
if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_itemsize)) != 0)) kw_args--;
else {
__Pyx_RaiseArgtupleInvalid("__cinit__", 0, 3, 5, 1); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
}
case 2:
if (likely((values[2] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_format)) != 0)) kw_args--;
else {
__Pyx_RaiseArgtupleInvalid("__cinit__", 0, 3, 5, 2); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
}
case 3:
if (kw_args > 0) {
PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_mode);
if (value) { values[3] = value; kw_args--; }
}
case 4:
if (kw_args > 0) {
PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_allocate_buffer);
if (value) { values[4] = value; kw_args--; }
}
}
if (unlikely(kw_args > 0)) {
if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__cinit__") < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
}
} else {
switch (PyTuple_GET_SIZE(__pyx_args)) {
case 5: values[4] = PyTuple_GET_ITEM(__pyx_args, 4);
case 4: values[3] = PyTuple_GET_ITEM(__pyx_args, 3);
case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2);
values[1] = PyTuple_GET_ITEM(__pyx_args, 1);
values[0] = PyTuple_GET_ITEM(__pyx_args, 0);
break;
default: goto __pyx_L5_argtuple_error;
}
}
__pyx_v_shape = ((PyObject*)values[0]);
__pyx_v_itemsize = __Pyx_PyIndex_AsSsize_t(values[1]); if (unlikely((__pyx_v_itemsize == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
__pyx_v_format = values[2];
__pyx_v_mode = values[3];
if (values[4]) {
__pyx_v_allocate_buffer = __Pyx_PyObject_IsTrue(values[4]); if (unlikely((__pyx_v_allocate_buffer == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 114; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
} else {
/* "View.MemoryView":114
*
* def __cinit__(array self, tuple shape, Py_ssize_t itemsize, format not None,
* mode=u"c", bint allocate_buffer=True): # <<<<<<<<<<<<<<
*
* cdef int idx
*/
__pyx_v_allocate_buffer = ((int)1);
}
}
goto __pyx_L4_argument_unpacking_done;
__pyx_L5_argtuple_error:;
__Pyx_RaiseArgtupleInvalid("__cinit__", 0, 3, 5, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
__pyx_L3_error:;
__Pyx_AddTraceback("View.MemoryView.array.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename);
__Pyx_RefNannyFinishContext();
return -1;
__pyx_L4_argument_unpacking_done:;
if (unlikely(!__Pyx_ArgTypeTest(((PyObject *)__pyx_v_shape), (&PyTuple_Type), 1, "shape", 1))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
if (unlikely(((PyObject *)__pyx_v_format) == Py_None)) {
PyErr_Format(PyExc_TypeError, "Argument '%.200s' must not be None", "format"); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 113; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
}
__pyx_r = __pyx_array_MemoryView_5array___cinit__(((struct __pyx_array_obj *)__pyx_v_self), __pyx_v_shape, __pyx_v_itemsize, __pyx_v_format, __pyx_v_mode, __pyx_v_allocate_buffer);
/* "View.MemoryView":113
* cdef bint dtype_is_object
*
* def __cinit__(array self, tuple shape, Py_ssize_t itemsize, format not None, # <<<<<<<<<<<<<<
* mode=u"c", bint allocate_buffer=True):
*
*/
/* function exit code */
goto __pyx_L0;
__pyx_L1_error:;
__pyx_r = -1;
__pyx_L0:;
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
static int __pyx_array_MemoryView_5array___cinit__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_shape, Py_ssize_t __pyx_v_itemsize, PyObject *__pyx_v_format, PyObject *__pyx_v_mode, int __pyx_v_allocate_buffer) {
int __pyx_v_idx;
Py_ssize_t __pyx_v_i;
PyObject **__pyx_v_p;
PyObject *__pyx_v_encode = NULL;
PyObject *__pyx_v_dim = NULL;
char __pyx_v_order;
PyObject *__pyx_v_decode = NULL;
int __pyx_r;
__Pyx_RefNannyDeclarations
Py_ssize_t __pyx_t_1;
int __pyx_t_2;
PyObject *__pyx_t_3 = NULL;
char *__pyx_t_4;
int __pyx_t_5;
int __pyx_t_6;
int __pyx_t_7;
PyObject *__pyx_t_8 = NULL;
PyObject *__pyx_t_9 = NULL;
Py_ssize_t __pyx_t_10;
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
__Pyx_RefNannySetupContext("__cinit__", 0);
__Pyx_INCREF(__pyx_v_format);
__Pyx_INCREF(__pyx_v_mode);
/* "View.MemoryView":120
* cdef PyObject **p
*
* self.ndim = <int> len(shape) # <<<<<<<<<<<<<<
* self.itemsize = itemsize
*
*/
if (unlikely(__pyx_v_shape == Py_None)) {
PyErr_SetString(PyExc_TypeError, "object of type 'NoneType' has no len()");
{__pyx_filename = __pyx_f[2]; __pyx_lineno = 120; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
}
__pyx_t_1 = PyTuple_GET_SIZE(__pyx_v_shape); if (unlikely(__pyx_t_1 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 120; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_v_self->ndim = ((int)__pyx_t_1);
/* "View.MemoryView":121
*
* self.ndim = <int> len(shape)
* self.itemsize = itemsize # <<<<<<<<<<<<<<
*
* if not self.ndim:
*/
__pyx_v_self->itemsize = __pyx_v_itemsize;
/* "View.MemoryView":123
* self.itemsize = itemsize
*
* if not self.ndim: # <<<<<<<<<<<<<<
* raise ValueError("Empty shape tuple for cython.array")
*
*/
__pyx_t_2 = ((!(__pyx_v_self->ndim != 0)) != 0);
if (__pyx_t_2) {
/* "View.MemoryView":124
*
* if not self.ndim:
* raise ValueError("Empty shape tuple for cython.array") # <<<<<<<<<<<<<<
*
* if self.itemsize <= 0:
*/
__pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__19, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 124; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_3);
__Pyx_Raise(__pyx_t_3, 0, 0, 0);
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
{__pyx_filename = __pyx_f[2]; __pyx_lineno = 124; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
}
/* "View.MemoryView":126
* raise ValueError("Empty shape tuple for cython.array")
*
* if self.itemsize <= 0: # <<<<<<<<<<<<<<
* raise ValueError("itemsize <= 0 for cython.array")
*
*/
__pyx_t_2 = ((__pyx_v_self->itemsize <= 0) != 0);
if (__pyx_t_2) {
/* "View.MemoryView":127
*
* if self.itemsize <= 0:
* raise ValueError("itemsize <= 0 for cython.array") # <<<<<<<<<<<<<<
*
* encode = getattr(format, 'encode', None)
*/
__pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__20, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 127; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_3);
__Pyx_Raise(__pyx_t_3, 0, 0, 0);
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
{__pyx_filename = __pyx_f[2]; __pyx_lineno = 127; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
}
/* "View.MemoryView":129
* raise ValueError("itemsize <= 0 for cython.array")
*
* encode = getattr(format, 'encode', None) # <<<<<<<<<<<<<<
* if encode:
* format = encode('ASCII')
*/
__pyx_t_3 = __Pyx_GetAttr3(__pyx_v_format, __pyx_n_s_encode, Py_None); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 129; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_3);
__pyx_v_encode = __pyx_t_3;
__pyx_t_3 = 0;
/* "View.MemoryView":130
*
* encode = getattr(format, 'encode', None)
* if encode: # <<<<<<<<<<<<<<
* format = encode('ASCII')
* self._format = format
*/
__pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_v_encode); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 130; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
if (__pyx_t_2) {
/* "View.MemoryView":131
* encode = getattr(format, 'encode', None)
* if encode:
* format = encode('ASCII') # <<<<<<<<<<<<<<
* self._format = format
* self.format = self._format
*/
__pyx_t_3 = __Pyx_PyObject_Call(__pyx_v_encode, __pyx_tuple__21, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 131; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_3);
__Pyx_DECREF_SET(__pyx_v_format, __pyx_t_3);
__pyx_t_3 = 0;
goto __pyx_L5;
}
__pyx_L5:;
/* "View.MemoryView":132
* if encode:
* format = encode('ASCII')
* self._format = format # <<<<<<<<<<<<<<
* self.format = self._format
*
*/
if (!(likely(PyBytes_CheckExact(__pyx_v_format))||((__pyx_v_format) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "bytes", Py_TYPE(__pyx_v_format)->tp_name), 0))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 132; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_t_3 = __pyx_v_format;
__Pyx_INCREF(__pyx_t_3);
__Pyx_GIVEREF(__pyx_t_3);
__Pyx_GOTREF(__pyx_v_self->_format);
__Pyx_DECREF(__pyx_v_self->_format);
__pyx_v_self->_format = ((PyObject*)__pyx_t_3);
__pyx_t_3 = 0;
/* "View.MemoryView":133
* format = encode('ASCII')
* self._format = format
* self.format = self._format # <<<<<<<<<<<<<<
*
* self._shape = <Py_ssize_t *> malloc(sizeof(Py_ssize_t)*self.ndim)
*/
__pyx_t_4 = __Pyx_PyObject_AsString(__pyx_v_self->_format); if (unlikely((!__pyx_t_4) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 133; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_v_self->format = __pyx_t_4;
/* "View.MemoryView":135
* self.format = self._format
*
* self._shape = <Py_ssize_t *> malloc(sizeof(Py_ssize_t)*self.ndim) # <<<<<<<<<<<<<<
* self._strides = <Py_ssize_t *> malloc(sizeof(Py_ssize_t)*self.ndim)
*
*/
__pyx_v_self->_shape = ((Py_ssize_t *)malloc(((sizeof(Py_ssize_t)) * __pyx_v_self->ndim)));
/* "View.MemoryView":136
*
* self._shape = <Py_ssize_t *> malloc(sizeof(Py_ssize_t)*self.ndim)
* self._strides = <Py_ssize_t *> malloc(sizeof(Py_ssize_t)*self.ndim) # <<<<<<<<<<<<<<
*
* if not self._shape or not self._strides:
*/
__pyx_v_self->_strides = ((Py_ssize_t *)malloc(((sizeof(Py_ssize_t)) * __pyx_v_self->ndim)));
/* "View.MemoryView":138
* self._strides = <Py_ssize_t *> malloc(sizeof(Py_ssize_t)*self.ndim)
*
* if not self._shape or not self._strides: # <<<<<<<<<<<<<<
* free(self._shape)
* free(self._strides)
*/
__pyx_t_2 = ((!(__pyx_v_self->_shape != 0)) != 0);
if (!__pyx_t_2) {
__pyx_t_5 = ((!(__pyx_v_self->_strides != 0)) != 0);
__pyx_t_6 = __pyx_t_5;
} else {
__pyx_t_6 = __pyx_t_2;
}
if (__pyx_t_6) {
/* "View.MemoryView":139
*
* if not self._shape or not self._strides:
* free(self._shape) # <<<<<<<<<<<<<<
* free(self._strides)
* raise MemoryError("unable to allocate shape or strides.")
*/
free(__pyx_v_self->_shape);
/* "View.MemoryView":140
* if not self._shape or not self._strides:
* free(self._shape)
* free(self._strides) # <<<<<<<<<<<<<<
* raise MemoryError("unable to allocate shape or strides.")
*
*/
free(__pyx_v_self->_strides);
/* "View.MemoryView":141
* free(self._shape)
* free(self._strides)
* raise MemoryError("unable to allocate shape or strides.") # <<<<<<<<<<<<<<
*
*
*/
__pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_MemoryError, __pyx_tuple__22, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 141; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_3);
__Pyx_Raise(__pyx_t_3, 0, 0, 0);
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
{__pyx_filename = __pyx_f[2]; __pyx_lineno = 141; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
}
/* "View.MemoryView":144
*
*
* idx = 0 # <<<<<<<<<<<<<<
* for idx, dim in enumerate(shape):
* if dim <= 0:
*/
__pyx_v_idx = 0;
/* "View.MemoryView":145
*
* idx = 0
* for idx, dim in enumerate(shape): # <<<<<<<<<<<<<<
* if dim <= 0:
* raise ValueError("Invalid shape in axis %d: %d." % (idx, dim))
*/
__pyx_t_7 = 0;
__pyx_t_3 = __pyx_v_shape; __Pyx_INCREF(__pyx_t_3); __pyx_t_1 = 0;
for (;;) {
if (__pyx_t_1 >= PyTuple_GET_SIZE(__pyx_t_3)) break;
#if CYTHON_COMPILING_IN_CPYTHON
__pyx_t_8 = PyTuple_GET_ITEM(__pyx_t_3, __pyx_t_1); __Pyx_INCREF(__pyx_t_8); __pyx_t_1++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 145; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
#else
__pyx_t_8 = PySequence_ITEM(__pyx_t_3, __pyx_t_1); __pyx_t_1++; if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 145; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
#endif
__Pyx_XDECREF_SET(__pyx_v_dim, __pyx_t_8);
__pyx_t_8 = 0;
__pyx_v_idx = __pyx_t_7;
__pyx_t_7 = (__pyx_t_7 + 1);
/* "View.MemoryView":146
* idx = 0
* for idx, dim in enumerate(shape):
* if dim <= 0: # <<<<<<<<<<<<<<
* raise ValueError("Invalid shape in axis %d: %d." % (idx, dim))
*
*/
__pyx_t_8 = PyObject_RichCompare(__pyx_v_dim, __pyx_int_0, Py_LE); __Pyx_XGOTREF(__pyx_t_8); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 146; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_8); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 146; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0;
if (__pyx_t_6) {
/* "View.MemoryView":147
* for idx, dim in enumerate(shape):
* if dim <= 0:
* raise ValueError("Invalid shape in axis %d: %d." % (idx, dim)) # <<<<<<<<<<<<<<
*
* self._shape[idx] = dim
*/
__pyx_t_8 = __Pyx_PyInt_From_int(__pyx_v_idx); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_8);
__pyx_t_9 = PyTuple_New(2); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_9);
PyTuple_SET_ITEM(__pyx_t_9, 0, __pyx_t_8);
__Pyx_GIVEREF(__pyx_t_8);
__Pyx_INCREF(__pyx_v_dim);
PyTuple_SET_ITEM(__pyx_t_9, 1, __pyx_v_dim);
__Pyx_GIVEREF(__pyx_v_dim);
__pyx_t_8 = 0;
__pyx_t_8 = __Pyx_PyString_Format(__pyx_kp_s_Invalid_shape_in_axis_d_d, __pyx_t_9); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_8);
__Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0;
__pyx_t_9 = PyTuple_New(1); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_9);
PyTuple_SET_ITEM(__pyx_t_9, 0, __pyx_t_8);
__Pyx_GIVEREF(__pyx_t_8);
__pyx_t_8 = 0;
__pyx_t_8 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_9, NULL); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_8);
__Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0;
__Pyx_Raise(__pyx_t_8, 0, 0, 0);
__Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0;
{__pyx_filename = __pyx_f[2]; __pyx_lineno = 147; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
}
/* "View.MemoryView":149
* raise ValueError("Invalid shape in axis %d: %d." % (idx, dim))
*
* self._shape[idx] = dim # <<<<<<<<<<<<<<
* idx += 1
*
*/
__pyx_t_10 = __Pyx_PyIndex_AsSsize_t(__pyx_v_dim); if (unlikely((__pyx_t_10 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 149; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
(__pyx_v_self->_shape[__pyx_v_idx]) = __pyx_t_10;
/* "View.MemoryView":150
*
* self._shape[idx] = dim
* idx += 1 # <<<<<<<<<<<<<<
*
* if mode not in ("fortran", "c"):
*/
__pyx_v_idx = (__pyx_v_idx + 1);
}
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
/* "View.MemoryView":152
* idx += 1
*
* if mode not in ("fortran", "c"): # <<<<<<<<<<<<<<
* raise ValueError("Invalid mode, expected 'c' or 'fortran', got %s" % mode)
*
*/
__Pyx_INCREF(__pyx_v_mode);
__pyx_t_3 = __pyx_v_mode;
__pyx_t_6 = (__Pyx_PyString_Equals(__pyx_t_3, __pyx_n_s_fortran, Py_NE)); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 152; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
if (__pyx_t_6) {
__pyx_t_2 = (__Pyx_PyString_Equals(__pyx_t_3, __pyx_n_s_c, Py_NE)); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 152; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_t_5 = __pyx_t_2;
} else {
__pyx_t_5 = __pyx_t_6;
}
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
__pyx_t_6 = (__pyx_t_5 != 0);
if (__pyx_t_6) {
/* "View.MemoryView":153
*
* if mode not in ("fortran", "c"):
* raise ValueError("Invalid mode, expected 'c' or 'fortran', got %s" % mode) # <<<<<<<<<<<<<<
*
* cdef char order
*/
__pyx_t_3 = __Pyx_PyString_Format(__pyx_kp_s_Invalid_mode_expected_c_or_fortr, __pyx_v_mode); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 153; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_3);
__pyx_t_8 = PyTuple_New(1); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 153; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_8);
PyTuple_SET_ITEM(__pyx_t_8, 0, __pyx_t_3);
__Pyx_GIVEREF(__pyx_t_3);
__pyx_t_3 = 0;
__pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_8, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 153; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_3);
__Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0;
__Pyx_Raise(__pyx_t_3, 0, 0, 0);
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
{__pyx_filename = __pyx_f[2]; __pyx_lineno = 153; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
}
/* "View.MemoryView":156
*
* cdef char order
* if mode == 'fortran': # <<<<<<<<<<<<<<
* order = 'F'
* else:
*/
__pyx_t_6 = (__Pyx_PyString_Equals(__pyx_v_mode, __pyx_n_s_fortran, Py_EQ)); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 156; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
if (__pyx_t_6) {
/* "View.MemoryView":157
* cdef char order
* if mode == 'fortran':
* order = 'F' # <<<<<<<<<<<<<<
* else:
* order = 'C'
*/
__pyx_v_order = 'F';
goto __pyx_L11;
}
/*else*/ {
/* "View.MemoryView":159
* order = 'F'
* else:
* order = 'C' # <<<<<<<<<<<<<<
*
* self.len = fill_contig_strides_array(self._shape, self._strides,
*/
__pyx_v_order = 'C';
}
__pyx_L11:;
/* "View.MemoryView":161
* order = 'C'
*
* self.len = fill_contig_strides_array(self._shape, self._strides, # <<<<<<<<<<<<<<
* itemsize, self.ndim, order)
*
*/
__pyx_v_self->len = __pyx_fill_contig_strides_array(__pyx_v_self->_shape, __pyx_v_self->_strides, __pyx_v_itemsize, __pyx_v_self->ndim, __pyx_v_order);
/* "View.MemoryView":164
* itemsize, self.ndim, order)
*
* decode = getattr(mode, 'decode', None) # <<<<<<<<<<<<<<
* if decode:
* mode = decode('ASCII')
*/
__pyx_t_3 = __Pyx_GetAttr3(__pyx_v_mode, __pyx_n_s_decode, Py_None); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 164; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_3);
__pyx_v_decode = __pyx_t_3;
__pyx_t_3 = 0;
/* "View.MemoryView":165
*
* decode = getattr(mode, 'decode', None)
* if decode: # <<<<<<<<<<<<<<
* mode = decode('ASCII')
* self.mode = mode
*/
__pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_v_decode); if (unlikely(__pyx_t_6 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 165; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
if (__pyx_t_6) {
/* "View.MemoryView":166
* decode = getattr(mode, 'decode', None)
* if decode:
* mode = decode('ASCII') # <<<<<<<<<<<<<<
* self.mode = mode
*
*/
__pyx_t_3 = __Pyx_PyObject_Call(__pyx_v_decode, __pyx_tuple__23, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 166; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_3);
__Pyx_DECREF_SET(__pyx_v_mode, __pyx_t_3);
__pyx_t_3 = 0;
goto __pyx_L12;
}
__pyx_L12:;
/* "View.MemoryView":167
* if decode:
* mode = decode('ASCII')
* self.mode = mode # <<<<<<<<<<<<<<
*
* self.free_data = allocate_buffer
*/
if (!(likely(PyUnicode_CheckExact(__pyx_v_mode))||((__pyx_v_mode) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "unicode", Py_TYPE(__pyx_v_mode)->tp_name), 0))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 167; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_t_3 = __pyx_v_mode;
__Pyx_INCREF(__pyx_t_3);
__Pyx_GIVEREF(__pyx_t_3);
__Pyx_GOTREF(__pyx_v_self->mode);
__Pyx_DECREF(__pyx_v_self->mode);
__pyx_v_self->mode = ((PyObject*)__pyx_t_3);
__pyx_t_3 = 0;
/* "View.MemoryView":169
* self.mode = mode
*
* self.free_data = allocate_buffer # <<<<<<<<<<<<<<
* self.dtype_is_object = format == b'O'
* if allocate_buffer:
*/
__pyx_v_self->free_data = __pyx_v_allocate_buffer;
/* "View.MemoryView":170
*
* self.free_data = allocate_buffer
* self.dtype_is_object = format == b'O' # <<<<<<<<<<<<<<
* if allocate_buffer:
* self.data = <char *>malloc(self.len)
*/
__pyx_t_3 = PyObject_RichCompare(__pyx_v_format, __pyx_n_b_O, Py_EQ); __Pyx_XGOTREF(__pyx_t_3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 170; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_t_6 = __Pyx_PyObject_IsTrue(__pyx_t_3); if (unlikely((__pyx_t_6 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 170; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
__pyx_v_self->dtype_is_object = __pyx_t_6;
/* "View.MemoryView":171
* self.free_data = allocate_buffer
* self.dtype_is_object = format == b'O'
* if allocate_buffer: # <<<<<<<<<<<<<<
* self.data = <char *>malloc(self.len)
* if not self.data:
*/
__pyx_t_6 = (__pyx_v_allocate_buffer != 0);
if (__pyx_t_6) {
/* "View.MemoryView":172
* self.dtype_is_object = format == b'O'
* if allocate_buffer:
* self.data = <char *>malloc(self.len) # <<<<<<<<<<<<<<
* if not self.data:
* raise MemoryError("unable to allocate array data.")
*/
__pyx_v_self->data = ((char *)malloc(__pyx_v_self->len));
/* "View.MemoryView":173
* if allocate_buffer:
* self.data = <char *>malloc(self.len)
* if not self.data: # <<<<<<<<<<<<<<
* raise MemoryError("unable to allocate array data.")
*
*/
__pyx_t_6 = ((!(__pyx_v_self->data != 0)) != 0);
if (__pyx_t_6) {
/* "View.MemoryView":174
* self.data = <char *>malloc(self.len)
* if not self.data:
* raise MemoryError("unable to allocate array data.") # <<<<<<<<<<<<<<
*
* if self.dtype_is_object:
*/
__pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_MemoryError, __pyx_tuple__24, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 174; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_3);
__Pyx_Raise(__pyx_t_3, 0, 0, 0);
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
{__pyx_filename = __pyx_f[2]; __pyx_lineno = 174; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
}
/* "View.MemoryView":176
* raise MemoryError("unable to allocate array data.")
*
* if self.dtype_is_object: # <<<<<<<<<<<<<<
* p = <PyObject **> self.data
* for i in range(self.len / itemsize):
*/
__pyx_t_6 = (__pyx_v_self->dtype_is_object != 0);
if (__pyx_t_6) {
/* "View.MemoryView":177
*
* if self.dtype_is_object:
* p = <PyObject **> self.data # <<<<<<<<<<<<<<
* for i in range(self.len / itemsize):
* p[i] = Py_None
*/
__pyx_v_p = ((PyObject **)__pyx_v_self->data);
/* "View.MemoryView":178
* if self.dtype_is_object:
* p = <PyObject **> self.data
* for i in range(self.len / itemsize): # <<<<<<<<<<<<<<
* p[i] = Py_None
* Py_INCREF(Py_None)
*/
if (unlikely(__pyx_v_itemsize == 0)) {
#ifdef WITH_THREAD
PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure();
#endif
PyErr_SetString(PyExc_ZeroDivisionError, "integer division or modulo by zero");
#ifdef WITH_THREAD
PyGILState_Release(__pyx_gilstate_save);
#endif
{__pyx_filename = __pyx_f[2]; __pyx_lineno = 178; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
}
else if (sizeof(Py_ssize_t) == sizeof(long) && unlikely(__pyx_v_itemsize == -1) && unlikely(UNARY_NEG_WOULD_OVERFLOW(__pyx_v_self->len))) {
#ifdef WITH_THREAD
PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure();
#endif
PyErr_SetString(PyExc_OverflowError, "value too large to perform division");
#ifdef WITH_THREAD
PyGILState_Release(__pyx_gilstate_save);
#endif
{__pyx_filename = __pyx_f[2]; __pyx_lineno = 178; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
}
__pyx_t_1 = (__pyx_v_self->len / __pyx_v_itemsize);
for (__pyx_t_10 = 0; __pyx_t_10 < __pyx_t_1; __pyx_t_10+=1) {
__pyx_v_i = __pyx_t_10;
/* "View.MemoryView":179
* p = <PyObject **> self.data
* for i in range(self.len / itemsize):
* p[i] = Py_None # <<<<<<<<<<<<<<
* Py_INCREF(Py_None)
*
*/
(__pyx_v_p[__pyx_v_i]) = Py_None;
/* "View.MemoryView":180
* for i in range(self.len / itemsize):
* p[i] = Py_None
* Py_INCREF(Py_None) # <<<<<<<<<<<<<<
*
* @cname('getbuffer')
*/
Py_INCREF(Py_None);
}
goto __pyx_L15;
}
__pyx_L15:;
goto __pyx_L13;
}
__pyx_L13:;
/* "View.MemoryView":113
* cdef bint dtype_is_object
*
* def __cinit__(array self, tuple shape, Py_ssize_t itemsize, format not None, # <<<<<<<<<<<<<<
* mode=u"c", bint allocate_buffer=True):
*
*/
/* function exit code */
__pyx_r = 0;
goto __pyx_L0;
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_3);
__Pyx_XDECREF(__pyx_t_8);
__Pyx_XDECREF(__pyx_t_9);
__Pyx_AddTraceback("View.MemoryView.array.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename);
__pyx_r = -1;
__pyx_L0:;
__Pyx_XDECREF(__pyx_v_encode);
__Pyx_XDECREF(__pyx_v_dim);
__Pyx_XDECREF(__pyx_v_decode);
__Pyx_XDECREF(__pyx_v_format);
__Pyx_XDECREF(__pyx_v_mode);
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "View.MemoryView":183
*
* @cname('getbuffer')
* def __getbuffer__(self, Py_buffer *info, int flags): # <<<<<<<<<<<<<<
* cdef int bufmode = -1
* if self.mode == b"c":
*/
/* Python wrapper */
static CYTHON_UNUSED int __pyx_array_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/
static CYTHON_UNUSED int __pyx_array_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) {
int __pyx_r;
__Pyx_RefNannyDeclarations
__Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0);
__pyx_r = __pyx_array_getbuffer_MemoryView_5array_2__getbuffer__(((struct __pyx_array_obj *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags));
/* function exit code */
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
static int __pyx_array_getbuffer_MemoryView_5array_2__getbuffer__(struct __pyx_array_obj *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) {
int __pyx_v_bufmode;
int __pyx_r;
__Pyx_RefNannyDeclarations
int __pyx_t_1;
int __pyx_t_2;
PyObject *__pyx_t_3 = NULL;
char *__pyx_t_4;
Py_ssize_t __pyx_t_5;
int __pyx_t_6;
Py_ssize_t *__pyx_t_7;
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
__Pyx_RefNannySetupContext("__getbuffer__", 0);
if (__pyx_v_info != NULL) {
__pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None);
__Pyx_GIVEREF(__pyx_v_info->obj);
}
/* "View.MemoryView":184
* @cname('getbuffer')
* def __getbuffer__(self, Py_buffer *info, int flags):
* cdef int bufmode = -1 # <<<<<<<<<<<<<<
* if self.mode == b"c":
* bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS
*/
__pyx_v_bufmode = -1;
/* "View.MemoryView":185
* def __getbuffer__(self, Py_buffer *info, int flags):
* cdef int bufmode = -1
* if self.mode == b"c": # <<<<<<<<<<<<<<
* bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS
* elif self.mode == b"fortran":
*/
__pyx_t_1 = (__Pyx_PyUnicode_Equals(__pyx_v_self->mode, __pyx_n_b_c, Py_EQ)); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 185; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_t_2 = (__pyx_t_1 != 0);
if (__pyx_t_2) {
/* "View.MemoryView":186
* cdef int bufmode = -1
* if self.mode == b"c":
* bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS # <<<<<<<<<<<<<<
* elif self.mode == b"fortran":
* bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS
*/
__pyx_v_bufmode = (PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS);
goto __pyx_L3;
}
/* "View.MemoryView":187
* if self.mode == b"c":
* bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS
* elif self.mode == b"fortran": # <<<<<<<<<<<<<<
* bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS
* if not (flags & bufmode):
*/
__pyx_t_2 = (__Pyx_PyUnicode_Equals(__pyx_v_self->mode, __pyx_n_b_fortran, Py_EQ)); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 187; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_t_1 = (__pyx_t_2 != 0);
if (__pyx_t_1) {
/* "View.MemoryView":188
* bufmode = PyBUF_C_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS
* elif self.mode == b"fortran":
* bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS # <<<<<<<<<<<<<<
* if not (flags & bufmode):
* raise ValueError("Can only create a buffer that is contiguous in memory.")
*/
__pyx_v_bufmode = (PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS);
goto __pyx_L3;
}
__pyx_L3:;
/* "View.MemoryView":189
* elif self.mode == b"fortran":
* bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS
* if not (flags & bufmode): # <<<<<<<<<<<<<<
* raise ValueError("Can only create a buffer that is contiguous in memory.")
* info.buf = self.data
*/
__pyx_t_1 = ((!((__pyx_v_flags & __pyx_v_bufmode) != 0)) != 0);
if (__pyx_t_1) {
/* "View.MemoryView":190
* bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS
* if not (flags & bufmode):
* raise ValueError("Can only create a buffer that is contiguous in memory.") # <<<<<<<<<<<<<<
* info.buf = self.data
* info.len = self.len
*/
__pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__25, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 190; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_3);
__Pyx_Raise(__pyx_t_3, 0, 0, 0);
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
{__pyx_filename = __pyx_f[2]; __pyx_lineno = 190; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
}
/* "View.MemoryView":191
* if not (flags & bufmode):
* raise ValueError("Can only create a buffer that is contiguous in memory.")
* info.buf = self.data # <<<<<<<<<<<<<<
* info.len = self.len
* info.ndim = self.ndim
*/
__pyx_t_4 = __pyx_v_self->data;
__pyx_v_info->buf = __pyx_t_4;
/* "View.MemoryView":192
* raise ValueError("Can only create a buffer that is contiguous in memory.")
* info.buf = self.data
* info.len = self.len # <<<<<<<<<<<<<<
* info.ndim = self.ndim
* info.shape = self._shape
*/
__pyx_t_5 = __pyx_v_self->len;
__pyx_v_info->len = __pyx_t_5;
/* "View.MemoryView":193
* info.buf = self.data
* info.len = self.len
* info.ndim = self.ndim # <<<<<<<<<<<<<<
* info.shape = self._shape
* info.strides = self._strides
*/
__pyx_t_6 = __pyx_v_self->ndim;
__pyx_v_info->ndim = __pyx_t_6;
/* "View.MemoryView":194
* info.len = self.len
* info.ndim = self.ndim
* info.shape = self._shape # <<<<<<<<<<<<<<
* info.strides = self._strides
* info.suboffsets = NULL
*/
__pyx_t_7 = __pyx_v_self->_shape;
__pyx_v_info->shape = __pyx_t_7;
/* "View.MemoryView":195
* info.ndim = self.ndim
* info.shape = self._shape
* info.strides = self._strides # <<<<<<<<<<<<<<
* info.suboffsets = NULL
* info.itemsize = self.itemsize
*/
__pyx_t_7 = __pyx_v_self->_strides;
__pyx_v_info->strides = __pyx_t_7;
/* "View.MemoryView":196
* info.shape = self._shape
* info.strides = self._strides
* info.suboffsets = NULL # <<<<<<<<<<<<<<
* info.itemsize = self.itemsize
* info.readonly = 0
*/
__pyx_v_info->suboffsets = NULL;
/* "View.MemoryView":197
* info.strides = self._strides
* info.suboffsets = NULL
* info.itemsize = self.itemsize # <<<<<<<<<<<<<<
* info.readonly = 0
*
*/
__pyx_t_5 = __pyx_v_self->itemsize;
__pyx_v_info->itemsize = __pyx_t_5;
/* "View.MemoryView":198
* info.suboffsets = NULL
* info.itemsize = self.itemsize
* info.readonly = 0 # <<<<<<<<<<<<<<
*
* if flags & PyBUF_FORMAT:
*/
__pyx_v_info->readonly = 0;
/* "View.MemoryView":200
* info.readonly = 0
*
* if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<<
* info.format = self.format
* else:
*/
__pyx_t_1 = ((__pyx_v_flags & PyBUF_FORMAT) != 0);
if (__pyx_t_1) {
/* "View.MemoryView":201
*
* if flags & PyBUF_FORMAT:
* info.format = self.format # <<<<<<<<<<<<<<
* else:
* info.format = NULL
*/
__pyx_t_4 = __pyx_v_self->format;
__pyx_v_info->format = __pyx_t_4;
goto __pyx_L5;
}
/*else*/ {
/* "View.MemoryView":203
* info.format = self.format
* else:
* info.format = NULL # <<<<<<<<<<<<<<
*
* info.obj = self
*/
__pyx_v_info->format = NULL;
}
__pyx_L5:;
/* "View.MemoryView":205
* info.format = NULL
*
* info.obj = self # <<<<<<<<<<<<<<
*
* __pyx_getbuffer = capsule(<void *> &__pyx_array_getbuffer, "getbuffer(obj, view, flags)")
*/
__Pyx_INCREF(((PyObject *)__pyx_v_self));
__Pyx_GIVEREF(((PyObject *)__pyx_v_self));
__Pyx_GOTREF(__pyx_v_info->obj);
__Pyx_DECREF(__pyx_v_info->obj);
__pyx_v_info->obj = ((PyObject *)__pyx_v_self);
/* "View.MemoryView":183
*
* @cname('getbuffer')
* def __getbuffer__(self, Py_buffer *info, int flags): # <<<<<<<<<<<<<<
* cdef int bufmode = -1
* if self.mode == b"c":
*/
/* function exit code */
__pyx_r = 0;
goto __pyx_L0;
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_3);
__Pyx_AddTraceback("View.MemoryView.array.__getbuffer__", __pyx_clineno, __pyx_lineno, __pyx_filename);
__pyx_r = -1;
if (__pyx_v_info != NULL && __pyx_v_info->obj != NULL) {
__Pyx_GOTREF(__pyx_v_info->obj);
__Pyx_DECREF(__pyx_v_info->obj); __pyx_v_info->obj = NULL;
}
goto __pyx_L2;
__pyx_L0:;
if (__pyx_v_info != NULL && __pyx_v_info->obj == Py_None) {
__Pyx_GOTREF(Py_None);
__Pyx_DECREF(Py_None); __pyx_v_info->obj = NULL;
}
__pyx_L2:;
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "View.MemoryView":209
* __pyx_getbuffer = capsule(<void *> &__pyx_array_getbuffer, "getbuffer(obj, view, flags)")
*
* def __dealloc__(array self): # <<<<<<<<<<<<<<
* if self.callback_free_data != NULL:
* self.callback_free_data(self.data)
*/
/* Python wrapper */
static void __pyx_array___dealloc__(PyObject *__pyx_v_self); /*proto*/
static void __pyx_array___dealloc__(PyObject *__pyx_v_self) {
__Pyx_RefNannyDeclarations
__Pyx_RefNannySetupContext("__dealloc__ (wrapper)", 0);
__pyx_array_MemoryView_5array_4__dealloc__(((struct __pyx_array_obj *)__pyx_v_self));
/* function exit code */
__Pyx_RefNannyFinishContext();
}
static void __pyx_array_MemoryView_5array_4__dealloc__(struct __pyx_array_obj *__pyx_v_self) {
__Pyx_RefNannyDeclarations
int __pyx_t_1;
__Pyx_RefNannySetupContext("__dealloc__", 0);
/* "View.MemoryView":210
*
* def __dealloc__(array self):
* if self.callback_free_data != NULL: # <<<<<<<<<<<<<<
* self.callback_free_data(self.data)
* elif self.free_data:
*/
__pyx_t_1 = ((__pyx_v_self->callback_free_data != NULL) != 0);
if (__pyx_t_1) {
/* "View.MemoryView":211
* def __dealloc__(array self):
* if self.callback_free_data != NULL:
* self.callback_free_data(self.data) # <<<<<<<<<<<<<<
* elif self.free_data:
* if self.dtype_is_object:
*/
__pyx_v_self->callback_free_data(__pyx_v_self->data);
goto __pyx_L3;
}
/* "View.MemoryView":212
* if self.callback_free_data != NULL:
* self.callback_free_data(self.data)
* elif self.free_data: # <<<<<<<<<<<<<<
* if self.dtype_is_object:
* refcount_objects_in_slice(self.data, self._shape,
*/
__pyx_t_1 = (__pyx_v_self->free_data != 0);
if (__pyx_t_1) {
/* "View.MemoryView":213
* self.callback_free_data(self.data)
* elif self.free_data:
* if self.dtype_is_object: # <<<<<<<<<<<<<<
* refcount_objects_in_slice(self.data, self._shape,
* self._strides, self.ndim, False)
*/
__pyx_t_1 = (__pyx_v_self->dtype_is_object != 0);
if (__pyx_t_1) {
/* "View.MemoryView":214
* elif self.free_data:
* if self.dtype_is_object:
* refcount_objects_in_slice(self.data, self._shape, # <<<<<<<<<<<<<<
* self._strides, self.ndim, False)
* free(self.data)
*/
__pyx_memoryview_refcount_objects_in_slice(__pyx_v_self->data, __pyx_v_self->_shape, __pyx_v_self->_strides, __pyx_v_self->ndim, 0);
goto __pyx_L4;
}
__pyx_L4:;
/* "View.MemoryView":216
* refcount_objects_in_slice(self.data, self._shape,
* self._strides, self.ndim, False)
* free(self.data) # <<<<<<<<<<<<<<
*
* free(self._strides)
*/
free(__pyx_v_self->data);
goto __pyx_L3;
}
__pyx_L3:;
/* "View.MemoryView":218
* free(self.data)
*
* free(self._strides) # <<<<<<<<<<<<<<
* free(self._shape)
*
*/
free(__pyx_v_self->_strides);
/* "View.MemoryView":219
*
* free(self._strides)
* free(self._shape) # <<<<<<<<<<<<<<
*
* property memview:
*/
free(__pyx_v_self->_shape);
/* "View.MemoryView":209
* __pyx_getbuffer = capsule(<void *> &__pyx_array_getbuffer, "getbuffer(obj, view, flags)")
*
* def __dealloc__(array self): # <<<<<<<<<<<<<<
* if self.callback_free_data != NULL:
* self.callback_free_data(self.data)
*/
/* function exit code */
__Pyx_RefNannyFinishContext();
}
/* "View.MemoryView":223
* property memview:
* @cname('get_memview')
* def __get__(self): # <<<<<<<<<<<<<<
*
* flags = PyBUF_ANY_CONTIGUOUS|PyBUF_FORMAT|PyBUF_WRITABLE
*/
/* Python wrapper */
static PyObject *get_memview(PyObject *__pyx_v_self); /*proto*/
static PyObject *get_memview(PyObject *__pyx_v_self) {
PyObject *__pyx_r = 0;
__Pyx_RefNannyDeclarations
__Pyx_RefNannySetupContext("__get__ (wrapper)", 0);
__pyx_r = get_memview_MemoryView_5array_7memview___get__(((struct __pyx_array_obj *)__pyx_v_self));
/* function exit code */
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
static PyObject *get_memview_MemoryView_5array_7memview___get__(struct __pyx_array_obj *__pyx_v_self) {
int __pyx_v_flags;
PyObject *__pyx_r = NULL;
__Pyx_RefNannyDeclarations
PyObject *__pyx_t_1 = NULL;
PyObject *__pyx_t_2 = NULL;
PyObject *__pyx_t_3 = NULL;
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
__Pyx_RefNannySetupContext("__get__", 0);
/* "View.MemoryView":225
* def __get__(self):
*
* flags = PyBUF_ANY_CONTIGUOUS|PyBUF_FORMAT|PyBUF_WRITABLE # <<<<<<<<<<<<<<
* return memoryview(self, flags, self.dtype_is_object)
*
*/
__pyx_v_flags = ((PyBUF_ANY_CONTIGUOUS | PyBUF_FORMAT) | PyBUF_WRITABLE);
/* "View.MemoryView":226
*
* flags = PyBUF_ANY_CONTIGUOUS|PyBUF_FORMAT|PyBUF_WRITABLE
* return memoryview(self, flags, self.dtype_is_object) # <<<<<<<<<<<<<<
*
*
*/
__Pyx_XDECREF(__pyx_r);
__pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_flags); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 226; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
__pyx_t_2 = __Pyx_PyBool_FromLong(__pyx_v_self->dtype_is_object); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 226; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_2);
__pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 226; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_3);
__Pyx_INCREF(((PyObject *)__pyx_v_self));
PyTuple_SET_ITEM(__pyx_t_3, 0, ((PyObject *)__pyx_v_self));
__Pyx_GIVEREF(((PyObject *)__pyx_v_self));
PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_1);
__Pyx_GIVEREF(__pyx_t_1);
PyTuple_SET_ITEM(__pyx_t_3, 2, __pyx_t_2);
__Pyx_GIVEREF(__pyx_t_2);
__pyx_t_1 = 0;
__pyx_t_2 = 0;
__pyx_t_2 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_memoryview_type)), __pyx_t_3, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 226; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_2);
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
__pyx_r = __pyx_t_2;
__pyx_t_2 = 0;
goto __pyx_L0;
/* "View.MemoryView":223
* property memview:
* @cname('get_memview')
* def __get__(self): # <<<<<<<<<<<<<<
*
* flags = PyBUF_ANY_CONTIGUOUS|PyBUF_FORMAT|PyBUF_WRITABLE
*/
/* function exit code */
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_1);
__Pyx_XDECREF(__pyx_t_2);
__Pyx_XDECREF(__pyx_t_3);
__Pyx_AddTraceback("View.MemoryView.array.memview.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename);
__pyx_r = NULL;
__pyx_L0:;
__Pyx_XGIVEREF(__pyx_r);
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "View.MemoryView":229
*
*
* def __getattr__(self, attr): # <<<<<<<<<<<<<<
* return getattr(self.memview, attr)
*
*/
/* Python wrapper */
static PyObject *__pyx_array___getattr__(PyObject *__pyx_v_self, PyObject *__pyx_v_attr); /*proto*/
static PyObject *__pyx_array___getattr__(PyObject *__pyx_v_self, PyObject *__pyx_v_attr) {
PyObject *__pyx_r = 0;
__Pyx_RefNannyDeclarations
__Pyx_RefNannySetupContext("__getattr__ (wrapper)", 0);
__pyx_r = __pyx_array_MemoryView_5array_6__getattr__(((struct __pyx_array_obj *)__pyx_v_self), ((PyObject *)__pyx_v_attr));
/* function exit code */
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
static PyObject *__pyx_array_MemoryView_5array_6__getattr__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_attr) {
PyObject *__pyx_r = NULL;
__Pyx_RefNannyDeclarations
PyObject *__pyx_t_1 = NULL;
PyObject *__pyx_t_2 = NULL;
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
__Pyx_RefNannySetupContext("__getattr__", 0);
/* "View.MemoryView":230
*
* def __getattr__(self, attr):
* return getattr(self.memview, attr) # <<<<<<<<<<<<<<
*
* def __getitem__(self, item):
*/
__Pyx_XDECREF(__pyx_r);
__pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_memview); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 230; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
__pyx_t_2 = __Pyx_GetAttr(__pyx_t_1, __pyx_v_attr); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 230; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_2);
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
__pyx_r = __pyx_t_2;
__pyx_t_2 = 0;
goto __pyx_L0;
/* "View.MemoryView":229
*
*
* def __getattr__(self, attr): # <<<<<<<<<<<<<<
* return getattr(self.memview, attr)
*
*/
/* function exit code */
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_1);
__Pyx_XDECREF(__pyx_t_2);
__Pyx_AddTraceback("View.MemoryView.array.__getattr__", __pyx_clineno, __pyx_lineno, __pyx_filename);
__pyx_r = NULL;
__pyx_L0:;
__Pyx_XGIVEREF(__pyx_r);
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "View.MemoryView":232
* return getattr(self.memview, attr)
*
* def __getitem__(self, item): # <<<<<<<<<<<<<<
* return self.memview[item]
*
*/
/* Python wrapper */
static PyObject *__pyx_array___getitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_item); /*proto*/
static PyObject *__pyx_array___getitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_item) {
PyObject *__pyx_r = 0;
__Pyx_RefNannyDeclarations
__Pyx_RefNannySetupContext("__getitem__ (wrapper)", 0);
__pyx_r = __pyx_array_MemoryView_5array_8__getitem__(((struct __pyx_array_obj *)__pyx_v_self), ((PyObject *)__pyx_v_item));
/* function exit code */
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
static PyObject *__pyx_array_MemoryView_5array_8__getitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item) {
PyObject *__pyx_r = NULL;
__Pyx_RefNannyDeclarations
PyObject *__pyx_t_1 = NULL;
PyObject *__pyx_t_2 = NULL;
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
__Pyx_RefNannySetupContext("__getitem__", 0);
/* "View.MemoryView":233
*
* def __getitem__(self, item):
* return self.memview[item] # <<<<<<<<<<<<<<
*
* def __setitem__(self, item, value):
*/
__Pyx_XDECREF(__pyx_r);
__pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_memview); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 233; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
__pyx_t_2 = PyObject_GetItem(__pyx_t_1, __pyx_v_item); if (unlikely(__pyx_t_2 == NULL)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 233; __pyx_clineno = __LINE__; goto __pyx_L1_error;};
__Pyx_GOTREF(__pyx_t_2);
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
__pyx_r = __pyx_t_2;
__pyx_t_2 = 0;
goto __pyx_L0;
/* "View.MemoryView":232
* return getattr(self.memview, attr)
*
* def __getitem__(self, item): # <<<<<<<<<<<<<<
* return self.memview[item]
*
*/
/* function exit code */
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_1);
__Pyx_XDECREF(__pyx_t_2);
__Pyx_AddTraceback("View.MemoryView.array.__getitem__", __pyx_clineno, __pyx_lineno, __pyx_filename);
__pyx_r = NULL;
__pyx_L0:;
__Pyx_XGIVEREF(__pyx_r);
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "View.MemoryView":235
* return self.memview[item]
*
* def __setitem__(self, item, value): # <<<<<<<<<<<<<<
* self.memview[item] = value
*
*/
/* Python wrapper */
static int __pyx_array___setitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_item, PyObject *__pyx_v_value); /*proto*/
static int __pyx_array___setitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_item, PyObject *__pyx_v_value) {
int __pyx_r;
__Pyx_RefNannyDeclarations
__Pyx_RefNannySetupContext("__setitem__ (wrapper)", 0);
__pyx_r = __pyx_array_MemoryView_5array_10__setitem__(((struct __pyx_array_obj *)__pyx_v_self), ((PyObject *)__pyx_v_item), ((PyObject *)__pyx_v_value));
/* function exit code */
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
static int __pyx_array_MemoryView_5array_10__setitem__(struct __pyx_array_obj *__pyx_v_self, PyObject *__pyx_v_item, PyObject *__pyx_v_value) {
int __pyx_r;
__Pyx_RefNannyDeclarations
PyObject *__pyx_t_1 = NULL;
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
__Pyx_RefNannySetupContext("__setitem__", 0);
/* "View.MemoryView":236
*
* def __setitem__(self, item, value):
* self.memview[item] = value # <<<<<<<<<<<<<<
*
*
*/
__pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_memview); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 236; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
if (unlikely(PyObject_SetItem(__pyx_t_1, __pyx_v_item, __pyx_v_value) < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 236; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
/* "View.MemoryView":235
* return self.memview[item]
*
* def __setitem__(self, item, value): # <<<<<<<<<<<<<<
* self.memview[item] = value
*
*/
/* function exit code */
__pyx_r = 0;
goto __pyx_L0;
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_1);
__Pyx_AddTraceback("View.MemoryView.array.__setitem__", __pyx_clineno, __pyx_lineno, __pyx_filename);
__pyx_r = -1;
__pyx_L0:;
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "View.MemoryView":240
*
* @cname("__pyx_array_new")
* cdef array array_cwrapper(tuple shape, Py_ssize_t itemsize, char *format, # <<<<<<<<<<<<<<
* char *mode, char *buf):
* cdef array result
*/
static struct __pyx_array_obj *__pyx_array_new(PyObject *__pyx_v_shape, Py_ssize_t __pyx_v_itemsize, char *__pyx_v_format, char *__pyx_v_mode, char *__pyx_v_buf) {
struct __pyx_array_obj *__pyx_v_result = 0;
struct __pyx_array_obj *__pyx_r = NULL;
__Pyx_RefNannyDeclarations
int __pyx_t_1;
PyObject *__pyx_t_2 = NULL;
PyObject *__pyx_t_3 = NULL;
PyObject *__pyx_t_4 = NULL;
PyObject *__pyx_t_5 = NULL;
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
__Pyx_RefNannySetupContext("array_cwrapper", 0);
/* "View.MemoryView":244
* cdef array result
*
* if buf == NULL: # <<<<<<<<<<<<<<
* result = array(shape, itemsize, format, mode.decode('ASCII'))
* else:
*/
__pyx_t_1 = ((__pyx_v_buf == NULL) != 0);
if (__pyx_t_1) {
/* "View.MemoryView":245
*
* if buf == NULL:
* result = array(shape, itemsize, format, mode.decode('ASCII')) # <<<<<<<<<<<<<<
* else:
* result = array(shape, itemsize, format, mode.decode('ASCII'),
*/
__pyx_t_2 = PyInt_FromSsize_t(__pyx_v_itemsize); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 245; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_2);
__pyx_t_3 = __Pyx_PyBytes_FromString(__pyx_v_format); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 245; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_3);
__pyx_t_4 = __Pyx_decode_c_string(__pyx_v_mode, 0, strlen(__pyx_v_mode), NULL, NULL, PyUnicode_DecodeASCII); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 245; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_4);
__pyx_t_5 = PyTuple_New(4); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 245; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_5);
__Pyx_INCREF(__pyx_v_shape);
PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_v_shape);
__Pyx_GIVEREF(__pyx_v_shape);
PyTuple_SET_ITEM(__pyx_t_5, 1, __pyx_t_2);
__Pyx_GIVEREF(__pyx_t_2);
PyTuple_SET_ITEM(__pyx_t_5, 2, __pyx_t_3);
__Pyx_GIVEREF(__pyx_t_3);
PyTuple_SET_ITEM(__pyx_t_5, 3, __pyx_t_4);
__Pyx_GIVEREF(__pyx_t_4);
__pyx_t_2 = 0;
__pyx_t_3 = 0;
__pyx_t_4 = 0;
__pyx_t_4 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_array_type)), __pyx_t_5, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 245; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_4);
__Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0;
__pyx_v_result = ((struct __pyx_array_obj *)__pyx_t_4);
__pyx_t_4 = 0;
goto __pyx_L3;
}
/*else*/ {
/* "View.MemoryView":247
* result = array(shape, itemsize, format, mode.decode('ASCII'))
* else:
* result = array(shape, itemsize, format, mode.decode('ASCII'), # <<<<<<<<<<<<<<
* allocate_buffer=False)
* result.data = buf
*/
__pyx_t_4 = PyInt_FromSsize_t(__pyx_v_itemsize); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 247; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_4);
__pyx_t_5 = __Pyx_PyBytes_FromString(__pyx_v_format); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 247; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_5);
__pyx_t_3 = __Pyx_decode_c_string(__pyx_v_mode, 0, strlen(__pyx_v_mode), NULL, NULL, PyUnicode_DecodeASCII); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 247; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_3);
__pyx_t_2 = PyTuple_New(4); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 247; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_2);
__Pyx_INCREF(__pyx_v_shape);
PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_v_shape);
__Pyx_GIVEREF(__pyx_v_shape);
PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_4);
__Pyx_GIVEREF(__pyx_t_4);
PyTuple_SET_ITEM(__pyx_t_2, 2, __pyx_t_5);
__Pyx_GIVEREF(__pyx_t_5);
PyTuple_SET_ITEM(__pyx_t_2, 3, __pyx_t_3);
__Pyx_GIVEREF(__pyx_t_3);
__pyx_t_4 = 0;
__pyx_t_5 = 0;
__pyx_t_3 = 0;
__pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 247; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_3);
/* "View.MemoryView":248
* else:
* result = array(shape, itemsize, format, mode.decode('ASCII'),
* allocate_buffer=False) # <<<<<<<<<<<<<<
* result.data = buf
*
*/
if (PyDict_SetItem(__pyx_t_3, __pyx_n_s_allocate_buffer, Py_False) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 247; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
/* "View.MemoryView":247
* result = array(shape, itemsize, format, mode.decode('ASCII'))
* else:
* result = array(shape, itemsize, format, mode.decode('ASCII'), # <<<<<<<<<<<<<<
* allocate_buffer=False)
* result.data = buf
*/
__pyx_t_5 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_array_type)), __pyx_t_2, __pyx_t_3); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 247; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_5);
__Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0;
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
__pyx_v_result = ((struct __pyx_array_obj *)__pyx_t_5);
__pyx_t_5 = 0;
/* "View.MemoryView":249
* result = array(shape, itemsize, format, mode.decode('ASCII'),
* allocate_buffer=False)
* result.data = buf # <<<<<<<<<<<<<<
*
* return result
*/
__pyx_v_result->data = __pyx_v_buf;
}
__pyx_L3:;
/* "View.MemoryView":251
* result.data = buf
*
* return result # <<<<<<<<<<<<<<
*
*
*/
__Pyx_XDECREF(((PyObject *)__pyx_r));
__Pyx_INCREF(((PyObject *)__pyx_v_result));
__pyx_r = __pyx_v_result;
goto __pyx_L0;
/* "View.MemoryView":240
*
* @cname("__pyx_array_new")
* cdef array array_cwrapper(tuple shape, Py_ssize_t itemsize, char *format, # <<<<<<<<<<<<<<
* char *mode, char *buf):
* cdef array result
*/
/* function exit code */
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_2);
__Pyx_XDECREF(__pyx_t_3);
__Pyx_XDECREF(__pyx_t_4);
__Pyx_XDECREF(__pyx_t_5);
__Pyx_AddTraceback("View.MemoryView.array_cwrapper", __pyx_clineno, __pyx_lineno, __pyx_filename);
__pyx_r = 0;
__pyx_L0:;
__Pyx_XDECREF((PyObject *)__pyx_v_result);
__Pyx_XGIVEREF((PyObject *)__pyx_r);
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "View.MemoryView":277
* cdef class Enum(object):
* cdef object name
* def __init__(self, name): # <<<<<<<<<<<<<<
* self.name = name
* def __repr__(self):
*/
/* Python wrapper */
static int __pyx_MemviewEnum___init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/
static int __pyx_MemviewEnum___init__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) {
PyObject *__pyx_v_name = 0;
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
int __pyx_r;
__Pyx_RefNannyDeclarations
__Pyx_RefNannySetupContext("__init__ (wrapper)", 0);
{
static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_name,0};
PyObject* values[1] = {0};
if (unlikely(__pyx_kwds)) {
Py_ssize_t kw_args;
const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args);
switch (pos_args) {
case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0);
case 0: break;
default: goto __pyx_L5_argtuple_error;
}
kw_args = PyDict_Size(__pyx_kwds);
switch (pos_args) {
case 0:
if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_name)) != 0)) kw_args--;
else goto __pyx_L5_argtuple_error;
}
if (unlikely(kw_args > 0)) {
if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__init__") < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 277; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
}
} else if (PyTuple_GET_SIZE(__pyx_args) != 1) {
goto __pyx_L5_argtuple_error;
} else {
values[0] = PyTuple_GET_ITEM(__pyx_args, 0);
}
__pyx_v_name = values[0];
}
goto __pyx_L4_argument_unpacking_done;
__pyx_L5_argtuple_error:;
__Pyx_RaiseArgtupleInvalid("__init__", 1, 1, 1, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 277; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
__pyx_L3_error:;
__Pyx_AddTraceback("View.MemoryView.Enum.__init__", __pyx_clineno, __pyx_lineno, __pyx_filename);
__Pyx_RefNannyFinishContext();
return -1;
__pyx_L4_argument_unpacking_done:;
__pyx_r = __pyx_MemviewEnum_MemoryView_4Enum___init__(((struct __pyx_MemviewEnum_obj *)__pyx_v_self), __pyx_v_name);
/* function exit code */
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
static int __pyx_MemviewEnum_MemoryView_4Enum___init__(struct __pyx_MemviewEnum_obj *__pyx_v_self, PyObject *__pyx_v_name) {
int __pyx_r;
__Pyx_RefNannyDeclarations
__Pyx_RefNannySetupContext("__init__", 0);
/* "View.MemoryView":278
* cdef object name
* def __init__(self, name):
* self.name = name # <<<<<<<<<<<<<<
* def __repr__(self):
* return self.name
*/
__Pyx_INCREF(__pyx_v_name);
__Pyx_GIVEREF(__pyx_v_name);
__Pyx_GOTREF(__pyx_v_self->name);
__Pyx_DECREF(__pyx_v_self->name);
__pyx_v_self->name = __pyx_v_name;
/* "View.MemoryView":277
* cdef class Enum(object):
* cdef object name
* def __init__(self, name): # <<<<<<<<<<<<<<
* self.name = name
* def __repr__(self):
*/
/* function exit code */
__pyx_r = 0;
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "View.MemoryView":279
* def __init__(self, name):
* self.name = name
* def __repr__(self): # <<<<<<<<<<<<<<
* return self.name
*
*/
/* Python wrapper */
static PyObject *__pyx_MemviewEnum___repr__(PyObject *__pyx_v_self); /*proto*/
static PyObject *__pyx_MemviewEnum___repr__(PyObject *__pyx_v_self) {
PyObject *__pyx_r = 0;
__Pyx_RefNannyDeclarations
__Pyx_RefNannySetupContext("__repr__ (wrapper)", 0);
__pyx_r = __pyx_MemviewEnum_MemoryView_4Enum_2__repr__(((struct __pyx_MemviewEnum_obj *)__pyx_v_self));
/* function exit code */
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
static PyObject *__pyx_MemviewEnum_MemoryView_4Enum_2__repr__(struct __pyx_MemviewEnum_obj *__pyx_v_self) {
PyObject *__pyx_r = NULL;
__Pyx_RefNannyDeclarations
__Pyx_RefNannySetupContext("__repr__", 0);
/* "View.MemoryView":280
* self.name = name
* def __repr__(self):
* return self.name # <<<<<<<<<<<<<<
*
* cdef generic = Enum("<strided and direct or indirect>")
*/
__Pyx_XDECREF(__pyx_r);
__Pyx_INCREF(__pyx_v_self->name);
__pyx_r = __pyx_v_self->name;
goto __pyx_L0;
/* "View.MemoryView":279
* def __init__(self, name):
* self.name = name
* def __repr__(self): # <<<<<<<<<<<<<<
* return self.name
*
*/
/* function exit code */
__pyx_L0:;
__Pyx_XGIVEREF(__pyx_r);
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "View.MemoryView":294
*
* @cname('__pyx_align_pointer')
* cdef void *align_pointer(void *memory, size_t alignment) nogil: # <<<<<<<<<<<<<<
* "Align pointer memory on a given boundary"
* cdef Py_intptr_t aligned_p = <Py_intptr_t> memory
*/
static void *__pyx_align_pointer(void *__pyx_v_memory, size_t __pyx_v_alignment) {
Py_intptr_t __pyx_v_aligned_p;
size_t __pyx_v_offset;
void *__pyx_r;
int __pyx_t_1;
/* "View.MemoryView":296
* cdef void *align_pointer(void *memory, size_t alignment) nogil:
* "Align pointer memory on a given boundary"
* cdef Py_intptr_t aligned_p = <Py_intptr_t> memory # <<<<<<<<<<<<<<
* cdef size_t offset
*
*/
__pyx_v_aligned_p = ((Py_intptr_t)__pyx_v_memory);
/* "View.MemoryView":300
*
* with cython.cdivision(True):
* offset = aligned_p % alignment # <<<<<<<<<<<<<<
*
* if offset > 0:
*/
__pyx_v_offset = (__pyx_v_aligned_p % __pyx_v_alignment);
/* "View.MemoryView":302
* offset = aligned_p % alignment
*
* if offset > 0: # <<<<<<<<<<<<<<
* aligned_p += alignment - offset
*
*/
__pyx_t_1 = ((__pyx_v_offset > 0) != 0);
if (__pyx_t_1) {
/* "View.MemoryView":303
*
* if offset > 0:
* aligned_p += alignment - offset # <<<<<<<<<<<<<<
*
* return <void *> aligned_p
*/
__pyx_v_aligned_p = (__pyx_v_aligned_p + (__pyx_v_alignment - __pyx_v_offset));
goto __pyx_L3;
}
__pyx_L3:;
/* "View.MemoryView":305
* aligned_p += alignment - offset
*
* return <void *> aligned_p # <<<<<<<<<<<<<<
*
* @cname('__pyx_memoryview')
*/
__pyx_r = ((void *)__pyx_v_aligned_p);
goto __pyx_L0;
/* "View.MemoryView":294
*
* @cname('__pyx_align_pointer')
* cdef void *align_pointer(void *memory, size_t alignment) nogil: # <<<<<<<<<<<<<<
* "Align pointer memory on a given boundary"
* cdef Py_intptr_t aligned_p = <Py_intptr_t> memory
*/
/* function exit code */
__pyx_L0:;
return __pyx_r;
}
/* "View.MemoryView":323
* cdef __Pyx_TypeInfo *typeinfo
*
* def __cinit__(memoryview self, object obj, int flags, bint dtype_is_object=False): # <<<<<<<<<<<<<<
* self.obj = obj
* self.flags = flags
*/
/* Python wrapper */
static int __pyx_memoryview___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds); /*proto*/
static int __pyx_memoryview___cinit__(PyObject *__pyx_v_self, PyObject *__pyx_args, PyObject *__pyx_kwds) {
PyObject *__pyx_v_obj = 0;
int __pyx_v_flags;
int __pyx_v_dtype_is_object;
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
int __pyx_r;
__Pyx_RefNannyDeclarations
__Pyx_RefNannySetupContext("__cinit__ (wrapper)", 0);
{
static PyObject **__pyx_pyargnames[] = {&__pyx_n_s_obj,&__pyx_n_s_flags,&__pyx_n_s_dtype_is_object,0};
PyObject* values[3] = {0,0,0};
if (unlikely(__pyx_kwds)) {
Py_ssize_t kw_args;
const Py_ssize_t pos_args = PyTuple_GET_SIZE(__pyx_args);
switch (pos_args) {
case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2);
case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1);
case 1: values[0] = PyTuple_GET_ITEM(__pyx_args, 0);
case 0: break;
default: goto __pyx_L5_argtuple_error;
}
kw_args = PyDict_Size(__pyx_kwds);
switch (pos_args) {
case 0:
if (likely((values[0] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_obj)) != 0)) kw_args--;
else goto __pyx_L5_argtuple_error;
case 1:
if (likely((values[1] = PyDict_GetItem(__pyx_kwds, __pyx_n_s_flags)) != 0)) kw_args--;
else {
__Pyx_RaiseArgtupleInvalid("__cinit__", 0, 2, 3, 1); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 323; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
}
case 2:
if (kw_args > 0) {
PyObject* value = PyDict_GetItem(__pyx_kwds, __pyx_n_s_dtype_is_object);
if (value) { values[2] = value; kw_args--; }
}
}
if (unlikely(kw_args > 0)) {
if (unlikely(__Pyx_ParseOptionalKeywords(__pyx_kwds, __pyx_pyargnames, 0, values, pos_args, "__cinit__") < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 323; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
}
} else {
switch (PyTuple_GET_SIZE(__pyx_args)) {
case 3: values[2] = PyTuple_GET_ITEM(__pyx_args, 2);
case 2: values[1] = PyTuple_GET_ITEM(__pyx_args, 1);
values[0] = PyTuple_GET_ITEM(__pyx_args, 0);
break;
default: goto __pyx_L5_argtuple_error;
}
}
__pyx_v_obj = values[0];
__pyx_v_flags = __Pyx_PyInt_As_int(values[1]); if (unlikely((__pyx_v_flags == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 323; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
if (values[2]) {
__pyx_v_dtype_is_object = __Pyx_PyObject_IsTrue(values[2]); if (unlikely((__pyx_v_dtype_is_object == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 323; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
} else {
__pyx_v_dtype_is_object = ((int)0);
}
}
goto __pyx_L4_argument_unpacking_done;
__pyx_L5_argtuple_error:;
__Pyx_RaiseArgtupleInvalid("__cinit__", 0, 2, 3, PyTuple_GET_SIZE(__pyx_args)); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 323; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
__pyx_L3_error:;
__Pyx_AddTraceback("View.MemoryView.memoryview.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename);
__Pyx_RefNannyFinishContext();
return -1;
__pyx_L4_argument_unpacking_done:;
__pyx_r = __pyx_memoryview_MemoryView_10memoryview___cinit__(((struct __pyx_memoryview_obj *)__pyx_v_self), __pyx_v_obj, __pyx_v_flags, __pyx_v_dtype_is_object);
/* function exit code */
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
static int __pyx_memoryview_MemoryView_10memoryview___cinit__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_obj, int __pyx_v_flags, int __pyx_v_dtype_is_object) {
int __pyx_r;
__Pyx_RefNannyDeclarations
int __pyx_t_1;
int __pyx_t_2;
int __pyx_t_3;
int __pyx_t_4;
PyObject *__pyx_t_5 = NULL;
PyObject *__pyx_t_6 = NULL;
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
__Pyx_RefNannySetupContext("__cinit__", 0);
/* "View.MemoryView":324
*
* def __cinit__(memoryview self, object obj, int flags, bint dtype_is_object=False):
* self.obj = obj # <<<<<<<<<<<<<<
* self.flags = flags
* if type(self) is memoryview or obj is not None:
*/
__Pyx_INCREF(__pyx_v_obj);
__Pyx_GIVEREF(__pyx_v_obj);
__Pyx_GOTREF(__pyx_v_self->obj);
__Pyx_DECREF(__pyx_v_self->obj);
__pyx_v_self->obj = __pyx_v_obj;
/* "View.MemoryView":325
* def __cinit__(memoryview self, object obj, int flags, bint dtype_is_object=False):
* self.obj = obj
* self.flags = flags # <<<<<<<<<<<<<<
* if type(self) is memoryview or obj is not None:
* __Pyx_GetBuffer(obj, &self.view, flags)
*/
__pyx_v_self->flags = __pyx_v_flags;
/* "View.MemoryView":326
* self.obj = obj
* self.flags = flags
* if type(self) is memoryview or obj is not None: # <<<<<<<<<<<<<<
* __Pyx_GetBuffer(obj, &self.view, flags)
* if <PyObject *> self.view.obj == NULL:
*/
__pyx_t_1 = (((PyObject *)Py_TYPE(((PyObject *)__pyx_v_self))) == ((PyObject *)((PyObject *)__pyx_memoryview_type)));
if (!(__pyx_t_1 != 0)) {
__pyx_t_2 = (__pyx_v_obj != Py_None);
__pyx_t_3 = (__pyx_t_2 != 0);
} else {
__pyx_t_3 = (__pyx_t_1 != 0);
}
if (__pyx_t_3) {
/* "View.MemoryView":327
* self.flags = flags
* if type(self) is memoryview or obj is not None:
* __Pyx_GetBuffer(obj, &self.view, flags) # <<<<<<<<<<<<<<
* if <PyObject *> self.view.obj == NULL:
* (<__pyx_buffer *> &self.view).obj = Py_None
*/
__pyx_t_4 = __Pyx_GetBuffer(__pyx_v_obj, (&__pyx_v_self->view), __pyx_v_flags); if (unlikely(__pyx_t_4 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 327; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
/* "View.MemoryView":328
* if type(self) is memoryview or obj is not None:
* __Pyx_GetBuffer(obj, &self.view, flags)
* if <PyObject *> self.view.obj == NULL: # <<<<<<<<<<<<<<
* (<__pyx_buffer *> &self.view).obj = Py_None
* Py_INCREF(Py_None)
*/
__pyx_t_3 = ((((PyObject *)__pyx_v_self->view.obj) == NULL) != 0);
if (__pyx_t_3) {
/* "View.MemoryView":329
* __Pyx_GetBuffer(obj, &self.view, flags)
* if <PyObject *> self.view.obj == NULL:
* (<__pyx_buffer *> &self.view).obj = Py_None # <<<<<<<<<<<<<<
* Py_INCREF(Py_None)
*
*/
((Py_buffer *)(&__pyx_v_self->view))->obj = Py_None;
/* "View.MemoryView":330
* if <PyObject *> self.view.obj == NULL:
* (<__pyx_buffer *> &self.view).obj = Py_None
* Py_INCREF(Py_None) # <<<<<<<<<<<<<<
*
* self.lock = PyThread_allocate_lock()
*/
Py_INCREF(Py_None);
goto __pyx_L4;
}
__pyx_L4:;
goto __pyx_L3;
}
__pyx_L3:;
/* "View.MemoryView":332
* Py_INCREF(Py_None)
*
* self.lock = PyThread_allocate_lock() # <<<<<<<<<<<<<<
* if self.lock == NULL:
* raise MemoryError
*/
__pyx_v_self->lock = PyThread_allocate_lock();
/* "View.MemoryView":333
*
* self.lock = PyThread_allocate_lock()
* if self.lock == NULL: # <<<<<<<<<<<<<<
* raise MemoryError
*
*/
__pyx_t_3 = ((__pyx_v_self->lock == NULL) != 0);
if (__pyx_t_3) {
/* "View.MemoryView":334
* self.lock = PyThread_allocate_lock()
* if self.lock == NULL:
* raise MemoryError # <<<<<<<<<<<<<<
*
* if flags & PyBUF_FORMAT:
*/
PyErr_NoMemory(); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 334; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
}
/* "View.MemoryView":336
* raise MemoryError
*
* if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<<
* self.dtype_is_object = self.view.format == b'O'
* else:
*/
__pyx_t_3 = ((__pyx_v_flags & PyBUF_FORMAT) != 0);
if (__pyx_t_3) {
/* "View.MemoryView":337
*
* if flags & PyBUF_FORMAT:
* self.dtype_is_object = self.view.format == b'O' # <<<<<<<<<<<<<<
* else:
* self.dtype_is_object = dtype_is_object
*/
__pyx_t_5 = __Pyx_PyBytes_FromString(__pyx_v_self->view.format); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 337; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_5);
__pyx_t_6 = PyObject_RichCompare(__pyx_t_5, __pyx_n_b_O, Py_EQ); __Pyx_XGOTREF(__pyx_t_6); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 337; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0;
__pyx_t_3 = __Pyx_PyObject_IsTrue(__pyx_t_6); if (unlikely((__pyx_t_3 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 337; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0;
__pyx_v_self->dtype_is_object = __pyx_t_3;
goto __pyx_L6;
}
/*else*/ {
/* "View.MemoryView":339
* self.dtype_is_object = self.view.format == b'O'
* else:
* self.dtype_is_object = dtype_is_object # <<<<<<<<<<<<<<
*
* self.acquisition_count_aligned_p = <__pyx_atomic_int *> align_pointer(
*/
__pyx_v_self->dtype_is_object = __pyx_v_dtype_is_object;
}
__pyx_L6:;
/* "View.MemoryView":341
* self.dtype_is_object = dtype_is_object
*
* self.acquisition_count_aligned_p = <__pyx_atomic_int *> align_pointer( # <<<<<<<<<<<<<<
* <void *> &self.acquisition_count[0], sizeof(__pyx_atomic_int))
* self.typeinfo = NULL
*/
__pyx_v_self->acquisition_count_aligned_p = ((__pyx_atomic_int *)__pyx_align_pointer(((void *)(&(__pyx_v_self->acquisition_count[0]))), (sizeof(__pyx_atomic_int))));
/* "View.MemoryView":343
* self.acquisition_count_aligned_p = <__pyx_atomic_int *> align_pointer(
* <void *> &self.acquisition_count[0], sizeof(__pyx_atomic_int))
* self.typeinfo = NULL # <<<<<<<<<<<<<<
*
* def __dealloc__(memoryview self):
*/
__pyx_v_self->typeinfo = NULL;
/* "View.MemoryView":323
* cdef __Pyx_TypeInfo *typeinfo
*
* def __cinit__(memoryview self, object obj, int flags, bint dtype_is_object=False): # <<<<<<<<<<<<<<
* self.obj = obj
* self.flags = flags
*/
/* function exit code */
__pyx_r = 0;
goto __pyx_L0;
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_5);
__Pyx_XDECREF(__pyx_t_6);
__Pyx_AddTraceback("View.MemoryView.memoryview.__cinit__", __pyx_clineno, __pyx_lineno, __pyx_filename);
__pyx_r = -1;
__pyx_L0:;
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "View.MemoryView":345
* self.typeinfo = NULL
*
* def __dealloc__(memoryview self): # <<<<<<<<<<<<<<
* if self.obj is not None:
* __Pyx_ReleaseBuffer(&self.view)
*/
/* Python wrapper */
static void __pyx_memoryview___dealloc__(PyObject *__pyx_v_self); /*proto*/
static void __pyx_memoryview___dealloc__(PyObject *__pyx_v_self) {
__Pyx_RefNannyDeclarations
__Pyx_RefNannySetupContext("__dealloc__ (wrapper)", 0);
__pyx_memoryview_MemoryView_10memoryview_2__dealloc__(((struct __pyx_memoryview_obj *)__pyx_v_self));
/* function exit code */
__Pyx_RefNannyFinishContext();
}
static void __pyx_memoryview_MemoryView_10memoryview_2__dealloc__(struct __pyx_memoryview_obj *__pyx_v_self) {
__Pyx_RefNannyDeclarations
int __pyx_t_1;
int __pyx_t_2;
__Pyx_RefNannySetupContext("__dealloc__", 0);
/* "View.MemoryView":346
*
* def __dealloc__(memoryview self):
* if self.obj is not None: # <<<<<<<<<<<<<<
* __Pyx_ReleaseBuffer(&self.view)
*
*/
__pyx_t_1 = (__pyx_v_self->obj != Py_None);
__pyx_t_2 = (__pyx_t_1 != 0);
if (__pyx_t_2) {
/* "View.MemoryView":347
* def __dealloc__(memoryview self):
* if self.obj is not None:
* __Pyx_ReleaseBuffer(&self.view) # <<<<<<<<<<<<<<
*
* if self.lock != NULL:
*/
__Pyx_ReleaseBuffer((&__pyx_v_self->view));
goto __pyx_L3;
}
__pyx_L3:;
/* "View.MemoryView":349
* __Pyx_ReleaseBuffer(&self.view)
*
* if self.lock != NULL: # <<<<<<<<<<<<<<
* PyThread_free_lock(self.lock)
*
*/
__pyx_t_2 = ((__pyx_v_self->lock != NULL) != 0);
if (__pyx_t_2) {
/* "View.MemoryView":350
*
* if self.lock != NULL:
* PyThread_free_lock(self.lock) # <<<<<<<<<<<<<<
*
* cdef char *get_item_pointer(memoryview self, object index) except NULL:
*/
PyThread_free_lock(__pyx_v_self->lock);
goto __pyx_L4;
}
__pyx_L4:;
/* "View.MemoryView":345
* self.typeinfo = NULL
*
* def __dealloc__(memoryview self): # <<<<<<<<<<<<<<
* if self.obj is not None:
* __Pyx_ReleaseBuffer(&self.view)
*/
/* function exit code */
__Pyx_RefNannyFinishContext();
}
/* "View.MemoryView":352
* PyThread_free_lock(self.lock)
*
* cdef char *get_item_pointer(memoryview self, object index) except NULL: # <<<<<<<<<<<<<<
* cdef Py_ssize_t dim
* cdef char *itemp = <char *> self.view.buf
*/
static char *__pyx_memoryview_get_item_pointer(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index) {
Py_ssize_t __pyx_v_dim;
char *__pyx_v_itemp;
PyObject *__pyx_v_idx = NULL;
char *__pyx_r;
__Pyx_RefNannyDeclarations
Py_ssize_t __pyx_t_1;
PyObject *__pyx_t_2 = NULL;
Py_ssize_t __pyx_t_3;
PyObject *(*__pyx_t_4)(PyObject *);
PyObject *__pyx_t_5 = NULL;
Py_ssize_t __pyx_t_6;
char *__pyx_t_7;
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
__Pyx_RefNannySetupContext("get_item_pointer", 0);
/* "View.MemoryView":354
* cdef char *get_item_pointer(memoryview self, object index) except NULL:
* cdef Py_ssize_t dim
* cdef char *itemp = <char *> self.view.buf # <<<<<<<<<<<<<<
*
* for dim, idx in enumerate(index):
*/
__pyx_v_itemp = ((char *)__pyx_v_self->view.buf);
/* "View.MemoryView":356
* cdef char *itemp = <char *> self.view.buf
*
* for dim, idx in enumerate(index): # <<<<<<<<<<<<<<
* itemp = pybuffer_index(&self.view, itemp, idx, dim)
*
*/
__pyx_t_1 = 0;
if (PyList_CheckExact(__pyx_v_index) || PyTuple_CheckExact(__pyx_v_index)) {
__pyx_t_2 = __pyx_v_index; __Pyx_INCREF(__pyx_t_2); __pyx_t_3 = 0;
__pyx_t_4 = NULL;
} else {
__pyx_t_3 = -1; __pyx_t_2 = PyObject_GetIter(__pyx_v_index); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 356; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_2);
__pyx_t_4 = Py_TYPE(__pyx_t_2)->tp_iternext;
}
for (;;) {
if (!__pyx_t_4 && PyList_CheckExact(__pyx_t_2)) {
if (__pyx_t_3 >= PyList_GET_SIZE(__pyx_t_2)) break;
#if CYTHON_COMPILING_IN_CPYTHON
__pyx_t_5 = PyList_GET_ITEM(__pyx_t_2, __pyx_t_3); __Pyx_INCREF(__pyx_t_5); __pyx_t_3++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 356; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
#else
__pyx_t_5 = PySequence_ITEM(__pyx_t_2, __pyx_t_3); __pyx_t_3++; if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 356; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
#endif
} else if (!__pyx_t_4 && PyTuple_CheckExact(__pyx_t_2)) {
if (__pyx_t_3 >= PyTuple_GET_SIZE(__pyx_t_2)) break;
#if CYTHON_COMPILING_IN_CPYTHON
__pyx_t_5 = PyTuple_GET_ITEM(__pyx_t_2, __pyx_t_3); __Pyx_INCREF(__pyx_t_5); __pyx_t_3++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 356; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
#else
__pyx_t_5 = PySequence_ITEM(__pyx_t_2, __pyx_t_3); __pyx_t_3++; if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 356; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
#endif
} else {
__pyx_t_5 = __pyx_t_4(__pyx_t_2);
if (unlikely(!__pyx_t_5)) {
PyObject* exc_type = PyErr_Occurred();
if (exc_type) {
if (likely(exc_type == PyExc_StopIteration || PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear();
else {__pyx_filename = __pyx_f[2]; __pyx_lineno = 356; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
}
break;
}
__Pyx_GOTREF(__pyx_t_5);
}
__Pyx_XDECREF_SET(__pyx_v_idx, __pyx_t_5);
__pyx_t_5 = 0;
__pyx_v_dim = __pyx_t_1;
__pyx_t_1 = (__pyx_t_1 + 1);
/* "View.MemoryView":357
*
* for dim, idx in enumerate(index):
* itemp = pybuffer_index(&self.view, itemp, idx, dim) # <<<<<<<<<<<<<<
*
* return itemp
*/
__pyx_t_6 = __Pyx_PyIndex_AsSsize_t(__pyx_v_idx); if (unlikely((__pyx_t_6 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 357; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_t_7 = __pyx_pybuffer_index((&__pyx_v_self->view), __pyx_v_itemp, __pyx_t_6, __pyx_v_dim); if (unlikely(__pyx_t_7 == NULL)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 357; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_v_itemp = __pyx_t_7;
}
__Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0;
/* "View.MemoryView":359
* itemp = pybuffer_index(&self.view, itemp, idx, dim)
*
* return itemp # <<<<<<<<<<<<<<
*
*
*/
__pyx_r = __pyx_v_itemp;
goto __pyx_L0;
/* "View.MemoryView":352
* PyThread_free_lock(self.lock)
*
* cdef char *get_item_pointer(memoryview self, object index) except NULL: # <<<<<<<<<<<<<<
* cdef Py_ssize_t dim
* cdef char *itemp = <char *> self.view.buf
*/
/* function exit code */
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_2);
__Pyx_XDECREF(__pyx_t_5);
__Pyx_AddTraceback("View.MemoryView.memoryview.get_item_pointer", __pyx_clineno, __pyx_lineno, __pyx_filename);
__pyx_r = NULL;
__pyx_L0:;
__Pyx_XDECREF(__pyx_v_idx);
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "View.MemoryView":362
*
*
* def __getitem__(memoryview self, object index): # <<<<<<<<<<<<<<
* if index is Ellipsis:
* return self
*/
/* Python wrapper */
static PyObject *__pyx_memoryview___getitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_index); /*proto*/
static PyObject *__pyx_memoryview___getitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_index) {
PyObject *__pyx_r = 0;
__Pyx_RefNannyDeclarations
__Pyx_RefNannySetupContext("__getitem__ (wrapper)", 0);
__pyx_r = __pyx_memoryview_MemoryView_10memoryview_4__getitem__(((struct __pyx_memoryview_obj *)__pyx_v_self), ((PyObject *)__pyx_v_index));
/* function exit code */
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
static PyObject *__pyx_memoryview_MemoryView_10memoryview_4__getitem__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index) {
PyObject *__pyx_v_have_slices = NULL;
PyObject *__pyx_v_indices = NULL;
char *__pyx_v_itemp;
PyObject *__pyx_r = NULL;
__Pyx_RefNannyDeclarations
int __pyx_t_1;
int __pyx_t_2;
PyObject *__pyx_t_3 = NULL;
PyObject *__pyx_t_4 = NULL;
PyObject *__pyx_t_5 = NULL;
char *__pyx_t_6;
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
__Pyx_RefNannySetupContext("__getitem__", 0);
/* "View.MemoryView":363
*
* def __getitem__(memoryview self, object index):
* if index is Ellipsis: # <<<<<<<<<<<<<<
* return self
*
*/
__pyx_t_1 = (__pyx_v_index == __pyx_builtin_Ellipsis);
__pyx_t_2 = (__pyx_t_1 != 0);
if (__pyx_t_2) {
/* "View.MemoryView":364
* def __getitem__(memoryview self, object index):
* if index is Ellipsis:
* return self # <<<<<<<<<<<<<<
*
* have_slices, indices = _unellipsify(index, self.view.ndim)
*/
__Pyx_XDECREF(__pyx_r);
__Pyx_INCREF(((PyObject *)__pyx_v_self));
__pyx_r = ((PyObject *)__pyx_v_self);
goto __pyx_L0;
}
/* "View.MemoryView":366
* return self
*
* have_slices, indices = _unellipsify(index, self.view.ndim) # <<<<<<<<<<<<<<
*
* cdef char *itemp
*/
__pyx_t_3 = _unellipsify(__pyx_v_index, __pyx_v_self->view.ndim); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 366; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_3);
if (likely(__pyx_t_3 != Py_None)) {
PyObject* sequence = __pyx_t_3;
#if CYTHON_COMPILING_IN_CPYTHON
Py_ssize_t size = Py_SIZE(sequence);
#else
Py_ssize_t size = PySequence_Size(sequence);
#endif
if (unlikely(size != 2)) {
if (size > 2) __Pyx_RaiseTooManyValuesError(2);
else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size);
{__pyx_filename = __pyx_f[2]; __pyx_lineno = 366; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
}
#if CYTHON_COMPILING_IN_CPYTHON
__pyx_t_4 = PyTuple_GET_ITEM(sequence, 0);
__pyx_t_5 = PyTuple_GET_ITEM(sequence, 1);
__Pyx_INCREF(__pyx_t_4);
__Pyx_INCREF(__pyx_t_5);
#else
__pyx_t_4 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 366; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_4);
__pyx_t_5 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 366; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_5);
#endif
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
} else {
__Pyx_RaiseNoneNotIterableError(); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 366; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
}
__pyx_v_have_slices = __pyx_t_4;
__pyx_t_4 = 0;
__pyx_v_indices = __pyx_t_5;
__pyx_t_5 = 0;
/* "View.MemoryView":369
*
* cdef char *itemp
* if have_slices: # <<<<<<<<<<<<<<
* return memview_slice(self, indices)
* else:
*/
__pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_v_have_slices); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 369; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
if (__pyx_t_2) {
/* "View.MemoryView":370
* cdef char *itemp
* if have_slices:
* return memview_slice(self, indices) # <<<<<<<<<<<<<<
* else:
* itemp = self.get_item_pointer(indices)
*/
__Pyx_XDECREF(__pyx_r);
__pyx_t_3 = ((PyObject *)__pyx_memview_slice(__pyx_v_self, __pyx_v_indices)); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 370; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_3);
__pyx_r = __pyx_t_3;
__pyx_t_3 = 0;
goto __pyx_L0;
}
/*else*/ {
/* "View.MemoryView":372
* return memview_slice(self, indices)
* else:
* itemp = self.get_item_pointer(indices) # <<<<<<<<<<<<<<
* return self.convert_item_to_object(itemp)
*
*/
__pyx_t_6 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->get_item_pointer(__pyx_v_self, __pyx_v_indices); if (unlikely(__pyx_t_6 == NULL)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 372; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_v_itemp = __pyx_t_6;
/* "View.MemoryView":373
* else:
* itemp = self.get_item_pointer(indices)
* return self.convert_item_to_object(itemp) # <<<<<<<<<<<<<<
*
* def __setitem__(memoryview self, object index, object value):
*/
__Pyx_XDECREF(__pyx_r);
__pyx_t_3 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->convert_item_to_object(__pyx_v_self, __pyx_v_itemp); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 373; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_3);
__pyx_r = __pyx_t_3;
__pyx_t_3 = 0;
goto __pyx_L0;
}
/* "View.MemoryView":362
*
*
* def __getitem__(memoryview self, object index): # <<<<<<<<<<<<<<
* if index is Ellipsis:
* return self
*/
/* function exit code */
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_3);
__Pyx_XDECREF(__pyx_t_4);
__Pyx_XDECREF(__pyx_t_5);
__Pyx_AddTraceback("View.MemoryView.memoryview.__getitem__", __pyx_clineno, __pyx_lineno, __pyx_filename);
__pyx_r = NULL;
__pyx_L0:;
__Pyx_XDECREF(__pyx_v_have_slices);
__Pyx_XDECREF(__pyx_v_indices);
__Pyx_XGIVEREF(__pyx_r);
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "View.MemoryView":375
* return self.convert_item_to_object(itemp)
*
* def __setitem__(memoryview self, object index, object value): # <<<<<<<<<<<<<<
* have_slices, index = _unellipsify(index, self.view.ndim)
*
*/
/* Python wrapper */
static int __pyx_memoryview___setitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value); /*proto*/
static int __pyx_memoryview___setitem__(PyObject *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value) {
int __pyx_r;
__Pyx_RefNannyDeclarations
__Pyx_RefNannySetupContext("__setitem__ (wrapper)", 0);
__pyx_r = __pyx_memoryview_MemoryView_10memoryview_6__setitem__(((struct __pyx_memoryview_obj *)__pyx_v_self), ((PyObject *)__pyx_v_index), ((PyObject *)__pyx_v_value));
/* function exit code */
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
static int __pyx_memoryview_MemoryView_10memoryview_6__setitem__(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value) {
PyObject *__pyx_v_have_slices = NULL;
PyObject *__pyx_v_obj = NULL;
int __pyx_r;
__Pyx_RefNannyDeclarations
PyObject *__pyx_t_1 = NULL;
PyObject *__pyx_t_2 = NULL;
PyObject *__pyx_t_3 = NULL;
int __pyx_t_4;
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
__Pyx_RefNannySetupContext("__setitem__", 0);
__Pyx_INCREF(__pyx_v_index);
/* "View.MemoryView":376
*
* def __setitem__(memoryview self, object index, object value):
* have_slices, index = _unellipsify(index, self.view.ndim) # <<<<<<<<<<<<<<
*
* if have_slices:
*/
__pyx_t_1 = _unellipsify(__pyx_v_index, __pyx_v_self->view.ndim); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 376; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
if (likely(__pyx_t_1 != Py_None)) {
PyObject* sequence = __pyx_t_1;
#if CYTHON_COMPILING_IN_CPYTHON
Py_ssize_t size = Py_SIZE(sequence);
#else
Py_ssize_t size = PySequence_Size(sequence);
#endif
if (unlikely(size != 2)) {
if (size > 2) __Pyx_RaiseTooManyValuesError(2);
else if (size >= 0) __Pyx_RaiseNeedMoreValuesError(size);
{__pyx_filename = __pyx_f[2]; __pyx_lineno = 376; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
}
#if CYTHON_COMPILING_IN_CPYTHON
__pyx_t_2 = PyTuple_GET_ITEM(sequence, 0);
__pyx_t_3 = PyTuple_GET_ITEM(sequence, 1);
__Pyx_INCREF(__pyx_t_2);
__Pyx_INCREF(__pyx_t_3);
#else
__pyx_t_2 = PySequence_ITEM(sequence, 0); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 376; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_2);
__pyx_t_3 = PySequence_ITEM(sequence, 1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 376; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_3);
#endif
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
} else {
__Pyx_RaiseNoneNotIterableError(); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 376; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
}
__pyx_v_have_slices = __pyx_t_2;
__pyx_t_2 = 0;
__Pyx_DECREF_SET(__pyx_v_index, __pyx_t_3);
__pyx_t_3 = 0;
/* "View.MemoryView":378
* have_slices, index = _unellipsify(index, self.view.ndim)
*
* if have_slices: # <<<<<<<<<<<<<<
* obj = self.is_slice(value)
* if obj:
*/
__pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_v_have_slices); if (unlikely(__pyx_t_4 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 378; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
if (__pyx_t_4) {
/* "View.MemoryView":379
*
* if have_slices:
* obj = self.is_slice(value) # <<<<<<<<<<<<<<
* if obj:
* self.setitem_slice_assignment(self[index], obj)
*/
__pyx_t_1 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->is_slice(__pyx_v_self, __pyx_v_value); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 379; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
__pyx_v_obj = __pyx_t_1;
__pyx_t_1 = 0;
/* "View.MemoryView":380
* if have_slices:
* obj = self.is_slice(value)
* if obj: # <<<<<<<<<<<<<<
* self.setitem_slice_assignment(self[index], obj)
* else:
*/
__pyx_t_4 = __Pyx_PyObject_IsTrue(__pyx_v_obj); if (unlikely(__pyx_t_4 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 380; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
if (__pyx_t_4) {
/* "View.MemoryView":381
* obj = self.is_slice(value)
* if obj:
* self.setitem_slice_assignment(self[index], obj) # <<<<<<<<<<<<<<
* else:
* self.setitem_slice_assign_scalar(self[index], value)
*/
__pyx_t_1 = PyObject_GetItem(((PyObject *)__pyx_v_self), __pyx_v_index); if (unlikely(__pyx_t_1 == NULL)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 381; __pyx_clineno = __LINE__; goto __pyx_L1_error;};
__Pyx_GOTREF(__pyx_t_1);
__pyx_t_3 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->setitem_slice_assignment(__pyx_v_self, __pyx_t_1, __pyx_v_obj); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 381; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_3);
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
goto __pyx_L4;
}
/*else*/ {
/* "View.MemoryView":383
* self.setitem_slice_assignment(self[index], obj)
* else:
* self.setitem_slice_assign_scalar(self[index], value) # <<<<<<<<<<<<<<
* else:
* self.setitem_indexed(index, value)
*/
__pyx_t_3 = PyObject_GetItem(((PyObject *)__pyx_v_self), __pyx_v_index); if (unlikely(__pyx_t_3 == NULL)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 383; __pyx_clineno = __LINE__; goto __pyx_L1_error;};
__Pyx_GOTREF(__pyx_t_3);
if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_memoryview_type))))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 383; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_t_1 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->setitem_slice_assign_scalar(__pyx_v_self, ((struct __pyx_memoryview_obj *)__pyx_t_3), __pyx_v_value); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 383; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
}
__pyx_L4:;
goto __pyx_L3;
}
/*else*/ {
/* "View.MemoryView":385
* self.setitem_slice_assign_scalar(self[index], value)
* else:
* self.setitem_indexed(index, value) # <<<<<<<<<<<<<<
*
* cdef is_slice(self, obj):
*/
__pyx_t_1 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->setitem_indexed(__pyx_v_self, __pyx_v_index, __pyx_v_value); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 385; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
}
__pyx_L3:;
/* "View.MemoryView":375
* return self.convert_item_to_object(itemp)
*
* def __setitem__(memoryview self, object index, object value): # <<<<<<<<<<<<<<
* have_slices, index = _unellipsify(index, self.view.ndim)
*
*/
/* function exit code */
__pyx_r = 0;
goto __pyx_L0;
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_1);
__Pyx_XDECREF(__pyx_t_2);
__Pyx_XDECREF(__pyx_t_3);
__Pyx_AddTraceback("View.MemoryView.memoryview.__setitem__", __pyx_clineno, __pyx_lineno, __pyx_filename);
__pyx_r = -1;
__pyx_L0:;
__Pyx_XDECREF(__pyx_v_have_slices);
__Pyx_XDECREF(__pyx_v_obj);
__Pyx_XDECREF(__pyx_v_index);
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "View.MemoryView":387
* self.setitem_indexed(index, value)
*
* cdef is_slice(self, obj): # <<<<<<<<<<<<<<
* if not isinstance(obj, memoryview):
* try:
*/
static PyObject *__pyx_memoryview_is_slice(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_obj) {
PyObject *__pyx_r = NULL;
__Pyx_RefNannyDeclarations
int __pyx_t_1;
int __pyx_t_2;
PyObject *__pyx_t_3 = NULL;
PyObject *__pyx_t_4 = NULL;
PyObject *__pyx_t_5 = NULL;
PyObject *__pyx_t_6 = NULL;
PyObject *__pyx_t_7 = NULL;
PyObject *__pyx_t_8 = NULL;
int __pyx_t_9;
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
__Pyx_RefNannySetupContext("is_slice", 0);
__Pyx_INCREF(__pyx_v_obj);
/* "View.MemoryView":388
*
* cdef is_slice(self, obj):
* if not isinstance(obj, memoryview): # <<<<<<<<<<<<<<
* try:
* obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS,
*/
__pyx_t_1 = __Pyx_TypeCheck(__pyx_v_obj, ((PyObject *)__pyx_memoryview_type));
__pyx_t_2 = ((!(__pyx_t_1 != 0)) != 0);
if (__pyx_t_2) {
/* "View.MemoryView":389
* cdef is_slice(self, obj):
* if not isinstance(obj, memoryview):
* try: # <<<<<<<<<<<<<<
* obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS,
* self.dtype_is_object)
*/
{
__Pyx_ExceptionSave(&__pyx_t_3, &__pyx_t_4, &__pyx_t_5);
__Pyx_XGOTREF(__pyx_t_3);
__Pyx_XGOTREF(__pyx_t_4);
__Pyx_XGOTREF(__pyx_t_5);
/*try:*/ {
/* "View.MemoryView":390
* if not isinstance(obj, memoryview):
* try:
* obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS, # <<<<<<<<<<<<<<
* self.dtype_is_object)
* except TypeError:
*/
__pyx_t_6 = __Pyx_PyInt_From_int((__pyx_v_self->flags | PyBUF_ANY_CONTIGUOUS)); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 390; __pyx_clineno = __LINE__; goto __pyx_L4_error;}
__Pyx_GOTREF(__pyx_t_6);
/* "View.MemoryView":391
* try:
* obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS,
* self.dtype_is_object) # <<<<<<<<<<<<<<
* except TypeError:
* return None
*/
__pyx_t_7 = __Pyx_PyBool_FromLong(__pyx_v_self->dtype_is_object); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 391; __pyx_clineno = __LINE__; goto __pyx_L4_error;}
__Pyx_GOTREF(__pyx_t_7);
/* "View.MemoryView":390
* if not isinstance(obj, memoryview):
* try:
* obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS, # <<<<<<<<<<<<<<
* self.dtype_is_object)
* except TypeError:
*/
__pyx_t_8 = PyTuple_New(3); if (unlikely(!__pyx_t_8)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 390; __pyx_clineno = __LINE__; goto __pyx_L4_error;}
__Pyx_GOTREF(__pyx_t_8);
__Pyx_INCREF(__pyx_v_obj);
PyTuple_SET_ITEM(__pyx_t_8, 0, __pyx_v_obj);
__Pyx_GIVEREF(__pyx_v_obj);
PyTuple_SET_ITEM(__pyx_t_8, 1, __pyx_t_6);
__Pyx_GIVEREF(__pyx_t_6);
PyTuple_SET_ITEM(__pyx_t_8, 2, __pyx_t_7);
__Pyx_GIVEREF(__pyx_t_7);
__pyx_t_6 = 0;
__pyx_t_7 = 0;
__pyx_t_7 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_memoryview_type)), __pyx_t_8, NULL); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 390; __pyx_clineno = __LINE__; goto __pyx_L4_error;}
__Pyx_GOTREF(__pyx_t_7);
__Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0;
__Pyx_DECREF_SET(__pyx_v_obj, __pyx_t_7);
__pyx_t_7 = 0;
}
__Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0;
__Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0;
__Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0;
goto __pyx_L11_try_end;
__pyx_L4_error:;
__Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0;
__Pyx_XDECREF(__pyx_t_8); __pyx_t_8 = 0;
__Pyx_XDECREF(__pyx_t_7); __pyx_t_7 = 0;
/* "View.MemoryView":392
* obj = memoryview(obj, self.flags|PyBUF_ANY_CONTIGUOUS,
* self.dtype_is_object)
* except TypeError: # <<<<<<<<<<<<<<
* return None
*
*/
__pyx_t_9 = PyErr_ExceptionMatches(__pyx_builtin_TypeError);
if (__pyx_t_9) {
__Pyx_AddTraceback("View.MemoryView.memoryview.is_slice", __pyx_clineno, __pyx_lineno, __pyx_filename);
if (__Pyx_GetException(&__pyx_t_7, &__pyx_t_8, &__pyx_t_6) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 392; __pyx_clineno = __LINE__; goto __pyx_L6_except_error;}
__Pyx_GOTREF(__pyx_t_7);
__Pyx_GOTREF(__pyx_t_8);
__Pyx_GOTREF(__pyx_t_6);
/* "View.MemoryView":393
* self.dtype_is_object)
* except TypeError:
* return None # <<<<<<<<<<<<<<
*
* return obj
*/
__Pyx_XDECREF(__pyx_r);
__Pyx_INCREF(Py_None);
__pyx_r = Py_None;
__Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0;
__Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0;
__Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0;
goto __pyx_L7_except_return;
__Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0;
__Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0;
__Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0;
goto __pyx_L5_exception_handled;
}
goto __pyx_L6_except_error;
__pyx_L6_except_error:;
__Pyx_XGIVEREF(__pyx_t_3);
__Pyx_XGIVEREF(__pyx_t_4);
__Pyx_XGIVEREF(__pyx_t_5);
__Pyx_ExceptionReset(__pyx_t_3, __pyx_t_4, __pyx_t_5);
goto __pyx_L1_error;
__pyx_L7_except_return:;
__Pyx_XGIVEREF(__pyx_t_3);
__Pyx_XGIVEREF(__pyx_t_4);
__Pyx_XGIVEREF(__pyx_t_5);
__Pyx_ExceptionReset(__pyx_t_3, __pyx_t_4, __pyx_t_5);
goto __pyx_L0;
__pyx_L5_exception_handled:;
__Pyx_XGIVEREF(__pyx_t_3);
__Pyx_XGIVEREF(__pyx_t_4);
__Pyx_XGIVEREF(__pyx_t_5);
__Pyx_ExceptionReset(__pyx_t_3, __pyx_t_4, __pyx_t_5);
__pyx_L11_try_end:;
}
goto __pyx_L3;
}
__pyx_L3:;
/* "View.MemoryView":395
* return None
*
* return obj # <<<<<<<<<<<<<<
*
* cdef setitem_slice_assignment(self, dst, src):
*/
__Pyx_XDECREF(__pyx_r);
__Pyx_INCREF(__pyx_v_obj);
__pyx_r = __pyx_v_obj;
goto __pyx_L0;
/* "View.MemoryView":387
* self.setitem_indexed(index, value)
*
* cdef is_slice(self, obj): # <<<<<<<<<<<<<<
* if not isinstance(obj, memoryview):
* try:
*/
/* function exit code */
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_6);
__Pyx_XDECREF(__pyx_t_7);
__Pyx_XDECREF(__pyx_t_8);
__Pyx_AddTraceback("View.MemoryView.memoryview.is_slice", __pyx_clineno, __pyx_lineno, __pyx_filename);
__pyx_r = 0;
__pyx_L0:;
__Pyx_XDECREF(__pyx_v_obj);
__Pyx_XGIVEREF(__pyx_r);
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "View.MemoryView":397
* return obj
*
* cdef setitem_slice_assignment(self, dst, src): # <<<<<<<<<<<<<<
* cdef __Pyx_memviewslice dst_slice
* cdef __Pyx_memviewslice src_slice
*/
static PyObject *__pyx_memoryview_setitem_slice_assignment(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_dst, PyObject *__pyx_v_src) {
__Pyx_memviewslice __pyx_v_dst_slice;
__Pyx_memviewslice __pyx_v_src_slice;
PyObject *__pyx_r = NULL;
__Pyx_RefNannyDeclarations
PyObject *__pyx_t_1 = NULL;
int __pyx_t_2;
int __pyx_t_3;
int __pyx_t_4;
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
__Pyx_RefNannySetupContext("setitem_slice_assignment", 0);
/* "View.MemoryView":401
* cdef __Pyx_memviewslice src_slice
*
* memoryview_copy_contents(get_slice_from_memview(src, &src_slice)[0], # <<<<<<<<<<<<<<
* get_slice_from_memview(dst, &dst_slice)[0],
* src.ndim, dst.ndim, self.dtype_is_object)
*/
if (!(likely(((__pyx_v_src) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_src, __pyx_memoryview_type))))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 401; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
/* "View.MemoryView":402
*
* memoryview_copy_contents(get_slice_from_memview(src, &src_slice)[0],
* get_slice_from_memview(dst, &dst_slice)[0], # <<<<<<<<<<<<<<
* src.ndim, dst.ndim, self.dtype_is_object)
*
*/
if (!(likely(((__pyx_v_dst) == Py_None) || likely(__Pyx_TypeTest(__pyx_v_dst, __pyx_memoryview_type))))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 402; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
/* "View.MemoryView":403
* memoryview_copy_contents(get_slice_from_memview(src, &src_slice)[0],
* get_slice_from_memview(dst, &dst_slice)[0],
* src.ndim, dst.ndim, self.dtype_is_object) # <<<<<<<<<<<<<<
*
* cdef setitem_slice_assign_scalar(self, memoryview dst, value):
*/
__pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_src, __pyx_n_s_ndim); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 403; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
__pyx_t_2 = __Pyx_PyInt_As_int(__pyx_t_1); if (unlikely((__pyx_t_2 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 403; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
__pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_dst, __pyx_n_s_ndim); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 403; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
__pyx_t_3 = __Pyx_PyInt_As_int(__pyx_t_1); if (unlikely((__pyx_t_3 == (int)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 403; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
/* "View.MemoryView":401
* cdef __Pyx_memviewslice src_slice
*
* memoryview_copy_contents(get_slice_from_memview(src, &src_slice)[0], # <<<<<<<<<<<<<<
* get_slice_from_memview(dst, &dst_slice)[0],
* src.ndim, dst.ndim, self.dtype_is_object)
*/
__pyx_t_4 = __pyx_memoryview_copy_contents((__pyx_memoryview_get_slice_from_memoryview(((struct __pyx_memoryview_obj *)__pyx_v_src), (&__pyx_v_src_slice))[0]), (__pyx_memoryview_get_slice_from_memoryview(((struct __pyx_memoryview_obj *)__pyx_v_dst), (&__pyx_v_dst_slice))[0]), __pyx_t_2, __pyx_t_3, __pyx_v_self->dtype_is_object); if (unlikely(__pyx_t_4 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 401; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
/* "View.MemoryView":397
* return obj
*
* cdef setitem_slice_assignment(self, dst, src): # <<<<<<<<<<<<<<
* cdef __Pyx_memviewslice dst_slice
* cdef __Pyx_memviewslice src_slice
*/
/* function exit code */
__pyx_r = Py_None; __Pyx_INCREF(Py_None);
goto __pyx_L0;
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_1);
__Pyx_AddTraceback("View.MemoryView.memoryview.setitem_slice_assignment", __pyx_clineno, __pyx_lineno, __pyx_filename);
__pyx_r = 0;
__pyx_L0:;
__Pyx_XGIVEREF(__pyx_r);
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "View.MemoryView":405
* src.ndim, dst.ndim, self.dtype_is_object)
*
* cdef setitem_slice_assign_scalar(self, memoryview dst, value): # <<<<<<<<<<<<<<
* cdef int array[128]
* cdef void *tmp = NULL
*/
static PyObject *__pyx_memoryview_setitem_slice_assign_scalar(struct __pyx_memoryview_obj *__pyx_v_self, struct __pyx_memoryview_obj *__pyx_v_dst, PyObject *__pyx_v_value) {
int __pyx_v_array[128];
void *__pyx_v_tmp;
void *__pyx_v_item;
__Pyx_memviewslice *__pyx_v_dst_slice;
__Pyx_memviewslice __pyx_v_tmp_slice;
PyObject *__pyx_r = NULL;
__Pyx_RefNannyDeclarations
int __pyx_t_1;
PyObject *__pyx_t_2 = NULL;
PyObject *__pyx_t_3 = NULL;
PyObject *__pyx_t_4 = NULL;
PyObject *__pyx_t_5 = NULL;
PyObject *__pyx_t_6 = NULL;
PyObject *__pyx_t_7 = NULL;
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
__Pyx_RefNannySetupContext("setitem_slice_assign_scalar", 0);
/* "View.MemoryView":407
* cdef setitem_slice_assign_scalar(self, memoryview dst, value):
* cdef int array[128]
* cdef void *tmp = NULL # <<<<<<<<<<<<<<
* cdef void *item
*
*/
__pyx_v_tmp = NULL;
/* "View.MemoryView":412
* cdef __Pyx_memviewslice *dst_slice
* cdef __Pyx_memviewslice tmp_slice
* dst_slice = get_slice_from_memview(dst, &tmp_slice) # <<<<<<<<<<<<<<
*
* if <size_t>self.view.itemsize > sizeof(array):
*/
__pyx_v_dst_slice = __pyx_memoryview_get_slice_from_memoryview(__pyx_v_dst, (&__pyx_v_tmp_slice));
/* "View.MemoryView":414
* dst_slice = get_slice_from_memview(dst, &tmp_slice)
*
* if <size_t>self.view.itemsize > sizeof(array): # <<<<<<<<<<<<<<
* tmp = malloc(self.view.itemsize)
* if tmp == NULL:
*/
__pyx_t_1 = ((((size_t)__pyx_v_self->view.itemsize) > (sizeof(__pyx_v_array))) != 0);
if (__pyx_t_1) {
/* "View.MemoryView":415
*
* if <size_t>self.view.itemsize > sizeof(array):
* tmp = malloc(self.view.itemsize) # <<<<<<<<<<<<<<
* if tmp == NULL:
* raise MemoryError
*/
__pyx_v_tmp = malloc(__pyx_v_self->view.itemsize);
/* "View.MemoryView":416
* if <size_t>self.view.itemsize > sizeof(array):
* tmp = malloc(self.view.itemsize)
* if tmp == NULL: # <<<<<<<<<<<<<<
* raise MemoryError
* item = tmp
*/
__pyx_t_1 = ((__pyx_v_tmp == NULL) != 0);
if (__pyx_t_1) {
/* "View.MemoryView":417
* tmp = malloc(self.view.itemsize)
* if tmp == NULL:
* raise MemoryError # <<<<<<<<<<<<<<
* item = tmp
* else:
*/
PyErr_NoMemory(); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 417; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
}
/* "View.MemoryView":418
* if tmp == NULL:
* raise MemoryError
* item = tmp # <<<<<<<<<<<<<<
* else:
* item = <void *> array
*/
__pyx_v_item = __pyx_v_tmp;
goto __pyx_L3;
}
/*else*/ {
/* "View.MemoryView":420
* item = tmp
* else:
* item = <void *> array # <<<<<<<<<<<<<<
*
* if self.dtype_is_object:
*/
__pyx_v_item = ((void *)__pyx_v_array);
}
__pyx_L3:;
/* "View.MemoryView":422
* item = <void *> array
*
* if self.dtype_is_object: # <<<<<<<<<<<<<<
* (<PyObject **> item)[0] = <PyObject *> value
* else:
*/
__pyx_t_1 = (__pyx_v_self->dtype_is_object != 0);
if (__pyx_t_1) {
/* "View.MemoryView":423
*
* if self.dtype_is_object:
* (<PyObject **> item)[0] = <PyObject *> value # <<<<<<<<<<<<<<
* else:
* try:
*/
(((PyObject **)__pyx_v_item)[0]) = ((PyObject *)__pyx_v_value);
goto __pyx_L5;
}
/*else*/ {
/* "View.MemoryView":425
* (<PyObject **> item)[0] = <PyObject *> value
* else:
* try: # <<<<<<<<<<<<<<
* self.assign_item_from_object(<char *> item, value)
* except:
*/
{
__Pyx_ExceptionSave(&__pyx_t_2, &__pyx_t_3, &__pyx_t_4);
__Pyx_XGOTREF(__pyx_t_2);
__Pyx_XGOTREF(__pyx_t_3);
__Pyx_XGOTREF(__pyx_t_4);
/*try:*/ {
/* "View.MemoryView":426
* else:
* try:
* self.assign_item_from_object(<char *> item, value) # <<<<<<<<<<<<<<
* except:
* free(tmp)
*/
__pyx_t_5 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->assign_item_from_object(__pyx_v_self, ((char *)__pyx_v_item), __pyx_v_value); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 426; __pyx_clineno = __LINE__; goto __pyx_L6_error;}
__Pyx_GOTREF(__pyx_t_5);
__Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0;
}
__Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0;
__Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0;
__Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0;
goto __pyx_L13_try_end;
__pyx_L6_error:;
__Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0;
/* "View.MemoryView":427
* try:
* self.assign_item_from_object(<char *> item, value)
* except: # <<<<<<<<<<<<<<
* free(tmp)
* raise
*/
/*except:*/ {
__Pyx_AddTraceback("View.MemoryView.memoryview.setitem_slice_assign_scalar", __pyx_clineno, __pyx_lineno, __pyx_filename);
if (__Pyx_GetException(&__pyx_t_5, &__pyx_t_6, &__pyx_t_7) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 427; __pyx_clineno = __LINE__; goto __pyx_L8_except_error;}
__Pyx_GOTREF(__pyx_t_5);
__Pyx_GOTREF(__pyx_t_6);
__Pyx_GOTREF(__pyx_t_7);
/* "View.MemoryView":428
* self.assign_item_from_object(<char *> item, value)
* except:
* free(tmp) # <<<<<<<<<<<<<<
* raise
*
*/
free(__pyx_v_tmp);
/* "View.MemoryView":429
* except:
* free(tmp)
* raise # <<<<<<<<<<<<<<
*
*
*/
__Pyx_GIVEREF(__pyx_t_5);
__Pyx_GIVEREF(__pyx_t_6);
__Pyx_XGIVEREF(__pyx_t_7);
__Pyx_ErrRestore(__pyx_t_5, __pyx_t_6, __pyx_t_7);
__pyx_t_5 = 0; __pyx_t_6 = 0; __pyx_t_7 = 0;
{__pyx_filename = __pyx_f[2]; __pyx_lineno = 429; __pyx_clineno = __LINE__; goto __pyx_L8_except_error;}
__Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0;
__Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0;
__Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0;
goto __pyx_L7_exception_handled;
}
__pyx_L8_except_error:;
__Pyx_XGIVEREF(__pyx_t_2);
__Pyx_XGIVEREF(__pyx_t_3);
__Pyx_XGIVEREF(__pyx_t_4);
__Pyx_ExceptionReset(__pyx_t_2, __pyx_t_3, __pyx_t_4);
goto __pyx_L1_error;
__pyx_L7_exception_handled:;
__Pyx_XGIVEREF(__pyx_t_2);
__Pyx_XGIVEREF(__pyx_t_3);
__Pyx_XGIVEREF(__pyx_t_4);
__Pyx_ExceptionReset(__pyx_t_2, __pyx_t_3, __pyx_t_4);
__pyx_L13_try_end:;
}
}
__pyx_L5:;
/* "View.MemoryView":433
*
*
* if self.view.suboffsets != NULL: # <<<<<<<<<<<<<<
* assert_direct_dimensions(self.view.suboffsets, self.view.ndim)
* slice_assign_scalar(dst_slice, dst.view.ndim, self.view.itemsize,
*/
__pyx_t_1 = ((__pyx_v_self->view.suboffsets != NULL) != 0);
if (__pyx_t_1) {
/* "View.MemoryView":434
*
* if self.view.suboffsets != NULL:
* assert_direct_dimensions(self.view.suboffsets, self.view.ndim) # <<<<<<<<<<<<<<
* slice_assign_scalar(dst_slice, dst.view.ndim, self.view.itemsize,
* item, self.dtype_is_object)
*/
__pyx_t_7 = assert_direct_dimensions(__pyx_v_self->view.suboffsets, __pyx_v_self->view.ndim); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 434; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_7);
__Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0;
goto __pyx_L16;
}
__pyx_L16:;
/* "View.MemoryView":435
* if self.view.suboffsets != NULL:
* assert_direct_dimensions(self.view.suboffsets, self.view.ndim)
* slice_assign_scalar(dst_slice, dst.view.ndim, self.view.itemsize, # <<<<<<<<<<<<<<
* item, self.dtype_is_object)
* free(tmp)
*/
__pyx_memoryview_slice_assign_scalar(__pyx_v_dst_slice, __pyx_v_dst->view.ndim, __pyx_v_self->view.itemsize, __pyx_v_item, __pyx_v_self->dtype_is_object);
/* "View.MemoryView":437
* slice_assign_scalar(dst_slice, dst.view.ndim, self.view.itemsize,
* item, self.dtype_is_object)
* free(tmp) # <<<<<<<<<<<<<<
*
* cdef setitem_indexed(self, index, value):
*/
free(__pyx_v_tmp);
/* "View.MemoryView":405
* src.ndim, dst.ndim, self.dtype_is_object)
*
* cdef setitem_slice_assign_scalar(self, memoryview dst, value): # <<<<<<<<<<<<<<
* cdef int array[128]
* cdef void *tmp = NULL
*/
/* function exit code */
__pyx_r = Py_None; __Pyx_INCREF(Py_None);
goto __pyx_L0;
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_5);
__Pyx_XDECREF(__pyx_t_6);
__Pyx_XDECREF(__pyx_t_7);
__Pyx_AddTraceback("View.MemoryView.memoryview.setitem_slice_assign_scalar", __pyx_clineno, __pyx_lineno, __pyx_filename);
__pyx_r = 0;
__pyx_L0:;
__Pyx_XGIVEREF(__pyx_r);
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "View.MemoryView":439
* free(tmp)
*
* cdef setitem_indexed(self, index, value): # <<<<<<<<<<<<<<
* cdef char *itemp = self.get_item_pointer(index)
* self.assign_item_from_object(itemp, value)
*/
static PyObject *__pyx_memoryview_setitem_indexed(struct __pyx_memoryview_obj *__pyx_v_self, PyObject *__pyx_v_index, PyObject *__pyx_v_value) {
char *__pyx_v_itemp;
PyObject *__pyx_r = NULL;
__Pyx_RefNannyDeclarations
char *__pyx_t_1;
PyObject *__pyx_t_2 = NULL;
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
__Pyx_RefNannySetupContext("setitem_indexed", 0);
/* "View.MemoryView":440
*
* cdef setitem_indexed(self, index, value):
* cdef char *itemp = self.get_item_pointer(index) # <<<<<<<<<<<<<<
* self.assign_item_from_object(itemp, value)
*
*/
__pyx_t_1 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->get_item_pointer(__pyx_v_self, __pyx_v_index); if (unlikely(__pyx_t_1 == NULL)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 440; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_v_itemp = __pyx_t_1;
/* "View.MemoryView":441
* cdef setitem_indexed(self, index, value):
* cdef char *itemp = self.get_item_pointer(index)
* self.assign_item_from_object(itemp, value) # <<<<<<<<<<<<<<
*
* cdef convert_item_to_object(self, char *itemp):
*/
__pyx_t_2 = ((struct __pyx_vtabstruct_memoryview *)__pyx_v_self->__pyx_vtab)->assign_item_from_object(__pyx_v_self, __pyx_v_itemp, __pyx_v_value); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 441; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_2);
__Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0;
/* "View.MemoryView":439
* free(tmp)
*
* cdef setitem_indexed(self, index, value): # <<<<<<<<<<<<<<
* cdef char *itemp = self.get_item_pointer(index)
* self.assign_item_from_object(itemp, value)
*/
/* function exit code */
__pyx_r = Py_None; __Pyx_INCREF(Py_None);
goto __pyx_L0;
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_2);
__Pyx_AddTraceback("View.MemoryView.memoryview.setitem_indexed", __pyx_clineno, __pyx_lineno, __pyx_filename);
__pyx_r = 0;
__pyx_L0:;
__Pyx_XGIVEREF(__pyx_r);
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "View.MemoryView":443
* self.assign_item_from_object(itemp, value)
*
* cdef convert_item_to_object(self, char *itemp): # <<<<<<<<<<<<<<
* """Only used if instantiated manually by the user, or if Cython doesn't
* know how to convert the type"""
*/
static PyObject *__pyx_memoryview_convert_item_to_object(struct __pyx_memoryview_obj *__pyx_v_self, char *__pyx_v_itemp) {
PyObject *__pyx_v_struct = NULL;
PyObject *__pyx_v_bytesitem = 0;
PyObject *__pyx_v_result = NULL;
PyObject *__pyx_r = NULL;
__Pyx_RefNannyDeclarations
PyObject *__pyx_t_1 = NULL;
PyObject *__pyx_t_2 = NULL;
PyObject *__pyx_t_3 = NULL;
PyObject *__pyx_t_4 = NULL;
PyObject *__pyx_t_5 = NULL;
PyObject *__pyx_t_6 = NULL;
size_t __pyx_t_7;
int __pyx_t_8;
int __pyx_t_9;
PyObject *__pyx_t_10 = NULL;
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
__Pyx_RefNannySetupContext("convert_item_to_object", 0);
/* "View.MemoryView":446
* """Only used if instantiated manually by the user, or if Cython doesn't
* know how to convert the type"""
* import struct # <<<<<<<<<<<<<<
* cdef bytes bytesitem
*
*/
__pyx_t_1 = __Pyx_Import(__pyx_n_s_struct, 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 446; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
__pyx_v_struct = __pyx_t_1;
__pyx_t_1 = 0;
/* "View.MemoryView":449
* cdef bytes bytesitem
*
* bytesitem = itemp[:self.view.itemsize] # <<<<<<<<<<<<<<
* try:
* result = struct.unpack(self.view.format, bytesitem)
*/
__pyx_t_1 = __Pyx_PyBytes_FromStringAndSize(__pyx_v_itemp + 0, __pyx_v_self->view.itemsize - 0); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 449; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
__pyx_v_bytesitem = ((PyObject*)__pyx_t_1);
__pyx_t_1 = 0;
/* "View.MemoryView":450
*
* bytesitem = itemp[:self.view.itemsize]
* try: # <<<<<<<<<<<<<<
* result = struct.unpack(self.view.format, bytesitem)
* except struct.error:
*/
{
__Pyx_ExceptionSave(&__pyx_t_2, &__pyx_t_3, &__pyx_t_4);
__Pyx_XGOTREF(__pyx_t_2);
__Pyx_XGOTREF(__pyx_t_3);
__Pyx_XGOTREF(__pyx_t_4);
/*try:*/ {
/* "View.MemoryView":451
* bytesitem = itemp[:self.view.itemsize]
* try:
* result = struct.unpack(self.view.format, bytesitem) # <<<<<<<<<<<<<<
* except struct.error:
* raise ValueError("Unable to convert item to object")
*/
__pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s_unpack); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 451; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
__Pyx_GOTREF(__pyx_t_1);
__pyx_t_5 = __Pyx_PyBytes_FromString(__pyx_v_self->view.format); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 451; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
__Pyx_GOTREF(__pyx_t_5);
__pyx_t_6 = PyTuple_New(2); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 451; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
__Pyx_GOTREF(__pyx_t_6);
PyTuple_SET_ITEM(__pyx_t_6, 0, __pyx_t_5);
__Pyx_GIVEREF(__pyx_t_5);
__Pyx_INCREF(__pyx_v_bytesitem);
PyTuple_SET_ITEM(__pyx_t_6, 1, __pyx_v_bytesitem);
__Pyx_GIVEREF(__pyx_v_bytesitem);
__pyx_t_5 = 0;
__pyx_t_5 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_t_6, NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 451; __pyx_clineno = __LINE__; goto __pyx_L3_error;}
__Pyx_GOTREF(__pyx_t_5);
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
__Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0;
__pyx_v_result = __pyx_t_5;
__pyx_t_5 = 0;
}
/*else:*/ {
/* "View.MemoryView":455
* raise ValueError("Unable to convert item to object")
* else:
* if len(self.view.format) == 1: # <<<<<<<<<<<<<<
* return result[0]
* return result
*/
__pyx_t_7 = strlen(__pyx_v_self->view.format);
__pyx_t_8 = ((__pyx_t_7 == 1) != 0);
if (__pyx_t_8) {
/* "View.MemoryView":456
* else:
* if len(self.view.format) == 1:
* return result[0] # <<<<<<<<<<<<<<
* return result
*
*/
__Pyx_XDECREF(__pyx_r);
__pyx_t_5 = __Pyx_GetItemInt(__pyx_v_result, 0, long, 1, __Pyx_PyInt_From_long, 0, 0, 0); if (unlikely(__pyx_t_5 == NULL)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 456; __pyx_clineno = __LINE__; goto __pyx_L5_except_error;};
__Pyx_GOTREF(__pyx_t_5);
__pyx_r = __pyx_t_5;
__pyx_t_5 = 0;
goto __pyx_L6_except_return;
}
/* "View.MemoryView":457
* if len(self.view.format) == 1:
* return result[0]
* return result # <<<<<<<<<<<<<<
*
* cdef assign_item_from_object(self, char *itemp, object value):
*/
__Pyx_XDECREF(__pyx_r);
__Pyx_INCREF(__pyx_v_result);
__pyx_r = __pyx_v_result;
goto __pyx_L6_except_return;
}
__Pyx_XDECREF(__pyx_t_2); __pyx_t_2 = 0;
__Pyx_XDECREF(__pyx_t_3); __pyx_t_3 = 0;
__Pyx_XDECREF(__pyx_t_4); __pyx_t_4 = 0;
goto __pyx_L10_try_end;
__pyx_L3_error:;
__Pyx_XDECREF(__pyx_t_1); __pyx_t_1 = 0;
__Pyx_XDECREF(__pyx_t_6); __pyx_t_6 = 0;
__Pyx_XDECREF(__pyx_t_5); __pyx_t_5 = 0;
/* "View.MemoryView":452
* try:
* result = struct.unpack(self.view.format, bytesitem)
* except struct.error: # <<<<<<<<<<<<<<
* raise ValueError("Unable to convert item to object")
* else:
*/
__pyx_t_5 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s_error); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 452; __pyx_clineno = __LINE__; goto __pyx_L5_except_error;}
__Pyx_GOTREF(__pyx_t_5);
__pyx_t_9 = PyErr_ExceptionMatches(__pyx_t_5);
__Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0;
if (__pyx_t_9) {
__Pyx_AddTraceback("View.MemoryView.memoryview.convert_item_to_object", __pyx_clineno, __pyx_lineno, __pyx_filename);
if (__Pyx_GetException(&__pyx_t_5, &__pyx_t_6, &__pyx_t_1) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 452; __pyx_clineno = __LINE__; goto __pyx_L5_except_error;}
__Pyx_GOTREF(__pyx_t_5);
__Pyx_GOTREF(__pyx_t_6);
__Pyx_GOTREF(__pyx_t_1);
/* "View.MemoryView":453
* result = struct.unpack(self.view.format, bytesitem)
* except struct.error:
* raise ValueError("Unable to convert item to object") # <<<<<<<<<<<<<<
* else:
* if len(self.view.format) == 1:
*/
__pyx_t_10 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__26, NULL); if (unlikely(!__pyx_t_10)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 453; __pyx_clineno = __LINE__; goto __pyx_L5_except_error;}
__Pyx_GOTREF(__pyx_t_10);
__Pyx_Raise(__pyx_t_10, 0, 0, 0);
__Pyx_DECREF(__pyx_t_10); __pyx_t_10 = 0;
{__pyx_filename = __pyx_f[2]; __pyx_lineno = 453; __pyx_clineno = __LINE__; goto __pyx_L5_except_error;}
__Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0;
__Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0;
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
goto __pyx_L4_exception_handled;
}
goto __pyx_L5_except_error;
__pyx_L5_except_error:;
__Pyx_XGIVEREF(__pyx_t_2);
__Pyx_XGIVEREF(__pyx_t_3);
__Pyx_XGIVEREF(__pyx_t_4);
__Pyx_ExceptionReset(__pyx_t_2, __pyx_t_3, __pyx_t_4);
goto __pyx_L1_error;
__pyx_L6_except_return:;
__Pyx_XGIVEREF(__pyx_t_2);
__Pyx_XGIVEREF(__pyx_t_3);
__Pyx_XGIVEREF(__pyx_t_4);
__Pyx_ExceptionReset(__pyx_t_2, __pyx_t_3, __pyx_t_4);
goto __pyx_L0;
__pyx_L4_exception_handled:;
__Pyx_XGIVEREF(__pyx_t_2);
__Pyx_XGIVEREF(__pyx_t_3);
__Pyx_XGIVEREF(__pyx_t_4);
__Pyx_ExceptionReset(__pyx_t_2, __pyx_t_3, __pyx_t_4);
__pyx_L10_try_end:;
}
/* "View.MemoryView":443
* self.assign_item_from_object(itemp, value)
*
* cdef convert_item_to_object(self, char *itemp): # <<<<<<<<<<<<<<
* """Only used if instantiated manually by the user, or if Cython doesn't
* know how to convert the type"""
*/
/* function exit code */
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_1);
__Pyx_XDECREF(__pyx_t_5);
__Pyx_XDECREF(__pyx_t_6);
__Pyx_XDECREF(__pyx_t_10);
__Pyx_AddTraceback("View.MemoryView.memoryview.convert_item_to_object", __pyx_clineno, __pyx_lineno, __pyx_filename);
__pyx_r = 0;
__pyx_L0:;
__Pyx_XDECREF(__pyx_v_struct);
__Pyx_XDECREF(__pyx_v_bytesitem);
__Pyx_XDECREF(__pyx_v_result);
__Pyx_XGIVEREF(__pyx_r);
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "View.MemoryView":459
* return result
*
* cdef assign_item_from_object(self, char *itemp, object value): # <<<<<<<<<<<<<<
* """Only used if instantiated manually by the user, or if Cython doesn't
* know how to convert the type"""
*/
static PyObject *__pyx_memoryview_assign_item_from_object(struct __pyx_memoryview_obj *__pyx_v_self, char *__pyx_v_itemp, PyObject *__pyx_v_value) {
PyObject *__pyx_v_struct = NULL;
char __pyx_v_c;
PyObject *__pyx_v_bytesvalue = 0;
Py_ssize_t __pyx_v_i;
PyObject *__pyx_r = NULL;
__Pyx_RefNannyDeclarations
PyObject *__pyx_t_1 = NULL;
int __pyx_t_2;
int __pyx_t_3;
PyObject *__pyx_t_4 = NULL;
PyObject *__pyx_t_5 = NULL;
PyObject *__pyx_t_6 = NULL;
Py_ssize_t __pyx_t_7;
PyObject *__pyx_t_8 = NULL;
char *__pyx_t_9;
char *__pyx_t_10;
char *__pyx_t_11;
char *__pyx_t_12;
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
__Pyx_RefNannySetupContext("assign_item_from_object", 0);
/* "View.MemoryView":462
* """Only used if instantiated manually by the user, or if Cython doesn't
* know how to convert the type"""
* import struct # <<<<<<<<<<<<<<
* cdef char c
* cdef bytes bytesvalue
*/
__pyx_t_1 = __Pyx_Import(__pyx_n_s_struct, 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 462; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
__pyx_v_struct = __pyx_t_1;
__pyx_t_1 = 0;
/* "View.MemoryView":467
* cdef Py_ssize_t i
*
* if isinstance(value, tuple): # <<<<<<<<<<<<<<
* bytesvalue = struct.pack(self.view.format, *value)
* else:
*/
__pyx_t_2 = PyTuple_Check(__pyx_v_value);
__pyx_t_3 = (__pyx_t_2 != 0);
if (__pyx_t_3) {
/* "View.MemoryView":468
*
* if isinstance(value, tuple):
* bytesvalue = struct.pack(self.view.format, *value) # <<<<<<<<<<<<<<
* else:
* bytesvalue = struct.pack(self.view.format, value)
*/
__pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s_pack); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 468; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
__pyx_t_4 = __Pyx_PyBytes_FromString(__pyx_v_self->view.format); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 468; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_4);
__pyx_t_5 = PyTuple_New(1); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 468; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_5);
PyTuple_SET_ITEM(__pyx_t_5, 0, __pyx_t_4);
__Pyx_GIVEREF(__pyx_t_4);
__pyx_t_4 = 0;
__pyx_t_4 = PySequence_Tuple(__pyx_v_value); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 468; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_4);
__pyx_t_6 = PyNumber_Add(__pyx_t_5, __pyx_t_4); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 468; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_6);
__Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0;
__Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
__pyx_t_4 = __Pyx_PyObject_Call(__pyx_t_1, __pyx_t_6, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 468; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_4);
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
__Pyx_DECREF(__pyx_t_6); __pyx_t_6 = 0;
if (!(likely(PyBytes_CheckExact(__pyx_t_4))||((__pyx_t_4) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "bytes", Py_TYPE(__pyx_t_4)->tp_name), 0))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 468; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_v_bytesvalue = ((PyObject*)__pyx_t_4);
__pyx_t_4 = 0;
goto __pyx_L3;
}
/*else*/ {
/* "View.MemoryView":470
* bytesvalue = struct.pack(self.view.format, *value)
* else:
* bytesvalue = struct.pack(self.view.format, value) # <<<<<<<<<<<<<<
*
* for i, c in enumerate(bytesvalue):
*/
__pyx_t_4 = __Pyx_PyObject_GetAttrStr(__pyx_v_struct, __pyx_n_s_pack); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 470; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_4);
__pyx_t_6 = __Pyx_PyBytes_FromString(__pyx_v_self->view.format); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 470; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_6);
__pyx_t_1 = PyTuple_New(2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 470; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
PyTuple_SET_ITEM(__pyx_t_1, 0, __pyx_t_6);
__Pyx_GIVEREF(__pyx_t_6);
__Pyx_INCREF(__pyx_v_value);
PyTuple_SET_ITEM(__pyx_t_1, 1, __pyx_v_value);
__Pyx_GIVEREF(__pyx_v_value);
__pyx_t_6 = 0;
__pyx_t_6 = __Pyx_PyObject_Call(__pyx_t_4, __pyx_t_1, NULL); if (unlikely(!__pyx_t_6)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 470; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_6);
__Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
if (!(likely(PyBytes_CheckExact(__pyx_t_6))||((__pyx_t_6) == Py_None)||(PyErr_Format(PyExc_TypeError, "Expected %.16s, got %.200s", "bytes", Py_TYPE(__pyx_t_6)->tp_name), 0))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 470; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_v_bytesvalue = ((PyObject*)__pyx_t_6);
__pyx_t_6 = 0;
}
__pyx_L3:;
/* "View.MemoryView":472
* bytesvalue = struct.pack(self.view.format, value)
*
* for i, c in enumerate(bytesvalue): # <<<<<<<<<<<<<<
* itemp[i] = c
*
*/
__pyx_t_7 = 0;
if (unlikely(__pyx_v_bytesvalue == Py_None)) {
PyErr_SetString(PyExc_TypeError, "'NoneType' is not iterable");
{__pyx_filename = __pyx_f[2]; __pyx_lineno = 472; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
}
__Pyx_INCREF(__pyx_v_bytesvalue);
__pyx_t_8 = __pyx_v_bytesvalue;
__pyx_t_10 = PyBytes_AS_STRING(__pyx_t_8);
__pyx_t_11 = (__pyx_t_10 + PyBytes_GET_SIZE(__pyx_t_8));
for (__pyx_t_12 = __pyx_t_10; __pyx_t_12 < __pyx_t_11; __pyx_t_12++) {
__pyx_t_9 = __pyx_t_12;
__pyx_v_c = (__pyx_t_9[0]);
/* "View.MemoryView":473
*
* for i, c in enumerate(bytesvalue):
* itemp[i] = c # <<<<<<<<<<<<<<
*
* @cname('getbuffer')
*/
__pyx_v_i = __pyx_t_7;
/* "View.MemoryView":472
* bytesvalue = struct.pack(self.view.format, value)
*
* for i, c in enumerate(bytesvalue): # <<<<<<<<<<<<<<
* itemp[i] = c
*
*/
__pyx_t_7 = (__pyx_t_7 + 1);
/* "View.MemoryView":473
*
* for i, c in enumerate(bytesvalue):
* itemp[i] = c # <<<<<<<<<<<<<<
*
* @cname('getbuffer')
*/
(__pyx_v_itemp[__pyx_v_i]) = __pyx_v_c;
}
__Pyx_DECREF(__pyx_t_8); __pyx_t_8 = 0;
/* "View.MemoryView":459
* return result
*
* cdef assign_item_from_object(self, char *itemp, object value): # <<<<<<<<<<<<<<
* """Only used if instantiated manually by the user, or if Cython doesn't
* know how to convert the type"""
*/
/* function exit code */
__pyx_r = Py_None; __Pyx_INCREF(Py_None);
goto __pyx_L0;
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_1);
__Pyx_XDECREF(__pyx_t_4);
__Pyx_XDECREF(__pyx_t_5);
__Pyx_XDECREF(__pyx_t_6);
__Pyx_XDECREF(__pyx_t_8);
__Pyx_AddTraceback("View.MemoryView.memoryview.assign_item_from_object", __pyx_clineno, __pyx_lineno, __pyx_filename);
__pyx_r = 0;
__pyx_L0:;
__Pyx_XDECREF(__pyx_v_struct);
__Pyx_XDECREF(__pyx_v_bytesvalue);
__Pyx_XGIVEREF(__pyx_r);
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "View.MemoryView":476
*
* @cname('getbuffer')
* def __getbuffer__(self, Py_buffer *info, int flags): # <<<<<<<<<<<<<<
* if flags & PyBUF_STRIDES:
* info.shape = self.view.shape
*/
/* Python wrapper */
static CYTHON_UNUSED int __pyx_memoryview_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags); /*proto*/
static CYTHON_UNUSED int __pyx_memoryview_getbuffer(PyObject *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) {
int __pyx_r;
__Pyx_RefNannyDeclarations
__Pyx_RefNannySetupContext("__getbuffer__ (wrapper)", 0);
__pyx_r = __pyx_memoryview_getbuffer_MemoryView_10memoryview_8__getbuffer__(((struct __pyx_memoryview_obj *)__pyx_v_self), ((Py_buffer *)__pyx_v_info), ((int)__pyx_v_flags));
/* function exit code */
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
static int __pyx_memoryview_getbuffer_MemoryView_10memoryview_8__getbuffer__(struct __pyx_memoryview_obj *__pyx_v_self, Py_buffer *__pyx_v_info, int __pyx_v_flags) {
int __pyx_r;
__Pyx_RefNannyDeclarations
int __pyx_t_1;
Py_ssize_t *__pyx_t_2;
char *__pyx_t_3;
void *__pyx_t_4;
int __pyx_t_5;
Py_ssize_t __pyx_t_6;
__Pyx_RefNannySetupContext("__getbuffer__", 0);
if (__pyx_v_info != NULL) {
__pyx_v_info->obj = Py_None; __Pyx_INCREF(Py_None);
__Pyx_GIVEREF(__pyx_v_info->obj);
}
/* "View.MemoryView":477
* @cname('getbuffer')
* def __getbuffer__(self, Py_buffer *info, int flags):
* if flags & PyBUF_STRIDES: # <<<<<<<<<<<<<<
* info.shape = self.view.shape
* else:
*/
__pyx_t_1 = ((__pyx_v_flags & PyBUF_STRIDES) != 0);
if (__pyx_t_1) {
/* "View.MemoryView":478
* def __getbuffer__(self, Py_buffer *info, int flags):
* if flags & PyBUF_STRIDES:
* info.shape = self.view.shape # <<<<<<<<<<<<<<
* else:
* info.shape = NULL
*/
__pyx_t_2 = __pyx_v_self->view.shape;
__pyx_v_info->shape = __pyx_t_2;
goto __pyx_L3;
}
/*else*/ {
/* "View.MemoryView":480
* info.shape = self.view.shape
* else:
* info.shape = NULL # <<<<<<<<<<<<<<
*
* if flags & PyBUF_STRIDES:
*/
__pyx_v_info->shape = NULL;
}
__pyx_L3:;
/* "View.MemoryView":482
* info.shape = NULL
*
* if flags & PyBUF_STRIDES: # <<<<<<<<<<<<<<
* info.strides = self.view.strides
* else:
*/
__pyx_t_1 = ((__pyx_v_flags & PyBUF_STRIDES) != 0);
if (__pyx_t_1) {
/* "View.MemoryView":483
*
* if flags & PyBUF_STRIDES:
* info.strides = self.view.strides # <<<<<<<<<<<<<<
* else:
* info.strides = NULL
*/
__pyx_t_2 = __pyx_v_self->view.strides;
__pyx_v_info->strides = __pyx_t_2;
goto __pyx_L4;
}
/*else*/ {
/* "View.MemoryView":485
* info.strides = self.view.strides
* else:
* info.strides = NULL # <<<<<<<<<<<<<<
*
* if flags & PyBUF_INDIRECT:
*/
__pyx_v_info->strides = NULL;
}
__pyx_L4:;
/* "View.MemoryView":487
* info.strides = NULL
*
* if flags & PyBUF_INDIRECT: # <<<<<<<<<<<<<<
* info.suboffsets = self.view.suboffsets
* else:
*/
__pyx_t_1 = ((__pyx_v_flags & PyBUF_INDIRECT) != 0);
if (__pyx_t_1) {
/* "View.MemoryView":488
*
* if flags & PyBUF_INDIRECT:
* info.suboffsets = self.view.suboffsets # <<<<<<<<<<<<<<
* else:
* info.suboffsets = NULL
*/
__pyx_t_2 = __pyx_v_self->view.suboffsets;
__pyx_v_info->suboffsets = __pyx_t_2;
goto __pyx_L5;
}
/*else*/ {
/* "View.MemoryView":490
* info.suboffsets = self.view.suboffsets
* else:
* info.suboffsets = NULL # <<<<<<<<<<<<<<
*
* if flags & PyBUF_FORMAT:
*/
__pyx_v_info->suboffsets = NULL;
}
__pyx_L5:;
/* "View.MemoryView":492
* info.suboffsets = NULL
*
* if flags & PyBUF_FORMAT: # <<<<<<<<<<<<<<
* info.format = self.view.format
* else:
*/
__pyx_t_1 = ((__pyx_v_flags & PyBUF_FORMAT) != 0);
if (__pyx_t_1) {
/* "View.MemoryView":493
*
* if flags & PyBUF_FORMAT:
* info.format = self.view.format # <<<<<<<<<<<<<<
* else:
* info.format = NULL
*/
__pyx_t_3 = __pyx_v_self->view.format;
__pyx_v_info->format = __pyx_t_3;
goto __pyx_L6;
}
/*else*/ {
/* "View.MemoryView":495
* info.format = self.view.format
* else:
* info.format = NULL # <<<<<<<<<<<<<<
*
* info.buf = self.view.buf
*/
__pyx_v_info->format = NULL;
}
__pyx_L6:;
/* "View.MemoryView":497
* info.format = NULL
*
* info.buf = self.view.buf # <<<<<<<<<<<<<<
* info.ndim = self.view.ndim
* info.itemsize = self.view.itemsize
*/
__pyx_t_4 = __pyx_v_self->view.buf;
__pyx_v_info->buf = __pyx_t_4;
/* "View.MemoryView":498
*
* info.buf = self.view.buf
* info.ndim = self.view.ndim # <<<<<<<<<<<<<<
* info.itemsize = self.view.itemsize
* info.len = self.view.len
*/
__pyx_t_5 = __pyx_v_self->view.ndim;
__pyx_v_info->ndim = __pyx_t_5;
/* "View.MemoryView":499
* info.buf = self.view.buf
* info.ndim = self.view.ndim
* info.itemsize = self.view.itemsize # <<<<<<<<<<<<<<
* info.len = self.view.len
* info.readonly = 0
*/
__pyx_t_6 = __pyx_v_self->view.itemsize;
__pyx_v_info->itemsize = __pyx_t_6;
/* "View.MemoryView":500
* info.ndim = self.view.ndim
* info.itemsize = self.view.itemsize
* info.len = self.view.len # <<<<<<<<<<<<<<
* info.readonly = 0
* info.obj = self
*/
__pyx_t_6 = __pyx_v_self->view.len;
__pyx_v_info->len = __pyx_t_6;
/* "View.MemoryView":501
* info.itemsize = self.view.itemsize
* info.len = self.view.len
* info.readonly = 0 # <<<<<<<<<<<<<<
* info.obj = self
*
*/
__pyx_v_info->readonly = 0;
/* "View.MemoryView":502
* info.len = self.view.len
* info.readonly = 0
* info.obj = self # <<<<<<<<<<<<<<
*
* __pyx_getbuffer = capsule(<void *> &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)")
*/
__Pyx_INCREF(((PyObject *)__pyx_v_self));
__Pyx_GIVEREF(((PyObject *)__pyx_v_self));
__Pyx_GOTREF(__pyx_v_info->obj);
__Pyx_DECREF(__pyx_v_info->obj);
__pyx_v_info->obj = ((PyObject *)__pyx_v_self);
/* "View.MemoryView":476
*
* @cname('getbuffer')
* def __getbuffer__(self, Py_buffer *info, int flags): # <<<<<<<<<<<<<<
* if flags & PyBUF_STRIDES:
* info.shape = self.view.shape
*/
/* function exit code */
__pyx_r = 0;
if (__pyx_v_info != NULL && __pyx_v_info->obj == Py_None) {
__Pyx_GOTREF(Py_None);
__Pyx_DECREF(Py_None); __pyx_v_info->obj = NULL;
}
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "View.MemoryView":509
* property T:
* @cname('__pyx_memoryview_transpose')
* def __get__(self): # <<<<<<<<<<<<<<
* cdef _memoryviewslice result = memoryview_copy(self)
* transpose_memslice(&result.from_slice)
*/
/* Python wrapper */
static PyObject *__pyx_memoryview_transpose(PyObject *__pyx_v_self); /*proto*/
static PyObject *__pyx_memoryview_transpose(PyObject *__pyx_v_self) {
PyObject *__pyx_r = 0;
__Pyx_RefNannyDeclarations
__Pyx_RefNannySetupContext("__get__ (wrapper)", 0);
__pyx_r = __pyx_memoryview_transpose_MemoryView_10memoryview_1T___get__(((struct __pyx_memoryview_obj *)__pyx_v_self));
/* function exit code */
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
static PyObject *__pyx_memoryview_transpose_MemoryView_10memoryview_1T___get__(struct __pyx_memoryview_obj *__pyx_v_self) {
struct __pyx_memoryviewslice_obj *__pyx_v_result = 0;
PyObject *__pyx_r = NULL;
__Pyx_RefNannyDeclarations
PyObject *__pyx_t_1 = NULL;
int __pyx_t_2;
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
__Pyx_RefNannySetupContext("__get__", 0);
/* "View.MemoryView":510
* @cname('__pyx_memoryview_transpose')
* def __get__(self):
* cdef _memoryviewslice result = memoryview_copy(self) # <<<<<<<<<<<<<<
* transpose_memslice(&result.from_slice)
* return result
*/
__pyx_t_1 = __pyx_memoryview_copy_object(__pyx_v_self); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 510; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
if (!(likely(((__pyx_t_1) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_1, __pyx_memoryviewslice_type))))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 510; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_v_result = ((struct __pyx_memoryviewslice_obj *)__pyx_t_1);
__pyx_t_1 = 0;
/* "View.MemoryView":511
* def __get__(self):
* cdef _memoryviewslice result = memoryview_copy(self)
* transpose_memslice(&result.from_slice) # <<<<<<<<<<<<<<
* return result
*
*/
__pyx_t_2 = __pyx_memslice_transpose((&__pyx_v_result->from_slice)); if (unlikely(__pyx_t_2 == 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 511; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
/* "View.MemoryView":512
* cdef _memoryviewslice result = memoryview_copy(self)
* transpose_memslice(&result.from_slice)
* return result # <<<<<<<<<<<<<<
*
* property base:
*/
__Pyx_XDECREF(__pyx_r);
__Pyx_INCREF(((PyObject *)__pyx_v_result));
__pyx_r = ((PyObject *)__pyx_v_result);
goto __pyx_L0;
/* "View.MemoryView":509
* property T:
* @cname('__pyx_memoryview_transpose')
* def __get__(self): # <<<<<<<<<<<<<<
* cdef _memoryviewslice result = memoryview_copy(self)
* transpose_memslice(&result.from_slice)
*/
/* function exit code */
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_1);
__Pyx_AddTraceback("View.MemoryView.memoryview.T.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename);
__pyx_r = NULL;
__pyx_L0:;
__Pyx_XDECREF((PyObject *)__pyx_v_result);
__Pyx_XGIVEREF(__pyx_r);
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "View.MemoryView":516
* property base:
* @cname('__pyx_memoryview__get__base')
* def __get__(self): # <<<<<<<<<<<<<<
* return self.obj
*
*/
/* Python wrapper */
static PyObject *__pyx_memoryview__get__base(PyObject *__pyx_v_self); /*proto*/
static PyObject *__pyx_memoryview__get__base(PyObject *__pyx_v_self) {
PyObject *__pyx_r = 0;
__Pyx_RefNannyDeclarations
__Pyx_RefNannySetupContext("__get__ (wrapper)", 0);
__pyx_r = __pyx_memoryview__get__base_MemoryView_10memoryview_4base___get__(((struct __pyx_memoryview_obj *)__pyx_v_self));
/* function exit code */
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
static PyObject *__pyx_memoryview__get__base_MemoryView_10memoryview_4base___get__(struct __pyx_memoryview_obj *__pyx_v_self) {
PyObject *__pyx_r = NULL;
__Pyx_RefNannyDeclarations
__Pyx_RefNannySetupContext("__get__", 0);
/* "View.MemoryView":517
* @cname('__pyx_memoryview__get__base')
* def __get__(self):
* return self.obj # <<<<<<<<<<<<<<
*
* property shape:
*/
__Pyx_XDECREF(__pyx_r);
__Pyx_INCREF(__pyx_v_self->obj);
__pyx_r = __pyx_v_self->obj;
goto __pyx_L0;
/* "View.MemoryView":516
* property base:
* @cname('__pyx_memoryview__get__base')
* def __get__(self): # <<<<<<<<<<<<<<
* return self.obj
*
*/
/* function exit code */
__pyx_L0:;
__Pyx_XGIVEREF(__pyx_r);
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "View.MemoryView":521
* property shape:
* @cname('__pyx_memoryview_get_shape')
* def __get__(self): # <<<<<<<<<<<<<<
* return tuple([self.view.shape[i] for i in xrange(self.view.ndim)])
*
*/
/* Python wrapper */
static PyObject *__pyx_memoryview_get_shape(PyObject *__pyx_v_self); /*proto*/
static PyObject *__pyx_memoryview_get_shape(PyObject *__pyx_v_self) {
PyObject *__pyx_r = 0;
__Pyx_RefNannyDeclarations
__Pyx_RefNannySetupContext("__get__ (wrapper)", 0);
__pyx_r = __pyx_memoryview_get_shape_MemoryView_10memoryview_5shape___get__(((struct __pyx_memoryview_obj *)__pyx_v_self));
/* function exit code */
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
static PyObject *__pyx_memoryview_get_shape_MemoryView_10memoryview_5shape___get__(struct __pyx_memoryview_obj *__pyx_v_self) {
int __pyx_v_i;
PyObject *__pyx_r = NULL;
__Pyx_RefNannyDeclarations
PyObject *__pyx_t_1 = NULL;
int __pyx_t_2;
int __pyx_t_3;
PyObject *__pyx_t_4 = NULL;
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
__Pyx_RefNannySetupContext("__get__", 0);
/* "View.MemoryView":522
* @cname('__pyx_memoryview_get_shape')
* def __get__(self):
* return tuple([self.view.shape[i] for i in xrange(self.view.ndim)]) # <<<<<<<<<<<<<<
*
* property strides:
*/
__Pyx_XDECREF(__pyx_r);
__pyx_t_1 = PyList_New(0); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 522; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
__pyx_t_2 = __pyx_v_self->view.ndim;
for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) {
__pyx_v_i = __pyx_t_3;
__pyx_t_4 = PyInt_FromSsize_t((__pyx_v_self->view.shape[__pyx_v_i])); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 522; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_4);
if (unlikely(__Pyx_ListComp_Append(__pyx_t_1, (PyObject*)__pyx_t_4))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 522; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
}
__pyx_t_4 = PyList_AsTuple(((PyObject*)__pyx_t_1)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 522; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_4);
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
__pyx_r = __pyx_t_4;
__pyx_t_4 = 0;
goto __pyx_L0;
/* "View.MemoryView":521
* property shape:
* @cname('__pyx_memoryview_get_shape')
* def __get__(self): # <<<<<<<<<<<<<<
* return tuple([self.view.shape[i] for i in xrange(self.view.ndim)])
*
*/
/* function exit code */
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_1);
__Pyx_XDECREF(__pyx_t_4);
__Pyx_AddTraceback("View.MemoryView.memoryview.shape.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename);
__pyx_r = NULL;
__pyx_L0:;
__Pyx_XGIVEREF(__pyx_r);
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "View.MemoryView":526
* property strides:
* @cname('__pyx_memoryview_get_strides')
* def __get__(self): # <<<<<<<<<<<<<<
* if self.view.strides == NULL:
*
*/
/* Python wrapper */
static PyObject *__pyx_memoryview_get_strides(PyObject *__pyx_v_self); /*proto*/
static PyObject *__pyx_memoryview_get_strides(PyObject *__pyx_v_self) {
PyObject *__pyx_r = 0;
__Pyx_RefNannyDeclarations
__Pyx_RefNannySetupContext("__get__ (wrapper)", 0);
__pyx_r = __pyx_memoryview_get_strides_MemoryView_10memoryview_7strides___get__(((struct __pyx_memoryview_obj *)__pyx_v_self));
/* function exit code */
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
static PyObject *__pyx_memoryview_get_strides_MemoryView_10memoryview_7strides___get__(struct __pyx_memoryview_obj *__pyx_v_self) {
int __pyx_v_i;
PyObject *__pyx_r = NULL;
__Pyx_RefNannyDeclarations
int __pyx_t_1;
PyObject *__pyx_t_2 = NULL;
int __pyx_t_3;
int __pyx_t_4;
PyObject *__pyx_t_5 = NULL;
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
__Pyx_RefNannySetupContext("__get__", 0);
/* "View.MemoryView":527
* @cname('__pyx_memoryview_get_strides')
* def __get__(self):
* if self.view.strides == NULL: # <<<<<<<<<<<<<<
*
* raise ValueError("Buffer view does not expose strides")
*/
__pyx_t_1 = ((__pyx_v_self->view.strides == NULL) != 0);
if (__pyx_t_1) {
/* "View.MemoryView":529
* if self.view.strides == NULL:
*
* raise ValueError("Buffer view does not expose strides") # <<<<<<<<<<<<<<
*
* return tuple([self.view.strides[i] for i in xrange(self.view.ndim)])
*/
__pyx_t_2 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__27, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 529; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_2);
__Pyx_Raise(__pyx_t_2, 0, 0, 0);
__Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0;
{__pyx_filename = __pyx_f[2]; __pyx_lineno = 529; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
}
/* "View.MemoryView":531
* raise ValueError("Buffer view does not expose strides")
*
* return tuple([self.view.strides[i] for i in xrange(self.view.ndim)]) # <<<<<<<<<<<<<<
*
* property suboffsets:
*/
__Pyx_XDECREF(__pyx_r);
__pyx_t_2 = PyList_New(0); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 531; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_2);
__pyx_t_3 = __pyx_v_self->view.ndim;
for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) {
__pyx_v_i = __pyx_t_4;
__pyx_t_5 = PyInt_FromSsize_t((__pyx_v_self->view.strides[__pyx_v_i])); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 531; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_5);
if (unlikely(__Pyx_ListComp_Append(__pyx_t_2, (PyObject*)__pyx_t_5))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 531; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0;
}
__pyx_t_5 = PyList_AsTuple(((PyObject*)__pyx_t_2)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 531; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_5);
__Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0;
__pyx_r = __pyx_t_5;
__pyx_t_5 = 0;
goto __pyx_L0;
/* "View.MemoryView":526
* property strides:
* @cname('__pyx_memoryview_get_strides')
* def __get__(self): # <<<<<<<<<<<<<<
* if self.view.strides == NULL:
*
*/
/* function exit code */
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_2);
__Pyx_XDECREF(__pyx_t_5);
__Pyx_AddTraceback("View.MemoryView.memoryview.strides.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename);
__pyx_r = NULL;
__pyx_L0:;
__Pyx_XGIVEREF(__pyx_r);
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "View.MemoryView":535
* property suboffsets:
* @cname('__pyx_memoryview_get_suboffsets')
* def __get__(self): # <<<<<<<<<<<<<<
* if self.view.suboffsets == NULL:
* return [-1] * self.view.ndim
*/
/* Python wrapper */
static PyObject *__pyx_memoryview_get_suboffsets(PyObject *__pyx_v_self); /*proto*/
static PyObject *__pyx_memoryview_get_suboffsets(PyObject *__pyx_v_self) {
PyObject *__pyx_r = 0;
__Pyx_RefNannyDeclarations
__Pyx_RefNannySetupContext("__get__ (wrapper)", 0);
__pyx_r = __pyx_memoryview_get_suboffsets_MemoryView_10memoryview_10suboffsets___get__(((struct __pyx_memoryview_obj *)__pyx_v_self));
/* function exit code */
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
static PyObject *__pyx_memoryview_get_suboffsets_MemoryView_10memoryview_10suboffsets___get__(struct __pyx_memoryview_obj *__pyx_v_self) {
int __pyx_v_i;
PyObject *__pyx_r = NULL;
__Pyx_RefNannyDeclarations
int __pyx_t_1;
PyObject *__pyx_t_2 = NULL;
int __pyx_t_3;
int __pyx_t_4;
PyObject *__pyx_t_5 = NULL;
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
__Pyx_RefNannySetupContext("__get__", 0);
/* "View.MemoryView":536
* @cname('__pyx_memoryview_get_suboffsets')
* def __get__(self):
* if self.view.suboffsets == NULL: # <<<<<<<<<<<<<<
* return [-1] * self.view.ndim
*
*/
__pyx_t_1 = ((__pyx_v_self->view.suboffsets == NULL) != 0);
if (__pyx_t_1) {
/* "View.MemoryView":537
* def __get__(self):
* if self.view.suboffsets == NULL:
* return [-1] * self.view.ndim # <<<<<<<<<<<<<<
*
* return tuple([self.view.suboffsets[i] for i in xrange(self.view.ndim)])
*/
__Pyx_XDECREF(__pyx_r);
__pyx_t_2 = PyList_New(1 * ((__pyx_v_self->view.ndim<0) ? 0:__pyx_v_self->view.ndim)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 537; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_2);
{ Py_ssize_t __pyx_temp;
for (__pyx_temp=0; __pyx_temp < __pyx_v_self->view.ndim; __pyx_temp++) {
__Pyx_INCREF(__pyx_int_neg_1);
PyList_SET_ITEM(__pyx_t_2, __pyx_temp, __pyx_int_neg_1);
__Pyx_GIVEREF(__pyx_int_neg_1);
}
}
__pyx_r = __pyx_t_2;
__pyx_t_2 = 0;
goto __pyx_L0;
}
/* "View.MemoryView":539
* return [-1] * self.view.ndim
*
* return tuple([self.view.suboffsets[i] for i in xrange(self.view.ndim)]) # <<<<<<<<<<<<<<
*
* property ndim:
*/
__Pyx_XDECREF(__pyx_r);
__pyx_t_2 = PyList_New(0); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 539; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_2);
__pyx_t_3 = __pyx_v_self->view.ndim;
for (__pyx_t_4 = 0; __pyx_t_4 < __pyx_t_3; __pyx_t_4+=1) {
__pyx_v_i = __pyx_t_4;
__pyx_t_5 = PyInt_FromSsize_t((__pyx_v_self->view.suboffsets[__pyx_v_i])); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 539; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_5);
if (unlikely(__Pyx_ListComp_Append(__pyx_t_2, (PyObject*)__pyx_t_5))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 539; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0;
}
__pyx_t_5 = PyList_AsTuple(((PyObject*)__pyx_t_2)); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 539; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_5);
__Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0;
__pyx_r = __pyx_t_5;
__pyx_t_5 = 0;
goto __pyx_L0;
/* "View.MemoryView":535
* property suboffsets:
* @cname('__pyx_memoryview_get_suboffsets')
* def __get__(self): # <<<<<<<<<<<<<<
* if self.view.suboffsets == NULL:
* return [-1] * self.view.ndim
*/
/* function exit code */
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_2);
__Pyx_XDECREF(__pyx_t_5);
__Pyx_AddTraceback("View.MemoryView.memoryview.suboffsets.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename);
__pyx_r = NULL;
__pyx_L0:;
__Pyx_XGIVEREF(__pyx_r);
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "View.MemoryView":543
* property ndim:
* @cname('__pyx_memoryview_get_ndim')
* def __get__(self): # <<<<<<<<<<<<<<
* return self.view.ndim
*
*/
/* Python wrapper */
static PyObject *__pyx_memoryview_get_ndim(PyObject *__pyx_v_self); /*proto*/
static PyObject *__pyx_memoryview_get_ndim(PyObject *__pyx_v_self) {
PyObject *__pyx_r = 0;
__Pyx_RefNannyDeclarations
__Pyx_RefNannySetupContext("__get__ (wrapper)", 0);
__pyx_r = __pyx_memoryview_get_ndim_MemoryView_10memoryview_4ndim___get__(((struct __pyx_memoryview_obj *)__pyx_v_self));
/* function exit code */
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
static PyObject *__pyx_memoryview_get_ndim_MemoryView_10memoryview_4ndim___get__(struct __pyx_memoryview_obj *__pyx_v_self) {
PyObject *__pyx_r = NULL;
__Pyx_RefNannyDeclarations
PyObject *__pyx_t_1 = NULL;
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
__Pyx_RefNannySetupContext("__get__", 0);
/* "View.MemoryView":544
* @cname('__pyx_memoryview_get_ndim')
* def __get__(self):
* return self.view.ndim # <<<<<<<<<<<<<<
*
* property itemsize:
*/
__Pyx_XDECREF(__pyx_r);
__pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_self->view.ndim); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 544; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
__pyx_r = __pyx_t_1;
__pyx_t_1 = 0;
goto __pyx_L0;
/* "View.MemoryView":543
* property ndim:
* @cname('__pyx_memoryview_get_ndim')
* def __get__(self): # <<<<<<<<<<<<<<
* return self.view.ndim
*
*/
/* function exit code */
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_1);
__Pyx_AddTraceback("View.MemoryView.memoryview.ndim.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename);
__pyx_r = NULL;
__pyx_L0:;
__Pyx_XGIVEREF(__pyx_r);
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "View.MemoryView":548
* property itemsize:
* @cname('__pyx_memoryview_get_itemsize')
* def __get__(self): # <<<<<<<<<<<<<<
* return self.view.itemsize
*
*/
/* Python wrapper */
static PyObject *__pyx_memoryview_get_itemsize(PyObject *__pyx_v_self); /*proto*/
static PyObject *__pyx_memoryview_get_itemsize(PyObject *__pyx_v_self) {
PyObject *__pyx_r = 0;
__Pyx_RefNannyDeclarations
__Pyx_RefNannySetupContext("__get__ (wrapper)", 0);
__pyx_r = __pyx_memoryview_get_itemsize_MemoryView_10memoryview_8itemsize___get__(((struct __pyx_memoryview_obj *)__pyx_v_self));
/* function exit code */
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
static PyObject *__pyx_memoryview_get_itemsize_MemoryView_10memoryview_8itemsize___get__(struct __pyx_memoryview_obj *__pyx_v_self) {
PyObject *__pyx_r = NULL;
__Pyx_RefNannyDeclarations
PyObject *__pyx_t_1 = NULL;
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
__Pyx_RefNannySetupContext("__get__", 0);
/* "View.MemoryView":549
* @cname('__pyx_memoryview_get_itemsize')
* def __get__(self):
* return self.view.itemsize # <<<<<<<<<<<<<<
*
* property nbytes:
*/
__Pyx_XDECREF(__pyx_r);
__pyx_t_1 = PyInt_FromSsize_t(__pyx_v_self->view.itemsize); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 549; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
__pyx_r = __pyx_t_1;
__pyx_t_1 = 0;
goto __pyx_L0;
/* "View.MemoryView":548
* property itemsize:
* @cname('__pyx_memoryview_get_itemsize')
* def __get__(self): # <<<<<<<<<<<<<<
* return self.view.itemsize
*
*/
/* function exit code */
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_1);
__Pyx_AddTraceback("View.MemoryView.memoryview.itemsize.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename);
__pyx_r = NULL;
__pyx_L0:;
__Pyx_XGIVEREF(__pyx_r);
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "View.MemoryView":553
* property nbytes:
* @cname('__pyx_memoryview_get_nbytes')
* def __get__(self): # <<<<<<<<<<<<<<
* return self.size * self.view.itemsize
*
*/
/* Python wrapper */
static PyObject *__pyx_memoryview_get_nbytes(PyObject *__pyx_v_self); /*proto*/
static PyObject *__pyx_memoryview_get_nbytes(PyObject *__pyx_v_self) {
PyObject *__pyx_r = 0;
__Pyx_RefNannyDeclarations
__Pyx_RefNannySetupContext("__get__ (wrapper)", 0);
__pyx_r = __pyx_memoryview_get_nbytes_MemoryView_10memoryview_6nbytes___get__(((struct __pyx_memoryview_obj *)__pyx_v_self));
/* function exit code */
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
static PyObject *__pyx_memoryview_get_nbytes_MemoryView_10memoryview_6nbytes___get__(struct __pyx_memoryview_obj *__pyx_v_self) {
PyObject *__pyx_r = NULL;
__Pyx_RefNannyDeclarations
PyObject *__pyx_t_1 = NULL;
PyObject *__pyx_t_2 = NULL;
PyObject *__pyx_t_3 = NULL;
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
__Pyx_RefNannySetupContext("__get__", 0);
/* "View.MemoryView":554
* @cname('__pyx_memoryview_get_nbytes')
* def __get__(self):
* return self.size * self.view.itemsize # <<<<<<<<<<<<<<
*
* property size:
*/
__Pyx_XDECREF(__pyx_r);
__pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_size); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 554; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
__pyx_t_2 = PyInt_FromSsize_t(__pyx_v_self->view.itemsize); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 554; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_2);
__pyx_t_3 = PyNumber_Multiply(__pyx_t_1, __pyx_t_2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 554; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_3);
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
__Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0;
__pyx_r = __pyx_t_3;
__pyx_t_3 = 0;
goto __pyx_L0;
/* "View.MemoryView":553
* property nbytes:
* @cname('__pyx_memoryview_get_nbytes')
* def __get__(self): # <<<<<<<<<<<<<<
* return self.size * self.view.itemsize
*
*/
/* function exit code */
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_1);
__Pyx_XDECREF(__pyx_t_2);
__Pyx_XDECREF(__pyx_t_3);
__Pyx_AddTraceback("View.MemoryView.memoryview.nbytes.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename);
__pyx_r = NULL;
__pyx_L0:;
__Pyx_XGIVEREF(__pyx_r);
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "View.MemoryView":558
* property size:
* @cname('__pyx_memoryview_get_size')
* def __get__(self): # <<<<<<<<<<<<<<
* if self._size is None:
* result = 1
*/
/* Python wrapper */
static PyObject *__pyx_memoryview_get_size(PyObject *__pyx_v_self); /*proto*/
static PyObject *__pyx_memoryview_get_size(PyObject *__pyx_v_self) {
PyObject *__pyx_r = 0;
__Pyx_RefNannyDeclarations
__Pyx_RefNannySetupContext("__get__ (wrapper)", 0);
__pyx_r = __pyx_memoryview_get_size_MemoryView_10memoryview_4size___get__(((struct __pyx_memoryview_obj *)__pyx_v_self));
/* function exit code */
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
static PyObject *__pyx_memoryview_get_size_MemoryView_10memoryview_4size___get__(struct __pyx_memoryview_obj *__pyx_v_self) {
PyObject *__pyx_v_result = NULL;
PyObject *__pyx_v_length = NULL;
PyObject *__pyx_r = NULL;
__Pyx_RefNannyDeclarations
int __pyx_t_1;
int __pyx_t_2;
PyObject *__pyx_t_3 = NULL;
PyObject *__pyx_t_4 = NULL;
Py_ssize_t __pyx_t_5;
PyObject *(*__pyx_t_6)(PyObject *);
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
__Pyx_RefNannySetupContext("__get__", 0);
/* "View.MemoryView":559
* @cname('__pyx_memoryview_get_size')
* def __get__(self):
* if self._size is None: # <<<<<<<<<<<<<<
* result = 1
*
*/
__pyx_t_1 = (__pyx_v_self->_size == Py_None);
__pyx_t_2 = (__pyx_t_1 != 0);
if (__pyx_t_2) {
/* "View.MemoryView":560
* def __get__(self):
* if self._size is None:
* result = 1 # <<<<<<<<<<<<<<
*
* for length in self.shape:
*/
__Pyx_INCREF(__pyx_int_1);
__pyx_v_result = __pyx_int_1;
/* "View.MemoryView":562
* result = 1
*
* for length in self.shape: # <<<<<<<<<<<<<<
* result *= length
*
*/
__pyx_t_3 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_shape); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 562; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_3);
if (PyList_CheckExact(__pyx_t_3) || PyTuple_CheckExact(__pyx_t_3)) {
__pyx_t_4 = __pyx_t_3; __Pyx_INCREF(__pyx_t_4); __pyx_t_5 = 0;
__pyx_t_6 = NULL;
} else {
__pyx_t_5 = -1; __pyx_t_4 = PyObject_GetIter(__pyx_t_3); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 562; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_4);
__pyx_t_6 = Py_TYPE(__pyx_t_4)->tp_iternext;
}
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
for (;;) {
if (!__pyx_t_6 && PyList_CheckExact(__pyx_t_4)) {
if (__pyx_t_5 >= PyList_GET_SIZE(__pyx_t_4)) break;
#if CYTHON_COMPILING_IN_CPYTHON
__pyx_t_3 = PyList_GET_ITEM(__pyx_t_4, __pyx_t_5); __Pyx_INCREF(__pyx_t_3); __pyx_t_5++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 562; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
#else
__pyx_t_3 = PySequence_ITEM(__pyx_t_4, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 562; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
#endif
} else if (!__pyx_t_6 && PyTuple_CheckExact(__pyx_t_4)) {
if (__pyx_t_5 >= PyTuple_GET_SIZE(__pyx_t_4)) break;
#if CYTHON_COMPILING_IN_CPYTHON
__pyx_t_3 = PyTuple_GET_ITEM(__pyx_t_4, __pyx_t_5); __Pyx_INCREF(__pyx_t_3); __pyx_t_5++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 562; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
#else
__pyx_t_3 = PySequence_ITEM(__pyx_t_4, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 562; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
#endif
} else {
__pyx_t_3 = __pyx_t_6(__pyx_t_4);
if (unlikely(!__pyx_t_3)) {
PyObject* exc_type = PyErr_Occurred();
if (exc_type) {
if (likely(exc_type == PyExc_StopIteration || PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear();
else {__pyx_filename = __pyx_f[2]; __pyx_lineno = 562; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
}
break;
}
__Pyx_GOTREF(__pyx_t_3);
}
__Pyx_XDECREF_SET(__pyx_v_length, __pyx_t_3);
__pyx_t_3 = 0;
/* "View.MemoryView":563
*
* for length in self.shape:
* result *= length # <<<<<<<<<<<<<<
*
* self._size = result
*/
__pyx_t_3 = PyNumber_InPlaceMultiply(__pyx_v_result, __pyx_v_length); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 563; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_3);
__Pyx_DECREF_SET(__pyx_v_result, __pyx_t_3);
__pyx_t_3 = 0;
}
__Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
/* "View.MemoryView":565
* result *= length
*
* self._size = result # <<<<<<<<<<<<<<
*
* return self._size
*/
__Pyx_INCREF(__pyx_v_result);
__Pyx_GIVEREF(__pyx_v_result);
__Pyx_GOTREF(__pyx_v_self->_size);
__Pyx_DECREF(__pyx_v_self->_size);
__pyx_v_self->_size = __pyx_v_result;
goto __pyx_L3;
}
__pyx_L3:;
/* "View.MemoryView":567
* self._size = result
*
* return self._size # <<<<<<<<<<<<<<
*
* def __len__(self):
*/
__Pyx_XDECREF(__pyx_r);
__Pyx_INCREF(__pyx_v_self->_size);
__pyx_r = __pyx_v_self->_size;
goto __pyx_L0;
/* "View.MemoryView":558
* property size:
* @cname('__pyx_memoryview_get_size')
* def __get__(self): # <<<<<<<<<<<<<<
* if self._size is None:
* result = 1
*/
/* function exit code */
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_3);
__Pyx_XDECREF(__pyx_t_4);
__Pyx_AddTraceback("View.MemoryView.memoryview.size.__get__", __pyx_clineno, __pyx_lineno, __pyx_filename);
__pyx_r = NULL;
__pyx_L0:;
__Pyx_XDECREF(__pyx_v_result);
__Pyx_XDECREF(__pyx_v_length);
__Pyx_XGIVEREF(__pyx_r);
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "View.MemoryView":569
* return self._size
*
* def __len__(self): # <<<<<<<<<<<<<<
* if self.view.ndim >= 1:
* return self.view.shape[0]
*/
/* Python wrapper */
static Py_ssize_t __pyx_memoryview___len__(PyObject *__pyx_v_self); /*proto*/
static Py_ssize_t __pyx_memoryview___len__(PyObject *__pyx_v_self) {
Py_ssize_t __pyx_r;
__Pyx_RefNannyDeclarations
__Pyx_RefNannySetupContext("__len__ (wrapper)", 0);
__pyx_r = __pyx_memoryview_MemoryView_10memoryview_10__len__(((struct __pyx_memoryview_obj *)__pyx_v_self));
/* function exit code */
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
static Py_ssize_t __pyx_memoryview_MemoryView_10memoryview_10__len__(struct __pyx_memoryview_obj *__pyx_v_self) {
Py_ssize_t __pyx_r;
__Pyx_RefNannyDeclarations
int __pyx_t_1;
__Pyx_RefNannySetupContext("__len__", 0);
/* "View.MemoryView":570
*
* def __len__(self):
* if self.view.ndim >= 1: # <<<<<<<<<<<<<<
* return self.view.shape[0]
*
*/
__pyx_t_1 = ((__pyx_v_self->view.ndim >= 1) != 0);
if (__pyx_t_1) {
/* "View.MemoryView":571
* def __len__(self):
* if self.view.ndim >= 1:
* return self.view.shape[0] # <<<<<<<<<<<<<<
*
* return 0
*/
__pyx_r = (__pyx_v_self->view.shape[0]);
goto __pyx_L0;
}
/* "View.MemoryView":573
* return self.view.shape[0]
*
* return 0 # <<<<<<<<<<<<<<
*
* def __repr__(self):
*/
__pyx_r = 0;
goto __pyx_L0;
/* "View.MemoryView":569
* return self._size
*
* def __len__(self): # <<<<<<<<<<<<<<
* if self.view.ndim >= 1:
* return self.view.shape[0]
*/
/* function exit code */
__pyx_L0:;
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "View.MemoryView":575
* return 0
*
* def __repr__(self): # <<<<<<<<<<<<<<
* return "<MemoryView of %r at 0x%x>" % (self.base.__class__.__name__,
* id(self))
*/
/* Python wrapper */
static PyObject *__pyx_memoryview___repr__(PyObject *__pyx_v_self); /*proto*/
static PyObject *__pyx_memoryview___repr__(PyObject *__pyx_v_self) {
PyObject *__pyx_r = 0;
__Pyx_RefNannyDeclarations
__Pyx_RefNannySetupContext("__repr__ (wrapper)", 0);
__pyx_r = __pyx_memoryview_MemoryView_10memoryview_12__repr__(((struct __pyx_memoryview_obj *)__pyx_v_self));
/* function exit code */
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
static PyObject *__pyx_memoryview_MemoryView_10memoryview_12__repr__(struct __pyx_memoryview_obj *__pyx_v_self) {
PyObject *__pyx_r = NULL;
__Pyx_RefNannyDeclarations
PyObject *__pyx_t_1 = NULL;
PyObject *__pyx_t_2 = NULL;
PyObject *__pyx_t_3 = NULL;
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
__Pyx_RefNannySetupContext("__repr__", 0);
/* "View.MemoryView":576
*
* def __repr__(self):
* return "<MemoryView of %r at 0x%x>" % (self.base.__class__.__name__, # <<<<<<<<<<<<<<
* id(self))
*
*/
__Pyx_XDECREF(__pyx_r);
__pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_base); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 576; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
__pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_class); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 576; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_2);
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
__pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_name_2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 576; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
__Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0;
/* "View.MemoryView":577
* def __repr__(self):
* return "<MemoryView of %r at 0x%x>" % (self.base.__class__.__name__,
* id(self)) # <<<<<<<<<<<<<<
*
* def __str__(self):
*/
__pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 577; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_2);
__Pyx_INCREF(((PyObject *)__pyx_v_self));
PyTuple_SET_ITEM(__pyx_t_2, 0, ((PyObject *)__pyx_v_self));
__Pyx_GIVEREF(((PyObject *)__pyx_v_self));
__pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_id, __pyx_t_2, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 577; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_3);
__Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0;
/* "View.MemoryView":576
*
* def __repr__(self):
* return "<MemoryView of %r at 0x%x>" % (self.base.__class__.__name__, # <<<<<<<<<<<<<<
* id(self))
*
*/
__pyx_t_2 = PyTuple_New(2); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 576; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_2);
PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_1);
__Pyx_GIVEREF(__pyx_t_1);
PyTuple_SET_ITEM(__pyx_t_2, 1, __pyx_t_3);
__Pyx_GIVEREF(__pyx_t_3);
__pyx_t_1 = 0;
__pyx_t_3 = 0;
__pyx_t_3 = __Pyx_PyString_Format(__pyx_kp_s_MemoryView_of_r_at_0x_x, __pyx_t_2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 576; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_3);
__Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0;
__pyx_r = __pyx_t_3;
__pyx_t_3 = 0;
goto __pyx_L0;
/* "View.MemoryView":575
* return 0
*
* def __repr__(self): # <<<<<<<<<<<<<<
* return "<MemoryView of %r at 0x%x>" % (self.base.__class__.__name__,
* id(self))
*/
/* function exit code */
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_1);
__Pyx_XDECREF(__pyx_t_2);
__Pyx_XDECREF(__pyx_t_3);
__Pyx_AddTraceback("View.MemoryView.memoryview.__repr__", __pyx_clineno, __pyx_lineno, __pyx_filename);
__pyx_r = NULL;
__pyx_L0:;
__Pyx_XGIVEREF(__pyx_r);
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "View.MemoryView":579
* id(self))
*
* def __str__(self): # <<<<<<<<<<<<<<
* return "<MemoryView of %r object>" % (self.base.__class__.__name__,)
*
*/
/* Python wrapper */
static PyObject *__pyx_memoryview___str__(PyObject *__pyx_v_self); /*proto*/
static PyObject *__pyx_memoryview___str__(PyObject *__pyx_v_self) {
PyObject *__pyx_r = 0;
__Pyx_RefNannyDeclarations
__Pyx_RefNannySetupContext("__str__ (wrapper)", 0);
__pyx_r = __pyx_memoryview_MemoryView_10memoryview_14__str__(((struct __pyx_memoryview_obj *)__pyx_v_self));
/* function exit code */
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
static PyObject *__pyx_memoryview_MemoryView_10memoryview_14__str__(struct __pyx_memoryview_obj *__pyx_v_self) {
PyObject *__pyx_r = NULL;
__Pyx_RefNannyDeclarations
PyObject *__pyx_t_1 = NULL;
PyObject *__pyx_t_2 = NULL;
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
__Pyx_RefNannySetupContext("__str__", 0);
/* "View.MemoryView":580
*
* def __str__(self):
* return "<MemoryView of %r object>" % (self.base.__class__.__name__,) # <<<<<<<<<<<<<<
*
*
*/
__Pyx_XDECREF(__pyx_r);
__pyx_t_1 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_self), __pyx_n_s_base); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 580; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
__pyx_t_2 = __Pyx_PyObject_GetAttrStr(__pyx_t_1, __pyx_n_s_class); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 580; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_2);
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
__pyx_t_1 = __Pyx_PyObject_GetAttrStr(__pyx_t_2, __pyx_n_s_name_2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 580; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
__Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0;
__pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 580; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_2);
PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_1);
__Pyx_GIVEREF(__pyx_t_1);
__pyx_t_1 = 0;
__pyx_t_1 = __Pyx_PyString_Format(__pyx_kp_s_MemoryView_of_r_object, __pyx_t_2); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 580; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
__Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0;
__pyx_r = __pyx_t_1;
__pyx_t_1 = 0;
goto __pyx_L0;
/* "View.MemoryView":579
* id(self))
*
* def __str__(self): # <<<<<<<<<<<<<<
* return "<MemoryView of %r object>" % (self.base.__class__.__name__,)
*
*/
/* function exit code */
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_1);
__Pyx_XDECREF(__pyx_t_2);
__Pyx_AddTraceback("View.MemoryView.memoryview.__str__", __pyx_clineno, __pyx_lineno, __pyx_filename);
__pyx_r = NULL;
__pyx_L0:;
__Pyx_XGIVEREF(__pyx_r);
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "View.MemoryView":583
*
*
* def is_c_contig(self): # <<<<<<<<<<<<<<
* cdef __Pyx_memviewslice *mslice
* cdef __Pyx_memviewslice tmp
*/
/* Python wrapper */
static PyObject *__pyx_memoryview_is_c_contig(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/
static PyObject *__pyx_memoryview_is_c_contig(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) {
PyObject *__pyx_r = 0;
__Pyx_RefNannyDeclarations
__Pyx_RefNannySetupContext("is_c_contig (wrapper)", 0);
__pyx_r = __pyx_memoryview_MemoryView_10memoryview_16is_c_contig(((struct __pyx_memoryview_obj *)__pyx_v_self));
/* function exit code */
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
static PyObject *__pyx_memoryview_MemoryView_10memoryview_16is_c_contig(struct __pyx_memoryview_obj *__pyx_v_self) {
__Pyx_memviewslice *__pyx_v_mslice;
__Pyx_memviewslice __pyx_v_tmp;
PyObject *__pyx_r = NULL;
__Pyx_RefNannyDeclarations
PyObject *__pyx_t_1 = NULL;
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
__Pyx_RefNannySetupContext("is_c_contig", 0);
/* "View.MemoryView":586
* cdef __Pyx_memviewslice *mslice
* cdef __Pyx_memviewslice tmp
* mslice = get_slice_from_memview(self, &tmp) # <<<<<<<<<<<<<<
* return slice_is_contig(mslice, 'C', self.view.ndim)
*
*/
__pyx_v_mslice = __pyx_memoryview_get_slice_from_memoryview(__pyx_v_self, (&__pyx_v_tmp));
/* "View.MemoryView":587
* cdef __Pyx_memviewslice tmp
* mslice = get_slice_from_memview(self, &tmp)
* return slice_is_contig(mslice, 'C', self.view.ndim) # <<<<<<<<<<<<<<
*
* def is_f_contig(self):
*/
__Pyx_XDECREF(__pyx_r);
__pyx_t_1 = __Pyx_PyBool_FromLong(__pyx_memviewslice_is_contig(__pyx_v_mslice, 'C', __pyx_v_self->view.ndim)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 587; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
__pyx_r = __pyx_t_1;
__pyx_t_1 = 0;
goto __pyx_L0;
/* "View.MemoryView":583
*
*
* def is_c_contig(self): # <<<<<<<<<<<<<<
* cdef __Pyx_memviewslice *mslice
* cdef __Pyx_memviewslice tmp
*/
/* function exit code */
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_1);
__Pyx_AddTraceback("View.MemoryView.memoryview.is_c_contig", __pyx_clineno, __pyx_lineno, __pyx_filename);
__pyx_r = NULL;
__pyx_L0:;
__Pyx_XGIVEREF(__pyx_r);
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "View.MemoryView":589
* return slice_is_contig(mslice, 'C', self.view.ndim)
*
* def is_f_contig(self): # <<<<<<<<<<<<<<
* cdef __Pyx_memviewslice *mslice
* cdef __Pyx_memviewslice tmp
*/
/* Python wrapper */
static PyObject *__pyx_memoryview_is_f_contig(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/
static PyObject *__pyx_memoryview_is_f_contig(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) {
PyObject *__pyx_r = 0;
__Pyx_RefNannyDeclarations
__Pyx_RefNannySetupContext("is_f_contig (wrapper)", 0);
__pyx_r = __pyx_memoryview_MemoryView_10memoryview_18is_f_contig(((struct __pyx_memoryview_obj *)__pyx_v_self));
/* function exit code */
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
static PyObject *__pyx_memoryview_MemoryView_10memoryview_18is_f_contig(struct __pyx_memoryview_obj *__pyx_v_self) {
__Pyx_memviewslice *__pyx_v_mslice;
__Pyx_memviewslice __pyx_v_tmp;
PyObject *__pyx_r = NULL;
__Pyx_RefNannyDeclarations
PyObject *__pyx_t_1 = NULL;
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
__Pyx_RefNannySetupContext("is_f_contig", 0);
/* "View.MemoryView":592
* cdef __Pyx_memviewslice *mslice
* cdef __Pyx_memviewslice tmp
* mslice = get_slice_from_memview(self, &tmp) # <<<<<<<<<<<<<<
* return slice_is_contig(mslice, 'F', self.view.ndim)
*
*/
__pyx_v_mslice = __pyx_memoryview_get_slice_from_memoryview(__pyx_v_self, (&__pyx_v_tmp));
/* "View.MemoryView":593
* cdef __Pyx_memviewslice tmp
* mslice = get_slice_from_memview(self, &tmp)
* return slice_is_contig(mslice, 'F', self.view.ndim) # <<<<<<<<<<<<<<
*
* def copy(self):
*/
__Pyx_XDECREF(__pyx_r);
__pyx_t_1 = __Pyx_PyBool_FromLong(__pyx_memviewslice_is_contig(__pyx_v_mslice, 'F', __pyx_v_self->view.ndim)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 593; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
__pyx_r = __pyx_t_1;
__pyx_t_1 = 0;
goto __pyx_L0;
/* "View.MemoryView":589
* return slice_is_contig(mslice, 'C', self.view.ndim)
*
* def is_f_contig(self): # <<<<<<<<<<<<<<
* cdef __Pyx_memviewslice *mslice
* cdef __Pyx_memviewslice tmp
*/
/* function exit code */
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_1);
__Pyx_AddTraceback("View.MemoryView.memoryview.is_f_contig", __pyx_clineno, __pyx_lineno, __pyx_filename);
__pyx_r = NULL;
__pyx_L0:;
__Pyx_XGIVEREF(__pyx_r);
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "View.MemoryView":595
* return slice_is_contig(mslice, 'F', self.view.ndim)
*
* def copy(self): # <<<<<<<<<<<<<<
* cdef __Pyx_memviewslice mslice
* cdef int flags = self.flags & ~PyBUF_F_CONTIGUOUS
*/
/* Python wrapper */
static PyObject *__pyx_memoryview_copy(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/
static PyObject *__pyx_memoryview_copy(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) {
PyObject *__pyx_r = 0;
__Pyx_RefNannyDeclarations
__Pyx_RefNannySetupContext("copy (wrapper)", 0);
__pyx_r = __pyx_memoryview_MemoryView_10memoryview_20copy(((struct __pyx_memoryview_obj *)__pyx_v_self));
/* function exit code */
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
static PyObject *__pyx_memoryview_MemoryView_10memoryview_20copy(struct __pyx_memoryview_obj *__pyx_v_self) {
__Pyx_memviewslice __pyx_v_mslice;
int __pyx_v_flags;
PyObject *__pyx_r = NULL;
__Pyx_RefNannyDeclarations
__Pyx_memviewslice __pyx_t_1;
PyObject *__pyx_t_2 = NULL;
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
__Pyx_RefNannySetupContext("copy", 0);
/* "View.MemoryView":597
* def copy(self):
* cdef __Pyx_memviewslice mslice
* cdef int flags = self.flags & ~PyBUF_F_CONTIGUOUS # <<<<<<<<<<<<<<
*
* slice_copy(self, &mslice)
*/
__pyx_v_flags = (__pyx_v_self->flags & (~PyBUF_F_CONTIGUOUS));
/* "View.MemoryView":599
* cdef int flags = self.flags & ~PyBUF_F_CONTIGUOUS
*
* slice_copy(self, &mslice) # <<<<<<<<<<<<<<
* mslice = slice_copy_contig(&mslice, "c", self.view.ndim,
* self.view.itemsize,
*/
__pyx_memoryview_slice_copy(__pyx_v_self, (&__pyx_v_mslice));
/* "View.MemoryView":600
*
* slice_copy(self, &mslice)
* mslice = slice_copy_contig(&mslice, "c", self.view.ndim, # <<<<<<<<<<<<<<
* self.view.itemsize,
* flags|PyBUF_C_CONTIGUOUS,
*/
__pyx_t_1 = __pyx_memoryview_copy_new_contig((&__pyx_v_mslice), __pyx_k_c, __pyx_v_self->view.ndim, __pyx_v_self->view.itemsize, (__pyx_v_flags | PyBUF_C_CONTIGUOUS), __pyx_v_self->dtype_is_object); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 600; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_v_mslice = __pyx_t_1;
/* "View.MemoryView":605
* self.dtype_is_object)
*
* return memoryview_copy_from_slice(self, &mslice) # <<<<<<<<<<<<<<
*
* def copy_fortran(self):
*/
__Pyx_XDECREF(__pyx_r);
__pyx_t_2 = __pyx_memoryview_copy_object_from_slice(__pyx_v_self, (&__pyx_v_mslice)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 605; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_2);
__pyx_r = __pyx_t_2;
__pyx_t_2 = 0;
goto __pyx_L0;
/* "View.MemoryView":595
* return slice_is_contig(mslice, 'F', self.view.ndim)
*
* def copy(self): # <<<<<<<<<<<<<<
* cdef __Pyx_memviewslice mslice
* cdef int flags = self.flags & ~PyBUF_F_CONTIGUOUS
*/
/* function exit code */
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_2);
__Pyx_AddTraceback("View.MemoryView.memoryview.copy", __pyx_clineno, __pyx_lineno, __pyx_filename);
__pyx_r = NULL;
__pyx_L0:;
__Pyx_XGIVEREF(__pyx_r);
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "View.MemoryView":607
* return memoryview_copy_from_slice(self, &mslice)
*
* def copy_fortran(self): # <<<<<<<<<<<<<<
* cdef __Pyx_memviewslice src, dst
* cdef int flags = self.flags & ~PyBUF_C_CONTIGUOUS
*/
/* Python wrapper */
static PyObject *__pyx_memoryview_copy_fortran(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused); /*proto*/
static PyObject *__pyx_memoryview_copy_fortran(PyObject *__pyx_v_self, CYTHON_UNUSED PyObject *unused) {
PyObject *__pyx_r = 0;
__Pyx_RefNannyDeclarations
__Pyx_RefNannySetupContext("copy_fortran (wrapper)", 0);
__pyx_r = __pyx_memoryview_MemoryView_10memoryview_22copy_fortran(((struct __pyx_memoryview_obj *)__pyx_v_self));
/* function exit code */
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
static PyObject *__pyx_memoryview_MemoryView_10memoryview_22copy_fortran(struct __pyx_memoryview_obj *__pyx_v_self) {
__Pyx_memviewslice __pyx_v_src;
__Pyx_memviewslice __pyx_v_dst;
int __pyx_v_flags;
PyObject *__pyx_r = NULL;
__Pyx_RefNannyDeclarations
__Pyx_memviewslice __pyx_t_1;
PyObject *__pyx_t_2 = NULL;
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
__Pyx_RefNannySetupContext("copy_fortran", 0);
/* "View.MemoryView":609
* def copy_fortran(self):
* cdef __Pyx_memviewslice src, dst
* cdef int flags = self.flags & ~PyBUF_C_CONTIGUOUS # <<<<<<<<<<<<<<
*
* slice_copy(self, &src)
*/
__pyx_v_flags = (__pyx_v_self->flags & (~PyBUF_C_CONTIGUOUS));
/* "View.MemoryView":611
* cdef int flags = self.flags & ~PyBUF_C_CONTIGUOUS
*
* slice_copy(self, &src) # <<<<<<<<<<<<<<
* dst = slice_copy_contig(&src, "fortran", self.view.ndim,
* self.view.itemsize,
*/
__pyx_memoryview_slice_copy(__pyx_v_self, (&__pyx_v_src));
/* "View.MemoryView":612
*
* slice_copy(self, &src)
* dst = slice_copy_contig(&src, "fortran", self.view.ndim, # <<<<<<<<<<<<<<
* self.view.itemsize,
* flags|PyBUF_F_CONTIGUOUS,
*/
__pyx_t_1 = __pyx_memoryview_copy_new_contig((&__pyx_v_src), __pyx_k_fortran, __pyx_v_self->view.ndim, __pyx_v_self->view.itemsize, (__pyx_v_flags | PyBUF_F_CONTIGUOUS), __pyx_v_self->dtype_is_object); if (unlikely(PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 612; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_v_dst = __pyx_t_1;
/* "View.MemoryView":617
* self.dtype_is_object)
*
* return memoryview_copy_from_slice(self, &dst) # <<<<<<<<<<<<<<
*
*
*/
__Pyx_XDECREF(__pyx_r);
__pyx_t_2 = __pyx_memoryview_copy_object_from_slice(__pyx_v_self, (&__pyx_v_dst)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 617; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_2);
__pyx_r = __pyx_t_2;
__pyx_t_2 = 0;
goto __pyx_L0;
/* "View.MemoryView":607
* return memoryview_copy_from_slice(self, &mslice)
*
* def copy_fortran(self): # <<<<<<<<<<<<<<
* cdef __Pyx_memviewslice src, dst
* cdef int flags = self.flags & ~PyBUF_C_CONTIGUOUS
*/
/* function exit code */
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_2);
__Pyx_AddTraceback("View.MemoryView.memoryview.copy_fortran", __pyx_clineno, __pyx_lineno, __pyx_filename);
__pyx_r = NULL;
__pyx_L0:;
__Pyx_XGIVEREF(__pyx_r);
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "View.MemoryView":621
*
* @cname('__pyx_memoryview_new')
* cdef memoryview_cwrapper(object o, int flags, bint dtype_is_object, __Pyx_TypeInfo *typeinfo): # <<<<<<<<<<<<<<
* cdef memoryview result = memoryview(o, flags, dtype_is_object)
* result.typeinfo = typeinfo
*/
static PyObject *__pyx_memoryview_new(PyObject *__pyx_v_o, int __pyx_v_flags, int __pyx_v_dtype_is_object, __Pyx_TypeInfo *__pyx_v_typeinfo) {
struct __pyx_memoryview_obj *__pyx_v_result = 0;
PyObject *__pyx_r = NULL;
__Pyx_RefNannyDeclarations
PyObject *__pyx_t_1 = NULL;
PyObject *__pyx_t_2 = NULL;
PyObject *__pyx_t_3 = NULL;
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
__Pyx_RefNannySetupContext("memoryview_cwrapper", 0);
/* "View.MemoryView":622
* @cname('__pyx_memoryview_new')
* cdef memoryview_cwrapper(object o, int flags, bint dtype_is_object, __Pyx_TypeInfo *typeinfo):
* cdef memoryview result = memoryview(o, flags, dtype_is_object) # <<<<<<<<<<<<<<
* result.typeinfo = typeinfo
* return result
*/
__pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_flags); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 622; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
__pyx_t_2 = __Pyx_PyBool_FromLong(__pyx_v_dtype_is_object); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 622; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_2);
__pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 622; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_3);
__Pyx_INCREF(__pyx_v_o);
PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_o);
__Pyx_GIVEREF(__pyx_v_o);
PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_1);
__Pyx_GIVEREF(__pyx_t_1);
PyTuple_SET_ITEM(__pyx_t_3, 2, __pyx_t_2);
__Pyx_GIVEREF(__pyx_t_2);
__pyx_t_1 = 0;
__pyx_t_2 = 0;
__pyx_t_2 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_memoryview_type)), __pyx_t_3, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 622; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_2);
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
__pyx_v_result = ((struct __pyx_memoryview_obj *)__pyx_t_2);
__pyx_t_2 = 0;
/* "View.MemoryView":623
* cdef memoryview_cwrapper(object o, int flags, bint dtype_is_object, __Pyx_TypeInfo *typeinfo):
* cdef memoryview result = memoryview(o, flags, dtype_is_object)
* result.typeinfo = typeinfo # <<<<<<<<<<<<<<
* return result
*
*/
__pyx_v_result->typeinfo = __pyx_v_typeinfo;
/* "View.MemoryView":624
* cdef memoryview result = memoryview(o, flags, dtype_is_object)
* result.typeinfo = typeinfo
* return result # <<<<<<<<<<<<<<
*
* @cname('__pyx_memoryview_check')
*/
__Pyx_XDECREF(__pyx_r);
__Pyx_INCREF(((PyObject *)__pyx_v_result));
__pyx_r = ((PyObject *)__pyx_v_result);
goto __pyx_L0;
/* "View.MemoryView":621
*
* @cname('__pyx_memoryview_new')
* cdef memoryview_cwrapper(object o, int flags, bint dtype_is_object, __Pyx_TypeInfo *typeinfo): # <<<<<<<<<<<<<<
* cdef memoryview result = memoryview(o, flags, dtype_is_object)
* result.typeinfo = typeinfo
*/
/* function exit code */
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_1);
__Pyx_XDECREF(__pyx_t_2);
__Pyx_XDECREF(__pyx_t_3);
__Pyx_AddTraceback("View.MemoryView.memoryview_cwrapper", __pyx_clineno, __pyx_lineno, __pyx_filename);
__pyx_r = 0;
__pyx_L0:;
__Pyx_XDECREF((PyObject *)__pyx_v_result);
__Pyx_XGIVEREF(__pyx_r);
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "View.MemoryView":627
*
* @cname('__pyx_memoryview_check')
* cdef inline bint memoryview_check(object o): # <<<<<<<<<<<<<<
* return isinstance(o, memoryview)
*
*/
static CYTHON_INLINE int __pyx_memoryview_check(PyObject *__pyx_v_o) {
int __pyx_r;
__Pyx_RefNannyDeclarations
int __pyx_t_1;
__Pyx_RefNannySetupContext("memoryview_check", 0);
/* "View.MemoryView":628
* @cname('__pyx_memoryview_check')
* cdef inline bint memoryview_check(object o):
* return isinstance(o, memoryview) # <<<<<<<<<<<<<<
*
* cdef tuple _unellipsify(object index, int ndim):
*/
__pyx_t_1 = __Pyx_TypeCheck(__pyx_v_o, ((PyObject *)__pyx_memoryview_type));
__pyx_r = __pyx_t_1;
goto __pyx_L0;
/* "View.MemoryView":627
*
* @cname('__pyx_memoryview_check')
* cdef inline bint memoryview_check(object o): # <<<<<<<<<<<<<<
* return isinstance(o, memoryview)
*
*/
/* function exit code */
__pyx_L0:;
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "View.MemoryView":630
* return isinstance(o, memoryview)
*
* cdef tuple _unellipsify(object index, int ndim): # <<<<<<<<<<<<<<
* """
* Replace all ellipses with full slices and fill incomplete indices with
*/
static PyObject *_unellipsify(PyObject *__pyx_v_index, int __pyx_v_ndim) {
PyObject *__pyx_v_tup = NULL;
PyObject *__pyx_v_result = NULL;
int __pyx_v_have_slices;
int __pyx_v_seen_ellipsis;
CYTHON_UNUSED PyObject *__pyx_v_idx = NULL;
PyObject *__pyx_v_item = NULL;
Py_ssize_t __pyx_v_nslices;
PyObject *__pyx_r = NULL;
__Pyx_RefNannyDeclarations
int __pyx_t_1;
int __pyx_t_2;
PyObject *__pyx_t_3 = NULL;
PyObject *__pyx_t_4 = NULL;
Py_ssize_t __pyx_t_5;
PyObject *(*__pyx_t_6)(PyObject *);
PyObject *__pyx_t_7 = NULL;
Py_ssize_t __pyx_t_8;
PyObject *__pyx_t_9 = NULL;
int __pyx_t_10;
int __pyx_t_11;
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
__Pyx_RefNannySetupContext("_unellipsify", 0);
/* "View.MemoryView":635
* full slices.
* """
* if not isinstance(index, tuple): # <<<<<<<<<<<<<<
* tup = (index,)
* else:
*/
__pyx_t_1 = PyTuple_Check(__pyx_v_index);
__pyx_t_2 = ((!(__pyx_t_1 != 0)) != 0);
if (__pyx_t_2) {
/* "View.MemoryView":636
* """
* if not isinstance(index, tuple):
* tup = (index,) # <<<<<<<<<<<<<<
* else:
* tup = index
*/
__pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 636; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_3);
__Pyx_INCREF(__pyx_v_index);
PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_v_index);
__Pyx_GIVEREF(__pyx_v_index);
__pyx_v_tup = __pyx_t_3;
__pyx_t_3 = 0;
goto __pyx_L3;
}
/*else*/ {
/* "View.MemoryView":638
* tup = (index,)
* else:
* tup = index # <<<<<<<<<<<<<<
*
* result = []
*/
__Pyx_INCREF(__pyx_v_index);
__pyx_v_tup = __pyx_v_index;
}
__pyx_L3:;
/* "View.MemoryView":640
* tup = index
*
* result = [] # <<<<<<<<<<<<<<
* have_slices = False
* seen_ellipsis = False
*/
__pyx_t_3 = PyList_New(0); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 640; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_3);
__pyx_v_result = ((PyObject*)__pyx_t_3);
__pyx_t_3 = 0;
/* "View.MemoryView":641
*
* result = []
* have_slices = False # <<<<<<<<<<<<<<
* seen_ellipsis = False
* for idx, item in enumerate(tup):
*/
__pyx_v_have_slices = 0;
/* "View.MemoryView":642
* result = []
* have_slices = False
* seen_ellipsis = False # <<<<<<<<<<<<<<
* for idx, item in enumerate(tup):
* if item is Ellipsis:
*/
__pyx_v_seen_ellipsis = 0;
/* "View.MemoryView":643
* have_slices = False
* seen_ellipsis = False
* for idx, item in enumerate(tup): # <<<<<<<<<<<<<<
* if item is Ellipsis:
* if not seen_ellipsis:
*/
__Pyx_INCREF(__pyx_int_0);
__pyx_t_3 = __pyx_int_0;
if (PyList_CheckExact(__pyx_v_tup) || PyTuple_CheckExact(__pyx_v_tup)) {
__pyx_t_4 = __pyx_v_tup; __Pyx_INCREF(__pyx_t_4); __pyx_t_5 = 0;
__pyx_t_6 = NULL;
} else {
__pyx_t_5 = -1; __pyx_t_4 = PyObject_GetIter(__pyx_v_tup); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 643; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_4);
__pyx_t_6 = Py_TYPE(__pyx_t_4)->tp_iternext;
}
for (;;) {
if (!__pyx_t_6 && PyList_CheckExact(__pyx_t_4)) {
if (__pyx_t_5 >= PyList_GET_SIZE(__pyx_t_4)) break;
#if CYTHON_COMPILING_IN_CPYTHON
__pyx_t_7 = PyList_GET_ITEM(__pyx_t_4, __pyx_t_5); __Pyx_INCREF(__pyx_t_7); __pyx_t_5++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 643; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
#else
__pyx_t_7 = PySequence_ITEM(__pyx_t_4, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 643; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
#endif
} else if (!__pyx_t_6 && PyTuple_CheckExact(__pyx_t_4)) {
if (__pyx_t_5 >= PyTuple_GET_SIZE(__pyx_t_4)) break;
#if CYTHON_COMPILING_IN_CPYTHON
__pyx_t_7 = PyTuple_GET_ITEM(__pyx_t_4, __pyx_t_5); __Pyx_INCREF(__pyx_t_7); __pyx_t_5++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 643; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
#else
__pyx_t_7 = PySequence_ITEM(__pyx_t_4, __pyx_t_5); __pyx_t_5++; if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 643; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
#endif
} else {
__pyx_t_7 = __pyx_t_6(__pyx_t_4);
if (unlikely(!__pyx_t_7)) {
PyObject* exc_type = PyErr_Occurred();
if (exc_type) {
if (likely(exc_type == PyExc_StopIteration || PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear();
else {__pyx_filename = __pyx_f[2]; __pyx_lineno = 643; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
}
break;
}
__Pyx_GOTREF(__pyx_t_7);
}
__Pyx_XDECREF_SET(__pyx_v_item, __pyx_t_7);
__pyx_t_7 = 0;
__Pyx_INCREF(__pyx_t_3);
__Pyx_XDECREF_SET(__pyx_v_idx, __pyx_t_3);
__pyx_t_7 = PyNumber_Add(__pyx_t_3, __pyx_int_1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 643; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_7);
__Pyx_DECREF(__pyx_t_3);
__pyx_t_3 = __pyx_t_7;
__pyx_t_7 = 0;
/* "View.MemoryView":644
* seen_ellipsis = False
* for idx, item in enumerate(tup):
* if item is Ellipsis: # <<<<<<<<<<<<<<
* if not seen_ellipsis:
* result.extend([slice(None)] * (ndim - len(tup) + 1))
*/
__pyx_t_2 = (__pyx_v_item == __pyx_builtin_Ellipsis);
__pyx_t_1 = (__pyx_t_2 != 0);
if (__pyx_t_1) {
/* "View.MemoryView":645
* for idx, item in enumerate(tup):
* if item is Ellipsis:
* if not seen_ellipsis: # <<<<<<<<<<<<<<
* result.extend([slice(None)] * (ndim - len(tup) + 1))
* seen_ellipsis = True
*/
__pyx_t_1 = ((!(__pyx_v_seen_ellipsis != 0)) != 0);
if (__pyx_t_1) {
/* "View.MemoryView":646
* if item is Ellipsis:
* if not seen_ellipsis:
* result.extend([slice(None)] * (ndim - len(tup) + 1)) # <<<<<<<<<<<<<<
* seen_ellipsis = True
* else:
*/
__pyx_t_7 = __Pyx_PyObject_Call(((PyObject *)((PyObject*)(&PySlice_Type))), __pyx_tuple__28, NULL); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 646; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_7);
__pyx_t_8 = PyObject_Length(__pyx_v_tup); if (unlikely(__pyx_t_8 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 646; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_t_9 = PyList_New(1 * ((((__pyx_v_ndim - __pyx_t_8) + 1)<0) ? 0:((__pyx_v_ndim - __pyx_t_8) + 1))); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 646; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_9);
{ Py_ssize_t __pyx_temp;
for (__pyx_temp=0; __pyx_temp < ((__pyx_v_ndim - __pyx_t_8) + 1); __pyx_temp++) {
__Pyx_INCREF(__pyx_t_7);
PyList_SET_ITEM(__pyx_t_9, __pyx_temp, __pyx_t_7);
__Pyx_GIVEREF(__pyx_t_7);
}
}
__Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0;
__pyx_t_10 = __Pyx_PyList_Extend(__pyx_v_result, __pyx_t_9); if (unlikely(__pyx_t_10 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 646; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0;
/* "View.MemoryView":647
* if not seen_ellipsis:
* result.extend([slice(None)] * (ndim - len(tup) + 1))
* seen_ellipsis = True # <<<<<<<<<<<<<<
* else:
* result.append(slice(None))
*/
__pyx_v_seen_ellipsis = 1;
goto __pyx_L7;
}
/*else*/ {
/* "View.MemoryView":649
* seen_ellipsis = True
* else:
* result.append(slice(None)) # <<<<<<<<<<<<<<
* have_slices = True
* else:
*/
__pyx_t_9 = __Pyx_PyObject_Call(((PyObject *)((PyObject*)(&PySlice_Type))), __pyx_tuple__29, NULL); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 649; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_9);
__pyx_t_10 = __Pyx_PyList_Append(__pyx_v_result, __pyx_t_9); if (unlikely(__pyx_t_10 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 649; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0;
}
__pyx_L7:;
/* "View.MemoryView":650
* else:
* result.append(slice(None))
* have_slices = True # <<<<<<<<<<<<<<
* else:
* if not isinstance(item, slice) and not PyIndex_Check(item):
*/
__pyx_v_have_slices = 1;
goto __pyx_L6;
}
/*else*/ {
/* "View.MemoryView":652
* have_slices = True
* else:
* if not isinstance(item, slice) and not PyIndex_Check(item): # <<<<<<<<<<<<<<
* raise TypeError("Cannot index with type '%s'" % type(item))
*
*/
__pyx_t_1 = PySlice_Check(__pyx_v_item);
__pyx_t_2 = ((!(__pyx_t_1 != 0)) != 0);
if (__pyx_t_2) {
__pyx_t_1 = ((!(__Pyx_PyIndex_Check(__pyx_v_item) != 0)) != 0);
__pyx_t_11 = __pyx_t_1;
} else {
__pyx_t_11 = __pyx_t_2;
}
if (__pyx_t_11) {
/* "View.MemoryView":653
* else:
* if not isinstance(item, slice) and not PyIndex_Check(item):
* raise TypeError("Cannot index with type '%s'" % type(item)) # <<<<<<<<<<<<<<
*
* have_slices = have_slices or isinstance(item, slice)
*/
__pyx_t_9 = __Pyx_PyString_Format(__pyx_kp_s_Cannot_index_with_type_s, ((PyObject *)Py_TYPE(__pyx_v_item))); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 653; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_9);
__pyx_t_7 = PyTuple_New(1); if (unlikely(!__pyx_t_7)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 653; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_7);
PyTuple_SET_ITEM(__pyx_t_7, 0, __pyx_t_9);
__Pyx_GIVEREF(__pyx_t_9);
__pyx_t_9 = 0;
__pyx_t_9 = __Pyx_PyObject_Call(__pyx_builtin_TypeError, __pyx_t_7, NULL); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 653; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_9);
__Pyx_DECREF(__pyx_t_7); __pyx_t_7 = 0;
__Pyx_Raise(__pyx_t_9, 0, 0, 0);
__Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0;
{__pyx_filename = __pyx_f[2]; __pyx_lineno = 653; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
}
/* "View.MemoryView":655
* raise TypeError("Cannot index with type '%s'" % type(item))
*
* have_slices = have_slices or isinstance(item, slice) # <<<<<<<<<<<<<<
* result.append(item)
*
*/
if (!__pyx_v_have_slices) {
__pyx_t_11 = PySlice_Check(__pyx_v_item);
__pyx_t_2 = __pyx_t_11;
} else {
__pyx_t_2 = __pyx_v_have_slices;
}
__pyx_v_have_slices = __pyx_t_2;
/* "View.MemoryView":656
*
* have_slices = have_slices or isinstance(item, slice)
* result.append(item) # <<<<<<<<<<<<<<
*
* nslices = ndim - len(result)
*/
__pyx_t_10 = __Pyx_PyList_Append(__pyx_v_result, __pyx_v_item); if (unlikely(__pyx_t_10 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 656; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
}
__pyx_L6:;
}
__Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
/* "View.MemoryView":658
* result.append(item)
*
* nslices = ndim - len(result) # <<<<<<<<<<<<<<
* if nslices:
* result.extend([slice(None)] * nslices)
*/
__pyx_t_5 = PyList_GET_SIZE(__pyx_v_result); if (unlikely(__pyx_t_5 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 658; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_v_nslices = (__pyx_v_ndim - __pyx_t_5);
/* "View.MemoryView":659
*
* nslices = ndim - len(result)
* if nslices: # <<<<<<<<<<<<<<
* result.extend([slice(None)] * nslices)
*
*/
__pyx_t_2 = (__pyx_v_nslices != 0);
if (__pyx_t_2) {
/* "View.MemoryView":660
* nslices = ndim - len(result)
* if nslices:
* result.extend([slice(None)] * nslices) # <<<<<<<<<<<<<<
*
* return have_slices or nslices, tuple(result)
*/
__pyx_t_3 = __Pyx_PyObject_Call(((PyObject *)((PyObject*)(&PySlice_Type))), __pyx_tuple__30, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 660; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_3);
__pyx_t_4 = PyList_New(1 * ((__pyx_v_nslices<0) ? 0:__pyx_v_nslices)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 660; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_4);
{ Py_ssize_t __pyx_temp;
for (__pyx_temp=0; __pyx_temp < __pyx_v_nslices; __pyx_temp++) {
__Pyx_INCREF(__pyx_t_3);
PyList_SET_ITEM(__pyx_t_4, __pyx_temp, __pyx_t_3);
__Pyx_GIVEREF(__pyx_t_3);
}
}
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
__pyx_t_10 = __Pyx_PyList_Extend(__pyx_v_result, __pyx_t_4); if (unlikely(__pyx_t_10 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 660; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
goto __pyx_L9;
}
__pyx_L9:;
/* "View.MemoryView":662
* result.extend([slice(None)] * nslices)
*
* return have_slices or nslices, tuple(result) # <<<<<<<<<<<<<<
*
* cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim):
*/
__Pyx_XDECREF(__pyx_r);
__pyx_t_4 = __Pyx_PyBool_FromLong(__pyx_v_have_slices); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 662; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_4);
__pyx_t_2 = __Pyx_PyObject_IsTrue(__pyx_t_4); if (unlikely(__pyx_t_2 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 662; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
if (!__pyx_t_2) {
__Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
__pyx_t_3 = PyInt_FromSsize_t(__pyx_v_nslices); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 662; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_3);
__pyx_t_9 = __pyx_t_3;
__pyx_t_3 = 0;
} else {
__pyx_t_9 = __pyx_t_4;
__pyx_t_4 = 0;
}
__pyx_t_4 = PyList_AsTuple(__pyx_v_result); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 662; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_4);
__pyx_t_3 = PyTuple_New(2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 662; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_3);
PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_9);
__Pyx_GIVEREF(__pyx_t_9);
PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_t_4);
__Pyx_GIVEREF(__pyx_t_4);
__pyx_t_9 = 0;
__pyx_t_4 = 0;
__pyx_r = ((PyObject*)__pyx_t_3);
__pyx_t_3 = 0;
goto __pyx_L0;
/* "View.MemoryView":630
* return isinstance(o, memoryview)
*
* cdef tuple _unellipsify(object index, int ndim): # <<<<<<<<<<<<<<
* """
* Replace all ellipses with full slices and fill incomplete indices with
*/
/* function exit code */
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_3);
__Pyx_XDECREF(__pyx_t_4);
__Pyx_XDECREF(__pyx_t_7);
__Pyx_XDECREF(__pyx_t_9);
__Pyx_AddTraceback("View.MemoryView._unellipsify", __pyx_clineno, __pyx_lineno, __pyx_filename);
__pyx_r = 0;
__pyx_L0:;
__Pyx_XDECREF(__pyx_v_tup);
__Pyx_XDECREF(__pyx_v_result);
__Pyx_XDECREF(__pyx_v_idx);
__Pyx_XDECREF(__pyx_v_item);
__Pyx_XGIVEREF(__pyx_r);
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "View.MemoryView":664
* return have_slices or nslices, tuple(result)
*
* cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): # <<<<<<<<<<<<<<
* cdef int i
* for i in range(ndim):
*/
static PyObject *assert_direct_dimensions(Py_ssize_t *__pyx_v_suboffsets, int __pyx_v_ndim) {
int __pyx_v_i;
PyObject *__pyx_r = NULL;
__Pyx_RefNannyDeclarations
int __pyx_t_1;
int __pyx_t_2;
int __pyx_t_3;
PyObject *__pyx_t_4 = NULL;
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
__Pyx_RefNannySetupContext("assert_direct_dimensions", 0);
/* "View.MemoryView":666
* cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim):
* cdef int i
* for i in range(ndim): # <<<<<<<<<<<<<<
* if suboffsets[i] >= 0:
* raise ValueError("Indirect dimensions not supported")
*/
__pyx_t_1 = __pyx_v_ndim;
for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) {
__pyx_v_i = __pyx_t_2;
/* "View.MemoryView":667
* cdef int i
* for i in range(ndim):
* if suboffsets[i] >= 0: # <<<<<<<<<<<<<<
* raise ValueError("Indirect dimensions not supported")
*
*/
__pyx_t_3 = (((__pyx_v_suboffsets[__pyx_v_i]) >= 0) != 0);
if (__pyx_t_3) {
/* "View.MemoryView":668
* for i in range(ndim):
* if suboffsets[i] >= 0:
* raise ValueError("Indirect dimensions not supported") # <<<<<<<<<<<<<<
*
*
*/
__pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_tuple__31, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 668; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_4);
__Pyx_Raise(__pyx_t_4, 0, 0, 0);
__Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
{__pyx_filename = __pyx_f[2]; __pyx_lineno = 668; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
}
}
/* "View.MemoryView":664
* return have_slices or nslices, tuple(result)
*
* cdef assert_direct_dimensions(Py_ssize_t *suboffsets, int ndim): # <<<<<<<<<<<<<<
* cdef int i
* for i in range(ndim):
*/
/* function exit code */
__pyx_r = Py_None; __Pyx_INCREF(Py_None);
goto __pyx_L0;
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_4);
__Pyx_AddTraceback("View.MemoryView.assert_direct_dimensions", __pyx_clineno, __pyx_lineno, __pyx_filename);
__pyx_r = 0;
__pyx_L0:;
__Pyx_XGIVEREF(__pyx_r);
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "View.MemoryView":675
*
* @cname('__pyx_memview_slice')
* cdef memoryview memview_slice(memoryview memview, object indices): # <<<<<<<<<<<<<<
* cdef int new_ndim = 0, suboffset_dim = -1, dim
* cdef bint negative_step
*/
static struct __pyx_memoryview_obj *__pyx_memview_slice(struct __pyx_memoryview_obj *__pyx_v_memview, PyObject *__pyx_v_indices) {
int __pyx_v_new_ndim;
int __pyx_v_suboffset_dim;
int __pyx_v_dim;
__Pyx_memviewslice __pyx_v_src;
__Pyx_memviewslice __pyx_v_dst;
__Pyx_memviewslice *__pyx_v_p_src;
struct __pyx_memoryviewslice_obj *__pyx_v_memviewsliceobj = 0;
__Pyx_memviewslice *__pyx_v_p_dst;
int *__pyx_v_p_suboffset_dim;
Py_ssize_t __pyx_v_start;
Py_ssize_t __pyx_v_stop;
Py_ssize_t __pyx_v_step;
int __pyx_v_have_start;
int __pyx_v_have_stop;
int __pyx_v_have_step;
PyObject *__pyx_v_index = NULL;
struct __pyx_memoryview_obj *__pyx_r = NULL;
__Pyx_RefNannyDeclarations
int __pyx_t_1;
int __pyx_t_2;
PyObject *__pyx_t_3 = NULL;
struct __pyx_memoryview_obj *__pyx_t_4;
char *__pyx_t_5;
int __pyx_t_6;
Py_ssize_t __pyx_t_7;
PyObject *(*__pyx_t_8)(PyObject *);
PyObject *__pyx_t_9 = NULL;
Py_ssize_t __pyx_t_10;
int __pyx_t_11;
PyObject *__pyx_t_12 = NULL;
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
__Pyx_RefNannySetupContext("memview_slice", 0);
/* "View.MemoryView":676
* @cname('__pyx_memview_slice')
* cdef memoryview memview_slice(memoryview memview, object indices):
* cdef int new_ndim = 0, suboffset_dim = -1, dim # <<<<<<<<<<<<<<
* cdef bint negative_step
* cdef __Pyx_memviewslice src, dst
*/
__pyx_v_new_ndim = 0;
__pyx_v_suboffset_dim = -1;
/* "View.MemoryView":683
*
*
* memset(&dst, 0, sizeof(dst)) # <<<<<<<<<<<<<<
*
* cdef _memoryviewslice memviewsliceobj
*/
memset((&__pyx_v_dst), 0, (sizeof(__pyx_v_dst)));
/* "View.MemoryView":687
* cdef _memoryviewslice memviewsliceobj
*
* assert memview.view.ndim > 0 # <<<<<<<<<<<<<<
*
* if isinstance(memview, _memoryviewslice):
*/
#ifndef CYTHON_WITHOUT_ASSERTIONS
if (unlikely(!Py_OptimizeFlag)) {
if (unlikely(!((__pyx_v_memview->view.ndim > 0) != 0))) {
PyErr_SetNone(PyExc_AssertionError);
{__pyx_filename = __pyx_f[2]; __pyx_lineno = 687; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
}
}
#endif
/* "View.MemoryView":689
* assert memview.view.ndim > 0
*
* if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<<
* memviewsliceobj = memview
* p_src = &memviewsliceobj.from_slice
*/
__pyx_t_1 = __Pyx_TypeCheck(((PyObject *)__pyx_v_memview), ((PyObject *)__pyx_memoryviewslice_type));
__pyx_t_2 = (__pyx_t_1 != 0);
if (__pyx_t_2) {
/* "View.MemoryView":690
*
* if isinstance(memview, _memoryviewslice):
* memviewsliceobj = memview # <<<<<<<<<<<<<<
* p_src = &memviewsliceobj.from_slice
* else:
*/
if (!(likely(((((PyObject *)__pyx_v_memview)) == Py_None) || likely(__Pyx_TypeTest(((PyObject *)__pyx_v_memview), __pyx_memoryviewslice_type))))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 690; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_t_3 = ((PyObject *)__pyx_v_memview);
__Pyx_INCREF(__pyx_t_3);
__pyx_v_memviewsliceobj = ((struct __pyx_memoryviewslice_obj *)__pyx_t_3);
__pyx_t_3 = 0;
/* "View.MemoryView":691
* if isinstance(memview, _memoryviewslice):
* memviewsliceobj = memview
* p_src = &memviewsliceobj.from_slice # <<<<<<<<<<<<<<
* else:
* slice_copy(memview, &src)
*/
__pyx_v_p_src = (&__pyx_v_memviewsliceobj->from_slice);
goto __pyx_L3;
}
/*else*/ {
/* "View.MemoryView":693
* p_src = &memviewsliceobj.from_slice
* else:
* slice_copy(memview, &src) # <<<<<<<<<<<<<<
* p_src = &src
*
*/
__pyx_memoryview_slice_copy(__pyx_v_memview, (&__pyx_v_src));
/* "View.MemoryView":694
* else:
* slice_copy(memview, &src)
* p_src = &src # <<<<<<<<<<<<<<
*
*
*/
__pyx_v_p_src = (&__pyx_v_src);
}
__pyx_L3:;
/* "View.MemoryView":700
*
*
* dst.memview = p_src.memview # <<<<<<<<<<<<<<
* dst.data = p_src.data
*
*/
__pyx_t_4 = __pyx_v_p_src->memview;
__pyx_v_dst.memview = __pyx_t_4;
/* "View.MemoryView":701
*
* dst.memview = p_src.memview
* dst.data = p_src.data # <<<<<<<<<<<<<<
*
*
*/
__pyx_t_5 = __pyx_v_p_src->data;
__pyx_v_dst.data = __pyx_t_5;
/* "View.MemoryView":706
*
*
* cdef __Pyx_memviewslice *p_dst = &dst # <<<<<<<<<<<<<<
* cdef int *p_suboffset_dim = &suboffset_dim
* cdef Py_ssize_t start, stop, step
*/
__pyx_v_p_dst = (&__pyx_v_dst);
/* "View.MemoryView":707
*
* cdef __Pyx_memviewslice *p_dst = &dst
* cdef int *p_suboffset_dim = &suboffset_dim # <<<<<<<<<<<<<<
* cdef Py_ssize_t start, stop, step
* cdef bint have_start, have_stop, have_step
*/
__pyx_v_p_suboffset_dim = (&__pyx_v_suboffset_dim);
/* "View.MemoryView":711
* cdef bint have_start, have_stop, have_step
*
* for dim, index in enumerate(indices): # <<<<<<<<<<<<<<
* if PyIndex_Check(index):
* slice_memviewslice(
*/
__pyx_t_6 = 0;
if (PyList_CheckExact(__pyx_v_indices) || PyTuple_CheckExact(__pyx_v_indices)) {
__pyx_t_3 = __pyx_v_indices; __Pyx_INCREF(__pyx_t_3); __pyx_t_7 = 0;
__pyx_t_8 = NULL;
} else {
__pyx_t_7 = -1; __pyx_t_3 = PyObject_GetIter(__pyx_v_indices); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 711; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_3);
__pyx_t_8 = Py_TYPE(__pyx_t_3)->tp_iternext;
}
for (;;) {
if (!__pyx_t_8 && PyList_CheckExact(__pyx_t_3)) {
if (__pyx_t_7 >= PyList_GET_SIZE(__pyx_t_3)) break;
#if CYTHON_COMPILING_IN_CPYTHON
__pyx_t_9 = PyList_GET_ITEM(__pyx_t_3, __pyx_t_7); __Pyx_INCREF(__pyx_t_9); __pyx_t_7++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 711; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
#else
__pyx_t_9 = PySequence_ITEM(__pyx_t_3, __pyx_t_7); __pyx_t_7++; if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 711; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
#endif
} else if (!__pyx_t_8 && PyTuple_CheckExact(__pyx_t_3)) {
if (__pyx_t_7 >= PyTuple_GET_SIZE(__pyx_t_3)) break;
#if CYTHON_COMPILING_IN_CPYTHON
__pyx_t_9 = PyTuple_GET_ITEM(__pyx_t_3, __pyx_t_7); __Pyx_INCREF(__pyx_t_9); __pyx_t_7++; if (unlikely(0 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 711; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
#else
__pyx_t_9 = PySequence_ITEM(__pyx_t_3, __pyx_t_7); __pyx_t_7++; if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 711; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
#endif
} else {
__pyx_t_9 = __pyx_t_8(__pyx_t_3);
if (unlikely(!__pyx_t_9)) {
PyObject* exc_type = PyErr_Occurred();
if (exc_type) {
if (likely(exc_type == PyExc_StopIteration || PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration))) PyErr_Clear();
else {__pyx_filename = __pyx_f[2]; __pyx_lineno = 711; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
}
break;
}
__Pyx_GOTREF(__pyx_t_9);
}
__Pyx_XDECREF_SET(__pyx_v_index, __pyx_t_9);
__pyx_t_9 = 0;
__pyx_v_dim = __pyx_t_6;
__pyx_t_6 = (__pyx_t_6 + 1);
/* "View.MemoryView":712
*
* for dim, index in enumerate(indices):
* if PyIndex_Check(index): # <<<<<<<<<<<<<<
* slice_memviewslice(
* p_dst, p_src.shape[dim], p_src.strides[dim], p_src.suboffsets[dim],
*/
__pyx_t_2 = (__Pyx_PyIndex_Check(__pyx_v_index) != 0);
if (__pyx_t_2) {
/* "View.MemoryView":716
* p_dst, p_src.shape[dim], p_src.strides[dim], p_src.suboffsets[dim],
* dim, new_ndim, p_suboffset_dim,
* index, 0, 0, # start, stop, step # <<<<<<<<<<<<<<
* 0, 0, 0, # have_{start,stop,step}
* False)
*/
__pyx_t_10 = __Pyx_PyIndex_AsSsize_t(__pyx_v_index); if (unlikely((__pyx_t_10 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 716; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
/* "View.MemoryView":713
* for dim, index in enumerate(indices):
* if PyIndex_Check(index):
* slice_memviewslice( # <<<<<<<<<<<<<<
* p_dst, p_src.shape[dim], p_src.strides[dim], p_src.suboffsets[dim],
* dim, new_ndim, p_suboffset_dim,
*/
__pyx_t_11 = __pyx_memoryview_slice_memviewslice(__pyx_v_p_dst, (__pyx_v_p_src->shape[__pyx_v_dim]), (__pyx_v_p_src->strides[__pyx_v_dim]), (__pyx_v_p_src->suboffsets[__pyx_v_dim]), __pyx_v_dim, __pyx_v_new_ndim, __pyx_v_p_suboffset_dim, __pyx_t_10, 0, 0, 0, 0, 0, 0); if (unlikely(__pyx_t_11 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 713; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
goto __pyx_L6;
}
/* "View.MemoryView":719
* 0, 0, 0, # have_{start,stop,step}
* False)
* elif index is None: # <<<<<<<<<<<<<<
* p_dst.shape[new_ndim] = 1
* p_dst.strides[new_ndim] = 0
*/
__pyx_t_2 = (__pyx_v_index == Py_None);
__pyx_t_1 = (__pyx_t_2 != 0);
if (__pyx_t_1) {
/* "View.MemoryView":720
* False)
* elif index is None:
* p_dst.shape[new_ndim] = 1 # <<<<<<<<<<<<<<
* p_dst.strides[new_ndim] = 0
* p_dst.suboffsets[new_ndim] = -1
*/
(__pyx_v_p_dst->shape[__pyx_v_new_ndim]) = 1;
/* "View.MemoryView":721
* elif index is None:
* p_dst.shape[new_ndim] = 1
* p_dst.strides[new_ndim] = 0 # <<<<<<<<<<<<<<
* p_dst.suboffsets[new_ndim] = -1
* new_ndim += 1
*/
(__pyx_v_p_dst->strides[__pyx_v_new_ndim]) = 0;
/* "View.MemoryView":722
* p_dst.shape[new_ndim] = 1
* p_dst.strides[new_ndim] = 0
* p_dst.suboffsets[new_ndim] = -1 # <<<<<<<<<<<<<<
* new_ndim += 1
* else:
*/
(__pyx_v_p_dst->suboffsets[__pyx_v_new_ndim]) = -1;
/* "View.MemoryView":723
* p_dst.strides[new_ndim] = 0
* p_dst.suboffsets[new_ndim] = -1
* new_ndim += 1 # <<<<<<<<<<<<<<
* else:
* start = index.start or 0
*/
__pyx_v_new_ndim = (__pyx_v_new_ndim + 1);
goto __pyx_L6;
}
/*else*/ {
/* "View.MemoryView":725
* new_ndim += 1
* else:
* start = index.start or 0 # <<<<<<<<<<<<<<
* stop = index.stop or 0
* step = index.step or 0
*/
__pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_start); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 725; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_9);
__pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_9); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 725; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
if (!__pyx_t_1) {
__Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0;
__Pyx_INCREF(__pyx_int_0);
__pyx_t_12 = __pyx_int_0;
} else {
__pyx_t_12 = __pyx_t_9;
__pyx_t_9 = 0;
}
__pyx_t_10 = __Pyx_PyIndex_AsSsize_t(__pyx_t_12); if (unlikely((__pyx_t_10 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 725; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0;
__pyx_v_start = __pyx_t_10;
/* "View.MemoryView":726
* else:
* start = index.start or 0
* stop = index.stop or 0 # <<<<<<<<<<<<<<
* step = index.step or 0
*
*/
__pyx_t_12 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_stop); if (unlikely(!__pyx_t_12)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 726; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_12);
__pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_12); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 726; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
if (!__pyx_t_1) {
__Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0;
__Pyx_INCREF(__pyx_int_0);
__pyx_t_9 = __pyx_int_0;
} else {
__pyx_t_9 = __pyx_t_12;
__pyx_t_12 = 0;
}
__pyx_t_10 = __Pyx_PyIndex_AsSsize_t(__pyx_t_9); if (unlikely((__pyx_t_10 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 726; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0;
__pyx_v_stop = __pyx_t_10;
/* "View.MemoryView":727
* start = index.start or 0
* stop = index.stop or 0
* step = index.step or 0 # <<<<<<<<<<<<<<
*
* have_start = index.start is not None
*/
__pyx_t_9 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_step); if (unlikely(!__pyx_t_9)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 727; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_9);
__pyx_t_1 = __Pyx_PyObject_IsTrue(__pyx_t_9); if (unlikely(__pyx_t_1 < 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 727; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
if (!__pyx_t_1) {
__Pyx_DECREF(__pyx_t_9); __pyx_t_9 = 0;
__Pyx_INCREF(__pyx_int_0);
__pyx_t_12 = __pyx_int_0;
} else {
__pyx_t_12 = __pyx_t_9;
__pyx_t_9 = 0;
}
__pyx_t_10 = __Pyx_PyIndex_AsSsize_t(__pyx_t_12); if (unlikely((__pyx_t_10 == (Py_ssize_t)-1) && PyErr_Occurred())) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 727; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0;
__pyx_v_step = __pyx_t_10;
/* "View.MemoryView":729
* step = index.step or 0
*
* have_start = index.start is not None # <<<<<<<<<<<<<<
* have_stop = index.stop is not None
* have_step = index.step is not None
*/
__pyx_t_12 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_start); if (unlikely(!__pyx_t_12)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 729; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_12);
__pyx_t_1 = (__pyx_t_12 != Py_None);
__Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0;
__pyx_v_have_start = __pyx_t_1;
/* "View.MemoryView":730
*
* have_start = index.start is not None
* have_stop = index.stop is not None # <<<<<<<<<<<<<<
* have_step = index.step is not None
*
*/
__pyx_t_12 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_stop); if (unlikely(!__pyx_t_12)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 730; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_12);
__pyx_t_1 = (__pyx_t_12 != Py_None);
__Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0;
__pyx_v_have_stop = __pyx_t_1;
/* "View.MemoryView":731
* have_start = index.start is not None
* have_stop = index.stop is not None
* have_step = index.step is not None # <<<<<<<<<<<<<<
*
* slice_memviewslice(
*/
__pyx_t_12 = __Pyx_PyObject_GetAttrStr(__pyx_v_index, __pyx_n_s_step); if (unlikely(!__pyx_t_12)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 731; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_12);
__pyx_t_1 = (__pyx_t_12 != Py_None);
__Pyx_DECREF(__pyx_t_12); __pyx_t_12 = 0;
__pyx_v_have_step = __pyx_t_1;
/* "View.MemoryView":733
* have_step = index.step is not None
*
* slice_memviewslice( # <<<<<<<<<<<<<<
* p_dst, p_src.shape[dim], p_src.strides[dim], p_src.suboffsets[dim],
* dim, new_ndim, p_suboffset_dim,
*/
__pyx_t_11 = __pyx_memoryview_slice_memviewslice(__pyx_v_p_dst, (__pyx_v_p_src->shape[__pyx_v_dim]), (__pyx_v_p_src->strides[__pyx_v_dim]), (__pyx_v_p_src->suboffsets[__pyx_v_dim]), __pyx_v_dim, __pyx_v_new_ndim, __pyx_v_p_suboffset_dim, __pyx_v_start, __pyx_v_stop, __pyx_v_step, __pyx_v_have_start, __pyx_v_have_stop, __pyx_v_have_step, 1); if (unlikely(__pyx_t_11 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 733; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
/* "View.MemoryView":739
* have_start, have_stop, have_step,
* True)
* new_ndim += 1 # <<<<<<<<<<<<<<
*
* if isinstance(memview, _memoryviewslice):
*/
__pyx_v_new_ndim = (__pyx_v_new_ndim + 1);
}
__pyx_L6:;
}
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
/* "View.MemoryView":741
* new_ndim += 1
*
* if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<<
* return memoryview_fromslice(dst, new_ndim,
* memviewsliceobj.to_object_func,
*/
__pyx_t_1 = __Pyx_TypeCheck(((PyObject *)__pyx_v_memview), ((PyObject *)__pyx_memoryviewslice_type));
__pyx_t_2 = (__pyx_t_1 != 0);
if (__pyx_t_2) {
/* "View.MemoryView":742
*
* if isinstance(memview, _memoryviewslice):
* return memoryview_fromslice(dst, new_ndim, # <<<<<<<<<<<<<<
* memviewsliceobj.to_object_func,
* memviewsliceobj.to_dtype_func,
*/
__Pyx_XDECREF(((PyObject *)__pyx_r));
/* "View.MemoryView":743
* if isinstance(memview, _memoryviewslice):
* return memoryview_fromslice(dst, new_ndim,
* memviewsliceobj.to_object_func, # <<<<<<<<<<<<<<
* memviewsliceobj.to_dtype_func,
* memview.dtype_is_object)
*/
if (unlikely(!__pyx_v_memviewsliceobj)) { __Pyx_RaiseUnboundLocalError("memviewsliceobj"); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 743; __pyx_clineno = __LINE__; goto __pyx_L1_error;} }
/* "View.MemoryView":744
* return memoryview_fromslice(dst, new_ndim,
* memviewsliceobj.to_object_func,
* memviewsliceobj.to_dtype_func, # <<<<<<<<<<<<<<
* memview.dtype_is_object)
* else:
*/
if (unlikely(!__pyx_v_memviewsliceobj)) { __Pyx_RaiseUnboundLocalError("memviewsliceobj"); {__pyx_filename = __pyx_f[2]; __pyx_lineno = 744; __pyx_clineno = __LINE__; goto __pyx_L1_error;} }
/* "View.MemoryView":742
*
* if isinstance(memview, _memoryviewslice):
* return memoryview_fromslice(dst, new_ndim, # <<<<<<<<<<<<<<
* memviewsliceobj.to_object_func,
* memviewsliceobj.to_dtype_func,
*/
__pyx_t_3 = __pyx_memoryview_fromslice(__pyx_v_dst, __pyx_v_new_ndim, __pyx_v_memviewsliceobj->to_object_func, __pyx_v_memviewsliceobj->to_dtype_func, __pyx_v_memview->dtype_is_object); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 742; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_3);
if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_memoryview_type))))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 742; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_r = ((struct __pyx_memoryview_obj *)__pyx_t_3);
__pyx_t_3 = 0;
goto __pyx_L0;
}
/*else*/ {
/* "View.MemoryView":747
* memview.dtype_is_object)
* else:
* return memoryview_fromslice(dst, new_ndim, NULL, NULL, # <<<<<<<<<<<<<<
* memview.dtype_is_object)
*
*/
__Pyx_XDECREF(((PyObject *)__pyx_r));
/* "View.MemoryView":748
* else:
* return memoryview_fromslice(dst, new_ndim, NULL, NULL,
* memview.dtype_is_object) # <<<<<<<<<<<<<<
*
*
*/
__pyx_t_3 = __pyx_memoryview_fromslice(__pyx_v_dst, __pyx_v_new_ndim, NULL, NULL, __pyx_v_memview->dtype_is_object); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 747; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_3);
/* "View.MemoryView":747
* memview.dtype_is_object)
* else:
* return memoryview_fromslice(dst, new_ndim, NULL, NULL, # <<<<<<<<<<<<<<
* memview.dtype_is_object)
*
*/
if (!(likely(((__pyx_t_3) == Py_None) || likely(__Pyx_TypeTest(__pyx_t_3, __pyx_memoryview_type))))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 747; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_r = ((struct __pyx_memoryview_obj *)__pyx_t_3);
__pyx_t_3 = 0;
goto __pyx_L0;
}
/* "View.MemoryView":675
*
* @cname('__pyx_memview_slice')
* cdef memoryview memview_slice(memoryview memview, object indices): # <<<<<<<<<<<<<<
* cdef int new_ndim = 0, suboffset_dim = -1, dim
* cdef bint negative_step
*/
/* function exit code */
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_3);
__Pyx_XDECREF(__pyx_t_9);
__Pyx_XDECREF(__pyx_t_12);
__Pyx_AddTraceback("View.MemoryView.memview_slice", __pyx_clineno, __pyx_lineno, __pyx_filename);
__pyx_r = 0;
__pyx_L0:;
__Pyx_XDECREF((PyObject *)__pyx_v_memviewsliceobj);
__Pyx_XDECREF(__pyx_v_index);
__Pyx_XGIVEREF((PyObject *)__pyx_r);
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "View.MemoryView":772
*
* @cname('__pyx_memoryview_slice_memviewslice')
* cdef int slice_memviewslice( # <<<<<<<<<<<<<<
* __Pyx_memviewslice *dst,
* Py_ssize_t shape, Py_ssize_t stride, Py_ssize_t suboffset,
*/
static int __pyx_memoryview_slice_memviewslice(__Pyx_memviewslice *__pyx_v_dst, Py_ssize_t __pyx_v_shape, Py_ssize_t __pyx_v_stride, Py_ssize_t __pyx_v_suboffset, int __pyx_v_dim, int __pyx_v_new_ndim, int *__pyx_v_suboffset_dim, Py_ssize_t __pyx_v_start, Py_ssize_t __pyx_v_stop, Py_ssize_t __pyx_v_step, int __pyx_v_have_start, int __pyx_v_have_stop, int __pyx_v_have_step, int __pyx_v_is_slice) {
Py_ssize_t __pyx_v_new_shape;
int __pyx_v_negative_step;
int __pyx_r;
int __pyx_t_1;
int __pyx_t_2;
int __pyx_t_3;
int __pyx_t_4;
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
/* "View.MemoryView":792
* cdef bint negative_step
*
* if not is_slice: # <<<<<<<<<<<<<<
*
* if start < 0:
*/
__pyx_t_1 = ((!(__pyx_v_is_slice != 0)) != 0);
if (__pyx_t_1) {
/* "View.MemoryView":794
* if not is_slice:
*
* if start < 0: # <<<<<<<<<<<<<<
* start += shape
* if not 0 <= start < shape:
*/
__pyx_t_1 = ((__pyx_v_start < 0) != 0);
if (__pyx_t_1) {
/* "View.MemoryView":795
*
* if start < 0:
* start += shape # <<<<<<<<<<<<<<
* if not 0 <= start < shape:
* _err_dim(IndexError, "Index out of bounds (axis %d)", dim)
*/
__pyx_v_start = (__pyx_v_start + __pyx_v_shape);
goto __pyx_L4;
}
__pyx_L4:;
/* "View.MemoryView":796
* if start < 0:
* start += shape
* if not 0 <= start < shape: # <<<<<<<<<<<<<<
* _err_dim(IndexError, "Index out of bounds (axis %d)", dim)
* else:
*/
__pyx_t_1 = (0 <= __pyx_v_start);
if (__pyx_t_1) {
__pyx_t_1 = (__pyx_v_start < __pyx_v_shape);
}
__pyx_t_2 = ((!(__pyx_t_1 != 0)) != 0);
if (__pyx_t_2) {
/* "View.MemoryView":797
* start += shape
* if not 0 <= start < shape:
* _err_dim(IndexError, "Index out of bounds (axis %d)", dim) # <<<<<<<<<<<<<<
* else:
*
*/
__pyx_t_3 = __pyx_memoryview_err_dim(__pyx_builtin_IndexError, __pyx_k_Index_out_of_bounds_axis_d, __pyx_v_dim); if (unlikely(__pyx_t_3 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 797; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
goto __pyx_L5;
}
__pyx_L5:;
goto __pyx_L3;
}
/*else*/ {
/* "View.MemoryView":800
* else:
*
* negative_step = have_step != 0 and step < 0 # <<<<<<<<<<<<<<
*
* if have_step and step == 0:
*/
__pyx_t_2 = (__pyx_v_have_step != 0);
if (__pyx_t_2) {
__pyx_t_1 = (__pyx_v_step < 0);
__pyx_t_4 = __pyx_t_1;
} else {
__pyx_t_4 = __pyx_t_2;
}
__pyx_v_negative_step = __pyx_t_4;
/* "View.MemoryView":802
* negative_step = have_step != 0 and step < 0
*
* if have_step and step == 0: # <<<<<<<<<<<<<<
* _err_dim(ValueError, "Step may not be zero (axis %d)", dim)
*
*/
if ((__pyx_v_have_step != 0)) {
__pyx_t_4 = (__pyx_v_step == 0);
__pyx_t_2 = __pyx_t_4;
} else {
__pyx_t_2 = (__pyx_v_have_step != 0);
}
if (__pyx_t_2) {
/* "View.MemoryView":803
*
* if have_step and step == 0:
* _err_dim(ValueError, "Step may not be zero (axis %d)", dim) # <<<<<<<<<<<<<<
*
*
*/
__pyx_t_3 = __pyx_memoryview_err_dim(__pyx_builtin_ValueError, __pyx_k_Step_may_not_be_zero_axis_d, __pyx_v_dim); if (unlikely(__pyx_t_3 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
goto __pyx_L6;
}
__pyx_L6:;
/* "View.MemoryView":806
*
*
* if have_start: # <<<<<<<<<<<<<<
* if start < 0:
* start += shape
*/
__pyx_t_2 = (__pyx_v_have_start != 0);
if (__pyx_t_2) {
/* "View.MemoryView":807
*
* if have_start:
* if start < 0: # <<<<<<<<<<<<<<
* start += shape
* if start < 0:
*/
__pyx_t_2 = ((__pyx_v_start < 0) != 0);
if (__pyx_t_2) {
/* "View.MemoryView":808
* if have_start:
* if start < 0:
* start += shape # <<<<<<<<<<<<<<
* if start < 0:
* start = 0
*/
__pyx_v_start = (__pyx_v_start + __pyx_v_shape);
/* "View.MemoryView":809
* if start < 0:
* start += shape
* if start < 0: # <<<<<<<<<<<<<<
* start = 0
* elif start >= shape:
*/
__pyx_t_2 = ((__pyx_v_start < 0) != 0);
if (__pyx_t_2) {
/* "View.MemoryView":810
* start += shape
* if start < 0:
* start = 0 # <<<<<<<<<<<<<<
* elif start >= shape:
* if negative_step:
*/
__pyx_v_start = 0;
goto __pyx_L9;
}
__pyx_L9:;
goto __pyx_L8;
}
/* "View.MemoryView":811
* if start < 0:
* start = 0
* elif start >= shape: # <<<<<<<<<<<<<<
* if negative_step:
* start = shape - 1
*/
__pyx_t_2 = ((__pyx_v_start >= __pyx_v_shape) != 0);
if (__pyx_t_2) {
/* "View.MemoryView":812
* start = 0
* elif start >= shape:
* if negative_step: # <<<<<<<<<<<<<<
* start = shape - 1
* else:
*/
__pyx_t_2 = (__pyx_v_negative_step != 0);
if (__pyx_t_2) {
/* "View.MemoryView":813
* elif start >= shape:
* if negative_step:
* start = shape - 1 # <<<<<<<<<<<<<<
* else:
* start = shape
*/
__pyx_v_start = (__pyx_v_shape - 1);
goto __pyx_L10;
}
/*else*/ {
/* "View.MemoryView":815
* start = shape - 1
* else:
* start = shape # <<<<<<<<<<<<<<
* else:
* if negative_step:
*/
__pyx_v_start = __pyx_v_shape;
}
__pyx_L10:;
goto __pyx_L8;
}
__pyx_L8:;
goto __pyx_L7;
}
/*else*/ {
/* "View.MemoryView":817
* start = shape
* else:
* if negative_step: # <<<<<<<<<<<<<<
* start = shape - 1
* else:
*/
__pyx_t_2 = (__pyx_v_negative_step != 0);
if (__pyx_t_2) {
/* "View.MemoryView":818
* else:
* if negative_step:
* start = shape - 1 # <<<<<<<<<<<<<<
* else:
* start = 0
*/
__pyx_v_start = (__pyx_v_shape - 1);
goto __pyx_L11;
}
/*else*/ {
/* "View.MemoryView":820
* start = shape - 1
* else:
* start = 0 # <<<<<<<<<<<<<<
*
* if have_stop:
*/
__pyx_v_start = 0;
}
__pyx_L11:;
}
__pyx_L7:;
/* "View.MemoryView":822
* start = 0
*
* if have_stop: # <<<<<<<<<<<<<<
* if stop < 0:
* stop += shape
*/
__pyx_t_2 = (__pyx_v_have_stop != 0);
if (__pyx_t_2) {
/* "View.MemoryView":823
*
* if have_stop:
* if stop < 0: # <<<<<<<<<<<<<<
* stop += shape
* if stop < 0:
*/
__pyx_t_2 = ((__pyx_v_stop < 0) != 0);
if (__pyx_t_2) {
/* "View.MemoryView":824
* if have_stop:
* if stop < 0:
* stop += shape # <<<<<<<<<<<<<<
* if stop < 0:
* stop = 0
*/
__pyx_v_stop = (__pyx_v_stop + __pyx_v_shape);
/* "View.MemoryView":825
* if stop < 0:
* stop += shape
* if stop < 0: # <<<<<<<<<<<<<<
* stop = 0
* elif stop > shape:
*/
__pyx_t_2 = ((__pyx_v_stop < 0) != 0);
if (__pyx_t_2) {
/* "View.MemoryView":826
* stop += shape
* if stop < 0:
* stop = 0 # <<<<<<<<<<<<<<
* elif stop > shape:
* stop = shape
*/
__pyx_v_stop = 0;
goto __pyx_L14;
}
__pyx_L14:;
goto __pyx_L13;
}
/* "View.MemoryView":827
* if stop < 0:
* stop = 0
* elif stop > shape: # <<<<<<<<<<<<<<
* stop = shape
* else:
*/
__pyx_t_2 = ((__pyx_v_stop > __pyx_v_shape) != 0);
if (__pyx_t_2) {
/* "View.MemoryView":828
* stop = 0
* elif stop > shape:
* stop = shape # <<<<<<<<<<<<<<
* else:
* if negative_step:
*/
__pyx_v_stop = __pyx_v_shape;
goto __pyx_L13;
}
__pyx_L13:;
goto __pyx_L12;
}
/*else*/ {
/* "View.MemoryView":830
* stop = shape
* else:
* if negative_step: # <<<<<<<<<<<<<<
* stop = -1
* else:
*/
__pyx_t_2 = (__pyx_v_negative_step != 0);
if (__pyx_t_2) {
/* "View.MemoryView":831
* else:
* if negative_step:
* stop = -1 # <<<<<<<<<<<<<<
* else:
* stop = shape
*/
__pyx_v_stop = -1;
goto __pyx_L15;
}
/*else*/ {
/* "View.MemoryView":833
* stop = -1
* else:
* stop = shape # <<<<<<<<<<<<<<
*
* if not have_step:
*/
__pyx_v_stop = __pyx_v_shape;
}
__pyx_L15:;
}
__pyx_L12:;
/* "View.MemoryView":835
* stop = shape
*
* if not have_step: # <<<<<<<<<<<<<<
* step = 1
*
*/
__pyx_t_2 = ((!(__pyx_v_have_step != 0)) != 0);
if (__pyx_t_2) {
/* "View.MemoryView":836
*
* if not have_step:
* step = 1 # <<<<<<<<<<<<<<
*
*
*/
__pyx_v_step = 1;
goto __pyx_L16;
}
__pyx_L16:;
/* "View.MemoryView":840
*
* with cython.cdivision(True):
* new_shape = (stop - start) // step # <<<<<<<<<<<<<<
*
* if (stop - start) - step * new_shape:
*/
__pyx_v_new_shape = ((__pyx_v_stop - __pyx_v_start) / __pyx_v_step);
/* "View.MemoryView":842
* new_shape = (stop - start) // step
*
* if (stop - start) - step * new_shape: # <<<<<<<<<<<<<<
* new_shape += 1
*
*/
__pyx_t_2 = (((__pyx_v_stop - __pyx_v_start) - (__pyx_v_step * __pyx_v_new_shape)) != 0);
if (__pyx_t_2) {
/* "View.MemoryView":843
*
* if (stop - start) - step * new_shape:
* new_shape += 1 # <<<<<<<<<<<<<<
*
* if new_shape < 0:
*/
__pyx_v_new_shape = (__pyx_v_new_shape + 1);
goto __pyx_L17;
}
__pyx_L17:;
/* "View.MemoryView":845
* new_shape += 1
*
* if new_shape < 0: # <<<<<<<<<<<<<<
* new_shape = 0
*
*/
__pyx_t_2 = ((__pyx_v_new_shape < 0) != 0);
if (__pyx_t_2) {
/* "View.MemoryView":846
*
* if new_shape < 0:
* new_shape = 0 # <<<<<<<<<<<<<<
*
*
*/
__pyx_v_new_shape = 0;
goto __pyx_L18;
}
__pyx_L18:;
/* "View.MemoryView":849
*
*
* dst.strides[new_ndim] = stride * step # <<<<<<<<<<<<<<
* dst.shape[new_ndim] = new_shape
* dst.suboffsets[new_ndim] = suboffset
*/
(__pyx_v_dst->strides[__pyx_v_new_ndim]) = (__pyx_v_stride * __pyx_v_step);
/* "View.MemoryView":850
*
* dst.strides[new_ndim] = stride * step
* dst.shape[new_ndim] = new_shape # <<<<<<<<<<<<<<
* dst.suboffsets[new_ndim] = suboffset
*
*/
(__pyx_v_dst->shape[__pyx_v_new_ndim]) = __pyx_v_new_shape;
/* "View.MemoryView":851
* dst.strides[new_ndim] = stride * step
* dst.shape[new_ndim] = new_shape
* dst.suboffsets[new_ndim] = suboffset # <<<<<<<<<<<<<<
*
*
*/
(__pyx_v_dst->suboffsets[__pyx_v_new_ndim]) = __pyx_v_suboffset;
}
__pyx_L3:;
/* "View.MemoryView":854
*
*
* if suboffset_dim[0] < 0: # <<<<<<<<<<<<<<
* dst.data += start * stride
* else:
*/
__pyx_t_2 = (((__pyx_v_suboffset_dim[0]) < 0) != 0);
if (__pyx_t_2) {
/* "View.MemoryView":855
*
* if suboffset_dim[0] < 0:
* dst.data += start * stride # <<<<<<<<<<<<<<
* else:
* dst.suboffsets[suboffset_dim[0]] += start * stride
*/
__pyx_v_dst->data = (__pyx_v_dst->data + (__pyx_v_start * __pyx_v_stride));
goto __pyx_L19;
}
/*else*/ {
/* "View.MemoryView":857
* dst.data += start * stride
* else:
* dst.suboffsets[suboffset_dim[0]] += start * stride # <<<<<<<<<<<<<<
*
* if suboffset >= 0:
*/
__pyx_t_3 = (__pyx_v_suboffset_dim[0]);
(__pyx_v_dst->suboffsets[__pyx_t_3]) = ((__pyx_v_dst->suboffsets[__pyx_t_3]) + (__pyx_v_start * __pyx_v_stride));
}
__pyx_L19:;
/* "View.MemoryView":859
* dst.suboffsets[suboffset_dim[0]] += start * stride
*
* if suboffset >= 0: # <<<<<<<<<<<<<<
* if not is_slice:
* if new_ndim == 0:
*/
__pyx_t_2 = ((__pyx_v_suboffset >= 0) != 0);
if (__pyx_t_2) {
/* "View.MemoryView":860
*
* if suboffset >= 0:
* if not is_slice: # <<<<<<<<<<<<<<
* if new_ndim == 0:
* dst.data = (<char **> dst.data)[0] + suboffset
*/
__pyx_t_2 = ((!(__pyx_v_is_slice != 0)) != 0);
if (__pyx_t_2) {
/* "View.MemoryView":861
* if suboffset >= 0:
* if not is_slice:
* if new_ndim == 0: # <<<<<<<<<<<<<<
* dst.data = (<char **> dst.data)[0] + suboffset
* else:
*/
__pyx_t_2 = ((__pyx_v_new_ndim == 0) != 0);
if (__pyx_t_2) {
/* "View.MemoryView":862
* if not is_slice:
* if new_ndim == 0:
* dst.data = (<char **> dst.data)[0] + suboffset # <<<<<<<<<<<<<<
* else:
* _err_dim(IndexError, "All dimensions preceding dimension %d "
*/
__pyx_v_dst->data = ((((char **)__pyx_v_dst->data)[0]) + __pyx_v_suboffset);
goto __pyx_L22;
}
/*else*/ {
/* "View.MemoryView":864
* dst.data = (<char **> dst.data)[0] + suboffset
* else:
* _err_dim(IndexError, "All dimensions preceding dimension %d " # <<<<<<<<<<<<<<
* "must be indexed and not sliced", dim)
* else:
*/
__pyx_t_3 = __pyx_memoryview_err_dim(__pyx_builtin_IndexError, __pyx_k_All_dimensions_preceding_dimensi, __pyx_v_dim); if (unlikely(__pyx_t_3 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 864; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
}
__pyx_L22:;
goto __pyx_L21;
}
/*else*/ {
/* "View.MemoryView":867
* "must be indexed and not sliced", dim)
* else:
* suboffset_dim[0] = new_ndim # <<<<<<<<<<<<<<
*
* return 0
*/
(__pyx_v_suboffset_dim[0]) = __pyx_v_new_ndim;
}
__pyx_L21:;
goto __pyx_L20;
}
__pyx_L20:;
/* "View.MemoryView":869
* suboffset_dim[0] = new_ndim
*
* return 0 # <<<<<<<<<<<<<<
*
*
*/
__pyx_r = 0;
goto __pyx_L0;
/* "View.MemoryView":772
*
* @cname('__pyx_memoryview_slice_memviewslice')
* cdef int slice_memviewslice( # <<<<<<<<<<<<<<
* __Pyx_memviewslice *dst,
* Py_ssize_t shape, Py_ssize_t stride, Py_ssize_t suboffset,
*/
/* function exit code */
__pyx_L1_error:;
{
#ifdef WITH_THREAD
PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure();
#endif
__Pyx_AddTraceback("View.MemoryView.slice_memviewslice", __pyx_clineno, __pyx_lineno, __pyx_filename);
#ifdef WITH_THREAD
PyGILState_Release(__pyx_gilstate_save);
#endif
}
__pyx_r = -1;
__pyx_L0:;
return __pyx_r;
}
/* "View.MemoryView":875
*
* @cname('__pyx_pybuffer_index')
* cdef char *pybuffer_index(Py_buffer *view, char *bufp, Py_ssize_t index, # <<<<<<<<<<<<<<
* Py_ssize_t dim) except NULL:
* cdef Py_ssize_t shape, stride, suboffset = -1
*/
static char *__pyx_pybuffer_index(Py_buffer *__pyx_v_view, char *__pyx_v_bufp, Py_ssize_t __pyx_v_index, Py_ssize_t __pyx_v_dim) {
Py_ssize_t __pyx_v_shape;
Py_ssize_t __pyx_v_stride;
Py_ssize_t __pyx_v_suboffset;
Py_ssize_t __pyx_v_itemsize;
char *__pyx_v_resultp;
char *__pyx_r;
__Pyx_RefNannyDeclarations
Py_ssize_t __pyx_t_1;
int __pyx_t_2;
PyObject *__pyx_t_3 = NULL;
PyObject *__pyx_t_4 = NULL;
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
__Pyx_RefNannySetupContext("pybuffer_index", 0);
/* "View.MemoryView":877
* cdef char *pybuffer_index(Py_buffer *view, char *bufp, Py_ssize_t index,
* Py_ssize_t dim) except NULL:
* cdef Py_ssize_t shape, stride, suboffset = -1 # <<<<<<<<<<<<<<
* cdef Py_ssize_t itemsize = view.itemsize
* cdef char *resultp
*/
__pyx_v_suboffset = -1;
/* "View.MemoryView":878
* Py_ssize_t dim) except NULL:
* cdef Py_ssize_t shape, stride, suboffset = -1
* cdef Py_ssize_t itemsize = view.itemsize # <<<<<<<<<<<<<<
* cdef char *resultp
*
*/
__pyx_t_1 = __pyx_v_view->itemsize;
__pyx_v_itemsize = __pyx_t_1;
/* "View.MemoryView":881
* cdef char *resultp
*
* if view.ndim == 0: # <<<<<<<<<<<<<<
* shape = view.len / itemsize
* stride = itemsize
*/
__pyx_t_2 = ((__pyx_v_view->ndim == 0) != 0);
if (__pyx_t_2) {
/* "View.MemoryView":882
*
* if view.ndim == 0:
* shape = view.len / itemsize # <<<<<<<<<<<<<<
* stride = itemsize
* else:
*/
if (unlikely(__pyx_v_itemsize == 0)) {
#ifdef WITH_THREAD
PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure();
#endif
PyErr_SetString(PyExc_ZeroDivisionError, "integer division or modulo by zero");
#ifdef WITH_THREAD
PyGILState_Release(__pyx_gilstate_save);
#endif
{__pyx_filename = __pyx_f[2]; __pyx_lineno = 882; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
}
else if (sizeof(Py_ssize_t) == sizeof(long) && unlikely(__pyx_v_itemsize == -1) && unlikely(UNARY_NEG_WOULD_OVERFLOW(__pyx_v_view->len))) {
#ifdef WITH_THREAD
PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure();
#endif
PyErr_SetString(PyExc_OverflowError, "value too large to perform division");
#ifdef WITH_THREAD
PyGILState_Release(__pyx_gilstate_save);
#endif
{__pyx_filename = __pyx_f[2]; __pyx_lineno = 882; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
}
__pyx_v_shape = (__pyx_v_view->len / __pyx_v_itemsize);
/* "View.MemoryView":883
* if view.ndim == 0:
* shape = view.len / itemsize
* stride = itemsize # <<<<<<<<<<<<<<
* else:
* shape = view.shape[dim]
*/
__pyx_v_stride = __pyx_v_itemsize;
goto __pyx_L3;
}
/*else*/ {
/* "View.MemoryView":885
* stride = itemsize
* else:
* shape = view.shape[dim] # <<<<<<<<<<<<<<
* stride = view.strides[dim]
* if view.suboffsets != NULL:
*/
__pyx_v_shape = (__pyx_v_view->shape[__pyx_v_dim]);
/* "View.MemoryView":886
* else:
* shape = view.shape[dim]
* stride = view.strides[dim] # <<<<<<<<<<<<<<
* if view.suboffsets != NULL:
* suboffset = view.suboffsets[dim]
*/
__pyx_v_stride = (__pyx_v_view->strides[__pyx_v_dim]);
/* "View.MemoryView":887
* shape = view.shape[dim]
* stride = view.strides[dim]
* if view.suboffsets != NULL: # <<<<<<<<<<<<<<
* suboffset = view.suboffsets[dim]
*
*/
__pyx_t_2 = ((__pyx_v_view->suboffsets != NULL) != 0);
if (__pyx_t_2) {
/* "View.MemoryView":888
* stride = view.strides[dim]
* if view.suboffsets != NULL:
* suboffset = view.suboffsets[dim] # <<<<<<<<<<<<<<
*
* if index < 0:
*/
__pyx_v_suboffset = (__pyx_v_view->suboffsets[__pyx_v_dim]);
goto __pyx_L4;
}
__pyx_L4:;
}
__pyx_L3:;
/* "View.MemoryView":890
* suboffset = view.suboffsets[dim]
*
* if index < 0: # <<<<<<<<<<<<<<
* index += view.shape[dim]
* if index < 0:
*/
__pyx_t_2 = ((__pyx_v_index < 0) != 0);
if (__pyx_t_2) {
/* "View.MemoryView":891
*
* if index < 0:
* index += view.shape[dim] # <<<<<<<<<<<<<<
* if index < 0:
* raise IndexError("Out of bounds on buffer access (axis %d)" % dim)
*/
__pyx_v_index = (__pyx_v_index + (__pyx_v_view->shape[__pyx_v_dim]));
/* "View.MemoryView":892
* if index < 0:
* index += view.shape[dim]
* if index < 0: # <<<<<<<<<<<<<<
* raise IndexError("Out of bounds on buffer access (axis %d)" % dim)
*
*/
__pyx_t_2 = ((__pyx_v_index < 0) != 0);
if (__pyx_t_2) {
/* "View.MemoryView":893
* index += view.shape[dim]
* if index < 0:
* raise IndexError("Out of bounds on buffer access (axis %d)" % dim) # <<<<<<<<<<<<<<
*
* if index >= shape:
*/
__pyx_t_3 = PyInt_FromSsize_t(__pyx_v_dim); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 893; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_3);
__pyx_t_4 = __Pyx_PyString_Format(__pyx_kp_s_Out_of_bounds_on_buffer_access_a, __pyx_t_3); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 893; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_4);
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
__pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 893; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_3);
PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_4);
__Pyx_GIVEREF(__pyx_t_4);
__pyx_t_4 = 0;
__pyx_t_4 = __Pyx_PyObject_Call(__pyx_builtin_IndexError, __pyx_t_3, NULL); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 893; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_4);
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
__Pyx_Raise(__pyx_t_4, 0, 0, 0);
__Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
{__pyx_filename = __pyx_f[2]; __pyx_lineno = 893; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
}
goto __pyx_L5;
}
__pyx_L5:;
/* "View.MemoryView":895
* raise IndexError("Out of bounds on buffer access (axis %d)" % dim)
*
* if index >= shape: # <<<<<<<<<<<<<<
* raise IndexError("Out of bounds on buffer access (axis %d)" % dim)
*
*/
__pyx_t_2 = ((__pyx_v_index >= __pyx_v_shape) != 0);
if (__pyx_t_2) {
/* "View.MemoryView":896
*
* if index >= shape:
* raise IndexError("Out of bounds on buffer access (axis %d)" % dim) # <<<<<<<<<<<<<<
*
* resultp = bufp + index * stride
*/
__pyx_t_4 = PyInt_FromSsize_t(__pyx_v_dim); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 896; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_4);
__pyx_t_3 = __Pyx_PyString_Format(__pyx_kp_s_Out_of_bounds_on_buffer_access_a, __pyx_t_4); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 896; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_3);
__Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
__pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 896; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_4);
PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3);
__Pyx_GIVEREF(__pyx_t_3);
__pyx_t_3 = 0;
__pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_IndexError, __pyx_t_4, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 896; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_3);
__Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
__Pyx_Raise(__pyx_t_3, 0, 0, 0);
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
{__pyx_filename = __pyx_f[2]; __pyx_lineno = 896; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
}
/* "View.MemoryView":898
* raise IndexError("Out of bounds on buffer access (axis %d)" % dim)
*
* resultp = bufp + index * stride # <<<<<<<<<<<<<<
* if suboffset >= 0:
* resultp = (<char **> resultp)[0] + suboffset
*/
__pyx_v_resultp = (__pyx_v_bufp + (__pyx_v_index * __pyx_v_stride));
/* "View.MemoryView":899
*
* resultp = bufp + index * stride
* if suboffset >= 0: # <<<<<<<<<<<<<<
* resultp = (<char **> resultp)[0] + suboffset
*
*/
__pyx_t_2 = ((__pyx_v_suboffset >= 0) != 0);
if (__pyx_t_2) {
/* "View.MemoryView":900
* resultp = bufp + index * stride
* if suboffset >= 0:
* resultp = (<char **> resultp)[0] + suboffset # <<<<<<<<<<<<<<
*
* return resultp
*/
__pyx_v_resultp = ((((char **)__pyx_v_resultp)[0]) + __pyx_v_suboffset);
goto __pyx_L8;
}
__pyx_L8:;
/* "View.MemoryView":902
* resultp = (<char **> resultp)[0] + suboffset
*
* return resultp # <<<<<<<<<<<<<<
*
*
*/
__pyx_r = __pyx_v_resultp;
goto __pyx_L0;
/* "View.MemoryView":875
*
* @cname('__pyx_pybuffer_index')
* cdef char *pybuffer_index(Py_buffer *view, char *bufp, Py_ssize_t index, # <<<<<<<<<<<<<<
* Py_ssize_t dim) except NULL:
* cdef Py_ssize_t shape, stride, suboffset = -1
*/
/* function exit code */
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_3);
__Pyx_XDECREF(__pyx_t_4);
__Pyx_AddTraceback("View.MemoryView.pybuffer_index", __pyx_clineno, __pyx_lineno, __pyx_filename);
__pyx_r = NULL;
__pyx_L0:;
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "View.MemoryView":908
*
* @cname('__pyx_memslice_transpose')
* cdef int transpose_memslice(__Pyx_memviewslice *memslice) nogil except 0: # <<<<<<<<<<<<<<
* cdef int ndim = memslice.memview.view.ndim
*
*/
static int __pyx_memslice_transpose(__Pyx_memviewslice *__pyx_v_memslice) {
int __pyx_v_ndim;
Py_ssize_t *__pyx_v_shape;
Py_ssize_t *__pyx_v_strides;
int __pyx_v_i;
int __pyx_v_j;
int __pyx_r;
int __pyx_t_1;
Py_ssize_t *__pyx_t_2;
long __pyx_t_3;
Py_ssize_t __pyx_t_4;
Py_ssize_t __pyx_t_5;
int __pyx_t_6;
int __pyx_t_7;
int __pyx_t_8;
int __pyx_t_9;
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
/* "View.MemoryView":909
* @cname('__pyx_memslice_transpose')
* cdef int transpose_memslice(__Pyx_memviewslice *memslice) nogil except 0:
* cdef int ndim = memslice.memview.view.ndim # <<<<<<<<<<<<<<
*
* cdef Py_ssize_t *shape = memslice.shape
*/
__pyx_t_1 = __pyx_v_memslice->memview->view.ndim;
__pyx_v_ndim = __pyx_t_1;
/* "View.MemoryView":911
* cdef int ndim = memslice.memview.view.ndim
*
* cdef Py_ssize_t *shape = memslice.shape # <<<<<<<<<<<<<<
* cdef Py_ssize_t *strides = memslice.strides
*
*/
__pyx_t_2 = __pyx_v_memslice->shape;
__pyx_v_shape = __pyx_t_2;
/* "View.MemoryView":912
*
* cdef Py_ssize_t *shape = memslice.shape
* cdef Py_ssize_t *strides = memslice.strides # <<<<<<<<<<<<<<
*
*
*/
__pyx_t_2 = __pyx_v_memslice->strides;
__pyx_v_strides = __pyx_t_2;
/* "View.MemoryView":916
*
* cdef int i, j
* for i in range(ndim / 2): # <<<<<<<<<<<<<<
* j = ndim - 1 - i
* strides[i], strides[j] = strides[j], strides[i]
*/
__pyx_t_3 = (__pyx_v_ndim / 2);
for (__pyx_t_1 = 0; __pyx_t_1 < __pyx_t_3; __pyx_t_1+=1) {
__pyx_v_i = __pyx_t_1;
/* "View.MemoryView":917
* cdef int i, j
* for i in range(ndim / 2):
* j = ndim - 1 - i # <<<<<<<<<<<<<<
* strides[i], strides[j] = strides[j], strides[i]
* shape[i], shape[j] = shape[j], shape[i]
*/
__pyx_v_j = ((__pyx_v_ndim - 1) - __pyx_v_i);
/* "View.MemoryView":918
* for i in range(ndim / 2):
* j = ndim - 1 - i
* strides[i], strides[j] = strides[j], strides[i] # <<<<<<<<<<<<<<
* shape[i], shape[j] = shape[j], shape[i]
*
*/
__pyx_t_4 = (__pyx_v_strides[__pyx_v_j]);
__pyx_t_5 = (__pyx_v_strides[__pyx_v_i]);
(__pyx_v_strides[__pyx_v_i]) = __pyx_t_4;
(__pyx_v_strides[__pyx_v_j]) = __pyx_t_5;
/* "View.MemoryView":919
* j = ndim - 1 - i
* strides[i], strides[j] = strides[j], strides[i]
* shape[i], shape[j] = shape[j], shape[i] # <<<<<<<<<<<<<<
*
* if memslice.suboffsets[i] >= 0 or memslice.suboffsets[j] >= 0:
*/
__pyx_t_5 = (__pyx_v_shape[__pyx_v_j]);
__pyx_t_4 = (__pyx_v_shape[__pyx_v_i]);
(__pyx_v_shape[__pyx_v_i]) = __pyx_t_5;
(__pyx_v_shape[__pyx_v_j]) = __pyx_t_4;
/* "View.MemoryView":921
* shape[i], shape[j] = shape[j], shape[i]
*
* if memslice.suboffsets[i] >= 0 or memslice.suboffsets[j] >= 0: # <<<<<<<<<<<<<<
* _err(ValueError, "Cannot transpose memoryview with indirect dimensions")
*
*/
__pyx_t_6 = (((__pyx_v_memslice->suboffsets[__pyx_v_i]) >= 0) != 0);
if (!__pyx_t_6) {
__pyx_t_7 = (((__pyx_v_memslice->suboffsets[__pyx_v_j]) >= 0) != 0);
__pyx_t_8 = __pyx_t_7;
} else {
__pyx_t_8 = __pyx_t_6;
}
if (__pyx_t_8) {
/* "View.MemoryView":922
*
* if memslice.suboffsets[i] >= 0 or memslice.suboffsets[j] >= 0:
* _err(ValueError, "Cannot transpose memoryview with indirect dimensions") # <<<<<<<<<<<<<<
*
* return 1
*/
__pyx_t_9 = __pyx_memoryview_err(__pyx_builtin_ValueError, __pyx_k_Cannot_transpose_memoryview_with); if (unlikely(__pyx_t_9 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 922; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
goto __pyx_L5;
}
__pyx_L5:;
}
/* "View.MemoryView":924
* _err(ValueError, "Cannot transpose memoryview with indirect dimensions")
*
* return 1 # <<<<<<<<<<<<<<
*
*
*/
__pyx_r = 1;
goto __pyx_L0;
/* "View.MemoryView":908
*
* @cname('__pyx_memslice_transpose')
* cdef int transpose_memslice(__Pyx_memviewslice *memslice) nogil except 0: # <<<<<<<<<<<<<<
* cdef int ndim = memslice.memview.view.ndim
*
*/
/* function exit code */
__pyx_L1_error:;
{
#ifdef WITH_THREAD
PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure();
#endif
__Pyx_AddTraceback("View.MemoryView.transpose_memslice", __pyx_clineno, __pyx_lineno, __pyx_filename);
#ifdef WITH_THREAD
PyGILState_Release(__pyx_gilstate_save);
#endif
}
__pyx_r = 0;
__pyx_L0:;
return __pyx_r;
}
/* "View.MemoryView":941
* cdef int (*to_dtype_func)(char *, object) except 0
*
* def __dealloc__(self): # <<<<<<<<<<<<<<
* __PYX_XDEC_MEMVIEW(&self.from_slice, 1)
*
*/
/* Python wrapper */
static void __pyx_memoryviewslice___dealloc__(PyObject *__pyx_v_self); /*proto*/
static void __pyx_memoryviewslice___dealloc__(PyObject *__pyx_v_self) {
__Pyx_RefNannyDeclarations
__Pyx_RefNannySetupContext("__dealloc__ (wrapper)", 0);
__pyx_memoryviewslice_MemoryView_16_memoryviewslice___dealloc__(((struct __pyx_memoryviewslice_obj *)__pyx_v_self));
/* function exit code */
__Pyx_RefNannyFinishContext();
}
static void __pyx_memoryviewslice_MemoryView_16_memoryviewslice___dealloc__(struct __pyx_memoryviewslice_obj *__pyx_v_self) {
__Pyx_RefNannyDeclarations
__Pyx_RefNannySetupContext("__dealloc__", 0);
/* "View.MemoryView":942
*
* def __dealloc__(self):
* __PYX_XDEC_MEMVIEW(&self.from_slice, 1) # <<<<<<<<<<<<<<
*
* cdef convert_item_to_object(self, char *itemp):
*/
__PYX_XDEC_MEMVIEW((&__pyx_v_self->from_slice), 1);
/* "View.MemoryView":941
* cdef int (*to_dtype_func)(char *, object) except 0
*
* def __dealloc__(self): # <<<<<<<<<<<<<<
* __PYX_XDEC_MEMVIEW(&self.from_slice, 1)
*
*/
/* function exit code */
__Pyx_RefNannyFinishContext();
}
/* "View.MemoryView":944
* __PYX_XDEC_MEMVIEW(&self.from_slice, 1)
*
* cdef convert_item_to_object(self, char *itemp): # <<<<<<<<<<<<<<
* if self.to_object_func != NULL:
* return self.to_object_func(itemp)
*/
static PyObject *__pyx_memoryviewslice_convert_item_to_object(struct __pyx_memoryviewslice_obj *__pyx_v_self, char *__pyx_v_itemp) {
PyObject *__pyx_r = NULL;
__Pyx_RefNannyDeclarations
int __pyx_t_1;
PyObject *__pyx_t_2 = NULL;
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
__Pyx_RefNannySetupContext("convert_item_to_object", 0);
/* "View.MemoryView":945
*
* cdef convert_item_to_object(self, char *itemp):
* if self.to_object_func != NULL: # <<<<<<<<<<<<<<
* return self.to_object_func(itemp)
* else:
*/
__pyx_t_1 = ((__pyx_v_self->to_object_func != NULL) != 0);
if (__pyx_t_1) {
/* "View.MemoryView":946
* cdef convert_item_to_object(self, char *itemp):
* if self.to_object_func != NULL:
* return self.to_object_func(itemp) # <<<<<<<<<<<<<<
* else:
* return memoryview.convert_item_to_object(self, itemp)
*/
__Pyx_XDECREF(__pyx_r);
__pyx_t_2 = __pyx_v_self->to_object_func(__pyx_v_itemp); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 946; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_2);
__pyx_r = __pyx_t_2;
__pyx_t_2 = 0;
goto __pyx_L0;
}
/*else*/ {
/* "View.MemoryView":948
* return self.to_object_func(itemp)
* else:
* return memoryview.convert_item_to_object(self, itemp) # <<<<<<<<<<<<<<
*
* cdef assign_item_from_object(self, char *itemp, object value):
*/
__Pyx_XDECREF(__pyx_r);
__pyx_t_2 = __pyx_vtabptr_memoryview->convert_item_to_object(((struct __pyx_memoryview_obj *)__pyx_v_self), __pyx_v_itemp); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 948; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_2);
__pyx_r = __pyx_t_2;
__pyx_t_2 = 0;
goto __pyx_L0;
}
/* "View.MemoryView":944
* __PYX_XDEC_MEMVIEW(&self.from_slice, 1)
*
* cdef convert_item_to_object(self, char *itemp): # <<<<<<<<<<<<<<
* if self.to_object_func != NULL:
* return self.to_object_func(itemp)
*/
/* function exit code */
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_2);
__Pyx_AddTraceback("View.MemoryView._memoryviewslice.convert_item_to_object", __pyx_clineno, __pyx_lineno, __pyx_filename);
__pyx_r = 0;
__pyx_L0:;
__Pyx_XGIVEREF(__pyx_r);
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "View.MemoryView":950
* return memoryview.convert_item_to_object(self, itemp)
*
* cdef assign_item_from_object(self, char *itemp, object value): # <<<<<<<<<<<<<<
* if self.to_dtype_func != NULL:
* self.to_dtype_func(itemp, value)
*/
static PyObject *__pyx_memoryviewslice_assign_item_from_object(struct __pyx_memoryviewslice_obj *__pyx_v_self, char *__pyx_v_itemp, PyObject *__pyx_v_value) {
PyObject *__pyx_r = NULL;
__Pyx_RefNannyDeclarations
int __pyx_t_1;
int __pyx_t_2;
PyObject *__pyx_t_3 = NULL;
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
__Pyx_RefNannySetupContext("assign_item_from_object", 0);
/* "View.MemoryView":951
*
* cdef assign_item_from_object(self, char *itemp, object value):
* if self.to_dtype_func != NULL: # <<<<<<<<<<<<<<
* self.to_dtype_func(itemp, value)
* else:
*/
__pyx_t_1 = ((__pyx_v_self->to_dtype_func != NULL) != 0);
if (__pyx_t_1) {
/* "View.MemoryView":952
* cdef assign_item_from_object(self, char *itemp, object value):
* if self.to_dtype_func != NULL:
* self.to_dtype_func(itemp, value) # <<<<<<<<<<<<<<
* else:
* memoryview.assign_item_from_object(self, itemp, value)
*/
__pyx_t_2 = __pyx_v_self->to_dtype_func(__pyx_v_itemp, __pyx_v_value); if (unlikely(__pyx_t_2 == 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 952; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
goto __pyx_L3;
}
/*else*/ {
/* "View.MemoryView":954
* self.to_dtype_func(itemp, value)
* else:
* memoryview.assign_item_from_object(self, itemp, value) # <<<<<<<<<<<<<<
*
* property base:
*/
__pyx_t_3 = __pyx_vtabptr_memoryview->assign_item_from_object(((struct __pyx_memoryview_obj *)__pyx_v_self), __pyx_v_itemp, __pyx_v_value); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 954; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_3);
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
}
__pyx_L3:;
/* "View.MemoryView":950
* return memoryview.convert_item_to_object(self, itemp)
*
* cdef assign_item_from_object(self, char *itemp, object value): # <<<<<<<<<<<<<<
* if self.to_dtype_func != NULL:
* self.to_dtype_func(itemp, value)
*/
/* function exit code */
__pyx_r = Py_None; __Pyx_INCREF(Py_None);
goto __pyx_L0;
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_3);
__Pyx_AddTraceback("View.MemoryView._memoryviewslice.assign_item_from_object", __pyx_clineno, __pyx_lineno, __pyx_filename);
__pyx_r = 0;
__pyx_L0:;
__Pyx_XGIVEREF(__pyx_r);
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "View.MemoryView":958
* property base:
* @cname('__pyx_memoryviewslice__get__base')
* def __get__(self): # <<<<<<<<<<<<<<
* return self.from_object
*
*/
/* Python wrapper */
static PyObject *__pyx_memoryviewslice__get__base(PyObject *__pyx_v_self); /*proto*/
static PyObject *__pyx_memoryviewslice__get__base(PyObject *__pyx_v_self) {
PyObject *__pyx_r = 0;
__Pyx_RefNannyDeclarations
__Pyx_RefNannySetupContext("__get__ (wrapper)", 0);
__pyx_r = __pyx_memoryviewslice__get__base_MemoryView_16_memoryviewslice_4base___get__(((struct __pyx_memoryviewslice_obj *)__pyx_v_self));
/* function exit code */
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
static PyObject *__pyx_memoryviewslice__get__base_MemoryView_16_memoryviewslice_4base___get__(struct __pyx_memoryviewslice_obj *__pyx_v_self) {
PyObject *__pyx_r = NULL;
__Pyx_RefNannyDeclarations
__Pyx_RefNannySetupContext("__get__", 0);
/* "View.MemoryView":959
* @cname('__pyx_memoryviewslice__get__base')
* def __get__(self):
* return self.from_object # <<<<<<<<<<<<<<
*
* __pyx_getbuffer = capsule(<void *> &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)")
*/
__Pyx_XDECREF(__pyx_r);
__Pyx_INCREF(__pyx_v_self->from_object);
__pyx_r = __pyx_v_self->from_object;
goto __pyx_L0;
/* "View.MemoryView":958
* property base:
* @cname('__pyx_memoryviewslice__get__base')
* def __get__(self): # <<<<<<<<<<<<<<
* return self.from_object
*
*/
/* function exit code */
__pyx_L0:;
__Pyx_XGIVEREF(__pyx_r);
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "View.MemoryView":965
*
* @cname('__pyx_memoryview_fromslice')
* cdef memoryview_fromslice(__Pyx_memviewslice memviewslice, # <<<<<<<<<<<<<<
* int ndim,
* object (*to_object_func)(char *),
*/
static PyObject *__pyx_memoryview_fromslice(__Pyx_memviewslice __pyx_v_memviewslice, int __pyx_v_ndim, PyObject *(*__pyx_v_to_object_func)(char *), int (*__pyx_v_to_dtype_func)(char *, PyObject *), int __pyx_v_dtype_is_object) {
struct __pyx_memoryviewslice_obj *__pyx_v_result = 0;
int __pyx_v_i;
PyObject *__pyx_r = NULL;
__Pyx_RefNannyDeclarations
int __pyx_t_1;
PyObject *__pyx_t_2 = NULL;
PyObject *__pyx_t_3 = NULL;
__Pyx_TypeInfo *__pyx_t_4;
Py_buffer __pyx_t_5;
Py_ssize_t __pyx_t_6;
int __pyx_t_7;
int __pyx_t_8;
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
__Pyx_RefNannySetupContext("memoryview_fromslice", 0);
/* "View.MemoryView":974
* cdef int i
*
* if <PyObject *> memviewslice.memview == Py_None: # <<<<<<<<<<<<<<
* return None
*
*/
__pyx_t_1 = ((((PyObject *)__pyx_v_memviewslice.memview) == Py_None) != 0);
if (__pyx_t_1) {
/* "View.MemoryView":975
*
* if <PyObject *> memviewslice.memview == Py_None:
* return None # <<<<<<<<<<<<<<
*
*
*/
__Pyx_XDECREF(__pyx_r);
__Pyx_INCREF(Py_None);
__pyx_r = Py_None;
goto __pyx_L0;
}
/* "View.MemoryView":980
*
*
* result = _memoryviewslice(None, 0, dtype_is_object) # <<<<<<<<<<<<<<
*
* result.from_slice = memviewslice
*/
__pyx_t_2 = __Pyx_PyBool_FromLong(__pyx_v_dtype_is_object); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 980; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_2);
__pyx_t_3 = PyTuple_New(3); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 980; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_3);
__Pyx_INCREF(Py_None);
PyTuple_SET_ITEM(__pyx_t_3, 0, Py_None);
__Pyx_GIVEREF(Py_None);
__Pyx_INCREF(__pyx_int_0);
PyTuple_SET_ITEM(__pyx_t_3, 1, __pyx_int_0);
__Pyx_GIVEREF(__pyx_int_0);
PyTuple_SET_ITEM(__pyx_t_3, 2, __pyx_t_2);
__Pyx_GIVEREF(__pyx_t_2);
__pyx_t_2 = 0;
__pyx_t_2 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_memoryviewslice_type)), __pyx_t_3, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 980; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_2);
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
__pyx_v_result = ((struct __pyx_memoryviewslice_obj *)__pyx_t_2);
__pyx_t_2 = 0;
/* "View.MemoryView":982
* result = _memoryviewslice(None, 0, dtype_is_object)
*
* result.from_slice = memviewslice # <<<<<<<<<<<<<<
* __PYX_INC_MEMVIEW(&memviewslice, 1)
*
*/
__pyx_v_result->from_slice = __pyx_v_memviewslice;
/* "View.MemoryView":983
*
* result.from_slice = memviewslice
* __PYX_INC_MEMVIEW(&memviewslice, 1) # <<<<<<<<<<<<<<
*
* result.from_object = (<memoryview> memviewslice.memview).base
*/
__PYX_INC_MEMVIEW((&__pyx_v_memviewslice), 1);
/* "View.MemoryView":985
* __PYX_INC_MEMVIEW(&memviewslice, 1)
*
* result.from_object = (<memoryview> memviewslice.memview).base # <<<<<<<<<<<<<<
* result.typeinfo = memviewslice.memview.typeinfo
*
*/
__pyx_t_2 = __Pyx_PyObject_GetAttrStr(((PyObject *)__pyx_v_memviewslice.memview), __pyx_n_s_base); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 985; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_2);
__Pyx_GIVEREF(__pyx_t_2);
__Pyx_GOTREF(__pyx_v_result->from_object);
__Pyx_DECREF(__pyx_v_result->from_object);
__pyx_v_result->from_object = __pyx_t_2;
__pyx_t_2 = 0;
/* "View.MemoryView":986
*
* result.from_object = (<memoryview> memviewslice.memview).base
* result.typeinfo = memviewslice.memview.typeinfo # <<<<<<<<<<<<<<
*
* result.view = memviewslice.memview.view
*/
__pyx_t_4 = __pyx_v_memviewslice.memview->typeinfo;
__pyx_v_result->__pyx_base.typeinfo = __pyx_t_4;
/* "View.MemoryView":988
* result.typeinfo = memviewslice.memview.typeinfo
*
* result.view = memviewslice.memview.view # <<<<<<<<<<<<<<
* result.view.buf = <void *> memviewslice.data
* result.view.ndim = ndim
*/
__pyx_t_5 = __pyx_v_memviewslice.memview->view;
__pyx_v_result->__pyx_base.view = __pyx_t_5;
/* "View.MemoryView":989
*
* result.view = memviewslice.memview.view
* result.view.buf = <void *> memviewslice.data # <<<<<<<<<<<<<<
* result.view.ndim = ndim
* (<__pyx_buffer *> &result.view).obj = Py_None
*/
__pyx_v_result->__pyx_base.view.buf = ((void *)__pyx_v_memviewslice.data);
/* "View.MemoryView":990
* result.view = memviewslice.memview.view
* result.view.buf = <void *> memviewslice.data
* result.view.ndim = ndim # <<<<<<<<<<<<<<
* (<__pyx_buffer *> &result.view).obj = Py_None
* Py_INCREF(Py_None)
*/
__pyx_v_result->__pyx_base.view.ndim = __pyx_v_ndim;
/* "View.MemoryView":991
* result.view.buf = <void *> memviewslice.data
* result.view.ndim = ndim
* (<__pyx_buffer *> &result.view).obj = Py_None # <<<<<<<<<<<<<<
* Py_INCREF(Py_None)
*
*/
((Py_buffer *)(&__pyx_v_result->__pyx_base.view))->obj = Py_None;
/* "View.MemoryView":992
* result.view.ndim = ndim
* (<__pyx_buffer *> &result.view).obj = Py_None
* Py_INCREF(Py_None) # <<<<<<<<<<<<<<
*
* result.flags = PyBUF_RECORDS
*/
Py_INCREF(Py_None);
/* "View.MemoryView":994
* Py_INCREF(Py_None)
*
* result.flags = PyBUF_RECORDS # <<<<<<<<<<<<<<
*
* result.view.shape = <Py_ssize_t *> result.from_slice.shape
*/
__pyx_v_result->__pyx_base.flags = PyBUF_RECORDS;
/* "View.MemoryView":996
* result.flags = PyBUF_RECORDS
*
* result.view.shape = <Py_ssize_t *> result.from_slice.shape # <<<<<<<<<<<<<<
* result.view.strides = <Py_ssize_t *> result.from_slice.strides
* result.view.suboffsets = <Py_ssize_t *> result.from_slice.suboffsets
*/
__pyx_v_result->__pyx_base.view.shape = ((Py_ssize_t *)__pyx_v_result->from_slice.shape);
/* "View.MemoryView":997
*
* result.view.shape = <Py_ssize_t *> result.from_slice.shape
* result.view.strides = <Py_ssize_t *> result.from_slice.strides # <<<<<<<<<<<<<<
* result.view.suboffsets = <Py_ssize_t *> result.from_slice.suboffsets
*
*/
__pyx_v_result->__pyx_base.view.strides = ((Py_ssize_t *)__pyx_v_result->from_slice.strides);
/* "View.MemoryView":998
* result.view.shape = <Py_ssize_t *> result.from_slice.shape
* result.view.strides = <Py_ssize_t *> result.from_slice.strides
* result.view.suboffsets = <Py_ssize_t *> result.from_slice.suboffsets # <<<<<<<<<<<<<<
*
* result.view.len = result.view.itemsize
*/
__pyx_v_result->__pyx_base.view.suboffsets = ((Py_ssize_t *)__pyx_v_result->from_slice.suboffsets);
/* "View.MemoryView":1000
* result.view.suboffsets = <Py_ssize_t *> result.from_slice.suboffsets
*
* result.view.len = result.view.itemsize # <<<<<<<<<<<<<<
* for i in range(ndim):
* result.view.len *= result.view.shape[i]
*/
__pyx_t_6 = __pyx_v_result->__pyx_base.view.itemsize;
__pyx_v_result->__pyx_base.view.len = __pyx_t_6;
/* "View.MemoryView":1001
*
* result.view.len = result.view.itemsize
* for i in range(ndim): # <<<<<<<<<<<<<<
* result.view.len *= result.view.shape[i]
*
*/
__pyx_t_7 = __pyx_v_ndim;
for (__pyx_t_8 = 0; __pyx_t_8 < __pyx_t_7; __pyx_t_8+=1) {
__pyx_v_i = __pyx_t_8;
/* "View.MemoryView":1002
* result.view.len = result.view.itemsize
* for i in range(ndim):
* result.view.len *= result.view.shape[i] # <<<<<<<<<<<<<<
*
* result.to_object_func = to_object_func
*/
__pyx_v_result->__pyx_base.view.len = (__pyx_v_result->__pyx_base.view.len * (__pyx_v_result->__pyx_base.view.shape[__pyx_v_i]));
}
/* "View.MemoryView":1004
* result.view.len *= result.view.shape[i]
*
* result.to_object_func = to_object_func # <<<<<<<<<<<<<<
* result.to_dtype_func = to_dtype_func
*
*/
__pyx_v_result->to_object_func = __pyx_v_to_object_func;
/* "View.MemoryView":1005
*
* result.to_object_func = to_object_func
* result.to_dtype_func = to_dtype_func # <<<<<<<<<<<<<<
*
* return result
*/
__pyx_v_result->to_dtype_func = __pyx_v_to_dtype_func;
/* "View.MemoryView":1007
* result.to_dtype_func = to_dtype_func
*
* return result # <<<<<<<<<<<<<<
*
* @cname('__pyx_memoryview_get_slice_from_memoryview')
*/
__Pyx_XDECREF(__pyx_r);
__Pyx_INCREF(((PyObject *)__pyx_v_result));
__pyx_r = ((PyObject *)__pyx_v_result);
goto __pyx_L0;
/* "View.MemoryView":965
*
* @cname('__pyx_memoryview_fromslice')
* cdef memoryview_fromslice(__Pyx_memviewslice memviewslice, # <<<<<<<<<<<<<<
* int ndim,
* object (*to_object_func)(char *),
*/
/* function exit code */
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_2);
__Pyx_XDECREF(__pyx_t_3);
__Pyx_AddTraceback("View.MemoryView.memoryview_fromslice", __pyx_clineno, __pyx_lineno, __pyx_filename);
__pyx_r = 0;
__pyx_L0:;
__Pyx_XDECREF((PyObject *)__pyx_v_result);
__Pyx_XGIVEREF(__pyx_r);
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "View.MemoryView":1010
*
* @cname('__pyx_memoryview_get_slice_from_memoryview')
* cdef __Pyx_memviewslice *get_slice_from_memview(memoryview memview, # <<<<<<<<<<<<<<
* __Pyx_memviewslice *mslice):
* cdef _memoryviewslice obj
*/
static __Pyx_memviewslice *__pyx_memoryview_get_slice_from_memoryview(struct __pyx_memoryview_obj *__pyx_v_memview, __Pyx_memviewslice *__pyx_v_mslice) {
struct __pyx_memoryviewslice_obj *__pyx_v_obj = 0;
__Pyx_memviewslice *__pyx_r;
__Pyx_RefNannyDeclarations
int __pyx_t_1;
int __pyx_t_2;
PyObject *__pyx_t_3 = NULL;
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
__Pyx_RefNannySetupContext("get_slice_from_memview", 0);
/* "View.MemoryView":1013
* __Pyx_memviewslice *mslice):
* cdef _memoryviewslice obj
* if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<<
* obj = memview
* return &obj.from_slice
*/
__pyx_t_1 = __Pyx_TypeCheck(((PyObject *)__pyx_v_memview), ((PyObject *)__pyx_memoryviewslice_type));
__pyx_t_2 = (__pyx_t_1 != 0);
if (__pyx_t_2) {
/* "View.MemoryView":1014
* cdef _memoryviewslice obj
* if isinstance(memview, _memoryviewslice):
* obj = memview # <<<<<<<<<<<<<<
* return &obj.from_slice
* else:
*/
if (!(likely(((((PyObject *)__pyx_v_memview)) == Py_None) || likely(__Pyx_TypeTest(((PyObject *)__pyx_v_memview), __pyx_memoryviewslice_type))))) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1014; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_t_3 = ((PyObject *)__pyx_v_memview);
__Pyx_INCREF(__pyx_t_3);
__pyx_v_obj = ((struct __pyx_memoryviewslice_obj *)__pyx_t_3);
__pyx_t_3 = 0;
/* "View.MemoryView":1015
* if isinstance(memview, _memoryviewslice):
* obj = memview
* return &obj.from_slice # <<<<<<<<<<<<<<
* else:
* slice_copy(memview, mslice)
*/
__pyx_r = (&__pyx_v_obj->from_slice);
goto __pyx_L0;
}
/*else*/ {
/* "View.MemoryView":1017
* return &obj.from_slice
* else:
* slice_copy(memview, mslice) # <<<<<<<<<<<<<<
* return mslice
*
*/
__pyx_memoryview_slice_copy(__pyx_v_memview, __pyx_v_mslice);
/* "View.MemoryView":1018
* else:
* slice_copy(memview, mslice)
* return mslice # <<<<<<<<<<<<<<
*
* @cname('__pyx_memoryview_slice_copy')
*/
__pyx_r = __pyx_v_mslice;
goto __pyx_L0;
}
/* "View.MemoryView":1010
*
* @cname('__pyx_memoryview_get_slice_from_memoryview')
* cdef __Pyx_memviewslice *get_slice_from_memview(memoryview memview, # <<<<<<<<<<<<<<
* __Pyx_memviewslice *mslice):
* cdef _memoryviewslice obj
*/
/* function exit code */
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_3);
__Pyx_WriteUnraisable("View.MemoryView.get_slice_from_memview", __pyx_clineno, __pyx_lineno, __pyx_filename, 0);
__pyx_r = 0;
__pyx_L0:;
__Pyx_XDECREF((PyObject *)__pyx_v_obj);
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "View.MemoryView":1021
*
* @cname('__pyx_memoryview_slice_copy')
* cdef void slice_copy(memoryview memview, __Pyx_memviewslice *dst): # <<<<<<<<<<<<<<
* cdef int dim
* cdef (Py_ssize_t*) shape, strides, suboffsets
*/
static void __pyx_memoryview_slice_copy(struct __pyx_memoryview_obj *__pyx_v_memview, __Pyx_memviewslice *__pyx_v_dst) {
int __pyx_v_dim;
Py_ssize_t *__pyx_v_shape;
Py_ssize_t *__pyx_v_strides;
Py_ssize_t *__pyx_v_suboffsets;
__Pyx_RefNannyDeclarations
Py_ssize_t *__pyx_t_1;
int __pyx_t_2;
int __pyx_t_3;
int __pyx_t_4;
__Pyx_RefNannySetupContext("slice_copy", 0);
/* "View.MemoryView":1025
* cdef (Py_ssize_t*) shape, strides, suboffsets
*
* shape = memview.view.shape # <<<<<<<<<<<<<<
* strides = memview.view.strides
* suboffsets = memview.view.suboffsets
*/
__pyx_t_1 = __pyx_v_memview->view.shape;
__pyx_v_shape = __pyx_t_1;
/* "View.MemoryView":1026
*
* shape = memview.view.shape
* strides = memview.view.strides # <<<<<<<<<<<<<<
* suboffsets = memview.view.suboffsets
*
*/
__pyx_t_1 = __pyx_v_memview->view.strides;
__pyx_v_strides = __pyx_t_1;
/* "View.MemoryView":1027
* shape = memview.view.shape
* strides = memview.view.strides
* suboffsets = memview.view.suboffsets # <<<<<<<<<<<<<<
*
* dst.memview = <__pyx_memoryview *> memview
*/
__pyx_t_1 = __pyx_v_memview->view.suboffsets;
__pyx_v_suboffsets = __pyx_t_1;
/* "View.MemoryView":1029
* suboffsets = memview.view.suboffsets
*
* dst.memview = <__pyx_memoryview *> memview # <<<<<<<<<<<<<<
* dst.data = <char *> memview.view.buf
*
*/
__pyx_v_dst->memview = ((struct __pyx_memoryview_obj *)__pyx_v_memview);
/* "View.MemoryView":1030
*
* dst.memview = <__pyx_memoryview *> memview
* dst.data = <char *> memview.view.buf # <<<<<<<<<<<<<<
*
* for dim in range(memview.view.ndim):
*/
__pyx_v_dst->data = ((char *)__pyx_v_memview->view.buf);
/* "View.MemoryView":1032
* dst.data = <char *> memview.view.buf
*
* for dim in range(memview.view.ndim): # <<<<<<<<<<<<<<
* dst.shape[dim] = shape[dim]
* dst.strides[dim] = strides[dim]
*/
__pyx_t_2 = __pyx_v_memview->view.ndim;
for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) {
__pyx_v_dim = __pyx_t_3;
/* "View.MemoryView":1033
*
* for dim in range(memview.view.ndim):
* dst.shape[dim] = shape[dim] # <<<<<<<<<<<<<<
* dst.strides[dim] = strides[dim]
* if suboffsets == NULL:
*/
(__pyx_v_dst->shape[__pyx_v_dim]) = (__pyx_v_shape[__pyx_v_dim]);
/* "View.MemoryView":1034
* for dim in range(memview.view.ndim):
* dst.shape[dim] = shape[dim]
* dst.strides[dim] = strides[dim] # <<<<<<<<<<<<<<
* if suboffsets == NULL:
* dst.suboffsets[dim] = -1
*/
(__pyx_v_dst->strides[__pyx_v_dim]) = (__pyx_v_strides[__pyx_v_dim]);
/* "View.MemoryView":1035
* dst.shape[dim] = shape[dim]
* dst.strides[dim] = strides[dim]
* if suboffsets == NULL: # <<<<<<<<<<<<<<
* dst.suboffsets[dim] = -1
* else:
*/
__pyx_t_4 = ((__pyx_v_suboffsets == NULL) != 0);
if (__pyx_t_4) {
/* "View.MemoryView":1036
* dst.strides[dim] = strides[dim]
* if suboffsets == NULL:
* dst.suboffsets[dim] = -1 # <<<<<<<<<<<<<<
* else:
* dst.suboffsets[dim] = suboffsets[dim]
*/
(__pyx_v_dst->suboffsets[__pyx_v_dim]) = -1;
goto __pyx_L5;
}
/*else*/ {
/* "View.MemoryView":1038
* dst.suboffsets[dim] = -1
* else:
* dst.suboffsets[dim] = suboffsets[dim] # <<<<<<<<<<<<<<
*
* @cname('__pyx_memoryview_copy_object')
*/
(__pyx_v_dst->suboffsets[__pyx_v_dim]) = (__pyx_v_suboffsets[__pyx_v_dim]);
}
__pyx_L5:;
}
/* "View.MemoryView":1021
*
* @cname('__pyx_memoryview_slice_copy')
* cdef void slice_copy(memoryview memview, __Pyx_memviewslice *dst): # <<<<<<<<<<<<<<
* cdef int dim
* cdef (Py_ssize_t*) shape, strides, suboffsets
*/
/* function exit code */
__Pyx_RefNannyFinishContext();
}
/* "View.MemoryView":1041
*
* @cname('__pyx_memoryview_copy_object')
* cdef memoryview_copy(memoryview memview): # <<<<<<<<<<<<<<
* "Create a new memoryview object"
* cdef __Pyx_memviewslice memviewslice
*/
static PyObject *__pyx_memoryview_copy_object(struct __pyx_memoryview_obj *__pyx_v_memview) {
__Pyx_memviewslice __pyx_v_memviewslice;
PyObject *__pyx_r = NULL;
__Pyx_RefNannyDeclarations
PyObject *__pyx_t_1 = NULL;
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
__Pyx_RefNannySetupContext("memoryview_copy", 0);
/* "View.MemoryView":1044
* "Create a new memoryview object"
* cdef __Pyx_memviewslice memviewslice
* slice_copy(memview, &memviewslice) # <<<<<<<<<<<<<<
* return memoryview_copy_from_slice(memview, &memviewslice)
*
*/
__pyx_memoryview_slice_copy(__pyx_v_memview, (&__pyx_v_memviewslice));
/* "View.MemoryView":1045
* cdef __Pyx_memviewslice memviewslice
* slice_copy(memview, &memviewslice)
* return memoryview_copy_from_slice(memview, &memviewslice) # <<<<<<<<<<<<<<
*
* @cname('__pyx_memoryview_copy_object_from_slice')
*/
__Pyx_XDECREF(__pyx_r);
__pyx_t_1 = __pyx_memoryview_copy_object_from_slice(__pyx_v_memview, (&__pyx_v_memviewslice)); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1045; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
__pyx_r = __pyx_t_1;
__pyx_t_1 = 0;
goto __pyx_L0;
/* "View.MemoryView":1041
*
* @cname('__pyx_memoryview_copy_object')
* cdef memoryview_copy(memoryview memview): # <<<<<<<<<<<<<<
* "Create a new memoryview object"
* cdef __Pyx_memviewslice memviewslice
*/
/* function exit code */
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_1);
__Pyx_AddTraceback("View.MemoryView.memoryview_copy", __pyx_clineno, __pyx_lineno, __pyx_filename);
__pyx_r = 0;
__pyx_L0:;
__Pyx_XGIVEREF(__pyx_r);
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "View.MemoryView":1048
*
* @cname('__pyx_memoryview_copy_object_from_slice')
* cdef memoryview_copy_from_slice(memoryview memview, __Pyx_memviewslice *memviewslice): # <<<<<<<<<<<<<<
* """
* Create a new memoryview object from a given memoryview object and slice.
*/
static PyObject *__pyx_memoryview_copy_object_from_slice(struct __pyx_memoryview_obj *__pyx_v_memview, __Pyx_memviewslice *__pyx_v_memviewslice) {
PyObject *(*__pyx_v_to_object_func)(char *);
int (*__pyx_v_to_dtype_func)(char *, PyObject *);
PyObject *__pyx_r = NULL;
__Pyx_RefNannyDeclarations
int __pyx_t_1;
int __pyx_t_2;
PyObject *(*__pyx_t_3)(char *);
int (*__pyx_t_4)(char *, PyObject *);
PyObject *__pyx_t_5 = NULL;
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
__Pyx_RefNannySetupContext("memoryview_copy_from_slice", 0);
/* "View.MemoryView":1055
* cdef int (*to_dtype_func)(char *, object) except 0
*
* if isinstance(memview, _memoryviewslice): # <<<<<<<<<<<<<<
* to_object_func = (<_memoryviewslice> memview).to_object_func
* to_dtype_func = (<_memoryviewslice> memview).to_dtype_func
*/
__pyx_t_1 = __Pyx_TypeCheck(((PyObject *)__pyx_v_memview), ((PyObject *)__pyx_memoryviewslice_type));
__pyx_t_2 = (__pyx_t_1 != 0);
if (__pyx_t_2) {
/* "View.MemoryView":1056
*
* if isinstance(memview, _memoryviewslice):
* to_object_func = (<_memoryviewslice> memview).to_object_func # <<<<<<<<<<<<<<
* to_dtype_func = (<_memoryviewslice> memview).to_dtype_func
* else:
*/
__pyx_t_3 = ((struct __pyx_memoryviewslice_obj *)__pyx_v_memview)->to_object_func;
__pyx_v_to_object_func = __pyx_t_3;
/* "View.MemoryView":1057
* if isinstance(memview, _memoryviewslice):
* to_object_func = (<_memoryviewslice> memview).to_object_func
* to_dtype_func = (<_memoryviewslice> memview).to_dtype_func # <<<<<<<<<<<<<<
* else:
* to_object_func = NULL
*/
__pyx_t_4 = ((struct __pyx_memoryviewslice_obj *)__pyx_v_memview)->to_dtype_func;
__pyx_v_to_dtype_func = __pyx_t_4;
goto __pyx_L3;
}
/*else*/ {
/* "View.MemoryView":1059
* to_dtype_func = (<_memoryviewslice> memview).to_dtype_func
* else:
* to_object_func = NULL # <<<<<<<<<<<<<<
* to_dtype_func = NULL
*
*/
__pyx_v_to_object_func = NULL;
/* "View.MemoryView":1060
* else:
* to_object_func = NULL
* to_dtype_func = NULL # <<<<<<<<<<<<<<
*
* return memoryview_fromslice(memviewslice[0], memview.view.ndim,
*/
__pyx_v_to_dtype_func = NULL;
}
__pyx_L3:;
/* "View.MemoryView":1062
* to_dtype_func = NULL
*
* return memoryview_fromslice(memviewslice[0], memview.view.ndim, # <<<<<<<<<<<<<<
* to_object_func, to_dtype_func,
* memview.dtype_is_object)
*/
__Pyx_XDECREF(__pyx_r);
/* "View.MemoryView":1064
* return memoryview_fromslice(memviewslice[0], memview.view.ndim,
* to_object_func, to_dtype_func,
* memview.dtype_is_object) # <<<<<<<<<<<<<<
*
*
*/
__pyx_t_5 = __pyx_memoryview_fromslice((__pyx_v_memviewslice[0]), __pyx_v_memview->view.ndim, __pyx_v_to_object_func, __pyx_v_to_dtype_func, __pyx_v_memview->dtype_is_object); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1062; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_5);
__pyx_r = __pyx_t_5;
__pyx_t_5 = 0;
goto __pyx_L0;
/* "View.MemoryView":1048
*
* @cname('__pyx_memoryview_copy_object_from_slice')
* cdef memoryview_copy_from_slice(memoryview memview, __Pyx_memviewslice *memviewslice): # <<<<<<<<<<<<<<
* """
* Create a new memoryview object from a given memoryview object and slice.
*/
/* function exit code */
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_5);
__Pyx_AddTraceback("View.MemoryView.memoryview_copy_from_slice", __pyx_clineno, __pyx_lineno, __pyx_filename);
__pyx_r = 0;
__pyx_L0:;
__Pyx_XGIVEREF(__pyx_r);
__Pyx_RefNannyFinishContext();
return __pyx_r;
}
/* "View.MemoryView":1070
*
*
* cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: # <<<<<<<<<<<<<<
* if arg < 0:
* return -arg
*/
static Py_ssize_t abs_py_ssize_t(Py_ssize_t __pyx_v_arg) {
Py_ssize_t __pyx_r;
int __pyx_t_1;
/* "View.MemoryView":1071
*
* cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil:
* if arg < 0: # <<<<<<<<<<<<<<
* return -arg
* else:
*/
__pyx_t_1 = ((__pyx_v_arg < 0) != 0);
if (__pyx_t_1) {
/* "View.MemoryView":1072
* cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil:
* if arg < 0:
* return -arg # <<<<<<<<<<<<<<
* else:
* return arg
*/
__pyx_r = (-__pyx_v_arg);
goto __pyx_L0;
}
/*else*/ {
/* "View.MemoryView":1074
* return -arg
* else:
* return arg # <<<<<<<<<<<<<<
*
* @cname('__pyx_get_best_slice_order')
*/
__pyx_r = __pyx_v_arg;
goto __pyx_L0;
}
/* "View.MemoryView":1070
*
*
* cdef Py_ssize_t abs_py_ssize_t(Py_ssize_t arg) nogil: # <<<<<<<<<<<<<<
* if arg < 0:
* return -arg
*/
/* function exit code */
__pyx_L0:;
return __pyx_r;
}
/* "View.MemoryView":1077
*
* @cname('__pyx_get_best_slice_order')
* cdef char get_best_order(__Pyx_memviewslice *mslice, int ndim) nogil: # <<<<<<<<<<<<<<
* """
* Figure out the best memory access order for a given slice.
*/
static char __pyx_get_best_slice_order(__Pyx_memviewslice *__pyx_v_mslice, int __pyx_v_ndim) {
int __pyx_v_i;
Py_ssize_t __pyx_v_c_stride;
Py_ssize_t __pyx_v_f_stride;
char __pyx_r;
int __pyx_t_1;
int __pyx_t_2;
int __pyx_t_3;
/* "View.MemoryView":1082
* """
* cdef int i
* cdef Py_ssize_t c_stride = 0 # <<<<<<<<<<<<<<
* cdef Py_ssize_t f_stride = 0
*
*/
__pyx_v_c_stride = 0;
/* "View.MemoryView":1083
* cdef int i
* cdef Py_ssize_t c_stride = 0
* cdef Py_ssize_t f_stride = 0 # <<<<<<<<<<<<<<
*
* for i in range(ndim - 1, -1, -1):
*/
__pyx_v_f_stride = 0;
/* "View.MemoryView":1085
* cdef Py_ssize_t f_stride = 0
*
* for i in range(ndim - 1, -1, -1): # <<<<<<<<<<<<<<
* if mslice.shape[i] > 1:
* c_stride = mslice.strides[i]
*/
for (__pyx_t_1 = (__pyx_v_ndim - 1); __pyx_t_1 > -1; __pyx_t_1-=1) {
__pyx_v_i = __pyx_t_1;
/* "View.MemoryView":1086
*
* for i in range(ndim - 1, -1, -1):
* if mslice.shape[i] > 1: # <<<<<<<<<<<<<<
* c_stride = mslice.strides[i]
* break
*/
__pyx_t_2 = (((__pyx_v_mslice->shape[__pyx_v_i]) > 1) != 0);
if (__pyx_t_2) {
/* "View.MemoryView":1087
* for i in range(ndim - 1, -1, -1):
* if mslice.shape[i] > 1:
* c_stride = mslice.strides[i] # <<<<<<<<<<<<<<
* break
*
*/
__pyx_v_c_stride = (__pyx_v_mslice->strides[__pyx_v_i]);
/* "View.MemoryView":1088
* if mslice.shape[i] > 1:
* c_stride = mslice.strides[i]
* break # <<<<<<<<<<<<<<
*
* for i in range(ndim):
*/
goto __pyx_L4_break;
}
}
__pyx_L4_break:;
/* "View.MemoryView":1090
* break
*
* for i in range(ndim): # <<<<<<<<<<<<<<
* if mslice.shape[i] > 1:
* f_stride = mslice.strides[i]
*/
__pyx_t_1 = __pyx_v_ndim;
for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_1; __pyx_t_3+=1) {
__pyx_v_i = __pyx_t_3;
/* "View.MemoryView":1091
*
* for i in range(ndim):
* if mslice.shape[i] > 1: # <<<<<<<<<<<<<<
* f_stride = mslice.strides[i]
* break
*/
__pyx_t_2 = (((__pyx_v_mslice->shape[__pyx_v_i]) > 1) != 0);
if (__pyx_t_2) {
/* "View.MemoryView":1092
* for i in range(ndim):
* if mslice.shape[i] > 1:
* f_stride = mslice.strides[i] # <<<<<<<<<<<<<<
* break
*
*/
__pyx_v_f_stride = (__pyx_v_mslice->strides[__pyx_v_i]);
/* "View.MemoryView":1093
* if mslice.shape[i] > 1:
* f_stride = mslice.strides[i]
* break # <<<<<<<<<<<<<<
*
* if abs_py_ssize_t(c_stride) <= abs_py_ssize_t(f_stride):
*/
goto __pyx_L7_break;
}
}
__pyx_L7_break:;
/* "View.MemoryView":1095
* break
*
* if abs_py_ssize_t(c_stride) <= abs_py_ssize_t(f_stride): # <<<<<<<<<<<<<<
* return 'C'
* else:
*/
__pyx_t_2 = ((abs_py_ssize_t(__pyx_v_c_stride) <= abs_py_ssize_t(__pyx_v_f_stride)) != 0);
if (__pyx_t_2) {
/* "View.MemoryView":1096
*
* if abs_py_ssize_t(c_stride) <= abs_py_ssize_t(f_stride):
* return 'C' # <<<<<<<<<<<<<<
* else:
* return 'F'
*/
__pyx_r = 'C';
goto __pyx_L0;
}
/*else*/ {
/* "View.MemoryView":1098
* return 'C'
* else:
* return 'F' # <<<<<<<<<<<<<<
*
* @cython.cdivision(True)
*/
__pyx_r = 'F';
goto __pyx_L0;
}
/* "View.MemoryView":1077
*
* @cname('__pyx_get_best_slice_order')
* cdef char get_best_order(__Pyx_memviewslice *mslice, int ndim) nogil: # <<<<<<<<<<<<<<
* """
* Figure out the best memory access order for a given slice.
*/
/* function exit code */
__pyx_L0:;
return __pyx_r;
}
/* "View.MemoryView":1101
*
* @cython.cdivision(True)
* cdef void _copy_strided_to_strided(char *src_data, Py_ssize_t *src_strides, # <<<<<<<<<<<<<<
* char *dst_data, Py_ssize_t *dst_strides,
* Py_ssize_t *src_shape, Py_ssize_t *dst_shape,
*/
static void _copy_strided_to_strided(char *__pyx_v_src_data, Py_ssize_t *__pyx_v_src_strides, char *__pyx_v_dst_data, Py_ssize_t *__pyx_v_dst_strides, Py_ssize_t *__pyx_v_src_shape, Py_ssize_t *__pyx_v_dst_shape, int __pyx_v_ndim, size_t __pyx_v_itemsize) {
CYTHON_UNUSED Py_ssize_t __pyx_v_i;
CYTHON_UNUSED Py_ssize_t __pyx_v_src_extent;
Py_ssize_t __pyx_v_dst_extent;
Py_ssize_t __pyx_v_src_stride;
Py_ssize_t __pyx_v_dst_stride;
int __pyx_t_1;
int __pyx_t_2;
int __pyx_t_3;
int __pyx_t_4;
Py_ssize_t __pyx_t_5;
Py_ssize_t __pyx_t_6;
/* "View.MemoryView":1108
*
* cdef Py_ssize_t i
* cdef Py_ssize_t src_extent = src_shape[0] # <<<<<<<<<<<<<<
* cdef Py_ssize_t dst_extent = dst_shape[0]
* cdef Py_ssize_t src_stride = src_strides[0]
*/
__pyx_v_src_extent = (__pyx_v_src_shape[0]);
/* "View.MemoryView":1109
* cdef Py_ssize_t i
* cdef Py_ssize_t src_extent = src_shape[0]
* cdef Py_ssize_t dst_extent = dst_shape[0] # <<<<<<<<<<<<<<
* cdef Py_ssize_t src_stride = src_strides[0]
* cdef Py_ssize_t dst_stride = dst_strides[0]
*/
__pyx_v_dst_extent = (__pyx_v_dst_shape[0]);
/* "View.MemoryView":1110
* cdef Py_ssize_t src_extent = src_shape[0]
* cdef Py_ssize_t dst_extent = dst_shape[0]
* cdef Py_ssize_t src_stride = src_strides[0] # <<<<<<<<<<<<<<
* cdef Py_ssize_t dst_stride = dst_strides[0]
*
*/
__pyx_v_src_stride = (__pyx_v_src_strides[0]);
/* "View.MemoryView":1111
* cdef Py_ssize_t dst_extent = dst_shape[0]
* cdef Py_ssize_t src_stride = src_strides[0]
* cdef Py_ssize_t dst_stride = dst_strides[0] # <<<<<<<<<<<<<<
*
* if ndim == 1:
*/
__pyx_v_dst_stride = (__pyx_v_dst_strides[0]);
/* "View.MemoryView":1113
* cdef Py_ssize_t dst_stride = dst_strides[0]
*
* if ndim == 1: # <<<<<<<<<<<<<<
* if (src_stride > 0 and dst_stride > 0 and
* <size_t> src_stride == itemsize == <size_t> dst_stride):
*/
__pyx_t_1 = ((__pyx_v_ndim == 1) != 0);
if (__pyx_t_1) {
/* "View.MemoryView":1114
*
* if ndim == 1:
* if (src_stride > 0 and dst_stride > 0 and # <<<<<<<<<<<<<<
* <size_t> src_stride == itemsize == <size_t> dst_stride):
* memcpy(dst_data, src_data, itemsize * dst_extent)
*/
__pyx_t_1 = ((__pyx_v_src_stride > 0) != 0);
if (__pyx_t_1) {
__pyx_t_2 = ((__pyx_v_dst_stride > 0) != 0);
if (__pyx_t_2) {
/* "View.MemoryView":1115
* if ndim == 1:
* if (src_stride > 0 and dst_stride > 0 and
* <size_t> src_stride == itemsize == <size_t> dst_stride): # <<<<<<<<<<<<<<
* memcpy(dst_data, src_data, itemsize * dst_extent)
* else:
*/
__pyx_t_3 = (((size_t)__pyx_v_src_stride) == __pyx_v_itemsize);
if (__pyx_t_3) {
__pyx_t_3 = (__pyx_v_itemsize == ((size_t)__pyx_v_dst_stride));
}
__pyx_t_4 = (__pyx_t_3 != 0);
} else {
__pyx_t_4 = __pyx_t_2;
}
__pyx_t_2 = __pyx_t_4;
} else {
__pyx_t_2 = __pyx_t_1;
}
if (__pyx_t_2) {
/* "View.MemoryView":1116
* if (src_stride > 0 and dst_stride > 0 and
* <size_t> src_stride == itemsize == <size_t> dst_stride):
* memcpy(dst_data, src_data, itemsize * dst_extent) # <<<<<<<<<<<<<<
* else:
* for i in range(dst_extent):
*/
memcpy(__pyx_v_dst_data, __pyx_v_src_data, (__pyx_v_itemsize * __pyx_v_dst_extent));
goto __pyx_L4;
}
/*else*/ {
/* "View.MemoryView":1118
* memcpy(dst_data, src_data, itemsize * dst_extent)
* else:
* for i in range(dst_extent): # <<<<<<<<<<<<<<
* memcpy(dst_data, src_data, itemsize)
* src_data += src_stride
*/
__pyx_t_5 = __pyx_v_dst_extent;
for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) {
__pyx_v_i = __pyx_t_6;
/* "View.MemoryView":1119
* else:
* for i in range(dst_extent):
* memcpy(dst_data, src_data, itemsize) # <<<<<<<<<<<<<<
* src_data += src_stride
* dst_data += dst_stride
*/
memcpy(__pyx_v_dst_data, __pyx_v_src_data, __pyx_v_itemsize);
/* "View.MemoryView":1120
* for i in range(dst_extent):
* memcpy(dst_data, src_data, itemsize)
* src_data += src_stride # <<<<<<<<<<<<<<
* dst_data += dst_stride
* else:
*/
__pyx_v_src_data = (__pyx_v_src_data + __pyx_v_src_stride);
/* "View.MemoryView":1121
* memcpy(dst_data, src_data, itemsize)
* src_data += src_stride
* dst_data += dst_stride # <<<<<<<<<<<<<<
* else:
* for i in range(dst_extent):
*/
__pyx_v_dst_data = (__pyx_v_dst_data + __pyx_v_dst_stride);
}
}
__pyx_L4:;
goto __pyx_L3;
}
/*else*/ {
/* "View.MemoryView":1123
* dst_data += dst_stride
* else:
* for i in range(dst_extent): # <<<<<<<<<<<<<<
* _copy_strided_to_strided(src_data, src_strides + 1,
* dst_data, dst_strides + 1,
*/
__pyx_t_5 = __pyx_v_dst_extent;
for (__pyx_t_6 = 0; __pyx_t_6 < __pyx_t_5; __pyx_t_6+=1) {
__pyx_v_i = __pyx_t_6;
/* "View.MemoryView":1124
* else:
* for i in range(dst_extent):
* _copy_strided_to_strided(src_data, src_strides + 1, # <<<<<<<<<<<<<<
* dst_data, dst_strides + 1,
* src_shape + 1, dst_shape + 1,
*/
_copy_strided_to_strided(__pyx_v_src_data, (__pyx_v_src_strides + 1), __pyx_v_dst_data, (__pyx_v_dst_strides + 1), (__pyx_v_src_shape + 1), (__pyx_v_dst_shape + 1), (__pyx_v_ndim - 1), __pyx_v_itemsize);
/* "View.MemoryView":1128
* src_shape + 1, dst_shape + 1,
* ndim - 1, itemsize)
* src_data += src_stride # <<<<<<<<<<<<<<
* dst_data += dst_stride
*
*/
__pyx_v_src_data = (__pyx_v_src_data + __pyx_v_src_stride);
/* "View.MemoryView":1129
* ndim - 1, itemsize)
* src_data += src_stride
* dst_data += dst_stride # <<<<<<<<<<<<<<
*
* cdef void copy_strided_to_strided(__Pyx_memviewslice *src,
*/
__pyx_v_dst_data = (__pyx_v_dst_data + __pyx_v_dst_stride);
}
}
__pyx_L3:;
/* "View.MemoryView":1101
*
* @cython.cdivision(True)
* cdef void _copy_strided_to_strided(char *src_data, Py_ssize_t *src_strides, # <<<<<<<<<<<<<<
* char *dst_data, Py_ssize_t *dst_strides,
* Py_ssize_t *src_shape, Py_ssize_t *dst_shape,
*/
/* function exit code */
}
/* "View.MemoryView":1131
* dst_data += dst_stride
*
* cdef void copy_strided_to_strided(__Pyx_memviewslice *src, # <<<<<<<<<<<<<<
* __Pyx_memviewslice *dst,
* int ndim, size_t itemsize) nogil:
*/
static void copy_strided_to_strided(__Pyx_memviewslice *__pyx_v_src, __Pyx_memviewslice *__pyx_v_dst, int __pyx_v_ndim, size_t __pyx_v_itemsize) {
/* "View.MemoryView":1134
* __Pyx_memviewslice *dst,
* int ndim, size_t itemsize) nogil:
* _copy_strided_to_strided(src.data, src.strides, dst.data, dst.strides, # <<<<<<<<<<<<<<
* src.shape, dst.shape, ndim, itemsize)
*
*/
_copy_strided_to_strided(__pyx_v_src->data, __pyx_v_src->strides, __pyx_v_dst->data, __pyx_v_dst->strides, __pyx_v_src->shape, __pyx_v_dst->shape, __pyx_v_ndim, __pyx_v_itemsize);
/* "View.MemoryView":1131
* dst_data += dst_stride
*
* cdef void copy_strided_to_strided(__Pyx_memviewslice *src, # <<<<<<<<<<<<<<
* __Pyx_memviewslice *dst,
* int ndim, size_t itemsize) nogil:
*/
/* function exit code */
}
/* "View.MemoryView":1138
*
* @cname('__pyx_memoryview_slice_get_size')
* cdef Py_ssize_t slice_get_size(__Pyx_memviewslice *src, int ndim) nogil: # <<<<<<<<<<<<<<
* "Return the size of the memory occupied by the slice in number of bytes"
* cdef int i
*/
static Py_ssize_t __pyx_memoryview_slice_get_size(__Pyx_memviewslice *__pyx_v_src, int __pyx_v_ndim) {
int __pyx_v_i;
Py_ssize_t __pyx_v_size;
Py_ssize_t __pyx_r;
Py_ssize_t __pyx_t_1;
int __pyx_t_2;
int __pyx_t_3;
/* "View.MemoryView":1141
* "Return the size of the memory occupied by the slice in number of bytes"
* cdef int i
* cdef Py_ssize_t size = src.memview.view.itemsize # <<<<<<<<<<<<<<
*
* for i in range(ndim):
*/
__pyx_t_1 = __pyx_v_src->memview->view.itemsize;
__pyx_v_size = __pyx_t_1;
/* "View.MemoryView":1143
* cdef Py_ssize_t size = src.memview.view.itemsize
*
* for i in range(ndim): # <<<<<<<<<<<<<<
* size *= src.shape[i]
*
*/
__pyx_t_2 = __pyx_v_ndim;
for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) {
__pyx_v_i = __pyx_t_3;
/* "View.MemoryView":1144
*
* for i in range(ndim):
* size *= src.shape[i] # <<<<<<<<<<<<<<
*
* return size
*/
__pyx_v_size = (__pyx_v_size * (__pyx_v_src->shape[__pyx_v_i]));
}
/* "View.MemoryView":1146
* size *= src.shape[i]
*
* return size # <<<<<<<<<<<<<<
*
* @cname('__pyx_fill_contig_strides_array')
*/
__pyx_r = __pyx_v_size;
goto __pyx_L0;
/* "View.MemoryView":1138
*
* @cname('__pyx_memoryview_slice_get_size')
* cdef Py_ssize_t slice_get_size(__Pyx_memviewslice *src, int ndim) nogil: # <<<<<<<<<<<<<<
* "Return the size of the memory occupied by the slice in number of bytes"
* cdef int i
*/
/* function exit code */
__pyx_L0:;
return __pyx_r;
}
/* "View.MemoryView":1149
*
* @cname('__pyx_fill_contig_strides_array')
* cdef Py_ssize_t fill_contig_strides_array( # <<<<<<<<<<<<<<
* Py_ssize_t *shape, Py_ssize_t *strides, Py_ssize_t stride,
* int ndim, char order) nogil:
*/
static Py_ssize_t __pyx_fill_contig_strides_array(Py_ssize_t *__pyx_v_shape, Py_ssize_t *__pyx_v_strides, Py_ssize_t __pyx_v_stride, int __pyx_v_ndim, char __pyx_v_order) {
int __pyx_v_idx;
Py_ssize_t __pyx_r;
int __pyx_t_1;
int __pyx_t_2;
int __pyx_t_3;
/* "View.MemoryView":1158
* cdef int idx
*
* if order == 'F': # <<<<<<<<<<<<<<
* for idx in range(ndim):
* strides[idx] = stride
*/
__pyx_t_1 = ((__pyx_v_order == 'F') != 0);
if (__pyx_t_1) {
/* "View.MemoryView":1159
*
* if order == 'F':
* for idx in range(ndim): # <<<<<<<<<<<<<<
* strides[idx] = stride
* stride = stride * shape[idx]
*/
__pyx_t_2 = __pyx_v_ndim;
for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) {
__pyx_v_idx = __pyx_t_3;
/* "View.MemoryView":1160
* if order == 'F':
* for idx in range(ndim):
* strides[idx] = stride # <<<<<<<<<<<<<<
* stride = stride * shape[idx]
* else:
*/
(__pyx_v_strides[__pyx_v_idx]) = __pyx_v_stride;
/* "View.MemoryView":1161
* for idx in range(ndim):
* strides[idx] = stride
* stride = stride * shape[idx] # <<<<<<<<<<<<<<
* else:
* for idx in range(ndim - 1, -1, -1):
*/
__pyx_v_stride = (__pyx_v_stride * (__pyx_v_shape[__pyx_v_idx]));
}
goto __pyx_L3;
}
/*else*/ {
/* "View.MemoryView":1163
* stride = stride * shape[idx]
* else:
* for idx in range(ndim - 1, -1, -1): # <<<<<<<<<<<<<<
* strides[idx] = stride
* stride = stride * shape[idx]
*/
for (__pyx_t_2 = (__pyx_v_ndim - 1); __pyx_t_2 > -1; __pyx_t_2-=1) {
__pyx_v_idx = __pyx_t_2;
/* "View.MemoryView":1164
* else:
* for idx in range(ndim - 1, -1, -1):
* strides[idx] = stride # <<<<<<<<<<<<<<
* stride = stride * shape[idx]
*
*/
(__pyx_v_strides[__pyx_v_idx]) = __pyx_v_stride;
/* "View.MemoryView":1165
* for idx in range(ndim - 1, -1, -1):
* strides[idx] = stride
* stride = stride * shape[idx] # <<<<<<<<<<<<<<
*
* return stride
*/
__pyx_v_stride = (__pyx_v_stride * (__pyx_v_shape[__pyx_v_idx]));
}
}
__pyx_L3:;
/* "View.MemoryView":1167
* stride = stride * shape[idx]
*
* return stride # <<<<<<<<<<<<<<
*
* @cname('__pyx_memoryview_copy_data_to_temp')
*/
__pyx_r = __pyx_v_stride;
goto __pyx_L0;
/* "View.MemoryView":1149
*
* @cname('__pyx_fill_contig_strides_array')
* cdef Py_ssize_t fill_contig_strides_array( # <<<<<<<<<<<<<<
* Py_ssize_t *shape, Py_ssize_t *strides, Py_ssize_t stride,
* int ndim, char order) nogil:
*/
/* function exit code */
__pyx_L0:;
return __pyx_r;
}
/* "View.MemoryView":1170
*
* @cname('__pyx_memoryview_copy_data_to_temp')
* cdef void *copy_data_to_temp(__Pyx_memviewslice *src, # <<<<<<<<<<<<<<
* __Pyx_memviewslice *tmpslice,
* char order,
*/
static void *__pyx_memoryview_copy_data_to_temp(__Pyx_memviewslice *__pyx_v_src, __Pyx_memviewslice *__pyx_v_tmpslice, char __pyx_v_order, int __pyx_v_ndim) {
int __pyx_v_i;
void *__pyx_v_result;
size_t __pyx_v_itemsize;
size_t __pyx_v_size;
void *__pyx_r;
Py_ssize_t __pyx_t_1;
int __pyx_t_2;
int __pyx_t_3;
struct __pyx_memoryview_obj *__pyx_t_4;
int __pyx_t_5;
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
/* "View.MemoryView":1181
* cdef void *result
*
* cdef size_t itemsize = src.memview.view.itemsize # <<<<<<<<<<<<<<
* cdef size_t size = slice_get_size(src, ndim)
*
*/
__pyx_t_1 = __pyx_v_src->memview->view.itemsize;
__pyx_v_itemsize = __pyx_t_1;
/* "View.MemoryView":1182
*
* cdef size_t itemsize = src.memview.view.itemsize
* cdef size_t size = slice_get_size(src, ndim) # <<<<<<<<<<<<<<
*
* result = malloc(size)
*/
__pyx_v_size = __pyx_memoryview_slice_get_size(__pyx_v_src, __pyx_v_ndim);
/* "View.MemoryView":1184
* cdef size_t size = slice_get_size(src, ndim)
*
* result = malloc(size) # <<<<<<<<<<<<<<
* if not result:
* _err(MemoryError, NULL)
*/
__pyx_v_result = malloc(__pyx_v_size);
/* "View.MemoryView":1185
*
* result = malloc(size)
* if not result: # <<<<<<<<<<<<<<
* _err(MemoryError, NULL)
*
*/
__pyx_t_2 = ((!(__pyx_v_result != 0)) != 0);
if (__pyx_t_2) {
/* "View.MemoryView":1186
* result = malloc(size)
* if not result:
* _err(MemoryError, NULL) # <<<<<<<<<<<<<<
*
*
*/
__pyx_t_3 = __pyx_memoryview_err(__pyx_builtin_MemoryError, NULL); if (unlikely(__pyx_t_3 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1186; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
goto __pyx_L3;
}
__pyx_L3:;
/* "View.MemoryView":1189
*
*
* tmpslice.data = <char *> result # <<<<<<<<<<<<<<
* tmpslice.memview = src.memview
* for i in range(ndim):
*/
__pyx_v_tmpslice->data = ((char *)__pyx_v_result);
/* "View.MemoryView":1190
*
* tmpslice.data = <char *> result
* tmpslice.memview = src.memview # <<<<<<<<<<<<<<
* for i in range(ndim):
* tmpslice.shape[i] = src.shape[i]
*/
__pyx_t_4 = __pyx_v_src->memview;
__pyx_v_tmpslice->memview = __pyx_t_4;
/* "View.MemoryView":1191
* tmpslice.data = <char *> result
* tmpslice.memview = src.memview
* for i in range(ndim): # <<<<<<<<<<<<<<
* tmpslice.shape[i] = src.shape[i]
* tmpslice.suboffsets[i] = -1
*/
__pyx_t_3 = __pyx_v_ndim;
for (__pyx_t_5 = 0; __pyx_t_5 < __pyx_t_3; __pyx_t_5+=1) {
__pyx_v_i = __pyx_t_5;
/* "View.MemoryView":1192
* tmpslice.memview = src.memview
* for i in range(ndim):
* tmpslice.shape[i] = src.shape[i] # <<<<<<<<<<<<<<
* tmpslice.suboffsets[i] = -1
*
*/
(__pyx_v_tmpslice->shape[__pyx_v_i]) = (__pyx_v_src->shape[__pyx_v_i]);
/* "View.MemoryView":1193
* for i in range(ndim):
* tmpslice.shape[i] = src.shape[i]
* tmpslice.suboffsets[i] = -1 # <<<<<<<<<<<<<<
*
* fill_contig_strides_array(&tmpslice.shape[0], &tmpslice.strides[0], itemsize,
*/
(__pyx_v_tmpslice->suboffsets[__pyx_v_i]) = -1;
}
/* "View.MemoryView":1195
* tmpslice.suboffsets[i] = -1
*
* fill_contig_strides_array(&tmpslice.shape[0], &tmpslice.strides[0], itemsize, # <<<<<<<<<<<<<<
* ndim, order)
*
*/
__pyx_fill_contig_strides_array((&(__pyx_v_tmpslice->shape[0])), (&(__pyx_v_tmpslice->strides[0])), __pyx_v_itemsize, __pyx_v_ndim, __pyx_v_order);
/* "View.MemoryView":1199
*
*
* for i in range(ndim): # <<<<<<<<<<<<<<
* if tmpslice.shape[i] == 1:
* tmpslice.strides[i] = 0
*/
__pyx_t_3 = __pyx_v_ndim;
for (__pyx_t_5 = 0; __pyx_t_5 < __pyx_t_3; __pyx_t_5+=1) {
__pyx_v_i = __pyx_t_5;
/* "View.MemoryView":1200
*
* for i in range(ndim):
* if tmpslice.shape[i] == 1: # <<<<<<<<<<<<<<
* tmpslice.strides[i] = 0
*
*/
__pyx_t_2 = (((__pyx_v_tmpslice->shape[__pyx_v_i]) == 1) != 0);
if (__pyx_t_2) {
/* "View.MemoryView":1201
* for i in range(ndim):
* if tmpslice.shape[i] == 1:
* tmpslice.strides[i] = 0 # <<<<<<<<<<<<<<
*
* if slice_is_contig(src, order, ndim):
*/
(__pyx_v_tmpslice->strides[__pyx_v_i]) = 0;
goto __pyx_L8;
}
__pyx_L8:;
}
/* "View.MemoryView":1203
* tmpslice.strides[i] = 0
*
* if slice_is_contig(src, order, ndim): # <<<<<<<<<<<<<<
* memcpy(result, src.data, size)
* else:
*/
__pyx_t_2 = (__pyx_memviewslice_is_contig(__pyx_v_src, __pyx_v_order, __pyx_v_ndim) != 0);
if (__pyx_t_2) {
/* "View.MemoryView":1204
*
* if slice_is_contig(src, order, ndim):
* memcpy(result, src.data, size) # <<<<<<<<<<<<<<
* else:
* copy_strided_to_strided(src, tmpslice, ndim, itemsize)
*/
memcpy(__pyx_v_result, __pyx_v_src->data, __pyx_v_size);
goto __pyx_L9;
}
/*else*/ {
/* "View.MemoryView":1206
* memcpy(result, src.data, size)
* else:
* copy_strided_to_strided(src, tmpslice, ndim, itemsize) # <<<<<<<<<<<<<<
*
* return result
*/
copy_strided_to_strided(__pyx_v_src, __pyx_v_tmpslice, __pyx_v_ndim, __pyx_v_itemsize);
}
__pyx_L9:;
/* "View.MemoryView":1208
* copy_strided_to_strided(src, tmpslice, ndim, itemsize)
*
* return result # <<<<<<<<<<<<<<
*
*
*/
__pyx_r = __pyx_v_result;
goto __pyx_L0;
/* "View.MemoryView":1170
*
* @cname('__pyx_memoryview_copy_data_to_temp')
* cdef void *copy_data_to_temp(__Pyx_memviewslice *src, # <<<<<<<<<<<<<<
* __Pyx_memviewslice *tmpslice,
* char order,
*/
/* function exit code */
__pyx_L1_error:;
{
#ifdef WITH_THREAD
PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure();
#endif
__Pyx_AddTraceback("View.MemoryView.copy_data_to_temp", __pyx_clineno, __pyx_lineno, __pyx_filename);
#ifdef WITH_THREAD
PyGILState_Release(__pyx_gilstate_save);
#endif
}
__pyx_r = NULL;
__pyx_L0:;
return __pyx_r;
}
/* "View.MemoryView":1213
*
* @cname('__pyx_memoryview_err_extents')
* cdef int _err_extents(int i, Py_ssize_t extent1, # <<<<<<<<<<<<<<
* Py_ssize_t extent2) except -1 with gil:
* raise ValueError("got differing extents in dimension %d (got %d and %d)" %
*/
static int __pyx_memoryview_err_extents(int __pyx_v_i, Py_ssize_t __pyx_v_extent1, Py_ssize_t __pyx_v_extent2) {
int __pyx_r;
__Pyx_RefNannyDeclarations
PyObject *__pyx_t_1 = NULL;
PyObject *__pyx_t_2 = NULL;
PyObject *__pyx_t_3 = NULL;
PyObject *__pyx_t_4 = NULL;
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
#ifdef WITH_THREAD
PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure();
#endif
__Pyx_RefNannySetupContext("_err_extents", 0);
/* "View.MemoryView":1216
* Py_ssize_t extent2) except -1 with gil:
* raise ValueError("got differing extents in dimension %d (got %d and %d)" %
* (i, extent1, extent2)) # <<<<<<<<<<<<<<
*
* @cname('__pyx_memoryview_err_dim')
*/
__pyx_t_1 = __Pyx_PyInt_From_int(__pyx_v_i); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1216; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
__pyx_t_2 = PyInt_FromSsize_t(__pyx_v_extent1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1216; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_2);
__pyx_t_3 = PyInt_FromSsize_t(__pyx_v_extent2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1216; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_3);
__pyx_t_4 = PyTuple_New(3); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1216; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_4);
PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_1);
__Pyx_GIVEREF(__pyx_t_1);
PyTuple_SET_ITEM(__pyx_t_4, 1, __pyx_t_2);
__Pyx_GIVEREF(__pyx_t_2);
PyTuple_SET_ITEM(__pyx_t_4, 2, __pyx_t_3);
__Pyx_GIVEREF(__pyx_t_3);
__pyx_t_1 = 0;
__pyx_t_2 = 0;
__pyx_t_3 = 0;
/* "View.MemoryView":1215
* cdef int _err_extents(int i, Py_ssize_t extent1,
* Py_ssize_t extent2) except -1 with gil:
* raise ValueError("got differing extents in dimension %d (got %d and %d)" % # <<<<<<<<<<<<<<
* (i, extent1, extent2))
*
*/
__pyx_t_3 = __Pyx_PyString_Format(__pyx_kp_s_got_differing_extents_in_dimensi, __pyx_t_4); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1215; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_3);
__Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
__pyx_t_4 = PyTuple_New(1); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1215; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_4);
PyTuple_SET_ITEM(__pyx_t_4, 0, __pyx_t_3);
__Pyx_GIVEREF(__pyx_t_3);
__pyx_t_3 = 0;
__pyx_t_3 = __Pyx_PyObject_Call(__pyx_builtin_ValueError, __pyx_t_4, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1215; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_3);
__Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
__Pyx_Raise(__pyx_t_3, 0, 0, 0);
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
{__pyx_filename = __pyx_f[2]; __pyx_lineno = 1215; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
/* "View.MemoryView":1213
*
* @cname('__pyx_memoryview_err_extents')
* cdef int _err_extents(int i, Py_ssize_t extent1, # <<<<<<<<<<<<<<
* Py_ssize_t extent2) except -1 with gil:
* raise ValueError("got differing extents in dimension %d (got %d and %d)" %
*/
/* function exit code */
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_1);
__Pyx_XDECREF(__pyx_t_2);
__Pyx_XDECREF(__pyx_t_3);
__Pyx_XDECREF(__pyx_t_4);
__Pyx_AddTraceback("View.MemoryView._err_extents", __pyx_clineno, __pyx_lineno, __pyx_filename);
__pyx_r = -1;
__Pyx_RefNannyFinishContext();
#ifdef WITH_THREAD
PyGILState_Release(__pyx_gilstate_save);
#endif
return __pyx_r;
}
/* "View.MemoryView":1219
*
* @cname('__pyx_memoryview_err_dim')
* cdef int _err_dim(object error, char *msg, int dim) except -1 with gil: # <<<<<<<<<<<<<<
* raise error(msg.decode('ascii') % dim)
*
*/
static int __pyx_memoryview_err_dim(PyObject *__pyx_v_error, char *__pyx_v_msg, int __pyx_v_dim) {
int __pyx_r;
__Pyx_RefNannyDeclarations
PyObject *__pyx_t_1 = NULL;
PyObject *__pyx_t_2 = NULL;
PyObject *__pyx_t_3 = NULL;
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
#ifdef WITH_THREAD
PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure();
#endif
__Pyx_RefNannySetupContext("_err_dim", 0);
__Pyx_INCREF(__pyx_v_error);
/* "View.MemoryView":1220
* @cname('__pyx_memoryview_err_dim')
* cdef int _err_dim(object error, char *msg, int dim) except -1 with gil:
* raise error(msg.decode('ascii') % dim) # <<<<<<<<<<<<<<
*
* @cname('__pyx_memoryview_err')
*/
__pyx_t_1 = __Pyx_decode_c_string(__pyx_v_msg, 0, strlen(__pyx_v_msg), NULL, NULL, PyUnicode_DecodeASCII); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1220; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
__pyx_t_2 = __Pyx_PyInt_From_int(__pyx_v_dim); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1220; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_2);
__pyx_t_3 = PyUnicode_Format(__pyx_t_1, __pyx_t_2); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1220; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_3);
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
__Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0;
__pyx_t_2 = PyTuple_New(1); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1220; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_2);
PyTuple_SET_ITEM(__pyx_t_2, 0, __pyx_t_3);
__Pyx_GIVEREF(__pyx_t_3);
__pyx_t_3 = 0;
__pyx_t_3 = __Pyx_PyObject_Call(__pyx_v_error, __pyx_t_2, NULL); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1220; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_3);
__Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0;
__Pyx_Raise(__pyx_t_3, 0, 0, 0);
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
{__pyx_filename = __pyx_f[2]; __pyx_lineno = 1220; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
/* "View.MemoryView":1219
*
* @cname('__pyx_memoryview_err_dim')
* cdef int _err_dim(object error, char *msg, int dim) except -1 with gil: # <<<<<<<<<<<<<<
* raise error(msg.decode('ascii') % dim)
*
*/
/* function exit code */
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_1);
__Pyx_XDECREF(__pyx_t_2);
__Pyx_XDECREF(__pyx_t_3);
__Pyx_AddTraceback("View.MemoryView._err_dim", __pyx_clineno, __pyx_lineno, __pyx_filename);
__pyx_r = -1;
__Pyx_XDECREF(__pyx_v_error);
__Pyx_RefNannyFinishContext();
#ifdef WITH_THREAD
PyGILState_Release(__pyx_gilstate_save);
#endif
return __pyx_r;
}
/* "View.MemoryView":1223
*
* @cname('__pyx_memoryview_err')
* cdef int _err(object error, char *msg) except -1 with gil: # <<<<<<<<<<<<<<
* if msg != NULL:
* raise error(msg.decode('ascii'))
*/
static int __pyx_memoryview_err(PyObject *__pyx_v_error, char *__pyx_v_msg) {
int __pyx_r;
__Pyx_RefNannyDeclarations
int __pyx_t_1;
PyObject *__pyx_t_2 = NULL;
PyObject *__pyx_t_3 = NULL;
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
#ifdef WITH_THREAD
PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure();
#endif
__Pyx_RefNannySetupContext("_err", 0);
__Pyx_INCREF(__pyx_v_error);
/* "View.MemoryView":1224
* @cname('__pyx_memoryview_err')
* cdef int _err(object error, char *msg) except -1 with gil:
* if msg != NULL: # <<<<<<<<<<<<<<
* raise error(msg.decode('ascii'))
* else:
*/
__pyx_t_1 = ((__pyx_v_msg != NULL) != 0);
if (__pyx_t_1) {
/* "View.MemoryView":1225
* cdef int _err(object error, char *msg) except -1 with gil:
* if msg != NULL:
* raise error(msg.decode('ascii')) # <<<<<<<<<<<<<<
* else:
* raise error
*/
__pyx_t_2 = __Pyx_decode_c_string(__pyx_v_msg, 0, strlen(__pyx_v_msg), NULL, NULL, PyUnicode_DecodeASCII); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1225; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_2);
__pyx_t_3 = PyTuple_New(1); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1225; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_3);
PyTuple_SET_ITEM(__pyx_t_3, 0, __pyx_t_2);
__Pyx_GIVEREF(__pyx_t_2);
__pyx_t_2 = 0;
__pyx_t_2 = __Pyx_PyObject_Call(__pyx_v_error, __pyx_t_3, NULL); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1225; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_2);
__Pyx_DECREF(__pyx_t_3); __pyx_t_3 = 0;
__Pyx_Raise(__pyx_t_2, 0, 0, 0);
__Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0;
{__pyx_filename = __pyx_f[2]; __pyx_lineno = 1225; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
}
/*else*/ {
/* "View.MemoryView":1227
* raise error(msg.decode('ascii'))
* else:
* raise error # <<<<<<<<<<<<<<
*
* @cname('__pyx_memoryview_copy_contents')
*/
__Pyx_Raise(__pyx_v_error, 0, 0, 0);
{__pyx_filename = __pyx_f[2]; __pyx_lineno = 1227; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
}
/* "View.MemoryView":1223
*
* @cname('__pyx_memoryview_err')
* cdef int _err(object error, char *msg) except -1 with gil: # <<<<<<<<<<<<<<
* if msg != NULL:
* raise error(msg.decode('ascii'))
*/
/* function exit code */
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_2);
__Pyx_XDECREF(__pyx_t_3);
__Pyx_AddTraceback("View.MemoryView._err", __pyx_clineno, __pyx_lineno, __pyx_filename);
__pyx_r = -1;
__Pyx_XDECREF(__pyx_v_error);
__Pyx_RefNannyFinishContext();
#ifdef WITH_THREAD
PyGILState_Release(__pyx_gilstate_save);
#endif
return __pyx_r;
}
/* "View.MemoryView":1230
*
* @cname('__pyx_memoryview_copy_contents')
* cdef int memoryview_copy_contents(__Pyx_memviewslice src, # <<<<<<<<<<<<<<
* __Pyx_memviewslice dst,
* int src_ndim, int dst_ndim,
*/
static int __pyx_memoryview_copy_contents(__Pyx_memviewslice __pyx_v_src, __Pyx_memviewslice __pyx_v_dst, int __pyx_v_src_ndim, int __pyx_v_dst_ndim, int __pyx_v_dtype_is_object) {
void *__pyx_v_tmpdata;
size_t __pyx_v_itemsize;
int __pyx_v_i;
char __pyx_v_order;
int __pyx_v_broadcasting;
int __pyx_v_direct_copy;
__Pyx_memviewslice __pyx_v_tmp;
int __pyx_v_ndim;
int __pyx_r;
Py_ssize_t __pyx_t_1;
int __pyx_t_2;
int __pyx_t_3;
int __pyx_t_4;
int __pyx_t_5;
void *__pyx_t_6;
int __pyx_t_7;
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
/* "View.MemoryView":1238
* Check for overlapping memory and verify the shapes.
* """
* cdef void *tmpdata = NULL # <<<<<<<<<<<<<<
* cdef size_t itemsize = src.memview.view.itemsize
* cdef int i
*/
__pyx_v_tmpdata = NULL;
/* "View.MemoryView":1239
* """
* cdef void *tmpdata = NULL
* cdef size_t itemsize = src.memview.view.itemsize # <<<<<<<<<<<<<<
* cdef int i
* cdef char order = get_best_order(&src, src_ndim)
*/
__pyx_t_1 = __pyx_v_src.memview->view.itemsize;
__pyx_v_itemsize = __pyx_t_1;
/* "View.MemoryView":1241
* cdef size_t itemsize = src.memview.view.itemsize
* cdef int i
* cdef char order = get_best_order(&src, src_ndim) # <<<<<<<<<<<<<<
* cdef bint broadcasting = False
* cdef bint direct_copy = False
*/
__pyx_v_order = __pyx_get_best_slice_order((&__pyx_v_src), __pyx_v_src_ndim);
/* "View.MemoryView":1242
* cdef int i
* cdef char order = get_best_order(&src, src_ndim)
* cdef bint broadcasting = False # <<<<<<<<<<<<<<
* cdef bint direct_copy = False
* cdef __Pyx_memviewslice tmp
*/
__pyx_v_broadcasting = 0;
/* "View.MemoryView":1243
* cdef char order = get_best_order(&src, src_ndim)
* cdef bint broadcasting = False
* cdef bint direct_copy = False # <<<<<<<<<<<<<<
* cdef __Pyx_memviewslice tmp
*
*/
__pyx_v_direct_copy = 0;
/* "View.MemoryView":1246
* cdef __Pyx_memviewslice tmp
*
* if src_ndim < dst_ndim: # <<<<<<<<<<<<<<
* broadcast_leading(&src, src_ndim, dst_ndim)
* elif dst_ndim < src_ndim:
*/
__pyx_t_2 = ((__pyx_v_src_ndim < __pyx_v_dst_ndim) != 0);
if (__pyx_t_2) {
/* "View.MemoryView":1247
*
* if src_ndim < dst_ndim:
* broadcast_leading(&src, src_ndim, dst_ndim) # <<<<<<<<<<<<<<
* elif dst_ndim < src_ndim:
* broadcast_leading(&dst, dst_ndim, src_ndim)
*/
__pyx_memoryview_broadcast_leading((&__pyx_v_src), __pyx_v_src_ndim, __pyx_v_dst_ndim);
goto __pyx_L3;
}
/* "View.MemoryView":1248
* if src_ndim < dst_ndim:
* broadcast_leading(&src, src_ndim, dst_ndim)
* elif dst_ndim < src_ndim: # <<<<<<<<<<<<<<
* broadcast_leading(&dst, dst_ndim, src_ndim)
*
*/
__pyx_t_2 = ((__pyx_v_dst_ndim < __pyx_v_src_ndim) != 0);
if (__pyx_t_2) {
/* "View.MemoryView":1249
* broadcast_leading(&src, src_ndim, dst_ndim)
* elif dst_ndim < src_ndim:
* broadcast_leading(&dst, dst_ndim, src_ndim) # <<<<<<<<<<<<<<
*
* cdef int ndim = max(src_ndim, dst_ndim)
*/
__pyx_memoryview_broadcast_leading((&__pyx_v_dst), __pyx_v_dst_ndim, __pyx_v_src_ndim);
goto __pyx_L3;
}
__pyx_L3:;
/* "View.MemoryView":1251
* broadcast_leading(&dst, dst_ndim, src_ndim)
*
* cdef int ndim = max(src_ndim, dst_ndim) # <<<<<<<<<<<<<<
*
* for i in range(ndim):
*/
__pyx_t_3 = __pyx_v_dst_ndim;
__pyx_t_4 = __pyx_v_src_ndim;
if (((__pyx_t_3 > __pyx_t_4) != 0)) {
__pyx_t_5 = __pyx_t_3;
} else {
__pyx_t_5 = __pyx_t_4;
}
__pyx_v_ndim = __pyx_t_5;
/* "View.MemoryView":1253
* cdef int ndim = max(src_ndim, dst_ndim)
*
* for i in range(ndim): # <<<<<<<<<<<<<<
* if src.shape[i] != dst.shape[i]:
* if src.shape[i] == 1:
*/
__pyx_t_5 = __pyx_v_ndim;
for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_5; __pyx_t_3+=1) {
__pyx_v_i = __pyx_t_3;
/* "View.MemoryView":1254
*
* for i in range(ndim):
* if src.shape[i] != dst.shape[i]: # <<<<<<<<<<<<<<
* if src.shape[i] == 1:
* broadcasting = True
*/
__pyx_t_2 = (((__pyx_v_src.shape[__pyx_v_i]) != (__pyx_v_dst.shape[__pyx_v_i])) != 0);
if (__pyx_t_2) {
/* "View.MemoryView":1255
* for i in range(ndim):
* if src.shape[i] != dst.shape[i]:
* if src.shape[i] == 1: # <<<<<<<<<<<<<<
* broadcasting = True
* src.strides[i] = 0
*/
__pyx_t_2 = (((__pyx_v_src.shape[__pyx_v_i]) == 1) != 0);
if (__pyx_t_2) {
/* "View.MemoryView":1256
* if src.shape[i] != dst.shape[i]:
* if src.shape[i] == 1:
* broadcasting = True # <<<<<<<<<<<<<<
* src.strides[i] = 0
* else:
*/
__pyx_v_broadcasting = 1;
/* "View.MemoryView":1257
* if src.shape[i] == 1:
* broadcasting = True
* src.strides[i] = 0 # <<<<<<<<<<<<<<
* else:
* _err_extents(i, dst.shape[i], src.shape[i])
*/
(__pyx_v_src.strides[__pyx_v_i]) = 0;
goto __pyx_L7;
}
/*else*/ {
/* "View.MemoryView":1259
* src.strides[i] = 0
* else:
* _err_extents(i, dst.shape[i], src.shape[i]) # <<<<<<<<<<<<<<
*
* if src.suboffsets[i] >= 0:
*/
__pyx_t_4 = __pyx_memoryview_err_extents(__pyx_v_i, (__pyx_v_dst.shape[__pyx_v_i]), (__pyx_v_src.shape[__pyx_v_i])); if (unlikely(__pyx_t_4 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1259; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
}
__pyx_L7:;
goto __pyx_L6;
}
__pyx_L6:;
/* "View.MemoryView":1261
* _err_extents(i, dst.shape[i], src.shape[i])
*
* if src.suboffsets[i] >= 0: # <<<<<<<<<<<<<<
* _err_dim(ValueError, "Dimension %d is not direct", i)
*
*/
__pyx_t_2 = (((__pyx_v_src.suboffsets[__pyx_v_i]) >= 0) != 0);
if (__pyx_t_2) {
/* "View.MemoryView":1262
*
* if src.suboffsets[i] >= 0:
* _err_dim(ValueError, "Dimension %d is not direct", i) # <<<<<<<<<<<<<<
*
* if slices_overlap(&src, &dst, ndim, itemsize):
*/
__pyx_t_4 = __pyx_memoryview_err_dim(__pyx_builtin_ValueError, __pyx_k_Dimension_d_is_not_direct, __pyx_v_i); if (unlikely(__pyx_t_4 == -1)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1262; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
goto __pyx_L8;
}
__pyx_L8:;
}
/* "View.MemoryView":1264
* _err_dim(ValueError, "Dimension %d is not direct", i)
*
* if slices_overlap(&src, &dst, ndim, itemsize): # <<<<<<<<<<<<<<
*
* if not slice_is_contig(&src, order, ndim):
*/
__pyx_t_2 = (__pyx_slices_overlap((&__pyx_v_src), (&__pyx_v_dst), __pyx_v_ndim, __pyx_v_itemsize) != 0);
if (__pyx_t_2) {
/* "View.MemoryView":1266
* if slices_overlap(&src, &dst, ndim, itemsize):
*
* if not slice_is_contig(&src, order, ndim): # <<<<<<<<<<<<<<
* order = get_best_order(&dst, ndim)
*
*/
__pyx_t_2 = ((!(__pyx_memviewslice_is_contig((&__pyx_v_src), __pyx_v_order, __pyx_v_ndim) != 0)) != 0);
if (__pyx_t_2) {
/* "View.MemoryView":1267
*
* if not slice_is_contig(&src, order, ndim):
* order = get_best_order(&dst, ndim) # <<<<<<<<<<<<<<
*
* tmpdata = copy_data_to_temp(&src, &tmp, order, ndim)
*/
__pyx_v_order = __pyx_get_best_slice_order((&__pyx_v_dst), __pyx_v_ndim);
goto __pyx_L10;
}
__pyx_L10:;
/* "View.MemoryView":1269
* order = get_best_order(&dst, ndim)
*
* tmpdata = copy_data_to_temp(&src, &tmp, order, ndim) # <<<<<<<<<<<<<<
* src = tmp
*
*/
__pyx_t_6 = __pyx_memoryview_copy_data_to_temp((&__pyx_v_src), (&__pyx_v_tmp), __pyx_v_order, __pyx_v_ndim); if (unlikely(__pyx_t_6 == NULL)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1269; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_v_tmpdata = __pyx_t_6;
/* "View.MemoryView":1270
*
* tmpdata = copy_data_to_temp(&src, &tmp, order, ndim)
* src = tmp # <<<<<<<<<<<<<<
*
* if not broadcasting:
*/
__pyx_v_src = __pyx_v_tmp;
goto __pyx_L9;
}
__pyx_L9:;
/* "View.MemoryView":1272
* src = tmp
*
* if not broadcasting: # <<<<<<<<<<<<<<
*
*
*/
__pyx_t_2 = ((!(__pyx_v_broadcasting != 0)) != 0);
if (__pyx_t_2) {
/* "View.MemoryView":1275
*
*
* if slice_is_contig(&src, 'C', ndim): # <<<<<<<<<<<<<<
* direct_copy = slice_is_contig(&dst, 'C', ndim)
* elif slice_is_contig(&src, 'F', ndim):
*/
__pyx_t_2 = (__pyx_memviewslice_is_contig((&__pyx_v_src), 'C', __pyx_v_ndim) != 0);
if (__pyx_t_2) {
/* "View.MemoryView":1276
*
* if slice_is_contig(&src, 'C', ndim):
* direct_copy = slice_is_contig(&dst, 'C', ndim) # <<<<<<<<<<<<<<
* elif slice_is_contig(&src, 'F', ndim):
* direct_copy = slice_is_contig(&dst, 'F', ndim)
*/
__pyx_v_direct_copy = __pyx_memviewslice_is_contig((&__pyx_v_dst), 'C', __pyx_v_ndim);
goto __pyx_L12;
}
/* "View.MemoryView":1277
* if slice_is_contig(&src, 'C', ndim):
* direct_copy = slice_is_contig(&dst, 'C', ndim)
* elif slice_is_contig(&src, 'F', ndim): # <<<<<<<<<<<<<<
* direct_copy = slice_is_contig(&dst, 'F', ndim)
*
*/
__pyx_t_2 = (__pyx_memviewslice_is_contig((&__pyx_v_src), 'F', __pyx_v_ndim) != 0);
if (__pyx_t_2) {
/* "View.MemoryView":1278
* direct_copy = slice_is_contig(&dst, 'C', ndim)
* elif slice_is_contig(&src, 'F', ndim):
* direct_copy = slice_is_contig(&dst, 'F', ndim) # <<<<<<<<<<<<<<
*
* if direct_copy:
*/
__pyx_v_direct_copy = __pyx_memviewslice_is_contig((&__pyx_v_dst), 'F', __pyx_v_ndim);
goto __pyx_L12;
}
__pyx_L12:;
/* "View.MemoryView":1280
* direct_copy = slice_is_contig(&dst, 'F', ndim)
*
* if direct_copy: # <<<<<<<<<<<<<<
*
* refcount_copying(&dst, dtype_is_object, ndim, False)
*/
__pyx_t_2 = (__pyx_v_direct_copy != 0);
if (__pyx_t_2) {
/* "View.MemoryView":1282
* if direct_copy:
*
* refcount_copying(&dst, dtype_is_object, ndim, False) # <<<<<<<<<<<<<<
* memcpy(dst.data, src.data, slice_get_size(&src, ndim))
* refcount_copying(&dst, dtype_is_object, ndim, True)
*/
__pyx_memoryview_refcount_copying((&__pyx_v_dst), __pyx_v_dtype_is_object, __pyx_v_ndim, 0);
/* "View.MemoryView":1283
*
* refcount_copying(&dst, dtype_is_object, ndim, False)
* memcpy(dst.data, src.data, slice_get_size(&src, ndim)) # <<<<<<<<<<<<<<
* refcount_copying(&dst, dtype_is_object, ndim, True)
* return 0
*/
memcpy(__pyx_v_dst.data, __pyx_v_src.data, __pyx_memoryview_slice_get_size((&__pyx_v_src), __pyx_v_ndim));
/* "View.MemoryView":1284
* refcount_copying(&dst, dtype_is_object, ndim, False)
* memcpy(dst.data, src.data, slice_get_size(&src, ndim))
* refcount_copying(&dst, dtype_is_object, ndim, True) # <<<<<<<<<<<<<<
* return 0
*
*/
__pyx_memoryview_refcount_copying((&__pyx_v_dst), __pyx_v_dtype_is_object, __pyx_v_ndim, 1);
/* "View.MemoryView":1285
* memcpy(dst.data, src.data, slice_get_size(&src, ndim))
* refcount_copying(&dst, dtype_is_object, ndim, True)
* return 0 # <<<<<<<<<<<<<<
*
* if order == 'F' == get_best_order(&dst, ndim):
*/
__pyx_r = 0;
goto __pyx_L0;
}
goto __pyx_L11;
}
__pyx_L11:;
/* "View.MemoryView":1287
* return 0
*
* if order == 'F' == get_best_order(&dst, ndim): # <<<<<<<<<<<<<<
*
*
*/
__pyx_t_2 = (__pyx_v_order == 'F');
if (__pyx_t_2) {
__pyx_t_2 = ('F' == __pyx_get_best_slice_order((&__pyx_v_dst), __pyx_v_ndim));
}
__pyx_t_7 = (__pyx_t_2 != 0);
if (__pyx_t_7) {
/* "View.MemoryView":1290
*
*
* transpose_memslice(&src) # <<<<<<<<<<<<<<
* transpose_memslice(&dst)
*
*/
__pyx_t_5 = __pyx_memslice_transpose((&__pyx_v_src)); if (unlikely(__pyx_t_5 == 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1290; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
/* "View.MemoryView":1291
*
* transpose_memslice(&src)
* transpose_memslice(&dst) # <<<<<<<<<<<<<<
*
* refcount_copying(&dst, dtype_is_object, ndim, False)
*/
__pyx_t_5 = __pyx_memslice_transpose((&__pyx_v_dst)); if (unlikely(__pyx_t_5 == 0)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 1291; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
goto __pyx_L14;
}
__pyx_L14:;
/* "View.MemoryView":1293
* transpose_memslice(&dst)
*
* refcount_copying(&dst, dtype_is_object, ndim, False) # <<<<<<<<<<<<<<
* copy_strided_to_strided(&src, &dst, ndim, itemsize)
* refcount_copying(&dst, dtype_is_object, ndim, True)
*/
__pyx_memoryview_refcount_copying((&__pyx_v_dst), __pyx_v_dtype_is_object, __pyx_v_ndim, 0);
/* "View.MemoryView":1294
*
* refcount_copying(&dst, dtype_is_object, ndim, False)
* copy_strided_to_strided(&src, &dst, ndim, itemsize) # <<<<<<<<<<<<<<
* refcount_copying(&dst, dtype_is_object, ndim, True)
*
*/
copy_strided_to_strided((&__pyx_v_src), (&__pyx_v_dst), __pyx_v_ndim, __pyx_v_itemsize);
/* "View.MemoryView":1295
* refcount_copying(&dst, dtype_is_object, ndim, False)
* copy_strided_to_strided(&src, &dst, ndim, itemsize)
* refcount_copying(&dst, dtype_is_object, ndim, True) # <<<<<<<<<<<<<<
*
* free(tmpdata)
*/
__pyx_memoryview_refcount_copying((&__pyx_v_dst), __pyx_v_dtype_is_object, __pyx_v_ndim, 1);
/* "View.MemoryView":1297
* refcount_copying(&dst, dtype_is_object, ndim, True)
*
* free(tmpdata) # <<<<<<<<<<<<<<
* return 0
*
*/
free(__pyx_v_tmpdata);
/* "View.MemoryView":1298
*
* free(tmpdata)
* return 0 # <<<<<<<<<<<<<<
*
* @cname('__pyx_memoryview_broadcast_leading')
*/
__pyx_r = 0;
goto __pyx_L0;
/* "View.MemoryView":1230
*
* @cname('__pyx_memoryview_copy_contents')
* cdef int memoryview_copy_contents(__Pyx_memviewslice src, # <<<<<<<<<<<<<<
* __Pyx_memviewslice dst,
* int src_ndim, int dst_ndim,
*/
/* function exit code */
__pyx_L1_error:;
{
#ifdef WITH_THREAD
PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure();
#endif
__Pyx_AddTraceback("View.MemoryView.memoryview_copy_contents", __pyx_clineno, __pyx_lineno, __pyx_filename);
#ifdef WITH_THREAD
PyGILState_Release(__pyx_gilstate_save);
#endif
}
__pyx_r = -1;
__pyx_L0:;
return __pyx_r;
}
/* "View.MemoryView":1301
*
* @cname('__pyx_memoryview_broadcast_leading')
* cdef void broadcast_leading(__Pyx_memviewslice *slice, # <<<<<<<<<<<<<<
* int ndim,
* int ndim_other) nogil:
*/
static void __pyx_memoryview_broadcast_leading(__Pyx_memviewslice *__pyx_v_slice, int __pyx_v_ndim, int __pyx_v_ndim_other) {
int __pyx_v_i;
int __pyx_v_offset;
int __pyx_t_1;
int __pyx_t_2;
/* "View.MemoryView":1305
* int ndim_other) nogil:
* cdef int i
* cdef int offset = ndim_other - ndim # <<<<<<<<<<<<<<
*
* for i in range(ndim - 1, -1, -1):
*/
__pyx_v_offset = (__pyx_v_ndim_other - __pyx_v_ndim);
/* "View.MemoryView":1307
* cdef int offset = ndim_other - ndim
*
* for i in range(ndim - 1, -1, -1): # <<<<<<<<<<<<<<
* slice.shape[i + offset] = slice.shape[i]
* slice.strides[i + offset] = slice.strides[i]
*/
for (__pyx_t_1 = (__pyx_v_ndim - 1); __pyx_t_1 > -1; __pyx_t_1-=1) {
__pyx_v_i = __pyx_t_1;
/* "View.MemoryView":1308
*
* for i in range(ndim - 1, -1, -1):
* slice.shape[i + offset] = slice.shape[i] # <<<<<<<<<<<<<<
* slice.strides[i + offset] = slice.strides[i]
* slice.suboffsets[i + offset] = slice.suboffsets[i]
*/
(__pyx_v_slice->shape[(__pyx_v_i + __pyx_v_offset)]) = (__pyx_v_slice->shape[__pyx_v_i]);
/* "View.MemoryView":1309
* for i in range(ndim - 1, -1, -1):
* slice.shape[i + offset] = slice.shape[i]
* slice.strides[i + offset] = slice.strides[i] # <<<<<<<<<<<<<<
* slice.suboffsets[i + offset] = slice.suboffsets[i]
*
*/
(__pyx_v_slice->strides[(__pyx_v_i + __pyx_v_offset)]) = (__pyx_v_slice->strides[__pyx_v_i]);
/* "View.MemoryView":1310
* slice.shape[i + offset] = slice.shape[i]
* slice.strides[i + offset] = slice.strides[i]
* slice.suboffsets[i + offset] = slice.suboffsets[i] # <<<<<<<<<<<<<<
*
* for i in range(offset):
*/
(__pyx_v_slice->suboffsets[(__pyx_v_i + __pyx_v_offset)]) = (__pyx_v_slice->suboffsets[__pyx_v_i]);
}
/* "View.MemoryView":1312
* slice.suboffsets[i + offset] = slice.suboffsets[i]
*
* for i in range(offset): # <<<<<<<<<<<<<<
* slice.shape[i] = 1
* slice.strides[i] = slice.strides[0]
*/
__pyx_t_1 = __pyx_v_offset;
for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) {
__pyx_v_i = __pyx_t_2;
/* "View.MemoryView":1313
*
* for i in range(offset):
* slice.shape[i] = 1 # <<<<<<<<<<<<<<
* slice.strides[i] = slice.strides[0]
* slice.suboffsets[i] = -1
*/
(__pyx_v_slice->shape[__pyx_v_i]) = 1;
/* "View.MemoryView":1314
* for i in range(offset):
* slice.shape[i] = 1
* slice.strides[i] = slice.strides[0] # <<<<<<<<<<<<<<
* slice.suboffsets[i] = -1
*
*/
(__pyx_v_slice->strides[__pyx_v_i]) = (__pyx_v_slice->strides[0]);
/* "View.MemoryView":1315
* slice.shape[i] = 1
* slice.strides[i] = slice.strides[0]
* slice.suboffsets[i] = -1 # <<<<<<<<<<<<<<
*
*
*/
(__pyx_v_slice->suboffsets[__pyx_v_i]) = -1;
}
/* "View.MemoryView":1301
*
* @cname('__pyx_memoryview_broadcast_leading')
* cdef void broadcast_leading(__Pyx_memviewslice *slice, # <<<<<<<<<<<<<<
* int ndim,
* int ndim_other) nogil:
*/
/* function exit code */
}
/* "View.MemoryView":1323
*
* @cname('__pyx_memoryview_refcount_copying')
* cdef void refcount_copying(__Pyx_memviewslice *dst, bint dtype_is_object, # <<<<<<<<<<<<<<
* int ndim, bint inc) nogil:
*
*/
static void __pyx_memoryview_refcount_copying(__Pyx_memviewslice *__pyx_v_dst, int __pyx_v_dtype_is_object, int __pyx_v_ndim, int __pyx_v_inc) {
int __pyx_t_1;
/* "View.MemoryView":1327
*
*
* if dtype_is_object: # <<<<<<<<<<<<<<
* refcount_objects_in_slice_with_gil(dst.data, dst.shape,
* dst.strides, ndim, inc)
*/
__pyx_t_1 = (__pyx_v_dtype_is_object != 0);
if (__pyx_t_1) {
/* "View.MemoryView":1328
*
* if dtype_is_object:
* refcount_objects_in_slice_with_gil(dst.data, dst.shape, # <<<<<<<<<<<<<<
* dst.strides, ndim, inc)
*
*/
__pyx_memoryview_refcount_objects_in_slice_with_gil(__pyx_v_dst->data, __pyx_v_dst->shape, __pyx_v_dst->strides, __pyx_v_ndim, __pyx_v_inc);
goto __pyx_L3;
}
__pyx_L3:;
/* "View.MemoryView":1323
*
* @cname('__pyx_memoryview_refcount_copying')
* cdef void refcount_copying(__Pyx_memviewslice *dst, bint dtype_is_object, # <<<<<<<<<<<<<<
* int ndim, bint inc) nogil:
*
*/
/* function exit code */
}
/* "View.MemoryView":1332
*
* @cname('__pyx_memoryview_refcount_objects_in_slice_with_gil')
* cdef void refcount_objects_in_slice_with_gil(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<<
* Py_ssize_t *strides, int ndim,
* bint inc) with gil:
*/
static void __pyx_memoryview_refcount_objects_in_slice_with_gil(char *__pyx_v_data, Py_ssize_t *__pyx_v_shape, Py_ssize_t *__pyx_v_strides, int __pyx_v_ndim, int __pyx_v_inc) {
__Pyx_RefNannyDeclarations
#ifdef WITH_THREAD
PyGILState_STATE __pyx_gilstate_save = PyGILState_Ensure();
#endif
__Pyx_RefNannySetupContext("refcount_objects_in_slice_with_gil", 0);
/* "View.MemoryView":1335
* Py_ssize_t *strides, int ndim,
* bint inc) with gil:
* refcount_objects_in_slice(data, shape, strides, ndim, inc) # <<<<<<<<<<<<<<
*
* @cname('__pyx_memoryview_refcount_objects_in_slice')
*/
__pyx_memoryview_refcount_objects_in_slice(__pyx_v_data, __pyx_v_shape, __pyx_v_strides, __pyx_v_ndim, __pyx_v_inc);
/* "View.MemoryView":1332
*
* @cname('__pyx_memoryview_refcount_objects_in_slice_with_gil')
* cdef void refcount_objects_in_slice_with_gil(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<<
* Py_ssize_t *strides, int ndim,
* bint inc) with gil:
*/
/* function exit code */
__Pyx_RefNannyFinishContext();
#ifdef WITH_THREAD
PyGILState_Release(__pyx_gilstate_save);
#endif
}
/* "View.MemoryView":1338
*
* @cname('__pyx_memoryview_refcount_objects_in_slice')
* cdef void refcount_objects_in_slice(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<<
* Py_ssize_t *strides, int ndim, bint inc):
* cdef Py_ssize_t i
*/
static void __pyx_memoryview_refcount_objects_in_slice(char *__pyx_v_data, Py_ssize_t *__pyx_v_shape, Py_ssize_t *__pyx_v_strides, int __pyx_v_ndim, int __pyx_v_inc) {
CYTHON_UNUSED Py_ssize_t __pyx_v_i;
__Pyx_RefNannyDeclarations
Py_ssize_t __pyx_t_1;
Py_ssize_t __pyx_t_2;
int __pyx_t_3;
__Pyx_RefNannySetupContext("refcount_objects_in_slice", 0);
/* "View.MemoryView":1342
* cdef Py_ssize_t i
*
* for i in range(shape[0]): # <<<<<<<<<<<<<<
* if ndim == 1:
* if inc:
*/
__pyx_t_1 = (__pyx_v_shape[0]);
for (__pyx_t_2 = 0; __pyx_t_2 < __pyx_t_1; __pyx_t_2+=1) {
__pyx_v_i = __pyx_t_2;
/* "View.MemoryView":1343
*
* for i in range(shape[0]):
* if ndim == 1: # <<<<<<<<<<<<<<
* if inc:
* Py_INCREF((<PyObject **> data)[0])
*/
__pyx_t_3 = ((__pyx_v_ndim == 1) != 0);
if (__pyx_t_3) {
/* "View.MemoryView":1344
* for i in range(shape[0]):
* if ndim == 1:
* if inc: # <<<<<<<<<<<<<<
* Py_INCREF((<PyObject **> data)[0])
* else:
*/
__pyx_t_3 = (__pyx_v_inc != 0);
if (__pyx_t_3) {
/* "View.MemoryView":1345
* if ndim == 1:
* if inc:
* Py_INCREF((<PyObject **> data)[0]) # <<<<<<<<<<<<<<
* else:
* Py_DECREF((<PyObject **> data)[0])
*/
Py_INCREF((((PyObject **)__pyx_v_data)[0]));
goto __pyx_L6;
}
/*else*/ {
/* "View.MemoryView":1347
* Py_INCREF((<PyObject **> data)[0])
* else:
* Py_DECREF((<PyObject **> data)[0]) # <<<<<<<<<<<<<<
* else:
* refcount_objects_in_slice(data, shape + 1, strides + 1,
*/
Py_DECREF((((PyObject **)__pyx_v_data)[0]));
}
__pyx_L6:;
goto __pyx_L5;
}
/*else*/ {
/* "View.MemoryView":1349
* Py_DECREF((<PyObject **> data)[0])
* else:
* refcount_objects_in_slice(data, shape + 1, strides + 1, # <<<<<<<<<<<<<<
* ndim - 1, inc)
*
*/
__pyx_memoryview_refcount_objects_in_slice(__pyx_v_data, (__pyx_v_shape + 1), (__pyx_v_strides + 1), (__pyx_v_ndim - 1), __pyx_v_inc);
}
__pyx_L5:;
/* "View.MemoryView":1352
* ndim - 1, inc)
*
* data += strides[0] # <<<<<<<<<<<<<<
*
*
*/
__pyx_v_data = (__pyx_v_data + (__pyx_v_strides[0]));
}
/* "View.MemoryView":1338
*
* @cname('__pyx_memoryview_refcount_objects_in_slice')
* cdef void refcount_objects_in_slice(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<<
* Py_ssize_t *strides, int ndim, bint inc):
* cdef Py_ssize_t i
*/
/* function exit code */
__Pyx_RefNannyFinishContext();
}
/* "View.MemoryView":1358
*
* @cname('__pyx_memoryview_slice_assign_scalar')
* cdef void slice_assign_scalar(__Pyx_memviewslice *dst, int ndim, # <<<<<<<<<<<<<<
* size_t itemsize, void *item,
* bint dtype_is_object) nogil:
*/
static void __pyx_memoryview_slice_assign_scalar(__Pyx_memviewslice *__pyx_v_dst, int __pyx_v_ndim, size_t __pyx_v_itemsize, void *__pyx_v_item, int __pyx_v_dtype_is_object) {
/* "View.MemoryView":1361
* size_t itemsize, void *item,
* bint dtype_is_object) nogil:
* refcount_copying(dst, dtype_is_object, ndim, False) # <<<<<<<<<<<<<<
* _slice_assign_scalar(dst.data, dst.shape, dst.strides, ndim,
* itemsize, item)
*/
__pyx_memoryview_refcount_copying(__pyx_v_dst, __pyx_v_dtype_is_object, __pyx_v_ndim, 0);
/* "View.MemoryView":1362
* bint dtype_is_object) nogil:
* refcount_copying(dst, dtype_is_object, ndim, False)
* _slice_assign_scalar(dst.data, dst.shape, dst.strides, ndim, # <<<<<<<<<<<<<<
* itemsize, item)
* refcount_copying(dst, dtype_is_object, ndim, True)
*/
__pyx_memoryview__slice_assign_scalar(__pyx_v_dst->data, __pyx_v_dst->shape, __pyx_v_dst->strides, __pyx_v_ndim, __pyx_v_itemsize, __pyx_v_item);
/* "View.MemoryView":1364
* _slice_assign_scalar(dst.data, dst.shape, dst.strides, ndim,
* itemsize, item)
* refcount_copying(dst, dtype_is_object, ndim, True) # <<<<<<<<<<<<<<
*
*
*/
__pyx_memoryview_refcount_copying(__pyx_v_dst, __pyx_v_dtype_is_object, __pyx_v_ndim, 1);
/* "View.MemoryView":1358
*
* @cname('__pyx_memoryview_slice_assign_scalar')
* cdef void slice_assign_scalar(__Pyx_memviewslice *dst, int ndim, # <<<<<<<<<<<<<<
* size_t itemsize, void *item,
* bint dtype_is_object) nogil:
*/
/* function exit code */
}
/* "View.MemoryView":1368
*
* @cname('__pyx_memoryview__slice_assign_scalar')
* cdef void _slice_assign_scalar(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<<
* Py_ssize_t *strides, int ndim,
* size_t itemsize, void *item) nogil:
*/
static void __pyx_memoryview__slice_assign_scalar(char *__pyx_v_data, Py_ssize_t *__pyx_v_shape, Py_ssize_t *__pyx_v_strides, int __pyx_v_ndim, size_t __pyx_v_itemsize, void *__pyx_v_item) {
CYTHON_UNUSED Py_ssize_t __pyx_v_i;
Py_ssize_t __pyx_v_stride;
Py_ssize_t __pyx_v_extent;
int __pyx_t_1;
Py_ssize_t __pyx_t_2;
Py_ssize_t __pyx_t_3;
/* "View.MemoryView":1372
* size_t itemsize, void *item) nogil:
* cdef Py_ssize_t i
* cdef Py_ssize_t stride = strides[0] # <<<<<<<<<<<<<<
* cdef Py_ssize_t extent = shape[0]
*
*/
__pyx_v_stride = (__pyx_v_strides[0]);
/* "View.MemoryView":1373
* cdef Py_ssize_t i
* cdef Py_ssize_t stride = strides[0]
* cdef Py_ssize_t extent = shape[0] # <<<<<<<<<<<<<<
*
* if ndim == 1:
*/
__pyx_v_extent = (__pyx_v_shape[0]);
/* "View.MemoryView":1375
* cdef Py_ssize_t extent = shape[0]
*
* if ndim == 1: # <<<<<<<<<<<<<<
* for i in range(extent):
* memcpy(data, item, itemsize)
*/
__pyx_t_1 = ((__pyx_v_ndim == 1) != 0);
if (__pyx_t_1) {
/* "View.MemoryView":1376
*
* if ndim == 1:
* for i in range(extent): # <<<<<<<<<<<<<<
* memcpy(data, item, itemsize)
* data += stride
*/
__pyx_t_2 = __pyx_v_extent;
for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) {
__pyx_v_i = __pyx_t_3;
/* "View.MemoryView":1377
* if ndim == 1:
* for i in range(extent):
* memcpy(data, item, itemsize) # <<<<<<<<<<<<<<
* data += stride
* else:
*/
memcpy(__pyx_v_data, __pyx_v_item, __pyx_v_itemsize);
/* "View.MemoryView":1378
* for i in range(extent):
* memcpy(data, item, itemsize)
* data += stride # <<<<<<<<<<<<<<
* else:
* for i in range(extent):
*/
__pyx_v_data = (__pyx_v_data + __pyx_v_stride);
}
goto __pyx_L3;
}
/*else*/ {
/* "View.MemoryView":1380
* data += stride
* else:
* for i in range(extent): # <<<<<<<<<<<<<<
* _slice_assign_scalar(data, shape + 1, strides + 1,
* ndim - 1, itemsize, item)
*/
__pyx_t_2 = __pyx_v_extent;
for (__pyx_t_3 = 0; __pyx_t_3 < __pyx_t_2; __pyx_t_3+=1) {
__pyx_v_i = __pyx_t_3;
/* "View.MemoryView":1381
* else:
* for i in range(extent):
* _slice_assign_scalar(data, shape + 1, strides + 1, # <<<<<<<<<<<<<<
* ndim - 1, itemsize, item)
* data += stride
*/
__pyx_memoryview__slice_assign_scalar(__pyx_v_data, (__pyx_v_shape + 1), (__pyx_v_strides + 1), (__pyx_v_ndim - 1), __pyx_v_itemsize, __pyx_v_item);
/* "View.MemoryView":1383
* _slice_assign_scalar(data, shape + 1, strides + 1,
* ndim - 1, itemsize, item)
* data += stride # <<<<<<<<<<<<<<
*
*
*/
__pyx_v_data = (__pyx_v_data + __pyx_v_stride);
}
}
__pyx_L3:;
/* "View.MemoryView":1368
*
* @cname('__pyx_memoryview__slice_assign_scalar')
* cdef void _slice_assign_scalar(char *data, Py_ssize_t *shape, # <<<<<<<<<<<<<<
* Py_ssize_t *strides, int ndim,
* size_t itemsize, void *item) nogil:
*/
/* function exit code */
}
static PyObject *__pyx_tp_new_array(PyTypeObject *t, PyObject *a, PyObject *k) {
struct __pyx_array_obj *p;
PyObject *o;
if (likely((t->tp_flags & Py_TPFLAGS_IS_ABSTRACT) == 0)) {
o = (*t->tp_alloc)(t, 0);
} else {
o = (PyObject *) PyBaseObject_Type.tp_new(t, __pyx_empty_tuple, 0);
}
if (unlikely(!o)) return 0;
p = ((struct __pyx_array_obj *)o);
p->mode = ((PyObject*)Py_None); Py_INCREF(Py_None);
p->_format = ((PyObject*)Py_None); Py_INCREF(Py_None);
if (unlikely(__pyx_array___cinit__(o, a, k) < 0)) {
Py_DECREF(o); o = 0;
}
return o;
}
static void __pyx_tp_dealloc_array(PyObject *o) {
struct __pyx_array_obj *p = (struct __pyx_array_obj *)o;
#if PY_VERSION_HEX >= 0x030400a1
if (unlikely(Py_TYPE(o)->tp_finalize) && (!PyType_IS_GC(Py_TYPE(o)) || !_PyGC_FINALIZED(o))) {
if (PyObject_CallFinalizerFromDealloc(o)) return;
}
#endif
{
PyObject *etype, *eval, *etb;
PyErr_Fetch(&etype, &eval, &etb);
++Py_REFCNT(o);
__pyx_array___dealloc__(o);
--Py_REFCNT(o);
PyErr_Restore(etype, eval, etb);
}
Py_CLEAR(p->mode);
Py_CLEAR(p->_format);
(*Py_TYPE(o)->tp_free)(o);
}
static PyObject *__pyx_sq_item_array(PyObject *o, Py_ssize_t i) {
PyObject *r;
PyObject *x = PyInt_FromSsize_t(i); if(!x) return 0;
r = Py_TYPE(o)->tp_as_mapping->mp_subscript(o, x);
Py_DECREF(x);
return r;
}
static int __pyx_mp_ass_subscript_array(PyObject *o, PyObject *i, PyObject *v) {
if (v) {
return __pyx_array___setitem__(o, i, v);
}
else {
PyErr_Format(PyExc_NotImplementedError,
"Subscript deletion not supported by %.200s", Py_TYPE(o)->tp_name);
return -1;
}
}
static PyObject *__pyx_tp_getattro_array(PyObject *o, PyObject *n) {
PyObject *v = PyObject_GenericGetAttr(o, n);
if (!v && PyErr_ExceptionMatches(PyExc_AttributeError)) {
PyErr_Clear();
v = __pyx_array___getattr__(o, n);
}
return v;
}
static PyObject *__pyx_getprop___pyx_array_memview(PyObject *o, CYTHON_UNUSED void *x) {
return get_memview(o);
}
static PyMethodDef __pyx_methods_array[] = {
{__Pyx_NAMESTR("__getattr__"), (PyCFunction)__pyx_array___getattr__, METH_O|METH_COEXIST, __Pyx_DOCSTR(0)},
{0, 0, 0, 0}
};
static struct PyGetSetDef __pyx_getsets_array[] = {
{(char *)"memview", __pyx_getprop___pyx_array_memview, 0, 0, 0},
{0, 0, 0, 0, 0}
};
static PySequenceMethods __pyx_tp_as_sequence_array = {
0, /*sq_length*/
0, /*sq_concat*/
0, /*sq_repeat*/
__pyx_sq_item_array, /*sq_item*/
0, /*sq_slice*/
0, /*sq_ass_item*/
0, /*sq_ass_slice*/
0, /*sq_contains*/
0, /*sq_inplace_concat*/
0, /*sq_inplace_repeat*/
};
static PyMappingMethods __pyx_tp_as_mapping_array = {
0, /*mp_length*/
__pyx_array___getitem__, /*mp_subscript*/
__pyx_mp_ass_subscript_array, /*mp_ass_subscript*/
};
static PyBufferProcs __pyx_tp_as_buffer_array = {
#if PY_MAJOR_VERSION < 3
0, /*bf_getreadbuffer*/
#endif
#if PY_MAJOR_VERSION < 3
0, /*bf_getwritebuffer*/
#endif
#if PY_MAJOR_VERSION < 3
0, /*bf_getsegcount*/
#endif
#if PY_MAJOR_VERSION < 3
0, /*bf_getcharbuffer*/
#endif
#if PY_VERSION_HEX >= 0x02060000
__pyx_array_getbuffer, /*bf_getbuffer*/
#endif
#if PY_VERSION_HEX >= 0x02060000
0, /*bf_releasebuffer*/
#endif
};
static PyTypeObject __pyx_type___pyx_array = {
PyVarObject_HEAD_INIT(0, 0)
__Pyx_NAMESTR("sklearn.metrics.pairwise_fast.array"), /*tp_name*/
sizeof(struct __pyx_array_obj), /*tp_basicsize*/
0, /*tp_itemsize*/
__pyx_tp_dealloc_array, /*tp_dealloc*/
0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
#if PY_MAJOR_VERSION < 3
0, /*tp_compare*/
#else
0, /*reserved*/
#endif
0, /*tp_repr*/
0, /*tp_as_number*/
&__pyx_tp_as_sequence_array, /*tp_as_sequence*/
&__pyx_tp_as_mapping_array, /*tp_as_mapping*/
0, /*tp_hash*/
0, /*tp_call*/
0, /*tp_str*/
__pyx_tp_getattro_array, /*tp_getattro*/
0, /*tp_setattro*/
&__pyx_tp_as_buffer_array, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE, /*tp_flags*/
0, /*tp_doc*/
0, /*tp_traverse*/
0, /*tp_clear*/
0, /*tp_richcompare*/
0, /*tp_weaklistoffset*/
0, /*tp_iter*/
0, /*tp_iternext*/
__pyx_methods_array, /*tp_methods*/
0, /*tp_members*/
__pyx_getsets_array, /*tp_getset*/
0, /*tp_base*/
0, /*tp_dict*/
0, /*tp_descr_get*/
0, /*tp_descr_set*/
0, /*tp_dictoffset*/
0, /*tp_init*/
0, /*tp_alloc*/
__pyx_tp_new_array, /*tp_new*/
0, /*tp_free*/
0, /*tp_is_gc*/
0, /*tp_bases*/
0, /*tp_mro*/
0, /*tp_cache*/
0, /*tp_subclasses*/
0, /*tp_weaklist*/
0, /*tp_del*/
#if PY_VERSION_HEX >= 0x02060000
0, /*tp_version_tag*/
#endif
#if PY_VERSION_HEX >= 0x030400a1
0, /*tp_finalize*/
#endif
};
static PyObject *__pyx_tp_new_Enum(PyTypeObject *t, CYTHON_UNUSED PyObject *a, CYTHON_UNUSED PyObject *k) {
struct __pyx_MemviewEnum_obj *p;
PyObject *o;
if (likely((t->tp_flags & Py_TPFLAGS_IS_ABSTRACT) == 0)) {
o = (*t->tp_alloc)(t, 0);
} else {
o = (PyObject *) PyBaseObject_Type.tp_new(t, __pyx_empty_tuple, 0);
}
if (unlikely(!o)) return 0;
p = ((struct __pyx_MemviewEnum_obj *)o);
p->name = Py_None; Py_INCREF(Py_None);
return o;
}
static void __pyx_tp_dealloc_Enum(PyObject *o) {
struct __pyx_MemviewEnum_obj *p = (struct __pyx_MemviewEnum_obj *)o;
#if PY_VERSION_HEX >= 0x030400a1
if (unlikely(Py_TYPE(o)->tp_finalize) && !_PyGC_FINALIZED(o)) {
if (PyObject_CallFinalizerFromDealloc(o)) return;
}
#endif
PyObject_GC_UnTrack(o);
Py_CLEAR(p->name);
(*Py_TYPE(o)->tp_free)(o);
}
static int __pyx_tp_traverse_Enum(PyObject *o, visitproc v, void *a) {
int e;
struct __pyx_MemviewEnum_obj *p = (struct __pyx_MemviewEnum_obj *)o;
if (p->name) {
e = (*v)(p->name, a); if (e) return e;
}
return 0;
}
static int __pyx_tp_clear_Enum(PyObject *o) {
PyObject* tmp;
struct __pyx_MemviewEnum_obj *p = (struct __pyx_MemviewEnum_obj *)o;
tmp = ((PyObject*)p->name);
p->name = Py_None; Py_INCREF(Py_None);
Py_XDECREF(tmp);
return 0;
}
static PyMethodDef __pyx_methods_Enum[] = {
{0, 0, 0, 0}
};
static PyTypeObject __pyx_type___pyx_MemviewEnum = {
PyVarObject_HEAD_INIT(0, 0)
__Pyx_NAMESTR("sklearn.metrics.pairwise_fast.Enum"), /*tp_name*/
sizeof(struct __pyx_MemviewEnum_obj), /*tp_basicsize*/
0, /*tp_itemsize*/
__pyx_tp_dealloc_Enum, /*tp_dealloc*/
0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
#if PY_MAJOR_VERSION < 3
0, /*tp_compare*/
#else
0, /*reserved*/
#endif
__pyx_MemviewEnum___repr__, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash*/
0, /*tp_call*/
0, /*tp_str*/
0, /*tp_getattro*/
0, /*tp_setattro*/
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/
0, /*tp_doc*/
__pyx_tp_traverse_Enum, /*tp_traverse*/
__pyx_tp_clear_Enum, /*tp_clear*/
0, /*tp_richcompare*/
0, /*tp_weaklistoffset*/
0, /*tp_iter*/
0, /*tp_iternext*/
__pyx_methods_Enum, /*tp_methods*/
0, /*tp_members*/
0, /*tp_getset*/
0, /*tp_base*/
0, /*tp_dict*/
0, /*tp_descr_get*/
0, /*tp_descr_set*/
0, /*tp_dictoffset*/
__pyx_MemviewEnum___init__, /*tp_init*/
0, /*tp_alloc*/
__pyx_tp_new_Enum, /*tp_new*/
0, /*tp_free*/
0, /*tp_is_gc*/
0, /*tp_bases*/
0, /*tp_mro*/
0, /*tp_cache*/
0, /*tp_subclasses*/
0, /*tp_weaklist*/
0, /*tp_del*/
#if PY_VERSION_HEX >= 0x02060000
0, /*tp_version_tag*/
#endif
#if PY_VERSION_HEX >= 0x030400a1
0, /*tp_finalize*/
#endif
};
static struct __pyx_vtabstruct_memoryview __pyx_vtable_memoryview;
static PyObject *__pyx_tp_new_memoryview(PyTypeObject *t, PyObject *a, PyObject *k) {
struct __pyx_memoryview_obj *p;
PyObject *o;
if (likely((t->tp_flags & Py_TPFLAGS_IS_ABSTRACT) == 0)) {
o = (*t->tp_alloc)(t, 0);
} else {
o = (PyObject *) PyBaseObject_Type.tp_new(t, __pyx_empty_tuple, 0);
}
if (unlikely(!o)) return 0;
p = ((struct __pyx_memoryview_obj *)o);
p->__pyx_vtab = __pyx_vtabptr_memoryview;
p->obj = Py_None; Py_INCREF(Py_None);
p->_size = Py_None; Py_INCREF(Py_None);
p->_array_interface = Py_None; Py_INCREF(Py_None);
p->view.obj = NULL;
if (unlikely(__pyx_memoryview___cinit__(o, a, k) < 0)) {
Py_DECREF(o); o = 0;
}
return o;
}
static void __pyx_tp_dealloc_memoryview(PyObject *o) {
struct __pyx_memoryview_obj *p = (struct __pyx_memoryview_obj *)o;
#if PY_VERSION_HEX >= 0x030400a1
if (unlikely(Py_TYPE(o)->tp_finalize) && !_PyGC_FINALIZED(o)) {
if (PyObject_CallFinalizerFromDealloc(o)) return;
}
#endif
PyObject_GC_UnTrack(o);
{
PyObject *etype, *eval, *etb;
PyErr_Fetch(&etype, &eval, &etb);
++Py_REFCNT(o);
__pyx_memoryview___dealloc__(o);
--Py_REFCNT(o);
PyErr_Restore(etype, eval, etb);
}
Py_CLEAR(p->obj);
Py_CLEAR(p->_size);
Py_CLEAR(p->_array_interface);
(*Py_TYPE(o)->tp_free)(o);
}
static int __pyx_tp_traverse_memoryview(PyObject *o, visitproc v, void *a) {
int e;
struct __pyx_memoryview_obj *p = (struct __pyx_memoryview_obj *)o;
if (p->obj) {
e = (*v)(p->obj, a); if (e) return e;
}
if (p->_size) {
e = (*v)(p->_size, a); if (e) return e;
}
if (p->_array_interface) {
e = (*v)(p->_array_interface, a); if (e) return e;
}
if (p->view.obj) {
e = (*v)(p->view.obj, a); if (e) return e;
}
return 0;
}
static int __pyx_tp_clear_memoryview(PyObject *o) {
PyObject* tmp;
struct __pyx_memoryview_obj *p = (struct __pyx_memoryview_obj *)o;
tmp = ((PyObject*)p->obj);
p->obj = Py_None; Py_INCREF(Py_None);
Py_XDECREF(tmp);
tmp = ((PyObject*)p->_size);
p->_size = Py_None; Py_INCREF(Py_None);
Py_XDECREF(tmp);
tmp = ((PyObject*)p->_array_interface);
p->_array_interface = Py_None; Py_INCREF(Py_None);
Py_XDECREF(tmp);
Py_CLEAR(p->view.obj);
return 0;
}
static PyObject *__pyx_sq_item_memoryview(PyObject *o, Py_ssize_t i) {
PyObject *r;
PyObject *x = PyInt_FromSsize_t(i); if(!x) return 0;
r = Py_TYPE(o)->tp_as_mapping->mp_subscript(o, x);
Py_DECREF(x);
return r;
}
static int __pyx_mp_ass_subscript_memoryview(PyObject *o, PyObject *i, PyObject *v) {
if (v) {
return __pyx_memoryview___setitem__(o, i, v);
}
else {
PyErr_Format(PyExc_NotImplementedError,
"Subscript deletion not supported by %.200s", Py_TYPE(o)->tp_name);
return -1;
}
}
static PyObject *__pyx_getprop___pyx_memoryview_T(PyObject *o, CYTHON_UNUSED void *x) {
return __pyx_memoryview_transpose(o);
}
static PyObject *__pyx_getprop___pyx_memoryview_base(PyObject *o, CYTHON_UNUSED void *x) {
return __pyx_memoryview__get__base(o);
}
static PyObject *__pyx_getprop___pyx_memoryview_shape(PyObject *o, CYTHON_UNUSED void *x) {
return __pyx_memoryview_get_shape(o);
}
static PyObject *__pyx_getprop___pyx_memoryview_strides(PyObject *o, CYTHON_UNUSED void *x) {
return __pyx_memoryview_get_strides(o);
}
static PyObject *__pyx_getprop___pyx_memoryview_suboffsets(PyObject *o, CYTHON_UNUSED void *x) {
return __pyx_memoryview_get_suboffsets(o);
}
static PyObject *__pyx_getprop___pyx_memoryview_ndim(PyObject *o, CYTHON_UNUSED void *x) {
return __pyx_memoryview_get_ndim(o);
}
static PyObject *__pyx_getprop___pyx_memoryview_itemsize(PyObject *o, CYTHON_UNUSED void *x) {
return __pyx_memoryview_get_itemsize(o);
}
static PyObject *__pyx_getprop___pyx_memoryview_nbytes(PyObject *o, CYTHON_UNUSED void *x) {
return __pyx_memoryview_get_nbytes(o);
}
static PyObject *__pyx_getprop___pyx_memoryview_size(PyObject *o, CYTHON_UNUSED void *x) {
return __pyx_memoryview_get_size(o);
}
static PyMethodDef __pyx_methods_memoryview[] = {
{__Pyx_NAMESTR("is_c_contig"), (PyCFunction)__pyx_memoryview_is_c_contig, METH_NOARGS, __Pyx_DOCSTR(0)},
{__Pyx_NAMESTR("is_f_contig"), (PyCFunction)__pyx_memoryview_is_f_contig, METH_NOARGS, __Pyx_DOCSTR(0)},
{__Pyx_NAMESTR("copy"), (PyCFunction)__pyx_memoryview_copy, METH_NOARGS, __Pyx_DOCSTR(0)},
{__Pyx_NAMESTR("copy_fortran"), (PyCFunction)__pyx_memoryview_copy_fortran, METH_NOARGS, __Pyx_DOCSTR(0)},
{0, 0, 0, 0}
};
static struct PyGetSetDef __pyx_getsets_memoryview[] = {
{(char *)"T", __pyx_getprop___pyx_memoryview_T, 0, 0, 0},
{(char *)"base", __pyx_getprop___pyx_memoryview_base, 0, 0, 0},
{(char *)"shape", __pyx_getprop___pyx_memoryview_shape, 0, 0, 0},
{(char *)"strides", __pyx_getprop___pyx_memoryview_strides, 0, 0, 0},
{(char *)"suboffsets", __pyx_getprop___pyx_memoryview_suboffsets, 0, 0, 0},
{(char *)"ndim", __pyx_getprop___pyx_memoryview_ndim, 0, 0, 0},
{(char *)"itemsize", __pyx_getprop___pyx_memoryview_itemsize, 0, 0, 0},
{(char *)"nbytes", __pyx_getprop___pyx_memoryview_nbytes, 0, 0, 0},
{(char *)"size", __pyx_getprop___pyx_memoryview_size, 0, 0, 0},
{0, 0, 0, 0, 0}
};
static PySequenceMethods __pyx_tp_as_sequence_memoryview = {
__pyx_memoryview___len__, /*sq_length*/
0, /*sq_concat*/
0, /*sq_repeat*/
__pyx_sq_item_memoryview, /*sq_item*/
0, /*sq_slice*/
0, /*sq_ass_item*/
0, /*sq_ass_slice*/
0, /*sq_contains*/
0, /*sq_inplace_concat*/
0, /*sq_inplace_repeat*/
};
static PyMappingMethods __pyx_tp_as_mapping_memoryview = {
__pyx_memoryview___len__, /*mp_length*/
__pyx_memoryview___getitem__, /*mp_subscript*/
__pyx_mp_ass_subscript_memoryview, /*mp_ass_subscript*/
};
static PyBufferProcs __pyx_tp_as_buffer_memoryview = {
#if PY_MAJOR_VERSION < 3
0, /*bf_getreadbuffer*/
#endif
#if PY_MAJOR_VERSION < 3
0, /*bf_getwritebuffer*/
#endif
#if PY_MAJOR_VERSION < 3
0, /*bf_getsegcount*/
#endif
#if PY_MAJOR_VERSION < 3
0, /*bf_getcharbuffer*/
#endif
#if PY_VERSION_HEX >= 0x02060000
__pyx_memoryview_getbuffer, /*bf_getbuffer*/
#endif
#if PY_VERSION_HEX >= 0x02060000
0, /*bf_releasebuffer*/
#endif
};
static PyTypeObject __pyx_type___pyx_memoryview = {
PyVarObject_HEAD_INIT(0, 0)
__Pyx_NAMESTR("sklearn.metrics.pairwise_fast.memoryview"), /*tp_name*/
sizeof(struct __pyx_memoryview_obj), /*tp_basicsize*/
0, /*tp_itemsize*/
__pyx_tp_dealloc_memoryview, /*tp_dealloc*/
0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
#if PY_MAJOR_VERSION < 3
0, /*tp_compare*/
#else
0, /*reserved*/
#endif
__pyx_memoryview___repr__, /*tp_repr*/
0, /*tp_as_number*/
&__pyx_tp_as_sequence_memoryview, /*tp_as_sequence*/
&__pyx_tp_as_mapping_memoryview, /*tp_as_mapping*/
0, /*tp_hash*/
0, /*tp_call*/
__pyx_memoryview___str__, /*tp_str*/
0, /*tp_getattro*/
0, /*tp_setattro*/
&__pyx_tp_as_buffer_memoryview, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/
0, /*tp_doc*/
__pyx_tp_traverse_memoryview, /*tp_traverse*/
__pyx_tp_clear_memoryview, /*tp_clear*/
0, /*tp_richcompare*/
0, /*tp_weaklistoffset*/
0, /*tp_iter*/
0, /*tp_iternext*/
__pyx_methods_memoryview, /*tp_methods*/
0, /*tp_members*/
__pyx_getsets_memoryview, /*tp_getset*/
0, /*tp_base*/
0, /*tp_dict*/
0, /*tp_descr_get*/
0, /*tp_descr_set*/
0, /*tp_dictoffset*/
0, /*tp_init*/
0, /*tp_alloc*/
__pyx_tp_new_memoryview, /*tp_new*/
0, /*tp_free*/
0, /*tp_is_gc*/
0, /*tp_bases*/
0, /*tp_mro*/
0, /*tp_cache*/
0, /*tp_subclasses*/
0, /*tp_weaklist*/
0, /*tp_del*/
#if PY_VERSION_HEX >= 0x02060000
0, /*tp_version_tag*/
#endif
#if PY_VERSION_HEX >= 0x030400a1
0, /*tp_finalize*/
#endif
};
static struct __pyx_vtabstruct__memoryviewslice __pyx_vtable__memoryviewslice;
static PyObject *__pyx_tp_new__memoryviewslice(PyTypeObject *t, PyObject *a, PyObject *k) {
struct __pyx_memoryviewslice_obj *p;
PyObject *o = __pyx_tp_new_memoryview(t, a, k);
if (unlikely(!o)) return 0;
p = ((struct __pyx_memoryviewslice_obj *)o);
p->__pyx_base.__pyx_vtab = (struct __pyx_vtabstruct_memoryview*)__pyx_vtabptr__memoryviewslice;
p->from_object = Py_None; Py_INCREF(Py_None);
p->from_slice.memview = NULL;
return o;
}
static void __pyx_tp_dealloc__memoryviewslice(PyObject *o) {
struct __pyx_memoryviewslice_obj *p = (struct __pyx_memoryviewslice_obj *)o;
#if PY_VERSION_HEX >= 0x030400a1
if (unlikely(Py_TYPE(o)->tp_finalize) && !_PyGC_FINALIZED(o)) {
if (PyObject_CallFinalizerFromDealloc(o)) return;
}
#endif
PyObject_GC_UnTrack(o);
{
PyObject *etype, *eval, *etb;
PyErr_Fetch(&etype, &eval, &etb);
++Py_REFCNT(o);
__pyx_memoryviewslice___dealloc__(o);
--Py_REFCNT(o);
PyErr_Restore(etype, eval, etb);
}
Py_CLEAR(p->from_object);
PyObject_GC_Track(o);
__pyx_tp_dealloc_memoryview(o);
}
static int __pyx_tp_traverse__memoryviewslice(PyObject *o, visitproc v, void *a) {
int e;
struct __pyx_memoryviewslice_obj *p = (struct __pyx_memoryviewslice_obj *)o;
e = __pyx_tp_traverse_memoryview(o, v, a); if (e) return e;
if (p->from_object) {
e = (*v)(p->from_object, a); if (e) return e;
}
return 0;
}
static int __pyx_tp_clear__memoryviewslice(PyObject *o) {
PyObject* tmp;
struct __pyx_memoryviewslice_obj *p = (struct __pyx_memoryviewslice_obj *)o;
__pyx_tp_clear_memoryview(o);
tmp = ((PyObject*)p->from_object);
p->from_object = Py_None; Py_INCREF(Py_None);
Py_XDECREF(tmp);
__PYX_XDEC_MEMVIEW(&p->from_slice, 1);
return 0;
}
static PyObject *__pyx_getprop___pyx_memoryviewslice_base(PyObject *o, CYTHON_UNUSED void *x) {
return __pyx_memoryviewslice__get__base(o);
}
static PyMethodDef __pyx_methods__memoryviewslice[] = {
{0, 0, 0, 0}
};
static struct PyGetSetDef __pyx_getsets__memoryviewslice[] = {
{(char *)"base", __pyx_getprop___pyx_memoryviewslice_base, 0, 0, 0},
{0, 0, 0, 0, 0}
};
static PyTypeObject __pyx_type___pyx_memoryviewslice = {
PyVarObject_HEAD_INIT(0, 0)
__Pyx_NAMESTR("sklearn.metrics.pairwise_fast._memoryviewslice"), /*tp_name*/
sizeof(struct __pyx_memoryviewslice_obj), /*tp_basicsize*/
0, /*tp_itemsize*/
__pyx_tp_dealloc__memoryviewslice, /*tp_dealloc*/
0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
#if PY_MAJOR_VERSION < 3
0, /*tp_compare*/
#else
0, /*reserved*/
#endif
#if CYTHON_COMPILING_IN_PYPY
__pyx_memoryview___repr__, /*tp_repr*/
#else
0, /*tp_repr*/
#endif
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash*/
0, /*tp_call*/
#if CYTHON_COMPILING_IN_PYPY
__pyx_memoryview___str__, /*tp_str*/
#else
0, /*tp_str*/
#endif
0, /*tp_getattro*/
0, /*tp_setattro*/
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT|Py_TPFLAGS_HAVE_VERSION_TAG|Py_TPFLAGS_CHECKTYPES|Py_TPFLAGS_HAVE_NEWBUFFER|Py_TPFLAGS_BASETYPE|Py_TPFLAGS_HAVE_GC, /*tp_flags*/
__Pyx_DOCSTR("Internal class for passing memoryview slices to Python"), /*tp_doc*/
__pyx_tp_traverse__memoryviewslice, /*tp_traverse*/
__pyx_tp_clear__memoryviewslice, /*tp_clear*/
0, /*tp_richcompare*/
0, /*tp_weaklistoffset*/
0, /*tp_iter*/
0, /*tp_iternext*/
__pyx_methods__memoryviewslice, /*tp_methods*/
0, /*tp_members*/
__pyx_getsets__memoryviewslice, /*tp_getset*/
0, /*tp_base*/
0, /*tp_dict*/
0, /*tp_descr_get*/
0, /*tp_descr_set*/
0, /*tp_dictoffset*/
0, /*tp_init*/
0, /*tp_alloc*/
__pyx_tp_new__memoryviewslice, /*tp_new*/
0, /*tp_free*/
0, /*tp_is_gc*/
0, /*tp_bases*/
0, /*tp_mro*/
0, /*tp_cache*/
0, /*tp_subclasses*/
0, /*tp_weaklist*/
0, /*tp_del*/
#if PY_VERSION_HEX >= 0x02060000
0, /*tp_version_tag*/
#endif
#if PY_VERSION_HEX >= 0x030400a1
0, /*tp_finalize*/
#endif
};
static PyMethodDef __pyx_methods[] = {
{0, 0, 0, 0}
};
#if PY_MAJOR_VERSION >= 3
static struct PyModuleDef __pyx_moduledef = {
#if PY_VERSION_HEX < 0x03020000
{ PyObject_HEAD_INIT(NULL) NULL, 0, NULL },
#else
PyModuleDef_HEAD_INIT,
#endif
__Pyx_NAMESTR("pairwise_fast"),
0, /* m_doc */
-1, /* m_size */
__pyx_methods /* m_methods */,
NULL, /* m_reload */
NULL, /* m_traverse */
NULL, /* m_clear */
NULL /* m_free */
};
#endif
static __Pyx_StringTabEntry __pyx_string_tab[] = {
{&__pyx_n_s_ASCII, __pyx_k_ASCII, sizeof(__pyx_k_ASCII), 0, 0, 1, 1},
{&__pyx_kp_s_Buffer_view_does_not_expose_stri, __pyx_k_Buffer_view_does_not_expose_stri, sizeof(__pyx_k_Buffer_view_does_not_expose_stri), 0, 0, 1, 0},
{&__pyx_kp_s_Can_only_create_a_buffer_that_is, __pyx_k_Can_only_create_a_buffer_that_is, sizeof(__pyx_k_Can_only_create_a_buffer_that_is), 0, 0, 1, 0},
{&__pyx_kp_s_Cannot_index_with_type_s, __pyx_k_Cannot_index_with_type_s, sizeof(__pyx_k_Cannot_index_with_type_s), 0, 0, 1, 0},
{&__pyx_n_s_D, __pyx_k_D, sizeof(__pyx_k_D), 0, 0, 1, 1},
{&__pyx_n_s_Ellipsis, __pyx_k_Ellipsis, sizeof(__pyx_k_Ellipsis), 0, 0, 1, 1},
{&__pyx_kp_s_Empty_shape_tuple_for_cython_arr, __pyx_k_Empty_shape_tuple_for_cython_arr, sizeof(__pyx_k_Empty_shape_tuple_for_cython_arr), 0, 0, 1, 0},
{&__pyx_kp_s_Expected_at_least_d_arguments, __pyx_k_Expected_at_least_d_arguments, sizeof(__pyx_k_Expected_at_least_d_arguments), 0, 0, 1, 0},
{&__pyx_kp_u_Format_string_allocated_too_shor, __pyx_k_Format_string_allocated_too_shor, sizeof(__pyx_k_Format_string_allocated_too_shor), 0, 1, 0, 0},
{&__pyx_kp_u_Format_string_allocated_too_shor_2, __pyx_k_Format_string_allocated_too_shor_2, sizeof(__pyx_k_Format_string_allocated_too_shor_2), 0, 1, 0, 0},
{&__pyx_kp_s_Function_call_with_ambiguous_arg, __pyx_k_Function_call_with_ambiguous_arg, sizeof(__pyx_k_Function_call_with_ambiguous_arg), 0, 0, 1, 0},
{&__pyx_n_s_ImportError, __pyx_k_ImportError, sizeof(__pyx_k_ImportError), 0, 0, 1, 1},
{&__pyx_n_s_IndexError, __pyx_k_IndexError, sizeof(__pyx_k_IndexError), 0, 0, 1, 1},
{&__pyx_kp_s_Indirect_dimensions_not_supporte, __pyx_k_Indirect_dimensions_not_supporte, sizeof(__pyx_k_Indirect_dimensions_not_supporte), 0, 0, 1, 0},
{&__pyx_kp_s_Invalid_mode_expected_c_or_fortr, __pyx_k_Invalid_mode_expected_c_or_fortr, sizeof(__pyx_k_Invalid_mode_expected_c_or_fortr), 0, 0, 1, 0},
{&__pyx_kp_s_Invalid_shape_in_axis_d_d, __pyx_k_Invalid_shape_in_axis_d_d, sizeof(__pyx_k_Invalid_shape_in_axis_d_d), 0, 0, 1, 0},
{&__pyx_n_s_MemoryError, __pyx_k_MemoryError, sizeof(__pyx_k_MemoryError), 0, 0, 1, 1},
{&__pyx_kp_s_MemoryView_of_r_at_0x_x, __pyx_k_MemoryView_of_r_at_0x_x, sizeof(__pyx_k_MemoryView_of_r_at_0x_x), 0, 0, 1, 0},
{&__pyx_kp_s_MemoryView_of_r_object, __pyx_k_MemoryView_of_r_object, sizeof(__pyx_k_MemoryView_of_r_object), 0, 0, 1, 0},
{&__pyx_kp_s_No_matching_signature_found, __pyx_k_No_matching_signature_found, sizeof(__pyx_k_No_matching_signature_found), 0, 0, 1, 0},
{&__pyx_kp_u_Non_native_byte_order_not_suppor, __pyx_k_Non_native_byte_order_not_suppor, sizeof(__pyx_k_Non_native_byte_order_not_suppor), 0, 1, 0, 0},
{&__pyx_n_b_O, __pyx_k_O, sizeof(__pyx_k_O), 0, 0, 0, 1},
{&__pyx_n_s_O, __pyx_k_O, sizeof(__pyx_k_O), 0, 0, 1, 1},
{&__pyx_kp_s_Out_of_bounds_on_buffer_access_a, __pyx_k_Out_of_bounds_on_buffer_access_a, sizeof(__pyx_k_Out_of_bounds_on_buffer_access_a), 0, 0, 1, 0},
{&__pyx_kp_u_Pairwise_L1_distances_for_CSR_ma, __pyx_k_Pairwise_L1_distances_for_CSR_ma, sizeof(__pyx_k_Pairwise_L1_distances_for_CSR_ma), 0, 1, 0, 0},
{&__pyx_n_s_RuntimeError, __pyx_k_RuntimeError, sizeof(__pyx_k_RuntimeError), 0, 0, 1, 1},
{&__pyx_n_s_TypeError, __pyx_k_TypeError, sizeof(__pyx_k_TypeError), 0, 0, 1, 1},
{&__pyx_kp_s_Unable_to_convert_item_to_object, __pyx_k_Unable_to_convert_item_to_object, sizeof(__pyx_k_Unable_to_convert_item_to_object), 0, 0, 1, 0},
{&__pyx_n_s_ValueError, __pyx_k_ValueError, sizeof(__pyx_k_ValueError), 0, 0, 1, 1},
{&__pyx_n_s_X, __pyx_k_X, sizeof(__pyx_k_X), 0, 0, 1, 1},
{&__pyx_n_s_X_data, __pyx_k_X_data, sizeof(__pyx_k_X_data), 0, 0, 1, 1},
{&__pyx_n_s_X_indices, __pyx_k_X_indices, sizeof(__pyx_k_X_indices), 0, 0, 1, 1},
{&__pyx_n_s_X_indptr, __pyx_k_X_indptr, sizeof(__pyx_k_X_indptr), 0, 0, 1, 1},
{&__pyx_n_s_Y, __pyx_k_Y, sizeof(__pyx_k_Y), 0, 0, 1, 1},
{&__pyx_n_s_Y_data, __pyx_k_Y_data, sizeof(__pyx_k_Y_data), 0, 0, 1, 1},
{&__pyx_n_s_Y_indices, __pyx_k_Y_indices, sizeof(__pyx_k_Y_indices), 0, 0, 1, 1},
{&__pyx_n_s_Y_indptr, __pyx_k_Y_indptr, sizeof(__pyx_k_Y_indptr), 0, 0, 1, 1},
{&__pyx_kp_s__2, __pyx_k__2, sizeof(__pyx_k__2), 0, 0, 1, 0},
{&__pyx_kp_s__4, __pyx_k__4, sizeof(__pyx_k__4), 0, 0, 1, 0},
{&__pyx_n_s_allocate_buffer, __pyx_k_allocate_buffer, sizeof(__pyx_k_allocate_buffer), 0, 0, 1, 1},
{&__pyx_n_s_args, __pyx_k_args, sizeof(__pyx_k_args), 0, 0, 1, 1},
{&__pyx_n_s_base, __pyx_k_base, sizeof(__pyx_k_base), 0, 0, 1, 1},
{&__pyx_n_b_c, __pyx_k_c, sizeof(__pyx_k_c), 0, 0, 0, 1},
{&__pyx_n_s_c, __pyx_k_c, sizeof(__pyx_k_c), 0, 0, 1, 1},
{&__pyx_n_u_c, __pyx_k_c, sizeof(__pyx_k_c), 0, 1, 0, 1},
{&__pyx_n_s_chi2_kernel_fast, __pyx_k_chi2_kernel_fast, sizeof(__pyx_k_chi2_kernel_fast), 0, 0, 1, 1},
{&__pyx_n_s_class, __pyx_k_class, sizeof(__pyx_k_class), 0, 0, 1, 1},
{&__pyx_kp_s_contiguous_and_direct, __pyx_k_contiguous_and_direct, sizeof(__pyx_k_contiguous_and_direct), 0, 0, 1, 0},
{&__pyx_kp_s_contiguous_and_indirect, __pyx_k_contiguous_and_indirect, sizeof(__pyx_k_contiguous_and_indirect), 0, 0, 1, 0},
{&__pyx_n_s_decode, __pyx_k_decode, sizeof(__pyx_k_decode), 0, 0, 1, 1},
{&__pyx_n_s_defaults, __pyx_k_defaults, sizeof(__pyx_k_defaults), 0, 0, 1, 1},
{&__pyx_n_s_denom, __pyx_k_denom, sizeof(__pyx_k_denom), 0, 0, 1, 1},
{&__pyx_kp_s_double_1, __pyx_k_double_1, sizeof(__pyx_k_double_1), 0, 0, 1, 0},
{&__pyx_n_s_double_array_2d_t, __pyx_k_double_array_2d_t, sizeof(__pyx_k_double_array_2d_t), 0, 0, 1, 1},
{&__pyx_n_s_dtype, __pyx_k_dtype, sizeof(__pyx_k_dtype), 0, 0, 1, 1},
{&__pyx_n_s_dtype_is_object, __pyx_k_dtype_is_object, sizeof(__pyx_k_dtype_is_object), 0, 0, 1, 1},
{&__pyx_n_s_empty, __pyx_k_empty, sizeof(__pyx_k_empty), 0, 0, 1, 1},
{&__pyx_n_s_encode, __pyx_k_encode, sizeof(__pyx_k_encode), 0, 0, 1, 1},
{&__pyx_n_s_enumerate, __pyx_k_enumerate, sizeof(__pyx_k_enumerate), 0, 0, 1, 1},
{&__pyx_n_s_error, __pyx_k_error, sizeof(__pyx_k_error), 0, 0, 1, 1},
{&__pyx_n_s_f, __pyx_k_f, sizeof(__pyx_k_f), 0, 0, 1, 1},
{&__pyx_n_s_flags, __pyx_k_flags, sizeof(__pyx_k_flags), 0, 0, 1, 1},
{&__pyx_kp_s_float_1, __pyx_k_float_1, sizeof(__pyx_k_float_1), 0, 0, 1, 0},
{&__pyx_n_s_float_array_2d_t, __pyx_k_float_array_2d_t, sizeof(__pyx_k_float_array_2d_t), 0, 0, 1, 1},
{&__pyx_n_s_format, __pyx_k_format, sizeof(__pyx_k_format), 0, 0, 1, 1},
{&__pyx_n_b_fortran, __pyx_k_fortran, sizeof(__pyx_k_fortran), 0, 0, 0, 1},
{&__pyx_n_s_fortran, __pyx_k_fortran, sizeof(__pyx_k_fortran), 0, 0, 1, 1},
{&__pyx_kp_s_got_differing_extents_in_dimensi, __pyx_k_got_differing_extents_in_dimensi, sizeof(__pyx_k_got_differing_extents_in_dimensi), 0, 0, 1, 0},
{&__pyx_kp_s_home_larsb_src_scikit_learn_skl, __pyx_k_home_larsb_src_scikit_learn_skl, sizeof(__pyx_k_home_larsb_src_scikit_learn_skl), 0, 0, 1, 0},
{&__pyx_n_s_i, __pyx_k_i, sizeof(__pyx_k_i), 0, 0, 1, 1},
{&__pyx_n_s_id, __pyx_k_id, sizeof(__pyx_k_id), 0, 0, 1, 1},
{&__pyx_n_s_import, __pyx_k_import, sizeof(__pyx_k_import), 0, 0, 1, 1},
{&__pyx_n_s_itemsize, __pyx_k_itemsize, sizeof(__pyx_k_itemsize), 0, 0, 1, 1},
{&__pyx_kp_s_itemsize_0_for_cython_array, __pyx_k_itemsize_0_for_cython_array, sizeof(__pyx_k_itemsize_0_for_cython_array), 0, 0, 1, 0},
{&__pyx_n_s_ix, __pyx_k_ix, sizeof(__pyx_k_ix), 0, 0, 1, 1},
{&__pyx_n_s_iy, __pyx_k_iy, sizeof(__pyx_k_iy), 0, 0, 1, 1},
{&__pyx_n_s_j, __pyx_k_j, sizeof(__pyx_k_j), 0, 0, 1, 1},
{&__pyx_n_s_k, __pyx_k_k, sizeof(__pyx_k_k), 0, 0, 1, 1},
{&__pyx_n_s_kind, __pyx_k_kind, sizeof(__pyx_k_kind), 0, 0, 1, 1},
{&__pyx_n_s_kwargs, __pyx_k_kwargs, sizeof(__pyx_k_kwargs), 0, 0, 1, 1},
{&__pyx_n_s_main, __pyx_k_main, sizeof(__pyx_k_main), 0, 0, 1, 1},
{&__pyx_n_s_memview, __pyx_k_memview, sizeof(__pyx_k_memview), 0, 0, 1, 1},
{&__pyx_n_s_mode, __pyx_k_mode, sizeof(__pyx_k_mode), 0, 0, 1, 1},
{&__pyx_n_s_n_features, __pyx_k_n_features, sizeof(__pyx_k_n_features), 0, 0, 1, 1},
{&__pyx_n_s_n_samples_X, __pyx_k_n_samples_X, sizeof(__pyx_k_n_samples_X), 0, 0, 1, 1},
{&__pyx_n_s_n_samples_Y, __pyx_k_n_samples_Y, sizeof(__pyx_k_n_samples_Y), 0, 0, 1, 1},
{&__pyx_n_s_name, __pyx_k_name, sizeof(__pyx_k_name), 0, 0, 1, 1},
{&__pyx_n_s_name_2, __pyx_k_name_2, sizeof(__pyx_k_name_2), 0, 0, 1, 1},
{&__pyx_n_s_ndarray, __pyx_k_ndarray, sizeof(__pyx_k_ndarray), 0, 0, 1, 1},
{&__pyx_kp_u_ndarray_is_not_C_contiguous, __pyx_k_ndarray_is_not_C_contiguous, sizeof(__pyx_k_ndarray_is_not_C_contiguous), 0, 1, 0, 0},
{&__pyx_kp_u_ndarray_is_not_Fortran_contiguou, __pyx_k_ndarray_is_not_Fortran_contiguou, sizeof(__pyx_k_ndarray_is_not_Fortran_contiguou), 0, 1, 0, 0},
{&__pyx_n_s_ndim, __pyx_k_ndim, sizeof(__pyx_k_ndim), 0, 0, 1, 1},
{&__pyx_n_s_nom, __pyx_k_nom, sizeof(__pyx_k_nom), 0, 0, 1, 1},
{&__pyx_n_s_np, __pyx_k_np, sizeof(__pyx_k_np), 0, 0, 1, 1},
{&__pyx_n_s_numpy, __pyx_k_numpy, sizeof(__pyx_k_numpy), 0, 0, 1, 1},
{&__pyx_n_s_obj, __pyx_k_obj, sizeof(__pyx_k_obj), 0, 0, 1, 1},
{&__pyx_n_s_ord, __pyx_k_ord, sizeof(__pyx_k_ord), 0, 0, 1, 1},
{&__pyx_n_s_pack, __pyx_k_pack, sizeof(__pyx_k_pack), 0, 0, 1, 1},
{&__pyx_n_s_pyx_getbuffer, __pyx_k_pyx_getbuffer, sizeof(__pyx_k_pyx_getbuffer), 0, 0, 1, 1},
{&__pyx_n_s_pyx_releasebuffer, __pyx_k_pyx_releasebuffer, sizeof(__pyx_k_pyx_releasebuffer), 0, 0, 1, 1},
{&__pyx_n_s_pyx_vtable, __pyx_k_pyx_vtable, sizeof(__pyx_k_pyx_vtable), 0, 0, 1, 1},
{&__pyx_n_s_range, __pyx_k_range, sizeof(__pyx_k_range), 0, 0, 1, 1},
{&__pyx_n_s_res, __pyx_k_res, sizeof(__pyx_k_res), 0, 0, 1, 1},
{&__pyx_n_s_result, __pyx_k_result, sizeof(__pyx_k_result), 0, 0, 1, 1},
{&__pyx_n_s_row, __pyx_k_row, sizeof(__pyx_k_row), 0, 0, 1, 1},
{&__pyx_n_s_shape, __pyx_k_shape, sizeof(__pyx_k_shape), 0, 0, 1, 1},
{&__pyx_n_s_signatures, __pyx_k_signatures, sizeof(__pyx_k_signatures), 0, 0, 1, 1},
{&__pyx_n_s_size, __pyx_k_size, sizeof(__pyx_k_size), 0, 0, 1, 1},
{&__pyx_n_s_sklearn_metrics_pairwise_fast, __pyx_k_sklearn_metrics_pairwise_fast, sizeof(__pyx_k_sklearn_metrics_pairwise_fast), 0, 0, 1, 1},
{&__pyx_n_s_sparse_manhattan, __pyx_k_sparse_manhattan, sizeof(__pyx_k_sparse_manhattan), 0, 0, 1, 1},
{&__pyx_kp_u_sparse_manhattan_line_53, __pyx_k_sparse_manhattan_line_53, sizeof(__pyx_k_sparse_manhattan_line_53), 0, 1, 0, 0},
{&__pyx_n_s_split, __pyx_k_split, sizeof(__pyx_k_split), 0, 0, 1, 1},
{&__pyx_n_s_start, __pyx_k_start, sizeof(__pyx_k_start), 0, 0, 1, 1},
{&__pyx_n_s_step, __pyx_k_step, sizeof(__pyx_k_step), 0, 0, 1, 1},
{&__pyx_n_s_stop, __pyx_k_stop, sizeof(__pyx_k_stop), 0, 0, 1, 1},
{&__pyx_kp_s_strided_and_direct, __pyx_k_strided_and_direct, sizeof(__pyx_k_strided_and_direct), 0, 0, 1, 0},
{&__pyx_kp_s_strided_and_direct_or_indirect, __pyx_k_strided_and_direct_or_indirect, sizeof(__pyx_k_strided_and_direct_or_indirect), 0, 0, 1, 0},
{&__pyx_kp_s_strided_and_indirect, __pyx_k_strided_and_indirect, sizeof(__pyx_k_strided_and_indirect), 0, 0, 1, 0},
{&__pyx_n_s_strip, __pyx_k_strip, sizeof(__pyx_k_strip), 0, 0, 1, 1},
{&__pyx_n_s_struct, __pyx_k_struct, sizeof(__pyx_k_struct), 0, 0, 1, 1},
{&__pyx_n_s_test, __pyx_k_test, sizeof(__pyx_k_test), 0, 0, 1, 1},
{&__pyx_n_s_u, __pyx_k_u, sizeof(__pyx_k_u), 0, 0, 1, 1},
{&__pyx_kp_s_unable_to_allocate_array_data, __pyx_k_unable_to_allocate_array_data, sizeof(__pyx_k_unable_to_allocate_array_data), 0, 0, 1, 0},
{&__pyx_kp_s_unable_to_allocate_shape_or_stri, __pyx_k_unable_to_allocate_shape_or_stri, sizeof(__pyx_k_unable_to_allocate_shape_or_stri), 0, 0, 1, 0},
{&__pyx_kp_u_unknown_dtype_code_in_numpy_pxd, __pyx_k_unknown_dtype_code_in_numpy_pxd, sizeof(__pyx_k_unknown_dtype_code_in_numpy_pxd), 0, 1, 0, 0},
{&__pyx_n_s_unpack, __pyx_k_unpack, sizeof(__pyx_k_unpack), 0, 0, 1, 1},
{&__pyx_n_s_xrange, __pyx_k_xrange, sizeof(__pyx_k_xrange), 0, 0, 1, 1},
{&__pyx_n_s_zip, __pyx_k_zip, sizeof(__pyx_k_zip), 0, 0, 1, 1},
{0, 0, 0, 0, 0, 0, 0}
};
static int __Pyx_InitCachedBuiltins(void) {
__pyx_builtin_ImportError = __Pyx_GetBuiltinName(__pyx_n_s_ImportError); if (!__pyx_builtin_ImportError) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_builtin_TypeError = __Pyx_GetBuiltinName(__pyx_n_s_TypeError); if (!__pyx_builtin_TypeError) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_builtin_ord = __Pyx_GetBuiltinName(__pyx_n_s_ord); if (!__pyx_builtin_ord) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_builtin_zip = __Pyx_GetBuiltinName(__pyx_n_s_zip); if (!__pyx_builtin_zip) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_builtin_range = __Pyx_GetBuiltinName(__pyx_n_s_range); if (!__pyx_builtin_range) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 42; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_builtin_ValueError = __Pyx_GetBuiltinName(__pyx_n_s_ValueError); if (!__pyx_builtin_ValueError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_builtin_RuntimeError = __Pyx_GetBuiltinName(__pyx_n_s_RuntimeError); if (!__pyx_builtin_RuntimeError) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_builtin_MemoryError = __Pyx_GetBuiltinName(__pyx_n_s_MemoryError); if (!__pyx_builtin_MemoryError) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 141; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_builtin_enumerate = __Pyx_GetBuiltinName(__pyx_n_s_enumerate); if (!__pyx_builtin_enumerate) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 145; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_builtin_Ellipsis = __Pyx_GetBuiltinName(__pyx_n_s_Ellipsis); if (!__pyx_builtin_Ellipsis) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 363; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
#if PY_MAJOR_VERSION >= 3
__pyx_builtin_xrange = __Pyx_GetBuiltinName(__pyx_n_s_range); if (!__pyx_builtin_xrange) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 522; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
#else
__pyx_builtin_xrange = __Pyx_GetBuiltinName(__pyx_n_s_xrange); if (!__pyx_builtin_xrange) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 522; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
#endif
__pyx_builtin_id = __Pyx_GetBuiltinName(__pyx_n_s_id); if (!__pyx_builtin_id) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 577; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_builtin_IndexError = __Pyx_GetBuiltinName(__pyx_n_s_IndexError); if (!__pyx_builtin_IndexError) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 797; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
return 0;
__pyx_L1_error:;
return -1;
}
static int __Pyx_InitCachedConstants(void) {
__Pyx_RefNannyDeclarations
__Pyx_RefNannySetupContext("__Pyx_InitCachedConstants", 0);
/* "sklearn/metrics/pairwise_fast.pyx":32
*
*
* def _chi2_kernel_fast(floating_array_2d_t X, # <<<<<<<<<<<<<<
* floating_array_2d_t Y,
* floating_array_2d_t result):
*/
__pyx_tuple_ = PyTuple_Pack(2, __pyx_n_s_i, __pyx_n_s_u); if (unlikely(!__pyx_tuple_)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_tuple_);
__Pyx_GIVEREF(__pyx_tuple_);
__pyx_tuple__3 = PyTuple_Pack(1, __pyx_kp_s__2); if (unlikely(!__pyx_tuple__3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_tuple__3);
__Pyx_GIVEREF(__pyx_tuple__3);
__pyx_tuple__5 = PyTuple_Pack(1, __pyx_kp_s__4); if (unlikely(!__pyx_tuple__5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_tuple__5);
__Pyx_GIVEREF(__pyx_tuple__5);
__pyx_tuple__6 = PyTuple_Pack(1, __pyx_kp_s_No_matching_signature_found); if (unlikely(!__pyx_tuple__6)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_tuple__6);
__Pyx_GIVEREF(__pyx_tuple__6);
__pyx_tuple__7 = PyTuple_Pack(1, __pyx_kp_s_Function_call_with_ambiguous_arg); if (unlikely(!__pyx_tuple__7)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_tuple__7);
__Pyx_GIVEREF(__pyx_tuple__7);
/* "sklearn/metrics/pairwise_fast.pyx":53
*
*
* def _sparse_manhattan(floating1d X_data, int[:] X_indices, int[:] X_indptr, # <<<<<<<<<<<<<<
* floating1d Y_data, int[:] Y_indices, int[:] Y_indptr,
* np.npy_intp n_features, double[:, ::1] D):
*/
__pyx_tuple__8 = PyTuple_Pack(2, __pyx_n_s_i, __pyx_n_s_u); if (unlikely(!__pyx_tuple__8)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_tuple__8);
__Pyx_GIVEREF(__pyx_tuple__8);
__pyx_tuple__9 = PyTuple_Pack(1, __pyx_kp_s__2); if (unlikely(!__pyx_tuple__9)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_tuple__9);
__Pyx_GIVEREF(__pyx_tuple__9);
__pyx_tuple__10 = PyTuple_Pack(1, __pyx_kp_s__4); if (unlikely(!__pyx_tuple__10)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_tuple__10);
__Pyx_GIVEREF(__pyx_tuple__10);
__pyx_tuple__11 = PyTuple_Pack(1, __pyx_kp_s_No_matching_signature_found); if (unlikely(!__pyx_tuple__11)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_tuple__11);
__Pyx_GIVEREF(__pyx_tuple__11);
__pyx_tuple__12 = PyTuple_Pack(1, __pyx_kp_s_Function_call_with_ambiguous_arg); if (unlikely(!__pyx_tuple__12)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_tuple__12);
__Pyx_GIVEREF(__pyx_tuple__12);
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":215
* if ((flags & pybuf.PyBUF_C_CONTIGUOUS == pybuf.PyBUF_C_CONTIGUOUS)
* and not PyArray_CHKFLAGS(self, NPY_C_CONTIGUOUS)):
* raise ValueError(u"ndarray is not C contiguous") # <<<<<<<<<<<<<<
*
* if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS)
*/
__pyx_tuple__13 = PyTuple_Pack(1, __pyx_kp_u_ndarray_is_not_C_contiguous); if (unlikely(!__pyx_tuple__13)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 215; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_tuple__13);
__Pyx_GIVEREF(__pyx_tuple__13);
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":219
* if ((flags & pybuf.PyBUF_F_CONTIGUOUS == pybuf.PyBUF_F_CONTIGUOUS)
* and not PyArray_CHKFLAGS(self, NPY_F_CONTIGUOUS)):
* raise ValueError(u"ndarray is not Fortran contiguous") # <<<<<<<<<<<<<<
*
* info.buf = PyArray_DATA(self)
*/
__pyx_tuple__14 = PyTuple_Pack(1, __pyx_kp_u_ndarray_is_not_Fortran_contiguou); if (unlikely(!__pyx_tuple__14)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 219; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_tuple__14);
__Pyx_GIVEREF(__pyx_tuple__14);
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":257
* if ((descr.byteorder == c'>' and little_endian) or
* (descr.byteorder == c'<' and not little_endian)):
* raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<<
* if t == NPY_BYTE: f = "b"
* elif t == NPY_UBYTE: f = "B"
*/
__pyx_tuple__15 = PyTuple_Pack(1, __pyx_kp_u_Non_native_byte_order_not_suppor); if (unlikely(!__pyx_tuple__15)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 257; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_tuple__15);
__Pyx_GIVEREF(__pyx_tuple__15);
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":799
*
* if (end - f) - <int>(new_offset - offset[0]) < 15:
* raise RuntimeError(u"Format string allocated too short, see comment in numpy.pxd") # <<<<<<<<<<<<<<
*
* if ((child.byteorder == c'>' and little_endian) or
*/
__pyx_tuple__16 = PyTuple_Pack(1, __pyx_kp_u_Format_string_allocated_too_shor); if (unlikely(!__pyx_tuple__16)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 799; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_tuple__16);
__Pyx_GIVEREF(__pyx_tuple__16);
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":803
* if ((child.byteorder == c'>' and little_endian) or
* (child.byteorder == c'<' and not little_endian)):
* raise ValueError(u"Non-native byte order not supported") # <<<<<<<<<<<<<<
* # One could encode it in the format string and have Cython
* # complain instead, BUT: < and > in format strings also imply
*/
__pyx_tuple__17 = PyTuple_Pack(1, __pyx_kp_u_Non_native_byte_order_not_suppor); if (unlikely(!__pyx_tuple__17)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 803; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_tuple__17);
__Pyx_GIVEREF(__pyx_tuple__17);
/* "/usr/local/lib/python2.7/dist-packages/Cython/Includes/numpy/__init__.pxd":823
* t = child.type_num
* if end - f < 5:
* raise RuntimeError(u"Format string allocated too short.") # <<<<<<<<<<<<<<
*
* # Until ticket #99 is fixed, use integers to avoid warnings
*/
__pyx_tuple__18 = PyTuple_Pack(1, __pyx_kp_u_Format_string_allocated_too_shor_2); if (unlikely(!__pyx_tuple__18)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 823; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_tuple__18);
__Pyx_GIVEREF(__pyx_tuple__18);
/* "View.MemoryView":124
*
* if not self.ndim:
* raise ValueError("Empty shape tuple for cython.array") # <<<<<<<<<<<<<<
*
* if self.itemsize <= 0:
*/
__pyx_tuple__19 = PyTuple_Pack(1, __pyx_kp_s_Empty_shape_tuple_for_cython_arr); if (unlikely(!__pyx_tuple__19)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 124; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_tuple__19);
__Pyx_GIVEREF(__pyx_tuple__19);
/* "View.MemoryView":127
*
* if self.itemsize <= 0:
* raise ValueError("itemsize <= 0 for cython.array") # <<<<<<<<<<<<<<
*
* encode = getattr(format, 'encode', None)
*/
__pyx_tuple__20 = PyTuple_Pack(1, __pyx_kp_s_itemsize_0_for_cython_array); if (unlikely(!__pyx_tuple__20)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 127; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_tuple__20);
__Pyx_GIVEREF(__pyx_tuple__20);
/* "View.MemoryView":131
* encode = getattr(format, 'encode', None)
* if encode:
* format = encode('ASCII') # <<<<<<<<<<<<<<
* self._format = format
* self.format = self._format
*/
__pyx_tuple__21 = PyTuple_Pack(1, __pyx_n_s_ASCII); if (unlikely(!__pyx_tuple__21)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 131; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_tuple__21);
__Pyx_GIVEREF(__pyx_tuple__21);
/* "View.MemoryView":141
* free(self._shape)
* free(self._strides)
* raise MemoryError("unable to allocate shape or strides.") # <<<<<<<<<<<<<<
*
*
*/
__pyx_tuple__22 = PyTuple_Pack(1, __pyx_kp_s_unable_to_allocate_shape_or_stri); if (unlikely(!__pyx_tuple__22)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 141; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_tuple__22);
__Pyx_GIVEREF(__pyx_tuple__22);
/* "View.MemoryView":166
* decode = getattr(mode, 'decode', None)
* if decode:
* mode = decode('ASCII') # <<<<<<<<<<<<<<
* self.mode = mode
*
*/
__pyx_tuple__23 = PyTuple_Pack(1, __pyx_n_s_ASCII); if (unlikely(!__pyx_tuple__23)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 166; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_tuple__23);
__Pyx_GIVEREF(__pyx_tuple__23);
/* "View.MemoryView":174
* self.data = <char *>malloc(self.len)
* if not self.data:
* raise MemoryError("unable to allocate array data.") # <<<<<<<<<<<<<<
*
* if self.dtype_is_object:
*/
__pyx_tuple__24 = PyTuple_Pack(1, __pyx_kp_s_unable_to_allocate_array_data); if (unlikely(!__pyx_tuple__24)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 174; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_tuple__24);
__Pyx_GIVEREF(__pyx_tuple__24);
/* "View.MemoryView":190
* bufmode = PyBUF_F_CONTIGUOUS | PyBUF_ANY_CONTIGUOUS
* if not (flags & bufmode):
* raise ValueError("Can only create a buffer that is contiguous in memory.") # <<<<<<<<<<<<<<
* info.buf = self.data
* info.len = self.len
*/
__pyx_tuple__25 = PyTuple_Pack(1, __pyx_kp_s_Can_only_create_a_buffer_that_is); if (unlikely(!__pyx_tuple__25)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 190; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_tuple__25);
__Pyx_GIVEREF(__pyx_tuple__25);
/* "View.MemoryView":453
* result = struct.unpack(self.view.format, bytesitem)
* except struct.error:
* raise ValueError("Unable to convert item to object") # <<<<<<<<<<<<<<
* else:
* if len(self.view.format) == 1:
*/
__pyx_tuple__26 = PyTuple_Pack(1, __pyx_kp_s_Unable_to_convert_item_to_object); if (unlikely(!__pyx_tuple__26)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 453; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_tuple__26);
__Pyx_GIVEREF(__pyx_tuple__26);
/* "View.MemoryView":529
* if self.view.strides == NULL:
*
* raise ValueError("Buffer view does not expose strides") # <<<<<<<<<<<<<<
*
* return tuple([self.view.strides[i] for i in xrange(self.view.ndim)])
*/
__pyx_tuple__27 = PyTuple_Pack(1, __pyx_kp_s_Buffer_view_does_not_expose_stri); if (unlikely(!__pyx_tuple__27)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 529; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_tuple__27);
__Pyx_GIVEREF(__pyx_tuple__27);
/* "View.MemoryView":646
* if item is Ellipsis:
* if not seen_ellipsis:
* result.extend([slice(None)] * (ndim - len(tup) + 1)) # <<<<<<<<<<<<<<
* seen_ellipsis = True
* else:
*/
__pyx_tuple__28 = PyTuple_Pack(1, Py_None); if (unlikely(!__pyx_tuple__28)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 646; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_tuple__28);
__Pyx_GIVEREF(__pyx_tuple__28);
/* "View.MemoryView":649
* seen_ellipsis = True
* else:
* result.append(slice(None)) # <<<<<<<<<<<<<<
* have_slices = True
* else:
*/
__pyx_tuple__29 = PyTuple_Pack(1, Py_None); if (unlikely(!__pyx_tuple__29)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 649; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_tuple__29);
__Pyx_GIVEREF(__pyx_tuple__29);
/* "View.MemoryView":660
* nslices = ndim - len(result)
* if nslices:
* result.extend([slice(None)] * nslices) # <<<<<<<<<<<<<<
*
* return have_slices or nslices, tuple(result)
*/
__pyx_tuple__30 = PyTuple_Pack(1, Py_None); if (unlikely(!__pyx_tuple__30)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 660; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_tuple__30);
__Pyx_GIVEREF(__pyx_tuple__30);
/* "View.MemoryView":668
* for i in range(ndim):
* if suboffsets[i] >= 0:
* raise ValueError("Indirect dimensions not supported") # <<<<<<<<<<<<<<
*
*
*/
__pyx_tuple__31 = PyTuple_Pack(1, __pyx_kp_s_Indirect_dimensions_not_supporte); if (unlikely(!__pyx_tuple__31)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 668; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_tuple__31);
__Pyx_GIVEREF(__pyx_tuple__31);
/* "sklearn/metrics/pairwise_fast.pyx":32
*
*
* def _chi2_kernel_fast(floating_array_2d_t X, # <<<<<<<<<<<<<<
* floating_array_2d_t Y,
* floating_array_2d_t result):
*/
__pyx_tuple__32 = PyTuple_Pack(12, __pyx_n_s_X, __pyx_n_s_Y, __pyx_n_s_result, __pyx_n_s_i, __pyx_n_s_j, __pyx_n_s_k, __pyx_n_s_n_samples_X, __pyx_n_s_n_samples_Y, __pyx_n_s_n_features, __pyx_n_s_res, __pyx_n_s_nom, __pyx_n_s_denom); if (unlikely(!__pyx_tuple__32)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_tuple__32);
__Pyx_GIVEREF(__pyx_tuple__32);
__pyx_codeobj__33 = (PyObject*)__Pyx_PyCode_New(3, 0, 12, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__32, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_home_larsb_src_scikit_learn_skl, __pyx_n_s_chi2_kernel_fast, 32, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__33)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
/* "sklearn/metrics/pairwise_fast.pyx":53
*
*
* def _sparse_manhattan(floating1d X_data, int[:] X_indices, int[:] X_indptr, # <<<<<<<<<<<<<<
* floating1d Y_data, int[:] Y_indices, int[:] Y_indptr,
* np.npy_intp n_features, double[:, ::1] D):
*/
__pyx_tuple__34 = PyTuple_Pack(12, __pyx_n_s_X_data, __pyx_n_s_X_indices, __pyx_n_s_X_indptr, __pyx_n_s_Y_data, __pyx_n_s_Y_indices, __pyx_n_s_Y_indptr, __pyx_n_s_n_features, __pyx_n_s_D, __pyx_n_s_row, __pyx_n_s_ix, __pyx_n_s_iy, __pyx_n_s_j); if (unlikely(!__pyx_tuple__34)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_tuple__34);
__Pyx_GIVEREF(__pyx_tuple__34);
__pyx_codeobj__35 = (PyObject*)__Pyx_PyCode_New(8, 0, 12, 0, 0, __pyx_empty_bytes, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_tuple__34, __pyx_empty_tuple, __pyx_empty_tuple, __pyx_kp_s_home_larsb_src_scikit_learn_skl, __pyx_n_s_sparse_manhattan, 53, __pyx_empty_bytes); if (unlikely(!__pyx_codeobj__35)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
/* "View.MemoryView":282
* return self.name
*
* cdef generic = Enum("<strided and direct or indirect>") # <<<<<<<<<<<<<<
* cdef strided = Enum("<strided and direct>") # default
* cdef indirect = Enum("<strided and indirect>")
*/
__pyx_tuple__36 = PyTuple_Pack(1, __pyx_kp_s_strided_and_direct_or_indirect); if (unlikely(!__pyx_tuple__36)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 282; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_tuple__36);
__Pyx_GIVEREF(__pyx_tuple__36);
/* "View.MemoryView":283
*
* cdef generic = Enum("<strided and direct or indirect>")
* cdef strided = Enum("<strided and direct>") # default # <<<<<<<<<<<<<<
* cdef indirect = Enum("<strided and indirect>")
*
*/
__pyx_tuple__37 = PyTuple_Pack(1, __pyx_kp_s_strided_and_direct); if (unlikely(!__pyx_tuple__37)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 283; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_tuple__37);
__Pyx_GIVEREF(__pyx_tuple__37);
/* "View.MemoryView":284
* cdef generic = Enum("<strided and direct or indirect>")
* cdef strided = Enum("<strided and direct>") # default
* cdef indirect = Enum("<strided and indirect>") # <<<<<<<<<<<<<<
*
*
*/
__pyx_tuple__38 = PyTuple_Pack(1, __pyx_kp_s_strided_and_indirect); if (unlikely(!__pyx_tuple__38)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 284; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_tuple__38);
__Pyx_GIVEREF(__pyx_tuple__38);
/* "View.MemoryView":287
*
*
* cdef contiguous = Enum("<contiguous and direct>") # <<<<<<<<<<<<<<
* cdef indirect_contiguous = Enum("<contiguous and indirect>")
*
*/
__pyx_tuple__39 = PyTuple_Pack(1, __pyx_kp_s_contiguous_and_direct); if (unlikely(!__pyx_tuple__39)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 287; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_tuple__39);
__Pyx_GIVEREF(__pyx_tuple__39);
/* "View.MemoryView":288
*
* cdef contiguous = Enum("<contiguous and direct>")
* cdef indirect_contiguous = Enum("<contiguous and indirect>") # <<<<<<<<<<<<<<
*
*
*/
__pyx_tuple__40 = PyTuple_Pack(1, __pyx_kp_s_contiguous_and_indirect); if (unlikely(!__pyx_tuple__40)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_tuple__40);
__Pyx_GIVEREF(__pyx_tuple__40);
__Pyx_RefNannyFinishContext();
return 0;
__pyx_L1_error:;
__Pyx_RefNannyFinishContext();
return -1;
}
static int __Pyx_InitGlobals(void) {
if (__Pyx_InitStrings(__pyx_string_tab) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;};
__pyx_int_0 = PyInt_FromLong(0); if (unlikely(!__pyx_int_0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_int_1 = PyInt_FromLong(1); if (unlikely(!__pyx_int_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_int_2 = PyInt_FromLong(2); if (unlikely(!__pyx_int_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_int_105 = PyInt_FromLong(105); if (unlikely(!__pyx_int_105)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_int_neg_1 = PyInt_FromLong(-1); if (unlikely(!__pyx_int_neg_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
return 0;
__pyx_L1_error:;
return -1;
}
#if PY_MAJOR_VERSION < 3
PyMODINIT_FUNC initpairwise_fast(void); /*proto*/
PyMODINIT_FUNC initpairwise_fast(void)
#else
PyMODINIT_FUNC PyInit_pairwise_fast(void); /*proto*/
PyMODINIT_FUNC PyInit_pairwise_fast(void)
#endif
{
PyObject *__pyx_t_1 = NULL;
PyObject *__pyx_t_2 = NULL;
PyObject *__pyx_t_3 = NULL;
PyObject *__pyx_t_4 = NULL;
PyObject *__pyx_t_5 = NULL;
int __pyx_lineno = 0;
const char *__pyx_filename = NULL;
int __pyx_clineno = 0;
__Pyx_RefNannyDeclarations
#if CYTHON_REFNANNY
__Pyx_RefNanny = __Pyx_RefNannyImportAPI("refnanny");
if (!__Pyx_RefNanny) {
PyErr_Clear();
__Pyx_RefNanny = __Pyx_RefNannyImportAPI("Cython.Runtime.refnanny");
if (!__Pyx_RefNanny)
Py_FatalError("failed to import 'refnanny' module");
}
#endif
__Pyx_RefNannySetupContext("PyMODINIT_FUNC PyInit_pairwise_fast(void)", 0);
if ( __Pyx_check_binary_version() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_empty_tuple = PyTuple_New(0); if (unlikely(!__pyx_empty_tuple)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_empty_bytes = PyBytes_FromStringAndSize("", 0); if (unlikely(!__pyx_empty_bytes)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
#ifdef __Pyx_CyFunction_USED
if (__Pyx_CyFunction_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
#endif
#ifdef __Pyx_FusedFunction_USED
if (__pyx_FusedFunction_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
#endif
#ifdef __Pyx_Generator_USED
if (__pyx_Generator_init() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
#endif
/*--- Library function declarations ---*/
/*--- Threads initialization code ---*/
#if defined(__PYX_FORCE_INIT_THREADS) && __PYX_FORCE_INIT_THREADS
#ifdef WITH_THREAD /* Python build with threading support? */
PyEval_InitThreads();
#endif
#endif
/*--- Module creation code ---*/
#if PY_MAJOR_VERSION < 3
__pyx_m = Py_InitModule4(__Pyx_NAMESTR("pairwise_fast"), __pyx_methods, 0, 0, PYTHON_API_VERSION); Py_XINCREF(__pyx_m);
#else
__pyx_m = PyModule_Create(&__pyx_moduledef);
#endif
if (unlikely(!__pyx_m)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_d = PyModule_GetDict(__pyx_m); if (unlikely(!__pyx_d)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
Py_INCREF(__pyx_d);
__pyx_b = PyImport_AddModule(__Pyx_NAMESTR(__Pyx_BUILTIN_MODULE_NAME)); if (unlikely(!__pyx_b)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
#if CYTHON_COMPILING_IN_PYPY
Py_INCREF(__pyx_b);
#endif
if (__Pyx_SetAttrString(__pyx_m, "__builtins__", __pyx_b) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;};
/*--- Initialize various global constants etc. ---*/
if (unlikely(__Pyx_InitGlobals() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
#if PY_MAJOR_VERSION < 3 && (__PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT)
if (__Pyx_init_sys_getdefaultencoding_params() < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
#endif
if (__pyx_module_is_main_sklearn__metrics__pairwise_fast) {
if (__Pyx_SetAttrString(__pyx_m, "__name__", __pyx_n_s_main) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;};
}
#if PY_MAJOR_VERSION >= 3
{
PyObject *modules = PyImport_GetModuleDict(); if (unlikely(!modules)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
if (!PyDict_GetItemString(modules, "sklearn.metrics.pairwise_fast")) {
if (unlikely(PyDict_SetItemString(modules, "sklearn.metrics.pairwise_fast", __pyx_m) < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
}
}
#endif
/*--- Builtin init code ---*/
if (unlikely(__Pyx_InitCachedBuiltins() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
/*--- Constants init code ---*/
if (unlikely(__Pyx_InitCachedConstants() < 0)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
/*--- Global init code ---*/
generic = Py_None; Py_INCREF(Py_None);
strided = Py_None; Py_INCREF(Py_None);
indirect = Py_None; Py_INCREF(Py_None);
contiguous = Py_None; Py_INCREF(Py_None);
indirect_contiguous = Py_None; Py_INCREF(Py_None);
/*--- Variable export code ---*/
/*--- Function export code ---*/
/*--- Type init code ---*/
if (PyType_Ready(&__pyx_type___pyx_array) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 96; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_type___pyx_array.tp_print = 0;
__pyx_array_type = &__pyx_type___pyx_array;
if (PyType_Ready(&__pyx_type___pyx_MemviewEnum) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 275; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_type___pyx_MemviewEnum.tp_print = 0;
__pyx_MemviewEnum_type = &__pyx_type___pyx_MemviewEnum;
__pyx_vtabptr_memoryview = &__pyx_vtable_memoryview;
__pyx_vtable_memoryview.get_item_pointer = (char *(*)(struct __pyx_memoryview_obj *, PyObject *))__pyx_memoryview_get_item_pointer;
__pyx_vtable_memoryview.is_slice = (PyObject *(*)(struct __pyx_memoryview_obj *, PyObject *))__pyx_memoryview_is_slice;
__pyx_vtable_memoryview.setitem_slice_assignment = (PyObject *(*)(struct __pyx_memoryview_obj *, PyObject *, PyObject *))__pyx_memoryview_setitem_slice_assignment;
__pyx_vtable_memoryview.setitem_slice_assign_scalar = (PyObject *(*)(struct __pyx_memoryview_obj *, struct __pyx_memoryview_obj *, PyObject *))__pyx_memoryview_setitem_slice_assign_scalar;
__pyx_vtable_memoryview.setitem_indexed = (PyObject *(*)(struct __pyx_memoryview_obj *, PyObject *, PyObject *))__pyx_memoryview_setitem_indexed;
__pyx_vtable_memoryview.convert_item_to_object = (PyObject *(*)(struct __pyx_memoryview_obj *, char *))__pyx_memoryview_convert_item_to_object;
__pyx_vtable_memoryview.assign_item_from_object = (PyObject *(*)(struct __pyx_memoryview_obj *, char *, PyObject *))__pyx_memoryview_assign_item_from_object;
if (PyType_Ready(&__pyx_type___pyx_memoryview) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 308; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_type___pyx_memoryview.tp_print = 0;
if (__Pyx_SetVtable(__pyx_type___pyx_memoryview.tp_dict, __pyx_vtabptr_memoryview) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 308; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_memoryview_type = &__pyx_type___pyx_memoryview;
__pyx_vtabptr__memoryviewslice = &__pyx_vtable__memoryviewslice;
__pyx_vtable__memoryviewslice.__pyx_base = *__pyx_vtabptr_memoryview;
__pyx_vtable__memoryviewslice.__pyx_base.convert_item_to_object = (PyObject *(*)(struct __pyx_memoryview_obj *, char *))__pyx_memoryviewslice_convert_item_to_object;
__pyx_vtable__memoryviewslice.__pyx_base.assign_item_from_object = (PyObject *(*)(struct __pyx_memoryview_obj *, char *, PyObject *))__pyx_memoryviewslice_assign_item_from_object;
__pyx_type___pyx_memoryviewslice.tp_base = __pyx_memoryview_type;
if (PyType_Ready(&__pyx_type___pyx_memoryviewslice) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 930; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_type___pyx_memoryviewslice.tp_print = 0;
if (__Pyx_SetVtable(__pyx_type___pyx_memoryviewslice.tp_dict, __pyx_vtabptr__memoryviewslice) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 930; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_memoryviewslice_type = &__pyx_type___pyx_memoryviewslice;
/*--- Type import code ---*/
__pyx_ptype_7cpython_4type_type = __Pyx_ImportType(__Pyx_BUILTIN_MODULE_NAME, "type",
#if CYTHON_COMPILING_IN_PYPY
sizeof(PyTypeObject),
#else
sizeof(PyHeapTypeObject),
#endif
0); if (unlikely(!__pyx_ptype_7cpython_4type_type)) {__pyx_filename = __pyx_f[3]; __pyx_lineno = 9; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_ptype_5numpy_dtype = __Pyx_ImportType("numpy", "dtype", sizeof(PyArray_Descr), 0); if (unlikely(!__pyx_ptype_5numpy_dtype)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 155; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_ptype_5numpy_flatiter = __Pyx_ImportType("numpy", "flatiter", sizeof(PyArrayIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_flatiter)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 165; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_ptype_5numpy_broadcast = __Pyx_ImportType("numpy", "broadcast", sizeof(PyArrayMultiIterObject), 0); if (unlikely(!__pyx_ptype_5numpy_broadcast)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 169; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_ptype_5numpy_ndarray = __Pyx_ImportType("numpy", "ndarray", sizeof(PyArrayObject), 0); if (unlikely(!__pyx_ptype_5numpy_ndarray)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 178; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__pyx_ptype_5numpy_ufunc = __Pyx_ImportType("numpy", "ufunc", sizeof(PyUFuncObject), 0); if (unlikely(!__pyx_ptype_5numpy_ufunc)) {__pyx_filename = __pyx_f[1]; __pyx_lineno = 861; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
/*--- Variable import code ---*/
/*--- Function import code ---*/
/*--- Execution code ---*/
/* "sklearn/metrics/pairwise_fast.pyx":11
*
* from libc.string cimport memset
* import numpy as np # <<<<<<<<<<<<<<
* cimport numpy as np
*
*/
__pyx_t_1 = __Pyx_Import(__pyx_n_s_numpy, 0, -1); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 11; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
if (PyDict_SetItem(__pyx_d, __pyx_n_s_np, __pyx_t_1) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 11; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_1); __pyx_t_1 = 0;
/* "sklearn/metrics/pairwise_fast.pyx":29
*
*
* np.import_array() # <<<<<<<<<<<<<<
*
*
*/
import_array();
/* "sklearn/metrics/pairwise_fast.pyx":32
*
*
* def _chi2_kernel_fast(floating_array_2d_t X, # <<<<<<<<<<<<<<
* floating_array_2d_t Y,
* floating_array_2d_t result):
*/
__pyx_t_1 = PyDict_New(); if (unlikely(!__pyx_t_1)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_1);
__pyx_t_2 = __pyx_FusedFunction_NewEx(&__pyx_fuse_0__pyx_mdef_7sklearn_7metrics_13pairwise_fast_5_chi2_kernel_fast, 0, __pyx_n_s_chi2_kernel_fast, NULL, __pyx_n_s_sklearn_metrics_pairwise_fast, PyModule_GetDict(__pyx_m), ((PyObject *)__pyx_codeobj__33)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_2);
__Pyx_CyFunction_SetDefaultsTuple(__pyx_t_2, __pyx_empty_tuple);
if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_float_array_2d_t, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0;
__pyx_t_2 = __pyx_FusedFunction_NewEx(&__pyx_fuse_1__pyx_mdef_7sklearn_7metrics_13pairwise_fast_7_chi2_kernel_fast, 0, __pyx_n_s_chi2_kernel_fast, NULL, __pyx_n_s_sklearn_metrics_pairwise_fast, PyModule_GetDict(__pyx_m), ((PyObject *)__pyx_codeobj__33)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_2);
__Pyx_CyFunction_SetDefaultsTuple(__pyx_t_2, __pyx_empty_tuple);
if (PyDict_SetItem(__pyx_t_1, __pyx_n_s_double_array_2d_t, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0;
__pyx_t_2 = __pyx_FusedFunction_NewEx(&__pyx_mdef_7sklearn_7metrics_13pairwise_fast_1_chi2_kernel_fast, 0, __pyx_n_s_chi2_kernel_fast, NULL, __pyx_n_s_sklearn_metrics_pairwise_fast, PyModule_GetDict(__pyx_m), ((PyObject *)__pyx_codeobj__33)); if (unlikely(!__pyx_t_2)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_2);
__Pyx_CyFunction_SetDefaultsTuple(__pyx_t_2, __pyx_empty_tuple);
((__pyx_FusedFunctionObject *) __pyx_t_2)->__signatures__ = __pyx_t_1;
__Pyx_GIVEREF(__pyx_t_1);
if (PyDict_SetItem(__pyx_d, __pyx_n_s_chi2_kernel_fast, __pyx_t_2) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 32; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_2); __pyx_t_2 = 0;
/* "sklearn/metrics/pairwise_fast.pyx":53
*
*
* def _sparse_manhattan(floating1d X_data, int[:] X_indices, int[:] X_indptr, # <<<<<<<<<<<<<<
* floating1d Y_data, int[:] Y_indices, int[:] Y_indptr,
* np.npy_intp n_features, double[:, ::1] D):
*/
__pyx_t_3 = PyDict_New(); if (unlikely(!__pyx_t_3)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_3);
__pyx_t_4 = __pyx_FusedFunction_NewEx(&__pyx_fuse_0__pyx_mdef_7sklearn_7metrics_13pairwise_fast_11_sparse_manhattan, 0, __pyx_n_s_sparse_manhattan, NULL, __pyx_n_s_sklearn_metrics_pairwise_fast, PyModule_GetDict(__pyx_m), ((PyObject *)__pyx_codeobj__35)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_4);
__Pyx_CyFunction_SetDefaultsTuple(__pyx_t_4, __pyx_empty_tuple);
if (PyDict_SetItem(__pyx_t_3, __pyx_kp_s_float_1, __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
__pyx_t_4 = __pyx_FusedFunction_NewEx(&__pyx_fuse_1__pyx_mdef_7sklearn_7metrics_13pairwise_fast_13_sparse_manhattan, 0, __pyx_n_s_sparse_manhattan, NULL, __pyx_n_s_sklearn_metrics_pairwise_fast, PyModule_GetDict(__pyx_m), ((PyObject *)__pyx_codeobj__35)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_4);
__Pyx_CyFunction_SetDefaultsTuple(__pyx_t_4, __pyx_empty_tuple);
if (PyDict_SetItem(__pyx_t_3, __pyx_kp_s_double_1, __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
__pyx_t_4 = __pyx_FusedFunction_NewEx(&__pyx_mdef_7sklearn_7metrics_13pairwise_fast_3_sparse_manhattan, 0, __pyx_n_s_sparse_manhattan, NULL, __pyx_n_s_sklearn_metrics_pairwise_fast, PyModule_GetDict(__pyx_m), ((PyObject *)__pyx_codeobj__35)); if (unlikely(!__pyx_t_4)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_4);
__Pyx_CyFunction_SetDefaultsTuple(__pyx_t_4, __pyx_empty_tuple);
((__pyx_FusedFunctionObject *) __pyx_t_4)->__signatures__ = __pyx_t_3;
__Pyx_GIVEREF(__pyx_t_3);
if (PyDict_SetItem(__pyx_d, __pyx_n_s_sparse_manhattan, __pyx_t_4) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 53; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_4); __pyx_t_4 = 0;
/* "sklearn/metrics/pairwise_fast.pyx":1
* #cython: boundscheck=False # <<<<<<<<<<<<<<
* #cython: cdivision=True
* #cython: wraparound=False
*/
__pyx_t_5 = PyDict_New(); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_5);
if (PyDict_SetItem(__pyx_t_5, __pyx_kp_u_sparse_manhattan_line_53, __pyx_kp_u_Pairwise_L1_distances_for_CSR_ma) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
if (PyDict_SetItem(__pyx_d, __pyx_n_s_test, __pyx_t_5) < 0) {__pyx_filename = __pyx_f[0]; __pyx_lineno = 1; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0;
/* "View.MemoryView":207
* info.obj = self
*
* __pyx_getbuffer = capsule(<void *> &__pyx_array_getbuffer, "getbuffer(obj, view, flags)") # <<<<<<<<<<<<<<
*
* def __dealloc__(array self):
*/
__pyx_t_5 = __pyx_capsule_create(((void *)(&__pyx_array_getbuffer)), __pyx_k_getbuffer_obj_view_flags); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 207; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_5);
if (PyDict_SetItem(__pyx_array_type->tp_dict, __pyx_n_s_pyx_getbuffer, __pyx_t_5) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 207; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0;
PyType_Modified(__pyx_array_type);
/* "View.MemoryView":282
* return self.name
*
* cdef generic = Enum("<strided and direct or indirect>") # <<<<<<<<<<<<<<
* cdef strided = Enum("<strided and direct>") # default
* cdef indirect = Enum("<strided and indirect>")
*/
__pyx_t_5 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_MemviewEnum_type)), __pyx_tuple__36, NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 282; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_5);
__Pyx_XGOTREF(generic);
__Pyx_DECREF_SET(generic, __pyx_t_5);
__Pyx_GIVEREF(__pyx_t_5);
__pyx_t_5 = 0;
/* "View.MemoryView":283
*
* cdef generic = Enum("<strided and direct or indirect>")
* cdef strided = Enum("<strided and direct>") # default # <<<<<<<<<<<<<<
* cdef indirect = Enum("<strided and indirect>")
*
*/
__pyx_t_5 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_MemviewEnum_type)), __pyx_tuple__37, NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 283; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_5);
__Pyx_XGOTREF(strided);
__Pyx_DECREF_SET(strided, __pyx_t_5);
__Pyx_GIVEREF(__pyx_t_5);
__pyx_t_5 = 0;
/* "View.MemoryView":284
* cdef generic = Enum("<strided and direct or indirect>")
* cdef strided = Enum("<strided and direct>") # default
* cdef indirect = Enum("<strided and indirect>") # <<<<<<<<<<<<<<
*
*
*/
__pyx_t_5 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_MemviewEnum_type)), __pyx_tuple__38, NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 284; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_5);
__Pyx_XGOTREF(indirect);
__Pyx_DECREF_SET(indirect, __pyx_t_5);
__Pyx_GIVEREF(__pyx_t_5);
__pyx_t_5 = 0;
/* "View.MemoryView":287
*
*
* cdef contiguous = Enum("<contiguous and direct>") # <<<<<<<<<<<<<<
* cdef indirect_contiguous = Enum("<contiguous and indirect>")
*
*/
__pyx_t_5 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_MemviewEnum_type)), __pyx_tuple__39, NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 287; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_5);
__Pyx_XGOTREF(contiguous);
__Pyx_DECREF_SET(contiguous, __pyx_t_5);
__Pyx_GIVEREF(__pyx_t_5);
__pyx_t_5 = 0;
/* "View.MemoryView":288
*
* cdef contiguous = Enum("<contiguous and direct>")
* cdef indirect_contiguous = Enum("<contiguous and indirect>") # <<<<<<<<<<<<<<
*
*
*/
__pyx_t_5 = __Pyx_PyObject_Call(((PyObject *)((PyObject *)__pyx_MemviewEnum_type)), __pyx_tuple__40, NULL); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 288; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_5);
__Pyx_XGOTREF(indirect_contiguous);
__Pyx_DECREF_SET(indirect_contiguous, __pyx_t_5);
__Pyx_GIVEREF(__pyx_t_5);
__pyx_t_5 = 0;
/* "View.MemoryView":504
* info.obj = self
*
* __pyx_getbuffer = capsule(<void *> &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") # <<<<<<<<<<<<<<
*
*
*/
__pyx_t_5 = __pyx_capsule_create(((void *)(&__pyx_memoryview_getbuffer)), __pyx_k_getbuffer_obj_view_flags); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 504; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_5);
if (PyDict_SetItem(__pyx_memoryview_type->tp_dict, __pyx_n_s_pyx_getbuffer, __pyx_t_5) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 504; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0;
PyType_Modified(__pyx_memoryview_type);
/* "View.MemoryView":961
* return self.from_object
*
* __pyx_getbuffer = capsule(<void *> &__pyx_memoryview_getbuffer, "getbuffer(obj, view, flags)") # <<<<<<<<<<<<<<
*
*
*/
__pyx_t_5 = __pyx_capsule_create(((void *)(&__pyx_memoryview_getbuffer)), __pyx_k_getbuffer_obj_view_flags); if (unlikely(!__pyx_t_5)) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 961; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_GOTREF(__pyx_t_5);
if (PyDict_SetItem(__pyx_memoryviewslice_type->tp_dict, __pyx_n_s_pyx_getbuffer, __pyx_t_5) < 0) {__pyx_filename = __pyx_f[2]; __pyx_lineno = 961; __pyx_clineno = __LINE__; goto __pyx_L1_error;}
__Pyx_DECREF(__pyx_t_5); __pyx_t_5 = 0;
PyType_Modified(__pyx_memoryviewslice_type);
/* "__pyxutil":2
*
* cdef extern from *: # <<<<<<<<<<<<<<
* void __pyx_PyErr_Clear "PyErr_Clear" ()
* __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dsds_float(object)
*/
goto __pyx_L0;
__pyx_L1_error:;
__Pyx_XDECREF(__pyx_t_1);
__Pyx_XDECREF(__pyx_t_2);
__Pyx_XDECREF(__pyx_t_3);
__Pyx_XDECREF(__pyx_t_4);
__Pyx_XDECREF(__pyx_t_5);
if (__pyx_m) {
__Pyx_AddTraceback("init sklearn.metrics.pairwise_fast", __pyx_clineno, __pyx_lineno, __pyx_filename);
Py_DECREF(__pyx_m); __pyx_m = 0;
} else if (!PyErr_Occurred()) {
PyErr_SetString(PyExc_ImportError, "init sklearn.metrics.pairwise_fast");
}
__pyx_L0:;
__Pyx_RefNannyFinishContext();
#if PY_MAJOR_VERSION < 3
return;
#else
return __pyx_m;
#endif
}
/* Runtime support code */
#if CYTHON_REFNANNY
static __Pyx_RefNannyAPIStruct *__Pyx_RefNannyImportAPI(const char *modname) {
PyObject *m = NULL, *p = NULL;
void *r = NULL;
m = PyImport_ImportModule((char *)modname);
if (!m) goto end;
p = PyObject_GetAttrString(m, (char *)"RefNannyAPI");
if (!p) goto end;
r = PyLong_AsVoidPtr(p);
end:
Py_XDECREF(p);
Py_XDECREF(m);
return (__Pyx_RefNannyAPIStruct *)r;
}
#endif /* CYTHON_REFNANNY */
static PyObject *__Pyx_GetBuiltinName(PyObject *name) {
PyObject* result = __Pyx_PyObject_GetAttrStr(__pyx_b, name);
if (unlikely(!result)) {
PyErr_Format(PyExc_NameError,
#if PY_MAJOR_VERSION >= 3
"name '%U' is not defined", name);
#else
"name '%.200s' is not defined", PyString_AS_STRING(name));
#endif
}
return result;
}
static void __Pyx_RaiseArgtupleInvalid(
const char* func_name,
int exact,
Py_ssize_t num_min,
Py_ssize_t num_max,
Py_ssize_t num_found)
{
Py_ssize_t num_expected;
const char *more_or_less;
if (num_found < num_min) {
num_expected = num_min;
more_or_less = "at least";
} else {
num_expected = num_max;
more_or_less = "at most";
}
if (exact) {
more_or_less = "exactly";
}
PyErr_Format(PyExc_TypeError,
"%.200s() takes %.8s %" CYTHON_FORMAT_SSIZE_T "d positional argument%.1s (%" CYTHON_FORMAT_SSIZE_T "d given)",
func_name, more_or_less, num_expected,
(num_expected == 1) ? "" : "s", num_found);
}
static void __Pyx_RaiseDoubleKeywordsError(
const char* func_name,
PyObject* kw_name)
{
PyErr_Format(PyExc_TypeError,
#if PY_MAJOR_VERSION >= 3
"%s() got multiple values for keyword argument '%U'", func_name, kw_name);
#else
"%s() got multiple values for keyword argument '%s'", func_name,
PyString_AsString(kw_name));
#endif
}
static int __Pyx_ParseOptionalKeywords(
PyObject *kwds,
PyObject **argnames[],
PyObject *kwds2,
PyObject *values[],
Py_ssize_t num_pos_args,
const char* function_name)
{
PyObject *key = 0, *value = 0;
Py_ssize_t pos = 0;
PyObject*** name;
PyObject*** first_kw_arg = argnames + num_pos_args;
while (PyDict_Next(kwds, &pos, &key, &value)) {
name = first_kw_arg;
while (*name && (**name != key)) name++;
if (*name) {
values[name-argnames] = value;
continue;
}
name = first_kw_arg;
#if PY_MAJOR_VERSION < 3
if (likely(PyString_CheckExact(key)) || likely(PyString_Check(key))) {
while (*name) {
if ((CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**name) == PyString_GET_SIZE(key))
&& _PyString_Eq(**name, key)) {
values[name-argnames] = value;
break;
}
name++;
}
if (*name) continue;
else {
PyObject*** argname = argnames;
while (argname != first_kw_arg) {
if ((**argname == key) || (
(CYTHON_COMPILING_IN_PYPY || PyString_GET_SIZE(**argname) == PyString_GET_SIZE(key))
&& _PyString_Eq(**argname, key))) {
goto arg_passed_twice;
}
argname++;
}
}
} else
#endif
if (likely(PyUnicode_Check(key))) {
while (*name) {
int cmp = (**name == key) ? 0 :
#if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3
(PyUnicode_GET_SIZE(**name) != PyUnicode_GET_SIZE(key)) ? 1 :
#endif
PyUnicode_Compare(**name, key);
if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad;
if (cmp == 0) {
values[name-argnames] = value;
break;
}
name++;
}
if (*name) continue;
else {
PyObject*** argname = argnames;
while (argname != first_kw_arg) {
int cmp = (**argname == key) ? 0 :
#if !CYTHON_COMPILING_IN_PYPY && PY_MAJOR_VERSION >= 3
(PyUnicode_GET_SIZE(**argname) != PyUnicode_GET_SIZE(key)) ? 1 :
#endif
PyUnicode_Compare(**argname, key);
if (cmp < 0 && unlikely(PyErr_Occurred())) goto bad;
if (cmp == 0) goto arg_passed_twice;
argname++;
}
}
} else
goto invalid_keyword_type;
if (kwds2) {
if (unlikely(PyDict_SetItem(kwds2, key, value))) goto bad;
} else {
goto invalid_keyword;
}
}
return 0;
arg_passed_twice:
__Pyx_RaiseDoubleKeywordsError(function_name, key);
goto bad;
invalid_keyword_type:
PyErr_Format(PyExc_TypeError,
"%.200s() keywords must be strings", function_name);
goto bad;
invalid_keyword:
PyErr_Format(PyExc_TypeError,
#if PY_MAJOR_VERSION < 3
"%.200s() got an unexpected keyword argument '%.200s'",
function_name, PyString_AsString(key));
#else
"%s() got an unexpected keyword argument '%U'",
function_name, key);
#endif
bad:
return -1;
}
static CYTHON_INLINE void __Pyx_ExceptionSave(PyObject **type, PyObject **value, PyObject **tb) {
#if CYTHON_COMPILING_IN_CPYTHON
PyThreadState *tstate = PyThreadState_GET();
*type = tstate->exc_type;
*value = tstate->exc_value;
*tb = tstate->exc_traceback;
Py_XINCREF(*type);
Py_XINCREF(*value);
Py_XINCREF(*tb);
#else
PyErr_GetExcInfo(type, value, tb);
#endif
}
static void __Pyx_ExceptionReset(PyObject *type, PyObject *value, PyObject *tb) {
#if CYTHON_COMPILING_IN_CPYTHON
PyObject *tmp_type, *tmp_value, *tmp_tb;
PyThreadState *tstate = PyThreadState_GET();
tmp_type = tstate->exc_type;
tmp_value = tstate->exc_value;
tmp_tb = tstate->exc_traceback;
tstate->exc_type = type;
tstate->exc_value = value;
tstate->exc_traceback = tb;
Py_XDECREF(tmp_type);
Py_XDECREF(tmp_value);
Py_XDECREF(tmp_tb);
#else
PyErr_SetExcInfo(type, value, tb);
#endif
}
static int __Pyx_GetException(PyObject **type, PyObject **value, PyObject **tb) {
PyObject *local_type, *local_value, *local_tb;
#if CYTHON_COMPILING_IN_CPYTHON
PyObject *tmp_type, *tmp_value, *tmp_tb;
PyThreadState *tstate = PyThreadState_GET();
local_type = tstate->curexc_type;
local_value = tstate->curexc_value;
local_tb = tstate->curexc_traceback;
tstate->curexc_type = 0;
tstate->curexc_value = 0;
tstate->curexc_traceback = 0;
#else
PyErr_Fetch(&local_type, &local_value, &local_tb);
#endif
PyErr_NormalizeException(&local_type, &local_value, &local_tb);
#if CYTHON_COMPILING_IN_CPYTHON
if (unlikely(tstate->curexc_type))
#else
if (unlikely(PyErr_Occurred()))
#endif
goto bad;
#if PY_MAJOR_VERSION >= 3
if (local_tb) {
if (unlikely(PyException_SetTraceback(local_value, local_tb) < 0))
goto bad;
}
#endif
Py_XINCREF(local_tb);
Py_XINCREF(local_type);
Py_XINCREF(local_value);
*type = local_type;
*value = local_value;
*tb = local_tb;
#if CYTHON_COMPILING_IN_CPYTHON
tmp_type = tstate->exc_type;
tmp_value = tstate->exc_value;
tmp_tb = tstate->exc_traceback;
tstate->exc_type = local_type;
tstate->exc_value = local_value;
tstate->exc_traceback = local_tb;
Py_XDECREF(tmp_type);
Py_XDECREF(tmp_value);
Py_XDECREF(tmp_tb);
#else
PyErr_SetExcInfo(local_type, local_value, local_tb);
#endif
return 0;
bad:
*type = 0;
*value = 0;
*tb = 0;
Py_XDECREF(local_type);
Py_XDECREF(local_value);
Py_XDECREF(local_tb);
return -1;
}
static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Generic(PyObject *o, PyObject* j) {
PyObject *r;
if (!j) return NULL;
r = PyObject_GetItem(o, j);
Py_DECREF(j);
return r;
}
static CYTHON_INLINE PyObject *__Pyx_GetItemInt_List_Fast(PyObject *o, Py_ssize_t i,
int wraparound, int boundscheck) {
#if CYTHON_COMPILING_IN_CPYTHON
if (wraparound & unlikely(i < 0)) i += PyList_GET_SIZE(o);
if ((!boundscheck) || likely((0 <= i) & (i < PyList_GET_SIZE(o)))) {
PyObject *r = PyList_GET_ITEM(o, i);
Py_INCREF(r);
return r;
}
return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i));
#else
return PySequence_GetItem(o, i);
#endif
}
static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Tuple_Fast(PyObject *o, Py_ssize_t i,
int wraparound, int boundscheck) {
#if CYTHON_COMPILING_IN_CPYTHON
if (wraparound & unlikely(i < 0)) i += PyTuple_GET_SIZE(o);
if ((!boundscheck) || likely((0 <= i) & (i < PyTuple_GET_SIZE(o)))) {
PyObject *r = PyTuple_GET_ITEM(o, i);
Py_INCREF(r);
return r;
}
return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i));
#else
return PySequence_GetItem(o, i);
#endif
}
static CYTHON_INLINE PyObject *__Pyx_GetItemInt_Fast(PyObject *o, Py_ssize_t i,
int is_list, int wraparound, int boundscheck) {
#if CYTHON_COMPILING_IN_CPYTHON
if (is_list || PyList_CheckExact(o)) {
Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyList_GET_SIZE(o);
if ((!boundscheck) || (likely((n >= 0) & (n < PyList_GET_SIZE(o))))) {
PyObject *r = PyList_GET_ITEM(o, n);
Py_INCREF(r);
return r;
}
}
else if (PyTuple_CheckExact(o)) {
Py_ssize_t n = ((!wraparound) | likely(i >= 0)) ? i : i + PyTuple_GET_SIZE(o);
if ((!boundscheck) || likely((n >= 0) & (n < PyTuple_GET_SIZE(o)))) {
PyObject *r = PyTuple_GET_ITEM(o, n);
Py_INCREF(r);
return r;
}
} else {
PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence;
if (likely(m && m->sq_item)) {
if (wraparound && unlikely(i < 0) && likely(m->sq_length)) {
Py_ssize_t l = m->sq_length(o);
if (likely(l >= 0)) {
i += l;
} else {
if (PyErr_ExceptionMatches(PyExc_OverflowError))
PyErr_Clear();
else
return NULL;
}
}
return m->sq_item(o, i);
}
}
#else
if (is_list || PySequence_Check(o)) {
return PySequence_GetItem(o, i);
}
#endif
return __Pyx_GetItemInt_Generic(o, PyInt_FromSsize_t(i));
}
#if CYTHON_COMPILING_IN_CPYTHON
static CYTHON_INLINE PyObject* __Pyx_PyObject_Call(PyObject *func, PyObject *arg, PyObject *kw) {
PyObject *result;
ternaryfunc call = func->ob_type->tp_call;
if (unlikely(!call))
return PyObject_Call(func, arg, kw);
#if PY_VERSION_HEX >= 0x02060000
if (unlikely(Py_EnterRecursiveCall((char*)" while calling a Python object")))
return NULL;
#endif
result = (*call)(func, arg, kw);
#if PY_VERSION_HEX >= 0x02060000
Py_LeaveRecursiveCall();
#endif
if (unlikely(!result) && unlikely(!PyErr_Occurred())) {
PyErr_SetString(
PyExc_SystemError,
"NULL result without error in PyObject_Call");
}
return result;
}
#endif
static CYTHON_INLINE void __Pyx_ErrRestore(PyObject *type, PyObject *value, PyObject *tb) {
#if CYTHON_COMPILING_IN_CPYTHON
PyObject *tmp_type, *tmp_value, *tmp_tb;
PyThreadState *tstate = PyThreadState_GET();
tmp_type = tstate->curexc_type;
tmp_value = tstate->curexc_value;
tmp_tb = tstate->curexc_traceback;
tstate->curexc_type = type;
tstate->curexc_value = value;
tstate->curexc_traceback = tb;
Py_XDECREF(tmp_type);
Py_XDECREF(tmp_value);
Py_XDECREF(tmp_tb);
#else
PyErr_Restore(type, value, tb);
#endif
}
static CYTHON_INLINE void __Pyx_ErrFetch(PyObject **type, PyObject **value, PyObject **tb) {
#if CYTHON_COMPILING_IN_CPYTHON
PyThreadState *tstate = PyThreadState_GET();
*type = tstate->curexc_type;
*value = tstate->curexc_value;
*tb = tstate->curexc_traceback;
tstate->curexc_type = 0;
tstate->curexc_value = 0;
tstate->curexc_traceback = 0;
#else
PyErr_Fetch(type, value, tb);
#endif
}
#if PY_MAJOR_VERSION < 3
static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb,
CYTHON_UNUSED PyObject *cause) {
Py_XINCREF(type);
if (!value || value == Py_None)
value = NULL;
else
Py_INCREF(value);
if (!tb || tb == Py_None)
tb = NULL;
else {
Py_INCREF(tb);
if (!PyTraceBack_Check(tb)) {
PyErr_SetString(PyExc_TypeError,
"raise: arg 3 must be a traceback or None");
goto raise_error;
}
}
#if PY_VERSION_HEX < 0x02050000
if (PyClass_Check(type)) {
#else
if (PyType_Check(type)) {
#endif
#if CYTHON_COMPILING_IN_PYPY
if (!value) {
Py_INCREF(Py_None);
value = Py_None;
}
#endif
PyErr_NormalizeException(&type, &value, &tb);
} else {
if (value) {
PyErr_SetString(PyExc_TypeError,
"instance exception may not have a separate value");
goto raise_error;
}
value = type;
#if PY_VERSION_HEX < 0x02050000
if (PyInstance_Check(type)) {
type = (PyObject*) ((PyInstanceObject*)type)->in_class;
Py_INCREF(type);
} else {
type = 0;
PyErr_SetString(PyExc_TypeError,
"raise: exception must be an old-style class or instance");
goto raise_error;
}
#else
type = (PyObject*) Py_TYPE(type);
Py_INCREF(type);
if (!PyType_IsSubtype((PyTypeObject *)type, (PyTypeObject *)PyExc_BaseException)) {
PyErr_SetString(PyExc_TypeError,
"raise: exception class must be a subclass of BaseException");
goto raise_error;
}
#endif
}
__Pyx_ErrRestore(type, value, tb);
return;
raise_error:
Py_XDECREF(value);
Py_XDECREF(type);
Py_XDECREF(tb);
return;
}
#else /* Python 3+ */
static void __Pyx_Raise(PyObject *type, PyObject *value, PyObject *tb, PyObject *cause) {
PyObject* owned_instance = NULL;
if (tb == Py_None) {
tb = 0;
} else if (tb && !PyTraceBack_Check(tb)) {
PyErr_SetString(PyExc_TypeError,
"raise: arg 3 must be a traceback or None");
goto bad;
}
if (value == Py_None)
value = 0;
if (PyExceptionInstance_Check(type)) {
if (value) {
PyErr_SetString(PyExc_TypeError,
"instance exception may not have a separate value");
goto bad;
}
value = type;
type = (PyObject*) Py_TYPE(value);
} else if (PyExceptionClass_Check(type)) {
PyObject *instance_class = NULL;
if (value && PyExceptionInstance_Check(value)) {
instance_class = (PyObject*) Py_TYPE(value);
if (instance_class != type) {
if (PyObject_IsSubclass(instance_class, type)) {
type = instance_class;
} else {
instance_class = NULL;
}
}
}
if (!instance_class) {
PyObject *args;
if (!value)
args = PyTuple_New(0);
else if (PyTuple_Check(value)) {
Py_INCREF(value);
args = value;
} else
args = PyTuple_Pack(1, value);
if (!args)
goto bad;
owned_instance = PyObject_Call(type, args, NULL);
Py_DECREF(args);
if (!owned_instance)
goto bad;
value = owned_instance;
if (!PyExceptionInstance_Check(value)) {
PyErr_Format(PyExc_TypeError,
"calling %R should have returned an instance of "
"BaseException, not %R",
type, Py_TYPE(value));
goto bad;
}
}
} else {
PyErr_SetString(PyExc_TypeError,
"raise: exception class must be a subclass of BaseException");
goto bad;
}
#if PY_VERSION_HEX >= 0x03030000
if (cause) {
#else
if (cause && cause != Py_None) {
#endif
PyObject *fixed_cause;
if (cause == Py_None) {
fixed_cause = NULL;
} else if (PyExceptionClass_Check(cause)) {
fixed_cause = PyObject_CallObject(cause, NULL);
if (fixed_cause == NULL)
goto bad;
} else if (PyExceptionInstance_Check(cause)) {
fixed_cause = cause;
Py_INCREF(fixed_cause);
} else {
PyErr_SetString(PyExc_TypeError,
"exception causes must derive from "
"BaseException");
goto bad;
}
PyException_SetCause(value, fixed_cause);
}
PyErr_SetObject(type, value);
if (tb) {
PyThreadState *tstate = PyThreadState_GET();
PyObject* tmp_tb = tstate->curexc_traceback;
if (tb != tmp_tb) {
Py_INCREF(tb);
tstate->curexc_traceback = tb;
Py_XDECREF(tmp_tb);
}
}
bad:
Py_XDECREF(owned_instance);
return;
}
#endif
static CYTHON_INLINE int __Pyx_PyBytes_Equals(PyObject* s1, PyObject* s2, int equals) {
#if CYTHON_COMPILING_IN_PYPY
return PyObject_RichCompareBool(s1, s2, equals);
#else
if (s1 == s2) {
return (equals == Py_EQ);
} else if (PyBytes_CheckExact(s1) & PyBytes_CheckExact(s2)) {
const char *ps1, *ps2;
Py_ssize_t length = PyBytes_GET_SIZE(s1);
if (length != PyBytes_GET_SIZE(s2))
return (equals == Py_NE);
ps1 = PyBytes_AS_STRING(s1);
ps2 = PyBytes_AS_STRING(s2);
if (ps1[0] != ps2[0]) {
return (equals == Py_NE);
} else if (length == 1) {
return (equals == Py_EQ);
} else {
int result = memcmp(ps1, ps2, (size_t)length);
return (equals == Py_EQ) ? (result == 0) : (result != 0);
}
} else if ((s1 == Py_None) & PyBytes_CheckExact(s2)) {
return (equals == Py_NE);
} else if ((s2 == Py_None) & PyBytes_CheckExact(s1)) {
return (equals == Py_NE);
} else {
int result;
PyObject* py_result = PyObject_RichCompare(s1, s2, equals);
if (!py_result)
return -1;
result = __Pyx_PyObject_IsTrue(py_result);
Py_DECREF(py_result);
return result;
}
#endif
}
static CYTHON_INLINE int __Pyx_PyUnicode_Equals(PyObject* s1, PyObject* s2, int equals) {
#if CYTHON_COMPILING_IN_PYPY
return PyObject_RichCompareBool(s1, s2, equals);
#else
#if PY_MAJOR_VERSION < 3
PyObject* owned_ref = NULL;
#endif
int s1_is_unicode, s2_is_unicode;
if (s1 == s2) {
goto return_eq;
}
s1_is_unicode = PyUnicode_CheckExact(s1);
s2_is_unicode = PyUnicode_CheckExact(s2);
#if PY_MAJOR_VERSION < 3
if ((s1_is_unicode & (!s2_is_unicode)) && PyString_CheckExact(s2)) {
owned_ref = PyUnicode_FromObject(s2);
if (unlikely(!owned_ref))
return -1;
s2 = owned_ref;
s2_is_unicode = 1;
} else if ((s2_is_unicode & (!s1_is_unicode)) && PyString_CheckExact(s1)) {
owned_ref = PyUnicode_FromObject(s1);
if (unlikely(!owned_ref))
return -1;
s1 = owned_ref;
s1_is_unicode = 1;
} else if (((!s2_is_unicode) & (!s1_is_unicode))) {
return __Pyx_PyBytes_Equals(s1, s2, equals);
}
#endif
if (s1_is_unicode & s2_is_unicode) {
Py_ssize_t length;
int kind;
void *data1, *data2;
#if CYTHON_PEP393_ENABLED
if (unlikely(PyUnicode_READY(s1) < 0) || unlikely(PyUnicode_READY(s2) < 0))
return -1;
#endif
length = __Pyx_PyUnicode_GET_LENGTH(s1);
if (length != __Pyx_PyUnicode_GET_LENGTH(s2)) {
goto return_ne;
}
kind = __Pyx_PyUnicode_KIND(s1);
if (kind != __Pyx_PyUnicode_KIND(s2)) {
goto return_ne;
}
data1 = __Pyx_PyUnicode_DATA(s1);
data2 = __Pyx_PyUnicode_DATA(s2);
if (__Pyx_PyUnicode_READ(kind, data1, 0) != __Pyx_PyUnicode_READ(kind, data2, 0)) {
goto return_ne;
} else if (length == 1) {
goto return_eq;
} else {
int result = memcmp(data1, data2, length * kind);
#if PY_MAJOR_VERSION < 3
Py_XDECREF(owned_ref);
#endif
return (equals == Py_EQ) ? (result == 0) : (result != 0);
}
} else if ((s1 == Py_None) & s2_is_unicode) {
goto return_ne;
} else if ((s2 == Py_None) & s1_is_unicode) {
goto return_ne;
} else {
int result;
PyObject* py_result = PyObject_RichCompare(s1, s2, equals);
if (!py_result)
return -1;
result = __Pyx_PyObject_IsTrue(py_result);
Py_DECREF(py_result);
return result;
}
return_eq:
#if PY_MAJOR_VERSION < 3
Py_XDECREF(owned_ref);
#endif
return (equals == Py_EQ);
return_ne:
#if PY_MAJOR_VERSION < 3
Py_XDECREF(owned_ref);
#endif
return (equals == Py_NE);
#endif
}
static CYTHON_INLINE int __Pyx_SetItemInt_Generic(PyObject *o, PyObject *j, PyObject *v) {
int r;
if (!j) return -1;
r = PyObject_SetItem(o, j, v);
Py_DECREF(j);
return r;
}
static CYTHON_INLINE int __Pyx_SetItemInt_Fast(PyObject *o, Py_ssize_t i, PyObject *v,
int is_list, int wraparound, int boundscheck) {
#if CYTHON_COMPILING_IN_CPYTHON
if (is_list || PyList_CheckExact(o)) {
Py_ssize_t n = (!wraparound) ? i : ((likely(i >= 0)) ? i : i + PyList_GET_SIZE(o));
if ((!boundscheck) || likely((n >= 0) & (n < PyList_GET_SIZE(o)))) {
PyObject* old = PyList_GET_ITEM(o, n);
Py_INCREF(v);
PyList_SET_ITEM(o, n, v);
Py_DECREF(old);
return 1;
}
} else {
PySequenceMethods *m = Py_TYPE(o)->tp_as_sequence;
if (likely(m && m->sq_ass_item)) {
if (wraparound && unlikely(i < 0) && likely(m->sq_length)) {
Py_ssize_t l = m->sq_length(o);
if (likely(l >= 0)) {
i += l;
} else {
if (PyErr_ExceptionMatches(PyExc_OverflowError))
PyErr_Clear();
else
return -1;
}
}
return m->sq_ass_item(o, i, v);
}
}
#else
#if CYTHON_COMPILING_IN_PYPY
if (is_list || (PySequence_Check(o) && !PyDict_Check(o))) {
#else
if (is_list || PySequence_Check(o)) {
#endif
return PySequence_SetItem(o, i, v);
}
#endif
return __Pyx_SetItemInt_Generic(o, PyInt_FromSsize_t(i), v);
}
static CYTHON_INLINE void __Pyx_RaiseTooManyValuesError(Py_ssize_t expected) {
PyErr_Format(PyExc_ValueError,
"too many values to unpack (expected %" CYTHON_FORMAT_SSIZE_T "d)", expected);
}
static CYTHON_INLINE void __Pyx_RaiseNeedMoreValuesError(Py_ssize_t index) {
PyErr_Format(PyExc_ValueError,
"need more than %" CYTHON_FORMAT_SSIZE_T "d value%.1s to unpack",
index, (index == 1) ? "" : "s");
}
static CYTHON_INLINE int __Pyx_IterFinish(void) {
#if CYTHON_COMPILING_IN_CPYTHON
PyThreadState *tstate = PyThreadState_GET();
PyObject* exc_type = tstate->curexc_type;
if (unlikely(exc_type)) {
if (likely(exc_type == PyExc_StopIteration) || PyErr_GivenExceptionMatches(exc_type, PyExc_StopIteration)) {
PyObject *exc_value, *exc_tb;
exc_value = tstate->curexc_value;
exc_tb = tstate->curexc_traceback;
tstate->curexc_type = 0;
tstate->curexc_value = 0;
tstate->curexc_traceback = 0;
Py_DECREF(exc_type);
Py_XDECREF(exc_value);
Py_XDECREF(exc_tb);
return 0;
} else {
return -1;
}
}
return 0;
#else
if (unlikely(PyErr_Occurred())) {
if (likely(PyErr_ExceptionMatches(PyExc_StopIteration))) {
PyErr_Clear();
return 0;
} else {
return -1;
}
}
return 0;
#endif
}
static int __Pyx_IternextUnpackEndCheck(PyObject *retval, Py_ssize_t expected) {
if (unlikely(retval)) {
Py_DECREF(retval);
__Pyx_RaiseTooManyValuesError(expected);
return -1;
} else {
return __Pyx_IterFinish();
}
return 0;
}
static CYTHON_INLINE int __Pyx_IsLittleEndian(void) {
unsigned int n = 1;
return *(unsigned char*)(&n) != 0;
}
static void __Pyx_BufFmt_Init(__Pyx_BufFmt_Context* ctx,
__Pyx_BufFmt_StackElem* stack,
__Pyx_TypeInfo* type) {
stack[0].field = &ctx->root;
stack[0].parent_offset = 0;
ctx->root.type = type;
ctx->root.name = "buffer dtype";
ctx->root.offset = 0;
ctx->head = stack;
ctx->head->field = &ctx->root;
ctx->fmt_offset = 0;
ctx->head->parent_offset = 0;
ctx->new_packmode = '@';
ctx->enc_packmode = '@';
ctx->new_count = 1;
ctx->enc_count = 0;
ctx->enc_type = 0;
ctx->is_complex = 0;
ctx->is_valid_array = 0;
ctx->struct_alignment = 0;
while (type->typegroup == 'S') {
++ctx->head;
ctx->head->field = type->fields;
ctx->head->parent_offset = 0;
type = type->fields->type;
}
}
static int __Pyx_BufFmt_ParseNumber(const char** ts) {
int count;
const char* t = *ts;
if (*t < '0' || *t > '9') {
return -1;
} else {
count = *t++ - '0';
while (*t >= '0' && *t < '9') {
count *= 10;
count += *t++ - '0';
}
}
*ts = t;
return count;
}
static int __Pyx_BufFmt_ExpectNumber(const char **ts) {
int number = __Pyx_BufFmt_ParseNumber(ts);
if (number == -1) /* First char was not a digit */
PyErr_Format(PyExc_ValueError,\
"Does not understand character buffer dtype format string ('%c')", **ts);
return number;
}
static void __Pyx_BufFmt_RaiseUnexpectedChar(char ch) {
PyErr_Format(PyExc_ValueError,
"Unexpected format string character: '%c'", ch);
}
static const char* __Pyx_BufFmt_DescribeTypeChar(char ch, int is_complex) {
switch (ch) {
case 'c': return "'char'";
case 'b': return "'signed char'";
case 'B': return "'unsigned char'";
case 'h': return "'short'";
case 'H': return "'unsigned short'";
case 'i': return "'int'";
case 'I': return "'unsigned int'";
case 'l': return "'long'";
case 'L': return "'unsigned long'";
case 'q': return "'long long'";
case 'Q': return "'unsigned long long'";
case 'f': return (is_complex ? "'complex float'" : "'float'");
case 'd': return (is_complex ? "'complex double'" : "'double'");
case 'g': return (is_complex ? "'complex long double'" : "'long double'");
case 'T': return "a struct";
case 'O': return "Python object";
case 'P': return "a pointer";
case 's': case 'p': return "a string";
case 0: return "end";
default: return "unparseable format string";
}
}
static size_t __Pyx_BufFmt_TypeCharToStandardSize(char ch, int is_complex) {
switch (ch) {
case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1;
case 'h': case 'H': return 2;
case 'i': case 'I': case 'l': case 'L': return 4;
case 'q': case 'Q': return 8;
case 'f': return (is_complex ? 8 : 4);
case 'd': return (is_complex ? 16 : 8);
case 'g': {
PyErr_SetString(PyExc_ValueError, "Python does not define a standard format string size for long double ('g')..");
return 0;
}
case 'O': case 'P': return sizeof(void*);
default:
__Pyx_BufFmt_RaiseUnexpectedChar(ch);
return 0;
}
}
static size_t __Pyx_BufFmt_TypeCharToNativeSize(char ch, int is_complex) {
switch (ch) {
case 'c': case 'b': case 'B': case 's': case 'p': return 1;
case 'h': case 'H': return sizeof(short);
case 'i': case 'I': return sizeof(int);
case 'l': case 'L': return sizeof(long);
#ifdef HAVE_LONG_LONG
case 'q': case 'Q': return sizeof(PY_LONG_LONG);
#endif
case 'f': return sizeof(float) * (is_complex ? 2 : 1);
case 'd': return sizeof(double) * (is_complex ? 2 : 1);
case 'g': return sizeof(long double) * (is_complex ? 2 : 1);
case 'O': case 'P': return sizeof(void*);
default: {
__Pyx_BufFmt_RaiseUnexpectedChar(ch);
return 0;
}
}
}
typedef struct { char c; short x; } __Pyx_st_short;
typedef struct { char c; int x; } __Pyx_st_int;
typedef struct { char c; long x; } __Pyx_st_long;
typedef struct { char c; float x; } __Pyx_st_float;
typedef struct { char c; double x; } __Pyx_st_double;
typedef struct { char c; long double x; } __Pyx_st_longdouble;
typedef struct { char c; void *x; } __Pyx_st_void_p;
#ifdef HAVE_LONG_LONG
typedef struct { char c; PY_LONG_LONG x; } __Pyx_st_longlong;
#endif
static size_t __Pyx_BufFmt_TypeCharToAlignment(char ch, CYTHON_UNUSED int is_complex) {
switch (ch) {
case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1;
case 'h': case 'H': return sizeof(__Pyx_st_short) - sizeof(short);
case 'i': case 'I': return sizeof(__Pyx_st_int) - sizeof(int);
case 'l': case 'L': return sizeof(__Pyx_st_long) - sizeof(long);
#ifdef HAVE_LONG_LONG
case 'q': case 'Q': return sizeof(__Pyx_st_longlong) - sizeof(PY_LONG_LONG);
#endif
case 'f': return sizeof(__Pyx_st_float) - sizeof(float);
case 'd': return sizeof(__Pyx_st_double) - sizeof(double);
case 'g': return sizeof(__Pyx_st_longdouble) - sizeof(long double);
case 'P': case 'O': return sizeof(__Pyx_st_void_p) - sizeof(void*);
default:
__Pyx_BufFmt_RaiseUnexpectedChar(ch);
return 0;
}
}
/* These are for computing the padding at the end of the struct to align
on the first member of the struct. This will probably the same as above,
but we don't have any guarantees.
*/
typedef struct { short x; char c; } __Pyx_pad_short;
typedef struct { int x; char c; } __Pyx_pad_int;
typedef struct { long x; char c; } __Pyx_pad_long;
typedef struct { float x; char c; } __Pyx_pad_float;
typedef struct { double x; char c; } __Pyx_pad_double;
typedef struct { long double x; char c; } __Pyx_pad_longdouble;
typedef struct { void *x; char c; } __Pyx_pad_void_p;
#ifdef HAVE_LONG_LONG
typedef struct { PY_LONG_LONG x; char c; } __Pyx_pad_longlong;
#endif
static size_t __Pyx_BufFmt_TypeCharToPadding(char ch, CYTHON_UNUSED int is_complex) {
switch (ch) {
case '?': case 'c': case 'b': case 'B': case 's': case 'p': return 1;
case 'h': case 'H': return sizeof(__Pyx_pad_short) - sizeof(short);
case 'i': case 'I': return sizeof(__Pyx_pad_int) - sizeof(int);
case 'l': case 'L': return sizeof(__Pyx_pad_long) - sizeof(long);
#ifdef HAVE_LONG_LONG
case 'q': case 'Q': return sizeof(__Pyx_pad_longlong) - sizeof(PY_LONG_LONG);
#endif
case 'f': return sizeof(__Pyx_pad_float) - sizeof(float);
case 'd': return sizeof(__Pyx_pad_double) - sizeof(double);
case 'g': return sizeof(__Pyx_pad_longdouble) - sizeof(long double);
case 'P': case 'O': return sizeof(__Pyx_pad_void_p) - sizeof(void*);
default:
__Pyx_BufFmt_RaiseUnexpectedChar(ch);
return 0;
}
}
static char __Pyx_BufFmt_TypeCharToGroup(char ch, int is_complex) {
switch (ch) {
case 'c':
return 'H';
case 'b': case 'h': case 'i':
case 'l': case 'q': case 's': case 'p':
return 'I';
case 'B': case 'H': case 'I': case 'L': case 'Q':
return 'U';
case 'f': case 'd': case 'g':
return (is_complex ? 'C' : 'R');
case 'O':
return 'O';
case 'P':
return 'P';
default: {
__Pyx_BufFmt_RaiseUnexpectedChar(ch);
return 0;
}
}
}
static void __Pyx_BufFmt_RaiseExpected(__Pyx_BufFmt_Context* ctx) {
if (ctx->head == NULL || ctx->head->field == &ctx->root) {
const char* expected;
const char* quote;
if (ctx->head == NULL) {
expected = "end";
quote = "";
} else {
expected = ctx->head->field->type->name;
quote = "'";
}
PyErr_Format(PyExc_ValueError,
"Buffer dtype mismatch, expected %s%s%s but got %s",
quote, expected, quote,
__Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex));
} else {
__Pyx_StructField* field = ctx->head->field;
__Pyx_StructField* parent = (ctx->head - 1)->field;
PyErr_Format(PyExc_ValueError,
"Buffer dtype mismatch, expected '%s' but got %s in '%s.%s'",
field->type->name, __Pyx_BufFmt_DescribeTypeChar(ctx->enc_type, ctx->is_complex),
parent->type->name, field->name);
}
}
static int __Pyx_BufFmt_ProcessTypeChunk(__Pyx_BufFmt_Context* ctx) {
char group;
size_t size, offset, arraysize = 1;
if (ctx->enc_type == 0) return 0;
if (ctx->head->field->type->arraysize[0]) {
int i, ndim = 0;
if (ctx->enc_type == 's' || ctx->enc_type == 'p') {
ctx->is_valid_array = ctx->head->field->type->ndim == 1;
ndim = 1;
if (ctx->enc_count != ctx->head->field->type->arraysize[0]) {
PyErr_Format(PyExc_ValueError,
"Expected a dimension of size %zu, got %zu",
ctx->head->field->type->arraysize[0], ctx->enc_count);
return -1;
}
}
if (!ctx->is_valid_array) {
PyErr_Format(PyExc_ValueError, "Expected %d dimensions, got %d",
ctx->head->field->type->ndim, ndim);
return -1;
}
for (i = 0; i < ctx->head->field->type->ndim; i++) {
arraysize *= ctx->head->field->type->arraysize[i];
}
ctx->is_valid_array = 0;
ctx->enc_count = 1;
}
group = __Pyx_BufFmt_TypeCharToGroup(ctx->enc_type, ctx->is_complex);
do {
__Pyx_StructField* field = ctx->head->field;
__Pyx_TypeInfo* type = field->type;
if (ctx->enc_packmode == '@' || ctx->enc_packmode == '^') {
size = __Pyx_BufFmt_TypeCharToNativeSize(ctx->enc_type, ctx->is_complex);
} else {
size = __Pyx_BufFmt_TypeCharToStandardSize(ctx->enc_type, ctx->is_complex);
}
if (ctx->enc_packmode == '@') {
size_t align_at = __Pyx_BufFmt_TypeCharToAlignment(ctx->enc_type, ctx->is_complex);
size_t align_mod_offset;
if (align_at == 0) return -1;
align_mod_offset = ctx->fmt_offset % align_at;
if (align_mod_offset > 0) ctx->fmt_offset += align_at - align_mod_offset;
if (ctx->struct_alignment == 0)
ctx->struct_alignment = __Pyx_BufFmt_TypeCharToPadding(ctx->enc_type,
ctx->is_complex);
}
if (type->size != size || type->typegroup != group) {
if (type->typegroup == 'C' && type->fields != NULL) {
size_t parent_offset = ctx->head->parent_offset + field->offset;
++ctx->head;
ctx->head->field = type->fields;
ctx->head->parent_offset = parent_offset;
continue;
}
if ((type->typegroup == 'H' || group == 'H') && type->size == size) {
} else {
__Pyx_BufFmt_RaiseExpected(ctx);
return -1;
}
}
offset = ctx->head->parent_offset + field->offset;
if (ctx->fmt_offset != offset) {
PyErr_Format(PyExc_ValueError,
"Buffer dtype mismatch; next field is at offset %" CYTHON_FORMAT_SSIZE_T "d but %" CYTHON_FORMAT_SSIZE_T "d expected",
(Py_ssize_t)ctx->fmt_offset, (Py_ssize_t)offset);
return -1;
}
ctx->fmt_offset += size;
if (arraysize)
ctx->fmt_offset += (arraysize - 1) * size;
--ctx->enc_count; /* Consume from buffer string */
while (1) {
if (field == &ctx->root) {
ctx->head = NULL;
if (ctx->enc_count != 0) {
__Pyx_BufFmt_RaiseExpected(ctx);
return -1;
}
break; /* breaks both loops as ctx->enc_count == 0 */
}
ctx->head->field = ++field;
if (field->type == NULL) {
--ctx->head;
field = ctx->head->field;
continue;
} else if (field->type->typegroup == 'S') {
size_t parent_offset = ctx->head->parent_offset + field->offset;
if (field->type->fields->type == NULL) continue; /* empty struct */
field = field->type->fields;
++ctx->head;
ctx->head->field = field;
ctx->head->parent_offset = parent_offset;
break;
} else {
break;
}
}
} while (ctx->enc_count);
ctx->enc_type = 0;
ctx->is_complex = 0;
return 0;
}
static CYTHON_INLINE PyObject *
__pyx_buffmt_parse_array(__Pyx_BufFmt_Context* ctx, const char** tsp)
{
const char *ts = *tsp;
int i = 0, number;
int ndim = ctx->head->field->type->ndim;
;
++ts;
if (ctx->new_count != 1) {
PyErr_SetString(PyExc_ValueError,
"Cannot handle repeated arrays in format string");
return NULL;
}
if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL;
while (*ts && *ts != ')') {
switch (*ts) {
case ' ': case '\f': case '\r': case '\n': case '\t': case '\v': continue;
default: break; /* not a 'break' in the loop */
}
number = __Pyx_BufFmt_ExpectNumber(&ts);
if (number == -1) return NULL;
if (i < ndim && (size_t) number != ctx->head->field->type->arraysize[i])
return PyErr_Format(PyExc_ValueError,
"Expected a dimension of size %zu, got %d",
ctx->head->field->type->arraysize[i], number);
if (*ts != ',' && *ts != ')')
return PyErr_Format(PyExc_ValueError,
"Expected a comma in format string, got '%c'", *ts);
if (*ts == ',') ts++;
i++;
}
if (i != ndim)
return PyErr_Format(PyExc_ValueError, "Expected %d dimension(s), got %d",
ctx->head->field->type->ndim, i);
if (!*ts) {
PyErr_SetString(PyExc_ValueError,
"Unexpected end of format string, expected ')'");
return NULL;
}
ctx->is_valid_array = 1;
ctx->new_count = 1;
*tsp = ++ts;
return Py_None;
}
static const char* __Pyx_BufFmt_CheckString(__Pyx_BufFmt_Context* ctx, const char* ts) {
int got_Z = 0;
while (1) {
switch(*ts) {
case 0:
if (ctx->enc_type != 0 && ctx->head == NULL) {
__Pyx_BufFmt_RaiseExpected(ctx);
return NULL;
}
if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL;
if (ctx->head != NULL) {
__Pyx_BufFmt_RaiseExpected(ctx);
return NULL;
}
return ts;
case ' ':
case 10:
case 13:
++ts;
break;
case '<':
if (!__Pyx_IsLittleEndian()) {
PyErr_SetString(PyExc_ValueError, "Little-endian buffer not supported on big-endian compiler");
return NULL;
}
ctx->new_packmode = '=';
++ts;
break;
case '>':
case '!':
if (__Pyx_IsLittleEndian()) {
PyErr_SetString(PyExc_ValueError, "Big-endian buffer not supported on little-endian compiler");
return NULL;
}
ctx->new_packmode = '=';
++ts;
break;
case '=':
case '@':
case '^':
ctx->new_packmode = *ts++;
break;
case 'T': /* substruct */
{
const char* ts_after_sub;
size_t i, struct_count = ctx->new_count;
size_t struct_alignment = ctx->struct_alignment;
ctx->new_count = 1;
++ts;
if (*ts != '{') {
PyErr_SetString(PyExc_ValueError, "Buffer acquisition: Expected '{' after 'T'");
return NULL;
}
if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL;
ctx->enc_type = 0; /* Erase processed last struct element */
ctx->enc_count = 0;
ctx->struct_alignment = 0;
++ts;
ts_after_sub = ts;
for (i = 0; i != struct_count; ++i) {
ts_after_sub = __Pyx_BufFmt_CheckString(ctx, ts);
if (!ts_after_sub) return NULL;
}
ts = ts_after_sub;
if (struct_alignment) ctx->struct_alignment = struct_alignment;
}
break;
case '}': /* end of substruct; either repeat or move on */
{
size_t alignment = ctx->struct_alignment;
++ts;
if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL;
ctx->enc_type = 0; /* Erase processed last struct element */
if (alignment && ctx->fmt_offset % alignment) {
ctx->fmt_offset += alignment - (ctx->fmt_offset % alignment);
}
}
return ts;
case 'x':
if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL;
ctx->fmt_offset += ctx->new_count;
ctx->new_count = 1;
ctx->enc_count = 0;
ctx->enc_type = 0;
ctx->enc_packmode = ctx->new_packmode;
++ts;
break;
case 'Z':
got_Z = 1;
++ts;
if (*ts != 'f' && *ts != 'd' && *ts != 'g') {
__Pyx_BufFmt_RaiseUnexpectedChar('Z');
return NULL;
} /* fall through */
case 'c': case 'b': case 'B': case 'h': case 'H': case 'i': case 'I':
case 'l': case 'L': case 'q': case 'Q':
case 'f': case 'd': case 'g':
case 'O': case 's': case 'p':
if (ctx->enc_type == *ts && got_Z == ctx->is_complex &&
ctx->enc_packmode == ctx->new_packmode) {
ctx->enc_count += ctx->new_count;
} else {
if (__Pyx_BufFmt_ProcessTypeChunk(ctx) == -1) return NULL;
ctx->enc_count = ctx->new_count;
ctx->enc_packmode = ctx->new_packmode;
ctx->enc_type = *ts;
ctx->is_complex = got_Z;
}
++ts;
ctx->new_count = 1;
got_Z = 0;
break;
case ':':
++ts;
while(*ts != ':') ++ts;
++ts;
break;
case '(':
if (!__pyx_buffmt_parse_array(ctx, &ts)) return NULL;
break;
default:
{
int number = __Pyx_BufFmt_ExpectNumber(&ts);
if (number == -1) return NULL;
ctx->new_count = (size_t)number;
}
}
}
}
static CYTHON_INLINE void __Pyx_ZeroBuffer(Py_buffer* buf) {
buf->buf = NULL;
buf->obj = NULL;
buf->strides = __Pyx_zeros;
buf->shape = __Pyx_zeros;
buf->suboffsets = __Pyx_minusones;
}
static CYTHON_INLINE int __Pyx_GetBufferAndValidate(
Py_buffer* buf, PyObject* obj, __Pyx_TypeInfo* dtype, int flags,
int nd, int cast, __Pyx_BufFmt_StackElem* stack)
{
if (obj == Py_None || obj == NULL) {
__Pyx_ZeroBuffer(buf);
return 0;
}
buf->buf = NULL;
if (__Pyx_GetBuffer(obj, buf, flags) == -1) goto fail;
if (buf->ndim != nd) {
PyErr_Format(PyExc_ValueError,
"Buffer has wrong number of dimensions (expected %d, got %d)",
nd, buf->ndim);
goto fail;
}
if (!cast) {
__Pyx_BufFmt_Context ctx;
__Pyx_BufFmt_Init(&ctx, stack, dtype);
if (!__Pyx_BufFmt_CheckString(&ctx, buf->format)) goto fail;
}
if ((unsigned)buf->itemsize != dtype->size) {
PyErr_Format(PyExc_ValueError,
"Item size of buffer (%" CYTHON_FORMAT_SSIZE_T "d byte%s) does not match size of '%s' (%" CYTHON_FORMAT_SSIZE_T "d byte%s)",
buf->itemsize, (buf->itemsize > 1) ? "s" : "",
dtype->name, (Py_ssize_t)dtype->size, (dtype->size > 1) ? "s" : "");
goto fail;
}
if (buf->suboffsets == NULL) buf->suboffsets = __Pyx_minusones;
return 0;
fail:;
__Pyx_ZeroBuffer(buf);
return -1;
}
static CYTHON_INLINE void __Pyx_SafeReleaseBuffer(Py_buffer* info) {
if (info->buf == NULL) return;
if (info->suboffsets == __Pyx_minusones) info->suboffsets = NULL;
__Pyx_ReleaseBuffer(info);
}
static int
__Pyx_init_memviewslice(struct __pyx_memoryview_obj *memview,
int ndim,
__Pyx_memviewslice *memviewslice,
int memview_is_new_reference)
{
__Pyx_RefNannyDeclarations
int i, retval=-1;
Py_buffer *buf = &memview->view;
__Pyx_RefNannySetupContext("init_memviewslice", 0);
if (!buf) {
PyErr_SetString(PyExc_ValueError,
"buf is NULL.");
goto fail;
} else if (memviewslice->memview || memviewslice->data) {
PyErr_SetString(PyExc_ValueError,
"memviewslice is already initialized!");
goto fail;
}
if (buf->strides) {
for (i = 0; i < ndim; i++) {
memviewslice->strides[i] = buf->strides[i];
}
} else {
Py_ssize_t stride = buf->itemsize;
for (i = ndim - 1; i >= 0; i--) {
memviewslice->strides[i] = stride;
stride *= buf->shape[i];
}
}
for (i = 0; i < ndim; i++) {
memviewslice->shape[i] = buf->shape[i];
if (buf->suboffsets) {
memviewslice->suboffsets[i] = buf->suboffsets[i];
} else {
memviewslice->suboffsets[i] = -1;
}
}
memviewslice->memview = memview;
memviewslice->data = (char *)buf->buf;
if (__pyx_add_acquisition_count(memview) == 0 && !memview_is_new_reference) {
Py_INCREF(memview);
}
retval = 0;
goto no_fail;
fail:
memviewslice->memview = 0;
memviewslice->data = 0;
retval = -1;
no_fail:
__Pyx_RefNannyFinishContext();
return retval;
}
static CYTHON_INLINE void __pyx_fatalerror(const char *fmt, ...) {
va_list vargs;
char msg[200];
va_start(vargs, fmt);
#ifdef HAVE_STDARG_PROTOTYPES
va_start(vargs, fmt);
#else
va_start(vargs);
#endif
vsnprintf(msg, 200, fmt, vargs);
Py_FatalError(msg);
va_end(vargs);
}
static CYTHON_INLINE int
__pyx_add_acquisition_count_locked(__pyx_atomic_int *acquisition_count,
PyThread_type_lock lock)
{
int result;
PyThread_acquire_lock(lock, 1);
result = (*acquisition_count)++;
PyThread_release_lock(lock);
return result;
}
static CYTHON_INLINE int
__pyx_sub_acquisition_count_locked(__pyx_atomic_int *acquisition_count,
PyThread_type_lock lock)
{
int result;
PyThread_acquire_lock(lock, 1);
result = (*acquisition_count)--;
PyThread_release_lock(lock);
return result;
}
static CYTHON_INLINE void
__Pyx_INC_MEMVIEW(__Pyx_memviewslice *memslice, int have_gil, int lineno)
{
int first_time;
struct __pyx_memoryview_obj *memview = memslice->memview;
if (!memview || (PyObject *) memview == Py_None)
return; /* allow uninitialized memoryview assignment */
if (__pyx_get_slice_count(memview) < 0)
__pyx_fatalerror("Acquisition count is %d (line %d)",
__pyx_get_slice_count(memview), lineno);
first_time = __pyx_add_acquisition_count(memview) == 0;
if (first_time) {
if (have_gil) {
Py_INCREF((PyObject *) memview);
} else {
PyGILState_STATE _gilstate = PyGILState_Ensure();
Py_INCREF((PyObject *) memview);
PyGILState_Release(_gilstate);
}
}
}
static CYTHON_INLINE void __Pyx_XDEC_MEMVIEW(__Pyx_memviewslice *memslice,
int have_gil, int lineno) {
int last_time;
struct __pyx_memoryview_obj *memview = memslice->memview;
if (!memview ) {
return;
} else if ((PyObject *) memview == Py_None) {
memslice->memview = NULL;
return;
}
if (__pyx_get_slice_count(memview) <= 0)
__pyx_fatalerror("Acquisition count is %d (line %d)",
__pyx_get_slice_count(memview), lineno);
last_time = __pyx_sub_acquisition_count(memview) == 1;
memslice->data = NULL;
if (last_time) {
if (have_gil) {
Py_CLEAR(memslice->memview);
} else {
PyGILState_STATE _gilstate = PyGILState_Ensure();
Py_CLEAR(memslice->memview);
PyGILState_Release(_gilstate);
}
} else {
memslice->memview = NULL;
}
}
static CYTHON_INLINE PyObject *__Pyx_GetModuleGlobalName(PyObject *name) {
PyObject *result;
#if CYTHON_COMPILING_IN_CPYTHON
result = PyDict_GetItem(__pyx_d, name);
if (result) {
Py_INCREF(result);
} else {
#else
result = PyObject_GetItem(__pyx_d, name);
if (!result) {
PyErr_Clear();
#endif
result = __Pyx_GetBuiltinName(name);
}
return result;
}
static CYTHON_INLINE void __Pyx_RaiseNoneNotIterableError(void) {
PyErr_SetString(PyExc_TypeError, "'NoneType' object is not iterable");
}
static CYTHON_INLINE int __Pyx_TypeTest(PyObject *obj, PyTypeObject *type) {
if (unlikely(!type)) {
PyErr_SetString(PyExc_SystemError, "Missing type object");
return 0;
}
if (likely(PyObject_TypeCheck(obj, type)))
return 1;
PyErr_Format(PyExc_TypeError, "Cannot convert %.200s to %.200s",
Py_TYPE(obj)->tp_name, type->tp_name);
return 0;
}
static void __Pyx_RaiseArgumentTypeInvalid(const char* name, PyObject *obj, PyTypeObject *type) {
PyErr_Format(PyExc_TypeError,
"Argument '%.200s' has incorrect type (expected %.200s, got %.200s)",
name, type->tp_name, Py_TYPE(obj)->tp_name);
}
static CYTHON_INLINE int __Pyx_ArgTypeTest(PyObject *obj, PyTypeObject *type, int none_allowed,
const char *name, int exact)
{
if (unlikely(!type)) {
PyErr_SetString(PyExc_SystemError, "Missing type object");
return 0;
}
if (none_allowed && obj == Py_None) return 1;
else if (exact) {
if (likely(Py_TYPE(obj) == type)) return 1;
#if PY_MAJOR_VERSION == 2
else if ((type == &PyBaseString_Type) && likely(__Pyx_PyBaseString_CheckExact(obj))) return 1;
#endif
}
else {
if (likely(PyObject_TypeCheck(obj, type))) return 1;
}
__Pyx_RaiseArgumentTypeInvalid(name, obj, type);
return 0;
}
static CYTHON_INLINE PyObject *__Pyx_GetAttr(PyObject *o, PyObject *n) {
#if CYTHON_COMPILING_IN_CPYTHON
#if PY_MAJOR_VERSION >= 3
if (likely(PyUnicode_Check(n)))
#else
if (likely(PyString_Check(n)))
#endif
return __Pyx_PyObject_GetAttrStr(o, n);
#endif
return PyObject_GetAttr(o, n);
}
static CYTHON_INLINE PyObject *__Pyx_GetAttr3(PyObject *o, PyObject *n, PyObject *d) {
PyObject *r = __Pyx_GetAttr(o, n);
if (unlikely(!r)) {
if (!PyErr_ExceptionMatches(PyExc_AttributeError))
goto bad;
PyErr_Clear();
r = d;
Py_INCREF(d);
}
return r;
bad:
return NULL;
}
static CYTHON_INLINE PyObject* __Pyx_decode_c_string(
const char* cstring, Py_ssize_t start, Py_ssize_t stop,
const char* encoding, const char* errors,
PyObject* (*decode_func)(const char *s, Py_ssize_t size, const char *errors)) {
Py_ssize_t length;
if (unlikely((start < 0) | (stop < 0))) {
length = strlen(cstring);
if (start < 0) {
start += length;
if (start < 0)
start = 0;
}
if (stop < 0)
stop += length;
}
length = stop - start;
if (unlikely(length <= 0))
return PyUnicode_FromUnicode(NULL, 0);
cstring += start;
if (decode_func) {
return decode_func(cstring, length, errors);
} else {
return PyUnicode_Decode(cstring, length, encoding, errors);
}
}
static CYTHON_INLINE void __Pyx_RaiseUnboundLocalError(const char *varname) {
PyErr_Format(PyExc_UnboundLocalError, "local variable '%s' referenced before assignment", varname);
}
static void __Pyx_WriteUnraisable(const char *name, CYTHON_UNUSED int clineno,
CYTHON_UNUSED int lineno, CYTHON_UNUSED const char *filename,
int full_traceback) {
PyObject *old_exc, *old_val, *old_tb;
PyObject *ctx;
__Pyx_ErrFetch(&old_exc, &old_val, &old_tb);
if (full_traceback) {
Py_XINCREF(old_exc);
Py_XINCREF(old_val);
Py_XINCREF(old_tb);
__Pyx_ErrRestore(old_exc, old_val, old_tb);
PyErr_PrintEx(1);
}
#if PY_MAJOR_VERSION < 3
ctx = PyString_FromString(name);
#else
ctx = PyUnicode_FromString(name);
#endif
__Pyx_ErrRestore(old_exc, old_val, old_tb);
if (!ctx) {
PyErr_WriteUnraisable(Py_None);
} else {
PyErr_WriteUnraisable(ctx);
Py_DECREF(ctx);
}
}
static int __Pyx_SetVtable(PyObject *dict, void *vtable) {
#if PY_VERSION_HEX >= 0x02070000 && !(PY_MAJOR_VERSION==3&&PY_MINOR_VERSION==0)
PyObject *ob = PyCapsule_New(vtable, 0, 0);
#else
PyObject *ob = PyCObject_FromVoidPtr(vtable, 0);
#endif
if (!ob)
goto bad;
if (PyDict_SetItem(dict, __pyx_n_s_pyx_vtable, ob) < 0)
goto bad;
Py_DECREF(ob);
return 0;
bad:
Py_XDECREF(ob);
return -1;
}
static PyTypeObject* __Pyx_FetchCommonType(PyTypeObject* type) {
PyObject* fake_module;
PyTypeObject* cached_type = NULL;
fake_module = PyImport_AddModule((char*) "_cython_" CYTHON_ABI);
if (!fake_module) return NULL;
Py_INCREF(fake_module);
cached_type = (PyTypeObject*) PyObject_GetAttrString(fake_module, type->tp_name);
if (cached_type) {
if (!PyType_Check((PyObject*)cached_type)) {
PyErr_Format(PyExc_TypeError,
"Shared Cython type %.200s is not a type object",
type->tp_name);
goto bad;
}
if (cached_type->tp_basicsize != type->tp_basicsize) {
PyErr_Format(PyExc_TypeError,
"Shared Cython type %.200s has the wrong size, try recompiling",
type->tp_name);
goto bad;
}
} else {
if (!PyErr_ExceptionMatches(PyExc_AttributeError)) goto bad;
PyErr_Clear();
if (PyType_Ready(type) < 0) goto bad;
if (PyObject_SetAttrString(fake_module, type->tp_name, (PyObject*) type) < 0)
goto bad;
Py_INCREF(type);
cached_type = type;
}
done:
Py_DECREF(fake_module);
return cached_type;
bad:
Py_XDECREF(cached_type);
cached_type = NULL;
goto done;
}
static PyObject *
__Pyx_CyFunction_get_doc(__pyx_CyFunctionObject *op, CYTHON_UNUSED void *closure)
{
if (unlikely(op->func_doc == NULL)) {
if (op->func.m_ml->ml_doc) {
#if PY_MAJOR_VERSION >= 3
op->func_doc = PyUnicode_FromString(op->func.m_ml->ml_doc);
#else
op->func_doc = PyString_FromString(op->func.m_ml->ml_doc);
#endif
if (unlikely(op->func_doc == NULL))
return NULL;
} else {
Py_INCREF(Py_None);
return Py_None;
}
}
Py_INCREF(op->func_doc);
return op->func_doc;
}
static int
__Pyx_CyFunction_set_doc(__pyx_CyFunctionObject *op, PyObject *value)
{
PyObject *tmp = op->func_doc;
if (value == NULL)
value = Py_None; /* Mark as deleted */
Py_INCREF(value);
op->func_doc = value;
Py_XDECREF(tmp);
return 0;
}
static PyObject *
__Pyx_CyFunction_get_name(__pyx_CyFunctionObject *op)
{
if (unlikely(op->func_name == NULL)) {
#if PY_MAJOR_VERSION >= 3
op->func_name = PyUnicode_InternFromString(op->func.m_ml->ml_name);
#else
op->func_name = PyString_InternFromString(op->func.m_ml->ml_name);
#endif
if (unlikely(op->func_name == NULL))
return NULL;
}
Py_INCREF(op->func_name);
return op->func_name;
}
static int
__Pyx_CyFunction_set_name(__pyx_CyFunctionObject *op, PyObject *value)
{
PyObject *tmp;
#if PY_MAJOR_VERSION >= 3
if (unlikely(value == NULL || !PyUnicode_Check(value))) {
#else
if (unlikely(value == NULL || !PyString_Check(value))) {
#endif
PyErr_SetString(PyExc_TypeError,
"__name__ must be set to a string object");
return -1;
}
tmp = op->func_name;
Py_INCREF(value);
op->func_name = value;
Py_XDECREF(tmp);
return 0;
}
static PyObject *
__Pyx_CyFunction_get_qualname(__pyx_CyFunctionObject *op)
{
Py_INCREF(op->func_qualname);
return op->func_qualname;
}
static int
__Pyx_CyFunction_set_qualname(__pyx_CyFunctionObject *op, PyObject *value)
{
PyObject *tmp;
#if PY_MAJOR_VERSION >= 3
if (unlikely(value == NULL || !PyUnicode_Check(value))) {
#else
if (unlikely(value == NULL || !PyString_Check(value))) {
#endif
PyErr_SetString(PyExc_TypeError,
"__qualname__ must be set to a string object");
return -1;
}
tmp = op->func_qualname;
Py_INCREF(value);
op->func_qualname = value;
Py_XDECREF(tmp);
return 0;
}
static PyObject *
__Pyx_CyFunction_get_self(__pyx_CyFunctionObject *m, CYTHON_UNUSED void *closure)
{
PyObject *self;
self = m->func_closure;
if (self == NULL)
self = Py_None;
Py_INCREF(self);
return self;
}
static PyObject *
__Pyx_CyFunction_get_dict(__pyx_CyFunctionObject *op)
{
if (unlikely(op->func_dict == NULL)) {
op->func_dict = PyDict_New();
if (unlikely(op->func_dict == NULL))
return NULL;
}
Py_INCREF(op->func_dict);
return op->func_dict;
}
static int
__Pyx_CyFunction_set_dict(__pyx_CyFunctionObject *op, PyObject *value)
{
PyObject *tmp;
if (unlikely(value == NULL)) {
PyErr_SetString(PyExc_TypeError,
"function's dictionary may not be deleted");
return -1;
}
if (unlikely(!PyDict_Check(value))) {
PyErr_SetString(PyExc_TypeError,
"setting function's dictionary to a non-dict");
return -1;
}
tmp = op->func_dict;
Py_INCREF(value);
op->func_dict = value;
Py_XDECREF(tmp);
return 0;
}
static PyObject *
__Pyx_CyFunction_get_globals(__pyx_CyFunctionObject *op)
{
Py_INCREF(op->func_globals);
return op->func_globals;
}
static PyObject *
__Pyx_CyFunction_get_closure(CYTHON_UNUSED __pyx_CyFunctionObject *op)
{
Py_INCREF(Py_None);
return Py_None;
}
static PyObject *
__Pyx_CyFunction_get_code(__pyx_CyFunctionObject *op)
{
PyObject* result = (op->func_code) ? op->func_code : Py_None;
Py_INCREF(result);
return result;
}
static int
__Pyx_CyFunction_init_defaults(__pyx_CyFunctionObject *op) {
PyObject *res = op->defaults_getter((PyObject *) op);
if (unlikely(!res))
return -1;
op->defaults_tuple = PyTuple_GET_ITEM(res, 0);
Py_INCREF(op->defaults_tuple);
op->defaults_kwdict = PyTuple_GET_ITEM(res, 1);
Py_INCREF(op->defaults_kwdict);
Py_DECREF(res);
return 0;
}
static int
__Pyx_CyFunction_set_defaults(__pyx_CyFunctionObject *op, PyObject* value) {
PyObject* tmp;
if (!value) {
value = Py_None;
} else if (value != Py_None && !PyTuple_Check(value)) {
PyErr_SetString(PyExc_TypeError,
"__defaults__ must be set to a tuple object");
return -1;
}
Py_INCREF(value);
tmp = op->defaults_tuple;
op->defaults_tuple = value;
Py_XDECREF(tmp);
return 0;
}
static PyObject *
__Pyx_CyFunction_get_defaults(__pyx_CyFunctionObject *op) {
PyObject* result = op->defaults_tuple;
if (unlikely(!result)) {
if (op->defaults_getter) {
if (__Pyx_CyFunction_init_defaults(op) < 0) return NULL;
result = op->defaults_tuple;
} else {
result = Py_None;
}
}
Py_INCREF(result);
return result;
}
static int
__Pyx_CyFunction_set_kwdefaults(__pyx_CyFunctionObject *op, PyObject* value) {
PyObject* tmp;
if (!value) {
value = Py_None;
} else if (value != Py_None && !PyDict_Check(value)) {
PyErr_SetString(PyExc_TypeError,
"__kwdefaults__ must be set to a dict object");
return -1;
}
Py_INCREF(value);
tmp = op->defaults_kwdict;
op->defaults_kwdict = value;
Py_XDECREF(tmp);
return 0;
}
static PyObject *
__Pyx_CyFunction_get_kwdefaults(__pyx_CyFunctionObject *op) {
PyObject* result = op->defaults_kwdict;
if (unlikely(!result)) {
if (op->defaults_getter) {
if (__Pyx_CyFunction_init_defaults(op) < 0) return NULL;
result = op->defaults_kwdict;
} else {
result = Py_None;
}
}
Py_INCREF(result);
return result;
}
static int
__Pyx_CyFunction_set_annotations(__pyx_CyFunctionObject *op, PyObject* value) {
PyObject* tmp;
if (!value || value == Py_None) {
value = NULL;
} else if (!PyDict_Check(value)) {
PyErr_SetString(PyExc_TypeError,
"__annotations__ must be set to a dict object");
return -1;
}
Py_XINCREF(value);
tmp = op->func_annotations;
op->func_annotations = value;
Py_XDECREF(tmp);
return 0;
}
static PyObject *
__Pyx_CyFunction_get_annotations(__pyx_CyFunctionObject *op) {
PyObject* result = op->func_annotations;
if (unlikely(!result)) {
result = PyDict_New();
if (unlikely(!result)) return NULL;
op->func_annotations = result;
}
Py_INCREF(result);
return result;
}
static PyGetSetDef __pyx_CyFunction_getsets[] = {
{(char *) "func_doc", (getter)__Pyx_CyFunction_get_doc, (setter)__Pyx_CyFunction_set_doc, 0, 0},
{(char *) "__doc__", (getter)__Pyx_CyFunction_get_doc, (setter)__Pyx_CyFunction_set_doc, 0, 0},
{(char *) "func_name", (getter)__Pyx_CyFunction_get_name, (setter)__Pyx_CyFunction_set_name, 0, 0},
{(char *) "__name__", (getter)__Pyx_CyFunction_get_name, (setter)__Pyx_CyFunction_set_name, 0, 0},
{(char *) "__qualname__", (getter)__Pyx_CyFunction_get_qualname, (setter)__Pyx_CyFunction_set_qualname, 0, 0},
{(char *) "__self__", (getter)__Pyx_CyFunction_get_self, 0, 0, 0},
{(char *) "func_dict", (getter)__Pyx_CyFunction_get_dict, (setter)__Pyx_CyFunction_set_dict, 0, 0},
{(char *) "__dict__", (getter)__Pyx_CyFunction_get_dict, (setter)__Pyx_CyFunction_set_dict, 0, 0},
{(char *) "func_globals", (getter)__Pyx_CyFunction_get_globals, 0, 0, 0},
{(char *) "__globals__", (getter)__Pyx_CyFunction_get_globals, 0, 0, 0},
{(char *) "func_closure", (getter)__Pyx_CyFunction_get_closure, 0, 0, 0},
{(char *) "__closure__", (getter)__Pyx_CyFunction_get_closure, 0, 0, 0},
{(char *) "func_code", (getter)__Pyx_CyFunction_get_code, 0, 0, 0},
{(char *) "__code__", (getter)__Pyx_CyFunction_get_code, 0, 0, 0},
{(char *) "func_defaults", (getter)__Pyx_CyFunction_get_defaults, (setter)__Pyx_CyFunction_set_defaults, 0, 0},
{(char *) "__defaults__", (getter)__Pyx_CyFunction_get_defaults, (setter)__Pyx_CyFunction_set_defaults, 0, 0},
{(char *) "__kwdefaults__", (getter)__Pyx_CyFunction_get_kwdefaults, (setter)__Pyx_CyFunction_set_kwdefaults, 0, 0},
{(char *) "__annotations__", (getter)__Pyx_CyFunction_get_annotations, (setter)__Pyx_CyFunction_set_annotations, 0, 0},
{0, 0, 0, 0, 0}
};
#ifndef PY_WRITE_RESTRICTED /* < Py2.5 */
#define PY_WRITE_RESTRICTED WRITE_RESTRICTED
#endif
static PyMemberDef __pyx_CyFunction_members[] = {
{(char *) "__module__", T_OBJECT, offsetof(__pyx_CyFunctionObject, func.m_module), PY_WRITE_RESTRICTED, 0},
{0, 0, 0, 0, 0}
};
static PyObject *
__Pyx_CyFunction_reduce(__pyx_CyFunctionObject *m, CYTHON_UNUSED PyObject *args)
{
#if PY_MAJOR_VERSION >= 3
return PyUnicode_FromString(m->func.m_ml->ml_name);
#else
return PyString_FromString(m->func.m_ml->ml_name);
#endif
}
static PyMethodDef __pyx_CyFunction_methods[] = {
{__Pyx_NAMESTR("__reduce__"), (PyCFunction)__Pyx_CyFunction_reduce, METH_VARARGS, 0},
{0, 0, 0, 0}
};
static PyObject *__Pyx_CyFunction_New(PyTypeObject *type, PyMethodDef *ml, int flags, PyObject* qualname,
PyObject *closure, PyObject *module, PyObject* globals, PyObject* code) {
__pyx_CyFunctionObject *op = PyObject_GC_New(__pyx_CyFunctionObject, type);
if (op == NULL)
return NULL;
op->flags = flags;
op->func_weakreflist = NULL;
op->func.m_ml = ml;
op->func.m_self = (PyObject *) op;
Py_XINCREF(closure);
op->func_closure = closure;
Py_XINCREF(module);
op->func.m_module = module;
op->func_dict = NULL;
op->func_name = NULL;
Py_INCREF(qualname);
op->func_qualname = qualname;
op->func_doc = NULL;
op->func_classobj = NULL;
op->func_globals = globals;
Py_INCREF(op->func_globals);
Py_XINCREF(code);
op->func_code = code;
op->defaults_pyobjects = 0;
op->defaults = NULL;
op->defaults_tuple = NULL;
op->defaults_kwdict = NULL;
op->defaults_getter = NULL;
op->func_annotations = NULL;
PyObject_GC_Track(op);
return (PyObject *) op;
}
static int
__Pyx_CyFunction_clear(__pyx_CyFunctionObject *m)
{
Py_CLEAR(m->func_closure);
Py_CLEAR(m->func.m_module);
Py_CLEAR(m->func_dict);
Py_CLEAR(m->func_name);
Py_CLEAR(m->func_qualname);
Py_CLEAR(m->func_doc);
Py_CLEAR(m->func_globals);
Py_CLEAR(m->func_code);
Py_CLEAR(m->func_classobj);
Py_CLEAR(m->defaults_tuple);
Py_CLEAR(m->defaults_kwdict);
Py_CLEAR(m->func_annotations);
if (m->defaults) {
PyObject **pydefaults = __Pyx_CyFunction_Defaults(PyObject *, m);
int i;
for (i = 0; i < m->defaults_pyobjects; i++)
Py_XDECREF(pydefaults[i]);
PyMem_Free(m->defaults);
m->defaults = NULL;
}
return 0;
}
static void __Pyx_CyFunction_dealloc(__pyx_CyFunctionObject *m)
{
PyObject_GC_UnTrack(m);
if (m->func_weakreflist != NULL)
PyObject_ClearWeakRefs((PyObject *) m);
__Pyx_CyFunction_clear(m);
PyObject_GC_Del(m);
}
static int __Pyx_CyFunction_traverse(__pyx_CyFunctionObject *m, visitproc visit, void *arg)
{
Py_VISIT(m->func_closure);
Py_VISIT(m->func.m_module);
Py_VISIT(m->func_dict);
Py_VISIT(m->func_name);
Py_VISIT(m->func_qualname);
Py_VISIT(m->func_doc);
Py_VISIT(m->func_globals);
Py_VISIT(m->func_code);
Py_VISIT(m->func_classobj);
Py_VISIT(m->defaults_tuple);
Py_VISIT(m->defaults_kwdict);
if (m->defaults) {
PyObject **pydefaults = __Pyx_CyFunction_Defaults(PyObject *, m);
int i;
for (i = 0; i < m->defaults_pyobjects; i++)
Py_VISIT(pydefaults[i]);
}
return 0;
}
static PyObject *__Pyx_CyFunction_descr_get(PyObject *func, PyObject *obj, PyObject *type)
{
__pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func;
if (m->flags & __Pyx_CYFUNCTION_STATICMETHOD) {
Py_INCREF(func);
return func;
}
if (m->flags & __Pyx_CYFUNCTION_CLASSMETHOD) {
if (type == NULL)
type = (PyObject *)(Py_TYPE(obj));
return PyMethod_New(func,
type, (PyObject *)(Py_TYPE(type)));
}
if (obj == Py_None)
obj = NULL;
return PyMethod_New(func, obj, type);
}
static PyObject*
__Pyx_CyFunction_repr(__pyx_CyFunctionObject *op)
{
#if PY_MAJOR_VERSION >= 3
return PyUnicode_FromFormat("<cyfunction %U at %p>",
op->func_qualname, (void *)op);
#else
return PyString_FromFormat("<cyfunction %s at %p>",
PyString_AsString(op->func_qualname), (void *)op);
#endif
}
#if CYTHON_COMPILING_IN_PYPY
static PyObject * __Pyx_CyFunction_Call(PyObject *func, PyObject *arg, PyObject *kw) {
PyCFunctionObject* f = (PyCFunctionObject*)func;
PyCFunction meth = PyCFunction_GET_FUNCTION(func);
PyObject *self = PyCFunction_GET_SELF(func);
Py_ssize_t size;
switch (PyCFunction_GET_FLAGS(func) & ~(METH_CLASS | METH_STATIC | METH_COEXIST)) {
case METH_VARARGS:
if (likely(kw == NULL) || PyDict_Size(kw) == 0)
return (*meth)(self, arg);
break;
case METH_VARARGS | METH_KEYWORDS:
return (*(PyCFunctionWithKeywords)meth)(self, arg, kw);
case METH_NOARGS:
if (likely(kw == NULL) || PyDict_Size(kw) == 0) {
size = PyTuple_GET_SIZE(arg);
if (size == 0)
return (*meth)(self, NULL);
PyErr_Format(PyExc_TypeError,
"%.200s() takes no arguments (%zd given)",
f->m_ml->ml_name, size);
return NULL;
}
break;
case METH_O:
if (likely(kw == NULL) || PyDict_Size(kw) == 0) {
size = PyTuple_GET_SIZE(arg);
if (size == 1)
return (*meth)(self, PyTuple_GET_ITEM(arg, 0));
PyErr_Format(PyExc_TypeError,
"%.200s() takes exactly one argument (%zd given)",
f->m_ml->ml_name, size);
return NULL;
}
break;
default:
PyErr_SetString(PyExc_SystemError, "Bad call flags in "
"__Pyx_CyFunction_Call. METH_OLDARGS is no "
"longer supported!");
return NULL;
}
PyErr_Format(PyExc_TypeError, "%.200s() takes no keyword arguments",
f->m_ml->ml_name);
return NULL;
}
#else
static PyObject * __Pyx_CyFunction_Call(PyObject *func, PyObject *arg, PyObject *kw) {
return PyCFunction_Call(func, arg, kw);
}
#endif
static PyTypeObject __pyx_CyFunctionType_type = {
PyVarObject_HEAD_INIT(0, 0)
__Pyx_NAMESTR("cython_function_or_method"), /*tp_name*/
sizeof(__pyx_CyFunctionObject), /*tp_basicsize*/
0, /*tp_itemsize*/
(destructor) __Pyx_CyFunction_dealloc, /*tp_dealloc*/
0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
#if PY_MAJOR_VERSION < 3
0, /*tp_compare*/
#else
0, /*reserved*/
#endif
(reprfunc) __Pyx_CyFunction_repr, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
0, /*tp_as_mapping*/
0, /*tp_hash*/
__Pyx_CyFunction_Call, /*tp_call*/
0, /*tp_str*/
0, /*tp_getattro*/
0, /*tp_setattro*/
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC, /* tp_flags*/
0, /*tp_doc*/
(traverseproc) __Pyx_CyFunction_traverse, /*tp_traverse*/
(inquiry) __Pyx_CyFunction_clear, /*tp_clear*/
0, /*tp_richcompare*/
offsetof(__pyx_CyFunctionObject, func_weakreflist), /* tp_weaklistoffse */
0, /*tp_iter*/
0, /*tp_iternext*/
__pyx_CyFunction_methods, /*tp_methods*/
__pyx_CyFunction_members, /*tp_members*/
__pyx_CyFunction_getsets, /*tp_getset*/
0, /*tp_base*/
0, /*tp_dict*/
__Pyx_CyFunction_descr_get, /*tp_descr_get*/
0, /*tp_descr_set*/
offsetof(__pyx_CyFunctionObject, func_dict),/*tp_dictoffset*/
0, /*tp_init*/
0, /*tp_alloc*/
0, /*tp_new*/
0, /*tp_free*/
0, /*tp_is_gc*/
0, /*tp_bases*/
0, /*tp_mro*/
0, /*tp_cache*/
0, /*tp_subclasses*/
0, /*tp_weaklist*/
0, /*tp_del*/
#if PY_VERSION_HEX >= 0x02060000
0, /*tp_version_tag*/
#endif
#if PY_VERSION_HEX >= 0x030400a1
0, /*tp_finalize*/
#endif
};
static int __Pyx_CyFunction_init(void) {
#if !CYTHON_COMPILING_IN_PYPY
__pyx_CyFunctionType_type.tp_call = PyCFunction_Call;
#endif
__pyx_CyFunctionType = __Pyx_FetchCommonType(&__pyx_CyFunctionType_type);
if (__pyx_CyFunctionType == NULL) {
return -1;
}
return 0;
}
static CYTHON_INLINE void *__Pyx_CyFunction_InitDefaults(PyObject *func, size_t size, int pyobjects) {
__pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func;
m->defaults = PyMem_Malloc(size);
if (!m->defaults)
return PyErr_NoMemory();
memset(m->defaults, 0, size);
m->defaults_pyobjects = pyobjects;
return m->defaults;
}
static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsTuple(PyObject *func, PyObject *tuple) {
__pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func;
m->defaults_tuple = tuple;
Py_INCREF(tuple);
}
static CYTHON_INLINE void __Pyx_CyFunction_SetDefaultsKwDict(PyObject *func, PyObject *dict) {
__pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func;
m->defaults_kwdict = dict;
Py_INCREF(dict);
}
static CYTHON_INLINE void __Pyx_CyFunction_SetAnnotationsDict(PyObject *func, PyObject *dict) {
__pyx_CyFunctionObject *m = (__pyx_CyFunctionObject *) func;
m->func_annotations = dict;
Py_INCREF(dict);
}
static PyObject *
__pyx_FusedFunction_New(PyTypeObject *type, PyMethodDef *ml, int flags,
PyObject *qualname, PyObject *self,
PyObject *module, PyObject *globals,
PyObject *code)
{
__pyx_FusedFunctionObject *fusedfunc =
(__pyx_FusedFunctionObject *) __Pyx_CyFunction_New(type, ml, flags, qualname,
self, module, globals, code);
if (!fusedfunc)
return NULL;
fusedfunc->__signatures__ = NULL;
fusedfunc->type = NULL;
fusedfunc->self = NULL;
return (PyObject *) fusedfunc;
}
static void __pyx_FusedFunction_dealloc(__pyx_FusedFunctionObject *self) {
__pyx_FusedFunction_clear(self);
__pyx_FusedFunctionType->tp_free((PyObject *) self);
}
static int
__pyx_FusedFunction_traverse(__pyx_FusedFunctionObject *self,
visitproc visit,
void *arg)
{
Py_VISIT(self->self);
Py_VISIT(self->type);
Py_VISIT(self->__signatures__);
return __Pyx_CyFunction_traverse((__pyx_CyFunctionObject *) self, visit, arg);
}
static int
__pyx_FusedFunction_clear(__pyx_FusedFunctionObject *self)
{
Py_CLEAR(self->self);
Py_CLEAR(self->type);
Py_CLEAR(self->__signatures__);
return __Pyx_CyFunction_clear((__pyx_CyFunctionObject *) self);
}
static PyObject *
__pyx_FusedFunction_descr_get(PyObject *self, PyObject *obj, PyObject *type)
{
__pyx_FusedFunctionObject *func, *meth;
func = (__pyx_FusedFunctionObject *) self;
if (func->self || func->func.flags & __Pyx_CYFUNCTION_STATICMETHOD) {
Py_INCREF(self);
return self;
}
if (obj == Py_None)
obj = NULL;
meth = (__pyx_FusedFunctionObject *) __pyx_FusedFunction_NewEx(
((PyCFunctionObject *) func)->m_ml,
((__pyx_CyFunctionObject *) func)->flags,
((__pyx_CyFunctionObject *) func)->func_qualname,
((__pyx_CyFunctionObject *) func)->func_closure,
((PyCFunctionObject *) func)->m_module,
((__pyx_CyFunctionObject *) func)->func_globals,
((__pyx_CyFunctionObject *) func)->func_code);
if (!meth)
return NULL;
Py_XINCREF(func->func.func_classobj);
meth->func.func_classobj = func->func.func_classobj;
Py_XINCREF(func->__signatures__);
meth->__signatures__ = func->__signatures__;
Py_XINCREF(type);
meth->type = type;
Py_XINCREF(func->func.defaults_tuple);
meth->func.defaults_tuple = func->func.defaults_tuple;
if (func->func.flags & __Pyx_CYFUNCTION_CLASSMETHOD)
obj = type;
Py_XINCREF(obj);
meth->self = obj;
return (PyObject *) meth;
}
static PyObject *
_obj_to_str(PyObject *obj)
{
if (PyType_Check(obj))
return PyObject_GetAttr(obj, __pyx_n_s_name_2);
else
return PyObject_Str(obj);
}
static PyObject *
__pyx_FusedFunction_getitem(__pyx_FusedFunctionObject *self, PyObject *idx)
{
PyObject *signature = NULL;
PyObject *unbound_result_func;
PyObject *result_func = NULL;
if (self->__signatures__ == NULL) {
PyErr_SetString(PyExc_TypeError, "Function is not fused");
return NULL;
}
if (PyTuple_Check(idx)) {
PyObject *list = PyList_New(0);
Py_ssize_t n = PyTuple_GET_SIZE(idx);
PyObject *string = NULL;
PyObject *sep = NULL;
int i;
if (!list)
return NULL;
for (i = 0; i < n; i++) {
PyObject *item = PyTuple_GET_ITEM(idx, i);
string = _obj_to_str(item);
if (!string || PyList_Append(list, string) < 0)
goto __pyx_err;
Py_DECREF(string);
}
sep = PyUnicode_FromString("|");
if (sep)
signature = PyUnicode_Join(sep, list);
__pyx_err:
;
Py_DECREF(list);
Py_XDECREF(sep);
} else {
signature = _obj_to_str(idx);
}
if (!signature)
return NULL;
unbound_result_func = PyObject_GetItem(self->__signatures__, signature);
if (unbound_result_func) {
if (self->self || self->type) {
__pyx_FusedFunctionObject *unbound = (__pyx_FusedFunctionObject *) unbound_result_func;
Py_CLEAR(unbound->func.func_classobj);
Py_XINCREF(self->func.func_classobj);
unbound->func.func_classobj = self->func.func_classobj;
result_func = __pyx_FusedFunction_descr_get(unbound_result_func,
self->self, self->type);
} else {
result_func = unbound_result_func;
Py_INCREF(result_func);
}
}
Py_DECREF(signature);
Py_XDECREF(unbound_result_func);
return result_func;
}
static PyObject *
__pyx_FusedFunction_callfunction(PyObject *func, PyObject *args, PyObject *kw)
{
__pyx_CyFunctionObject *cyfunc = (__pyx_CyFunctionObject *) func;
PyObject *result;
int static_specialized = (cyfunc->flags & __Pyx_CYFUNCTION_STATICMETHOD &&
!((__pyx_FusedFunctionObject *) func)->__signatures__);
if (cyfunc->flags & __Pyx_CYFUNCTION_CCLASS && !static_specialized) {
Py_ssize_t argc;
PyObject *new_args;
PyObject *self;
PyObject *m_self;
argc = PyTuple_GET_SIZE(args);
new_args = PyTuple_GetSlice(args, 1, argc);
if (!new_args)
return NULL;
self = PyTuple_GetItem(args, 0);
if (!self)
return NULL;
m_self = cyfunc->func.m_self;
cyfunc->func.m_self = self;
result = __Pyx_CyFunction_Call(func, new_args, kw);
cyfunc->func.m_self = m_self;
Py_DECREF(new_args);
} else {
result = __Pyx_CyFunction_Call(func, args, kw);
}
return result;
}
/* Note: the 'self' from method binding is passed in in the args tuple,
whereas PyCFunctionObject's m_self is passed in as the first
argument to the C function. For extension methods we need
to pass 'self' as 'm_self' and not as the first element of the
args tuple.
*/
static PyObject *
__pyx_FusedFunction_call(PyObject *func, PyObject *args, PyObject *kw)
{
__pyx_FusedFunctionObject *binding_func = (__pyx_FusedFunctionObject *) func;
Py_ssize_t argc = PyTuple_GET_SIZE(args);
PyObject *new_args = NULL;
__pyx_FusedFunctionObject *new_func = NULL;
PyObject *result = NULL;
PyObject *self = NULL;
int is_staticmethod = binding_func->func.flags & __Pyx_CYFUNCTION_STATICMETHOD;
int is_classmethod = binding_func->func.flags & __Pyx_CYFUNCTION_CLASSMETHOD;
if (binding_func->self) {
Py_ssize_t i;
new_args = PyTuple_New(argc + 1);
if (!new_args)
return NULL;
self = binding_func->self;
Py_INCREF(self);
PyTuple_SET_ITEM(new_args, 0, self);
for (i = 0; i < argc; i++) {
PyObject *item = PyTuple_GET_ITEM(args, i);
Py_INCREF(item);
PyTuple_SET_ITEM(new_args, i + 1, item);
}
args = new_args;
} else if (binding_func->type) {
if (argc < 1) {
PyErr_SetString(PyExc_TypeError, "Need at least one argument, 0 given.");
return NULL;
}
self = PyTuple_GET_ITEM(args, 0);
}
if (self && !is_classmethod && !is_staticmethod &&
!PyObject_IsInstance(self, binding_func->type)) {
PyErr_Format(PyExc_TypeError,
"First argument should be of type %.200s, got %.200s.",
((PyTypeObject *) binding_func->type)->tp_name,
self->ob_type->tp_name);
goto __pyx_err;
}
if (binding_func->__signatures__) {
PyObject *tup = PyTuple_Pack(4, binding_func->__signatures__, args,
kw == NULL ? Py_None : kw,
binding_func->func.defaults_tuple);
if (!tup)
goto __pyx_err;
new_func = (__pyx_FusedFunctionObject *) __pyx_FusedFunction_callfunction(func, tup, NULL);
Py_DECREF(tup);
if (!new_func)
goto __pyx_err;
Py_XINCREF(binding_func->func.func_classobj);
Py_CLEAR(new_func->func.func_classobj);
new_func->func.func_classobj = binding_func->func.func_classobj;
func = (PyObject *) new_func;
}
result = __pyx_FusedFunction_callfunction(func, args, kw);
__pyx_err:
Py_XDECREF(new_args);
Py_XDECREF((PyObject *) new_func);
return result;
}
static PyMemberDef __pyx_FusedFunction_members[] = {
{(char *) "__signatures__",
T_OBJECT,
offsetof(__pyx_FusedFunctionObject, __signatures__),
READONLY,
__Pyx_DOCSTR(0)},
{0, 0, 0, 0, 0},
};
static PyMappingMethods __pyx_FusedFunction_mapping_methods = {
0,
(binaryfunc) __pyx_FusedFunction_getitem,
0,
};
static PyTypeObject __pyx_FusedFunctionType_type = {
PyVarObject_HEAD_INIT(0, 0)
__Pyx_NAMESTR("fused_cython_function"), /*tp_name*/
sizeof(__pyx_FusedFunctionObject), /*tp_basicsize*/
0, /*tp_itemsize*/
(destructor) __pyx_FusedFunction_dealloc, /*tp_dealloc*/
0, /*tp_print*/
0, /*tp_getattr*/
0, /*tp_setattr*/
#if PY_MAJOR_VERSION < 3
0, /*tp_compare*/
#else
0, /*reserved*/
#endif
0, /*tp_repr*/
0, /*tp_as_number*/
0, /*tp_as_sequence*/
&__pyx_FusedFunction_mapping_methods, /*tp_as_mapping*/
0, /*tp_hash*/
(ternaryfunc) __pyx_FusedFunction_call, /*tp_call*/
0, /*tp_str*/
0, /*tp_getattro*/
0, /*tp_setattro*/
0, /*tp_as_buffer*/
Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_BASETYPE, /* tp_flags*/
0, /*tp_doc*/
(traverseproc) __pyx_FusedFunction_traverse, /*tp_traverse*/
(inquiry) __pyx_FusedFunction_clear,/*tp_clear*/
0, /*tp_richcompare*/
0, /*tp_weaklistoffset*/
0, /*tp_iter*/
0, /*tp_iternext*/
0, /*tp_methods*/
__pyx_FusedFunction_members, /*tp_members*/
__pyx_CyFunction_getsets, /*tp_getset*/
&__pyx_CyFunctionType_type, /*tp_base*/
0, /*tp_dict*/
__pyx_FusedFunction_descr_get, /*tp_descr_get*/
0, /*tp_descr_set*/
0, /*tp_dictoffset*/
0, /*tp_init*/
0, /*tp_alloc*/
0, /*tp_new*/
0, /*tp_free*/
0, /*tp_is_gc*/
0, /*tp_bases*/
0, /*tp_mro*/
0, /*tp_cache*/
0, /*tp_subclasses*/
0, /*tp_weaklist*/
0, /*tp_del*/
#if PY_VERSION_HEX >= 0x02060000
0, /*tp_version_tag*/
#endif
#if PY_VERSION_HEX >= 0x030400a1
0, /*tp_finalize*/
#endif
};
static int __pyx_FusedFunction_init(void) {
__pyx_FusedFunctionType = __Pyx_FetchCommonType(&__pyx_FusedFunctionType_type);
if (__pyx_FusedFunctionType == NULL) {
return -1;
}
return 0;
}
static int
__pyx_typeinfo_cmp(__Pyx_TypeInfo *a, __Pyx_TypeInfo *b)
{
int i;
if (!a || !b)
return 0;
if (a == b)
return 1;
if (a->size != b->size || a->typegroup != b->typegroup ||
a->is_unsigned != b->is_unsigned || a->ndim != b->ndim) {
if (a->typegroup == 'H' || b->typegroup == 'H') {
return a->size == b->size;
} else {
return 0;
}
}
if (a->ndim) {
for (i = 0; i < a->ndim; i++)
if (a->arraysize[i] != b->arraysize[i])
return 0;
}
if (a->typegroup == 'S') {
if (a->flags != b->flags)
return 0;
if (a->fields || b->fields) {
if (!(a->fields && b->fields))
return 0;
for (i = 0; a->fields[i].type && b->fields[i].type; i++) {
__Pyx_StructField *field_a = a->fields + i;
__Pyx_StructField *field_b = b->fields + i;
if (field_a->offset != field_b->offset ||
!__pyx_typeinfo_cmp(field_a->type, field_b->type))
return 0;
}
return !a->fields[i].type && !b->fields[i].type;
}
}
return 1;
}
static int
__pyx_check_strides(Py_buffer *buf, int dim, int ndim, int spec)
{
if (buf->shape[dim] <= 1)
return 1;
if (buf->strides) {
if (spec & __Pyx_MEMVIEW_CONTIG) {
if (spec & (__Pyx_MEMVIEW_PTR|__Pyx_MEMVIEW_FULL)) {
if (buf->strides[dim] != sizeof(void *)) {
PyErr_Format(PyExc_ValueError,
"Buffer is not indirectly contiguous "
"in dimension %d.", dim);
goto fail;
}
} else if (buf->strides[dim] != buf->itemsize) {
PyErr_SetString(PyExc_ValueError,
"Buffer and memoryview are not contiguous "
"in the same dimension.");
goto fail;
}
}
if (spec & __Pyx_MEMVIEW_FOLLOW) {
Py_ssize_t stride = buf->strides[dim];
if (stride < 0)
stride = -stride;
if (stride < buf->itemsize) {
PyErr_SetString(PyExc_ValueError,
"Buffer and memoryview are not contiguous "
"in the same dimension.");
goto fail;
}
}
} else {
if (spec & __Pyx_MEMVIEW_CONTIG && dim != ndim - 1) {
PyErr_Format(PyExc_ValueError,
"C-contiguous buffer is not contiguous in "
"dimension %d", dim);
goto fail;
} else if (spec & (__Pyx_MEMVIEW_PTR)) {
PyErr_Format(PyExc_ValueError,
"C-contiguous buffer is not indirect in "
"dimension %d", dim);
goto fail;
} else if (buf->suboffsets) {
PyErr_SetString(PyExc_ValueError,
"Buffer exposes suboffsets but no strides");
goto fail;
}
}
return 1;
fail:
return 0;
}
static int
__pyx_check_suboffsets(Py_buffer *buf, int dim, CYTHON_UNUSED int ndim, int spec)
{
if (spec & __Pyx_MEMVIEW_DIRECT) {
if (buf->suboffsets && buf->suboffsets[dim] >= 0) {
PyErr_Format(PyExc_ValueError,
"Buffer not compatible with direct access "
"in dimension %d.", dim);
goto fail;
}
}
if (spec & __Pyx_MEMVIEW_PTR) {
if (!buf->suboffsets || (buf->suboffsets && buf->suboffsets[dim] < 0)) {
PyErr_Format(PyExc_ValueError,
"Buffer is not indirectly accessible "
"in dimension %d.", dim);
goto fail;
}
}
return 1;
fail:
return 0;
}
static int
__pyx_verify_contig(Py_buffer *buf, int ndim, int c_or_f_flag)
{
int i;
if (c_or_f_flag & __Pyx_IS_F_CONTIG) {
Py_ssize_t stride = 1;
for (i = 0; i < ndim; i++) {
if (stride * buf->itemsize != buf->strides[i] &&
buf->shape[i] > 1)
{
PyErr_SetString(PyExc_ValueError,
"Buffer not fortran contiguous.");
goto fail;
}
stride = stride * buf->shape[i];
}
} else if (c_or_f_flag & __Pyx_IS_C_CONTIG) {
Py_ssize_t stride = 1;
for (i = ndim - 1; i >- 1; i--) {
if (stride * buf->itemsize != buf->strides[i] &&
buf->shape[i] > 1) {
PyErr_SetString(PyExc_ValueError,
"Buffer not C contiguous.");
goto fail;
}
stride = stride * buf->shape[i];
}
}
return 1;
fail:
return 0;
}
static int __Pyx_ValidateAndInit_memviewslice(
int *axes_specs,
int c_or_f_flag,
int buf_flags,
int ndim,
__Pyx_TypeInfo *dtype,
__Pyx_BufFmt_StackElem stack[],
__Pyx_memviewslice *memviewslice,
PyObject *original_obj)
{
struct __pyx_memoryview_obj *memview, *new_memview;
__Pyx_RefNannyDeclarations
Py_buffer *buf;
int i, spec = 0, retval = -1;
__Pyx_BufFmt_Context ctx;
int from_memoryview = __pyx_memoryview_check(original_obj);
__Pyx_RefNannySetupContext("ValidateAndInit_memviewslice", 0);
if (from_memoryview && __pyx_typeinfo_cmp(dtype, ((struct __pyx_memoryview_obj *)
original_obj)->typeinfo)) {
memview = (struct __pyx_memoryview_obj *) original_obj;
new_memview = NULL;
} else {
memview = (struct __pyx_memoryview_obj *) __pyx_memoryview_new(
original_obj, buf_flags, 0, dtype);
new_memview = memview;
if (unlikely(!memview))
goto fail;
}
buf = &memview->view;
if (buf->ndim != ndim) {
PyErr_Format(PyExc_ValueError,
"Buffer has wrong number of dimensions (expected %d, got %d)",
ndim, buf->ndim);
goto fail;
}
if (new_memview) {
__Pyx_BufFmt_Init(&ctx, stack, dtype);
if (!__Pyx_BufFmt_CheckString(&ctx, buf->format)) goto fail;
}
if ((unsigned) buf->itemsize != dtype->size) {
PyErr_Format(PyExc_ValueError,
"Item size of buffer (%" CYTHON_FORMAT_SSIZE_T "u byte%s) "
"does not match size of '%s' (%" CYTHON_FORMAT_SSIZE_T "u byte%s)",
buf->itemsize,
(buf->itemsize > 1) ? "s" : "",
dtype->name,
dtype->size,
(dtype->size > 1) ? "s" : "");
goto fail;
}
for (i = 0; i < ndim; i++) {
spec = axes_specs[i];
if (!__pyx_check_strides(buf, i, ndim, spec))
goto fail;
if (!__pyx_check_suboffsets(buf, i, ndim, spec))
goto fail;
}
if (buf->strides && !__pyx_verify_contig(buf, ndim, c_or_f_flag))
goto fail;
if (unlikely(__Pyx_init_memviewslice(memview, ndim, memviewslice,
new_memview != NULL) == -1)) {
goto fail;
}
retval = 0;
goto no_fail;
fail:
Py_XDECREF(new_memview);
retval = -1;
no_fail:
__Pyx_RefNannyFinishContext();
return retval;
}
static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dsds_float(PyObject *obj) {
__Pyx_memviewslice result = { 0, 0, { 0 }, { 0 }, { 0 } };
__Pyx_BufFmt_StackElem stack[1];
int axes_specs[] = { (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_STRIDED), (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_STRIDED) };
int retcode;
if (obj == Py_None) {
result.memview = (struct __pyx_memoryview_obj *) Py_None;
return result;
}
retcode = __Pyx_ValidateAndInit_memviewslice(axes_specs, 0,
PyBUF_RECORDS, 2,
&__Pyx_TypeInfo_float, stack,
&result, obj);
if (unlikely(retcode == -1))
goto __pyx_fail;
return result;
__pyx_fail:
result.memview = NULL;
result.data = NULL;
return result;
}
static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dsds_double(PyObject *obj) {
__Pyx_memviewslice result = { 0, 0, { 0 }, { 0 }, { 0 } };
__Pyx_BufFmt_StackElem stack[1];
int axes_specs[] = { (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_STRIDED), (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_STRIDED) };
int retcode;
if (obj == Py_None) {
result.memview = (struct __pyx_memoryview_obj *) Py_None;
return result;
}
retcode = __Pyx_ValidateAndInit_memviewslice(axes_specs, 0,
PyBUF_RECORDS, 2,
&__Pyx_TypeInfo_double, stack,
&result, obj);
if (unlikely(retcode == -1))
goto __pyx_fail;
return result;
__pyx_fail:
result.memview = NULL;
result.data = NULL;
return result;
}
static PyObject *__Pyx_Import(PyObject *name, PyObject *from_list, int level) {
PyObject *empty_list = 0;
PyObject *module = 0;
PyObject *global_dict = 0;
PyObject *empty_dict = 0;
PyObject *list;
#if PY_VERSION_HEX < 0x03030000
PyObject *py_import;
py_import = __Pyx_PyObject_GetAttrStr(__pyx_b, __pyx_n_s_import);
if (!py_import)
goto bad;
#endif
if (from_list)
list = from_list;
else {
empty_list = PyList_New(0);
if (!empty_list)
goto bad;
list = empty_list;
}
global_dict = PyModule_GetDict(__pyx_m);
if (!global_dict)
goto bad;
empty_dict = PyDict_New();
if (!empty_dict)
goto bad;
#if PY_VERSION_HEX >= 0x02050000
{
#if PY_MAJOR_VERSION >= 3
if (level == -1) {
if (strchr(__Pyx_MODULE_NAME, '.')) {
#if PY_VERSION_HEX < 0x03030000
PyObject *py_level = PyInt_FromLong(1);
if (!py_level)
goto bad;
module = PyObject_CallFunctionObjArgs(py_import,
name, global_dict, empty_dict, list, py_level, NULL);
Py_DECREF(py_level);
#else
module = PyImport_ImportModuleLevelObject(
name, global_dict, empty_dict, list, 1);
#endif
if (!module) {
if (!PyErr_ExceptionMatches(PyExc_ImportError))
goto bad;
PyErr_Clear();
}
}
level = 0; /* try absolute import on failure */
}
#endif
if (!module) {
#if PY_VERSION_HEX < 0x03030000
PyObject *py_level = PyInt_FromLong(level);
if (!py_level)
goto bad;
module = PyObject_CallFunctionObjArgs(py_import,
name, global_dict, empty_dict, list, py_level, NULL);
Py_DECREF(py_level);
#else
module = PyImport_ImportModuleLevelObject(
name, global_dict, empty_dict, list, level);
#endif
}
}
#else
if (level>0) {
PyErr_SetString(PyExc_RuntimeError, "Relative import is not supported for Python <=2.4.");
goto bad;
}
module = PyObject_CallFunctionObjArgs(py_import,
name, global_dict, empty_dict, list, NULL);
#endif
bad:
#if PY_VERSION_HEX < 0x03030000
Py_XDECREF(py_import);
#endif
Py_XDECREF(empty_list);
Py_XDECREF(empty_dict);
return module;
}
static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dc_float(PyObject *obj) {
__Pyx_memviewslice result = { 0, 0, { 0 }, { 0 }, { 0 } };
__Pyx_BufFmt_StackElem stack[1];
int axes_specs[] = { (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_CONTIG) };
int retcode;
if (obj == Py_None) {
result.memview = (struct __pyx_memoryview_obj *) Py_None;
return result;
}
retcode = __Pyx_ValidateAndInit_memviewslice(axes_specs, __Pyx_IS_C_CONTIG,
(PyBUF_C_CONTIGUOUS | PyBUF_FORMAT | PyBUF_WRITABLE), 1,
&__Pyx_TypeInfo_float, stack,
&result, obj);
if (unlikely(retcode == -1))
goto __pyx_fail;
return result;
__pyx_fail:
result.memview = NULL;
result.data = NULL;
return result;
}
static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_dc_double(PyObject *obj) {
__Pyx_memviewslice result = { 0, 0, { 0 }, { 0 }, { 0 } };
__Pyx_BufFmt_StackElem stack[1];
int axes_specs[] = { (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_CONTIG) };
int retcode;
if (obj == Py_None) {
result.memview = (struct __pyx_memoryview_obj *) Py_None;
return result;
}
retcode = __Pyx_ValidateAndInit_memviewslice(axes_specs, __Pyx_IS_C_CONTIG,
(PyBUF_C_CONTIGUOUS | PyBUF_FORMAT | PyBUF_WRITABLE), 1,
&__Pyx_TypeInfo_double, stack,
&result, obj);
if (unlikely(retcode == -1))
goto __pyx_fail;
return result;
__pyx_fail:
result.memview = NULL;
result.data = NULL;
return result;
}
#if PY_MAJOR_VERSION < 3
static int __Pyx_GetBuffer(PyObject *obj, Py_buffer *view, int flags) {
#if PY_VERSION_HEX >= 0x02060000
if (PyObject_CheckBuffer(obj)) return PyObject_GetBuffer(obj, view, flags);
#endif
if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) return __pyx_pw_5numpy_7ndarray_1__getbuffer__(obj, view, flags);
if (PyObject_TypeCheck(obj, __pyx_array_type)) return __pyx_array_getbuffer(obj, view, flags);
if (PyObject_TypeCheck(obj, __pyx_memoryview_type)) return __pyx_memoryview_getbuffer(obj, view, flags);
#if PY_VERSION_HEX < 0x02060000
if (obj->ob_type->tp_dict) {
PyObject *getbuffer_cobj = PyObject_GetItem(
obj->ob_type->tp_dict, __pyx_n_s_pyx_getbuffer);
if (getbuffer_cobj) {
getbufferproc func = (getbufferproc) PyCObject_AsVoidPtr(getbuffer_cobj);
Py_DECREF(getbuffer_cobj);
if (!func)
goto fail;
return func(obj, view, flags);
} else {
PyErr_Clear();
}
}
#endif
PyErr_Format(PyExc_TypeError, "'%.200s' does not have the buffer interface", Py_TYPE(obj)->tp_name);
#if PY_VERSION_HEX < 0x02060000
fail:
#endif
return -1;
}
static void __Pyx_ReleaseBuffer(Py_buffer *view) {
PyObject *obj = view->obj;
if (!obj) return;
#if PY_VERSION_HEX >= 0x02060000
if (PyObject_CheckBuffer(obj)) {
PyBuffer_Release(view);
return;
}
#endif
if (PyObject_TypeCheck(obj, __pyx_ptype_5numpy_ndarray)) { __pyx_pw_5numpy_7ndarray_3__releasebuffer__(obj, view); return; }
#if PY_VERSION_HEX < 0x02060000
if (obj->ob_type->tp_dict) {
PyObject *releasebuffer_cobj = PyObject_GetItem(
obj->ob_type->tp_dict, __pyx_n_s_pyx_releasebuffer);
if (releasebuffer_cobj) {
releasebufferproc func = (releasebufferproc) PyCObject_AsVoidPtr(releasebuffer_cobj);
Py_DECREF(releasebuffer_cobj);
if (!func)
goto fail;
func(obj, view);
return;
} else {
PyErr_Clear();
}
}
#endif
goto nofail;
#if PY_VERSION_HEX < 0x02060000
fail:
#endif
PyErr_WriteUnraisable(obj);
nofail:
Py_DECREF(obj);
view->obj = NULL;
}
#endif /* PY_MAJOR_VERSION < 3 */
static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_ds_int(PyObject *obj) {
__Pyx_memviewslice result = { 0, 0, { 0 }, { 0 }, { 0 } };
__Pyx_BufFmt_StackElem stack[1];
int axes_specs[] = { (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_STRIDED) };
int retcode;
if (obj == Py_None) {
result.memview = (struct __pyx_memoryview_obj *) Py_None;
return result;
}
retcode = __Pyx_ValidateAndInit_memviewslice(axes_specs, 0,
PyBUF_RECORDS, 1,
&__Pyx_TypeInfo_int, stack,
&result, obj);
if (unlikely(retcode == -1))
goto __pyx_fail;
return result;
__pyx_fail:
result.memview = NULL;
result.data = NULL;
return result;
}
#define __PYX_VERIFY_RETURN_INT(target_type, func_type, func) \
{ \
func_type value = func(x); \
if (sizeof(target_type) < sizeof(func_type)) { \
if (unlikely(value != (func_type) (target_type) value)) { \
func_type zero = 0; \
PyErr_SetString(PyExc_OverflowError, \
(is_unsigned && unlikely(value < zero)) ? \
"can't convert negative value to " #target_type : \
"value too large to convert to " #target_type); \
return (target_type) -1; \
} \
} \
return (target_type) value; \
}
#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3
#if CYTHON_USE_PYLONG_INTERNALS
#include "longintrepr.h"
#endif
#endif
static CYTHON_INLINE Py_intptr_t __Pyx_PyInt_As_Py_intptr_t(PyObject *x) {
const Py_intptr_t neg_one = (Py_intptr_t) -1, const_zero = 0;
const int is_unsigned = neg_one > const_zero;
#if PY_MAJOR_VERSION < 3
if (likely(PyInt_Check(x))) {
if (sizeof(Py_intptr_t) < sizeof(long)) {
__PYX_VERIFY_RETURN_INT(Py_intptr_t, long, PyInt_AS_LONG)
} else {
long val = PyInt_AS_LONG(x);
if (is_unsigned && unlikely(val < 0)) {
PyErr_SetString(PyExc_OverflowError,
"can't convert negative value to Py_intptr_t");
return (Py_intptr_t) -1;
}
return (Py_intptr_t) val;
}
} else
#endif
if (likely(PyLong_Check(x))) {
if (is_unsigned) {
#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3
#if CYTHON_USE_PYLONG_INTERNALS
if (sizeof(digit) <= sizeof(Py_intptr_t)) {
switch (Py_SIZE(x)) {
case 0: return 0;
case 1: return (Py_intptr_t) ((PyLongObject*)x)->ob_digit[0];
}
}
#endif
#endif
if (unlikely(Py_SIZE(x) < 0)) {
PyErr_SetString(PyExc_OverflowError,
"can't convert negative value to Py_intptr_t");
return (Py_intptr_t) -1;
}
if (sizeof(Py_intptr_t) <= sizeof(unsigned long)) {
__PYX_VERIFY_RETURN_INT(Py_intptr_t, unsigned long, PyLong_AsUnsignedLong)
} else if (sizeof(Py_intptr_t) <= sizeof(unsigned long long)) {
__PYX_VERIFY_RETURN_INT(Py_intptr_t, unsigned long long, PyLong_AsUnsignedLongLong)
}
} else {
#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3
#if CYTHON_USE_PYLONG_INTERNALS
if (sizeof(digit) <= sizeof(Py_intptr_t)) {
switch (Py_SIZE(x)) {
case 0: return 0;
case 1: return +(Py_intptr_t) ((PyLongObject*)x)->ob_digit[0];
case -1: return -(Py_intptr_t) ((PyLongObject*)x)->ob_digit[0];
}
}
#endif
#endif
if (sizeof(Py_intptr_t) <= sizeof(long)) {
__PYX_VERIFY_RETURN_INT(Py_intptr_t, long, PyLong_AsLong)
} else if (sizeof(Py_intptr_t) <= sizeof(long long)) {
__PYX_VERIFY_RETURN_INT(Py_intptr_t, long long, PyLong_AsLongLong)
}
}
{
#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray)
PyErr_SetString(PyExc_RuntimeError,
"_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers");
#else
Py_intptr_t val;
PyObject *v = __Pyx_PyNumber_Int(x);
#if PY_MAJOR_VERSION < 3
if (likely(v) && !PyLong_Check(v)) {
PyObject *tmp = v;
v = PyNumber_Long(tmp);
Py_DECREF(tmp);
}
#endif
if (likely(v)) {
int one = 1; int is_little = (int)*(unsigned char *)&one;
unsigned char *bytes = (unsigned char *)&val;
int ret = _PyLong_AsByteArray((PyLongObject *)v,
bytes, sizeof(val),
is_little, !is_unsigned);
Py_DECREF(v);
if (likely(!ret))
return val;
}
#endif
return (Py_intptr_t) -1;
}
} else {
Py_intptr_t val;
PyObject *tmp = __Pyx_PyNumber_Int(x);
if (!tmp) return (Py_intptr_t) -1;
val = __Pyx_PyInt_As_Py_intptr_t(tmp);
Py_DECREF(tmp);
return val;
}
}
static CYTHON_INLINE __Pyx_memviewslice __Pyx_PyObject_to_MemoryviewSlice_d_dc_double(PyObject *obj) {
__Pyx_memviewslice result = { 0, 0, { 0 }, { 0 }, { 0 } };
__Pyx_BufFmt_StackElem stack[1];
int axes_specs[] = { (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_FOLLOW), (__Pyx_MEMVIEW_DIRECT | __Pyx_MEMVIEW_CONTIG) };
int retcode;
if (obj == Py_None) {
result.memview = (struct __pyx_memoryview_obj *) Py_None;
return result;
}
retcode = __Pyx_ValidateAndInit_memviewslice(axes_specs, __Pyx_IS_C_CONTIG,
(PyBUF_C_CONTIGUOUS | PyBUF_FORMAT | PyBUF_WRITABLE), 2,
&__Pyx_TypeInfo_double, stack,
&result, obj);
if (unlikely(retcode == -1))
goto __pyx_fail;
return result;
__pyx_fail:
result.memview = NULL;
result.data = NULL;
return result;
}
static CYTHON_INLINE PyObject* __Pyx_PyInt_From_long(long value) {
const long neg_one = (long) -1, const_zero = 0;
const int is_unsigned = neg_one > const_zero;
if (is_unsigned) {
if (sizeof(long) < sizeof(long)) {
return PyInt_FromLong((long) value);
} else if (sizeof(long) <= sizeof(unsigned long)) {
return PyLong_FromUnsignedLong((unsigned long) value);
} else if (sizeof(long) <= sizeof(unsigned long long)) {
return PyLong_FromUnsignedLongLong((unsigned long long) value);
}
} else {
if (sizeof(long) <= sizeof(long)) {
return PyInt_FromLong((long) value);
} else if (sizeof(long) <= sizeof(long long)) {
return PyLong_FromLongLong((long long) value);
}
}
{
int one = 1; int little = (int)*(unsigned char *)&one;
unsigned char *bytes = (unsigned char *)&value;
return _PyLong_FromByteArray(bytes, sizeof(long),
little, !is_unsigned);
}
}
#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3
#if CYTHON_USE_PYLONG_INTERNALS
#include "longintrepr.h"
#endif
#endif
static CYTHON_INLINE char __Pyx_PyInt_As_char(PyObject *x) {
const char neg_one = (char) -1, const_zero = 0;
const int is_unsigned = neg_one > const_zero;
#if PY_MAJOR_VERSION < 3
if (likely(PyInt_Check(x))) {
if (sizeof(char) < sizeof(long)) {
__PYX_VERIFY_RETURN_INT(char, long, PyInt_AS_LONG)
} else {
long val = PyInt_AS_LONG(x);
if (is_unsigned && unlikely(val < 0)) {
PyErr_SetString(PyExc_OverflowError,
"can't convert negative value to char");
return (char) -1;
}
return (char) val;
}
} else
#endif
if (likely(PyLong_Check(x))) {
if (is_unsigned) {
#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3
#if CYTHON_USE_PYLONG_INTERNALS
if (sizeof(digit) <= sizeof(char)) {
switch (Py_SIZE(x)) {
case 0: return 0;
case 1: return (char) ((PyLongObject*)x)->ob_digit[0];
}
}
#endif
#endif
if (unlikely(Py_SIZE(x) < 0)) {
PyErr_SetString(PyExc_OverflowError,
"can't convert negative value to char");
return (char) -1;
}
if (sizeof(char) <= sizeof(unsigned long)) {
__PYX_VERIFY_RETURN_INT(char, unsigned long, PyLong_AsUnsignedLong)
} else if (sizeof(char) <= sizeof(unsigned long long)) {
__PYX_VERIFY_RETURN_INT(char, unsigned long long, PyLong_AsUnsignedLongLong)
}
} else {
#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3
#if CYTHON_USE_PYLONG_INTERNALS
if (sizeof(digit) <= sizeof(char)) {
switch (Py_SIZE(x)) {
case 0: return 0;
case 1: return +(char) ((PyLongObject*)x)->ob_digit[0];
case -1: return -(char) ((PyLongObject*)x)->ob_digit[0];
}
}
#endif
#endif
if (sizeof(char) <= sizeof(long)) {
__PYX_VERIFY_RETURN_INT(char, long, PyLong_AsLong)
} else if (sizeof(char) <= sizeof(long long)) {
__PYX_VERIFY_RETURN_INT(char, long long, PyLong_AsLongLong)
}
}
{
#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray)
PyErr_SetString(PyExc_RuntimeError,
"_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers");
#else
char val;
PyObject *v = __Pyx_PyNumber_Int(x);
#if PY_MAJOR_VERSION < 3
if (likely(v) && !PyLong_Check(v)) {
PyObject *tmp = v;
v = PyNumber_Long(tmp);
Py_DECREF(tmp);
}
#endif
if (likely(v)) {
int one = 1; int is_little = (int)*(unsigned char *)&one;
unsigned char *bytes = (unsigned char *)&val;
int ret = _PyLong_AsByteArray((PyLongObject *)v,
bytes, sizeof(val),
is_little, !is_unsigned);
Py_DECREF(v);
if (likely(!ret))
return val;
}
#endif
return (char) -1;
}
} else {
char val;
PyObject *tmp = __Pyx_PyNumber_Int(x);
if (!tmp) return (char) -1;
val = __Pyx_PyInt_As_char(tmp);
Py_DECREF(tmp);
return val;
}
}
static CYTHON_INLINE PyObject* __Pyx_PyInt_From_char(char value) {
const char neg_one = (char) -1, const_zero = 0;
const int is_unsigned = neg_one > const_zero;
if (is_unsigned) {
if (sizeof(char) < sizeof(long)) {
return PyInt_FromLong((long) value);
} else if (sizeof(char) <= sizeof(unsigned long)) {
return PyLong_FromUnsignedLong((unsigned long) value);
} else if (sizeof(char) <= sizeof(unsigned long long)) {
return PyLong_FromUnsignedLongLong((unsigned long long) value);
}
} else {
if (sizeof(char) <= sizeof(long)) {
return PyInt_FromLong((long) value);
} else if (sizeof(char) <= sizeof(long long)) {
return PyLong_FromLongLong((long long) value);
}
}
{
int one = 1; int little = (int)*(unsigned char *)&one;
unsigned char *bytes = (unsigned char *)&value;
return _PyLong_FromByteArray(bytes, sizeof(char),
little, !is_unsigned);
}
}
static CYTHON_INLINE PyObject* __Pyx_PyInt_From_Py_intptr_t(Py_intptr_t value) {
const Py_intptr_t neg_one = (Py_intptr_t) -1, const_zero = 0;
const int is_unsigned = neg_one > const_zero;
if (is_unsigned) {
if (sizeof(Py_intptr_t) < sizeof(long)) {
return PyInt_FromLong((long) value);
} else if (sizeof(Py_intptr_t) <= sizeof(unsigned long)) {
return PyLong_FromUnsignedLong((unsigned long) value);
} else if (sizeof(Py_intptr_t) <= sizeof(unsigned long long)) {
return PyLong_FromUnsignedLongLong((unsigned long long) value);
}
} else {
if (sizeof(Py_intptr_t) <= sizeof(long)) {
return PyInt_FromLong((long) value);
} else if (sizeof(Py_intptr_t) <= sizeof(long long)) {
return PyLong_FromLongLong((long long) value);
}
}
{
int one = 1; int little = (int)*(unsigned char *)&one;
unsigned char *bytes = (unsigned char *)&value;
return _PyLong_FromByteArray(bytes, sizeof(Py_intptr_t),
little, !is_unsigned);
}
}
static CYTHON_INLINE PyObject* __Pyx_PyInt_From_int(int value) {
const int neg_one = (int) -1, const_zero = 0;
const int is_unsigned = neg_one > const_zero;
if (is_unsigned) {
if (sizeof(int) < sizeof(long)) {
return PyInt_FromLong((long) value);
} else if (sizeof(int) <= sizeof(unsigned long)) {
return PyLong_FromUnsignedLong((unsigned long) value);
} else if (sizeof(int) <= sizeof(unsigned long long)) {
return PyLong_FromUnsignedLongLong((unsigned long long) value);
}
} else {
if (sizeof(int) <= sizeof(long)) {
return PyInt_FromLong((long) value);
} else if (sizeof(int) <= sizeof(long long)) {
return PyLong_FromLongLong((long long) value);
}
}
{
int one = 1; int little = (int)*(unsigned char *)&one;
unsigned char *bytes = (unsigned char *)&value;
return _PyLong_FromByteArray(bytes, sizeof(int),
little, !is_unsigned);
}
}
#if CYTHON_CCOMPLEX
#ifdef __cplusplus
static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) {
return ::std::complex< float >(x, y);
}
#else
static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) {
return x + y*(__pyx_t_float_complex)_Complex_I;
}
#endif
#else
static CYTHON_INLINE __pyx_t_float_complex __pyx_t_float_complex_from_parts(float x, float y) {
__pyx_t_float_complex z;
z.real = x;
z.imag = y;
return z;
}
#endif
#if CYTHON_CCOMPLEX
#else
static CYTHON_INLINE int __Pyx_c_eqf(__pyx_t_float_complex a, __pyx_t_float_complex b) {
return (a.real == b.real) && (a.imag == b.imag);
}
static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_sumf(__pyx_t_float_complex a, __pyx_t_float_complex b) {
__pyx_t_float_complex z;
z.real = a.real + b.real;
z.imag = a.imag + b.imag;
return z;
}
static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_difff(__pyx_t_float_complex a, __pyx_t_float_complex b) {
__pyx_t_float_complex z;
z.real = a.real - b.real;
z.imag = a.imag - b.imag;
return z;
}
static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_prodf(__pyx_t_float_complex a, __pyx_t_float_complex b) {
__pyx_t_float_complex z;
z.real = a.real * b.real - a.imag * b.imag;
z.imag = a.real * b.imag + a.imag * b.real;
return z;
}
static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_quotf(__pyx_t_float_complex a, __pyx_t_float_complex b) {
__pyx_t_float_complex z;
float denom = b.real * b.real + b.imag * b.imag;
z.real = (a.real * b.real + a.imag * b.imag) / denom;
z.imag = (a.imag * b.real - a.real * b.imag) / denom;
return z;
}
static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_negf(__pyx_t_float_complex a) {
__pyx_t_float_complex z;
z.real = -a.real;
z.imag = -a.imag;
return z;
}
static CYTHON_INLINE int __Pyx_c_is_zerof(__pyx_t_float_complex a) {
return (a.real == 0) && (a.imag == 0);
}
static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_conjf(__pyx_t_float_complex a) {
__pyx_t_float_complex z;
z.real = a.real;
z.imag = -a.imag;
return z;
}
#if 1
static CYTHON_INLINE float __Pyx_c_absf(__pyx_t_float_complex z) {
#if !defined(HAVE_HYPOT) || defined(_MSC_VER)
return sqrtf(z.real*z.real + z.imag*z.imag);
#else
return hypotf(z.real, z.imag);
#endif
}
static CYTHON_INLINE __pyx_t_float_complex __Pyx_c_powf(__pyx_t_float_complex a, __pyx_t_float_complex b) {
__pyx_t_float_complex z;
float r, lnr, theta, z_r, z_theta;
if (b.imag == 0 && b.real == (int)b.real) {
if (b.real < 0) {
float denom = a.real * a.real + a.imag * a.imag;
a.real = a.real / denom;
a.imag = -a.imag / denom;
b.real = -b.real;
}
switch ((int)b.real) {
case 0:
z.real = 1;
z.imag = 0;
return z;
case 1:
return a;
case 2:
z = __Pyx_c_prodf(a, a);
return __Pyx_c_prodf(a, a);
case 3:
z = __Pyx_c_prodf(a, a);
return __Pyx_c_prodf(z, a);
case 4:
z = __Pyx_c_prodf(a, a);
return __Pyx_c_prodf(z, z);
}
}
if (a.imag == 0) {
if (a.real == 0) {
return a;
}
r = a.real;
theta = 0;
} else {
r = __Pyx_c_absf(a);
theta = atan2f(a.imag, a.real);
}
lnr = logf(r);
z_r = expf(lnr * b.real - theta * b.imag);
z_theta = theta * b.real + lnr * b.imag;
z.real = z_r * cosf(z_theta);
z.imag = z_r * sinf(z_theta);
return z;
}
#endif
#endif
#if CYTHON_CCOMPLEX
#ifdef __cplusplus
static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) {
return ::std::complex< double >(x, y);
}
#else
static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) {
return x + y*(__pyx_t_double_complex)_Complex_I;
}
#endif
#else
static CYTHON_INLINE __pyx_t_double_complex __pyx_t_double_complex_from_parts(double x, double y) {
__pyx_t_double_complex z;
z.real = x;
z.imag = y;
return z;
}
#endif
#if CYTHON_CCOMPLEX
#else
static CYTHON_INLINE int __Pyx_c_eq(__pyx_t_double_complex a, __pyx_t_double_complex b) {
return (a.real == b.real) && (a.imag == b.imag);
}
static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_sum(__pyx_t_double_complex a, __pyx_t_double_complex b) {
__pyx_t_double_complex z;
z.real = a.real + b.real;
z.imag = a.imag + b.imag;
return z;
}
static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_diff(__pyx_t_double_complex a, __pyx_t_double_complex b) {
__pyx_t_double_complex z;
z.real = a.real - b.real;
z.imag = a.imag - b.imag;
return z;
}
static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_prod(__pyx_t_double_complex a, __pyx_t_double_complex b) {
__pyx_t_double_complex z;
z.real = a.real * b.real - a.imag * b.imag;
z.imag = a.real * b.imag + a.imag * b.real;
return z;
}
static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_quot(__pyx_t_double_complex a, __pyx_t_double_complex b) {
__pyx_t_double_complex z;
double denom = b.real * b.real + b.imag * b.imag;
z.real = (a.real * b.real + a.imag * b.imag) / denom;
z.imag = (a.imag * b.real - a.real * b.imag) / denom;
return z;
}
static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_neg(__pyx_t_double_complex a) {
__pyx_t_double_complex z;
z.real = -a.real;
z.imag = -a.imag;
return z;
}
static CYTHON_INLINE int __Pyx_c_is_zero(__pyx_t_double_complex a) {
return (a.real == 0) && (a.imag == 0);
}
static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_conj(__pyx_t_double_complex a) {
__pyx_t_double_complex z;
z.real = a.real;
z.imag = -a.imag;
return z;
}
#if 1
static CYTHON_INLINE double __Pyx_c_abs(__pyx_t_double_complex z) {
#if !defined(HAVE_HYPOT) || defined(_MSC_VER)
return sqrt(z.real*z.real + z.imag*z.imag);
#else
return hypot(z.real, z.imag);
#endif
}
static CYTHON_INLINE __pyx_t_double_complex __Pyx_c_pow(__pyx_t_double_complex a, __pyx_t_double_complex b) {
__pyx_t_double_complex z;
double r, lnr, theta, z_r, z_theta;
if (b.imag == 0 && b.real == (int)b.real) {
if (b.real < 0) {
double denom = a.real * a.real + a.imag * a.imag;
a.real = a.real / denom;
a.imag = -a.imag / denom;
b.real = -b.real;
}
switch ((int)b.real) {
case 0:
z.real = 1;
z.imag = 0;
return z;
case 1:
return a;
case 2:
z = __Pyx_c_prod(a, a);
return __Pyx_c_prod(a, a);
case 3:
z = __Pyx_c_prod(a, a);
return __Pyx_c_prod(z, a);
case 4:
z = __Pyx_c_prod(a, a);
return __Pyx_c_prod(z, z);
}
}
if (a.imag == 0) {
if (a.real == 0) {
return a;
}
r = a.real;
theta = 0;
} else {
r = __Pyx_c_abs(a);
theta = atan2(a.imag, a.real);
}
lnr = log(r);
z_r = exp(lnr * b.real - theta * b.imag);
z_theta = theta * b.real + lnr * b.imag;
z.real = z_r * cos(z_theta);
z.imag = z_r * sin(z_theta);
return z;
}
#endif
#endif
#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3
#if CYTHON_USE_PYLONG_INTERNALS
#include "longintrepr.h"
#endif
#endif
static CYTHON_INLINE int __Pyx_PyInt_As_int(PyObject *x) {
const int neg_one = (int) -1, const_zero = 0;
const int is_unsigned = neg_one > const_zero;
#if PY_MAJOR_VERSION < 3
if (likely(PyInt_Check(x))) {
if (sizeof(int) < sizeof(long)) {
__PYX_VERIFY_RETURN_INT(int, long, PyInt_AS_LONG)
} else {
long val = PyInt_AS_LONG(x);
if (is_unsigned && unlikely(val < 0)) {
PyErr_SetString(PyExc_OverflowError,
"can't convert negative value to int");
return (int) -1;
}
return (int) val;
}
} else
#endif
if (likely(PyLong_Check(x))) {
if (is_unsigned) {
#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3
#if CYTHON_USE_PYLONG_INTERNALS
if (sizeof(digit) <= sizeof(int)) {
switch (Py_SIZE(x)) {
case 0: return 0;
case 1: return (int) ((PyLongObject*)x)->ob_digit[0];
}
}
#endif
#endif
if (unlikely(Py_SIZE(x) < 0)) {
PyErr_SetString(PyExc_OverflowError,
"can't convert negative value to int");
return (int) -1;
}
if (sizeof(int) <= sizeof(unsigned long)) {
__PYX_VERIFY_RETURN_INT(int, unsigned long, PyLong_AsUnsignedLong)
} else if (sizeof(int) <= sizeof(unsigned long long)) {
__PYX_VERIFY_RETURN_INT(int, unsigned long long, PyLong_AsUnsignedLongLong)
}
} else {
#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3
#if CYTHON_USE_PYLONG_INTERNALS
if (sizeof(digit) <= sizeof(int)) {
switch (Py_SIZE(x)) {
case 0: return 0;
case 1: return +(int) ((PyLongObject*)x)->ob_digit[0];
case -1: return -(int) ((PyLongObject*)x)->ob_digit[0];
}
}
#endif
#endif
if (sizeof(int) <= sizeof(long)) {
__PYX_VERIFY_RETURN_INT(int, long, PyLong_AsLong)
} else if (sizeof(int) <= sizeof(long long)) {
__PYX_VERIFY_RETURN_INT(int, long long, PyLong_AsLongLong)
}
}
{
#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray)
PyErr_SetString(PyExc_RuntimeError,
"_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers");
#else
int val;
PyObject *v = __Pyx_PyNumber_Int(x);
#if PY_MAJOR_VERSION < 3
if (likely(v) && !PyLong_Check(v)) {
PyObject *tmp = v;
v = PyNumber_Long(tmp);
Py_DECREF(tmp);
}
#endif
if (likely(v)) {
int one = 1; int is_little = (int)*(unsigned char *)&one;
unsigned char *bytes = (unsigned char *)&val;
int ret = _PyLong_AsByteArray((PyLongObject *)v,
bytes, sizeof(val),
is_little, !is_unsigned);
Py_DECREF(v);
if (likely(!ret))
return val;
}
#endif
return (int) -1;
}
} else {
int val;
PyObject *tmp = __Pyx_PyNumber_Int(x);
if (!tmp) return (int) -1;
val = __Pyx_PyInt_As_int(tmp);
Py_DECREF(tmp);
return val;
}
}
static int
__pyx_memviewslice_is_contig(const __Pyx_memviewslice *mvs,
char order, int ndim)
{
int i, index, step, start;
Py_ssize_t itemsize = mvs->memview->view.itemsize;
if (order == 'F') {
step = 1;
start = 0;
} else {
step = -1;
start = ndim - 1;
}
for (i = 0; i < ndim; i++) {
index = start + step * i;
if (mvs->suboffsets[index] >= 0 || mvs->strides[index] != itemsize)
return 0;
itemsize *= mvs->shape[index];
}
return 1;
}
static void
__pyx_get_array_memory_extents(__Pyx_memviewslice *slice,
void **out_start, void **out_end,
int ndim, size_t itemsize)
{
char *start, *end;
int i;
start = end = slice->data;
for (i = 0; i < ndim; i++) {
Py_ssize_t stride = slice->strides[i];
Py_ssize_t extent = slice->shape[i];
if (extent == 0) {
*out_start = *out_end = start;
return;
} else {
if (stride > 0)
end += stride * (extent - 1);
else
start += stride * (extent - 1);
}
}
*out_start = start;
*out_end = end + itemsize;
}
static int
__pyx_slices_overlap(__Pyx_memviewslice *slice1,
__Pyx_memviewslice *slice2,
int ndim, size_t itemsize)
{
void *start1, *end1, *start2, *end2;
__pyx_get_array_memory_extents(slice1, &start1, &end1, ndim, itemsize);
__pyx_get_array_memory_extents(slice2, &start2, &end2, ndim, itemsize);
return (start1 < end2) && (start2 < end1);
}
static __Pyx_memviewslice
__pyx_memoryview_copy_new_contig(const __Pyx_memviewslice *from_mvs,
const char *mode, int ndim,
size_t sizeof_dtype, int contig_flag,
int dtype_is_object)
{
__Pyx_RefNannyDeclarations
int i;
__Pyx_memviewslice new_mvs = { 0, 0, { 0 }, { 0 }, { 0 } };
struct __pyx_memoryview_obj *from_memview = from_mvs->memview;
Py_buffer *buf = &from_memview->view;
PyObject *shape_tuple = NULL;
PyObject *temp_int = NULL;
struct __pyx_array_obj *array_obj = NULL;
struct __pyx_memoryview_obj *memview_obj = NULL;
__Pyx_RefNannySetupContext("__pyx_memoryview_copy_new_contig", 0);
for (i = 0; i < ndim; i++) {
if (from_mvs->suboffsets[i] >= 0) {
PyErr_Format(PyExc_ValueError, "Cannot copy memoryview slice with "
"indirect dimensions (axis %d)", i);
goto fail;
}
}
shape_tuple = PyTuple_New(ndim);
if (unlikely(!shape_tuple)) {
goto fail;
}
__Pyx_GOTREF(shape_tuple);
for(i = 0; i < ndim; i++) {
temp_int = PyInt_FromSsize_t(from_mvs->shape[i]);
if(unlikely(!temp_int)) {
goto fail;
} else {
PyTuple_SET_ITEM(shape_tuple, i, temp_int);
temp_int = NULL;
}
}
array_obj = __pyx_array_new(shape_tuple, sizeof_dtype, buf->format, (char *) mode, NULL);
if (unlikely(!array_obj)) {
goto fail;
}
__Pyx_GOTREF(array_obj);
memview_obj = (struct __pyx_memoryview_obj *) __pyx_memoryview_new(
(PyObject *) array_obj, contig_flag,
dtype_is_object,
from_mvs->memview->typeinfo);
if (unlikely(!memview_obj))
goto fail;
if (unlikely(__Pyx_init_memviewslice(memview_obj, ndim, &new_mvs, 1) < 0))
goto fail;
if (unlikely(__pyx_memoryview_copy_contents(*from_mvs, new_mvs, ndim, ndim,
dtype_is_object) < 0))
goto fail;
goto no_fail;
fail:
__Pyx_XDECREF(new_mvs.memview);
new_mvs.memview = NULL;
new_mvs.data = NULL;
no_fail:
__Pyx_XDECREF(shape_tuple);
__Pyx_XDECREF(temp_int);
__Pyx_XDECREF(array_obj);
__Pyx_RefNannyFinishContext();
return new_mvs;
}
static CYTHON_INLINE PyObject *
__pyx_capsule_create(void *p, CYTHON_UNUSED const char *sig)
{
PyObject *cobj;
#if PY_VERSION_HEX >= 0x02070000 && !(PY_MAJOR_VERSION == 3 && PY_MINOR_VERSION == 0)
cobj = PyCapsule_New(p, sig, NULL);
#else
cobj = PyCObject_FromVoidPtr(p, NULL);
#endif
return cobj;
}
#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3
#if CYTHON_USE_PYLONG_INTERNALS
#include "longintrepr.h"
#endif
#endif
static CYTHON_INLINE long __Pyx_PyInt_As_long(PyObject *x) {
const long neg_one = (long) -1, const_zero = 0;
const int is_unsigned = neg_one > const_zero;
#if PY_MAJOR_VERSION < 3
if (likely(PyInt_Check(x))) {
if (sizeof(long) < sizeof(long)) {
__PYX_VERIFY_RETURN_INT(long, long, PyInt_AS_LONG)
} else {
long val = PyInt_AS_LONG(x);
if (is_unsigned && unlikely(val < 0)) {
PyErr_SetString(PyExc_OverflowError,
"can't convert negative value to long");
return (long) -1;
}
return (long) val;
}
} else
#endif
if (likely(PyLong_Check(x))) {
if (is_unsigned) {
#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3
#if CYTHON_USE_PYLONG_INTERNALS
if (sizeof(digit) <= sizeof(long)) {
switch (Py_SIZE(x)) {
case 0: return 0;
case 1: return (long) ((PyLongObject*)x)->ob_digit[0];
}
}
#endif
#endif
if (unlikely(Py_SIZE(x) < 0)) {
PyErr_SetString(PyExc_OverflowError,
"can't convert negative value to long");
return (long) -1;
}
if (sizeof(long) <= sizeof(unsigned long)) {
__PYX_VERIFY_RETURN_INT(long, unsigned long, PyLong_AsUnsignedLong)
} else if (sizeof(long) <= sizeof(unsigned long long)) {
__PYX_VERIFY_RETURN_INT(long, unsigned long long, PyLong_AsUnsignedLongLong)
}
} else {
#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3
#if CYTHON_USE_PYLONG_INTERNALS
if (sizeof(digit) <= sizeof(long)) {
switch (Py_SIZE(x)) {
case 0: return 0;
case 1: return +(long) ((PyLongObject*)x)->ob_digit[0];
case -1: return -(long) ((PyLongObject*)x)->ob_digit[0];
}
}
#endif
#endif
if (sizeof(long) <= sizeof(long)) {
__PYX_VERIFY_RETURN_INT(long, long, PyLong_AsLong)
} else if (sizeof(long) <= sizeof(long long)) {
__PYX_VERIFY_RETURN_INT(long, long long, PyLong_AsLongLong)
}
}
{
#if CYTHON_COMPILING_IN_PYPY && !defined(_PyLong_AsByteArray)
PyErr_SetString(PyExc_RuntimeError,
"_PyLong_AsByteArray() not available in PyPy, cannot convert large numbers");
#else
long val;
PyObject *v = __Pyx_PyNumber_Int(x);
#if PY_MAJOR_VERSION < 3
if (likely(v) && !PyLong_Check(v)) {
PyObject *tmp = v;
v = PyNumber_Long(tmp);
Py_DECREF(tmp);
}
#endif
if (likely(v)) {
int one = 1; int is_little = (int)*(unsigned char *)&one;
unsigned char *bytes = (unsigned char *)&val;
int ret = _PyLong_AsByteArray((PyLongObject *)v,
bytes, sizeof(val),
is_little, !is_unsigned);
Py_DECREF(v);
if (likely(!ret))
return val;
}
#endif
return (long) -1;
}
} else {
long val;
PyObject *tmp = __Pyx_PyNumber_Int(x);
if (!tmp) return (long) -1;
val = __Pyx_PyInt_As_long(tmp);
Py_DECREF(tmp);
return val;
}
}
static int __Pyx_check_binary_version(void) {
char ctversion[4], rtversion[4];
PyOS_snprintf(ctversion, 4, "%d.%d", PY_MAJOR_VERSION, PY_MINOR_VERSION);
PyOS_snprintf(rtversion, 4, "%s", Py_GetVersion());
if (ctversion[0] != rtversion[0] || ctversion[2] != rtversion[2]) {
char message[200];
PyOS_snprintf(message, sizeof(message),
"compiletime version %s of module '%.100s' "
"does not match runtime version %s",
ctversion, __Pyx_MODULE_NAME, rtversion);
#if PY_VERSION_HEX < 0x02050000
return PyErr_Warn(NULL, message);
#else
return PyErr_WarnEx(NULL, message, 1);
#endif
}
return 0;
}
#ifndef __PYX_HAVE_RT_ImportModule
#define __PYX_HAVE_RT_ImportModule
static PyObject *__Pyx_ImportModule(const char *name) {
PyObject *py_name = 0;
PyObject *py_module = 0;
py_name = __Pyx_PyIdentifier_FromString(name);
if (!py_name)
goto bad;
py_module = PyImport_Import(py_name);
Py_DECREF(py_name);
return py_module;
bad:
Py_XDECREF(py_name);
return 0;
}
#endif
#ifndef __PYX_HAVE_RT_ImportType
#define __PYX_HAVE_RT_ImportType
static PyTypeObject *__Pyx_ImportType(const char *module_name, const char *class_name,
size_t size, int strict)
{
PyObject *py_module = 0;
PyObject *result = 0;
PyObject *py_name = 0;
char warning[200];
Py_ssize_t basicsize;
#ifdef Py_LIMITED_API
PyObject *py_basicsize;
#endif
py_module = __Pyx_ImportModule(module_name);
if (!py_module)
goto bad;
py_name = __Pyx_PyIdentifier_FromString(class_name);
if (!py_name)
goto bad;
result = PyObject_GetAttr(py_module, py_name);
Py_DECREF(py_name);
py_name = 0;
Py_DECREF(py_module);
py_module = 0;
if (!result)
goto bad;
if (!PyType_Check(result)) {
PyErr_Format(PyExc_TypeError,
"%.200s.%.200s is not a type object",
module_name, class_name);
goto bad;
}
#ifndef Py_LIMITED_API
basicsize = ((PyTypeObject *)result)->tp_basicsize;
#else
py_basicsize = PyObject_GetAttrString(result, "__basicsize__");
if (!py_basicsize)
goto bad;
basicsize = PyLong_AsSsize_t(py_basicsize);
Py_DECREF(py_basicsize);
py_basicsize = 0;
if (basicsize == (Py_ssize_t)-1 && PyErr_Occurred())
goto bad;
#endif
if (!strict && (size_t)basicsize > size) {
PyOS_snprintf(warning, sizeof(warning),
"%s.%s size changed, may indicate binary incompatibility",
module_name, class_name);
#if PY_VERSION_HEX < 0x02050000
if (PyErr_Warn(NULL, warning) < 0) goto bad;
#else
if (PyErr_WarnEx(NULL, warning, 0) < 0) goto bad;
#endif
}
else if ((size_t)basicsize != size) {
PyErr_Format(PyExc_ValueError,
"%.200s.%.200s has the wrong size, try recompiling",
module_name, class_name);
goto bad;
}
return (PyTypeObject *)result;
bad:
Py_XDECREF(py_module);
Py_XDECREF(result);
return NULL;
}
#endif
static int __pyx_bisect_code_objects(__Pyx_CodeObjectCacheEntry* entries, int count, int code_line) {
int start = 0, mid = 0, end = count - 1;
if (end >= 0 && code_line > entries[end].code_line) {
return count;
}
while (start < end) {
mid = (start + end) / 2;
if (code_line < entries[mid].code_line) {
end = mid;
} else if (code_line > entries[mid].code_line) {
start = mid + 1;
} else {
return mid;
}
}
if (code_line <= entries[mid].code_line) {
return mid;
} else {
return mid + 1;
}
}
static PyCodeObject *__pyx_find_code_object(int code_line) {
PyCodeObject* code_object;
int pos;
if (unlikely(!code_line) || unlikely(!__pyx_code_cache.entries)) {
return NULL;
}
pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line);
if (unlikely(pos >= __pyx_code_cache.count) || unlikely(__pyx_code_cache.entries[pos].code_line != code_line)) {
return NULL;
}
code_object = __pyx_code_cache.entries[pos].code_object;
Py_INCREF(code_object);
return code_object;
}
static void __pyx_insert_code_object(int code_line, PyCodeObject* code_object) {
int pos, i;
__Pyx_CodeObjectCacheEntry* entries = __pyx_code_cache.entries;
if (unlikely(!code_line)) {
return;
}
if (unlikely(!entries)) {
entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Malloc(64*sizeof(__Pyx_CodeObjectCacheEntry));
if (likely(entries)) {
__pyx_code_cache.entries = entries;
__pyx_code_cache.max_count = 64;
__pyx_code_cache.count = 1;
entries[0].code_line = code_line;
entries[0].code_object = code_object;
Py_INCREF(code_object);
}
return;
}
pos = __pyx_bisect_code_objects(__pyx_code_cache.entries, __pyx_code_cache.count, code_line);
if ((pos < __pyx_code_cache.count) && unlikely(__pyx_code_cache.entries[pos].code_line == code_line)) {
PyCodeObject* tmp = entries[pos].code_object;
entries[pos].code_object = code_object;
Py_DECREF(tmp);
return;
}
if (__pyx_code_cache.count == __pyx_code_cache.max_count) {
int new_max = __pyx_code_cache.max_count + 64;
entries = (__Pyx_CodeObjectCacheEntry*)PyMem_Realloc(
__pyx_code_cache.entries, new_max*sizeof(__Pyx_CodeObjectCacheEntry));
if (unlikely(!entries)) {
return;
}
__pyx_code_cache.entries = entries;
__pyx_code_cache.max_count = new_max;
}
for (i=__pyx_code_cache.count; i>pos; i--) {
entries[i] = entries[i-1];
}
entries[pos].code_line = code_line;
entries[pos].code_object = code_object;
__pyx_code_cache.count++;
Py_INCREF(code_object);
}
#include "compile.h"
#include "frameobject.h"
#include "traceback.h"
static PyCodeObject* __Pyx_CreateCodeObjectForTraceback(
const char *funcname, int c_line,
int py_line, const char *filename) {
PyCodeObject *py_code = 0;
PyObject *py_srcfile = 0;
PyObject *py_funcname = 0;
#if PY_MAJOR_VERSION < 3
py_srcfile = PyString_FromString(filename);
#else
py_srcfile = PyUnicode_FromString(filename);
#endif
if (!py_srcfile) goto bad;
if (c_line) {
#if PY_MAJOR_VERSION < 3
py_funcname = PyString_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line);
#else
py_funcname = PyUnicode_FromFormat( "%s (%s:%d)", funcname, __pyx_cfilenm, c_line);
#endif
}
else {
#if PY_MAJOR_VERSION < 3
py_funcname = PyString_FromString(funcname);
#else
py_funcname = PyUnicode_FromString(funcname);
#endif
}
if (!py_funcname) goto bad;
py_code = __Pyx_PyCode_New(
0, /*int argcount,*/
0, /*int kwonlyargcount,*/
0, /*int nlocals,*/
0, /*int stacksize,*/
0, /*int flags,*/
__pyx_empty_bytes, /*PyObject *code,*/
__pyx_empty_tuple, /*PyObject *consts,*/
__pyx_empty_tuple, /*PyObject *names,*/
__pyx_empty_tuple, /*PyObject *varnames,*/
__pyx_empty_tuple, /*PyObject *freevars,*/
__pyx_empty_tuple, /*PyObject *cellvars,*/
py_srcfile, /*PyObject *filename,*/
py_funcname, /*PyObject *name,*/
py_line, /*int firstlineno,*/
__pyx_empty_bytes /*PyObject *lnotab*/
);
Py_DECREF(py_srcfile);
Py_DECREF(py_funcname);
return py_code;
bad:
Py_XDECREF(py_srcfile);
Py_XDECREF(py_funcname);
return NULL;
}
static void __Pyx_AddTraceback(const char *funcname, int c_line,
int py_line, const char *filename) {
PyCodeObject *py_code = 0;
PyObject *py_globals = 0;
PyFrameObject *py_frame = 0;
py_code = __pyx_find_code_object(c_line ? c_line : py_line);
if (!py_code) {
py_code = __Pyx_CreateCodeObjectForTraceback(
funcname, c_line, py_line, filename);
if (!py_code) goto bad;
__pyx_insert_code_object(c_line ? c_line : py_line, py_code);
}
py_globals = PyModule_GetDict(__pyx_m);
if (!py_globals) goto bad;
py_frame = PyFrame_New(
PyThreadState_GET(), /*PyThreadState *tstate,*/
py_code, /*PyCodeObject *code,*/
py_globals, /*PyObject *globals,*/
0 /*PyObject *locals*/
);
if (!py_frame) goto bad;
py_frame->f_lineno = py_line;
PyTraceBack_Here(py_frame);
bad:
Py_XDECREF(py_code);
Py_XDECREF(py_frame);
}
static int __Pyx_InitStrings(__Pyx_StringTabEntry *t) {
while (t->p) {
#if PY_MAJOR_VERSION < 3
if (t->is_unicode) {
*t->p = PyUnicode_DecodeUTF8(t->s, t->n - 1, NULL);
} else if (t->intern) {
*t->p = PyString_InternFromString(t->s);
} else {
*t->p = PyString_FromStringAndSize(t->s, t->n - 1);
}
#else /* Python 3+ has unicode identifiers */
if (t->is_unicode | t->is_str) {
if (t->intern) {
*t->p = PyUnicode_InternFromString(t->s);
} else if (t->encoding) {
*t->p = PyUnicode_Decode(t->s, t->n - 1, t->encoding, NULL);
} else {
*t->p = PyUnicode_FromStringAndSize(t->s, t->n - 1);
}
} else {
*t->p = PyBytes_FromStringAndSize(t->s, t->n - 1);
}
#endif
if (!*t->p)
return -1;
++t;
}
return 0;
}
static CYTHON_INLINE PyObject* __Pyx_PyUnicode_FromString(char* c_str) {
return __Pyx_PyUnicode_FromStringAndSize(c_str, strlen(c_str));
}
static CYTHON_INLINE char* __Pyx_PyObject_AsString(PyObject* o) {
Py_ssize_t ignore;
return __Pyx_PyObject_AsStringAndSize(o, &ignore);
}
static CYTHON_INLINE char* __Pyx_PyObject_AsStringAndSize(PyObject* o, Py_ssize_t *length) {
#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT
if (
#if PY_MAJOR_VERSION < 3 && __PYX_DEFAULT_STRING_ENCODING_IS_ASCII
__Pyx_sys_getdefaultencoding_not_ascii &&
#endif
PyUnicode_Check(o)) {
#if PY_VERSION_HEX < 0x03030000
char* defenc_c;
PyObject* defenc = _PyUnicode_AsDefaultEncodedString(o, NULL);
if (!defenc) return NULL;
defenc_c = PyBytes_AS_STRING(defenc);
#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII
{
char* end = defenc_c + PyBytes_GET_SIZE(defenc);
char* c;
for (c = defenc_c; c < end; c++) {
if ((unsigned char) (*c) >= 128) {
PyUnicode_AsASCIIString(o);
return NULL;
}
}
}
#endif /*__PYX_DEFAULT_STRING_ENCODING_IS_ASCII*/
*length = PyBytes_GET_SIZE(defenc);
return defenc_c;
#else /* PY_VERSION_HEX < 0x03030000 */
if (PyUnicode_READY(o) == -1) return NULL;
#if __PYX_DEFAULT_STRING_ENCODING_IS_ASCII
if (PyUnicode_IS_ASCII(o)) {
*length = PyUnicode_GET_DATA_SIZE(o);
return PyUnicode_AsUTF8(o);
} else {
PyUnicode_AsASCIIString(o);
return NULL;
}
#else /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII */
return PyUnicode_AsUTF8AndSize(o, length);
#endif /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII */
#endif /* PY_VERSION_HEX < 0x03030000 */
} else
#endif /* __PYX_DEFAULT_STRING_ENCODING_IS_ASCII || __PYX_DEFAULT_STRING_ENCODING_IS_DEFAULT */
#if !CYTHON_COMPILING_IN_PYPY
#if PY_VERSION_HEX >= 0x02060000
if (PyByteArray_Check(o)) {
*length = PyByteArray_GET_SIZE(o);
return PyByteArray_AS_STRING(o);
} else
#endif
#endif
{
char* result;
int r = PyBytes_AsStringAndSize(o, &result, length);
if (unlikely(r < 0)) {
return NULL;
} else {
return result;
}
}
}
static CYTHON_INLINE int __Pyx_PyObject_IsTrue(PyObject* x) {
int is_true = x == Py_True;
if (is_true | (x == Py_False) | (x == Py_None)) return is_true;
else return PyObject_IsTrue(x);
}
static CYTHON_INLINE PyObject* __Pyx_PyNumber_Int(PyObject* x) {
PyNumberMethods *m;
const char *name = NULL;
PyObject *res = NULL;
#if PY_MAJOR_VERSION < 3
if (PyInt_Check(x) || PyLong_Check(x))
#else
if (PyLong_Check(x))
#endif
return Py_INCREF(x), x;
m = Py_TYPE(x)->tp_as_number;
#if PY_MAJOR_VERSION < 3
if (m && m->nb_int) {
name = "int";
res = PyNumber_Int(x);
}
else if (m && m->nb_long) {
name = "long";
res = PyNumber_Long(x);
}
#else
if (m && m->nb_int) {
name = "int";
res = PyNumber_Long(x);
}
#endif
if (res) {
#if PY_MAJOR_VERSION < 3
if (!PyInt_Check(res) && !PyLong_Check(res)) {
#else
if (!PyLong_Check(res)) {
#endif
PyErr_Format(PyExc_TypeError,
"__%.4s__ returned non-%.4s (type %.200s)",
name, name, Py_TYPE(res)->tp_name);
Py_DECREF(res);
return NULL;
}
}
else if (!PyErr_Occurred()) {
PyErr_SetString(PyExc_TypeError,
"an integer is required");
}
return res;
}
#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3
#if CYTHON_USE_PYLONG_INTERNALS
#include "longintrepr.h"
#endif
#endif
static CYTHON_INLINE Py_ssize_t __Pyx_PyIndex_AsSsize_t(PyObject* b) {
Py_ssize_t ival;
PyObject *x;
#if PY_MAJOR_VERSION < 3
if (likely(PyInt_CheckExact(b)))
return PyInt_AS_LONG(b);
#endif
if (likely(PyLong_CheckExact(b))) {
#if CYTHON_COMPILING_IN_CPYTHON && PY_MAJOR_VERSION >= 3
#if CYTHON_USE_PYLONG_INTERNALS
switch (Py_SIZE(b)) {
case -1: return -(sdigit)((PyLongObject*)b)->ob_digit[0];
case 0: return 0;
case 1: return ((PyLongObject*)b)->ob_digit[0];
}
#endif
#endif
#if PY_VERSION_HEX < 0x02060000
return PyInt_AsSsize_t(b);
#else
return PyLong_AsSsize_t(b);
#endif
}
x = PyNumber_Index(b);
if (!x) return -1;
ival = PyInt_AsSsize_t(x);
Py_DECREF(x);
return ival;
}
static CYTHON_INLINE PyObject * __Pyx_PyInt_FromSize_t(size_t ival) {
#if PY_VERSION_HEX < 0x02050000
if (ival <= LONG_MAX)
return PyInt_FromLong((long)ival);
else {
unsigned char *bytes = (unsigned char *) &ival;
int one = 1; int little = (int)*(unsigned char*)&one;
return _PyLong_FromByteArray(bytes, sizeof(size_t), little, 0);
}
#else
return PyInt_FromSize_t(ival);
#endif
}
#endif /* Py_PYTHON_H */
| bsd-3-clause |
drobilla/serd | src/serdi.c | 1 | 10503 | // Copyright 2011-2022 David Robillard <d@drobilla.net>
// SPDX-License-Identifier: ISC
#include "serd_config.h"
#include "string_utils.h"
#include "serd/serd.h"
#ifdef _WIN32
# ifdef _MSC_VER
# define WIN32_LEAN_AND_MEAN 1
# endif
# include <fcntl.h>
# include <io.h>
#endif
#if USE_POSIX_FADVISE && USE_FILENO
# include <fcntl.h>
#endif
#include <errno.h>
#include <stdbool.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SERDI_ERROR(msg) fprintf(stderr, "serdi: " msg)
#define SERDI_ERRORF(fmt, ...) fprintf(stderr, "serdi: " fmt, __VA_ARGS__)
typedef struct {
SerdSyntax syntax;
const char* name;
const char* extension;
} Syntax;
static const Syntax syntaxes[] = {{SERD_TURTLE, "turtle", ".ttl"},
{SERD_NTRIPLES, "ntriples", ".nt"},
{SERD_NQUADS, "nquads", ".nq"},
{SERD_TRIG, "trig", ".trig"},
{(SerdSyntax)0, NULL, NULL}};
static SerdSyntax
get_syntax(const char* const name)
{
for (const Syntax* s = syntaxes; s->name; ++s) {
if (!serd_strncasecmp(s->name, name, strlen(name))) {
return s->syntax;
}
}
SERDI_ERRORF("unknown syntax `%s'\n", name);
return (SerdSyntax)0;
}
static SERD_PURE_FUNC SerdSyntax
guess_syntax(const char* const filename)
{
const char* ext = strrchr(filename, '.');
if (ext) {
for (const Syntax* s = syntaxes; s->name; ++s) {
if (!serd_strncasecmp(s->extension, ext, strlen(ext))) {
return s->syntax;
}
}
}
return (SerdSyntax)0;
}
static int
print_version(void)
{
printf("serdi " SERD_VERSION " <http://drobilla.net/software/serd>\n");
printf("Copyright 2011-2022 David Robillard <d@drobilla.net>.\n"
"License ISC: <https://spdx.org/licenses/ISC>.\n"
"This is free software; you are free to change and redistribute it."
"\nThere is NO WARRANTY, to the extent permitted by law.\n");
return 0;
}
static int
print_usage(const char* const name, const bool error)
{
static const char* const description =
"Read and write RDF syntax.\n"
"Use - for INPUT to read from standard input.\n\n"
" -a Write ASCII output if possible.\n"
" -b Fast bulk output for large serialisations.\n"
" -c PREFIX Chop PREFIX from matching blank node IDs.\n"
" -e Eat input one character at a time.\n"
" -f Keep full URIs in input (don't qualify).\n"
" -h Display this help and exit.\n"
" -i SYNTAX Input syntax: turtle/ntriples/trig/nquads.\n"
" -l Lax (non-strict) parsing.\n"
" -o SYNTAX Output syntax: turtle/ntriples/nquads.\n"
" -p PREFIX Add PREFIX to blank node IDs.\n"
" -q Suppress all output except data.\n"
" -r ROOT_URI Keep relative URIs within ROOT_URI.\n"
" -s INPUT Parse INPUT as string (terminates options).\n"
" -v Display version information and exit.\n";
FILE* const os = error ? stderr : stdout;
fprintf(os, "%s", error ? "\n" : "");
fprintf(os, "Usage: %s [OPTION]... INPUT [BASE_URI]\n", name);
fprintf(os, "%s", description);
return error ? 1 : 0;
}
static int
missing_arg(const char* const name, const char opt)
{
SERDI_ERRORF("option requires an argument -- '%c'\n", opt);
return print_usage(name, true);
}
static SerdStatus
quiet_error_sink(void* const handle, const SerdError* const e)
{
(void)handle;
(void)e;
return SERD_SUCCESS;
}
static FILE*
serd_fopen(const char* const path, const char* const mode)
{
FILE* fd = fopen(path, mode);
if (!fd) {
SERDI_ERRORF("failed to open file %s (%s)\n", path, strerror(errno));
return NULL;
}
#if USE_POSIX_FADVISE && USE_FILENO
posix_fadvise(fileno(fd), 0, 0, POSIX_FADV_SEQUENTIAL | POSIX_FADV_NOREUSE);
#endif
return fd;
}
static SerdStyle
choose_style(const SerdSyntax input_syntax,
const SerdSyntax output_syntax,
const bool ascii,
const bool bulk_write,
const bool full_uris)
{
unsigned output_style = 0U;
if (output_syntax == SERD_NTRIPLES || ascii) {
output_style |= SERD_STYLE_ASCII;
} else if (output_syntax == SERD_TURTLE) {
output_style |= SERD_STYLE_ABBREVIATED;
if (!full_uris) {
output_style |= SERD_STYLE_CURIED;
}
}
if ((input_syntax == SERD_TURTLE || input_syntax == SERD_TRIG) ||
(output_style & SERD_STYLE_CURIED)) {
// Base URI may change and/or we're abbreviating URIs, so must resolve
output_style |= SERD_STYLE_RESOLVED;
}
if (bulk_write) {
output_style |= SERD_STYLE_BULK;
}
return (SerdStyle)output_style;
}
int
main(int argc, char** argv)
{
const char* const prog = argv[0];
FILE* in_fd = NULL;
SerdSyntax input_syntax = (SerdSyntax)0;
SerdSyntax output_syntax = (SerdSyntax)0;
bool from_file = true;
bool ascii = false;
bool bulk_read = true;
bool bulk_write = false;
bool full_uris = false;
bool lax = false;
bool quiet = false;
const uint8_t* in_name = NULL;
const uint8_t* add_prefix = NULL;
const uint8_t* chop_prefix = NULL;
const uint8_t* root_uri = NULL;
int a = 1;
for (; a < argc && from_file && argv[a][0] == '-'; ++a) {
if (argv[a][1] == '\0') {
in_name = (const uint8_t*)"(stdin)";
in_fd = stdin;
break;
}
for (int o = 1; argv[a][o]; ++o) {
const char opt = argv[a][o];
if (opt == 'a') {
ascii = true;
} else if (opt == 'b') {
bulk_write = true;
} else if (opt == 'e') {
bulk_read = false;
} else if (opt == 'f') {
full_uris = true;
} else if (opt == 'h') {
return print_usage(prog, false);
} else if (opt == 'l') {
lax = true;
} else if (opt == 'q') {
quiet = true;
} else if (opt == 'v') {
return print_version();
} else if (opt == 's') {
in_name = (const uint8_t*)"(string)";
from_file = false;
break;
} else if (opt == 'c') {
if (argv[a][o + 1] || ++a == argc) {
return missing_arg(prog, 'c');
}
chop_prefix = (const uint8_t*)argv[a];
break;
} else if (opt == 'i') {
if (argv[a][o + 1] || ++a == argc) {
return missing_arg(prog, 'i');
}
if (!(input_syntax = get_syntax(argv[a]))) {
return print_usage(prog, true);
}
break;
} else if (opt == 'o') {
if (argv[a][o + 1] || ++a == argc) {
return missing_arg(prog, 'o');
}
if (!(output_syntax = get_syntax(argv[a]))) {
return print_usage(prog, true);
}
break;
} else if (opt == 'p') {
if (argv[a][o + 1] || ++a == argc) {
return missing_arg(prog, 'p');
}
add_prefix = (const uint8_t*)argv[a];
break;
} else if (opt == 'r') {
if (argv[a][o + 1] || ++a == argc) {
return missing_arg(prog, 'r');
}
root_uri = (const uint8_t*)argv[a];
break;
} else {
SERDI_ERRORF("invalid option -- '%s'\n", argv[a] + 1);
return print_usage(prog, true);
}
}
}
if (a == argc) {
SERDI_ERROR("missing input\n");
return print_usage(prog, true);
}
#ifdef _WIN32
_setmode(_fileno(stdin), _O_BINARY);
_setmode(_fileno(stdout), _O_BINARY);
#endif
uint8_t* input_path = NULL;
const uint8_t* input = (const uint8_t*)argv[a++];
if (from_file) {
in_name = in_name ? in_name : input;
if (!in_fd) {
if (!strncmp((const char*)input, "file:", 5)) {
input_path = serd_file_uri_parse(input, NULL);
input = input_path;
}
if (!input || !(in_fd = serd_fopen((const char*)input, "rb"))) {
return 1;
}
}
}
if (!input_syntax && !(input_syntax = guess_syntax((const char*)in_name))) {
input_syntax = SERD_TRIG;
}
if (!output_syntax) {
output_syntax =
((input_syntax == SERD_TURTLE || input_syntax == SERD_NTRIPLES)
? SERD_NTRIPLES
: SERD_NQUADS);
}
const SerdStyle output_style =
choose_style(input_syntax, output_syntax, ascii, bulk_write, full_uris);
SerdURI base_uri = SERD_URI_NULL;
SerdNode base = SERD_NODE_NULL;
if (a < argc) { // Base URI given on command line
base =
serd_node_new_uri_from_string((const uint8_t*)argv[a], NULL, &base_uri);
} else if (from_file && in_fd != stdin) { // Use input file URI
base = serd_node_new_file_uri(input, NULL, &base_uri, true);
}
FILE* const out_fd = stdout;
SerdEnv* const env = serd_env_new(&base);
SerdWriter* const writer = serd_writer_new(
output_syntax, output_style, env, &base_uri, serd_file_sink, out_fd);
SerdReader* const reader =
serd_reader_new(input_syntax,
writer,
NULL,
(SerdBaseSink)serd_writer_set_base_uri,
(SerdPrefixSink)serd_writer_set_prefix,
(SerdStatementSink)serd_writer_write_statement,
(SerdEndSink)serd_writer_end_anon);
serd_reader_set_strict(reader, !lax);
if (quiet) {
serd_reader_set_error_sink(reader, quiet_error_sink, NULL);
serd_writer_set_error_sink(writer, quiet_error_sink, NULL);
}
SerdNode root = serd_node_from_string(SERD_URI, root_uri);
serd_writer_set_root_uri(writer, &root);
serd_writer_chop_blank_prefix(writer, chop_prefix);
serd_reader_add_blank_prefix(reader, add_prefix);
SerdStatus st = SERD_SUCCESS;
if (!from_file) {
st = serd_reader_read_string(reader, input);
} else if (bulk_read) {
st = serd_reader_read_file_handle(reader, in_fd, in_name);
} else {
st = serd_reader_start_stream(reader, in_fd, in_name, false);
while (!st) {
st = serd_reader_read_chunk(reader);
}
serd_reader_end_stream(reader);
}
serd_reader_free(reader);
serd_writer_finish(writer);
serd_writer_free(writer);
serd_env_free(env);
serd_node_free(&base);
free(input_path);
if (from_file) {
fclose(in_fd);
}
if (fclose(out_fd)) {
perror("serdi: write error");
st = SERD_ERR_UNKNOWN;
}
return (st > SERD_FAILURE) ? 1 : 0;
}
| isc |
eriknstr/ThinkPad-FreeBSD-setup | FreeBSD/contrib/tcsh/tc.bind.c | 8 | 12378 | /* $Header: /p/tcsh/cvsroot/tcsh/tc.bind.c,v 3.45 2009/06/25 21:15:37 christos Exp $ */
/*
* tc.bind.c: Key binding functions
*/
/*-
* Copyright (c) 1980, 1991 The Regents of the University of California.
* 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 University 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 REGENTS 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 REGENTS 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.
*/
#include "sh.h"
RCSID("$tcsh: tc.bind.c,v 3.45 2009/06/25 21:15:37 christos Exp $")
#include "ed.h"
#include "ed.defns.h"
static void printkey (const KEYCMD *, CStr *);
static KEYCMD parsecmd (Char *);
static void bad_spec (const Char *);
static CStr *parsestring (const Char *, CStr *);
static CStr *parsebind (const Char *, CStr *);
static void print_all_keys (void);
static void printkeys (KEYCMD *, int, int);
static void bindkey_usage (void);
static void list_functions (void);
extern int MapsAreInited;
/*ARGSUSED*/
void
dobindkey(Char **v, struct command *c)
{
KEYCMD *map;
int ntype, no, removeb, key, bindk;
Char *par;
Char p;
KEYCMD cmd;
CStr in;
CStr out;
uChar ch;
USE(c);
if (!MapsAreInited)
ed_InitMaps();
map = CcKeyMap;
ntype = XK_CMD;
key = removeb = bindk = 0;
for (no = 1, par = v[no];
par != NULL && (*par++ & CHAR) == '-'; no++, par = v[no]) {
if ((p = (*par & CHAR)) == '-') {
no++;
break;
}
else
switch (p) {
case 'b':
bindk = 1;
break;
case 'k':
key = 1;
break;
case 'a':
map = CcAltMap;
break;
case 's':
ntype = XK_STR;
break;
case 'c':
ntype = XK_EXE;
break;
case 'r':
removeb = 1;
break;
case 'v':
ed_InitVIMaps();
return;
case 'e':
ed_InitEmacsMaps();
return;
case 'd':
#ifdef VIDEFAULT
ed_InitVIMaps();
#else /* EMACSDEFAULT */
ed_InitEmacsMaps();
#endif /* VIDEFAULT */
return;
case 'l':
list_functions();
return;
default:
bindkey_usage();
return;
}
}
if (!v[no]) {
print_all_keys();
return;
}
if (key) {
if (!IsArrowKey(v[no]))
xprintf(CGETS(20, 1, "Invalid key name `%S'\n"), v[no]);
in.buf = Strsave(v[no++]);
in.len = Strlen(in.buf);
}
else {
if (bindk) {
if (parsebind(v[no++], &in) == NULL)
return;
}
else {
if (parsestring(v[no++], &in) == NULL)
return;
}
}
cleanup_push(in.buf, xfree);
#ifndef WINNT_NATIVE
if (in.buf[0] > 0xFF) {
bad_spec(in.buf);
cleanup_until(in.buf);
return;
}
#endif
ch = (uChar) in.buf[0];
if (removeb) {
if (key)
(void) ClearArrowKeys(&in);
else if (in.len > 1) {
(void) DeleteXkey(&in);
}
else if (map[ch] == F_XKEY) {
(void) DeleteXkey(&in);
map[ch] = F_UNASSIGNED;
}
else {
map[ch] = F_UNASSIGNED;
}
cleanup_until(in.buf);
return;
}
if (!v[no]) {
if (key)
PrintArrowKeys(&in);
else
printkey(map, &in);
cleanup_until(in.buf);
return;
}
if (v[no + 1]) {
bindkey_usage();
cleanup_until(in.buf);
return;
}
switch (ntype) {
case XK_STR:
case XK_EXE:
if (parsestring(v[no], &out) == NULL) {
cleanup_until(in.buf);
return;
}
cleanup_push(out.buf, xfree);
if (key) {
if (SetArrowKeys(&in, XmapStr(&out), ntype) == -1)
xprintf(CGETS(20, 2, "Bad key name: %S\n"), in.buf);
else
cleanup_ignore(out.buf);
}
else
AddXkey(&in, XmapStr(&out), ntype);
map[ch] = F_XKEY;
break;
case XK_CMD:
if ((cmd = parsecmd(v[no])) == 0) {
cleanup_until(in.buf);
return;
}
if (key)
(void) SetArrowKeys(&in, XmapCmd((int) cmd), ntype);
else {
if (in.len > 1) {
AddXkey(&in, XmapCmd((int) cmd), ntype);
map[ch] = F_XKEY;
}
else {
ClearXkey(map, &in);
map[ch] = cmd;
}
}
break;
default:
abort();
break;
}
cleanup_until(in.buf);
if (key)
BindArrowKeys();
}
static void
printkey(const KEYCMD *map, CStr *in)
{
struct KeyFuncs *fp;
if (in->len < 2) {
unsigned char *unparsed;
unparsed = unparsestring(in, STRQQ);
cleanup_push(unparsed, xfree);
for (fp = FuncNames; fp->name; fp++) {
if (fp->func == map[(uChar) *(in->buf)]) {
xprintf("%s\t->\t%s\n", unparsed, fp->name);
}
}
cleanup_until(unparsed);
}
else
PrintXkey(in);
}
static KEYCMD
parsecmd(Char *str)
{
struct KeyFuncs *fp;
for (fp = FuncNames; fp->name; fp++) {
if (strcmp(short2str(str), fp->name) == 0) {
return (KEYCMD) fp->func;
}
}
xprintf(CGETS(20, 3, "Bad command name: %S\n"), str);
return 0;
}
static void
bad_spec(const Char *str)
{
xprintf(CGETS(20, 4, "Bad key spec %S\n"), str);
}
static CStr *
parsebind(const Char *s, CStr *str)
{
struct Strbuf b = Strbuf_INIT;
cleanup_push(&b, Strbuf_cleanup);
if (Iscntrl(*s)) {
Strbuf_append1(&b, *s);
goto end;
}
switch (*s) {
case '^':
s++;
#ifdef IS_ASCII
Strbuf_append1(&b, (*s == '?') ? '\177' : ((*s & CHAR) & 0237));
#else
Strbuf_append1(&b, (*s == '?') ? CTL_ESC('\177')
: _toebcdic[_toascii[*s & CHAR] & 0237]);
#endif
break;
case 'F':
case 'M':
case 'X':
case 'C':
#ifdef WINNT_NATIVE
case 'N':
#endif /* WINNT_NATIVE */
if (s[1] != '-' || s[2] == '\0')
goto bad_spec;
s += 2;
switch (s[-2]) {
case 'F': case 'f': /* Turn into ^[str */
Strbuf_append1(&b, CTL_ESC('\033'));
Strbuf_append(&b, s);
break;
case 'C': case 'c': /* Turn into ^c */
#ifdef IS_ASCII
Strbuf_append1(&b, (*s == '?') ? '\177' : ((*s & CHAR) & 0237));
#else
Strbuf_append1(&b, (*s == '?') ? CTL_ESC('\177')
: _toebcdic[_toascii[*s & CHAR] & 0237]);
#endif
break;
case 'X' : case 'x': /* Turn into ^Xc */
#ifdef IS_ASCII
Strbuf_append1(&b, 'X' & 0237);
#else
Strbuf_append1(&b, _toebcdic[_toascii['X'] & 0237]);
#endif
Strbuf_append1(&b, *s);
break;
case 'M' : case 'm': /* Turn into 0x80|c */
if (!NoNLSRebind) {
Strbuf_append1(&b, CTL_ESC('\033'));
Strbuf_append1(&b, *s);
} else {
#ifdef IS_ASCII
Strbuf_append1(&b, *s | 0x80);
#else
Strbuf_append1(&b, _toebcdic[_toascii[*s] | 0x80]);
#endif
}
break;
#ifdef WINNT_NATIVE
case 'N' : case 'n': /* NT */
{
Char bnt;
bnt = nt_translate_bindkey(s);
if (bnt != 0)
Strbuf_append1(&b, bnt);
else
bad_spec(s);
}
break;
#endif /* WINNT_NATIVE */
default:
abort();
}
break;
default:
goto bad_spec;
}
end:
cleanup_ignore(&b);
cleanup_until(&b);
Strbuf_terminate(&b);
str->buf = xrealloc(b.s, (b.len + 1) * sizeof (*str->buf));
str->len = b.len;
return str;
bad_spec:
bad_spec(s);
cleanup_until(&b);
return NULL;
}
static CStr *
parsestring(const Char *str, CStr *buf)
{
struct Strbuf b = Strbuf_INIT;
const Char *p;
eChar es;
if (*str == 0) {
xprintf("%s", CGETS(20, 5, "Null string specification\n"));
return NULL;
}
cleanup_push(&b, Strbuf_cleanup);
for (p = str; *p != 0; p++) {
if ((*p & CHAR) == '\\' || (*p & CHAR) == '^') {
if ((es = parseescape(&p)) == CHAR_ERR) {
cleanup_until(&b);
return 0;
} else
Strbuf_append1(&b, es);
}
else
Strbuf_append1(&b, *p & CHAR);
}
cleanup_ignore(&b);
cleanup_until(&b);
Strbuf_terminate(&b);
buf->buf = xrealloc(b.s, (b.len + 1) * sizeof (*buf->buf));
buf->len = b.len;
return buf;
}
static void
print_all_keys(void)
{
int prev, i;
CStr nilstr;
nilstr.buf = NULL;
nilstr.len = 0;
xprintf("%s", CGETS(20, 6, "Standard key bindings\n"));
prev = 0;
for (i = 0; i < 256; i++) {
if (CcKeyMap[prev] == CcKeyMap[i])
continue;
printkeys(CcKeyMap, prev, i - 1);
prev = i;
}
printkeys(CcKeyMap, prev, i - 1);
xprintf("%s", CGETS(20, 7, "Alternative key bindings\n"));
prev = 0;
for (i = 0; i < 256; i++) {
if (CcAltMap[prev] == CcAltMap[i])
continue;
printkeys(CcAltMap, prev, i - 1);
prev = i;
}
printkeys(CcAltMap, prev, i - 1);
xprintf("%s", CGETS(20, 8, "Multi-character bindings\n"));
PrintXkey(NULL); /* print all Xkey bindings */
xprintf("%s", CGETS(20, 9, "Arrow key bindings\n"));
PrintArrowKeys(&nilstr);
}
static void
printkeys(KEYCMD *map, int first, int last)
{
struct KeyFuncs *fp;
Char firstbuf[2], lastbuf[2];
CStr fb, lb;
unsigned char *unparsed;
fb.buf = firstbuf;
lb.buf = lastbuf;
firstbuf[0] = (Char) first;
firstbuf[1] = 0;
lastbuf[0] = (Char) last;
lastbuf[1] = 0;
fb.len = 1;
lb.len = 1;
unparsed = unparsestring(&fb, STRQQ);
cleanup_push(unparsed, xfree);
if (map[first] == F_UNASSIGNED) {
if (first == last)
xprintf(CGETS(20, 10, "%-15s-> is undefined\n"), unparsed);
cleanup_until(unparsed);
return;
}
for (fp = FuncNames; fp->name; fp++) {
if (fp->func == map[first]) {
if (first == last)
xprintf("%-15s-> %s\n", unparsed, fp->name);
else {
unsigned char *p;
p = unparsestring(&lb, STRQQ);
cleanup_push(p, xfree);
xprintf("%-4s to %-7s-> %s\n", unparsed, p, fp->name);
}
cleanup_until(unparsed);
return;
}
}
xprintf(CGETS(20, 11, "BUG!!! %s isn't bound to anything.\n"), unparsed);
if (map == CcKeyMap)
xprintf("CcKeyMap[%d] == %d\n", first, CcKeyMap[first]);
else
xprintf("CcAltMap[%d] == %d\n", first, CcAltMap[first]);
cleanup_until(unparsed);
}
static void
bindkey_usage(void)
{
xprintf("%s", CGETS(20, 12,
"Usage: bindkey [options] [--] [KEY [COMMAND]]\n"));
xprintf("%s", CGETS(20, 13,
" -a list or bind KEY in alternative key map\n"));
xprintf("%s", CGETS(20, 14,
" -b interpret KEY as a C-, M-, F- or X- key name\n"));
xprintf("%s", CGETS(20, 15,
" -s interpret COMMAND as a literal string to be output\n"));
xprintf("%s", CGETS(20, 16,
" -c interpret COMMAND as a builtin or external command\n"));
xprintf("%s", CGETS(20, 17,
" -v bind all keys to vi bindings\n"));
xprintf("%s", CGETS(20, 18,
" -e bind all keys to emacs bindings\n"));
xprintf("%s", CGETS(20, 19,
" -d bind all keys to default editor's bindings\n"));
xprintf("%s", CGETS(20, 20,
" -l list editor commands with descriptions\n"));
xprintf("%s", CGETS(20, 21,
" -r remove KEY's binding\n"));
xprintf("%s", CGETS(20, 22,
" -k interpret KEY as a symbolic arrow-key name\n"));
xprintf("%s", CGETS(20, 23,
" -- force a break from option processing\n"));
xprintf("%s", CGETS(20, 24,
" -u (or any invalid option) this message\n"));
xprintf("\n");
xprintf("%s", CGETS(20, 25,
"Without KEY or COMMAND, prints all bindings\n"));
xprintf("%s", CGETS(20, 26,
"Without COMMAND, prints the binding for KEY.\n"));
}
static void
list_functions(void)
{
struct KeyFuncs *fp;
for (fp = FuncNames; fp->name; fp++) {
xprintf("%s\n %s\n", fp->name, fp->desc);
}
}
| isc |
Tech-Curriculums/FPGA-101---Introduction-to-Verilog | digilent.adept.sdk_2.3.1/samples/depp/DeppDemo/DeppDemo.cpp | 1 | 12945 | /************************************************************************/
/* */
/* DeppDemo.cpp -- DEPP DEMO Main Program */
/* */
/************************************************************************/
/* Author: Aaron Odell */
/* Copyright: 2010 Digilent, Inc. */
/************************************************************************/
/* Module Description: */
/* DEPP Demo demonstrates how to transfer data to and from */
/* a Digilent FPGA board using the DEPP module of the Adept */
/* SDK. */
/* */
/************************************************************************/
/* Revision History: */
/* */
/* 03/02/2010(AaronO): created */
/* */
/************************************************************************/
#define _CRT_SECURE_NO_WARNINGS
/* ------------------------------------------------------------ */
/* Include File Definitions */
/* ------------------------------------------------------------ */
#if defined(WIN32)
/* Include Windows specific headers here.
*/
#include <windows.h>
#else
/* Include Unix specific headers here.
*/
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "dpcdecl.h"
#include "depp.h"
#include "dmgr.h"
/* ------------------------------------------------------------ */
/* Local Type and Constant Definitions */
/* ------------------------------------------------------------ */
const int cchSzLen = 1024;
const int cbBlockSize = 1000;
/* ------------------------------------------------------------ */
/* Global Variables */
/* ------------------------------------------------------------ */
BOOL fGetReg;
BOOL fPutReg;
BOOL fGetRegRepeat;
BOOL fPutRegRepeat;
BOOL fDvc;
BOOL fFile;
BOOL fCount;
BOOL fByte;
char szAction[cchSzLen];
char szRegister[cchSzLen];
char szDvc[cchSzLen];
char szFile[cchSzLen];
char szCount[cchSzLen];
char szByte[cchSzLen];
HIF hif = hifInvalid;
FILE * fhin = NULL;
FILE * fhout = NULL;
/* ------------------------------------------------------------ */
/* Local Variables */
/* ------------------------------------------------------------ */
/* ------------------------------------------------------------ */
/* Forward Declarations */
/* ------------------------------------------------------------ */
BOOL FParseParam(int cszArg, char * rgszArg[]);
void ShowUsage(char * sz);
BOOL FInit();
void ErrorExit();
void DoDvcTbl();
void DoPutReg();
void DoGetReg();
void DoPutRegRepeat();
void DoGetRegRepeat();
void StrcpyS( char* szDst, size_t cchDst, const char* szSrc );
/* ------------------------------------------------------------ */
/* Procedure Definitions */
/* ------------------------------------------------------------ */
/*** main
**
** Synopsis
** int main(cszArg, rgszArg)
**
** Input:
** cszArg - count of command line arguments
** rgszArg - array of command line arguments
**
** Output:
** none
**
** Errors:
** Exits with exit code 0 if successful, else non-zero
**
** Description:
** main function of DEPP Demo application.
*/
int main(int cszArg, char * rgszArg[]) {
if (!FParseParam(cszArg, rgszArg)) {
ShowUsage(rgszArg[0]);
return 1;
}
// DMGR API Call: DmgrOpen
if(!DmgrOpen(&hif, szDvc)) {
printf("DmgrOpen failed (check the device name you provided)\n");
return 0;
}
// DEPP API call: DeppEnable
if(!DeppEnable(hif)) {
printf("DeppEnable failed\n");
return 0;
}
if(fGetReg) {
DoGetReg(); /* Get single byte from register */
}
else if (fPutReg) {
DoPutReg(); /* Send single byte to register */
}
else if (fGetRegRepeat) {
DoGetRegRepeat(); /* Save file with contents of register */
}
else if (fPutRegRepeat) {
DoPutRegRepeat(); /* Load register with contents of file */
}
if( hif != hifInvalid ) {
// DEPP API Call: DeppDisable
DeppDisable(hif);
// DMGR API Call: DmgrClose
DmgrClose(hif);
}
return 0;
}
/* ------------------------------------------------------------ */
/*** DoGetReg
**
** Synopsis
** void DoGetReg()
**
** Input:
** none
**
** Output:
** none
**
** Errors:
** none
**
** Description:
** Gets a byte from, a specified register
*/
void DoGetReg() {
BYTE idReg;
BYTE idData;
char * szStop;
idReg = (BYTE) strtol(szRegister, &szStop, 10);
// DEPP API Call: DeppGetReg
if(!DeppGetReg(hif, idReg, &idData, fFalse)) {
printf("DeppGetReg failed\n");
ErrorExit();
}
printf("Complete. Recieved data %d\n", idData);
return;
}
/* ------------------------------------------------------------ */
/*** DoPutReg
**
** Synopsis
** void DoPutReg()
**
** Input:
** none
**
** Output:
** none
**
** Errors:
** none
**
** Description:
** Sends a byte to a specified register
*/
void DoPutReg() {
BYTE idReg;
BYTE idData;
char * szStop;
idReg = (BYTE) strtol(szRegister, &szStop, 10);
idData = (BYTE) strtol(szByte, &szStop, 10);
// DEPP API Call: DeppPutReg
if(!DeppPutReg(hif, idReg, idData, fFalse)) {
printf("DeppPutReg failed\n");
return;
}
printf("Complete. Register set.\n");
return;
}
/* ------------------------------------------------------------ */
/*** DoGetRegRepeat
**
** Synopsis
** void DoGetRegRepeat()
**
** Input:
** none
**
** Output:
** none
**
** Errors:
** none
**
** Description:
** Gets a stream of bytes from specified register
*/
void DoGetRegRepeat() {
long cb;
BYTE idReg;
char * szStop;
BYTE rgbStf[cbBlockSize];
int cbGet, cbGetTotal;
idReg = (BYTE) strtol(szRegister, &szStop, 10);
cb = strtol(szCount, &szStop, 10);
fhout = fopen(szFile, "wb");
if(fhout == NULL){
printf("Cannot open file\n");
ErrorExit();
}
cbGet = 0;
cbGetTotal = cb;
while (cbGetTotal > 0) {
if ((cbGetTotal - cbBlockSize) <= 0) {
cbGet = cbGetTotal;
cbGetTotal = 0;
}
else {
cbGet = cbBlockSize;
cbGetTotal -= cbBlockSize;
}
// DEPP API Call: DeppGetRegRepeat
if (!DeppGetRegRepeat(hif, idReg, rgbStf, cbGet, fFalse)) {
printf("DeppGetRegRepeat failed.\n");
ErrorExit();
}
fwrite(rgbStf, sizeof(BYTE), cbGet, fhout);
}
printf("Stream from register complete!\n");
if( fhout != NULL ) {
fclose(fhout);
}
return;
}
/* ------------------------------------------------------------ */
/*** DoPutRegRepeat
**
** Synopsis
** void DoPutRegRepeat()
**
** Input:
** none
**
** Output:
** none
**
** Errors:
** none
**
** Description:
** Sends a stream of bytes to specified register
*/
void DoPutRegRepeat() {
long cb;
BYTE idReg;
char * szStop;
BYTE rgbLd[cbBlockSize];
int cbSend, cbSendTotal, cbSendCheck;
idReg = (BYTE) strtol(szRegister, &szStop, 10);
cb = strtol(szCount, &szStop, 10);
fhin = fopen(szFile, "r+b");
if (fhin == NULL) {
printf("Cannot open file\n");
ErrorExit();
}
cbSendTotal = cb;
cbSend = 0;
while (cbSendTotal > 0) {
if ((cbSendTotal - cbBlockSize) <= 0) {
cbSend = cbSendTotal;
cbSendTotal = 0;
}
else {
cbSend = cbBlockSize;
cbSendTotal -= cbBlockSize;
}
cbSendCheck = fread(rgbLd, sizeof(BYTE), cbSend, fhin);
if (cbSendCheck != cbSend) {
printf("Cannot read specified number of bytes from file.\n");
ErrorExit();
}
// DEPP API Call: DeppPutRegRepeat
if(!DeppPutRegRepeat(hif, idReg, rgbLd, cbSend, fFalse)){
printf("DeppPutRegRepeat failed.\n");
ErrorExit();
}
}
printf("Stream to register complete!\n");
if( fhin != NULL ) {
fclose(fhin);
}
return;
}
/* ------------------------------------------------------------ */
/*** FParseParam
**
** Parameters:
** cszArg - number of command line arguments
** rgszArg - array of command line argument strings
**
** Return Value:
** none
**
** Errors:
** Returns fTrue if not parse errors, fFalse if command line
** errors detected.
**
** Description:
** Parse the command line parameters and set global variables
** based on what is found.
*/
BOOL FParseParam(int cszArg, char * rgszArg[]) {
int iszArg;
/* Initialize default flag values */
fGetReg = fFalse;
fPutReg = fFalse;
fGetRegRepeat = fFalse;
fPutRegRepeat = fFalse;
fDvc = fFalse;
fFile = fFalse;
fCount = fFalse;
fByte = fFalse;
// Ensure sufficient paramaters. Need at least program name, action flag, register number
if (cszArg < 3) {
return fFalse;
}
/* The first parameter is the action to perform. Copy the
** the first parameter into the action string.
*/
StrcpyS(szAction, cchSzLen, rgszArg[1]);
if(strcmp(szAction, "-g") == 0) {
fGetReg = fTrue;
}
else if( strcmp(szAction, "-p") == 0) {
fPutReg = fTrue;
}
else if( strcmp(szAction, "-s") == 0) {
fGetRegRepeat = fTrue;
}
else if( strcmp(szAction, "-l") == 0) {
fPutRegRepeat = fTrue;
}
else { // unrecognized action
return fFalse;
}
/* Second paramater is target register on device. Copy second
** paramater to the register string */
StrcpyS(szRegister, cchSzLen, rgszArg[2]);
/* Parse the command line parameters.
*/
iszArg = 3;
while(iszArg < cszArg) {
/* Check for the -d parameter which is used to specify
** the device name of the device to query.
*/
if (strcmp(rgszArg[iszArg], "-d") == 0) {
iszArg += 1;
if (iszArg >= cszArg) {
return fFalse;
}
StrcpyS(szDvc, cchSzLen, rgszArg[iszArg++]);
fDvc = fTrue;
}
/* Check for the -f parameter used to specify the
** input/output file name.
*/
else if (strcmp(rgszArg[iszArg], "-f") == 0) {
iszArg += 1;
if (iszArg >= cszArg) {
return fFalse;
}
StrcpyS(szFile, cchSnMax, rgszArg[iszArg++]);
fFile = fTrue;
}
/* Check for the -c parameter used to specify the
** number of bytes to read/write from file.
*/
else if (strcmp(rgszArg[iszArg], "-c") == 0) {
iszArg += 1;
if (iszArg >= cszArg) {
return fFalse;
}
StrcpyS(szCount, cchUsrNameMax, rgszArg[iszArg++]);
fCount = fTrue;
}
/* Check for the -b paramater used to specify the
** value of a single data byte to be written to the register
*/
else if (strcmp(rgszArg[iszArg], "-b") == 0) {
iszArg += 1;
if (iszArg >= cszArg) {
return fFalse;
}
StrcpyS(szByte, cchUsrNameMax, rgszArg[iszArg++]);
fByte = fTrue;
}
/* Not a recognized parameter
*/
else {
return fFalse;
}
} // End while
/* Input combination validity checks
*/
if(!fDvc) {
printf("Error: No device specified\n");
return fFalse;
}
if( fPutReg && !fByte ) {
printf("Error: No byte value provided\n");
return fFalse;
}
if( (fGetRegRepeat || fPutRegRepeat) && !fFile ) {
printf("Error: No filename provided\n");
return fFalse;
}
return fTrue;
}
/* ------------------------------------------------------------ */
/*** ShowUsage
**
** Synopsis
** VOID ShowUsage(sz)
**
** Input:
** szProgName - program name as called
**
** Output:
** none
**
** Errors:
** none
**
** Description:
** prints message to user detailing command line options
*/
void ShowUsage(char * szProgName) {
printf("\nDigilent DEPP demo\n");
printf("Usage: %s <action> <register> -d <device name> [options]\n", szProgName);
printf("\n\tActions:\n");
printf("\t-g\t\t\t\tGet register byte\n");
printf("\t-p\t\t\t\tPut Register byte\n");
printf("\t-l\t\t\t\tStream file into register\n");
printf("\t-s\t\t\t\tStream register into file\n");
printf("\n\tOptions:\n");
printf("\t-f <filename>\t\t\tSpecify file name\n");
printf("\t-c <# bytes>\t\t\tNumber of bytes to read/write\n");
printf("\t-b <byte>\t\t\tValue to load into register\n");
printf("\n\n");
}
/* ------------------------------------------------------------ */
/*** ErrorExit
**
** Parameters:
** none
**
** Return Value:
** none
**
** Errors:
** none
**
** Description:
** Disables DEPP, closes the device, close any open files, and exits the program
*/
void ErrorExit() {
if( hif != hifInvalid ) {
// DEPP API Call: DeppDisable
DeppDisable(hif);
// DMGR API Call: DmgrClose
DmgrClose(hif);
}
if( fhin != NULL ) {
fclose(fhin);
}
if( fhout != NULL ) {
fclose(fhout);
}
exit(1);
}
/* ------------------------------------------------------------ */
/*** StrcpyS
**
** Parameters:
** szDst - pointer to the destination string
** cchDst - size of destination string
** szSrc - pointer to zero terminated source string
**
** Return Value:
** none
**
** Errors:
** none
**
** Description:
** Cross platform version of Windows function strcpy_s.
*/
void StrcpyS( char* szDst, size_t cchDst, const char* szSrc ) {
#if defined (WIN32)
strcpy_s(szDst, cchDst, szSrc);
#else
if ( 0 < cchDst ) {
strncpy(szDst, szSrc, cchDst - 1);
szDst[cchDst - 1] = '\0';
}
#endif
}
/* ------------------------------------------------------------ */
/************************************************************************/
| mit |
onepercent/op | deps/freetype-gl-read-only/text-buffer.c | 1 | 15793 | /* ============================================================================
* Freetype GL - A C OpenGL Freetype engine
* Platform: Any
* WWW: http://code.google.com/p/freetype-gl/
* ----------------------------------------------------------------------------
* Copyright 2011,2012 Nicolas P. Rougier. 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.
*
* THIS SOFTWARE IS PROVIDED BY NICOLAS P. ROUGIER ''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 NICOLAS P. ROUGIER 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.
*
* The views and conclusions contained in the software and documentation are
* those of the authors and should not be interpreted as representing official
* policies, either expressed or implied, of Nicolas P. Rougier.
* ============================================================================
*/
#include <wchar.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <assert.h>
#include "opengl.h"
#include "text-buffer.h"
#define SET_GLYPH_VERTEX(value,x0,y0,z0,s0,t0,r,g,b,a,sh,gm) { \
glyph_vertex_t *gv=&value; \
gv->x=x0; gv->y=y0; gv->z=z0; \
gv->u=s0; gv->v=t0; \
gv->r=r; gv->g=g; gv->b=b; gv->a=a; \
gv->shift=sh; gv->gamma=gm;}
// ----------------------------------------------------------------------------
text_buffer_t *
text_buffer_new( size_t depth )
{
text_buffer_t *self = (text_buffer_t *) malloc (sizeof(text_buffer_t));
self->buffer = vertex_buffer_new("vertex:3f,tex_coord:2f,color:4f,ashift:1f,agamma:1f" );
self->manager = font_manager_new( 512, 512, depth );
self->shader = shader_load("/Users/jie/svn/v8/deps/freetype-gl-read-only/shaders/text.vert", "/Users/jie/svn/v8/deps/freetype-gl-read-only/shaders/text.frag");
self->shader_texture = glGetUniformLocation(self->shader, "texture");
self->shader_pixel = glGetUniformLocation(self->shader, "pixel");
self->line_start = 0;
self->line_ascender = 0;
self->base_color.r = 0.0;
self->base_color.g = 0.0;
self->base_color.b = 0.0;
self->base_color.a = 1.0;
self->line_descender = 0;
return self;
}
// ----------------------------------------------------------------------------
void
text_buffer_clear( text_buffer_t * self )
{
assert( self );
vertex_buffer_clear( self->buffer );
self->line_start = 0;
self->line_ascender = 0;
self->line_descender = 0;
}
// ----------------------------------------------------------------------------
void
text_buffer_render( text_buffer_t * self )
{
glEnable( GL_BLEND );
glEnable( GL_TEXTURE_2D );
glBindTexture( GL_TEXTURE_2D, self->manager->atlas->id );
if( self->manager->atlas->depth == 1 )
{
//glDisable( GL_COLOR_MATERIAL );
glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
glBlendColor( 1, 1, 1, 1 );
}
else
{
//glEnable( GL_COLOR_MATERIAL );
//glTexEnvi( GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_MODULATE );
//glBlendFunc( GL_ONE, GL_ONE_MINUS_SRC_ALPHA );
//glBlendColor( 1.0, 1.0, 1.0, 1.0 );
//glBlendFunc( GL_CONSTANT_COLOR_EXT, GL_ONE_MINUS_SRC_COLOR );
//glBlendColor( self->base_color.r,
//self->base_color.g,
//self->base_color.b,
//self->base_color.a );
glBlendFunc( GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA );
glBlendColor( 1, 1, 1, 1 );
}
glUseProgram( self->shader );
glUniform1i( self->shader_texture, 0 );
glUniform3f( self->shader_pixel,
1.0/self->manager->atlas->width,
1.0/self->manager->atlas->height,
self->manager->atlas->depth );
vertex_buffer_render( self->buffer, GL_TRIANGLES );
glUseProgram( 0 );
}
// ----------------------------------------------------------------------------
void
text_buffer_printf( text_buffer_t * self, vec2 *pen, ... )
{
markup_t *markup;
wchar_t *text;
va_list args;
if( vertex_buffer_size( self->buffer ) == 0 )
{
self->origin = *pen;
}
va_start ( args, pen );
do {
markup = va_arg( args, markup_t * );
if( markup == NULL )
{
return;
}
text = va_arg( args, wchar_t * );
text_buffer_add_text( self, pen, markup, text, wcslen(text) );
} while( markup != 0 );
va_end ( args );
}
// ----------------------------------------------------------------------------
void
text_buffer_move_last_line( text_buffer_t * self, float dy )
{
size_t i, j;
for( i=self->line_start; i < vector_size( self->buffer->items ); ++i )
{
ivec4 *item = (ivec4 *) vector_get( self->buffer->items, i);
for( j=item->vstart; j<item->vstart+item->vcount; ++j)
{
glyph_vertex_t * vertex =
(glyph_vertex_t *) vector_get( self->buffer->vertices, j );
vertex->y -= dy;
}
}
}
// ----------------------------------------------------------------------------
void
text_buffer_add_text( text_buffer_t * self,
vec2 * pen, markup_t * markup,
wchar_t * text, size_t length )
{
font_manager_t * manager = self->manager;
size_t i;
if( markup == NULL )
{
return;
}
if( !markup->font )
{
markup->font = font_manager_get_from_markup( manager, markup );
if( ! markup->font )
{
fprintf( stderr, "Houston, we've got a problem !\n" );
exit( EXIT_FAILURE );
}
}
if( length == 0 )
{
length = wcslen(text);
}
if( vertex_buffer_size( self->buffer ) == 0 )
{
self->origin = *pen;
}
text_buffer_add_wchar( self, pen, markup, text[0], 0 );
for( i=1; i<length; ++i )
{
text_buffer_add_wchar( self, pen, markup, text[i], text[i-1] );
}
}
// ----------------------------------------------------------------------------
void
text_buffer_add_wchar( text_buffer_t * self,
vec2 * pen, markup_t * markup,
wchar_t current, wchar_t previous )
{
size_t vcount = 0;
size_t icount = 0;
vertex_buffer_t * buffer = self->buffer;
texture_font_t * font = markup->font;
float gamma = markup->gamma;
// Maximum number of vertices is 20 (= 5x2 triangles) per glyph:
// - 2 triangles for background
// - 2 triangles for overline
// - 2 triangles for underline
// - 2 triangles for strikethrough
// - 2 triangles for glyph
glyph_vertex_t vertices[4*5];
GLuint indices[6*5];
texture_glyph_t *glyph;
texture_glyph_t *black;
float kerning = 0;
if( current == L'\n' )
{
pen->x = self->origin.x;
pen->y += self->line_descender;
self->line_descender = 0;
self->line_ascender = 0;
self->line_start = vector_size( self->buffer->items );
return;
}
if( markup->font->ascender > self->line_ascender )
{
float y = pen->y;
pen->y -= (markup->font->ascender - self->line_ascender);
text_buffer_move_last_line( self, (int)(y-pen->y) );
self->line_ascender = markup->font->ascender;
}
if( markup->font->descender < self->line_descender )
{
self->line_descender = markup->font->descender;
}
glyph = texture_font_get_glyph( font, current );
black = texture_font_get_glyph( font, -1 );
if( glyph == NULL )
{
return;
}
if( previous && markup->font->kerning )
{
kerning = texture_glyph_get_kerning( glyph, previous );
}
pen->x += kerning;
// Background
if( markup->background_color.alpha > 0 )
{
float r = markup->background_color.r;
float g = markup->background_color.g;
float b = markup->background_color.b;
float a = markup->background_color.a;
float x0 = ( pen->x -kerning );
float y0 = (int)( pen->y + font->descender );
float x1 = ( x0 + glyph->advance_x );
float y1 = (int)( y0 + font->height + font->linegap );
float s0 = black->s0;
float t0 = black->t0;
float s1 = black->s1;
float t1 = black->t1;
SET_GLYPH_VERTEX(vertices[vcount+0],
(int)x0,y0,0, s0,t0, r,g,b,a, x0-((int)x0), gamma );
SET_GLYPH_VERTEX(vertices[vcount+1],
(int)x0,y1,0, s0,t1, r,g,b,a, x0-((int)x0), gamma );
SET_GLYPH_VERTEX(vertices[vcount+2],
(int)x1,y1,0, s1,t1, r,g,b,a, x1-((int)x1), gamma );
SET_GLYPH_VERTEX(vertices[vcount+3],
(int)x1,y0,0, s1,t0, r,g,b,a, x1-((int)x1), gamma );
indices[icount + 0] = vcount+0;
indices[icount + 1] = vcount+1;
indices[icount + 2] = vcount+2;
indices[icount + 3] = vcount+0;
indices[icount + 4] = vcount+2;
indices[icount + 5] = vcount+3;
vcount += 4;
icount += 6;
}
// Underline
if( markup->underline )
{
float r = markup->underline_color.r;
float g = markup->underline_color.g;
float b = markup->underline_color.b;
float a = markup->underline_color.a;
float x0 = ( pen->x - kerning );
float y0 = (int)( pen->y + font->underline_position );
float x1 = ( x0 + glyph->advance_x );
float y1 = (int)( y0 + font->underline_thickness );
float s0 = black->s0;
float t0 = black->t0;
float s1 = black->s1;
float t1 = black->t1;
SET_GLYPH_VERTEX(vertices[vcount+0],
(int)x0,y0,0, s0,t0, r,g,b,a, x0-((int)x0), gamma );
SET_GLYPH_VERTEX(vertices[vcount+1],
(int)x0,y1,0, s0,t1, r,g,b,a, x0-((int)x0), gamma );
SET_GLYPH_VERTEX(vertices[vcount+2],
(int)x1,y1,0, s1,t1, r,g,b,a, x1-((int)x1), gamma );
SET_GLYPH_VERTEX(vertices[vcount+3],
(int)x1,y0,0, s1,t0, r,g,b,a, x1-((int)x1), gamma );
indices[icount + 0] = vcount+0;
indices[icount + 1] = vcount+1;
indices[icount + 2] = vcount+2;
indices[icount + 3] = vcount+0;
indices[icount + 4] = vcount+2;
indices[icount + 5] = vcount+3;
vcount += 4;
icount += 6;
}
// Overline
if( markup->overline )
{
float r = markup->overline_color.r;
float g = markup->overline_color.g;
float b = markup->overline_color.b;
float a = markup->overline_color.a;
float x0 = ( pen->x -kerning );
float y0 = (int)( pen->y + (int)font->ascender );
float x1 = ( x0 + glyph->advance_x );
float y1 = (int)( y0 + (int)font->underline_thickness );
float s0 = black->s0;
float t0 = black->t0;
float s1 = black->s1;
float t1 = black->t1;
SET_GLYPH_VERTEX(vertices[vcount+0],
(int)x0,y0,0, s0,t0, r,g,b,a, x0-((int)x0), gamma );
SET_GLYPH_VERTEX(vertices[vcount+1],
(int)x0,y1,0, s0,t1, r,g,b,a, x0-((int)x0), gamma );
SET_GLYPH_VERTEX(vertices[vcount+2],
(int)x1,y1,0, s1,t1, r,g,b,a, x1-((int)x1), gamma );
SET_GLYPH_VERTEX(vertices[vcount+3],
(int)x1,y0,0, s1,t0, r,g,b,a, x1-((int)x1), gamma );
indices[icount + 0] = vcount+0;
indices[icount + 1] = vcount+1;
indices[icount + 2] = vcount+2;
indices[icount + 3] = vcount+0;
indices[icount + 4] = vcount+2;
indices[icount + 5] = vcount+3;
vcount += 4;
icount += 6;
}
/* Strikethrough */
if( markup->strikethrough )
{
float r = markup->strikethrough_color.r;
float g = markup->strikethrough_color.g;
float b = markup->strikethrough_color.b;
float a = markup->strikethrough_color.a;
float x0 = ( pen->x -kerning );
float y0 = (int)( pen->y + (int)font->ascender*.33);
float x1 = ( x0 + glyph->advance_x );
float y1 = (int)( y0 + (int)font->underline_thickness );
float s0 = black->s0;
float t0 = black->t0;
float s1 = black->s1;
float t1 = black->t1;
SET_GLYPH_VERTEX(vertices[vcount+0],
(int)x0,y0,0, s0,t0, r,g,b,a, x0-((int)x0), gamma );
SET_GLYPH_VERTEX(vertices[vcount+1],
(int)x0,y1,0, s0,t1, r,g,b,a, x0-((int)x0), gamma );
SET_GLYPH_VERTEX(vertices[vcount+2],
(int)x1,y1,0, s1,t1, r,g,b,a, x1-((int)x1), gamma );
SET_GLYPH_VERTEX(vertices[vcount+3],
(int)x1,y0,0, s1,t0, r,g,b,a, x1-((int)x1), gamma );
indices[icount + 0] = vcount+0;
indices[icount + 1] = vcount+1;
indices[icount + 2] = vcount+2;
indices[icount + 3] = vcount+0;
indices[icount + 4] = vcount+2;
indices[icount + 5] = vcount+3;
vcount += 4;
icount += 6;
}
{
// Actual glyph
float r = markup->foreground_color.red;
float g = markup->foreground_color.green;
float b = markup->foreground_color.blue;
float a = markup->foreground_color.alpha;
float x0 = ( pen->x + glyph->offset_x );
float y0 = (int)( pen->y + glyph->offset_y );
float x1 = ( x0 + glyph->width );
float y1 = (int)( y0 - glyph->height );
float s0 = glyph->s0;
float t0 = glyph->t0;
float s1 = glyph->s1;
float t1 = glyph->t1;
SET_GLYPH_VERTEX(vertices[vcount+0],
(int)x0,y0,0, s0,t0, r,g,b,a, x0-((int)x0), gamma );
SET_GLYPH_VERTEX(vertices[vcount+1],
(int)x0,y1,0, s0,t1, r,g,b,a, x0-((int)x0), gamma );
SET_GLYPH_VERTEX(vertices[vcount+2],
(int)x1,y1,0, s1,t1, r,g,b,a, x1-((int)x1), gamma );
SET_GLYPH_VERTEX(vertices[vcount+3],
(int)x1,y0,0, s1,t0, r,g,b,a, x1-((int)x1), gamma );
indices[icount + 0] = vcount+0;
indices[icount + 1] = vcount+1;
indices[icount + 2] = vcount+2;
indices[icount + 3] = vcount+0;
indices[icount + 4] = vcount+2;
indices[icount + 5] = vcount+3;
vcount += 4;
icount += 6;
vertex_buffer_push_back( buffer, vertices, vcount, indices, icount );
pen->x += glyph->advance_x * (1.0 + markup->spacing);
}
}
| mit |
pokecoin/PokeCoin | src/addrman.cpp | 1 | 15730 | // Copyright (c) 2012 Pieter Wuille
// Copyright (c) 2013-2014 Pokécoin Developers
// Distributed under the MIT/X11 software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "addrman.h"
#include "hash.h"
using namespace std;
int CAddrInfo::GetTriedBucket(const std::vector<unsigned char> &nKey) const
{
CDataStream ss1(SER_GETHASH, 0);
std::vector<unsigned char> vchKey = GetKey();
ss1 << nKey << vchKey;
uint64 hash1 = Hash(ss1.begin(), ss1.end()).Get64();
CDataStream ss2(SER_GETHASH, 0);
std::vector<unsigned char> vchGroupKey = GetGroup();
ss2 << nKey << vchGroupKey << (hash1 % ADDRMAN_TRIED_BUCKETS_PER_GROUP);
uint64 hash2 = Hash(ss2.begin(), ss2.end()).Get64();
return hash2 % ADDRMAN_TRIED_BUCKET_COUNT;
}
int CAddrInfo::GetNewBucket(const std::vector<unsigned char> &nKey, const CNetAddr& src) const
{
CDataStream ss1(SER_GETHASH, 0);
std::vector<unsigned char> vchGroupKey = GetGroup();
std::vector<unsigned char> vchSourceGroupKey = src.GetGroup();
ss1 << nKey << vchGroupKey << vchSourceGroupKey;
uint64 hash1 = Hash(ss1.begin(), ss1.end()).Get64();
CDataStream ss2(SER_GETHASH, 0);
ss2 << nKey << vchSourceGroupKey << (hash1 % ADDRMAN_NEW_BUCKETS_PER_SOURCE_GROUP);
uint64 hash2 = Hash(ss2.begin(), ss2.end()).Get64();
return hash2 % ADDRMAN_NEW_BUCKET_COUNT;
}
bool CAddrInfo::IsTerrible(int64 nNow) const
{
if (nLastTry && nLastTry >= nNow-60) // never remove things tried the last minute
return false;
if (nTime > nNow + 10*60) // came in a flying DeLorean
return true;
if (nTime==0 || nNow-nTime > ADDRMAN_HORIZON_DAYS*86400) // not seen in over a month
return true;
if (nLastSuccess==0 && nAttempts>=ADDRMAN_RETRIES) // tried three times and never a success
return true;
if (nNow-nLastSuccess > ADDRMAN_MIN_FAIL_DAYS*86400 && nAttempts>=ADDRMAN_MAX_FAILURES) // 10 successive failures in the last week
return true;
return false;
}
double CAddrInfo::GetChance(int64 nNow) const
{
double fChance = 1.0;
int64 nSinceLastSeen = nNow - nTime;
int64 nSinceLastTry = nNow - nLastTry;
if (nSinceLastSeen < 0) nSinceLastSeen = 0;
if (nSinceLastTry < 0) nSinceLastTry = 0;
fChance *= 600.0 / (600.0 + nSinceLastSeen);
// deprioritize very recent attempts away
if (nSinceLastTry < 60*10)
fChance *= 0.01;
// deprioritize 50% after each failed attempt
for (int n=0; n<nAttempts; n++)
fChance /= 1.5;
return fChance;
}
CAddrInfo* CAddrMan::Find(const CNetAddr& addr, int *pnId)
{
std::map<CNetAddr, int>::iterator it = mapAddr.find(addr);
if (it == mapAddr.end())
return NULL;
if (pnId)
*pnId = (*it).second;
std::map<int, CAddrInfo>::iterator it2 = mapInfo.find((*it).second);
if (it2 != mapInfo.end())
return &(*it2).second;
return NULL;
}
CAddrInfo* CAddrMan::Create(const CAddress &addr, const CNetAddr &addrSource, int *pnId)
{
int nId = nIdCount++;
mapInfo[nId] = CAddrInfo(addr, addrSource);
mapAddr[addr] = nId;
mapInfo[nId].nRandomPos = vRandom.size();
vRandom.push_back(nId);
if (pnId)
*pnId = nId;
return &mapInfo[nId];
}
void CAddrMan::SwapRandom(unsigned int nRndPos1, unsigned int nRndPos2)
{
if (nRndPos1 == nRndPos2)
return;
assert(nRndPos1 < vRandom.size() && nRndPos2 < vRandom.size());
int nId1 = vRandom[nRndPos1];
int nId2 = vRandom[nRndPos2];
assert(mapInfo.count(nId1) == 1);
assert(mapInfo.count(nId2) == 1);
mapInfo[nId1].nRandomPos = nRndPos2;
mapInfo[nId2].nRandomPos = nRndPos1;
vRandom[nRndPos1] = nId2;
vRandom[nRndPos2] = nId1;
}
int CAddrMan::SelectTried(int nKBucket)
{
std::vector<int> &vTried = vvTried[nKBucket];
// random shuffle the first few elements (using the entire list)
// find the least recently tried among them
int64 nOldest = -1;
int nOldestPos = -1;
for (unsigned int i = 0; i < ADDRMAN_TRIED_ENTRIES_INSPECT_ON_EVICT && i < vTried.size(); i++)
{
int nPos = GetRandInt(vTried.size() - i) + i;
int nTemp = vTried[nPos];
vTried[nPos] = vTried[i];
vTried[i] = nTemp;
assert(nOldest == -1 || mapInfo.count(nTemp) == 1);
if (nOldest == -1 || mapInfo[nTemp].nLastSuccess < mapInfo[nOldest].nLastSuccess) {
nOldest = nTemp;
nOldestPos = nPos;
}
}
return nOldestPos;
}
int CAddrMan::ShrinkNew(int nUBucket)
{
assert(nUBucket >= 0 && (unsigned int)nUBucket < vvNew.size());
std::set<int> &vNew = vvNew[nUBucket];
// first look for deletable items
for (std::set<int>::iterator it = vNew.begin(); it != vNew.end(); it++)
{
assert(mapInfo.count(*it));
CAddrInfo &info = mapInfo[*it];
if (info.IsTerrible())
{
if (--info.nRefCount == 0)
{
SwapRandom(info.nRandomPos, vRandom.size()-1);
vRandom.pop_back();
mapAddr.erase(info);
mapInfo.erase(*it);
nNew--;
}
vNew.erase(it);
return 0;
}
}
// otherwise, select four randomly, and pick the oldest of those to replace
int n[4] = {GetRandInt(vNew.size()), GetRandInt(vNew.size()), GetRandInt(vNew.size()), GetRandInt(vNew.size())};
int nI = 0;
int nOldest = -1;
for (std::set<int>::iterator it = vNew.begin(); it != vNew.end(); it++)
{
if (nI == n[0] || nI == n[1] || nI == n[2] || nI == n[3])
{
assert(nOldest == -1 || mapInfo.count(*it) == 1);
if (nOldest == -1 || mapInfo[*it].nTime < mapInfo[nOldest].nTime)
nOldest = *it;
}
nI++;
}
assert(mapInfo.count(nOldest) == 1);
CAddrInfo &info = mapInfo[nOldest];
if (--info.nRefCount == 0)
{
SwapRandom(info.nRandomPos, vRandom.size()-1);
vRandom.pop_back();
mapAddr.erase(info);
mapInfo.erase(nOldest);
nNew--;
}
vNew.erase(nOldest);
return 1;
}
void CAddrMan::MakeTried(CAddrInfo& info, int nId, int nOrigin)
{
assert(vvNew[nOrigin].count(nId) == 1);
// remove the entry from all new buckets
for (std::vector<std::set<int> >::iterator it = vvNew.begin(); it != vvNew.end(); it++)
{
if ((*it).erase(nId))
info.nRefCount--;
}
nNew--;
assert(info.nRefCount == 0);
// what tried bucket to move the entry to
int nKBucket = info.GetTriedBucket(nKey);
std::vector<int> &vTried = vvTried[nKBucket];
// first check whether there is place to just add it
if (vTried.size() < ADDRMAN_TRIED_BUCKET_SIZE)
{
vTried.push_back(nId);
nTried++;
info.fInTried = true;
return;
}
// otherwise, find an item to evict
int nPos = SelectTried(nKBucket);
// find which new bucket it belongs to
assert(mapInfo.count(vTried[nPos]) == 1);
int nUBucket = mapInfo[vTried[nPos]].GetNewBucket(nKey);
std::set<int> &vNew = vvNew[nUBucket];
// remove the to-be-replaced tried entry from the tried set
CAddrInfo& infoOld = mapInfo[vTried[nPos]];
infoOld.fInTried = false;
infoOld.nRefCount = 1;
// do not update nTried, as we are going to move something else there immediately
// check whether there is place in that one,
if (vNew.size() < ADDRMAN_NEW_BUCKET_SIZE)
{
// if so, move it back there
vNew.insert(vTried[nPos]);
} else {
// otherwise, move it to the new bucket nId came from (there is certainly place there)
vvNew[nOrigin].insert(vTried[nPos]);
}
nNew++;
vTried[nPos] = nId;
// we just overwrote an entry in vTried; no need to update nTried
info.fInTried = true;
return;
}
void CAddrMan::Good_(const CService &addr, int64 nTime)
{
// printf("Good: addr=%s\n", addr.ToString().c_str());
int nId;
CAddrInfo *pinfo = Find(addr, &nId);
// if not found, bail out
if (!pinfo)
return;
CAddrInfo &info = *pinfo;
// check whether we are talking about the exact same CService (including same port)
if (info != addr)
return;
// update info
info.nLastSuccess = nTime;
info.nLastTry = nTime;
info.nTime = nTime;
info.nAttempts = 0;
// if it is already in the tried set, don't do anything else
if (info.fInTried)
return;
// find a bucket it is in now
int nRnd = GetRandInt(vvNew.size());
int nUBucket = -1;
for (unsigned int n = 0; n < vvNew.size(); n++)
{
int nB = (n+nRnd) % vvNew.size();
std::set<int> &vNew = vvNew[nB];
if (vNew.count(nId))
{
nUBucket = nB;
break;
}
}
// if no bucket is found, something bad happened;
// TODO: maybe re-add the node, but for now, just bail out
if (nUBucket == -1) return;
printf("Moving %s to tried\n", addr.ToString().c_str());
// move nId to the tried tables
MakeTried(info, nId, nUBucket);
}
bool CAddrMan::Add_(const CAddress &addr, const CNetAddr& source, int64 nTimePenalty)
{
if (!addr.IsRoutable())
return false;
bool fNew = false;
int nId;
CAddrInfo *pinfo = Find(addr, &nId);
if (pinfo)
{
// periodically update nTime
bool fCurrentlyOnline = (GetAdjustedTime() - addr.nTime < 24 * 60 * 60);
int64 nUpdateInterval = (fCurrentlyOnline ? 60 * 60 : 24 * 60 * 60);
if (addr.nTime && (!pinfo->nTime || pinfo->nTime < addr.nTime - nUpdateInterval - nTimePenalty))
pinfo->nTime = max((int64)0, addr.nTime - nTimePenalty);
// add services
pinfo->nServices |= addr.nServices;
// do not update if no new information is present
if (!addr.nTime || (pinfo->nTime && addr.nTime <= pinfo->nTime))
return false;
// do not update if the entry was already in the "tried" table
if (pinfo->fInTried)
return false;
// do not update if the max reference count is reached
if (pinfo->nRefCount == ADDRMAN_NEW_BUCKETS_PER_ADDRESS)
return false;
// stochastic test: previous nRefCount == N: 2^N times harder to increase it
int nFactor = 1;
for (int n=0; n<pinfo->nRefCount; n++)
nFactor *= 2;
if (nFactor > 1 && (GetRandInt(nFactor) != 0))
return false;
} else {
pinfo = Create(addr, source, &nId);
pinfo->nTime = max((int64)0, (int64)pinfo->nTime - nTimePenalty);
// printf("Added %s [nTime=%fhr]\n", pinfo->ToString().c_str(), (GetAdjustedTime() - pinfo->nTime) / 3600.0);
nNew++;
fNew = true;
}
int nUBucket = pinfo->GetNewBucket(nKey, source);
std::set<int> &vNew = vvNew[nUBucket];
if (!vNew.count(nId))
{
pinfo->nRefCount++;
if (vNew.size() == ADDRMAN_NEW_BUCKET_SIZE)
ShrinkNew(nUBucket);
vvNew[nUBucket].insert(nId);
}
return fNew;
}
void CAddrMan::Attempt_(const CService &addr, int64 nTime)
{
CAddrInfo *pinfo = Find(addr);
// if not found, bail out
if (!pinfo)
return;
CAddrInfo &info = *pinfo;
// check whether we are talking about the exact same CService (including same port)
if (info != addr)
return;
// update info
info.nLastTry = nTime;
info.nAttempts++;
}
CAddress CAddrMan::Select_(int nUnkBias)
{
if (size() == 0)
return CAddress();
double nCorTried = sqrt(nTried) * (100.0 - nUnkBias);
double nCorNew = sqrt(nNew) * nUnkBias;
if ((nCorTried + nCorNew)*GetRandInt(1<<30)/(1<<30) < nCorTried)
{
// use a tried node
double fChanceFactor = 1.0;
while(1)
{
int nKBucket = GetRandInt(vvTried.size());
std::vector<int> &vTried = vvTried[nKBucket];
if (vTried.size() == 0) continue;
int nPos = GetRandInt(vTried.size());
assert(mapInfo.count(vTried[nPos]) == 1);
CAddrInfo &info = mapInfo[vTried[nPos]];
if (GetRandInt(1<<30) < fChanceFactor*info.GetChance()*(1<<30))
return info;
fChanceFactor *= 1.2;
}
} else {
// use a new node
double fChanceFactor = 1.0;
while(1)
{
int nUBucket = GetRandInt(vvNew.size());
std::set<int> &vNew = vvNew[nUBucket];
if (vNew.size() == 0) continue;
int nPos = GetRandInt(vNew.size());
std::set<int>::iterator it = vNew.begin();
while (nPos--)
it++;
assert(mapInfo.count(*it) == 1);
CAddrInfo &info = mapInfo[*it];
if (GetRandInt(1<<30) < fChanceFactor*info.GetChance()*(1<<30))
return info;
fChanceFactor *= 1.2;
}
}
}
#ifdef DEBUG_ADDRMAN
int CAddrMan::Check_()
{
std::set<int> setTried;
std::map<int, int> mapNew;
if (vRandom.size() != nTried + nNew) return -7;
for (std::map<int, CAddrInfo>::iterator it = mapInfo.begin(); it != mapInfo.end(); it++)
{
int n = (*it).first;
CAddrInfo &info = (*it).second;
if (info.fInTried)
{
if (!info.nLastSuccess) return -1;
if (info.nRefCount) return -2;
setTried.insert(n);
} else {
if (info.nRefCount < 0 || info.nRefCount > ADDRMAN_NEW_BUCKETS_PER_ADDRESS) return -3;
if (!info.nRefCount) return -4;
mapNew[n] = info.nRefCount;
}
if (mapAddr[info] != n) return -5;
if (info.nRandomPos<0 || info.nRandomPos>=vRandom.size() || vRandom[info.nRandomPos] != n) return -14;
if (info.nLastTry < 0) return -6;
if (info.nLastSuccess < 0) return -8;
}
if (setTried.size() != nTried) return -9;
if (mapNew.size() != nNew) return -10;
for (int n=0; n<vvTried.size(); n++)
{
std::vector<int> &vTried = vvTried[n];
for (std::vector<int>::iterator it = vTried.begin(); it != vTried.end(); it++)
{
if (!setTried.count(*it)) return -11;
setTried.erase(*it);
}
}
for (int n=0; n<vvNew.size(); n++)
{
std::set<int> &vNew = vvNew[n];
for (std::set<int>::iterator it = vNew.begin(); it != vNew.end(); it++)
{
if (!mapNew.count(*it)) return -12;
if (--mapNew[*it] == 0)
mapNew.erase(*it);
}
}
if (setTried.size()) return -13;
if (mapNew.size()) return -15;
return 0;
}
#endif
void CAddrMan::GetAddr_(std::vector<CAddress> &vAddr)
{
int nNodes = ADDRMAN_GETADDR_MAX_PCT*vRandom.size()/100;
if (nNodes > ADDRMAN_GETADDR_MAX)
nNodes = ADDRMAN_GETADDR_MAX;
// perform a random shuffle over the first nNodes elements of vRandom (selecting from all)
for (int n = 0; n<nNodes; n++)
{
int nRndPos = GetRandInt(vRandom.size() - n) + n;
SwapRandom(n, nRndPos);
assert(mapInfo.count(vRandom[n]) == 1);
vAddr.push_back(mapInfo[vRandom[n]]);
}
}
void CAddrMan::Connected_(const CService &addr, int64 nTime)
{
CAddrInfo *pinfo = Find(addr);
// if not found, bail out
if (!pinfo)
return;
CAddrInfo &info = *pinfo;
// check whether we are talking about the exact same CService (including same port)
if (info != addr)
return;
// update info
int64 nUpdateInterval = 20 * 60;
if (nTime - info.nTime > nUpdateInterval)
info.nTime = nTime;
}
| mit |
IECS/MansOS | mos/chips/ads1115/ads1115.c | 1 | 3098 | /*
* Copyright (c) 2008-2012 the MansOS team. 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.
* 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 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.
*/
#include "ads1115.h"
#include "stdmansos.h"
#define ADS111X_I2C_ID I2C_BUS_SW
uint16_t adsActiveConfig;
// Write ADS111x register
bool writeAdsRegister(uint8_t reg, uint16_t val)
{
uint8_t err = false;
Handle_t intHandle;
ATOMIC_START(intHandle);
i2cSoftStart();
err |= i2cSoftWriteByte((ADS_ADDRESS << 1) | I2C_WRITE_FLAG);
err |= i2cSoftWriteByte(reg);
err |= i2cSoftWriteByte(val >> 8);
err |= i2cSoftWriteByte(val & 0xff);
i2cSoftStop();
ATOMIC_END(intHandle);
//PRINTF("wrote: %#x%x\n",val >> 8,val & 0xff);
return err == 0;
}
// Read ADS111x register
bool readAdsRegister(uint8_t reg, uint16_t *val)
{
uint8_t err = false;
*val = 0;
Handle_t intHandle;
ATOMIC_START(intHandle);
i2cSoftStart();
err |= i2cSoftWriteByte((ADS_ADDRESS << 1) | I2C_WRITE_FLAG);
err |= i2cSoftWriteByte(reg);
i2cSoftStop();
i2cSoftStart();
err |= i2cSoftWriteByte((ADS_ADDRESS << 1) | I2C_READ_FLAG);
uint8_t hi = i2cSoftReadByte(I2C_ACK);
uint8_t lo = i2cSoftReadByte(I2C_NO_ACK);
*val = (hi << 8) | lo;
i2cSoftStop();
ATOMIC_END(intHandle);
//PRINTF("recieved: %#x%x\n",hi,lo);
return err == 0;
}
void adsInit(void)
{
i2cInit(ADS111X_I2C_ID);
adsActiveConfig = ADS_DEFAULT_CONFIG;
writeAdsRegister(ADS_CONFIG_REGISTER, 0x8483);
adsSelectInput(0);
adsPowerDownSingleShotMode();
// this decreases energy usage if ADS is never read
i2cSoftStop();
}
bool readAds(uint16_t *val)
{
// check for mode, begin conversion if neccesary
if (adsActiveConfig & ADS_MODE_MASK) {
adsBeginSingleConversion();
}
return readAdsRegister(ADS_CONVERSION_REGISTER,val);
}
| mit |
sinamoeini/mapp4py | src/ff_meam.cpp | 1 | 2511 | /*--------------------------------------------
Created by Sina on 07/15/13.
Copyright (c) 2013 MIT. All rights reserved.
--------------------------------------------*/
#include "ff_meam.h"
#include "neighbor_md.h"
#include "atoms_md.h"
#include "elements.h"
#include "memory.h"
#include "pgcmc.h"
#include "api.h"
using namespace MAPP_NS;
/*--------------------------------------------
constructor
--------------------------------------------*/
ForceFieldMEAM::
ForceFieldMEAM(AtomsMD* atoms):
ForceFieldMD(atoms)
{
gcmc_n_cutoff=1;
gcmc_n_vars=1;
gcmc_tag_enabled=false;
neighbor->pair_wise=false;
}
/*--------------------------------------------
destructor
--------------------------------------------*/
ForceFieldMEAM::~ForceFieldMEAM()
{
}
/*--------------------------------------------
initiate before a run
--------------------------------------------*/
void ForceFieldMEAM::init()
{
pre_init();
}
/*--------------------------------------------
after a run
--------------------------------------------*/
void ForceFieldMEAM::fin()
{
post_fin();
}
/*--------------------------------------------
init xchng
--------------------------------------------*/
void ForceFieldMEAM::init_xchng()
{
}
/*--------------------------------------------
fin xchng
--------------------------------------------*/
void ForceFieldMEAM::fin_xchng()
{
}
/*--------------------------------------------
pre xchng energy
--------------------------------------------*/
void ForceFieldMEAM::pre_xchng_energy(GCMC* gcmc)
{
}
/*--------------------------------------------
xchng energy
--------------------------------------------*/
type0 ForceFieldMEAM::xchng_energy(GCMC* gcmc)
{
return 0.0;
}
/*--------------------------------------------
post xchng energy
--------------------------------------------*/
void ForceFieldMEAM::post_xchng_energy(GCMC*)
{
}
/*--------------------------------------------
force and energy calculation
--------------------------------------------*/
void ForceFieldMEAM::__force_calc()
{
}
/*--------------------------------------------
only energy calculation this is useful for
minimization/linesearch methods that do not
use derivatives of energy
--------------------------------------------*/
void ForceFieldMEAM::__energy_calc()
{
}
/*--------------------------------------------
python constructor
--------------------------------------------*/
void ForceFieldMEAM::ml_new(PyMethodDef& tp_methods)
{
}
| mit |
buoncubi/document_class_hierarchy | src/PointerArray.cpp | 1 | 13852 | /**
* @file PointerArray.cpp
* @author Buoncompagni Luca
* @date Sep 14, 2016
*
* @brief The complete #parray (parray#PointerArray<T>) and #patch names paces definition.
*
* It describes a common templated method to convert an object into a string (patch#to_string()).
* Also, it defines a templated manager to a dynamic array (parray#PointerArray) as well as a
* specialisation that deal with arrays of string (parray#StringPointerArray).
* For the last, also a static method for behavior testing is provided (StringPointerArray#tester()).
*/
#ifndef POINTER_ARRAY_H_
#define POINTER_ARRAY_H_
#include <iostream>
#include <sstream>
#include <string>
/// to emulate C++11 and get to_string translator
namespace patch{
/// returns the description of the parameter by using << operator on a fresh std#ostringstream
template < typename T > std::string to_string( const T& n ){
std::ostringstream stm ;
stm << n ;
return stm.str() ;
}
}
/// it specify the dynamic array manager for a generic data T and a std#string specialisation.
namespace parray{
/// the debugging string to be appended on log head by this list manager
const std::string LOG_HEADER = " PointerArray: ";
/// the debugging string to be appended on log head by the StringPointerArray#tester() for Test logs
const std::string LOG_HEADER_TEST = "\t[TEST] " + LOG_HEADER;
/// the debugging string to be appended on log head by the StringPointerArray#tester() for Warning logs
const std::string LOG_HEADER_WARNING = "[WARNING] " + LOG_HEADER;
/// the debugging string to be appended on log head by the StringPointerArray#tester() for Info logs
const std::string LOG_HEADER_INFO = "[INFO] " + LOG_HEADER;
/// the debugging string to be appended on log head by the StringPointerArray#tester() for Error logs
const std::string LOG_HEADER_ERROR = "[ERROR] " + LOG_HEADER;
/**
* \brief This class describes a manager of a dynamic array of generic type T*.
*
* It manage manipulation, creation, copy and destruction, as well as basic operator overloading.
* In details, the array is specified by: a pointer to the head, a size integer and a cnt meaning
* the number of elements currently in the array.
*/
template < class T> class PointerArray{
public:
/// does not initialise the set and invalidates the counter (generates also warning log to advertise the call of #setSize())
PointerArray(){
std::cout << LOG_HEADER_WARNING << "Construct empty object. First of all, call setSize(..)" << std::endl;
set = 0;
size = -1;
cnt = -1;
}
/// create a new empty array of specified size
PointerArray( const int length){
std::cout << LOG_HEADER_INFO << "Construct a new array with size: " << length << std::endl;
init( length);
}
/// #copy() constructors
PointerArray( const PointerArray<T>& original){
std::cout << LOG_HEADER_INFO << "Construct a copy of: " << original << std::endl;
copy( original);
}
/// destructors, invalidate counter, pointer and clear memory. Logs: "deleting", for debugging purposes.
virtual ~PointerArray(){
std::cout << LOG_HEADER_INFO << "deleting " << *this << std::endl;
if( set != 0){
delete [] set;
set = 0;
size = -1;
cnt = -1;
}
}
/// set the size of a new empty array on memory and delete the previous.
void setSize( const int length){
init( length);
}
/// returns the actual size of the array.
int getSize() const{
return size;
}
/// returns the actual number of elements in the array.
int getCnt() const{
return cnt;
}
/// returns the head to the memory managed by this class.
const T* getArray() const{
return set;
}
/// returns an element of the array by index.
virtual const T& get( int idx) const{
return set[ idx];
}
/** returns #get(). */
const T& operator[]( size_t idx) const{
return this->get( idx);
}
/// add an element into the array. Returns false if the array is full
virtual bool add( const T toAdd){
if( cnt < size){
set[ cnt++] = toAdd;
return true;
} else {
//cerr << LOG_HEADER_INFO << "array full, cannot add \"" << toAdd << "\"." << endl;
return false;
}
}
/// returns the index of an occurrence in the array. -1 if not found
virtual const int find( const T toFind) const{
for( int i = 0; i < size; i++)
if( set[ i] == toFind)
return i;
return -1;
}
/// delete the array and create a new memory location of the same size.
virtual void clear(){
cnt = 0;
newSet();
}
/// remove an element from the array (based on #find() and #remove(int)).
virtual const bool remove( T toRemove){
return remove( find( toRemove));
}
/// remove an element from the array by index.
virtual const bool remove( int idx){
if( idx >= 0 && idx < size){
for( int i = idx; i < size - 1; i++)
set[i] = set[i + 1];
cnt -= 1;
return true;
}
std::cerr << LOG_HEADER_ERROR << "array out of index, cannot remove the (" << idx << ")-th element." << std::endl;
return false;
}
/// replace the array with a new memory of the defined size. Possible old values are copied from start up to fill the array.
virtual void resize( const int newLenght){
if( newLenght == size)
return;
// make a copy
T* copy = new T[ size];
int copyCnt = cnt;
for( int i = 0 ; i < copyCnt; i++)
copy[ i] = set[ i];
// reset list
cnt = 0;
size = newLenght;
newSet();
// get the new size
int newCnt = copyCnt;
if( newCnt > newLenght)
newCnt = newLenght;
// re-populate the new list
for( int i = 0; i < newCnt; i++)
add( copy[i]);
// delete copy
delete [] copy;
copy = 0;
}
/// replace the array by removing empty cell on tail (size will be equal to cnt). Based on #resize().
virtual void pack(){
resize( cnt);
}
/// returns a description of the memory managed by this class
virtual const std::string toString() const{
std::string out = "(size=" + patch::to_string( size) + ", cnt=" + patch::to_string( cnt) + ", ";
for( int i = 0; i < size; i++){
if( i == 0)
out += "[ " + set[ i];
else {
out += ", " + set[ i];
if( i >= size - 1)
out += "]";
}
}
if( size == 1)
out += "]";
if( size == 0)
out += "[]";
out += ")";
return out;
}
/// calls #toString() to describe the object.
friend std::ostream& operator<<( std::ostream& strm, const PointerArray<T>& par){
return strm << par.toString();
}
/// returns true if all the elements of this array are the only elements of the parameter.
virtual bool equals( const PointerArray<T>& toCompare) const{
if( cnt != toCompare.getCnt())
return false;
for( int i = 0; i < cnt; i++)
if( set[ i] != toCompare.get( i))
return false;
return true;
}
/// calls #equals()
friend bool operator== (const PointerArray<T>& c1, const PointerArray<T>& c2){
return c1.equals( c2);
}
/// returns the negation of #equals()
friend bool operator!= (const PointerArray<T>& c1, const PointerArray<T>& c2){
return !operator==( c1, c2);
}
/// make a #copy() of this array.
PointerArray<T>& operator= ( const PointerArray<T>& newCopy){
this->copy( newCopy);
return *this;
}
/// returns true if there are no elements in the array.
virtual const bool isEmpty() const{
if( cnt == 0)
return true;
return false;
}
/// returns #isEmpty().
bool const operator! () const{
return isEmpty();
}
private:
int size; ///< the size of the dynamic array
int cnt; ///< the number of elements in the array
T* set; ///< the head of the array
/// initialises a new array of given lenght (based on #newSet()).
void init( int length){
if( length >= 0){
cnt = 0;
size = length;
set = 0;
newSet();
} else std::cerr << LOG_HEADER_ERROR << "cannot instantiate an array with negative length" << std::endl;
}
/// allocate a new memory of this object size. Delete old memory if is not invalidated.
void newSet(){
if( set != 0)
delete [] set;
set = new T[ size];
}
/// make a new copy in memory (based on #newSet()).
virtual void copy( const PointerArray<T>& original){
this->size = original.getSize();
this->cnt = original.getCnt();
this->set = 0;
newSet();
for( int i = 0; i < cnt; i++)
this->set[ i] = original.set[ i];
}
};
/**
* \brief It implements a #PointerArray with a string parameter (T).
* @see PointerArray
*/
class StringPointerArray : public PointerArray< std::string>{
public:
/// empty constructor, based on PointerArray#PointerArray().
StringPointerArray() : PointerArray() {}
/// constructor a new array of given length, based on PointerArray#PointerArray( int).
StringPointerArray( const int length) : PointerArray( length) {}
/// PointerArray#copy() constructor, based on PointerArray#PointerArray( PointerArray).
StringPointerArray( const StringPointerArray& original) : PointerArray( original) {}
/// empty destructor, it relies on the base implementation.
virtual ~StringPointerArray(){}
/// overload the PointerArray#add() method by call #resize if the array is full (generate warning).
virtual bool add( std::string toAdd){
if( ! PointerArray< std::string>::add( toAdd)){
resize( getSize() + 1);
std::cout << LOG_HEADER_WARNING << " array resized in order to add a new element." << std::endl;
add( toAdd);
}
return true;
}
/// static method to test the behavior of a PointerArray of strings.
static void tester(){
int n0 = 10;
int cnt0 = 5;
/// Creates (pa0) new StringPointerArray( const int) and populate with letters.
StringPointerArray pa0( n0);
for( int i = 0; i < cnt0; i++)
pa0.add( std::string( 1, 'A' + i)); // !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
std::cout << LOG_HEADER_TEST << "create an array of size " << n0 << " with " << cnt0 << " elements: \t\t pa0 = " << pa0 << std::endl;
printTestDelitator(); // "----------------------------"
/// StringPointerArray#remove( T) an element from pa0 and access the first char (StringPointerArray#operator[]()) after the manipulation.
std::cout << LOG_HEADER_TEST << "remove the first element: \t\t\t\t pa0 = ";
pa0.remove( std::string( 1, 'A'));
std::cout << pa0 << std::endl;
std::cout << LOG_HEADER_TEST << "so the first element of pa0 now is: pa[0]=" << pa0[0] << std::endl;
printTestDelitator(); // "----------------------------"
/// Creates (pa1) a new #StringPointerArray() and set is size to be smaller than pa0.
std::cout << LOG_HEADER_TEST << "create an array of unknown size..." << std::endl;
StringPointerArray pa1;
int n1 = n0 - 3;
int cnt1 = cnt0 - 1;
pa1.setSize( n1);
std::cout << LOG_HEADER_TEST << "set the size to " << n1 << " and add " << cnt1 << " elements and pack(): \t\t pa1 = ";
/// Populate (StringPointerArray::add()) pa1 with some elements.
for( int i = 0; i < cnt1; i++)
pa1.add( std::string( 1, 'B' + i));
pa1.pack();
std::cout << pa1 << std::endl;
printTestDelitator(); // "----------------------------"
/// Make a comparison (StringPointerArray#operator==()) between two #StringPointerArray (pa0 == pa1)
bool comparison1 = ( pa0 == pa1);
std::cout << LOG_HEADER_TEST << "are pa0 and pa1 equal? (pa0==pa1?)" << ( comparison1 ? "Yes." : "No.") << std::endl;
printTestDelitator(); // "----------------------------"
/// Creates (pa2) a copy (StringPointerArray#copy() and StringPointerArray(StringPointerArray)) of pa1.
StringPointerArray pa2;
pa2 = pa1; //pa2.copy( pa1);
std::cout << LOG_HEADER_TEST << "copy pa1 in pa2 \t\t\t\t\t\t pa2 = " << pa2 << std::endl;
/// StringPointerArray#remove() all its elements and makes a comparison.
pa2.clear();
std::cout << LOG_HEADER_TEST << "clear pa2 \t\t\t\t\t\t pa2 = " << pa2 << std::endl;
std::cout << LOG_HEADER_TEST << "is pa2 empty? " << ( !pa2 ? "Yes." : "No.") << " Is pa1 empty? " << ( !pa1 ? "Yes." : "No.") << "\t\t\t pa1 = " << pa1 << std::endl;
printTestDelitator(); // "----------------------------"
/// Adds two strings to pa2.
pa2.add( "hi");
pa2.add( "there");
std::cout << LOG_HEADER_TEST << "add something to pa2 \t\t\t\t\t pa2 = " << pa2 << std::endl;
/// Creates (pa3) a #copy() of pa2 and remove the first element.
StringPointerArray pa3( pa2);
pa3.remove( 0);
std::cout << LOG_HEADER_TEST << "copy constructor on pa2 and remove \"" << pa3[0] << "\" \t\t pa3 = " << pa3 << std::endl;
/// Makes a comparison (pa3 == pa2) and #pack() pa2.
bool comparison2 = ( pa3 == pa2);
std::cout << LOG_HEADER_TEST << "Are pa3 and pa2 equal? " << ( comparison2 ? "Yes." : "No.") << std::endl;
pa2.pack();
std::cout << LOG_HEADER_TEST << "Pack pa2. \t\t\t\t\t\t pa2 = " << pa2 << std::endl;
printTestDelitator(); // "----------------------------"
/// #resize() pa1 to be bigger and smaller.
int res1 = 20;
pa1.resize( res1);
std::cout << LOG_HEADER_TEST << "resize pa1 to " << res1 << " \t\t\t\t\t\t pa1 = " << pa1 << std::endl;
int res2 = 2;
pa1.resize( res2);
std::cout << LOG_HEADER_TEST << "resize pa1 to " << res2 << " \t\t\t\t\t\t pa1 = " << pa1 << std::endl;
}
private:
/// prints a line to separe different tests used in #tester() function
static void printTestDelitator(){
std::cout << " -------------------------------------------------------------------------------------------------------------------------------------------------- " << std::endl;
}
};
}
#endif /* POINTERARRAY_H_ */
| mit |
Xaetrz/AddSyn | AddSyn/Source/PluginEditor.cpp | 1 | 36238 | /*
==============================================================================
This is an automatically generated GUI class created by the Introjucer!
Be careful when adding custom code to these files, as only the code within
the "//[xyz]" and "//[/xyz]" sections will be retained when the file is loaded
and re-saved.
Created with Introjucer version: 3.1.0
------------------------------------------------------------------------------
The Introjucer is part of the JUCE library - "Jules' Utility Class Extensions"
Copyright 2004-13 by Raw Material Software Ltd.
==============================================================================
*/
//[Headers] You can add your own extra header files here...
#include "PluginProcessor.h"
//[/Headers]
#include "PluginEditor.h"
//[MiscUserDefs] You can add your own user definitions and misc code here...
//[/MiscUserDefs]
//==============================================================================
AddSynAudioProcessorEditor::AddSynAudioProcessorEditor (AddSynAudioProcessor& ownerFilter)
: AudioProcessorEditor(ownerFilter)
{
addAndMakeVisible (uxTabs = new TabbedComponent (TabbedButtonBar::TabsAtTop));
uxTabs->setTabBarDepth (30);
uxTabs->addTab (TRANS("Attack"), Colours::white, 0, false);
uxTabs->addTab (TRANS("Sustain"), Colours::white, 0, false);
uxTabs->addTab (TRANS("Release"), Colours::white, 0, false);
uxTabs->setCurrentTabIndex (0);
addAndMakeVisible (uxSlider1 = new Slider ("uxSlider1"));
uxSlider1->setRange (0, 1, 0);
uxSlider1->setSliderStyle (Slider::LinearVertical);
uxSlider1->setTextBoxStyle (Slider::NoTextBox, false, 80, 20);
uxSlider1->addListener (this);
addAndMakeVisible (uxSlider2 = new Slider ("uxSlider2"));
uxSlider2->setRange (0, 1, 0);
uxSlider2->setSliderStyle (Slider::LinearVertical);
uxSlider2->setTextBoxStyle (Slider::NoTextBox, false, 80, 20);
uxSlider2->addListener (this);
addAndMakeVisible (uxSlider3 = new Slider ("uxSlider3"));
uxSlider3->setRange (0, 1, 0);
uxSlider3->setSliderStyle (Slider::LinearVertical);
uxSlider3->setTextBoxStyle (Slider::NoTextBox, false, 80, 20);
uxSlider3->addListener (this);
addAndMakeVisible (uxSlider4 = new Slider ("uxSlider4"));
uxSlider4->setRange (0, 1, 0);
uxSlider4->setSliderStyle (Slider::LinearVertical);
uxSlider4->setTextBoxStyle (Slider::NoTextBox, false, 80, 20);
uxSlider4->addListener (this);
addAndMakeVisible (uxSlider5 = new Slider ("uxSlider5"));
uxSlider5->setRange (0, 1, 0);
uxSlider5->setSliderStyle (Slider::LinearVertical);
uxSlider5->setTextBoxStyle (Slider::NoTextBox, false, 80, 20);
uxSlider5->addListener (this);
addAndMakeVisible (uxSlider6 = new Slider ("uxSlider6"));
uxSlider6->setRange (0, 1, 0);
uxSlider6->setSliderStyle (Slider::LinearVertical);
uxSlider6->setTextBoxStyle (Slider::NoTextBox, false, 80, 20);
uxSlider6->addListener (this);
addAndMakeVisible (uxSlider7 = new Slider ("uxSlider7"));
uxSlider7->setRange (0, 1, 0);
uxSlider7->setSliderStyle (Slider::LinearVertical);
uxSlider7->setTextBoxStyle (Slider::NoTextBox, false, 80, 20);
uxSlider7->addListener (this);
addAndMakeVisible (uxSlider8 = new Slider ("uxSlider8"));
uxSlider8->setRange (0, 1, 0);
uxSlider8->setSliderStyle (Slider::LinearVertical);
uxSlider8->setTextBoxStyle (Slider::NoTextBox, false, 80, 20);
uxSlider8->addListener (this);
addAndMakeVisible (uxSlider9 = new Slider ("uxSlider9"));
uxSlider9->setRange (0, 1, 0);
uxSlider9->setSliderStyle (Slider::LinearVertical);
uxSlider9->setTextBoxStyle (Slider::NoTextBox, false, 80, 20);
uxSlider9->addListener (this);
addAndMakeVisible (uxSlider10 = new Slider ("uxSlider10"));
uxSlider10->setRange (0, 1, 0);
uxSlider10->setSliderStyle (Slider::LinearVertical);
uxSlider10->setTextBoxStyle (Slider::NoTextBox, false, 80, 20);
uxSlider10->addListener (this);
addAndMakeVisible (uxSlider11 = new Slider ("uxSlider11"));
uxSlider11->setRange (0, 1, 0);
uxSlider11->setSliderStyle (Slider::LinearVertical);
uxSlider11->setTextBoxStyle (Slider::NoTextBox, false, 80, 20);
uxSlider11->addListener (this);
addAndMakeVisible (uxSlider12 = new Slider ("uxSlider12"));
uxSlider12->setRange (0, 1, 0);
uxSlider12->setSliderStyle (Slider::LinearVertical);
uxSlider12->setTextBoxStyle (Slider::NoTextBox, false, 80, 20);
uxSlider12->addListener (this);
addAndMakeVisible (uxLeftButton = new TextButton ("uxLeftButton"));
uxLeftButton->setButtonText (TRANS("<"));
uxLeftButton->addListener (this);
addAndMakeVisible (uxName = new TextEditor ("uxName"));
uxName->setMultiLine (false);
uxName->setReturnKeyStartsNewLine (false);
uxName->setReadOnly (false);
uxName->setScrollbarsShown (true);
uxName->setCaretVisible (true);
uxName->setPopupMenuEnabled (true);
uxName->setText (String::empty);
addAndMakeVisible (uxRightButton = new TextButton ("uxRightButton"));
uxRightButton->setButtonText (TRANS(">"));
uxRightButton->addListener (this);
addAndMakeVisible (uxCreateInstrument = new TextButton ("uxCreateInstrument"));
uxCreateInstrument->setButtonText (TRANS("+"));
uxCreateInstrument->addListener (this);
uxCreateInstrument->setColour (TextButton::textColourOffId, Colour (0xff077c24));
addAndMakeVisible (uxDestroyInstrument = new TextButton ("uxDestroyInstrument"));
uxDestroyInstrument->setButtonText (TRANS("x"));
uxDestroyInstrument->addListener (this);
uxDestroyInstrument->setColour (TextButton::textColourOffId, Colour (0xfffd0000));
addAndMakeVisible (uxSineButton = new ToggleButton ("uxSineButton"));
uxSineButton->setButtonText (TRANS("Sine"));
uxSineButton->addListener (this);
uxSineButton->setToggleState (true, dontSendNotification);
addAndMakeVisible (uxTriangleButton = new ToggleButton ("uxTriangleButton"));
uxTriangleButton->setButtonText (TRANS("Triangle"));
uxTriangleButton->addListener (this);
addAndMakeVisible (uxSquareButton = new ToggleButton ("uxSquareButton"));
uxSquareButton->setButtonText (TRANS("Square"));
uxSquareButton->addListener (this);
addAndMakeVisible (uxSawButton = new ToggleButton ("uxSawButton"));
uxSawButton->setButtonText (TRANS("Saw"));
uxSawButton->addListener (this);
addAndMakeVisible (uxAttackSlider = new Slider ("uxAttackSlider"));
uxAttackSlider->setRange (0, 1, 0);
uxAttackSlider->setSliderStyle (Slider::RotaryHorizontalDrag);
uxAttackSlider->setTextBoxStyle (Slider::NoTextBox, false, 80, 20);
uxAttackSlider->setColour (Slider::rotarySliderFillColourId, Colour (0x7f000000));
uxAttackSlider->addListener (this);
addAndMakeVisible (uxReleaseSlider = new Slider ("uxReleaseSlider"));
uxReleaseSlider->setRange (0, 1, 0);
uxReleaseSlider->setSliderStyle (Slider::RotaryHorizontalDrag);
uxReleaseSlider->setTextBoxStyle (Slider::NoTextBox, false, 80, 20);
uxReleaseSlider->setColour (Slider::rotarySliderFillColourId, Colour (0x7f000000));
uxReleaseSlider->addListener (this);
addAndMakeVisible (label = new Label ("uxAttackLabel",
TRANS("Attack Rate")));
label->setFont (Font (15.00f, Font::plain));
label->setJustificationType (Justification::centredLeft);
label->setEditable (false, false, false);
label->setColour (TextEditor::textColourId, Colours::black);
label->setColour (TextEditor::backgroundColourId, Colour (0x00000000));
addAndMakeVisible (label2 = new Label ("uxReleaseLabel",
TRANS("Release Rate")));
label2->setFont (Font (15.00f, Font::plain));
label2->setJustificationType (Justification::centredLeft);
label2->setEditable (false, false, false);
label2->setColour (TextEditor::textColourId, Colours::black);
label2->setColour (TextEditor::backgroundColourId, Colour (0x00000000));
addAndMakeVisible (uxSustainSlider = new Slider ("uxSustainSlider"));
uxSustainSlider->setRange (0, 1, 0);
uxSustainSlider->setSliderStyle (Slider::RotaryHorizontalDrag);
uxSustainSlider->setTextBoxStyle (Slider::NoTextBox, false, 80, 20);
uxSustainSlider->setColour (Slider::rotarySliderFillColourId, Colour (0x7f000000));
uxSustainSlider->addListener (this);
addAndMakeVisible (label3 = new Label ("uxReleaseLabel",
TRANS("Sustain Rate")));
label3->setFont (Font (15.00f, Font::plain));
label3->setJustificationType (Justification::centredLeft);
label3->setEditable (false, false, false);
label3->setColour (TextEditor::textColourId, Colours::black);
label3->setColour (TextEditor::backgroundColourId, Colour (0x00000000));
addAndMakeVisible (uxSustainButton = new ToggleButton ("uxSustainButton"));
uxSustainButton->setButtonText (TRANS("Sustain"));
uxSustainButton->addListener (this);
uxSustainButton->setToggleState (true, dontSendNotification);
addAndMakeVisible (midiKeyboard = new MidiKeyboardComponent (ownerFilter.keyboardState, MidiKeyboardComponent::horizontalKeyboard));
midiKeyboard->setName ("MIDI Keyboard");
addAndMakeVisible (uxSoloButton = new ToggleButton ("uxSoloButton"));
uxSoloButton->setButtonText (TRANS("Solo"));
uxSoloButton->addListener (this);
addAndMakeVisible (uxMuteButton = new ToggleButton ("uxSoloButton"));
uxMuteButton->setButtonText (TRANS("Mute"));
uxMuteButton->addListener (this);
//[UserPreSize]
//[/UserPreSize]
setSize (472, 400);
//[Constructor] You can add your own custom stuff here..
startTimer(200); //starts timer with interval of 200ms
currTab = Attack;
ResetGUI(Attack);
//[/Constructor]
}
AddSynAudioProcessorEditor::~AddSynAudioProcessorEditor()
{
//[Destructor_pre]. You can add your own custom destruction code here..
//[/Destructor_pre]
uxTabs = nullptr;
uxSlider1 = nullptr;
uxSlider2 = nullptr;
uxSlider3 = nullptr;
uxSlider4 = nullptr;
uxSlider5 = nullptr;
uxSlider6 = nullptr;
uxSlider7 = nullptr;
uxSlider8 = nullptr;
uxSlider9 = nullptr;
uxSlider10 = nullptr;
uxSlider11 = nullptr;
uxSlider12 = nullptr;
uxLeftButton = nullptr;
uxName = nullptr;
uxRightButton = nullptr;
uxCreateInstrument = nullptr;
uxDestroyInstrument = nullptr;
uxSineButton = nullptr;
uxTriangleButton = nullptr;
uxSquareButton = nullptr;
uxSawButton = nullptr;
uxAttackSlider = nullptr;
uxReleaseSlider = nullptr;
label = nullptr;
label2 = nullptr;
uxSustainSlider = nullptr;
label3 = nullptr;
uxSustainButton = nullptr;
midiKeyboard = nullptr;
uxSoloButton = nullptr;
uxMuteButton = nullptr;
//[Destructor]. You can add your own custom destruction code here..
//[/Destructor]
}
//==============================================================================
void AddSynAudioProcessorEditor::paint (Graphics& g)
{
//[UserPrePaint] Add your own custom painting code here..
//[/UserPrePaint]
g.fillAll (Colour (0xff939393));
//[UserPaint] Add your own custom painting code here..
//[/UserPaint]
}
void AddSynAudioProcessorEditor::resized()
{
//[UserPreResize] Add your own custom resize code here..
//[/UserPreResize]
uxTabs->setBounds (16, 48, 288, 224);
uxSlider1->setBounds (16, 88, 23, 184);
uxSlider2->setBounds (40, 88, 23, 184);
uxSlider3->setBounds (64, 88, 23, 184);
uxSlider4->setBounds (88, 88, 23, 184);
uxSlider5->setBounds (112, 88, 23, 184);
uxSlider6->setBounds (136, 88, 23, 184);
uxSlider7->setBounds (160, 88, 23, 184);
uxSlider8->setBounds (184, 88, 23, 184);
uxSlider9->setBounds (208, 88, 23, 184);
uxSlider10->setBounds (232, 88, 23, 184);
uxSlider11->setBounds (256, 88, 23, 184);
uxSlider12->setBounds (280, 88, 23, 184);
uxLeftButton->setBounds (8, 8, 31, 24);
uxName->setBounds (80, 8, 158, 24);
uxRightButton->setBounds (40, 8, 32, 24);
uxCreateInstrument->setBounds (248, 8, 32, 24);
uxDestroyInstrument->setBounds (280, 8, 32, 24);
uxSineButton->setBounds (24, 288, 56, 24);
uxTriangleButton->setBounds (88, 288, 64, 24);
uxSquareButton->setBounds (168, 288, 64, 24);
uxSawButton->setBounds (248, 288, 64, 24);
uxAttackSlider->setBounds (304, 80, 64, 48);
uxReleaseSlider->setBounds (304, 136, 64, 48);
label->setBounds (376, 88, 80, 24);
label2->setBounds (376, 144, 80, 24);
uxSustainSlider->setBounds (304, 192, 64, 48);
label3->setBounds (376, 200, 80, 24);
uxSustainButton->setBounds (344, 248, 64, 24);
midiKeyboard->setBounds (0, 320, 472, 80);
uxSoloButton->setBounds (328, 8, 56, 24);
uxMuteButton->setBounds (384, 8, 56, 24);
//[UserResized] Add your own custom resize handling here..
//[/UserResized]
}
void AddSynAudioProcessorEditor::sliderValueChanged (Slider* sliderThatWasMoved)
{
//[UsersliderValueChanged_Pre]
AddSynthesizer synth = getProcessor()->getSynth();
EnvelopeType envType = getCurrentTab();
//[/UsersliderValueChanged_Pre]
if (sliderThatWasMoved == uxSlider1)
{
//[UserSliderCode_uxSlider1] -- add your slider handling code here..
synth.setLevels(currPos, 0, envType, uxSlider1->getValue());
//uxName->setText(juce::String(proc->getLevels(currPos).attackValues[0]));
//[/UserSliderCode_uxSlider1]
}
else if (sliderThatWasMoved == uxSlider2)
{
//[UserSliderCode_uxSlider2] -- add your slider handling code here..
synth.setLevels(currPos, 1, envType, uxSlider2->getValue());
//[/UserSliderCode_uxSlider2]
}
else if (sliderThatWasMoved == uxSlider3)
{
//[UserSliderCode_uxSlider3] -- add your slider handling code here..
synth.setLevels(currPos, 2, envType, uxSlider3->getValue());
//[/UserSliderCode_uxSlider3]
}
else if (sliderThatWasMoved == uxSlider4)
{
//[UserSliderCode_uxSlider4] -- add your slider handling code here..
synth.setLevels(currPos, 3, envType, uxSlider4->getValue());
//[/UserSliderCode_uxSlider4]
}
else if (sliderThatWasMoved == uxSlider5)
{
//[UserSliderCode_uxSlider5] -- add your slider handling code here..
synth.setLevels(currPos, 4, envType, uxSlider5->getValue());
//[/UserSliderCode_uxSlider5]
}
else if (sliderThatWasMoved == uxSlider6)
{
//[UserSliderCode_uxSlider6] -- add your slider handling code here..
synth.setLevels(currPos, 5, envType, uxSlider6->getValue());
//[/UserSliderCode_uxSlider6]
}
else if (sliderThatWasMoved == uxSlider7)
{
//[UserSliderCode_uxSlider7] -- add your slider handling code here..
synth.setLevels(currPos, 6, envType, uxSlider7->getValue());
//[/UserSliderCode_uxSlider7]
}
else if (sliderThatWasMoved == uxSlider8)
{
//[UserSliderCode_uxSlider8] -- add your slider handling code here..
synth.setLevels(currPos, 7, envType, uxSlider8->getValue());
//[/UserSliderCode_uxSlider8]
}
else if (sliderThatWasMoved == uxSlider9)
{
//[UserSliderCode_uxSlider9] -- add your slider handling code here..
synth.setLevels(currPos, 8, envType, uxSlider9->getValue());
//[/UserSliderCode_uxSlider9]
}
else if (sliderThatWasMoved == uxSlider10)
{
//[UserSliderCode_uxSlider10] -- add your slider handling code here..
synth.setLevels(currPos, 9, envType, uxSlider10->getValue());
//[/UserSliderCode_uxSlider10]
}
else if (sliderThatWasMoved == uxSlider11)
{
//[UserSliderCode_uxSlider11] -- add your slider handling code here..
synth.setLevels(currPos, 10, envType, uxSlider11->getValue());
//[/UserSliderCode_uxSlider11]
}
else if (sliderThatWasMoved == uxSlider12)
{
//[UserSliderCode_uxSlider12] -- add your slider handling code here..
synth.setLevels(currPos, 11, envType, uxSlider12->getValue());
//[/UserSliderCode_uxSlider12]
}
else if (sliderThatWasMoved == uxAttackSlider)
{
//[UserSliderCode_uxAttackSlider] -- add your slider handling code here..
synth.setRates(currPos, Attack, uxAttackSlider->getValue());
//[/UserSliderCode_uxAttackSlider]
}
else if (sliderThatWasMoved == uxReleaseSlider)
{
//[UserSliderCode_uxReleaseSlider] -- add your slider handling code here..
synth.setRates(currPos, Release, uxReleaseSlider->getValue());
//[/UserSliderCode_uxReleaseSlider]
}
else if (sliderThatWasMoved == uxSustainSlider)
{
//[UserSliderCode_uxSustainSlider] -- add your slider handling code here..
synth.setRates(currPos, Sustain, uxSustainSlider->getValue());
//[/UserSliderCode_uxSustainSlider]
}
//[UsersliderValueChanged_Post]
//[/UsersliderValueChanged_Post]
}
void AddSynAudioProcessorEditor::buttonClicked (Button* buttonThatWasClicked)
{
//[UserbuttonClicked_Pre]
AddSynAudioProcessor* proc = getProcessor();
AddSynthesizer synth = getProcessor()->getSynth();
//[/UserbuttonClicked_Pre]
if (buttonThatWasClicked == uxLeftButton)
{
//[UserButtonCode_uxLeftButton] -- add your button handler code here..
MoveNextInstrument(false);
//[/UserButtonCode_uxLeftButton]
}
else if (buttonThatWasClicked == uxRightButton)
{
//[UserButtonCode_uxRightButton] -- add your button handler code here..
MoveNextInstrument(true);
//[/UserButtonCode_uxRightButton]
}
else if (buttonThatWasClicked == uxCreateInstrument)
{
//[UserButtonCode_uxCreateInstrument] -- add your button handler code here..
for (int i = currPos + 1; i < currPos + 16; i++)
{
int currIndex = i % 16;
if (!synth.getActive(currIndex))
{
currPos = currIndex;
synth.setActive(currPos, true);
break;
}
}
ResetGUI(Attack);
//[/UserButtonCode_uxCreateInstrument]
}
else if (buttonThatWasClicked == uxDestroyInstrument)
{
//[UserButtonCode_uxDestroyInstrument] -- add your button handler code here..
synth.setActive(currPos, false);
MoveNextInstrument(false);
//[/UserButtonCode_uxDestroyInstrument]
}
else if (buttonThatWasClicked == uxSineButton)
{
//[UserButtonCode_uxSineButton] -- add your button handler code here..
setWaveTypeGUI(Sine);
synth.setWaveType(currPos, Sine);
//[/UserButtonCode_uxSineButton]
}
else if (buttonThatWasClicked == uxTriangleButton)
{
//[UserButtonCode_uxTriangleButton] -- add your button handler code here..
setWaveTypeGUI(Triangle);
synth.setWaveType(currPos, Triangle);
//[/UserButtonCode_uxTriangleButton]
}
else if (buttonThatWasClicked == uxSquareButton)
{
//[UserButtonCode_uxSquareButton] -- add your button handler code here..
setWaveTypeGUI(Square);
synth.setWaveType(currPos, Square);
//[/UserButtonCode_uxSquareButton]
}
else if (buttonThatWasClicked == uxSawButton)
{
//[UserButtonCode_uxSawButton] -- add your button handler code here..
setWaveTypeGUI(Sawtooth);
synth.setWaveType(currPos, Sawtooth);
//[/UserButtonCode_uxSawButton]
}
else if (buttonThatWasClicked == uxSustainButton)
{
//[UserButtonCode_uxSustainButton] -- add your button handler code here..
synth.setSustain(currPos, uxSustainButton->getToggleState());
//[/UserButtonCode_uxSustainButton]
}
else if (buttonThatWasClicked == uxSoloButton)
{
//[UserButtonCode_uxSoloButton] -- add your button handler code here..
uxMuteButton->setToggleState(false, new NotificationType());
bool isSolo = uxSoloButton->getToggleState();
proc->muted[currPos] = false;
for (int i = 0; i < 16; i++)
{
if (i != currPos)
proc->muted[i] = isSolo;
}
//[/UserButtonCode_uxSoloButton]
}
else if (buttonThatWasClicked == uxMuteButton)
{
//[UserButtonCode_uxMuteButton] -- add your button handler code here..
proc->muted[currPos] = uxMuteButton->getToggleState();
//[/UserButtonCode_uxMuteButton]
}
//[UserbuttonClicked_Post]
//[/UserbuttonClicked_Post]
}
//[MiscUserCode] You can add your own definitions of your custom methods or any other code here...
AddSynAudioProcessor* AddSynAudioProcessorEditor::getProcessor()
{
return static_cast <AddSynAudioProcessor*>(getAudioProcessor());
}
void AddSynAudioProcessorEditor::timerCallback()
{
AddSynAudioProcessor* ourProcessor = getProcessor();
//exchange any data you want between UI elements and the Plugin "ourProcessor"
// Hack for handling tab changes since I can't figure out how to add a ChangeListener to the TabbedComponenet
if (currTab != uxTabs->getCurrentTabIndex())
{
currTab = getCurrentTab();
ResetGUI(currTab);
}
}
// Move the currently displayed instrument GUI to next instrument
void AddSynAudioProcessorEditor::MoveNextInstrument(bool forward)
{
AddSynAudioProcessor* proc = getProcessor();
AddSynthesizer synth = proc->getSynth();
// If solo, turn off all mutes
if (uxSoloButton->getToggleState())
{
uxSoloButton->setToggleState(false, new NotificationType());
for (int i = 0; i < 16; i++)
{
proc->muted[i] = false;
}
}
int firstForward = -1;
int firstBackward = -1;
for (int i = currPos + 1; i < currPos + 16; i++)
{
int currIndex = i % 16;
if (synth.getActive(currIndex))
{
if (firstForward == -1) firstForward = currIndex;
firstBackward = currIndex;
}
}
if (firstForward != -1 && forward) currPos = firstForward;
else if (firstBackward != -1 && !forward) currPos = firstBackward;
ResetGUI(currTab);
}
// Reset all of the GUI elements according to given tab and current instrument index
void AddSynAudioProcessorEditor::ResetGUI(EnvelopeType envType)
{
AddSynthesizer synth = getProcessor()->getSynth();
Levels levels = synth.getLevels(currPos);
WaveType wavetype = synth.getWaveType(currPos);
uxName->setText(juce::String(currPos));
if (envType == Attack)
{
uxSlider1->setValue(levels.attackValues[0]);
uxSlider2->setValue(levels.attackValues[1]);
uxSlider3->setValue(levels.attackValues[2]);
uxSlider4->setValue(levels.attackValues[3]);
uxSlider5->setValue(levels.attackValues[4]);
uxSlider6->setValue(levels.attackValues[5]);
uxSlider7->setValue(levels.attackValues[6]);
uxSlider8->setValue(levels.attackValues[7]);
uxSlider9->setValue(levels.attackValues[8]);
uxSlider10->setValue(levels.attackValues[9]);
uxSlider11->setValue(levels.attackValues[10]);
uxSlider12->setValue(levels.attackValues[11]);
}
else if (envType == Sustain)
{
uxSlider1->setValue(levels.sustainValues[0]);
uxSlider2->setValue(levels.sustainValues[1]);
uxSlider3->setValue(levels.sustainValues[2]);
uxSlider4->setValue(levels.sustainValues[3]);
uxSlider5->setValue(levels.sustainValues[4]);
uxSlider6->setValue(levels.sustainValues[5]);
uxSlider7->setValue(levels.sustainValues[6]);
uxSlider8->setValue(levels.sustainValues[7]);
uxSlider9->setValue(levels.sustainValues[8]);
uxSlider10->setValue(levels.sustainValues[9]);
uxSlider11->setValue(levels.sustainValues[10]);
uxSlider12->setValue(levels.sustainValues[11]);
}
else // Release
{
uxSlider1->setValue(levels.releaseValues[0]);
uxSlider2->setValue(levels.releaseValues[1]);
uxSlider3->setValue(levels.releaseValues[2]);
uxSlider4->setValue(levels.releaseValues[3]);
uxSlider5->setValue(levels.releaseValues[4]);
uxSlider6->setValue(levels.releaseValues[5]);
uxSlider7->setValue(levels.releaseValues[6]);
uxSlider8->setValue(levels.releaseValues[7]);
uxSlider9->setValue(levels.releaseValues[8]);
uxSlider10->setValue(levels.releaseValues[9]);
uxSlider11->setValue(levels.releaseValues[10]);
uxSlider12->setValue(levels.releaseValues[11]);
}
uxAttackSlider->setValue(levels.attackRate);
uxReleaseSlider->setValue(levels.releaseRate);
uxSustainSlider->setValue(levels.sustainRate);
uxSustainButton->setToggleState(levels.isSustain, new NotificationType());
uxMuteButton->setToggleState(getProcessor()->muted[currPos], new NotificationType());
setWaveTypeGUI(wavetype);
}
void AddSynAudioProcessorEditor::setWaveTypeGUI(WaveType wt)
{
// Only allow one wavetype to be selected
uxSineButton->setToggleState(false, juce::NotificationType());
uxTriangleButton->setToggleState(false, juce::NotificationType());
uxSquareButton->setToggleState(false, juce::NotificationType());
uxSawButton->setToggleState(false, juce::NotificationType());
if (wt == Sine)
{
uxSineButton->setToggleState(true, juce::NotificationType());
}
else if (wt == Triangle)
{
uxTriangleButton->setToggleState(true, juce::NotificationType());
}
else if (wt == Square)
{
uxSquareButton->setToggleState(true, juce::NotificationType());
}
else
{
uxSawButton->setToggleState(true, juce::NotificationType());
}
}
EnvelopeType AddSynAudioProcessorEditor::getCurrentTab()
{
if (uxTabs->getCurrentTabName() == "Attack") return Attack;
else if (uxTabs->getCurrentTabName() == "Sustain") return Sustain;
else return Release;
}
//[/MiscUserCode]
//==============================================================================
#if 0
/* -- Introjucer information section --
This is where the Introjucer stores the metadata that describe this GUI layout, so
make changes in here at your peril!
BEGIN_JUCER_METADATA
<JUCER_COMPONENT documentType="Component" className="AddSynAudioProcessorEditor"
componentName="" parentClasses="public AudioProcessorEditor, public Timer"
constructorParams="AddSynAudioProcessor& ownerFilter" variableInitialisers="AudioProcessorEditor(ownerFilter)"
snapPixels="8" snapActive="1" snapShown="1" overlayOpacity="0.330"
fixedSize="0" initialWidth="472" initialHeight="400">
<BACKGROUND backgroundColour="ff939393"/>
<TABBEDCOMPONENT name="uxTabs" id="2611b740ea85765c" memberName="uxTabs" virtualName=""
explicitFocusOrder="0" pos="16 48 288 224" orientation="top"
tabBarDepth="30" initialTab="0">
<TAB name="Attack" colour="ffffffff" useJucerComp="0" contentClassName=""
constructorParams="" jucerComponentFile=""/>
<TAB name="Sustain" colour="ffffffff" useJucerComp="0" contentClassName=""
constructorParams="" jucerComponentFile=""/>
<TAB name="Release" colour="ffffffff" useJucerComp="0" contentClassName=""
constructorParams="" jucerComponentFile=""/>
</TABBEDCOMPONENT>
<SLIDER name="uxSlider1" id="c2f0fd34eb464ed7" memberName="uxSlider1"
virtualName="" explicitFocusOrder="0" pos="16 88 23 184" min="0"
max="1" int="0" style="LinearVertical" textBoxPos="NoTextBox"
textBoxEditable="1" textBoxWidth="80" textBoxHeight="20" skewFactor="1"/>
<SLIDER name="uxSlider2" id="b623ff4a4fc6be2" memberName="uxSlider2"
virtualName="" explicitFocusOrder="0" pos="40 88 23 184" min="0"
max="1" int="0" style="LinearVertical" textBoxPos="NoTextBox"
textBoxEditable="1" textBoxWidth="80" textBoxHeight="20" skewFactor="1"/>
<SLIDER name="uxSlider3" id="9c27aafe20719efc" memberName="uxSlider3"
virtualName="" explicitFocusOrder="0" pos="64 88 23 184" min="0"
max="1" int="0" style="LinearVertical" textBoxPos="NoTextBox"
textBoxEditable="1" textBoxWidth="80" textBoxHeight="20" skewFactor="1"/>
<SLIDER name="uxSlider4" id="33ba5a9f81e1224b" memberName="uxSlider4"
virtualName="" explicitFocusOrder="0" pos="88 88 23 184" min="0"
max="1" int="0" style="LinearVertical" textBoxPos="NoTextBox"
textBoxEditable="1" textBoxWidth="80" textBoxHeight="20" skewFactor="1"/>
<SLIDER name="uxSlider5" id="b91e3611b5a4511f" memberName="uxSlider5"
virtualName="" explicitFocusOrder="0" pos="112 88 23 184" min="0"
max="1" int="0" style="LinearVertical" textBoxPos="NoTextBox"
textBoxEditable="1" textBoxWidth="80" textBoxHeight="20" skewFactor="1"/>
<SLIDER name="uxSlider6" id="17f268caa59ccf84" memberName="uxSlider6"
virtualName="" explicitFocusOrder="0" pos="136 88 23 184" min="0"
max="1" int="0" style="LinearVertical" textBoxPos="NoTextBox"
textBoxEditable="1" textBoxWidth="80" textBoxHeight="20" skewFactor="1"/>
<SLIDER name="uxSlider7" id="2d66a2f0787933a6" memberName="uxSlider7"
virtualName="" explicitFocusOrder="0" pos="160 88 23 184" min="0"
max="1" int="0" style="LinearVertical" textBoxPos="NoTextBox"
textBoxEditable="1" textBoxWidth="80" textBoxHeight="20" skewFactor="1"/>
<SLIDER name="uxSlider8" id="875f6d0cd9506171" memberName="uxSlider8"
virtualName="" explicitFocusOrder="0" pos="184 88 23 184" min="0"
max="1" int="0" style="LinearVertical" textBoxPos="NoTextBox"
textBoxEditable="1" textBoxWidth="80" textBoxHeight="20" skewFactor="1"/>
<SLIDER name="uxSlider9" id="9fdf82fe5c247c77" memberName="uxSlider9"
virtualName="" explicitFocusOrder="0" pos="208 88 23 184" min="0"
max="1" int="0" style="LinearVertical" textBoxPos="NoTextBox"
textBoxEditable="1" textBoxWidth="80" textBoxHeight="20" skewFactor="1"/>
<SLIDER name="uxSlider10" id="f5b76a3051889417" memberName="uxSlider10"
virtualName="" explicitFocusOrder="0" pos="232 88 23 184" min="0"
max="1" int="0" style="LinearVertical" textBoxPos="NoTextBox"
textBoxEditable="1" textBoxWidth="80" textBoxHeight="20" skewFactor="1"/>
<SLIDER name="uxSlider11" id="d5dbb70ea1b26dda" memberName="uxSlider11"
virtualName="" explicitFocusOrder="0" pos="256 88 23 184" min="0"
max="1" int="0" style="LinearVertical" textBoxPos="NoTextBox"
textBoxEditable="1" textBoxWidth="80" textBoxHeight="20" skewFactor="1"/>
<SLIDER name="uxSlider12" id="99d5b5b537f41220" memberName="uxSlider12"
virtualName="" explicitFocusOrder="0" pos="280 88 23 184" min="0"
max="1" int="0" style="LinearVertical" textBoxPos="NoTextBox"
textBoxEditable="1" textBoxWidth="80" textBoxHeight="20" skewFactor="1"/>
<TEXTBUTTON name="uxLeftButton" id="7cea6a0e7fd85c52" memberName="uxLeftButton"
virtualName="" explicitFocusOrder="0" pos="8 8 31 24" buttonText="<"
connectedEdges="0" needsCallback="1" radioGroupId="0"/>
<TEXTEDITOR name="uxName" id="758b022a6f99cbeb" memberName="uxName" virtualName=""
explicitFocusOrder="0" pos="80 8 158 24" initialText="" multiline="0"
retKeyStartsLine="0" readonly="0" scrollbars="1" caret="1" popupmenu="1"/>
<TEXTBUTTON name="uxRightButton" id="af1d2284bc1e614f" memberName="uxRightButton"
virtualName="" explicitFocusOrder="0" pos="40 8 32 24" buttonText=">"
connectedEdges="0" needsCallback="1" radioGroupId="0"/>
<TEXTBUTTON name="uxCreateInstrument" id="622bc8e38a604465" memberName="uxCreateInstrument"
virtualName="" explicitFocusOrder="0" pos="248 8 32 24" textColOn="ff077c24"
buttonText="+" connectedEdges="0" needsCallback="1" radioGroupId="0"/>
<TEXTBUTTON name="uxDestroyInstrument" id="ccf53c0dfab64dda" memberName="uxDestroyInstrument"
virtualName="" explicitFocusOrder="0" pos="280 8 32 24" textColOn="fffd0000"
buttonText="x" connectedEdges="0" needsCallback="1" radioGroupId="0"/>
<TOGGLEBUTTON name="uxSineButton" id="8714c20a01cd6bb6" memberName="uxSineButton"
virtualName="" explicitFocusOrder="0" pos="24 288 56 24" buttonText="Sine"
connectedEdges="0" needsCallback="1" radioGroupId="0" state="1"/>
<TOGGLEBUTTON name="uxTriangleButton" id="2d0c5343bc4a811d" memberName="uxTriangleButton"
virtualName="" explicitFocusOrder="0" pos="88 288 64 24" buttonText="Triangle"
connectedEdges="0" needsCallback="1" radioGroupId="0" state="0"/>
<TOGGLEBUTTON name="uxSquareButton" id="8767e706be00dd68" memberName="uxSquareButton"
virtualName="" explicitFocusOrder="0" pos="168 288 64 24" buttonText="Square"
connectedEdges="0" needsCallback="1" radioGroupId="0" state="0"/>
<TOGGLEBUTTON name="uxSawButton" id="2084b9b8cb90582f" memberName="uxSawButton"
virtualName="" explicitFocusOrder="0" pos="248 288 64 24" buttonText="Saw"
connectedEdges="0" needsCallback="1" radioGroupId="0" state="0"/>
<SLIDER name="uxAttackSlider" id="2295b727f9479e61" memberName="uxAttackSlider"
virtualName="" explicitFocusOrder="0" pos="304 80 64 48" rotarysliderfill="7f000000"
min="0" max="1" int="0" style="RotaryHorizontalDrag" textBoxPos="NoTextBox"
textBoxEditable="1" textBoxWidth="80" textBoxHeight="20" skewFactor="1"/>
<SLIDER name="uxReleaseSlider" id="cef7c00c399fee98" memberName="uxReleaseSlider"
virtualName="" explicitFocusOrder="0" pos="304 136 64 48" rotarysliderfill="7f000000"
min="0" max="1" int="0" style="RotaryHorizontalDrag" textBoxPos="NoTextBox"
textBoxEditable="1" textBoxWidth="80" textBoxHeight="20" skewFactor="1"/>
<LABEL name="uxAttackLabel" id="ee617925784fb64d" memberName="label"
virtualName="" explicitFocusOrder="0" pos="376 88 80 24" edTextCol="ff000000"
edBkgCol="0" labelText="Attack Rate" editableSingleClick="0"
editableDoubleClick="0" focusDiscardsChanges="0" fontname="Default font"
fontsize="15" bold="0" italic="0" justification="33"/>
<LABEL name="uxReleaseLabel" id="fd9d0e1ffe0c86ea" memberName="label2"
virtualName="" explicitFocusOrder="0" pos="376 144 80 24" edTextCol="ff000000"
edBkgCol="0" labelText="Release Rate" editableSingleClick="0"
editableDoubleClick="0" focusDiscardsChanges="0" fontname="Default font"
fontsize="15" bold="0" italic="0" justification="33"/>
<SLIDER name="uxSustainSlider" id="ffee8eede01c4f9e" memberName="uxSustainSlider"
virtualName="" explicitFocusOrder="0" pos="304 192 64 48" rotarysliderfill="7f000000"
min="0" max="1" int="0" style="RotaryHorizontalDrag" textBoxPos="NoTextBox"
textBoxEditable="1" textBoxWidth="80" textBoxHeight="20" skewFactor="1"/>
<LABEL name="uxReleaseLabel" id="c9461fd4fb8c08" memberName="label3"
virtualName="" explicitFocusOrder="0" pos="376 200 80 24" edTextCol="ff000000"
edBkgCol="0" labelText="Sustain Rate" editableSingleClick="0"
editableDoubleClick="0" focusDiscardsChanges="0" fontname="Default font"
fontsize="15" bold="0" italic="0" justification="33"/>
<TOGGLEBUTTON name="uxSustainButton" id="140b6db1460d230e" memberName="uxSustainButton"
virtualName="" explicitFocusOrder="0" pos="344 248 64 24" buttonText="Sustain"
connectedEdges="0" needsCallback="1" radioGroupId="0" state="1"/>
<GENERICCOMPONENT name="MIDI Keyboard" id="a2d2fd3359bafd05" memberName="midiKeyboard"
virtualName="" explicitFocusOrder="0" pos="0 320 472 80" class="MidiKeyboardComponent"
params="ownerFilter.keyboardState, MidiKeyboardComponent::horizontalKeyboard"/>
<TOGGLEBUTTON name="uxSoloButton" id="892bd3dd7d282e09" memberName="uxSoloButton"
virtualName="" explicitFocusOrder="0" pos="328 8 56 24" buttonText="Solo"
connectedEdges="0" needsCallback="1" radioGroupId="0" state="0"/>
<TOGGLEBUTTON name="uxSoloButton" id="2b390ac4b5c07878" memberName="uxMuteButton"
virtualName="" explicitFocusOrder="0" pos="384 8 56 24" buttonText="Mute"
connectedEdges="0" needsCallback="1" radioGroupId="0" state="0"/>
</JUCER_COMPONENT>
END_JUCER_METADATA
*/
#endif
//[EndFile] You can add extra defines here...
//[/EndFile]
| mit |
ap--/python-seabreeze | src/libseabreeze/src/vendors/OceanOptics/protocols/interfaces/SpectrometerProtocolInterface.cpp | 1 | 1693 | /***************************************************//**
* @file SpectrometerProtocolInterface.cpp
* @date February 2009
* @author Ocean Optics, Inc.
*
* LICENSE:
*
* SeaBreeze Copyright (C) 2014, Ocean Optics 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.
*******************************************************/
#include "common/globals.h"
#include "vendors/OceanOptics/protocols/interfaces/SpectrometerProtocolInterface.h"
using namespace seabreeze;
SpectrometerProtocolInterface::SpectrometerProtocolInterface(Protocol *protocol)
: ProtocolHelper(protocol) {
}
SpectrometerProtocolInterface::~SpectrometerProtocolInterface() {
}
| mit |
junhuac/MQUIC | src/third_party/boringssl/src/crypto/cipher/e_chacha20poly1305.c | 1 | 11170 | /* Copyright (c) 2014, Google Inc.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
* SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
* OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
* CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
#include <openssl/aead.h>
#include <string.h>
#include <openssl/chacha.h>
#include <openssl/cipher.h>
#include <openssl/err.h>
#include <openssl/mem.h>
#include <openssl/poly1305.h>
#include "internal.h"
#include "../internal.h"
#define POLY1305_TAG_LEN 16
struct aead_chacha20_poly1305_ctx {
unsigned char key[32];
unsigned char tag_len;
};
static int aead_chacha20_poly1305_init(EVP_AEAD_CTX *ctx, const uint8_t *key,
size_t key_len, size_t tag_len) {
struct aead_chacha20_poly1305_ctx *c20_ctx;
if (tag_len == 0) {
tag_len = POLY1305_TAG_LEN;
}
if (tag_len > POLY1305_TAG_LEN) {
OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_TOO_LARGE);
return 0;
}
if (key_len != sizeof(c20_ctx->key)) {
return 0; /* internal error - EVP_AEAD_CTX_init should catch this. */
}
c20_ctx = OPENSSL_malloc(sizeof(struct aead_chacha20_poly1305_ctx));
if (c20_ctx == NULL) {
return 0;
}
memcpy(c20_ctx->key, key, key_len);
c20_ctx->tag_len = tag_len;
ctx->aead_state = c20_ctx;
return 1;
}
static void aead_chacha20_poly1305_cleanup(EVP_AEAD_CTX *ctx) {
struct aead_chacha20_poly1305_ctx *c20_ctx = ctx->aead_state;
OPENSSL_cleanse(c20_ctx->key, sizeof(c20_ctx->key));
OPENSSL_free(c20_ctx);
}
static void poly1305_update_length(poly1305_state *poly1305, size_t data_len) {
uint8_t length_bytes[8];
unsigned i;
for (i = 0; i < sizeof(length_bytes); i++) {
length_bytes[i] = data_len;
data_len >>= 8;
}
CRYPTO_poly1305_update(poly1305, length_bytes, sizeof(length_bytes));
}
typedef void (*aead_poly1305_update)(poly1305_state *ctx, const uint8_t *ad,
size_t ad_len, const uint8_t *ciphertext,
size_t ciphertext_len);
/* aead_poly1305 fills |tag| with the authentication tag for the given
* inputs, using |update| to control the order and format that the inputs are
* signed/authenticated. */
static void aead_poly1305(aead_poly1305_update update,
uint8_t tag[POLY1305_TAG_LEN],
const struct aead_chacha20_poly1305_ctx *c20_ctx,
const uint8_t nonce[12], const uint8_t *ad,
size_t ad_len, const uint8_t *ciphertext,
size_t ciphertext_len) {
alignas(16) uint8_t poly1305_key[32];
memset(poly1305_key, 0, sizeof(poly1305_key));
CRYPTO_chacha_20(poly1305_key, poly1305_key, sizeof(poly1305_key),
c20_ctx->key, nonce, 0);
poly1305_state ctx;
CRYPTO_poly1305_init(&ctx, poly1305_key);
update(&ctx, ad, ad_len, ciphertext, ciphertext_len);
CRYPTO_poly1305_finish(&ctx, tag);
}
static int seal_impl(aead_poly1305_update poly1305_update,
const EVP_AEAD_CTX *ctx, uint8_t *out, size_t *out_len,
size_t max_out_len, const uint8_t nonce[12],
const uint8_t *in, size_t in_len, const uint8_t *ad,
size_t ad_len) {
const struct aead_chacha20_poly1305_ctx *c20_ctx = ctx->aead_state;
const uint64_t in_len_64 = in_len;
/* |CRYPTO_chacha_20| uses a 32-bit block counter. Therefore we disallow
* individual operations that work on more than 256GB at a time.
* |in_len_64| is needed because, on 32-bit platforms, size_t is only
* 32-bits and this produces a warning because it's always false.
* Casting to uint64_t inside the conditional is not sufficient to stop
* the warning. */
if (in_len_64 >= (UINT64_C(1) << 32) * 64 - 64) {
OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_TOO_LARGE);
return 0;
}
if (in_len + c20_ctx->tag_len < in_len) {
OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_TOO_LARGE);
return 0;
}
if (max_out_len < in_len + c20_ctx->tag_len) {
OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BUFFER_TOO_SMALL);
return 0;
}
CRYPTO_chacha_20(out, in, in_len, c20_ctx->key, nonce, 1);
alignas(16) uint8_t tag[POLY1305_TAG_LEN];
aead_poly1305(poly1305_update, tag, c20_ctx, nonce, ad, ad_len, out, in_len);
memcpy(out + in_len, tag, c20_ctx->tag_len);
*out_len = in_len + c20_ctx->tag_len;
return 1;
}
static int open_impl(aead_poly1305_update poly1305_update,
const EVP_AEAD_CTX *ctx, uint8_t *out, size_t *out_len,
size_t max_out_len, const uint8_t nonce[12],
const uint8_t *in, size_t in_len, const uint8_t *ad,
size_t ad_len) {
const struct aead_chacha20_poly1305_ctx *c20_ctx = ctx->aead_state;
size_t plaintext_len;
const uint64_t in_len_64 = in_len;
if (in_len < c20_ctx->tag_len) {
OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BAD_DECRYPT);
return 0;
}
/* |CRYPTO_chacha_20| uses a 32-bit block counter. Therefore we disallow
* individual operations that work on more than 256GB at a time.
* |in_len_64| is needed because, on 32-bit platforms, size_t is only
* 32-bits and this produces a warning because it's always false.
* Casting to uint64_t inside the conditional is not sufficient to stop
* the warning. */
if (in_len_64 >= (UINT64_C(1) << 32) * 64 - 64) {
OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_TOO_LARGE);
return 0;
}
plaintext_len = in_len - c20_ctx->tag_len;
alignas(16) uint8_t tag[POLY1305_TAG_LEN];
aead_poly1305(poly1305_update, tag, c20_ctx, nonce, ad, ad_len, in,
plaintext_len);
if (CRYPTO_memcmp(tag, in + plaintext_len, c20_ctx->tag_len) != 0) {
OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_BAD_DECRYPT);
return 0;
}
CRYPTO_chacha_20(out, in, plaintext_len, c20_ctx->key, nonce, 1);
*out_len = plaintext_len;
return 1;
}
static void poly1305_update_padded_16(poly1305_state *poly1305,
const uint8_t *data, size_t data_len) {
static const uint8_t padding[16] = { 0 }; /* Padding is all zeros. */
CRYPTO_poly1305_update(poly1305, data, data_len);
if (data_len % 16 != 0) {
CRYPTO_poly1305_update(poly1305, padding, sizeof(padding) - (data_len % 16));
}
}
static void poly1305_update(poly1305_state *ctx, const uint8_t *ad,
size_t ad_len, const uint8_t *ciphertext,
size_t ciphertext_len) {
poly1305_update_padded_16(ctx, ad, ad_len);
poly1305_update_padded_16(ctx, ciphertext, ciphertext_len);
poly1305_update_length(ctx, ad_len);
poly1305_update_length(ctx, ciphertext_len);
}
static int aead_chacha20_poly1305_seal(const EVP_AEAD_CTX *ctx, uint8_t *out,
size_t *out_len, size_t max_out_len,
const uint8_t *nonce, size_t nonce_len,
const uint8_t *in, size_t in_len,
const uint8_t *ad, size_t ad_len) {
if (nonce_len != 12) {
OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_UNSUPPORTED_NONCE_SIZE);
return 0;
}
return seal_impl(poly1305_update, ctx, out, out_len, max_out_len, nonce, in,
in_len, ad, ad_len);
}
static int aead_chacha20_poly1305_open(const EVP_AEAD_CTX *ctx, uint8_t *out,
size_t *out_len, size_t max_out_len,
const uint8_t *nonce, size_t nonce_len,
const uint8_t *in, size_t in_len,
const uint8_t *ad, size_t ad_len) {
if (nonce_len != 12) {
OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_UNSUPPORTED_NONCE_SIZE);
return 0;
}
return open_impl(poly1305_update, ctx, out, out_len, max_out_len, nonce, in,
in_len, ad, ad_len);
}
static const EVP_AEAD aead_chacha20_poly1305 = {
32, /* key len */
12, /* nonce len */
POLY1305_TAG_LEN, /* overhead */
POLY1305_TAG_LEN, /* max tag length */
aead_chacha20_poly1305_init,
NULL, /* init_with_direction */
aead_chacha20_poly1305_cleanup,
aead_chacha20_poly1305_seal,
aead_chacha20_poly1305_open,
NULL, /* get_rc4_state */
NULL, /* get_iv */
};
const EVP_AEAD *EVP_aead_chacha20_poly1305(void) {
return &aead_chacha20_poly1305;
}
const EVP_AEAD *EVP_aead_chacha20_poly1305_rfc7539(void) {
return EVP_aead_chacha20_poly1305();
}
static void poly1305_update_old(poly1305_state *ctx, const uint8_t *ad,
size_t ad_len, const uint8_t *ciphertext,
size_t ciphertext_len) {
CRYPTO_poly1305_update(ctx, ad, ad_len);
poly1305_update_length(ctx, ad_len);
CRYPTO_poly1305_update(ctx, ciphertext, ciphertext_len);
poly1305_update_length(ctx, ciphertext_len);
}
static int aead_chacha20_poly1305_old_seal(
const EVP_AEAD_CTX *ctx, uint8_t *out, size_t *out_len, size_t max_out_len,
const uint8_t *nonce, size_t nonce_len, const uint8_t *in, size_t in_len,
const uint8_t *ad, size_t ad_len) {
if (nonce_len != 8) {
OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_UNSUPPORTED_NONCE_SIZE);
return 0;
}
uint8_t nonce_96[12];
memset(nonce_96, 0, 4);
memcpy(nonce_96 + 4, nonce, 8);
return seal_impl(poly1305_update_old, ctx, out, out_len, max_out_len,
nonce_96, in, in_len, ad, ad_len);
}
static int aead_chacha20_poly1305_old_open(
const EVP_AEAD_CTX *ctx, uint8_t *out, size_t *out_len, size_t max_out_len,
const uint8_t *nonce, size_t nonce_len, const uint8_t *in, size_t in_len,
const uint8_t *ad, size_t ad_len) {
if (nonce_len != 8) {
OPENSSL_PUT_ERROR(CIPHER, CIPHER_R_UNSUPPORTED_NONCE_SIZE);
return 0;
}
uint8_t nonce_96[12];
memset(nonce_96, 0, 4);
memcpy(nonce_96 + 4, nonce, 8);
return open_impl(poly1305_update_old, ctx, out, out_len, max_out_len,
nonce_96, in, in_len, ad, ad_len);
}
static const EVP_AEAD aead_chacha20_poly1305_old = {
32, /* key len */
8, /* nonce len */
POLY1305_TAG_LEN, /* overhead */
POLY1305_TAG_LEN, /* max tag length */
aead_chacha20_poly1305_init,
NULL, /* init_with_direction */
aead_chacha20_poly1305_cleanup,
aead_chacha20_poly1305_old_seal,
aead_chacha20_poly1305_old_open,
NULL, /* get_rc4_state */
NULL, /* get_iv */
};
const EVP_AEAD *EVP_aead_chacha20_poly1305_old(void) {
return &aead_chacha20_poly1305_old;
}
| mit |
metbosch/PCA-Lab | finalProject/PATH_LLIB/fftw-2.1.3/rfftw/fhf_16.c | 1 | 28228 | /*
* Copyright (c) 1997-1999 Massachusetts Institute of Technology
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
/* This file was automatically generated --- DO NOT EDIT */
/* Generated on Sun Nov 7 20:44:51 EST 1999 */
#include <fftw-int.h>
#include <fftw.h>
/* Generated by: ./genfft -magic-alignment-check -magic-twiddle-load-all -magic-variables 4 -magic-loopi -hc2hc-forward 16 */
/*
* This function contains 298 FP additions, 130 FP multiplications,
* (or, 244 additions, 76 multiplications, 54 fused multiply/add),
* 51 stack variables, and 128 memory accesses
*/
static const fftw_real K277785116 = FFTW_KONST(+0.277785116509801112371415406974266437187468595);
static const fftw_real K415734806 = FFTW_KONST(+0.415734806151272618539394188808952878369280406);
static const fftw_real K490392640 = FFTW_KONST(+0.490392640201615224563091118067119518486966865);
static const fftw_real K097545161 = FFTW_KONST(+0.097545161008064133924142434238511120463845809);
static const fftw_real K1_414213562 = FFTW_KONST(+1.414213562373095048801688724209698078569671875);
static const fftw_real K2_000000000 = FFTW_KONST(+2.000000000000000000000000000000000000000000000);
static const fftw_real K707106781 = FFTW_KONST(+0.707106781186547524400844362104849039284835938);
static const fftw_real K923879532 = FFTW_KONST(+0.923879532511286756128183189396788286822416626);
static const fftw_real K382683432 = FFTW_KONST(+0.382683432365089771728459984030398866761344562);
/*
* Generator Id's :
* $Id: exprdag.ml,v 1.41 1999/05/26 15:44:14 fftw Exp $
* $Id: fft.ml,v 1.43 1999/05/17 19:44:18 fftw Exp $
* $Id: to_c.ml,v 1.25 1999/10/26 21:41:32 stevenj Exp $
*/
void fftw_hc2hc_forward_16(fftw_real *A, const fftw_complex *W, int iostride, int m, int dist)
{
int i;
fftw_real *X;
fftw_real *Y;
X = A;
Y = A + (16 * iostride);
{
fftw_real tmp277;
fftw_real tmp280;
fftw_real tmp281;
fftw_real tmp309;
fftw_real tmp292;
fftw_real tmp307;
fftw_real tmp314;
fftw_real tmp322;
fftw_real tmp330;
fftw_real tmp284;
fftw_real tmp287;
fftw_real tmp288;
fftw_real tmp310;
fftw_real tmp291;
fftw_real tmp300;
fftw_real tmp315;
fftw_real tmp325;
fftw_real tmp331;
fftw_real tmp290;
fftw_real tmp289;
fftw_real tmp317;
fftw_real tmp318;
ASSERT_ALIGNED_DOUBLE;
{
fftw_real tmp275;
fftw_real tmp276;
fftw_real tmp278;
fftw_real tmp279;
ASSERT_ALIGNED_DOUBLE;
tmp275 = X[0];
tmp276 = X[8 * iostride];
tmp277 = tmp275 + tmp276;
tmp278 = X[4 * iostride];
tmp279 = X[12 * iostride];
tmp280 = tmp278 + tmp279;
tmp281 = tmp277 + tmp280;
tmp309 = tmp275 - tmp276;
tmp292 = tmp278 - tmp279;
}
{
fftw_real tmp303;
fftw_real tmp320;
fftw_real tmp306;
fftw_real tmp321;
ASSERT_ALIGNED_DOUBLE;
{
fftw_real tmp301;
fftw_real tmp302;
fftw_real tmp304;
fftw_real tmp305;
ASSERT_ALIGNED_DOUBLE;
tmp301 = X[iostride];
tmp302 = X[9 * iostride];
tmp303 = tmp301 - tmp302;
tmp320 = tmp301 + tmp302;
tmp304 = X[5 * iostride];
tmp305 = X[13 * iostride];
tmp306 = tmp304 - tmp305;
tmp321 = tmp304 + tmp305;
}
tmp307 = (K382683432 * tmp303) + (K923879532 * tmp306);
tmp314 = (K923879532 * tmp303) - (K382683432 * tmp306);
tmp322 = tmp320 - tmp321;
tmp330 = tmp320 + tmp321;
}
{
fftw_real tmp282;
fftw_real tmp283;
fftw_real tmp285;
fftw_real tmp286;
ASSERT_ALIGNED_DOUBLE;
tmp282 = X[2 * iostride];
tmp283 = X[10 * iostride];
tmp284 = tmp282 + tmp283;
tmp290 = tmp282 - tmp283;
tmp285 = X[14 * iostride];
tmp286 = X[6 * iostride];
tmp287 = tmp285 + tmp286;
tmp289 = tmp285 - tmp286;
}
tmp288 = tmp284 + tmp287;
tmp310 = K707106781 * (tmp290 + tmp289);
tmp291 = K707106781 * (tmp289 - tmp290);
{
fftw_real tmp296;
fftw_real tmp323;
fftw_real tmp299;
fftw_real tmp324;
ASSERT_ALIGNED_DOUBLE;
{
fftw_real tmp294;
fftw_real tmp295;
fftw_real tmp297;
fftw_real tmp298;
ASSERT_ALIGNED_DOUBLE;
tmp294 = X[15 * iostride];
tmp295 = X[7 * iostride];
tmp296 = tmp294 - tmp295;
tmp323 = tmp294 + tmp295;
tmp297 = X[3 * iostride];
tmp298 = X[11 * iostride];
tmp299 = tmp297 - tmp298;
tmp324 = tmp297 + tmp298;
}
tmp300 = (K382683432 * tmp296) - (K923879532 * tmp299);
tmp315 = (K923879532 * tmp296) + (K382683432 * tmp299);
tmp325 = tmp323 - tmp324;
tmp331 = tmp323 + tmp324;
}
{
fftw_real tmp329;
fftw_real tmp332;
fftw_real tmp327;
fftw_real tmp328;
ASSERT_ALIGNED_DOUBLE;
X[4 * iostride] = tmp281 - tmp288;
tmp329 = tmp281 + tmp288;
tmp332 = tmp330 + tmp331;
X[8 * iostride] = tmp329 - tmp332;
X[0] = tmp329 + tmp332;
Y[-4 * iostride] = tmp331 - tmp330;
tmp327 = tmp287 - tmp284;
tmp328 = K707106781 * (tmp325 - tmp322);
Y[-2 * iostride] = tmp327 + tmp328;
Y[-6 * iostride] = tmp328 - tmp327;
}
{
fftw_real tmp319;
fftw_real tmp326;
fftw_real tmp313;
fftw_real tmp316;
ASSERT_ALIGNED_DOUBLE;
tmp319 = tmp277 - tmp280;
tmp326 = K707106781 * (tmp322 + tmp325);
X[6 * iostride] = tmp319 - tmp326;
X[2 * iostride] = tmp319 + tmp326;
tmp313 = tmp309 + tmp310;
tmp316 = tmp314 + tmp315;
X[7 * iostride] = tmp313 - tmp316;
X[iostride] = tmp313 + tmp316;
}
tmp317 = tmp292 + tmp291;
tmp318 = tmp315 - tmp314;
Y[-3 * iostride] = tmp317 + tmp318;
Y[-5 * iostride] = tmp318 - tmp317;
{
fftw_real tmp293;
fftw_real tmp308;
fftw_real tmp311;
fftw_real tmp312;
ASSERT_ALIGNED_DOUBLE;
tmp293 = tmp291 - tmp292;
tmp308 = tmp300 - tmp307;
Y[-iostride] = tmp293 + tmp308;
Y[-7 * iostride] = tmp308 - tmp293;
tmp311 = tmp309 - tmp310;
tmp312 = tmp307 + tmp300;
X[5 * iostride] = tmp311 - tmp312;
X[3 * iostride] = tmp311 + tmp312;
}
}
X = X + dist;
Y = Y - dist;
for (i = 2; i < m; i = i + 2, X = X + dist, Y = Y - dist, W = W + 15) {
fftw_real tmp77;
fftw_real tmp161;
fftw_real tmp249;
fftw_real tmp262;
fftw_real tmp88;
fftw_real tmp263;
fftw_real tmp164;
fftw_real tmp246;
fftw_real tmp147;
fftw_real tmp158;
fftw_real tmp231;
fftw_real tmp198;
fftw_real tmp214;
fftw_real tmp232;
fftw_real tmp233;
fftw_real tmp234;
fftw_real tmp193;
fftw_real tmp213;
fftw_real tmp100;
fftw_real tmp222;
fftw_real tmp170;
fftw_real tmp206;
fftw_real tmp111;
fftw_real tmp223;
fftw_real tmp175;
fftw_real tmp207;
fftw_real tmp124;
fftw_real tmp135;
fftw_real tmp226;
fftw_real tmp187;
fftw_real tmp211;
fftw_real tmp227;
fftw_real tmp228;
fftw_real tmp229;
fftw_real tmp182;
fftw_real tmp210;
ASSERT_ALIGNED_DOUBLE;
{
fftw_real tmp71;
fftw_real tmp248;
fftw_real tmp76;
fftw_real tmp247;
ASSERT_ALIGNED_DOUBLE;
tmp71 = X[0];
tmp248 = Y[-15 * iostride];
{
fftw_real tmp73;
fftw_real tmp75;
fftw_real tmp72;
fftw_real tmp74;
ASSERT_ALIGNED_DOUBLE;
tmp73 = X[8 * iostride];
tmp75 = Y[-7 * iostride];
tmp72 = c_re(W[7]);
tmp74 = c_im(W[7]);
tmp76 = (tmp72 * tmp73) - (tmp74 * tmp75);
tmp247 = (tmp74 * tmp73) + (tmp72 * tmp75);
}
tmp77 = tmp71 + tmp76;
tmp161 = tmp71 - tmp76;
tmp249 = tmp247 + tmp248;
tmp262 = tmp248 - tmp247;
}
{
fftw_real tmp82;
fftw_real tmp162;
fftw_real tmp87;
fftw_real tmp163;
ASSERT_ALIGNED_DOUBLE;
{
fftw_real tmp79;
fftw_real tmp81;
fftw_real tmp78;
fftw_real tmp80;
ASSERT_ALIGNED_DOUBLE;
tmp79 = X[4 * iostride];
tmp81 = Y[-11 * iostride];
tmp78 = c_re(W[3]);
tmp80 = c_im(W[3]);
tmp82 = (tmp78 * tmp79) - (tmp80 * tmp81);
tmp162 = (tmp80 * tmp79) + (tmp78 * tmp81);
}
{
fftw_real tmp84;
fftw_real tmp86;
fftw_real tmp83;
fftw_real tmp85;
ASSERT_ALIGNED_DOUBLE;
tmp84 = X[12 * iostride];
tmp86 = Y[-3 * iostride];
tmp83 = c_re(W[11]);
tmp85 = c_im(W[11]);
tmp87 = (tmp83 * tmp84) - (tmp85 * tmp86);
tmp163 = (tmp85 * tmp84) + (tmp83 * tmp86);
}
tmp88 = tmp82 + tmp87;
tmp263 = tmp82 - tmp87;
tmp164 = tmp162 - tmp163;
tmp246 = tmp162 + tmp163;
}
{
fftw_real tmp141;
fftw_real tmp194;
fftw_real tmp157;
fftw_real tmp191;
fftw_real tmp146;
fftw_real tmp195;
fftw_real tmp152;
fftw_real tmp190;
ASSERT_ALIGNED_DOUBLE;
{
fftw_real tmp138;
fftw_real tmp140;
fftw_real tmp137;
fftw_real tmp139;
ASSERT_ALIGNED_DOUBLE;
tmp138 = X[15 * iostride];
tmp140 = Y[0];
tmp137 = c_re(W[14]);
tmp139 = c_im(W[14]);
tmp141 = (tmp137 * tmp138) - (tmp139 * tmp140);
tmp194 = (tmp139 * tmp138) + (tmp137 * tmp140);
}
{
fftw_real tmp154;
fftw_real tmp156;
fftw_real tmp153;
fftw_real tmp155;
ASSERT_ALIGNED_DOUBLE;
tmp154 = X[11 * iostride];
tmp156 = Y[-4 * iostride];
tmp153 = c_re(W[10]);
tmp155 = c_im(W[10]);
tmp157 = (tmp153 * tmp154) - (tmp155 * tmp156);
tmp191 = (tmp155 * tmp154) + (tmp153 * tmp156);
}
{
fftw_real tmp143;
fftw_real tmp145;
fftw_real tmp142;
fftw_real tmp144;
ASSERT_ALIGNED_DOUBLE;
tmp143 = X[7 * iostride];
tmp145 = Y[-8 * iostride];
tmp142 = c_re(W[6]);
tmp144 = c_im(W[6]);
tmp146 = (tmp142 * tmp143) - (tmp144 * tmp145);
tmp195 = (tmp144 * tmp143) + (tmp142 * tmp145);
}
{
fftw_real tmp149;
fftw_real tmp151;
fftw_real tmp148;
fftw_real tmp150;
ASSERT_ALIGNED_DOUBLE;
tmp149 = X[3 * iostride];
tmp151 = Y[-12 * iostride];
tmp148 = c_re(W[2]);
tmp150 = c_im(W[2]);
tmp152 = (tmp148 * tmp149) - (tmp150 * tmp151);
tmp190 = (tmp150 * tmp149) + (tmp148 * tmp151);
}
{
fftw_real tmp196;
fftw_real tmp197;
fftw_real tmp189;
fftw_real tmp192;
ASSERT_ALIGNED_DOUBLE;
tmp147 = tmp141 + tmp146;
tmp158 = tmp152 + tmp157;
tmp231 = tmp147 - tmp158;
tmp196 = tmp194 - tmp195;
tmp197 = tmp152 - tmp157;
tmp198 = tmp196 + tmp197;
tmp214 = tmp196 - tmp197;
tmp232 = tmp194 + tmp195;
tmp233 = tmp190 + tmp191;
tmp234 = tmp232 - tmp233;
tmp189 = tmp141 - tmp146;
tmp192 = tmp190 - tmp191;
tmp193 = tmp189 - tmp192;
tmp213 = tmp189 + tmp192;
}
}
{
fftw_real tmp94;
fftw_real tmp166;
fftw_real tmp99;
fftw_real tmp167;
fftw_real tmp168;
fftw_real tmp169;
ASSERT_ALIGNED_DOUBLE;
{
fftw_real tmp91;
fftw_real tmp93;
fftw_real tmp90;
fftw_real tmp92;
ASSERT_ALIGNED_DOUBLE;
tmp91 = X[2 * iostride];
tmp93 = Y[-13 * iostride];
tmp90 = c_re(W[1]);
tmp92 = c_im(W[1]);
tmp94 = (tmp90 * tmp91) - (tmp92 * tmp93);
tmp166 = (tmp92 * tmp91) + (tmp90 * tmp93);
}
{
fftw_real tmp96;
fftw_real tmp98;
fftw_real tmp95;
fftw_real tmp97;
ASSERT_ALIGNED_DOUBLE;
tmp96 = X[10 * iostride];
tmp98 = Y[-5 * iostride];
tmp95 = c_re(W[9]);
tmp97 = c_im(W[9]);
tmp99 = (tmp95 * tmp96) - (tmp97 * tmp98);
tmp167 = (tmp97 * tmp96) + (tmp95 * tmp98);
}
tmp100 = tmp94 + tmp99;
tmp222 = tmp166 + tmp167;
tmp168 = tmp166 - tmp167;
tmp169 = tmp94 - tmp99;
tmp170 = tmp168 - tmp169;
tmp206 = tmp169 + tmp168;
}
{
fftw_real tmp105;
fftw_real tmp172;
fftw_real tmp110;
fftw_real tmp173;
fftw_real tmp171;
fftw_real tmp174;
ASSERT_ALIGNED_DOUBLE;
{
fftw_real tmp102;
fftw_real tmp104;
fftw_real tmp101;
fftw_real tmp103;
ASSERT_ALIGNED_DOUBLE;
tmp102 = X[14 * iostride];
tmp104 = Y[-iostride];
tmp101 = c_re(W[13]);
tmp103 = c_im(W[13]);
tmp105 = (tmp101 * tmp102) - (tmp103 * tmp104);
tmp172 = (tmp103 * tmp102) + (tmp101 * tmp104);
}
{
fftw_real tmp107;
fftw_real tmp109;
fftw_real tmp106;
fftw_real tmp108;
ASSERT_ALIGNED_DOUBLE;
tmp107 = X[6 * iostride];
tmp109 = Y[-9 * iostride];
tmp106 = c_re(W[5]);
tmp108 = c_im(W[5]);
tmp110 = (tmp106 * tmp107) - (tmp108 * tmp109);
tmp173 = (tmp108 * tmp107) + (tmp106 * tmp109);
}
tmp111 = tmp105 + tmp110;
tmp223 = tmp172 + tmp173;
tmp171 = tmp105 - tmp110;
tmp174 = tmp172 - tmp173;
tmp175 = tmp171 + tmp174;
tmp207 = tmp171 - tmp174;
}
{
fftw_real tmp118;
fftw_real tmp178;
fftw_real tmp134;
fftw_real tmp185;
fftw_real tmp123;
fftw_real tmp179;
fftw_real tmp129;
fftw_real tmp184;
ASSERT_ALIGNED_DOUBLE;
{
fftw_real tmp115;
fftw_real tmp117;
fftw_real tmp114;
fftw_real tmp116;
ASSERT_ALIGNED_DOUBLE;
tmp115 = X[iostride];
tmp117 = Y[-14 * iostride];
tmp114 = c_re(W[0]);
tmp116 = c_im(W[0]);
tmp118 = (tmp114 * tmp115) - (tmp116 * tmp117);
tmp178 = (tmp116 * tmp115) + (tmp114 * tmp117);
}
{
fftw_real tmp131;
fftw_real tmp133;
fftw_real tmp130;
fftw_real tmp132;
ASSERT_ALIGNED_DOUBLE;
tmp131 = X[13 * iostride];
tmp133 = Y[-2 * iostride];
tmp130 = c_re(W[12]);
tmp132 = c_im(W[12]);
tmp134 = (tmp130 * tmp131) - (tmp132 * tmp133);
tmp185 = (tmp132 * tmp131) + (tmp130 * tmp133);
}
{
fftw_real tmp120;
fftw_real tmp122;
fftw_real tmp119;
fftw_real tmp121;
ASSERT_ALIGNED_DOUBLE;
tmp120 = X[9 * iostride];
tmp122 = Y[-6 * iostride];
tmp119 = c_re(W[8]);
tmp121 = c_im(W[8]);
tmp123 = (tmp119 * tmp120) - (tmp121 * tmp122);
tmp179 = (tmp121 * tmp120) + (tmp119 * tmp122);
}
{
fftw_real tmp126;
fftw_real tmp128;
fftw_real tmp125;
fftw_real tmp127;
ASSERT_ALIGNED_DOUBLE;
tmp126 = X[5 * iostride];
tmp128 = Y[-10 * iostride];
tmp125 = c_re(W[4]);
tmp127 = c_im(W[4]);
tmp129 = (tmp125 * tmp126) - (tmp127 * tmp128);
tmp184 = (tmp127 * tmp126) + (tmp125 * tmp128);
}
{
fftw_real tmp183;
fftw_real tmp186;
fftw_real tmp180;
fftw_real tmp181;
ASSERT_ALIGNED_DOUBLE;
tmp124 = tmp118 + tmp123;
tmp135 = tmp129 + tmp134;
tmp226 = tmp124 - tmp135;
tmp183 = tmp118 - tmp123;
tmp186 = tmp184 - tmp185;
tmp187 = tmp183 - tmp186;
tmp211 = tmp183 + tmp186;
tmp227 = tmp178 + tmp179;
tmp228 = tmp184 + tmp185;
tmp229 = tmp227 - tmp228;
tmp180 = tmp178 - tmp179;
tmp181 = tmp129 - tmp134;
tmp182 = tmp180 + tmp181;
tmp210 = tmp180 - tmp181;
}
}
{
fftw_real tmp177;
fftw_real tmp201;
fftw_real tmp271;
fftw_real tmp273;
fftw_real tmp200;
fftw_real tmp274;
fftw_real tmp204;
fftw_real tmp272;
ASSERT_ALIGNED_DOUBLE;
{
fftw_real tmp165;
fftw_real tmp176;
fftw_real tmp269;
fftw_real tmp270;
ASSERT_ALIGNED_DOUBLE;
tmp165 = tmp161 - tmp164;
tmp176 = K707106781 * (tmp170 - tmp175);
tmp177 = tmp165 + tmp176;
tmp201 = tmp165 - tmp176;
tmp269 = K707106781 * (tmp207 - tmp206);
tmp270 = tmp263 + tmp262;
tmp271 = tmp269 + tmp270;
tmp273 = tmp270 - tmp269;
}
{
fftw_real tmp188;
fftw_real tmp199;
fftw_real tmp202;
fftw_real tmp203;
ASSERT_ALIGNED_DOUBLE;
tmp188 = (K923879532 * tmp182) + (K382683432 * tmp187);
tmp199 = (K382683432 * tmp193) - (K923879532 * tmp198);
tmp200 = tmp188 + tmp199;
tmp274 = tmp199 - tmp188;
tmp202 = (K382683432 * tmp182) - (K923879532 * tmp187);
tmp203 = (K382683432 * tmp198) + (K923879532 * tmp193);
tmp204 = tmp202 - tmp203;
tmp272 = tmp202 + tmp203;
}
Y[-11 * iostride] = tmp177 - tmp200;
X[3 * iostride] = tmp177 + tmp200;
Y[-15 * iostride] = tmp201 - tmp204;
X[7 * iostride] = tmp201 + tmp204;
X[11 * iostride] = -(tmp271 - tmp272);
Y[-3 * iostride] = tmp272 + tmp271;
X[15 * iostride] = -(tmp273 - tmp274);
Y[-7 * iostride] = tmp274 + tmp273;
}
{
fftw_real tmp209;
fftw_real tmp217;
fftw_real tmp265;
fftw_real tmp267;
fftw_real tmp216;
fftw_real tmp268;
fftw_real tmp220;
fftw_real tmp266;
ASSERT_ALIGNED_DOUBLE;
{
fftw_real tmp205;
fftw_real tmp208;
fftw_real tmp261;
fftw_real tmp264;
ASSERT_ALIGNED_DOUBLE;
tmp205 = tmp161 + tmp164;
tmp208 = K707106781 * (tmp206 + tmp207);
tmp209 = tmp205 + tmp208;
tmp217 = tmp205 - tmp208;
tmp261 = K707106781 * (tmp170 + tmp175);
tmp264 = tmp262 - tmp263;
tmp265 = tmp261 + tmp264;
tmp267 = tmp264 - tmp261;
}
{
fftw_real tmp212;
fftw_real tmp215;
fftw_real tmp218;
fftw_real tmp219;
ASSERT_ALIGNED_DOUBLE;
tmp212 = (K382683432 * tmp210) + (K923879532 * tmp211);
tmp215 = (K923879532 * tmp213) - (K382683432 * tmp214);
tmp216 = tmp212 + tmp215;
tmp268 = tmp215 - tmp212;
tmp218 = (K923879532 * tmp210) - (K382683432 * tmp211);
tmp219 = (K923879532 * tmp214) + (K382683432 * tmp213);
tmp220 = tmp218 - tmp219;
tmp266 = tmp218 + tmp219;
}
Y[-9 * iostride] = tmp209 - tmp216;
X[iostride] = tmp209 + tmp216;
Y[-13 * iostride] = tmp217 - tmp220;
X[5 * iostride] = tmp217 + tmp220;
X[9 * iostride] = -(tmp265 - tmp266);
Y[-iostride] = tmp266 + tmp265;
X[13 * iostride] = -(tmp267 - tmp268);
Y[-5 * iostride] = tmp268 + tmp267;
}
{
fftw_real tmp225;
fftw_real tmp237;
fftw_real tmp257;
fftw_real tmp259;
fftw_real tmp236;
fftw_real tmp260;
fftw_real tmp240;
fftw_real tmp258;
ASSERT_ALIGNED_DOUBLE;
{
fftw_real tmp221;
fftw_real tmp224;
fftw_real tmp255;
fftw_real tmp256;
ASSERT_ALIGNED_DOUBLE;
tmp221 = tmp77 - tmp88;
tmp224 = tmp222 - tmp223;
tmp225 = tmp221 + tmp224;
tmp237 = tmp221 - tmp224;
tmp255 = tmp111 - tmp100;
tmp256 = tmp249 - tmp246;
tmp257 = tmp255 + tmp256;
tmp259 = tmp256 - tmp255;
}
{
fftw_real tmp230;
fftw_real tmp235;
fftw_real tmp238;
fftw_real tmp239;
ASSERT_ALIGNED_DOUBLE;
tmp230 = tmp226 + tmp229;
tmp235 = tmp231 - tmp234;
tmp236 = K707106781 * (tmp230 + tmp235);
tmp260 = K707106781 * (tmp235 - tmp230);
tmp238 = tmp229 - tmp226;
tmp239 = tmp231 + tmp234;
tmp240 = K707106781 * (tmp238 - tmp239);
tmp258 = K707106781 * (tmp238 + tmp239);
}
Y[-10 * iostride] = tmp225 - tmp236;
X[2 * iostride] = tmp225 + tmp236;
Y[-14 * iostride] = tmp237 - tmp240;
X[6 * iostride] = tmp237 + tmp240;
X[10 * iostride] = -(tmp257 - tmp258);
Y[-2 * iostride] = tmp258 + tmp257;
X[14 * iostride] = -(tmp259 - tmp260);
Y[-6 * iostride] = tmp260 + tmp259;
}
{
fftw_real tmp113;
fftw_real tmp241;
fftw_real tmp251;
fftw_real tmp253;
fftw_real tmp160;
fftw_real tmp254;
fftw_real tmp244;
fftw_real tmp252;
ASSERT_ALIGNED_DOUBLE;
{
fftw_real tmp89;
fftw_real tmp112;
fftw_real tmp245;
fftw_real tmp250;
ASSERT_ALIGNED_DOUBLE;
tmp89 = tmp77 + tmp88;
tmp112 = tmp100 + tmp111;
tmp113 = tmp89 + tmp112;
tmp241 = tmp89 - tmp112;
tmp245 = tmp222 + tmp223;
tmp250 = tmp246 + tmp249;
tmp251 = tmp245 + tmp250;
tmp253 = tmp250 - tmp245;
}
{
fftw_real tmp136;
fftw_real tmp159;
fftw_real tmp242;
fftw_real tmp243;
ASSERT_ALIGNED_DOUBLE;
tmp136 = tmp124 + tmp135;
tmp159 = tmp147 + tmp158;
tmp160 = tmp136 + tmp159;
tmp254 = tmp159 - tmp136;
tmp242 = tmp227 + tmp228;
tmp243 = tmp232 + tmp233;
tmp244 = tmp242 - tmp243;
tmp252 = tmp242 + tmp243;
}
Y[-8 * iostride] = tmp113 - tmp160;
X[0] = tmp113 + tmp160;
Y[-12 * iostride] = tmp241 - tmp244;
X[4 * iostride] = tmp241 + tmp244;
X[8 * iostride] = -(tmp251 - tmp252);
Y[0] = tmp252 + tmp251;
X[12 * iostride] = -(tmp253 - tmp254);
Y[-4 * iostride] = tmp254 + tmp253;
}
}
if (i == m) {
fftw_real tmp5;
fftw_real tmp41;
fftw_real tmp61;
fftw_real tmp67;
fftw_real tmp30;
fftw_real tmp49;
fftw_real tmp34;
fftw_real tmp50;
fftw_real tmp12;
fftw_real tmp66;
fftw_real tmp44;
fftw_real tmp58;
fftw_real tmp19;
fftw_real tmp46;
fftw_real tmp23;
fftw_real tmp47;
ASSERT_ALIGNED_DOUBLE;
{
fftw_real tmp1;
fftw_real tmp60;
fftw_real tmp4;
fftw_real tmp59;
fftw_real tmp2;
fftw_real tmp3;
ASSERT_ALIGNED_DOUBLE;
tmp1 = X[0];
tmp60 = X[8 * iostride];
tmp2 = X[4 * iostride];
tmp3 = X[12 * iostride];
tmp4 = K707106781 * (tmp2 - tmp3);
tmp59 = K707106781 * (tmp2 + tmp3);
tmp5 = tmp1 + tmp4;
tmp41 = tmp1 - tmp4;
tmp61 = tmp59 + tmp60;
tmp67 = tmp60 - tmp59;
}
{
fftw_real tmp29;
fftw_real tmp33;
fftw_real tmp27;
fftw_real tmp31;
ASSERT_ALIGNED_DOUBLE;
{
fftw_real tmp28;
fftw_real tmp32;
fftw_real tmp25;
fftw_real tmp26;
ASSERT_ALIGNED_DOUBLE;
tmp28 = X[15 * iostride];
tmp29 = K2_000000000 * tmp28;
tmp32 = X[7 * iostride];
tmp33 = K2_000000000 * tmp32;
tmp25 = X[3 * iostride];
tmp26 = X[11 * iostride];
tmp27 = K1_414213562 * (tmp25 - tmp26);
tmp31 = K1_414213562 * (tmp25 + tmp26);
}
tmp30 = tmp27 - tmp29;
tmp49 = tmp27 + tmp29;
tmp34 = tmp31 + tmp33;
tmp50 = tmp33 - tmp31;
}
{
fftw_real tmp8;
fftw_real tmp42;
fftw_real tmp11;
fftw_real tmp43;
ASSERT_ALIGNED_DOUBLE;
{
fftw_real tmp6;
fftw_real tmp7;
fftw_real tmp9;
fftw_real tmp10;
ASSERT_ALIGNED_DOUBLE;
tmp6 = X[2 * iostride];
tmp7 = X[10 * iostride];
tmp8 = (K923879532 * tmp6) - (K382683432 * tmp7);
tmp42 = (K382683432 * tmp6) + (K923879532 * tmp7);
tmp9 = X[6 * iostride];
tmp10 = X[14 * iostride];
tmp11 = (K382683432 * tmp9) - (K923879532 * tmp10);
tmp43 = (K923879532 * tmp9) + (K382683432 * tmp10);
}
tmp12 = tmp8 + tmp11;
tmp66 = tmp11 - tmp8;
tmp44 = tmp42 - tmp43;
tmp58 = tmp42 + tmp43;
}
{
fftw_real tmp15;
fftw_real tmp22;
fftw_real tmp18;
fftw_real tmp20;
ASSERT_ALIGNED_DOUBLE;
{
fftw_real tmp14;
fftw_real tmp21;
fftw_real tmp16;
fftw_real tmp17;
ASSERT_ALIGNED_DOUBLE;
tmp14 = X[iostride];
tmp15 = K2_000000000 * tmp14;
tmp21 = X[9 * iostride];
tmp22 = K2_000000000 * tmp21;
tmp16 = X[5 * iostride];
tmp17 = X[13 * iostride];
tmp18 = K1_414213562 * (tmp16 - tmp17);
tmp20 = K1_414213562 * (tmp16 + tmp17);
}
tmp19 = tmp15 + tmp18;
tmp46 = tmp15 - tmp18;
tmp23 = tmp20 + tmp22;
tmp47 = tmp22 - tmp20;
}
{
fftw_real tmp13;
fftw_real tmp62;
fftw_real tmp36;
fftw_real tmp57;
fftw_real tmp24;
fftw_real tmp35;
ASSERT_ALIGNED_DOUBLE;
tmp13 = tmp5 - tmp12;
tmp62 = tmp58 + tmp61;
tmp24 = (K097545161 * tmp19) + (K490392640 * tmp23);
tmp35 = (K097545161 * tmp30) - (K490392640 * tmp34);
tmp36 = tmp24 + tmp35;
tmp57 = tmp35 - tmp24;
X[4 * iostride] = tmp13 - tmp36;
X[3 * iostride] = tmp13 + tmp36;
Y[0] = tmp57 - tmp62;
Y[-7 * iostride] = tmp57 + tmp62;
}
{
fftw_real tmp37;
fftw_real tmp64;
fftw_real tmp40;
fftw_real tmp63;
fftw_real tmp38;
fftw_real tmp39;
ASSERT_ALIGNED_DOUBLE;
tmp37 = tmp5 + tmp12;
tmp64 = tmp61 - tmp58;
tmp38 = (K490392640 * tmp19) - (K097545161 * tmp23);
tmp39 = (K490392640 * tmp30) + (K097545161 * tmp34);
tmp40 = tmp38 + tmp39;
tmp63 = tmp39 - tmp38;
X[7 * iostride] = tmp37 - tmp40;
X[0] = tmp37 + tmp40;
Y[-4 * iostride] = tmp63 - tmp64;
Y[-3 * iostride] = tmp63 + tmp64;
}
{
fftw_real tmp45;
fftw_real tmp68;
fftw_real tmp52;
fftw_real tmp65;
fftw_real tmp48;
fftw_real tmp51;
ASSERT_ALIGNED_DOUBLE;
tmp45 = tmp41 + tmp44;
tmp68 = tmp66 - tmp67;
tmp48 = (K415734806 * tmp46) + (K277785116 * tmp47);
tmp51 = (K415734806 * tmp49) + (K277785116 * tmp50);
tmp52 = tmp48 - tmp51;
tmp65 = tmp48 + tmp51;
X[6 * iostride] = tmp45 - tmp52;
X[iostride] = tmp45 + tmp52;
Y[-5 * iostride] = -(tmp65 + tmp68);
Y[-2 * iostride] = tmp68 - tmp65;
}
{
fftw_real tmp53;
fftw_real tmp70;
fftw_real tmp56;
fftw_real tmp69;
fftw_real tmp54;
fftw_real tmp55;
ASSERT_ALIGNED_DOUBLE;
tmp53 = tmp41 - tmp44;
tmp70 = tmp66 + tmp67;
tmp54 = (K415734806 * tmp50) - (K277785116 * tmp49);
tmp55 = (K415734806 * tmp47) - (K277785116 * tmp46);
tmp56 = tmp54 - tmp55;
tmp69 = tmp55 + tmp54;
X[5 * iostride] = tmp53 - tmp56;
X[2 * iostride] = tmp53 + tmp56;
Y[-6 * iostride] = tmp69 - tmp70;
Y[-iostride] = tmp69 + tmp70;
}
}
}
static const int twiddle_order[] =
{1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
fftw_codelet_desc fftw_hc2hc_forward_16_desc =
{
"fftw_hc2hc_forward_16",
(void (*)()) fftw_hc2hc_forward_16,
16,
FFTW_FORWARD,
FFTW_HC2HC,
355,
15,
twiddle_order,
};
| mit |
alexey-malov/ips-oop2015 | lab2/task1/VectorProcessor.cpp | 1 | 1601 | #include "stdafx.h"
#include "VectorProcessor.h"
#include <algorithm>
#include <numeric>
#include <functional>
#include <boost/range/algorithm/transform.hpp>
#include <boost/phoenix.hpp>
using namespace std;
using namespace std::placeholders;
using namespace boost::phoenix::placeholders;
using namespace boost::phoenix;
using boost::transform;
void ProcessVector(std::vector<double> & numbers)
{
auto IsPositive = [](double number){return number > 0; };
size_t numberOfPositives = 0;
// функция, суммирующая только положительные числа с подсчетом их количества
auto addIfPositive = [&numberOfPositives](double acc, double current) {
if (current > 0.0)
{
++numberOfPositives;
return acc + current;
}
return acc;
};
auto sumOfPositives = accumulate(numbers.begin(), numbers.end(), 0.0, addIfPositive);
double avg = (numberOfPositives > 0) ? sumOfPositives / numberOfPositives : 0.0;
// TODO: Используй силу алгоритма std::transform, Люк, вместо этого цикла
boost::transform(numbers, numbers.begin(), arg1 + avg);
/*
auto addAvg = bind(plus<double>(), _1, avg);
transform(numbers, numbers.begin(), addAvg);
*/
/*transform(numbers, numbers.begin(), bind(plus<double>(), _1, avg));*/
/*transform(numbers.begin(), numbers.end(), numbers.begin(), bind(plus<double>(), _1, avg));*/
/*
transform(numbers.begin(), numbers.end(), numbers.begin(), [&avg](double current){
return current + avg;
});
*/
/*
for (auto &number : numbers)
{
number += avg;
}*/
} | mit |
rangsimanketkaew/NWChem | src/tce/eomccsdtq/eomccsdtq_y4_11.F | 1 | 8607 | SUBROUTINE eomccsdtq_y4_11(d_a,k_a_offset,d_b,k_b_offset,d_c,k_c_o
&ffset)
C $Id$
C This is a Fortran77 program generated by Tensor Contraction Engine v.1.0
C Copyright (c) Battelle & Pacific Northwest National Laboratory (2002)
C i0 ( h5 h6 h7 h8 p1 p2 p3 p4 )_ytf + = 1 * P( 4 ) * Sum ( h9 ) * i1 ( h5 h6 h7 h8 h9 p1 p2 p3 )_yt * f ( h9 p4 )_f
IMPLICIT NONE
#include "global.fh"
#include "mafdecls.fh"
#include "sym.fh"
#include "errquit.fh"
#include "tce.fh"
INTEGER d_a
INTEGER k_a_offset
INTEGER d_b
INTEGER k_b_offset
INTEGER d_c
INTEGER k_c_offset
INTEGER NXTASK
INTEGER next
INTEGER nprocs
INTEGER count
INTEGER h5b
INTEGER h6b
INTEGER h7b
INTEGER h8b
INTEGER p1b
INTEGER p2b
INTEGER p3b
INTEGER p4b
INTEGER dimc
INTEGER l_c_sort
INTEGER k_c_sort
INTEGER h9b
INTEGER h5b_1
INTEGER h6b_1
INTEGER h7b_1
INTEGER h8b_1
INTEGER p1b_1
INTEGER p2b_1
INTEGER p3b_1
INTEGER h9b_1
INTEGER h9b_2
INTEGER p4b_2
INTEGER dim_common
INTEGER dima_sort
INTEGER dima
INTEGER dimb_sort
INTEGER dimb
INTEGER l_a_sort
INTEGER k_a_sort
INTEGER l_a
INTEGER k_a
INTEGER l_b_sort
INTEGER k_b_sort
INTEGER l_b
INTEGER k_b
INTEGER l_c
INTEGER k_c
EXTERNAL NXTASK
nprocs = GA_NNODES()
count = 0
next = NXTASK(nprocs,1)
DO h5b = 1,noab
DO h6b = h5b,noab
DO h7b = h6b,noab
DO h8b = h7b,noab
DO p1b = noab+1,noab+nvab
DO p2b = p1b,noab+nvab
DO p3b = p2b,noab+nvab
DO p4b = noab+1,noab+nvab
IF (next.eq.count) THEN
IF ((.not.restricted).or.(int_mb(k_spin+h5b-1)+int_mb(k_spin+h6b-1
&)+int_mb(k_spin+h7b-1)+int_mb(k_spin+h8b-1)+int_mb(k_spin+p1b-1)+i
&nt_mb(k_spin+p2b-1)+int_mb(k_spin+p3b-1)+int_mb(k_spin+p4b-1).ne.1
&6)) THEN
IF (int_mb(k_spin+h5b-1)+int_mb(k_spin+h6b-1)+int_mb(k_spin+h7b-1)
&+int_mb(k_spin+h8b-1) .eq. int_mb(k_spin+p1b-1)+int_mb(k_spin+p2b-
&1)+int_mb(k_spin+p3b-1)+int_mb(k_spin+p4b-1)) THEN
IF (ieor(int_mb(k_sym+h5b-1),ieor(int_mb(k_sym+h6b-1),ieor(int_mb(
&k_sym+h7b-1),ieor(int_mb(k_sym+h8b-1),ieor(int_mb(k_sym+p1b-1),ieo
&r(int_mb(k_sym+p2b-1),ieor(int_mb(k_sym+p3b-1),int_mb(k_sym+p4b-1)
&))))))) .eq. ieor(irrep_y,ieor(irrep_t,irrep_f))) THEN
dimc = int_mb(k_range+h5b-1) * int_mb(k_range+h6b-1) * int_mb(k_ra
&nge+h7b-1) * int_mb(k_range+h8b-1) * int_mb(k_range+p1b-1) * int_m
&b(k_range+p2b-1) * int_mb(k_range+p3b-1) * int_mb(k_range+p4b-1)
IF (.not.MA_PUSH_GET(mt_dbl,dimc,'noname',l_c_sort,k_c_sort)) CALL
& ERRQUIT('eomccsdtq_y4_11',0,MA_ERR)
CALL DFILL(dimc,0.0d0,dbl_mb(k_c_sort),1)
DO h9b = 1,noab
IF (int_mb(k_spin+h5b-1)+int_mb(k_spin+h6b-1)+int_mb(k_spin+h7b-1)
&+int_mb(k_spin+h8b-1) .eq. int_mb(k_spin+p1b-1)+int_mb(k_spin+p2b-
&1)+int_mb(k_spin+p3b-1)+int_mb(k_spin+h9b-1)) THEN
IF (ieor(int_mb(k_sym+h5b-1),ieor(int_mb(k_sym+h6b-1),ieor(int_mb(
&k_sym+h7b-1),ieor(int_mb(k_sym+h8b-1),ieor(int_mb(k_sym+p1b-1),ieo
&r(int_mb(k_sym+p2b-1),ieor(int_mb(k_sym+p3b-1),int_mb(k_sym+h9b-1)
&))))))) .eq. ieor(irrep_y,irrep_t)) THEN
CALL TCE_RESTRICTED_8(h5b,h6b,h7b,h8b,p1b,p2b,p3b,h9b,h5b_1,h6b_1,
&h7b_1,h8b_1,p1b_1,p2b_1,p3b_1,h9b_1)
CALL TCE_RESTRICTED_2(h9b,p4b,h9b_2,p4b_2)
dim_common = int_mb(k_range+h9b-1)
dima_sort = int_mb(k_range+h5b-1) * int_mb(k_range+h6b-1) * int_mb
&(k_range+h7b-1) * int_mb(k_range+h8b-1) * int_mb(k_range+p1b-1) *
&int_mb(k_range+p2b-1) * int_mb(k_range+p3b-1)
dima = dim_common * dima_sort
dimb_sort = int_mb(k_range+p4b-1)
dimb = dim_common * dimb_sort
IF ((dima .gt. 0) .and. (dimb .gt. 0)) THEN
IF (.not.MA_PUSH_GET(mt_dbl,dima,'noname',l_a_sort,k_a_sort)) CALL
& ERRQUIT('eomccsdtq_y4_11',1,MA_ERR)
IF (.not.MA_PUSH_GET(mt_dbl,dima,'noname',l_a,k_a)) CALL ERRQUIT('
&eomccsdtq_y4_11',2,MA_ERR)
CALL GET_HASH_BLOCK(d_a,dbl_mb(k_a),dima,int_mb(k_a_offset),(h9b_1
& - 1 + noab * (p3b_1 - noab - 1 + nvab * (p2b_1 - noab - 1 + nvab
&* (p1b_1 - noab - 1 + nvab * (h8b_1 - 1 + noab * (h7b_1 - 1 + noab
& * (h6b_1 - 1 + noab * (h5b_1 - 1)))))))))
CALL TCE_SORT_8(dbl_mb(k_a),dbl_mb(k_a_sort),int_mb(k_range+h5b-1)
&,int_mb(k_range+h6b-1),int_mb(k_range+h7b-1),int_mb(k_range+h8b-1)
&,int_mb(k_range+p1b-1),int_mb(k_range+p2b-1),int_mb(k_range+p3b-1)
&,int_mb(k_range+h9b-1),7,6,5,4,3,2,1,8,1.0d0)
IF (.not.MA_POP_STACK(l_a)) CALL ERRQUIT('eomccsdtq_y4_11',3,MA_ER
&R)
IF (.not.MA_PUSH_GET(mt_dbl,dimb,'noname',l_b_sort,k_b_sort)) CALL
& ERRQUIT('eomccsdtq_y4_11',4,MA_ERR)
IF (.not.MA_PUSH_GET(mt_dbl,dimb,'noname',l_b,k_b)) CALL ERRQUIT('
&eomccsdtq_y4_11',5,MA_ERR)
CALL GET_HASH_BLOCK(d_b,dbl_mb(k_b),dimb,int_mb(k_b_offset),(p4b_2
& - 1 + (noab+nvab) * (h9b_2 - 1)))
CALL TCE_SORT_2(dbl_mb(k_b),dbl_mb(k_b_sort),int_mb(k_range+h9b-1)
&,int_mb(k_range+p4b-1),2,1,1.0d0)
IF (.not.MA_POP_STACK(l_b)) CALL ERRQUIT('eomccsdtq_y4_11',6,MA_ER
&R)
CALL DGEMM('T','N',dima_sort,dimb_sort,dim_common,1.0d0,dbl_mb(k_a
&_sort),dim_common,dbl_mb(k_b_sort),dim_common,1.0d0,dbl_mb(k_c_sor
&t),dima_sort)
IF (.not.MA_POP_STACK(l_b_sort)) CALL ERRQUIT('eomccsdtq_y4_11',7,
&MA_ERR)
IF (.not.MA_POP_STACK(l_a_sort)) CALL ERRQUIT('eomccsdtq_y4_11',8,
&MA_ERR)
END IF
END IF
END IF
END DO
IF (.not.MA_PUSH_GET(mt_dbl,dimc,'noname',l_c,k_c)) CALL ERRQUIT('
&eomccsdtq_y4_11',9,MA_ERR)
IF ((p3b .le. p4b)) THEN
CALL TCE_SORT_8(dbl_mb(k_c_sort),dbl_mb(k_c),int_mb(k_range+p4b-1)
&,int_mb(k_range+p3b-1),int_mb(k_range+p2b-1),int_mb(k_range+p1b-1)
&,int_mb(k_range+h8b-1),int_mb(k_range+h7b-1),int_mb(k_range+h6b-1)
&,int_mb(k_range+h5b-1),8,7,6,5,4,3,2,1,1.0d0)
CALL ADD_HASH_BLOCK(d_c,dbl_mb(k_c),dimc,int_mb(k_c_offset),(p4b -
& noab - 1 + nvab * (p3b - noab - 1 + nvab * (p2b - noab - 1 + nvab
& * (p1b - noab - 1 + nvab * (h8b - 1 + noab * (h7b - 1 + noab * (h
&6b - 1 + noab * (h5b - 1)))))))))
END IF
IF ((p4b .le. p1b)) THEN
CALL TCE_SORT_8(dbl_mb(k_c_sort),dbl_mb(k_c),int_mb(k_range+p4b-1)
&,int_mb(k_range+p3b-1),int_mb(k_range+p2b-1),int_mb(k_range+p1b-1)
&,int_mb(k_range+h8b-1),int_mb(k_range+h7b-1),int_mb(k_range+h6b-1)
&,int_mb(k_range+h5b-1),8,7,6,5,1,4,3,2,-1.0d0)
CALL ADD_HASH_BLOCK(d_c,dbl_mb(k_c),dimc,int_mb(k_c_offset),(p3b -
& noab - 1 + nvab * (p2b - noab - 1 + nvab * (p1b - noab - 1 + nvab
& * (p4b - noab - 1 + nvab * (h8b - 1 + noab * (h7b - 1 + noab * (h
&6b - 1 + noab * (h5b - 1)))))))))
END IF
IF ((p1b .le. p4b) .and. (p4b .le. p2b)) THEN
CALL TCE_SORT_8(dbl_mb(k_c_sort),dbl_mb(k_c),int_mb(k_range+p4b-1)
&,int_mb(k_range+p3b-1),int_mb(k_range+p2b-1),int_mb(k_range+p1b-1)
&,int_mb(k_range+h8b-1),int_mb(k_range+h7b-1),int_mb(k_range+h6b-1)
&,int_mb(k_range+h5b-1),8,7,6,5,4,1,3,2,1.0d0)
CALL ADD_HASH_BLOCK(d_c,dbl_mb(k_c),dimc,int_mb(k_c_offset),(p3b -
& noab - 1 + nvab * (p2b - noab - 1 + nvab * (p4b - noab - 1 + nvab
& * (p1b - noab - 1 + nvab * (h8b - 1 + noab * (h7b - 1 + noab * (h
&6b - 1 + noab * (h5b - 1)))))))))
END IF
IF ((p2b .le. p4b) .and. (p4b .le. p3b)) THEN
CALL TCE_SORT_8(dbl_mb(k_c_sort),dbl_mb(k_c),int_mb(k_range+p4b-1)
&,int_mb(k_range+p3b-1),int_mb(k_range+p2b-1),int_mb(k_range+p1b-1)
&,int_mb(k_range+h8b-1),int_mb(k_range+h7b-1),int_mb(k_range+h6b-1)
&,int_mb(k_range+h5b-1),8,7,6,5,4,3,1,2,-1.0d0)
CALL ADD_HASH_BLOCK(d_c,dbl_mb(k_c),dimc,int_mb(k_c_offset),(p3b -
& noab - 1 + nvab * (p4b - noab - 1 + nvab * (p2b - noab - 1 + nvab
& * (p1b - noab - 1 + nvab * (h8b - 1 + noab * (h7b - 1 + noab * (h
&6b - 1 + noab * (h5b - 1)))))))))
END IF
IF (.not.MA_POP_STACK(l_c)) CALL ERRQUIT('eomccsdtq_y4_11',10,MA_E
&RR)
IF (.not.MA_POP_STACK(l_c_sort)) CALL ERRQUIT('eomccsdtq_y4_11',11
&,MA_ERR)
END IF
END IF
END IF
next = NXTASK(nprocs,1)
END IF
count = count + 1
END DO
END DO
END DO
END DO
END DO
END DO
END DO
END DO
next = NXTASK(-nprocs,1)
call GA_SYNC()
RETURN
END
| mit |
yoshito-n-students/affine_invariant_features | src/extract_features.cpp | 1 | 3372 | #include <iostream>
#include <string>
#include <affine_invariant_features/affine_invariant_feature.hpp>
#include <affine_invariant_features/feature_parameters.hpp>
#include <affine_invariant_features/results.hpp>
#include <affine_invariant_features/target.hpp>
#include <opencv2/core.hpp>
#include <opencv2/features2d.hpp>
#include <opencv2/highgui.hpp>
#include "aif_assert.hpp"
int main(int argc, char *argv[]) {
namespace aif = affine_invariant_features;
const cv::CommandLineParser args(
argc, argv, "{ help | | }"
"{ @parameter-file | <none> | can be generated by generate_parameter_file }"
"{ @target-file | <none> | can be generated by generate_target_file }"
"{ @result-file | <none> | }");
if (args.has("help")) {
args.printMessage();
return 0;
}
const std::string param_path(args.get< std::string >("@parameter-file"));
const std::string target_path(args.get< std::string >("@target-file"));
const std::string result_path(args.get< std::string >("@result-file"));
if (!args.check()) {
args.printErrors();
return 1;
}
const cv::FileStorage param_file(param_path, cv::FileStorage::READ);
AIF_Assert(param_file.isOpened(), "Could not open %s", param_path.c_str());
const cv::Ptr< const aif::FeatureParameters > params(
aif::load< aif::FeatureParameters >(param_file.root()));
AIF_Assert(params, "Could not load a parameter set from %s", param_path.c_str());
const cv::Ptr< cv::Feature2D > feature(params->createFeature());
AIF_Assert(feature, "Could not create a feature algorithm from %s", param_path.c_str());
const cv::FileStorage target_file(target_path, cv::FileStorage::READ);
AIF_Assert(target_file.isOpened(), "Could not open %s", target_path.c_str());
const cv::Ptr< const aif::TargetDescription > target_desc(
aif::load< aif::TargetDescription >(target_file.root()));
AIF_Assert(target_desc, "Could not load an target description from %s", target_path.c_str());
const cv::Ptr< const aif::TargetData > target_data(aif::TargetData::retrieve(*target_desc));
AIF_Assert(target_data, "Could not load target data described in %s", target_path.c_str());
cv::Mat target_image(target_data->image / 4);
target_data->image.copyTo(target_image, target_data->mask);
std::cout << "Showing the target image with mask. Press any key to continue." << std::endl;
cv::imshow("Target", target_image);
cv::waitKey(0);
std::cout << "Extracting features. This may take seconds or minutes." << std::endl;
aif::Results results;
feature->detectAndCompute(target_data->image, target_data->mask, results.keypoints,
results.descriptors);
results.normType = feature->defaultNorm();
cv::Mat result_image;
cv::drawKeypoints(target_image, results.keypoints, result_image);
std::cout << "Showing a result image with keypoints. Press any key to continue." << std::endl;
cv::imshow("Results", result_image);
cv::waitKey(0);
cv::FileStorage result_file(result_path, cv::FileStorage::WRITE);
AIF_Assert(result_file.isOpened(), "Could not open or create %s", result_path.c_str());
params->save(result_file);
target_desc->save(result_file);
results.save(result_file);
std::cout << "Wrote context and results of feature extraction to " << result_path << std::endl;
return 0;
}
| mit |
stackprobe/Factory | Common/Options/MergeSort_v1.c | 1 | 4695 | #include "MergeSort_v1.h"
static void CommitPart(
autoList_t *partFiles,
char *wMode,
void (*writeElement_x)(FILE *fp, uint element),
sint (*compElement)(uint element1, uint element2),
autoList_t *elements
)
{
rapidSort(elements, compElement);
{
char *partFile = makeTempPath("part");
FILE *fp;
uint element;
uint index;
addElement(partFiles, (uint)partFile);
fp = fileOpen(partFile, wMode);
foreach(elements, element, index)
writeElement_x(fp, element);
fileClose(fp);
releaseAutoList(elements);
}
}
static void MergePart(
char *srcFile1,
char *srcFile2,
char *destFile,
char *rMode,
char *wMode,
uint (*readElement)(FILE *fp),
void (*writeElement_x)(FILE *fp, uint element),
sint (*compElement)(uint element1, uint element2)
)
{
FILE *rfp1 = fileOpen(srcFile1, rMode);
FILE *rfp2 = fileOpen(srcFile2, rMode);
FILE *wfp = fileOpen(destFile, wMode);
uint element1;
uint element2;
element1 = readElement(rfp1);
element2 = readElement(rfp2);
while(element1 && element2)
{
if(compElement(element1, element2) <= 0) // ? element1 <= element2
{
writeElement_x(wfp, element1);
element1 = readElement(rfp1);
}
else // element1 > element2
{
writeElement_x(wfp, element2);
element2 = readElement(rfp2);
}
}
{
FILE *tfp;
uint tElement;
if(element1)
{
tfp = rfp1;
tElement = element1;
}
else
{
tfp = rfp2;
tElement = element2;
}
do
{
writeElement_x(wfp, tElement);
}
while(tElement = readElement(tfp));
}
fileClose(rfp1);
fileClose(rfp2);
fileClose(wfp);
removeFile(srcFile1);
removeFile(srcFile2);
}
/*
srcFile
ÇÝݳt@C
destFile
oÍæt@C
srcFile Ư¶pXÅ ÁÄàÇ¢B
textMode
^ÌÆ« -> eLXg[h
UÌÆ« -> oCi[[h
uint readElement(FILE *fp)
PR[hÇÝÞB
±êÈãR[hª³¢Æ«Í 0 ðÔ·±ÆB
void writeElement_x(FILE *fp, uint element)
PR[h«ÞB
KvÅ êÎ element ðJú·é±ÆB
sint compElement(uint element1, uint element2)
element1 Æ element2 ðärµ½Êð strcmp() IÉÔ·B
partSize
ÉêxúÉÇÝßéuR[hÌvoCgvÌÅålÌÚÀ
srcFile ÌV[NÊuÌÏ»ðoCgÉ·ZµÄ¢é¾¯B
0 ÌÆ«ÍíÉPR[h¸ÂÉÈéB
ep[gÌR[hª partSize / 100 ð´¦È¢æ¤É·éB
*/
void MergeSort(
char *srcFile,
char *destFile,
int textMode,
uint (*readElement)(FILE *fp),
void (*writeElement_x)(FILE *fp, uint element),
sint (*compElement)(uint element1, uint element2),
uint partSize
)
{
autoList_t *partFiles = newList();
autoList_t *elements = NULL;
char *rMode;
char *wMode;
FILE *fp;
uint64 startPos = 0;
if(textMode)
{
rMode = "rt";
wMode = "wt";
}
else
{
rMode = "rb";
wMode = "wb";
}
fp = fileOpen(srcFile, rMode);
for(; ; )
{
uint element = readElement(fp);
uint64 currPos;
if(!element)
break;
if(!elements)
elements = createAutoList(partSize / 100 + 1);
addElement(elements, element);
currPos = _ftelli64(fp);
errorCase(currPos < 0);
if(startPos + partSize <= currPos || partSize / 100 < getCount(elements))
{
CommitPart(partFiles, wMode, writeElement_x, compElement, elements);
elements = NULL;
startPos = currPos;
// ÌftO?
{
char *wkFile = makeTempPath("work");
writeLines_cx(wkFile, partFiles);
partFiles = readLines(wkFile);
removeFile(wkFile);
memFree(wkFile);
}
}
}
if(elements)
CommitPart(partFiles, wMode, writeElement_x, compElement, elements);
fileClose(fp);
while(2 < getCount(partFiles))
{
char *partFile1 = (char *)unaddElement(partFiles);
char *partFile2 = (char *)unaddElement(partFiles);
char *partFile3 = makeTempPath("part");
MergePart(partFile1, partFile2, partFile3, rMode, wMode, readElement, writeElement_x, compElement);
memFree(partFile1);
memFree(partFile2);
insertElement(partFiles, 0, (uint)partFile3);
}
switch(getCount(partFiles))
{
case 2:
MergePart(getLine(partFiles, 0), getLine(partFiles, 1), destFile, rMode, wMode, readElement, writeElement_x, compElement);
break;
case 1:
removeFileIfExist(destFile);
moveFile(getLine(partFiles, 0), destFile);
break;
case 0:
createFile(destFile);
break;
default:
error();
}
releaseDim(partFiles, 1);
}
void MergeSortTextComp(char *srcFile, char *destFile, sint (*funcComp)(char *, char *), uint partSize)
{
MergeSort(srcFile, destFile, 1, (uint (*)(FILE *))readLine, (void (*)(FILE *, uint))writeLine_x, (sint (*)(uint, uint))funcComp, partSize);
}
void MergeSortText(char *srcFile, char *destFile, uint partSize)
{
MergeSortTextComp(srcFile, destFile, strcmp, partSize);
}
| mit |
bugsnag/bugsnag-js | packages/plugin-electron-client-state-persistence/src/deps/parson/parson.c | 1 | 74015 | /*
SPDX-License-Identifier: MIT
Parson 1.1.0 ( http://kgabis.github.com/parson/ )
Copyright (c) 2012 - 2020 Krzysztof Gabis
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.
*/
#ifdef _MSC_VER
#ifndef _CRT_SECURE_NO_WARNINGS
#define _CRT_SECURE_NO_WARNINGS
#endif /* _CRT_SECURE_NO_WARNINGS */
#endif /* _MSC_VER */
#include "parson.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
#include <errno.h>
/* Apparently sscanf is not implemented in some "standard" libraries, so don't use it, if you
* don't have to. */
#define sscanf THINK_TWICE_ABOUT_USING_SSCANF
#define STARTING_CAPACITY 16
#define MAX_NESTING 2048
#define FLOAT_FORMAT "%1.17g" /* do not increase precision without incresing NUM_BUF_SIZE */
#define NUM_BUF_SIZE 64 /* double printed with "%1.17g" shouldn't be longer than 25 bytes so let's be paranoid and use 64 */
#define SIZEOF_TOKEN(a) (sizeof(a) - 1)
#define SKIP_CHAR(str) ((*str)++)
#define SKIP_WHITESPACES(str) while (isspace((unsigned char)(**str))) { SKIP_CHAR(str); }
#define MAX(a, b) ((a) > (b) ? (a) : (b))
#undef malloc
#undef free
#if defined(isnan) && defined(isinf)
#define IS_NUMBER_INVALID(x) (isnan((x)) || isinf((x)))
#else
#define IS_NUMBER_INVALID(x) (((x) * 0.0) != 0.0)
#endif
static JSON_Malloc_Function parson_malloc = malloc;
static JSON_Free_Function parson_free = free;
static int parson_escape_slashes = 1;
#define IS_CONT(b) (((unsigned char)(b) & 0xC0) == 0x80) /* is utf-8 continuation byte */
typedef struct json_string {
char *chars;
size_t length;
} JSON_String;
/* Type definitions */
typedef union json_value_value {
JSON_String string;
double number;
JSON_Object *object;
JSON_Array *array;
int boolean;
int null;
} JSON_Value_Value;
struct json_value_t {
JSON_Value *parent;
JSON_Value_Type type;
JSON_Value_Value value;
};
struct json_object_t {
JSON_Value *wrapping_value;
char **names;
JSON_Value **values;
size_t count;
size_t capacity;
};
struct json_array_t {
JSON_Value *wrapping_value;
JSON_Value **items;
size_t count;
size_t capacity;
};
/* Various */
static char * read_file(const char *filename);
static void remove_comments(char *string, const char *start_token, const char *end_token);
static char * parson_strndup(const char *string, size_t n);
static char * parson_strdup(const char *string);
static int hex_char_to_int(char c);
static int parse_utf16_hex(const char *string, unsigned int *result);
static int num_bytes_in_utf8_sequence(unsigned char c);
static int verify_utf8_sequence(const unsigned char *string, int *len);
static int is_valid_utf8(const char *string, size_t string_len);
static int is_decimal(const char *string, size_t length);
/* JSON Object */
static JSON_Object * json_object_init(JSON_Value *wrapping_value);
static JSON_Status json_object_add(JSON_Object *object, const char *name, JSON_Value *value);
static JSON_Status json_object_addn(JSON_Object *object, const char *name, size_t name_len, JSON_Value *value);
static JSON_Status json_object_resize(JSON_Object *object, size_t new_capacity);
static JSON_Value * json_object_getn_value(const JSON_Object *object, const char *name, size_t name_len);
static JSON_Status json_object_remove_internal(JSON_Object *object, const char *name, int free_value);
static JSON_Status json_object_dotremove_internal(JSON_Object *object, const char *name, int free_value);
static void json_object_free(JSON_Object *object);
/* JSON Array */
static JSON_Array * json_array_init(JSON_Value *wrapping_value);
static JSON_Status json_array_add(JSON_Array *array, JSON_Value *value);
static JSON_Status json_array_resize(JSON_Array *array, size_t new_capacity);
static void json_array_free(JSON_Array *array);
/* JSON Value */
static JSON_Value * json_value_init_string_no_copy(char *string, size_t length);
static const JSON_String * json_value_get_string_desc(const JSON_Value *value);
/* Parser */
static JSON_Status skip_quotes(const char **string);
static int parse_utf16(const char **unprocessed, char **processed);
static char * process_string(const char *input, size_t input_len, size_t *output_len);
static char * get_quoted_string(const char **string, size_t *output_string_len);
static JSON_Value * parse_object_value(const char **string, size_t nesting);
static JSON_Value * parse_array_value(const char **string, size_t nesting);
static JSON_Value * parse_string_value(const char **string);
static JSON_Value * parse_boolean_value(const char **string);
static JSON_Value * parse_number_value(const char **string);
static JSON_Value * parse_null_value(const char **string);
static JSON_Value * parse_value(const char **string, size_t nesting);
/* Serialization */
static int json_serialize_to_buffer_r(const JSON_Value *value, char *buf, int level, int is_pretty, char *num_buf);
static int json_serialize_string(const char *string, size_t len, char *buf);
static int append_indent(char *buf, int level);
static int append_string(char *buf, const char *string);
/* Various */
static char * parson_strndup(const char *string, size_t n) {
/* We expect the caller has validated that 'n' fits within the input buffer. */
char *output_string = (char*)parson_malloc(n + 1);
if (!output_string) {
return NULL;
}
output_string[n] = '\0';
memcpy(output_string, string, n);
return output_string;
}
static char * parson_strdup(const char *string) {
return parson_strndup(string, strlen(string));
}
static int hex_char_to_int(char c) {
if (c >= '0' && c <= '9') {
return c - '0';
} else if (c >= 'a' && c <= 'f') {
return c - 'a' + 10;
} else if (c >= 'A' && c <= 'F') {
return c - 'A' + 10;
}
return -1;
}
static int parse_utf16_hex(const char *s, unsigned int *result) {
int x1, x2, x3, x4;
if (s[0] == '\0' || s[1] == '\0' || s[2] == '\0' || s[3] == '\0') {
return 0;
}
x1 = hex_char_to_int(s[0]);
x2 = hex_char_to_int(s[1]);
x3 = hex_char_to_int(s[2]);
x4 = hex_char_to_int(s[3]);
if (x1 == -1 || x2 == -1 || x3 == -1 || x4 == -1) {
return 0;
}
*result = (unsigned int)((x1 << 12) | (x2 << 8) | (x3 << 4) | x4);
return 1;
}
static int num_bytes_in_utf8_sequence(unsigned char c) {
if (c == 0xC0 || c == 0xC1 || c > 0xF4 || IS_CONT(c)) {
return 0;
} else if ((c & 0x80) == 0) { /* 0xxxxxxx */
return 1;
} else if ((c & 0xE0) == 0xC0) { /* 110xxxxx */
return 2;
} else if ((c & 0xF0) == 0xE0) { /* 1110xxxx */
return 3;
} else if ((c & 0xF8) == 0xF0) { /* 11110xxx */
return 4;
}
return 0; /* won't happen */
}
static int verify_utf8_sequence(const unsigned char *string, int *len) {
unsigned int cp = 0;
*len = num_bytes_in_utf8_sequence(string[0]);
if (*len == 1) {
cp = string[0];
} else if (*len == 2 && IS_CONT(string[1])) {
cp = string[0] & 0x1F;
cp = (cp << 6) | (string[1] & 0x3F);
} else if (*len == 3 && IS_CONT(string[1]) && IS_CONT(string[2])) {
cp = ((unsigned char)string[0]) & 0xF;
cp = (cp << 6) | (string[1] & 0x3F);
cp = (cp << 6) | (string[2] & 0x3F);
} else if (*len == 4 && IS_CONT(string[1]) && IS_CONT(string[2]) && IS_CONT(string[3])) {
cp = string[0] & 0x7;
cp = (cp << 6) | (string[1] & 0x3F);
cp = (cp << 6) | (string[2] & 0x3F);
cp = (cp << 6) | (string[3] & 0x3F);
} else {
return 0;
}
/* overlong encodings */
if ((cp < 0x80 && *len > 1) ||
(cp < 0x800 && *len > 2) ||
(cp < 0x10000 && *len > 3)) {
return 0;
}
/* invalid unicode */
if (cp > 0x10FFFF) {
return 0;
}
/* surrogate halves */
if (cp >= 0xD800 && cp <= 0xDFFF) {
return 0;
}
return 1;
}
static int is_valid_utf8(const char *string, size_t string_len) {
int len = 0;
const char *string_end = string + string_len;
while (string < string_end) {
if (!verify_utf8_sequence((const unsigned char*)string, &len)) {
return 0;
}
string += len;
}
return 1;
}
static int is_decimal(const char *string, size_t length) {
if (length > 1 && string[0] == '0' && string[1] != '.') {
return 0;
}
if (length > 2 && !strncmp(string, "-0", 2) && string[2] != '.') {
return 0;
}
while (length--) {
if (strchr("xX", string[length])) {
return 0;
}
}
return 1;
}
static char * read_file(const char * filename) {
FILE *fp = fopen(filename, "r");
size_t size_to_read = 0;
size_t size_read = 0;
long pos;
char *file_contents;
if (!fp) {
return NULL;
}
fseek(fp, 0L, SEEK_END);
pos = ftell(fp);
if (pos < 0) {
fclose(fp);
return NULL;
}
size_to_read = pos;
rewind(fp);
file_contents = (char*)parson_malloc(sizeof(char) * (size_to_read + 1));
if (!file_contents) {
fclose(fp);
return NULL;
}
size_read = fread(file_contents, 1, size_to_read, fp);
if (size_read == 0 || ferror(fp)) {
fclose(fp);
parson_free(file_contents);
return NULL;
}
fclose(fp);
file_contents[size_read] = '\0';
return file_contents;
}
static void remove_comments(char *string, const char *start_token, const char *end_token) {
int in_string = 0, escaped = 0;
size_t i;
char *ptr = NULL, current_char;
size_t start_token_len = strlen(start_token);
size_t end_token_len = strlen(end_token);
if (start_token_len == 0 || end_token_len == 0) {
return;
}
while ((current_char = *string) != '\0') {
if (current_char == '\\' && !escaped) {
escaped = 1;
string++;
continue;
} else if (current_char == '\"' && !escaped) {
in_string = !in_string;
} else if (!in_string && strncmp(string, start_token, start_token_len) == 0) {
for(i = 0; i < start_token_len; i++) {
string[i] = ' ';
}
string = string + start_token_len;
ptr = strstr(string, end_token);
if (!ptr) {
return;
}
for (i = 0; i < (ptr - string) + end_token_len; i++) {
string[i] = ' ';
}
string = ptr + end_token_len - 1;
}
escaped = 0;
string++;
}
}
/* JSON Object */
static JSON_Object * json_object_init(JSON_Value *wrapping_value) {
JSON_Object *new_obj = (JSON_Object*)parson_malloc(sizeof(JSON_Object));
if (new_obj == NULL) {
return NULL;
}
new_obj->wrapping_value = wrapping_value;
new_obj->names = (char**)NULL;
new_obj->values = (JSON_Value**)NULL;
new_obj->capacity = 0;
new_obj->count = 0;
return new_obj;
}
static JSON_Status json_object_add(JSON_Object *object, const char *name, JSON_Value *value) {
if (name == NULL) {
return JSONFailure;
}
return json_object_addn(object, name, strlen(name), value);
}
static JSON_Status json_object_addn(JSON_Object *object, const char *name, size_t name_len, JSON_Value *value) {
size_t index = 0;
if (object == NULL || name == NULL || value == NULL) {
return JSONFailure;
}
if (json_object_getn_value(object, name, name_len) != NULL) {
return JSONFailure;
}
if (object->count >= object->capacity) {
size_t new_capacity = MAX(object->capacity * 2, STARTING_CAPACITY);
if (json_object_resize(object, new_capacity) == JSONFailure) {
return JSONFailure;
}
}
index = object->count;
object->names[index] = parson_strndup(name, name_len);
if (object->names[index] == NULL) {
return JSONFailure;
}
value->parent = json_object_get_wrapping_value(object);
object->values[index] = value;
object->count++;
return JSONSuccess;
}
static JSON_Status json_object_resize(JSON_Object *object, size_t new_capacity) {
char **temp_names = NULL;
JSON_Value **temp_values = NULL;
if ((object->names == NULL && object->values != NULL) ||
(object->names != NULL && object->values == NULL) ||
new_capacity == 0) {
return JSONFailure; /* Shouldn't happen */
}
temp_names = (char**)parson_malloc(new_capacity * sizeof(char*));
if (temp_names == NULL) {
return JSONFailure;
}
temp_values = (JSON_Value**)parson_malloc(new_capacity * sizeof(JSON_Value*));
if (temp_values == NULL) {
parson_free(temp_names);
return JSONFailure;
}
if (object->names != NULL && object->values != NULL && object->count > 0) {
memcpy(temp_names, object->names, object->count * sizeof(char*));
memcpy(temp_values, object->values, object->count * sizeof(JSON_Value*));
}
parson_free(object->names);
parson_free(object->values);
object->names = temp_names;
object->values = temp_values;
object->capacity = new_capacity;
return JSONSuccess;
}
static JSON_Value * json_object_getn_value(const JSON_Object *object, const char *name, size_t name_len) {
size_t i, name_length;
for (i = 0; i < json_object_get_count(object); i++) {
name_length = strlen(object->names[i]);
if (name_length != name_len) {
continue;
}
if (strncmp(object->names[i], name, name_len) == 0) {
return object->values[i];
}
}
return NULL;
}
static JSON_Status json_object_remove_internal(JSON_Object *object, const char *name, int free_value) {
size_t i = 0, last_item_index = 0;
if (object == NULL || json_object_get_value(object, name) == NULL) {
return JSONFailure;
}
last_item_index = json_object_get_count(object) - 1;
for (i = 0; i < json_object_get_count(object); i++) {
if (strcmp(object->names[i], name) == 0) {
parson_free(object->names[i]);
if (free_value) {
json_value_free(object->values[i]);
}
if (i != last_item_index) { /* Replace key value pair with one from the end */
object->names[i] = object->names[last_item_index];
object->values[i] = object->values[last_item_index];
}
object->count -= 1;
return JSONSuccess;
}
}
return JSONFailure; /* No execution path should end here */
}
static JSON_Status json_object_dotremove_internal(JSON_Object *object, const char *name, int free_value) {
JSON_Value *temp_value = NULL;
JSON_Object *temp_object = NULL;
const char *dot_pos = strchr(name, '.');
if (dot_pos == NULL) {
return json_object_remove_internal(object, name, free_value);
}
temp_value = json_object_getn_value(object, name, dot_pos - name);
if (json_value_get_type(temp_value) != JSONObject) {
return JSONFailure;
}
temp_object = json_value_get_object(temp_value);
return json_object_dotremove_internal(temp_object, dot_pos + 1, free_value);
}
static void json_object_free(JSON_Object *object) {
size_t i;
for (i = 0; i < object->count; i++) {
parson_free(object->names[i]);
json_value_free(object->values[i]);
}
parson_free(object->names);
parson_free(object->values);
parson_free(object);
}
/* JSON Array */
static JSON_Array * json_array_init(JSON_Value *wrapping_value) {
JSON_Array *new_array = (JSON_Array*)parson_malloc(sizeof(JSON_Array));
if (new_array == NULL) {
return NULL;
}
new_array->wrapping_value = wrapping_value;
new_array->items = (JSON_Value**)NULL;
new_array->capacity = 0;
new_array->count = 0;
return new_array;
}
static JSON_Status json_array_add(JSON_Array *array, JSON_Value *value) {
if (array->count >= array->capacity) {
size_t new_capacity = MAX(array->capacity * 2, STARTING_CAPACITY);
if (json_array_resize(array, new_capacity) == JSONFailure) {
return JSONFailure;
}
}
value->parent = json_array_get_wrapping_value(array);
array->items[array->count] = value;
array->count++;
return JSONSuccess;
}
static JSON_Status json_array_resize(JSON_Array *array, size_t new_capacity) {
JSON_Value **new_items = NULL;
if (new_capacity == 0) {
return JSONFailure;
}
new_items = (JSON_Value**)parson_malloc(new_capacity * sizeof(JSON_Value*));
if (new_items == NULL) {
return JSONFailure;
}
if (array->items != NULL && array->count > 0) {
memcpy(new_items, array->items, array->count * sizeof(JSON_Value*));
}
parson_free(array->items);
array->items = new_items;
array->capacity = new_capacity;
return JSONSuccess;
}
static void json_array_free(JSON_Array *array) {
size_t i;
for (i = 0; i < array->count; i++) {
json_value_free(array->items[i]);
}
parson_free(array->items);
parson_free(array);
}
/* JSON Value */
static JSON_Value * json_value_init_string_no_copy(char *string, size_t length) {
JSON_Value *new_value = (JSON_Value*)parson_malloc(sizeof(JSON_Value));
if (!new_value) {
return NULL;
}
new_value->parent = NULL;
new_value->type = JSONString;
new_value->value.string.chars = string;
new_value->value.string.length = length;
return new_value;
}
/* Parser */
static JSON_Status skip_quotes(const char **string) {
if (**string != '\"') {
return JSONFailure;
}
SKIP_CHAR(string);
while (**string != '\"') {
if (**string == '\0') {
return JSONFailure;
} else if (**string == '\\') {
SKIP_CHAR(string);
if (**string == '\0') {
return JSONFailure;
}
}
SKIP_CHAR(string);
}
SKIP_CHAR(string);
return JSONSuccess;
}
static int parse_utf16(const char **unprocessed, char **processed) {
unsigned int cp, lead, trail;
int parse_succeeded = 0;
char *processed_ptr = *processed;
const char *unprocessed_ptr = *unprocessed;
unprocessed_ptr++; /* skips u */
parse_succeeded = parse_utf16_hex(unprocessed_ptr, &cp);
if (!parse_succeeded) {
return JSONFailure;
}
if (cp < 0x80) {
processed_ptr[0] = (char)cp; /* 0xxxxxxx */
} else if (cp < 0x800) {
processed_ptr[0] = ((cp >> 6) & 0x1F) | 0xC0; /* 110xxxxx */
processed_ptr[1] = ((cp) & 0x3F) | 0x80; /* 10xxxxxx */
processed_ptr += 1;
} else if (cp < 0xD800 || cp > 0xDFFF) {
processed_ptr[0] = ((cp >> 12) & 0x0F) | 0xE0; /* 1110xxxx */
processed_ptr[1] = ((cp >> 6) & 0x3F) | 0x80; /* 10xxxxxx */
processed_ptr[2] = ((cp) & 0x3F) | 0x80; /* 10xxxxxx */
processed_ptr += 2;
} else if (cp >= 0xD800 && cp <= 0xDBFF) { /* lead surrogate (0xD800..0xDBFF) */
lead = cp;
unprocessed_ptr += 4; /* should always be within the buffer, otherwise previous sscanf would fail */
if (*unprocessed_ptr++ != '\\' || *unprocessed_ptr++ != 'u') {
return JSONFailure;
}
parse_succeeded = parse_utf16_hex(unprocessed_ptr, &trail);
if (!parse_succeeded || trail < 0xDC00 || trail > 0xDFFF) { /* valid trail surrogate? (0xDC00..0xDFFF) */
return JSONFailure;
}
cp = ((((lead - 0xD800) & 0x3FF) << 10) | ((trail - 0xDC00) & 0x3FF)) + 0x010000;
processed_ptr[0] = (((cp >> 18) & 0x07) | 0xF0); /* 11110xxx */
processed_ptr[1] = (((cp >> 12) & 0x3F) | 0x80); /* 10xxxxxx */
processed_ptr[2] = (((cp >> 6) & 0x3F) | 0x80); /* 10xxxxxx */
processed_ptr[3] = (((cp) & 0x3F) | 0x80); /* 10xxxxxx */
processed_ptr += 3;
} else { /* trail surrogate before lead surrogate */
return JSONFailure;
}
unprocessed_ptr += 3;
*processed = processed_ptr;
*unprocessed = unprocessed_ptr;
return JSONSuccess;
}
/* Copies and processes passed string up to supplied length.
Example: "\u006Corem ipsum" -> lorem ipsum */
static char* process_string(const char *input, size_t input_len, size_t *output_len) {
const char *input_ptr = input;
size_t initial_size = (input_len + 1) * sizeof(char);
size_t final_size = 0;
char *output = NULL, *output_ptr = NULL, *resized_output = NULL;
output = (char*)parson_malloc(initial_size);
if (output == NULL) {
goto error;
}
output_ptr = output;
while ((*input_ptr != '\0') && (size_t)(input_ptr - input) < input_len) {
if (*input_ptr == '\\') {
input_ptr++;
switch (*input_ptr) {
case '\"': *output_ptr = '\"'; break;
case '\\': *output_ptr = '\\'; break;
case '/': *output_ptr = '/'; break;
case 'b': *output_ptr = '\b'; break;
case 'f': *output_ptr = '\f'; break;
case 'n': *output_ptr = '\n'; break;
case 'r': *output_ptr = '\r'; break;
case 't': *output_ptr = '\t'; break;
case 'u':
if (parse_utf16(&input_ptr, &output_ptr) == JSONFailure) {
goto error;
}
break;
default:
goto error;
}
} else if ((unsigned char)*input_ptr < 0x20) {
goto error; /* 0x00-0x19 are invalid characters for json string (http://www.ietf.org/rfc/rfc4627.txt) */
} else {
*output_ptr = *input_ptr;
}
output_ptr++;
input_ptr++;
}
*output_ptr = '\0';
/* resize to new length */
final_size = (size_t)(output_ptr-output) + 1;
/* todo: don't resize if final_size == initial_size */
resized_output = (char*)parson_malloc(final_size);
if (resized_output == NULL) {
goto error;
}
memcpy(resized_output, output, final_size);
*output_len = final_size - 1;
parson_free(output);
return resized_output;
error:
parson_free(output);
return NULL;
}
/* Return processed contents of a string between quotes and
skips passed argument to a matching quote. */
static char * get_quoted_string(const char **string, size_t *output_string_len) {
const char *string_start = *string;
size_t input_string_len = 0;
JSON_Status status = skip_quotes(string);
if (status != JSONSuccess) {
return NULL;
}
input_string_len = *string - string_start - 2; /* length without quotes */
return process_string(string_start + 1, input_string_len, output_string_len);
}
static JSON_Value * parse_value(const char **string, size_t nesting) {
if (nesting > MAX_NESTING) {
return NULL;
}
SKIP_WHITESPACES(string);
switch (**string) {
case '{':
return parse_object_value(string, nesting + 1);
case '[':
return parse_array_value(string, nesting + 1);
case '\"':
return parse_string_value(string);
case 'f': case 't':
return parse_boolean_value(string);
case '-':
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
return parse_number_value(string);
case 'n':
return parse_null_value(string);
default:
return NULL;
}
}
static JSON_Value * parse_object_value(const char **string, size_t nesting) {
JSON_Value *output_value = NULL, *new_value = NULL;
JSON_Object *output_object = NULL;
char *new_key = NULL;
output_value = json_value_init_object();
if (output_value == NULL) {
return NULL;
}
if (**string != '{') {
json_value_free(output_value);
return NULL;
}
output_object = json_value_get_object(output_value);
SKIP_CHAR(string);
SKIP_WHITESPACES(string);
if (**string == '}') { /* empty object */
SKIP_CHAR(string);
return output_value;
}
while (**string != '\0') {
size_t key_len = 0;
new_key = get_quoted_string(string, &key_len);
/* We do not support key names with embedded \0 chars */
if (new_key == NULL || key_len != strlen(new_key)) {
json_value_free(output_value);
return NULL;
}
SKIP_WHITESPACES(string);
if (**string != ':') {
parson_free(new_key);
json_value_free(output_value);
return NULL;
}
SKIP_CHAR(string);
new_value = parse_value(string, nesting);
if (new_value == NULL) {
parson_free(new_key);
json_value_free(output_value);
return NULL;
}
if (json_object_add(output_object, new_key, new_value) == JSONFailure) {
parson_free(new_key);
json_value_free(new_value);
json_value_free(output_value);
return NULL;
}
parson_free(new_key);
SKIP_WHITESPACES(string);
if (**string != ',') {
break;
}
SKIP_CHAR(string);
SKIP_WHITESPACES(string);
}
SKIP_WHITESPACES(string);
if (**string != '}' || /* Trim object after parsing is over */
json_object_resize(output_object, json_object_get_count(output_object)) == JSONFailure) {
json_value_free(output_value);
return NULL;
}
SKIP_CHAR(string);
return output_value;
}
static JSON_Value * parse_array_value(const char **string, size_t nesting) {
JSON_Value *output_value = NULL, *new_array_value = NULL;
JSON_Array *output_array = NULL;
output_value = json_value_init_array();
if (output_value == NULL) {
return NULL;
}
if (**string != '[') {
json_value_free(output_value);
return NULL;
}
output_array = json_value_get_array(output_value);
SKIP_CHAR(string);
SKIP_WHITESPACES(string);
if (**string == ']') { /* empty array */
SKIP_CHAR(string);
return output_value;
}
while (**string != '\0') {
new_array_value = parse_value(string, nesting);
if (new_array_value == NULL) {
json_value_free(output_value);
return NULL;
}
if (json_array_add(output_array, new_array_value) == JSONFailure) {
json_value_free(new_array_value);
json_value_free(output_value);
return NULL;
}
SKIP_WHITESPACES(string);
if (**string != ',') {
break;
}
SKIP_CHAR(string);
SKIP_WHITESPACES(string);
}
SKIP_WHITESPACES(string);
if (**string != ']' || /* Trim array after parsing is over */
json_array_resize(output_array, json_array_get_count(output_array)) == JSONFailure) {
json_value_free(output_value);
return NULL;
}
SKIP_CHAR(string);
return output_value;
}
static JSON_Value * parse_string_value(const char **string) {
JSON_Value *value = NULL;
size_t new_string_len = 0;
char *new_string = get_quoted_string(string, &new_string_len);
if (new_string == NULL) {
return NULL;
}
value = json_value_init_string_no_copy(new_string, new_string_len);
if (value == NULL) {
parson_free(new_string);
return NULL;
}
return value;
}
static JSON_Value * parse_boolean_value(const char **string) {
size_t true_token_size = SIZEOF_TOKEN("true");
size_t false_token_size = SIZEOF_TOKEN("false");
if (strncmp("true", *string, true_token_size) == 0) {
*string += true_token_size;
return json_value_init_boolean(1);
} else if (strncmp("false", *string, false_token_size) == 0) {
*string += false_token_size;
return json_value_init_boolean(0);
}
return NULL;
}
static JSON_Value * parse_number_value(const char **string) {
char *end;
double number = 0;
errno = 0;
number = strtod(*string, &end);
if (errno || !is_decimal(*string, end - *string)) {
return NULL;
}
*string = end;
return json_value_init_number(number);
}
static JSON_Value * parse_null_value(const char **string) {
size_t token_size = SIZEOF_TOKEN("null");
if (strncmp("null", *string, token_size) == 0) {
*string += token_size;
return json_value_init_null();
}
return NULL;
}
/* Serialization */
#define APPEND_STRING(str) do { written = append_string(buf, (str));\
if (written < 0) { return -1; }\
if (buf != NULL) { buf += written; }\
written_total += written; } while(0)
#define APPEND_INDENT(level) do { written = append_indent(buf, (level));\
if (written < 0) { return -1; }\
if (buf != NULL) { buf += written; }\
written_total += written; } while(0)
static int json_serialize_to_buffer_r(const JSON_Value *value, char *buf, int level, int is_pretty, char *num_buf)
{
const char *key = NULL, *string = NULL;
JSON_Value *temp_value = NULL;
JSON_Array *array = NULL;
JSON_Object *object = NULL;
size_t i = 0, count = 0;
double num = 0.0;
int written = -1, written_total = 0;
size_t len = 0;
switch (json_value_get_type(value)) {
case JSONArray:
array = json_value_get_array(value);
count = json_array_get_count(array);
APPEND_STRING("[");
if (count > 0 && is_pretty) {
APPEND_STRING("\n");
}
for (i = 0; i < count; i++) {
if (is_pretty) {
APPEND_INDENT(level+1);
}
temp_value = json_array_get_value(array, i);
written = json_serialize_to_buffer_r(temp_value, buf, level+1, is_pretty, num_buf);
if (written < 0) {
return -1;
}
if (buf != NULL) {
buf += written;
}
written_total += written;
if (i < (count - 1)) {
APPEND_STRING(",");
}
if (is_pretty) {
APPEND_STRING("\n");
}
}
if (count > 0 && is_pretty) {
APPEND_INDENT(level);
}
APPEND_STRING("]");
return written_total;
case JSONObject:
object = json_value_get_object(value);
count = json_object_get_count(object);
APPEND_STRING("{");
if (count > 0 && is_pretty) {
APPEND_STRING("\n");
}
for (i = 0; i < count; i++) {
key = json_object_get_name(object, i);
if (key == NULL) {
return -1;
}
if (is_pretty) {
APPEND_INDENT(level+1);
}
/* We do not support key names with embedded \0 chars */
written = json_serialize_string(key, strlen(key), buf);
if (written < 0) {
return -1;
}
if (buf != NULL) {
buf += written;
}
written_total += written;
APPEND_STRING(":");
if (is_pretty) {
APPEND_STRING(" ");
}
temp_value = json_object_get_value(object, key);
written = json_serialize_to_buffer_r(temp_value, buf, level+1, is_pretty, num_buf);
if (written < 0) {
return -1;
}
if (buf != NULL) {
buf += written;
}
written_total += written;
if (i < (count - 1)) {
APPEND_STRING(",");
}
if (is_pretty) {
APPEND_STRING("\n");
}
}
if (count > 0 && is_pretty) {
APPEND_INDENT(level);
}
APPEND_STRING("}");
return written_total;
case JSONString:
string = json_value_get_string(value);
if (string == NULL) {
return -1;
}
len = json_value_get_string_len(value);
written = json_serialize_string(string, len, buf);
if (written < 0) {
return -1;
}
if (buf != NULL) {
buf += written;
}
written_total += written;
return written_total;
case JSONBoolean:
if (json_value_get_boolean(value)) {
APPEND_STRING("true");
} else {
APPEND_STRING("false");
}
return written_total;
case JSONNumber:
num = json_value_get_number(value);
if (buf != NULL) {
num_buf = buf;
}
written = sprintf(num_buf, FLOAT_FORMAT, num);
if (written < 0) {
return -1;
}
if (buf != NULL) {
buf += written;
}
written_total += written;
return written_total;
case JSONNull:
APPEND_STRING("null");
return written_total;
case JSONError:
return -1;
default:
return -1;
}
}
static int json_serialize_string(const char *string, size_t len, char *buf) {
size_t i = 0;
char c = '\0';
int written = -1, written_total = 0;
APPEND_STRING("\"");
for (i = 0; i < len; i++) {
c = string[i];
switch (c) {
case '\"': APPEND_STRING("\\\""); break;
case '\\': APPEND_STRING("\\\\"); break;
case '\b': APPEND_STRING("\\b"); break;
case '\f': APPEND_STRING("\\f"); break;
case '\n': APPEND_STRING("\\n"); break;
case '\r': APPEND_STRING("\\r"); break;
case '\t': APPEND_STRING("\\t"); break;
case '\x00': APPEND_STRING("\\u0000"); break;
case '\x01': APPEND_STRING("\\u0001"); break;
case '\x02': APPEND_STRING("\\u0002"); break;
case '\x03': APPEND_STRING("\\u0003"); break;
case '\x04': APPEND_STRING("\\u0004"); break;
case '\x05': APPEND_STRING("\\u0005"); break;
case '\x06': APPEND_STRING("\\u0006"); break;
case '\x07': APPEND_STRING("\\u0007"); break;
/* '\x08' duplicate: '\b' */
/* '\x09' duplicate: '\t' */
/* '\x0a' duplicate: '\n' */
case '\x0b': APPEND_STRING("\\u000b"); break;
/* '\x0c' duplicate: '\f' */
/* '\x0d' duplicate: '\r' */
case '\x0e': APPEND_STRING("\\u000e"); break;
case '\x0f': APPEND_STRING("\\u000f"); break;
case '\x10': APPEND_STRING("\\u0010"); break;
case '\x11': APPEND_STRING("\\u0011"); break;
case '\x12': APPEND_STRING("\\u0012"); break;
case '\x13': APPEND_STRING("\\u0013"); break;
case '\x14': APPEND_STRING("\\u0014"); break;
case '\x15': APPEND_STRING("\\u0015"); break;
case '\x16': APPEND_STRING("\\u0016"); break;
case '\x17': APPEND_STRING("\\u0017"); break;
case '\x18': APPEND_STRING("\\u0018"); break;
case '\x19': APPEND_STRING("\\u0019"); break;
case '\x1a': APPEND_STRING("\\u001a"); break;
case '\x1b': APPEND_STRING("\\u001b"); break;
case '\x1c': APPEND_STRING("\\u001c"); break;
case '\x1d': APPEND_STRING("\\u001d"); break;
case '\x1e': APPEND_STRING("\\u001e"); break;
case '\x1f': APPEND_STRING("\\u001f"); break;
case '/':
if (parson_escape_slashes) {
APPEND_STRING("\\/"); /* to make json embeddable in xml\/html */
} else {
APPEND_STRING("/");
}
break;
default:
if (buf != NULL) {
buf[0] = c;
buf += 1;
}
written_total += 1;
break;
}
}
APPEND_STRING("\"");
return written_total;
}
static int append_indent(char *buf, int level) {
int i;
int written = -1, written_total = 0;
for (i = 0; i < level; i++) {
APPEND_STRING(" ");
}
return written_total;
}
static int append_string(char *buf, const char *string) {
if (buf == NULL) {
return (int)strlen(string);
}
return sprintf(buf, "%s", string);
}
#undef APPEND_STRING
#undef APPEND_INDENT
/* Parser API */
JSON_Value * json_parse_file(const char *filename) {
char *file_contents = read_file(filename);
JSON_Value *output_value = NULL;
if (file_contents == NULL) {
return NULL;
}
output_value = json_parse_string(file_contents);
parson_free(file_contents);
return output_value;
}
JSON_Value * json_parse_file_with_comments(const char *filename) {
char *file_contents = read_file(filename);
JSON_Value *output_value = NULL;
if (file_contents == NULL) {
return NULL;
}
output_value = json_parse_string_with_comments(file_contents);
parson_free(file_contents);
return output_value;
}
JSON_Value * json_parse_string(const char *string) {
if (string == NULL) {
return NULL;
}
if (string[0] == '\xEF' && string[1] == '\xBB' && string[2] == '\xBF') {
string = string + 3; /* Support for UTF-8 BOM */
}
return parse_value((const char**)&string, 0);
}
JSON_Value * json_parse_string_with_comments(const char *string) {
JSON_Value *result = NULL;
char *string_mutable_copy = NULL, *string_mutable_copy_ptr = NULL;
string_mutable_copy = parson_strdup(string);
if (string_mutable_copy == NULL) {
return NULL;
}
remove_comments(string_mutable_copy, "/*", "*/");
remove_comments(string_mutable_copy, "//", "\n");
string_mutable_copy_ptr = string_mutable_copy;
result = parse_value((const char**)&string_mutable_copy_ptr, 0);
parson_free(string_mutable_copy);
return result;
}
/* JSON Object API */
JSON_Value * json_object_get_value(const JSON_Object *object, const char *name) {
if (object == NULL || name == NULL) {
return NULL;
}
return json_object_getn_value(object, name, strlen(name));
}
const char * json_object_get_string(const JSON_Object *object, const char *name) {
return json_value_get_string(json_object_get_value(object, name));
}
size_t json_object_get_string_len(const JSON_Object *object, const char *name) {
return json_value_get_string_len(json_object_get_value(object, name));
}
double json_object_get_number(const JSON_Object *object, const char *name) {
return json_value_get_number(json_object_get_value(object, name));
}
JSON_Object * json_object_get_object(const JSON_Object *object, const char *name) {
return json_value_get_object(json_object_get_value(object, name));
}
JSON_Array * json_object_get_array(const JSON_Object *object, const char *name) {
return json_value_get_array(json_object_get_value(object, name));
}
int json_object_get_boolean(const JSON_Object *object, const char *name) {
return json_value_get_boolean(json_object_get_value(object, name));
}
JSON_Value * json_object_dotget_value(const JSON_Object *object, const char *name) {
const char *dot_position = strchr(name, '.');
if (!dot_position) {
return json_object_get_value(object, name);
}
object = json_value_get_object(json_object_getn_value(object, name, dot_position - name));
return json_object_dotget_value(object, dot_position + 1);
}
const char * json_object_dotget_string(const JSON_Object *object, const char *name) {
return json_value_get_string(json_object_dotget_value(object, name));
}
size_t json_object_dotget_string_len(const JSON_Object *object, const char *name) {
return json_value_get_string_len(json_object_dotget_value(object, name));
}
double json_object_dotget_number(const JSON_Object *object, const char *name) {
return json_value_get_number(json_object_dotget_value(object, name));
}
JSON_Object * json_object_dotget_object(const JSON_Object *object, const char *name) {
return json_value_get_object(json_object_dotget_value(object, name));
}
JSON_Array * json_object_dotget_array(const JSON_Object *object, const char *name) {
return json_value_get_array(json_object_dotget_value(object, name));
}
int json_object_dotget_boolean(const JSON_Object *object, const char *name) {
return json_value_get_boolean(json_object_dotget_value(object, name));
}
size_t json_object_get_count(const JSON_Object *object) {
return object ? object->count : 0;
}
const char * json_object_get_name(const JSON_Object *object, size_t index) {
if (object == NULL || index >= json_object_get_count(object)) {
return NULL;
}
return object->names[index];
}
JSON_Value * json_object_get_value_at(const JSON_Object *object, size_t index) {
if (object == NULL || index >= json_object_get_count(object)) {
return NULL;
}
return object->values[index];
}
JSON_Value *json_object_get_wrapping_value(const JSON_Object *object) {
return object->wrapping_value;
}
int json_object_has_value (const JSON_Object *object, const char *name) {
return json_object_get_value(object, name) != NULL;
}
int json_object_has_value_of_type(const JSON_Object *object, const char *name, JSON_Value_Type type) {
JSON_Value *val = json_object_get_value(object, name);
return val != NULL && json_value_get_type(val) == type;
}
int json_object_dothas_value (const JSON_Object *object, const char *name) {
return json_object_dotget_value(object, name) != NULL;
}
int json_object_dothas_value_of_type(const JSON_Object *object, const char *name, JSON_Value_Type type) {
JSON_Value *val = json_object_dotget_value(object, name);
return val != NULL && json_value_get_type(val) == type;
}
/* JSON Array API */
JSON_Value * json_array_get_value(const JSON_Array *array, size_t index) {
if (array == NULL || index >= json_array_get_count(array)) {
return NULL;
}
return array->items[index];
}
const char * json_array_get_string(const JSON_Array *array, size_t index) {
return json_value_get_string(json_array_get_value(array, index));
}
size_t json_array_get_string_len(const JSON_Array *array, size_t index) {
return json_value_get_string_len(json_array_get_value(array, index));
}
double json_array_get_number(const JSON_Array *array, size_t index) {
return json_value_get_number(json_array_get_value(array, index));
}
JSON_Object * json_array_get_object(const JSON_Array *array, size_t index) {
return json_value_get_object(json_array_get_value(array, index));
}
JSON_Array * json_array_get_array(const JSON_Array *array, size_t index) {
return json_value_get_array(json_array_get_value(array, index));
}
int json_array_get_boolean(const JSON_Array *array, size_t index) {
return json_value_get_boolean(json_array_get_value(array, index));
}
size_t json_array_get_count(const JSON_Array *array) {
return array ? array->count : 0;
}
JSON_Value * json_array_get_wrapping_value(const JSON_Array *array) {
return array->wrapping_value;
}
/* JSON Value API */
JSON_Value_Type json_value_get_type(const JSON_Value *value) {
return value ? value->type : JSONError;
}
JSON_Object * json_value_get_object(const JSON_Value *value) {
return json_value_get_type(value) == JSONObject ? value->value.object : NULL;
}
JSON_Array * json_value_get_array(const JSON_Value *value) {
return json_value_get_type(value) == JSONArray ? value->value.array : NULL;
}
static const JSON_String * json_value_get_string_desc(const JSON_Value *value) {
return json_value_get_type(value) == JSONString ? &value->value.string : NULL;
}
const char * json_value_get_string(const JSON_Value *value) {
const JSON_String *str = json_value_get_string_desc(value);
return str ? str->chars : NULL;
}
size_t json_value_get_string_len(const JSON_Value *value) {
const JSON_String *str = json_value_get_string_desc(value);
return str ? str->length : 0;
}
double json_value_get_number(const JSON_Value *value) {
return json_value_get_type(value) == JSONNumber ? value->value.number : 0;
}
int json_value_get_boolean(const JSON_Value *value) {
return json_value_get_type(value) == JSONBoolean ? value->value.boolean : -1;
}
JSON_Value * json_value_get_parent (const JSON_Value *value) {
return value ? value->parent : NULL;
}
void json_value_free(JSON_Value *value) {
switch (json_value_get_type(value)) {
case JSONObject:
json_object_free(value->value.object);
break;
case JSONString:
parson_free(value->value.string.chars);
break;
case JSONArray:
json_array_free(value->value.array);
break;
default:
break;
}
parson_free(value);
}
JSON_Value * json_value_init_object(void) {
JSON_Value *new_value = (JSON_Value*)parson_malloc(sizeof(JSON_Value));
if (!new_value) {
return NULL;
}
new_value->parent = NULL;
new_value->type = JSONObject;
new_value->value.object = json_object_init(new_value);
if (!new_value->value.object) {
parson_free(new_value);
return NULL;
}
return new_value;
}
JSON_Value * json_value_init_array(void) {
JSON_Value *new_value = (JSON_Value*)parson_malloc(sizeof(JSON_Value));
if (!new_value) {
return NULL;
}
new_value->parent = NULL;
new_value->type = JSONArray;
new_value->value.array = json_array_init(new_value);
if (!new_value->value.array) {
parson_free(new_value);
return NULL;
}
return new_value;
}
JSON_Value * json_value_init_string(const char *string) {
if (string == NULL) {
return NULL;
}
return json_value_init_string_with_len(string, strlen(string));
}
JSON_Value * json_value_init_string_with_len(const char *string, size_t length) {
char *copy = NULL;
JSON_Value *value;
if (string == NULL) {
return NULL;
}
if (!is_valid_utf8(string, length)) {
return NULL;
}
copy = parson_strndup(string, length);
if (copy == NULL) {
return NULL;
}
value = json_value_init_string_no_copy(copy, length);
if (value == NULL) {
parson_free(copy);
}
return value;
}
JSON_Value * json_value_init_number(double number) {
JSON_Value *new_value = NULL;
if (IS_NUMBER_INVALID(number)) {
return NULL;
}
new_value = (JSON_Value*)parson_malloc(sizeof(JSON_Value));
if (new_value == NULL) {
return NULL;
}
new_value->parent = NULL;
new_value->type = JSONNumber;
new_value->value.number = number;
return new_value;
}
JSON_Value * json_value_init_boolean(int boolean) {
JSON_Value *new_value = (JSON_Value*)parson_malloc(sizeof(JSON_Value));
if (!new_value) {
return NULL;
}
new_value->parent = NULL;
new_value->type = JSONBoolean;
new_value->value.boolean = boolean ? 1 : 0;
return new_value;
}
JSON_Value * json_value_init_null(void) {
JSON_Value *new_value = (JSON_Value*)parson_malloc(sizeof(JSON_Value));
if (!new_value) {
return NULL;
}
new_value->parent = NULL;
new_value->type = JSONNull;
return new_value;
}
JSON_Value * json_value_deep_copy(const JSON_Value *value) {
size_t i = 0;
JSON_Value *return_value = NULL, *temp_value_copy = NULL, *temp_value = NULL;
const JSON_String *temp_string = NULL;
const char *temp_key = NULL;
char *temp_string_copy = NULL;
JSON_Array *temp_array = NULL, *temp_array_copy = NULL;
JSON_Object *temp_object = NULL, *temp_object_copy = NULL;
switch (json_value_get_type(value)) {
case JSONArray:
temp_array = json_value_get_array(value);
return_value = json_value_init_array();
if (return_value == NULL) {
return NULL;
}
temp_array_copy = json_value_get_array(return_value);
for (i = 0; i < json_array_get_count(temp_array); i++) {
temp_value = json_array_get_value(temp_array, i);
temp_value_copy = json_value_deep_copy(temp_value);
if (temp_value_copy == NULL) {
json_value_free(return_value);
return NULL;
}
if (json_array_add(temp_array_copy, temp_value_copy) == JSONFailure) {
json_value_free(return_value);
json_value_free(temp_value_copy);
return NULL;
}
}
return return_value;
case JSONObject:
temp_object = json_value_get_object(value);
return_value = json_value_init_object();
if (return_value == NULL) {
return NULL;
}
temp_object_copy = json_value_get_object(return_value);
for (i = 0; i < json_object_get_count(temp_object); i++) {
temp_key = json_object_get_name(temp_object, i);
temp_value = json_object_get_value(temp_object, temp_key);
temp_value_copy = json_value_deep_copy(temp_value);
if (temp_value_copy == NULL) {
json_value_free(return_value);
return NULL;
}
if (json_object_add(temp_object_copy, temp_key, temp_value_copy) == JSONFailure) {
json_value_free(return_value);
json_value_free(temp_value_copy);
return NULL;
}
}
return return_value;
case JSONBoolean:
return json_value_init_boolean(json_value_get_boolean(value));
case JSONNumber:
return json_value_init_number(json_value_get_number(value));
case JSONString:
temp_string = json_value_get_string_desc(value);
if (temp_string == NULL) {
return NULL;
}
temp_string_copy = parson_strndup(temp_string->chars, temp_string->length);
if (temp_string_copy == NULL) {
return NULL;
}
return_value = json_value_init_string_no_copy(temp_string_copy, temp_string->length);
if (return_value == NULL) {
parson_free(temp_string_copy);
}
return return_value;
case JSONNull:
return json_value_init_null();
case JSONError:
return NULL;
default:
return NULL;
}
}
size_t json_serialization_size(const JSON_Value *value) {
char num_buf[NUM_BUF_SIZE]; /* recursively allocating buffer on stack is a bad idea, so let's do it only once */
int res = json_serialize_to_buffer_r(value, NULL, 0, 0, num_buf);
return res < 0 ? 0 : (size_t)(res) + 1;
}
JSON_Status json_serialize_to_buffer(const JSON_Value *value, char *buf, size_t buf_size_in_bytes) {
int written = -1;
size_t needed_size_in_bytes = json_serialization_size(value);
if (needed_size_in_bytes == 0 || buf_size_in_bytes < needed_size_in_bytes) {
return JSONFailure;
}
written = json_serialize_to_buffer_r(value, buf, 0, 0, NULL);
if (written < 0) {
return JSONFailure;
}
return JSONSuccess;
}
JSON_Status json_serialize_to_file(const JSON_Value *value, const char *filename) {
JSON_Status return_code = JSONSuccess;
FILE *fp = NULL;
char *serialized_string = json_serialize_to_string(value);
if (serialized_string == NULL) {
return JSONFailure;
}
fp = fopen(filename, "w");
if (fp == NULL) {
json_free_serialized_string(serialized_string);
return JSONFailure;
}
if (fputs(serialized_string, fp) == EOF) {
return_code = JSONFailure;
}
if (fclose(fp) == EOF) {
return_code = JSONFailure;
}
json_free_serialized_string(serialized_string);
return return_code;
}
char * json_serialize_to_string(const JSON_Value *value) {
JSON_Status serialization_result = JSONFailure;
size_t buf_size_bytes = json_serialization_size(value);
char *buf = NULL;
if (buf_size_bytes == 0) {
return NULL;
}
buf = (char*)parson_malloc(buf_size_bytes);
if (buf == NULL) {
return NULL;
}
serialization_result = json_serialize_to_buffer(value, buf, buf_size_bytes);
if (serialization_result == JSONFailure) {
json_free_serialized_string(buf);
return NULL;
}
return buf;
}
size_t json_serialization_size_pretty(const JSON_Value *value) {
char num_buf[NUM_BUF_SIZE]; /* recursively allocating buffer on stack is a bad idea, so let's do it only once */
int res = json_serialize_to_buffer_r(value, NULL, 0, 1, num_buf);
return res < 0 ? 0 : (size_t)(res) + 1;
}
JSON_Status json_serialize_to_buffer_pretty(const JSON_Value *value, char *buf, size_t buf_size_in_bytes) {
int written = -1;
size_t needed_size_in_bytes = json_serialization_size_pretty(value);
if (needed_size_in_bytes == 0 || buf_size_in_bytes < needed_size_in_bytes) {
return JSONFailure;
}
written = json_serialize_to_buffer_r(value, buf, 0, 1, NULL);
if (written < 0) {
return JSONFailure;
}
return JSONSuccess;
}
JSON_Status json_serialize_to_file_pretty(const JSON_Value *value, const char *filename) {
JSON_Status return_code = JSONSuccess;
FILE *fp = NULL;
char *serialized_string = json_serialize_to_string_pretty(value);
if (serialized_string == NULL) {
return JSONFailure;
}
fp = fopen(filename, "w");
if (fp == NULL) {
json_free_serialized_string(serialized_string);
return JSONFailure;
}
if (fputs(serialized_string, fp) == EOF) {
return_code = JSONFailure;
}
if (fclose(fp) == EOF) {
return_code = JSONFailure;
}
json_free_serialized_string(serialized_string);
return return_code;
}
char * json_serialize_to_string_pretty(const JSON_Value *value) {
JSON_Status serialization_result = JSONFailure;
size_t buf_size_bytes = json_serialization_size_pretty(value);
char *buf = NULL;
if (buf_size_bytes == 0) {
return NULL;
}
buf = (char*)parson_malloc(buf_size_bytes);
if (buf == NULL) {
return NULL;
}
serialization_result = json_serialize_to_buffer_pretty(value, buf, buf_size_bytes);
if (serialization_result == JSONFailure) {
json_free_serialized_string(buf);
return NULL;
}
return buf;
}
void json_free_serialized_string(char *string) {
parson_free(string);
}
JSON_Status json_array_remove(JSON_Array *array, size_t ix) {
size_t to_move_bytes = 0;
if (array == NULL || ix >= json_array_get_count(array)) {
return JSONFailure;
}
json_value_free(json_array_get_value(array, ix));
to_move_bytes = (json_array_get_count(array) - 1 - ix) * sizeof(JSON_Value*);
memmove(array->items + ix, array->items + ix + 1, to_move_bytes);
array->count -= 1;
return JSONSuccess;
}
JSON_Status json_array_replace_value(JSON_Array *array, size_t ix, JSON_Value *value) {
if (array == NULL || value == NULL || value->parent != NULL || ix >= json_array_get_count(array)) {
return JSONFailure;
}
json_value_free(json_array_get_value(array, ix));
value->parent = json_array_get_wrapping_value(array);
array->items[ix] = value;
return JSONSuccess;
}
JSON_Status json_array_replace_string(JSON_Array *array, size_t i, const char* string) {
JSON_Value *value = json_value_init_string(string);
if (value == NULL) {
return JSONFailure;
}
if (json_array_replace_value(array, i, value) == JSONFailure) {
json_value_free(value);
return JSONFailure;
}
return JSONSuccess;
}
JSON_Status json_array_replace_string_with_len(JSON_Array *array, size_t i, const char *string, size_t len) {
JSON_Value *value = json_value_init_string_with_len(string, len);
if (value == NULL) {
return JSONFailure;
}
if (json_array_replace_value(array, i, value) == JSONFailure) {
json_value_free(value);
return JSONFailure;
}
return JSONSuccess;
}
JSON_Status json_array_replace_number(JSON_Array *array, size_t i, double number) {
JSON_Value *value = json_value_init_number(number);
if (value == NULL) {
return JSONFailure;
}
if (json_array_replace_value(array, i, value) == JSONFailure) {
json_value_free(value);
return JSONFailure;
}
return JSONSuccess;
}
JSON_Status json_array_replace_boolean(JSON_Array *array, size_t i, int boolean) {
JSON_Value *value = json_value_init_boolean(boolean);
if (value == NULL) {
return JSONFailure;
}
if (json_array_replace_value(array, i, value) == JSONFailure) {
json_value_free(value);
return JSONFailure;
}
return JSONSuccess;
}
JSON_Status json_array_replace_null(JSON_Array *array, size_t i) {
JSON_Value *value = json_value_init_null();
if (value == NULL) {
return JSONFailure;
}
if (json_array_replace_value(array, i, value) == JSONFailure) {
json_value_free(value);
return JSONFailure;
}
return JSONSuccess;
}
JSON_Status json_array_clear(JSON_Array *array) {
size_t i = 0;
if (array == NULL) {
return JSONFailure;
}
for (i = 0; i < json_array_get_count(array); i++) {
json_value_free(json_array_get_value(array, i));
}
array->count = 0;
return JSONSuccess;
}
JSON_Status json_array_append_value(JSON_Array *array, JSON_Value *value) {
if (array == NULL || value == NULL || value->parent != NULL) {
return JSONFailure;
}
return json_array_add(array, value);
}
JSON_Status json_array_append_string(JSON_Array *array, const char *string) {
JSON_Value *value = json_value_init_string(string);
if (value == NULL) {
return JSONFailure;
}
if (json_array_append_value(array, value) == JSONFailure) {
json_value_free(value);
return JSONFailure;
}
return JSONSuccess;
}
JSON_Status json_array_append_string_with_len(JSON_Array *array, const char *string, size_t len) {
JSON_Value *value = json_value_init_string_with_len(string, len);
if (value == NULL) {
return JSONFailure;
}
if (json_array_append_value(array, value) == JSONFailure) {
json_value_free(value);
return JSONFailure;
}
return JSONSuccess;
}
JSON_Status json_array_append_number(JSON_Array *array, double number) {
JSON_Value *value = json_value_init_number(number);
if (value == NULL) {
return JSONFailure;
}
if (json_array_append_value(array, value) == JSONFailure) {
json_value_free(value);
return JSONFailure;
}
return JSONSuccess;
}
JSON_Status json_array_append_boolean(JSON_Array *array, int boolean) {
JSON_Value *value = json_value_init_boolean(boolean);
if (value == NULL) {
return JSONFailure;
}
if (json_array_append_value(array, value) == JSONFailure) {
json_value_free(value);
return JSONFailure;
}
return JSONSuccess;
}
JSON_Status json_array_append_null(JSON_Array *array) {
JSON_Value *value = json_value_init_null();
if (value == NULL) {
return JSONFailure;
}
if (json_array_append_value(array, value) == JSONFailure) {
json_value_free(value);
return JSONFailure;
}
return JSONSuccess;
}
JSON_Status json_object_set_value(JSON_Object *object, const char *name, JSON_Value *value) {
size_t i = 0;
JSON_Value *old_value;
if (object == NULL || name == NULL || value == NULL || value->parent != NULL) {
return JSONFailure;
}
old_value = json_object_get_value(object, name);
if (old_value != NULL) { /* free and overwrite old value */
json_value_free(old_value);
for (i = 0; i < json_object_get_count(object); i++) {
if (strcmp(object->names[i], name) == 0) {
value->parent = json_object_get_wrapping_value(object);
object->values[i] = value;
return JSONSuccess;
}
}
}
/* add new key value pair */
return json_object_add(object, name, value);
}
JSON_Status json_object_set_string(JSON_Object *object, const char *name, const char *string) {
JSON_Value *value = json_value_init_string(string);
JSON_Status status = json_object_set_value(object, name, value);
if (status == JSONFailure) {
json_value_free(value);
}
return status;
}
JSON_Status json_object_set_string_with_len(JSON_Object *object, const char *name, const char *string, size_t len) {
JSON_Value *value = json_value_init_string_with_len(string, len);
JSON_Status status = json_object_set_value(object, name, value);
if (status == JSONFailure) {
json_value_free(value);
}
return status;
}
JSON_Status json_object_set_number(JSON_Object *object, const char *name, double number) {
JSON_Value *value = json_value_init_number(number);
JSON_Status status = json_object_set_value(object, name, value);
if (status == JSONFailure) {
json_value_free(value);
}
return status;
}
JSON_Status json_object_set_boolean(JSON_Object *object, const char *name, int boolean) {
JSON_Value *value = json_value_init_boolean(boolean);
JSON_Status status = json_object_set_value(object, name, value);
if (status == JSONFailure) {
json_value_free(value);
}
return status;
}
JSON_Status json_object_set_null(JSON_Object *object, const char *name) {
JSON_Value *value = json_value_init_null();
JSON_Status status = json_object_set_value(object, name, value);
if (status == JSONFailure) {
json_value_free(value);
}
return status;
}
JSON_Status json_object_dotset_value(JSON_Object *object, const char *name, JSON_Value *value) {
const char *dot_pos = NULL;
JSON_Value *temp_value = NULL, *new_value = NULL;
JSON_Object *temp_object = NULL, *new_object = NULL;
JSON_Status status = JSONFailure;
size_t name_len = 0;
if (object == NULL || name == NULL || value == NULL) {
return JSONFailure;
}
dot_pos = strchr(name, '.');
if (dot_pos == NULL) {
return json_object_set_value(object, name, value);
}
name_len = dot_pos - name;
temp_value = json_object_getn_value(object, name, name_len);
if (temp_value) {
/* Don't overwrite existing non-object (unlike json_object_set_value, but it shouldn't be changed at this point) */
if (json_value_get_type(temp_value) != JSONObject) {
return JSONFailure;
}
temp_object = json_value_get_object(temp_value);
return json_object_dotset_value(temp_object, dot_pos + 1, value);
}
new_value = json_value_init_object();
if (new_value == NULL) {
return JSONFailure;
}
new_object = json_value_get_object(new_value);
status = json_object_dotset_value(new_object, dot_pos + 1, value);
if (status != JSONSuccess) {
json_value_free(new_value);
return JSONFailure;
}
status = json_object_addn(object, name, name_len, new_value);
if (status != JSONSuccess) {
json_object_dotremove_internal(new_object, dot_pos + 1, 0);
json_value_free(new_value);
return JSONFailure;
}
return JSONSuccess;
}
JSON_Status json_object_dotset_string(JSON_Object *object, const char *name, const char *string) {
JSON_Value *value = json_value_init_string(string);
if (value == NULL) {
return JSONFailure;
}
if (json_object_dotset_value(object, name, value) == JSONFailure) {
json_value_free(value);
return JSONFailure;
}
return JSONSuccess;
}
JSON_Status json_object_dotset_string_with_len(JSON_Object *object, const char *name, const char *string, size_t len) {
JSON_Value *value = json_value_init_string_with_len(string, len);
if (value == NULL) {
return JSONFailure;
}
if (json_object_dotset_value(object, name, value) == JSONFailure) {
json_value_free(value);
return JSONFailure;
}
return JSONSuccess;
}
JSON_Status json_object_dotset_number(JSON_Object *object, const char *name, double number) {
JSON_Value *value = json_value_init_number(number);
if (value == NULL) {
return JSONFailure;
}
if (json_object_dotset_value(object, name, value) == JSONFailure) {
json_value_free(value);
return JSONFailure;
}
return JSONSuccess;
}
JSON_Status json_object_dotset_boolean(JSON_Object *object, const char *name, int boolean) {
JSON_Value *value = json_value_init_boolean(boolean);
if (value == NULL) {
return JSONFailure;
}
if (json_object_dotset_value(object, name, value) == JSONFailure) {
json_value_free(value);
return JSONFailure;
}
return JSONSuccess;
}
JSON_Status json_object_dotset_null(JSON_Object *object, const char *name) {
JSON_Value *value = json_value_init_null();
if (value == NULL) {
return JSONFailure;
}
if (json_object_dotset_value(object, name, value) == JSONFailure) {
json_value_free(value);
return JSONFailure;
}
return JSONSuccess;
}
JSON_Status json_object_remove(JSON_Object *object, const char *name) {
return json_object_remove_internal(object, name, 1);
}
JSON_Status json_object_dotremove(JSON_Object *object, const char *name) {
return json_object_dotremove_internal(object, name, 1);
}
JSON_Status json_object_clear(JSON_Object *object) {
size_t i = 0;
if (object == NULL) {
return JSONFailure;
}
for (i = 0; i < json_object_get_count(object); i++) {
parson_free(object->names[i]);
json_value_free(object->values[i]);
}
object->count = 0;
return JSONSuccess;
}
JSON_Status json_validate(const JSON_Value *schema, const JSON_Value *value) {
JSON_Value *temp_schema_value = NULL, *temp_value = NULL;
JSON_Array *schema_array = NULL, *value_array = NULL;
JSON_Object *schema_object = NULL, *value_object = NULL;
JSON_Value_Type schema_type = JSONError, value_type = JSONError;
const char *key = NULL;
size_t i = 0, count = 0;
if (schema == NULL || value == NULL) {
return JSONFailure;
}
schema_type = json_value_get_type(schema);
value_type = json_value_get_type(value);
if (schema_type != value_type && schema_type != JSONNull) { /* null represents all values */
return JSONFailure;
}
switch (schema_type) {
case JSONArray:
schema_array = json_value_get_array(schema);
value_array = json_value_get_array(value);
count = json_array_get_count(schema_array);
if (count == 0) {
return JSONSuccess; /* Empty array allows all types */
}
/* Get first value from array, rest is ignored */
temp_schema_value = json_array_get_value(schema_array, 0);
for (i = 0; i < json_array_get_count(value_array); i++) {
temp_value = json_array_get_value(value_array, i);
if (json_validate(temp_schema_value, temp_value) == JSONFailure) {
return JSONFailure;
}
}
return JSONSuccess;
case JSONObject:
schema_object = json_value_get_object(schema);
value_object = json_value_get_object(value);
count = json_object_get_count(schema_object);
if (count == 0) {
return JSONSuccess; /* Empty object allows all objects */
} else if (json_object_get_count(value_object) < count) {
return JSONFailure; /* Tested object mustn't have less name-value pairs than schema */
}
for (i = 0; i < count; i++) {
key = json_object_get_name(schema_object, i);
temp_schema_value = json_object_get_value(schema_object, key);
temp_value = json_object_get_value(value_object, key);
if (temp_value == NULL) {
return JSONFailure;
}
if (json_validate(temp_schema_value, temp_value) == JSONFailure) {
return JSONFailure;
}
}
return JSONSuccess;
case JSONString: case JSONNumber: case JSONBoolean: case JSONNull:
return JSONSuccess; /* equality already tested before switch */
case JSONError: default:
return JSONFailure;
}
}
int json_value_equals(const JSON_Value *a, const JSON_Value *b) {
JSON_Object *a_object = NULL, *b_object = NULL;
JSON_Array *a_array = NULL, *b_array = NULL;
const JSON_String *a_string = NULL, *b_string = NULL;
const char *key = NULL;
size_t a_count = 0, b_count = 0, i = 0;
JSON_Value_Type a_type, b_type;
a_type = json_value_get_type(a);
b_type = json_value_get_type(b);
if (a_type != b_type) {
return 0;
}
switch (a_type) {
case JSONArray:
a_array = json_value_get_array(a);
b_array = json_value_get_array(b);
a_count = json_array_get_count(a_array);
b_count = json_array_get_count(b_array);
if (a_count != b_count) {
return 0;
}
for (i = 0; i < a_count; i++) {
if (!json_value_equals(json_array_get_value(a_array, i),
json_array_get_value(b_array, i))) {
return 0;
}
}
return 1;
case JSONObject:
a_object = json_value_get_object(a);
b_object = json_value_get_object(b);
a_count = json_object_get_count(a_object);
b_count = json_object_get_count(b_object);
if (a_count != b_count) {
return 0;
}
for (i = 0; i < a_count; i++) {
key = json_object_get_name(a_object, i);
if (!json_value_equals(json_object_get_value(a_object, key),
json_object_get_value(b_object, key))) {
return 0;
}
}
return 1;
case JSONString:
a_string = json_value_get_string_desc(a);
b_string = json_value_get_string_desc(b);
if (a_string == NULL || b_string == NULL) {
return 0; /* shouldn't happen */
}
return a_string->length == b_string->length &&
memcmp(a_string->chars, b_string->chars, a_string->length) == 0;
case JSONBoolean:
return json_value_get_boolean(a) == json_value_get_boolean(b);
case JSONNumber:
return fabs(json_value_get_number(a) - json_value_get_number(b)) < 0.000001; /* EPSILON */
case JSONError:
return 1;
case JSONNull:
return 1;
default:
return 1;
}
}
JSON_Value_Type json_type(const JSON_Value *value) {
return json_value_get_type(value);
}
JSON_Object * json_object (const JSON_Value *value) {
return json_value_get_object(value);
}
JSON_Array * json_array (const JSON_Value *value) {
return json_value_get_array(value);
}
const char * json_string (const JSON_Value *value) {
return json_value_get_string(value);
}
size_t json_string_len(const JSON_Value *value) {
return json_value_get_string_len(value);
}
double json_number (const JSON_Value *value) {
return json_value_get_number(value);
}
int json_boolean(const JSON_Value *value) {
return json_value_get_boolean(value);
}
void json_set_allocation_functions(JSON_Malloc_Function malloc_fun, JSON_Free_Function free_fun) {
parson_malloc = malloc_fun;
parson_free = free_fun;
}
void json_set_escape_slashes(int escape_slashes) {
parson_escape_slashes = escape_slashes;
}
| mit |
josephbisch/deb-namecoin-core | src/auxpow.cpp | 1 | 6665 | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2011 Vince Durham
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2014-2015 Daniel Kraft
// Distributed under the MIT/X11 software license, see the accompanying
// file license.txt or http://www.opensource.org/licenses/mit-license.php.
#include "auxpow.h"
#include "consensus/validation.h"
#include "main.h"
#include "script/script.h"
#include "util.h"
#include <algorithm>
/* Moved from wallet.cpp. CMerkleTx is necessary for auxpow, independent
of an enabled (or disabled) wallet. Always include the code. */
int CMerkleTx::SetMerkleBranch(const CBlock& block)
{
AssertLockHeld(cs_main);
CBlock blockTmp;
// Update the tx's hashBlock
hashBlock = block.GetHash();
// Locate the transaction
for (nIndex = 0; nIndex < (int)block.vtx.size(); nIndex++)
if (block.vtx[nIndex] == *(CTransaction*)this)
break;
if (nIndex == (int)block.vtx.size())
{
vMerkleBranch.clear();
nIndex = -1;
LogPrintf("ERROR: SetMerkleBranch(): couldn't find tx in block\n");
return 0;
}
// Fill in merkle branch
vMerkleBranch = block.GetMerkleBranch(nIndex);
// Is the tx in a block that's in the main chain
BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
if (mi == mapBlockIndex.end())
return 0;
const CBlockIndex* pindex = (*mi).second;
if (!pindex || !chainActive.Contains(pindex))
return 0;
return chainActive.Height() - pindex->nHeight + 1;
}
int CMerkleTx::GetDepthInMainChainINTERNAL(const CBlockIndex* &pindexRet) const
{
if (hashBlock.IsNull() || nIndex == -1)
return 0;
AssertLockHeld(cs_main);
// Find the block it claims to be in
BlockMap::iterator mi = mapBlockIndex.find(hashBlock);
if (mi == mapBlockIndex.end())
return 0;
CBlockIndex* pindex = (*mi).second;
if (!pindex || !chainActive.Contains(pindex))
return 0;
// Make sure the merkle branch connects to this block
if (!fMerkleVerified)
{
if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != pindex->hashMerkleRoot)
return 0;
fMerkleVerified = true;
}
pindexRet = pindex;
return chainActive.Height() - pindex->nHeight + 1;
}
int CMerkleTx::GetDepthInMainChain(const CBlockIndex* &pindexRet) const
{
AssertLockHeld(cs_main);
int nResult = GetDepthInMainChainINTERNAL(pindexRet);
if (nResult == 0 && !mempool.exists(GetHash()))
return -1; // Not in chain, not in mempool
return nResult;
}
int CMerkleTx::GetBlocksToMaturity() const
{
if (!IsCoinBase())
return 0;
return std::max(0, (COINBASE_MATURITY+1) - GetDepthInMainChain());
}
bool CMerkleTx::AcceptToMemoryPool(bool fLimitFree, bool fRejectAbsurdFee)
{
CValidationState state;
return ::AcceptToMemoryPool(mempool, state, *this, fLimitFree, NULL, fRejectAbsurdFee);
}
/* ************************************************************************** */
bool
CAuxPow::check (const uint256& hashAuxBlock, int nChainId,
const Consensus::Params& params) const
{
if (nIndex != 0)
return error("AuxPow is not a generate");
if (params.fStrictChainId && parentBlock.nVersion.GetChainId () == nChainId)
return error("Aux POW parent has our chain ID");
if (vChainMerkleBranch.size() > 30)
return error("Aux POW chain merkle branch too long");
// Check that the chain merkle root is in the coinbase
const uint256 nRootHash
= CBlock::CheckMerkleBranch (hashAuxBlock, vChainMerkleBranch,
nChainIndex);
valtype vchRootHash(nRootHash.begin (), nRootHash.end ());
std::reverse (vchRootHash.begin (), vchRootHash.end ()); // correct endian
// Check that we are in the parent block merkle tree
if (CBlock::CheckMerkleBranch(GetHash(), vMerkleBranch, nIndex) != parentBlock.hashMerkleRoot)
return error("Aux POW merkle root incorrect");
const CScript script = vin[0].scriptSig;
// Check that the same work is not submitted twice to our chain.
//
CScript::const_iterator pcHead =
std::search(script.begin(), script.end(), UBEGIN(pchMergedMiningHeader), UEND(pchMergedMiningHeader));
CScript::const_iterator pc =
std::search(script.begin(), script.end(), vchRootHash.begin(), vchRootHash.end());
if (pc == script.end())
return error("Aux POW missing chain merkle root in parent coinbase");
if (pcHead != script.end())
{
// Enforce only one chain merkle root by checking that a single instance of the merged
// mining header exists just before.
if (script.end() != std::search(pcHead + 1, script.end(), UBEGIN(pchMergedMiningHeader), UEND(pchMergedMiningHeader)))
return error("Multiple merged mining headers in coinbase");
if (pcHead + sizeof(pchMergedMiningHeader) != pc)
return error("Merged mining header is not just before chain merkle root");
}
else
{
// For backward compatibility.
// Enforce only one chain merkle root by checking that it starts early in the coinbase.
// 8-12 bytes are enough to encode extraNonce and nBits.
if (pc - script.begin() > 20)
return error("Aux POW chain merkle root must start in the first 20 bytes of the parent coinbase");
}
// Ensure we are at a deterministic point in the merkle leaves by hashing
// a nonce and our chain ID and comparing to the index.
pc += vchRootHash.size();
if (script.end() - pc < 8)
return error("Aux POW missing chain merkle tree size and nonce in parent coinbase");
int nSize;
memcpy(&nSize, &pc[0], 4);
const unsigned merkleHeight = vChainMerkleBranch.size ();
if (nSize != (1 << merkleHeight))
return error("Aux POW merkle branch size does not match parent coinbase");
int nNonce;
memcpy(&nNonce, &pc[4], 4);
if (nChainIndex != getExpectedIndex (nNonce, nChainId, merkleHeight))
return error("Aux POW wrong index");
return true;
}
int
CAuxPow::getExpectedIndex (int nNonce, int nChainId, unsigned h)
{
// Choose a pseudo-random slot in the chain merkle tree
// but have it be fixed for a size/nonce/chain combination.
//
// This prevents the same work from being used twice for the
// same chain while reducing the chance that two chains clash
// for the same slot.
unsigned rand = nNonce;
rand = rand * 1103515245 + 12345;
rand += nChainId;
rand = rand * 1103515245 + 12345;
return rand % (1 << h);
}
| mit |
mcodegeeks/OpenKODE-Framework | 03_Tutorial/T07_XMOgre3D/Source/Sample/NewInstancing.cpp | 1 | 3109 | /* ------------------------------------------------------------------------------------
*
* File NewInstancing.cpp
* Description This source file is part of OGRE
* (Object-oriented Graphics Rendering Engine)
* Author Y.H Mun
*
* ------------------------------------------------------------------------------------
*
* Copyright (c) 2010-2013 XMSoft. All rights reserved.
*
* Contact Email: xmsoft77@gmail.com
*
* ------------------------------------------------------------------------------------
*
* Copyright (c) 2010-2012 Torus Knot Software Ltd.
*
* For the latest info, see http://www.ogre3d.org/
*
* ------------------------------------------------------------------------------------
*
* 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 "NewInstancing.h"
Sample_NewInstancing::Sample_NewInstancing ( KDvoid )
{
m_aInfo [ "Title" ] = "New Instancing";
m_aInfo [ "Description" ] = "Demonstrates how to use the new InstancedManager to setup many dynamic"
" instances of the same mesh with much less performance impact";
m_aInfo [ "Thumbnail" ] = "thumb_newinstancing.png";
m_aInfo [ "Category" ] = "Environment";
m_aInfo [ "Help" ] = "Press Space to switch Instancing Techniques.\n"
"Press B to toggle bounding boxes.\n\n"
"Changes in the slider take effect after switching instancing technique\n"
"Different batch sizes give different results depending on CPU culling"
" and instance numbers on the scene.\n\n"
"If performance is too slow, try defragmenting batches once in a while";
}
KDvoid Sample_NewInstancing::setupContent ( KDvoid )
{
}
| mit |
maurer/tiamat | samples/Juliet/testcases/CWE789_Uncontrolled_Mem_Alloc/s01/CWE789_Uncontrolled_Mem_Alloc__malloc_char_fgets_53d.c | 1 | 3596 | /* TEMPLATE GENERATED TESTCASE FILE
Filename: CWE789_Uncontrolled_Mem_Alloc__malloc_char_fgets_53d.c
Label Definition File: CWE789_Uncontrolled_Mem_Alloc__malloc.label.xml
Template File: sources-sinks-53d.tmpl.c
*/
/*
* @description
* CWE: 789 Uncontrolled Memory Allocation
* BadSource: fgets Read data from the console using fgets()
* GoodSource: Small number greater than zero
* Sinks:
* GoodSink: Allocate memory with malloc() and check the size of the memory to be allocated
* BadSink : Allocate memory with malloc(), but incorrectly check the size of the memory to be allocated
* Flow Variant: 53 Data flow: data passed as an argument from one function through two others to a fourth; all four functions are in different source files
*
* */
#include "std_testcase.h"
#ifndef _WIN32
#include <wchar.h>
#endif
#define CHAR_ARRAY_SIZE (3 * sizeof(data) + 2)
#define HELLO_STRING "hello"
#ifndef OMITBAD
void CWE789_Uncontrolled_Mem_Alloc__malloc_char_fgets_53d_badSink(size_t data)
{
{
char * myString;
/* POTENTIAL FLAW: No MAXIMUM limitation for memory allocation, but ensure data is large enough
* for the strcpy() function to not cause a buffer overflow */
/* INCIDENTAL FLAW: The source could cause a type overrun in data or in the memory allocation */
if (data > strlen(HELLO_STRING))
{
myString = (char *)malloc(data*sizeof(char));
/* Copy a small string into myString */
strcpy(myString, HELLO_STRING);
printLine(myString);
free(myString);
}
else
{
printLine("Input is less than the length of the source string");
}
}
}
#endif /* OMITBAD */
#ifndef OMITGOOD
/* goodG2B uses the GoodSource with the BadSink */
void CWE789_Uncontrolled_Mem_Alloc__malloc_char_fgets_53d_goodG2BSink(size_t data)
{
{
char * myString;
/* POTENTIAL FLAW: No MAXIMUM limitation for memory allocation, but ensure data is large enough
* for the strcpy() function to not cause a buffer overflow */
/* INCIDENTAL FLAW: The source could cause a type overrun in data or in the memory allocation */
if (data > strlen(HELLO_STRING))
{
myString = (char *)malloc(data*sizeof(char));
/* Copy a small string into myString */
strcpy(myString, HELLO_STRING);
printLine(myString);
free(myString);
}
else
{
printLine("Input is less than the length of the source string");
}
}
}
/* goodB2G uses the BadSource with the GoodSink */
void CWE789_Uncontrolled_Mem_Alloc__malloc_char_fgets_53d_goodB2GSink(size_t data)
{
{
char * myString;
/* FIX: Include a MAXIMUM limitation for memory allocation and a check to ensure data is large enough
* for the strcpy() function to not cause a buffer overflow */
/* INCIDENTAL FLAW: The source could cause a type overrun in data or in the memory allocation */
if (data > strlen(HELLO_STRING) && data < 100)
{
myString = (char *)malloc(data*sizeof(char));
/* Copy a small string into myString */
strcpy(myString, HELLO_STRING);
printLine(myString);
free(myString);
}
else
{
printLine("Input is less than the length of the source string or too large");
}
}
}
#endif /* OMITGOOD */
| mit |
maxnolan/summer2017 | makeashape.cpp | 1 | 2441 | #include <iostream>
#include <vector>
#include <fstream>
#include <CGAL/HalfedgeDS_default.h>
#include <CGAL/HalfedgeDS_vertex_base.h>
#include <CGAL/HalfedgeDS_decorator.h>
#include <CGAL/Simple_cartesian.h>
// typedef CGAL::Simple_cartesian<double> Kernel;
// typedef Kernel::Point_3 Point_3;
struct Traits { typedef int Point_2; };
typedef CGAL::HalfedgeDS_default<Traits> HDS;
// typedef CGAL::HalfedgeDS_vertex_base<HDS,CGAL::Tag_true,Point_3> Vertex;
typedef CGAL::HalfedgeDS_decorator<HDS> Decorator;
typedef HDS::Halfedge_iterator Iterator;
typedef HDS::Vertex_iterator VIterator;
// typedef HDS::Vertex_const_handle Vertex_const_handle;
typedef HDS::Halfedge_handle Halfedge_handle;
typedef HDS::Halfedge Halfedge;
typedef HDS::Vertex Vertex;
typedef HDS::Face Face;
typedef HDS::Face_handle Face_handle;
typedef HDS::Vertex_handle Vertex_handle;
Face_handle createFace(HDS *hds, Decorator decorator, int numEdges) //TODO should take vertices as arg not edges
{
std::vector<Halfedge_handle> edges;
for (int i = 0; i < numEdges; i++)
{
edges.push_back( hds->edges_push_back( Halfedge(), Halfedge()));
}
for (int i = 0; i < numEdges; i++)
{
edges[i]->Halfedge::Base::set_next( edges[(i+1) % numEdges]);
edges[(i+1) % numEdges]->opposite()->Halfedge::Base::set_next( edges[i]->opposite());
decorator.set_prev( edges[(i+1) % numEdges], edges[i]);
decorator.set_prev( edges[i], edges[(i+1) % numEdges]);
decorator.set_vertex( edges[i], decorator.vertices_push_back( Vertex()));
decorator.set_vertex( edges[(i+1) % numEdges]->opposite(), decorator.get_vertex(edges[i]));
decorator.set_vertex_halfedge( edges[i]);
}
decorator.set_face( edges[0], decorator.faces_push_back( Face()));
decorator.set_face( edges[0]->opposite(), decorator.faces_push_back( Face()));
for (int i = 1; i < numEdges; i++)
{
decorator.set_face( edges[i], decorator.get_face(edges[0]));
decorator.set_face( edges[i]->opposite(), decorator.get_face(edges[0]->opposite()));
}
decorator.set_face_halfedge( edges[0]);
decorator.set_face_halfedge( edges[0]->opposite());
return decorator.get_face(edges[0]);
}
int main()
{
HDS hds;
Decorator decorator(hds);
createFace(hds, decorator, 3);
CGAL_assertion( decorator.is_valid());
return 0;
}
| mit |
peteo/BSDSocketTest | libs/cocos2dx/platform/CCFileUtils.cpp | 2 | 10984 | /****************************************************************************
Copyright (c) 2010 cocos2d-x.org
http://www.cocos2d-x.org
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 "CCFileUtils.h"
#include "CCDirector.h"
#if (CC_TARGET_PLATFORM != CC_PLATFORM_IOS) && (CC_TARGET_PLATFORM != CC_PLATFORM_AIRPLAY)
#include <stack>
#include <libxml/parser.h>
#include <libxml/tree.h>
#include <libxml/xmlmemory.h>
#include "CCLibxml2.h"
#include "CCString.h"
#include "CCSAXParser.h"
#include "support/zip_support/unzip.h"
NS_CC_BEGIN;
typedef enum
{
SAX_NONE = 0,
SAX_KEY,
SAX_DICT,
SAX_INT,
SAX_REAL,
SAX_STRING,
SAX_ARRAY
}CCSAXState;
class CCDictMaker : public CCSAXDelegator
{
public:
CCDictionary<std::string, CCObject*> *m_pRootDict;
CCDictionary<std::string, CCObject*> *m_pCurDict;
std::stack<CCDictionary<std::string, CCObject*>*> m_tDictStack;
std::string m_sCurKey;///< parsed key
CCSAXState m_tState;
CCMutableArray<CCObject*> *m_pArray;
std::stack<CCMutableArray<CCObject*>*> m_tArrayStack;
std::stack<CCSAXState> m_tStateStack;
public:
CCDictMaker()
: m_pRootDict(NULL),
m_pCurDict(NULL),
m_tState(SAX_NONE),
m_pArray(NULL)
{
}
~CCDictMaker()
{
}
CCDictionary<std::string, CCObject*> *dictionaryWithContentsOfFile(const char *pFileName)
{
CCSAXParser parser;
if (false == parser.init("UTF-8"))
{
return NULL;
}
parser.setDelegator(this);
parser.parse(pFileName);
return m_pRootDict;
}
void startElement(void *ctx, const char *name, const char **atts)
{
CC_UNUSED_PARAM(ctx);
CC_UNUSED_PARAM(atts);
std::string sName((char*)name);
if( sName == "dict" )
{
m_pCurDict = new CCDictionary<std::string, CCObject*>();
if(! m_pRootDict)
{
// Because it will call m_pCurDict->release() later, so retain here.
m_pRootDict = m_pCurDict;
m_pRootDict->retain();
}
m_tState = SAX_DICT;
CCSAXState preState = SAX_NONE;
if (! m_tStateStack.empty())
{
preState = m_tStateStack.top();
}
if (SAX_ARRAY == preState)
{
// add the dictionary into the array
m_pArray->addObject(m_pCurDict);
}
else if (SAX_DICT == preState)
{
// add the dictionary into the pre dictionary
CCAssert(! m_tDictStack.empty(), "The state is wrong!");
CCDictionary<std::string, CCObject*>* pPreDict = m_tDictStack.top();
pPreDict->setObject(m_pCurDict, m_sCurKey);
}
m_pCurDict->release();
// record the dict state
m_tStateStack.push(m_tState);
m_tDictStack.push(m_pCurDict);
}
else if(sName == "key")
{
m_tState = SAX_KEY;
}
else if(sName == "integer")
{
m_tState = SAX_INT;
}
else if(sName == "real")
{
m_tState = SAX_REAL;
}
else if(sName == "string")
{
m_tState = SAX_STRING;
}
else if (sName == "array")
{
m_tState = SAX_ARRAY;
m_pArray = new CCMutableArray<CCObject*>();
CCSAXState preState = m_tStateStack.empty() ? SAX_DICT : m_tStateStack.top();
if (preState == SAX_DICT)
{
m_pCurDict->setObject(m_pArray, m_sCurKey);
}
else if (preState == SAX_ARRAY)
{
CCAssert(! m_tArrayStack.empty(), "The state is worng!");
CCMutableArray<CCObject*>* pPreArray = m_tArrayStack.top();
pPreArray->addObject(m_pArray);
}
m_pArray->release();
// record the array state
m_tStateStack.push(m_tState);
m_tArrayStack.push(m_pArray);
}
else
{
m_tState = SAX_NONE;
}
}
void endElement(void *ctx, const char *name)
{
CC_UNUSED_PARAM(ctx);
CCSAXState curState = m_tStateStack.empty() ? SAX_DICT : m_tStateStack.top();
std::string sName((char*)name);
if( sName == "dict" )
{
m_tStateStack.pop();
m_tDictStack.pop();
if ( !m_tDictStack.empty())
{
m_pCurDict = m_tDictStack.top();
}
}
else if (sName == "array")
{
m_tStateStack.pop();
m_tArrayStack.pop();
if (! m_tArrayStack.empty())
{
m_pArray = m_tArrayStack.top();
}
}
else if (sName == "true")
{
CCString *str = new CCString("1");
if (SAX_ARRAY == curState)
{
m_pArray->addObject(str);
}
else if (SAX_DICT == curState)
{
m_pCurDict->setObject(str, m_sCurKey);
}
str->release();
}
else if (sName == "false")
{
CCString *str = new CCString("0");
if (SAX_ARRAY == curState)
{
m_pArray->addObject(str);
}
else if (SAX_DICT == curState)
{
m_pCurDict->setObject(str, m_sCurKey);
}
str->release();
}
m_tState = SAX_NONE;
}
void textHandler(void *ctx, const char *ch, int len)
{
CC_UNUSED_PARAM(ctx);
if (m_tState == SAX_NONE)
{
return;
}
CCSAXState curState = m_tStateStack.empty() ? SAX_DICT : m_tStateStack.top();
CCString *pText = new CCString();
pText->m_sString = std::string((char*)ch,0,len);
switch(m_tState)
{
case SAX_KEY:
m_sCurKey = pText->m_sString;
break;
case SAX_INT:
case SAX_REAL:
case SAX_STRING:
{
CCAssert(!m_sCurKey.empty(), "not found key : <integet/real>");
if (SAX_ARRAY == curState)
{
m_pArray->addObject(pText);
}
else if (SAX_DICT == curState)
{
m_pCurDict->setObject(pText, m_sCurKey);
}
break;
}
default:
break;
}
pText->release();
}
};
std::string& CCFileUtils::ccRemoveHDSuffixFromFile(std::string& path)
{
#if CC_IS_RETINA_DISPLAY_SUPPORTED
if( CC_CONTENT_SCALE_FACTOR() == 2 )
{
std::string::size_type pos = path.rfind("/") + 1; // the begin index of last part of path
std::string::size_type suffixPos = path.rfind(CC_RETINA_DISPLAY_FILENAME_SUFFIX);
if (std::string::npos != suffixPos && suffixPos > pos)
{
CCLog("cocos2d: FilePath(%s) contains suffix(%s), remove it.", path.c_str(),
CC_RETINA_DISPLAY_FILENAME_SUFFIX);
path.replace(suffixPos, strlen(CC_RETINA_DISPLAY_FILENAME_SUFFIX), "");
}
}
#endif // CC_IS_RETINA_DISPLAY_SUPPORTED
return path;
}
CCDictionary<std::string, CCObject*> *CCFileUtils::dictionaryWithContentsOfFile(const char *pFileName)
{
CCDictionary<std::string, CCObject*> *ret = dictionaryWithContentsOfFileThreadSafe(pFileName);
ret->autorelease();
return ret;
}
CCDictionary<std::string, CCObject*> *CCFileUtils::dictionaryWithContentsOfFileThreadSafe(const char *pFileName)
{
CCDictMaker tMaker;
return tMaker.dictionaryWithContentsOfFile(pFileName);
}
unsigned char* CCFileUtils::getFileDataFromZip(const char* pszZipFilePath, const char* pszFileName, unsigned long * pSize)
{
unsigned char * pBuffer = NULL;
unzFile pFile = NULL;
*pSize = 0;
do
{
CC_BREAK_IF(!pszZipFilePath || !pszFileName);
CC_BREAK_IF(strlen(pszZipFilePath) == 0);
pFile = unzOpen(pszZipFilePath);
CC_BREAK_IF(!pFile);
int nRet = unzLocateFile(pFile, pszFileName, 1);
CC_BREAK_IF(UNZ_OK != nRet);
char szFilePathA[260];
unz_file_info FileInfo;
nRet = unzGetCurrentFileInfo(pFile, &FileInfo, szFilePathA, sizeof(szFilePathA), NULL, 0, NULL, 0);
CC_BREAK_IF(UNZ_OK != nRet);
nRet = unzOpenCurrentFile(pFile);
CC_BREAK_IF(UNZ_OK != nRet);
pBuffer = new unsigned char[FileInfo.uncompressed_size];
int nSize = 0;
nSize = unzReadCurrentFile(pFile, pBuffer, FileInfo.uncompressed_size);
CCAssert(nSize == 0 || nSize == (int)FileInfo.uncompressed_size, "the file size is wrong");
*pSize = FileInfo.uncompressed_size;
unzCloseCurrentFile(pFile);
} while (0);
if (pFile)
{
unzClose(pFile);
}
return pBuffer;
}
//////////////////////////////////////////////////////////////////////////
// Notification support when getFileData from invalid file path.
//////////////////////////////////////////////////////////////////////////
static bool s_bPopupNotify = true;
void CCFileUtils::setIsPopupNotify(bool bNotify)
{
s_bPopupNotify = bNotify;
}
bool CCFileUtils::getIsPopupNotify()
{
return s_bPopupNotify;
}
NS_CC_END;
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WIN32)
#include "win32/CCFileUtils_win32.cpp"
#endif
#if (CC_TARGET_PLATFORM == CC_PLATFORM_WOPHONE)
#include "wophone/CCFileUtils_wophone.cpp"
#endif
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)
#include "android/CCFileUtils_android.cpp"
#endif
#if (CC_TARGET_PLATFORM == CC_PLATFORM_BADA)
#include "bada/CCFileUtils_bada.cpp"
#endif
#endif // (CC_TARGET_PLATFORM != CC_PLATFORM_IOS && CC_TARGET_PLATFORM != CC_PLATFORM_AIRPLAY)
| mit |
nonconforme/AtomicGameEngine | Source/ThirdParty/TurboBadger/tb_scroller.cpp | 2 | 12331 | // ================================================================================
// == This file is a part of Turbo Badger. (C) 2011-2014, Emil Segerås ==
// == See tb_core.h for more information. ==
// ================================================================================
#include "tb_scroller.h"
#include "tb_widgets.h"
#include "tb_system.h"
#include <math.h>
namespace tb {
// == Misc constants ====================================================================
#define PAN_TARGET_FPS 60
#define PAN_MSG_DELAY_MS ((double)(1000.0 / PAN_TARGET_FPS))
#define PAN_START_THRESHOLD_MS 50
#define PAN_POWER_ACC_THRESHOLD_MS 600
#define PAN_POWER_MULTIPLIER 1.3f
#define SCROLL_DECAY 200.0f
#define SF_GATE_THRESHOLD 0.01f
// == TBScrollerFunction ================================================================
// Lab: http://www.madtealab.com/?V=1&C=6&F=5&G=1&O=1&W=774&GW=720&GH=252&GX=13.389616776278201&GY=4.790704772336853&GS=0.13102127484993598&EH=189&a=3.6666666666666665&aMa=20&aN=OrgSpeed&bMa=3&bN=CurPos&c=8&cMa=60&cI=1&cN=FrameRate&d=16&dMa=16&dI=1&dN=numSimulatedSeconds&l=2.388888888888889&lMa=5&lN=Decay&m=0.1&mMa=0.1&mN=GateThreshold&f1=OrgSpeed+%2A+exp%28-x+%2F+Decay%29&f1N=Speed&f2=CurPos+%2B+OrgSpeed+%2A+%281-exp%28-x+%2F+Decay%29%29%2A+Decay&f2N=Pos&f3=marker%28x%2C+predictGatedPoint%29&f3N=GatePoint&f4=aToF%28simulatedPoints%2Cnearest%2C0%2CnumSimulatedSeconds%29%28x%29&f4N=Iterated&f5=OrgSpeed+%2A+x&f5N=Linear1&Expr=%0ApredictGatedPoint+%3D+-log%28GateThreshold+%2F+%28OrgSpeed%29%29+%2A+Decay%0A%0Avar+cur+%3D+OrgSpeed%0AsimulatedPoints+%3D+sample%28function%28%29+%7B%0A+++cur+%3D+cur+%2A+%281+-+0.05%29%3B%0A+++return+cur%0A+%7D%2C+%5BnumSimulatedSeconds+%2A+FrameRate%5D%29%3B%0A%0ApredictGatedPoint
float TBScrollerFunction::GetDurationFromSpeed(float start_speed)
{
float abs_start_speed = ABS(start_speed);
if (abs_start_speed <= SF_GATE_THRESHOLD)
return 0;
return -log(SF_GATE_THRESHOLD / abs_start_speed) * m_decay;
}
float TBScrollerFunction::GetSpeedFromDistance(float distance)
{
float speed = distance / m_decay;
if (distance > SF_GATE_THRESHOLD)
return speed + SF_GATE_THRESHOLD;
else if (distance < -SF_GATE_THRESHOLD)
return speed - SF_GATE_THRESHOLD;
return speed;
}
float TBScrollerFunction::GetDistanceAtTime(float start_speed, float elapsed_time_ms)
{
assert(elapsed_time_ms >= 0);
return start_speed * (1 - exp(-elapsed_time_ms / m_decay)) * m_decay;
}
int TBScrollerFunction::GetDistanceAtTimeInt(float start_speed, float elapsed_time_ms)
{
float distance = GetDistanceAtTime(start_speed, elapsed_time_ms);
return (int)(distance < 0 ? distance - 0.5f : distance + 0.5f);
}
// == TBScroller ========================================================================
TBScroller::TBScroller(TBWidget *target)
: m_target(target)
, m_snap_listener(nullptr)
, m_func(SCROLL_DECAY)
, m_previous_pan_dx(0)
, m_previous_pan_dy(0)
, m_scroll_start_ms(0)
, m_scroll_duration_x_ms(0)
, m_scroll_duration_y_ms(0)
, m_pan_power_multiplier_x(1)
, m_pan_power_multiplier_y(1)
{
Reset();
}
TBScroller::~TBScroller()
{
}
void TBScroller::Reset()
{
m_is_started = false;
m_pan_dx = m_pan_dy = 0;
m_pan_time_ms = 0;
m_pan_delta_time_ms = 0;
m_scroll_start_speed_ppms_x = m_scroll_start_speed_ppms_y = 0;
m_scroll_start_scroll_x = m_scroll_start_scroll_y = 0;
// don't reset m_previous_pan_dx and m_previous_pan_dy here.
// don't reset m_pan_power here. It's done on start since it's needed for next pan!
m_expected_scroll_x = m_expected_scroll_y = 0;
}
void TBScroller::OnScrollBy(int dx, int dy, bool accumulative)
{
if (!IsStarted())
Start();
float ppms_x = m_func.GetSpeedFromDistance((float)dx);
float ppms_y = m_func.GetSpeedFromDistance((float)dy);
if (accumulative && IsScrolling())
{
TBWidget::ScrollInfo info = m_target->GetScrollInfo();
// If new direction is the same as the current direction,
// calculate the speed needed for the remaining part and
// add that to the new scroll speed.
if ((ppms_x < 0) == (m_scroll_start_speed_ppms_x < 0))
{
int distance_x = m_func.GetDistanceAtTimeInt(m_scroll_start_speed_ppms_x,
m_func.GetDurationFromSpeed(m_scroll_start_speed_ppms_x));
int distance_remaining_x = m_scroll_start_scroll_x + distance_x - info.x;
distance_remaining_x += m_func.GetDistanceAtTimeInt(ppms_x, m_func.GetDurationFromSpeed(ppms_x));
ppms_x = m_func.GetSpeedFromDistance((float)distance_remaining_x);
}
if ((ppms_y < 0) == (m_scroll_start_speed_ppms_y < 0))
{
int distance_y = m_func.GetDistanceAtTimeInt(m_scroll_start_speed_ppms_y,
m_func.GetDurationFromSpeed(m_scroll_start_speed_ppms_y));
int distance_remaining_y = m_scroll_start_scroll_y + distance_y - info.y;
distance_remaining_y += m_func.GetDistanceAtTimeInt(ppms_y, m_func.GetDurationFromSpeed(ppms_y));
ppms_y = m_func.GetSpeedFromDistance((float)distance_remaining_y);
}
}
AdjustToSnappingAndScroll(ppms_x, ppms_y);
}
bool TBScroller::OnPan(int dx, int dy)
{
if (!IsStarted())
Start();
// Pan the target
const int in_dx = dx, in_dy = dy;
m_target->ScrollByRecursive(dx, dy);
// Calculate the pan speed. Smooth it out with the
// previous pan speed to reduce fluctuation a little.
double now_ms = TBSystem::GetTimeMS();
if (m_pan_time_ms)
{
if (m_pan_delta_time_ms)
m_pan_delta_time_ms = (now_ms - m_pan_time_ms + m_pan_delta_time_ms) / 2.0f;
else
m_pan_delta_time_ms = now_ms - m_pan_time_ms;
}
m_pan_time_ms = now_ms;
m_pan_dx = (m_pan_dx + in_dx) / 2.0f;
m_pan_dy = (m_pan_dy + in_dy) / 2.0f;
// If we change direction, reset the pan power multiplier in that axis.
if (m_pan_dx != 0 && (m_previous_pan_dx < 0) != (m_pan_dx < 0))
m_pan_power_multiplier_x = 1;
if (m_pan_dy != 0 && (m_previous_pan_dy < 0) != (m_pan_dy < 0))
m_pan_power_multiplier_y = 1;
m_previous_pan_dx = m_pan_dx;
m_previous_pan_dy = m_pan_dy;
return in_dx != dx || in_dy != dy;
}
void TBScroller::OnPanReleased()
{
if (TBSystem::GetTimeMS() < m_pan_time_ms + PAN_START_THRESHOLD_MS)
{
// Don't start scroll if we have too little speed.
// This will prevent us from scrolling accidently.
float pan_start_distance_threshold_px = 2 * TBSystem::GetDPI() / 100.0f;
if (ABS(m_pan_dx) < pan_start_distance_threshold_px && ABS(m_pan_dy) < pan_start_distance_threshold_px)
{
StopOrSnapScroll();
return;
}
if (m_pan_delta_time_ms == 0)
{
StopOrSnapScroll();
return;
}
float ppms_x = (float)m_pan_dx / (float)m_pan_delta_time_ms;
float ppms_y = (float)m_pan_dy / (float)m_pan_delta_time_ms;
ppms_x *= m_pan_power_multiplier_x;
ppms_y *= m_pan_power_multiplier_y;
AdjustToSnappingAndScroll(ppms_x, ppms_y);
}
else
StopOrSnapScroll();
}
void TBScroller::Start()
{
if (IsStarted())
return;
m_is_started = true;
double now_ms = TBSystem::GetTimeMS();
if (now_ms < m_scroll_start_ms + PAN_POWER_ACC_THRESHOLD_MS)
{
m_pan_power_multiplier_x *= PAN_POWER_MULTIPLIER;
m_pan_power_multiplier_y *= PAN_POWER_MULTIPLIER;
}
else
{
m_pan_power_multiplier_x = m_pan_power_multiplier_y = 1;
}
}
void TBScroller::Stop()
{
DeleteAllMessages();
Reset();
}
bool TBScroller::StopIfAlmostStill()
{
double now_ms = TBSystem::GetTimeMS();
if (now_ms > m_scroll_start_ms + (double)m_scroll_duration_x_ms &&
now_ms > m_scroll_start_ms + (double)m_scroll_duration_y_ms)
{
Stop();
return true;
}
return false;
}
void TBScroller::StopOrSnapScroll()
{
AdjustToSnappingAndScroll(0, 0);
if (!IsScrolling())
Stop();
}
void TBScroller::AdjustToSnappingAndScroll(float ppms_x, float ppms_y)
{
if (m_snap_listener)
{
// Calculate the distance
int distance_x = m_func.GetDistanceAtTimeInt(ppms_x, m_func.GetDurationFromSpeed(ppms_x));
int distance_y = m_func.GetDistanceAtTimeInt(ppms_y, m_func.GetDurationFromSpeed(ppms_y));
// Let the snap listener modify the distance
TBWidget::ScrollInfo info = m_target->GetScrollInfo();
int target_x = distance_x + info.x;
int target_y = distance_y + info.y;
m_snap_listener->OnScrollSnap(m_target, target_x, target_y);
distance_x = target_x - info.x;
distance_y = target_y - info.y;
// Get the start speed from the new distance
ppms_x = m_func.GetSpeedFromDistance((float)distance_x);
ppms_y = m_func.GetSpeedFromDistance((float)distance_y);
}
Scroll(ppms_x, ppms_y);
}
void TBScroller::Scroll(float start_speed_ppms_x, float start_speed_ppms_y)
{
// Set start values
m_scroll_start_ms = TBSystem::GetTimeMS();
GetTargetScrollXY(m_scroll_start_scroll_x, m_scroll_start_scroll_y);
m_scroll_start_speed_ppms_x = start_speed_ppms_x;
m_scroll_start_speed_ppms_y = start_speed_ppms_y;
// Calculate duration for the scroll (each axis independently)
m_scroll_duration_x_ms = m_func.GetDurationFromSpeed(m_scroll_start_speed_ppms_x);
m_scroll_duration_y_ms = m_func.GetDurationFromSpeed(m_scroll_start_speed_ppms_y);
if (StopIfAlmostStill())
return;
// Post the pan message if we don't already have one
if (!GetMessageByID(TBIDC("scroll")))
{
// Update expected translation
GetTargetChildTranslation(m_expected_scroll_x, m_expected_scroll_y);
PostMessageDelayed(TBIDC("scroll"), nullptr, (uint32)PAN_MSG_DELAY_MS);
}
}
bool TBScroller::IsScrolling()
{
return GetMessageByID(TBIDC("scroll")) ? true : false;
}
void TBScroller::GetTargetChildTranslation(int &x, int &y) const
{
int root_x = 0, root_y = 0;
int child_translation_x = 0, child_translation_y = 0;
TBWidget *scroll_root = m_target->GetScrollRoot();
scroll_root->ConvertToRoot(root_x, root_y);
scroll_root->GetChildTranslation(child_translation_x, child_translation_y);
x = root_x + child_translation_x;
y = root_y + child_translation_y;
}
void TBScroller::GetTargetScrollXY(int &x, int &y) const
{
x = 0;
y = 0;
TBWidget *tmp = m_target->GetScrollRoot();
while (tmp)
{
TBWidget::ScrollInfo info = tmp->GetScrollInfo();
x += info.x;
y += info.y;
tmp = tmp->GetParent();
}
}
void TBScroller::OnMessageReceived(TBMessage *msg)
{
if (msg->message == TBIDC("scroll"))
{
int actual_scroll_x = 0, actual_scroll_y = 0;
GetTargetChildTranslation(actual_scroll_x, actual_scroll_y);
if (actual_scroll_x != m_expected_scroll_x ||
actual_scroll_y != m_expected_scroll_y)
{
// Something else has affected the target child translation.
// This should abort the scroll.
// This could happen f.ex if something shrunk the scroll limits,
// some other action changed scroll position, or if another
// scroller started operating on a sub child that when reacing
// its scroll limit, started scrolling its chain of parents.
Stop();
return;
}
// Calculate the time elapsed from scroll start. Clip within the
// duration for each axis.
double now_ms = TBSystem::GetTimeMS();
float elapsed_time_x = (float)(now_ms - m_scroll_start_ms);
float elapsed_time_y = elapsed_time_x;
elapsed_time_x = MIN(elapsed_time_x, m_scroll_duration_x_ms);
elapsed_time_y = MIN(elapsed_time_y, m_scroll_duration_y_ms);
// Get the new scroll position from the current distance in each axis.
int scroll_x = m_func.GetDistanceAtTimeInt(m_scroll_start_speed_ppms_x, elapsed_time_x);
int scroll_y = m_func.GetDistanceAtTimeInt(m_scroll_start_speed_ppms_y, elapsed_time_y);
scroll_x += m_scroll_start_scroll_x;
scroll_y += m_scroll_start_scroll_y;
// Get the scroll delta and invoke ScrollByRecursive.
int curr_scroll_x, curr_scroll_y;
GetTargetScrollXY(curr_scroll_x, curr_scroll_y);
const int dx = scroll_x - curr_scroll_x;
const int dy = scroll_y - curr_scroll_y;
int idx = dx, idy = dy;
m_target->ScrollByRecursive(idx, idy);
// Update expected translation
GetTargetChildTranslation(m_expected_scroll_x, m_expected_scroll_y);
if ((dx && actual_scroll_x == m_expected_scroll_x) &&
(dy && actual_scroll_y == m_expected_scroll_y))
{
// We didn't get anywhere despite we tried,
// so we're done (reached the end).
Stop();
return;
}
if (!StopIfAlmostStill())
{
double next_fire_time = msg->GetFireTime() + PAN_MSG_DELAY_MS;
// avoid timer catch-up if program went sleeping for a while.
next_fire_time = MAX(next_fire_time, now_ms);
PostMessageOnTime(TBIDC("scroll"), nullptr, next_fire_time);
}
}
}
}; // namespace tb
| mit |
lggomez/dedupify | src/External/ImageMagick/include/MagickCore/widget.c | 2 | 328311 | /*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% %
% W W IIIII DDDD GGGG EEEEE TTTTT %
% W W I D D G E T %
% W W W I D D G GG EEE T %
% WW WW I D D G G E T %
% W W IIIII DDDD GGGG EEEEE T %
% %
% %
% MagickCore X11 User Interface Methods %
% %
% Software Design %
% Cristy %
% September 1993 %
% %
% %
% Copyright 1999-2017 ImageMagick Studio LLC, a non-profit organization %
% dedicated to making software imaging solutions freely available. %
% %
% You may not use this file except in compliance with the License. You may %
% obtain a copy of the License at %
% %
% https://www.imagemagick.org/script/license.php %
% %
% Unless required by applicable law or agreed to in writing, software %
% distributed under the License is distributed on an "AS IS" BASIS, %
% WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. %
% See the License for the specific language governing permissions and %
% limitations under the License. %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
%
*/
/*
Include declarations.
*/
#include "MagickCore/studio.h"
#include "MagickCore/color.h"
#include "MagickCore/color-private.h"
#include "MagickCore/exception.h"
#include "MagickCore/exception-private.h"
#include "MagickCore/image.h"
#include "MagickCore/magick.h"
#include "MagickCore/memory_.h"
#include "MagickCore/string_.h"
#include "MagickCore/token.h"
#include "MagickCore/token-private.h"
#include "MagickCore/utility.h"
#include "MagickCore/utility-private.h"
#include "MagickCore/xwindow-private.h"
#include "MagickCore/widget.h"
#include "MagickCore/widget-private.h"
#if defined(MAGICKCORE_X11_DELEGATE)
/*
Define declarations.
*/
#define AreaIsActive(matte_info,position) ( \
((position.y >= (int) (matte_info.y-matte_info.bevel_width)) && \
(position.y < (int) (matte_info.y+matte_info.height+matte_info.bevel_width))) \
? MagickTrue : MagickFalse)
#define Extent(s) ((int) strlen(s))
#define MatteIsActive(matte_info,position) ( \
((position.x >= (int) (matte_info.x-matte_info.bevel_width)) && \
(position.y >= (int) (matte_info.y-matte_info.bevel_width)) && \
(position.x < (int) (matte_info.x+matte_info.width+matte_info.bevel_width)) && \
(position.y < (int) (matte_info.y+matte_info.height+matte_info.bevel_width))) \
? MagickTrue : MagickFalse)
#define MaxTextWidth ((unsigned int) (255*XTextWidth(font_info,"_",1)))
#define MinTextWidth (26*XTextWidth(font_info,"_",1))
#define QuantumMargin MagickMax(font_info->max_bounds.width,12)
#define WidgetTextWidth(font_info,text) \
((unsigned int) XTextWidth(font_info,text,Extent(text)))
#define WindowIsActive(window_info,position) ( \
((position.x >= 0) && (position.y >= 0) && \
(position.x < (int) window_info.width) && \
(position.y < (int) window_info.height)) ? MagickTrue : MagickFalse)
/*
Enum declarations.
*/
typedef enum
{
ControlState = 0x0001,
InactiveWidgetState = 0x0004,
JumpListState = 0x0008,
RedrawActionState = 0x0010,
RedrawListState = 0x0020,
RedrawWidgetState = 0x0040,
UpdateListState = 0x0100
} WidgetState;
/*
Typedef declarations.
*/
typedef struct _XWidgetInfo
{
char
*cursor,
*text,
*marker;
int
id;
unsigned int
bevel_width,
width,
height;
int
x,
y,
min_y,
max_y;
MagickStatusType
raised,
active,
center,
trough,
highlight;
} XWidgetInfo;
/*
Variable declarations.
*/
static XWidgetInfo
monitor_info =
{
(char *) NULL, (char *) NULL, (char *) NULL, 0, 0, 0, 0, 0, 0, 0, 0,
MagickFalse, MagickFalse, MagickFalse, MagickFalse, MagickFalse
},
submenu_info =
{
(char *) NULL, (char *) NULL, (char *) NULL, 0, 0, 0, 0, 0, 0, 0, 0,
MagickFalse, MagickFalse, MagickFalse, MagickFalse, MagickFalse
},
*selection_info = (XWidgetInfo *) NULL,
toggle_info =
{
(char *) NULL, (char *) NULL, (char *) NULL, 0, 0, 0, 0, 0, 0, 0, 0,
MagickFalse, MagickFalse, MagickFalse, MagickFalse, MagickFalse
};
/*
Constant declarations.
*/
static const int
BorderOffset = 4,
DoubleClick = 250;
/*
Method prototypes.
*/
static void
XDrawMatte(Display *,const XWindowInfo *,const XWidgetInfo *),
XSetBevelColor(Display *,const XWindowInfo *,const MagickStatusType),
XSetMatteColor(Display *,const XWindowInfo *,const MagickStatusType),
XSetTextColor(Display *,const XWindowInfo *,const MagickStatusType);
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% D e s t r o y X W i d g e t %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% DestroyXWidget() destroys resources associated with the X widget.
%
% The format of the DestroyXWidget method is:
%
% void DestroyXWidget()
%
% A description of each parameter follows:
%
*/
MagickPrivate void DestroyXWidget(void)
{
if (selection_info != (XWidgetInfo *) NULL)
selection_info=(XWidgetInfo *) RelinquishMagickMemory(selection_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ X D r a w B e v e l %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% XDrawBevel() "sets off" an area with a highlighted upper and left bevel and
% a shadowed lower and right bevel. The highlighted and shadowed bevels
% create a 3-D effect.
%
% The format of the XDrawBevel function is:
%
% XDrawBevel(display,window_info,bevel_info)
%
% A description of each parameter follows:
%
% o display: Specifies a pointer to the Display structure; returned from
% XOpenDisplay.
%
% o window_info: Specifies a pointer to a X11 XWindowInfo structure.
%
% o bevel_info: Specifies a pointer to a XWidgetInfo structure. It
% contains the extents of the bevel.
%
*/
static void XDrawBevel(Display *display,const XWindowInfo *window_info,
const XWidgetInfo *bevel_info)
{
int
x1,
x2,
y1,
y2;
unsigned int
bevel_width;
XPoint
points[6];
/*
Draw upper and left beveled border.
*/
x1=bevel_info->x;
y1=bevel_info->y+bevel_info->height;
x2=bevel_info->x+bevel_info->width;
y2=bevel_info->y;
bevel_width=bevel_info->bevel_width;
points[0].x=x1;
points[0].y=y1;
points[1].x=x1;
points[1].y=y2;
points[2].x=x2;
points[2].y=y2;
points[3].x=x2+bevel_width;
points[3].y=y2-bevel_width;
points[4].x=x1-bevel_width;
points[4].y=y2-bevel_width;
points[5].x=x1-bevel_width;
points[5].y=y1+bevel_width;
XSetBevelColor(display,window_info,bevel_info->raised);
(void) XFillPolygon(display,window_info->id,window_info->widget_context,
points,6,Complex,CoordModeOrigin);
/*
Draw lower and right beveled border.
*/
points[0].x=x1;
points[0].y=y1;
points[1].x=x2;
points[1].y=y1;
points[2].x=x2;
points[2].y=y2;
points[3].x=x2+bevel_width;
points[3].y=y2-bevel_width;
points[4].x=x2+bevel_width;
points[4].y=y1+bevel_width;
points[5].x=x1-bevel_width;
points[5].y=y1+bevel_width;
XSetBevelColor(display,window_info,!bevel_info->raised);
(void) XFillPolygon(display,window_info->id,window_info->widget_context,
points,6,Complex,CoordModeOrigin);
(void) XSetFillStyle(display,window_info->widget_context,FillSolid);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ X D r a w B e v e l e d B u t t o n %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% XDrawBeveledButton() draws a button with a highlighted upper and left bevel
% and a shadowed lower and right bevel. The highlighted and shadowed bevels
% create a 3-D effect.
%
% The format of the XDrawBeveledButton function is:
%
% XDrawBeveledButton(display,window_info,button_info)
%
% A description of each parameter follows:
%
% o display: Specifies a pointer to the Display structure; returned from
% XOpenDisplay.
%
% o window_info: Specifies a pointer to a X11 XWindowInfo structure.
%
% o button_info: Specifies a pointer to a XWidgetInfo structure. It
% contains the extents of the button.
%
*/
static void XDrawBeveledButton(Display *display,const XWindowInfo *window_info,
const XWidgetInfo *button_info)
{
int
x,
y;
unsigned int
width;
XFontStruct
*font_info;
XRectangle
crop_info;
/*
Draw matte.
*/
XDrawBevel(display,window_info,button_info);
XSetMatteColor(display,window_info,button_info->raised);
(void) XFillRectangle(display,window_info->id,window_info->widget_context,
button_info->x,button_info->y,button_info->width,button_info->height);
x=button_info->x-button_info->bevel_width-1;
y=button_info->y-button_info->bevel_width-1;
(void) XSetForeground(display,window_info->widget_context,
window_info->pixel_info->trough_color.pixel);
if (button_info->raised || (window_info->depth == 1))
(void) XDrawRectangle(display,window_info->id,window_info->widget_context,
x,y,button_info->width+(button_info->bevel_width << 1)+1,
button_info->height+(button_info->bevel_width << 1)+1);
if (button_info->text == (char *) NULL)
return;
/*
Set cropping region.
*/
crop_info.width=(unsigned short) button_info->width;
crop_info.height=(unsigned short) button_info->height;
crop_info.x=button_info->x;
crop_info.y=button_info->y;
/*
Draw text.
*/
font_info=window_info->font_info;
width=WidgetTextWidth(font_info,button_info->text);
x=button_info->x+(QuantumMargin >> 1);
if (button_info->center)
x=button_info->x+(button_info->width >> 1)-(width >> 1);
y=button_info->y+((button_info->height-
(font_info->ascent+font_info->descent)) >> 1)+font_info->ascent;
if ((int) button_info->width == (QuantumMargin >> 1))
{
/*
Option button-- write label to right of button.
*/
XSetTextColor(display,window_info,MagickTrue);
x=button_info->x+button_info->width+button_info->bevel_width+
(QuantumMargin >> 1);
(void) XDrawString(display,window_info->id,window_info->widget_context,
x,y,button_info->text,Extent(button_info->text));
return;
}
(void) XSetClipRectangles(display,window_info->widget_context,0,0,&crop_info,
1,Unsorted);
XSetTextColor(display,window_info,button_info->raised);
(void) XDrawString(display,window_info->id,window_info->widget_context,x,y,
button_info->text,Extent(button_info->text));
(void) XSetClipMask(display,window_info->widget_context,None);
if (button_info->raised == MagickFalse)
XDelay(display,SuspendTime << 2);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ X D r a w B e v e l e d M a t t e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% XDrawBeveledMatte() draws a matte with a shadowed upper and left bevel and
% a highlighted lower and right bevel. The highlighted and shadowed bevels
% create a 3-D effect.
%
% The format of the XDrawBeveledMatte function is:
%
% XDrawBeveledMatte(display,window_info,matte_info)
%
% A description of each parameter follows:
%
% o display: Specifies a pointer to the Display structure; returned from
% XOpenDisplay.
%
% o window_info: Specifies a pointer to a X11 XWindowInfo structure.
%
% o matte_info: Specifies a pointer to a XWidgetInfo structure. It
% contains the extents of the matte.
%
*/
static void XDrawBeveledMatte(Display *display,const XWindowInfo *window_info,
const XWidgetInfo *matte_info)
{
/*
Draw matte.
*/
XDrawBevel(display,window_info,matte_info);
XDrawMatte(display,window_info,matte_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ X D r a w M a t t e %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% XDrawMatte() fills a rectangular area with the matte color.
%
% The format of the XDrawMatte function is:
%
% XDrawMatte(display,window_info,matte_info)
%
% A description of each parameter follows:
%
% o display: Specifies a pointer to the Display structure; returned from
% XOpenDisplay.
%
% o window_info: Specifies a pointer to a X11 XWindowInfo structure.
%
% o matte_info: Specifies a pointer to a XWidgetInfo structure. It
% contains the extents of the matte.
%
*/
static void XDrawMatte(Display *display,const XWindowInfo *window_info,
const XWidgetInfo *matte_info)
{
/*
Draw matte.
*/
if ((matte_info->trough == MagickFalse) || (window_info->depth == 1))
(void) XFillRectangle(display,window_info->id,
window_info->highlight_context,matte_info->x,matte_info->y,
matte_info->width,matte_info->height);
else
{
(void) XSetForeground(display,window_info->widget_context,
window_info->pixel_info->trough_color.pixel);
(void) XFillRectangle(display,window_info->id,window_info->widget_context,
matte_info->x,matte_info->y,matte_info->width,matte_info->height);
}
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ X D r a w M a t t e T e x t %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% XDrawMatteText() draws a matte with text. If the text exceeds the extents
% of the text, a portion of the text relative to the cursor is displayed.
%
% The format of the XDrawMatteText function is:
%
% XDrawMatteText(display,window_info,text_info)
%
% A description of each parameter follows:
%
% o display: Specifies a pointer to the Display structure; returned from
% XOpenDisplay.
%
% o window_info: Specifies a pointer to a X11 XWindowInfo structure.
%
% o text_info: Specifies a pointer to a XWidgetInfo structure. It
% contains the extents of the text.
%
*/
static void XDrawMatteText(Display *display,const XWindowInfo *window_info,
XWidgetInfo *text_info)
{
const char
*text;
int
n,
x,
y;
register int
i;
unsigned int
height,
width;
XFontStruct
*font_info;
XRectangle
crop_info;
/*
Clear the text area.
*/
XSetMatteColor(display,window_info,MagickFalse);
(void) XFillRectangle(display,window_info->id,window_info->widget_context,
text_info->x,text_info->y,text_info->width,text_info->height);
if (text_info->text == (char *) NULL)
return;
XSetTextColor(display,window_info,text_info->highlight);
font_info=window_info->font_info;
x=text_info->x+(QuantumMargin >> 2);
y=text_info->y+font_info->ascent+(text_info->height >> 2);
width=text_info->width-(QuantumMargin >> 1);
height=(unsigned int) (font_info->ascent+font_info->descent);
if (*text_info->text == '\0')
{
/*
No text-- just draw cursor.
*/
(void) XDrawLine(display,window_info->id,window_info->annotate_context,
x,y+3,x,y-height+3);
return;
}
/*
Set cropping region.
*/
crop_info.width=(unsigned short) text_info->width;
crop_info.height=(unsigned short) text_info->height;
crop_info.x=text_info->x;
crop_info.y=text_info->y;
/*
Determine beginning of the visible text.
*/
if (text_info->cursor < text_info->marker)
text_info->marker=text_info->cursor;
else
{
text=text_info->marker;
if (XTextWidth(font_info,(char *) text,(int) (text_info->cursor-text)) >
(int) width)
{
text=text_info->text;
for (i=0; i < Extent(text); i++)
{
n=XTextWidth(font_info,(char *) text+i,(int)
(text_info->cursor-text-i));
if (n <= (int) width)
break;
}
text_info->marker=(char *) text+i;
}
}
/*
Draw text and cursor.
*/
if (text_info->highlight == MagickFalse)
{
(void) XSetClipRectangles(display,window_info->widget_context,0,0,
&crop_info,1,Unsorted);
(void) XDrawString(display,window_info->id,window_info->widget_context,
x,y,text_info->marker,Extent(text_info->marker));
(void) XSetClipMask(display,window_info->widget_context,None);
}
else
{
(void) XSetClipRectangles(display,window_info->annotate_context,0,0,
&crop_info,1,Unsorted);
width=WidgetTextWidth(font_info,text_info->marker);
(void) XFillRectangle(display,window_info->id,
window_info->annotate_context,x,y-font_info->ascent,width,height);
(void) XSetClipMask(display,window_info->annotate_context,None);
(void) XSetClipRectangles(display,window_info->highlight_context,0,0,
&crop_info,1,Unsorted);
(void) XDrawString(display,window_info->id,
window_info->highlight_context,x,y,text_info->marker,
Extent(text_info->marker));
(void) XSetClipMask(display,window_info->highlight_context,None);
}
x+=XTextWidth(font_info,text_info->marker,(int)
(text_info->cursor-text_info->marker));
(void) XDrawLine(display,window_info->id,window_info->annotate_context,x,y+3,
x,y-height+3);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ X D r a w T r i a n g l e E a s t %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% XDrawTriangleEast() draws a triangle with a highlighted left bevel and a
% shadowed right and lower bevel. The highlighted and shadowed bevels create
% a 3-D effect.
%
% The format of the XDrawTriangleEast function is:
%
% XDrawTriangleEast(display,window_info,triangle_info)
%
% A description of each parameter follows:
%
% o display: Specifies a pointer to the Display structure; returned from
% XOpenDisplay.
%
% o window_info: Specifies a pointer to a X11 XWindowInfo structure.
%
% o triangle_info: Specifies a pointer to a XWidgetInfo structure. It
% contains the extents of the triangle.
%
*/
static void XDrawTriangleEast(Display *display,const XWindowInfo *window_info,
const XWidgetInfo *triangle_info)
{
int
x1,
x2,
x3,
y1,
y2,
y3;
unsigned int
bevel_width;
XFontStruct
*font_info;
XPoint
points[4];
/*
Draw triangle matte.
*/
x1=triangle_info->x;
y1=triangle_info->y;
x2=triangle_info->x+triangle_info->width;
y2=triangle_info->y+(triangle_info->height >> 1);
x3=triangle_info->x;
y3=triangle_info->y+triangle_info->height;
bevel_width=triangle_info->bevel_width;
points[0].x=x1;
points[0].y=y1;
points[1].x=x2;
points[1].y=y2;
points[2].x=x3;
points[2].y=y3;
XSetMatteColor(display,window_info,triangle_info->raised);
(void) XFillPolygon(display,window_info->id,window_info->widget_context,
points,3,Complex,CoordModeOrigin);
/*
Draw bottom bevel.
*/
points[0].x=x2;
points[0].y=y2;
points[1].x=x3;
points[1].y=y3;
points[2].x=x3-bevel_width;
points[2].y=y3+bevel_width;
points[3].x=x2+bevel_width;
points[3].y=y2;
XSetBevelColor(display,window_info,!triangle_info->raised);
(void) XFillPolygon(display,window_info->id,window_info->widget_context,
points,4,Complex,CoordModeOrigin);
/*
Draw Left bevel.
*/
points[0].x=x3;
points[0].y=y3;
points[1].x=x1;
points[1].y=y1;
points[2].x=x1-bevel_width+1;
points[2].y=y1-bevel_width;
points[3].x=x3-bevel_width+1;
points[3].y=y3+bevel_width;
XSetBevelColor(display,window_info,triangle_info->raised);
(void) XFillPolygon(display,window_info->id,window_info->widget_context,
points,4,Complex,CoordModeOrigin);
/*
Draw top bevel.
*/
points[0].x=x1;
points[0].y=y1;
points[1].x=x2;
points[1].y=y2;
points[2].x=x2+bevel_width;
points[2].y=y2;
points[3].x=x1-bevel_width;
points[3].y=y1-bevel_width;
(void) XFillPolygon(display,window_info->id,window_info->widget_context,
points,4,Complex,CoordModeOrigin);
(void) XSetFillStyle(display,window_info->widget_context,FillSolid);
if (triangle_info->text == (char *) NULL)
return;
/*
Write label to right of triangle.
*/
font_info=window_info->font_info;
XSetTextColor(display,window_info,MagickTrue);
x1=triangle_info->x+triangle_info->width+triangle_info->bevel_width+
(QuantumMargin >> 1);
y1=triangle_info->y+((triangle_info->height-
(font_info->ascent+font_info->descent)) >> 1)+font_info->ascent;
(void) XDrawString(display,window_info->id,window_info->widget_context,x1,y1,
triangle_info->text,Extent(triangle_info->text));
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ X D r a w T r i a n g l e N o r t h %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% XDrawTriangleNorth() draws a triangle with a highlighted left bevel and a
% shadowed right and lower bevel. The highlighted and shadowed bevels create
% a 3-D effect.
%
% The format of the XDrawTriangleNorth function is:
%
% XDrawTriangleNorth(display,window_info,triangle_info)
%
% A description of each parameter follows:
%
% o display: Specifies a pointer to the Display structure; returned from
% XOpenDisplay.
%
% o window_info: Specifies a pointer to a X11 XWindowInfo structure.
%
% o triangle_info: Specifies a pointer to a XWidgetInfo structure. It
% contains the extents of the triangle.
%
*/
static void XDrawTriangleNorth(Display *display,const XWindowInfo *window_info,
const XWidgetInfo *triangle_info)
{
int
x1,
x2,
x3,
y1,
y2,
y3;
unsigned int
bevel_width;
XPoint
points[4];
/*
Draw triangle matte.
*/
x1=triangle_info->x;
y1=triangle_info->y+triangle_info->height;
x2=triangle_info->x+(triangle_info->width >> 1);
y2=triangle_info->y;
x3=triangle_info->x+triangle_info->width;
y3=triangle_info->y+triangle_info->height;
bevel_width=triangle_info->bevel_width;
points[0].x=x1;
points[0].y=y1;
points[1].x=x2;
points[1].y=y2;
points[2].x=x3;
points[2].y=y3;
XSetMatteColor(display,window_info,triangle_info->raised);
(void) XFillPolygon(display,window_info->id,window_info->widget_context,
points,3,Complex,CoordModeOrigin);
/*
Draw left bevel.
*/
points[0].x=x1;
points[0].y=y1;
points[1].x=x2;
points[1].y=y2;
points[2].x=x2;
points[2].y=y2-bevel_width-2;
points[3].x=x1-bevel_width-1;
points[3].y=y1+bevel_width;
XSetBevelColor(display,window_info,triangle_info->raised);
(void) XFillPolygon(display,window_info->id,window_info->widget_context,
points,4,Complex,CoordModeOrigin);
/*
Draw right bevel.
*/
points[0].x=x2;
points[0].y=y2;
points[1].x=x3;
points[1].y=y3;
points[2].x=x3+bevel_width;
points[2].y=y3+bevel_width;
points[3].x=x2;
points[3].y=y2-bevel_width;
XSetBevelColor(display,window_info,!triangle_info->raised);
(void) XFillPolygon(display,window_info->id,window_info->widget_context,
points,4,Complex,CoordModeOrigin);
/*
Draw lower bevel.
*/
points[0].x=x3;
points[0].y=y3;
points[1].x=x1;
points[1].y=y1;
points[2].x=x1-bevel_width;
points[2].y=y1+bevel_width;
points[3].x=x3+bevel_width;
points[3].y=y3+bevel_width;
(void) XFillPolygon(display,window_info->id,window_info->widget_context,
points,4,Complex,CoordModeOrigin);
(void) XSetFillStyle(display,window_info->widget_context,FillSolid);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ X D r a w T r i a n g l e S o u t h %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% XDrawTriangleSouth() draws a border with a highlighted left and right bevel
% and a shadowed lower bevel. The highlighted and shadowed bevels create a
% 3-D effect.
%
% The format of the XDrawTriangleSouth function is:
%
% XDrawTriangleSouth(display,window_info,triangle_info)
%
% A description of each parameter follows:
%
% o display: Specifies a pointer to the Display structure; returned from
% XOpenDisplay.
%
% o window_info: Specifies a pointer to a X11 XWindowInfo structure.
%
% o triangle_info: Specifies a pointer to a XWidgetInfo structure. It
% contains the extents of the triangle.
%
*/
static void XDrawTriangleSouth(Display *display,const XWindowInfo *window_info,
const XWidgetInfo *triangle_info)
{
int
x1,
x2,
x3,
y1,
y2,
y3;
unsigned int
bevel_width;
XPoint
points[4];
/*
Draw triangle matte.
*/
x1=triangle_info->x;
y1=triangle_info->y;
x2=triangle_info->x+(triangle_info->width >> 1);
y2=triangle_info->y+triangle_info->height;
x3=triangle_info->x+triangle_info->width;
y3=triangle_info->y;
bevel_width=triangle_info->bevel_width;
points[0].x=x1;
points[0].y=y1;
points[1].x=x2;
points[1].y=y2;
points[2].x=x3;
points[2].y=y3;
XSetMatteColor(display,window_info,triangle_info->raised);
(void) XFillPolygon(display,window_info->id,window_info->widget_context,
points,3,Complex,CoordModeOrigin);
/*
Draw top bevel.
*/
points[0].x=x3;
points[0].y=y3;
points[1].x=x1;
points[1].y=y1;
points[2].x=x1-bevel_width;
points[2].y=y1-bevel_width;
points[3].x=x3+bevel_width;
points[3].y=y3-bevel_width;
XSetBevelColor(display,window_info,triangle_info->raised);
(void) XFillPolygon(display,window_info->id,window_info->widget_context,
points,4,Complex,CoordModeOrigin);
/*
Draw right bevel.
*/
points[0].x=x2;
points[0].y=y2;
points[1].x=x3+1;
points[1].y=y3-bevel_width;
points[2].x=x3+bevel_width;
points[2].y=y3-bevel_width;
points[3].x=x2;
points[3].y=y2+bevel_width;
XSetBevelColor(display,window_info,!triangle_info->raised);
(void) XFillPolygon(display,window_info->id,window_info->widget_context,
points,4,Complex,CoordModeOrigin);
/*
Draw left bevel.
*/
points[0].x=x1;
points[0].y=y1;
points[1].x=x2;
points[1].y=y2;
points[2].x=x2;
points[2].y=y2+bevel_width;
points[3].x=x1-bevel_width;
points[3].y=y1-bevel_width;
XSetBevelColor(display,window_info,triangle_info->raised);
(void) XFillPolygon(display,window_info->id,window_info->widget_context,
points,4,Complex,CoordModeOrigin);
(void) XSetFillStyle(display,window_info->widget_context,FillSolid);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ X D r a w W i d g e t T e x t %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% XDrawWidgetText() first clears the widget and draws a text string justifed
% left (or center) in the x-direction and centered within the y-direction.
%
% The format of the XDrawWidgetText function is:
%
% XDrawWidgetText(display,window_info,text_info)
%
% A description of each parameter follows:
%
% o display: Specifies a pointer to the Display structure; returned from
% XOpenDisplay.
%
% o window_info: Specifies a pointer to a XWindowText structure.
%
% o text_info: Specifies a pointer to XWidgetInfo structure.
%
*/
static void XDrawWidgetText(Display *display,const XWindowInfo *window_info,
XWidgetInfo *text_info)
{
GC
widget_context;
int
x,
y;
unsigned int
height,
width;
XFontStruct
*font_info;
XRectangle
crop_info;
/*
Clear the text area.
*/
widget_context=window_info->annotate_context;
if (text_info->raised)
(void) XClearArea(display,window_info->id,text_info->x,text_info->y,
text_info->width,text_info->height,MagickFalse);
else
{
(void) XFillRectangle(display,window_info->id,widget_context,text_info->x,
text_info->y,text_info->width,text_info->height);
widget_context=window_info->highlight_context;
}
if (text_info->text == (char *) NULL)
return;
if (*text_info->text == '\0')
return;
/*
Set cropping region.
*/
font_info=window_info->font_info;
crop_info.width=(unsigned short) text_info->width;
crop_info.height=(unsigned short) text_info->height;
crop_info.x=text_info->x;
crop_info.y=text_info->y;
/*
Draw text.
*/
width=WidgetTextWidth(font_info,text_info->text);
x=text_info->x+(QuantumMargin >> 1);
if (text_info->center)
x=text_info->x+(text_info->width >> 1)-(width >> 1);
if (text_info->raised)
if (width > (text_info->width-QuantumMargin))
x+=(text_info->width-QuantumMargin-width);
height=(unsigned int) (font_info->ascent+font_info->descent);
y=text_info->y+((text_info->height-height) >> 1)+font_info->ascent;
(void) XSetClipRectangles(display,widget_context,0,0,&crop_info,1,Unsorted);
(void) XDrawString(display,window_info->id,widget_context,x,y,text_info->text,
Extent(text_info->text));
(void) XSetClipMask(display,widget_context,None);
if (x < text_info->x)
(void) XDrawLine(display,window_info->id,window_info->annotate_context,
text_info->x,text_info->y,text_info->x,text_info->y+text_info->height-1);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ X E d i t T e x t %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% XEditText() edits a text string as indicated by the key symbol.
%
% The format of the XEditText function is:
%
% XEditText(display,text_info,key_symbol,text,state)
%
% A description of each parameter follows:
%
% o display: Specifies a connection to an X server; returned from
% XOpenDisplay.
%
% o text_info: Specifies a pointer to a XWidgetInfo structure. It
% contains the extents of the text.
%
% o key_symbol: A X11 KeySym that indicates what editing function to
% perform to the text.
%
% o text: A character string to insert into the text.
%
% o state: An size_t that indicates whether the key symbol is a
% control character or not.
%
*/
static void XEditText(Display *display,XWidgetInfo *text_info,
const KeySym key_symbol,char *text,const size_t state)
{
switch ((int) key_symbol)
{
case XK_BackSpace:
case XK_Delete:
{
if (text_info->highlight)
{
/*
Erase the entire line of text.
*/
*text_info->text='\0';
text_info->cursor=text_info->text;
text_info->marker=text_info->text;
text_info->highlight=MagickFalse;
}
/*
Erase one character.
*/
if (text_info->cursor != text_info->text)
{
text_info->cursor--;
(void) CopyMagickString(text_info->cursor,text_info->cursor+1,
MagickPathExtent);
text_info->highlight=MagickFalse;
break;
}
}
case XK_Left:
case XK_KP_Left:
{
/*
Move cursor one position left.
*/
if (text_info->cursor == text_info->text)
break;
text_info->cursor--;
break;
}
case XK_Right:
case XK_KP_Right:
{
/*
Move cursor one position right.
*/
if (text_info->cursor == (text_info->text+Extent(text_info->text)))
break;
text_info->cursor++;
break;
}
default:
{
register char
*p,
*q;
register int
i;
if (state & ControlState)
break;
if (*text == '\0')
break;
if ((Extent(text_info->text)+1) >= (int) MagickPathExtent)
(void) XBell(display,0);
else
{
if (text_info->highlight)
{
/*
Erase the entire line of text.
*/
*text_info->text='\0';
text_info->cursor=text_info->text;
text_info->marker=text_info->text;
text_info->highlight=MagickFalse;
}
/*
Insert a string into the text.
*/
q=text_info->text+Extent(text_info->text)+strlen(text);
for (i=0; i <= Extent(text_info->cursor); i++)
{
*q=(*(q-Extent(text)));
q--;
}
p=text;
for (i=0; i < Extent(text); i++)
*text_info->cursor++=(*p++);
}
break;
}
}
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ X G e t W i d g e t I n f o %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% XGetWidgetInfo() initializes the XWidgetInfo structure.
%
% The format of the XGetWidgetInfo function is:
%
% XGetWidgetInfo(text,widget_info)
%
% A description of each parameter follows:
%
% o text: A string of characters associated with the widget.
%
% o widget_info: Specifies a pointer to a X11 XWidgetInfo structure.
%
*/
static void XGetWidgetInfo(const char *text,XWidgetInfo *widget_info)
{
/*
Initialize widget info.
*/
widget_info->id=(~0);
widget_info->bevel_width=3;
widget_info->width=1;
widget_info->height=1;
widget_info->x=0;
widget_info->y=0;
widget_info->min_y=0;
widget_info->max_y=0;
widget_info->raised=MagickTrue;
widget_info->active=MagickFalse;
widget_info->center=MagickTrue;
widget_info->trough=MagickFalse;
widget_info->highlight=MagickFalse;
widget_info->text=(char *) text;
widget_info->cursor=(char *) text;
if (text != (char *) NULL)
widget_info->cursor+=Extent(text);
widget_info->marker=(char *) text;
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ X H i g h l i g h t W i d g e t %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% XHighlightWidget() draws a highlighted border around a window.
%
% The format of the XHighlightWidget function is:
%
% XHighlightWidget(display,window_info,x,y)
%
% A description of each parameter follows:
%
% o display: Specifies a pointer to the Display structure; returned from
% XOpenDisplay.
%
% o window_info: Specifies a pointer to a X11 XWindowInfo structure.
%
% o x: Specifies an integer representing the rectangle offset in the
% x-direction.
%
% o y: Specifies an integer representing the rectangle offset in the
% y-direction.
%
*/
static void XHighlightWidget(Display *display,const XWindowInfo *window_info,
const int x,const int y)
{
/*
Draw the widget highlighting rectangle.
*/
XSetBevelColor(display,window_info,MagickTrue);
(void) XDrawRectangle(display,window_info->id,window_info->widget_context,x,y,
window_info->width-(x << 1),window_info->height-(y << 1));
(void) XDrawRectangle(display,window_info->id,window_info->widget_context,
x-1,y-1,window_info->width-(x << 1)+1,window_info->height-(y << 1)+1);
XSetBevelColor(display,window_info,MagickFalse);
(void) XDrawRectangle(display,window_info->id,window_info->widget_context,
x-1,y-1,window_info->width-(x << 1),window_info->height-(y << 1));
(void) XSetFillStyle(display,window_info->widget_context,FillSolid);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ X S c r e e n E v e n t %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% XScreenEvent() returns MagickTrue if the any event on the X server queue is
% associated with the widget window.
%
% The format of the XScreenEvent function is:
%
% int XScreenEvent(Display *display,XEvent *event,char *data)
%
% A description of each parameter follows:
%
% o display: Specifies a pointer to the Display structure; returned from
% XOpenDisplay.
%
% o event: Specifies a pointer to a X11 XEvent structure.
%
% o data: Specifies a pointer to a XWindows structure.
%
*/
#if defined(__cplusplus) || defined(c_plusplus)
extern "C" {
#endif
static int XScreenEvent(Display *display,XEvent *event,char *data)
{
XWindows
*windows;
windows=(XWindows *) data;
if (event->xany.window == windows->popup.id)
{
if (event->type == MapNotify)
windows->popup.mapped=MagickTrue;
if (event->type == UnmapNotify)
windows->popup.mapped=MagickFalse;
return(MagickTrue);
}
if (event->xany.window == windows->widget.id)
{
if (event->type == MapNotify)
windows->widget.mapped=MagickTrue;
if (event->type == UnmapNotify)
windows->widget.mapped=MagickFalse;
return(MagickTrue);
}
switch (event->type)
{
case ButtonPress:
{
if ((event->xbutton.button == Button3) &&
(event->xbutton.state & Mod1Mask))
{
/*
Convert Alt-Button3 to Button2.
*/
event->xbutton.button=Button2;
event->xbutton.state&=(~Mod1Mask);
}
return(MagickTrue);
}
case Expose:
{
if (event->xexpose.window == windows->image.id)
{
XRefreshWindow(display,&windows->image,event);
break;
}
if (event->xexpose.window == windows->magnify.id)
if (event->xexpose.count == 0)
if (windows->magnify.mapped)
{
ExceptionInfo
*exception;
exception=AcquireExceptionInfo();
XMakeMagnifyImage(display,windows,exception);
exception=DestroyExceptionInfo(exception);
break;
}
if (event->xexpose.window == windows->command.id)
if (event->xexpose.count == 0)
{
(void) XCommandWidget(display,windows,(const char **) NULL,event);
break;
}
break;
}
case FocusOut:
{
/*
Set input focus for backdrop window.
*/
if (event->xfocus.window == windows->image.id)
(void) XSetInputFocus(display,windows->image.id,RevertToNone,
CurrentTime);
return(MagickTrue);
}
case ButtonRelease:
case KeyPress:
case KeyRelease:
case MotionNotify:
case SelectionNotify:
return(MagickTrue);
default:
break;
}
return(MagickFalse);
}
#if defined(__cplusplus) || defined(c_plusplus)
}
#endif
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ X S e t B e v e l C o l o r %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% XSetBevelColor() sets the graphic context for drawing a beveled border.
%
% The format of the XSetBevelColor function is:
%
% XSetBevelColor(display,window_info,raised)
%
% A description of each parameter follows:
%
% o display: Specifies a pointer to the Display structure; returned from
% XOpenDisplay.
%
% o window_info: Specifies a pointer to a X11 XWindowInfo structure.
%
% o raised: A value other than zero indicates the color show be a
% "highlight" color, otherwise the "shadow" color is set.
%
*/
static void XSetBevelColor(Display *display,const XWindowInfo *window_info,
const MagickStatusType raised)
{
if (window_info->depth == 1)
{
Pixmap
stipple;
/*
Monochrome window.
*/
(void) XSetBackground(display,window_info->widget_context,
XBlackPixel(display,window_info->screen));
(void) XSetForeground(display,window_info->widget_context,
XWhitePixel(display,window_info->screen));
(void) XSetFillStyle(display,window_info->widget_context,
FillOpaqueStippled);
stipple=window_info->highlight_stipple;
if (raised == MagickFalse)
stipple=window_info->shadow_stipple;
(void) XSetStipple(display,window_info->widget_context,stipple);
}
else
if (raised)
(void) XSetForeground(display,window_info->widget_context,
window_info->pixel_info->highlight_color.pixel);
else
(void) XSetForeground(display,window_info->widget_context,
window_info->pixel_info->shadow_color.pixel);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ X S e t M a t t e C o l o r %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% XSetMatteColor() sets the graphic context for drawing the matte.
%
% The format of the XSetMatteColor function is:
%
% XSetMatteColor(display,window_info,raised)
%
% A description of each parameter follows:
%
% o display: Specifies a pointer to the Display structure; returned from
% XOpenDisplay.
%
% o window_info: Specifies a pointer to a X11 XWindowInfo structure.
%
% o raised: A value other than zero indicates the matte is active.
%
*/
static void XSetMatteColor(Display *display,const XWindowInfo *window_info,
const MagickStatusType raised)
{
if (window_info->depth == 1)
{
/*
Monochrome window.
*/
if (raised)
(void) XSetForeground(display,window_info->widget_context,
XWhitePixel(display,window_info->screen));
else
(void) XSetForeground(display,window_info->widget_context,
XBlackPixel(display,window_info->screen));
}
else
if (raised)
(void) XSetForeground(display,window_info->widget_context,
window_info->pixel_info->matte_color.pixel);
else
(void) XSetForeground(display,window_info->widget_context,
window_info->pixel_info->depth_color.pixel);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
+ X S e t T e x t C o l o r %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% XSetTextColor() sets the graphic context for drawing text on a matte.
%
% The format of the XSetTextColor function is:
%
% XSetTextColor(display,window_info,raised)
%
% A description of each parameter follows:
%
% o display: Specifies a pointer to the Display structure; returned from
% XOpenDisplay.
%
% o window_info: Specifies a pointer to a X11 XWindowInfo structure.
%
% o raised: A value other than zero indicates the color show be a
% "highlight" color, otherwise the "shadow" color is set.
%
*/
static void XSetTextColor(Display *display,const XWindowInfo *window_info,
const MagickStatusType raised)
{
ssize_t
foreground,
matte;
if (window_info->depth == 1)
{
/*
Monochrome window.
*/
if (raised)
(void) XSetForeground(display,window_info->widget_context,
XBlackPixel(display,window_info->screen));
else
(void) XSetForeground(display,window_info->widget_context,
XWhitePixel(display,window_info->screen));
return;
}
foreground=(ssize_t) XPixelIntensity(
&window_info->pixel_info->foreground_color);
matte=(ssize_t) XPixelIntensity(&window_info->pixel_info->matte_color);
if (MagickAbsoluteValue((int) (foreground-matte)) > (65535L >> 3))
(void) XSetForeground(display,window_info->widget_context,
window_info->pixel_info->foreground_color.pixel);
else
(void) XSetForeground(display,window_info->widget_context,
window_info->pixel_info->background_color.pixel);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% X C o l o r B r o w s e r W i d g e t %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% XColorBrowserWidget() displays a Color Browser widget with a color query
% to the user. The user keys a reply and presses the Action or Cancel button
% to exit. The typed text is returned as the reply function parameter.
%
% The format of the XColorBrowserWidget method is:
%
% void XColorBrowserWidget(Display *display,XWindows *windows,
% const char *action,char *reply)
%
% A description of each parameter follows:
%
% o display: Specifies a connection to an X server; returned from
% XOpenDisplay.
%
% o window: Specifies a pointer to a XWindows structure.
%
% o action: Specifies a pointer to the action of this widget.
%
% o reply: the response from the user is returned in this parameter.
%
*/
MagickPrivate void XColorBrowserWidget(Display *display,XWindows *windows,
const char *action,char *reply)
{
#define CancelButtonText "Cancel"
#define ColornameText "Name:"
#define ColorPatternText "Pattern:"
#define GrabButtonText "Grab"
#define ResetButtonText "Reset"
char
**colorlist,
primary_selection[MagickPathExtent],
reset_pattern[MagickPathExtent],
text[MagickPathExtent];
ExceptionInfo
*exception;
int
x,
y;
register int
i;
static char
glob_pattern[MagickPathExtent] = "*";
static MagickStatusType
mask = (MagickStatusType) (CWWidth | CWHeight | CWX | CWY);
Status
status;
unsigned int
height,
text_width,
visible_colors,
width;
size_t
colors,
delay,
state;
XColor
color;
XEvent
event;
XFontStruct
*font_info;
XTextProperty
window_name;
XWidgetInfo
action_info,
cancel_info,
expose_info,
grab_info,
list_info,
mode_info,
north_info,
reply_info,
reset_info,
scroll_info,
selection_info,
slider_info,
south_info,
text_info;
XWindowChanges
window_changes;
/*
Get color list and sort in ascending order.
*/
assert(display != (Display *) NULL);
assert(windows != (XWindows *) NULL);
assert(action != (char *) NULL);
assert(reply != (char *) NULL);
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",action);
XSetCursorState(display,windows,MagickTrue);
XCheckRefreshWindows(display,windows);
(void) CopyMagickString(reset_pattern,"*",MagickPathExtent);
exception=AcquireExceptionInfo();
colorlist=GetColorList(glob_pattern,&colors,exception);
if (colorlist == (char **) NULL)
{
/*
Pattern failed, obtain all the colors.
*/
(void) CopyMagickString(glob_pattern,"*",MagickPathExtent);
colorlist=GetColorList(glob_pattern,&colors,exception);
if (colorlist == (char **) NULL)
{
XNoticeWidget(display,windows,"Unable to obtain colors names:",
glob_pattern);
(void) XDialogWidget(display,windows,action,"Enter color name:",
reply);
return;
}
}
/*
Determine Color Browser widget attributes.
*/
font_info=windows->widget.font_info;
text_width=0;
for (i=0; i < (int) colors; i++)
if (WidgetTextWidth(font_info,colorlist[i]) > text_width)
text_width=WidgetTextWidth(font_info,colorlist[i]);
width=WidgetTextWidth(font_info,(char *) action);
if (WidgetTextWidth(font_info,CancelButtonText) > width)
width=WidgetTextWidth(font_info,CancelButtonText);
if (WidgetTextWidth(font_info,ResetButtonText) > width)
width=WidgetTextWidth(font_info,ResetButtonText);
if (WidgetTextWidth(font_info,GrabButtonText) > width)
width=WidgetTextWidth(font_info,GrabButtonText);
width+=QuantumMargin;
if (WidgetTextWidth(font_info,ColorPatternText) > width)
width=WidgetTextWidth(font_info,ColorPatternText);
if (WidgetTextWidth(font_info,ColornameText) > width)
width=WidgetTextWidth(font_info,ColornameText);
height=(unsigned int) (font_info->ascent+font_info->descent);
/*
Position Color Browser widget.
*/
windows->widget.width=(unsigned int)
(width+MagickMin((int) text_width,(int) MaxTextWidth)+6*QuantumMargin);
windows->widget.min_width=(unsigned int)
(width+MinTextWidth+4*QuantumMargin);
if (windows->widget.width < windows->widget.min_width)
windows->widget.width=windows->widget.min_width;
windows->widget.height=(unsigned int)
((81*height) >> 2)+((13*QuantumMargin) >> 1)+4;
windows->widget.min_height=(unsigned int)
(((23*height) >> 1)+((13*QuantumMargin) >> 1)+4);
if (windows->widget.height < windows->widget.min_height)
windows->widget.height=windows->widget.min_height;
XConstrainWindowPosition(display,&windows->widget);
/*
Map Color Browser widget.
*/
(void) CopyMagickString(windows->widget.name,"Browse and Select a Color",
MagickPathExtent);
status=XStringListToTextProperty(&windows->widget.name,1,&window_name);
if (status != False)
{
XSetWMName(display,windows->widget.id,&window_name);
XSetWMIconName(display,windows->widget.id,&window_name);
(void) XFree((void *) window_name.value);
}
window_changes.width=(int) windows->widget.width;
window_changes.height=(int) windows->widget.height;
window_changes.x=windows->widget.x;
window_changes.y=windows->widget.y;
(void) XReconfigureWMWindow(display,windows->widget.id,windows->widget.screen,
mask,&window_changes);
(void) XMapRaised(display,windows->widget.id);
windows->widget.mapped=MagickFalse;
/*
Respond to X events.
*/
XGetWidgetInfo((char *) NULL,&mode_info);
XGetWidgetInfo((char *) NULL,&slider_info);
XGetWidgetInfo((char *) NULL,&north_info);
XGetWidgetInfo((char *) NULL,&south_info);
XGetWidgetInfo((char *) NULL,&expose_info);
XGetWidgetInfo((char *) NULL,&selection_info);
visible_colors=0;
delay=SuspendTime << 2;
state=UpdateConfigurationState;
do
{
if (state & UpdateConfigurationState)
{
int
id;
/*
Initialize button information.
*/
XGetWidgetInfo(CancelButtonText,&cancel_info);
cancel_info.width=width;
cancel_info.height=(unsigned int) ((3*height) >> 1);
cancel_info.x=(int)
(windows->widget.width-cancel_info.width-QuantumMargin-2);
cancel_info.y=(int)
(windows->widget.height-cancel_info.height-QuantumMargin);
XGetWidgetInfo(action,&action_info);
action_info.width=width;
action_info.height=(unsigned int) ((3*height) >> 1);
action_info.x=cancel_info.x-(cancel_info.width+(QuantumMargin >> 1)+
(action_info.bevel_width << 1));
action_info.y=cancel_info.y;
XGetWidgetInfo(GrabButtonText,&grab_info);
grab_info.width=width;
grab_info.height=(unsigned int) ((3*height) >> 1);
grab_info.x=QuantumMargin;
grab_info.y=((5*QuantumMargin) >> 1)+height;
XGetWidgetInfo(ResetButtonText,&reset_info);
reset_info.width=width;
reset_info.height=(unsigned int) ((3*height) >> 1);
reset_info.x=QuantumMargin;
reset_info.y=grab_info.y+grab_info.height+QuantumMargin;
/*
Initialize reply information.
*/
XGetWidgetInfo(reply,&reply_info);
reply_info.raised=MagickFalse;
reply_info.bevel_width--;
reply_info.width=windows->widget.width-width-((6*QuantumMargin) >> 1);
reply_info.height=height << 1;
reply_info.x=(int) (width+(QuantumMargin << 1));
reply_info.y=action_info.y-reply_info.height-QuantumMargin;
/*
Initialize mode information.
*/
XGetWidgetInfo((char *) NULL,&mode_info);
mode_info.active=MagickTrue;
mode_info.bevel_width=0;
mode_info.width=(unsigned int) (action_info.x-(QuantumMargin << 1));
mode_info.height=action_info.height;
mode_info.x=QuantumMargin;
mode_info.y=action_info.y;
/*
Initialize scroll information.
*/
XGetWidgetInfo((char *) NULL,&scroll_info);
scroll_info.bevel_width--;
scroll_info.width=height;
scroll_info.height=(unsigned int) (reply_info.y-grab_info.y-
(QuantumMargin >> 1));
scroll_info.x=reply_info.x+(reply_info.width-scroll_info.width);
scroll_info.y=grab_info.y-reply_info.bevel_width;
scroll_info.raised=MagickFalse;
scroll_info.trough=MagickTrue;
north_info=scroll_info;
north_info.raised=MagickTrue;
north_info.width-=(north_info.bevel_width << 1);
north_info.height=north_info.width-1;
north_info.x+=north_info.bevel_width;
north_info.y+=north_info.bevel_width;
south_info=north_info;
south_info.y=scroll_info.y+scroll_info.height-scroll_info.bevel_width-
south_info.height;
id=slider_info.id;
slider_info=north_info;
slider_info.id=id;
slider_info.width-=2;
slider_info.min_y=north_info.y+north_info.height+north_info.bevel_width+
slider_info.bevel_width+2;
slider_info.height=scroll_info.height-((slider_info.min_y-
scroll_info.y+1) << 1)+4;
visible_colors=scroll_info.height/(height+(height >> 3));
if (colors > visible_colors)
slider_info.height=(unsigned int)
((visible_colors*slider_info.height)/colors);
slider_info.max_y=south_info.y-south_info.bevel_width-
slider_info.bevel_width-2;
slider_info.x=scroll_info.x+slider_info.bevel_width+1;
slider_info.y=slider_info.min_y;
expose_info=scroll_info;
expose_info.y=slider_info.y;
/*
Initialize list information.
*/
XGetWidgetInfo((char *) NULL,&list_info);
list_info.raised=MagickFalse;
list_info.bevel_width--;
list_info.width=(unsigned int)
(scroll_info.x-reply_info.x-(QuantumMargin >> 1));
list_info.height=scroll_info.height;
list_info.x=reply_info.x;
list_info.y=scroll_info.y;
if (windows->widget.mapped == MagickFalse)
state|=JumpListState;
/*
Initialize text information.
*/
*text='\0';
XGetWidgetInfo(text,&text_info);
text_info.center=MagickFalse;
text_info.width=reply_info.width;
text_info.height=height;
text_info.x=list_info.x-(QuantumMargin >> 1);
text_info.y=QuantumMargin;
/*
Initialize selection information.
*/
XGetWidgetInfo((char *) NULL,&selection_info);
selection_info.center=MagickFalse;
selection_info.width=list_info.width;
selection_info.height=(unsigned int) ((9*height) >> 3);
selection_info.x=list_info.x;
state&=(~UpdateConfigurationState);
}
if (state & RedrawWidgetState)
{
/*
Redraw Color Browser window.
*/
x=QuantumMargin;
y=text_info.y+((text_info.height-height) >> 1)+font_info->ascent;
(void) XDrawString(display,windows->widget.id,
windows->widget.annotate_context,x,y,ColorPatternText,
Extent(ColorPatternText));
(void) CopyMagickString(text_info.text,glob_pattern,MagickPathExtent);
XDrawWidgetText(display,&windows->widget,&text_info);
XDrawBeveledButton(display,&windows->widget,&grab_info);
XDrawBeveledButton(display,&windows->widget,&reset_info);
XDrawBeveledMatte(display,&windows->widget,&list_info);
XDrawBeveledMatte(display,&windows->widget,&scroll_info);
XDrawTriangleNorth(display,&windows->widget,&north_info);
XDrawBeveledButton(display,&windows->widget,&slider_info);
XDrawTriangleSouth(display,&windows->widget,&south_info);
x=QuantumMargin;
y=reply_info.y+((reply_info.height-height) >> 1)+font_info->ascent;
(void) XDrawString(display,windows->widget.id,
windows->widget.annotate_context,x,y,ColornameText,
Extent(ColornameText));
XDrawBeveledMatte(display,&windows->widget,&reply_info);
XDrawMatteText(display,&windows->widget,&reply_info);
XDrawBeveledButton(display,&windows->widget,&action_info);
XDrawBeveledButton(display,&windows->widget,&cancel_info);
XHighlightWidget(display,&windows->widget,BorderOffset,BorderOffset);
selection_info.id=(~0);
state|=RedrawActionState;
state|=RedrawListState;
state&=(~RedrawWidgetState);
}
if (state & UpdateListState)
{
char
**checklist;
size_t
number_colors;
status=XParseColor(display,windows->widget.map_info->colormap,
glob_pattern,&color);
if ((status != False) || (strchr(glob_pattern,'-') != (char *) NULL))
{
/*
Reply is a single color name-- exit.
*/
(void) CopyMagickString(reply,glob_pattern,MagickPathExtent);
(void) CopyMagickString(glob_pattern,reset_pattern,MagickPathExtent);
action_info.raised=MagickFalse;
XDrawBeveledButton(display,&windows->widget,&action_info);
break;
}
/*
Update color list.
*/
checklist=GetColorList(glob_pattern,&number_colors,exception);
if (number_colors == 0)
{
(void) CopyMagickString(glob_pattern,reset_pattern,MagickPathExtent);
(void) XBell(display,0);
}
else
{
for (i=0; i < (int) colors; i++)
colorlist[i]=DestroyString(colorlist[i]);
if (colorlist != (char **) NULL)
colorlist=(char **) RelinquishMagickMemory(colorlist);
colorlist=checklist;
colors=number_colors;
}
/*
Sort color list in ascending order.
*/
slider_info.height=
scroll_info.height-((slider_info.min_y-scroll_info.y+1) << 1)+1;
if (colors > visible_colors)
slider_info.height=(unsigned int)
((visible_colors*slider_info.height)/colors);
slider_info.max_y=south_info.y-south_info.bevel_width-
slider_info.bevel_width-2;
slider_info.id=0;
slider_info.y=slider_info.min_y;
expose_info.y=slider_info.y;
selection_info.id=(~0);
list_info.id=(~0);
state|=RedrawListState;
/*
Redraw color name & reply.
*/
*reply_info.text='\0';
reply_info.cursor=reply_info.text;
(void) CopyMagickString(text_info.text,glob_pattern,MagickPathExtent);
XDrawWidgetText(display,&windows->widget,&text_info);
XDrawMatteText(display,&windows->widget,&reply_info);
XDrawBeveledMatte(display,&windows->widget,&scroll_info);
XDrawTriangleNorth(display,&windows->widget,&north_info);
XDrawBeveledButton(display,&windows->widget,&slider_info);
XDrawTriangleSouth(display,&windows->widget,&south_info);
XHighlightWidget(display,&windows->widget,BorderOffset,BorderOffset);
state&=(~UpdateListState);
}
if (state & JumpListState)
{
/*
Jump scroll to match user color.
*/
list_info.id=(~0);
for (i=0; i < (int) colors; i++)
if (LocaleCompare(colorlist[i],reply) >= 0)
{
list_info.id=LocaleCompare(colorlist[i],reply) == 0 ? i : ~0;
break;
}
if ((i < slider_info.id) ||
(i >= (int) (slider_info.id+visible_colors)))
slider_info.id=i-(visible_colors >> 1);
selection_info.id=(~0);
state|=RedrawListState;
state&=(~JumpListState);
}
if (state & RedrawListState)
{
/*
Determine slider id and position.
*/
if (slider_info.id >= (int) (colors-visible_colors))
slider_info.id=(int) (colors-visible_colors);
if ((slider_info.id < 0) || (colors <= visible_colors))
slider_info.id=0;
slider_info.y=slider_info.min_y;
if (colors != 0)
slider_info.y+=(int) (slider_info.id*(slider_info.max_y-
slider_info.min_y+1)/colors);
if (slider_info.id != selection_info.id)
{
/*
Redraw scroll bar and file names.
*/
selection_info.id=slider_info.id;
selection_info.y=list_info.y+(height >> 3)+2;
for (i=0; i < (int) visible_colors; i++)
{
selection_info.raised=(slider_info.id+i) != list_info.id ?
MagickTrue : MagickFalse;
selection_info.text=(char *) NULL;
if ((slider_info.id+i) < (int) colors)
selection_info.text=colorlist[slider_info.id+i];
XDrawWidgetText(display,&windows->widget,&selection_info);
selection_info.y+=(int) selection_info.height;
}
/*
Update slider.
*/
if (slider_info.y > expose_info.y)
{
expose_info.height=(unsigned int) slider_info.y-expose_info.y;
expose_info.y=slider_info.y-expose_info.height-
slider_info.bevel_width-1;
}
else
{
expose_info.height=(unsigned int) expose_info.y-slider_info.y;
expose_info.y=slider_info.y+slider_info.height+
slider_info.bevel_width+1;
}
XDrawTriangleNorth(display,&windows->widget,&north_info);
XDrawMatte(display,&windows->widget,&expose_info);
XDrawBeveledButton(display,&windows->widget,&slider_info);
XDrawTriangleSouth(display,&windows->widget,&south_info);
expose_info.y=slider_info.y;
}
state&=(~RedrawListState);
}
if (state & RedrawActionState)
{
static char
colorname[MagickPathExtent];
/*
Display the selected color in a drawing area.
*/
color=windows->widget.pixel_info->matte_color;
(void) XParseColor(display,windows->widget.map_info->colormap,
reply_info.text,&windows->widget.pixel_info->matte_color);
XBestPixel(display,windows->widget.map_info->colormap,(XColor *) NULL,
(unsigned int) windows->widget.visual_info->colormap_size,
&windows->widget.pixel_info->matte_color);
mode_info.text=colorname;
(void) FormatLocaleString(mode_info.text,MagickPathExtent,
"#%02x%02x%02x",windows->widget.pixel_info->matte_color.red,
windows->widget.pixel_info->matte_color.green,
windows->widget.pixel_info->matte_color.blue);
XDrawBeveledButton(display,&windows->widget,&mode_info);
windows->widget.pixel_info->matte_color=color;
state&=(~RedrawActionState);
}
/*
Wait for next event.
*/
if (north_info.raised && south_info.raised)
(void) XIfEvent(display,&event,XScreenEvent,(char *) windows);
else
{
/*
Brief delay before advancing scroll bar.
*/
XDelay(display,delay);
delay=SuspendTime;
(void) XCheckIfEvent(display,&event,XScreenEvent,(char *) windows);
if (north_info.raised == MagickFalse)
if (slider_info.id > 0)
{
/*
Move slider up.
*/
slider_info.id--;
state|=RedrawListState;
}
if (south_info.raised == MagickFalse)
if (slider_info.id < (int) colors)
{
/*
Move slider down.
*/
slider_info.id++;
state|=RedrawListState;
}
if (event.type != ButtonRelease)
continue;
}
switch (event.type)
{
case ButtonPress:
{
if (MatteIsActive(slider_info,event.xbutton))
{
/*
Track slider.
*/
slider_info.active=MagickTrue;
break;
}
if (MatteIsActive(north_info,event.xbutton))
if (slider_info.id > 0)
{
/*
Move slider up.
*/
north_info.raised=MagickFalse;
slider_info.id--;
state|=RedrawListState;
break;
}
if (MatteIsActive(south_info,event.xbutton))
if (slider_info.id < (int) colors)
{
/*
Move slider down.
*/
south_info.raised=MagickFalse;
slider_info.id++;
state|=RedrawListState;
break;
}
if (MatteIsActive(scroll_info,event.xbutton))
{
/*
Move slider.
*/
if (event.xbutton.y < slider_info.y)
slider_info.id-=(visible_colors-1);
else
slider_info.id+=(visible_colors-1);
state|=RedrawListState;
break;
}
if (MatteIsActive(list_info,event.xbutton))
{
int
id;
/*
User pressed list matte.
*/
id=slider_info.id+(event.xbutton.y-(list_info.y+(height >> 1))+1)/
selection_info.height;
if (id >= (int) colors)
break;
(void) CopyMagickString(reply_info.text,colorlist[id],
MagickPathExtent);
reply_info.highlight=MagickFalse;
reply_info.marker=reply_info.text;
reply_info.cursor=reply_info.text+Extent(reply_info.text);
XDrawMatteText(display,&windows->widget,&reply_info);
state|=RedrawActionState;
if (id == list_info.id)
{
(void) CopyMagickString(glob_pattern,reply_info.text,
MagickPathExtent);
state|=UpdateListState;
}
selection_info.id=(~0);
list_info.id=id;
state|=RedrawListState;
break;
}
if (MatteIsActive(grab_info,event.xbutton))
{
/*
User pressed Grab button.
*/
grab_info.raised=MagickFalse;
XDrawBeveledButton(display,&windows->widget,&grab_info);
break;
}
if (MatteIsActive(reset_info,event.xbutton))
{
/*
User pressed Reset button.
*/
reset_info.raised=MagickFalse;
XDrawBeveledButton(display,&windows->widget,&reset_info);
break;
}
if (MatteIsActive(mode_info,event.xbutton))
{
/*
User pressed mode button.
*/
if (mode_info.text != (char *) NULL)
(void) CopyMagickString(reply_info.text,mode_info.text,
MagickPathExtent);
(void) CopyMagickString(primary_selection,reply_info.text,
MagickPathExtent);
(void) XSetSelectionOwner(display,XA_PRIMARY,windows->widget.id,
event.xbutton.time);
reply_info.highlight=XGetSelectionOwner(display,XA_PRIMARY) ==
windows->widget.id ? MagickTrue : MagickFalse;
reply_info.marker=reply_info.text;
reply_info.cursor=reply_info.text+Extent(reply_info.text);
XDrawMatteText(display,&windows->widget,&reply_info);
break;
}
if (MatteIsActive(action_info,event.xbutton))
{
/*
User pressed action button.
*/
action_info.raised=MagickFalse;
XDrawBeveledButton(display,&windows->widget,&action_info);
break;
}
if (MatteIsActive(cancel_info,event.xbutton))
{
/*
User pressed Cancel button.
*/
cancel_info.raised=MagickFalse;
XDrawBeveledButton(display,&windows->widget,&cancel_info);
break;
}
if (MatteIsActive(reply_info,event.xbutton) == MagickFalse)
break;
if (event.xbutton.button != Button2)
{
static Time
click_time;
/*
Move text cursor to position of button press.
*/
x=event.xbutton.x-reply_info.x-(QuantumMargin >> 2);
for (i=1; i <= Extent(reply_info.marker); i++)
if (XTextWidth(font_info,reply_info.marker,i) > x)
break;
reply_info.cursor=reply_info.marker+i-1;
if (event.xbutton.time > (click_time+DoubleClick))
reply_info.highlight=MagickFalse;
else
{
/*
Become the XA_PRIMARY selection owner.
*/
(void) CopyMagickString(primary_selection,reply_info.text,
MagickPathExtent);
(void) XSetSelectionOwner(display,XA_PRIMARY,windows->widget.id,
event.xbutton.time);
reply_info.highlight=XGetSelectionOwner(display,XA_PRIMARY) ==
windows->widget.id ? MagickTrue : MagickFalse;
}
XDrawMatteText(display,&windows->widget,&reply_info);
click_time=event.xbutton.time;
break;
}
/*
Request primary selection.
*/
(void) XConvertSelection(display,XA_PRIMARY,XA_STRING,XA_STRING,
windows->widget.id,event.xbutton.time);
break;
}
case ButtonRelease:
{
if (windows->widget.mapped == MagickFalse)
break;
if (north_info.raised == MagickFalse)
{
/*
User released up button.
*/
delay=SuspendTime << 2;
north_info.raised=MagickTrue;
XDrawTriangleNorth(display,&windows->widget,&north_info);
}
if (south_info.raised == MagickFalse)
{
/*
User released down button.
*/
delay=SuspendTime << 2;
south_info.raised=MagickTrue;
XDrawTriangleSouth(display,&windows->widget,&south_info);
}
if (slider_info.active)
{
/*
Stop tracking slider.
*/
slider_info.active=MagickFalse;
break;
}
if (grab_info.raised == MagickFalse)
{
if (event.xbutton.window == windows->widget.id)
if (MatteIsActive(grab_info,event.xbutton))
{
/*
Select a fill color from the X server.
*/
(void) XGetWindowColor(display,windows,reply_info.text,
exception);
reply_info.marker=reply_info.text;
reply_info.cursor=reply_info.text+Extent(reply_info.text);
XDrawMatteText(display,&windows->widget,&reply_info);
state|=RedrawActionState;
}
grab_info.raised=MagickTrue;
XDrawBeveledButton(display,&windows->widget,&grab_info);
}
if (reset_info.raised == MagickFalse)
{
if (event.xbutton.window == windows->widget.id)
if (MatteIsActive(reset_info,event.xbutton))
{
(void) CopyMagickString(glob_pattern,reset_pattern,
MagickPathExtent);
state|=UpdateListState;
}
reset_info.raised=MagickTrue;
XDrawBeveledButton(display,&windows->widget,&reset_info);
}
if (action_info.raised == MagickFalse)
{
if (event.xbutton.window == windows->widget.id)
{
if (MatteIsActive(action_info,event.xbutton))
{
if (*reply_info.text == '\0')
(void) XBell(display,0);
else
state|=ExitState;
}
}
action_info.raised=MagickTrue;
XDrawBeveledButton(display,&windows->widget,&action_info);
}
if (cancel_info.raised == MagickFalse)
{
if (event.xbutton.window == windows->widget.id)
if (MatteIsActive(cancel_info,event.xbutton))
{
*reply_info.text='\0';
state|=ExitState;
}
cancel_info.raised=MagickTrue;
XDrawBeveledButton(display,&windows->widget,&cancel_info);
}
if (MatteIsActive(reply_info,event.xbutton) == MagickFalse)
break;
break;
}
case ClientMessage:
{
/*
If client window delete message, exit.
*/
if (event.xclient.message_type != windows->wm_protocols)
break;
if (*event.xclient.data.l == (int) windows->wm_take_focus)
{
(void) XSetInputFocus(display,event.xclient.window,RevertToParent,
(Time) event.xclient.data.l[1]);
break;
}
if (*event.xclient.data.l != (int) windows->wm_delete_window)
break;
if (event.xclient.window == windows->widget.id)
{
*reply_info.text='\0';
state|=ExitState;
break;
}
break;
}
case ConfigureNotify:
{
/*
Update widget configuration.
*/
if (event.xconfigure.window != windows->widget.id)
break;
if ((event.xconfigure.width == (int) windows->widget.width) &&
(event.xconfigure.height == (int) windows->widget.height))
break;
windows->widget.width=(unsigned int)
MagickMax(event.xconfigure.width,(int) windows->widget.min_width);
windows->widget.height=(unsigned int)
MagickMax(event.xconfigure.height,(int) windows->widget.min_height);
state|=UpdateConfigurationState;
break;
}
case EnterNotify:
{
if (event.xcrossing.window != windows->widget.id)
break;
state&=(~InactiveWidgetState);
break;
}
case Expose:
{
if (event.xexpose.window != windows->widget.id)
break;
if (event.xexpose.count != 0)
break;
state|=RedrawWidgetState;
break;
}
case KeyPress:
{
static char
command[MagickPathExtent];
static int
length;
static KeySym
key_symbol;
/*
Respond to a user key press.
*/
if (event.xkey.window != windows->widget.id)
break;
length=XLookupString((XKeyEvent *) &event.xkey,command,
(int) sizeof(command),&key_symbol,(XComposeStatus *) NULL);
*(command+length)='\0';
if (AreaIsActive(scroll_info,event.xkey))
{
/*
Move slider.
*/
switch ((int) key_symbol)
{
case XK_Home:
case XK_KP_Home:
{
slider_info.id=0;
break;
}
case XK_Up:
case XK_KP_Up:
{
slider_info.id--;
break;
}
case XK_Down:
case XK_KP_Down:
{
slider_info.id++;
break;
}
case XK_Prior:
case XK_KP_Prior:
{
slider_info.id-=visible_colors;
break;
}
case XK_Next:
case XK_KP_Next:
{
slider_info.id+=visible_colors;
break;
}
case XK_End:
case XK_KP_End:
{
slider_info.id=(int) colors;
break;
}
}
state|=RedrawListState;
break;
}
if ((key_symbol == XK_Return) || (key_symbol == XK_KP_Enter))
{
/*
Read new color or glob patterm.
*/
if (*reply_info.text == '\0')
break;
(void) CopyMagickString(glob_pattern,reply_info.text,MagickPathExtent);
state|=UpdateListState;
break;
}
if (key_symbol == XK_Control_L)
{
state|=ControlState;
break;
}
if (state & ControlState)
switch ((int) key_symbol)
{
case XK_u:
case XK_U:
{
/*
Erase the entire line of text.
*/
*reply_info.text='\0';
reply_info.cursor=reply_info.text;
reply_info.marker=reply_info.text;
reply_info.highlight=MagickFalse;
break;
}
default:
break;
}
XEditText(display,&reply_info,key_symbol,command,state);
XDrawMatteText(display,&windows->widget,&reply_info);
state|=JumpListState;
status=XParseColor(display,windows->widget.map_info->colormap,
reply_info.text,&color);
if (status != False)
state|=RedrawActionState;
break;
}
case KeyRelease:
{
static char
command[MagickPathExtent];
static KeySym
key_symbol;
/*
Respond to a user key release.
*/
if (event.xkey.window != windows->widget.id)
break;
(void) XLookupString((XKeyEvent *) &event.xkey,command,
(int) sizeof(command),&key_symbol,(XComposeStatus *) NULL);
if (key_symbol == XK_Control_L)
state&=(~ControlState);
break;
}
case LeaveNotify:
{
if (event.xcrossing.window != windows->widget.id)
break;
state|=InactiveWidgetState;
break;
}
case MapNotify:
{
mask&=(~CWX);
mask&=(~CWY);
break;
}
case MotionNotify:
{
/*
Discard pending button motion events.
*/
while (XCheckMaskEvent(display,ButtonMotionMask,&event)) ;
if (slider_info.active)
{
/*
Move slider matte.
*/
slider_info.y=event.xmotion.y-
((slider_info.height+slider_info.bevel_width) >> 1)+1;
if (slider_info.y < slider_info.min_y)
slider_info.y=slider_info.min_y;
if (slider_info.y > slider_info.max_y)
slider_info.y=slider_info.max_y;
slider_info.id=0;
if (slider_info.y != slider_info.min_y)
slider_info.id=(int) ((colors*(slider_info.y-
slider_info.min_y+1))/(slider_info.max_y-slider_info.min_y+1));
state|=RedrawListState;
break;
}
if (state & InactiveWidgetState)
break;
if (grab_info.raised == MatteIsActive(grab_info,event.xmotion))
{
/*
Grab button status changed.
*/
grab_info.raised=!grab_info.raised;
XDrawBeveledButton(display,&windows->widget,&grab_info);
break;
}
if (reset_info.raised == MatteIsActive(reset_info,event.xmotion))
{
/*
Reset button status changed.
*/
reset_info.raised=!reset_info.raised;
XDrawBeveledButton(display,&windows->widget,&reset_info);
break;
}
if (action_info.raised == MatteIsActive(action_info,event.xmotion))
{
/*
Action button status changed.
*/
action_info.raised=action_info.raised == MagickFalse ?
MagickTrue : MagickFalse;
XDrawBeveledButton(display,&windows->widget,&action_info);
break;
}
if (cancel_info.raised == MatteIsActive(cancel_info,event.xmotion))
{
/*
Cancel button status changed.
*/
cancel_info.raised=cancel_info.raised == MagickFalse ?
MagickTrue : MagickFalse;
XDrawBeveledButton(display,&windows->widget,&cancel_info);
break;
}
break;
}
case SelectionClear:
{
reply_info.highlight=MagickFalse;
XDrawMatteText(display,&windows->widget,&reply_info);
break;
}
case SelectionNotify:
{
Atom
type;
int
format;
unsigned char
*data;
unsigned long
after,
length;
/*
Obtain response from primary selection.
*/
if (event.xselection.property == (Atom) None)
break;
status=XGetWindowProperty(display,event.xselection.requestor,
event.xselection.property,0L,2047L,MagickTrue,XA_STRING,&type,
&format,&length,&after,&data);
if ((status != Success) || (type != XA_STRING) || (format == 32) ||
(length == 0))
break;
if ((Extent(reply_info.text)+length) >= (MagickPathExtent-1))
(void) XBell(display,0);
else
{
/*
Insert primary selection in reply text.
*/
*(data+length)='\0';
XEditText(display,&reply_info,(KeySym) XK_Insert,(char *) data,
state);
XDrawMatteText(display,&windows->widget,&reply_info);
state|=JumpListState;
state|=RedrawActionState;
}
(void) XFree((void *) data);
break;
}
case SelectionRequest:
{
XSelectionEvent
notify;
XSelectionRequestEvent
*request;
if (reply_info.highlight == MagickFalse)
break;
/*
Set primary selection.
*/
request=(&(event.xselectionrequest));
(void) XChangeProperty(request->display,request->requestor,
request->property,request->target,8,PropModeReplace,
(unsigned char *) primary_selection,Extent(primary_selection));
notify.type=SelectionNotify;
notify.send_event=MagickTrue;
notify.display=request->display;
notify.requestor=request->requestor;
notify.selection=request->selection;
notify.target=request->target;
notify.time=request->time;
if (request->property == None)
notify.property=request->target;
else
notify.property=request->property;
(void) XSendEvent(request->display,request->requestor,False,
NoEventMask,(XEvent *) ¬ify);
}
default:
break;
}
} while ((state & ExitState) == 0);
XSetCursorState(display,windows,MagickFalse);
(void) XWithdrawWindow(display,windows->widget.id,windows->widget.screen);
XCheckRefreshWindows(display,windows);
/*
Free color list.
*/
for (i=0; i < (int) colors; i++)
colorlist[i]=DestroyString(colorlist[i]);
if (colorlist != (char **) NULL)
colorlist=(char **) RelinquishMagickMemory(colorlist);
exception=DestroyExceptionInfo(exception);
if ((*reply == '\0') || (strchr(reply,'-') != (char *) NULL))
return;
status=XParseColor(display,windows->widget.map_info->colormap,reply,&color);
if (status != False)
return;
XNoticeWidget(display,windows,"Color is unknown to X server:",reply);
(void) CopyMagickString(reply,"gray",MagickPathExtent);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% X C o m m a n d W i d g e t %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% XCommandWidget() maps a menu and returns the command pointed to by the user
% when the button is released.
%
% The format of the XCommandWidget method is:
%
% int XCommandWidget(Display *display,XWindows *windows,
% const char **selections,XEvent *event)
%
% A description of each parameter follows:
%
% o selection_number: Specifies the number of the selection that the
% user choose.
%
% o display: Specifies a connection to an X server; returned from
% XOpenDisplay.
%
% o window: Specifies a pointer to a XWindows structure.
%
% o selections: Specifies a pointer to one or more strings that comprise
% the choices in the menu.
%
% o event: Specifies a pointer to a X11 XEvent structure.
%
*/
MagickPrivate int XCommandWidget(Display *display,XWindows *windows,
const char **selections,XEvent *event)
{
#define tile_width 112
#define tile_height 70
static const unsigned char
tile_bits[]=
{
0x1f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x1f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x1f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1f, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1f, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1e, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x1e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x1e, 0x38, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x1e, 0xbc, 0x9f, 0x03, 0x00, 0x3e, 0x00, 0xc0,
0x1f, 0x00, 0x0e, 0x00, 0x00, 0x00, 0x1e, 0xfc, 0xff, 0x0f, 0x80, 0x3f,
0x00, 0xf0, 0x1f, 0xc0, 0x0f, 0x00, 0x00, 0x00, 0x1e, 0xfc, 0xff, 0x1f,
0xe0, 0x3f, 0x00, 0xfc, 0x1f, 0xf0, 0x0f, 0x00, 0x00, 0x00, 0x1e, 0xfc,
0xff, 0x1f, 0xf0, 0x3f, 0x00, 0xfe, 0x1f, 0xf8, 0x0f, 0x00, 0x00, 0x00,
0x1e, 0xfc, 0xfc, 0x3f, 0xf8, 0x3f, 0x00, 0xff, 0x1e, 0xfc, 0x0f, 0x00,
0x00, 0x00, 0x1e, 0x7c, 0xfc, 0x3e, 0xf8, 0x3c, 0x80, 0x1f, 0x1e, 0x7c,
0x0f, 0x00, 0x00, 0x00, 0x1e, 0x78, 0x78, 0x3c, 0x7c, 0x3c, 0xc0, 0x0f,
0x1e, 0x3e, 0x0f, 0x00, 0x00, 0x00, 0x1e, 0x78, 0x78, 0x3c, 0x7c, 0x3c,
0xc0, 0x07, 0x1e, 0x3e, 0x0f, 0x00, 0x00, 0x00, 0x1e, 0x78, 0x78, 0x3c,
0x7c, 0x7c, 0xc0, 0x0f, 0x1e, 0x3e, 0x00, 0x00, 0x00, 0x00, 0x1e, 0x78,
0x78, 0x3c, 0xfc, 0x7c, 0x80, 0x7f, 0x1e, 0x7c, 0x00, 0x00, 0x00, 0x00,
0x1e, 0xf8, 0x78, 0x7c, 0xf8, 0xff, 0x00, 0xff, 0x1f, 0xf8, 0xff, 0x00,
0x00, 0x00, 0x1e, 0xf8, 0x78, 0x7c, 0xf0, 0xff, 0x07, 0xfe, 0x1f, 0xf8,
0xff, 0x00, 0x00, 0x00, 0x1e, 0xf8, 0x78, 0x7c, 0xf0, 0xff, 0x07, 0xf8,
0x1f, 0xf0, 0xff, 0x01, 0x00, 0x00, 0x1e, 0xf8, 0x78, 0x7c, 0xc0, 0xef,
0x07, 0xe0, 0x1f, 0xc0, 0xff, 0x01, 0x00, 0x00, 0x1e, 0x70, 0x40, 0x78,
0x00, 0xc7, 0x07, 0x00, 0x1e, 0x00, 0x1f, 0x00, 0x00, 0x00, 0x1e, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1e, 0x00, 0x00, 0x00, 0x00, 0x00,
0x1e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1f, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1f, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80,
0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0xc0, 0x0f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0xe0, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0xf0, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0x01, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfc, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x78,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x30, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x01, 0x02, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x07,
0x1e, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0xc0, 0x0f, 0x1f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x60, 0x00, 0xc0, 0x0f, 0x1f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x78, 0x00, 0xc0, 0x8f, 0x3f, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x78, 0x00, 0xc0, 0x8f, 0x3f, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x78, 0x00, 0xe0, 0x9f, 0x7f, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x78, 0x00, 0xe0, 0xdf,
0x7f, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1e, 0x00, 0x00, 0x78, 0x00,
0xe0, 0xdf, 0x7b, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1e, 0x00, 0x0c,
0x78, 0x30, 0xf0, 0xff, 0x7b, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x1e,
0x00, 0x0f, 0xf8, 0x70, 0xf0, 0xff, 0x7b, 0x00, 0x00, 0x1f, 0x00, 0xe0,
0x0f, 0x1e, 0x80, 0x0f, 0xf8, 0x78, 0xf0, 0xfd, 0xf9, 0x00, 0xc0, 0x1f,
0x00, 0xf8, 0x0f, 0x00, 0xe0, 0x1f, 0xf8, 0x7c, 0xf0, 0xfc, 0xf9, 0x00,
0xf0, 0x1f, 0x00, 0xfe, 0x0f, 0x00, 0xf0, 0x07, 0xf8, 0x3e, 0xf8, 0xfc,
0xf0, 0x01, 0xf8, 0x1f, 0x00, 0xff, 0x0f, 0x1e, 0xf0, 0x03, 0xf8, 0x3f,
0xf8, 0xf8, 0xf0, 0x01, 0xfc, 0x1f, 0x80, 0x7f, 0x0f, 0x1e, 0xf8, 0x00,
0xf8, 0x1f, 0x78, 0x18, 0xf0, 0x01, 0x7c, 0x1e, 0xc0, 0x0f, 0x0f, 0x1e,
0x7c, 0x00, 0xf0, 0x0f, 0x78, 0x00, 0xf0, 0x01, 0x3e, 0x1e, 0xe0, 0x07,
0x0f, 0x1e, 0x7c, 0x00, 0xf0, 0x07, 0x7c, 0x00, 0xe0, 0x01, 0x3e, 0x1e,
0xe0, 0x03, 0x0f, 0x1e, 0x3e, 0x00, 0xf0, 0x0f, 0x7c, 0x00, 0xe0, 0x03,
0x3e, 0x3e, 0xe0, 0x07, 0x0f, 0x1e, 0x1e, 0x00, 0xf0, 0x1f, 0x3c, 0x00,
0xe0, 0x03, 0x7e, 0x3e, 0xc0, 0x3f, 0x0f, 0x1e, 0x3e, 0x00, 0xf0, 0x1f,
0x3e, 0x00, 0xe0, 0x03, 0xfc, 0x7f, 0x80, 0xff, 0x0f, 0x1e, 0xfc, 0x00,
0xf0, 0x3e, 0x3e, 0x00, 0xc0, 0x03, 0xf8, 0xff, 0x03, 0xff, 0x0f, 0x1e,
0xfc, 0x07, 0xf0, 0x7c, 0x1e, 0x00, 0xc0, 0x03, 0xf8, 0xff, 0x03, 0xfc,
0x0f, 0x1e, 0xf8, 0x1f, 0xf0, 0xf8, 0x1e, 0x00, 0xc0, 0x03, 0xe0, 0xf7,
0x03, 0xf0, 0x0f, 0x1e, 0xe0, 0x3f, 0xf0, 0x78, 0x1c, 0x00, 0x80, 0x03,
0x80, 0xe3, 0x03, 0x00, 0x0f, 0x1e, 0xc0, 0x3f, 0xf0, 0x30, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0f, 0x0e, 0x00, 0x3e, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x0f, 0x00, 0x00, 0x10,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x0f, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xc0,
0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0xe0, 0x07, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0xf0, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0xf8, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xfc, 0x00, 0x00, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7e, 0x00, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x3c,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
0x00, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00
};
int
id,
y;
register int
i;
static unsigned int
number_selections;
unsigned int
height;
size_t
state;
XFontStruct
*font_info;
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(display != (Display *) NULL);
assert(windows != (XWindows *) NULL);
font_info=windows->command.font_info;
height=(unsigned int) (font_info->ascent+font_info->descent);
id=(~0);
state=DefaultState;
if (event == (XEvent *) NULL)
{
unsigned int
width;
XTextProperty
window_name;
XWindowChanges
window_changes;
/*
Determine command window attributes.
*/
assert(selections != (const char **) NULL);
windows->command.width=0;
for (i=0; selections[i] != (char *) NULL; i++)
{
width=WidgetTextWidth(font_info,(char *) selections[i]);
if (width > windows->command.width)
windows->command.width=width;
}
number_selections=(unsigned int) i;
windows->command.width+=3*QuantumMargin+10;
if ((int) windows->command.width < (tile_width+QuantumMargin+10))
windows->command.width=(unsigned int) (tile_width+QuantumMargin+10);
windows->command.height=(unsigned int) (number_selections*
(((3*height) >> 1)+10)+tile_height+20);
windows->command.min_width=windows->command.width;
windows->command.min_height=windows->command.height;
XConstrainWindowPosition(display,&windows->command);
if (windows->command.id != (Window) NULL)
{
Status
status;
/*
Reconfigure command window.
*/
status=XStringListToTextProperty(&windows->command.name,1,
&window_name);
if (status != False)
{
XSetWMName(display,windows->command.id,&window_name);
XSetWMIconName(display,windows->command.id,&window_name);
(void) XFree((void *) window_name.value);
}
window_changes.width=(int) windows->command.width;
window_changes.height=(int) windows->command.height;
(void) XReconfigureWMWindow(display,windows->command.id,
windows->command.screen,(unsigned int) (CWWidth | CWHeight),
&window_changes);
}
/*
Allocate selection info memory.
*/
if (selection_info != (XWidgetInfo *) NULL)
selection_info=(XWidgetInfo *) RelinquishMagickMemory(selection_info);
selection_info=(XWidgetInfo *) AcquireQuantumMemory(number_selections,
sizeof(*selection_info));
if (selection_info == (XWidgetInfo *) NULL)
{
ThrowXWindowFatalException(ResourceLimitFatalError,
"MemoryAllocationFailed","...");
return(id);
}
state|=UpdateConfigurationState | RedrawWidgetState;
}
/*
Wait for next event.
*/
if (event != (XEvent *) NULL)
switch (event->type)
{
case ButtonPress:
{
for (i=0; i < (int) number_selections; i++)
{
if (MatteIsActive(selection_info[i],event->xbutton) == MagickFalse)
continue;
if (i >= (int) windows->command.data)
{
selection_info[i].raised=MagickFalse;
XDrawBeveledButton(display,&windows->command,&selection_info[i]);
break;
}
submenu_info=selection_info[i];
submenu_info.active=MagickTrue;
toggle_info.y=submenu_info.y+(submenu_info.height >> 1)-
(toggle_info.height >> 1);
id=i;
(void) XCheckWindowEvent(display,windows->widget.id,LeaveWindowMask,
event);
break;
}
break;
}
case ButtonRelease:
{
for (i=0; i < (int) number_selections; i++)
{
if (MatteIsActive(selection_info[i],event->xbutton) == MagickFalse)
continue;
id=i;
if (id >= (int) windows->command.data)
{
selection_info[id].raised=MagickTrue;
XDrawBeveledButton(display,&windows->command,&selection_info[id]);
break;
}
break;
}
break;
}
case ClientMessage:
{
/*
If client window delete message, withdraw command widget.
*/
if (event->xclient.message_type != windows->wm_protocols)
break;
if (*event->xclient.data.l != (int) windows->wm_delete_window)
break;
(void) XWithdrawWindow(display,windows->command.id,
windows->command.screen);
break;
}
case ConfigureNotify:
{
/*
Update widget configuration.
*/
if (event->xconfigure.window != windows->command.id)
break;
if (event->xconfigure.send_event != 0)
{
windows->command.x=event->xconfigure.x;
windows->command.y=event->xconfigure.y;
}
if ((event->xconfigure.width == (int) windows->command.width) &&
(event->xconfigure.height == (int) windows->command.height))
break;
windows->command.width=(unsigned int)
MagickMax(event->xconfigure.width,(int) windows->command.min_width);
windows->command.height=(unsigned int)
MagickMax(event->xconfigure.height,(int) windows->command.min_height);
state|=UpdateConfigurationState;
break;
}
case Expose:
{
if (event->xexpose.window != windows->command.id)
break;
if (event->xexpose.count != 0)
break;
state|=RedrawWidgetState;
break;
}
case MotionNotify:
{
/*
Return the ID of the highlighted menu entry.
*/
for ( ; ; )
{
for (i=0; i < (int) number_selections; i++)
{
if (i >= (int) windows->command.data)
{
if (selection_info[i].raised ==
MatteIsActive(selection_info[i],event->xmotion))
{
/*
Button status changed.
*/
selection_info[i].raised=!selection_info[i].raised;
XDrawBeveledButton(display,&windows->command,
&selection_info[i]);
}
continue;
}
if (MatteIsActive(selection_info[i],event->xmotion) == MagickFalse)
continue;
submenu_info=selection_info[i];
submenu_info.active=MagickTrue;
toggle_info.raised=MagickTrue;
toggle_info.y=submenu_info.y+(submenu_info.height >> 1)-
(toggle_info.height >> 1);
XDrawTriangleEast(display,&windows->command,&toggle_info);
id=i;
}
XDelay(display,SuspendTime);
if (XCheckMaskEvent(display,ButtonMotionMask,event) == MagickFalse)
break;
while (XCheckMaskEvent(display,ButtonMotionMask,event)) ;
toggle_info.raised=MagickFalse;
if (windows->command.data != 0)
XDrawTriangleEast(display,&windows->command,&toggle_info);
}
break;
}
case MapNotify:
{
windows->command.mapped=MagickTrue;
break;
}
case UnmapNotify:
{
windows->command.mapped=MagickFalse;
break;
}
default:
break;
}
if (state & UpdateConfigurationState)
{
/*
Initialize button information.
*/
assert(selections != (const char **) NULL);
y=tile_height+20;
for (i=0; i < (int) number_selections; i++)
{
XGetWidgetInfo(selections[i],&selection_info[i]);
selection_info[i].center=MagickFalse;
selection_info[i].bevel_width--;
selection_info[i].height=(unsigned int) ((3*height) >> 1);
selection_info[i].x=(QuantumMargin >> 1)+4;
selection_info[i].width=(unsigned int) (windows->command.width-
(selection_info[i].x << 1));
selection_info[i].y=y;
y+=selection_info[i].height+(selection_info[i].bevel_width << 1)+6;
}
XGetWidgetInfo((char *) NULL,&toggle_info);
toggle_info.bevel_width--;
toggle_info.width=(unsigned int) (((5*height) >> 3)-
(toggle_info.bevel_width << 1));
toggle_info.height=toggle_info.width;
toggle_info.x=selection_info[0].x+selection_info[0].width-
toggle_info.width-(QuantumMargin >> 1);
if (windows->command.mapped)
(void) XClearWindow(display,windows->command.id);
}
if (state & RedrawWidgetState)
{
Pixmap
tile_pixmap;
/*
Draw command buttons.
*/
tile_pixmap=XCreatePixmapFromBitmapData(display,windows->command.id,
(char *) tile_bits,tile_width,tile_height,1L,0L,1);
if (tile_pixmap != (Pixmap) NULL)
{
(void) XCopyPlane(display,tile_pixmap,windows->command.id,
windows->command.annotate_context,0,0,tile_width,tile_height,
(int) ((windows->command.width-tile_width) >> 1),10,1L);
(void) XFreePixmap(display,tile_pixmap);
}
for (i=0; i < (int) number_selections; i++)
{
XDrawBeveledButton(display,&windows->command,&selection_info[i]);
if (i >= (int) windows->command.data)
continue;
toggle_info.raised=MagickFalse;
toggle_info.y=selection_info[i].y+(selection_info[i].height >> 1)-
(toggle_info.height >> 1);
XDrawTriangleEast(display,&windows->command,&toggle_info);
}
XHighlightWidget(display,&windows->command,BorderOffset,BorderOffset);
}
return(id);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% X C o n f i r m W i d g e t %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% XConfirmWidget() displays a Confirm widget with a notice to the user. The
% function returns -1 if Dismiss is pressed, 0 for Cancel, and 1 for Yes.
%
% The format of the XConfirmWidget method is:
%
% int XConfirmWidget(Display *display,XWindows *windows,
% const char *reason,const char *description)
%
% A description of each parameter follows:
%
% o display: Specifies a connection to an X server; returned from
% XOpenDisplay.
%
% o window: Specifies a pointer to a XWindows structure.
%
% o reason: Specifies the message to display before terminating the
% program.
%
% o description: Specifies any description to the message.
%
*/
MagickPrivate int XConfirmWidget(Display *display,XWindows *windows,
const char *reason,const char *description)
{
#define CancelButtonText "Cancel"
#define DismissButtonText "Dismiss"
#define YesButtonText "Yes"
int
confirm,
x,
y;
Status
status;
unsigned int
height,
width;
size_t
state;
XEvent
event;
XFontStruct
*font_info;
XTextProperty
window_name;
XWidgetInfo
cancel_info,
dismiss_info,
yes_info;
XWindowChanges
window_changes;
/*
Determine Confirm widget attributes.
*/
assert(display != (Display *) NULL);
assert(windows != (XWindows *) NULL);
assert(reason != (char *) NULL);
assert(description != (char *) NULL);
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",reason);
XCheckRefreshWindows(display,windows);
font_info=windows->widget.font_info;
width=WidgetTextWidth(font_info,CancelButtonText);
if (WidgetTextWidth(font_info,DismissButtonText) > width)
width=WidgetTextWidth(font_info,DismissButtonText);
if (WidgetTextWidth(font_info,YesButtonText) > width)
width=WidgetTextWidth(font_info,YesButtonText);
width<<=1;
if (description != (char *) NULL)
if (WidgetTextWidth(font_info,(char *) description) > width)
width=WidgetTextWidth(font_info,(char *) description);
height=(unsigned int) (font_info->ascent+font_info->descent);
/*
Position Confirm widget.
*/
windows->widget.width=(unsigned int) (width+9*QuantumMargin);
windows->widget.min_width=(unsigned int) (9*QuantumMargin+
WidgetTextWidth(font_info,CancelButtonText)+
WidgetTextWidth(font_info,DismissButtonText)+
WidgetTextWidth(font_info,YesButtonText));
if (windows->widget.width < windows->widget.min_width)
windows->widget.width=windows->widget.min_width;
windows->widget.height=(unsigned int) (12*height);
windows->widget.min_height=(unsigned int) (7*height);
if (windows->widget.height < windows->widget.min_height)
windows->widget.height=windows->widget.min_height;
XConstrainWindowPosition(display,&windows->widget);
/*
Map Confirm widget.
*/
(void) CopyMagickString(windows->widget.name,"Confirm",MagickPathExtent);
status=XStringListToTextProperty(&windows->widget.name,1,&window_name);
if (status != False)
{
XSetWMName(display,windows->widget.id,&window_name);
XSetWMIconName(display,windows->widget.id,&window_name);
(void) XFree((void *) window_name.value);
}
window_changes.width=(int) windows->widget.width;
window_changes.height=(int) windows->widget.height;
window_changes.x=windows->widget.x;
window_changes.y=windows->widget.y;
(void) XReconfigureWMWindow(display,windows->widget.id,windows->widget.screen,
(unsigned int) (CWWidth | CWHeight | CWX | CWY),&window_changes);
(void) XMapRaised(display,windows->widget.id);
windows->widget.mapped=MagickFalse;
/*
Respond to X events.
*/
confirm=0;
state=UpdateConfigurationState;
XSetCursorState(display,windows,MagickTrue);
do
{
if (state & UpdateConfigurationState)
{
/*
Initialize button information.
*/
XGetWidgetInfo(CancelButtonText,&cancel_info);
cancel_info.width=(unsigned int) QuantumMargin+
WidgetTextWidth(font_info,CancelButtonText);
cancel_info.height=(unsigned int) ((3*height) >> 1);
cancel_info.x=(int) (windows->widget.width-cancel_info.width-
QuantumMargin);
cancel_info.y=(int) (windows->widget.height-(cancel_info.height << 1));
dismiss_info=cancel_info;
dismiss_info.text=(char *) DismissButtonText;
if (LocaleCompare(description,"Do you want to save it") == 0)
dismiss_info.text=(char *) "Don't Save";
dismiss_info.width=(unsigned int) QuantumMargin+
WidgetTextWidth(font_info,dismiss_info.text);
dismiss_info.x=(int)
((windows->widget.width >> 1)-(dismiss_info.width >> 1));
yes_info=cancel_info;
yes_info.text=(char *) YesButtonText;
if (LocaleCompare(description,"Do you want to save it") == 0)
yes_info.text=(char *) "Save";
yes_info.width=(unsigned int) QuantumMargin+
WidgetTextWidth(font_info,yes_info.text);
if (yes_info.width < cancel_info.width)
yes_info.width=cancel_info.width;
yes_info.x=QuantumMargin;
state&=(~UpdateConfigurationState);
}
if (state & RedrawWidgetState)
{
/*
Redraw Confirm widget.
*/
width=WidgetTextWidth(font_info,(char *) reason);
x=(int) ((windows->widget.width >> 1)-(width >> 1));
y=(int) ((windows->widget.height >> 1)-(height << 1));
(void) XDrawString(display,windows->widget.id,
windows->widget.annotate_context,x,y,(char *) reason,Extent(reason));
if (description != (char *) NULL)
{
char
question[MagickPathExtent];
(void) CopyMagickString(question,description,MagickPathExtent);
(void) ConcatenateMagickString(question,"?",MagickPathExtent);
width=WidgetTextWidth(font_info,question);
x=(int) ((windows->widget.width >> 1)-(width >> 1));
y+=height;
(void) XDrawString(display,windows->widget.id,
windows->widget.annotate_context,x,y,question,Extent(question));
}
XDrawBeveledButton(display,&windows->widget,&cancel_info);
XDrawBeveledButton(display,&windows->widget,&dismiss_info);
XDrawBeveledButton(display,&windows->widget,&yes_info);
XHighlightWidget(display,&windows->widget,BorderOffset,BorderOffset);
state&=(~RedrawWidgetState);
}
/*
Wait for next event.
*/
(void) XIfEvent(display,&event,XScreenEvent,(char *) windows);
switch (event.type)
{
case ButtonPress:
{
if (MatteIsActive(cancel_info,event.xbutton))
{
/*
User pressed No button.
*/
cancel_info.raised=MagickFalse;
XDrawBeveledButton(display,&windows->widget,&cancel_info);
break;
}
if (MatteIsActive(dismiss_info,event.xbutton))
{
/*
User pressed Dismiss button.
*/
dismiss_info.raised=MagickFalse;
XDrawBeveledButton(display,&windows->widget,&dismiss_info);
break;
}
if (MatteIsActive(yes_info,event.xbutton))
{
/*
User pressed Yes button.
*/
yes_info.raised=MagickFalse;
XDrawBeveledButton(display,&windows->widget,&yes_info);
break;
}
break;
}
case ButtonRelease:
{
if (windows->widget.mapped == MagickFalse)
break;
if (cancel_info.raised == MagickFalse)
{
if (event.xbutton.window == windows->widget.id)
if (MatteIsActive(cancel_info,event.xbutton))
{
confirm=0;
state|=ExitState;
}
cancel_info.raised=MagickTrue;
XDrawBeveledButton(display,&windows->widget,&cancel_info);
}
if (dismiss_info.raised == MagickFalse)
{
if (event.xbutton.window == windows->widget.id)
if (MatteIsActive(dismiss_info,event.xbutton))
{
confirm=(-1);
state|=ExitState;
}
dismiss_info.raised=MagickTrue;
XDrawBeveledButton(display,&windows->widget,&dismiss_info);
}
if (yes_info.raised == MagickFalse)
{
if (event.xbutton.window == windows->widget.id)
if (MatteIsActive(yes_info,event.xbutton))
{
confirm=1;
state|=ExitState;
}
yes_info.raised=MagickTrue;
XDrawBeveledButton(display,&windows->widget,&yes_info);
}
break;
}
case ClientMessage:
{
/*
If client window delete message, exit.
*/
if (event.xclient.message_type != windows->wm_protocols)
break;
if (*event.xclient.data.l == (int) windows->wm_take_focus)
{
(void) XSetInputFocus(display,event.xclient.window,RevertToParent,
(Time) event.xclient.data.l[1]);
break;
}
if (*event.xclient.data.l != (int) windows->wm_delete_window)
break;
if (event.xclient.window == windows->widget.id)
{
state|=ExitState;
break;
}
break;
}
case ConfigureNotify:
{
/*
Update widget configuration.
*/
if (event.xconfigure.window != windows->widget.id)
break;
if ((event.xconfigure.width == (int) windows->widget.width) &&
(event.xconfigure.height == (int) windows->widget.height))
break;
windows->widget.width=(unsigned int)
MagickMax(event.xconfigure.width,(int) windows->widget.min_width);
windows->widget.height=(unsigned int)
MagickMax(event.xconfigure.height,(int) windows->widget.min_height);
state|=UpdateConfigurationState;
break;
}
case EnterNotify:
{
if (event.xcrossing.window != windows->widget.id)
break;
state&=(~InactiveWidgetState);
break;
}
case Expose:
{
if (event.xexpose.window != windows->widget.id)
break;
if (event.xexpose.count != 0)
break;
state|=RedrawWidgetState;
break;
}
case KeyPress:
{
static char
command[MagickPathExtent];
static KeySym
key_symbol;
/*
Respond to a user key press.
*/
if (event.xkey.window != windows->widget.id)
break;
(void) XLookupString((XKeyEvent *) &event.xkey,command,
(int) sizeof(command),&key_symbol,(XComposeStatus *) NULL);
if ((key_symbol == XK_Return) || (key_symbol == XK_KP_Enter))
{
yes_info.raised=MagickFalse;
XDrawBeveledButton(display,&windows->widget,&yes_info);
confirm=1;
state|=ExitState;
break;
}
break;
}
case LeaveNotify:
{
if (event.xcrossing.window != windows->widget.id)
break;
state|=InactiveWidgetState;
break;
}
case MotionNotify:
{
/*
Discard pending button motion events.
*/
while (XCheckMaskEvent(display,ButtonMotionMask,&event)) ;
if (state & InactiveWidgetState)
break;
if (cancel_info.raised == MatteIsActive(cancel_info,event.xmotion))
{
/*
Cancel button status changed.
*/
cancel_info.raised=cancel_info.raised == MagickFalse ?
MagickTrue : MagickFalse;
XDrawBeveledButton(display,&windows->widget,&cancel_info);
break;
}
if (dismiss_info.raised == MatteIsActive(dismiss_info,event.xmotion))
{
/*
Dismiss button status changed.
*/
dismiss_info.raised=dismiss_info.raised == MagickFalse ?
MagickTrue : MagickFalse;
XDrawBeveledButton(display,&windows->widget,&dismiss_info);
break;
}
if (yes_info.raised == MatteIsActive(yes_info,event.xmotion))
{
/*
Yes button status changed.
*/
yes_info.raised=yes_info.raised == MagickFalse ?
MagickTrue : MagickFalse;
XDrawBeveledButton(display,&windows->widget,&yes_info);
break;
}
break;
}
default:
break;
}
} while ((state & ExitState) == 0);
XSetCursorState(display,windows,MagickFalse);
(void) XWithdrawWindow(display,windows->widget.id,windows->widget.screen);
XCheckRefreshWindows(display,windows);
return(confirm);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% X D i a l o g W i d g e t %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% XDialogWidget() displays a Dialog widget with a query to the user. The user
% keys a reply and presses the Ok or Cancel button to exit. The typed text is
% returned as the reply function parameter.
%
% The format of the XDialogWidget method is:
%
% int XDialogWidget(Display *display,XWindows *windows,const char *action,
% const char *query,char *reply)
%
% A description of each parameter follows:
%
% o display: Specifies a connection to an X server; returned from
% XOpenDisplay.
%
% o window: Specifies a pointer to a XWindows structure.
%
% o action: Specifies a pointer to the action of this widget.
%
% o query: Specifies a pointer to the query to present to the user.
%
% o reply: the response from the user is returned in this parameter.
%
*/
MagickPrivate int XDialogWidget(Display *display,XWindows *windows,
const char *action,const char *query,char *reply)
{
#define CancelButtonText "Cancel"
char
primary_selection[MagickPathExtent];
int
x;
register int
i;
static MagickBooleanType
raised = MagickFalse;
Status
status;
unsigned int
anomaly,
height,
width;
size_t
state;
XEvent
event;
XFontStruct
*font_info;
XTextProperty
window_name;
XWidgetInfo
action_info,
cancel_info,
reply_info,
special_info,
text_info;
XWindowChanges
window_changes;
/*
Determine Dialog widget attributes.
*/
assert(display != (Display *) NULL);
assert(windows != (XWindows *) NULL);
assert(action != (char *) NULL);
assert(query != (char *) NULL);
assert(reply != (char *) NULL);
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",action);
XCheckRefreshWindows(display,windows);
font_info=windows->widget.font_info;
width=WidgetTextWidth(font_info,(char *) action);
if (WidgetTextWidth(font_info,CancelButtonText) > width)
width=WidgetTextWidth(font_info,CancelButtonText);
width+=(3*QuantumMargin) >> 1;
height=(unsigned int) (font_info->ascent+font_info->descent);
/*
Position Dialog widget.
*/
windows->widget.width=(unsigned int) MagickMax((int) (2*width),(int)
WidgetTextWidth(font_info,(char *) query));
if (windows->widget.width < WidgetTextWidth(font_info,reply))
windows->widget.width=WidgetTextWidth(font_info,reply);
windows->widget.width+=6*QuantumMargin;
windows->widget.min_width=(unsigned int)
(width+28*XTextWidth(font_info,"#",1)+4*QuantumMargin);
if (windows->widget.width < windows->widget.min_width)
windows->widget.width=windows->widget.min_width;
windows->widget.height=(unsigned int) (7*height+(QuantumMargin << 1));
windows->widget.min_height=windows->widget.height;
if (windows->widget.height < windows->widget.min_height)
windows->widget.height=windows->widget.min_height;
XConstrainWindowPosition(display,&windows->widget);
/*
Map Dialog widget.
*/
(void) CopyMagickString(windows->widget.name,"Dialog",MagickPathExtent);
status=XStringListToTextProperty(&windows->widget.name,1,&window_name);
if (status != False)
{
XSetWMName(display,windows->widget.id,&window_name);
XSetWMIconName(display,windows->widget.id,&window_name);
(void) XFree((void *) window_name.value);
}
window_changes.width=(int) windows->widget.width;
window_changes.height=(int) windows->widget.height;
window_changes.x=windows->widget.x;
window_changes.y=windows->widget.y;
(void) XReconfigureWMWindow(display,windows->widget.id,windows->widget.screen,
(unsigned int) (CWWidth | CWHeight | CWX | CWY),&window_changes);
(void) XMapRaised(display,windows->widget.id);
windows->widget.mapped=MagickFalse;
/*
Respond to X events.
*/
anomaly=(LocaleCompare(action,"Background") == 0) ||
(LocaleCompare(action,"New") == 0) ||
(LocaleCompare(action,"Quantize") == 0) ||
(LocaleCompare(action,"Resize") == 0) ||
(LocaleCompare(action,"Save") == 0) ||
(LocaleCompare(action,"Shade") == 0);
state=UpdateConfigurationState;
XSetCursorState(display,windows,MagickTrue);
do
{
if (state & UpdateConfigurationState)
{
/*
Initialize button information.
*/
XGetWidgetInfo(CancelButtonText,&cancel_info);
cancel_info.width=width;
cancel_info.height=(unsigned int) ((3*height) >> 1);
cancel_info.x=(int)
(windows->widget.width-cancel_info.width-((3*QuantumMargin) >> 1));
cancel_info.y=(int)
(windows->widget.height-cancel_info.height-((3*QuantumMargin) >> 1));
XGetWidgetInfo(action,&action_info);
action_info.width=width;
action_info.height=(unsigned int) ((3*height) >> 1);
action_info.x=cancel_info.x-(cancel_info.width+QuantumMargin+
(action_info.bevel_width << 1));
action_info.y=cancel_info.y;
/*
Initialize reply information.
*/
XGetWidgetInfo(reply,&reply_info);
reply_info.raised=MagickFalse;
reply_info.bevel_width--;
reply_info.width=windows->widget.width-(3*QuantumMargin);
reply_info.height=height << 1;
reply_info.x=(3*QuantumMargin) >> 1;
reply_info.y=action_info.y-reply_info.height-QuantumMargin;
/*
Initialize option information.
*/
XGetWidgetInfo("Dither",&special_info);
special_info.raised=raised;
special_info.bevel_width--;
special_info.width=(unsigned int) QuantumMargin >> 1;
special_info.height=(unsigned int) QuantumMargin >> 1;
special_info.x=reply_info.x;
special_info.y=action_info.y+action_info.height-special_info.height;
if (LocaleCompare(action,"Background") == 0)
special_info.text=(char *) "Backdrop";
if (LocaleCompare(action,"New") == 0)
special_info.text=(char *) "Gradation";
if (LocaleCompare(action,"Resize") == 0)
special_info.text=(char *) "Constrain ratio";
if (LocaleCompare(action,"Save") == 0)
special_info.text=(char *) "Non-progressive";
if (LocaleCompare(action,"Shade") == 0)
special_info.text=(char *) "Color shading";
/*
Initialize text information.
*/
XGetWidgetInfo(query,&text_info);
text_info.width=reply_info.width;
text_info.height=height;
text_info.x=reply_info.x-(QuantumMargin >> 1);
text_info.y=QuantumMargin;
text_info.center=MagickFalse;
state&=(~UpdateConfigurationState);
}
if (state & RedrawWidgetState)
{
/*
Redraw Dialog widget.
*/
XDrawWidgetText(display,&windows->widget,&text_info);
XDrawBeveledMatte(display,&windows->widget,&reply_info);
XDrawMatteText(display,&windows->widget,&reply_info);
if (anomaly)
XDrawBeveledButton(display,&windows->widget,&special_info);
XDrawBeveledButton(display,&windows->widget,&action_info);
XDrawBeveledButton(display,&windows->widget,&cancel_info);
XHighlightWidget(display,&windows->widget,BorderOffset,BorderOffset);
state&=(~RedrawWidgetState);
}
/*
Wait for next event.
*/
(void) XIfEvent(display,&event,XScreenEvent,(char *) windows);
switch (event.type)
{
case ButtonPress:
{
if (anomaly)
if (MatteIsActive(special_info,event.xbutton))
{
/*
Option button status changed.
*/
special_info.raised=!special_info.raised;
XDrawBeveledButton(display,&windows->widget,&special_info);
break;
}
if (MatteIsActive(action_info,event.xbutton))
{
/*
User pressed Action button.
*/
action_info.raised=MagickFalse;
XDrawBeveledButton(display,&windows->widget,&action_info);
break;
}
if (MatteIsActive(cancel_info,event.xbutton))
{
/*
User pressed Cancel button.
*/
cancel_info.raised=MagickFalse;
XDrawBeveledButton(display,&windows->widget,&cancel_info);
break;
}
if (MatteIsActive(reply_info,event.xbutton) == MagickFalse)
break;
if (event.xbutton.button != Button2)
{
static Time
click_time;
/*
Move text cursor to position of button press.
*/
x=event.xbutton.x-reply_info.x-(QuantumMargin >> 2);
for (i=1; i <= Extent(reply_info.marker); i++)
if (XTextWidth(font_info,reply_info.marker,i) > x)
break;
reply_info.cursor=reply_info.marker+i-1;
if (event.xbutton.time > (click_time+DoubleClick))
reply_info.highlight=MagickFalse;
else
{
/*
Become the XA_PRIMARY selection owner.
*/
(void) CopyMagickString(primary_selection,reply_info.text,
MagickPathExtent);
(void) XSetSelectionOwner(display,XA_PRIMARY,windows->widget.id,
event.xbutton.time);
reply_info.highlight=XGetSelectionOwner(display,XA_PRIMARY) ==
windows->widget.id ? MagickTrue : MagickFalse;
}
XDrawMatteText(display,&windows->widget,&reply_info);
click_time=event.xbutton.time;
break;
}
/*
Request primary selection.
*/
(void) XConvertSelection(display,XA_PRIMARY,XA_STRING,XA_STRING,
windows->widget.id,event.xbutton.time);
break;
}
case ButtonRelease:
{
if (windows->widget.mapped == MagickFalse)
break;
if (action_info.raised == MagickFalse)
{
if (event.xbutton.window == windows->widget.id)
if (MatteIsActive(action_info,event.xbutton))
state|=ExitState;
action_info.raised=MagickTrue;
XDrawBeveledButton(display,&windows->widget,&action_info);
}
if (cancel_info.raised == MagickFalse)
{
if (event.xbutton.window == windows->widget.id)
if (MatteIsActive(cancel_info,event.xbutton))
{
*reply_info.text='\0';
state|=ExitState;
}
cancel_info.raised=MagickTrue;
XDrawBeveledButton(display,&windows->widget,&cancel_info);
}
break;
}
case ClientMessage:
{
/*
If client window delete message, exit.
*/
if (event.xclient.message_type != windows->wm_protocols)
break;
if (*event.xclient.data.l == (int) windows->wm_take_focus)
{
(void) XSetInputFocus(display,event.xclient.window,RevertToParent,
(Time) event.xclient.data.l[1]);
break;
}
if (*event.xclient.data.l != (int) windows->wm_delete_window)
break;
if (event.xclient.window == windows->widget.id)
{
*reply_info.text='\0';
state|=ExitState;
break;
}
break;
}
case ConfigureNotify:
{
/*
Update widget configuration.
*/
if (event.xconfigure.window != windows->widget.id)
break;
if ((event.xconfigure.width == (int) windows->widget.width) &&
(event.xconfigure.height == (int) windows->widget.height))
break;
windows->widget.width=(unsigned int)
MagickMax(event.xconfigure.width,(int) windows->widget.min_width);
windows->widget.height=(unsigned int)
MagickMax(event.xconfigure.height,(int) windows->widget.min_height);
state|=UpdateConfigurationState;
break;
}
case EnterNotify:
{
if (event.xcrossing.window != windows->widget.id)
break;
state&=(~InactiveWidgetState);
break;
}
case Expose:
{
if (event.xexpose.window != windows->widget.id)
break;
if (event.xexpose.count != 0)
break;
state|=RedrawWidgetState;
break;
}
case KeyPress:
{
static char
command[MagickPathExtent];
static int
length;
static KeySym
key_symbol;
/*
Respond to a user key press.
*/
if (event.xkey.window != windows->widget.id)
break;
length=XLookupString((XKeyEvent *) &event.xkey,command,
(int) sizeof(command),&key_symbol,(XComposeStatus *) NULL);
*(command+length)='\0';
if ((key_symbol == XK_Return) || (key_symbol == XK_KP_Enter))
{
action_info.raised=MagickFalse;
XDrawBeveledButton(display,&windows->widget,&action_info);
state|=ExitState;
break;
}
if (key_symbol == XK_Control_L)
{
state|=ControlState;
break;
}
if (state & ControlState)
switch ((int) key_symbol)
{
case XK_u:
case XK_U:
{
/*
Erase the entire line of text.
*/
*reply_info.text='\0';
reply_info.cursor=reply_info.text;
reply_info.marker=reply_info.text;
reply_info.highlight=MagickFalse;
break;
}
default:
break;
}
XEditText(display,&reply_info,key_symbol,command,state);
XDrawMatteText(display,&windows->widget,&reply_info);
break;
}
case KeyRelease:
{
static char
command[MagickPathExtent];
static KeySym
key_symbol;
/*
Respond to a user key release.
*/
if (event.xkey.window != windows->widget.id)
break;
(void) XLookupString((XKeyEvent *) &event.xkey,command,
(int) sizeof(command),&key_symbol,(XComposeStatus *) NULL);
if (key_symbol == XK_Control_L)
state&=(~ControlState);
break;
}
case LeaveNotify:
{
if (event.xcrossing.window != windows->widget.id)
break;
state|=InactiveWidgetState;
break;
}
case MotionNotify:
{
/*
Discard pending button motion events.
*/
while (XCheckMaskEvent(display,ButtonMotionMask,&event)) ;
if (state & InactiveWidgetState)
break;
if (action_info.raised == MatteIsActive(action_info,event.xmotion))
{
/*
Action button status changed.
*/
action_info.raised=action_info.raised == MagickFalse ?
MagickTrue : MagickFalse;
XDrawBeveledButton(display,&windows->widget,&action_info);
break;
}
if (cancel_info.raised == MatteIsActive(cancel_info,event.xmotion))
{
/*
Cancel button status changed.
*/
cancel_info.raised=cancel_info.raised == MagickFalse ?
MagickTrue : MagickFalse;
XDrawBeveledButton(display,&windows->widget,&cancel_info);
break;
}
break;
}
case SelectionClear:
{
reply_info.highlight=MagickFalse;
XDrawMatteText(display,&windows->widget,&reply_info);
break;
}
case SelectionNotify:
{
Atom
type;
int
format;
unsigned char
*data;
unsigned long
after,
length;
/*
Obtain response from primary selection.
*/
if (event.xselection.property == (Atom) None)
break;
status=XGetWindowProperty(display,event.xselection.requestor,
event.xselection.property,0L,2047L,MagickTrue,XA_STRING,&type,
&format,&length,&after,&data);
if ((status != Success) || (type != XA_STRING) || (format == 32) ||
(length == 0))
break;
if ((Extent(reply_info.text)+length) >= (MagickPathExtent-1))
(void) XBell(display,0);
else
{
/*
Insert primary selection in reply text.
*/
*(data+length)='\0';
XEditText(display,&reply_info,(KeySym) XK_Insert,(char *) data,
state);
XDrawMatteText(display,&windows->widget,&reply_info);
}
(void) XFree((void *) data);
break;
}
case SelectionRequest:
{
XSelectionEvent
notify;
XSelectionRequestEvent
*request;
if (reply_info.highlight == MagickFalse)
break;
/*
Set primary selection.
*/
request=(&(event.xselectionrequest));
(void) XChangeProperty(request->display,request->requestor,
request->property,request->target,8,PropModeReplace,
(unsigned char *) primary_selection,Extent(primary_selection));
notify.type=SelectionNotify;
notify.display=request->display;
notify.requestor=request->requestor;
notify.selection=request->selection;
notify.target=request->target;
notify.time=request->time;
if (request->property == None)
notify.property=request->target;
else
notify.property=request->property;
(void) XSendEvent(request->display,request->requestor,False,0,
(XEvent *) ¬ify);
}
default:
break;
}
} while ((state & ExitState) == 0);
XSetCursorState(display,windows,MagickFalse);
(void) XWithdrawWindow(display,windows->widget.id,windows->widget.screen);
XCheckRefreshWindows(display,windows);
if (anomaly)
if (special_info.raised)
if (*reply != '\0')
raised=MagickTrue;
return(raised == MagickFalse);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% X F i l e B r o w s e r W i d g e t %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% XFileBrowserWidget() displays a File Browser widget with a file query to the
% user. The user keys a reply and presses the Action or Cancel button to
% exit. The typed text is returned as the reply function parameter.
%
% The format of the XFileBrowserWidget method is:
%
% void XFileBrowserWidget(Display *display,XWindows *windows,
% const char *action,char *reply)
%
% A description of each parameter follows:
%
% o display: Specifies a connection to an X server; returned from
% XOpenDisplay.
%
% o window: Specifies a pointer to a XWindows structure.
%
% o action: Specifies a pointer to the action of this widget.
%
% o reply: the response from the user is returned in this parameter.
%
*/
MagickPrivate void XFileBrowserWidget(Display *display,XWindows *windows,
const char *action,char *reply)
{
#define CancelButtonText "Cancel"
#define DirectoryText "Directory:"
#define FilenameText "File name:"
#define GrabButtonText "Grab"
#define FormatButtonText "Format"
#define HomeButtonText "Home"
#define UpButtonText "Up"
char
*directory,
**filelist,
home_directory[MagickPathExtent],
primary_selection[MagickPathExtent],
text[MagickPathExtent],
working_path[MagickPathExtent];
int
x,
y;
register ssize_t
i;
static char
glob_pattern[MagickPathExtent] = "*",
format[MagickPathExtent] = "miff";
static MagickStatusType
mask = (MagickStatusType) (CWWidth | CWHeight | CWX | CWY);
Status
status;
unsigned int
anomaly,
height,
text_width,
visible_files,
width;
size_t
delay,
files,
state;
XEvent
event;
XFontStruct
*font_info;
XTextProperty
window_name;
XWidgetInfo
action_info,
cancel_info,
expose_info,
special_info,
list_info,
home_info,
north_info,
reply_info,
scroll_info,
selection_info,
slider_info,
south_info,
text_info,
up_info;
XWindowChanges
window_changes;
/*
Read filelist from current directory.
*/
assert(display != (Display *) NULL);
assert(windows != (XWindows *) NULL);
assert(action != (char *) NULL);
assert(reply != (char *) NULL);
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",action);
XSetCursorState(display,windows,MagickTrue);
XCheckRefreshWindows(display,windows);
directory=getcwd(home_directory,MagickPathExtent);
(void) directory;
(void) CopyMagickString(working_path,home_directory,MagickPathExtent);
filelist=ListFiles(working_path,glob_pattern,&files);
if (filelist == (char **) NULL)
{
/*
Directory read failed.
*/
XNoticeWidget(display,windows,"Unable to read directory:",working_path);
(void) XDialogWidget(display,windows,action,"Enter filename:",reply);
return;
}
/*
Determine File Browser widget attributes.
*/
font_info=windows->widget.font_info;
text_width=0;
for (i=0; i < (ssize_t) files; i++)
if (WidgetTextWidth(font_info,filelist[i]) > text_width)
text_width=WidgetTextWidth(font_info,filelist[i]);
width=WidgetTextWidth(font_info,(char *) action);
if (WidgetTextWidth(font_info,GrabButtonText) > width)
width=WidgetTextWidth(font_info,GrabButtonText);
if (WidgetTextWidth(font_info,FormatButtonText) > width)
width=WidgetTextWidth(font_info,FormatButtonText);
if (WidgetTextWidth(font_info,CancelButtonText) > width)
width=WidgetTextWidth(font_info,CancelButtonText);
if (WidgetTextWidth(font_info,HomeButtonText) > width)
width=WidgetTextWidth(font_info,HomeButtonText);
if (WidgetTextWidth(font_info,UpButtonText) > width)
width=WidgetTextWidth(font_info,UpButtonText);
width+=QuantumMargin;
if (WidgetTextWidth(font_info,DirectoryText) > width)
width=WidgetTextWidth(font_info,DirectoryText);
if (WidgetTextWidth(font_info,FilenameText) > width)
width=WidgetTextWidth(font_info,FilenameText);
height=(unsigned int) (font_info->ascent+font_info->descent);
/*
Position File Browser widget.
*/
windows->widget.width=width+MagickMin((int) text_width,(int) MaxTextWidth)+
6*QuantumMargin;
windows->widget.min_width=width+MinTextWidth+4*QuantumMargin;
if (windows->widget.width < windows->widget.min_width)
windows->widget.width=windows->widget.min_width;
windows->widget.height=(unsigned int)
(((81*height) >> 2)+((13*QuantumMargin) >> 1)+4);
windows->widget.min_height=(unsigned int)
(((23*height) >> 1)+((13*QuantumMargin) >> 1)+4);
if (windows->widget.height < windows->widget.min_height)
windows->widget.height=windows->widget.min_height;
XConstrainWindowPosition(display,&windows->widget);
/*
Map File Browser widget.
*/
(void) CopyMagickString(windows->widget.name,"Browse and Select a File",
MagickPathExtent);
status=XStringListToTextProperty(&windows->widget.name,1,&window_name);
if (status != False)
{
XSetWMName(display,windows->widget.id,&window_name);
XSetWMIconName(display,windows->widget.id,&window_name);
(void) XFree((void *) window_name.value);
}
window_changes.width=(int) windows->widget.width;
window_changes.height=(int) windows->widget.height;
window_changes.x=windows->widget.x;
window_changes.y=windows->widget.y;
(void) XReconfigureWMWindow(display,windows->widget.id,
windows->widget.screen,mask,&window_changes);
(void) XMapRaised(display,windows->widget.id);
windows->widget.mapped=MagickFalse;
/*
Respond to X events.
*/
XGetWidgetInfo((char *) NULL,&slider_info);
XGetWidgetInfo((char *) NULL,&north_info);
XGetWidgetInfo((char *) NULL,&south_info);
XGetWidgetInfo((char *) NULL,&expose_info);
visible_files=0;
anomaly=(LocaleCompare(action,"Composite") == 0) ||
(LocaleCompare(action,"Open") == 0) || (LocaleCompare(action,"Map") == 0);
*reply='\0';
delay=SuspendTime << 2;
state=UpdateConfigurationState;
do
{
if (state & UpdateConfigurationState)
{
int
id;
/*
Initialize button information.
*/
XGetWidgetInfo(CancelButtonText,&cancel_info);
cancel_info.width=width;
cancel_info.height=(unsigned int) ((3*height) >> 1);
cancel_info.x=(int)
(windows->widget.width-cancel_info.width-QuantumMargin-2);
cancel_info.y=(int)
(windows->widget.height-cancel_info.height-QuantumMargin);
XGetWidgetInfo(action,&action_info);
action_info.width=width;
action_info.height=(unsigned int) ((3*height) >> 1);
action_info.x=cancel_info.x-(cancel_info.width+(QuantumMargin >> 1)+
(action_info.bevel_width << 1));
action_info.y=cancel_info.y;
XGetWidgetInfo(GrabButtonText,&special_info);
special_info.width=width;
special_info.height=(unsigned int) ((3*height) >> 1);
special_info.x=action_info.x-(action_info.width+(QuantumMargin >> 1)+
(special_info.bevel_width << 1));
special_info.y=action_info.y;
if (anomaly == MagickFalse)
{
register char
*p;
special_info.text=(char *) FormatButtonText;
p=reply+Extent(reply)-1;
while ((p > (reply+1)) && (*(p-1) != '.'))
p--;
if ((p > (reply+1)) && (*(p-1) == '.'))
(void) CopyMagickString(format,p,MagickPathExtent);
}
XGetWidgetInfo(UpButtonText,&up_info);
up_info.width=width;
up_info.height=(unsigned int) ((3*height) >> 1);
up_info.x=QuantumMargin;
up_info.y=((5*QuantumMargin) >> 1)+height;
XGetWidgetInfo(HomeButtonText,&home_info);
home_info.width=width;
home_info.height=(unsigned int) ((3*height) >> 1);
home_info.x=QuantumMargin;
home_info.y=up_info.y+up_info.height+QuantumMargin;
/*
Initialize reply information.
*/
XGetWidgetInfo(reply,&reply_info);
reply_info.raised=MagickFalse;
reply_info.bevel_width--;
reply_info.width=windows->widget.width-width-((6*QuantumMargin) >> 1);
reply_info.height=height << 1;
reply_info.x=(int) (width+(QuantumMargin << 1));
reply_info.y=action_info.y-reply_info.height-QuantumMargin;
/*
Initialize scroll information.
*/
XGetWidgetInfo((char *) NULL,&scroll_info);
scroll_info.bevel_width--;
scroll_info.width=height;
scroll_info.height=(unsigned int)
(reply_info.y-up_info.y-(QuantumMargin >> 1));
scroll_info.x=reply_info.x+(reply_info.width-scroll_info.width);
scroll_info.y=up_info.y-reply_info.bevel_width;
scroll_info.raised=MagickFalse;
scroll_info.trough=MagickTrue;
north_info=scroll_info;
north_info.raised=MagickTrue;
north_info.width-=(north_info.bevel_width << 1);
north_info.height=north_info.width-1;
north_info.x+=north_info.bevel_width;
north_info.y+=north_info.bevel_width;
south_info=north_info;
south_info.y=scroll_info.y+scroll_info.height-scroll_info.bevel_width-
south_info.height;
id=slider_info.id;
slider_info=north_info;
slider_info.id=id;
slider_info.width-=2;
slider_info.min_y=north_info.y+north_info.height+north_info.bevel_width+
slider_info.bevel_width+2;
slider_info.height=scroll_info.height-((slider_info.min_y-
scroll_info.y+1) << 1)+4;
visible_files=scroll_info.height/(height+(height >> 3));
if (files > visible_files)
slider_info.height=(unsigned int)
((visible_files*slider_info.height)/files);
slider_info.max_y=south_info.y-south_info.bevel_width-
slider_info.bevel_width-2;
slider_info.x=scroll_info.x+slider_info.bevel_width+1;
slider_info.y=slider_info.min_y;
expose_info=scroll_info;
expose_info.y=slider_info.y;
/*
Initialize list information.
*/
XGetWidgetInfo((char *) NULL,&list_info);
list_info.raised=MagickFalse;
list_info.bevel_width--;
list_info.width=(unsigned int)
(scroll_info.x-reply_info.x-(QuantumMargin >> 1));
list_info.height=scroll_info.height;
list_info.x=reply_info.x;
list_info.y=scroll_info.y;
if (windows->widget.mapped == MagickFalse)
state|=JumpListState;
/*
Initialize text information.
*/
*text='\0';
XGetWidgetInfo(text,&text_info);
text_info.center=MagickFalse;
text_info.width=reply_info.width;
text_info.height=height;
text_info.x=list_info.x-(QuantumMargin >> 1);
text_info.y=QuantumMargin;
/*
Initialize selection information.
*/
XGetWidgetInfo((char *) NULL,&selection_info);
selection_info.center=MagickFalse;
selection_info.width=list_info.width;
selection_info.height=(unsigned int) ((9*height) >> 3);
selection_info.x=list_info.x;
state&=(~UpdateConfigurationState);
}
if (state & RedrawWidgetState)
{
/*
Redraw File Browser window.
*/
x=QuantumMargin;
y=text_info.y+((text_info.height-height) >> 1)+font_info->ascent;
(void) XDrawString(display,windows->widget.id,
windows->widget.annotate_context,x,y,DirectoryText,
Extent(DirectoryText));
(void) CopyMagickString(text_info.text,working_path,MagickPathExtent);
(void) ConcatenateMagickString(text_info.text,DirectorySeparator,
MagickPathExtent);
(void) ConcatenateMagickString(text_info.text,glob_pattern,
MagickPathExtent);
XDrawWidgetText(display,&windows->widget,&text_info);
XDrawBeveledButton(display,&windows->widget,&up_info);
XDrawBeveledButton(display,&windows->widget,&home_info);
XDrawBeveledMatte(display,&windows->widget,&list_info);
XDrawBeveledMatte(display,&windows->widget,&scroll_info);
XDrawTriangleNorth(display,&windows->widget,&north_info);
XDrawBeveledButton(display,&windows->widget,&slider_info);
XDrawTriangleSouth(display,&windows->widget,&south_info);
x=QuantumMargin;
y=reply_info.y+((reply_info.height-height) >> 1)+font_info->ascent;
(void) XDrawString(display,windows->widget.id,
windows->widget.annotate_context,x,y,FilenameText,
Extent(FilenameText));
XDrawBeveledMatte(display,&windows->widget,&reply_info);
XDrawMatteText(display,&windows->widget,&reply_info);
XDrawBeveledButton(display,&windows->widget,&special_info);
XDrawBeveledButton(display,&windows->widget,&action_info);
XDrawBeveledButton(display,&windows->widget,&cancel_info);
XHighlightWidget(display,&windows->widget,BorderOffset,BorderOffset);
selection_info.id=(~0);
state|=RedrawListState;
state&=(~RedrawWidgetState);
}
if (state & UpdateListState)
{
char
**checklist;
size_t
number_files;
/*
Update file list.
*/
checklist=ListFiles(working_path,glob_pattern,&number_files);
if (checklist == (char **) NULL)
{
/*
Reply is a filename, exit.
*/
action_info.raised=MagickFalse;
XDrawBeveledButton(display,&windows->widget,&action_info);
break;
}
for (i=0; i < (ssize_t) files; i++)
filelist[i]=DestroyString(filelist[i]);
if (filelist != (char **) NULL)
filelist=(char **) RelinquishMagickMemory(filelist);
filelist=checklist;
files=number_files;
/*
Update file list.
*/
slider_info.height=
scroll_info.height-((slider_info.min_y-scroll_info.y+1) << 1)+1;
if (files > visible_files)
slider_info.height=(unsigned int)
((visible_files*slider_info.height)/files);
slider_info.max_y=south_info.y-south_info.bevel_width-
slider_info.bevel_width-2;
slider_info.id=0;
slider_info.y=slider_info.min_y;
expose_info.y=slider_info.y;
selection_info.id=(~0);
list_info.id=(~0);
state|=RedrawListState;
/*
Redraw directory name & reply.
*/
if (IsGlob(reply_info.text) == MagickFalse)
{
*reply_info.text='\0';
reply_info.cursor=reply_info.text;
}
(void) CopyMagickString(text_info.text,working_path,MagickPathExtent);
(void) ConcatenateMagickString(text_info.text,DirectorySeparator,
MagickPathExtent);
(void) ConcatenateMagickString(text_info.text,glob_pattern,
MagickPathExtent);
XDrawWidgetText(display,&windows->widget,&text_info);
XDrawMatteText(display,&windows->widget,&reply_info);
XDrawBeveledMatte(display,&windows->widget,&scroll_info);
XDrawTriangleNorth(display,&windows->widget,&north_info);
XDrawBeveledButton(display,&windows->widget,&slider_info);
XDrawTriangleSouth(display,&windows->widget,&south_info);
XHighlightWidget(display,&windows->widget,BorderOffset,BorderOffset);
state&=(~UpdateListState);
}
if (state & JumpListState)
{
/*
Jump scroll to match user filename.
*/
list_info.id=(~0);
for (i=0; i < (ssize_t) files; i++)
if (LocaleCompare(filelist[i],reply) >= 0)
{
list_info.id=(int)
(LocaleCompare(filelist[i],reply) == 0 ? i : ~0);
break;
}
if ((i < (ssize_t) slider_info.id) ||
(i >= (ssize_t) (slider_info.id+visible_files)))
slider_info.id=(int) i-(visible_files >> 1);
selection_info.id=(~0);
state|=RedrawListState;
state&=(~JumpListState);
}
if (state & RedrawListState)
{
/*
Determine slider id and position.
*/
if (slider_info.id >= (int) (files-visible_files))
slider_info.id=(int) (files-visible_files);
if ((slider_info.id < 0) || (files <= visible_files))
slider_info.id=0;
slider_info.y=slider_info.min_y;
if (files > 0)
slider_info.y+=(int) (slider_info.id*(slider_info.max_y-
slider_info.min_y+1)/files);
if (slider_info.id != selection_info.id)
{
/*
Redraw scroll bar and file names.
*/
selection_info.id=slider_info.id;
selection_info.y=list_info.y+(height >> 3)+2;
for (i=0; i < (ssize_t) visible_files; i++)
{
selection_info.raised=(int) (slider_info.id+i) != list_info.id ?
MagickTrue : MagickFalse;
selection_info.text=(char *) NULL;
if ((slider_info.id+i) < (ssize_t) files)
selection_info.text=filelist[slider_info.id+i];
XDrawWidgetText(display,&windows->widget,&selection_info);
selection_info.y+=(int) selection_info.height;
}
/*
Update slider.
*/
if (slider_info.y > expose_info.y)
{
expose_info.height=(unsigned int) slider_info.y-expose_info.y;
expose_info.y=slider_info.y-expose_info.height-
slider_info.bevel_width-1;
}
else
{
expose_info.height=(unsigned int) expose_info.y-slider_info.y;
expose_info.y=slider_info.y+slider_info.height+
slider_info.bevel_width+1;
}
XDrawTriangleNorth(display,&windows->widget,&north_info);
XDrawMatte(display,&windows->widget,&expose_info);
XDrawBeveledButton(display,&windows->widget,&slider_info);
XDrawTriangleSouth(display,&windows->widget,&south_info);
expose_info.y=slider_info.y;
}
state&=(~RedrawListState);
}
/*
Wait for next event.
*/
if (north_info.raised && south_info.raised)
(void) XIfEvent(display,&event,XScreenEvent,(char *) windows);
else
{
/*
Brief delay before advancing scroll bar.
*/
XDelay(display,delay);
delay=SuspendTime;
(void) XCheckIfEvent(display,&event,XScreenEvent,(char *) windows);
if (north_info.raised == MagickFalse)
if (slider_info.id > 0)
{
/*
Move slider up.
*/
slider_info.id--;
state|=RedrawListState;
}
if (south_info.raised == MagickFalse)
if (slider_info.id < (int) files)
{
/*
Move slider down.
*/
slider_info.id++;
state|=RedrawListState;
}
if (event.type != ButtonRelease)
continue;
}
switch (event.type)
{
case ButtonPress:
{
if (MatteIsActive(slider_info,event.xbutton))
{
/*
Track slider.
*/
slider_info.active=MagickTrue;
break;
}
if (MatteIsActive(north_info,event.xbutton))
if (slider_info.id > 0)
{
/*
Move slider up.
*/
north_info.raised=MagickFalse;
slider_info.id--;
state|=RedrawListState;
break;
}
if (MatteIsActive(south_info,event.xbutton))
if (slider_info.id < (int) files)
{
/*
Move slider down.
*/
south_info.raised=MagickFalse;
slider_info.id++;
state|=RedrawListState;
break;
}
if (MatteIsActive(scroll_info,event.xbutton))
{
/*
Move slider.
*/
if (event.xbutton.y < slider_info.y)
slider_info.id-=(visible_files-1);
else
slider_info.id+=(visible_files-1);
state|=RedrawListState;
break;
}
if (MatteIsActive(list_info,event.xbutton))
{
int
id;
/*
User pressed file matte.
*/
id=slider_info.id+(event.xbutton.y-(list_info.y+(height >> 1))+1)/
selection_info.height;
if (id >= (int) files)
break;
(void) CopyMagickString(reply_info.text,filelist[id],MagickPathExtent);
reply_info.highlight=MagickFalse;
reply_info.marker=reply_info.text;
reply_info.cursor=reply_info.text+Extent(reply_info.text);
XDrawMatteText(display,&windows->widget,&reply_info);
if (id == list_info.id)
{
register char
*p;
p=reply_info.text+strlen(reply_info.text)-1;
if (*p == *DirectorySeparator)
ChopPathComponents(reply_info.text,1);
(void) ConcatenateMagickString(working_path,DirectorySeparator,
MagickPathExtent);
(void) ConcatenateMagickString(working_path,reply_info.text,
MagickPathExtent);
*reply='\0';
state|=UpdateListState;
}
selection_info.id=(~0);
list_info.id=id;
state|=RedrawListState;
break;
}
if (MatteIsActive(up_info,event.xbutton))
{
/*
User pressed Up button.
*/
up_info.raised=MagickFalse;
XDrawBeveledButton(display,&windows->widget,&up_info);
break;
}
if (MatteIsActive(home_info,event.xbutton))
{
/*
User pressed Home button.
*/
home_info.raised=MagickFalse;
XDrawBeveledButton(display,&windows->widget,&home_info);
break;
}
if (MatteIsActive(special_info,event.xbutton))
{
/*
User pressed Special button.
*/
special_info.raised=MagickFalse;
XDrawBeveledButton(display,&windows->widget,&special_info);
break;
}
if (MatteIsActive(action_info,event.xbutton))
{
/*
User pressed action button.
*/
action_info.raised=MagickFalse;
XDrawBeveledButton(display,&windows->widget,&action_info);
break;
}
if (MatteIsActive(cancel_info,event.xbutton))
{
/*
User pressed Cancel button.
*/
cancel_info.raised=MagickFalse;
XDrawBeveledButton(display,&windows->widget,&cancel_info);
break;
}
if (MatteIsActive(reply_info,event.xbutton) == MagickFalse)
break;
if (event.xbutton.button != Button2)
{
static Time
click_time;
/*
Move text cursor to position of button press.
*/
x=event.xbutton.x-reply_info.x-(QuantumMargin >> 2);
for (i=1; i <= (ssize_t) Extent(reply_info.marker); i++)
if (XTextWidth(font_info,reply_info.marker,(int) i) > x)
break;
reply_info.cursor=reply_info.marker+i-1;
if (event.xbutton.time > (click_time+DoubleClick))
reply_info.highlight=MagickFalse;
else
{
/*
Become the XA_PRIMARY selection owner.
*/
(void) CopyMagickString(primary_selection,reply_info.text,
MagickPathExtent);
(void) XSetSelectionOwner(display,XA_PRIMARY,windows->widget.id,
event.xbutton.time);
reply_info.highlight=XGetSelectionOwner(display,XA_PRIMARY) ==
windows->widget.id ? MagickTrue : MagickFalse;
}
XDrawMatteText(display,&windows->widget,&reply_info);
click_time=event.xbutton.time;
break;
}
/*
Request primary selection.
*/
(void) XConvertSelection(display,XA_PRIMARY,XA_STRING,XA_STRING,
windows->widget.id,event.xbutton.time);
break;
}
case ButtonRelease:
{
if (windows->widget.mapped == MagickFalse)
break;
if (north_info.raised == MagickFalse)
{
/*
User released up button.
*/
delay=SuspendTime << 2;
north_info.raised=MagickTrue;
XDrawTriangleNorth(display,&windows->widget,&north_info);
}
if (south_info.raised == MagickFalse)
{
/*
User released down button.
*/
delay=SuspendTime << 2;
south_info.raised=MagickTrue;
XDrawTriangleSouth(display,&windows->widget,&south_info);
}
if (slider_info.active)
{
/*
Stop tracking slider.
*/
slider_info.active=MagickFalse;
break;
}
if (up_info.raised == MagickFalse)
{
if (event.xbutton.window == windows->widget.id)
if (MatteIsActive(up_info,event.xbutton))
{
ChopPathComponents(working_path,1);
if (*working_path == '\0')
(void) CopyMagickString(working_path,DirectorySeparator,
MagickPathExtent);
state|=UpdateListState;
}
up_info.raised=MagickTrue;
XDrawBeveledButton(display,&windows->widget,&up_info);
}
if (home_info.raised == MagickFalse)
{
if (event.xbutton.window == windows->widget.id)
if (MatteIsActive(home_info,event.xbutton))
{
(void) CopyMagickString(working_path,home_directory,
MagickPathExtent);
state|=UpdateListState;
}
home_info.raised=MagickTrue;
XDrawBeveledButton(display,&windows->widget,&home_info);
}
if (special_info.raised == MagickFalse)
{
if (anomaly == MagickFalse)
{
char
**formats;
ExceptionInfo
*exception;
size_t
number_formats;
/*
Let user select image format.
*/
exception=AcquireExceptionInfo();
formats=GetMagickList("*",&number_formats,exception);
exception=DestroyExceptionInfo(exception);
(void) XCheckDefineCursor(display,windows->widget.id,
windows->widget.busy_cursor);
windows->popup.x=windows->widget.x+60;
windows->popup.y=windows->widget.y+60;
XListBrowserWidget(display,windows,&windows->popup,
(const char **) formats,"Select","Select image format type:",
format);
XSetCursorState(display,windows,MagickTrue);
(void) XCheckDefineCursor(display,windows->widget.id,
windows->widget.cursor);
LocaleLower(format);
AppendImageFormat(format,reply_info.text);
reply_info.cursor=reply_info.text+Extent(reply_info.text);
XDrawMatteText(display,&windows->widget,&reply_info);
special_info.raised=MagickTrue;
XDrawBeveledButton(display,&windows->widget,&special_info);
for (i=0; i < (ssize_t) number_formats; i++)
formats[i]=DestroyString(formats[i]);
formats=(char **) RelinquishMagickMemory(formats);
break;
}
if (event.xbutton.window == windows->widget.id)
if (MatteIsActive(special_info,event.xbutton))
{
(void) CopyMagickString(working_path,"x:",MagickPathExtent);
state|=ExitState;
}
special_info.raised=MagickTrue;
XDrawBeveledButton(display,&windows->widget,&special_info);
}
if (action_info.raised == MagickFalse)
{
if (event.xbutton.window == windows->widget.id)
{
if (MatteIsActive(action_info,event.xbutton))
{
if (*reply_info.text == '\0')
(void) XBell(display,0);
else
state|=ExitState;
}
}
action_info.raised=MagickTrue;
XDrawBeveledButton(display,&windows->widget,&action_info);
}
if (cancel_info.raised == MagickFalse)
{
if (event.xbutton.window == windows->widget.id)
if (MatteIsActive(cancel_info,event.xbutton))
{
*reply_info.text='\0';
*reply='\0';
state|=ExitState;
}
cancel_info.raised=MagickTrue;
XDrawBeveledButton(display,&windows->widget,&cancel_info);
}
break;
}
case ClientMessage:
{
/*
If client window delete message, exit.
*/
if (event.xclient.message_type != windows->wm_protocols)
break;
if (*event.xclient.data.l == (int) windows->wm_take_focus)
{
(void) XSetInputFocus(display,event.xclient.window,RevertToParent,
(Time) event.xclient.data.l[1]);
break;
}
if (*event.xclient.data.l != (int) windows->wm_delete_window)
break;
if (event.xclient.window == windows->widget.id)
{
*reply_info.text='\0';
state|=ExitState;
break;
}
break;
}
case ConfigureNotify:
{
/*
Update widget configuration.
*/
if (event.xconfigure.window != windows->widget.id)
break;
if ((event.xconfigure.width == (int) windows->widget.width) &&
(event.xconfigure.height == (int) windows->widget.height))
break;
windows->widget.width=(unsigned int)
MagickMax(event.xconfigure.width,(int) windows->widget.min_width);
windows->widget.height=(unsigned int)
MagickMax(event.xconfigure.height,(int) windows->widget.min_height);
state|=UpdateConfigurationState;
break;
}
case EnterNotify:
{
if (event.xcrossing.window != windows->widget.id)
break;
state&=(~InactiveWidgetState);
break;
}
case Expose:
{
if (event.xexpose.window != windows->widget.id)
break;
if (event.xexpose.count != 0)
break;
state|=RedrawWidgetState;
break;
}
case KeyPress:
{
static char
command[MagickPathExtent];
static int
length;
static KeySym
key_symbol;
/*
Respond to a user key press.
*/
if (event.xkey.window != windows->widget.id)
break;
length=XLookupString((XKeyEvent *) &event.xkey,command,
(int) sizeof(command),&key_symbol,(XComposeStatus *) NULL);
*(command+length)='\0';
if (AreaIsActive(scroll_info,event.xkey))
{
/*
Move slider.
*/
switch ((int) key_symbol)
{
case XK_Home:
case XK_KP_Home:
{
slider_info.id=0;
break;
}
case XK_Up:
case XK_KP_Up:
{
slider_info.id--;
break;
}
case XK_Down:
case XK_KP_Down:
{
slider_info.id++;
break;
}
case XK_Prior:
case XK_KP_Prior:
{
slider_info.id-=visible_files;
break;
}
case XK_Next:
case XK_KP_Next:
{
slider_info.id+=visible_files;
break;
}
case XK_End:
case XK_KP_End:
{
slider_info.id=(int) files;
break;
}
}
state|=RedrawListState;
break;
}
if ((key_symbol == XK_Return) || (key_symbol == XK_KP_Enter))
{
/*
Read new directory or glob patterm.
*/
if (*reply_info.text == '\0')
break;
if (IsGlob(reply_info.text))
(void) CopyMagickString(glob_pattern,reply_info.text,
MagickPathExtent);
else
{
(void) ConcatenateMagickString(working_path,DirectorySeparator,
MagickPathExtent);
(void) ConcatenateMagickString(working_path,reply_info.text,
MagickPathExtent);
if (*working_path == '~')
ExpandFilename(working_path);
*reply='\0';
}
state|=UpdateListState;
break;
}
if (key_symbol == XK_Control_L)
{
state|=ControlState;
break;
}
if (state & ControlState)
switch ((int) key_symbol)
{
case XK_u:
case XK_U:
{
/*
Erase the entire line of text.
*/
*reply_info.text='\0';
reply_info.cursor=reply_info.text;
reply_info.marker=reply_info.text;
reply_info.highlight=MagickFalse;
break;
}
default:
break;
}
XEditText(display,&reply_info,key_symbol,command,state);
XDrawMatteText(display,&windows->widget,&reply_info);
state|=JumpListState;
break;
}
case KeyRelease:
{
static char
command[MagickPathExtent];
static KeySym
key_symbol;
/*
Respond to a user key release.
*/
if (event.xkey.window != windows->widget.id)
break;
(void) XLookupString((XKeyEvent *) &event.xkey,command,
(int) sizeof(command),&key_symbol,(XComposeStatus *) NULL);
if (key_symbol == XK_Control_L)
state&=(~ControlState);
break;
}
case LeaveNotify:
{
if (event.xcrossing.window != windows->widget.id)
break;
state|=InactiveWidgetState;
break;
}
case MapNotify:
{
mask&=(~CWX);
mask&=(~CWY);
break;
}
case MotionNotify:
{
/*
Discard pending button motion events.
*/
while (XCheckMaskEvent(display,ButtonMotionMask,&event)) ;
if (slider_info.active)
{
/*
Move slider matte.
*/
slider_info.y=event.xmotion.y-
((slider_info.height+slider_info.bevel_width) >> 1)+1;
if (slider_info.y < slider_info.min_y)
slider_info.y=slider_info.min_y;
if (slider_info.y > slider_info.max_y)
slider_info.y=slider_info.max_y;
slider_info.id=0;
if (slider_info.y != slider_info.min_y)
slider_info.id=(int) ((files*(slider_info.y-slider_info.min_y+1))/
(slider_info.max_y-slider_info.min_y+1));
state|=RedrawListState;
break;
}
if (state & InactiveWidgetState)
break;
if (up_info.raised == MatteIsActive(up_info,event.xmotion))
{
/*
Up button status changed.
*/
up_info.raised=!up_info.raised;
XDrawBeveledButton(display,&windows->widget,&up_info);
break;
}
if (home_info.raised == MatteIsActive(home_info,event.xmotion))
{
/*
Home button status changed.
*/
home_info.raised=!home_info.raised;
XDrawBeveledButton(display,&windows->widget,&home_info);
break;
}
if (special_info.raised == MatteIsActive(special_info,event.xmotion))
{
/*
Grab button status changed.
*/
special_info.raised=!special_info.raised;
XDrawBeveledButton(display,&windows->widget,&special_info);
break;
}
if (action_info.raised == MatteIsActive(action_info,event.xmotion))
{
/*
Action button status changed.
*/
action_info.raised=action_info.raised == MagickFalse ?
MagickTrue : MagickFalse;
XDrawBeveledButton(display,&windows->widget,&action_info);
break;
}
if (cancel_info.raised == MatteIsActive(cancel_info,event.xmotion))
{
/*
Cancel button status changed.
*/
cancel_info.raised=cancel_info.raised == MagickFalse ?
MagickTrue : MagickFalse;
XDrawBeveledButton(display,&windows->widget,&cancel_info);
break;
}
break;
}
case SelectionClear:
{
reply_info.highlight=MagickFalse;
XDrawMatteText(display,&windows->widget,&reply_info);
break;
}
case SelectionNotify:
{
Atom
type;
int
format;
unsigned char
*data;
unsigned long
after,
length;
/*
Obtain response from primary selection.
*/
if (event.xselection.property == (Atom) None)
break;
status=XGetWindowProperty(display,event.xselection.requestor,
event.xselection.property,0L,2047L,MagickTrue,XA_STRING,&type,
&format,&length,&after,&data);
if ((status != Success) || (type != XA_STRING) || (format == 32) ||
(length == 0))
break;
if ((Extent(reply_info.text)+length) >= (MagickPathExtent-1))
(void) XBell(display,0);
else
{
/*
Insert primary selection in reply text.
*/
*(data+length)='\0';
XEditText(display,&reply_info,(KeySym) XK_Insert,(char *) data,
state);
XDrawMatteText(display,&windows->widget,&reply_info);
state|=JumpListState;
state|=RedrawActionState;
}
(void) XFree((void *) data);
break;
}
case SelectionRequest:
{
XSelectionEvent
notify;
XSelectionRequestEvent
*request;
if (reply_info.highlight == MagickFalse)
break;
/*
Set primary selection.
*/
request=(&(event.xselectionrequest));
(void) XChangeProperty(request->display,request->requestor,
request->property,request->target,8,PropModeReplace,
(unsigned char *) primary_selection,Extent(primary_selection));
notify.type=SelectionNotify;
notify.display=request->display;
notify.requestor=request->requestor;
notify.selection=request->selection;
notify.target=request->target;
notify.time=request->time;
if (request->property == None)
notify.property=request->target;
else
notify.property=request->property;
(void) XSendEvent(request->display,request->requestor,False,0,
(XEvent *) ¬ify);
}
default:
break;
}
} while ((state & ExitState) == 0);
XSetCursorState(display,windows,MagickFalse);
(void) XWithdrawWindow(display,windows->widget.id,windows->widget.screen);
XCheckRefreshWindows(display,windows);
/*
Free file list.
*/
for (i=0; i < (ssize_t) files; i++)
filelist[i]=DestroyString(filelist[i]);
if (filelist != (char **) NULL)
filelist=(char **) RelinquishMagickMemory(filelist);
if (*reply != '\0')
{
(void) ConcatenateMagickString(working_path,DirectorySeparator,
MagickPathExtent);
(void) ConcatenateMagickString(working_path,reply,MagickPathExtent);
}
(void) CopyMagickString(reply,working_path,MagickPathExtent);
if (*reply == '~')
ExpandFilename(reply);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% X F o n t B r o w s e r W i d g e t %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% XFontBrowserWidget() displays a Font Browser widget with a font query to the
% user. The user keys a reply and presses the Action or Cancel button to
% exit. The typed text is returned as the reply function parameter.
%
% The format of the XFontBrowserWidget method is:
%
% void XFontBrowserWidget(Display *display,XWindows *windows,
% const char *action,char *reply)
%
% A description of each parameter follows:
%
% o display: Specifies a connection to an X server; returned from
% XOpenDisplay.
%
% o window: Specifies a pointer to a XWindows structure.
%
% o action: Specifies a pointer to the action of this widget.
%
% o reply: the response from the user is returned in this parameter.
%
%
*/
#if defined(__cplusplus) || defined(c_plusplus)
extern "C" {
#endif
static int FontCompare(const void *x,const void *y)
{
register char
*p,
*q;
p=(char *) *((char **) x);
q=(char *) *((char **) y);
while ((*p != '\0') && (*q != '\0') && (*p == *q))
{
p++;
q++;
}
return(*p-(*q));
}
#if defined(__cplusplus) || defined(c_plusplus)
}
#endif
MagickPrivate void XFontBrowserWidget(Display *display,XWindows *windows,
const char *action,char *reply)
{
#define BackButtonText "Back"
#define CancelButtonText "Cancel"
#define FontnameText "Name:"
#define FontPatternText "Pattern:"
#define ResetButtonText "Reset"
char
back_pattern[MagickPathExtent],
**fontlist,
**listhead,
primary_selection[MagickPathExtent],
reset_pattern[MagickPathExtent],
text[MagickPathExtent];
int
fonts,
x,
y;
register int
i;
static char
glob_pattern[MagickPathExtent] = "*";
static MagickStatusType
mask = (MagickStatusType) (CWWidth | CWHeight | CWX | CWY);
Status
status;
unsigned int
height,
text_width,
visible_fonts,
width;
size_t
delay,
state;
XEvent
event;
XFontStruct
*font_info;
XTextProperty
window_name;
XWidgetInfo
action_info,
back_info,
cancel_info,
expose_info,
list_info,
mode_info,
north_info,
reply_info,
reset_info,
scroll_info,
selection_info,
slider_info,
south_info,
text_info;
XWindowChanges
window_changes;
/*
Get font list and sort in ascending order.
*/
assert(display != (Display *) NULL);
assert(windows != (XWindows *) NULL);
assert(action != (char *) NULL);
assert(reply != (char *) NULL);
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",action);
XSetCursorState(display,windows,MagickTrue);
XCheckRefreshWindows(display,windows);
(void) CopyMagickString(back_pattern,glob_pattern,MagickPathExtent);
(void) CopyMagickString(reset_pattern,"*",MagickPathExtent);
fontlist=XListFonts(display,glob_pattern,32767,&fonts);
if (fonts == 0)
{
/*
Pattern failed, obtain all the fonts.
*/
XNoticeWidget(display,windows,"Unable to obtain fonts names:",
glob_pattern);
(void) CopyMagickString(glob_pattern,"*",MagickPathExtent);
fontlist=XListFonts(display,glob_pattern,32767,&fonts);
if (fontlist == (char **) NULL)
{
XNoticeWidget(display,windows,"Unable to obtain fonts names:",
glob_pattern);
return;
}
}
/*
Sort font list in ascending order.
*/
listhead=fontlist;
fontlist=(char **) AcquireQuantumMemory((size_t) fonts,sizeof(*fontlist));
if (fontlist == (char **) NULL)
{
XNoticeWidget(display,windows,"MemoryAllocationFailed",
"UnableToViewFonts");
return;
}
for (i=0; i < fonts; i++)
fontlist[i]=listhead[i];
qsort((void *) fontlist,(size_t) fonts,sizeof(*fontlist),FontCompare);
/*
Determine Font Browser widget attributes.
*/
font_info=windows->widget.font_info;
text_width=0;
for (i=0; i < fonts; i++)
if (WidgetTextWidth(font_info,fontlist[i]) > text_width)
text_width=WidgetTextWidth(font_info,fontlist[i]);
width=WidgetTextWidth(font_info,(char *) action);
if (WidgetTextWidth(font_info,CancelButtonText) > width)
width=WidgetTextWidth(font_info,CancelButtonText);
if (WidgetTextWidth(font_info,ResetButtonText) > width)
width=WidgetTextWidth(font_info,ResetButtonText);
if (WidgetTextWidth(font_info,BackButtonText) > width)
width=WidgetTextWidth(font_info,BackButtonText);
width+=QuantumMargin;
if (WidgetTextWidth(font_info,FontPatternText) > width)
width=WidgetTextWidth(font_info,FontPatternText);
if (WidgetTextWidth(font_info,FontnameText) > width)
width=WidgetTextWidth(font_info,FontnameText);
height=(unsigned int) (font_info->ascent+font_info->descent);
/*
Position Font Browser widget.
*/
windows->widget.width=width+MagickMin((int) text_width,(int) MaxTextWidth)+
6*QuantumMargin;
windows->widget.min_width=width+MinTextWidth+4*QuantumMargin;
if (windows->widget.width < windows->widget.min_width)
windows->widget.width=windows->widget.min_width;
windows->widget.height=(unsigned int)
(((85*height) >> 2)+((13*QuantumMargin) >> 1)+4);
windows->widget.min_height=(unsigned int)
(((27*height) >> 1)+((13*QuantumMargin) >> 1)+4);
if (windows->widget.height < windows->widget.min_height)
windows->widget.height=windows->widget.min_height;
XConstrainWindowPosition(display,&windows->widget);
/*
Map Font Browser widget.
*/
(void) CopyMagickString(windows->widget.name,"Browse and Select a Font",
MagickPathExtent);
status=XStringListToTextProperty(&windows->widget.name,1,&window_name);
if (status != False)
{
XSetWMName(display,windows->widget.id,&window_name);
XSetWMIconName(display,windows->widget.id,&window_name);
(void) XFree((void *) window_name.value);
}
window_changes.width=(int) windows->widget.width;
window_changes.height=(int) windows->widget.height;
window_changes.x=windows->widget.x;
window_changes.y=windows->widget.y;
(void) XReconfigureWMWindow(display,windows->widget.id,
windows->widget.screen,mask,&window_changes);
(void) XMapRaised(display,windows->widget.id);
windows->widget.mapped=MagickFalse;
/*
Respond to X events.
*/
XGetWidgetInfo((char *) NULL,&slider_info);
XGetWidgetInfo((char *) NULL,&north_info);
XGetWidgetInfo((char *) NULL,&south_info);
XGetWidgetInfo((char *) NULL,&expose_info);
XGetWidgetInfo((char *) NULL,&selection_info);
visible_fonts=0;
delay=SuspendTime << 2;
state=UpdateConfigurationState;
do
{
if (state & UpdateConfigurationState)
{
int
id;
/*
Initialize button information.
*/
XGetWidgetInfo(CancelButtonText,&cancel_info);
cancel_info.width=width;
cancel_info.height=(unsigned int) ((3*height) >> 1);
cancel_info.x=(int)
(windows->widget.width-cancel_info.width-QuantumMargin-2);
cancel_info.y=(int)
(windows->widget.height-cancel_info.height-QuantumMargin);
XGetWidgetInfo(action,&action_info);
action_info.width=width;
action_info.height=(unsigned int) ((3*height) >> 1);
action_info.x=cancel_info.x-(cancel_info.width+(QuantumMargin >> 1)+
(action_info.bevel_width << 1));
action_info.y=cancel_info.y;
XGetWidgetInfo(BackButtonText,&back_info);
back_info.width=width;
back_info.height=(unsigned int) ((3*height) >> 1);
back_info.x=QuantumMargin;
back_info.y=((5*QuantumMargin) >> 1)+height;
XGetWidgetInfo(ResetButtonText,&reset_info);
reset_info.width=width;
reset_info.height=(unsigned int) ((3*height) >> 1);
reset_info.x=QuantumMargin;
reset_info.y=back_info.y+back_info.height+QuantumMargin;
/*
Initialize reply information.
*/
XGetWidgetInfo(reply,&reply_info);
reply_info.raised=MagickFalse;
reply_info.bevel_width--;
reply_info.width=windows->widget.width-width-((6*QuantumMargin) >> 1);
reply_info.height=height << 1;
reply_info.x=(int) (width+(QuantumMargin << 1));
reply_info.y=action_info.y-(action_info.height << 1)-QuantumMargin;
/*
Initialize mode information.
*/
XGetWidgetInfo(reply,&mode_info);
mode_info.bevel_width=0;
mode_info.width=(unsigned int)
(action_info.x-reply_info.x-QuantumMargin);
mode_info.height=action_info.height << 1;
mode_info.x=reply_info.x;
mode_info.y=action_info.y-action_info.height+action_info.bevel_width;
/*
Initialize scroll information.
*/
XGetWidgetInfo((char *) NULL,&scroll_info);
scroll_info.bevel_width--;
scroll_info.width=height;
scroll_info.height=(unsigned int)
(reply_info.y-back_info.y-(QuantumMargin >> 1));
scroll_info.x=reply_info.x+(reply_info.width-scroll_info.width);
scroll_info.y=back_info.y-reply_info.bevel_width;
scroll_info.raised=MagickFalse;
scroll_info.trough=MagickTrue;
north_info=scroll_info;
north_info.raised=MagickTrue;
north_info.width-=(north_info.bevel_width << 1);
north_info.height=north_info.width-1;
north_info.x+=north_info.bevel_width;
north_info.y+=north_info.bevel_width;
south_info=north_info;
south_info.y=scroll_info.y+scroll_info.height-scroll_info.bevel_width-
south_info.height;
id=slider_info.id;
slider_info=north_info;
slider_info.id=id;
slider_info.width-=2;
slider_info.min_y=north_info.y+north_info.height+north_info.bevel_width+
slider_info.bevel_width+2;
slider_info.height=scroll_info.height-((slider_info.min_y-
scroll_info.y+1) << 1)+4;
visible_fonts=scroll_info.height/(height+(height >> 3));
if (fonts > (int) visible_fonts)
slider_info.height=(visible_fonts*slider_info.height)/fonts;
slider_info.max_y=south_info.y-south_info.bevel_width-
slider_info.bevel_width-2;
slider_info.x=scroll_info.x+slider_info.bevel_width+1;
slider_info.y=slider_info.min_y;
expose_info=scroll_info;
expose_info.y=slider_info.y;
/*
Initialize list information.
*/
XGetWidgetInfo((char *) NULL,&list_info);
list_info.raised=MagickFalse;
list_info.bevel_width--;
list_info.width=(unsigned int)
(scroll_info.x-reply_info.x-(QuantumMargin >> 1));
list_info.height=scroll_info.height;
list_info.x=reply_info.x;
list_info.y=scroll_info.y;
if (windows->widget.mapped == MagickFalse)
state|=JumpListState;
/*
Initialize text information.
*/
*text='\0';
XGetWidgetInfo(text,&text_info);
text_info.center=MagickFalse;
text_info.width=reply_info.width;
text_info.height=height;
text_info.x=list_info.x-(QuantumMargin >> 1);
text_info.y=QuantumMargin;
/*
Initialize selection information.
*/
XGetWidgetInfo((char *) NULL,&selection_info);
selection_info.center=MagickFalse;
selection_info.width=list_info.width;
selection_info.height=(unsigned int) ((9*height) >> 3);
selection_info.x=list_info.x;
state&=(~UpdateConfigurationState);
}
if (state & RedrawWidgetState)
{
/*
Redraw Font Browser window.
*/
x=QuantumMargin;
y=text_info.y+((text_info.height-height) >> 1)+font_info->ascent;
(void) XDrawString(display,windows->widget.id,
windows->widget.annotate_context,x,y,FontPatternText,
Extent(FontPatternText));
(void) CopyMagickString(text_info.text,glob_pattern,MagickPathExtent);
XDrawWidgetText(display,&windows->widget,&text_info);
XDrawBeveledButton(display,&windows->widget,&back_info);
XDrawBeveledButton(display,&windows->widget,&reset_info);
XDrawBeveledMatte(display,&windows->widget,&list_info);
XDrawBeveledMatte(display,&windows->widget,&scroll_info);
XDrawTriangleNorth(display,&windows->widget,&north_info);
XDrawBeveledButton(display,&windows->widget,&slider_info);
XDrawTriangleSouth(display,&windows->widget,&south_info);
x=QuantumMargin;
y=reply_info.y+((reply_info.height-height) >> 1)+font_info->ascent;
(void) XDrawString(display,windows->widget.id,
windows->widget.annotate_context,x,y,FontnameText,
Extent(FontnameText));
XDrawBeveledMatte(display,&windows->widget,&reply_info);
XDrawMatteText(display,&windows->widget,&reply_info);
XDrawBeveledButton(display,&windows->widget,&action_info);
XDrawBeveledButton(display,&windows->widget,&cancel_info);
XHighlightWidget(display,&windows->widget,BorderOffset,BorderOffset);
selection_info.id=(~0);
state|=RedrawActionState;
state|=RedrawListState;
state&=(~RedrawWidgetState);
}
if (state & UpdateListState)
{
char
**checklist;
int
number_fonts;
/*
Update font list.
*/
checklist=XListFonts(display,glob_pattern,32767,&number_fonts);
if (checklist == (char **) NULL)
{
if ((strchr(glob_pattern,'*') == (char *) NULL) &&
(strchr(glob_pattern,'?') == (char *) NULL))
{
/*
Might be a scaleable font-- exit.
*/
(void) CopyMagickString(reply,glob_pattern,MagickPathExtent);
(void) CopyMagickString(glob_pattern,back_pattern,MagickPathExtent);
action_info.raised=MagickFalse;
XDrawBeveledButton(display,&windows->widget,&action_info);
break;
}
(void) CopyMagickString(glob_pattern,back_pattern,MagickPathExtent);
(void) XBell(display,0);
}
else
if (number_fonts == 1)
{
/*
Reply is a single font name-- exit.
*/
(void) CopyMagickString(reply,checklist[0],MagickPathExtent);
(void) CopyMagickString(glob_pattern,back_pattern,MagickPathExtent);
(void) XFreeFontNames(checklist);
action_info.raised=MagickFalse;
XDrawBeveledButton(display,&windows->widget,&action_info);
break;
}
else
{
(void) XFreeFontNames(listhead);
fontlist=(char **) RelinquishMagickMemory(fontlist);
fontlist=checklist;
fonts=number_fonts;
}
/*
Sort font list in ascending order.
*/
listhead=fontlist;
fontlist=(char **) AcquireQuantumMemory((size_t) fonts,
sizeof(*fontlist));
if (fontlist == (char **) NULL)
{
XNoticeWidget(display,windows,"MemoryAllocationFailed",
"UnableToViewFonts");
return;
}
for (i=0; i < fonts; i++)
fontlist[i]=listhead[i];
qsort((void *) fontlist,(size_t) fonts,sizeof(*fontlist),FontCompare);
slider_info.height=
scroll_info.height-((slider_info.min_y-scroll_info.y+1) << 1)+1;
if (fonts > (int) visible_fonts)
slider_info.height=(visible_fonts*slider_info.height)/fonts;
slider_info.max_y=south_info.y-south_info.bevel_width-
slider_info.bevel_width-2;
slider_info.id=0;
slider_info.y=slider_info.min_y;
expose_info.y=slider_info.y;
selection_info.id=(~0);
list_info.id=(~0);
state|=RedrawListState;
/*
Redraw font name & reply.
*/
*reply_info.text='\0';
reply_info.cursor=reply_info.text;
(void) CopyMagickString(text_info.text,glob_pattern,MagickPathExtent);
XDrawWidgetText(display,&windows->widget,&text_info);
XDrawMatteText(display,&windows->widget,&reply_info);
XDrawBeveledMatte(display,&windows->widget,&scroll_info);
XDrawTriangleNorth(display,&windows->widget,&north_info);
XDrawBeveledButton(display,&windows->widget,&slider_info);
XDrawTriangleSouth(display,&windows->widget,&south_info);
XHighlightWidget(display,&windows->widget,BorderOffset,BorderOffset);
state&=(~UpdateListState);
}
if (state & JumpListState)
{
/*
Jump scroll to match user font.
*/
list_info.id=(~0);
for (i=0; i < fonts; i++)
if (LocaleCompare(fontlist[i],reply) >= 0)
{
list_info.id=LocaleCompare(fontlist[i],reply) == 0 ? i : ~0;
break;
}
if ((i < slider_info.id) || (i >= (int) (slider_info.id+visible_fonts)))
slider_info.id=i-(visible_fonts >> 1);
selection_info.id=(~0);
state|=RedrawListState;
state&=(~JumpListState);
}
if (state & RedrawListState)
{
/*
Determine slider id and position.
*/
if (slider_info.id >= (int) (fonts-visible_fonts))
slider_info.id=fonts-visible_fonts;
if ((slider_info.id < 0) || (fonts <= (int) visible_fonts))
slider_info.id=0;
slider_info.y=slider_info.min_y;
if (fonts > 0)
slider_info.y+=
slider_info.id*(slider_info.max_y-slider_info.min_y+1)/fonts;
if (slider_info.id != selection_info.id)
{
/*
Redraw scroll bar and file names.
*/
selection_info.id=slider_info.id;
selection_info.y=list_info.y+(height >> 3)+2;
for (i=0; i < (int) visible_fonts; i++)
{
selection_info.raised=(slider_info.id+i) != list_info.id ?
MagickTrue : MagickFalse;
selection_info.text=(char *) NULL;
if ((slider_info.id+i) < fonts)
selection_info.text=fontlist[slider_info.id+i];
XDrawWidgetText(display,&windows->widget,&selection_info);
selection_info.y+=(int) selection_info.height;
}
/*
Update slider.
*/
if (slider_info.y > expose_info.y)
{
expose_info.height=(unsigned int) slider_info.y-expose_info.y;
expose_info.y=slider_info.y-expose_info.height-
slider_info.bevel_width-1;
}
else
{
expose_info.height=(unsigned int) expose_info.y-slider_info.y;
expose_info.y=slider_info.y+slider_info.height+
slider_info.bevel_width+1;
}
XDrawTriangleNorth(display,&windows->widget,&north_info);
XDrawMatte(display,&windows->widget,&expose_info);
XDrawBeveledButton(display,&windows->widget,&slider_info);
XDrawTriangleSouth(display,&windows->widget,&south_info);
expose_info.y=slider_info.y;
}
state&=(~RedrawListState);
}
if (state & RedrawActionState)
{
XFontStruct
*save_info;
/*
Display the selected font in a drawing area.
*/
save_info=windows->widget.font_info;
font_info=XLoadQueryFont(display,reply_info.text);
if (font_info != (XFontStruct *) NULL)
{
windows->widget.font_info=font_info;
(void) XSetFont(display,windows->widget.widget_context,
font_info->fid);
}
XDrawBeveledButton(display,&windows->widget,&mode_info);
windows->widget.font_info=save_info;
if (font_info != (XFontStruct *) NULL)
{
(void) XSetFont(display,windows->widget.widget_context,
windows->widget.font_info->fid);
(void) XFreeFont(display,font_info);
}
XHighlightWidget(display,&windows->widget,BorderOffset,BorderOffset);
XDrawMatteText(display,&windows->widget,&reply_info);
state&=(~RedrawActionState);
}
/*
Wait for next event.
*/
if (north_info.raised && south_info.raised)
(void) XIfEvent(display,&event,XScreenEvent,(char *) windows);
else
{
/*
Brief delay before advancing scroll bar.
*/
XDelay(display,delay);
delay=SuspendTime;
(void) XCheckIfEvent(display,&event,XScreenEvent,(char *) windows);
if (north_info.raised == MagickFalse)
if (slider_info.id > 0)
{
/*
Move slider up.
*/
slider_info.id--;
state|=RedrawListState;
}
if (south_info.raised == MagickFalse)
if (slider_info.id < fonts)
{
/*
Move slider down.
*/
slider_info.id++;
state|=RedrawListState;
}
if (event.type != ButtonRelease)
continue;
}
switch (event.type)
{
case ButtonPress:
{
if (MatteIsActive(slider_info,event.xbutton))
{
/*
Track slider.
*/
slider_info.active=MagickTrue;
break;
}
if (MatteIsActive(north_info,event.xbutton))
if (slider_info.id > 0)
{
/*
Move slider up.
*/
north_info.raised=MagickFalse;
slider_info.id--;
state|=RedrawListState;
break;
}
if (MatteIsActive(south_info,event.xbutton))
if (slider_info.id < fonts)
{
/*
Move slider down.
*/
south_info.raised=MagickFalse;
slider_info.id++;
state|=RedrawListState;
break;
}
if (MatteIsActive(scroll_info,event.xbutton))
{
/*
Move slider.
*/
if (event.xbutton.y < slider_info.y)
slider_info.id-=(visible_fonts-1);
else
slider_info.id+=(visible_fonts-1);
state|=RedrawListState;
break;
}
if (MatteIsActive(list_info,event.xbutton))
{
int
id;
/*
User pressed list matte.
*/
id=slider_info.id+(event.xbutton.y-(list_info.y+(height >> 1))+1)/
selection_info.height;
if (id >= (int) fonts)
break;
(void) CopyMagickString(reply_info.text,fontlist[id],MagickPathExtent);
reply_info.highlight=MagickFalse;
reply_info.marker=reply_info.text;
reply_info.cursor=reply_info.text+Extent(reply_info.text);
XDrawMatteText(display,&windows->widget,&reply_info);
state|=RedrawActionState;
if (id == list_info.id)
{
(void) CopyMagickString(glob_pattern,reply_info.text,
MagickPathExtent);
state|=UpdateListState;
}
selection_info.id=(~0);
list_info.id=id;
state|=RedrawListState;
break;
}
if (MatteIsActive(back_info,event.xbutton))
{
/*
User pressed Back button.
*/
back_info.raised=MagickFalse;
XDrawBeveledButton(display,&windows->widget,&back_info);
break;
}
if (MatteIsActive(reset_info,event.xbutton))
{
/*
User pressed Reset button.
*/
reset_info.raised=MagickFalse;
XDrawBeveledButton(display,&windows->widget,&reset_info);
break;
}
if (MatteIsActive(action_info,event.xbutton))
{
/*
User pressed action button.
*/
action_info.raised=MagickFalse;
XDrawBeveledButton(display,&windows->widget,&action_info);
break;
}
if (MatteIsActive(cancel_info,event.xbutton))
{
/*
User pressed Cancel button.
*/
cancel_info.raised=MagickFalse;
XDrawBeveledButton(display,&windows->widget,&cancel_info);
break;
}
if (MatteIsActive(reply_info,event.xbutton) == MagickFalse)
break;
if (event.xbutton.button != Button2)
{
static Time
click_time;
/*
Move text cursor to position of button press.
*/
x=event.xbutton.x-reply_info.x-(QuantumMargin >> 2);
for (i=1; i <= Extent(reply_info.marker); i++)
if (XTextWidth(font_info,reply_info.marker,i) > x)
break;
reply_info.cursor=reply_info.marker+i-1;
if (event.xbutton.time > (click_time+DoubleClick))
reply_info.highlight=MagickFalse;
else
{
/*
Become the XA_PRIMARY selection owner.
*/
(void) CopyMagickString(primary_selection,reply_info.text,
MagickPathExtent);
(void) XSetSelectionOwner(display,XA_PRIMARY,windows->widget.id,
event.xbutton.time);
reply_info.highlight=XGetSelectionOwner(display,XA_PRIMARY) ==
windows->widget.id ? MagickTrue : MagickFalse;
}
XDrawMatteText(display,&windows->widget,&reply_info);
click_time=event.xbutton.time;
break;
}
/*
Request primary selection.
*/
(void) XConvertSelection(display,XA_PRIMARY,XA_STRING,XA_STRING,
windows->widget.id,event.xbutton.time);
break;
}
case ButtonRelease:
{
if (windows->widget.mapped == MagickFalse)
break;
if (north_info.raised == MagickFalse)
{
/*
User released up button.
*/
delay=SuspendTime << 2;
north_info.raised=MagickTrue;
XDrawTriangleNorth(display,&windows->widget,&north_info);
}
if (south_info.raised == MagickFalse)
{
/*
User released down button.
*/
delay=SuspendTime << 2;
south_info.raised=MagickTrue;
XDrawTriangleSouth(display,&windows->widget,&south_info);
}
if (slider_info.active)
{
/*
Stop tracking slider.
*/
slider_info.active=MagickFalse;
break;
}
if (back_info.raised == MagickFalse)
{
if (event.xbutton.window == windows->widget.id)
if (MatteIsActive(back_info,event.xbutton))
{
(void) CopyMagickString(glob_pattern,back_pattern,
MagickPathExtent);
state|=UpdateListState;
}
back_info.raised=MagickTrue;
XDrawBeveledButton(display,&windows->widget,&back_info);
}
if (reset_info.raised == MagickFalse)
{
if (event.xbutton.window == windows->widget.id)
if (MatteIsActive(reset_info,event.xbutton))
{
(void) CopyMagickString(back_pattern,glob_pattern,MagickPathExtent);
(void) CopyMagickString(glob_pattern,reset_pattern,MagickPathExtent);
state|=UpdateListState;
}
reset_info.raised=MagickTrue;
XDrawBeveledButton(display,&windows->widget,&reset_info);
}
if (action_info.raised == MagickFalse)
{
if (event.xbutton.window == windows->widget.id)
{
if (MatteIsActive(action_info,event.xbutton))
{
if (*reply_info.text == '\0')
(void) XBell(display,0);
else
state|=ExitState;
}
}
action_info.raised=MagickTrue;
XDrawBeveledButton(display,&windows->widget,&action_info);
}
if (cancel_info.raised == MagickFalse)
{
if (event.xbutton.window == windows->widget.id)
if (MatteIsActive(cancel_info,event.xbutton))
{
*reply_info.text='\0';
state|=ExitState;
}
cancel_info.raised=MagickTrue;
XDrawBeveledButton(display,&windows->widget,&cancel_info);
}
break;
}
case ClientMessage:
{
/*
If client window delete message, exit.
*/
if (event.xclient.message_type != windows->wm_protocols)
break;
if (*event.xclient.data.l == (int) windows->wm_take_focus)
{
(void) XSetInputFocus(display,event.xclient.window,RevertToParent,
(Time) event.xclient.data.l[1]);
break;
}
if (*event.xclient.data.l != (int) windows->wm_delete_window)
break;
if (event.xclient.window == windows->widget.id)
{
*reply_info.text='\0';
state|=ExitState;
break;
}
break;
}
case ConfigureNotify:
{
/*
Update widget configuration.
*/
if (event.xconfigure.window != windows->widget.id)
break;
if ((event.xconfigure.width == (int) windows->widget.width) &&
(event.xconfigure.height == (int) windows->widget.height))
break;
windows->widget.width=(unsigned int)
MagickMax(event.xconfigure.width,(int) windows->widget.min_width);
windows->widget.height=(unsigned int)
MagickMax(event.xconfigure.height,(int) windows->widget.min_height);
state|=UpdateConfigurationState;
break;
}
case EnterNotify:
{
if (event.xcrossing.window != windows->widget.id)
break;
state&=(~InactiveWidgetState);
break;
}
case Expose:
{
if (event.xexpose.window != windows->widget.id)
break;
if (event.xexpose.count != 0)
break;
state|=RedrawWidgetState;
break;
}
case KeyPress:
{
static char
command[MagickPathExtent];
static int
length;
static KeySym
key_symbol;
/*
Respond to a user key press.
*/
if (event.xkey.window != windows->widget.id)
break;
length=XLookupString((XKeyEvent *) &event.xkey,command,
(int) sizeof(command),&key_symbol,(XComposeStatus *) NULL);
*(command+length)='\0';
if (AreaIsActive(scroll_info,event.xkey))
{
/*
Move slider.
*/
switch ((int) key_symbol)
{
case XK_Home:
case XK_KP_Home:
{
slider_info.id=0;
break;
}
case XK_Up:
case XK_KP_Up:
{
slider_info.id--;
break;
}
case XK_Down:
case XK_KP_Down:
{
slider_info.id++;
break;
}
case XK_Prior:
case XK_KP_Prior:
{
slider_info.id-=visible_fonts;
break;
}
case XK_Next:
case XK_KP_Next:
{
slider_info.id+=visible_fonts;
break;
}
case XK_End:
case XK_KP_End:
{
slider_info.id=fonts;
break;
}
}
state|=RedrawListState;
break;
}
if ((key_symbol == XK_Return) || (key_symbol == XK_KP_Enter))
{
/*
Read new font or glob patterm.
*/
if (*reply_info.text == '\0')
break;
(void) CopyMagickString(back_pattern,glob_pattern,MagickPathExtent);
(void) CopyMagickString(glob_pattern,reply_info.text,MagickPathExtent);
state|=UpdateListState;
break;
}
if (key_symbol == XK_Control_L)
{
state|=ControlState;
break;
}
if (state & ControlState)
switch ((int) key_symbol)
{
case XK_u:
case XK_U:
{
/*
Erase the entire line of text.
*/
*reply_info.text='\0';
reply_info.cursor=reply_info.text;
reply_info.marker=reply_info.text;
reply_info.highlight=MagickFalse;
break;
}
default:
break;
}
XEditText(display,&reply_info,key_symbol,command,state);
XDrawMatteText(display,&windows->widget,&reply_info);
state|=JumpListState;
break;
}
case KeyRelease:
{
static char
command[MagickPathExtent];
static KeySym
key_symbol;
/*
Respond to a user key release.
*/
if (event.xkey.window != windows->widget.id)
break;
(void) XLookupString((XKeyEvent *) &event.xkey,command,
(int) sizeof(command),&key_symbol,(XComposeStatus *) NULL);
if (key_symbol == XK_Control_L)
state&=(~ControlState);
break;
}
case LeaveNotify:
{
if (event.xcrossing.window != windows->widget.id)
break;
state|=InactiveWidgetState;
break;
}
case MapNotify:
{
mask&=(~CWX);
mask&=(~CWY);
break;
}
case MotionNotify:
{
/*
Discard pending button motion events.
*/
while (XCheckMaskEvent(display,ButtonMotionMask,&event)) ;
if (slider_info.active)
{
/*
Move slider matte.
*/
slider_info.y=event.xmotion.y-
((slider_info.height+slider_info.bevel_width) >> 1)+1;
if (slider_info.y < slider_info.min_y)
slider_info.y=slider_info.min_y;
if (slider_info.y > slider_info.max_y)
slider_info.y=slider_info.max_y;
slider_info.id=0;
if (slider_info.y != slider_info.min_y)
slider_info.id=(fonts*(slider_info.y-slider_info.min_y+1))/
(slider_info.max_y-slider_info.min_y+1);
state|=RedrawListState;
break;
}
if (state & InactiveWidgetState)
break;
if (back_info.raised == MatteIsActive(back_info,event.xmotion))
{
/*
Back button status changed.
*/
back_info.raised=!back_info.raised;
XDrawBeveledButton(display,&windows->widget,&back_info);
break;
}
if (reset_info.raised == MatteIsActive(reset_info,event.xmotion))
{
/*
Reset button status changed.
*/
reset_info.raised=!reset_info.raised;
XDrawBeveledButton(display,&windows->widget,&reset_info);
break;
}
if (action_info.raised == MatteIsActive(action_info,event.xmotion))
{
/*
Action button status changed.
*/
action_info.raised=action_info.raised == MagickFalse ?
MagickTrue : MagickFalse;
XDrawBeveledButton(display,&windows->widget,&action_info);
break;
}
if (cancel_info.raised == MatteIsActive(cancel_info,event.xmotion))
{
/*
Cancel button status changed.
*/
cancel_info.raised=cancel_info.raised == MagickFalse ?
MagickTrue : MagickFalse;
XDrawBeveledButton(display,&windows->widget,&cancel_info);
break;
}
break;
}
case SelectionClear:
{
reply_info.highlight=MagickFalse;
XDrawMatteText(display,&windows->widget,&reply_info);
break;
}
case SelectionNotify:
{
Atom
type;
int
format;
unsigned char
*data;
unsigned long
after,
length;
/*
Obtain response from primary selection.
*/
if (event.xselection.property == (Atom) None)
break;
status=XGetWindowProperty(display,event.xselection.requestor,
event.xselection.property,0L,2047L,MagickTrue,XA_STRING,&type,
&format,&length,&after,&data);
if ((status != Success) || (type != XA_STRING) || (format == 32) ||
(length == 0))
break;
if ((Extent(reply_info.text)+length) >= (MagickPathExtent-1))
(void) XBell(display,0);
else
{
/*
Insert primary selection in reply text.
*/
*(data+length)='\0';
XEditText(display,&reply_info,(KeySym) XK_Insert,(char *) data,
state);
XDrawMatteText(display,&windows->widget,&reply_info);
state|=JumpListState;
state|=RedrawActionState;
}
(void) XFree((void *) data);
break;
}
case SelectionRequest:
{
XSelectionEvent
notify;
XSelectionRequestEvent
*request;
/*
Set XA_PRIMARY selection.
*/
request=(&(event.xselectionrequest));
(void) XChangeProperty(request->display,request->requestor,
request->property,request->target,8,PropModeReplace,
(unsigned char *) primary_selection,Extent(primary_selection));
notify.type=SelectionNotify;
notify.display=request->display;
notify.requestor=request->requestor;
notify.selection=request->selection;
notify.target=request->target;
notify.time=request->time;
if (request->property == None)
notify.property=request->target;
else
notify.property=request->property;
(void) XSendEvent(request->display,request->requestor,False,0,
(XEvent *) ¬ify);
}
default:
break;
}
} while ((state & ExitState) == 0);
XSetCursorState(display,windows,MagickFalse);
(void) XWithdrawWindow(display,windows->widget.id,windows->widget.screen);
XCheckRefreshWindows(display,windows);
/*
Free font list.
*/
(void) XFreeFontNames(listhead);
fontlist=(char **) RelinquishMagickMemory(fontlist);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% X I n f o W i d g e t %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% XInfoWidget() displays text in the Info widget. The purpose is to inform
% the user that what activity is currently being performed (e.g. reading
% an image, rotating an image, etc.).
%
% The format of the XInfoWidget method is:
%
% void XInfoWidget(Display *display,XWindows *windows,const char *activity)
%
% A description of each parameter follows:
%
% o display: Specifies a connection to an X server; returned from
% XOpenDisplay.
%
% o window: Specifies a pointer to a XWindows structure.
%
% o activity: This character string reflects the current activity and is
% displayed in the Info widget.
%
*/
MagickPrivate void XInfoWidget(Display *display,XWindows *windows,
const char *activity)
{
unsigned int
height,
margin,
width;
XFontStruct
*font_info;
XWindowChanges
window_changes;
/*
Map Info widget.
*/
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(display != (Display *) NULL);
assert(windows != (XWindows *) NULL);
assert(activity != (char *) NULL);
font_info=windows->info.font_info;
width=WidgetTextWidth(font_info,(char *) activity)+((3*QuantumMargin) >> 1)+4;
height=(unsigned int) (((6*(font_info->ascent+font_info->descent)) >> 2)+4);
if ((windows->info.width != width) || (windows->info.height != height))
{
/*
Size Info widget to accommodate the activity text.
*/
windows->info.width=width;
windows->info.height=height;
window_changes.width=(int) width;
window_changes.height=(int) height;
(void) XReconfigureWMWindow(display,windows->info.id,windows->info.screen,
(unsigned int) (CWWidth | CWHeight),&window_changes);
}
if (windows->info.mapped == MagickFalse)
{
(void) XMapRaised(display,windows->info.id);
windows->info.mapped=MagickTrue;
}
/*
Initialize Info matte information.
*/
height=(unsigned int) (font_info->ascent+font_info->descent);
XGetWidgetInfo(activity,&monitor_info);
monitor_info.bevel_width--;
margin=monitor_info.bevel_width+((windows->info.height-height) >> 1)-2;
monitor_info.center=MagickFalse;
monitor_info.x=(int) margin;
monitor_info.y=(int) margin;
monitor_info.width=windows->info.width-(margin << 1);
monitor_info.height=windows->info.height-(margin << 1)+1;
/*
Draw Info widget.
*/
monitor_info.raised=MagickFalse;
XDrawBeveledMatte(display,&windows->info,&monitor_info);
monitor_info.raised=MagickTrue;
XDrawWidgetText(display,&windows->info,&monitor_info);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% X L i s t B r o w s e r W i d g e t %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% XListBrowserWidget() displays a List Browser widget with a query to the
% user. The user keys a reply or select a reply from the list. Finally, the
% user presses the Action or Cancel button to exit. The typed text is
% returned as the reply function parameter.
%
% The format of the XListBrowserWidget method is:
%
% void XListBrowserWidget(Display *display,XWindows *windows,
% XWindowInfo *window_info,const char **list,const char *action,
% const char *query,char *reply)
%
% A description of each parameter follows:
%
% o display: Specifies a connection to an X server; returned from
% XOpenDisplay.
%
% o window: Specifies a pointer to a XWindows structure.
%
% o list: Specifies a pointer to an array of strings. The user can
% select from these strings as a possible reply value.
%
% o action: Specifies a pointer to the action of this widget.
%
% o query: Specifies a pointer to the query to present to the user.
%
% o reply: the response from the user is returned in this parameter.
%
*/
MagickPrivate void XListBrowserWidget(Display *display,XWindows *windows,
XWindowInfo *window_info,const char **list,const char *action,
const char *query,char *reply)
{
#define CancelButtonText "Cancel"
char
primary_selection[MagickPathExtent];
int
x;
register int
i;
static MagickStatusType
mask = (MagickStatusType) (CWWidth | CWHeight | CWX | CWY);
Status
status;
unsigned int
entries,
height,
text_width,
visible_entries,
width;
size_t
delay,
state;
XEvent
event;
XFontStruct
*font_info;
XTextProperty
window_name;
XWidgetInfo
action_info,
cancel_info,
expose_info,
list_info,
north_info,
reply_info,
scroll_info,
selection_info,
slider_info,
south_info,
text_info;
XWindowChanges
window_changes;
/*
Count the number of entries in the list.
*/
assert(display != (Display *) NULL);
assert(windows != (XWindows *) NULL);
assert(window_info != (XWindowInfo *) NULL);
assert(list != (const char **) NULL);
assert(action != (char *) NULL);
assert(query != (char *) NULL);
assert(reply != (char *) NULL);
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",action);
XSetCursorState(display,windows,MagickTrue);
XCheckRefreshWindows(display,windows);
if (list == (const char **) NULL)
{
XNoticeWidget(display,windows,"No text to browse:",(char *) NULL);
return;
}
for (entries=0; ; entries++)
if (list[entries] == (char *) NULL)
break;
/*
Determine Font Browser widget attributes.
*/
font_info=window_info->font_info;
text_width=WidgetTextWidth(font_info,(char *) query);
for (i=0; i < (int) entries; i++)
if (WidgetTextWidth(font_info,(char *) list[i]) > text_width)
text_width=WidgetTextWidth(font_info,(char *) list[i]);
width=WidgetTextWidth(font_info,(char *) action);
if (WidgetTextWidth(font_info,CancelButtonText) > width)
width=WidgetTextWidth(font_info,CancelButtonText);
width+=QuantumMargin;
height=(unsigned int) (font_info->ascent+font_info->descent);
/*
Position List Browser widget.
*/
window_info->width=(unsigned int) MagickMin((int) text_width,(int)
MaxTextWidth)+((9*QuantumMargin) >> 1);
window_info->min_width=(unsigned int) (MinTextWidth+4*QuantumMargin);
if (window_info->width < window_info->min_width)
window_info->width=window_info->min_width;
window_info->height=(unsigned int)
(((81*height) >> 2)+((13*QuantumMargin) >> 1)+4);
window_info->min_height=(unsigned int)
(((23*height) >> 1)+((13*QuantumMargin) >> 1)+4);
if (window_info->height < window_info->min_height)
window_info->height=window_info->min_height;
XConstrainWindowPosition(display,window_info);
/*
Map List Browser widget.
*/
(void) CopyMagickString(window_info->name,"Browse",MagickPathExtent);
status=XStringListToTextProperty(&window_info->name,1,&window_name);
if (status != False)
{
XSetWMName(display,window_info->id,&window_name);
XSetWMIconName(display,windows->widget.id,&window_name);
(void) XFree((void *) window_name.value);
}
window_changes.width=(int) window_info->width;
window_changes.height=(int) window_info->height;
window_changes.x=window_info->x;
window_changes.y=window_info->y;
(void) XReconfigureWMWindow(display,window_info->id,window_info->screen,mask,
&window_changes);
(void) XMapRaised(display,window_info->id);
window_info->mapped=MagickFalse;
/*
Respond to X events.
*/
XGetWidgetInfo((char *) NULL,&slider_info);
XGetWidgetInfo((char *) NULL,&north_info);
XGetWidgetInfo((char *) NULL,&south_info);
XGetWidgetInfo((char *) NULL,&expose_info);
XGetWidgetInfo((char *) NULL,&selection_info);
visible_entries=0;
delay=SuspendTime << 2;
state=UpdateConfigurationState;
do
{
if (state & UpdateConfigurationState)
{
int
id;
/*
Initialize button information.
*/
XGetWidgetInfo(CancelButtonText,&cancel_info);
cancel_info.width=width;
cancel_info.height=(unsigned int) ((3*height) >> 1);
cancel_info.x=(int)
(window_info->width-cancel_info.width-QuantumMargin-2);
cancel_info.y=(int)
(window_info->height-cancel_info.height-QuantumMargin);
XGetWidgetInfo(action,&action_info);
action_info.width=width;
action_info.height=(unsigned int) ((3*height) >> 1);
action_info.x=cancel_info.x-(cancel_info.width+(QuantumMargin >> 1)+
(action_info.bevel_width << 1));
action_info.y=cancel_info.y;
/*
Initialize reply information.
*/
XGetWidgetInfo(reply,&reply_info);
reply_info.raised=MagickFalse;
reply_info.bevel_width--;
reply_info.width=window_info->width-((4*QuantumMargin) >> 1);
reply_info.height=height << 1;
reply_info.x=QuantumMargin;
reply_info.y=action_info.y-reply_info.height-QuantumMargin;
/*
Initialize scroll information.
*/
XGetWidgetInfo((char *) NULL,&scroll_info);
scroll_info.bevel_width--;
scroll_info.width=height;
scroll_info.height=(unsigned int)
(reply_info.y-((6*QuantumMargin) >> 1)-height);
scroll_info.x=reply_info.x+(reply_info.width-scroll_info.width);
scroll_info.y=((5*QuantumMargin) >> 1)+height-reply_info.bevel_width;
scroll_info.raised=MagickFalse;
scroll_info.trough=MagickTrue;
north_info=scroll_info;
north_info.raised=MagickTrue;
north_info.width-=(north_info.bevel_width << 1);
north_info.height=north_info.width-1;
north_info.x+=north_info.bevel_width;
north_info.y+=north_info.bevel_width;
south_info=north_info;
south_info.y=scroll_info.y+scroll_info.height-scroll_info.bevel_width-
south_info.height;
id=slider_info.id;
slider_info=north_info;
slider_info.id=id;
slider_info.width-=2;
slider_info.min_y=north_info.y+north_info.height+north_info.bevel_width+
slider_info.bevel_width+2;
slider_info.height=scroll_info.height-((slider_info.min_y-
scroll_info.y+1) << 1)+4;
visible_entries=scroll_info.height/(height+(height >> 3));
if (entries > visible_entries)
slider_info.height=(visible_entries*slider_info.height)/entries;
slider_info.max_y=south_info.y-south_info.bevel_width-
slider_info.bevel_width-2;
slider_info.x=scroll_info.x+slider_info.bevel_width+1;
slider_info.y=slider_info.min_y;
expose_info=scroll_info;
expose_info.y=slider_info.y;
/*
Initialize list information.
*/
XGetWidgetInfo((char *) NULL,&list_info);
list_info.raised=MagickFalse;
list_info.bevel_width--;
list_info.width=(unsigned int)
(scroll_info.x-reply_info.x-(QuantumMargin >> 1));
list_info.height=scroll_info.height;
list_info.x=reply_info.x;
list_info.y=scroll_info.y;
if (window_info->mapped == MagickFalse)
for (i=0; i < (int) entries; i++)
if (LocaleCompare(list[i],reply) == 0)
{
list_info.id=i;
slider_info.id=i-(visible_entries >> 1);
if (slider_info.id < 0)
slider_info.id=0;
}
/*
Initialize text information.
*/
XGetWidgetInfo(query,&text_info);
text_info.width=reply_info.width;
text_info.height=height;
text_info.x=list_info.x-(QuantumMargin >> 1);
text_info.y=QuantumMargin;
/*
Initialize selection information.
*/
XGetWidgetInfo((char *) NULL,&selection_info);
selection_info.center=MagickFalse;
selection_info.width=list_info.width;
selection_info.height=(unsigned int) ((9*height) >> 3);
selection_info.x=list_info.x;
state&=(~UpdateConfigurationState);
}
if (state & RedrawWidgetState)
{
/*
Redraw List Browser window.
*/
XDrawWidgetText(display,window_info,&text_info);
XDrawBeveledMatte(display,window_info,&list_info);
XDrawBeveledMatte(display,window_info,&scroll_info);
XDrawTriangleNorth(display,window_info,&north_info);
XDrawBeveledButton(display,window_info,&slider_info);
XDrawTriangleSouth(display,window_info,&south_info);
XDrawBeveledMatte(display,window_info,&reply_info);
XDrawMatteText(display,window_info,&reply_info);
XDrawBeveledButton(display,window_info,&action_info);
XDrawBeveledButton(display,window_info,&cancel_info);
XHighlightWidget(display,window_info,BorderOffset,BorderOffset);
selection_info.id=(~0);
state|=RedrawActionState;
state|=RedrawListState;
state&=(~RedrawWidgetState);
}
if (state & RedrawListState)
{
/*
Determine slider id and position.
*/
if (slider_info.id >= (int) (entries-visible_entries))
slider_info.id=(int) (entries-visible_entries);
if ((slider_info.id < 0) || (entries <= visible_entries))
slider_info.id=0;
slider_info.y=slider_info.min_y;
if (entries > 0)
slider_info.y+=
slider_info.id*(slider_info.max_y-slider_info.min_y+1)/entries;
if (slider_info.id != selection_info.id)
{
/*
Redraw scroll bar and file names.
*/
selection_info.id=slider_info.id;
selection_info.y=list_info.y+(height >> 3)+2;
for (i=0; i < (int) visible_entries; i++)
{
selection_info.raised=(slider_info.id+i) != list_info.id ?
MagickTrue : MagickFalse;
selection_info.text=(char *) NULL;
if ((slider_info.id+i) < (int) entries)
selection_info.text=(char *) list[slider_info.id+i];
XDrawWidgetText(display,window_info,&selection_info);
selection_info.y+=(int) selection_info.height;
}
/*
Update slider.
*/
if (slider_info.y > expose_info.y)
{
expose_info.height=(unsigned int) slider_info.y-expose_info.y;
expose_info.y=slider_info.y-expose_info.height-
slider_info.bevel_width-1;
}
else
{
expose_info.height=(unsigned int) expose_info.y-slider_info.y;
expose_info.y=slider_info.y+slider_info.height+
slider_info.bevel_width+1;
}
XDrawTriangleNorth(display,window_info,&north_info);
XDrawMatte(display,window_info,&expose_info);
XDrawBeveledButton(display,window_info,&slider_info);
XDrawTriangleSouth(display,window_info,&south_info);
expose_info.y=slider_info.y;
}
state&=(~RedrawListState);
}
/*
Wait for next event.
*/
if (north_info.raised && south_info.raised)
(void) XIfEvent(display,&event,XScreenEvent,(char *) windows);
else
{
/*
Brief delay before advancing scroll bar.
*/
XDelay(display,delay);
delay=SuspendTime;
(void) XCheckIfEvent(display,&event,XScreenEvent,(char *) windows);
if (north_info.raised == MagickFalse)
if (slider_info.id > 0)
{
/*
Move slider up.
*/
slider_info.id--;
state|=RedrawListState;
}
if (south_info.raised == MagickFalse)
if (slider_info.id < (int) entries)
{
/*
Move slider down.
*/
slider_info.id++;
state|=RedrawListState;
}
if (event.type != ButtonRelease)
continue;
}
switch (event.type)
{
case ButtonPress:
{
if (MatteIsActive(slider_info,event.xbutton))
{
/*
Track slider.
*/
slider_info.active=MagickTrue;
break;
}
if (MatteIsActive(north_info,event.xbutton))
if (slider_info.id > 0)
{
/*
Move slider up.
*/
north_info.raised=MagickFalse;
slider_info.id--;
state|=RedrawListState;
break;
}
if (MatteIsActive(south_info,event.xbutton))
if (slider_info.id < (int) entries)
{
/*
Move slider down.
*/
south_info.raised=MagickFalse;
slider_info.id++;
state|=RedrawListState;
break;
}
if (MatteIsActive(scroll_info,event.xbutton))
{
/*
Move slider.
*/
if (event.xbutton.y < slider_info.y)
slider_info.id-=(visible_entries-1);
else
slider_info.id+=(visible_entries-1);
state|=RedrawListState;
break;
}
if (MatteIsActive(list_info,event.xbutton))
{
int
id;
/*
User pressed list matte.
*/
id=slider_info.id+(event.xbutton.y-(list_info.y+(height >> 1))+1)/
selection_info.height;
if (id >= (int) entries)
break;
(void) CopyMagickString(reply_info.text,list[id],MagickPathExtent);
reply_info.highlight=MagickFalse;
reply_info.marker=reply_info.text;
reply_info.cursor=reply_info.text+Extent(reply_info.text);
XDrawMatteText(display,window_info,&reply_info);
selection_info.id=(~0);
if (id == list_info.id)
{
action_info.raised=MagickFalse;
XDrawBeveledButton(display,window_info,&action_info);
state|=ExitState;
}
list_info.id=id;
state|=RedrawListState;
break;
}
if (MatteIsActive(action_info,event.xbutton))
{
/*
User pressed action button.
*/
action_info.raised=MagickFalse;
XDrawBeveledButton(display,window_info,&action_info);
break;
}
if (MatteIsActive(cancel_info,event.xbutton))
{
/*
User pressed Cancel button.
*/
cancel_info.raised=MagickFalse;
XDrawBeveledButton(display,window_info,&cancel_info);
break;
}
if (MatteIsActive(reply_info,event.xbutton) == MagickFalse)
break;
if (event.xbutton.button != Button2)
{
static Time
click_time;
/*
Move text cursor to position of button press.
*/
x=event.xbutton.x-reply_info.x-(QuantumMargin >> 2);
for (i=1; i <= Extent(reply_info.marker); i++)
if (XTextWidth(font_info,reply_info.marker,i) > x)
break;
reply_info.cursor=reply_info.marker+i-1;
if (event.xbutton.time > (click_time+DoubleClick))
reply_info.highlight=MagickFalse;
else
{
/*
Become the XA_PRIMARY selection owner.
*/
(void) CopyMagickString(primary_selection,reply_info.text,
MagickPathExtent);
(void) XSetSelectionOwner(display,XA_PRIMARY,window_info->id,
event.xbutton.time);
reply_info.highlight=XGetSelectionOwner(display,XA_PRIMARY) ==
window_info->id ? MagickTrue : MagickFalse;
}
XDrawMatteText(display,window_info,&reply_info);
click_time=event.xbutton.time;
break;
}
/*
Request primary selection.
*/
(void) XConvertSelection(display,XA_PRIMARY,XA_STRING,XA_STRING,
window_info->id,event.xbutton.time);
break;
}
case ButtonRelease:
{
if (window_info->mapped == MagickFalse)
break;
if (north_info.raised == MagickFalse)
{
/*
User released up button.
*/
delay=SuspendTime << 2;
north_info.raised=MagickTrue;
XDrawTriangleNorth(display,window_info,&north_info);
}
if (south_info.raised == MagickFalse)
{
/*
User released down button.
*/
delay=SuspendTime << 2;
south_info.raised=MagickTrue;
XDrawTriangleSouth(display,window_info,&south_info);
}
if (slider_info.active)
{
/*
Stop tracking slider.
*/
slider_info.active=MagickFalse;
break;
}
if (action_info.raised == MagickFalse)
{
if (event.xbutton.window == window_info->id)
{
if (MatteIsActive(action_info,event.xbutton))
{
if (*reply_info.text == '\0')
(void) XBell(display,0);
else
state|=ExitState;
}
}
action_info.raised=MagickTrue;
XDrawBeveledButton(display,window_info,&action_info);
}
if (cancel_info.raised == MagickFalse)
{
if (event.xbutton.window == window_info->id)
if (MatteIsActive(cancel_info,event.xbutton))
{
*reply_info.text='\0';
state|=ExitState;
}
cancel_info.raised=MagickTrue;
XDrawBeveledButton(display,window_info,&cancel_info);
}
if (MatteIsActive(reply_info,event.xbutton) == MagickFalse)
break;
break;
}
case ClientMessage:
{
/*
If client window delete message, exit.
*/
if (event.xclient.message_type != windows->wm_protocols)
break;
if (*event.xclient.data.l == (int) windows->wm_take_focus)
{
(void) XSetInputFocus(display,event.xclient.window,RevertToParent,
(Time) event.xclient.data.l[1]);
break;
}
if (*event.xclient.data.l != (int) windows->wm_delete_window)
break;
if (event.xclient.window == window_info->id)
{
*reply_info.text='\0';
state|=ExitState;
break;
}
break;
}
case ConfigureNotify:
{
/*
Update widget configuration.
*/
if (event.xconfigure.window != window_info->id)
break;
if ((event.xconfigure.width == (int) window_info->width) &&
(event.xconfigure.height == (int) window_info->height))
break;
window_info->width=(unsigned int)
MagickMax(event.xconfigure.width,(int) window_info->min_width);
window_info->height=(unsigned int)
MagickMax(event.xconfigure.height,(int) window_info->min_height);
state|=UpdateConfigurationState;
break;
}
case EnterNotify:
{
if (event.xcrossing.window != window_info->id)
break;
state&=(~InactiveWidgetState);
break;
}
case Expose:
{
if (event.xexpose.window != window_info->id)
break;
if (event.xexpose.count != 0)
break;
state|=RedrawWidgetState;
break;
}
case KeyPress:
{
static char
command[MagickPathExtent];
static int
length;
static KeySym
key_symbol;
/*
Respond to a user key press.
*/
if (event.xkey.window != window_info->id)
break;
length=XLookupString((XKeyEvent *) &event.xkey,command,
(int) sizeof(command),&key_symbol,(XComposeStatus *) NULL);
*(command+length)='\0';
if (AreaIsActive(scroll_info,event.xkey))
{
/*
Move slider.
*/
switch ((int) key_symbol)
{
case XK_Home:
case XK_KP_Home:
{
slider_info.id=0;
break;
}
case XK_Up:
case XK_KP_Up:
{
slider_info.id--;
break;
}
case XK_Down:
case XK_KP_Down:
{
slider_info.id++;
break;
}
case XK_Prior:
case XK_KP_Prior:
{
slider_info.id-=visible_entries;
break;
}
case XK_Next:
case XK_KP_Next:
{
slider_info.id+=visible_entries;
break;
}
case XK_End:
case XK_KP_End:
{
slider_info.id=(int) entries;
break;
}
}
state|=RedrawListState;
break;
}
if ((key_symbol == XK_Return) || (key_symbol == XK_KP_Enter))
{
/*
Read new entry.
*/
if (*reply_info.text == '\0')
break;
action_info.raised=MagickFalse;
XDrawBeveledButton(display,window_info,&action_info);
state|=ExitState;
break;
}
if (key_symbol == XK_Control_L)
{
state|=ControlState;
break;
}
if (state & ControlState)
switch ((int) key_symbol)
{
case XK_u:
case XK_U:
{
/*
Erase the entire line of text.
*/
*reply_info.text='\0';
reply_info.cursor=reply_info.text;
reply_info.marker=reply_info.text;
reply_info.highlight=MagickFalse;
break;
}
default:
break;
}
XEditText(display,&reply_info,key_symbol,command,state);
XDrawMatteText(display,window_info,&reply_info);
break;
}
case KeyRelease:
{
static char
command[MagickPathExtent];
static KeySym
key_symbol;
/*
Respond to a user key release.
*/
if (event.xkey.window != window_info->id)
break;
(void) XLookupString((XKeyEvent *) &event.xkey,command,
(int) sizeof(command),&key_symbol,(XComposeStatus *) NULL);
if (key_symbol == XK_Control_L)
state&=(~ControlState);
break;
}
case LeaveNotify:
{
if (event.xcrossing.window != window_info->id)
break;
state|=InactiveWidgetState;
break;
}
case MapNotify:
{
mask&=(~CWX);
mask&=(~CWY);
break;
}
case MotionNotify:
{
/*
Discard pending button motion events.
*/
while (XCheckMaskEvent(display,ButtonMotionMask,&event)) ;
if (slider_info.active)
{
/*
Move slider matte.
*/
slider_info.y=event.xmotion.y-
((slider_info.height+slider_info.bevel_width) >> 1)+1;
if (slider_info.y < slider_info.min_y)
slider_info.y=slider_info.min_y;
if (slider_info.y > slider_info.max_y)
slider_info.y=slider_info.max_y;
slider_info.id=0;
if (slider_info.y != slider_info.min_y)
slider_info.id=(int) ((entries*(slider_info.y-
slider_info.min_y+1))/(slider_info.max_y-slider_info.min_y+1));
state|=RedrawListState;
break;
}
if (state & InactiveWidgetState)
break;
if (action_info.raised == MatteIsActive(action_info,event.xmotion))
{
/*
Action button status changed.
*/
action_info.raised=action_info.raised == MagickFalse ?
MagickTrue : MagickFalse;
XDrawBeveledButton(display,window_info,&action_info);
break;
}
if (cancel_info.raised == MatteIsActive(cancel_info,event.xmotion))
{
/*
Cancel button status changed.
*/
cancel_info.raised=cancel_info.raised == MagickFalse ?
MagickTrue : MagickFalse;
XDrawBeveledButton(display,window_info,&cancel_info);
break;
}
break;
}
case SelectionClear:
{
reply_info.highlight=MagickFalse;
XDrawMatteText(display,window_info,&reply_info);
break;
}
case SelectionNotify:
{
Atom
type;
int
format;
unsigned char
*data;
unsigned long
after,
length;
/*
Obtain response from primary selection.
*/
if (event.xselection.property == (Atom) None)
break;
status=XGetWindowProperty(display,
event.xselection.requestor,event.xselection.property,0L,2047L,
MagickTrue,XA_STRING,&type,&format,&length,&after,&data);
if ((status != Success) || (type != XA_STRING) || (format == 32) ||
(length == 0))
break;
if ((Extent(reply_info.text)+length) >= (MagickPathExtent-1))
(void) XBell(display,0);
else
{
/*
Insert primary selection in reply text.
*/
*(data+length)='\0';
XEditText(display,&reply_info,(KeySym) XK_Insert,(char *) data,
state);
XDrawMatteText(display,window_info,&reply_info);
state|=RedrawActionState;
}
(void) XFree((void *) data);
break;
}
case SelectionRequest:
{
XSelectionEvent
notify;
XSelectionRequestEvent
*request;
if (reply_info.highlight == MagickFalse)
break;
/*
Set primary selection.
*/
request=(&(event.xselectionrequest));
(void) XChangeProperty(request->display,request->requestor,
request->property,request->target,8,PropModeReplace,
(unsigned char *) primary_selection,Extent(primary_selection));
notify.type=SelectionNotify;
notify.send_event=MagickTrue;
notify.display=request->display;
notify.requestor=request->requestor;
notify.selection=request->selection;
notify.target=request->target;
notify.time=request->time;
if (request->property == None)
notify.property=request->target;
else
notify.property=request->property;
(void) XSendEvent(request->display,request->requestor,False,NoEventMask,
(XEvent *) ¬ify);
}
default:
break;
}
} while ((state & ExitState) == 0);
XSetCursorState(display,windows,MagickFalse);
(void) XWithdrawWindow(display,window_info->id,window_info->screen);
XCheckRefreshWindows(display,windows);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% X M e n u W i d g e t %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% XMenuWidget() maps a menu and returns the command pointed to by the user
% when the button is released.
%
% The format of the XMenuWidget method is:
%
% int XMenuWidget(Display *display,XWindows *windows,const char *title,
% const char **selections,char *item)
%
% A description of each parameter follows:
%
% o selection_number: Specifies the number of the selection that the
% user choose.
%
% o display: Specifies a connection to an X server; returned from
% XOpenDisplay.
%
% o window: Specifies a pointer to a XWindows structure.
%
% o title: Specifies a character string that describes the menu selections.
%
% o selections: Specifies a pointer to one or more strings that comprise
% the choices in the menu.
%
% o item: Specifies a character array. The item selected from the menu
% is returned here.
%
*/
MagickPrivate int XMenuWidget(Display *display,XWindows *windows,
const char *title,const char **selections,char *item)
{
Cursor
cursor;
int
id,
x,
y;
unsigned int
height,
number_selections,
title_height,
top_offset,
width;
size_t
state;
XEvent
event;
XFontStruct
*font_info;
XSetWindowAttributes
window_attributes;
XWidgetInfo
highlight_info,
menu_info,
selection_info;
XWindowChanges
window_changes;
/*
Determine Menu widget attributes.
*/
assert(display != (Display *) NULL);
assert(windows != (XWindows *) NULL);
assert(title != (char *) NULL);
assert(selections != (const char **) NULL);
assert(item != (char *) NULL);
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",title);
font_info=windows->widget.font_info;
windows->widget.width=submenu_info.active == 0 ?
WidgetTextWidth(font_info,(char *) title) : 0;
for (id=0; selections[id] != (char *) NULL; id++)
{
width=WidgetTextWidth(font_info,(char *) selections[id]);
if (width > windows->widget.width)
windows->widget.width=width;
}
number_selections=(unsigned int) id;
XGetWidgetInfo((char *) NULL,&menu_info);
title_height=(unsigned int) (submenu_info.active == 0 ?
(3*(font_info->descent+font_info->ascent) >> 1)+5 : 2);
width=WidgetTextWidth(font_info,(char *) title);
height=(unsigned int) ((3*(font_info->ascent+font_info->descent)) >> 1);
/*
Position Menu widget.
*/
windows->widget.width+=QuantumMargin+(menu_info.bevel_width << 1);
top_offset=title_height+menu_info.bevel_width-1;
windows->widget.height=top_offset+number_selections*height+4;
windows->widget.min_width=windows->widget.width;
windows->widget.min_height=windows->widget.height;
XQueryPosition(display,windows->widget.root,&x,&y);
windows->widget.x=x-(QuantumMargin >> 1);
if (submenu_info.active != 0)
{
windows->widget.x=
windows->command.x+windows->command.width-QuantumMargin;
toggle_info.raised=MagickTrue;
XDrawTriangleEast(display,&windows->command,&toggle_info);
}
windows->widget.y=submenu_info.active == 0 ? y-(int)
((3*title_height) >> 2) : y;
if (submenu_info.active != 0)
windows->widget.y=windows->command.y+submenu_info.y;
XConstrainWindowPosition(display,&windows->widget);
/*
Map Menu widget.
*/
window_attributes.override_redirect=MagickTrue;
(void) XChangeWindowAttributes(display,windows->widget.id,
(size_t) CWOverrideRedirect,&window_attributes);
window_changes.width=(int) windows->widget.width;
window_changes.height=(int) windows->widget.height;
window_changes.x=windows->widget.x;
window_changes.y=windows->widget.y;
(void) XReconfigureWMWindow(display,windows->widget.id,windows->widget.screen,
(unsigned int) (CWWidth | CWHeight | CWX | CWY),&window_changes);
(void) XMapRaised(display,windows->widget.id);
windows->widget.mapped=MagickFalse;
/*
Respond to X events.
*/
selection_info.height=height;
cursor=XCreateFontCursor(display,XC_right_ptr);
(void) XCheckDefineCursor(display,windows->image.id,cursor);
(void) XCheckDefineCursor(display,windows->command.id,cursor);
(void) XCheckDefineCursor(display,windows->widget.id,cursor);
state=UpdateConfigurationState;
do
{
if (state & UpdateConfigurationState)
{
/*
Initialize selection information.
*/
XGetWidgetInfo((char *) NULL,&menu_info);
menu_info.bevel_width--;
menu_info.width=windows->widget.width-((menu_info.bevel_width) << 1);
menu_info.height=windows->widget.height-((menu_info.bevel_width) << 1);
menu_info.x=(int) menu_info.bevel_width;
menu_info.y=(int) menu_info.bevel_width;
XGetWidgetInfo((char *) NULL,&selection_info);
selection_info.center=MagickFalse;
selection_info.width=menu_info.width;
selection_info.height=height;
selection_info.x=menu_info.x;
highlight_info=selection_info;
highlight_info.bevel_width--;
highlight_info.width-=(highlight_info.bevel_width << 1);
highlight_info.height-=(highlight_info.bevel_width << 1);
highlight_info.x+=highlight_info.bevel_width;
state&=(~UpdateConfigurationState);
}
if (state & RedrawWidgetState)
{
/*
Redraw Menu widget.
*/
if (submenu_info.active == 0)
{
y=(int) title_height;
XSetBevelColor(display,&windows->widget,MagickFalse);
(void) XDrawLine(display,windows->widget.id,
windows->widget.widget_context,selection_info.x,y-1,
(int) selection_info.width,y-1);
XSetBevelColor(display,&windows->widget,MagickTrue);
(void) XDrawLine(display,windows->widget.id,
windows->widget.widget_context,selection_info.x,y,
(int) selection_info.width,y);
(void) XSetFillStyle(display,windows->widget.widget_context,
FillSolid);
}
/*
Draw menu selections.
*/
selection_info.center=MagickTrue;
selection_info.y=(int) menu_info.bevel_width;
selection_info.text=(char *) title;
if (submenu_info.active == 0)
XDrawWidgetText(display,&windows->widget,&selection_info);
selection_info.center=MagickFalse;
selection_info.y=(int) top_offset;
for (id=0; id < (int) number_selections; id++)
{
selection_info.text=(char *) selections[id];
XDrawWidgetText(display,&windows->widget,&selection_info);
highlight_info.y=selection_info.y+highlight_info.bevel_width;
if (id == selection_info.id)
XDrawBevel(display,&windows->widget,&highlight_info);
selection_info.y+=(int) selection_info.height;
}
XDrawBevel(display,&windows->widget,&menu_info);
state&=(~RedrawWidgetState);
}
if (number_selections > 2)
{
/*
Redraw Menu line.
*/
y=(int) (top_offset+selection_info.height*(number_selections-1));
XSetBevelColor(display,&windows->widget,MagickFalse);
(void) XDrawLine(display,windows->widget.id,
windows->widget.widget_context,selection_info.x,y-1,
(int) selection_info.width,y-1);
XSetBevelColor(display,&windows->widget,MagickTrue);
(void) XDrawLine(display,windows->widget.id,
windows->widget.widget_context,selection_info.x,y,
(int) selection_info.width,y);
(void) XSetFillStyle(display,windows->widget.widget_context,FillSolid);
}
/*
Wait for next event.
*/
(void) XIfEvent(display,&event,XScreenEvent,(char *) windows);
switch (event.type)
{
case ButtonPress:
{
if (event.xbutton.window != windows->widget.id)
{
/*
exit menu.
*/
if (event.xbutton.window == windows->command.id)
(void) XPutBackEvent(display,&event);
selection_info.id=(~0);
*item='\0';
state|=ExitState;
break;
}
state&=(~InactiveWidgetState);
id=(event.xbutton.y-top_offset)/(int) selection_info.height;
selection_info.id=id;
if ((id < 0) || (id >= (int) number_selections))
break;
/*
Highlight this selection.
*/
selection_info.y=(int) (top_offset+id*selection_info.height);
selection_info.text=(char *) selections[id];
XDrawWidgetText(display,&windows->widget,&selection_info);
highlight_info.y=selection_info.y+highlight_info.bevel_width;
XDrawBevel(display,&windows->widget,&highlight_info);
break;
}
case ButtonRelease:
{
if (windows->widget.mapped == MagickFalse)
break;
if (event.xbutton.window == windows->command.id)
if ((state & InactiveWidgetState) == 0)
break;
/*
exit menu.
*/
XSetCursorState(display,windows,MagickFalse);
*item='\0';
state|=ExitState;
break;
}
case ConfigureNotify:
{
/*
Update widget configuration.
*/
if (event.xconfigure.window != windows->widget.id)
break;
if ((event.xconfigure.width == (int) windows->widget.width) &&
(event.xconfigure.height == (int) windows->widget.height))
break;
windows->widget.width=(unsigned int)
MagickMax(event.xconfigure.width,(int) windows->widget.min_width);
windows->widget.height=(unsigned int)
MagickMax(event.xconfigure.height,(int) windows->widget.min_height);
state|=UpdateConfigurationState;
break;
}
case EnterNotify:
{
if (event.xcrossing.window != windows->widget.id)
break;
if (event.xcrossing.state == 0)
break;
state&=(~InactiveWidgetState);
id=((event.xcrossing.y-top_offset)/(int) selection_info.height);
if ((selection_info.id >= 0) &&
(selection_info.id < (int) number_selections))
{
/*
Unhighlight last selection.
*/
if (id == selection_info.id)
break;
selection_info.y=(int)
(top_offset+selection_info.id*selection_info.height);
selection_info.text=(char *) selections[selection_info.id];
XDrawWidgetText(display,&windows->widget,&selection_info);
}
if ((id < 0) || (id >= (int) number_selections))
break;
/*
Highlight this selection.
*/
selection_info.id=id;
selection_info.y=(int)
(top_offset+selection_info.id*selection_info.height);
selection_info.text=(char *) selections[selection_info.id];
XDrawWidgetText(display,&windows->widget,&selection_info);
highlight_info.y=selection_info.y+highlight_info.bevel_width;
XDrawBevel(display,&windows->widget,&highlight_info);
break;
}
case Expose:
{
if (event.xexpose.window != windows->widget.id)
break;
if (event.xexpose.count != 0)
break;
state|=RedrawWidgetState;
break;
}
case LeaveNotify:
{
if (event.xcrossing.window != windows->widget.id)
break;
state|=InactiveWidgetState;
id=selection_info.id;
if ((id < 0) || (id >= (int) number_selections))
break;
/*
Unhighlight last selection.
*/
selection_info.y=(int) (top_offset+id*selection_info.height);
selection_info.id=(~0);
selection_info.text=(char *) selections[id];
XDrawWidgetText(display,&windows->widget,&selection_info);
break;
}
case MotionNotify:
{
/*
Discard pending button motion events.
*/
while (XCheckMaskEvent(display,ButtonMotionMask,&event)) ;
if (submenu_info.active != 0)
if (event.xmotion.window == windows->command.id)
{
if ((state & InactiveWidgetState) == 0)
{
if (MatteIsActive(submenu_info,event.xmotion) == MagickFalse)
{
selection_info.id=(~0);
*item='\0';
state|=ExitState;
break;
}
}
else
if (WindowIsActive(windows->command,event.xmotion))
{
selection_info.id=(~0);
*item='\0';
state|=ExitState;
break;
}
}
if (event.xmotion.window != windows->widget.id)
break;
if (state & InactiveWidgetState)
break;
id=(event.xmotion.y-top_offset)/(int) selection_info.height;
if ((selection_info.id >= 0) &&
(selection_info.id < (int) number_selections))
{
/*
Unhighlight last selection.
*/
if (id == selection_info.id)
break;
selection_info.y=(int)
(top_offset+selection_info.id*selection_info.height);
selection_info.text=(char *) selections[selection_info.id];
XDrawWidgetText(display,&windows->widget,&selection_info);
}
selection_info.id=id;
if ((id < 0) || (id >= (int) number_selections))
break;
/*
Highlight this selection.
*/
selection_info.y=(int) (top_offset+id*selection_info.height);
selection_info.text=(char *) selections[id];
XDrawWidgetText(display,&windows->widget,&selection_info);
highlight_info.y=selection_info.y+highlight_info.bevel_width;
XDrawBevel(display,&windows->widget,&highlight_info);
break;
}
default:
break;
}
} while ((state & ExitState) == 0);
(void) XFreeCursor(display,cursor);
window_attributes.override_redirect=MagickFalse;
(void) XChangeWindowAttributes(display,windows->widget.id,
(size_t) CWOverrideRedirect,&window_attributes);
(void) XWithdrawWindow(display,windows->widget.id,windows->widget.screen);
XCheckRefreshWindows(display,windows);
if (submenu_info.active != 0)
{
submenu_info.active=MagickFalse;
toggle_info.raised=MagickFalse;
XDrawTriangleEast(display,&windows->command,&toggle_info);
}
if ((selection_info.id < 0) || (selection_info.id >= (int) number_selections))
return(~0);
(void) CopyMagickString(item,selections[selection_info.id],MagickPathExtent);
return(selection_info.id);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% X N o t i c e W i d g e t %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% XNoticeWidget() displays a Notice widget with a notice to the user. The
% function returns when the user presses the "Dismiss" button.
%
% The format of the XNoticeWidget method is:
%
% void XNoticeWidget(Display *display,XWindows *windows,
% const char *reason,const char *description)
%
% A description of each parameter follows:
%
% o display: Specifies a connection to an X server; returned from
% XOpenDisplay.
%
% o window: Specifies a pointer to a XWindows structure.
%
% o reason: Specifies the message to display before terminating the
% program.
%
% o description: Specifies any description to the message.
%
*/
MagickPrivate void XNoticeWidget(Display *display,XWindows *windows,
const char *reason,const char *description)
{
#define DismissButtonText "Dismiss"
#define Timeout 8
const char
*text;
int
x,
y;
Status
status;
time_t
timer;
unsigned int
height,
width;
size_t
state;
XEvent
event;
XFontStruct
*font_info;
XTextProperty
window_name;
XWidgetInfo
dismiss_info;
XWindowChanges
window_changes;
/*
Determine Notice widget attributes.
*/
assert(display != (Display *) NULL);
assert(windows != (XWindows *) NULL);
assert(reason != (char *) NULL);
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",reason);
XDelay(display,SuspendTime << 3); /* avoid surpise with delay */
XSetCursorState(display,windows,MagickTrue);
XCheckRefreshWindows(display,windows);
font_info=windows->widget.font_info;
width=WidgetTextWidth(font_info,DismissButtonText);
text=GetLocaleExceptionMessage(XServerError,reason);
if (text != (char *) NULL)
if (WidgetTextWidth(font_info,(char *) text) > width)
width=WidgetTextWidth(font_info,(char *) text);
if (description != (char *) NULL)
{
text=GetLocaleExceptionMessage(XServerError,description);
if (text != (char *) NULL)
if (WidgetTextWidth(font_info,(char *) text) > width)
width=WidgetTextWidth(font_info,(char *) text);
}
height=(unsigned int) (font_info->ascent+font_info->descent);
/*
Position Notice widget.
*/
windows->widget.width=width+4*QuantumMargin;
windows->widget.min_width=width+QuantumMargin;
if (windows->widget.width < windows->widget.min_width)
windows->widget.width=windows->widget.min_width;
windows->widget.height=(unsigned int) (12*height);
windows->widget.min_height=(unsigned int) (7*height);
if (windows->widget.height < windows->widget.min_height)
windows->widget.height=windows->widget.min_height;
XConstrainWindowPosition(display,&windows->widget);
/*
Map Notice widget.
*/
(void) CopyMagickString(windows->widget.name,"Notice",MagickPathExtent);
status=XStringListToTextProperty(&windows->widget.name,1,&window_name);
if (status != False)
{
XSetWMName(display,windows->widget.id,&window_name);
XSetWMIconName(display,windows->widget.id,&window_name);
(void) XFree((void *) window_name.value);
}
window_changes.width=(int) windows->widget.width;
window_changes.height=(int) windows->widget.height;
window_changes.x=windows->widget.x;
window_changes.y=windows->widget.y;
(void) XReconfigureWMWindow(display,windows->widget.id,windows->widget.screen,
(unsigned int) (CWWidth | CWHeight | CWX | CWY),&window_changes);
(void) XMapRaised(display,windows->widget.id);
windows->widget.mapped=MagickFalse;
(void) XBell(display,0);
/*
Respond to X events.
*/
timer=time((time_t *) NULL)+Timeout;
state=UpdateConfigurationState;
do
{
if (time((time_t *) NULL) > timer)
break;
if (state & UpdateConfigurationState)
{
/*
Initialize Dismiss button information.
*/
XGetWidgetInfo(DismissButtonText,&dismiss_info);
dismiss_info.width=(unsigned int) QuantumMargin+
WidgetTextWidth(font_info,DismissButtonText);
dismiss_info.height=(unsigned int) ((3*height) >> 1);
dismiss_info.x=(int)
((windows->widget.width >> 1)-(dismiss_info.width >> 1));
dismiss_info.y=(int)
(windows->widget.height-(dismiss_info.height << 1));
state&=(~UpdateConfigurationState);
}
if (state & RedrawWidgetState)
{
/*
Redraw Notice widget.
*/
width=WidgetTextWidth(font_info,(char *) reason);
x=(int) ((windows->widget.width >> 1)-(width >> 1));
y=(int) ((windows->widget.height >> 1)-(height << 1));
(void) XDrawString(display,windows->widget.id,
windows->widget.annotate_context,x,y,(char *) reason,Extent(reason));
if (description != (char *) NULL)
{
width=WidgetTextWidth(font_info,(char *) description);
x=(int) ((windows->widget.width >> 1)-(width >> 1));
y+=height;
(void) XDrawString(display,windows->widget.id,
windows->widget.annotate_context,x,y,(char *) description,
Extent(description));
}
XDrawBeveledButton(display,&windows->widget,&dismiss_info);
XHighlightWidget(display,&windows->widget,BorderOffset,BorderOffset);
state&=(~RedrawWidgetState);
}
/*
Wait for next event.
*/
if (XCheckIfEvent(display,&event,XScreenEvent,(char *) windows) == MagickFalse)
{
/*
Do not block if delay > 0.
*/
XDelay(display,SuspendTime << 2);
continue;
}
switch (event.type)
{
case ButtonPress:
{
if (MatteIsActive(dismiss_info,event.xbutton))
{
/*
User pressed Dismiss button.
*/
dismiss_info.raised=MagickFalse;
XDrawBeveledButton(display,&windows->widget,&dismiss_info);
break;
}
break;
}
case ButtonRelease:
{
if (windows->widget.mapped == MagickFalse)
break;
if (dismiss_info.raised == MagickFalse)
{
if (event.xbutton.window == windows->widget.id)
if (MatteIsActive(dismiss_info,event.xbutton))
state|=ExitState;
dismiss_info.raised=MagickTrue;
XDrawBeveledButton(display,&windows->widget,&dismiss_info);
}
break;
}
case ClientMessage:
{
/*
If client window delete message, exit.
*/
if (event.xclient.message_type != windows->wm_protocols)
break;
if (*event.xclient.data.l == (int) windows->wm_take_focus)
{
(void) XSetInputFocus(display,event.xclient.window,RevertToParent,
(Time) event.xclient.data.l[1]);
break;
}
if (*event.xclient.data.l != (int) windows->wm_delete_window)
break;
if (event.xclient.window == windows->widget.id)
{
state|=ExitState;
break;
}
break;
}
case ConfigureNotify:
{
/*
Update widget configuration.
*/
if (event.xconfigure.window != windows->widget.id)
break;
if ((event.xconfigure.width == (int) windows->widget.width) &&
(event.xconfigure.height == (int) windows->widget.height))
break;
windows->widget.width=(unsigned int)
MagickMax(event.xconfigure.width,(int) windows->widget.min_width);
windows->widget.height=(unsigned int)
MagickMax(event.xconfigure.height,(int) windows->widget.min_height);
state|=UpdateConfigurationState;
break;
}
case EnterNotify:
{
if (event.xcrossing.window != windows->widget.id)
break;
state&=(~InactiveWidgetState);
break;
}
case Expose:
{
if (event.xexpose.window != windows->widget.id)
break;
if (event.xexpose.count != 0)
break;
state|=RedrawWidgetState;
break;
}
case KeyPress:
{
static char
command[MagickPathExtent];
static KeySym
key_symbol;
/*
Respond to a user key press.
*/
if (event.xkey.window != windows->widget.id)
break;
(void) XLookupString((XKeyEvent *) &event.xkey,command,
(int) sizeof(command),&key_symbol,(XComposeStatus *) NULL);
if ((key_symbol == XK_Return) || (key_symbol == XK_KP_Enter))
{
dismiss_info.raised=MagickFalse;
XDrawBeveledButton(display,&windows->widget,&dismiss_info);
state|=ExitState;
break;
}
break;
}
case LeaveNotify:
{
if (event.xcrossing.window != windows->widget.id)
break;
state|=InactiveWidgetState;
break;
}
case MotionNotify:
{
/*
Discard pending button motion events.
*/
while (XCheckMaskEvent(display,ButtonMotionMask,&event)) ;
if (state & InactiveWidgetState)
break;
if (dismiss_info.raised == MatteIsActive(dismiss_info,event.xmotion))
{
/*
Dismiss button status changed.
*/
dismiss_info.raised=
dismiss_info.raised == MagickFalse ? MagickTrue : MagickFalse;
XDrawBeveledButton(display,&windows->widget,&dismiss_info);
break;
}
break;
}
default:
break;
}
} while ((state & ExitState) == 0);
XSetCursorState(display,windows,MagickFalse);
(void) XWithdrawWindow(display,windows->widget.id,windows->widget.screen);
XCheckRefreshWindows(display,windows);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% X P r e f e r e n c e s W i d g e t %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% XPreferencesWidget() displays a Preferences widget with program preferences.
% If the user presses the Apply button, the preferences are stored in a
% configuration file in the users' home directory.
%
% The format of the XPreferencesWidget method is:
%
% MagickBooleanType XPreferencesWidget(Display *display,
% XResourceInfo *resource_info,XWindows *windows)
%
% A description of each parameter follows:
%
% o display: Specifies a connection to an X server; returned from
% XOpenDisplay.
%
% o resource_info: Specifies a pointer to a X11 XResourceInfo structure.
%
% o window: Specifies a pointer to a XWindows structure.
%
*/
MagickPrivate MagickBooleanType XPreferencesWidget(Display *display,
XResourceInfo *resource_info,XWindows *windows)
{
#define ApplyButtonText "Apply"
#define CacheButtonText "%lu mega-bytes of memory in the undo edit cache "
#define CancelButtonText "Cancel"
#define NumberPreferences 8
static const char
*Preferences[] =
{
"display image centered on a backdrop",
"confirm on program exit",
"confirm on image edits",
"correct image for display gamma",
"display warning messages",
"apply Floyd/Steinberg error diffusion to image",
"use a shared colormap for colormapped X visuals",
"display images as an X server pixmap"
};
char
cache[MagickPathExtent];
int
x,
y;
register int
i;
Status
status;
unsigned int
height,
text_width,
width;
size_t
state;
XEvent
event;
XFontStruct
*font_info;
XTextProperty
window_name;
XWidgetInfo
apply_info,
cache_info,
cancel_info,
preferences_info[NumberPreferences];
XWindowChanges
window_changes;
/*
Determine Preferences widget attributes.
*/
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"...");
assert(display != (Display *) NULL);
assert(resource_info != (XResourceInfo *) NULL);
assert(windows != (XWindows *) NULL);
XCheckRefreshWindows(display,windows);
font_info=windows->widget.font_info;
text_width=WidgetTextWidth(font_info,CacheButtonText);
for (i=0; i < NumberPreferences; i++)
if (WidgetTextWidth(font_info,(char *) Preferences[i]) > text_width)
text_width=WidgetTextWidth(font_info,(char *) Preferences[i]);
width=WidgetTextWidth(font_info,ApplyButtonText);
if (WidgetTextWidth(font_info,CancelButtonText) > width)
width=WidgetTextWidth(font_info,CancelButtonText);
width+=(unsigned int) QuantumMargin;
height=(unsigned int) (font_info->ascent+font_info->descent);
/*
Position Preferences widget.
*/
windows->widget.width=(unsigned int) (MagickMax((int) (width << 1),
(int) text_width)+6*QuantumMargin);
windows->widget.min_width=(width << 1)+QuantumMargin;
if (windows->widget.width < windows->widget.min_width)
windows->widget.width=windows->widget.min_width;
windows->widget.height=(unsigned int)
(7*height+NumberPreferences*(height+(QuantumMargin >> 1)));
windows->widget.min_height=(unsigned int)
(7*height+NumberPreferences*(height+(QuantumMargin >> 1)));
if (windows->widget.height < windows->widget.min_height)
windows->widget.height=windows->widget.min_height;
XConstrainWindowPosition(display,&windows->widget);
/*
Map Preferences widget.
*/
(void) CopyMagickString(windows->widget.name,"Preferences",MagickPathExtent);
status=XStringListToTextProperty(&windows->widget.name,1,&window_name);
if (status != False)
{
XSetWMName(display,windows->widget.id,&window_name);
XSetWMIconName(display,windows->widget.id,&window_name);
(void) XFree((void *) window_name.value);
}
window_changes.width=(int) windows->widget.width;
window_changes.height=(int) windows->widget.height;
window_changes.x=windows->widget.x;
window_changes.y=windows->widget.y;
(void) XReconfigureWMWindow(display,windows->widget.id,windows->widget.screen,
(unsigned int) (CWWidth | CWHeight | CWX | CWY),&window_changes);
(void) XMapRaised(display,windows->widget.id);
windows->widget.mapped=MagickFalse;
/*
Respond to X events.
*/
state=UpdateConfigurationState;
XSetCursorState(display,windows,MagickTrue);
do
{
if (state & UpdateConfigurationState)
{
/*
Initialize button information.
*/
XGetWidgetInfo(CancelButtonText,&cancel_info);
cancel_info.width=width;
cancel_info.height=(unsigned int) (3*height) >> 1;
cancel_info.x=(int) windows->widget.width-cancel_info.width-
(QuantumMargin << 1);
cancel_info.y=(int) windows->widget.height-
cancel_info.height-QuantumMargin;
XGetWidgetInfo(ApplyButtonText,&apply_info);
apply_info.width=width;
apply_info.height=(unsigned int) (3*height) >> 1;
apply_info.x=QuantumMargin << 1;
apply_info.y=cancel_info.y;
y=(int) (height << 1);
for (i=0; i < NumberPreferences; i++)
{
XGetWidgetInfo(Preferences[i],&preferences_info[i]);
preferences_info[i].bevel_width--;
preferences_info[i].width=(unsigned int) QuantumMargin >> 1;
preferences_info[i].height=(unsigned int) QuantumMargin >> 1;
preferences_info[i].x=QuantumMargin << 1;
preferences_info[i].y=y;
y+=height+(QuantumMargin >> 1);
}
preferences_info[0].raised=resource_info->backdrop ==
MagickFalse ? MagickTrue : MagickFalse;
preferences_info[1].raised=resource_info->confirm_exit ==
MagickFalse ? MagickTrue : MagickFalse;
preferences_info[2].raised=resource_info->confirm_edit ==
MagickFalse ? MagickTrue : MagickFalse;
preferences_info[3].raised=resource_info->gamma_correct ==
MagickFalse ? MagickTrue : MagickFalse;
preferences_info[4].raised=resource_info->display_warnings ==
MagickFalse ? MagickTrue : MagickFalse;
preferences_info[5].raised=
resource_info->quantize_info->dither_method == NoDitherMethod ?
MagickTrue : MagickFalse;
preferences_info[6].raised=resource_info->colormap !=
SharedColormap ? MagickTrue : MagickFalse;
preferences_info[7].raised=resource_info->use_pixmap ==
MagickFalse ? MagickTrue : MagickFalse;
(void) FormatLocaleString(cache,MagickPathExtent,CacheButtonText,
(unsigned long) resource_info->undo_cache);
XGetWidgetInfo(cache,&cache_info);
cache_info.bevel_width--;
cache_info.width=(unsigned int) QuantumMargin >> 1;
cache_info.height=(unsigned int) QuantumMargin >> 1;
cache_info.x=QuantumMargin << 1;
cache_info.y=y;
state&=(~UpdateConfigurationState);
}
if (state & RedrawWidgetState)
{
/*
Redraw Preferences widget.
*/
XDrawBeveledButton(display,&windows->widget,&apply_info);
XDrawBeveledButton(display,&windows->widget,&cancel_info);
for (i=0; i < NumberPreferences; i++)
XDrawBeveledButton(display,&windows->widget,&preferences_info[i]);
XDrawTriangleEast(display,&windows->widget,&cache_info);
XHighlightWidget(display,&windows->widget,BorderOffset,BorderOffset);
state&=(~RedrawWidgetState);
}
/*
Wait for next event.
*/
(void) XIfEvent(display,&event,XScreenEvent,(char *) windows);
switch (event.type)
{
case ButtonPress:
{
if (MatteIsActive(apply_info,event.xbutton))
{
/*
User pressed Apply button.
*/
apply_info.raised=MagickFalse;
XDrawBeveledButton(display,&windows->widget,&apply_info);
break;
}
if (MatteIsActive(cancel_info,event.xbutton))
{
/*
User pressed Cancel button.
*/
cancel_info.raised=MagickFalse;
XDrawBeveledButton(display,&windows->widget,&cancel_info);
break;
}
for (i=0; i < NumberPreferences; i++)
if (MatteIsActive(preferences_info[i],event.xbutton))
{
/*
User pressed a Preferences button.
*/
preferences_info[i].raised=preferences_info[i].raised ==
MagickFalse ? MagickTrue : MagickFalse;
XDrawBeveledButton(display,&windows->widget,&preferences_info[i]);
break;
}
if (MatteIsActive(cache_info,event.xbutton))
{
/*
User pressed Cache button.
*/
x=cache_info.x+cache_info.width+cache_info.bevel_width+
(QuantumMargin >> 1);
y=cache_info.y+((cache_info.height-height) >> 1);
width=WidgetTextWidth(font_info,cache);
(void) XClearArea(display,windows->widget.id,x,y,width,height,
False);
resource_info->undo_cache<<=1;
if (resource_info->undo_cache > 256)
resource_info->undo_cache=1;
(void) FormatLocaleString(cache,MagickPathExtent,CacheButtonText,
(unsigned long) resource_info->undo_cache);
cache_info.raised=MagickFalse;
XDrawTriangleEast(display,&windows->widget,&cache_info);
break;
}
break;
}
case ButtonRelease:
{
if (windows->widget.mapped == MagickFalse)
break;
if (apply_info.raised == MagickFalse)
{
if (event.xbutton.window == windows->widget.id)
if (MatteIsActive(apply_info,event.xbutton))
state|=ExitState;
apply_info.raised=MagickTrue;
XDrawBeveledButton(display,&windows->widget,&apply_info);
apply_info.raised=MagickFalse;
}
if (cancel_info.raised == MagickFalse)
{
if (event.xbutton.window == windows->widget.id)
if (MatteIsActive(cancel_info,event.xbutton))
state|=ExitState;
cancel_info.raised=MagickTrue;
XDrawBeveledButton(display,&windows->widget,&cancel_info);
}
if (cache_info.raised == MagickFalse)
{
cache_info.raised=MagickTrue;
XDrawTriangleEast(display,&windows->widget,&cache_info);
}
break;
}
case ClientMessage:
{
/*
If client window delete message, exit.
*/
if (event.xclient.message_type != windows->wm_protocols)
break;
if (*event.xclient.data.l == (int) windows->wm_take_focus)
{
(void) XSetInputFocus(display,event.xclient.window,RevertToParent,
(Time) event.xclient.data.l[1]);
break;
}
if (*event.xclient.data.l != (int) windows->wm_delete_window)
break;
if (event.xclient.window == windows->widget.id)
{
state|=ExitState;
break;
}
break;
}
case ConfigureNotify:
{
/*
Update widget configuration.
*/
if (event.xconfigure.window != windows->widget.id)
break;
if ((event.xconfigure.width == (int) windows->widget.width) &&
(event.xconfigure.height == (int) windows->widget.height))
break;
windows->widget.width=(unsigned int)
MagickMax(event.xconfigure.width,(int) windows->widget.min_width);
windows->widget.height=(unsigned int)
MagickMax(event.xconfigure.height,(int) windows->widget.min_height);
state|=UpdateConfigurationState;
break;
}
case EnterNotify:
{
if (event.xcrossing.window != windows->widget.id)
break;
state&=(~InactiveWidgetState);
break;
}
case Expose:
{
if (event.xexpose.window != windows->widget.id)
break;
if (event.xexpose.count != 0)
break;
state|=RedrawWidgetState;
break;
}
case KeyPress:
{
static char
command[MagickPathExtent];
static KeySym
key_symbol;
/*
Respond to a user key press.
*/
if (event.xkey.window != windows->widget.id)
break;
(void) XLookupString((XKeyEvent *) &event.xkey,command,
(int) sizeof(command),&key_symbol,(XComposeStatus *) NULL);
if ((key_symbol == XK_Return) || (key_symbol == XK_KP_Enter))
{
apply_info.raised=MagickFalse;
XDrawBeveledButton(display,&windows->widget,&apply_info);
state|=ExitState;
break;
}
break;
}
case LeaveNotify:
{
if (event.xcrossing.window != windows->widget.id)
break;
state|=InactiveWidgetState;
break;
}
case MotionNotify:
{
/*
Discard pending button motion events.
*/
while (XCheckMaskEvent(display,ButtonMotionMask,&event)) ;
if (state & InactiveWidgetState)
break;
if (apply_info.raised == MatteIsActive(apply_info,event.xmotion))
{
/*
Apply button status changed.
*/
apply_info.raised=
apply_info.raised == MagickFalse ? MagickTrue : MagickFalse;
XDrawBeveledButton(display,&windows->widget,&apply_info);
break;
}
if (cancel_info.raised == MatteIsActive(cancel_info,event.xmotion))
{
/*
Cancel button status changed.
*/
cancel_info.raised=
cancel_info.raised == MagickFalse ? MagickTrue : MagickFalse;
XDrawBeveledButton(display,&windows->widget,&cancel_info);
break;
}
break;
}
default:
break;
}
} while ((state & ExitState) == 0);
XSetCursorState(display,windows,MagickFalse);
(void) XWithdrawWindow(display,windows->widget.id,windows->widget.screen);
XCheckRefreshWindows(display,windows);
if (apply_info.raised)
return(MagickFalse);
/*
Save user preferences to the client configuration file.
*/
resource_info->backdrop=
preferences_info[0].raised == MagickFalse ? MagickTrue : MagickFalse;
resource_info->confirm_exit=
preferences_info[1].raised == MagickFalse ? MagickTrue : MagickFalse;
resource_info->confirm_edit=
preferences_info[2].raised == MagickFalse ? MagickTrue : MagickFalse;
resource_info->gamma_correct=
preferences_info[3].raised == MagickFalse ? MagickTrue : MagickFalse;
resource_info->display_warnings=
preferences_info[4].raised == MagickFalse ? MagickTrue : MagickFalse;
resource_info->quantize_info->dither_method=
preferences_info[5].raised == MagickFalse ?
RiemersmaDitherMethod : NoDitherMethod;
resource_info->colormap=SharedColormap;
if (preferences_info[6].raised)
resource_info->colormap=PrivateColormap;
resource_info->use_pixmap=
preferences_info[7].raised == MagickFalse ? MagickTrue : MagickFalse;
XUserPreferences(resource_info);
return(MagickTrue);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% X P r o g r e s s M o n i t o r W i d g e t %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% XProgressMonitorWidget() displays the progress a task is making in
% completing a task. A span of zero toggles the active status. An inactive
% state disables the progress monitor.
%
% The format of the XProgressMonitorWidget method is:
%
% void XProgressMonitorWidget(Display *display,XWindows *windows,
% const char *task,const MagickOffsetType offset,
% const MagickSizeType span)
%
% A description of each parameter follows:
%
% o display: Specifies a connection to an X server; returned from
% XOpenDisplay.
%
% o window: Specifies a pointer to a XWindows structure.
%
% o task: Identifies the task in progress.
%
% o offset: Specifies the offset position within the span which represents
% how much progress has been made in completing a task.
%
% o span: Specifies the span relative to completing a task.
%
*/
MagickPrivate void XProgressMonitorWidget(Display *display,XWindows *windows,
const char *task,const MagickOffsetType offset,const MagickSizeType span)
{
unsigned int
width;
XEvent
event;
assert(display != (Display *) NULL);
assert(windows != (XWindows *) NULL);
assert(task != (const char *) NULL);
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",task);
if (span == 0)
return;
/*
Update image windows if there is a pending expose event.
*/
while (XCheckTypedWindowEvent(display,windows->command.id,Expose,&event))
(void) XCommandWidget(display,windows,(const char **) NULL,&event);
while (XCheckTypedWindowEvent(display,windows->image.id,Expose,&event))
XRefreshWindow(display,&windows->image,&event);
while (XCheckTypedWindowEvent(display,windows->info.id,Expose,&event))
if (monitor_info.text != (char *) NULL)
XInfoWidget(display,windows,monitor_info.text);
/*
Draw progress monitor bar to represent percent completion of a task.
*/
if ((windows->info.mapped == MagickFalse) || (task != monitor_info.text))
XInfoWidget(display,windows,task);
width=(unsigned int) (((offset+1)*(windows->info.width-
(2*monitor_info.x)))/span);
if (width < monitor_info.width)
{
monitor_info.raised=MagickTrue;
XDrawWidgetText(display,&windows->info,&monitor_info);
monitor_info.raised=MagickFalse;
}
monitor_info.width=width;
XDrawWidgetText(display,&windows->info,&monitor_info);
(void) XFlush(display);
}
/*
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
% %
% %
% %
% X T e x t V i e w W i d g e t %
% %
% %
% %
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%
% XTextViewWidget() displays text in a Text View widget.
%
% The format of the XTextViewWidget method is:
%
% void XTextViewWidget(Display *display,const XResourceInfo *resource_info,
% XWindows *windows,const MagickBooleanType mono,const char *title,
% const char **textlist)
%
% A description of each parameter follows:
%
% o display: Specifies a connection to an X server; returned from
% XOpenDisplay.
%
% o resource_info: Specifies a pointer to a X11 XResourceInfo structure.
%
% o window: Specifies a pointer to a XWindows structure.
%
% o mono: Use mono-spaced font when displaying text.
%
% o title: This character string is displayed at the top of the widget
% window.
%
% o textlist: This string list is displayed within the Text View widget.
%
*/
MagickPrivate void XTextViewWidget(Display *display,
const XResourceInfo *resource_info,XWindows *windows,
const MagickBooleanType mono,const char *title,const char **textlist)
{
#define DismissButtonText "Dismiss"
char
primary_selection[MagickPathExtent];
register int
i;
static MagickStatusType
mask = (MagickStatusType) (CWWidth | CWHeight | CWX | CWY);
Status
status;
unsigned int
height,
lines,
text_width,
visible_lines,
width;
size_t
delay,
state;
XEvent
event;
XFontStruct
*font_info,
*text_info;
XTextProperty
window_name;
XWidgetInfo
dismiss_info,
expose_info,
list_info,
north_info,
scroll_info,
selection_info,
slider_info,
south_info;
XWindowChanges
window_changes;
/*
Convert text string to a text list.
*/
assert(display != (Display *) NULL);
assert(resource_info != (XResourceInfo *) NULL);
assert(windows != (XWindows *) NULL);
assert(title != (const char *) NULL);
assert(textlist != (const char **) NULL);
(void) LogMagickEvent(TraceEvent,GetMagickModule(),"%s",title);
XSetCursorState(display,windows,MagickTrue);
XCheckRefreshWindows(display,windows);
if (textlist == (const char **) NULL)
{
XNoticeWidget(display,windows,"No text to view:",(char *) NULL);
return;
}
/*
Determine Text View widget attributes.
*/
font_info=windows->widget.font_info;
text_info=(XFontStruct *) NULL;
if (mono != MagickFalse)
text_info=XBestFont(display,resource_info,MagickTrue);
if (text_info == (XFontStruct *) NULL)
text_info=windows->widget.font_info;
text_width=0;
for (i=0; textlist[i] != (char *) NULL; i++)
if (WidgetTextWidth(text_info,(char *) textlist[i]) > text_width)
text_width=(unsigned int) XTextWidth(text_info,(char *) textlist[i],
MagickMin(Extent(textlist[i]),160));
lines=(unsigned int) i;
width=WidgetTextWidth(font_info,DismissButtonText);
width+=QuantumMargin;
height=(unsigned int) (text_info->ascent+text_info->descent);
/*
Position Text View widget.
*/
windows->widget.width=(unsigned int) (MagickMin((int) text_width,
(int) MaxTextWidth)+5*QuantumMargin);
windows->widget.min_width=(unsigned int) (MinTextWidth+4*QuantumMargin);
if (windows->widget.width < windows->widget.min_width)
windows->widget.width=windows->widget.min_width;
windows->widget.height=(unsigned int) (MagickMin(MagickMax((int) lines,3),32)*
height+((13*height) >> 1)+((9*QuantumMargin) >> 1));
windows->widget.min_height=(unsigned int) (3*height+((13*height) >> 1)+((9*
QuantumMargin) >> 1));
if (windows->widget.height < windows->widget.min_height)
windows->widget.height=windows->widget.min_height;
XConstrainWindowPosition(display,&windows->widget);
/*
Map Text View widget.
*/
(void) CopyMagickString(windows->widget.name,title,MagickPathExtent);
status=XStringListToTextProperty(&windows->widget.name,1,&window_name);
if (status != False)
{
XSetWMName(display,windows->widget.id,&window_name);
XSetWMIconName(display,windows->widget.id,&window_name);
(void) XFree((void *) window_name.value);
}
window_changes.width=(int) windows->widget.width;
window_changes.height=(int) windows->widget.height;
window_changes.x=windows->widget.x;
window_changes.y=windows->widget.y;
(void) XReconfigureWMWindow(display,windows->widget.id,
windows->widget.screen,(unsigned int) mask,&window_changes);
(void) XMapRaised(display,windows->widget.id);
windows->widget.mapped=MagickFalse;
/*
Respond to X events.
*/
XGetWidgetInfo((char *) NULL,&slider_info);
XGetWidgetInfo((char *) NULL,&north_info);
XGetWidgetInfo((char *) NULL,&south_info);
XGetWidgetInfo((char *) NULL,&expose_info);
XGetWidgetInfo((char *) NULL,&selection_info);
visible_lines=0;
delay=SuspendTime << 2;
height=(unsigned int) (font_info->ascent+font_info->descent);
state=UpdateConfigurationState;
do
{
if (state & UpdateConfigurationState)
{
int
id;
/*
Initialize button information.
*/
XGetWidgetInfo(DismissButtonText,&dismiss_info);
dismiss_info.width=width;
dismiss_info.height=(unsigned int) ((3*height) >> 1);
dismiss_info.x=(int) windows->widget.width-dismiss_info.width-
QuantumMargin-2;
dismiss_info.y=(int) windows->widget.height-dismiss_info.height-
QuantumMargin;
/*
Initialize scroll information.
*/
XGetWidgetInfo((char *) NULL,&scroll_info);
scroll_info.bevel_width--;
scroll_info.width=height;
scroll_info.height=(unsigned int) (dismiss_info.y-((5*QuantumMargin) >>
1));
scroll_info.x=(int) windows->widget.width-QuantumMargin-
scroll_info.width;
scroll_info.y=(3*QuantumMargin) >> 1;
scroll_info.raised=MagickFalse;
scroll_info.trough=MagickTrue;
north_info=scroll_info;
north_info.raised=MagickTrue;
north_info.width-=(north_info.bevel_width << 1);
north_info.height=north_info.width-1;
north_info.x+=north_info.bevel_width;
north_info.y+=north_info.bevel_width;
south_info=north_info;
south_info.y=scroll_info.y+scroll_info.height-scroll_info.bevel_width-
south_info.height;
id=slider_info.id;
slider_info=north_info;
slider_info.id=id;
slider_info.width-=2;
slider_info.min_y=north_info.y+north_info.height+north_info.bevel_width+
slider_info.bevel_width+2;
slider_info.height=scroll_info.height-((slider_info.min_y-
scroll_info.y+1) << 1)+4;
visible_lines=scroll_info.height/(text_info->ascent+text_info->descent+
((text_info->ascent+text_info->descent) >> 3));
if (lines > visible_lines)
slider_info.height=(unsigned int) (visible_lines*slider_info.height)/
lines;
slider_info.max_y=south_info.y-south_info.bevel_width-
slider_info.bevel_width-2;
slider_info.x=scroll_info.x+slider_info.bevel_width+1;
slider_info.y=slider_info.min_y;
expose_info=scroll_info;
expose_info.y=slider_info.y;
/*
Initialize list information.
*/
XGetWidgetInfo((char *) NULL,&list_info);
list_info.raised=MagickFalse;
list_info.bevel_width--;
list_info.width=(unsigned int) scroll_info.x-((3*QuantumMargin) >> 1);
list_info.height=scroll_info.height;
list_info.x=QuantumMargin;
list_info.y=scroll_info.y;
/*
Initialize selection information.
*/
XGetWidgetInfo((char *) NULL,&selection_info);
selection_info.center=MagickFalse;
selection_info.width=list_info.width;
selection_info.height=(unsigned int)
(9*(text_info->ascent+text_info->descent)) >> 3;
selection_info.x=list_info.x;
state&=(~UpdateConfigurationState);
}
if (state & RedrawWidgetState)
{
/*
Redraw Text View window.
*/
XDrawBeveledMatte(display,&windows->widget,&list_info);
XDrawBeveledMatte(display,&windows->widget,&scroll_info);
XDrawTriangleNorth(display,&windows->widget,&north_info);
XDrawBeveledButton(display,&windows->widget,&slider_info);
XDrawTriangleSouth(display,&windows->widget,&south_info);
XDrawBeveledButton(display,&windows->widget,&dismiss_info);
XHighlightWidget(display,&windows->widget,BorderOffset,BorderOffset);
selection_info.id=(~0);
state|=RedrawListState;
state&=(~RedrawWidgetState);
}
if (state & RedrawListState)
{
/*
Determine slider id and position.
*/
if (slider_info.id >= (int) (lines-visible_lines))
slider_info.id=(int) lines-visible_lines;
if ((slider_info.id < 0) || (lines <= visible_lines))
slider_info.id=0;
slider_info.y=slider_info.min_y;
if (lines != 0)
slider_info.y+=
slider_info.id*(slider_info.max_y-slider_info.min_y+1)/lines;
if (slider_info.id != selection_info.id)
{
/*
Redraw scroll bar and text.
*/
windows->widget.font_info=text_info;
(void) XSetFont(display,windows->widget.annotate_context,
text_info->fid);
(void) XSetFont(display,windows->widget.highlight_context,
text_info->fid);
selection_info.id=slider_info.id;
selection_info.y=list_info.y+(height >> 3)+2;
for (i=0; i < (int) visible_lines; i++)
{
selection_info.raised=
(slider_info.id+i) != list_info.id ? MagickTrue : MagickFalse;
selection_info.text=(char *) NULL;
if ((slider_info.id+i) < (int) lines)
selection_info.text=(char *) textlist[slider_info.id+i];
XDrawWidgetText(display,&windows->widget,&selection_info);
selection_info.y+=(int) selection_info.height;
}
windows->widget.font_info=font_info;
(void) XSetFont(display,windows->widget.annotate_context,
font_info->fid);
(void) XSetFont(display,windows->widget.highlight_context,
font_info->fid);
/*
Update slider.
*/
if (slider_info.y > expose_info.y)
{
expose_info.height=(unsigned int) slider_info.y-expose_info.y;
expose_info.y=slider_info.y-expose_info.height-
slider_info.bevel_width-1;
}
else
{
expose_info.height=(unsigned int) expose_info.y-slider_info.y;
expose_info.y=slider_info.y+slider_info.height+
slider_info.bevel_width+1;
}
XDrawTriangleNorth(display,&windows->widget,&north_info);
XDrawMatte(display,&windows->widget,&expose_info);
XDrawBeveledButton(display,&windows->widget,&slider_info);
XDrawTriangleSouth(display,&windows->widget,&south_info);
expose_info.y=slider_info.y;
}
state&=(~RedrawListState);
}
/*
Wait for next event.
*/
if (north_info.raised && south_info.raised)
(void) XIfEvent(display,&event,XScreenEvent,(char *) windows);
else
{
/*
Brief delay before advancing scroll bar.
*/
XDelay(display,delay);
delay=SuspendTime;
(void) XCheckIfEvent(display,&event,XScreenEvent,(char *) windows);
if (north_info.raised == MagickFalse)
if (slider_info.id > 0)
{
/*
Move slider up.
*/
slider_info.id--;
state|=RedrawListState;
}
if (south_info.raised == MagickFalse)
if (slider_info.id < (int) lines)
{
/*
Move slider down.
*/
slider_info.id++;
state|=RedrawListState;
}
if (event.type != ButtonRelease)
continue;
}
switch (event.type)
{
case ButtonPress:
{
if (MatteIsActive(slider_info,event.xbutton))
{
/*
Track slider.
*/
slider_info.active=MagickTrue;
break;
}
if (MatteIsActive(north_info,event.xbutton))
if (slider_info.id > 0)
{
/*
Move slider up.
*/
north_info.raised=MagickFalse;
slider_info.id--;
state|=RedrawListState;
break;
}
if (MatteIsActive(south_info,event.xbutton))
if (slider_info.id < (int) lines)
{
/*
Move slider down.
*/
south_info.raised=MagickFalse;
slider_info.id++;
state|=RedrawListState;
break;
}
if (MatteIsActive(scroll_info,event.xbutton))
{
/*
Move slider.
*/
if (event.xbutton.y < slider_info.y)
slider_info.id-=(visible_lines-1);
else
slider_info.id+=(visible_lines-1);
state|=RedrawListState;
break;
}
if (MatteIsActive(dismiss_info,event.xbutton))
{
/*
User pressed Dismiss button.
*/
dismiss_info.raised=MagickFalse;
XDrawBeveledButton(display,&windows->widget,&dismiss_info);
break;
}
if (MatteIsActive(list_info,event.xbutton))
{
int
id;
static Time
click_time;
/*
User pressed list matte.
*/
id=slider_info.id+(event.xbutton.y-(list_info.y+(height >> 1))+1)/
selection_info.height;
if (id >= (int) lines)
break;
if (id != list_info.id)
{
list_info.id=id;
click_time=event.xbutton.time;
break;
}
list_info.id=id;
if (event.xbutton.time >= (click_time+DoubleClick))
{
click_time=event.xbutton.time;
break;
}
click_time=event.xbutton.time;
/*
Become the XA_PRIMARY selection owner.
*/
(void) CopyMagickString(primary_selection,textlist[list_info.id],
MagickPathExtent);
(void) XSetSelectionOwner(display,XA_PRIMARY,windows->widget.id,
event.xbutton.time);
if (XGetSelectionOwner(display,XA_PRIMARY) != windows->widget.id)
break;
selection_info.id=(~0);
list_info.id=id;
state|=RedrawListState;
break;
}
break;
}
case ButtonRelease:
{
if (windows->widget.mapped == MagickFalse)
break;
if (north_info.raised == MagickFalse)
{
/*
User released up button.
*/
delay=SuspendTime << 2;
north_info.raised=MagickTrue;
XDrawTriangleNorth(display,&windows->widget,&north_info);
}
if (south_info.raised == MagickFalse)
{
/*
User released down button.
*/
delay=SuspendTime << 2;
south_info.raised=MagickTrue;
XDrawTriangleSouth(display,&windows->widget,&south_info);
}
if (slider_info.active)
{
/*
Stop tracking slider.
*/
slider_info.active=MagickFalse;
break;
}
if (dismiss_info.raised == MagickFalse)
{
if (event.xbutton.window == windows->widget.id)
if (MatteIsActive(dismiss_info,event.xbutton))
state|=ExitState;
dismiss_info.raised=MagickTrue;
XDrawBeveledButton(display,&windows->widget,&dismiss_info);
}
break;
}
case ClientMessage:
{
/*
If client window delete message, exit.
*/
if (event.xclient.message_type != windows->wm_protocols)
break;
if (*event.xclient.data.l == (int) windows->wm_take_focus)
{
(void) XSetInputFocus(display,event.xclient.window,RevertToParent,
(Time) event.xclient.data.l[1]);
break;
}
if (*event.xclient.data.l != (int) windows->wm_delete_window)
break;
if (event.xclient.window == windows->widget.id)
{
state|=ExitState;
break;
}
break;
}
case ConfigureNotify:
{
/*
Update widget configuration.
*/
if (event.xconfigure.window != windows->widget.id)
break;
if ((event.xconfigure.width == (int) windows->widget.width) &&
(event.xconfigure.height == (int) windows->widget.height))
break;
windows->widget.width=(unsigned int)
MagickMax(event.xconfigure.width,(int) windows->widget.min_width);
windows->widget.height=(unsigned int)
MagickMax(event.xconfigure.height,(int) windows->widget.min_height);
state|=UpdateConfigurationState;
break;
}
case EnterNotify:
{
if (event.xcrossing.window != windows->widget.id)
break;
state&=(~InactiveWidgetState);
break;
}
case Expose:
{
if (event.xexpose.window != windows->widget.id)
break;
if (event.xexpose.count != 0)
break;
state|=RedrawWidgetState;
break;
}
case KeyPress:
{
static char
command[MagickPathExtent];
static int
length;
static KeySym
key_symbol;
/*
Respond to a user key press.
*/
if (event.xkey.window != windows->widget.id)
break;
length=XLookupString((XKeyEvent *) &event.xkey,command,
(int) sizeof(command),&key_symbol,(XComposeStatus *) NULL);
*(command+length)='\0';
if ((key_symbol == XK_Return) || (key_symbol == XK_KP_Enter))
{
dismiss_info.raised=MagickFalse;
XDrawBeveledButton(display,&windows->widget,&dismiss_info);
state|=ExitState;
break;
}
if (AreaIsActive(scroll_info,event.xkey))
{
/*
Move slider.
*/
switch ((int) key_symbol)
{
case XK_Home:
case XK_KP_Home:
{
slider_info.id=0;
break;
}
case XK_Up:
case XK_KP_Up:
{
slider_info.id--;
break;
}
case XK_Down:
case XK_KP_Down:
{
slider_info.id++;
break;
}
case XK_Prior:
case XK_KP_Prior:
{
slider_info.id-=visible_lines;
break;
}
case XK_Next:
case XK_KP_Next:
{
slider_info.id+=visible_lines;
break;
}
case XK_End:
case XK_KP_End:
{
slider_info.id=(int) lines;
break;
}
}
state|=RedrawListState;
break;
}
break;
}
case KeyRelease:
break;
case LeaveNotify:
{
if (event.xcrossing.window != windows->widget.id)
break;
state|=InactiveWidgetState;
break;
}
case MapNotify:
{
mask&=(~CWX);
mask&=(~CWY);
break;
}
case MotionNotify:
{
/*
Discard pending button motion events.
*/
while (XCheckMaskEvent(display,ButtonMotionMask,&event)) ;
if (slider_info.active)
{
/*
Move slider matte.
*/
slider_info.y=event.xmotion.y-
((slider_info.height+slider_info.bevel_width) >> 1)+1;
if (slider_info.y < slider_info.min_y)
slider_info.y=slider_info.min_y;
if (slider_info.y > slider_info.max_y)
slider_info.y=slider_info.max_y;
slider_info.id=0;
if (slider_info.y != slider_info.min_y)
slider_info.id=(int) (lines*(slider_info.y-slider_info.min_y+1))/
(slider_info.max_y-slider_info.min_y+1);
state|=RedrawListState;
break;
}
if (state & InactiveWidgetState)
break;
if (dismiss_info.raised == MatteIsActive(dismiss_info,event.xmotion))
{
/*
Dismiss button status changed.
*/
dismiss_info.raised=
dismiss_info.raised == MagickFalse ? MagickTrue : MagickFalse;
XDrawBeveledButton(display,&windows->widget,&dismiss_info);
break;
}
break;
}
case SelectionClear:
{
list_info.id=(~0);
selection_info.id=(~0);
state|=RedrawListState;
break;
}
case SelectionRequest:
{
XSelectionEvent
notify;
XSelectionRequestEvent
*request;
if (list_info.id == (~0))
break;
/*
Set primary selection.
*/
request=(&(event.xselectionrequest));
(void) XChangeProperty(request->display,request->requestor,
request->property,request->target,8,PropModeReplace,
(unsigned char *) primary_selection,Extent(primary_selection));
notify.type=SelectionNotify;
notify.send_event=MagickTrue;
notify.display=request->display;
notify.requestor=request->requestor;
notify.selection=request->selection;
notify.target=request->target;
notify.time=request->time;
if (request->property == None)
notify.property=request->target;
else
notify.property=request->property;
(void) XSendEvent(request->display,request->requestor,False,NoEventMask,
(XEvent *) ¬ify);
}
default:
break;
}
} while ((state & ExitState) == 0);
if (text_info != windows->widget.font_info)
(void) XFreeFont(display,text_info);
XSetCursorState(display,windows,MagickFalse);
(void) XWithdrawWindow(display,windows->widget.id,windows->widget.screen);
XCheckRefreshWindows(display,windows);
}
#endif
| mit |
legends420/OfficalGanjaCoin | build/moc_optionsmodel.cpp | 2 | 6228 | /****************************************************************************
** Meta object code from reading C++ file 'optionsmodel.h'
**
** Created by: The Qt Meta Object Compiler version 67 (Qt 5.5.1)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include "../src/qt/optionsmodel.h"
#include <QtCore/qbytearray.h>
#include <QtCore/qmetatype.h>
#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'optionsmodel.h' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 67
#error "This file was generated using the moc from 5.5.1. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif
QT_BEGIN_MOC_NAMESPACE
struct qt_meta_stringdata_OptionsModel_t {
QByteArrayData data[7];
char stringdata0[109];
};
#define QT_MOC_LITERAL(idx, ofs, len) \
Q_STATIC_BYTE_ARRAY_DATA_HEADER_INITIALIZER_WITH_OFFSET(len, \
qptrdiff(offsetof(qt_meta_stringdata_OptionsModel_t, stringdata0) + ofs \
- idx * sizeof(QByteArrayData)) \
)
static const qt_meta_stringdata_OptionsModel_t qt_meta_stringdata_OptionsModel = {
{
QT_MOC_LITERAL(0, 0, 12), // "OptionsModel"
QT_MOC_LITERAL(1, 13, 18), // "displayUnitChanged"
QT_MOC_LITERAL(2, 32, 0), // ""
QT_MOC_LITERAL(3, 33, 4), // "unit"
QT_MOC_LITERAL(4, 38, 21), // "transactionFeeChanged"
QT_MOC_LITERAL(5, 60, 21), // "reserveBalanceChanged"
QT_MOC_LITERAL(6, 82, 26) // "coinControlFeaturesChanged"
},
"OptionsModel\0displayUnitChanged\0\0unit\0"
"transactionFeeChanged\0reserveBalanceChanged\0"
"coinControlFeaturesChanged"
};
#undef QT_MOC_LITERAL
static const uint qt_meta_data_OptionsModel[] = {
// content:
7, // revision
0, // classname
0, 0, // classinfo
4, 14, // methods
0, 0, // properties
0, 0, // enums/sets
0, 0, // constructors
0, // flags
4, // signalCount
// signals: name, argc, parameters, tag, flags
1, 1, 34, 2, 0x06 /* Public */,
4, 1, 37, 2, 0x06 /* Public */,
5, 1, 40, 2, 0x06 /* Public */,
6, 1, 43, 2, 0x06 /* Public */,
// signals: parameters
QMetaType::Void, QMetaType::Int, 3,
QMetaType::Void, QMetaType::LongLong, 2,
QMetaType::Void, QMetaType::LongLong, 2,
QMetaType::Void, QMetaType::Bool, 2,
0 // eod
};
void OptionsModel::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
if (_c == QMetaObject::InvokeMetaMethod) {
OptionsModel *_t = static_cast<OptionsModel *>(_o);
Q_UNUSED(_t)
switch (_id) {
case 0: _t->displayUnitChanged((*reinterpret_cast< int(*)>(_a[1]))); break;
case 1: _t->transactionFeeChanged((*reinterpret_cast< qint64(*)>(_a[1]))); break;
case 2: _t->reserveBalanceChanged((*reinterpret_cast< qint64(*)>(_a[1]))); break;
case 3: _t->coinControlFeaturesChanged((*reinterpret_cast< bool(*)>(_a[1]))); break;
default: ;
}
} else if (_c == QMetaObject::IndexOfMethod) {
int *result = reinterpret_cast<int *>(_a[0]);
void **func = reinterpret_cast<void **>(_a[1]);
{
typedef void (OptionsModel::*_t)(int );
if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&OptionsModel::displayUnitChanged)) {
*result = 0;
}
}
{
typedef void (OptionsModel::*_t)(qint64 );
if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&OptionsModel::transactionFeeChanged)) {
*result = 1;
}
}
{
typedef void (OptionsModel::*_t)(qint64 );
if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&OptionsModel::reserveBalanceChanged)) {
*result = 2;
}
}
{
typedef void (OptionsModel::*_t)(bool );
if (*reinterpret_cast<_t *>(func) == static_cast<_t>(&OptionsModel::coinControlFeaturesChanged)) {
*result = 3;
}
}
}
}
const QMetaObject OptionsModel::staticMetaObject = {
{ &QAbstractListModel::staticMetaObject, qt_meta_stringdata_OptionsModel.data,
qt_meta_data_OptionsModel, qt_static_metacall, Q_NULLPTR, Q_NULLPTR}
};
const QMetaObject *OptionsModel::metaObject() const
{
return QObject::d_ptr->metaObject ? QObject::d_ptr->dynamicMetaObject() : &staticMetaObject;
}
void *OptionsModel::qt_metacast(const char *_clname)
{
if (!_clname) return Q_NULLPTR;
if (!strcmp(_clname, qt_meta_stringdata_OptionsModel.stringdata0))
return static_cast<void*>(const_cast< OptionsModel*>(this));
return QAbstractListModel::qt_metacast(_clname);
}
int OptionsModel::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
_id = QAbstractListModel::qt_metacall(_c, _id, _a);
if (_id < 0)
return _id;
if (_c == QMetaObject::InvokeMetaMethod) {
if (_id < 4)
qt_static_metacall(this, _c, _id, _a);
_id -= 4;
} else if (_c == QMetaObject::RegisterMethodArgumentMetaType) {
if (_id < 4)
*reinterpret_cast<int*>(_a[0]) = -1;
_id -= 4;
}
return _id;
}
// SIGNAL 0
void OptionsModel::displayUnitChanged(int _t1)
{
void *_a[] = { Q_NULLPTR, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) };
QMetaObject::activate(this, &staticMetaObject, 0, _a);
}
// SIGNAL 1
void OptionsModel::transactionFeeChanged(qint64 _t1)
{
void *_a[] = { Q_NULLPTR, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) };
QMetaObject::activate(this, &staticMetaObject, 1, _a);
}
// SIGNAL 2
void OptionsModel::reserveBalanceChanged(qint64 _t1)
{
void *_a[] = { Q_NULLPTR, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) };
QMetaObject::activate(this, &staticMetaObject, 2, _a);
}
// SIGNAL 3
void OptionsModel::coinControlFeaturesChanged(bool _t1)
{
void *_a[] = { Q_NULLPTR, const_cast<void*>(reinterpret_cast<const void*>(&_t1)) };
QMetaObject::activate(this, &staticMetaObject, 3, _a);
}
QT_END_MOC_NAMESPACE
| mit |
hmgle/dot_matrix_font_to_bmp | src/dot_matrix_font_to_bmp.c | 2 | 16632 | #include <stdio.h>
#include "debug_log.h"
#include "dot_matrix_font_to_bmp.h"
static void conv_row(const uint8_t *ptrfontdata, uint32_t width,
uint8_t *pdest, uint16_t bits_per_pix,
color_setting_t *pcolor);
void
set_header(bmp_file_t *pbmp_f,
uint32_t width,
uint32_t height,
uint16_t bits_per_pix)
{
uint32_t rowsize;
pbmp_f->bmp_h.magic[0] = 'B';
pbmp_f->bmp_h.magic[1] = 'M';
pbmp_f->bmp_h.offset = sizeof(bmp_file_header_t) + sizeof(dib_header_t);
pbmp_f->dib_h.dib_header_size = sizeof(dib_header_t);
pbmp_f->dib_h.width = width;
pbmp_f->dib_h.height = height;
pbmp_f->dib_h.planes = 1;
pbmp_f->dib_h.bits_per_pix = bits_per_pix;
pbmp_f->dib_h.compression = 0;
rowsize = (bits_per_pix * width + 31) / 32 * 4; /* 4字节对齐 */
pbmp_f->dib_h.image_size = rowsize * height;
pbmp_f->dib_h.x_pix_per_meter = 0;
pbmp_f->dib_h.y_pix_per_meter = 0;
pbmp_f->dib_h.colors_in_colortable = 0;
pbmp_f->dib_h.important_color_count = 0;
pbmp_f->bmp_h.file_size = pbmp_f->bmp_h.offset +
pbmp_f->dib_h.image_size;
}
void
get_header(const bmp_file_t *pbmp_f, bmp_file_header_t *bmp_header,
dib_header_t *dib_header)
{
bmp_header->magic[0] = pbmp_f->bmp_h.magic[0];
bmp_header->magic[1] = pbmp_f->bmp_h.magic[1];
bmp_header->file_size = pbmp_f->bmp_h.file_size;
bmp_header->reserved1 = pbmp_f->bmp_h.reserved1;
bmp_header->reserved2 = pbmp_f->bmp_h.reserved2;
bmp_header->offset = pbmp_f->bmp_h.offset;
dib_header->dib_header_size = pbmp_f->dib_h.dib_header_size;
}
static void
conv_row(const uint8_t *ptrfontdata,
uint32_t width,
uint8_t *pdest,
uint16_t bits_per_pix,
color_setting_t *pcolor)
{
uint32_t i;
int char_num;
int char_bit;
char bit;
uint8_t *ptmp;
ptmp = pdest;
for (i = 0; i < width; i++) {
char_num = i / 8;
char_bit = 7 - i % 8;
bit = ptrfontdata[char_num] & (1 << char_bit);
if (bit) {
switch (bits_per_pix) {
case 16:
memcpy(ptmp, &pcolor->fg_color, 2);
ptmp += 2;
break;
case 24:
memcpy(ptmp, &pcolor->fg_color, 3);
ptmp += 3;
break;
case 1:
break;
default:
break;
}
} else {
switch (bits_per_pix) {
case 16:
memcpy(ptmp, &pcolor->bg_color, 2);
ptmp += 2;
break;
case 24:
memcpy(ptmp, &pcolor->bg_color, 3);
ptmp += 3;
break;
case 1:
break;
default:
break;
}
}
}
}
void
fontdata2bmp(const uint8_t *ptrfontdata,
uint32_t width,
uint32_t height,
bmp_file_t *ptrbmp,
uint16_t bits_per_pix,
color_setting_t *pcolor)
{
uint32_t rowsize;
uint8_t *ptrbmpdata;
int i;
ptrbmpdata = ptrbmp->pdata;
set_header(ptrbmp, width, height, bits_per_pix);
rowsize = (bits_per_pix * width + 31) / 32 * 4; /* 4字节对齐 */
#if 0
for (i = 0; i < height; i++) /* 倒立的位图 */
#else
for (i = height - 1; i >= 0; i--) /* 正立的位图 */
#endif
{
conv_row(ptrfontdata + (width + 7) / 8 * i,
width,
ptrbmpdata,
bits_per_pix,
pcolor);
ptrbmpdata += rowsize;
}
}
uint32_t
gb2312code_to_fontoffset(uint32_t gb2312code, uint32_t font_height)
{
uint32_t fontoffset;
fontoffset = (gb2312code % 0x100 - 0xA1) * 94
+ (gb2312code / 0x100 - 0xA1);
fontoffset *= (font_height * font_height / 8);
return fontoffset;
}
uint32_t
ascii_to_fontoffset(uint32_t ascii)
{
return (ascii * 16) + 1;
}
bmp_file_t *
create_blank_bmp(bmp_file_t *dst,
uint32_t w, uint32_t h,
uint16_t bits_per_pix,
uint32_t color)
{
set_header(dst, w, h, bits_per_pix);
uint32_t i;
switch (bits_per_pix) {
case 16:
for (i = 0; i < dst->dib_h.image_size; i += 2)
memcpy(dst->pdata + i, &color, 2);
break;
case 24:
for (i = 0; i < dst->dib_h.image_size; i += 3)
memcpy(dst->pdata + i, &color, 3);
break;
default:
break;
}
return dst;
}
/*
* 位图水平合并
*/
bmp_file_t *
bmp_h_combin(const bmp_file_t *src1, const bmp_file_t *src2, bmp_file_t *dst)
{
uint32_t i;
uint32_t rowsize;
uint32_t rowsize_src1;
uint32_t rowsize_src2;
uint32_t row_length_src1;
uint32_t row_length_src2;
uint8_t *ptrbmpdata;
memset(&dst->bmp_h, 0, sizeof(struct bmp_file_header));
memset(&dst->dib_h, 0, sizeof(struct dib_header));
dst->bmp_h.magic[0] = 'B';
dst->bmp_h.magic[1] = 'M';
dst->bmp_h.offset = sizeof(bmp_file_header_t) + sizeof(dib_header_t);
dst->dib_h.dib_header_size = sizeof(dib_header_t);
dst->dib_h.width = src1->dib_h.width + src2->dib_h.width;
dst->dib_h.height = src1->dib_h.height;
dst->dib_h.planes = 1;
dst->dib_h.bits_per_pix = src1->dib_h.bits_per_pix;
dst->dib_h.compression = 0;
rowsize = (dst->dib_h.bits_per_pix * dst->dib_h.width + 31) / 32 * 4;
dst->dib_h.image_size = rowsize * dst->dib_h.height;
dst->dib_h.x_pix_per_meter = 0;
dst->dib_h.y_pix_per_meter = 0;
dst->dib_h.colors_in_colortable = 0;
dst->dib_h.important_color_count = 0;
dst->bmp_h.file_size = dst->bmp_h.offset + dst->dib_h.image_size;
rowsize_src1 = (src1->dib_h.bits_per_pix * src1->dib_h.width +
31) / 32 * 4;
rowsize_src2 = (src2->dib_h.bits_per_pix * src2->dib_h.width +
31) / 32 * 4;
row_length_src1 = src1->dib_h.width * (src1->dib_h.bits_per_pix / 8);
row_length_src2 = src2->dib_h.width * (src1->dib_h.bits_per_pix / 8);
ptrbmpdata = dst->pdata;
for (i = 0; i < dst->dib_h.height; i++) {
memcpy(ptrbmpdata,
src1->pdata + i * rowsize_src1,
row_length_src1);
memcpy(ptrbmpdata + row_length_src1,
src2->pdata + i * rowsize_src2,
row_length_src2);
if (rowsize > row_length_src1 + row_length_src2)
memset(ptrbmpdata + row_length_src1 + row_length_src2,
0,
rowsize - row_length_src1 - row_length_src2);
ptrbmpdata += rowsize;
}
return dst;
}
/*
* 位图垂直合并
*/
bmp_file_t *
bmp_v_combin(const bmp_file_t *src1, const bmp_file_t *src2, bmp_file_t *dst)
{
uint32_t rowsize;
uint32_t rowsize_src1;
uint32_t rowsize_src2;
uint32_t row_length_src1;
uint32_t row_length_src2;
uint8_t *ptrbmpdata;
memset(&dst->bmp_h, 0, sizeof(struct bmp_file_header));
memset(&dst->dib_h, 0, sizeof(struct dib_header));
dst->bmp_h.magic[0] = 'B';
dst->bmp_h.magic[1] = 'M';
dst->bmp_h.offset = sizeof(bmp_file_header_t) + sizeof(dib_header_t);
dst->dib_h.dib_header_size = sizeof(dib_header_t);
dst->dib_h.width = src1->dib_h.width;
dst->dib_h.height = src1->dib_h.height + src2->dib_h.height;
dst->dib_h.planes = 1;
dst->dib_h.bits_per_pix = src1->dib_h.bits_per_pix;
dst->dib_h.compression = 0;
rowsize = (dst->dib_h.bits_per_pix * dst->dib_h.width + 31) / 32 * 4;
dst->dib_h.image_size = rowsize * dst->dib_h.height;
dst->dib_h.x_pix_per_meter = 0;
dst->dib_h.y_pix_per_meter = 0;
dst->dib_h.colors_in_colortable = 0;
dst->dib_h.important_color_count = 0;
dst->bmp_h.file_size = dst->bmp_h.offset + dst->dib_h.image_size;
rowsize_src1 = (src1->dib_h.bits_per_pix * src1->dib_h.width +
31) / 32 * 4;
rowsize_src2 = (src2->dib_h.bits_per_pix * src2->dib_h.width +
31) / 32 * 4;
row_length_src1 = src1->dib_h.width * (src1->dib_h.bits_per_pix / 8);
row_length_src2 = src2->dib_h.width * (src1->dib_h.bits_per_pix / 8);
ptrbmpdata = dst->pdata;
/*
* 按从上到下的顺序合并
* 若需从下到上的顺序, 则:
* memcpy(ptrbmpdata, src1->pdata, src1->dib_h.image_size);
* memcpy(ptrbmpdata + src1->dib_h.image_size,
* src2->pdata, src2->dib_h.image_size);
*/
memcpy(ptrbmpdata, src2->pdata, src2->dib_h.image_size);
memcpy(ptrbmpdata + src2->dib_h.image_size, src1->pdata,
src1->dib_h.image_size);
return dst;
}
bmp_file_t *
bmp_h_combin_2(bmp_file_t *dst, const bmp_file_t *add)
{
bmp_file_t tmp;
if (dst->pdata == NULL) {
memcpy(dst, add, sizeof(bmp_file_t));
dst->pdata = malloc(dst->dib_h.image_size);
memcpy(dst->pdata, add->pdata, add->dib_h.image_size);
} else {
memcpy(&tmp, dst, sizeof(bmp_file_t));
tmp.pdata = malloc(tmp.dib_h.image_size);
memcpy(tmp.pdata, dst->pdata, tmp.dib_h.image_size);
dst->pdata = realloc(dst->pdata,
dst->dib_h.image_size + add->dib_h.image_size);
bmp_h_combin(&tmp, add, dst);
free(tmp.pdata);
}
return dst;
}
/*
* 水平合并支持垂直分辨率不同位图
* 垂直分辨率较小的位图上边将补齐空白
*/
bmp_file_t *
bmp_h_combin_3(bmp_file_t *dst, const bmp_file_t *add, uint32_t blank_color)
{
uint32_t h_diff;
uint32_t rowsize;
bmp_file_t bmp_blank;
bmp_file_t tmp_bmp;
if (dst->pdata == NULL) {
memcpy(dst, add, sizeof(bmp_file_t));
dst->pdata = malloc(dst->dib_h.image_size);
memcpy(dst->pdata, add->pdata, add->dib_h.image_size);
return dst;
}
if (dst->dib_h.height > add->dib_h.height) {
h_diff = dst->dib_h.height - add->dib_h.height;
rowsize = (add->dib_h.bits_per_pix * add->dib_h.width +
31) / 32 * 4;
bmp_blank.pdata = malloc(rowsize * h_diff);
create_blank_bmp(&bmp_blank, add->dib_h.width, h_diff,
dst->dib_h.bits_per_pix, blank_color);
memcpy(&tmp_bmp, &bmp_blank, sizeof(tmp_bmp));
tmp_bmp.pdata = malloc(tmp_bmp.dib_h.image_size);
memcpy(tmp_bmp.pdata, bmp_blank.pdata,
tmp_bmp.dib_h.image_size);
bmp_v_combin_2(&tmp_bmp, add);
bmp_h_combin_2(dst, &tmp_bmp);
free(tmp_bmp.pdata);
free(bmp_blank.pdata);
} else if (dst->dib_h.height < add->dib_h.height) {
h_diff = add->dib_h.height - dst->dib_h.height;
rowsize = (add->dib_h.bits_per_pix * dst->dib_h.width +
31) / 32 * 4;
bmp_blank.pdata = malloc(rowsize * h_diff);
create_blank_bmp(&bmp_blank, dst->dib_h.width, h_diff,
dst->dib_h.bits_per_pix, blank_color);
bmp_v_combin_2(&bmp_blank, dst);
bmp_h_combin_2(&bmp_blank, add);
memcpy(&dst->bmp_h, &bmp_blank.bmp_h,
sizeof(bmp_file_header_t));
memcpy(&dst->dib_h, &bmp_blank.dib_h, sizeof(dib_header_t));
dst->pdata = realloc(dst->pdata, dst->dib_h.image_size);
memcpy(dst->pdata, bmp_blank.pdata, dst->dib_h.image_size);
free(bmp_blank.pdata);
} else
bmp_h_combin_2(dst, add);
return dst;
}
/*
* 合并的位图水平分辨率相同才能调用该函数
*/
bmp_file_t *
bmp_v_combin_2(bmp_file_t *dst, const bmp_file_t *add)
{
bmp_file_t tmp;
if (dst->pdata == NULL) {
memcpy(dst, add, sizeof(bmp_file_t));
dst->pdata = malloc(dst->dib_h.image_size);
memcpy(dst->pdata, add->pdata, add->dib_h.image_size);
} else {
memcpy(&tmp, dst, sizeof(bmp_file_t));
tmp.pdata = malloc(tmp.dib_h.image_size);
memcpy(tmp.pdata, dst->pdata, tmp.dib_h.image_size);
dst->pdata = realloc(dst->pdata,
dst->dib_h.image_size + add->dib_h.image_size);
bmp_v_combin(&tmp, add, dst);
free(tmp.pdata);
}
return dst;
}
/*
* 垂直合并支持水平分辨率不同位图
* 水平分辨率较小的位图左边将补齐空白
*/
bmp_file_t *
bmp_v_combin_3(bmp_file_t *dst, const bmp_file_t *add, uint32_t blank_color)
{
bmp_file_t tmp_bmp;
bmp_file_t blank_bmp;
uint32_t w_diff;
uint32_t rowsize;
if (dst->pdata == NULL) {
memcpy(dst, add, sizeof(bmp_file_t));
dst->pdata = malloc(dst->dib_h.image_size);
memcpy(dst->pdata, add->pdata, add->dib_h.image_size);
return dst;
}
/*
* else
*/
if (dst->dib_h.width > add->dib_h.width) {
w_diff = dst->dib_h.width - add->dib_h.width;
rowsize = (add->dib_h.bits_per_pix * w_diff + 31) / 32 * 4;
blank_bmp.pdata = malloc(rowsize * add->dib_h.height);
create_blank_bmp(&blank_bmp, w_diff, add->dib_h.height,
add->dib_h.bits_per_pix, blank_color);
memcpy(&tmp_bmp, add, sizeof(tmp_bmp));
tmp_bmp.pdata = malloc(tmp_bmp.dib_h.image_size);
memcpy(tmp_bmp.pdata, add->pdata, tmp_bmp.dib_h.image_size);
bmp_h_combin_2(&tmp_bmp, &blank_bmp);
bmp_v_combin_2(dst, &tmp_bmp);
free(tmp_bmp.pdata);
free(blank_bmp.pdata);
} else if (dst->dib_h.width < add->dib_h.width) {
w_diff = add->dib_h.width - dst->dib_h.width;
rowsize = (add->dib_h.bits_per_pix * w_diff + 31) / 32 * 4;
blank_bmp.pdata = malloc(rowsize * dst->dib_h.height);
create_blank_bmp(&blank_bmp, w_diff, dst->dib_h.height,
add->dib_h.bits_per_pix, blank_color);
bmp_h_combin_2(dst, &blank_bmp);
bmp_v_combin_2(dst, add);
free(blank_bmp.pdata);
} else
bmp_v_combin_2(dst, add);
return dst;
}
bmp_file_t *
bmp_h_combin_rl_2(bmp_file_t *dst, const bmp_file_t *add)
{
bmp_file_t tmp;
if (dst->pdata == NULL) {
memcpy(dst, add, sizeof(bmp_file_t));
dst->pdata = malloc(dst->dib_h.image_size);
memcpy(dst->pdata, add->pdata, add->dib_h.image_size);
} else {
memcpy(&tmp, dst, sizeof(bmp_file_t));
tmp.pdata = malloc(tmp.dib_h.image_size);
memcpy(tmp.pdata, dst->pdata, tmp.dib_h.image_size);
dst->pdata = realloc(dst->pdata,
dst->dib_h.image_size + add->dib_h.image_size);
bmp_h_combin(add, &tmp, dst);
free(tmp.pdata);
}
return dst;
}
/*
* 水平合并支持垂直分辨率不同位图
* 垂直分辨率较小的位图上边将补齐空白
*/
bmp_file_t *
bmp_h_combin_rl_3(bmp_file_t *dst, const bmp_file_t *add, uint32_t blank_color)
{
uint32_t h_diff;
uint32_t rowsize;
bmp_file_t bmp_blank;
bmp_file_t tmp_bmp;
if (dst->pdata == NULL) {
memcpy(dst, add, sizeof(bmp_file_t));
dst->pdata = malloc(dst->dib_h.image_size);
memcpy(dst->pdata, add->pdata, add->dib_h.image_size);
return dst;
}
/*
* else
*/
if (dst->dib_h.height > add->dib_h.height) {
h_diff = dst->dib_h.height - add->dib_h.height;
rowsize = (add->dib_h.bits_per_pix * add->dib_h.width +
31) / 32 * 4;
bmp_blank.pdata = malloc(rowsize * h_diff);
create_blank_bmp(&bmp_blank, add->dib_h.width, h_diff,
dst->dib_h.bits_per_pix, blank_color);
memcpy(&tmp_bmp, &bmp_blank, sizeof(tmp_bmp));
tmp_bmp.pdata = malloc(tmp_bmp.dib_h.image_size);
memcpy(tmp_bmp.pdata, bmp_blank.pdata,
tmp_bmp.dib_h.image_size);
bmp_v_combin_2(&tmp_bmp, add);
bmp_h_combin_rl_2(dst, &tmp_bmp);
free(tmp_bmp.pdata);
free(bmp_blank.pdata);
} else if (dst->dib_h.height < add->dib_h.height) {
h_diff = add->dib_h.height - dst->dib_h.height;
rowsize = (add->dib_h.bits_per_pix * dst->dib_h.width +
31) / 32 * 4;
bmp_blank.pdata = malloc(rowsize * h_diff);
create_blank_bmp(&bmp_blank, dst->dib_h.width, h_diff,
dst->dib_h.bits_per_pix, blank_color);
bmp_v_combin_2(&bmp_blank, dst);
bmp_h_combin_rl_2(&bmp_blank, add);
memcpy(&dst->bmp_h, &bmp_blank.bmp_h,
sizeof(bmp_file_header_t));
memcpy(&dst->dib_h, &bmp_blank.dib_h, sizeof(dib_header_t));
dst->pdata = realloc(dst->pdata, dst->dib_h.image_size);
memcpy(dst->pdata, bmp_blank.pdata, dst->dib_h.image_size);
free(bmp_blank.pdata);
} else
bmp_h_combin_rl_2(dst, add);
return dst;
}
/*
* 合并的位图水平分辨率相同才能调用该函数
*/
bmp_file_t *
bmp_v_combin_du_2(bmp_file_t *dst, const bmp_file_t *add)
{
bmp_file_t tmp;
if (dst->pdata == NULL) {
memcpy(dst, add, sizeof(bmp_file_t));
dst->pdata = malloc(dst->dib_h.image_size);
memcpy(dst->pdata, add->pdata, add->dib_h.image_size);
} else {
memcpy(&tmp, dst, sizeof(bmp_file_t));
tmp.pdata = malloc(tmp.dib_h.image_size);
memcpy(tmp.pdata, dst->pdata, tmp.dib_h.image_size);
dst->pdata = realloc(dst->pdata,
dst->dib_h.image_size + add->dib_h.image_size);
bmp_v_combin(add, &tmp, dst);
free(tmp.pdata);
}
return dst;
}
/*
* 垂直合并支持水平分辨率不同位图
* 水平分辨率较小的位图左边将补齐空白
*/
bmp_file_t *
bmp_v_combin_du_3(bmp_file_t *dst, const bmp_file_t *add, uint32_t blank_color)
{
bmp_file_t tmp_bmp;
bmp_file_t blank_bmp;
uint32_t w_diff;
uint32_t rowsize;
if (dst->pdata == NULL) {
memcpy(dst, add, sizeof(bmp_file_t));
dst->pdata = malloc(dst->dib_h.image_size);
memcpy(dst->pdata, add->pdata, add->dib_h.image_size);
return dst;
}
/*
* else
*/
if (dst->dib_h.width > add->dib_h.width) {
w_diff = dst->dib_h.width - add->dib_h.width;
rowsize = (add->dib_h.bits_per_pix * w_diff + 31) / 32 * 4;
blank_bmp.pdata = malloc(rowsize * add->dib_h.height);
create_blank_bmp(&blank_bmp, w_diff, add->dib_h.height,
add->dib_h.bits_per_pix, blank_color);
memcpy(&tmp_bmp, add, sizeof(tmp_bmp));
tmp_bmp.pdata = malloc(tmp_bmp.dib_h.image_size);
memcpy(tmp_bmp.pdata, add->pdata, tmp_bmp.dib_h.image_size);
bmp_h_combin_2(&tmp_bmp, &blank_bmp);
bmp_v_combin_du_2(dst, &tmp_bmp);
free(tmp_bmp.pdata);
free(blank_bmp.pdata);
} else if (dst->dib_h.width < add->dib_h.width) {
w_diff = add->dib_h.width - dst->dib_h.width;
rowsize = (add->dib_h.bits_per_pix * w_diff + 31) / 32 * 4;
blank_bmp.pdata = malloc(rowsize * dst->dib_h.height);
create_blank_bmp(&blank_bmp, w_diff, dst->dib_h.height,
add->dib_h.bits_per_pix, blank_color);
bmp_h_combin_2(dst, &blank_bmp);
bmp_v_combin_du_2(dst, add);
free(blank_bmp.pdata);
} else
bmp_v_combin_du_2(dst, add);
return dst;
}
| mit |
Josiastech/vuforia-gamekit-integration | Gamekit/Dependencies/Source/libRocket/Source/Core/Context.cpp | 2 | 32493 | /*
* This source file is part of libRocket, the HTML/CSS Interface Middleware
*
* For the latest information, see http://www.librocket.com
*
* Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd
*
* 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 <Rocket/Core.h>
#include "EventDispatcher.h"
#include "EventIterators.h"
#include "PluginRegistry.h"
#include "StreamFile.h"
#include <Rocket/Core/StreamMemory.h>
#include <algorithm>
#include <iterator>
namespace Rocket {
namespace Core {
const float DOUBLE_CLICK_TIME = 0.5f;
Context::Context(const String& name) : name(name), mouse_position(0, 0), dimensions(0, 0)
{
instancer = NULL;
// Initialise this to NULL; this will be set in Rocket::Core::CreateContext().
render_interface = NULL;
root = Factory::InstanceElement(NULL, "*", "#root", XMLAttributes());
root->SetId(name);
root->SetOffset(Vector2f(0, 0), NULL);
root->SetProperty(Z_INDEX, "0");
Element* element = Factory::InstanceElement(NULL, "body", "body", XMLAttributes());
cursor_proxy = dynamic_cast< ElementDocument* >(element);
if (cursor_proxy == NULL)
{
if (element != NULL)
element->RemoveReference();
}
document_focus_history.push_back(root);
focus = root;
show_cursor = true;
drag_started = false;
drag_verbose = false;
drag_clone = NULL;
last_click_element = NULL;
last_click_time = 0;
}
Context::~Context()
{
PluginRegistry::NotifyContextDestroy(this);
UnloadAllDocuments();
UnloadAllMouseCursors();
ReleaseUnloadedDocuments();
if (cursor_proxy != NULL)
cursor_proxy->RemoveReference();
if (root != NULL)
root->RemoveReference();
if (instancer)
instancer->RemoveReference();
if (render_interface)
render_interface->RemoveReference();
}
// Returns the name of the context.
const String& Context::GetName() const
{
return name;
}
// Changes the dimensions of the screen.
void Context::SetDimensions(const Vector2i& _dimensions)
{
if (dimensions != _dimensions)
{
dimensions = _dimensions;
root->SetBox(Box(Vector2f((float) dimensions.x, (float) dimensions.y)));
root->DirtyLayout();
for (int i = 0; i < root->GetNumChildren(); ++i)
{
ElementDocument* document = root->GetChild(i)->GetOwnerDocument();
if (document != NULL)
{
document->DirtyLayout();
document->UpdatePosition();
}
}
}
}
// Returns the dimensions of the screen.
const Vector2i& Context::GetDimensions() const
{
return dimensions;
}
// Updates all elements in the element tree.
bool Context::Update()
{
root->Update();
// Release any documents that were unloaded during the update.
ReleaseUnloadedDocuments();
return true;
}
// Renders all visible elements in the element tree.
bool Context::Render()
{
RenderInterface* render_interface = GetRenderInterface();
if (render_interface == NULL)
return false;
// Update the layout for all documents in the root. This is done now as events during the
// update may have caused elements to require an update.
for (int i = 0; i < root->GetNumChildren(); ++i)
root->GetChild(i)->UpdateLayout();
render_interface->context = this;
ElementUtilities::PushClipCache(render_interface);
root->Render();
ElementUtilities::SetClippingRegion(NULL, this);
// Render the cursor proxy so any elements attached the cursor will be rendered below the cursor.
if (cursor_proxy != NULL)
{
cursor_proxy->Update();
cursor_proxy->SetOffset(Vector2f((float) Math::Clamp(mouse_position.x, 0, dimensions.x),
(float) Math::Clamp(mouse_position.y, 0, dimensions.y)),
NULL);
cursor_proxy->Render();
}
// Render the cursor document if we have one and we're showing the cursor.
if (active_cursor &&
show_cursor)
{
active_cursor->Update();
active_cursor->SetOffset(Vector2f((float) Math::Clamp(mouse_position.x, 0, dimensions.x),
(float) Math::Clamp(mouse_position.y, 0, dimensions.y)),
NULL);
active_cursor->Render();
}
render_interface->context = NULL;
return true;
}
// Creates a new, empty document and places it into this context.
ElementDocument* Context::CreateDocument(const String& tag)
{
Element* element = Factory::InstanceElement(NULL, tag, "body", XMLAttributes());
if (element == NULL)
{
Log::Message(Log::LT_ERROR, "Failed to instance document on tag '%s', instancer returned NULL.", tag.CString());
return NULL;
}
ElementDocument* document = dynamic_cast< ElementDocument* >(element);
if (document == NULL)
{
Log::Message(Log::LT_ERROR, "Failed to instance document on tag '%s', Found type '%s', was expecting derivative of ElementDocument.", tag.CString(), typeid(element).name());
element->RemoveReference();
return NULL;
}
document->context = this;
root->AppendChild(document);
PluginRegistry::NotifyDocumentLoad(document);
return document;
}
// Load a document into the context.
ElementDocument* Context::LoadDocument(const String& document_path)
{
// Open the stream based on the file path
StreamFile* stream = new StreamFile();
if (!stream->Open(document_path))
{
stream->RemoveReference();
return NULL;
}
// Load the document from the stream
ElementDocument* document = LoadDocument(stream);
stream->RemoveReference();
return document;
}
// Load a document into the context.
ElementDocument* Context::LoadDocument(Stream* stream)
{
PluginRegistry::NotifyDocumentOpen(this, stream->GetSourceURL().GetURL());
// Load the document from the stream.
ElementDocument* document = Factory::InstanceDocumentStream(this, stream);
if (!document)
return NULL;
root->AppendChild(document);
// Bind the events, run the layout and fire the 'onload' event.
ElementUtilities::BindEventAttributes(document);
document->UpdateLayout();
// Dispatch the load notifications.
PluginRegistry::NotifyDocumentLoad(document);
document->DispatchEvent(LOAD, Dictionary(), false);
return document;
}
// Load a document into the context.
ElementDocument* Context::LoadDocumentFromMemory(const String& string)
{
// Open the stream based on the string contents.
StreamMemory* stream = new StreamMemory((byte*)string.CString(), string.Length());
stream->SetSourceURL("[document from memory]");
// Load the document from the stream.
ElementDocument* document = LoadDocument(stream);
stream->RemoveReference();
return document;
}
// Unload the given document
void Context::UnloadDocument(ElementDocument* _document)
{
// Has this document already been unloaded?
for (size_t i = 0; i < unloaded_documents.size(); ++i)
{
if (unloaded_documents[i] == _document)
return;
}
// Add a reference, to ensure the document isn't released
// while we're closing it.
unloaded_documents.push_back(_document);
ElementDocument* document = _document;
if (document->GetParentNode() == root)
{
// Dispatch the unload notifications.
document->DispatchEvent(UNLOAD, Dictionary(), false);
PluginRegistry::NotifyDocumentUnload(document);
// Remove the document from the context.
root->RemoveChild(document);
}
// Remove the item from the focus history.
ElementList::iterator itr = std::find(document_focus_history.begin(), document_focus_history.end(), document);
if (itr != document_focus_history.end())
document_focus_history.erase(itr);
// Focus to the previous document if the old document is the current focus.
if (focus && focus->GetOwnerDocument() == document)
{
focus = NULL;
document_focus_history.back()->GetFocusLeafNode()->Focus();
}
// Clear the active element if the old document is the active element.
if (active && active->GetOwnerDocument() == document)
{
active = NULL;
}
// Rebuild the hover state.
UpdateHoverChain(Dictionary(), Dictionary(), mouse_position);
}
// Unload all the currently loaded documents
void Context::UnloadAllDocuments()
{
// Unload all children.
while (root->GetNumChildren(true) > 0)
UnloadDocument(root->GetChild(0)->GetOwnerDocument());
// Force cleanup of child elements now, reference counts must hit zero so that python (if it's in use) cleans up
// before we exit this method.
root->active_children.clear();
root->ReleaseElements(root->deleted_children);
}
// Adds a previously-loaded cursor document as a mouse cursor within this context.
void Context::AddMouseCursor(ElementDocument* cursor_document)
{
cursor_document->AddReference();
CursorMap::iterator i = cursors.find(cursor_document->GetTitle());
if (i != cursors.end())
{
if (active_cursor == (*i).second)
active_cursor = cursor_document;
if (default_cursor == (*i).second)
default_cursor = cursor_document;
(*i).second->RemoveReference();
}
cursors[cursor_document->GetTitle()] = cursor_document;
if (!default_cursor)
{
default_cursor = cursor_document;
active_cursor = cursor_document;
}
}
// Loads a document as a mouse cursor.
ElementDocument* Context::LoadMouseCursor(const String& document_path)
{
StreamFile* stream = new StreamFile();
if (!stream->Open(document_path))
return NULL;
// Load the document from the stream.
ElementDocument* document = Factory::InstanceDocumentStream(this, stream);
if (document == NULL)
return NULL;
AddMouseCursor(document);
// Bind the events, run the layout and fire the 'onload' event.
ElementUtilities::BindEventAttributes(document);
document->UpdateLayout();
document->DispatchEvent(LOAD, Dictionary(), false);
return document;
}
// Unload the given cursor.
void Context::UnloadMouseCursor(const String& cursor_name)
{
CursorMap::iterator i = cursors.find(cursor_name);
if (i != cursors.end())
{
if (default_cursor == (*i).second)
default_cursor = NULL;
if (active_cursor == (*i).second)
active_cursor = default_cursor;
(*i).second->RemoveReference();
cursors.erase(i);
}
}
// Unloads all currently loaded cursors.
void Context::UnloadAllMouseCursors()
{
while (!cursors.empty())
UnloadMouseCursor((*cursors.begin()).first.CString());
}
// Sets a cursor as the active cursor.
bool Context::SetMouseCursor(const String& cursor_name)
{
CursorMap::iterator i = cursors.find(cursor_name);
if (i == cursors.end())
{
active_cursor = default_cursor;
Log::Message(Log::LT_WARNING, "Failed to find cursor '%s' in context '%s', reverting to default cursor.", cursor_name.CString(), name.CString());
return false;
}
active_cursor = (*i).second;
return true;
}
// Shows or hides the cursor.
void Context::ShowMouseCursor(bool show)
{
show_cursor = show;
}
// Returns the first document found in the root with the given id.
ElementDocument* Context::GetDocument(const String& id)
{
const String lower_id = id.ToLower();
for (int i = 0; i < root->GetNumChildren(); i++)
{
ElementDocument* document = root->GetChild(i)->GetOwnerDocument();
if (document == NULL)
continue;
if (document->GetId() == lower_id)
return document;
}
return NULL;
}
// Returns a document in the context by index.
ElementDocument* Context::GetDocument(int index)
{
Element* element = root->GetChild(index);
if (element == NULL)
return NULL;
return element->GetOwnerDocument();
}
// Returns the number of documents in the context.
int Context::GetNumDocuments() const
{
return root->GetNumChildren();
}
// Returns the hover element.
Element* Context::GetHoverElement()
{
return *hover;
}
// Returns the focus element.
Element* Context::GetFocusElement()
{
return *focus;
}
// Returns the root element.
Element* Context::GetRootElement()
{
return root;
}
// Brings the document to the front of the document stack.
void Context::PullDocumentToFront(ElementDocument* document)
{
if (document != root->GetLastChild())
{
// Calling RemoveChild() / AppendChild() would be cleaner, but that dirties the document's layout
// unnecessarily, so we'll go under the hood here.
for (int i = 0; i < root->GetNumChildren(); ++i)
{
if (root->GetChild(i) == document)
{
root->children.erase(root->children.begin() + i);
root->children.insert(root->children.begin() + root->GetNumChildren(), document);
root->DirtyStackingContext();
}
}
}
}
// Sends the document to the back of the document stack.
void Context::PushDocumentToBack(ElementDocument* document)
{
if (document != root->GetFirstChild())
{
// See PullDocumentToFront().
for (int i = 0; i < root->GetNumChildren(); ++i)
{
if (root->GetChild(i) == document)
{
root->children.erase(root->children.begin() + i);
root->children.insert(root->children.begin(), document);
root->DirtyStackingContext();
}
}
}
}
// Adds an event listener to the root element.
void Context::AddEventListener(const String& event, EventListener* listener, bool in_capture_phase)
{
root->AddEventListener(event, listener, in_capture_phase);
}
// Removes an event listener from the root element.
void Context::RemoveEventListener(const String& event, EventListener* listener, bool in_capture_phase)
{
root->RemoveEventListener(event, listener, in_capture_phase);
}
// Sends a key down event into Rocket.
bool Context::ProcessKeyDown(Input::KeyIdentifier key_identifier, int key_modifier_state)
{
// Generate the parameters for the key event.
Dictionary parameters;
GenerateKeyEventParameters(parameters, key_identifier);
GenerateKeyModifierEventParameters(parameters, key_modifier_state);
if (focus)
return focus->DispatchEvent(KEYDOWN, parameters, true);
else
return root->DispatchEvent(KEYDOWN, parameters, true);
}
// Sends a key up event into Rocket.
bool Context::ProcessKeyUp(Input::KeyIdentifier key_identifier, int key_modifier_state)
{
// Generate the parameters for the key event.
Dictionary parameters;
GenerateKeyEventParameters(parameters, key_identifier);
GenerateKeyModifierEventParameters(parameters, key_modifier_state);
if (focus)
return focus->DispatchEvent(KEYUP, parameters, true);
else
return root->DispatchEvent(KEYUP, parameters, true);
}
// Sends a single character of text as text input into Rocket.
bool Context::ProcessTextInput(word character)
{
// Generate the parameters for the key event.
Dictionary parameters;
parameters.Set("data", character);
if (focus)
return focus->DispatchEvent(TEXTINPUT, parameters, true);
else
return root->DispatchEvent(TEXTINPUT, parameters, true);
}
// Sends a string of text as text input into Rocket.
bool Context::ProcessTextInput(const String& string)
{
bool consumed = true;
for (size_t i = 0; i < string.Length(); ++i)
{
// Generate the parameters for the key event.
Dictionary parameters;
parameters.Set("data", string[i]);
if (focus)
consumed = focus->DispatchEvent(TEXTINPUT, parameters, true) && consumed;
else
consumed = root->DispatchEvent(TEXTINPUT, parameters, true) && consumed;
}
return consumed;
}
// Sends a mouse movement event into Rocket.
void Context::ProcessMouseMove(int x, int y, int key_modifier_state)
{
// Check whether the mouse moved since the last event came through.
Vector2i old_mouse_position = mouse_position;
bool mouse_moved = (x != mouse_position.x) || (y != mouse_position.y);
if (mouse_moved)
{
mouse_position.x = x;
mouse_position.y = y;
}
// Generate the parameters for the mouse events (there could be a few!).
Dictionary parameters;
GenerateMouseEventParameters(parameters, -1);
GenerateKeyModifierEventParameters(parameters, key_modifier_state);
Dictionary drag_parameters;
GenerateMouseEventParameters(drag_parameters);
GenerateDragEventParameters(drag_parameters);
GenerateKeyModifierEventParameters(drag_parameters, key_modifier_state);
// Update the current hover chain. This will send all necessary 'onmouseout', 'onmouseover', 'ondragout' and
// 'ondragover' messages.
UpdateHoverChain(parameters, drag_parameters, old_mouse_position);
// Dispatch any 'onmousemove' events.
if (mouse_moved)
{
if (hover)
{
hover->DispatchEvent(MOUSEMOVE, parameters, true);
if (drag_hover &&
drag_verbose)
drag_hover->DispatchEvent(DRAGMOVE, drag_parameters, true);
}
}
}
// Sends a mouse-button down event into Rocket.
void Context::ProcessMouseButtonDown(int button_index, int key_modifier_state)
{
Dictionary parameters;
GenerateMouseEventParameters(parameters, button_index);
GenerateKeyModifierEventParameters(parameters, key_modifier_state);
if (button_index == 0)
{
// Set the currently hovered element to focus if it isn't already the focus.
if (hover)
{
if (hover != focus)
{
if (!hover->Focus())
return;
}
}
// Save the just-pressed-on element as the pressed element.
active = hover;
// Call 'onmousedown' on every item in the hover chain, and copy the hover chain to the active chain.
if (hover)
hover->DispatchEvent(MOUSEDOWN, parameters, true);
// Check for a double-click on an element; if one has occured, we send the 'dblclick' event to the hover
// element. If not, we'll start a timer to catch the next one.
float click_time = GetSystemInterface()->GetElapsedTime();
if (active == last_click_element &&
click_time - last_click_time < DOUBLE_CLICK_TIME)
{
if (hover)
hover->DispatchEvent(DBLCLICK, parameters, true);
last_click_element = NULL;
last_click_time = 0;
}
else
{
last_click_element = *active;
last_click_time = click_time;
}
for (ElementSet::iterator itr = hover_chain.begin(); itr != hover_chain.end(); ++itr)
active_chain.push_back((*itr));
// Traverse down the hierarchy of the newly focussed element (if any), and see if we can begin dragging it.
drag_started = false;
drag = hover;
while (drag)
{
int drag_style = drag->GetProperty(DRAG)->value.Get< int >();
switch (drag_style)
{
case DRAG_NONE: drag = drag->GetParentNode(); continue;
case DRAG_BLOCK: drag = NULL; continue;
default: drag_verbose = (drag_style == DRAG_DRAG_DROP || drag_style == DRAG_CLONE);
}
break;
}
}
else
{
// Not the primary mouse button, so we're not doing any special processing.
if (hover)
hover->DispatchEvent(MOUSEDOWN, parameters, true);
}
}
// Sends a mouse-button up event into Rocket.
void Context::ProcessMouseButtonUp(int button_index, int key_modifier_state)
{
Dictionary parameters;
GenerateMouseEventParameters(parameters, button_index);
GenerateKeyModifierEventParameters(parameters, key_modifier_state);
// Process primary click.
if (button_index == 0)
{
// The elements in the new hover chain have the 'onmouseup' event called on them.
if (hover)
hover->DispatchEvent(MOUSEUP, parameters, true);
// If the active element (the one that was being hovered over when the mouse button was pressed) is still being
// hovered over, we click it.
if (active == hover && active)
hover->DispatchEvent(CLICK, parameters, true);
// Unset the 'active' pseudo-class on all the elements in the active chain; because they may not necessarily
// have had 'onmouseup' called on them, we can't guarantee this has happened already.
std::for_each(active_chain.begin(), active_chain.end(), PseudoClassFunctor("active", false));
active_chain.clear();
if (drag)
{
if (drag_started)
{
Dictionary drag_parameters;
GenerateMouseEventParameters(drag_parameters);
GenerateDragEventParameters(drag_parameters);
GenerateKeyModifierEventParameters(drag_parameters, key_modifier_state);
if (drag_hover)
{
if (drag_verbose)
{
drag_hover->DispatchEvent(DRAGDROP, drag_parameters, true);
drag_hover->DispatchEvent(DRAGOUT, drag_parameters, true);
}
}
drag->DispatchEvent(DRAGEND, drag_parameters, true);
ReleaseDragClone();
}
drag = NULL;
drag_hover = NULL;
drag_hover_chain.clear();
}
}
else
{
// Not the left mouse button, so we're not doing any special processing.
if (hover)
hover->DispatchEvent(MOUSEUP, parameters, true);
}
}
// Sends a mouse-wheel movement event into Rocket.
bool Context::ProcessMouseWheel(int wheel_delta, int key_modifier_state)
{
if (hover)
{
Dictionary scroll_parameters;
GenerateKeyModifierEventParameters(scroll_parameters, key_modifier_state);
scroll_parameters.Set("wheel_delta", wheel_delta);
return hover->DispatchEvent(MOUSESCROLL, scroll_parameters, true);
}
return true;
}
// Gets the context's render interface.
RenderInterface* Context::GetRenderInterface() const
{
return render_interface;
}
// Sets the instancer to use for releasing this object.
void Context::SetInstancer(ContextInstancer* _instancer)
{
ROCKET_ASSERT(instancer == NULL);
instancer = _instancer;
instancer->AddReference();
}
// Internal callback for when an element is removed from the hierarchy.
void Context::OnElementRemove(Element* element)
{
ElementSet::iterator i = hover_chain.find(element);
if (i == hover_chain.end())
return;
ElementSet old_hover_chain = hover_chain;
hover_chain.erase(i);
Element* hover_element = element;
while (hover_element != NULL)
{
Element* next_hover_element = NULL;
// Look for a child on this element's children that is also hovered.
for (int j = 0; j < hover_element->GetNumChildren(true); ++j)
{
// Is this child also in the hover chain?
Element* hover_child_element = hover_element->GetChild(j);
ElementSet::iterator k = hover_chain.find(hover_child_element);
if (k != hover_chain.end())
{
next_hover_element = hover_child_element;
hover_chain.erase(k);
break;
}
}
hover_element = next_hover_element;
}
Dictionary parameters;
GenerateMouseEventParameters(parameters, -1);
SendEvents(old_hover_chain, hover_chain, MOUSEOUT, parameters, true);
}
// Internal callback for when a new element gains focus
bool Context::OnFocusChange(Element* new_focus)
{
ElementSet old_chain;
ElementSet new_chain;
Element* old_focus = *(focus);
ElementDocument* old_document = old_focus ? old_focus->GetOwnerDocument() : NULL;
ElementDocument* new_document = new_focus->GetOwnerDocument();
// If the current focus is modal and the new focus is not modal, deny the request
if (old_document && old_document->IsModal() && (!new_document || !new_document->GetOwnerDocument()->IsModal()))
return false;
// Build the old chains
Element* element = old_focus;
while (element)
{
old_chain.insert(element);
element = element->GetParentNode();
}
// Build the new chain
element = new_focus;
while (element)
{
new_chain.insert(element);
element = element->GetParentNode();
}
Dictionary parameters;
// Send out blur/focus events.
SendEvents(old_chain, new_chain, BLUR, parameters, false);
SendEvents(new_chain, old_chain, FOCUS, parameters, false);
focus = new_focus;
// Raise the element's document to the front, if desired.
ElementDocument* document = focus->GetOwnerDocument();
if (document != NULL)
{
const Property* z_index_property = document->GetProperty(Z_INDEX);
if (z_index_property->unit == Property::KEYWORD &&
z_index_property->value.Get< int >() == Z_INDEX_AUTO)
document->PullToFront();
}
// Update the focus history
if (old_document != new_document)
{
// If documents have changed, add the new document to the end of the history
ElementList::iterator itr = std::find(document_focus_history.begin(), document_focus_history.end(), new_document);
if (itr != document_focus_history.end())
document_focus_history.erase(itr);
if (new_document != NULL)
document_focus_history.push_back(new_document);
}
return true;
}
// Generates an event for faking clicks on an element.
void Context::GenerateClickEvent(Element* element)
{
Dictionary parameters;
GenerateMouseEventParameters(parameters, 0);
element->DispatchEvent(CLICK, parameters, true);
}
// Updates the current hover elements, sending required events.
void Context::UpdateHoverChain(const Dictionary& parameters, const Dictionary& drag_parameters, const Vector2i& old_mouse_position)
{
Vector2f position((float) mouse_position.x, (float) mouse_position.y);
// Send out drag events.
if (drag)
{
if (mouse_position != old_mouse_position)
{
if (!drag_started)
{
Dictionary drag_start_parameters = drag_parameters;
drag_start_parameters.Set("mouse_x", old_mouse_position.x);
drag_start_parameters.Set("mouse_y", old_mouse_position.y);
drag->DispatchEvent(DRAGSTART, drag_start_parameters);
drag_started = true;
if (drag->GetProperty< int >(DRAG) == DRAG_CLONE)
{
// Clone the element and attach it to the mouse cursor.
CreateDragClone(*drag);
}
}
drag->DispatchEvent(DRAG, drag_parameters);
}
}
hover = GetElementAtPoint(position);
if (!hover ||
hover->GetProperty(CURSOR)->unit == Property::KEYWORD)
active_cursor = default_cursor;
else
SetMouseCursor(hover->GetProperty< String >(CURSOR));
// Build the new hover chain.
ElementSet new_hover_chain;
Element* element = *hover;
while (element != NULL)
{
new_hover_chain.insert(element);
element = element->GetParentNode();
}
// Send mouseout / mouseover events.
SendEvents(hover_chain, new_hover_chain, MOUSEOUT, parameters, true);
SendEvents(new_hover_chain, hover_chain, MOUSEOVER, parameters, true);
// Send out drag events.
if (drag)
{
drag_hover = GetElementAtPoint(position, *drag);
ElementSet new_drag_hover_chain;
element = *drag_hover;
while (element != NULL)
{
new_drag_hover_chain.insert(element);
element = element->GetParentNode();
}
/* if (mouse_moved && !drag_started)
{
drag->DispatchEvent(DRAGSTART, drag_parameters);
drag_started = true;
if (drag->GetProperty< int >(DRAG) == DRAG_CLONE)
{
// Clone the element and attach it to the mouse cursor.
CreateDragClone(*drag);
}
}*/
if (drag_started &&
drag_verbose)
{
// Send out ondragover and ondragout events as appropriate.
SendEvents(drag_hover_chain, new_drag_hover_chain, DRAGOUT, drag_parameters, true);
SendEvents(new_drag_hover_chain, drag_hover_chain, DRAGOVER, drag_parameters, true);
}
drag_hover_chain.swap(new_drag_hover_chain);
}
// Swap the new chain in.
hover_chain.swap(new_hover_chain);
}
// Returns the youngest descendent of the given element which is under the given point in screen coodinates.
Element* Context::GetElementAtPoint(const Vector2f& point, const Element* ignore_element, Element* element)
{
// Update the layout on all documents prior to this call.
for (int i = 0; i < GetNumDocuments(); ++i)
GetDocument(i)->UpdateLayout();
if (element == NULL)
{
if (ignore_element == root)
return NULL;
element = root;
}
// Check if any documents have modal focus; if so, only check down than document.
if (element == root)
{
if (focus)
{
ElementDocument* focus_document = focus->GetOwnerDocument();
if (focus_document != NULL &&
focus_document->IsModal())
{
element = focus_document;
}
}
}
// Check any elements within our stacking context. We want to return the lowest-down element
// that is under the cursor.
if (element->local_stacking_context)
{
if (element->stacking_context_dirty)
element->BuildLocalStackingContext();
for (int i = (int) element->stacking_context.size() - 1; i >= 0; --i)
{
if (ignore_element != NULL)
{
Element* element_hierarchy = element->stacking_context[i];
while (element_hierarchy != NULL)
{
if (element_hierarchy == ignore_element)
break;
element_hierarchy = element_hierarchy->GetParentNode();
}
if (element_hierarchy != NULL)
continue;
}
Element* child_element = GetElementAtPoint(point, ignore_element, element->stacking_context[i]);
if (child_element != NULL)
return child_element;
}
}
// Check if the point is actually within this element.
bool within_element = element->IsPointWithinElement(point);
if (within_element)
{
Vector2i clip_origin, clip_dimensions;
if (ElementUtilities::GetClippingRegion(clip_origin, clip_dimensions, element))
{
within_element = point.x >= clip_origin.x &&
point.y >= clip_origin.y &&
point.x < (clip_origin.x + clip_dimensions.x) &&
point.y < (clip_origin.y + clip_dimensions.y);
}
}
if (within_element)
return element;
return NULL;
}
// Creates the drag clone from the given element.
void Context::CreateDragClone(Element* element)
{
if (cursor_proxy == NULL)
{
Log::Message(Log::LT_ERROR, "Unable to create drag clone, no cursor proxy document.");
return;
}
ReleaseDragClone();
// Instance the drag clone.
drag_clone = element->Clone();
if (drag_clone == NULL)
{
Log::Message(Log::LT_ERROR, "Unable to duplicate drag clone.");
return;
}
// Append the clone to the cursor proxy element.
cursor_proxy->AppendChild(drag_clone);
drag_clone->RemoveReference();
// Set the style sheet on the cursor proxy.
cursor_proxy->SetStyleSheet(element->GetStyleSheet());
// Set all the required properties and pseudo-classes on the clone.
drag_clone->SetPseudoClass("drag", true);
drag_clone->SetProperty("position", "absolute");
drag_clone->SetProperty("left", Property(element->GetAbsoluteLeft() - element->GetBox().GetEdge(Box::MARGIN, Box::LEFT) - mouse_position.x, Property::PX));
drag_clone->SetProperty("top", Property(element->GetAbsoluteTop() - element->GetBox().GetEdge(Box::MARGIN, Box::TOP) - mouse_position.y, Property::PX));
}
// Releases the drag clone, if one exists.
void Context::ReleaseDragClone()
{
if (drag_clone != NULL)
{
cursor_proxy->RemoveChild(drag_clone);
drag_clone = NULL;
}
}
// Builds the parameters for a generic key event.
void Context::GenerateKeyEventParameters(Dictionary& parameters, Input::KeyIdentifier key_identifier)
{
parameters.Set("key_identifier", (int) key_identifier);
}
// Builds the parameters for a generic mouse event.
void Context::GenerateMouseEventParameters(Dictionary& parameters, int button_index)
{
parameters.Set("mouse_x", mouse_position.x);
parameters.Set("mouse_y", mouse_position.y);
if (button_index >= 0)
parameters.Set("button", button_index);
}
// Builds the parameters for the key modifier state.
void Context::GenerateKeyModifierEventParameters(Dictionary& parameters, int key_modifier_state)
{
static String property_names[] = {
"ctrl_key",
"shift_key",
"alt_key",
"meta_key",
"caps_lock_key",
"num_lock_key",
"scroll_lock_key"
};
for (int i = 0; i < 7; i++)
parameters.Set(property_names[i], (int) ((key_modifier_state & (1 << i)) > 0));
}
// Builds the parameters for a drag event.
void Context::GenerateDragEventParameters(Dictionary& parameters)
{
parameters.Set("drag_element", (void*) *drag);
}
// Releases all unloaded documents pending destruction.
void Context::ReleaseUnloadedDocuments()
{
if (!unloaded_documents.empty())
{
ElementList documents = unloaded_documents;
unloaded_documents.clear();
// Clear the deleted list.
for (size_t i = 0; i < documents.size(); ++i)
documents[i]->GetEventDispatcher()->DetachAllEvents();
documents.clear();
}
}
// Sends the specified event to all elements in new_items that don't appear in old_items.
void Context::SendEvents(const ElementSet& old_items, const ElementSet& new_items, const String& event, const Dictionary& parameters, bool interruptible)
{
ElementList elements;
std::set_difference(old_items.begin(), old_items.end(), new_items.begin(), new_items.end(), std::back_inserter(elements));
std::for_each(elements.begin(), elements.end(), RKTEventFunctor(event, parameters, interruptible));
}
void Context::OnReferenceDeactivate()
{
if (instancer != NULL)
{
instancer->ReleaseContext(this);
}
}
}
}
| mit |
starwels/starwels | src/merkleblock.cpp | 2 | 6421 | // Copyright (c) 2009-2019 Satoshi Nakamoto
// Copyright (c) 2009-2019 The Starwels developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <merkleblock.h>
#include <hash.h>
#include <consensus/consensus.h>
#include <utilstrencodings.h>
CMerkleBlock::CMerkleBlock(const CBlock& block, CBloomFilter* filter, const std::set<uint256>* txids)
{
header = block.GetBlockHeader();
std::vector<bool> vMatch;
std::vector<uint256> vHashes;
vMatch.reserve(block.vtx.size());
vHashes.reserve(block.vtx.size());
for (unsigned int i = 0; i < block.vtx.size(); i++)
{
const uint256& hash = block.vtx[i]->GetHash();
if (txids && txids->count(hash)) {
vMatch.push_back(true);
} else if (filter && filter->IsRelevantAndUpdate(*block.vtx[i])) {
vMatch.push_back(true);
vMatchedTxn.emplace_back(i, hash);
} else {
vMatch.push_back(false);
}
vHashes.push_back(hash);
}
txn = CPartialMerkleTree(vHashes, vMatch);
}
uint256 CPartialMerkleTree::CalcHash(int height, unsigned int pos, const std::vector<uint256> &vTxid) {
//we can never have zero txs in a merkle block, we always need the coinbase tx
//if we do not have this assert, we can hit a memory access violation when indexing into vTxid
assert(vTxid.size() != 0);
if (height == 0) {
// hash at height 0 is the txids themself
return vTxid[pos];
} else {
// calculate left hash
uint256 left = CalcHash(height-1, pos*2, vTxid), right;
// calculate right hash if not beyond the end of the array - copy left hash otherwise
if (pos*2+1 < CalcTreeWidth(height-1))
right = CalcHash(height-1, pos*2+1, vTxid);
else
right = left;
// combine subhashes
return Hash(BEGIN(left), END(left), BEGIN(right), END(right));
}
}
void CPartialMerkleTree::TraverseAndBuild(int height, unsigned int pos, const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch) {
// determine whether this node is the parent of at least one matched txid
bool fParentOfMatch = false;
for (unsigned int p = pos << height; p < (pos+1) << height && p < nTransactions; p++)
fParentOfMatch |= vMatch[p];
// store as flag bit
vBits.push_back(fParentOfMatch);
if (height==0 || !fParentOfMatch) {
// if at height 0, or nothing interesting below, store hash and stop
vHash.push_back(CalcHash(height, pos, vTxid));
} else {
// otherwise, don't store any hash, but descend into the subtrees
TraverseAndBuild(height-1, pos*2, vTxid, vMatch);
if (pos*2+1 < CalcTreeWidth(height-1))
TraverseAndBuild(height-1, pos*2+1, vTxid, vMatch);
}
}
uint256 CPartialMerkleTree::TraverseAndExtract(int height, unsigned int pos, unsigned int &nBitsUsed, unsigned int &nHashUsed, std::vector<uint256> &vMatch, std::vector<unsigned int> &vnIndex) {
if (nBitsUsed >= vBits.size()) {
// overflowed the bits array - failure
fBad = true;
return uint256();
}
bool fParentOfMatch = vBits[nBitsUsed++];
if (height==0 || !fParentOfMatch) {
// if at height 0, or nothing interesting below, use stored hash and do not descend
if (nHashUsed >= vHash.size()) {
// overflowed the hash array - failure
fBad = true;
return uint256();
}
const uint256 &hash = vHash[nHashUsed++];
if (height==0 && fParentOfMatch) { // in case of height 0, we have a matched txid
vMatch.push_back(hash);
vnIndex.push_back(pos);
}
return hash;
} else {
// otherwise, descend into the subtrees to extract matched txids and hashes
uint256 left = TraverseAndExtract(height-1, pos*2, nBitsUsed, nHashUsed, vMatch, vnIndex), right;
if (pos*2+1 < CalcTreeWidth(height-1)) {
right = TraverseAndExtract(height-1, pos*2+1, nBitsUsed, nHashUsed, vMatch, vnIndex);
if (right == left) {
// The left and right branches should never be identical, as the transaction
// hashes covered by them must each be unique.
fBad = true;
}
} else {
right = left;
}
// and combine them before returning
return Hash(BEGIN(left), END(left), BEGIN(right), END(right));
}
}
CPartialMerkleTree::CPartialMerkleTree(const std::vector<uint256> &vTxid, const std::vector<bool> &vMatch) : nTransactions(vTxid.size()), fBad(false) {
// reset state
vBits.clear();
vHash.clear();
// calculate height of tree
int nHeight = 0;
while (CalcTreeWidth(nHeight) > 1)
nHeight++;
// traverse the partial tree
TraverseAndBuild(nHeight, 0, vTxid, vMatch);
}
CPartialMerkleTree::CPartialMerkleTree() : nTransactions(0), fBad(true) {}
uint256 CPartialMerkleTree::ExtractMatches(std::vector<uint256> &vMatch, std::vector<unsigned int> &vnIndex) {
vMatch.clear();
// An empty set will not work
if (nTransactions == 0)
return uint256();
// check for excessively high numbers of transactions
if (nTransactions > MAX_BLOCK_WEIGHT / MIN_TRANSACTION_WEIGHT)
return uint256();
// there can never be more hashes provided than one for every txid
if (vHash.size() > nTransactions)
return uint256();
// there must be at least one bit per node in the partial tree, and at least one node per hash
if (vBits.size() < vHash.size())
return uint256();
// calculate height of tree
int nHeight = 0;
while (CalcTreeWidth(nHeight) > 1)
nHeight++;
// traverse the partial tree
unsigned int nBitsUsed = 0, nHashUsed = 0;
uint256 hashMerkleRoot = TraverseAndExtract(nHeight, 0, nBitsUsed, nHashUsed, vMatch, vnIndex);
// verify that no problems occurred during the tree traversal
if (fBad)
return uint256();
// verify that all bits were consumed (except for the padding caused by serializing it as a byte sequence)
if ((nBitsUsed+7)/8 != (vBits.size()+7)/8)
return uint256();
// verify that all hashes were consumed
if (nHashUsed != vHash.size())
return uint256();
return hashMerkleRoot;
}
| mit |
mattparizeau/Marble-Blast-Clone | Engine/source/ts/loader/tsShapeLoader.cpp | 2 | 43515 | //-----------------------------------------------------------------------------
// Copyright (c) 2012 GarageGames, LLC
//
// 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 "platform/platform.h"
#include "ts/loader/tsShapeLoader.h"
#include "core/volume.h"
#include "materials/materialList.h"
#include "materials/matInstance.h"
#include "materials/materialManager.h"
#include "ts/tsShapeInstance.h"
#include "ts/tsMaterialList.h"
const F32 TSShapeLoader::DefaultTime = -1.0f;
const double TSShapeLoader::MinFrameRate = 15.0f;
const double TSShapeLoader::MaxFrameRate = 60.0f;
const double TSShapeLoader::AppGroundFrameRate = 10.0f;
Torque::Path TSShapeLoader::shapePath;
//------------------------------------------------------------------------------
// Utility functions
void TSShapeLoader::zapScale(MatrixF& mat)
{
Point3F invScale = mat.getScale();
invScale.x = invScale.x ? (1.0f / invScale.x) : 0;
invScale.y = invScale.y ? (1.0f / invScale.y) : 0;
invScale.z = invScale.z ? (1.0f / invScale.z) : 0;
mat.scale(invScale);
}
//------------------------------------------------------------------------------
// Shape utility functions
MatrixF TSShapeLoader::getLocalNodeMatrix(AppNode* node, F32 t)
{
MatrixF m1 = node->getNodeTransform(t);
// multiply by inverse scale at t=0
MatrixF m10 = node->getNodeTransform(DefaultTime);
m1.scale(Point3F(1.0f/m10.getScale().x, 1.0f/m10.getScale().y, 1.0f/m10.getScale().z));
if (node->mParentIndex >= 0)
{
AppNode *parent = appNodes[node->mParentIndex];
MatrixF m2 = parent->getNodeTransform(t);
// multiply by inverse scale at t=0
MatrixF m20 = parent->getNodeTransform(DefaultTime);
m2.scale(Point3F(1.0f/m20.getScale().x, 1.0f/m20.getScale().y, 1.0f/m20.getScale().z));
// get local transform by pre-multiplying by inverted parent transform
m1 = m2.inverse() * m1;
}
else if (boundsNode && node != boundsNode)
{
// make transform relative to bounds node transform at time=t
MatrixF mb = boundsNode->getNodeTransform(t);
zapScale(mb);
m1 = mb.inverse() * m1;
}
return m1;
}
void TSShapeLoader::generateNodeTransform(AppNode* node, F32 t, bool blend, F32 referenceTime,
QuatF& rot, Point3F& trans, QuatF& srot, Point3F& scale)
{
MatrixF m1 = getLocalNodeMatrix(node, t);
if (blend)
{
MatrixF m0 = getLocalNodeMatrix(node, referenceTime);
m1 = m0.inverse() * m1;
}
rot.set(m1);
trans = m1.getPosition();
srot.identity(); //@todo: srot not supported yet
scale = m1.getScale();
}
//-----------------------------------------------------------------------------
void TSShapeLoader::updateProgress(int major, const char* msg, int numMinor, int minor)
{
// Calculate progress value
F32 progress = (F32)major / NumLoadPhases;
const char *progressMsg = msg;
if (numMinor)
{
progress += (minor * (1.0f / NumLoadPhases) / numMinor);
progressMsg = avar("%s (%d of %d)", msg, minor + 1, numMinor);
}
Con::executef("updateTSShapeLoadProgress", Con::getFloatArg(progress), progressMsg);
}
//-----------------------------------------------------------------------------
// Shape creation entry point
TSShape* TSShapeLoader::generateShape(const Torque::Path& path)
{
shapePath = path;
shape = new TSShape();
shape->mExporterVersion = 124;
shape->mSmallestVisibleSize = 999999;
shape->mSmallestVisibleDL = 0;
shape->mReadVersion = 24;
shape->mFlags = 0;
shape->mSequencesConstructed = 0;
// Get all nodes, objects and sequences in the shape
updateProgress(Load_EnumerateScene, "Enumerating scene...");
enumerateScene();
if (!subshapes.size())
{
delete shape;
Con::errorf("Failed to load shape \"%s\", no subshapes found", path.getFullPath().c_str());
return NULL;
}
// Create the TSShape::Node hierarchy
generateSubshapes();
// Create objects (meshes and details)
generateObjects();
// Generate initial object states and node transforms
generateDefaultStates();
// Generate skins
generateSkins();
// Generate material list
generateMaterialList();
// Generate animation sequences
generateSequences();
// Sort detail levels and meshes
updateProgress(Load_InitShape, "Initialising shape...");
sortDetails();
// Install the TS memory helper into a TSShape object.
install();
return shape;
}
bool TSShapeLoader::processNode(AppNode* node)
{
// Detect bounds node
if ( node->isBounds() )
{
if ( boundsNode )
{
Con::warnf( "More than one bounds node found" );
return false;
}
boundsNode = node;
// Process bounds geometry
MatrixF boundsMat(boundsNode->getNodeTransform(DefaultTime));
boundsMat.inverse();
zapScale(boundsMat);
for (S32 iMesh = 0; iMesh < boundsNode->getNumMesh(); iMesh++)
{
AppMesh* mesh = boundsNode->getMesh(iMesh);
MatrixF transform = mesh->getMeshTransform(DefaultTime);
transform.mulL(boundsMat);
mesh->lockMesh(DefaultTime, transform);
}
return true;
}
// Detect sequence markers
if ( node->isSequence() )
{
//appSequences.push_back(new AppSequence(node));
return false;
}
// Add this node to the subshape (create one if needed)
if ( subshapes.size() == 0 )
subshapes.push_back( new TSShapeLoader::Subshape );
subshapes.last()->branches.push_back( node );
return true;
}
//-----------------------------------------------------------------------------
// Nodes, meshes and skins
typedef bool (*NameCmpFunc)(const String&, const Vector<String>&, void*, void*);
bool cmpShapeName(const String& key, const Vector<String>& names, void* arg1, void* arg2)
{
for (S32 i = 0; i < names.size(); i++)
{
if (names[i].compare(key, 0, String::NoCase) == 0)
return false;
}
return true;
}
String getUniqueName(const char* name, NameCmpFunc isNameUnique, const Vector<String>& names, void* arg1=0, void* arg2=0)
{
const int MAX_ITERATIONS = 0x10000; // maximum of 4 characters (A-P) will be appended
String suffix;
for (S32 i = 0; i < MAX_ITERATIONS; i++)
{
// Generate a suffix using the first 16 characters of the alphabet
suffix.clear();
for (S32 value = i; value != 0; value >>= 4)
suffix = suffix + (char)('A' + (value & 0xF));
String uname = name + suffix;
if (isNameUnique(uname, names, arg1, arg2))
return uname;
}
return name;
}
void TSShapeLoader::recurseSubshape(AppNode* appNode, S32 parentIndex, bool recurseChildren)
{
// Ignore local bounds nodes
if (appNode->isBounds())
return;
S32 subShapeNum = shape->subShapeFirstNode.size()-1;
Subshape* subshape = subshapes[subShapeNum];
// Check if we should collapse this node
S32 myIndex;
if (ignoreNode(appNode->getName()))
{
myIndex = parentIndex;
}
else
{
// Check that adding this node will not exceed the maximum node count
if (shape->nodes.size() >= MAX_TS_SET_SIZE)
return;
myIndex = shape->nodes.size();
String nodeName = getUniqueName(appNode->getName(), cmpShapeName, shape->names);
// Create the 3space node
shape->nodes.increment();
shape->nodes.last().nameIndex = shape->addName(nodeName);
shape->nodes.last().parentIndex = parentIndex;
shape->nodes.last().firstObject = -1;
shape->nodes.last().firstChild = -1;
shape->nodes.last().nextSibling = -1;
// Add the AppNode to a matching list (so AppNodes can be accessed using 3space
// node indices)
appNodes.push_back(appNode);
appNodes.last()->mParentIndex = parentIndex;
// Check for NULL detail or AutoBillboard nodes (no children or geometry)
if ((appNode->getNumChildNodes() == 0) &&
(appNode->getNumMesh() == 0))
{
S32 size = 0x7FFFFFFF;
String dname(String::GetTrailingNumber(appNode->getName(), size));
if (dStrEqual(dname, "nulldetail") && (size != 0x7FFFFFFF))
{
shape->addDetail("detail", size, subShapeNum);
}
else if (appNode->isBillboard() && (size != 0x7FFFFFFF))
{
// AutoBillboard detail
S32 numEquatorSteps = 4;
S32 numPolarSteps = 0;
F32 polarAngle = 0.0f;
S32 dl = 0;
S32 dim = 64;
bool includePoles = true;
appNode->getInt("BB::EQUATOR_STEPS", numEquatorSteps);
appNode->getInt("BB::POLAR_STEPS", numPolarSteps);
appNode->getFloat("BB::POLAR_ANGLE", polarAngle);
appNode->getInt("BB::DL", dl);
appNode->getInt("BB::DIM", dim);
appNode->getBool("BB::INCLUDE_POLES", includePoles);
S32 detIndex = shape->addDetail( "bbDetail", size, -1 );
shape->details[detIndex].bbEquatorSteps = numEquatorSteps;
shape->details[detIndex].bbPolarSteps = numPolarSteps;
shape->details[detIndex].bbDetailLevel = dl;
shape->details[detIndex].bbDimension = dim;
shape->details[detIndex].bbIncludePoles = includePoles;
shape->details[detIndex].bbPolarAngle = polarAngle;
}
}
}
// Collect geometry
for (U32 iMesh = 0; iMesh < appNode->getNumMesh(); iMesh++)
{
AppMesh* mesh = appNode->getMesh(iMesh);
if (!ignoreMesh(mesh->getName()))
{
subshape->objMeshes.push_back(mesh);
subshape->objNodes.push_back(mesh->isSkin() ? -1 : myIndex);
}
}
// Create children
if (recurseChildren)
{
for (int iChild = 0; iChild < appNode->getNumChildNodes(); iChild++)
recurseSubshape(appNode->getChildNode(iChild), myIndex, true);
}
}
void TSShapeLoader::generateSubshapes()
{
for (U32 iSub = 0; iSub < subshapes.size(); iSub++)
{
updateProgress(Load_GenerateSubshapes, "Generating subshapes...", subshapes.size(), iSub);
Subshape* subshape = subshapes[iSub];
// Recurse through the node hierarchy, adding 3space nodes and
// collecting geometry
S32 firstNode = shape->nodes.size();
shape->subShapeFirstNode.push_back(firstNode);
for (U32 iBranch = 0; iBranch < subshape->branches.size(); iBranch++)
recurseSubshape(subshape->branches[iBranch], -1, true);
shape->subShapeNumNodes.push_back(shape->nodes.size() - firstNode);
if (shape->nodes.size() >= MAX_TS_SET_SIZE)
{
Con::warnf("Shape exceeds the maximum node count (%d). Ignoring additional nodes.",
MAX_TS_SET_SIZE);
}
}
}
// Custom name comparison function to compare mesh name and detail size
bool cmpMeshNameAndSize(const String& key, const Vector<String>& names, void* arg1, void* arg2)
{
const Vector<AppMesh*>& meshes = *(Vector<AppMesh*>*)arg1;
S32 meshSize = (S32)arg2;
for (S32 i = 0; i < names.size(); i++)
{
if (names[i].compare(key, 0, String::NoCase) == 0)
{
if (meshes[i]->detailSize == meshSize)
return false;
}
}
return true;
}
void TSShapeLoader::generateObjects()
{
for (S32 iSub = 0; iSub < subshapes.size(); iSub++)
{
Subshape* subshape = subshapes[iSub];
shape->subShapeFirstObject.push_back(shape->objects.size());
// Get the names and sizes of the meshes for this subshape
Vector<String> meshNames;
for (S32 iMesh = 0; iMesh < subshape->objMeshes.size(); iMesh++)
{
AppMesh* mesh = subshape->objMeshes[iMesh];
mesh->detailSize = 2;
String name = String::GetTrailingNumber( mesh->getName(), mesh->detailSize );
name = getUniqueName( name, cmpMeshNameAndSize, meshNames, &(subshape->objMeshes), (void*)mesh->detailSize );
meshNames.push_back( name );
// Fix up any collision details that don't have a negative detail level.
if ( dStrStartsWith(meshNames[iMesh], "Collision") ||
dStrStartsWith(meshNames[iMesh], "LOSCol") )
{
if (mesh->detailSize > 0)
mesh->detailSize = -mesh->detailSize;
}
}
// An 'object' is a collection of meshes with the same base name and
// different detail sizes. The object is attached to the node of the
// highest detail mesh.
// Sort the 3 arrays (objMeshes, objNodes, meshNames) by name and size
for (S32 i = 0; i < subshape->objMeshes.size()-1; i++)
{
for (S32 j = i+1; j < subshape->objMeshes.size(); j++)
{
if ((meshNames[i].compare(meshNames[j]) < 0) ||
((meshNames[i].compare(meshNames[j]) == 0) &&
(subshape->objMeshes[i]->detailSize < subshape->objMeshes[j]->detailSize)))
{
{
AppMesh* tmp = subshape->objMeshes[i];
subshape->objMeshes[i] = subshape->objMeshes[j];
subshape->objMeshes[j] = tmp;
}
{
S32 tmp = subshape->objNodes[i];
subshape->objNodes[i] = subshape->objNodes[j];
subshape->objNodes[j] = tmp;
}
{
String tmp = meshNames[i];
meshNames[i] = meshNames[j];
meshNames[j] = tmp;
}
}
}
}
// Now create objects
const String* lastName = 0;
for (S32 iMesh = 0; iMesh < subshape->objMeshes.size(); iMesh++)
{
AppMesh* mesh = subshape->objMeshes[iMesh];
if (!lastName || (meshNames[iMesh] != *lastName))
{
shape->objects.increment();
shape->objects.last().nameIndex = shape->addName(meshNames[iMesh]);
shape->objects.last().nodeIndex = subshape->objNodes[iMesh];
shape->objects.last().startMeshIndex = appMeshes.size();
shape->objects.last().numMeshes = 0;
lastName = &meshNames[iMesh];
}
// Add this mesh to the object
appMeshes.push_back(mesh);
shape->objects.last().numMeshes++;
// Set mesh flags
mesh->flags = 0;
if (mesh->isBillboard())
{
mesh->flags |= TSMesh::Billboard;
if (mesh->isBillboardZAxis())
mesh->flags |= TSMesh::BillboardZAxis;
}
// Set the detail name... do fixups for collision details.
const char* detailName = "detail";
if ( mesh->detailSize < 0 )
{
if ( dStrStartsWith(meshNames[iMesh], "Collision") ||
dStrStartsWith(meshNames[iMesh], "Col") )
detailName = "Collision";
else if (dStrStartsWith(meshNames[iMesh], "LOSCol"))
detailName = "LOS";
}
// Attempt to add the detail (will fail if it already exists)
S32 oldNumDetails = shape->details.size();
shape->addDetail(detailName, mesh->detailSize, iSub);
if (shape->details.size() > oldNumDetails)
{
Con::warnf("Object mesh \"%s\" has no matching detail (\"%s%d\" has"
" been added automatically)", mesh->getName(false), detailName, mesh->detailSize);
}
}
// Get object count for this subshape
shape->subShapeNumObjects.push_back(shape->objects.size() - shape->subShapeFirstObject.last());
}
}
void TSShapeLoader::generateSkins()
{
Vector<AppMesh*> skins;
for (int iObject = 0; iObject < shape->objects.size(); iObject++)
{
for (int iMesh = 0; iMesh < shape->objects[iObject].numMeshes; iMesh++)
{
AppMesh* mesh = appMeshes[shape->objects[iObject].startMeshIndex + iMesh];
if (mesh->isSkin())
skins.push_back(mesh);
}
}
for (int iSkin = 0; iSkin < skins.size(); iSkin++)
{
updateProgress(Load_GenerateSkins, "Generating skins...", skins.size(), iSkin);
// Get skin data (bones, vertex weights etc)
AppMesh* skin = skins[iSkin];
skin->lookupSkinData();
// Just copy initial verts and norms for now
skin->initialVerts.set(skin->points.address(), skin->vertsPerFrame);
skin->initialNorms.set(skin->normals.address(), skin->vertsPerFrame);
// Map bones to nodes
skin->nodeIndex.setSize(skin->bones.size());
for (int iBone = 0; iBone < skin->bones.size(); iBone++)
{
// Find the node that matches this bone
skin->nodeIndex[iBone] = -1;
for (int iNode = 0; iNode < appNodes.size(); iNode++)
{
if (appNodes[iNode]->isEqual(skin->bones[iBone]))
{
delete skin->bones[iBone];
skin->bones[iBone] = appNodes[iNode];
skin->nodeIndex[iBone] = iNode;
break;
}
}
if (skin->nodeIndex[iBone] == -1)
{
Con::warnf("Could not find bone %d. Defaulting to first node", iBone);
skin->nodeIndex[iBone] = 0;
}
}
}
}
void TSShapeLoader::generateDefaultStates()
{
// Generate default object states (includes initial geometry)
for (int iObject = 0; iObject < shape->objects.size(); iObject++)
{
updateProgress(Load_GenerateDefaultStates, "Generating initial mesh and node states...",
shape->objects.size(), iObject);
TSShape::Object& obj = shape->objects[iObject];
// Calculate the objectOffset for each mesh at T=0
for (int iMesh = 0; iMesh < obj.numMeshes; iMesh++)
{
AppMesh* appMesh = appMeshes[obj.startMeshIndex + iMesh];
AppNode* appNode = obj.nodeIndex >= 0 ? appNodes[obj.nodeIndex] : boundsNode;
MatrixF meshMat(appMesh->getMeshTransform(DefaultTime));
MatrixF nodeMat(appMesh->isSkin() ? meshMat : appNode->getNodeTransform(DefaultTime));
zapScale(nodeMat);
appMesh->objectOffset = nodeMat.inverse() * meshMat;
}
generateObjectState(shape->objects[iObject], DefaultTime, true, true);
}
// Generate default node transforms
for (int iNode = 0; iNode < appNodes.size(); iNode++)
{
// Determine the default translation and rotation for the node
QuatF rot, srot;
Point3F trans, scale;
generateNodeTransform(appNodes[iNode], DefaultTime, false, 0, rot, trans, srot, scale);
// Add default node translation and rotation
addNodeRotation(rot, true);
addNodeTranslation(trans, true);
}
}
void TSShapeLoader::generateObjectState(TSShape::Object& obj, F32 t, bool addFrame, bool addMatFrame)
{
shape->objectStates.increment();
TSShape::ObjectState& state = shape->objectStates.last();
state.frameIndex = 0;
state.matFrameIndex = 0;
state.vis = mClampF(appMeshes[obj.startMeshIndex]->getVisValue(t), 0.0f, 1.0f);
if (addFrame || addMatFrame)
{
generateFrame(obj, t, addFrame, addMatFrame);
// set the frame number for the object state
state.frameIndex = appMeshes[obj.startMeshIndex]->numFrames - 1;
state.matFrameIndex = appMeshes[obj.startMeshIndex]->numMatFrames - 1;
}
}
void TSShapeLoader::generateFrame(TSShape::Object& obj, F32 t, bool addFrame, bool addMatFrame)
{
for (int iMesh = 0; iMesh < obj.numMeshes; iMesh++)
{
AppMesh* appMesh = appMeshes[obj.startMeshIndex + iMesh];
U32 oldNumPoints = appMesh->points.size();
U32 oldNumUvs = appMesh->uvs.size();
// Get the mesh geometry at time, 't'
// Geometry verts, normals and tverts can be animated (different set for
// each frame), but the TSDrawPrimitives stay the same, so the way lockMesh
// works is that it will only generate the primitives once, then after that
// will just append verts, normals and tverts each time it is called.
appMesh->lockMesh(t, appMesh->objectOffset);
// Calculate vertex normals if required
if (appMesh->normals.size() != appMesh->points.size())
appMesh->computeNormals();
// If this is the first call, set the number of points per frame
if (appMesh->numFrames == 0)
{
appMesh->vertsPerFrame = appMesh->points.size();
}
else
{
// Check frame topology => ie. that the right number of points, normals
// and tverts was added
if ((appMesh->points.size() - oldNumPoints) != appMesh->vertsPerFrame)
{
Con::warnf("Wrong number of points (%d) added at time=%f (expected %d)",
appMesh->points.size() - oldNumPoints, t, appMesh->vertsPerFrame);
addFrame = false;
}
if ((appMesh->normals.size() - oldNumPoints) != appMesh->vertsPerFrame)
{
Con::warnf("Wrong number of normals (%d) added at time=%f (expected %d)",
appMesh->normals.size() - oldNumPoints, t, appMesh->vertsPerFrame);
addFrame = false;
}
if ((appMesh->uvs.size() - oldNumUvs) != appMesh->vertsPerFrame)
{
Con::warnf("Wrong number of tverts (%d) added at time=%f (expected %d)",
appMesh->uvs.size() - oldNumUvs, t, appMesh->vertsPerFrame);
addMatFrame = false;
}
}
// Because lockMesh adds points, normals AND tverts each call, if we didn't
// actually want another frame or matFrame, we need to remove them afterwards.
// In the common case (we DO want the frame), we can do nothing => the
// points/normals/tverts are already in place!
if (addFrame)
{
appMesh->numFrames++;
}
else
{
appMesh->points.setSize(oldNumPoints);
appMesh->normals.setSize(oldNumPoints);
}
if (addMatFrame)
{
appMesh->numMatFrames++;
}
else
{
appMesh->uvs.setSize(oldNumPoints);
}
}
}
//-----------------------------------------------------------------------------
// Materials
/// Convert all Collada materials into a single TSMaterialList
void TSShapeLoader::generateMaterialList()
{
// Install the materials into the material list
shape->materialList = new TSMaterialList;
for (int iMat = 0; iMat < AppMesh::appMaterials.size(); iMat++)
{
updateProgress(Load_GenerateMaterials, "Generating materials...", AppMesh::appMaterials.size(), iMat);
AppMaterial* appMat = AppMesh::appMaterials[iMat];
shape->materialList->push_back(appMat->getName(), appMat->getFlags(), U32(-1), U32(-1), U32(-1), 1.0f, appMat->getReflectance());
}
}
//-----------------------------------------------------------------------------
// Animation Sequences
void TSShapeLoader::generateSequences()
{
for (int iSeq = 0; iSeq < appSequences.size(); iSeq++)
{
updateProgress(Load_GenerateSequences, "Generating sequences...", appSequences.size(), iSeq);
// Initialize the sequence
appSequences[iSeq]->setActive(true);
shape->sequences.increment();
TSShape::Sequence& seq = shape->sequences.last();
seq.nameIndex = shape->addName(appSequences[iSeq]->getName());
seq.toolBegin = appSequences[iSeq]->getStart();
seq.priority = appSequences[iSeq]->getPriority();
seq.flags = appSequences[iSeq]->getFlags();
// Compute duration and number of keyframes (then adjust time between frames to match)
seq.duration = appSequences[iSeq]->getEnd() - appSequences[iSeq]->getStart();
seq.numKeyframes = (S32)(seq.duration * appSequences[iSeq]->fps + 0.5f) + 1;
seq.sourceData.start = 0;
seq.sourceData.end = seq.numKeyframes-1;
seq.sourceData.total = seq.numKeyframes;
// Set membership arrays (ie. which nodes and objects are affected by this sequence)
setNodeMembership(seq, appSequences[iSeq]);
setObjectMembership(seq, appSequences[iSeq]);
// Generate keyframes
generateNodeAnimation(seq);
generateObjectAnimation(seq, appSequences[iSeq]);
generateGroundAnimation(seq, appSequences[iSeq]);
generateFrameTriggers(seq, appSequences[iSeq]);
// Set sequence flags
seq.dirtyFlags = 0;
if (seq.rotationMatters.testAll() || seq.translationMatters.testAll() || seq.scaleMatters.testAll())
seq.dirtyFlags |= TSShapeInstance::TransformDirty;
if (seq.visMatters.testAll())
seq.dirtyFlags |= TSShapeInstance::VisDirty;
if (seq.frameMatters.testAll())
seq.dirtyFlags |= TSShapeInstance::FrameDirty;
if (seq.matFrameMatters.testAll())
seq.dirtyFlags |= TSShapeInstance::MatFrameDirty;
// Set shape flags (only the most significant scale type)
U32 curVal = shape->mFlags & TSShape::AnyScale;
shape->mFlags &= ~(TSShape::AnyScale);
shape->mFlags |= getMax(curVal, seq.flags & TSShape::AnyScale); // take the larger value (can only convert upwards)
appSequences[iSeq]->setActive(false);
}
}
void TSShapeLoader::setNodeMembership(TSShape::Sequence& seq, const AppSequence* appSeq)
{
seq.rotationMatters.clearAll(); // node rotation (size = nodes.size())
seq.translationMatters.clearAll(); // node translation (size = nodes.size())
seq.scaleMatters.clearAll(); // node scale (size = nodes.size())
// This shouldn't be allowed, but check anyway...
if (seq.numKeyframes < 2)
return;
// Note: this fills the cache with current sequence data. Methods that get
// called later (e.g. generateNodeAnimation) use this info (and assume it's set).
fillNodeTransformCache(seq, appSeq);
// Test to see if the transform changes over the interval in order to decide
// whether to animate the transform in 3space. We don't use app's mechanism
// for doing this because it functions different in different apps and we do
// some special stuff with scale.
setRotationMembership(seq);
setTranslationMembership(seq);
setScaleMembership(seq);
}
void TSShapeLoader::setRotationMembership(TSShape::Sequence& seq)
{
for (int iNode = 0; iNode < appNodes.size(); iNode++)
{
// Check if any of the node rotations are different to
// the default rotation
QuatF defaultRot;
shape->defaultRotations[iNode].getQuatF(&defaultRot);
for (int iFrame = 0; iFrame < seq.numKeyframes; iFrame++)
{
if (nodeRotCache[iNode][iFrame] != defaultRot)
{
seq.rotationMatters.set(iNode);
break;
}
}
}
}
void TSShapeLoader::setTranslationMembership(TSShape::Sequence& seq)
{
for (int iNode = 0; iNode < appNodes.size(); iNode++)
{
// Check if any of the node translations are different to
// the default translation
Point3F& defaultTrans = shape->defaultTranslations[iNode];
for (int iFrame = 0; iFrame < seq.numKeyframes; iFrame++)
{
if (!nodeTransCache[iNode][iFrame].equal(defaultTrans))
{
seq.translationMatters.set(iNode);
break;
}
}
}
}
void TSShapeLoader::setScaleMembership(TSShape::Sequence& seq)
{
Point3F unitScale(1,1,1);
U32 arbitraryScaleCount = 0;
U32 alignedScaleCount = 0;
U32 uniformScaleCount = 0;
for (int iNode = 0; iNode < appNodes.size(); iNode++)
{
// Check if any of the node scales are not the unit scale
for (int iFrame = 0; iFrame < seq.numKeyframes; iFrame++)
{
Point3F& scale = nodeScaleCache[iNode][iFrame];
if (!unitScale.equal(scale))
{
// Determine what type of scale this is
if (!nodeScaleRotCache[iNode][iFrame].isIdentity())
arbitraryScaleCount++;
else if (scale.x != scale.y || scale.y != scale.z)
alignedScaleCount++;
else
uniformScaleCount++;
seq.scaleMatters.set(iNode);
break;
}
}
}
// Only one type of scale is animated
if (arbitraryScaleCount)
seq.flags |= TSShape::ArbitraryScale;
else if (alignedScaleCount)
seq.flags |= TSShape::AlignedScale;
else if (uniformScaleCount)
seq.flags |= TSShape::UniformScale;
}
void TSShapeLoader::setObjectMembership(TSShape::Sequence& seq, const AppSequence* appSeq)
{
seq.visMatters.clearAll(); // object visibility (size = objects.size())
seq.frameMatters.clearAll(); // vert animation (morph) (size = objects.size())
seq.matFrameMatters.clearAll(); // UV animation (size = objects.size())
for (int iObject = 0; iObject < shape->objects.size(); iObject++)
{
if (!appMeshes[shape->objects[iObject].startMeshIndex])
continue;
if (appMeshes[shape->objects[iObject].startMeshIndex]->animatesVis(appSeq))
seq.visMatters.set(iObject);
// Morph and UV animation has been deprecated
//if (appMeshes[shape->objects[iObject].startMeshIndex]->animatesFrame(appSeq))
//seq.frameMatters.set(iObject);
//if (appMeshes[shape->objects[iObject].startMeshIndex]->animatesMatFrame(appSeq))
//seq.matFrameMatters.set(iObject);
}
}
void TSShapeLoader::clearNodeTransformCache()
{
// clear out the transform caches
for (int i = 0; i < nodeRotCache.size(); i++)
delete [] nodeRotCache[i];
nodeRotCache.clear();
for (int i = 0; i < nodeTransCache.size(); i++)
delete [] nodeTransCache[i];
nodeTransCache.clear();
for (int i = 0; i < nodeScaleRotCache.size(); i++)
delete [] nodeScaleRotCache[i];
nodeScaleRotCache.clear();
for (int i = 0; i < nodeScaleCache.size(); i++)
delete [] nodeScaleCache[i];
nodeScaleCache.clear();
}
void TSShapeLoader::fillNodeTransformCache(TSShape::Sequence& seq, const AppSequence* appSeq)
{
// clear out the transform caches and set it up for this sequence
clearNodeTransformCache();
nodeRotCache.setSize(appNodes.size());
for (int i = 0; i < nodeRotCache.size(); i++)
nodeRotCache[i] = new QuatF[seq.numKeyframes];
nodeTransCache.setSize(appNodes.size());
for (int i = 0; i < nodeTransCache.size(); i++)
nodeTransCache[i] = new Point3F[seq.numKeyframes];
nodeScaleRotCache.setSize(appNodes.size());
for (int i = 0; i < nodeScaleRotCache.size(); i++)
nodeScaleRotCache[i] = new QuatF[seq.numKeyframes];
nodeScaleCache.setSize(appNodes.size());
for (int i = 0; i < nodeScaleCache.size(); i++)
nodeScaleCache[i] = new Point3F[seq.numKeyframes];
// get the node transforms for every frame
for (int iFrame = 0; iFrame < seq.numKeyframes; iFrame++)
{
F32 time = appSeq->getStart() + seq.duration * iFrame / getMax(1, seq.numKeyframes - 1);
for (int iNode = 0; iNode < appNodes.size(); iNode++)
{
generateNodeTransform(appNodes[iNode], time, seq.isBlend(), appSeq->getBlendRefTime(),
nodeRotCache[iNode][iFrame], nodeTransCache[iNode][iFrame],
nodeScaleRotCache[iNode][iFrame], nodeScaleCache[iNode][iFrame]);
}
}
}
void TSShapeLoader::addNodeRotation(QuatF& rot, bool defaultVal)
{
Quat16 rot16;
rot16.set(rot);
if (!defaultVal)
shape->nodeRotations.push_back(rot16);
else
shape->defaultRotations.push_back(rot16);
}
void TSShapeLoader::addNodeTranslation(Point3F& trans, bool defaultVal)
{
if (!defaultVal)
shape->nodeTranslations.push_back(trans);
else
shape->defaultTranslations.push_back(trans);
}
void TSShapeLoader::addNodeUniformScale(F32 scale)
{
shape->nodeUniformScales.push_back(scale);
}
void TSShapeLoader::addNodeAlignedScale(Point3F& scale)
{
shape->nodeAlignedScales.push_back(scale);
}
void TSShapeLoader::addNodeArbitraryScale(QuatF& qrot, Point3F& scale)
{
Quat16 rot16;
rot16.set(qrot);
shape->nodeArbitraryScaleRots.push_back(rot16);
shape->nodeArbitraryScaleFactors.push_back(scale);
}
void TSShapeLoader::generateNodeAnimation(TSShape::Sequence& seq)
{
seq.baseRotation = shape->nodeRotations.size();
seq.baseTranslation = shape->nodeTranslations.size();
seq.baseScale = (seq.flags & TSShape::ArbitraryScale) ? shape->nodeArbitraryScaleRots.size() :
(seq.flags & TSShape::AlignedScale) ? shape->nodeAlignedScales.size() :
shape->nodeUniformScales.size();
for (int iNode = 0; iNode < appNodes.size(); iNode++)
{
for (int iFrame = 0; iFrame < seq.numKeyframes; iFrame++)
{
if (seq.rotationMatters.test(iNode))
addNodeRotation(nodeRotCache[iNode][iFrame], false);
if (seq.translationMatters.test(iNode))
addNodeTranslation(nodeTransCache[iNode][iFrame], false);
if (seq.scaleMatters.test(iNode))
{
QuatF& rot = nodeScaleRotCache[iNode][iFrame];
Point3F scale = nodeScaleCache[iNode][iFrame];
if (seq.flags & TSShape::ArbitraryScale)
addNodeArbitraryScale(rot, scale);
else if (seq.flags & TSShape::AlignedScale)
addNodeAlignedScale(scale);
else if (seq.flags & TSShape::UniformScale)
addNodeUniformScale((scale.x+scale.y+scale.z)/3.0f);
}
}
}
}
void TSShapeLoader::generateObjectAnimation(TSShape::Sequence& seq, const AppSequence* appSeq)
{
seq.baseObjectState = shape->objectStates.size();
for (int iObject = 0; iObject < shape->objects.size(); iObject++)
{
bool visMatters = seq.visMatters.test(iObject);
bool frameMatters = seq.frameMatters.test(iObject);
bool matFrameMatters = seq.matFrameMatters.test(iObject);
if (visMatters || frameMatters || matFrameMatters)
{
for (int iFrame = 0; iFrame < seq.numKeyframes; iFrame++)
{
F32 time = appSeq->getStart() + seq.duration * iFrame / getMax(1, seq.numKeyframes - 1);
generateObjectState(shape->objects[iObject], time, frameMatters, matFrameMatters);
}
}
}
}
void TSShapeLoader::generateGroundAnimation(TSShape::Sequence& seq, const AppSequence* appSeq)
{
seq.firstGroundFrame = shape->groundTranslations.size();
seq.numGroundFrames = 0;
if (!boundsNode)
return;
// Check if the bounds node is animated by this sequence
seq.numGroundFrames = (S32)((seq.duration + 0.25f/AppGroundFrameRate) * AppGroundFrameRate);
seq.flags |= TSShape::MakePath;
// Get ground transform at the start of the sequence
MatrixF invStartMat = boundsNode->getNodeTransform(appSeq->getStart());
zapScale(invStartMat);
invStartMat.inverse();
for (int iFrame = 0; iFrame < seq.numGroundFrames; iFrame++)
{
F32 time = appSeq->getStart() + seq.duration * iFrame / getMax(1, seq.numGroundFrames - 1);
// Determine delta bounds node transform at 't'
MatrixF mat = boundsNode->getNodeTransform(time);
zapScale(mat);
mat = invStartMat * mat;
// Add ground transform
Quat16 rotation;
rotation.set(QuatF(mat));
shape->groundTranslations.push_back(mat.getPosition());
shape->groundRotations.push_back(rotation);
}
}
void TSShapeLoader::generateFrameTriggers(TSShape::Sequence& seq, const AppSequence* appSeq)
{
// Initialize triggers
seq.firstTrigger = shape->triggers.size();
seq.numTriggers = appSeq->getNumTriggers();
if (!seq.numTriggers)
return;
seq.flags |= TSShape::MakePath;
// Add triggers
for (int iTrigger = 0; iTrigger < seq.numTriggers; iTrigger++)
{
shape->triggers.increment();
appSeq->getTrigger(iTrigger, shape->triggers.last());
}
// Track the triggers that get turned off by this shape...normally, triggers
// aren't turned on/off, just on...if we are a trigger that does both then we
// need to mark ourselves as such so that on/off can become off/on when sequence
// is played in reverse...
U32 offTriggers = 0;
for (int iTrigger = 0; iTrigger < seq.numTriggers; iTrigger++)
{
U32 state = shape->triggers[seq.firstTrigger+iTrigger].state;
if ((state & TSShape::Trigger::StateOn) == 0)
offTriggers |= (state & TSShape::Trigger::StateMask);
}
// We now know which states are turned off, set invert on all those (including when turned on)
for (int iTrigger = 0; iTrigger < seq.numTriggers; iTrigger++)
{
if (shape->triggers[seq.firstTrigger + iTrigger].state & offTriggers)
shape->triggers[seq.firstTrigger + iTrigger].state |= TSShape::Trigger::InvertOnReverse;
}
}
//-----------------------------------------------------------------------------
void TSShapeLoader::sortDetails()
{
// Sort objects by: transparency, material index and node index
// Insert NULL meshes where required
for (int iSub = 0; iSub < subshapes.size(); iSub++)
{
Vector<S32> validDetails;
shape->getSubShapeDetails(iSub, validDetails);
for (int iDet = 0; iDet < validDetails.size(); iDet++)
{
TSShape::Detail &detail = shape->details[validDetails[iDet]];
if (detail.subShapeNum >= 0)
detail.objectDetailNum = iDet;
for (int iObj = shape->subShapeFirstObject[iSub];
iObj < (shape->subShapeFirstObject[iSub] + shape->subShapeNumObjects[iSub]);
iObj++)
{
TSShape::Object &object = shape->objects[iObj];
// Insert a NULL mesh for this detail level if required (ie. if the
// object does not already have a mesh with an equal or higher detail)
S32 meshIndex = (iDet < object.numMeshes) ? iDet : object.numMeshes-1;
if (appMeshes[object.startMeshIndex + meshIndex]->detailSize < shape->details[iDet].size)
{
// Add a NULL mesh
appMeshes.insert(object.startMeshIndex + iDet, NULL);
object.numMeshes++;
// Fixup the start index for the other objects
for (int k = iObj+1; k < shape->objects.size(); k++)
shape->objects[k].startMeshIndex++;
}
}
}
}
}
// Install into the TSShape, the shape is expected to be empty.
// Data is not copied, the TSShape is modified to point to memory
// managed by this object. This object is also bound to the TSShape
// object and will be deleted when it's deleted.
void TSShapeLoader::install()
{
// Arrays that are filled in by ts shape init, but need
// to be allocated beforehand.
shape->subShapeFirstTranslucentObject.setSize(shape->subShapeFirstObject.size());
// Construct TS sub-meshes
shape->meshes.setSize(appMeshes.size());
for (U32 m = 0; m < appMeshes.size(); m++)
shape->meshes[m] = appMeshes[m] ? appMeshes[m]->constructTSMesh() : NULL;
// Remove empty meshes and objects
for (S32 iObj = shape->objects.size()-1; iObj >= 0; iObj--)
{
TSShape::Object& obj = shape->objects[iObj];
for (S32 iMesh = obj.numMeshes-1; iMesh >= 0; iMesh--)
{
TSMesh *mesh = shape->meshes[obj.startMeshIndex + iMesh];
if (mesh && !mesh->primitives.size())
{
S32 oldMeshCount = obj.numMeshes;
destructInPlace(mesh);
shape->removeMeshFromObject(iObj, iMesh);
iMesh -= (oldMeshCount - obj.numMeshes - 1); // handle when more than one mesh is removed
}
}
if (!obj.numMeshes)
shape->removeObject(shape->getName(obj.nameIndex));
}
// Add a dummy object if needed so the shape loads and renders ok
if (!shape->details.size())
{
shape->addDetail("detail", 2, 0);
shape->subShapeNumObjects.last() = 1;
shape->meshes.push_back(NULL);
shape->objects.increment();
shape->objects.last().nameIndex = shape->addName("dummy");
shape->objects.last().nodeIndex = 0;
shape->objects.last().startMeshIndex = 0;
shape->objects.last().numMeshes = 1;
shape->objectStates.increment();
shape->objectStates.last().frameIndex = 0;
shape->objectStates.last().matFrameIndex = 0;
shape->objectStates.last().vis = 1.0f;
}
// Update smallest visible detail
shape->mSmallestVisibleDL = -1;
shape->mSmallestVisibleSize = 999999;
for (S32 i = 0; i < shape->details.size(); i++)
{
if ((shape->details[i].size >= 0) &&
(shape->details[i].size < shape->mSmallestVisibleSize))
{
shape->mSmallestVisibleDL = i;
shape->mSmallestVisibleSize = shape->details[i].size;
}
}
computeBounds(shape->bounds);
if (!shape->bounds.isValidBox())
shape->bounds = Box3F(1.0f);
shape->bounds.getCenter(&shape->center);
shape->radius = (shape->bounds.maxExtents - shape->center).len();
shape->tubeRadius = shape->radius;
shape->init();
}
void TSShapeLoader::computeBounds(Box3F& bounds)
{
// Compute the box that encloses the model geometry
bounds = Box3F::Invalid;
// Use bounds node geometry if present
if ( boundsNode && boundsNode->getNumMesh() )
{
for (S32 iMesh = 0; iMesh < boundsNode->getNumMesh(); iMesh++)
{
AppMesh* mesh = boundsNode->getMesh( iMesh );
if ( !mesh )
continue;
Box3F meshBounds;
mesh->computeBounds( meshBounds );
if ( meshBounds.isValidBox() )
bounds.intersect( meshBounds );
}
}
else
{
// Compute bounds based on all geometry in the model
for (S32 iMesh = 0; iMesh < appMeshes.size(); iMesh++)
{
AppMesh* mesh = appMeshes[iMesh];
if ( !mesh )
continue;
Box3F meshBounds;
mesh->computeBounds( meshBounds );
if ( meshBounds.isValidBox() )
bounds.intersect( meshBounds );
}
}
}
TSShapeLoader::~TSShapeLoader()
{
clearNodeTransformCache();
// Clear shared AppMaterial list
for (int iMat = 0; iMat < AppMesh::appMaterials.size(); iMat++)
delete AppMesh::appMaterials[iMat];
AppMesh::appMaterials.clear();
// Delete Subshapes
delete boundsNode;
for (int iSub = 0; iSub < subshapes.size(); iSub++)
delete subshapes[iSub];
// Delete AppSequences
for (int iSeq = 0; iSeq < appSequences.size(); iSeq++)
delete appSequences[iSeq];
appSequences.clear();
}
| mit |
gogartom/caffe-textmaps | src/caffe/layers/bn_layer.cpp | 2 | 16089 | #include <algorithm>
#include <vector>
#include "caffe/common_layers.hpp"
#include "caffe/filler.hpp"
#include "caffe/layer.hpp"
#include "caffe/util/math_functions.hpp"
namespace caffe {
template <typename Dtype>
void BNLayer<Dtype>::Reshape(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top) {
top[0]->Reshape(bottom[0]->num(), bottom[0]->channels(),
bottom[0]->height(), bottom[0]->width());
if (top.size() > 1) {
// top blob for batch mean
top[1]->Reshape(1, C_, 1, 1);
}
if (top.size() > 2) {
// top blob for batch variance
top[2]->Reshape(1, C_, 1, 1);
}
x_norm_.Reshape(bottom[0]->num(), bottom[0]->channels(),
bottom[0]->height(), bottom[0]->width());
// mean
spatial_mean_.Reshape(N_, C_, 1, 1);
batch_mean_.Reshape(1, C_, 1, 1);
// variance
spatial_variance_.Reshape(N_, C_, 1, 1);
batch_variance_.Reshape(1, C_, 1, 1);
// buffer blob
buffer_blob_.Reshape(N_, C_, H_, W_);
// fill spatial multiplier
spatial_sum_multiplier_.Reshape(1, 1, H_, W_);
Dtype* spatial_multipl_data = spatial_sum_multiplier_.mutable_cpu_data();
caffe_set(spatial_sum_multiplier_.count(), Dtype(1),
spatial_multipl_data);
caffe_set(spatial_sum_multiplier_.count(), Dtype(0),
spatial_sum_multiplier_.mutable_cpu_diff());
// fill batch multiplier
batch_sum_multiplier_.Reshape(N_, 1, 1, 1);
Dtype* batch_multiplier_data = batch_sum_multiplier_.mutable_cpu_data();
caffe_set(batch_sum_multiplier_.count(), Dtype(1),
batch_multiplier_data);
caffe_set(batch_sum_multiplier_.count(), Dtype(0),
batch_sum_multiplier_.mutable_cpu_diff());
}
template <typename Dtype>
void BNLayer<Dtype>::LayerSetUp(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top) {
// Figure out the dimensions
N_ = bottom[0]->num();
C_ = bottom[0]->channels();
H_ = bottom[0]->height();
W_ = bottom[0]->width();
var_eps_ = 1e-9;
// Check if we need to set up the weights
if (this->blobs_.size() > 0) {
LOG(INFO) << "Skipping parameter initialization";
} else {
this->blobs_.resize(2);
// fill scale with scale_filler
this->blobs_[0].reset(new Blob<Dtype>(1, C_, 1, 1));
shared_ptr<Filler<Dtype> > scale_filler(GetFiller<Dtype>(
this->layer_param_.bn_param().scale_filler()));
scale_filler->Fill(this->blobs_[0].get());
// fill shift with shift_filler
this->blobs_[1].reset(new Blob<Dtype>(1, C_, 1, 1));
shared_ptr<Filler<Dtype> > shift_filler(GetFiller<Dtype>(
this->layer_param_.bn_param().shift_filler()));
shift_filler->Fill(this->blobs_[1].get());
} // parameter initialization
this->param_propagate_down_.resize(this->blobs_.size(), true);
}
template <typename Dtype>
void BNLayer<Dtype>::Forward_cpu(const vector<Blob<Dtype>*>& bottom,
const vector<Blob<Dtype>*>& top) {
const Dtype* bottom_data = bottom[0]->cpu_data();
Dtype* top_data = top[0]->mutable_cpu_data();
const Dtype* const_top_data = top[0]->cpu_data();
const Dtype* scale_data = this->blobs_[0]->cpu_data();
const Dtype* shift_data = this->blobs_[1]->cpu_data();
switch (this->layer_param_.bn_param().bn_mode()) {
case BNParameter_BNMode_LEARN:
// put the squares of bottom into buffer_blob_
caffe_powx(bottom[0]->count(), bottom_data, Dtype(2),
buffer_blob_.mutable_cpu_data());
// computes variance using var(X) = E(X^2) - (EX)^2
// EX across spatial
caffe_cpu_gemv<Dtype>(CblasNoTrans, N_ * C_, H_ * W_,
Dtype(1. / (H_ * W_)), bottom_data,
spatial_sum_multiplier_.cpu_data(), Dtype(0),
spatial_mean_.mutable_cpu_data());
// EX across batch
caffe_cpu_gemv<Dtype>(CblasTrans, N_, C_, Dtype(1. / N_),
spatial_mean_.cpu_data(),
batch_sum_multiplier_.cpu_data(), Dtype(0),
batch_mean_.mutable_cpu_data());
// E(X^2) across spatial
caffe_cpu_gemv<Dtype>(CblasNoTrans, N_ * C_, H_ * W_,
Dtype(1. / (H_ * W_)), buffer_blob_.cpu_data(),
spatial_sum_multiplier_.cpu_data(), Dtype(0),
spatial_variance_.mutable_cpu_data());
// E(X^2) across batch
caffe_cpu_gemv<Dtype>(CblasTrans, N_, C_, Dtype(1. / N_),
spatial_variance_.cpu_data(),
batch_sum_multiplier_.cpu_data(), Dtype(0),
batch_variance_.mutable_cpu_data());
caffe_powx(batch_mean_.count(), batch_mean_.cpu_data(), Dtype(2),
buffer_blob_.mutable_cpu_data()); // (EX)^2
caffe_sub(batch_mean_.count(), batch_variance_.cpu_data(),
buffer_blob_.cpu_data(),
batch_variance_.mutable_cpu_data()); // variance
// save top[1] (batch_mean) and top[2] (batch_variance)
if (top.size() > 1) {
caffe_copy(batch_mean_.count(), batch_mean_.cpu_data(),
top[1]->mutable_cpu_data());
}
if (top.size() > 2) {
caffe_copy(batch_variance_.count(), batch_variance_.cpu_data(),
top[2]->mutable_cpu_data());
}
// do mean and variance normalization
// subtract mean
caffe_cpu_gemm<Dtype>(CblasNoTrans, CblasNoTrans, N_,
C_, 1, Dtype(1),
batch_sum_multiplier_.cpu_data(),
batch_mean_.cpu_data(), Dtype(0),
spatial_mean_.mutable_cpu_data());
caffe_cpu_gemm<Dtype>(CblasNoTrans, CblasNoTrans, N_ * C_,
H_ * W_, 1, Dtype(-1),
spatial_mean_.cpu_data(),
spatial_sum_multiplier_.cpu_data(), Dtype(0),
buffer_blob_.mutable_cpu_data());
caffe_add(buffer_blob_.count(), bottom_data,
buffer_blob_.cpu_data(), top_data);
// normalize variance
caffe_add_scalar(batch_variance_.count(), var_eps_,
batch_variance_.mutable_cpu_data());
caffe_powx(batch_variance_.count(),
batch_variance_.cpu_data(), Dtype(0.5),
batch_variance_.mutable_cpu_data());
caffe_cpu_gemm<Dtype>(CblasNoTrans, CblasNoTrans, N_,
C_, 1, Dtype(1),
batch_sum_multiplier_.cpu_data(),
batch_variance_.cpu_data(), Dtype(0),
spatial_variance_.mutable_cpu_data());
caffe_cpu_gemm<Dtype>(CblasNoTrans, CblasNoTrans,
N_ * C_, H_ * W_, 1, Dtype(1),
spatial_variance_.cpu_data(),
spatial_sum_multiplier_.cpu_data(), Dtype(0),
buffer_blob_.mutable_cpu_data());
caffe_div(buffer_blob_.count(), const_top_data,
buffer_blob_.cpu_data(), top_data);
// Saving x_norm
caffe_copy(buffer_blob_.count(), const_top_data,
x_norm_.mutable_cpu_data());
// scale
caffe_cpu_gemm<Dtype>(CblasNoTrans, CblasNoTrans, N_, C_, 1, Dtype(1),
batch_sum_multiplier_.cpu_data(), scale_data, Dtype(0),
spatial_variance_.mutable_cpu_data());
caffe_cpu_gemm<Dtype>(CblasNoTrans, CblasNoTrans, N_ * C_,
H_ * W_, 1, Dtype(1),
spatial_variance_.cpu_data(),
spatial_sum_multiplier_.cpu_data(), Dtype(0),
buffer_blob_.mutable_cpu_data());
caffe_mul(buffer_blob_.count(), top_data,
buffer_blob_.cpu_data(), top_data);
// shift
caffe_cpu_gemm<Dtype>(CblasNoTrans, CblasNoTrans, N_, C_, 1, Dtype(1),
batch_sum_multiplier_.cpu_data(), shift_data, Dtype(0),
spatial_mean_.mutable_cpu_data());
caffe_cpu_gemm<Dtype>(CblasNoTrans, CblasNoTrans,
N_ * C_, H_ * W_, 1, Dtype(1),
spatial_mean_.cpu_data(),
spatial_sum_multiplier_.cpu_data(), Dtype(0),
buffer_blob_.mutable_cpu_data());
caffe_add(buffer_blob_.count(), const_top_data,
buffer_blob_.cpu_data(), top_data);
break;
case BNParameter_BNMode_INFERENCE:
// scale
caffe_cpu_gemm<Dtype>(CblasNoTrans, CblasNoTrans, N_, C_, 1, Dtype(1),
batch_sum_multiplier_.cpu_data(), scale_data, Dtype(0),
spatial_variance_.mutable_cpu_data());
caffe_cpu_gemm<Dtype>(CblasNoTrans, CblasNoTrans, N_ * C_,
H_ * W_, 1, Dtype(1),
spatial_variance_.cpu_data(),
spatial_sum_multiplier_.cpu_data(), Dtype(0),
buffer_blob_.mutable_cpu_data());
caffe_mul(buffer_blob_.count(), bottom_data,
buffer_blob_.cpu_data(), top_data);
// shift
caffe_cpu_gemm<Dtype>(CblasNoTrans, CblasNoTrans, N_, C_, 1, Dtype(1),
batch_sum_multiplier_.cpu_data(), shift_data, Dtype(0),
spatial_mean_.mutable_cpu_data());
caffe_cpu_gemm<Dtype>(CblasNoTrans, CblasNoTrans,
N_ * C_, H_ * W_, 1, Dtype(1),
spatial_mean_.cpu_data(),
spatial_sum_multiplier_.cpu_data(), Dtype(0),
buffer_blob_.mutable_cpu_data());
caffe_add(buffer_blob_.count(), const_top_data,
buffer_blob_.cpu_data(), top_data);
break;
default:
LOG(FATAL) << "Unknown BN mode.";
}
}
template <typename Dtype>
void BNLayer<Dtype>::Backward_cpu(const vector<Blob<Dtype>*>& top,
const vector<bool>& propagate_down,
const vector<Blob<Dtype>*>& bottom) {
const Dtype* top_diff = top[0]->cpu_diff();
const Dtype* bottom_data = bottom[0]->cpu_data();
Dtype* bottom_diff = bottom[0]->mutable_cpu_diff();
Dtype* scale_diff = this->blobs_[0]->mutable_cpu_diff();
Dtype* shift_diff = this->blobs_[1]->mutable_cpu_diff();
const Dtype* scale_data = this->blobs_[0]->cpu_data();
switch (this->layer_param_.bn_param().bn_mode()) {
case BNParameter_BNMode_LEARN:
// Propagate layer to parameters
// gradient w.r.t. scale
caffe_mul(buffer_blob_.count(), x_norm_.cpu_data(),
top_diff, buffer_blob_.mutable_cpu_data());
// EX across spatial
caffe_cpu_gemv<Dtype>(CblasNoTrans, N_ * C_,
H_ * W_, Dtype(1), buffer_blob_.cpu_data(),
spatial_sum_multiplier_.cpu_data(), Dtype(0),
spatial_variance_.mutable_cpu_diff());
// EX across batch
caffe_cpu_gemv<Dtype>(CblasTrans, N_, C_, Dtype(1),
spatial_variance_.cpu_diff(),
batch_sum_multiplier_.cpu_data(), Dtype(0), scale_diff);
// gradient w.r.t. shift
// EX across spatial
caffe_cpu_gemv<Dtype>(CblasNoTrans, N_ * C_,
H_ * W_, Dtype(1), top_diff,
spatial_sum_multiplier_.cpu_data(),
Dtype(0), spatial_mean_.mutable_cpu_diff());
// EX across batch
caffe_cpu_gemv<Dtype>(CblasTrans, N_, C_,
Dtype(1), spatial_mean_.cpu_diff(),
batch_sum_multiplier_.cpu_data(),
Dtype(0), shift_diff);
// Propagate down
// put scale * top_diff to buffer_blob_
caffe_cpu_gemm<Dtype>(CblasNoTrans, CblasNoTrans, N_, C_, 1, Dtype(1),
batch_sum_multiplier_.cpu_data(), scale_data, Dtype(0),
spatial_variance_.mutable_cpu_data());
caffe_cpu_gemm<Dtype>(CblasNoTrans, CblasNoTrans, N_ * C_,
H_ * W_, 1, Dtype(1),
spatial_variance_.cpu_data(),
spatial_sum_multiplier_.cpu_data(), Dtype(0),
buffer_blob_.mutable_cpu_data());
caffe_mul(buffer_blob_.count(), top_diff, buffer_blob_.cpu_data(),
buffer_blob_.mutable_cpu_data());
// use new top diff for computation
caffe_mul(buffer_blob_.count(), x_norm_.cpu_data(),
buffer_blob_.cpu_data(), bottom_diff);
// EX across spatial
caffe_cpu_gemv<Dtype>(CblasNoTrans, N_ * C_, H_ * W_,
Dtype(1), bottom_diff,
spatial_sum_multiplier_.cpu_data(), Dtype(0),
spatial_mean_.mutable_cpu_data());
// EX across batch
caffe_cpu_gemv<Dtype>(CblasTrans, N_, C_, Dtype(1),
spatial_mean_.cpu_data(),
batch_sum_multiplier_.cpu_data(), Dtype(0),
batch_mean_.mutable_cpu_data());
caffe_cpu_gemm<Dtype>(CblasNoTrans, CblasNoTrans,
N_, C_, 1, Dtype(1),
batch_sum_multiplier_.cpu_data(),
batch_mean_.cpu_data(), Dtype(0),
spatial_mean_.mutable_cpu_data());
caffe_cpu_gemm<Dtype>(CblasNoTrans, CblasNoTrans, N_ * C_,
H_ * W_, 1, Dtype(1),
spatial_mean_.cpu_data(),
spatial_sum_multiplier_.cpu_data(), Dtype(0),
bottom_diff);
caffe_mul(buffer_blob_.count(),
x_norm_.cpu_data(), bottom_diff, bottom_diff);
// EX across spatial
caffe_cpu_gemv<Dtype>(CblasNoTrans, N_ * C_,
H_ * W_, Dtype(1), buffer_blob_.cpu_data(),
spatial_sum_multiplier_.cpu_data(), Dtype(0),
spatial_mean_.mutable_cpu_data());
// EX across batch
caffe_cpu_gemv<Dtype>(CblasTrans, N_, C_, Dtype(1),
spatial_mean_.cpu_data(),
batch_sum_multiplier_.cpu_data(), Dtype(0),
batch_mean_.mutable_cpu_data());
caffe_cpu_gemm<Dtype>(CblasNoTrans, CblasNoTrans,
N_, C_, 1, Dtype(1),
batch_sum_multiplier_.cpu_data(),
batch_mean_.cpu_data(), Dtype(0),
spatial_mean_.mutable_cpu_data());
caffe_cpu_gemm<Dtype>(CblasNoTrans, CblasNoTrans,
N_ * C_, H_ * W_, 1, Dtype(1),
spatial_mean_.cpu_data(),
spatial_sum_multiplier_.cpu_data(), Dtype(1), bottom_diff);
caffe_cpu_axpby(buffer_blob_.count(), Dtype(1),
buffer_blob_.cpu_data(), Dtype(-1. / (N_ * H_ * W_)),
bottom_diff);
// put the squares of bottom into buffer_blob_
caffe_powx(buffer_blob_.count(), bottom_data, Dtype(2),
buffer_blob_.mutable_cpu_data());
caffe_cpu_gemm<Dtype>(CblasNoTrans, CblasNoTrans,
N_, C_, 1, Dtype(1),
batch_sum_multiplier_.cpu_data(),
batch_variance_.cpu_data(), Dtype(0),
spatial_variance_.mutable_cpu_data());
caffe_cpu_gemm<Dtype>(CblasNoTrans, CblasNoTrans,
N_ * C_, H_ * W_, 1, Dtype(1),
spatial_variance_.cpu_data(),
spatial_sum_multiplier_.cpu_data(), Dtype(0),
buffer_blob_.mutable_cpu_data());
caffe_div(buffer_blob_.count(), bottom_diff,
buffer_blob_.cpu_data(), bottom_diff);
break;
case BNParameter_BNMode_INFERENCE:
// Propagate layer to parameters
// gradient w.r.t. scale
caffe_mul(buffer_blob_.count(), bottom_data,
top_diff, buffer_blob_.mutable_cpu_data());
// EX across spatial
caffe_cpu_gemv<Dtype>(CblasNoTrans, N_ * C_,
H_ * W_, Dtype(1), buffer_blob_.cpu_data(),
spatial_sum_multiplier_.cpu_data(), Dtype(0),
spatial_variance_.mutable_cpu_diff());
// EX across batch
caffe_cpu_gemv<Dtype>(CblasTrans, N_, C_, Dtype(1),
spatial_variance_.cpu_diff(),
batch_sum_multiplier_.cpu_data(), Dtype(0), scale_diff);
// gradient w.r.t. shift
// EX across spatial
caffe_cpu_gemv<Dtype>(CblasNoTrans, N_ * C_,
H_ * W_, Dtype(1), top_diff,
spatial_sum_multiplier_.cpu_data(),
Dtype(0), spatial_mean_.mutable_cpu_diff());
// EX across batch
caffe_cpu_gemv<Dtype>(CblasTrans, N_, C_,
Dtype(1), spatial_mean_.cpu_diff(),
batch_sum_multiplier_.cpu_data(),
Dtype(0), shift_diff);
// Propagate down
// put scale * top_diff to buffer_blob_
caffe_cpu_gemm<Dtype>(CblasNoTrans, CblasNoTrans, N_, C_, 1, Dtype(1),
batch_sum_multiplier_.cpu_data(), scale_data, Dtype(0),
spatial_variance_.mutable_cpu_data());
caffe_cpu_gemm<Dtype>(CblasNoTrans, CblasNoTrans, N_ * C_,
H_ * W_, 1, Dtype(1),
spatial_variance_.cpu_data(),
spatial_sum_multiplier_.cpu_data(), Dtype(0),
buffer_blob_.mutable_cpu_data());
caffe_mul(buffer_blob_.count(), top_diff, buffer_blob_.cpu_data(),
bottom_diff);
break;
default:
LOG(FATAL) << "Unknown BN mode.";
}
}
#ifdef CPU_ONLY
STUB_GPU(BNLayer);
#endif
INSTANTIATE_CLASS(BNLayer);
REGISTER_LAYER_CLASS(BN);
} // namespace caffe
| mit |
nzavagli/UnrealPy | UnrealPyEmbed/Development/Python/2015.08.07-Python2710-x64-Source-vs2015/Python27/Source/tcl-8.5.2.1/libtommath/bn_mp_xor.c | 3 | 1191 | #include <tommath.h>
#ifdef BN_MP_XOR_C
/* LibTomMath, multiple-precision integer library -- Tom St Denis
*
* LibTomMath is a library that provides multiple-precision
* integer arithmetic as well as number theoretic functionality.
*
* The library was designed directly after the MPI library by
* Michael Fromberger but has been written from scratch with
* additional optimizations in place.
*
* The library is free for all purposes without any express
* guarantee it works.
*
* Tom St Denis, tomstdenis@gmail.com, http://math.libtomcrypt.com
*/
/* XOR two ints together */
int
mp_xor (mp_int * a, mp_int * b, mp_int * c)
{
int res, ix, px;
mp_int t, *x;
if (a->used > b->used) {
if ((res = mp_init_copy (&t, a)) != MP_OKAY) {
return res;
}
px = b->used;
x = b;
} else {
if ((res = mp_init_copy (&t, b)) != MP_OKAY) {
return res;
}
px = a->used;
x = a;
}
for (ix = 0; ix < px; ix++) {
t.dp[ix] ^= x->dp[ix];
}
mp_clamp (&t);
mp_exch (c, &t);
mp_clear (&t);
return MP_OKAY;
}
#endif
/* $Source: /cvsroot/tcl/libtommath/bn_mp_xor.c,v $ */
/* $Revision: 1.1.1.4 $ */
/* $Date: 2006/12/01 00:08:11 $ */
| mit |
openmv/openmv | src/hal/nrfx/src/nrfx_i2s.c | 3 | 15054 | /*
* Copyright (c) 2015 - 2019, Nordic Semiconductor ASA
* 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 copyright holder 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.
*/
#include <nrfx.h>
#if NRFX_CHECK(NRFX_I2S_ENABLED)
#include <nrfx_i2s.h>
#include <hal/nrf_gpio.h>
#define NRFX_LOG_MODULE I2S
#include <nrfx_log.h>
#define EVT_TO_STR(event) \
(event == NRF_I2S_EVENT_RXPTRUPD ? "NRF_I2S_EVENT_RXPTRUPD" : \
(event == NRF_I2S_EVENT_TXPTRUPD ? "NRF_I2S_EVENT_TXPTRUPD" : \
(event == NRF_I2S_EVENT_STOPPED ? "NRF_I2S_EVENT_STOPPED" : \
"UNKNOWN EVENT")))
#if !defined(USE_WORKAROUND_FOR_I2S_STOP_ANOMALY) && \
(defined(NRF52832_XXAA) || defined(NRF52832_XXAB) || defined(NRF52840_XXAA) || \
defined(NRF9160_XXAA))
// Enable workaround for nRF52832 and nRF52840 anomaly 194 / nrf9160 anomaly 1
// (STOP task does not switch off all resources).
#define USE_WORKAROUND_FOR_I2S_STOP_ANOMALY 1
#endif
// Control block - driver instance local data.
typedef struct
{
nrfx_i2s_data_handler_t handler;
nrfx_drv_state_t state;
bool use_rx : 1;
bool use_tx : 1;
bool rx_ready : 1;
bool tx_ready : 1;
bool buffers_needed : 1;
bool buffers_reused : 1;
uint16_t buffer_size;
nrfx_i2s_buffers_t next_buffers;
nrfx_i2s_buffers_t current_buffers;
} i2s_control_block_t;
static i2s_control_block_t m_cb;
static void configure_pins(nrfx_i2s_config_t const * p_config)
{
uint32_t mck_pin, sdout_pin, sdin_pin;
// Configure pins used by the peripheral:
// - SCK and LRCK (required) - depending on the mode of operation these
// pins are configured as outputs (in Master mode) or inputs (in Slave
// mode).
if (p_config->mode == NRF_I2S_MODE_MASTER)
{
nrf_gpio_cfg_output(p_config->sck_pin);
nrf_gpio_cfg_output(p_config->lrck_pin);
}
else
{
nrf_gpio_cfg_input(p_config->sck_pin, NRF_GPIO_PIN_NOPULL);
nrf_gpio_cfg_input(p_config->lrck_pin, NRF_GPIO_PIN_NOPULL);
}
// - MCK (optional) - always output,
if (p_config->mck_pin != NRFX_I2S_PIN_NOT_USED)
{
mck_pin = p_config->mck_pin;
nrf_gpio_cfg_output(mck_pin);
}
else
{
mck_pin = NRF_I2S_PIN_NOT_CONNECTED;
}
// - SDOUT (optional) - always output,
if (p_config->sdout_pin != NRFX_I2S_PIN_NOT_USED)
{
sdout_pin = p_config->sdout_pin;
nrf_gpio_cfg_output(sdout_pin);
}
else
{
sdout_pin = NRF_I2S_PIN_NOT_CONNECTED;
}
// - SDIN (optional) - always input.
if (p_config->sdin_pin != NRFX_I2S_PIN_NOT_USED)
{
sdin_pin = p_config->sdin_pin;
nrf_gpio_cfg_input(sdin_pin, NRF_GPIO_PIN_NOPULL);
}
else
{
sdin_pin = NRF_I2S_PIN_NOT_CONNECTED;
}
nrf_i2s_pins_set(NRF_I2S,
p_config->sck_pin,
p_config->lrck_pin,
mck_pin,
sdout_pin,
sdin_pin);
}
nrfx_err_t nrfx_i2s_init(nrfx_i2s_config_t const * p_config,
nrfx_i2s_data_handler_t handler)
{
NRFX_ASSERT(p_config);
NRFX_ASSERT(handler);
nrfx_err_t err_code;
if (m_cb.state != NRFX_DRV_STATE_UNINITIALIZED)
{
err_code = NRFX_ERROR_INVALID_STATE;
NRFX_LOG_WARNING("Function: %s, error code: %s.",
__func__,
NRFX_LOG_ERROR_STRING_GET(err_code));
return err_code;
}
if (!nrf_i2s_configure(NRF_I2S,
p_config->mode,
p_config->format,
p_config->alignment,
p_config->sample_width,
p_config->channels,
p_config->mck_setup,
p_config->ratio))
{
err_code = NRFX_ERROR_INVALID_PARAM;
NRFX_LOG_WARNING("Function: %s, error code: %s.",
__func__,
NRFX_LOG_ERROR_STRING_GET(err_code));
return err_code;
}
configure_pins(p_config);
m_cb.handler = handler;
NRFX_IRQ_PRIORITY_SET(nrfx_get_irq_number(NRF_I2S), p_config->irq_priority);
NRFX_IRQ_ENABLE(nrfx_get_irq_number(NRF_I2S));
m_cb.state = NRFX_DRV_STATE_INITIALIZED;
NRFX_LOG_INFO("Initialized.");
return NRFX_SUCCESS;
}
void nrfx_i2s_uninit(void)
{
NRFX_ASSERT(m_cb.state != NRFX_DRV_STATE_UNINITIALIZED);
nrfx_i2s_stop();
NRFX_IRQ_DISABLE(nrfx_get_irq_number(NRF_I2S));
nrf_i2s_pins_set(NRF_I2S,
NRF_I2S_PIN_NOT_CONNECTED,
NRF_I2S_PIN_NOT_CONNECTED,
NRF_I2S_PIN_NOT_CONNECTED,
NRF_I2S_PIN_NOT_CONNECTED,
NRF_I2S_PIN_NOT_CONNECTED);
m_cb.state = NRFX_DRV_STATE_UNINITIALIZED;
NRFX_LOG_INFO("Uninitialized.");
}
nrfx_err_t nrfx_i2s_start(nrfx_i2s_buffers_t const * p_initial_buffers,
uint16_t buffer_size,
uint8_t flags)
{
NRFX_ASSERT(p_initial_buffers != NULL);
NRFX_ASSERT(p_initial_buffers->p_rx_buffer != NULL ||
p_initial_buffers->p_tx_buffer != NULL);
NRFX_ASSERT((p_initial_buffers->p_rx_buffer == NULL) ||
(nrfx_is_in_ram(p_initial_buffers->p_rx_buffer) &&
nrfx_is_word_aligned(p_initial_buffers->p_rx_buffer)));
NRFX_ASSERT((p_initial_buffers->p_tx_buffer == NULL) ||
(nrfx_is_in_ram(p_initial_buffers->p_tx_buffer) &&
nrfx_is_word_aligned(p_initial_buffers->p_tx_buffer)));
NRFX_ASSERT(buffer_size != 0);
(void)(flags);
nrfx_err_t err_code;
if (m_cb.state != NRFX_DRV_STATE_INITIALIZED)
{
err_code = NRFX_ERROR_INVALID_STATE;
NRFX_LOG_WARNING("Function: %s, error code: %s.",
__func__,
NRFX_LOG_ERROR_STRING_GET(err_code));
return err_code;
}
if (((p_initial_buffers->p_rx_buffer != NULL)
&& !nrfx_is_in_ram(p_initial_buffers->p_rx_buffer))
||
((p_initial_buffers->p_tx_buffer != NULL)
&& !nrfx_is_in_ram(p_initial_buffers->p_tx_buffer)))
{
err_code = NRFX_ERROR_INVALID_ADDR;
NRFX_LOG_WARNING("Function: %s, error code: %s.",
__func__,
NRFX_LOG_ERROR_STRING_GET(err_code));
return err_code;
}
m_cb.use_rx = (p_initial_buffers->p_rx_buffer != NULL);
m_cb.use_tx = (p_initial_buffers->p_tx_buffer != NULL);
m_cb.rx_ready = false;
m_cb.tx_ready = false;
m_cb.buffers_needed = false;
m_cb.buffer_size = buffer_size;
// Set the provided initial buffers as next, they will become the current
// ones after the IRQ handler is called for the first time, what will occur
// right after the START task is triggered.
m_cb.next_buffers = *p_initial_buffers;
m_cb.current_buffers.p_rx_buffer = NULL;
m_cb.current_buffers.p_tx_buffer = NULL;
nrf_i2s_transfer_set(NRF_I2S,
m_cb.buffer_size,
m_cb.next_buffers.p_rx_buffer,
m_cb.next_buffers.p_tx_buffer);
nrf_i2s_enable(NRF_I2S);
m_cb.state = NRFX_DRV_STATE_POWERED_ON;
nrf_i2s_event_clear(NRF_I2S, NRF_I2S_EVENT_RXPTRUPD);
nrf_i2s_event_clear(NRF_I2S, NRF_I2S_EVENT_TXPTRUPD);
nrf_i2s_event_clear(NRF_I2S, NRF_I2S_EVENT_STOPPED);
nrf_i2s_int_enable(NRF_I2S, (m_cb.use_rx ? NRF_I2S_INT_RXPTRUPD_MASK : 0) |
(m_cb.use_tx ? NRF_I2S_INT_TXPTRUPD_MASK : 0) |
NRF_I2S_INT_STOPPED_MASK);
nrf_i2s_task_trigger(NRF_I2S, NRF_I2S_TASK_START);
NRFX_LOG_INFO("Started.");
return NRFX_SUCCESS;
}
nrfx_err_t nrfx_i2s_next_buffers_set(nrfx_i2s_buffers_t const * p_buffers)
{
NRFX_ASSERT(m_cb.state == NRFX_DRV_STATE_POWERED_ON);
NRFX_ASSERT(p_buffers);
NRFX_ASSERT((p_buffers->p_rx_buffer == NULL) ||
(nrfx_is_in_ram(p_buffers->p_rx_buffer) &&
nrfx_is_word_aligned(p_buffers->p_rx_buffer)));
NRFX_ASSERT((p_buffers->p_tx_buffer == NULL) ||
(nrfx_is_in_ram(p_buffers->p_tx_buffer) &&
nrfx_is_word_aligned(p_buffers->p_tx_buffer)));
nrfx_err_t err_code;
if (!m_cb.buffers_needed)
{
err_code = NRFX_ERROR_INVALID_STATE;
NRFX_LOG_WARNING("Function: %s, error code: %s.",
__func__,
NRFX_LOG_ERROR_STRING_GET(err_code));
return err_code;
}
if (((p_buffers->p_rx_buffer != NULL)
&& !nrfx_is_in_ram(p_buffers->p_rx_buffer))
||
((p_buffers->p_tx_buffer != NULL)
&& !nrfx_is_in_ram(p_buffers->p_tx_buffer)))
{
err_code = NRFX_ERROR_INVALID_ADDR;
NRFX_LOG_WARNING("Function: %s, error code: %s.",
__func__,
NRFX_LOG_ERROR_STRING_GET(err_code));
return err_code;
}
if (m_cb.use_tx)
{
NRFX_ASSERT(p_buffers->p_tx_buffer != NULL);
nrf_i2s_tx_buffer_set(NRF_I2S, p_buffers->p_tx_buffer);
}
if (m_cb.use_rx)
{
NRFX_ASSERT(p_buffers->p_rx_buffer != NULL);
nrf_i2s_rx_buffer_set(NRF_I2S, p_buffers->p_rx_buffer);
}
m_cb.next_buffers = *p_buffers;
m_cb.buffers_needed = false;
return NRFX_SUCCESS;
}
void nrfx_i2s_stop(void)
{
NRFX_ASSERT(m_cb.state != NRFX_DRV_STATE_UNINITIALIZED);
m_cb.buffers_needed = false;
// First disable interrupts, then trigger the STOP task, so no spurious
// RXPTRUPD and TXPTRUPD events (see nRF52 anomaly 55) are processed.
nrf_i2s_int_disable(NRF_I2S, NRF_I2S_INT_RXPTRUPD_MASK |
NRF_I2S_INT_TXPTRUPD_MASK);
nrf_i2s_task_trigger(NRF_I2S, NRF_I2S_TASK_STOP);
#if NRFX_CHECK(USE_WORKAROUND_FOR_I2S_STOP_ANOMALY)
*((volatile uint32_t *)(((uint32_t)NRF_I2S) + 0x38)) = 1;
*((volatile uint32_t *)(((uint32_t)NRF_I2S) + 0x3C)) = 1;
#endif
}
void nrfx_i2s_irq_handler(void)
{
if (nrf_i2s_event_check(NRF_I2S, NRF_I2S_EVENT_TXPTRUPD))
{
nrf_i2s_event_clear(NRF_I2S, NRF_I2S_EVENT_TXPTRUPD);
m_cb.tx_ready = true;
if (m_cb.use_tx && m_cb.buffers_needed)
{
m_cb.buffers_reused = true;
}
}
if (nrf_i2s_event_check(NRF_I2S, NRF_I2S_EVENT_RXPTRUPD))
{
nrf_i2s_event_clear(NRF_I2S, NRF_I2S_EVENT_RXPTRUPD);
m_cb.rx_ready = true;
if (m_cb.use_rx && m_cb.buffers_needed)
{
m_cb.buffers_reused = true;
}
}
if (nrf_i2s_event_check(NRF_I2S, NRF_I2S_EVENT_STOPPED))
{
nrf_i2s_event_clear(NRF_I2S, NRF_I2S_EVENT_STOPPED);
nrf_i2s_int_disable(NRF_I2S, NRF_I2S_INT_STOPPED_MASK);
nrf_i2s_disable(NRF_I2S);
// When stopped, release all buffers, including these scheduled for
// the next transfer.
m_cb.handler(&m_cb.current_buffers, 0);
m_cb.handler(&m_cb.next_buffers, 0);
m_cb.state = NRFX_DRV_STATE_INITIALIZED;
NRFX_LOG_INFO("Stopped.");
}
else
{
// Check if the requested transfer has been completed:
// - full-duplex mode
if ((m_cb.use_tx && m_cb.use_rx && m_cb.tx_ready && m_cb.rx_ready) ||
// - TX only mode
(!m_cb.use_rx && m_cb.tx_ready) ||
// - RX only mode
(!m_cb.use_tx && m_cb.rx_ready))
{
m_cb.tx_ready = false;
m_cb.rx_ready = false;
// If the application did not supply the buffers for the next
// part of the transfer until this moment, the current buffers
// cannot be released, since the I2S peripheral already started
// using them. Signal this situation to the application by
// passing NULL instead of the structure with released buffers.
if (m_cb.buffers_reused)
{
m_cb.buffers_reused = false;
// This will most likely be set at this point. However, there is
// a small time window between TXPTRUPD and RXPTRUPD events,
// and it is theoretically possible that next buffers will be
// set in this window, so to be sure this flag is set to true,
// set it explicitly.
m_cb.buffers_needed = true;
m_cb.handler(NULL,
NRFX_I2S_STATUS_NEXT_BUFFERS_NEEDED);
}
else
{
// Buffers that have been used by the I2S peripheral (current)
// are now released and will be returned to the application,
// and the ones scheduled to be used as next become the current
// ones.
nrfx_i2s_buffers_t released_buffers = m_cb.current_buffers;
m_cb.current_buffers = m_cb.next_buffers;
m_cb.next_buffers.p_rx_buffer = NULL;
m_cb.next_buffers.p_tx_buffer = NULL;
m_cb.buffers_needed = true;
m_cb.handler(&released_buffers,
NRFX_I2S_STATUS_NEXT_BUFFERS_NEEDED);
}
}
}
}
#endif // NRFX_CHECK(NRFX_I2S_ENABLED)
| mit |
shinpei0208/gdev | mod/linux/pscnv/pscnv_sysram.c | 3 | 2120 | #include "drmP.h"
#include "drm.h"
#include "nouveau_drv.h"
#include "pscnv_mem.h"
#include <linux/list.h>
#include <linux/kernel.h>
#include <linux/mutex.h>
#include <linux/gfp.h>
int
pscnv_sysram_alloc(struct pscnv_bo *bo)
{
int numpages, i, j;
gfp_t gfp_flags;
numpages = bo->size >> PAGE_SHIFT;
if (numpages > 1 && bo->flags & PSCNV_GEM_CONTIG)
return -EINVAL;
bo->pages = kmalloc(numpages * sizeof *bo->pages, GFP_KERNEL);
if (!bo->pages)
return -ENOMEM;
bo->dmapages = kmalloc(numpages * sizeof *bo->dmapages, GFP_KERNEL);
if (!bo->dmapages) {
kfree(bo->pages);
return -ENOMEM;
}
if (bo->dev->pdev->dma_mask > 0xffffffff)
gfp_flags = GFP_KERNEL;
else
gfp_flags = GFP_DMA32;
for (i = 0; i < numpages; i++) {
bo->pages[i] = alloc_pages(gfp_flags, 0);
if (!bo->pages[i]) {
for (j = 0; j < i; j++)
put_page(bo->pages[j]);
kfree(bo->pages);
kfree(bo->dmapages);
return -ENOMEM;
}
}
for (i = 0; i < numpages; i++) {
bo->dmapages[i] = pci_map_page(bo->dev->pdev, bo->pages[i], 0, PAGE_SIZE, PCI_DMA_BIDIRECTIONAL);
if (pci_dma_mapping_error(bo->dev->pdev, bo->dmapages[i])) {
for (j = 0; j < i; j++)
pci_unmap_page(bo->dev->pdev, bo->dmapages[j], PAGE_SIZE, PCI_DMA_BIDIRECTIONAL);
for (j = 0; j < numpages; j++)
put_page(bo->pages[j]);
kfree(bo->pages);
kfree(bo->dmapages);
return -ENOMEM;
}
}
return 0;
}
int
pscnv_sysram_free(struct pscnv_bo *bo)
{
int numpages, i;
numpages = bo->size >> PAGE_SHIFT;
for (i = 0; i < numpages; i++)
pci_unmap_page(bo->dev->pdev, bo->dmapages[i], PAGE_SIZE, PCI_DMA_BIDIRECTIONAL);
for (i = 0; i < numpages; i++)
put_page(bo->pages[i]);
kfree(bo->pages);
kfree(bo->dmapages);
return 0;
}
extern int pscnv_sysram_vm_fault(struct vm_area_struct *vma, struct vm_fault *vmf)
{
struct drm_gem_object *obj = vma->vm_private_data;
struct pscnv_bo *bo = obj->driver_private;
uint64_t offset = (uint64_t)vmf->virtual_address - vma->vm_start;
struct page *res;
if (offset > bo->size)
return VM_FAULT_SIGBUS;
res = bo->pages[offset >> PAGE_SHIFT];
get_page(res);
vmf->page = res;
return 0;
}
| mit |
igui/RPSolver | Gui/gui/docks/SceneDock.cpp | 3 | 1402 | /*
* Copyright (c) 2013 Opposite Renderer
* For the full copyright and license information, please view the LICENSE.txt
* file that was distributed with this source code.
*/
#include "SceneDock.hxx"
#include "ui/ui_SceneDock.h"
#include <QMessageBox>
#include "scene/SceneManager.hxx"
SceneDock::SceneDock(QWidget *parent, SceneManager & sceneManager) :
QDockWidget(parent),
m_sceneManager(sceneManager),
ui(new Ui::SceneDock)
{
ui->setupUi(this);
this->setFeatures(QDockWidget::DockWidgetFloatable|QDockWidget::DockWidgetMovable);
this->setAllowedAreas(Qt::LeftDockWidgetArea|Qt::RightDockWidgetArea);
connect(&sceneManager, SIGNAL(sceneUpdated()), this, SLOT(onSceneUpdated()));
connect(&sceneManager, SIGNAL(sceneLoadingNew()), this, SLOT(onSceneLoadingNew()));
connect(&sceneManager, SIGNAL(sceneLoadError(QString)), this, SLOT(onSceneUpdated()));
onSceneUpdated();
}
SceneDock::~SceneDock()
{
delete ui;
}
void SceneDock::onSceneUpdated()
{
if(m_sceneManager.getScene() != NULL)
{
ui->sceneNameLabel->setText(QString(m_sceneManager.getScene()->getSceneName()));
ui->numTrianglesLabel->setText(QString::number(m_sceneManager.getScene()->getNumTriangles()));
}
}
void SceneDock::onSceneLoadingNew()
{
ui->sceneNameLabel->setText(QString("Loading new scene..."));
ui->numTrianglesLabel->setText(QString(""));
}
| mit |
yihuang/pyccv | deps/ccv/lib/ccv_cache.c | 5 | 12658 | #include "ccv.h"
#include "ccv_internal.h"
#define CCV_GET_CACHE_TYPE(x) ((x) >> 60)
#define CCV_GET_TERMINAL_AGE(x) (((x) >> 32) & 0x0FFFFFFF)
#define CCV_GET_TERMINAL_SIZE(x) ((x) & 0xFFFFFFFF)
#define CCV_SET_TERMINAL_TYPE(x, y, z) (((uint64_t)(x) << 60) | ((uint64_t)(y) << 32) | (z))
void ccv_cache_init(ccv_cache_t* cache, size_t up, int cache_types, ccv_cache_index_free_f ffree, ...)
{
cache->rnum = 0;
cache->age = 0;
cache->up = up;
cache->size = 0;
assert(cache_types > 0 && cache_types <= 16);
va_list arguments;
va_start(arguments, ffree);
int i;
cache->ffree[0] = ffree;
for (i = 1; i < cache_types; i++)
cache->ffree[i] = va_arg(arguments, ccv_cache_index_free_f);
va_end(arguments);
memset(&cache->origin, 0, sizeof(ccv_cache_index_t));
}
static int bits_in_16bits[0x1u << 16];
static int bits_in_16bits_init = 0;
static int sparse_bitcount(unsigned int n) {
int count = 0;
while (n) {
count++;
n &= (n - 1);
}
return count;
}
static void precomputed_16bits() {
int i;
for (i = 0; i < (0x1u << 16); i++)
bits_in_16bits[i] = sparse_bitcount(i);
bits_in_16bits_init = 1;
}
static uint32_t compute_bits(uint64_t m) {
return (bits_in_16bits[m & 0xffff] + bits_in_16bits[(m >> 16) & 0xffff] +
bits_in_16bits[(m >> 32) & 0xffff] + bits_in_16bits[(m >> 48) & 0xffff]);
}
/* update age along a path in the radix tree */
static void _ccv_cache_aging(ccv_cache_index_t* branch, uint64_t sign)
{
if (!bits_in_16bits_init)
precomputed_16bits();
int i;
uint64_t j = 63;
ccv_cache_index_t* breadcrumb[10];
for (i = 0; i < 10; i++)
{
breadcrumb[i] = branch;
int leaf = branch->terminal.off & 0x1;
int full = branch->terminal.off & 0x2;
if (leaf)
{
break;
} else {
ccv_cache_index_t* set = (ccv_cache_index_t*)(branch->branch.set - (branch->branch.set & 0x3));
int dice = (sign & j) >> (i * 6);
if (full)
{
branch = set + dice;
} else {
uint64_t k = 1;
k = k << dice;
if (k & branch->branch.bitmap) {
uint64_t m = (k - 1) & branch->branch.bitmap;
branch = set + compute_bits(m);
} else {
break;
}
}
j <<= 6;
}
}
assert(i < 10);
for (; i >= 0; i--)
{
branch = breadcrumb[i];
int leaf = branch->terminal.off & 0x1;
if (!leaf)
{
ccv_cache_index_t* set = (ccv_cache_index_t*)(branch->branch.set - (branch->branch.set & 0x3));
uint32_t total = compute_bits(branch->branch.bitmap);
uint32_t min_age = (set[0].terminal.off & 0x1) ? CCV_GET_TERMINAL_AGE(set[0].terminal.type) : set[0].branch.age;
for (j = 1; j < total; j++)
{
uint32_t age = (set[j].terminal.off & 0x1) ? CCV_GET_TERMINAL_AGE(set[j].terminal.type) : set[j].branch.age;
if (age < min_age)
min_age = age;
}
branch->branch.age = min_age;
}
}
}
static ccv_cache_index_t* _ccv_cache_seek(ccv_cache_index_t* branch, uint64_t sign, int* depth)
{
if (!bits_in_16bits_init)
precomputed_16bits();
int i;
uint64_t j = 63;
for (i = 0; i < 10; i++)
{
int leaf = branch->terminal.off & 0x1;
int full = branch->terminal.off & 0x2;
if (leaf)
{
if (depth)
*depth = i;
return branch;
} else {
ccv_cache_index_t* set = (ccv_cache_index_t*)(branch->branch.set - (branch->branch.set & 0x3));
int dice = (sign & j) >> (i * 6);
if (full)
{
branch = set + dice;
} else {
uint64_t k = 1;
k = k << dice;
if (k & branch->branch.bitmap) {
uint64_t m = (k - 1) & branch->branch.bitmap;
branch = set + compute_bits(m);
} else {
if (depth)
*depth = i;
return branch;
}
}
j <<= 6;
}
}
return 0;
}
void* ccv_cache_get(ccv_cache_t* cache, uint64_t sign, uint8_t* type)
{
if (cache->rnum == 0)
return 0;
ccv_cache_index_t* branch = _ccv_cache_seek(&cache->origin, sign, 0);
if (!branch)
return 0;
int leaf = branch->terminal.off & 0x1;
if (!leaf)
return 0;
if (branch->terminal.sign != sign)
return 0;
if (type)
*type = CCV_GET_CACHE_TYPE(branch->terminal.type);
return (void*)(branch->terminal.off - (branch->terminal.off & 0x3));
}
// only call this function when the cache space is delpeted
static void _ccv_cache_lru(ccv_cache_t* cache)
{
ccv_cache_index_t* branch = &cache->origin;
int leaf = branch->terminal.off & 0x1;
if (leaf)
{
void* result = (void*)(branch->terminal.off - (branch->terminal.off & 0x3));
uint8_t type = CCV_GET_CACHE_TYPE(branch->terminal.type);
if (result != 0)
{
assert(type >= 0 && type < 16);
cache->ffree[type](result);
}
cache->rnum = 0;
cache->size = 0;
return;
}
uint32_t min_age = branch->branch.age;
int i, j;
for (i = 0; i < 10; i++)
{
ccv_cache_index_t* old_branch = branch;
int leaf = branch->terminal.off & 0x1;
if (leaf)
{
ccv_cache_delete(cache, branch->terminal.sign);
break;
} else {
ccv_cache_index_t* set = (ccv_cache_index_t*)(branch->branch.set - (branch->branch.set & 0x3));
uint32_t total = compute_bits(branch->branch.bitmap);
for (j = 0; j < total; j++)
{
uint32_t age = (set[j].terminal.off & 0x1) ? CCV_GET_TERMINAL_AGE(set[j].terminal.type) : set[j].branch.age;
assert(age >= min_age);
if (age == min_age)
{
branch = set + j;
break;
}
}
assert(old_branch != branch);
}
}
assert(i < 10);
}
static void _ccv_cache_depleted(ccv_cache_t* cache, size_t size)
{
while (cache->size > size)
_ccv_cache_lru(cache);
}
int ccv_cache_put(ccv_cache_t* cache, uint64_t sign, void* x, uint32_t size, uint8_t type)
{
assert(((uint64_t)x & 0x3) == 0);
if (size > cache->up)
return -1;
if (size + cache->size > cache->up)
_ccv_cache_depleted(cache, cache->up - size);
if (cache->rnum == 0)
{
cache->age = 1;
cache->origin.terminal.off = (uint64_t)x | 0x1;
cache->origin.terminal.sign = sign;
cache->origin.terminal.type = CCV_SET_TERMINAL_TYPE(type, cache->age, size);
cache->size = size;
cache->rnum = 1;
return 0;
}
++cache->age;
int i, depth = -1;
ccv_cache_index_t* branch = _ccv_cache_seek(&cache->origin, sign, &depth);
if (!branch)
return -1;
int leaf = branch->terminal.off & 0x1;
uint64_t on = 1;
assert(depth >= 0);
if (leaf)
{
if (sign == branch->terminal.sign)
{
cache->ffree[CCV_GET_CACHE_TYPE(branch->terminal.type)]((void*)(branch->terminal.off - (branch->terminal.off & 0x3)));
branch->terminal.off = (uint64_t)x | 0x1;
uint32_t old_size = CCV_GET_TERMINAL_SIZE(branch->terminal.type);
cache->size = cache->size + size - old_size;
branch->terminal.type = CCV_SET_TERMINAL_TYPE(type, cache->age, size);
_ccv_cache_aging(&cache->origin, sign);
return 1;
} else {
ccv_cache_index_t t = *branch;
uint32_t age = CCV_GET_TERMINAL_AGE(branch->terminal.type);
uint64_t j = 63;
j = j << (depth * 6);
int dice, udice;
assert(depth < 10);
for (i = depth; i < 10; i++)
{
dice = (t.terminal.sign & j) >> (i * 6);
udice = (sign & j) >> (i * 6);
if (dice == udice)
{
branch->branch.bitmap = on << dice;
ccv_cache_index_t* set = (ccv_cache_index_t*)ccmalloc(sizeof(ccv_cache_index_t));
assert(((uint64_t)set & 0x3) == 0);
branch->branch.set = (uint64_t)set;
branch->branch.age = age;
branch = set;
} else {
break;
}
j <<= 6;
}
branch->branch.bitmap = (on << dice) | (on << udice);
ccv_cache_index_t* set = (ccv_cache_index_t*)ccmalloc(sizeof(ccv_cache_index_t) * 2);
assert(((uint64_t)set & 0x3) == 0);
branch->branch.set = (uint64_t)set;
branch->branch.age = age;
int u = dice < udice;
set[u].terminal.sign = sign;
set[u].terminal.off = (uint64_t)x | 0x1;
set[u].terminal.type = CCV_SET_TERMINAL_TYPE(type, cache->age, size);
set[1 - u] = t;
}
} else {
uint64_t k = 1, j = 63;
k = k << ((sign & (j << (depth * 6))) >> (depth * 6));
uint64_t m = (k - 1) & branch->branch.bitmap;
uint32_t start = compute_bits(m);
uint32_t total = compute_bits(branch->branch.bitmap);
ccv_cache_index_t* set = (ccv_cache_index_t*)(branch->branch.set - (branch->branch.set & 0x3));
set = (ccv_cache_index_t*)ccrealloc(set, sizeof(ccv_cache_index_t) * (total + 1));
assert(((uint64_t)set & 0x3) == 0);
for (i = total; i > start; i--)
set[i] = set[i - 1];
set[start].terminal.off = (uint64_t)x | 0x1;
set[start].terminal.sign = sign;
set[start].terminal.type = CCV_SET_TERMINAL_TYPE(type, cache->age, size);
branch->branch.set = (uint64_t)set;
branch->branch.bitmap |= k;
if (total == 63)
branch->branch.set |= 0x2;
}
cache->rnum++;
cache->size += size;
return 0;
}
static void _ccv_cache_cleanup(ccv_cache_index_t* branch)
{
int leaf = branch->terminal.off & 0x1;
if (!leaf)
{
int i;
uint64_t total = compute_bits(branch->branch.bitmap);
ccv_cache_index_t* set = (ccv_cache_index_t*)(branch->branch.set - (branch->branch.set & 0x3));
for (i = 0; i < total; i++)
{
if (!(set[i].terminal.off & 0x1))
_ccv_cache_cleanup(set + i);
}
ccfree(set);
}
}
static void _ccv_cache_cleanup_and_free(ccv_cache_index_t* branch, ccv_cache_index_free_f ffree[])
{
int leaf = branch->terminal.off & 0x1;
if (!leaf)
{
int i;
uint64_t total = compute_bits(branch->branch.bitmap);
ccv_cache_index_t* set = (ccv_cache_index_t*)(branch->branch.set - (branch->branch.set & 0x3));
for (i = 0; i < total; i++)
_ccv_cache_cleanup_and_free(set + i, ffree);
ccfree(set);
} else {
assert(CCV_GET_CACHE_TYPE(branch->terminal.type) >= 0 && CCV_GET_CACHE_TYPE(branch->terminal.type) < 16);
ffree[CCV_GET_CACHE_TYPE(branch->terminal.type)]((void*)(branch->terminal.off - (branch->terminal.off & 0x3)));
}
}
void* ccv_cache_out(ccv_cache_t* cache, uint64_t sign, uint8_t* type)
{
if (!bits_in_16bits_init)
precomputed_16bits();
if (cache->rnum == 0)
return 0;
int i, found = 0, depth = -1;
ccv_cache_index_t* parent = 0;
ccv_cache_index_t* uncle = &cache->origin;
ccv_cache_index_t* branch = &cache->origin;
uint64_t j = 63;
for (i = 0; i < 10; i++)
{
int leaf = branch->terminal.off & 0x1;
int full = branch->terminal.off & 0x2;
if (leaf)
{
found = 1;
break;
}
if (parent != 0 && compute_bits(parent->branch.bitmap) > 1)
uncle = branch;
parent = branch;
depth = i;
ccv_cache_index_t* set = (ccv_cache_index_t*)(branch->branch.set - (branch->branch.set & 0x3));
int dice = (sign & j) >> (i * 6);
if (full)
{
branch = set + dice;
} else {
uint64_t k = 1;
k = k << dice;
if (k & branch->branch.bitmap)
{
uint64_t m = (k - 1) & branch->branch.bitmap;
branch = set + compute_bits(m);
} else {
return 0;
}
}
j <<= 6;
}
if (!found)
return 0;
int leaf = branch->terminal.off & 0x1;
if (!leaf)
return 0;
if (branch->terminal.sign != sign)
return 0;
void* result = (void*)(branch->terminal.off - (branch->terminal.off & 0x3));
if (type)
*type = CCV_GET_CACHE_TYPE(branch->terminal.type);
uint32_t size = CCV_GET_TERMINAL_SIZE(branch->terminal.type);
if (branch != &cache->origin)
{
uint64_t k = 1, j = 63;
int dice = (sign & (j << (depth * 6))) >> (depth * 6);
k = k << dice;
uint64_t m = (k - 1) & parent->branch.bitmap;
uint32_t start = compute_bits(m);
uint32_t total = compute_bits(parent->branch.bitmap);
assert(total > 1);
ccv_cache_index_t* set = (ccv_cache_index_t*)(parent->branch.set - (parent->branch.set & 0x3));
if (total > 2 || (total == 2 && !(set[1 - start].terminal.off & 0x1)))
{
parent->branch.bitmap &= ~k;
for (i = start + 1; i < total; i++)
set[i - 1] = set[i];
set = (ccv_cache_index_t*)ccrealloc(set, sizeof(ccv_cache_index_t) * (total - 1));
parent->branch.set = (uint64_t)set;
} else {
ccv_cache_index_t t = set[1 - start];
_ccv_cache_cleanup(uncle);
*uncle = t;
}
_ccv_cache_aging(&cache->origin, sign);
} else {
// if I only have one item, reset age to 1
cache->age = 1;
}
cache->rnum--;
cache->size -= size;
return result;
}
int ccv_cache_delete(ccv_cache_t* cache, uint64_t sign)
{
uint8_t type = 0;
void* result = ccv_cache_out(cache, sign, &type);
if (result != 0)
{
assert(type >= 0 && type < 16);
cache->ffree[type](result);
return 0;
}
return -1;
}
void ccv_cache_cleanup(ccv_cache_t* cache)
{
if (cache->rnum > 0)
{
_ccv_cache_cleanup_and_free(&cache->origin, cache->ffree);
cache->size = 0;
cache->age = 0;
cache->rnum = 0;
memset(&cache->origin, 0, sizeof(ccv_cache_index_t));
}
}
void ccv_cache_close(ccv_cache_t* cache)
{
// for radix-tree based cache, close/cleanup are the same (it is not the same for cuckoo based one,
// because for cuckoo based one, it will free up space in close whereas only cleanup space in cleanup
ccv_cache_cleanup(cache);
}
| mit |
steveschnepp/OpenApoc | game/state/battle/battleforces.cpp | 6 | 1426 | #include "game/state/battle/battleforces.h"
#include "game/state/battle/battleunit.h"
#include "library/sp.h"
#include <vector>
namespace OpenApoc
{
BattleForces::BattleForces() : squads(6){};
bool BattleForces::insert(unsigned squad, sp<BattleUnit> unit)
{
if (squads[squad].getNumUnits() == 6 && unit->squadNumber != (int)squad)
return false;
return insertAt(squad, squads[squad].getNumUnits(), unit);
}
bool BattleForces::insertAt(unsigned squad, unsigned position, sp<BattleUnit> unit)
{
if (squads[squad].getNumUnits() == 6 && unit->squadNumber != (int)squad)
{
return false;
}
if (unit->squadNumber != -1)
{
removeAt(unit->squadNumber, unit->squadPosition);
}
if (position > squads[squad].units.size())
{
position = (unsigned)squads[squad].units.size();
}
squads[squad].units.insert(squads[squad].units.begin() + position, unit);
unit->squadNumber = squad;
for (int i = 0; i < squads[squad].getNumUnits(); i++)
{
squads[squad].units[i]->squadPosition = i;
}
return true;
}
void BattleForces::removeAt(unsigned squad, unsigned position)
{
squads[squad].units[position]->squadNumber = -1;
squads[squad].units.erase(squads[squad].units.begin() + position);
for (unsigned int i = 0; i < squads[squad].units.size(); i++)
{
squads[squad].units[i]->squadPosition = i;
}
}
BattleSquad::BattleSquad(){};
int BattleSquad::getNumUnits() { return (int)units.size(); }
} // namespace OpenApoc | mit |
kmalakoff/phonegap-couchbase-xplatform | phonegap-couchbase-ios/phonegap-couchbase-ios/Vendor/TouchFoundation_MinimalExtraction/Base64Transcoder.c | 6 | 9593 | //
// Base64Transcoder.c
// TouchCode
//
// Created by Jonathan Wight on Tue Mar 18 2003.
// Copyright 2003 toxicsoftware.com. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
//
#include "Base64Transcoder.h"
#include <math.h>
#include <string.h>
const u_int8_t kBase64EncodeTable[64] = {
/* 0 */ 'A', /* 1 */ 'B', /* 2 */ 'C', /* 3 */ 'D',
/* 4 */ 'E', /* 5 */ 'F', /* 6 */ 'G', /* 7 */ 'H',
/* 8 */ 'I', /* 9 */ 'J', /* 10 */ 'K', /* 11 */ 'L',
/* 12 */ 'M', /* 13 */ 'N', /* 14 */ 'O', /* 15 */ 'P',
/* 16 */ 'Q', /* 17 */ 'R', /* 18 */ 'S', /* 19 */ 'T',
/* 20 */ 'U', /* 21 */ 'V', /* 22 */ 'W', /* 23 */ 'X',
/* 24 */ 'Y', /* 25 */ 'Z', /* 26 */ 'a', /* 27 */ 'b',
/* 28 */ 'c', /* 29 */ 'd', /* 30 */ 'e', /* 31 */ 'f',
/* 32 */ 'g', /* 33 */ 'h', /* 34 */ 'i', /* 35 */ 'j',
/* 36 */ 'k', /* 37 */ 'l', /* 38 */ 'm', /* 39 */ 'n',
/* 40 */ 'o', /* 41 */ 'p', /* 42 */ 'q', /* 43 */ 'r',
/* 44 */ 's', /* 45 */ 't', /* 46 */ 'u', /* 47 */ 'v',
/* 48 */ 'w', /* 49 */ 'x', /* 50 */ 'y', /* 51 */ 'z',
/* 52 */ '0', /* 53 */ '1', /* 54 */ '2', /* 55 */ '3',
/* 56 */ '4', /* 57 */ '5', /* 58 */ '6', /* 59 */ '7',
/* 60 */ '8', /* 61 */ '9', /* 62 */ '+', /* 63 */ '/'
};
/*
-1 = Base64 end of data marker.
-2 = White space (tabs, cr, lf, space)
-3 = Noise (all non whitespace, non-base64 characters)
-4 = Dangerous noise
-5 = Illegal noise (null byte)
*/
const int8_t kBase64DecodeTable[128] = {
/* 0x00 */ -5, /* 0x01 */ -3, /* 0x02 */ -3, /* 0x03 */ -3,
/* 0x04 */ -3, /* 0x05 */ -3, /* 0x06 */ -3, /* 0x07 */ -3,
/* 0x08 */ -3, /* 0x09 */ -2, /* 0x0a */ -2, /* 0x0b */ -2,
/* 0x0c */ -2, /* 0x0d */ -2, /* 0x0e */ -3, /* 0x0f */ -3,
/* 0x10 */ -3, /* 0x11 */ -3, /* 0x12 */ -3, /* 0x13 */ -3,
/* 0x14 */ -3, /* 0x15 */ -3, /* 0x16 */ -3, /* 0x17 */ -3,
/* 0x18 */ -3, /* 0x19 */ -3, /* 0x1a */ -3, /* 0x1b */ -3,
/* 0x1c */ -3, /* 0x1d */ -3, /* 0x1e */ -3, /* 0x1f */ -3,
/* ' ' */ -2, /* '!' */ -3, /* '"' */ -3, /* '#' */ -3,
/* '$' */ -3, /* '%' */ -3, /* '&' */ -3, /* ''' */ -3,
/* '(' */ -3, /* ')' */ -3, /* '*' */ -3, /* '+' */ 62,
/* ',' */ -3, /* '-' */ -3, /* '.' */ -3, /* '/' */ 63,
/* '0' */ 52, /* '1' */ 53, /* '2' */ 54, /* '3' */ 55,
/* '4' */ 56, /* '5' */ 57, /* '6' */ 58, /* '7' */ 59,
/* '8' */ 60, /* '9' */ 61, /* ':' */ -3, /* ';' */ -3,
/* '<' */ -3, /* '=' */ -1, /* '>' */ -3, /* '?' */ -3,
/* '@' */ -3, /* 'A' */ 0, /* 'B' */ 1, /* 'C' */ 2,
/* 'D' */ 3, /* 'E' */ 4, /* 'F' */ 5, /* 'G' */ 6,
/* 'H' */ 7, /* 'I' */ 8, /* 'J' */ 9, /* 'K' */ 10,
/* 'L' */ 11, /* 'M' */ 12, /* 'N' */ 13, /* 'O' */ 14,
/* 'P' */ 15, /* 'Q' */ 16, /* 'R' */ 17, /* 'S' */ 18,
/* 'T' */ 19, /* 'U' */ 20, /* 'V' */ 21, /* 'W' */ 22,
/* 'X' */ 23, /* 'Y' */ 24, /* 'Z' */ 25, /* '[' */ -3,
/* '\' */ -3, /* ']' */ -3, /* '^' */ -3, /* '_' */ -3,
/* '`' */ -3, /* 'a' */ 26, /* 'b' */ 27, /* 'c' */ 28,
/* 'd' */ 29, /* 'e' */ 30, /* 'f' */ 31, /* 'g' */ 32,
/* 'h' */ 33, /* 'i' */ 34, /* 'j' */ 35, /* 'k' */ 36,
/* 'l' */ 37, /* 'm' */ 38, /* 'n' */ 39, /* 'o' */ 40,
/* 'p' */ 41, /* 'q' */ 42, /* 'r' */ 43, /* 's' */ 44,
/* 't' */ 45, /* 'u' */ 46, /* 'v' */ 47, /* 'w' */ 48,
/* 'x' */ 49, /* 'y' */ 50, /* 'z' */ 51, /* '{' */ -3,
/* '|' */ -3, /* '}' */ -3, /* '~' */ -3, /* 0x7f */ -3
};
const u_int8_t kBits_00000011 = 0x03;
const u_int8_t kBits_00001111 = 0x0F;
const u_int8_t kBits_00110000 = 0x30;
const u_int8_t kBits_00111100 = 0x3C;
const u_int8_t kBits_00111111 = 0x3F;
const u_int8_t kBits_11000000 = 0xC0;
const u_int8_t kBits_11110000 = 0xF0;
const u_int8_t kBits_11111100 = 0xFC;
size_t EstimateBas64EncodedDataSize(size_t inDataSize, int32_t inFlags)
{
#pragma unused (inFlags)
size_t theEncodedDataSize = (int)ceil(inDataSize / 3.0) * 4;
theEncodedDataSize = theEncodedDataSize / 72 * 74 + theEncodedDataSize % 72 + 1;
return(theEncodedDataSize);
}
size_t EstimateBas64DecodedDataSize(size_t inDataSize, int32_t inFlags)
{
#pragma unused (inFlags)
size_t theDecodedDataSize = (int)ceil(inDataSize / 4.0) * 3;
//theDecodedDataSize = theDecodedDataSize / 72 * 74 + theDecodedDataSize % 72;
return(theDecodedDataSize);
}
bool Base64EncodeData(const void *inInputData, size_t inInputDataSize, char *outOutputData, size_t *ioOutputDataSize, int32_t inFlags)
{
size_t theEncodedDataSize = EstimateBas64EncodedDataSize(inInputDataSize, inFlags);
if (*ioOutputDataSize < theEncodedDataSize)
return(false);
*ioOutputDataSize = theEncodedDataSize;
const u_int8_t *theInPtr = (const u_int8_t *)inInputData;
u_int32_t theInIndex = 0, theOutIndex = 0;
for (; theInIndex < (inInputDataSize / 3) * 3; theInIndex += 3)
{
outOutputData[theOutIndex++] = kBase64EncodeTable[(theInPtr[theInIndex] & kBits_11111100) >> 2];
outOutputData[theOutIndex++] = kBase64EncodeTable[(theInPtr[theInIndex] & kBits_00000011) << 4 | (theInPtr[theInIndex + 1] & kBits_11110000) >> 4];
outOutputData[theOutIndex++] = kBase64EncodeTable[(theInPtr[theInIndex + 1] & kBits_00001111) << 2 | (theInPtr[theInIndex + 2] & kBits_11000000) >> 6];
outOutputData[theOutIndex++] = kBase64EncodeTable[(theInPtr[theInIndex + 2] & kBits_00111111) >> 0];
if (inFlags & Base64Flags_IncludeNewlines && theOutIndex % 74 == 72)
{
outOutputData[theOutIndex++] = '\r';
outOutputData[theOutIndex++] = '\n';
}
}
const size_t theRemainingBytes = inInputDataSize - theInIndex;
if (theRemainingBytes == 1)
{
outOutputData[theOutIndex++] = kBase64EncodeTable[(theInPtr[theInIndex] & kBits_11111100) >> 2];
outOutputData[theOutIndex++] = kBase64EncodeTable[(theInPtr[theInIndex] & kBits_00000011) << 4 | (0 & kBits_11110000) >> 4];
outOutputData[theOutIndex++] = '=';
outOutputData[theOutIndex++] = '=';
if (inFlags & Base64Flags_IncludeNewlines && theOutIndex % 74 == 72)
{
outOutputData[theOutIndex++] = '\r';
outOutputData[theOutIndex++] = '\n';
}
}
else if (theRemainingBytes == 2)
{
outOutputData[theOutIndex++] = kBase64EncodeTable[(theInPtr[theInIndex] & kBits_11111100) >> 2];
outOutputData[theOutIndex++] = kBase64EncodeTable[(theInPtr[theInIndex] & kBits_00000011) << 4 | (theInPtr[theInIndex + 1] & kBits_11110000) >> 4];
outOutputData[theOutIndex++] = kBase64EncodeTable[(theInPtr[theInIndex + 1] & kBits_00001111) << 2 | (0 & kBits_11000000) >> 6];
outOutputData[theOutIndex++] = '=';
if (inFlags & Base64Flags_IncludeNewlines & theOutIndex % 74 == 72)
{
outOutputData[theOutIndex++] = '\r';
outOutputData[theOutIndex++] = '\n';
}
}
outOutputData[theOutIndex] = 0;
return(true);
}
bool Base64DecodeData(const void *inInputData, size_t inInputDataSize, void *ioOutputData, size_t *ioOutputDataSize, int32_t inFlags)
{
memset(ioOutputData, '.', *ioOutputDataSize);
size_t theDecodedDataSize = EstimateBas64DecodedDataSize(inInputDataSize, inFlags);
if (*ioOutputDataSize < theDecodedDataSize)
return(false);
*ioOutputDataSize = 0;
const u_int8_t *theInPtr = (const u_int8_t *)inInputData;
u_int8_t *theOutPtr = (u_int8_t *)ioOutputData;
size_t theInIndex = 0, theOutIndex = 0;
u_int8_t theOutputOctet;
size_t theSequence = 0;
for (; theInIndex < inInputDataSize; )
{
int8_t theSextet = 0;
int8_t theCurrentInputOctet = theInPtr[theInIndex];
theSextet = kBase64DecodeTable[theCurrentInputOctet];
if (theSextet == -1)
break;
while (theSextet == -2)
{
theCurrentInputOctet = theInPtr[++theInIndex];
theSextet = kBase64DecodeTable[theCurrentInputOctet];
}
while (theSextet == -3)
{
theCurrentInputOctet = theInPtr[++theInIndex];
theSextet = kBase64DecodeTable[theCurrentInputOctet];
}
if (theSequence == 0)
{
theOutputOctet = (theSextet >= 0 ? theSextet : 0) << 2 & kBits_11111100;
}
else if (theSequence == 1)
{
theOutputOctet |= (theSextet >- 0 ? theSextet : 0) >> 4 & kBits_00000011;
theOutPtr[theOutIndex++] = theOutputOctet;
}
else if (theSequence == 2)
{
theOutputOctet = (theSextet >= 0 ? theSextet : 0) << 4 & kBits_11110000;
}
else if (theSequence == 3)
{
theOutputOctet |= (theSextet >= 0 ? theSextet : 0) >> 2 & kBits_00001111;
theOutPtr[theOutIndex++] = theOutputOctet;
}
else if (theSequence == 4)
{
theOutputOctet = (theSextet >= 0 ? theSextet : 0) << 6 & kBits_11000000;
}
else if (theSequence == 5)
{
theOutputOctet |= (theSextet >= 0 ? theSextet : 0) >> 0 & kBits_00111111;
theOutPtr[theOutIndex++] = theOutputOctet;
}
theSequence = (theSequence + 1) % 6;
if (theSequence != 2 && theSequence != 4)
theInIndex++;
}
*ioOutputDataSize = theOutIndex;
return(true);
}
| mit |
henriknelson/micropython | ports/nrf/modules/uos/microbitfs.c | 6 | 25412 | /*
* This file is part of the Micro Python project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2016 Mark Shannon
* Copyright (c) 2017 Ayke van Laethem
*
* 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 <string.h>
#include <stdio.h>
#include <sys/stat.h>
#include "microbitfs.h"
#include "drivers/flash.h"
#include "drivers/rng.h"
#include "py/obj.h"
#include "py/stream.h"
#include "py/runtime.h"
#include "extmod/vfs.h"
#if MICROPY_MBFS
#define DEBUG_FILE 0
#if DEBUG_FILE
#define DEBUG(s) printf s
#else
#define DEBUG(s) (void)0
#endif
/** How it works:
* The File System consists of up to MAX_CHUNKS_IN_FILE_SYSTEM chunks of CHUNK_SIZE each,
* plus one spare page which holds persistent configuration data and is used. for bulk erasing.
* The spare page is either the first or the last page and will be switched by a bulk erase.
* The exact number of chunks will depend on the amount of flash available.
*
* Each chunk consists of a one byte marker and a one byte tail
* The marker shows whether this chunk is the start of a file, the midst of a file
* (in which case it refers to the previous chunk in the file) or whether it is UNUSED
* (and erased) or FREED (which means it is unused, but not erased).
* Chunks are selected in a randomised round-robin fashion to even out wear on the flash
* memory as much as possible.
* A file consists of a linked list of chunks. The first chunk in a file contains its name
* as well as the end chunk and offset.
* Files are found by linear search of the chunks, this means that no meta-data needs to be stored
* outside of the file, which prevents wear hot-spots. Since there are fewer than 250 chunks,
* the search is fast enough.
*
* Chunks are numbered from 1 as we need to reserve 0 as the FREED marker.
*
* Writing to files relies on the persistent API which is high-level wrapper on top of the Nordic SDK.
*/
#define CHUNK_SIZE (1<<MBFS_LOG_CHUNK_SIZE)
#define DATA_PER_CHUNK (CHUNK_SIZE-2)
#define UNUSED_CHUNK 255
#define FREED_CHUNK 0
#define FILE_START 254
#define PERSISTENT_DATA_MARKER 253
/** Must be such that sizeof(file_header) < DATA_PER_CHUNK */
#define MAX_FILENAME_LENGTH 120
//Minimum number of free chunks to justify sweeping.
//If this is too low it may cause excessive wear
#define MIN_CHUNKS_FOR_SWEEP (FLASH_PAGESIZE / CHUNK_SIZE)
#define FILE_NOT_FOUND ((uint8_t)-1)
/** Maximum number of chunks allowed in filesystem. 252 chunks is 31.5kB */
#define MAX_CHUNKS_IN_FILE_SYSTEM 252
#define STATIC_ASSERT(e) extern char static_assert_failed[(e) ? 1 : -1]
typedef struct _file_descriptor_obj {
mp_obj_base_t base;
uint8_t start_chunk;
uint8_t seek_chunk;
uint8_t seek_offset;
bool writable;
bool open;
bool binary;
} file_descriptor_obj;
typedef struct _file_header {
uint8_t end_offset;
uint8_t name_len;
char filename[MAX_FILENAME_LENGTH];
} file_header;
typedef struct _file_chunk {
uint8_t marker;
union {
char data[DATA_PER_CHUNK];
file_header header;
};
uint8_t next_chunk;
} file_chunk;
typedef struct _persistent_config_t {
// Must start with a marker, so that we can identify it.
uint8_t marker; // Should always be PERSISTENT_DATA_MARKER
} persistent_config_t;
extern const mp_obj_type_t uos_mbfs_fileio_type;
extern const mp_obj_type_t uos_mbfs_textio_type;
// Page indexes count down from the end of ROM.
STATIC uint8_t first_page_index;
STATIC uint8_t last_page_index;
// The number of useable chunks in the file system.
STATIC uint8_t chunks_in_file_system;
// Index of chunk to start searches. This is randomised to even out wear.
STATIC uint8_t start_index;
STATIC file_chunk *file_system_chunks;
// Defined by the linker
extern byte _fs_start[];
extern byte _fs_end[];
STATIC_ASSERT((sizeof(file_chunk) == CHUNK_SIZE));
// From micro:bit memory.h
STATIC inline byte *rounddown(byte *addr, uint32_t align) {
return (byte*)(((uint32_t)addr)&(-align));
}
// From micro:bit memory.h
STATIC inline byte *roundup(byte *addr, uint32_t align) {
return (byte*)((((uint32_t)addr)+align-1)&(-align));
}
STATIC inline void *first_page(void) {
return _fs_end - FLASH_PAGESIZE * first_page_index;
}
STATIC inline void *last_page(void) {
return _fs_end - FLASH_PAGESIZE * last_page_index;
}
STATIC void init_limits(void) {
// First determine where to end
byte *end = _fs_end;
end = rounddown(end, FLASH_PAGESIZE)-FLASH_PAGESIZE;
last_page_index = (_fs_end - end)/FLASH_PAGESIZE;
// Now find the start
byte *start = roundup(end - CHUNK_SIZE*MAX_CHUNKS_IN_FILE_SYSTEM, FLASH_PAGESIZE);
while (start < _fs_start) {
start += FLASH_PAGESIZE;
}
first_page_index = (_fs_end - start)/FLASH_PAGESIZE;
chunks_in_file_system = (end-start)>>MBFS_LOG_CHUNK_SIZE;
}
STATIC void randomise_start_index(void) {
start_index = rng_generate_random_word() % chunks_in_file_system + 1;
}
void microbit_filesystem_init(void) {
init_limits();
randomise_start_index();
file_chunk *base = first_page();
if (base->marker == PERSISTENT_DATA_MARKER) {
file_system_chunks = &base[(FLASH_PAGESIZE>>MBFS_LOG_CHUNK_SIZE)-1];
} else if (((file_chunk *)last_page())->marker == PERSISTENT_DATA_MARKER) {
file_system_chunks = &base[-1];
} else {
flash_write_byte((uint32_t)&((file_chunk *)last_page())->marker, PERSISTENT_DATA_MARKER);
file_system_chunks = &base[-1];
}
}
STATIC void copy_page(void *dest, void *src) {
DEBUG(("FILE DEBUG: Copying page from %lx to %lx.\r\n", (uint32_t)src, (uint32_t)dest));
flash_page_erase((uint32_t)dest);
file_chunk *src_chunk = src;
file_chunk *dest_chunk = dest;
uint32_t chunks = FLASH_PAGESIZE>>MBFS_LOG_CHUNK_SIZE;
for (uint32_t i = 0; i < chunks; i++) {
if (src_chunk[i].marker != FREED_CHUNK) {
flash_write_bytes((uint32_t)&dest_chunk[i], (uint8_t*)&src_chunk[i], CHUNK_SIZE);
}
}
}
// Move entire file system up or down one page, copying all used chunks
// Freed chunks are not copied, so become erased.
// There should be no erased chunks before the sweep (or it would be unnecessary)
// but if there are this should work correctly.
//
// The direction of the sweep depends on whether the persistent data is in the first or last page
// The persistent data is copied to RAM, leaving its page unused.
// Then all the pages are copied, one by one, into the adjacent newly unused page.
// Finally, the persistent data is saved back to the opposite end of the filesystem from whence it came.
//
STATIC void filesystem_sweep(void) {
persistent_config_t config;
uint8_t *page;
uint8_t *end_page;
int step;
uint32_t page_size = FLASH_PAGESIZE;
DEBUG(("FILE DEBUG: Sweeping file system\r\n"));
if (((file_chunk *)first_page())->marker == PERSISTENT_DATA_MARKER) {
config = *(persistent_config_t *)first_page();
page = first_page();
end_page = last_page();
step = page_size;
} else {
config = *(persistent_config_t *)last_page();
page = last_page();
end_page = first_page();
step = -page_size;
}
while (page != end_page) {
uint8_t *next_page = page+step;
flash_page_erase((uint32_t)page);
copy_page(page, next_page);
page = next_page;
}
flash_page_erase((uint32_t)end_page);
flash_write_bytes((uint32_t)end_page, (uint8_t*)&config, sizeof(config));
microbit_filesystem_init();
}
STATIC inline byte *seek_address(file_descriptor_obj *self) {
return (byte*)&(file_system_chunks[self->seek_chunk].data[self->seek_offset]);
}
STATIC uint8_t microbit_find_file(const char *name, int name_len) {
for (uint8_t index = 1; index <= chunks_in_file_system; index++) {
const file_chunk *p = &file_system_chunks[index];
if (p->marker != FILE_START)
continue;
if (p->header.name_len != name_len)
continue;
if (memcmp(name, &p->header.filename[0], name_len) == 0) {
DEBUG(("FILE DEBUG: File found. index %d\r\n", index));
return index;
}
}
DEBUG(("FILE DEBUG: File not found.\r\n"));
return FILE_NOT_FOUND;
}
// Return a free, erased chunk.
// Search the chunks:
// 1 If an UNUSED chunk is found, then return that.
// 2. If an entire page of FREED chunks is found, then erase the page and return the first chunk
// 3. If the number of FREED chunks is >= MIN_CHUNKS_FOR_SWEEP, then
// 3a. Sweep the filesystem and restart.
// 3b. Fail and return FILE_NOT_FOUND
//
STATIC uint8_t find_chunk_and_erase(void) {
// Start search at a random chunk to spread the wear more evenly.
// Search for unused chunk
uint8_t index = start_index;
do {
const file_chunk *p = &file_system_chunks[index];
if (p->marker == UNUSED_CHUNK) {
DEBUG(("FILE DEBUG: Unused chunk found: %d\r\n", index));
return index;
}
index++;
if (index == chunks_in_file_system+1) index = 1;
} while (index != start_index);
// Search for FREED page, and total up FREED chunks
uint32_t freed_chunks = 0;
index = start_index;
uint32_t chunks_per_page = FLASH_PAGESIZE>>MBFS_LOG_CHUNK_SIZE;
do {
const file_chunk *p = &file_system_chunks[index];
if (p->marker == FREED_CHUNK) {
freed_chunks++;
}
if (FLASH_IS_PAGE_ALIGNED(p)) {
uint32_t i;
for (i = 0; i < chunks_per_page; i++) {
if (p[i].marker != FREED_CHUNK)
break;
}
if (i == chunks_per_page) {
DEBUG(("FILE DEBUG: Found freed page of chunks: %d\r\n", index));
flash_page_erase((uint32_t)&file_system_chunks[index]);
return index;
}
}
index++;
if (index == chunks_in_file_system+1) index = 1;
} while (index != start_index);
DEBUG(("FILE DEBUG: %lu free chunks\r\n", freed_chunks));
if (freed_chunks < MIN_CHUNKS_FOR_SWEEP) {
return FILE_NOT_FOUND;
}
// No freed pages, so sweep file system.
filesystem_sweep();
// This is guaranteed to succeed.
return find_chunk_and_erase();
}
STATIC mp_obj_t microbit_file_name(file_descriptor_obj *fd) {
return mp_obj_new_str(&(file_system_chunks[fd->start_chunk].header.filename[0]), file_system_chunks[fd->start_chunk].header.name_len);
}
STATIC file_descriptor_obj *microbit_file_descriptor_new(uint8_t start_chunk, bool write, bool binary);
STATIC void clear_file(uint8_t chunk) {
do {
flash_write_byte((uint32_t)&(file_system_chunks[chunk].marker), FREED_CHUNK);
DEBUG(("FILE DEBUG: Freeing chunk %d.\n", chunk));
chunk = file_system_chunks[chunk].next_chunk;
} while (chunk <= chunks_in_file_system);
}
STATIC file_descriptor_obj *microbit_file_open(const char *name, size_t name_len, bool write, bool binary) {
if (name_len > MAX_FILENAME_LENGTH) {
return NULL;
}
uint8_t index = microbit_find_file(name, name_len);
if (write) {
if (index != FILE_NOT_FOUND) {
// Free old file
clear_file(index);
}
index = find_chunk_and_erase();
if (index == FILE_NOT_FOUND) {
mp_raise_OSError(MP_ENOSPC);
}
flash_write_byte((uint32_t)&(file_system_chunks[index].marker), FILE_START);
flash_write_byte((uint32_t)&(file_system_chunks[index].header.name_len), name_len);
flash_write_bytes((uint32_t)&(file_system_chunks[index].header.filename[0]), (uint8_t*)name, name_len);
} else {
if (index == FILE_NOT_FOUND) {
return NULL;
}
}
return microbit_file_descriptor_new(index, write, binary);
}
STATIC file_descriptor_obj *microbit_file_descriptor_new(uint8_t start_chunk, bool write, bool binary) {
file_descriptor_obj *res = m_new_obj(file_descriptor_obj);
if (binary) {
res->base.type = &uos_mbfs_fileio_type;
} else {
res->base.type = &uos_mbfs_textio_type;
}
res->start_chunk = start_chunk;
res->seek_chunk = start_chunk;
res->seek_offset = file_system_chunks[start_chunk].header.name_len+2;
res->writable = write;
res->open = true;
res->binary = binary;
return res;
}
STATIC mp_obj_t microbit_remove(mp_obj_t filename) {
size_t name_len;
const char *name = mp_obj_str_get_data(filename, &name_len);
mp_uint_t index = microbit_find_file(name, name_len);
if (index == 255) {
mp_raise_OSError(MP_ENOENT);
}
clear_file(index);
return mp_const_none;
}
STATIC void check_file_open(file_descriptor_obj *self) {
if (!self->open) {
mp_raise_ValueError(MP_ERROR_TEXT("I/O operation on closed file"));
}
}
STATIC int advance(file_descriptor_obj *self, uint32_t n, bool write) {
DEBUG(("FILE DEBUG: Advancing from chunk %d, offset %d.\r\n", self->seek_chunk, self->seek_offset));
self->seek_offset += n;
if (self->seek_offset == DATA_PER_CHUNK) {
self->seek_offset = 0;
if (write) {
uint8_t next_chunk = find_chunk_and_erase();
if (next_chunk == FILE_NOT_FOUND) {
clear_file(self->start_chunk);
self->open = false;
return MP_ENOSPC;
}
// Link next chunk to this one
flash_write_byte((uint32_t)&(file_system_chunks[self->seek_chunk].next_chunk), next_chunk);
flash_write_byte((uint32_t)&(file_system_chunks[next_chunk].marker), self->seek_chunk);
}
self->seek_chunk = file_system_chunks[self->seek_chunk].next_chunk;
}
DEBUG(("FILE DEBUG: Advanced to chunk %d, offset %d.\r\n", self->seek_chunk, self->seek_offset));
return 0;
}
STATIC mp_uint_t microbit_file_read(mp_obj_t obj, void *buf, mp_uint_t size, int *errcode) {
file_descriptor_obj *self = (file_descriptor_obj *)obj;
check_file_open(self);
if (self->writable || file_system_chunks[self->start_chunk].marker == FREED_CHUNK) {
*errcode = MP_EBADF;
return MP_STREAM_ERROR;
}
uint32_t bytes_read = 0;
uint8_t *data = buf;
while (1) {
mp_uint_t to_read = DATA_PER_CHUNK - self->seek_offset;
if (file_system_chunks[self->seek_chunk].next_chunk == UNUSED_CHUNK) {
uint8_t end_offset = file_system_chunks[self->start_chunk].header.end_offset;
if (end_offset == UNUSED_CHUNK) {
to_read = 0;
} else {
to_read = MIN(to_read, (mp_uint_t)end_offset-self->seek_offset);
}
}
to_read = MIN(to_read, size-bytes_read);
if (to_read == 0) {
break;
}
memcpy(data+bytes_read, seek_address(self), to_read);
advance(self, to_read, false);
bytes_read += to_read;
}
return bytes_read;
}
STATIC mp_uint_t microbit_file_write(mp_obj_t obj, const void *buf, mp_uint_t size, int *errcode) {
file_descriptor_obj *self = (file_descriptor_obj *)obj;
check_file_open(self);
if (!self->writable || file_system_chunks[self->start_chunk].marker == FREED_CHUNK) {
*errcode = MP_EBADF;
return MP_STREAM_ERROR;
}
uint32_t len = size;
const uint8_t *data = buf;
while (len) {
uint32_t to_write = MIN(((uint32_t)(DATA_PER_CHUNK - self->seek_offset)), len);
flash_write_bytes((uint32_t)seek_address(self), data, to_write);
int err = advance(self, to_write, true);
if (err) {
*errcode = err;
return MP_STREAM_ERROR;
}
data += to_write;
len -= to_write;
}
return size;
}
STATIC void microbit_file_close(file_descriptor_obj *fd) {
if (fd->writable) {
flash_write_byte((uint32_t)&(file_system_chunks[fd->start_chunk].header.end_offset), fd->seek_offset);
}
fd->open = false;
}
STATIC mp_obj_t microbit_file_list(void) {
mp_obj_t res = mp_obj_new_list(0, NULL);
for (uint8_t index = 1; index <= chunks_in_file_system; index++) {
if (file_system_chunks[index].marker == FILE_START) {
mp_obj_t name = mp_obj_new_str(&file_system_chunks[index].header.filename[0], file_system_chunks[index].header.name_len);
mp_obj_list_append(res, name);
}
}
return res;
}
STATIC mp_obj_t microbit_file_size(mp_obj_t filename) {
size_t name_len;
const char *name = mp_obj_str_get_data(filename, &name_len);
uint8_t chunk = microbit_find_file(name, name_len);
if (chunk == 255) {
mp_raise_OSError(MP_ENOENT);
}
mp_uint_t len = 0;
uint8_t end_offset = file_system_chunks[chunk].header.end_offset;
uint8_t offset = file_system_chunks[chunk].header.name_len+2;
while (file_system_chunks[chunk].next_chunk != UNUSED_CHUNK) {
len += DATA_PER_CHUNK - offset;
chunk = file_system_chunks[chunk].next_chunk;
offset = 0;
}
len += end_offset - offset;
return mp_obj_new_int(len);
}
STATIC mp_uint_t file_read_byte(file_descriptor_obj *fd) {
if (file_system_chunks[fd->seek_chunk].next_chunk == UNUSED_CHUNK) {
uint8_t end_offset = file_system_chunks[fd->start_chunk].header.end_offset;
if (end_offset == UNUSED_CHUNK || fd->seek_offset == end_offset) {
return (mp_uint_t)-1;
}
}
mp_uint_t res = file_system_chunks[fd->seek_chunk].data[fd->seek_offset];
advance(fd, 1, false);
return res;
}
// Now follows the code to integrate this filesystem into the uos module.
mp_lexer_t *uos_mbfs_new_reader(const char *filename) {
file_descriptor_obj *fd = microbit_file_open(filename, strlen(filename), false, false);
if (fd == NULL) {
mp_raise_OSError(MP_ENOENT);
}
mp_reader_t reader;
reader.data = fd;
reader.readbyte = (mp_uint_t(*)(void*))file_read_byte;
reader.close = (void(*)(void*))microbit_file_close; // no-op
return mp_lexer_new(qstr_from_str(filename), reader);
}
mp_import_stat_t uos_mbfs_import_stat(const char *path) {
uint8_t chunk = microbit_find_file(path, strlen(path));
if (chunk == FILE_NOT_FOUND) {
return MP_IMPORT_STAT_NO_EXIST;
} else {
return MP_IMPORT_STAT_FILE;
}
}
STATIC mp_obj_t uos_mbfs_file_name(mp_obj_t self) {
file_descriptor_obj *fd = (file_descriptor_obj*)self;
return microbit_file_name(fd);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(uos_mbfs_file_name_obj, uos_mbfs_file_name);
STATIC mp_obj_t uos_mbfs_file_close(mp_obj_t self) {
file_descriptor_obj *fd = (file_descriptor_obj*)self;
microbit_file_close(fd);
return mp_const_none;
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(uos_mbfs_file_close_obj, uos_mbfs_file_close);
STATIC mp_obj_t uos_mbfs_remove(mp_obj_t name) {
return microbit_remove(name);
}
MP_DEFINE_CONST_FUN_OBJ_1(uos_mbfs_remove_obj, uos_mbfs_remove);
STATIC mp_obj_t uos_mbfs_file___exit__(size_t n_args, const mp_obj_t *args) {
(void)n_args;
return uos_mbfs_file_close(args[0]);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(uos_mbfs_file___exit___obj, 4, 4, uos_mbfs_file___exit__);
typedef struct {
mp_obj_base_t base;
mp_fun_1_t iternext;
uint8_t index;
} uos_mbfs_ilistdir_it_t;
STATIC mp_obj_t uos_mbfs_ilistdir_it_iternext(mp_obj_t self_in) {
uos_mbfs_ilistdir_it_t *self = MP_OBJ_TO_PTR(self_in);
// Read until the next FILE_START chunk.
for (; self->index <= chunks_in_file_system; self->index++) {
if (file_system_chunks[self->index].marker != FILE_START) {
continue;
}
// Get the file name as str object.
mp_obj_t name = mp_obj_new_str(&file_system_chunks[self->index].header.filename[0], file_system_chunks[self->index].header.name_len);
// make 3-tuple with info about this entry
mp_obj_tuple_t *t = MP_OBJ_TO_PTR(mp_obj_new_tuple(3, NULL));
t->items[0] = name;
t->items[1] = MP_OBJ_NEW_SMALL_INT(MP_S_IFREG); // all entries are files
t->items[2] = MP_OBJ_NEW_SMALL_INT(0); // no inode number
self->index++;
return MP_OBJ_FROM_PTR(t);
}
return MP_OBJ_STOP_ITERATION;
}
STATIC mp_obj_t uos_mbfs_ilistdir(void) {
uos_mbfs_ilistdir_it_t *iter = m_new_obj(uos_mbfs_ilistdir_it_t);
iter->base.type = &mp_type_polymorph_iter;
iter->iternext = uos_mbfs_ilistdir_it_iternext;
iter->index = 1;
return MP_OBJ_FROM_PTR(iter);
}
MP_DEFINE_CONST_FUN_OBJ_0(uos_mbfs_ilistdir_obj, uos_mbfs_ilistdir);
MP_DEFINE_CONST_FUN_OBJ_0(uos_mbfs_listdir_obj, microbit_file_list);
STATIC mp_obj_t microbit_file_writable(mp_obj_t self) {
return mp_obj_new_bool(((file_descriptor_obj *)self)->writable);
}
STATIC MP_DEFINE_CONST_FUN_OBJ_1(microbit_file_writable_obj, microbit_file_writable);
STATIC const mp_map_elem_t uos_mbfs_file_locals_dict_table[] = {
{ MP_OBJ_NEW_QSTR(MP_QSTR_close), (mp_obj_t)&uos_mbfs_file_close_obj },
{ MP_OBJ_NEW_QSTR(MP_QSTR_name), (mp_obj_t)&uos_mbfs_file_name_obj },
{ MP_ROM_QSTR(MP_QSTR___enter__), (mp_obj_t)&mp_identity_obj },
{ MP_ROM_QSTR(MP_QSTR___exit__), (mp_obj_t)&uos_mbfs_file___exit___obj },
{ MP_OBJ_NEW_QSTR(MP_QSTR_writable), (mp_obj_t)µbit_file_writable_obj },
/* Stream methods */
{ MP_OBJ_NEW_QSTR(MP_QSTR_read), (mp_obj_t)&mp_stream_read_obj },
{ MP_OBJ_NEW_QSTR(MP_QSTR_readinto), (mp_obj_t)&mp_stream_readinto_obj },
{ MP_OBJ_NEW_QSTR(MP_QSTR_readline), (mp_obj_t)&mp_stream_unbuffered_readline_obj},
{ MP_OBJ_NEW_QSTR(MP_QSTR_write), (mp_obj_t)&mp_stream_write_obj},
};
STATIC MP_DEFINE_CONST_DICT(uos_mbfs_file_locals_dict, uos_mbfs_file_locals_dict_table);
STATIC const mp_stream_p_t textio_stream_p = {
.read = microbit_file_read,
.write = microbit_file_write,
.is_text = true,
};
const mp_obj_type_t uos_mbfs_textio_type = {
{ &mp_type_type },
.name = MP_QSTR_TextIO,
.protocol = &textio_stream_p,
.locals_dict = (mp_obj_dict_t*)&uos_mbfs_file_locals_dict,
};
STATIC const mp_stream_p_t fileio_stream_p = {
.read = microbit_file_read,
.write = microbit_file_write,
};
const mp_obj_type_t uos_mbfs_fileio_type = {
{ &mp_type_type },
.name = MP_QSTR_FileIO,
.protocol = &fileio_stream_p,
.locals_dict = (mp_obj_dict_t*)&uos_mbfs_file_locals_dict,
};
// From micro:bit fileobj.c
mp_obj_t uos_mbfs_open(size_t n_args, const mp_obj_t *args) {
/// -1 means default; 0 explicitly false; 1 explicitly true.
int read = -1;
int text = -1;
if (n_args == 2) {
size_t len;
const char *mode = mp_obj_str_get_data(args[1], &len);
for (mp_uint_t i = 0; i < len; i++) {
if (mode[i] == 'r' || mode[i] == 'w') {
if (read >= 0) {
goto mode_error;
}
read = (mode[i] == 'r');
} else if (mode[i] == 'b' || mode[i] == 't') {
if (text >= 0) {
goto mode_error;
}
text = (mode[i] == 't');
} else {
goto mode_error;
}
}
}
size_t name_len;
const char *filename = mp_obj_str_get_data(args[0], &name_len);
file_descriptor_obj *res = microbit_file_open(filename, name_len, read == 0, text == 0);
if (res == NULL) {
mp_raise_OSError(MP_ENOENT);
}
return res;
mode_error:
mp_raise_ValueError(MP_ERROR_TEXT("illegal mode"));
}
STATIC mp_obj_t uos_mbfs_stat(mp_obj_t filename) {
mp_obj_t file_size = microbit_file_size(filename);
mp_obj_tuple_t *t = MP_OBJ_TO_PTR(mp_obj_new_tuple(10, NULL));
t->items[0] = MP_OBJ_NEW_SMALL_INT(MP_S_IFREG); // st_mode
t->items[1] = MP_OBJ_NEW_SMALL_INT(0); // st_ino
t->items[2] = MP_OBJ_NEW_SMALL_INT(0); // st_dev
t->items[3] = MP_OBJ_NEW_SMALL_INT(0); // st_nlink
t->items[4] = MP_OBJ_NEW_SMALL_INT(0); // st_uid
t->items[5] = MP_OBJ_NEW_SMALL_INT(0); // st_gid
t->items[6] = file_size; // st_size
t->items[7] = MP_OBJ_NEW_SMALL_INT(0); // st_atime
t->items[8] = MP_OBJ_NEW_SMALL_INT(0); // st_mtime
t->items[9] = MP_OBJ_NEW_SMALL_INT(0); // st_ctime
return MP_OBJ_FROM_PTR(t);
}
MP_DEFINE_CONST_FUN_OBJ_1(uos_mbfs_stat_obj, uos_mbfs_stat);
#endif // MICROPY_MBFS
| mit |
hasebems/TouchMIDI32_firmware | bleocarina.cydsn/Generated_Source/PSoC4/I2C_1_sda_PM.c | 7 | 3561 | /*******************************************************************************
* File Name: I2C_1_sda.c
* Version 2.20
*
* Description:
* This file contains APIs to set up the Pins component for low power modes.
*
* Note:
*
********************************************************************************
* Copyright 2015, Cypress Semiconductor Corporation. All rights reserved.
* You may use this file only in accordance with the license, terms, conditions,
* disclaimers, and limitations in the end user license agreement accompanying
* the software package with which this file was provided.
*******************************************************************************/
#include "cytypes.h"
#include "I2C_1_sda.h"
static I2C_1_sda_BACKUP_STRUCT I2C_1_sda_backup = {0u, 0u, 0u};
/*******************************************************************************
* Function Name: I2C_1_sda_Sleep
****************************************************************************//**
*
* \brief Stores the pin configuration and prepares the pin for entering chip
* deep-sleep/hibernate modes. This function must be called for SIO and USBIO
* pins. It is not essential if using GPIO or GPIO_OVT pins.
*
* <b>Note</b> This function is available in PSoC 4 only.
*
* \return
* None
*
* \sideeffect
* For SIO pins, this function configures the pin input threshold to CMOS and
* drive level to Vddio. This is needed for SIO pins when in device
* deep-sleep/hibernate modes.
*
* \funcusage
* \snippet I2C_1_sda_SUT.c usage_I2C_1_sda_Sleep_Wakeup
*******************************************************************************/
void I2C_1_sda_Sleep(void)
{
#if defined(I2C_1_sda__PC)
I2C_1_sda_backup.pcState = I2C_1_sda_PC;
#else
#if (CY_PSOC4_4200L)
/* Save the regulator state and put the PHY into suspend mode */
I2C_1_sda_backup.usbState = I2C_1_sda_CR1_REG;
I2C_1_sda_USB_POWER_REG |= I2C_1_sda_USBIO_ENTER_SLEEP;
I2C_1_sda_CR1_REG &= I2C_1_sda_USBIO_CR1_OFF;
#endif
#endif
#if defined(CYIPBLOCK_m0s8ioss_VERSION) && defined(I2C_1_sda__SIO)
I2C_1_sda_backup.sioState = I2C_1_sda_SIO_REG;
/* SIO requires unregulated output buffer and single ended input buffer */
I2C_1_sda_SIO_REG &= (uint32)(~I2C_1_sda_SIO_LPM_MASK);
#endif
}
/*******************************************************************************
* Function Name: I2C_1_sda_Wakeup
****************************************************************************//**
*
* \brief Restores the pin configuration that was saved during Pin_Sleep().
*
* For USBIO pins, the wakeup is only triggered for falling edge interrupts.
*
* <b>Note</b> This function is available in PSoC 4 only.
*
* \return
* None
*
* \funcusage
* Refer to I2C_1_sda_Sleep() for an example usage.
*******************************************************************************/
void I2C_1_sda_Wakeup(void)
{
#if defined(I2C_1_sda__PC)
I2C_1_sda_PC = I2C_1_sda_backup.pcState;
#else
#if (CY_PSOC4_4200L)
/* Restore the regulator state and come out of suspend mode */
I2C_1_sda_USB_POWER_REG &= I2C_1_sda_USBIO_EXIT_SLEEP_PH1;
I2C_1_sda_CR1_REG = I2C_1_sda_backup.usbState;
I2C_1_sda_USB_POWER_REG &= I2C_1_sda_USBIO_EXIT_SLEEP_PH2;
#endif
#endif
#if defined(CYIPBLOCK_m0s8ioss_VERSION) && defined(I2C_1_sda__SIO)
I2C_1_sda_SIO_REG = I2C_1_sda_backup.sioState;
#endif
}
/* [] END OF FILE */
| mit |
gfneto/Peershares | src/qt/optionsdialog.cpp | 9 | 9842 | #include "optionsdialog.h"
#include "optionsmodel.h"
#include "bitcoinamountfield.h"
#include "monitoreddatamapper.h"
#include "guiutil.h"
#include "bitcoinunits.h"
#include "qvaluecombobox.h"
#include <QHBoxLayout>
#include <QVBoxLayout>
#include <QPushButton>
#include <QListWidget>
#include <QStackedWidget>
#include <QCheckBox>
#include <QLabel>
#include <QLineEdit>
#include <QIntValidator>
#include <QDoubleValidator>
#include <QRegExpValidator>
#include <QDialogButtonBox>
/* First page of options */
class MainOptionsPage : public QWidget
{
Q_OBJECT
public:
explicit MainOptionsPage(QWidget *parent=0);
void setMapper(MonitoredDataMapper *mapper);
private:
QCheckBox *bitcoin_at_startup;
#ifndef Q_WS_MAC
QCheckBox *minimize_to_tray;
#endif
QCheckBox *map_port_upnp;
#ifndef Q_WS_MAC
QCheckBox *minimize_on_close;
#endif
QCheckBox *connect_socks4;
QCheckBox *detach_database;
QLineEdit *proxy_ip;
QLineEdit *proxy_port;
BitcoinAmountField *fee_edit;
signals:
public slots:
};
class DisplayOptionsPage : public QWidget
{
Q_OBJECT
public:
explicit DisplayOptionsPage(QWidget *parent=0);
void setMapper(MonitoredDataMapper *mapper);
private:
QValueComboBox *unit;
QCheckBox *display_addresses;
signals:
public slots:
};
#include "optionsdialog.moc"
OptionsDialog::OptionsDialog(QWidget *parent):
QDialog(parent), contents_widget(0), pages_widget(0),
model(0), main_page(0), display_page(0)
{
contents_widget = new QListWidget();
contents_widget->setMaximumWidth(128);
pages_widget = new QStackedWidget();
pages_widget->setMinimumWidth(300);
QListWidgetItem *item_main = new QListWidgetItem(tr("Main"));
contents_widget->addItem(item_main);
main_page = new MainOptionsPage(this);
pages_widget->addWidget(main_page);
QListWidgetItem *item_display = new QListWidgetItem(tr("Display"));
contents_widget->addItem(item_display);
display_page = new DisplayOptionsPage(this);
pages_widget->addWidget(display_page);
contents_widget->setCurrentRow(0);
QHBoxLayout *main_layout = new QHBoxLayout();
main_layout->addWidget(contents_widget);
main_layout->addWidget(pages_widget, 1);
QVBoxLayout *layout = new QVBoxLayout();
layout->addLayout(main_layout);
QDialogButtonBox *buttonbox = new QDialogButtonBox();
buttonbox->setStandardButtons(QDialogButtonBox::Apply|QDialogButtonBox::Ok|QDialogButtonBox::Cancel);
apply_button = buttonbox->button(QDialogButtonBox::Apply);
layout->addWidget(buttonbox);
setLayout(layout);
setWindowTitle(tr("Options"));
/* Widget-to-option mapper */
mapper = new MonitoredDataMapper(this);
mapper->setSubmitPolicy(QDataWidgetMapper::ManualSubmit);
mapper->setOrientation(Qt::Vertical);
/* enable apply button when data modified */
connect(mapper, SIGNAL(viewModified()), this, SLOT(enableApply()));
/* disable apply button when new data loaded */
connect(mapper, SIGNAL(currentIndexChanged(int)), this, SLOT(disableApply()));
/* Event bindings */
connect(contents_widget, SIGNAL(currentRowChanged(int)), this, SLOT(changePage(int)));
connect(buttonbox->button(QDialogButtonBox::Ok), SIGNAL(clicked()), this, SLOT(okClicked()));
connect(buttonbox->button(QDialogButtonBox::Cancel), SIGNAL(clicked()), this, SLOT(cancelClicked()));
connect(buttonbox->button(QDialogButtonBox::Apply), SIGNAL(clicked()), this, SLOT(applyClicked()));
}
void OptionsDialog::setModel(OptionsModel *model)
{
this->model = model;
mapper->setModel(model);
main_page->setMapper(mapper);
display_page->setMapper(mapper);
mapper->toFirst();
}
void OptionsDialog::changePage(int index)
{
pages_widget->setCurrentIndex(index);
}
void OptionsDialog::okClicked()
{
mapper->submit();
accept();
}
void OptionsDialog::cancelClicked()
{
reject();
}
void OptionsDialog::applyClicked()
{
mapper->submit();
apply_button->setEnabled(false);
}
void OptionsDialog::enableApply()
{
apply_button->setEnabled(true);
}
void OptionsDialog::disableApply()
{
apply_button->setEnabled(false);
}
MainOptionsPage::MainOptionsPage(QWidget *parent):
QWidget(parent)
{
QVBoxLayout *layout = new QVBoxLayout();
bitcoin_at_startup = new QCheckBox(tr("&Start Peershares on system startup"));
bitcoin_at_startup->setToolTip(tr("Automatically start Peershares after the computer is turned on"));
layout->addWidget(bitcoin_at_startup);
#ifndef Q_WS_MAC
minimize_to_tray = new QCheckBox(tr("&Minimize to the tray instead of the taskbar"));
minimize_to_tray->setToolTip(tr("Show only a tray icon after minimizing the window"));
layout->addWidget(minimize_to_tray);
minimize_on_close = new QCheckBox(tr("M&inimize on close"));
minimize_on_close->setToolTip(tr("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."));
layout->addWidget(minimize_on_close);
#endif
map_port_upnp = new QCheckBox(tr("Map port using &UPnP"));
map_port_upnp->setToolTip(tr("Automatically open the Peershares client port on the router. This only works when your router supports UPnP and it is enabled."));
layout->addWidget(map_port_upnp);
connect_socks4 = new QCheckBox(tr("&Connect through SOCKS4 proxy:"));
connect_socks4->setToolTip(tr("Connect to the Peershares network through a SOCKS4 proxy (e.g. when connecting through Tor)"));
layout->addWidget(connect_socks4);
QHBoxLayout *proxy_hbox = new QHBoxLayout();
proxy_hbox->addSpacing(18);
QLabel *proxy_ip_label = new QLabel(tr("Proxy &IP: "));
proxy_hbox->addWidget(proxy_ip_label);
proxy_ip = new QLineEdit();
proxy_ip->setMaximumWidth(140);
proxy_ip->setEnabled(false);
proxy_ip->setValidator(new QRegExpValidator(QRegExp("[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}"), this));
proxy_ip->setToolTip(tr("IP address of the proxy (e.g. 127.0.0.1)"));
proxy_ip_label->setBuddy(proxy_ip);
proxy_hbox->addWidget(proxy_ip);
QLabel *proxy_port_label = new QLabel(tr("&Port: "));
proxy_hbox->addWidget(proxy_port_label);
proxy_port = new QLineEdit();
proxy_port->setMaximumWidth(55);
proxy_port->setValidator(new QIntValidator(0, 65535, this));
proxy_port->setEnabled(false);
proxy_port->setToolTip(tr("Port of the proxy (e.g. 1234)"));
proxy_port_label->setBuddy(proxy_port);
proxy_hbox->addWidget(proxy_port);
proxy_hbox->addStretch(1);
layout->addLayout(proxy_hbox);
QLabel *fee_help = new QLabel(tr("Mandatory network transaction fee per kB transferred. Most transactions are 1 kB and incur a 0.01 share fee. Note: transfer size may increase depending on the number of input transactions totaled to fund the output."));
fee_help->setWordWrap(true);
layout->addWidget(fee_help);
QHBoxLayout *fee_hbox = new QHBoxLayout();
fee_hbox->addSpacing(18);
QLabel *fee_label = new QLabel(tr("Additional network &fee"));
fee_hbox->addWidget(fee_label);
fee_edit = new BitcoinAmountField();
fee_edit->setDisabled(true);
fee_label->setBuddy(fee_edit);
fee_hbox->addWidget(fee_edit);
fee_hbox->addStretch(1);
layout->addLayout(fee_hbox);
detach_database = new QCheckBox(tr("Detach databases at shutdown"));
detach_database->setToolTip(tr("Detach block and address databases at shutdown. This means they can be moved to another data directory, but it slows down shutdown. The wallet is always detached."));
layout->addWidget(detach_database);
layout->addStretch(1); // Extra space at bottom
setLayout(layout);
connect(connect_socks4, SIGNAL(toggled(bool)), proxy_ip, SLOT(setEnabled(bool)));
connect(connect_socks4, SIGNAL(toggled(bool)), proxy_port, SLOT(setEnabled(bool)));
#ifndef USE_UPNP
map_port_upnp->setDisabled(true);
#endif
}
void MainOptionsPage::setMapper(MonitoredDataMapper *mapper)
{
// Map model to widgets
mapper->addMapping(bitcoin_at_startup, OptionsModel::StartAtStartup);
#ifndef Q_WS_MAC
mapper->addMapping(minimize_to_tray, OptionsModel::MinimizeToTray);
#endif
mapper->addMapping(map_port_upnp, OptionsModel::MapPortUPnP);
#ifndef Q_WS_MAC
mapper->addMapping(minimize_on_close, OptionsModel::MinimizeOnClose);
#endif
mapper->addMapping(connect_socks4, OptionsModel::ConnectSOCKS4);
mapper->addMapping(proxy_ip, OptionsModel::ProxyIP);
mapper->addMapping(proxy_port, OptionsModel::ProxyPort);
mapper->addMapping(fee_edit, OptionsModel::Fee);
mapper->addMapping(detach_database, OptionsModel::DetachDatabases);
}
DisplayOptionsPage::DisplayOptionsPage(QWidget *parent):
QWidget(parent)
{
QVBoxLayout *layout = new QVBoxLayout();
QHBoxLayout *unit_hbox = new QHBoxLayout();
unit_hbox->addSpacing(18);
QLabel *unit_label = new QLabel(tr("&Unit to show amounts in: "));
unit_hbox->addWidget(unit_label);
unit = new QValueComboBox(this);
unit->setModel(new BitcoinUnits(this));
unit->setToolTip(tr("Choose the default subdivision unit to show in the interface, and when sending coins"));
unit_label->setBuddy(unit);
unit_hbox->addWidget(unit);
layout->addLayout(unit_hbox);
display_addresses = new QCheckBox(tr("&Display addresses in transaction list"), this);
display_addresses->setToolTip(tr("Whether to show Peershares addresses in the transaction list"));
layout->addWidget(display_addresses);
layout->addStretch();
setLayout(layout);
}
void DisplayOptionsPage::setMapper(MonitoredDataMapper *mapper)
{
mapper->addMapping(unit, OptionsModel::DisplayUnit);
mapper->addMapping(display_addresses, OptionsModel::DisplayAddresses);
}
| mit |
JTriggerFish/protoplug | Frameworks/JuceModules/juce_gui_basics/widgets/juce_TableHeaderComponent.cpp | 9 | 26976 | /*
==============================================================================
This file is part of the JUCE library.
Copyright (c) 2013 - Raw Material Software Ltd.
Permission is granted to use this software under the terms of either:
a) the GPL v2 (or any later version)
b) the Affero GPL v3
Details of these licenses can be found at: www.gnu.org/licenses
JUCE 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 General Public License for more details.
------------------------------------------------------------------------------
To release a closed-source product which uses JUCE, commercial licenses are
available: visit www.juce.com for more information.
==============================================================================
*/
class TableHeaderComponent::DragOverlayComp : public Component
{
public:
DragOverlayComp (const Image& image_)
: image (image_)
{
image.duplicateIfShared();
image.multiplyAllAlphas (0.8f);
setAlwaysOnTop (true);
}
void paint (Graphics& g) override
{
g.drawImageAt (image, 0, 0);
}
private:
Image image;
JUCE_DECLARE_NON_COPYABLE (DragOverlayComp)
};
//==============================================================================
TableHeaderComponent::TableHeaderComponent()
: columnsChanged (false),
columnsResized (false),
sortChanged (false),
menuActive (true),
stretchToFit (false),
columnIdBeingResized (0),
columnIdBeingDragged (0),
columnIdUnderMouse (0),
lastDeliberateWidth (0)
{
}
TableHeaderComponent::~TableHeaderComponent()
{
dragOverlayComp = nullptr;
}
//==============================================================================
void TableHeaderComponent::setPopupMenuActive (const bool hasMenu)
{
menuActive = hasMenu;
}
bool TableHeaderComponent::isPopupMenuActive() const { return menuActive; }
//==============================================================================
int TableHeaderComponent::getNumColumns (const bool onlyCountVisibleColumns) const
{
if (onlyCountVisibleColumns)
{
int num = 0;
for (int i = columns.size(); --i >= 0;)
if (columns.getUnchecked(i)->isVisible())
++num;
return num;
}
return columns.size();
}
String TableHeaderComponent::getColumnName (const int columnId) const
{
if (const ColumnInfo* const ci = getInfoForId (columnId))
return ci->name;
return String::empty;
}
void TableHeaderComponent::setColumnName (const int columnId, const String& newName)
{
if (ColumnInfo* const ci = getInfoForId (columnId))
{
if (ci->name != newName)
{
ci->name = newName;
sendColumnsChanged();
}
}
}
void TableHeaderComponent::addColumn (const String& columnName,
const int columnId,
const int width,
const int minimumWidth,
const int maximumWidth,
const int propertyFlags,
const int insertIndex)
{
// can't have a duplicate or null ID!
jassert (columnId != 0 && getIndexOfColumnId (columnId, false) < 0);
jassert (width > 0);
ColumnInfo* const ci = new ColumnInfo();
ci->name = columnName;
ci->id = columnId;
ci->width = width;
ci->lastDeliberateWidth = width;
ci->minimumWidth = minimumWidth;
ci->maximumWidth = maximumWidth;
if (ci->maximumWidth < 0)
ci->maximumWidth = std::numeric_limits<int>::max();
jassert (ci->maximumWidth >= ci->minimumWidth);
ci->propertyFlags = propertyFlags;
columns.insert (insertIndex, ci);
sendColumnsChanged();
}
void TableHeaderComponent::removeColumn (const int columnIdToRemove)
{
const int index = getIndexOfColumnId (columnIdToRemove, false);
if (index >= 0)
{
columns.remove (index);
sortChanged = true;
sendColumnsChanged();
}
}
void TableHeaderComponent::removeAllColumns()
{
if (columns.size() > 0)
{
columns.clear();
sendColumnsChanged();
}
}
void TableHeaderComponent::moveColumn (const int columnId, int newIndex)
{
const int currentIndex = getIndexOfColumnId (columnId, false);
newIndex = visibleIndexToTotalIndex (newIndex);
if (columns [currentIndex] != 0 && currentIndex != newIndex)
{
columns.move (currentIndex, newIndex);
sendColumnsChanged();
}
}
int TableHeaderComponent::getColumnWidth (const int columnId) const
{
if (const ColumnInfo* const ci = getInfoForId (columnId))
return ci->width;
return 0;
}
void TableHeaderComponent::setColumnWidth (const int columnId, const int newWidth)
{
ColumnInfo* const ci = getInfoForId (columnId);
if (ci != nullptr && ci->width != newWidth)
{
const int numColumns = getNumColumns (true);
ci->lastDeliberateWidth = ci->width
= jlimit (ci->minimumWidth, ci->maximumWidth, newWidth);
if (stretchToFit)
{
const int index = getIndexOfColumnId (columnId, true) + 1;
if (isPositiveAndBelow (index, numColumns))
{
const int x = getColumnPosition (index).getX();
if (lastDeliberateWidth == 0)
lastDeliberateWidth = getTotalWidth();
resizeColumnsToFit (visibleIndexToTotalIndex (index), lastDeliberateWidth - x);
}
}
repaint();
columnsResized = true;
triggerAsyncUpdate();
}
}
//==============================================================================
int TableHeaderComponent::getIndexOfColumnId (const int columnId, const bool onlyCountVisibleColumns) const
{
int n = 0;
for (int i = 0; i < columns.size(); ++i)
{
if ((! onlyCountVisibleColumns) || columns.getUnchecked(i)->isVisible())
{
if (columns.getUnchecked(i)->id == columnId)
return n;
++n;
}
}
return -1;
}
int TableHeaderComponent::getColumnIdOfIndex (int index, const bool onlyCountVisibleColumns) const
{
if (onlyCountVisibleColumns)
index = visibleIndexToTotalIndex (index);
if (const ColumnInfo* const ci = columns [index])
return ci->id;
return 0;
}
Rectangle<int> TableHeaderComponent::getColumnPosition (const int index) const
{
int x = 0, width = 0, n = 0;
for (int i = 0; i < columns.size(); ++i)
{
x += width;
if (columns.getUnchecked(i)->isVisible())
{
width = columns.getUnchecked(i)->width;
if (n++ == index)
break;
}
else
{
width = 0;
}
}
return Rectangle<int> (x, 0, width, getHeight());
}
int TableHeaderComponent::getColumnIdAtX (const int xToFind) const
{
if (xToFind >= 0)
{
int x = 0;
for (int i = 0; i < columns.size(); ++i)
{
const ColumnInfo* const ci = columns.getUnchecked(i);
if (ci->isVisible())
{
x += ci->width;
if (xToFind < x)
return ci->id;
}
}
}
return 0;
}
int TableHeaderComponent::getTotalWidth() const
{
int w = 0;
for (int i = columns.size(); --i >= 0;)
if (columns.getUnchecked(i)->isVisible())
w += columns.getUnchecked(i)->width;
return w;
}
void TableHeaderComponent::setStretchToFitActive (const bool shouldStretchToFit)
{
stretchToFit = shouldStretchToFit;
lastDeliberateWidth = getTotalWidth();
resized();
}
bool TableHeaderComponent::isStretchToFitActive() const
{
return stretchToFit;
}
void TableHeaderComponent::resizeAllColumnsToFit (int targetTotalWidth)
{
if (stretchToFit && getWidth() > 0
&& columnIdBeingResized == 0 && columnIdBeingDragged == 0)
{
lastDeliberateWidth = targetTotalWidth;
resizeColumnsToFit (0, targetTotalWidth);
}
}
void TableHeaderComponent::resizeColumnsToFit (int firstColumnIndex, int targetTotalWidth)
{
targetTotalWidth = jmax (targetTotalWidth, 0);
StretchableObjectResizer sor;
for (int i = firstColumnIndex; i < columns.size(); ++i)
{
ColumnInfo* const ci = columns.getUnchecked(i);
if (ci->isVisible())
sor.addItem (ci->lastDeliberateWidth, ci->minimumWidth, ci->maximumWidth);
}
sor.resizeToFit (targetTotalWidth);
int visIndex = 0;
for (int i = firstColumnIndex; i < columns.size(); ++i)
{
ColumnInfo* const ci = columns.getUnchecked(i);
if (ci->isVisible())
{
const int newWidth = jlimit (ci->minimumWidth, ci->maximumWidth,
(int) std::floor (sor.getItemSize (visIndex++)));
if (newWidth != ci->width)
{
ci->width = newWidth;
repaint();
columnsResized = true;
triggerAsyncUpdate();
}
}
}
}
void TableHeaderComponent::setColumnVisible (const int columnId, const bool shouldBeVisible)
{
if (ColumnInfo* const ci = getInfoForId (columnId))
{
if (shouldBeVisible != ci->isVisible())
{
if (shouldBeVisible)
ci->propertyFlags |= visible;
else
ci->propertyFlags &= ~visible;
sendColumnsChanged();
resized();
}
}
}
bool TableHeaderComponent::isColumnVisible (const int columnId) const
{
const ColumnInfo* const ci = getInfoForId (columnId);
return ci != nullptr && ci->isVisible();
}
//==============================================================================
void TableHeaderComponent::setSortColumnId (const int columnId, const bool sortForwards)
{
if (getSortColumnId() != columnId || isSortedForwards() != sortForwards)
{
for (int i = columns.size(); --i >= 0;)
columns.getUnchecked(i)->propertyFlags &= ~(sortedForwards | sortedBackwards);
if (ColumnInfo* const ci = getInfoForId (columnId))
ci->propertyFlags |= (sortForwards ? sortedForwards : sortedBackwards);
reSortTable();
}
}
int TableHeaderComponent::getSortColumnId() const
{
for (int i = columns.size(); --i >= 0;)
if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
return columns.getUnchecked(i)->id;
return 0;
}
bool TableHeaderComponent::isSortedForwards() const
{
for (int i = columns.size(); --i >= 0;)
if ((columns.getUnchecked(i)->propertyFlags & (sortedForwards | sortedBackwards)) != 0)
return (columns.getUnchecked(i)->propertyFlags & sortedForwards) != 0;
return true;
}
void TableHeaderComponent::reSortTable()
{
sortChanged = true;
repaint();
triggerAsyncUpdate();
}
//==============================================================================
String TableHeaderComponent::toString() const
{
String s;
XmlElement doc ("TABLELAYOUT");
doc.setAttribute ("sortedCol", getSortColumnId());
doc.setAttribute ("sortForwards", isSortedForwards());
for (int i = 0; i < columns.size(); ++i)
{
const ColumnInfo* const ci = columns.getUnchecked (i);
XmlElement* const e = doc.createNewChildElement ("COLUMN");
e->setAttribute ("id", ci->id);
e->setAttribute ("visible", ci->isVisible());
e->setAttribute ("width", ci->width);
}
return doc.createDocument ("", true, false);
}
void TableHeaderComponent::restoreFromString (const String& storedVersion)
{
ScopedPointer <XmlElement> storedXml (XmlDocument::parse (storedVersion));
int index = 0;
if (storedXml != nullptr && storedXml->hasTagName ("TABLELAYOUT"))
{
forEachXmlChildElement (*storedXml, col)
{
const int tabId = col->getIntAttribute ("id");
if (ColumnInfo* const ci = getInfoForId (tabId))
{
columns.move (columns.indexOf (ci), index);
ci->width = col->getIntAttribute ("width");
setColumnVisible (tabId, col->getBoolAttribute ("visible"));
}
++index;
}
columnsResized = true;
sendColumnsChanged();
setSortColumnId (storedXml->getIntAttribute ("sortedCol"),
storedXml->getBoolAttribute ("sortForwards", true));
}
}
//==============================================================================
void TableHeaderComponent::addListener (Listener* const newListener)
{
listeners.addIfNotAlreadyThere (newListener);
}
void TableHeaderComponent::removeListener (Listener* const listenerToRemove)
{
listeners.removeFirstMatchingValue (listenerToRemove);
}
//==============================================================================
void TableHeaderComponent::columnClicked (int columnId, const ModifierKeys& mods)
{
if (const ColumnInfo* const ci = getInfoForId (columnId))
if ((ci->propertyFlags & sortable) != 0 && ! mods.isPopupMenu())
setSortColumnId (columnId, (ci->propertyFlags & sortedForwards) == 0);
}
void TableHeaderComponent::addMenuItems (PopupMenu& menu, const int /*columnIdClicked*/)
{
for (int i = 0; i < columns.size(); ++i)
{
const ColumnInfo* const ci = columns.getUnchecked(i);
if ((ci->propertyFlags & appearsOnColumnMenu) != 0)
menu.addItem (ci->id, ci->name,
(ci->propertyFlags & (sortedForwards | sortedBackwards)) == 0,
isColumnVisible (ci->id));
}
}
void TableHeaderComponent::reactToMenuItem (const int menuReturnId, const int /*columnIdClicked*/)
{
if (getIndexOfColumnId (menuReturnId, false) >= 0)
setColumnVisible (menuReturnId, ! isColumnVisible (menuReturnId));
}
void TableHeaderComponent::paint (Graphics& g)
{
LookAndFeel& lf = getLookAndFeel();
lf.drawTableHeaderBackground (g, *this);
const Rectangle<int> clip (g.getClipBounds());
int x = 0;
for (int i = 0; i < columns.size(); ++i)
{
const ColumnInfo* const ci = columns.getUnchecked(i);
if (ci->isVisible())
{
if (x + ci->width > clip.getX()
&& (ci->id != columnIdBeingDragged
|| dragOverlayComp == nullptr
|| ! dragOverlayComp->isVisible()))
{
Graphics::ScopedSaveState ss (g);
g.setOrigin (x, 0);
g.reduceClipRegion (0, 0, ci->width, getHeight());
lf.drawTableHeaderColumn (g, ci->name, ci->id, ci->width, getHeight(),
ci->id == columnIdUnderMouse,
ci->id == columnIdUnderMouse && isMouseButtonDown(),
ci->propertyFlags);
}
x += ci->width;
if (x >= clip.getRight())
break;
}
}
}
void TableHeaderComponent::resized()
{
}
void TableHeaderComponent::mouseMove (const MouseEvent& e)
{
updateColumnUnderMouse (e);
}
void TableHeaderComponent::mouseEnter (const MouseEvent& e)
{
updateColumnUnderMouse (e);
}
void TableHeaderComponent::mouseExit (const MouseEvent&)
{
setColumnUnderMouse (0);
}
void TableHeaderComponent::mouseDown (const MouseEvent& e)
{
repaint();
columnIdBeingResized = 0;
columnIdBeingDragged = 0;
if (columnIdUnderMouse != 0)
{
draggingColumnOffset = e.x - getColumnPosition (getIndexOfColumnId (columnIdUnderMouse, true)).getX();
if (e.mods.isPopupMenu())
columnClicked (columnIdUnderMouse, e.mods);
}
if (menuActive && e.mods.isPopupMenu())
showColumnChooserMenu (columnIdUnderMouse);
}
void TableHeaderComponent::mouseDrag (const MouseEvent& e)
{
if (columnIdBeingResized == 0
&& columnIdBeingDragged == 0
&& ! (e.mouseWasClicked() || e.mods.isPopupMenu()))
{
dragOverlayComp = nullptr;
columnIdBeingResized = getResizeDraggerAt (e.getMouseDownX());
if (columnIdBeingResized != 0)
{
const ColumnInfo* const ci = getInfoForId (columnIdBeingResized);
initialColumnWidth = ci->width;
}
else
{
beginDrag (e);
}
}
if (columnIdBeingResized != 0)
{
if (const ColumnInfo* const ci = getInfoForId (columnIdBeingResized))
{
int w = jlimit (ci->minimumWidth, ci->maximumWidth,
initialColumnWidth + e.getDistanceFromDragStartX());
if (stretchToFit)
{
// prevent us dragging a column too far right if we're in stretch-to-fit mode
int minWidthOnRight = 0;
for (int i = getIndexOfColumnId (columnIdBeingResized, false) + 1; i < columns.size(); ++i)
if (columns.getUnchecked (i)->isVisible())
minWidthOnRight += columns.getUnchecked (i)->minimumWidth;
const Rectangle<int> currentPos (getColumnPosition (getIndexOfColumnId (columnIdBeingResized, true)));
w = jmax (ci->minimumWidth, jmin (w, lastDeliberateWidth - minWidthOnRight - currentPos.getX()));
}
setColumnWidth (columnIdBeingResized, w);
}
}
else if (columnIdBeingDragged != 0)
{
if (e.y >= -50 && e.y < getHeight() + 50)
{
if (dragOverlayComp != nullptr)
{
dragOverlayComp->setVisible (true);
dragOverlayComp->setBounds (jlimit (0,
jmax (0, getTotalWidth() - dragOverlayComp->getWidth()),
e.x - draggingColumnOffset),
0,
dragOverlayComp->getWidth(),
getHeight());
for (int i = columns.size(); --i >= 0;)
{
const int currentIndex = getIndexOfColumnId (columnIdBeingDragged, true);
int newIndex = currentIndex;
if (newIndex > 0)
{
// if the previous column isn't draggable, we can't move our column
// past it, because that'd change the undraggable column's position..
const ColumnInfo* const previous = columns.getUnchecked (newIndex - 1);
if ((previous->propertyFlags & draggable) != 0)
{
const int leftOfPrevious = getColumnPosition (newIndex - 1).getX();
const int rightOfCurrent = getColumnPosition (newIndex).getRight();
if (abs (dragOverlayComp->getX() - leftOfPrevious)
< abs (dragOverlayComp->getRight() - rightOfCurrent))
{
--newIndex;
}
}
}
if (newIndex < columns.size() - 1)
{
// if the next column isn't draggable, we can't move our column
// past it, because that'd change the undraggable column's position..
const ColumnInfo* const nextCol = columns.getUnchecked (newIndex + 1);
if ((nextCol->propertyFlags & draggable) != 0)
{
const int leftOfCurrent = getColumnPosition (newIndex).getX();
const int rightOfNext = getColumnPosition (newIndex + 1).getRight();
if (abs (dragOverlayComp->getX() - leftOfCurrent)
> abs (dragOverlayComp->getRight() - rightOfNext))
{
++newIndex;
}
}
}
if (newIndex != currentIndex)
moveColumn (columnIdBeingDragged, newIndex);
else
break;
}
}
}
else
{
endDrag (draggingColumnOriginalIndex);
}
}
}
void TableHeaderComponent::beginDrag (const MouseEvent& e)
{
if (columnIdBeingDragged == 0)
{
columnIdBeingDragged = getColumnIdAtX (e.getMouseDownX());
const ColumnInfo* const ci = getInfoForId (columnIdBeingDragged);
if (ci == nullptr || (ci->propertyFlags & draggable) == 0)
{
columnIdBeingDragged = 0;
}
else
{
draggingColumnOriginalIndex = getIndexOfColumnId (columnIdBeingDragged, true);
const Rectangle<int> columnRect (getColumnPosition (draggingColumnOriginalIndex));
const int temp = columnIdBeingDragged;
columnIdBeingDragged = 0;
addAndMakeVisible (dragOverlayComp = new DragOverlayComp (createComponentSnapshot (columnRect, false)));
columnIdBeingDragged = temp;
dragOverlayComp->setBounds (columnRect);
for (int i = listeners.size(); --i >= 0;)
{
listeners.getUnchecked(i)->tableColumnDraggingChanged (this, columnIdBeingDragged);
i = jmin (i, listeners.size() - 1);
}
}
}
}
void TableHeaderComponent::endDrag (const int finalIndex)
{
if (columnIdBeingDragged != 0)
{
moveColumn (columnIdBeingDragged, finalIndex);
columnIdBeingDragged = 0;
repaint();
for (int i = listeners.size(); --i >= 0;)
{
listeners.getUnchecked(i)->tableColumnDraggingChanged (this, 0);
i = jmin (i, listeners.size() - 1);
}
}
}
void TableHeaderComponent::mouseUp (const MouseEvent& e)
{
mouseDrag (e);
for (int i = columns.size(); --i >= 0;)
if (columns.getUnchecked (i)->isVisible())
columns.getUnchecked (i)->lastDeliberateWidth = columns.getUnchecked (i)->width;
columnIdBeingResized = 0;
repaint();
endDrag (getIndexOfColumnId (columnIdBeingDragged, true));
updateColumnUnderMouse (e);
if (columnIdUnderMouse != 0 && e.mouseWasClicked() && ! e.mods.isPopupMenu())
columnClicked (columnIdUnderMouse, e.mods);
dragOverlayComp = nullptr;
}
MouseCursor TableHeaderComponent::getMouseCursor()
{
if (columnIdBeingResized != 0 || (getResizeDraggerAt (getMouseXYRelative().getX()) != 0 && ! isMouseButtonDown()))
return MouseCursor (MouseCursor::LeftRightResizeCursor);
return Component::getMouseCursor();
}
//==============================================================================
bool TableHeaderComponent::ColumnInfo::isVisible() const
{
return (propertyFlags & TableHeaderComponent::visible) != 0;
}
TableHeaderComponent::ColumnInfo* TableHeaderComponent::getInfoForId (const int id) const
{
for (int i = columns.size(); --i >= 0;)
if (columns.getUnchecked(i)->id == id)
return columns.getUnchecked(i);
return nullptr;
}
int TableHeaderComponent::visibleIndexToTotalIndex (const int visibleIndex) const
{
int n = 0;
for (int i = 0; i < columns.size(); ++i)
{
if (columns.getUnchecked(i)->isVisible())
{
if (n == visibleIndex)
return i;
++n;
}
}
return -1;
}
void TableHeaderComponent::sendColumnsChanged()
{
if (stretchToFit && lastDeliberateWidth > 0)
resizeAllColumnsToFit (lastDeliberateWidth);
repaint();
columnsChanged = true;
triggerAsyncUpdate();
}
void TableHeaderComponent::handleAsyncUpdate()
{
const bool changed = columnsChanged || sortChanged;
const bool sized = columnsResized || changed;
const bool sorted = sortChanged;
columnsChanged = false;
columnsResized = false;
sortChanged = false;
if (sorted)
{
for (int i = listeners.size(); --i >= 0;)
{
listeners.getUnchecked(i)->tableSortOrderChanged (this);
i = jmin (i, listeners.size() - 1);
}
}
if (changed)
{
for (int i = listeners.size(); --i >= 0;)
{
listeners.getUnchecked(i)->tableColumnsChanged (this);
i = jmin (i, listeners.size() - 1);
}
}
if (sized)
{
for (int i = listeners.size(); --i >= 0;)
{
listeners.getUnchecked(i)->tableColumnsResized (this);
i = jmin (i, listeners.size() - 1);
}
}
}
int TableHeaderComponent::getResizeDraggerAt (const int mouseX) const
{
if (isPositiveAndBelow (mouseX, getWidth()))
{
const int draggableDistance = 3;
int x = 0;
for (int i = 0; i < columns.size(); ++i)
{
const ColumnInfo* const ci = columns.getUnchecked(i);
if (ci->isVisible())
{
if (abs (mouseX - (x + ci->width)) <= draggableDistance
&& (ci->propertyFlags & resizable) != 0)
return ci->id;
x += ci->width;
}
}
}
return 0;
}
void TableHeaderComponent::setColumnUnderMouse (const int newCol)
{
if (newCol != columnIdUnderMouse)
{
columnIdUnderMouse = newCol;
repaint();
}
}
void TableHeaderComponent::updateColumnUnderMouse (const MouseEvent& e)
{
setColumnUnderMouse (reallyContains (e.getPosition(), true) && getResizeDraggerAt (e.x) == 0
? getColumnIdAtX (e.x) : 0);
}
static void tableHeaderMenuCallback (int result, TableHeaderComponent* tableHeader, int columnIdClicked)
{
if (tableHeader != nullptr && result != 0)
tableHeader->reactToMenuItem (result, columnIdClicked);
}
void TableHeaderComponent::showColumnChooserMenu (const int columnIdClicked)
{
PopupMenu m;
addMenuItems (m, columnIdClicked);
if (m.getNumItems() > 0)
{
m.setLookAndFeel (&getLookAndFeel());
m.showMenuAsync (PopupMenu::Options(),
ModalCallbackFunction::forComponent (tableHeaderMenuCallback, this, columnIdClicked));
}
}
void TableHeaderComponent::Listener::tableColumnDraggingChanged (TableHeaderComponent*, int)
{
}
| mit |
takashi310/fluorender | fluorender/ffmpeg/OSX/include/libavcodec/libfdk-aacdec.c | 9 | 9975 | /*
* AAC decoder wrapper
* Copyright (c) 2012 Martin Storsjo
*
* This file is part of FFmpeg.
*
* Permission to use, copy, modify, and/or distribute this software for any
* purpose with or without fee is hereby granted, provided that the above
* copyright notice and this permission notice appear in all copies.
*
* THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
* WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
* ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
* WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
* ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
* OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
#include <fdk-aac/aacdecoder_lib.h>
#include "libavutil/channel_layout.h"
#include "libavutil/common.h"
#include "libavutil/opt.h"
#include "avcodec.h"
#include "internal.h"
enum ConcealMethod {
CONCEAL_METHOD_SPECTRAL_MUTING = 0,
CONCEAL_METHOD_NOISE_SUBSTITUTION = 1,
CONCEAL_METHOD_ENERGY_INTERPOLATION = 2,
CONCEAL_METHOD_NB,
};
typedef struct FDKAACDecContext {
const AVClass *class;
HANDLE_AACDECODER handle;
int initialized;
enum ConcealMethod conceal_method;
} FDKAACDecContext;
#define OFFSET(x) offsetof(FDKAACDecContext, x)
#define AD AV_OPT_FLAG_AUDIO_PARAM | AV_OPT_FLAG_DECODING_PARAM
static const AVOption fdk_aac_dec_options[] = {
{ "conceal", "Error concealment method", OFFSET(conceal_method), AV_OPT_TYPE_INT, { .i64 = CONCEAL_METHOD_NOISE_SUBSTITUTION }, CONCEAL_METHOD_SPECTRAL_MUTING, CONCEAL_METHOD_NB - 1, AD, "conceal" },
{ "spectral", "Spectral muting", 0, AV_OPT_TYPE_CONST, { .i64 = CONCEAL_METHOD_SPECTRAL_MUTING }, INT_MIN, INT_MAX, AD, "conceal" },
{ "noise", "Noise Substitution", 0, AV_OPT_TYPE_CONST, { .i64 = CONCEAL_METHOD_NOISE_SUBSTITUTION }, INT_MIN, INT_MAX, AD, "conceal" },
{ "energy", "Energy Interpolation", 0, AV_OPT_TYPE_CONST, { .i64 = CONCEAL_METHOD_ENERGY_INTERPOLATION }, INT_MIN, INT_MAX, AD, "conceal" },
{ NULL }
};
static const AVClass fdk_aac_dec_class = {
"libfdk-aac decoder", av_default_item_name, fdk_aac_dec_options, LIBAVUTIL_VERSION_INT
};
static int get_stream_info(AVCodecContext *avctx)
{
FDKAACDecContext *s = avctx->priv_data;
CStreamInfo *info = aacDecoder_GetStreamInfo(s->handle);
int channel_counts[9] = { 0 };
int i, ch_error = 0;
uint64_t ch_layout = 0;
if (!info) {
av_log(avctx, AV_LOG_ERROR, "Unable to get stream info\n");
return AVERROR_UNKNOWN;
}
if (info->sampleRate <= 0) {
av_log(avctx, AV_LOG_ERROR, "Stream info not initialized\n");
return AVERROR_UNKNOWN;
}
avctx->sample_rate = info->sampleRate;
avctx->frame_size = info->frameSize;
for (i = 0; i < info->numChannels; i++) {
AUDIO_CHANNEL_TYPE ctype = info->pChannelType[i];
if (ctype <= ACT_NONE || ctype > ACT_TOP) {
av_log(avctx, AV_LOG_WARNING, "unknown channel type\n");
break;
}
channel_counts[ctype]++;
}
av_log(avctx, AV_LOG_DEBUG,
"%d channels - front:%d side:%d back:%d lfe:%d top:%d\n",
info->numChannels,
channel_counts[ACT_FRONT], channel_counts[ACT_SIDE],
channel_counts[ACT_BACK], channel_counts[ACT_LFE],
channel_counts[ACT_FRONT_TOP] + channel_counts[ACT_SIDE_TOP] +
channel_counts[ACT_BACK_TOP] + channel_counts[ACT_TOP]);
switch (channel_counts[ACT_FRONT]) {
case 4:
ch_layout |= AV_CH_LAYOUT_STEREO | AV_CH_FRONT_LEFT_OF_CENTER |
AV_CH_FRONT_RIGHT_OF_CENTER;
break;
case 3:
ch_layout |= AV_CH_LAYOUT_STEREO | AV_CH_FRONT_CENTER;
break;
case 2:
ch_layout |= AV_CH_LAYOUT_STEREO;
break;
case 1:
ch_layout |= AV_CH_FRONT_CENTER;
break;
default:
av_log(avctx, AV_LOG_WARNING,
"unsupported number of front channels: %d\n",
channel_counts[ACT_FRONT]);
ch_error = 1;
break;
}
if (channel_counts[ACT_SIDE] > 0) {
if (channel_counts[ACT_SIDE] == 2) {
ch_layout |= AV_CH_SIDE_LEFT | AV_CH_SIDE_RIGHT;
} else {
av_log(avctx, AV_LOG_WARNING,
"unsupported number of side channels: %d\n",
channel_counts[ACT_SIDE]);
ch_error = 1;
}
}
if (channel_counts[ACT_BACK] > 0) {
switch (channel_counts[ACT_BACK]) {
case 3:
ch_layout |= AV_CH_BACK_LEFT | AV_CH_BACK_RIGHT | AV_CH_BACK_CENTER;
break;
case 2:
ch_layout |= AV_CH_BACK_LEFT | AV_CH_BACK_RIGHT;
break;
case 1:
ch_layout |= AV_CH_BACK_CENTER;
break;
default:
av_log(avctx, AV_LOG_WARNING,
"unsupported number of back channels: %d\n",
channel_counts[ACT_BACK]);
ch_error = 1;
break;
}
}
if (channel_counts[ACT_LFE] > 0) {
if (channel_counts[ACT_LFE] == 1) {
ch_layout |= AV_CH_LOW_FREQUENCY;
} else {
av_log(avctx, AV_LOG_WARNING,
"unsupported number of LFE channels: %d\n",
channel_counts[ACT_LFE]);
ch_error = 1;
}
}
if (!ch_error &&
av_get_channel_layout_nb_channels(ch_layout) != info->numChannels) {
av_log(avctx, AV_LOG_WARNING, "unsupported channel configuration\n");
ch_error = 1;
}
if (ch_error)
avctx->channel_layout = 0;
else
avctx->channel_layout = ch_layout;
avctx->channels = info->numChannels;
return 0;
}
static av_cold int fdk_aac_decode_close(AVCodecContext *avctx)
{
FDKAACDecContext *s = avctx->priv_data;
if (s->handle)
aacDecoder_Close(s->handle);
return 0;
}
static av_cold int fdk_aac_decode_init(AVCodecContext *avctx)
{
FDKAACDecContext *s = avctx->priv_data;
AAC_DECODER_ERROR err;
s->handle = aacDecoder_Open(avctx->extradata_size ? TT_MP4_RAW : TT_MP4_ADTS, 1);
if (!s->handle) {
av_log(avctx, AV_LOG_ERROR, "Error opening decoder\n");
return AVERROR_UNKNOWN;
}
if (avctx->extradata_size) {
if ((err = aacDecoder_ConfigRaw(s->handle, &avctx->extradata,
&avctx->extradata_size)) != AAC_DEC_OK) {
av_log(avctx, AV_LOG_ERROR, "Unable to set extradata\n");
return AVERROR_INVALIDDATA;
}
}
if ((err = aacDecoder_SetParam(s->handle, AAC_CONCEAL_METHOD,
s->conceal_method)) != AAC_DEC_OK) {
av_log(avctx, AV_LOG_ERROR, "Unable to set error concealment method\n");
return AVERROR_UNKNOWN;
}
avctx->sample_fmt = AV_SAMPLE_FMT_S16;
return 0;
}
static int fdk_aac_decode_frame(AVCodecContext *avctx, void *data,
int *got_frame_ptr, AVPacket *avpkt)
{
FDKAACDecContext *s = avctx->priv_data;
AVFrame *frame = data;
int ret;
AAC_DECODER_ERROR err;
UINT valid = avpkt->size;
uint8_t *buf, *tmpptr = NULL;
int buf_size;
err = aacDecoder_Fill(s->handle, &avpkt->data, &avpkt->size, &valid);
if (err != AAC_DEC_OK) {
av_log(avctx, AV_LOG_ERROR, "aacDecoder_Fill() failed: %x\n", err);
return AVERROR_INVALIDDATA;
}
if (s->initialized) {
frame->nb_samples = avctx->frame_size;
if ((ret = ff_get_buffer(avctx, frame, 0)) < 0)
return ret;
buf = frame->extended_data[0];
buf_size = avctx->channels * frame->nb_samples *
av_get_bytes_per_sample(avctx->sample_fmt);
} else {
buf_size = 50 * 1024;
buf = tmpptr = av_malloc(buf_size);
if (!buf)
return AVERROR(ENOMEM);
}
err = aacDecoder_DecodeFrame(s->handle, (INT_PCM *) buf, buf_size, 0);
if (err == AAC_DEC_NOT_ENOUGH_BITS) {
ret = avpkt->size - valid;
goto end;
}
if (err != AAC_DEC_OK) {
av_log(avctx, AV_LOG_ERROR,
"aacDecoder_DecodeFrame() failed: %x\n", err);
ret = AVERROR_UNKNOWN;
goto end;
}
if (!s->initialized) {
if ((ret = get_stream_info(avctx)) < 0)
goto end;
s->initialized = 1;
frame->nb_samples = avctx->frame_size;
}
if (tmpptr) {
frame->nb_samples = avctx->frame_size;
if ((ret = ff_get_buffer(avctx, frame, 0)) < 0)
goto end;
memcpy(frame->extended_data[0], tmpptr,
avctx->channels * avctx->frame_size *
av_get_bytes_per_sample(avctx->sample_fmt));
}
*got_frame_ptr = 1;
ret = avpkt->size - valid;
end:
av_free(tmpptr);
return ret;
}
static av_cold void fdk_aac_decode_flush(AVCodecContext *avctx)
{
FDKAACDecContext *s = avctx->priv_data;
AAC_DECODER_ERROR err;
if (!s->handle)
return;
if ((err = aacDecoder_SetParam(s->handle,
AAC_TPDEC_CLEAR_BUFFER, 1)) != AAC_DEC_OK)
av_log(avctx, AV_LOG_WARNING, "failed to clear buffer when flushing\n");
}
AVCodec ff_libfdk_aac_decoder = {
.name = "libfdk_aac",
.long_name = NULL_IF_CONFIG_SMALL("Fraunhofer FDK AAC"),
.type = AVMEDIA_TYPE_AUDIO,
.id = AV_CODEC_ID_AAC,
.priv_data_size = sizeof(FDKAACDecContext),
.init = fdk_aac_decode_init,
.decode = fdk_aac_decode_frame,
.close = fdk_aac_decode_close,
.flush = fdk_aac_decode_flush,
.capabilities = CODEC_CAP_DR1 | CODEC_CAP_CHANNEL_CONF,
.priv_class = &fdk_aac_dec_class,
};
| mit |
iosoccer/iosoccer-game | game/server/data_collector.cpp | 9 | 1915 | //========= Copyright © 1996-2005, Valve Corporation, All rights reserved. ============//
//
// Purpose:
//
// $NoKeywords: $
//
//=============================================================================//
// data_collector.cpp
// Data collection system
// Author: Michael S. Booth, June 2004
#include "cbase.h"
#include "data_collector.h"
static CDataCollector *collector = NULL;
//----------------------------------------------------------------------------------------------------------------------
void StartDataCollection( void )
{
if (collector)
{
// already collecting
return;
}
collector = new CDataCollector;
Msg( "Data colletion started.\n" );
}
ConCommand data_collection_start( "data_collection_start", StartDataCollection, "Start collecting game event data." );
//----------------------------------------------------------------------------------------------------------------------
void StopDataCollection( void )
{
if (collector)
{
delete collector;
collector = NULL;
Msg( "Data collection stopped.\n" );
}
}
ConCommand data_collection_stop( "data_collection_stop", StopDataCollection, "Stop collecting game event data." );
//----------------------------------------------------------------------------------------------------------------------
CDataCollector::CDataCollector( void )
{
// register for all events
gameeventmanager->AddListener( this, true );
}
//----------------------------------------------------------------------------------------------------------------------
CDataCollector::~CDataCollector()
{
gameeventmanager->RemoveListener( this );
}
//----------------------------------------------------------------------------------------------------------------------
/**
* This is invoked for each event that occurs in the game
*/
void CDataCollector::FireGameEvent( KeyValues *event )
{
DevMsg( "Collected event '%s'\n", event->GetName() );
}
| mit |
mauro-belgiovine/belgiovi-clmagma | testing/lin/ctpt02.f | 9 | 4979 | SUBROUTINE CTPT02( UPLO, TRANS, DIAG, N, NRHS, AP, X, LDX, B, LDB,
$ WORK, RWORK, RESID )
*
* -- LAPACK test routine (version 3.1) --
* Univ. of Tennessee, Univ. of California Berkeley and NAG Ltd..
* November 2006
*
* .. Scalar Arguments ..
CHARACTER DIAG, TRANS, UPLO
INTEGER LDB, LDX, N, NRHS
REAL RESID
* ..
* .. Array Arguments ..
REAL RWORK( * )
COMPLEX AP( * ), B( LDB, * ), WORK( * ), X( LDX, * )
* ..
*
* Purpose
* =======
*
* CTPT02 computes the residual for the computed solution to a
* triangular system of linear equations A*x = b, A**T *x = b, or
* A**H *x = b, when the triangular matrix A is stored in packed format.
* Here A**T denotes the transpose of A, A**H denotes the conjugate
* transpose of A, and x and b are N by NRHS matrices. The test ratio
* is the maximum over the number of right hand sides of
* the maximum over the number of right hand sides of
* norm(b - op(A)*x) / ( norm(op(A)) * norm(x) * EPS ),
* where op(A) denotes A, A**T, or A**H, and EPS is the machine epsilon.
*
* Arguments
* =========
*
* UPLO (input) CHARACTER*1
* Specifies whether the matrix A is upper or lower triangular.
* = 'U': Upper triangular
* = 'L': Lower triangular
*
* TRANS (input) CHARACTER*1
* Specifies the operation applied to A.
* = 'N': A *x = b (No transpose)
* = 'T': A**T *x = b (Transpose)
* = 'C': A**H *x = b (Conjugate transpose)
*
* DIAG (input) CHARACTER*1
* Specifies whether or not the matrix A is unit triangular.
* = 'N': Non-unit triangular
* = 'U': Unit triangular
*
* N (input) INTEGER
* The order of the matrix A. N >= 0.
*
* NRHS (input) INTEGER
* The number of right hand sides, i.e., the number of columns
* of the matrices X and B. NRHS >= 0.
*
* AP (input) COMPLEX array, dimension (N*(N+1)/2)
* The upper or lower triangular matrix A, packed columnwise in
* a linear array. The j-th column of A is stored in the array
* AP as follows:
* if UPLO = 'U', AP((j-1)*j/2 + i) = A(i,j) for 1<=i<=j;
* if UPLO = 'L',
* AP((j-1)*(n-j) + j*(j+1)/2 + i-j) = A(i,j) for j<=i<=n.
*
* X (input) COMPLEX array, dimension (LDX,NRHS)
* The computed solution vectors for the system of linear
* equations.
*
* LDX (input) INTEGER
* The leading dimension of the array X. LDX >= max(1,N).
*
* B (input) COMPLEX array, dimension (LDB,NRHS)
* The right hand side vectors for the system of linear
* equations.
*
* LDB (input) INTEGER
* The leading dimension of the array B. LDB >= max(1,N).
*
* WORK (workspace) COMPLEX array, dimension (N)
*
* RWORK (workspace) REAL array, dimension (N)
*
* RESID (output) REAL
* The maximum over the number of right hand sides of
* norm(op(A)*x - b) / ( norm(op(A)) * norm(x) * EPS ).
*
* =====================================================================
*
* .. Parameters ..
REAL ZERO, ONE
PARAMETER ( ZERO = 0.0E+0, ONE = 1.0E+0 )
* ..
* .. Local Scalars ..
INTEGER J
REAL ANORM, BNORM, EPS, XNORM
* ..
* .. External Functions ..
LOGICAL LSAME
REAL CLANTP, SCASUM, SLAMCH
EXTERNAL LSAME, CLANTP, SCASUM, SLAMCH
* ..
* .. External Subroutines ..
EXTERNAL CAXPY, CCOPY, CTPMV
* ..
* .. Intrinsic Functions ..
INTRINSIC CMPLX, MAX
* ..
* .. Executable Statements ..
*
* Quick exit if N = 0 or NRHS = 0
*
IF( N.LE.0 .OR. NRHS.LE.0 ) THEN
RESID = ZERO
RETURN
END IF
*
* Compute the 1-norm of A or A**H.
*
IF( LSAME( TRANS, 'N' ) ) THEN
ANORM = CLANTP( '1', UPLO, DIAG, N, AP, RWORK )
ELSE
ANORM = CLANTP( 'I', UPLO, DIAG, N, AP, RWORK )
END IF
*
* Exit with RESID = 1/EPS if ANORM = 0.
*
EPS = SLAMCH( 'Epsilon' )
IF( ANORM.LE.ZERO ) THEN
RESID = ONE / EPS
RETURN
END IF
*
* Compute the maximum over the number of right hand sides of
* norm(op(A)*x - b) / ( norm(op(A)) * norm(x) * EPS ).
*
RESID = ZERO
DO 10 J = 1, NRHS
CALL CCOPY( N, X( 1, J ), 1, WORK, 1 )
CALL CTPMV( UPLO, TRANS, DIAG, N, AP, WORK, 1 )
CALL CAXPY( N, CMPLX( -ONE ), B( 1, J ), 1, WORK, 1 )
BNORM = SCASUM( N, WORK, 1 )
XNORM = SCASUM( N, X( 1, J ), 1 )
IF( XNORM.LE.ZERO ) THEN
RESID = ONE / EPS
ELSE
RESID = MAX( RESID, ( ( BNORM / ANORM ) / XNORM ) / EPS )
END IF
10 CONTINUE
*
RETURN
*
* End of CTPT02
*
END
| mit |
Dr-Shadow/android_bootloader_acer_c10 | platform/msm_shared/mipi_dsi_phy.c | 10 | 5512 | /* Copyright (c) 2012, Code Aurora Forum. 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 Code Aurora Forum, Inc. 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 "AS IS" AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT
* 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.
*
*/
#include <debug.h>
#include <reg.h>
#include <mipi_dsi.h>
#include <platform/iomap.h>
static void mipi_dsi_calibration(void)
{
uint32_t i = 0;
uint32_t term_cnt = 5000;
int32_t cal_busy = readl(MIPI_DSI_BASE + 0x550);
/* DSI1_DSIPHY_REGULATOR_CAL_PWR_CFG */
writel(0x01, MIPI_DSI_BASE + 0x0518);
/* DSI1_DSIPHY_CAL_SW_CFG2 */
writel(0x0, MIPI_DSI_BASE + 0x0534);
/* DSI1_DSIPHY_CAL_HW_CFG1 */
writel(0x5a, MIPI_DSI_BASE + 0x053c);
/* DSI1_DSIPHY_CAL_HW_CFG3 */
writel(0x10, MIPI_DSI_BASE + 0x0544);
/* DSI1_DSIPHY_CAL_HW_CFG4 */
writel(0x01, MIPI_DSI_BASE + 0x0548);
/* DSI1_DSIPHY_CAL_HW_CFG0 */
writel(0x01, MIPI_DSI_BASE + 0x0538);
/* DSI1_DSIPHY_CAL_HW_TRIGGER */
writel(0x01, MIPI_DSI_BASE + 0x0528);
/* DSI1_DSIPHY_CAL_HW_TRIGGER */
writel(0x00, MIPI_DSI_BASE + 0x0528);
cal_busy = readl(MIPI_DSI_BASE + 0x550);
while (cal_busy & 0x10) {
i++;
if (i > term_cnt) {
dprintf(CRITICAL, "DSI1 PHY REGULATOR NOT READY,"
"exceeded polling TIMEOUT!\n");
break;
}
cal_busy = readl(MIPI_DSI_BASE + 0x550);
}
}
int mipi_dsi_phy_init(struct mipi_dsi_panel_config *pinfo)
{
struct mipi_dsi_phy_ctrl *pd;
uint32_t i, off = 0;
int mdp_rev;
mdp_rev = mdp_get_revision();
if (MDP_REV_303 == mdp_rev || MDP_REV_41 == mdp_rev) {
writel(0x00000001, DSIPHY_SW_RESET);
writel(0x00000000, DSIPHY_SW_RESET);
pd = (pinfo->dsi_phy_config);
off = 0x02cc; /* regulator ctrl 0 */
for (i = 0; i < 4; i++) {
writel(pd->regulator[i], MIPI_DSI_BASE + off);
off += 4;
}
off = 0x0260; /* phy timig ctrl 0 */
for (i = 0; i < 11; i++) {
writel(pd->timing[i], MIPI_DSI_BASE + off);
off += 4;
}
/* T_CLK_POST, T_CLK_PRE for CLK lane P/N HS 200 mV timing
length should > data lane HS timing length */
writel(0xa1e, DSI_CLKOUT_TIMING_CTRL);
off = 0x0290; /* ctrl 0 */
for (i = 0; i < 4; i++) {
writel(pd->ctrl[i], MIPI_DSI_BASE + off);
off += 4;
}
off = 0x02a0; /* strength 0 */
for (i = 0; i < 4; i++) {
writel(pd->strength[i], MIPI_DSI_BASE + off);
off += 4;
}
if (1 == pinfo->num_of_lanes)
pd->pll[10] |= 0x8;
off = 0x0204; /* pll ctrl 1, skip 0 */
for (i = 1; i < 21; i++) {
writel(pd->pll[i], MIPI_DSI_BASE + off);
off += 4;
}
/* pll ctrl 0 */
writel(pd->pll[0], MIPI_DSI_BASE + 0x200);
writel((pd->pll[0] | 0x01), MIPI_DSI_BASE + 0x200);
/* lane swp ctrol */
if (pinfo->lane_swap)
writel(pinfo->lane_swap, MIPI_DSI_BASE + 0xac);
} else {
writel(0x0001, MIPI_DSI_BASE + 0x128); /* start phy sw reset */
writel(0x0000, MIPI_DSI_BASE + 0x128); /* end phy w reset */
writel(0x0003, MIPI_DSI_BASE + 0x500); /* regulator_ctrl_0 */
writel(0x0001, MIPI_DSI_BASE + 0x504); /* regulator_ctrl_1 */
writel(0x0001, MIPI_DSI_BASE + 0x508); /* regulator_ctrl_2 */
writel(0x0000, MIPI_DSI_BASE + 0x50c); /* regulator_ctrl_3 */
writel(0x0100, MIPI_DSI_BASE + 0x510); /* regulator_ctrl_4 */
pd = (pinfo->dsi_phy_config);
off = 0x0480; /* strength 0 - 2 */
for (i = 0; i < 3; i++) {
writel(pd->strength[i], MIPI_DSI_BASE + off);
off += 4;
}
off = 0x0470; /* ctrl 0 - 3 */
for (i = 0; i < 4; i++) {
writel(pd->ctrl[i], MIPI_DSI_BASE + off);
off += 4;
}
off = 0x0500; /* regulator ctrl 0 - 4 */
for (i = 0; i < 5; i++) {
writel(pd->regulator[i], MIPI_DSI_BASE + off);
off += 4;
}
mipi_dsi_calibration();
off = 0x0204; /* pll ctrl 1 - 19, skip 0 */
for (i = 1; i < 20; i++) {
writel(pd->pll[i], MIPI_DSI_BASE + off);
off += 4;
}
/* pll ctrl 0 */
writel(pd->pll[0], MIPI_DSI_BASE + 0x200);
writel((pd->pll[0] | 0x01), MIPI_DSI_BASE + 0x200);
/* Check that PHY is ready */
while (!(readl(DSIPHY_PLL_RDY) & 0x01))
udelay(1);
writel(0x202D, DSI_CLKOUT_TIMING_CTRL);
off = 0x0440; /* phy timing ctrl 0 - 11 */
for (i = 0; i < 12; i++) {
writel(pd->timing[i], MIPI_DSI_BASE + off);
off += 4;
}
}
return 0;
}
| mit |
xufei198907/ME_557_2015_FX | Homework_4/gl_common/GLSphere.cpp | 11 | 27251 | //
// GLSphere.cpp
// OpenGL_Transformations
//
// Created by Rafael Radkowski on 9/12/15.
//
//
#include "GLSphere.h"
static const string vs_string_GLSphere_410 =
"#version 410 core \n"
" \n"
"uniform mat4 projectionMatrixBox; \n"
"uniform mat4 viewMatrixBox; \n"
"uniform mat4 inverseViewMatrix; \n"
"uniform mat4 modelMatrixBox; \n"
"uniform vec3 diffuse_color; \n"
"uniform vec3 ambient_color; \n"
"uniform vec3 specular_color; \n"
"uniform vec4 light_position; \n"
"uniform float diffuse_intensity; \n"
"uniform float ambient_intensity; \n"
"uniform float specular_intensity; \n"
"uniform float shininess; \n"
"in vec3 in_Position; \n"
"in vec3 in_Normal; \n"
"in vec3 in_Color; \n"
"out vec3 pass_Color; \n"
" \n"
" \n"
" \n"
" \n"
"void main(void) \n"
"{ \n"
" vec3 normal = normalize(in_Normal); \n"
" vec4 transformedNormal = normalize(transpose(inverse(modelMatrixBox)) * vec4( normal, 1.0 )); \n"
" vec4 surfacePostion = modelMatrixBox * vec4(in_Position, 1.0); \n"
" \n"
" vec4 surface_to_light = normalize( light_position - surfacePostion ); \n"
" \n"
" // Diffuse color \n"
" float diffuse_coefficient = max( dot(transformedNormal, surface_to_light), 0.0); \n"
" vec3 out_diffuse_color = diffuse_color * diffuse_coefficient * diffuse_intensity; \n"
" \n"
" // Ambient color \n"
" vec3 out_ambient_color = vec3(ambient_color) * ambient_intensity; \n"
" \n"
" // Specular color \n"
" vec3 incidenceVector = -surface_to_light.xyz; \n"
" vec3 reflectionVector = reflect(incidenceVector, normal); \n"
" vec3 cameraPosition = vec3( inverseViewMatrix[3][0], inverseViewMatrix[3][1], inverseViewMatrix[3][2]); \n"
" vec3 surfaceToCamera = normalize(cameraPosition - surfacePostion.xyz); \n"
" float cosAngle = max( dot(surfaceToCamera, reflectionVector), 0.0); \n"
" float specular_coefficient = pow(cosAngle, shininess); \n"
" vec3 out_specular_color = specular_color * specular_coefficient * specular_intensity; \n"
" \n"
" gl_Position = projectionMatrixBox * viewMatrixBox * modelMatrixBox * vec4(in_Position, 1.0); \n"
" \n"
" pass_Color = vec3(out_diffuse_color + out_ambient_color + out_specular_color); \n"
"} \n";
static const string vs_string_GLSphere_300 =
"#version 310 core \n"
" \n"
"uniform mat4 projectionMatrixBox; \n"
"uniform mat4 viewMatrixBox; \n"
"uniform mat4 modelMatrixBox; \n"
"uniform mat4 inverseViewMatrix; \n"
"uniform vec3 diffuse_color; \n"
"uniform vec3 ambient_color; \n"
"uniform vec3 specular_color; \n"
"uniform vec4 light_position; \n"
"uniform float diffuse_intensity; \n"
"uniform float ambient_intensity; \n"
"uniform float specular_intensity; \n"
"uniform float shininess; \n"
"in vec3 in_Position; \n"
"in vec3 in_Normal; \n"
"in vec3 in_Color; \n"
" \n"
" \n"
" \n"
"void main(void) \n"
"{ \n"
" vec3 normal = normalize(in_Normal); \n"
" vec4 transformedNormal = normalize(transpose(inverse(modelMatrixBox)) * vec4( normal, 1.0 )); \n"
" vec4 surfacePostion = viewMatrixBox * modelMatrixBox * vec4(in_Position, 1.0); \n"
" \n"
" vec4 surface_to_light = normalize( light_position - surfacePostion ); \n"
" \n"
" // Diffuse color \n"
" float diffuse_coefficient = max( dot(transformedNormal, surface_to_light), 0.0); \n"
" vec3 out_diffuse_color = diffuse_color * diffuse_coefficient * diffuse_intensity; \n"
" \n"
" // Ambient color \n"
" vec3 out_ambient_color = vec3(ambient_color) * ambient_intensity; \n"
" \n"
" // Specular color \n"
" vec3 incidenceVector = -surface_to_light.xyz; \n"
" vec3 reflectionVector = reflect(incidenceVector, normal); \n"
" vec3 cameraPosition = vec3( inverseViewMatrix[3][0], inverseViewMatrix[3][1], inverseViewMatrix[3][2]); \n"
" vec3 surfaceToCamera = normalize(cameraPosition - surfacePostion.xyz); \n"
" float cosAngle = max( dot(surfaceToCamera, reflectionVector), 0.0); \n"
" float specular_coefficient = pow(cosAngle, shininess); \n"
" vec3 out_specular_color = specular_color * specular_coefficient * specular_intensity; \n"
" \n"
" gl_Position = projectionMatrixBox * viewMatrixBox * modelMatrixBox * vec4(in_Position, 1.0); \n"
" \n"
" gl_FrontColor = vec3(out_diffuse_color + out_ambient_color + out_specular_color); \n"
"} \n";
// Fragment shader source code. This determines the colors in the fragment generated in the shader pipeline. In this case, it colors the inside of our triangle specified by our vertex shader.
static const string fs_string_GLSphere_410 =
"#version 410 core \n"
" \n"
"in vec3 pass_Color; \n"
"out vec4 color; \n"
"void main(void) \n"
"{ \n"
" color = vec4(pass_Color, 1.0); \n"
"} \n";
static const string fs_string_GLSphere_300 =
"#version 310 core \n"
" \n"
" \n"
" \n"
"void main(void) \n"
"{ \n"
" gl_FragColor = vec4(pass_Color, 1.0); \n"
"} \n";
GLSphere::GLSphere(float center_x, float center_y, float center_z, float radius, int rows, int segments )
{
_center.x() = center_x;
_center.y() = center_y;
_center.z() = center_z;
_radius = radius;
_rows = rows;
_segments = segments;
_render_normal_vectors = false;
_program_normals = -1;
_program = -1;
initShader();
initVBO();
initShaderNormal();
initVBONormals();
}
GLSphere::~GLSphere()
{
// Program clean up when the window gets closed.
glDeleteVertexArrays(1, _vaoID);
glDeleteVertexArrays(1, _vaoIDNormals);
glDeleteProgram(_program);
glDeleteProgram(_program_normals);
}
/*!
Draw the objects
*/
void GLSphere::draw(void)
{
//////////////////////////////////////////////////
// Renders the sphere
// Enable the shader program
glUseProgram(_program);
// this changes the camera location
glm::mat4 rotated_view = rotatedViewMatrix();
glUniformMatrix4fv(_viewMatrixLocation, 1, GL_FALSE, &rotated_view[0][0]); // send the view matrix to our shader
glUniformMatrix4fv(_inverseViewMatrixLocation, 1, GL_FALSE, &invRotatedViewMatrix()[0][0]);
glUniformMatrix4fv(_modelMatrixLocation, 1, GL_FALSE, &_modelMatrix[0][0]); //
// Bind the buffer and switch it to an active buffer
glBindVertexArray(_vaoID[0]);
//glPolygonMode( GL_FRONT_AND_BACK, GL_LINE ); // allows to see the primitives
// Draw the triangles
glDrawArrays(GL_TRIANGLE_STRIP, 0, _num_vertices);
//////////////////////////////////////////////////
// Renders the normal vectors
if(_render_normal_vectors)
{
// Enable the shader program
glUseProgram(_program_normals);
glUniformMatrix4fv(_viewMatrixLocationN, 1, GL_FALSE, &rotated_view[0][0]); // send the view matrix to our shader
glUniformMatrix4fv(_modelMatrixLocationN, 1, GL_FALSE, &_modelMatrix[0][0]); //
// Bind the buffer and switch it to an active buffer
glBindVertexArray(_vaoIDNormals[0]);
glDrawArrays(GL_LINES, 0, _num_vertices_normals);
}
// Unbind our Vertex Array Object
glBindVertexArray(0);
// Unbind the shader program
glUseProgram(0);
}
/*!
Set the model matrix for this object
@param modelmatrix: 4x4 model matrix
*/
void GLSphere::setModelMatrix(glm::mat4& modelmatrix)
{
_modelMatrix=modelmatrix;
}
/*!
Enables or disables the normal vector renderer
@param value = true -> enables the renderer, false -> disables the renderer
*/
void GLSphere::enableNormalVectorRenderer(bool value )
{
_render_normal_vectors = value;
}
/*!
Create the vertex buffer object for this element
*/
void GLSphere::initVBO(void)
{
_spherePoints.clear();
_normalVectors.clear();
make_Sphere(_center, _radius, _spherePoints, _normalVectors);
_num_vertices = _spherePoints.size();
// create memory for the vertices, etc.
float* vertices = new float[_spherePoints.size() * 3];
float* colors = new float[_spherePoints.size() * 3];
float* normals = new float[_spherePoints.size() * 3];
// copy the data to the vectors
for(int i=0; i<_spherePoints.size() ; i++)
{
Vertex v = _spherePoints[i];
vertices[(i*3)] = v.x(); vertices[(i*3)+1] = v.y(); vertices[(i*3)+2] = v.z();
Vertex n = _normalVectors[i];
normals[(i*3)] = n.x(); normals[(i*3)+1] = n.y(); normals[(i*3)+2] = n.z();
colors[(i*3)] = 1.0; colors[(i*3)+1] = 1.0; colors[(i*3)+2] = 0.0;
}
glUseProgram(_program);
glGenVertexArrays(1, _vaoID); // Create our Vertex Array Object
glBindVertexArray(_vaoID[0]); // Bind our Vertex Array Object so we can use it
glGenBuffers(3, _vboID); // Generate our Vertex Buffer Object
// vertices
glBindBuffer(GL_ARRAY_BUFFER, _vboID[0]); // Bind our Vertex Buffer Object
glBufferData(GL_ARRAY_BUFFER, _num_vertices * 3 * sizeof(GLfloat), vertices, GL_STATIC_DRAW); // Set the size and data of our VBO and set it to STATIC_DRAW
int locPos = glGetAttribLocation(_program, "in_Position");
glVertexAttribPointer((GLuint)locPos, 3, GL_FLOAT, GL_FALSE, 0, 0); // Set up our vertex attributes pointer
glEnableVertexAttribArray(locPos); //
//Normals
glBindBuffer(GL_ARRAY_BUFFER, _vboID[1]); // Bind our second Vertex Buffer Object
glBufferData(GL_ARRAY_BUFFER, _num_vertices * 3 * sizeof(GLfloat), normals, GL_STATIC_DRAW); // Set the size and data of our VBO and set it to STATIC_DRAW
int locNorm = glGetAttribLocation(_program, "in_Normal");
glVertexAttribPointer((GLuint)locNorm, 3, GL_FLOAT, GL_FALSE, 0, 0); // Set up our vertex attributes pointer
glEnableVertexAttribArray(locNorm); //
//Color
glBindBuffer(GL_ARRAY_BUFFER, _vboID[2]); // Bind our second Vertex Buffer Object
glBufferData(GL_ARRAY_BUFFER, _num_vertices * 3 * sizeof(GLfloat), colors, GL_STATIC_DRAW); // Set the size and data of our VBO and set it to STATIC_DRAW
int logColor = glGetAttribLocation(_program, "in_Color");
glVertexAttribPointer((GLuint)logColor, 3, GL_FLOAT, GL_FALSE, 0, 0); // Set up our vertex attributes pointer
glEnableVertexAttribArray(logColor); //
glBindVertexArray(0); // Disable our Vertex Buffer Object
// delete the memory
delete vertices;
delete colors;
delete normals;
}
/*!
Init a frame buffer object to draw normal vectors
*/
void GLSphere::initVBONormals(void)
{
// create the normal vector lines
vector<Vertex> normalVectorLines;
for(int i=0; i<_spherePoints.size() ; i++)
{
Vertex v = _spherePoints[i];
Vertex n = _normalVectors[i];
normalVectorLines.push_back(v);
normalVectorLines.push_back(v+n);
}
float *normal_lines = new float[normalVectorLines.size() * 3];
float *colors = new float[normalVectorLines.size() * 3];
for(int i=0; i<normalVectorLines.size() ; i++)
{
normal_lines[(i*3)] = normalVectorLines[i].x();
normal_lines[(i*3)+1] = normalVectorLines[i].y();
normal_lines[(i*3)+2] = normalVectorLines[i].z();
colors[(i*3)] = 0.0; colors[(i*3)+1] = 0.0; colors[(i*3)+2] = 1.0;
}
_num_vertices_normals = normalVectorLines.size();
glUseProgram(_program_normals);
glGenVertexArrays(1, _vaoIDNormals); // Create our Vertex Array Object
glBindVertexArray(_vaoIDNormals[0]); // Bind our Vertex Array Object so we can use it
glGenBuffers(2, _vboIDNormals); // Generate our Vertex Buffer Object
// vertices
glBindBuffer(GL_ARRAY_BUFFER, _vboIDNormals[0]); // Bind our Vertex Buffer Object
glBufferData(GL_ARRAY_BUFFER, normalVectorLines.size() * 3 * sizeof(GLfloat), normal_lines, GL_STATIC_DRAW); // Set the size and data of our VBO and set it to STATIC_DRAW
glVertexAttribPointer((GLuint)0, 3, GL_FLOAT, GL_FALSE, 0, 0); // Set up our vertex attributes pointer
glEnableVertexAttribArray(0); //
//Color
glBindBuffer(GL_ARRAY_BUFFER, _vboIDNormals[1]); // Bind our second Vertex Buffer Object
glBufferData(GL_ARRAY_BUFFER, normalVectorLines.size() * 3 * sizeof(GLfloat), colors, GL_STATIC_DRAW); // Set the size and data of our VBO and set it to STATIC_DRAW
glVertexAttribPointer((GLuint)glGetAttribLocation(_program, "in_Color"), 3, GL_FLOAT, GL_FALSE, 0, 0); // Set up our vertex attributes pointer
glEnableVertexAttribArray(glGetAttribLocation(_program, "in_Color")); //
glBindVertexArray(0); // Disable our Vertex Buffer Object
delete normal_lines;
delete colors;
}
/*
Inits the shader program for this object
*/
void GLSphere::initShader(void)
{
// Vertex shader source code. This draws the vertices in our window. We have 3 vertices since we're drawing an triangle.
// Each vertex is represented by a vector of size 4 (x, y, z, w) coordinates.
// static const string vertex_code = vs_string_CoordSystem;
static const char * vs_source = vs_string_GLSphere_410.c_str();
// Fragment shader source code. This determines the colors in the fragment generated in the shader pipeline. In this case, it colors the inside of our triangle specified by our vertex shader.
// static const string fragment_code = fs_string_CoordSystem;
static const char * fs_source = fs_string_GLSphere_410.c_str();
// This next section we'll generate the OpenGL program and attach the shaders to it so that we can render our triangle.
_program = glCreateProgram();
// We create a shader with our fragment shader source code and compile it.
GLuint fs = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(fs, 1, &fs_source, NULL);
glCompileShader(fs);
CheckShader(fs, GL_FRAGMENT_SHADER);
// We create a shader with our vertex shader source code and compile it.
GLuint vs = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(vs, 1, &vs_source, NULL);
glCompileShader(vs);
CheckShader(vs, GL_VERTEX_SHADER);
// We'll attach our two compiled shaders to the OpenGL program.
glAttachShader(_program, vs);
glAttachShader(_program, fs);
glLinkProgram(_program);
glUseProgram(_program);
_modelMatrix = glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, 0.0f, 0.0f)); // Create our model matrix which will halve the size of our model
int projectionMatrixLocation = glGetUniformLocation(_program, "projectionMatrixBox"); // Get the location of our projection matrix in the shader
_viewMatrixLocation = glGetUniformLocation(_program, "viewMatrixBox"); // Get the location of our view matrix in the shader
_modelMatrixLocation = glGetUniformLocation(_program, "modelMatrixBox"); // Get the location of our model matrix in the shader
_inverseViewMatrixLocation = glGetUniformLocation(_program, "inverseViewMatrix");
_light_source0._lightPosIdx = glGetUniformLocation(_program, "light_position");
glUniformMatrix4fv(projectionMatrixLocation, 1, GL_FALSE, &projectionMatrix()[0][0] ); // Send our projection matrix to the shader
glUniformMatrix4fv(_viewMatrixLocation, 1, GL_FALSE, &viewMatrix()[0][0]); // Send our view matrix to the shader
glUniformMatrix4fv(_modelMatrixLocation, 1, GL_FALSE, &_modelMatrix[0][0]); // Send our model matrix to the shader
glUniformMatrix4fv(_inverseViewMatrixLocation, 1, GL_FALSE, &invRotatedViewMatrix()[0][0]);
///////////////////////////////////////////////////////////////////////////////////////////////
// Material
_material._diffuse_material = glm::vec3(1.0, 0.5, 0.0);
_material._ambient_material = glm::vec3(1.0, 0.5, 0.0);
_material._specular_material = glm::vec3(1.0, 1.0, 1.0);
_material._shininess = 12.0;
_material._ambientColorPos = glGetUniformLocation(_program, "ambient_color");
_material._diffuseColorPos = glGetUniformLocation(_program, "diffuse_color");
_material._specularColorPos = glGetUniformLocation(_program, "specular_color");
_material._shininessIdx = glGetUniformLocation(_program, "shininess");
// Send the material to your shader program
glUniform3fv(_material._ambientColorPos, 1, &_material._ambient_material[0] );
glUniform3fv(_material._diffuseColorPos, 1, &_material._diffuse_material[0]);
glUniform3fv(_material._specularColorPos, 1, &_material._specular_material[0]);
glUniform1f(_material._shininessIdx, _material._shininess);
///////////////////////////////////////////////////////////////////////////////////////////////
// Light
// define the position of the light and send the light position to your shader program
_light_source0._lightPos = glm::vec4(50.0,50.0,0.0,1.0);
_light_source0._ambient_intensity = 0.5;
_light_source0._specular_intensity = 1.0;
_light_source0._diffuse_intensity = 1.0;
_light_source0._ambientIdx = glGetUniformLocation(_program, "ambient_intensity");
_light_source0._diffuseIdx = glGetUniformLocation(_program, "diffuse_intensity");
_light_source0._specularIdx = glGetUniformLocation(_program, "specular_intensity");
// Send the light information to your shader program
glUniform1f(_light_source0._ambientIdx, _light_source0._ambient_intensity );
glUniform1f(_light_source0._diffuseIdx, _light_source0._diffuse_intensity);
glUniform1f(_light_source0._specularIdx, _light_source0._specular_intensity);
glUniform4fv(_light_source0._lightPosIdx, 1, &_light_source0._lightPos[0]);
///////////////////////////////////////////////////////////////////////////////////////////////
// Vertex information / names
// bind the to the shader program
glBindAttribLocation(_program, 0, "in_Position");
glBindAttribLocation(_program, 1, "in_Normal");
glBindAttribLocation(_program, 2, "in_Color");
glUseProgram(0);
}
/*!
Shader for the normal vector renderer
*/
void GLSphere::initShaderNormal(void)
{
_program_normals = CreateShaderProgram(vs_string_simple_shader_410, fs_string_simple_shader_410);
glUseProgram(_program_normals);
unsigned int projectionMatrixLocation = glGetUniformLocation(_program_normals, "projectionMatrix"); // Get the location of our projection matrix in the shader
_viewMatrixLocationN = glGetUniformLocation(_program_normals, "viewMatrix"); // Get the location of our view matrix in the shader
_modelMatrixLocationN = glGetUniformLocation(_program_normals, "modelMatrix"); // Get the location of our model matrix in the shader
glUniformMatrix4fv(projectionMatrixLocation, 1, GL_FALSE, &projectionMatrix()[0][0] ); // Send our projection matrix to the shader
glUniformMatrix4fv(_viewMatrixLocationN, 1, GL_FALSE, &viewMatrix()[0][0]); // Send our view matrix to the shader
glUniformMatrix4fv(_modelMatrixLocationN, 1, GL_FALSE, &_modelMatrix[0][0]); // Send our model matrix to the shader
glBindAttribLocation(_program_normals, 0, "in_Position");
glBindAttribLocation(_program_normals, 1, "in_Color");
glUseProgram(0);
}
void GLSphere::make_Sphere(Vertex center, double r, std::vector<Vertex> &spherePoints, std::vector<Vertex> &normals)
{
const double PI = 3.141592653589793238462643383279502884197;
spherePoints.clear();
int current_size = 0;
for (double theta = 0.; theta < PI; theta += PI/float(_rows)) // Elevation [0, PI]
{
//double theta = 1.57;
double theta2 = theta + PI/float(_rows);
int count = 0;
int count_row = 0;
current_size = spherePoints.size();
// Iterate through phi, theta then convert r,theta,phi to XYZ
for (double phi = 0.; phi < 2*PI + PI/float(_segments) ; phi += PI/float(_segments)) // Azimuth [0, 2PI]
{
Vertex point;
point.x() = r * cos(phi) * sin(theta) + center.x();
point.y() = r * sin(phi) * sin(theta) + center.y();
point.z() = r * cos(theta) + center.z();
spherePoints.push_back(point); count++;
Vertex point2;
point2.x() = r * cos(phi) * sin(theta2) + center.x();
point2.y() = r * sin(phi) * sin(theta2) + center.y();
point2.z() = r * cos(theta2) + center.z();
spherePoints.push_back(point2); count++;
Vertex normal;
normal.x() = cos(phi) * sin(theta);
normal.y() = sin(phi) * sin(theta);
normal.z() = cos(theta);
normals.push_back(normal);
Vertex normal2;
normal2.x() = cos(phi) * sin(theta2);
normal2.y() = sin(phi) * sin(theta2);
normal2.z() = cos(theta2);
normals.push_back(normal2);
}
if(count_row == 0) count_row = count;
}
return;
}
| mit |
KitSprout/MicroMultimeter | Software/uM_PeripheralSTD_ADC/Libraries/STM32F30x_StdPeriph_Driver/src/stm32f30x_usart.c | 11 | 84451 | /**
******************************************************************************
* @file stm32f30x_usart.c
* @author MCD Application Team
* @version V1.2.2
* @date 27-February-2015
* @brief This file provides firmware functions to manage the following
* functionalities of the Universal synchronous asynchronous receiver
* transmitter (USART):
* + Initialization and Configuration
* + STOP Mode
* + AutoBaudRate
* + Data transfers
* + Multi-Processor Communication
* + LIN mode
* + Half-duplex mode
* + Smartcard mode
* + IrDA mode
* + RS485 mode
* + DMA transfers management
* + Interrupts and flags management
*
* @verbatim
===============================================================================
##### How to use this driver #####
===============================================================================
[..]
(#) Enable peripheral clock using RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE)
function for USART1 or using RCC_APB1PeriphClockCmd(RCC_APB1Periph_USARTx, ENABLE)
function for USART2, USART3, UART4 and UART5.
(#) According to the USART mode, enable the GPIO clocks using
RCC_AHBPeriphClockCmd() function. (The I/O can be TX, RX, CTS,
or and SCLK).
(#) Peripheral's alternate function:
(++) Connect the pin to the desired peripherals' Alternate
Function (AF) using GPIO_PinAFConfig() function.
(++) Configure the desired pin in alternate function by:
GPIO_InitStruct->GPIO_Mode = GPIO_Mode_AF.
(++) Select the type, pull-up/pull-down and output speed via
GPIO_PuPd, GPIO_OType and GPIO_Speed members.
(++) Call GPIO_Init() function.
(#) Program the Baud Rate, Word Length , Stop Bit, Parity, Hardware
flow control and Mode(Receiver/Transmitter) using the SPI_Init()
function.
(#) For synchronous mode, enable the clock and program the polarity,
phase and last bit using the USART_ClockInit() function.
(#) Enable the USART using the USART_Cmd() function.
(#) Enable the NVIC and the corresponding interrupt using the function
USART_ITConfig() if you need to use interrupt mode.
(#) When using the DMA mode:
(++) Configure the DMA using DMA_Init() function.
(++) Activate the needed channel Request using USART_DMACmd() function.
(#) Enable the DMA using the DMA_Cmd() function, when using DMA mode.
[..]
Refer to Multi-Processor, LIN, half-duplex, Smartcard, IrDA sub-sections
for more details.
@endverbatim
******************************************************************************
* @attention
*
* <h2><center>© COPYRIGHT 2015 STMicroelectronics</center></h2>
*
* Licensed under MCD-ST Liberty SW License Agreement V2, (the "License");
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at:
*
* http://www.st.com/software_license_agreement_liberty_v2
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
******************************************************************************
*/
/* Includes ------------------------------------------------------------------*/
#include "stm32f30x_usart.h"
#include "stm32f30x_rcc.h"
/** @addtogroup STM32F30x_StdPeriph_Driver
* @{
*/
/** @defgroup USART
* @brief USART driver modules
* @{
*/
/* Private typedef -----------------------------------------------------------*/
/* Private define ------------------------------------------------------------*/
/*!< USART CR1 register clear Mask ((~(uint32_t)0xFFFFE6F3)) */
#define CR1_CLEAR_MASK ((uint32_t)(USART_CR1_M | USART_CR1_PCE | \
USART_CR1_PS | USART_CR1_TE | \
USART_CR1_RE))
/*!< USART CR2 register clock bits clear Mask ((~(uint32_t)0xFFFFF0FF)) */
#define CR2_CLOCK_CLEAR_MASK ((uint32_t)(USART_CR2_CLKEN | USART_CR2_CPOL | \
USART_CR2_CPHA | USART_CR2_LBCL))
/*!< USART CR3 register clear Mask ((~(uint32_t)0xFFFFFCFF)) */
#define CR3_CLEAR_MASK ((uint32_t)(USART_CR3_RTSE | USART_CR3_CTSE))
/*!< USART Interrupts mask */
#define IT_MASK ((uint32_t)0x000000FF)
/* Private macro -------------------------------------------------------------*/
/* Private variables ---------------------------------------------------------*/
/* Private function prototypes -----------------------------------------------*/
/* Private functions ---------------------------------------------------------*/
/** @defgroup USART_Private_Functions
* @{
*/
/** @defgroup USART_Group1 Initialization and Configuration functions
* @brief Initialization and Configuration functions
*
@verbatim
===============================================================================
##### Initialization and Configuration functions #####
===============================================================================
[..]
This subsection provides a set of functions allowing to initialize the USART
in asynchronous and in synchronous modes.
(+) For the asynchronous mode only these parameters can be configured:
(++) Baud Rate.
(++) Word Length.
(++) Stop Bit.
(++) Parity: If the parity is enabled, then the MSB bit of the data written
in the data register is transmitted but is changed by the parity bit.
Depending on the frame length defined by the M bit (8-bits or 9-bits),
the possible USART frame formats are as listed in the following table:
[..]
+-------------------------------------------------------------+
| M bit | PCE bit | USART frame |
|---------------------|---------------------------------------|
| 0 | 0 | | SB | 8 bit data | STB | |
|---------|-----------|---------------------------------------|
| 0 | 1 | | SB | 7 bit data | PB | STB | |
|---------|-----------|---------------------------------------|
| 1 | 0 | | SB | 9 bit data | STB | |
|---------|-----------|---------------------------------------|
| 1 | 1 | | SB | 8 bit data | PB | STB | |
+-------------------------------------------------------------+
[..]
(++) Hardware flow control.
(++) Receiver/transmitter modes.
[..] The USART_Init() function follows the USART asynchronous configuration
procedure(details for the procedure are available in reference manual.
(+) For the synchronous mode in addition to the asynchronous mode parameters
these parameters should be also configured:
(++) USART Clock Enabled.
(++) USART polarity.
(++) USART phase.
(++) USART LastBit.
[..] These parameters can be configured using the USART_ClockInit() function.
@endverbatim
* @{
*/
/**
* @brief Deinitializes the USARTx peripheral registers to their default reset values.
* @param USARTx: Select the USART peripheral. This parameter can be one of the
* following values: USART1 or USART2 or USART3 or UART4 or UART5.
* @retval None
*/
void USART_DeInit(USART_TypeDef* USARTx)
{
/* Check the parameters */
assert_param(IS_USART_ALL_PERIPH(USARTx));
if (USARTx == USART1)
{
RCC_APB2PeriphResetCmd(RCC_APB2Periph_USART1, ENABLE);
RCC_APB2PeriphResetCmd(RCC_APB2Periph_USART1, DISABLE);
}
else if (USARTx == USART2)
{
RCC_APB1PeriphResetCmd(RCC_APB1Periph_USART2, ENABLE);
RCC_APB1PeriphResetCmd(RCC_APB1Periph_USART2, DISABLE);
}
else if (USARTx == USART3)
{
RCC_APB1PeriphResetCmd(RCC_APB1Periph_USART3, ENABLE);
RCC_APB1PeriphResetCmd(RCC_APB1Periph_USART3, DISABLE);
}
else if (USARTx == UART4)
{
RCC_APB1PeriphResetCmd(RCC_APB1Periph_UART4, ENABLE);
RCC_APB1PeriphResetCmd(RCC_APB1Periph_UART4, DISABLE);
}
else
{
if (USARTx == UART5)
{
RCC_APB1PeriphResetCmd(RCC_APB1Periph_UART5, ENABLE);
RCC_APB1PeriphResetCmd(RCC_APB1Periph_UART5, DISABLE);
}
}
}
/**
* @brief Initializes the USARTx peripheral according to the specified
* parameters in the USART_InitStruct .
* @param USARTx: Select the USART peripheral. This parameter can be one of the
* following values: USART1 or USART2 or USART3 or UART4 or UART5.
* @param USART_InitStruct: pointer to a USART_InitTypeDef structure
* that contains the configuration information for the specified USART peripheral.
* @retval None
*/
void USART_Init(USART_TypeDef* USARTx, USART_InitTypeDef* USART_InitStruct)
{
uint32_t divider = 0, apbclock = 0, tmpreg = 0;
RCC_ClocksTypeDef RCC_ClocksStatus;
/* Check the parameters */
assert_param(IS_USART_ALL_PERIPH(USARTx));
assert_param(IS_USART_BAUDRATE(USART_InitStruct->USART_BaudRate));
assert_param(IS_USART_WORD_LENGTH(USART_InitStruct->USART_WordLength));
assert_param(IS_USART_STOPBITS(USART_InitStruct->USART_StopBits));
assert_param(IS_USART_PARITY(USART_InitStruct->USART_Parity));
assert_param(IS_USART_MODE(USART_InitStruct->USART_Mode));
assert_param(IS_USART_HARDWARE_FLOW_CONTROL(USART_InitStruct->USART_HardwareFlowControl));
/* Disable USART */
USARTx->CR1 &= (uint32_t)~((uint32_t)USART_CR1_UE);
/*---------------------------- USART CR2 Configuration -----------------------*/
tmpreg = USARTx->CR2;
/* Clear STOP[13:12] bits */
tmpreg &= (uint32_t)~((uint32_t)USART_CR2_STOP);
/* Configure the USART Stop Bits, Clock, CPOL, CPHA and LastBit ------------*/
/* Set STOP[13:12] bits according to USART_StopBits value */
tmpreg |= (uint32_t)USART_InitStruct->USART_StopBits;
/* Write to USART CR2 */
USARTx->CR2 = tmpreg;
/*---------------------------- USART CR1 Configuration -----------------------*/
tmpreg = USARTx->CR1;
/* Clear M, PCE, PS, TE and RE bits */
tmpreg &= (uint32_t)~((uint32_t)CR1_CLEAR_MASK);
/* Configure the USART Word Length, Parity and mode ----------------------- */
/* Set the M bits according to USART_WordLength value */
/* Set PCE and PS bits according to USART_Parity value */
/* Set TE and RE bits according to USART_Mode value */
tmpreg |= (uint32_t)USART_InitStruct->USART_WordLength | USART_InitStruct->USART_Parity |
USART_InitStruct->USART_Mode;
/* Write to USART CR1 */
USARTx->CR1 = tmpreg;
/*---------------------------- USART CR3 Configuration -----------------------*/
tmpreg = USARTx->CR3;
/* Clear CTSE and RTSE bits */
tmpreg &= (uint32_t)~((uint32_t)CR3_CLEAR_MASK);
/* Configure the USART HFC -------------------------------------------------*/
/* Set CTSE and RTSE bits according to USART_HardwareFlowControl value */
tmpreg |= USART_InitStruct->USART_HardwareFlowControl;
/* Write to USART CR3 */
USARTx->CR3 = tmpreg;
/*---------------------------- USART BRR Configuration -----------------------*/
/* Configure the USART Baud Rate -------------------------------------------*/
RCC_GetClocksFreq(&RCC_ClocksStatus);
if (USARTx == USART1)
{
apbclock = RCC_ClocksStatus.USART1CLK_Frequency;
}
else if (USARTx == USART2)
{
apbclock = RCC_ClocksStatus.USART2CLK_Frequency;
}
else if (USARTx == USART3)
{
apbclock = RCC_ClocksStatus.USART3CLK_Frequency;
}
else if (USARTx == UART4)
{
apbclock = RCC_ClocksStatus.UART4CLK_Frequency;
}
else
{
apbclock = RCC_ClocksStatus.UART5CLK_Frequency;
}
/* Determine the integer part */
if ((USARTx->CR1 & USART_CR1_OVER8) != 0)
{
/* (divider * 10) computing in case Oversampling mode is 8 Samples */
divider = (uint32_t)((2 * apbclock) / (USART_InitStruct->USART_BaudRate));
tmpreg = (uint32_t)((2 * apbclock) % (USART_InitStruct->USART_BaudRate));
}
else /* if ((USARTx->CR1 & CR1_OVER8_Set) == 0) */
{
/* (divider * 10) computing in case Oversampling mode is 16 Samples */
divider = (uint32_t)((apbclock) / (USART_InitStruct->USART_BaudRate));
tmpreg = (uint32_t)((apbclock) % (USART_InitStruct->USART_BaudRate));
}
/* round the divider : if fractional part i greater than 0.5 increment divider */
if (tmpreg >= (USART_InitStruct->USART_BaudRate) / 2)
{
divider++;
}
/* Implement the divider in case Oversampling mode is 8 Samples */
if ((USARTx->CR1 & USART_CR1_OVER8) != 0)
{
/* get the LSB of divider and shift it to the right by 1 bit */
tmpreg = (divider & (uint16_t)0x000F) >> 1;
/* update the divider value */
divider = (divider & (uint16_t)0xFFF0) | tmpreg;
}
/* Write to USART BRR */
USARTx->BRR = (uint16_t)divider;
}
/**
* @brief Fills each USART_InitStruct member with its default value.
* @param USART_InitStruct: pointer to a USART_InitTypeDef structure
* which will be initialized.
* @retval None
*/
void USART_StructInit(USART_InitTypeDef* USART_InitStruct)
{
/* USART_InitStruct members default value */
USART_InitStruct->USART_BaudRate = 9600;
USART_InitStruct->USART_WordLength = USART_WordLength_8b;
USART_InitStruct->USART_StopBits = USART_StopBits_1;
USART_InitStruct->USART_Parity = USART_Parity_No ;
USART_InitStruct->USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
USART_InitStruct->USART_HardwareFlowControl = USART_HardwareFlowControl_None;
}
/**
* @brief Initializes the USARTx peripheral Clock according to the
* specified parameters in the USART_ClockInitStruct.
* @param USARTx: Select the USART peripheral. This parameter can be one of the
* following values: USART1 or USART2 or USART3.
* @param USART_ClockInitStruct: pointer to a USART_ClockInitTypeDef
* structure that contains the configuration information for the specified
* USART peripheral.
* @retval None
*/
void USART_ClockInit(USART_TypeDef* USARTx, USART_ClockInitTypeDef* USART_ClockInitStruct)
{
uint32_t tmpreg = 0;
/* Check the parameters */
assert_param(IS_USART_123_PERIPH(USARTx));
assert_param(IS_USART_CLOCK(USART_ClockInitStruct->USART_Clock));
assert_param(IS_USART_CPOL(USART_ClockInitStruct->USART_CPOL));
assert_param(IS_USART_CPHA(USART_ClockInitStruct->USART_CPHA));
assert_param(IS_USART_LASTBIT(USART_ClockInitStruct->USART_LastBit));
/*---------------------------- USART CR2 Configuration -----------------------*/
tmpreg = USARTx->CR2;
/* Clear CLKEN, CPOL, CPHA, LBCL and SSM bits */
tmpreg &= (uint32_t)~((uint32_t)CR2_CLOCK_CLEAR_MASK);
/* Configure the USART Clock, CPOL, CPHA, LastBit and SSM ------------*/
/* Set CLKEN bit according to USART_Clock value */
/* Set CPOL bit according to USART_CPOL value */
/* Set CPHA bit according to USART_CPHA value */
/* Set LBCL bit according to USART_LastBit value */
tmpreg |= (uint32_t)(USART_ClockInitStruct->USART_Clock | USART_ClockInitStruct->USART_CPOL |
USART_ClockInitStruct->USART_CPHA | USART_ClockInitStruct->USART_LastBit);
/* Write to USART CR2 */
USARTx->CR2 = tmpreg;
}
/**
* @brief Fills each USART_ClockInitStruct member with its default value.
* @param USART_ClockInitStruct: pointer to a USART_ClockInitTypeDef
* structure which will be initialized.
* @retval None
*/
void USART_ClockStructInit(USART_ClockInitTypeDef* USART_ClockInitStruct)
{
/* USART_ClockInitStruct members default value */
USART_ClockInitStruct->USART_Clock = USART_Clock_Disable;
USART_ClockInitStruct->USART_CPOL = USART_CPOL_Low;
USART_ClockInitStruct->USART_CPHA = USART_CPHA_1Edge;
USART_ClockInitStruct->USART_LastBit = USART_LastBit_Disable;
}
/**
* @brief Enables or disables the specified USART peripheral.
* @param USARTx: Select the USART peripheral. This parameter can be one of the
* following values: USART1 or USART2 or USART3 or UART4 or UART5.
* @param NewState: new state of the USARTx peripheral.
* This parameter can be: ENABLE or DISABLE.
* @retval None
*/
void USART_Cmd(USART_TypeDef* USARTx, FunctionalState NewState)
{
/* Check the parameters */
assert_param(IS_USART_ALL_PERIPH(USARTx));
assert_param(IS_FUNCTIONAL_STATE(NewState));
if (NewState != DISABLE)
{
/* Enable the selected USART by setting the UE bit in the CR1 register */
USARTx->CR1 |= USART_CR1_UE;
}
else
{
/* Disable the selected USART by clearing the UE bit in the CR1 register */
USARTx->CR1 &= (uint32_t)~((uint32_t)USART_CR1_UE);
}
}
/**
* @brief Enables or disables the USART's transmitter or receiver.
* @param USARTx: Select the USART peripheral. This parameter can be one of the
* following values: USART1 or USART2 or USART3 or UART4 or UART5.
* @param USART_Direction: specifies the USART direction.
* This parameter can be any combination of the following values:
* @arg USART_Mode_Tx: USART Transmitter
* @arg USART_Mode_Rx: USART Receiver
* @param NewState: new state of the USART transfer direction.
* This parameter can be: ENABLE or DISABLE.
* @retval None
*/
void USART_DirectionModeCmd(USART_TypeDef* USARTx, uint32_t USART_DirectionMode, FunctionalState NewState)
{
/* Check the parameters */
assert_param(IS_USART_ALL_PERIPH(USARTx));
assert_param(IS_USART_MODE(USART_DirectionMode));
assert_param(IS_FUNCTIONAL_STATE(NewState));
if (NewState != DISABLE)
{
/* Enable the USART's transfer interface by setting the TE and/or RE bits
in the USART CR1 register */
USARTx->CR1 |= USART_DirectionMode;
}
else
{
/* Disable the USART's transfer interface by clearing the TE and/or RE bits
in the USART CR3 register */
USARTx->CR1 &= (uint32_t)~USART_DirectionMode;
}
}
/**
* @brief Enables or disables the USART's 8x oversampling mode.
* @param USARTx: Select the USART peripheral. This parameter can be one of the
* following values: USART1 or USART2 or USART3 or UART4 or UART5.
* @param NewState: new state of the USART 8x oversampling mode.
* This parameter can be: ENABLE or DISABLE.
* @note
* This function has to be called before calling USART_Init()
* function in order to have correct baudrate Divider value.
* @retval None
*/
void USART_OverSampling8Cmd(USART_TypeDef* USARTx, FunctionalState NewState)
{
/* Check the parameters */
assert_param(IS_USART_ALL_PERIPH(USARTx));
assert_param(IS_FUNCTIONAL_STATE(NewState));
if (NewState != DISABLE)
{
/* Enable the 8x Oversampling mode by setting the OVER8 bit in the CR1 register */
USARTx->CR1 |= USART_CR1_OVER8;
}
else
{
/* Disable the 8x Oversampling mode by clearing the OVER8 bit in the CR1 register */
USARTx->CR1 &= (uint32_t)~((uint32_t)USART_CR1_OVER8);
}
}
/**
* @brief Enables or disables the USART's one bit sampling method.
* @param USARTx: Select the USART peripheral. This parameter can be one of the
* following values: USART1 or USART2 or USART3 or UART4 or UART5.
* @param NewState: new state of the USART one bit sampling method.
* This parameter can be: ENABLE or DISABLE.
* @note
* This function has to be called before calling USART_Cmd() function.
* @retval None
*/
void USART_OneBitMethodCmd(USART_TypeDef* USARTx, FunctionalState NewState)
{
/* Check the parameters */
assert_param(IS_USART_ALL_PERIPH(USARTx));
assert_param(IS_FUNCTIONAL_STATE(NewState));
if (NewState != DISABLE)
{
/* Enable the one bit method by setting the ONEBIT bit in the CR3 register */
USARTx->CR3 |= USART_CR3_ONEBIT;
}
else
{
/* Disable the one bit method by clearing the ONEBIT bit in the CR3 register */
USARTx->CR3 &= (uint32_t)~((uint32_t)USART_CR3_ONEBIT);
}
}
/**
* @brief Enables or disables the USART's most significant bit first
* transmitted/received following the start bit.
* @param USARTx: Select the USART peripheral. This parameter can be one of the
* following values: USART1 or USART2 or USART3 or UART4 or UART5.
* @param NewState: new state of the USART most significant bit first
* transmitted/received following the start bit.
* This parameter can be: ENABLE or DISABLE.
* @note
* This function has to be called before calling USART_Cmd() function.
* @retval None
*/
void USART_MSBFirstCmd(USART_TypeDef* USARTx, FunctionalState NewState)
{
/* Check the parameters */
assert_param(IS_USART_ALL_PERIPH(USARTx));
assert_param(IS_FUNCTIONAL_STATE(NewState));
if (NewState != DISABLE)
{
/* Enable the most significant bit first transmitted/received following the
start bit by setting the MSBFIRST bit in the CR2 register */
USARTx->CR2 |= USART_CR2_MSBFIRST;
}
else
{
/* Disable the most significant bit first transmitted/received following the
start bit by clearing the MSBFIRST bit in the CR2 register */
USARTx->CR2 &= (uint32_t)~((uint32_t)USART_CR2_MSBFIRST);
}
}
/**
* @brief Enables or disables the binary data inversion.
* @param USARTx: Select the USART peripheral. This parameter can be one of the
* following values: USART1 or USART2 or USART3 or UART4 or UART5.
* @param NewState: new defined levels for the USART data.
* This parameter can be: ENABLE or DISABLE.
* @arg ENABLE: Logical data from the data register are send/received in negative
* logic. (1=L, 0=H). The parity bit is also inverted.
* @arg DISABLE: Logical data from the data register are send/received in positive
* logic. (1=H, 0=L)
* @note
* This function has to be called before calling USART_Cmd() function.
* @retval None
*/
void USART_DataInvCmd(USART_TypeDef* USARTx, FunctionalState NewState)
{
/* Check the parameters */
assert_param(IS_USART_ALL_PERIPH(USARTx));
assert_param(IS_FUNCTIONAL_STATE(NewState));
if (NewState != DISABLE)
{
/* Enable the binary data inversion feature by setting the DATAINV bit in
the CR2 register */
USARTx->CR2 |= USART_CR2_DATAINV;
}
else
{
/* Disable the binary data inversion feature by clearing the DATAINV bit in
the CR2 register */
USARTx->CR2 &= (uint32_t)~((uint32_t)USART_CR2_DATAINV);
}
}
/**
* @brief Enables or disables the Pin(s) active level inversion.
* @param USARTx: Select the USART peripheral. This parameter can be one of the
* following values: USART1 or USART2 or USART3 or UART4 or UART5.
* @param USART_InvPin: specifies the USART pin(s) to invert.
* This parameter can be any combination of the following values:
* @arg USART_InvPin_Tx: USART Tx pin active level inversion.
* @arg USART_InvPin_Rx: USART Rx pin active level inversion.
* @param NewState: new active level status for the USART pin(s).
* This parameter can be: ENABLE or DISABLE.
* - ENABLE: pin(s) signal values are inverted (Vdd =0, Gnd =1).
* - DISABLE: pin(s) signal works using the standard logic levels (Vdd =1, Gnd =0).
* @note
* This function has to be called before calling USART_Cmd() function.
* @retval None
*/
void USART_InvPinCmd(USART_TypeDef* USARTx, uint32_t USART_InvPin, FunctionalState NewState)
{
/* Check the parameters */
assert_param(IS_USART_ALL_PERIPH(USARTx));
assert_param(IS_USART_INVERSTION_PIN(USART_InvPin));
assert_param(IS_FUNCTIONAL_STATE(NewState));
if (NewState != DISABLE)
{
/* Enable the active level inversion for selected pins by setting the TXINV
and/or RXINV bits in the USART CR2 register */
USARTx->CR2 |= USART_InvPin;
}
else
{
/* Disable the active level inversion for selected requests by clearing the
TXINV and/or RXINV bits in the USART CR2 register */
USARTx->CR2 &= (uint32_t)~USART_InvPin;
}
}
/**
* @brief Enables or disables the swap Tx/Rx pins.
* @param USARTx: Select the USART peripheral. This parameter can be one of the
* following values: USART1 or USART2 or USART3 or UART4 or UART5.
* @param NewState: new state of the USARTx TX/RX pins pinout.
* This parameter can be: ENABLE or DISABLE.
* @arg ENABLE: The TX and RX pins functions are swapped.
* @arg DISABLE: TX/RX pins are used as defined in standard pinout
* @note
* This function has to be called before calling USART_Cmd() function.
* @retval None
*/
void USART_SWAPPinCmd(USART_TypeDef* USARTx, FunctionalState NewState)
{
/* Check the parameters */
assert_param(IS_USART_ALL_PERIPH(USARTx));
assert_param(IS_FUNCTIONAL_STATE(NewState));
if (NewState != DISABLE)
{
/* Enable the SWAP feature by setting the SWAP bit in the CR2 register */
USARTx->CR2 |= USART_CR2_SWAP;
}
else
{
/* Disable the SWAP feature by clearing the SWAP bit in the CR2 register */
USARTx->CR2 &= (uint32_t)~((uint32_t)USART_CR2_SWAP);
}
}
/**
* @brief Enables or disables the receiver Time Out feature.
* @param USARTx: Select the USART peripheral. This parameter can be one of the
* following values: USART1 or USART2 or USART3 or UART4 or UART5.
* @param NewState: new state of the USARTx receiver Time Out.
* This parameter can be: ENABLE or DISABLE.
* @retval None
*/
void USART_ReceiverTimeOutCmd(USART_TypeDef* USARTx, FunctionalState NewState)
{
/* Check the parameters */
assert_param(IS_USART_ALL_PERIPH(USARTx));
assert_param(IS_FUNCTIONAL_STATE(NewState));
if (NewState != DISABLE)
{
/* Enable the receiver time out feature by setting the RTOEN bit in the CR2
register */
USARTx->CR2 |= USART_CR2_RTOEN;
}
else
{
/* Disable the receiver time out feature by clearing the RTOEN bit in the CR2
register */
USARTx->CR2 &= (uint32_t)~((uint32_t)USART_CR2_RTOEN);
}
}
/**
* @brief Sets the receiver Time Out value.
* @param USARTx: Select the USART peripheral. This parameter can be one of the
* following values: USART1 or USART2 or USART3 or UART4 or UART5.
* @param USART_ReceiverTimeOut: specifies the Receiver Time Out value.
* @retval None
*/
void USART_SetReceiverTimeOut(USART_TypeDef* USARTx, uint32_t USART_ReceiverTimeOut)
{
/* Check the parameters */
assert_param(IS_USART_ALL_PERIPH(USARTx));
assert_param(IS_USART_TIMEOUT(USART_ReceiverTimeOut));
/* Clear the receiver Time Out value by clearing the RTO[23:0] bits in the RTOR
register */
USARTx->RTOR &= (uint32_t)~((uint32_t)USART_RTOR_RTO);
/* Set the receiver Time Out value by setting the RTO[23:0] bits in the RTOR
register */
USARTx->RTOR |= USART_ReceiverTimeOut;
}
/**
* @brief Sets the system clock prescaler.
* @param USARTx: Select the USART peripheral. This parameter can be one of the
* following values: USART1 or USART2 or USART3 or UART4 or UART5.
* @param USART_Prescaler: specifies the prescaler clock.
* @note
* This function has to be called before calling USART_Cmd() function.
* @retval None
*/
void USART_SetPrescaler(USART_TypeDef* USARTx, uint8_t USART_Prescaler)
{
/* Check the parameters */
assert_param(IS_USART_ALL_PERIPH(USARTx));
/* Clear the USART prescaler */
USARTx->GTPR &= USART_GTPR_GT;
/* Set the USART prescaler */
USARTx->GTPR |= USART_Prescaler;
}
/**
* @}
*/
/** @defgroup USART_Group2 STOP Mode functions
* @brief STOP Mode functions
*
@verbatim
===============================================================================
##### STOP Mode functions #####
===============================================================================
[..] This subsection provides a set of functions allowing to manage
WakeUp from STOP mode.
[..] The USART is able to WakeUp from Stop Mode if USART clock is set to HSI
or LSI.
[..] The WakeUp source is configured by calling USART_StopModeWakeUpSourceConfig()
function.
[..] After configuring the source of WakeUp and before entering in Stop Mode
USART_STOPModeCmd() function should be called to allow USART WakeUp.
@endverbatim
* @{
*/
/**
* @brief Enables or disables the specified USART peripheral in STOP Mode.
* @param USARTx: Select the USART peripheral. This parameter can be one of the
* following values: USART1 or USART2 or USART3 or UART4 or UART5.
* @param NewState: new state of the USARTx peripheral state in stop mode.
* This parameter can be: ENABLE or DISABLE.
* @note
* This function has to be called when USART clock is set to HSI or LSE.
* @retval None
*/
void USART_STOPModeCmd(USART_TypeDef* USARTx, FunctionalState NewState)
{
/* Check the parameters */
assert_param(IS_USART_ALL_PERIPH(USARTx));
assert_param(IS_FUNCTIONAL_STATE(NewState));
if (NewState != DISABLE)
{
/* Enable the selected USART in STOP mode by setting the UESM bit in the CR1
register */
USARTx->CR1 |= USART_CR1_UESM;
}
else
{
/* Disable the selected USART in STOP mode by clearing the UE bit in the CR1
register */
USARTx->CR1 &= (uint32_t)~((uint32_t)USART_CR1_UESM);
}
}
/**
* @brief Selects the USART WakeUp method form stop mode.
* @param USARTx: Select the USART peripheral. This parameter can be one of the
* following values: USART1 or USART2 or USART3 or UART4 or UART5.
* @param USART_WakeUp: specifies the selected USART wakeup method.
* This parameter can be one of the following values:
* @arg USART_WakeUpSource_AddressMatch: WUF active on address match.
* @arg USART_WakeUpSource_StartBit: WUF active on Start bit detection.
* @arg USART_WakeUpSource_RXNE: WUF active on RXNE.
* @note
* This function has to be called before calling USART_Cmd() function.
* @retval None
*/
void USART_StopModeWakeUpSourceConfig(USART_TypeDef* USARTx, uint32_t USART_WakeUpSource)
{
/* Check the parameters */
assert_param(IS_USART_ALL_PERIPH(USARTx));
assert_param(IS_USART_STOPMODE_WAKEUPSOURCE(USART_WakeUpSource));
USARTx->CR3 &= (uint32_t)~((uint32_t)USART_CR3_WUS);
USARTx->CR3 |= USART_WakeUpSource;
}
/**
* @}
*/
/** @defgroup USART_Group3 AutoBaudRate functions
* @brief AutoBaudRate functions
*
@verbatim
===============================================================================
##### AutoBaudRate functions #####
===============================================================================
[..] This subsection provides a set of functions allowing to manage
the AutoBaudRate detections.
[..] Before Enabling AutoBaudRate detection using USART_AutoBaudRateCmd ()
The character patterns used to calculate baudrate must be chosen by calling
USART_AutoBaudRateConfig() function. These function take as parameter :
(#)USART_AutoBaudRate_StartBit : any character starting with a bit 1.
(#)USART_AutoBaudRate_FallingEdge : any character starting with a 10xx bit pattern.
[..] At any later time, another request for AutoBaudRate detection can be performed
using USART_RequestCmd() function.
[..] The AutoBaudRate detection is monitored by the status of ABRF flag which indicate
that the AutoBaudRate detection is completed. In addition to ABRF flag, the ABRE flag
indicate that this procedure is completed without success. USART_GetFlagStatus ()
function should be used to monitor the status of these flags.
@endverbatim
* @{
*/
/**
* @brief Enables or disables the Auto Baud Rate.
* @param USARTx: Select the USART peripheral. This parameter can be one of the
* following values: USART1 or USART2 or USART3 or UART4 or UART5.
* @param NewState: new state of the USARTx auto baud rate.
* This parameter can be: ENABLE or DISABLE.
* @retval None
*/
void USART_AutoBaudRateCmd(USART_TypeDef* USARTx, FunctionalState NewState)
{
/* Check the parameters */
assert_param(IS_USART_ALL_PERIPH(USARTx));
assert_param(IS_FUNCTIONAL_STATE(NewState));
if (NewState != DISABLE)
{
/* Enable the auto baud rate feature by setting the ABREN bit in the CR2
register */
USARTx->CR2 |= USART_CR2_ABREN;
}
else
{
/* Disable the auto baud rate feature by clearing the ABREN bit in the CR2
register */
USARTx->CR2 &= (uint32_t)~((uint32_t)USART_CR2_ABREN);
}
}
/**
* @brief Selects the USART auto baud rate method.
* @param USARTx: Select the USART peripheral. This parameter can be one of the
* following values: USART1 or USART2 or USART3 or UART4 or UART5.
* @param USART_AutoBaudRate: specifies the selected USART auto baud rate method.
* This parameter can be one of the following values:
* @arg USART_AutoBaudRate_StartBit: Start Bit duration measurement.
* @arg USART_AutoBaudRate_FallingEdge: Falling edge to falling edge measurement.
* @arg USART_AutoBaudRate_0x7FFrame: 0x7F frame.
* @arg USART_AutoBaudRate_0x55Frame: 0x55 frame.
* @note
* This function has to be called before calling USART_Cmd() function.
* @retval None
*/
void USART_AutoBaudRateConfig(USART_TypeDef* USARTx, uint32_t USART_AutoBaudRate)
{
/* Check the parameters */
assert_param(IS_USART_ALL_PERIPH(USARTx));
assert_param(IS_USART_AUTOBAUDRATE_MODE(USART_AutoBaudRate));
USARTx->CR2 &= (uint32_t)~((uint32_t)USART_CR2_ABRMODE);
USARTx->CR2 |= USART_AutoBaudRate;
}
/**
* @}
*/
/** @defgroup USART_Group4 Data transfers functions
* @brief Data transfers functions
*
@verbatim
===============================================================================
##### Data transfers functions #####
===============================================================================
[..] This subsection provides a set of functions allowing to manage
the USART data transfers.
[..] During an USART reception, data shifts in least significant bit first
through the RX pin. When a transmission is taking place, a write instruction to
the USART_TDR register stores the data in the shift register.
[..] The read access of the USART_RDR register can be done using
the USART_ReceiveData() function and returns the RDR value.
Whereas a write access to the USART_TDR can be done using USART_SendData()
function and stores the written data into TDR.
@endverbatim
* @{
*/
/**
* @brief Transmits single data through the USARTx peripheral.
* @param USARTx: Select the USART peripheral. This parameter can be one of the
* following values: USART1 or USART2 or USART3 or UART4 or UART5.
* @param Data: the data to transmit.
* @retval None
*/
void USART_SendData(USART_TypeDef* USARTx, uint16_t Data)
{
/* Check the parameters */
assert_param(IS_USART_ALL_PERIPH(USARTx));
assert_param(IS_USART_DATA(Data));
/* Transmit Data */
USARTx->TDR = (Data & (uint16_t)0x01FF);
}
/**
* @brief Returns the most recent received data by the USARTx peripheral.
* @param USARTx: Select the USART peripheral. This parameter can be one of the
* following values: USART1 or USART2 or USART3 or UART4 or UART5.
* @retval The received data.
*/
uint16_t USART_ReceiveData(USART_TypeDef* USARTx)
{
/* Check the parameters */
assert_param(IS_USART_ALL_PERIPH(USARTx));
/* Receive Data */
return (uint16_t)(USARTx->RDR & (uint16_t)0x01FF);
}
/**
* @}
*/
/** @defgroup USART_Group5 MultiProcessor Communication functions
* @brief Multi-Processor Communication functions
*
@verbatim
===============================================================================
##### Multi-Processor Communication functions #####
===============================================================================
[..] This subsection provides a set of functions allowing to manage the USART
multiprocessor communication.
[..] For instance one of the USARTs can be the master, its TX output is
connected to the RX input of the other USART. The others are slaves,
their respective TX outputs are logically ANDed together and connected
to the RX input of the master. USART multiprocessor communication is
possible through the following procedure:
(#) Program the Baud rate, Word length = 9 bits, Stop bits, Parity,
Mode transmitter or Mode receiver and hardware flow control values
using the USART_Init() function.
(#) Configures the USART address using the USART_SetAddress() function.
(#) Configures the wake up methode (USART_WakeUp_IdleLine or
USART_WakeUp_AddressMark) using USART_WakeUpConfig() function only
for the slaves.
(#) Enable the USART using the USART_Cmd() function.
(#) Enter the USART slaves in mute mode using USART_ReceiverWakeUpCmd()
function.
[..] The USART Slave exit from mute mode when receive the wake up condition.
@endverbatim
* @{
*/
/**
* @brief Sets the address of the USART node.
* @param USARTx: Select the USART peripheral. This parameter can be one of the
* following values: USART1 or USART2 or USART3 or UART4 or UART5.
* @param USART_Address: Indicates the address of the USART node.
* @retval None
*/
void USART_SetAddress(USART_TypeDef* USARTx, uint8_t USART_Address)
{
/* Check the parameters */
assert_param(IS_USART_ALL_PERIPH(USARTx));
/* Clear the USART address */
USARTx->CR2 &= (uint32_t)~((uint32_t)USART_CR2_ADD);
/* Set the USART address node */
USARTx->CR2 |=((uint32_t)USART_Address << (uint32_t)0x18);
}
/**
* @brief Enables or disables the USART's mute mode.
* @param USARTx: Select the USART peripheral. This parameter can be one of the
* following values: USART1 or USART2 or USART3 or UART4 or UART5.
* @param NewState: new state of the USART mute mode.
* This parameter can be: ENABLE or DISABLE.
* @retval None
*/
void USART_MuteModeCmd(USART_TypeDef* USARTx, FunctionalState NewState)
{
/* Check the parameters */
assert_param(IS_USART_ALL_PERIPH(USARTx));
assert_param(IS_FUNCTIONAL_STATE(NewState));
if (NewState != DISABLE)
{
/* Enable the USART mute mode by setting the MME bit in the CR1 register */
USARTx->CR1 |= USART_CR1_MME;
}
else
{
/* Disable the USART mute mode by clearing the MME bit in the CR1 register */
USARTx->CR1 &= (uint32_t)~((uint32_t)USART_CR1_MME);
}
}
/**
* @brief Selects the USART WakeUp method from mute mode.
* @param USARTx: Select the USART peripheral. This parameter can be one of the
* following values: USART1 or USART2 or USART3 or UART4 or UART5.
* @param USART_WakeUp: specifies the USART wakeup method.
* This parameter can be one of the following values:
* @arg USART_WakeUp_IdleLine: WakeUp by an idle line detection
* @arg USART_WakeUp_AddressMark: WakeUp by an address mark
* @retval None
*/
void USART_MuteModeWakeUpConfig(USART_TypeDef* USARTx, uint32_t USART_WakeUp)
{
/* Check the parameters */
assert_param(IS_USART_ALL_PERIPH(USARTx));
assert_param(IS_USART_MUTEMODE_WAKEUP(USART_WakeUp));
USARTx->CR1 &= (uint32_t)~((uint32_t)USART_CR1_WAKE);
USARTx->CR1 |= USART_WakeUp;
}
/**
* @brief Configure the USART Address detection length.
* @param USARTx: Select the USART peripheral. This parameter can be one of the
* following values: USART1 or USART2 or USART3 or UART4 or UART5.
* @param USART_AddressLength: specifies the USART address length detection.
* This parameter can be one of the following values:
* @arg USART_AddressLength_4b: 4-bit address length detection
* @arg USART_AddressLength_7b: 7-bit address length detection
* @retval None
*/
void USART_AddressDetectionConfig(USART_TypeDef* USARTx, uint32_t USART_AddressLength)
{
/* Check the parameters */
assert_param(IS_USART_ALL_PERIPH(USARTx));
assert_param(IS_USART_ADDRESS_DETECTION(USART_AddressLength));
USARTx->CR2 &= (uint32_t)~((uint32_t)USART_CR2_ADDM7);
USARTx->CR2 |= USART_AddressLength;
}
/**
* @}
*/
/** @defgroup USART_Group6 LIN mode functions
* @brief LIN mode functions
*
@verbatim
===============================================================================
##### LIN mode functions #####
===============================================================================
[..] This subsection provides a set of functions allowing to manage the USART
LIN Mode communication.
[..] In LIN mode, 8-bit data format with 1 stop bit is required in accordance
with the LIN standard.
[..] Only this LIN Feature is supported by the USART IP:
(+) LIN Master Synchronous Break send capability and LIN slave break
detection capability : 13-bit break generation and 10/11 bit break
detection.
[..] USART LIN Master transmitter communication is possible through the
following procedure:
(#) Program the Baud rate, Word length = 8bits, Stop bits = 1bit, Parity,
Mode transmitter or Mode receiver and hardware flow control values
using the USART_Init() function.
(#) Enable the LIN mode using the USART_LINCmd() function.
(#) Enable the USART using the USART_Cmd() function.
(#) Send the break character using USART_SendBreak() function.
[..] USART LIN Master receiver communication is possible through the
following procedure:
(#) Program the Baud rate, Word length = 8bits, Stop bits = 1bit, Parity,
Mode transmitter or Mode receiver and hardware flow control values
using the USART_Init() function.
(#) Configures the break detection length
using the USART_LINBreakDetectLengthConfig() function.
(#) Enable the LIN mode using the USART_LINCmd() function.
(#) Enable the USART using the USART_Cmd() function.
[..]
(@) In LIN mode, the following bits must be kept cleared:
(+@) CLKEN in the USART_CR2 register.
(+@) STOP[1:0], SCEN, HDSEL and IREN in the USART_CR3 register.
@endverbatim
* @{
*/
/**
* @brief Sets the USART LIN Break detection length.
* @param USARTx: Select the USART peripheral. This parameter can be one of the
* following values: USART1 or USART2 or USART3 or UART4 or UART5.
* @param USART_LINBreakDetectLength: specifies the LIN break detection length.
* This parameter can be one of the following values:
* @arg USART_LINBreakDetectLength_10b: 10-bit break detection
* @arg USART_LINBreakDetectLength_11b: 11-bit break detection
* @retval None
*/
void USART_LINBreakDetectLengthConfig(USART_TypeDef* USARTx, uint32_t USART_LINBreakDetectLength)
{
/* Check the parameters */
assert_param(IS_USART_ALL_PERIPH(USARTx));
assert_param(IS_USART_LIN_BREAK_DETECT_LENGTH(USART_LINBreakDetectLength));
USARTx->CR2 &= (uint32_t)~((uint32_t)USART_CR2_LBDL);
USARTx->CR2 |= USART_LINBreakDetectLength;
}
/**
* @brief Enables or disables the USART's LIN mode.
* @param USARTx: Select the USART peripheral. This parameter can be one of the
* following values: USART1 or USART2 or USART3 or UART4 or UART5.
* @param NewState: new state of the USART LIN mode.
* This parameter can be: ENABLE or DISABLE.
* @retval None
*/
void USART_LINCmd(USART_TypeDef* USARTx, FunctionalState NewState)
{
/* Check the parameters */
assert_param(IS_USART_ALL_PERIPH(USARTx));
assert_param(IS_FUNCTIONAL_STATE(NewState));
if (NewState != DISABLE)
{
/* Enable the LIN mode by setting the LINEN bit in the CR2 register */
USARTx->CR2 |= USART_CR2_LINEN;
}
else
{
/* Disable the LIN mode by clearing the LINEN bit in the CR2 register */
USARTx->CR2 &= (uint32_t)~((uint32_t)USART_CR2_LINEN);
}
}
/**
* @}
*/
/** @defgroup USART_Group7 Halfduplex mode function
* @brief Half-duplex mode function
*
@verbatim
===============================================================================
##### Half-duplex mode function #####
===============================================================================
[..] This subsection provides a set of functions allowing to manage the USART
Half-duplex communication.
[..] The USART can be configured to follow a single-wire half-duplex protocol
where the TX and RX lines are internally connected.
[..] USART Half duplex communication is possible through the following procedure:
(#) Program the Baud rate, Word length, Stop bits, Parity, Mode transmitter
or Mode receiver and hardware flow control values using the USART_Init()
function.
(#) Configures the USART address using the USART_SetAddress() function.
(#) Enable the half duplex mode using USART_HalfDuplexCmd() function.
(#) Enable the USART using the USART_Cmd() function.
[..]
(@) The RX pin is no longer used.
(@) In Half-duplex mode the following bits must be kept cleared:
(+@) LINEN and CLKEN bits in the USART_CR2 register.
(+@) SCEN and IREN bits in the USART_CR3 register.
@endverbatim
* @{
*/
/**
* @brief Enables or disables the USART's Half Duplex communication.
* @param USARTx: Select the USART peripheral. This parameter can be one of the
* following values: USART1 or USART2 or USART3 or UART4 or UART5.
* @param NewState: new state of the USART Communication.
* This parameter can be: ENABLE or DISABLE.
* @retval None
*/
void USART_HalfDuplexCmd(USART_TypeDef* USARTx, FunctionalState NewState)
{
/* Check the parameters */
assert_param(IS_USART_ALL_PERIPH(USARTx));
assert_param(IS_FUNCTIONAL_STATE(NewState));
if (NewState != DISABLE)
{
/* Enable the Half-Duplex mode by setting the HDSEL bit in the CR3 register */
USARTx->CR3 |= USART_CR3_HDSEL;
}
else
{
/* Disable the Half-Duplex mode by clearing the HDSEL bit in the CR3 register */
USARTx->CR3 &= (uint32_t)~((uint32_t)USART_CR3_HDSEL);
}
}
/**
* @}
*/
/** @defgroup USART_Group8 Smartcard mode functions
* @brief Smartcard mode functions
*
@verbatim
===============================================================================
##### Smartcard mode functions #####
===============================================================================
[..] This subsection provides a set of functions allowing to manage the USART
Smartcard communication.
[..] The Smartcard interface is designed to support asynchronous protocol
Smartcards as defined in the ISO 7816-3 standard. The USART can provide
a clock to the smartcard through the SCLK output. In smartcard mode,
SCLK is not associated to the communication but is simply derived from
the internal peripheral input clock through a 5-bit prescaler.
[..] Smartcard communication is possible through the following procedure:
(#) Configures the Smartcard Prescaler using the USART_SetPrescaler()
function.
(#) Configures the Smartcard Guard Time using the USART_SetGuardTime()
function.
(#) Program the USART clock using the USART_ClockInit() function as following:
(++) USART Clock enabled.
(++) USART CPOL Low.
(++) USART CPHA on first edge.
(++) USART Last Bit Clock Enabled.
(#) Program the Smartcard interface using the USART_Init() function as
following:
(++) Word Length = 9 Bits.
(++) 1.5 Stop Bit.
(++) Even parity.
(++) BaudRate = 12096 baud.
(++) Hardware flow control disabled (RTS and CTS signals).
(++) Tx and Rx enabled
(#) Optionally you can enable the parity error interrupt using
the USART_ITConfig() function.
(#) Enable the Smartcard NACK using the USART_SmartCardNACKCmd() function.
(#) Enable the Smartcard interface using the USART_SmartCardCmd() function.
(#) Enable the USART using the USART_Cmd() function.
[..]
Please refer to the ISO 7816-3 specification for more details.
[..]
(@) It is also possible to choose 0.5 stop bit for receiving but it is
recommended to use 1.5 stop bits for both transmitting and receiving
to avoid switching between the two configurations.
(@) In smartcard mode, the following bits must be kept cleared:
(+@) LINEN bit in the USART_CR2 register.
(+@) HDSEL and IREN bits in the USART_CR3 register.
@endverbatim
* @{
*/
/**
* @brief Sets the specified USART guard time.
* @param USARTx: Select the USART peripheral. This parameter can be one of the
* following values: USART1 or USART2 or USART3.
* @param USART_GuardTime: specifies the guard time.
* @retval None
*/
void USART_SetGuardTime(USART_TypeDef* USARTx, uint8_t USART_GuardTime)
{
/* Check the parameters */
assert_param(IS_USART_123_PERIPH(USARTx));
/* Clear the USART Guard time */
USARTx->GTPR &= USART_GTPR_PSC;
/* Set the USART guard time */
USARTx->GTPR |= (uint16_t)((uint16_t)USART_GuardTime << 0x08);
}
/**
* @brief Enables or disables the USART's Smart Card mode.
* @param USARTx: Select the USART peripheral. This parameter can be one of the
* following values: USART1 or USART2 or USART3.
* @param NewState: new state of the Smart Card mode.
* This parameter can be: ENABLE or DISABLE.
* @retval None
*/
void USART_SmartCardCmd(USART_TypeDef* USARTx, FunctionalState NewState)
{
/* Check the parameters */
assert_param(IS_USART_123_PERIPH(USARTx));
assert_param(IS_FUNCTIONAL_STATE(NewState));
if (NewState != DISABLE)
{
/* Enable the SC mode by setting the SCEN bit in the CR3 register */
USARTx->CR3 |= USART_CR3_SCEN;
}
else
{
/* Disable the SC mode by clearing the SCEN bit in the CR3 register */
USARTx->CR3 &= (uint32_t)~((uint32_t)USART_CR3_SCEN);
}
}
/**
* @brief Enables or disables NACK transmission.
* @param USARTx: Select the USART peripheral. This parameter can be one of the
* following values: USART1 or USART2 or USART3.
* @param NewState: new state of the NACK transmission.
* This parameter can be: ENABLE or DISABLE.
* @retval None
*/
void USART_SmartCardNACKCmd(USART_TypeDef* USARTx, FunctionalState NewState)
{
/* Check the parameters */
assert_param(IS_USART_123_PERIPH(USARTx));
assert_param(IS_FUNCTIONAL_STATE(NewState));
if (NewState != DISABLE)
{
/* Enable the NACK transmission by setting the NACK bit in the CR3 register */
USARTx->CR3 |= USART_CR3_NACK;
}
else
{
/* Disable the NACK transmission by clearing the NACK bit in the CR3 register */
USARTx->CR3 &= (uint32_t)~((uint32_t)USART_CR3_NACK);
}
}
/**
* @brief Sets the Smart Card number of retries in transmit and receive.
* @param USARTx: Select the USART peripheral. This parameter can be one of the
* following values: USART1 or USART2 or USART3.
* @param USART_AutoCount: specifies the Smart Card auto retry count.
* @retval None
*/
void USART_SetAutoRetryCount(USART_TypeDef* USARTx, uint8_t USART_AutoCount)
{
/* Check the parameters */
assert_param(IS_USART_123_PERIPH(USARTx));
assert_param(IS_USART_AUTO_RETRY_COUNTER(USART_AutoCount));
/* Clear the USART auto retry count */
USARTx->CR3 &= (uint32_t)~((uint32_t)USART_CR3_SCARCNT);
/* Set the USART auto retry count*/
USARTx->CR3 |= (uint32_t)((uint32_t)USART_AutoCount << 0x11);
}
/**
* @brief Sets the Smart Card Block length.
* @param USARTx: Select the USART peripheral. This parameter can be one of the
* following values: USART1 or USART2 or USART3.
* @param USART_BlockLength: specifies the Smart Card block length.
* @retval None
*/
void USART_SetBlockLength(USART_TypeDef* USARTx, uint8_t USART_BlockLength)
{
/* Check the parameters */
assert_param(IS_USART_123_PERIPH(USARTx));
/* Clear the Smart card block length */
USARTx->RTOR &= (uint32_t)~((uint32_t)USART_RTOR_BLEN);
/* Set the Smart Card block length */
USARTx->RTOR |= (uint32_t)((uint32_t)USART_BlockLength << 0x18);
}
/**
* @}
*/
/** @defgroup USART_Group9 IrDA mode functions
* @brief IrDA mode functions
*
@verbatim
===============================================================================
##### IrDA mode functions #####
===============================================================================
[..] This subsection provides a set of functions allowing to manage the USART
IrDA communication.
[..] IrDA is a half duplex communication protocol. If the Transmitter is busy,
any data on the IrDA receive line will be ignored by the IrDA decoder
and if the Receiver is busy, data on the TX from the USART to IrDA will
not be encoded by IrDA. While receiving data, transmission should be
avoided as the data to be transmitted could be corrupted.
[..] IrDA communication is possible through the following procedure:
(#) Program the Baud rate, Word length = 8 bits, Stop bits, Parity,
Transmitter/Receiver modes and hardware flow control values using
the USART_Init() function.
(#) Configures the IrDA pulse width by configuring the prescaler using
the USART_SetPrescaler() function.
(#) Configures the IrDA USART_IrDAMode_LowPower or USART_IrDAMode_Normal
mode using the USART_IrDAConfig() function.
(#) Enable the IrDA using the USART_IrDACmd() function.
(#) Enable the USART using the USART_Cmd() function.
[..]
(@) A pulse of width less than two and greater than one PSC period(s) may or
may not be rejected.
(@) The receiver set up time should be managed by software. The IrDA physical
layer specification specifies a minimum of 10 ms delay between
transmission and reception (IrDA is a half duplex protocol).
(@) In IrDA mode, the following bits must be kept cleared:
(+@) LINEN, STOP and CLKEN bits in the USART_CR2 register.
(+@) SCEN and HDSEL bits in the USART_CR3 register.
@endverbatim
* @{
*/
/**
* @brief Configures the USART's IrDA interface.
* @param USARTx: Select the USART peripheral. This parameter can be one of the
* following values: USART1 or USART2 or USART3 or UART4 or UART5.
* @param USART_IrDAMode: specifies the IrDA mode.
* This parameter can be one of the following values:
* @arg USART_IrDAMode_LowPower
* @arg USART_IrDAMode_Normal
* @retval None
*/
void USART_IrDAConfig(USART_TypeDef* USARTx, uint32_t USART_IrDAMode)
{
/* Check the parameters */
assert_param(IS_USART_ALL_PERIPH(USARTx));
assert_param(IS_USART_IRDA_MODE(USART_IrDAMode));
USARTx->CR3 &= (uint32_t)~((uint32_t)USART_CR3_IRLP);
USARTx->CR3 |= USART_IrDAMode;
}
/**
* @brief Enables or disables the USART's IrDA interface.
* @param USARTx: Select the USART peripheral. This parameter can be one of the
* following values: USART1 or USART2 or USART3 or UART4 or UART5.
* @param NewState: new state of the IrDA mode.
* This parameter can be: ENABLE or DISABLE.
* @retval None
*/
void USART_IrDACmd(USART_TypeDef* USARTx, FunctionalState NewState)
{
/* Check the parameters */
assert_param(IS_USART_ALL_PERIPH(USARTx));
assert_param(IS_FUNCTIONAL_STATE(NewState));
if (NewState != DISABLE)
{
/* Enable the IrDA mode by setting the IREN bit in the CR3 register */
USARTx->CR3 |= USART_CR3_IREN;
}
else
{
/* Disable the IrDA mode by clearing the IREN bit in the CR3 register */
USARTx->CR3 &= (uint32_t)~((uint32_t)USART_CR3_IREN);
}
}
/**
* @}
*/
/** @defgroup USART_Group10 RS485 mode function
* @brief RS485 mode function
*
@verbatim
===============================================================================
##### RS485 mode functions #####
===============================================================================
[..] This subsection provides a set of functions allowing to manage the USART
RS485 flow control.
[..] RS485 flow control (Driver enable feature) handling is possible through
the following procedure:
(#) Program the Baud rate, Word length = 8 bits, Stop bits, Parity,
Transmitter/Receiver modes and hardware flow control values using
the USART_Init() function.
(#) Enable the Driver Enable using the USART_DECmd() function.
(#) Configures the Driver Enable polarity using the USART_DEPolarityConfig()
function.
(#) Configures the Driver Enable assertion time using USART_SetDEAssertionTime()
function and deassertion time using the USART_SetDEDeassertionTime()
function.
(#) Enable the USART using the USART_Cmd() function.
[..]
(@) The assertion and dessertion times are expressed in sample time units (1/8 or
1/16 bit time, depending on the oversampling rate).
@endverbatim
* @{
*/
/**
* @brief Enables or disables the USART's DE functionality.
* @param USARTx: Select the USART peripheral. This parameter can be one of the
* following values: USART1 or USART2 or USART3 or UART4 or UART5.
* @param NewState: new state of the driver enable mode.
* This parameter can be: ENABLE or DISABLE.
* @retval None
*/
void USART_DECmd(USART_TypeDef* USARTx, FunctionalState NewState)
{
/* Check the parameters */
assert_param(IS_USART_ALL_PERIPH(USARTx));
assert_param(IS_FUNCTIONAL_STATE(NewState));
if (NewState != DISABLE)
{
/* Enable the DE functionality by setting the DEM bit in the CR3 register */
USARTx->CR3 |= USART_CR3_DEM;
}
else
{
/* Disable the DE functionality by clearing the DEM bit in the CR3 register */
USARTx->CR3 &= (uint32_t)~((uint32_t)USART_CR3_DEM);
}
}
/**
* @brief Configures the USART's DE polarity
* @param USARTx: Select the USART peripheral. This parameter can be one of the
* following values: USART1 or USART2 or USART3 or UART4 or UART5.
* @param USART_DEPolarity: specifies the DE polarity.
* This parameter can be one of the following values:
* @arg USART_DEPolarity_Low
* @arg USART_DEPolarity_High
* @retval None
*/
void USART_DEPolarityConfig(USART_TypeDef* USARTx, uint32_t USART_DEPolarity)
{
/* Check the parameters */
assert_param(IS_USART_ALL_PERIPH(USARTx));
assert_param(IS_USART_DE_POLARITY(USART_DEPolarity));
USARTx->CR3 &= (uint32_t)~((uint32_t)USART_CR3_DEP);
USARTx->CR3 |= USART_DEPolarity;
}
/**
* @brief Sets the specified RS485 DE assertion time
* @param USARTx: Select the USART peripheral. This parameter can be one of the
* following values: USART1 or USART2 or USART3 or UART4 or UART5.
* @param USART_AssertionTime: specifies the time between the activation of the DE
* signal and the beginning of the start bit
* @retval None
*/
void USART_SetDEAssertionTime(USART_TypeDef* USARTx, uint32_t USART_DEAssertionTime)
{
/* Check the parameters */
assert_param(IS_USART_ALL_PERIPH(USARTx));
assert_param(IS_USART_DE_ASSERTION_DEASSERTION_TIME(USART_DEAssertionTime));
/* Clear the DE assertion time */
USARTx->CR1 &= (uint32_t)~((uint32_t)USART_CR1_DEAT);
/* Set the new value for the DE assertion time */
USARTx->CR1 |=((uint32_t)USART_DEAssertionTime << (uint32_t)0x15);
}
/**
* @brief Sets the specified RS485 DE deassertion time
* @param USARTx: Select the USART peripheral. This parameter can be one of the
* following values: USART1 or USART2 or USART3 or UART4 or UART5.
* @param USART_DeassertionTime: specifies the time between the middle of the last
* stop bit in a transmitted message and the de-activation of the DE signal
* @retval None
*/
void USART_SetDEDeassertionTime(USART_TypeDef* USARTx, uint32_t USART_DEDeassertionTime)
{
/* Check the parameters */
assert_param(IS_USART_ALL_PERIPH(USARTx));
assert_param(IS_USART_DE_ASSERTION_DEASSERTION_TIME(USART_DEDeassertionTime));
/* Clear the DE deassertion time */
USARTx->CR1 &= (uint32_t)~((uint32_t)USART_CR1_DEDT);
/* Set the new value for the DE deassertion time */
USARTx->CR1 |=((uint32_t)USART_DEDeassertionTime << (uint32_t)0x10);
}
/**
* @}
*/
/** @defgroup USART_Group11 DMA transfers management functions
* @brief DMA transfers management functions
*
@verbatim
===============================================================================
##### DMA transfers management functions #####
===============================================================================
[..] This section provides two functions that can be used only in DMA mode.
[..] In DMA Mode, the USART communication can be managed by 2 DMA Channel
requests:
(#) USART_DMAReq_Tx: specifies the Tx buffer DMA transfer request.
(#) USART_DMAReq_Rx: specifies the Rx buffer DMA transfer request.
[..] In this Mode it is advised to use the following function:
(+) void USART_DMACmd(USART_TypeDef* USARTx, uint16_t USART_DMAReq,
FunctionalState NewState).
@endverbatim
* @{
*/
/**
* @brief Enables or disables the USART's DMA interface.
* @param USARTx: Select the USART peripheral. This parameter can be one of the
* following values: USART1 or USART2 or USART3 or UART4.
* @param USART_DMAReq: specifies the DMA request.
* This parameter can be any combination of the following values:
* @arg USART_DMAReq_Tx: USART DMA transmit request
* @arg USART_DMAReq_Rx: USART DMA receive request
* @param NewState: new state of the DMA Request sources.
* This parameter can be: ENABLE or DISABLE.
* @retval None
*/
void USART_DMACmd(USART_TypeDef* USARTx, uint32_t USART_DMAReq, FunctionalState NewState)
{
/* Check the parameters */
assert_param(IS_USART_1234_PERIPH(USARTx));
assert_param(IS_USART_DMAREQ(USART_DMAReq));
assert_param(IS_FUNCTIONAL_STATE(NewState));
if (NewState != DISABLE)
{
/* Enable the DMA transfer for selected requests by setting the DMAT and/or
DMAR bits in the USART CR3 register */
USARTx->CR3 |= USART_DMAReq;
}
else
{
/* Disable the DMA transfer for selected requests by clearing the DMAT and/or
DMAR bits in the USART CR3 register */
USARTx->CR3 &= (uint32_t)~USART_DMAReq;
}
}
/**
* @brief Enables or disables the USART's DMA interface when reception error occurs.
* @param USARTx: Select the USART peripheral. This parameter can be one of the
* following values: USART1 or USART2 or USART3 or UART4.
* @param USART_DMAOnError: specifies the DMA status in case of reception error.
* This parameter can be any combination of the following values:
* @arg USART_DMAOnError_Enable: DMA receive request enabled when the USART DMA
* reception error is asserted.
* @arg USART_DMAOnError_Disable: DMA receive request disabled when the USART DMA
* reception error is asserted.
* @retval None
*/
void USART_DMAReceptionErrorConfig(USART_TypeDef* USARTx, uint32_t USART_DMAOnError)
{
/* Check the parameters */
assert_param(IS_USART_1234_PERIPH(USARTx));
assert_param(IS_USART_DMAONERROR(USART_DMAOnError));
/* Clear the DMA Reception error detection bit */
USARTx->CR3 &= (uint32_t)~((uint32_t)USART_CR3_DDRE);
/* Set the new value for the DMA Reception error detection bit */
USARTx->CR3 |= USART_DMAOnError;
}
/**
* @}
*/
/** @defgroup USART_Group12 Interrupts and flags management functions
* @brief Interrupts and flags management functions
*
@verbatim
===============================================================================
##### Interrupts and flags management functions #####
===============================================================================
[..] This subsection provides a set of functions allowing to configure the
USART Interrupts sources, Requests and check or clear the flags or pending bits status.
The user should identify which mode will be used in his application to
manage the communication: Polling mode, Interrupt mode.
*** Polling Mode ***
====================
[..] In Polling Mode, the SPI communication can be managed by these flags:
(#) USART_FLAG_REACK: to indicate the status of the Receive Enable
acknowledge flag
(#) USART_FLAG_TEACK: to indicate the status of the Transmit Enable
acknowledge flag.
(#) USART_FLAG_WUF: to indicate the status of the Wake up flag.
(#) USART_FLAG_RWU: to indicate the status of the Receive Wake up flag.
(#) USART_FLAG_SBK: to indicate the status of the Send Break flag.
(#) USART_FLAG_CMF: to indicate the status of the Character match flag.
(#) USART_FLAG_BUSY: to indicate the status of the Busy flag.
(#) USART_FLAG_ABRF: to indicate the status of the Auto baud rate flag.
(#) USART_FLAG_ABRE: to indicate the status of the Auto baud rate error flag.
(#) USART_FLAG_EOBF: to indicate the status of the End of block flag.
(#) USART_FLAG_RTOF: to indicate the status of the Receive time out flag.
(#) USART_FLAG_nCTSS: to indicate the status of the Inverted nCTS input
bit status.
(#) USART_FLAG_TXE: to indicate the status of the transmit buffer register.
(#) USART_FLAG_RXNE: to indicate the status of the receive buffer register.
(#) USART_FLAG_TC: to indicate the status of the transmit operation.
(#) USART_FLAG_IDLE: to indicate the status of the Idle Line.
(#) USART_FLAG_CTS: to indicate the status of the nCTS input.
(#) USART_FLAG_LBD: to indicate the status of the LIN break detection.
(#) USART_FLAG_NE: to indicate if a noise error occur.
(#) USART_FLAG_FE: to indicate if a frame error occur.
(#) USART_FLAG_PE: to indicate if a parity error occur.
(#) USART_FLAG_ORE: to indicate if an Overrun error occur.
[..] In this Mode it is advised to use the following functions:
(+) FlagStatus USART_GetFlagStatus(USART_TypeDef* USARTx, uint16_t USART_FLAG).
(+) void USART_ClearFlag(USART_TypeDef* USARTx, uint16_t USART_FLAG).
*** Interrupt Mode ***
======================
[..] In Interrupt Mode, the USART communication can be managed by 8 interrupt
sources and 10 pending bits:
(+) Pending Bits:
(##) USART_IT_WU: to indicate the status of the Wake up interrupt.
(##) USART_IT_CM: to indicate the status of Character match interrupt.
(##) USART_IT_EOB: to indicate the status of End of block interrupt.
(##) USART_IT_RTO: to indicate the status of Receive time out interrupt.
(##) USART_IT_CTS: to indicate the status of CTS change interrupt.
(##) USART_IT_LBD: to indicate the status of LIN Break detection interrupt.
(##) USART_IT_TC: to indicate the status of Transmission complete interrupt.
(##) USART_IT_IDLE: to indicate the status of IDLE line detected interrupt.
(##) USART_IT_ORE: to indicate the status of OverRun Error interrupt.
(##) USART_IT_NE: to indicate the status of Noise Error interrupt.
(##) USART_IT_FE: to indicate the status of Framing Error interrupt.
(##) USART_IT_PE: to indicate the status of Parity Error interrupt.
(+) Interrupt Source:
(##) USART_IT_WU: specifies the interrupt source for Wake up interrupt.
(##) USART_IT_CM: specifies the interrupt source for Character match
interrupt.
(##) USART_IT_EOB: specifies the interrupt source for End of block
interrupt.
(##) USART_IT_RTO: specifies the interrupt source for Receive time-out
interrupt.
(##) USART_IT_CTS: specifies the interrupt source for CTS change interrupt.
(##) USART_IT_LBD: specifies the interrupt source for LIN Break
detection interrupt.
(##) USART_IT_TXE: specifies the interrupt source for Transmit Data
Register empty interrupt.
(##) USART_IT_TC: specifies the interrupt source for Transmission
complete interrupt.
(##) USART_IT_RXNE: specifies the interrupt source for Receive Data
register not empty interrupt.
(##) USART_IT_IDLE: specifies the interrupt source for Idle line
detection interrupt.
(##) USART_IT_PE: specifies the interrupt source for Parity Error interrupt.
(##) USART_IT_ERR: specifies the interrupt source for Error interrupt
(Frame error, noise error, overrun error)
-@@- Some parameters are coded in order to use them as interrupt
source or as pending bits.
[..] In this Mode it is advised to use the following functions:
(+) void USART_ITConfig(USART_TypeDef* USARTx, uint16_t USART_IT, FunctionalState NewState).
(+) ITStatus USART_GetITStatus(USART_TypeDef* USARTx, uint16_t USART_IT).
(+) void USART_ClearITPendingBit(USART_TypeDef* USARTx, uint16_t USART_IT).
@endverbatim
* @{
*/
/**
* @brief Enables or disables the specified USART interrupts.
* @param USARTx: Select the USART peripheral. This parameter can be one of the
* following values: USART1 or USART2 or USART3 or UART4 or UART5.
* @param USART_IT: specifies the USART interrupt sources to be enabled or disabled.
* This parameter can be one of the following values:
* @arg USART_IT_WU: Wake up interrupt.
* @arg USART_IT_CM: Character match interrupt.
* @arg USART_IT_EOB: End of block interrupt.
* @arg USART_IT_RTO: Receive time out interrupt.
* @arg USART_IT_CTS: CTS change interrupt.
* @arg USART_IT_LBD: LIN Break detection interrupt.
* @arg USART_IT_TXE: Transmit Data Register empty interrupt.
* @arg USART_IT_TC: Transmission complete interrupt.
* @arg USART_IT_RXNE: Receive Data register not empty interrupt.
* @arg USART_IT_IDLE: Idle line detection interrupt.
* @arg USART_IT_PE: Parity Error interrupt.
* @arg USART_IT_ERR: Error interrupt(Frame error, noise error, overrun error)
* @param NewState: new state of the specified USARTx interrupts.
* This parameter can be: ENABLE or DISABLE.
* @retval None
*/
void USART_ITConfig(USART_TypeDef* USARTx, uint32_t USART_IT, FunctionalState NewState)
{
uint32_t usartreg = 0, itpos = 0, itmask = 0;
uint32_t usartxbase = 0;
/* Check the parameters */
assert_param(IS_USART_ALL_PERIPH(USARTx));
assert_param(IS_USART_CONFIG_IT(USART_IT));
assert_param(IS_FUNCTIONAL_STATE(NewState));
usartxbase = (uint32_t)USARTx;
/* Get the USART register index */
usartreg = (((uint16_t)USART_IT) >> 0x08);
/* Get the interrupt position */
itpos = USART_IT & IT_MASK;
itmask = (((uint32_t)0x01) << itpos);
if (usartreg == 0x02) /* The IT is in CR2 register */
{
usartxbase += 0x04;
}
else if (usartreg == 0x03) /* The IT is in CR3 register */
{
usartxbase += 0x08;
}
else /* The IT is in CR1 register */
{
}
if (NewState != DISABLE)
{
*(__IO uint32_t*)usartxbase |= itmask;
}
else
{
*(__IO uint32_t*)usartxbase &= ~itmask;
}
}
/**
* @brief Enables the specified USART's Request.
* @param USARTx: Select the USART peripheral. This parameter can be one of the
* following values: USART1 or USART2 or USART3 or UART4 or UART5.
* @param USART_Request: specifies the USART request.
* This parameter can be any combination of the following values:
* @arg USART_Request_TXFRQ: Transmit data flush ReQuest
* @arg USART_Request_RXFRQ: Receive data flush ReQuest
* @arg USART_Request_MMRQ: Mute Mode ReQuest
* @arg USART_Request_SBKRQ: Send Break ReQuest
* @arg USART_Request_ABRRQ: Auto Baud Rate ReQuest
* @param NewState: new state of the DMA interface when reception error occurs.
* This parameter can be: ENABLE or DISABLE.
* @retval None
*/
void USART_RequestCmd(USART_TypeDef* USARTx, uint32_t USART_Request, FunctionalState NewState)
{
/* Check the parameters */
assert_param(IS_USART_ALL_PERIPH(USARTx));
assert_param(IS_USART_REQUEST(USART_Request));
assert_param(IS_FUNCTIONAL_STATE(NewState));
if (NewState != DISABLE)
{
/* Enable the USART ReQuest by setting the dedicated request bit in the RQR
register.*/
USARTx->RQR |= USART_Request;
}
else
{
/* Disable the USART ReQuest by clearing the dedicated request bit in the RQR
register.*/
USARTx->RQR &= (uint32_t)~USART_Request;
}
}
/**
* @brief Enables or disables the USART's Overrun detection.
* @param USARTx: Select the USART peripheral. This parameter can be one of the
* following values: USART1 or USART2 or USART3 or UART4 or UART5.
* @param USART_OVRDetection: specifies the OVR detection status in case of OVR error.
* This parameter can be any combination of the following values:
* @arg USART_OVRDetection_Enable: OVR error detection enabled when the USART OVR error
* is asserted.
* @arg USART_OVRDetection_Disable: OVR error detection disabled when the USART OVR error
* is asserted.
* @retval None
*/
void USART_OverrunDetectionConfig(USART_TypeDef* USARTx, uint32_t USART_OVRDetection)
{
/* Check the parameters */
assert_param(IS_USART_ALL_PERIPH(USARTx));
assert_param(IS_USART_OVRDETECTION(USART_OVRDetection));
/* Clear the OVR detection bit */
USARTx->CR3 &= (uint32_t)~((uint32_t)USART_CR3_OVRDIS);
/* Set the new value for the OVR detection bit */
USARTx->CR3 |= USART_OVRDetection;
}
/**
* @brief Checks whether the specified USART flag is set or not.
* @param USARTx: Select the USART peripheral. This parameter can be one of the
* following values: USART1 or USART2 or USART3 or UART4 or UART5.
* @param USART_FLAG: specifies the flag to check.
* This parameter can be one of the following values:
* @arg USART_FLAG_REACK: Receive Enable acknowledge flag.
* @arg USART_FLAG_TEACK: Transmit Enable acknowledge flag.
* @arg USART_FLAG_WUF: Wake up flag.
* @arg USART_FLAG_RWU: Receive Wake up flag.
* @arg USART_FLAG_SBK: Send Break flag.
* @arg USART_FLAG_CMF: Character match flag.
* @arg USART_FLAG_BUSY: Busy flag.
* @arg USART_FLAG_ABRF: Auto baud rate flag.
* @arg USART_FLAG_ABRE: Auto baud rate error flag.
* @arg USART_FLAG_EOBF: End of block flag.
* @arg USART_FLAG_RTOF: Receive time out flag.
* @arg USART_FLAG_nCTSS: Inverted nCTS input bit status.
* @arg USART_FLAG_CTS: CTS Change flag.
* @arg USART_FLAG_LBD: LIN Break detection flag.
* @arg USART_FLAG_TXE: Transmit data register empty flag.
* @arg USART_FLAG_TC: Transmission Complete flag.
* @arg USART_FLAG_RXNE: Receive data register not empty flag.
* @arg USART_FLAG_IDLE: Idle Line detection flag.
* @arg USART_FLAG_ORE: OverRun Error flag.
* @arg USART_FLAG_NE: Noise Error flag.
* @arg USART_FLAG_FE: Framing Error flag.
* @arg USART_FLAG_PE: Parity Error flag.
* @retval The new state of USART_FLAG (SET or RESET).
*/
FlagStatus USART_GetFlagStatus(USART_TypeDef* USARTx, uint32_t USART_FLAG)
{
FlagStatus bitstatus = RESET;
/* Check the parameters */
assert_param(IS_USART_ALL_PERIPH(USARTx));
assert_param(IS_USART_FLAG(USART_FLAG));
if ((USARTx->ISR & USART_FLAG) != (uint16_t)RESET)
{
bitstatus = SET;
}
else
{
bitstatus = RESET;
}
return bitstatus;
}
/**
* @brief Clears the USARTx's pending flags.
* @param USARTx: Select the USART peripheral. This parameter can be one of the
* following values: USART1 or USART2 or USART3 or UART4 or UART5.
* @param USART_FLAG: specifies the flag to clear.
* This parameter can be any combination of the following values:
* @arg USART_FLAG_WUF: Wake up flag.
* @arg USART_FLAG_CMF: Character match flag.
* @arg USART_FLAG_EOBF: End of block flag.
* @arg USART_FLAG_RTOF: Receive time out flag.
* @arg USART_FLAG_CTS: CTS Change flag.
* @arg USART_FLAG_LBD: LIN Break detection flag.
* @arg USART_FLAG_TC: Transmission Complete flag.
* @arg USART_FLAG_IDLE: IDLE line detected flag.
* @arg USART_FLAG_ORE: OverRun Error flag.
* @arg USART_FLAG_NE: Noise Error flag.
* @arg USART_FLAG_FE: Framing Error flag.
* @arg USART_FLAG_PE: Parity Errorflag.
*
* @note
* - RXNE pending bit is cleared by a read to the USART_RDR register
* (USART_ReceiveData()) or by writing 1 to the RXFRQ in the register USART_RQR
* (USART_RequestCmd()).
* - TC flag can be also cleared by software sequence: a read operation to
* USART_SR register (USART_GetFlagStatus()) followed by a write operation
* to USART_TDR register (USART_SendData()).
* - TXE flag is cleared by a write to the USART_TDR register
* (USART_SendData()) or by writing 1 to the TXFRQ in the register USART_RQR
* (USART_RequestCmd()).
* - SBKF flag is cleared by 1 to the SBKRQ in the register USART_RQR
* (USART_RequestCmd()).
* @retval None
*/
void USART_ClearFlag(USART_TypeDef* USARTx, uint32_t USART_FLAG)
{
/* Check the parameters */
assert_param(IS_USART_ALL_PERIPH(USARTx));
assert_param(IS_USART_CLEAR_FLAG(USART_FLAG));
USARTx->ICR = USART_FLAG;
}
/**
* @brief Checks whether the specified USART interrupt has occurred or not.
* @param USARTx: Select the USART peripheral. This parameter can be one of the
* following values: USART1 or USART2 or USART3 or UART4 or UART5.
* @param USART_IT: specifies the USART interrupt source to check.
* This parameter can be one of the following values:
* @arg USART_IT_WU: Wake up interrupt.
* @arg USART_IT_CM: Character match interrupt.
* @arg USART_IT_EOB: End of block interrupt.
* @arg USART_IT_RTO: Receive time out interrupt.
* @arg USART_IT_CTS: CTS change interrupt.
* @arg USART_IT_LBD: LIN Break detection interrupt.
* @arg USART_IT_TXE: Transmit Data Register empty interrupt.
* @arg USART_IT_TC: Transmission complete interrupt.
* @arg USART_IT_RXNE: Receive Data register not empty interrupt.
* @arg USART_IT_IDLE: Idle line detection interrupt.
* @arg USART_IT_ORE: OverRun Error interrupt.
* @arg USART_IT_NE: Noise Error interrupt.
* @arg USART_IT_FE: Framing Error interrupt.
* @arg USART_IT_PE: Parity Error interrupt.
* @retval The new state of USART_IT (SET or RESET).
*/
ITStatus USART_GetITStatus(USART_TypeDef* USARTx, uint32_t USART_IT)
{
uint32_t bitpos = 0, itmask = 0, usartreg = 0;
ITStatus bitstatus = RESET;
/* Check the parameters */
assert_param(IS_USART_ALL_PERIPH(USARTx));
assert_param(IS_USART_GET_IT(USART_IT));
/* Get the USART register index */
usartreg = (((uint16_t)USART_IT) >> 0x08);
/* Get the interrupt position */
itmask = USART_IT & IT_MASK;
itmask = (uint32_t)0x01 << itmask;
if (usartreg == 0x01) /* The IT is in CR1 register */
{
itmask &= USARTx->CR1;
}
else if (usartreg == 0x02) /* The IT is in CR2 register */
{
itmask &= USARTx->CR2;
}
else /* The IT is in CR3 register */
{
itmask &= USARTx->CR3;
}
bitpos = USART_IT >> 0x10;
bitpos = (uint32_t)0x01 << bitpos;
bitpos &= USARTx->ISR;
if ((itmask != (uint16_t)RESET)&&(bitpos != (uint16_t)RESET))
{
bitstatus = SET;
}
else
{
bitstatus = RESET;
}
return bitstatus;
}
/**
* @brief Clears the USARTx's interrupt pending bits.
* @param USARTx: Select the USART peripheral. This parameter can be one of the
* following values: USART1 or USART2 or USART3 or UART4 or UART5.
* @param USART_IT: specifies the interrupt pending bit to clear.
* This parameter can be one of the following values:
* @arg USART_IT_WU: Wake up interrupt.
* @arg USART_IT_CM: Character match interrupt.
* @arg USART_IT_EOB: End of block interrupt.
* @arg USART_IT_RTO: Receive time out interrupt.
* @arg USART_IT_CTS: CTS change interrupt.
* @arg USART_IT_LBD: LIN Break detection interrupt.
* @arg USART_IT_TC: Transmission complete interrupt.
* @arg USART_IT_IDLE: IDLE line detected interrupt.
* @arg USART_IT_ORE: OverRun Error interrupt.
* @arg USART_IT_NE: Noise Error interrupt.
* @arg USART_IT_FE: Framing Error interrupt.
* @arg USART_IT_PE: Parity Error interrupt.
* @note
* - RXNE pending bit is cleared by a read to the USART_RDR register
* (USART_ReceiveData()) or by writing 1 to the RXFRQ in the register USART_RQR
* (USART_RequestCmd()).
* - TC pending bit can be also cleared by software sequence: a read
* operation to USART_SR register (USART_GetITStatus()) followed by a write
* operation to USART_TDR register (USART_SendData()).
* - TXE pending bit is cleared by a write to the USART_TDR register
* (USART_SendData()) or by writing 1 to the TXFRQ in the register USART_RQR
* (USART_RequestCmd()).
* @retval None
*/
void USART_ClearITPendingBit(USART_TypeDef* USARTx, uint32_t USART_IT)
{
uint32_t bitpos = 0, itmask = 0;
/* Check the parameters */
assert_param(IS_USART_ALL_PERIPH(USARTx));
assert_param(IS_USART_CLEAR_IT(USART_IT));
bitpos = USART_IT >> 0x10;
itmask = ((uint32_t)0x01 << (uint32_t)bitpos);
USARTx->ICR = (uint32_t)itmask;
}
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/**
* @}
*/
/************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
| mit |
cnsuperx/Cocos2d-x-2.2.5 | external/emscripten/tests/hello_world_gles_deriv.c | 11 | 19757 | /*
* Copyright (C) 1999-2001 Brian Paul All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included
* in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* BRIAN PAUL 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.
*/
/*
* Ported to GLES2.
* Kristian Høgsberg <krh@bitplanet.net>
* May 3, 2010
*
* Improve GLES2 port:
* * Refactor gear drawing.
* * Use correct normals for surfaces.
* * Improve shader.
* * Use perspective projection transformation.
* * Add FPS count.
* * Add comments.
* Alexandros Frantzis <alexandros.frantzis@linaro.org>
* Jul 13, 2010
*/
#define GL_GLEXT_PROTOTYPES
#define EGL_EGLEXT_PROTOTYPES
#define _GNU_SOURCE
#include <math.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <sys/time.h>
#include <unistd.h>
#include <GL/gl.h>
#include <GL/glut.h>
#ifndef HAVE_BUILTIN_SINCOS
#include "sincos.h"
#endif
#define STRIPS_PER_TOOTH 7
#define VERTICES_PER_TOOTH 34
#define GEAR_VERTEX_STRIDE 6
/**
* Struct describing the vertices in triangle strip
*/
struct vertex_strip {
/** The first vertex in the strip */
GLint first;
/** The number of consecutive vertices in the strip after the first */
GLint count;
};
/* Each vertex consist of GEAR_VERTEX_STRIDE GLfloat attributes */
typedef GLfloat GearVertex[GEAR_VERTEX_STRIDE];
/**
* Struct representing a gear.
*/
struct gear {
/** The array of vertices comprising the gear */
GearVertex *vertices;
/** The number of vertices comprising the gear */
int nvertices;
/** The array of triangle strips comprising the gear */
struct vertex_strip *strips;
/** The number of triangle strips comprising the gear */
int nstrips;
/** The Vertex Buffer Object holding the vertices in the graphics card */
GLuint vbo;
};
/** The view rotation [x, y, z] */
static GLfloat view_rot[3] = { 20.0, 30.0, 0.0 };
/** The gears */
static struct gear *gear1, *gear2, *gear3;
/** The current gear rotation angle */
static GLfloat angle = 0.0;
/** The location of the shader uniforms */
static GLuint ModelViewProjectionMatrix_location,
NormalMatrix_location,
LightSourcePosition_location,
MaterialColor_location;
/** The projection matrix */
static GLfloat ProjectionMatrix[16];
/** The direction of the directional light for the scene */
static const GLfloat LightSourcePosition[4] = { 5.0, 5.0, 10.0, 1.0};
/**
* Fills a gear vertex.
*
* @param v the vertex to fill
* @param x the x coordinate
* @param y the y coordinate
* @param z the z coortinate
* @param n pointer to the normal table
*
* @return the operation error code
*/
static GearVertex *
vert(GearVertex *v, GLfloat x, GLfloat y, GLfloat z, GLfloat n[3])
{
v[0][0] = x;
v[0][1] = y;
v[0][2] = z;
v[0][3] = n[0];
v[0][4] = n[1];
v[0][5] = n[2];
return v + 1;
}
/**
* Create a gear wheel.
*
* @param inner_radius radius of hole at center
* @param outer_radius radius at center of teeth
* @param width width of gear
* @param teeth number of teeth
* @param tooth_depth depth of tooth
*
* @return pointer to the constructed struct gear
*/
static struct gear *
create_gear(GLfloat inner_radius, GLfloat outer_radius, GLfloat width,
GLint teeth, GLfloat tooth_depth)
{
GLfloat r0, r1, r2;
GLfloat da;
GearVertex *v;
struct gear *gear;
double s[5], c[5];
GLfloat normal[3];
int cur_strip = 0;
int i;
/* Allocate memory for the gear */
gear = malloc(sizeof *gear);
if (gear == NULL)
return NULL;
/* Calculate the radii used in the gear */
r0 = inner_radius;
r1 = outer_radius - tooth_depth / 2.0;
r2 = outer_radius + tooth_depth / 2.0;
da = 2.0 * M_PI / teeth / 4.0;
/* Allocate memory for the triangle strip information */
gear->nstrips = STRIPS_PER_TOOTH * teeth;
gear->strips = calloc(gear->nstrips, sizeof (*gear->strips));
/* Allocate memory for the vertices */
gear->vertices = calloc(VERTICES_PER_TOOTH * teeth, sizeof(*gear->vertices));
v = gear->vertices;
for (i = 0; i < teeth; i++) {
/* Calculate needed sin/cos for varius angles */
sincos(i * 2.0 * M_PI / teeth, &s[0], &c[0]);
sincos(i * 2.0 * M_PI / teeth + da, &s[1], &c[1]);
sincos(i * 2.0 * M_PI / teeth + da * 2, &s[2], &c[2]);
sincos(i * 2.0 * M_PI / teeth + da * 3, &s[3], &c[3]);
sincos(i * 2.0 * M_PI / teeth + da * 4, &s[4], &c[4]);
/* A set of macros for making the creation of the gears easier */
#define GEAR_POINT(r, da) { (r) * c[(da)], (r) * s[(da)] }
#define SET_NORMAL(x, y, z) do { \
normal[0] = (x); normal[1] = (y); normal[2] = (z); \
} while(0)
#define GEAR_VERT(v, point, sign) vert((v), p[(point)].x, p[(point)].y, (sign) * width * 0.5, normal)
#define START_STRIP do { \
gear->strips[cur_strip].first = v - gear->vertices; \
} while(0);
#define END_STRIP do { \
int _tmp = (v - gear->vertices); \
gear->strips[cur_strip].count = _tmp - gear->strips[cur_strip].first; \
cur_strip++; \
} while (0)
#define QUAD_WITH_NORMAL(p1, p2) do { \
SET_NORMAL((p[(p1)].y - p[(p2)].y), -(p[(p1)].x - p[(p2)].x), 0); \
v = GEAR_VERT(v, (p1), -1); \
v = GEAR_VERT(v, (p1), 1); \
v = GEAR_VERT(v, (p2), -1); \
v = GEAR_VERT(v, (p2), 1); \
} while(0)
struct point {
GLfloat x;
GLfloat y;
};
/* Create the 7 points (only x,y coords) used to draw a tooth */
struct point p[7] = {
GEAR_POINT(r2, 1), // 0
GEAR_POINT(r2, 2), // 1
GEAR_POINT(r1, 0), // 2
GEAR_POINT(r1, 3), // 3
GEAR_POINT(r0, 0), // 4
GEAR_POINT(r1, 4), // 5
GEAR_POINT(r0, 4), // 6
};
/* Front face */
START_STRIP;
SET_NORMAL(0, 0, 1.0);
v = GEAR_VERT(v, 0, +1);
v = GEAR_VERT(v, 1, +1);
v = GEAR_VERT(v, 2, +1);
v = GEAR_VERT(v, 3, +1);
v = GEAR_VERT(v, 4, +1);
v = GEAR_VERT(v, 5, +1);
v = GEAR_VERT(v, 6, +1);
END_STRIP;
/* Inner face */
START_STRIP;
QUAD_WITH_NORMAL(4, 6);
END_STRIP;
/* Back face */
START_STRIP;
SET_NORMAL(0, 0, -1.0);
v = GEAR_VERT(v, 6, -1);
v = GEAR_VERT(v, 5, -1);
v = GEAR_VERT(v, 4, -1);
v = GEAR_VERT(v, 3, -1);
v = GEAR_VERT(v, 2, -1);
v = GEAR_VERT(v, 1, -1);
v = GEAR_VERT(v, 0, -1);
END_STRIP;
/* Outer face */
START_STRIP;
QUAD_WITH_NORMAL(0, 2);
END_STRIP;
START_STRIP;
QUAD_WITH_NORMAL(1, 0);
END_STRIP;
START_STRIP;
QUAD_WITH_NORMAL(3, 1);
END_STRIP;
START_STRIP;
QUAD_WITH_NORMAL(5, 3);
END_STRIP;
}
gear->nvertices = (v - gear->vertices);
/* Store the vertices in a vertex buffer object (VBO) */
glGenBuffers(1, &gear->vbo);
glBindBuffer(GL_ARRAY_BUFFER, gear->vbo);
glBufferData(GL_ARRAY_BUFFER, gear->nvertices * sizeof(GearVertex),
gear->vertices, GL_STATIC_DRAW);
return gear;
}
/**
* Multiplies two 4x4 matrices.
*
* The result is stored in matrix m.
*
* @param m the first matrix to multiply
* @param n the second matrix to multiply
*/
static void
multiply(GLfloat *m, const GLfloat *n)
{
GLfloat tmp[16];
const GLfloat *row, *column;
div_t d;
int i, j;
for (i = 0; i < 16; i++) {
tmp[i] = 0;
d = div(i, 4);
row = n + d.quot * 4;
column = m + d.rem;
for (j = 0; j < 4; j++)
tmp[i] += row[j] * column[j * 4];
}
memcpy(m, &tmp, sizeof tmp);
}
/**
* Rotates a 4x4 matrix.
*
* @param[in,out] m the matrix to rotate
* @param angle the angle to rotate
* @param x the x component of the direction to rotate to
* @param y the y component of the direction to rotate to
* @param z the z component of the direction to rotate to
*/
static void
rotate(GLfloat *m, GLfloat angle, GLfloat x, GLfloat y, GLfloat z)
{
double s, c;
sincos(angle, &s, &c);
GLfloat r[16] = {
x * x * (1 - c) + c, y * x * (1 - c) + z * s, x * z * (1 - c) - y * s, 0,
x * y * (1 - c) - z * s, y * y * (1 - c) + c, y * z * (1 - c) + x * s, 0,
x * z * (1 - c) + y * s, y * z * (1 - c) - x * s, z * z * (1 - c) + c, 0,
0, 0, 0, 1
};
multiply(m, r);
}
/**
* Translates a 4x4 matrix.
*
* @param[in,out] m the matrix to translate
* @param x the x component of the direction to translate to
* @param y the y component of the direction to translate to
* @param z the z component of the direction to translate to
*/
static void
translate(GLfloat *m, GLfloat x, GLfloat y, GLfloat z)
{
GLfloat t[16] = { 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, x, y, z, 1 };
multiply(m, t);
}
/**
* Creates an identity 4x4 matrix.
*
* @param m the matrix make an identity matrix
*/
static void
identity(GLfloat *m)
{
GLfloat t[16] = {
1.0, 0.0, 0.0, 0.0,
0.0, 1.0, 0.0, 0.0,
0.0, 0.0, 1.0, 0.0,
0.0, 0.0, 0.0, 1.0,
};
memcpy(m, t, sizeof(t));
}
/**
* Transposes a 4x4 matrix.
*
* @param m the matrix to transpose
*/
static void
transpose(GLfloat *m)
{
GLfloat t[16] = {
m[0], m[4], m[8], m[12],
m[1], m[5], m[9], m[13],
m[2], m[6], m[10], m[14],
m[3], m[7], m[11], m[15]};
memcpy(m, t, sizeof(t));
}
/**
* Inverts a 4x4 matrix.
*
* This function can currently handle only pure translation-rotation matrices.
* Read http://www.gamedev.net/community/forums/topic.asp?topic_id=425118
* for an explanation.
*/
static void
invert(GLfloat *m)
{
GLfloat t[16];
identity(t);
// Extract and invert the translation part 't'. The inverse of a
// translation matrix can be calculated by negating the translation
// coordinates.
t[12] = -m[12]; t[13] = -m[13]; t[14] = -m[14];
// Invert the rotation part 'r'. The inverse of a rotation matrix is
// equal to its transpose.
m[12] = m[13] = m[14] = 0;
transpose(m);
// inv(m) = inv(r) * inv(t)
multiply(m, t);
}
/**
* Calculate a perspective projection transformation.
*
* @param m the matrix to save the transformation in
* @param fovy the field of view in the y direction
* @param aspect the view aspect ratio
* @param zNear the near clipping plane
* @param zFar the far clipping plane
*/
void perspective(GLfloat *m, GLfloat fovy, GLfloat aspect, GLfloat zNear, GLfloat zFar)
{
GLfloat tmp[16];
identity(tmp);
double sine, cosine, cotangent, deltaZ;
GLfloat radians = fovy / 2 * M_PI / 180;
deltaZ = zFar - zNear;
sincos(radians, &sine, &cosine);
if ((deltaZ == 0) || (sine == 0) || (aspect == 0))
return;
cotangent = cosine / sine;
tmp[0] = cotangent / aspect;
tmp[5] = cotangent;
tmp[10] = -(zFar + zNear) / deltaZ;
tmp[11] = -1;
tmp[14] = -2 * zNear * zFar / deltaZ;
tmp[15] = 0;
memcpy(m, tmp, sizeof(tmp));
}
/**
* Draws a gear.
*
* @param gear the gear to draw
* @param transform the current transformation matrix
* @param x the x position to draw the gear at
* @param y the y position to draw the gear at
* @param angle the rotation angle of the gear
* @param color the color of the gear
*/
static void
draw_gear(struct gear *gear, GLfloat *transform,
GLfloat x, GLfloat y, GLfloat angle, const GLfloat color[4])
{
GLfloat model_view[16];
GLfloat normal_matrix[16];
GLfloat model_view_projection[16];
/* Translate and rotate the gear */
memcpy(model_view, transform, sizeof (model_view));
translate(model_view, x, y, 0);
rotate(model_view, 2 * M_PI * angle / 360.0, 0, 0, 1);
/* Create and set the ModelViewProjectionMatrix */
memcpy(model_view_projection, ProjectionMatrix, sizeof(model_view_projection));
multiply(model_view_projection, model_view);
glUniformMatrix4fv(ModelViewProjectionMatrix_location, 1, GL_FALSE,
model_view_projection);
/*
* Create and set the NormalMatrix. It's the inverse transpose of the
* ModelView matrix.
*/
memcpy(normal_matrix, model_view, sizeof (normal_matrix));
invert(normal_matrix);
transpose(normal_matrix);
glUniformMatrix4fv(NormalMatrix_location, 1, GL_FALSE, normal_matrix);
/* Set the gear color */
glUniform4fv(MaterialColor_location, 1, color);
/* Set the vertex buffer object to use */
glBindBuffer(GL_ARRAY_BUFFER, gear->vbo);
/* Set up the position of the attributes in the vertex buffer object */
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE,
6 * sizeof(GLfloat), NULL);
glVertexAttribPointer(1, 3, GL_FLOAT, GL_FALSE,
6 * sizeof(GLfloat), (GLfloat *) 0 + 3);
/* Enable the attributes */
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
/* Draw the triangle strips that comprise the gear */
int n;
for (n = 0; n < gear->nstrips; n++)
glDrawArrays(GL_TRIANGLE_STRIP, gear->strips[n].first, gear->strips[n].count);
/* Disable the attributes */
glDisableVertexAttribArray(1);
glDisableVertexAttribArray(0);
}
/**
* Draws the gears.
*/
static void
gears_draw(void)
{
const static GLfloat red[4] = { 0.8, 0.1, 0.0, 1.0 };
const static GLfloat green[4] = { 0.0, 0.8, 0.2, 1.0 };
const static GLfloat blue[4] = { 0.2, 0.2, 1.0, 1.0 };
GLfloat transform[16];
identity(transform);
glClearColor(0.0, 0.0, 0.0, 0.0);
glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
/* Translate and rotate the view */
translate(transform, 0, 0, -20);
rotate(transform, 2 * M_PI * view_rot[0] / 360.0, 1, 0, 0);
rotate(transform, 2 * M_PI * view_rot[1] / 360.0, 0, 1, 0);
rotate(transform, 2 * M_PI * view_rot[2] / 360.0, 0, 0, 1);
/* Draw the gears */
draw_gear(gear1, transform, -3.0, -2.0, angle, red);
draw_gear(gear2, transform, 3.1, -2.0, -2 * angle - 9.0, green);
draw_gear(gear3, transform, -3.1, 4.2, -2 * angle - 25.0, blue);
glutSwapBuffers();
}
/**
* Handles a new window size or exposure.
*
* @param width the window width
* @param height the window height
*/
static void
gears_reshape(int width, int height)
{
/* Update the projection matrix */
perspective(ProjectionMatrix, 60.0, width / (float)height, 1.0, 1024.0);
/* Set the viewport */
glViewport(0, 0, (GLint) width, (GLint) height);
}
/**
* Handles special glut events.
*
* @param special the event to handle.
*/
static void
gears_special(int special, int crap, int morecrap)
{
switch (special) {
case GLUT_KEY_LEFT:
view_rot[1] += 5.0;
break;
case GLUT_KEY_RIGHT:
view_rot[1] -= 5.0;
break;
case GLUT_KEY_UP:
view_rot[0] += 5.0;
break;
case GLUT_KEY_DOWN:
view_rot[0] -= 5.0;
break;
}
}
static void
gears_idle(void)
{
static int frames = 0;
static double tRot0 = -1.0, tRate0 = -1.0;
double dt, t = glutGet(GLUT_ELAPSED_TIME) / 1000.0;
if (tRot0 < 0.0)
tRot0 = t;
dt = t - tRot0;
tRot0 = t;
/* advance rotation for next frame */
angle += 70.0 * dt; /* 70 degrees per second */
if (angle > 3600.0)
angle -= 3600.0;
glutPostRedisplay();
frames++;
if (tRate0 < 0.0)
tRate0 = t;
if (t - tRate0 >= 5.0) {
GLfloat seconds = t - tRate0;
GLfloat fps = frames / seconds;
printf("%d frames in %3.1f seconds = %6.3f FPS\n", frames, seconds,
fps);
tRate0 = t;
frames = 0;
}
}
static const char vertex_shader[] =
"attribute vec3 position;\n"
"attribute vec3 normal;\n"
"\n"
"uniform mat4 ModelViewProjectionMatrix;\n"
"uniform mat4 NormalMatrix;\n"
"uniform vec4 LightSourcePosition;\n"
"uniform vec4 MaterialColor;\n"
"\n"
"varying vec4 Color;\n"
"\n"
"void main(void)\n"
"{\n"
" // Transform the normal to eye coordinates\n"
" vec3 N = normalize(vec3(NormalMatrix * vec4(normal, 1.0)));\n"
"\n"
" // The LightSourcePosition is actually its direction for directional light\n"
" vec3 L = normalize(LightSourcePosition.xyz);\n"
"\n"
" // Multiply the diffuse value by the vertex color (which is fixed in this case)\n"
" // to get the actual color that we will use to draw this vertex with\n"
" float diffuse = max(dot(N, L), 0.0);\n"
" Color = diffuse * MaterialColor;\n"
"\n"
" // Transform the position to clip coordinates\n"
" gl_Position = ModelViewProjectionMatrix * vec4(position, 1.0);\n"
"}";
static const char fragment_shader[] =
"#ifdef GL_ES\n"
"precision mediump float;\n"
"#endif\n"
"varying vec4 Color;\n"
"\n"
"void main(void)\n"
"{\n"
" vec2 d = dFdx(Color.xy);\n"
" gl_FragColor = Color;\n"
"}";
static void
gears_init(void)
{
GLuint v, f, program;
const char *p;
char msg[512];
glEnable(GL_CULL_FACE);
glEnable(GL_DEPTH_TEST);
/* Compile the vertex shader */
p = vertex_shader;
v = glCreateShader(GL_VERTEX_SHADER);
glShaderSource(v, 1, &p, NULL);
glCompileShader(v);
glGetShaderInfoLog(v, sizeof msg, NULL, msg);
printf("vertex shader info: %s\n", msg);
/* Compile the fragment shader */
p = fragment_shader;
f = glCreateShader(GL_FRAGMENT_SHADER);
glShaderSource(f, 1, &p, NULL);
glCompileShader(f);
glGetShaderInfoLog(f, sizeof msg, NULL, msg);
printf("fragment shader info: %s\n", msg);
/* Create and link the shader program */
program = glCreateProgram();
glAttachShader(program, v);
glAttachShader(program, f);
glBindAttribLocation(program, 0, "position");
glBindAttribLocation(program, 1, "normal");
glLinkProgram(program);
glGetProgramInfoLog(program, sizeof msg, NULL, msg);
printf("info: %s\n", msg);
/* Enable the shaders */
glUseProgram(program);
/* Get the locations of the uniforms so we can access them */
ModelViewProjectionMatrix_location = glGetUniformLocation(program, "ModelViewProjectionMatrix");
NormalMatrix_location = glGetUniformLocation(program, "NormalMatrix");
LightSourcePosition_location = glGetUniformLocation(program, "LightSourcePosition");
MaterialColor_location = glGetUniformLocation(program, "MaterialColor");
/* Set the LightSourcePosition uniform which is constant throught the program */
glUniform4fv(LightSourcePosition_location, 1, LightSourcePosition);
/* make the gears */
gear1 = create_gear(1.0, 4.0, 1.0, 20, 0.7);
gear2 = create_gear(0.5, 2.0, 2.0, 10, 0.7);
gear3 = create_gear(1.3, 2.0, 0.5, 10, 0.7);
}
int
main(int argc, char *argv[])
{
/* Initialize the window */
glutInit(&argc, argv);
glutInitWindowSize(300, 300);
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH);
glutCreateWindow("es2gears");
/* Set up glut callback functions */
gears_idle();
glutReshapeFunc(gears_reshape);
glutDisplayFunc(gears_draw);
glutSpecialFunc(gears_special);
/* Initialize the gears */
gears_init();
glutMainLoop();
return 0;
}
| mit |
impedimentToProgress/UCI-BlueChip | snapgear_linux/linux-2.6.21.1/arch/ia64/kernel/smpboot.c | 13 | 22084 | /*
* SMP boot-related support
*
* Copyright (C) 1998-2003, 2005 Hewlett-Packard Co
* David Mosberger-Tang <davidm@hpl.hp.com>
* Copyright (C) 2001, 2004-2005 Intel Corp
* Rohit Seth <rohit.seth@intel.com>
* Suresh Siddha <suresh.b.siddha@intel.com>
* Gordon Jin <gordon.jin@intel.com>
* Ashok Raj <ashok.raj@intel.com>
*
* 01/05/16 Rohit Seth <rohit.seth@intel.com> Moved SMP booting functions from smp.c to here.
* 01/04/27 David Mosberger <davidm@hpl.hp.com> Added ITC synching code.
* 02/07/31 David Mosberger <davidm@hpl.hp.com> Switch over to hotplug-CPU boot-sequence.
* smp_boot_cpus()/smp_commence() is replaced by
* smp_prepare_cpus()/__cpu_up()/smp_cpus_done().
* 04/06/21 Ashok Raj <ashok.raj@intel.com> Added CPU Hotplug Support
* 04/12/26 Jin Gordon <gordon.jin@intel.com>
* 04/12/26 Rohit Seth <rohit.seth@intel.com>
* Add multi-threading and multi-core detection
* 05/01/30 Suresh Siddha <suresh.b.siddha@intel.com>
* Setup cpu_sibling_map and cpu_core_map
*/
#include <linux/module.h>
#include <linux/acpi.h>
#include <linux/bootmem.h>
#include <linux/cpu.h>
#include <linux/delay.h>
#include <linux/init.h>
#include <linux/interrupt.h>
#include <linux/irq.h>
#include <linux/kernel.h>
#include <linux/kernel_stat.h>
#include <linux/mm.h>
#include <linux/notifier.h>
#include <linux/smp.h>
#include <linux/smp_lock.h>
#include <linux/spinlock.h>
#include <linux/efi.h>
#include <linux/percpu.h>
#include <linux/bitops.h>
#include <asm/atomic.h>
#include <asm/cache.h>
#include <asm/current.h>
#include <asm/delay.h>
#include <asm/ia32.h>
#include <asm/io.h>
#include <asm/irq.h>
#include <asm/machvec.h>
#include <asm/mca.h>
#include <asm/page.h>
#include <asm/pgalloc.h>
#include <asm/pgtable.h>
#include <asm/processor.h>
#include <asm/ptrace.h>
#include <asm/sal.h>
#include <asm/system.h>
#include <asm/tlbflush.h>
#include <asm/unistd.h>
#define SMP_DEBUG 0
#if SMP_DEBUG
#define Dprintk(x...) printk(x)
#else
#define Dprintk(x...)
#endif
#ifdef CONFIG_HOTPLUG_CPU
#ifdef CONFIG_PERMIT_BSP_REMOVE
#define bsp_remove_ok 1
#else
#define bsp_remove_ok 0
#endif
/*
* Store all idle threads, this can be reused instead of creating
* a new thread. Also avoids complicated thread destroy functionality
* for idle threads.
*/
struct task_struct *idle_thread_array[NR_CPUS];
/*
* Global array allocated for NR_CPUS at boot time
*/
struct sal_to_os_boot sal_boot_rendez_state[NR_CPUS];
/*
* start_ap in head.S uses this to store current booting cpu
* info.
*/
struct sal_to_os_boot *sal_state_for_booting_cpu = &sal_boot_rendez_state[0];
#define set_brendez_area(x) (sal_state_for_booting_cpu = &sal_boot_rendez_state[(x)]);
#define get_idle_for_cpu(x) (idle_thread_array[(x)])
#define set_idle_for_cpu(x,p) (idle_thread_array[(x)] = (p))
#else
#define get_idle_for_cpu(x) (NULL)
#define set_idle_for_cpu(x,p)
#define set_brendez_area(x)
#endif
/*
* ITC synchronization related stuff:
*/
#define MASTER (0)
#define SLAVE (SMP_CACHE_BYTES/8)
#define NUM_ROUNDS 64 /* magic value */
#define NUM_ITERS 5 /* likewise */
static DEFINE_SPINLOCK(itc_sync_lock);
static volatile unsigned long go[SLAVE + 1];
#define DEBUG_ITC_SYNC 0
extern void __devinit calibrate_delay (void);
extern void start_ap (void);
extern unsigned long ia64_iobase;
struct task_struct *task_for_booting_cpu;
/*
* State for each CPU
*/
DEFINE_PER_CPU(int, cpu_state);
/* Bitmasks of currently online, and possible CPUs */
cpumask_t cpu_online_map;
EXPORT_SYMBOL(cpu_online_map);
cpumask_t cpu_possible_map = CPU_MASK_NONE;
EXPORT_SYMBOL(cpu_possible_map);
cpumask_t cpu_core_map[NR_CPUS] __cacheline_aligned;
cpumask_t cpu_sibling_map[NR_CPUS] __cacheline_aligned;
int smp_num_siblings = 1;
int smp_num_cpucores = 1;
/* which logical CPU number maps to which CPU (physical APIC ID) */
volatile int ia64_cpu_to_sapicid[NR_CPUS];
EXPORT_SYMBOL(ia64_cpu_to_sapicid);
static volatile cpumask_t cpu_callin_map;
struct smp_boot_data smp_boot_data __initdata;
unsigned long ap_wakeup_vector = -1; /* External Int use to wakeup APs */
char __initdata no_int_routing;
unsigned char smp_int_redirect; /* are INT and IPI redirectable by the chipset? */
#ifdef CONFIG_FORCE_CPEI_RETARGET
#define CPEI_OVERRIDE_DEFAULT (1)
#else
#define CPEI_OVERRIDE_DEFAULT (0)
#endif
unsigned int force_cpei_retarget = CPEI_OVERRIDE_DEFAULT;
static int __init
cmdl_force_cpei(char *str)
{
int value=0;
get_option (&str, &value);
force_cpei_retarget = value;
return 1;
}
__setup("force_cpei=", cmdl_force_cpei);
static int __init
nointroute (char *str)
{
no_int_routing = 1;
printk ("no_int_routing on\n");
return 1;
}
__setup("nointroute", nointroute);
static void fix_b0_for_bsp(void)
{
#ifdef CONFIG_HOTPLUG_CPU
int cpuid;
static int fix_bsp_b0 = 1;
cpuid = smp_processor_id();
/*
* Cache the b0 value on the first AP that comes up
*/
if (!(fix_bsp_b0 && cpuid))
return;
sal_boot_rendez_state[0].br[0] = sal_boot_rendez_state[cpuid].br[0];
printk ("Fixed BSP b0 value from CPU %d\n", cpuid);
fix_bsp_b0 = 0;
#endif
}
void
sync_master (void *arg)
{
unsigned long flags, i;
go[MASTER] = 0;
local_irq_save(flags);
{
for (i = 0; i < NUM_ROUNDS*NUM_ITERS; ++i) {
while (!go[MASTER])
cpu_relax();
go[MASTER] = 0;
go[SLAVE] = ia64_get_itc();
}
}
local_irq_restore(flags);
}
/*
* Return the number of cycles by which our itc differs from the itc on the master
* (time-keeper) CPU. A positive number indicates our itc is ahead of the master,
* negative that it is behind.
*/
static inline long
get_delta (long *rt, long *master)
{
unsigned long best_t0 = 0, best_t1 = ~0UL, best_tm = 0;
unsigned long tcenter, t0, t1, tm;
long i;
for (i = 0; i < NUM_ITERS; ++i) {
t0 = ia64_get_itc();
go[MASTER] = 1;
while (!(tm = go[SLAVE]))
cpu_relax();
go[SLAVE] = 0;
t1 = ia64_get_itc();
if (t1 - t0 < best_t1 - best_t0)
best_t0 = t0, best_t1 = t1, best_tm = tm;
}
*rt = best_t1 - best_t0;
*master = best_tm - best_t0;
/* average best_t0 and best_t1 without overflow: */
tcenter = (best_t0/2 + best_t1/2);
if (best_t0 % 2 + best_t1 % 2 == 2)
++tcenter;
return tcenter - best_tm;
}
/*
* Synchronize ar.itc of the current (slave) CPU with the ar.itc of the MASTER CPU
* (normally the time-keeper CPU). We use a closed loop to eliminate the possibility of
* unaccounted-for errors (such as getting a machine check in the middle of a calibration
* step). The basic idea is for the slave to ask the master what itc value it has and to
* read its own itc before and after the master responds. Each iteration gives us three
* timestamps:
*
* slave master
*
* t0 ---\
* ---\
* --->
* tm
* /---
* /---
* t1 <---
*
*
* The goal is to adjust the slave's ar.itc such that tm falls exactly half-way between t0
* and t1. If we achieve this, the clocks are synchronized provided the interconnect
* between the slave and the master is symmetric. Even if the interconnect were
* asymmetric, we would still know that the synchronization error is smaller than the
* roundtrip latency (t0 - t1).
*
* When the interconnect is quiet and symmetric, this lets us synchronize the itc to
* within one or two cycles. However, we can only *guarantee* that the synchronization is
* accurate to within a round-trip time, which is typically in the range of several
* hundred cycles (e.g., ~500 cycles). In practice, this means that the itc's are usually
* almost perfectly synchronized, but we shouldn't assume that the accuracy is much better
* than half a micro second or so.
*/
void
ia64_sync_itc (unsigned int master)
{
long i, delta, adj, adjust_latency = 0, done = 0;
unsigned long flags, rt, master_time_stamp, bound;
#if DEBUG_ITC_SYNC
struct {
long rt; /* roundtrip time */
long master; /* master's timestamp */
long diff; /* difference between midpoint and master's timestamp */
long lat; /* estimate of itc adjustment latency */
} t[NUM_ROUNDS];
#endif
/*
* Make sure local timer ticks are disabled while we sync. If
* they were enabled, we'd have to worry about nasty issues
* like setting the ITC ahead of (or a long time before) the
* next scheduled tick.
*/
BUG_ON((ia64_get_itv() & (1 << 16)) == 0);
go[MASTER] = 1;
if (smp_call_function_single(master, sync_master, NULL, 1, 0) < 0) {
printk(KERN_ERR "sync_itc: failed to get attention of CPU %u!\n", master);
return;
}
while (go[MASTER])
cpu_relax(); /* wait for master to be ready */
spin_lock_irqsave(&itc_sync_lock, flags);
{
for (i = 0; i < NUM_ROUNDS; ++i) {
delta = get_delta(&rt, &master_time_stamp);
if (delta == 0) {
done = 1; /* let's lock on to this... */
bound = rt;
}
if (!done) {
if (i > 0) {
adjust_latency += -delta;
adj = -delta + adjust_latency/4;
} else
adj = -delta;
ia64_set_itc(ia64_get_itc() + adj);
}
#if DEBUG_ITC_SYNC
t[i].rt = rt;
t[i].master = master_time_stamp;
t[i].diff = delta;
t[i].lat = adjust_latency/4;
#endif
}
}
spin_unlock_irqrestore(&itc_sync_lock, flags);
#if DEBUG_ITC_SYNC
for (i = 0; i < NUM_ROUNDS; ++i)
printk("rt=%5ld master=%5ld diff=%5ld adjlat=%5ld\n",
t[i].rt, t[i].master, t[i].diff, t[i].lat);
#endif
printk(KERN_INFO "CPU %d: synchronized ITC with CPU %u (last diff %ld cycles, "
"maxerr %lu cycles)\n", smp_processor_id(), master, delta, rt);
}
/*
* Ideally sets up per-cpu profiling hooks. Doesn't do much now...
*/
static inline void __devinit
smp_setup_percpu_timer (void)
{
}
static void __devinit
smp_callin (void)
{
int cpuid, phys_id, itc_master;
struct cpuinfo_ia64 *last_cpuinfo, *this_cpuinfo;
extern void ia64_init_itm(void);
extern volatile int time_keeper_id;
#ifdef CONFIG_PERFMON
extern void pfm_init_percpu(void);
#endif
cpuid = smp_processor_id();
phys_id = hard_smp_processor_id();
itc_master = time_keeper_id;
if (cpu_online(cpuid)) {
printk(KERN_ERR "huh, phys CPU#0x%x, CPU#0x%x already present??\n",
phys_id, cpuid);
BUG();
}
fix_b0_for_bsp();
lock_ipi_calllock();
cpu_set(cpuid, cpu_online_map);
unlock_ipi_calllock();
per_cpu(cpu_state, cpuid) = CPU_ONLINE;
smp_setup_percpu_timer();
ia64_mca_cmc_vector_setup(); /* Setup vector on AP */
#ifdef CONFIG_PERFMON
pfm_init_percpu();
#endif
local_irq_enable();
if (!(sal_platform_features & IA64_SAL_PLATFORM_FEATURE_ITC_DRIFT)) {
/*
* Synchronize the ITC with the BP. Need to do this after irqs are
* enabled because ia64_sync_itc() calls smp_call_function_single(), which
* calls spin_unlock_bh(), which calls spin_unlock_bh(), which calls
* local_bh_enable(), which bugs out if irqs are not enabled...
*/
Dprintk("Going to syncup ITC with ITC Master.\n");
ia64_sync_itc(itc_master);
}
/*
* Get our bogomips.
*/
ia64_init_itm();
/*
* Delay calibration can be skipped if new processor is identical to the
* previous processor.
*/
last_cpuinfo = cpu_data(cpuid - 1);
this_cpuinfo = local_cpu_data;
if (last_cpuinfo->itc_freq != this_cpuinfo->itc_freq ||
last_cpuinfo->proc_freq != this_cpuinfo->proc_freq ||
last_cpuinfo->features != this_cpuinfo->features ||
last_cpuinfo->revision != this_cpuinfo->revision ||
last_cpuinfo->family != this_cpuinfo->family ||
last_cpuinfo->archrev != this_cpuinfo->archrev ||
last_cpuinfo->model != this_cpuinfo->model)
calibrate_delay();
local_cpu_data->loops_per_jiffy = loops_per_jiffy;
#ifdef CONFIG_IA32_SUPPORT
ia32_gdt_init();
#endif
/*
* Allow the master to continue.
*/
cpu_set(cpuid, cpu_callin_map);
Dprintk("Stack on CPU %d at about %p\n",cpuid, &cpuid);
}
/*
* Activate a secondary processor. head.S calls this.
*/
int __devinit
start_secondary (void *unused)
{
/* Early console may use I/O ports */
ia64_set_kr(IA64_KR_IO_BASE, __pa(ia64_iobase));
Dprintk("start_secondary: starting CPU 0x%x\n", hard_smp_processor_id());
efi_map_pal_code();
cpu_init();
preempt_disable();
smp_callin();
cpu_idle();
return 0;
}
struct pt_regs * __devinit idle_regs(struct pt_regs *regs)
{
return NULL;
}
struct create_idle {
struct work_struct work;
struct task_struct *idle;
struct completion done;
int cpu;
};
void
do_fork_idle(struct work_struct *work)
{
struct create_idle *c_idle =
container_of(work, struct create_idle, work);
c_idle->idle = fork_idle(c_idle->cpu);
complete(&c_idle->done);
}
static int __devinit
do_boot_cpu (int sapicid, int cpu)
{
int timeout;
struct create_idle c_idle = {
.work = __WORK_INITIALIZER(c_idle.work, do_fork_idle),
.cpu = cpu,
.done = COMPLETION_INITIALIZER(c_idle.done),
};
c_idle.idle = get_idle_for_cpu(cpu);
if (c_idle.idle) {
init_idle(c_idle.idle, cpu);
goto do_rest;
}
/*
* We can't use kernel_thread since we must avoid to reschedule the child.
*/
if (!keventd_up() || current_is_keventd())
c_idle.work.func(&c_idle.work);
else {
schedule_work(&c_idle.work);
wait_for_completion(&c_idle.done);
}
if (IS_ERR(c_idle.idle))
panic("failed fork for CPU %d", cpu);
set_idle_for_cpu(cpu, c_idle.idle);
do_rest:
task_for_booting_cpu = c_idle.idle;
Dprintk("Sending wakeup vector %lu to AP 0x%x/0x%x.\n", ap_wakeup_vector, cpu, sapicid);
set_brendez_area(cpu);
platform_send_ipi(cpu, ap_wakeup_vector, IA64_IPI_DM_INT, 0);
/*
* Wait 10s total for the AP to start
*/
Dprintk("Waiting on callin_map ...");
for (timeout = 0; timeout < 100000; timeout++) {
if (cpu_isset(cpu, cpu_callin_map))
break; /* It has booted */
udelay(100);
}
Dprintk("\n");
if (!cpu_isset(cpu, cpu_callin_map)) {
printk(KERN_ERR "Processor 0x%x/0x%x is stuck.\n", cpu, sapicid);
ia64_cpu_to_sapicid[cpu] = -1;
cpu_clear(cpu, cpu_online_map); /* was set in smp_callin() */
return -EINVAL;
}
return 0;
}
static int __init
decay (char *str)
{
int ticks;
get_option (&str, &ticks);
return 1;
}
__setup("decay=", decay);
/*
* Initialize the logical CPU number to SAPICID mapping
*/
void __init
smp_build_cpu_map (void)
{
int sapicid, cpu, i;
int boot_cpu_id = hard_smp_processor_id();
for (cpu = 0; cpu < NR_CPUS; cpu++) {
ia64_cpu_to_sapicid[cpu] = -1;
}
ia64_cpu_to_sapicid[0] = boot_cpu_id;
cpus_clear(cpu_present_map);
cpu_set(0, cpu_present_map);
cpu_set(0, cpu_possible_map);
for (cpu = 1, i = 0; i < smp_boot_data.cpu_count; i++) {
sapicid = smp_boot_data.cpu_phys_id[i];
if (sapicid == boot_cpu_id)
continue;
cpu_set(cpu, cpu_present_map);
cpu_set(cpu, cpu_possible_map);
ia64_cpu_to_sapicid[cpu] = sapicid;
cpu++;
}
}
/*
* Cycle through the APs sending Wakeup IPIs to boot each.
*/
void __init
smp_prepare_cpus (unsigned int max_cpus)
{
int boot_cpu_id = hard_smp_processor_id();
/*
* Initialize the per-CPU profiling counter/multiplier
*/
smp_setup_percpu_timer();
/*
* We have the boot CPU online for sure.
*/
cpu_set(0, cpu_online_map);
cpu_set(0, cpu_callin_map);
local_cpu_data->loops_per_jiffy = loops_per_jiffy;
ia64_cpu_to_sapicid[0] = boot_cpu_id;
printk(KERN_INFO "Boot processor id 0x%x/0x%x\n", 0, boot_cpu_id);
current_thread_info()->cpu = 0;
/*
* If SMP should be disabled, then really disable it!
*/
if (!max_cpus) {
printk(KERN_INFO "SMP mode deactivated.\n");
cpus_clear(cpu_online_map);
cpus_clear(cpu_present_map);
cpus_clear(cpu_possible_map);
cpu_set(0, cpu_online_map);
cpu_set(0, cpu_present_map);
cpu_set(0, cpu_possible_map);
return;
}
}
void __devinit smp_prepare_boot_cpu(void)
{
cpu_set(smp_processor_id(), cpu_online_map);
cpu_set(smp_processor_id(), cpu_callin_map);
per_cpu(cpu_state, smp_processor_id()) = CPU_ONLINE;
}
#ifdef CONFIG_HOTPLUG_CPU
static inline void
clear_cpu_sibling_map(int cpu)
{
int i;
for_each_cpu_mask(i, cpu_sibling_map[cpu])
cpu_clear(cpu, cpu_sibling_map[i]);
for_each_cpu_mask(i, cpu_core_map[cpu])
cpu_clear(cpu, cpu_core_map[i]);
cpu_sibling_map[cpu] = cpu_core_map[cpu] = CPU_MASK_NONE;
}
static void
remove_siblinginfo(int cpu)
{
int last = 0;
if (cpu_data(cpu)->threads_per_core == 1 &&
cpu_data(cpu)->cores_per_socket == 1) {
cpu_clear(cpu, cpu_core_map[cpu]);
cpu_clear(cpu, cpu_sibling_map[cpu]);
return;
}
last = (cpus_weight(cpu_core_map[cpu]) == 1 ? 1 : 0);
/* remove it from all sibling map's */
clear_cpu_sibling_map(cpu);
}
extern void fixup_irqs(void);
int migrate_platform_irqs(unsigned int cpu)
{
int new_cpei_cpu;
irq_desc_t *desc = NULL;
cpumask_t mask;
int retval = 0;
/*
* dont permit CPEI target to removed.
*/
if (cpe_vector > 0 && is_cpu_cpei_target(cpu)) {
printk ("CPU (%d) is CPEI Target\n", cpu);
if (can_cpei_retarget()) {
/*
* Now re-target the CPEI to a different processor
*/
new_cpei_cpu = any_online_cpu(cpu_online_map);
mask = cpumask_of_cpu(new_cpei_cpu);
set_cpei_target_cpu(new_cpei_cpu);
desc = irq_desc + ia64_cpe_irq;
/*
* Switch for now, immediatly, we need to do fake intr
* as other interrupts, but need to study CPEI behaviour with
* polling before making changes.
*/
if (desc) {
desc->chip->disable(ia64_cpe_irq);
desc->chip->set_affinity(ia64_cpe_irq, mask);
desc->chip->enable(ia64_cpe_irq);
printk ("Re-targetting CPEI to cpu %d\n", new_cpei_cpu);
}
}
if (!desc) {
printk ("Unable to retarget CPEI, offline cpu [%d] failed\n", cpu);
retval = -EBUSY;
}
}
return retval;
}
/* must be called with cpucontrol mutex held */
int __cpu_disable(void)
{
int cpu = smp_processor_id();
/*
* dont permit boot processor for now
*/
if (cpu == 0 && !bsp_remove_ok) {
printk ("Your platform does not support removal of BSP\n");
return (-EBUSY);
}
cpu_clear(cpu, cpu_online_map);
if (migrate_platform_irqs(cpu)) {
cpu_set(cpu, cpu_online_map);
return (-EBUSY);
}
remove_siblinginfo(cpu);
cpu_clear(cpu, cpu_online_map);
fixup_irqs();
local_flush_tlb_all();
cpu_clear(cpu, cpu_callin_map);
return 0;
}
void __cpu_die(unsigned int cpu)
{
unsigned int i;
for (i = 0; i < 100; i++) {
/* They ack this in play_dead by setting CPU_DEAD */
if (per_cpu(cpu_state, cpu) == CPU_DEAD)
{
printk ("CPU %d is now offline\n", cpu);
return;
}
msleep(100);
}
printk(KERN_ERR "CPU %u didn't die...\n", cpu);
}
#else /* !CONFIG_HOTPLUG_CPU */
int __cpu_disable(void)
{
return -ENOSYS;
}
void __cpu_die(unsigned int cpu)
{
/* We said "no" in __cpu_disable */
BUG();
}
#endif /* CONFIG_HOTPLUG_CPU */
void
smp_cpus_done (unsigned int dummy)
{
int cpu;
unsigned long bogosum = 0;
/*
* Allow the user to impress friends.
*/
for_each_online_cpu(cpu) {
bogosum += cpu_data(cpu)->loops_per_jiffy;
}
printk(KERN_INFO "Total of %d processors activated (%lu.%02lu BogoMIPS).\n",
(int)num_online_cpus(), bogosum/(500000/HZ), (bogosum/(5000/HZ))%100);
}
static inline void __devinit
set_cpu_sibling_map(int cpu)
{
int i;
for_each_online_cpu(i) {
if ((cpu_data(cpu)->socket_id == cpu_data(i)->socket_id)) {
cpu_set(i, cpu_core_map[cpu]);
cpu_set(cpu, cpu_core_map[i]);
if (cpu_data(cpu)->core_id == cpu_data(i)->core_id) {
cpu_set(i, cpu_sibling_map[cpu]);
cpu_set(cpu, cpu_sibling_map[i]);
}
}
}
}
int __devinit
__cpu_up (unsigned int cpu)
{
int ret;
int sapicid;
sapicid = ia64_cpu_to_sapicid[cpu];
if (sapicid == -1)
return -EINVAL;
/*
* Already booted cpu? not valid anymore since we dont
* do idle loop tightspin anymore.
*/
if (cpu_isset(cpu, cpu_callin_map))
return -EINVAL;
per_cpu(cpu_state, cpu) = CPU_UP_PREPARE;
/* Processor goes to start_secondary(), sets online flag */
ret = do_boot_cpu(sapicid, cpu);
if (ret < 0)
return ret;
if (cpu_data(cpu)->threads_per_core == 1 &&
cpu_data(cpu)->cores_per_socket == 1) {
cpu_set(cpu, cpu_sibling_map[cpu]);
cpu_set(cpu, cpu_core_map[cpu]);
return 0;
}
set_cpu_sibling_map(cpu);
return 0;
}
/*
* Assume that CPU's have been discovered by some platform-dependent interface. For
* SoftSDV/Lion, that would be ACPI.
*
* Setup of the IPI irq handler is done in irq.c:init_IRQ_SMP().
*/
void __init
init_smp_config(void)
{
struct fptr {
unsigned long fp;
unsigned long gp;
} *ap_startup;
long sal_ret;
/* Tell SAL where to drop the AP's. */
ap_startup = (struct fptr *) start_ap;
sal_ret = ia64_sal_set_vectors(SAL_VECTOR_OS_BOOT_RENDEZ,
ia64_tpa(ap_startup->fp), ia64_tpa(ap_startup->gp), 0, 0, 0, 0);
if (sal_ret < 0)
printk(KERN_ERR "SMP: Can't set SAL AP Boot Rendezvous: %s\n",
ia64_sal_strerror(sal_ret));
}
/*
* identify_siblings(cpu) gets called from identify_cpu. This populates the
* information related to logical execution units in per_cpu_data structure.
*/
void __devinit
identify_siblings(struct cpuinfo_ia64 *c)
{
s64 status;
u16 pltid;
pal_logical_to_physical_t info;
if (smp_num_cpucores == 1 && smp_num_siblings == 1)
return;
if ((status = ia64_pal_logical_to_phys(-1, &info)) != PAL_STATUS_SUCCESS) {
printk(KERN_ERR "ia64_pal_logical_to_phys failed with %ld\n",
status);
return;
}
if ((status = ia64_sal_physical_id_info(&pltid)) != PAL_STATUS_SUCCESS) {
printk(KERN_ERR "ia64_sal_pltid failed with %ld\n", status);
return;
}
c->socket_id = (pltid << 8) | info.overview_ppid;
c->cores_per_socket = info.overview_cpp;
c->threads_per_core = info.overview_tpc;
c->num_log = info.overview_num_log;
c->core_id = info.log1_cid;
c->thread_id = info.log1_tid;
}
/*
* returns non zero, if multi-threading is enabled
* on at least one physical package. Due to hotplug cpu
* and (maxcpus=), all threads may not necessarily be enabled
* even though the processor supports multi-threading.
*/
int is_multithreading_enabled(void)
{
int i, j;
for_each_present_cpu(i) {
for_each_present_cpu(j) {
if (j == i)
continue;
if ((cpu_data(j)->socket_id == cpu_data(i)->socket_id)) {
if (cpu_data(j)->core_id == cpu_data(i)->core_id)
return 1;
}
}
}
return 0;
}
EXPORT_SYMBOL_GPL(is_multithreading_enabled);
| mit |
Achierius/SysSim | include/Eigen/test/qr_colpivoting.cpp | 14 | 5332 | // This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2008 Gael Guennebaud <gael.guennebaud@inria.fr>
// Copyright (C) 2009 Benoit Jacob <jacob.benoit.1@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include "main.h"
#include <Eigen/QR>
template<typename MatrixType> void qr()
{
typedef typename MatrixType::Index Index;
Index rows = internal::random<Index>(2,EIGEN_TEST_MAX_SIZE), cols = internal::random<Index>(2,EIGEN_TEST_MAX_SIZE), cols2 = internal::random<Index>(2,EIGEN_TEST_MAX_SIZE);
Index rank = internal::random<Index>(1, (std::min)(rows, cols)-1);
typedef typename MatrixType::Scalar Scalar;
typedef Matrix<Scalar, MatrixType::RowsAtCompileTime, MatrixType::RowsAtCompileTime> MatrixQType;
MatrixType m1;
createRandomPIMatrixOfRank(rank,rows,cols,m1);
ColPivHouseholderQR<MatrixType> qr(m1);
VERIFY_IS_EQUAL(rank, qr.rank());
VERIFY_IS_EQUAL(cols - qr.rank(), qr.dimensionOfKernel());
VERIFY(!qr.isInjective());
VERIFY(!qr.isInvertible());
VERIFY(!qr.isSurjective());
MatrixQType q = qr.householderQ();
VERIFY_IS_UNITARY(q);
MatrixType r = qr.matrixQR().template triangularView<Upper>();
MatrixType c = q * r * qr.colsPermutation().inverse();
VERIFY_IS_APPROX(m1, c);
MatrixType m2 = MatrixType::Random(cols,cols2);
MatrixType m3 = m1*m2;
m2 = MatrixType::Random(cols,cols2);
m2 = qr.solve(m3);
VERIFY_IS_APPROX(m3, m1*m2);
}
template<typename MatrixType, int Cols2> void qr_fixedsize()
{
enum { Rows = MatrixType::RowsAtCompileTime, Cols = MatrixType::ColsAtCompileTime };
typedef typename MatrixType::Scalar Scalar;
int rank = internal::random<int>(1, (std::min)(int(Rows), int(Cols))-1);
Matrix<Scalar,Rows,Cols> m1;
createRandomPIMatrixOfRank(rank,Rows,Cols,m1);
ColPivHouseholderQR<Matrix<Scalar,Rows,Cols> > qr(m1);
VERIFY_IS_EQUAL(rank, qr.rank());
VERIFY_IS_EQUAL(Cols - qr.rank(), qr.dimensionOfKernel());
VERIFY_IS_EQUAL(qr.isInjective(), (rank == Rows));
VERIFY_IS_EQUAL(qr.isSurjective(), (rank == Cols));
VERIFY_IS_EQUAL(qr.isInvertible(), (qr.isInjective() && qr.isSurjective()));
Matrix<Scalar,Rows,Cols> r = qr.matrixQR().template triangularView<Upper>();
Matrix<Scalar,Rows,Cols> c = qr.householderQ() * r * qr.colsPermutation().inverse();
VERIFY_IS_APPROX(m1, c);
Matrix<Scalar,Cols,Cols2> m2 = Matrix<Scalar,Cols,Cols2>::Random(Cols,Cols2);
Matrix<Scalar,Rows,Cols2> m3 = m1*m2;
m2 = Matrix<Scalar,Cols,Cols2>::Random(Cols,Cols2);
m2 = qr.solve(m3);
VERIFY_IS_APPROX(m3, m1*m2);
}
template<typename MatrixType> void qr_invertible()
{
using std::log;
using std::abs;
typedef typename NumTraits<typename MatrixType::Scalar>::Real RealScalar;
typedef typename MatrixType::Scalar Scalar;
int size = internal::random<int>(10,50);
MatrixType m1(size, size), m2(size, size), m3(size, size);
m1 = MatrixType::Random(size,size);
if (internal::is_same<RealScalar,float>::value)
{
// let's build a matrix more stable to inverse
MatrixType a = MatrixType::Random(size,size*2);
m1 += a * a.adjoint();
}
ColPivHouseholderQR<MatrixType> qr(m1);
m3 = MatrixType::Random(size,size);
m2 = qr.solve(m3);
//VERIFY_IS_APPROX(m3, m1*m2);
// now construct a matrix with prescribed determinant
m1.setZero();
for(int i = 0; i < size; i++) m1(i,i) = internal::random<Scalar>();
RealScalar absdet = abs(m1.diagonal().prod());
m3 = qr.householderQ(); // get a unitary
m1 = m3 * m1 * m3;
qr.compute(m1);
VERIFY_IS_APPROX(absdet, qr.absDeterminant());
VERIFY_IS_APPROX(log(absdet), qr.logAbsDeterminant());
}
template<typename MatrixType> void qr_verify_assert()
{
MatrixType tmp;
ColPivHouseholderQR<MatrixType> qr;
VERIFY_RAISES_ASSERT(qr.matrixQR())
VERIFY_RAISES_ASSERT(qr.solve(tmp))
VERIFY_RAISES_ASSERT(qr.householderQ())
VERIFY_RAISES_ASSERT(qr.dimensionOfKernel())
VERIFY_RAISES_ASSERT(qr.isInjective())
VERIFY_RAISES_ASSERT(qr.isSurjective())
VERIFY_RAISES_ASSERT(qr.isInvertible())
VERIFY_RAISES_ASSERT(qr.inverse())
VERIFY_RAISES_ASSERT(qr.absDeterminant())
VERIFY_RAISES_ASSERT(qr.logAbsDeterminant())
}
void test_qr_colpivoting()
{
for(int i = 0; i < g_repeat; i++) {
CALL_SUBTEST_1( qr<MatrixXf>() );
CALL_SUBTEST_2( qr<MatrixXd>() );
CALL_SUBTEST_3( qr<MatrixXcd>() );
CALL_SUBTEST_4(( qr_fixedsize<Matrix<float,3,5>, 4 >() ));
CALL_SUBTEST_5(( qr_fixedsize<Matrix<double,6,2>, 3 >() ));
CALL_SUBTEST_5(( qr_fixedsize<Matrix<double,1,1>, 1 >() ));
}
for(int i = 0; i < g_repeat; i++) {
CALL_SUBTEST_1( qr_invertible<MatrixXf>() );
CALL_SUBTEST_2( qr_invertible<MatrixXd>() );
CALL_SUBTEST_6( qr_invertible<MatrixXcf>() );
CALL_SUBTEST_3( qr_invertible<MatrixXcd>() );
}
CALL_SUBTEST_7(qr_verify_assert<Matrix3f>());
CALL_SUBTEST_8(qr_verify_assert<Matrix3d>());
CALL_SUBTEST_1(qr_verify_assert<MatrixXf>());
CALL_SUBTEST_2(qr_verify_assert<MatrixXd>());
CALL_SUBTEST_6(qr_verify_assert<MatrixXcf>());
CALL_SUBTEST_3(qr_verify_assert<MatrixXcd>());
// Test problem size constructors
CALL_SUBTEST_9(ColPivHouseholderQR<MatrixXf>(10, 20));
}
| mit |
ignorabimus/micropython-c-api | micropython/py/persistentcode.c | 15 | 12709 | /*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2013-2016 Damien P. George
*
* 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 <stdint.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include "py/reader.h"
#include "py/emitglue.h"
#include "py/persistentcode.h"
#include "py/bc.h"
#if MICROPY_PERSISTENT_CODE_LOAD || MICROPY_PERSISTENT_CODE_SAVE
#include "py/smallint.h"
// The current version of .mpy files
#define MPY_VERSION (2)
// The feature flags byte encodes the compile-time config options that
// affect the generate bytecode.
#define MPY_FEATURE_FLAGS ( \
((MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE) << 0) \
| ((MICROPY_PY_BUILTINS_STR_UNICODE) << 1) \
)
// This is a version of the flags that can be configured at runtime.
#define MPY_FEATURE_FLAGS_DYNAMIC ( \
((MICROPY_OPT_CACHE_MAP_LOOKUP_IN_BYTECODE_DYNAMIC) << 0) \
| ((MICROPY_PY_BUILTINS_STR_UNICODE_DYNAMIC) << 1) \
)
#if MICROPY_PERSISTENT_CODE_LOAD || (MICROPY_PERSISTENT_CODE_SAVE && !MICROPY_DYNAMIC_COMPILER)
// The bytecode will depend on the number of bits in a small-int, and
// this function computes that (could make it a fixed constant, but it
// would need to be defined in mpconfigport.h).
STATIC int mp_small_int_bits(void) {
mp_int_t i = MP_SMALL_INT_MAX;
int n = 1;
while (i != 0) {
i >>= 1;
++n;
}
return n;
}
#endif
typedef struct _bytecode_prelude_t {
uint n_state;
uint n_exc_stack;
uint scope_flags;
uint n_pos_args;
uint n_kwonly_args;
uint n_def_pos_args;
uint code_info_size;
} bytecode_prelude_t;
// ip will point to start of opcodes
// ip2 will point to simple_name, source_file qstrs
STATIC void extract_prelude(const byte **ip, const byte **ip2, bytecode_prelude_t *prelude) {
prelude->n_state = mp_decode_uint(ip);
prelude->n_exc_stack = mp_decode_uint(ip);
prelude->scope_flags = *(*ip)++;
prelude->n_pos_args = *(*ip)++;
prelude->n_kwonly_args = *(*ip)++;
prelude->n_def_pos_args = *(*ip)++;
*ip2 = *ip;
prelude->code_info_size = mp_decode_uint(ip2);
*ip += prelude->code_info_size;
while (*(*ip)++ != 255) {
}
}
#endif // MICROPY_PERSISTENT_CODE_LOAD || MICROPY_PERSISTENT_CODE_SAVE
#if MICROPY_PERSISTENT_CODE_LOAD
#include "py/parsenum.h"
#include "py/bc0.h"
STATIC int read_byte(mp_reader_t *reader) {
return reader->readbyte(reader->data);
}
STATIC void read_bytes(mp_reader_t *reader, byte *buf, size_t len) {
while (len-- > 0) {
*buf++ = reader->readbyte(reader->data);
}
}
STATIC size_t read_uint(mp_reader_t *reader) {
size_t unum = 0;
for (;;) {
byte b = reader->readbyte(reader->data);
unum = (unum << 7) | (b & 0x7f);
if ((b & 0x80) == 0) {
break;
}
}
return unum;
}
STATIC qstr load_qstr(mp_reader_t *reader) {
size_t len = read_uint(reader);
char *str = m_new(char, len);
read_bytes(reader, (byte*)str, len);
qstr qst = qstr_from_strn(str, len);
m_del(char, str, len);
return qst;
}
STATIC mp_obj_t load_obj(mp_reader_t *reader) {
byte obj_type = read_byte(reader);
if (obj_type == 'e') {
return MP_OBJ_FROM_PTR(&mp_const_ellipsis_obj);
} else {
size_t len = read_uint(reader);
vstr_t vstr;
vstr_init_len(&vstr, len);
read_bytes(reader, (byte*)vstr.buf, len);
if (obj_type == 's' || obj_type == 'b') {
return mp_obj_new_str_from_vstr(obj_type == 's' ? &mp_type_str : &mp_type_bytes, &vstr);
} else if (obj_type == 'i') {
return mp_parse_num_integer(vstr.buf, vstr.len, 10, NULL);
} else {
assert(obj_type == 'f' || obj_type == 'c');
return mp_parse_num_decimal(vstr.buf, vstr.len, obj_type == 'c', false, NULL);
}
}
}
STATIC void load_bytecode_qstrs(mp_reader_t *reader, byte *ip, byte *ip_top) {
while (ip < ip_top) {
size_t sz;
uint f = mp_opcode_format(ip, &sz);
if (f == MP_OPCODE_QSTR) {
qstr qst = load_qstr(reader);
ip[1] = qst;
ip[2] = qst >> 8;
}
ip += sz;
}
}
STATIC mp_raw_code_t *load_raw_code(mp_reader_t *reader) {
// load bytecode
size_t bc_len = read_uint(reader);
byte *bytecode = m_new(byte, bc_len);
read_bytes(reader, bytecode, bc_len);
// extract prelude
const byte *ip = bytecode;
const byte *ip2;
bytecode_prelude_t prelude;
extract_prelude(&ip, &ip2, &prelude);
// load qstrs and link global qstr ids into bytecode
qstr simple_name = load_qstr(reader);
qstr source_file = load_qstr(reader);
((byte*)ip2)[0] = simple_name; ((byte*)ip2)[1] = simple_name >> 8;
((byte*)ip2)[2] = source_file; ((byte*)ip2)[3] = source_file >> 8;
load_bytecode_qstrs(reader, (byte*)ip, bytecode + bc_len);
// load constant table
size_t n_obj = read_uint(reader);
size_t n_raw_code = read_uint(reader);
mp_uint_t *const_table = m_new(mp_uint_t, prelude.n_pos_args + prelude.n_kwonly_args + n_obj + n_raw_code);
mp_uint_t *ct = const_table;
for (size_t i = 0; i < prelude.n_pos_args + prelude.n_kwonly_args; ++i) {
*ct++ = (mp_uint_t)MP_OBJ_NEW_QSTR(load_qstr(reader));
}
for (size_t i = 0; i < n_obj; ++i) {
*ct++ = (mp_uint_t)load_obj(reader);
}
for (size_t i = 0; i < n_raw_code; ++i) {
*ct++ = (mp_uint_t)(uintptr_t)load_raw_code(reader);
}
// create raw_code and return it
mp_raw_code_t *rc = mp_emit_glue_new_raw_code();
mp_emit_glue_assign_bytecode(rc, bytecode, bc_len, const_table,
#if MICROPY_PERSISTENT_CODE_SAVE
n_obj, n_raw_code,
#endif
prelude.scope_flags);
return rc;
}
mp_raw_code_t *mp_raw_code_load(mp_reader_t *reader) {
byte header[4];
read_bytes(reader, header, sizeof(header));
if (header[0] != 'M'
|| header[1] != MPY_VERSION
|| header[2] != MPY_FEATURE_FLAGS
|| header[3] > mp_small_int_bits()) {
mp_raise_ValueError("incompatible .mpy file");
}
mp_raw_code_t *rc = load_raw_code(reader);
reader->close(reader->data);
return rc;
}
mp_raw_code_t *mp_raw_code_load_mem(const byte *buf, size_t len) {
mp_reader_t reader;
mp_reader_new_mem(&reader, buf, len, 0);
return mp_raw_code_load(&reader);
}
mp_raw_code_t *mp_raw_code_load_file(const char *filename) {
mp_reader_t reader;
mp_reader_new_file(&reader, filename);
return mp_raw_code_load(&reader);
}
#endif // MICROPY_PERSISTENT_CODE_LOAD
#if MICROPY_PERSISTENT_CODE_SAVE
#include "py/objstr.h"
STATIC void mp_print_bytes(mp_print_t *print, const byte *data, size_t len) {
print->print_strn(print->data, (const char*)data, len);
}
#define BYTES_FOR_INT ((BYTES_PER_WORD * 8 + 6) / 7)
STATIC void mp_print_uint(mp_print_t *print, size_t n) {
byte buf[BYTES_FOR_INT];
byte *p = buf + sizeof(buf);
*--p = n & 0x7f;
n >>= 7;
for (; n != 0; n >>= 7) {
*--p = 0x80 | (n & 0x7f);
}
print->print_strn(print->data, (char*)p, buf + sizeof(buf) - p);
}
STATIC void save_qstr(mp_print_t *print, qstr qst) {
size_t len;
const byte *str = qstr_data(qst, &len);
mp_print_uint(print, len);
mp_print_bytes(print, str, len);
}
STATIC void save_obj(mp_print_t *print, mp_obj_t o) {
if (MP_OBJ_IS_STR_OR_BYTES(o)) {
byte obj_type;
if (MP_OBJ_IS_STR(o)) {
obj_type = 's';
} else {
obj_type = 'b';
}
mp_uint_t len;
const char *str = mp_obj_str_get_data(o, &len);
mp_print_bytes(print, &obj_type, 1);
mp_print_uint(print, len);
mp_print_bytes(print, (const byte*)str, len);
} else if (MP_OBJ_TO_PTR(o) == &mp_const_ellipsis_obj) {
byte obj_type = 'e';
mp_print_bytes(print, &obj_type, 1);
} else {
// we save numbers using a simplistic text representation
// TODO could be improved
byte obj_type;
if (MP_OBJ_IS_TYPE(o, &mp_type_int)) {
obj_type = 'i';
#if MICROPY_PY_BUILTINS_COMPLEX
} else if (MP_OBJ_IS_TYPE(o, &mp_type_complex)) {
obj_type = 'c';
#endif
} else {
assert(mp_obj_is_float(o));
obj_type = 'f';
}
vstr_t vstr;
mp_print_t pr;
vstr_init_print(&vstr, 10, &pr);
mp_obj_print_helper(&pr, o, PRINT_REPR);
mp_print_bytes(print, &obj_type, 1);
mp_print_uint(print, vstr.len);
mp_print_bytes(print, (const byte*)vstr.buf, vstr.len);
vstr_clear(&vstr);
}
}
STATIC void save_bytecode_qstrs(mp_print_t *print, const byte *ip, const byte *ip_top) {
while (ip < ip_top) {
size_t sz;
uint f = mp_opcode_format(ip, &sz);
if (f == MP_OPCODE_QSTR) {
qstr qst = ip[1] | (ip[2] << 8);
save_qstr(print, qst);
}
ip += sz;
}
}
STATIC void save_raw_code(mp_print_t *print, mp_raw_code_t *rc) {
if (rc->kind != MP_CODE_BYTECODE) {
mp_raise_ValueError("can only save bytecode");
}
// save bytecode
mp_print_uint(print, rc->data.u_byte.bc_len);
mp_print_bytes(print, rc->data.u_byte.bytecode, rc->data.u_byte.bc_len);
// extract prelude
const byte *ip = rc->data.u_byte.bytecode;
const byte *ip2;
bytecode_prelude_t prelude;
extract_prelude(&ip, &ip2, &prelude);
// save qstrs
save_qstr(print, ip2[0] | (ip2[1] << 8)); // simple_name
save_qstr(print, ip2[2] | (ip2[3] << 8)); // source_file
save_bytecode_qstrs(print, ip, rc->data.u_byte.bytecode + rc->data.u_byte.bc_len);
// save constant table
mp_print_uint(print, rc->data.u_byte.n_obj);
mp_print_uint(print, rc->data.u_byte.n_raw_code);
const mp_uint_t *const_table = rc->data.u_byte.const_table;
for (uint i = 0; i < prelude.n_pos_args + prelude.n_kwonly_args; ++i) {
mp_obj_t o = (mp_obj_t)*const_table++;
save_qstr(print, MP_OBJ_QSTR_VALUE(o));
}
for (uint i = 0; i < rc->data.u_byte.n_obj; ++i) {
save_obj(print, (mp_obj_t)*const_table++);
}
for (uint i = 0; i < rc->data.u_byte.n_raw_code; ++i) {
save_raw_code(print, (mp_raw_code_t*)(uintptr_t)*const_table++);
}
}
void mp_raw_code_save(mp_raw_code_t *rc, mp_print_t *print) {
// header contains:
// byte 'M'
// byte version
// byte feature flags
// byte number of bits in a small int
byte header[4] = {'M', MPY_VERSION, MPY_FEATURE_FLAGS_DYNAMIC,
#if MICROPY_DYNAMIC_COMPILER
mp_dynamic_compiler.small_int_bits,
#else
mp_small_int_bits(),
#endif
};
mp_print_bytes(print, header, sizeof(header));
save_raw_code(print, rc);
}
// here we define mp_raw_code_save_file depending on the port
// TODO abstract this away properly
#if defined(__i386__) || defined(__x86_64__) || (defined(__arm__) && (defined(__unix__)))
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
STATIC void fd_print_strn(void *env, const char *str, size_t len) {
int fd = (intptr_t)env;
ssize_t ret = write(fd, str, len);
(void)ret;
}
void mp_raw_code_save_file(mp_raw_code_t *rc, const char *filename) {
int fd = open(filename, O_WRONLY | O_CREAT | O_TRUNC, 0644);
mp_print_t fd_print = {(void*)(intptr_t)fd, fd_print_strn};
mp_raw_code_save(rc, &fd_print);
close(fd);
}
#else
#error mp_raw_code_save_file not implemented for this platform
#endif
#endif // MICROPY_PERSISTENT_CODE_SAVE
| mit |
carnalis/Urho3D | Source/ThirdParty/Assimp/code/STLLoader.cpp | 17 | 19124 | /*
---------------------------------------------------------------------------
Open Asset Import Library (assimp)
---------------------------------------------------------------------------
Copyright (c) 2006-2017, assimp 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 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.
---------------------------------------------------------------------------
*/
/** @file Implementation of the STL importer class */
#ifndef ASSIMP_BUILD_NO_STL_IMPORTER
// internal headers
#include "STLLoader.h"
#include "ParsingUtils.h"
#include "fast_atof.h"
#include <memory>
#include <assimp/IOSystem.hpp>
#include <assimp/scene.h>
#include <assimp/DefaultLogger.hpp>
#include <assimp/importerdesc.h>
using namespace Assimp;
namespace {
static const aiImporterDesc desc = {
"Stereolithography (STL) Importer",
"",
"",
"",
aiImporterFlags_SupportTextFlavour | aiImporterFlags_SupportBinaryFlavour,
0,
0,
0,
0,
"stl"
};
// A valid binary STL buffer should consist of the following elements, in order:
// 1) 80 byte header
// 2) 4 byte face count
// 3) 50 bytes per face
static bool IsBinarySTL(const char* buffer, unsigned int fileSize) {
if( fileSize < 84 ) {
return false;
}
const char *facecount_pos = buffer + 80;
uint32_t faceCount( 0 );
::memcpy( &faceCount, facecount_pos, sizeof( uint32_t ) );
const uint32_t expectedBinaryFileSize = faceCount * 50 + 84;
return expectedBinaryFileSize == fileSize;
}
// An ascii STL buffer will begin with "solid NAME", where NAME is optional.
// Note: The "solid NAME" check is necessary, but not sufficient, to determine
// if the buffer is ASCII; a binary header could also begin with "solid NAME".
static bool IsAsciiSTL(const char* buffer, unsigned int fileSize) {
if (IsBinarySTL(buffer, fileSize))
return false;
const char* bufferEnd = buffer + fileSize;
if (!SkipSpaces(&buffer))
return false;
if (buffer + 5 >= bufferEnd)
return false;
bool isASCII( strncmp( buffer, "solid", 5 ) == 0 );
if( isASCII ) {
// A lot of importers are write solid even if the file is binary. So we have to check for ASCII-characters.
if( fileSize >= 500 ) {
isASCII = true;
for( unsigned int i = 0; i < 500; i++ ) {
if( buffer[ i ] > 127 ) {
isASCII = false;
break;
}
}
}
}
return isASCII;
}
} // namespace
// ------------------------------------------------------------------------------------------------
// Constructor to be privately used by Importer
STLImporter::STLImporter()
: mBuffer(),
fileSize(),
pScene()
{}
// ------------------------------------------------------------------------------------------------
// Destructor, private as well
STLImporter::~STLImporter()
{}
// ------------------------------------------------------------------------------------------------
// Returns whether the class can handle the format of the given file.
bool STLImporter::CanRead( const std::string& pFile, IOSystem* pIOHandler, bool checkSig) const
{
const std::string extension = GetExtension(pFile);
if( extension == "stl" ) {
return true;
} else if (!extension.length() || checkSig) {
if( !pIOHandler ) {
return true;
}
const char* tokens[] = {"STL","solid"};
return SearchFileHeaderForToken(pIOHandler,pFile,tokens,2);
}
return false;
}
// ------------------------------------------------------------------------------------------------
const aiImporterDesc* STLImporter::GetInfo () const {
return &desc;
}
void addFacesToMesh(aiMesh* pMesh)
{
pMesh->mFaces = new aiFace[pMesh->mNumFaces];
for (unsigned int i = 0, p = 0; i < pMesh->mNumFaces;++i) {
aiFace& face = pMesh->mFaces[i];
face.mIndices = new unsigned int[face.mNumIndices = 3];
for (unsigned int o = 0; o < 3;++o,++p) {
face.mIndices[o] = p;
}
}
}
// ------------------------------------------------------------------------------------------------
// Imports the given file into the given scene structure.
void STLImporter::InternReadFile( const std::string& pFile, aiScene* pScene, IOSystem* pIOHandler )
{
std::unique_ptr<IOStream> file( pIOHandler->Open( pFile, "rb"));
// Check whether we can read from the file
if( file.get() == NULL) {
throw DeadlyImportError( "Failed to open STL file " + pFile + ".");
}
fileSize = (unsigned int)file->FileSize();
// allocate storage and copy the contents of the file to a memory buffer
// (terminate it with zero)
std::vector<char> mBuffer2;
TextFileToBuffer(file.get(),mBuffer2);
this->pScene = pScene;
this->mBuffer = &mBuffer2[0];
// the default vertex color is light gray.
clrColorDefault.r = clrColorDefault.g = clrColorDefault.b = clrColorDefault.a = (ai_real) 0.6;
// allocate a single node
pScene->mRootNode = new aiNode();
bool bMatClr = false;
if (IsBinarySTL(mBuffer, fileSize)) {
bMatClr = LoadBinaryFile();
} else if (IsAsciiSTL(mBuffer, fileSize)) {
LoadASCIIFile( pScene->mRootNode );
} else {
throw DeadlyImportError( "Failed to determine STL storage representation for " + pFile + ".");
}
// create a single default material, using a white diffuse color for consistency with
// other geometric types (e.g., PLY).
aiMaterial* pcMat = new aiMaterial();
aiString s;
s.Set(AI_DEFAULT_MATERIAL_NAME);
pcMat->AddProperty(&s, AI_MATKEY_NAME);
aiColor4D clrDiffuse(ai_real(1.0),ai_real(1.0),ai_real(1.0),ai_real(1.0));
if (bMatClr) {
clrDiffuse = clrColorDefault;
}
pcMat->AddProperty(&clrDiffuse,1,AI_MATKEY_COLOR_DIFFUSE);
pcMat->AddProperty(&clrDiffuse,1,AI_MATKEY_COLOR_SPECULAR);
clrDiffuse = aiColor4D( ai_real(1.0), ai_real(1.0), ai_real(1.0), ai_real(1.0));
pcMat->AddProperty(&clrDiffuse,1,AI_MATKEY_COLOR_AMBIENT);
pScene->mNumMaterials = 1;
pScene->mMaterials = new aiMaterial*[1];
pScene->mMaterials[0] = pcMat;
}
// ------------------------------------------------------------------------------------------------
// Read an ASCII STL file
void STLImporter::LoadASCIIFile( aiNode *root ) {
std::vector<aiMesh*> meshes;
std::vector<aiNode*> nodes;
const char* sz = mBuffer;
const char* bufferEnd = mBuffer + fileSize;
std::vector<aiVector3D> positionBuffer;
std::vector<aiVector3D> normalBuffer;
// try to guess how many vertices we could have
// assume we'll need 160 bytes for each face
size_t sizeEstimate = std::max(1u, fileSize / 160u ) * 3;
positionBuffer.reserve(sizeEstimate);
normalBuffer.reserve(sizeEstimate);
while (IsAsciiSTL(sz, static_cast<unsigned int>(bufferEnd - sz))) {
std::vector<unsigned int> meshIndices;
aiMesh* pMesh = new aiMesh();
pMesh->mMaterialIndex = 0;
meshIndices.push_back((unsigned int) meshes.size() );
meshes.push_back(pMesh);
aiNode *node = new aiNode;
node->mParent = root;
nodes.push_back( node );
SkipSpaces(&sz);
ai_assert(!IsLineEnd(sz));
sz += 5; // skip the "solid"
SkipSpaces(&sz);
const char* szMe = sz;
while (!::IsSpaceOrNewLine(*sz)) {
sz++;
}
size_t temp;
// setup the name of the node
if ((temp = (size_t)(sz-szMe))) {
if (temp >= MAXLEN) {
throw DeadlyImportError( "STL: Node name too long" );
}
std::string name( szMe, temp );
node->mName.Set( name.c_str() );
//pScene->mRootNode->mName.length = temp;
//memcpy(pScene->mRootNode->mName.data,szMe,temp);
//pScene->mRootNode->mName.data[temp] = '\0';
} else {
pScene->mRootNode->mName.Set("<STL_ASCII>");
}
unsigned int faceVertexCounter = 3;
for ( ;; ) {
// go to the next token
if(!SkipSpacesAndLineEnd(&sz))
{
// seems we're finished although there was no end marker
DefaultLogger::get()->warn("STL: unexpected EOF. \'endsolid\' keyword was expected");
break;
}
// facet normal -0.13 -0.13 -0.98
if (!strncmp(sz,"facet",5) && IsSpaceOrNewLine(*(sz+5)) && *(sz + 5) != '\0') {
if (faceVertexCounter != 3) {
DefaultLogger::get()->warn("STL: A new facet begins but the old is not yet complete");
}
faceVertexCounter = 0;
normalBuffer.push_back(aiVector3D());
aiVector3D* vn = &normalBuffer.back();
sz += 6;
SkipSpaces(&sz);
if (strncmp(sz,"normal",6)) {
DefaultLogger::get()->warn("STL: a facet normal vector was expected but not found");
} else {
if (sz[6] == '\0') {
throw DeadlyImportError("STL: unexpected EOF while parsing facet");
}
sz += 7;
SkipSpaces(&sz);
sz = fast_atoreal_move<ai_real>(sz, (ai_real&)vn->x );
SkipSpaces(&sz);
sz = fast_atoreal_move<ai_real>(sz, (ai_real&)vn->y );
SkipSpaces(&sz);
sz = fast_atoreal_move<ai_real>(sz, (ai_real&)vn->z );
normalBuffer.push_back(*vn);
normalBuffer.push_back(*vn);
}
} else if (!strncmp(sz,"vertex",6) && ::IsSpaceOrNewLine(*(sz+6))) { // vertex 1.50000 1.50000 0.00000
if (faceVertexCounter >= 3) {
DefaultLogger::get()->error("STL: a facet with more than 3 vertices has been found");
++sz;
} else {
if (sz[6] == '\0') {
throw DeadlyImportError("STL: unexpected EOF while parsing facet");
}
sz += 7;
SkipSpaces(&sz);
positionBuffer.push_back(aiVector3D());
aiVector3D* vn = &positionBuffer.back();
sz = fast_atoreal_move<ai_real>(sz, (ai_real&)vn->x );
SkipSpaces(&sz);
sz = fast_atoreal_move<ai_real>(sz, (ai_real&)vn->y );
SkipSpaces(&sz);
sz = fast_atoreal_move<ai_real>(sz, (ai_real&)vn->z );
faceVertexCounter++;
}
} else if (!::strncmp(sz,"endsolid",8)) {
do {
++sz;
} while (!::IsLineEnd(*sz));
SkipSpacesAndLineEnd(&sz);
// finished!
break;
} else { // else skip the whole identifier
do {
++sz;
} while (!::IsSpaceOrNewLine(*sz));
}
}
if (positionBuffer.empty()) {
pMesh->mNumFaces = 0;
throw DeadlyImportError("STL: ASCII file is empty or invalid; no data loaded");
}
if (positionBuffer.size() % 3 != 0) {
pMesh->mNumFaces = 0;
throw DeadlyImportError("STL: Invalid number of vertices");
}
if (normalBuffer.size() != positionBuffer.size()) {
pMesh->mNumFaces = 0;
throw DeadlyImportError("Normal buffer size does not match position buffer size");
}
pMesh->mNumFaces = static_cast<unsigned int>(positionBuffer.size() / 3);
pMesh->mNumVertices = static_cast<unsigned int>(positionBuffer.size());
pMesh->mVertices = new aiVector3D[pMesh->mNumVertices];
memcpy(pMesh->mVertices, &positionBuffer[0].x, pMesh->mNumVertices * sizeof(aiVector3D));
positionBuffer.clear();
pMesh->mNormals = new aiVector3D[pMesh->mNumVertices];
memcpy(pMesh->mNormals, &normalBuffer[0].x, pMesh->mNumVertices * sizeof(aiVector3D));
normalBuffer.clear();
// now copy faces
addFacesToMesh(pMesh);
// assign the meshes to the current node
pushMeshesToNode( meshIndices, node );
}
// now add the loaded meshes
pScene->mNumMeshes = (unsigned int)meshes.size();
pScene->mMeshes = new aiMesh*[pScene->mNumMeshes];
for (size_t i = 0; i < meshes.size(); i++) {
pScene->mMeshes[ i ] = meshes[i];
}
root->mNumChildren = (unsigned int) nodes.size();
root->mChildren = new aiNode*[ root->mNumChildren ];
for ( size_t i=0; i<nodes.size(); ++i ) {
root->mChildren[ i ] = nodes[ i ];
}
}
// ------------------------------------------------------------------------------------------------
// Read a binary STL file
bool STLImporter::LoadBinaryFile()
{
// allocate one mesh
pScene->mNumMeshes = 1;
pScene->mMeshes = new aiMesh*[1];
aiMesh* pMesh = pScene->mMeshes[0] = new aiMesh();
pMesh->mMaterialIndex = 0;
// skip the first 80 bytes
if (fileSize < 84) {
throw DeadlyImportError("STL: file is too small for the header");
}
bool bIsMaterialise = false;
// search for an occurrence of "COLOR=" in the header
const unsigned char* sz2 = (const unsigned char*)mBuffer;
const unsigned char* const szEnd = sz2+80;
while (sz2 < szEnd) {
if ('C' == *sz2++ && 'O' == *sz2++ && 'L' == *sz2++ &&
'O' == *sz2++ && 'R' == *sz2++ && '=' == *sz2++) {
// read the default vertex color for facets
bIsMaterialise = true;
DefaultLogger::get()->info("STL: Taking code path for Materialise files");
const ai_real invByte = (ai_real)1.0 / ( ai_real )255.0;
clrColorDefault.r = (*sz2++) * invByte;
clrColorDefault.g = (*sz2++) * invByte;
clrColorDefault.b = (*sz2++) * invByte;
clrColorDefault.a = (*sz2++) * invByte;
break;
}
}
const unsigned char* sz = (const unsigned char*)mBuffer + 80;
// now read the number of facets
pScene->mRootNode->mName.Set("<STL_BINARY>");
pMesh->mNumFaces = *((uint32_t*)sz);
sz += 4;
if (fileSize < 84 + pMesh->mNumFaces*50) {
throw DeadlyImportError("STL: file is too small to hold all facets");
}
if (!pMesh->mNumFaces) {
throw DeadlyImportError("STL: file is empty. There are no facets defined");
}
pMesh->mNumVertices = pMesh->mNumFaces*3;
aiVector3D* vp,*vn;
vp = pMesh->mVertices = new aiVector3D[pMesh->mNumVertices];
vn = pMesh->mNormals = new aiVector3D[pMesh->mNumVertices];
for (unsigned int i = 0; i < pMesh->mNumFaces;++i) {
// NOTE: Blender sometimes writes empty normals ... this is not
// our fault ... the RemoveInvalidData helper step should fix that
*vn = *((aiVector3D*)sz);
sz += sizeof(aiVector3D);
*(vn+1) = *vn;
*(vn+2) = *vn;
vn += 3;
*vp++ = *((aiVector3D*)sz);
sz += sizeof(aiVector3D);
*vp++ = *((aiVector3D*)sz);
sz += sizeof(aiVector3D);
*vp++ = *((aiVector3D*)sz);
sz += sizeof(aiVector3D);
uint16_t color = *((uint16_t*)sz);
sz += 2;
if (color & (1 << 15))
{
// seems we need to take the color
if (!pMesh->mColors[0])
{
pMesh->mColors[0] = new aiColor4D[pMesh->mNumVertices];
for (unsigned int i = 0; i <pMesh->mNumVertices;++i)
*pMesh->mColors[0]++ = this->clrColorDefault;
pMesh->mColors[0] -= pMesh->mNumVertices;
DefaultLogger::get()->info("STL: Mesh has vertex colors");
}
aiColor4D* clr = &pMesh->mColors[0][i*3];
clr->a = 1.0;
const ai_real invVal( (ai_real)1.0 / ( ai_real )31.0 );
if (bIsMaterialise) // this is reversed
{
clr->r = (color & 0x31u) *invVal;
clr->g = ((color & (0x31u<<5))>>5u) *invVal;
clr->b = ((color & (0x31u<<10))>>10u) *invVal;
}
else
{
clr->b = (color & 0x31u) *invVal;
clr->g = ((color & (0x31u<<5))>>5u) *invVal;
clr->r = ((color & (0x31u<<10))>>10u) *invVal;
}
// assign the color to all vertices of the face
*(clr+1) = *clr;
*(clr+2) = *clr;
}
}
// now copy faces
addFacesToMesh(pMesh);
// add all created meshes to the single node
pScene->mRootNode->mNumMeshes = pScene->mNumMeshes;
pScene->mRootNode->mMeshes = new unsigned int[pScene->mNumMeshes];
for (unsigned int i = 0; i < pScene->mNumMeshes; i++)
pScene->mRootNode->mMeshes[i] = i;
if (bIsMaterialise && !pMesh->mColors[0])
{
// use the color as diffuse material color
return true;
}
return false;
}
void STLImporter::pushMeshesToNode( std::vector<unsigned int> &meshIndices, aiNode *node ) {
ai_assert( nullptr != node );
if ( meshIndices.empty() ) {
return;
}
node->mNumMeshes = static_cast<unsigned int>( meshIndices.size() );
node->mMeshes = new unsigned int[ meshIndices.size() ];
for ( size_t i=0; i<meshIndices.size(); ++i ) {
node->mMeshes[ i ] = meshIndices[ i ];
}
meshIndices.clear();
}
#endif // !! ASSIMP_BUILD_NO_STL_IMPORTER
| mit |
bellahyejin/carplate_CV | Tesseract-OCR/tesseract-ocr/ccutil/elst.cpp | 17 | 16665 | /**********************************************************************
* File: elst.c (Formerly elist.c)
* Description: Embedded list handling code which is not in the include file.
* Author: Phil Cheatle
* Created: Fri Jan 04 13:55:49 GMT 1991
*
* (C) Copyright 1991, Hewlett-Packard Ltd.
** Licensed under the Apache License, Version 2.0 (the "License");
** you may not use this file except in compliance with the License.
** You may obtain a copy of the License at
** http://www.apache.org/licenses/LICENSE-2.0
** Unless required by applicable law or agreed to in writing, software
** distributed under the License is distributed on an "AS IS" BASIS,
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
** See the License for the specific language governing permissions and
** limitations under the License.
*
**********************************************************************/
#include "mfcpch.h" //precompiled headers
#include <stdlib.h>
#include "elst.h"
/***********************************************************************
* MEMBER FUNCTIONS OF CLASS: ELIST
* ================================
**********************************************************************/
/***********************************************************************
* ELIST::internal_clear
*
* Used by the destructor and the "clear" member function of derived list
* classes to destroy all the elements on the list.
* The calling function passes a "zapper" function which can be called to
* delete each element of the list, regardless of its derived type. This
* technique permits a generic clear function to destroy elements of
* different derived types correctly, without requiring virtual functions and
* the consequential memory overhead.
**********************************************************************/
void
ELIST::internal_clear ( //destroy all links
void (*zapper) (ELIST_LINK *)) {
//ptr to zapper functn
ELIST_LINK *ptr;
ELIST_LINK *next;
#ifndef NDEBUG
if (!this)
NULL_OBJECT.error ("ELIST::internal_clear", ABORT, NULL);
#endif
if (!empty ()) {
ptr = last->next; //set to first
last->next = NULL; //break circle
last = NULL; //set list empty
while (ptr) {
next = ptr->next;
zapper(ptr);
ptr = next;
}
}
}
/***********************************************************************
* ELIST::assign_to_sublist
*
* The list is set to a sublist of another list. "This" list must be empty
* before this function is invoked. The two iterators passed must refer to
* the same list, different from "this" one. The sublist removed is the
* inclusive list from start_it's current position to end_it's current
* position. If this range passes over the end of the source list then the
* source list has its end set to the previous element of start_it. The
* extracted sublist is unaffected by the end point of the source list, its
* end point is always the end_it position.
**********************************************************************/
void ELIST::assign_to_sublist( //to this list
ELIST_ITERATOR *start_it, //from list start
ELIST_ITERATOR *end_it) { //from list end
const ERRCODE LIST_NOT_EMPTY =
"Destination list must be empty before extracting a sublist";
#ifndef NDEBUG
if (!this)
NULL_OBJECT.error ("ELIST::assign_to_sublist", ABORT, NULL);
#endif
if (!empty ())
LIST_NOT_EMPTY.error ("ELIST.assign_to_sublist", ABORT, NULL);
last = start_it->extract_sublist (end_it);
}
/***********************************************************************
* ELIST::length
*
* Return count of elements on list
**********************************************************************/
inT32 ELIST::length() const { // count elements
ELIST_ITERATOR it(const_cast<ELIST*>(this));
inT32 count = 0;
#ifndef NDEBUG
if (!this)
NULL_OBJECT.error ("ELIST::length", ABORT, NULL);
#endif
for (it.mark_cycle_pt (); !it.cycled_list (); it.forward ())
count++;
return count;
}
/***********************************************************************
* ELIST::sort
*
* Sort elements on list
* NB If you dont like the const declarations in the comparator, coerce yours:
* ( int (*)(const void *, const void *)
**********************************************************************/
void
ELIST::sort ( //sort elements
int comparator ( //comparison routine
const void *, const void *)) {
ELIST_ITERATOR it(this);
inT32 count;
ELIST_LINK **base; //ptr array to sort
ELIST_LINK **current;
inT32 i;
#ifndef NDEBUG
if (!this)
NULL_OBJECT.error ("ELIST::sort", ABORT, NULL);
#endif
/* Allocate an array of pointers, one per list element */
count = length ();
base = (ELIST_LINK **) malloc (count * sizeof (ELIST_LINK *));
/* Extract all elements, putting the pointers in the array */
current = base;
for (it.mark_cycle_pt (); !it.cycled_list (); it.forward ()) {
*current = it.extract ();
current++;
}
/* Sort the pointer array */
qsort ((char *) base, count, sizeof (*base), comparator);
/* Rebuild the list from the sorted pointers */
current = base;
for (i = 0; i < count; i++) {
it.add_to_end (*current);
current++;
}
free(base);
}
// Assuming list has been sorted already, insert new_link to
// keep the list sorted according to the same comparison function.
// Comparision function is the same as used by sort, i.e. uses double
// indirection. Time is O(1) to add to beginning or end.
// Time is linear to add pre-sorted items to an empty list.
// If unique is set to true and comparator() returns 0 (an entry with the
// same information as the one contained in new_link is already in the
// list) - new_link is not added to the list and the function returns the
// pointer to the identical entry that already exists in the list
// (otherwise the function returns new_link).
ELIST_LINK *ELIST::add_sorted_and_find(
int comparator(const void*, const void*),
bool unique, ELIST_LINK* new_link) {
// Check for adding at the end.
if (last == NULL || comparator(&last, &new_link) < 0) {
if (last == NULL) {
new_link->next = new_link;
} else {
new_link->next = last->next;
last->next = new_link;
}
last = new_link;
} else {
// Need to use an iterator.
ELIST_ITERATOR it(this);
for (it.mark_cycle_pt(); !it.cycled_list(); it.forward()) {
ELIST_LINK* link = it.data();
int compare = comparator(&link, &new_link);
if (compare > 0) {
break;
} else if (unique && compare == 0) {
return link;
}
}
if (it.cycled_list())
it.add_to_end(new_link);
else
it.add_before_then_move(new_link);
}
return new_link;
}
/***********************************************************************
* MEMBER FUNCTIONS OF CLASS: ELIST_ITERATOR
* =========================================
**********************************************************************/
/***********************************************************************
* ELIST_ITERATOR::forward
*
* Move the iterator to the next element of the list.
* REMEMBER: ALL LISTS ARE CIRCULAR.
**********************************************************************/
ELIST_LINK *ELIST_ITERATOR::forward() {
#ifndef NDEBUG
if (!this)
NULL_OBJECT.error ("ELIST_ITERATOR::forward", ABORT, NULL);
if (!list)
NO_LIST.error ("ELIST_ITERATOR::forward", ABORT, NULL);
#endif
if (list->empty ())
return NULL;
if (current) { //not removed so
//set previous
prev = current;
started_cycling = TRUE;
// In case next is deleted by another iterator, get next from current.
current = current->next;
} else {
if (ex_current_was_cycle_pt)
cycle_pt = next;
current = next;
}
next = current->next;
#ifndef NDEBUG
if (!current)
NULL_DATA.error ("ELIST_ITERATOR::forward", ABORT, NULL);
if (!next)
NULL_NEXT.error ("ELIST_ITERATOR::forward", ABORT,
"This is: %p Current is: %p", this, current);
#endif
return current;
}
/***********************************************************************
* ELIST_ITERATOR::data_relative
*
* Return the data pointer to the element "offset" elements from current.
* "offset" must not be less than -1.
* (This function can't be INLINEd because it contains a loop)
**********************************************************************/
ELIST_LINK *ELIST_ITERATOR::data_relative( //get data + or - ...
inT8 offset) { //offset from current
ELIST_LINK *ptr;
#ifndef NDEBUG
if (!this)
NULL_OBJECT.error ("ELIST_ITERATOR::data_relative", ABORT, NULL);
if (!list)
NO_LIST.error ("ELIST_ITERATOR::data_relative", ABORT, NULL);
if (list->empty ())
EMPTY_LIST.error ("ELIST_ITERATOR::data_relative", ABORT, NULL);
if (offset < -1)
BAD_PARAMETER.error ("ELIST_ITERATOR::data_relative", ABORT,
"offset < -l");
#endif
if (offset == -1)
ptr = prev;
else
for (ptr = current ? current : prev; offset-- > 0; ptr = ptr->next);
#ifndef NDEBUG
if (!ptr)
NULL_DATA.error ("ELIST_ITERATOR::data_relative", ABORT, NULL);
#endif
return ptr;
}
/***********************************************************************
* ELIST_ITERATOR::move_to_last()
*
* Move current so that it is set to the end of the list.
* Return data just in case anyone wants it.
* (This function can't be INLINEd because it contains a loop)
**********************************************************************/
ELIST_LINK *ELIST_ITERATOR::move_to_last() {
#ifndef NDEBUG
if (!this)
NULL_OBJECT.error ("ELIST_ITERATOR::move_to_last", ABORT, NULL);
if (!list)
NO_LIST.error ("ELIST_ITERATOR::move_to_last", ABORT, NULL);
#endif
while (current != list->last)
forward();
return current;
}
/***********************************************************************
* ELIST_ITERATOR::exchange()
*
* Given another iterator, whose current element is a different element on
* the same list list OR an element of another list, exchange the two current
* elements. On return, each iterator points to the element which was the
* other iterators current on entry.
* (This function hasn't been in-lined because its a bit big!)
**********************************************************************/
void ELIST_ITERATOR::exchange( //positions of 2 links
ELIST_ITERATOR *other_it) { //other iterator
const ERRCODE DONT_EXCHANGE_DELETED =
"Can't exchange deleted elements of lists";
ELIST_LINK *old_current;
#ifndef NDEBUG
if (!this)
NULL_OBJECT.error ("ELIST_ITERATOR::exchange", ABORT, NULL);
if (!list)
NO_LIST.error ("ELIST_ITERATOR::exchange", ABORT, NULL);
if (!other_it)
BAD_PARAMETER.error ("ELIST_ITERATOR::exchange", ABORT, "other_it NULL");
if (!(other_it->list))
NO_LIST.error ("ELIST_ITERATOR::exchange", ABORT, "other_it");
#endif
/* Do nothing if either list is empty or if both iterators reference the same
link */
if ((list->empty ()) ||
(other_it->list->empty ()) || (current == other_it->current))
return;
/* Error if either current element is deleted */
if (!current || !other_it->current)
DONT_EXCHANGE_DELETED.error ("ELIST_ITERATOR.exchange", ABORT, NULL);
/* Now handle the 4 cases: doubleton list; non-doubleton adjacent elements
(other before this); non-doubleton adjacent elements (this before other);
non-adjacent elements. */
//adjacent links
if ((next == other_it->current) ||
(other_it->next == current)) {
//doubleton list
if ((next == other_it->current) &&
(other_it->next == current)) {
prev = next = current;
other_it->prev = other_it->next = other_it->current;
}
else { //non-doubleton with
//adjacent links
//other before this
if (other_it->next == current) {
other_it->prev->next = current;
other_it->current->next = next;
current->next = other_it->current;
other_it->next = other_it->current;
prev = current;
}
else { //this before other
prev->next = other_it->current;
current->next = other_it->next;
other_it->current->next = current;
next = current;
other_it->prev = other_it->current;
}
}
}
else { //no overlap
prev->next = other_it->current;
current->next = other_it->next;
other_it->prev->next = current;
other_it->current->next = next;
}
/* update end of list pointer when necessary (remember that the 2 iterators
may iterate over different lists!) */
if (list->last == current)
list->last = other_it->current;
if (other_it->list->last == other_it->current)
other_it->list->last = current;
if (current == cycle_pt)
cycle_pt = other_it->cycle_pt;
if (other_it->current == other_it->cycle_pt)
other_it->cycle_pt = cycle_pt;
/* The actual exchange - in all cases*/
old_current = current;
current = other_it->current;
other_it->current = old_current;
}
/***********************************************************************
* ELIST_ITERATOR::extract_sublist()
*
* This is a private member, used only by ELIST::assign_to_sublist.
* Given another iterator for the same list, extract the links from THIS to
* OTHER inclusive, link them into a new circular list, and return a
* pointer to the last element.
* (Can't inline this function because it contains a loop)
**********************************************************************/
ELIST_LINK *ELIST_ITERATOR::extract_sublist( //from this current
ELIST_ITERATOR *other_it) { //to other current
#ifndef NDEBUG
const ERRCODE BAD_EXTRACTION_PTS =
"Can't extract sublist from points on different lists";
const ERRCODE DONT_EXTRACT_DELETED =
"Can't extract a sublist marked by deleted points";
#endif
const ERRCODE BAD_SUBLIST = "Can't find sublist end point in original list";
ELIST_ITERATOR temp_it = *this;
ELIST_LINK *end_of_new_list;
#ifndef NDEBUG
if (!this)
NULL_OBJECT.error ("ELIST_ITERATOR::extract_sublist", ABORT, NULL);
if (!other_it)
BAD_PARAMETER.error ("ELIST_ITERATOR::extract_sublist", ABORT,
"other_it NULL");
if (!list)
NO_LIST.error ("ELIST_ITERATOR::extract_sublist", ABORT, NULL);
if (list != other_it->list)
BAD_EXTRACTION_PTS.error ("ELIST_ITERATOR.extract_sublist", ABORT, NULL);
if (list->empty ())
EMPTY_LIST.error ("ELIST_ITERATOR::extract_sublist", ABORT, NULL);
if (!current || !other_it->current)
DONT_EXTRACT_DELETED.error ("ELIST_ITERATOR.extract_sublist", ABORT,
NULL);
#endif
ex_current_was_last = other_it->ex_current_was_last = FALSE;
ex_current_was_cycle_pt = FALSE;
other_it->ex_current_was_cycle_pt = FALSE;
temp_it.mark_cycle_pt ();
do { //walk sublist
if (temp_it.cycled_list ()) //cant find end pt
BAD_SUBLIST.error ("ELIST_ITERATOR.extract_sublist", ABORT, NULL);
if (temp_it.at_last ()) {
list->last = prev;
ex_current_was_last = other_it->ex_current_was_last = TRUE;
}
if (temp_it.current == cycle_pt)
ex_current_was_cycle_pt = TRUE;
if (temp_it.current == other_it->cycle_pt)
other_it->ex_current_was_cycle_pt = TRUE;
temp_it.forward ();
}
while (temp_it.prev != other_it->current);
//circularise sublist
other_it->current->next = current;
end_of_new_list = other_it->current;
//sublist = whole list
if (prev == other_it->current) {
list->last = NULL;
prev = current = next = NULL;
other_it->prev = other_it->current = other_it->next = NULL;
}
else {
prev->next = other_it->next;
current = other_it->current = NULL;
next = other_it->next;
other_it->prev = prev;
}
return end_of_new_list;
}
| mit |
AmazingJaze/Windows-universal-samples | Samples/Accelerometer/cpp/Scenario3_Polling.xaml.cpp | 17 | 4375 | //*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
//
// Scenario3_Polling.xaml.cpp
// Implementation of the Scenario3_Polling class
//
#include "pch.h"
#include "Scenario3_Polling.xaml.h"
using namespace SDKTemplate;
using namespace Platform;
using namespace Windows::Devices::Sensors;
using namespace Windows::Foundation;
using namespace Windows::UI::Core;
using namespace Windows::UI::Xaml;
using namespace Windows::UI::Xaml::Controls;
using namespace Windows::UI::Xaml::Navigation;
Scenario3_Polling::Scenario3_Polling()
{
InitializeComponent();
}
void Scenario3_Polling::OnNavigatedTo(NavigationEventArgs^ e)
{
accelerometer = Accelerometer::GetDefault(rootPage->AccelerometerReadingType);
if (accelerometer != nullptr)
{
// Select a report interval that is both suitable for the purposes of the app and supported by the sensor.
// This value will be used later to activate the sensor.
desiredReportInterval = (std::max)(accelerometer->MinimumReportInterval, 16U);
// Set up a DispatchTimer
TimeSpan span;
span.Duration = static_cast<int32>(desiredReportInterval) * 10000; // convert to 100ns ticks
dispatcherTimer = ref new DispatcherTimer();
dispatcherTimer->Interval = span;
dispatcherTimer->Tick += ref new Windows::Foundation::EventHandler<Object^>(this, &Scenario3_Polling::DisplayCurrentReading);
rootPage->NotifyUser(rootPage->AccelerometerReadingType.ToString() + " accelerometer ready", NotifyType::StatusMessage);
ScenarioEnableButton->IsEnabled = true;
}
else
{
rootPage->NotifyUser(rootPage->AccelerometerReadingType.ToString() + " accelerometer not found", NotifyType::ErrorMessage);
}
}
void Scenario3_Polling::OnNavigatedFrom(NavigationEventArgs^ e)
{
if (ScenarioDisableButton->IsEnabled)
{
ScenarioDisable();
}
}
/// <summary>
/// This is the event handler for VisibilityChanged events. You would register for these notifications
/// if handling sensor data when the app is not visible could cause unintended actions in the app.
/// </summary>
/// <param name="sender"></param>
/// <param name="e">
/// Event data that can be examined for the current visibility state.
/// </param>
void Scenario3_Polling::VisibilityChanged(Object^ sender, VisibilityChangedEventArgs^ e)
{
// The app should watch for VisibilityChanged events to disable and re-enable sensor input as appropriate
if (ScenarioDisableButton->IsEnabled)
{
if (e->Visible)
{
// Re-enable sensor input (no need to restore the desired reportInterval... it is restored for us upon app resume)
dispatcherTimer->Start();
}
else
{
// Disable sensor input (no need to restore the default reportInterval... resources will be released upon app suspension)
dispatcherTimer->Stop();
}
}
}
void Scenario3_Polling::DisplayCurrentReading(Object^ sender, Object^ e)
{
AccelerometerReading^ reading = accelerometer->GetCurrentReading();
if (reading != nullptr)
{
MainPage::SetReadingText(ScenarioOutput, reading);
}
}
void Scenario3_Polling::ScenarioEnable()
{
visibilityToken = Window::Current->VisibilityChanged += ref new WindowVisibilityChangedEventHandler(this, &Scenario3_Polling::VisibilityChanged);
// Set the report interval to enable the sensor for polling
accelerometer->ReportInterval = desiredReportInterval;
dispatcherTimer->Start();
ScenarioEnableButton->IsEnabled = false;
ScenarioDisableButton->IsEnabled = true;
}
void Scenario3_Polling::ScenarioDisable()
{
Window::Current->VisibilityChanged -= visibilityToken;
dispatcherTimer->Stop();
// Restore the default report interval to release resources while the sensor is not in use
accelerometer->ReportInterval = 0;
ScenarioEnableButton->IsEnabled = true;
ScenarioDisableButton->IsEnabled = false;
}
| mit |
blazewicz/micropython | ports/pic16bit/main.c | 19 | 3576 | /*
* This file is part of the MicroPython project, http://micropython.org/
*
* The MIT License (MIT)
*
* Copyright (c) 2015 Damien P. George
*
* 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 <stdint.h>
#include <stdio.h>
#include <string.h>
#include <p33Fxxxx.h>
#include "py/compile.h"
#include "py/runtime.h"
#include "py/gc.h"
#include "py/mphal.h"
#include "py/mperrno.h"
#include "lib/utils/pyexec.h"
#include "lib/mp-readline/readline.h"
#include "board.h"
#include "modpyb.h"
_FGS(GWRP_OFF & GCP_OFF);
_FOSCSEL(FNOSC_FRC);
_FOSC(FCKSM_CSECMD & OSCIOFNC_ON & POSCMD_NONE);
_FWDT(FWDTEN_OFF);
// maximum heap for device with 8k RAM
static char heap[4600];
int main(int argc, char **argv) {
// init the CPU and the peripherals
cpu_init();
led_init();
switch_init();
uart_init();
soft_reset:
// flash green led for 150ms to indicate boot
led_state(1, 0);
led_state(2, 0);
led_state(3, 1);
mp_hal_delay_ms(150);
led_state(3, 0);
// init MicroPython runtime
int stack_dummy;
MP_STATE_THREAD(stack_top) = (char*)&stack_dummy;
gc_init(heap, heap + sizeof(heap));
mp_init();
mp_hal_init();
readline_init0();
// REPL loop
for (;;) {
if (pyexec_mode_kind == PYEXEC_MODE_RAW_REPL) {
if (pyexec_raw_repl() != 0) {
break;
}
} else {
if (pyexec_friendly_repl() != 0) {
break;
}
}
}
printf("PYB: soft reboot\n");
mp_deinit();
goto soft_reset;
}
void gc_collect(void) {
// TODO possibly need to trace registers
void *dummy;
gc_collect_start();
// Node: stack is ascending
gc_collect_root(&dummy, ((mp_uint_t)&dummy - (mp_uint_t)MP_STATE_THREAD(stack_top)) / sizeof(mp_uint_t));
gc_collect_end();
}
mp_lexer_t *mp_lexer_new_from_file(const char *filename) {
mp_raise_OSError(MP_ENOENT);
}
mp_import_stat_t mp_import_stat(const char *path) {
return MP_IMPORT_STAT_NO_EXIST;
}
mp_obj_t mp_builtin_open(size_t n_args, const mp_obj_t *args, mp_map_t *kwargs) {
return mp_const_none;
}
MP_DEFINE_CONST_FUN_OBJ_KW(mp_builtin_open_obj, 1, mp_builtin_open);
void nlr_jump_fail(void *val) {
while (1);
}
void NORETURN __fatal_error(const char *msg) {
while (1);
}
#ifndef NDEBUG
void MP_WEAK __assert_func(const char *file, int line, const char *func, const char *expr) {
printf("Assertion '%s' failed, at file %s:%d\n", expr, file, line);
__fatal_error("Assertion failed");
}
#endif
| mit |
JeremyRubin/bitcoin | src/blockencodings.cpp | 21 | 10332 | // Copyright (c) 2016-2020 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include <blockencodings.h>
#include <consensus/consensus.h>
#include <consensus/validation.h>
#include <chainparams.h>
#include <crypto/sha256.h>
#include <crypto/siphash.h>
#include <random.h>
#include <streams.h>
#include <txmempool.h>
#include <validation.h>
#include <util/system.h>
#include <unordered_map>
CBlockHeaderAndShortTxIDs::CBlockHeaderAndShortTxIDs(const CBlock& block, bool fUseWTXID) :
nonce(GetRand(std::numeric_limits<uint64_t>::max())),
shorttxids(block.vtx.size() - 1), prefilledtxn(1), header(block) {
FillShortTxIDSelector();
//TODO: Use our mempool prior to block acceptance to predictively fill more than just the coinbase
prefilledtxn[0] = {0, block.vtx[0]};
for (size_t i = 1; i < block.vtx.size(); i++) {
const CTransaction& tx = *block.vtx[i];
shorttxids[i - 1] = GetShortID(fUseWTXID ? tx.GetWitnessHash() : tx.GetHash());
}
}
void CBlockHeaderAndShortTxIDs::FillShortTxIDSelector() const {
CDataStream stream(SER_NETWORK, PROTOCOL_VERSION);
stream << header << nonce;
CSHA256 hasher;
hasher.Write((unsigned char*)&(*stream.begin()), stream.end() - stream.begin());
uint256 shorttxidhash;
hasher.Finalize(shorttxidhash.begin());
shorttxidk0 = shorttxidhash.GetUint64(0);
shorttxidk1 = shorttxidhash.GetUint64(1);
}
uint64_t CBlockHeaderAndShortTxIDs::GetShortID(const uint256& txhash) const {
static_assert(SHORTTXIDS_LENGTH == 6, "shorttxids calculation assumes 6-byte shorttxids");
return SipHashUint256(shorttxidk0, shorttxidk1, txhash) & 0xffffffffffffL;
}
ReadStatus PartiallyDownloadedBlock::InitData(const CBlockHeaderAndShortTxIDs& cmpctblock, const std::vector<std::pair<uint256, CTransactionRef>>& extra_txn) {
if (cmpctblock.header.IsNull() || (cmpctblock.shorttxids.empty() && cmpctblock.prefilledtxn.empty()))
return READ_STATUS_INVALID;
if (cmpctblock.shorttxids.size() + cmpctblock.prefilledtxn.size() > MAX_BLOCK_WEIGHT / MIN_SERIALIZABLE_TRANSACTION_WEIGHT)
return READ_STATUS_INVALID;
assert(header.IsNull() && txn_available.empty());
header = cmpctblock.header;
txn_available.resize(cmpctblock.BlockTxCount());
int32_t lastprefilledindex = -1;
for (size_t i = 0; i < cmpctblock.prefilledtxn.size(); i++) {
if (cmpctblock.prefilledtxn[i].tx->IsNull())
return READ_STATUS_INVALID;
lastprefilledindex += cmpctblock.prefilledtxn[i].index + 1; //index is a uint16_t, so can't overflow here
if (lastprefilledindex > std::numeric_limits<uint16_t>::max())
return READ_STATUS_INVALID;
if ((uint32_t)lastprefilledindex > cmpctblock.shorttxids.size() + i) {
// If we are inserting a tx at an index greater than our full list of shorttxids
// plus the number of prefilled txn we've inserted, then we have txn for which we
// have neither a prefilled txn or a shorttxid!
return READ_STATUS_INVALID;
}
txn_available[lastprefilledindex] = cmpctblock.prefilledtxn[i].tx;
}
prefilled_count = cmpctblock.prefilledtxn.size();
// Calculate map of txids -> positions and check mempool to see what we have (or don't)
// Because well-formed cmpctblock messages will have a (relatively) uniform distribution
// of short IDs, any highly-uneven distribution of elements can be safely treated as a
// READ_STATUS_FAILED.
std::unordered_map<uint64_t, uint16_t> shorttxids(cmpctblock.shorttxids.size());
uint16_t index_offset = 0;
for (size_t i = 0; i < cmpctblock.shorttxids.size(); i++) {
while (txn_available[i + index_offset])
index_offset++;
shorttxids[cmpctblock.shorttxids[i]] = i + index_offset;
// To determine the chance that the number of entries in a bucket exceeds N,
// we use the fact that the number of elements in a single bucket is
// binomially distributed (with n = the number of shorttxids S, and p =
// 1 / the number of buckets), that in the worst case the number of buckets is
// equal to S (due to std::unordered_map having a default load factor of 1.0),
// and that the chance for any bucket to exceed N elements is at most
// buckets * (the chance that any given bucket is above N elements).
// Thus: P(max_elements_per_bucket > N) <= S * (1 - cdf(binomial(n=S,p=1/S), N)).
// If we assume blocks of up to 16000, allowing 12 elements per bucket should
// only fail once per ~1 million block transfers (per peer and connection).
if (shorttxids.bucket_size(shorttxids.bucket(cmpctblock.shorttxids[i])) > 12)
return READ_STATUS_FAILED;
}
// TODO: in the shortid-collision case, we should instead request both transactions
// which collided. Falling back to full-block-request here is overkill.
if (shorttxids.size() != cmpctblock.shorttxids.size())
return READ_STATUS_FAILED; // Short ID collision
std::vector<bool> have_txn(txn_available.size());
{
LOCK(pool->cs);
for (size_t i = 0; i < pool->vTxHashes.size(); i++) {
uint64_t shortid = cmpctblock.GetShortID(pool->vTxHashes[i].first);
std::unordered_map<uint64_t, uint16_t>::iterator idit = shorttxids.find(shortid);
if (idit != shorttxids.end()) {
if (!have_txn[idit->second]) {
txn_available[idit->second] = pool->vTxHashes[i].second->GetSharedTx();
have_txn[idit->second] = true;
mempool_count++;
} else {
// If we find two mempool txn that match the short id, just request it.
// This should be rare enough that the extra bandwidth doesn't matter,
// but eating a round-trip due to FillBlock failure would be annoying
if (txn_available[idit->second]) {
txn_available[idit->second].reset();
mempool_count--;
}
}
}
// Though ideally we'd continue scanning for the two-txn-match-shortid case,
// the performance win of an early exit here is too good to pass up and worth
// the extra risk.
if (mempool_count == shorttxids.size())
break;
}
}
for (size_t i = 0; i < extra_txn.size(); i++) {
uint64_t shortid = cmpctblock.GetShortID(extra_txn[i].first);
std::unordered_map<uint64_t, uint16_t>::iterator idit = shorttxids.find(shortid);
if (idit != shorttxids.end()) {
if (!have_txn[idit->second]) {
txn_available[idit->second] = extra_txn[i].second;
have_txn[idit->second] = true;
mempool_count++;
extra_count++;
} else {
// If we find two mempool/extra txn that match the short id, just
// request it.
// This should be rare enough that the extra bandwidth doesn't matter,
// but eating a round-trip due to FillBlock failure would be annoying
// Note that we don't want duplication between extra_txn and mempool to
// trigger this case, so we compare witness hashes first
if (txn_available[idit->second] &&
txn_available[idit->second]->GetWitnessHash() != extra_txn[i].second->GetWitnessHash()) {
txn_available[idit->second].reset();
mempool_count--;
extra_count--;
}
}
}
// Though ideally we'd continue scanning for the two-txn-match-shortid case,
// the performance win of an early exit here is too good to pass up and worth
// the extra risk.
if (mempool_count == shorttxids.size())
break;
}
LogPrint(BCLog::CMPCTBLOCK, "Initialized PartiallyDownloadedBlock for block %s using a cmpctblock of size %lu\n", cmpctblock.header.GetHash().ToString(), GetSerializeSize(cmpctblock, PROTOCOL_VERSION));
return READ_STATUS_OK;
}
bool PartiallyDownloadedBlock::IsTxAvailable(size_t index) const {
assert(!header.IsNull());
assert(index < txn_available.size());
return txn_available[index] != nullptr;
}
ReadStatus PartiallyDownloadedBlock::FillBlock(CBlock& block, const std::vector<CTransactionRef>& vtx_missing) {
assert(!header.IsNull());
uint256 hash = header.GetHash();
block = header;
block.vtx.resize(txn_available.size());
size_t tx_missing_offset = 0;
for (size_t i = 0; i < txn_available.size(); i++) {
if (!txn_available[i]) {
if (vtx_missing.size() <= tx_missing_offset)
return READ_STATUS_INVALID;
block.vtx[i] = vtx_missing[tx_missing_offset++];
} else
block.vtx[i] = std::move(txn_available[i]);
}
// Make sure we can't call FillBlock again.
header.SetNull();
txn_available.clear();
if (vtx_missing.size() != tx_missing_offset)
return READ_STATUS_INVALID;
BlockValidationState state;
if (!CheckBlock(block, state, Params().GetConsensus())) {
// TODO: We really want to just check merkle tree manually here,
// but that is expensive, and CheckBlock caches a block's
// "checked-status" (in the CBlock?). CBlock should be able to
// check its own merkle root and cache that check.
if (state.GetResult() == BlockValidationResult::BLOCK_MUTATED)
return READ_STATUS_FAILED; // Possible Short ID collision
return READ_STATUS_CHECKBLOCK_FAILED;
}
LogPrint(BCLog::CMPCTBLOCK, "Successfully reconstructed block %s with %lu txn prefilled, %lu txn from mempool (incl at least %lu from extra pool) and %lu txn requested\n", hash.ToString(), prefilled_count, mempool_count, extra_count, vtx_missing.size());
if (vtx_missing.size() < 5) {
for (const auto& tx : vtx_missing) {
LogPrint(BCLog::CMPCTBLOCK, "Reconstructed block %s required tx %s\n", hash.ToString(), tx->GetHash().ToString());
}
}
return READ_STATUS_OK;
}
| mit |
OUWECAD/MOWE | Projects/All RX Terminal+Gimbal/Firmware_RX/Drivers/CMSIS/DSP_Lib/Source/MatrixFunctions/arm_mat_add_q31.c | 279 | 6471 | /* ----------------------------------------------------------------------
* Copyright (C) 2010-2014 ARM Limited. All rights reserved.
*
* $Date: 19. March 2015
* $Revision: V.1.4.5
*
* Project: CMSIS DSP Library
* Title: arm_mat_add_q31.c
*
* Description: Q31 matrix addition
*
* Target Processor: Cortex-M4/Cortex-M3/Cortex-M0
*
* 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 ARM LIMITED 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.
* -------------------------------------------------------------------- */
#include "arm_math.h"
/**
* @ingroup groupMatrix
*/
/**
* @addtogroup MatrixAdd
* @{
*/
/**
* @brief Q31 matrix addition.
* @param[in] *pSrcA points to the first input matrix structure
* @param[in] *pSrcB points to the second input matrix structure
* @param[out] *pDst points to output matrix structure
* @return The function returns either
* <code>ARM_MATH_SIZE_MISMATCH</code> or <code>ARM_MATH_SUCCESS</code> based on the outcome of size checking.
*
* <b>Scaling and Overflow Behavior:</b>
* \par
* The function uses saturating arithmetic.
* Results outside of the allowable Q31 range [0x80000000 0x7FFFFFFF] will be saturated.
*/
arm_status arm_mat_add_q31(
const arm_matrix_instance_q31 * pSrcA,
const arm_matrix_instance_q31 * pSrcB,
arm_matrix_instance_q31 * pDst)
{
q31_t *pIn1 = pSrcA->pData; /* input data matrix pointer A */
q31_t *pIn2 = pSrcB->pData; /* input data matrix pointer B */
q31_t *pOut = pDst->pData; /* output data matrix pointer */
q31_t inA1, inB1; /* temporary variables */
#ifndef ARM_MATH_CM0_FAMILY
q31_t inA2, inB2; /* temporary variables */
q31_t out1, out2; /* temporary variables */
#endif // #ifndef ARM_MATH_CM0_FAMILY
uint32_t numSamples; /* total number of elements in the matrix */
uint32_t blkCnt; /* loop counters */
arm_status status; /* status of matrix addition */
#ifdef ARM_MATH_MATRIX_CHECK
/* Check for matrix mismatch condition */
if((pSrcA->numRows != pSrcB->numRows) ||
(pSrcA->numCols != pSrcB->numCols) ||
(pSrcA->numRows != pDst->numRows) || (pSrcA->numCols != pDst->numCols))
{
/* Set status as ARM_MATH_SIZE_MISMATCH */
status = ARM_MATH_SIZE_MISMATCH;
}
else
#endif
{
/* Total number of samples in the input matrix */
numSamples = (uint32_t) pSrcA->numRows * pSrcA->numCols;
#ifndef ARM_MATH_CM0_FAMILY
/* Run the below code for Cortex-M4 and Cortex-M3 */
/* Loop Unrolling */
blkCnt = numSamples >> 2u;
/* First part of the processing with loop unrolling. Compute 4 outputs at a time.
** a second loop below computes the remaining 1 to 3 samples. */
while(blkCnt > 0u)
{
/* C(m,n) = A(m,n) + B(m,n) */
/* Add, saturate and then store the results in the destination buffer. */
/* Read values from source A */
inA1 = pIn1[0];
/* Read values from source B */
inB1 = pIn2[0];
/* Read values from source A */
inA2 = pIn1[1];
/* Add and saturate */
out1 = __QADD(inA1, inB1);
/* Read values from source B */
inB2 = pIn2[1];
/* Read values from source A */
inA1 = pIn1[2];
/* Add and saturate */
out2 = __QADD(inA2, inB2);
/* Read values from source B */
inB1 = pIn2[2];
/* Store result in destination */
pOut[0] = out1;
pOut[1] = out2;
/* Read values from source A */
inA2 = pIn1[3];
/* Read values from source B */
inB2 = pIn2[3];
/* Add and saturate */
out1 = __QADD(inA1, inB1);
out2 = __QADD(inA2, inB2);
/* Store result in destination */
pOut[2] = out1;
pOut[3] = out2;
/* update pointers to process next sampels */
pIn1 += 4u;
pIn2 += 4u;
pOut += 4u;
/* Decrement the loop counter */
blkCnt--;
}
/* If the numSamples is not a multiple of 4, compute any remaining output samples here.
** No loop unrolling is used. */
blkCnt = numSamples % 0x4u;
#else
/* Run the below code for Cortex-M0 */
/* Initialize blkCnt with number of samples */
blkCnt = numSamples;
#endif /* #ifndef ARM_MATH_CM0_FAMILY */
while(blkCnt > 0u)
{
/* C(m,n) = A(m,n) + B(m,n) */
/* Add, saturate and then store the results in the destination buffer. */
inA1 = *pIn1++;
inB1 = *pIn2++;
inA1 = __QADD(inA1, inB1);
/* Decrement the loop counter */
blkCnt--;
*pOut++ = inA1;
}
/* set status as ARM_MATH_SUCCESS */
status = ARM_MATH_SUCCESS;
}
/* Return to application */
return (status);
}
/**
* @} end of MatrixAdd group
*/
| mit |
kristofe/SimpleRenderer | libraries/glfw/src/x11_joystick.c | 25 | 6758 | //========================================================================
// GLFW 3.0 X11 - www.glfw.org
//------------------------------------------------------------------------
// Copyright (c) 2002-2006 Marcus Geelnard
// Copyright (c) 2006-2010 Camilla Berglund <elmindreda@elmindreda.org>
//
// This software is provided 'as-is', without any express or implied
// warranty. In no event will the authors be held liable for any damages
// arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,
// including commercial applications, and to alter it and redistribute it
// freely, subject to the following restrictions:
//
// 1. The origin of this software must not be misrepresented; you must not
// claim that you wrote the original software. If you use this software
// in a product, an acknowledgment in the product documentation would
// be appreciated but is not required.
//
// 2. Altered source versions must be plainly marked as such, and must not
// be misrepresented as being the original software.
//
// 3. This notice may not be removed or altered from any source
// distribution.
//
//========================================================================
#include "internal.h"
#ifdef __linux__
#include <linux/joystick.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <regex.h>
#include <dirent.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#endif // __linux__
// Attempt to open the specified joystick device
//
static int openJoystickDevice(int joy, const char* path)
{
#ifdef __linux__
char axisCount, buttonCount;
char name[256];
int fd, version;
fd = open(path, O_RDONLY | O_NONBLOCK);
if (fd == -1)
return GL_FALSE;
_glfw.x11.joystick[joy].fd = fd;
// Verify that the joystick driver version is at least 1.0
ioctl(fd, JSIOCGVERSION, &version);
if (version < 0x010000)
{
// It's an old 0.x interface (we don't support it)
close(fd);
return GL_FALSE;
}
if (ioctl(fd, JSIOCGNAME(sizeof(name)), name) < 0)
strncpy(name, "Unknown", sizeof(name));
_glfw.x11.joystick[joy].name = strdup(name);
ioctl(fd, JSIOCGAXES, &axisCount);
_glfw.x11.joystick[joy].axisCount = (int) axisCount;
ioctl(fd, JSIOCGBUTTONS, &buttonCount);
_glfw.x11.joystick[joy].buttonCount = (int) buttonCount;
_glfw.x11.joystick[joy].axes = calloc(axisCount, sizeof(float));
_glfw.x11.joystick[joy].buttons = calloc(buttonCount, 1);
_glfw.x11.joystick[joy].present = GL_TRUE;
#endif // __linux__
return GL_TRUE;
}
// Polls for and processes events for all present joysticks
//
static void pollJoystickEvents(void)
{
#ifdef __linux__
int i;
ssize_t result;
struct js_event e;
for (i = 0; i <= GLFW_JOYSTICK_LAST; i++)
{
if (!_glfw.x11.joystick[i].present)
continue;
// Read all queued events (non-blocking)
for (;;)
{
errno = 0;
result = read(_glfw.x11.joystick[i].fd, &e, sizeof(e));
if (errno == ENODEV)
{
free(_glfw.x11.joystick[i].axes);
free(_glfw.x11.joystick[i].buttons);
free(_glfw.x11.joystick[i].name);
_glfw.x11.joystick[i].present = GL_FALSE;
}
if (result == -1)
break;
// We don't care if it's an init event or not
e.type &= ~JS_EVENT_INIT;
switch (e.type)
{
case JS_EVENT_AXIS:
_glfw.x11.joystick[i].axes[e.number] =
(float) e.value / 32767.0f;
break;
case JS_EVENT_BUTTON:
_glfw.x11.joystick[i].buttons[e.number] =
e.value ? GLFW_PRESS : GLFW_RELEASE;
break;
default:
break;
}
}
}
#endif // __linux__
}
//////////////////////////////////////////////////////////////////////////
////// GLFW internal API //////
//////////////////////////////////////////////////////////////////////////
// Initialize joystick interface
//
void _glfwInitJoysticks(void)
{
#ifdef __linux__
int joy = 0;
size_t i;
regex_t regex;
DIR* dir;
const char* dirs[] =
{
"/dev/input",
"/dev"
};
if (regcomp(®ex, "^js[0-9]\\+$", 0) != 0)
{
_glfwInputError(GLFW_PLATFORM_ERROR, "X11: Failed to compile regex");
return;
}
for (i = 0; i < sizeof(dirs) / sizeof(dirs[0]); i++)
{
struct dirent* entry;
dir = opendir(dirs[i]);
if (!dir)
continue;
while ((entry = readdir(dir)))
{
char path[20];
regmatch_t match;
if (regexec(®ex, entry->d_name, 1, &match, 0) != 0)
continue;
snprintf(path, sizeof(path), "%s/%s", dirs[i], entry->d_name);
if (openJoystickDevice(joy, path))
joy++;
}
closedir(dir);
}
regfree(®ex);
#endif // __linux__
}
// Close all opened joystick handles
//
void _glfwTerminateJoysticks(void)
{
#ifdef __linux__
int i;
for (i = 0; i <= GLFW_JOYSTICK_LAST; i++)
{
if (_glfw.x11.joystick[i].present)
{
close(_glfw.x11.joystick[i].fd);
free(_glfw.x11.joystick[i].axes);
free(_glfw.x11.joystick[i].buttons);
free(_glfw.x11.joystick[i].name);
_glfw.x11.joystick[i].present = GL_FALSE;
}
}
#endif // __linux__
}
//////////////////////////////////////////////////////////////////////////
////// GLFW platform API //////
//////////////////////////////////////////////////////////////////////////
int _glfwPlatformJoystickPresent(int joy)
{
pollJoystickEvents();
return _glfw.x11.joystick[joy].present;
}
const float* _glfwPlatformGetJoystickAxes(int joy, int* count)
{
pollJoystickEvents();
if (!_glfw.x11.joystick[joy].present)
return NULL;
*count = _glfw.x11.joystick[joy].axisCount;
return _glfw.x11.joystick[joy].axes;
}
const unsigned char* _glfwPlatformGetJoystickButtons(int joy, int* count)
{
pollJoystickEvents();
if (!_glfw.x11.joystick[joy].present)
return NULL;
*count = _glfw.x11.joystick[joy].buttonCount;
return _glfw.x11.joystick[joy].buttons;
}
const char* _glfwPlatformGetJoystickName(int joy)
{
pollJoystickEvents();
return _glfw.x11.joystick[joy].name;
}
| mit |
Tech4Race/nrf5x-base | sdk/nrf51_sdk_9.0.0/components/serialization/application/codecs/s120/serializers/ble_gap_evt_sec_params_request.c | 25 | 1910 | /* Copyright (c) 2013 Nordic Semiconductor. All Rights Reserved.
*
* The information contained herein is property of Nordic Semiconductor ASA.
* Terms and conditions of usage are described in detail in NORDIC
* SEMICONDUCTOR STANDARD SOFTWARE LICENSE AGREEMENT.
*
* Licensees are granted free, non-transferable use of the information. NO
* WARRANTY of ANY KIND is provided. This heading must NOT be removed from
* the file.
*
*/
#include "ble_gap_evt_app.h"
#include "ble_serialization.h"
#include "ble_gap_struct_serialization.h"
#include "app_util.h"
uint32_t ble_gap_evt_sec_params_request_dec(uint8_t const * const p_buf,
uint32_t packet_len,
ble_evt_t * const p_event,
uint32_t * const p_event_len)
{
uint32_t index = 0;
uint32_t event_len;
uint32_t err_code = NRF_SUCCESS;
SER_ASSERT_NOT_NULL(p_buf);
SER_ASSERT_NOT_NULL(p_event_len);
SER_ASSERT_LENGTH_LEQ(7, packet_len);
event_len = SER_EVT_CONN_HANDLE_SIZE + sizeof (ble_gap_evt_sec_params_request_t);
if (p_event == NULL)
{
*p_event_len = event_len;
return NRF_SUCCESS;
}
SER_ASSERT(event_len <= *p_event_len, NRF_ERROR_DATA_SIZE);
p_event->header.evt_id = BLE_GAP_EVT_SEC_PARAMS_REQUEST;
p_event->header.evt_len = event_len;
err_code = uint16_t_dec(p_buf, packet_len, &index, &(p_event->evt.gap_evt.conn_handle));
SER_ASSERT(err_code == NRF_SUCCESS, err_code);
err_code = ble_gap_evt_sec_params_request_t_dec(p_buf, packet_len, &index, &(p_event->evt.gap_evt.params.sec_params_request));
SER_ASSERT(err_code == NRF_SUCCESS, err_code);
SER_ASSERT_LENGTH_EQ(index, packet_len);
*p_event_len = event_len;
return err_code;
}
| mit |
litecoin-project/litecore-litecoin | src/protocol.cpp | 41 | 5045 | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "protocol.h"
#include "util.h"
#include "utilstrencodings.h"
#ifndef WIN32
# include <arpa/inet.h>
#endif
namespace NetMsgType {
const char *VERSION="version";
const char *VERACK="verack";
const char *ADDR="addr";
const char *INV="inv";
const char *GETDATA="getdata";
const char *MERKLEBLOCK="merkleblock";
const char *GETBLOCKS="getblocks";
const char *GETHEADERS="getheaders";
const char *TX="tx";
const char *HEADERS="headers";
const char *BLOCK="block";
const char *GETADDR="getaddr";
const char *MEMPOOL="mempool";
const char *PING="ping";
const char *PONG="pong";
const char *NOTFOUND="notfound";
const char *FILTERLOAD="filterload";
const char *FILTERADD="filteradd";
const char *FILTERCLEAR="filterclear";
const char *REJECT="reject";
const char *SENDHEADERS="sendheaders";
const char *FEEFILTER="feefilter";
const char *SENDCMPCT="sendcmpct";
const char *CMPCTBLOCK="cmpctblock";
const char *GETBLOCKTXN="getblocktxn";
const char *BLOCKTXN="blocktxn";
};
/** All known message types. Keep this in the same order as the list of
* messages above and in protocol.h.
*/
const static std::string allNetMessageTypes[] = {
NetMsgType::VERSION,
NetMsgType::VERACK,
NetMsgType::ADDR,
NetMsgType::INV,
NetMsgType::GETDATA,
NetMsgType::MERKLEBLOCK,
NetMsgType::GETBLOCKS,
NetMsgType::GETHEADERS,
NetMsgType::TX,
NetMsgType::HEADERS,
NetMsgType::BLOCK,
NetMsgType::GETADDR,
NetMsgType::MEMPOOL,
NetMsgType::PING,
NetMsgType::PONG,
NetMsgType::NOTFOUND,
NetMsgType::FILTERLOAD,
NetMsgType::FILTERADD,
NetMsgType::FILTERCLEAR,
NetMsgType::REJECT,
NetMsgType::SENDHEADERS,
NetMsgType::FEEFILTER,
NetMsgType::SENDCMPCT,
NetMsgType::CMPCTBLOCK,
NetMsgType::GETBLOCKTXN,
NetMsgType::BLOCKTXN,
};
const static std::vector<std::string> allNetMessageTypesVec(allNetMessageTypes, allNetMessageTypes+ARRAYLEN(allNetMessageTypes));
CMessageHeader::CMessageHeader(const MessageStartChars& pchMessageStartIn)
{
memcpy(pchMessageStart, pchMessageStartIn, MESSAGE_START_SIZE);
memset(pchCommand, 0, sizeof(pchCommand));
nMessageSize = -1;
nChecksum = 0;
}
CMessageHeader::CMessageHeader(const MessageStartChars& pchMessageStartIn, const char* pszCommand, unsigned int nMessageSizeIn)
{
memcpy(pchMessageStart, pchMessageStartIn, MESSAGE_START_SIZE);
memset(pchCommand, 0, sizeof(pchCommand));
strncpy(pchCommand, pszCommand, COMMAND_SIZE);
nMessageSize = nMessageSizeIn;
nChecksum = 0;
}
std::string CMessageHeader::GetCommand() const
{
return std::string(pchCommand, pchCommand + strnlen(pchCommand, COMMAND_SIZE));
}
bool CMessageHeader::IsValid(const MessageStartChars& pchMessageStartIn) const
{
// Check start string
if (memcmp(pchMessageStart, pchMessageStartIn, MESSAGE_START_SIZE) != 0)
return false;
// Check the command string for errors
for (const char* p1 = pchCommand; p1 < pchCommand + COMMAND_SIZE; p1++)
{
if (*p1 == 0)
{
// Must be all zeros after the first zero
for (; p1 < pchCommand + COMMAND_SIZE; p1++)
if (*p1 != 0)
return false;
}
else if (*p1 < ' ' || *p1 > 0x7E)
return false;
}
// Message size
if (nMessageSize > MAX_SIZE)
{
LogPrintf("CMessageHeader::IsValid(): (%s, %u bytes) nMessageSize > MAX_SIZE\n", GetCommand(), nMessageSize);
return false;
}
return true;
}
CAddress::CAddress() : CService()
{
Init();
}
CAddress::CAddress(CService ipIn, ServiceFlags nServicesIn) : CService(ipIn)
{
Init();
nServices = nServicesIn;
}
void CAddress::Init()
{
nServices = NODE_NONE;
nTime = 100000000;
}
CInv::CInv()
{
type = 0;
hash.SetNull();
}
CInv::CInv(int typeIn, const uint256& hashIn)
{
type = typeIn;
hash = hashIn;
}
bool operator<(const CInv& a, const CInv& b)
{
return (a.type < b.type || (a.type == b.type && a.hash < b.hash));
}
std::string CInv::GetCommand() const
{
std::string cmd;
if (type & MSG_WITNESS_FLAG)
cmd.append("witness-");
int masked = type & MSG_TYPE_MASK;
switch (masked)
{
case MSG_TX: return cmd.append(NetMsgType::TX);
case MSG_BLOCK: return cmd.append(NetMsgType::BLOCK);
case MSG_FILTERED_BLOCK: return cmd.append(NetMsgType::MERKLEBLOCK);
case MSG_CMPCT_BLOCK: return cmd.append(NetMsgType::CMPCTBLOCK);
default:
throw std::out_of_range(strprintf("CInv::GetCommand(): type=%d unknown type", type));
}
}
std::string CInv::ToString() const
{
return strprintf("%s %s", GetCommand(), hash.ToString());
}
const std::vector<std::string> &getAllNetMessageTypes()
{
return allNetMessageTypesVec;
}
| mit |
jordansite/jekyll-vlog | vendor/ruby/2.3.0/gems/ffi-1.9.18/ext/ffi_c/libffi/testsuite/libffi.call/closure_fn5.c | 812 | 3065 | /* Area: closure_call
Purpose: Check multiple long long values passing.
Exceed the limit of gpr registers on PowerPC
Darwin.
Limitations: none.
PR: none.
Originator: <andreast@gcc.gnu.org> 20031026 */
/* { dg-do run } */
#include "ffitest.h"
static void
closure_test_fn5(ffi_cif* cif __UNUSED__, void* resp, void** args,
void* userdata)
{
*(ffi_arg*)resp =
(int)*(unsigned long long *)args[0] + (int)*(unsigned long long *)args[1] +
(int)*(unsigned long long *)args[2] + (int)*(unsigned long long *)args[3] +
(int)*(unsigned long long *)args[4] + (int)*(unsigned long long *)args[5] +
(int)*(unsigned long long *)args[6] + (int)*(unsigned long long *)args[7] +
(int)*(unsigned long long *)args[8] + (int)*(unsigned long long *)args[9] +
(int)*(int *)args[10] +
(int)*(unsigned long long *)args[11] +
(int)*(unsigned long long *)args[12] +
(int)*(unsigned long long *)args[13] +
(int)*(unsigned long long *)args[14] +
*(int *)args[15] + (intptr_t)userdata;
printf("%d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d %d: %d\n",
(int)*(unsigned long long *)args[0],
(int)*(unsigned long long *)args[1],
(int)*(unsigned long long *)args[2],
(int)*(unsigned long long *)args[3],
(int)*(unsigned long long *)args[4],
(int)*(unsigned long long *)args[5],
(int)*(unsigned long long *)args[6],
(int)*(unsigned long long *)args[7],
(int)*(unsigned long long *)args[8],
(int)*(unsigned long long *)args[9],
(int)*(int *)args[10],
(int)*(unsigned long long *)args[11],
(int)*(unsigned long long *)args[12],
(int)*(unsigned long long *)args[13],
(int)*(unsigned long long *)args[14],
*(int *)args[15],
(int)(intptr_t)userdata, (int)*(ffi_arg *)resp);
}
typedef int (*closure_test_type0)(unsigned long long, unsigned long long,
unsigned long long, unsigned long long,
unsigned long long, unsigned long long,
unsigned long long, unsigned long long,
unsigned long long, unsigned long long,
int, unsigned long long,
unsigned long long, unsigned long long,
unsigned long long, int);
int main (void)
{
ffi_cif cif;
void *code;
ffi_closure *pcl = ffi_closure_alloc(sizeof(ffi_closure), &code);
ffi_type * cl_arg_types[17];
int i, res;
for (i = 0; i < 10; i++) {
cl_arg_types[i] = &ffi_type_uint64;
}
cl_arg_types[10] = &ffi_type_sint;
for (i = 11; i < 15; i++) {
cl_arg_types[i] = &ffi_type_uint64;
}
cl_arg_types[15] = &ffi_type_sint;
cl_arg_types[16] = NULL;
/* Initialize the cif */
CHECK(ffi_prep_cif(&cif, FFI_DEFAULT_ABI, 16,
&ffi_type_sint, cl_arg_types) == FFI_OK);
CHECK(ffi_prep_closure_loc(pcl, &cif, closure_test_fn5,
(void *) 3 /* userdata */, code) == FFI_OK);
res = (*((closure_test_type0)code))
(1LL, 2LL, 3LL, 4LL, 127LL, 429LL, 7LL, 8LL, 9LL, 10LL, 11, 12LL,
13LL, 19LL, 21LL, 1);
/* { dg-output "1 2 3 4 127 429 7 8 9 10 11 12 13 19 21 1 3: 680" } */
printf("res: %d\n",res);
/* { dg-output "\nres: 680" } */
exit(0);
}
| mit |
dwaynebailey/poedit | deps/boost/libs/chrono/perf/store_now_in_vector.cpp | 47 | 3371 | // Copyright 2011 Vicente J. Botet Escriba
// Copyright (c) Microsoft Corporation 2014
// Distributed under the Boost Software License, Version 1.0.
// See http://www.boost.org/LICENSE_1_0.txt
#include <boost/chrono/chrono.hpp>
#include <boost/chrono/chrono_io.hpp>
#include <libs/chrono/example/timer.hpp>
#include <boost/chrono/process_cpu_clocks.hpp>
#include <vector>
//#define BOOST_CHRONO_HAS_TIMES_AND_CLOCK
#ifdef BOOST_CHRONO_HAS_TIMES_AND_CLOCK
#include <sys/time.h> //for gettimeofday and timeval
#include <sys/times.h> //for times
#include <unistd.h>
#endif
static const std::size_t size = 1000000;
typedef boost::chrono::timer<boost::chrono::high_resolution_clock> Stopwatch;
template <typename Clock>
void perf_constant(std::vector<typename Clock::time_point>& vec)
{
for (int i=size-1; i>=0; --i)
{
vec[i]=typename Clock::time_point();
}
}
template <typename Clock>
void perf(std::vector<typename Clock::time_point>& vec)
{
for (int i=size-1; i>=0; --i)
{
vec[i]=Clock::now();
}
}
template <typename Clock>
void test()
{
std::vector<typename Clock::time_point> vec(size);
Stopwatch sw1;
perf_constant<Clock>(vec);
Stopwatch::duration t1 = sw1.elapsed();
Stopwatch sw2;
perf<Clock>(vec);
Stopwatch::duration t2 = sw2.elapsed();
std::cout <<" "<< (t2-t1) << std::endl;
//std::cout <<" "<< ((t2-t1)/size) << std::endl;
std::size_t cnt=0;
for (int i=size-1; i>0; --i)
{
if (vec[i]!=vec[i-1]) ++cnt;
}
std::cout <<"changes: "<< cnt << std::endl;
}
#ifdef BOOST_CHRONO_HAS_TIMES_AND_CLOCK
void perf2(std::vector<clock_t>& vec)
{
Stopwatch sw;
for (int i=size-1; i>=0; --i)
{
tms tm;
vec[i]=::times(&tm);
}
std::cout << sw.elapsed() << std::endl;
}
void perf3(std::vector<clock_t>& vec)
{
Stopwatch sw;
for (int i=size-1; i>=0; --i)
{
vec[i]=::clock();
}
std::cout << sw.elapsed() << std::endl;
}
void test2()
{
std::vector<clock_t> vec(size);
perf2(vec);
std::size_t cnt=0;
for (int i=10; i>0; --i)
{
if (vec[i]!=vec[i-1]) ++cnt;
std::cout << vec[i] << " " ;
}
std::cout<< std::endl;
std::cout <<"changes: "<< cnt << std::endl;
}
void test3()
{
std::vector<clock_t> vec(size);
perf3(vec);
std::size_t cnt=0;
for (int i=10; i>0; --i)
{
if (vec[i]!=vec[i-1]) ++cnt;
std::cout << vec[i] << " " ;
}
std::cout<< std::endl;
std::cout <<"changes: "<< cnt << std::endl;
}
#endif
int main() {
std::cout << "system_clock ";
test<boost::chrono::system_clock>();
#ifdef BOOST_CHRONO_HAS_CLOCK_STEADY
std::cout << "steady_clock " ;
test<boost::chrono::steady_clock>();
#endif
std::cout << "high_resolution_clock " ;
test<boost::chrono::high_resolution_clock>();
#if defined(BOOST_CHRONO_HAS_PROCESS_CLOCKS)
std::cout << "process_real_cpu_clock ";
test<boost::chrono::process_real_cpu_clock>();
#if ! BOOST_OS_WINDOWS || BOOST_PLAT_WINDOWS_DESKTOP
std::cout << "process_user_cpu_clock ";
test<boost::chrono::process_user_cpu_clock>();
std::cout << "process_system_cpu_clock " ;
test<boost::chrono::process_system_cpu_clock>();
std::cout << "process_cpu_clock " ;
test<boost::chrono::process_cpu_clock>();
#endif
#endif
std::cout << "system_clock ";
test<boost::chrono::system_clock>();
#if 0
std::cout << "times ";
test2();
std::cout << "clock ";
test3();
#endif
return 1;
}
| mit |
FFMG/myoddweb.piger | myodd/boost/libs/graph/test/grid_graph_test.cpp | 51 | 6842 | //=======================================================================
// Copyright 2009 Trustees of Indiana University.
// Authors: Michael Hansen, Andrew Lumsdaine
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#include <fstream>
#include <iostream>
#include <set>
#include <boost/foreach.hpp>
#include <boost/lexical_cast.hpp>
#include <boost/graph/grid_graph.hpp>
#include <boost/random.hpp>
#include <boost/test/minimal.hpp>
using namespace boost;
// Function that prints a vertex to std::cout
template <typename Vertex>
void print_vertex(Vertex vertex_to_print) {
std::cout << "(";
for (std::size_t dimension_index = 0;
dimension_index < vertex_to_print.size();
++dimension_index) {
std::cout << vertex_to_print[dimension_index];
if (dimension_index != (vertex_to_print.size() - 1)) {
std::cout << ", ";
}
}
std::cout << ")";
}
template <unsigned int Dims>
void do_test(minstd_rand& generator) {
typedef grid_graph<Dims> Graph;
typedef typename graph_traits<Graph>::vertices_size_type vertices_size_type;
typedef typename graph_traits<Graph>::edges_size_type edges_size_type;
typedef typename graph_traits<Graph>::vertex_descriptor vertex_descriptor;
typedef typename graph_traits<Graph>::edge_descriptor edge_descriptor;
std::cout << "Dimensions: " << Dims << ", lengths: ";
// Randomly generate the dimension lengths (3-10) and wrapping
boost::array<vertices_size_type, Dims> lengths;
boost::array<bool, Dims> wrapped;
for (unsigned int dimension_index = 0;
dimension_index < Dims;
++dimension_index) {
lengths[dimension_index] = 3 + (generator() % 8);
wrapped[dimension_index] = ((generator() % 2) == 0);
std::cout << lengths[dimension_index] <<
(wrapped[dimension_index] ? " [W]" : " [U]") << ", ";
}
std::cout << std::endl;
Graph graph(lengths, wrapped);
// Verify dimension lengths and wrapping
for (unsigned int dimension_index = 0;
dimension_index < Dims;
++dimension_index) {
BOOST_REQUIRE(graph.length(dimension_index) == lengths[dimension_index]);
BOOST_REQUIRE(graph.wrapped(dimension_index) == wrapped[dimension_index]);
}
// Verify matching indices
for (vertices_size_type vertex_index = 0;
vertex_index < num_vertices(graph);
++vertex_index) {
BOOST_REQUIRE(get(boost::vertex_index, graph, vertex(vertex_index, graph)) == vertex_index);
}
for (edges_size_type edge_index = 0;
edge_index < num_edges(graph);
++edge_index) {
edge_descriptor current_edge = edge_at(edge_index, graph);
BOOST_REQUIRE(get(boost::edge_index, graph, current_edge) == edge_index);
}
// Verify all vertices are within bounds
vertices_size_type vertex_count = 0;
BOOST_FOREACH(vertex_descriptor current_vertex, vertices(graph)) {
vertices_size_type current_index =
get(boost::vertex_index, graph, current_vertex);
for (unsigned int dimension_index = 0;
dimension_index < Dims;
++dimension_index) {
BOOST_REQUIRE(/*(current_vertex[dimension_index] >= 0) && */ // Always true
(current_vertex[dimension_index] < lengths[dimension_index]));
}
// Verify out-edges of this vertex
edges_size_type out_edge_count = 0;
std::set<vertices_size_type> target_vertices;
BOOST_FOREACH(edge_descriptor out_edge,
out_edges(current_vertex, graph)) {
target_vertices.insert
(get(boost::vertex_index, graph, target(out_edge, graph)));
++out_edge_count;
}
BOOST_REQUIRE(out_edge_count == out_degree(current_vertex, graph));
// Verify in-edges of this vertex
edges_size_type in_edge_count = 0;
BOOST_FOREACH(edge_descriptor in_edge,
in_edges(current_vertex, graph)) {
BOOST_REQUIRE(target_vertices.count
(get(boost::vertex_index, graph, source(in_edge, graph))) > 0);
++in_edge_count;
}
BOOST_REQUIRE(in_edge_count == in_degree(current_vertex, graph));
// The number of out-edges and in-edges should be the same
BOOST_REQUIRE(degree(current_vertex, graph) ==
out_degree(current_vertex, graph) +
in_degree(current_vertex, graph));
// Verify adjacent vertices to this vertex
vertices_size_type adjacent_count = 0;
BOOST_FOREACH(vertex_descriptor adjacent_vertex,
adjacent_vertices(current_vertex, graph)) {
BOOST_REQUIRE(target_vertices.count
(get(boost::vertex_index, graph, adjacent_vertex)) > 0);
++adjacent_count;
}
BOOST_REQUIRE(adjacent_count == out_degree(current_vertex, graph));
// Verify that this vertex is not listed as connected to any
// vertices outside of its adjacent vertices.
BOOST_FOREACH(vertex_descriptor unconnected_vertex, vertices(graph)) {
vertices_size_type unconnected_index =
get(boost::vertex_index, graph, unconnected_vertex);
if ((unconnected_index == current_index) ||
(target_vertices.count(unconnected_index) > 0)) {
continue;
}
BOOST_REQUIRE(!edge(current_vertex, unconnected_vertex, graph).second);
BOOST_REQUIRE(!edge(unconnected_vertex, current_vertex, graph).second);
}
++vertex_count;
}
BOOST_REQUIRE(vertex_count == num_vertices(graph));
// Verify all edges are within bounds
edges_size_type edge_count = 0;
BOOST_FOREACH(edge_descriptor current_edge, edges(graph)) {
vertices_size_type source_index =
get(boost::vertex_index, graph, source(current_edge, graph));
vertices_size_type target_index =
get(boost::vertex_index, graph, target(current_edge, graph));
BOOST_REQUIRE(source_index != target_index);
BOOST_REQUIRE(/* (source_index >= 0) : always true && */ (source_index < num_vertices(graph)));
BOOST_REQUIRE(/* (target_index >= 0) : always true && */ (target_index < num_vertices(graph)));
// Verify that the edge is listed as existing in both directions
BOOST_REQUIRE(edge(source(current_edge, graph), target(current_edge, graph), graph).second);
BOOST_REQUIRE(edge(target(current_edge, graph), source(current_edge, graph), graph).second);
++edge_count;
}
BOOST_REQUIRE(edge_count == num_edges(graph));
}
int test_main(int argc, char* argv[]) {
std::size_t random_seed = time(0);
if (argc > 1) {
random_seed = lexical_cast<std::size_t>(argv[1]);
}
minstd_rand generator(random_seed);
do_test<0>(generator);
do_test<1>(generator);
do_test<2>(generator);
do_test<3>(generator);
do_test<4>(generator);
return (0);
}
| mit |
firefly2442/godot | thirdparty/icu4c/common/uiter.cpp | 52 | 32120 | // © 2016 and later: Unicode, Inc. and others.
// License & terms of use: http://www.unicode.org/copyright.html
/*
*******************************************************************************
*
* Copyright (C) 2002-2012, International Business Machines
* Corporation and others. All Rights Reserved.
*
*******************************************************************************
* file name: uiter.cpp
* encoding: UTF-8
* tab size: 8 (not used)
* indentation:4
*
* created on: 2002jan18
* created by: Markus W. Scherer
*/
#include "unicode/utypes.h"
#include "unicode/ustring.h"
#include "unicode/chariter.h"
#include "unicode/rep.h"
#include "unicode/uiter.h"
#include "unicode/utf.h"
#include "unicode/utf8.h"
#include "unicode/utf16.h"
#include "cstring.h"
U_NAMESPACE_USE
#define IS_EVEN(n) (((n)&1)==0)
#define IS_POINTER_EVEN(p) IS_EVEN((size_t)p)
U_CDECL_BEGIN
/* No-Op UCharIterator implementation for illegal input --------------------- */
static int32_t U_CALLCONV
noopGetIndex(UCharIterator * /*iter*/, UCharIteratorOrigin /*origin*/) {
return 0;
}
static int32_t U_CALLCONV
noopMove(UCharIterator * /*iter*/, int32_t /*delta*/, UCharIteratorOrigin /*origin*/) {
return 0;
}
static UBool U_CALLCONV
noopHasNext(UCharIterator * /*iter*/) {
return FALSE;
}
static UChar32 U_CALLCONV
noopCurrent(UCharIterator * /*iter*/) {
return U_SENTINEL;
}
static uint32_t U_CALLCONV
noopGetState(const UCharIterator * /*iter*/) {
return UITER_NO_STATE;
}
static void U_CALLCONV
noopSetState(UCharIterator * /*iter*/, uint32_t /*state*/, UErrorCode *pErrorCode) {
*pErrorCode=U_UNSUPPORTED_ERROR;
}
static const UCharIterator noopIterator={
0, 0, 0, 0, 0, 0,
noopGetIndex,
noopMove,
noopHasNext,
noopHasNext,
noopCurrent,
noopCurrent,
noopCurrent,
NULL,
noopGetState,
noopSetState
};
/* UCharIterator implementation for simple strings -------------------------- */
/*
* This is an implementation of a code unit (UChar) iterator
* for UChar * strings.
*
* The UCharIterator.context field holds a pointer to the string.
*/
static int32_t U_CALLCONV
stringIteratorGetIndex(UCharIterator *iter, UCharIteratorOrigin origin) {
switch(origin) {
case UITER_ZERO:
return 0;
case UITER_START:
return iter->start;
case UITER_CURRENT:
return iter->index;
case UITER_LIMIT:
return iter->limit;
case UITER_LENGTH:
return iter->length;
default:
/* not a valid origin */
/* Should never get here! */
return -1;
}
}
static int32_t U_CALLCONV
stringIteratorMove(UCharIterator *iter, int32_t delta, UCharIteratorOrigin origin) {
int32_t pos;
switch(origin) {
case UITER_ZERO:
pos=delta;
break;
case UITER_START:
pos=iter->start+delta;
break;
case UITER_CURRENT:
pos=iter->index+delta;
break;
case UITER_LIMIT:
pos=iter->limit+delta;
break;
case UITER_LENGTH:
pos=iter->length+delta;
break;
default:
return -1; /* Error */
}
if(pos<iter->start) {
pos=iter->start;
} else if(pos>iter->limit) {
pos=iter->limit;
}
return iter->index=pos;
}
static UBool U_CALLCONV
stringIteratorHasNext(UCharIterator *iter) {
return iter->index<iter->limit;
}
static UBool U_CALLCONV
stringIteratorHasPrevious(UCharIterator *iter) {
return iter->index>iter->start;
}
static UChar32 U_CALLCONV
stringIteratorCurrent(UCharIterator *iter) {
if(iter->index<iter->limit) {
return ((const UChar *)(iter->context))[iter->index];
} else {
return U_SENTINEL;
}
}
static UChar32 U_CALLCONV
stringIteratorNext(UCharIterator *iter) {
if(iter->index<iter->limit) {
return ((const UChar *)(iter->context))[iter->index++];
} else {
return U_SENTINEL;
}
}
static UChar32 U_CALLCONV
stringIteratorPrevious(UCharIterator *iter) {
if(iter->index>iter->start) {
return ((const UChar *)(iter->context))[--iter->index];
} else {
return U_SENTINEL;
}
}
static uint32_t U_CALLCONV
stringIteratorGetState(const UCharIterator *iter) {
return (uint32_t)iter->index;
}
static void U_CALLCONV
stringIteratorSetState(UCharIterator *iter, uint32_t state, UErrorCode *pErrorCode) {
if(pErrorCode==NULL || U_FAILURE(*pErrorCode)) {
/* do nothing */
} else if(iter==NULL) {
*pErrorCode=U_ILLEGAL_ARGUMENT_ERROR;
} else if((int32_t)state<iter->start || iter->limit<(int32_t)state) {
*pErrorCode=U_INDEX_OUTOFBOUNDS_ERROR;
} else {
iter->index=(int32_t)state;
}
}
static const UCharIterator stringIterator={
0, 0, 0, 0, 0, 0,
stringIteratorGetIndex,
stringIteratorMove,
stringIteratorHasNext,
stringIteratorHasPrevious,
stringIteratorCurrent,
stringIteratorNext,
stringIteratorPrevious,
NULL,
stringIteratorGetState,
stringIteratorSetState
};
U_CAPI void U_EXPORT2
uiter_setString(UCharIterator *iter, const UChar *s, int32_t length) {
if(iter!=0) {
if(s!=0 && length>=-1) {
*iter=stringIterator;
iter->context=s;
if(length>=0) {
iter->length=length;
} else {
iter->length=u_strlen(s);
}
iter->limit=iter->length;
} else {
*iter=noopIterator;
}
}
}
/* UCharIterator implementation for UTF-16BE strings ------------------------ */
/*
* This is an implementation of a code unit (UChar) iterator
* for UTF-16BE strings, i.e., strings in byte-vectors where
* each UChar is stored as a big-endian pair of bytes.
*
* The UCharIterator.context field holds a pointer to the string.
* Everything works just like with a normal UChar iterator (uiter_setString),
* except that UChars are assembled from byte pairs.
*/
/* internal helper function */
static inline UChar32
utf16BEIteratorGet(UCharIterator *iter, int32_t index) {
const uint8_t *p=(const uint8_t *)iter->context;
return ((UChar)p[2*index]<<8)|(UChar)p[2*index+1];
}
static UChar32 U_CALLCONV
utf16BEIteratorCurrent(UCharIterator *iter) {
int32_t index;
if((index=iter->index)<iter->limit) {
return utf16BEIteratorGet(iter, index);
} else {
return U_SENTINEL;
}
}
static UChar32 U_CALLCONV
utf16BEIteratorNext(UCharIterator *iter) {
int32_t index;
if((index=iter->index)<iter->limit) {
iter->index=index+1;
return utf16BEIteratorGet(iter, index);
} else {
return U_SENTINEL;
}
}
static UChar32 U_CALLCONV
utf16BEIteratorPrevious(UCharIterator *iter) {
int32_t index;
if((index=iter->index)>iter->start) {
iter->index=--index;
return utf16BEIteratorGet(iter, index);
} else {
return U_SENTINEL;
}
}
static const UCharIterator utf16BEIterator={
0, 0, 0, 0, 0, 0,
stringIteratorGetIndex,
stringIteratorMove,
stringIteratorHasNext,
stringIteratorHasPrevious,
utf16BEIteratorCurrent,
utf16BEIteratorNext,
utf16BEIteratorPrevious,
NULL,
stringIteratorGetState,
stringIteratorSetState
};
/*
* Count the number of UChars in a UTF-16BE string before a terminating UChar NUL,
* i.e., before a pair of 0 bytes where the first 0 byte is at an even
* offset from s.
*/
static int32_t
utf16BE_strlen(const char *s) {
if(IS_POINTER_EVEN(s)) {
/*
* even-aligned, call u_strlen(s)
* we are probably on a little-endian machine, but searching for UChar NUL
* does not care about endianness
*/
return u_strlen((const UChar *)s);
} else {
/* odd-aligned, search for pair of 0 bytes */
const char *p=s;
while(!(*p==0 && p[1]==0)) {
p+=2;
}
return (int32_t)((p-s)/2);
}
}
U_CAPI void U_EXPORT2
uiter_setUTF16BE(UCharIterator *iter, const char *s, int32_t length) {
if(iter!=NULL) {
/* allow only even-length strings (the input length counts bytes) */
if(s!=NULL && (length==-1 || (length>=0 && IS_EVEN(length)))) {
/* length/=2, except that >>=1 also works for -1 (-1/2==0, -1>>1==-1) */
length>>=1;
if(U_IS_BIG_ENDIAN && IS_POINTER_EVEN(s)) {
/* big-endian machine and 2-aligned UTF-16BE string: use normal UChar iterator */
uiter_setString(iter, (const UChar *)s, length);
return;
}
*iter=utf16BEIterator;
iter->context=s;
if(length>=0) {
iter->length=length;
} else {
iter->length=utf16BE_strlen(s);
}
iter->limit=iter->length;
} else {
*iter=noopIterator;
}
}
}
/* UCharIterator wrapper around CharacterIterator --------------------------- */
/*
* This is wrapper code around a C++ CharacterIterator to
* look like a C UCharIterator.
*
* The UCharIterator.context field holds a pointer to the CharacterIterator.
*/
static int32_t U_CALLCONV
characterIteratorGetIndex(UCharIterator *iter, UCharIteratorOrigin origin) {
switch(origin) {
case UITER_ZERO:
return 0;
case UITER_START:
return ((CharacterIterator *)(iter->context))->startIndex();
case UITER_CURRENT:
return ((CharacterIterator *)(iter->context))->getIndex();
case UITER_LIMIT:
return ((CharacterIterator *)(iter->context))->endIndex();
case UITER_LENGTH:
return ((CharacterIterator *)(iter->context))->getLength();
default:
/* not a valid origin */
/* Should never get here! */
return -1;
}
}
static int32_t U_CALLCONV
characterIteratorMove(UCharIterator *iter, int32_t delta, UCharIteratorOrigin origin) {
switch(origin) {
case UITER_ZERO:
((CharacterIterator *)(iter->context))->setIndex(delta);
return ((CharacterIterator *)(iter->context))->getIndex();
case UITER_START:
case UITER_CURRENT:
case UITER_LIMIT:
return ((CharacterIterator *)(iter->context))->move(delta, (CharacterIterator::EOrigin)origin);
case UITER_LENGTH:
((CharacterIterator *)(iter->context))->setIndex(((CharacterIterator *)(iter->context))->getLength()+delta);
return ((CharacterIterator *)(iter->context))->getIndex();
default:
/* not a valid origin */
/* Should never get here! */
return -1;
}
}
static UBool U_CALLCONV
characterIteratorHasNext(UCharIterator *iter) {
return ((CharacterIterator *)(iter->context))->hasNext();
}
static UBool U_CALLCONV
characterIteratorHasPrevious(UCharIterator *iter) {
return ((CharacterIterator *)(iter->context))->hasPrevious();
}
static UChar32 U_CALLCONV
characterIteratorCurrent(UCharIterator *iter) {
UChar32 c;
c=((CharacterIterator *)(iter->context))->current();
if(c!=0xffff || ((CharacterIterator *)(iter->context))->hasNext()) {
return c;
} else {
return U_SENTINEL;
}
}
static UChar32 U_CALLCONV
characterIteratorNext(UCharIterator *iter) {
if(((CharacterIterator *)(iter->context))->hasNext()) {
return ((CharacterIterator *)(iter->context))->nextPostInc();
} else {
return U_SENTINEL;
}
}
static UChar32 U_CALLCONV
characterIteratorPrevious(UCharIterator *iter) {
if(((CharacterIterator *)(iter->context))->hasPrevious()) {
return ((CharacterIterator *)(iter->context))->previous();
} else {
return U_SENTINEL;
}
}
static uint32_t U_CALLCONV
characterIteratorGetState(const UCharIterator *iter) {
return ((CharacterIterator *)(iter->context))->getIndex();
}
static void U_CALLCONV
characterIteratorSetState(UCharIterator *iter, uint32_t state, UErrorCode *pErrorCode) {
if(pErrorCode==NULL || U_FAILURE(*pErrorCode)) {
/* do nothing */
} else if(iter==NULL || iter->context==NULL) {
*pErrorCode=U_ILLEGAL_ARGUMENT_ERROR;
} else if((int32_t)state<((CharacterIterator *)(iter->context))->startIndex() || ((CharacterIterator *)(iter->context))->endIndex()<(int32_t)state) {
*pErrorCode=U_INDEX_OUTOFBOUNDS_ERROR;
} else {
((CharacterIterator *)(iter->context))->setIndex((int32_t)state);
}
}
static const UCharIterator characterIteratorWrapper={
0, 0, 0, 0, 0, 0,
characterIteratorGetIndex,
characterIteratorMove,
characterIteratorHasNext,
characterIteratorHasPrevious,
characterIteratorCurrent,
characterIteratorNext,
characterIteratorPrevious,
NULL,
characterIteratorGetState,
characterIteratorSetState
};
U_CAPI void U_EXPORT2
uiter_setCharacterIterator(UCharIterator *iter, CharacterIterator *charIter) {
if(iter!=0) {
if(charIter!=0) {
*iter=characterIteratorWrapper;
iter->context=charIter;
} else {
*iter=noopIterator;
}
}
}
/* UCharIterator wrapper around Replaceable --------------------------------- */
/*
* This is an implementation of a code unit (UChar) iterator
* based on a Replaceable object.
*
* The UCharIterator.context field holds a pointer to the Replaceable.
* UCharIterator.length and UCharIterator.index hold Replaceable.length()
* and the iteration index.
*/
static UChar32 U_CALLCONV
replaceableIteratorCurrent(UCharIterator *iter) {
if(iter->index<iter->limit) {
return ((Replaceable *)(iter->context))->charAt(iter->index);
} else {
return U_SENTINEL;
}
}
static UChar32 U_CALLCONV
replaceableIteratorNext(UCharIterator *iter) {
if(iter->index<iter->limit) {
return ((Replaceable *)(iter->context))->charAt(iter->index++);
} else {
return U_SENTINEL;
}
}
static UChar32 U_CALLCONV
replaceableIteratorPrevious(UCharIterator *iter) {
if(iter->index>iter->start) {
return ((Replaceable *)(iter->context))->charAt(--iter->index);
} else {
return U_SENTINEL;
}
}
static const UCharIterator replaceableIterator={
0, 0, 0, 0, 0, 0,
stringIteratorGetIndex,
stringIteratorMove,
stringIteratorHasNext,
stringIteratorHasPrevious,
replaceableIteratorCurrent,
replaceableIteratorNext,
replaceableIteratorPrevious,
NULL,
stringIteratorGetState,
stringIteratorSetState
};
U_CAPI void U_EXPORT2
uiter_setReplaceable(UCharIterator *iter, const Replaceable *rep) {
if(iter!=0) {
if(rep!=0) {
*iter=replaceableIterator;
iter->context=rep;
iter->limit=iter->length=rep->length();
} else {
*iter=noopIterator;
}
}
}
/* UCharIterator implementation for UTF-8 strings --------------------------- */
/*
* Possible, probably necessary only for an implementation for arbitrary
* converters:
* Maintain a buffer (ring buffer?) for a piece of converted 16-bit text.
* This would require to turn reservedFn into a close function and
* to introduce a uiter_close(iter).
*/
#define UITER_CNV_CAPACITY 16
/*
* Minimal implementation:
* Maintain a single-UChar buffer for an additional surrogate.
* The caller must not modify start and limit because they are used internally.
*
* Use UCharIterator fields as follows:
* context pointer to UTF-8 string
* length UTF-16 length of the string; -1 until lazy evaluation
* start current UTF-8 index
* index current UTF-16 index; may be -1="unknown" after setState()
* limit UTF-8 length of the string
* reservedField supplementary code point
*
* Since UCharIterator delivers 16-bit code units, the iteration can be
* currently in the middle of the byte sequence for a supplementary code point.
* In this case, reservedField will contain that code point and start will
* point to after the corresponding byte sequence. The UTF-16 index will be
* one less than what it would otherwise be corresponding to the UTF-8 index.
* Otherwise, reservedField will be 0.
*/
/*
* Possible optimization for NUL-terminated UTF-8 and UTF-16 strings:
* Add implementations that do not call strlen() for iteration but check for NUL.
*/
static int32_t U_CALLCONV
utf8IteratorGetIndex(UCharIterator *iter, UCharIteratorOrigin origin) {
switch(origin) {
case UITER_ZERO:
case UITER_START:
return 0;
case UITER_CURRENT:
if(iter->index<0) {
/* the current UTF-16 index is unknown after setState(), count from the beginning */
const uint8_t *s;
UChar32 c;
int32_t i, limit, index;
s=(const uint8_t *)iter->context;
i=index=0;
limit=iter->start; /* count up to the UTF-8 index */
while(i<limit) {
U8_NEXT_OR_FFFD(s, i, limit, c);
index+=U16_LENGTH(c);
}
iter->start=i; /* just in case setState() did not get us to a code point boundary */
if(i==iter->limit) {
iter->length=index; /* in case it was <0 or wrong */
}
if(iter->reservedField!=0) {
--index; /* we are in the middle of a supplementary code point */
}
iter->index=index;
}
return iter->index;
case UITER_LIMIT:
case UITER_LENGTH:
if(iter->length<0) {
const uint8_t *s;
UChar32 c;
int32_t i, limit, length;
s=(const uint8_t *)iter->context;
if(iter->index<0) {
/*
* the current UTF-16 index is unknown after setState(),
* we must first count from the beginning to here
*/
i=length=0;
limit=iter->start;
/* count from the beginning to the current index */
while(i<limit) {
U8_NEXT_OR_FFFD(s, i, limit, c);
length+=U16_LENGTH(c);
}
/* assume i==limit==iter->start, set the UTF-16 index */
iter->start=i; /* just in case setState() did not get us to a code point boundary */
iter->index= iter->reservedField!=0 ? length-1 : length;
} else {
i=iter->start;
length=iter->index;
if(iter->reservedField!=0) {
++length;
}
}
/* count from the current index to the end */
limit=iter->limit;
while(i<limit) {
U8_NEXT_OR_FFFD(s, i, limit, c);
length+=U16_LENGTH(c);
}
iter->length=length;
}
return iter->length;
default:
/* not a valid origin */
/* Should never get here! */
return -1;
}
}
static int32_t U_CALLCONV
utf8IteratorMove(UCharIterator *iter, int32_t delta, UCharIteratorOrigin origin) {
const uint8_t *s;
UChar32 c;
int32_t pos; /* requested UTF-16 index */
int32_t i; /* UTF-8 index */
UBool havePos;
/* calculate the requested UTF-16 index */
switch(origin) {
case UITER_ZERO:
case UITER_START:
pos=delta;
havePos=TRUE;
/* iter->index<0 (unknown) is possible */
break;
case UITER_CURRENT:
if(iter->index>=0) {
pos=iter->index+delta;
havePos=TRUE;
} else {
/* the current UTF-16 index is unknown after setState(), use only delta */
pos=0;
havePos=FALSE;
}
break;
case UITER_LIMIT:
case UITER_LENGTH:
if(iter->length>=0) {
pos=iter->length+delta;
havePos=TRUE;
} else {
/* pin to the end, avoid counting the length */
iter->index=-1;
iter->start=iter->limit;
iter->reservedField=0;
if(delta>=0) {
return UITER_UNKNOWN_INDEX;
} else {
/* the current UTF-16 index is unknown, use only delta */
pos=0;
havePos=FALSE;
}
}
break;
default:
return -1; /* Error */
}
if(havePos) {
/* shortcuts: pinning to the edges of the string */
if(pos<=0) {
iter->index=iter->start=iter->reservedField=0;
return 0;
} else if(iter->length>=0 && pos>=iter->length) {
iter->index=iter->length;
iter->start=iter->limit;
iter->reservedField=0;
return iter->index;
}
/* minimize the number of U8_NEXT/PREV operations */
if(iter->index<0 || pos<iter->index/2) {
/* go forward from the start instead of backward from the current index */
iter->index=iter->start=iter->reservedField=0;
} else if(iter->length>=0 && (iter->length-pos)<(pos-iter->index)) {
/*
* if we have the UTF-16 index and length and the new position is
* closer to the end than the current index,
* then go backward from the end instead of forward from the current index
*/
iter->index=iter->length;
iter->start=iter->limit;
iter->reservedField=0;
}
delta=pos-iter->index;
if(delta==0) {
return iter->index; /* nothing to do */
}
} else {
/* move relative to unknown UTF-16 index */
if(delta==0) {
return UITER_UNKNOWN_INDEX; /* nothing to do */
} else if(-delta>=iter->start) {
/* moving backwards by more UChars than there are UTF-8 bytes, pin to 0 */
iter->index=iter->start=iter->reservedField=0;
return 0;
} else if(delta>=(iter->limit-iter->start)) {
/* moving forward by more UChars than the remaining UTF-8 bytes, pin to the end */
iter->index=iter->length; /* may or may not be <0 (unknown) */
iter->start=iter->limit;
iter->reservedField=0;
return iter->index>=0 ? iter->index : (int32_t)UITER_UNKNOWN_INDEX;
}
}
/* delta!=0 */
/* move towards the requested position, pin to the edges of the string */
s=(const uint8_t *)iter->context;
pos=iter->index; /* could be <0 (unknown) */
i=iter->start;
if(delta>0) {
/* go forward */
int32_t limit=iter->limit;
if(iter->reservedField!=0) {
iter->reservedField=0;
++pos;
--delta;
}
while(delta>0 && i<limit) {
U8_NEXT_OR_FFFD(s, i, limit, c);
if(c<=0xffff) {
++pos;
--delta;
} else if(delta>=2) {
pos+=2;
delta-=2;
} else /* delta==1 */ {
/* stop in the middle of a supplementary code point */
iter->reservedField=c;
++pos;
break; /* delta=0; */
}
}
if(i==limit) {
if(iter->length<0 && iter->index>=0) {
iter->length= iter->reservedField==0 ? pos : pos+1;
} else if(iter->index<0 && iter->length>=0) {
iter->index= iter->reservedField==0 ? iter->length : iter->length-1;
}
}
} else /* delta<0 */ {
/* go backward */
if(iter->reservedField!=0) {
iter->reservedField=0;
i-=4; /* we stayed behind the supplementary code point; go before it now */
--pos;
++delta;
}
while(delta<0 && i>0) {
U8_PREV_OR_FFFD(s, 0, i, c);
if(c<=0xffff) {
--pos;
++delta;
} else if(delta<=-2) {
pos-=2;
delta+=2;
} else /* delta==-1 */ {
/* stop in the middle of a supplementary code point */
i+=4; /* back to behind this supplementary code point for consistent state */
iter->reservedField=c;
--pos;
break; /* delta=0; */
}
}
}
iter->start=i;
if(iter->index>=0) {
return iter->index=pos;
} else {
/* we started with index<0 (unknown) so pos is bogus */
if(i<=1) {
return iter->index=i; /* reached the beginning */
} else {
/* we still don't know the UTF-16 index */
return UITER_UNKNOWN_INDEX;
}
}
}
static UBool U_CALLCONV
utf8IteratorHasNext(UCharIterator *iter) {
return iter->start<iter->limit || iter->reservedField!=0;
}
static UBool U_CALLCONV
utf8IteratorHasPrevious(UCharIterator *iter) {
return iter->start>0;
}
static UChar32 U_CALLCONV
utf8IteratorCurrent(UCharIterator *iter) {
if(iter->reservedField!=0) {
return U16_TRAIL(iter->reservedField);
} else if(iter->start<iter->limit) {
const uint8_t *s=(const uint8_t *)iter->context;
UChar32 c;
int32_t i=iter->start;
U8_NEXT_OR_FFFD(s, i, iter->limit, c);
if(c<=0xffff) {
return c;
} else {
return U16_LEAD(c);
}
} else {
return U_SENTINEL;
}
}
static UChar32 U_CALLCONV
utf8IteratorNext(UCharIterator *iter) {
int32_t index;
if(iter->reservedField!=0) {
UChar trail=U16_TRAIL(iter->reservedField);
iter->reservedField=0;
if((index=iter->index)>=0) {
iter->index=index+1;
}
return trail;
} else if(iter->start<iter->limit) {
const uint8_t *s=(const uint8_t *)iter->context;
UChar32 c;
U8_NEXT_OR_FFFD(s, iter->start, iter->limit, c);
if((index=iter->index)>=0) {
iter->index=++index;
if(iter->length<0 && iter->start==iter->limit) {
iter->length= c<=0xffff ? index : index+1;
}
} else if(iter->start==iter->limit && iter->length>=0) {
iter->index= c<=0xffff ? iter->length : iter->length-1;
}
if(c<=0xffff) {
return c;
} else {
iter->reservedField=c;
return U16_LEAD(c);
}
} else {
return U_SENTINEL;
}
}
static UChar32 U_CALLCONV
utf8IteratorPrevious(UCharIterator *iter) {
int32_t index;
if(iter->reservedField!=0) {
UChar lead=U16_LEAD(iter->reservedField);
iter->reservedField=0;
iter->start-=4; /* we stayed behind the supplementary code point; go before it now */
if((index=iter->index)>0) {
iter->index=index-1;
}
return lead;
} else if(iter->start>0) {
const uint8_t *s=(const uint8_t *)iter->context;
UChar32 c;
U8_PREV_OR_FFFD(s, 0, iter->start, c);
if((index=iter->index)>0) {
iter->index=index-1;
} else if(iter->start<=1) {
iter->index= c<=0xffff ? iter->start : iter->start+1;
}
if(c<=0xffff) {
return c;
} else {
iter->start+=4; /* back to behind this supplementary code point for consistent state */
iter->reservedField=c;
return U16_TRAIL(c);
}
} else {
return U_SENTINEL;
}
}
static uint32_t U_CALLCONV
utf8IteratorGetState(const UCharIterator *iter) {
uint32_t state=(uint32_t)(iter->start<<1);
if(iter->reservedField!=0) {
state|=1;
}
return state;
}
static void U_CALLCONV
utf8IteratorSetState(UCharIterator *iter,
uint32_t state,
UErrorCode *pErrorCode)
{
if(pErrorCode==NULL || U_FAILURE(*pErrorCode)) {
/* do nothing */
} else if(iter==NULL) {
*pErrorCode=U_ILLEGAL_ARGUMENT_ERROR;
} else if(state==utf8IteratorGetState(iter)) {
/* setting to the current state: no-op */
} else {
int32_t index=(int32_t)(state>>1); /* UTF-8 index */
state&=1; /* 1 if in surrogate pair, must be index>=4 */
if((state==0 ? index<0 : index<4) || iter->limit<index) {
*pErrorCode=U_INDEX_OUTOFBOUNDS_ERROR;
} else {
iter->start=index; /* restore UTF-8 byte index */
if(index<=1) {
iter->index=index;
} else {
iter->index=-1; /* unknown UTF-16 index */
}
if(state==0) {
iter->reservedField=0;
} else {
/* verified index>=4 above */
UChar32 c;
U8_PREV_OR_FFFD((const uint8_t *)iter->context, 0, index, c);
if(c<=0xffff) {
*pErrorCode=U_INDEX_OUTOFBOUNDS_ERROR;
} else {
iter->reservedField=c;
}
}
}
}
}
static const UCharIterator utf8Iterator={
0, 0, 0, 0, 0, 0,
utf8IteratorGetIndex,
utf8IteratorMove,
utf8IteratorHasNext,
utf8IteratorHasPrevious,
utf8IteratorCurrent,
utf8IteratorNext,
utf8IteratorPrevious,
NULL,
utf8IteratorGetState,
utf8IteratorSetState
};
U_CAPI void U_EXPORT2
uiter_setUTF8(UCharIterator *iter, const char *s, int32_t length) {
if(iter!=0) {
if(s!=0 && length>=-1) {
*iter=utf8Iterator;
iter->context=s;
if(length>=0) {
iter->limit=length;
} else {
iter->limit=(int32_t)uprv_strlen(s);
}
iter->length= iter->limit<=1 ? iter->limit : -1;
} else {
*iter=noopIterator;
}
}
}
/* Helper functions --------------------------------------------------------- */
U_CAPI UChar32 U_EXPORT2
uiter_current32(UCharIterator *iter) {
UChar32 c, c2;
c=iter->current(iter);
if(U16_IS_SURROGATE(c)) {
if(U16_IS_SURROGATE_LEAD(c)) {
/*
* go to the next code unit
* we know that we are not at the limit because c!=U_SENTINEL
*/
iter->move(iter, 1, UITER_CURRENT);
if(U16_IS_TRAIL(c2=iter->current(iter))) {
c=U16_GET_SUPPLEMENTARY(c, c2);
}
/* undo index movement */
iter->move(iter, -1, UITER_CURRENT);
} else {
if(U16_IS_LEAD(c2=iter->previous(iter))) {
c=U16_GET_SUPPLEMENTARY(c2, c);
}
if(c2>=0) {
/* undo index movement */
iter->move(iter, 1, UITER_CURRENT);
}
}
}
return c;
}
U_CAPI UChar32 U_EXPORT2
uiter_next32(UCharIterator *iter) {
UChar32 c, c2;
c=iter->next(iter);
if(U16_IS_LEAD(c)) {
if(U16_IS_TRAIL(c2=iter->next(iter))) {
c=U16_GET_SUPPLEMENTARY(c, c2);
} else if(c2>=0) {
/* unmatched first surrogate, undo index movement */
iter->move(iter, -1, UITER_CURRENT);
}
}
return c;
}
U_CAPI UChar32 U_EXPORT2
uiter_previous32(UCharIterator *iter) {
UChar32 c, c2;
c=iter->previous(iter);
if(U16_IS_TRAIL(c)) {
if(U16_IS_LEAD(c2=iter->previous(iter))) {
c=U16_GET_SUPPLEMENTARY(c2, c);
} else if(c2>=0) {
/* unmatched second surrogate, undo index movement */
iter->move(iter, 1, UITER_CURRENT);
}
}
return c;
}
U_CAPI uint32_t U_EXPORT2
uiter_getState(const UCharIterator *iter) {
if(iter==NULL || iter->getState==NULL) {
return UITER_NO_STATE;
} else {
return iter->getState(iter);
}
}
U_CAPI void U_EXPORT2
uiter_setState(UCharIterator *iter, uint32_t state, UErrorCode *pErrorCode) {
if(pErrorCode==NULL || U_FAILURE(*pErrorCode)) {
/* do nothing */
} else if(iter==NULL) {
*pErrorCode=U_ILLEGAL_ARGUMENT_ERROR;
} else if(iter->setState==NULL) {
*pErrorCode=U_UNSUPPORTED_ERROR;
} else {
iter->setState(iter, state, pErrorCode);
}
}
U_CDECL_END
| mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.