source: tspsg/src/mainwindow.cpp @ 6beb157497

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

+ Preliminary Symbian support.

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