/
mainwindow.cpp
2214 lines (1994 loc) · 81.8 KB
/
mainwindow.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
/*
* TSPSG: TSP Solver and Generator
* Copyright (C) 2007-2014 Oleksii Serdiuk <contacts[at]oleksii[dot]name>
*
* $Id: $Format:%h %ai %an$ $
* $URL: http://tspsg.info/ $
*
* This file is part of TSPSG.
*
* TSPSG is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* TSPSG is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with TSPSG. If not, see <http://www.gnu.org/licenses/>.
*/
#include "mainwindow.h"
#include "settingsdialog.h"
#include "tspmodel.h"
#include <QBuffer>
#include <QCloseEvent>
#include <QDate>
#include <QDesktopServices>
#include <QDesktopWidget>
#include <QFileDialog>
#include <QImageWriter>
#include <QLibraryInfo>
#include <QMessageBox>
#include <QPageSetupDialog>
#include <QPainter>
#include <QProgressBar>
#include <QProgressDialog>
#include <QSettings>
#include <QStatusBar>
#include <QStyleFactory>
#include <QTextCodec>
#include <QTextDocumentWriter>
#include <QTextBrowser>
#include <QTextStream>
#include <QTextTable>
#include <QTranslator>
#ifdef Q_OS_WINCE_WM
# include <QScrollArea>
#endif
#ifndef QT_NO_PRINTER
# include <QPrinter>
# include <QPrintDialog>
# include <QPrintPreviewDialog>
#endif
#if !defined(NOSVG)
# include <QSvgGenerator>
#endif // NOSVG
#include <QtConcurrentRun>
#include "os.h"
#ifndef HANDHELD
# include "qttoolbardialog.h"
// Eyecandy
# include "qtwin.h"
#endif // HANDHELD
#ifndef QT_NO_PRINTER
Q_DECLARE_METATYPE(QPrinter::PageSize)
Q_DECLARE_METATYPE(QPrinter::Orientation)
#endif
#ifdef Q_OS_WIN32
# include <initguid.h>
# include "shobjidl.h"
#endif
#ifdef Q_OS_BLACKBERRY
# include <bb/ApplicationSupport>
# include <bb/cascades/pickers/FilePicker>
using namespace bb::cascades::pickers;
#endif
#ifdef _T_T_L_
#include "_.h"
_C_ _R_ _Y_ _P_ _T_
#endif
// BEGIN HELPER FUNCTIONS
/*!
* \brief Checks whether \a x contains an integer value.
* \param x A value to check.
* \return \c true if \a x countains an integer, oherwise \c false.
*/
inline bool isInteger(double x)
{
double i;
#ifdef Q_OS_BLACKBERRY
return (std::modf(x, &i) == 0.0);
#else
return (modf(x, &i) == 0.0);
#endif
}
/*!
* \brief Converts \a in into Base64 format with lines wrapped at 64 characters.
* \param in A byte array to be converted.
* \return Converted byte array.
*/
inline QByteArray toWrappedBase64(const QByteArray &in)
{
QByteArray out, base64(in.toBase64());
for (int i = 0; i <= base64.size() - 64; i += 64) {
out.append(QByteArray::fromRawData(base64.data() + i, 64)).append('\n');
}
if (int rest = base64.size() % 64)
out.append(QByteArray::fromRawData(base64.data() + base64.size() - rest, rest));
return out;
}
// END HELPER FUNCTIONS
/*!
* \brief Class constructor.
* \param parent Main Window parent widget.
*
* Initializes Main Window and creates its layout based on target OS.
* Loads TSPSG settings and opens a task file if it was specified as a commandline parameter.
*/
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
{
settings = initSettings(this);
// Sanity check
int m = settings->value("Tweaks/MaxNumCities", MAX_NUM_CITIES).toInt();
if (m < 3)
settings->setValue("Tweaks/MaxNumCities", 3);
if (settings->contains("Style")) {
QStyle *s = QStyleFactory::create(settings->value("Style").toString());
if (s != NULL)
QApplication::setStyle(s);
else
settings->remove("Style");
}
loadLanguage();
setupUi();
setAcceptDrops(true);
#ifdef Q_OS_BLACKBERRY
taskView->setEditTriggers(QAbstractItemView::AllEditTriggers);
#endif
initDocStyleSheet();
#ifndef QT_NO_PRINTER
printer = new QPrinter(QPrinter::HighResolution);
settings->beginGroup("Printer");
QPrinter::PaperSize size = qvariant_cast<QPrinter::PaperSize>(settings->value("PaperSize", DEF_PAGE_SIZE));
if (size != QPrinter::Custom) {
printer->setPaperSize(size);
} else {
printer->setPaperSize(QSizeF(settings->value("PaperWidth").toReal(), settings->value("PaperHeight").toReal()),
QPrinter::Millimeter);
}
printer->setOrientation(qvariant_cast<QPrinter::Orientation>(settings->value("PageOrientation", DEF_PAGE_ORIENTATION)));
printer->setPageMargins(
settings->value("MarginLeft", DEF_MARGIN_LEFT).toReal(),
settings->value("MarginTop", DEF_MARGIN_TOP).toReal(),
settings->value("MarginRight", DEF_MARGIN_RIGHT).toReal(),
settings->value("MarginBottom", DEF_MARGIN_BOTTOM).toReal(),
QPrinter::Millimeter);
settings->endGroup();
#endif // QT_NO_PRINTER
#ifdef Q_OS_WINCE_WM
currentGeometry = QApplication::desktop()->availableGeometry(0);
// We need to react to SIP show/hide and resize the window appropriately
connect(QApplication::desktop(), SIGNAL(workAreaResized(int)), SLOT(desktopResized(int)));
#endif // Q_OS_WINCE_WM
connect(actionFileNew, SIGNAL(triggered()), SLOT(actionFileNewTriggered()));
connect(actionFileOpen, SIGNAL(triggered()), SLOT(actionFileOpenTriggered()));
connect(actionFileSave, SIGNAL(triggered()), SLOT(actionFileSaveTriggered()));
connect(actionFileSaveAsTask, SIGNAL(triggered()), SLOT(actionFileSaveAsTaskTriggered()));
connect(actionFileSaveAsSolution, SIGNAL(triggered()), SLOT(actionFileSaveAsSolutionTriggered()));
#ifndef QT_NO_PRINTDIALOG
connect(actionFilePrintPreview, SIGNAL(triggered()), SLOT(actionFilePrintPreviewTriggered()));
connect(actionFilePageSetup, SIGNAL(triggered()), SLOT(actionFilePageSetupTriggered()));
connect(actionFilePrint, SIGNAL(triggered()), SLOT(actionFilePrintTriggered()));
#endif // QT_NO_PRINTER
#ifndef HANDHELD
connect(actionSettingsToolbarsConfigure, SIGNAL(triggered()), SLOT(actionSettingsToolbarsConfigureTriggered()));
#endif // HANDHELD
connect(actionSettingsPreferences, SIGNAL(triggered()), SLOT(actionSettingsPreferencesTriggered()));
if (actionHelpCheck4Updates != NULL)
connect(actionHelpCheck4Updates, SIGNAL(triggered()), SLOT(actionHelpCheck4UpdatesTriggered()));
connect(actionSettingsLanguageAutodetect, SIGNAL(triggered(bool)), SLOT(actionSettingsLanguageAutodetectTriggered(bool)));
connect(groupSettingsLanguageList, SIGNAL(triggered(QAction *)), SLOT(groupSettingsLanguageListTriggered(QAction *)));
connect(actionSettingsStyleSystem, SIGNAL(triggered(bool)), SLOT(actionSettingsStyleSystemTriggered(bool)));
connect(groupSettingsStyleList, SIGNAL(triggered(QAction*)), SLOT(groupSettingsStyleListTriggered(QAction*)));
connect(actionHelpOnlineSupport, SIGNAL(triggered()), SLOT(actionHelpOnlineSupportTriggered()));
connect(actionHelpReportBug, SIGNAL(triggered()), SLOT(actionHelpReportBugTriggered()));
connect(actionHelpAboutQt, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
connect(actionHelpAbout, SIGNAL(triggered()), SLOT(actionHelpAboutTriggered()));
connect(buttonSolve, SIGNAL(clicked()), SLOT(buttonSolveClicked()));
connect(buttonRandom, SIGNAL(clicked()), SLOT(buttonRandomClicked()));
connect(buttonBackToTask, SIGNAL(clicked()), SLOT(buttonBackToTaskClicked()));
connect(spinCities, SIGNAL(valueChanged(int)), SLOT(spinCitiesValueChanged(int)));
#ifndef HANDHELD
// Centering main window
QRect rect = geometry();
rect.moveCenter(QApplication::desktop()->availableGeometry(this).center());
setGeometry(rect);
if (settings->value("SavePos", DEF_SAVEPOS).toBool()) {
// Loading of saved window state
settings->beginGroup("MainWindow");
restoreGeometry(settings->value("Geometry").toByteArray());
restoreState(settings->value("State").toByteArray());
settings->endGroup();
}
#endif // HANDHELD
tspmodel = new CTSPModel(this);
taskView->setModel(tspmodel);
connect(tspmodel, SIGNAL(numCitiesChanged(int)), SLOT(numCitiesChanged(int)));
connect(tspmodel, SIGNAL(dataChanged(const QModelIndex &, const QModelIndex &)), SLOT(dataChanged(const QModelIndex &, const QModelIndex &)));
connect(tspmodel, SIGNAL(layoutChanged()), SLOT(dataChanged()));
if ((QCoreApplication::arguments().count() > 1) && (tspmodel->loadTask(QCoreApplication::arguments().at(1))))
setFileName(QCoreApplication::arguments().at(1));
else {
setFileName();
spinCities->setValue(settings->value("NumCities",DEF_NUM_CITIES).toInt());
spinCitiesValueChanged(spinCities->value());
}
setWindowModified(false);
if (actionHelpCheck4Updates != NULL) {
if (!settings->contains("Check4Updates/Enabled")) {
QApplication::setOverrideCursor(QCursor(Qt::ArrowCursor));
settings->setValue("Check4Updates/Enabled",
QMessageBox::question(this, QCoreApplication::applicationName(),
tr("Would you like %1 to automatically check for updates every %n day(s)?", "", settings->value("Check4Updates/Interval", DEF_UPDATE_CHECK_INTERVAL).toInt()).arg(QCoreApplication::applicationName()),
QMessageBox::Yes | QMessageBox::No
) == QMessageBox::Yes
);
QApplication::restoreOverrideCursor();
}
if ((settings->value("Check4Updates/Enabled", DEF_CHECK_FOR_UPDATES).toBool())
&& (QDate(qvariant_cast<QDate>(settings->value("Check4Updates/LastAttempt"))).daysTo(QDate::currentDate()) >= settings->value("Check4Updates/Interval", DEF_UPDATE_CHECK_INTERVAL).toInt())) {
check4Updates(true);
}
}
}
MainWindow::~MainWindow()
{
#ifndef QT_NO_PRINTER
delete printer;
#endif
}
#ifdef Q_OS_BLACKBERRY
void MainWindow::setWindowModified(bool modified)
{
QMainWindow::setWindowModified(modified);
bb::ApplicationSupport app;
if (modified)
app.setClosePrompt(tr("Unsaved Changes"), tr("The task has unsaved changes. Would you really like to close the application?"));
else
app.clearClosePrompt();
}
#endif
/* Privates **********************************************************/
void MainWindow::actionFileNewTriggered()
{
if (!maybeSave())
return;
QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
tspmodel->clear();
setFileName();
setWindowModified(false);
tabWidget->setCurrentIndex(0);
solutionText->clear();
graph = QPicture();
toggleSolutionActions(false);
QApplication::restoreOverrideCursor();
}
void MainWindow::actionFileOpenTriggered()
{
if (!maybeSave())
return;
QStringList filters;
#ifdef Q_OS_BLACKBERRY
filters << "*.tspt" << "*.zkt";
#else
filters.append(tr("All Supported Formats") + " (*.tspt *.zkt)");
filters.append(tr("%1 Task Files").arg("TSPSG") + " (*.tspt)");
filters.append(tr("%1 Task Files").arg("ZKomModRd") + " (*.zkt)");
filters.append(tr("All Files") + " (*)");
#endif
QString file;
if ((fileName == tr("Untitled") + ".tspt") && settings->value("SaveLastUsed", DEF_SAVE_LAST_USED).toBool())
#ifdef Q_OS_BLACKBERRY
file = settings->value(OS"/LastUsed/TaskLoadPath", "/accounts/1000/shared/documents").toString();
#else
file = settings->value(OS"/LastUsed/TaskLoadPath").toString();
#endif
else
file = QFileInfo(fileName).path();
#ifdef Q_OS_BLACKBERRY
FilePicker fd;
fd.setType(FileType::Document | FileType::Other);
fd.setDefaultType(FileType::Document);
fd.setTitle(tr("Task Load"));
fd.setFilter(filters);
fd.setDirectories(QStringList(file));
fd.open();
QEventLoop loop;
connect(&fd, SIGNAL(pickerClosed()), &loop, SLOT(quit()));
loop.exec();
if (fd.selectedFiles().count() < 1)
return;
file = fd.selectedFiles().at(0);
if (!QFileInfo(file).isFile())
return;
#else
QFileDialog::Options opts = settings->value("UseNativeDialogs", DEF_USE_NATIVE_DIALOGS).toBool() ? QFileDialog::Options() : QFileDialog::DontUseNativeDialog;
file = QFileDialog::getOpenFileName(this, tr("Task Load"), file, filters.join(";;"), NULL, opts);
if (file.isEmpty() || !QFileInfo(file).isFile())
return;
#endif
if (settings->value("SaveLastUsed", DEF_SAVE_LAST_USED).toBool())
settings->setValue(OS"/LastUsed/TaskLoadPath", QFileInfo(file).path());
if (!tspmodel->loadTask(file))
return;
setFileName(file);
tabWidget->setCurrentIndex(0);
setWindowModified(false);
solutionText->clear();
toggleSolutionActions(false);
}
bool MainWindow::actionFileSaveTriggered()
{
if ((fileName == tr("Untitled") + ".tspt") || !fileName.endsWith(".tspt", Qt::CaseInsensitive))
return saveTask();
else
if (tspmodel->saveTask(fileName)) {
setWindowModified(false);
return true;
} else
return false;
}
void MainWindow::actionFileSaveAsTaskTriggered()
{
saveTask();
}
void MainWindow::actionFileSaveAsSolutionTriggered()
{
static QString selectedFile;
if (selectedFile.isEmpty()) {
if (settings->value("SaveLastUsed", DEF_SAVE_LAST_USED).toBool()) {
#ifdef Q_OS_BLACKBERRY
selectedFile = settings->value(OS"/LastUsed/SolutionSavePath", "/accounts/1000/shared/documents").toString();
#else
selectedFile = settings->value(OS"/LastUsed/SolutionSavePath").toString();
#endif
}
} else
selectedFile = QFileInfo(selectedFile).path();
if (!selectedFile.isEmpty())
selectedFile.append("/");
if (fileName == tr("Untitled") + ".tspt") {
#ifndef QT_NO_PRINTER
selectedFile += "solution.pdf";
#else
selectedFile += "solution.html";
#endif // QT_NO_PRINTER
} else {
#ifndef QT_NO_PRINTER
selectedFile += QFileInfo(fileName).completeBaseName() + ".pdf";
#else
selectedFile += QFileInfo(fileName).completeBaseName() + ".html";
#endif // QT_NO_PRINTER
}
QStringList filters;
#ifdef Q_OS_BLACKBERRY
filters << "*.pdf" << "*.html" << "*.htm" << "*.odf";
#else
#ifndef QT_NO_PRINTER
filters.append(tr("PDF Files") + " (*.pdf)");
#endif
filters.append(tr("HTML Files") + " (*.html *.htm)");
filters.append(tr("Web Archive Files") + " (*.mht *.mhtml)");
filters.append(tr("OpenDocument Files") + " (*.odt)");
filters.append(tr("All Files") + " (*)");
#endif
#ifdef Q_OS_BLACKBERRY
FilePicker fd;
fd.setMode(FilePickerMode::Saver);
fd.setType(FileType::Document | FileType::Other);
fd.setDefaultType(FileType::Document);
fd.setAllowOverwrite(true);
fd.setTitle(tr("Solution Save"));
// fd.setDirectories(QStringList(QFileInfo(selectedFile).path()));
fd.setDefaultSaveFileNames(QStringList(selectedFile));
fd.setFilter(filters);
fd.open();
QEventLoop loop;
connect(&fd, SIGNAL(pickerClosed()), &loop, SLOT(quit()));
loop.exec();
if (fd.selectedFiles().count() < 1)
return;
selectedFile = fd.selectedFiles().at(0);
#else
QFileDialog::Options opts(settings->value("UseNativeDialogs", DEF_USE_NATIVE_DIALOGS).toBool() ? QFileDialog::Options() : QFileDialog::DontUseNativeDialog);
QString file = QFileDialog::getSaveFileName(this, QString(), selectedFile, filters.join(";;"), NULL, opts);
if (file.isEmpty())
return;
selectedFile = file;
#endif
if (settings->value("SaveLastUsed", DEF_SAVE_LAST_USED).toBool())
settings->setValue(OS"/LastUsed/SolutionSavePath", QFileInfo(selectedFile).path());
QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
#ifndef QT_NO_PRINTER
if (selectedFile.endsWith(".pdf", Qt::CaseInsensitive)) {
printer->setOutputFileName(selectedFile);
solutionText->document()->print(printer);
printer->setOutputFileName(QString());
QApplication::restoreOverrideCursor();
return;
}
#endif
QByteArray imgdata;
bool mhtml = selectedFile.contains(QRegExp("\\.mht(ml)?$", Qt::CaseInsensitive));
bool embed = !mhtml && settings->value("Output/EmbedGraphIntoHTML", DEF_EMBED_GRAPH_INTO_HTML).toBool();
if (selectedFile.contains(QRegExp("\\.(html?|mht(ml)?)$", Qt::CaseInsensitive))) {
QFile file(selectedFile);
if (!file.open(QFile::WriteOnly | QFile::Text)) {
QApplication::restoreOverrideCursor();
QMessageBox::critical(this, tr("Solution Save"), tr("Unable to save the solution.\nError: %1").arg(file.errorString()));
return;
}
QString html = solutionText->document()->toHtml("UTF-8");
html.replace(QRegExp("font-family:([^;]*);"),
"font-family:\\1, 'DejaVu Sans Mono', 'Courier New', Courier, monospace;");
html.replace(QRegExp("<style ([^>]*)>"), QString("<style \\1>\n"
"body { color: %1 }\n"
"td { border-style: solid; border-width: 1px; border-color: %2; }")
.arg(settings->value("Output/Colors/Font", DEF_TEXT_COLOR).toString(),
settings->value("Output/Colors/TableBorder", DEF_TABLE_COLOR).toString()));
QFileInfo fi(selectedFile);
QString format = settings->value("Output/GraphImageFormat", DEF_GRAPH_IMAGE_FORMAT).toString();
#if !defined(NOSVG)
if (!QImageWriter::supportedImageFormats().contains(format.toLatin1()) && (format != "svg")) {
#else // NOSVG
if (!QImageWriter::supportedImageFormats().contains(format.toLatin1())) {
#endif // NOSVG
format = DEF_GRAPH_IMAGE_FORMAT;
settings->remove("Output/GraphImageFormat");
}
if (!graph.isNull()) {
imgdata = generateImage(format);
if (imgdata.isEmpty()) {
QApplication::restoreOverrideCursor();
return;
}
if (embed) {
QString fmt = format;
if (format == "svg")
fmt.append("+xml");
html.replace(QRegExp("<img\\s+src=\"tspsg://graph.pic\""),
QString("<img src=\"data:image/%1;base64,%2\" alt=\"%3\"")
.arg(fmt, toWrappedBase64(imgdata), tr("Solution Graph")));
} else {
html.replace(QRegExp("<img\\s+src=\"tspsg://graph.pic\""),
QString("<img src=\"%1\" alt=\"%2\"")
.arg(fi.completeBaseName() + "." + format, tr("Solution Graph")));
}
}
// Saving solution text as HTML
QTextStream ts(&file);
ts.setCodec(QTextCodec::codecForName("UTF-8"));
QString boundary = QString("------=multipart_boundary.%1").arg(qHash(selectedFile));
if (mhtml) {
ts << "Content-Type: multipart/related; start=<solution@tspsg.info>; boundary=\""
<< boundary << "\"; type=\"text/html\"" << endl;
boundary.prepend("--");
ts << "MIME-Version: 1.0" << endl;
ts << endl;
ts << boundary << endl;
ts << "Content-Disposition: inline; filename=" << fi.completeBaseName() << ".html" << endl;
ts << "Content-Type: text/html; name=" << fi.completeBaseName() << ".html" << endl;
ts << "Content-ID: <solution@tspsg.info>" << endl;
ts << "Content-Location: " << fi.completeBaseName() << ".html" << endl;
ts << "Content-Transfer-Encoding: 8bit" << endl;
ts << endl;
}
ts << html << endl;
if (mhtml) {
ts << endl << boundary << endl;
ts << "Content-Disposition: inline; filename=" << fi.completeBaseName() << "." << format << endl;
ts << "Content-Type: image/" << format;
if (format == "svg")
ts << "+xml";
ts << "; name=" << fi.completeBaseName() << "." << format << endl;
ts << "Content-Location: " << fi.completeBaseName() << "." << format << endl;
ts << "Content-Transfer-Encoding: Base64" << endl;
ts << endl;
ts << toWrappedBase64(imgdata) << endl;
ts << endl << boundary << "--" << endl;
}
file.close();
if (!embed && !mhtml) {
QFile img(fi.path() + "/" + fi.completeBaseName() + "." + format);
if (!img.open(QFile::WriteOnly)) {
QApplication::restoreOverrideCursor();
QMessageBox::critical(this, tr("Solution Save"), tr("Unable to save the solution graph.\nError: %1").arg(img.errorString()));
return;
}
if (img.write(imgdata) != imgdata.size()) {
QApplication::restoreOverrideCursor();
QMessageBox::critical(this, tr("Solution Save"), tr("Unable to save the solution graph.\nError: %1").arg(img.errorString()));
}
img.close();
}
} else {
QTextDocumentWriter dw(selectedFile);
if (!selectedFile.endsWith(".odt",Qt::CaseInsensitive))
dw.setFormat("plaintext");
if (!dw.write(solutionText->document()))
QMessageBox::critical(this, tr("Solution Save"), tr("Unable to save the solution.\nError: %1").arg(dw.device()->errorString()));
}
QApplication::restoreOverrideCursor();
}
#ifndef QT_NO_PRINTDIALOG
void MainWindow::actionFilePrintPreviewTriggered()
{
QPrintPreviewDialog ppd(printer, this);
connect(&ppd,SIGNAL(paintRequested(QPrinter *)),SLOT(printPreview(QPrinter *)));
ppd.exec();
qreal l, t, r, b;
printer->getPageMargins(&l, &t, &r, &b, QPrinter::Millimeter);
settings->beginGroup("Printer");
settings->setValue("PaperSize", printer->paperSize());
if (printer->paperSize() == QPrinter::Custom) {
QSizeF size(printer->paperSize(QPrinter::Millimeter));
settings->setValue("PaperWidth", size.width());
settings->setValue("PaperHeight", size.height());
}
settings->setValue("PageOrientation", printer->orientation());
settings->setValue("MarginLeft", l);
settings->setValue("MarginTop", t);
settings->setValue("MarginRight", r);
settings->setValue("MarginBottom", b);
settings->endGroup();
}
void MainWindow::actionFilePageSetupTriggered()
{
QPageSetupDialog psd(printer, this);
if (psd.exec() != QDialog::Accepted)
return;
qreal l, t, r ,b;
printer->getPageMargins(&l, &t, &r, &b, QPrinter::Millimeter);
settings->beginGroup("Printer");
settings->setValue("PaperSize", printer->paperSize());
if (printer->paperSize() == QPrinter::Custom) {
QSizeF size(printer->paperSize(QPrinter::Millimeter));
settings->setValue("PaperWidth", size.width());
settings->setValue("PaperHeight", size.height());
}
settings->setValue("PageOrientation", printer->orientation());
settings->setValue("MarginLeft", l);
settings->setValue("MarginTop", t);
settings->setValue("MarginRight", r);
settings->setValue("MarginBottom", b);
settings->endGroup();
}
void MainWindow::actionFilePrintTriggered()
{
QPrintDialog pd(printer,this);
if (pd.exec() != QDialog::Accepted)
return;
QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
solutionText->print(printer);
QApplication::restoreOverrideCursor();
}
#endif // QT_NO_PRINTDIALOG
void MainWindow::actionSettingsPreferencesTriggered()
{
SettingsDialog sd(this);
#ifdef Q_OS_SYMBIAN
sd.setWindowState(Qt::WindowMaximized);
#endif
if (sd.exec() != QDialog::Accepted)
return;
if (sd.colorChanged() || sd.fontChanged()) {
if (!solutionText->document()->isEmpty() && sd.colorChanged())
QMessageBox::information(this, tr("Settings Changed"), tr("You have changed color settings.\nThey will be applied to the next solution output."));
initDocStyleSheet();
}
if (sd.translucencyChanged() != 0)
toggleTranclucency(sd.translucencyChanged() == 1);
}
void MainWindow::actionSettingsLanguageAutodetectTriggered(bool checked)
{
if (checked) {
settings->remove("Language");
QMessageBox::information(this, tr("Language change"), tr("Language will be autodetected on the next %1 start.").arg(QCoreApplication::applicationName()));
} else
settings->setValue("Language", groupSettingsLanguageList->checkedAction()->data().toString());
}
void MainWindow::groupSettingsLanguageListTriggered(QAction *action)
{
#ifndef Q_WS_MAEMO_5
if (actionSettingsLanguageAutodetect->isChecked())
actionSettingsLanguageAutodetect->trigger();
#endif
bool untitled = (fileName == tr("Untitled") + ".tspt");
if (loadLanguage(action->data().toString())) {
QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
settings->setValue("Language",action->data().toString());
retranslateUi();
if (untitled)
setFileName();
#ifndef HANDHELD
if (QtWin::isCompositionEnabled() && settings->value("UseTranslucency", DEF_USE_TRANSLUCENCY).toBool()) {
toggleStyle(labelVariant, true);
toggleStyle(labelCities, true);
}
#endif
QApplication::restoreOverrideCursor();
if (!solutionText->document()->isEmpty())
QMessageBox::information(this, tr("Settings Changed"), tr("You have changed the application language.\nTo get current solution output in the new language\nyou need to re-run the solution process."));
}
}
void MainWindow::actionSettingsStyleSystemTriggered(bool checked)
{
if (checked) {
settings->remove("Style");
QMessageBox::information(this, tr("Style Change"), tr("To apply the default style you need to restart %1.").arg(QCoreApplication::applicationName()));
} else {
settings->setValue("Style", groupSettingsStyleList->checkedAction()->text());
}
}
void MainWindow::groupSettingsStyleListTriggered(QAction *action)
{
QStyle *s = QStyleFactory::create(action->text());
if (s != NULL) {
QApplication::setStyle(s);
settings->setValue("Style", action->text());
actionSettingsStyleSystem->setChecked(false);
}
}
#ifndef HANDHELD
void MainWindow::actionSettingsToolbarsConfigureTriggered()
{
QtToolBarDialog dlg(this);
dlg.setToolBarManager(toolBarManager);
dlg.exec();
QToolButton *tb = static_cast<QToolButton *>(toolBarMain->widgetForAction(actionFileSave));
if (tb != NULL) {
tb->setMenu(menuFileSaveAs);
tb->setPopupMode(QToolButton::MenuButtonPopup);
tb->resize(tb->sizeHint());
}
loadToolbarList();
}
#endif // HANDHELD
void MainWindow::actionHelpCheck4UpdatesTriggered()
{
if (!hasUpdater()) {
QMessageBox::warning(this, tr("Unsupported Feature"), tr("Sorry, but this feature is not supported on your\nplatform or support for it was not installed."));
return;
}
check4Updates();
}
void MainWindow::actionHelpAboutTriggered()
{
QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
QString title;
title += QString("<b>%1</b><br>").arg(QCoreApplication::applicationName());
title += QString("%1: <b>%2</b><br>").arg(tr("Version"), QCoreApplication::applicationVersion());
#ifndef HANDHELD
title += QString("<b>© 2007-%1 <a href=\"http://%2/\">%3</a></b><br>").arg(QDate::currentDate().toString("yyyy"), QCoreApplication::organizationDomain(), QCoreApplication::organizationName());
#endif // HANDHELD
title += QString("<b><a href=\"http://tspsg.info/\">http://tspsg.info/</a></b>");
QString about;
about += QString("%1: <b>%2</b><br>").arg(tr("Target OS (ARCH)"), PLATFROM);
about += QString("%1:<br>").arg(tr("Qt library"));
about += QString(" %1: <b>%2</b><br>").arg(tr("Build time"), QT_VERSION_STR);
about += QString(" %1: <b>%2</b><br>").arg(tr("Runtime"), qVersion());
about.append(QString("%1: <b>%2x%3</b><br>").arg(tr("Logical screen DPI")).arg(logicalDpiX()).arg(logicalDpiY()));
QString tag;
#ifdef REVISION_STR
tag = tr(" from git commit <b>%1</b>").arg(QString(REVISION_STR).left(10));
#endif
about += tr("Build <b>%1</b>, built on <b>%2</b> at <b>%3</b>%5 with <b>%4</b> compiler.").arg(BUILD_NUMBER).arg(__DATE__).arg(__TIME__).arg(COMPILER).arg(tag) + "<br>";
about += QString("%1: <b>%2</b><br>").arg(tr("Algorithm"), TSPSolver::CTSPSolver::getVersionId());
about += "<br>";
about += tr("This program is free software: you can redistribute it and/or modify<br>\n"
"it under the terms of the GNU General Public License as published by<br>\n"
"the Free Software Foundation, either version 2 of the License, or<br>\n"
"(at your option) any later version.<br>\n"
"<br>\n"
"This program is distributed in the hope that it will be useful,<br>\n"
"but WITHOUT ANY WARRANTY; without even the implied warranty of<br>\n"
"MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the<br>\n"
"GNU General Public License for more details.<br>\n"
"<br>\n"
"You should have received a copy of the GNU General Public License<br>\n"
"along with TSPSG. If not, see <a href=\"http://www.gnu.org/licenses/\">www.gnu.org/licenses/</a>.");
QString credits;
credits += tr("%1 was created using <b>Qt</b> framework licensed "
"under the terms of <i>GNU Lesser General Public License</i>,<br>\n"
"see <a href=\"http://qt-project.org/\">qt-project.org</a><br>\n"
"<br>\n"
"Most icons used in %1 are part of <b>Oxygen Icons</b> project "
"licensed according to the <i>GNU Lesser General Public License</i>,<br>\n"
"see <a href=\"http://www.oxygen-icons.org/\">www.oxygen-icons.org</a><br>\n"
"<br>\n"
"Country flag icons used in %1 are part of <b>Flag Icons</b> by "
"<b>GoSquared</b> licensed under the terms of <i>MIT License</i>,<br>\n"
"see <a href=\"https://www.gosquared.com/\">www.gosquared.com</a><br>\n"
"<br>\n"
"%1 comes with the default \"embedded\" font <b>DejaVu LGC Sans "
"Mono</b> from the <b>DejaVu fonts</b> licensed under <i>Free license</i></a>,<br>\n"
"see <a href=\"http://dejavu-fonts.org/\">dejavu-fonts.org</a>")
.arg("TSPSG");
QFile f(":/files/COPYING");
f.open(QIODevice::ReadOnly);
QString translation = QCoreApplication::translate("--------", "AUTHORS %1", "Please, provide translator credits here. %1 will be replaced with VERSION");
if ((translation != "AUTHORS %1") && (translation.contains("%1"))) {
QString about = QCoreApplication::translate("--------", "VERSION", "Please, provide your translation version here.");
if (about != "VERSION")
translation = translation.arg(about);
}
QDialog *dlg = new QDialog(this);
QLabel *lblIcon = new QLabel(dlg),
*lblTitle = new QLabel(dlg);
#ifdef HANDHELD
QLabel *lblSubTitle = new QLabel(QString("<b>© 2007-%1 <a href=\"http://%2/\">%3</a></b>").arg(QDate::currentDate().toString("yyyy"), QCoreApplication::organizationDomain(), QCoreApplication::organizationName()), dlg);
#endif // HANDHELD
QTabWidget *tabs = new QTabWidget(dlg);
QTextBrowser *txtAbout = new QTextBrowser(dlg);
QTextBrowser *txtLicense = new QTextBrowser(dlg);
QTextBrowser *txtCredits = new QTextBrowser(dlg);
QVBoxLayout *vb = new QVBoxLayout();
QHBoxLayout *hb1 = new QHBoxLayout(),
*hb2 = new QHBoxLayout();
QDialogButtonBox *bb = new QDialogButtonBox(QDialogButtonBox::Ok, Qt::Horizontal, dlg);
lblTitle->setOpenExternalLinks(true);
lblTitle->setText(title);
lblTitle->setAlignment(Qt::AlignTop);
lblTitle->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
#ifndef HANDHELD
lblTitle->setStyleSheet(QString("QLabel {background-color: %1; border-color: %2; border-width: 1px; border-style: solid; border-radius: 4px; padding: 1px;}").arg(palette().alternateBase().color().name(), palette().shadow().color().name()));
#endif // HANDHELD
lblIcon->setPixmap(QPixmap(":/images/tspsg.png").scaledToHeight(lblTitle->sizeHint().height(), Qt::SmoothTransformation));
lblIcon->setAlignment(Qt::AlignVCenter);
#ifndef HANDHELD
lblIcon->setStyleSheet(QString("QLabel {background-color: white; border-color: %1; border-width: 1px; border-style: solid; border-radius: 4px; padding: 1px;}").arg(palette().windowText().color().name()));
#endif // HANDHELD
hb1->addWidget(lblIcon);
hb1->addWidget(lblTitle);
txtAbout->setWordWrapMode(QTextOption::NoWrap);
txtAbout->setOpenExternalLinks(true);
txtAbout->setHtml(about);
txtAbout->moveCursor(QTextCursor::Start);
txtAbout->setFrameShape(QFrame::NoFrame);
#ifdef Q_OS_BLACKBERRY
txtAbout->setAttribute(Qt::WA_InputMethodEnabled, false);
#endif
// txtCredits->setWordWrapMode(QTextOption::NoWrap);
txtCredits->setOpenExternalLinks(true);
txtCredits->setHtml(credits);
txtCredits->moveCursor(QTextCursor::Start);
txtCredits->setFrameShape(QFrame::NoFrame);
#ifdef Q_OS_BLACKBERRY
txtCredits->setAttribute(Qt::WA_InputMethodEnabled, false);
#endif
txtLicense->setWordWrapMode(QTextOption::NoWrap);
txtLicense->setOpenExternalLinks(true);
txtLicense->setText(f.readAll());
txtLicense->moveCursor(QTextCursor::Start);
txtLicense->setFrameShape(QFrame::NoFrame);
#ifdef Q_OS_BLACKBERRY
txtLicense->setAttribute(Qt::WA_InputMethodEnabled, false);
#endif
bb->button(QDialogButtonBox::Ok)->setCursor(QCursor(Qt::PointingHandCursor));
bb->button(QDialogButtonBox::Ok)->setIcon(GET_ICON("dialog-ok"));
hb2->addWidget(bb);
#ifdef Q_OS_WINCE_WM
vb->setMargin(3);
#endif // Q_OS_WINCE_WM
vb->addLayout(hb1);
#ifdef HANDHELD
vb->addWidget(lblSubTitle);
#endif // HANDHELD
tabs->addTab(txtAbout, tr("About"));
tabs->addTab(txtLicense, tr("License"));
tabs->addTab(txtCredits, tr("Credits"));
if (translation != "AUTHORS %1") {
QTextBrowser *txtTranslation = new QTextBrowser(dlg);
// txtTranslation->setWordWrapMode(QTextOption::NoWrap);
txtTranslation->setOpenExternalLinks(true);
txtTranslation->setText(translation);
txtTranslation->moveCursor(QTextCursor::Start);
txtTranslation->setFrameShape(QFrame::NoFrame);
tabs->addTab(txtTranslation, tr("Translation"));
}
#ifndef HANDHELD
tabs->setStyleSheet(QString("QTabWidget::pane {background-color: %1; border-color: %3; border-width: 1px; border-style: solid; border-bottom-left-radius: 4px; border-bottom-right-radius: 4px; padding: 1px;} QTabBar::tab {background-color: %2; border-color: %3; border-width: 1px; border-style: solid; border-bottom: none; border-top-left-radius: 4px; border-top-right-radius: 4px; padding: 2px 6px;} QTabBar::tab:selected {background-color: %4;} QTabBar::tab:!selected {margin-top: 1px;}").arg(palette().base().color().name(), palette().button().color().name(), palette().shadow().color().name(), palette().light().color().name()));
#endif // HANDHELD
vb->addWidget(tabs);
vb->addLayout(hb2);
dlg->setWindowFlags(Qt::Dialog | Qt::CustomizeWindowHint | Qt::WindowTitleHint | Qt::WindowCloseButtonHint);
dlg->setWindowTitle(tr("About %1").arg(QCoreApplication::applicationName()));
dlg->setWindowIcon(GET_ICON("help-about"));
dlg->setLayout(vb);
connect(bb, SIGNAL(accepted()), dlg, SLOT(accept()));
#ifndef HANDHELD
// Adding some eyecandy
if (QtWin::isCompositionEnabled()) {
QtWin::enableBlurBehindWindow(dlg, true);
}
#endif // HANDHELD
#ifndef HANDHELD
dlg->resize(450, 350);
#elif defined(Q_OS_SYMBIAN) || defined(Q_OS_BLACKBERRY)
dlg->setWindowState(Qt::WindowMaximized);
#endif
QApplication::restoreOverrideCursor();
dlg->exec();
delete dlg;
}
void MainWindow::buttonBackToTaskClicked()
{
tabWidget->setCurrentIndex(0);
}
void MainWindow::buttonRandomClicked()
{
QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
tspmodel->randomize();
QApplication::restoreOverrideCursor();
}
void MainWindow::buttonSolveClicked()
{
TSPSolver::TMatrix matrix;
QList<double> row;
int n = spinCities->value();
bool ok;
for (int r = 0; r < n; r++) {
row.clear();
for (int c = 0; c < n; c++) {
row.append(tspmodel->index(r,c).data(Qt::UserRole).toDouble(&ok));
if (!ok) {
QMessageBox::critical(this, tr("Data error"), tr("Error in cell [Row %1; Column %2]: Invalid data format.").arg(r + 1).arg(c + 1));
return;
}
}
matrix.append(row);
}
QProgressDialog pd(this);
QProgressBar *pb = new QProgressBar(&pd);
pb->setAlignment(Qt::AlignCenter);
pb->setFormat(tr("%v of %1 parts found").arg(n));
pd.setBar(pb);
QPushButton *cancel = new QPushButton(&pd);
cancel->setIcon(GET_ICON("dialog-cancel"));
cancel->setText(QCoreApplication::translate("QDialogButtonBox", "Cancel", "No need to translate this. The translation will be taken from Qt translation files."));
pd.setCancelButton(cancel);
pd.setMaximum(n);
pd.setAutoClose(false);
pd.setAutoReset(false);
pd.setLabelText(tr("Calculating optimal route..."));
pd.setWindowTitle(tr("Solution Progress"));
pd.setWindowModality(Qt::ApplicationModal);
pd.setWindowFlags(Qt::Dialog | Qt::CustomizeWindowHint | Qt::WindowTitleHint);
pd.show();
#ifdef Q_OS_WIN32
HRESULT hr = CoCreateInstance(CLSID_TaskbarList, NULL, CLSCTX_INPROC_SERVER, IID_ITaskbarList3, (LPVOID*)&tl);
if (SUCCEEDED(hr)) {
hr = tl->HrInit();
if (FAILED(hr)) {
tl->Release();
tl = NULL;
} else {
tl->SetProgressValue(HWND(winId()), 0, n * 2);
}
}
#endif
TSPSolver::CTSPSolver solver;
solver.setCleanupOnCancel(false);
connect(&solver, SIGNAL(routePartFound(int)), &pd, SLOT(setValue(int)));
connect(&pd, SIGNAL(canceled()), &solver, SLOT(cancel()));
#ifdef Q_OS_WIN32
if (tl != NULL)
connect(&solver, SIGNAL(routePartFound(int)), SLOT(solverRoutePartFound(int)));
#endif
TSPSolver::SStep *root = solver.solve(n, matrix);
#ifdef Q_OS_WIN32
if (tl != NULL)
disconnect(&solver, SIGNAL(routePartFound(int)), this, SLOT(solverRoutePartFound(int)));
#endif
disconnect(&solver, SIGNAL(routePartFound(int)), &pd, SLOT(setValue(int)));
disconnect(&pd, SIGNAL(canceled()), &solver, SLOT(cancel()));
if (!root) {
pd.reset();
if (!solver.wasCanceled()) {
#ifdef Q_OS_WIN32
if (tl != NULL) {
tl->SetProgressState(HWND(winId()), TBPF_ERROR);
}
#endif
QApplication::alert(this);
QMessageBox::warning(this, tr("Solution Result"), tr("Unable to find a solution.\nMaybe, this task has no solution."));
}
pd.setLabelText(tr("Memory cleanup..."));
pd.setMaximum(0);
pd.setCancelButton(NULL);
pd.show();
#ifdef Q_OS_WIN32