source: tspsg/src/mainwindow.cpp @ fcaa74f7d7

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