//! return the size of the stream in bytes
	virtual unsigned long size() {

		if (!fa)
			return 0;

		return fa->get_len();
	};
	//! return the current position of the source pointer
	virtual unsigned long tell() {

		if (!fa)
			return 0;

		return fa->get_pos();
	};
	int read(void* output,int nBytes) {

		if (!fa)
			return -1;

		return fa->get_buffer((uint8_t*)output, nBytes);
	};
	//! position the source pointer to byte_index from the start of the source
	virtual void seek(unsigned long byte_index) {

		if (!fa)
			return;

		fa->seek(byte_index);
	};
Example #5
0
void CreateDialog::_save_favorite_list() {

	FileAccess *f = FileAccess::open(EditorSettings::get_singleton()->get_project_settings_dir().plus_file("favorites." + base_type), FileAccess::WRITE);

	if (f) {

		for (int i = 0; i < favorite_list.size(); i++) {
			String l = favorite_list[i];
			String name = l.split(" ")[0];
			if (!(ClassDB::class_exists(name) || ScriptServer::is_global_class(name)))
				continue;
			f->store_line(l);
		}
		memdelete(f);
	}
}
Example #6
0
void EditorExportPlatformOSX::_make_icon(const Ref<Image> &p_icon, Vector<uint8_t> &p_data) {

	Ref<ImageTexture> it = memnew(ImageTexture);
	int size = 512;

	Vector<uint8_t> data;

	data.resize(8);
	data[0] = 'i';
	data[1] = 'c';
	data[2] = 'n';
	data[3] = 's';

	const char *name[] = { "ic09", "ic08", "ic07", "icp6", "icp5", "icp4" };
	int index = 0;

	while (size >= 16) {

		Ref<Image> copy = p_icon; // does this make sense? doesn't this just increase the reference count instead of making a copy? Do we even need a copy?
		copy->convert(Image::FORMAT_RGBA8);
		copy->resize(size, size);
		it->create_from_image(copy);
		String path = EditorSettings::get_singleton()->get_cache_dir().plus_file("icon.png");
		ResourceSaver::save(path, it);

		FileAccess *f = FileAccess::open(path, FileAccess::READ);
		ERR_FAIL_COND(!f);

		int ofs = data.size();
		uint32_t len = f->get_len();
		data.resize(data.size() + len + 8);
		f->get_buffer(&data[ofs + 8], len);
		memdelete(f);
		len += 8;
		len = BSWAP32(len);
		copymem(&data[ofs], name[index], 4);
		encode_uint32(len, &data[ofs + 4]);
		index++;
		size /= 2;
	}

	uint32_t total_len = data.size();
	total_len = BSWAP32(total_len);
	encode_uint32(total_len, &data[4]);

	p_data = data;
}
Example #7
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);
}
Error ResourceFormatLoaderBinary::load_import_metadata(const String &p_path, Ref<ResourceImportMetadata>& r_var) const {


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

	Ref<ResourceInteractiveLoaderBinary> ria = memnew( ResourceInteractiveLoaderBinary );
	ria->local_path=Globals::get_singleton()->localize_path(p_path);
	ria->res_path=ria->local_path;
//	ria->set_local_path( Globals::get_singleton()->localize_path(p_path) );
	ria->recognize(f);
	if(ria->error!=OK)
		return ERR_FILE_UNRECOGNIZED;
	f=ria->f;
	uint64_t imp_ofs = f->get_64();

	if (imp_ofs==0)
		return ERR_UNAVAILABLE;

	f->seek(imp_ofs);
	Ref<ResourceImportMetadata> imd = memnew( ResourceImportMetadata );
	imd->set_editor(ria->get_unicode_string());
	int sc = f->get_32();
	for(int i=0;i<sc;i++) {

		String src = ria->get_unicode_string();
		String md5 = ria->get_unicode_string();
		imd->add_source(src,md5);
	}
	int pc = f->get_32();

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

		String name = ria->get_unicode_string();
		Variant val;
		ria->parse_variant(val);
		imd->set_option(name,val);
	}

	r_var=imd;

	return OK;

}
Ref<Texture> EditorResourcePreview::_generate_preview(const QueueItem &p_item, const String &cache_base) {

	String type;

	if (p_item.resource.is_valid())
		type = p_item.resource->get_class();
	else
		type = ResourceLoader::get_resource_type(p_item.path);

	if (type == "")
		return Ref<Texture>(); //could not guess type

	Ref<Texture> generated;

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

		if (!preview_generators[i]->handles(type))
			continue;
		if (p_item.resource.is_valid()) {
			generated = preview_generators[i]->generate(p_item.resource);
		} else {
			generated = preview_generators[i]->generate_from_path(p_item.path);
		}

		break;
	}

	if (!p_item.resource.is_valid()) {
		// cache the preview in case it's a resource on disk
		if (generated.is_valid()) {
			int thumbnail_size = EditorSettings::get_singleton()->get("filesystem/file_dialog/thumbnail_size");
			thumbnail_size *= EDSCALE;
			//wow it generated a preview... save cache
			ResourceSaver::save(cache_base + ".png", generated);
			FileAccess *f = FileAccess::open(cache_base + ".txt", FileAccess::WRITE);
			f->store_line(itos(thumbnail_size));
			f->store_line(itos(FileAccess::get_modified_time(p_item.path)));
			f->store_line(FileAccess::get_md5(p_item.path));
			memdelete(f);
		} else {
			//print_line("was not generated");
		}
	}

	return generated;
}
Example #10
0
int64_t GDAPI godot_videodecoder_file_seek(void *ptr, int64_t pos, int whence) {
	// file
	FileAccess *file = reinterpret_cast<FileAccess *>(ptr);

	if (file) {
		size_t len = file->get_len();
		switch (whence) {
			case SEEK_SET: {
				// Just for explicitness
				size_t new_pos = static_cast<size_t>(pos);
				if (new_pos > len) {
					return -1;
				}
				file->seek(new_pos);
				pos = static_cast<int64_t>(file->get_position());
				return pos;
			} break;
			case SEEK_CUR: {
				// Just in case it doesn't exist
				if (pos < 0 && (size_t)-pos > file->get_position()) {
					return -1;
				}
				pos = pos + static_cast<int>(file->get_position());
				file->seek(pos);
				pos = static_cast<int64_t>(file->get_position());
				return pos;
			} break;
			case SEEK_END: {
				// Just in case something goes wrong
				if ((size_t)-pos > len) {
					return -1;
				}
				file->seek_end(pos);
				pos = static_cast<int64_t>(file->get_position());
				return pos;
			} break;
			default: {
				// Only 4 possible options, hence default = AVSEEK_SIZE
				// Asks to return the length of file
				return static_cast<int64_t>(len);
			} break;
		}
	}
	// In case nothing works out.
	return -1;
}
void RichTextEditor::_file_selected(const String& p_path) {

	CharString cs;
	FileAccess *fa = FileAccess::open(p_path,FileAccess::READ);
	if (!fa) {
		ERR_FAIL();
	}

	while(!fa->eof_reached())
		cs.push_back(fa->get_8());
	cs.push_back(0);
	memdelete(fa);

	String bbcode;
	bbcode.parse_utf8(&cs[0]);
	node->parse_bbcode(bbcode);

}
Example #12
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();
}
Example #13
0
RES ResourceFormatPKM::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);
	if (!f)
		return RES();

	FileAccessRef fref(f);
	if (r_error)
		*r_error = ERR_FILE_CORRUPT;

	ERR_EXPLAIN("Unable to open PKM texture file: " + p_path);
	ERR_FAIL_COND_V(err != OK, RES());

	// big endian
	f->set_endian_swap(true);

	ETC1Header h;
	ERR_EXPLAIN("Invalid or Unsupported PKM texture file: " + p_path);
	f->get_buffer((uint8_t *)&h.tag, sizeof(h.tag));
	if (strncmp(h.tag, "PKM 10", sizeof(h.tag)))
		ERR_FAIL_V(RES());

	h.format = f->get_16();
	h.texWidth = f->get_16();
	h.texHeight = f->get_16();
	h.origWidth = f->get_16();
	h.origHeight = f->get_16();

	PoolVector<uint8_t> src_data;

	uint32_t size = h.texWidth * h.texHeight / 2;
	src_data.resize(size);
	PoolVector<uint8_t>::Write wb = src_data.write();
	f->get_buffer(wb.ptr(), size);
	wb = PoolVector<uint8_t>::Write();

	int mipmaps = h.format;
	int width = h.origWidth;
	int height = h.origHeight;

	Ref<Image> img = memnew(Image(width, height, mipmaps, Image::FORMAT_ETC, src_data));

	Ref<ImageTexture> texture = memnew(ImageTexture);
	texture->create_from_image(img);

	if (r_error)
		*r_error = OK;

	return texture;
}
Example #14
0
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
}
Example #15
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;
}
Example #16
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;
};
Example #17
0
static long godot_seek(voidpf opaque, voidpf stream, uLong offset, int origin) {

	FileAccess* f = (FileAccess*)opaque;

	int pos = offset;
	switch (origin) {

	case ZLIB_FILEFUNC_SEEK_CUR:
		pos = f->get_pos() + offset;
		break;
	case ZLIB_FILEFUNC_SEEK_END:
		pos = f->get_len() + offset;
		break;
	default:
		break;
	};

	f->seek(pos);
	return 0;
};
Example #18
0
Vector<uint8_t> EditorExportPlatform::get_exported_file(String& p_fname) const {

	Ref<EditorExportPlatform> ep=EditorImportExport::get_singleton()->get_export_platform(get_name());

	for(int i=0;i<EditorImportExport::get_singleton()->get_export_plugin_count();i++) {

		Vector<uint8_t> data = EditorImportExport::get_singleton()->get_export_plugin(i)->custom_export(p_fname,ep);
		if (data.size())
			return data;

	}


	FileAccess *f = FileAccess::open(p_fname,FileAccess::READ);
	ERR_FAIL_COND_V(!f,Vector<uint8_t>());
	Vector<uint8_t> ret;
	ret.resize(f->get_len());
	int rbs = f->get_buffer(ret.ptr(),ret.size());
	memdelete(f);
	return ret;
}
void VideoStreamTheoraplayer::set_file(const String& p_file) {

	FileAccess* f = FileAccess::open(p_file, FileAccess::READ);
	if (!f || !f->is_open())
		return;

	if (!audio_factory) {
		audio_factory = memnew(TPAudioGodotFactory);
	};

	if (mgr == NULL) {
		mgr = memnew(TheoraVideoManager(4));
		mgr->setAudioInterfaceFactory(audio_factory);
	};

	int track = GLOBAL_DEF("theora/audio_track", 0); // hack

	if (p_file.find(".mp4") != -1) {
		
		std::string file = p_file.replace("res://", "").utf8().get_data();
		clip = mgr->createVideoClip(file, TH_RGBX, 2, false, track);
		//clip->set_audio_track(audio_track);
		memdelete(f);

	} else {

		TheoraDataSource* ds = memnew(TPDataFA(f, p_file));

		try {
			clip = mgr->createVideoClip(ds);
			clip->set_audio_track(audio_track);
		} catch (_TheoraGenericException e) {
			printf("exception ocurred! %s\n", e.repr().c_str());
			clip = NULL;
		};
	};

	clip->pause();
	started = true;
};
Error ResourceImporterImage::import(const String &p_source_file, const String &p_save_path, const Map<StringName, Variant> &p_options, List<String> *r_platform_variants, List<String> *r_gen_files) {

	FileAccess *f = FileAccess::open(p_source_file, FileAccess::READ);
	if (!f) {
		ERR_FAIL_COND_V(!f, ERR_CANT_OPEN);
	}

	size_t len = f->get_len();

	Vector<uint8_t> data;
	data.resize(len);

	f->get_buffer(data.ptrw(), len);

	memdelete(f);

	f = FileAccess::open(p_save_path + ".image", FileAccess::WRITE);

	//save the header GDIM
	const uint8_t header[4] = { 'G', 'D', 'I', 'M' };
	f->store_buffer(header, 4);
	//SAVE the extension (so it can be recognized by the loader later
	f->store_pascal_string(p_source_file.get_extension().to_lower());
	//SAVE the actual image
	f->store_buffer(data.ptr(), len);

	memdelete(f);

	return OK;
}
Example #21
0
int AudioStreamPlaybackOGGVorbis::_ov_seek_func(void *_f, ogg_int64_t offs, int whence) {

	//printf("seek to %p, offs %i, whence %i\n",_f,(int)offs,whence);

#ifdef SEEK_SET
	//printf("seek set defined\n");
	FileAccess *fa = (FileAccess *)_f;

	if (whence == SEEK_SET) {

		fa->seek(offs);
	} else if (whence == SEEK_CUR) {

		fa->seek(fa->get_position() + offs);
	} else if (whence == SEEK_END) {

		fa->seek_end(offs);
	} else {

		ERR_PRINT("Vorbis seek function failure: Unexpected value in _whence\n");
	}
	int ret = fa->eof_reached() ? -1 : 0;
	//printf("returning %i\n",ret);
	return ret;

#else
	return -1; // no seeking
#endif
}
Example #22
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;
}
Example #23
0
void StreamPeerMbedTLS::initialize_ssl() {

	_create = _create_func;
	load_certs_func = _load_certs;

	mbedtls_x509_crt_init(&cacert);

#ifdef DEBUG_ENABLED
	mbedtls_debug_set_threshold(1);
#endif

	String certs_path = GLOBAL_DEF("network/ssl/certificates", "");
	ProjectSettings::get_singleton()->set_custom_property_info("network/ssl/certificates", PropertyInfo(Variant::STRING, "network/ssl/certificates", PROPERTY_HINT_FILE, "*.crt"));

	if (certs_path != "") {

		FileAccess *f = FileAccess::open(certs_path, FileAccess::READ);
		if (f) {
			PoolByteArray arr;
			int flen = f->get_len();
			arr.resize(flen + 1);
			{
				PoolByteArray::Write w = arr.write();
				f->get_buffer(w.ptr(), flen);
				w[flen] = 0; //end f string
			}

			memdelete(f);

			_load_certs(arr);
			print_line("Loaded certs from '" + certs_path);
		}
	}

	available = true;
}
Example #24
0
void AudioStreamSpeex::set_file(const String &p_file) {

	if (this->file == p_file)
		return;

	this->file = p_file;

	if (p_file == "") {
		data.resize(0);
		return;
	};

	Error err;
	FileAccess *file = FileAccess::open(p_file, FileAccess::READ, &err);
	if (err != OK) {
		data.resize(0);
	};
	ERR_FAIL_COND(err != OK);

	this->file = p_file;
	data.resize(file->get_len());
	int read = file->get_buffer(&data[0], data.size());
	memdelete(file);
}
void ExportTemplateManager::_install_from_file(const String &p_file, bool p_use_progress) {

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

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

		EditorNode::get_singleton()->show_warning(TTR("Can't open export templates zip."));
		return;
	}
	int ret = unzGoToFirstFile(pkg);

	int fc = 0; //count them and find version
	String version;

	while (ret == UNZ_OK) {

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

		String file = fname;

		if (file.ends_with("version.txt")) {

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

			//read
			unzOpenCurrentFile(pkg);
			ret = unzReadCurrentFile(pkg, data.ptrw(), data.size());
			unzCloseCurrentFile(pkg);

			String data_str;
			data_str.parse_utf8((const char *)data.ptr(), data.size());
			data_str = data_str.strip_edges();

			// Version number should be of the form major.minor[.patch].status[.module_config]
			// so it can in theory have 3 or more slices.
			if (data_str.get_slice_count(".") < 3) {
				EditorNode::get_singleton()->show_warning(vformat(TTR("Invalid version.txt format inside templates: %s."), data_str));
				unzClose(pkg);
				return;
			}

			version = data_str;
		}

		if (file.get_file().size() != 0) {
			fc++;
		}

		ret = unzGoToNextFile(pkg);
	}

	if (version == String()) {
		EditorNode::get_singleton()->show_warning(TTR("No version.txt found inside templates."));
		unzClose(pkg);
		return;
	}

	String template_path = EditorSettings::get_singleton()->get_templates_dir().plus_file(version);

	DirAccess *d = DirAccess::create(DirAccess::ACCESS_FILESYSTEM);
	Error err = d->make_dir_recursive(template_path);
	if (err != OK) {
		EditorNode::get_singleton()->show_warning(TTR("Error creating path for templates:") + "\n" + template_path);
		unzClose(pkg);
		return;
	}

	memdelete(d);

	ret = unzGoToFirstFile(pkg);

	EditorProgress *p = NULL;
	if (p_use_progress) {
		p = memnew(EditorProgress("ltask", TTR("Extracting Export Templates"), fc));
	}

	fc = 0;

	while (ret == UNZ_OK) {

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

		String file = String(fname).get_file();

		if (file.size() == 0) {
			ret = unzGoToNextFile(pkg);
			continue;
		}

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

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

		if (p) {
			p->step(TTR("Importing:") + " " + file, fc);
		}

		FileAccess *f = FileAccess::open(template_path.plus_file(file), FileAccess::WRITE);

		if (!f) {
			ret = unzGoToNextFile(pkg);
			fc++;
			ERR_CONTINUE(!f);
		}

		f->store_buffer(data.ptr(), data.size());

		memdelete(f);

		ret = unzGoToNextFile(pkg);
		fc++;
	}

	if (p) {
		memdelete(p);
	}

	unzClose(pkg);

	_update_template_list();
}
Example #26
0
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;
}
	void _choose_file(const String& p_path) {

		import_path->set_text(p_path);
		FileAccess *f = FileAccess::open(p_path,FileAccess::READ);
		if (!f) {

			error_dialog->set_text(TTR("Invalid source!"));
			error_dialog->popup_centered(Size2(200,100));
			return;

		}

		Vector<String> csvh = f->get_csv_line();
		memdelete(f);

		if (csvh.size()<2) {

			error_dialog->set_text(TTR("Invalid translation source!"));
			error_dialog->popup_centered(Size2(200,100));
			return;

		}

		columns->clear();
		columns->set_columns(2);
		TreeItem *root = columns->create_item();
		columns->set_hide_root(true);
		columns->set_column_titles_visible(true);
		columns->set_column_title(0,TTR("Column"));
		columns->set_column_title(1,TTR("Language"));
		Vector<String> langs = TranslationServer::get_all_locales();
		Vector<String> names = TranslationServer::get_all_locale_names();
		if (csvh[0]=="")
			ignore_first->set_pressed(true);


		items.clear();

		for(int i=1;i<csvh.size();i++) {

			TreeItem *ti = columns->create_item(root);

			ti->set_editable(0,true);
			ti->set_selectable(0,false);
			ti->set_cell_mode(0,TreeItem::CELL_MODE_CHECK);
			ti->set_checked(0,true);
			ti->set_text(0,itos(i));
			items.push_back(ti);

			String lname = csvh[i].to_lower().strip_edges();
			int idx=-1;
			String hint;
			for(int j=0;j<langs.size();j++) {

				if (langs[j]==lname.substr(0,langs[j].length()).to_lower()) {
					idx=j;
				}
				if (j>0) {
					hint+=",";
				}
				hint+=names[j].replace(","," ");
			}

			ti->set_cell_mode(1,TreeItem::CELL_MODE_RANGE);
			ti->set_text(1,hint);
			ti->set_editable(1,true);


			if (idx!=-1) {
				ignore_first->set_pressed(true);
				ti->set_range(1,idx);
			} else {

				//not found, maybe used stupid name
				if (lname.begins_with("br")) //brazilian
					ti->set_range(1,langs.find("pt"));
				else if (lname.begins_with("ch")) //chinese
					ti->set_range(1,langs.find("zh"));
				else if (lname.begins_with("sp")) //spanish
					ti->set_range(1,langs.find("es"));
				else if (lname.begins_with("kr"))// kprean
					ti->set_range(1,langs.find("ko"));
				else if (i==0)
					ti->set_range(1,langs.find("en"));
				else
					ti->set_range(1,langs.find("es"));
			}

			ti->set_metadata(1,names[ti->get_range(1)]);
		}



	}
