ImageEditor.cpp 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948
  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_tool) {
  250. if (m_show_rulers) {
  251. auto clipped_event = GUI::PaintEvent(subtract_rulers_from_rect(event.rect()), event.window_size());
  252. m_active_tool->on_second_paint(m_active_layer, clipped_event);
  253. } else {
  254. m_active_tool->on_second_paint(m_active_layer, event);
  255. }
  256. }
  257. }
  258. GUI::MouseEvent ImageEditor::event_with_pan_and_scale_applied(GUI::MouseEvent const& event) const
  259. {
  260. auto image_position = frame_to_content_position(event.position());
  261. auto tool_adjusted_image_position = m_active_tool->point_position_to_preferred_cell(image_position);
  262. return {
  263. static_cast<GUI::Event::Type>(event.type()),
  264. tool_adjusted_image_position,
  265. event.buttons(),
  266. event.button(),
  267. event.modifiers(),
  268. event.wheel_delta_x(),
  269. event.wheel_delta_y(),
  270. event.wheel_raw_delta_x(),
  271. event.wheel_raw_delta_y(),
  272. };
  273. }
  274. GUI::MouseEvent ImageEditor::event_adjusted_for_layer(GUI::MouseEvent const& event, Layer const& layer) const
  275. {
  276. auto image_position = frame_to_content_position(event.position());
  277. image_position.translate_by(-layer.location().x(), -layer.location().y());
  278. auto tool_adjusted_image_position = m_active_tool->point_position_to_preferred_cell(image_position);
  279. return {
  280. static_cast<GUI::Event::Type>(event.type()),
  281. tool_adjusted_image_position,
  282. event.buttons(),
  283. event.button(),
  284. event.modifiers(),
  285. event.wheel_delta_x(),
  286. event.wheel_delta_y(),
  287. event.wheel_raw_delta_x(),
  288. event.wheel_raw_delta_y(),
  289. };
  290. }
  291. Optional<Color> ImageEditor::color_from_position(Gfx::IntPoint position, bool sample_all_layers)
  292. {
  293. Color color;
  294. auto* layer = active_layer();
  295. if (sample_all_layers) {
  296. color = image().color_at(position);
  297. } else {
  298. if (!layer || !layer->rect().contains(position))
  299. return {};
  300. color = layer->currently_edited_bitmap().get_pixel(position);
  301. }
  302. return color;
  303. }
  304. void ImageEditor::set_status_info_to_color_at_mouse_position(Gfx::IntPoint position, bool sample_all_layers)
  305. {
  306. auto const color = color_from_position(position, sample_all_layers);
  307. if (!color.has_value())
  308. return;
  309. set_appended_status_info(DeprecatedString::formatted("R:{}, G:{}, B:{}, A:{} [{}]", color->red(), color->green(), color->blue(), color->alpha(), color->to_deprecated_string()));
  310. }
  311. void ImageEditor::set_editor_color_to_color_at_mouse_position(GUI::MouseEvent const& event, bool sample_all_layers = false)
  312. {
  313. auto const color = color_from_position(event.position(), sample_all_layers);
  314. if (!color.has_value())
  315. return;
  316. // We picked a transparent pixel, do nothing.
  317. if (!color->alpha())
  318. return;
  319. if (event.buttons() & GUI::MouseButton::Primary)
  320. set_primary_color(*color);
  321. if (event.buttons() & GUI::MouseButton::Secondary)
  322. set_secondary_color(*color);
  323. }
  324. void ImageEditor::mousedown_event(GUI::MouseEvent& event)
  325. {
  326. if (event.button() == GUI::MouseButton::Middle) {
  327. start_panning(event.position());
  328. set_override_cursor(Gfx::StandardCursor::Drag);
  329. return;
  330. }
  331. if (!m_active_tool)
  332. return;
  333. if (auto* tool = dynamic_cast<MoveTool*>(m_active_tool); tool && tool->layer_selection_mode() == MoveTool::LayerSelectionMode::ForegroundLayer) {
  334. if (auto* foreground_layer = layer_at_editor_position(event.position()); foreground_layer && !tool->cursor_is_within_resize_anchor())
  335. set_active_layer(foreground_layer);
  336. }
  337. auto layer_event = m_active_layer ? event_adjusted_for_layer(event, *m_active_layer) : event;
  338. if (event.alt() && !m_active_tool->is_overriding_alt()) {
  339. set_editor_color_to_color_at_mouse_position(layer_event);
  340. return; // Pick Color instead of acivating active tool when holding alt.
  341. }
  342. auto image_event = event_with_pan_and_scale_applied(event);
  343. Tool::MouseEvent tool_event(Tool::MouseEvent::Action::MouseDown, layer_event, image_event, event);
  344. m_active_tool->on_mousedown(m_active_layer.ptr(), tool_event);
  345. }
  346. void ImageEditor::doubleclick_event(GUI::MouseEvent& event)
  347. {
  348. if (!m_active_tool || (event.alt() && !m_active_tool->is_overriding_alt()))
  349. return;
  350. auto layer_event = m_active_layer ? event_adjusted_for_layer(event, *m_active_layer) : event;
  351. auto image_event = event_with_pan_and_scale_applied(event);
  352. Tool::MouseEvent tool_event(Tool::MouseEvent::Action::DoubleClick, layer_event, image_event, event);
  353. m_active_tool->on_doubleclick(m_active_layer.ptr(), tool_event);
  354. }
  355. void ImageEditor::mousemove_event(GUI::MouseEvent& event)
  356. {
  357. m_mouse_position = event.position();
  358. if (m_show_rulers) {
  359. update(mouse_indicator_rect_x());
  360. update(mouse_indicator_rect_y());
  361. }
  362. if (is_panning()) {
  363. GUI::AbstractZoomPanWidget::mousemove_event(event);
  364. return;
  365. }
  366. auto image_event = event_with_pan_and_scale_applied(event);
  367. if (on_image_mouse_position_change) {
  368. on_image_mouse_position_change(image_event.position());
  369. }
  370. auto layer_event = m_active_layer ? event_adjusted_for_layer(event, *m_active_layer) : event;
  371. if (m_active_tool && event.alt() && !m_active_tool->is_overriding_alt()) {
  372. set_override_cursor(Gfx::StandardCursor::Eyedropper);
  373. set_editor_color_to_color_at_mouse_position(layer_event);
  374. return;
  375. }
  376. Tool::MouseEvent tool_event(Tool::MouseEvent::Action::MouseDown, layer_event, image_event, event);
  377. m_active_tool->on_mousemove(m_active_layer.ptr(), tool_event);
  378. }
  379. void ImageEditor::mouseup_event(GUI::MouseEvent& event)
  380. {
  381. if (!(m_active_tool && event.alt() && !m_active_tool->is_overriding_alt()))
  382. set_override_cursor(m_active_cursor);
  383. if (event.button() == GUI::MouseButton::Middle) {
  384. stop_panning();
  385. return;
  386. }
  387. if (!m_active_tool || (event.alt() && !m_active_tool->is_overriding_alt()))
  388. return;
  389. auto layer_event = m_active_layer ? event_adjusted_for_layer(event, *m_active_layer) : event;
  390. auto image_event = event_with_pan_and_scale_applied(event);
  391. Tool::MouseEvent tool_event(Tool::MouseEvent::Action::MouseDown, layer_event, image_event, event);
  392. m_active_tool->on_mouseup(m_active_layer.ptr(), tool_event);
  393. }
  394. void ImageEditor::context_menu_event(GUI::ContextMenuEvent& event)
  395. {
  396. if (!m_active_tool)
  397. return;
  398. m_active_tool->on_context_menu(m_active_layer, event);
  399. }
  400. void ImageEditor::keydown_event(GUI::KeyEvent& event)
  401. {
  402. if (event.key() == Key_Delete && !m_image->selection().is_empty() && active_layer()) {
  403. active_layer()->erase_selection(m_image->selection());
  404. did_complete_action("Erase Selection"sv);
  405. return;
  406. }
  407. if (!m_active_tool)
  408. return;
  409. if (!m_active_tool->is_overriding_alt() && event.key() == Key_Alt)
  410. set_override_cursor(Gfx::StandardCursor::Eyedropper);
  411. if (m_active_tool->on_keydown(event))
  412. return;
  413. if (event.key() == Key_Escape && !m_image->selection().is_empty()) {
  414. m_image->selection().clear();
  415. did_complete_action("Clear Selection"sv);
  416. return;
  417. }
  418. event.ignore();
  419. }
  420. void ImageEditor::keyup_event(GUI::KeyEvent& event)
  421. {
  422. if (!m_active_tool)
  423. return;
  424. if (!m_active_tool->is_overriding_alt() && event.key() == Key_Alt)
  425. update_tool_cursor();
  426. m_active_tool->on_keyup(event);
  427. }
  428. void ImageEditor::enter_event(Core::Event&)
  429. {
  430. set_override_cursor(m_active_cursor);
  431. }
  432. void ImageEditor::leave_event(Core::Event&)
  433. {
  434. set_override_cursor(Gfx::StandardCursor::None);
  435. if (on_leave)
  436. on_leave();
  437. }
  438. void ImageEditor::set_active_layer(Layer* layer)
  439. {
  440. if (m_active_layer == layer)
  441. return;
  442. m_active_layer = layer;
  443. if (m_active_layer) {
  444. VERIFY(&m_active_layer->image() == m_image.ptr());
  445. size_t index = 0;
  446. for (; index < m_image->layer_count(); ++index) {
  447. if (&m_image->layer(index) == layer)
  448. break;
  449. }
  450. if (on_active_layer_change)
  451. on_active_layer_change(layer);
  452. } else {
  453. if (on_active_layer_change)
  454. on_active_layer_change({});
  455. }
  456. if (m_show_active_layer_boundary)
  457. update();
  458. }
  459. ErrorOr<void> ImageEditor::add_new_layer_from_selection()
  460. {
  461. auto current_layer_selection = image().selection();
  462. if (current_layer_selection.is_empty())
  463. return Error::from_string_literal("There is no active selection to create layer from.");
  464. // save offsets of selection so we know where to place the new layer
  465. auto selection_offset = current_layer_selection.bounding_rect().location();
  466. auto selection_bitmap = active_layer()->copy_bitmap(current_layer_selection);
  467. if (selection_bitmap.is_null())
  468. return Error::from_string_literal("Unable to create bitmap from selection.");
  469. auto layer_or_error = PixelPaint::Layer::create_with_bitmap(image(), selection_bitmap.release_nonnull(), "New Layer"sv);
  470. if (layer_or_error.is_error())
  471. return Error::from_string_literal("Unable to create layer from selection.");
  472. auto new_layer = layer_or_error.release_value();
  473. new_layer->set_location(selection_offset);
  474. image().add_layer(new_layer);
  475. layers_did_change();
  476. return {};
  477. }
  478. void ImageEditor::set_active_tool(Tool* tool)
  479. {
  480. if (m_active_tool == tool) {
  481. if (m_active_tool)
  482. m_active_tool->setup(*this);
  483. return;
  484. }
  485. if (m_active_tool) {
  486. m_active_tool->on_tool_deactivation();
  487. m_active_tool->clear();
  488. }
  489. m_active_tool = tool;
  490. if (m_active_tool) {
  491. m_active_tool->setup(*this);
  492. m_active_tool->on_tool_activation();
  493. m_active_cursor = m_active_tool->cursor();
  494. set_override_cursor(m_active_cursor);
  495. }
  496. }
  497. void ImageEditor::update_tool_cursor()
  498. {
  499. if (m_active_tool) {
  500. m_active_cursor = m_active_tool->cursor();
  501. set_override_cursor(m_active_cursor);
  502. }
  503. }
  504. void ImageEditor::set_guide_visibility(bool show_guides)
  505. {
  506. if (m_show_guides == show_guides)
  507. return;
  508. m_show_guides = show_guides;
  509. if (on_set_guide_visibility)
  510. on_set_guide_visibility(m_show_guides);
  511. update();
  512. }
  513. void ImageEditor::set_ruler_visibility(bool show_rulers)
  514. {
  515. if (m_show_rulers == show_rulers)
  516. return;
  517. m_show_rulers = show_rulers;
  518. if (on_set_ruler_visibility)
  519. on_set_ruler_visibility(m_show_rulers);
  520. update();
  521. }
  522. void ImageEditor::set_pixel_grid_visibility(bool show_pixel_grid)
  523. {
  524. if (m_show_pixel_grid == show_pixel_grid)
  525. return;
  526. m_show_pixel_grid = show_pixel_grid;
  527. update();
  528. }
  529. void ImageEditor::clear_guides()
  530. {
  531. m_guides.clear();
  532. update();
  533. }
  534. void ImageEditor::layers_did_change()
  535. {
  536. update_modified();
  537. update();
  538. }
  539. Color ImageEditor::color_for(GUI::MouseButton button) const
  540. {
  541. if (button == GUI::MouseButton::Primary)
  542. return m_primary_color;
  543. if (button == GUI::MouseButton::Secondary)
  544. return m_secondary_color;
  545. VERIFY_NOT_REACHED();
  546. }
  547. Color ImageEditor::color_for(GUI::MouseEvent const& event) const
  548. {
  549. if (event.buttons() & GUI::MouseButton::Primary)
  550. return m_primary_color;
  551. if (event.buttons() & GUI::MouseButton::Secondary)
  552. return m_secondary_color;
  553. VERIFY_NOT_REACHED();
  554. }
  555. void ImageEditor::set_primary_color(Color color)
  556. {
  557. if (m_primary_color == color)
  558. return;
  559. m_primary_color = color;
  560. if (on_primary_color_change)
  561. on_primary_color_change(color);
  562. }
  563. void ImageEditor::set_secondary_color(Color color)
  564. {
  565. if (m_secondary_color == color)
  566. return;
  567. m_secondary_color = color;
  568. if (on_secondary_color_change)
  569. on_secondary_color_change(color);
  570. }
  571. Layer* ImageEditor::layer_at_editor_position(Gfx::IntPoint editor_position)
  572. {
  573. auto image_position = frame_to_content_position(editor_position);
  574. for (ssize_t i = m_image->layer_count() - 1; i >= 0; --i) {
  575. auto& layer = m_image->layer(i);
  576. if (!layer.is_visible())
  577. continue;
  578. if (layer.relative_rect().contains(Gfx::IntPoint(image_position.x(), image_position.y())))
  579. return const_cast<Layer*>(&layer);
  580. }
  581. return nullptr;
  582. }
  583. void ImageEditor::fit_image_to_view(FitType type)
  584. {
  585. auto viewport_rect = rect();
  586. if (m_show_rulers) {
  587. viewport_rect = {
  588. viewport_rect.x() + m_ruler_thickness,
  589. viewport_rect.y() + m_ruler_thickness,
  590. viewport_rect.width() - m_ruler_thickness,
  591. viewport_rect.height() - m_ruler_thickness
  592. };
  593. }
  594. fit_content_to_rect(viewport_rect, type);
  595. }
  596. void ImageEditor::image_did_change(Gfx::IntRect const& modified_image_rect)
  597. {
  598. update(content_rect().intersected(enclosing_int_rect(content_to_frame_rect(modified_image_rect))));
  599. }
  600. void ImageEditor::image_did_change_rect(Gfx::IntRect const& new_image_rect)
  601. {
  602. set_original_rect(new_image_rect);
  603. set_content_rect(new_image_rect);
  604. relayout();
  605. }
  606. void ImageEditor::image_select_layer(Layer* layer)
  607. {
  608. set_active_layer(layer);
  609. }
  610. bool ImageEditor::request_close()
  611. {
  612. if (!undo_stack().is_current_modified())
  613. return true;
  614. auto result = GUI::MessageBox::ask_about_unsaved_changes(window(), path(), undo_stack().last_unmodified_timestamp());
  615. if (result == GUI::MessageBox::ExecResult::Yes) {
  616. save_project();
  617. return true;
  618. }
  619. if (result == GUI::MessageBox::ExecResult::No)
  620. return true;
  621. return false;
  622. }
  623. void ImageEditor::save_project()
  624. {
  625. if (path().is_empty() || m_loaded_from_image) {
  626. save_project_as();
  627. return;
  628. }
  629. auto response = FileSystemAccessClient::Client::the().request_file(window(), path(), Core::File::OpenMode::Truncate | Core::File::OpenMode::Write);
  630. if (response.is_error())
  631. return;
  632. auto result = save_project_to_file(response.value().release_stream());
  633. if (result.is_error()) {
  634. GUI::MessageBox::show_error(window(), MUST(String::formatted("Could not save {}: {}", path(), result.release_error())));
  635. return;
  636. }
  637. set_unmodified();
  638. }
  639. void ImageEditor::save_project_as()
  640. {
  641. auto response = FileSystemAccessClient::Client::the().save_file(window(), m_title.to_deprecated_string(), "pp");
  642. if (response.is_error())
  643. return;
  644. auto file = response.release_value();
  645. auto result = save_project_to_file(file.release_stream());
  646. if (result.is_error()) {
  647. GUI::MessageBox::show_error(window(), MUST(String::formatted("Could not save {}: {}", file.filename(), result.release_error())));
  648. return;
  649. }
  650. set_path(file.filename().to_deprecated_string());
  651. set_loaded_from_image(false);
  652. set_unmodified();
  653. }
  654. ErrorOr<void> ImageEditor::save_project_to_file(NonnullOwnPtr<Core::File> file) const
  655. {
  656. StringBuilder builder;
  657. auto json = TRY(JsonObjectSerializer<>::try_create(builder));
  658. TRY(m_image->serialize_as_json(json));
  659. auto json_guides = TRY(json.add_array("guides"sv));
  660. for (auto const& guide : m_guides) {
  661. auto json_guide = TRY(json_guides.add_object());
  662. TRY(json_guide.add("offset"sv, (double)guide->offset()));
  663. if (guide->orientation() == Guide::Orientation::Vertical)
  664. TRY(json_guide.add("orientation"sv, "vertical"));
  665. else if (guide->orientation() == Guide::Orientation::Horizontal)
  666. TRY(json_guide.add("orientation"sv, "horizontal"));
  667. TRY(json_guide.finish());
  668. }
  669. TRY(json_guides.finish());
  670. TRY(json.finish());
  671. TRY(file->write_until_depleted(builder.string_view().bytes()));
  672. return {};
  673. }
  674. void ImageEditor::set_show_active_layer_boundary(bool show)
  675. {
  676. if (m_show_active_layer_boundary == show)
  677. return;
  678. m_show_active_layer_boundary = show;
  679. update();
  680. }
  681. void ImageEditor::set_loaded_from_image(bool loaded_from_image)
  682. {
  683. m_loaded_from_image = loaded_from_image;
  684. }
  685. void ImageEditor::paint_selection(Gfx::Painter& painter)
  686. {
  687. if (m_image->selection().is_empty())
  688. return;
  689. draw_marching_ants(painter, m_image->selection().mask());
  690. }
  691. void ImageEditor::draw_marching_ants(Gfx::Painter& painter, Gfx::IntRect const& rect) const
  692. {
  693. // Top line
  694. for (int x = rect.left(); x < rect.right(); ++x)
  695. draw_marching_ants_pixel(painter, x, rect.top());
  696. // Right line
  697. for (int y = rect.top() + 1; y < rect.bottom(); ++y)
  698. draw_marching_ants_pixel(painter, rect.right() - 1, y);
  699. // Bottom line
  700. for (int x = rect.right() - 2; x >= rect.left(); --x)
  701. draw_marching_ants_pixel(painter, x, rect.bottom() - 1);
  702. // Left line
  703. for (int y = rect.bottom() - 2; y > rect.top(); --y)
  704. draw_marching_ants_pixel(painter, rect.left(), y);
  705. }
  706. void ImageEditor::draw_marching_ants(Gfx::Painter& painter, Mask const& mask) const
  707. {
  708. // If the zoom is < 100%, we can skip pixels to save a lot of time drawing the ants
  709. int step = max(1, (int)floorf(1.0f / scale()));
  710. // Only check the visible selection area when drawing for performance
  711. auto rect = this->rect();
  712. rect = Gfx::enclosing_int_rect(frame_to_content_rect(rect));
  713. rect.inflate(step * 2, step * 2); // prevent borders from having visible ants if the selection extends beyond it
  714. // Scan the image horizontally to find vertical borders
  715. for (int y = rect.top(); y < rect.bottom(); y += step) {
  716. bool previous_selected = false;
  717. for (int x = rect.left(); x < rect.right(); x += step) {
  718. bool this_selected = mask.get(x, y) > 0;
  719. if (this_selected != previous_selected) {
  720. Gfx::IntRect image_pixel { x, y, 1, 1 };
  721. auto pixel = content_to_frame_rect(image_pixel).to_type<int>();
  722. auto end = max(pixel.top() + 1, pixel.bottom()); // for when the zoom is < 100%
  723. for (int pixel_y = pixel.top(); pixel_y < end; pixel_y++) {
  724. draw_marching_ants_pixel(painter, pixel.left(), pixel_y);
  725. }
  726. }
  727. previous_selected = this_selected;
  728. }
  729. }
  730. // Scan the image vertically to find horizontal borders
  731. for (int x = rect.left(); x < rect.right(); x += step) {
  732. bool previous_selected = false;
  733. for (int y = rect.top(); y < rect.bottom(); y += step) {
  734. bool this_selected = mask.get(x, y) > 0;
  735. if (this_selected != previous_selected) {
  736. Gfx::IntRect image_pixel { x, y, 1, 1 };
  737. auto pixel = content_to_frame_rect(image_pixel).to_type<int>();
  738. auto end = max(pixel.left() + 1, pixel.right()); // for when the zoom is < 100%
  739. for (int pixel_x = pixel.left(); pixel_x < end; pixel_x++)
  740. draw_marching_ants_pixel(painter, pixel_x, pixel.top());
  741. }
  742. previous_selected = this_selected;
  743. }
  744. }
  745. }
  746. void ImageEditor::draw_marching_ants_pixel(Gfx::Painter& painter, int x, int y) const
  747. {
  748. int pattern_index = x + y + m_marching_ants_offset;
  749. if (pattern_index % (marching_ant_length * 2) < marching_ant_length) {
  750. painter.set_pixel(x, y, Color::Black);
  751. } else {
  752. painter.set_pixel(x, y, Color::White);
  753. }
  754. }
  755. void ImageEditor::selection_did_change()
  756. {
  757. update();
  758. }
  759. void ImageEditor::set_appended_status_info(DeprecatedString new_status_info)
  760. {
  761. m_appended_status_info = new_status_info;
  762. if (on_appended_status_info_change)
  763. on_appended_status_info_change(m_appended_status_info);
  764. }
  765. DeprecatedString ImageEditor::generate_unique_layer_name(DeprecatedString const& original_layer_name)
  766. {
  767. constexpr StringView copy_string_view = " copy"sv;
  768. auto copy_suffix_index = original_layer_name.find_last(copy_string_view);
  769. if (!copy_suffix_index.has_value())
  770. return DeprecatedString::formatted("{}{}", original_layer_name, copy_string_view);
  771. auto after_copy_suffix_view = original_layer_name.substring_view(copy_suffix_index.value() + copy_string_view.length());
  772. if (!after_copy_suffix_view.is_empty()) {
  773. auto after_copy_suffix_number = after_copy_suffix_view.trim_whitespace().to_int();
  774. if (!after_copy_suffix_number.has_value())
  775. return DeprecatedString::formatted("{}{}", original_layer_name, copy_string_view);
  776. }
  777. auto layer_with_name_exists = [this](auto name) {
  778. for (size_t i = 0; i < image().layer_count(); ++i) {
  779. if (image().layer(i).name() == name)
  780. return true;
  781. }
  782. return false;
  783. };
  784. auto base_layer_name = original_layer_name.substring_view(0, copy_suffix_index.value());
  785. StringBuilder new_layer_name;
  786. auto duplicate_name_count = 0;
  787. do {
  788. new_layer_name.clear();
  789. new_layer_name.appendff("{}{} {}", base_layer_name, copy_string_view, ++duplicate_name_count);
  790. } while (layer_with_name_exists(new_layer_name.string_view()));
  791. return new_layer_name.to_deprecated_string();
  792. }
  793. }