ViewWidget.cpp 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. /*
  2. * Copyright (c) 2018-2021, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021, Linus Groh <linusg@serenityos.org>
  4. * Copyright (c) 2021, Mohsan Ali <mohsan0073@gmail.com>
  5. * Copyright (c) 2022, Mustafa Quraish <mustafa@serenityos.org>
  6. * Copyright (c) 2022, the SerenityOS developers.
  7. * Copyright (c) 2023, Caoimhe Byrne <caoimhebyrne06@gmail.com>
  8. * Copyright (c) 2023, MacDue <macdue@dueutil.tech>
  9. *
  10. * SPDX-License-Identifier: BSD-2-Clause
  11. */
  12. #include "ViewWidget.h"
  13. #include <AK/LexicalPath.h>
  14. #include <AK/StringBuilder.h>
  15. #include <LibCore/Directory.h>
  16. #include <LibCore/MappedFile.h>
  17. #include <LibCore/MimeData.h>
  18. #include <LibCore/Timer.h>
  19. #include <LibFileSystemAccessClient/Client.h>
  20. #include <LibGUI/Application.h>
  21. #include <LibGUI/MessageBox.h>
  22. #include <LibGfx/Bitmap.h>
  23. #include <LibGfx/ImageFormats/ImageDecoder.h>
  24. #include <LibGfx/Orientation.h>
  25. #include <LibGfx/Palette.h>
  26. #include <LibImageDecoderClient/Client.h>
  27. namespace ImageViewer {
  28. void VectorImage::flip(Gfx::Orientation orientation)
  29. {
  30. if (orientation == Gfx::Orientation::Horizontal)
  31. apply_transform(Gfx::AffineTransform {}.scale(-1, 1));
  32. else
  33. apply_transform(Gfx::AffineTransform {}.scale(1, -1));
  34. }
  35. void VectorImage::rotate(Gfx::RotationDirection rotation_direction)
  36. {
  37. if (rotation_direction == Gfx::RotationDirection::Clockwise)
  38. apply_transform(Gfx::AffineTransform {}.rotate_radians(AK::Pi<float> / 2));
  39. else
  40. apply_transform(Gfx::AffineTransform {}.rotate_radians(-AK::Pi<float> / 2));
  41. m_size = { m_size.height(), m_size.width() };
  42. }
  43. void VectorImage::draw_into(Gfx::Painter& painter, Gfx::IntRect const& dest, Gfx::Painter::ScalingMode) const
  44. {
  45. m_vector->draw_into(painter, dest, m_transform);
  46. }
  47. ErrorOr<NonnullRefPtr<Gfx::Bitmap>> VectorImage::bitmap(Optional<Gfx::IntSize> ideal_size) const
  48. {
  49. return m_vector->bitmap(ideal_size.value_or(size()), m_transform);
  50. }
  51. void BitmapImage::flip(Gfx::Orientation orientation)
  52. {
  53. m_bitmap = m_bitmap->flipped(orientation).release_value_but_fixme_should_propagate_errors();
  54. }
  55. void BitmapImage::rotate(Gfx::RotationDirection rotation)
  56. {
  57. m_bitmap = m_bitmap->rotated(rotation).release_value_but_fixme_should_propagate_errors();
  58. }
  59. void BitmapImage::draw_into(Gfx::Painter& painter, Gfx::IntRect const& dest, Gfx::Painter::ScalingMode scaling_mode) const
  60. {
  61. painter.draw_scaled_bitmap(dest, *m_bitmap, m_bitmap->rect(), 1.0f, scaling_mode);
  62. }
  63. ViewWidget::ViewWidget()
  64. : m_timer(Core::Timer::try_create().release_value_but_fixme_should_propagate_errors())
  65. {
  66. set_fill_with_background_color(false);
  67. }
  68. void ViewWidget::clear()
  69. {
  70. m_timer->stop();
  71. m_animation.clear();
  72. m_image = nullptr;
  73. if (on_image_change)
  74. on_image_change(m_image);
  75. set_original_rect({});
  76. m_path = {};
  77. reset_view();
  78. update();
  79. }
  80. void ViewWidget::flip(Gfx::Orientation orientation)
  81. {
  82. m_image->flip(orientation);
  83. scale_image_for_window();
  84. }
  85. void ViewWidget::rotate(Gfx::RotationDirection rotation_direction)
  86. {
  87. m_image->rotate(rotation_direction);
  88. scale_image_for_window();
  89. }
  90. bool ViewWidget::is_next_available() const
  91. {
  92. if (m_current_index.has_value())
  93. return m_current_index.value() + 1 < m_files_in_same_dir.size();
  94. return false;
  95. }
  96. bool ViewWidget::is_previous_available() const
  97. {
  98. if (m_current_index.has_value())
  99. return m_current_index.value() > 0;
  100. return false;
  101. }
  102. // FIXME: Convert to `String` & use LibFileSystemAccessClient + `Core::System::unveil(nullptr, nullptr)`
  103. // - Converting to String is not super-trivial due to the LexicalPath usage, while we can do a bunch of
  104. // String::from_deprecated_string() and String.to_deprecated_string(), it is quite ugly to read and
  105. // probably not the best approach.
  106. //
  107. // - If we go full-unveil (`Core::System::unveil(nullptr, nullptr)`) this functionality does not work,
  108. // we can not access the list of contents of a directory through LibFileSystemAccessClient at the moment.
  109. Vector<DeprecatedString> ViewWidget::load_files_from_directory(DeprecatedString const& path) const
  110. {
  111. Vector<DeprecatedString> files_in_directory;
  112. auto current_dir = LexicalPath(path).parent().string();
  113. // FIXME: Propagate errors
  114. (void)Core::Directory::for_each_entry(current_dir, Core::DirIterator::Flags::SkipDots, [&](auto const& entry, auto const& directory) -> ErrorOr<IterationDecision> {
  115. auto full_path = LexicalPath::join(directory.path().string(), entry.name).string();
  116. if (Gfx::Bitmap::is_path_a_supported_image_format(full_path))
  117. files_in_directory.append(full_path);
  118. return IterationDecision::Continue;
  119. });
  120. return files_in_directory;
  121. }
  122. void ViewWidget::set_path(String const& path)
  123. {
  124. m_path = path;
  125. m_files_in_same_dir = load_files_from_directory(path.to_deprecated_string());
  126. m_current_index = m_files_in_same_dir.find_first_index(path.to_deprecated_string());
  127. }
  128. void ViewWidget::navigate(Directions direction)
  129. {
  130. if (!m_current_index.has_value()) {
  131. return;
  132. }
  133. auto index = m_current_index.value();
  134. if (direction == Directions::Back) {
  135. index--;
  136. } else if (direction == Directions::Forward) {
  137. index++;
  138. } else if (direction == Directions::First) {
  139. index = 0;
  140. } else if (direction == Directions::Last) {
  141. index = m_files_in_same_dir.size() - 1;
  142. }
  143. auto result = FileSystemAccessClient::Client::the().request_file_read_only_approved(window(), m_files_in_same_dir.at(index));
  144. if (result.is_error())
  145. return;
  146. m_current_index = index;
  147. auto value = result.release_value();
  148. open_file(value.filename(), value.stream());
  149. }
  150. void ViewWidget::doubleclick_event(GUI::MouseEvent&)
  151. {
  152. on_doubleclick();
  153. }
  154. void ViewWidget::paint_event(GUI::PaintEvent& event)
  155. {
  156. Frame::paint_event(event);
  157. GUI::Painter painter(*this);
  158. painter.add_clip_rect(event.rect());
  159. painter.add_clip_rect(frame_inner_rect());
  160. Gfx::StylePainter::paint_transparency_grid(painter, frame_inner_rect(), palette());
  161. if (m_image)
  162. return m_image->draw_into(painter, content_rect(), m_scaling_mode);
  163. }
  164. void ViewWidget::mousedown_event(GUI::MouseEvent& event)
  165. {
  166. if (event.button() == GUI::MouseButton::Primary)
  167. start_panning(event.position());
  168. GUI::AbstractZoomPanWidget::mousedown_event(event);
  169. }
  170. void ViewWidget::mouseup_event(GUI::MouseEvent& event)
  171. {
  172. if (event.button() == GUI::MouseButton::Primary)
  173. stop_panning();
  174. GUI::AbstractZoomPanWidget::mouseup_event(event);
  175. }
  176. void ViewWidget::open_file(String const& path, Core::File& file)
  177. {
  178. auto open_result = try_open_file(path, file);
  179. if (open_result.is_error()) {
  180. auto error = open_result.release_error();
  181. auto user_error_message = String::formatted("Failed to open the image: {}.", error).release_value_but_fixme_should_propagate_errors();
  182. GUI::MessageBox::show_error(nullptr, user_error_message);
  183. }
  184. }
  185. ErrorOr<void> ViewWidget::try_open_file(String const& path, Core::File& file)
  186. {
  187. auto file_data = TRY(file.read_until_eof());
  188. bool is_animated = false;
  189. size_t loop_count = 0;
  190. Vector<Animation::Frame> frames;
  191. // Note: Doing this check only requires reading the header of images
  192. // (so if the image is not vector graphics it can be still be decoded OOP).
  193. if (auto decoder = Gfx::ImageDecoder::try_create_for_raw_bytes(file_data); decoder && decoder->is_vector()) {
  194. // Use in-process decoding for vector graphics.
  195. is_animated = decoder->is_animated();
  196. loop_count = decoder->loop_count();
  197. frames.ensure_capacity(decoder->frame_count());
  198. for (u32 i = 0; i < decoder->frame_count(); i++) {
  199. auto frame_data = TRY(decoder->vector_frame(i));
  200. frames.unchecked_append({ VectorImage::create(*frame_data.image), frame_data.duration });
  201. }
  202. } else {
  203. // Use out-of-process decoding for raster formats.
  204. auto client = TRY(ImageDecoderClient::Client::try_create());
  205. auto mime_type = Core::guess_mime_type_based_on_filename(path);
  206. auto decoded_image = client->decode_image(file_data, mime_type);
  207. if (!decoded_image.has_value()) {
  208. return Error::from_string_literal("Failed to decode image");
  209. }
  210. is_animated = decoded_image->is_animated;
  211. loop_count = decoded_image->loop_count;
  212. frames.ensure_capacity(decoded_image->frames.size());
  213. for (u32 i = 0; i < decoded_image->frames.size(); i++) {
  214. auto& frame_data = decoded_image->frames[i];
  215. frames.unchecked_append({ BitmapImage::create(*frame_data.bitmap), int(frame_data.duration) });
  216. }
  217. }
  218. m_image = frames[0].image;
  219. if (is_animated && frames.size() > 1) {
  220. m_animation = Animation { loop_count, move(frames) };
  221. }
  222. set_original_rect(m_image->rect());
  223. if (m_animation.has_value()) {
  224. auto const& first_frame = m_animation->frames[0];
  225. m_timer->set_interval(first_frame.duration);
  226. m_timer->on_timeout = [this] { animate(); };
  227. m_timer->start();
  228. } else {
  229. m_timer->stop();
  230. }
  231. set_path(path);
  232. GUI::Application::the()->set_most_recently_open_file(path);
  233. if (on_image_change)
  234. on_image_change(m_image);
  235. if (scaled_for_first_image())
  236. scale_image_for_window();
  237. else
  238. reset_view();
  239. return {};
  240. }
  241. void ViewWidget::drag_enter_event(GUI::DragEvent& event)
  242. {
  243. auto const& mime_types = event.mime_types();
  244. if (mime_types.contains_slow("text/uri-list"sv))
  245. event.accept();
  246. }
  247. void ViewWidget::drop_event(GUI::DropEvent& event)
  248. {
  249. event.accept();
  250. if (on_drop)
  251. on_drop(event);
  252. }
  253. void ViewWidget::resize_event(GUI::ResizeEvent& event)
  254. {
  255. event.accept();
  256. scale_image_for_window();
  257. }
  258. void ViewWidget::scale_image_for_window()
  259. {
  260. if (!m_image)
  261. return;
  262. set_original_rect(m_image->rect());
  263. fit_content_to_view(GUI::AbstractZoomPanWidget::FitType::Both);
  264. }
  265. void ViewWidget::resize_window()
  266. {
  267. if (window()->is_fullscreen() || window()->is_maximized())
  268. return;
  269. auto absolute_bitmap_rect = content_rect();
  270. absolute_bitmap_rect.translate_by(window()->rect().top_left());
  271. if (!m_image)
  272. return;
  273. auto new_size = content_rect().size();
  274. if (new_size.width() < 300)
  275. new_size.set_width(300);
  276. if (new_size.height() < 200)
  277. new_size.set_height(200);
  278. if (new_size.width() > 500)
  279. new_size = { 500, 500 * absolute_bitmap_rect.height() / absolute_bitmap_rect.width() };
  280. if (new_size.height() > 500)
  281. new_size = { 500 * absolute_bitmap_rect.width() / absolute_bitmap_rect.height(), 500 };
  282. new_size.set_height(new_size.height() + m_toolbar_height);
  283. window()->resize(new_size);
  284. scale_image_for_window();
  285. }
  286. void ViewWidget::set_image(Image const* image)
  287. {
  288. if (m_image == image)
  289. return;
  290. m_image = image;
  291. set_original_rect(m_image->rect());
  292. update();
  293. }
  294. // Same as ImageWidget::animate(), you probably want to keep any changes in sync
  295. void ViewWidget::animate()
  296. {
  297. if (!m_animation.has_value())
  298. return;
  299. m_current_frame_index = (m_current_frame_index + 1) % m_animation->frames.size();
  300. auto const& current_frame = m_animation->frames[m_current_frame_index];
  301. set_image(current_frame.image);
  302. if ((int)current_frame.duration != m_timer->interval()) {
  303. m_timer->restart(current_frame.duration);
  304. }
  305. if (m_current_frame_index == m_animation->frames.size() - 1) {
  306. ++m_loops_completed;
  307. if (m_loops_completed > 0 && m_loops_completed == m_animation->loop_count) {
  308. m_timer->stop();
  309. }
  310. }
  311. }
  312. void ViewWidget::set_scaling_mode(Gfx::Painter::ScalingMode scaling_mode)
  313. {
  314. m_scaling_mode = scaling_mode;
  315. update();
  316. }
  317. }