aboutsummaryrefslogtreecommitdiff
path: root/src/script/lua_api
Commit message (Expand)AuthorAge
...
* Add minetest.set_noiseparam_defaults() Lua APIkwolekr2014-02-15
* Add capability to read table flag fields from Lua APIkwolekr2014-02-09
* Make flag strings clear specified flag with 'no' prefixkwolekr2014-02-08
* Fix invalid check for fread error on extracting zipsapier2014-02-07
* Huge overhaul of the entire MapgenParams systemkwolekr2014-02-03
* Add minetest.kick_player(name, reason)sapier2014-02-03
* Add player:override_day_night_ratio() for arbitrarily controlling sunlight br...Perttu Ahola2014-02-01
* Add player:set_sky() with simple skybox supportPerttu Ahola2014-02-01
* New HUD element - waypoint.RealBadAngel2014-01-26
* Pass pointed_thing to on_punch and minetest.register_on_punchnode callbacksShadowNinja2014-01-23
* LuaVoxelManip: Add get_param2_data and set_param2_datakwolekr2014-01-19
* Add formspec tableKahrl2014-01-13
* Allow vertical axis particle rotation constraintkhonkhortisan2014-01-13
* Fix some errors reported by clang static analyzer.Ilya Zhuravlev2014-01-13
* Rename get_json_value to read_json_valueShadowNinja2014-01-11
* Add InvRef::get/set_lists()ShadowNinja2014-01-11
* Add forceloadingNovatux2014-01-11
* Fix absence of images when compiled with RUN_IN_PLACE=0.Ilya Zhuravlev2014-01-05
* Fix enum element name in Lua HUD code (position vs. pos)kaeza2013-12-31
* Bugfix to get_all_craft_recipes.RealBadAngel2013-12-21
* Don't throw a error when writing JSON failsShadowNinja2013-12-18
* Add 'minetest.write_json'ShadowNinja2013-12-18
* Handle LuaErrors in Lua -> C++ calls on LuaJITShadowNinja2013-12-18
* Add map feature generation notify Lua APIkwolekr2013-12-14
* Make line_of_sight return blocking node positionstujones112013-12-12
* Implement search tab and version pickersapier2013-12-11
* Fix leak and possible segfault in minetest.set_mapgen_paramskwolekr2013-12-08
* Use a table in set_physics_override()PilzAdam2013-12-03
* Add sneak and sneak_glitch to set_physics_override()PilzAdam2013-12-03
* Fix broken async locking in release buildsapier2013-12-03
* Fix MinGW buildSfan52013-12-01
* Cleanup jthread and fix win32 buildsapier2013-12-01
* Decoration: Add schematic Y-slice probability supportkwolekr2013-12-01
* Add error handler to async stepShadowNinja2013-11-30
* Optimize table creationShadowNinja2013-11-30
* Add minetest.swap_nodeNovatux2013-11-30
* Fix MSVC build.Ilya Zhuravlev2013-11-30
* LuaVoxelManip: Add area parameters back to calc_lighting and set_lighting, ma...kwolekr2013-11-30
* LuaVoxelManip: Add get_light_data() and set_light_data()kwolekr2013-11-30
* Fixed potential NULL pointer and leak when setting node metadataMetaDucky2013-11-29
* Fix broken thread stop handlingsapier2013-11-30
* Fix old gcc buildsapier2013-11-29
* Fix modstore/favourites hang by adding asynchronous lua job supportsapier2013-11-29
* Rollback fixes and get_node_actionsShadowNinja2013-11-27
* Fix line_of_sight (AGAIN)sapier2013-11-25
* LuaVoxelManip: Update parameter index of set_lighting()kwolekr2013-11-21
* Fix issue #1009 (minetest.get_connected_players() returns non-existing players)kwolekr2013-11-17
* Decoration: Stop DecoSimple::resolveNodeNames from complaining about no node ...kwolekr2013-11-17
* Fix invalid listname and listsize not handled correctly in set_sizesapier2013-11-16
* Pass a errfunc to lua_pcall to get a tracebackShadowNinja2013-11-15
ef='#n458'>458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911
/*
Minetest
Copyright (C) 2021 Minetest

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published by
the Free Software Foundation; either version 2.1 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/

#include "guiEditBox.h"

#include "IGUISkin.h"
#include "IGUIEnvironment.h"
#include "IGUIFont.h"

#include "porting.h"

GUIEditBox::~GUIEditBox()
{
	if (m_override_font)
		m_override_font->drop();

	if (m_operator)
		m_operator->drop();

	if (m_vscrollbar)
		m_vscrollbar->drop();
}

void GUIEditBox::setOverrideFont(IGUIFont *font)
{
	if (m_override_font == font)
		return;

	if (m_override_font)
		m_override_font->drop();

	m_override_font = font;

	if (m_override_font)
		m_override_font->grab();

	breakText();
}

//! Get the font which is used right now for drawing
IGUIFont *GUIEditBox::getActiveFont() const
{
	if (m_override_font)
		return m_override_font;
	IGUISkin *skin = Environment->getSkin();
	if (skin)
		return skin->getFont();
	return 0;
}

//! Sets another color for the text.
void GUIEditBox::setOverrideColor(video::SColor color)
{
	m_override_color = color;
	m_override_color_enabled = true;
}

video::SColor GUIEditBox::getOverrideColor() const
{
	return m_override_color;
}

//! Sets if the text should use the overide color or the color in the gui skin.
void GUIEditBox::enableOverrideColor(bool enable)
{
	m_override_color_enabled = enable;
}

//! Enables or disables word wrap
void GUIEditBox::setWordWrap(bool enable)
{
	m_word_wrap = enable;
	breakText();
}

//! Enables or disables newlines.
void GUIEditBox::setMultiLine(bool enable)
{
	m_multiline = enable;
}

//! Enables or disables automatic scrolling with cursor position
//! \param enable: If set to true, the text will move around with the cursor position
void GUIEditBox::setAutoScroll(bool enable)
{
	m_autoscroll = enable;
}

void GUIEditBox::setPasswordBox(bool password_box, wchar_t password_char)
{
	m_passwordbox = password_box;
	if (m_passwordbox) {
		m_passwordchar = password_char;
		setMultiLine(false);
		setWordWrap(false);
		m_broken_text.clear();
	}
}

//! Sets text justification
void GUIEditBox::setTextAlignment(EGUI_ALIGNMENT horizontal, EGUI_ALIGNMENT vertical)
{
	m_halign = horizontal;
	m_valign = vertical;
}

//! Sets the new caption of this element.
void GUIEditBox::setText(const wchar_t *text)
{
	Text = text;
	if (u32(m_cursor_pos) > Text.size())
		m_cursor_pos = Text.size();
	m_hscroll_pos = 0;
	breakText();
}

//! Sets the maximum amount of characters which may be entered in the box.
//! \param max: Maximum amount of characters. If 0, the character amount is
//! infinity.
void GUIEditBox::setMax(u32 max)
{
	m_max = max;

	if (Text.size() > m_max && m_max != 0)
		Text = Text.subString(0, m_max);
}

//! Gets the area of the text in the edit box
//! \return Returns the size in pixels of the text
core::dimension2du GUIEditBox::getTextDimension()
{
	core::rect<s32> ret;

	setTextRect(0);
	ret = m_current_text_rect;

	for (u32 i = 1; i < m_broken_text.size(); ++i) {
		setTextRect(i);
		ret.addInternalPoint(m_current_text_rect.UpperLeftCorner);
		ret.addInternalPoint(m_current_text_rect.LowerRightCorner);
	}

	return core::dimension2du(ret.getSize());
}

//! Turns the border on or off
void GUIEditBox::setDrawBorder(bool border)
{
	m_border = border;
}

void GUIEditBox::setWritable(bool can_write_text)
{
	m_writable = can_write_text;
}

//! set text markers
void GUIEditBox::setTextMarkers(s32 begin, s32 end)
{
	if (begin != m_mark_begin || end != m_mark_end) {
		m_mark_begin = begin;
		m_mark_end = end;
		sendGuiEvent(EGET_EDITBOX_MARKING_CHANGED);
	}
}

//! send some gui event to parent
void GUIEditBox::sendGuiEvent(EGUI_EVENT_TYPE type)
{
	if (Parent) {
		SEvent e;
		e.EventType = EET_GUI_EVENT;
		e.GUIEvent.Caller = this;
		e.GUIEvent.Element = 0;
		e.GUIEvent.EventType = type;

		Parent->OnEvent(e);
	}
}

//! called if an event happened.
bool GUIEditBox::OnEvent(const SEvent &event)
{
	if (isEnabled()) {

		switch (event.EventType) {
		case EET_GUI_EVENT:
			if (event.GUIEvent.EventType == EGET_ELEMENT_FOCUS_LOST) {
				if (event.GUIEvent.Caller == this) {
					m_mouse_marking = false;
					setTextMarkers(0, 0);
				}
			}
			break;
		case EET_KEY_INPUT_EVENT: {
#if (defined(__linux__) || defined(__FreeBSD__)) || defined(__DragonFly__)
			// ################################################################
			// ValkaTR:
			// This part is the difference from the original intlGUIEditBox
			// It converts UTF-8 character into a UCS-2 (wchar_t)
			wchar_t wc = L'_';
			mbtowc(&wc, (char *)&event.KeyInput.Char,
					sizeof(event.KeyInput.Char));

			// printf( "char: %lc (%u)  \r\n", wc, wc );

			SEvent irrevent(event);
			irrevent.KeyInput.Char = wc;
			// ################################################################

			if (processKey(irrevent))
				return true;
#else
			if (processKey(event))
				return true;
#endif // defined(linux)

			break;
		}
		case EET_MOUSE_INPUT_EVENT:
			if (processMouse(event))
				return true;
			break;
		default:
			break;
		}
	}

	return IGUIElement::OnEvent(event);
}

bool GUIEditBox::processKey(const SEvent &event)
{
	if (!m_writable) {
		return false;
	}

	if (!event.KeyInput.PressedDown)
		return false;

	bool text_changed = false;
	s32 new_mark_begin = m_mark_begin;
	s32 new_mark_end = m_mark_end;

	// control shortcut handling
	if (event.KeyInput.Control) {

		// german backlash '\' entered with control + '?'
		if (event.KeyInput.Char == '\\') {
			inputChar(event.KeyInput.Char);
			return true;
		}

		switch (event.KeyInput.Key) {
		case KEY_KEY_A:
			// select all
			new_mark_begin = 0;
			new_mark_end = Text.size();
			break;
		case KEY_KEY_C:
			onKeyControlC(event);
			break;
		case KEY_KEY_X:
			text_changed = onKeyControlX(event, new_mark_begin, new_mark_end);
			break;
		case KEY_KEY_V:
			text_changed = onKeyControlV(event, new_mark_begin, new_mark_end);
			break;
		case KEY_HOME:
			// move/highlight to start of text
			if (event.KeyInput.Shift) {
				new_mark_end = m_cursor_pos;
				new_mark_begin = 0;
				m_cursor_pos = 0;
			} else {
				m_cursor_pos = 0;
				new_mark_begin = 0;
				new_mark_end = 0;
			}
			break;
		case KEY_END:
			// move/highlight to end of text
			if (event.KeyInput.Shift) {
				new_mark_begin = m_cursor_pos;
				new_mark_end = Text.size();
				m_cursor_pos = 0;
			} else {
				m_cursor_pos = Text.size();
				new_mark_begin = 0;
				new_mark_end = 0;
			}
			break;
		default:
			return false;
		}
	} else {
		switch (event.KeyInput.Key) {
		case KEY_END: {
			s32 p = Text.size();
			if (m_word_wrap || m_multiline) {
				p = getLineFromPos(m_cursor_pos);
				p = m_broken_text_positions[p] +
				    (s32)m_broken_text[p].size();
				if (p > 0 && (Text[p - 1] == L'\r' ||
							     Text[p - 1] == L'\n'))
					p -= 1;
			}

			if (event.KeyInput.Shift) {
				if (m_mark_begin == m_mark_end)
					new_mark_begin = m_cursor_pos;

				new_mark_end = p;
			} else {
				new_mark_begin = 0;
				new_mark_end = 0;
			}
			m_cursor_pos = p;
			m_blink_start_time = porting::getTimeMs();
		} break;
		case KEY_HOME: {

			s32 p = 0;
			if (m_word_wrap || m_multiline) {
				p = getLineFromPos(m_cursor_pos);
				p = m_broken_text_positions[p];
			}

			if (event.KeyInput.Shift) {
				if (m_mark_begin == m_mark_end)
					new_mark_begin = m_cursor_pos;
				new_mark_end = p;
			} else {
				new_mark_begin = 0;
				new_mark_end = 0;
			}
			m_cursor_pos = p;
			m_blink_start_time = porting::getTimeMs();
		} break;
		case KEY_RETURN:
			if (m_multiline) {
				inputChar(L'\n');
			} else {
				calculateScrollPos();
				sendGuiEvent(EGET_EDITBOX_ENTER);
			}
			return true;
		case KEY_LEFT:
			if (event.KeyInput.Shift) {
				if (m_cursor_pos > 0) {
					if (m_mark_begin == m_mark_end)
						new_mark_begin = m_cursor_pos;

					new_mark_end = m_cursor_pos - 1;
				}
			} else {
				new_mark_begin = 0;
				new_mark_end = 0;
			}

			if (m_cursor_pos > 0)
				m_cursor_pos--;
			m_blink_start_time = porting::getTimeMs();
			break;
		case KEY_RIGHT:
			if (event.KeyInput.Shift) {
				if (Text.size() > (u32)m_cursor_pos) {
					if (m_mark_begin == m_mark_end)
						new_mark_begin = m_cursor_pos;

					new_mark_end = m_cursor_pos + 1;
				}
			} else {
				new_mark_begin = 0;
				new_mark_end = 0;
			}

			if (Text.size() > (u32)m_cursor_pos)
				m_cursor_pos++;
			m_blink_start_time = porting::getTimeMs();
			break;
		case KEY_UP:
			if (!onKeyUp(event, new_mark_begin, new_mark_end)) {
				return false;
			}
			break;
		case KEY_DOWN:
			if (!onKeyDown(event, new_mark_begin, new_mark_end)) {
				return false;
			}
			break;
		case KEY_BACK:
			text_changed = onKeyBack(event, new_mark_begin, new_mark_end);
			break;

		case KEY_DELETE:
			text_changed = onKeyDelete(event, new_mark_begin, new_mark_end);
			break;

		case KEY_ESCAPE:
		case KEY_TAB:
		case KEY_SHIFT:
		case KEY_F1:
		case KEY_F2:
		case KEY_F3:
		case KEY_F4:
		case KEY_F5:
		case KEY_F6:
		case KEY_F7:
		case KEY_F8:
		case KEY_F9:
		case KEY_F10:
		case KEY_F11:
		case KEY_F12:
		case KEY_F13:
		case KEY_F14:
		case KEY_F15:
		case KEY_F16:
		case KEY_F17:
		case KEY_F18:
		case KEY_F19:
		case KEY_F20:
		case KEY_F21:
		case KEY_F22:
		case KEY_F23:
		case KEY_F24:
			// ignore these keys
			return false;

		default:
			inputChar(event.KeyInput.Char);
			return true;
		}
	}

	// Set new text markers
	setTextMarkers(new_mark_begin, new_mark_end);

	// break the text if it has changed
	if (text_changed) {
		breakText();
		sendGuiEvent(EGET_EDITBOX_CHANGED);
	}

	calculateScrollPos();

	return true;
}

bool GUIEditBox::onKeyUp(const SEvent &event, s32 &mark_begin, s32 &mark_end)
{
	// clang-format off
	if (m_multiline || (m_word_wrap && m_broken_text.size() > 1)) {
		s32 lineNo = getLineFromPos(m_cursor_pos);
		s32 mb = (m_mark_begin == m_mark_end) ? m_cursor_pos :
			(m_mark_begin > m_mark_end ? m_mark_begin : m_mark_end);
		if (lineNo > 0) {
			s32 cp = m_cursor_pos - m_broken_text_positions[lineNo];
			if ((s32)m_broken_text[lineNo - 1].size() < cp) {
				m_cursor_pos = m_broken_text_positions[lineNo - 1] +
					core::max_((u32)1, m_broken_text[lineNo - 1].size()) - 1;
			}
			else
				m_cursor_pos = m_broken_text_positions[lineNo - 1] + cp;
		}

		if (event.KeyInput.Shift) {
			mark_begin = mb;
			mark_end = m_cursor_pos;
		} else {
			mark_begin = 0;
			mark_end = 0;
		}

		return true;
	}

	// clang-format on
	return false;
}

bool GUIEditBox::onKeyDown(const SEvent &event, s32 &mark_begin, s32 &mark_end)
{
	// clang-format off
	if (m_multiline || (m_word_wrap && m_broken_text.size() > 1)) {
		s32 lineNo = getLineFromPos(m_cursor_pos);
		s32 mb = (m_mark_begin == m_mark_end) ? m_cursor_pos :
			(m_mark_begin < m_mark_end ? m_mark_begin : m_mark_end);
		if (lineNo < (s32)m_broken_text.size() - 1) {
			s32 cp = m_cursor_pos - m_broken_text_positions[lineNo];
			if ((s32)m_broken_text[lineNo + 1].size() < cp) {
				m_cursor_pos = m_broken_text_positions[lineNo + 1] +
					core::max_((u32)1, m_broken_text[lineNo + 1].size()) - 1;
			}
			else
				m_cursor_pos = m_broken_text_positions[lineNo + 1] + cp;
		}

		if (event.KeyInput.Shift) {
			mark_begin = mb;
			mark_end = m_cursor_pos;
		} else {
			mark_begin = 0;
			mark_end = 0;
		}

		return true;
	}

	// clang-format on
	return false;
}

void GUIEditBox::onKeyControlC(const SEvent &event)
{
	// copy to clipboard
	if (m_passwordbox || !m_operator || m_mark_begin == m_mark_end)
		return;

	const s32 realmbgn = m_mark_begin < m_mark_end ? m_mark_begin : m_mark_end;
	const s32 realmend = m_mark_begin < m_mark_end ? m_mark_end : m_mark_begin;

	core::stringc s;
	s = Text.subString(realmbgn, realmend - realmbgn).c_str();
	m_operator->copyToClipboard(s.c_str());
}

bool GUIEditBox::onKeyControlX(const SEvent &event, s32 &mark_begin, s32 &mark_end)
{
	// First copy to clipboard
	onKeyControlC(event);

	if (m_passwordbox || !m_operator || m_mark_begin == m_mark_end)
		return false;

	const s32 realmbgn = m_mark_begin < m_mark_end ? m_mark_begin : m_mark_end;
	const s32 realmend = m_mark_begin < m_mark_end ? m_mark_end : m_mark_begin;

	// Now remove from box if enabled
	if (isEnabled()) {
		// delete
		core::stringw s;
		s = Text.subString(0, realmbgn);
		s.append(Text.subString(realmend, Text.size() - realmend));
		Text = s;

		m_cursor_pos = realmbgn;
		mark_begin = 0;
		mark_end = 0;
		return true;
	}

	return false;
}

bool GUIEditBox::onKeyControlV(const SEvent &event, s32 &mark_begin, s32 &mark_end)
{
	if (!isEnabled())
		return false;

	// paste from the clipboard
	if (!m_operator)
		return false;

	const s32 realmbgn = m_mark_begin < m_mark_end ? m_mark_begin : m_mark_end;
	const s32 realmend = m_mark_begin < m_mark_end ? m_mark_end : m_mark_begin;

	// add new character
	if (const c8 *p = m_operator->getTextFromClipboard()) {
		if (m_mark_begin == m_mark_end) {
			// insert text
			core::stringw s = Text.subString(0, m_cursor_pos);
			s.append(p);
			s.append(Text.subString(
					m_cursor_pos, Text.size() - m_cursor_pos));

			if (!m_max || s.size() <= m_max) {
				Text = s;
				s = p;
				m_cursor_pos += s.size();
			}
		} else {
			// replace text

			core::stringw s = Text.subString(0, realmbgn);
			s.append(p);
			s.append(Text.subString(realmend, Text.size() - realmend));

			if (!m_max || s.size() <= m_max) {
				Text = s;
				s = p;
				m_cursor_pos = realmbgn + s.size();
			}
		}
	}

	mark_begin = 0;
	mark_end = 0;
	return true;
}

bool GUIEditBox::onKeyBack(const SEvent &event, s32 &mark_begin, s32 &mark_end)
{
	if (!isEnabled() || Text.empty())
		return false;

	core::stringw s;

	if (m_mark_begin != m_mark_end) {
		// delete marked text
		const s32 realmbgn =
				m_mark_begin < m_mark_end ? m_mark_begin : m_mark_end;
		const s32 realmend =
				m_mark_begin < m_mark_end ? m_mark_end : m_mark_begin;

		s = Text.subString(0, realmbgn);
		s.append(Text.subString(realmend, Text.size() - realmend));
		Text = s;

		m_cursor_pos = realmbgn;
	} else {
		// delete text behind cursor
		if (m_cursor_pos > 0)
			s = Text.subString(0, m_cursor_pos - 1);
		else
			s = L"";
		s.append(Text.subString(m_cursor_pos, Text.size() - m_cursor_pos));
		Text = s;
		--m_cursor_pos;
	}

	if (m_cursor_pos < 0)
		m_cursor_pos = 0;
	m_blink_start_time = porting::getTimeMs(); // os::Timer::getTime();
	mark_begin = 0;
	mark_end = 0;
	return true;
}

bool GUIEditBox::onKeyDelete(const SEvent &event, s32 &mark_begin, s32 &mark_end)
{
	if (!isEnabled() || Text.empty())
		return false;

	core::stringw s;

	if (m_mark_begin != m_mark_end) {
		// delete marked text
		const s32 realmbgn =
				m_mark_begin < m_mark_end ? m_mark_begin : m_mark_end;
		const s32 realmend =
				m_mark_begin < m_mark_end ? m_mark_end : m_mark_begin;

		s = Text.subString(0, realmbgn);
		s.append(Text.subString(realmend, Text.size() - realmend));
		Text = s;

		m_cursor_pos = realmbgn;
	} else {
		// delete text before cursor
		s = Text.subString(0, m_cursor_pos);
		s.append(Text.subString(
				m_cursor_pos + 1, Text.size() - m_cursor_pos - 1));
		Text = s;
	}

	if (m_cursor_pos > (s32)Text.size())
		m_cursor_pos = (s32)Text.size();

	m_blink_start_time = porting::getTimeMs(); // os::Timer::getTime();
	mark_begin = 0;
	mark_end = 0;
	return true;
}

void GUIEditBox::inputChar(wchar_t c)
{
	if (!isEnabled() || !m_writable)
		return;

	if (c != 0) {
		if (Text.size() < m_max || m_max == 0) {
			core::stringw s;

			if (m_mark_begin != m_mark_end) {
				// clang-format off
				// replace marked text
				s32 real_begin = m_mark_begin < m_mark_end ? m_mark_begin : m_mark_end;
				s32 real_end = m_mark_begin < m_mark_end ? m_mark_end : m_mark_begin;

				s = Text.subString(0, real_begin);
				s.append(c);
				s.append(Text.subString(real_end, Text.size() - real_end));
				Text = s;
				m_cursor_pos = real_begin + 1;
				// clang-format on
			} else {
				// add new character
				s = Text.subString(0, m_cursor_pos);
				s.append(c);
				s.append(Text.subString(m_cursor_pos,
						Text.size() - m_cursor_pos));
				Text = s;
				++m_cursor_pos;
			}

			m_blink_start_time = porting::getTimeMs();
			setTextMarkers(0, 0);
		}
	}
	breakText();
	sendGuiEvent(EGET_EDITBOX_CHANGED);
	calculateScrollPos();
}

bool GUIEditBox::processMouse(const SEvent &event)
{
	switch (event.MouseInput.Event) {
	case irr::EMIE_LMOUSE_LEFT_UP:
		if (Environment->hasFocus(this)) {
			m_cursor_pos = getCursorPos(
					event.MouseInput.X, event.MouseInput.Y);
			if (m_mouse_marking) {
				setTextMarkers(m_mark_begin, m_cursor_pos);
			}
			m_mouse_marking = false;
			calculateScrollPos();
			return true;
		}
		break;
	case irr::EMIE_MOUSE_MOVED: {
		if (m_mouse_marking) {
			m_cursor_pos = getCursorPos(
					event.MouseInput.X, event.MouseInput.Y);
			setTextMarkers(m_mark_begin, m_cursor_pos);
			calculateScrollPos();
			return true;
		}
	} break;
	case EMIE_LMOUSE_PRESSED_DOWN:

		if (!Environment->hasFocus(this)) {
			m_blink_start_time = porting::getTimeMs();
			m_mouse_marking = true;
			m_cursor_pos = getCursorPos(
					event.MouseInput.X, event.MouseInput.Y);
			setTextMarkers(m_cursor_pos, m_cursor_pos);
			calculateScrollPos();
			return true;
		} else {
			if (!AbsoluteClippingRect.isPointInside(core::position2d<s32>(
					    event.MouseInput.X, event.MouseInput.Y))) {
				return false;
			} else {
				// move cursor
				m_cursor_pos = getCursorPos(
						event.MouseInput.X, event.MouseInput.Y);

				s32 newMarkBegin = m_mark_begin;
				if (!m_mouse_marking)
					newMarkBegin = m_cursor_pos;

				m_mouse_marking = true;
				setTextMarkers(newMarkBegin, m_cursor_pos);
				calculateScrollPos();
				return true;
			}
		}
	case EMIE_MOUSE_WHEEL:
		if (m_vscrollbar && m_vscrollbar->isVisible()) {
			s32 pos = m_vscrollbar->getPos();
			s32 step = m_vscrollbar->getSmallStep();
			m_vscrollbar->setPos(pos - event.MouseInput.Wheel * step);
			return true;
		}
		break;
	default:
		break;
	}

	return false;
}

s32 GUIEditBox::getLineFromPos(s32 pos)
{
	if (!m_word_wrap && !m_multiline)
		return 0;

	s32 i = 0;
	while (i < (s32)m_broken_text_positions.size()) {
		if (m_broken_text_positions[i] > pos)
			return i - 1;
		++i;
	}
	return (s32)m_broken_text_positions.size() - 1;
}

void GUIEditBox::updateVScrollBar()
{
	if (!m_vscrollbar) {
		return;
	}

	// OnScrollBarChanged(...)
	if (m_vscrollbar->getPos() != m_vscroll_pos) {
		s32 deltaScrollY = m_vscrollbar->getPos() - m_vscroll_pos;
		m_current_text_rect.UpperLeftCorner.Y -= deltaScrollY;
		m_current_text_rect.LowerRightCorner.Y -= deltaScrollY;

		s32 scrollymax = getTextDimension().Height - m_frame_rect.getHeight();
		if (scrollymax != m_vscrollbar->getMax()) {
			// manage a newline or a deleted line
			m_vscrollbar->setMax(scrollymax);
			m_vscrollbar->setPageSize(s32(getTextDimension().Height));
			calculateScrollPos();
		} else {
			// manage a newline or a deleted line
			m_vscroll_pos = m_vscrollbar->getPos();
		}
	}

	// check if a vertical scrollbar is needed ?
	if (getTextDimension().Height > (u32)m_frame_rect.getHeight()) {
		m_frame_rect.LowerRightCorner.X -= m_scrollbar_width;

		s32 scrollymax = getTextDimension().Height - m_frame_rect.getHeight();
		if (scrollymax != m_vscrollbar->getMax()) {
			m_vscrollbar->setMax(scrollymax);
			m_vscrollbar->setPageSize(s32(getTextDimension().Height));
		}

		if (!m_vscrollbar->isVisible()) {
			m_vscrollbar->setVisible(true);
		}
	} else {
		if (m_vscrollbar->isVisible()) {
			m_vscrollbar->setVisible(false);
			m_vscroll_pos = 0;
			m_vscrollbar->setPos(0);
			m_vscrollbar->setMax(1);
			m_vscrollbar->setPageSize(s32(getTextDimension().Height));
		}
	}
}

void GUIEditBox::deserializeAttributes(
		io::IAttributes *in, io::SAttributeReadWriteOptions *options = 0)
{
	IGUIEditBox::deserializeAttributes(in, options);

	setOverrideColor(in->getAttributeAsColor("OverrideColor"));
	enableOverrideColor(in->getAttributeAsBool("OverrideColorEnabled"));
	setMax(in->getAttributeAsInt("MaxChars"));
	setWordWrap(in->getAttributeAsBool("WordWrap"));
	setMultiLine(in->getAttributeAsBool("MultiLine"));
	setAutoScroll(in->getAttributeAsBool("AutoScroll"));
	core::stringw ch = in->getAttributeAsStringW("PasswordChar");

	if (ch.empty())
		setPasswordBox(in->getAttributeAsBool("PasswordBox"));
	else
		setPasswordBox(in->getAttributeAsBool("PasswordBox"), ch[0]);

	setTextAlignment((EGUI_ALIGNMENT)in->getAttributeAsEnumeration(
					 "HTextAlign", GUIAlignmentNames),
			(EGUI_ALIGNMENT)in->getAttributeAsEnumeration(
					"VTextAlign", GUIAlignmentNames));

	setWritable(in->getAttributeAsBool("Writable"));
	// setOverrideFont(in->getAttributeAsFont("OverrideFont"));
}

//! Writes attributes of the element.
void GUIEditBox::serializeAttributes(
		io::IAttributes *out, io::SAttributeReadWriteOptions *options = 0) const
{
	// IGUIEditBox::serializeAttributes(out,options);

	out->addBool("OverrideColorEnabled", m_override_color_enabled);
	out->addColor("OverrideColor", m_override_color);
	// out->addFont("OverrideFont",m_override_font);
	out->addInt("MaxChars", m_max);
	out->addBool("WordWrap", m_word_wrap);
	out->addBool("MultiLine", m_multiline);
	out->addBool("AutoScroll", m_autoscroll);
	out->addBool("PasswordBox", m_passwordbox);
	core::stringw ch = L" ";
	ch[0] = m_passwordchar;
	out->addString("PasswordChar", ch.c_str());
	out->addEnum("HTextAlign", m_halign, GUIAlignmentNames);
	out->addEnum("VTextAlign", m_valign, GUIAlignmentNames);
	out->addBool("Writable", m_writable);

	IGUIEditBox::serializeAttributes(out, options);
}