<commit_before>/*************************************************************************/
/*  item_list.cpp                                                        */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2022 <NAME>, <NAME>.                 */
/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md).   */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/

#include "item_list.h"

#include "core/config/project_settings.h"
#include "core/os/os.h"
#include "core/string/translation.h"

void ItemList::_shape(int p_idx) {
	Item &item = items.write[p_idx];

	item.text_buf->clear();
	if (item.text_direction == Control::TEXT_DIRECTION_INHERITED) {
		item.text_buf->set_direction(is_layout_rtl() ? TextServer::DIRECTION_RTL : TextServer::DIRECTION_LTR);
	} else {
		item.text_buf->set_direction((TextServer::Direction)item.text_direction);
	}
	item.text_buf->add_string(item.text, get_theme_font(SNAME("font")), get_theme_font_size(SNAME("font_size")), item.language);
	if (icon_mode == ICON_MODE_TOP && max_text_lines > 0) {
		item.text_buf->set_break_flags(TextServer::BREAK_MANDATORY | TextServer::BREAK_WORD_BOUND | TextServer::BREAK_GRAPHEME_BOUND);
	} else {
		item.text_buf->set_break_flags(TextServer::BREAK_NONE);
	}
	item.text_buf->set_text_overrun_behavior(text_overrun_behavior);
	item.text_buf->set_max_lines_visible(max_text_lines);
}

int ItemList::add_item(const String &p_item, const Ref<Texture2D> &p_texture, bool p_selectable) {
	Item item;
	item.icon = p_texture;
	item.text = p_item;
	item.selectable = p_selectable;
	items.push_back(item);
	int item_id = items.size() - 1;

	_shape(items.size() - 1);

	update();
	shape_changed = true;
	notify_property_list_changed();
	return item_id;
}

int ItemList::add_icon_item(const Ref<Texture2D> &p_item, bool p_selectable) {
	Item item;
	item.icon = p_item;
	item.selectable = p_selectable;
	items.push_back(item);
	int item_id = items.size() - 1;

	update();
	shape_changed = true;
	notify_property_list_changed();
	return item_id;
}

void ItemList::set_item_text(int p_idx, const String &p_text) {
	if (p_idx < 0) {
		p_idx += get_item_count();
	}
	ERR_FAIL_INDEX(p_idx, items.size());

	items.write[p_idx].text = p_text;
	_shape(p_idx);
	update();
	shape_changed = true;
}

String ItemList::get_item_text(int p_idx) const {
	ERR_FAIL_INDEX_V(p_idx, items.size(), String());
	return items[p_idx].text;
}

void ItemList::set_item_text_direction(int p_idx, Control::TextDirection p_text_direction) {
	if (p_idx < 0) {
		p_idx += get_item_count();
	}
	ERR_FAIL_INDEX(p_idx, items.size());
	ERR_FAIL_COND((int)p_text_direction < -1 || (int)p_text_direction > 3);
	if (items[p_idx].text_direction != p_text_direction) {
		items.write[p_idx].text_direction = p_text_direction;
		_shape(p_idx);
		update();
	}
}

Control::TextDirection ItemList::get_item_text_direction(int p_idx) const {
	ERR_FAIL_INDEX_V(p_idx, items.size(), TEXT_DIRECTION_INHERITED);
	return items[p_idx].text_direction;
}

void ItemList::set_item_language(int p_idx, const String &p_language) {
	if (p_idx < 0) {
		p_idx += get_item_count();
	}
	ERR_FAIL_INDEX(p_idx, items.size());
	if (items[p_idx].language != p_language) {
		items.write[p_idx].language = p_language;
		_shape(p_idx);
		update();
	}
}

String ItemList::get_item_language(int p_idx) const {
	ERR_FAIL_INDEX_V(p_idx, items.size(), "");
	return items[p_idx].language;
}

void ItemList::set_item_tooltip_enabled(int p_idx, const bool p_enabled) {
	if (p_idx < 0) {
		p_idx += get_item_count();
	}
	ERR_FAIL_INDEX(p_idx, items.size());
	items.write[p_idx].tooltip_enabled = p_enabled;
}

bool ItemList::is_item_tooltip_enabled(int p_idx) const {
	ERR_FAIL_INDEX_V(p_idx, items.size(), false);
	return items[p_idx].tooltip_enabled;
}

void ItemList::set_item_tooltip(int p_idx, const String &p_tooltip) {
	if (p_idx < 0) {
		p_idx += get_item_count();
	}
	ERR_FAIL_INDEX(p_idx, items.size());

	items.write[p_idx].tooltip = p_tooltip;
	update();
	shape_changed = true;
}

String ItemList::get_item_tooltip(int p_idx) const {
	ERR_FAIL_INDEX_V(p_idx, items.size(), String());
	return items[p_idx].tooltip;
}

void ItemList::set_item_icon(int p_idx, const Ref<Texture2D> &p_icon) {
	if (p_idx < 0) {
		p_idx += get_item_count();
	}
	ERR_FAIL_INDEX(p_idx, items.size());

	items.write[p_idx].icon = p_icon;
	update();
	shape_changed = true;
}

Ref<Texture2D> ItemList::get_item_icon(int p_idx) const {
	ERR_FAIL_INDEX_V(p_idx, items.size(), Ref<Texture2D>());

	return items[p_idx].icon;
}

void ItemList::set_item_icon_transposed(int p_idx, const bool p_transposed) {
	if (p_idx < 0) {
		p_idx += get_item_count();
	}
	ERR_FAIL_INDEX(p_idx, items.size());

	items.write[p_idx].icon_transposed = p_transposed;
	update();
	shape_changed = true;
}

bool ItemList::is_item_icon_transposed(int p_idx) const {
	ERR_FAIL_INDEX_V(p_idx, items.size(), false);

	return items[p_idx].icon_transposed;
}

void ItemList::set_item_icon_region(int p_idx, const Rect2 &p_region) {
	if (p_idx < 0) {
		p_idx += get_item_count();
	}
	ERR_FAIL_INDEX(p_idx, items.size());

	items.write[p_idx].icon_region = p_region;
	update();
	shape_changed = true;
}

Rect2 ItemList::get_item_icon_region(int p_idx) const {
	ERR_FAIL_INDEX_V(p_idx, items.size(), Rect2());

	return items[p_idx].icon_region;
}

void ItemList::set_item_icon_modulate(int p_idx, const Color &p_modulate) {
	if (p_idx < 0) {
		p_idx += get_item_count();
	}
	ERR_FAIL_INDEX(p_idx, items.size());

	items.write[p_idx].icon_modulate = p_modulate;
	update();
}

Color ItemList::get_item_icon_modulate(int p_idx) const {
	ERR_FAIL_INDEX_V(p_idx, items.size(), Color());

	return items[p_idx].icon_modulate;
}

void ItemList::set_item_custom_bg_color(int p_idx, const Color &p_custom_bg_color) {
	if (p_idx < 0) {
		p_idx += get_item_count();
	}
	ERR_FAIL_INDEX(p_idx, items.size());

	items.write[p_idx].custom_bg = p_custom_bg_color;
	update();
}

Color ItemList::get_item_custom_bg_color(int p_idx) const {
	ERR_FAIL_INDEX_V(p_idx, items.size(), Color());

	return items[p_idx].custom_bg;
}

void ItemList::set_item_custom_fg_color(int p_idx, const Color &p_custom_fg_color) {
	if (p_idx < 0) {
		p_idx += get_item_count();
	}
	ERR_FAIL_INDEX(p_idx, items.size());

	items.write[p_idx].custom_fg = p_custom_fg_color;
	update();
}

Color ItemList::get_item_custom_fg_color(int p_idx) const {
	ERR_FAIL_INDEX_V(p_idx, items.size(), Color());

	return items[p_idx].custom_fg;
}

void ItemList::set_item_tag_icon(int p_idx, const Ref<Texture2D> &p_tag_icon) {
	if (p_idx < 0) {
		p_idx += get_item_count();
	}
	ERR_FAIL_INDEX(p_idx, items.size());

	items.write[p_idx].tag_icon = p_tag_icon;
	update();
	shape_changed = true;
}

Ref<Texture2D> ItemList::get_item_tag_icon(int p_idx) const {
	ERR_FAIL_INDEX_V(p_idx, items.size(), Ref<Texture2D>());

	return items[p_idx].tag_icon;
}

void ItemList::set_item_selectable(int p_idx, bool p_selectable) {
	if (p_idx < 0) {
		p_idx += get_item_count();
	}
	ERR_FAIL_INDEX(p_idx, items.size());

	items.write[p_idx].selectable = p_selectable;
}

bool ItemList::is_item_selectable(int p_idx) const {
	ERR_FAIL_INDEX_V(p_idx, items.size(), false);
	return items[p_idx].selectable;
}

