ImageEditor.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826
  1. /*
  2. * Copyright (c) 2020, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2021, Tobias Christiansen <tobyase@serenityos.org>
  4. * Copyright (c) 2021-2022, Mustafa Quraish <mustafa@serenityos.org>
  5. * Copyright (c) 2021, David Isaksson <davidisaksson93@gmail.com>
  6. * Copyright (c) 2022, Timothy Slater <tslater2006@gmail.com>
  7. *
  8. * SPDX-License-Identifier: BSD-2-Clause
  9. */
  10. #include "ImageEditor.h"
  11. #include "Image.h"
  12. #include "Layer.h"
  13. #include "Tools/MoveTool.h"
  14. #include "Tools/Tool.h"
  15. #include <AK/IntegralMath.h>
  16. #include <AK/LexicalPath.h>
  17. #include <LibConfig/Client.h>
  18. #include <LibFileSystemAccessClient/Client.h>
  19. #include <LibGUI/Command.h>
  20. #include <LibGUI/MessageBox.h>
  21. #include <LibGUI/Painter.h>
  22. #include <LibGfx/DisjointRectSet.h>
  23. #include <LibGfx/Palette.h>
  24. #include <LibGfx/Rect.h>
  25. namespace PixelPaint {
  26. constexpr int marching_ant_length = 4;
  27. ImageEditor::ImageEditor(NonnullRefPtr<Image> image)
  28. : m_image(move(image))
  29. , m_title("Untitled")
  30. , m_gui_event_loop(Core::EventLoop::current())
  31. {
  32. set_focus_policy(GUI::FocusPolicy::StrongFocus);
  33. m_undo_stack.push(make<ImageUndoCommand>(*m_image, String()));
  34. m_image->add_client(*this);
  35. m_image->selection().add_client(*this);
  36. set_original_rect(m_image->rect());
  37. set_scale_bounds(0.1f, 100.0f);
  38. m_pixel_grid_threshold = (float)Config::read_i32("PixelPaint"sv, "PixelGrid"sv, "Threshold"sv, 15);
  39. m_show_pixel_grid = Config::read_bool("PixelPaint"sv, "PixelGrid"sv, "Show"sv, true);
  40. m_show_rulers = Config::read_bool("PixelPaint"sv, "Rulers"sv, "Show"sv, true);
  41. m_show_guides = Config::read_bool("PixelPaint"sv, "Guides"sv, "Show"sv, true);
  42. m_marching_ants_timer = Core::Timer::create_repeating(80, [this] {
  43. ++m_marching_ants_offset;
  44. m_marching_ants_offset %= (marching_ant_length * 2);
  45. if (!m_image->selection().is_empty() || m_image->selection().in_interactive_selection())
  46. update();
  47. });
  48. m_marching_ants_timer->start();
  49. }
  50. ImageEditor::~ImageEditor()
  51. {
  52. m_image->selection().remove_client(*this);
  53. m_image->remove_client(*this);
  54. }
  55. void ImageEditor::did_complete_action(String action_text)
  56. {
  57. if (on_modified_change)
  58. on_modified_change(true);
  59. m_undo_stack.push(make<ImageUndoCommand>(*m_image, move(action_text)));
  60. }
  61. bool ImageEditor::is_modified()
  62. {
  63. return undo_stack().is_current_modified();
  64. }
  65. bool ImageEditor::undo()
  66. {
  67. if (!m_undo_stack.can_undo())
  68. return false;
  69. /* Without this you need to undo twice to actually start undoing stuff.
  70. * This is due to the fact that the top of the UndoStack contains the snapshot of the currently
  71. * shown image but what we actually want to restore is the snapshot right below it.
  72. * Doing "undo->undo->redo" restores the 2nd topmost snapshot on the stack while lowering the
  73. * stack pointer only by 1. This is important because we want the UndoStack's pointer to always point
  74. * at the currently shown snapshot, otherwise doing 'undo->undo->draw something else' would delete
  75. * one of the snapshots.
  76. * This works because UndoStack::undo first decrements the stack pointer and then restores the snapshot,
  77. * while UndoStack::redo first restores the snapshot and then increments the stack pointer.
  78. */
  79. m_undo_stack.undo();
  80. m_undo_stack.undo();
  81. m_undo_stack.redo();
  82. layers_did_change();
  83. return true;
  84. }
  85. bool ImageEditor::redo()
  86. {
  87. if (!m_undo_stack.can_redo())
  88. return false;
  89. m_undo_stack.redo();
  90. layers_did_change();
  91. return true;
  92. }
  93. void ImageEditor::set_title(String title)
  94. {
  95. m_title = move(title);
  96. if (on_title_change)
  97. on_title_change(m_title);
  98. }
  99. void ImageEditor::set_path(String path)
  100. {
  101. m_path = move(path);
  102. set_title(LexicalPath::title(m_path));
  103. }
  104. void ImageEditor::paint_event(GUI::PaintEvent& event)
  105. {
  106. GUI::Frame::paint_event(event);
  107. GUI::Painter painter(*this);
  108. painter.add_clip_rect(event.rect());
  109. painter.add_clip_rect(frame_inner_rect());
  110. {
  111. Gfx::DisjointRectSet background_rects;
  112. background_rects.add(frame_inner_rect());
  113. background_rects.shatter(content_rect());
  114. for (auto& rect : background_rects.rects())
  115. painter.fill_rect(rect, palette().color(Gfx::ColorRole::Tray));
  116. }
  117. Gfx::StylePainter::paint_transparency_grid(painter, content_rect(), palette());
  118. painter.draw_rect(content_rect().inflated(2, 2), Color::Black);
  119. m_image->paint_into(painter, content_rect());
  120. if (m_active_layer && m_show_active_layer_boundary)
  121. painter.draw_rect(content_to_frame_rect(m_active_layer->relative_rect()).to_rounded<int>().inflated(2, 2), Color::Black);
  122. if (m_show_pixel_grid && scale() > m_pixel_grid_threshold) {
  123. auto event_image_rect = enclosing_int_rect(frame_to_content_rect(event.rect())).inflated(1, 1);
  124. auto image_rect = m_image->rect().inflated(1, 1).intersected(event_image_rect);
  125. for (auto i = image_rect.left(); i < image_rect.right(); i++) {
  126. auto start_point = content_to_frame_position({ i, image_rect.top() }).to_type<int>();
  127. auto end_point = content_to_frame_position({ i, image_rect.bottom() }).to_type<int>();
  128. painter.draw_line(start_point, end_point, Color::LightGray);
  129. }
  130. for (auto i = image_rect.top(); i < image_rect.bottom(); i++) {
  131. auto start_point = content_to_frame_position({ image_rect.left(), i }).to_type<int>();
  132. auto end_point = content_to_frame_position({ image_rect.right(), i }).to_type<int>();
  133. painter.draw_line(start_point, end_point, Color::LightGray);
  134. }
  135. }
  136. if (m_show_guides) {
  137. for (auto& guide : m_guides) {
  138. if (guide.orientation() == Guide::Orientation::Horizontal) {
  139. int y_coordinate = (int)content_to_frame_position({ 0.0f, guide.offset() }).y();
  140. painter.draw_line({ 0, y_coordinate }, { rect().width(), y_coordinate }, Color::Cyan, 1, Gfx::Painter::LineStyle::Dashed, Color::LightGray);
  141. } else if (guide.orientation() == Guide::Orientation::Vertical) {
  142. int x_coordinate = (int)content_to_frame_position({ guide.offset(), 0.0f }).x();
  143. painter.draw_line({ x_coordinate, 0 }, { x_coordinate, rect().height() }, Color::Cyan, 1, Gfx::Painter::LineStyle::Dashed, Color::LightGray);
  144. }
  145. }
  146. }
  147. paint_selection(painter);
  148. if (m_show_rulers) {
  149. auto const ruler_bg_color = palette().color(Gfx::ColorRole::InactiveSelection);
  150. auto const ruler_fg_color = palette().color(Gfx::ColorRole::Ruler);
  151. auto const ruler_text_color = palette().color(Gfx::ColorRole::InactiveSelectionText);
  152. auto const mouse_indicator_color = Color::White;
  153. // Ruler background
  154. painter.fill_rect({ { 0, 0 }, { m_ruler_thickness, rect().height() } }, ruler_bg_color);
  155. painter.fill_rect({ { 0, 0 }, { rect().width(), m_ruler_thickness } }, ruler_bg_color);
  156. auto const ruler_step = calculate_ruler_step_size();
  157. auto const editor_origin_to_image = frame_to_content_position({ 0, 0 });
  158. auto const editor_max_to_image = frame_to_content_position({ width(), height() });
  159. // Horizontal ruler
  160. painter.draw_line({ 0, m_ruler_thickness }, { rect().width(), m_ruler_thickness }, ruler_fg_color);
  161. auto const x_start = floor(editor_origin_to_image.x()) - ((int)floor(editor_origin_to_image.x()) % ruler_step) - ruler_step;
  162. for (int x = x_start; x < editor_max_to_image.x(); x += ruler_step) {
  163. int const num_sub_divisions = min(ruler_step, 10);
  164. for (int x_sub = 0; x_sub < num_sub_divisions; ++x_sub) {
  165. int const x_pos = x + (int)(ruler_step * x_sub / num_sub_divisions);
  166. int const editor_x_sub = content_to_frame_position({ x_pos, 0 }).x();
  167. int const line_length = (x_sub % 2 == 0) ? m_ruler_thickness / 3 : m_ruler_thickness / 6;
  168. painter.draw_line({ editor_x_sub, m_ruler_thickness - line_length }, { editor_x_sub, m_ruler_thickness }, ruler_fg_color);
  169. }
  170. int const editor_x = content_to_frame_position({ x, 0 }).x();
  171. painter.draw_line({ editor_x, 0 }, { editor_x, m_ruler_thickness }, ruler_fg_color);
  172. painter.draw_text({ { editor_x + 2, 0 }, { m_ruler_thickness, m_ruler_thickness - 2 } }, String::formatted("{}", x), painter.font(), Gfx::TextAlignment::CenterLeft, ruler_text_color);
  173. }
  174. // Vertical ruler
  175. painter.draw_line({ m_ruler_thickness, 0 }, { m_ruler_thickness, rect().height() }, ruler_fg_color);
  176. auto const y_start = floor(editor_origin_to_image.y()) - ((int)floor(editor_origin_to_image.y()) % ruler_step) - ruler_step;
  177. for (int y = y_start; y < editor_max_to_image.y(); y += ruler_step) {
  178. int const num_sub_divisions = min(ruler_step, 10);
  179. for (int y_sub = 0; y_sub < num_sub_divisions; ++y_sub) {
  180. int const y_pos = y + (int)(ruler_step * y_sub / num_sub_divisions);
  181. int const editor_y_sub = content_to_frame_position({ 0, y_pos }).y();
  182. int const line_length = (y_sub % 2 == 0) ? m_ruler_thickness / 3 : m_ruler_thickness / 6;
  183. painter.draw_line({ m_ruler_thickness - line_length, editor_y_sub }, { m_ruler_thickness, editor_y_sub }, ruler_fg_color);
  184. }
  185. int const editor_y = content_to_frame_position({ 0, y }).y();
  186. painter.draw_line({ 0, editor_y }, { m_ruler_thickness, editor_y }, ruler_fg_color);
  187. painter.draw_text({ { 0, editor_y - m_ruler_thickness }, { m_ruler_thickness, m_ruler_thickness } }, String::formatted("{}", y), painter.font(), Gfx::TextAlignment::BottomRight, ruler_text_color);
  188. }
  189. // Mouse position indicator
  190. const Gfx::IntPoint indicator_x({ m_mouse_position.x(), m_ruler_thickness });
  191. const Gfx::IntPoint indicator_y({ m_ruler_thickness, m_mouse_position.y() });
  192. painter.draw_triangle(indicator_x, indicator_x + Gfx::IntPoint(-m_mouse_indicator_triangle_size, -m_mouse_indicator_triangle_size), indicator_x + Gfx::IntPoint(m_mouse_indicator_triangle_size, -m_mouse_indicator_triangle_size), mouse_indicator_color);
  193. painter.draw_triangle(indicator_y, indicator_y + Gfx::IntPoint(-m_mouse_indicator_triangle_size, -m_mouse_indicator_triangle_size), indicator_y + Gfx::IntPoint(-m_mouse_indicator_triangle_size, m_mouse_indicator_triangle_size), mouse_indicator_color);
  194. // Top left square
  195. painter.fill_rect({ { 0, 0 }, { m_ruler_thickness, m_ruler_thickness } }, ruler_bg_color);
  196. }
  197. }
  198. int ImageEditor::calculate_ruler_step_size() const
  199. {
  200. auto const step_target = 80 / scale();
  201. auto const max_factor = 5;
  202. for (int factor = 0; factor < max_factor; ++factor) {
  203. int ten_to_factor = AK::pow<int>(10, factor);
  204. if (step_target <= 1 * ten_to_factor)
  205. return 1 * ten_to_factor;
  206. if (step_target <= 2 * ten_to_factor)
  207. return 2 * ten_to_factor;
  208. if (step_target <= 5 * ten_to_factor)
  209. return 5 * ten_to_factor;
  210. }
  211. return AK::pow<int>(10, max_factor);
  212. }
  213. Gfx::IntRect ImageEditor::mouse_indicator_rect_x() const
  214. {
  215. const Gfx::IntPoint top_left({ m_ruler_thickness, m_ruler_thickness - m_mouse_indicator_triangle_size });
  216. const Gfx::IntSize size({ width() + 1, m_mouse_indicator_triangle_size + 1 });
  217. return Gfx::IntRect(top_left, size);
  218. }
  219. Gfx::IntRect ImageEditor::mouse_indicator_rect_y() const
  220. {
  221. const Gfx::IntPoint top_left({ m_ruler_thickness - m_mouse_indicator_triangle_size, m_ruler_thickness });
  222. const Gfx::IntSize size({ m_mouse_indicator_triangle_size + 1, height() + 1 });
  223. return Gfx::IntRect(top_left, size);
  224. }
  225. void ImageEditor::second_paint_event(GUI::PaintEvent& event)
  226. {
  227. if (m_active_tool)
  228. m_active_tool->on_second_paint(m_active_layer, event);
  229. }
  230. GUI::MouseEvent ImageEditor::event_with_pan_and_scale_applied(GUI::MouseEvent const& event) const
  231. {
  232. auto image_position = frame_to_content_position(event.position());
  233. auto tool_adjusted_image_position = m_active_tool->point_position_to_preferred_cell(image_position);
  234. return {
  235. static_cast<GUI::Event::Type>(event.type()),
  236. tool_adjusted_image_position,
  237. event.buttons(),
  238. event.button(),
  239. event.modifiers(),
  240. event.wheel_delta_x(),
  241. event.wheel_delta_y(),
  242. event.wheel_raw_delta_x(),
  243. event.wheel_raw_delta_y(),
  244. };
  245. }
  246. GUI::MouseEvent ImageEditor::event_adjusted_for_layer(GUI::MouseEvent const& event, Layer const& layer) const
  247. {
  248. auto image_position = frame_to_content_position(event.position());
  249. image_position.translate_by(-layer.location().x(), -layer.location().y());
  250. auto tool_adjusted_image_position = m_active_tool->point_position_to_preferred_cell(image_position);
  251. return {
  252. static_cast<GUI::Event::Type>(event.type()),
  253. tool_adjusted_image_position,
  254. event.buttons(),
  255. event.button(),
  256. event.modifiers(),
  257. event.wheel_delta_x(),
  258. event.wheel_delta_y(),
  259. event.wheel_raw_delta_x(),
  260. event.wheel_raw_delta_y(),
  261. };
  262. }
  263. void ImageEditor::set_editor_color_to_color_at_mouse_position(GUI::MouseEvent const& event, bool sample_all_layers = false)
  264. {
  265. auto position = event.position();
  266. Color color;
  267. auto layer = active_layer();
  268. if (sample_all_layers) {
  269. color = image().color_at(position);
  270. } else {
  271. if (!layer || !layer->rect().contains(position))
  272. return;
  273. color = layer->currently_edited_bitmap().get_pixel(position);
  274. }
  275. // We picked a transparent pixel, do nothing.
  276. if (!color.alpha())
  277. return;
  278. if (event.button() == GUI::MouseButton::Primary)
  279. set_primary_color(color);
  280. else if (event.button() == GUI::MouseButton::Secondary)
  281. set_secondary_color(color);
  282. }
  283. void ImageEditor::mousedown_event(GUI::MouseEvent& event)
  284. {
  285. if (event.button() == GUI::MouseButton::Middle) {
  286. start_panning(event.position());
  287. set_override_cursor(Gfx::StandardCursor::Drag);
  288. return;
  289. }
  290. if (event.alt() && !m_active_tool->is_overriding_alt()) {
  291. set_editor_color_to_color_at_mouse_position(event);
  292. return; // Pick Color instead of acivating active tool when holding alt.
  293. }
  294. if (!m_active_tool)
  295. return;
  296. if (is<MoveTool>(*m_active_tool)) {
  297. if (auto* other_layer = layer_at_editor_position(event.position())) {
  298. set_active_layer(other_layer);
  299. }
  300. }
  301. auto layer_event = m_active_layer ? event_adjusted_for_layer(event, *m_active_layer) : event;
  302. auto image_event = event_with_pan_and_scale_applied(event);
  303. Tool::MouseEvent tool_event(Tool::MouseEvent::Action::MouseDown, layer_event, image_event, event);
  304. m_active_tool->on_mousedown(m_active_layer.ptr(), tool_event);
  305. }
  306. void ImageEditor::mousemove_event(GUI::MouseEvent& event)
  307. {
  308. m_mouse_position = event.position();
  309. if (m_show_rulers) {
  310. update(mouse_indicator_rect_x());
  311. update(mouse_indicator_rect_y());
  312. }
  313. if (is_panning()) {
  314. GUI::AbstractZoomPanWidget::mousemove_event(event);
  315. return;
  316. }
  317. if (!m_active_tool)
  318. return;
  319. auto image_event = event_with_pan_and_scale_applied(event);
  320. if (on_image_mouse_position_change) {
  321. on_image_mouse_position_change(image_event.position());
  322. }
  323. auto layer_event = m_active_layer ? event_adjusted_for_layer(event, *m_active_layer) : event;
  324. Tool::MouseEvent tool_event(Tool::MouseEvent::Action::MouseDown, layer_event, image_event, event);
  325. m_active_tool->on_mousemove(m_active_layer.ptr(), tool_event);
  326. }
  327. void ImageEditor::mouseup_event(GUI::MouseEvent& event)
  328. {
  329. set_override_cursor(m_active_cursor);
  330. if (event.button() == GUI::MouseButton::Middle) {
  331. stop_panning();
  332. return;
  333. }
  334. if (!m_active_tool)
  335. return;
  336. auto layer_event = m_active_layer ? event_adjusted_for_layer(event, *m_active_layer) : event;
  337. auto image_event = event_with_pan_and_scale_applied(event);
  338. Tool::MouseEvent tool_event(Tool::MouseEvent::Action::MouseDown, layer_event, image_event, event);
  339. m_active_tool->on_mouseup(m_active_layer.ptr(), tool_event);
  340. }
  341. void ImageEditor::context_menu_event(GUI::ContextMenuEvent& event)
  342. {
  343. if (!m_active_tool)
  344. return;
  345. m_active_tool->on_context_menu(m_active_layer, event);
  346. }
  347. void ImageEditor::keydown_event(GUI::KeyEvent& event)
  348. {
  349. if (event.key() == Key_Delete && !m_image->selection().is_empty() && active_layer()) {
  350. active_layer()->erase_selection(m_image->selection());
  351. return;
  352. }
  353. if (m_active_tool)
  354. m_active_tool->on_keydown(event);
  355. }
  356. void ImageEditor::keyup_event(GUI::KeyEvent& event)
  357. {
  358. if (m_active_tool)
  359. m_active_tool->on_keyup(event);
  360. }
  361. void ImageEditor::enter_event(Core::Event&)
  362. {
  363. set_override_cursor(m_active_cursor);
  364. }
  365. void ImageEditor::leave_event(Core::Event&)
  366. {
  367. set_override_cursor(Gfx::StandardCursor::None);
  368. if (on_leave)
  369. on_leave();
  370. }
  371. void ImageEditor::set_active_layer(Layer* layer)
  372. {
  373. if (m_active_layer == layer)
  374. return;
  375. m_active_layer = layer;
  376. if (m_active_layer) {
  377. VERIFY(&m_active_layer->image() == m_image.ptr());
  378. size_t index = 0;
  379. for (; index < m_image->layer_count(); ++index) {
  380. if (&m_image->layer(index) == layer)
  381. break;
  382. }
  383. if (on_active_layer_change)
  384. on_active_layer_change(layer);
  385. } else {
  386. if (on_active_layer_change)
  387. on_active_layer_change({});
  388. }
  389. }
  390. ErrorOr<void> ImageEditor::add_new_layer_from_selection()
  391. {
  392. auto current_layer_selection = image().selection();
  393. if (current_layer_selection.is_empty())
  394. return Error::from_string_literal("There is no active selection to create layer from.");
  395. // save offsets of selection so we know where to place the new layer
  396. auto selection_offset = current_layer_selection.bounding_rect().location();
  397. auto selection_bitmap = active_layer()->try_copy_bitmap(current_layer_selection);
  398. if (selection_bitmap.is_null())
  399. return Error::from_string_literal("Unable to create bitmap from selection.");
  400. auto layer_or_error = PixelPaint::Layer::try_create_with_bitmap(image(), selection_bitmap.release_nonnull(), "New Layer"sv);
  401. if (layer_or_error.is_error())
  402. return Error::from_string_literal("Unable to create layer from selection.");
  403. auto new_layer = layer_or_error.release_value();
  404. new_layer->set_location(selection_offset);
  405. image().add_layer(new_layer);
  406. layers_did_change();
  407. return {};
  408. }
  409. void ImageEditor::set_active_tool(Tool* tool)
  410. {
  411. if (m_active_tool == tool)
  412. return;
  413. if (m_active_tool)
  414. m_active_tool->clear();
  415. m_active_tool = tool;
  416. if (m_active_tool) {
  417. m_active_tool->setup(*this);
  418. m_active_tool->on_tool_activation();
  419. m_active_cursor = m_active_tool->cursor();
  420. set_override_cursor(m_active_cursor);
  421. }
  422. }
  423. void ImageEditor::update_tool_cursor()
  424. {
  425. if (m_active_tool) {
  426. m_active_cursor = m_active_tool->cursor();
  427. set_override_cursor(m_active_cursor);
  428. }
  429. }
  430. void ImageEditor::set_guide_visibility(bool show_guides)
  431. {
  432. if (m_show_guides == show_guides)
  433. return;
  434. m_show_guides = show_guides;
  435. if (on_set_guide_visibility)
  436. on_set_guide_visibility(m_show_guides);
  437. update();
  438. }
  439. void ImageEditor::set_ruler_visibility(bool show_rulers)
  440. {
  441. if (m_show_rulers == show_rulers)
  442. return;
  443. m_show_rulers = show_rulers;
  444. if (on_set_ruler_visibility)
  445. on_set_ruler_visibility(m_show_rulers);
  446. update();
  447. }
  448. void ImageEditor::set_pixel_grid_visibility(bool show_pixel_grid)
  449. {
  450. if (m_show_pixel_grid == show_pixel_grid)
  451. return;
  452. m_show_pixel_grid = show_pixel_grid;
  453. update();
  454. }
  455. void ImageEditor::clear_guides()
  456. {
  457. m_guides.clear();
  458. update();
  459. }
  460. void ImageEditor::layers_did_change()
  461. {
  462. if (on_modified_change)
  463. on_modified_change(true);
  464. update();
  465. }
  466. Color ImageEditor::color_for(GUI::MouseButton button) const
  467. {
  468. if (button == GUI::MouseButton::Primary)
  469. return m_primary_color;
  470. if (button == GUI::MouseButton::Secondary)
  471. return m_secondary_color;
  472. VERIFY_NOT_REACHED();
  473. }
  474. Color ImageEditor::color_for(GUI::MouseEvent const& event) const
  475. {
  476. if (event.buttons() & GUI::MouseButton::Primary)
  477. return m_primary_color;
  478. if (event.buttons() & GUI::MouseButton::Secondary)
  479. return m_secondary_color;
  480. VERIFY_NOT_REACHED();
  481. }
  482. void ImageEditor::set_primary_color(Color color)
  483. {
  484. if (m_primary_color == color)
  485. return;
  486. m_primary_color = color;
  487. if (on_primary_color_change)
  488. on_primary_color_change(color);
  489. }
  490. void ImageEditor::set_secondary_color(Color color)
  491. {
  492. if (m_secondary_color == color)
  493. return;
  494. m_secondary_color = color;
  495. if (on_secondary_color_change)
  496. on_secondary_color_change(color);
  497. }
  498. Layer* ImageEditor::layer_at_editor_position(Gfx::IntPoint const& editor_position)
  499. {
  500. auto image_position = frame_to_content_position(editor_position);
  501. for (ssize_t i = m_image->layer_count() - 1; i >= 0; --i) {
  502. auto& layer = m_image->layer(i);
  503. if (!layer.is_visible())
  504. continue;
  505. if (layer.relative_rect().contains(Gfx::IntPoint(image_position.x(), image_position.y())))
  506. return const_cast<Layer*>(&layer);
  507. }
  508. return nullptr;
  509. }
  510. void ImageEditor::fit_image_to_view(FitType type)
  511. {
  512. auto viewport_rect = rect();
  513. if (m_show_rulers) {
  514. viewport_rect = {
  515. viewport_rect.x() + m_ruler_thickness,
  516. viewport_rect.y() + m_ruler_thickness,
  517. viewport_rect.width() - m_ruler_thickness,
  518. viewport_rect.height() - m_ruler_thickness
  519. };
  520. }
  521. fit_content_to_rect(viewport_rect, type);
  522. }
  523. void ImageEditor::image_did_change(Gfx::IntRect const& modified_image_rect)
  524. {
  525. update(content_rect().intersected(enclosing_int_rect(content_to_frame_rect(modified_image_rect))));
  526. }
  527. void ImageEditor::image_did_change_rect(Gfx::IntRect const& new_image_rect)
  528. {
  529. set_original_rect(new_image_rect);
  530. set_content_rect(new_image_rect);
  531. relayout();
  532. }
  533. void ImageEditor::image_select_layer(Layer* layer)
  534. {
  535. set_active_layer(layer);
  536. }
  537. bool ImageEditor::request_close()
  538. {
  539. if (!undo_stack().is_current_modified())
  540. return true;
  541. auto result = GUI::MessageBox::ask_about_unsaved_changes(window(), path(), undo_stack().last_unmodified_timestamp());
  542. if (result == GUI::MessageBox::ExecResult::Yes) {
  543. save_project();
  544. return true;
  545. }
  546. if (result == GUI::MessageBox::ExecResult::No)
  547. return true;
  548. return false;
  549. }
  550. void ImageEditor::save_project()
  551. {
  552. if (path().is_empty() || m_loaded_from_image) {
  553. save_project_as();
  554. return;
  555. }
  556. auto response = FileSystemAccessClient::Client::the().try_request_file(window(), path(), Core::OpenMode::Truncate | Core::OpenMode::WriteOnly);
  557. if (response.is_error())
  558. return;
  559. auto result = save_project_to_file(*response.value());
  560. if (result.is_error()) {
  561. GUI::MessageBox::show_error(window(), String::formatted("Could not save {}: {}", path(), result.error()));
  562. return;
  563. }
  564. undo_stack().set_current_unmodified();
  565. if (on_modified_change)
  566. on_modified_change(false);
  567. }
  568. void ImageEditor::save_project_as()
  569. {
  570. auto response = FileSystemAccessClient::Client::the().try_save_file(window(), m_title, "pp");
  571. if (response.is_error())
  572. return;
  573. auto file = response.value();
  574. auto result = save_project_to_file(*file);
  575. if (result.is_error()) {
  576. GUI::MessageBox::show_error(window(), String::formatted("Could not save {}: {}", file->filename(), result.error()));
  577. return;
  578. }
  579. set_path(file->filename());
  580. set_loaded_from_image(false);
  581. undo_stack().set_current_unmodified();
  582. if (on_modified_change)
  583. on_modified_change(false);
  584. }
  585. Result<void, String> ImageEditor::save_project_to_file(Core::File& file) const
  586. {
  587. StringBuilder builder;
  588. auto json = MUST(JsonObjectSerializer<>::try_create(builder));
  589. m_image->serialize_as_json(json);
  590. auto json_guides = MUST(json.add_array("guides"sv));
  591. for (auto const& guide : m_guides) {
  592. auto json_guide = MUST(json_guides.add_object());
  593. MUST(json_guide.add("offset"sv, (double)guide.offset()));
  594. if (guide.orientation() == Guide::Orientation::Vertical)
  595. MUST(json_guide.add("orientation"sv, "vertical"));
  596. else if (guide.orientation() == Guide::Orientation::Horizontal)
  597. MUST(json_guide.add("orientation"sv, "horizontal"));
  598. MUST(json_guide.finish());
  599. }
  600. MUST(json_guides.finish());
  601. MUST(json.finish());
  602. if (!file.write(builder.string_view()))
  603. return String { file.error_string() };
  604. return {};
  605. }
  606. void ImageEditor::set_show_active_layer_boundary(bool show)
  607. {
  608. if (m_show_active_layer_boundary == show)
  609. return;
  610. m_show_active_layer_boundary = show;
  611. update();
  612. }
  613. void ImageEditor::set_loaded_from_image(bool loaded_from_image)
  614. {
  615. m_loaded_from_image = loaded_from_image;
  616. }
  617. void ImageEditor::paint_selection(Gfx::Painter& painter)
  618. {
  619. if (m_image->selection().is_empty())
  620. return;
  621. draw_marching_ants(painter, m_image->selection().mask());
  622. }
  623. void ImageEditor::draw_marching_ants(Gfx::Painter& painter, Gfx::IntRect const& rect) const
  624. {
  625. // Top line
  626. for (int x = rect.left(); x <= rect.right(); ++x)
  627. draw_marching_ants_pixel(painter, x, rect.top());
  628. // Right line
  629. for (int y = rect.top() + 1; y <= rect.bottom(); ++y)
  630. draw_marching_ants_pixel(painter, rect.right(), y);
  631. // Bottom line
  632. for (int x = rect.right() - 1; x >= rect.left(); --x)
  633. draw_marching_ants_pixel(painter, x, rect.bottom());
  634. // Left line
  635. for (int y = rect.bottom() - 1; y > rect.top(); --y)
  636. draw_marching_ants_pixel(painter, rect.left(), y);
  637. }
  638. void ImageEditor::draw_marching_ants(Gfx::Painter& painter, Mask const& mask) const
  639. {
  640. // If the zoom is < 100%, we can skip pixels to save a lot of time drawing the ants
  641. int step = max(1, (int)floorf(1.0f / scale()));
  642. // Only check the visible selection area when drawing for performance
  643. auto rect = this->rect();
  644. rect = Gfx::enclosing_int_rect(frame_to_content_rect(rect));
  645. rect.inflate(step * 2, step * 2); // prevent borders from having visible ants if the selection extends beyond it
  646. // Scan the image horizontally to find vertical borders
  647. for (int y = rect.top(); y <= rect.bottom(); y += step) {
  648. bool previous_selected = false;
  649. for (int x = rect.left(); x <= rect.right(); x += step) {
  650. bool this_selected = mask.get(x, y) > 0;
  651. if (this_selected != previous_selected) {
  652. Gfx::IntRect image_pixel { x, y, 1, 1 };
  653. auto pixel = content_to_frame_rect(image_pixel).to_type<int>();
  654. auto end = max(pixel.top(), pixel.bottom()); // for when the zoom is < 100%
  655. for (int pixel_y = pixel.top(); pixel_y <= end; pixel_y++) {
  656. draw_marching_ants_pixel(painter, pixel.left(), pixel_y);
  657. }
  658. }
  659. previous_selected = this_selected;
  660. }
  661. }
  662. // Scan the image vertically to find horizontal borders
  663. for (int x = rect.left(); x <= rect.right(); x += step) {
  664. bool previous_selected = false;
  665. for (int y = rect.top(); y <= rect.bottom(); y += step) {
  666. bool this_selected = mask.get(x, y) > 0;
  667. if (this_selected != previous_selected) {
  668. Gfx::IntRect image_pixel { x, y, 1, 1 };
  669. auto pixel = content_to_frame_rect(image_pixel).to_type<int>();
  670. auto end = max(pixel.left(), pixel.right()); // for when the zoom is < 100%
  671. for (int pixel_x = pixel.left(); pixel_x <= end; pixel_x++) {
  672. draw_marching_ants_pixel(painter, pixel_x, pixel.top());
  673. }
  674. }
  675. previous_selected = this_selected;
  676. }
  677. }
  678. }
  679. void ImageEditor::draw_marching_ants_pixel(Gfx::Painter& painter, int x, int y) const
  680. {
  681. int pattern_index = x + y + m_marching_ants_offset;
  682. if (pattern_index % (marching_ant_length * 2) < marching_ant_length) {
  683. painter.set_pixel(x, y, Color::Black);
  684. } else {
  685. painter.set_pixel(x, y, Color::White);
  686. }
  687. }
  688. void ImageEditor::selection_did_change()
  689. {
  690. update();
  691. }
  692. }