source: tspsg/src/mainwindow.cpp @ 1fbf016a09

0.1.3.145-beta1-symbian0.1.4.170-beta2-bb10appveyorimgbotreadme
Last change on this file since 1fbf016a09 was 1fbf016a09, checked in by Oleksii Serdiuk, 14 years ago

+ Added an ability to disable showing of the solution steps' matrices in solution output.

  • Replaced Ok and Cancel buttons in SettingsDialog? with QButtonBox. Now the buttons conform the interface guidelines of the target platform.
  • Increased the allowed maximum number of cities to 50. Solution steps' matrices aren't shown by default if the number of cities in task is more than 15.
  • For WinCE the size of the toolbar buttons is now determined based on the device DPI instead of its resolution.
  • Open and save file dialogs are now using native dialogs where supported.
  • Reworked About dialog a little bit.
  • Property mode set to 100644
File size: 26.3 KB
RevLine 
[ec54b4490b]1/*
[430bd7f7e9]2 *  TSPSG: TSP Solver and Generator
[5354a01311]3 *  Copyright (C) 2007-2009 Lёppa <contacts[at]oleksii[dot]name>
[003e4193be]4 *
[bb994a7ff8]5 *  $Id$
6 *  $URL$
[5515c2c2a7]7 *
[bb994a7ff8]8 *  This file is part of TSPSG.
[5515c2c2a7]9 *
[bb994a7ff8]10 *  TSPSG is free software: you can redistribute it and/or modify
11 *  it under the terms of the GNU General Public License as published by
12 *  the Free Software Foundation, either version 3 of the License, or
13 *  (at your option) any later version.
[5515c2c2a7]14 *
[bb994a7ff8]15 *  TSPSG is distributed in the hope that it will be useful,
16 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
17 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 *  GNU General Public License for more details.
[5515c2c2a7]19 *
[bb994a7ff8]20 *  You should have received a copy of the GNU General Public License
21 *  along with TSPSG.  If not, see <http://www.gnu.org/licenses/>.
[5515c2c2a7]22 */
23
24#include "mainwindow.h"
25
[caef58b531]26/*!
27 * \brief Class constructor.
28 * \param parent Main Window parent widget.
29 *
30 *  Initializes Main Window and creates its layout based on target OS.
31 *  Loads TSPSG settings and opens a task file if it was specified as a commandline parameter.
32 */
[5515c2c2a7]33MainWindow::MainWindow(QWidget *parent)
[aecdf994f9]34        : QMainWindow(parent)
[5515c2c2a7]35{
[665d32434f]36        settings = new QSettings(QSettings::IniFormat,QSettings::UserScope,"TSPSG","tspsg");
[899d1b8e15]37        loadLanguage();
38        setupUi(this);
[c10297cf73]39#ifndef Q_OS_WINCE
40QStatusBar *statusbar = new QStatusBar(this);
41        statusbar->setObjectName("statusbar");
42        setStatusBar(statusbar);
43#endif // Q_OS_WINCE
[430bd7f7e9]44        initDocStyleSheet();
45        solutionText->document()->setDefaultFont(settings->value("Output/Font",QFont(DEF_FONT_FAMILY,DEF_FONT_SIZE)).value<QFont>());
46        solutionText->setTextColor(settings->value("Output/Color",DEF_FONT_COLOR).value<QColor>());
47        solutionText->setWordWrapMode(QTextOption::WordWrap);
[134a9158bd]48#ifdef Q_OS_WINCE
[1fbf016a09]49        // A little hack for toolbar icons to have a sane size.
50        toolBar->setIconSize(QSize(logicalDpiX() / 4, logicalDpiY() / 4));
[134a9158bd]51#endif
[c10297cf73]52#ifndef QT_NO_PRINTER
[56dca709c9]53        printer = new QPrinter(QPrinter::HighResolution);
[c10297cf73]54#endif // QT_NO_PRINTER
[899d1b8e15]55        groupSettingsLanguageList = new QActionGroup(this);
[ac4cb71650]56        actionSettingsLanguageEnglish->setData("en");
57        actionSettingsLanguageEnglish->setActionGroup(groupSettingsLanguageList);
[899d1b8e15]58        loadLangList();
[aaf2113307]59        spinCities->setMaximum(MAX_NUM_CITIES);
[899d1b8e15]60        actionSettingsLanguageAutodetect->setChecked(settings->value("Language","").toString().isEmpty());
61        connect(actionFileNew,SIGNAL(triggered()),this,SLOT(actionFileNewTriggered()));
[993d5af6f6]62        connect(actionFileOpen,SIGNAL(triggered()),this,SLOT(actionFileOpenTriggered()));
[aaf2113307]63        connect(actionFileSave,SIGNAL(triggered()),this,SLOT(actionFileSaveTriggered()));
[430bd7f7e9]64        connect(actionFileSaveAsTask,SIGNAL(triggered()),this,SLOT(actionFileSaveAsTaskTriggered()));
65        connect(actionFileSaveAsSolution,SIGNAL(triggered()),this,SLOT(actionFileSaveAsSolutionTriggered()));
[899d1b8e15]66        connect(actionSettingsPreferences,SIGNAL(triggered()),this,SLOT(actionSettingsPreferencesTriggered()));
67        connect(actionSettingsLanguageAutodetect,SIGNAL(triggered(bool)),this,SLOT(actionSettingsLanguageAutodetectTriggered(bool)));
68        connect(groupSettingsLanguageList,SIGNAL(triggered(QAction *)),this,SLOT(groupSettingsLanguageListTriggered(QAction *)));
[690f6939a7]69        connect(actionHelpAboutQt,SIGNAL(triggered()),qApp,SLOT(aboutQt()));
[899d1b8e15]70        connect(actionHelpAbout,SIGNAL(triggered()),this,SLOT(actionHelpAboutTriggered()));
[c10297cf73]71#ifndef QT_NO_PRINTER
72        menuFile->insertAction(actionFileExit,actionFilePrintPreview);
73        menuFile->insertAction(actionFileExit,actionFilePrint);
74        menuFile->insertSeparator(actionFileExit);
75        toolBar->insertAction(actionSettingsPreferences,actionFilePrint);
[56dca709c9]76        connect(actionFilePrintPreview,SIGNAL(triggered()),this,SLOT(actionFilePrintPreviewTriggered()));
77        connect(actionFilePrint,SIGNAL(triggered()),this,SLOT(actionFilePrintTriggered()));
[c10297cf73]78#endif // QT_NO_PRINTER
[899d1b8e15]79        connect(buttonSolve,SIGNAL(clicked()),this,SLOT(buttonSolveClicked()));
80        connect(buttonRandom,SIGNAL(clicked()),this,SLOT(buttonRandomClicked()));
[aaf2113307]81        connect(buttonBackToTask,SIGNAL(clicked()),this,SLOT(buttonBackToTaskClicked()));
[899d1b8e15]82        connect(spinCities,SIGNAL(valueChanged(int)),this,SLOT(spinCitiesValueChanged(int)));
[134a9158bd]83        setCentralWidget(tabWidget);
[0ac9690913]84
85        if (settings->value("SavePos", false).toBool()) {
[aecdf994f9]86                // Loading of saved window state
[665d32434f]87                settings->beginGroup("MainWindow");
[0ac9690913]88#ifndef Q_OS_WINCE
89                restoreGeometry(settings->value("Geometry").toByteArray());
90#endif // Q_OS_WINCE
91                restoreState(settings->value("State").toByteArray());
[665d32434f]92                settings->endGroup();
[0ac9690913]93#ifndef Q_OS_WINCE
[aecdf994f9]94        } else {
95                // Centering main window
[0ac9690913]96QRect rect = geometry();
[aecdf994f9]97                rect.moveCenter(QApplication::desktop()->availableGeometry(this).center());
98                setGeometry(rect);
[5354a01311]99#endif // Q_OS_WINCE
[0ac9690913]100        }
101
[fc9f661ded]102        qsrand(QDateTime().currentDateTime().toTime_t());
[0ac9690913]103        tspmodel = new CTSPModel(this);
[56dca709c9]104        taskView->setModel(tspmodel);
[993d5af6f6]105        connect(tspmodel,SIGNAL(numCitiesChanged(int)),this,SLOT(numCitiesChanged(int)));
[2fb523720a]106        connect(tspmodel,SIGNAL(dataChanged(const QModelIndex &, const QModelIndex &)),this,SLOT(dataChanged(const QModelIndex &, const QModelIndex &)));
[690f6939a7]107        connect(tspmodel,SIGNAL(layoutChanged()),this,SLOT(dataChanged()));
[aaf2113307]108        if ((QCoreApplication::arguments().count() > 1) && (tspmodel->loadTask(QCoreApplication::arguments().at(1))))
[b424a7e320]109                setFileName(QCoreApplication::arguments().at(1));
[aaf2113307]110        else {
[b424a7e320]111                setFileName();
[aaf2113307]112                spinCities->setValue(settings->value("NumCities",DEF_NUM_CITIES).toInt());
[56dca709c9]113                spinCitiesValueChanged(spinCities->value());
[aaf2113307]114        }
115        setWindowModified(false);
[003e4193be]116}
[052d1b9331]117
[e0fcac5f2c]118/* Privates **********************************************************/
[899d1b8e15]119
120void MainWindow::actionFileNewTriggered()
121{
[b424a7e320]122        if (!maybeSave())
123                return;
[c10297cf73]124        QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
[899d1b8e15]125        tspmodel->clear();
[b424a7e320]126        setFileName();
[690f6939a7]127        setWindowModified(false);
[430bd7f7e9]128        tabWidget->setCurrentIndex(0);
129        solutionText->clear();
[1fbf016a09]130        toggleSolutionActions(false);
[c10297cf73]131        QApplication::restoreOverrideCursor();
[899d1b8e15]132}
133
[993d5af6f6]134void MainWindow::actionFileOpenTriggered()
135{
[b424a7e320]136        if (!maybeSave())
137                return;
[1fbf016a09]138
[993d5af6f6]139QStringList filters(trUtf8("All Supported Formats") + " (*.tspt *.zkt)");
[b424a7e320]140        filters.append(trUtf8("%1 Task Files").arg("TSPSG") + " (*.tspt)");
141        filters.append(trUtf8("%1 Task Files").arg("ZKomModRd") + " (*.zkt)");
[993d5af6f6]142        filters.append(trUtf8("All Files") + " (*)");
[1fbf016a09]143
144QString file = QFileDialog::getOpenFileName(this, trUtf8("Task Load"), QString(), filters.join(";;"));
145        if (file.isEmpty() || !QFileInfo(file).isFile())
[b424a7e320]146                return;
[1fbf016a09]147        if (!tspmodel->loadTask(file))
[993d5af6f6]148                return;
[1fbf016a09]149        setFileName(file);
[b424a7e320]150        tabWidget->setCurrentIndex(0);
[690f6939a7]151        setWindowModified(false);
[430bd7f7e9]152        solutionText->clear();
[1fbf016a09]153        toggleSolutionActions(false);
[993d5af6f6]154}
155
[aaf2113307]156void MainWindow::actionFileSaveTriggered()
157{
158        if ((fileName == trUtf8("Untitled") + ".tspt") || (!fileName.endsWith(".tspt",Qt::CaseInsensitive)))
159                saveTask();
[244c614c6b]160        else
[aaf2113307]161                if (tspmodel->saveTask(fileName))
162                        setWindowModified(false);
163}
164
[430bd7f7e9]165void MainWindow::actionFileSaveAsTaskTriggered()
[993d5af6f6]166{
[690f6939a7]167        saveTask();
168}
169
[430bd7f7e9]170void MainWindow::actionFileSaveAsSolutionTriggered()
171{
172static QString selectedFile;
[1fbf016a09]173        if (selectedFile.isEmpty()) {
174                if (fileName == trUtf8("Untitled") + ".tspt") {
175#ifndef QT_NO_PRINTER
176                        selectedFile = "solution.pdf";
177#else
178                        selectedFile = "solution.html";
179#endif // QT_NO_PRINTER
180                } else {
[6dfdef0c3e]181#ifndef QT_NO_PRINTER
[1fbf016a09]182                        selectedFile = QFileInfo(fileName).canonicalPath() + "/" + QFileInfo(fileName).completeBaseName() + ".pdf";
[6dfdef0c3e]183#else
[1fbf016a09]184                        selectedFile = QFileInfo(fileName).canonicalPath() + "/" + QFileInfo(fileName).completeBaseName() + ".html";
[6dfdef0c3e]185#endif // QT_NO_PRINTER
[1fbf016a09]186                }
187        }
188
[6dfdef0c3e]189QStringList filters;
190#ifndef QT_NO_PRINTER
[1fbf016a09]191        filters.append(trUtf8("PDF Files") + " (*.pdf)");
[6dfdef0c3e]192#endif
193        filters.append(trUtf8("HTML Files") + " (*.html *.htm)");
[ec54b4490b]194#if QT_VERSION >= 0x040500
[430bd7f7e9]195        filters.append(trUtf8("OpenDocument Files") + " (*.odt)");
[ec54b4490b]196#endif // QT_VERSION >= 0x040500
[430bd7f7e9]197        filters.append(trUtf8("All Files") + " (*)");
[1fbf016a09]198
199QString file = QFileDialog::getSaveFileName(this, QString(), selectedFile, filters.join(";;"));
200        if (file.isEmpty())
[430bd7f7e9]201                return;
[1fbf016a09]202        selectedFile = file;
[f44855d99e]203        QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
[6dfdef0c3e]204#ifndef QT_NO_PRINTER
205        if (selectedFile.endsWith(".pdf",Qt::CaseInsensitive)) {
206QPrinter printer(QPrinter::HighResolution);
207                printer.setOutputFormat(QPrinter::PdfFormat);
208                printer.setOutputFileName(selectedFile);
209                solutionText->document()->print(&printer);
210                QApplication::restoreOverrideCursor();
211                return;
212        }
213#endif
[ec54b4490b]214#if QT_VERSION >= 0x040500
[430bd7f7e9]215QTextDocumentWriter dw(selectedFile);
216        if (!(selectedFile.endsWith(".htm",Qt::CaseInsensitive) || selectedFile.endsWith(".html",Qt::CaseInsensitive) || selectedFile.endsWith(".odt",Qt::CaseInsensitive) || selectedFile.endsWith(".txt",Qt::CaseInsensitive)))
217                dw.setFormat("plaintext");
218        dw.write(solutionText->document());
[ec54b4490b]219#else
220        // Qt < 4.5 has no QTextDocumentWriter class
221QFile file(selectedFile);
[f44855d99e]222        if (!file.open(QFile::WriteOnly)) {
223                QApplication::restoreOverrideCursor();
[ec54b4490b]224                return;
[f44855d99e]225        }
[ec54b4490b]226QTextStream ts(&file);
227        ts.setCodec(QTextCodec::codecForName("UTF-8"));
228        ts << solutionText->document()->toHtml("UTF-8");
[f44855d99e]229        file.close();
[ec54b4490b]230#endif // QT_VERSION >= 0x040500
[f44855d99e]231        QApplication::restoreOverrideCursor();
[430bd7f7e9]232}
233
[c10297cf73]234#ifndef QT_NO_PRINTER
[56dca709c9]235void MainWindow::actionFilePrintPreviewTriggered()
236{
237QPrintPreviewDialog ppd(printer, this);
238    connect(&ppd,SIGNAL(paintRequested(QPrinter *)),SLOT(printPreview(QPrinter *)));
239    ppd.exec();
240}
241
242void MainWindow::actionFilePrintTriggered()
[5354a01311]243{
[899d1b8e15]244QPrintDialog pd(printer,this);
[140912822f]245#if QT_VERSION >= 0x040500
246        // No such methods in Qt < 4.5
[899d1b8e15]247        pd.setOption(QAbstractPrintDialog::PrintSelection,false);
248        pd.setOption(QAbstractPrintDialog::PrintPageRange,false);
[140912822f]249#endif
[56dca709c9]250        if (pd.exec() != QDialog::Accepted)
251                return;
[c10297cf73]252        QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
[56dca709c9]253        solutionText->document()->print(printer);
[c10297cf73]254        QApplication::restoreOverrideCursor();
[5354a01311]255}
[c10297cf73]256#endif // QT_NO_PRINTER
[5354a01311]257
[e0fcac5f2c]258void MainWindow::actionSettingsPreferencesTriggered()
[bb994a7ff8]259{
[e0fcac5f2c]260SettingsDialog sd(this);
261        if (sd.exec() != QDialog::Accepted)
262                return;
263        if (sd.colorChanged() || sd.fontChanged()) {
264                initDocStyleSheet();
265                if (!output.isEmpty() && sd.colorChanged() && (QMessageBox(QMessageBox::Question,trUtf8("Settings Changed"),trUtf8("You have changed color settings.\nDo you wish to apply them to current solution text?"),QMessageBox::Yes | QMessageBox::No,this).exec() == QMessageBox::Yes)) {
266                        QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
267                        solutionText->clear();
268                        solutionText->setHtml(output.join(""));
269                        QApplication::restoreOverrideCursor();
270                }
271        }
272}
273
274void MainWindow::actionSettingsLanguageAutodetectTriggered(bool checked)
275{
276        if (checked) {
277                settings->remove("Language");
278                QMessageBox(QMessageBox::Information,trUtf8("Language change"),trUtf8("Language will be autodetected on next application start."),QMessageBox::Ok,this).exec();
279        } else
280                settings->setValue("Language",groupSettingsLanguageList->checkedAction()->data().toString());
281}
282
283void MainWindow::groupSettingsLanguageListTriggered(QAction *action)
284{
285        if (actionSettingsLanguageAutodetect->isChecked()) {
286                // We have language autodetection. It needs to be disabled to change language.
287                if (QMessageBox(QMessageBox::Question,trUtf8("Language change"),trUtf8("You have language autodetection turned on.\nIt needs to be off.\nDo you wish to turn it off?"),QMessageBox::Yes | QMessageBox::No,this).exec() == QMessageBox::Yes) {
288                        actionSettingsLanguageAutodetect->trigger();
289                } else
290                        return;
291        }
292bool untitled = (fileName == trUtf8("Untitled") + ".tspt");
293        if (loadLanguage(action->data().toString())) {
294                settings->setValue("Language",action->data().toString());
295                retranslateUi(this);
296                if (untitled)
297                        setFileName();
298        }
299}
300
301void MainWindow::actionHelpAboutTriggered()
302{
303//! \todo TODO: Normal about window :-)
[1fbf016a09]304QString title;
305#ifdef Q_OS_WINCE
306        title += QString::fromUtf8("<b>TSPSG<br>TSP Solver and Generator</b><br>");
307#else
308        title += QString::fromUtf8("<b>TSPSG: TSP Solver and Generator</b><br>");
309#endif // Q_OS_WINCE
310        title += QString::fromUtf8("Version: <b>"BUILD_VERSION"</b><br>");
311        title += QString::fromUtf8("<b>&copy; 2007-%1 Lёppa</b><br>").arg(QDate::currentDate().toString("yyyy"));
312        title += QString::fromUtf8("<b><a href=\"http://tspsg.sourceforge.net/\">http://tspsg.sf.net/</a></b><br>");
313QString about;
[f0464480db]314        about += QString::fromUtf8("Target OS: <b>%1</b><br>").arg(OS);
[1fbf016a09]315#ifndef STATIC_BUILD
316        about += "Qt library (shared):<br>";
[f0464480db]317        about += QString::fromUtf8("&nbsp;&nbsp;&nbsp;&nbsp;Build time: <b>%1</b><br>").arg(QT_VERSION_STR);
318        about += QString::fromUtf8("&nbsp;&nbsp;&nbsp;&nbsp;Runtime: <b>%1</b><br>").arg(qVersion());
[1fbf016a09]319#else
320        about += QString::fromUtf8("Qt library: <b>%1</b> (static)<br>").arg(QT_VERSION_STR);
321#endif // STATIC_BUILD
[f0464480db]322        about += QString::fromUtf8("Built on <b>%1</b> at <b>%2</b><br>").arg(__DATE__).arg(__TIME__);
[1fbf016a09]323        about += "<br>";
[f0464480db]324        about += QString::fromUtf8("Id: <b>"VERSIONID"</b><br>");
325        about += QString::fromUtf8("Algorithm: <b>%1</b><br>").arg(CTSPSolver::getVersionId());
326        about += "<br>";
327        about += "TSPSG is free software: you can redistribute it and/or modify it<br>"
328                "under the terms of the GNU General Public License as published<br>"
329                "by the Free Software Foundation, either version 3 of the License,<br>"
330                "or (at your option) any later version.<br>"
331                "<br>"
332                "TSPSG is distributed in the hope that it will be useful, but<br>"
333                "WITHOUT ANY WARRANTY; without even the implied warranty of<br>"
334                "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the<br>"
335                "GNU General Public License for more details.<br>"
336                "<br>"
337                "You should have received a copy of the GNU General Public License<br>"
338                "along with TSPSG.  If not, see <a href=\"http://www.gnu.org/licenses/\">http://www.gnu.org/licenses/</a>.";
339
340QDialog *dlg = new QDialog(this);
[1fbf016a09]341QLabel *lblIcon = new QLabel(dlg),
342        *lblTitle = new QLabel(dlg);
[f0464480db]343QTextBrowser *txtAbout = new QTextBrowser(dlg);
[1fbf016a09]344QVBoxLayout *vb = new QVBoxLayout();
[f0464480db]345QHBoxLayout *hb = new QHBoxLayout();
346QDialogButtonBox *bb = new QDialogButtonBox(QDialogButtonBox::Ok, Qt::Horizontal, dlg);
347
[1fbf016a09]348        lblIcon->setPixmap(QPixmap(":/images/tspsg.png").scaledToWidth(logicalDpiX() * 2 / 3, Qt::SmoothTransformation));
349        lblIcon->setAlignment(Qt::AlignTop);
350        lblTitle->setText(title);
[f0464480db]351
[1fbf016a09]352        hb->addWidget(lblIcon);
353        hb->addWidget(lblTitle);
354        hb->addStretch();
[f0464480db]355
356//      txtAbout->setTextInteractionFlags(txtAbout->textInteractionFlags() ^ Qt::TextEditable);
357        txtAbout->setWordWrapMode(QTextOption::NoWrap);
358        txtAbout->setOpenExternalLinks(true);
359        txtAbout->setHtml(about);
360        txtAbout->moveCursor(QTextCursor::Start);
361
[1fbf016a09]362        vb->addLayout(hb);
363        vb->addWidget(txtAbout);
364        vb->addWidget(bb);
[f0464480db]365
[1fbf016a09]366        dlg->setWindowFlags(Qt::Dialog | Qt::CustomizeWindowHint | Qt::WindowTitleHint | Qt::WindowCloseButtonHint);
[f0464480db]367        dlg->setWindowTitle(trUtf8("About TSPSG"));
[1fbf016a09]368        dlg->setLayout(vb);
[f0464480db]369
370        connect(bb, SIGNAL(accepted()), dlg, SLOT(accept()));
371
[1fbf016a09]372        dlg->resize(410, 300);
[f0464480db]373        dlg->exec();
374
375        delete dlg;
[aaf2113307]376}
377
378void MainWindow::buttonBackToTaskClicked()
379{
380        tabWidget->setCurrentIndex(0);
[bb994a7ff8]381}
382
[e0fcac5f2c]383void MainWindow::buttonRandomClicked()
[430bd7f7e9]384{
[e0fcac5f2c]385        QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
386        tspmodel->randomize();
387        QApplication::restoreOverrideCursor();
[430bd7f7e9]388}
389
[899d1b8e15]390void MainWindow::buttonSolveClicked()
[bb994a7ff8]391{
[f0464480db]392TMatrix matrix;
[430bd7f7e9]393QList<double> row;
[2bc8e278b7]394int n = spinCities->value();
[e664262f7d]395bool ok;
[2bc8e278b7]396        for (int r = 0; r < n; r++) {
[430bd7f7e9]397                row.clear();
[2bc8e278b7]398                for (int c = 0; c < n; c++) {
[430bd7f7e9]399                        row.append(tspmodel->index(r,c).data(Qt::UserRole).toDouble(&ok));
[2bc8e278b7]400                        if (!ok) {
[b424a7e320]401                                QMessageBox(QMessageBox::Critical,trUtf8("Data error"),trUtf8("Error in cell [Row %1; Column %2]: Invalid data format.").arg(r + 1).arg(c + 1),QMessageBox::Ok,this).exec();
[2bc8e278b7]402                                return;
[e664262f7d]403                        }
404                }
405                matrix.append(row);
406        }
407CTSPSolver solver;
[f0464480db]408SStep *root = solver.solve(n,matrix,this);
[e664262f7d]409        if (!root)
[430bd7f7e9]410                return;
411        QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
412QColor color = settings->value("Output/Color",DEF_FONT_COLOR).value<QColor>();
413        output.clear();
414        output.append("<p>" + trUtf8("Variant #%1").arg(spinVariant->value()) + "</p>");
415        output.append("<p>" + trUtf8("Task:") + "</p>");
[1fbf016a09]416        outputMatrix(matrix, output);
[430bd7f7e9]417        output.append("<hr>");
418        output.append("<p>" + trUtf8("Solution of Variant #%1 task").arg(spinVariant->value()) + "</p>");
[f0464480db]419SStep *step = root;
[430bd7f7e9]420        n = 1;
421        while (n <= spinCities->value()) {
[f0464480db]422                if (step->prNode->prNode != NULL || ((step->prNode->prNode == NULL) && (step->plNode->prNode == NULL))) {
[430bd7f7e9]423                        if (n != spinCities->value()) {
424                                output.append("<p>" + trUtf8("Step #%1").arg(n++) + "</p>");
[1fbf016a09]425                                if (settings->value("Output/ShowMatrix", DEF_SHOW_MATRIX).toBool() && settings->value("Output/UseShowMatrixLimit", DEF_USE_SHOW_MATRIX_LIMIT).toBool() && (spinCities->value() <= settings->value("Output/ShowMatrixCitiesLimit", DEF_SHOW_MATRIX_CITY_LIMIT).toInt())) {
426                                        outputMatrix(*step, output);
427                                }
[f0464480db]428                                output.append("<p>" + trUtf8("Selected candidate for branching: %1.").arg(trUtf8("(%1;%2)").arg(step->candidate.nRow + 1).arg(step->candidate.nCol + 1)) + "</p>");
429                                if (!step->alts.empty()) {
[fcaa74f7d7]430SCandidate cand;
[f0464480db]431QString alts;
432                                        foreach(cand, step->alts) {
433                                                if (!alts.isEmpty())
434                                                        alts += ", ";
435                                                alts += trUtf8("(%1;%2)").arg(cand.nRow + 1).arg(cand.nCol + 1);
436                                        }
437                                        output.append("<p class=\"hasalts\">" + trUtf8("%n alternate candidate(s) for branching: %1.","",step->alts.count()).arg(alts) + "</p>");
438                                }
[430bd7f7e9]439                                output.append("<p>&nbsp;</p>");
440                        }
441                }
442                if (step->prNode->prNode != NULL)
443                        step = step->prNode;
444                else if (step->plNode->prNode != NULL)
445                        step = step->plNode;
446                else
447                        break;
448        }
[9cf98b9bd6]449        if (solver.isOptimal())
450                output.append("<p>" + trUtf8("Optimal path:") + "</p>");
451        else
452                output.append("<p>" + trUtf8("Resulting path:") + "</p>");
453        output.append("<p>&nbsp;&nbsp;" + solver.getSortedPath() + "</p>");
[430bd7f7e9]454        output.append("<p>" + trUtf8("The price is <b>%1</b> units.").arg(step->price) + "</p>");
[9cf98b9bd6]455        if (!solver.isOptimal()) {
456                output.append("<p>&nbsp;</p>");
457                output.append("<p>" + trUtf8("<b>WARNING!!!</b><br>This result is a record, but it may not be optimal.<br>Iterations need to be continued to check whether this result is optimal or get an optimal one.") + "</p>");
458        }
[caef58b531]459        output.append("<p></p>");
[1fbf016a09]460
[430bd7f7e9]461        solutionText->setHtml(output.join(""));
462        solutionText->setDocumentTitle(trUtf8("Solution of Variant #%1 task").arg(spinVariant->value()));
[caef58b531]463
464        // Scrolling to the end of text.
[f0464480db]465        solutionText->moveCursor(QTextCursor::End);
[caef58b531]466
[1fbf016a09]467        toggleSolutionActions();
[430bd7f7e9]468        tabWidget->setCurrentIndex(1);
469        QApplication::restoreOverrideCursor();
[bb994a7ff8]470}
[aecdf994f9]471
[e0fcac5f2c]472void MainWindow::dataChanged()
[aecdf994f9]473{
[e0fcac5f2c]474        setWindowModified(true);
475}
476
477void MainWindow::dataChanged(const QModelIndex &tl, const QModelIndex &br)
478{
479        setWindowModified(true);
480        if (settings->value("Autosize",true).toBool()) {
481                for (int k = tl.row(); k <= br.row(); k++)
482                        taskView->resizeRowToContents(k);
483                for (int k = tl.column(); k <= br.column(); k++)
484                        taskView->resizeColumnToContents(k);
485        }
486}
487
488void MainWindow::numCitiesChanged(int nCities)
489{
490        blockSignals(true);
491        spinCities->setValue(nCities);
492        blockSignals(false);
493}
494
495#ifndef QT_NO_PRINTER
496void MainWindow::printPreview(QPrinter *printer)
497{
498        solutionText->print(printer);
499}
500#endif // QT_NO_PRINTER
501
502void MainWindow::spinCitiesValueChanged(int n)
503{
504int count = tspmodel->numCities();
505        tspmodel->setNumCities(n);
506        if ((n > count) && settings->value("Autosize",true).toBool())
507                for (int k = count; k < n; k++) {
508                        taskView->resizeColumnToContents(k);
509                        taskView->resizeRowToContents(k);
510                }
511}
512
[0ac9690913]513void MainWindow::closeEvent(QCloseEvent *ev)
[f383cb181c]514{
515        if (!maybeSave()) {
[0ac9690913]516                ev->ignore();
[f383cb181c]517                return;
518        }
[0ac9690913]519        settings->setValue("NumCities", spinCities->value());
520
521        // Saving Main Window state
522        if (settings->value("SavePos", false).toBool()) {
[f383cb181c]523                settings->beginGroup("MainWindow");
[0ac9690913]524#ifndef Q_OS_WINCE
525                settings->setValue("Geometry", saveGeometry());
526#endif // Q_OS_WINCE
527                settings->setValue("State", saveState());
[f383cb181c]528                settings->endGroup();
529        }
[0ac9690913]530
531        QMainWindow::closeEvent(ev);
[f383cb181c]532}
533
[e0fcac5f2c]534void MainWindow::initDocStyleSheet()
535{
536QColor color = settings->value("Output/Color",DEF_FONT_COLOR).value<QColor>();
537QColor hilight;
538        if (color.value() < 192)
539                hilight.setHsv(color.hue(),color.saturation(),127 + qRound(color.value() / 2));
540        else
541                hilight.setHsv(color.hue(),color.saturation(),color.value() / 2);
542        solutionText->document()->setDefaultStyleSheet("* {color: " + color.name() +";} p {margin: 0px 10px;} table {margin: 5px;} td {padding: 1px 5px;} .hasalts {color: " + hilight.name() + ";} .selected {color: #A00000; font-weight: bold;} .alternate {color: #008000; font-weight: bold;}");
543        solutionText->document()->setDefaultFont(settings->value("Output/Font",QFont(DEF_FONT_FAMILY,DEF_FONT_SIZE)).value<QFont>());
[aecdf994f9]544}
545
[899d1b8e15]546void MainWindow::loadLangList()
547{
[2fb523720a]548QSettings langinfo(PATH_I18N"/languages.ini",QSettings::IniFormat);
[140912822f]549#if QT_VERSION >= 0x040500
550        // In Qt < 4.5 QSettings doesn't have method setIniCodec.
[899d1b8e15]551        langinfo.setIniCodec("UTF-8");
[140912822f]552#endif
[2fb523720a]553QDir dir(PATH_I18N,"*.qm",QDir::Name | QDir::IgnoreCase,QDir::Files);
[899d1b8e15]554        if (!dir.exists())
555                return;
556QFileInfoList langs = dir.entryInfoList();
557        if (langs.size() <= 0)
558                return;
559QAction *a;
560        for (int k = 0; k < langs.size(); k++) {
561                QFileInfo lang = langs.at(k);
[ac4cb71650]562                if (!lang.completeBaseName().startsWith("qt_") && lang.completeBaseName().compare("en")) {
[140912822f]563#if QT_VERSION >= 0x040500
[899d1b8e15]564                        a = menuSettingsLanguage->addAction(langinfo.value(lang.completeBaseName() + "/NativeName",lang.completeBaseName()).toString());
[140912822f]565#else
566                        // We use Name if Qt < 4.5 because NativeName is in UTF-8, QSettings
567                        // reads .ini file as ASCII and there is no way to set file encoding.
568                        a = menuSettingsLanguage->addAction(langinfo.value(lang.completeBaseName() + "/Name",lang.completeBaseName()).toString());
569#endif
[899d1b8e15]570                        a->setData(lang.completeBaseName());
571                        a->setCheckable(true);
572                        a->setActionGroup(groupSettingsLanguageList);
573                        if (settings->value("Language",QLocale::system().name()).toString().startsWith(lang.completeBaseName()))
574                                a->setChecked(true);
575                }
576        }
577}
578
[0ac9690913]579bool MainWindow::loadLanguage(const QString &lang)
[899d1b8e15]580{
[e0fcac5f2c]581// i18n
582bool ad = false;
[0ac9690913]583QString lng = lang;
584        if (lng.isEmpty()) {
[e0fcac5f2c]585                ad = settings->value("Language","").toString().isEmpty();
[0ac9690913]586                lng = settings->value("Language",QLocale::system().name()).toString();
[899d1b8e15]587        }
[e0fcac5f2c]588static QTranslator *qtTranslator; // Qt library translator
589        if (qtTranslator) {
590                qApp->removeTranslator(qtTranslator);
591                delete qtTranslator;
592                qtTranslator = NULL;
[899d1b8e15]593        }
[e0fcac5f2c]594static QTranslator *translator; // Application translator
595        if (translator) {
596                qApp->removeTranslator(translator);
597                delete translator;
[690f6939a7]598        }
[e0fcac5f2c]599        translator = new QTranslator();
[f0464480db]600        if ((lng.compare("en") != 0) && !lng.startsWith("en_")) {
[e0fcac5f2c]601                // Trying to load system Qt library translation...
[f0464480db]602                qtTranslator = new QTranslator();
[0ac9690913]603                if (qtTranslator->load("qt_" + lng,QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
[e0fcac5f2c]604                        qApp->installTranslator(qtTranslator);
[f0464480db]605                else {
606                        // No luck. Let's try to load a bundled one.
[0ac9690913]607                        if (qtTranslator->load("qt_" + lng,PATH_I18N))
[e0fcac5f2c]608                                qApp->installTranslator(qtTranslator);
609                        else {
610                                // Qt library translation unavailable
611                                delete qtTranslator;
612                                qtTranslator = NULL;
613                        }
[f0464480db]614                }
615        }
616        // Now let's load application translation.
617        if (translator->load(lng,PATH_I18N))
618                qApp->installTranslator(translator);
619        else {
620                delete translator;
621                translator = NULL;
622                if ((lng.compare("en") != 0) && !lng.startsWith("en_")) {
[e0fcac5f2c]623                        if (!ad)
624                                QMessageBox(QMessageBox::Warning,trUtf8("Language Change"),trUtf8("Unable to load translation language."),QMessageBox::Ok,this).exec();
625                        return false;
[aecdf994f9]626                }
627        }
[e0fcac5f2c]628        return true;
[aecdf994f9]629}
[993d5af6f6]630
[e0fcac5f2c]631bool MainWindow::maybeSave()
[690f6939a7]632{
[e0fcac5f2c]633        if (!isWindowModified())
634                return true;
635int res = QMessageBox(QMessageBox::Warning,trUtf8("Unsaved Changes"),trUtf8("Would you like to save changes in current task?"),QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel,this).exec();
636        if (res == QMessageBox::Save)
637                return saveTask();
638        else if (res == QMessageBox::Cancel)
639                return false;
640        else
641                return true;
[690f6939a7]642}
643
[f0464480db]644void MainWindow::outputMatrix(const TMatrix &matrix, QStringList &output)
[2fb523720a]645{
[e0fcac5f2c]646int n = spinCities->value();
647QString line="";
648        output.append("<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\">");
649        for (int r = 0; r < n; r++) {
650                line = "<tr>";
651                for (int c = 0; c < n; c++) {
[0ac9690913]652                        if (matrix.at(r).at(c) == INFINITY)
[e0fcac5f2c]653                                line += "<td align=\"center\">"INFSTR"</td>";
654                        else
[0ac9690913]655                                line += "<td align=\"center\">" + QVariant(matrix.at(r).at(c)).toString() + "</td>";
[e0fcac5f2c]656                }
657                line += "</tr>";
658                output.append(line);
[f0464480db]659        }
660        output.append("</table>");
661}
662
663void MainWindow::outputMatrix(const SStep &step, QStringList &output)
664{
665int n = spinCities->value();
666QString line="";
667        output.append("<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\">");
668        for (int r = 0; r < n; r++) {
669                line = "<tr>";
670                for (int c = 0; c < n; c++) {
671                        if (step.matrix.at(r).at(c) == INFINITY)
672                                line += "<td align=\"center\">"INFSTR"</td>";
673                        else if ((r == step.candidate.nRow) && (c == step.candidate.nCol))
674                                line += "<td align=\"center\" class=\"selected\">" + QVariant(step.matrix.at(r).at(c)).toString() + "</td>";
675                        else {
[fcaa74f7d7]676SCandidate cand;
[f0464480db]677                                cand.nRow = r;
678                                cand.nCol = c;
679                                if (step.alts.contains(cand))
680                                        line += "<td align=\"center\" class=\"alternate\">" + QVariant(step.matrix.at(r).at(c)).toString() + "</td>";
681                                else
682                                        line += "<td align=\"center\">" + QVariant(step.matrix.at(r).at(c)).toString() + "</td>";
683                        }
684                }
685                line += "</tr>";
686                output.append(line);
[2fb523720a]687        }
[e0fcac5f2c]688        output.append("</table>");
[2fb523720a]689}
690
[e0fcac5f2c]691bool MainWindow::saveTask() {
692QStringList filters(trUtf8("%1 Task File").arg("TSPSG") + " (*.tspt)");
693        filters.append(trUtf8("All Files") + " (*)");
[1fbf016a09]694QString file;
695        if (fileName.endsWith(".tspt", Qt::CaseInsensitive))
696                file = fileName;
[e0fcac5f2c]697        else
[1fbf016a09]698                file = QFileInfo(fileName).canonicalPath() + "/" + QFileInfo(fileName).completeBaseName() + ".tspt";
699
700        file = QFileDialog::getSaveFileName(this, trUtf8("Task Save"), file, filters.join(";;"));
701        if (file.isEmpty())
[e0fcac5f2c]702                return false;
[1fbf016a09]703        if (tspmodel->saveTask(file)) {
704                setFileName(file);
[e0fcac5f2c]705                setWindowModified(false);
706                return true;
707        }
708        return false;
709}
710
[0ac9690913]711void MainWindow::setFileName(const QString &fileName)
[993d5af6f6]712{
[e0fcac5f2c]713        this->fileName = fileName;
714        setWindowTitle(QString("%1[*] - %2").arg(QFileInfo(fileName).completeBaseName()).arg(trUtf8("Travelling Salesman Problem")));
[993d5af6f6]715}
[1fbf016a09]716
717void MainWindow::toggleSolutionActions(bool enable)
718{
719        buttonSaveSolution->setEnabled(enable);
720        actionFileSaveAsSolution->setEnabled(enable);
721        solutionText->setEnabled(enable);
722        if (!enable)
723                output.clear();
724#ifndef QT_NO_PRINTER
725        actionFilePrint->setEnabled(enable);
726        actionFilePrintPreview->setEnabled(enable);
727#endif // QT_NO_PRINTER
728}
Note: See TracBrowser for help on using the repository browser.