forked from simulationcraft/simc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsc_window.cpp
1555 lines (1381 loc) · 49.3 KB
/
sc_window.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ==========================================================================
// Dedmonwakeen's Raid DPS/TPS Simulator.
// Send questions to [email protected]
// ==========================================================================
#include "simulationcraft.hpp"
#include "simulationcraftqt.hpp"
#include "sc_OptionsTab.hpp"
#include "sc_SpellQueryTab.hpp"
#include "sc_SimulationThread.hpp"
#include "sc_SampleProfilesTab.hpp"
#include "sc_SimulateTab.hpp"
#include "sc_WelcomeTab.hpp"
#include "sc_AddonImportTab.hpp"
#include "util/sc_mainwindowcommandline.hpp"
#include "util/git_info.hpp"
#if defined( Q_OS_MAC )
#include <CoreFoundation/CoreFoundation.h>
#endif
#include <QStandardPaths>
#include <QDateTime>
namespace { // UNNAMED NAMESPACE
constexpr int SC_GUI_HISTORY_VERSION = 801;
#if ! defined( SC_USE_WEBKIT )
struct HtmlOutputFunctor
{
QString fname;
HtmlOutputFunctor(const QString& fn) : fname( fn )
{ }
void operator()( QString htmlOutput )
{
QFile file( fname );
if (file.open(QIODevice::WriteOnly | QIODevice::Text))
{
QByteArray out_utf8 = htmlOutput.toUtf8();
qint64 ret = file.write(out_utf8);
file.close();
assert(ret == htmlOutput.size());
(void)ret;
}
}
};
#endif
} // UNNAMED NAMESPACE
// ==========================================================================
// SC_PATHS
// ==========================================================================
QString SC_PATHS::getDataPath()
{
#if defined( Q_OS_WIN )
return QCoreApplication::applicationDirPath();
#elif defined( Q_OS_MAC )
return QCoreApplication::applicationDirPath() + "/../Resources";
#else
#if !defined( SC_TO_INSTALL )
return QCoreApplication::applicationDirPath();
#else
QString shared_path;
QStringList appdatalocation = QStandardPaths::standardLocations( QStandardPaths::DataLocation );
for( int i = 0; i < appdatalocation.size(); ++i )
{
QDir dir( appdatalocation[ i ]);
if ( dir.exists() )
{
shared_path = dir.path();
break;
}
}
return shared_path;
#endif
#endif
}
// ==========================================================================
// SC_MainWindow
// ==========================================================================
void SC_MainWindow::updateSimProgress()
{
std::string progressBarToolTip;
if ( simRunning() )
{
simProgress = static_cast<int>( 100.0 * sim -> progress( simPhase, &progressBarToolTip ) );
}
if ( importRunning() )
{
importSimProgress = static_cast<int>( 100.0 * import_sim -> progress( importSimPhase, &progressBarToolTip ) );
if ( soloChar -> isActive() && importSimProgress == 0 )
{
soloimport += 2;
importSimProgress = static_cast<int>( std::min( soloimport, 100 ) );
}
}
#if !defined( SC_WINDOWS ) && !defined( SC_OSX )
// Progress bar text in Linux is displayed inside the progress bar as opposed next to it in Windows
// so it does not look as bad to include iteration details in it
if ( simPhase.find( ": " ) == std::string::npos ) // can end up with Simulating: : : : : : : in rare circumstances
{
simPhase += ": ";
simPhase += progressBarToolTip;
}
#endif
cmdLine -> setSimulatingProgress( simProgress, QString::fromStdString(simPhase), QString::fromStdString(progressBarToolTip) );
cmdLine -> setImportingProgress( importSimProgress, QString::fromStdString(importSimPhase), QString::fromStdString(progressBarToolTip) );
}
void SC_MainWindow::loadHistory()
{
QSettings settings;
QString saveApiKey;
saveApiKey = settings.value( "options/apikey" ).toString();
QVariant simulateHistory = settings.value( "user_data/simulateHistory" );
if ( simulateHistory.isValid() )
{
for ( auto& entry : simulateHistory.toList() )
{
if ( entry.isValid() )
{
QStringList sl = entry.toStringList();
if ( sl.size() == 2 )
{
simulateTab -> add_Text( sl.at( 1 ), sl.at( 0 ) );
}
}
}
}
int gui_version_number = settings.value( "gui/gui_version_number", 0 ).toInt();
if ( gui_version_number < SC_GUI_HISTORY_VERSION )
{
settings.clear();
settings.setValue( "options/apikey", saveApiKey );
QMessageBox::information( this, tr("GUI settings reset"),
tr("We have reset your configuration settings due to major changes to the GUI") );
}
QVariant size = settings.value( "gui/size" );
QRect savedApplicationGeometry = geometry();
if ( size.isValid() )
{
savedApplicationGeometry.setSize( size.toSize() );
}
QVariant pos = settings.value( "gui/position" );
if ( pos.isValid() )
{
savedApplicationGeometry.moveTopLeft( pos.toPoint() );
}
QVariant maximized = settings.value( "gui/maximized" );
if ( maximized.isValid() )
{
if ( maximized.toBool() )
showMaximized();
else
showNormal();
}
else
showMaximized();
QString cache_file = QDir::toNativeSeparators( TmpDir + "/simc_cache.dat" );
http::cache_load( cache_file.toStdString() );
optionsTab -> decodeOptions();
spellQueryTab -> decodeSettings();
if ( simulateTab -> count() <= 1 )
{ // If we haven't retrieved any simulate tabs from history, add a default one.
simulateTab -> add_Text( defaultSimulateText, tr("Simulate!") );
}
}
void SC_MainWindow::saveHistory()
{
QSettings settings;
settings.beginGroup( "gui" );
settings.setValue( "gui_version_number", SC_GUI_HISTORY_VERSION );
settings.setValue( "size", normalGeometry().size() );
settings.setValue( "position", normalGeometry().topLeft() );
settings.setValue( "maximized", bool( windowState() & Qt::WindowMaximized ) );
settings.endGroup();
QString cache_file = QDir::toNativeSeparators( TmpDir + "/simc_cache.dat" );
http::cache_save( cache_file.toStdString() );
settings.beginGroup( "user_data" );
// simulate tab history
QList< QVariant > simulateHist;
for ( int i = 0; i < simulateTab -> count() - 1; ++i )
{
SC_TextEdit* tab = static_cast<SC_TextEdit*>( simulateTab -> widget( i ) );
QStringList entry;
entry << simulateTab -> tabText( i );
entry << tab -> toPlainText();
simulateHist.append( QVariant( entry ) );
}
settings.setValue( "simulateHistory", simulateHist );
settings.endGroup();// end user_data
optionsTab -> encodeOptions();
spellQueryTab -> encodeSettings();
}
// ==========================================================================
// Widget Creation
// ==========================================================================
SC_MainWindow::SC_MainWindow( QWidget *parent )
: QWidget( parent ),
visibleWebView(),
cmdLine(),
recentlyClosedTabModel(),
sim(),
import_sim(),
simPhase( "%p%" ),
importSimPhase( "%p%" ),
simProgress( 100 ),
importSimProgress( 100 ),
soloimport( 0 ),
simResults( 0 ),
AppDataDir( "." ),
ResultsDestDir( "." ),
TmpDir( "." ),
consecutiveSimulationsRun( 0 )
{
setWindowTitle( QCoreApplication::applicationName() + " " + QCoreApplication::applicationVersion() + " " + webEngineName());
setAttribute( Qt::WA_AlwaysShowToolTips );
#if defined( Q_OS_WIN )
AppDataDir = QCoreApplication::applicationDirPath();
#else
QStringList q = QStandardPaths::standardLocations( QStandardPaths::AppDataLocation );
assert( !q.isEmpty() );
AppDataDir = q.first();
QDir::home().mkpath( AppDataDir );
#endif
QStringList s = QStandardPaths::standardLocations( QStandardPaths::CacheLocation );
assert( !s.isEmpty() );
TmpDir = s.first();
// Set ResultsDestDir
s = QStandardPaths::standardLocations( QStandardPaths::DocumentsLocation );
assert( !s.isEmpty() );
ResultsDestDir = s.first();
logFileText = QDir::toNativeSeparators( AppDataDir + "/log.txt" );
resultsFileText = QDir::toNativeSeparators( AppDataDir + "/results.html" );
mainTab = new SC_MainTab( this );
createWelcomeTab();
createImportTab();
createOptionsTab();
createSimulateTab();
createResultsTab();
createOverridesTab();
createHelpTab();
createLogTab();
createSpellQueryTab();
createCmdLine();
#if defined( Q_OS_MAC )
createTabShortcuts();
#endif
connect( mainTab, SIGNAL( currentChanged( int ) ), this, SLOT( mainTabChanged( int ) ) );
QVBoxLayout* vLayout = new QVBoxLayout();
vLayout -> addWidget( mainTab, 1 );
vLayout -> addWidget( cmdLine, 0 );
setLayout( vLayout );
vLayout -> activate();
soloChar = new QTimer( this );
connect( soloChar, SIGNAL( timeout() ), this, SLOT( updatetimer() ) );
timer = new QTimer( this );
connect( timer, SIGNAL( timeout() ), this, SLOT( updateSimProgress() ) );
importThread = new SC_ImportThread( this );
connect( importThread, SIGNAL( finished() ), this, SLOT( importFinished() ) );
simulateThread = new SC_SimulateThread( this );
connect( simulateThread, &SC_SimulateThread::simulationFinished, this, &SC_MainWindow::simulateFinished );
setAcceptDrops( true );
loadHistory();
#if defined( Q_OS_MAC ) || defined( VS_NEW_BUILD_SYSTEM )
new BattleNetImportWindow( this );
#endif /* Q_OS_MAC || VS_NEW_BUILD_SYSTEM */
}
void SC_MainWindow::createCmdLine()
{
cmdLine = new SC_MainWindowCommandLine( this );
connect( &simulationQueue, SIGNAL( firstItemWasAdded() ), this, SLOT( itemWasEnqueuedTryToSim() ) );
connect( cmdLine, SIGNAL( pauseClicked() ), this, SLOT( pauseButtonClicked() ) );
connect( cmdLine, SIGNAL( resumeClicked() ), this, SLOT( pauseButtonClicked() ) );
connect( cmdLine, SIGNAL( backButtonClicked() ), this, SLOT( backButtonClicked() ) );
connect( cmdLine, SIGNAL( forwardButtonClicked() ), this, SLOT( forwardButtonClicked() ) );
connect( cmdLine, SIGNAL( simulateClicked() ), this, SLOT( enqueueSim() ) );
connect( cmdLine, SIGNAL( queueClicked() ), this, SLOT( enqueueSim() ) );
connect( cmdLine, SIGNAL( queryClicked() ), this, SLOT( queryButtonClicked() ) );
connect( cmdLine, SIGNAL( importClicked() ), this, SLOT( importButtonClicked() ) );
connect( cmdLine, SIGNAL( saveLogClicked() ), this, SLOT( saveLog() ) );
connect( cmdLine, SIGNAL( saveResultsClicked() ), this, SLOT( saveResults() ) );
connect( cmdLine, SIGNAL( cancelSimulationClicked() ), this, SLOT( stopSim() ) );
connect( cmdLine, SIGNAL( cancelAllSimulationClicked() ), this, SLOT( stopAllSim() ) );
connect( cmdLine, SIGNAL( cancelImportClicked() ), this, SLOT( stopImport() ) );
connect( cmdLine, SIGNAL( commandLineReturnPressed() ), this, SLOT( cmdLineReturnPressed() ) );
connect( cmdLine, SIGNAL( commandLineTextEdited( const QString& ) ), this, SLOT( cmdLineTextEdited( const QString& ) ) );
connect( cmdLine, SIGNAL( switchToLeftSubTab() ), this, SLOT( switchToLeftSubTab() ) );
connect( cmdLine, SIGNAL( switchToRightSubTab() ), this, SLOT( switchToRightSubTab() ) );
connect( cmdLine, SIGNAL( currentlyViewedTabCloseRequest() ), this, SLOT( currentlyViewedTabCloseRequest() ) );
}
void SC_MainWindow::createWelcomeTab()
{
mainTab -> addTab( new SC_WelcomeTabWidget( this ), tr( "Welcome" ) );
}
void SC_MainWindow::createOptionsTab()
{
optionsTab = new SC_OptionsTab( this );
mainTab -> addTab( optionsTab, tr( "Options" ) );
connect( optionsTab, SIGNAL( armory_region_changed( const QString& ) ),
newBattleNetView -> widget(), SLOT( armoryRegionChangedIn( const QString& ) ) );
connect( newBattleNetView -> widget(), SIGNAL( armoryRegionChangedOut( const QString& ) ),
optionsTab, SLOT( _armoryRegionChanged( const QString& ) ) );
}
void SC_MainWindow::createImportTab()
{
importTab = new SC_ImportTab( this );
mainTab -> addTab( importTab, tr( "Import" ) );
newBattleNetView = new BattleNetImportWindow( this, true );
importTab -> addTab( newBattleNetView, tr( "Battle.net" ) );
importTab -> addTab( importTab -> addonTab, tr("Simc Addon") );
SC_SampleProfilesTab* bisTab = new SC_SampleProfilesTab( this );
connect( bisTab -> tree, SIGNAL( itemDoubleClicked( QTreeWidgetItem*, int ) ), this, SLOT( bisDoubleClicked( QTreeWidgetItem*, int ) ) );
importTab -> addTab( bisTab, tr( "Sample Profiles" ) );
recentlyClosedTabImport = new SC_RecentlyClosedTabWidget( this, QBoxLayout::LeftToRight );
recentlyClosedTabModel = recentlyClosedTabImport -> getModel();
importTab -> addTab( recentlyClosedTabImport, tr( "Recently Closed" ) );
connect(recentlyClosedTabImport, SIGNAL(restoreTab(QWidget*, const QString&, const QString&, const QIcon&)),
this, SLOT(simulateTabRestored(QWidget*, const QString&, const QString&, const QIcon&)));
connect(importTab, SIGNAL(currentChanged(int)), this, SLOT(importTabChanged(int)));
// Commenting out until it is more fleshed out.
// createCustomTab();
}
void SC_MainWindow::createCustomTab()
{
//In Dev - Character Retrieval Boxes & Buttons
//In Dev - Load & Save Profile Buttons
//In Dev - Profiler Slots, Talent Layout
QHBoxLayout* customLayout = new QHBoxLayout();
QGroupBox* customGroupBox = new QGroupBox();
customGroupBox -> setLayout( customLayout );
importTab -> addTab( customGroupBox, tr("Custom Profile") );
customLayout -> addWidget( createCustomCharData = new QGroupBox( tr( "Character Data" ) ), 1 );
createCustomCharData -> setObjectName( QString::fromUtf8( "createCustomCharData" ) );
customLayout -> addWidget( createCustomProfileDock = new QTabWidget(), 1 );
createCustomProfileDock -> setObjectName( QString::fromUtf8( "createCustomProfileDock" ) );
createCustomProfileDock -> setAcceptDrops( true );
customGearTab = new QWidget();
customGearTab -> setObjectName( QString::fromUtf8( "customGearTab" ) );
createCustomProfileDock -> addTab( customGearTab, QString() );
customTalentsTab = new QWidget();
customTalentsTab -> setObjectName( QString::fromUtf8( "customTalentsTab" ) );
createCustomProfileDock -> addTab( customTalentsTab, QString() );
createCustomProfileDock -> setTabText( createCustomProfileDock -> indexOf( customGearTab ), tr( "Gear", "createCustomTab" ) );
createCustomProfileDock -> setTabToolTip( createCustomProfileDock -> indexOf( customGearTab ), tr( "Customize Gear Setup", "createCustomTab" ) );
createCustomProfileDock -> setTabText( createCustomProfileDock -> indexOf( customTalentsTab ), tr( "Talents", "createCustomTab" ) );
createCustomProfileDock -> setTabToolTip( createCustomProfileDock -> indexOf( customTalentsTab ), tr( "Customize Talents", "createCustomTab" ) );
}
void SC_MainWindow::createSimulateTab()
{
simulateTab = new SC_SimulateTab( mainTab, recentlyClosedTabModel );
mainTab -> addTab( simulateTab, tr( "Simulate" ) );
}
void SC_MainWindow::createOverridesTab()
{
overridesText = new SC_OverridesTab( this );
mainTab -> addTab( overridesText, tr( "Overrides" ) );
}
void SC_MainWindow::createLogTab()
{
logText = new SC_TextEdit( this, false );
logText -> setReadOnly( true );
logText -> setPlainText( tr("Look here for error messages and simple text-only reporting.\n") );
mainTab -> addTab( logText, tr( "Log" ) );
}
void SC_MainWindow::createHelpTab()
{
helpView = new SC_WebView( this );
helpView -> setUrl( QUrl( "https://github.com/simulationcraft/simc/wiki/StartersGuide" ) );
mainTab -> addTab( helpView, tr( "Help" ) );
}
void SC_MainWindow::createResultsTab()
{
resultsTab = new SC_ResultTab( this );
connect( resultsTab, SIGNAL( currentChanged( int ) ), this, SLOT( resultsTabChanged( int ) ) );
connect( resultsTab, SIGNAL( tabCloseRequested( int ) ), this, SLOT( resultsTabCloseRequest( int ) ) );
mainTab -> addTab( resultsTab, tr( "Results" ) );
}
void SC_MainWindow::createSpellQueryTab()
{
spellQueryTab = new SC_SpellQueryTab( this );
mainTab -> addTab( spellQueryTab, tr( "Spell Query" ) );
}
void SC_MainWindow::createTabShortcuts()
{
Qt::Key keys[] = { Qt::Key_1, Qt::Key_2, Qt::Key_3, Qt::Key_4, Qt::Key_5, Qt::Key_6, Qt::Key_7, Qt::Key_8, Qt::Key_9, Qt::Key_unknown };
for ( int i = 0; keys[i] != Qt::Key_unknown; i++ )
{
// OS X needs to set the sequence to Cmd-<number>, since Alt is used for normal keys in certain cases
#if ! defined( Q_OS_MAC )
QShortcut* shortcut = new QShortcut( QKeySequence( Qt::ALT + keys[i] ), this );
#else
QShortcut* shortcut = new QShortcut( QKeySequence( Qt::CTRL + keys[i] ), this );
#endif
mainTabSignalMapper.setMapping( shortcut, i );
connect( shortcut, SIGNAL( activated() ), &mainTabSignalMapper, SLOT( map() ) );
shortcuts.push_back( shortcut );
}
connect( &mainTabSignalMapper, SIGNAL( mapped( int ) ), mainTab, SLOT( setCurrentIndex( int ) ) );
}
void SC_MainWindow::updateWebView( SC_WebView* wv )
{
assert( wv );
visibleWebView = wv;
if ( cmdLine != 0 ) // can be called before widget is setup
{
if ( visibleWebView == helpView )
{
cmdLine -> setHelpViewProgress( visibleWebView -> progress, "%p%", "" );
cmdLine -> setCommandLineText( TAB_HELP, visibleWebView -> url_to_show );
}
}
}
// ==========================================================================
// Sim Initialization
// ==========================================================================
std::shared_ptr<sim_t> SC_MainWindow::initSim()
{
auto sim = std::make_shared<sim_t>();
sim -> pause_mutex = std::unique_ptr<mutex_t>(new mutex_t());
sim -> report_progress = 0;
#if SC_USE_PTR
sim -> parse_option( "ptr", ( ( optionsTab -> choice.version -> currentIndex() == 1 ) ? "1" : "0" ) );
#endif
sim -> parse_option( "debug", ( ( optionsTab -> choice.debug -> currentIndex() == 2 ) ? "1" : "0" ) );
sim -> cleanup_threads = true;
return sim;
}
void SC_MainWindow::deleteSim( std::shared_ptr<sim_t>& sim, SC_TextEdit* append_error_message )
{
if ( sim )
{
std::list< std::string > files;
std::vector< std::string > errorListCopy( sim -> error_list );
files.push_back( sim -> output_file_str );
files.push_back( sim -> html_file_str );
files.push_back( sim -> json_file_str );
files.push_back( sim -> xml_file_str );
files.push_back( sim -> reforge_plot_output_file_str );
std::string output_file_str = sim -> output_file_str;
bool sim_control_was_not_zero = sim -> control != 0;
sim = nullptr;
QString contents;
bool logFileOpenedSuccessfully = false;
QFile logFile( QString::fromStdString( output_file_str ) );
if ( sim_control_was_not_zero ) // sim -> setup() was not called, output file was not opened
{
// ReadWrite failure indicates permission issues
if ( logFile.open( QIODevice::ReadWrite | QIODevice::Text ) )
{
contents = QString::fromUtf8( logFile.readAll() );
logFile.close();
logFileOpenedSuccessfully = true;
}
}
// Nothing in the log file, no point wondering about "permission issues"
else
logFileOpenedSuccessfully = true;
if ( !logFileOpenedSuccessfully )
{
for ( std::vector< std::string >::iterator it = errorListCopy.begin(); it != errorListCopy.end(); ++it )
{
contents.append( QString::fromStdString( *it + "\n" ) );
}
// If the failure is due to permissions issues, make this very clear to the user that the problem is on their end and what must be done to fix it
std::list< QString > directoriesWithPermissionIssues;
std::list< QString > filesWithPermissionIssues;
std::list< QString > filesThatAreDirectories;
std::string windowsPermissionRecommendation;
std::string suggestions;
#ifdef SC_WINDOWS
if ( QSysInfo::WindowsVersion >= QSysInfo::WV_VISTA )
{
windowsPermissionRecommendation = "Try running the program with administrative privileges by right clicking and selecting \"Run as administrator\"\n Or even installing the program to a different directory may help resolve these permission issues.";
}
#endif
for ( std::list< std::string >::iterator it = files.begin(); it != files.end(); ++it )
{
if ( !( *it ).empty() )
{
QFileInfo file( QString::fromStdString( *it ) );
if ( file.isDir() )
{
filesThatAreDirectories.push_back( file.absoluteFilePath() );
}
else if ( !file.isWritable() )
{
QFileInfo filesDirectory( file.absolutePath() );
if ( !filesDirectory.isWritable() )
directoriesWithPermissionIssues.push_back( file.absolutePath() );
filesWithPermissionIssues.push_back( file.absoluteFilePath() );
}
}
}
directoriesWithPermissionIssues.unique();
if ( filesThatAreDirectories.size() != 0 )
{
suggestions.append( "The following files are directories, SimulationCraft uses these as files, please rename them\n" );
}
for ( std::list< QString >::iterator it = filesThatAreDirectories.begin(); it != filesThatAreDirectories.end(); ++it )
{
suggestions.append( " " + ( *it ).toStdString() + "\n" );
}
if ( filesWithPermissionIssues.size() != 0 )
{
suggestions.append( "The following files have permission issues and are unwritable\n SimulationCraft needs to write to these files to simulate\n" );
}
for ( std::list< QString >::iterator it = filesWithPermissionIssues.begin(); it != filesWithPermissionIssues.end(); ++it )
{
suggestions.append( " " + ( *it ).toStdString() + "\n" );
}
if ( directoriesWithPermissionIssues.size() != 0 )
{
suggestions.append( "The following directories have permission issues and are unwritable\n meaning SimulationCraft cannot create files in these directories\n" );
}
for ( std::list< QString >::iterator it = directoriesWithPermissionIssues.begin(); it != directoriesWithPermissionIssues.end(); ++it )
{
suggestions.append( " " + ( *it ).toStdString() + "\n" );
}
if ( suggestions.length() != 0 )
{
suggestions = "\nSome possible suggestions on how to fix:\n" + suggestions;
append_error_message -> appendPlainText( QString::fromStdString( suggestions ) );
if ( windowsPermissionRecommendation.length() != 0 )
{
contents.append( QString::fromStdString( windowsPermissionRecommendation + "\n" ) );
}
}
if ( contents.contains( "Internal server error" ) )
{
contents.append( "\nAn Internal server error means an error occurred with the server, trying again later should fix it\n" );
}
contents.append( "\nIf for some reason you cannot resolve this issue, check if it is a known issue at\n https://github.com/simulationcraft/simc/issues\n" );
contents.append( "Or try an older version\n http://www.simulationcraft.org/download.html\n" );
contents.append( "And if all else fails you can come talk to us on IRC at\n irc.stratics.com (#simulationcraft)\n" );
}
// If requested, append the error message to the given Text Widget as well.
if ( append_error_message )
{
append_error_message -> appendPlainText( contents );
}
if ( logText != append_error_message )
{
logText -> appendPlainText( contents );
logText -> moveCursor( QTextCursor::End );
}
}
}
void SC_MainWindow::enqueueSim()
{
QString title = simulateTab -> tabText( simulateTab -> currentIndex() );
QString options = simulateTab -> current_Text() -> toPlainText().toUtf8();
QString fullOptions = optionsTab -> mergeOptions();
simulationQueue.enqueue( title, options, fullOptions );
}
void SC_MainWindow::startNewImport( const QString& region, const QString& realm, const QString& character, const QString& specialization )
{
if ( importRunning() )
{
stopImport();
return;
}
simProgress = 0;
import_sim = initSim();
importThread -> start( import_sim, region, realm, character, specialization );
simulateTab -> add_Text( defaultSimulateText, tr( "Importing" ) );
}
void SC_MainWindow::startImport( int tab, const QString& url )
{
if ( importRunning() )
{
stopImport();
return;
}
simProgress = 0;
import_sim = initSim();
importThread -> start( import_sim, tab, url, optionsTab -> get_db_order(), optionsTab -> get_active_spec(), optionsTab -> get_player_role(), optionsTab -> get_api_key() );
simulateTab -> add_Text( defaultSimulateText, tr( "Importing" ) );
}
void SC_MainWindow::stopImport()
{
if ( importRunning() )
{
import_sim -> cancel();
}
}
bool SC_MainWindow::importRunning()
{
return ( import_sim != 0 );
}
void SC_MainWindow::itemWasEnqueuedTryToSim()
{
if ( !simRunning() )
{
startSim();
}
else
{
cmdLine -> setState( SC_MainWindowCommandLine::SIMULATING_MULTIPLE );
}
}
void SC_MainWindow::updatetimer()
{
if ( importRunning() )
{
updateSimProgress();
soloChar -> start();
}
else
{
soloimport = 0;
}
}
void SC_MainWindow::importFinished()
{
importSimPhase = "%p%";
simProgress = 100;
importSimProgress = 100;
cmdLine -> setImportingProgress( importSimProgress, importSimPhase.c_str(), "" );
logText -> clear();
if ( importThread -> player )
{
simulateTab -> set_Text( importThread -> profile );
simulateTab->setTabText( simulateTab -> currentIndex(), QString::fromUtf8( importThread -> player -> name_str.c_str() ) );
QString label = QString::fromStdString( importThread -> player -> name_str );
while ( label.size() < 20 ) label += ' ';
label += QString::fromStdString( importThread -> player -> origin_str );
if ( label.contains( ".api." ) )
{ // Strip the s out of https and the api. out of the string so that it is a usable link.
label.replace( QString( ".api" ), QString( "" ) );
label.replace( QString( "https"), QString( "http" ) );
}
deleteSim( import_sim );
}
else
{
simulateTab -> setTabText( simulateTab -> currentIndex(), tr( "Import Failed" ) );
simulateTab -> append_Text( tr("# Unable to generate profile from: ") + importThread -> url + "\n" );
for( const std::string& error : import_sim -> error_list )
{
simulateTab -> append_Text( QString( "# ") + QString::fromStdString( error ) );
}
deleteSim( import_sim, simulateTab -> current_Text() );
}
if ( !simRunning() )
{
timer -> stop();
}
mainTab -> setCurrentTab( TAB_SIMULATE );
}
void SC_MainWindow::startSim()
{
saveHistory(); // This is to save whatever work the person has done, just in case there's a crash.
if ( simRunning() )
{
stopSim();
return;
}
if ( simulationQueue.isEmpty() )
{
// enqueue will call itemWasEnqueuedTryToSim() since it is empty
// which starts the sim
enqueueSim();
return;
}
optionsTab -> encodeOptions();
// Clear log text on success so users don't get confused if there is
// an error from previous attempts
if ( consecutiveSimulationsRun == 0 ) // Only clear on first queued sim
{
logText -> clear();
}
simProgress = 0;
sim = initSim();
auto value = simulationQueue.dequeue();
QString tab_name = std::get<0>( value );
// Build combined input profile
auto simc_gui_profile = std::get<1>( value );
QString simc_version;
if ( !git_info::available())
{
simc_version = QString("### SimulationCraft %1 for World of Warcraft %2 %3 (wow build %4) ###\n").
arg(SC_VERSION).arg(sim->dbc.wow_version()).arg(sim->dbc.wow_ptr_status()).arg(sim->dbc.build_level());
}
else
{
simc_version = QString("### SimulationCraft %1 for World of Warcraft %2 %3 (wow build %4, git build %5 %6) ###\n").
arg(SC_VERSION).arg(sim->dbc.wow_version()).arg(sim->dbc.wow_ptr_status()).arg(sim->dbc.build_level()).
arg(git_info::branch()).arg(git_info::revision());
}
QString gui_version = QString("### Using QT %1 with %2 ###\n\n").arg(QTCORE_VERSION_STR).arg(webEngineName());
simc_gui_profile = simc_version + gui_version + simc_gui_profile;
QByteArray utf8_profile = simc_gui_profile.toUtf8();
// Save profile to simc_gui.simc
QFile file( AppDataDir + QDir::separator() + "simc_gui.simc" );
if ( file.open( QIODevice::WriteOnly | QIODevice::Text ) )
{
file.write( utf8_profile );
file.close();
}
QString reportFileBase = QDir::toNativeSeparators( optionsTab -> getReportlDestination() );
sim -> output_file_str = (reportFileBase + ".txt").toStdString();
sim -> html_file_str = (reportFileBase + ".html").toStdString();
sim -> json_file_str = (reportFileBase + ".json").toStdString();
//sim -> xml_file_str = (reportFileBase + ".xml").toStdString();
sim -> reforge_plot_output_file_str = (reportFileBase + "_plotdata.csv").toStdString();
if ( optionsTab -> get_api_key().size() == 32 ) // api keys are 32 characters long, it's not worth parsing <32 character keys.
sim -> parse_option( "apikey", optionsTab -> get_api_key().toUtf8().constData() );
if ( cmdLine -> currentState() != SC_MainWindowCommandLine::SIMULATING_MULTIPLE )
{
cmdLine -> setState( SC_MainWindowCommandLine::SIMULATING );
}
simulateThread -> start( sim, utf8_profile, tab_name );
cmdLineText = "";
timer -> start( 100 );
}
void SC_MainWindow::stopSim()
{
if ( simRunning() )
{
simulationQueue.clear();
sim -> cancel();
stopImport();
if ( sim -> paused )
{
toggle_pause();
}
}
}
void SC_MainWindow::stopAllSim()
{
stopSim();
}
bool SC_MainWindow::simRunning()
{
return ( sim != 0 );
}
void SC_MainWindow::simulateFinished( std::shared_ptr<sim_t> sim )
{
simPhase = "%p%";
simProgress = 100;
cmdLine -> setSimulatingProgress( simProgress, QString::fromStdString(simPhase), tr( "Finished!" ) );
bool sim_was_debug = sim -> debug || sim -> log;
logText -> clear();
if ( ! simulateThread -> success )
{
// Spell Query ( is no not an error )
if ( mainTab -> currentTab() == TAB_SPELLQUERY )
{
QString result;
std::stringstream ss;
try
{
sim -> spell_query -> evaluate();
report::print_spell_query( ss, *sim, *sim -> spell_query, sim -> spell_query_level );
}
catch ( const std::exception& e ){
ss << "ERROR! Spell Query failure: " << e.what() << std::endl;
}
result = QString::fromStdString( ss.str() );
if ( result.isEmpty() )
{
result = "No results found!";
}
spellQueryTab -> textbox.result -> setPlainText( result );
spellQueryTab -> checkForSave();
}
else
{
logText -> moveCursor( QTextCursor::End );
if ( mainTab -> currentTab() != TAB_SPELLQUERY )
mainTab -> setCurrentTab( TAB_LOG );
QString errorText;
errorText += tr("SimulationCraft encountered an error!");
errorText += "<br><br>";
errorText += "<i>" + simulateThread -> getErrorCategory() + ":</i>";
errorText += "<br>";
errorText += "<b>" + simulateThread -> getError().replace("\n", "<br>") + "</b>";
errorText += "<br><br>";
errorText += tr("If you think this is a bug, please open a ticket, copying the detailed text below.<br>"
"It contains all the input options of the last simulation"
" and helps us reproduce the issue.<br>");
// Build error details which users can copy-paste into a ticket
// Use simulation options used, same as goes to simc_gui.simc
QString errorDetails;
errorDetails += "# SimulationCraft encountered an error!\n";
errorDetails += QString("* Category: %1\n").arg(simulateThread -> getErrorCategory());
errorDetails += QString("* Error: %1\n\n").arg(simulateThread -> getError());
errorDetails += "## All options used for simulation:\n";
errorDetails += "``` ini\n"; // start code section
errorDetails += simulateThread -> getOptions();
errorDetails += "\n```\n"; // end code section
QMessageBox mBox;
mBox.setWindowTitle(simulateThread -> getErrorCategory());
mBox.setText( errorText );
mBox.setDetailedText( errorDetails );
mBox.exec();
// print to log as well.
logText -> appendHtml( errorText );
logText -> appendPlainText( errorDetails );
}
}
else
{
QDateTime now = QDateTime::currentDateTime();
now.setOffsetFromUtc(now.offsetFromUtc());
QString datetime = now.toString(Qt::ISODate);
QString resultsName = simulateThread -> getTabName();
SC_SingleResultTab* resultsEntry = new SC_SingleResultTab( this, resultsTab );
if ( resultsTab -> count() != 0 )
{
QList< Qt::KeyboardModifier > s;
s.push_back( Qt::ControlModifier );
QList< Qt::KeyboardModifier > emptyList;
if ( resultsTab -> count() == 1 )
{
SC_SingleResultTab* resultsEntry_one = static_cast <SC_SingleResultTab*>(resultsTab -> widget( 0 ));
resultsEntry_one -> addIgnoreKeyPressEvent( Qt::Key_Tab, s );
resultsEntry_one -> addIgnoreKeyPressEvent( Qt::Key_Backtab, emptyList );
}
resultsEntry -> addIgnoreKeyPressEvent( Qt::Key_Tab, s );
resultsEntry -> addIgnoreKeyPressEvent( Qt::Key_Backtab, emptyList );
}
int index = resultsTab -> addTab( resultsEntry, resultsName );
resultsTab -> setTabToolTip( index, datetime );
if ( ++consecutiveSimulationsRun == 1 )
{
// only switch to the new tab if we are the first simulation in queue
resultsTab -> setCurrentWidget( resultsEntry );
}
// HTML
SC_WebView* resultsHtmlView = new SC_WebView( this, resultsEntry );
resultsHtmlView -> enableKeyboardNavigation();
resultsHtmlView -> enableMouseNavigation();
resultsEntry -> addTab( resultsHtmlView, "html" );
QFile html_file( sim -> html_file_str.c_str() );
if ( html_file.open( QIODevice::ReadOnly ) )
{
resultsHtmlView -> out_html = html_file.readAll();
html_file.close();
}
QString html_file_absolute_path = QFileInfo( html_file ).absoluteFilePath();
// just load it, let the error page extension handle failure to open
resultsHtmlView -> load( QUrl::fromLocalFile( html_file_absolute_path ) );
// Text
SC_TextEdit* resultsTextView = new SC_TextEdit( resultsEntry );
resultsEntry -> addTab( resultsTextView, "text" );
QFile logFile( sim -> output_file_str.c_str() );
if ( logFile.open( QIODevice::ReadOnly | QIODevice::Text ) )
{
resultsTextView -> setPlainText( logFile.readAll() );
logFile.close();
}
else
{
resultsTextView -> setPlainText( tr( "Error opening %1. %2" ).arg( sim -> output_file_str.c_str(), logFile.errorString() ) );
}
// JSON
SC_TextEdit* resultsJSONView = new SC_TextEdit( resultsEntry );
resultsEntry -> addTab( resultsJSONView, "JSON" );
QFile json_file( sim -> json_file_str.c_str() );
if ( json_file.open( QIODevice::ReadOnly | QIODevice::Text ) )
{
resultsJSONView -> appendPlainText( json_file.readAll() );
json_file.close();
}
else
{
resultsJSONView -> setPlainText( tr( "Error opening %1. %2" ).arg( sim -> json_file_str.c_str(), json_file.errorString() ) );
}
// Plot Data
SC_TextEdit* resultsPlotView = new SC_TextEdit( resultsEntry );
resultsEntry -> addTab( resultsPlotView, tr("plot data") );
QFile plot_file( sim -> reforge_plot_output_file_str.c_str() );
if ( plot_file.open( QIODevice::ReadOnly | QIODevice::Text ) )
{
resultsPlotView -> appendPlainText( plot_file.readAll() );
plot_file.close();
}
else
{
resultsPlotView -> setPlainText( tr( "Error opening %1. %2" ).arg( sim -> reforge_plot_output_file_str.c_str(), plot_file.errorString() ) );
}
if ( simulationQueue.isEmpty() )
{
mainTab -> setCurrentTab( sim_was_debug ? TAB_LOG : TAB_RESULTS );
}
}
if ( simulationQueue.isEmpty() && !importRunning() )
timer -> stop();