source: tspsg/src/mainwindow.cpp @ caef58b531

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

More code documentation.

  • Property mode set to 100644
File size: 22.9 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
49        // A little hack for toolbar icons to have sane size.
50int s = qMin(QApplication::desktop()->screenGeometry().width(),QApplication::desktop()->screenGeometry().height());
51        toolBar->setIconSize(QSize(s / 10,s / 10));
52#endif
[c10297cf73]53#ifndef QT_NO_PRINTER
[56dca709c9]54        printer = new QPrinter(QPrinter::HighResolution);
[c10297cf73]55#endif // QT_NO_PRINTER
[899d1b8e15]56        groupSettingsLanguageList = new QActionGroup(this);
[ac4cb71650]57        actionSettingsLanguageEnglish->setData("en");
58        actionSettingsLanguageEnglish->setActionGroup(groupSettingsLanguageList);
[899d1b8e15]59        loadLangList();
[aaf2113307]60        spinCities->setMaximum(MAX_NUM_CITIES);
[899d1b8e15]61        actionSettingsLanguageAutodetect->setChecked(settings->value("Language","").toString().isEmpty());
62        connect(actionFileNew,SIGNAL(triggered()),this,SLOT(actionFileNewTriggered()));
[993d5af6f6]63        connect(actionFileOpen,SIGNAL(triggered()),this,SLOT(actionFileOpenTriggered()));
[aaf2113307]64        connect(actionFileSave,SIGNAL(triggered()),this,SLOT(actionFileSaveTriggered()));
[430bd7f7e9]65        connect(actionFileSaveAsTask,SIGNAL(triggered()),this,SLOT(actionFileSaveAsTaskTriggered()));
66        connect(actionFileSaveAsSolution,SIGNAL(triggered()),this,SLOT(actionFileSaveAsSolutionTriggered()));
[899d1b8e15]67        connect(actionSettingsPreferences,SIGNAL(triggered()),this,SLOT(actionSettingsPreferencesTriggered()));
68        connect(actionSettingsLanguageAutodetect,SIGNAL(triggered(bool)),this,SLOT(actionSettingsLanguageAutodetectTriggered(bool)));
69        connect(groupSettingsLanguageList,SIGNAL(triggered(QAction *)),this,SLOT(groupSettingsLanguageListTriggered(QAction *)));
[690f6939a7]70        connect(actionHelpAboutQt,SIGNAL(triggered()),qApp,SLOT(aboutQt()));
[899d1b8e15]71        connect(actionHelpAbout,SIGNAL(triggered()),this,SLOT(actionHelpAboutTriggered()));
[c10297cf73]72#ifndef QT_NO_PRINTER
73        menuFile->insertAction(actionFileExit,actionFilePrintPreview);
74        menuFile->insertAction(actionFileExit,actionFilePrint);
75        menuFile->insertSeparator(actionFileExit);
76        toolBar->insertAction(actionSettingsPreferences,actionFilePrint);
[56dca709c9]77        connect(actionFilePrintPreview,SIGNAL(triggered()),this,SLOT(actionFilePrintPreviewTriggered()));
78        connect(actionFilePrint,SIGNAL(triggered()),this,SLOT(actionFilePrintTriggered()));
[c10297cf73]79#endif // QT_NO_PRINTER
[899d1b8e15]80        connect(buttonSolve,SIGNAL(clicked()),this,SLOT(buttonSolveClicked()));
81        connect(buttonRandom,SIGNAL(clicked()),this,SLOT(buttonRandomClicked()));
[aaf2113307]82        connect(buttonBackToTask,SIGNAL(clicked()),this,SLOT(buttonBackToTaskClicked()));
[899d1b8e15]83        connect(spinCities,SIGNAL(valueChanged(int)),this,SLOT(spinCitiesValueChanged(int)));
[134a9158bd]84        setCentralWidget(tabWidget);
[aaf2113307]85QRect rect = geometry();
[430bd7f7e9]86#ifndef Q_OS_WINCE
[665d32434f]87        if (settings->value("SavePos",false).toBool()) {
[aecdf994f9]88                // Loading of saved window state
[665d32434f]89                settings->beginGroup("MainWindow");
90                resize(settings->value("Size",size()).toSize());
91                move(settings->value("Position",pos()).toPoint());
92                if (settings->value("Maximized",false).toBool())
[aecdf994f9]93                        setWindowState(windowState() | Qt::WindowMaximized);
[665d32434f]94                settings->endGroup();
[aecdf994f9]95        } else {
96                // Centering main window
97                rect.moveCenter(QApplication::desktop()->availableGeometry(this).center());
98                setGeometry(rect);
99        }
[5354a01311]100#endif // Q_OS_WINCE
[fc9f661ded]101        qsrand(QDateTime().currentDateTime().toTime_t());
[2bc8e278b7]102        tspmodel = new CTSPModel();
[56dca709c9]103        taskView->setModel(tspmodel);
[993d5af6f6]104        connect(tspmodel,SIGNAL(numCitiesChanged(int)),this,SLOT(numCitiesChanged(int)));
[2fb523720a]105        connect(tspmodel,SIGNAL(dataChanged(const QModelIndex &, const QModelIndex &)),this,SLOT(dataChanged(const QModelIndex &, const QModelIndex &)));
[690f6939a7]106        connect(tspmodel,SIGNAL(layoutChanged()),this,SLOT(dataChanged()));
[aaf2113307]107        if ((QCoreApplication::arguments().count() > 1) && (tspmodel->loadTask(QCoreApplication::arguments().at(1))))
[b424a7e320]108                setFileName(QCoreApplication::arguments().at(1));
[aaf2113307]109        else {
[b424a7e320]110                setFileName();
[aaf2113307]111                spinCities->setValue(settings->value("NumCities",DEF_NUM_CITIES).toInt());
[56dca709c9]112                spinCitiesValueChanged(spinCities->value());
[aaf2113307]113        }
114        setWindowModified(false);
[003e4193be]115}
[052d1b9331]116
[430bd7f7e9]117void MainWindow::enableSolutionActions(bool enable)
118{
[aaf2113307]119        buttonSaveSolution->setEnabled(enable);
[430bd7f7e9]120        actionFileSaveAsSolution->setEnabled(enable);
121        solutionText->setEnabled(enable);
122        if (!enable)
123                output.clear();
[c10297cf73]124#ifndef QT_NO_PRINTER
[56dca709c9]125        actionFilePrint->setEnabled(enable);
126        actionFilePrintPreview->setEnabled(enable);
[c10297cf73]127#endif // QT_NO_PRINTER
[430bd7f7e9]128}
129
[ac4cb71650]130bool MainWindow::loadLanguage(QString lang)
[899d1b8e15]131{
132// i18n
[ac4cb71650]133bool ad = false;
134        if (lang.isEmpty()) {
135                ad = settings->value("Language","").toString().isEmpty();
136                lang = settings->value("Language",QLocale::system().name()).toString();
137        }
[56dca709c9]138static QTranslator *qtTranslator; // Qt library translator
[899d1b8e15]139        if (qtTranslator) {
140                qApp->removeTranslator(qtTranslator);
141                delete qtTranslator;
142                qtTranslator = NULL;
143        }
144        qtTranslator = new QTranslator();
[56dca709c9]145static QTranslator *translator; // Application translator
[ac4cb71650]146        if (translator) {
147                qApp->removeTranslator(translator);
148                delete translator;
149        }
150        translator = new QTranslator();
[899d1b8e15]151        if (lang.compare("en") && !lang.startsWith("en_")) {
152                // Trying to load system Qt library translation...
153                if (qtTranslator->load("qt_" + lang,QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
154                        qApp->installTranslator(qtTranslator);
155                else
156                        // No luck. Let's try to load bundled one.
[2fb523720a]157                        if (qtTranslator->load("qt_" + lang,PATH_I18N))
[899d1b8e15]158                                qApp->installTranslator(qtTranslator);
159                        else {
[56dca709c9]160                                // Qt library translation unavailable
[899d1b8e15]161                                delete qtTranslator;
162                                qtTranslator = NULL;
163                        }
[ac4cb71650]164                // Now let's load application translation.
[2fb523720a]165                if (translator->load(lang,PATH_I18N))
[899d1b8e15]166                        qApp->installTranslator(translator);
167                else {
168                        if (!ad)
[56dca709c9]169                                QMessageBox(QMessageBox::Warning,trUtf8("Language Change"),trUtf8("Unable to load translation language."),QMessageBox::Ok,this).exec();
[899d1b8e15]170                        delete translator;
171                        translator = NULL;
172                        return false;
173                }
174        }
175        return true;
176}
177
[430bd7f7e9]178void MainWindow::initDocStyleSheet()
179{
180QColor color = settings->value("Output/Color",DEF_FONT_COLOR).value<QColor>();
181QColor hilight;
182        if (color.value() < 192)
183                hilight.setHsv(color.hue(),color.saturation(),127 + qRound(color.value() / 2));
184        else
185                hilight.setHsv(color.hue(),color.saturation(),color.value() / 2);
186        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;}");
187        solutionText->document()->setDefaultFont(settings->value("Output/Font",QFont(DEF_FONT_FAMILY,DEF_FONT_SIZE)).value<QFont>());
188}
189
[b424a7e320]190void MainWindow::setFileName(QString fileName)
191{
192        this->fileName = fileName;
193        setWindowTitle(QString("%1[*] - %2").arg(QFileInfo(fileName).completeBaseName()).arg(trUtf8("Travelling Salesman Problem")));
194}
195
[899d1b8e15]196void MainWindow::spinCitiesValueChanged(int n)
[003e4193be]197{
[aecdf994f9]198int count = tspmodel->numCities();
[2bc8e278b7]199        tspmodel->setNumCities(n);
[2fb523720a]200        if ((n > count) && settings->value("Autosize",true).toBool())
[aecdf994f9]201                for (int k = count; k < n; k++) {
202                        taskView->resizeColumnToContents(k);
203                        taskView->resizeRowToContents(k);
204                }
[5515c2c2a7]205}
206
[b424a7e320]207bool MainWindow::maybeSave()
208{
209        if (!isWindowModified())
210                return true;
211int 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();
212        if (res == QMessageBox::Save)
213                return saveTask();
214        else if (res == QMessageBox::Cancel)
215                return false;
216        else
217                return true;
218}
[899d1b8e15]219
220void MainWindow::actionFileNewTriggered()
221{
[b424a7e320]222        if (!maybeSave())
223                return;
[c10297cf73]224        QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
[899d1b8e15]225        tspmodel->clear();
[b424a7e320]226        setFileName();
[690f6939a7]227        setWindowModified(false);
[430bd7f7e9]228        tabWidget->setCurrentIndex(0);
229        solutionText->clear();
230        enableSolutionActions(false);
[c10297cf73]231        QApplication::restoreOverrideCursor();
[899d1b8e15]232}
233
[993d5af6f6]234void MainWindow::actionFileOpenTriggered()
235{
[b424a7e320]236        if (!maybeSave())
237                return;
[993d5af6f6]238QFileDialog od(this);
239        od.setAcceptMode(QFileDialog::AcceptOpen);
240        od.setFileMode(QFileDialog::ExistingFile);
241QStringList filters(trUtf8("All Supported Formats") + " (*.tspt *.zkt)");
[b424a7e320]242        filters.append(trUtf8("%1 Task Files").arg("TSPSG") + " (*.tspt)");
243        filters.append(trUtf8("%1 Task Files").arg("ZKomModRd") + " (*.zkt)");
[993d5af6f6]244        filters.append(trUtf8("All Files") + " (*)");
245        od.setNameFilters(filters);
246        if (od.exec() != QDialog::Accepted)
247                return;
248QStringList files = od.selectedFiles();
[b424a7e320]249        if (files.empty())
250                return;
[244c614c6b]251        if (!tspmodel->loadTask(files.first()))
[993d5af6f6]252                return;
[b424a7e320]253        setFileName(files.first());
254        tabWidget->setCurrentIndex(0);
[690f6939a7]255        setWindowModified(false);
[430bd7f7e9]256        solutionText->clear();
257        enableSolutionActions(false);
[993d5af6f6]258}
259
[aaf2113307]260void MainWindow::actionFileSaveTriggered()
261{
262        if ((fileName == trUtf8("Untitled") + ".tspt") || (!fileName.endsWith(".tspt",Qt::CaseInsensitive)))
263                saveTask();
[244c614c6b]264        else
[aaf2113307]265                if (tspmodel->saveTask(fileName))
266                        setWindowModified(false);
267}
268
[430bd7f7e9]269void MainWindow::actionFileSaveAsTaskTriggered()
[993d5af6f6]270{
[690f6939a7]271        saveTask();
272}
273
[430bd7f7e9]274void MainWindow::actionFileSaveAsSolutionTriggered()
275{
276static QString selectedFile;
277        if (selectedFile.isEmpty())
[6dfdef0c3e]278#ifndef QT_NO_PRINTER
279                selectedFile = "solution.pdf";
280#else
[430bd7f7e9]281                selectedFile = "solution.html";
[6dfdef0c3e]282#endif // QT_NO_PRINTER
[430bd7f7e9]283QFileDialog sd(this);
284        sd.setAcceptMode(QFileDialog::AcceptSave);
[6dfdef0c3e]285QStringList filters;
286#ifndef QT_NO_PRINTER
287        filters.append(trUtf8("PDF Files") + "(*.pdf)");
288#endif
289        filters.append(trUtf8("HTML Files") + " (*.html *.htm)");
[ec54b4490b]290#if QT_VERSION >= 0x040500
[430bd7f7e9]291        filters.append(trUtf8("OpenDocument Files") + " (*.odt)");
[ec54b4490b]292#endif // QT_VERSION >= 0x040500
[430bd7f7e9]293        filters.append(trUtf8("All Files") + " (*)");
294        sd.setNameFilters(filters);
295        sd.selectFile(selectedFile);
296        if (sd.exec() != QDialog::Accepted)
297                return;
298QStringList files = sd.selectedFiles();
299        if (files.empty())
300                return;
301        selectedFile = files.first();
[f44855d99e]302        QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
[6dfdef0c3e]303#ifndef QT_NO_PRINTER
304        if (selectedFile.endsWith(".pdf",Qt::CaseInsensitive)) {
305QPrinter printer(QPrinter::HighResolution);
306                printer.setOutputFormat(QPrinter::PdfFormat);
307                printer.setOutputFileName(selectedFile);
308                solutionText->document()->print(&printer);
309                QApplication::restoreOverrideCursor();
310                return;
311        }
312#endif
[ec54b4490b]313#if QT_VERSION >= 0x040500
[430bd7f7e9]314QTextDocumentWriter dw(selectedFile);
315        if (!(selectedFile.endsWith(".htm",Qt::CaseInsensitive) || selectedFile.endsWith(".html",Qt::CaseInsensitive) || selectedFile.endsWith(".odt",Qt::CaseInsensitive) || selectedFile.endsWith(".txt",Qt::CaseInsensitive)))
316                dw.setFormat("plaintext");
317        dw.write(solutionText->document());
[ec54b4490b]318#else
319        // Qt < 4.5 has no QTextDocumentWriter class
320QFile file(selectedFile);
[f44855d99e]321        if (!file.open(QFile::WriteOnly)) {
322                QApplication::restoreOverrideCursor();
[ec54b4490b]323                return;
[f44855d99e]324        }
[ec54b4490b]325QTextStream ts(&file);
326        ts.setCodec(QTextCodec::codecForName("UTF-8"));
327        ts << solutionText->document()->toHtml("UTF-8");
[f44855d99e]328        file.close();
[ec54b4490b]329#endif // QT_VERSION >= 0x040500
[f44855d99e]330        QApplication::restoreOverrideCursor();
[430bd7f7e9]331}
332
[690f6939a7]333bool MainWindow::saveTask() {
[993d5af6f6]334QFileDialog sd(this);
335        sd.setAcceptMode(QFileDialog::AcceptSave);
[b424a7e320]336QStringList filters(trUtf8("%1 Task File").arg("TSPSG") + " (*.tspt)");
[993d5af6f6]337        filters.append(trUtf8("All Files") + " (*)");
338        sd.setNameFilters(filters);
339        sd.setDefaultSuffix("tspt");
[b424a7e320]340        if (fileName.endsWith(".tspt",Qt::CaseInsensitive))
341                sd.selectFile(fileName);
342        else
343                sd.selectFile(QFileInfo(fileName).canonicalPath() + "/" + QFileInfo(fileName).completeBaseName() + ".tspt");
[993d5af6f6]344        if (sd.exec() != QDialog::Accepted)
[690f6939a7]345                return false;
[993d5af6f6]346QStringList files = sd.selectedFiles();
[b424a7e320]347        if (files.empty())
[690f6939a7]348                return false;
349        if (tspmodel->saveTask(files.first())) {
[b424a7e320]350                setFileName(files.first());
[690f6939a7]351                setWindowModified(false);
352                return true;
[b424a7e320]353        }
354        return false;
[993d5af6f6]355}
356
[899d1b8e15]357void MainWindow::actionSettingsPreferencesTriggered()
[5515c2c2a7]358{
359SettingsDialog sd(this);
[430bd7f7e9]360        if (sd.exec() != QDialog::Accepted)
361                return;
362        if (sd.colorChanged() || sd.fontChanged()) {
363                initDocStyleSheet();
364                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)) {
365                        QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
366                        solutionText->clear();
367                        solutionText->setHtml(output.join(""));
368                        QApplication::restoreOverrideCursor();
369                }
370        }
[5515c2c2a7]371}
[bb994a7ff8]372
[c10297cf73]373#ifndef QT_NO_PRINTER
[56dca709c9]374void MainWindow::printPreview(QPrinter *printer)
375{
376        solutionText->print(printer);
377}
378
379void MainWindow::actionFilePrintPreviewTriggered()
380{
381QPrintPreviewDialog ppd(printer, this);
382    connect(&ppd,SIGNAL(paintRequested(QPrinter *)),SLOT(printPreview(QPrinter *)));
383    ppd.exec();
384}
385
386void MainWindow::actionFilePrintTriggered()
[5354a01311]387{
[899d1b8e15]388QPrintDialog pd(printer,this);
[140912822f]389#if QT_VERSION >= 0x040500
390        // No such methods in Qt < 4.5
[899d1b8e15]391        pd.setOption(QAbstractPrintDialog::PrintSelection,false);
392        pd.setOption(QAbstractPrintDialog::PrintPageRange,false);
[140912822f]393#endif
[56dca709c9]394        if (pd.exec() != QDialog::Accepted)
395                return;
[c10297cf73]396        QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
[56dca709c9]397        solutionText->document()->print(printer);
[c10297cf73]398        QApplication::restoreOverrideCursor();
[5354a01311]399}
[c10297cf73]400#endif // QT_NO_PRINTER
[5354a01311]401
[899d1b8e15]402void MainWindow::buttonRandomClicked()
[bb994a7ff8]403{
[c10297cf73]404        QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
[2bc8e278b7]405        tspmodel->randomize();
[c10297cf73]406        QApplication::restoreOverrideCursor();
[aaf2113307]407}
408
409void MainWindow::buttonBackToTaskClicked()
410{
411        tabWidget->setCurrentIndex(0);
[bb994a7ff8]412}
413
[430bd7f7e9]414void MainWindow::outputMatrix(tMatrix matrix, QStringList &output, int nRow, int nCol)
415{
416int n = spinCities->value();
417QString line="";
418        output.append("<table border=\"0\" cellspacing=\"0\" cellpadding=\"0\">");
419        for (int r = 0; r < n; r++) {
420                line = "<tr>";
421                for (int c = 0; c < n; c++) {
422                        if (matrix[r][c] == INFINITY)
423                                line += "<td align=\"center\">"INFSTR"</td>";
424                        else if ((r == nRow) && (c == nCol))
425                                line += "<td align=\"center\" class=\"selected\">" + QVariant(matrix[r][c]).toString() + "</td>";
426                        else
427                                line += "<td align=\"center\">" + QVariant(matrix[r][c]).toString() + "</td>";
428                }
429                line += "</tr>";
430                output.append(line);
431        }
432        output.append("</table>");
433}
434
[899d1b8e15]435void MainWindow::buttonSolveClicked()
[bb994a7ff8]436{
[e664262f7d]437tMatrix matrix;
[430bd7f7e9]438QList<double> row;
[2bc8e278b7]439int n = spinCities->value();
[e664262f7d]440bool ok;
[2bc8e278b7]441        for (int r = 0; r < n; r++) {
[430bd7f7e9]442                row.clear();
[2bc8e278b7]443                for (int c = 0; c < n; c++) {
[430bd7f7e9]444                        row.append(tspmodel->index(r,c).data(Qt::UserRole).toDouble(&ok));
[2bc8e278b7]445                        if (!ok) {
[b424a7e320]446                                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]447                                return;
[e664262f7d]448                        }
449                }
450                matrix.append(row);
451        }
452CTSPSolver solver;
[aaf2113307]453sStep *root = solver.solve(n,matrix,this);
[e664262f7d]454        if (!root)
[430bd7f7e9]455                return;
456        QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
457QColor color = settings->value("Output/Color",DEF_FONT_COLOR).value<QColor>();
458        output.clear();
459        output.append("<p>" + trUtf8("Variant #%1").arg(spinVariant->value()) + "</p>");
460        output.append("<p>" + trUtf8("Task:") + "</p>");
461        outputMatrix(matrix,output);
462        output.append("<hr>");
463        output.append("<p>" + trUtf8("Solution of Variant #%1 task").arg(spinVariant->value()) + "</p>");
464sStep *step = root;
465        n = 1;
466        while (n <= spinCities->value()) {
467                if (step->prNode->prNode != NULL || (step->prNode->prNode == NULL && step->plNode->prNode == NULL)) {
468                        if (n != spinCities->value()) {
469                                output.append("<p>" + trUtf8("Step #%1").arg(n++) + "</p>");
470                                outputMatrix(step->matrix,output,step->candidate.nRow,step->candidate.nCol);
471                                if (step->alts)
472                                        output.append("<p class=\"hasalts\">" + trUtf8("This step has alternate candidates for branching.") + "</p>");
473                                output.append("<p>&nbsp;</p>");
474                        }
475                }
476                if (step->prNode->prNode != NULL)
477                        step = step->prNode;
478                else if (step->plNode->prNode != NULL)
479                        step = step->plNode;
480                else
481                        break;
482        }
[9cf98b9bd6]483        if (solver.isOptimal())
484                output.append("<p>" + trUtf8("Optimal path:") + "</p>");
485        else
486                output.append("<p>" + trUtf8("Resulting path:") + "</p>");
487        output.append("<p>&nbsp;&nbsp;" + solver.getSortedPath() + "</p>");
[430bd7f7e9]488        output.append("<p>" + trUtf8("The price is <b>%1</b> units.").arg(step->price) + "</p>");
[9cf98b9bd6]489        if (!solver.isOptimal()) {
490                output.append("<p>&nbsp;</p>");
491                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>");
492        }
[caef58b531]493        output.append("<p></p>");
[430bd7f7e9]494        solutionText->setHtml(output.join(""));
495        solutionText->setDocumentTitle(trUtf8("Solution of Variant #%1 task").arg(spinVariant->value()));
[caef58b531]496
497        // Scrolling to the end of text.
498QTextCursor cursor(solutionText->textCursor());
499        cursor.movePosition(QTextCursor::End, QTextCursor::MoveAnchor);
500        solutionText->setTextCursor(cursor);
501
[430bd7f7e9]502        enableSolutionActions();
503        tabWidget->setCurrentIndex(1);
504        QApplication::restoreOverrideCursor();
[bb994a7ff8]505}
[aecdf994f9]506
[899d1b8e15]507void MainWindow::actionHelpAboutTriggered()
[aecdf994f9]508{
[caef58b531]509//! \todo TODO: Normal about window :-)
[6dfdef0c3e]510QString about = QString::fromUtf8("TSPSG: TSP Solver and Generator\n");
[ec54b4490b]511        about += QString::fromUtf8("    Version: "BUILD_VERSION"\n");
[430bd7f7e9]512        about += QString::fromUtf8("    Copyright (C) 2007-%1 Lёppa <contacts[at]oleksii[dot]name>\n").arg(QDate::currentDate().toString("yyyy"));
[690f6939a7]513        about += QString::fromUtf8("Target OS: %1\n").arg(OS);
514        about += "Qt library:\n";
[ac4cb71650]515        about += QString::fromUtf8("    Compile time: %1\n").arg(QT_VERSION_STR);
516        about += QString::fromUtf8("    Runtime: %1\n").arg(qVersion());
[b5c9bcb585]517        about += QString::fromUtf8("Built on %1 at %2\n").arg(__DATE__).arg(__TIME__);
[55c4b858e9]518        about += QString::fromUtf8(VERSIONID"\n\n");
519        about += QString::fromUtf8("Algorithm: %1\n").arg(CTSPSolver::getVersionId());
[ac4cb71650]520        about += "\n";
521        about += "TSPSG is licensed under the terms of the GNU General Public License. You should have received a copy of the GNU General Public License along with TSPSG.";
[5587b87fac]522        QMessageBox(QMessageBox::Information,"About",about,QMessageBox::Ok,this).exec();
[aecdf994f9]523}
524
[899d1b8e15]525void MainWindow::loadLangList()
526{
[2fb523720a]527QSettings langinfo(PATH_I18N"/languages.ini",QSettings::IniFormat);
[140912822f]528#if QT_VERSION >= 0x040500
529        // In Qt < 4.5 QSettings doesn't have method setIniCodec.
[899d1b8e15]530        langinfo.setIniCodec("UTF-8");
[140912822f]531#endif
[2fb523720a]532QDir dir(PATH_I18N,"*.qm",QDir::Name | QDir::IgnoreCase,QDir::Files);
[899d1b8e15]533        if (!dir.exists())
534                return;
535QFileInfoList langs = dir.entryInfoList();
536        if (langs.size() <= 0)
537                return;
538QAction *a;
539        for (int k = 0; k < langs.size(); k++) {
540                QFileInfo lang = langs.at(k);
[ac4cb71650]541                if (!lang.completeBaseName().startsWith("qt_") && lang.completeBaseName().compare("en")) {
[140912822f]542#if QT_VERSION >= 0x040500
[899d1b8e15]543                        a = menuSettingsLanguage->addAction(langinfo.value(lang.completeBaseName() + "/NativeName",lang.completeBaseName()).toString());
[140912822f]544#else
545                        // We use Name if Qt < 4.5 because NativeName is in UTF-8, QSettings
546                        // reads .ini file as ASCII and there is no way to set file encoding.
547                        a = menuSettingsLanguage->addAction(langinfo.value(lang.completeBaseName() + "/Name",lang.completeBaseName()).toString());
548#endif
[899d1b8e15]549                        a->setData(lang.completeBaseName());
550                        a->setCheckable(true);
551                        a->setActionGroup(groupSettingsLanguageList);
552                        if (settings->value("Language",QLocale::system().name()).toString().startsWith(lang.completeBaseName()))
553                                a->setChecked(true);
554                }
555        }
556}
557
558void MainWindow::actionSettingsLanguageAutodetectTriggered(bool checked)
559{
560        if (checked) {
561                settings->remove("Language");
562                QMessageBox(QMessageBox::Information,trUtf8("Language change"),trUtf8("Language will be autodetected on next application start."),QMessageBox::Ok,this).exec();
563        } else
564                settings->setValue("Language",groupSettingsLanguageList->checkedAction()->data().toString());
565}
566
567void MainWindow::groupSettingsLanguageListTriggered(QAction *action)
568{
569        if (actionSettingsLanguageAutodetect->isChecked()) {
570                // We have language autodetection. It needs to be disabled to change language.
571                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) {
572                        actionSettingsLanguageAutodetect->trigger();
573                } else
574                        return;
575        }
[b424a7e320]576bool untitled = (fileName == trUtf8("Untitled") + ".tspt");
[ac4cb71650]577        if (loadLanguage(action->data().toString())) {
[899d1b8e15]578                settings->setValue("Language",action->data().toString());
579                retranslateUi(this);
[b424a7e320]580                if (untitled)
581                        setFileName();
[899d1b8e15]582        }
583}
584
[caef58b531]585/*!
586 * \brief Handles Main Window close event.
587 * \param event Close event.
588 *
589 *  Checks whether or not a current task was saved and asks for saving if not.
590 *  Saves TSPSG settings.
591 */
[aecdf994f9]592void MainWindow::closeEvent(QCloseEvent *event)
593{
[b424a7e320]594        if (!maybeSave()) {
595                event->ignore();
596                return;
[690f6939a7]597        }
[665d32434f]598        settings->setValue("NumCities",spinCities->value());
[0621172ec1]599#ifndef Q_OS_WINCE
600        // Saving windows state
[665d32434f]601        if (settings->value("SavePos",false).toBool()) {
602                settings->beginGroup("MainWindow");
603                settings->setValue("Maximized",isMaximized());
[aecdf994f9]604                if (!isMaximized()) {
[665d32434f]605                        settings->setValue("Size",size());
606                        settings->setValue("Position",pos());
[aecdf994f9]607                }
[665d32434f]608                settings->endGroup();
[aecdf994f9]609        }
[0621172ec1]610#endif // Q_OS_WINCE
[aecdf994f9]611        QMainWindow::closeEvent(event);
612}
[993d5af6f6]613
[690f6939a7]614void MainWindow::dataChanged()
615{
616        setWindowModified(true);
617}
618
[2fb523720a]619void MainWindow::dataChanged(const QModelIndex &tl, const QModelIndex &br)
620{
621        setWindowModified(true);
622        if (settings->value("Autosize",true).toBool()) {
623                for (int k = tl.row(); k <= br.row(); k++)
624                        taskView->resizeRowToContents(k);
625                for (int k = tl.column(); k <= br.column(); k++)
626                        taskView->resizeColumnToContents(k);
627        }
628}
629
[993d5af6f6]630void MainWindow::numCitiesChanged(int nCities)
631{
[aaf2113307]632        blockSignals(true);
[993d5af6f6]633        spinCities->setValue(nCities);
[aaf2113307]634        blockSignals(false);
[993d5af6f6]635}
Note: See TracBrowser for help on using the repository browser.