示例#1
0
Error DirAccess::copy(String p_from, String p_to, int p_chmod_flags) {

	//printf("copy %s -> %s\n",p_from.ascii().get_data(),p_to.ascii().get_data());
	Error err;
	FileAccess *fsrc = FileAccess::open(p_from, FileAccess::READ, &err);

	if (err) {
		ERR_PRINTS("Failed to open " + p_from);
		return err;
	}

	FileAccess *fdst = FileAccess::open(p_to, FileAccess::WRITE, &err);
	if (err) {

		fsrc->close();
		memdelete(fsrc);
		ERR_PRINTS("Failed to open " + p_to);
		return err;
	}

	fsrc->seek_end(0);
	int size = fsrc->get_position();
	fsrc->seek(0);
	err = OK;
	while (size--) {

		if (fsrc->get_error() != OK) {
			err = fsrc->get_error();
			break;
		}
		if (fdst->get_error() != OK) {
			err = fdst->get_error();
			break;
		}

		fdst->store_8(fsrc->get_8());
	}

	if (err == OK && p_chmod_flags != -1) {
		fdst->close();
		err = FileAccess::set_unix_permissions(p_to, p_chmod_flags);
		// If running on a platform with no chmod support (i.e., Windows), don't fail
		if (err == ERR_UNAVAILABLE)
			err = OK;
	}

	memdelete(fsrc);
	memdelete(fdst);

	return err;
}
示例#2
0
void FindInFiles::_scan_file(String fpath) {

	FileAccess *f = FileAccess::open(fpath, FileAccess::READ);
	if (f == NULL) {
		print_verbose(String("Cannot open file ") + fpath);
		return;
	}

	int line_number = 0;

	while (!f->eof_reached()) {

		// line number starts at 1
		++line_number;

		int begin = 0;
		int end = 0;

		String line = f->get_line();

		while (find_next(line, _pattern, end, _match_case, _whole_words, begin, end)) {
			emit_signal(SIGNAL_RESULT_FOUND, fpath, line_number, begin, end, line);
		}
	}

	f->close();
}
示例#3
0
void FindInFilesPanel::apply_replaces_in_file(String fpath, const Vector<Result> &locations, String new_text) {

	// If the file is already open, I assume the editor will reload it.
	// If there are unsaved changes, the user will be asked on focus,
	// however that means either losing changes or losing replaces.

	FileAccess *f = FileAccess::open(fpath, FileAccess::READ);
	ERR_FAIL_COND(f == NULL);

	String buffer;
	int current_line = 1;

	ConservativeGetLine conservative;

	String line = conservative.get_line(f);
	String search_text = _finder->get_search_text();

	int offset = 0;

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

		int repl_line_number = locations[i].line_number;

		while (current_line < repl_line_number) {
			buffer += line;
			line = conservative.get_line(f);
			++current_line;
			offset = 0;
		}

		int repl_begin = locations[i].begin + offset;
		int repl_end = locations[i].end + offset;

		int _;
		if (!find_next(line, search_text, repl_begin, _finder->is_match_case(), _finder->is_whole_words(), _, _)) {
			// Make sure the replace is still valid in case the file was tampered with.
			print_verbose(String("Occurrence no longer matches, replace will be ignored in {0}: line {1}, col {2}").format(varray(fpath, repl_line_number, repl_begin)));
			continue;
		}

		line = line.left(repl_begin) + new_text + line.right(repl_end);
		// keep an offset in case there are successive replaces in the same line
		offset += new_text.length() - (repl_end - repl_begin);
	}

	buffer += line;

	while (!f->eof_reached()) {
		buffer += conservative.get_line(f);
	}

	// Now the modified contents are in the buffer, rewrite the file with our changes

	Error err = f->reopen(fpath, FileAccess::WRITE);
	ERR_FAIL_COND(err != OK);

	f->store_string(buffer);

	f->close();
}
示例#4
0
Error ResourceFormatSaverShader::save(const String &p_path, const RES &p_resource, uint32_t p_flags) {

	Ref<Shader> shader = p_resource;
	ERR_FAIL_COND_V(shader.is_null(), ERR_INVALID_PARAMETER);

	String source = shader->get_code();

	Error err;
	FileAccess *file = FileAccess::open(p_path, FileAccess::WRITE, &err);

	if (err) {

		ERR_FAIL_COND_V(err, err);
	}

	file->store_string(source);
	if (file->get_error() != OK && file->get_error() != ERR_FILE_EOF) {
		memdelete(file);
		return ERR_CANT_CREATE;
	}
	file->close();
	memdelete(file);

	return OK;
}
示例#5
0
void EditorFileSystem::_save_filesystem_cache() {
	String fscache = EditorSettings::get_singleton()->get_project_settings_path().plus_file("filesystem_cache2");

	FileAccess *f = FileAccess::open(fscache, FileAccess::WRITE);
	_save_filesystem_cache(filesystem, f);
	f->close();
	memdelete(f);
}
示例#6
0
int AudioStreamPlaybackOGGVorbis::_ov_close_func(void *_f) {

	//printf("close %p\n",_f);
	if (!_f)
		return 0;
	FileAccess *fa = (FileAccess *)_f;
	if (fa->is_open())
		fa->close();
	return 0;
}
示例#7
0
void FindInFilesPanel::apply_replaces_in_file(String fpath, PoolIntArray locations, String text) {

	ERR_FAIL_COND(locations.size() % 3 != 0);

	//print_line(String("Replacing {0} occurrences in {1}").format(varray(fpath, locations.size() / 3)));

	// If the file is already open, I assume the editor will reload it.
	// If there are unsaved changes, the user will be asked on focus,
	// however that means either loosing changes or loosing replaces.

	FileAccess *f = FileAccess::open(fpath, FileAccess::READ);
	ERR_FAIL_COND(f == NULL);

	String buffer;
	int current_line = 1;

	ConservativeGetLine conservative;

	String line = conservative.get_line(f);

	PoolIntArray::Read locations_read = locations.read();
	for (int i = 0; i < locations.size(); i += 3) {

		int repl_line_number = locations_read[i];
		int repl_begin = locations_read[i + 1];
		int repl_end = locations_read[i + 2];

		while (current_line < repl_line_number) {
			buffer += line;
			line = conservative.get_line(f);
			++current_line;
		}

		line = line.left(repl_begin) + text + line.right(repl_end);
	}

	buffer += line;

	while (!f->eof_reached()) {
		buffer += conservative.get_line(f);
	}

	// Now the modified contents are in the buffer, rewrite the file with our changes

	Error err = f->reopen(fpath, FileAccess::WRITE);
	ERR_FAIL_COND(err != OK);

	f->store_string(buffer);

	f->close();
}
示例#8
0
MainLoop *test() {

	print_line("this is test io");
	DirAccess *da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
	da->change_dir(".");
	print_line("Opening current dir " + da->get_current_dir());
	String entry;
	da->list_dir_begin();
	while ((entry = da->get_next()) != "") {

		print_line("entry " + entry + " is dir: " + Variant(da->current_is_dir()));
	};
	da->list_dir_end();

	RES texture = ResourceLoader::load("test_data/rock.png");
	ERR_FAIL_COND_V(texture.is_null(), NULL);

	ResourceSaver::save("test_data/rock.xml", texture);

	print_line("localize paths");
	print_line(ProjectSettings::get_singleton()->localize_path("algo.xml"));
	print_line(ProjectSettings::get_singleton()->localize_path("c:\\windows\\algo.xml"));
	print_line(ProjectSettings::get_singleton()->localize_path(ProjectSettings::get_singleton()->get_resource_path() + "/something/something.xml"));
	print_line(ProjectSettings::get_singleton()->localize_path("somedir/algo.xml"));

	{

		FileAccess *z = FileAccess::open("test_data/archive.zip", FileAccess::READ);
		int len = z->get_len();
		Vector<uint8_t> zip;
		zip.resize(len);
		z->get_buffer(&zip[0], len);
		z->close();
		memdelete(z);

		FileAccessMemory::register_file("a_package", zip);
		FileAccess::make_default<FileAccessMemory>(FileAccess::ACCESS_RESOURCES);
		FileAccess::make_default<FileAccessMemory>(FileAccess::ACCESS_FILESYSTEM);
		FileAccess::make_default<FileAccessMemory>(FileAccess::ACCESS_USERDATA);

		print_line("archive test");
	};

	print_line("test done");

	return memnew(TestMainLoop);
}
示例#9
0
void FindInFiles::_scan_file(String fpath) {

	FileAccess *f = FileAccess::open(fpath, FileAccess::READ);
	if (f == NULL) {
		print_line(String("Cannot open file ") + fpath);
		return;
	}

	int line_number = 0;

	while (!f->eof_reached()) {

		// line number starts at 1
		++line_number;

		int begin = 0;
		int end = 0;

		String line = f->get_line();

		// Find all occurrences in the current line
		while (true) {
			begin = _match_case ? line.find(_pattern, end) : line.findn(_pattern, end);

			if (begin == -1)
				break;

			end = begin + _pattern.length();

			if (_whole_words) {
				if (begin > 0 && is_text_char(line[begin - 1])) {
					continue;
				}
				if (end < line.size() && is_text_char(line[end])) {
					continue;
				}
			}

			emit_signal(SIGNAL_RESULT_FOUND, fpath, line_number, begin, end, line);
		}
	}

	f->close();
}
示例#10
0
Error DirAccess::copy(String p_from,String p_to) {

	//printf("copy %s -> %s\n",p_from.ascii().get_data(),p_to.ascii().get_data());
	Error err;
	FileAccess *fsrc = FileAccess::open(p_from, FileAccess::READ,&err);

	if (err) {

		ERR_FAIL_COND_V( err, err );
	}


	FileAccess *fdst = FileAccess::open(p_to, FileAccess::WRITE,&err );
	if (err) {

		fsrc->close();
		memdelete( fsrc );
		ERR_FAIL_COND_V( err, err );
	}

	fsrc->seek_end(0);
	int size = fsrc->get_pos();
	fsrc->seek(0);
	err = OK;
	while(size--) {

		if (fsrc->get_error()!=OK) {
			err= fsrc->get_error();
			break;
		}
		if (fdst->get_error()!=OK) {
			err= fdst->get_error();
			break;
		}

		fdst->store_8( fsrc->get_8() );
	}

	memdelete(fsrc);
	memdelete(fdst);

	return err;
}
示例#11
0
Error DotNetSolution::save() {
	bool dir_exists = DirAccess::exists(path);
	ERR_EXPLAIN("The directory does not exist.");
	ERR_FAIL_COND_V(!dir_exists, ERR_FILE_NOT_FOUND);

	String projs_decl;
	String sln_platform_cfg;
	String proj_platform_cfg;

	for (Map<String, ProjectInfo>::Element *E = projects.front(); E; E = E->next()) {
		const String &name = E->key();
		const ProjectInfo &proj_info = E->value();

		bool is_front = E == projects.front();

		if (!is_front)
			projs_decl += "\n";

		projs_decl += sformat(PROJECT_DECLARATION, name, proj_info.relpath.replace("/", "\\"), proj_info.guid);

		for (int i = 0; i < proj_info.configs.size(); i++) {
			const String &config = proj_info.configs[i];

			if (i != 0 || !is_front) {
				sln_platform_cfg += "\n";
				proj_platform_cfg += "\n";
			}

			sln_platform_cfg += sformat(SOLUTION_PLATFORMS_CONFIG, config);
			proj_platform_cfg += sformat(PROJECT_PLATFORMS_CONFIG, proj_info.guid, config);
		}
	}

	String content = sformat(SOLUTION_TEMPLATE, projs_decl, sln_platform_cfg, proj_platform_cfg);

	FileAccess *file = FileAccess::open(path_join(path, name + ".sln"), FileAccess::WRITE);
	ERR_FAIL_NULL_V(file, ERR_FILE_CANT_WRITE);
	file->store_string(content);
	file->close();
	memdelete(file);

	return OK;
}
示例#12
0
文件: resource.cpp 项目: Zylann/godot
void ResourceCache::dump(const char *p_file, bool p_short) {
#ifdef DEBUG_ENABLED
	lock->read_lock();

	Map<String, int> type_count;

	FileAccess *f = NULL;
	if (p_file) {
		f = FileAccess::open(p_file, FileAccess::WRITE);
		ERR_FAIL_COND(!f);
	}

	const String *K = NULL;
	while ((K = resources.next(K))) {

		Resource *r = resources[*K];

		if (!type_count.has(r->get_class())) {
			type_count[r->get_class()] = 0;
		}

		type_count[r->get_class()]++;

		if (!p_short) {
			if (f)
				f->store_line(r->get_class() + ": " + r->get_path());
		}
	}

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

		if (f)
			f->store_line(E->key() + " count: " + itos(E->get()));
	}
	if (f) {
		f->close();
		memdelete(f);
	}

	lock->read_unlock();

