コード例 #1
0
ファイル: lineeq.cpp プロジェクト: assutech/isis3
void apply(Buffer &in, Buffer &out) {
  for(int sample = 0; sample < in.size(); sample ++) {
    out[sample] = in[sample] * cubeAverage[in.Band() - 1] / lineAverages[in.Band() - 1][in.Line() - 1];
  }
}
コード例 #2
0
void Container::init()
{
    if (m_bInit)
        return;

    QFrame *frm = new QFrame(this, "container");
    setCentralWidget(frm);

    connect(CorePlugin::m_plugin, SIGNAL(modeChanged()), this, SLOT(modeChanged()));

    QVBoxLayout *lay = new QVBoxLayout(frm);
    m_wnds = new QWidgetStack(frm);
    m_wnds->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding));
    lay->addWidget(m_wnds);

    m_tabSplitter = new Splitter(frm);
    m_tabSplitter->setSizePolicy(QSizePolicy(QSizePolicy::Expanding, QSizePolicy::Minimum));
    m_tabBar = new UserTabBar(m_tabSplitter);
    m_tabBar->setSizePolicy(QSizePolicy(QSizePolicy::Minimum, QSizePolicy::Expanding));
    m_tabBar->hide();

    m_bInit = true;

    m_status = new ContainerStatus(m_tabSplitter);
    lay->addWidget(m_tabSplitter);
    connect(m_tabBar, SIGNAL(selected(int)), this, SLOT(contactSelected(int)));
    connect(this, SIGNAL(toolBarPositionChanged(QToolBar*)), this, SLOT(toolbarChanged(QToolBar*)));
    connect(m_status, SIGNAL(sizeChanged(int)), this, SLOT(statusChanged(int)));
    m_accel = new QAccel(this);
    connect(m_accel, SIGNAL(activated(int)), this, SLOT(accelActivated(int)));
    setupAccel();
    showBar();

    for (list<UserWnd*>::iterator it = m_childs.begin(); it != m_childs.end(); ++it)
        addUserWnd((*it), false);
    m_childs.clear();

    string windows = getWindows();
    while (!windows.empty()){
        unsigned long id = strtoul(getToken(windows, ',').c_str(), NULL, 10);
        Contact *contact = getContacts()->contact(id);
        if (contact == NULL)
            continue;
        Buffer config;
        const char *cfg = getWndConfig(id);
        if (cfg && *cfg){
            config << "[Title]\n" << cfg;
            config.setWritePos(0);
            config.getSection();
        }
        addUserWnd(new UserWnd(id, &config, false, true), true);
    }

    if (m_tabBar->count() == 0)
        QTimer::singleShot(0, this, SLOT(close()));
    setWindows(NULL);
    clearWndConfig();
    m_tabBar->raiseTab(getActiveWindow());

    show();
}
コード例 #3
0
ファイル: documentMap.cpp プロジェクト: Loreia/UDL2
void DocumentMap::setSyntaxLiliting()
{
    Buffer *buf = _pScintillaEditView->getCurrentBuffer();
    _pScintillaEditView->defineDocType(buf->getLangType());
    _pScintillaEditView->showMargin(ScintillaEditView::_SC_MARGE_FOLDER, false);
}
コード例 #4
0
void AdlPrimitivesDemo::test( Buffer<int2>& buf, int size, Stopwatch& sw )
{
	Kernel* kernel = KernelManager::query( m_deviceData, "..\\..\\AdlDemos\\TestBed\\Demos\\AdlPrimitivesDemoKernel", "FillInt4Kernel" );
	Buffer<int4> constBuffer( m_deviceData, 1, BufferBase::BUFFER_CONST );


	int numGroups = (size+128*4-1)/(128*4);
	Buffer<u32> workBuffer0( m_deviceData, numGroups*(16) );
	Buffer<u32> workBuffer1( m_deviceData, numGroups*(16) );

	Buffer<int2> sortBuffer( m_deviceData, size );
	{
		int2* host = new int2[size];
		for(int i=0; i<size; i++)
		{
			host[i] = make_int2( getRandom(0, 0xf), i );
		}
		sortBuffer.write( host, size );
		DeviceUtils::waitForCompletion( m_deviceData );
		delete [] host;
	}

	int4 constData;
	{
		constData.x = size;
		constData.y = 0;
		constData.z = numGroups;
		constData.w = 0;
	}

	sw.start();

	int nThreads = size/4;
	{
		BufferInfo bInfo[] = { BufferInfo( &buf ), BufferInfo( &workBuffer0 ), BufferInfo( &workBuffer1 ) };
		Launcher launcher( m_deviceData, kernel );
		launcher.setBuffers( bInfo, sizeof(bInfo)/sizeof(Launcher::BufferInfo) );
		launcher.setConst( constBuffer, constData );
		launcher.launch1D( nThreads, 128 );
	}

	sw.split();

	{
		constData.w = 1;
		int nThreads = size/4;
		BufferInfo bInfo[] = { BufferInfo( &buf ), BufferInfo( &workBuffer0 ), BufferInfo( &workBuffer1 ) };
		Launcher launcher( m_deviceData, kernel );
		launcher.setBuffers( bInfo, sizeof(bInfo)/sizeof(Launcher::BufferInfo) );
		launcher.setConst( constBuffer, constData );
		launcher.launch1D( nThreads, 128 );
	}

	sw.split();

	{
		constData.w = 2;
		int nThreads = size/4;
		BufferInfo bInfo[] = { BufferInfo( &sortBuffer ), BufferInfo( &workBuffer0 ), BufferInfo( &workBuffer1 ) };
		Launcher launcher( m_deviceData, kernel );
		launcher.setBuffers( bInfo, sizeof(bInfo)/sizeof(Launcher::BufferInfo) );
		launcher.setConst( constBuffer, constData );
		launcher.launch1D( nThreads, 128 );
	}

	sw.stop();

	{
		int2* host = new int2[size];
		buf.read( host, size );
		DeviceUtils::waitForCompletion( m_deviceData );

		for(int i=0; i<128*4-1; i++)
		{
			ADLASSERT( host[i].x <= host[i+1].x );
		}

		delete [] host;
	}

	{
		float t[3];
		sw.getMs(t, 3);
		//	(byte * nElems)
		sprintf_s(m_txtBuffer[m_nTxtLines++], LINE_CAPACITY, "LoadStore: %3.2fGB/s (%3.2fns)", (4*8*2)*nThreads/t[0]/1000/1000, t[0]*1000.f);		
		sprintf_s(m_txtBuffer[m_nTxtLines++], LINE_CAPACITY, "GenHistog: %3.2fGB/s (%3.2fns)", (4*(8*2+2))*nThreads/t[1]/1000/1000, t[1]*1000.f);		
		sprintf_s(m_txtBuffer[m_nTxtLines++], LINE_CAPACITY, "FullSort: %3.2fGB/s (%3.2fns)", (4*(8*2+2))*nThreads/t[2]/1000/1000, t[2]*1000.f);		
	}
}
コード例 #5
0
bool SDBPRequestMessage::Write(Buffer& buffer)
{
    uint64_t*   it;

    switch (request->type)
    {
    /* Master query */
    case CLIENTREQUEST_GET_MASTER:
        buffer.Appendf("%c:%U",
                       request->type, request->commandID);
        return true;

    /* Get config state: databases, tables, shards, quora */
    case CLIENTREQUEST_GET_CONFIG_STATE:
        buffer.Appendf("%c:%U",
                       request->type, request->commandID);
        return true;

    /* Quorum management */
    case CLIENTREQUEST_CREATE_QUORUM:
        buffer.Appendf("%c:%U:%u",
                       request->type, request->commandID, request->nodes.GetLength());
        for (it = request->nodes.First(); it != NULL; it = request->nodes.Next(it))
            buffer.Appendf(":%U", *it);
        return true;
    case CLIENTREQUEST_DELETE_QUORUM:
        buffer.Appendf("%c:%U:%U",
                       request->type, request->commandID, request->quorumID);
        return true;
    case CLIENTREQUEST_ADD_NODE:
        buffer.Appendf("%c:%U:%U:%U",
                       request->type, request->commandID, request->quorumID, request->nodeID);
        return true;
    case CLIENTREQUEST_REMOVE_NODE:
        buffer.Appendf("%c:%U:%U:%U",
                       request->type, request->commandID, request->quorumID, request->nodeID);
        return true;
    case CLIENTREQUEST_ACTIVATE_NODE:
        buffer.Appendf("%c:%U:%U",
                       request->type, request->commandID, request->nodeID);
        return true;

    /* Database management */
    case CLIENTREQUEST_CREATE_DATABASE:
        buffer.Appendf("%c:%U:%#B",
                       request->type, request->commandID, &request->name);
        return true;
    case CLIENTREQUEST_RENAME_DATABASE:
        buffer.Appendf("%c:%U:%U:%#B",
                       request->type, request->commandID, request->databaseID,
                       &request->name);
        return true;
    case CLIENTREQUEST_DELETE_DATABASE:
        buffer.Appendf("%c:%U:%U",
                       request->type, request->commandID, request->databaseID);
        return true;
    case CLIENTREQUEST_SPLIT_SHARD:
        buffer.Appendf("%c:%U:%U:%#B",
                       request->type, request->commandID, request->shardID, &request->key);
        return true;
    case CLIENTREQUEST_MIGRATE_SHARD:
        buffer.Appendf("%c:%U:%U:%U",
                       request->type, request->commandID, request->shardID, request->quorumID);
        return true;

    /* Table management */
    case CLIENTREQUEST_CREATE_TABLE:
        buffer.Appendf("%c:%U:%U:%U:%#B",
                       request->type, request->commandID, request->databaseID,
                       request->quorumID, &request->name);
        return true;
    case CLIENTREQUEST_RENAME_TABLE:
        buffer.Appendf("%c:%U:%U:%#B",
                       request->type, request->commandID,
                       request->tableID, &request->name);
        return true;
    case CLIENTREQUEST_DELETE_TABLE:
        buffer.Appendf("%c:%U:%U",
                       request->type, request->commandID,
                       request->tableID);
        return true;
    case CLIENTREQUEST_TRUNCATE_TABLE:
        buffer.Appendf("%c:%U:%U",
                       request->type, request->commandID,
                       request->tableID);
        return true;

    /* Data operations */
    case CLIENTREQUEST_GET:
        buffer.Appendf("%c:%U:%U:%U:%#B",
                       request->type, request->commandID,
                       request->tableID, request->paxosID,
                       &request->key);
        return true;
    case CLIENTREQUEST_SET:
    case CLIENTREQUEST_SET_IF_NOT_EXISTS:
    case CLIENTREQUEST_GET_AND_SET:
        buffer.Appendf("%c:%U:%U:%#B:%#B",
                       request->type, request->commandID,
                       request->tableID, &request->key, &request->value);
        return true;
    case CLIENTREQUEST_TEST_AND_SET:
        buffer.Appendf("%c:%U:%U:%#B:%#B:%#B",
                       request->type, request->commandID,
                       request->tableID, &request->key, &request->test, &request->value);
        return true;
    case CLIENTREQUEST_ADD:
        buffer.Appendf("%c:%U:%U:%#B:%I",
                       request->type, request->commandID,
                       request->tableID, &request->key, request->number);
        return true;
    case CLIENTREQUEST_APPEND:
        buffer.Appendf("%c:%U:%U:%#B:%#B",
                       request->type, request->commandID,
                       request->tableID, &request->key, &request->value);
        return true;
    case CLIENTREQUEST_DELETE:
    case CLIENTREQUEST_REMOVE:
        buffer.Appendf("%c:%U:%U:%#B",
                       request->type, request->commandID,
                       request->tableID, &request->key);
        return true;

    case CLIENTREQUEST_TEST_AND_DELETE:
        buffer.Appendf("%c:%U:%U:%#B:%#B",
                       request->type, request->commandID,
                       request->tableID, &request->key, &request->test);
        return true;

    case CLIENTREQUEST_LIST_KEYS:
    case CLIENTREQUEST_LIST_KEYVALUES:
    case CLIENTREQUEST_COUNT:
        buffer.Appendf("%c:%U:%U:%#B:%#B:%#B:%U:%U",
                       request->type, request->commandID,
                       request->tableID, &request->key, &request->endKey, &request->prefix,
                       request->count, request->offset);
        return true;

    case CLIENTREQUEST_SUBMIT:
        buffer.Appendf("%c:%U", request->type, request->quorumID);
        return true;

    case CLIENTREQUEST_BULK_LOADING:
        buffer.Appendf("%c:%U", request->type, request->commandID);
        return true;

    default:
        return false;
    }
}
コード例 #6
0
ファイル: SNAC-SRV.cpp プロジェクト: transacid/CenterIM
  void SrvRequestFullWP::OutputBody(Buffer& b) const {
    b << (unsigned short)0x0001;

    Buffer::marker m1 = b.getAutoSizeShortMarker();

    b.setLittleEndian();
    Buffer::marker m2 = b.getAutoSizeShortMarker();

    b << m_my_uin;

    b << (unsigned short)2000	/* type 9808 */
      << (unsigned short)m_requestID /* low word of the request ID */
      << (unsigned short)0x0533;	/* subtype wp-full-request */
    b.PackUint16StringNull(m_firstname);
    b.PackUint16StringNull(m_lastname);
    b.PackUint16StringNull(m_nickname);
    b.PackUint16StringNull(m_email);
    b << (unsigned short)m_min_age;		// minimum age
    b << (unsigned short)m_max_age;		// maximum age
    b << (unsigned char)m_sex;			// sex
    b << (unsigned char)m_language;             // language
    b.PackUint16StringNull(m_city);             // city
    b.PackUint16StringNull(m_state);            // state
    b << (unsigned short)m_country;             // country
    b.PackUint16StringNull(m_company_name);	// company name
    b.PackUint16StringNull(m_department);	// department
    b.PackUint16StringNull(m_position);		// position
    b << (unsigned char)0x00;			// occupation
    b << (unsigned short)0x0000;		// past info category
    b.PackUint16StringNull("");			//           description
    b << (unsigned short)0x0000;		// interests category
    b.PackUint16StringNull("");			//           description
    b << (unsigned short)0x0000;		// affiliation/organization
    b.PackUint16StringNull("");			//           description
    b << (unsigned short)0x0000;		// homepage category
    b.PackUint16StringNull("");			//           description
    b << (unsigned char)(m_only_online ? 0x01 : 0x00);
                                                // only-online flag
    b.setAutoSizeMarker(m1);
    b.setAutoSizeMarker(m2);
  }
