ImageEditor.cpp 29 KB

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