ImageEditor.cpp 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969
  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)
  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, ByteString()));
  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(ByteString 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(ByteString path)
  98. {
  99. m_path = move(path);
  100. set_title(String::from_byte_string(LexicalPath::title(m_path)).release_value_but_fixme_should_propagate_errors());
  101. }
  102. void ImageEditor::set_modified(ByteString 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 } }, ByteString::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 } }, ByteString::formatted("{}", y), painter.font(), Gfx::TextAlignment::BottomRight, ruler_text_color);
  210. }
  211. // Mouse position indicator
  212. Gfx::IntPoint const indicator_x({ m_mouse_position.x(), m_ruler_thickness });
  213. Gfx::IntPoint const 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. Gfx::IntPoint const top_left({ m_ruler_thickness, m_ruler_thickness - m_mouse_indicator_triangle_size });
  238. Gfx::IntSize const 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. Gfx::IntPoint const top_left({ m_ruler_thickness - m_mouse_indicator_triangle_size, m_ruler_thickness });
  244. Gfx::IntSize const 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(ByteString::formatted("R:{}, G:{}, B:{}, A:{} [{}]", color->red(), color->green(), color->blue(), color->alpha(), color->to_byte_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. if (active_tool() == nullptr)
  369. return;
  370. auto image_event = event_with_pan_and_scale_applied(event);
  371. if (on_image_mouse_position_change) {
  372. on_image_mouse_position_change(image_event.position());
  373. }
  374. auto layer_event = m_active_layer ? event_adjusted_for_layer(event, *m_active_layer) : event;
  375. if (m_active_tool && event.alt() && !m_active_tool->is_overriding_alt()) {
  376. set_override_cursor(Gfx::StandardCursor::Eyedropper);
  377. set_editor_color_to_color_at_mouse_position(layer_event);
  378. return;
  379. }
  380. Tool::MouseEvent tool_event(Tool::MouseEvent::Action::MouseDown, layer_event, image_event, event);
  381. m_active_tool->on_mousemove(m_active_layer.ptr(), tool_event);
  382. }
  383. void ImageEditor::mouseup_event(GUI::MouseEvent& event)
  384. {
  385. if (!(m_active_tool && event.alt() && !m_active_tool->is_overriding_alt()))
  386. set_override_cursor(m_active_cursor);
  387. if (event.button() == GUI::MouseButton::Middle) {
  388. stop_panning();
  389. return;
  390. }
  391. if (!m_active_tool || (event.alt() && !m_active_tool->is_overriding_alt()))
  392. return;
  393. auto layer_event = m_active_layer ? event_adjusted_for_layer(event, *m_active_layer) : event;
  394. auto image_event = event_with_pan_and_scale_applied(event);
  395. Tool::MouseEvent tool_event(Tool::MouseEvent::Action::MouseDown, layer_event, image_event, event);
  396. m_active_tool->on_mouseup(m_active_layer.ptr(), tool_event);
  397. }
  398. void ImageEditor::context_menu_event(GUI::ContextMenuEvent& event)
  399. {
  400. if (!m_active_tool)
  401. return;
  402. m_active_tool->on_context_menu(m_active_layer, event);
  403. }
  404. void ImageEditor::keydown_event(GUI::KeyEvent& event)
  405. {
  406. if (event.key() == Key_Delete && !m_image->selection().is_empty() && active_layer()) {
  407. active_layer()->erase_selection(m_image->selection());
  408. did_complete_action("Erase Selection"sv);
  409. return;
  410. }
  411. if (!m_active_tool)
  412. return;
  413. if (!m_active_tool->is_overriding_alt() && event.key() == Key_Alt)
  414. set_override_cursor(Gfx::StandardCursor::Eyedropper);
  415. if (m_active_tool->on_keydown(event))
  416. return;
  417. if (event.key() == Key_Escape && !m_image->selection().is_empty()) {
  418. m_image->selection().clear();
  419. did_complete_action("Clear Selection"sv);
  420. return;
  421. }
  422. event.ignore();
  423. }
  424. void ImageEditor::keyup_event(GUI::KeyEvent& event)
  425. {
  426. if (!m_active_tool)
  427. return;
  428. if (!m_active_tool->is_overriding_alt() && event.key() == Key_Alt)
  429. update_tool_cursor();
  430. m_active_tool->on_keyup(event);
  431. }
  432. void ImageEditor::enter_event(Core::Event&)
  433. {
  434. set_override_cursor(m_active_cursor);
  435. }
  436. void ImageEditor::leave_event(Core::Event&)
  437. {
  438. set_override_cursor(Gfx::StandardCursor::None);
  439. if (on_leave)
  440. on_leave();
  441. }
  442. void ImageEditor::set_active_layer(Layer* layer)
  443. {
  444. if (m_active_layer == layer)
  445. return;
  446. m_active_layer = layer;
  447. if (m_active_layer) {
  448. VERIFY(&m_active_layer->image() == m_image.ptr());
  449. size_t index = 0;
  450. for (; index < m_image->layer_count(); ++index) {
  451. if (&m_image->layer(index) == layer)
  452. break;
  453. }
  454. if (on_active_layer_change)
  455. on_active_layer_change(layer);
  456. } else {
  457. if (on_active_layer_change)
  458. on_active_layer_change({});
  459. }
  460. if (m_show_active_layer_boundary)
  461. update();
  462. }
  463. ErrorOr<void> ImageEditor::add_new_layer_from_selection()
  464. {
  465. auto current_layer_selection = image().selection();
  466. if (current_layer_selection.is_empty())
  467. return Error::from_string_literal("There is no active selection to create layer from.");
  468. // save offsets of selection so we know where to place the new layer
  469. auto selection_offset = current_layer_selection.bounding_rect().location();
  470. auto selection_bitmap = active_layer()->copy_bitmap(current_layer_selection);
  471. if (selection_bitmap.is_null())
  472. return Error::from_string_literal("Unable to create bitmap from selection.");
  473. auto layer_or_error = PixelPaint::Layer::create_with_bitmap(image(), selection_bitmap.release_nonnull(), "New Layer"sv);
  474. if (layer_or_error.is_error())
  475. return Error::from_string_literal("Unable to create layer from selection.");
  476. auto new_layer = layer_or_error.release_value();
  477. new_layer->set_location(selection_offset);
  478. image().add_layer(new_layer);
  479. layers_did_change();
  480. return {};
  481. }
  482. void ImageEditor::set_active_tool(Tool* tool)
  483. {
  484. if (m_active_tool == tool) {
  485. if (m_active_tool)
  486. m_active_tool->setup(*this);
  487. return;
  488. }
  489. if (m_active_tool) {
  490. m_active_tool->on_tool_deactivation();
  491. m_active_tool->clear();
  492. }
  493. m_active_tool = tool;
  494. if (m_active_tool) {
  495. m_active_tool->setup(*this);
  496. m_active_tool->on_tool_activation();
  497. m_active_cursor = m_active_tool->cursor();
  498. set_override_cursor(m_active_cursor);
  499. }
  500. }
  501. void ImageEditor::update_tool_cursor()
  502. {
  503. if (m_active_tool) {
  504. m_active_cursor = m_active_tool->cursor();
  505. set_override_cursor(m_active_cursor);
  506. }
  507. }
  508. void ImageEditor::set_guide_visibility(bool show_guides)
  509. {
  510. if (m_show_guides == show_guides)
  511. return;
  512. m_show_guides = show_guides;
  513. if (on_set_guide_visibility)
  514. on_set_guide_visibility(m_show_guides);
  515. update();
  516. }
  517. void ImageEditor::set_ruler_visibility(bool show_rulers)
  518. {
  519. if (m_show_rulers == show_rulers)
  520. return;
  521. m_show_rulers = show_rulers;
  522. if (on_set_ruler_visibility)
  523. on_set_ruler_visibility(m_show_rulers);
  524. update();
  525. }
  526. void ImageEditor::set_pixel_grid_visibility(bool show_pixel_grid)
  527. {
  528. if (m_show_pixel_grid == show_pixel_grid)
  529. return;
  530. m_show_pixel_grid = show_pixel_grid;
  531. update();
  532. }
  533. void ImageEditor::clear_guides()
  534. {
  535. m_guides.clear();
  536. update();
  537. }
  538. void ImageEditor::layers_did_change()
  539. {
  540. update_modified();
  541. update();
  542. }
  543. Color ImageEditor::color_for(GUI::MouseButton button) const
  544. {
  545. if (button == GUI::MouseButton::Primary)
  546. return m_primary_color;
  547. if (button == GUI::MouseButton::Secondary)
  548. return m_secondary_color;
  549. VERIFY_NOT_REACHED();
  550. }
  551. Color ImageEditor::color_for(GUI::MouseEvent const& event) const
  552. {
  553. if (event.buttons() & GUI::MouseButton::Primary)
  554. return m_primary_color;
  555. if (event.buttons() & GUI::MouseButton::Secondary)
  556. return m_secondary_color;
  557. VERIFY_NOT_REACHED();
  558. }
  559. void ImageEditor::set_primary_color(Color color)
  560. {
  561. if (m_primary_color == color)
  562. return;
  563. m_primary_color = color;
  564. if (on_primary_color_change)
  565. on_primary_color_change(color);
  566. }
  567. void ImageEditor::set_secondary_color(Color color)
  568. {
  569. if (m_secondary_color == color)
  570. return;
  571. m_secondary_color = color;
  572. if (on_secondary_color_change)
  573. on_secondary_color_change(color);
  574. }
  575. Layer* ImageEditor::layer_at_editor_position(Gfx::IntPoint editor_position)
  576. {
  577. auto image_position = frame_to_content_position(editor_position);
  578. for (ssize_t i = m_image->layer_count() - 1; i >= 0; --i) {
  579. auto& layer = m_image->layer(i);
  580. if (!layer.is_visible())
  581. continue;
  582. if (layer.relative_rect().contains(Gfx::IntPoint(image_position.x(), image_position.y())))
  583. return const_cast<Layer*>(&layer);
  584. }
  585. return nullptr;
  586. }
  587. void ImageEditor::fit_image_to_view(FitType type)
  588. {
  589. auto viewport_rect = rect();
  590. if (m_show_rulers) {
  591. viewport_rect = {
  592. viewport_rect.x() + m_ruler_thickness,
  593. viewport_rect.y() + m_ruler_thickness,
  594. viewport_rect.width() - m_ruler_thickness,
  595. viewport_rect.height() - m_ruler_thickness
  596. };
  597. }
  598. fit_content_to_rect(viewport_rect, type);
  599. }
  600. void ImageEditor::image_did_change(Gfx::IntRect const& modified_image_rect)
  601. {
  602. update(content_rect().intersected(enclosing_int_rect(content_to_frame_rect(modified_image_rect))));
  603. }
  604. void ImageEditor::image_did_change_rect(Gfx::IntRect const& new_image_rect)
  605. {
  606. set_original_rect(new_image_rect);
  607. set_content_rect(new_image_rect);
  608. relayout();
  609. }
  610. void ImageEditor::image_select_layer(Layer* layer)
  611. {
  612. set_active_layer(layer);
  613. }
  614. bool ImageEditor::request_close()
  615. {
  616. if (!undo_stack().is_current_modified())
  617. return true;
  618. auto result = GUI::MessageBox::ask_about_unsaved_changes(window(), path(), undo_stack().last_unmodified_timestamp());
  619. if (result == GUI::MessageBox::ExecResult::Yes) {
  620. save_project();
  621. return true;
  622. }
  623. if (result == GUI::MessageBox::ExecResult::No)
  624. return true;
  625. return false;
  626. }
  627. void ImageEditor::save_project()
  628. {
  629. if (path().is_empty() || m_loaded_from_image) {
  630. save_project_as();
  631. return;
  632. }
  633. auto response = FileSystemAccessClient::Client::the().request_file(window(), path(), Core::File::OpenMode::Truncate | Core::File::OpenMode::Write);
  634. if (response.is_error())
  635. return;
  636. auto result = save_project_to_file(response.value().release_stream());
  637. if (result.is_error()) {
  638. GUI::MessageBox::show_error(window(), MUST(String::formatted("Could not save {}: {}", path(), result.release_error())));
  639. return;
  640. }
  641. set_unmodified();
  642. if (on_file_saved)
  643. on_file_saved(path());
  644. }
  645. void ImageEditor::save_project_as()
  646. {
  647. auto response = FileSystemAccessClient::Client::the().save_file(window(), m_title.to_byte_string(), "pp");
  648. if (response.is_error())
  649. return;
  650. auto file = response.release_value();
  651. auto result = save_project_to_file(file.release_stream());
  652. if (result.is_error()) {
  653. GUI::MessageBox::show_error(window(), MUST(String::formatted("Could not save {}: {}", file.filename(), result.release_error())));
  654. return;
  655. }
  656. set_path(file.filename());
  657. set_loaded_from_image(false);
  658. set_unmodified();
  659. if (on_file_saved)
  660. on_file_saved(path());
  661. }
  662. ErrorOr<void> ImageEditor::save_project_to_file(NonnullOwnPtr<Core::File> file) const
  663. {
  664. StringBuilder builder;
  665. auto json = TRY(JsonObjectSerializer<>::try_create(builder));
  666. TRY(m_image->serialize_as_json(json));
  667. auto json_guides = TRY(json.add_array("guides"sv));
  668. for (auto const& guide : m_guides) {
  669. auto json_guide = TRY(json_guides.add_object());
  670. TRY(json_guide.add("offset"sv, (double)guide->offset()));
  671. if (guide->orientation() == Guide::Orientation::Vertical)
  672. TRY(json_guide.add("orientation"sv, "vertical"));
  673. else if (guide->orientation() == Guide::Orientation::Horizontal)
  674. TRY(json_guide.add("orientation"sv, "horizontal"));
  675. TRY(json_guide.finish());
  676. }
  677. TRY(json_guides.finish());
  678. TRY(json.finish());
  679. TRY(file->write_until_depleted(builder.string_view().bytes()));
  680. return {};
  681. }
  682. void ImageEditor::set_show_active_layer_boundary(bool show)
  683. {
  684. if (m_show_active_layer_boundary == show)
  685. return;
  686. m_show_active_layer_boundary = show;
  687. update();
  688. }
  689. void ImageEditor::set_loaded_from_image(bool loaded_from_image)
  690. {
  691. m_loaded_from_image = loaded_from_image;
  692. }
  693. void ImageEditor::paint_selection(Gfx::Painter& painter)
  694. {
  695. if (m_image->selection().is_empty())
  696. return;
  697. draw_marching_ants(painter, m_image->selection().mask());
  698. }
  699. void ImageEditor::draw_marching_ants(Gfx::Painter& painter, Gfx::IntRect const& rect) const
  700. {
  701. // Top line
  702. for (int x = rect.left(); x < rect.right(); ++x)
  703. draw_marching_ants_pixel(painter, x, rect.top());
  704. // Right line
  705. for (int y = rect.top() + 1; y < rect.bottom(); ++y)
  706. draw_marching_ants_pixel(painter, rect.right() - 1, y);
  707. // Bottom line
  708. for (int x = rect.right() - 2; x >= rect.left(); --x)
  709. draw_marching_ants_pixel(painter, x, rect.bottom() - 1);
  710. // Left line
  711. for (int y = rect.bottom() - 2; y > rect.top(); --y)
  712. draw_marching_ants_pixel(painter, rect.left(), y);
  713. }
  714. void ImageEditor::draw_marching_ants(Gfx::Painter& painter, Mask const& mask) const
  715. {
  716. // If the zoom is < 100%, we can skip pixels to save a lot of time drawing the ants
  717. int step = max(1, (int)floorf(1.0f / scale()));
  718. // Only check the visible selection area when drawing for performance
  719. auto rect = this->rect();
  720. rect = Gfx::enclosing_int_rect(frame_to_content_rect(rect));
  721. rect.inflate(step * 2, step * 2); // prevent borders from having visible ants if the selection extends beyond it
  722. // Scan the image horizontally to find vertical borders
  723. for (int y = rect.top(); y < rect.bottom(); y += step) {
  724. bool previous_selected = false;
  725. for (int x = rect.left(); x < rect.right(); x += step) {
  726. bool this_selected = mask.get(x, y) > 0;
  727. if (this_selected != previous_selected) {
  728. Gfx::IntRect image_pixel { x, y, 1, 1 };
  729. auto pixel = content_to_frame_rect(image_pixel).to_type<int>();
  730. auto end = max(pixel.top() + 1, pixel.bottom()); // for when the zoom is < 100%
  731. for (int pixel_y = pixel.top(); pixel_y < end; pixel_y++) {
  732. draw_marching_ants_pixel(painter, pixel.left(), pixel_y);
  733. }
  734. }
  735. previous_selected = this_selected;
  736. }
  737. }
  738. // Scan the image vertically to find horizontal borders
  739. for (int x = rect.left(); x < rect.right(); x += step) {
  740. bool previous_selected = false;
  741. for (int y = rect.top(); y < rect.bottom(); y += step) {
  742. bool this_selected = mask.get(x, y) > 0;
  743. if (this_selected != previous_selected) {
  744. Gfx::IntRect image_pixel { x, y, 1, 1 };
  745. auto pixel = content_to_frame_rect(image_pixel).to_type<int>();
  746. auto end = max(pixel.left() + 1, pixel.right()); // for when the zoom is < 100%
  747. for (int pixel_x = pixel.left(); pixel_x < end; pixel_x++)
  748. draw_marching_ants_pixel(painter, pixel_x, pixel.top());
  749. }
  750. previous_selected = this_selected;
  751. }
  752. }
  753. }
  754. void ImageEditor::draw_marching_ants_pixel(Gfx::Painter& painter, int x, int y) const
  755. {
  756. int pattern_index = x + y + m_marching_ants_offset;
  757. if (pattern_index % (marching_ant_length * 2) < marching_ant_length) {
  758. painter.set_pixel(x, y, Color::Black);
  759. } else {
  760. painter.set_pixel(x, y, Color::White);
  761. }
  762. }
  763. void ImageEditor::selection_did_change()
  764. {
  765. update();
  766. }
  767. void ImageEditor::set_appended_status_info(ByteString new_status_info)
  768. {
  769. m_appended_status_info = new_status_info;
  770. if (on_appended_status_info_change)
  771. on_appended_status_info_change(m_appended_status_info);
  772. }
  773. ByteString ImageEditor::generate_unique_layer_name(ByteString const& original_layer_name)
  774. {
  775. constexpr StringView copy_string_view = " copy"sv;
  776. auto copy_suffix_index = original_layer_name.find_last(copy_string_view);
  777. if (!copy_suffix_index.has_value())
  778. return ByteString::formatted("{}{}", original_layer_name, copy_string_view);
  779. auto after_copy_suffix_view = original_layer_name.substring_view(copy_suffix_index.value() + copy_string_view.length());
  780. if (!after_copy_suffix_view.is_empty()) {
  781. auto after_copy_suffix_number = after_copy_suffix_view.trim_whitespace().to_number<int>();
  782. if (!after_copy_suffix_number.has_value())
  783. return ByteString::formatted("{}{}", original_layer_name, copy_string_view);
  784. }
  785. auto layer_with_name_exists = [this](auto name) {
  786. for (size_t i = 0; i < image().layer_count(); ++i) {
  787. if (image().layer(i).name() == name)
  788. return true;
  789. }
  790. return false;
  791. };
  792. auto base_layer_name = original_layer_name.substring_view(0, copy_suffix_index.value());
  793. StringBuilder new_layer_name;
  794. auto duplicate_name_count = 0;
  795. do {
  796. new_layer_name.clear();
  797. new_layer_name.appendff("{}{} {}", base_layer_name, copy_string_view, ++duplicate_name_count);
  798. } while (layer_with_name_exists(new_layer_name.string_view()));
  799. return new_layer_name.to_byte_string();
  800. }
  801. Gfx::IntRect ImageEditor::active_layer_visible_rect()
  802. {
  803. if (!active_layer())
  804. return {};
  805. auto scaled_layer_rect = active_layer()->relative_rect().to_type<float>().scaled(scale(), scale()).to_type<int>().translated(content_rect().location());
  806. auto visible_editor_rect = ruler_visibility() ? subtract_rulers_from_rect(rect()) : rect();
  807. scaled_layer_rect.intersect(visible_editor_rect);
  808. return scaled_layer_rect;
  809. }
  810. }