コード例 #7
0
ファイル: SNAC-SRV.cpp プロジェクト: transacid/CenterIM
  void SrvUpdateWorkInfo::OutputBody(Buffer& b) const {
        b << (unsigned short)0x0001;

        Buffer::marker m1 = b.getAutoSizeShortMarker();
    
        b.setLittleEndian();
        Buffer::marker m2 = b.getAutoSizeShortMarker();

        b << m_my_uin;

        b << (unsigned short)2000   /* type 9808 */
            << (unsigned short)m_requestID /* low word of the request ID */
            << (unsigned short)0x03f3; /* subtype */
        b.PackUint16StringNull(m_work_info.city);     	    // city
        b.PackUint16StringNull(m_work_info.state);     	    // state
        b << (unsigned short)0x0000
          << (unsigned short)0x0000;
        b.PackUint16StringNull(m_work_info.street);         // street
        b.PackUint16StringNull(m_work_info.zip);     	    // zip
        b << m_work_info.country;			    // country-code
        b.PackUint16StringNull(m_work_info.company_name);   // company: name
        b.PackUint16StringNull(m_work_info.company_dept);   // company: department
        b.PackUint16StringNull(m_work_info.company_position); // company: position
        b << (unsigned short)0x0000;
        b.PackUint16StringNull(m_work_info.company_web);    // company: homepage
        b.setAutoSizeMarker(m1);
        b.setAutoSizeMarker(m2);
    }
コード例 #8
0
ファイル: ArchiveBuffer.cpp プロジェクト: kyhhdm/TPlatform
int ArchiveBuffer::getCurPos()
{
    Buffer *curBuffer = m_buffers[m_buffers.size()-1];
    return curBuffer->cur()-curBuffer->begin() + m_bufferSize * (m_buffers.size()-1);
}
コード例 #9
0
ファイル: ArchiveBuffer.cpp プロジェクト: kyhhdm/TPlatform
//
// Read
//
char* ArchiveBuffer::readZString(char endChar)
{
    char *p, *pRet;
    Buffer *curBuffer = m_buffers[m_buffers.size()-1];
    pRet = NULL;

    //#TODO, need faster search algorithm 
    for(p = curBuffer->cur(); p< curBuffer->end(); ++p){
        if (*p == endChar) {

            //modify source data!!!
            *p = '\0'; //return ZString always

            pRet = curBuffer->cur();
            //if(p+1 <= curBuffer->end()){
                curBuffer->setCur(p + 1 - curBuffer->begin());
                return pRet;
            //}
        }
    }

    //record break, let's add new buffer
	if(0 == readInNewBuffer()){
		//reach eof
		return NULL;
	}

    curBuffer = m_buffers[m_buffers.size()-1];
    for(p = curBuffer->cur(); p< curBuffer->end(); ++p){
        if (*p == endChar) {

            //modify source data!!!
            *p = '\0'; //return ZString always

            pRet = curBuffer->cur();
            curBuffer->setCur(p + 1 - curBuffer->begin());
            return pRet;
        }
    }

    //not found in new buffer
    throw BufferError("ArchiveBuffer::readZString fail for record too large");
}
コード例 #10
0
	ShadowVolExample(const ExampleParams& params)
	 : shape_instr(make_shape.Instructions())
	 , shape_indices(make_shape.Indices())
	 , shape_vs(ShaderType::Vertex, ObjectDesc("Shape vertex"))
	 , depth_vs(ShaderType::Vertex, ObjectDesc("Depth vertex"))
	 , light_vs(ShaderType::Vertex, ObjectDesc("Light vertex"))
	 , depth_gs(ShaderType::Geometry, ObjectDesc("Depth geometry"))
	 , light_gs(ShaderType::Geometry, ObjectDesc("Light geometry"))
	 , shape_fs(ShaderType::Fragment, ObjectDesc("Shape fragment"))
	 , depth_fs(ShaderType::Fragment, ObjectDesc("Depthfragment"))
	 , light_fs(ShaderType::Fragment, ObjectDesc("Light fragment"))
	 , shape_prog(ObjectDesc("Shape"))
	 , depth_prog(ObjectDesc("Depth"))
	 , light_prog(ObjectDesc("Light"))
	 , tex_side(128)
	 , sample_count(params.HighQuality()?1024:128)
	{
		shape_vs.Source(
			"#version 330\n"
			"uniform mat4 ProjectionMatrix, CameraMatrix, ModelMatrix;"
			"in vec4 Position;"
			"in vec3 Normal;"
			"in vec2 TexCoord;"
			"out vec3 vertNormal;"
			"out vec3 vertLightDir;"
			"out vec3 vertLightRefl;"
			"out vec3 vertViewDir;"
			"out vec3 vertViewRefl;"
			"uniform vec3 LightPos;"
			"void main(void)"
			"{"
			"	gl_Position = ModelMatrix * Position;"
			"	vertNormal = mat3(ModelMatrix)*Normal;"
			"	vertLightDir = LightPos - gl_Position.xyz;"
			"	vertLightRefl = reflect("
			"		-normalize(vertLightDir),"
			"		normalize(vertNormal)"
			"	);"
			"	vertViewDir = (vec4(0.0, 0.0, 1.0, 1.0)* CameraMatrix).xyz;"
			"	vertViewRefl = reflect("
			"		normalize(vertViewDir),"
			"		normalize(vertNormal)"
			"	);"
			"	gl_Position = ProjectionMatrix * CameraMatrix * gl_Position;"
			"}"
		);
		shape_vs.Compile();

		shape_fs.Source(
			"#version 330\n"
			"in vec3 vertNormal;"
			"in vec3 vertLightDir;"
			"in vec3 vertLightRefl;"
			"in vec3 vertViewDir;"
			"in vec3 vertViewRefl;"
			"out vec4 fragColor;"
			"void main(void)"
			"{"
			"	float l = length(vertLightDir);"
			"	float d = dot("
			"		normalize(vertNormal), "
			"		normalize(vertLightDir)"
			"	) / l;"
			"	float s = dot("
			"		normalize(vertLightRefl),"
			"		normalize(vertViewDir)"
			"	);"
			"	vec3 ambi = vec3(0.6, 0.3, 0.5);"
			"	vec3 diff = vec3(0.9, 0.7, 0.8);"
			"	vec3 spec = vec3(1.0, 0.9, 0.95);"
			"	fragColor = vec4("
			"		ambi * 0.3 + "
			"		diff * 0.7 * max(d, 0.0) + "
			"		spec * pow(max(s, 0.0), 64), "
			"		1.0"
			"	);"
			"}"
		);
		shape_fs.Compile();

		shape_prog.AttachShader(shape_vs);
		shape_prog.AttachShader(shape_fs);
		shape_prog.Link();

		depth_vs.Source(
			"#version 330\n"
			"uniform mat4 ModelMatrix;"
			"uniform vec3 LightPos;"
			"in vec4 Position;"
			"void main(void)"
			"{"
			"	gl_Position = "
			"		mat4("
			"			1.0, 0.0, 0.0, -LightPos.x,"
			"			0.0, 1.0, 0.0, -LightPos.y,"
			"			0.0, 0.0, 1.0, -LightPos.z,"
			"			0.0, 0.0, 0.0,  1.0"
			"		)*"
			"		ModelMatrix *"
			"		mat4("
			"			10.0,  0.0,  0.0,  0.0,"
			"			 0.0, 10.0,  0.0,  0.0,"
			"			 0.0,  0.0, 10.0,  0.0,"
			"			 0.0,  0.0,  0.0,  1.0 "
			"		)*"
			"		Position;"
			"}"
		);
		depth_vs.Compile();

		depth_gs.Source(
			"#version 330\n"
			"layout(triangles) in;"
			"layout(triangle_strip, max_vertices = 18) out;"

			"uniform mat4 ProjectionMatrix;"

			"const mat4 CubeFaceMatrix[6] = mat4[6]("
			"	mat4("
			"		 0.0,  0.0, -1.0,  0.0,"
			"		 0.0, -1.0,  0.0,  0.0,"
			"		-1.0,  0.0,  0.0,  0.0,"
			"		 0.0,  0.0,  0.0,  1.0 "
			"	), mat4("
			"		 0.0,  0.0,  1.0,  0.0,"
			"		 0.0, -1.0,  0.0,  0.0,"
			"		 1.0,  0.0,  0.0,  0.0,"
			"		 0.0,  0.0,  0.0,  1.0 "
			"	), mat4("
			"		 1.0,  0.0,  0.0,  0.0,"
			"		 0.0,  0.0, -1.0,  0.0,"
			"		 0.0,  1.0,  0.0,  0.0,"
			"		 0.0,  0.0,  0.0,  1.0 "
			"	), mat4("
			"		 1.0,  0.0,  0.0,  0.0,"
			"		 0.0,  0.0,  1.0,  0.0,"
			"		 0.0, -1.0,  0.0,  0.0,"
			"		 0.0,  0.0,  0.0,  1.0 "
			"	), mat4("
			"		 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 "
			"	), mat4("
			"		-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 "
			"	)"
			");"

			"void main(void)"
			"{"
			"	for(gl_Layer=0; gl_Layer!=6; ++gl_Layer)"
			"	{"
			"		for(int i=0; i!=3; ++i)"
			"		{"
			"			gl_Position = "
			"				ProjectionMatrix *"
			"				CubeFaceMatrix[gl_Layer]*"
			"				gl_in[i].gl_Position;"
			"			EmitVertex();"
			"		}"
			"		EndPrimitive();"
			"	}"
			"}"
		);
		depth_gs.Compile();

		depth_fs.Source(
			"#version 330\n"
			"void main(void)"
			"{"
			"	gl_FragDepth = gl_FragCoord.z;"
			"}"
		);
		depth_fs.Compile();

		depth_prog.AttachShader(depth_vs);
		depth_prog.AttachShader(depth_gs);
		depth_prog.AttachShader(depth_fs);
		depth_prog.Link();
		depth_prog.Use();

		Uniform<Mat4f>(depth_prog, "ProjectionMatrix").Set(
			CamMatrixf::PerspectiveX(
				RightAngles(1.0),
				1.0,
				0.1,
				10.0
			)
		);

		// bind the VAO for the shape
		shape.Bind();

		shape_positions.Bind(Buffer::Target::Array);
		{
			std::vector<GLfloat> data;
			GLuint n_per_vertex = make_shape.Positions(data);
			Buffer::Data(Buffer::Target::Array, data);

			VertexAttribSlot location;
			if(VertexAttribArray::QueryCommonLocation(
				"Position",
				location,
				shape_prog,
				depth_prog
			))
			{
				VertexAttribArray shape_attr(location);
				shape_attr.Setup(n_per_vertex, DataType::Float);
				shape_attr.Enable();
			}
			else assert(!"Inconsistent 'Position' location");
		}

		shape_normals.Bind(Buffer::Target::Array);
		{
			std::vector<GLfloat> data;
			GLuint n_per_vertex = make_shape.Normals(data);
			Buffer::Data(Buffer::Target::Array, data);

			shape_prog.Use();
			VertexAttribArray attr(shape_prog, "Normal");
			attr.Setup(n_per_vertex, DataType::Float);
			attr.Enable();
		}

		light_vs.Source(
			"#version 330\n"
			"in vec3 Position;"
			"out float vertZOffs;"
			"uniform vec3 LightPos;"
			"uniform int SampleCount;"
			"void main(void)"
			"{"
			"	float hp = (SampleCount-1) * 0.5;"
			"	vertZOffs = (gl_InstanceID - hp)/hp;"
			"	gl_Position = vec4(Position + LightPos, 1.0);"
			"}"
		);
		light_vs.Compile();

		light_gs.Source(
			"#version 330\n"
			"layout(points) in;"
			"layout(triangle_strip, max_vertices = 4) out;"
			"in float vertZOffs[];"
			"out vec4 geomPosition;"
			"uniform mat4 CameraMatrix, ProjectionMatrix;"
			"uniform vec3 ViewX, ViewY, ViewZ;"
			"uniform float LightVolSize;"
			"void main(void)"
			"{"
			"	float zo = vertZOffs[0];"
			"	float yo[2] = float[2](-1.0, 1.0);"
			"	float xo[2] = float[2](-1.0, 1.0);"
			"	for(int j=0;j!=2;++j)"
			"	for(int i=0;i!=2;++i)"
			"	{"
			"		geomPosition = vec4("
			"			gl_in[0].gl_Position.xyz+"
			"			ViewX * xo[i] * LightVolSize+"
			"			ViewY * yo[j] * LightVolSize+"
			"			ViewZ * zo    * LightVolSize,"
			"			1.0"
			"		);"
			"		gl_Position = "
			"			ProjectionMatrix *"
			"			CameraMatrix *"
			"			geomPosition;"
			"		EmitVertex();"
			"	}"
			"	EndPrimitive();"
			"}"
		);
		light_gs.Compile();

		light_fs.Source(
			"#version 330\n"
			"in vec4 geomPosition;"
			"out vec4 fragColor;"
			"uniform samplerCubeShadow ShadowMap;"
			"uniform int SampleCount;"
			"uniform vec3 LightPos;"
			"void main(void)"
			"{"
			"	vec3 LightDir = geomPosition.xyz - LightPos;"
			"	vec4 ShadowCoord = vec4("
			"		normalize(LightDir),"
			"		length(LightDir)"
			"	);"
			"	float s = texture(ShadowMap, ShadowCoord);"
			"	float alpha = s / (SampleCount * pow(length(LightDir), 2));"
			"	fragColor = vec4(1.0, 1.0, 1.0, alpha);"
			"}"
		);
		light_fs.Compile();

		light_prog.AttachShader(light_vs);
		light_prog.AttachShader(light_gs);
		light_prog.AttachShader(light_fs);
		light_prog.Link();
		light_prog.Use();

		// bind the VAO for the light volume
		light.Bind();

		// bind the VBO for the light volume plane positions
		light_positions.Bind(Buffer::Target::Array);
		{
			GLfloat position[3] = {0.0, 0.0, 0.0};
			Buffer::Data(Buffer::Target::Array, 3, position);
			VertexAttribArray attr(light_prog, "Position");
			attr.Setup(3, DataType::Float);
			attr.Enable();
		}

		Uniform<GLint>(light_prog, "SampleCount").Set(sample_count);
		Uniform<GLfloat>(light_prog, "LightVolSize").Set(4);
		UniformSampler(light_prog, "ShadowMap").Set(0);

		// Setup the texture and the offscreen FBO
		Texture::Active(0);
		{
			auto bound_tex = Bind(depth_tex, Texture::Target::CubeMap);
			bound_tex.MinFilter(TextureMinFilter::Linear);
			bound_tex.MagFilter(TextureMagFilter::Linear);
			bound_tex.WrapS(TextureWrap::ClampToEdge);
			bound_tex.WrapT(TextureWrap::ClampToEdge);
			bound_tex.WrapR(TextureWrap::ClampToEdge);
			bound_tex.CompareFunc(CompareFunction::LEqual);
			bound_tex.CompareMode(
				TextureCompareMode::CompareRefToTexture
			);

			for(int i=0; i!=6; ++i)
			{
				Texture::Image2D(
					Texture::CubeMapFace(i),
					0,
					PixelDataInternalFormat::DepthComponent,
					tex_side, tex_side,
					0,
					PixelDataFormat::DepthComponent,
					PixelDataType::Float,
					nullptr
				);
			}

			auto bound_fbo = Bind(
				depth_fbo,
				Framebuffer::Target::Draw
			);
			bound_fbo.AttachTexture(
				FramebufferAttachment::Depth,
				depth_tex,
				0
			);
		}
		//
		gl.ClearColor(0.2f, 0.05f, 0.1f, 0.0f);
		gl.ClearDepth(1.0f);
		gl.Enable(Capability::DepthTest);

		gl.Enable(Capability::CullFace);
		gl.FrontFace(make_shape.FaceWinding());
		gl.CullFace(Face::Back);

		gl.BlendFunc(BlendFunction::SrcAlpha, BlendFunction::One);
	}