Example #28
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;

}
Example #29
0
Error EditorExportPlatform::save_pack(const Ref<EditorExportPreset> &p_preset, const String &p_path, Vector<SharedObject> *p_so_files) {

	EditorProgress ep("savepack", TTR("Packing"), 102, true);

	String tmppath = EditorSettings::get_singleton()->get_cache_dir().plus_file("packtmp");
	FileAccess *ftmp = FileAccess::open(tmppath, FileAccess::WRITE);
	ERR_FAIL_COND_V(!ftmp, ERR_CANT_CREATE)

	PackData pd;
	pd.ep = &ep;
	pd.f = ftmp;
	pd.so_files = p_so_files;

	Error err = export_project_files(p_preset, _save_pack_file, &pd, _add_shared_object);

	memdelete(ftmp); //close tmp file

	if (err)
		return err;

	pd.file_ofs.sort(); //do sort, so we can do binary search later

	FileAccess *f = FileAccess::open(p_path, FileAccess::WRITE);
	ERR_FAIL_COND_V(!f, ERR_CANT_CREATE)
	f->store_32(0x43504447); //GDPK
	f->store_32(1); //pack version
	f->store_32(VERSION_MAJOR);
	f->store_32(VERSION_MINOR);
	f->store_32(0); //hmph
	for (int i = 0; i < 16; i++) {
		//reserved
		f->store_32(0);
	}

	f->store_32(pd.file_ofs.size()); //amount of files

	size_t header_size = f->get_position();

	//precalculate header size

	for (int i = 0; i < pd.file_ofs.size(); i++) {
		header_size += 4; // size of path string (32 bits is enough)
		uint32_t string_len = pd.file_ofs[i].path_utf8.length();
		header_size += string_len + _get_pad(4, string_len); ///size of path string
		header_size += 8; // offset to file _with_ header size included
		header_size += 8; // size of file
		header_size += 16; // md5
	}

	size_t header_padding = _get_pad(PCK_PADDING, header_size);

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

		uint32_t string_len = pd.file_ofs[i].path_utf8.length();
		uint32_t pad = _get_pad(4, string_len);
		;
		f->store_32(string_len + pad);
		f->store_buffer((const uint8_t *)pd.file_ofs[i].path_utf8.get_data(), string_len);
		for (uint32_t j = 0; j < pad; j++) {
			f->store_8(0);
		}

		f->store_64(pd.file_ofs[i].ofs + header_padding + header_size);
		f->store_64(pd.file_ofs[i].size); // pay attention here, this is where file is
		f->store_buffer(pd.file_ofs[i].md5.ptr(), 16); //also save md5 for file
	}

	for (uint32_t j = 0; j < header_padding; j++) {
		f->store_8(0);
	}

	//save the rest of the data

	ftmp = FileAccess::open(tmppath, FileAccess::READ);
	if (!ftmp) {
		memdelete(f);
		ERR_FAIL_COND_V(!ftmp, ERR_CANT_CREATE)
	}
