Exemplo n.º 1
0
void
PNamesBuilderImpl::writeCSourceFile(const char *path, UErrorCode &errorCode) {
    if(U_FAILURE(errorCode)) { return; }
    FILE *f=usrc_create(path, "propname_data.h",
                        "icu/tools/unicode/c/genprops/pnamesbuilder.cpp");
    if(f==NULL) {
        errorCode=U_FILE_ACCESS_ERROR;
        return;
    }

    fputs("#ifndef INCLUDED_FROM_PROPNAME_CPP\n"
          "#   error This file must be #included from propname.cpp only.\n"
          "#endif\n\n", f);

    fputs("U_NAMESPACE_BEGIN\n\n", f);

    usrc_writeArray(f, "const int32_t PropNameData::indexes[%ld]={",
                    indexes, 32, PropNameData::IX_COUNT,
                    "};\n\n");
    usrc_writeArray(f, "const int32_t PropNameData::valueMaps[%ld]={\n",
                    valueMaps.getBuffer(), 32, valueMaps.size(),
                    "\n};\n\n");
    usrc_writeArray(f, "const uint8_t PropNameData::bytesTries[%ld]={\n",
                    bytesTries.data(), 8, bytesTries.length(),
                    "\n};\n\n");
    usrc_writeArrayOfMostlyInvChars(
        f, "const char PropNameData::nameGroups[%ld]={\n",
        nameGroups.data(), nameGroups.length(),
        "\n};\n\n");

    fputs("U_NAMESPACE_END\n", f);

    fclose(f);
}
Error FileAccessNetwork::_open(const String& p_path, int p_mode_flags) {

	ERR_FAIL_COND_V(p_mode_flags!=READ,ERR_UNAVAILABLE);
	if (opened)
		close();
	FileAccessNetworkClient *nc = FileAccessNetworkClient::singleton;
	DEBUG_PRINT("open: "+p_path);

	DEBUG_TIME("open_begin");

	nc->lock_mutex();
	nc->put_32(id);
	nc->accesses[id]=this;
	nc->put_32(COMMAND_OPEN_FILE);
	CharString cs =p_path.utf8();
	nc->put_32(cs.length());
	nc->client->put_data((const uint8_t*)cs.ptr(),cs.length());
	pos=0;
	eof_flag=false;
	last_page=-1;
	last_page_buff=NULL;

//	buffers.clear();
	nc->unlock_mutex();
	DEBUG_PRINT("OPEN POST");
	DEBUG_TIME("open_post");
	nc->sem->post(); //awaiting answer
	DEBUG_PRINT("WAIT...");
	sem->wait();
	DEBUG_TIME("open_end");
	DEBUG_PRINT("WAIT ENDED...");

	return response;
}
Exemplo n.º 3
0
	bool operator==(const CharString& str1, const CharString& str2){
		int len = str1.length();
		if(len!=str2.length())
			return false;
		for(int i=0; i<len; i++){
			if(str1[i] != str2[i])
				return false;
		}
		return true;
	}
Exemplo n.º 4
0
	CharString operator+(const CharString& str1, const CharString& str2){
		CharString str;
		for(int i=0; i<str1.length(); i++){
			str.append(str1[i]);
		}
		for(int i=0; i<str2.length(); i++){
			str.append(str2[i]);
		}
		return str;
	}
Exemplo n.º 5
0
void FileAccessCompressed::close(){

	if (!f)
		return;


	if (writing) {
		//save block table and all compressed blocks

		CharString mgc = magic.utf8();
		f->store_buffer((const uint8_t*)mgc.get_data(),mgc.length()); //write header 4
		f->store_32(cmode); //write compression mode 4
		f->store_32(block_size); //write block size 4
		f->store_32(write_max); //max amount of data written 4
		int bc=(write_max/block_size)+1;

		for(int i=0;i<bc;i++) {
			f->store_32(0); //compressed sizes, will update later
		}


		Vector<int> block_sizes;
		for(int i=0;i<bc;i++) {

			int bl = i==(bc-1) ? write_max % block_size : block_size;
			uint8_t *bp = &write_ptr[i*block_size];

			Vector<uint8_t> cblock;
			cblock.resize(Compression::get_max_compressed_buffer_size(bl,cmode));
			int s = Compression::compress(cblock.ptr(),bp,bl,cmode);

			f->store_buffer(cblock.ptr(),s);
			block_sizes.push_back(s);
		}

		f->seek(16); //ok write block sizes
		for(int i=0;i<bc;i++)
			f->store_32(block_sizes[i]);
		f->seek_end();
		f->store_buffer((const uint8_t*)mgc.get_data(),mgc.length()); //magic at the end too

		buffer.clear();

	} else {


		comp_buffer.clear();
		buffer.clear();
		read_blocks.clear();
	}

	memdelete(f);
	f=NULL;

}
Exemplo n.º 6
0
	bool CharString::operator<(const CharString& str1) const{
		int len;
		if(str1.length() != length())
			return (str1.length() < length());//len = str1.length();
		else
			len = length();

		for(int i=0; i<len; i++){
			if(str1[i] == operator[](i))
				continue;
			return (str1[i] < operator[](i));
		}
		//identical
		return false;//str1IsShorter;
	}
Exemplo n.º 7
0
  bool Shader::link()
  {
    //Create a new program
    deleteProgram();
    program = new GLProgram;
    program->create();

    //Attach all the shaders and link the program
    attachShaders();
    bool status = program->link();

    if (status)
      printf ("Shading program linked.\n");
    else printf ("Failed linking shading program!\n");

    CharString infoLog = program->getInfoLog ();
    if (infoLog.length() > 0)
      printf ("Info Log:\n%s\n", infoLog.buffer());

    //Query attribute locations
    for (UintSize a=0; a<attribs.size(); ++a)
      attribs[a].ID = program->getAttribute( attribs[a].name.buffer() );

    //Query uniform locations
    for (UintSize u=0; u<uniforms.size(); ++u)
      uniforms[u].ID = program->getUniform( uniforms[u].name.buffer() );

    return status;
  }