コード例 #11
0
ファイル: ArchiveBuffer.cpp プロジェクト: kyhhdm/TPlatform
void ArchiveBuffer::commitAppendRecord()
{
    Buffer *curBuffer = m_buffers[m_buffers.size()-1];
    curBuffer->setRecordEnd(); 
}
コード例 #12
0
void
CSettingsView::SaveSettings()
{
   iContainer->StoreSettingsL();

   SimpleParameterMess* message;
   GeneralParameterMess* gen_mess;

   message = new (ELeave) SimpleParameterMess( GuiProtEnums::paramSoundVolume, (uint8)(iData->iVolume*10) );
   SendGuiProtMessage(message);

   message = new (ELeave) SimpleParameterMess( GuiProtEnums::paramUseSpeaker, (bool)iData->iUseSpeaker );
   SendGuiProtMessage(message);

   isab::GuiProtEnums::TurnSoundsLevel soundsLevel = isab::GuiProtEnums::turnsound_mute;
   if (iData->iOldVehicle == iData->iVehicle) {
      // User did not change this setting.'
      soundsLevel = iData->iTurnSoundsLevel;
   } else {
      // User did change transportation mode
      if (iData->iVehicle == isab::NavServerComEnums::pedestrian) {
         // If user changed to pedestrian, mute
         soundsLevel = isab::GuiProtEnums::turnsound_mute;
      } else {
         // User changed to something else than pedestrian, normal
         soundsLevel = isab::GuiProtEnums::turnsound_normal;
      }
   }
   iData->iOldVehicle = iData->iVehicle;
   //message = new (ELeave) SimpleParameterMess( GuiProtEnums::paramTurnSoundsLevel, (uint8)iData->iTurnSoundsLevel );
   message = new (ELeave) SimpleParameterMess( GuiProtEnums::paramTurnSoundsLevel, (uint8)soundsLevel );
   SendGuiProtMessage(message);

   message = new (ELeave) SimpleParameterMess( GuiProtEnums::paramAutoReroute, (bool)iData->iAutoReroute );
   SendGuiProtMessage(message);

   message = new (ELeave) SimpleParameterMess( GuiProtEnums::paramTransportationType, (uint8)iData->iVehicle );
   SendGuiProtMessage(message);

   message = new (ELeave) SimpleParameterMess( GuiProtEnums::paramDistanceMode, (uint8)iData->iDistanceMode );
   SendGuiProtMessage(message);

   gen_mess = new (ELeave) GeneralParameterMess( GuiProtEnums::paramTollRoads, (int32)iData->iTollRoads );
   SendGuiProtMessage(gen_mess);

   gen_mess = new (ELeave) GeneralParameterMess( GuiProtEnums::paramHighways, (int32)iData->iHighways );
   SendGuiProtMessage(gen_mess);

   gen_mess = new (ELeave) GeneralParameterMess( GuiProtEnums::paramTimeDist, (int32)iData->iTimeDist );
   SendGuiProtMessage(gen_mess);

   gen_mess = new (ELeave) GeneralParameterMess( GuiProtEnums::paramAutoTracking, (int32)iData->iAutoTrackingOn );
   SendGuiProtMessage(gen_mess);

   message = new (ELeave) SimpleParameterMess( GuiProtEnums::paramStoreSMSDestInMyDest, (uint8)iData->iSaveSMSDest );
   SendGuiProtMessage(message);

   message = new (ELeave) SimpleParameterMess( GuiProtEnums::paramAutomaticRouteOnSMSDest, (bool)iData->iAutoSMSRoute );
   SendGuiProtMessage(message);

   message = new (ELeave) SimpleParameterMess( GuiProtEnums::paramKeepSMSDestInInbox, (uint8)iData->iKeepSMSDest );
   SendGuiProtMessage(message);

   message = new (ELeave) SimpleParameterMess( GuiProtEnums::userDirectionMode, (uint8)iData->iDirectionType );
   SendGuiProtMessage(message);

   message = new (ELeave) SimpleParameterMess( GuiProtEnums::userVicinityFeedMode, (uint8)iData->iFeedOutputFormat );
   SendGuiProtMessage(message);

   message = new (ELeave) SimpleParameterMess( GuiProtEnums::paramFeedWaitPeriod, (uint8)iData->iVicinityFeedRate );
   SendGuiProtMessage(message);
   
   message = new (ELeave) SimpleParameterMess( GuiProtEnums::paramLockedNavWaitPeriod, (uint8)iData->iLockedNavRate );
   SendGuiProtMessage(message);

   message = new (ELeave) SimpleParameterMess( GuiProtEnums::paramGpsMinWalkingSpeed, (uint8)iData->iWalkingSpeedCutOff );
   SendGuiProtMessage(message);

   message = new (ELeave) SimpleParameterMess( GuiProtEnums::paramVicinityListUpdatePeriod, (uint8)iData->iVicinityListPeriod );
   SendGuiProtMessage(message);
   
   message = new (ELeave) SimpleParameterMess(
         GuiProtEnums::paramBacklightStrategy,
         (uint8)iData->iBacklightStrategy );
   SendGuiProtMessage(message);

   TInt updTime = iData->iRouteTrafficInfoUpdTime;
   if (!iData->iRouteTrafficInfoEnabled) {
      // Let nav2 know that user has switched this option off.
      // Set the second highest bit.
      updTime |= 0x40000000;
   }
   gen_mess = new (ELeave) GeneralParameterMess(GuiProtEnums::userTrafficUpdatePeriod,
                                                (int32)updTime);
   SendGuiProtMessage(gen_mess);

   if (iData->iOldIAP != iData->iIAP) {
      //User selected new iap so delete iap.txt file.
      iWayFinderUI->DeleteIapTxt();

      message = new (ELeave) SimpleParameterMess(
            GuiProtEnums::paramSelectedAccessPointId,
            (uint32)iData->iIAP );
      SendGuiProtMessage(message);

      message = new (ELeave) SimpleParameterMess(
            GuiProtEnums::paramSelectedAccessPointId2,
            (uint32)iData->iIAP );
      SendGuiProtMessage(message);
   }

   gen_mess = 
      new (ELeave) GeneralParameterMess(GuiProtEnums::paramLinkLayerKeepAlive,
            (int32)iData->iLinkLayerKeepAlive);
   SendGuiProtMessage(gen_mess);

   char* serverPortStr;

   if (iData->iServer.Compare(iData->iServerOld)) {
      serverPortStr = WFTextUtil::newTDesDupL(iData->iServer);
      message = new (ELeave) SimpleParameterMess( GuiProtEnums::paramServerNameAndPort, serverPortStr );
      SendGuiProtMessage(message);
   }

   serverPortStr = WFTextUtil::newTDesDupL(iData->iWebUsername);
   message = new (ELeave) SimpleParameterMess( GuiProtEnums::paramWebUsername,
         serverPortStr );
   SendGuiProtMessage(message);

   {
      HBufC* buf = CCoeEnv::Static()->AllocReadResourceLC(R_WAYFINDER_SET_PASSWORD_TEXT );
      if ((! iWayFinderUI->IsTrialVersion()) && ( iData->iWebPassword.Length() > 0 ) && iData->iWebPassword.Compare(*buf)) {
         serverPortStr = WFTextUtil::newTDesDupL(iData->iWebPassword);
         message = new (ELeave) SimpleParameterMess(
               GuiProtEnums::paramWebPassword,
               serverPortStr );
         SendGuiProtMessage(message);
      } else {
         /* Web password string was "Set Password"... */
      }
      CleanupStack::PopAndDestroy(buf);
   }

   TBuf<KBuf256Length> serverPort;

   if (iData->iUsername.Compare(iData->iOldUsername)) {
      serverPortStr = WFTextUtil::newTDesDupL(iData->iUsername);
      message = new (ELeave) SimpleParameterMess( GuiProtEnums::paramUsername,
            serverPortStr );
      SendGuiProtMessage(message);
   }

   if (iData->iPassword.Compare(iData->iOldPassword)) {
      serverPortStr = WFTextUtil::newTDesDupL(iData->iPassword);
      message = new (ELeave) SimpleParameterMess( GuiProtEnums::paramPassword,
            serverPortStr );
      SendGuiProtMessage(message);
   }

   {
      // Need to set map type directly, since the return message
      // is slower than the view change when settings are called
      // from the map view.
      // WARNING! The vector map blob is generated in the make_seed.pl file!

      int32 *vectorMapSettings = new int32[vector_map_settings_num];
      LOGNEW(vectorMapSettings, int32[vector_map_settings_num]);
      vectorMapSettings[vmap_set_version_pos] = VECTOR_MAP_SETTINGS_VERSION;
      vectorMapSettings[vmap_set_cache_pos] = iData->iMapCacheSize;
      vectorMapSettings[vmap_set_maptype_pos] = iData->iMapType;
      vectorMapSettings[vmap_set_orientation_pos] = iData->iMapTrackingOrientation;
      vectorMapSettings[vmap_set_favorite_show_pos] = iData->iFavoriteShow;
      vectorMapSettings[vmap_set_guide_mode_pos] = iData->iPreferredGuideMode;
      vectorMapSettings[vmap_set_gui_mode_pos] = 0;

      gen_mess = new (ELeave) GeneralParameterMess(
               GuiProtEnums::paramVectorMapSettings,
               vectorMapSettings,
               vector_map_settings_num );

      SendGuiProtMessage(gen_mess);
   }

   gen_mess = new (ELeave) GeneralParameterMess( GuiProtEnums::paramGPSAutoConnect, (int32)iData->iGPSAutoConnect );
   SendGuiProtMessage(gen_mess);

   if(iData->iGpsSetting == 1/*EGpsNewGps*/){
      delete iData->iGpsName; 
      iData->iGpsName = NULL;
      iData->iGpsName = CEikonEnv::Static()->AllocReadResourceL(R_WAYFINDER_SETTINGSITEM_GPS_NONE);
      iWayFinderUI->ReConnectGps();
      iData->iGpsSetting = 0;
   }

   if ( iData->iTrackingLevel != iData->iOldTrackingLevel ) {
      gen_mess = new (ELeave) GeneralParameterMess( 
         GuiProtEnums::paramTrackingLevel, 
         (int32)iData->iTrackingLevel );
      SendGuiProtMessage(gen_mess);
   }

   if ( iData->iTrackingPIN.Compare( iData->iOldTrackingPIN ) ) {
      // Hack to get at least four numbers in PIN
      serverPort.Copy( iData->iTrackingPIN );
      uint32 addSize = serverPort.Length() < 4 ? 
         4 - serverPort.Length() : 0;
      TBuf<KBuf256Length> zeroBuf;
      zeroBuf.Copy( _L( "0" ) );
      for ( uint32 i = 0 ; i < addSize ; ++i ) {
         serverPort.Insert( 0, zeroBuf );
      }
      // All zero then clear PIN
      bool allZero = true;
      for ( TInt j = 0 ; j < serverPort.Length() && allZero ; ++j ) {
         if ( serverPort[ j ] != '0' ) {
            allZero = false;
         }
      }
      serverPortStr = WFTextUtil::newTDesDupL( serverPort );
      char** s = new(ELeave) char*[ 2 ];
      s[ 0 ] = serverPortStr;
      s[ 1 ] = WFTextUtil::strdupL( "" ); // Comment
//      TRACE_DBG( "New PIN %s", s[ 0 ] );

      if ( iData->m_trackPINList == NULL ) {
         iData->m_trackPINList = new(ELeave) TrackPINList();
      }
      TrackPINList::iterator it = iData->m_trackPINList->begin();
      while ( it != iData->m_trackPINList->end() ) {
//         TRACE_DBG( "Have PIN list size %d", iData->m_trackPINList->size() );
         if ( (*it)->getID() == 0 ) {
            TrackPINList::iterator next = it;
            ++next;
            iData->m_trackPINList->removePIN( (*it) );
            it = next;
         } else {
            iData->m_trackPINList->deletePIN( (*it) );
            ++it;
         }
      }
      if ( !allZero ) {
         iData->m_trackPINList->addPIN( s[ 0 ], s[ 1 ] );
      }

      delete [] s[ 0 ];
      delete [] s[ 1 ];
      delete [] s;

      Buffer buff;
      iData->m_trackPINList->packInto( &buff );
      gen_mess = new (ELeave) GeneralParameterMess( 
         GuiProtEnums::paramTrackingPIN, 
         (uint8*)buff.accessRawData( 0 ), buff.getLength() );
//      TRACE_DBG( "Sending lits size %"PRId32, buff.getLength() );
      buff.releaseData();

      SendGuiProtMessage(gen_mess);
   }

   /** Save Maplib Map layers */
   if ( iData->iTrafficOldEnabled != iData->iTrafficEnabled ||
        iData->iTrafficOldTime != iData->iTrafficTime) {
      /* Setting changed. */
      iWayFinderUI->SaveMapLayerSettings();
   }

   if (iData->iShowCategories) {
      /* Save the disabled poi categories in parameter file. */

      /* Buffer will resize itself if larger than this. */
      Buffer *buf = new Buffer(256);
      LOGNEW(buf, Buffer);

      /* Version number. */
      buf->writeNextUnaligned16bit(VECTOR_MAP_POI_CATEGORY_VERSION);

      for (int32 i = 0; i < iData->iCheckboxArray.Count(); i++) {
         buf->writeNextCharString(iData->iCheckboxTextArray[i]);
         buf->writeNextUnaligned32bit(iData->iCheckboxIdArray[i]);
         buf->writeNext8bit(iData->iCheckboxArray[i]);
      }

      /* Cast necessary to lose warning about const. */
      uint8 *rawData = (uint8 *)buf->accessRawData();
      /* Save the buffer in Nav2. */
      gen_mess = new (ELeave) GeneralParameterMess(
               GuiProtEnums::paramPoiCategories,
               rawData,
               buf->getLength() );

      SendGuiProtMessage(gen_mess);
   }


   /* Save language code in special file. */
   iWayFinderUI->SaveLanguageCode(iData->iLanguage);

   if (iData->iMapType != iData->iOldMapType) {
      WFDialog::ShowScrollingDialogL(iCoeEnv,
            R_WAYFINDER_SETTINGS_CHANGED_HEADER, 
            R_WAYFINDER_SETTINGS_CHANGED_TEXT,
            EFalse);
      iShutdownNeeded = ETrue;
   } else if (iData->iLanguage != iData->iOldLanguage) {
      /* Language changed. */
      WFDialog::ShowScrollingDialogL(iCoeEnv,
            R_WAYFINDER_LANGUAGE_CHANGED_HEADER, 
            R_WAYFINDER_LANGUAGE_CHANGED_TEXT,
            EFalse);
   }

}
コード例 #13
0
Boolean BasicAuthenticationHandler::authenticate(
    const String& authHeader,
    AuthenticationInfo* authInfo)
{
    PEG_METHOD_ENTER(
        TRC_AUTHENTICATION, "BasicAuthenticationHandler::authenticate()");

    Boolean authenticated = false;

    //
    // copy userPass string to char array for decoding
    //
    Buffer userPassArray;

    Uint32 length = authHeader.size();

    userPassArray.reserveCapacity( length );
    userPassArray.clear();

    for( Uint32 i = 0; i < length; i++ )
    {
        userPassArray.append( static_cast<char>(authHeader[i]) );
    }

    //
    // base64 decode the userPass array
    //
    Buffer  decodedArray;

    decodedArray = Base64::decode( userPassArray );

    String decodedStr =
        String( (const char*)decodedArray.getData(), decodedArray.size() );

    Uint32 pos = decodedStr.find(':');

    if (pos == PEG_NOT_FOUND)
    {
        PEG_METHOD_EXIT();
        return (authenticated);
    }

    String userName = decodedStr.subString(0, pos);

    String password = decodedStr.subString(pos + 1);

    Uint32 userNameLen = userName.size();
    if (userNameLen > PEGASUS_MAX_USER_NAME_LEN)
    {
        String badUserName = userName.subString(0, PEGASUS_MAX_USER_NAME_LEN);

        Logger::put_l(Logger::STANDARD_LOG, System::CIMSERVER,
            Logger::INFORMATION,
            MessageLoaderParms(
                BASIC_AUTHENTICATION_FAILED_KEY,
                BASIC_AUTHENTICATION_FAILED, badUserName,
                authInfo->getIpAddress()));
        PEG_METHOD_EXIT();
        return false;
    }

    // PASE APIs require user profile to be uppercase
#ifdef PEGASUS_OS_PASE
    for (Uint32 i = 0; i < userNameLen; i++)
    {
        userName[i] = toupper(userName[i]);
    }
#endif

#ifdef PEGASUS_WMIMAPPER
    authenticated = true;

    authInfo->setAuthenticatedUser(userName);
    authInfo->setAuthenticatedPassword(password);
#else

    if (!AuthenticationManager::isRemotePrivilegedUserAccessAllowed(userName))
    {
        return false;
    }
    authInfo->setRemotePrivilegedUserAccessChecked();

    authenticated = _basicAuthenticator->authenticate(userName, password);

    // Log audit message.
    PEG_AUDIT_LOG(logBasicAuthentication(
        userName,
        authInfo->getIpAddress(),
        authenticated));

    if (authenticated)
    {
        authInfo->setAuthenticatedUser(userName + String(" ") + password);
    }
    else
    {
        //
        //  Log a message for basic authentication failure
        //
        Logger::put_l(Logger::STANDARD_LOG, System::CIMSERVER,
            Logger::INFORMATION,
            MessageLoaderParms(
                BASIC_AUTHENTICATION_FAILED_KEY,
                BASIC_AUTHENTICATION_FAILED, userName,
                authInfo->getIpAddress()));
    }
#endif

    PEG_METHOD_EXIT();

    return (authenticated);
}
コード例 #14
0
ファイル: buffer_ref.hpp プロジェクト: bingmann/thrill
 //! Constructor, assign memory area from net::Buffer, does NOT copy!
 BufferRef(const Buffer& b) // NOLINT
     : data_(b.data()), size_(b.size())
 { }
