ImageEditor.cpp 30 KB

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