-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgui.cpp
More file actions
1132 lines (993 loc) · 40.7 KB
/
Copy pathgui.cpp
File metadata and controls
1132 lines (993 loc) · 40.7 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 "gui.h"
#include "logger.h"
#include <iostream>
#include <sstream>
#include <iomanip>
#include <math.h>
// Constructor
BlockchainGUI::BlockchainGUI(Blockchain *bc) : blockchain(bc), currentState(AppState::MAIN_MENU),
animationTime(0), scrollOffset(0), statusTimer(0)
{
// Create window with minimize, maximize, and close buttons
window.create(sf::VideoMode(1200, 800), "AlgoChain - Blockchain Simulation",
sf::Style::Titlebar | sf::Style::Close | sf::Style::Resize);
window.setFramerateLimit(60);
// Load font with multiple fallback options
bool fontLoaded = false;
// Try loading fonts in order of preference
const std::vector<std::string> fontPaths = {
"ARIAL.TTF", // Local uppercase
"arial.ttf", // Local lowercase
"/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf", // Linux DejaVu
"/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf", // Linux Liberation
"/usr/share/fonts/truetype/ubuntu/Ubuntu-R.ttf", // Linux Ubuntu
"/System/Library/Fonts/Helvetica.ttc", // macOS
"C:/Windows/Fonts/arial.ttf", // Windows
"C:/Windows/Fonts/Arial.ttf" // Windows uppercase
};
for (const auto &path : fontPaths)
{
if (font.loadFromFile(path))
{
Logger::success("Font loaded successfully: " + path, "GUI");
fontLoaded = true;
break;
}
}
if (!fontLoaded)
{
Logger::error("Failed to load any font. Text will not display!", "GUI");
Logger::warning("Please ensure ARIAL.TTF exists in project directory or system fonts are available.", "GUI");
}
initializeColors();
initializeUI();
}
BlockchainGUI::~BlockchainGUI()
{
// Clean up
}
void BlockchainGUI::initializeColors()
{
// Modern Blue/Teal palette with dark theme
primaryColor = sf::Color(41, 128, 185); // Modern Blue
secondaryColor = sf::Color(52, 152, 219); // Light Blue
accentColor = sf::Color(26, 188, 156); // Teal/Turquoise
backgroundColor = sf::Color(44, 62, 80); // Dark Blue-Grey
textColor = sf::Color(236, 240, 241); // Light Grey
successColor = sf::Color(46, 204, 113); // Emerald Green
errorColor = sf::Color(231, 76, 60); // Soft Red
}
void BlockchainGUI::initializeUI()
{
// Clear existing UI elements
buttons.clear();
inputFields.clear();
// Get window dimensions for centering
float windowWidth = 1200.0f;
float windowHeight = 800.0f;
float centerX = windowWidth / 2.0f;
// Initialize based on current state
switch (currentState)
{
case AppState::MAIN_MENU:
// Main menu buttons - centered and evenly spaced
buttons.push_back(make_unique<Button>(sf::Vector2f(centerX - 150, 180), sf::Vector2f(300, 55), "Add Transaction"));
buttons.push_back(make_unique<Button>(sf::Vector2f(centerX - 150, 250), sf::Vector2f(300, 55), "Mine Block"));
buttons.push_back(make_unique<Button>(sf::Vector2f(centerX - 150, 320), sf::Vector2f(300, 55), "View Blockchain"));
buttons.push_back(make_unique<Button>(sf::Vector2f(centerX - 150, 390), sf::Vector2f(300, 55), "Transaction Pool"));
buttons.push_back(make_unique<Button>(sf::Vector2f(centerX - 150, 460), sf::Vector2f(300, 55), "Check Balance"));
buttons.push_back(make_unique<Button>(sf::Vector2f(centerX - 150, 530), sf::Vector2f(300, 55), "Statistics"));
// Bottom buttons
buttons.push_back(make_unique<Button>(sf::Vector2f(centerX - 220, 650), sf::Vector2f(130, 50), "Settings"));
buttons.push_back(make_unique<Button>(sf::Vector2f(centerX + 90, 650), sf::Vector2f(130, 50), "Exit"));
break;
case AppState::ADD_TRANSACTION:
inputFields.push_back(make_unique<InputField>(sf::Vector2f(centerX - 175, 230), sf::Vector2f(350, 45), "From Address:"));
inputFields.push_back(make_unique<InputField>(sf::Vector2f(centerX - 175, 320), sf::Vector2f(350, 45), "To Address:"));
inputFields.push_back(make_unique<InputField>(sf::Vector2f(centerX - 175, 410), sf::Vector2f(350, 45), "Amount:"));
buttons.push_back(make_unique<Button>(sf::Vector2f(centerX - 110, 500), sf::Vector2f(220, 50), "Add Transaction"));
buttons.push_back(make_unique<Button>(sf::Vector2f(50, 730), sf::Vector2f(140, 50), "← Back"));
break;
case AppState::MINE_BLOCK:
buttons.push_back(make_unique<Button>(sf::Vector2f(centerX - 100, 350), sf::Vector2f(200, 55), "⛏ Mine Block"));
buttons.push_back(make_unique<Button>(sf::Vector2f(50, 730), sf::Vector2f(140, 50), "← Back"));
break;
case AppState::VIEW_BLOCKCHAIN:
buttons.push_back(make_unique<Button>(sf::Vector2f(50, 730), sf::Vector2f(140, 50), "← Back"));
break;
case AppState::VIEW_TRANSACTIONS:
buttons.push_back(make_unique<Button>(sf::Vector2f(50, 730), sf::Vector2f(140, 50), "← Back"));
break;
case AppState::STATISTICS:
buttons.push_back(make_unique<Button>(sf::Vector2f(50, 730), sf::Vector2f(140, 50), "← Back"));
break;
case AppState::CHECK_BALANCE:
inputFields.push_back(make_unique<InputField>(sf::Vector2f(centerX - 175, 280), sf::Vector2f(350, 45), "Address:"));
buttons.push_back(make_unique<Button>(sf::Vector2f(centerX - 80, 360), sf::Vector2f(160, 50), "Check Balance"));
buttons.push_back(make_unique<Button>(sf::Vector2f(50, 730), sf::Vector2f(140, 50), "← Back"));
break;
case AppState::SETTINGS:
inputFields.push_back(make_unique<InputField>(sf::Vector2f(centerX - 175, 240), sf::Vector2f(350, 45), "Difficulty (1-6):"));
inputFields.push_back(make_unique<InputField>(sf::Vector2f(centerX - 175, 320), sf::Vector2f(350, 45), "Mining Reward:"));
// Set current values
inputFields[0]->setValue(to_string(blockchain->getDifficulty()));
inputFields[1]->setValue(to_string(blockchain->getMiningReward()));
buttons.push_back(make_unique<Button>(sf::Vector2f(centerX - 220, 410), sf::Vector2f(200, 50), "Apply Settings"));
buttons.push_back(make_unique<Button>(sf::Vector2f(centerX + 20, 410), sf::Vector2f(200, 50), "Reset Defaults"));
buttons.push_back(make_unique<Button>(sf::Vector2f(50, 730), sf::Vector2f(140, 50), "← Back"));
break;
default:
buttons.push_back(make_unique<Button>(sf::Vector2f(50, 50), sf::Vector2f(100, 40), "Back"));
break;
}
}
bool BlockchainGUI::isOpen() const
{
return window.isOpen();
}
void BlockchainGUI::run()
{
sf::Clock clock;
while (window.isOpen())
{
float deltaTime = clock.restart().asSeconds();
handleEvents();
update(deltaTime);
render();
}
}
void BlockchainGUI::handleEvents()
{
sf::Event event;
while (window.pollEvent(event))
{
switch (event.type)
{
case sf::Event::Closed:
window.close();
break;
case sf::Event::MouseButtonPressed:
if (event.mouseButton.button == sf::Mouse::Left)
{
sf::Vector2f mousePos(static_cast<float>(event.mouseButton.x), static_cast<float>(event.mouseButton.y));
Logger::debug("Mouse click detected at position (" + std::to_string(mousePos.x) + ", " + std::to_string(mousePos.y) + ")", "GUI");
// Debug: Show all buttons and their positions (only in debug mode)
std::stringstream buttonInfo;
buttonInfo << "Available buttons in state " << static_cast<int>(currentState) << ":";
Logger::debug(buttonInfo.str(), "GUI");
for (size_t i = 0; i < buttons.size(); i++)
{
auto &button = buttons[i];
sf::Vector2f pos = button->getPosition();
sf::Vector2f size = button->getSize();
std::stringstream ss;
ss << "Button " << i << ": '" << button->getText() << "' at ("
<< pos.x << ", " << pos.y << ") size (" << size.x << ", " << size.y << ")";
ss << " - Contains mouse: " << (button->contains(mousePos) ? "YES" : "NO");
Logger::debug(ss.str(), "GUI");
}
// Check button clicks
bool buttonClicked = false;
for (auto &button : buttons)
{
if (button->contains(mousePos))
{
button->setPressed(true);
buttonClicked = true;
// Handle button actions
string buttonText = button->getText();
Logger::info("Button clicked: '" + buttonText + "' in state: " + std::to_string(static_cast<int>(currentState)), "GUI");
if (buttonText == "Back" || buttonText == "← Back")
{
Logger::info("Navigating back to main menu", "GUI");
setState(AppState::MAIN_MENU);
break;
}
else if (buttonText == "Add Transaction" && currentState == AppState::MAIN_MENU)
{
setState(AppState::ADD_TRANSACTION);
break;
}
else if ((buttonText == "Mine Block" || buttonText == "⛏ Mine Block") && currentState == AppState::MAIN_MENU)
{
setState(AppState::MINE_BLOCK);
break;
}
else if ((buttonText == "Mine Block" || buttonText == "⛏ Mine Block") && currentState == AppState::MINE_BLOCK)
{
// Perform mining
blockchain->mineBlock();
setStatusMessage("Block mined successfully!", false);
break;
}
else if (buttonText == "View Blockchain")
{
setState(AppState::VIEW_BLOCKCHAIN);
break;
}
else if (buttonText == "Transaction Pool")
{
setState(AppState::VIEW_TRANSACTIONS);
break;
}
else if (buttonText == "Check Balance" && currentState == AppState::MAIN_MENU)
{
setState(AppState::CHECK_BALANCE);
break;
}
else if (buttonText == "Statistics")
{
setState(AppState::STATISTICS);
break;
}
else if (buttonText == "Settings")
{
setState(AppState::SETTINGS);
break;
}
else if (buttonText == "Exit")
{
window.close();
break;
}
else if (buttonText == "Add Transaction" && currentState == AppState::ADD_TRANSACTION)
{
// Process transaction
if (inputFields.size() >= 3)
{
string from = inputFields[0]->getValue();
string to = inputFields[1]->getValue();
string amountStr = inputFields[2]->getValue();
if (!from.empty() && !to.empty() && !amountStr.empty())
{
try
{
double amount = stod(amountStr);
Transaction tx(from, to, amount);
blockchain->addTransaction(tx);
setStatusMessage("Transaction added successfully!", false);
clearInputFields();
}
catch (const exception &e)
{
setStatusMessage("Invalid amount!", true);
}
}
else
{
setStatusMessage("Please fill all fields!", true);
}
}
break;
}
else if ((buttonText == "Check" || buttonText == "Check Balance") && currentState == AppState::CHECK_BALANCE)
{
if (!inputFields.empty())
{
string address = inputFields[0]->getValue();
if (!address.empty())
{
double balance = blockchain->getBalance(address);
setStatusMessage("Balance: " + to_string(balance), false);
}
else
{
setStatusMessage("Please enter an address!", true);
}
}
break;
}
else if ((buttonText == "Mine Block" || buttonText == "⛏ Mine Block") && currentState == AppState::MINE_BLOCK)
{
// Start mining process
try
{
// Check if there are transactions to mine
if (blockchain->getTransactionPool().empty())
{
setStatusMessage("No transactions to mine! Add some transactions first.", true);
break;
}
setStatusMessage("Mining block... Please wait.", false);
sf::Clock miningClock;
miningClock.restart();
blockchain->mineBlock();
float miningTime = miningClock.getElapsedTime().asMilliseconds();
setStatusMessage("Block mined successfully in " + to_string((int)miningTime) + "ms! Click Back to return.", false);
}
catch (const exception &e)
{
setStatusMessage("Mining failed: " + string(e.what()), true);
}
break;
}
else if (buttonText == "Apply Settings" && currentState == AppState::SETTINGS)
{
// Apply difficulty and reward settings
if (inputFields.size() >= 2)
{
string diffStr = inputFields[0]->getValue();
string rewardStr = inputFields[1]->getValue();
try
{
if (!diffStr.empty())
{
int newDifficulty = stoi(diffStr);
blockchain->setDifficulty(newDifficulty);
}
if (!rewardStr.empty())
{
double newReward = stod(rewardStr);
blockchain->setMiningReward(newReward);
}
setStatusMessage("Settings applied successfully!", false);
clearInputFields();
}
catch (const exception &e)
{
setStatusMessage("Invalid values! Use numbers only.", true);
}
}
break;
}
else if ((buttonText == "Reset" || buttonText == "Reset Defaults") && currentState == AppState::SETTINGS)
{
// Reset to default values
blockchain->setDifficulty(1);
blockchain->setMiningReward(10.0);
// Update input fields to show new values
if (inputFields.size() >= 2)
{
inputFields[0]->setValue(to_string(blockchain->getDifficulty()));
inputFields[1]->setValue(to_string(blockchain->getMiningReward()));
}
setStatusMessage("Settings reset to defaults!", false);
break;
}
break; // Exit the button loop after handling one button
}
}
// Only check input field clicks if no button was clicked
if (!buttonClicked)
{
for (auto &field : inputFields)
{
field->setActive(field->contains(mousePos));
}
}
}
break;
case sf::Event::MouseButtonReleased:
if (event.mouseButton.button == sf::Mouse::Left)
{
for (auto &button : buttons)
{
button->setPressed(false);
}
}
break;
case sf::Event::MouseMoved:
{
sf::Vector2f mousePos(static_cast<float>(event.mouseMove.x), static_cast<float>(event.mouseMove.y));
for (auto &button : buttons)
{
button->setHovered(button->contains(mousePos));
}
}
break;
case sf::Event::TextEntered:
handleTextInput(event.text.unicode);
break;
case sf::Event::KeyPressed:
if (event.key.code == sf::Keyboard::Return)
{
// Handle enter key for quick actions
}
else if (event.key.code == sf::Keyboard::Escape)
{
if (currentState != AppState::MAIN_MENU)
{
setState(AppState::MAIN_MENU);
}
}
else if (event.key.code == sf::Keyboard::Backspace)
{
for (auto &field : inputFields)
{
if (field->getIsActive())
{
field->removeCharacter();
}
}
}
break;
case sf::Event::MouseWheelScrolled:
if (currentState == AppState::VIEW_BLOCKCHAIN)
{
scrollOffset += event.mouseWheelScroll.delta * 20;
scrollOffset = max(0.0f, scrollOffset);
}
break;
}
}
}
void BlockchainGUI::handleTextInput(sf::Uint32 unicode)
{
if (unicode >= 32 && unicode < 127)
{ // Printable ASCII characters
for (auto &field : inputFields)
{
if (field->getIsActive())
{
field->addCharacter(static_cast<char>(unicode));
break;
}
}
}
}
void BlockchainGUI::update(float deltaTime)
{
animationTime += deltaTime;
// Update status message timer
if (statusTimer > 0)
{
statusTimer -= deltaTime;
if (statusTimer <= 0)
{
statusMessage.clear();
}
}
// Handle mining block state - removed auto-mining logic
// Mining is now handled by button click
}
void BlockchainGUI::render()
{
window.clear(backgroundColor);
// Render based on current state
switch (currentState)
{
case AppState::MAIN_MENU:
renderMainMenu();
break;
case AppState::ADD_TRANSACTION:
renderAddTransaction();
break;
case AppState::MINE_BLOCK:
renderMineBlock();
break;
case AppState::VIEW_BLOCKCHAIN:
renderBlockchain();
break;
case AppState::VIEW_TRANSACTIONS:
renderTransactions();
break;
case AppState::CHECK_BALANCE:
renderCheckBalance();
break;
case AppState::STATISTICS:
renderStatistics();
break;
case AppState::SETTINGS:
renderSettings();
break;
}
// Render status message
if (!statusMessage.empty() && statusTimer > 0)
{
drawText(statusMessage, sf::Vector2f(600, 750), 18, statusColor, true);
}
window.display();
}
void BlockchainGUI::renderMainMenu()
{
// Title with modern styling
sf::Text titleText("AlgoChain", font, 54);
titleText.setFillColor(accentColor);
titleText.setStyle(sf::Text::Bold);
sf::FloatRect titleBounds = titleText.getLocalBounds();
titleText.setPosition((1200 - titleBounds.width) / 2, 40);
window.draw(titleText);
// Subtitle
sf::Text subtitleText("Blockchain Simulation", font, 22);
subtitleText.setFillColor(textColor);
subtitleText.setStyle(sf::Text::Italic);
sf::FloatRect subtitleBounds = subtitleText.getLocalBounds();
subtitleText.setPosition((1200 - subtitleBounds.width) / 2, 100);
window.draw(subtitleText);
// Decorative line under title
sf::RectangleShape line(sf::Vector2f(400, 3));
line.setPosition(400, 135);
line.setFillColor(accentColor);
window.draw(line);
// Stats overview with better styling
string stats = "\u26d3 Blocks: " + to_string(blockchain->getChainLength()) +
" | \u2699 Difficulty: " + to_string(blockchain->getDifficulty());
sf::Text statsText(stats, font, 16);
statsText.setFillColor(sf::Color(189, 195, 199)); // Light grey
sf::FloatRect statsBounds = statsText.getLocalBounds();
statsText.setPosition((1200 - statsBounds.width) / 2, 145);
window.draw(statsText);
// Render buttons
for (auto &button : buttons)
{
drawButton(button->getPosition(), button->getSize(), button->getText(),
button->getIsHovered(), button->getIsPressed());
}
}
void BlockchainGUI::renderAddTransaction()
{
// Title with icon
sf::Text titleText("\u2699 Add New Transaction", font, 38);
titleText.setFillColor(accentColor);
titleText.setStyle(sf::Text::Bold);
sf::FloatRect titleBounds = titleText.getLocalBounds();
titleText.setPosition((1200 - titleBounds.width) / 2, 80);
window.draw(titleText);
// Decorative line
sf::RectangleShape line(sf::Vector2f(350, 3));
line.setPosition(425, 130);
line.setFillColor(accentColor);
window.draw(line);
// Instructions
sf::Text instructionText("Fill in the details below to create a new transaction", font, 14);
instructionText.setFillColor(sf::Color(149, 165, 166));
sf::FloatRect instrBounds = instructionText.getLocalBounds();
instructionText.setPosition((1200 - instrBounds.width) / 2, 145);
window.draw(instructionText);
// Render input fields
for (auto &field : inputFields)
{
drawInputField(field->getPosition(), field->getSize(), field->getLabel(),
field->getValue(), field->getIsActive());
}
// Render buttons
for (auto &button : buttons)
{
drawButton(button->getPosition(), button->getSize(), button->getText(),
button->getIsHovered(), button->getIsPressed());
}
}
void BlockchainGUI::renderMineBlock()
{
// Title with icon
sf::Text titleText("\u26cf Mine New Block", font, 38);
titleText.setFillColor(accentColor);
titleText.setStyle(sf::Text::Bold);
sf::FloatRect titleBounds = titleText.getLocalBounds();
titleText.setPosition((1200 - titleBounds.width) / 2, 120);
window.draw(titleText);
// Decorative line
sf::RectangleShape line(sf::Vector2f(300, 3));
line.setPosition(450, 170);
line.setFillColor(accentColor);
window.draw(line);
// Show pending transactions count
int pendingCount = blockchain->getTransactionPool().size();
// Info panel background
sf::RectangleShape infoPanel(sf::Vector2f(500, 120));
infoPanel.setPosition(350, 210);
infoPanel.setFillColor(sf::Color(52, 73, 94));
infoPanel.setOutlineThickness(2);
infoPanel.setOutlineColor(primaryColor);
window.draw(infoPanel);
// Pending transactions info
sf::Text pendingLabel("Pending Transactions:", font, 18);
pendingLabel.setFillColor(textColor);
pendingLabel.setStyle(sf::Text::Bold);
pendingLabel.setPosition(380, 230);
window.draw(pendingLabel);
sf::Text pendingValue(to_string(pendingCount), font, 32);
pendingValue.setFillColor(pendingCount > 0 ? successColor : errorColor);
pendingValue.setStyle(sf::Text::Bold);
pendingValue.setPosition(600, 260);
window.draw(pendingValue);
if (pendingCount == 0)
{
sf::Text warningText("\u26a0 Add some transactions before mining!", font, 16);
warningText.setFillColor(errorColor);
sf::FloatRect warnBounds = warningText.getLocalBounds();
warningText.setPosition((1200 - warnBounds.width) / 2, 290);
window.draw(warningText);
}
else
{
sf::Text readyText("\u2713 Ready to mine a new block", font, 16);
readyText.setFillColor(successColor);
sf::FloatRect readyBounds = readyText.getLocalBounds();
readyText.setPosition((1200 - readyBounds.width) / 2, 290);
window.draw(readyText);
}
// Show current difficulty
sf::Text diffText("Mining Difficulty: " + to_string(blockchain->getDifficulty()), font, 14);
diffText.setFillColor(sf::Color(149, 165, 166));
sf::FloatRect diffBounds = diffText.getLocalBounds();
diffText.setPosition((1200 - diffBounds.width) / 2, 315);
window.draw(diffText);
// Render buttons
for (auto &button : buttons)
{
drawButton(button->getPosition(), button->getSize(), button->getText(),
button->getIsHovered(), button->getIsPressed());
}
// Show status message if any
if (!statusMessage.empty())
{
drawText(statusMessage, sf::Vector2f(600, 500), 18, statusColor, true);
}
}
void BlockchainGUI::renderBlockchain()
{
drawText("Blockchain Explorer", sf::Vector2f(600, 30), 36, primaryColor, true);
string chainInfo = "Total Blocks: " + to_string(blockchain->getChainLength()) +
" | Valid: " + (blockchain->isChainValid() ? "Yes" : "No");
drawText(chainInfo, sf::Vector2f(600, 70), 16, textColor, true);
// Render blockchain
float yPos = 100 - scrollOffset;
float blockWidth = 1100;
float blockHeight = 150;
for (int i = 0; i < blockchain->getChainLength(); i++)
{
if (yPos > -blockHeight && yPos < 800)
{
const Block &block = blockchain->getBlock(i);
drawBlock(block, sf::Vector2f(50, yPos), blockWidth);
}
yPos += blockHeight + 20;
}
// Scroll instruction
if (blockchain->getChainLength() > 4)
{
drawText("Use mouse wheel to scroll", sf::Vector2f(600, 750), 14, textColor, true);
}
// Render back button
for (auto &button : buttons)
{
drawButton(button->getPosition(), button->getSize(), button->getText(),
button->getIsHovered(), button->getIsPressed());
}
}
void BlockchainGUI::renderTransactions()
{
drawText("Transaction Pool", sf::Vector2f(600, 50), 36, primaryColor, true);
const vector<Transaction> &txPool = blockchain->getTransactionPool();
string poolInfo = "Pending Transactions: " + to_string(txPool.size());
drawText(poolInfo, sf::Vector2f(600, 90), 18, textColor, true);
if (txPool.empty())
{
drawText("No pending transactions", sf::Vector2f(600, 300), 20, textColor, true);
drawText("Add some transactions to see them here", sf::Vector2f(600, 330), 16, textColor, true);
}
else
{
float yPos = 150;
float txWidth = 1100;
float txHeight = 80;
for (size_t i = 0; i < txPool.size() && i < 8; i++)
{
drawTransaction(txPool[i], sf::Vector2f(50, yPos), txWidth);
yPos += txHeight + 10;
}
if (txPool.size() > 8)
{
drawText("... and " + to_string(txPool.size() - 8) + " more",
sf::Vector2f(600, yPos), 16, textColor, true);
}
}
// Render back button
for (auto &button : buttons)
{
drawButton(button->getPosition(), button->getSize(), button->getText(),
button->getIsHovered(), button->getIsPressed());
}
}
void BlockchainGUI::renderCheckBalance()
{
drawText("Check Balance", sf::Vector2f(600, 100), 36, primaryColor, true);
// Render input fields
for (auto &field : inputFields)
{
drawInputField(field->getPosition(), field->getSize(), field->getLabel(),
field->getValue(), field->getIsActive());
}
// Render buttons
for (auto &button : buttons)
{
drawButton(button->getPosition(), button->getSize(), button->getText(),
button->getIsHovered(), button->getIsPressed());
}
}
void BlockchainGUI::renderStatistics()
{
drawText("Blockchain Statistics", sf::Vector2f(600, 100), 36, primaryColor, true);
float yPos = 200;
string stats[] = {
"Total Blocks: " + to_string(blockchain->getChainLength()),
"Mining Difficulty: " + to_string(blockchain->getDifficulty()),
"Mining Reward: " + to_string(blockchain->getMiningReward()),
"Chain Valid: " + string(blockchain->isChainValid() ? "Yes" : "No")};
for (const string &stat : stats)
{
drawText(stat, sf::Vector2f(100, yPos), 20, textColor);
yPos += 40;
}
// Render back button
for (auto &button : buttons)
{
drawButton(button->getPosition(), button->getSize(), button->getText(),
button->getIsHovered(), button->getIsPressed());
}
}
void BlockchainGUI::renderSettings()
{
drawText("Blockchain Settings", sf::Vector2f(600, 100), 36, primaryColor, true);
// Show current settings
float yPos = 180;
stringstream rewardStream;
rewardStream << fixed << setprecision(1) << blockchain->getMiningReward();
string currentSettings[] = {
"Current Difficulty: " + to_string(blockchain->getDifficulty()) + " (1-6 range)",
"Current Mining Reward: " + rewardStream.str() + " coins"};
for (const string &setting : currentSettings)
{
drawText(setting, sf::Vector2f(100, yPos), 18, textColor);
yPos += 30;
}
// Render input fields
for (auto &field : inputFields)
{
drawInputField(field->getPosition(), field->getSize(), field->getLabel(),
field->getValue(), field->getIsActive());
}
// Instructions
drawText("Enter new values and click 'Apply Settings'", sf::Vector2f(600, 380), 16, textColor, true);
drawText("Higher difficulty = more secure but slower mining", sf::Vector2f(600, 560), 14, textColor, true);
drawText("Difficulty 1-2: Fast | 3-4: Moderate | 5-6: Slow", sf::Vector2f(600, 580), 14, textColor, true);
// Render buttons
for (auto &button : buttons)
{
drawButton(button->getPosition(), button->getSize(), button->getText(),
button->getIsHovered(), button->getIsPressed());
}
}
// UI Helper Functions
void BlockchainGUI::drawButton(const sf::Vector2f &position, const sf::Vector2f &size,
const string &text, bool isHovered, bool isPressed)
{
// Draw shadow for depth effect
sf::RectangleShape shadow(size);
shadow.setPosition(position.x + 3, position.y + 3);
shadow.setFillColor(sf::Color(0, 0, 0, 80));
window.draw(shadow);
// Draw main button
sf::RectangleShape button(size);
button.setPosition(position);
if (isPressed)
{
button.setFillColor(sf::Color(primaryColor.r * 0.7f, primaryColor.g * 0.7f, primaryColor.b * 0.7f));
}
else if (isHovered)
{
button.setFillColor(accentColor);
}
else
{
button.setFillColor(primaryColor);
}
button.setOutlineThickness(2);
button.setOutlineColor(isHovered ? sf::Color(255, 255, 255, 150) : secondaryColor);
window.draw(button);
// Draw text
sf::Text buttonText(text, font, 18);
buttonText.setFillColor(sf::Color::White);
buttonText.setStyle(sf::Text::Bold);
sf::FloatRect textBounds = buttonText.getLocalBounds();
buttonText.setPosition(
position.x + (size.x - textBounds.width) / 2,
position.y + (size.y - textBounds.height) / 2 - 5);
window.draw(buttonText);
}
void BlockchainGUI::drawInputField(const sf::Vector2f &position, const sf::Vector2f &size,
const string &label, const string &value, bool isActive)
{
// Draw label with better styling
sf::Text labelText(label, font, 16);
labelText.setFillColor(textColor);
labelText.setStyle(sf::Text::Bold);
labelText.setPosition(position.x, position.y - 35);
window.draw(labelText);
// Draw input box shadow
sf::RectangleShape shadow(size);
shadow.setPosition(position.x + 2, position.y + 2);
shadow.setFillColor(sf::Color(0, 0, 0, 100));
window.draw(shadow);
// Draw input box
sf::RectangleShape inputBox(size);
inputBox.setPosition(position);
inputBox.setFillColor(sf::Color(52, 73, 94)); // Darker blue-grey
inputBox.setOutlineThickness(2);
inputBox.setOutlineColor(isActive ? accentColor : sf::Color(100, 120, 140));
window.draw(inputBox);
// Draw text
sf::Text inputText(value, font, 16);
inputText.setFillColor(sf::Color::White);
inputText.setPosition(position.x + 10, position.y + 12);
window.draw(inputText);
// Draw cursor if active with animation
if (isActive)
{
float cursorX = position.x + 10 + inputText.getLocalBounds().width + 2;
sf::RectangleShape cursor(sf::Vector2f(2, size.y - 14));
cursor.setPosition(cursorX, position.y + 7);
cursor.setFillColor(accentColor);
if (fmod(animationTime, 1.0f) < 0.5f)
{
window.draw(cursor);
}
}
}
void BlockchainGUI::drawPanel(const sf::Vector2f &position, const sf::Vector2f &size)
{
sf::RectangleShape panel(size);
panel.setPosition(position);
panel.setFillColor(sf::Color(50, 50, 50, 200));
panel.setOutlineThickness(1);
panel.setOutlineColor(secondaryColor);
window.draw(panel);
}
void BlockchainGUI::drawText(const string &text, const sf::Vector2f &position,
int fontSize, sf::Color color, bool centered)
{
sf::Text sfText(text, font, fontSize);
sfText.setFillColor(color);
if (centered)
{
sf::FloatRect textBounds = sfText.getLocalBounds();
sfText.setPosition(position.x - textBounds.width / 2, position.y);
}
else
{
sfText.setPosition(position);
}
window.draw(sfText);
}
void BlockchainGUI::clearInputFields()
{
for (auto &field : inputFields)
{
field->clear();
}
}
void BlockchainGUI::setStatusMessage(const string &message, bool isError)
{
statusMessage = message;
statusColor = isError ? errorColor : successColor;
statusTimer = 3.0f; // Show for 3 seconds
}
void BlockchainGUI::setState(AppState newState)
{
currentState = newState;
scrollOffset = 0;
initializeUI();
}
// Button Implementation
Button::Button(const sf::Vector2f &pos, const sf::Vector2f &sz, const string &txt)
: position(pos), size(sz), text(txt), isHovered(false), isPressed(false)
{
}
bool Button::contains(const sf::Vector2f &point) const
{
return point.x >= position.x && point.x <= position.x + size.x &&
point.y >= position.y && point.y <= position.y + size.y;
}
void Button::setHovered(bool hovered)
{
isHovered = hovered;
}