コード例 #15
0
bool_t BtcChinaBtcCny::process(Callback& callback)
{
  if(!callback.receivedTime(Time::time()))
    return false;

  HttpRequest httpRequest;
  Buffer data;
  String dataStr;
  for(;; Thread::sleep(14000))
  {
    String url("https://data.btcchina.com/data/historydata");
    if(lastTradeId != 0)
      url.printf("https://data.btcchina.com/data/historydata?since=%llu", lastTradeId);
    if(!httpRequest.get(url, data))
    {
      error = httpRequest.getErrorString();
      open = false;
      return false;
    }
    timestamp_t localTime = Time::time();

    dataStr.attach((const char_t*)(byte_t*)data, data.size());
    Variant dataVar;
    if(!Json::parse(dataStr, dataVar))
    {
      error = "Could not parse trade data.";
      open = false;
      return false;
    }

    const List<Variant>& tradesList = dataVar.toList();
    if(!tradesList.isEmpty())
    {
      const HashMap<String, Variant>& tradeData = tradesList.back().toMap();
      timestamp_t serverTime = tradeData.find("date")->toInt64() * 1000LL;
      timestamp_t offset = serverTime - localTime;
      if(offset < timeOffset || !timeOffsetSet)
      {
        timeOffset = offset;
        timeOffsetSet = true;
        if(!callback.receivedTime(serverTime))
          return false;
      }
    }

    Trade trade;
    for(List<Variant>::Iterator i = tradesList.begin(), end = tradesList.end(); i != end; ++i)
    {
      const HashMap<String, Variant>& tradeData = i->toMap();
      trade.id = tradeData.find("tid")->toInt64();
      trade.time = tradeData.find("date")->toInt64() * 1000LL;
      trade.price = tradeData.find("price")->toDouble();
      trade.amount = tradeData.find("amount")->toDouble();
      trade.flags = 0;
      if(trade.id > lastTradeId)
      {
        if(!callback.receivedTrade(trade))
          return false;
        lastTradeId = trade.id;
      }
    }
  }

  return false; // unreachable
}
コード例 #16
0
ファイル: ArchiveBuffer.cpp プロジェクト: kyhhdm/TPlatform
char* ArchiveBuffer::readPString(int &stringLen)
{
    char *p;
    Buffer *curBuffer = m_buffers[m_buffers.size()-1];
    bool newBufferReaded = false;
    
    p = curBuffer->cur(); 
    stringLen = 0;

    //first get len byte of PString
    if(p + 4 <= curBuffer->end()){
        stringLen = CByteCode::decode(p);
    }
    else{
        //assume the PString is at least 4 bytes,
        //otherwise move it to new buffer.
        if(0 == readInNewBuffer()){
			return NULL;
		}
        newBufferReaded = true;
        curBuffer = m_buffers[m_buffers.size()-1];
        p = curBuffer->cur(); 
        stringLen = CByteCode::decode(p);
    }
   
    //now, p pointer to string content
    if(p + stringLen <= curBuffer->end()){
        curBuffer->setCur(p + stringLen - curBuffer->begin());
        return p;
    }

    if(!newBufferReaded){
        //record break, let's add new buffer
        if(0 == readInNewBuffer()){
			return NULL;
		}
        curBuffer = m_buffers[m_buffers.size()-1];
        p = curBuffer->cur(); 
        stringLen = CByteCode::decode(p);

        if(p + stringLen <= curBuffer->end()){
            curBuffer->setCur(p + stringLen - curBuffer->begin());
            return p;
        }
    }

    //not found in new buffer
    throw BufferError("readPString fail for record too large");
}
コード例 #17
0
ファイル: Simulation.hpp プロジェクト: ALaDyn/picongpu
    void init()
    {
        /* subGrid holds global and
         * local SimulationSize and where the local SimArea is in the greater
         * scheme using Offsets from global LEFT, TOP, FRONT
         */
        const SubGrid<DIM2>& subGrid = Environment<DIM2>::get().SubGrid();

        /* The following sets up the local layout which consists of the actual
         * grid cells and some surrounding cells, called guards.
         *
         * ASCII Visualization: example taken for 1D,
         * distributed over 2 GPUs, only 1 border shown between those two GPUs
         * assuming non-periodic boundary conditions.
         * In a N-GPU or periodic example, border cells guard cells exist in each direction.
         * _______GPU 0________       _______GPU 1________
         * | 0 | 1 | 2 | 3 | 4 |      | 3 | 4 | 5 | 6 | 7 |  <-- Global (super)cell idx
         * |___|___|___|___|___|      |___|___|___|___|___|
         * |___Core____|Bor|Gua|      |Gua|Bor|___Core____|
         * |___________|der|rd_|      |rd_|der|___________|
         * |__"real" cells_|***|      |***|__"real" cells_|
         *
         * |***| Clones cells which correspond to the border cells of the neighbor GPU
         *       (sometimes also called "ghost" or "halo" cells/region)
         *
         * Recall that the following is defined:
         *     typedef MappingDescription<DIM2, math::CT::Int<16,16> > MappingDesc;
         * where math::CT::Int<16,16> is arbitrarily(!) chosen SuperCellSize
         * and DIM2 is the dimension of the grid.
         * Expression of 2nd argument translates to DataSpace<DIM3>(16,16,0).
         * This is the guard size (here set to be one Supercell wide in all
         * directions). Meaning we have 16*16*(2*grid.x+2*grid.y+4) more
         * cells in GridLayout than in the SubGrid.
         * The formula above is SuperCellSize * TotalNumGuardCells with (in this case)
         * SuperCellSize = 16*16 (16 cells in 2 dimensions)
         * TotalNumGuardCells =   2 * grid.x (top and bottom)
         *                      + 2 * grid.y (left and right)
         *                      + 4          (the corners)
         */
        GridLayout<DIM2> layout( subGrid.getLocalDomain().size,
                                 MappingDesc::SuperCellSize::toRT());

        /* getDataSpace will return DataSpace( grid.x +16+16, grid.y +16+16)  *
         * MappingDesc stores the layout regarding Core, Border and Guard     *
         * in units of SuperCells.                                            *
         * This is saved by init to be used by the kernel to identify itself. */
        evo.init(layout.getDataSpace(), Space::create(1));

        buff1 = new Buffer(layout, false);
        buff2 = new Buffer(layout, false);

        /* Set up the future data exchange. In this case we need to copy the
         * border cells of our neighbors to our guard cells, since we only read
         * from the guard cells but never write to it.
         * guardingCells holds the number of guard(super)cells in each dimension
         */
        Space guardingCells(1, 1);
        for (uint32_t i = 1; i < traits::NumberOfExchanges<DIM2>::value; ++i)
        {
            /* to check which number corresponds to which direction, you can  *
             * use the following member of class Mask like done in the two    *
             * lines below:                                                   *
             * DataSpace<DIM2>relVec = Mask::getRelativeDirections<DIM2>(i);  *
             * std::cout << "Direction:" << i << " => Vec: (" << relVec[0]    *
             *           << "," << relVec[1] << ")\n";                        *
             * The result is: 1:right(1,0), 2:left(-1,0), 3:up(0,1),          *
             *    4:up right(1,1), 5:(-1,1), 6:(0,-1), 7:(1,-1), 8:(-1,-1)    */

            /* types.hpp: enum CommunicationTags{ BUFF1 = 0u, BUFF2 = 1u };   */
            buff1->addExchange(GUARD, Mask(i), guardingCells, BUFF1);
            buff2->addExchange(GUARD, Mask(i), guardingCells, BUFF2);
        }

         /* Both next lines are defined in GatherSlice.hpp:                   *
          *  -gather saves the MessageHeader object                           *
          *  -Then do an Allgather for the gloabalRanks from GC, sort out     *
          *  -inactive processes (second/boolean ,argument in gather.init) and*
          *   save new MPI_COMMUNICATOR created from these into private var.  *
          *  -return if rank == 0                                             */
        MessageHeader header(gridSize, layout, subGrid.getLocalDomain().offset);
        isMaster = gather.init(header, true);

        /* Calls kernel to initialize random generator. Game of Life is then  *
         * initialized using uniform random numbers. With 10% (second arg)    *
         * white points. World will be written to buffer in first argument    */
        evo.initEvolution(buff1->getDeviceBuffer().getDataBox(), 0.1);

    }
コード例 #18
0
ファイル: ArchiveBuffer.cpp プロジェクト: kyhhdm/TPlatform
void ArchiveBuffer::clearBuffer()
{
    //
    //#!!!, all position returned by getCurPos will invalidate after this call
    //

    if(m_mode == FileStream::ReadOnly){
        //realse all buffers before the last record
        //for(int i = 0; i < m_endBufferId ; i++){
        //    delete m_buffers[i];
        //}
        vector<Buffer*>::iterator pos = m_buffers.begin();
        for(int i = 0; i < m_endBufferId ; i++){

            //update stream buffer offset
            m_bufferOffset += (*pos)->end() - (*pos)->begin();

            //for debug purpose
            (*pos)->clear();

            delete *pos;
            pos = m_buffers.erase(pos);
        }
        //m_buffers.erase(0,m_endBufferId);
        
        /*if(m_endBufferId > 0){
            cout << "clearBuffer : endBufferId = " << m_endBufferId << endl;
        }*/

        m_endBufferId = 0;
    }
    else if (m_mode == FileStream::Append){
        //write data and clear buffer
        Buffer *curBuffer = m_buffers[m_buffers.size()-1];
        int dataSize;

        dataSize = curBuffer->recordEnd()-curBuffer->begin();
        if(dataSize > 0){
            m_stream->append(curBuffer->begin(), dataSize);

            //update stream buffer offset
            m_bufferOffset += dataSize;

            if((dataSize = curBuffer->cur() - curBuffer->recordEnd())>0){
                //move data from <recordEnd,cur> to 0
                if(curBuffer->recordEnd() - curBuffer->begin() < dataSize){
                    char *tmp = new char[dataSize];
                    memcpy(tmp, curBuffer->recordEnd(), dataSize);
                    memcpy(curBuffer->begin(), tmp, dataSize);
                    delete[] tmp;
                }
                else{
                    memcpy(curBuffer->begin(), curBuffer->recordEnd(), dataSize);
                }
            }

            curBuffer->setCur(0);
            curBuffer->setRecordEnd();
            curBuffer->setCur(dataSize);
        }
    }

}
コード例 #19
0
ファイル: SNAC-SRV.cpp プロジェクト: transacid/CenterIM
  void SrvUpdateMainHomeInfo::OutputBody(Buffer& b) const {
        b << (unsigned short)0x0001;

        Buffer::marker m1 = b.getAutoSizeShortMarker();
    
        b.setLittleEndian();
        Buffer::marker m2 = b.getAutoSizeShortMarker();

        b << m_my_uin;

        b << (unsigned short)2000   /* type 9808 */
            << (unsigned short)m_requestID /* low word of the request ID */
            << (unsigned short)0x03ea; /* subtype */
        b.PackUint16StringNull(m_main_home_info.alias);     // alias
        b.PackUint16StringNull(m_main_home_info.firstname); // first name
        b.PackUint16StringNull(m_main_home_info.lastname);  // last name
        b.PackUint16StringNull(m_main_home_info.email);	    // email
        b.PackUint16StringNull(m_main_home_info.city);	    // city
        b.PackUint16StringNull(m_main_home_info.state);     // state
        b.PackUint16StringNull(m_main_home_info.phone);     // phone
        b.PackUint16StringNull(m_main_home_info.fax);       // fax
        b.PackUint16StringNull(m_main_home_info.street);    // street
        b.PackUint16StringNull(m_main_home_info.getMobileNo());  // cellular
        b.PackUint16StringNull(m_main_home_info.zip);       // zip
        b << m_main_home_info.country;
        b << m_main_home_info.timezone;
        unsigned char publish_email = 0;
        b << publish_email;
        b.setAutoSizeMarker(m1);
        b.setAutoSizeMarker(m2);
    }