void EditorResourcePreview::_thread() {

	while (!exit) {

		preview_sem->wait();
		preview_mutex->lock();

		if (queue.size()) {

			QueueItem item = queue.front()->get();
			queue.pop_front();

			if (cache.has(item.path)) {
				//already has it because someone loaded it, just let it know it's ready
				String path = item.path;
				if (item.resource.is_valid()) {
					path += ":" + itos(cache[item.path].last_hash); //keep last hash (see description of what this is in condition below)
				}

				_preview_ready(path, cache[item.path].preview, cache[item.path].small_preview, item.id, item.function, item.userdata);

				preview_mutex->unlock();
			} else {

				preview_mutex->unlock();

				Ref<ImageTexture> texture;
				Ref<ImageTexture> small_texture;

				int thumbnail_size = EditorSettings::get_singleton()->get("filesystem/file_dialog/thumbnail_size");
				thumbnail_size *= EDSCALE;

				if (item.resource.is_valid()) {

					_generate_preview(texture, small_texture, item, String());

					//adding hash to the end of path (should be ID:<objid>:<hash>) because of 5 argument limit to call_deferred
					_preview_ready(item.path + ":" + itos(item.resource->hash_edited_version()), texture, small_texture, item.id, item.function, item.userdata);

				} else {

					String temp_path = EditorSettings::get_singleton()->get_cache_dir();
					String cache_base = ProjectSettings::get_singleton()->globalize_path(item.path).md5_text();
					cache_base = temp_path.plus_file("resthumb-" + cache_base);

					//does not have it, try to load a cached thumbnail

					String file = cache_base + ".txt";
					FileAccess *f = FileAccess::open(file, FileAccess::READ);
					if (!f) {

						// No cache found, generate
						_generate_preview(texture, small_texture, item, cache_base);
					} else {

						uint64_t modtime = FileAccess::get_modified_time(item.path);
						int tsize = f->get_line().to_int64();
						bool has_small_texture = f->get_line().to_int();
						uint64_t last_modtime = f->get_line().to_int64();

						bool cache_valid = true;

						if (tsize != thumbnail_size) {

							cache_valid = false;
							memdelete(f);
						} else if (last_modtime != modtime) {

							String last_md5 = f->get_line();
							String md5 = FileAccess::get_md5(item.path);
							memdelete(f);

							if (last_md5 != md5) {

								cache_valid = false;

							} else {
								//update modified time

								f = FileAccess::open(file, FileAccess::WRITE);
								f->store_line(itos(modtime));
								f->store_line(itos(has_small_texture));
								f->store_line(md5);
								memdelete(f);
							}
						} else {
							memdelete(f);
						}

						if (cache_valid) {

							Ref<Image> img;
							img.instance();
							Ref<Image> small_img;
							small_img.instance();

							if (img->load(cache_base + ".png") != OK) {
								cache_valid = false;
							} else {

								texture.instance();
								texture->create_from_image(img, Texture::FLAG_FILTER);

								if (has_small_texture) {
									if (small_img->load(cache_base + "_small.png") != OK) {
										cache_valid = false;
									} else {
										small_texture.instance();
										small_texture->create_from_image(small_img, Texture::FLAG_FILTER);
									}
								}
							}
						}

						if (!cache_valid) {

							_generate_preview(texture, small_texture, item, cache_base);
						}
					}
					_preview_ready(item.path, texture, small_texture, item.id, item.function, item.userdata);
				}
			}

		} else {
			preview_mutex->unlock();
		}
	}
}