1 /*
2  * This source file is part of libRocket, the HTML/CSS Interface Middleware
3  *
4  * For the latest information, see http://www.librocket.com
5  *
6  * Copyright (c) 2008-2010 CodePoint Ltd, Shift Technology Ltd
7  *
8  * Permission is hereby granted, free of charge, to any person obtaining a copy
9  * of this software and associated documentation files (the "Software"), to deal
10  * in the Software without restriction, including without limitation the rights
11  * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12  * copies of the Software, and to permit persons to whom the Software is
13  * furnished to do so, subject to the following conditions:
14  *
15  * The above copyright notice and this permission notice shall be included in
16  * all copies or substantial portions of the Software.
17  *
18  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20  * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21  * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22  * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23  * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24  * THE SOFTWARE.
25  *
26  */
27 
28 #include "WidgetTextInput.h"
29 #include "ElementTextSelection.h"
30 #include "../../Include/Rocket/Core.h"
31 #include "../../Include/Rocket/Controls/ElementFormControl.h"
32 #include "../../Include/Rocket/Controls/Clipboard.h"
33 #include "../../Include/Rocket/Core/SystemInterface.h"
34 
35 namespace Rocket {
36 namespace Controls {
37 
38 const float CURSOR_BLINK_TIME = 0.7f;
39 
WidgetTextInput(ElementFormControl * _parent)40 WidgetTextInput::WidgetTextInput(ElementFormControl* _parent) : internal_dimensions(0, 0), scroll_offset(0, 0), selection_geometry(_parent), cursor_position(0, 0), cursor_size(0, 0), cursor_geometry(_parent)
41 {
42 	keyboard_showed = false;
43 
44 	parent = _parent;
45 	parent->SetProperty("white-space", "pre");
46 	parent->SetProperty("overflow", "hidden");
47 	parent->SetProperty("drag", "drag");
48 	parent->SetClientArea(Rocket::Core::Box::CONTENT);
49 
50 	parent->AddEventListener("resize", this, true);
51 	parent->AddEventListener("keydown", this, true);
52 	parent->AddEventListener("textinput", this, true);
53 	parent->AddEventListener("focus", this, true);
54 	parent->AddEventListener("blur", this, true);
55 	parent->AddEventListener("mousedown", this, true);
56 	parent->AddEventListener("drag", this, true);
57 
58 	text_element = dynamic_cast< Core::ElementText* >(Core::Factory::InstanceElement(parent, "#text", "#text", Rocket::Core::XMLAttributes()));
59 	selected_text_element = dynamic_cast< Core::ElementText* >(Core::Factory::InstanceElement(parent, "#text", "#text", Rocket::Core::XMLAttributes()));
60 	if (text_element != NULL)
61 	{
62 		text_element->SuppressAutoLayout();
63 		parent->AppendChild(text_element, false);
64 		text_element->RemoveReference();
65 
66 		selected_text_element->SuppressAutoLayout();
67 		parent->AppendChild(selected_text_element, false);
68 		selected_text_element->RemoveReference();
69 	}
70 
71 	// Create the dummy selection element.
72 	selection_element = Core::Factory::InstanceElement(parent, "#selection", "selection", Rocket::Core::XMLAttributes());
73 	ElementTextSelection* text_selection_element = dynamic_cast< ElementTextSelection* >(selection_element);
74 	if (text_selection_element != NULL)
75 	{
76 		text_selection_element->SetWidget(this);
77 		parent->AppendChild(text_selection_element, false);
78 		text_selection_element->RemoveReference();
79 	}
80 
81 	edit_index = 0;
82 	absolute_cursor_index = 0;
83 	cursor_line_index = 0;
84 	cursor_character_index = 0;
85 
86 	ideal_cursor_position = 0;
87 
88 	max_length = -1;
89 
90 	selection_anchor_index = 0;
91 	selection_begin_index = 0;
92 	selection_length = 0;
93 
94 	ShowCursor(false);
95 }
96 
~WidgetTextInput()97 WidgetTextInput::~WidgetTextInput()
98 {
99 	parent->RemoveEventListener("resize", this, true);
100 	parent->RemoveEventListener("keydown", this, true);
101 	parent->RemoveEventListener("textinput", this, true);
102 	parent->RemoveEventListener("focus", this, true);
103 	parent->RemoveEventListener("blur", this, true);
104 	parent->RemoveEventListener("mousedown", this, true);
105 	parent->RemoveEventListener("drag", this, true);
106 
107 	// Remove all the children added by the text widget.
108 	parent->RemoveChild(text_element);
109 	parent->RemoveChild(selected_text_element);
110 	parent->RemoveChild(selection_element);
111 }
112 
113 // Sets the value of the text field.
SetValue(const Core::String & value)114 void WidgetTextInput::SetValue(const Core::String& value)
115 {
116 	text_element->SetText(value);
117 	FormatElement();
118 
119 	UpdateRelativeCursor();
120 }
121 
122 // Sets the maximum length (in characters) of this text field.
SetMaxLength(int _max_length)123 void WidgetTextInput::SetMaxLength(int _max_length)
124 {
125 	if (max_length != _max_length)
126 	{
127 		max_length = _max_length;
128 		if (max_length >= 0)
129 		{
130 			const Core::WString& value = GetElement()->GetAttribute< Rocket::Core::String >("value", "");
131 			if ((int) value.Length() > max_length)
132 			{
133 				Rocket::Core::String new_value;
134 				Core::WString(value.CString(), value.CString() + max_length).ToUTF8(new_value);
135 
136 				GetElement()->SetAttribute("value", new_value);
137 			}
138 		}
139 	}
140 }
141 
142 // Returns the maximum length (in characters) of this text field.
GetMaxLength() const143 int WidgetTextInput::GetMaxLength() const
144 {
145 	return max_length;
146 }
147 
148 // Update the colours of the selected text.
UpdateSelectionColours()149 void WidgetTextInput::UpdateSelectionColours()
150 {
151 	// Determine what the colour of the selected text is. If our 'selection' element has the 'color'
152 	// attribute set, then use that. Otherwise, use the inverse of our own text colour.
153 	Rocket::Core::Colourb colour;
154 	const Rocket::Core::Property* colour_property = selection_element->GetLocalProperty("color");
155 	if (colour_property != NULL)
156 		colour = colour_property->Get< Rocket::Core::Colourb >();
157 	else
158 	{
159 		colour = parent->GetProperty< Rocket::Core::Colourb >("color");
160 		colour.red = 255 - colour.red;
161 		colour.green = 255 - colour.green;
162 		colour.blue = 255 - colour.blue;
163 	}
164 
165 	// Set the computed text colour on the element holding the selected text.
166 	selected_text_element->SetProperty("color", Rocket::Core::Property(colour, Rocket::Core::Property::COLOUR));
167 
168 	// If the 'background-color' property has been set on the 'selection' element, use that as the
169 	// background colour for the selected text. Otherwise, use the inverse of the selected text
170 	// colour.
171 	colour_property = selection_element->GetLocalProperty("background-color");
172 	if (colour_property != NULL)
173 		selection_colour = colour_property->Get< Rocket::Core::Colourb >();
174 	else
175 		selection_colour = Rocket::Core::Colourb(255 - colour.red, 255 - colour.green, 255 - colour.blue, colour.alpha);
176 }
177 
178 // Updates the cursor, if necessary.
OnUpdate()179 void WidgetTextInput::OnUpdate()
180 {
181 	if (cursor_timer > 0)
182 	{
183 		float current_time = Core::GetSystemInterface()->GetElapsedTime();
184 		cursor_timer -= (current_time - last_update_time);
185 		last_update_time = current_time;
186 
187 		while (cursor_timer <= 0)
188 		{
189 			cursor_timer += CURSOR_BLINK_TIME;
190 			cursor_visible = !cursor_visible;
191 		}
192 	}
193 }
194 
195 // Renders the cursor, if it is visible.
OnRender()196 void WidgetTextInput::OnRender()
197 {
198 	Core::ElementUtilities::SetClippingRegion(text_element);
199 
200 	Rocket::Core::Vector2f text_translation = parent->GetAbsoluteOffset() - Rocket::Core::Vector2f(parent->GetScrollLeft(), parent->GetScrollTop());
201 	selection_geometry.Render(text_translation);
202 
203 	if (cursor_visible &&
204 		!parent->IsDisabled())
205 	{
206 		cursor_geometry.Render(text_translation + cursor_position);
207 	}
208 }
209 
210 // Formats the widget's internal content.
OnLayout()211 void WidgetTextInput::OnLayout()
212 {
213 	FormatElement();
214 	parent->SetScrollLeft(scroll_offset.x);
215 	parent->SetScrollTop(scroll_offset.y);
216 }
217 
218 // Returns the input element's underlying text element.
GetTextElement()219 Core::ElementText* WidgetTextInput::GetTextElement()
220 {
221 	return text_element;
222 }
223 
224 // Returns the input element's maximum allowed text dimensions.
GetTextDimensions() const225 const Rocket::Core::Vector2f& WidgetTextInput::GetTextDimensions() const
226 {
227 	return internal_dimensions;
228 }
229 
230 // Gets the parent element containing the widget.
GetElement()231 Core::Element* WidgetTextInput::GetElement()
232 {
233 	return parent;
234 }
235 
236 // Dispatches a change event to the widget's element.
DispatchChangeEvent(bool linebreak)237 void WidgetTextInput::DispatchChangeEvent(bool linebreak)
238 {
239 	Rocket::Core::Dictionary parameters;
240 	parameters.Set("value", GetElement()->GetAttribute< Rocket::Core::String >("value", ""));
241 	parameters.Set("linebreak", linebreak);
242 	GetElement()->DispatchEvent("change", parameters);
243 }
244 
245 // Processes the "keydown" and "textinput" event to write to the input field, and the "focus" and "blur" to set
246 // the state of the cursor.
ProcessEvent(Core::Event & event)247 void WidgetTextInput::ProcessEvent(Core::Event& event)
248 {
249 	if (event == "resize")
250 	{
251 		GenerateCursor();
252 
253 		Rocket::Core::Vector2f text_position = parent->GetBox().GetPosition(Core::Box::CONTENT);
254 		text_element->SetOffset(text_position, parent);
255 		selected_text_element->SetOffset(text_position, parent);
256 
257 		Rocket::Core::Vector2f new_internal_dimensions = parent->GetBox().GetSize(Core::Box::CONTENT);
258 		if (new_internal_dimensions != internal_dimensions)
259 		{
260 			internal_dimensions = new_internal_dimensions;
261 
262 			FormatElement();
263 			UpdateCursorPosition();
264 		}
265 	}
266 	else if (parent->IsDisabled())
267 	{
268 		return;
269 	}
270 	else if (event == "keydown")
271 	{
272 		Core::Input::KeyIdentifier key_identifier = (Core::Input::KeyIdentifier) event.GetParameter< int >("key_identifier", 0);
273 		bool numlock = event.GetParameter< int >("num_lock_key", 0) > 0;
274 		bool shift = event.GetParameter< int >("shift_key", 0) > 0;
275         bool ctrl = event.GetParameter< int >("ctrl_key", 0) > 0;
276 
277 		switch (key_identifier)
278 		{
279 			case Core::Input::KI_NUMPAD4:	if (numlock) break;
280 			case Core::Input::KI_LEFT:		MoveCursorHorizontal(-1, shift); break;
281 
282 			case Core::Input::KI_NUMPAD6:	if (numlock) break;
283 			case Core::Input::KI_RIGHT:		MoveCursorHorizontal(1, shift); break;
284 
285 			case Core::Input::KI_NUMPAD8:	if (numlock) break;
286 			case Core::Input::KI_UP:		MoveCursorVertical(-1, shift); break;
287 
288 			case Core::Input::KI_NUMPAD2:	if (numlock) break;
289 			case Core::Input::KI_DOWN:		MoveCursorVertical(1, shift); break;
290 
291 			case Core::Input::KI_NUMPAD7:	if (numlock) break;
292 			case Core::Input::KI_HOME:		MoveCursorHorizontal(-cursor_character_index, shift); break;
293 
294 			case Core::Input::KI_NUMPAD1:	if (numlock) break;
295 			case Core::Input::KI_END:		MoveCursorHorizontal(lines[cursor_line_index].content_length - cursor_character_index, shift); break;
296 
297 			case Core::Input::KI_BACK:
298 			{
299 				if (DeleteCharacter(true))
300 				{
301 					FormatElement();
302 					UpdateRelativeCursor();
303 				}
304 
305 				ShowCursor(true);
306 			}
307 			break;
308 
309 			case Core::Input::KI_DECIMAL:	if (numlock) break;
310 			case Core::Input::KI_DELETE:
311 			{
312 				if (DeleteCharacter(false))
313 				{
314 					FormatElement();
315 					UpdateRelativeCursor();
316 				}
317 
318 				ShowCursor(true);
319 			}
320 			break;
321 
322 			case Core::Input::KI_NUMPADENTER:
323 			case Core::Input::KI_RETURN:
324 			{
325 				LineBreak();
326 			}
327 			break;
328 
329 			case Core::Input::KI_C:
330 			{
331                 if (ctrl)
332                     CopySelection();
333 			}
334 			break;
335 
336 			case Core::Input::KI_X:
337 			{
338                 if (ctrl)
339                 {
340                     CopySelection();
341                     DeleteSelection();
342                 }
343 			}
344 			break;
345 
346 			case Core::Input::KI_V:
347 			{
348                 if (ctrl)
349                 {
350     				const Core::WString clipboard_content = Clipboard::Get();
351     				for (size_t i = 0; i < clipboard_content.Length(); ++i)
352     				{
353     					if (max_length > 0 &&
354     						(int) Core::WString(GetElement()->GetAttribute< Rocket::Core::String >("value", "")).Length() > max_length)
355     						break;
356 
357     					AddCharacter(clipboard_content[i]);
358     				}
359                 }
360 			}
361 			break;
362 
363 			// Ignore tabs so input fields can be navigated through with keys.
364 			case Core::Input::KI_TAB:
365 				return;
366 
367 			default:
368 			{
369 			}
370 			break;
371 		}
372 
373 		event.StopPropagation();
374 	}
375 	else if (event == "textinput")
376 	{
377 		// Only process the text if no modifier keys are pressed.
378 		if (event.GetParameter< int >("ctrl_key", 0) == 0 &&
379 			event.GetParameter< int >("alt_key", 0) == 0 &&
380 			event.GetParameter< int >("meta_key", 0) == 0)
381 		{
382 			Rocket::Core::word character = event.GetParameter< Rocket::Core::word >("data", 0);
383 			if (max_length < 0 || (int) Core::String(GetElement()->GetAttribute< Rocket::Core::String >("value", "")).Length() < max_length)
384 				AddCharacter(character);
385 		}
386 
387 		ShowCursor(true);
388 		event.StopPropagation();
389 	}
390 	else if (event == "focus" &&
391 			 event.GetTargetElement() == parent)
392 	{
393 		UpdateSelection(false);
394 		ShowCursor(true, false);
395 	}
396 	else if (event == "blur" &&
397 		     event.GetTargetElement() == parent)
398 	{
399 		ClearSelection();
400 		ShowCursor(false, false);
401 	}
402 	else if ((event == "mousedown" ||
403 			  event == "drag") &&
404 			 event.GetTargetElement() == parent)
405 	{
406 		Rocket::Core::Vector2f mouse_position = Rocket::Core::Vector2f((float) event.GetParameter< int >("mouse_x", 0),
407 																 (float) event.GetParameter< int >("mouse_y", 0));
408 		mouse_position -= text_element->GetAbsoluteOffset();
409 
410 		cursor_line_index = CalculateLineIndex(mouse_position.y);
411 		cursor_character_index = CalculateCharacterIndex(cursor_line_index, mouse_position.x);
412 
413 		UpdateAbsoluteCursor();
414 		UpdateCursorPosition();
415 		ideal_cursor_position = cursor_position.x;
416 
417 		UpdateSelection(event == "drag" || event.GetParameter< int >("shift_key", 0) > 0);
418 
419 		ShowCursor(true);
420 	}
421 }
422 
423 // Adds a new character to the string at the cursor position.
AddCharacter(Rocket::Core::word character)424 bool WidgetTextInput::AddCharacter(Rocket::Core::word character)
425 {
426 	if (!IsCharacterValid(character))
427 		return false;
428 
429 	if (selection_length > 0)
430 		DeleteSelection();
431 
432 	Core::WString value = GetElement()->GetAttribute< Rocket::Core::String >("value", "");
433 	value.Insert(GetCursorIndex(), Core::WString(1, character), 1);
434 
435 	edit_index += 1;
436 
437 	Rocket::Core::String utf8_value;
438 	value.ToUTF8(utf8_value);
439 	GetElement()->SetAttribute("value", utf8_value);
440 	DispatchChangeEvent();
441 
442 	UpdateSelection(false);
443 
444 	return true;
445 }
446 
447 // Deletes a character from the string.
DeleteCharacter(bool back)448 bool WidgetTextInput::DeleteCharacter(bool back)
449 {
450 	// First, check if we have anything selected; if so, delete that first before we start delete
451 	// individual characters.
452 	if (selection_length > 0)
453 	{
454 		DeleteSelection();
455 		DispatchChangeEvent();
456 
457 		UpdateSelection(false);
458 
459 		return true;
460 	}
461 
462 	Core::WString value = GetElement()->GetAttribute< Rocket::Core::String >("value", "");
463 
464 	if (back)
465 	{
466 		if (GetCursorIndex() == 0)
467 			return false;
468 
469 		value.Erase(GetCursorIndex() - 1, 1);
470 		edit_index -= 1;
471 	}
472 	else
473 	{
474 		if (GetCursorIndex() == (int) value.Length())
475 			return false;
476 
477 		value.Erase(GetCursorIndex(), 1);
478 	}
479 
480 	Rocket::Core::String utf8_value;
481 	value.ToUTF8(utf8_value);
482 	GetElement()->SetAttribute("value", utf8_value);
483 	DispatchChangeEvent();
484 
485 	UpdateSelection(false);
486 
487 	return true;
488 }
489 
490 // Copies the selection (if any) to the clipboard.
CopySelection()491 void WidgetTextInput::CopySelection()
492 {
493 	const Core::String& value = GetElement()->GetAttribute< Rocket::Core::String >("value", "");
494 	Clipboard::Set(Core::String(value.Substring(selection_begin_index, selection_length)));
495 }
496 
497 // Returns the absolute index of the cursor.
GetCursorIndex() const498 int WidgetTextInput::GetCursorIndex() const
499 {
500 	return edit_index;
501 }
502 
503 // Moves the cursor along the current line.
MoveCursorHorizontal(int distance,bool select)504 void WidgetTextInput::MoveCursorHorizontal(int distance, bool select)
505 {
506 	absolute_cursor_index += distance;
507 	absolute_cursor_index = Rocket::Core::Math::Max(0, absolute_cursor_index);
508 
509 	UpdateRelativeCursor();
510 	ideal_cursor_position = cursor_position.x;
511 
512 	UpdateSelection(select);
513 
514 	ShowCursor(true);
515 }
516 
517 // Moves the cursor up and down the text field.
MoveCursorVertical(int distance,bool select)518 void WidgetTextInput::MoveCursorVertical(int distance, bool select)
519 {
520 	bool update_ideal_cursor_position = false;
521 	cursor_line_index += distance;
522 
523 	if (cursor_line_index < 0)
524 	{
525 		cursor_line_index = 0;
526 		cursor_character_index = 0;
527 
528 		update_ideal_cursor_position = true;
529 	}
530 	else if (cursor_line_index >= (int) lines.size())
531 	{
532 		cursor_line_index = (int) lines.size() - 1;
533 		cursor_character_index = (int) lines[cursor_line_index].content_length;
534 
535 		update_ideal_cursor_position = true;
536 	}
537 	else
538 		cursor_character_index = CalculateCharacterIndex(cursor_line_index, ideal_cursor_position);
539 
540 	UpdateAbsoluteCursor();
541 	UpdateCursorPosition();
542 
543 	if (update_ideal_cursor_position)
544 		ideal_cursor_position = cursor_position.x;
545 
546 	UpdateSelection(select);
547 
548 	ShowCursor(true);
549 }
550 
551 // Updates the absolute cursor index from the relative cursor indices.
UpdateAbsoluteCursor()552 void WidgetTextInput::UpdateAbsoluteCursor()
553 {
554 	ROCKET_ASSERT(cursor_line_index < (int) lines.size())
555 
556 	absolute_cursor_index = cursor_character_index;
557 	edit_index = cursor_character_index;
558 
559 	for (int i = 0; i < cursor_line_index; i++)
560 	{
561 		absolute_cursor_index += (int)lines[i].content.Length();
562 		edit_index += (int)lines[i].content.Length() + lines[i].extra_characters;
563 	}
564 }
565 
566 // Updates the relative cursor indices from the absolute cursor index.
UpdateRelativeCursor()567 void WidgetTextInput::UpdateRelativeCursor()
568 {
569 	int num_characters = 0;
570 	edit_index = absolute_cursor_index;
571 
572 	for (size_t i = 0; i < lines.size(); i++)
573 	{
574 		if (num_characters + lines[i].content_length >= absolute_cursor_index)
575 		{
576 			cursor_line_index = (int) i;
577 			cursor_character_index = absolute_cursor_index - num_characters;
578 
579 			UpdateCursorPosition();
580 
581 			return;
582 		}
583 
584 		num_characters += (int) lines[i].content.Length();
585 		edit_index += lines[i].extra_characters;
586 	}
587 
588 	// We shouldn't ever get here; this means we actually couldn't find where the absolute cursor said it was. So we'll
589 	// just set the relative cursors to the very end of the text field, and update the absolute cursor to point here.
590 	cursor_line_index = (int) lines.size() - 1;
591 	cursor_character_index = lines[cursor_line_index].content_length;
592 	absolute_cursor_index = num_characters;
593 	edit_index = num_characters;
594 
595 	UpdateCursorPosition();
596 }
597 
598 // Calculates the line index under a specific vertical position.
CalculateLineIndex(float position)599 int WidgetTextInput::CalculateLineIndex(float position)
600 {
601 	float line_height = (float) Core::ElementUtilities::GetLineHeight(parent);
602 	int line_index = Rocket::Core::Math::RealToInteger(position / line_height);
603 	return Rocket::Core::Math::Clamp(line_index, 0, (int) (lines.size() - 1));
604 }
605 
606 // Calculates the character index along a line under a specific horizontal position.
CalculateCharacterIndex(int line_index,float position)607 int WidgetTextInput::CalculateCharacterIndex(int line_index, float position)
608 {
609 	int character_index = 0;
610 	float line_width = 0;
611 
612 	while (character_index < lines[line_index].content_length)
613 	{
614 		float next_line_width = (float) Core::ElementUtilities::GetStringWidth(text_element, lines[line_index].content.Substring(0, character_index));
615 		if (next_line_width > position)
616 		{
617 			if (position - line_width < next_line_width - position)
618 				return Rocket::Core::Math::Max(0, character_index - 1);
619 			else
620 				return character_index;
621 		}
622 
623 		line_width = next_line_width;
624 		character_index++;
625 	}
626 
627 	return character_index;
628 }
629 
630 // Shows or hides the cursor.
ShowCursor(bool show,bool move_to_cursor)631 void WidgetTextInput::ShowCursor(bool show, bool move_to_cursor)
632 {
633 	if (show)
634 	{
635 		cursor_visible = true;
636 		SetKeyboardActive(true);
637 		keyboard_showed = true;
638 
639 		cursor_timer = CURSOR_BLINK_TIME;
640 		last_update_time = Core::GetSystemInterface()->GetElapsedTime();
641 
642 		// Shift the cursor into view.
643 		if (move_to_cursor)
644 		{
645 			float minimum_scroll_top = (cursor_position.y + cursor_size.y) - parent->GetClientHeight();
646 			if (parent->GetScrollTop() < minimum_scroll_top)
647 				parent->SetScrollTop(minimum_scroll_top);
648 			else if (parent->GetScrollTop() > cursor_position.y)
649 				parent->SetScrollTop(cursor_position.y);
650 
651 			float minimum_scroll_left = (cursor_position.x + cursor_size.x) - parent->GetClientWidth();
652 			if (parent->GetScrollLeft() < minimum_scroll_left)
653 				parent->SetScrollLeft(minimum_scroll_left);
654 			else if (parent->GetScrollLeft() > cursor_position.x)
655 				parent->SetScrollLeft(cursor_position.x);
656 
657 			scroll_offset.x = parent->GetScrollLeft();
658 			scroll_offset.y = parent->GetScrollTop();
659 		}
660 	}
661 	else
662 	{
663 		cursor_visible = false;
664 		cursor_timer = -1;
665 		last_update_time = 0;
666 		if (keyboard_showed)
667 		{
668 			SetKeyboardActive(false);
669 			keyboard_showed = false;
670 		}
671 	}
672 }
673 
674 // Formats the element, laying out the text and inserting scrollbars as appropriate.
FormatElement()675 void WidgetTextInput::FormatElement()
676 {
677 	Core::ElementScroll* scroll = parent->GetElementScroll();
678 	float width = parent->GetBox().GetSize(Core::Box::PADDING).x;
679 
680 	int x_overflow_property = parent->GetProperty< int >("overflow-x");
681 	int y_overflow_property = parent->GetProperty< int >("overflow-y");
682 
683 	if (x_overflow_property == Core::OVERFLOW_SCROLL)
684 		scroll->EnableScrollbar(Core::ElementScroll::HORIZONTAL, width);
685 	else
686 		scroll->DisableScrollbar(Core::ElementScroll::HORIZONTAL);
687 
688 	if (y_overflow_property == Core::OVERFLOW_SCROLL)
689 		scroll->EnableScrollbar(Core::ElementScroll::VERTICAL, width);
690 	else
691 		scroll->DisableScrollbar(Core::ElementScroll::VERTICAL);
692 
693 	// Format the text and determine its total area.
694 	Rocket::Core::Vector2f content_area = FormatText();
695 
696 	// If we're set to automatically generate horizontal scrollbars, check for that now.
697 	if (x_overflow_property == Core::OVERFLOW_AUTO)
698 	{
699 		if (parent->GetClientWidth() < content_area.x)
700 			scroll->EnableScrollbar(Core::ElementScroll::HORIZONTAL, width);
701 	}
702 
703 	// Now check for vertical overflow. If we do turn on the scrollbar, this will cause a reflow.
704 	if (y_overflow_property == Core::OVERFLOW_AUTO)
705 	{
706 		if (parent->GetClientHeight() < content_area.y)
707 		{
708 			scroll->EnableScrollbar(Core::ElementScroll::VERTICAL, width);
709 			content_area = FormatText();
710 
711 			if (x_overflow_property == Core::OVERFLOW_AUTO &&
712 				parent->GetClientWidth() < content_area.y)
713 			{
714 				scroll->EnableScrollbar(Core::ElementScroll::HORIZONTAL, width);
715 			}
716 		}
717 	}
718 
719 	parent->SetContentBox(Rocket::Core::Vector2f(0, 0), content_area);
720 	scroll->FormatScrollbars();
721 }
722 
723 // Formats the input element's text field.
FormatText()724 Rocket::Core::Vector2f WidgetTextInput::FormatText()
725 {
726 	absolute_cursor_index = edit_index;
727 
728 	Rocket::Core::Vector2f content_area(0, 0);
729 
730 	// Clear the old lines, and all the lines in the text elements.
731 	lines.clear();
732 	text_element->ClearLines();
733 	selected_text_element->ClearLines();
734 
735 	// Clear the selection background geometry, and get the vertices and indices so the new geo can
736 	// be generated.
737 	selection_geometry.Release(true);
738 	std::vector< Core::Vertex >& selection_vertices = selection_geometry.GetVertices();
739 	std::vector< int >& selection_indices = selection_geometry.GetIndices();
740 
741 	// Determine the line-height of the text element.
742 	int line_height = Rocket::Core::ElementUtilities::GetLineHeight(parent);
743 
744 	int line_begin = 0;
745 	Rocket::Core::Vector2f line_position(0, 0);
746 	bool last_line = false;
747 
748 	// Keep generating lines until all the text content is placed.
749 	do
750 	{
751 		Line line;
752 		line.extra_characters = 0;
753 		float line_width;
754 
755 		// Generate the next line.
756 		last_line = text_element->GenerateLine(line.content, line.content_length, line_width, line_begin, parent->GetClientWidth() - cursor_size.x, 0, false);
757 
758 		// If this line terminates in a soft-return, then the line may be leaving a space or two behind as an orphan.
759 		// If so, we must append the orphan onto the line even though it will push the line outside of the input
760 		// field's bounds.
761 		bool soft_return = false;
762 		if (!last_line &&
763 			(line.content.Empty() ||
764 			 line.content[line.content.Length() - 1] != '\n'))
765 		{
766 			soft_return = true;
767 
768 			const Core::WString& text = text_element->GetText();
769 			Core::WString orphan;
770 			for (int i = 1; i >= 0; --i)
771 			{
772 				int index = line_begin + line.content_length + i;
773 				if (index >= (int) text.Length())
774 					continue;
775 
776 				if (text[index] != ' ')
777 				{
778 					orphan = "";
779 					continue;
780 				}
781 
782 				int next_index = index + 1;
783 				if (!orphan.Empty() ||
784 					next_index >= (int) text.Length() ||
785 					text[next_index] != ' ')
786 					orphan += ' ';
787 			}
788 
789 			if (!orphan.Empty())
790 			{
791 				line.content += orphan;
792 				line.content_length += (int) orphan.Length();
793 				line_width += Core::ElementUtilities::GetStringWidth(text_element, orphan);
794 			}
795 		}
796 
797 
798 		// Now that we have the string of characters appearing on the new line, we split it into
799 		// three parts; the unselected text appearing before any selected text on the line, the
800 		// selected text on the line, and any unselected text after the selection.
801 		Core::WString pre_selection, selection, post_selection;
802 		GetLineSelection(pre_selection, selection, post_selection, line.content, line_begin);
803 
804 		// The pre-selected text is placed, if there is any (if the selection starts on or before
805 		// the beginning of this line, then this will be empty).
806 		if (!pre_selection.Empty())
807 		{
808 			text_element->AddLine(line_position, pre_selection);
809 			line_position.x += Core::ElementUtilities::GetStringWidth(text_element, pre_selection);
810 		}
811 
812 		// If there is any selected text on this line, place it in the selected text element and
813 		// generate the geometry for its background.
814 		if (!selection.Empty())
815 		{
816 			selected_text_element->AddLine(line_position, selection);
817 			int selection_width = Core::ElementUtilities::GetStringWidth(selected_text_element, selection);
818 
819 			selection_vertices.resize(selection_vertices.size() + 4);
820 			selection_indices.resize(selection_indices.size() + 6);
821 			Core::GeometryUtilities::GenerateQuad(&selection_vertices[selection_vertices.size() - 4], &selection_indices[selection_indices.size() - 6], line_position, Rocket::Core::Vector2f((float)selection_width, (float)line_height), selection_colour, (int)selection_vertices.size() - 4);
822 
823 			line_position.x += selection_width;
824 		}
825 
826 		// If there is any unselected text after the selection on this line, place it in the
827 		// standard text element after the selected text.
828 		if (!post_selection.Empty())
829 			text_element->AddLine(line_position, post_selection);
830 
831 
832 		// Update variables for the next line.
833 		line_begin += line.content_length;
834 		line_position.x = 0;
835 		line_position.y += line_height;
836 
837 		// Grow the content area width-wise if this line is the longest so far, and push the
838 		// height out.
839 		content_area.x = Rocket::Core::Math::Max(content_area.x, line_width + cursor_size.x);
840 		content_area.y = line_position.y;
841 
842 		// Push a trailing '\r' token onto the back to indicate a soft return if necessary.
843 		if (soft_return)
844 		{
845 			line.content += '\r';
846 			line.extra_characters -= 1;
847 
848 			if (edit_index >= line_begin)
849 				absolute_cursor_index += 1;
850 		}
851 
852 		// Push the new line into our array of lines, but first check if its content length needs to be truncated to
853 		// dodge a trailing endline.
854 		if (!line.content.Empty() &&
855 			line.content[line.content.Length() - 1] == '\n')
856 			line.content_length -= 1;
857 		lines.push_back(line);
858 	}
859 	while (!last_line);
860 
861 	return content_area;
862 }
863 
864 // Generates the text cursor.
GenerateCursor()865 void WidgetTextInput::GenerateCursor()
866 {
867 	// Generates the cursor.
868 	cursor_geometry.Release();
869 
870 	std::vector< Core::Vertex >& vertices = cursor_geometry.GetVertices();
871 	vertices.resize(4);
872 
873 	std::vector< int >& indices = cursor_geometry.GetIndices();
874 	indices.resize(6);
875 
876 	cursor_size.x = 1;
877 	cursor_size.y = (float) Core::ElementUtilities::GetLineHeight(text_element) + 2;
878 	Core::GeometryUtilities::GenerateQuad(&vertices[0], &indices[0], Rocket::Core::Vector2f(0, 0), cursor_size, parent->GetProperty< Rocket::Core::Colourb >("color"));
879 }
880 
UpdateCursorPosition()881 void WidgetTextInput::UpdateCursorPosition()
882 {
883 	if (text_element->GetFontFaceHandle() == NULL)
884 		return;
885 
886 	cursor_position.x = (float) Core::ElementUtilities::GetStringWidth(text_element, lines[cursor_line_index].content.Substring(0, cursor_character_index));
887 	cursor_position.y = -1 + cursor_line_index * (float) Core::ElementUtilities::GetLineHeight(text_element);
888 }
889 
890 // Expand the text selection to the position of the cursor.
UpdateSelection(bool selecting)891 void WidgetTextInput::UpdateSelection(bool selecting)
892 {
893 	if (!selecting)
894 	{
895 		selection_anchor_index = edit_index;
896 		ClearSelection();
897 	}
898 	else
899 	{
900 		int new_begin_index;
901 		int new_end_index;
902 
903 		if (edit_index > selection_anchor_index)
904 		{
905 			new_begin_index = selection_anchor_index;
906 			new_end_index = edit_index;
907 		}
908 		else
909 		{
910 			new_begin_index = edit_index;
911 			new_end_index = selection_anchor_index;
912 		}
913 
914 		if (new_begin_index != selection_begin_index ||
915 			new_end_index - new_begin_index != selection_length)
916 		{
917 			selection_begin_index = new_begin_index;
918 			selection_length = new_end_index - new_begin_index;
919 
920 			FormatText();
921 		}
922 	}
923 }
924 
925 // Removes the selection of text.
ClearSelection()926 void WidgetTextInput::ClearSelection()
927 {
928 	if (selection_length > 0)
929 	{
930 		selection_length = 0;
931 		FormatElement();
932 	}
933 }
934 
935 // Deletes all selected text and removes the selection.
DeleteSelection()936 void WidgetTextInput::DeleteSelection()
937 {
938 	if (selection_length > 0)
939 	{
940 		const Core::WString& value = GetElement()->GetAttribute< Rocket::Core::String >("value", "");
941 
942 		Rocket::Core::String new_value;
943 		Core::WString(value.Substring(0, selection_begin_index) + value.Substring(selection_begin_index + selection_length)).ToUTF8(new_value);
944 		GetElement()->SetAttribute("value", new_value);
945 
946 		// Move the cursor to the beginning of the old selection.
947 		absolute_cursor_index = selection_begin_index;
948 		UpdateRelativeCursor();
949 
950 		// Erase our record of the selection.
951 		ClearSelection();
952 	}
953 }
954 
955 // Split one line of text into three parts, based on the current selection.
GetLineSelection(Core::WString & pre_selection,Core::WString & selection,Core::WString & post_selection,const Core::WString & line,int line_begin)956 void WidgetTextInput::GetLineSelection(Core::WString& pre_selection, Core::WString& selection, Core::WString& post_selection, const Core::WString& line, int line_begin)
957 {
958 	// Check if we have any selection at all, and if so if the selection is on this line.
959 	if (selection_length <= 0 ||
960 		selection_begin_index + selection_length < line_begin ||
961 		selection_begin_index > line_begin + (int) line.Length())
962 	{
963 		pre_selection = line;
964 		return;
965 	}
966 
967 	// Split the line up into its three parts, depending on the size and placement of the selection.
968 	pre_selection = line.Substring(0, Rocket::Core::Math::Max(0, selection_begin_index - line_begin));
969 	selection = line.Substring(Rocket::Core::Math::Max(0, selection_begin_index - line_begin), Rocket::Core::Math::Max(0, selection_length + Rocket::Core::Math::Min(0, selection_begin_index - line_begin)));
970 	post_selection = line.Substring(selection_begin_index + selection_length - line_begin);
971 }
972 
SetKeyboardActive(bool active)973 void WidgetTextInput::SetKeyboardActive(bool active)
974 {
975 	Core::SystemInterface* system = Core::GetSystemInterface();
976 	if (system) {
977 		if (active)
978 		{
979 			system->ActivateKeyboard();
980 		} else
981 		{
982 			system->DeactivateKeyboard();
983 		}
984 	}
985 }
986 
987 }
988 }
989