コード例 #20
0
ファイル: ArchiveBuffer.cpp プロジェクト: kyhhdm/TPlatform
int ArchiveBuffer::readInNewBuffer()
{
    Buffer *curBuffer = m_buffers[m_buffers.size()-1];
    int readLen;

    int curDataLen = curBuffer->end() - curBuffer->begin();
    bool emptyBuffer = (curBuffer->end() == curBuffer->begin());
    bool fullBuffer = (curDataLen == m_bufferSize);
    
    if(!fullBuffer){
        if(emptyBuffer || (m_bufferSize - curDataLen) > m_recordSizeThreshold){
            //it an empty buffer, just read in data
            readLen = m_stream->read(curBuffer->cur(), m_bufferSize - curDataLen);
            curBuffer->setTail(curDataLen + readLen);
            if(m_autoClearBuffer) clearBuffer();
            return readLen;
        }
        else{
            //the left space is too small, so skip them
        }
    }

    Buffer *buffer = new Buffer(m_bufferSize);
    m_buffers.push_back(buffer);

    int copyDataLen = curBuffer->end() - curBuffer->cur();
    int fillDataLen = m_bufferSize - copyDataLen;


    if(copyDataLen > 0) memcpy(buffer->begin(),curBuffer->cur(),copyDataLen);
    curBuffer->cutTail();
    
    readLen = m_stream->read(buffer->cur() + copyDataLen, fillDataLen);
    buffer->setTail(copyDataLen + readLen);

	//at last , free buffer if autoClearBuffer
	if(m_autoClearBuffer) clearBuffer();
    return readLen;
}
コード例 #21
0
ファイル: makecube.cpp プロジェクト: corburn/ISIS
 void operator()(Buffer &output) const {
   for (int i = 0; i < output.size(); i++) {
     output[i] = m_value;
   }
 }
