editor_resource_preview.cpp 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657
  1. /**************************************************************************/
  2. /* editor_resource_preview.cpp */
  3. /**************************************************************************/
  4. /* This file is part of: */
  5. /* GODOT ENGINE */
  6. /* https://godotengine.org */
  7. /**************************************************************************/
  8. /* Copyright (c) 2014-present Godot Engine contributors (see AUTHORS.md). */
  9. /* Copyright (c) 2007-2014 Juan Linietsky, Ariel Manzur. */
  10. /* */
  11. /* Permission is hereby granted, free of charge, to any person obtaining */
  12. /* a copy of this software and associated documentation files (the */
  13. /* "Software"), to deal in the Software without restriction, including */
  14. /* without limitation the rights to use, copy, modify, merge, publish, */
  15. /* distribute, sublicense, and/or sell copies of the Software, and to */
  16. /* permit persons to whom the Software is furnished to do so, subject to */
  17. /* the following conditions: */
  18. /* */
  19. /* The above copyright notice and this permission notice shall be */
  20. /* included in all copies or substantial portions of the Software. */
  21. /* */
  22. /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, */
  23. /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF */
  24. /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. */
  25. /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY */
  26. /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, */
  27. /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE */
  28. /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */
  29. /**************************************************************************/
  30. #include "editor_resource_preview.h"
  31. #include "core/config/project_settings.h"
  32. #include "core/io/file_access.h"
  33. #include "core/io/resource_loader.h"
  34. #include "core/io/resource_saver.h"
  35. #include "core/variant/variant_utility.h"
  36. #include "editor/editor_node.h"
  37. #include "editor/editor_paths.h"
  38. #include "editor/editor_settings.h"
  39. #include "editor/editor_string_names.h"
  40. #include "editor/themes/editor_scale.h"
  41. #include "scene/main/window.h"
  42. #include "scene/resources/image_texture.h"
  43. #include "servers/rendering/rendering_server_globals.h"
  44. bool EditorResourcePreviewGenerator::handles(const String &p_type) const {
  45. bool success = false;
  46. if (GDVIRTUAL_CALL(_handles, p_type, success)) {
  47. return success;
  48. }
  49. ERR_FAIL_V_MSG(false, "EditorResourcePreviewGenerator::_handles needs to be overridden.");
  50. }
  51. Ref<Texture2D> EditorResourcePreviewGenerator::generate(const Ref<Resource> &p_from, const Size2 &p_size, Dictionary &p_metadata) const {
  52. Ref<Texture2D> preview;
  53. if (GDVIRTUAL_CALL(_generate, p_from, p_size, p_metadata, preview)) {
  54. return preview;
  55. }
  56. ERR_FAIL_V_MSG(Ref<Texture2D>(), "EditorResourcePreviewGenerator::_generate needs to be overridden.");
  57. }
  58. Ref<Texture2D> EditorResourcePreviewGenerator::generate_from_path(const String &p_path, const Size2 &p_size, Dictionary &p_metadata) const {
  59. Ref<Texture2D> preview;
  60. if (GDVIRTUAL_CALL(_generate_from_path, p_path, p_size, p_metadata, preview)) {
  61. return preview;
  62. }
  63. Ref<Resource> res = ResourceLoader::load(p_path);
  64. if (res.is_null()) {
  65. return res;
  66. }
  67. return generate(res, p_size, p_metadata);
  68. }
  69. bool EditorResourcePreviewGenerator::generate_small_preview_automatically() const {
  70. bool success = false;
  71. GDVIRTUAL_CALL(_generate_small_preview_automatically, success);
  72. return success;
  73. }
  74. bool EditorResourcePreviewGenerator::can_generate_small_preview() const {
  75. bool success = false;
  76. GDVIRTUAL_CALL(_can_generate_small_preview, success);
  77. return success;
  78. }
  79. void EditorResourcePreviewGenerator::_bind_methods() {
  80. GDVIRTUAL_BIND(_handles, "type");
  81. GDVIRTUAL_BIND(_generate, "resource", "size", "metadata");
  82. GDVIRTUAL_BIND(_generate_from_path, "path", "size", "metadata");
  83. GDVIRTUAL_BIND(_generate_small_preview_automatically);
  84. GDVIRTUAL_BIND(_can_generate_small_preview);
  85. }
  86. void EditorResourcePreviewGenerator::DrawRequester::request_and_wait(RID p_viewport) {
  87. Callable request_vp_update_once = callable_mp(RS::get_singleton(), &RS::viewport_set_update_mode).bind(p_viewport, RS::VIEWPORT_UPDATE_ONCE);
  88. if (EditorResourcePreview::get_singleton()->is_threaded()) {
  89. if (!RS::get_singleton()->is_connected(SNAME("frame_pre_draw"), request_vp_update_once)) {
  90. RS::get_singleton()->connect(SNAME("frame_pre_draw"), request_vp_update_once, Object::CONNECT_ONE_SHOT);
  91. }
  92. RS::get_singleton()->request_frame_drawn_callback(callable_mp(this, &EditorResourcePreviewGenerator::DrawRequester::_post_semaphore));
  93. semaphore.wait();
  94. } else {
  95. // Avoid the main viewport and children being redrawn.
  96. SceneTree *st = Object::cast_to<SceneTree>(OS::get_singleton()->get_main_loop());
  97. ERR_FAIL_NULL_MSG(st, "Editor's MainLoop is not a SceneTree. This is a bug.");
  98. RID root_vp = st->get_root()->get_viewport_rid();
  99. RenderingServer::get_singleton()->viewport_set_active(root_vp, false);
  100. request_vp_update_once.call();
  101. RS::get_singleton()->draw(false);
  102. // Let main viewport and children be drawn again.
  103. RenderingServer::get_singleton()->viewport_set_active(root_vp, true);
  104. }
  105. }
  106. void EditorResourcePreviewGenerator::DrawRequester::abort() {
  107. if (EditorResourcePreview::get_singleton()->is_threaded()) {
  108. semaphore.post();
  109. }
  110. }
  111. Variant EditorResourcePreviewGenerator::DrawRequester::_post_semaphore() {
  112. semaphore.post();
  113. return Variant(); // Needed because of how the callback is used.
  114. }
  115. bool EditorResourcePreview::can_run_on_thread() const {
  116. return RSG::rasterizer->can_create_resources_async();
  117. }
  118. bool EditorResourcePreview::is_threaded() const {
  119. return thread.is_started();
  120. }
  121. void EditorResourcePreview::_thread_func(void *ud) {
  122. EditorResourcePreview *erp = (EditorResourcePreview *)ud;
  123. erp->_thread();
  124. }
  125. void EditorResourcePreview::_preview_ready(const String &p_path, int p_hash, const Ref<Texture2D> &p_texture, const Ref<Texture2D> &p_small_texture, ObjectID id, const StringName &p_func, const Variant &p_ud, const Dictionary &p_metadata) {
  126. {
  127. MutexLock lock(preview_mutex);
  128. uint64_t modified_time = 0;
  129. if (!p_path.begins_with("ID:")) {
  130. modified_time = FileAccess::get_modified_time(p_path);
  131. String import_path = p_path + ".import";
  132. if (FileAccess::exists(import_path)) {
  133. modified_time = MAX(modified_time, FileAccess::get_modified_time(import_path));
  134. }
  135. }
  136. Item item;
  137. item.preview = p_texture;
  138. item.small_preview = p_small_texture;
  139. item.last_hash = p_hash;
  140. item.modified_time = modified_time;
  141. item.preview_metadata = p_metadata;
  142. cache[p_path] = item;
  143. }
  144. Callable(id, p_func).call_deferred(p_path, p_texture, p_small_texture, p_ud);
  145. }
  146. void EditorResourcePreview::_generate_preview(Ref<ImageTexture> &r_texture, Ref<ImageTexture> &r_small_texture, const QueueItem &p_item, const String &cache_base, Dictionary &p_metadata) {
  147. String type;
  148. uint64_t started_at = OS::get_singleton()->get_ticks_usec();
  149. if (p_item.resource.is_valid()) {
  150. type = p_item.resource->get_class();
  151. } else {
  152. type = ResourceLoader::get_resource_type(p_item.path);
  153. }
  154. if (type.is_empty()) {
  155. r_texture = Ref<ImageTexture>();
  156. r_small_texture = Ref<ImageTexture>();
  157. if (is_print_verbose_enabled()) {
  158. print_line(vformat("Generated '%s' preview in %d usec", p_item.path, OS::get_singleton()->get_ticks_usec() - started_at));
  159. }
  160. return; //could not guess type
  161. }
  162. int thumbnail_size = EDITOR_GET("filesystem/file_dialog/thumbnail_size");
  163. thumbnail_size *= EDSCALE;
  164. r_texture = Ref<ImageTexture>();
  165. r_small_texture = Ref<ImageTexture>();
  166. for (int i = 0; i < preview_generators.size(); i++) {
  167. if (!preview_generators[i]->handles(type)) {
  168. continue;
  169. }
  170. Ref<Texture2D> generated;
  171. if (p_item.resource.is_valid()) {
  172. generated = preview_generators.write[i]->generate(p_item.resource, Vector2(thumbnail_size, thumbnail_size), p_metadata);
  173. } else {
  174. generated = preview_generators.write[i]->generate_from_path(p_item.path, Vector2(thumbnail_size, thumbnail_size), p_metadata);
  175. }
  176. r_texture = generated;
  177. if (preview_generators[i]->can_generate_small_preview()) {
  178. Ref<Texture2D> generated_small;
  179. Dictionary d;
  180. if (p_item.resource.is_valid()) {
  181. generated_small = preview_generators.write[i]->generate(p_item.resource, Vector2(small_thumbnail_size, small_thumbnail_size), d);
  182. } else {
  183. generated_small = preview_generators.write[i]->generate_from_path(p_item.path, Vector2(small_thumbnail_size, small_thumbnail_size), d);
  184. }
  185. r_small_texture = generated_small;
  186. }
  187. if (r_small_texture.is_null() && r_texture.is_valid() && preview_generators[i]->generate_small_preview_automatically()) {
  188. Ref<Image> small_image = r_texture->get_image();
  189. small_image = small_image->duplicate();
  190. small_image->resize(small_thumbnail_size, small_thumbnail_size, Image::INTERPOLATE_CUBIC);
  191. r_small_texture.instantiate();
  192. r_small_texture->set_image(small_image);
  193. }
  194. if (generated.is_valid()) {
  195. break;
  196. }
  197. }
  198. if (p_item.resource.is_null()) {
  199. // Cache the preview in case it's a resource on disk.
  200. if (r_texture.is_valid()) {
  201. // Wow it generated a preview... save cache.
  202. bool has_small_texture = r_small_texture.is_valid();
  203. ResourceSaver::save(r_texture, cache_base + ".png");
  204. if (has_small_texture) {
  205. ResourceSaver::save(r_small_texture, cache_base + "_small.png");
  206. }
  207. Ref<FileAccess> f = FileAccess::open(cache_base + ".txt", FileAccess::WRITE);
  208. ERR_FAIL_COND_MSG(f.is_null(), "Cannot create file '" + cache_base + ".txt'. Check user write permissions.");
  209. uint64_t modtime = FileAccess::get_modified_time(p_item.path);
  210. String import_path = p_item.path + ".import";
  211. if (FileAccess::exists(import_path)) {
  212. modtime = MAX(modtime, FileAccess::get_modified_time(import_path));
  213. }
  214. _write_preview_cache(f, thumbnail_size, has_small_texture, modtime, FileAccess::get_md5(p_item.path), p_metadata);
  215. }
  216. }
  217. if (is_print_verbose_enabled()) {
  218. print_line(vformat("Generated '%s' preview in %d usec", p_item.path, OS::get_singleton()->get_ticks_usec() - started_at));
  219. }
  220. }
  221. const Dictionary EditorResourcePreview::get_preview_metadata(const String &p_path) const {
  222. ERR_FAIL_COND_V(!cache.has(p_path), Dictionary());
  223. return cache[p_path].preview_metadata;
  224. }
  225. void EditorResourcePreview::_iterate() {
  226. preview_mutex.lock();
  227. if (queue.is_empty()) {
  228. preview_mutex.unlock();
  229. return;
  230. }
  231. QueueItem item = queue.front()->get();
  232. queue.pop_front();
  233. singleton->processing_item = item;
  234. singleton->last_process_msec = OS::get_singleton()->get_ticks_msec();
  235. if (cache.has(item.path)) {
  236. Item cached_item = cache[item.path];
  237. // Already has it because someone loaded it, just let it know it's ready.
  238. _preview_ready(item.path, cached_item.last_hash, cached_item.preview, cached_item.small_preview, item.id, item.function, item.userdata, cached_item.preview_metadata);
  239. singleton->processing_item = QueueItem();
  240. preview_mutex.unlock();
  241. return;
  242. }
  243. preview_mutex.unlock();
  244. Ref<ImageTexture> texture;
  245. Ref<ImageTexture> small_texture;
  246. int thumbnail_size = EDITOR_GET("filesystem/file_dialog/thumbnail_size");
  247. thumbnail_size *= EDSCALE;
  248. if (item.resource.is_valid()) {
  249. Dictionary preview_metadata;
  250. _generate_preview(texture, small_texture, item, String(), preview_metadata);
  251. _preview_ready(item.path, item.resource->hash_edited_version_for_preview(), texture, small_texture, item.id, item.function, item.userdata, preview_metadata);
  252. preview_mutex.lock();
  253. singleton->processing_item = QueueItem();
  254. preview_mutex.unlock();
  255. return;
  256. }
  257. Dictionary preview_metadata;
  258. String temp_path = EditorPaths::get_singleton()->get_cache_dir();
  259. String cache_base = ProjectSettings::get_singleton()->globalize_path(item.path).md5_text();
  260. cache_base = temp_path.path_join("resthumb-" + cache_base);
  261. // Does not have it, try to load a cached thumbnail.
  262. String file = cache_base + ".txt";
  263. Ref<FileAccess> f = FileAccess::open(file, FileAccess::READ);
  264. if (f.is_null()) {
  265. // No cache found, generate.
  266. _generate_preview(texture, small_texture, item, cache_base, preview_metadata);
  267. } else {
  268. uint64_t modtime = FileAccess::get_modified_time(item.path);
  269. String import_path = item.path + ".import";
  270. if (FileAccess::exists(import_path)) {
  271. modtime = MAX(modtime, FileAccess::get_modified_time(import_path));
  272. }
  273. int tsize;
  274. bool has_small_texture;
  275. uint64_t last_modtime;
  276. String hash;
  277. bool outdated;
  278. _read_preview_cache(f, &tsize, &has_small_texture, &last_modtime, &hash, &preview_metadata, &outdated);
  279. bool cache_valid = true;
  280. if (tsize != thumbnail_size) {
  281. cache_valid = false;
  282. f.unref();
  283. } else if (outdated) {
  284. cache_valid = false;
  285. f.unref();
  286. } else if (last_modtime != modtime) {
  287. String last_md5 = hash;
  288. String md5 = FileAccess::get_md5(item.path);
  289. f.unref();
  290. if (last_md5 != md5) {
  291. cache_valid = false;
  292. } else {
  293. // Update modified time.
  294. Ref<FileAccess> f2 = FileAccess::open(file, FileAccess::WRITE);
  295. if (f2.is_null()) {
  296. // Not returning as this would leave the thread hanging and would require
  297. // some proper cleanup/disabling of resource preview generation.
  298. ERR_PRINT("Cannot create file '" + file + "'. Check user write permissions.");
  299. } else {
  300. _write_preview_cache(f2, thumbnail_size, has_small_texture, modtime, md5, preview_metadata);
  301. }
  302. }
  303. } else {
  304. f.unref();
  305. }
  306. if (cache_valid) {
  307. Ref<Image> img;
  308. img.instantiate();
  309. Ref<Image> small_img;
  310. small_img.instantiate();
  311. if (img->load(cache_base + ".png") != OK) {
  312. cache_valid = false;
  313. } else {
  314. texture.instantiate();
  315. texture->set_image(img);
  316. if (has_small_texture) {
  317. if (small_img->load(cache_base + "_small.png") != OK) {
  318. cache_valid = false;
  319. } else {
  320. small_texture.instantiate();
  321. small_texture->set_image(small_img);
  322. }
  323. }
  324. }
  325. }
  326. if (!cache_valid) {
  327. _generate_preview(texture, small_texture, item, cache_base, preview_metadata);
  328. }
  329. }
  330. _preview_ready(item.path, 0, texture, small_texture, item.id, item.function, item.userdata, preview_metadata);
  331. preview_mutex.lock();
  332. singleton->processing_item = QueueItem();
  333. preview_mutex.unlock();
  334. }
  335. void EditorResourcePreview::_write_preview_cache(Ref<FileAccess> p_file, int p_thumbnail_size, bool p_has_small_texture, uint64_t p_modified_time, const String &p_hash, const Dictionary &p_metadata) {
  336. p_file->store_line(itos(p_thumbnail_size));
  337. p_file->store_line(itos(p_has_small_texture));
  338. p_file->store_line(itos(p_modified_time));
  339. p_file->store_line(p_hash);
  340. p_file->store_line(VariantUtilityFunctions::var_to_str(p_metadata).replace_char('\n', ' '));
  341. p_file->store_line(itos(CURRENT_METADATA_VERSION));
  342. }
  343. void EditorResourcePreview::_read_preview_cache(Ref<FileAccess> p_file, int *r_thumbnail_size, bool *r_has_small_texture, uint64_t *r_modified_time, String *r_hash, Dictionary *r_metadata, bool *r_outdated) {
  344. *r_thumbnail_size = p_file->get_line().to_int();
  345. *r_has_small_texture = p_file->get_line().to_int();
  346. *r_modified_time = p_file->get_line().to_int();
  347. *r_hash = p_file->get_line();
  348. *r_metadata = VariantUtilityFunctions::str_to_var(p_file->get_line());
  349. *r_outdated = p_file->get_line().to_int() < CURRENT_METADATA_VERSION;
  350. }
  351. void EditorResourcePreview::_thread() {
  352. exited.clear();
  353. while (!exiting.is_set()) {
  354. preview_sem.wait();
  355. _iterate();
  356. }
  357. exited.set();
  358. }
  359. void EditorResourcePreview::_idle_callback() {
  360. if (!singleton) {
  361. // Just in case the shutdown of the editor involves the deletion of the singleton
  362. // happening while additional idle callbacks can happen.
  363. return;
  364. }
  365. singleton->_update_progress_bar();
  366. // Ensure to process one item at a time
  367. singleton->preview_mutex.lock();
  368. bool processing = singleton->processing_item.path != "";
  369. singleton->preview_mutex.unlock();
  370. if (processing) {
  371. return;
  372. }
  373. singleton->_iterate();
  374. }
  375. EditorProgress *EditorResourcePreview::thumbnail_progress = nullptr; // it's static
  376. void EditorResourcePreview::_update_progress_bar() {
  377. DEV_ASSERT(Thread::get_caller_id() == Thread::get_main_id()); // Progress bar can only be updated in main thread
  378. // Return if nothing is happening
  379. if (singleton->queue.is_empty() && thumbnail_progress == nullptr) {
  380. singleton->progress_total_steps = -1;
  381. return;
  382. }
  383. // Create progress bar if not present
  384. if (!singleton->queue.is_empty() && thumbnail_progress == nullptr && singleton->progress_total_steps == -1) {
  385. singleton->progress_total_steps = singleton->queue.size();
  386. thumbnail_progress = memnew(EditorProgress("generate_thumbnails", "Generate Thumbnails", singleton->progress_total_steps));
  387. }
  388. // Update progress bar
  389. if (!singleton->queue.is_empty() && thumbnail_progress != nullptr) {
  390. // The full path could be too long to display, show only the file name
  391. String queue_file;
  392. if (singleton->queue.front()->get().path.count("/") > 1) {
  393. queue_file = singleton->queue.front()->get().path.rsplit("/", true, 1)[1];
  394. }
  395. int queue_steps = singleton->progress_total_steps - singleton->queue.size();
  396. int queue_total = singleton->progress_total_steps;
  397. String msg = vformat("%s (%d/%d)", queue_file, queue_steps, queue_total);
  398. // Don't force update or will stuck in infinite loop at _idle_callback(), since ProgressDialog::task_step() iterates the main loop
  399. thumbnail_progress->step(msg, queue_steps, false);
  400. }
  401. // Destroy progress bar when queue empty
  402. if (singleton->queue.is_empty() && thumbnail_progress != nullptr) {
  403. memdelete(thumbnail_progress);
  404. thumbnail_progress = nullptr;
  405. }
  406. return;
  407. }
  408. void EditorResourcePreview::_update_thumbnail_sizes() {
  409. if (small_thumbnail_size == -1) {
  410. // Kind of a workaround to retrieve the default icon size.
  411. small_thumbnail_size = EditorNode::get_singleton()->get_editor_theme()->get_icon(SNAME("Object"), EditorStringName(EditorIcons))->get_width();
  412. }
  413. }
  414. EditorResourcePreview::PreviewItem EditorResourcePreview::get_resource_preview_if_available(const String &p_path) {
  415. PreviewItem item;
  416. {
  417. MutexLock lock(preview_mutex);
  418. HashMap<String, EditorResourcePreview::Item>::Iterator I = cache.find(p_path);
  419. if (!I) {
  420. return item;
  421. }
  422. EditorResourcePreview::Item &cached_item = I->value;
  423. item.preview = cached_item.preview;
  424. item.small_preview = cached_item.small_preview;
  425. }
  426. preview_sem.post();
  427. return item;
  428. }
  429. void EditorResourcePreview::queue_edited_resource_preview(const Ref<Resource> &p_res, Object *p_receiver, const StringName &p_receiver_func, const Variant &p_userdata) {
  430. ERR_FAIL_NULL(p_receiver);
  431. ERR_FAIL_COND(p_res.is_null());
  432. _update_thumbnail_sizes();
  433. {
  434. MutexLock lock(preview_mutex);
  435. String path_id = "ID:" + itos(p_res->get_instance_id());
  436. if (cache.has(path_id) && cache[path_id].last_hash == p_res->hash_edited_version_for_preview()) {
  437. p_receiver->call(p_receiver_func, path_id, cache[path_id].preview, cache[path_id].small_preview, p_userdata);
  438. return;
  439. }
  440. cache.erase(path_id); //erase if exists, since it will be regen
  441. QueueItem item;
  442. item.function = p_receiver_func;
  443. item.id = p_receiver->get_instance_id();
  444. item.resource = p_res;
  445. item.path = path_id;
  446. item.userdata = p_userdata;
  447. queue.push_back(item);
  448. }
  449. preview_sem.post();
  450. }
  451. void EditorResourcePreview::queue_resource_preview(const String &p_path, Object *p_receiver, const StringName &p_receiver_func, const Variant &p_userdata) {
  452. ERR_FAIL_NULL(p_receiver);
  453. _update_thumbnail_sizes();
  454. {
  455. MutexLock lock(preview_mutex);
  456. if (cache.has(p_path)) {
  457. p_receiver->call(p_receiver_func, p_path, cache[p_path].preview, cache[p_path].small_preview, p_userdata);
  458. return;
  459. }
  460. QueueItem item;
  461. item.function = p_receiver_func;
  462. item.id = p_receiver->get_instance_id();
  463. item.path = p_path;
  464. item.userdata = p_userdata;
  465. queue.push_back(item);
  466. }
  467. preview_sem.post();
  468. }
  469. void EditorResourcePreview::add_preview_generator(const Ref<EditorResourcePreviewGenerator> &p_generator) {
  470. preview_generators.push_back(p_generator);
  471. }
  472. void EditorResourcePreview::remove_preview_generator(const Ref<EditorResourcePreviewGenerator> &p_generator) {
  473. preview_generators.erase(p_generator);
  474. }
  475. EditorResourcePreview *EditorResourcePreview::get_singleton() {
  476. return singleton;
  477. }
  478. void EditorResourcePreview::_bind_methods() {
  479. ClassDB::bind_method(D_METHOD("queue_resource_preview", "path", "receiver", "receiver_func", "userdata"), &EditorResourcePreview::queue_resource_preview);
  480. ClassDB::bind_method(D_METHOD("queue_edited_resource_preview", "resource", "receiver", "receiver_func", "userdata"), &EditorResourcePreview::queue_edited_resource_preview);
  481. ClassDB::bind_method(D_METHOD("add_preview_generator", "generator"), &EditorResourcePreview::add_preview_generator);
  482. ClassDB::bind_method(D_METHOD("remove_preview_generator", "generator"), &EditorResourcePreview::remove_preview_generator);
  483. ClassDB::bind_method(D_METHOD("check_for_invalidation", "path"), &EditorResourcePreview::check_for_invalidation);
  484. ADD_SIGNAL(MethodInfo("preview_invalidated", PropertyInfo(Variant::STRING, "path")));
  485. }
  486. void EditorResourcePreview::_notification(int p_what) {
  487. switch (p_what) {
  488. case NOTIFICATION_EXIT_TREE: {
  489. stop();
  490. } break;
  491. }
  492. }
  493. void EditorResourcePreview::check_for_invalidation(const String &p_path) {
  494. bool call_invalidated = false;
  495. {
  496. MutexLock lock(preview_mutex);
  497. if (cache.has(p_path)) {
  498. uint64_t modified_time = FileAccess::get_modified_time(p_path);
  499. String import_path = p_path + ".import";
  500. if (FileAccess::exists(import_path)) {
  501. modified_time = MAX(modified_time, FileAccess::get_modified_time(import_path));
  502. }
  503. if (modified_time != cache[p_path].modified_time) {
  504. cache.erase(p_path);
  505. call_invalidated = true;
  506. }
  507. }
  508. }
  509. if (call_invalidated) { //do outside mutex
  510. call_deferred(SNAME("emit_signal"), "preview_invalidated", p_path);
  511. }
  512. }
  513. void EditorResourcePreview::start() {
  514. if (DisplayServer::get_singleton()->get_name() == "headless") {
  515. return;
  516. }
  517. if (can_run_on_thread()) {
  518. ERR_FAIL_COND_MSG(thread.is_started(), "Thread already started.");
  519. thread.start(_thread_func, this);
  520. } else {
  521. SceneTree *st = Object::cast_to<SceneTree>(OS::get_singleton()->get_main_loop());
  522. ERR_FAIL_NULL_MSG(st, "Editor's MainLoop is not a SceneTree. This is a bug.");
  523. st->add_idle_callback(&_idle_callback);
  524. }
  525. }
  526. void EditorResourcePreview::stop() {
  527. if (is_threaded()) {
  528. exiting.set();
  529. preview_sem.post();
  530. for (int i = 0; i < preview_generators.size(); i++) {
  531. preview_generators.write[i]->abort();
  532. }
  533. while (!exited.is_set()) {
  534. // Sync pending work.
  535. OS::get_singleton()->delay_usec(10000);
  536. RenderingServer::get_singleton()->sync();
  537. MessageQueue::get_singleton()->flush();
  538. }
  539. thread.wait_to_finish();
  540. }
  541. }
  542. EditorResourcePreview::EditorResourcePreview() {
  543. singleton = this;
  544. }
  545. EditorResourcePreview::~EditorResourcePreview() {
  546. stop();
  547. }