-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmainwindow.cpp
More file actions
2910 lines (2363 loc) · 95.6 KB
/
mainwindow.cpp
File metadata and controls
2910 lines (2363 loc) · 95.6 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 "define.h"
#include "resourcepaths.h"
#include <QList>
#include <QDir>
#include <QFileDialog>
#include <QTimer>
#include <QVariantAnimation>
#include <QRandomGenerator>
#include <QSequentialAnimationGroup>
#include <QPauseAnimation>
#include <QButtonGroup>
#include <QGraphicsColorizeEffect>
#include <QGraphicsItemAnimation>
#include <QTimeLine>
#include <QPropertyAnimation> // Pas obligatoire ici, mais au cas où
#include <QMessageBox>
#include <QWindow>
#include <QListWidget>
#include <QShortcut>
#include <QKeySequence>
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
// Protect side players' cards from clipping
setMinimumHeight(MIN_APPL_HEIGHT);
setMinimumWidth(MIN_APPL_WIDTH);
/*
Please note:
“SmartViewportUpdate” provides smoother performance overall, but green visual artifacts can appear during frequent or extreme window resizing.
With “FullViewportUpdate,” these artifacts disappear, but animations (especially the animated arrow when Neoclassical's deck is selected)
can feel jerky or less fluid. I chose “SmartViewportUpdate” for the best balance in normal use, but it’s a difficult compromise.
If you notice glitches, try switching to Full. (it may improve in Qt 6.8+).
*/
ui->graphicsView->setViewportUpdateMode(QGraphicsView::SmartViewportUpdate);
ui->graphicsView->setCacheMode(QGraphicsView::CacheBackground);
//ui->graphicsView->setRenderHint(QPainter::Antialiasing, false);
ui->splitterHelp->setSizes(QList<int>() << 250 << 750);
setWindowTitle(VERSION);
message(tr("Welcome to ") + QString(VERSION), MESSAGE_SYSTEM);
config = new Config();
statistics = new Statistics(this);
ui->statisticsLayout->addWidget(statistics);
sounds = new Sounds(this);
scene = new CardScene(this);
scene->setItemIndexMethod(QGraphicsScene::NoIndex);
deck = new Deck(this);
engine = new Engine(this, this);
ui->graphicsView->setScene(scene);
background = new Background(scene, this);
scene->protectItem(background);
initCardsPlayedPointers();
createButtonsGroups();
create_arrows();
createPlayerNames();
applyAllSettings();
ui->channel->setStyleSheet(
"color: yellow;" // Text color
"background-color: black;" // Background of the widget itself
"selection-background-color: black;" // Optional: keeps selection bg black
);
ui->channel->setReadOnly(true);
ui->labelBackgroundPreview->setScaledContents(true);
ui->labelBackgroundPreview->setAlignment(Qt::AlignCenter);
ui->labelBackgroundPreview->setMouseTracking(true);
ui->labelBackgroundPreview->setCursor(Qt::PointingHandCursor);
ui->labelBackgroundPreview->installEventFilter(this);
ui->labelBackgroundPreview->setStyleSheet("QLabel { border-radius: 10px; background: lightgray; border: 2px solid gray; }"
"QLabel:hover { border: 4px solid white; }");
// Overlay label (top)
ui->labelPreviewOverlay->setAlignment(Qt::AlignCenter);
ui->labelPreviewOverlay->setAttribute(Qt::WA_TransparentForMouseEvents, true);
ui->labelPreviewOverlay->setVisible(false); // Initially hidden
ui->labelPreviewOverlay->setStyleSheet("border-radius: 10px;"
"background-color: gray;"
"color: white;"
"font-size: 12px;"
// "font-weight: bold;"
"background-color: rgba(0,0,0,180);"
// "padding: 15px;"
);
// We must delay the creation of the credits label or it won't be added to the scene.
// We must delay the creation of the scores board, or it size and position will be wrong.
QTimer::singleShot(0, this, [this]() {
createCreditsLabel();
updatePlayerNames();
createScoreDisplay();
setLanguage(); // creditsLabel must be created first.
scene->protectItem(m_scoreGroup);
scene->protectItem(m_scoreText);
scene->protectItem(m_scoreBackground);
});
// Optional: disable scrollbars for clean look
ui->graphicsView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
ui->graphicsView->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
// Optional: nicer rendering when scaled
ui->graphicsView->setRenderHint(QPainter::Antialiasing);
ui->graphicsView->setRenderHint(QPainter::SmoothPixmapTransform);
// Important anchors
ui->graphicsView->setResizeAnchor(QGraphicsView::AnchorViewCenter);
ui->graphicsView->setAlignment(Qt::AlignCenter);
ui->graphicsView->setSceneRect(scene->itemsBoundingRect());
// Solid green background (no repeat)
ui->graphicsView->setBackgroundBrush(QBrush(QColor(0, 100, 0))); // dark green felt
connect(scene, &CardScene::cardClicked, this, &MainWindow::onCardClicked);
connect(scene, &CardScene::arrowClicked, this, &MainWindow::onArrowClicked);
connect(deck, &Deck::deckChange, this, &MainWindow::onDeckChanged);
connect(ui->pushButton_reveal, &QPushButton::clicked, this, [this](bool checked) {
refresh_deck();
config->set_config_file(CONFIG_CHEAT_REVEAL, checked);
});
connect(ui->checkBox_confirm_exit, &QCheckBox::clicked, this, [this](bool checked) {
config->set_config_file(CONFIG_CONFIRM_EXIT, checked);
});
connect(ui->checkBox_tram, &QCheckBox::clicked, this, [this](bool checked) {
config->set_config_file(CONFIG_DETECT_TRAM, checked);
engine->set_tram(checked);
});
connect(ui->checkBox_cheat, &QCheckBox::clicked, this, [this](bool checked) {
config->set_config_file(CONFIG_CHEAT_MODE, checked);
setCheatMode(checked);
});
connect(ui->pushButton_sound, &QPushButton::clicked, this, [this](bool checked) {
sounds->setEnabled(checked);
config->set_config_file(CONFIG_SOUNDS, checked);
});
connect(ui->pushButton_new, &QPushButton::clicked, this, &MainWindow::onNewGame);
connect(ui->checkBox_new_game, &QCheckBox::clicked, this, [this](bool checked) {
config->set_config_file(CONFIG_COMFIRM_NEW_GAME, checked);
});
connect(ui->tabWidget, &QTabWidget::currentChanged, this, &MainWindow::onTabChanged);
connect(background, &Background::backgroundChanged, this, [this](const QString &path) {
if (loadBackgroundPreview(path)) {
updateCredits(background->Credits(), background->CreditTextColor());
config->set_background_path(path);
}
});
connect(statistics, &Statistics::sig_message, this, &MainWindow::message);
connect(engine, &Engine::sig_your_turn, this, &MainWindow::onYourTurn);
connect(engine, &Engine::sig_play_sound, this, &MainWindow::onPlaySound);
connect(engine, &Engine::sig_update_stat, this, &MainWindow::onUpdateStat);
connect(engine, &Engine::sig_update_stat_score, this, &MainWindow::onUpdateStatScore);
connect(engine, &Engine::sig_message, this, &MainWindow::message);
connect(engine, &Engine::sig_setTrickPile, this, &MainWindow::onSetTrickPile);
connect(engine, &Engine::sig_enableAllCards, this, &MainWindow::enableAllCards);
connect(engine, &Engine::sig_refresh_deck, this, &MainWindow::refresh_deck);
connect(engine, &Engine::sig_clear_deck, this, &MainWindow::onClearDeck);
connect(engine, &Engine::sig_new_players, this, &MainWindow::onNewPlayers);
connect(engine, &Engine::sig_update_scores_board, this, &MainWindow::onUpdateScoresBoard);
connect(engine, &Engine::sig_collect_tricks, this, &MainWindow::onCollectTricks);
connect(engine, &Engine::sig_play_card, this, &MainWindow::onPlayCard);
connect(engine, &Engine::sig_deal_cards, this, &MainWindow::onDealCards);
connect(engine, &Engine::sig_passed, this, &MainWindow::onPassed);
connect(engine, &Engine::sig_pass_to, this, &MainWindow::onPassTo);
connect(engine, &Engine::sig_refresh_cards_played, this, &MainWindow::onRefreshCardsPlayed);
connect(engine, &Engine::sig_card_played, this, &MainWindow::onCardPlayed);
connect(qApp, &QCoreApplication::aboutToQuit, this, &MainWindow::aboutToQuit);
connect(ui->treeHelpTOC, &QTreeWidget::currentItemChanged,
this, [this](QTreeWidgetItem *current, QTreeWidgetItem *previous) {
if (!current) return;
QString anchor = current->data(0, Qt::UserRole).toString();
if (!anchor.isEmpty()) {
ui->textHelpContent->setSource(QUrl("#" + anchor));
}
});
// Global quick Quit with shortcut Ctrl+Q
QShortcut *quitShortcut = new QShortcut(QKeySequence("Ctrl+Q"), this);
quitShortcut->setContext(Qt::ApplicationShortcut);
connect(quitShortcut, &QShortcut::activated, this, &MainWindow::tryQuit);
connect(ui->pushButton_exit, &QPushButton::clicked, this, [this]() {
if (!ui->checkBox_confirm_exit->isChecked()) {
qApp->quit();
return;
}
QMessageBox::StandardButton reply = QMessageBox::question(this,
tr("Exit the game?"),
tr("Do you really want to leave the game?"),
QMessageBox::Yes | QMessageBox::No,
QMessageBox::No);
if (reply == QMessageBox::Yes) {
qApp->quit();
}
});
}
MainWindow::~MainWindow()
{
disconnect(this, nullptr, nullptr, nullptr);
delete config; config = nullptr; // no parent
qDebug() << "~MainWindow() terminé";
}
// ************************************************************************************************
// Section 1- [ EVENTS OVERRIDE ]
// resizeEvent(QResizeEvent *event)
// eventFilter(QObject *obj, QEvent *event)
// showEvent(QShowEvent *event)
// closeEvent(QCloseEvent *event) override
// tryQuit()
// aboutToQuit()
//
// Section 2- [ Initialisation / Set / Loads ]
// initCardsPlayedPointers()
// loadHelpFile()
// loadBackgroundPreview(const QString &image_path)
// loadCardsPlayed()
// applyAllSettings()
// setAnimationLock()
// setAnimationUnlock()
// setCheatMode(bool enabled)
// setAnimationButtons(bool enabled)
// setLanguage()
//
// Section 3- [ Private Slots ]
// onDeckChanged(int deckId)
// onBackgroundPreviewClicked()
// onCardClicked(QGraphicsItem *item)
// onArrowClicked
// onYourTurn();
// onPlaySound(SOUNDS soundId);
// onUpdateStat(int player, STATS stat);
// onEngineMessage(const QString &msg);
// onSetTrickPile(const QList<int> &pile);
// onClearDeck();
// onCollectTricks(PLAYER winner, bool tram);
// onPlayCard(int cardId, PLAYER player);
// onDealCards();
// onPassed();
// onPassTo(int direction);
// onNewPlayers(const QString names[4]);
// onUpdateScoresBoard(const QString names[4], const int hand[4], const int total[4]);
// onUpdateStatScore(int player, int score);
// onNewGame();
// onTabChanged(int index);
// onDeckStyle(int id);
// onVariantToggled(int id, bool checked);
// onAnimationToggled(int id, bool checked);
// onRefreshCardsPlayed()
// onCardPlayed()
// on_opt_animations_clicked()
// on_pushButton_undo_clicked()
// on_opt_anim_arrow_clicked(bool checked)
// on_pushButton_score_clicked()
//
// Section 4- [ Create Functions ]
// createCreditsLabel()
// create_arrows()
// createButtonsGroups()
// createPlayerNames()
// createScoreDisplay()
// createTOC()
//
// Section 5- [ Update Functions ]
// updateTurnArrow()
// updateYourTurnIndicator()
// updateTrickPile()
// updateSceneRect()
// updateBackground()
// updateCreditsPosition()
// updateCredits()
// refresh_deck()
// updatePlayerNames()
// updateScores(const int handScores[4], const int totalScores[4], const QString playersName[4], const PlayerIcon icons[4])
// repositionAllCardsAndElements()
//
// Section 6- [ Animate Functions ]
// animatePlayCard(int cardId, int player)
// animatePassCards(const QList<int> passedCards[4], int direction)
// animateCardsToCenter(const QList<int> &cardsId, QParallelAnimationGroup *masterGroup, int startDelay, int perCardStagger)
// animateCardsToPlayer(const QList<int> &cardsId, int targetPlayer, int duration, QParallelAnimationGroup *masterGroup, int startDelay, int perCardStagger, bool takeAllRemaining)
// animateCardsOffBoard(const QList<int> &cardsId, int winner)
// animateCollectTrick(int winner, bool takeAllRemaining = false)
// animateDeal(int dealDuration, int delayBetweenCards)
// animateYourTurnIndicator()
// highlightAIPassedCards(int player, const QList<int>& passedCardIds)
//
// Section 7- [ Mathematic Functions ]
// cardX(int cardId, int player, int handIndex)
// cardY(int cardId, int player, int handIndex)
// getTakenPileCenter(int player, const QSize& viewSize) const
// anim_rotation_value(int player)
// calc_scale()
// cardZ(int player, int cardId)
// calculatePlayerNamePos(int player)
//
// Section 8- [ UNSORTED FUNCTIONS ]
//
// ************************************************************************************************
// ************************************[ 1- EVENTS OVERRIDE ] *************************************
void MainWindow::resizeEvent(QResizeEvent *event)
{
QMainWindow::resizeEvent(event);
if (ui->graphicsView->scene()) {
ui->graphicsView->scene()->invalidate(QRectF(), QGraphicsScene::AllLayers); // ← invalide TOUT
ui->graphicsView->scene()->update(); // scène globale
ui->graphicsView->viewport()->update(); // ← le plus important : force le widget viewport
ui->graphicsView->viewport()->repaint(); // ← repaint immédiat, bypass le paint event queue
}
// Only update if Board tab is visible (avoids unnecessary work)
if (ui->tabWidget->currentIndex() == TAB_BOARD) {
updateSceneRect();
repositionAllCardsAndElements();
ui->graphicsView->scene()->update();
lastBoardViewSize = ui->graphicsView->size();
} else {
windowWasResizedWhileAway = true;
}
}
bool MainWindow::eventFilter(QObject *obj, QEvent *event)
{
if (obj == ui->labelBackgroundPreview) {
if (event->type() == QEvent::Enter) {
ui->labelPreviewOverlay->setVisible(true);
return false;
}
if (event->type() == QEvent::Leave) {
ui->labelPreviewOverlay->setVisible(false);
return false;
}
if (event->type() == QEvent::MouseButtonPress) {
QMouseEvent *mouseEvent = static_cast<QMouseEvent*>(event);
if (mouseEvent->button() == Qt::LeftButton) {
onBackgroundPreviewClicked();
return true;
}
}
}
return QMainWindow::eventFilter(obj, event);
}
void MainWindow::showEvent(QShowEvent *event)
{
QMainWindow::showEvent(event);
// Only do this the first time the window is shown
static bool firstShow = true;
if (firstShow) {
firstShow = false;
// this will prevent start or load game...
// No valid deck loaded... DON'T refresh or it will crash.
if (forced_new_deck) {
start_engine_dalayed = true;
return;
}
// Let the layout fully settle, then reposition everything and start the engine.
QTimer::singleShot(0, this, [this]() {
updateSceneRect();
repositionAllCardsAndElements();
engine->Start();
});
}
}
void MainWindow::closeEvent(QCloseEvent *event)
{
qDebug() << "closeEvent appelé, busy =" << engine->isBusy();
sounds->setEnabled(false);
sounds->stopAllSounds();
QCoreApplication::processEvents(QEventLoop::AllEvents, 800);
tryQuit();
event->ignore();
}
void MainWindow::tryQuit()
{
if (!engine->isBusy()) {
qDebug() << "tryQuit : idle → fermeture immédiate";
qApp->quit();
return;
}
ui->opt_animations->setChecked(false);
hide();
qDebug() << "tryQuit : busy → attente sig_busy(false)";
static QMetaObject::Connection busyConnection;
// On déconnecte l'ancienne si elle existe (pour éviter accumulation)
if (busyConnection) {
disconnect(busyConnection);
}
busyConnection = connect(engine, &Engine::sig_busy, this,
[this](bool busy) {
qDebug() << "sig_busy pendant fermeture :" << busy;
if (!busy) {
qDebug() << "→ idle détecté → on quitte";
qApp->quit();
// Optionnel : on peut déconnecter ici, mais pas obligatoire
// (la static reste mais la connexion est inactive)
if (busyConnection) {
disconnect(busyConnection);
busyConnection = {}; // reset pour la prochaine fois
}
}
});
QTimer::singleShot(10000, this, [this]() {
qWarning() << "Timeout → fermeture forcée";
qApp->quit();
// Nettoyage aussi dans le timeout
if (busyConnection) {
disconnect(busyConnection);
busyConnection = {};
}
});
}
void MainWindow::aboutToQuit()
{
statistics->save_stats_file();
engine->save_game();
config->set_width(size().width());
config->set_height(size().height());
config->set_posX(pos().x());
config->set_posY(pos().y());
// Give Pulse audio time to clean stuff to avoid crashes on exit()
sounds->stopAllSounds();
QTimer::singleShot(200, qApp, &QApplication::quit);
}
// ************************************************************************************************
// *****************************[ 2- Initialisation / Set / Loads ] *******************************
void MainWindow::initCardsPlayedPointers()
{
cardLabels[CLUBS_TWO] = ui->label_clubs_2;
cardLabels[CLUBS_THREE] = ui->label_clubs_3;
cardLabels[CLUBS_FOUR] = ui->label_clubs_4;
cardLabels[CLUBS_FIVE] = ui->label_clubs_5;
cardLabels[CLUBS_SIX] = ui->label_clubs_6;
cardLabels[CLUBS_SEVEN] = ui->label_clubs_7;
cardLabels[CLUBS_EIGHT] = ui->label_clubs_8;
cardLabels[CLUBS_NINE] = ui->label_clubs_9;
cardLabels[CLUBS_TEN] = ui->label_clubs_10;
cardLabels[CLUBS_JACK] = ui->label_clubs_jack;
cardLabels[CLUBS_QUEEN] = ui->label_clubs_queen;
cardLabels[CLUBS_KING] = ui->label_clubs_king;
cardLabels[CLUBS_ACE] = ui->label_clubs_ace;
cardLabels[SPADES_TWO] = ui->label_spades_2;
cardLabels[SPADES_THREE] = ui->label_spades_3;
cardLabels[SPADES_FOUR] = ui->label_spades_4;
cardLabels[SPADES_FIVE] = ui->label_spades_5;
cardLabels[SPADES_SIX] = ui->label_spades_6;
cardLabels[SPADES_SEVEN] = ui->label_spades_7;
cardLabels[SPADES_EIGHT] = ui->label_spades_8;
cardLabels[SPADES_NINE] = ui->label_spades_9;
cardLabels[SPADES_TEN] = ui->label_spades_10;
cardLabels[SPADES_JACK] = ui->label_spades_jack;
cardLabels[SPADES_QUEEN] = ui->label_spades_queen;
cardLabels[SPADES_KING] = ui->label_spades_king;
cardLabels[SPADES_ACE] = ui->label_spades_ace;
cardLabels[DIAMONDS_TWO] = ui->label_diamonds_2;
cardLabels[DIAMONDS_THREE] = ui->label_diamonds_3;
cardLabels[DIAMONDS_FOUR] = ui->label_diamonds_4;
cardLabels[DIAMONDS_FIVE] = ui->label_diamonds_5;
cardLabels[DIAMONDS_SIX] = ui->label_diamonds_6;
cardLabels[DIAMONDS_SEVEN] = ui->label_diamonds_7;
cardLabels[DIAMONDS_EIGHT] = ui->label_diamonds_8;
cardLabels[DIAMONDS_NINE] = ui->label_diamonds_9;
cardLabels[DIAMONDS_TEN] = ui->label_diamonds_10;
cardLabels[DIAMONDS_JACK] = ui->label_diamonds_jack;
cardLabels[DIAMONDS_QUEEN] = ui->label_diamonds_queen;
cardLabels[DIAMONDS_KING] = ui->label_diamonds_king;
cardLabels[DIAMONDS_ACE] = ui->label_diamonds_ace;
cardLabels[HEARTS_TWO] = ui->label_hearts_2;
cardLabels[HEARTS_THREE] = ui->label_hearts_3;
cardLabels[HEARTS_FOUR] = ui->label_hearts_4;
cardLabels[HEARTS_FIVE] = ui->label_hearts_5;
cardLabels[HEARTS_SIX] = ui->label_hearts_6;
cardLabels[HEARTS_SEVEN] = ui->label_hearts_7;
cardLabels[HEARTS_EIGHT] = ui->label_hearts_8;
cardLabels[HEARTS_NINE] = ui->label_hearts_9;
cardLabels[HEARTS_TEN] = ui->label_hearts_10;
cardLabels[HEARTS_JACK] = ui->label_hearts_jack;
cardLabels[HEARTS_QUEEN] = ui->label_hearts_queen;
cardLabels[HEARTS_KING] = ui->label_hearts_king;
cardLabels[HEARTS_ACE] = ui->label_hearts_ace;
}
void MainWindow::loadHelpFile()
{
QFile file; // (":/translations/help.html");
if (ui->opt_english->isChecked()) {
file.setFileName(":/translations/help.html");
} else
if (ui->opt_french->isChecked()) {
qDebug() << "Set french help.";
file.setFileName(":/translations/help_fr.html");
} else
if (ui->opt_russian->isChecked()) {
file.setFileName(":/translations/help_ru.html");
}
if (file.open(QIODevice::ReadOnly | QIODevice::Text)) {
QTextStream in(&file);
QString html = in.readAll();
ui->textHelpContent->setHtml(html);
file.close();
} else {
qWarning() << "Impossible de charger help.html";
ui->textHelpContent->setPlainText(tr("Error : help file not found."));
}
ui->textHelpContent->setOpenExternalLinks(true);
ui->textHelpContent->setOpenLinks(true);
}
bool MainWindow::loadBackgroundPreview(const QString &image_path)
{
QPixmap preview(image_path);
if (preview.isNull())
return false;
ui->labelBackgroundPreview->setPixmap(preview.scaled(ui->labelBackgroundPreview->size(),
Qt::KeepAspectRatioByExpanding,
Qt::SmoothTransformation ));
return true;
}
void MainWindow::loadCardsPlayed()
{
static const QStringList ranks = { "2", "3", "4", "5", "6", "7", "8", "9", "10", "Jack", "Queen", "King", "Ace" };
static const QStringList suits = { " ♣", " ♠", " ♦", " ♥" };
QPixmap pix;
QString sRank;
for (int cardId = 0; cardId < DECK_SIZE; cardId++) {
int suit = cardId / 13;
int rank = cardId % 13;
switch (rank) {
case 9 : sRank = tr("Jack"); break;
case 10 : sRank = tr("Queen"); break;
case 11 : sRank = tr("King"); break;
case 12 : sRank = tr("Ace"); break;
default : sRank = ranks[rank];
}
pix = deck->get_card_pixmap(cardId);
cardLabels[cardId]->setPixmap(pix);
cardLabels[cardId]->setToolTip(sRank + QString(suits[suit]));
cardLabels[cardId]->setDisabled(engine->isCardPlayed(cardId));
}
}
void MainWindow::applyAllSettings()
{
int deck_style = config->get_deck_style();
bool deck_loaded = deck->set_deck(deck_style);
bool enabled;
if (!deck_loaded) {
deck_style = STANDARD_DECK;
deck_loaded = deck->set_deck(deck_style);
}
// Load the built-in deck. It should not fail, but as a safety i'll check it
if (!deck_loaded) {
disableDeck(deck_style);
} else {
deckGroup->button(deck_style)->setChecked(true);
import_allCards_to_scene();
}
enabled = config->is_sounds();
ui->pushButton_sound->setChecked(enabled);
sounds->setEnabled(enabled);
enabled = config->is_queen_spade_break_heart();
ui->opt_queen_spade->setChecked(enabled);
engine->set_variant(VARIANT_QUEEN_SPADE, enabled);
enabled = config->is_perfect_100();
ui->opt_perfect_100->setChecked(enabled);
engine->set_variant(VARIANT_PERFECT_100, enabled);
enabled = config->is_omnibus();
ui->opt_omnibus->setChecked(enabled);
engine->set_variant(VARIANT_OMNIBUS, enabled);
enabled = config->is_no_trick_bonus();
ui->opt_no_tricks->setChecked(enabled);
engine->set_variant(VARIANT_NO_TRICKS, enabled);
enabled = config->is_new_moon();
ui->opt_new_moon->setChecked(enabled);
engine->set_variant(VARIANT_NEW_MOON, enabled);
enabled = config->is_no_draw();
ui->opt_no_draw->setChecked(enabled);
engine->set_variant(VARIANT_NO_DRAW, enabled);
enabled = config->is_animated_play();
ui->opt_animations->setChecked(enabled);
setAnimationButtons(enabled);
enabled = config->is_confirm_exit();
ui->checkBox_confirm_exit->setChecked(enabled);
enabled = config->is_detect_tram();
ui->checkBox_tram->setChecked(enabled);
engine->set_tram(enabled);
enabled = config->is_cheat_reveal();
ui->pushButton_reveal->setChecked(enabled);
enabled = config->is_confirm_new_game();
ui->checkBox_new_game->setChecked(enabled);
// This settings must be applied after is_cheat_reveal(), so setCheatMode will unset
// reveal pushButton if the overall cheat mode has been set to false.
enabled = config->is_cheat_mode();
ui->checkBox_cheat->setChecked(enabled);
setCheatMode(enabled);
ui->opt_anim_deal_cards->setChecked(config->is_anim_deal_cards());
ui->opt_anim_play_card->setChecked(config->is_anim_play_card());
ui->opt_anim_collect_tricks->setChecked(config->is_anim_collect_tricks());
ui->opt_anim_pass_cards->setChecked(config->is_anim_pass_cards());
enabled = config->is_animated_arrow();
ui->opt_anim_arrow->setChecked(enabled);
on_opt_anim_arrow_clicked(enabled);
ui->opt_anim_triangle->setChecked(config->is_anim_turn_indicator());
switch (config->get_language()) {
case LANG_ENGLISH: ui->opt_english->setChecked(true); break;
case LANG_FRENCH: ui->opt_french->setChecked(true); break;
case LANG_RUSSIAN: ui->opt_russian->setChecked(true); break;
}
QSize savedSize(config->width(), config->height());
QPoint savedPos(config->posX(), config->posY());
// If there is no background path. We load the legacy background save by index.
if (config->Path().isEmpty()) {
qDebug() << "applyAllSettings loading a legacy background!";
background->setBackground(config->get_background_index());
} else {
background->setBackgroundPixmap(config->Path());
}
resize(savedSize);
// With all the Linux window managers THAT doesn't works.
// move(savedPos);
loadBackgroundPreview(background->FullPath());
}
void MainWindow::setAnimationLock()
{
m_animationLockCount++;
if (m_animationLockCount == 1) { // First lock (was 0 → 1)
// Remember current size before fixing
m_fixedSizeDuringLock = size();
// Lock window size
setFixedSize(m_fixedSizeDuringLock);
// Disable deck switch tab
ui->tabWidget->setTabEnabled(TAB_SETTINGS, false);
// Disable cards reveal
ui->pushButton_reveal->setDisabled(true);
// Disable new game
ui->pushButton_new->setDisabled(true);
// Disable undo
ui->pushButton_undo->setDisabled(true);
// Visual feedback
// ui->graphicsView->setCursor(Qt::WaitCursor);
QApplication::setOverrideCursor(Qt::WaitCursor);
}
}
void MainWindow::setAnimationUnlock()
{
if (m_animationLockCount <= 0) {
m_animationLockCount = 0;
return;
}
m_animationLockCount--;
if (m_animationLockCount == 0) {
// Fully unlocked
ui->tabWidget->setTabEnabled(TAB_SETTINGS, true);
// TODO don't enable reveal and undo, if we're playing ONLINE
ui->pushButton_reveal->setDisabled(false);
ui->pushButton_undo->setDisabled(false);
ui->pushButton_new->setDisabled(false);
// ui->graphicsView->unsetCursor();
QApplication::restoreOverrideCursor();
// Restore full resizability
setMinimumSize(QSize(MIN_APPL_WIDTH, MIN_APPL_HEIGHT));
setMaximumSize(QSize(QWIDGETSIZE_MAX, QWIDGETSIZE_MAX));
}
}
void MainWindow::setCheatMode(bool enabled)
{
if (!enabled) {
ui->pushButton_reveal->setChecked(false);
config->set_config_file(CONFIG_CHEAT_REVEAL, false);
}
ui->tabWidget->setTabVisible(TAB_CARDS_PLAYED, enabled);
ui->pushButton_reveal->setVisible(enabled);
}
void MainWindow::setAnimationButtons(bool enabled)
{
ui->opt_anim_deal_cards->setEnabled(enabled);
ui->opt_anim_play_card->setEnabled(enabled);
ui->opt_anim_collect_tricks->setEnabled(enabled);
ui->opt_anim_pass_cards->setEnabled(enabled);
ui->opt_anim_arrow->setEnabled(enabled);
ui->opt_anim_triangle->setEnabled(enabled);
}
void MainWindow::setLanguage()
{
// Retirer l’ancien translator s’il existe
if (currentTranslator) {
qApp->removeTranslator(currentTranslator);
delete currentTranslator;
currentTranslator = nullptr;
}
currentTranslator = new QTranslator(this);
QString translation(":/translations/Hearts_en_CA.qm");
if (ui->opt_french->isChecked()) {
translation = ":/translations/Hearts_fr_CA.qm";
} else
if (ui->opt_russian->isChecked()) {
translation = ":/translations/Hearts_ru_RU.qm";
}
// Chargement depuis les ressources embarquées
if (currentTranslator->load(translation)) {
qApp->installTranslator(currentTranslator);
} else {
qDebug() << "Échec chargement traduction :" << translation;
}
ui->retranslateUi(this);
statistics->Translate();
ui->treeHelpTOC->clear();
qDebug() << "Create new TOC";
createTOC();
loadHelpFile();
loadCardsPlayed();
background->setCredits();
engine->refresh_scoreboard();
updateCredits(background->Credits(), background->CreditTextColor());
updateCreditsPosition();
}
// ************************************************************************************************
// ************************************[ 3- Private Slots ] ***************************************
void MainWindow::onDeckChanged(int deckId)
{
qDebug() << "onDeckChanged: " << deckId;
qDebug() << "onDeckChanged: Scene size: " << scene->items().size();
QGraphicsItem *item;
for (int i = 0; i < selectedCards.size(); i++) {
item = deck->get_card_item(selectedCards.at(i), true);
item->setData(1, true);
}
loadCardsPlayed();
}
void MainWindow::onBackgroundPreviewClicked()
{
QString path = getResourceFile(QString("backgrounds"));
QString fileName = QFileDialog::getOpenFileName(this,
tr("Choose Background Image"),
path,
tr("Images (*.png *.jpg *.jpeg *.bmp *.gif *.svg)"));
if (fileName.isEmpty()) return;
QPixmap pix(fileName);
if (pix.isNull()) {
qDebug() << "Failed to load background:" << fileName;
return;
}
// Update the actual scene background
background->setBackgroundPixmap(fileName);
updateCreditsPosition();
// Update preview label
loadBackgroundPreview(fileName);
}
void MainWindow::onCardClicked(QGraphicsItem *item)
{
if (!item) return;
QVariant idVar = item->data(0);
if (!idVar.isValid() || !idVar.canConvert<int>()) return;
int cardId = idVar.toInt();
if (cardId < 0 || cardId >= DECK_SIZE) return;
int player = engine->Owner(cardId);
if (player != PLAYER_SOUTH)
return;
idVar = item->data(1);
if (!idVar.isValid() || !idVar.canConvert<bool>()) return;
bool selected = idVar.toBool();
if (engine->Status() == SELECT_CARDS) {
if (selected) {
selectedCards.removeAll(cardId);
item->setData(1, false);
item->setPos(item->pos().x(), item->pos().y() + SELECTED_CARD_OFFSET);
} else {
if (selectedCards.size() >= 3)
return;
// Must saved those selected cards. Switching to a new deck will destroy all the previous items and information.
selectedCards.append(cardId);
item->setData(1, true);
item->setPos(item->pos().x(), item->pos().y() - SELECTED_CARD_OFFSET);
sounds->play(SOUND_CONTACT);
}
} else {
if (!isProcessingTurn && engine->isPlaying() && (engine->Turn() == PLAYER_SOUTH)) {
isProcessingTurn = true;
engine->Play(cardId);
sounds->play(SOUND_DEALING_CARD);
yourTurnIndicator->hide();
removeInvalidCardsEffect();
playCard(cardId, PLAYER_SOUTH);
}
}
if (player == PLAYER_NOBODY) {
qDebug() << "Warning: Clicked card" << cardId << "not found in any player's hand!";
return;
}
}
void MainWindow::onArrowClicked()
{
if (selectedCards.size() != 3) {
message(tr("You must select 3 cards to pass!"), MESSAGE_ERROR);
} else {
arrowLabel->hide();
engine->set_passedFromSouth(selectedCards);
selectedCards.clear();
engine->Step();
}
}
void MainWindow::onYourTurn() {
isProcessingTurn = false;
disableInvalidCards();
showTurnIndicator();
}
void MainWindow::onPlaySound(SOUNDS soundId) {
sounds->play(soundId);
}
void MainWindow::onUpdateStat(int player, STATS stat) {
statistics->increase_stats(player, stat);
}
void MainWindow::onSetTrickPile(const QList<int> &pile) {
int cpt = 0;
currentTrick = pile;
for (int i = pile.size() - 1; i >= 0; --i) {
QGraphicsSvgItem *item = deck->get_card_item(currentTrick.at(i), true);
switch (cpt) {
case 0: item->setRotation(-90); break;
case 1: item->setRotation(180); break;
case 2: item->setRotation(90); break;
break;
}
cpt++;
item->setZValue(Z_TRICKS_BASE - cpt);
}
updateTrickPile();
}
void MainWindow::onClearDeck() {
scene->clear();
clearTricks();
yourTurnIndicator->hide();
arrowLabel->hide();
}
void MainWindow::onCollectTricks(PLAYER winner, bool tram) {
if (ui->opt_animations->isChecked() && ui->opt_anim_collect_tricks->isChecked()) {
animateCollectTrick(winner, tram);
} else {
QTimer::singleShot(1000, this, [this]() {
clearTricks();
engine->Step();
});
}
}
void MainWindow::onPlayCard(int cardId, PLAYER player) {
sounds->play(SOUND_DEALING_CARD);