コード例 #22
0
ファイル: Loaders.cpp プロジェクト: Jesna/ppsspp
size_t HTTPFileLoader::ReadAt(s64 absolutePos, size_t bytes, void *data) {
	s64 absoluteEnd = std::min(absolutePos + (s64)bytes, filesize_);
	if (absolutePos >= filesize_ || bytes == 0) {
		// Read outside of the file or no read at all, just fail immediately.
		return 0;
	}

	Connect();

	char requestHeaders[4096];
	// Note that the Range header is *inclusive*.
	snprintf(requestHeaders, sizeof(requestHeaders),
		"Range: bytes=%lld-%lld\r\n", absolutePos, absoluteEnd - 1);

	int err = client_.SendRequest("GET", url_.Resource().c_str(), requestHeaders, nullptr);
	if (err < 0) {
		Disconnect();
		return 0;
	}

	Buffer readbuf;
	std::vector<std::string> responseHeaders;
	int code = client_.ReadResponseHeaders(&readbuf, responseHeaders);
	if (code != 206) {
		ERROR_LOG(LOADER, "HTTP server did not respond with range, received code=%03d", code);
		Disconnect();
		return 0;
	}

	// TODO: Expire cache via ETag, etc.
	// We don't support multipart/byteranges responses.
	bool supportedResponse = false;
	for (std::string header : responseHeaders) {
		if (startsWithNoCase(header, "Content-Range:")) {
			// TODO: More correctness.  Whitespace can be missing or different.
			s64 first = -1, last = -1, total = -1;
			std::string lowerHeader = header;
			std::transform(lowerHeader.begin(), lowerHeader.end(), lowerHeader.begin(), tolower);
			if (sscanf(lowerHeader.c_str(), "content-range: bytes %lld-%lld/%lld", &first, &last, &total) >= 2) {
				if (first == absolutePos && last == absoluteEnd - 1) {
					supportedResponse = true;
				} else {
					ERROR_LOG(LOADER, "Unexpected HTTP range: got %lld-%lld, wanted %lld-%lld.", first, last, absolutePos, absoluteEnd - 1);
				}
			} else {
				ERROR_LOG(LOADER, "Unexpected HTTP range response: %s", header.c_str());
			}
		}
	}

	// TODO: Would be nice to read directly.
	Buffer output;
	int res = client_.ReadResponseEntity(&readbuf, responseHeaders, &output);
	if (res != 0) {
		ERROR_LOG(LOADER, "Unable to read HTTP response entity: %d", res);
		// Let's take anything we got anyway.  Not worse than returning nothing?
	}

	// TODO: Keepalive instead.
	Disconnect();

	if (!supportedResponse) {
		ERROR_LOG(LOADER, "HTTP server did not respond with the range we wanted.");
		return 0;
	}

	size_t readBytes = output.size();
	output.Take(readBytes, (char *)data);
	filepos_ = absolutePos + readBytes;
	return readBytes;
}
コード例 #23
0
ファイル: playersession.cpp プロジェクト: Portalcake/Soldin
/* Sends the characterlist to the client. */
void PlayerSession::SendCharacterList()
{
	if ( !IsAuthenticated() )
		return;

	/* Send the character limit and the available character licenses. */
	Buffer licensepkt;
	licensepkt.WriteUInt32( mAccount->mMaxChars );
	licensepkt.WriteUInt32( HASH_LIST_CHARLICENCES );
	licensepkt.WriteUInt32( mAccount->mLicenseCount );
	if ( mAccount->mLicenseCount > 0 )
		for ( uint32_t i = 0; i < mAccount->mLicenseCount; i++ )
			licensepkt.WriteUInt32( mAccount->mLicenses[i] );

	Send( licensepkt, MSG_CHARACTER_LICENSE );

	/* Send the character list. */
	Buffer listpkt;
	listpkt.WriteUInt32( HASH_LIST_CHARACTERS );
	listpkt.WriteUInt32( mAccount->mCharacters.size() );
	if ( mAccount->mCharacters.size() > 0 )
	{
		uint32_t index = 0;
		for ( CharacterList::iterator i = mAccount->mCharacters.begin(); i != mAccount->mCharacters.end(); ++i, index++ )
		{
			CharacterData *chara = *i;

			listpkt.WriteUInt32( HASH_OBJ_CHARACTER +  index );
			listpkt.WriteWideString( UTF16( chara->mName ) );

			listpkt.WriteUInt32( 0 );
			listpkt.WriteUInt32( chara->mClassId );
			listpkt.WriteUInt16( chara->mLevel );
			listpkt.WriteUInt32( chara->mExperience );
			listpkt.WriteUInt16( chara->mPvpLevel );
			listpkt.WriteUInt32( chara->mPvpExperience );
			listpkt.WriteUInt16( chara->mWarLevel );
			listpkt.WriteUInt32( chara->mWarExperience );
			listpkt.WriteUInt16( chara->mRebirthLevel );
			listpkt.WriteUInt16( chara->mRebirthCount );

			struct tm *timeinfo = localtime( &chara->mLastPlayed );
			listpkt.WriteUInt32( HASH_DATETIME_LASTPLAYED );
			listpkt.WriteUInt16( timeinfo->tm_year + 1900 );
			listpkt.WriteUInt16( timeinfo->tm_mon + 1 );
			listpkt.WriteUInt16( timeinfo->tm_wday );
			listpkt.WriteUInt16( timeinfo->tm_hour );
			listpkt.WriteUInt16( timeinfo->tm_min );
			listpkt.WriteUInt16( timeinfo->tm_sec );
			listpkt.WriteUInt16( 0 );

			listpkt.WriteUInt32( HASH_LIST_EQUIPMENT );
			listpkt.WriteUInt32( chara->mEquipmentCount );
			for ( uint8_t j = 0; j < chara->mEquipmentCount; j++ )
			{
				listpkt.WriteUInt32( HASH_OBJ_EQUIPMENT + j );
				listpkt.WriteUInt32( chara->mEquipment[j].mId );

				listpkt.WriteUInt32( 0x613E5DCA );
				listpkt.Write( (byte *)"\0\0\0\0\0\0\0\0\0\0\0", 11 );
			}

			listpkt.WriteUInt32( HASH_LIST_STAGELICENCES );
			listpkt.WriteUInt32( 0 );
		}
	}
	Send( listpkt, MSG_CHARACTER_LIST );
}
コード例 #24
0
BOOL Notepad_plus::notify(SCNotification *notification)
{
	//Important, keep track of which element generated the message
	bool isFromPrimary = (_mainEditView.getHSelf() == notification->nmhdr.hwndFrom || _mainDocTab.getHSelf() == notification->nmhdr.hwndFrom);
	bool isFromSecondary = !isFromPrimary && (_subEditView.getHSelf() == notification->nmhdr.hwndFrom || _subDocTab.getHSelf() == notification->nmhdr.hwndFrom);
	ScintillaEditView * notifyView = isFromPrimary?&_mainEditView:&_subEditView;
	DocTabView *notifyDocTab = isFromPrimary?&_mainDocTab:&_subDocTab;
	TBHDR * tabNotification = (TBHDR*) notification;
	switch (notification->nmhdr.code) 
	{
		case SCN_MODIFIED:
		{
			static bool prevWasEdit = false;
			if (notification->modificationType & (SC_MOD_DELETETEXT | SC_MOD_INSERTTEXT))
			{
				_pEditView->updateBeginEndSelectPosition(notification->modificationType & SC_MOD_INSERTTEXT, notification->position, notification->length);
				prevWasEdit = true;
				_linkTriggered = true;
				::InvalidateRect(notifyView->getHSelf(), NULL, TRUE);
			}

			if (notification->modificationType & (SC_MOD_DELETETEXT | SC_MOD_INSERTTEXT | SC_PERFORMED_UNDO | SC_PERFORMED_REDO))
			{
				// for the backup system
				_pEditView->getCurrentBuffer()->setModifiedStatus(true);
			}

			if (notification->modificationType & SC_MOD_CHANGEFOLD)
			{
				if (prevWasEdit) 
				{
					notifyView->foldChanged(notification->line, notification->foldLevelNow, notification->foldLevelPrev);
					prevWasEdit = false;
				}
			}
			else if (!(notification->modificationType & (SC_MOD_DELETETEXT | SC_MOD_INSERTTEXT)))
			{
				prevWasEdit = false;
			}


		}
		break;

		case SCN_SAVEPOINTREACHED:
		case SCN_SAVEPOINTLEFT:
		{
			Buffer * buf = 0;
			if (isFromPrimary)
			{
				buf = _mainEditView.getCurrentBuffer();
			}
			else if (isFromSecondary)
			{
				buf = _subEditView.getCurrentBuffer();
			}
			else
			{
				//Done by invisibleEditView?
				BufferID id = BUFFER_INVALID;
				if (notification->nmhdr.hwndFrom == _invisibleEditView.getHSelf()) 
				{
					id = MainFileManager->getBufferFromDocument(_invisibleEditView.execute(SCI_GETDOCPOINTER));
				}
				else if (notification->nmhdr.hwndFrom == _fileEditView.getHSelf())
				{
					id = MainFileManager->getBufferFromDocument(_fileEditView.execute(SCI_GETDOCPOINTER));
				}
				else 
				{
					break;	//wrong scintilla
				}

				if (id != BUFFER_INVALID)
				{
					buf = MainFileManager->getBufferByID(id);
				}
				else
				{
					break;
				}
			}
			bool isDirty = notification->nmhdr.code == SCN_SAVEPOINTLEFT;
			bool isSnapshotMode = NppParameters::getInstance()->getNppGUI().isSnapshotMode();
			if (isSnapshotMode && !isDirty)
			{
				bool canUndo = _pEditView->execute(SCI_CANUNDO) == TRUE;
				if (!canUndo && buf->isLoadedDirty())
					isDirty = true;
			}
			buf->setDirty(isDirty);
			break; 
		}

		case  SCN_MODIFYATTEMPTRO :
			// on fout rien
			break;

		case SCN_KEY:
			break;

	case TCN_TABDROPPEDOUTSIDE:
	case TCN_TABDROPPED:
	{
        TabBarPlus *sender = reinterpret_cast<TabBarPlus *>(notification->nmhdr.idFrom);
        bool isInCtrlStat = (::GetKeyState(VK_LCONTROL) & 0x80000000) != 0;
        if (notification->nmhdr.code == TCN_TABDROPPEDOUTSIDE)
        {
            POINT p = sender->getDraggingPoint();

			//It's the coordinate of screen, so we can call 
			//"WindowFromPoint" function without converting the point
            HWND hWin = ::WindowFromPoint(p);
			if (hWin == _pEditView->getHSelf()) // In the same view group
			{
				if (!_tabPopupDropMenu.isCreated())
				{
					TCHAR goToView[32] = TEXT("Move to other view");
					TCHAR cloneToView[32] = TEXT("Clone to other View");
					vector<MenuItemUnit> itemUnitArray;
					itemUnitArray.push_back(MenuItemUnit(IDM_VIEW_GOTO_ANOTHER_VIEW, goToView));
					itemUnitArray.push_back(MenuItemUnit(IDM_VIEW_CLONE_TO_ANOTHER_VIEW, cloneToView));
					_tabPopupDropMenu.create(_pPublicInterface->getHSelf(), itemUnitArray, _mainMenuHandle);
					_nativeLangSpeaker.changeLangTabDrapContextMenu(_tabPopupDropMenu.getMenuHandle());
				}
				_tabPopupDropMenu.display(p);
			}
			else if ((hWin == _pNonDocTab->getHSelf()) || 
				     (hWin == _pNonEditView->getHSelf())) // In the another view group
			{
                docGotoAnotherEditView(isInCtrlStat?TransferClone:TransferMove);
			}/*
			else if ((hWin == _pProjectPanel_1->getTreeHandle()))
			{
				
                //printStr(TEXT("IN!!!"));
			}*/
			else
			{
				RECT nppZone;
				::GetWindowRect(_pPublicInterface->getHSelf(), &nppZone);
				bool isInNppZone = (((p.x >= nppZone.left) && (p.x <= nppZone.right)) && (p.y >= nppZone.top) && (p.y <= nppZone.bottom));
				if (isInNppZone)
				{
					// Do nothing
					return TRUE;
				}
				generic_string quotFileName = TEXT("\"");
				quotFileName += _pEditView->getCurrentBuffer()->getFullPathName();
				quotFileName += TEXT("\"");
				COPYDATASTRUCT fileNamesData;
				fileNamesData.dwData = COPYDATA_FILENAMES;
				fileNamesData.lpData = (void *)quotFileName.c_str();
				fileNamesData.cbData = long(quotFileName.length() + 1)*(sizeof(TCHAR));

				HWND hWinParent = ::GetParent(hWin);
				TCHAR className[MAX_PATH];
				::GetClassName(hWinParent,className, sizeof(className));
				if (lstrcmp(className, _pPublicInterface->getClassName()) == 0 && hWinParent != _pPublicInterface->getHSelf()) // another Notepad++
				{
					int index = _pDocTab->getCurrentTabIndex();
					BufferID bufferToClose = notifyDocTab->getBufferByIndex(index);
					Buffer * buf = MainFileManager->getBufferByID(bufferToClose);
					int iView = isFromPrimary?MAIN_VIEW:SUB_VIEW;
					if (buf->isDirty()) 
					{
						generic_string msg, title;
						_nativeLangSpeaker.messageBox("CannotMoveDoc",
							_pPublicInterface->getHSelf(),
							TEXT("Document is modified, save it then try again."),
							TEXT("Move to new Notepad++ Instance"),
							MB_OK);
					}
					else
					{
						::SendMessage(hWinParent, NPPM_INTERNAL_SWITCHVIEWFROMHWND, 0, (LPARAM)hWin);
						::SendMessage(hWinParent, WM_COPYDATA, (WPARAM)_pPublicInterface->getHinst(), (LPARAM)&fileNamesData);
                        if (!isInCtrlStat)
						{
							fileClose(bufferToClose, iView);
							if (noOpenedDoc())
								::SendMessage(_pPublicInterface->getHSelf(), WM_CLOSE, 0, 0);
						}
					}
				}
                else // Not Notepad++, we open it here
                {
					docOpenInNewInstance(isInCtrlStat?TransferClone:TransferMove, p.x, p.y);
                }
			}
        }
		//break;
		sender->resetDraggingPoint();
		return TRUE;
	}

	case TCN_TABDELETE:
	{
		int index = tabNotification->tabOrigin;
		BufferID bufferToClose = notifyDocTab->getBufferByIndex(index);
		Buffer * buf = MainFileManager->getBufferByID(bufferToClose);
		int iView = isFromPrimary?MAIN_VIEW:SUB_VIEW;
		if (buf->isDirty())
		{
			activateBuffer(bufferToClose, iView);
		}
		fileClose(bufferToClose, iView);
		break;
	}

	case TCN_SELCHANGE:
	{
		int iView = -1;
        if (notification->nmhdr.hwndFrom == _mainDocTab.getHSelf())
		{
			iView = MAIN_VIEW;
		}
		else if (notification->nmhdr.hwndFrom == _subDocTab.getHSelf())
		{
			iView = SUB_VIEW;
		}
		else
		{
			break;
		}

		switchEditViewTo(iView);
		BufferID bufid = _pDocTab->getBufferByIndex(_pDocTab->getCurrentTabIndex());
		if (bufid != BUFFER_INVALID)
			activateBuffer(bufid, iView);
		
		break;
	}

	case NM_CLICK :
    {        
		if (notification->nmhdr.hwndFrom == _statusBar.getHSelf())
        {
            LPNMMOUSE lpnm = (LPNMMOUSE)notification;
			if (lpnm->dwItemSpec == DWORD(STATUSBAR_TYPING_MODE))
			{
				bool isOverTypeMode = (_pEditView->execute(SCI_GETOVERTYPE) != 0);
				_pEditView->execute(SCI_SETOVERTYPE, !isOverTypeMode);
				_statusBar.setText((_pEditView->execute(SCI_GETOVERTYPE))?TEXT("OVR"):TEXT("INS"), STATUSBAR_TYPING_MODE);
			}
        }
		else if (notification->nmhdr.hwndFrom == _mainDocTab.getHSelf() && _activeView == SUB_VIEW)
		{
			bool isSnapshotMode = NppParameters::getInstance()->getNppGUI().isSnapshotMode();
			if (isSnapshotMode)
			{
				// Before switching off, synchronize backup file
				MainFileManager->backupCurrentBuffer();
			}
			// Switch off
            switchEditViewTo(MAIN_VIEW);
		}
        else if (notification->nmhdr.hwndFrom == _subDocTab.getHSelf() && _activeView == MAIN_VIEW)
        {
			bool isSnapshotMode = NppParameters::getInstance()->getNppGUI().isSnapshotMode();
			if (isSnapshotMode)
			{
				// Before switching off, synchronize backup file
				MainFileManager->backupCurrentBuffer();
			}
			// Switch off
            switchEditViewTo(SUB_VIEW);
        }

		break;
	}

	case NM_DBLCLK :
    {        
		if (notification->nmhdr.hwndFrom == _statusBar.getHSelf())
        {
            LPNMMOUSE lpnm = (LPNMMOUSE)notification;
			if (lpnm->dwItemSpec == DWORD(STATUSBAR_CUR_POS))
			{
				bool isFirstTime = !_goToLineDlg.isCreated();
                _goToLineDlg.doDialog(_nativeLangSpeaker.isRTL());
				if (isFirstTime)
                    _nativeLangSpeaker.changeDlgLang(_goToLineDlg.getHSelf(), "GoToLine");
			}
            else if (lpnm->dwItemSpec == DWORD(STATUSBAR_DOC_SIZE))
			{
				command(IDM_VIEW_SUMMARY);
			}
        }
		break;
	}

    case NM_RCLICK :
    {
		POINT p;
		::GetCursorPos(&p);

		if (notification->nmhdr.hwndFrom == _mainDocTab.getHSelf())
		{
            switchEditViewTo(MAIN_VIEW);
		}
        else if (notification->nmhdr.hwndFrom == _subDocTab.getHSelf())
        {
            switchEditViewTo(SUB_VIEW);
        }
		else if (_pFileSwitcherPanel && notification->nmhdr.hwndFrom == _pFileSwitcherPanel->getHSelf())
        {
			// Already switched, so do nothing here.

			if (_pFileSwitcherPanel->nbSelectedFiles() > 1)
			{
				if (!_fileSwitcherMultiFilePopupMenu.isCreated())
				{
					vector<MenuItemUnit> itemUnitArray;
					itemUnitArray.push_back(MenuItemUnit(IDM_FILESWITCHER_FILESCLOSE, TEXT("Close Selected files")));
					itemUnitArray.push_back(MenuItemUnit(IDM_FILESWITCHER_FILESCLOSEOTHERS, TEXT("Close others files")));

					_fileSwitcherMultiFilePopupMenu.create(_pPublicInterface->getHSelf(), itemUnitArray);
					_nativeLangSpeaker.changeLangTabContextMenu(_fileSwitcherMultiFilePopupMenu.getMenuHandle());
				}
				_fileSwitcherMultiFilePopupMenu.display(p);
				return TRUE;
			}
		}
		else // From tool bar or Status Bar
			return TRUE;
			//break;

		if (!_tabPopupMenu.isCreated())
		{
			vector<MenuItemUnit> itemUnitArray;
			itemUnitArray.push_back(MenuItemUnit(IDM_FILE_CLOSE, TEXT("Close")));
			itemUnitArray.push_back(MenuItemUnit(IDM_FILE_CLOSEALL_BUT_CURRENT, TEXT("Close All BUT This")));
			itemUnitArray.push_back(MenuItemUnit(IDM_FILE_CLOSEALL_TOLEFT, TEXT("Close All to the Left")));
			itemUnitArray.push_back(MenuItemUnit(IDM_FILE_CLOSEALL_TORIGHT, TEXT("Close All to the Right")));
			itemUnitArray.push_back(MenuItemUnit(IDM_FILE_SAVE, TEXT("Save")));
			itemUnitArray.push_back(MenuItemUnit(IDM_FILE_SAVEAS, TEXT("Save As...")));
			itemUnitArray.push_back(MenuItemUnit(IDM_FILE_RENAME, TEXT("Rename")));
			itemUnitArray.push_back(MenuItemUnit(IDM_FILE_DELETE, TEXT("Move to Recycle Bin")));
			itemUnitArray.push_back(MenuItemUnit(IDM_FILE_RELOAD, TEXT("Reload")));
			itemUnitArray.push_back(MenuItemUnit(IDM_FILE_PRINT, TEXT("Print")));
			itemUnitArray.push_back(MenuItemUnit(0, NULL));
			itemUnitArray.push_back(MenuItemUnit(IDM_FILE_OPEN_FOLDER, TEXT("Open Containing Folder in Explorer")));
			itemUnitArray.push_back(MenuItemUnit(IDM_FILE_OPEN_CMD, TEXT("Open Containing Folder in cmd")));
			itemUnitArray.push_back(MenuItemUnit(0, NULL));
			itemUnitArray.push_back(MenuItemUnit(IDM_EDIT_SETREADONLY, TEXT("Read-Only")));
			itemUnitArray.push_back(MenuItemUnit(IDM_EDIT_CLEARREADONLY, TEXT("Clear Read-Only Flag")));
			itemUnitArray.push_back(MenuItemUnit(0, NULL));
			itemUnitArray.push_back(MenuItemUnit(IDM_EDIT_FULLPATHTOCLIP,	TEXT("Full File Path to Clipboard")));
			itemUnitArray.push_back(MenuItemUnit(IDM_EDIT_FILENAMETOCLIP,   TEXT("Filename to Clipboard")));
			itemUnitArray.push_back(MenuItemUnit(IDM_EDIT_CURRENTDIRTOCLIP, TEXT("Current Dir. Path to Clipboard")));
			itemUnitArray.push_back(MenuItemUnit(0, NULL));
			itemUnitArray.push_back(MenuItemUnit(IDM_VIEW_GOTO_ANOTHER_VIEW, TEXT("Move to Other View")));
			itemUnitArray.push_back(MenuItemUnit(IDM_VIEW_CLONE_TO_ANOTHER_VIEW, TEXT("Clone to Other View")));
			itemUnitArray.push_back(MenuItemUnit(IDM_VIEW_GOTO_NEW_INSTANCE, TEXT("Move to New Instance")));
			itemUnitArray.push_back(MenuItemUnit(IDM_VIEW_LOAD_IN_NEW_INSTANCE, TEXT("Open in New Instance")));

			_tabPopupMenu.create(_pPublicInterface->getHSelf(), itemUnitArray);
            _nativeLangSpeaker.changeLangTabContextMenu(_tabPopupMenu.getMenuHandle());
		}

		bool isEnable = ((::GetMenuState(_mainMenuHandle, IDM_FILE_SAVE, MF_BYCOMMAND)&MF_DISABLED) == 0);
		_tabPopupMenu.enableItem(IDM_FILE_SAVE, isEnable);
		
		Buffer * buf = _pEditView->getCurrentBuffer();
		bool isUserReadOnly = buf->getUserReadOnly();
		_tabPopupMenu.checkItem(IDM_EDIT_SETREADONLY, isUserReadOnly);

		bool isSysReadOnly = buf->getFileReadOnly();
		_tabPopupMenu.enableItem(IDM_EDIT_SETREADONLY, !isSysReadOnly);
		_tabPopupMenu.enableItem(IDM_EDIT_CLEARREADONLY, isSysReadOnly);

		bool isFileExisting = PathFileExists(buf->getFullPathName()) != FALSE;
		_tabPopupMenu.enableItem(IDM_FILE_DELETE, isFileExisting);
		_tabPopupMenu.enableItem(IDM_FILE_RENAME, isFileExisting);

		bool isDirty = buf->isDirty();
		bool isUntitled = buf->isUntitled();
		_tabPopupMenu.enableItem(IDM_VIEW_GOTO_NEW_INSTANCE, !(isDirty||isUntitled));
		_tabPopupMenu.enableItem(IDM_VIEW_LOAD_IN_NEW_INSTANCE, !(isDirty||isUntitled));

		_tabPopupMenu.display(p);
		return TRUE;
    }

    
	case SCN_MARGINCLICK:
    {
        if (notification->nmhdr.hwndFrom == _mainEditView.getHSelf())
            switchEditViewTo(MAIN_VIEW);
		else if (notification->nmhdr.hwndFrom == _subEditView.getHSelf())
            switchEditViewTo(SUB_VIEW);

        int lineClick = int(_pEditView->execute(SCI_LINEFROMPOSITION, notification->position));
        
		if (notification->margin == ScintillaEditView::_SC_MARGE_FOLDER)
        {
            _pEditView->marginClick(notification->position, notification->modifiers);
			if (_pDocMap)
				_pDocMap->fold(lineClick, _pEditView->isFolded(lineClick));
        }
        else if ((notification->margin == ScintillaEditView::_SC_MARGE_SYBOLE) && !notification->modifiers)
        {
			if (!_pEditView->markerMarginClick(lineClick))
				bookmarkToggle(lineClick);
        }
		break;
	}

	case SCN_FOLDINGSTATECHANGED :
	{
		if ((notification->nmhdr.hwndFrom == _mainEditView.getHSelf())
		|| (notification->nmhdr.hwndFrom == _subEditView.getHSelf()))
		{
			int lineClicked = notification->line;
			
			if (!_isFolding)
			{
				int urlAction = (NppParameters::getInstance())->getNppGUI()._styleURL;
				if ((urlAction == 1) || (urlAction == 2))
					addHotSpot();
			}

			if (_pDocMap)
				_pDocMap->fold(lineClicked, _pEditView->isFolded(lineClicked));
		}
		return TRUE;
	}

	case SCN_CHARADDED:
	{
		const NppGUI & nppGui = NppParameters::getInstance()->getNppGUI();
		bool indentMaintain = nppGui._maitainIndent;
		if (indentMaintain)
			maintainIndentation(static_cast<TCHAR>(notification->ch));
		
		AutoCompletion * autoC = isFromPrimary?&_autoCompleteMain:&_autoCompleteSub;
		
		if (nppGui._matchedPairConf.hasAnyPairsPair())
			autoC->insertMatchedChars(notification->ch, nppGui._matchedPairConf);
		autoC->update(notification->ch);

		break;
	}

	case SCN_DOUBLECLICK :
	{
		if(notification->modifiers == SCMOD_CTRL)
		{
			const NppGUI & nppGUI = NppParameters::getInstance()->getNppGUI();

			std::string bufstring;
			unsigned int position_of_click;

			// Anonymous scope to limit use of the buf pointer (much easier to deal with std::string).
			{
				char *buf;
				int length;
				
				if(nppGUI._delimiterSelectionOnEntireDocument)
				{
					// Get entire document.
					length = notifyView->execute(SCI_GETLENGTH);
					buf = new char[length + 1];
					notifyView->execute(SCI_GETTEXT, (LPARAM)(length + 1), (WPARAM)buf);

					// For some reason Ctrl+DoubleClick on an empty line means that notification->position == 1.
					// In that case we use SCI_GETCURRENTPOS to get the position.
					if(notification->position != -1)
						position_of_click = notification->position;
					else
						position_of_click = int(_pEditView->execute(SCI_GETCURRENTPOS));
				}
				else
				{
					// Get single line.
					length = notifyView->execute(SCI_GETCURLINE);
					buf = new char[length + 1];
					notifyView->execute(SCI_GETCURLINE, (WPARAM)length, (LPARAM)buf);

					// Compute the position of the click (relative to the beginning of the line).
					const int line_position = notifyView->execute(SCI_POSITIONFROMLINE, notifyView->getCurrentLineNumber());
					position_of_click = notification->position - line_position;
				}

				bufstring = buf;
				delete [] buf;
			}

			int leftmost_position = -1;
			int rightmost_position = -1;

			if(nppGUI._rightmostDelimiter == nppGUI._leftmostDelimiter)
			{
				// If the delimiters are the same (e.g. they are both a quotation mark), choose the ones
				// which are closest to the clicked position.

				for(unsigned int i = position_of_click; i >= 0; --i)
				{
					if(bufstring.at(i) == nppGUI._leftmostDelimiter)
					{
						// Respect escaped quotation marks.
						if(nppGUI._leftmostDelimiter == '"')
						{
							if(! (i > 0 && bufstring.at(i - 1) == '\\'))
							{
								leftmost_position = i;
								break;
							}
						}
						else
						{
							leftmost_position = i;
							break;
						}
					}
				}

				if(leftmost_position == -1)
					break;

				// Scan for right delimiter.
				for(unsigned int i = position_of_click; i < bufstring.length(); ++i)
				{
					if(bufstring.at(i) == nppGUI._rightmostDelimiter)
					{
						// Respect escaped quotation marks.
						if(nppGUI._rightmostDelimiter == '"')
						{
							if(! (i > 0 && bufstring.at(i - 1) == '\\'))
							{
								rightmost_position = i;
								break;
							}
						}
						else
						{
							rightmost_position = i;
							break;
						}
					}
				}
			}
			else
			{
				// Find matching pairs of delimiters (e.g. parantheses).
				// The pair where the distance from the left delimiter to position_of_click is at a minimum is the one we're looking for.
				// Of course position_of_click must lie between the delimiters.

				// This logic is required to handle cases like this:
				// (size_t i = function(); i < _buffers.size(); i++)

				std::stack<unsigned int> leftmost_delimiter_positions;

				for(unsigned int i = 0; i < bufstring.length(); ++i)
				{
					if(bufstring.at(i) == nppGUI._leftmostDelimiter)
						leftmost_delimiter_positions.push(i);
					else if(bufstring.at(i) == nppGUI._rightmostDelimiter && ! leftmost_delimiter_positions.empty())
					{
						unsigned int matching_leftmost = leftmost_delimiter_positions.top();
						leftmost_delimiter_positions.pop();

						// We have either 1) chosen neither the left- or rightmost position, or 2) chosen both left- and rightmost position.
						assert( (leftmost_position == -1 && rightmost_position == -1) || (leftmost_position >= 0 && rightmost_position >= 0) );

						// Note: cast of leftmost_position to unsigned int is safe, since if leftmost_position is not -1 then it is guaranteed to be positive.
						// If it was possible, leftmost_position and rightmost_position should be of type optional<unsigned int>.
						if( matching_leftmost <= position_of_click && i >= position_of_click &&  (leftmost_position == -1 ||  matching_leftmost > (unsigned int)leftmost_position) )
						{
							leftmost_position = matching_leftmost;
							rightmost_position = i;
						}
					}
				}
			}

			// Set selection to the position we found (if any).
			if(rightmost_position != -1 && leftmost_position != -1)
			{
				if(nppGUI._delimiterSelectionOnEntireDocument)
				{
					notifyView->execute(SCI_SETCURRENTPOS, rightmost_position);
					notifyView->execute(SCI_SETANCHOR, leftmost_position + 1);
				}
				else
				{
					const int line_position = notifyView->execute(SCI_POSITIONFROMLINE, notifyView->getCurrentLineNumber());
					notifyView->execute(SCI_SETCURRENTPOS, line_position + rightmost_position);
					notifyView->execute(SCI_SETANCHOR, line_position + leftmost_position + 1);
				}
			}
		}
		else if (_isHotspotDblClicked)
		{
			int pos = notifyView->execute(SCI_GETCURRENTPOS);
			notifyView->execute(SCI_SETCURRENTPOS, pos);
			notifyView->execute(SCI_SETANCHOR, pos);
			_isHotspotDblClicked = false;
		}

		//display dialog, this dialog display current line information(ymj)
		//only my Log file need to display line info dialog
		//if(MainFileManager->isConvertFile())  //maybe have some problem
		BufferID id = _pEditView->getCurrentBufferID();
		
		if(id != BUFFER_INVALID)
		{
			Buffer *buf = MainFileManager->getBufferByID(id);

			if(buf->isConvertFile())
			{
				int tmpLength = notifyView->execute(SCI_GETCURLINE);
				if(tmpLength < (1024 * 8))
				{
					char *buf = _lineDetailInfoDlg.getLineContentBuf();
					memset(buf, 0x00, tmpLength + 1);
					notifyView->execute(SCI_GETCURLINE, (LPARAM)(tmpLength + 1), (WPARAM)buf);

					bool isFirstTime = !_lineDetailInfoDlg.isCreated();
					_lineDetailInfoDlg.doDialog(_nativeLangSpeaker.isRTL());
					if (isFirstTime)
						_nativeLangSpeaker.changeDlgLang(_lineDetailInfoDlg.getHSelf(), "LineInfo");

					_lineDetailInfoDlg.DisplayLineInfo(tmpLength);

					
				}
			}
		}
	}
	break;

	case SCN_UPDATEUI:
	{
		NppParameters *nppParam = NppParameters::getInstance();

		// replacement for obsolete custom SCN_SCROLLED
		if (notification->updated & SC_UPDATE_V_SCROLL)
		{
			int urlAction = (NppParameters::getInstance())->getNppGUI()._styleURL;
			if ((urlAction == 1) || (urlAction == 2))
				addHotSpot();
		}

		// if it's searching/replacing, then do nothing
		if (nppParam->_isFindReplacing)
			break;

		if (notification->nmhdr.hwndFrom != _pEditView->getHSelf())
			break;
		
        braceMatch();

		NppGUI & nppGui = (NppGUI &)nppParam->getNppGUI();

		if (nppGui._enableTagsMatchHilite)
		{
			XmlMatchedTagsHighlighter xmlTagMatchHiliter(_pEditView);
			xmlTagMatchHiliter.tagMatch(nppGui._enableTagAttrsHilite);
		}
		
		if (nppGui._enableSmartHilite)
		{
			if (nppGui._disableSmartHiliteTmp)
				nppGui._disableSmartHiliteTmp = false;
			else
				_smartHighlighter.highlightView(notifyView);
		}

		updateStatusBar();
		AutoCompletion * autoC = isFromPrimary?&_autoCompleteMain:&_autoCompleteSub;
		autoC->update(0);

        break;
	}

    case TTN_GETDISPINFO:
    {
		try {
			LPTOOLTIPTEXT lpttt = (LPTOOLTIPTEXT)notification; 

			//Joce's fix
			lpttt->hinst = NULL; 

			POINT p;
			::GetCursorPos(&p);
			::ScreenToClient(_pPublicInterface->getHSelf(), &p);
			HWND hWin = ::RealChildWindowFromPoint(_pPublicInterface->getHSelf(), p);
			const int tipMaxLen = 1024;
			static TCHAR docTip[tipMaxLen];
			docTip[0] = '\0';

			generic_string tipTmp(TEXT(""));
			int id = int(lpttt->hdr.idFrom);

			if (hWin == _rebarTop.getHSelf())
			{
				getNameStrFromCmd(id, tipTmp);
				if (tipTmp.length() >= 80)
					return FALSE;

				lstrcpy(lpttt->szText, tipTmp.c_str());
				return TRUE;
			}
			else if (hWin == _mainDocTab.getHSelf())
			{
				BufferID idd = _mainDocTab.getBufferByIndex(id);
				Buffer * buf = MainFileManager->getBufferByID(idd);
				tipTmp = buf->getFullPathName();

				if (tipTmp.length() >= tipMaxLen)
					return FALSE;
				lstrcpy(docTip, tipTmp.c_str());
				lpttt->lpszText = docTip;
				return TRUE;
			}
			else if (hWin == _subDocTab.getHSelf())
			{
				BufferID idd = _subDocTab.getBufferByIndex(id);
				Buffer * buf = MainFileManager->getBufferByID(idd);
				tipTmp = buf->getFullPathName();

				if (tipTmp.length() >= tipMaxLen)
					return FALSE;
				lstrcpy(docTip, tipTmp.c_str());
				lpttt->lpszText = docTip;
				return TRUE;
			}
			else
			{
				return FALSE;
			}
		} catch (...) {
			//printStr(TEXT("ToolTip crash is caught!"));
		}
    }
	break;


    case SCN_ZOOM:
		break;

    case SCN_MACRORECORD:
        _macro.push_back(recordedMacroStep(notification->message, notification->wParam, notification->lParam, _pEditView->execute(SCI_GETCODEPAGE)));
		break;

	case SCN_PAINTED:
	{
		//--FLS: ViewMoveAtWrappingDisableFix: Disable wrapping messes up visible lines. Therefore save view position before in IDM_VIEW_WRAP and restore after SCN_PAINTED, as doc. says
		if (_mainEditView.isWrapRestoreNeeded())
		{
			_mainEditView.restoreCurrentPos();
			_mainEditView.setWrapRestoreNeeded(false);
		}

		if (_subEditView.isWrapRestoreNeeded())
		{
			_subEditView.restoreCurrentPos();
			_subEditView.setWrapRestoreNeeded(false);
		}
		notifyView->updateLineNumberWidth();
		if (_syncInfo.doSync()) 
			doSynScorll(HWND(notification->nmhdr.hwndFrom));

		NppParameters *nppParam = NppParameters::getInstance();
		
		// if it's searching/replacing, then do nothing
		if ((_linkTriggered && !nppParam->_isFindReplacing) || notification->wParam == LINKTRIGGERED)
		{
			int urlAction = (NppParameters::getInstance())->getNppGUI()._styleURL;
			if ((urlAction == 1) || (urlAction == 2))
				addHotSpot();
			_linkTriggered = false;
		}

		if (_pDocMap)
		{
			_pDocMap->wrapMap();
			_pDocMap->scrollMap();
		}
		break;
	}

	case SCN_HOTSPOTDOUBLECLICK :
	{
		notifyView->execute(SCI_SETWORDCHARS, 0, (LPARAM)"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_-+.,:?&@=/%#()");
		
		int pos = notifyView->execute(SCI_GETCURRENTPOS);
		int startPos = static_cast<int>(notifyView->execute(SCI_WORDSTARTPOSITION, pos, false));
		int endPos = static_cast<int>(notifyView->execute(SCI_WORDENDPOSITION, pos, false));

		notifyView->execute(SCI_SETTARGETSTART, startPos);
		notifyView->execute(SCI_SETTARGETEND, endPos);
	
		int posFound = notifyView->execute(SCI_SEARCHINTARGET, strlen(URL_REG_EXPR), (LPARAM)URL_REG_EXPR);
		if (posFound != -2)
		{
			if (posFound != -1)
			{
				startPos = int(notifyView->execute(SCI_GETTARGETSTART));
				endPos = int(notifyView->execute(SCI_GETTARGETEND));
			}

			// Prevent buffer overflow in getGenericText().
			if(endPos - startPos > 2*MAX_PATH)
				endPos = startPos + 2*MAX_PATH;

			TCHAR currentWord[2*MAX_PATH];

			notifyView->getGenericText(currentWord, MAX_PATH*2, startPos, endPos);

			// This treatment would fail on some valid URLs where there's actually supposed to be a comma or parenthesis at the end.
			int lastCharIndex = _tcsnlen(currentWord, MAX_PATH*2) - 1;
			if(lastCharIndex >= 0 && (currentWord[lastCharIndex] == ',' || currentWord[lastCharIndex] == ')' || currentWord[lastCharIndex] == '('))
				currentWord[lastCharIndex] = '\0';

			::ShellExecute(_pPublicInterface->getHSelf(), TEXT("open"), currentWord, NULL, NULL, SW_SHOW);
			_isHotspotDblClicked = true;
			notifyView->execute(SCI_SETCHARSDEFAULT);
		}
		break;
	}

	case SCN_NEEDSHOWN :
	{
		int begin = notifyView->execute(SCI_LINEFROMPOSITION, notification->position);
		int end = notifyView->execute(SCI_LINEFROMPOSITION, notification->position + notification->length);
		int firstLine = begin < end ? begin : end;
		int lastLine = begin > end ? begin : end;
		for (int line = firstLine; line <= lastLine; ++line)
		{
			notifyView->execute(SCI_ENSUREVISIBLE, line, 0);
		}
		break;
	}

	case SCN_CALLTIPCLICK:
	{
		AutoCompletion * autoC = isFromPrimary?&_autoCompleteMain:&_autoCompleteSub;
		autoC->callTipClick(notification->position);
		break;
	}

	case RBN_HEIGHTCHANGE:
	{
		SendMessage(_pPublicInterface->getHSelf(), WM_SIZE, 0, 0);
		break;
	}
	case RBN_CHEVRONPUSHED:
	{
		NMREBARCHEVRON * lpnm = (NMREBARCHEVRON*) notification;
		ReBar * notifRebar = &_rebarTop;
		if (_rebarBottom.getHSelf() == lpnm->hdr.hwndFrom)
			notifRebar = &_rebarBottom;
		//If N++ ID, use proper object
		switch(lpnm->wID) {
			case REBAR_BAR_TOOLBAR: {
				POINT pt;
				pt.x = lpnm->rc.left;
				pt.y = lpnm->rc.bottom;
				ClientToScreen(notifRebar->getHSelf(), &pt);
				_toolBar.doPopop(pt);
				return TRUE;
				break; }
		}
		//Else forward notification to window of rebarband
		REBARBANDINFO rbBand;
		ZeroMemory(&rbBand, REBARBAND_SIZE);
		rbBand.cbSize  = REBARBAND_SIZE;

		rbBand.fMask = RBBIM_CHILD;
		::SendMessage(notifRebar->getHSelf(), RB_GETBANDINFO, lpnm->uBand, (LPARAM)&rbBand);
		::SendMessage(rbBand.hwndChild, WM_NOTIFY, 0, (LPARAM)lpnm);
		break;
	}

	default :
		break;

  }
  return FALSE;
}
コード例 #25
0
Container::Container(unsigned id, const char *cfg)
{
    m_bInit   = false;
    m_bInSize = false;
    m_bStatusSize = false;
    m_bBarChanged = false;
    m_bReceived = false;
    m_bNoSwitch = false;
    m_bNoRead   = false;
    m_wnds		= NULL;
    m_tabBar	= NULL;

    SET_WNDPROC("container")
    setWFlags(WDestructiveClose);

    if (cfg && *cfg){
        Buffer config;
        config << "[Title]\n" << cfg;
        config.setWritePos(0);
        config.getSection();
        load_data(containerData, &data, &config);
    }else{
        load_data(containerData, &data, NULL);
    }

    bool bPos = true;
    if (cfg == NULL){
        setId(id);
        memcpy(data.barState, CorePlugin::m_plugin->data.containerBar, sizeof(data.barState));
        memcpy(data.geometry, CorePlugin::m_plugin->data.containerGeo, sizeof(data.geometry));
        if ((data.geometry[WIDTH].value == (unsigned long)-1) || (data.geometry[HEIGHT].value == (unsigned long)-1)){
            QWidget *desktop = QApplication::desktop();
            data.geometry[WIDTH].value = desktop->width() / 3;
            data.geometry[HEIGHT].value = desktop->height() / 3;
        }
        bPos = false;
        if ((data.geometry[TOP].value != (unsigned long)-1) || (data.geometry[LEFT].value != (unsigned long)-1)){
            bPos = true;
            QWidgetList  *list = QApplication::topLevelWidgets();
            for (int i = 0; i < 2; i++){
                bool bOK = true;
                QWidgetListIt it(*list);
                QWidget * w;
                while ((w = it.current()) != NULL){
                    if (w == this){
                        ++it;
                        continue;
                    }
                    if (w->inherits("Container")){
                        int dw = w->pos().x() - data.geometry[LEFT].value;
                        int dh = w->pos().y() - data.geometry[TOP].value;
                        if (dw < 0) dw = -dw;
                        if (dh < 0) dh = -dh;
                        if ((dw < 3) && (dh < 3)){
                            int nl = data.geometry[LEFT].value;
                            int nt = data.geometry[TOP].value;
                            nl += 21;
                            nt += 20;
                            QWidget *desktop = QApplication::desktop();
                            if (nl + (int)data.geometry[WIDTH].value > desktop->width())
                                nl = 0;
                            if (nt + (int)data.geometry[WIDTH].value > desktop->width())
                                nt = 0;
                            if ((nl != (int)data.geometry[LEFT].value) && (nt != (int)data.geometry[TOP].value)){
                                data.geometry[LEFT].value = nl;
                                data.geometry[TOP].value  = nt;
                                bOK = false;
                            }
                        }
                    }
                    ++it;
                }
                if (bOK)
                    break;
            }
            delete list;
        }
        setStatusSize(CorePlugin::m_plugin->getContainerStatusSize());
    }
    m_bInSize = true;
    restoreGeometry(this, data.geometry, bPos, true);
    m_bInSize = false;
}
コード例 #26
0
	void EncryptionTestDialog::EncryptOrDecrypt (bool encrypt)
	{
		try
		{
			bool xts = XtsModeCheckBox->IsChecked();

			shared_ptr <EncryptionAlgorithm> ea = GetSelectedEncryptionAlgorithm();

			Buffer key;
			GetTextCtrlData (KeyTextCtrl, key);
			
			if (key.Size() != ea->GetKeySize())
				throw_err (LangString["TEST_KEY_SIZE"]);

			ea->SetKey (key);

			Buffer data;
			GetTextCtrlData (encrypt ? PlainTextTextCtrl : CipherTextTextCtrl, data);

			if (data.Size() != ea->GetMaxBlockSize())
				throw_err (LangString[encrypt ? "TEST_PLAINTEXT_SIZE" : "TEST_CIPHERTEXT_SIZE"]);

			if (xts)
			{
				Buffer secondaryKey;
				GetTextCtrlData (SecondaryKeyTextCtrl, secondaryKey);

				if (secondaryKey.Size() != ea->GetKeySize())
					throw_err (LangString["TEST_INCORRECT_SECONDARY_KEY_SIZE"]);

				uint64 dataUnitNumber;
				size_t blockNumber;

				try
				{
					dataUnitNumber = StringConverter::ToUInt64 (wstring (DataUnitNumberTextCtrl->GetValue()));
				}
				catch (...)
				{
					DataUnitNumberTextCtrl->SetFocus();
					throw StringConversionFailed (SRC_POS);
				}

				try
				{
					blockNumber = StringConverter::ToUInt32 (wstring (BlockNumberTextCtrl->GetValue()));
					if (blockNumber > 31)
					{
						blockNumber = 31;
						BlockNumberTextCtrl->SetValue (L"31");
					}
				}
				catch (...)
				{
					BlockNumberTextCtrl->SetFocus();
					throw StringConversionFailed (SRC_POS);
				}

				shared_ptr <EncryptionMode> xts (new EncryptionModeXTS);
				xts->SetKey (secondaryKey);
				ea->SetMode (xts);

				Buffer sector (ENCRYPTION_DATA_UNIT_SIZE);
				BufferPtr block = sector.GetRange (blockNumber * ea->GetMaxBlockSize(), ea->GetMaxBlockSize());
				
				block.CopyFrom (data);

				if (encrypt)
					ea->EncryptSectors (sector, dataUnitNumber, 1, sector.Size());
				else
					ea->DecryptSectors (sector, dataUnitNumber, 1, sector.Size());

				data.CopyFrom (block);
			}
			else
			{
				if (encrypt)
					ea->GetCiphers().front()->EncryptBlock (data);
				else
					ea->GetCiphers().front()->DecryptBlock (data);
			}

			SetTextCtrlData (encrypt ? CipherTextTextCtrl : PlainTextTextCtrl, data);
		}
		catch (exception &e)
		{
			Gui->ShowError (e);
		}
	}
