-
Notifications
You must be signed in to change notification settings - Fork 160
/
GovernmentWnd.cpp
1711 lines (1385 loc) · 69.2 KB
/
GovernmentWnd.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "GovernmentWnd.h"
#include "ClientUI.h"
#include "CUIControls.h"
#include "QueueListBox.h" // for PromptRow
#include "IconTextBrowseWnd.h"
#include "Sound.h"
#include "TextBrowseWnd.h"
#include "SidePanel.h"
#include "FleetWnd.h"
#include "../parse/Parse.h"
#include "../util/i18n.h"
#include "../util/Logger.h"
#include "../util/Order.h"
#include "../util/OptionsDB.h"
#include "../util/ScopedTimer.h"
#include "../Empire/Empire.h"
#include "../Empire/Government.h"
#include "../client/human/GGHumanClientApp.h"
#include <GG/DrawUtil.h>
#include <GG/StaticGraphic.h>
#include <GG/TabWnd.h>
#include <boost/algorithm/string.hpp>
using boost::placeholders::_1;
using boost::placeholders::_2;
enum class Availability : uint8_t {
Adopted = 0, // Policy is currently adopted
Adoptable = 1, // Policy can be adopted, but hasn't been adopted
Unaffordable = 2, // Policy is unlocked and has no restrictions, but is too expensive to adopt
Restricted = 3, // Policy is unlocked, but is restricted by exclusions and thus cannot be adopted
Locked = 4 // Policy has not been unlocked and thus cannot be adopted
};
namespace {
#if defined(__cpp_lib_constexpr_string) && ((!defined(__GNUC__) || (__GNUC__ > 12) || (__GNUC__ == 12 && __GNUC_MINOR__ >= 2))) && ((!defined(_MSC_VER) || (_MSC_VER >= 1934))) && ((!defined(__clang_major__) || (__clang_major__ >= 17)))
constexpr std::string EMPTY_STRING;
#else
const std::string EMPTY_STRING;
#endif
constexpr std::string_view POLICY_CONTROL_DROP_TYPE_STRING = "Policy Control";
constexpr GG::X SLOT_CONTROL_WIDTH{120};
constexpr GG::Y SLOT_CONTROL_HEIGHT{180};
constexpr int PAD{3};
constexpr double POLICY_PAD{0.125};
constexpr double POLICY_TEXT_POS_X{0.0625};
constexpr double POLICY_TEXT_POS_Y{0.75};
constexpr double POLICY_COST_POS_X{0.75};
constexpr double POLICY_COST_POS_Y{0.0625};
constexpr GG::X POLICY_SIZE_BUTTON_WIDTH{32};
/** Returns texture with which to render a PolicySlotControl, depending on
* \a category */
std::shared_ptr<GG::Texture> SlotBackgroundTexture(const std::string& category) {
std::string filename = boost::algorithm::to_lower_copy(category) + "_slot.png";
return ClientUI::GetTexture(ClientUI::ArtDir() / "icons" / "policies" / filename, true);
}
/** Returns background texture with which to render a PolicyControl,
* depending on the category of slot that the indicated \a policy can
* be put into. */
std::shared_ptr<GG::Texture> PolicyBackgroundTexture(const Policy* policy) {
if (policy) {
std::string filename = boost::algorithm::to_lower_copy(policy->Category()) + "_policy.png";
return ClientUI::GetTexture(ClientUI::ArtDir() / "icons" / "policies" / filename, true);
}
return ClientUI::GetTexture(ClientUI::ArtDir() / "misc" / "missing.png", true);
}
//////////////////////////////////////////////////
// AvailabilityManager //
//////////////////////////////////////////////////
/** A class to allow the storage of the state of a GUI availabilty filter
and the querying of that state WRT a policy. */
class AvailabilityManager {
public:
using DisplayedAvailabilies = std::array<bool, 5>;
AvailabilityManager(bool adopted, bool adoptable, bool unaffordable, bool restricted, bool locked);
const DisplayedAvailabilies& GetAvailabilities() const { return m_availabilities; };
bool GetAvailability(const Availability type) const;
void SetAvailability(const Availability type, const bool state);
void ToggleAvailability(const Availability type);
/** Given the GUI's displayed availabilities as stored in this
AvailabilityManager, return the displayed state of the \p policy.
Return none if the \p policy should not be displayed. */
bool PolicyDisplayed(const Policy& policy, int empire_id = GGHumanClientApp::GetApp()->EmpireID()) const;
private:
// A tuple of the toogle state of the 3-tuple of coupled
// availability filters in the GUI:
// Restricted, Available and Unavailable
DisplayedAvailabilies m_availabilities;
};
AvailabilityManager::AvailabilityManager(bool adopted, bool adoptable, bool unaffordable,
bool restricted, bool locked) :
m_availabilities{adopted, adoptable, unaffordable, restricted, locked}
{}
bool AvailabilityManager::GetAvailability(Availability availability) const {
auto idx = static_cast<std::underlying_type_t<Availability>>(availability);
if (idx >= m_availabilities.size())
return false;
return m_availabilities[idx];
}
void AvailabilityManager::SetAvailability(const Availability availability, bool state) {
auto idx = static_cast<std::underlying_type_t<Availability>>(availability);
if (idx >= m_availabilities.size())
ErrorLogger() << "AvailabilityManager::SetAvailability passed invalid availability: " << idx;
else
m_availabilities[idx] = state;
}
void AvailabilityManager::ToggleAvailability(const Availability type)
{ SetAvailability(type, !GetAvailability(type)); }
bool AvailabilityManager::PolicyDisplayed(const Policy& policy, int empire_id) const {
const auto [show_adopted, show_adoptable, show_unaffordable, show_restricted, show_locked] = m_availabilities;
const ScriptingContext context;
const auto* empire = context.GetEmpire(empire_id).get();
if (!empire)
return true;
const ScriptingContext source_context{empire->Source(context.ContextObjects()).get()};
const bool policy_adopted = empire->PolicyAdopted(policy.Name());
const bool policy_affordable = empire->PolicyAffordable(policy.Name(), source_context);
const bool policy_restricted = !empire->PolicyPrereqsAndExclusionsOK(policy.Name(), context.current_turn);
const bool policy_locked = !empire->PolicyAvailable(policy.Name());
if (policy_adopted && show_adopted)
return true;
if (show_locked && policy_locked && !policy_adopted)
return true;
if (show_unaffordable && !policy_affordable && !policy_adopted && !policy_restricted && !policy_locked)
return true;
if (show_restricted && policy_restricted && !policy_adopted && !policy_locked)
return true;
if (show_adoptable && !policy_adopted && policy_affordable && !policy_restricted && !policy_locked)
return true;
return false;
}
//////////////////////////
// PolicyBrowseWnd //
//////////////////////////
std::shared_ptr<GG::BrowseInfoWnd> PolicyBrowseWnd(const std::string& policy_name) {
const Policy* policy = GetPolicy(policy_name);
if (!policy)
return nullptr;
const ScriptingContext context;
int empire_id = GGHumanClientApp::GetApp()->EmpireID();
auto empire = context.GetEmpire(empire_id);
std::string main_text;
main_text += UserString(policy->Category()) + " - ";
main_text += UserString(policy->ShortDescription()) + "\n\n";
if (empire) {
bool adopted = empire->PolicyAdopted(policy_name);
bool available = empire->PolicyAvailable(policy_name);
bool restricted = !empire->PolicyPrereqsAndExclusionsOK(policy_name, context.current_turn);
const auto& adoption_cost_template{
adopted ? UserString("POLICY_ADOPTED") :
available && !restricted ? UserString("POLICY_ADOPTABLE_COST") :
restricted ? UserString("POLICY_RESTRICTED") :
UserString("POLICY_LOCKED")};
auto cost = policy->AdoptionCost(empire_id, context);
main_text += boost::io::str(FlexibleFormat(adoption_cost_template) % cost) + "\n\n";
bool exclusion_prereq_line_added = false;
const auto empire_policies = empire->AdoptedPolicies();
for (auto& ex : policy->Exclusions()) {
auto ad_it = std::find(empire_policies.begin(), empire_policies.end(), ex);
if (ad_it == empire_policies.end())
continue;
main_text += boost::io::str(FlexibleFormat(UserString("POLICY_EXCLUDED"))
% UserString(ex)) + "\n";
exclusion_prereq_line_added = true;
}
const auto empire_initial_policies = empire->InitialAdoptedPolicies();
for (auto& prereq : policy->Prerequisites()) {
auto init_it = std::find(
empire_initial_policies.begin(), empire_initial_policies.end(), prereq);
const auto& template_str = init_it == empire_initial_policies.end() ?
UserString("POLICY_PREREQ_MISSING") : UserString("POLICY_PREREQ_MET");
main_text += boost::io::str(FlexibleFormat(template_str)
% UserString(prereq)) + "\n";
exclusion_prereq_line_added = true;
}
if (exclusion_prereq_line_added)
main_text += "\n";
auto current_adoption_duration = empire->CurrentTurnsPolicyHasBeenAdopted(policy_name);
auto total_adoption_duration = empire->CumulativeTurnsPolicyHasBeenAdopted(policy_name);
const auto& adopted_time_timeplate{adopted ?
UserString("POLICY_ADOPTION_TIMES_CURRENT_AND_TOTAL") : UserString("POLICY_ADOPTION_TIME_TOTAL")};
main_text += boost::io::str(FlexibleFormat(adopted_time_timeplate)
% current_adoption_duration % total_adoption_duration) + "\n\n";
}
main_text += UserString(policy->Description());
return GG::Wnd::Create<IconTextBrowseWnd>(
ClientUI::PolicyIcon(policy_name), UserString(policy_name), main_text);
}
}
//////////////////////////////////////////////////
// PolicyControl //
//////////////////////////////////////////////////
/** UI representation of a government policy. Displayed in the PolicyPalette,
* and can be dragged onto SlotControls to add policies to the government. */
class PolicyControl : public GG::Control {
public:
explicit PolicyControl(const Policy* policy);
void CompleteConstruction() override;
const std::string& PolicyName() const { return m_policy ? m_policy->Name() : EMPTY_STRING; }
const Policy* GetPolicy() const { return m_policy; }
void Resize(GG::Pt sz, const int pts = ClientUI::Pts());
void Render() override;
void LClick(GG::Pt pt, GG::Flags<GG::ModKey> mod_keys) override;
void LDoubleClick(GG::Pt pt, GG::Flags<GG::ModKey> mod_keys) override;
void RClick(GG::Pt pt, GG::Flags<GG::ModKey> mod_keys) override;
mutable boost::signals2::signal<void (const Policy*, GG::Flags<GG::ModKey>)> ClickedSignal;
mutable boost::signals2::signal<void (const Policy*, GG::Pt pt)> RightClickedSignal;
mutable boost::signals2::signal<void (const Policy*)> DoubleClickedSignal;
private:
std::shared_ptr<GG::TextControl> m_name_label;
std::shared_ptr<GG::TextControl> m_cost_label;
std::shared_ptr<GG::StaticGraphic> m_icon;
std::shared_ptr<GG::StaticGraphic> m_background;
const Policy* m_policy = nullptr;
};
PolicyControl::PolicyControl(const Policy* policy) :
GG::Control(GG::X0, GG::Y0, SLOT_CONTROL_WIDTH, SLOT_CONTROL_HEIGHT, GG::INTERACTIVE),
m_policy(policy)
{}
void PolicyControl::CompleteConstruction() {
GG::Control::CompleteConstruction();
if (!m_policy)
return;
int empire_id = GGHumanClientApp::GetApp()->EmpireID();
const ScriptingContext context;
const auto& name = UserString(m_policy->Name());
const auto cost = static_cast<int>(m_policy->AdoptionCost(empire_id, context));
//std::cout << "PolicyControl: " << m_policy->Name() << std::endl;
m_background = GG::Wnd::Create<GG::StaticGraphic>(PolicyBackgroundTexture(m_policy),
GG::GRAPHIC_FITGRAPHIC | GG::GRAPHIC_PROPSCALE);
m_icon = GG::Wnd::Create<GG::StaticGraphic>(ClientUI::PolicyIcon(m_policy->Name()),
GG::GRAPHIC_FITGRAPHIC | GG::GRAPHIC_PROPSCALE);
m_name_label = GG::Wnd::Create<GG::TextControl>(GG::X0, GG::Y0, GG::X1, GG::Y1, name,
ClientUI::GetBoldFont(), ClientUI::TextColor(), GG::FORMAT_WORDBREAK);
m_cost_label = GG::Wnd::Create<GG::TextControl>(GG::X0, GG::Y0, GG::X1, GG::Y1, std::to_string(cost),
ClientUI::GetBoldFont(), ClientUI::TextColor());
m_background->Show();
m_icon->Show();
AttachChild(m_background);
AttachChild(m_icon);
AttachChild(m_name_label);
AttachChild(m_cost_label);
Resize(Size());
//DebugLogger() << "PolicyControl::PolicyControl this: " << this << " policy: " << policy << " named: " << (policy ? policy->Name() : "no policy");
SetDragDropDataType(POLICY_CONTROL_DROP_TYPE_STRING);
//DebugLogger() << "PolicyControl::PolicyControl policy name: " << m_policy->Name();
SetBrowseModeTime(GetOptionsDB().Get<int>("ui.tooltip.delay"));
SetBrowseInfoWnd(PolicyBrowseWnd(m_policy->Name()));
}
void PolicyControl::Resize(GG::Pt sz, const int pts) {
m_background->Resize(sz);
m_icon->Resize(GG::Pt(sz.x, sz.y * 2/3));
std::shared_ptr<GG::Font> font = ClientUI::GetBoldFont(pts);
m_name_label->SetFont(font);
m_cost_label->SetFont(std::move(font));
m_name_label->SizeMove(GG::Pt(GG::ToX(sz.x * POLICY_TEXT_POS_X), GG::ToY(sz.y * POLICY_TEXT_POS_Y)),
GG::Pt(GG::ToX(sz.x * (1 - POLICY_TEXT_POS_X)), GG::ToY(sz.y * POLICY_TEXT_POS_Y)));
m_cost_label->MoveTo( GG::Pt(GG::ToX(sz.x * POLICY_COST_POS_X), GG::ToY(sz.y * (1 - POLICY_COST_POS_Y))));
GG::Control::Resize(sz);
}
void PolicyControl::Render() {}
void PolicyControl::LClick(GG::Pt pt, GG::Flags<GG::ModKey> mod_keys)
{ ClickedSignal(m_policy, mod_keys); }
void PolicyControl::LDoubleClick(GG::Pt pt, GG::Flags<GG::ModKey> mod_keys)
{ DoubleClickedSignal(m_policy); }
void PolicyControl::RClick(GG::Pt pt, GG::Flags<GG::ModKey> mod_keys)
{ RightClickedSignal(m_policy, pt); }
//////////////////////////////////////////////////
// PoliciesListBox //
//////////////////////////////////////////////////
/** Arrangement of PolicyControls that can be dragged onto SlotControls */
class PoliciesListBox : public CUIListBox {
public:
class PoliciesListBoxRow : public CUIListBox::Row {
public:
PoliciesListBoxRow(GG::X w, GG::Y h, const AvailabilityManager& availabilities_state);
void ChildrenDraggedAway(const std::vector<GG::Wnd*>& wnds,
const GG::Wnd* destination) override;
private:
const AvailabilityManager& m_availabilities_state;
};
explicit PoliciesListBox(const AvailabilityManager& availabilities_state);
const auto& GetCategoriesShown() const noexcept { return m_policy_categories_shown; }
const auto& AvailabilityState() const noexcept { return m_availabilities_state; }
void SizeMove(GG::Pt ul, GG::Pt lr) override;
void AcceptDrops(GG::Pt pt, std::vector<std::shared_ptr<GG::Wnd>> wnds,
GG::Flags<GG::ModKey> mod_keys) override;
void Populate();
void ShowCategory(const std::string& category, bool refresh_list = true);
void ShowAllCategories(bool refresh_list = true);
void HideCategory(const std::string& category, bool refresh_list = true);
void HideAllCategories(bool refresh_list = true);
void ResizePolicies(GG::Pt sz, const int pts = ClientUI::Pts());
mutable boost::signals2::signal<void (const Policy*, GG::Flags<GG::ModKey>)> PolicyClickedSignal;
mutable boost::signals2::signal<void (const Policy*)> PolicyDoubleClickedSignal;
mutable boost::signals2::signal<void (const Policy*, GG::Pt pt)> PolicyRightClickedSignal;
mutable boost::signals2::signal<void (const std::string&)> ClearPolicySignal;
protected:
void DropsAcceptable(DropsAcceptableIter first, DropsAcceptableIter last,
GG::Pt pt, GG::Flags<GG::ModKey> mod_keys) const override;
private:
// policies indexed by category that conform to current availability state
std::map<std::string, std::vector<const Policy*>>
GroupAvailableDisplayablePolicies(const Empire* empire) const;
mutable boost::signals2::scoped_connection m_empire_policies_changed_signal_connection;
boost::container::flat_set<std::string, std::less<>> m_policy_categories_shown;
int m_previous_num_columns = -1;
const AvailabilityManager& m_availabilities_state;
};
PoliciesListBox::PoliciesListBoxRow::PoliciesListBoxRow(
GG::X w, GG::Y h, const AvailabilityManager& availabilities_state) :
CUIListBox::Row(w, h),
m_availabilities_state(availabilities_state)
{}
void PoliciesListBox::PoliciesListBoxRow::ChildrenDraggedAway(
const std::vector<GG::Wnd*>& wnds, const GG::Wnd* destination)
{
if (wnds.empty())
return;
// should only be one wnd in list because PolicyControls doesn't allow selection, so dragging is
// only one-at-a-time
auto control = dynamic_cast<GG::Control*>(wnds.front());
if (!control || empty())
return;
// find control in row
unsigned int ii = 0;
for (; ii < size(); ++ii) {
if (at(ii) != control)
continue;
}
if (ii == size())
return;
RemoveCell(ii); // Wnd that accepts drop takes ownership of dragged-away control
const auto* policy_control = dynamic_cast<PolicyControl*>(control);
if (!policy_control)
return;
const auto* policy_type = policy_control->GetPolicy();
if (!policy_type)
return;
auto new_policy_control = GG::Wnd::Create<PolicyControl>(policy_type);
if (auto parent = std::dynamic_pointer_cast<const PoliciesListBox>(Parent())) {
new_policy_control->ClickedSignal.connect(parent->PolicyClickedSignal);
new_policy_control->DoubleClickedSignal.connect(parent->PolicyDoubleClickedSignal);
new_policy_control->RightClickedSignal.connect(parent->PolicyRightClickedSignal);
}
SetCell(ii, new_policy_control);
}
PoliciesListBox::PoliciesListBox(const AvailabilityManager& availabilities_state) :
CUIListBox(),
m_availabilities_state(availabilities_state)
{
ManuallyManageColProps();
NormalizeRowsOnInsert(false);
SetStyle(GG::LIST_NOSEL);
}
void PoliciesListBox::SizeMove(GG::Pt ul, GG::Pt lr) {
const GG::Pt old_size = GG::Wnd::Size();
const auto policy_palette = Parent();
const auto gov_wnd = std::dynamic_pointer_cast<GovernmentWnd>(policy_palette->Parent());
const GG::Pt slot_size = gov_wnd ? gov_wnd->GetPolicySlotSize() : GG::Pt(SLOT_CONTROL_WIDTH, SLOT_CONTROL_HEIGHT);
// maybe later do something interesting with docking
CUIListBox::SizeMove(ul, lr);
if (old_size != GG::Wnd::Size()) {
// determine how many columns can fit in the box now...
const GG::X TOTAL_WIDTH = Size().x - ClientUI::ScrollWidth();
const int NUM_COLUMNS = std::max(1, TOTAL_WIDTH / (slot_size.x + PAD));
if (NUM_COLUMNS != m_previous_num_columns)
Populate();
}
}
void PoliciesListBox::AcceptDrops(GG::Pt, std::vector<std::shared_ptr<GG::Wnd>> wnds,
GG::Flags<GG::ModKey> mod_keys)
{
// If ctrl is pressed then signal all policies of the same type to be cleared.
if (!(mod_keys & GG::MOD_KEY_CTRL))
return;
if (wnds.empty())
return;
auto control = std::dynamic_pointer_cast<const PolicyControl>(wnds.front());
const Policy* policy_type = control ? control->GetPolicy() : nullptr;
if (!policy_type)
return;
ClearPolicySignal(policy_type->Name());
}
std::map<std::string, std::vector<const Policy*>>
PoliciesListBox::GroupAvailableDisplayablePolicies(const Empire*) const {
using PolicyAndCat = const std::pair<const Policy*, const std::string&>;
static constexpr auto to_policy_and_cat = [](const Policy& p) -> PolicyAndCat { return {&p, p.Category()}; };
const auto cat_shown_policy_displayed = [this](PolicyAndCat& p_c) {
return m_policy_categories_shown.contains(p_c.second) &&
m_availabilities_state.PolicyDisplayed(*p_c.first);
};
// loop through all possible policies, outputting those shown
std::map<std::string, std::vector<const Policy*>> policies_categorized;
auto policies_rng = std::as_const(GetPolicyManager()) | range_values;
auto policy_cat_rng = policies_rng | range_transform(to_policy_and_cat)
| range_filter(cat_shown_policy_displayed);
for (const auto& [policy, category] : policy_cat_rng)
policies_categorized[category].push_back(policy);
return policies_categorized;
}
void PoliciesListBox::Populate() {
//std::cout << "PoliciesListBox::Populate" << std::endl;
ScopedTimer scoped_timer("PoliciesListBox::Populate");
GG::Pt slot_size = GG::Pt(SLOT_CONTROL_WIDTH, SLOT_CONTROL_HEIGHT);
auto policy_palette = Parent();
if (auto gov_wnd = std::dynamic_pointer_cast<GovernmentWnd>(policy_palette->Parent()))
slot_size = gov_wnd->GetPolicySlotSize();
const GG::X TOTAL_WIDTH = ClientWidth() - ClientUI::ScrollWidth();
const int MAX_COLUMNS = std::max(1, TOTAL_WIDTH / (slot_size.x + PAD));
const int empire_id = GGHumanClientApp::GetApp()->EmpireID();
const Empire* empire = GetEmpire(empire_id); // may be nullptr
m_empire_policies_changed_signal_connection.disconnect();
if (empire)
m_empire_policies_changed_signal_connection = empire->PoliciesChangedSignal.connect(
boost::bind(&PoliciesListBox::Populate, this), boost::signals2::at_front);
int cur_col = MAX_COLUMNS;
std::shared_ptr<PoliciesListBoxRow> cur_row;
int num_policies = 0;
// remove policies currently in rows of listbox
Clear();
// filter policies by availability and current designation of categories
// for display
const auto policies = GroupAvailableDisplayablePolicies(empire);
for (const auto& policies_vec : policies | range_values) { // TODO: if std::views::join is available, avoid douple loop by flattening
// take the sorted policies and make UI element rows for the PoliciesListBox
for (const auto policy : policies_vec) {
// check if current row is full, and make a new row if necessary
if (cur_col >= MAX_COLUMNS) {
if (cur_row)
Insert(cur_row);
cur_col = 0;
cur_row = GG::Wnd::Create<PoliciesListBoxRow>(
TOTAL_WIDTH, slot_size.y + GG::Y(PAD), m_availabilities_state);
}
++cur_col;
++num_policies;
// make new policy control and add to row
auto control = GG::Wnd::Create<PolicyControl>(policy);
control->ClickedSignal.connect(PoliciesListBox::PolicyClickedSignal);
control->DoubleClickedSignal.connect(PoliciesListBox::PolicyDoubleClickedSignal);
control->RightClickedSignal.connect(PoliciesListBox::PolicyRightClickedSignal);
cur_row->push_back(std::move(control));
}
}
// add any incomplete rows
if (cur_row)
Insert(std::move(cur_row));
// keep track of how many columns are present now
m_previous_num_columns = MAX_COLUMNS;
// If there are no policies add a prompt to suggest a solution.
if (num_policies == 0)
Insert(GG::Wnd::Create<PromptRow>(TOTAL_WIDTH, UserString("ALL_POLICY_AVAILABILITY_FILTERS_BLOCKING_PROMPT")),
begin(), false);
}
void PoliciesListBox::ShowCategory(const std::string& category, bool refresh_list) {
if (!m_policy_categories_shown.contains(category)) {
m_policy_categories_shown.insert(category);
if (refresh_list)
Populate();
}
}
void PoliciesListBox::ShowAllCategories(bool refresh_list) {
const auto cats = GetPolicyManager().PolicyCategories();
std::transform(cats.begin(), cats.end(), std::inserter(m_policy_categories_shown, m_policy_categories_shown.end()),
[](const auto sv) { return std::string{sv}; });
if (refresh_list)
Populate();
}
void PoliciesListBox::HideCategory(const std::string& category, bool refresh_list) {
if (m_policy_categories_shown.erase(category) > 0 && refresh_list)
Populate();
}
void PoliciesListBox::HideAllCategories(bool refresh_list) {
m_policy_categories_shown.clear();
if (refresh_list)
Populate();
}
void PoliciesListBox::ResizePolicies(GG::Pt sz, const int pts) {
auto it = begin();
while (it != end()) {
const auto& row = *it;
unsigned int itt = 0;
while (itt < row->size()) {
auto policy_control = dynamic_cast<PolicyControl*>(row->at(itt));
if (policy_control)
policy_control->Resize(sz, pts);
++itt;
}
++it;
}
}
//////////////////////////////////////////////////
// GovernmentWnd::PolicyPalette //
//////////////////////////////////////////////////
/** Contains graphical list of PolicyControl which can be dragged and dropped
* onto slots to assign policies to those slots */
class GovernmentWnd::PolicyPalette : public GG::Wnd {
public:
PolicyPalette(GG::X w, GG::Y h);
void CompleteConstruction() override;
void SizeMove(GG::Pt ul, GG::Pt lr) override;
void ShowCategory(const std::string& category, bool refresh_list = true);
void ShowAllCategories(bool refresh_list = true);
void HideCategory(const std::string& category, bool refresh_list = true);
void HideAllCategories(bool refresh_list = true);
void ToggleCategory(const std::string& category, bool refresh_list = true);
void ToggleAllCategories(bool refresh_list = true);
void ToggleAvailability(const Availability type);
void Populate();
mutable boost::signals2::signal<void (const Policy*, GG::Flags<GG::ModKey>)> PolicyClickedSignal;
mutable boost::signals2::signal<void (const Policy*)> PolicyDoubleClickedSignal;
mutable boost::signals2::signal<void (const Policy*, GG::Pt pt)> PolicyRightClickedSignal;
mutable boost::signals2::signal<void (const std::string&)> ClearPolicySignal;
private:
void DoLayout();
/** A policy type click with ctrl obsoletes policy. */
void HandlePolicyClicked(const Policy*, GG::Flags<GG::ModKey>);
void HandlePolicyRightClicked(const Policy*, GG::Pt pt);
std::shared_ptr<PoliciesListBox> m_policies_list;
std::map<std::string, std::shared_ptr<CUIStateButton>> m_category_buttons;
AvailabilityManager m_availabilities_state{true, true, false, false, false};
static constexpr std::size_t NUM_AVAILABILITY_BUTTONS = 5;
std::array<std::shared_ptr<CUIStateButton>, NUM_AVAILABILITY_BUTTONS> m_availabilities_buttons{};
};
GovernmentWnd::PolicyPalette::PolicyPalette(GG::X w, GG::Y h) :
GG::Wnd(GG::X0, GG::Y0, w, h, GG::ONTOP | GG::INTERACTIVE)
{}
void GovernmentWnd::PolicyPalette::CompleteConstruction() {
SetChildClippingMode(ChildClippingMode::ClipToClient);
m_policies_list = GG::Wnd::Create<PoliciesListBox>(m_availabilities_state);
AttachChild(m_policies_list);
m_policies_list->PolicyClickedSignal.connect(
boost::bind(&GovernmentWnd::PolicyPalette::HandlePolicyClicked, this, _1, _2));
m_policies_list->PolicyDoubleClickedSignal.connect(
PolicyDoubleClickedSignal);
m_policies_list->PolicyRightClickedSignal.connect(
boost::bind(&GovernmentWnd::PolicyPalette::HandlePolicyRightClicked, this, _1, _2));
m_policies_list->ClearPolicySignal.connect(ClearPolicySignal);
// class buttons
for (auto& cat_view : GetPolicyManager().PolicyCategories()) {
// are there any policies of this class?
if (std::none_of(GetPolicyManager().begin(), GetPolicyManager().end(),
[cat_view](auto& e){ return cat_view == e.second.Category(); }))
{ continue; }
const auto& us_cateory{UserString(cat_view)};
auto ptr_it = m_category_buttons.emplace(std::string{cat_view}, GG::Wnd::Create<CUIStateButton>(
us_cateory, GG::FORMAT_CENTER, std::make_shared<CUILabelButtonRepresenter>())).first;
auto& [string_in_map, ptr_in_map] = *ptr_it;
AttachChild(ptr_in_map);
ptr_in_map->CheckedSignal.connect(
boost::bind(&GovernmentWnd::PolicyPalette::ToggleCategory, this, string_in_map, true));
}
static constexpr std::array<std::string_view, 5> BUTTON_LABELS = {{
UserStringNop("POLICY_LIST_ADOPTED"), UserStringNop("POLICY_LIST_ADOPTABLE"),
UserStringNop("POLICY_LIST_UNAFFORDABLE"), UserStringNop("POLICY_LIST_RESTRICTED"),
UserStringNop("POLICY_LIST_LOCKED")}};
for (std::size_t n = 0; n < 5; ++n) {
auto& button = m_availabilities_buttons[n];
button = GG::Wnd::Create<CUIStateButton>(UserString(BUTTON_LABELS[n]),
GG::FORMAT_CENTER, std::make_shared<CUILabelButtonRepresenter>());
AttachChild(button);
button->CheckedSignal.connect(
boost::bind(&GovernmentWnd::PolicyPalette::ToggleAvailability, this, Availability(n)));
button->SetCheck(m_availabilities_state.GetAvailability(Availability(n)));
}
// default to showing everything
ShowAllCategories(false);
Populate();
GG::Wnd::CompleteConstruction();
}
void GovernmentWnd::PolicyPalette::SizeMove(GG::Pt ul, GG::Pt lr) {
GG::Wnd::SizeMove(ul, lr);
DoLayout();
}
void GovernmentWnd::PolicyPalette::DoLayout() {
const int PTS = ClientUI::Pts();
const GG::X PTS_WIDE{PTS/2}; // guess at how wide per character the font needs
const GG::Y BUTTON_HEIGHT{PTS*3/2};
static constexpr int BUTTON_SEPARATION = 3; // vertical or horizontal sepration between adjacent buttons
static constexpr int BUTTON_EDGE_PAD = 2; // distance from edges of control to buttons
static constexpr GG::X RIGHT_EDGE_PAD{8}; // to account for border of CUIWnd
const GG::X USABLE_WIDTH = std::max(ClientWidth() - RIGHT_EDGE_PAD, GG::X1);// space in which to fit buttons
static constexpr int GUESSTIMATE_NUM_CHARS_IN_BUTTON_LABEL = 14; // rough guesstimate... avoid overly long policy class names
const GG::X MIN_BUTTON_WIDTH = PTS_WIDE*GUESSTIMATE_NUM_CHARS_IN_BUTTON_LABEL;
const std::size_t MAX_BUTTONS_PER_ROW = std::max(USABLE_WIDTH / (MIN_BUTTON_WIDTH + BUTTON_SEPARATION), 1);
const std::size_t NUM_CATEGORY_BUTTONS = std::max(1, static_cast<int>(m_category_buttons.size()));
const std::size_t TOTAL_BUTTONS = NUM_CATEGORY_BUTTONS + NUM_AVAILABILITY_BUTTONS;
// determine how to arrange category and availability buttons into rows and columns
// eg:
// [CAT1] [CAT2] [CAT3] [AVB1] [AVB2] [AVB3] [AVB4] [AVB5]
//
// [CAT1] [CAT2] [AVB1] [AVB2] [AVB3]
// [CAT3] [AVB4] [AVB5]
//
// [CAT1] [AVB1] [AVB2]
// [CAT2] [AVB3] [AVB4]
// [CAT3] [AVB5]
float NUM_ROWS = 1.0f;
auto AVAILABILITY_BUTTONS_PER_ROW = static_cast<std::size_t>(std::ceil(NUM_AVAILABILITY_BUTTONS / NUM_ROWS));
auto CATEGORY_BUTTONS_PER_ROW = static_cast<std::size_t>(std::ceil(NUM_CATEGORY_BUTTONS / NUM_ROWS));
int TOTAL_BUTTONS_PER_ROW = AVAILABILITY_BUTTONS_PER_ROW + CATEGORY_BUTTONS_PER_ROW;
while (TOTAL_BUTTONS_PER_ROW > static_cast<int>(MAX_BUTTONS_PER_ROW) && NUM_ROWS < TOTAL_BUTTONS) {
NUM_ROWS += 1.0f;
AVAILABILITY_BUTTONS_PER_ROW = static_cast<std::size_t>(std::ceil(NUM_AVAILABILITY_BUTTONS / NUM_ROWS));
CATEGORY_BUTTONS_PER_ROW = static_cast<std::size_t>(std::ceil(NUM_CATEGORY_BUTTONS / NUM_ROWS));
TOTAL_BUTTONS_PER_ROW = AVAILABILITY_BUTTONS_PER_ROW + CATEGORY_BUTTONS_PER_ROW;
}
//const std::size_t NUM_CATEGORY_BUTTON_ROWS = static_cast<std::size_t>(std::ceil(
// NUM_CATEGORY_BUTTONS * 1.0f / CATEGORY_BUTTONS_PER_ROW));
//const std::size_t NUM_AVAILABILITY_BUTTON_ROWS = static_cast<std::size_t>(std::ceil(
// NUM_AVAILABILITY_BUTTONS * 1.0f / AVAILABILITY_BUTTONS_PER_ROW));
const GG::X BUTTON_WIDTH = (USABLE_WIDTH - (TOTAL_BUTTONS_PER_ROW - 1)*BUTTON_SEPARATION) / TOTAL_BUTTONS_PER_ROW;
const GG::X COL_OFFSET = BUTTON_WIDTH + BUTTON_SEPARATION; // horizontal distance between each column of buttons
const GG::Y ROW_OFFSET = BUTTON_HEIGHT + BUTTON_SEPARATION; // vertical distance between each row of buttons
// place category buttons
int col = CATEGORY_BUTTONS_PER_ROW;
int row = -1;
for (auto& entry : m_category_buttons) {
if (col >= static_cast<int>(CATEGORY_BUTTONS_PER_ROW)) {
col = 0;
++row;
}
GG::Pt ul(BUTTON_EDGE_PAD + col*COL_OFFSET, BUTTON_EDGE_PAD + row*ROW_OFFSET);
GG::Pt lr = ul + GG::Pt(BUTTON_WIDTH, BUTTON_HEIGHT);
entry.second->SizeMove(ul, lr);
++col;
}
const auto NUM_CATEGORY_BUTTON_ROWS = row;
// reset row / column
col = CATEGORY_BUTTONS_PER_ROW;
row = 0;
// place availability buttons
for (auto& button : m_availabilities_buttons) {
if (col >= TOTAL_BUTTONS_PER_ROW) {
col = CATEGORY_BUTTONS_PER_ROW;
row++;
}
auto ul = GG::Pt{BUTTON_EDGE_PAD + col*COL_OFFSET, BUTTON_EDGE_PAD + row*ROW_OFFSET};
auto lr = ul + GG::Pt{BUTTON_WIDTH, BUTTON_HEIGHT};
button->SizeMove(ul, lr);
col++;
}
const auto TOTAL_ROWS = std::max(NUM_CATEGORY_BUTTON_ROWS, row);
// place policies list
m_policies_list->SizeMove(GG::Pt{GG::X0, BUTTON_EDGE_PAD + ROW_OFFSET*(TOTAL_ROWS + 1)},
GG::Pt{ClientWidth(), ClientHeight() - GG::Y{INNER_BORDER_ANGLE_OFFSET}});
// adjust size of policies
GG::Pt slot_size = GG::Pt(SLOT_CONTROL_WIDTH, SLOT_CONTROL_HEIGHT);
int text_pts = ClientUI::Pts();
auto gov_wnd = std::dynamic_pointer_cast<GovernmentWnd>(Parent());
if (gov_wnd) {
slot_size = gov_wnd->GetPolicySlotSize();
text_pts = gov_wnd->GetPolicyTextSize();
}
m_policies_list->ResizePolicies(slot_size, text_pts);
}
void GovernmentWnd::PolicyPalette::HandlePolicyClicked(const Policy* policy_type,
GG::Flags<GG::ModKey> modkeys)
{ PolicyClickedSignal(policy_type, modkeys); }
void GovernmentWnd::PolicyPalette::HandlePolicyRightClicked(const Policy* policy_type,
GG::Pt pt)
{ PolicyRightClickedSignal(policy_type, pt); }
void GovernmentWnd::PolicyPalette::ShowCategory(const std::string& category,
bool refresh_list)
{
if (!m_category_buttons.contains(category)) {
ErrorLogger() << "PolicyPalette::ShowCategory was passed an invalid category name: " << category;
return;
}
m_policies_list->ShowCategory(category, refresh_list);
m_category_buttons[category]->SetCheck();
DoLayout();
}
void GovernmentWnd::PolicyPalette::ShowAllCategories(bool refresh_list) {
m_policies_list->ShowAllCategories(refresh_list);
for (auto& entry : m_category_buttons)
entry.second->SetCheck();
DoLayout();
}
void GovernmentWnd::PolicyPalette::HideCategory(const std::string& category,
bool refresh_list)
{
if (!m_category_buttons.contains(category)) {
ErrorLogger() << "PolicyPalette::HideCategory was passed an invalid category name: " << category;
return;
}
m_policies_list->HideCategory(category, refresh_list);
m_category_buttons[category]->SetCheck(false);
DoLayout();
}
void GovernmentWnd::PolicyPalette::HideAllCategories(bool refresh_list) {
m_policies_list->HideAllCategories(refresh_list);
for (auto& entry : m_category_buttons)
entry.second->SetCheck(false);
DoLayout();
}
void GovernmentWnd::PolicyPalette::ToggleCategory(const std::string& category, bool refresh_list) {
if (!m_category_buttons.contains(category)) {
ErrorLogger() << "PolicyPalette::ToggleCategory was passed an invalid category name: " << category;
return;
}
const auto& categories_shown = m_policies_list->GetCategoriesShown();
if (categories_shown.contains(category))
HideCategory(category, refresh_list);
else
ShowCategory(category, refresh_list);
}
void GovernmentWnd::PolicyPalette::ToggleAllCategories(bool refresh_list) {
const auto& categories_shown = m_policies_list->GetCategoriesShown();
if (categories_shown.size() == m_category_buttons.size())
HideAllCategories(refresh_list);
else
ShowAllCategories(refresh_list);
}
void GovernmentWnd::PolicyPalette::ToggleAvailability(Availability type) {
auto idx = static_cast<std::underlying_type_t<Availability>>(type);
if (idx >= m_availabilities_buttons.size())
return;
m_availabilities_state.ToggleAvailability(type);
bool state = m_availabilities_state.GetAvailability(type);
auto& button = m_availabilities_buttons[idx];
button->SetCheck(state);
Populate();
}
void GovernmentWnd::PolicyPalette::Populate() {
m_policies_list->Populate();
DoLayout();
}
//////////////////////////////////////////////////
// PolicySlotControl //
//////////////////////////////////////////////////
/** UI representation and drop-target for policies of a government.
* PolicyControl may be dropped into slots to add the corresponding policies to
* the government, or the policy may be set programmatically with SetPolicy(). */
class PolicySlotControl : public GG::Control {
public:
PolicySlotControl();
PolicySlotControl(std::string slot_category, int category_index, std::size_t slot_index);
void CompleteConstruction() override;
[[nodiscard]] const auto& SlotCategory() const noexcept { return m_slot_category; }
[[nodiscard]] const Policy* GetPolicy() const;
[[nodiscard]] auto CategoryIndex() const noexcept { return m_category_index; }
[[nodiscard]] auto SlotIndex() const noexcept { return m_slot_index; }
void StartingChildDragDrop(const GG::Wnd* wnd, GG::Pt offset) override;
void CancellingChildDragDrop(const std::vector<const GG::Wnd*>& wnds) override;
void AcceptDrops(GG::Pt pt, std::vector<std::shared_ptr<GG::Wnd>> wnds,
GG::Flags<GG::ModKey> mod_keys) override;
void ChildrenDraggedAway(const std::vector<GG::Wnd*>& wnds,
const GG::Wnd* destination) override;
void DragDropEnter(GG::Pt pt, std::map<const Wnd*, bool>& drop_wnds_acceptable,
GG::Flags<GG::ModKey> mod_keys) override;
void DragDropLeave() override;
void Resize(GG::Pt sz, const int pts = ClientUI::Pts());
void Render() override;
void Highlight(bool actually = true);
void SetPolicy(const std::string& policy_name); //!< used to programmatically set the PolicyControl in this slot.
void SetPolicy(const Policy* policy); //!< used to programmatically set the PolicyControl in this slot.
/** emitted when the contents of a slot are altered by the dragging
* a PolicyControl in or out of the slot. signal should be caught and the
* slot contents set using SetPolicy accordingly */
mutable boost::signals2::signal<void (const Policy*, bool)> SlotContentsAlteredSignal;
mutable boost::signals2::signal<void (const Policy*, GG::Flags<GG::ModKey>)> PolicyClickedSignal;
protected:
bool EventFilter(GG::Wnd* w, const GG::WndEvent& event) override;
void DropsAcceptable(DropsAcceptableIter first, DropsAcceptableIter last,
GG::Pt pt, GG::Flags<GG::ModKey> mod_keys) const override;
private:
std::string m_slot_category;
std::shared_ptr<PolicyControl> m_policy_control;
std::shared_ptr<GG::StaticGraphic> m_background;
int m_category_index = -1;
std::size_t m_slot_index = 0;
bool m_highlighted = false;
};
PolicySlotControl::PolicySlotControl() :
GG::Control(GG::X0, GG::Y0, SLOT_CONTROL_WIDTH, SLOT_CONTROL_HEIGHT, GG::INTERACTIVE)
{}
PolicySlotControl::PolicySlotControl(std::string slot_category, int category_index,
std::size_t slot_index) :
GG::Control(GG::X0, GG::Y0, SLOT_CONTROL_WIDTH, SLOT_CONTROL_HEIGHT, GG::INTERACTIVE),
m_slot_category(std::move(slot_category)),
m_category_index(category_index),
m_slot_index(slot_index)
{}
void PolicySlotControl::CompleteConstruction() {
GG::Control::CompleteConstruction();
m_background = GG::Wnd::Create<GG::StaticGraphic>(SlotBackgroundTexture(m_slot_category), GG::GRAPHIC_FITGRAPHIC | GG::GRAPHIC_PROPSCALE);
m_background->Resize(GG::Pt(SLOT_CONTROL_WIDTH, SLOT_CONTROL_HEIGHT));
m_background->Show();
AttachChild(m_background);
SetBrowseModeTime(GetOptionsDB().Get<int>("ui.tooltip.delay"));
SetBrowseInfoWnd(GG::Wnd::Create<IconTextBrowseWnd>(
SlotBackgroundTexture(m_slot_category),
UserString(m_slot_category),
UserString("SL_TOOLTIP_DESC")
));
}
bool PolicySlotControl::EventFilter(GG::Wnd* w, const GG::WndEvent& event) {
if (w == this)
return false;
switch (event.Type()) {
case GG::WndEvent::EventType::DragDropEnter:
case GG::WndEvent::EventType::DragDropHere:
case GG::WndEvent::EventType::CheckDrops:
case GG::WndEvent::EventType::DragDropLeave:
case GG::WndEvent::EventType::DragDroppedOn:
HandleEvent(event);
return true;
break;
default:
return false;
}
}
void PolicySlotControl::DropsAcceptable(DropsAcceptableIter first, DropsAcceptableIter last,
GG::Pt pt, GG::Flags<GG::ModKey> mod_keys) const
{
for (DropsAcceptableIter it = first; it != last; ++it)
it->second = false;
// if more than one control dropped somehow, reject all
if (std::distance(first, last) != 1)
return;
const ScriptingContext context;