void ItemList::set_item_disabled(int p_idx, bool p_disabled) {
	if (p_idx < 0) {
		p_idx += get_item_count();
	}
	ERR_FAIL_INDEX(p_idx, items.size());

	items.write[p_idx].disabled = p_disabled;
	update();
}

bool ItemList::is_item_disabled(int p_idx) const {
	ERR_FAIL_INDEX_V(p_idx, items.size(), false);
	return items[p_idx].disabled;
}

void ItemList::set_item_metadata(int p_idx, const Variant &p_metadata) {
	if (p_idx < 0) {
		p_idx += get_item_count();
	}
	ERR_FAIL_INDEX(p_idx, items.size());

	items.write[p_idx].metadata = p_metadata;
	update();
	shape_changed = true;
}

Variant ItemList::get_item_metadata(int p_idx) const {
	ERR_FAIL_INDEX_V(p_idx, items.size(), Variant());
	return items[p_idx].metadata;
}

void ItemList::select(int p_idx, bool p_single) {
	ERR_FAIL_INDEX(p_idx, items.size());

	if (p_single || select_mode == SELECT_SINGLE) {
		if (!items[p_idx].selectable || items[p_idx].disabled) {
			return;
		}

		for (int i = 0; i < items.size(); i++) {
			items.write[i].selected = p_idx == i;
		}

		current = p_idx;
		ensure_selected_visible = false;
	} else {
		if (items[p_idx].selectable && !items[p_idx].disabled) {
			items.write[p_idx].selected = true;
		}
	}
	update();
}

void ItemList::deselect(int p_idx) {
	ERR_FAIL_INDEX(p_idx, items.size());

	if (select_mode != SELECT_MULTI) {
		items.write[p_idx].selected = false;
		current = -1;
	} else {
		items.write[p_idx].selected = false;
	}
	update();
}

void ItemList::deselect_all() {
	if (items.size() < 1) {
		return;
	}

	for (int i = 0; i < items.size(); i++) {
		items.write[i].selected = false;
	}
	current = -1;
	update();
}

bool ItemList::is_selected(int p_idx) const {
	ERR_FAIL_INDEX_V(p_idx, items.size(), false);

	return items[p_idx].selected;
}

void ItemList::set_current(int p_current) {
	ERR_FAIL_INDEX(p_current, items.size());

	if (select_mode == SELECT_SINGLE) {
		select(p_current, true);
	} else {
		current = p_current;
		update();
	}
}

int ItemList::get_current() const {
	return current;
}

void ItemList::move_item(int p_from_idx, int p_to_idx) {
	ERR_FAIL_INDEX(p_from_idx, items.size());
	ERR_FAIL_INDEX(p_to_idx, items.size());

	if (is_anything_selected() && get_selected_items()[0] == p_from_idx) {
		current = p_to_idx;
	}

	Item item = items[p_from_idx];
	items.remove_at(p_from_idx);
	items.insert(p_to_idx, item);

	update();
	shape_changed = true;
	notify_property_list_changed();
}

void ItemList::set_item_count(int p_count) {
	ERR_FAIL_COND(p_count < 0);
	items.resize(p_count);
	update();
	shape_changed = true;
	notify_property_list_changed();
}

int ItemList::get_item_count() const {
	return items.size();
}

void ItemList::remove_item(int p_idx) {
	ERR_FAIL_INDEX(p_idx, items.size());

	items.remove_at(p_idx);
	if (current == p_idx) {
		current = -1;
	}
	update();
	shape_changed = true;
	defer_select_single = -1;
	notify_property_list_changed();
}

void ItemList::clear() {
	items.clear();
	current = -1;
	ensure_selected_visible = false;
	update();
	shape_changed = true;
	defer_select_single = -1;
	notify_property_list_changed();
}

void ItemList::set_fixed_column_width(int p_size) {
	ERR_FAIL_COND(p_size < 0);
	fixed_column_width = p_size;
	update();
	shape_changed = true;
}

int ItemList::get_fixed_column_width() const {
	return fixed_column_width;
}

void ItemList::set_same_column_width(bool p_enable) {
	same_column_width = p_enable;
	update();
	shape_changed = true;
}

bool ItemList::is_same_column_width() const {
	return same_column_width;
}

void ItemList::set_max_text_lines(int p_lines) {
	ERR_FAIL_COND(p_lines < 1);
	if (max_text_lines != p_lines) {
		max_text_lines = p_lines;
		for (int i = 0; i < items.size(); i++) {
			if (icon_mode == ICON_MODE_TOP && max_text_lines > 0) {
				items.write[i].text_buf->set_break_flags(TextServer::BREAK_MANDATORY | TextServer::BREAK_WORD_BOUND | TextServer::BREAK_GRAPHEME_BOUND);
				items.write[i].text_buf->set_max_lines_visible(p_lines);
			} else {
				items.write[i].text_buf->set_break_flags(TextServer::BREAK_NONE);
			}
		}
		shape_changed = true;
		update();
	}
}

int ItemList::get_max_text_lines() const {
	return max_text_lines;
}

void ItemList::set_max_columns(int p_amount) {
	ERR_FAIL_COND(p_amount < 0);
	max_columns = p_amount;
	update();
	shape_changed = true;
}

int ItemList::get_max_columns() const {
	return max_columns;
}

void ItemList::set_select_mode(SelectMode p_mode) {
	select_mode = p_mode;
	update();
}

ItemList::SelectMode ItemList::get_select_mode() const {
	return select_mode;
}

void ItemList::set_icon_mode(IconMode p_mode) {
	ERR_FAIL_INDEX((int)p_mode, 2);
	if (icon_mode != p_mode) {
		icon_mode = p_mode;
		for (int i = 0; i < items.size(); i++) {
			if (icon_mode == ICON_MODE_TOP && max_text_lines > 0) {
				items.write[i].text_buf->set_break_flags(TextServer::BREAK_MANDATORY | TextServer::BREAK_WORD_BOUND | TextServer::BREAK_GRAPHEME_BOUND);
			} else {
				items.write[i].text_buf->set_break_flags(TextServer::BREAK_NONE);
			}
		}
		shape_changed = true;
		update();
	}
}

ItemList::IconMode ItemList::get_icon_mode() const {
	return icon_mode;
}

void ItemList::set_fixed_icon_size(const Size2 &p_size) {
	fixed_icon_size = p_size;
	update();
}

Size2 ItemList::get_fixed_icon_size() const {
	return fixed_icon_size;
}

Size2 ItemList::Item::get_icon_size() const {
	if (icon.is_null()) {
		return Size2();
	}

	Size2 size_result = Size2(icon_region.size).abs();
	if (icon_region.size.x == 0 || icon_region.size.y == 0) {
		size_result = icon->get_size();
	}

	if (icon_transposed) {
		Size2 size_tmp = size_result;
		size_result.x = size_tmp.y;
		size_result.y = size_tmp.x;
	}

	return size_result;
}