コード例 #27
0
ファイル: Deployable.cpp プロジェクト: Ahava/evemu_server
void DeployableEntity::EncodeDestiny( Buffer& into ) const
{
    const GPoint& position = GetPosition();
    const std::string itemName( GetName() );

    /*if(m_orbitingID != 0) {
        #pragma pack(1)
        struct AddBall_Orbit {
            BallHeader head;
            MassSector mass;
            ShipSector ship;
            DSTBALL_ORBIT_Struct main;
            NameStruct name;
        };
        #pragma pack()

        into.resize(start
            + sizeof(AddBall_Orbit)
            + slen*sizeof(uint16) );
        uint8 *ptr = &into[start];
        AddBall_Orbit *item = (AddBall_Orbit *) ptr;
        ptr += sizeof(AddBall_Orbit);

        item->head.entityID = GetID();
        item->head.mode = Destiny::DSTBALL_ORBIT;
        item->head.radius = m_self->radius();
        item->head.x = x();
        item->head.y = y();
        item->head.z = z();
        item->head.sub_type = IsMassive | IsFree;

        item->mass.mass = m_self->mass();
        item->mass.unknown51 = 0;
        item->mass.unknown52 = 0xFFFFFFFFFFFFFFFFLL;
        item->mass.corpID = GetCorporationID();
        item->mass.unknown64 = 0xFFFFFFFF;

        item->ship.max_speed = m_self->maxVelocity();
        item->ship.velocity_x = m_self->maxVelocity();    //hacky hacky
        item->ship.velocity_y = 0.0;
        item->ship.velocity_z = 0.0;
        item->ship.agility = 1.0;    //hacky
        item->ship.speed_fraction = 0.133f;    //just strolling around. TODO: put in speed fraction!

        item->main.unknown116 = 0xFF;
        item->main.followID = m_orbitingID;
        item->main.followRange = 6000.0f;

        item->name.name_len = slen;    // in number of unicode chars
        //strcpy_fake_unicode(item->name.name, GetName());
    } else {
        BallHeader head;
        head.entityID = GetID();
        head.mode = Destiny::DSTBALL_STOP;
        head.radius = GetRadius();
        head.x = position.x;
        head.y = position.y;
        head.z = position.z;
        head.sub_type = IsMassive | IsFree;
        into.Append( head );

        MassSector mass;
        mass.mass = GetMass();
        mass.cloak = 0;
        mass.unknown52 = 0xFFFFFFFFFFFFFFFFLL;
        mass.corpID = GetCorporationID();
        mass.allianceID = GetAllianceID();
        into.Append( mass );

        ShipSector ship;
        ship.max_speed = GetMaxVelocity();
        ship.velocity_x = 0.0;
        ship.velocity_y = 0.0;
        ship.velocity_z = 0.0;
        ship.unknown_x = 0.0;
        ship.unknown_y = 0.0;
        ship.unknown_z = 0.0;
        ship.agility = GetAgility();
        ship.speed_fraction = 0.0;
        into.Append( ship );

        DSTBALL_STOP_Struct main;
        main.formationID = 0xFF;
        into.Append( main );

        const uint8 nameLen = utf8::distance( itemName.begin(), itemName.end() );
        into.Append( nameLen );

        const Buffer::iterator<uint16> name = into.end<uint16>();
        into.ResizeAt( name, nameLen );
        utf8::utf8to16( itemName.begin(), itemName.end(), name );
    }
*/
    BallHeader head;
    head.entityID = GetID();
    head.mode = Destiny::DSTBALL_RIGID;
    head.radius = GetRadius();
    head.x = position.x;
    head.y = position.y;
    head.z = position.z;
    head.sub_type = /*HasMiniBalls | */IsGlobal;
    into.Append( head );

    DSTBALL_RIGID_Struct main;
    main.formationID = 0xFF;
    into.Append( main );

/*
    const uint16 miniballsCount = 1;
    into.Append( miniballsCount );

    MiniBall miniball;
    miniball.x = -7701.181;
    miniball.y = 8060.06;
    miniball.z = 27878.900;
    miniball.radius = 1639.241;
    into.Append( miniball );
*/
}
コード例 #28
0
ファイル: ClusterMessage.cpp プロジェクト: crnt/scaliendb
bool ClusterMessage::Write(Buffer& buffer)
{
    Buffer          tempBuffer;
    
    switch (type)
    {
        case CLUSTERMESSAGE_SET_NODEID:
            buffer.Writef("%c:%U:%U",
             type, clusterID, nodeID);
            return true;
        case CLUSTERMESSAGE_UNREGISTER_STOP:
            buffer.Writef("%c",
             type);
            return true;
        case CLUSTERMESSAGE_HEARTBEAT:
            buffer.Writef("%c:%U:%u:%u",
             type, nodeID, httpPort, sdbpPort);
            buffer.Appendf(":");
            QuorumInfo::WriteList(buffer, quorumInfos);
            buffer.Appendf(":");
            QuorumShardInfo::WriteList(buffer, quorumShardInfos);
            return true;
        case CLUSTERMESSAGE_SET_CONFIG_STATE:
            buffer.Clear();
            return configState.Write(buffer, true);
        case CLUSTERMESSAGE_REQUEST_LEASE:
            buffer.Writef("%c:%U:%U:%U:%U:%U:%u",
             type, nodeID, quorumID, proposalID, paxosID, configID, duration);
            return true;
        case CLUSTERMESSAGE_RECEIVE_LEASE:
            buffer.Writef("%c:%U:%U:%U:%U:%u:%b",
             type, nodeID, quorumID, proposalID, configID, duration, watchingPaxosID);
            buffer.Appendf(":");
            MessageUtil::WriteIDList(activeNodes, buffer);
            buffer.Appendf(":");
            MessageUtil::WriteIDList(shards, buffer);
            return true;
        case CLUSTERMESSAGE_SHARDMIGRATION_INITIATE:
            buffer.Writef("%c:%U:%U:%U:%U",
             type, nodeID, quorumID, srcShardID, dstShardID);
            return true;
        case CLUSTERMESSAGE_SHARDMIGRATION_BEGIN:
            buffer.Writef("%c:%U:%U:%U",
             type, quorumID, srcShardID, dstShardID);
            return true;
        case CLUSTERMESSAGE_SHARDMIGRATION_SET:
            buffer.Writef("%c:%U:%U:%#R:%#R",
             type, quorumID, shardID, &key, &value);
            return true;
        case CLUSTERMESSAGE_SHARDMIGRATION_DELETE:
            buffer.Writef("%c:%U:%U:%#R",
             type, quorumID, shardID, &key);
            return true;
        case CLUSTERMESSAGE_SHARDMIGRATION_COMMIT:
            buffer.Writef("%c:%U:%U",
             type, quorumID, shardID);
            return true;
        case CLUSTERMESSAGE_SHARDMIGRATION_COMPLETE:
            buffer.Writef("%c:%U:%U",
             type, quorumID, shardID);
            return true;
        case CLUSTERMESSAGE_SHARDMIGRATION_PAUSE:
            buffer.Writef("%c",
             type);
            return true;
        case CLUSTERMESSAGE_SHARDMIGRATION_RESUME:
            buffer.Writef("%c",
             type);
            return true;
        case CLUSTERMESSAGE_HELLO:
            tempBuffer.Writef("ScalienDB cluster protocol, server version " VERSION_STRING);
            buffer.Writef("%c:%U:%#B",
             type, clusterID, &tempBuffer);
            return true;
        case CLUSTERMESSAGE_HTTP_ENDPOINT:
            buffer.Writef("%c:%U:%#R",
             type, nodeID, &endpoint);
            return true;
        default:
            return false;
    }
}
コード例 #29
0
ファイル: Buffer.cpp プロジェクト: katoun/kg_engine
void Buffer::copyData(Buffer& srcBuffer, unsigned int srcOffset, unsigned int dstOffset, unsigned int length, bool discardWholeBuffer)
{
	const void *srcData = srcBuffer.lock(srcOffset, length, BL_READ_ONLY);
	this->writeData(dstOffset, length, srcData, discardWholeBuffer);
	srcBuffer.unlock();
}
コード例 #30
0
	void WavFile::read(Buffer &buffer, size_t size)
	{
		buffer.set_size(size);
		if (fread(buffer.get_ptr(), 1, size, _f) != size)
			throw std::runtime_error("read failed");
	}