Exemplo n.º 8
0
bool FileAccessNetwork::file_exists(const String &p_path) {

	FileAccessNetworkClient *nc = FileAccessNetworkClient::singleton;
	nc->lock_mutex();
	nc->put_32(id);
	nc->put_32(COMMAND_FILE_EXISTS);
	CharString cs = p_path.utf8();
	nc->put_32(cs.length());
	nc->client->put_data((const uint8_t *)cs.ptr(), cs.length());
	nc->unlock_mutex();
	DEBUG_PRINT("FILE EXISTS POST");
	nc->sem->post();
	sem->wait();

	return exists_modtime != 0;
}
Exemplo n.º 9
0
uint64_t FileAccessNetwork::_get_modified_time(const String &p_file) {

	FileAccessNetworkClient *nc = FileAccessNetworkClient::singleton;
	nc->lock_mutex();
	nc->put_32(id);
	nc->put_32(COMMAND_GET_MODTIME);
	CharString cs = p_file.utf8();
	nc->put_32(cs.length());
	nc->client->put_data((const uint8_t *)cs.ptr(), cs.length());
	nc->unlock_mutex();
	DEBUG_PRINT("MODTIME POST");
	nc->sem->post();
	sem->wait();

	return exists_modtime;
}
Exemplo n.º 10
0
Arquivo: export.cpp Projeto: ex/godot
void EditorExportPlatformJavaScript::_fix_html(Vector<uint8_t>& p_html, const String& p_name, bool p_debug) {


	String str;
	String strnew;
	str.parse_utf8((const char*)p_html.ptr(),p_html.size());
	Vector<String> lines=str.split("\n");
	for(int i=0;i<lines.size();i++) {

		String current_line = lines[i];
		current_line = current_line.replace("$GODOT_TMEM",itos((1<<(max_memory+5))*1024*1024));
		current_line = current_line.replace("$GODOT_FS",p_name+"fs.js");
		current_line = current_line.replace("$GODOT_MEM",p_name+".mem");
		current_line = current_line.replace("$GODOT_JS",p_name+".js");
		current_line = current_line.replace("$GODOT_CANVAS_WIDTH",Globals::get_singleton()->get("display/width"));
		current_line = current_line.replace("$GODOT_CANVAS_HEIGHT",Globals::get_singleton()->get("display/height"));
		current_line = current_line.replace("$GODOT_HEAD_TITLE",!html_title.empty()?html_title:(String) Globals::get_singleton()->get("application/name"));
		current_line = current_line.replace("$GODOT_HEAD_INCLUDE",html_head_include);
		current_line = current_line.replace("$GODOT_STYLE_FONT_FAMILY",html_font_family);
		current_line = current_line.replace("$GODOT_STYLE_INCLUDE",html_style_include);
		current_line = current_line.replace("$GODOT_CONTROLS_ENABLED",html_controls_enabled?"true":"false");
		current_line = current_line.replace("$GODOT_DEBUG_ENABLED",p_debug?"true":"false");
		strnew += current_line+"\n";
	}

	CharString cs = strnew.utf8();
	p_html.resize(cs.length());
	for(int i=9;i<cs.length();i++) {
		p_html[i]=cs[i];
	}
}
Exemplo n.º 11
0
  bool Shader::compile (ShaderType::Enum target, const CharString &source)
  {
    //Make sure old shaders are detached
    detachShaders();

    //Create a new shader
    GLShader *shader = new GLShader;
    shader->create( target );

    //Add to shader list
    switch (target) {
    case ShaderType::Vertex:
      vertShaders.pushBack( shader ); break;
    case ShaderType::Fragment:
      fragShaders.pushBack( shader ); break; }

    //Compile the source
    bool status = shader->compile( source );

    if (status)
      printf( "%s shader compiled.\n",
        target == ShaderType::Vertex ? "Vertex" : "Fragment" );
    else
      printf( "Failed compiling %s shader!",
        target == ShaderType::Vertex ? "vertex" : "fragment" );

    CharString infoLog = shader->getInfoLog ();
    if (infoLog.length() > 0)
      printf ("Info Log:\n%s\n", infoLog.buffer());

    return status;
  }
Exemplo n.º 12
0
Error HTTPClient::request_raw(Method p_method, const String &p_url, const Vector<String> &p_headers, const PoolVector<uint8_t> &p_body) {

	ERR_FAIL_INDEX_V(p_method, METHOD_MAX, ERR_INVALID_PARAMETER);
	ERR_FAIL_COND_V(status != STATUS_CONNECTED, ERR_INVALID_PARAMETER);
	ERR_FAIL_COND_V(connection.is_null(), ERR_INVALID_DATA);

	static const char *_methods[METHOD_MAX] = {
		"GET",
		"HEAD",
		"POST",
		"PUT",
		"DELETE",
		"OPTIONS",
		"TRACE",
		"CONNECT"
	};

	String request = String(_methods[p_method]) + " " + p_url + " HTTP/1.1\r\n";
	if ((ssl && conn_port == 443) || (!ssl && conn_port == 80)) {
		// don't append the standard ports
		request += "Host: " + conn_host + "\r\n";
	} else {
		request += "Host: " + conn_host + ":" + itos(conn_port) + "\r\n";
	}
	bool add_clen = p_body.size() > 0;
	for (int i = 0; i < p_headers.size(); i++) {
		request += p_headers[i] + "\r\n";
		if (add_clen && p_headers[i].find("Content-Length:") == 0) {
			add_clen = false;
		}
	}
	if (add_clen) {
		request += "Content-Length: " + itos(p_body.size()) + "\r\n";
		//should it add utf8 encoding? not sure
	}
	request += "\r\n";
	CharString cs = request.utf8();

	PoolVector<uint8_t> data;

	//Maybe this goes faster somehow?
	for (int i = 0; i < cs.length(); i++) {
		data.append(cs[i]);
	}
	data.append_array(p_body);

	PoolVector<uint8_t>::Read r = data.read();
	Error err = connection->put_data(&r[0], data.size());

	if (err) {
		close();
		status = STATUS_CONNECTION_ERROR;
		return err;
	}

	status = STATUS_REQUESTING;

	return OK;
}
Exemplo n.º 13
0
void FileAccess::store_string(const String &p_string) {

	if (p_string.length() == 0)
		return;

	CharString cs = p_string.utf8();
	store_buffer((uint8_t *)&cs[0], cs.length());
}
Exemplo n.º 14
0
	//find W(word) in S(sentence)
	//return the index of the first appearance
	//implementing KMP algorithm
	int CharString::indexOf(CharString W, int start) const{
		if(W.length() == 0)
			return NOT_FOUND;
		if(W.length() == 1)
			return indexOf(W[0], start);

		//first, make the table
		int* T = new int[W.length()];
		int pos=2, cnd=0;
		T[0] = -1;
		T[1] = 0;

		while(pos < W.length()){
			if(W[pos-1] == W[cnd]){
				cnd = cnd + 1;
				T[pos] = cnd;
				pos = pos + 1;
			}else if(cnd > 0){
				cnd = T[cnd];
			}else{
				T[pos] = 0;
				pos = pos + 1;
			}
		}


		//now let's do KMP 
		int m=start, i=0;
		while((m + i) < length()){
			if(W[i] == operator[](m+i)){
				if(i == W.length() - 1)
					return m;
				i = i + 1;
			}else{
				if(T[i] > -1){
					m = m + i - T[i];
					i = T[i];
				}else{
					i = 0;
					m = m + 1;
				}
			}
		}
		return NOT_FOUND;
	}