void ItemList::gui_input(const Ref<InputEvent> &p_event) {
	ERR_FAIL_COND(p_event.is_null());

#define CAN_SELECT(i) (items[i].selectable && !items[i].disabled)
#define IS_SAME_ROW(i, row) (i / current_columns == row)

	double prev_scroll = scroll_bar->get_value();

	Ref<InputEventMouseMotion> mm = p_event;
	if (defer_select_single >= 0 && mm.is_valid()) {
		defer_select_single = -1;
		return;
	}

	Ref<InputEventMouseButton> mb = p_event;

	if (defer_select_single >= 0 && mb.is_valid() && mb->get_button_index() == MouseButton::LEFT && !mb->is_pressed()) {
		select(defer_select_single, true);

		emit_signal(SNAME("multi_selected"), defer_select_single, true);
		defer_select_single = -1;
		return;
	}

	if (mb.is_valid() && mb->is_pressed()) {
		search_string = ""; //any mousepress cancels
		Vector2 pos = mb->get_position();
		Ref<StyleBox> bg = get_theme_stylebox(SNAME("bg"));
		pos -= bg->get_offset();
		pos.y += scroll_bar->get_value();

		if (is_layout_rtl()) {
			pos.x = get_size().width - pos.x;
		}

		int closest = -1;

		for (int i = 0; i < items.size(); i++) {
			Rect2 rc = items[i].rect_cache;
			if (i % current_columns == current_columns - 1) {
				rc.size.width = get_size().width; //not right but works
			}

			if (rc.has_point(pos)) {
				closest = i;
				break;
			}
		}

		if (closest != -1 && (mb->get_button_index() == MouseButton::LEFT || (allow_rmb_select && mb->get_button_index() == MouseButton::RIGHT))) {
			int i = closest;

			if (select_mode == SELECT_MULTI && items[i].selected && mb->is_command_pressed()) {
				deselect(i);
				emit_signal(SNAME("multi_selected"), i, false);

			} else if (select_mode == SELECT_MULTI && mb->is_shift_pressed() && current >= 0 && current < items.size() && current != i) {
				int from = current;
				int to = i;
				if (i < current) {
					SWAP(from, to);
				}
				for (int j = from; j <= to; j++) {
					if (!CAN_SELECT(j)) {
						continue;
					}
					bool selected = !items[j].selected;
					select(j, false);
					if (selected) {
						emit_signal(SNAME("multi_selected"), j, true);
					}
				}
				emit_signal(SNAME("item_clicked"), i, get_local_mouse_position(), mb->get_button_index());

			} else {
				if (!mb->is_double_click() && !mb->is_command_pressed() && select_mode == SELECT_MULTI && items[i].selectable && !items[i].disabled && items[i].selected && mb->get_button_index() == MouseButton::LEFT) {
					defer_select_single = i;
					return;
				}

				if (!items[i].selected || allow_reselect) {
					select(i, select_mode == SELECT_SINGLE || !mb->is_command_pressed());

					if (select_mode == SELECT_SINGLE) {
						emit_signal(SNAME("item_selected"), i);
					} else {
						emit_signal(SNAME("multi_selected"), i, true);
					}
				}

				emit_signal(SNAME("item_clicked"), i, get_local_mouse_position(), mb->get_button_index());

				if (mb->get_button_index() == MouseButton::LEFT && mb->is_double_click()) {
					emit_signal(SNAME("item_activated"), i);
				}
			}

			return;
		} else if (closest != -1) {
			emit_signal(SNAME("item_clicked"), closest, get_local_mouse_position(), mb->get_button_index());
		} else {
			// Since closest is null, more likely we clicked on empty space, so send signal to interested controls. Allows, for example, implement items deselecting.
			emit_signal(SNAME("empty_clicked"), get_local_mouse_position(), mb->get_button_index());
		}
	}
	if (mb.is_valid() && mb->get_button_index() == MouseButton::WHEEL_UP && mb->is_pressed()) {
		scroll_bar->set_value(scroll_bar->get_value() - scroll_bar->get_page() * mb->get_factor() / 8);
	}
	if (mb.is_valid() && mb->get_button_index() == MouseButton::WHEEL_DOWN && mb->is_pressed()) {
		scroll_bar->set_value(scroll_bar->get_value() + scroll_bar->get_page() * mb->get_factor() / 8);
	}

	if (p_event->is_pressed() && items.size() > 0) {
		if (p_event->is_action("ui_up")) {
			if (!search_string.is_empty()) {
				uint64_t now = OS::get_singleton()->get_ticks_msec();
				uint64_t diff = now - search_time_msec;

				if (diff < uint64_t(ProjectSettings::get_singleton()->get("gui/timers/incremental_search_max_interval_msec")) * 2) {
					for (int i = current - 1; i >= 0; i--) {
						if (CAN_SELECT(i) && items[i].text.begins_with(search_string)) {
							set_current(i);
							ensure_current_is_visible();
							if (select_mode == SELECT_SINGLE) {
								emit_signal(SNAME("item_selected"), current);
							}

							break;
						}
					}
					accept_event();
					return;
				}
			}

			if (current >= current_columns) {
				int next = current - current_columns;
				while (next >= 0 && !CAN_SELECT(next)) {
					next = next - current_columns;
				}
				if (next < 0) {
					accept_event();
					return;
				}
				set_current(next);
				ensure_current_is_visible();
				if (select_mode == SELECT_SINGLE) {
					emit_signal(SNAME("item_selected"), current);
				}
				accept_event();
			}
		} else if (p_event->is_action("ui_down")) {
			if (!search_string.is_empty()) {
				uint64_t now = OS::get_singleton()->get_ticks_msec();
				uint64_t diff = now - search_time_msec;

				if (diff < uint64_t(ProjectSettings::get_singleton()->get("gui/timers/incremental_search_max_interval_msec")) * 2) {
					for (int i = current + 1; i < items.size(); i++) {
						if (CAN_SELECT(i) && items[i].text.begins_with(search_string)) {
							set_current(i);
							ensure_current_is_visible();
							if (select_mode == SELECT_SINGLE) {
								emit_signal(SNAME("item_selected"), current);
							}
							break;
						}
					}
					accept_event();
					return;
				}
			}

			if (current < items.size() - current_columns) {
				int next = current + current_columns;
				while (next < items.size() && !CAN_SELECT(next)) {
					next = next + current_columns;
				}
				if (next >= items.size()) {
					accept_event();
					return;
				}
				set_current(next);
				ensure_current_is_visible();
				if (select_mode == SELECT_SINGLE) {
					emit_signal(SNAME("item_selected"), current);
				}
				accept_event();
			}
		} else if (p_event->is_action("ui_page_up")) {
			search_string = ""; //any mousepress cancels

			for (int i = 4; i > 0; i--) {
				if (current - current_columns * i >= 0 && CAN_SELECT(current - current_columns * i)) {
					set_current(current - current_columns * i);
					ensure_current_is_visible();
					if (select_mode == SELECT_SINGLE) {
						emit_signal(SNAME("item_selected"), current);
					}
					accept_event();
					break;
				}
			}
		} else if (p_event->is_action("ui_page_down")) {
			search_string = ""; //any mousepress cancels

			for (int i = 4; i > 0; i--) {
				if (current + current_columns * i < items.size() && CAN_SELECT(current + current_columns * i)) {
					set_current(current + current_columns * i);
					ensure_current_is_visible();
					if (select_mode == SELECT_SINGLE) {
						emit_signal(SNAME("item_selected"), current);
					}
					accept_event();

					break;
				}
			}
		} else if (p_event->is_action("ui_left")) {
			search_string = ""; //any mousepress cancels

			if (current % current_columns != 0) {
				int current_row = current / current_columns;
				int next = current - 1;
				while (!CAN_SELECT(next)) {
					next = next - 1;
				}
				if (next < 0 || !IS_SAME_ROW(next, current_row)) {
					accept_event();
					return;
				}
				set_current(next);
				ensure_current_is_visible();
				if (select_mode == SELECT_SINGLE) {
					emit_signal(SNAME("item_selected"), current);
				}
				accept_event();
			}
		} else if (p_event->is_action("ui_right")) {
			search_string = ""; //any mousepress cancels

			if (current % current_columns != (current_columns - 1) && current + 1 < items.size()) {
				int current_row = current / current_columns;
				int next = current + 1;
				while (!CAN_SELECT(next)) {
					next = next + 1;
				}
				if (items.size() <= next || !IS_SAME_ROW(next, current_row)) {
					accept_event();
					return;
				}
				set_current(next);
				ensure_current_is_visible();
				if (select_mode == SELECT_SINGLE) {
					emit_signal(SNAME("item_selected"), current);
				}
				accept_event();
			}
		} else if (p_event->is_action("ui_cancel")) {
			search_string = "";
		} else if (p_event->is_action("ui_select") && select_mode == SELECT_MULTI) {
			if (current >= 0 && current < items.size()) {
				if (items[current].selectable && !items[current].disabled && !items[current].selected) {
					select(current, false);
					emit_signal(SNAME("multi_selected"), current, true);
				} else if (items[current].selected) {
					deselect(current);
					emit_signal(SNAME("multi_selected"), current, false);
				}
			}
		} else if (p_event->is_action("ui_accept")) {
			search_string = ""; //any mousepress cancels

			if (current >= 0 && current < items.size()) {
				emit_signal(SNAME("item_activated"), current);
			}
		} else {
			Ref<InputEventKey> k = p_event;

			if (k.is_valid() && k->get_unicode()) {
				uint64_t now = OS::get_singleton()->get_ticks_msec();
				uint64_t diff = now - search_time_msec;
				uint64_t max_interval = uint64_t(GLOBAL_DEF("gui/timers/incremental_search_max_interval_msec", 2000));
				search_time_msec = now;

				if (diff > max_interval) {
					search_string = "";
				}

				if (String::chr(k->get_unicode()) != search_string) {
					search_string += String::chr(k->get_unicode());
				}

				for (int i = current + 1; i <= items.size(); i++) {
					if (i == items.size()) {
						if (current == 0 || current == -1) {
							break;
						} else {
							i = 0;
						}
					}

					if (i == current) {
						break;
					}

					if (items[i].text.findn(search_string) == 0) {
						set_current(i);
						ensure_current_is_visible();
						if (select_mode == SELECT_SINGLE) {
							emit_signal(SNAME("item_selected"), current);
						}
						break;
					}
				}
			}
		}
	}

	Ref<InputEventPanGesture> pan_gesture = p_event;
	if (pan_gesture.is_valid()) {
		scroll_bar->set_value(scroll_bar->get_value() + scroll_bar->get_page() * pan_gesture->get_delta().y / 8);
	}

	if (scroll_bar->get_value() != prev_scroll) {
		accept_event(); //accept event if scroll changed
	}

#undef CAN_SELECT
#undef IS_SAME_ROW
}

