Update: Translations from eints
[openttd-github.git] / src / signs_gui.cpp
blob56357e648de062cdd6976e3b8af4b355e79f79a7
1 /*
2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD 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.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
6 */
8 /** @file signs_gui.cpp The GUI for signs. */
10 #include "stdafx.h"
11 #include "company_gui.h"
12 #include "company_func.h"
13 #include "signs_base.h"
14 #include "signs_func.h"
15 #include "debug.h"
16 #include "command_func.h"
17 #include "strings_func.h"
18 #include "window_func.h"
19 #include "map_func.h"
20 #include "viewport_func.h"
21 #include "querystring_gui.h"
22 #include "sortlist_type.h"
23 #include "stringfilter_type.h"
24 #include "string_func.h"
25 #include "core/geometry_func.hpp"
26 #include "hotkeys.h"
27 #include "transparency.h"
28 #include "gui.h"
29 #include "signs_cmd.h"
30 #include "timer/timer.h"
31 #include "timer/timer_window.h"
33 #include "widgets/sign_widget.h"
35 #include "table/strings.h"
36 #include "table/sprites.h"
38 #include "safeguards.h"
40 struct SignList {
41 /**
42 * A GUIList contains signs and uses a StringFilter for filtering.
44 typedef GUIList<const Sign *, std::nullptr_t, StringFilter &> GUISignList;
46 GUISignList signs;
48 StringFilter string_filter; ///< The match string to be used when the GUIList is (re)-sorted.
49 static bool match_case; ///< Should case sensitive matching be used?
50 static std::string default_name; ///< Default sign name, used if Sign::name is nullptr.
52 /**
53 * Creates a SignList with filtering disabled by default.
55 SignList() : string_filter(&match_case)
59 void BuildSignsList()
61 if (!this->signs.NeedRebuild()) return;
63 Debug(misc, 3, "Building sign list");
65 this->signs.clear();
66 this->signs.reserve(Sign::GetNumItems());
68 for (const Sign *si : Sign::Iterate()) this->signs.push_back(si);
70 this->signs.SetFilterState(true);
71 this->FilterSignList();
72 this->signs.RebuildDone();
75 /** Sort signs by their name */
76 static bool SignNameSorter(const Sign * const &a, const Sign * const &b)
78 /* Signs are very very rarely using the default text, but there can also be
79 * a lot of them. Therefore a worthwhile performance gain can be made by
80 * directly comparing Sign::name instead of going through the string
81 * system for each comparison. */
82 const std::string &a_name = a->name.empty() ? SignList::default_name : a->name;
83 const std::string &b_name = b->name.empty() ? SignList::default_name : b->name;
85 int r = StrNaturalCompare(a_name, b_name); // Sort by name (natural sorting).
87 return r != 0 ? r < 0 : (a->index < b->index);
90 void SortSignsList()
92 if (!this->signs.Sort(&SignNameSorter)) return;
95 /** Filter sign list by sign name */
96 static bool SignNameFilter(const Sign * const *a, StringFilter &filter)
98 /* Same performance benefit as above for sorting. */
99 const std::string &a_name = (*a)->name.empty() ? SignList::default_name : (*a)->name;
101 filter.ResetState();
102 filter.AddLine(a_name);
103 return filter.GetState();
106 /** Filter sign list excluding OWNER_DEITY */
107 static bool OwnerDeityFilter(const Sign * const *a, StringFilter &)
109 /* You should never be able to edit signs of owner DEITY */
110 return (*a)->owner != OWNER_DEITY;
113 /** Filter sign list by owner */
114 static bool OwnerVisibilityFilter(const Sign * const *a, StringFilter &)
116 assert(!HasBit(_display_opt, DO_SHOW_COMPETITOR_SIGNS));
117 /* Hide sign if non-own signs are hidden in the viewport */
118 return (*a)->owner == _local_company || (*a)->owner == OWNER_DEITY;
121 /** Filter out signs from the sign list that does not match the name filter */
122 void FilterSignList()
124 this->signs.Filter(&SignNameFilter, this->string_filter);
125 if (_game_mode != GM_EDITOR) this->signs.Filter(&OwnerDeityFilter, this->string_filter);
126 if (!HasBit(_display_opt, DO_SHOW_COMPETITOR_SIGNS)) {
127 this->signs.Filter(&OwnerVisibilityFilter, this->string_filter);
132 bool SignList::match_case = false;
133 std::string SignList::default_name;
135 /** Enum referring to the Hotkeys in the sign list window */
136 enum SignListHotkeys {
137 SLHK_FOCUS_FILTER_BOX, ///< Focus the edit box for editing the filter string
140 struct SignListWindow : Window, SignList {
141 QueryString filter_editbox; ///< Filter editbox;
142 int text_offset; ///< Offset of the sign text relative to the left edge of the WID_SIL_LIST widget.
143 Scrollbar *vscroll;
145 SignListWindow(WindowDesc &desc, WindowNumber window_number) : Window(desc), filter_editbox(MAX_LENGTH_SIGN_NAME_CHARS * MAX_CHAR_LENGTH, MAX_LENGTH_SIGN_NAME_CHARS)
147 this->CreateNestedTree();
148 this->vscroll = this->GetScrollbar(WID_SIL_SCROLLBAR);
149 this->FinishInitNested(window_number);
150 this->SetWidgetLoweredState(WID_SIL_FILTER_MATCH_CASE_BTN, SignList::match_case);
152 /* Initialize the text edit widget */
153 this->querystrings[WID_SIL_FILTER_TEXT] = &this->filter_editbox;
154 this->filter_editbox.cancel_button = QueryString::ACTION_CLEAR;
156 /* Initialize the filtering variables */
157 this->SetFilterString("");
159 /* Create initial list. */
160 this->signs.ForceRebuild();
161 this->signs.ForceResort();
162 this->BuildSortSignList();
165 void OnInit() override
167 /* Default sign name, used if Sign::name is nullptr. */
168 SignList::default_name = GetString(STR_DEFAULT_SIGN_NAME);
169 this->signs.ForceResort();
170 this->SortSignsList();
171 this->SetDirty();
175 * This function sets the filter string of the sign list. The contents of
176 * the edit widget is not updated by this function. Depending on if the
177 * new string is zero-length or not the clear button is made
178 * disabled/enabled. The sign list is updated according to the new filter.
180 void SetFilterString(const char *new_filter_string)
182 /* check if there is a new filter string */
183 this->string_filter.SetFilterTerm(new_filter_string);
185 /* Rebuild the list of signs */
186 this->InvalidateData();
189 void OnPaint() override
191 if (!this->IsShaded() && this->signs.NeedRebuild()) this->BuildSortSignList();
192 this->DrawWidgets();
195 void DrawWidget(const Rect &r, WidgetID widget) const override
197 switch (widget) {
198 case WID_SIL_LIST: {
199 Rect tr = r.Shrink(WidgetDimensions::scaled.framerect);
200 uint text_offset_y = (this->resize.step_height - GetCharacterHeight(FS_NORMAL) + 1) / 2;
201 /* No signs? */
202 if (this->vscroll->GetCount() == 0) {
203 DrawString(tr.left, tr.right, tr.top + text_offset_y, STR_STATION_LIST_NONE);
204 return;
207 Dimension d = GetSpriteSize(SPR_COMPANY_ICON);
208 bool rtl = _current_text_dir == TD_RTL;
209 int sprite_offset_y = (this->resize.step_height - d.height + 1) / 2;
210 uint icon_left = rtl ? tr.right - this->text_offset : tr.left;
211 tr = tr.Indent(this->text_offset, rtl);
213 /* At least one sign available. */
214 auto [first, last] = this->vscroll->GetVisibleRangeIterators(this->signs);
215 for (auto it = first; it != last; ++it) {
216 const Sign *si = *it;
218 if (si->owner != OWNER_NONE) DrawCompanyIcon(si->owner, icon_left, tr.top + sprite_offset_y);
220 SetDParam(0, si->index);
221 DrawString(tr.left, tr.right, tr.top + text_offset_y, STR_SIGN_NAME, TC_YELLOW);
222 tr.top += this->resize.step_height;
224 break;
229 void SetStringParameters(WidgetID widget) const override
231 if (widget == WID_SIL_CAPTION) SetDParam(0, this->vscroll->GetCount());
234 void OnClick([[maybe_unused]] Point pt, WidgetID widget, [[maybe_unused]] int click_count) override
236 switch (widget) {
237 case WID_SIL_LIST: {
238 auto it = this->vscroll->GetScrolledItemFromWidget(this->signs, pt.y, this, WID_SIL_LIST, WidgetDimensions::scaled.framerect.top);
239 if (it == this->signs.end()) return;
241 const Sign *si = *it;
242 ScrollMainWindowToTile(TileVirtXY(si->x, si->y));
243 break;
246 case WID_SIL_FILTER_MATCH_CASE_BTN:
247 SignList::match_case = !SignList::match_case; // Toggle match case
248 this->SetWidgetLoweredState(WID_SIL_FILTER_MATCH_CASE_BTN, SignList::match_case); // Toggle button pushed state
249 this->InvalidateData(); // Rebuild the list of signs
250 break;
254 void OnResize() override
256 this->vscroll->SetCapacityFromWidget(this, WID_SIL_LIST, WidgetDimensions::scaled.framerect.Vertical());
259 void UpdateWidgetSize(WidgetID widget, Dimension &size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension &fill, [[maybe_unused]] Dimension &resize) override
261 switch (widget) {
262 case WID_SIL_LIST: {
263 Dimension spr_dim = GetSpriteSize(SPR_COMPANY_ICON);
264 this->text_offset = WidgetDimensions::scaled.frametext.left + spr_dim.width + 2; // 2 pixels space between icon and the sign text.
265 resize.height = std::max<uint>(GetCharacterHeight(FS_NORMAL), spr_dim.height + 2);
266 Dimension d = {(uint)(this->text_offset + WidgetDimensions::scaled.frametext.right), padding.height + 5 * resize.height};
267 size = maxdim(size, d);
268 break;
271 case WID_SIL_CAPTION:
272 SetDParamMaxValue(0, Sign::GetPoolSize(), 3);
273 size = GetStringBoundingBox(STR_SIGN_LIST_CAPTION);
274 size.height += padding.height;
275 size.width += padding.width;
276 break;
280 EventState OnHotkey(int hotkey) override
282 switch (hotkey) {
283 case SLHK_FOCUS_FILTER_BOX:
284 this->SetFocusedWidget(WID_SIL_FILTER_TEXT);
285 SetFocusedWindow(this); // The user has asked to give focus to the text box, so make sure this window is focused.
286 break;
288 default:
289 return ES_NOT_HANDLED;
292 return ES_HANDLED;
295 void OnEditboxChanged(WidgetID widget) override
297 if (widget == WID_SIL_FILTER_TEXT) this->SetFilterString(this->filter_editbox.text.buf);
300 void BuildSortSignList()
302 if (this->signs.NeedRebuild()) {
303 this->BuildSignsList();
304 this->vscroll->SetCount(this->signs.size());
305 this->SetWidgetDirty(WID_SIL_CAPTION);
307 this->SortSignsList();
310 /** Resort the sign listing on a regular interval. */
311 IntervalTimer<TimerWindow> rebuild_interval = {std::chrono::seconds(3), [this](auto) {
312 this->BuildSortSignList();
313 this->SetDirty();
317 * Some data on this window has become invalid.
318 * @param data Information about the changed data.
319 * @param gui_scope Whether the call is done from GUI scope. You may not do everything when not in GUI scope. See #InvalidateWindowData() for details.
321 void OnInvalidateData([[maybe_unused]] int data = 0, [[maybe_unused]] bool gui_scope = true) override
323 /* When there is a filter string, we always need to rebuild the list even if
324 * the amount of signs in total is unchanged, as the subset of signs that is
325 * accepted by the filter might has changed. */
326 if (data == 0 || data == -1 || !this->string_filter.IsEmpty()) { // New or deleted sign, changed visibility setting or there is a filter string
327 /* This needs to be done in command-scope to enforce rebuilding before resorting invalid data */
328 this->signs.ForceRebuild();
329 } else { // Change of sign contents while there is no filter string
330 this->signs.ForceResort();
335 * Handler for global hotkeys of the SignListWindow.
336 * @param hotkey Hotkey
337 * @return ES_HANDLED if hotkey was accepted.
339 static EventState SignListGlobalHotkeys(int hotkey)
341 if (_game_mode == GM_MENU) return ES_NOT_HANDLED;
342 Window *w = ShowSignList();
343 if (w == nullptr) return ES_NOT_HANDLED;
344 return w->OnHotkey(hotkey);
347 static inline HotkeyList hotkeys{"signlist", {
348 Hotkey('F', "focus_filter_box", SLHK_FOCUS_FILTER_BOX),
349 }, SignListGlobalHotkeys};
352 static constexpr NWidgetPart _nested_sign_list_widgets[] = {
353 NWidget(NWID_HORIZONTAL),
354 NWidget(WWT_CLOSEBOX, COLOUR_BROWN),
355 NWidget(WWT_CAPTION, COLOUR_BROWN, WID_SIL_CAPTION), SetDataTip(STR_SIGN_LIST_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
356 NWidget(WWT_SHADEBOX, COLOUR_BROWN),
357 NWidget(WWT_DEFSIZEBOX, COLOUR_BROWN),
358 NWidget(WWT_STICKYBOX, COLOUR_BROWN),
359 EndContainer(),
360 NWidget(NWID_HORIZONTAL),
361 NWidget(NWID_VERTICAL),
362 NWidget(WWT_PANEL, COLOUR_BROWN, WID_SIL_LIST), SetMinimalSize(WidgetDimensions::unscaled.frametext.Horizontal() + 16 + 255, 0),
363 SetResize(1, 1), SetFill(1, 0), SetScrollbar(WID_SIL_SCROLLBAR), EndContainer(),
364 NWidget(NWID_HORIZONTAL),
365 NWidget(WWT_PANEL, COLOUR_BROWN), SetFill(1, 1),
366 NWidget(WWT_EDITBOX, COLOUR_BROWN, WID_SIL_FILTER_TEXT), SetMinimalSize(80, 0), SetResize(1, 0), SetFill(1, 0), SetPadding(2, 2, 2, 2),
367 SetDataTip(STR_LIST_FILTER_OSKTITLE, STR_LIST_FILTER_TOOLTIP),
368 EndContainer(),
369 NWidget(WWT_TEXTBTN, COLOUR_BROWN, WID_SIL_FILTER_MATCH_CASE_BTN), SetDataTip(STR_SIGN_LIST_MATCH_CASE, STR_SIGN_LIST_MATCH_CASE_TOOLTIP),
370 EndContainer(),
371 EndContainer(),
372 NWidget(NWID_VERTICAL),
373 NWidget(NWID_VSCROLLBAR, COLOUR_BROWN, WID_SIL_SCROLLBAR),
374 NWidget(WWT_RESIZEBOX, COLOUR_BROWN),
375 EndContainer(),
376 EndContainer(),
379 static WindowDesc _sign_list_desc(
380 WDP_AUTO, "list_signs", 358, 138,
381 WC_SIGN_LIST, WC_NONE,
383 _nested_sign_list_widgets,
384 &SignListWindow::hotkeys
388 * Open the sign list window
390 * @return newly opened sign list window, or nullptr if the window could not be opened.
392 Window *ShowSignList()
394 return AllocateWindowDescFront<SignListWindow>(_sign_list_desc, 0);
398 * Actually rename the sign.
399 * @param index the sign to rename.
400 * @param text the new name.
401 * @return true if the window will already be removed after returning.
403 static bool RenameSign(SignID index, const char *text)
405 bool remove = StrEmpty(text);
406 Command<CMD_RENAME_SIGN>::Post(StrEmpty(text) ? STR_ERROR_CAN_T_DELETE_SIGN : STR_ERROR_CAN_T_CHANGE_SIGN_NAME, index, text);
407 return remove;
410 struct SignWindow : Window, SignList {
411 QueryString name_editbox;
412 SignID cur_sign;
414 SignWindow(WindowDesc &desc, const Sign *si) : Window(desc), name_editbox(MAX_LENGTH_SIGN_NAME_CHARS * MAX_CHAR_LENGTH, MAX_LENGTH_SIGN_NAME_CHARS)
416 this->querystrings[WID_QES_TEXT] = &this->name_editbox;
417 this->name_editbox.caption = STR_EDIT_SIGN_CAPTION;
418 this->name_editbox.cancel_button = WID_QES_CANCEL;
419 this->name_editbox.ok_button = WID_QES_OK;
421 this->InitNested(WN_QUERY_STRING_SIGN);
423 UpdateSignEditWindow(si);
424 this->SetFocusedWidget(WID_QES_TEXT);
427 void UpdateSignEditWindow(const Sign *si)
429 /* Display an empty string when the sign hasn't been edited yet */
430 if (!si->name.empty()) {
431 SetDParam(0, si->index);
432 this->name_editbox.text.Assign(STR_SIGN_NAME);
433 } else {
434 this->name_editbox.text.DeleteAll();
437 this->cur_sign = si->index;
439 this->SetWidgetDirty(WID_QES_TEXT);
440 this->SetFocusedWidget(WID_QES_TEXT);
444 * Returns a pointer to the (alphabetically) previous or next sign of the current sign.
445 * @param next false if the previous sign is wanted, true if the next sign is wanted
446 * @return pointer to the previous/next sign
448 const Sign *PrevNextSign(bool next)
450 /* Rebuild the sign list */
451 this->signs.ForceRebuild();
452 this->signs.NeedResort();
453 this->BuildSignsList();
454 this->SortSignsList();
456 /* Search through the list for the current sign, excluding
457 * - the first sign if we want the previous sign or
458 * - the last sign if we want the next sign */
459 size_t end = this->signs.size() - (next ? 1 : 0);
460 for (uint i = next ? 0 : 1; i < end; i++) {
461 if (this->cur_sign == this->signs[i]->index) {
462 /* We've found the current sign, so return the sign before/after it */
463 return this->signs[i + (next ? 1 : -1)];
466 /* If we haven't found the current sign by now, return the last/first sign */
467 return next ? this->signs.front() : this->signs.back();
470 void SetStringParameters(WidgetID widget) const override
472 switch (widget) {
473 case WID_QES_CAPTION:
474 SetDParam(0, this->name_editbox.caption);
475 break;
479 void OnClick([[maybe_unused]] Point pt, WidgetID widget, [[maybe_unused]] int click_count) override
481 switch (widget) {
482 case WID_QES_LOCATION: {
483 const Sign *si = Sign::Get(this->cur_sign);
484 TileIndex tile = TileVirtXY(si->x, si->y);
485 if (_ctrl_pressed) {
486 ShowExtraViewportWindow(tile);
487 } else {
488 ScrollMainWindowToTile(tile);
490 break;
493 case WID_QES_PREVIOUS:
494 case WID_QES_NEXT: {
495 const Sign *si = this->PrevNextSign(widget == WID_QES_NEXT);
497 /* Rebuild the sign list */
498 this->signs.ForceRebuild();
499 this->signs.NeedResort();
500 this->BuildSignsList();
501 this->SortSignsList();
503 /* Scroll to sign and reopen window */
504 ScrollMainWindowToTile(TileVirtXY(si->x, si->y));
505 UpdateSignEditWindow(si);
506 break;
509 case WID_QES_DELETE:
510 /* Only need to set the buffer to null, the rest is handled as the OK button */
511 RenameSign(this->cur_sign, "");
512 /* don't delete this, we are deleted in Sign::~Sign() -> DeleteRenameSignWindow() */
513 break;
515 case WID_QES_OK:
516 if (RenameSign(this->cur_sign, this->name_editbox.text.buf)) break;
517 [[fallthrough]];
519 case WID_QES_CANCEL:
520 this->Close();
521 break;
526 static constexpr NWidgetPart _nested_query_sign_edit_widgets[] = {
527 NWidget(NWID_HORIZONTAL),
528 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
529 NWidget(WWT_CAPTION, COLOUR_GREY, WID_QES_CAPTION), SetDataTip(STR_JUST_STRING, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS), SetTextStyle(TC_WHITE),
530 NWidget(WWT_PUSHIMGBTN, COLOUR_GREY, WID_QES_LOCATION), SetAspect(WidgetDimensions::ASPECT_LOCATION), SetDataTip(SPR_GOTO_LOCATION, STR_EDIT_SIGN_LOCATION_TOOLTIP),
531 EndContainer(),
532 NWidget(WWT_PANEL, COLOUR_GREY),
533 NWidget(WWT_EDITBOX, COLOUR_GREY, WID_QES_TEXT), SetMinimalSize(256, 0), SetDataTip(STR_EDIT_SIGN_SIGN_OSKTITLE, STR_NULL), SetPadding(2, 2, 2, 2),
534 EndContainer(),
535 NWidget(NWID_HORIZONTAL),
536 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_QES_OK), SetMinimalSize(61, 12), SetDataTip(STR_BUTTON_OK, STR_NULL),
537 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_QES_CANCEL), SetMinimalSize(60, 12), SetDataTip(STR_BUTTON_CANCEL, STR_NULL),
538 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_QES_DELETE), SetMinimalSize(60, 12), SetDataTip(STR_TOWN_VIEW_DELETE_BUTTON, STR_NULL),
539 NWidget(WWT_PANEL, COLOUR_GREY), SetFill(1, 1), EndContainer(),
540 NWidget(WWT_PUSHARROWBTN, COLOUR_GREY, WID_QES_PREVIOUS), SetMinimalSize(11, 12), SetDataTip(AWV_DECREASE, STR_EDIT_SIGN_PREVIOUS_SIGN_TOOLTIP),
541 NWidget(WWT_PUSHARROWBTN, COLOUR_GREY, WID_QES_NEXT), SetMinimalSize(11, 12), SetDataTip(AWV_INCREASE, STR_EDIT_SIGN_NEXT_SIGN_TOOLTIP),
542 EndContainer(),
545 static WindowDesc _query_sign_edit_desc(
546 WDP_CENTER, nullptr, 0, 0,
547 WC_QUERY_STRING, WC_NONE,
548 WDF_CONSTRUCTION,
549 _nested_query_sign_edit_widgets
553 * Handle clicking on a sign.
554 * @param si The sign that was clicked on.
556 void HandleClickOnSign(const Sign *si)
558 /* If we can't rename the sign, don't even open the rename GUI. */
559 if (!CompanyCanRenameSign(si)) return;
561 if (_ctrl_pressed && (si->owner == _local_company || (si->owner == OWNER_DEITY && _game_mode == GM_EDITOR))) {
562 RenameSign(si->index, "");
563 return;
566 ShowRenameSignWindow(si);
570 * Show the window to change the text of a sign.
571 * @param si The sign to show the window for.
573 void ShowRenameSignWindow(const Sign *si)
575 /* Delete all other edit windows */
576 CloseWindowByClass(WC_QUERY_STRING);
578 new SignWindow(_query_sign_edit_desc, si);
582 * Close the sign window associated with the given sign.
583 * @param sign The sign to close the window for.
585 void DeleteRenameSignWindow(SignID sign)
587 SignWindow *w = dynamic_cast<SignWindow *>(FindWindowById(WC_QUERY_STRING, WN_QUERY_STRING_SIGN));
589 if (w != nullptr && w->cur_sign == sign) w->Close();