#endif
}
示例#13
0
Error PCKPacker::add_file(const String& p_file, const String& p_src) {

	FileAccess* f = FileAccess::open(p_src, FileAccess::READ);
	if (!f) {
		return ERR_FILE_CANT_OPEN;
	};

	File pf;
	pf.path = p_file;
	pf.src_path = p_src;
	pf.size = f->get_len();
	pf.offset_offset = 0;

	files.push_back(pf);

	f->close();
	memdelete(f);

	return OK;
};
示例#14
0
Error read_all_file_utf8(const String &p_path, String &r_content) {
	PoolVector<uint8_t> sourcef;
	Error err;
	FileAccess *f = FileAccess::open(p_path, FileAccess::READ, &err);
	ERR_FAIL_COND_V(err != OK, err);

	int len = f->get_len();
	sourcef.resize(len + 1);
	PoolVector<uint8_t>::Write w = sourcef.write();
	int r = f->get_buffer(w.ptr(), len);
	f->close();
	memdelete(f);
	ERR_FAIL_COND_V(r != len, ERR_CANT_OPEN);
	w[len] = 0;

	String source;
	if (source.parse_utf8((const char *)w.ptr())) {
		ERR_FAIL_V(ERR_INVALID_DATA);
	}

	r_content = source;
	return OK;
}
示例#15
0
文件: theme.cpp 项目: nitpum/godot
RES ResourceFormatLoaderTheme::load(const String &p_path, const String& p_original_path, Error *r_error) {
    if (r_error)
        *r_error=ERR_CANT_OPEN;

    Error err;
    FileAccess *f = FileAccess::open(p_path,FileAccess::READ,&err);

    ERR_EXPLAIN("Unable to open theme file: "+p_path);
    ERR_FAIL_COND_V(err,RES());
    String base_path = p_path.get_base_dir();
    Ref<Theme> theme( memnew( Theme ) );
    Map<StringName,Variant> library;
    if (r_error)
        *r_error=ERR_FILE_CORRUPT;

    bool reading_library=false;
    int line=0;

    while(!f->eof_reached()) {

        String l = f->get_line().strip_edges();
        line++;

        int comment = l.find(";");
        if (comment!=-1)
            l=l.substr(0,comment);
        if (l=="")
            continue;

        if (l.begins_with("[")) {
            if (l=="[library]") {
                reading_library=true;
            }  else if (l=="[theme]") {
                reading_library=false;
            } else {
                memdelete(f);
                ERR_EXPLAIN(p_path+":"+itos(line)+": Unknown section type: '"+l+"'.");
                ERR_FAIL_V(RES());
            }
            continue;
        }

        int eqpos = l.find("=");
        if (eqpos==-1) {
            memdelete(f);
            ERR_EXPLAIN(p_path+":"+itos(line)+": Expected '='.");
            ERR_FAIL_V(RES());
        }


        String right=l.substr(eqpos+1,l.length()).strip_edges();
        if (right=="") {
            memdelete(f);
            ERR_EXPLAIN(p_path+":"+itos(line)+": Expected value after '='.");
            ERR_FAIL_V(RES());
        }

        Variant value;

        if (right.is_valid_integer()) {
            //is number
            value = right.to_int();
        } else if (right.is_valid_html_color()) {
            //is html color
            value = Color::html(right);
        } else if (right.begins_with("@")) { //reference

            String reference = right.substr(1,right.length());
            if (!library.has(reference)) {
                memdelete(f);
                ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid reference to '"+reference+"'.");
                ERR_FAIL_V(RES());

            }

            value=library[reference];

        } else if (right.begins_with("default")) { //use default
            //do none
        } else {
            //attempt to parse a constructor
            int popenpos = right.find("(");

            if (popenpos==-1) {
                memdelete(f);
                ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid constructor syntax: "+right);
                ERR_FAIL_V(RES());
            }

            int pclosepos = right.find_last(")");

            if (pclosepos==-1) {
                ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid constructor parameter syntax: "+right);
                ERR_FAIL_V(RES());

            }

            String type = right.substr(0,popenpos);
            String param = right.substr(popenpos+1,pclosepos-popenpos-1);



            if (type=="icon") {

                String path;

                if (param.is_abs_path())
                    path=param;
                else
                    path=base_path+"/"+param;

                Ref<Texture> texture = ResourceLoader::load(path);
                if (!texture.is_valid()) {
                    memdelete(f);
                    ERR_EXPLAIN(p_path+":"+itos(line)+": Couldn't find icon at path: "+path);
                    ERR_FAIL_V(RES());
                }

                value=texture;

            } else if (type=="sbox") {

                String path;

                if (param.is_abs_path())
                    path=param;
                else
                    path=base_path+"/"+param;

                Ref<StyleBox> stylebox = ResourceLoader::load(path);
                if (!stylebox.is_valid()) {
                    memdelete(f);
                    ERR_EXPLAIN(p_path+":"+itos(line)+": Couldn't find stylebox at path: "+path);
                    ERR_FAIL_V(RES());
                }

                value=stylebox;

            } else if (type=="sboxt") {

                Vector<String> params = param.split(",");
                if (params.size()!=5 && params.size()!=9) {
                    memdelete(f);
                    ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid param count for sboxt(): '"+right+"'.");
                    ERR_FAIL_V(RES());

                }

                String path=params[0];

                if (!param.is_abs_path())
                    path=base_path+"/"+path;

                Ref<Texture> tex = ResourceLoader::load(path);
                if (tex.is_null()) {
                    memdelete(f);
                    ERR_EXPLAIN(p_path+":"+itos(line)+": Could not open texture for sboxt at path: '"+params[0]+"'.");
                    ERR_FAIL_V(RES());

                }

                Ref<StyleBoxTexture> sbtex( memnew(StyleBoxTexture) );

                sbtex->set_texture(tex);

                for(int i=0; i<4; i++) {
                    if (!params[i+1].is_valid_integer()) {

                        memdelete(f);
                        ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid expand margin parameter for sboxt #"+itos(i+1) +", expected integer constant, got: '"+params[i+1]+"'.");
                        ERR_FAIL_V(RES());
                    }

                    int margin = params[i+1].to_int();
                    sbtex->set_expand_margin_size(Margin(i),margin);
                }

                if (params.size()==9) {

                    for(int i=0; i<4; i++) {

                        if (!params[i+5].is_valid_integer()) {
                            memdelete(f);
                            ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid expand margin parameter for sboxt #"+itos(i+5) +", expected integer constant, got: '"+params[i+5]+"'.");
                            ERR_FAIL_V(RES());
                        }

                        int margin = params[i+5].to_int();
                        sbtex->set_margin_size(Margin(i),margin);
                    }
                }

                value = sbtex;
            } else if (type=="sboxf") {

                Vector<String> params = param.split(",");
                if (params.size()<2) {

                    memdelete(f);
                    ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid param count for sboxf(): '"+right+"'.");
                    ERR_FAIL_V(RES());

                }

                Ref<StyleBoxFlat> sbflat( memnew(StyleBoxFlat) );

                if (!params[0].is_valid_integer()) {

                    memdelete(f);
                    ERR_EXPLAIN(p_path+":"+itos(line)+": Expected integer numeric constant for parameter 0 (border size).");
                    ERR_FAIL_V(RES());

                }

                sbflat->set_border_size(params[0].to_int());

                if (!params[0].is_valid_integer()) {

                    memdelete(f);
                    ERR_EXPLAIN(p_path+":"+itos(line)+": Expected integer numeric constant for parameter 0 (border size).");
                    ERR_FAIL_V(RES());

                }


                int left = MIN( params.size()-1, 3 );

                int ccodes=0;

                for(int i=0; i<left; i++) {

                    if (params[i+1].is_valid_html_color())
                        ccodes++;
                    else
                        break;
                }

                Color normal;
                Color bright;
                Color dark;

                if (ccodes<1) {
                    memdelete(f);
                    ERR_EXPLAIN(p_path+":"+itos(line)+": Expected at least 1, 2 or 3 html color codes.");
                    ERR_FAIL_V(RES());
                } else if (ccodes==1) {

                    normal=Color::html(params[1]);
                    bright=Color::html(params[1]);
                    dark=Color::html(params[1]);
                } else if (ccodes==2) {

                    normal=Color::html(params[1]);
                    bright=Color::html(params[2]);
                    dark=Color::html(params[2]);
                } else {

                    normal=Color::html(params[1]);
                    bright=Color::html(params[2]);
                    dark=Color::html(params[3]);
                }

                sbflat->set_dark_color(dark);
                sbflat->set_light_color(bright);
                sbflat->set_bg_color(normal);

                if (params.size()==ccodes+5) {
                    //margins
                    for(int i=0; i<4; i++) {

                        if (!params[i+ccodes+1].is_valid_integer()) {
                            memdelete(f);
                            ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid expand margin parameter for sboxf #"+itos(i+ccodes+1) +", expected integer constant, got: '"+params[i+ccodes+1]+"'.");
                            ERR_FAIL_V(RES());
                        }

//						int margin = params[i+ccodes+1].to_int();
                        //sbflat->set_margin_size(Margin(i),margin);
                    }
                } else if (params.size()!=ccodes+1) {
                    memdelete(f);
                    ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid amount of margin parameters for sboxt.");
                    ERR_FAIL_V(RES());

                }


                value=sbflat;

            } else {
                memdelete(f);
                ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid constructor type: '"+type+"'.");
                ERR_FAIL_V(RES());

            }

        }


        //parse left and do something with it
        String left= l.substr(0,eqpos);

        if (reading_library) {

            left=left.strip_edges();
            if (!left.is_valid_identifier()) {
                memdelete(f);
                ERR_EXPLAIN(p_path+":"+itos(line)+": <LibraryItem> is not a valid identifier.");
                ERR_FAIL_V(RES());
            }
            if (library.has(left)) {
                memdelete(f);
                ERR_EXPLAIN(p_path+":"+itos(line)+": Already in library: '"+left+"'.");
                ERR_FAIL_V(RES());
            }

            library[left]=value;
        } else {

            int pointpos = left.find(".");
            if (pointpos==-1) {
                memdelete(f);
                ERR_EXPLAIN(p_path+":"+itos(line)+": Expected 'control.item=..' assign syntax.");
                ERR_FAIL_V(RES());
            }

            String control=left.substr(0,pointpos).strip_edges();
            if (!control.is_valid_identifier()) {
                memdelete(f);
                ERR_EXPLAIN(p_path+":"+itos(line)+": <Control> is not a valid identifier.");
                ERR_FAIL_V(RES());
            }
            String item=left.substr(pointpos+1,left.size()).strip_edges();
            if (!item.is_valid_identifier()) {
                memdelete(f);
                ERR_EXPLAIN(p_path+":"+itos(line)+": <Item> is not a valid identifier.");
                ERR_FAIL_V(RES());
            }

            if (value.get_type()==Variant::NIL) {
                //try to use exiting
                if (Theme::get_default()->has_stylebox(item,control))
                    value=Theme::get_default()->get_stylebox(item,control);
                else if (Theme::get_default()->has_font(item,control))
                    value=Theme::get_default()->get_font(item,control);
                else if (Theme::get_default()->has_icon(item,control))
                    value=Theme::get_default()->get_icon(item,control);
                else if (Theme::get_default()->has_color(item,control))
                    value=Theme::get_default()->get_color(item,control);
                else if (Theme::get_default()->has_constant(item,control))
                    value=Theme::get_default()->get_constant(item,control);
                else {
                    memdelete(f);
                    ERR_EXPLAIN(p_path+":"+itos(line)+": Default not present for: '"+control+"."+item+"'.");
                    ERR_FAIL_V(RES());
                }

            }

            if (value.get_type()==Variant::OBJECT) {

                Ref<Resource> res = value;
                if (!res.is_valid()) {

                    memdelete(f);
                    ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid resource (NULL).");
                    ERR_FAIL_V(RES());
                }

                if (res->cast_to<StyleBox>()) {

                    theme->set_stylebox(item,control,res);
                } else if (res->cast_to<Font>()) {
                    theme->set_font(item,control,res);
                } else if (res->cast_to<Font>()) {
                    theme->set_font(item,control,res);
                } else if (res->cast_to<Texture>()) {
                    theme->set_icon(item,control,res);
                } else {
                    memdelete(f);
                    ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid resource type.");
                    ERR_FAIL_V(RES());
                }
            } else if (value.get_type()==Variant::COLOR) {

                theme->set_color(item,control,value);

            } else if (value.get_type()==Variant::INT) {

                theme->set_constant(item,control,value);

            } else {

                memdelete(f);
                ERR_EXPLAIN(p_path+":"+itos(line)+": Couldn't even determine what this setting is! what did you do!?");
                ERR_FAIL_V(RES());
            }

        }


    }

    f->close();
    memdelete(f);

    if (r_error)
        *r_error=OK;

    return theme;
}
示例#16
0
Error PCKPacker::flush(bool p_verbose) {

	if (!file) {
		ERR_FAIL_COND_V(!file, ERR_INVALID_PARAMETER);
		return ERR_INVALID_PARAMETER;
	};

	// write the index

	file->store_32(files.size());

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

		file->store_pascal_string(files[i].path);
		files[i].offset_offset = file->get_pos();
		file->store_64(0); // offset
		file->store_64(files[i].size); // size

		// # empty md5
		file->store_32(0);
		file->store_32(0);
		file->store_32(0);
		file->store_32(0);
	};


	uint64_t ofs = file->get_pos();
	ofs = _align(ofs, alignment);

	_pad(file, ofs - file->get_pos());

	const uint32_t buf_max = 65536;
	uint8_t *buf = memnew_arr(uint8_t, buf_max);

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

		FileAccess* src = FileAccess::open(files[i].src_path, FileAccess::READ);
		uint64_t to_write = files[i].size;
		while (to_write > 0) {

			int read = src->get_buffer(buf, MIN(to_write, buf_max));
			file->store_buffer(buf, read);
			to_write -= read;
		};

		uint64_t pos = file->get_pos();
		file->seek(files[i].offset_offset); // go back to store the file's offset
		file->store_64(ofs);
		file->seek(pos);

		ofs = _align(ofs + files[i].size, alignment);
		_pad(file, ofs - pos);

		src->close();
		memdelete(src);
		count += 1;
		if (p_verbose) {
			if (count % 100 == 0) {
				printf("%i/%i (%.2f)\r", count, files.size(), float(count) / files.size() * 100);
				fflush(stdout);
			};
		};
	};

	if (p_verbose)
		printf("\n");

	file->close();

	return OK;
};
示例#17
0
void DocDump::dump(const String &p_file) {

	List<StringName> class_list;
	ClassDB::get_class_list(&class_list);

	class_list.sort_custom<StringName::AlphCompare>();

	FileAccess *f = FileAccess::open(p_file, FileAccess::WRITE);

	_write_string(f, 0, "<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");

	_write_string(f, 0, "<doc version=\"" + String(VERSION_MKSTRING) + "\" name=\"Engine Types\">");
	while (class_list.size()) {

		String name = class_list.front()->get();

		String header = "<class name=\"" + name + "\"";
		String inherits = ClassDB::get_parent_class(name);
		if (inherits != "")
			header += " inherits=\"" + inherits + "\"";
		String category = ClassDB::get_category(name);
		if (category == "")
			category = "Core";
		header += " category=\"" + category + "\"";
		header += ">";
		_write_string(f, 0, header);
		_write_string(f, 1, "<brief_description>");
		_write_string(f, 1, "</brief_description>");
		_write_string(f, 1, "<description>");
		_write_string(f, 1, "</description>");
		_write_string(f, 1, "<methods>");

		List<MethodInfo> method_list;
		ClassDB::get_method_list(name, &method_list, true);
		method_list.sort();

		for (List<MethodInfo>::Element *E = method_list.front(); E; E = E->next()) {
			if (E->get().name == "" || E->get().name[0] == '_')
				continue; //hiden

			MethodBind *m = ClassDB::get_method(name, E->get().name);

			String qualifiers;
			if (E->get().flags & METHOD_FLAG_CONST)
				qualifiers += "qualifiers=\"const\"";

			_write_string(f, 2, "<method name=\"" + _escape_string(E->get().name) + "\" " + qualifiers + " >");

			for (int i = -1; i < E->get().arguments.size(); i++) {

				PropertyInfo arginfo;

				if (i == -1) {

					arginfo = E->get().return_val;
					String type_name = (arginfo.hint == PROPERTY_HINT_RESOURCE_TYPE) ? arginfo.hint_string : Variant::get_type_name(arginfo.type);

					if (arginfo.type == Variant::NIL)
						continue;
					_write_string(f, 3, "<return type=\"" + type_name + "\">");
				} else {

					arginfo = E->get().arguments[i];

					String type_name;

					if (arginfo.hint == PROPERTY_HINT_RESOURCE_TYPE)
						type_name = arginfo.hint_string;
					else if (arginfo.type == Variant::NIL)
						type_name = "var";
					else
						type_name = Variant::get_type_name(arginfo.type);

					if (m && m->has_default_argument(i)) {
						Variant default_arg = m->get_default_argument(i);
						String default_arg_text = String(_escape_string(m->get_default_argument(i)));

						switch (default_arg.get_type()) {

							case Variant::NIL:
								default_arg_text = "NULL";
								break;
							// atomic types
							case Variant::BOOL:
								if (bool(default_arg))
									default_arg_text = "true";
								else
									default_arg_text = "false";
								break;
							case Variant::INT:
							case Variant::REAL:
								//keep it
								break;
							case Variant::STRING: // 15
							case Variant::NODE_PATH: // 15
								default_arg_text = "\"" + default_arg_text + "\"";
								break;
							case Variant::TRANSFORM:
								if (default_arg.operator Transform() == Transform()) {
									default_arg_text = "";
								}

								default_arg_text = Variant::get_type_name(default_arg.get_type()) + "(" + default_arg_text + ")";
								break;

							case Variant::VECTOR2: // 5
							case Variant::RECT2:
							case Variant::VECTOR3:
							case Variant::PLANE:
							case Variant::QUAT:
							case Variant::RECT3: //sorry naming convention fail :( not like it's used often // 10
							case Variant::BASIS:
							case Variant::COLOR:
							case Variant::POOL_BYTE_ARRAY:
							case Variant::POOL_INT_ARRAY:
							case Variant::POOL_REAL_ARRAY:
							case Variant::POOL_STRING_ARRAY: //25
							case Variant::POOL_VECTOR3_ARRAY:
							case Variant::POOL_COLOR_ARRAY:
								default_arg_text = Variant::get_type_name(default_arg.get_type()) + "(" + default_arg_text + ")";
								break;
							case Variant::OBJECT:
							case Variant::INPUT_EVENT:
							case Variant::DICTIONARY: // 20
							case Variant::ARRAY:
							case Variant::_RID:
							case Variant::IMAGE:
								//case Variant::RESOURCE:

								default_arg_text = Variant::get_type_name(default_arg.get_type()) + "()";
								break;
							default: {}
						}

						_write_string(f, 3, "<argument index=\"" + itos(i) + "\" name=\"" + _escape_string(arginfo.name) + "\" type=\"" + type_name + "\" default=\"" + _escape_string(default_arg_text) + "\">");
					} else
						_write_string(f, 3, "<argument index=\"" + itos(i) + "\" name=\"" + arginfo.name + "\" type=\"" + type_name + "\">");
				}

				String hint;
				switch (arginfo.hint) {
					case PROPERTY_HINT_DIR: hint = "A directory."; break;
					case PROPERTY_HINT_RANGE: hint = "Range - min: " + arginfo.hint_string.get_slice(",", 0) + " max: " + arginfo.hint_string.get_slice(",", 1) + " step: " + arginfo.hint_string.get_slice(",", 2); break;
					case PROPERTY_HINT_ENUM:
						hint = "Values: ";
						for (int j = 0; j < arginfo.hint_string.get_slice_count(","); j++) {
							if (j > 0) hint += ", ";
							hint += arginfo.hint_string.get_slice(",", j) + "=" + itos(j);
						}
						break;
					case PROPERTY_HINT_LENGTH: hint = "Length: " + arginfo.hint_string; break;
					case PROPERTY_HINT_FLAGS:
						hint = "Values: ";
						for (int j = 0; j < arginfo.hint_string.get_slice_count(","); j++) {
							if (j > 0) hint += ", ";
							hint += arginfo.hint_string.get_slice(",", j) + "=" + itos(1 << j);
						}
						break;
					case PROPERTY_HINT_FILE: hint = "A file:"; break;
					default: {}
						//case PROPERTY_HINT_RESOURCE_TYPE: hint="Type: "+arginfo.hint_string; break;
				};
				if (hint != "")
					_write_string(f, 4, hint);

				_write_string(f, 3, (i == -1) ? "</return>" : "</argument>");
			}

			_write_string(f, 3, "<description>");
			_write_string(f, 3, "</description>");

			_write_string(f, 2, "</method>");
		}

		_write_string(f, 1, "</methods>");

		List<MethodInfo> signal_list;
		ClassDB::get_signal_list(name, &signal_list, true);

		if (signal_list.size()) {

			_write_string(f, 1, "<signals>");
			for (List<MethodInfo>::Element *EV = signal_list.front(); EV; EV = EV->next()) {

				_write_string(f, 2, "<signal name=\"" + EV->get().name + "\">");
				for (int i = 0; i < EV->get().arguments.size(); i++) {
					PropertyInfo arginfo = EV->get().arguments[i];
					_write_string(f, 3, "<argument index=\"" + itos(i) + "\" name=\"" + arginfo.name + "\" type=\"" + Variant::get_type_name(arginfo.type) + "\">");
					_write_string(f, 3, "</argument>");
				}
				_write_string(f, 3, "<description>");
				_write_string(f, 3, "</description>");

				_write_string(f, 2, "</signal>");
			}

			_write_string(f, 1, "</signals>");
		}

		_write_string(f, 1, "<constants>");

		List<String> constant_list;
		ClassDB::get_integer_constant_list(name, &constant_list, true);

		/* constants are sorted in a special way */

		List<_ConstantSort> constant_sort;

		for (List<String>::Element *E = constant_list.front(); E; E = E->next()) {
			_ConstantSort cs;
			cs.name = E->get();
			cs.value = ClassDB::get_integer_constant(name, E->get());
			constant_sort.push_back(cs);
		}

		constant_sort.sort();

		for (List<_ConstantSort>::Element *E = constant_sort.front(); E; E = E->next()) {

			_write_string(f, 2, "<constant name=\"" + E->get().name + "\" value=\"" + itos(E->get().value) + "\">");
			_write_string(f, 2, "</constant>");
		}

		_write_string(f, 1, "</constants>");
		_write_string(f, 0, "</class>");

		class_list.erase(name);
	}

	_write_string(f, 0, "</doc>");
	f->close();
	memdelete(f);
}
示例#18
0
文件: export.cpp 项目: nakoff/godot
Error EditorExportPlatformOSX::export_project(const Ref<EditorExportPreset> &p_preset, bool p_debug, const String &p_path, int p_flags) {

	String src_pkg_name;

	EditorProgress ep("export", "Exporting for OSX", 3);

	if (p_debug)
		src_pkg_name = p_preset->get("custom_package/debug");
	else
		src_pkg_name = p_preset->get("custom_package/release");

	if (src_pkg_name == "") {
		String err;
		src_pkg_name = find_export_template("osx.zip", &err);
		if (src_pkg_name == "") {
			EditorNode::add_io_error(err);
			return ERR_FILE_NOT_FOUND;
		}
	}

	FileAccess *src_f = NULL;
	zlib_filefunc_def io = zipio_create_io_from_file(&src_f);

	ep.step("Creating app", 0);

	unzFile src_pkg_zip = unzOpen2(src_pkg_name.utf8().get_data(), &io);
	if (!src_pkg_zip) {

		EditorNode::add_io_error("Could not find template app to export:\n" + src_pkg_name);
		return ERR_FILE_NOT_FOUND;
	}

	ERR_FAIL_COND_V(!src_pkg_zip, ERR_CANT_OPEN);
	int ret = unzGoToFirstFile(src_pkg_zip);

	String binary_to_use = "godot_osx_" + String(p_debug ? "debug" : "release") + ".";
	int bits_mode = p_preset->get("application/bits_mode");
	binary_to_use += String(bits_mode == 0 ? "fat" : bits_mode == 1 ? "64" : "32");

	print_line("binary: " + binary_to_use);
	String pkg_name;
	if (p_preset->get("application/name") != "")
		pkg_name = p_preset->get("application/name"); // app_name
	else if (String(ProjectSettings::get_singleton()->get("application/config/name")) != "")
		pkg_name = String(ProjectSettings::get_singleton()->get("application/config/name"));
	else
		pkg_name = "Unnamed";

	Error err = OK;
	String tmp_app_path_name = "";
	zlib_filefunc_def io2 = io;
	FileAccess *dst_f = NULL;
	io2.opaque = &dst_f;
	zipFile dst_pkg_zip = NULL;

	if (use_dmg()) {
		// We're on OSX so we can export to DMG, but first we create our application bundle
		tmp_app_path_name = EditorSettings::get_singleton()->get_cache_dir().plus_file(pkg_name + ".app");
		print_line("Exporting to " + tmp_app_path_name);
		DirAccess *tmp_app_path = DirAccess::create_for_path(tmp_app_path_name);
		if (!tmp_app_path) {
			err = ERR_CANT_CREATE;
		}

		// Create our folder structure or rely on unzip?
		if (err == OK) {
			print_line("Creating " + tmp_app_path_name + "/Contents/MacOS");
			err = tmp_app_path->make_dir_recursive(tmp_app_path_name + "/Contents/MacOS");
		}

		if (err == OK) {
			print_line("Creating " + tmp_app_path_name + "/Contents/Resources");
			err = tmp_app_path->make_dir_recursive(tmp_app_path_name + "/Contents/Resources");
		}
	} else {
		// Open our destination zip file
		dst_pkg_zip = zipOpen2(p_path.utf8().get_data(), APPEND_STATUS_CREATE, NULL, &io2);
		if (!dst_pkg_zip) {
			err = ERR_CANT_CREATE;
		}
	}

	// Now process our template
	bool found_binary = false;
	int total_size = 0;

	while (ret == UNZ_OK && err == OK) {
		bool is_execute = false;

		//get filename
		unz_file_info info;
		char fname[16384];
		ret = unzGetCurrentFileInfo(src_pkg_zip, &info, fname, 16384, NULL, 0, NULL, 0);

		String file = fname;

		print_line("READ: " + file);
		Vector<uint8_t> data;
		data.resize(info.uncompressed_size);

		//read
		unzOpenCurrentFile(src_pkg_zip);
		unzReadCurrentFile(src_pkg_zip, data.ptr(), data.size());
		unzCloseCurrentFile(src_pkg_zip);

		//write

		file = file.replace_first("osx_template.app/", "");

		if (file == "Contents/Info.plist") {
			print_line("parse plist");
			_fix_plist(p_preset, data, pkg_name);
		}

		if (file.begins_with("Contents/MacOS/godot_")) {
			if (file != "Contents/MacOS/" + binary_to_use) {
				ret = unzGoToNextFile(src_pkg_zip);
				continue; //ignore!
			}
			found_binary = true;
			is_execute = true;
			file = "Contents/MacOS/" + pkg_name;
		}

		if (file == "Contents/Resources/icon.icns") {
			//see if there is an icon
			String iconpath;
			if (p_preset->get("application/icon") != "")
				iconpath = p_preset->get("application/icon");
			else
				iconpath = ProjectSettings::get_singleton()->get("application/config/icon");
			print_line("icon? " + iconpath);
			if (iconpath != "") {
				Ref<Image> icon;
				icon.instance();
				icon->load(iconpath);
				if (!icon->empty()) {
					print_line("loaded?");
					_make_icon(icon, data);
				}
			}
			//bleh?
		}

		if (data.size() > 0) {
			print_line("ADDING: " + file + " size: " + itos(data.size()));
			total_size += data.size();

			if (use_dmg()) {
				// write it into our application bundle
				file = tmp_app_path_name + "/" + file;

				// write the file, need to add chmod
				FileAccess *f = FileAccess::open(file, FileAccess::WRITE);
				if (f) {
					f->store_buffer(data.ptr(), data.size());
					f->close();
					if (is_execute) {
						// Chmod with 0755 if the file is executable
						f->_chmod(file, 0755);
					}
					memdelete(f);
				} else {
					err = ERR_CANT_CREATE;
				}
			} else {
				// add it to our zip file
				file = pkg_name + ".app/" + file;

				zip_fileinfo fi;
				fi.tmz_date.tm_hour = info.tmu_date.tm_hour;
				fi.tmz_date.tm_min = info.tmu_date.tm_min;
				fi.tmz_date.tm_sec = info.tmu_date.tm_sec;
				fi.tmz_date.tm_mon = info.tmu_date.tm_mon;
				fi.tmz_date.tm_mday = info.tmu_date.tm_mday;
				fi.tmz_date.tm_year = info.tmu_date.tm_year;
				fi.dosDate = info.dosDate;
				fi.internal_fa = info.internal_fa;
				fi.external_fa = info.external_fa;

				int zerr = zipOpenNewFileInZip(dst_pkg_zip,
						file.utf8().get_data(),
						&fi,
						NULL,
						0,
						NULL,
						0,
						NULL,
						Z_DEFLATED,
						Z_DEFAULT_COMPRESSION);

				print_line("OPEN ERR: " + itos(zerr));
				zerr = zipWriteInFileInZip(dst_pkg_zip, data.ptr(), data.size());
				print_line("WRITE ERR: " + itos(zerr));
				zipCloseFileInZip(dst_pkg_zip);
			}
		}

		ret = unzGoToNextFile(src_pkg_zip);
	}

	// we're done with our source zip
	unzClose(src_pkg_zip);

	if (!found_binary) {
		ERR_PRINTS("Requested template binary '" + binary_to_use + "' not found. It might be missing from your template archive.");
		err = ERR_FILE_NOT_FOUND;
	}

	if (err == OK) {
		ep.step("Making PKG", 1);

		if (use_dmg()) {
			String pack_path = tmp_app_path_name + "/Contents/Resources/" + pkg_name + ".pck";
			err = save_pack(p_preset, pack_path);

			// see if we can code sign our new package
			String identity = p_preset->get("codesign/identity");
			if (err == OK && identity != "") {
				ep.step("Code signing bundle", 2);

				// the order in which we code sign is important, this is a bit of a shame or we could do this in our loop that extracts the files from our ZIP

				// start with our application
				err = _code_sign(p_preset, tmp_app_path_name + "/Contents/MacOS/" + pkg_name);

				///@TODO we should check the contents of /Contents/Frameworks for frameworks to sign
			}

			if (err == OK && identity != "") {
				// we should probably loop through all resources and sign them?
				err = _code_sign(p_preset, tmp_app_path_name + "/Contents/Resources/icon.icns");
			}

			if (err == OK && identity != "") {
				err = _code_sign(p_preset, pack_path);
			}

			if (err == OK && identity != "") {
				err = _code_sign(p_preset, tmp_app_path_name + "/Contents/Info.plist");
			}

			// and finally create a DMG
			if (err == OK) {
				ep.step("Making DMG", 3);
				err = _create_dmg(p_path, pkg_name, tmp_app_path_name);
			}

			// Clean up temporary .app dir
			OS::get_singleton()->move_to_trash(tmp_app_path_name);
		} else {

			String pack_path = EditorSettings::get_singleton()->get_cache_dir().plus_file(pkg_name + ".pck");
			Error err = save_pack(p_preset, pack_path);

			if (err == OK) {
				zipOpenNewFileInZip(dst_pkg_zip,
						(pkg_name + ".app/Contents/Resources/" + pkg_name + ".pck").utf8().get_data(),
						NULL,
						NULL,
						0,
						NULL,
						0,
						NULL,
						Z_DEFLATED,
						Z_DEFAULT_COMPRESSION);

				FileAccess *pf = FileAccess::open(pack_path, FileAccess::READ);
				if (pf) {
					const int BSIZE = 16384;
					uint8_t buf[BSIZE];

					while (true) {

						int r = pf->get_buffer(buf, BSIZE);
						if (r <= 0)
							break;
						zipWriteInFileInZip(dst_pkg_zip, buf, r);
					}
					zipCloseFileInZip(dst_pkg_zip);
					memdelete(pf);
				} else {
					err = ERR_CANT_OPEN;
				}
			}
		}
	}

	if (dst_pkg_zip) {
		zipClose(dst_pkg_zip, NULL);
	}

	return OK;
}
示例#19
0
void EditorFileSystem::_scan_scenes() {

	ERR_FAIL_COND(!scanning || scandir);

	//read .fscache
	HashMap<String,FileCache> file_cache;
	HashMap<String,DirCache> dir_cache;
	DirCache *dc=NULL;
	String cpath;

	sources_changed.clear();



	String project=Globals::get_singleton()->get_resource_path();
	FileAccess *f =FileAccess::open(project+"/.fscache",FileAccess::READ);

	if (f) {
		//read the disk cache
		while(!f->eof_reached()) {

			String l = f->get_line().strip_edges();
			if (l==String())
				continue;

			if (l.begins_with("::")) {
				Vector<String> split = l.split("::");
				ERR_CONTINUE( split.size() != 3);
				String name = split[1];

				dir_cache[name]=DirCache();
				dc=&dir_cache[name];
				dc->modification_time=split[2].to_int64();

				if (name!="res://") {

					cpath=name+"/";

					int sp=name.find_last("/");
					if (sp==5)
						sp=6;
					String pd = name.substr(0,sp);
					DirCache *dcp = dir_cache.getptr(pd);
					ERR_CONTINUE(!dcp);
					dcp->subdirs.insert(name.get_file());
				} else {

					cpath=name;
				}


			} else {
				Vector<String> split = l.split("::");
				ERR_CONTINUE( split.size() != 4);
				String name = split[0];
				String file;

				if (!name.begins_with("res://")) {
					file=name;
					name=cpath+name;
				} else {
					file=name.get_file();
				}

				FileCache fc;
				fc.type=split[1];
				fc.modification_time=split[2].to_int64();
				String meta = split[3].strip_edges();
				fc.meta.enabled=false;
				if (meta.find("<>")!=-1){
					Vector<String> spl = meta.split("<>");
					int sc = spl.size()-1;
					if (sc%3==0){
						fc.meta.enabled=true;
						fc.meta.import_editor=spl[0];
						fc.meta.sources.resize(sc/3);
						for(int i=0;i<fc.meta.sources.size();i++) {
							fc.meta.sources[i].path=spl[1+i*3+0];
							fc.meta.sources[i].md5=spl[1+i*3+1];
							fc.meta.sources[i].modified_time=spl[1+i*3+2].to_int64();
						}

					}

				}
				file_cache[name]=fc;

				ERR_CONTINUE(!dc);
				dc->files.insert(file);
			}

		}

		f->close();
		memdelete(f);
	}






	total=0;
	DirAccess *da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
	//da->change_dir( Globals::get_singleton()->get_resource_path() );


	List<String> extensionsl;
	ResourceLoader::get_recognized_extensions_for_type("",&extensionsl);
	Set<String> extensions;
	for(List<String>::Element *E = extensionsl.front();E;E=E->next()) {

		extensions.insert(E->get());
	}

	EditorProgressBG scan_progress("efs","ScanFS",100);

	md_count=0;
	scandir=_scan_dir(da,extensions,"",0,1,"",file_cache,dir_cache,scan_progress);
	memdelete(da);
	if (abort_scan && scandir) {
		memdelete(scandir);
		scandir=NULL;

	}


	//save back the findings
	f=FileAccess::open(project+"/.fscache",FileAccess::WRITE);
	_save_type_cache_fs(scandir,f);
	f->close();
	memdelete(f);

	scanning=false;

}
示例#20
0
void EditorFileSystem::_reimport_file(const String &p_file) {

	print_line("REIMPORTING: " + p_file);

	EditorFileSystemDirectory *fs = NULL;
	int cpos = -1;
	bool found = _find_file(p_file, &fs, cpos);
	ERR_FAIL_COND(!found);

	//try to obtain existing params

	Map<StringName, Variant> params;
	String importer_name;

	if (FileAccess::exists(p_file + ".import")) {
		//use existing
		Ref<ConfigFile> cf;
		cf.instance();
		Error err = cf->load(p_file + ".import");
		if (err == OK) {
			List<String> sk;
			cf->get_section_keys("params", &sk);
			for (List<String>::Element *E = sk.front(); E; E = E->next()) {
				params[E->get()] = cf->get_value("params", E->get());
			}
			importer_name = cf->get_value("remap", "importer");
		}

	} else {
		late_added_files.insert(p_file); //imported files do not call update_file(), but just in case..
	}

	Ref<ResourceImporter> importer;
	bool load_default = false;
	//find the importer
	if (importer_name != "") {
		importer = ResourceFormatImporter::get_singleton()->get_importer_by_name(importer_name);
	}

	if (importer.is_null()) {
		//not found by name, find by extension
		importer = ResourceFormatImporter::get_singleton()->get_importer_by_extension(p_file.get_extension());
		load_default = true;
		if (importer.is_null()) {
			ERR_PRINT("BUG: File queued for import, but can't be imported!");
			ERR_FAIL();
		}
	}

	//mix with default params, in case a parameter is missing

	List<ResourceImporter::ImportOption> opts;
	importer->get_import_options(&opts);
	for (List<ResourceImporter::ImportOption>::Element *E = opts.front(); E; E = E->next()) {
		if (!params.has(E->get().option.name)) { //this one is not present
			params[E->get().option.name] = E->get().default_value;
		}
	}

	if (load_default && ProjectSettings::get_singleton()->get("importer_defaults/" + importer->get_importer_name())) {
		//use defaults if exist
		Dictionary d = ProjectSettings::get_singleton()->get("importer_defaults/" + importer->get_importer_name());
		List<Variant> v;
		d.get_key_list(&v);

		for (List<Variant>::Element *E = v.front(); E; E = E->next()) {
			params[E->get()] = d[E->get()];
		}
	}

	//finally, perform import!!
	String base_path = ResourceFormatImporter::get_singleton()->get_import_base_path(p_file);

	List<String> import_variants;
	List<String> gen_files;

	Error err = importer->import(p_file, base_path, params, &import_variants, &gen_files);

	if (err != OK) {
		ERR_PRINTS("Error importing: " + p_file);
	}

	//as import is complete, save the .import file

	FileAccess *f = FileAccess::open(p_file + ".import", FileAccess::WRITE);
	ERR_FAIL_COND(!f);

	//write manually, as order matters ([remap] has to go first for performance).
	f->store_line("[remap]");
	f->store_line("");
	f->store_line("importer=\"" + importer->get_importer_name() + "\"");
	if (importer->get_resource_type() != "") {
		f->store_line("type=\"" + importer->get_resource_type() + "\"");
	}

	if (importer->get_save_extension() == "") {
		//no path
	} else if (import_variants.size()) {
		//import with variants
		for (List<String>::Element *E = import_variants.front(); E; E = E->next()) {

			String path = base_path.c_escape() + "." + E->get() + "." + importer->get_save_extension();

			f->store_line("path." + E->get() + "=\"" + path + "\"");
		}
	} else {

		f->store_line("path=\"" + base_path + "." + importer->get_save_extension() + "\"");
	}

	f->store_line("");

	if (gen_files.size()) {
		f->store_line("[gen]");
		Array genf;
		for (List<String>::Element *E = gen_files.front(); E; E = E->next()) {
			genf.push_back(E->get());
		}

		String value;
		VariantWriter::write_to_string(genf, value);
		f->store_line("files=" + value);
		f->store_line("");
	}

	f->store_line("[params]");
	f->store_line("");

	//store options in provided order, to avoid file changing. Order is also important because first match is accepted first.

	for (List<ResourceImporter::ImportOption>::Element *E = opts.front(); E; E = E->next()) {

		String base = E->get().option.name;
		String value;
		VariantWriter::write_to_string(params[base], value);
		f->store_line(base + "=" + value);
	}

	f->close();
	memdelete(f);

	//update modified times, to avoid reimport
	fs->files[cpos]->modified_time = FileAccess::get_modified_time(p_file);
	fs->files[cpos]->import_modified_time = FileAccess::get_modified_time(p_file + ".import");
	fs->files[cpos]->deps = _get_dependencies(p_file);
	fs->files[cpos]->type = importer->get_resource_type();

	//if file is currently up, maybe the source it was loaded from changed, so import math must be updated for it
	//to reload properly
	if (ResourceCache::has(p_file)) {

		Resource *r = ResourceCache::get(p_file);

		if (r->get_import_path() != String()) {

			String dst_path = ResourceFormatImporter::get_singleton()->get_internal_resource_path(p_file);
			r->set_import_path(dst_path);
			r->set_import_last_modified_time(0);
		}
	}
}
void EditorFileSystem::_scan_filesystem() {

	ERR_FAIL_COND(!scanning || new_filesystem);

	//read .fscache
	String cpath;

	sources_changed.clear();
	file_cache.clear();

	String project=Globals::get_singleton()->get_resource_path();

	String fscache = EditorSettings::get_singleton()->get_project_settings_path().plus_file("filesystem_cache");
	FileAccess *f =FileAccess::open(fscache,FileAccess::READ);

	if (f) {
		//read the disk cache
		while(!f->eof_reached()) {

			String l = f->get_line().strip_edges();
			if (l==String())
				continue;

			if (l.begins_with("::")) {
				Vector<String> split = l.split("::");
				ERR_CONTINUE( split.size() != 3);
				String name = split[1];

				cpath=name;

			} else {
				Vector<String> split = l.split("::");
				ERR_CONTINUE( split.size() != 5);
				String name = split[0];
				String file;

				file=name;
				name=cpath.plus_file(name);

				FileCache fc;
				fc.type=split[1];
				fc.modification_time=split[2].to_int64();
				String meta = split[3].strip_edges();
				fc.meta.enabled=false;
				if (meta.find("<>")!=-1){
					Vector<String> spl = meta.split("<>");
					int sc = spl.size()-1;
					if (sc%3==0){
						fc.meta.enabled=true;
						fc.meta.import_editor=spl[0];
						fc.meta.sources.resize(sc/3);
						for(int i=0;i<fc.meta.sources.size();i++) {
							fc.meta.sources[i].path=spl[1+i*3+0];
							fc.meta.sources[i].md5=spl[1+i*3+1];
							fc.meta.sources[i].modified_time=spl[1+i*3+2].to_int64();
						}

					}

				}
				String deps = split[4].strip_edges();
				if (deps.length()) {
					Vector<String> dp = deps.split("<>");
					for(int i=0;i<dp.size();i++) {
						String path=dp[i];
						fc.meta.deps.push_back(path);
					}
				}

				file_cache[name]=fc;

			}

		}

		f->close();
		memdelete(f);
	}



	EditorProgressBG scan_progress("efs","ScanFS",1000);

	ScanProgress sp;
	sp.low=0;
	sp.hi=1;
	sp.progress=&scan_progress;


	new_filesystem = memnew( EditorFileSystemDirectory );
	new_filesystem->parent=NULL;

	DirAccess *d = DirAccess::create(DirAccess::ACCESS_RESOURCES);
	d->change_dir("res://");
	_scan_new_dir(new_filesystem,d,sp);

	file_cache.clear(); //clear caches, no longer needed

	memdelete(d);


	//save back the findings
//	String fscache = EditorSettings::get_singleton()->get_project_settings_path().plus_file("file_cache");

	f=FileAccess::open(fscache,FileAccess::WRITE);
	_save_filesystem_cache(new_filesystem,f);
	f->close();
	memdelete(f);

	scanning=false;

}
示例#22
0
Error EditorExportPlatformBB10::export_project(const String& p_path, bool p_debug, int p_flags) {


	EditorProgress ep("export","Exporting for BlackBerry 10",104);

	String src_template=custom_package;

	if (src_template=="") {
		String err;
		src_template = find_export_template("bb10.zip", &err);
		if (src_template=="") {
			EditorNode::add_io_error(err);
			return ERR_FILE_NOT_FOUND;
		}
	}

	FileAccess *src_f=NULL;
	zlib_filefunc_def io = zipio_create_io_from_file(&src_f);

	ep.step("Creating FileSystem for BAR",0);

	unzFile pkg = unzOpen2(src_template.utf8().get_data(), &io);
	if (!pkg) {

		EditorNode::add_io_error("Could not find template zip to export:\n"+src_template);
		return ERR_FILE_NOT_FOUND;
	}

	DirAccessRef da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
	da->change_dir(EditorSettings::get_singleton()->get_settings_path());


	if (da->change_dir("tmp")!=OK) {
		da->make_dir("tmp");
		if (da->change_dir("tmp")!=OK)
			return ERR_CANT_CREATE;
	}

	if (da->change_dir("bb10_export")!=OK) {
		da->make_dir("bb10_export");
		if (da->change_dir("bb10_export")!=OK) {
			return ERR_CANT_CREATE;
		}
	}


	String bar_dir = da->get_current_dir();
	if (bar_dir.ends_with("/")) {
		bar_dir=bar_dir.substr(0,bar_dir.length()-1);
	}

	//THIS IS SUPER, SUPER DANGEROUS!!!!
	//CAREFUL WITH THIS CODE, MIGHT DELETE USERS HARD DRIVE OR HOME DIR
	//EXTRA CHECKS ARE IN PLACE EVERYWERE TO MAKE SURE NOTHING BAD HAPPENS BUT STILL....
	//BE SUPER CAREFUL WITH THIS PLEASE!!!
	//BLACKBERRY THIS IS YOUR FAULT FOR NOT MAKING A BETTER WAY!!

	bool berr = bar_dir.ends_with("bb10_export");
	if (berr) {
		if (da->list_dir_begin()) {
			EditorNode::add_io_error("Can't ensure that dir is empty:\n"+bar_dir);
			ERR_FAIL_COND_V(berr,FAILED);
		};

		String f = da->get_next();
		while (f != "") {

			if (f == "." || f == "..") {
				f = da->get_next();
				continue;
			};
			Error err = da->remove(bar_dir + "/" + f);
			if (err != OK) {
				EditorNode::add_io_error("Can't ensure that dir is empty:\n"+bar_dir);
				ERR_FAIL_COND_V(err!=OK,err);
			};
			f = da->get_next();
		};

		da->list_dir_end();

	} else {
		print_line("ARE YOU CRAZY??? THIS IS A SERIOUS BUG HERE!!!");
		ERR_FAIL_V(ERR_OMFG_THIS_IS_VERY_VERY_BAD);
	}


	ERR_FAIL_COND_V(!pkg, ERR_CANT_OPEN);
	int ret = unzGoToFirstFile(pkg);



	while(ret==UNZ_OK) {

		//get filename
		unz_file_info info;
		char fname[16384];
		ret = unzGetCurrentFileInfo(pkg,&info,fname,16384,NULL,0,NULL,0);

		String file=fname;

		Vector<uint8_t> data;
		data.resize(info.uncompressed_size);

		//read
		unzOpenCurrentFile(pkg);
		unzReadCurrentFile(pkg,data.ptr(),data.size());
		unzCloseCurrentFile(pkg);

		//write

		if (file=="bar-descriptor.xml") {

			_fix_descriptor(data);
		}

		if (file=="icon.png") {
			bool found=false;

			if (this->icon!="" && this->icon.ends_with(".png")) {

				FileAccess *f = FileAccess::open(this->icon,FileAccess::READ);
				if (f) {

					data.resize(f->get_len());
					f->get_buffer(data.ptr(),data.size());
					memdelete(f);
					found=true;
				}

			}

			if (!found) {

				String appicon = GlobalConfig::get_singleton()->get("application/icon");
				if (appicon!="" && appicon.ends_with(".png")) {
					FileAccess*f = FileAccess::open(appicon,FileAccess::READ);
					if (f) {
						data.resize(f->get_len());
						f->get_buffer(data.ptr(),data.size());
						memdelete(f);
					}
				}
			}
		}


		if (file.find("/")) {

			da->make_dir_recursive(file.get_base_dir());
		}

		FileAccessRef wf = FileAccess::open(bar_dir.plus_file(file),FileAccess::WRITE);
		wf->store_buffer(data.ptr(),data.size());

		ret = unzGoToNextFile(pkg);
	}

	ep.step("Adding Files..",2);

	FileAccess* dst = FileAccess::open(bar_dir+"/data.pck", FileAccess::WRITE);
	if (!dst) {
		EditorNode::add_io_error("Can't copy executable file to:\n "+p_path);
		return ERR_FILE_CANT_WRITE;
	}
	save_pack(dst, false, 1024);
	dst->close();
	memdelete(dst);

	ep.step("Creating BAR Package..",104);

	String bb_packager=EditorSettings::get_singleton()->get("blackberry/host_tools");
	bb_packager=bb_packager.plus_file("blackberry-nativepackager");
	if (OS::get_singleton()->get_name()=="Windows")
		bb_packager+=".bat";


	if (!FileAccess::exists(bb_packager)) {
		EditorNode::add_io_error("Can't find packager:\n"+bb_packager);
		return ERR_CANT_OPEN;
	}

	List<String> args;
	args.push_back("-package");
	args.push_back(p_path);
	if (p_debug) {

		String debug_token=EditorSettings::get_singleton()->get("blackberry/debug_token");
		if (!FileAccess::exists(debug_token)) {
			EditorNode::add_io_error("Debug token not found!");
		} else {
			args.push_back("-debugToken");
			args.push_back(debug_token);
		}
		args.push_back("-devMode");
		args.push_back("-configuration");
		args.push_back("Device-Debug");
	} else {

		args.push_back("-configuration");
		args.push_back("Device-Release");
	}
	args.push_back(bar_dir.plus_file("bar-descriptor.xml"));

	int ec;

	Error err = OS::get_singleton()->execute(bb_packager,args,true,NULL,NULL,&ec);

	if (err!=OK)
		return err;
	if (ec!=0)
		return ERR_CANT_CREATE;

	return OK;

}
示例#23
0
void EditorFileSystem::_scan_filesystem() {

	ERR_FAIL_COND(!scanning || new_filesystem);

	//read .fscache
	String cpath;

	sources_changed.clear();
	file_cache.clear();

	String project = ProjectSettings::get_singleton()->get_resource_path();

	String fscache = EditorSettings::get_singleton()->get_project_settings_path().plus_file("filesystem_cache2");
	FileAccess *f = FileAccess::open(fscache, FileAccess::READ);

	if (f) {
		//read the disk cache
		while (!f->eof_reached()) {

			String l = f->get_line().strip_edges();
			if (l == String())
				continue;

			if (l.begins_with("::")) {
				Vector<String> split = l.split("::");
				ERR_CONTINUE(split.size() != 3);
				String name = split[1];

				cpath = name;

			} else {
				Vector<String> split = l.split("::");
				ERR_CONTINUE(split.size() != 5);
				String name = split[0];
				String file;

				file = name;
				name = cpath.plus_file(name);

				FileCache fc;
				fc.type = split[1];
				fc.modification_time = split[2].to_int64();
				fc.import_modification_time = split[3].to_int64();

				String deps = split[4].strip_edges();
				if (deps.length()) {
					Vector<String> dp = deps.split("<>");
					for (int i = 0; i < dp.size(); i++) {
						String path = dp[i];
						fc.deps.push_back(path);
					}
				}

				file_cache[name] = fc;
			}
		}

		f->close();
		memdelete(f);
	}

	String update_cache = EditorSettings::get_singleton()->get_project_settings_path().plus_file("filesystem_update2");

	print_line("try to see fs update2");
	if (FileAccess::exists(update_cache)) {

		print_line("it exists");

		{
			FileAccessRef f = FileAccess::open(update_cache, FileAccess::READ);
			String l = f->get_line().strip_edges();
			while (l != String()) {

				print_line("erased cache for: " + l + " " + itos(file_cache.has(l)));
				file_cache.erase(l); //erase cache for this, so it gets updated
				l = f->get_line().strip_edges();
			}
		}

		DirAccessRef d = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
		d->remove(update_cache); //bye bye update cache
	}

	EditorProgressBG scan_progress("efs", "ScanFS", 1000);

	ScanProgress sp;
	sp.low = 0;
	sp.hi = 1;
	sp.progress = &scan_progress;

	new_filesystem = memnew(EditorFileSystemDirectory);
	new_filesystem->parent = NULL;

	DirAccess *d = DirAccess::create(DirAccess::ACCESS_RESOURCES);
	d->change_dir("res://");
	_scan_new_dir(new_filesystem, d, sp);

	file_cache.clear(); //clear caches, no longer needed

	memdelete(d);

	//save back the findings
	//String fscache = EditorSettings::get_singleton()->get_project_settings_path().plus_file("file_cache");

	f = FileAccess::open(fscache, FileAccess::WRITE);
	_save_filesystem_cache(new_filesystem, f);
	f->close();
	memdelete(f);

	scanning = false;
}
示例#24
0
static int godot_close(voidpf opaque, voidpf stream) {

	FileAccess* f = (FileAccess*)opaque;
	f->close();
	return 0;
};
示例#25
0
Error DocData::save(const String& p_path) {

	Error err;
	FileAccess *f = FileAccess::open(p_path,FileAccess::WRITE,&err);

	if (err) {
		ERR_EXPLAIN("Can't write doc file: "+p_path);

		ERR_FAIL_V(err);

	}

	_write_string(f,0,"<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
	_write_string(f,0,"<doc version=\""+String(VERSION_MKSTRING)+"\" name=\"Engine Types\">");

	for( Map<String,ClassDoc>::Element *E=class_list.front();E;E=E->next()) {

		ClassDoc &c=E->get();

		String header="<class name=\""+c.name+"\"";
		if (c.inherits!="")
			header+=" inherits=\""+c.inherits+"\"";

		String category=c.category;
		if (c.category=="")
			category="Core";
		header+=" category=\""+category+"\"";
		header+=">";
		_write_string(f,0,header);
		_write_string(f,1,"<brief_description>");
		if (c.brief_description!="")
			_write_string(f,1,c.brief_description.xml_escape());
		_write_string(f,1,"</brief_description>");
		_write_string(f,1,"<description>");
		if (c.description!="")
			_write_string(f,1,c.description.xml_escape());
		_write_string(f,1,"</description>");
		_write_string(f,1,"<methods>");

		c.methods.sort();

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

			MethodDoc &m=c.methods[i];

			String qualifiers;
			if (m.qualifiers!="")
				qualifiers+=" qualifiers=\""+m.qualifiers.xml_escape()+"\"";

			_write_string(f,2,"<method name=\""+m.name+"\""+qualifiers+">");

			if (m.return_type!="") {

				_write_string(f,3,"<return type=\""+m.return_type+"\">");
				_write_string(f,3,"</return>");
			}

			for(int j=0;j<m.arguments.size();j++) {

				ArgumentDoc &a = m.arguments[j];
				if (a.default_value!="")
					_write_string(f,3,"<argument index=\""+itos(j)+"\" name=\""+a.name.xml_escape()+"\" type=\""+a.type.xml_escape()+"\" default=\""+a.default_value.xml_escape(true)+"\">");
				else
					_write_string(f,3,"<argument index=\""+itos(j)+"\" name=\""+a.name.xml_escape()+"\" type=\""+a.type.xml_escape()+"\">");

				_write_string(f,3,"</argument>");

			}

			_write_string(f,3,"<description>");
			if (m.description!="")
				_write_string(f,3,m.description.xml_escape());
			_write_string(f,3,"</description>");

			_write_string(f,2,"</method>");

		}

		_write_string(f,1,"</methods>");

		if (c.properties.size()) {
			_write_string(f,1,"<members>");

			c.properties.sort();

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


				PropertyDoc &p=c.properties[i];
				_write_string(f,2,"<member name=\""+p.name+"\" type=\""+p.type+"\">");
				if (p.description!="")
					_write_string(f,3,p.description.xml_escape());
				_write_string(f,2,"</member>");

			}
			_write_string(f,1,"</members>");
		}

		if (c.signals.size()) {

			c.signals.sort();

			_write_string(f,1,"<signals>");
			for(int i=0;i<c.signals.size();i++) {

				MethodDoc &m=c.signals[i];
				_write_string(f,2,"<signal name=\""+m.name+"\">");
				for(int j=0;j<m.arguments.size();j++) {

					ArgumentDoc &a = m.arguments[j];
						_write_string(f,3,"<argument index=\""+itos(j)+"\" name=\""+a.name.xml_escape()+"\" type=\""+a.type.xml_escape()+"\">");
						_write_string(f,3,"</argument>");

				}

				_write_string(f,3,"<description>");
				if (m.description!="")
					_write_string(f,3,m.description.xml_escape());
				_write_string(f,3,"</description>");

				_write_string(f,2,"</signal>");
			}

			_write_string(f,1,"</signals>");
		}

		_write_string(f,1,"<constants>");

		c.constants.sort_custom<_ConstantComparator>();

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

			ConstantDoc &k=c.constants[i];
			_write_string(f,2,"<constant name=\""+k.name+"\" value=\""+k.value+"\">");
			if (k.description!="")
				_write_string(f,3,k.description.xml_escape());
			_write_string(f,2,"</constant>");
		}

		_write_string(f,1,"</constants>");

		if (c.theme_properties.size()) {

			c.theme_properties.sort();

			_write_string(f,1,"<theme_items>");
			for(int i=0;i<c.theme_properties.size();i++) {


				PropertyDoc &p=c.theme_properties[i];
				_write_string(f,2,"<theme_item name=\""+p.name+"\" type=\""+p.type+"\">");
				_write_string(f,2,"</theme_item>");

			}
			_write_string(f,1,"</theme_items>");
		}

		_write_string(f,0,"</class>");

	}

	_write_string(f,0,"</doc>");
	f->close();
	memdelete(f);

	return OK;
}
示例#26
0
MainLoop* test() {

	print_line("this is test io");
	DirAccess* da = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
	da->change_dir(".");
	print_line("Opening current dir "+ da->get_current_dir());
	String entry;
	da->list_dir_begin();
	while ( (entry = da->get_next()) != "") {

		print_line("entry "+entry+" is dir: " + Variant(da->current_is_dir()));
	};
	da->list_dir_end();

	RES texture = ResourceLoader::load("test_data/rock.png");
	ERR_FAIL_COND_V(texture.is_null(), NULL);

	ResourceSaver::save("test_data/rock.xml",texture);

	print_line("localize paths");
	print_line(Globals::get_singleton()->localize_path("algo.xml"));
	print_line(Globals::get_singleton()->localize_path("c:\\windows\\algo.xml"));
	print_line(Globals::get_singleton()->localize_path(Globals::get_singleton()->get_resource_path()+"/something/something.xml"));
	print_line(Globals::get_singleton()->localize_path("somedir/algo.xml"));

	{

		FileAccess* z = FileAccess::open("test_data/archive.zip", FileAccess::READ);
		int len = z->get_len();
		Vector<uint8_t> zip;
		zip.resize(len);
		z->get_buffer(&zip[0], len);
		z->close();
		memdelete(z);

		FileAccessMemory::register_file("a_package", zip);
		FileAccess::make_default<FileAccessMemory>(FileAccess::ACCESS_RESOURCES);
		FileAccess::make_default<FileAccessMemory>(FileAccess::ACCESS_FILESYSTEM);
		FileAccess::make_default<FileAccessMemory>(FileAccess::ACCESS_USERDATA);

		print_line("archive test");
#if 0
		Archive arch;

		Archive::get_singleton()->add_package("a_package");
		FileAccessArchive f;

		print_line("opening for read");
		f._open("file.txt", FileAccess::READ);
		int pos = f.get_pos();
		printf("file has %i bytes, initial pos %i\n", (int)f.get_len(), pos);

		do {
			printf("%c", f.get_8());

		} while (!f.eof_reached());

		print_line("opening for stored seek");
		f.open("seek.bin", FileAccess::READ);
		pos = f.get_pos();
		printf("byte at pos %i is %i\n", pos, (int)f.get_8());
		f.seek(128);
		pos = f.get_pos();
		printf("byte at pos %i is %i\n", pos, (int)f.get_8());

		print_line("opening for deflated seek");
		f.open("seek_deflated.bin", FileAccess::READ);
		pos = f.get_pos();
		printf("byte at pos %i is %i\n", pos, (int)f.get_8());
		f.seek(128);
		pos = f.get_pos();
		printf("byte at pos %i is %i\n", pos, (int)f.get_8());
		pos = f.get_pos();
		printf("byte at pos %i is %i\n", pos, (int)f.get_8());
		pos = f.get_pos();
		printf("byte at pos %i is %i\n", pos, (int)f.get_8());
		f.seek(256);
		pos = f.get_pos();
		printf("byte at pos %i is %i\n", pos, (int)f.get_8());
		pos = f.get_pos();
		printf("byte at pos %i is %i\n", pos, (int)f.get_8());
		pos = f.get_pos();
		printf("byte at pos %i is %i\n", pos, (int)f.get_8());
		f.seek(4);
		pos = f.get_pos();
		printf("byte at pos %i is %i\n", pos, (int)f.get_8());
		pos = f.get_pos();
		printf("byte at pos %i is %i\n", pos, (int)f.get_8());
		pos = f.get_pos();
		printf("byte at pos %i is %i\n", pos, (int)f.get_8());

		f.close();

		DirAccessArchive d;
		String dir = "../blah1/blah2/blahask/../blah3/.//blah4/";
		printf("changing dir to %s\n", dir.utf8().get_data());
		d.change_dir(dir);
		printf("current dir is %s\n", d.get_current_dir().utf8().get_data());

		FileAccessMemory::cleanup();
#endif
	};

	print_line("test done");


	return memnew( TestMainLoop );

}
示例#27
0
Error DynamicFontAtSize::_load() {

	int error = FT_Init_FreeType(&library);

	ERR_EXPLAIN(TTR("Error initializing FreeType."));
	ERR_FAIL_COND_V(error != 0, ERR_CANT_CREATE);

	// FT_OPEN_STREAM is extremely slow only on Android.
	if (OS::get_singleton()->get_name() == "Android" && font->font_mem == NULL && font->font_path != String()) {
		// cache font only once for each font->font_path
		if (_fontdata.has(font->font_path)) {

			font->set_font_ptr(_fontdata[font->font_path].ptr(), _fontdata[font->font_path].size());

		} else {

			FileAccess *f = FileAccess::open(font->font_path, FileAccess::READ);
			ERR_FAIL_COND_V(!f, ERR_CANT_OPEN);

			size_t len = f->get_len();
			_fontdata[font->font_path] = Vector<uint8_t>();
			Vector<uint8_t> &fontdata = _fontdata[font->font_path];
			fontdata.resize(len);
			f->get_buffer(fontdata.ptr(), len);
			font->set_font_ptr(fontdata.ptr(), len);
			f->close();
		}
	}

	if (font->font_mem == NULL && font->font_path != String()) {

		FileAccess *f = FileAccess::open(font->font_path, FileAccess::READ);
		ERR_FAIL_COND_V(!f, ERR_CANT_OPEN);

		memset(&stream, 0, sizeof(FT_StreamRec));
		stream.base = NULL;
		stream.size = f->get_len();
		stream.pos = 0;
		stream.descriptor.pointer = f;
		stream.read = _ft_stream_io;
		stream.close = _ft_stream_close;

		FT_Open_Args fargs;
		memset(&fargs, 0, sizeof(FT_Open_Args));
		fargs.flags = FT_OPEN_STREAM;
		fargs.stream = &stream;
		error = FT_Open_Face(library, &fargs, 0, &face);
	} else if (font->font_mem) {

		memset(&stream, 0, sizeof(FT_StreamRec));
		stream.base = (unsigned char *)font->font_mem;
		stream.size = font->font_mem_size;
		stream.pos = 0;

		FT_Open_Args fargs;
		memset(&fargs, 0, sizeof(FT_Open_Args));
		fargs.memory_base = (unsigned char *)font->font_mem;
		fargs.memory_size = font->font_mem_size;
		fargs.flags = FT_OPEN_MEMORY;
		fargs.stream = &stream;
		error = FT_Open_Face(library, &fargs, 0, &face);

	} else {
		ERR_EXPLAIN("DynamicFont uninitialized");
		ERR_FAIL_V(ERR_UNCONFIGURED);
	}

	//error = FT_New_Face( library, src_path.utf8().get_data(),0,&face );

	if (error == FT_Err_Unknown_File_Format) {
		ERR_EXPLAIN(TTR("Unknown font format."));
		FT_Done_FreeType(library);

	} else if (error) {

		ERR_EXPLAIN(TTR("Error loading font."));
		FT_Done_FreeType(library);
	}

	ERR_FAIL_COND_V(error, ERR_FILE_CANT_OPEN);

	/*error = FT_Set_Char_Size(face,0,64*size,512,512);

	if ( error ) {
		FT_Done_FreeType( library );
		ERR_EXPLAIN(TTR("Invalid font size."));
		ERR_FAIL_COND_V( error, ERR_INVALID_PARAMETER );
	}*/

	error = FT_Set_Pixel_Sizes(face, 0, id.size);

	ascent = face->size->metrics.ascender >> 6;
	descent = -face->size->metrics.descender >> 6;
	linegap = 0;
	texture_flags = 0;
	if (id.mipmaps)
		texture_flags |= Texture::FLAG_MIPMAPS;
	if (id.filter)
		texture_flags |= Texture::FLAG_FILTER;

	//print_line("ASCENT: "+itos(ascent)+" descent "+itos(descent)+" hinted: "+itos(face->face_flags&FT_FACE_FLAG_HINTER));

	valid = true;
	return OK;
}
示例#28
0
文件: shader.cpp 项目: a12n/godot
RES ResourceFormatLoaderShader::load(const String &p_path, const String& p_original_path, Error *r_error) {

	if (r_error)
		*r_error=ERR_FILE_CANT_OPEN;

	String fragment_code;
	String vertex_code;
	String light_code;

	int mode=-1;

	Error err;
	FileAccess *f = FileAccess::open(p_path,FileAccess::READ,&err);


	ERR_EXPLAIN("Unable to open shader file: "+p_path);
	ERR_FAIL_COND_V(err,RES());
	String base_path = p_path.get_base_dir();

	if (r_error)
		*r_error=ERR_FILE_CORRUPT;

	Ref<Shader> shader;//( memnew( Shader ) );

	int line=0;

	while(!f->eof_reached()) {

		String l = f->get_line();
		line++;

		if (mode<=0) {
			l = l.strip_edges();
			int comment = l.find(";");
			if (comment!=-1)
				l=l.substr(0,comment);
		}

		if (mode<1)
			vertex_code+="\n";
		if (mode<2)
			fragment_code+="\n";

		if (mode < 1 && l=="")
			continue;

		if (l.begins_with("[")) {
			l=l.strip_edges();
			if (l=="[params]") {
				if (mode>=0) {
					memdelete(f);
					ERR_EXPLAIN(p_path+":"+itos(line)+": Misplaced [params] section.");
					ERR_FAIL_V(RES());
				}
				mode=0;
			}  else if (l=="[vertex]") {
				if (mode>=1) {
					memdelete(f);
					ERR_EXPLAIN(p_path+":"+itos(line)+": Misplaced [vertex] section.");
					ERR_FAIL_V(RES());
				}
				mode=1;
			}  else if (l=="[fragment]") {
				if (mode>=2) {
					memdelete(f);
					ERR_EXPLAIN(p_path+":"+itos(line)+": Misplaced [fragment] section.");
					ERR_FAIL_V(RES());
				}
				mode=1;
			} else {
				memdelete(f);
				ERR_EXPLAIN(p_path+":"+itos(line)+": Unknown section type: '"+l+"'.");
				ERR_FAIL_V(RES());
			}
			continue;
		}

		if (mode==0) {

			int eqpos = l.find("=");
			if (eqpos==-1) {
				memdelete(f);
				ERR_EXPLAIN(p_path+":"+itos(line)+": Expected '='.");
				ERR_FAIL_V(RES());
			}


			String right=l.substr(eqpos+1,l.length()).strip_edges();
			if (right=="") {
				memdelete(f);
				ERR_EXPLAIN(p_path+":"+itos(line)+": Expected value after '='.");
				ERR_FAIL_V(RES());
			}

			Variant value;

			if (right=="true") {
				value = true;
			} else if (right=="false") {
				value = false;
			} else if (right.is_valid_float()) {
				//is number
				value = right.to_double();
			} else if (right.is_valid_html_color()) {
				//is html color
				value = Color::html(right);
			} else {
				//attempt to parse a constructor
				int popenpos = right.find("(");

				if (popenpos==-1) {
					memdelete(f);
					ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid constructor syntax: "+right);
					ERR_FAIL_V(RES());
				}

				int pclosepos = right.find_last(")");

				if (pclosepos==-1) {
					ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid constructor parameter syntax: "+right);
					ERR_FAIL_V(RES());

				}

				String type = right.substr(0,popenpos);
				String param = right.substr(popenpos+1,pclosepos-popenpos-1).strip_edges();


				if (type=="tex") {

					if (param=="") {

						value=RID();
					} else {

						String path;

						if (param.is_abs_path())
							path=param;
						else
							path=base_path+"/"+param;

						Ref<Texture> texture = ResourceLoader::load(path);
						if (!texture.is_valid()) {
							memdelete(f);
							ERR_EXPLAIN(p_path+":"+itos(line)+": Couldn't find icon at path: "+path);
							ERR_FAIL_V(RES());
						}

						value=texture;
					}

				} else if (type=="vec3") {

					if (param=="") {
						value=Vector3();
					} else {
						Vector<String> params = param.split(",");
						if (params.size()!=3) {
							memdelete(f);
							ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid param count for vec3(): '"+right+"'.");
							ERR_FAIL_V(RES());

						}

						Vector3 v;
						for(int i=0;i<3;i++)
							v[i]=params[i].to_double();
						value=v;
					}


				} else if (type=="xform") {

					if (param=="") {
						value=Transform();
					} else {

						Vector<String> params = param.split(",");
						if (params.size()!=12) {
							memdelete(f);
							ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid param count for xform(): '"+right+"'.");
							ERR_FAIL_V(RES());

						}

						Transform t;
						for(int i=0;i<9;i++)
							t.basis[i%3][i/3]=params[i].to_double();
						for(int i=0;i<3;i++)
							t.origin[i]=params[i-9].to_double();

						value=t;
					}

				} else {
					memdelete(f);
					ERR_EXPLAIN(p_path+":"+itos(line)+": Invalid constructor type: '"+type+"'.");
					ERR_FAIL_V(RES());

				}

			}

			String left= l.substr(0,eqpos);

//			shader->set_param(left,value);
		} else if (mode==1) {

			vertex_code+=l;

		} else if (mode==2) {

			fragment_code+=l;
		}
	}

	shader->set_code(vertex_code,fragment_code,light_code);

	f->close();
	memdelete(f);
	if (r_error)
		*r_error=OK;

	return shader;
}
示例#29
0
文件: export.cpp 项目: Scrik/godot
Error EditorExportPlatformWindows::export_project(const String& p_path, bool p_debug, int p_flags) {

	Error err = EditorExportPlatformPC::export_project(p_path, p_debug, p_flags);
	if(err != OK)
	{
		return err;
	}
	EditorProgress ep("editexe","Edit EXE File",102);
	ep.step("Create ico file..",0);
	
		DVector<uint8_t> icon_content;
		if (this->icon_ico!="" && this->icon_ico.ends_with(".ico")) {
			FileAccess *f = FileAccess::open(this->icon_ico,FileAccess::READ);
			if (f) {
				icon_content.resize(f->get_len());
				DVector<uint8_t>::Write write = icon_content.write();
				f->get_buffer(write.ptr(),icon_content.size());
				f->close();
				memdelete(f);
			}
		} else if (this->icon_png!="" && this->icon_png.ends_with(".png") && (icon16 || icon32 || icon48 || icon64 || icon128 || icon256)) {
			#ifdef PNG_ENABLED
			Vector<Image> pngs;
			Image png;
			Error err_png = png.load(this->icon_png);
			if (err_png==OK && !png.empty()) {
				if(icon256) {
					Image icon_256(png);
					if(!(png.get_height()==256 && png.get_width()==256)) icon_256.resize(256,256);
					pngs.push_back(icon_256);
				}
				if(icon128) {
					Image icon_128(png);
					if(!(png.get_height()==128 && png.get_width()==128)) icon_128.resize(128,128);
					pngs.push_back(icon_128);
				}
				if(icon64) {
					Image icon_64(png);
					if(!(png.get_height()==64 && png.get_width()==64)) icon_64.resize(64,64);
					pngs.push_back(icon_64);
				}
				if(icon48) {
					Image icon_48(png);
					if(!(png.get_height()==48 && png.get_width()==48)) icon_48.resize(48,48);
					pngs.push_back(icon_48);
				}
				if(icon32) {
					Image icon_32(png);
					if(!(png.get_height()==32 && png.get_width()==32)) icon_32.resize(32,32);
					pngs.push_back(icon_32);
				}
				if(icon16) {
					Image icon_16(png);
					if(!(png.get_height()==16 && png.get_width()==16)) icon_16.resize(16,16);
					pngs.push_back(icon_16);
				}
				// create icon according to https://www.daubnet.com/en/file-format-ico
				store_16(icon_content,0); //Reserved
				store_16(icon_content,1); //Type
				store_16(icon_content,pngs.size()); //Count
				int offset = 6+pngs.size()*16;
				//List of bitmaps 
				for(int i=0;i<pngs.size();i++) {
					int w = pngs[i].get_width();
					int h = pngs[i].get_height();
					icon_content.push_back(w<256?w:0); //width
					icon_content.push_back(h<256?h:0); //height
					icon_content.push_back(0); //ColorCount = 0
					icon_content.push_back(0); //Reserved
					store_16(icon_content,1); //Planes
					store_16(icon_content,32); //BitCount (bit per pixel)
					int size = 40 + (w * h * 4) + (w * h / 8);
					store_32(icon_content,size); //Size of (InfoHeader + ANDbitmap + XORbitmap) 
					store_32(icon_content,offset); //FileOffset
					offset += size;
				}
				//Write bmp files.
				for(int i=0;i<pngs.size();i++) {
					int w = pngs[i].get_width();
					int h = pngs[i].get_height();
					store_32(icon_content,40); //Size of InfoHeader structure = 40
					store_32(icon_content,w); //Width
					store_32(icon_content,h*2); //Height
					store_16(icon_content,1); //Planes
					store_16(icon_content,32); //BitCount
					store_32(icon_content,0); //Compression
					store_32(icon_content,w*h*4); //ImageSize = Size of Image in Bytes
					store_32(icon_content,0); //unused = 0 
					store_32(icon_content,0); //unused = 0 
					store_32(icon_content,0); //unused = 0 
					store_32(icon_content,0); //unused = 0 
					//XORBitmap
					for(int y=h-1;y>=0;y--) {
						for(int x=0;x<w;x++) {
							store_32(icon_content,pngs[i].get_pixel(x,y).to_32());
						}
					}
					//ANDBitmap
					for(int m=0;m<(w * h / 8);m+=4) store_32(icon_content,0x00000000); // Add empty ANDBitmap , TODO create full ANDBitmap Structure if need.
				}
			}
			#endif
		}
	
	ep.step("Add rsrc..",50);
	
		String basename = Globals::get_singleton()->get("application/name");
		product_name=product_name.replace("$genname",basename);
		String godot_version;
		if(set_godot_version) godot_version = String( VERSION_MKSTRING );
		String ret = pe_bliss_add_resrc(p_path.utf8(), version_major, version_minor,
																						company_name, file_description, legal_copyright, version_text,
																						product_name, godot_version, icon_content);
		if (ret.empty()) {
			return OK;
		} else {
			EditorNode::add_io_error(ret);
			return ERR_FILE_CANT_WRITE;
		}
}