ImageEditor.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962
  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"_string.release_value_but_fixme_should_propagate_errors())
  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, DeprecatedString()));
  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. }).release_value_but_fixme_should_propagate_errors();
  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(DeprecatedString action_text)
  56. {
  57. set_modified(move(action_text));
  58. }
  59. bool ImageEditor::is_modified()
  60. {
  61. return undo_stack().is_current_modified();
  62. }
  63. bool ImageEditor::undo()
  64. {
  65. if (!m_undo_stack.can_undo())
  66. return false;
  67. /* Without this you need to undo twice to actually start undoing stuff.
  68. * This is due to the fact that the top of the UndoStack contains the snapshot of the currently
  69. * shown image but what we actually want to restore is the snapshot right below it.
  70. * Doing "undo->undo->redo" restores the 2nd topmost snapshot on the stack while lowering the
  71. * stack pointer only by 1. This is important because we want the UndoStack's pointer to always point
  72. * at the currently shown snapshot, otherwise doing 'undo->undo->draw something else' would delete
  73. * one of the snapshots.
  74. * This works because UndoStack::undo first decrements the stack pointer and then restores the snapshot,
  75. * while UndoStack::redo first restores the snapshot and then increments the stack pointer.
  76. */
  77. m_undo_stack.undo();
  78. m_undo_stack.undo();
  79. m_undo_stack.redo();
  80. layers_did_change();
  81. return true;
  82. }
  83. bool ImageEditor::redo()
  84. {
  85. if (!m_undo_stack.can_redo())
  86. return false;
  87. m_undo_stack.redo();
  88. layers_did_change();
  89. return true;
  90. }
  91. void ImageEditor::set_title(String title)
  92. {
  93. m_title = move(title);
  94. if (on_title_change)
  95. on_title_change(m_title);
  96. }
  97. void ImageEditor::set_path(DeprecatedString path)
  98. {
  99. m_path = move(path);
  100. set_title(String::from_deprecated_string(LexicalPath::title(m_path)).release_value_but_fixme_should_propagate_errors());
  101. }
  102. void ImageEditor::set_modified(DeprecatedString action_text)
  103. {
  104. m_undo_stack.push(make<ImageUndoCommand>(*m_image, move(action_text)));
  105. update_modified();
  106. }
  107. void ImageEditor::set_unmodified()
  108. {
  109. m_undo_stack.set_current_unmodified();
  110. update_modified();
  111. }
  112. void ImageEditor::update_modified()
  113. {
  114. if (on_modified_change)
  115. on_modified_change(is_modified());
  116. }
  117. Gfx::IntRect ImageEditor::subtract_rulers_from_rect(Gfx::IntRect const& rect) const
  118. {
  119. Gfx::IntRect clipped_rect {};
  120. clipped_rect.set_top(max(rect.y(), m_ruler_thickness + 1));
  121. clipped_rect.set_left(max(rect.x(), m_ruler_thickness + 1));
  122. clipped_rect.set_bottom(rect.bottom());
  123. clipped_rect.set_right(rect.right());
  124. return clipped_rect;
  125. }
  126. void ImageEditor::paint_event(GUI::PaintEvent& event)
  127. {
  128. GUI::Frame::paint_event(event);
  129. GUI::Painter painter(*this);
  130. painter.add_clip_rect(event.rect());
  131. painter.add_clip_rect(frame_inner_rect());
  132. {
  133. Gfx::DisjointIntRectSet background_rects;
  134. background_rects.add(frame_inner_rect());
  135. background_rects.shatter(content_rect());
  136. for (auto& rect : background_rects.rects())
  137. painter.fill_rect(rect, palette().color(Gfx::ColorRole::Tray));
  138. }
  139. Gfx::StylePainter::paint_transparency_grid(painter, content_rect(), palette());
  140. painter.draw_rect(content_rect().inflated(2, 2), Color::Black);
  141. m_image->paint_into(painter, content_rect(), scale());
  142. if (m_active_layer && m_show_active_layer_boundary)
  143. painter.draw_rect(content_to_frame_rect(m_active_layer->relative_rect()).to_type<int>().inflated(2, 2), Color::Black);
  144. if (m_show_pixel_grid && scale() > m_pixel_grid_threshold) {
  145. auto event_image_rect = enclosing_int_rect(frame_to_content_rect(event.rect())).inflated(1, 1);
  146. auto image_rect = m_image->rect().inflated(1, 1).intersected(event_image_rect);
  147. for (auto i = image_rect.left(); i < image_rect.right() - 1; i++) {
  148. auto start_point = content_to_frame_position({ i, image_rect.top() }).to_type<int>();
  149. auto end_point = content_to_frame_position({ i, image_rect.bottom() - 1 }).to_type<int>();
  150. painter.draw_line(start_point, end_point, Color::LightGray);
  151. }
  152. for (auto i = image_rect.top(); i < image_rect.bottom() - 1; i++) {
  153. auto start_point = content_to_frame_position({ image_rect.left(), i }).to_type<int>();
  154. auto end_point = content_to_frame_position({ image_rect.right() - 1, i }).to_type<int>();
  155. painter.draw_line(start_point, end_point, Color::LightGray);
  156. }
  157. }
  158. if (m_show_guides) {
  159. for (auto& guide : m_guides) {
  160. if (guide->orientation() == Guide::Orientation::Horizontal) {
  161. int y_coordinate = (int)content_to_frame_position({ 0.0f, guide->offset() }).y();
  162. painter.draw_line({ 0, y_coordinate }, { rect().width(), y_coordinate }, Color::Cyan, 1, Gfx::Painter::LineStyle::Dashed, Color::LightGray);
  163. } else if (guide->orientation() == Guide::Orientation::Vertical) {
  164. int x_coordinate = (int)content_to_frame_position({ guide->offset(), 0.0f }).x();
  165. painter.draw_line({ x_coordinate, 0 }, { x_coordinate, rect().height() }, Color::Cyan, 1, Gfx::Painter::LineStyle::Dashed, Color::LightGray);
  166. }
  167. }
  168. }
  169. paint_selection(painter);
  170. if (m_show_rulers) {
  171. auto const ruler_bg_color = palette().color(Gfx::ColorRole::InactiveSelection);
  172. auto const ruler_fg_color = palette().color(Gfx::ColorRole::Ruler);
  173. auto const ruler_text_color = palette().color(Gfx::ColorRole::InactiveSelectionText);
  174. auto const mouse_indicator_color = Color::White;
  175. // Ruler background
  176. painter.fill_rect({ { 0, 0 }, { m_ruler_thickness, rect().height() } }, ruler_bg_color);
  177. painter.fill_rect({ { 0, 0 }, { rect().width(), m_ruler_thickness } }, ruler_bg_color);
  178. auto const ruler_step = calculate_ruler_step_size();
  179. auto const editor_origin_to_image = frame_to_content_position({ 0, 0 });
  180. auto const editor_max_to_image = frame_to_content_position({ width(), height() });
  181. // Horizontal ruler
  182. painter.draw_line({ 0, m_ruler_thickness }, { rect().width(), m_ruler_thickness }, ruler_fg_color);
  183. auto const x_start = floor(editor_origin_to_image.x()) - ((int)floor(editor_origin_to_image.x()) % ruler_step) - ruler_step;
  184. for (int x = x_start; x < editor_max_to_image.x(); x += ruler_step) {
  185. int const num_sub_divisions = min(ruler_step, 10);
  186. for (int x_sub = 0; x_sub < num_sub_divisions; ++x_sub) {
  187. int const x_pos = x + (int)(ruler_step * x_sub / num_sub_divisions);
  188. int const editor_x_sub = content_to_frame_position({ x_pos, 0 }).x();
  189. int const line_length = (x_sub % 2 == 0) ? m_ruler_thickness / 3 : m_ruler_thickness / 6;
  190. painter.draw_line({ editor_x_sub, m_ruler_thickness - line_length }, { editor_x_sub, m_ruler_thickness }, ruler_fg_color);
  191. }
  192. int const editor_x = content_to_frame_position({ x, 0 }).x();
  193. painter.draw_line({ editor_x, 0 }, { editor_x, m_ruler_thickness }, ruler_fg_color);
  194. painter.draw_text(Gfx::IntRect { { editor_x + 2, 0 }, { m_ruler_thickness, m_ruler_thickness - 2 } }, DeprecatedString::formatted("{}", x), painter.font(), Gfx::TextAlignment::CenterLeft, ruler_text_color);
  195. }
  196. // Vertical ruler
  197. painter.draw_line({ m_ruler_thickness, 0 }, { m_ruler_thickness, rect().height() }, ruler_fg_color);
  198. auto const y_start = floor(editor_origin_to_image.y()) - ((int)floor(editor_origin_to_image.y()) % ruler_step) - ruler_step;
  199. for (int y = y_start; y < editor_max_to_image.y(); y += ruler_step) {
  200. int const num_sub_divisions = min(ruler_step, 10);
  201. for (int y_sub = 0; y_sub < num_sub_divisions; ++y_sub) {
  202. int const y_pos = y + (int)(ruler_step * y_sub / num_sub_divisions);
  203. int const editor_y_sub = content_to_frame_position({ 0, y_pos }).y();
  204. int const line_length = (y_sub % 2 == 0) ? m_ruler_thickness / 3 : m_ruler_thickness / 6;
  205. painter.draw_line({ m_ruler_thickness - line_length, editor_y_sub }, { m_ruler_thickness, editor_y_sub }, ruler_fg_color);
  206. }
  207. int const editor_y = content_to_frame_position({ 0, y }).y();
  208. painter.draw_line({ 0, editor_y }, { m_ruler_thickness, editor_y }, ruler_fg_color);
  209. painter.draw_text(Gfx::IntRect { { 0, editor_y - m_ruler_thickness }, { m_ruler_thickness, m_ruler_thickness } }, DeprecatedString::formatted("{}", y), painter.font(), Gfx::TextAlignment::BottomRight, ruler_text_color);
  210. }
  211. // Mouse position indicator
  212. const Gfx::IntPoint indicator_x({ m_mouse_position.x(), m_ruler_thickness });
  213. const Gfx::IntPoint indicator_y({ m_ruler_thickness, m_mouse_position.y() });
  214. 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);
  215. 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);
  216. // Top left square
  217. painter.fill_rect({ { 0, 0 }, { m_ruler_thickness, m_ruler_thickness } }, ruler_bg_color);
  218. }
  219. }
  220. int ImageEditor::calculate_ruler_step_size() const
  221. {
  222. auto const step_target = 80 / scale();
  223. auto const max_factor = 5;
  224. for (int factor = 0; factor < max_factor; ++factor) {
  225. int ten_to_factor = AK::pow<int>(10, factor);
  226. if (step_target <= 1 * ten_to_factor)
  227. return 1 * ten_to_factor;
  228. if (step_target <= 2 * ten_to_factor)
  229. return 2 * ten_to_factor;
  230. if (step_target <= 5 * ten_to_factor)
  231. return 5 * ten_to_factor;
  232. }
  233. return AK::pow<int>(10, max_factor);
  234. }
  235. Gfx::IntRect ImageEditor::mouse_indicator_rect_x() const
  236. {
  237. const Gfx::IntPoint top_left({ m_ruler_thickness, m_ruler_thickness - m_mouse_indicator_triangle_size });
  238. const Gfx::IntSize size({ width() + 1, m_mouse_indicator_triangle_size + 1 });
  239. return Gfx::IntRect(top_left, size);
  240. }
  241. Gfx::IntRect ImageEditor::mouse_indicator_rect_y() const
  242. {
  243. const Gfx::IntPoint top_left({ m_ruler_thickness - m_mouse_indicator_triangle_size, m_ruler_thickness });
  244. const Gfx::IntSize size({ m_mouse_indicator_triangle_size + 1, height() + 1 });
  245. return Gfx::IntRect(top_left, size);
  246. }
  247. void ImageEditor::second_paint_event(GUI::PaintEvent& event)
  248. {
  249. if (m_active_layer && m_active_layer->mask_type() != Layer::MaskType::None)
  250. m_active_layer->on_second_paint(*this);
  251. if (m_active_tool) {
  252. if (m_show_rulers) {
  253. auto clipped_event = GUI::PaintEvent(subtract_rulers_from_rect(event.rect()), event.window_size());
  254. m_active_tool->on_second_paint(m_active_layer, clipped_event);
  255. } else {
  256. m_active_tool->on_second_paint(m_active_layer, event);
  257. }
  258. }
  259. }
  260. GUI::MouseEvent ImageEditor::event_with_pan_and_scale_applied(GUI::MouseEvent const& event) const
  261. {
  262. auto image_position = frame_to_content_position(event.position());
  263. auto tool_adjusted_image_position = m_active_tool->point_position_to_preferred_cell(image_position);
  264. return {
  265. static_cast<GUI::Event::Type>(event.type()),
  266. tool_adjusted_image_position,
  267. event.buttons(),
  268. event.button(),
  269. event.modifiers(),
  270. event.wheel_delta_x(),
  271. event.wheel_delta_y(),
  272. event.wheel_raw_delta_x(),
  273. event.wheel_raw_delta_y(),
  274. };
  275. }
  276. GUI::MouseEvent ImageEditor::event_adjusted_for_layer(GUI::MouseEvent const& event, Layer const& layer) const
  277. {
  278. auto image_position = frame_to_content_position(event.position());
  279. image_position.translate_by(-layer.location().x(), -layer.location().y());
  280. auto tool_adjusted_image_position = m_active_tool->point_position_to_preferred_cell(image_position);
  281. return {
  282. static_cast<GUI::Event::Type>(event.type()),
  283. tool_adjusted_image_position,
  284. event.buttons(),
  285. event.button(),
  286. event.modifiers(),
  287. event.wheel_delta_x(),
  288. event.wheel_delta_y(),
  289. event.wheel_raw_delta_x(),
  290. event.wheel_raw_delta_y(),
  291. };
  292. }
  293. Optional<Color> ImageEditor::color_from_position(Gfx::IntPoint position, bool sample_all_layers)
  294. {
  295. Color color;
  296. auto* layer = active_layer();
  297. if (sample_all_layers) {
  298. color = image().color_at(position);
  299. } else {
  300. if (!layer || !layer->rect().contains(position))
  301. return {};
  302. color = layer->currently_edited_bitmap().get_pixel(position);
  303. }
  304. return color;
  305. }
  306. void ImageEditor::set_status_info_to_color_at_mouse_position(Gfx::IntPoint position, bool sample_all_layers)
  307. {
  308. auto const color = color_from_position(position, sample_all_layers);
  309. if (!color.has_value())
  310. return;
  311. set_appended_status_info(DeprecatedString::formatted("R:{}, G:{}, B:{}, A:{} [{}]", color->red(), color->green(), color->blue(), color->alpha(), color->to_deprecated_string()));
  312. }
  313. void ImageEditor::set_editor_color_to_color_at_mouse_position(GUI::MouseEvent const& event, bool sample_all_layers = false)
  314. {
  315. auto const color = color_from_position(event.position(), sample_all_layers);
  316. if (!color.has_value())
  317. return;
  318. // We picked a transparent pixel, do nothing.
  319. if (!color->alpha())
  320. return;
  321. if (event.buttons() & GUI::MouseButton::Primary)
  322. set_primary_color(*color);
  323. if (event.buttons() & GUI::MouseButton::Secondary)
  324. set_secondary_color(*color);
  325. }
  326. void ImageEditor::mousedown_event(GUI::MouseEvent& event)
  327. {
  328. if (event.button() == GUI::MouseButton::Middle) {
  329. start_panning(event.position());
  330. set_override_cursor(Gfx::StandardCursor::Drag);
  331. return;
  332. }
  333. if (!m_active_tool)
  334. return;
  335. if (auto* tool = dynamic_cast<MoveTool*>(m_active_tool); tool && tool->layer_selection_mode() == MoveTool::LayerSelectionMode::ForegroundLayer) {
  336. if (auto* foreground_layer = layer_at_editor_position(event.position()); foreground_layer && !tool->cursor_is_within_resize_anchor())
  337. set_active_layer(foreground_layer);
  338. }
  339. auto layer_event = m_active_layer ? event_adjusted_for_layer(event, *m_active_layer) : event;
  340. if (event.alt() && !m_active_tool->is_overriding_alt()) {
  341. set_editor_color_to_color_at_mouse_position(layer_event);
  342. return; // Pick Color instead of acivating active tool when holding alt.
  343. }
  344. auto image_event = event_with_pan_and_scale_applied(event);
  345. Tool::MouseEvent tool_event(Tool::MouseEvent::Action::MouseDown, layer_event, image_event, event);
  346. m_active_tool->on_mousedown(m_active_layer.ptr(), tool_event);
  347. }
  348. void ImageEditor::doubleclick_event(GUI::MouseEvent& event)
  349. {
  350. if (!m_active_tool || (event.alt() && !m_active_tool->is_overriding_alt()))
  351. return;
  352. auto layer_event = m_active_layer ? event_adjusted_for_layer(event, *m_active_layer) : event;
  353. auto image_event = event_with_pan_and_scale_applied(event);
  354. Tool::MouseEvent tool_event(Tool::MouseEvent::Action::DoubleClick, layer_event, image_event, event);
  355. m_active_tool->on_doubleclick(m_active_layer.ptr(), tool_event);
  356. }
  357. void ImageEditor::mousemove_event(GUI::MouseEvent& event)
  358. {
  359. m_mouse_position = event.position();
  360. if (m_show_rulers) {
  361. update(mouse_indicator_rect_x());
  362. update(mouse_indicator_rect_y());
  363. }
  364. if (is_panning()) {
  365. GUI::AbstractZoomPanWidget::mousemove_event(event);
  366. return;
  367. }
  368. auto image_event = event_with_pan_and_scale_applied(event);
  369. if (on_image_mouse_position_change) {
  370. on_image_mouse_position_change(image_event.position());
  371. }
  372. auto layer_event = m_active_layer ? event_adjusted_for_layer(event, *m_active_layer) : event;
  373. if (m_active_tool && event.alt() && !m_active_tool->is_overriding_alt()) {
  374. set_override_cursor(Gfx::StandardCursor::Eyedropper);
  375. set_editor_color_to_color_at_mouse_position(layer_event);
  376. return;
  377. }
  378. Tool::MouseEvent tool_event(Tool::MouseEvent::Action::MouseDown, layer_event, image_event, event);
  379. m_active_tool->on_mousemove(m_active_layer.ptr(), tool_event);
  380. }
  381. void ImageEditor::mouseup_event(GUI::MouseEvent& event)
  382. {
  383. if (!(m_active_tool && event.alt() && !m_active_tool->is_overriding_alt()))
  384. set_override_cursor(m_active_cursor);
  385. if (event.button() == GUI::MouseButton::Middle) {
  386. stop_panning();
  387. return;
  388. }
  389. if (!m_active_tool || (event.alt() && !m_active_tool->is_overriding_alt()))
  390. return;
  391. auto layer_event = m_active_layer ? event_adjusted_for_layer(event, *m_active_layer) : event;
  392. auto image_event = event_with_pan_and_scale_applied(event);
  393. Tool::MouseEvent tool_event(Tool::MouseEvent::Action::MouseDown, layer_event, image_event, event);
  394. m_active_tool->on_mouseup(m_active_layer.ptr(), tool_event);
  395. }
  396. void ImageEditor::context_menu_event(GUI::ContextMenuEvent& event)
  397. {
  398. if (!m_active_tool)
  399. return;
  400. m_active_tool->on_context_menu(m_active_layer, event);
  401. }
  402. void ImageEditor::keydown_event(GUI::KeyEvent& event)
  403. {
  404. if (event.key() == Key_Delete && !m_image->selection().is_empty() && active_layer()) {
  405. active_layer()->erase_selection(m_image->selection());
  406. did_complete_action("Erase Selection"sv);
  407. return;
  408. }
  409. if (!m_active_tool)
  410. return;
  411. if (!m_active_tool->is_overriding_alt() && event.key() == Key_Alt)
  412. set_override_cursor(Gfx::StandardCursor::Eyedropper);
  413. if (m_active_tool->on_keydown(event))
  414. return;
  415. if (event.key() == Key_Escape && !m_image->selection().is_empty()) {
  416. m_image->selection().clear();
  417. did_complete_action("Clear Selection"sv);
  418. return;
  419. }
  420. event.ignore();
  421. }
  422. void ImageEditor::keyup_event(GUI::KeyEvent& event)
  423. {
  424. if (!m_active_tool)
  425. return;
  426. if (!m_active_tool->is_overriding_alt() && event.key() == Key_Alt)
  427. update_tool_cursor();
  428. m_active_tool->on_keyup(event);
  429. }
  430. void ImageEditor::enter_event(Core::Event&)
  431. {
  432. set_override_cursor(m_active_cursor);
  433. }
  434. void ImageEditor::leave_event(Core::Event&)
  435. {
  436. set_override_cursor(Gfx::StandardCursor::None);
  437. if (on_leave)
  438. on_leave();
  439. }
  440. void ImageEditor::set_active_layer(Layer* layer)
  441. {
  442. if (m_active_layer == layer)
  443. return;
  444. m_active_layer = layer;
  445. if (m_active_layer) {
  446. VERIFY(&m_active_layer->image() == m_image.ptr());
  447. size_t index = 0;
  448. for (; index < m_image->layer_count(); ++index) {
  449. if (&m_image->layer(index) == layer)
  450. break;
  451. }
  452. if (on_active_layer_change)
  453. on_active_layer_change(layer);
  454. } else {
  455. if (on_active_layer_change)
  456. on_active_layer_change({});
  457. }
  458. if (m_show_active_layer_boundary)
  459. update();
  460. }
  461. ErrorOr<void> ImageEditor::add_new_layer_from_selection()
  462. {
  463. auto current_layer_selection = image().selection();
  464. if (current_layer_selection.is_empty())
  465. return Error::from_string_literal("There is no active selection to create layer from.");
  466. // save offsets of selection so we know where to place the new layer
  467. auto selection_offset = current_layer_selection.bounding_rect().location();
  468. auto selection_bitmap = active_layer()->copy_bitmap(current_layer_selection);
  469. if (selection_bitmap.is_null())
  470. return Error::from_string_literal("Unable to create bitmap from selection.");
  471. auto layer_or_error = PixelPaint::Layer::create_with_bitmap(image(), selection_bitmap.release_nonnull(), "New Layer"sv);
  472. if (layer_or_error.is_error())
  473. return Error::from_string_literal("Unable to create layer from selection.");
  474. auto new_layer = layer_or_error.release_value();
  475. new_layer->set_location(selection_offset);
  476. image().add_layer(new_layer);
  477. layers_did_change();
  478. return {};
  479. }
  480. void ImageEditor::set_active_tool(Tool* tool)
  481. {
  482. if (m_active_tool == tool) {
  483. if (m_active_tool)
  484. m_active_tool->setup(*this);
  485. return;
  486. }
  487. if (m_active_tool) {
  488. m_active_tool->on_tool_deactivation();
  489. m_active_tool->clear();
  490. }
  491. m_active_tool = tool;
  492. if (m_active_tool) {
  493. m_active_tool->setup(*this);
  494. m_active_tool->on_tool_activation();
  495. m_active_cursor = m_active_tool->cursor();
  496. set_override_cursor(m_active_cursor);
  497. }
  498. }
  499. void ImageEditor::update_tool_cursor()
  500. {
  501. if (m_active_tool) {
  502. m_active_cursor = m_active_tool->cursor();
  503. set_override_cursor(m_active_cursor);
  504. }
  505. }
  506. void ImageEditor::set_guide_visibility(bool show_guides)
  507. {
  508. if (m_show_guides == show_guides)
  509. return;
  510. m_show_guides = show_guides;
  511. if (on_set_guide_visibility)
  512. on_set_guide_visibility(m_show_guides);
  513. update();
  514. }
  515. void ImageEditor::set_ruler_visibility(bool show_rulers)
  516. {
  517. if (m_show_rulers == show_rulers)
  518. return;
  519. m_show_rulers = show_rulers;
  520. if (on_set_ruler_visibility)
  521. on_set_ruler_visibility(m_show_rulers);
  522. update();
  523. }
  524. void ImageEditor::set_pixel_grid_visibility(bool show_pixel_grid)
  525. {
  526. if (m_show_pixel_grid == show_pixel_grid)
  527. return;
  528. m_show_pixel_grid = show_pixel_grid;
  529. update();
  530. }
  531. void ImageEditor::clear_guides()
  532. {
  533. m_guides.clear();
  534. update();
  535. }
  536. void ImageEditor::layers_did_change()
  537. {
  538. update_modified();
  539. update();
  540. }
  541. Color ImageEditor::color_for(GUI::MouseButton button) const
  542. {
  543. if (button == GUI::MouseButton::Primary)
  544. return m_primary_color;
  545. if (button == GUI::MouseButton::Secondary)
  546. return m_secondary_color;
  547. VERIFY_NOT_REACHED();
  548. }
  549. Color ImageEditor::color_for(GUI::MouseEvent const& event) const
  550. {
  551. if (event.buttons() & GUI::MouseButton::Primary)
  552. return m_primary_color;
  553. if (event.buttons() & GUI::MouseButton::Secondary)
  554. return m_secondary_color;
  555. VERIFY_NOT_REACHED();
  556. }
  557. void ImageEditor::set_primary_color(Color color)
  558. {
  559. if (m_primary_color == color)
  560. return;
  561. m_primary_color = color;
  562. if (on_primary_color_change)
  563. on_primary_color_change(color);
  564. }
  565. void ImageEditor::set_secondary_color(Color color)
  566. {
  567. if (m_secondary_color == color)
  568. return;
  569. m_secondary_color = color;
  570. if (on_secondary_color_change)
  571. on_secondary_color_change(color);
  572. }
  573. Layer* ImageEditor::layer_at_editor_position(Gfx::IntPoint editor_position)
  574. {
  575. auto image_position = frame_to_content_position(editor_position);
  576. for (ssize_t i = m_image->layer_count() - 1; i >= 0; --i) {
  577. auto& layer = m_image->layer(i);
  578. if (!layer.is_visible())
  579. continue;
  580. if (layer.relative_rect().contains(Gfx::IntPoint(image_position.x(), image_position.y())))
  581. return const_cast<Layer*>(&layer);
  582. }
  583. return nullptr;
  584. }
  585. void ImageEditor::fit_image_to_view(FitType type)
  586. {
  587. auto viewport_rect = rect();
  588. if (m_show_rulers) {
  589. viewport_rect = {
  590. viewport_rect.x() + m_ruler_thickness,
  591. viewport_rect.y() + m_ruler_thickness,
  592. viewport_rect.width() - m_ruler_thickness,
  593. viewport_rect.height() - m_ruler_thickness
  594. };
  595. }
  596. fit_content_to_rect(viewport_rect, type);
  597. }
  598. void ImageEditor::image_did_change(Gfx::IntRect const& modified_image_rect)
  599. {
  600. update(content_rect().intersected(enclosing_int_rect(content_to_frame_rect(modified_image_rect))));
  601. }
  602. void ImageEditor::image_did_change_rect(Gfx::IntRect const& new_image_rect)
  603. {
  604. set_original_rect(new_image_rect);
  605. set_content_rect(new_image_rect);
  606. relayout();
  607. }
  608. void ImageEditor::image_select_layer(Layer* layer)
  609. {
  610. set_active_layer(layer);
  611. }
  612. bool ImageEditor::request_close()
  613. {
  614. if (!undo_stack().is_current_modified())
  615. return true;
  616. auto result = GUI::MessageBox::ask_about_unsaved_changes(window(), path(), undo_stack().last_unmodified_timestamp());
  617. if (result == GUI::MessageBox::ExecResult::Yes) {
  618. save_project();
  619. return true;
  620. }
  621. if (result == GUI::MessageBox::ExecResult::No)
  622. return true;
  623. return false;
  624. }
  625. void ImageEditor::save_project()
  626. {
  627. if (path().is_empty() || m_loaded_from_image) {
  628. save_project_as();
  629. return;
  630. }
  631. auto response = FileSystemAccessClient::Client::the().request_file(window(), path(), Core::File::OpenMode::Truncate | Core::File::OpenMode::Write);
  632. if (response.is_error())
  633. return;
  634. auto result = save_project_to_file(response.value().release_stream());
  635. if (result.is_error()) {
  636. GUI::MessageBox::show_error(window(), MUST(String::formatted("Could not save {}: {}", path(), result.release_error())));
  637. return;
  638. }
  639. set_unmodified();
  640. }
  641. void ImageEditor::save_project_as()
  642. {
  643. auto response = FileSystemAccessClient::Client::the().save_file(window(), m_title.to_deprecated_string(), "pp");
  644. if (response.is_error())
  645. return;
  646. auto file = response.release_value();
  647. auto result = save_project_to_file(file.release_stream());
  648. if (result.is_error()) {
  649. GUI::MessageBox::show_error(window(), MUST(String::formatted("Could not save {}: {}", file.filename(), result.release_error())));
  650. return;
  651. }
  652. set_path(file.filename().to_deprecated_string());
  653. set_loaded_from_image(false);
  654. set_unmodified();
  655. }
  656. ErrorOr<void> ImageEditor::save_project_to_file(NonnullOwnPtr<Core::File> file) const
  657. {
  658. StringBuilder builder;
  659. auto json = TRY(JsonObjectSerializer<>::try_create(builder));
  660. TRY(m_image->serialize_as_json(json));
  661. auto json_guides = TRY(json.add_array("guides"sv));
  662. for (auto const& guide : m_guides) {
  663. auto json_guide = TRY(json_guides.add_object());
  664. TRY(json_guide.add("offset"sv, (double)guide->offset()));
  665. if (guide->orientation() == Guide::Orientation::Vertical)
  666. TRY(json_guide.add("orientation"sv, "vertical"));
  667. else if (guide->orientation() == Guide::Orientation::Horizontal)
  668. TRY(json_guide.add("orientation"sv, "horizontal"));
  669. TRY(json_guide.finish());
  670. }
  671. TRY(json_guides.finish());
  672. TRY(json.finish());
  673. TRY(file->write_until_depleted(builder.string_view().bytes()));
  674. return {};
  675. }
  676. void ImageEditor::set_show_active_layer_boundary(bool show)
  677. {
  678. if (m_show_active_layer_boundary == show)
  679. return;
  680. m_show_active_layer_boundary = show;
  681. update();
  682. }
  683. void ImageEditor::set_loaded_from_image(bool loaded_from_image)
  684. {
  685. m_loaded_from_image = loaded_from_image;
  686. }
  687. void ImageEditor::paint_selection(Gfx::Painter& painter)
  688. {
  689. if (m_image->selection().is_empty())
  690. return;
  691. draw_marching_ants(painter, m_image->selection().mask());
  692. }
  693. void ImageEditor::draw_marching_ants(Gfx::Painter& painter, Gfx::IntRect const& rect) const
  694. {
  695. // Top line
  696. for (int x = rect.left(); x < rect.right(); ++x)
  697. draw_marching_ants_pixel(painter, x, rect.top());
  698. // Right line
  699. for (int y = rect.top() + 1; y < rect.bottom(); ++y)
  700. draw_marching_ants_pixel(painter, rect.right() - 1, y);
  701. // Bottom line
  702. for (int x = rect.right() - 2; x >= rect.left(); --x)
  703. draw_marching_ants_pixel(painter, x, rect.bottom() - 1);
  704. // Left line
  705. for (int y = rect.bottom() - 2; y > rect.top(); --y)
  706. draw_marching_ants_pixel(painter, rect.left(), y);
  707. }
  708. void ImageEditor::draw_marching_ants(Gfx::Painter& painter, Mask const& mask) const
  709. {
  710. // If the zoom is < 100%, we can skip pixels to save a lot of time drawing the ants
  711. int step = max(1, (int)floorf(1.0f / scale()));
  712. // Only check the visible selection area when drawing for performance
  713. auto rect = this->rect();
  714. rect = Gfx::enclosing_int_rect(frame_to_content_rect(rect));
  715. rect.inflate(step * 2, step * 2); // prevent borders from having visible ants if the selection extends beyond it
  716. // Scan the image horizontally to find vertical borders
  717. for (int y = rect.top(); y < rect.bottom(); y += step) {
  718. bool previous_selected = false;
  719. for (int x = rect.left(); x < rect.right(); x += step) {
  720. bool this_selected = mask.get(x, y) > 0;
  721. if (this_selected != previous_selected) {
  722. Gfx::IntRect image_pixel { x, y, 1, 1 };
  723. auto pixel = content_to_frame_rect(image_pixel).to_type<int>();
  724. auto end = max(pixel.top() + 1, pixel.bottom()); // for when the zoom is < 100%
  725. for (int pixel_y = pixel.top(); pixel_y < end; pixel_y++) {
  726. draw_marching_ants_pixel(painter, pixel.left(), pixel_y);
  727. }
  728. }
  729. previous_selected = this_selected;
  730. }
  731. }
  732. // Scan the image vertically to find horizontal borders
  733. for (int x = rect.left(); x < rect.right(); x += step) {
  734. bool previous_selected = false;
  735. for (int y = rect.top(); y < rect.bottom(); y += step) {
  736. bool this_selected = mask.get(x, y) > 0;
  737. if (this_selected != previous_selected) {
  738. Gfx::IntRect image_pixel { x, y, 1, 1 };
  739. auto pixel = content_to_frame_rect(image_pixel).to_type<int>();
  740. auto end = max(pixel.left() + 1, pixel.right()); // for when the zoom is < 100%
  741. for (int pixel_x = pixel.left(); pixel_x < end; pixel_x++)
  742. draw_marching_ants_pixel(painter, pixel_x, pixel.top());
  743. }
  744. previous_selected = this_selected;
  745. }
  746. }
  747. }
  748. void ImageEditor::draw_marching_ants_pixel(Gfx::Painter& painter, int x, int y) const
  749. {
  750. int pattern_index = x + y + m_marching_ants_offset;
  751. if (pattern_index % (marching_ant_length * 2) < marching_ant_length) {
  752. painter.set_pixel(x, y, Color::Black);
  753. } else {
  754. painter.set_pixel(x, y, Color::White);
  755. }
  756. }
  757. void ImageEditor::selection_did_change()
  758. {
  759. update();
  760. }
  761. void ImageEditor::set_appended_status_info(DeprecatedString new_status_info)
  762. {
  763. m_appended_status_info = new_status_info;
  764. if (on_appended_status_info_change)
  765. on_appended_status_info_change(m_appended_status_info);
  766. }
  767. DeprecatedString ImageEditor::generate_unique_layer_name(DeprecatedString const& original_layer_name)
  768. {
  769. constexpr StringView copy_string_view = " copy"sv;
  770. auto copy_suffix_index = original_layer_name.find_last(copy_string_view);
  771. if (!copy_suffix_index.has_value())
  772. return DeprecatedString::formatted("{}{}", original_layer_name, copy_string_view);
  773. auto after_copy_suffix_view = original_layer_name.substring_view(copy_suffix_index.value() + copy_string_view.length());
  774. if (!after_copy_suffix_view.is_empty()) {
  775. auto after_copy_suffix_number = after_copy_suffix_view.trim_whitespace().to_int();
  776. if (!after_copy_suffix_number.has_value())
  777. return DeprecatedString::formatted("{}{}", original_layer_name, copy_string_view);
  778. }
  779. auto layer_with_name_exists = [this](auto name) {
  780. for (size_t i = 0; i < image().layer_count(); ++i) {
  781. if (image().layer(i).name() == name)
  782. return true;
  783. }
  784. return false;
  785. };
  786. auto base_layer_name = original_layer_name.substring_view(0, copy_suffix_index.value());
  787. StringBuilder new_layer_name;
  788. auto duplicate_name_count = 0;
  789. do {
  790. new_layer_name.clear();
  791. new_layer_name.appendff("{}{} {}", base_layer_name, copy_string_view, ++duplicate_name_count);
  792. } while (layer_with_name_exists(new_layer_name.string_view()));
  793. return new_layer_name.to_deprecated_string();
  794. }
  795. Gfx::IntRect ImageEditor::active_layer_visible_rect()
  796. {
  797. if (!active_layer())
  798. return {};
  799. auto scaled_layer_rect = active_layer()->relative_rect().to_type<float>().scaled(scale(), scale()).to_type<int>().translated(content_rect().location());
  800. auto visible_editor_rect = ruler_visibility() ? subtract_rulers_from_rect(rect()) : rect();
  801. scaled_layer_rect.intersect(visible_editor_rect);
  802. return scaled_layer_rect;
  803. }
  804. }