Exemplo n.º 15
0
Error HTTPClient::request(Method p_method, const String &p_url, const Vector<String> &p_headers, const String &p_body) {

	ERR_FAIL_INDEX_V(p_method, METHOD_MAX, ERR_INVALID_PARAMETER);
	ERR_FAIL_COND_V(!p_url.begins_with("/"), ERR_INVALID_PARAMETER);
	ERR_FAIL_COND_V(status != STATUS_CONNECTED, ERR_INVALID_PARAMETER);
	ERR_FAIL_COND_V(connection.is_null(), ERR_INVALID_DATA);

	String request = String(_methods[p_method]) + " " + p_url + " HTTP/1.1\r\n";
	if ((ssl && conn_port == PORT_HTTPS) || (!ssl && conn_port == PORT_HTTP)) {
		// Don't append the standard ports
		request += "Host: " + conn_host + "\r\n";
	} else {
		request += "Host: " + conn_host + ":" + itos(conn_port) + "\r\n";
	}
	bool add_uagent = true;
	bool add_accept = true;
	bool add_clen = p_body.length() > 0;
	for (int i = 0; i < p_headers.size(); i++) {
		request += p_headers[i] + "\r\n";
		if (add_clen && p_headers[i].findn("Content-Length:") == 0) {
			add_clen = false;
		}
		if (add_uagent && p_headers[i].findn("User-Agent:") == 0) {
			add_uagent = false;
		}
		if (add_accept && p_headers[i].findn("Accept:") == 0) {
			add_accept = false;
		}
	}
	if (add_clen) {
		request += "Content-Length: " + itos(p_body.utf8().length()) + "\r\n";
		// Should it add utf8 encoding?
	}
	if (add_uagent) {
		request += "User-Agent: GodotEngine/" + String(VERSION_FULL_BUILD) + " (" + OS::get_singleton()->get_name() + ")\r\n";
	}
	if (add_accept) {
		request += "Accept: */*\r\n";
	}
	request += "\r\n";
	request += p_body;

	CharString cs = request.utf8();
	Error err = connection->put_data((const uint8_t *)cs.ptr(), cs.length());
	if (err) {
		close();
		status = STATUS_CONNECTION_ERROR;
		return err;
	}

	status = STATUS_REQUESTING;

	return OK;
}
Exemplo n.º 16
0
static void _fix_files(Vector<uint8_t>& html,uint64_t p_data_size) {


	String str;
	String strnew;
	str.parse_utf8((const char*)html.ptr(),html.size());
	Vector<String> lines=str.split("\n");
	for(int i=0;i<lines.size();i++) {
		if (lines[i].find("$DPLEN")!=-1) {
			strnew+=lines[i].replace("$DPLEN",itos(p_data_size));
		} else {
			strnew+=lines[i]+"\n";
		}
	}

	CharString cs = strnew.utf8();
	html.resize(cs.length());
	for(int i=9;i<cs.length();i++) {
		html[i]=cs[i];
	}

}
Exemplo n.º 17
0
static void store_file_buffer(FileAccess*f,const String& p_path,const Vector<uint8_t>& p_data) {


    String pre = "Module['FS_createDataFile']('/', '"+p_path.replace("res://","")+"',[";
    CharString cs = pre.utf8();
    f->store_buffer((const uint8_t*)cs.ptr(),cs.length());
    for(int i=0; i<p_data.size(); i++) {


        uint8_t c=',';
        if (i>0)
            f->store_buffer(&c,1);

        uint8_t str[4];
        uint8_t d = p_data[i];
        if (d<10) {
            str[0]='0'+d;
            str[1]=0;
            f->store_buffer(str,1);
        } else if (d<100) {

            str[0]='0'+d/10;
            str[1]='0'+d%10;
            str[2]=0;
            f->store_buffer(str,2);

        } else {
            str[0]='0'+d/100;
            str[1]='0'+(d/10)%10;
            str[2]='0'+d%10;
            str[3]=0;
            f->store_buffer(str,3);
        }
    }
    String post = "],true,true);\n";
    cs = post.utf8();
    f->store_buffer((const uint8_t*)cs.ptr(),cs.length());
}
Exemplo n.º 18
0
void
PNamesBuilderImpl::writeBinaryData(const char *path, UBool withCopyright, UErrorCode &errorCode) {
    if(U_FAILURE(errorCode)) { return; }
    UNewDataMemory *pdata=udata_create(path, PNAME_DATA_TYPE, PNAME_DATA_NAME, &dataInfo,
                                       withCopyright ? U_COPYRIGHT_STRING : 0, &errorCode);
    if(U_FAILURE(errorCode)) {
        fprintf(stderr, "genprops: udata_create(%s, pnames.icu) failed - %s\n",
                path, u_errorName(errorCode));
        return;
    }

    udata_writeBlock(pdata, indexes, PropNameData::IX_COUNT*4);
    udata_writeBlock(pdata, valueMaps.getBuffer(), valueMaps.size()*4);
    udata_writeBlock(pdata, bytesTries.data(), bytesTries.length());
    udata_writeBlock(pdata, nameGroups.data(), nameGroups.length());

    int32_t dataLength=(int32_t)udata_finish(pdata, &errorCode);
    if(dataLength!=indexes[PropNameData::IX_TOTAL_SIZE]) {
        fprintf(stderr,
                "udata_finish(pnames.icu) reports %ld bytes written but should be %ld\n",
                (long)dataLength, (long)indexes[PropNameData::IX_TOTAL_SIZE]);
        errorCode=U_INTERNAL_PROGRAM_ERROR;
    }
}
Exemplo n.º 19
0
Error FileAccessNetworkClient::connect(const String& p_host,int p_port,const String& p_password) {

	IP_Address ip;

	if (p_host.is_valid_ip_address()) {
		ip=p_host;
	} else {
		ip=IP::get_singleton()->resolve_hostname(p_host);
	}

	DEBUG_PRINT("IP: "+String(ip)+" port "+itos(p_port));
	Error err = client->connect(ip,p_port);
	ERR_FAIL_COND_V(err,err);
	while(client->get_status()==StreamPeerTCP::STATUS_CONNECTING) {
//DEBUG_PRINT("trying to connect....");
		OS::get_singleton()->delay_usec(1000);
	}

	if (client->get_status()!=StreamPeerTCP::STATUS_CONNECTED) {
		return ERR_CANT_CONNECT;
	}

	CharString cs = p_password.utf8();	
	put_32(cs.length());
	client->put_data((const uint8_t*)cs.ptr(),cs.length());

	int e = get_32();

	if (e!=OK) {
		return ERR_INVALID_PARAMETER;
	}

	thread = Thread::create(_thread_func,this);

	return OK;
}
Exemplo n.º 20
0
inline int findMatchingLine( CharString & sText, int nPosition, CharString & sLine )
{
	int startPos = sText.reverseFind('\n',nPosition);	// left linebreak
	if( startPos > 0 )
		startPos++;		// Skip linebreak

	int endPos = sText.find( '\n', nPosition );				// right linebreak
	if( endPos < 0 )
		endPos = startPos+sText.length() - 1;

	sLine = sText.copy(sText);
	sLine.mid( startPos, ( endPos - startPos ) + 1 );

	return endPos + 1;
}
Exemplo n.º 21
0
String FileAccess::get_token() const {

	CharString token;

	CharType c = get_8();

	while (!eof_reached()) {

		if (c <= ' ') {
			if (token.length())
				break;
		} else {
			token += c;
		}
		c = get_8();
	}

	return String::utf8(token.get_data());
}
Exemplo n.º 22
0
U_DRAFT const char * U_EXPORT2
ufmt_getDecNumChars(UFormattable *fmt, int32_t *len, UErrorCode *status) {
  if(U_FAILURE(*status)) {
    return "";
  }
  Formattable *obj = Formattable::fromUFormattable(fmt);
  CharString *charString = obj->internalGetCharString(*status);
  if(U_FAILURE(*status)) {
    return "";
  }
  if(charString == NULL) {
    *status = U_MEMORY_ALLOCATION_ERROR;
    return "";
  } else {
    if(len!=NULL) {
      *len = charString->length();
    }
    return charString->data();
  }
}
Exemplo n.º 23
0
void EditorExportPlatformBB10::_fix_descriptor(Vector<uint8_t>& p_descriptor) {

	String fpath =  EditorSettings::get_singleton()->get_settings_path().plus_file("tmp_bar-settings.xml");
	{
		FileAccessRef f = FileAccess::open(fpath,FileAccess::WRITE);
		f->store_buffer(p_descriptor.ptr(),p_descriptor.size());
	}

	Ref<XMLParser> parser = memnew( XMLParser );
	Error err = parser->open(fpath);
	ERR_FAIL_COND(err!=OK);

	String txt;
	err = parser->read();
	Vector<String> depth;

	while(err!=ERR_FILE_EOF) {

		ERR_FAIL_COND(err!=OK);

		switch(parser->get_node_type()) {

			case XMLParser::NODE_NONE: {
				print_line("???");
			} break;
			case XMLParser::NODE_ELEMENT: {
				String e="<";
				e+=parser->get_node_name();
				for(int i=0;i<parser->get_attribute_count();i++) {
					e+=" ";
					e+=parser->get_attribute_name(i)+"=\"";
					e+=parser->get_attribute_value(i)+"\" ";
				}



				if (parser->is_empty()) {
					e+="/";
				} else {
					depth.push_back(parser->get_node_name());
				}

				e+=">";
				txt+=e;

			} break;
			case XMLParser::NODE_ELEMENT_END: {

				txt+="</"+parser->get_node_name()+">";
				if (depth.size() && depth[depth.size()-1]==parser->get_node_name()) {
					depth.resize(depth.size()-1);
				}


			} break;
			case XMLParser::NODE_TEXT: {
				if (depth.size()==2 && depth[0]=="qnx" && depth[1]=="id") {

					txt+=package;
				} else if (depth.size()==2 && depth[0]=="qnx" && depth[1]=="name") {

					String aname;
					if (this->name!="") {
						aname=this->name;
					} else {
						aname = GlobalConfig::get_singleton()->get("application/name");

					}

					if (aname=="") {
						aname=_MKSTR(VERSION_NAME);
					}

					txt+=aname;

				} else if (depth.size()==2 && depth[0]=="qnx" && depth[1]=="versionNumber") {
					txt+=itos(version_code);
				} else if (depth.size()==2 && depth[0]=="qnx" && depth[1]=="description") {
					txt+=description;
				} else if (depth.size()==2 && depth[0]=="qnx" && depth[1]=="author") {
					txt+=author_name;
				} else if (depth.size()==2 && depth[0]=="qnx" && depth[1]=="authorId") {
					txt+=author_id;
				} else if (depth.size()==2 && depth[0]=="qnx" && depth[1]=="category") {
					txt+=category;
				} else {
					txt+=parser->get_node_data();
				}
			} break;
			case XMLParser::NODE_COMMENT: {
				txt+="<!--"+parser->get_node_name()+"-->";
			} break;
			case XMLParser::NODE_CDATA: {
				//ignore
				//print_line("cdata");
			} break;
			case XMLParser::NODE_UNKNOWN: {
				//ignore
				txt+="<"+parser->get_node_name()+">";
			} break;
		}

		err = parser->read();
	}


	CharString cs = txt.utf8();
	p_descriptor.resize(cs.length());
	for(int i=0;i<cs.length();i++)
		p_descriptor[i]=cs[i];

}
Exemplo n.º 24
0
void StreamPeer::put_utf8_string(const String &p_string) {

	CharString cs = p_string.utf8();
	put_data((const uint8_t *)cs.get_data(), cs.length());
}
Exemplo n.º 25
0
void FileAccess::store_pascal_string(const String &p_string) {

	CharString cs = p_string.utf8();
	store_32(cs.length());
	store_buffer((uint8_t *)&cs[0], cs.length());
};
Exemplo n.º 26
0
Vector<uint8_t> GDTokenizerBuffer::parse_code_string(const String& p_code) {

	Vector<uint8_t> buf;


	Map<StringName,int> identifier_map;
	HashMap<Variant,int,VariantHasher> constant_map;
	Map<uint32_t,int> line_map;
	Vector<uint32_t> token_array;

	GDTokenizerText tt;
	tt.set_code(p_code);
	int line=-1;
	int col=0;

	while(true) {

		if (tt.get_token_line()!=line) {

			line=tt.get_token_line();
			line_map[line]=token_array.size();
		}

		uint32_t token=tt.get_token();
		switch(tt.get_token()) {

			case TK_IDENTIFIER: {
				StringName id = tt.get_token_identifier();
				if (!identifier_map.has(id)) {
					int idx = identifier_map.size();
					identifier_map[id]=idx;
				}
				token|=identifier_map[id]<<TOKEN_BITS;
			} break;
			case TK_CONSTANT: {

				Variant c = tt.get_token_constant();
				if (!constant_map.has(c)) {
					int idx = constant_map.size();
					constant_map[c]=idx;
				}
				token|=constant_map[c]<<TOKEN_BITS;
			} break;
			case TK_BUILT_IN_TYPE: {

				token|=tt.get_token_type()<<TOKEN_BITS;
			} break;
			case TK_BUILT_IN_FUNC: {

				token|=tt.get_token_built_in_func()<<TOKEN_BITS;

			} break;
			case TK_NEWLINE: {

				token|=tt.get_token_line_indent()<<TOKEN_BITS;
			} break;
			case TK_ERROR: {

				ERR_FAIL_V(Vector<uint8_t>());
			} break;
			default: {}

		};

		token_array.push_back(token);

		if (tt.get_token()==TK_EOF)
			break;
		tt.advance();

	}

	//reverse maps

	Map<int,StringName> rev_identifier_map;
	for(Map<StringName,int>::Element *E=identifier_map.front();E;E=E->next()) {
		rev_identifier_map[E->get()]=E->key();
	}

	Map<int,Variant> rev_constant_map;
	const Variant *K =NULL;
	while((K=constant_map.next(K))) {
		rev_constant_map[constant_map[*K]]=*K;
	}

	Map<int,uint32_t> rev_line_map;
	for(Map<uint32_t,int>::Element *E=line_map.front();E;E=E->next()) {
		rev_line_map[E->get()]=E->key();
	}

	//save header
	buf.resize(24);
	buf[0]='G';
	buf[1]='D';
	buf[2]='S';
	buf[3]='C';
	encode_uint32(BYTECODE_VERSION,&buf[4]);
	encode_uint32(identifier_map.size(),&buf[8]);
	encode_uint32(constant_map.size(),&buf[12]);
	encode_uint32(line_map.size(),&buf[16]);
	encode_uint32(token_array.size(),&buf[20]);

	//save identifiers

	for(Map<int,StringName>::Element *E=rev_identifier_map.front();E;E=E->next()) {

		CharString cs = String(E->get()).utf8();
		int len = cs.length()+1;
		int extra = 4-(len%4);
		if (extra==4)
			extra=0;

		uint8_t ibuf[4];
		encode_uint32(len+extra,ibuf);
		for(int i=0;i<4;i++) {
			buf.push_back(ibuf[i]);
		}
		for(int i=0;i<len;i++) {
			buf.push_back(cs[i]^0xb6);
		}
		for(int i=0;i<extra;i++) {
			buf.push_back(0^0xb6);
		}
	}

	for(Map<int,Variant>::Element *E=rev_constant_map.front();E;E=E->next()) {

		int len;
		Error err = encode_variant(E->get(),NULL,len);
		ERR_FAIL_COND_V(err!=OK,Vector<uint8_t>());
		int pos=buf.size();
		buf.resize(pos+len);
		encode_variant(E->get(),&buf[pos],len);
	}

	for(Map<int,uint32_t>::Element *E=rev_line_map.front();E;E=E->next()) {

		uint8_t ibuf[8];
		encode_uint32(E->key(),&ibuf[0]);
		encode_uint32(E->get(),&ibuf[4]);
		for(int i=0;i<8;i++)
			buf.push_back(ibuf[i]);
	}

	for(int i=0;i<token_array.size();i++) {

		uint32_t token = token_array[i];

		if (token&~TOKEN_MASK) {
			uint8_t buf4[4];
			encode_uint32(token_array[i]|TOKEN_BYTE_MASK,&buf4[0]);
			for(int j=0;j<4;j++) {
				buf.push_back(buf4[j]);
			}
		} else {
			buf.push_back(token);
		}
	}

	return buf;

}
Exemplo n.º 27
0
void OS_X11::process_xevents() {

	//printf("checking events %i\n", XPending(x11_display));

	bool do_mouse_warp=false;

	while (XPending(x11_display) > 0) {
		XEvent event;
		XNextEvent(x11_display, &event);

		switch (event.type) {
		case Expose:
			Main::force_redraw();
			break;

		case NoExpose:
			minimized = true;
			break;

		case VisibilityNotify: {

			XVisibilityEvent * visibility = (XVisibilityEvent *)&event;
			minimized = (visibility->state == VisibilityFullyObscured);

		} break;

		case FocusIn:
			main_loop->notification(MainLoop::NOTIFICATION_WM_FOCUS_IN);
			if (mouse_mode==MOUSE_MODE_CAPTURED) {
				XGrabPointer(x11_display, x11_window, True,
						    ButtonPressMask | ButtonReleaseMask |
						    PointerMotionMask, GrabModeAsync, GrabModeAsync,
						    x11_window, None, CurrentTime);
			}
			break;

		case FocusOut:
			main_loop->notification(MainLoop::NOTIFICATION_WM_FOCUS_OUT);
			if (mouse_mode==MOUSE_MODE_CAPTURED) {
				//dear X11, I try, I really try, but you never work, you do whathever you want.
				XUngrabPointer(x11_display, CurrentTime);
			}
			break;

		case ConfigureNotify:
		/* call resizeGLScene only if our window-size changed */
		
			if ((event.xconfigure.width == current_videomode.width) && 
			(event.xconfigure.height == current_videomode.height))
				break;
				
			current_videomode.width=event.xconfigure.width;
			current_videomode.height=event.xconfigure.height;
			break;
		case ButtonPress:
		case ButtonRelease: {
			
			/* exit in case of a mouse button press */
			last_timestamp=event.xbutton.time;
			if (mouse_mode==MOUSE_MODE_CAPTURED) {
				event.xbutton.x=last_mouse_pos.x;
				event.xbutton.y=last_mouse_pos.y;
			}
			
			InputEvent mouse_event;
			mouse_event.ID=++event_id;
			mouse_event.type = InputEvent::MOUSE_BUTTON;
			mouse_event.device=0;
			mouse_event.mouse_button.mod = get_key_modifier_state(event.xbutton.state);
			mouse_event.mouse_button.button_mask = get_mouse_button_state(event.xbutton.state);
			mouse_event.mouse_button.x=event.xbutton.x;
			mouse_event.mouse_button.y=event.xbutton.y;
			mouse_event.mouse_button.global_x=event.xbutton.x;
			mouse_event.mouse_button.global_y=event.xbutton.y;
			mouse_event.mouse_button.button_index=event.xbutton.button;
			if (mouse_event.mouse_button.button_index==2)
				mouse_event.mouse_button.button_index=3;
			else if (mouse_event.mouse_button.button_index==3)
				mouse_event.mouse_button.button_index=2;
				
			mouse_event.mouse_button.pressed=(event.type==ButtonPress);


			if (event.type==ButtonPress && event.xbutton.button==1) {
				
				uint64_t diff = get_ticks_usec()/1000 - last_click_ms;

				if (diff<400 && Point2(last_click_pos).distance_to(Point2(event.xbutton.x,event.xbutton.y))<5) {
					
					last_click_ms=0;
					last_click_pos = Point2(-100,-100);
					mouse_event.mouse_button.doubleclick=true;					
					mouse_event.ID=++event_id;
					
				} else {
					last_click_ms+=diff;	
					last_click_pos = Point2(event.xbutton.x,event.xbutton.y);
				}
			}		

			input->parse_input_event( mouse_event);

			
		} break;	
		case MotionNotify: {
						
			
			last_timestamp=event.xmotion.time;
			
			// Motion is also simple.
			// A little hack is in order
			// to be able to send relative motion events.
			
			Point2i pos( event.xmotion.x, event.xmotion.y );

			if (mouse_mode==MOUSE_MODE_CAPTURED) {
#if 1
				Vector2 c = Point2i(current_videomode.width/2,current_videomode.height/2);
				if (pos==Point2i(current_videomode.width/2,current_videomode.height/2)) {
					//this sucks, it's a hack, etc and is a little inaccurate, etc.
					//but nothing I can do, X11 sucks.

					center=pos;
					break;
				}

				Point2i ncenter = pos;
				pos = last_mouse_pos + ( pos-center );
				center=ncenter;
				do_mouse_warp=true;
#else
				//Dear X11, thanks for making my life miserable

				center.x = current_videomode.width/2;
				center.y = current_videomode.height/2;
				pos = last_mouse_pos + ( pos-center );
				if (pos==last_mouse_pos)
					break;
				XWarpPointer(x11_display, None, x11_window,
					      0,0,0,0, (int)center.x, (int)center.y);
#endif

			}

			
			if (!last_mouse_pos_valid) {
				
				last_mouse_pos=pos;
				last_mouse_pos_valid=true;
			}
			
			Point2i rel = pos - last_mouse_pos;
			
			InputEvent motion_event;
			motion_event.ID=++event_id;
			motion_event.type=InputEvent::MOUSE_MOTION;
			motion_event.device=0;
			
			motion_event.mouse_motion.mod = get_key_modifier_state(event.xmotion.state);
			motion_event.mouse_motion.button_mask = get_mouse_button_state(event.xmotion.state);
			motion_event.mouse_motion.x=pos.x;
			motion_event.mouse_motion.y=pos.y;
			input->set_mouse_pos(pos);
			motion_event.mouse_motion.global_x=pos.x;
			motion_event.mouse_motion.global_y=pos.y;
			motion_event.mouse_motion.speed_x=input->get_mouse_speed().x;
			motion_event.mouse_motion.speed_y=input->get_mouse_speed().y;

			motion_event.mouse_motion.relative_x=rel.x;
			motion_event.mouse_motion.relative_y=rel.y;
						
			last_mouse_pos=pos;
			
			input->parse_input_event( motion_event);
			
		} break;			
		case KeyPress: 
		case KeyRelease: {

			last_timestamp=event.xkey.time;
				
			// key event is a little complex, so
			// it will be handled in it's own function.
			handle_key_event( (XKeyEvent*)&event );
		} break;			
		case SelectionRequest: {

			XSelectionRequestEvent *req;
			XEvent e, respond;
			e = event;

			req=&(e.xselectionrequest);
			if (req->target == XA_STRING || req->target == XInternAtom(x11_display, "COMPOUND_TEXT", 0) ||
				req->target == XInternAtom(x11_display, "UTF8_STRING", 0))
			{
				CharString clip = OS::get_clipboard().utf8();
				XChangeProperty (x11_display,
					req->requestor,
					req->property,
					req->target,
					8,
					PropModeReplace,
					(unsigned char*)clip.get_data(),
					clip.length());
				respond.xselection.property=req->property;
			} else if (req->target == XInternAtom(x11_display, "TARGETS", 0)) {

				Atom data[2];
				data[0] = XInternAtom(x11_display, "UTF8_STRING", 0);
				data[1] = XA_STRING;
				XChangeProperty (x11_display, req->requestor, req->property, req->target,
						 8, PropModeReplace, (unsigned char *) &data,
						 sizeof (data));
				respond.xselection.property=req->property;

			} else {
				printf ("No String %x\n",
					(int)req->target);
				respond.xselection.property= None;
			}
			respond.xselection.type= SelectionNotify;
			respond.xselection.display= req->display;
			respond.xselection.requestor= req->requestor;
			respond.xselection.selection=req->selection;
			respond.xselection.target= req->target;
			respond.xselection.time = req->time;
			XSendEvent (x11_display, req->requestor,0,0,&respond);
			XFlush (x11_display);
		} break;


		case ClientMessage:    
		
			if ((unsigned int)event.xclient.data.l[0]==(unsigned int)wm_delete)
				main_loop->notification(MainLoop::NOTIFICATION_WM_QUIT_REQUEST);
			break;
		default:
			break;
		}
	}
	
	XFlush(x11_display);

	if (do_mouse_warp) {

		XWarpPointer(x11_display, None, x11_window,
			      0,0,0,0, (int)current_videomode.width/2, (int)current_videomode.height/2);

	}
}
Exemplo n.º 28
0
//----------------------------------------------------------------------------
CharString ProcessServer::searchLogFiles( CharString sFilemask, CharString sSearch, bool bRegExp, char nSearchLevel,
									 bool bResolveClients )
{
	CharString sResult;
	
	RegExpM rxSearch;
	RegExpM rxClientId, rxLogin;
	Tree< unsigned int, String > trClientLookup;

	sSearch.lower();	// all search is performed case insensitive

	if( bRegExp )
		rxSearch.regComp( sSearch );

	if( bResolveClients )
		rxClientId.regComp( STR("[Cc]lient ([0-9]+)[, ]") );
	

	FindFile ff;
	CharString sMask = CharString().format("./Logs/%s.log",sFilemask.cstr());
	ff.findFiles( sMask, false, false );	// sorted by date

	int nTotalFoundSize = 0;
	int nTotalSearchedSize = 0;
	int nTotalFilesSearched = 0;
	CharString sLine;
	dword tStart = Time::seconds();
	bool bAbort = false;

	// search through all found files
	for( int i = 0 ; i < ff.fileCount() && !bAbort ; i++ )
	{
		CharString sLocalFile( ff.file( i ) );

		if( nSearchLevel == 2 )		// only list the files, not search them ?
		{
			CharString sFile = CharString().format("./Logs/%s", sLocalFile.cstr()) ;
			sResult += String().format("*** [%s] *** %s\r\n", Time::format( FileDisk::fileDate( sFile ),"%c").cstr(), sLocalFile.cstr() );

			continue;
		}
		
		bool fileNamePrintedYet = false;
		CharString sText;
		CharString sTextOrig;
		int nCurPos = 0;
		try {
			CharString sFile = CharString().format("./Logs/%s",sLocalFile.cstr() );
			char * pTemp = FileDisk::loadTextFile( sFile );
			sText.copy( pTemp ).lower();	// pText is all lowercase, as it's used for case insensitive search
			sTextOrig = CharString().format("%s", pTemp );		// pTextOrig is orig-case, as it's used to build sResult
			delete pTemp;

			int nTextLen = sText.length();
			nTotalSearchedSize += nTextLen;
			nTotalFilesSearched++;

			int pos = -1;
			// loop to find all occurences of the string
			while( nCurPos < nTextLen && ( pos = findString( sText, nCurPos, sSearch, &rxSearch, bRegExp )  ) >= 0 )
			{
				if( !fileNamePrintedYet )
				{
					if( nSearchLevel == 0 )
						sResult += STR("\r\n\r\n");

					CharString sFile = CharString().format("./Logs/%s", sLocalFile.cstr()) ;
					sResult += String().format("*** [%s] *** %s\r\n", Time::format( FileDisk::fileDate( sFile ),"%c").cstr(), sLocalFile.cstr() );

					fileNamePrintedYet = true;
				}
				
				if( nSearchLevel == 1 )		// only check if there is a match in the file at all ?
					break;
				
				// find the matching line, this time in the original-case text
				nCurPos = findMatchingLine( sTextOrig, nCurPos + pos, sLine );	
				
				// need to resolve clientIds when found ?
				if( bResolveClients )
				{
					int nClientIdPos = rxClientId.regFind( sLine );
					if( nClientIdPos >= 0 )		// line holds a clientId ?
					{
						int nClientIdLen = rxClientId.getFindLen() - 8;	// match length - static chars

						// extract the clientId
						CharString sClientId = sLine;
						sClientId.right( sClientId.length() - ( nClientIdPos + 7 ) );
						sClientId.left( nClientIdLen );
						
						int nClientId = CharString::strint(sClientId);
						CharString sResolvedClient(STR(""));
						if( trClientLookup.find( nClientId ).valid() )	// know this clientId already ?
						{
							sResolvedClient = trClientLookup[ nClientId ];
						}
						else
						{
							// haven't seen it yet. Look it up.
							rxLogin.regComp( String().format( STR("\n../../.. ..:..:.. : Login client %d user ([^,\n]+), userId = ([0-9]+), "), nClientId ) );
							if( rxLogin.regFind( sTextOrig ) >= 0 )
							{
								sResolvedClient = rxLogin.getReplaceString( STR(" ( \\1 @\\2 )") );
							}
							else
							{
								// not found yet ? Try alternate way to resolve it
								rxLogin.regComp( String().format( STR("\n../../.. ..:..:.. : Client %d login, id = ([^\r]+)"), nClientId ) );
								if( rxLogin.regFind( sTextOrig ) >= 0 )
								{
									sResolvedClient = rxLogin.getReplaceString( STR(" ( \\1 )") );
								}	// no further "else". If it's not found the result is left blank
							}	

							trClientLookup[ nClientId ] = sResolvedClient;
						}

						if( sResolvedClient != "" )		// got something to insert ?
							sLine.insert( sResolvedClient, nClientIdPos + nClientIdLen + 7 );
					}
				}	// done resolving clientId

				// add the found line to the result
				nTotalFoundSize += sLine.length();
				sResult += sLine;
				
				// abort conditions
				if( nTotalFoundSize > 300000 )
				{
					sResult += STR("\r\n\r\n*** Result too large, search aborted");
					bAbort = true;
					break;
				}

			}
		}
		catch( ... )
		{
			return STR("Failed");
		}
	}

	if( sResult.length() == 0 )
		sResult = STR("No results");
	else
		sResult += STR("\r\nDone...");
	
	sResult += CharString().format( STR("\r\nSearched %d file(s) containing %d bytes within %d seconds. Result is %d bytes."),
		nTotalFilesSearched, nTotalSearchedSize, Time::seconds() - tStart, nTotalFoundSize );
	
	return sResult;
}
Exemplo n.º 29
0
int main( int argc, char ** argv )
{
	CharString iniFile = "./ProcessServer.ini";
	if ( argc > 1 )
		iniFile = argv[1];

	Settings settings( "ProcessServer", iniFile );
	
	// initialize the logging first thing before we do anything else..
	std::string logFile( settings.get( "logFile", "ProcessServer.log" ) );
	std::string logExclude( settings.get( "logExclude", "" ) );
	unsigned int nMinLogLevel = settings.get( "logLevel", LL_STATUS );
	new FileReactor( logFile, nMinLogLevel, logExclude );

	bool bRemoteUpdate = settings.get( "remoteUpdate", 1 ) != 0;
	bool bLocalUpdate = settings.get( "localUpdate", (dword)0 ) != 0;

	CharString sPath( FileDisk::currentDirectory() );
	if (! sPath.endsWith( PATH_SEPERATOR ) )
		sPath += PATH_SEPERATOR;

#if !defined(_DEBUG)
	// update the files
	if ( settings.get( "doUpdate", 1 ) != 0 )
	{
		settings.put( "doUpdate", (dword)0 );

		if ( bLocalUpdate )
		{
			CharString updatePath = settings.get( "localUpdatePath", "" );
			if ( updatePath.length() > 0 )
			{
				FileDisk::normalizePath( updatePath.buffer() );
				if (! updatePath.endsWith( PATH_SEPERATOR ) )
					updatePath += PATH_SEPERATOR;

				// copy the files from a directory
				if ( localUpdate( sPath, updatePath ) )
					return -3;		// let the service/script update our files..
			}
		}
	}
#endif

	// do the update next time!
	settings.put( "doUpdate", 1 );

	ProcessServer::Context context;
	context.logFile = logFile.c_str();
	context.name = settings.get( "name", "ProcessServer" );
	context.config = iniFile;
	context.gameId = settings.get( "gameId", 1 );
	context.processGroup = settings.get( "processGroup", 1 );
	context.networkGroup = settings.get( "networkGroup", 1 );
	context.metaAddress = settings.get( "metaAddress", "meta-server.palestar.com" );
	context.metaPort = settings.get( "metaPort", 9000 );
	context.uid = settings.get( "uid", "DSS" );
	context.pw = settings.get( "pw", "darkspace" );
	context.address = settings.get( "address", "" );
	context.port = settings.get( "port", 8000 );
	context.maxClients = settings.get( "maxClients", 1000 );
	context.processFile = iniFile;
	context.syncClock = settings.get ("syncClock", (dword)0 ) != 0;

	// start the server
	MyProcessServer theServer;
	if (! theServer.start( context ) )
		return -1;

	// signal that we are running
	Event serverRunning( "ProcessServerRun" );
	serverRunning.signal();

	dword nNextUpdateCheck = Time::seconds() + settings.get("updateTime",300);
	dword nLastCRC = 0;

	// run the server forever, unless it crashes
	Event serverStop( "ProcessServerStop" );
	while( theServer.running() && !theServer.shutdownCompleted() )
	{
		if (! serverStop.wait( 10 ) )
		{
			LOG_STATUS( "ProcessServer", "Recevied shutdown signal." );
			theServer.shutdown();

			serverStop.clear();
		}

		theServer.update();
		theServer.updatePerformanceMonitor();

#if !defined(_DEBUG)
		if ( bRemoteUpdate && nNextUpdateCheck < Time::seconds() )
		{
			// check for new code update
			MirrorClient mirrorClient;
			if ( mirrorClient.open( 
				settings.get( "mirrorAddress", "mirror-server.palestar.com" ),
				settings.get( "mirrorPort", 9200 ), sPath, NULL, true ) )
			{
				// attempt to login, ingore if failed
				mirrorClient.login( settings.get( "uid", "" ), settings.get( "pw", "" ) );

				// get the CRC only, only do a sync if remote files have been changed...
				dword nCRC = mirrorClient.getCRC();
				if ( nCRC != nLastCRC )
				{
					nLastCRC = nCRC;

					dword nJobID = mirrorClient.syncronize();
					if ( nJobID != 0 && mirrorClient.waitJob( nJobID, 86400 * 1000 ) )
					{
						int nWarningTime = settings.get( "warningTime", 300 );

						LOG_STATUS( "ProcessServer", "Files updated -- Restarting the server in %d seconds.", nWarningTime );

						CharString sWarningMessage = settings.get( "warningMessage", 
							CharString().format("/notice /%s Updating in $T...", context.name.cstr() ) );
						while( nWarningTime > 0 )
						{
							CharString sTimeLeft;
							sTimeLeft.format("%d %s", 
								nWarningTime > 60 ? nWarningTime / 60 : nWarningTime,
								nWarningTime > 60 ? "minute(s)" : "second(s)");

							// replace the "$T" token with the time remaining...
							CharString sChat = sWarningMessage;
							sChat.replace( "$T", sTimeLeft );

							theServer.sendChat( sChat );

							int nSleepTime = 0;
							if ( nWarningTime > (60 * 10) )
								nSleepTime = 60 * 5;			// sleep for 5 minutes
							else
								nSleepTime = 60;				// sleep for 1 minute

							if ( nSleepTime > nWarningTime )
								nSleepTime = nWarningTime;

							nWarningTime -= nSleepTime;

							dword nEndSleep = Time::seconds() + nSleepTime;
							while( Time::seconds() < nEndSleep )
							{
								if (! serverStop.wait( 10 ) )
								{
									LOG_STATUS( "ProcessServer", "Received stop signal, stopping now." );
									nSleepTime = nWarningTime = 0;		// stop now... no warning
									break;
								}

								theServer.update();
								theServer.updatePerformanceMonitor();
							}
						}

						// start the shutdown, server will exit once the last process has stopped..
						theServer.shutdown();
					}
				}
				mirrorClient.close();
			}
			else
			{
				LOG_ERROR( "ProcessServer", "Failed to connect to MirrorServer!" );
			}
		

			nNextUpdateCheck = Time::seconds() + settings.get("updateTime",300);
		}
#endif
	}

	theServer.stop();

	return 0;
}
Exemplo n.º 30
0
void OS_X11::process_xevents() {

	//printf("checking events %i\n", XPending(x11_display));

	do_mouse_warp=false;

	while (XPending(x11_display) > 0) {
		XEvent event;
		XNextEvent(x11_display, &event);

		switch (event.type) {
		case Expose:
			Main::force_redraw();
			break;

		case NoExpose:
			minimized = true;
			break;

		case VisibilityNotify: {
			XVisibilityEvent * visibility = (XVisibilityEvent *)&event;
			minimized = (visibility->state == VisibilityFullyObscured);
		} break;
		case LeaveNotify: {

			if (main_loop && mouse_mode!=MOUSE_MODE_CAPTURED)
				main_loop->notification(MainLoop::NOTIFICATION_WM_MOUSE_EXIT);
			if (input)
				input->set_mouse_in_window(false);

		} break;
		case EnterNotify: {

			if (main_loop && mouse_mode!=MOUSE_MODE_CAPTURED)
				main_loop->notification(MainLoop::NOTIFICATION_WM_MOUSE_ENTER);
			if (input)
				input->set_mouse_in_window(true);
		} break;
		case FocusIn:
			minimized = false;
#ifdef NEW_WM_API
			if(current_videomode.fullscreen) {
				set_wm_fullscreen(true);
			}
#endif
			main_loop->notification(MainLoop::NOTIFICATION_WM_FOCUS_IN);
			if (mouse_mode==MOUSE_MODE_CAPTURED) {
				XGrabPointer(x11_display, x11_window, True,
						    ButtonPressMask | ButtonReleaseMask |
						    PointerMotionMask, GrabModeAsync, GrabModeAsync,
						    x11_window, None, CurrentTime);
			}
			break;

		case FocusOut:
#ifdef NEW_WM_API
			if(current_videomode.fullscreen) {
				set_wm_fullscreen(false);
				set_window_minimized(true);
			}
#endif
			main_loop->notification(MainLoop::NOTIFICATION_WM_FOCUS_OUT);
			if (mouse_mode==MOUSE_MODE_CAPTURED) {
				//dear X11, I try, I really try, but you never work, you do whathever you want.
				XUngrabPointer(x11_display, CurrentTime);
			}
			break;

		case ConfigureNotify:
		/* call resizeGLScene only if our window-size changed */

			if ((event.xconfigure.width == current_videomode.width) &&
			(event.xconfigure.height == current_videomode.height))
				break;

			current_videomode.width=event.xconfigure.width;
			current_videomode.height=event.xconfigure.height;
			break;
		case ButtonPress:
		case ButtonRelease: {

			/* exit in case of a mouse button press */
			last_timestamp=event.xbutton.time;
			if (mouse_mode==MOUSE_MODE_CAPTURED) {
				event.xbutton.x=last_mouse_pos.x;
				event.xbutton.y=last_mouse_pos.y;
			}

			InputEvent mouse_event;
			mouse_event.ID=++event_id;
			mouse_event.type = InputEvent::MOUSE_BUTTON;
			mouse_event.device=0;
			mouse_event.mouse_button.mod = get_key_modifier_state(event.xbutton.state);
			mouse_event.mouse_button.button_mask = get_mouse_button_state(event.xbutton.state);
			mouse_event.mouse_button.x=event.xbutton.x;
			mouse_event.mouse_button.y=event.xbutton.y;
			mouse_event.mouse_button.global_x=event.xbutton.x;
			mouse_event.mouse_button.global_y=event.xbutton.y;
			mouse_event.mouse_button.button_index=event.xbutton.button;
			if (mouse_event.mouse_button.button_index==2)
				mouse_event.mouse_button.button_index=3;
			else if (mouse_event.mouse_button.button_index==3)
				mouse_event.mouse_button.button_index=2;

			mouse_event.mouse_button.pressed=(event.type==ButtonPress);


			if (event.type==ButtonPress && event.xbutton.button==1) {

				uint64_t diff = get_ticks_usec()/1000 - last_click_ms;

				if (diff<400 && Point2(last_click_pos).distance_to(Point2(event.xbutton.x,event.xbutton.y))<5) {

					last_click_ms=0;
					last_click_pos = Point2(-100,-100);
					mouse_event.mouse_button.doubleclick=true;
					mouse_event.ID=++event_id;

				} else {
					last_click_ms+=diff;
					last_click_pos = Point2(event.xbutton.x,event.xbutton.y);
				}
			}

			input->parse_input_event( mouse_event);


		} break;
		case MotionNotify: {

			// F**K YOU X11 API YOU SERIOUSLY GROSS ME OUT
			// YOU ARE AS GROSS AS LOOKING AT A PUTRID PILE
			// OF POOP STICKING OUT OF A CLOGGED TOILET
			// HOW THE F**K I AM SUPPOSED TO KNOW WHICH ONE
			// OF THE MOTION NOTIFY EVENTS IS THE ONE GENERATED
			// BY WARPING THE MOUSE POINTER?
			// YOU ARE FORCING ME TO FILTER ONE BY ONE TO FIND IT
			// PLEASE DO ME A FAVOR AND DIE DROWNED IN A FECAL
			// MOUNTAIN BECAUSE THAT'S WHERE YOU BELONG.


			while(true) {
				if (mouse_mode==MOUSE_MODE_CAPTURED && event.xmotion.x==current_videomode.width/2 && event.xmotion.y==current_videomode.height/2) {
					//this is likely the warp event since it was warped here
					center=Vector2(event.xmotion.x,event.xmotion.y);
					break;
				}

				if (XPending(x11_display) > 0) {
					XEvent tevent;
					XPeekEvent(x11_display, &tevent);
					if (tevent.type==MotionNotify) {
						XNextEvent(x11_display,&event);
					} else {
						break;
					}
				} else {
					break;
				}
			}

			last_timestamp=event.xmotion.time;

			// Motion is also simple.
			// A little hack is in order
			// to be able to send relative motion events.
			Point2i pos( event.xmotion.x, event.xmotion.y );

			if (mouse_mode==MOUSE_MODE_CAPTURED) {
#if 1
				//Vector2 c = Point2i(current_videomode.width/2,current_videomode.height/2);
				if (pos==Point2i(current_videomode.width/2,current_videomode.height/2)) {
					//this sucks, it's a hack, etc and is a little inaccurate, etc.
					//but nothing I can do, X11 sucks.

					center=pos;
					break;
				}

				Point2i new_center = pos;
				pos = last_mouse_pos + ( pos - center );
				center=new_center;
				do_mouse_warp=true;
#else
				//Dear X11, thanks for making my life miserable

				center.x = current_videomode.width/2;
				center.y = current_videomode.height/2;
				pos = last_mouse_pos + ( pos-center );
				if (pos==last_mouse_pos)
					break;
				XWarpPointer(x11_display, None, x11_window,
					      0,0,0,0, (int)center.x, (int)center.y);
#endif
			}

			if (!last_mouse_pos_valid) {

				last_mouse_pos=pos;
				last_mouse_pos_valid=true;
			}

			Point2i rel = pos - last_mouse_pos;

#ifdef NEW_WM_API
			if (mouse_mode==MOUSE_MODE_CAPTURED) {
				pos.x = current_videomode.width / 2;
				pos.y = current_videomode.height / 2;
			}
#endif

			InputEvent motion_event;
			motion_event.ID=++event_id;
			motion_event.type=InputEvent::MOUSE_MOTION;
			motion_event.device=0;

			motion_event.mouse_motion.mod = get_key_modifier_state(event.xmotion.state);
			motion_event.mouse_motion.button_mask = get_mouse_button_state(event.xmotion.state);
			motion_event.mouse_motion.x=pos.x;
			motion_event.mouse_motion.y=pos.y;
			input->set_mouse_pos(pos);
			motion_event.mouse_motion.global_x=pos.x;
			motion_event.mouse_motion.global_y=pos.y;
			motion_event.mouse_motion.speed_x=input->get_mouse_speed().x;
			motion_event.mouse_motion.speed_y=input->get_mouse_speed().y;

			motion_event.mouse_motion.relative_x=rel.x;
			motion_event.mouse_motion.relative_y=rel.y;

			last_mouse_pos=pos;

			// printf("rel: %d,%d\n", rel.x, rel.y );

			input->parse_input_event( motion_event);

		} break;
		case KeyPress:
		case KeyRelease: {

			last_timestamp=event.xkey.time;

			// key event is a little complex, so
			// it will be handled in it's own function.
			handle_key_event( (XKeyEvent*)&event );
		} break;
		case SelectionRequest: {

			XSelectionRequestEvent *req;
			XEvent e, respond;
			e = event;

			req=&(e.xselectionrequest);
			if (req->target == XA_STRING || req->target == XInternAtom(x11_display, "COMPOUND_TEXT", 0) ||
				req->target == XInternAtom(x11_display, "UTF8_STRING", 0))
			{
				CharString clip = OS::get_clipboard().utf8();
				XChangeProperty (x11_display,
					req->requestor,
					req->property,
					req->target,
					8,
					PropModeReplace,
					(unsigned char*)clip.get_data(),
					clip.length());
				respond.xselection.property=req->property;
			} else if (req->target == XInternAtom(x11_display, "TARGETS", 0)) {

				Atom data[2];
				data[0] = XInternAtom(x11_display, "UTF8_STRING", 0);
				data[1] = XA_STRING;
				XChangeProperty (x11_display, req->requestor, req->property, req->target,
						 8, PropModeReplace, (unsigned char *) &data,
						 sizeof (data));
				respond.xselection.property=req->property;

			} else {
				printf ("No String %x\n",
					(int)req->target);
				respond.xselection.property= None;
			}
			respond.xselection.type= SelectionNotify;
			respond.xselection.display= req->display;
			respond.xselection.requestor= req->requestor;
			respond.xselection.selection=req->selection;
			respond.xselection.target= req->target;
			respond.xselection.time = req->time;
			XSendEvent (x11_display, req->requestor,0,0,&respond);
			XFlush (x11_display);
		} break;


		case ClientMessage:

			if ((unsigned int)event.xclient.data.l[0]==(unsigned int)wm_delete)
				main_loop->notification(MainLoop::NOTIFICATION_WM_QUIT_REQUEST);
			break;
		default:
			break;
		}
	}

	XFlush(x11_display);

	if (do_mouse_warp) {

		XWarpPointer(x11_display, None, x11_window,
		 	      0,0,0,0, (int)current_videomode.width/2, (int)current_videomode.height/2);

		/*
		Window root, child;
		int root_x, root_y;
		int win_x, win_y;
		unsigned int mask;
		XQueryPointer( x11_display, x11_window, &root, &child, &root_x, &root_y, &win_x, &win_y, &mask );

		printf("Root: %d,%d\n", root_x, root_y);
		printf("Win: %d,%d\n", win_x, win_y);
		*/
	}
}