source: tspsg/src/mainwindow.cpp @ f1fb54b9f7

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

+ Added the ability to generate fractional random numbers.
+ Added "Scroll to the end of solution output after solving" option.

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