void ItemList::ensure_current_is_visible() {
	ensure_selected_visible = true;
	update();
}

static Rect2 _adjust_to_max_size(Size2 p_size, Size2 p_max_size) {
	Size2 size = p_max_size;
	int tex_width = p_size.width * size.height / p_size.height;
	int tex_height = size.height;

	if (tex_width > size.width) {
		tex_width = size.width;
		tex_height = p_size.height * tex_width / p_size.width;
	}

	int ofs_x = (size.width - tex_width) / 2;
	int ofs_y = (size.height - tex_height) / 2;

	return Rect2(ofs_x, ofs_y, tex_width, tex_height);
}

void ItemList::_notification(int p_what) {
	switch (p_what) {
		case NOTIFICATION_RESIZED: {
			shape_changed = true;
			update();
		} break;

		case NOTIFICATION_LAYOUT_DIRECTION_CHANGED:
		case NOTIFICATION_TRANSLATION_CHANGED:
		case NOTIFICATION_THEME_CHANGED: {
			for (int i = 0; i < items.size(); i++) {
				_shape(i);
			}
			shape_changed = true;
			update();
		} break;

		case NOTIFICATION_DRAW: {
			Ref<StyleBox> bg = get_theme_stylebox(SNAME("bg"));

			int mw = scroll_bar->get_minimum_size().x;
			scroll_bar->set_anchor_and_offset(SIDE_LEFT, ANCHOR_END, -mw);
			scroll_bar->set_anchor_and_offset(SIDE_RIGHT, ANCHOR_END, 0);
			scroll_bar->set_anchor_and_offset(SIDE_TOP, ANCHOR_BEGIN, bg->get_margin(SIDE_TOP));
			scroll_bar->set_anchor_and_offset(SIDE_BOTTOM, ANCHOR_END, -bg->get_margin(SIDE_BOTTOM));

			Size2 size = get_size();

			int width = size.width - bg->get_minimum_size().width;
			if (scroll_bar->is_visible()) {
				width -= mw;
			}

			draw_style_box(bg, Rect2(Point2(), size));

			int hseparation = get_theme_constant(SNAME("h_separation"));
			int vseparation = get_theme_constant(SNAME("v_separation"));
			int icon_margin = get_theme_constant(SNAME("icon_margin"));
			int line_separation = get_theme_constant(SNAME("line_separation"));
			Color font_outline_color = get_theme_color(SNAME("font_outline_color"));
			int outline_size = get_theme_constant(SNAME("outline_size"));

			Ref<StyleBox> sbsel = has_focus() ? get_theme_stylebox(SNAME("selected_focus")) : get_theme_stylebox(SNAME("selected"));
			Ref<StyleBox> cursor = has_focus() ? get_theme_stylebox(SNAME("cursor")) : get_theme_stylebox(SNAME("cursor_unfocused"));
			bool rtl = is_layout_rtl();

			Color guide_color = get_theme_color(SNAME("guide_color"));
			Color font_color = get_theme_color(SNAME("font_color"));
			Color font_selected_color = get_theme_color(SNAME("font_selected_color"));

			if (has_focus()) {
				RenderingServer::get_singleton()->canvas_item_add_clip_ignore(get_canvas_item(), true);
				draw_style_box(get_theme_stylebox(SNAME("bg_focus")), Rect2(Point2(), size));
				RenderingServer::get_singleton()->canvas_item_add_clip_ignore(get_canvas_item(), false);
			}

			if (shape_changed) {
				float max_column_width = 0.0;

				//1- compute item minimum sizes
				for (int i = 0; i < items.size(); i++) {
					Size2 minsize;
					if (items[i].icon.is_valid()) {
						if (fixed_icon_size.x > 0 && fixed_icon_size.y > 0) {
							minsize = fixed_icon_size * icon_scale;
						} else {
							minsize = items[i].get_icon_size() * icon_scale;
						}

						if (!items[i].text.is_empty()) {
							if (icon_mode == ICON_MODE_TOP) {
								minsize.y += icon_margin;
							} else {
								minsize.x += icon_margin;
							}
						}
					}

					if (!items[i].text.is_empty()) {
						int max_width = -1;
						if (fixed_column_width) {
							max_width = fixed_column_width;
						} else if (same_column_width) {
							max_width = items[i].rect_cache.size.x;
						}
						items.write[i].text_buf->set_width(max_width);
						Size2 s = items[i].text_buf->get_size();

						if (icon_mode == ICON_MODE_TOP) {
							minsize.x = MAX(minsize.x, s.width);
							if (max_text_lines > 0) {
								minsize.y += s.height + line_separation * max_text_lines;
							} else {
								minsize.y += s.height;
							}

						} else {
							minsize.y = MAX(minsize.y, s.height);
							minsize.x += s.width;
						}
					}

					if (fixed_column_width > 0) {
						minsize.x = fixed_column_width;
					}
					max_column_width = MAX(max_column_width, minsize.x);

					// elements need to adapt to the selected size
					minsize.y += vseparation;
					minsize.x += hseparation;
					items.write[i].rect_cache.size = minsize;
					items.write[i].min_rect_cache.size = minsize;
				}

				int fit_size = size.x - bg->get_minimum_size().width - mw;

				//2-attempt best fit
				current_columns = 0x7FFFFFFF;
				if (max_columns > 0) {
					current_columns = max_columns;
				}

				while (true) {
					//repeat until all fits
					bool all_fit = true;
					Vector2 ofs;
					int col = 0;
					int max_h = 0;
					separators.clear();
					for (int i = 0; i < items.size(); i++) {
						if (current_columns > 1 && items[i].rect_cache.size.width + ofs.x > fit_size) {
							//went past
							current_columns = MAX(col, 1);
							all_fit = false;
							break;
						}

						if (same_column_width) {
							items.write[i].rect_cache.size.x = max_column_width;
						}
						items.write[i].rect_cache.position = ofs;
						max_h = MAX(max_h, items[i].rect_cache.size.y);
						ofs.x += items[i].rect_cache.size.x + hseparation;
						col++;
						if (col == current_columns) {
							if (i < items.size() - 1) {
								separators.push_back(ofs.y + max_h + vseparation / 2);
							}

							for (int j = i; j >= 0 && col > 0; j--, col--) {
								items.write[j].rect_cache.size.y = max_h;
							}

							ofs.x = 0;
							ofs.y += max_h + vseparation;
							col = 0;
							max_h = 0;
						}
					}

					for (int j = items.size() - 1; j >= 0 && col > 0; j--, col--) {
						items.write[j].rect_cache.size.y = max_h;
					}

					if (all_fit) {
						float page = MAX(0, size.height - bg->get_minimum_size().height);
						float max = MAX(page, ofs.y + max_h);
						if (auto_height) {
							auto_height_value = ofs.y + max_h + bg->get_minimum_size().height;
						}
						scroll_bar->set_max(max);
						scroll_bar->set_page(page);
						if (max <= page) {
							scroll_bar->set_value(0);
							scroll_bar->hide();
						} else {
							scroll_bar->show();

							if (do_autoscroll_to_bottom) {
								scroll_bar->set_value(max);
							}
						}
						break;
					}
				}

				update_minimum_size();
				shape_changed = false;
			}

			//ensure_selected_visible needs to be checked before we draw the list.
			if (ensure_selected_visible && current >= 0 && current < items.size()) {
				Rect2 r = items[current].rect_cache;
				int from = scroll_bar->get_value();
				int to = from + scroll_bar->get_page();

				if (r.position.y < from) {
					scroll_bar->set_value(r.position.y);<commit_msg>Fix `ItemList` selection visual when the scrollbar visibility changes<commit_after>/*************************************************************************/
/*  item_list.cpp                                                        */
/*************************************************************************/
/*                       This file is part of:                           */
/*                           GODOT ENGINE                                */
/*                      https://godotengine.org                          */
/*************************************************************************/
/* Copyright (c) 2007-2022 <NAME>, <NAME>.                 */
/* Copyright (c) 2014-2022 Godot Engine contributors (cf. AUTHORS.md).   */
/*                                                                       */
/* Permission is hereby granted, free of charge, to any person obtaining */
/* a copy of this software and associated documentation files (the       */
/* "Software"), to deal in the Software without restriction, including   */
/* without limitation the rights to use, copy, modify, merge, publish,   */
/* distribute, sublicense, and/or sell copies of the Software, and to    */
/* permit persons to whom the Software is furnished to do so, subject to */
/* the following conditions:                                             */
/*                                                                       */
/* The above copyright notice and this permission notice shall be        */
/* included in all copies or substantial portions of the Software.       */
/*                                                                       */
/* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
/* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
/* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
/* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
/* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
/* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
/* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
/*************************************************************************/

#include "item_list.h"

#include "core/config/project_settings.h"
#include "core/os/os.h"
#include "core/string/translation.h"

void ItemList::_shape(int p_idx) {
	Item &item = items.write[p_idx];

	item.text_buf->clear();
	if (item.text_direction == Control::TEXT_DIRECTION_INHERITED) {
		item.text_buf->set_direction(is_layout_rtl() ? TextServer::DIRECTION_RTL : TextServer::DIRECTION_LTR);
	} else {
		item.text_buf->set_direction((TextServer::Direction)item.text_direction);
	}
	item.text_buf->add_string(item.text, get_theme_font(SNAME("font")), get_theme_font_size(SNAME("font_size")), item.language);
	if (icon_mode == ICON_MODE_TOP && max_text_lines > 0) {
		item.text_buf->set_break_flags(TextServer::BREAK_MANDATORY | TextServer::BREAK_WORD_BOUND | TextServer::BREAK_GRAPHEME_BOUND);
	} else {
		item.text_buf->set_break_flags(TextServer::BREAK_NONE);
	}
	item.text_buf->set_text_overrun_behavior(text_overrun_behavior);
	item.text_buf->set_max_lines_visible(max_text_lines);
}

int ItemList::add_item(const String &p_item, const Ref<Texture2D> &p_texture, bool p_selectable) {
	Item item;
	item.icon = p_texture;
	item.text = p_item;
	item.selectable = p_selectable;
	items.push_back(item);
	int item_id = items.size() - 1;

	_shape(items.size() - 1);

	update();
	shape_changed = true;
	notify_property_list_changed();
	return item_id;
}

int ItemList::add_icon_item(const Ref<Texture2D> &p_item, bool p_selectable) {
	Item item;
	item.icon = p_item;
	item.selectable = p_selectable;
	items.push_back(item);
	int item_id = items.size() - 1;

	update();
	shape_changed = true;
	notify_property_list_changed();
	return item_id;
}

void ItemList::set_item_text(int p_idx, const String &p_text) {
	if (p_idx < 0) {
		p_idx += get_item_count();
	}
	ERR_FAIL_INDEX(p_idx, items.size());

	items.write[p_idx].text = p_text;
	_shape(p_idx);
	update();
	shape_changed = true;
}

String ItemList::get_item_text(int p_idx) const {
	ERR_FAIL_INDEX_V(p_idx, items.size(), String());
	return items[p_idx].text;
}

void ItemList::set_item_text_direction(int p_idx, Control::TextDirection p_text_direction) {
	if (p_idx < 0) {
		p_idx += get_item_count();
	}
	ERR_FAIL_INDEX(p_idx, items.size());
	ERR_FAIL_COND((int)p_text_direction < -1 || (int)p_text_direction > 3);
	if (items[p_idx].text_direction != p_text_direction) {
		items.write[p_idx].text_direction = p_text_direction;
		_shape(p_idx);
		update();
	}
}

Control::TextDirection ItemList::get_item_text_direction(int p_idx) const {
	ERR_FAIL_INDEX_V(p_idx, items.size(), TEXT_DIRECTION_INHERITED);
	return items[p_idx].text_direction;
}

void ItemList::set_item_language(int p_idx, const String &p_language) {
	if (p_idx < 0) {
		p_idx += get_item_count();
	}
	ERR_FAIL_INDEX(p_idx, items.size());
	if (items[p_idx].language != p_language) {
		items.write[p_idx].language = p_language;
		_shape(p_idx);
		update();
	}
}

String ItemList::get_item_language(int p_idx) const {
	ERR_FAIL_INDEX_V(p_idx, items.size(), "");
	return items[p_idx].language;
}

void ItemList::set_item_tooltip_enabled(int p_idx, const bool p_enabled) {
	if (p_idx < 0) {
		p_idx += get_item_count();
	}
	ERR_FAIL_INDEX(p_idx, items.size());
	items.write[p_idx].tooltip_enabled = p_enabled;
}

bool ItemList::is_item_tooltip_enabled(int p_idx) const {
	ERR_FAIL_INDEX_V(p_idx, items.size(), false);
	return items[p_idx].tooltip_enabled;
}

void ItemList::set_item_tooltip(int p_idx, const String &p_tooltip) {
	if (p_idx < 0) {
		p_idx += get_item_count();
	}
	ERR_FAIL_INDEX(p_idx, items.size());

	items.write[p_idx].tooltip = p_tooltip;
	update();
	shape_changed = true;
}

String ItemList::get_item_tooltip(int p_idx) const {
	ERR_FAIL_INDEX_V(p_idx, items.size(), String());
	return items[p_idx].tooltip;
}

void ItemList::set_item_icon(int p_idx, const Ref<Texture2D> &p_icon) {
	if (p_idx < 0) {
		p_idx += get_item_count();
	}
	ERR_FAIL_INDEX(p_idx, items.size());

	items.write[p_idx].icon = p_icon;
	update();
	shape_changed = true;
}

Ref<Texture2D> ItemList::get_item_icon(int p_idx) const {
	ERR_FAIL_INDEX_V(p_idx, items.size(), Ref<Texture2D>());

	return items[p_idx].icon;
}

void ItemList::set_item_icon_transposed(int p_idx, const bool p_transposed) {
	if (p_idx < 0) {
		p_idx += get_item_count();
	}
	ERR_FAIL_INDEX(p_idx, items.size());

	items.write[p_idx].icon_transposed = p_transposed;
	update();
	shape_changed = true;
}

bool ItemList::is_item_icon_transposed(int p_idx) const {
	ERR_FAIL_INDEX_V(p_idx, items.size(), false);

	return items[p_idx].icon_transposed;
}

void ItemList::set_item_icon_region(int p_idx, const Rect2 &p_region) {
	if (p_idx < 0) {
		p_idx += get_item_count();
	}
	ERR_FAIL_INDEX(p_idx, items.size());

	items.write[p_idx].icon_region = p_region;
	update();
	shape_changed = true;
}

Rect2 ItemList::get_item_icon_region(int p_idx) const {
	ERR_FAIL_INDEX_V(p_idx, items.size(), Rect2());

	return items[p_idx].icon_region;
}

void ItemList::set_item_icon_modulate(int p_idx, const Color &p_modulate) {
	if (p_idx < 0) {
		p_idx += get_item_count();
	}
	ERR_FAIL_INDEX(p_idx, items.size());

	items.write[p_idx].icon_modulate = p_modulate;
	update();
}

Color ItemList::get_item_icon_modulate(int p_idx) const {
	ERR_FAIL_INDEX_V(p_idx, items.size(), Color());

	return items[p_idx].icon_modulate;
}

void ItemList::set_item_custom_bg_color(int p_idx, const Color &p_custom_bg_color) {
	if (p_idx < 0) {
		p_idx += get_item_count();
	}
	ERR_FAIL_INDEX(p_idx, items.size());

	items.write[p_idx].custom_bg = p_custom_bg_color;
	update();
}

Color ItemList::get_item_custom_bg_color(int p_idx) const {
	ERR_FAIL_INDEX_V(p_idx, items.size(), Color());

	return items[p_idx].custom_bg;
}

void ItemList::set_item_custom_fg_color(int p_idx, const Color &p_custom_fg_color) {
	if (p_idx < 0) {
		p_idx += get_item_count();
	}
	ERR_FAIL_INDEX(p_idx, items.size());

	items.write[p_idx].custom_fg = p_custom_fg_color;
	update();
}

Color ItemList::get_item_custom_fg_color(int p_idx) const {
	ERR_FAIL_INDEX_V(p_idx, items.size(), Color());

	return items[p_idx].custom_fg;
}

void ItemList::set_item_tag_icon(int p_idx, const Ref<Texture2D> &p_tag_icon) {
	if (p_idx < 0) {
		p_idx += get_item_count();
	}
	ERR_FAIL_INDEX(p_idx, items.size());

	items.write[p_idx].tag_icon = p_tag_icon;
	update();
	shape_changed = true;
}

Ref<Texture2D> ItemList::get_item_tag_icon(int p_idx) const {
	ERR_FAIL_INDEX_V(p_idx, items.size(), Ref<Texture2D>());

	return items[p_idx].tag_icon;
}

void ItemList::set_item_selectable(int p_idx, bool p_selectable) {
	if (p_idx < 0) {
		p_idx += get_item_count();
	}
	ERR_FAIL_INDEX(p_idx, items.size());

	items.write[p_idx].selectable = p_selectable;
}

bool ItemList::is_item_selectable(int p_idx) const {
	ERR_FAIL_INDEX_V(p_idx, items.size(), false);
	return items[p_idx].selectable;
}

void ItemList::set_item_disabled(int p_idx, bool p_disabled) {
	if (p_idx < 0) {
		p_idx += get_item_count();
	}
	ERR_FAIL_INDEX(p_idx, items.size());

	items.write[p_idx].disabled = p_disabled;
	update();
}

bool ItemList::is_item_disabled(int p_idx) const {
	ERR_FAIL_INDEX_V(p_idx, items.size(), false);
	return items[p_idx].disabled;
}

void ItemList::set_item_metadata(int p_idx, const Variant &p_metadata) {
	if (p_idx < 0) {
		p_idx += get_item_count();
	}
	ERR_FAIL_INDEX(p_idx, items.size());

	items.write[p_idx].metadata = p_metadata;
	update();
	shape_changed = true;
}

Variant ItemList::get_item_metadata(int p_idx) const {
	ERR_FAIL_INDEX_V(p_idx, items.size(), Variant());
	return items[p_idx].metadata;
}

void ItemList::select(int p_idx, bool p_single) {
	ERR_FAIL_INDEX(p_idx, items.size());

	if (p_single || select_mode == SELECT_SINGLE) {
		if (!items[p_idx].selectable || items[p_idx].disabled) {
			return;
		}

		for (int i = 0; i < items.size(); i++) {
			items.write[i].selected = p_idx == i;
		}

		current = p_idx;
		ensure_selected_visible = false;
	} else {
		if (items[p_idx].selectable && !items[p_idx].disabled) {
			items.write[p_idx].selected = true;
		}
	}
	update();
}

void ItemList::deselect(int p_idx) {
	ERR_FAIL_INDEX(p_idx, items.size());

	if (select_mode != SELECT_MULTI) {
		items.write[p_idx].selected = false;
		current = -1;
	} else {
		items.write[p_idx].selected = false;
	}
	update();
}

void ItemList::deselect_all() {
	if (items.size() < 1) {
		return;
	}

	for (int i = 0; i < items.size(); i++) {
		items.write[i].selected = false;
	}
	current = -1;
	update();
}

bool ItemList::is_selected(int p_idx) const {
	ERR_FAIL_INDEX_V(p_idx, items.size(), false);

	return items[p_idx].selected;
}

void ItemList::set_current(int p_current) {
	ERR_FAIL_INDEX(p_current, items.size());

	if (select_mode == SELECT_SINGLE) {
		select(p_current, true);
	} else {
		current = p_current;
		update();
	}
}

int ItemList::get_current() const {
	return current;
}

void ItemList::move_item(int p_from_idx, int p_to_idx) {
	ERR_FAIL_INDEX(p_from_idx, items.size());
	ERR_FAIL_INDEX(p_to_idx, items.size());

	if (is_anything_selected() && get_selected_items()[0] == p_from_idx) {
		current = p_to_idx;
	}

	Item item = items[p_from_idx];
	items.remove_at(p_from_idx);
	items.insert(p_to_idx, item);

	update();
	shape_changed = true;
	notify_property_list_changed();
}

void ItemList::set_item_count(int p_count) {
	ERR_FAIL_COND(p_count < 0);
	items.resize(p_count);
	update();
	shape_changed = true;
	notify_property_list_changed();
}

int ItemList::get_item_count() const {
	return items.size();
}

void ItemList::remove_item(int p_idx) {
	ERR_FAIL_INDEX(p_idx, items.size());

	items.remove_at(p_idx);
	if (current == p_idx) {
		current = -1;
	}
	update();
	shape_changed = true;
	defer_select_single = -1;
	notify_property_list_changed();
}

void ItemList::clear() {
	items.clear();
	current = -1;
	ensure_selected_visible = false;
	update();
	shape_changed = true;
	defer_select_single = -1;
	notify_property_list_changed();
}

void ItemList::set_fixed_column_width(int p_size) {
	ERR_FAIL_COND(p_size < 0);
	fixed_column_width = p_size;
	update();
	shape_changed = true;
}

int ItemList::get_fixed_column_width() const {
	return fixed_column_width;
}

void ItemList::set_same_column_width(bool p_enable) {
	same_column_width = p_enable;
	update();
	shape_changed = true;
}

bool ItemList::is_same_column_width() const {
	return same_column_width;
}

void ItemList::set_max_text_lines(int p_lines) {
	ERR_FAIL_COND(p_lines < 1);
	if (max_text_lines != p_lines) {
		max_text_lines = p_lines;
		for (int i = 0; i < items.size(); i++) {
			if (icon_mode == ICON_MODE_TOP && max_text_lines > 0) {
				items.write[i].text_buf->set_break_flags(TextServer::BREAK_MANDATORY | TextServer::BREAK_WORD_BOUND | TextServer::BREAK_GRAPHEME_BOUND);
				items.write[i].text_buf->set_max_lines_visible(p_lines);
			} else {
				items.write[i].text_buf->set_break_flags(TextServer::BREAK_NONE);
			}
		}
		shape_changed = true;
		update();
	}
}

int ItemList::get_max_text_lines() const {
	return max_text_lines;
}

void ItemList::set_max_columns(int p_amount) {
	ERR_FAIL_COND(p_amount < 0);
	max_columns = p_amount;
	update();
	shape_changed = true;
}

int ItemList::get_max_columns() const {
	return max_columns;
}

void ItemList::set_select_mode(SelectMode p_mode) {
	select_mode = p_mode;
	update();
}

ItemList::SelectMode ItemList::get_select_mode() const {
	return select_mode;
}

void ItemList::set_icon_mode(IconMode p_mode) {
	ERR_FAIL_INDEX((int)p_mode, 2);
	if (icon_mode != p_mode) {
		icon_mode = p_mode;
		for (int i = 0; i < items.size(); i++) {
			if (icon_mode == ICON_MODE_TOP && max_text_lines > 0) {
				items.write[i].text_buf->set_break_flags(TextServer::BREAK_MANDATORY | TextServer::BREAK_WORD_BOUND | TextServer::BREAK_GRAPHEME_BOUND);
			} else {
				items.write[i].text_buf->set_break_flags(TextServer::BREAK_NONE);
			}
		}
		shape_changed = true;
		update();
	}
}

ItemList::IconMode ItemList::get_icon_mode() const {
	return icon_mode;
}

void ItemList::set_fixed_icon_size(const Size2 &p_size) {
	fixed_icon_size = p_size;
	update();
}

Size2 ItemList::get_fixed_icon_size() const {
	return fixed_icon_size;
}

Size2 ItemList::Item::get_icon_size() const {
	if (icon.is_null()) {
		return Size2();
	}

	Size2 size_result = Size2(icon_region.size).abs();
	if (icon_region.size.x == 0 || icon_region.size.y == 0) {
		size_result = icon->get_size();
	}

	if (icon_transposed) {
		Size2 size_tmp = size_result;
		size_result.x = size_tmp.y;
		size_result.y = size_tmp.x;
	}

	return size_result;
}

void ItemList::gui_input(const Ref<InputEvent> &p_event) {
	ERR_FAIL_COND(p_event.is_null());

#define CAN_SELECT(i) (items[i].selectable && !items[i].disabled)
#define IS_SAME_ROW(i, row) (i / current_columns == row)

	double prev_scroll = scroll_bar->get_value();

	Ref<InputEventMouseMotion> mm = p_event;
	if (defer_select_single >= 0 && mm.is_valid()) {
		defer_select_single = -1;
		return;
	}

	Ref<InputEventMouseButton> mb = p_event;

	if (defer_select_single >= 0 && mb.is_valid() && mb->get_button_index() == MouseButton::LEFT && !mb->is_pressed()) {
		select(defer_select_single, true);

		emit_signal(SNAME("multi_selected"), defer_select_single, true);
		defer_select_single = -1;
		return;
	}

	if (mb.is_valid() && mb->is_pressed()) {
		search_string = ""; //any mousepress cancels
		Vector2 pos = mb->get_position();
		Ref<StyleBox> bg = get_theme_stylebox(SNAME("bg"));
		pos -= bg->get_offset();
		pos.y += scroll_bar->get_value();

		if (is_layout_rtl()) {
			pos.x = get_size().width - pos.x;
		}

		int closest = -1;

		for (int i = 0; i < items.size(); i++) {
			Rect2 rc = items[i].rect_cache;
			if (i % current_columns == current_columns - 1) {
				rc.size.width = get_size().width; //not right but works
			}

			if (rc.has_point(pos)) {
				closest = i;
				break;
			}
		}

		if (closest != -1 && (mb->get_button_index() == MouseButton::LEFT || (allow_rmb_select && mb->get_button_index() == MouseButton::RIGHT))) {
			int i = closest;

			if (select_mode == SELECT_MULTI && items[i].selected && mb->is_command_pressed()) {
				deselect(i);
				emit_signal(SNAME("multi_selected"), i, false);

			} else if (select_mode == SELECT_MULTI && mb->is_shift_pressed() && current >= 0 && current < items.size() && current != i) {
				int from = current;
				int to = i;
				if (i < current) {
					SWAP(from, to);
				}
				for (int j = from; j <= to; j++) {
					if (!CAN_SELECT(j)) {
						continue;
					}
					bool selected = !items[j].selected;
					select(j, false);
					if (selected) {
						emit_signal(SNAME("multi_selected"), j, true);
					}
				}
				emit_signal(SNAME("item_clicked"), i, get_local_mouse_position(), mb->get_button_index());

			} else {
				if (!mb->is_double_click() && !mb->is_command_pressed() && select_mode == SELECT_MULTI && items[i].selectable && !items[i].disabled && items[i].selected && mb->get_button_index() == MouseButton::LEFT) {
					defer_select_single = i;
					return;
				}

				if (!items[i].selected || allow_reselect) {
					select(i, select_mode == SELECT_SINGLE || !mb->is_command_pressed());

					if (select_mode == SELECT_SINGLE) {
						emit_signal(SNAME("item_selected"), i);
					} else {
						emit_signal(SNAME("multi_selected"), i, true);
					}
				}

				emit_signal(SNAME("item_clicked"), i, get_local_mouse_position(), mb->get_button_index());

				if (mb->get_button_index() == MouseButton::LEFT && mb->is_double_click()) {
					emit_signal(SNAME("item_activated"), i);
				}
			}

			return;
		} else if (closest != -1) {
			emit_signal(SNAME("item_clicked"), closest, get_local_mouse_position(), mb->get_button_index());
		} else {
			// Since closest is null, more likely we clicked on empty space, so send signal to interested controls. Allows, for example, implement items deselecting.
			emit_signal(SNAME("empty_clicked"), get_local_mouse_position(), mb->get_button_index());
		}
	}
	if (mb.is_valid() && mb->get_button_index() == MouseButton::WHEEL_UP && mb->is_pressed()) {
		scroll_bar->set_value(scroll_bar->get_value() - scroll_bar->get_page() * mb->get_factor() / 8);
	}
	if (mb.is_valid() && mb->get_button_index() == MouseButton::WHEEL_DOWN && mb->is_pressed()) {
		scroll_bar->set_value(scroll_bar->get_value() + scroll_bar->get_page() * mb->get_factor() / 8);
	}

	if (p_event->is_pressed() && items.size() > 0) {
		if (p_event->is_action("ui_up")) {
			if (!search_string.is_empty()) {
				uint64_t now = OS::get_singleton()->get_ticks_msec();
				uint64_t diff = now - search_time_msec;

				if (diff < uint64_t(ProjectSettings::get_singleton()->get("gui/timers/incremental_search_max_interval_msec")) * 2) {
					for (int i = current - 1; i >= 0; i--) {
						if (CAN_SELECT(i) && items[i].text.begins_with(search_string)) {
							set_current(i);
							ensure_current_is_visible();
							if (select_mode == SELECT_SINGLE) {
								emit_signal(SNAME("item_selected"), current);
							}

							break;
						}
					}
					accept_event();
					return;
				}
			}

			if (current >= current_columns) {
				int next = current - current_columns;
				while (next >= 0 && !CAN_SELECT(next)) {
					next = next - current_columns;
				}
				if (next < 0) {
					accept_event();
					return;
				}
				set_current(next);
				ensure_current_is_visible();
				if (select_mode == SELECT_SINGLE) {
					emit_signal(SNAME("item_selected"), current);
				}
				accept_event();
			}
		} else if (p_event->is_action("ui_down")) {
			if (!search_string.is_empty()) {
				uint64_t now = OS::get_singleton()->get_ticks_msec();
				uint64_t diff = now - search_time_msec;

				if (diff < uint64_t(ProjectSettings::get_singleton()->get("gui/timers/incremental_search_max_interval_msec")) * 2) {
					for (int i = current + 1; i < items.size(); i++) {
						if (CAN_SELECT(i) && items[i].text.begins_with(search_string)) {
							set_current(i);
							ensure_current_is_visible();
							if (select_mode == SELECT_SINGLE) {
								emit_signal(SNAME("item_selected"), current);
							}
							break;
						}
					}
					accept_event();
					return;
				}
			}

			if (current < items.size() - current_columns) {
				int next = current + current_columns;
				while (next < items.size() && !CAN_SELECT(next)) {
					next = next + current_columns;
				}
				if (next >= items.size()) {
					accept_event();
					return;
				}
				set_current(next);
				ensure_current_is_visible();
				if (select_mode == SELECT_SINGLE) {
					emit_signal(SNAME("item_selected"), current);
				}
				accept_event();
			}
		} else if (p_event->is_action("ui_page_up")) {
			search_string = ""; //any mousepress cancels

			for (int i = 4; i > 0; i--) {
				if (current - current_columns * i >= 0 && CAN_SELECT(current - current_columns * i)) {
					set_current(current - current_columns * i);
					ensure_current_is_visible();
					if (select_mode == SELECT_SINGLE) {
						emit_signal(SNAME("item_selected"), current);
					}
					accept_event();
					break;
				}
			}
		} else if (p_event->is_action("ui_page_down")) {
			search_string = ""; //any mousepress cancels

			for (int i = 4; i > 0; i--) {
				if (current + current_columns * i < items.size() && CAN_SELECT(current + current_columns * i)) {
					set_current(current + current_columns * i);
					ensure_current_is_visible();
					if (select_mode == SELECT_SINGLE) {
						emit_signal(SNAME("item_selected"), current);
					}
					accept_event();

					break;
				}
			}
		} else if (p_event->is_action("ui_left")) {
			search_string = ""; //any mousepress cancels

			if (current % current_columns != 0) {
				int current_row = current / current_columns;
				int next = current - 1;
				while (!CAN_SELECT(next)) {
					next = next - 1;
				}
				if (next < 0 || !IS_SAME_ROW(next, current_row)) {
					accept_event();
					return;
				}
				set_current(next);
				ensure_current_is_visible();
				if (select_mode == SELECT_SINGLE) {
					emit_signal(SNAME("item_selected"), current);
				}
				accept_event();
			}
		} else if (p_event->is_action("ui_right")) {
			search_string = ""; //any mousepress cancels

			if (current % current_columns != (current_columns - 1) && current + 1 < items.size()) {
				int current_row = current / current_columns;
				int next = current + 1;
				while (!CAN_SELECT(next)) {
					next = next + 1;
				}
				if (items.size() <= next || !IS_SAME_ROW(next, current_row)) {
					accept_event();
					return;
				}
				set_current(next);
				ensure_current_is_visible();
				if (select_mode == SELECT_SINGLE) {
					emit_signal(SNAME("item_selected"), current);
				}
				accept_event();
			}
		} else if (p_event->is_action("ui_cancel")) {
			search_string = "";
		} else if (p_event->is_action("ui_select") && select_mode == SELECT_MULTI) {
			if (current >= 0 && current < items.size()) {
				if (items[current].selectable && !items[current].disabled && !items[current].selected) {
					select(current, false);
					emit_signal(SNAME("multi_selected"), current, true);
				} else if (items[current].selected) {
					deselect(current);
					emit_signal(SNAME("multi_selected"), current, false);
				}
			}
		} else if (p_event->is_action("ui_accept")) {
			search_string = ""; //any mousepress cancels

			if (current >= 0 && current < items.size()) {
				emit_signal(SNAME("item_activated"), current);
			}
		} else {
			Ref<InputEventKey> k = p_event;

			if (k.is_valid() && k->get_unicode()) {
				uint64_t now = OS::get_singleton()->get_ticks_msec();
				uint64_t diff = now - search_time_msec;
				uint64_t max_interval = uint64_t(GLOBAL_DEF("gui/timers/incremental_search_max_interval_msec", 2000));
				search_time_msec = now;

				if (diff > max_interval) {
					search_string = "";
				}

				if (String::chr(k->get_unicode()) != search_string) {
					search_string += String::chr(k->get_unicode());
				}

				for (int i = current + 1; i <= items.size(); i++) {
					if (i == items.size()) {
						if (current == 0 || current == -1) {
							break;
						} else {
							i = 0;
						}
					}

					if (i == current) {
						break;
					}

					if (items[i].text.findn(search_string) == 0) {
						set_current(i);
						ensure_current_is_visible();
						if (select_mode == SELECT_SINGLE) {
							emit_signal(SNAME("item_selected"), current);
						}
						break;
					}
				}
			}
		}
	}

	Ref<InputEventPanGesture> pan_gesture = p_event;
	if (pan_gesture.is_valid()) {
		scroll_bar->set_value(scroll_bar->get_value() + scroll_bar->get_page() * pan_gesture->get_delta().y / 8);
	}

	if (scroll_bar->get_value() != prev_scroll) {
		accept_event(); //accept event if scroll changed
	}

#undef CAN_SELECT
#undef IS_SAME_ROW
}

void ItemList::ensure_current_is_visible() {
	ensure_selected_visible = true;
	update();
}

static Rect2 _adjust_to_max_size(Size2 p_size, Size2 p_max_size) {
	Size2 size = p_max_size;
	int tex_width = p_size.width * size.height / p_size.height;
	int tex_height = size.height;

	if (tex_width > size.width) {
		tex_width = size.width;
		tex_height = p_size.height * tex_width / p_size.width;
	}

	int ofs_x = (size.width - tex_width) / 2;
	int ofs_y = (size.height - tex_height) / 2;

	return Rect2(ofs_x, ofs_y, tex_width, tex_height);
}

void ItemList::_notification(int p_what) {
	switch (p_what) {
		case NOTIFICATION_RESIZED: {
			shape_changed = true;
			update();
		} break;

		case NOTIFICATION_LAYOUT_DIRECTION_CHANGED:
		case NOTIFICATION_TRANSLATION_CHANGED:
		case NOTIFICATION_THEME_CHANGED: {
			for (int i = 0; i < items.size(); i++) {
				_shape(i);
			}
			shape_changed = true;
			update();
		} break;

		case NOTIFICATION_DRAW: {
			Ref<StyleBox> bg = get_theme_stylebox(SNAME("bg"));

			int mw = scroll_bar->get_minimum_size().x;
			scroll_bar->set_anchor_and_offset(SIDE_LEFT, ANCHOR_END, -mw);
			scroll_bar->set_anchor_and_offset(SIDE_RIGHT, ANCHOR_END, 0);
			scroll_bar->set_anchor_and_offset(SIDE_TOP, ANCHOR_BEGIN, bg->get_margin(SIDE_TOP));
			scroll_bar->set_anchor_and_offset(SIDE_BOTTOM, ANCHOR_END, -bg->get_margin(SIDE_BOTTOM));

			Size2 size = get_size();
			int width = size.width - bg->get_minimum_size().width;

			draw_style_box(bg, Rect2(Point2(), size));

			int hseparation = get_theme_constant(SNAME("h_separation"));
			int vseparation = get_theme_constant(SNAME("v_separation"));
			int icon_margin = get_theme_constant(SNAME("icon_margin"));
			int line_separation = get_theme_constant(SNAME("line_separation"));
			Color font_outline_color = get_theme_color(SNAME("font_outline_color"));
			int outline_size = get_theme_constant(SNAME("outline_size"));

			Ref<StyleBox> sbsel = has_focus() ? get_theme_stylebox(SNAME("selected_focus")) : get_theme_stylebox(SNAME("selected"));
			Ref<StyleBox> cursor = has_focus() ? get_theme_stylebox(SNAME("cursor")) : get_theme_stylebox(SNAME("cursor_unfocused"));
			bool rtl = is_layout_rtl();

			Color guide_color = get_theme_color(SNAME("guide_color"));
			Color font_color = get_theme_color(SNAME("font_color"));
			Color font_selected_color = get_theme_color(SNAME("font_selected_color"));

			if (has_focus()) {
				RenderingServer::get_singleton()->canvas_item_add_clip_ignore(get_canvas_item(), true);
				draw_style_box(get_theme_stylebox(SNAME("bg_focus")), Rect2(Point2(), size));
				RenderingServer::get_singleton()->canvas_item_add_clip_ignore(get_canvas_item(), false);
			}

			if (shape_changed) {
				float max_column_width = 0.0;

				//1- compute item minimum sizes
				for (int i = 0; i < items.size(); i++) {
					Size2 minsize;
					if (items[i].icon.is_valid()) {
						if (fixed_icon_size.x > 0 && fixed_icon_size.y > 0) {
							minsize = fixed_icon_size * icon_scale;
						} else {
							minsize = items[i].get_icon_size() * icon_scale;
						}

						if (!items[i].text.is_empty()) {
							if (icon_mode == ICON_MODE_TOP) {
								minsize.y += icon_margin;
							} else {
								minsize.x += icon_margin;
							}
						}
					}

					if (!items[i].text.is_empty()) {
						int max_width = -1;
						if (fixed_column_width) {
							max_width = fixed_column_width;
						} else if (same_column_width) {
							max_width = items[i].rect_cache.size.x;
						}
						items.write[i].text_buf->set_width(max_width);
						Size2 s = items[i].text_buf->get_size();

						if (icon_mode == ICON_MODE_TOP) {
							minsize.x = MAX(minsize.x, s.width);
							if (max_text_lines > 0) {
								minsize.y += s.height + line_separation * max_text_lines;
							} else {
								minsize.y += s.height;
							}

						} else {
							minsize.y = MAX(minsize.y, s.height);
							minsize.x += s.width;
						}
					}

					if (fixed_column_width > 0) {
						minsize.x = fixed_column_width;
					}
					max_column_width = MAX(max_column_width, minsize.x);

					// elements need to adapt to the selected size
					minsize.y += vseparation;
					minsize.x += hseparation;
					items.write[i].rect_cache.size = minsize;
					items.write[i].min_rect_cache.size = minsize;
				}

				int fit_size = size.x - bg->get_minimum_size().width - mw;

				//2-attempt best fit
				current_columns = 0x7FFFFFFF;
				if (max_columns > 0) {
					current_columns = max_columns;
				}

				while (true) {
					//repeat until all fits
					bool all_fit = true;
					Vector2 ofs;
					int col = 0;
					int max_h = 0;
					separators.clear();
					for (int i = 0; i < items.size(); i++) {
						if (current_columns > 1 && items[i].rect_cache.size.width + ofs.x > fit_size) {
							//went past
							current_columns = MAX(col, 1);
							all_fit = false;
							break;
						}

						if (same_column_width) {
							items.write[i].rect_cache.size.x = max_column_width;
						}
						items.write[i].rect_cache.position = ofs;
						max_h = MAX(max_h, items[i].rect_cache.size.y);
						ofs.x += items[i].rect_cache.size.x + hseparation;
						col++;
						if (col == current_columns) {
							if (i < items.size() - 1) {
								separators.push_back(ofs.y + max_h + vseparation / 2);
							}

							for (int j = i; j >= 0 && col > 0; j--, col--) {
								items.write[j].rect_cache.size.y = max_h;
							}

							ofs.x = 0;
							ofs.y += max_h + vseparation;
							col = 0;
							max_h = 0;
						}
					}

					for (int j = items.size() - 1; j >= 0 && col > 0; j--, col--) {
						items.write[j].rect_cache.size.y = max_h;
					}

					if (all_fit) {
						float page = MAX(0, size.height - bg->get_minimum_size().height);
						float max = MAX(page, ofs.y + max_h);
						if (auto_height) {
							auto_height_value = ofs.y + max_h + bg->get_minimum_size().height;
						}
						scroll_bar->set_max(max);
						scroll_bar->set_page(page);
						if (max <= page) {
							scroll_bar->set_value(0);
							scroll_bar->hide();
						} else {
							scroll_bar->show();

							if (do_autoscroll_to_bottom) {
								scroll_bar->set_value(max);
							}
						}
						break;
					}
				}

				update_minimum_size();
				shape_changed = false;
			}

			if (scroll_bar->is_visible()) {
				width -= mw;
			}

			//ensure_selected_visible needs to be checked before we draw the list.
			if (ensure_selected_visible && current >= 0 && current < items.size()) {
				Rect2 r = items[current].rect_cache;
				int from = scroll_bar->get_value();
				int to = from + scroll_bar->get_page();

				if (r.position.y < from) {
					scroll_bar->set_value(r.position.y);
{'fraction_non_alphanumeric': 0.15311993388219589, 'fraction_numerical': 0.006103181919323564, 'mean_word_length': 3.6240170500477698, 'pattern_counts': {'":': 0, '<': 139, '<?xml version=': 0, '>': 293, 'https://': 2, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 2, 'word_list_counts': {'cursed_substrings.json': 26, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '320825', 'n_tokens_mistral': 26447, 'n_tokens_neox': 22666, 'n_words': 4235}