source: tspsg-svn/trunk/src/mainwindow.cpp @ 96

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