Repository navigation
Expand file tree
/
Copy pathmainwindow.cpp
More file actions
1239 lines (1049 loc) · 50.2 KB
/
Copy pathmainwindow.cpp
File metadata and controls
1239 lines (1049 loc) · 50.2 KB
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 "mainwindow.h"
#include "ui_mainwindow.h"
#include "settings_dialog.h"
#include "pawnrow.h"
#include "QUuid"
#include "QJsonArray"
#include "QJsonObject"
#include "QFile"
#include "QListWidget"
#include "QListWidgetItem"
#include "QGraphicsOpacityEffect"
#include "QMessageBox"
#include "pawn_editor.h"
#include "QWidgetAction"
#include <QDialog>
#include <QDialogButtonBox>
#include <QVBoxLayout>
#include <QHBoxLayout>
#include <QLabel>
#include <QSpinBox>
#include <QLineEdit>
#include <QTableView>
#include <QHeaderView>
#include <QPushButton>
#include <QInputDialog>
#include <QGuiApplication>
#include <QStyleHints>
#include <algorithm>
// Helper: compute the correct stylesheet for System mode based on current OS palette
static QString systemModeStylesheet()
{
const bool isDark = (QGuiApplication::styleHints()->colorScheme() != Qt::ColorScheme::Light);
return (isDark ? AppTheme::darkPreset() : AppTheme::lightPreset()).toStylesheet();
}
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
LoadFromJSon();
// Apply initial stylesheet — use OS-matched preset when in System mode
if (PathTrackerStruct::instance().theme().themeMode == ThemeMode::System)
qApp->setStyleSheet(systemModeStylesheet());
else
qApp->setStyleSheet(PathTrackerStruct::instance().stylesheet());
// Drive font size through QApplication::setFont() so Windows picks it up.
// QSS font-size on QWidget doesn't reliably cascade on Windows at startup.
{
QFont f = qApp->font();
f.setPointSize(PathTrackerStruct::instance().theme().fontSize);
qApp->setFont(f);
}
// Track OS colour scheme changes so System mode stays in sync
connect(QGuiApplication::styleHints(), &QStyleHints::colorSchemeChanged,
this, &MainWindow::OnSystemColorSchemeChanged);
// Ensure there is always an active encounter so pawns can be added immediately.
// Use startEmptyEncounter() — does NOT add a template to m_encounterTemplates,
// so the runtime encounter never leaks into the Editor's Encounter list.
if (!PathTrackerStruct::instance().activeEncounter())
PathTrackerStruct::instance().startEmptyEncounter();
ui->PawnList->setContextMenuPolicy(Qt::CustomContextMenu);
connect(ui->PawnList, &QListWidget::customContextMenuRequested, this, &MainWindow::ShowPawnContextMenu);
ui->EffectList->setColumnCount(2);
ui->EffectList->setHeaderLabels({"Property", "Value"});
ui->EffectList->setRootIsDecorated(true);
ui->EffectList->setAlternatingRowColors(true);
ui->EffectList->setUniformRowHeights(true);
ui->EffectList->setSortingEnabled(false);
ui->AttributeList->setColumnCount(2);
ui->AttributeList->setHeaderLabels({"Property", "Value"});
ui->AttributeList->setRootIsDecorated(true);
ui->AttributeList->setAlternatingRowColors(true);
ui->AttributeList->setUniformRowHeights(true);
ui->AttributeList->setSortingEnabled(false);
ui->NextTurnButton->setEnabled(false);
ui->UndoButton->setEnabled(false);
ui->RedoButton->setEnabled(false);
if (enc() && enc()->isOngoing) {
for (PawnInstance* p : enc()->allCombatants()) {
if (p->state == PawnState::Active) { CurrentPawnID = p->instanceId; break; }
}
if (CurrentPawnID.isEmpty() && !enc()->initiativeOrder.isEmpty() && enc()->initiativeOrder[0].pawn)
CurrentPawnID = enc()->initiativeOrder[0].pawn->instanceId;
}
RefreshPawnList();
if (enc() && enc()->isOngoing) {
EncounterOngoing = true;
ui->NextTurnButton->setEnabled(true);
}
UpdateStartStopButtonAppearance();
if (!CurrentPawnID.isEmpty())
FullRefresh();
}
MainWindow::~MainWindow()
{
delete ui;
}
// ─────────────────────────────────────────────────────────────────────────────
// System colour scheme tracking
// ─────────────────────────────────────────────────────────────────────────────
void MainWindow::OnSystemColorSchemeChanged()
{
if (PathTrackerStruct::instance().theme().themeMode != ThemeMode::System)
return;
qApp->setStyleSheet(systemModeStylesheet());
RefreshPawnList();
}
// ─────────────────────────────────────────────────────────────────────────────
// Encounter accessor
// ─────────────────────────────────────────────────────────────────────────────
EncounterInstance* MainWindow::enc()
{
return PathTrackerStruct::instance().activeEncounter();
}
// ─────────────────────────────────────────────────────────────────────────────
// Open editor dialog
// ─────────────────────────────────────────────────────────────────────────────
void MainWindow::on_pushButton_4_clicked()
{
Editor editor(&PathTrackerStruct::instance(), this);
editor.exec();
RefreshPawnList();
}
void MainWindow::on_SettingsButton_clicked()
{
SettingsDialog dialog(this);
connect(&dialog, &SettingsDialog::ThemeApplied, this, &MainWindow::RefreshPawnList);
dialog.exec();
RefreshPawnList();
}
// ─────────────────────────────────────────────────────────────────────────────
// Save / Load
// ─────────────────────────────────────────────────────────────────────────────
void MainWindow::SaveToJson()
{
PathTrackerStruct::instance().save();
}
void MainWindow::LoadFromJSon()
{
PathTrackerStruct::instance().load();
}
// ─────────────────────────────────────────────────────────────────────────────
// Undo / Redo
// ─────────────────────────────────────────────────────────────────────────────
void MainWindow::SaveSnapshot()
{
if (!enc()) return;
m_pastStates.append(enc()->saveToJson());
m_futureStates.clear();
ui->UndoButton->setEnabled(true);
ui->RedoButton->setEnabled(false);
}
void MainWindow::RestoreFromSnapshot(const QJsonObject& snap)
{
if (!enc()) return;
enc()->loadFromJson(snap);
ui->RoundNumbeLabel->setText(QString::number(enc()->currentRound));
if (!enc()->initiativeOrder.isEmpty() && enc()->initiativeOrder[0].pawn)
CurrentPawnID = enc()->initiativeOrder[0].pawn->instanceId;
RefreshPawnList();
FullRefresh();
SaveToJson();
}
void MainWindow::on_UndoButton_clicked()
{
if (m_pastStates.isEmpty()) return;
m_futureStates.prepend(enc()->saveToJson());
RestoreFromSnapshot(m_pastStates.takeLast());
ui->UndoButton->setEnabled(!m_pastStates.isEmpty());
ui->RedoButton->setEnabled(true);
}
void MainWindow::on_DiceHistoryButton_clicked()
{
auto* dlg = new QDialog(this);
dlg->setWindowTitle("Dice Roll History");
dlg->setAttribute(Qt::WA_DeleteOnClose);
dlg->resize(450, 380);
auto* layout = new QVBoxLayout(dlg);
// ── Arbitrary roll section ──────────────────────────────────────
auto* rollRow = new QHBoxLayout;
auto* formulaEdit = new QLineEdit(dlg);
formulaEdit->setPlaceholderText("e.g. 2D6+3");
auto* rollBtn = new QPushButton("Roll", dlg);
auto* resultLabel = new QLabel("—", dlg);
QFont rf = resultLabel->font();
rf.setBold(true);
rf.setPointSize(14);
resultLabel->setFont(rf);
resultLabel->setMinimumWidth(50);
resultLabel->setAlignment(Qt::AlignCenter);
rollRow->addWidget(new QLabel("Formula:", dlg));
rollRow->addWidget(formulaEdit, 1);
rollRow->addWidget(rollBtn);
rollRow->addWidget(resultLabel);
layout->addLayout(rollRow);
connect(rollBtn, &QPushButton::clicked, dlg, [formulaEdit, resultLabel](){
const QString formula = formulaEdit->text().trimmed();
if (formula.isEmpty()) return;
const int result = DiceParser::roll(formula);
resultLabel->setText(QString::number(result));
PathTrackerStruct::instance().save();
});
// Allow pressing Enter in the formula field to roll
connect(formulaEdit, &QLineEdit::returnPressed, rollBtn, &QPushButton::click);
// ── History table ───────────────────────────────────────────────
auto* view = new QTableView(dlg);
view->setModel(&DiceHistoryModel::instance());
view->horizontalHeader()->setStretchLastSection(true);
view->setSelectionBehavior(QAbstractItemView::SelectRows);
view->setEditTriggers(QAbstractItemView::NoEditTriggers);
// Auto-scroll to the latest roll
connect(&DiceHistoryModel::instance(), &QAbstractTableModel::rowsInserted,
view, [view](){ view->scrollToBottom(); });
layout->addWidget(view);
auto* btnRow = new QHBoxLayout;
auto* clearBtn = new QPushButton("Clear", dlg);
auto* closeBtn = new QPushButton("Close", dlg);
btnRow->addWidget(clearBtn);
btnRow->addStretch();
btnRow->addWidget(closeBtn);
layout->addLayout(btnRow);
connect(clearBtn, &QPushButton::clicked, dlg, [resultLabel](){
DiceHistoryModel::instance().clear();
resultLabel->setText("—");
PathTrackerStruct::instance().save();
});
connect(closeBtn, &QPushButton::clicked, dlg, &QDialog::accept);
dlg->show();
}
void MainWindow::on_RedoButton_clicked()
{
if (m_futureStates.isEmpty()) return;
m_pastStates.append(enc()->saveToJson());
RestoreFromSnapshot(m_futureStates.takeFirst());
ui->UndoButton->setEnabled(true);
ui->RedoButton->setEnabled(!m_futureStates.isEmpty());
}
// ─────────────────────────────────────────────────────────────────────────────
// Pawn CRUD
// ─────────────────────────────────────────────────────────────────────────────
void MainWindow::on_PawnAdd_clicked()
{
if (!enc()) return;
int initiative = ui->PawnNr->value();
QString name = ui->PawnLine->text();
if (initiative == 0 || name.isEmpty()) return;
SaveSnapshot();
// Create a PawnTemplate, register it, then instantiate into the encounter.
auto tmpl = std::make_unique<PawnTemplate>();
tmpl->id = QUuid::createUuid().toString(QUuid::WithoutBraces);
tmpl->name = name;
QString templateId = tmpl->id;
PathTrackerStruct::instance().addPawnTemplate(std::move(tmpl));
PawnTemplate* pawnTemplate = PathTrackerStruct::instance().findPawnTemplate(templateId);
enc()->addPawnInstance(*pawnTemplate);
// The new pawn is the last entry added to ownedPawns.
PawnInstance* newPawn = enc()->ownedPawns.back().get();
enc()->setInitiative(newPawn->instanceId, initiative);
enc()->sortInitiative();
RefreshPawnList();
SaveToJson();
}
void MainWindow::RefreshPawnList()
{
ui->PawnList->clear();
if (!enc()) return;
for (const InitiativeEntry& entry : enc()->initiativeOrder) {
if (entry.pawn)
AddPawnListVisual(entry.pawn, entry.initiative);
}
// Graveyard: dead pawns removed from initiativeOrder
QList<PawnInstance*> deadPawns;
for (PawnInstance* pawn : enc()->allCombatants())
if (pawn->state == PawnState::Dead) deadPawns.append(pawn);
if (!deadPawns.isEmpty()) {
auto* graveyardSeparator = new QListWidgetItem(QString::fromUtf8("\u26B0 Graveyard"), ui->PawnList);
graveyardSeparator->setFlags(Qt::NoItemFlags);
graveyardSeparator->setBackground(QColor(50, 15, 15));
graveyardSeparator->setForeground(Qt::lightGray);
for (PawnInstance* deadPawn : deadPawns)
AddPawnListVisual(deadPawn, deadPawn->savedInitiative);
}
PopulatePawnAdderCombos();
}
void MainWindow::AddPawnListVisual(PawnInstance* Pawn, int initiative)
{
QListWidgetItem* item = new QListWidgetItem(ui->PawnList);
item->setData(Qt::UserRole, Pawn->instanceId);
QWidget* row = Pawn->createListWidget(initiative);
item->setSizeHint(row->sizeHint());
ui->PawnList->setItemWidget(item, row);
if (PawnRow* pawnRow = qobject_cast<PawnRow*>(row))
pawnRow->SetSelected(Pawn->instanceId == CurrentPawnID);
}
void MainWindow::UpdatePawnSelectionIndicators()
{
for (int i = 0; i < ui->PawnList->count(); ++i) {
QListWidgetItem* item = ui->PawnList->item(i);
if (!item) continue;
QString itemId = item->data(Qt::UserRole).toString();
if (PawnRow* row = qobject_cast<PawnRow*>(ui->PawnList->itemWidget(item)))
row->SetSelected(itemId == CurrentPawnID);
}
}
void MainWindow::DeletePawn(QString PawnID)
{
if (!enc()) return;
SaveSnapshot();
// Clear initiative entries for this pawn first (they hold non-owning pointers).
for (int i = static_cast<int>(enc()->initiativeOrder.size()) - 1; i >= 0; --i) {
if (enc()->initiativeOrder[i].pawn &&
enc()->initiativeOrder[i].pawn->instanceId == PawnID)
enc()->initiativeOrder.removeAt(i);
}
// Remove from owned pawns (destructs the PawnInstance).
for (int i = static_cast<int>(enc()->ownedPawns.size()) - 1; i >= 0; --i) {
if (enc()->ownedPawns[i]->instanceId == PawnID) {
enc()->ownedPawns.erase(enc()->ownedPawns.begin() + i);
break;
}
}
// Remove from active players if this is a player pawn (non-owning pointer, just unregisters).
enc()->removePlayer(PawnID);
if (CurrentPawnID == PawnID) {
CurrentPawnID.clear();
ui->EffectList->clear();
ui->AttributeList->clear();
ui->ActionList->clear();
}
RefreshPawnList();
SaveToJson();
}
// ─────────────────────────────────────────────────────────────────────────────
// Pawn list selection
// ─────────────────────────────────────────────────────────────────────────────
void MainWindow::on_PawnList_itemClicked(QListWidgetItem *item)
{
CurrentPawnID = item->data(Qt::UserRole).toString();
UpdatePawnSelectionIndicators();
}
void MainWindow::on_PawnList_currentItemChanged(QListWidgetItem *current, QListWidgetItem *previous)
{
Q_UNUSED(previous)
if (!current) return;
FirstItem = (ui->PawnList->row(current) == 0);
CurrentPawnID = current->data(Qt::UserRole).toString();
UpdatePawnSelectionIndicators();
FullRefresh();
}
// ─────────────────────────────────────────────────────────────────────────────
// Pawn context menu
// ─────────────────────────────────────────────────────────────────────────────
void MainWindow::ShowPawnContextMenu(const QPoint &pos)
{
QListWidgetItem* item = ui->PawnList->itemAt(pos);
if (!item) return;
QString PawnID = item->data(Qt::UserRole).toString();
PawnInstance* Pawn = nullptr;
for (PawnInstance* p : enc()->allCombatants()) {
if (p->instanceId == PawnID) { Pawn = p; break; }
}
if (!Pawn) return;
QMenu Menu(this);
// --- Edit Effect submenu ---
QMenu* EditEffectMenu = Menu.addMenu(QIcon::fromTheme("document-properties"), "Edit Effect");
for (const auto& effect : Pawn->effects) {
EffectTemplate* tmpl = PathTrackerStruct::instance().findEffectTemplate(effect->templateId);
QString effectName = tmpl ? tmpl->name : effect->templateId;
QMenu* effectMenu = EditEffectMenu->addMenu(effectName);
QAction* IncreaseLevel = effectMenu->addAction(QIcon::fromTheme("go-up"), "Increase Level");
connect(IncreaseLevel, &QAction::triggered,
this, [this, Pawn, effectPtr = effect.get()]() {
SaveSnapshot();
effectPtr->level++;
Pawn->resolveAttributes();
FullRefresh();
SaveToJson();
});
QAction* DecreaseLevel = effectMenu->addAction(QIcon::fromTheme("go-down"), "Decrease Level");
connect(DecreaseLevel, &QAction::triggered,
this, [this, Pawn, effectPtr = effect.get()]() {
SaveSnapshot();
effectPtr->level--;
Pawn->resolveAttributes();
FullRefresh();
SaveToJson();
});
QAction* IncreaseStage = effectMenu->addAction(QIcon::fromTheme("go-next"), "Increase Stage");
connect(IncreaseStage, &QAction::triggered,
this, [this, effectPtr = effect.get()]() {
SaveSnapshot();
effectPtr->advanceStage(); // syncBoundChildEffects called internally
FullRefresh();
SaveToJson();
});
QAction* DecreaseStage = effectMenu->addAction(QIcon::fromTheme("go-previous"), "Decrease Stage");
connect(DecreaseStage, &QAction::triggered,
this, [this, effectPtr = effect.get()]() {
SaveSnapshot();
effectPtr->regressStage(); // syncBoundChildEffects called internally
FullRefresh();
SaveToJson();
});
}
// --- Remove Effect submenu ---
QMenu* RemoveEffectMenu = Menu.addMenu(QIcon::fromTheme("list-remove"), "Remove Effect");
for (const auto& effect : Pawn->effects) {
EffectTemplate* tmpl = PathTrackerStruct::instance().findEffectTemplate(effect->templateId);
QString effectName = tmpl ? tmpl->name : effect->templateId;
QAction* RemoveEffect = RemoveEffectMenu->addAction(effectName);
connect(RemoveEffect, &QAction::triggered,
this, [this, Pawn, instId = effect->instanceId]() {
SaveSnapshot();
Pawn->removeEffect(instId);
FullRefresh();
SaveToJson();
});
}
// --- Add Effect submenu ---
QMenu* AddEffectMenu = Menu.addMenu(QIcon::fromTheme("list-add"), "Add Effect...");
for (EffectTemplate* tmpl : PathTrackerStruct::instance().allEffectTemplates()) {
QAction* act = AddEffectMenu->addAction(tmpl->name);
connect(act, &QAction::triggered,
this, [this, Pawn, tmpl]() {
SaveSnapshot();
Pawn->applyEffect(*tmpl);
FullRefresh();
SaveToJson();
});
}
// State-change actions (only during an encounter)
if (EncounterOngoing) {
Menu.addSeparator();
// Find current initiative for pre-filling the dialog
int currentInitiative = 0;
for (const InitiativeEntry& entry : enc()->initiativeOrder)
if (entry.pawn && entry.pawn->instanceId == PawnID) { currentInitiative = entry.initiative; break; }
QAction* changeInitAction = Menu.addAction(QIcon::fromTheme("go-jump"), "Change Initiative...");
connect(changeInitAction, &QAction::triggered, this, [this, Pawn, currentInitiative]() {
bool ok = false;
int newInit = QInputDialog::getInt(this, "Change Initiative",
"New initiative for " + Pawn->displayName + ":",
currentInitiative, 1, 2147483647, 1, &ok);
if (!ok) return;
SaveSnapshot();
enc()->setInitiative(Pawn->instanceId, newInit);
Pawn->savedInitiative = newInit;
enc()->sortInitiative();
RefreshPawnList();
SaveToJson();
});
Menu.addSeparator();
if (Pawn->state == PawnState::Unconscious) {
QAction* markConsciousAction = Menu.addAction(
QIcon::fromTheme("dialog-ok"), "Mark Conscious");
connect(markConsciousAction, &QAction::triggered, this, [this, Pawn]() {
SaveSnapshot();
enc()->markUnconscious(Pawn->instanceId);
RefreshPawnList(); FullRefresh(); SaveToJson();
});
} else if (Pawn->state != PawnState::Dead) {
QAction* markUnconsciousAction = Menu.addAction(
QIcon::fromTheme("dialog-warning"), "Mark Unconscious");
connect(markUnconsciousAction, &QAction::triggered, this, [this, Pawn]() {
SaveSnapshot();
enc()->markUnconscious(Pawn->instanceId);
RefreshPawnList(); FullRefresh(); SaveToJson();
});
}
if (Pawn->state == PawnState::Dead) {
QAction* reviveAction = Menu.addAction(
QIcon::fromTheme("view-refresh"), "Revive");
connect(reviveAction, &QAction::triggered, this, [this, Pawn]() {
SaveSnapshot();
enc()->revive(Pawn->instanceId);
RefreshPawnList(); FullRefresh(); SaveToJson();
});
} else {
QAction* killAction = Menu.addAction(
QIcon::fromTheme("process-stop"), "Kill Pawn");
connect(killAction, &QAction::triggered, this, [this, Pawn]() {
SaveSnapshot();
enc()->markDead(Pawn->instanceId);
RefreshPawnList(); FullRefresh(); SaveToJson();
});
}
}
// HP manipulation actions
Menu.addSeparator();
{
int currentHp = Pawn->getAttribute(HP_KEY);
int maxHp = 0;
for (const AttributeValue& av : Pawn->attributes)
if (av.key == HP_KEY) { maxHp = av.baseValue; break; }
QAction* healAction = Menu.addAction(QIcon::fromTheme("go-up"), "Heal...");
connect(healAction, &QAction::triggered, this, [this, Pawn, currentHp, maxHp]() {
bool ok = false;
int amount = QInputDialog::getInt(this, "Heal", "Heal amount:", 0, 0, 9999, 1, &ok);
if (!ok || amount <= 0) return;
SaveSnapshot();
int newHp = (maxHp > 0) ? qMin(currentHp + amount, maxHp) : currentHp + amount;
Pawn->setAttribute(HP_KEY, newHp);
Pawn->resolveAttributes();
RefreshPawnList(); FullRefresh(); SaveToJson();
});
QAction* damageAction = Menu.addAction(QIcon::fromTheme("go-down"), "Damage...");
connect(damageAction, &QAction::triggered, this, [this, Pawn, currentHp]() {
bool ok = false;
int amount = QInputDialog::getInt(this, "Damage", "Damage amount:", 0, 0, 9999, 1, &ok);
if (!ok || amount <= 0) return;
SaveSnapshot();
Pawn->setAttribute(HP_KEY, currentHp - amount);
Pawn->resolveAttributes();
RefreshPawnList(); FullRefresh(); SaveToJson();
});
QAction* setHpAction = Menu.addAction(QIcon::fromTheme("document-edit"), "Set HP...");
connect(setHpAction, &QAction::triggered, this, [this, Pawn, currentHp]() {
bool ok = false;
int newHp = QInputDialog::getInt(this, "Set HP", "New HP value:", currentHp, -9999, 9999, 1, &ok);
if (!ok) return;
SaveSnapshot();
Pawn->setAttribute(HP_KEY, newHp);
Pawn->resolveAttributes();
RefreshPawnList(); FullRefresh(); SaveToJson();
});
}
Menu.addSeparator();
// --- Change Name ---
QAction* changeNameAction = Menu.addAction(QIcon::fromTheme("document-edit"), "Change Name...");
connect(changeNameAction, &QAction::triggered, this, [this, Pawn]() {
bool ok = false;
QString newName = QInputDialog::getText(this, "Change Name",
"New display name:",
QLineEdit::Normal,
Pawn->displayName, &ok);
if (!ok || newName.trimmed().isEmpty()) return;
SaveSnapshot();
Pawn->displayName = newName.trimmed();
RefreshPawnList();
FullRefresh();
SaveToJson();
});
// --- Note actions ---
if (Pawn->note.isEmpty()) {
QAction* addNoteAction = Menu.addAction(QIcon::fromTheme("document-new"), "Add Note...");
connect(addNoteAction, &QAction::triggered, this, [this, Pawn]() {
bool ok = false;
QString text = QInputDialog::getMultiLineText(this, "Add Note",
"Note for " + Pawn->displayName + ":",
QString(), &ok);
if (!ok || text.trimmed().isEmpty()) return;
SaveSnapshot();
Pawn->note = text.trimmed();
FullRefresh();
SaveToJson();
});
} else {
QAction* editNoteAction = Menu.addAction(QIcon::fromTheme("document-edit"), "Edit Note...");
connect(editNoteAction, &QAction::triggered, this, [this, Pawn]() {
bool ok = false;
QString text = QInputDialog::getMultiLineText(this, "Edit Note",
"Note for " + Pawn->displayName + ":",
Pawn->note, &ok);
if (!ok) return;
SaveSnapshot();
Pawn->note = text.trimmed();
FullRefresh();
SaveToJson();
});
QAction* deleteNoteAction = Menu.addAction(QIcon::fromTheme("edit-delete"), "Delete Note");
connect(deleteNoteAction, &QAction::triggered, this, [this, Pawn]() {
SaveSnapshot();
Pawn->note.clear();
FullRefresh();
SaveToJson();
});
}
Menu.addSeparator();
QAction* DeleteAction = Menu.addAction(QIcon::fromTheme("edit-delete"), "Delete Pawn");
connect(DeleteAction, &QAction::triggered,
this, [this, PawnID]() {
DeletePawn(PawnID);
});
Menu.exec(ui->PawnList->mapToGlobal(pos));
}
// ─────────────────────────────────────────────────────────────────────────────
// Runtime display
// ─────────────────────────────────────────────────────────────────────────────
void MainWindow::FullRefresh()
{
ui->EffectList->clear();
ui->ActionList->clear();
ui->AttributeList->clear();
if (!enc()) return;
PawnInstance* Pawn = nullptr;
for (PawnInstance* p : enc()->allCombatants()) {
if (p->instanceId == CurrentPawnID) { Pawn = p; break; }
}
if (!Pawn) return;
// --- Active Effects ---
for (const auto& effect : Pawn->effects) {
EffectTemplate* tmpl = PathTrackerStruct::instance().findEffectTemplate(effect->templateId);
QString effectName = tmpl ? tmpl->name : effect->templateId;
auto* effectItem = new QTreeWidgetItem(ui->EffectList);
effectItem->setText(0, effectName);
QFont font = effectItem->font(0);
font.setBold(true);
font.setPointSize(font.pointSize() + 1);
effectItem->setFont(0, font);
effectItem->setExpanded(true);
effectItem->setFlags(effectItem->flags() & ~Qt::ItemIsSelectable);
ui->EffectList->addTopLevelItem(effectItem);
for (const auto& [prop, val] : effect->getDisplayProperties(tmpl))
AddPropertyWithValue(effectItem, prop, val);
}
// --- Attributes ---
for (const AttributeValue& attrVal : Pawn->attributes) {
QString displayName = attrVal.key;
if (PathTrackerStruct::attributes().hasAttribute(attrVal.key))
displayName = PathTrackerStruct::attributes().getAttribute(attrVal.key).displayName;
auto* attrItem = new QTreeWidgetItem(ui->AttributeList);
attrItem->setText(0, displayName);
attrItem->setText(1, QString::number(attrVal.currentValue));
QFont font = attrItem->font(0);
font.setBold(true);
font.setPointSize(font.pointSize() + 1);
attrItem->setFont(0, font);
attrItem->setFont(1, font);
attrItem->setExpanded(true);
attrItem->setFlags(attrItem->flags() & ~Qt::ItemIsSelectable);
ui->AttributeList->addTopLevelItem(attrItem);
if (attrVal.baseValue != 0)
AddPropertyWithValue(attrItem, "Base", QString::number(attrVal.baseValue));
for (const auto& effect : Pawn->effects) {
EffectTemplate* fxTmpl = PathTrackerStruct::instance().findEffectTemplate(effect->templateId);
QString fxName = fxTmpl ? fxTmpl->name : effect->templateId;
const Stage* stage = effect->currentStage();
if (!stage) continue;
for (const AttributeModifier& mod : stage->modifiers) {
if (mod.attributeKey != attrVal.key) continue;
QString sign;
switch (mod.op) {
case ModifierOp::Plus: sign = QString("+%1").arg(mod.value); break;
case ModifierOp::Minus: sign = QString("-%1").arg(mod.value); break;
case ModifierOp::Multiply: sign = QString("×%1").arg(mod.value); break;
}
QString label = mod.description.isEmpty()
? fxName
: QString("%1 (%2)").arg(fxName, mod.description);
AddPropertyWithValue(attrItem, label, sign);
}
}
}
// --- Effect-only attributes (modifier targets the pawn doesn't own) ---
QSet<QString> displayedKeys;
for (const AttributeValue& attrVal : Pawn->attributes)
displayedKeys.insert(attrVal.key);
QMap<QString, QList<QPair<QString, AttributeModifier>>> effectOnlyMods;
for (const auto& effect : Pawn->effects) {
EffectTemplate* fxTmpl = PathTrackerStruct::instance().findEffectTemplate(effect->templateId);
QString fxName = fxTmpl ? fxTmpl->name : effect->templateId;
const Stage* stage = effect->currentStage();
if (!stage) continue;
for (const AttributeModifier& mod : stage->modifiers) {
if (displayedKeys.contains(mod.attributeKey)) continue;
effectOnlyMods[mod.attributeKey].append({fxName, mod});
}
}
for (auto it = effectOnlyMods.begin(); it != effectOnlyMods.end(); ++it) {
const QString& key = it.key();
const auto& mods = it.value();
QString displayName = key;
if (PathTrackerStruct::attributes().hasAttribute(key))
displayName = PathTrackerStruct::attributes().getAttribute(key).displayName;
double total = 0.0;
for (const auto& [fxName, mod] : mods) {
switch (mod.op) {
case ModifierOp::Plus: total += mod.value; break;
case ModifierOp::Minus: total -= mod.value; break;
case ModifierOp::Multiply: total *= mod.value; break;
}
}
auto* attrItem = new QTreeWidgetItem(ui->AttributeList);
attrItem->setText(0, displayName);
attrItem->setText(1, QString::number(total));
QFont font = attrItem->font(0);
font.setBold(true);
font.setPointSize(font.pointSize() + 1);
attrItem->setFont(0, font);
attrItem->setFont(1, font);
attrItem->setExpanded(true);
attrItem->setFlags(attrItem->flags() & ~Qt::ItemIsSelectable);
ui->AttributeList->addTopLevelItem(attrItem);
for (const auto& [fxName, mod] : mods) {
QString sign;
switch (mod.op) {
case ModifierOp::Plus: sign = QString("+%1").arg(mod.value); break;
case ModifierOp::Minus: sign = QString("-%1").arg(mod.value); break;
case ModifierOp::Multiply: sign = QString("×%1").arg(mod.value); break;
}
QString label = mod.description.isEmpty()
? fxName
: QString("%1 (%2)").arg(fxName, mod.description);
AddPropertyWithValue(attrItem, label, sign);
}
}
// --- Note (shown as a clickable grey button at the top of the action list) ---
if (!Pawn->note.isEmpty()) {
auto* noteButton = new QPushButton(Pawn->note, ui->ActionList);
noteButton->setFlat(false);
noteButton->setStyleSheet("QPushButton { background-color: #555555; color: #dddddd; "
"text-align: left; padding: 4px 8px; border-radius: 3px; }");
noteButton->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
connect(noteButton, &QPushButton::clicked, this, [this, Pawn]() {
bool ok = false;
QString text = QInputDialog::getMultiLineText(this, "Edit Note",
"Note for " + Pawn->displayName + ":",
Pawn->note, &ok);
if (!ok) return;
SaveSnapshot();
Pawn->note = text.trimmed();
FullRefresh();
SaveToJson();
});
auto* noteItem = new QListWidgetItem(ui->ActionList);
noteItem->setSizeHint(QSize(ui->ActionList->viewport()->width(),
noteButton->sizeHint().height() + 8));
ui->ActionList->setItemWidget(noteItem, noteButton);
}
// --- Actions ---
for (const auto& effect : Pawn->effects) {
const Stage* stage = effect->currentStage();
if (!stage) continue;
for (const auto& action : stage->actions) {
QWidget* w = action->createRuntimeWidget(
ui->ActionList,
Pawn,
[this]{ RefreshPawnList(); });
if (!w) continue;
auto* actionItem = new QListWidgetItem(ui->ActionList);
actionItem->setSizeHint(QSize(ui->ActionList->viewport()->width(),
w->sizeHint().height()));
ui->ActionList->setItemWidget(actionItem, w);
}
}
// Grey out the entire action panel when the pawn is not the active combatant
const bool isActive = (Pawn->state == PawnState::Active);
if (!isActive) {
auto* fx = new QGraphicsOpacityEffect(ui->ActionList);
fx->setOpacity(0.4);
ui->ActionList->setGraphicsEffect(fx);
ui->ActionList->setEnabled(false);
} else {
ui->ActionList->setGraphicsEffect(nullptr);
ui->ActionList->setEnabled(true);
}
RefreshPawnIcons();
}
void MainWindow::RefreshPawnIcons()
{
for (int i = 0; i < ui->PawnList->count(); ++i) {
QListWidgetItem* item = ui->PawnList->item(i);
if (!item) continue;
if (PawnRow* row = qobject_cast<PawnRow*>(ui->PawnList->itemWidget(item)))
row->RefreshIcons();
}
}
// ─────────────────────────────────────────────────────────────────────────────
// Turn / encounter management
// ─────────────────────────────────────────────────────────────────────────────
void MainWindow::on_NextTurnButton_clicked()
{
if (!enc()) return;
SaveSnapshot();
enc()->advanceTurn();
if (!enc()->initiativeOrder.isEmpty() && enc()->initiativeOrder[0].pawn)
CurrentPawnID = enc()->initiativeOrder[0].pawn->instanceId;
ui->RoundNumbeLabel->setText(QString::number(enc()->currentRound));
RefreshPawnList();
FullRefresh();
SaveToJson();
}
void MainWindow::UpdateStartStopButtonAppearance()
{
const AppTheme& t = PathTrackerStruct::instance().theme();
if (EncounterOngoing) {
ui->StartStopButton->setStyleSheet(
"background-color: #cc2222; color: white;");
ui->StartStopButton->setText("Stop Encounter");
} else {
const QString accText = (t.accentColor.lightness() > 128) ? "black" : "white";
ui->StartStopButton->setStyleSheet(
QString("background-color: %1; color: %2;")
.arg(t.accentColor.name(), accText));
ui->StartStopButton->setText("Start Encounter");
}
}
void MainWindow::on_StartStopButton_clicked()
{
if (!enc() || enc()->initiativeOrder.isEmpty()) {
QMessageBox::information(this, "Error", "The Encounter has no Participants");
return;
}
if (!EncounterOngoing) {
// --- Start encounter ---
EncounterOngoing = true;
UpdateStartStopButtonAppearance();
enc()->isOngoing = true;
// Reset all pawn states to Waiting
for (PawnInstance* p : enc()->allCombatants())
p->state = PawnState::Waiting;
enc()->sortInitiative();
// Mark first pawn Active and fire initial events
if (!enc()->initiativeOrder.isEmpty() && enc()->initiativeOrder[0].pawn) {
enc()->initiativeOrder[0].pawn->state = PawnState::Active;
CurrentPawnID = enc()->initiativeOrder[0].pawn->instanceId;
}
enc()->fireRoundStart();
if (PawnInstance* first = enc()->currentActor())
first->fireEvent(EventType::OnTurnStart);
enc()->currentRound = 1;
m_pastStates.clear();
m_futureStates.clear();
SaveSnapshot();
ui->UndoButton->setEnabled(false); // first snapshot – nothing to undo yet
ui->RedoButton->setEnabled(false);
ui->RoundNumbeLabel->setText("1");
ui->NextTurnButton->setEnabled(true);
RefreshPawnList();
FullRefresh();
SaveToJson();
return;
}
// --- Stop encounter: show confirmation dialog ---
QDialog confirmDlg(this);
confirmDlg.setWindowTitle("Stop Encounter?");
auto* dlgLayout = new QVBoxLayout(&confirmDlg);
dlgLayout->addWidget(new QLabel("What would you like to do?", &confirmDlg));
auto* btnRow = new QHBoxLayout;
auto* noBtn = new QPushButton("No", &confirmDlg);
auto* yesBtn = new QPushButton("Yes (Stop)", &confirmDlg);
auto* clearDeadBtn = new QPushButton("Yes + Clear Dead Pawns", &confirmDlg);
auto* clearEncounterBtn = new QPushButton("Yes + Clear Encounter", &confirmDlg);
btnRow->addWidget(noBtn);
btnRow->addWidget(yesBtn);
btnRow->addWidget(clearDeadBtn);
btnRow->addWidget(clearEncounterBtn);
dlgLayout->addLayout(btnRow);
int result = 0; // 0=no, 1=stop, 2=clearDead, 3=clearAll
connect(noBtn, &QPushButton::clicked, &confirmDlg, [&]{ result = 0; confirmDlg.accept(); });
connect(yesBtn, &QPushButton::clicked, &confirmDlg, [&]{ result = 1; confirmDlg.accept(); });
connect(clearDeadBtn, &QPushButton::clicked, &confirmDlg, [&]{ result = 2; confirmDlg.accept(); });
connect(clearEncounterBtn, &QPushButton::clicked, &confirmDlg, [&]{ result = 3; confirmDlg.accept(); });
confirmDlg.exec();