OpenTTD Source 20261112-master-gbcbec5e63f
company_gui.cpp
Go to the documentation of this file.
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 <https://www.gnu.org/licenses/old-licenses/gpl-2.0>.
6 */
7
9
10#include "stdafx.h"
11#include "currency_func.h"
12#include "error.h"
13#include "gui.h"
14#include "settings_gui.h"
15#include "window_gui.h"
16#include "textbuf_gui.h"
17#include "viewport_func.h"
18#include "company_func.h"
19#include "command_func.h"
20#include "network/network.h"
22#include "newgrf.h"
24#include "strings_func.h"
26#include "dropdown_type.h"
27#include "tilehighlight_func.h"
28#include "company_base.h"
30#include "object_type.h"
31#include "rail.h"
32#include "road.h"
33#include "window_func.h"
34#include "road_func.h"
35#include "water.h"
36#include "station_func.h"
37#include "company_cmd.h"
38#include "economy_cmd.h"
39#include "group_cmd.h"
40#include "group_gui.h"
41#include "misc_cmd.h"
42#include "object_cmd.h"
43#include "timer/timer.h"
44#include "timer/timer_window.h"
46
48
49#include "table/strings.h"
50
52
53#include "safeguards.h"
54
55
57static void DoSelectCompanyManagerFace(Window *parent);
58static void ShowCompanyInfrastructure(CompanyID company);
59
67
77
79static const std::initializer_list<ExpensesType> _expenses_list_capital_costs = {
83};
84
86struct ExpensesList {
88 const std::initializer_list<ExpensesType> &items;
89
90 ExpensesList(StringID title, const std::initializer_list<ExpensesType> &list) : title(title), items(list)
91 {
92 }
93
94 uint GetHeight() const
95 {
96 /* Add up the height of all the lines. */
97 return static_cast<uint>(this->items.size()) * GetCharacterHeight(FontSize::Normal);
98 }
99
104 uint GetListWidth() const
105 {
106 uint width = 0;
107 for (const ExpensesType &et : this->items) {
108 width = std::max(width, GetStringBoundingBox(STR_FINANCES_SECTION_CONSTRUCTION + to_underlying(et)).width);
109 }
110 return width;
111 }
112};
113
115static const std::initializer_list<ExpensesList> _expenses_list_types = {
116 { STR_FINANCES_REVENUE_TITLE, _expenses_list_revenue },
117 { STR_FINANCES_OPERATING_EXPENSES_TITLE, _expenses_list_operating_costs },
118 { STR_FINANCES_CAPITAL_EXPENSES_TITLE, _expenses_list_capital_costs },
119};
120
126{
127 /* There's an empty line and blockspace on the year row */
128 uint total_height = GetCharacterHeight(FontSize::Normal) + WidgetDimensions::scaled.vsep_wide;
129
130 for (const ExpensesList &list : _expenses_list_types) {
131 /* Title + expense list + total line + total + blockspace after category */
133 }
134
135 /* Total income */
137
138 return total_height;
139}
140
146{
147 uint max_width = GetStringBoundingBox(TimerGameEconomy::UsingWallclockUnits() ? STR_FINANCES_PERIOD_CAPTION : STR_FINANCES_YEAR_CAPTION).width;
148
149 /* Loop through categories to check max widths. */
150 for (const ExpensesList &list : _expenses_list_types) {
151 /* Title of category */
152 max_width = std::max(max_width, GetStringBoundingBox(list.title).width);
153 /* Entries in category */
154 max_width = std::max(max_width, list.GetListWidth() + WidgetDimensions::scaled.hsep_indent);
155 }
156
157 return max_width;
158}
159
166static void DrawCategory(const Rect &r, int start_y, const ExpensesList &list)
167{
169
170 tr.top = start_y;
171
172 for (const ExpensesType &et : list.items) {
173 DrawString(tr, STR_FINANCES_SECTION_CONSTRUCTION + to_underlying(et));
175 }
176}
177
183static void DrawCategories(const Rect &r)
184{
185 int y = r.top;
186 /* Draw description of 12-minute economic period. */
187 DrawString(r.left, r.right, y, (TimerGameEconomy::UsingWallclockUnits() ? STR_FINANCES_PERIOD_CAPTION : STR_FINANCES_YEAR_CAPTION), TextColour::FromString, AlignmentH::Start, true);
189
190 for (const ExpensesList &list : _expenses_list_types) {
191 /* Draw category title and advance y */
192 DrawString(r.left, r.right, y, list.title, TextColour::FromString, AlignmentH::Start);
194
195 /* Draw category items and advance y */
196 DrawCategory(r, y, list);
197 y += list.GetHeight();
198
199 /* Advance y by the height of the horizontal line between amounts and subtotal */
200 y += WidgetDimensions::scaled.vsep_normal;
201
202 /* Draw category total and advance y */
203 DrawString(r.left, r.right, y, STR_FINANCES_TOTAL_CAPTION, TextColour::FromString, AlignmentH::End);
205
206 /* Advance y by a blockspace after this category block */
207 y += WidgetDimensions::scaled.vsep_wide;
208 }
209
210 /* Draw total profit/loss */
211 y += WidgetDimensions::scaled.vsep_normal;
212 DrawString(r.left, r.right, y, STR_FINANCES_PROFIT, TextColour::FromString, AlignmentH::Start);
213}
214
223static void DrawPrice(Money amount, int left, int right, int top, TextColour colour)
224{
225 StringID str = STR_FINANCES_NEGATIVE_INCOME;
226 if (amount == 0) {
227 str = STR_FINANCES_ZERO_INCOME;
228 } else if (amount < 0) {
229 amount = -amount;
230 str = STR_FINANCES_POSITIVE_INCOME;
231 }
232 DrawString(left, right, top, GetString(str, amount), colour, AlignmentH::ForceRight);
233}
234
243static Money DrawYearCategory(const Rect &r, int start_y, const ExpensesList &list, const Expenses &tbl)
244{
245 int y = start_y;
246 Money sum = 0;
247
248 for (const ExpensesType &et : list.items) {
249 Money cost = tbl[et];
250 sum += cost;
251 if (cost != 0) DrawPrice(cost, r.left, r.right, y, TextColour::Black);
253 }
254
255 /* Draw the total at the bottom of the category. */
256 GfxFillRect(r.left, y, r.right, y + WidgetDimensions::scaled.bevel.top - 1, PC_BLACK);
257 y += WidgetDimensions::scaled.vsep_normal;
258 if (sum != 0) DrawPrice(sum, r.left, r.right, y, TextColour::White);
259
260 /* Return the sum for the yearly total. */
261 return sum;
262}
263
264
272static void DrawYearColumn(const Rect &r, TimerGameEconomy::Year year, const Expenses &tbl)
273{
274 int y = r.top;
275 Money sum;
276
277 /* Year header */
278 DrawString(r.left, r.right, y, GetString(STR_FINANCES_YEAR, year), TextColour::FromString, AlignmentH::ForceRight, true);
280
281 /* Categories */
282 for (const ExpensesList &list : _expenses_list_types) {
284 sum += DrawYearCategory(r, y, list, tbl);
285 /* Expense list + expense category title + expense category total + blockspace after category */
286 y += list.GetHeight() + WidgetDimensions::scaled.vsep_normal + GetCharacterHeight(FontSize::Normal) + WidgetDimensions::scaled.vsep_wide;
287 }
288
289 /* Total income. */
290 GfxFillRect(r.left, y, r.right, y + WidgetDimensions::scaled.bevel.top - 1, PC_BLACK);
291 y += WidgetDimensions::scaled.vsep_normal;
292 DrawPrice(sum, r.left, r.right, y, TextColour::White);
293}
294
295static constexpr std::initializer_list<NWidgetPart> _nested_company_finances_widgets = {
299 NWidget(WWT_IMGBTN, Colours::Grey, WID_CF_TOGGLE_SIZE), SetSpriteTip(SPR_LARGE_SMALL_WINDOW, STR_TOOLTIP_TOGGLE_LARGE_SMALL_WINDOW), SetAspect(WidgetDimensions::ASPECT_TOGGLE_SIZE),
302 EndContainer(),
310 EndContainer(),
311 EndContainer(),
312 EndContainer(),
315 NWidget(NWID_VERTICAL), // Vertical column with 'bank balance', 'loan'
316 NWidget(WWT_TEXT, Colours::Invalid), SetStringTip(STR_FINANCES_OWN_FUNDS_TITLE),
317 NWidget(WWT_TEXT, Colours::Invalid), SetStringTip(STR_FINANCES_LOAN_TITLE),
318 NWidget(WWT_TEXT, Colours::Invalid), SetStringTip(STR_FINANCES_BANK_BALANCE_TITLE), SetPadding(WidgetDimensions::unscaled.vsep_normal, 0, 0, 0),
319 EndContainer(),
320 NWidget(NWID_VERTICAL), // Vertical column with bank balance amount, loan amount, and total.
325 EndContainer(),
327 NWidget(NWID_VERTICAL), SetPIPRatio(0, 0, 1), // Max loan information
330 EndContainer(),
331 EndContainer(),
332 EndContainer(),
333 EndContainer(),
336 NWidget(WWT_PUSHTXTBTN, Colours::Grey, WID_CF_INCREASE_LOAN), SetFill(1, 0), SetToolTip(STR_FINANCES_BORROW_TOOLTIP),
337 NWidget(WWT_PUSHTXTBTN, Colours::Grey, WID_CF_REPAY_LOAN), SetFill(1, 0), SetToolTip(STR_FINANCES_REPAY_TOOLTIP),
338 NWidget(WWT_PUSHTXTBTN, Colours::Grey, WID_CF_INFRASTRUCTURE), SetFill(1, 0), SetStringTip(STR_FINANCES_INFRASTRUCTURE_BUTTON, STR_COMPANY_VIEW_INFRASTRUCTURE_TOOLTIP),
339 EndContainer(),
340 EndContainer(),
341};
342
344struct CompanyFinancesWindow : Window {
345 static constexpr int NUM_PERIODS = WID_CF_EXPS_PRICE3 - WID_CF_EXPS_PRICE1 + 1;
346
347 static Money max_money;
348 bool small = false;
349 uint8_t first_visible = NUM_PERIODS - 1;
350
351 CompanyFinancesWindow(WindowDesc &desc, CompanyID company) : Window(desc)
352 {
353 this->CreateNestedTree();
354 this->SetupWidgets();
355 this->FinishInitNested(company);
356
357 this->owner = this->window_number;
358 this->InvalidateData();
359 }
360
361 std::string GetWidgetString(WidgetID widget, StringID stringid) const override
362 {
363 switch (widget) {
364 case WID_CF_CAPTION:
365 return GetString(STR_FINANCES_CAPTION, this->window_number, this->window_number);
366
368 const Company *c = Company::Get(this->window_number);
369 return GetString(STR_FINANCES_BANK_BALANCE, c->money);
370 }
371
372 case WID_CF_LOAN_VALUE: {
373 const Company *c = Company::Get(this->window_number);
374 return GetString(STR_FINANCES_TOTAL_CURRENCY, c->current_loan);
375 }
376
377 case WID_CF_OWN_VALUE: {
378 const Company *c = Company::Get(this->window_number);
379 return GetString(STR_FINANCES_TOTAL_CURRENCY, c->money - c->current_loan);
380 }
381
383 return GetString(STR_FINANCES_INTEREST_RATE, _settings_game.difficulty.initial_interest);
384
386 const Company *c = Company::Get(this->window_number);
387 return GetString(STR_FINANCES_MAX_LOAN, c->GetMaxLoan());
388 }
389
391 return GetString(STR_FINANCES_BORROW_BUTTON, LOAN_INTERVAL);
392
394 return GetString(STR_FINANCES_REPAY_BUTTON, LOAN_INTERVAL);
395
396 default:
397 return this->Window::GetWidgetString(widget, stringid);
398 }
399 }
400
401 void UpdateWidgetSize(WidgetID widget, Dimension &size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension &fill, [[maybe_unused]] Dimension &resize) override
402 {
403 switch (widget) {
407 break;
408
413 [[fallthrough]];
414
417 case WID_CF_OWN_VALUE: {
419 size.width = std::max(GetStringBoundingBox(GetString(STR_FINANCES_NEGATIVE_INCOME, max_value)).width, GetStringBoundingBox(GetString(STR_FINANCES_POSITIVE_INCOME, max_value)).width);
420 size.width += padding.width;
421 break;
422 }
423
426 break;
427 }
428 }
429
430 void DrawWidget(const Rect &r, WidgetID widget) const override
431 {
432 switch (widget) {
435 break;
436
439 case WID_CF_EXPS_PRICE3: {
440 int period = widget - WID_CF_EXPS_PRICE1;
441 if (period < this->first_visible) break;
442
443 const Company *c = Company::Get(this->window_number);
444 const auto &expenses = c->yearly_expenses[NUM_PERIODS - period - 1];
445 DrawYearColumn(r, TimerGameEconomy::year - (NUM_PERIODS - period - 1), expenses);
446 break;
447 }
448
450 GfxFillRect(r.left, r.top, r.right, r.top + WidgetDimensions::scaled.bevel.top - 1, PC_BLACK);
451 break;
452 }
453 }
454
460 {
461 int plane = this->small ? SZSP_NONE : 0;
462 this->GetWidget<NWidgetStacked>(WID_CF_SEL_PANEL)->SetDisplayedPlane(plane);
463 this->GetWidget<NWidgetStacked>(WID_CF_SEL_MAXLOAN)->SetDisplayedPlane(plane);
464
465 CompanyID company = this->window_number;
466 plane = (company != _local_company) ? SZSP_NONE : 0;
467 this->GetWidget<NWidgetStacked>(WID_CF_SEL_BUTTONS)->SetDisplayedPlane(plane);
468 }
469
470 void OnPaint() override
471 {
472 if (!this->IsShaded()) {
473 if (!this->small) {
474 /* Check that the expenses panel height matches the height needed for the layout. */
476 this->SetupWidgets();
477 this->ReInit();
478 return;
479 }
480 }
481
482 /* Check that the loan buttons are shown only when the user owns the company. */
483 CompanyID company = this->window_number;
484 int req_plane = (company != _local_company) ? SZSP_NONE : 0;
485 if (req_plane != this->GetWidget<NWidgetStacked>(WID_CF_SEL_BUTTONS)->shown_plane) {
486 this->SetupWidgets();
487 this->ReInit();
488 return;
489 }
490
491 const Company *c = Company::Get(company);
492 this->SetWidgetDisabledState(WID_CF_INCREASE_LOAN, c->current_loan >= c->GetMaxLoan()); // Borrow button only shows when there is any more money to loan.
493 this->SetWidgetDisabledState(WID_CF_REPAY_LOAN, company != _local_company || c->current_loan == 0); // Repay button only shows when there is any more money to repay.
494 }
495
496 this->DrawWidgets();
497 }
498
499 void OnClick([[maybe_unused]] Point pt, WidgetID widget, [[maybe_unused]] int click_count) override
500 {
501 switch (widget) {
502 case WID_CF_TOGGLE_SIZE: // toggle size
503 this->small = !this->small;
504 this->SetupWidgets();
505 if (this->IsShaded()) {
506 /* Finances window is not resizable, so size hints given during unshading have no effect
507 * on the changed appearance of the window. */
508 this->SetShaded(false);
509 } else {
510 this->ReInit();
511 }
512 break;
513
514 case WID_CF_INCREASE_LOAN: // increase loan
515 Command<Commands::IncreaseLoan>::Post(STR_ERROR_CAN_T_BORROW_ANY_MORE_MONEY, IsCtrlPressed() ? LoanCommand::Max : LoanCommand::Interval, 0);
516 break;
517
518 case WID_CF_REPAY_LOAN: // repay loan
519 Command<Commands::DecreaseLoan>::Post(STR_ERROR_CAN_T_REPAY_LOAN, IsCtrlPressed() ? LoanCommand::Max : LoanCommand::Interval, 0);
520 break;
521
522 case WID_CF_INFRASTRUCTURE: // show infrastructure details
524 break;
525 }
526 }
527
528 void RefreshVisibleColumns()
529 {
530 for (uint period = 0; period < this->first_visible; ++period) {
531 const Company *c = Company::Get(this->window_number);
532 const Expenses &expenses = c->yearly_expenses[NUM_PERIODS - period - 1];
533 /* Show expenses column if it has any non-zero value in it. */
534 if (std::ranges::any_of(expenses, [](const Money &value) { return value != 0; })) {
535 this->first_visible = period;
536 break;
537 }
538 }
539 }
540
541 void OnInvalidateData(int, bool) override
542 {
543 this->RefreshVisibleColumns();
544 }
545
550 const IntervalTimer<TimerWindow> rescale_interval = {std::chrono::seconds(3), [this](auto) {
551 const Company *c = Company::Get(this->window_number);
554 this->SetupWidgets();
555 this->ReInit();
556 }
557 }};
558};
559
561Money CompanyFinancesWindow::max_money = INT32_MAX;
562
565 WindowPosition::Automatic, "company_finances", 0, 0,
566 WindowClass::Finances, WindowClass::None,
567 {},
568 _nested_company_finances_widgets
569);
570
576void ShowCompanyFinances(CompanyID company)
577{
578 if (!Company::IsValidID(company)) return;
579 if (BringWindowToFrontById(WindowClass::Finances, company)) return;
580
582}
583
593
598template <SpriteID TSprite = SPR_SQUARE>
599class DropDownListColourItem : public DropDownIcon<DropDownString<DropDownListItem>> {
600public:
601 DropDownListColourItem(int colour, bool masked) :
602 DropDownIcon<DropDownString<DropDownListItem>>(TSprite, GetColourPalette(static_cast<Colours>(colour % to_underlying(Colours::End))), GetString(colour < to_underlying(Colours::End) ? (STR_COLOUR_DARK_BLUE + colour) : STR_COLOUR_DEFAULT), colour, masked)
603
604 {
605 }
606};
607
614constexpr uint8_t GetColourOffset(const Livery &l, bool primary)
615{
616 return to_underlying(primary ? l.colour1 : l.colour2);
617}
618
620struct SelectCompanyLiveryWindow : public Window {
621private:
622 struct {
624 GroupID group = GroupID::Invalid();
625 } sel{};
626 LiveryClass livery_class{};
627 Dimension square{};
628 uint rows = 0;
629 uint line_height = 0;
630 GUIGroupList groups{};
631 Scrollbar *vscroll = nullptr;
633
634 void ShowColourDropDownMenu(uint32_t widget)
635 {
637 const Livery *livery, *default_livery = nullptr;
638 bool primary = widget == WID_SCL_PRI_COL_DROPDOWN;
639 uint8_t default_col{};
640
641 /* Disallow other company colours for the primary colour */
642 if (this->livery_class < LiveryClass::GroupRail && this->sel.schemes.Test(LiveryScheme::Default) && primary) {
643 for (const Company *c : Company::Iterate()) {
644 if (c->index != _local_company) used_colours.Set(c->colour);
645 }
646 }
647
648 const Company *c = Company::Get(this->window_number);
649
650 if (this->livery_class < LiveryClass::GroupRail) {
651 /* Get the first selected livery to use as the default dropdown item */
652 LiveryScheme scheme = this->sel.schemes.GetNthSetBit(0).value_or(LiveryScheme::Default);
653 livery = &c->livery[scheme];
654 if (scheme != LiveryScheme::Default) default_livery = &c->livery[LiveryScheme::Default];
655 } else {
656 const Group *g = Group::Get(this->sel.group);
657 livery = &g->livery;
658 if (g->parent == GroupID::Invalid()) {
659 default_livery = &c->livery[LiveryScheme::Default];
660 } else {
661 const Group *pg = Group::Get(g->parent);
662 default_livery = &pg->livery;
663 }
664 }
665
666 DropDownList list;
667 if (default_livery != nullptr) {
668 /* Add Colours::End to put the colour out of range, but also allow us to show what the default is */
669 default_col = GetColourOffset(*default_livery, primary) + to_underlying(Colours::End);
670 list.push_back(std::make_unique<DropDownListColourItem<>>(default_col, false));
671 }
672 for (Colours colour : EnumRange(Colours::End)) {
673 list.push_back(std::make_unique<DropDownListColourItem<>>(to_underlying(colour), used_colours.Test(colour)));
674 }
675
676 uint8_t sel;
677 if (default_livery == nullptr || livery->in_use.Test(primary ? Livery::Flag::Primary : Livery::Flag::Secondary)) {
678 sel = GetColourOffset(*livery, primary);
679 } else {
680 sel = default_col;
681 }
682 ShowDropDownList(this, std::move(list), sel, widget);
683 }
684
687 {
688 visible_schemes.Reset();
689 for (LiveryScheme scheme : _loaded_newgrf_features.used_liveries) {
690 if (_livery_class[scheme] != this->livery_class) continue;
691 visible_schemes.Set(scheme);
692 }
693 }
694
695 void BuildGroupList(CompanyID owner)
696 {
697 if (!this->groups.NeedRebuild()) return;
698
699 this->groups.clear();
700
701 if (this->livery_class >= LiveryClass::GroupRail) {
702 VehicleType vtype = static_cast<VehicleType>(this->livery_class - LiveryClass::GroupRail);
703 BuildGuiGroupList(this->groups, false, owner, vtype);
704 }
705
706 this->groups.RebuildDone();
707 }
708
709 void SetRows()
710 {
711 if (this->livery_class < LiveryClass::GroupRail) {
712 this->rows = this->visible_schemes.Count();
713 } else {
714 this->rows = (uint)this->groups.size();
715 }
716
717 this->vscroll->SetCount(this->rows);
718 }
719
720public:
721 SelectCompanyLiveryWindow(WindowDesc &desc, CompanyID company, GroupID group) : Window(desc)
722 {
723 this->CreateNestedTree();
725 this->vscroll = this->GetScrollbar(WID_SCL_MATRIX_SCROLLBAR);
726
727 if (group == GroupID::Invalid()) {
728 this->livery_class = LiveryClass::Other;
729 this->sel.schemes = LiveryScheme::Default;
731 this->BuildLiveryList();
732 this->BuildGroupList(company);
733 this->SetRows();
734 } else {
735 this->SetSelectedGroup(company, group);
736 }
737
738 this->FinishInitNested(company);
739 this->owner = company;
740 this->InvalidateData(1);
741 }
742
743 void SetSelectedGroup(CompanyID company, GroupID group)
744 {
745 this->RaiseWidget(WID_SCL_CLASS_GENERAL + this->livery_class);
746 const Group *g = Group::Get(group);
747 switch (g->vehicle_type) {
748 case VehicleType::Train: this->livery_class = LiveryClass::GroupRail; break;
749 case VehicleType::Road: this->livery_class = LiveryClass::GroupRoad; break;
750 case VehicleType::Ship: this->livery_class = LiveryClass::GroupShip; break;
751 case VehicleType::Aircraft: this->livery_class = LiveryClass::GroupAircraft; break;
752 default: NOT_REACHED();
753 }
754 this->sel.group = group;
755 this->LowerWidget(WID_SCL_CLASS_GENERAL + this->livery_class);
756
757 this->groups.ForceRebuild();
758 this->BuildGroupList(company);
759 this->SetRows();
760
761 /* Position scrollbar to selected group */
762 for (uint i = 0; i < this->rows; i++) {
763 if (this->groups[i].group->index == this->sel.group) {
764 this->vscroll->SetPosition(i - this->vscroll->GetCapacity() / 2);
765 break;
766 }
767 }
768 }
769
770 void UpdateWidgetSize(WidgetID widget, Dimension &size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension &fill, [[maybe_unused]] Dimension &resize) override
771 {
772 switch (widget) {
774 /* The matrix widget below needs enough room to print all the schemes. */
775 Dimension d = {0, 0};
776 for (LiveryScheme scheme : _loaded_newgrf_features.used_liveries) {
777 d = maxdim(d, GetStringBoundingBox(STR_LIVERY_DEFAULT + to_underlying(scheme)));
778 }
779
780 size.width = std::max(size.width, 5 + d.width + padding.width);
781 break;
782 }
783
784 case WID_SCL_MATRIX: {
785 /* 11 items in the default rail class */
786 this->square = GetSpriteSize(SPR_SQUARE);
787 this->line_height = std::max(this->square.height, (uint)GetCharacterHeight(FontSize::Normal)) + padding.height;
788
789 size.height = 5 * this->line_height;
790 resize.width = 1;
791 fill.height = resize.height = this->line_height;
792 break;
793 }
794
796 if (!_loaded_newgrf_features.has_2CC) break;
797 [[fallthrough]];
798
800 this->square = GetSpriteSize(SPR_SQUARE);
801 int string_padding = this->square.width + WidgetDimensions::scaled.hsep_normal + padding.width;
802 for (Colours colour : EnumRange(Colours::End)) {
803 size.width = std::max(size.width, GetStringBoundingBox(STR_COLOUR_DARK_BLUE + to_underlying(colour)).width + string_padding);
804 }
805 size.width = std::max(size.width, GetStringBoundingBox(STR_COLOUR_DEFAULT).width + string_padding);
806 break;
807 }
808 }
809 }
810
811 void OnPaint() override
812 {
813 bool local = this->window_number == _local_company;
814
815 /* Disable dropdown controls if no scheme is selected */
816 bool disabled = this->livery_class < LiveryClass::GroupRail ? this->sel.schemes.None() : (this->sel.group == GroupID::Invalid());
817 this->SetWidgetDisabledState(WID_SCL_PRI_COL_DROPDOWN, !local || disabled);
818 this->SetWidgetDisabledState(WID_SCL_SEC_COL_DROPDOWN, !local || disabled);
819
820 this->BuildGroupList(this->window_number);
821
822 this->DrawWidgets();
823 }
824
825 std::string GetWidgetString(WidgetID widget, StringID stringid) const override
826 {
827 switch (widget) {
828 case WID_SCL_CAPTION:
829 return GetString(STR_LIVERY_CAPTION, this->window_number);
830
833 const Company *c = Company::Get(this->window_number);
834 bool primary = widget == WID_SCL_PRI_COL_DROPDOWN;
835 StringID colour = STR_COLOUR_DEFAULT;
836
837 if (this->livery_class < LiveryClass::GroupRail) {
838 LiveryScheme scheme = this->sel.schemes.GetNthSetBit(0).value_or(LiveryScheme::End);
839 if (scheme != LiveryScheme::End) {
840 const Livery &livery = c->livery[scheme];
842 colour = STR_COLOUR_DARK_BLUE + GetColourOffset(livery, primary);
843 }
844 }
845 } else {
846 if (this->sel.group != GroupID::Invalid()) {
847 const Group *g = Group::Get(this->sel.group);
848 const Livery &livery = g->livery;
850 colour = STR_COLOUR_DARK_BLUE + GetColourOffset(livery, primary);
851 }
852 }
853 }
854 return GetString(colour);
855 }
856
857 default:
858 return this->Window::GetWidgetString(widget, stringid);
859 }
860 }
861
862 void DrawWidget(const Rect &r, WidgetID widget) const override
863 {
864 if (widget != WID_SCL_MATRIX) return;
865
866 bool rtl = _current_text_dir == TD_RTL;
867
868 /* Coordinates of scheme name column. */
870 Rect sch = nwi->GetCurrentRect().Shrink(WidgetDimensions::scaled.framerect);
871 /* Coordinates of first dropdown. */
873 Rect pri = nwi->GetCurrentRect().Shrink(WidgetDimensions::scaled.framerect);
874 /* Coordinates of second dropdown. */
876 Rect sec = nwi->GetCurrentRect().Shrink(WidgetDimensions::scaled.framerect);
877
878 Rect pri_squ = pri.WithWidth(this->square.width, rtl);
879 Rect sec_squ = sec.WithWidth(this->square.width, rtl);
880
881 pri = pri.Indent(this->square.width + WidgetDimensions::scaled.hsep_normal, rtl);
882 sec = sec.Indent(this->square.width + WidgetDimensions::scaled.hsep_normal, rtl);
883
884 Rect ir = r.WithHeight(this->resize.step_height).Shrink(WidgetDimensions::scaled.matrix);
885 int square_offs = (ir.Height() - this->square.height) / 2;
886 int text_offs = (ir.Height() - GetCharacterHeight(FontSize::Normal)) / 2;
887
888 int y = ir.top;
889
890 /* Helper function to draw livery info. */
891 auto draw_livery = [&](std::string_view str, const Livery &livery, bool is_selected, bool is_default_scheme, int indent) {
892 /* Livery Label. */
893 DrawString(sch.left + (rtl ? 0 : indent), sch.right - (rtl ? indent : 0), y + text_offs, str, is_selected ? TextColour::White : TextColour::Black);
894
895 /* Text below the first dropdown. */
896 DrawSprite(SPR_SQUARE, GetColourPalette(livery.colour1), pri_squ.left, y + square_offs);
897 DrawString(pri.left, pri.right, y + text_offs, (is_default_scheme || livery.in_use.Test(Livery::Flag::Primary)) ? STR_COLOUR_DARK_BLUE + to_underlying(livery.colour1) : STR_COLOUR_DEFAULT, is_selected ? TextColour::White : TextColour::Gold);
898
899 /* Text below the second dropdown. */
900 if (sec.right > sec.left) { // Second dropdown has non-zero size.
901 DrawSprite(SPR_SQUARE, GetColourPalette(livery.colour2), sec_squ.left, y + square_offs);
902 DrawString(sec.left, sec.right, y + text_offs, (is_default_scheme || livery.in_use.Test(Livery::Flag::Secondary)) ? STR_COLOUR_DARK_BLUE + to_underlying(livery.colour2) : STR_COLOUR_DEFAULT, is_selected ? TextColour::White : TextColour::Gold);
903 }
904
905 y += this->line_height;
906 };
907
908 const Company *c = Company::Get(this->window_number);
909
910 if (livery_class < LiveryClass::GroupRail) {
911 int pos = this->vscroll->GetPosition();
912 for (LiveryScheme scheme : this->visible_schemes) {
913 if (pos-- > 0) continue;
914 draw_livery(GetString(STR_LIVERY_DEFAULT + to_underlying(scheme)), c->livery[scheme], this->sel.schemes.Test(scheme), scheme == LiveryScheme::Default, 0);
915 }
916 } else {
917 auto [first, last] = this->vscroll->GetVisibleRangeIterators(this->groups);
918 for (auto it = first; it != last; ++it) {
919 const Group *g = it->group;
920 draw_livery(GetString(STR_GROUP_NAME, g->index), g->livery, this->sel.group == g->index, false, it->indent * WidgetDimensions::scaled.hsep_indent);
921 }
922
923 if (this->vscroll->GetCount() == 0) {
924 constexpr VehicleTypeIndexArray<const StringID> empty_labels = { STR_LIVERY_TRAIN_GROUP_EMPTY, STR_LIVERY_ROAD_VEHICLE_GROUP_EMPTY, STR_LIVERY_SHIP_GROUP_EMPTY, STR_LIVERY_AIRCRAFT_GROUP_EMPTY };
925 VehicleType vtype = static_cast<VehicleType>(this->livery_class - LiveryClass::GroupRail);
926 DrawString(ir.left, ir.right, y + text_offs, empty_labels[vtype], TextColour::Black);
927 }
928 }
929 }
930
931 void OnClick([[maybe_unused]] Point pt, WidgetID widget, [[maybe_unused]] int click_count) override
932 {
933 switch (widget) {
934 /* Livery Class buttons */
944 this->RaiseWidget(WID_SCL_CLASS_GENERAL + this->livery_class);
945 this->livery_class = static_cast<LiveryClass>(widget - WID_SCL_CLASS_GENERAL);
946 this->LowerWidget(WID_SCL_CLASS_GENERAL + this->livery_class);
947
948 /* Select the first item in the list */
949 if (this->livery_class < LiveryClass::GroupRail) {
950 this->BuildLiveryList();
951 this->sel.schemes = this->visible_schemes.GetNthSetBit(0).value_or(LiveryScheme::Default);
952 } else {
953 this->sel.group = GroupID::Invalid();
954 this->groups.ForceRebuild();
955 this->BuildGroupList(this->window_number);
956
957 if (!this->groups.empty()) {
958 this->sel.group = this->groups[0].group->index;
959 }
960 }
961
962 this->SetRows();
963 this->SetDirty();
964 break;
965
966 case WID_SCL_PRI_COL_DROPDOWN: // First colour dropdown
967 ShowColourDropDownMenu(WID_SCL_PRI_COL_DROPDOWN);
968 break;
969
970 case WID_SCL_SEC_COL_DROPDOWN: // Second colour dropdown
971 ShowColourDropDownMenu(WID_SCL_SEC_COL_DROPDOWN);
972 break;
973
974 case WID_SCL_MATRIX: {
975 if (this->livery_class < LiveryClass::GroupRail) {
976 uint row = this->vscroll->GetScrolledRowFromWidget(pt.y, this, widget);
977 if (row >= this->rows) return;
978
979 LiveryScheme scheme = this->visible_schemes.GetNthSetBit(row).value();
980
981 if (IsCtrlPressed()) {
982 this->sel.schemes.Flip(scheme);
983 } else {
984 this->sel.schemes = scheme;
985 }
986 } else {
987 auto it = this->vscroll->GetScrolledItemFromWidget(this->groups, pt.y, this, widget);
988 if (it == std::end(this->groups)) return;
989
990 this->sel.group = it->group->index;
991 }
992 this->SetDirty();
993 break;
994 }
995 }
996 }
997
998 void OnResize() override
999 {
1000 this->vscroll->SetCapacityFromWidget(this, WID_SCL_MATRIX);
1001 }
1002
1003 void OnDropdownSelect(WidgetID widget, int index, int) override
1004 {
1005 bool local = this->window_number == _local_company;
1006 if (!local) return;
1007
1008 Colours colour = static_cast<Colours>(index);
1009 if (colour >= Colours::End) colour = Colours::Invalid;
1010
1011 if (this->livery_class < LiveryClass::GroupRail) {
1012 /* Set company colour livery */
1013 for (LiveryScheme scheme : this->visible_schemes) {
1014 /* Changed colour for the selected scheme, or all visible schemes if CTRL is pressed. */
1015 if (this->sel.schemes.Test(scheme) || IsCtrlPressed()) {
1016 Command<Commands::SetCompanyColour>::Post(scheme, widget == WID_SCL_PRI_COL_DROPDOWN, colour);
1017 }
1018 }
1019 } else {
1020 /* Setting group livery */
1021 Command<Commands::SetGroupLivery>::Post(this->sel.group, widget == WID_SCL_PRI_COL_DROPDOWN, colour);
1022 }
1023 }
1024
1030 void OnInvalidateData([[maybe_unused]] int data = 0, [[maybe_unused]] bool gui_scope = true) override
1031 {
1032 if (!gui_scope) return;
1033
1034 if (data != -1) {
1035 /* data contains a VehicleType, rebuild list if it is displayed */
1036 if (this->livery_class == static_cast<LiveryClass>(to_underlying(LiveryClass::GroupRail) + data)) {
1037 this->groups.ForceRebuild();
1038 this->BuildGroupList(this->window_number);
1039 this->SetRows();
1040
1041 if (!Group::IsValidID(this->sel.group)) {
1042 this->sel.group = GroupID::Invalid();
1043 if (!this->groups.empty()) this->sel.group = this->groups[0].group->index;
1044 }
1045
1046 this->SetDirty();
1047 }
1048 return;
1049 }
1050
1052
1053 bool current_class_valid = this->livery_class == LiveryClass::Other || this->livery_class >= LiveryClass::GroupRail;
1054 if (_settings_client.gui.liveries == LIT_ALL || (_settings_client.gui.liveries == LIT_COMPANY && this->window_number == _local_company)) {
1055 /* Clear selection of unused schemes. */
1056 this->sel.schemes &= _loaded_newgrf_features.used_liveries;
1057 for (LiveryScheme scheme : _loaded_newgrf_features.used_liveries) {
1058 if (_livery_class[scheme] == this->livery_class) current_class_valid = true;
1060 }
1061 }
1062
1063 if (!current_class_valid) {
1064 Point pt = {0, 0};
1065 this->OnClick(pt, WID_SCL_CLASS_GENERAL, 1);
1066 }
1067 }
1068};
1069
1070static constexpr std::initializer_list<NWidgetPart> _nested_select_company_livery_widgets = {
1077 EndContainer(),
1084 NWidget(WWT_IMGBTN, Colours::Grey, WID_SCL_GROUPS_RAIL), SetToolbarMinimalSize(1), SetFill(0, 1), SetSpriteTip(SPR_GROUP_LIVERY_TRAIN, STR_LIVERY_TRAIN_GROUP_TOOLTIP),
1085 NWidget(WWT_IMGBTN, Colours::Grey, WID_SCL_GROUPS_ROAD), SetToolbarMinimalSize(1), SetFill(0, 1), SetSpriteTip(SPR_GROUP_LIVERY_ROADVEH, STR_LIVERY_ROAD_VEHICLE_GROUP_TOOLTIP),
1086 NWidget(WWT_IMGBTN, Colours::Grey, WID_SCL_GROUPS_SHIP), SetToolbarMinimalSize(1), SetFill(0, 1), SetSpriteTip(SPR_GROUP_LIVERY_SHIP, STR_LIVERY_SHIP_GROUP_TOOLTIP),
1087 NWidget(WWT_IMGBTN, Colours::Grey, WID_SCL_GROUPS_AIRCRAFT), SetToolbarMinimalSize(1), SetFill(0, 1), SetSpriteTip(SPR_GROUP_LIVERY_AIRCRAFT, STR_LIVERY_AIRCRAFT_GROUP_TOOLTIP),
1089 EndContainer(),
1093 EndContainer(),
1096 NWidget(WWT_DROPDOWN, Colours::Grey, WID_SCL_PRI_COL_DROPDOWN), SetFill(0, 1), SetToolTip(STR_LIVERY_PRIMARY_TOOLTIP),
1098 NWidget(WWT_DROPDOWN, Colours::Grey, WID_SCL_SEC_COL_DROPDOWN), SetFill(0, 1), SetToolTip(STR_LIVERY_SECONDARY_TOOLTIP),
1099 EndContainer(),
1101 EndContainer(),
1102};
1103
1106 WindowPosition::Automatic, "company_colour_scheme", 0, 0,
1107 WindowClass::CompanyLivery, WindowClass::None,
1108 {},
1109 _nested_select_company_livery_widgets
1110);
1111
1112void ShowCompanyLiveryWindow(CompanyID company, GroupID group)
1113{
1114 SelectCompanyLiveryWindow *w = (SelectCompanyLiveryWindow *)BringWindowToFrontById(WindowClass::CompanyLivery, company);
1115 if (w == nullptr) {
1117 } else if (group != GroupID::Invalid()) {
1118 w->SetSelectedGroup(company, group);
1119 }
1120}
1121
1128void DrawCompanyManagerFace(const CompanyManagerFace &cmf, Colours colour, const Rect &r)
1129{
1130 /* Determine offset from centre of drawing rect. */
1132 int x = CentreBounds(r.left, r.right, d.width);
1133 int y = CentreBounds(r.top, r.bottom, d.height);
1134
1135 FaceVars vars = GetCompanyManagerFaceVars(cmf.style);
1136
1137 /* First determine which parts are enabled. */
1138 uint64_t active_vars = GetActiveFaceVars(cmf, vars);
1139
1140 std::unordered_map<uint8_t, PaletteID> palettes;
1141
1142 /* Second, get palettes. */
1143 for (auto var : SetBitIterator(active_vars)) {
1144 if (vars[var].type != FaceVarType::Palette) continue;
1145
1146 PaletteID pal = PAL_NONE;
1147 switch (vars[var].GetBits(cmf)) {
1148 default: NOT_REACHED();
1149 case 0: pal = PALETTE_TO_BROWN; break;
1150 case 1: pal = PALETTE_TO_BLUE; break;
1151 case 2: pal = PALETTE_TO_GREEN; break;
1152 }
1153 for (uint8_t affected_var : SetBitIterator(std::get<uint64_t>(vars[var].data))) {
1154 palettes[affected_var] = pal;
1155 }
1156 }
1157
1158 /* Draw the gradient (background) */
1160
1161 /* Thirdly, draw sprites. */
1162 for (auto var : SetBitIterator(active_vars)) {
1163 if (vars[var].type != FaceVarType::Sprite) continue;
1164
1165 auto it = palettes.find(var);
1166 PaletteID pal = (it == std::end(palettes)) ? PAL_NONE : it->second;
1167 DrawSprite(vars[var].GetSprite(cmf), pal, x, y);
1168 }
1169}
1170
1172static constexpr std::initializer_list<NWidgetPart> _nested_select_company_manager_face_widgets = {
1175 NWidget(WWT_CAPTION, Colours::Grey, WID_SCMF_CAPTION), SetStringTip(STR_FACE_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
1176 NWidget(WWT_IMGBTN, Colours::Grey, WID_SCMF_TOGGLE_LARGE_SMALL), SetSpriteTip(SPR_LARGE_SMALL_WINDOW, STR_FACE_ADVANCED_TOOLTIP), SetAspect(WidgetDimensions::ASPECT_TOGGLE_SIZE),
1177 EndContainer(),
1180 /* Left side */
1183 NWidget(WWT_PUSHTXTBTN, Colours::Grey, WID_SCMF_RANDOM_NEW_FACE), SetFill(1, 0), SetStringTip(STR_FACE_NEW_FACE_BUTTON, STR_FACE_NEW_FACE_TOOLTIP),
1184 NWidget(WWT_PUSHTXTBTN, Colours::Grey, WID_SCMF_TOGGLE_LARGE_SMALL_BUTTON), SetFill(1, 0), SetStringTip(STR_FACE_ADVANCED, STR_FACE_ADVANCED_TOOLTIP),
1185 NWidget(NWID_SELECTION, Colours::Invalid, WID_SCMF_SEL_LOADSAVE), // Load/number/save buttons under the portrait in the advanced view.
1187 NWidget(NWID_SPACER), SetFill(1, 1), SetResize(0, 1),
1188 NWidget(WWT_PUSHTXTBTN, Colours::Grey, WID_SCMF_LOAD), SetFill(1, 0), SetStringTip(STR_FACE_LOAD, STR_FACE_LOAD_TOOLTIP),
1189 NWidget(WWT_PUSHTXTBTN, Colours::Grey, WID_SCMF_FACECODE), SetFill(1, 0), SetStringTip(STR_FACE_FACECODE, STR_FACE_FACECODE_TOOLTIP),
1190 NWidget(WWT_PUSHTXTBTN, Colours::Grey, WID_SCMF_SAVE), SetFill(1, 0), SetStringTip(STR_FACE_SAVE, STR_FACE_SAVE_TOOLTIP),
1191 EndContainer(),
1192 EndContainer(),
1193 EndContainer(),
1194 EndContainer(),
1195 /* Right side */
1196 NWidget(NWID_SELECTION, Colours::Invalid, WID_SCMF_SEL_PARTS), // Advanced face parts setting.
1202 EndContainer(),
1203 EndContainer(),
1204 EndContainer(),
1205 EndContainer(),
1207 NWidget(WWT_PUSHTXTBTN, Colours::Grey, WID_SCMF_CANCEL), SetFill(1, 0), SetResize(1, 0), SetStringTip(STR_BUTTON_CANCEL, STR_FACE_CANCEL_TOOLTIP),
1208 NWidget(WWT_PUSHTXTBTN, Colours::Grey, WID_SCMF_ACCEPT), SetFill(1, 0), SetResize(1, 0), SetStringTip(STR_BUTTON_OK, STR_FACE_OK_TOOLTIP),
1211 EndContainer(),
1212 EndContainer(),
1213};
1214
1216class SelectCompanyManagerFaceWindow : public Window
1217{
1219 bool advanced = false;
1220 uint selected_var = UINT_MAX;
1221 uint click_state = 0;
1222 int line_height = 0;
1223
1224 std::vector<const FaceVar *> face_vars;
1225
1230 {
1231 FaceVars vars = GetCompanyManagerFaceVars(this->face.style);
1232 ScaleAllCompanyManagerFaceBits(this->face, vars);
1233
1234 uint64_t active_vars = GetActiveFaceVars(this->face, vars);
1235 /* Exclude active parts which have no string. */
1236 for (auto var : SetBitIterator(active_vars)) {
1237 if (vars[var].name == STR_NULL) ClrBit(active_vars, var);
1238 }
1239
1240 /* Rebuild the sorted list of face variable pointers. */
1241 this->face_vars.clear();
1242 for (auto var : SetBitIterator(active_vars)) {
1243 this->face_vars.emplace_back(&vars[var]);
1244 }
1245 std::ranges::sort(this->face_vars, std::less{}, &FaceVar::position);
1246
1247 this->GetScrollbar(WID_SCMF_PARTS_SCROLLBAR)->SetCount(std::size(this->face_vars));
1248 }
1249
1250public:
1252 {
1253 this->CreateNestedTree();
1254 this->SelectDisplayPlanes(this->advanced);
1255 this->FinishInitNested(parent->window_number);
1256 this->parent = parent;
1257 this->owner = this->window_number;
1258 this->face = Company::Get(this->window_number)->face;
1259
1260 this->UpdateData();
1261 }
1262
1263 void OnInit() override
1264 {
1265 this->line_height = std::max(SETTING_BUTTON_HEIGHT, GetCharacterHeight(FontSize::Normal)) + WidgetDimensions::scaled.matrix.Vertical();
1266 }
1267
1273 {
1275 this->GetWidget<NWidgetStacked>(WID_SCMF_SEL_PARTS)->SetDisplayedPlane(advanced ? 0 : SZSP_NONE);
1276 this->GetWidget<NWidgetStacked>(WID_SCMF_SEL_RESIZE)->SetDisplayedPlane(advanced ? 0 : SZSP_NONE);
1277
1279 if (advanced) {
1280 wi->SetStringTip(STR_FACE_SIMPLE, STR_FACE_SIMPLE_TOOLTIP);
1281 } else {
1282 wi->SetStringTip(STR_FACE_ADVANCED, STR_FACE_ADVANCED_TOOLTIP);
1283 }
1284 }
1285
1286 static StringID GetLongestString(StringID a, StringID b)
1287 {
1289 }
1290
1291 static uint GetMaximumFacePartsWidth()
1292 {
1293 StringID yes_no = GetLongestString(STR_FACE_YES, STR_FACE_NO);
1294
1295 uint width = 0;
1296 for (uint style_index = 0; style_index != GetNumCompanyManagerFaceStyles(); ++style_index) {
1297 FaceVars vars = GetCompanyManagerFaceVars(style_index);
1298 for (const auto &info : vars) {
1299 if (info.name == STR_NULL) continue;
1300 if (info.type == FaceVarType::Toggle) {
1301 width = std::max(width, GetStringBoundingBox(GetString(STR_FACE_SETTING_TOGGLE, info.name, yes_no)).width);
1302 } else {
1303 uint64_t max_digits = GetParamMaxValue(info.valid_values);
1304 width = std::max(width, GetStringBoundingBox(GetString(STR_FACE_SETTING_NUMERIC, info.name, max_digits, max_digits)).width);
1305 }
1306 }
1307 }
1308
1309 /* Include width of button and spacing. */
1311 return width;
1312 }
1313
1314 void UpdateWidgetSize(WidgetID widget, Dimension &size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension &fill, [[maybe_unused]] Dimension &resize) override
1315 {
1316 switch (widget) {
1317 case WID_SCMF_FACE:
1319 break;
1320
1321 case WID_SCMF_STYLE:
1322 size.height = this->line_height;
1323 break;
1324
1325 case WID_SCMF_PARTS:
1326 fill.height = resize.height = this->line_height;
1327 size.width = GetMaximumFacePartsWidth();
1328 size.height = resize.height * 5;
1329 break;
1330 }
1331 }
1332
1333 void DrawWidget(const Rect &r, WidgetID widget) const override
1334 {
1335 switch (widget) {
1336 case WID_SCMF_FACE:
1337 DrawCompanyManagerFace(this->face, Company::Get(this->window_number)->colour, r);
1338 break;
1339
1340 case WID_SCMF_STYLE: {
1341 Rect ir = r.Shrink(WidgetDimensions::scaled.frametext, RectPadding::zero).WithHeight(this->line_height);
1342 bool rtl = _current_text_dir == TD_RTL;
1343
1346
1347 DrawArrowButtons(br.left, br.top, Colours::Yellow, this->selected_var == UINT_MAX - 1 ? this->click_state : 0, true, true);
1348 DrawString(tr, GetString(STR_FACE_SETTING_NUMERIC, STR_FACE_STYLE, this->face.style + 1, GetNumCompanyManagerFaceStyles()), TextColour::White);
1349 break;
1350 }
1351
1352 case WID_SCMF_PARTS: {
1353 Rect ir = r.Shrink(WidgetDimensions::scaled.frametext, RectPadding::zero).WithHeight(this->line_height);
1354 bool rtl = _current_text_dir == TD_RTL;
1355
1356 FaceVars vars = GetCompanyManagerFaceVars(this->face.style);
1357
1358 auto [first, last] = this->GetScrollbar(WID_SCMF_PARTS_SCROLLBAR)->GetVisibleRangeIterators(this->face_vars);
1359 for (auto it = first; it != last; ++it) {
1360 const uint8_t var = static_cast<uint8_t>(*it - vars.data());
1361 const FaceVar &facevar = **it;
1362
1365
1366 uint val = vars[var].GetBits(this->face);
1367 if (facevar.type == FaceVarType::Toggle) {
1368 DrawBoolButton(br.left, br.top, Colours::Yellow, Colours::Grey, val == 1, true);
1369 DrawString(tr, GetString(STR_FACE_SETTING_TOGGLE, facevar.name, val == 1 ? STR_FACE_YES : STR_FACE_NO), TextColour::White);
1370 } else {
1371 DrawArrowButtons(br.left, br.top, Colours::Yellow, this->selected_var == var ? this->click_state : 0, true, true);
1372 DrawString(tr, GetString(STR_FACE_SETTING_NUMERIC, facevar.name, val + 1, facevar.valid_values), TextColour::White);
1373 }
1374
1375 ir = ir.Translate(0, this->line_height);
1376 }
1377 break;
1378 }
1379 }
1380 }
1381
1382 void OnClick([[maybe_unused]] Point pt, WidgetID widget, [[maybe_unused]] int click_count) override
1383 {
1384 switch (widget) {
1385 /* Toggle size, advanced/simple face selection */
1388 this->advanced = !this->advanced;
1389 this->SelectDisplayPlanes(this->advanced);
1390 this->ReInit();
1391 break;
1392
1393 /* OK button */
1394 case WID_SCMF_ACCEPT:
1395 Command<Commands::SetCompanyManagerFace>::Post(this->face.style, this->face.bits);
1396 [[fallthrough]];
1397
1398 /* Cancel button */
1399 case WID_SCMF_CANCEL:
1400 this->Close();
1401 break;
1402
1403 /* Load button */
1404 case WID_SCMF_LOAD: {
1406 if (cmf.has_value()) this->face = *cmf;
1407 ShowErrorMessage(GetEncodedString(STR_FACE_LOAD_DONE), {}, WarningLevel::Info);
1408 this->UpdateData();
1409 this->SetDirty();
1410 break;
1411 }
1412
1413 /* 'Company manager face number' button, view and/or set company manager face number */
1414 case WID_SCMF_FACECODE:
1415 ShowQueryString(FormatCompanyManagerFaceCode(this->face), STR_FACE_FACECODE_CAPTION, 128, this, CS_ALPHANUMERAL, {});
1416 break;
1417
1418 /* Save button */
1419 case WID_SCMF_SAVE:
1421 ShowErrorMessage(GetEncodedString(STR_FACE_SAVE_DONE), {}, WarningLevel::Info);
1422 break;
1423
1424 /* Randomize face button */
1427 this->UpdateData();
1428 this->SetDirty();
1429 break;
1430
1431 case WID_SCMF_STYLE: {
1432 bool rtl = _current_text_dir == TD_RTL;
1433 Rect ir = this->GetWidget<NWidgetCore>(widget)->GetCurrentRect().Shrink(WidgetDimensions::scaled.frametext, RectPadding::zero);
1434 Rect br = ir.WithWidth(SETTING_BUTTON_WIDTH, rtl);
1435
1436 uint num_styles = GetNumCompanyManagerFaceStyles();
1437 this->selected_var = UINT_MAX - 1;
1438 if (IsInsideBS(pt.x, br.left, SETTING_BUTTON_WIDTH / 2)) {
1439 SetCompanyManagerFaceStyle(this->face, (this->face.style + num_styles - 1) % num_styles);
1440 this->click_state = 1;
1441 } else if (IsInsideBS(pt.x, br.left + SETTING_BUTTON_WIDTH / 2, SETTING_BUTTON_WIDTH / 2)) {
1442 SetCompanyManagerFaceStyle(this->face, (this->face.style + 1) % num_styles);
1443 this->click_state = 2;
1444 }
1445
1446 this->UpdateData();
1447 this->SetTimeout();
1448 this->SetDirty();
1449 break;
1450 }
1451
1452 case WID_SCMF_PARTS: {
1453 bool rtl = _current_text_dir == TD_RTL;
1454 Rect ir = this->GetWidget<NWidgetCore>(widget)->GetCurrentRect().Shrink(WidgetDimensions::scaled.frametext, RectPadding::zero);
1455 Rect br = ir.WithWidth(SETTING_BUTTON_WIDTH, rtl);
1456
1457 this->selected_var = UINT_MAX;
1458
1459 FaceVars vars = GetCompanyManagerFaceVars(this->face.style);
1460 auto it = this->GetScrollbar(WID_SCMF_PARTS_SCROLLBAR)->GetScrolledItemFromWidget(this->face_vars, pt.y, this, widget, 0, this->line_height);
1461 if (it == std::end(this->face_vars)) break;
1462
1463 this->selected_var = static_cast<uint8_t>(*it - vars.data());
1464 const auto &facevar = **it;
1465
1466 if (facevar.type == FaceVarType::Toggle) {
1467 if (!IsInsideBS(pt.x, br.left, SETTING_BUTTON_WIDTH)) break;
1468 facevar.ChangeBits(this->face, 1);
1469 this->UpdateData();
1470 } else {
1471 if (IsInsideBS(pt.x, br.left, SETTING_BUTTON_WIDTH / 2)) {
1472 facevar.ChangeBits(this->face, -1);
1473 this->click_state = 1;
1474 } else if (IsInsideBS(pt.x, br.left + SETTING_BUTTON_WIDTH / 2, SETTING_BUTTON_WIDTH / 2)) {
1475 facevar.ChangeBits(this->face, 1);
1476 this->click_state = 2;
1477 } else {
1478 break;
1479 }
1480 }
1481
1482 this->SetTimeout();
1483 this->SetDirty();
1484 break;
1485 }
1486 }
1487 }
1488
1489 void OnResize() override
1490 {
1491 if (auto *wid = this->GetWidget<NWidgetResizeBase>(WID_SCMF_PARTS); wid != nullptr) {
1492 /* Workaround for automatic widget sizing ignoring resize steps. Manually ensure parts matrix is a
1493 * multiple of its resize step. This trick only works here as the window itself is not resizable. */
1494 if (wid->UpdateVerticalSize((wid->current_y + wid->resize_y - 1) / wid->resize_y * wid->resize_y)) {
1495 this->ReInit();
1496 return;
1497 }
1498 }
1499
1501 }
1502
1503 void OnTimeout() override
1504 {
1505 this->click_state = 0;
1506 this->selected_var = UINT_MAX;
1507 this->SetDirty();
1508 }
1509
1510 void OnQueryTextFinished(std::optional<std::string> str) override
1511 {
1512 if (!str.has_value()) return;
1513 /* Parse new company manager face number */
1514 auto cmf = ParseCompanyManagerFaceCode(*str);
1515 if (cmf.has_value()) {
1516 this->face = *cmf;
1517 ShowErrorMessage(GetEncodedString(STR_FACE_FACECODE_SET), {}, WarningLevel::Info);
1518 this->UpdateData();
1519 this->SetDirty();
1520 } else {
1521 ShowErrorMessage(GetEncodedString(STR_FACE_FACECODE_ERR), {}, WarningLevel::Info);
1522 }
1523 }
1524};
1525
1528 WindowPosition::Automatic, {}, 0, 0,
1529 WindowClass::CompanyManagerFace, WindowClass::None,
1532);
1533
1540{
1541 if (!Company::IsValidID(parent->window_number)) return;
1542
1543 if (BringWindowToFrontById(WindowClass::CompanyManagerFace, parent->window_number)) return;
1545}
1546
1547static constexpr std::initializer_list<NWidgetPart> _nested_company_infrastructure_widgets = {
1554 EndContainer(),
1558 EndContainer(),
1562 EndContainer(),
1563 EndContainer(),
1564};
1565
1569struct CompanyInfrastructureWindow : Window
1570{
1577
1580 StringID label;
1581 uint count;
1582 Money cost;
1583 };
1584
1585 uint count_width = 0;
1586 uint cost_width = 0;
1587
1588 mutable std::vector<InfrastructureItem> list;
1589
1590 CompanyInfrastructureWindow(WindowDesc &desc, WindowNumber window_number) : Window(desc)
1591 {
1592 this->InitNested(window_number);
1593 this->owner = this->window_number;
1594 }
1595
1596 void OnInit() override
1597 {
1598 this->UpdateInfrastructureList();
1599 }
1600
1601 void UpdateInfrastructureList()
1602 {
1603 this->list.clear();
1604
1605 const Company *c = Company::GetIfValid(this->window_number);
1606 if (c == nullptr) return;
1607
1608 Money total_monthly_cost = 0;
1609
1610 if (uint32_t rail_total = c->infrastructure.GetRailTotal(); rail_total > 0) {
1611 /* Rail types and signals. */
1612 this->list.emplace_back(InfrastructureItemType::Header, STR_COMPANY_INFRASTRUCTURE_VIEW_RAIL_SECT);
1613
1614 for (const RailType &rt : _sorted_railtypes) {
1615 if (c->infrastructure.rail[rt] == 0) continue;
1616 Money monthly_cost = RailMaintenanceCost(rt, c->infrastructure.rail[rt], rail_total);
1617 total_monthly_cost += monthly_cost;
1618 this->list.emplace_back(InfrastructureItemType::Value, GetRailTypeInfo(rt)->strings.name, c->infrastructure.rail[rt], monthly_cost);
1619 }
1620
1621 if (c->infrastructure.signal > 0) {
1622 Money monthly_cost = SignalMaintenanceCost(c->infrastructure.signal);
1623 total_monthly_cost += monthly_cost;
1624 this->list.emplace_back(InfrastructureItemType::Value, STR_COMPANY_INFRASTRUCTURE_VIEW_SIGNALS, c->infrastructure.signal, monthly_cost);
1625 }
1626 }
1627
1628 if (uint32_t road_total = c->infrastructure.GetRoadTotal(); road_total > 0) {
1629 /* Road types. */
1630 if (!this->list.empty()) this->list.emplace_back(InfrastructureItemType::Spacer);
1631 this->list.emplace_back(InfrastructureItemType::Header, STR_COMPANY_INFRASTRUCTURE_VIEW_ROAD_SECT);
1632
1633 for (const RoadType &rt : _sorted_roadtypes) {
1634 if (!RoadTypeIsRoad(rt)) continue;
1635 if (c->infrastructure.road[rt] == 0) continue;
1636 Money monthly_cost = RoadMaintenanceCost(rt, c->infrastructure.road[rt], road_total);
1637 total_monthly_cost += monthly_cost;
1638 this->list.emplace_back(InfrastructureItemType::Value, GetRoadTypeInfo(rt)->strings.name, c->infrastructure.road[rt], monthly_cost);
1639 }
1640 }
1641
1642 if (uint32_t tram_total = c->infrastructure.GetTramTotal(); tram_total > 0) {
1643 /* Tram types. */
1644 if (!this->list.empty()) this->list.emplace_back(InfrastructureItemType::Spacer);
1645 this->list.emplace_back(InfrastructureItemType::Header, STR_COMPANY_INFRASTRUCTURE_VIEW_TRAM_SECT);
1646
1647 for (const RoadType &rt : _sorted_roadtypes) {
1648 if (!RoadTypeIsTram(rt)) continue;
1649 if (c->infrastructure.road[rt] == 0) continue;
1650 Money monthly_cost = RoadMaintenanceCost(rt, c->infrastructure.road[rt], tram_total);
1651 total_monthly_cost += monthly_cost;
1652 this->list.emplace_back(InfrastructureItemType::Value, GetRoadTypeInfo(rt)->strings.name, c->infrastructure.road[rt], monthly_cost);
1653 }
1654 }
1655
1656 if (c->infrastructure.water > 0) {
1657 /* Canals, locks, and ship depots (docks are counted as stations). */
1658 if (!this->list.empty()) this->list.emplace_back(InfrastructureItemType::Spacer);
1659 this->list.emplace_back(InfrastructureItemType::Header, STR_COMPANY_INFRASTRUCTURE_VIEW_WATER_SECT);
1660
1661 Money monthly_cost = CanalMaintenanceCost(c->infrastructure.water);
1662 total_monthly_cost += monthly_cost;
1663 this->list.emplace_back(InfrastructureItemType::Value, STR_COMPANY_INFRASTRUCTURE_VIEW_CANALS, c->infrastructure.water, monthly_cost);
1664 }
1665
1666 if (Money airport_cost = AirportMaintenanceCost(c->index); airport_cost > 0 || c->infrastructure.station > 0) {
1667 /* Stations and airports. */
1668 if (!this->list.empty()) this->list.emplace_back(InfrastructureItemType::Spacer);
1669 this->list.emplace_back(InfrastructureItemType::Header, STR_COMPANY_INFRASTRUCTURE_VIEW_STATION_SECT);
1670
1671 if (c->infrastructure.station > 0) {
1672 Money monthly_cost = StationMaintenanceCost(c->infrastructure.station);
1673 total_monthly_cost += monthly_cost;
1674 this->list.emplace_back(InfrastructureItemType::Value, STR_COMPANY_INFRASTRUCTURE_VIEW_STATIONS, c->infrastructure.station, monthly_cost);
1675 }
1676
1677 if (airport_cost > 0) {
1678 Money monthly_cost = airport_cost;
1679 total_monthly_cost += monthly_cost;
1680 this->list.emplace_back(InfrastructureItemType::Value, STR_COMPANY_INFRASTRUCTURE_VIEW_AIRPORTS, c->infrastructure.airport, monthly_cost);
1681 }
1682 }
1683
1685 /* Total monthly maintenance cost. */
1686 this->list.emplace_back(InfrastructureItemType::Spacer);
1687 this->list.emplace_back(InfrastructureItemType::Total, STR_NULL, 0, total_monthly_cost);
1688 }
1689
1690 /* Update scrollbar. */
1691 this->GetScrollbar(WID_CI_SCROLLBAR)->SetCount(std::size(list));
1692 }
1693
1694 std::string GetWidgetString(WidgetID widget, StringID stringid) const override
1695 {
1696 switch (widget) {
1697 case WID_CI_CAPTION:
1698 return GetString(STR_COMPANY_INFRASTRUCTURE_VIEW_CAPTION, this->window_number);
1699
1700 default:
1701 return this->Window::GetWidgetString(widget, stringid);
1702 }
1703 }
1704
1705 void FindWindowPlacementAndResize(int def_width, int def_height, bool allow_resize) override
1706 {
1707 if (def_height == 0) {
1708 /* Try to open the window with the exact required rows, but clamp to a reasonable limit. */
1709 int rows = (this->GetWidget<NWidgetBase>(WID_CI_LIST)->current_y - WidgetDimensions::scaled.framerect.Vertical()) / GetCharacterHeight(FontSize::Normal);
1710 int delta = std::min(20, static_cast<int>(std::size(this->list))) - rows;
1711 def_height = this->height + delta * GetCharacterHeight(FontSize::Normal);
1712 }
1713
1714 this->Window::FindWindowPlacementAndResize(def_width, def_height, allow_resize);
1715 }
1716
1717 void UpdateWidgetSize(WidgetID widget, Dimension &size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension &fill, [[maybe_unused]] Dimension &resize) override
1718 {
1719 if (widget != WID_CI_LIST) return;
1720
1721 uint max_count = 1000; // Some random number to reserve minimum space.
1722 Money max_cost = 1000000; // Some random number to reserve minimum space.
1723
1724 /* List of headers that might be used. */
1725 static constexpr StringID header_strings[] = {
1726 STR_COMPANY_INFRASTRUCTURE_VIEW_RAIL_SECT,
1727 STR_COMPANY_INFRASTRUCTURE_VIEW_ROAD_SECT,
1728 STR_COMPANY_INFRASTRUCTURE_VIEW_TRAM_SECT,
1729 STR_COMPANY_INFRASTRUCTURE_VIEW_WATER_SECT,
1730 STR_COMPANY_INFRASTRUCTURE_VIEW_STATION_SECT,
1731 };
1732 /* List of labels that might be used. */
1733 static constexpr StringID label_strings[] = {
1734 STR_COMPANY_INFRASTRUCTURE_VIEW_SIGNALS,
1735 STR_COMPANY_INFRASTRUCTURE_VIEW_CANALS,
1736 STR_COMPANY_INFRASTRUCTURE_VIEW_STATIONS,
1737 STR_COMPANY_INFRASTRUCTURE_VIEW_AIRPORTS,
1738 };
1739
1740 uint max_header_width = GetStringListWidth(header_strings);
1741 uint max_label_width = GetStringListWidth(label_strings);
1742
1743 /* Include width of all possible rail and road types. */
1744 for (const RailType &rt : _sorted_railtypes) max_label_width = std::max(max_label_width, GetStringBoundingBox(GetRailTypeInfo(rt)->strings.name).width);
1745 for (const RoadType &rt : _sorted_roadtypes) max_label_width = std::max(max_label_width, GetStringBoundingBox(GetRoadTypeInfo(rt)->strings.name).width);
1746
1747 for (const InfrastructureItem &entry : this->list) {
1748 max_count = std::max(max_count, entry.count);
1749 max_cost = std::max(max_cost, entry.cost * 12);
1750 }
1751
1752 max_label_width += WidgetDimensions::scaled.hsep_indent;
1753 this->count_width = GetStringBoundingBox(GetString(STR_JUST_COMMA, max_count)).width;
1754
1755 if (_settings_game.economy.infrastructure_maintenance) {
1756 this->cost_width = GetStringBoundingBox(GetString(TimerGameEconomy::UsingWallclockUnits() ? STR_COMPANY_INFRASTRUCTURE_VIEW_TOTAL_PERIOD : STR_COMPANY_INFRASTRUCTURE_VIEW_TOTAL_YEAR, max_cost)).width;
1757 } else {
1758 this->cost_width = 0;
1759 }
1760
1761 size.width = max_label_width + WidgetDimensions::scaled.hsep_wide + this->count_width + WidgetDimensions::scaled.hsep_wide + this->cost_width;
1762 size.width = std::max(size.width, max_header_width) + WidgetDimensions::scaled.framerect.Horizontal();
1763
1764 fill.height = resize.height = GetCharacterHeight(FontSize::Normal);
1765 }
1766
1767 void DrawWidget(const Rect &r, WidgetID widget) const override
1768 {
1769 if (widget != WID_CI_LIST) return;
1770
1771 bool rtl = _current_text_dir == TD_RTL; // We allocate space from end-to-start so the label fills.
1772 int line_height = GetCharacterHeight(FontSize::Normal);
1773
1774 Rect ir = r.Shrink(WidgetDimensions::scaled.framerect);
1775 Rect countr = ir.WithWidth(this->count_width, !rtl);
1776 Rect costr = ir.Indent(this->count_width + WidgetDimensions::scaled.hsep_wide, !rtl).WithWidth(this->cost_width, !rtl);
1777 Rect labelr = ir.Indent(this->count_width + WidgetDimensions::scaled.hsep_wide + this->cost_width + WidgetDimensions::scaled.hsep_wide, !rtl);
1778
1779 auto [first, last] = this->GetScrollbar(WID_CI_SCROLLBAR)->GetVisibleRangeIterators(this->list);
1780 for (auto it = first; it != last; ++it) {
1781 switch (it->type) {
1783 /* Header is allowed to fill the window's width. */
1784 DrawString(ir.left, ir.right, labelr.top, GetString(it->label), TextColour::Orange);
1785 break;
1786
1788 break;
1789
1791 /* Draw line in the spacer above the total. */
1793 DrawString(costr, GetString(TimerGameEconomy::UsingWallclockUnits() ? STR_COMPANY_INFRASTRUCTURE_VIEW_TOTAL_PERIOD : STR_COMPANY_INFRASTRUCTURE_VIEW_TOTAL_YEAR, it->cost * 12), TextColour::Black, AlignmentH::ForceRight);
1794 break;
1795
1797 DrawString(labelr.Indent(WidgetDimensions::scaled.hsep_indent, rtl), GetString(it->label), TextColour::White);
1798 DrawString(countr, GetString(STR_JUST_COMMA, it->count), TextColour::White, AlignmentH::ForceRight);
1799 if (_settings_game.economy.infrastructure_maintenance) {
1800 DrawString(costr, GetString(TimerGameEconomy::UsingWallclockUnits() ? STR_COMPANY_INFRASTRUCTURE_VIEW_TOTAL_PERIOD : STR_COMPANY_INFRASTRUCTURE_VIEW_TOTAL_YEAR, it->cost * 12), TextColour::Black, AlignmentH::ForceRight);
1801 }
1802 break;
1803 }
1804
1805 labelr.top += line_height;
1806 countr.top += line_height;
1807 costr.top += line_height;
1808 }
1809 }
1810
1811 const IntervalTimer<TimerWindow> redraw_interval = {std::chrono::seconds(1), [this](auto) {
1812 this->UpdateInfrastructureList();
1814 }};
1815
1816 void OnResize() override
1817 {
1819 }
1820
1826 void OnInvalidateData([[maybe_unused]] int data = 0, [[maybe_unused]] bool gui_scope = true) override
1827 {
1828 if (!gui_scope) return;
1829
1830 this->ReInit();
1831 }
1832};
1833
1836 WindowPosition::Automatic, "company_infrastructure", 0, 0,
1837 WindowClass::CompanyInfrastructure, WindowClass::None,
1838 {},
1839 _nested_company_infrastructure_widgets
1840);
1841
1846static void ShowCompanyInfrastructure(CompanyID company)
1847{
1848 if (!Company::IsValidID(company)) return;
1850}
1851
1852static constexpr std::initializer_list<NWidgetPart> _nested_company_widgets = {
1858 EndContainer(),
1864 EndContainer(),
1870 NWidget(WWT_LABEL, Colours::Invalid, WID_C_DESC_COLOUR_SCHEME), SetStringTip(STR_COMPANY_VIEW_COLOUR_SCHEME_TITLE),
1872 EndContainer(),
1876 EndContainer(),
1877 EndContainer(),
1880 NWidget(WWT_PUSHTXTBTN, Colours::Grey, WID_C_VIEW_HQ), SetStringTip(STR_COMPANY_VIEW_VIEW_HQ_BUTTON, STR_COMPANY_VIEW_VIEW_HQ_TOOLTIP),
1881 NWidget(WWT_TEXTBTN, Colours::Grey, WID_C_BUILD_HQ), SetStringTip(STR_COMPANY_VIEW_BUILD_HQ_BUTTON, STR_COMPANY_VIEW_BUILD_HQ_TOOLTIP),
1882 EndContainer(),
1884 NWidget(WWT_TEXTBTN, Colours::Grey, WID_C_RELOCATE_HQ), SetStringTip(STR_COMPANY_VIEW_RELOCATE_HQ, STR_COMPANY_VIEW_RELOCATE_HQ_TOOLTIP),
1886 EndContainer(),
1887 EndContainer(),
1888 EndContainer(),
1889
1891
1896 NWidget(WWT_PUSHTXTBTN, Colours::Grey, WID_C_VIEW_INFRASTRUCTURE), SetStringTip(STR_COMPANY_VIEW_INFRASTRUCTURE_BUTTON, STR_COMPANY_VIEW_INFRASTRUCTURE_TOOLTIP),
1897 EndContainer(),
1898 EndContainer(),
1899
1900 /* Multi player buttons. */
1904 NWidget(WWT_PUSHTXTBTN, Colours::Grey, WID_C_HOSTILE_TAKEOVER), SetStringTip(STR_COMPANY_VIEW_HOSTILE_TAKEOVER_BUTTON, STR_COMPANY_VIEW_HOSTILE_TAKEOVER_TOOLTIP),
1905 EndContainer(),
1907 NWidget(WWT_PUSHTXTBTN, Colours::Grey, WID_C_GIVE_MONEY), SetStringTip(STR_COMPANY_VIEW_GIVE_MONEY_BUTTON, STR_COMPANY_VIEW_GIVE_MONEY_TOOLTIP),
1908 EndContainer(),
1910 NWidget(WWT_PUSHTXTBTN, Colours::Grey, WID_C_COMPANY_JOIN), SetStringTip(STR_COMPANY_VIEW_JOIN, STR_COMPANY_VIEW_JOIN_TOOLTIP),
1911 EndContainer(),
1912 EndContainer(),
1913 EndContainer(),
1914 EndContainer(),
1915 EndContainer(),
1916 EndContainer(),
1917 /* Button bars at the bottom. */
1920 NWidget(WWT_PUSHTXTBTN, Colours::Grey, WID_C_NEW_FACE), SetFill(1, 0), SetStringTip(STR_COMPANY_VIEW_NEW_FACE_BUTTON, STR_COMPANY_VIEW_NEW_FACE_TOOLTIP),
1921 NWidget(WWT_PUSHTXTBTN, Colours::Grey, WID_C_COLOUR_SCHEME), SetFill(1, 0), SetStringTip(STR_COMPANY_VIEW_COLOUR_SCHEME_BUTTON, STR_COMPANY_VIEW_COLOUR_SCHEME_TOOLTIP),
1922 NWidget(WWT_PUSHTXTBTN, Colours::Grey, WID_C_PRESIDENT_NAME), SetFill(1, 0), SetStringTip(STR_COMPANY_VIEW_PRESIDENT_NAME_BUTTON, STR_COMPANY_VIEW_PRESIDENT_NAME_TOOLTIP),
1923 NWidget(WWT_PUSHTXTBTN, Colours::Grey, WID_C_COMPANY_NAME), SetFill(1, 0), SetStringTip(STR_COMPANY_VIEW_COMPANY_NAME_BUTTON, STR_COMPANY_VIEW_COMPANY_NAME_TOOLTIP),
1924 EndContainer(),
1925 EndContainer(),
1926};
1927
1930 STR_COMPANY_VIEW_TRAINS, STR_COMPANY_VIEW_ROAD_VEHICLES, STR_COMPANY_VIEW_SHIPS, STR_COMPANY_VIEW_AIRCRAFT
1931};
1932
1936struct CompanyWindow : Window
1937{
1940
1941 CompanyWidgets query_widget{};
1942
1944 enum CompanyWindowPlanes : uint8_t {
1945 /* Display planes of the #WID_C_SELECT_VIEW_BUILD_HQ selection widget. */
1948
1949 /* Display planes of the #WID_C_SELECT_RELOCATE selection widget. */
1952 };
1953
1955 {
1956 this->InitNested(window_number);
1957 this->owner = this->window_number;
1958 this->OnInvalidateData();
1959 }
1960
1961 void OnPaint() override
1962 {
1963 const Company *c = Company::Get(this->window_number);
1964 bool local = this->window_number == _local_company;
1965
1966 if (!this->IsShaded()) {
1967 bool reinit = false;
1968
1969 /* Button bar selection. */
1970 reinit |= this->GetWidget<NWidgetStacked>(WID_C_SELECT_BUTTONS)->SetDisplayedPlane(local ? 0 : SZSP_NONE);
1971
1972 /* Build HQ button handling. */
1973 reinit |= this->GetWidget<NWidgetStacked>(WID_C_SELECT_VIEW_BUILD_HQ)->SetDisplayedPlane((local && c->location_of_HQ == INVALID_TILE) ? CWP_VB_BUILD : CWP_VB_VIEW);
1974
1976
1977 /* Enable/disable 'Relocate HQ' button. */
1978 reinit |= this->GetWidget<NWidgetStacked>(WID_C_SELECT_RELOCATE)->SetDisplayedPlane((!local || c->location_of_HQ == INVALID_TILE) ? CWP_RELOCATE_HIDE : CWP_RELOCATE_SHOW);
1979 /* Enable/disable 'Give money' button. */
1980 reinit |= this->GetWidget<NWidgetStacked>(WID_C_SELECT_GIVE_MONEY)->SetDisplayedPlane((local || _local_company == COMPANY_SPECTATOR || !_settings_game.economy.give_money) ? SZSP_NONE : 0);
1981 /* Enable/disable 'Hostile Takeover' button. */
1982 reinit |= this->GetWidget<NWidgetStacked>(WID_C_SELECT_HOSTILE_TAKEOVER)->SetDisplayedPlane((local || _local_company == COMPANY_SPECTATOR || !c->is_ai || _networking) ? SZSP_NONE : 0);
1983
1984 /* Multiplayer buttons. */
1985 reinit |= this->GetWidget<NWidgetStacked>(WID_C_SELECT_MULTIPLAYER)->SetDisplayedPlane((!_networking || !NetworkCanJoinCompany(c->index) || _local_company == c->index) ? (int)SZSP_NONE : 0);
1986
1988
1989 if (reinit) {
1990 this->ReInit();
1991 return;
1992 }
1993 }
1994
1995 this->DrawWidgets();
1996 }
1997
1998 void UpdateWidgetSize(WidgetID widget, Dimension &size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension &fill, [[maybe_unused]] Dimension &resize) override
1999 {
2000 switch (widget) {
2001 case WID_C_FACE:
2003 break;
2004
2006 Point offset;
2008 d.width -= offset.x;
2009 d.height -= offset.y;
2010 size = maxdim(size, d);
2011 break;
2012 }
2013
2015 /* INT64_MAX is arguably the maximum company value */
2016 size.width = GetStringBoundingBox(GetString(STR_COMPANY_VIEW_COMPANY_VALUE, INT64_MAX)).width;
2017 break;
2018
2020 uint64_t max_value = GetParamMaxValue(10000); // Maximum number of vehicles
2021 for (const auto &count_string : _company_view_vehicle_count_strings) {
2022 size.width = std::max(size.width, GetStringBoundingBox(GetString(count_string, max_value)).width + padding.width);
2023 }
2024 break;
2025 }
2026
2028 uint64_t max_value = GetParamMaxValue(UINT_MAX);
2029 size.width = GetStringBoundingBox(GetString(STR_COMPANY_VIEW_INFRASTRUCTURE_RAIL, max_value)).width;
2030 size.width = std::max(size.width, GetStringBoundingBox(GetString(STR_COMPANY_VIEW_INFRASTRUCTURE_ROAD, max_value)).width);
2031 size.width = std::max(size.width, GetStringBoundingBox(GetString(STR_COMPANY_VIEW_INFRASTRUCTURE_WATER, max_value)).width);
2032 size.width = std::max(size.width, GetStringBoundingBox(GetString(STR_COMPANY_VIEW_INFRASTRUCTURE_STATION, max_value)).width);
2033 size.width = std::max(size.width, GetStringBoundingBox(GetString(STR_COMPANY_VIEW_INFRASTRUCTURE_AIRPORT, max_value)).width);
2034 size.width = std::max(size.width, GetStringBoundingBox(GetString(STR_COMPANY_VIEW_INFRASTRUCTURE_NONE, max_value)).width);
2035 size.width += padding.width;
2036 break;
2037 }
2038
2039 case WID_C_VIEW_HQ:
2040 case WID_C_BUILD_HQ:
2041 case WID_C_RELOCATE_HQ:
2043 case WID_C_GIVE_MONEY:
2045 case WID_C_COMPANY_JOIN:
2046 size.width = GetStringBoundingBox(STR_COMPANY_VIEW_VIEW_HQ_BUTTON).width;
2047 size.width = std::max(size.width, GetStringBoundingBox(STR_COMPANY_VIEW_BUILD_HQ_BUTTON).width);
2048 size.width = std::max(size.width, GetStringBoundingBox(STR_COMPANY_VIEW_RELOCATE_HQ).width);
2049 size.width = std::max(size.width, GetStringBoundingBox(STR_COMPANY_VIEW_INFRASTRUCTURE_BUTTON).width);
2050 size.width = std::max(size.width, GetStringBoundingBox(STR_COMPANY_VIEW_GIVE_MONEY_BUTTON).width);
2051 size.width = std::max(size.width, GetStringBoundingBox(STR_COMPANY_VIEW_HOSTILE_TAKEOVER_BUTTON).width);
2052 size.width = std::max(size.width, GetStringBoundingBox(STR_COMPANY_VIEW_JOIN).width);
2053 size.width += padding.width;
2054 break;
2055 }
2056 }
2057
2058 void DrawVehicleCountsWidget(const Rect &r, const Company *c) const
2059 {
2060 int y = r.top;
2062 uint amount = c->group_all[type].num_vehicle;
2063 if (amount != 0) {
2064 DrawString(r.left, r.right, y, GetString(_company_view_vehicle_count_strings[type], amount));
2066 }
2067 }
2068
2069 if (y == r.top) {
2070 /* No String was emitted before, so there must be no vehicles at all. */
2071 DrawString(r.left, r.right, y, STR_COMPANY_VIEW_VEHICLES_NONE);
2072 }
2073 }
2074
2075 void DrawInfrastructureCountsWidget(const Rect &r, const Company *c) const
2076 {
2077 int y = r.top;
2078
2079 uint rail_pieces = c->infrastructure.signal + c->infrastructure.GetRailTotal();
2080 if (rail_pieces != 0) {
2081 DrawString(r.left, r.right, y, GetString(STR_COMPANY_VIEW_INFRASTRUCTURE_RAIL, rail_pieces));
2083 }
2084
2085 /* GetRoadTotal() skips tram pieces, but we actually want road and tram here. */
2086 uint road_pieces = std::accumulate(std::begin(c->infrastructure.road), std::end(c->infrastructure.road), 0U);
2087 if (road_pieces != 0) {
2088 DrawString(r.left, r.right, y, GetString(STR_COMPANY_VIEW_INFRASTRUCTURE_ROAD, road_pieces));
2090 }
2091
2092 if (c->infrastructure.water != 0) {
2093 DrawString(r.left, r.right, y, GetString(STR_COMPANY_VIEW_INFRASTRUCTURE_WATER, c->infrastructure.water));
2095 }
2096
2097 if (c->infrastructure.station != 0) {
2098 DrawString(r.left, r.right, y, GetString(STR_COMPANY_VIEW_INFRASTRUCTURE_STATION, c->infrastructure.station));
2100 }
2101
2102 if (c->infrastructure.airport != 0) {
2103 DrawString(r.left, r.right, y, GetString(STR_COMPANY_VIEW_INFRASTRUCTURE_AIRPORT, c->infrastructure.airport));
2105 }
2106
2107 if (y == r.top) {
2108 /* No String was emitted before, so there must be no infrastructure at all. */
2109 DrawString(r.left, r.right, y, STR_COMPANY_VIEW_INFRASTRUCTURE_NONE);
2110 }
2111 }
2112
2113 void DrawWidget(const Rect &r, WidgetID widget) const override
2114 {
2115 const Company *c = Company::Get(this->window_number);
2116 switch (widget) {
2117 case WID_C_FACE:
2119 break;
2120
2121 case WID_C_FACE_TITLE:
2122 DrawStringMultiLine(r, GetString(STR_COMPANY_VIEW_PRESIDENT_MANAGER_TITLE, c->index), TextColour::FromString, AlignmentH::Centre);
2123 break;
2124
2126 Point offset;
2128 d.height -= offset.y;
2129 DrawSprite(SPR_VEH_BUS_SW_VIEW, GetCompanyPalette(c->index), r.left - offset.x, CentreBounds(r.top, r.bottom, d.height) - offset.y);
2130 break;
2131 }
2132
2134 DrawVehicleCountsWidget(r, c);
2135 break;
2136
2138 DrawInfrastructureCountsWidget(r, c);
2139 break;
2140 }
2141 }
2142
2143 std::string GetWidgetString(WidgetID widget, StringID stringid) const override
2144 {
2145 switch (widget) {
2146 case WID_C_CAPTION:
2147 return GetString(STR_COMPANY_VIEW_CAPTION, this->window_number, this->window_number);
2148
2150 const Company &c = *Company::Get(this->window_number);
2152 return GetString(STR_COMPANY_VIEW_INAUGURATED_TITLE_WALLCLOCK, c.inaugurated_year_calendar, c.inaugurated_year);
2153 }
2154 return GetString(STR_COMPANY_VIEW_INAUGURATED_TITLE, c.inaugurated_year);
2155 }
2156
2158 return GetString(STR_COMPANY_VIEW_COMPANY_VALUE, CalculateCompanyValue(Company::Get(this->window_number)));
2159
2160 default:
2161 return this->Window::GetWidgetString(widget, stringid);
2162 }
2163 }
2164
2165 void OnResize() override
2166 {
2168 int y = GetStringHeight(GetString(STR_COMPANY_VIEW_PRESIDENT_MANAGER_TITLE, this->owner), wid->current_x);
2169 if (wid->UpdateVerticalSize(y)) this->ReInit(0, 0);
2170 }
2171
2172 void OnClick([[maybe_unused]] Point pt, WidgetID widget, [[maybe_unused]] int click_count) override
2173 {
2174 switch (widget) {
2175 case WID_C_NEW_FACE: DoSelectCompanyManagerFace(this); break;
2176
2178 ShowCompanyLiveryWindow(this->window_number, GroupID::Invalid());
2179 break;
2180
2182 ShowQueryString(GetString(STR_PRESIDENT_NAME, this->window_number), STR_COMPANY_VIEW_PRESIDENT_S_NAME_QUERY_CAPTION, MAX_LENGTH_PRESIDENT_NAME_CHARS, this, CS_ALPHANUMERAL, {QueryStringFlag::EnableDefault, QueryStringFlag::LengthIsInChars});
2183 this->query_widget = WID_C_PRESIDENT_NAME;
2184 break;
2185
2186 case WID_C_COMPANY_NAME:
2187 ShowQueryString(GetString(STR_COMPANY_NAME, this->window_number), STR_COMPANY_VIEW_COMPANY_NAME_QUERY_CAPTION, MAX_LENGTH_COMPANY_NAME_CHARS, this, CS_ALPHANUMERAL, {QueryStringFlag::EnableDefault, QueryStringFlag::LengthIsInChars});
2188 this->query_widget = WID_C_COMPANY_NAME;
2189 break;
2190
2191 case WID_C_VIEW_HQ: {
2192 TileIndex tile = Company::Get(this->window_number)->location_of_HQ;
2193 if (IsCtrlPressed()) {
2195 } else {
2197 }
2198 break;
2199 }
2200
2201 case WID_C_BUILD_HQ:
2202 if (this->window_number != _local_company) return;
2203 if (this->IsWidgetLowered(WID_C_BUILD_HQ)) {
2205 this->RaiseButtons();
2206 break;
2207 }
2208 SetObjectToPlaceWnd(SPR_CURSOR_HQ, PAL_NONE, HT_RECT, this);
2209 SetTileSelectSize(2, 2);
2212 break;
2213
2214 case WID_C_RELOCATE_HQ:
2217 this->RaiseButtons();
2218 break;
2219 }
2220 SetObjectToPlaceWnd(SPR_CURSOR_HQ, PAL_NONE, HT_RECT, this);
2221 SetTileSelectSize(2, 2);
2224 break;
2225
2228 break;
2229
2230 case WID_C_GIVE_MONEY:
2231 ShowQueryString({}, STR_COMPANY_VIEW_GIVE_MONEY_QUERY_CAPTION, 30, this, CS_NUMERAL, {});
2232 this->query_widget = WID_C_GIVE_MONEY;
2233 break;
2234
2237 break;
2238
2239 case WID_C_COMPANY_JOIN: {
2240 this->query_widget = WID_C_COMPANY_JOIN;
2241 CompanyID company = this->window_number;
2242 if (_network_server) {
2245 } else {
2246 /* just send the join command */
2247 NetworkClientRequestMove(company);
2248 }
2249 break;
2250 }
2251 }
2252 }
2253
2255 const IntervalTimer<TimerWindow> redraw_interval = {std::chrono::seconds(3), [this](auto) {
2256 this->SetDirty();
2257 }};
2258
2259 void OnPlaceObject([[maybe_unused]] Point pt, TileIndex tile) override
2260 {
2261 if (Command<Commands::BuildObject>::Post(STR_ERROR_CAN_T_BUILD_COMPANY_HEADQUARTERS, tile, OBJECT_HQ, 0) && !IsShiftPressed()) {
2263 this->RaiseButtons();
2264 }
2265 }
2266
2267 void OnPlaceObjectAbort() override
2268 {
2269 this->RaiseButtons();
2270 }
2271
2272 void OnQueryTextFinished(std::optional<std::string> str) override
2273 {
2274 CompanyWidgets widget = this->query_widget;
2275 this->query_widget = CompanyWindow::INVALID_QUERY_WIDGET;
2276
2277 if (!str.has_value()) return;
2278
2279 switch (widget) {
2280 default: NOT_REACHED();
2281
2282 case WID_C_GIVE_MONEY: {
2283 auto value = ParseInteger<uint64_t>(*str, 10, true);
2284 if (!value.has_value()) return;
2285 Money money = *value / GetCurrency().rate;
2286 Command<Commands::GiveMoney>::Post(STR_ERROR_CAN_T_GIVE_MONEY, money, this->window_number);
2287 break;
2288 }
2289
2291 Command<Commands::RenamePresident>::Post(STR_ERROR_CAN_T_CHANGE_PRESIDENT, *str);
2292 break;
2293
2294 case WID_C_COMPANY_NAME:
2295 Command<Commands::RenameCompany>::Post(STR_ERROR_CAN_T_CHANGE_COMPANY_NAME, *str);
2296 break;
2297 }
2298 }
2299
2300 void OnInvalidateData([[maybe_unused]] int data = 0, [[maybe_unused]] bool gui_scope = true) override
2301 {
2302 if (!gui_scope) return;
2303
2304 /* Manually call OnResize to adjust minimum height of president name widget. */
2305 if (data == WID_C_PRESIDENT_NAME) this->OnResize();
2306
2307 /* If a query string is visible, update its default value. */
2308 if (this->query_widget != CompanyWindow::INVALID_QUERY_WIDGET && data == this->query_widget) {
2309 UpdateQueryStringDefault(GetString(data == WID_C_COMPANY_NAME ? STR_COMPANY_NAME : STR_PRESIDENT_NAME, this->window_number));
2310 }
2311 }
2312};
2313
2316 WindowPosition::Automatic, "company", 0, 0,
2317 WindowClass::Company, WindowClass::None,
2318 {},
2319 _nested_company_widgets
2320);
2321
2326void ShowCompany(CompanyID company)
2327{
2328 if (!Company::IsValidID(company)) return;
2329
2331}
2332
2338{
2339 SetWindowDirty(WindowClass::Company, company);
2340 SetWindowDirty(WindowClass::CompanyInfrastructure, company);
2341}
2342
2343struct BuyCompanyWindow : Window {
2345 {
2346 this->InitNested(window_number);
2347
2348 const Company *c = Company::Get(this->window_number);
2349 this->company_value = hostile_takeover ? CalculateHostileTakeoverValue(c) : c->bankrupt_value;
2350 }
2351
2352 void UpdateWidgetSize(WidgetID widget, Dimension &size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension &fill, [[maybe_unused]] Dimension &resize) override
2353 {
2354 switch (widget) {
2355 case WID_BC_FACE:
2357 break;
2358
2359 case WID_BC_QUESTION:
2360 const Company *c = Company::Get(this->window_number);
2361 size.height = GetStringHeight(GetString(this->hostile_takeover ? STR_BUY_COMPANY_HOSTILE_TAKEOVER : STR_BUY_COMPANY_MESSAGE, c->index, this->company_value), size.width);
2362 break;
2363 }
2364 }
2365
2366 std::string GetWidgetString(WidgetID widget, StringID stringid) const override
2367 {
2368 switch (widget) {
2369 case WID_BC_CAPTION:
2370 return GetString(STR_ERROR_MESSAGE_CAPTION_OTHER_COMPANY, Company::Get(this->window_number)->index);
2371
2372 default:
2373 return this->Window::GetWidgetString(widget, stringid);
2374 }
2375 }
2376
2377 void DrawWidget(const Rect &r, WidgetID widget) const override
2378 {
2379 switch (widget) {
2380 case WID_BC_FACE: {
2381 const Company *c = Company::Get(this->window_number);
2383 break;
2384 }
2385
2386 case WID_BC_QUESTION: {
2387 const Company *c = Company::Get(this->window_number);
2388 DrawStringMultiLine(r, GetString(this->hostile_takeover ? STR_BUY_COMPANY_HOSTILE_TAKEOVER : STR_BUY_COMPANY_MESSAGE, c->index, this->company_value), TextColour::FromString, {AlignmentH::Centre, AlignmentV::Middle});
2389 break;
2390 }
2391 }
2392 }
2393
2394 void OnClick([[maybe_unused]] Point pt, WidgetID widget, [[maybe_unused]] int click_count) override
2395 {
2396 switch (widget) {
2397 case WID_BC_NO:
2398 this->Close();
2399 break;
2400
2401 case WID_BC_YES:
2402 Command<Commands::BuyCompany>::Post(STR_ERROR_CAN_T_BUY_COMPANY, this->window_number, this->hostile_takeover);
2403 break;
2404 }
2405 }
2406
2410 const IntervalTimer<TimerWindow> rescale_interval = {std::chrono::seconds(3), [this](auto) {
2411 /* Value can't change when in bankruptcy. */
2412 if (!this->hostile_takeover) return;
2413
2414 const Company *c = Company::Get(this->window_number);
2415 auto new_value = CalculateHostileTakeoverValue(c);
2416 if (new_value != this->company_value) {
2417 this->company_value = new_value;
2418 this->ReInit();
2419 }
2420 }};
2421
2422private:
2423 bool hostile_takeover = false;
2425};
2426
2427static constexpr std::initializer_list<NWidgetPart> _nested_buy_company_widgets = {
2431 EndContainer(),
2437 EndContainer(),
2441 EndContainer(),
2442 EndContainer(),
2443 EndContainer(),
2444};
2445
2448 WindowPosition::Automatic, {}, 0, 0,
2449 WindowClass::BuyCompany, WindowClass::None,
2451 _nested_buy_company_widgets
2452);
2453
2459void ShowBuyCompanyDialog(CompanyID company, bool hostile_takeover)
2460{
2461 auto window = BringWindowToFrontById(WindowClass::BuyCompany, company);
2462 if (window == nullptr) {
2463 new BuyCompanyWindow(_buy_company_desc, company, hostile_takeover);
2464 }
2465}
constexpr T ClrBit(T &x, const uint8_t y)
Clears a bit in a variable.
constexpr bool Test(Tvalue_type value) const
Test if the value-th bit is set.
constexpr Timpl & Set()
Set all bits.
std::optional< Tvalue_type > GetNthSetBit(uint n) const
Get the value of the Nth set bit.
bool masked
Masked and unselectable item.
Enum-as-bit-set wrapper.
Iterate a range of enum values.
void RebuildDone()
Notify the sortlist that the rebuild is done.
bool NeedRebuild() const
Check if a rebuild is needed.
void ForceRebuild()
Force that a rebuild is needed.
An interval timer will fire every interval, and will continue to fire until it is deleted.
Definition timer.h:76
Baseclass for nested widgets.
uint current_x
Current horizontal size (after resizing).
Base class for a 'real' widget.
void SetStringTip(StringID string, StringID tool_tip)
Set string and tool tip of the nested widget.
Definition widget.cpp:1200
Base class for a resizable nested widget.
bool UpdateVerticalSize(uint min_y)
Set absolute (post-scaling) minimal size of the widget.
Definition widget.cpp:1156
StringID name
Name of this rail type.
Definition rail.h:184
StringID name
Name of this rail type.
Definition road.h:79
void SetCount(size_t num)
Sets the number of elements in the list.
auto GetScrolledItemFromWidget(Tcontainer &container, int clickpos, const Window *const w, WidgetID widget, int padding=0, int line_height=-1) const
Return an iterator pointing to the element of a scrolled widget that a user clicked in.
size_type GetScrolledRowFromWidget(int clickpos, const Window *const w, WidgetID widget, int padding=0, int line_height=-1) const
Compute the row of a scrolled widget that a user clicked in.
Definition widget.cpp:2474
void SetCapacityFromWidget(Window *w, WidgetID widget, int padding=0)
Set capacity of visible elements from the size and resize properties of a widget.
Definition widget.cpp:2548
size_type GetCount() const
Gets the number of elements in the list.
auto GetVisibleRangeIterators(Tcontainer &container) const
Get a pair of iterators for the range of visible elements in a container.
size_type GetPosition() const
Gets the position of the first visible element in the list.
Management class for customizing the face of the company manager.
void SelectDisplayPlanes(bool advanced)
Select planes to display to the user with the NWID_SELECTION widgets WID_SCMF_SEL_LOADSAVE,...
uint click_state
Click state on selected face variable.
void UpdateWidgetSize(WidgetID widget, Dimension &size, const Dimension &padding, Dimension &fill, Dimension &resize) override
Update size and resize step of a widget in the window.
std::vector< const FaceVar * > face_vars
Visible face variables.
void OnResize() override
Called after the window got resized.
bool advanced
advanced company manager face selection window
uint selected_var
Currently selected face variable. UINT_MAX for none, UINT_MAX - 1 means style is clicked instead.
void DrawWidget(const Rect &r, WidgetID widget) const override
Draw the contents of a nested widget.
CompanyManagerFace face
company manager face bits
int line_height
Height of each face variable row.
void UpdateData()
Make face bits valid and update visible face variables.
void OnQueryTextFinished(std::optional< std::string > str) override
The query window opened from this window has closed.
void OnClick(Point pt, WidgetID widget, int click_count) override
A click with the left mouse button has been made on the window.
void OnTimeout() override
Called when this window's timeout has been reached.
void OnInit() override
Notification that the nested widget tree gets initialized.
static Year year
Current year, starting at 0.
static bool UsingWallclockUnits(bool newgame=false)
Check if we are using wallclock units.
StrongType::Typedef< int32_t, struct YearTag< struct Economy >, StrongType::Compare, StrongType::Integer > Year
RectPadding frametext
Padding inside frame with text.
Definition window_gui.h:42
static WidgetDimensions scaled
Widget dimensions scaled for current zoom level.
Definition window_gui.h:30
int hsep_wide
Wide horizontal spacing.
Definition window_gui.h:63
static const WidgetDimensions unscaled
Unscaled widget dimensions.
Definition window_gui.h:94
Functions related to commands.
Definition of stuff that is very close to a company, like the company struct itself.
Money CalculateHostileTakeoverValue(const Company *c)
Calculate what you have to pay to take over a company.
Definition economy.cpp:180
Money CalculateCompanyValue(const Company *c, bool including_loan=true)
Calculate the value of the company.
Definition economy.cpp:153
std::optional< CompanyManagerFace > ParseCompanyManagerFaceCode(std::string_view str)
Parse a face code into a company manager face.
FaceVars GetCompanyManagerFaceVars(uint style)
Get the face variables for a face style.
void RandomiseCompanyManagerFace(CompanyManagerFace &cmf, Randomizer &randomizer)
Completely randomise a company manager face, including style.
std::string _company_manager_face
for company manager face storage in openttd.cfg
PaletteID GetCompanyPalette(CompanyID company)
Get the palette for recolouring with a company colour.
void SetCompanyManagerFaceStyle(CompanyManagerFace &cmf, uint style)
Set a company face style.
uint GetNumCompanyManagerFaceStyles()
Get the number of company manager face styles.
std::string FormatCompanyManagerFaceCode(const CompanyManagerFace &cmf)
Get a face code representation of a company manager face.
CompanyID _local_company
Company controlled by the human player at this client. Can also be COMPANY_SPECTATOR.
Command definitions related to companies.
Functions related to companies.
void ShowCompanyFinances(CompanyID company)
Open the finances window of a company.
static Money DrawYearCategory(const Rect &r, int start_y, const ExpensesList &list, const Expenses &tbl)
Draw a category of expenses/revenues in the year column.
static uint GetMaxCategoriesWidth()
Get the required width of the "categories" column, equal to the widest element.
constexpr uint8_t GetColourOffset(const Livery &l, bool primary)
Get either the primary or secondary colour of the given Livery for offsets.
static void DrawYearColumn(const Rect &r, TimerGameEconomy::Year year, const Expenses &tbl)
Draw a column with prices.
static WindowDesc _company_desc(WindowPosition::Automatic, "company", 0, 0, WindowClass::Company, WindowClass::None, {}, _nested_company_widgets)
Window definition for the company window.
static const std::initializer_list< ExpensesType > _expenses_list_capital_costs
List of capital expenses.
void ShowBuyCompanyDialog(CompanyID company, bool hostile_takeover)
Show the query to buy another company.
static WindowDesc _company_finances_desc(WindowPosition::Automatic, "company_finances", 0, 0, WindowClass::Finances, WindowClass::None, {}, _nested_company_finances_widgets)
Window definition for the company finances window.
static const std::initializer_list< ExpensesList > _expenses_list_types
Types of expense lists.
static void DrawPrice(Money amount, int left, int right, int top, TextColour colour)
Draw an amount of money.
static constexpr VehicleTypeIndexArray< const StringID > _company_view_vehicle_count_strings
Strings for the company vehicle counts.
static const EnumIndexArray< LiveryClass, LiveryScheme, LiveryScheme::End > _livery_class
Association of liveries to livery classes.
static void ShowCompanyInfrastructure(CompanyID company)
Open the infrastructure window of a company.
static void DrawCategories(const Rect &r)
Draw the expenses categories.
static void DoSelectCompanyManagerFace(Window *parent)
Company GUI constants.
void ShowCompany(CompanyID company)
Show the window with the overview of the company.
static WindowDesc _buy_company_desc(WindowPosition::Automatic, {}, 0, 0, WindowClass::BuyCompany, WindowClass::None, WindowDefaultFlag::Construction, _nested_buy_company_widgets)
Window definition for the window to buy a company.
static WindowDesc _select_company_manager_face_desc(WindowPosition::Automatic, {}, 0, 0, WindowClass::CompanyManagerFace, WindowClass::None, WindowDefaultFlag::Construction, _nested_select_company_manager_face_widgets)
Company manager face selection window description.
static WindowDesc _company_infrastructure_desc(WindowPosition::Automatic, "company_infrastructure", 0, 0, WindowClass::CompanyInfrastructure, WindowClass::None, {}, _nested_company_infrastructure_widgets)
Window definition for the company infrastructure statistics window.
static const std::initializer_list< ExpensesType > _expenses_list_operating_costs
List of operating expenses.
static uint GetTotalCategoriesHeight()
Get the total height of the "categories" column.
static constexpr std::initializer_list< NWidgetPart > _nested_select_company_manager_face_widgets
Nested widget description for the company manager face selection dialog.
static const std::initializer_list< ExpensesType > _expenses_list_revenue
List of revenues.
static WindowDesc _select_company_livery_desc(WindowPosition::Automatic, "company_colour_scheme", 0, 0, WindowClass::CompanyLivery, WindowClass::None, {}, _nested_select_company_livery_widgets)
Window definition for the company livery configuration window.
void DirtyCompanyInfrastructureWindows(CompanyID company)
Redraw all windows with company infrastructure counts.
void DrawCompanyManagerFace(const CompanyManagerFace &cmf, Colours colour, const Rect &r)
Draws the face of a company manager's face.
static void DrawCategory(const Rect &r, int start_y, const ExpensesList &list)
Draw a category of expenses (revenue, operating expenses, capital expenses).
Functionality related to the company manager's face.
@ Palette
FaceVar describes a palette to apply to the given parts bitmask.
@ Sprite
FaceVar describes an offset to the given SpriteID.
@ Toggle
FaceVar describes which other FaceVars should be turned off.
uint64_t GetActiveFaceVars(const CompanyManagerFace &cmf, FaceVars vars)
Get a bitmask of currently active face variables.
void ScaleAllCompanyManagerFaceBits(CompanyManagerFace &cmf, FaceVars vars)
Scales all company manager's face bits to the correct scope.
static const uint MAX_LENGTH_PRESIDENT_NAME_CHARS
The maximum length of a president name in characters including '\0'.
static const uint MAX_LENGTH_COMPANY_NAME_CHARS
The maximum length of a company name in characters including '\0'.
static constexpr CompanyID COMPANY_SPECTATOR
The client is spectating.
Types related to the company widgets.
@ WID_CF_CAPTION
Caption of the window.
@ WID_CF_SEL_BUTTONS
Selection of buttons.
@ WID_CF_SEL_PANEL
Select panel or nothing.
@ WID_CF_EXPS_CATEGORY
Column for expenses category strings.
@ WID_CF_EXPS_PRICE1
Column for year Y-2 expenses.
@ WID_CF_INFRASTRUCTURE
View company infrastructure.
@ WID_CF_TOGGLE_SIZE
Toggle windows size.
@ WID_CF_EXPS_PRICE2
Column for year Y-1 expenses.
@ WID_CF_OWN_VALUE
Own funds, not including loan.
@ WID_CF_LOAN_VALUE
Loan.
@ WID_CF_INCREASE_LOAN
Increase loan.
@ WID_CF_INTEREST_RATE
Loan interest rate.
@ WID_CF_BALANCE_VALUE
Bank balance value.
@ WID_CF_EXPS_PRICE3
Column for year Y expenses.
@ WID_CF_BALANCE_LINE
Available cash.
@ WID_CF_REPAY_LOAN
Decrease loan..
@ WID_CF_SEL_MAXLOAN
Selection of maxloan column.
@ WID_CF_MAXLOAN_VALUE
Max loan widget.
@ WID_BC_NO
No button.
@ WID_BC_YES
Yes button.
@ WID_BC_QUESTION
Question text.
@ WID_BC_CAPTION
Caption of window.
@ WID_BC_FACE
Face button.
@ WID_SCMF_CAPTION
Caption of window.
@ WID_SCMF_TOGGLE_LARGE_SMALL_BUTTON
Toggle for large or small.
@ WID_SCMF_STYLE
Style selector widget.
@ WID_SCMF_SEL_RESIZE
Selection to display the resize button.
@ WID_SCMF_SELECT_FACE
Select face.
@ WID_SCMF_RANDOM_NEW_FACE
Create random new face.
@ WID_SCMF_SEL_PARTS
Selection to display the buttons for setting each part of the face in the advanced view.
@ WID_SCMF_PARTS_SCROLLBAR
Scrollbar for configuration parts widget.
@ WID_SCMF_CANCEL
Cancel.
@ WID_SCMF_SAVE
Save face.
@ WID_SCMF_SEL_LOADSAVE
Selection to display the load/save/number buttons in the advanced view.
@ WID_SCMF_FACE
Current face.
@ WID_SCMF_LOAD
Load face.
@ WID_SCMF_ACCEPT
Accept.
@ WID_SCMF_TOGGLE_LARGE_SMALL
Toggle for large or small.
@ WID_SCMF_FACECODE
Get the face code.
@ WID_SCMF_PARTS
Face configuration parts widget.
@ WID_SCL_CLASS_AIRCRAFT
Class aircraft.
@ WID_SCL_MATRIX_SCROLLBAR
Matrix scrollbar.
@ WID_SCL_CLASS_SHIP
Class ship.
@ WID_SCL_SEC_COL_DROP_SEL
Container for secondary color dropdown, which can be hidden.
@ WID_SCL_GROUPS_SHIP
Ship groups.
@ WID_SCL_GROUPS_ROAD
Road groups.
@ WID_SCL_CLASS_ROAD
Class road.
@ WID_SCL_GROUPS_AIRCRAFT
Aircraft groups.
@ WID_SCL_SEC_COL_DROPDOWN
Dropdown for secondary colour.
@ WID_SCL_SPACER_DROPDOWN
Spacer for dropdown.
@ WID_SCL_GROUPS_RAIL
Rail groups.
@ WID_SCL_PRI_COL_DROPDOWN
Dropdown for primary colour.
@ WID_SCL_CLASS_RAIL
Class rail.
@ WID_SCL_MATRIX
Matrix.
@ WID_SCL_CAPTION
Caption of window.
@ WID_SCL_CLASS_GENERAL
Class general.
@ WID_CI_SCROLLBAR
Infrastructure list scrollbar.
@ WID_CI_CAPTION
Caption of window.
@ WID_CI_LIST
Infrastructure list.
CompanyWidgets
Widgets of the CompanyWindow class.
@ WID_C_SELECT_VIEW_BUILD_HQ
Panel about HQ.
@ WID_C_DESC_INFRASTRUCTURE_COUNTS
Infrastructure count.
@ WID_C_DESC_VEHICLE
Vehicles.
@ WID_C_COLOUR_SCHEME
Button to change colour scheme.
@ WID_C_CAPTION
Caption of the window.
@ WID_C_VIEW_HQ
Button to view the HQ.
@ WID_C_SELECT_RELOCATE
Panel about 'Relocate HQ'.
@ WID_C_SELECT_BUTTONS
Selection widget for the button bar.
@ WID_C_VIEW_INFRASTRUCTURE
Panel about infrastructure.
@ WID_C_SELECT_HOSTILE_TAKEOVER
Selection widget for the hostile takeover button.
@ WID_C_SELECT_GIVE_MONEY
Selection widget for the give money button.
@ WID_C_DESC_COLOUR_SCHEME
Colour scheme.
@ WID_C_GIVE_MONEY
Button to give money.
@ WID_C_SELECT_MULTIPLAYER
Multiplayer selection panel.
@ WID_C_DESC_INAUGURATION
Inauguration.
@ WID_C_DESC_COLOUR_SCHEME_EXAMPLE
Colour scheme example.
@ WID_C_BUILD_HQ
Button to build the HQ.
@ WID_C_HOSTILE_TAKEOVER
Button to hostile takeover another company.
@ WID_C_DESC_INFRASTRUCTURE
Infrastructure.
@ WID_C_FACE_TITLE
Title for the face.
@ WID_C_DESC_COMPANY_VALUE
Company value.
@ WID_C_COMPANY_JOIN
Button to join company.
@ WID_C_PRESIDENT_NAME
Button to change president name.
@ WID_C_DESC_VEHICLE_COUNTS
Vehicle count.
@ WID_C_NEW_FACE
Button to make new face.
@ WID_C_FACE
View of the face.
@ WID_C_RELOCATE_HQ
Button to relocate the HQ.
@ WID_C_COMPANY_NAME
Button to change company name.
Functions to handle different currencies.
const CurrencySpec & GetCurrency()
Get the currently selected currency.
void ShowDropDownList(Window *w, DropDownList &&list, int selected, WidgetID button, uint width, DropDownOptions options, std::string *const persistent_filter_text)
Show a drop down list.
Definition dropdown.cpp:591
Common drop down list components.
Types related to the drop down widget.
std::vector< std::unique_ptr< const DropDownListItem > > DropDownList
A drop down list is a collection of drop down list items.
Command definitions related to the economy.
EnumIndexArray< Money, ExpensesType, ExpensesType::End > Expenses
Data type for storage of Money for each ExpensesType category.
ExpensesType
Types of expenses.
@ LoanInterest
Interest payments over the loan.
@ Construction
Construction costs.
@ TrainRun
Running costs trains.
@ AircraftRevenue
Revenue from aircraft.
@ Property
Property costs.
@ Other
Other expenses.
@ RoadVehRevenue
Revenue from road vehicles.
@ NewVehicles
New vehicles.
@ AircraftRun
Running costs aircraft.
@ RoadVehRun
Running costs road vehicles.
@ ShipRevenue
Revenue from ships.
@ TrainRevenue
Revenue from trains.
@ ShipRun
Running costs ships.
static const int LOAN_INTERVAL
The "steps" in loan size, in British Pounds!
constexpr std::underlying_type_t< enum_type > to_underlying(enum_type e)
Implementation of std::to_underlying (from C++23).
Definition enum_type.hpp:21
EnumClassIndexContainer< std::array< T, to_underlying(N)>, Index > EnumIndexArray
A typedef for EnumClassIndexContainer using std::array as the backing container type.
Functions related to errors.
@ Info
Used for DoCommand-like (and some non-fatal AI GUI) errors/information.
Definition error.h:22
void ShowErrorMessage(EncodedString &&summary_msg, int x, int y, CommandCost &cc)
Display an error message in a window.
int GetCharacterHeight(FontSize size)
Get height of a character for a given font size.
Definition fontcache.cpp:88
Dimension maxdim(const Dimension &d1, const Dimension &d2)
Compute bounding box of both dimensions.
Geometry functions.
@ ForceRight
Force align to the right.
@ Centre
Align to the centre.
@ End
Align to the end, LTR/RTL aware.
@ Start
Align to the start, LTR/RTL aware.
int CentreBounds(int min, int max, int size)
Determine where to position a centred object.
@ Top
Align to the top.
@ Middle
Align to the middle.
int GetStringHeight(std::string_view str, int maxw, FontSize fontsize)
Calculates height of string (in pixels).
Definition gfx.cpp:711
Dimension GetSpriteSize(SpriteID sprid, Point *offset, ZoomLevel zoom)
Get the size of a sprite.
Definition gfx.cpp:966
Dimension GetStringBoundingBox(std::string_view str, FontSize start_fontsize)
Return the string dimension in pixels.
Definition gfx.cpp:894
uint GetStringListWidth(std::span< const StringID > list, FontSize fontsize)
Get maximum width of a list of strings.
Definition gfx.cpp:918
void DrawSprite(SpriteID img, PaletteID pal, int x, int y, const SubSprite *sub, ZoomLevel zoom)
Draw a sprite, not in a viewport.
Definition gfx.cpp:1032
void GfxFillRect(int left, int top, int right, int bottom, const std::variant< PixelColour, PaletteID > &colour, FillRectMode mode)
Applies a certain FillRectMode-operation to a rectangle [left, right] x [top, bottom] on the screen.
Definition gfx.cpp:111
int DrawStringMultiLine(int left, int right, int top, int bottom, std::string_view str, ExtendedTextColour colour, Alignment align, bool underline, FontSize fontsize)
Draw string, possibly over multiple lines.
Definition gfx.cpp:782
int DrawString(int left, int right, int top, std::string_view str, ExtendedTextColour colour, Alignment align, bool underline, FontSize fontsize)
Draw string, possibly truncated to make it fit in its allocated space.
Definition gfx.cpp:663
bool IsShiftPressed()
Test if the shift key is pressed.
Definition gfx_func.h:88
Dimension GetScaledSpriteSize(SpriteID sprid)
Scale sprite size for GUI.
Definition widget.cpp:70
bool IsCtrlPressed()
Test if the ctrl key is pressed.
Definition gfx_func.h:82
@ Normal
Index of the normal font in the font tables.
Definition gfx_type.h:249
uint32_t PaletteID
The number of the palette.
Definition gfx_type.h:18
Colours
One of 16 base colours used for companies and windows/widgets.
Definition gfx_type.h:283
@ Invalid
Invalid marker.
Definition gfx_type.h:302
@ LightBlue
Light blue.
Definition gfx_type.h:290
@ Yellow
Yellow.
Definition gfx_type.h:288
@ End
End-of-array marker.
Definition gfx_type.h:301
@ Grey
Grey.
Definition gfx_type.h:299
TextColour
Colour of the strings, see _string_colourmap in table/string_colours.h or docs/ottd-colourtext-palett...
Definition gfx_type.h:315
@ White
White colour.
Definition gfx_type.h:330
@ FromString
Marker for telling to use the colour from the string.
Definition gfx_type.h:317
@ Orange
Orange colour.
Definition gfx_type.h:324
@ Gold
Gold colour.
Definition gfx_type.h:320
@ Black
Black colour.
Definition gfx_type.h:334
@ Company
Destination is a company.
Definition goal_type.h:56
constexpr NWidgetPart SetMatrixDataTip(uint32_t cols, uint32_t rows, StringID tip={})
Widget part function for setting the data and tooltip of WWT_MATRIX widgets.
constexpr NWidgetPart SetFill(uint16_t fill_x, uint16_t fill_y)
Widget part function for setting filling.
constexpr NWidgetPart SetSpriteTip(SpriteID sprite, StringID tip={})
Widget part function for setting the sprite and tooltip.
constexpr NWidgetPart SetToolbarMinimalSize(int width)
Widget part function to setting the minimal size for a toolbar button.
constexpr NWidgetPart SetPIP(uint8_t pre, uint8_t inter, uint8_t post)
Widget part function for setting a pre/inter/post spaces.
constexpr NWidgetPart SetScrollbar(WidgetID index)
Attach a scrollbar to a widget.
constexpr NWidgetPart SetPadding(uint8_t top, uint8_t right, uint8_t bottom, uint8_t left)
Widget part function for setting additional space around a widget.
constexpr NWidgetPart SetStringTip(StringID string, StringID tip={})
Widget part function for setting the string and tooltip.
constexpr NWidgetPart SetAspect(float ratio, AspectFlags flags=AspectFlag::ResizeX)
Widget part function for setting the aspect ratio.
constexpr NWidgetPart SetMinimalTextLines(uint8_t lines, uint8_t spacing, FontSize size=FontSize::Normal)
Widget part function for setting the minimal text lines.
constexpr NWidgetPart SetMinimalSize(int16_t x, int16_t y)
Widget part function for setting the minimal size.
constexpr NWidgetPart SetToolTip(StringID tip)
Widget part function for setting tooltip and clearing the widget data.
constexpr NWidgetPart EndContainer()
Widget part function for denoting the end of a container (horizontal, vertical, WWT_FRAME,...
constexpr NWidgetPart NWidget(WidgetType tp, Colours col, WidgetID idx=INVALID_WIDGET)
Widget part function for starting a new 'real' widget.
constexpr NWidgetPart SetAlignment(Alignment align)
Widget part function for setting the alignment of text/images.
constexpr NWidgetPart SetResize(int16_t dx, int16_t dy)
Widget part function for setting the resize step.
constexpr NWidgetPart SetPIPRatio(uint8_t ratio_pre, uint8_t ratio_inter, uint8_t ratio_post)
Widget part function for setting a pre/inter/post ratio.
Command definitions related to engine groups.
static const CursorID SPR_CURSOR_HQ
Definition sprites.h:1572
void SetDirty() const
Mark entire window as dirty (in need of re-paint).
Definition window.cpp:1013
void MarkWholeScreenDirty()
This function mark the whole screen as dirty.
Definition gfx.cpp:1548
void BuildGuiGroupList(GUIGroupList &list, bool fold, Owner owner, VehicleType veh_type)
Build GUI group list, a sorted hierarchical list of groups for owner and vehicle type.
Functions/definitions that have something to do with groups.
GUI functions that shouldn't be here.
void ShowExtraViewportWindow(TileIndex tile=INVALID_TILE)
Show a new Extra Viewport window.
static const uint8_t LIT_ALL
Show the liveries of all companies.
Definition livery.h:19
EnumBitSet< LiveryScheme, uint32_t, LiveryScheme::End > LiverySchemes
Bitset of LiveryScheme elements.
Definition livery.h:64
LiveryScheme
List of different livery schemes.
Definition livery.h:22
@ Default
Default scheme.
Definition livery.h:24
@ End
End marker.
Definition livery.h:58
static const uint8_t LIT_COMPANY
Show the liveries of your own company.
Definition livery.h:18
LiveryClass
List of different livery classes, used only by the livery GUI.
Definition livery.h:67
@ Ship
Ship livery schemes.
Definition livery.h:71
@ GroupShip
Ship group.
Definition livery.h:75
@ Rail
Rail livery schemes.
Definition livery.h:69
@ Other
General livery schemes.
Definition livery.h:68
@ GroupRail
Rail group.
Definition livery.h:73
@ GroupAircraft
Aircraft group.
Definition livery.h:76
@ GroupRoad
Road group.
Definition livery.h:74
@ Aircraft
Aircraft livery schemes.
Definition livery.h:72
@ Road
Road livery schemes.
Definition livery.h:70
#define Rect
Macro that prevents name conflicts between included headers.
#define Point
Macro that prevents name conflicts between included headers.
constexpr bool IsInsideBS(const T x, const size_t base, const size_t size)
Checks if a value is between a window started at some base point.
Miscellaneous command definitions.
@ Max
Loan/repay the maximum amount permitting money/settings.
Definition misc_cmd.h:20
@ Interval
Loan/repay LOAN_INTERVAL.
Definition misc_cmd.h:19
void ShowQueryString(std::string_view str, StringID caption, uint maxsize, Window *parent, CharSetFilter afilter, QueryStringFlags flags)
Show a query popup window with a textbox in it.
void UpdateQueryStringDefault(std::string_view str)
Updates default text value of query strign window.
bool _networking
are we in networking mode?
Definition network.cpp:63
bool _network_server
network-server is active
Definition network.cpp:64
bool NetworkCanJoinCompany(CompanyID company_id)
Returns whether the given company can be joined by this client.
Definition network.cpp:139
Basic functions/variables used all over the place.
void NetworkClientRequestMove(CompanyID company_id)
Notify the server of this client wanting to be moved to another company.
Network functions used by other parts of OpenTTD.
void NetworkServerDoMove(ClientID client_id, CompanyID company_id)
Handle the tid-bits of moving a client from one company to another.
@ Server
Servers always have this ID.
GRFLoadedFeatures _loaded_newgrf_features
Indicates which are the newgrf features currently loaded ingame.
Definition newgrf.cpp:75
Base for the NewGRF implementation.
Command definitions related to objects.
Types related to object tiles.
static const ObjectType OBJECT_HQ
HeadQuarter of a player.
Definition object_type.h:22
static constexpr PixelColour PC_BLACK
Black palette colour.
static constexpr PixelColour PC_WHITE
White palette colour.
Rail specific functions.
std::vector< RailType > _sorted_railtypes
Sorted list of rail types.
Definition rail_cmd.cpp:46
Money RailMaintenanceCost(RailType railtype, uint32_t num, uint32_t total_num)
Calculates the maintenance cost of a number of track bits.
Definition rail.h:503
Money SignalMaintenanceCost(uint32_t num)
Calculates the maintenance cost of a number of signals.
Definition rail.h:514
const RailTypeInfo * GetRailTypeInfo(RailType railtype)
Returns a pointer to the Railtype information for a given railtype.
Definition rail.h:320
RailType
Enumeration for all possible railtypes.
Definition rail_type.h:26
Randomizer _interactive_random
Random used everywhere else, where it does not (directly) influence the game state.
Road specific functions.
const RoadTypeInfo * GetRoadTypeInfo(RoadType roadtype)
Returns a pointer to the Roadtype information for a given roadtype.
Definition road.h:217
std::vector< RoadType > _sorted_roadtypes
Sorted list of road types.
Definition road_cmd.cpp:56
Functions related to roads.
Money RoadMaintenanceCost(RoadType roadtype, uint32_t num, uint32_t total_num)
Calculates the maintenance cost of a number of road bits.
Definition road_func.h:107
RoadType
The different roadtypes we support.
Definition road_type.h:24
A number of safeguards to prevent using unsafe methods.
GameSettings _settings_game
Game settings of a running game or the scenario editor.
Definition settings.cpp:61
ClientSettings _settings_client
The current settings for this game.
Definition settings.cpp:60
void DrawArrowButtons(int x, int y, Colours button_colour, uint8_t state, bool clickable_left, bool clickable_right)
Draw [<][>] boxes.
void DrawBoolButton(int x, int y, Colours button_colour, Colours background, bool state, bool clickable)
Draw a toggle button.
Functions for setting GUIs.
#define SETTING_BUTTON_WIDTH
Width of setting buttons.
#define SETTING_BUTTON_HEIGHT
Height of setting buttons.
static PaletteID GetColourPalette(Colours colour)
Get recolour palette for a colour.
Definition sprite.h:221
static const SpriteID SPR_IMG_COMPANY_GENERAL
Definition sprites.h:1253
static const SpriteID SPR_IMG_TRAINLIST
Definition sprites.h:1261
static const SpriteID SPR_SQUARE
Coloured square (used for newgrf compatibility).
Definition sprites.h:71
static const SpriteID SPR_IMG_TRUCKLIST
Definition sprites.h:1262
static const PaletteID PALETTE_TO_BROWN
Definition sprites.h:1777
static const PaletteID PALETTE_TO_BLUE
Definition sprites.h:1771
static const PaletteID PALETTE_TO_GREEN
Definition sprites.h:1769
static const SpriteID SPR_IMG_AIRPLANESLIST
Definition sprites.h:1264
static const SpriteID SPR_IMG_SHIPLIST
Definition sprites.h:1263
static const SpriteID SPR_GRADIENT
Manager face sprites.
Definition sprites.h:385
static const SpriteID SPR_VEH_BUS_SW_VIEW
Definition sprites.h:1101
Money AirportMaintenanceCost(Owner owner)
Calculates the maintenance cost of all airports of a company.
Definition station.cpp:548
Functions related to stations.
Money StationMaintenanceCost(uint32_t num)
Calculates the maintenance cost of a number of station tiles.
Definition of base types and functions in a cross-platform compatible way.
Parse strings.
static std::optional< T > ParseInteger(std::string_view arg, int base=10, bool clamp=false)
Change a string into its number representation.
@ CS_NUMERAL
Only numeric ones.
Definition string_type.h:26
@ CS_ALPHANUMERAL
Both numeric and alphabetic and spaces and stuff.
Definition string_type.h:25
uint64_t GetParamMaxValue(uint64_t max_value, uint min_count, FontSize size)
Get some number that is suitable for string size computations.
Definition strings.cpp:235
EncodedString GetEncodedString(StringID str)
Encode a string with no parameters into an encoded string.
Definition strings.cpp:89
std::string GetString(StringID string)
Resolve the given StringID into a std::string with formatting but no parameters.
Definition strings.cpp:423
TextDirection _current_text_dir
Text direction of the currently selected language.
Definition strings.cpp:55
Functions related to OTTD's strings.
StrongType::Typedef< uint32_t, struct StringIDTag, StrongType::Compare, StrongType::Integer > StringID
Numeric value that represents a string, independent of the selected language.
@ TD_RTL
Text is written right-to-left by default.
void DrawWidget(const Rect &r, WidgetID widget) const override
Draw the contents of a nested widget.
Money company_value
The value of the company for which the user can buy it.
std::string GetWidgetString(WidgetID widget, StringID stringid) const override
Get the raw string for a widget.
void OnClick(Point pt, WidgetID widget, int click_count) override
A click with the left mouse button has been made on the window.
void UpdateWidgetSize(WidgetID widget, Dimension &size, const Dimension &padding, Dimension &fill, Dimension &resize) override
Update size and resize step of a widget in the window.
bool hostile_takeover
Whether the window is showing a hostile takeover.
const IntervalTimer< TimerWindow > rescale_interval
Check on a regular interval if the company value has changed.
Window class displaying the company finances.
const IntervalTimer< TimerWindow > rescale_interval
Check on a regular interval if the maximum amount of money has changed.
void DrawWidget(const Rect &r, WidgetID widget) const override
Draw the contents of a nested widget.
void UpdateWidgetSize(WidgetID widget, Dimension &size, const Dimension &padding, Dimension &fill, Dimension &resize) override
Update size and resize step of a widget in the window.
void OnClick(Point pt, WidgetID widget, int click_count) override
A click with the left mouse button has been made on the window.
void OnInvalidateData(int, bool) override
Some data on this window has become invalid.
std::string GetWidgetString(WidgetID widget, StringID stringid) const override
Get the raw string for a widget.
bool small
Window is toggled to 'small'.
static Money max_money
The maximum amount of money a company has had this 'run'.
uint8_t first_visible
First visible expenses column. The last column (current) is always visible.
void SetupWidgets()
Setup the widgets in the nested tree, such that the finances window is displayed properly.
void OnPaint() override
The window must be repainted.
void OnInit() override
Notification that the nested widget tree gets initialized.
void OnInvalidateData(int data=0, bool gui_scope=true) override
Some data on this window has become invalid.
void UpdateWidgetSize(WidgetID widget, Dimension &size, const Dimension &padding, Dimension &fill, Dimension &resize) override
Update size and resize step of a widget in the window.
void FindWindowPlacementAndResize(int def_width, int def_height, bool allow_resize) override
Resize window towards the default size.
void DrawWidget(const Rect &r, WidgetID widget) const override
Draw the contents of a nested widget.
std::string GetWidgetString(WidgetID widget, StringID stringid) const override
Get the raw string for a widget.
void OnResize() override
Called after the window got resized.
std::array< uint32_t, ROADTYPE_END > road
Count of company owned track bits for each road type.
uint32_t GetRailTotal() const
Get total sum of all owned track bits.
uint32_t station
Count of company owned station tiles.
uint32_t signal
Count of company owned signals.
std::array< uint32_t, RAILTYPE_END > rail
Count of company owned track bits for each rail type.
uint32_t airport
Count of company owned airports.
uint32_t water
Count of company owned track bits for canals.
uint style
Company manager face style.
TileIndex location_of_HQ
Northern tile of HQ; INVALID_TILE when there is none.
bool is_ai
If true, the company is (also) controlled by the computer (a NoAI program).
Money current_loan
Amount of money borrowed from the bank.
TimerGameCalendar::Year inaugurated_year_calendar
Calendar year of starting the company. Used to display proper Inauguration year while in wallclock mo...
TimerGameEconomy::Year inaugurated_year
Economy year of starting the company.
Colours colour
Company colour.
CompanyManagerFace face
Face description of the president.
std::array< Expenses, 3 > yearly_expenses
Expenses of the company for the last three years.
Money money
Money owned by the company.
Window with general information about a company.
void OnResize() override
Called after the window got resized.
const IntervalTimer< TimerWindow > redraw_interval
Redraw the window on a regular interval.
void UpdateWidgetSize(WidgetID widget, Dimension &size, const Dimension &padding, Dimension &fill, Dimension &resize) override
Update size and resize step of a widget in the window.
static constexpr CompanyWidgets INVALID_QUERY_WIDGET
WID_C_CAPTION does not have a query string, so it can be safely used as invalid value.
void OnClick(Point pt, WidgetID widget, int click_count) override
A click with the left mouse button has been made on the window.
void OnPlaceObjectAbort() override
The user cancelled a tile highlight mode that has been set.
std::string GetWidgetString(WidgetID widget, StringID stringid) const override
Get the raw string for a widget.
void OnPlaceObject(Point pt, TileIndex tile) override
The user clicked some place on the map when a tile highlight mode has been set.
void DrawWidget(const Rect &r, WidgetID widget) const override
Draw the contents of a nested widget.
void OnQueryTextFinished(std::optional< std::string > str) override
The query window opened from this window has closed.
void OnInvalidateData(int data=0, bool gui_scope=true) override
Some data on this window has become invalid.
CompanyWindowPlanes
Display planes in the company window.
@ CWP_RELOCATE_SHOW
Show the relocate HQ button.
@ CWP_RELOCATE_HIDE
Hide the relocate HQ button.
@ CWP_VB_BUILD
Display the build button.
@ CWP_VB_VIEW
Display the view button.
void OnPaint() override
The window must be repainted.
Money GetMaxLoan() const
Calculate the max allowed loan for this company.
VehicleTypeIndexArray< GroupStatistics > group_all
NOSAVE: Statistics for the ALL_GROUP group.
CompanyInfrastructure infrastructure
NOSAVE: Counts of company owned infrastructure.
T y
Y coordinate.
T x
X coordinate.
uint16_t rate
The conversion rate compared to the base currency.
Dimensions (a width and height) of a rectangle in 2D.
value_type height
The height of the rectangle.
value_type width
The width of the rectangle.
bool infrastructure_maintenance
enable monthly maintenance fee for owner infrastructure
Expense list container.
uint GetListWidth() const
Compute width of the expenses categories.
const std::initializer_list< ExpensesType > & items
List of expenses types.
const StringID title
StringID of list title.
Information about the valid values of CompanyManagerFace bitgroups as well as the sprites to draw.
uint8_t position
Position in UI.
FaceVarType type
Type of variable.
StringID name
Name of the configurable component of the face.
uint8_t valid_values
The number of valid values.
bool has_2CC
Set if any vehicle is loaded which uses 2cc (two company colours).
Definition newgrf.h:208
EconomySettings economy
settings to change the economy
Group data.
Definition group.h:76
Livery livery
Custom colour scheme for vehicles in this group.
Definition group.h:82
GroupID parent
Parent group.
Definition group.h:88
VehicleType vehicle_type
Vehicle type of the group.
Definition group.h:79
Information about a particular livery.
Definition livery.h:82
Flags in_use
Livery flags.
Definition livery.h:92
Colours colour2
Second colour, for vehicles with 2CC support.
Definition livery.h:94
Colours colour1
First colour, for all vehicles.
Definition livery.h:93
@ Primary
Primary colour is set.
Definition livery.h:85
@ Secondary
Secondary colour is set.
Definition livery.h:86
static Company * Get(auto index)
static Company * GetIfValid(auto index)
constexpr uint Horizontal() const
Get total horizontal padding of RectPadding.
Specification of a rectangle with absolute coordinates of all edges.
Rect WithWidth(int width, bool end) const
Copy Rect and set its width.
Rect Shrink(int s) const
Copy and shrink Rect by s pixels.
Rect WithHeight(int height, bool end=false) const
Copy Rect and set its height.
Rect Indent(int indent, bool end) const
Copy Rect and indent it from its position.
Rect CentreToHeight(int height) const
Centre a vertical dimension within this Rect.
int Height() const
Get height of Rect.
Rect Translate(int x, int y) const
Copy and translate Rect by x,y pixels.
Company livery colour scheme window.
void OnDropdownSelect(WidgetID widget, int index, int) override
A dropdown option associated to this window has been selected.
LiverySchemes visible_schemes
Currently visible livery schemes.
void OnInvalidateData(int data=0, bool gui_scope=true) override
Some data on this window has become invalid.
void BuildLiveryList()
Build 'list' of visible livery schemes.
struct SelectCompanyLiveryWindow::@313207310206021013204234143253377076057020012134 sel
Current selection.
void UpdateWidgetSize(WidgetID widget, Dimension &size, const Dimension &padding, Dimension &fill, Dimension &resize) override
Update size and resize step of a widget in the window.
void OnPaint() override
The window must be repainted.
LiverySchemes schemes
Selected schemes.
void DrawWidget(const Rect &r, WidgetID widget) const override
Draw the contents of a nested widget.
void OnClick(Point pt, WidgetID widget, int click_count) override
A click with the left mouse button has been made on the window.
std::string GetWidgetString(WidgetID widget, StringID stringid) const override
Get the raw string for a widget.
void OnResize() override
Called after the window got resized.
GroupID group
Selected group.
Iterable ensemble of each set bit in a value.
High level window description.
Definition window_gui.h:171
Number to differentiate different windows of the same class.
Data structure for an opened window.
Definition window_gui.h:272
void ReInit(int rx=0, int ry=0, bool reposition=false)
Re-initialize a window, and optionally change its size.
Definition window.cpp:1025
virtual void Close(int data=0)
Hide the window and all its child windows, and mark them for a later deletion.
Definition window.cpp:1150
void FinishInitNested(WindowNumber window_number=0)
Perform the second part of the initialization of a nested widget tree.
Definition window.cpp:1855
void DrawWidgets() const
Paint all widgets of a window.
Definition widget.cpp:792
void InvalidateData(int data=0, bool gui_scope=true)
Mark this window's data as invalid (in need of re-computing).
Definition window.cpp:3317
Window * parent
Parent window.
Definition window_gui.h:327
void RaiseWidget(WidgetID widget_index)
Marks a widget as raised.
Definition window_gui.h:468
void SetWidgetDirty(WidgetID widget_index) const
Invalidate a widget, i.e.
Definition window.cpp:565
virtual std::string GetWidgetString(WidgetID widget, StringID stringid) const
Get the raw string for a widget.
Definition window.cpp:513
ResizeInfo resize
Resize information.
Definition window_gui.h:313
void SetShaded(bool make_shaded)
Set the shaded state of the window to make_shaded.
Definition window.cpp:1068
void SetWidgetsDisabledState(bool disab_stat, Args... widgets)
Sets the enabled/disabled status of a list of widgets.
Definition window_gui.h:514
void CreateNestedTree()
Perform the first part of the initialization of a nested widget tree.
Definition window.cpp:1845
bool IsWidgetLowered(WidgetID widget_index) const
Gets the lowered state of a widget.
Definition window_gui.h:490
void RaiseButtons(bool autoraise=false)
Raise the buttons of the window.
Definition window.cpp:539
Owner owner
The owner of the content shown in this window. Company colour is acquired from this variable.
Definition window_gui.h:315
void EnableWidget(WidgetID widget_index)
Sets a widget to Enabled.
Definition window_gui.h:399
virtual void FindWindowPlacementAndResize(int def_width, int def_height, bool allow_resize)
Resize window towards the default size.
Definition window.cpp:1523
bool IsShaded() const
Is window shaded currently?
Definition window_gui.h:561
void SetTimeout()
Set the timeout flag of the window and initiate the timer.
Definition window_gui.h:354
Window(WindowDesc &desc)
Empty constructor, initialization has been moved to InitNested() called from the constructor of the d...
Definition window.cpp:1879
const NWID * GetWidget(WidgetID widnum) const
Get the nested widget with number widnum from the nested widget tree.
void LowerWidget(WidgetID widget_index)
Marks a widget as lowered.
Definition window_gui.h:459
void InitNested(WindowNumber number=0)
Perform complete initialization of the Window with nested widgets, to allow use.
Definition window.cpp:1869
const Scrollbar * GetScrollbar(WidgetID widnum) const
Return the Scrollbar to a widget index.
Definition window.cpp:322
void SetWidgetDisabledState(WidgetID widget_index, bool disab_stat)
Sets the enabled/disabled status of a widget.
Definition window_gui.h:380
int height
Height of the window (number of pixels down in y direction).
Definition window_gui.h:311
int width
width of the window (number of pixels to the right in x direction)
Definition window_gui.h:310
WindowNumber window_number
Window number within the window class.
Definition window_gui.h:301
Stuff related to the text buffer GUI.
@ EnableDefault
enable the 'Default' button ("\0" is returned)
Definition textbuf_gui.h:20
@ LengthIsInChars
the length of the string is counted in characters
Definition textbuf_gui.h:21
StrongType::Typedef< uint32_t, struct TileIndexTag, StrongType::Compare, StrongType::Integer, StrongType::Compatible< int32_t >, StrongType::Compatible< int64_t > > TileIndex
The index/ID of a Tile.
Definition tile_type.h:92
constexpr TileIndex INVALID_TILE
The very nice invalid tile marker.
Definition tile_type.h:100
Functions related to tile highlights.
void ResetObjectToPlace()
Reset the cursor and mouse mode handling back to default (normal cursor, only clicking in windows).
void SetObjectToPlaceWnd(CursorID icon, PaletteID pal, HighLightStyle mode, Window *w)
Change the cursor and mouse click/drag handling to a mode for performing special operations like tile...
@ HT_RECT
rectangle (stations, depots, ...)
Definition of Interval and OneShot timers.
Definition of the game-economy-timer.
Definition of the Window system.
VehicleType
Available vehicle types.
@ Ship
Ship vehicle type.
@ CompanyEnd
Last company-ownable type.
@ Aircraft
Aircraft vehicle type.
@ Road
Road vehicle type.
@ Train
Train vehicle type.
EnumIndexArray< T, VehicleType, Tend > VehicleTypeIndexArray
Array with VehicleType as index.
@ Group
Index is the group.
Definition vehiclelist.h:27
void SetTileSelectSize(int w, int h)
Highlight w by h tiles at the cursor.
bool ScrollMainWindowToTile(TileIndex tile, bool instant)
Scrolls the viewport of the main window to a given location.
Functions related to (drawing on) viewports.
Functions related to water management.
Money CanalMaintenanceCost(uint32_t num)
Calculates the maintenance cost of a number of canal tiles.
Definition water.h:53
@ WWT_PUSHTXTBTN
Normal push-button (no toggle button) with text caption.
@ WWT_IMGBTN
(Toggle) Button with image
Definition widget_type.h:41
@ WWT_LABEL
Centered label.
Definition widget_type.h:48
@ NWID_SPACER
Invisible widget that takes some space.
Definition widget_type.h:70
@ NWID_HORIZONTAL
Horizontal container.
Definition widget_type.h:66
@ WWT_TEXTBTN
(Toggle) Button with text
Definition widget_type.h:44
@ WWT_PANEL
Simple depressed panel.
Definition widget_type.h:39
@ WWT_STICKYBOX
Sticky box (at top-right of a window, after WWT_DEFSIZEBOX).
Definition widget_type.h:57
@ WWT_MATRIX
Grid of rows and columns.
Definition widget_type.h:50
@ WWT_SHADEBOX
Shade box (at top-right of a window, between WWT_DEBUGBOX and WWT_DEFSIZEBOX).
Definition widget_type.h:55
@ WWT_CAPTION
Window caption (window title between closebox and stickybox).
Definition widget_type.h:52
@ NWID_VSCROLLBAR
Vertical scrollbar.
Definition widget_type.h:76
@ NWID_VERTICAL
Vertical container.
Definition widget_type.h:68
@ WWT_CLOSEBOX
Close box (at top-left of a window).
Definition widget_type.h:60
@ WWT_EMPTY
Empty widget, place holder to reserve space in widget tree.
Definition widget_type.h:37
@ WWT_RESIZEBOX
Resize box (normally at bottom-right of a window).
Definition widget_type.h:59
@ WWT_DEFSIZEBOX
Default window size box (at top-right of a window, between WWT_SHADEBOX and WWT_STICKYBOX).
Definition widget_type.h:56
@ WWT_DROPDOWN
Drop down list.
Definition widget_type.h:61
@ WWT_TEXT
Pure simple text.
Definition widget_type.h:49
@ NWID_SELECTION
Stacked widgets, only one visible at a time (eg in a panel with tabs).
Definition widget_type.h:71
@ SZSP_HORIZONTAL
Display plane with zero size vertically, and filling and resizing horizontally.
@ SZSP_NONE
Display plane with zero size in both directions (none filling and resizing).
@ EqualSize
Containers should keep all their (resizing) children equally large.
Window * BringWindowToFrontById(WindowClass cls, WindowNumber number)
Find a window and make it the relative top-window on the screen.
Definition window.cpp:1326
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting).
Definition window.cpp:3255
Window functions not directly related to making/drawing windows.
Functions, definitions and such used only by the GUI.
@ Construction
This window is used for construction; close it whenever changing company.
Definition window_gui.h:154
Twindow * AllocateWindowDescFront(WindowDesc &desc, WindowNumber window_number, Targs... extra_arguments)
Open a new window.
@ Automatic
Find a place automatically.
Definition window_gui.h:145
int WidgetID
Widget ID.
Definition window_type.h:21