Serenity Operating System
1/*
2 * Copyright (c) 2022, Timothy Slater <tslater2006@gmail.com>
3 *
4 * SPDX-License-Identifier: BSD-2-Clause
5 */
6
7#include "TextTool.h"
8#include "../ImageEditor.h"
9#include "../Layer.h"
10#include <LibGUI/Action.h>
11#include <LibGUI/BoxLayout.h>
12#include <LibGUI/Button.h>
13#include <LibGUI/FontPicker.h>
14#include <LibGUI/Label.h>
15#include <LibGUI/Menu.h>
16#include <LibGUI/Painter.h>
17#include <LibGUI/TextBox.h>
18#include <LibGfx/Bitmap.h>
19#include <LibGfx/Palette.h>
20
21namespace PixelPaint {
22
23TextToolEditor::TextToolEditor()
24 : TextEditor(TextEditor::MultiLine)
25{
26}
27
28void TextToolEditor::handle_keyevent(Badge<TextTool>, GUI::KeyEvent& event)
29{
30 TextEditor::keydown_event(event);
31}
32
33Vector<NonnullRefPtr<GUI::Action>> TextToolEditor::actions()
34{
35 static Vector<NonnullRefPtr<GUI::Action>> actions = { cut_action(), copy_action(), paste_action(), undo_action(), redo_action(), select_all_action() };
36 return actions;
37}
38
39TextTool::TextTool()
40{
41 m_text_editor = TextToolEditor::construct();
42 m_text_editor->set_wrapping_mode(GUI::TextEditor::WrappingMode::NoWrap);
43 m_selected_font = Gfx::FontDatabase::default_font();
44 m_text_editor->set_font(m_selected_font);
45 m_cursor_blink_timer = Core::Timer::create_repeating(500, [&]() {
46 m_cursor_blink_state = !m_cursor_blink_state;
47 }).release_value_but_fixme_should_propagate_errors();
48}
49
50void TextTool::on_primary_color_change(Color color)
51{
52 m_text_color = color;
53}
54
55void TextTool::on_tool_deactivation()
56{
57 reset_tool();
58}
59void TextTool::on_mousemove(Layer*, MouseEvent& event)
60{
61 if (m_text_input_is_active) {
62 auto mouse_position = editor_stroke_position(event.layer_event().position(), 1);
63 m_mouse_is_over_text = m_ants_rect.contains(mouse_position);
64 m_editor->update_tool_cursor();
65 }
66
67 if (m_is_dragging) {
68 auto new_position = event.layer_event().position();
69 m_add_text_position = m_add_text_position + (new_position - m_drag_start_point);
70 m_drag_start_point = new_position;
71 }
72}
73void TextTool::on_mouseup(Layer*, MouseEvent&)
74{
75 m_is_dragging = false;
76}
77void TextTool::on_mousedown(Layer*, MouseEvent& event)
78{
79 auto start_text_region = [&] {
80 m_text_color = m_editor->color_for(event.layer_event());
81 m_text_input_is_active = true;
82 m_text_editor->set_text(""sv);
83 m_add_text_position = event.layer_event().position();
84 m_editor->image().selection().begin_interactive_selection();
85 m_cursor_blink_timer->start();
86 m_editor->update();
87 };
88
89 if (!m_text_input_is_active) {
90 start_text_region();
91 return;
92 }
93
94 if (m_mouse_is_over_text) {
95 m_is_dragging = true;
96 m_drag_start_point = event.layer_event().position();
97 } else {
98 // User clicked somewhere outside the currently edited text region
99 // apply the current text and then start a new one where they clicked.
100 apply_text_to_layer();
101 reset_tool();
102 start_text_region();
103 }
104}
105
106ErrorOr<GUI::Widget*> TextTool::get_properties_widget()
107{
108 if (m_properties_widget)
109 return m_properties_widget.ptr();
110
111 auto properties_widget = TRY(GUI::Widget::try_create());
112 (void)TRY(properties_widget->try_set_layout<GUI::VerticalBoxLayout>());
113
114 auto font_header = TRY(properties_widget->try_add<GUI::Label>("Current Font:"));
115 font_header->set_text_alignment(Gfx::TextAlignment::CenterLeft);
116
117 m_font_label = TRY(properties_widget->try_add<GUI::Label>(m_selected_font->human_readable_name()));
118
119 auto change_font_button = TRY(properties_widget->try_add<GUI::Button>(TRY("Change Font..."_string)));
120 change_font_button->on_click = [this](auto) {
121 auto picker = GUI::FontPicker::construct(nullptr, m_selected_font, false);
122 if (picker->exec() == GUI::Dialog::ExecResult::OK) {
123 m_font_label->set_text(picker->font()->human_readable_name());
124 m_selected_font = picker->font();
125 m_text_editor->set_font(m_selected_font);
126 m_editor->set_focus(true);
127 }
128 };
129
130 m_properties_widget = properties_widget;
131 return m_properties_widget.ptr();
132}
133
134void TextTool::on_second_paint(Layer const* layer, GUI::PaintEvent& event)
135{
136 if (!m_text_input_is_active)
137 return;
138
139 GUI::Painter painter(*m_editor);
140 painter.add_clip_rect(event.rect());
141 painter.translate(editor_layer_location(*layer));
142 auto typed_text = m_text_editor->text();
143 auto text_width = max<int>(m_selected_font->width(typed_text), m_selected_font->width(" "sv));
144 auto text_height = static_cast<int>(ceilf(m_selected_font->preferred_line_height() * max<int>(static_cast<int>(m_text_editor->line_count()), 1)));
145 auto text_location = editor_stroke_position(m_add_text_position, 1);
146
147 // Since ImageEditor can be zoomed in/out, we need to be able to render the preview properly scaled
148 // GUI::Painter doesn't have a way to draw a font scaled directly, so we draw the text to a bitmap
149 // and then scale the bitmap and blit the result to the ImageEditor.
150 auto text_bitmap_result = Gfx::Bitmap::create(Gfx::BitmapFormat::BGRA8888, { text_width, text_height });
151 if (text_bitmap_result.is_error())
152 return;
153 auto text_bitmap = text_bitmap_result.release_value();
154 auto text_painter = GUI::Painter(text_bitmap);
155 text_painter.set_font(*m_selected_font);
156 text_painter.draw_text(Gfx::IntRect { 0, 0, text_width, text_height }, typed_text, Gfx::TextAlignment::TopLeft, m_text_color);
157
158 m_text_editor->update();
159
160 // Draw selected text (if any)
161 if (m_text_editor->has_selection()) {
162 auto selection = m_text_editor->selection();
163
164 // Draw selected text for each line...
165 auto selection_start_line = selection.normalized().start().line();
166 auto selection_end_line = selection.normalized().end().line();
167
168 for (auto i = selection_start_line; i <= selection_end_line; ++i) {
169
170 auto start_col = 0;
171 auto end_col = 0;
172
173 // First line of selection.
174 if (i == selection_start_line) {
175
176 if (i < selection_end_line) {
177 // multiple lines selected. we select from selection start to the end of the line
178 start_col = m_text_editor->selection().normalized().start().column();
179 end_col = m_text_editor->line(i).length();
180 } else {
181 // only a single line in the selection
182 start_col = m_text_editor->selection().normalized().start().column();
183 end_col = m_text_editor->selection().normalized().end().column();
184 }
185 } else if (i == selection_end_line) {
186 // We are highlighting the final line of the selection.
187 // Start from first char and continue to selection end.
188 start_col = 0;
189 end_col = m_text_editor->selection().normalized().end().column();
190 } else {
191 // We are between the start and end lines, highlight the whole thing.
192 start_col = 0;
193 end_col = m_text_editor->line(i).length();
194 }
195 auto line_selection_length = end_col - start_col;
196 auto selected_string = m_text_editor->line(i).view().substring_view(start_col, line_selection_length);
197 auto text_before_selection = m_text_editor->line(i).view().substring_view(0, start_col);
198 auto selected_width = m_selected_font->width(selected_string);
199 auto selection_x_offset = m_selected_font->width(text_before_selection);
200
201 // the + 4 here is because that's how Painter::do_draw_text calculates line height, instead of asking
202 // the font it's preferred line height. If we don't replicate that here, the letters jump around when they
203 // get selected.
204 auto selection_y_offset = static_cast<int>((m_selected_font->pixel_size() + 4) * i);
205
206 auto selection_rect = Gfx::IntRect(selection_x_offset, selection_y_offset, selected_width, m_selected_font->preferred_line_height());
207 text_painter.fill_rect(selection_rect, m_text_editor->palette().selection());
208 text_painter.draw_text(selection_rect, selected_string, Gfx::TextAlignment::TopLeft, m_text_editor->palette().selection_text());
209 }
210 }
211
212 auto scaled_width = static_cast<int>(ceilf(m_editor->scale() * static_cast<float>(text_bitmap->width())));
213 auto scaled_height = static_cast<int>(ceilf(m_editor->scale() * static_cast<float>(text_bitmap->height())));
214 auto scaled_rect = Gfx::IntRect(text_location.x(), text_location.y(), scaled_width, scaled_height);
215 scaled_rect.set_location({ text_location.x(), text_location.y() });
216 painter.draw_scaled_bitmap(scaled_rect, text_bitmap, text_bitmap->rect(), 1.0);
217
218 // marching ants box
219 auto right_padding = static_cast<int>(ceilf(m_selected_font->width(" "sv)));
220 m_ants_rect = Gfx::IntRect(text_location.translated(-4, -2), { scaled_rect.width() + 4 + right_padding, scaled_rect.height() + 4 });
221 m_editor->draw_marching_ants(painter, m_ants_rect);
222
223 // Draw the blinking cursor.
224 if (m_cursor_blink_state) {
225 auto editor_cursor_rect = m_text_editor->cursor_content_rect();
226
227 // TextEditor starts left most at 3, for TextTool this ends up putting the cursor in the middle of the letter.
228 // Looks better if we treat 0 as left most here, so we just translate it to the left.
229 editor_cursor_rect.translate_by(-3, 0);
230
231 // ImageEditor scale is a float, but we are working with int and IntRects.
232 auto scaled_cursor_x = static_cast<int>(ceilf(m_editor->scale() * static_cast<float>(editor_cursor_rect.x())));
233 auto scaled_cursor_y = static_cast<int>(ceilf(m_editor->scale() * static_cast<float>(editor_cursor_rect.y())));
234 auto scaled_cursor_width = static_cast<int>(ceilf(m_editor->scale() * static_cast<float>(editor_cursor_rect.width())));
235 auto scaled_cursor_height = static_cast<int>(ceilf(m_editor->scale() * static_cast<float>(editor_cursor_rect.height())));
236
237 auto scaled_cursor_rect = Gfx::IntRect { scaled_cursor_x + text_location.x(),
238 scaled_cursor_y + text_location.y(),
239 scaled_cursor_width,
240 scaled_cursor_height };
241 painter.fill_rect(scaled_cursor_rect, m_text_color);
242 }
243}
244
245void TextTool::apply_text_to_layer()
246{
247 auto layer = m_editor->active_layer();
248 GUI::Painter painter(layer->get_scratch_edited_bitmap());
249
250 auto demo_text = m_text_editor->text();
251 auto text_width = m_selected_font->width(demo_text);
252 auto text_height = static_cast<int>(ceilf(m_selected_font->preferred_line_height() * static_cast<int>(m_text_editor->line_count())));
253
254 painter.set_font(*m_selected_font);
255 auto text_rect = Gfx::Rect<int>(m_add_text_position, { static_cast<int>(ceilf(text_width)), text_height });
256 painter.draw_text(text_rect, demo_text, Gfx::TextAlignment::TopLeft, m_text_color);
257 m_editor->did_complete_action(tool_name());
258 layer->did_modify_bitmap(text_rect);
259}
260void TextTool::reset_tool()
261{
262 // This puts the tool back into initial state between text additions (except for selected font/color)
263 m_text_input_is_active = false;
264 m_is_dragging = false;
265 m_mouse_is_over_text = false;
266 m_text_editor->set_text(""sv);
267 m_editor->image().selection().end_interactive_selection();
268 m_cursor_blink_timer->stop();
269 m_editor->update();
270 m_editor->update_tool_cursor();
271}
272bool TextTool::on_keydown(GUI::KeyEvent& event)
273{
274 if (!m_text_input_is_active)
275 return false;
276
277 // Cancels current text entry
278 if (event.key() == Key_Escape) {
279 reset_tool();
280 return true;
281 }
282
283 // A plain Return is treated as accepting the current state and rasterizing to the layer.
284 // For multi-line text Shift + Enter will add new lines.
285 if (event.modifiers() == Mod_None && event.key() == Key_Return) {
286 apply_text_to_layer();
287 reset_tool();
288 return true;
289 }
290
291 // Pass key events that would normally be handled by menu shortcuts to our TextEditor subclass.
292 for (auto& action : m_text_editor->actions()) {
293 auto const& shortcut = action->shortcut();
294 if (event.key() == shortcut.key() && event.modifiers() == shortcut.modifiers()) {
295 action->activate(m_text_editor);
296 return true;
297 }
298 }
299
300 // Pass the key event off to our TextEditor subclass which handles all text entry features like
301 // caret navigation, backspace/delete, etc.
302 m_text_editor->handle_keyevent({}, event);
303 m_editor->update();
304 return true;
305}
306
307Variant<Gfx::StandardCursor, NonnullRefPtr<Gfx::Bitmap const>> TextTool::cursor()
308{
309 if (m_mouse_is_over_text)
310 return Gfx::StandardCursor::Move;
311
312 return Gfx::StandardCursor::Arrow;
313}
314
315}