source: tspsg/src/mainwindow.cpp @ 760f2aae97

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

+ Added question about enabling automatic updates (will be asked only once).

  • Updated translations.
  • Property mode set to 100644
File size: 58.9 KB
RevLine 
[1babbd6ba3]1/*
2 *  TSPSG: TSP Solver and Generator
3 *  Copyright (C) 2007-2010 Lёppa <contacts[at]oleksii[dot]name>
4 *
5 *  $Id$
6 *  $URL$
7 *
8 *  This file is part of TSPSG.
9 *
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.
14 *
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.
19 *
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/>.
22 */
23
24#include "mainwindow.h"
25
[97e90f9be6]26#ifdef Q_WS_WIN32
[43c29c04ba]27        #include "shobjidl.h"
28#endif
29
[3cadf24d00]30#ifdef _T_T_L_
31#include "_.h"
[e9db3e216b]32_C_ _R_ _Y_ _P_ _T_
[3cadf24d00]33#endif
34
[1babbd6ba3]35/*!
36 * \brief Class constructor.
37 * \param parent Main Window parent widget.
38 *
39 *  Initializes Main Window and creates its layout based on target OS.
40 *  Loads TSPSG settings and opens a task file if it was specified as a commandline parameter.
41 */
42MainWindow::MainWindow(QWidget *parent)
43        : QMainWindow(parent)
44{
45        settings = new QSettings(QSettings::IniFormat, QSettings::UserScope, "TSPSG", "tspsg", this);
46
[e3533af1cf]47        if (settings->contains("Style")) {
48QStyle *s = QStyleFactory::create(settings->value("Style").toString());
49                if (s != NULL)
50                        QApplication::setStyle(s);
51                else
52                        settings->remove("Style");
53        }
54
[1babbd6ba3]55        loadLanguage();
56        setupUi();
[b574c383b7]57        setAcceptDrops(true);
[1babbd6ba3]58
59        initDocStyleSheet();
60
61#ifndef QT_NO_PRINTER
62        printer = new QPrinter(QPrinter::HighResolution);
63#endif // QT_NO_PRINTER
64
[97e90f9be6]65#ifdef Q_WS_WINCE_WM
[1babbd6ba3]66        currentGeometry = QApplication::desktop()->availableGeometry(0);
67        // We need to react to SIP show/hide and resize the window appropriately
68        connect(QApplication::desktop(), SIGNAL(workAreaResized(int)), SLOT(desktopResized(int)));
[97e90f9be6]69#endif // Q_WS_WINCE_WM
[e51c78af27]70        connect(actionFileNew, SIGNAL(triggered()), SLOT(actionFileNewTriggered()));
71        connect(actionFileOpen, SIGNAL(triggered()), SLOT(actionFileOpenTriggered()));
72        connect(actionFileSave, SIGNAL(triggered()), SLOT(actionFileSaveTriggered()));
73        connect(actionFileSaveAsTask, SIGNAL(triggered()), SLOT(actionFileSaveAsTaskTriggered()));
74        connect(actionFileSaveAsSolution, SIGNAL(triggered()), SLOT(actionFileSaveAsSolutionTriggered()));
[1babbd6ba3]75#ifndef QT_NO_PRINTER
[e51c78af27]76        connect(actionFilePrintPreview, SIGNAL(triggered()), SLOT(actionFilePrintPreviewTriggered()));
77        connect(actionFilePrint, SIGNAL(triggered()), SLOT(actionFilePrintTriggered()));
[1babbd6ba3]78#endif // QT_NO_PRINTER
[7bb19df196]79#ifndef HANDHELD
80        connect(actionSettingsToolbarsConfigure, SIGNAL(triggered()), SLOT(actionSettingsToolbarsConfigureTriggered()));
81#endif // HANDHELD
[e51c78af27]82        connect(actionSettingsPreferences, SIGNAL(triggered()), SLOT(actionSettingsPreferencesTriggered()));
[f5c945d7ac]83        if (actionHelpCheck4Updates != NULL)
84                connect(actionHelpCheck4Updates, SIGNAL(triggered()), SLOT(actionHelpCheck4UpdatesTriggered()));
[e51c78af27]85        connect(actionSettingsLanguageAutodetect, SIGNAL(triggered(bool)), SLOT(actionSettingsLanguageAutodetectTriggered(bool)));
86        connect(groupSettingsLanguageList, SIGNAL(triggered(QAction *)), SLOT(groupSettingsLanguageListTriggered(QAction *)));
[e3533af1cf]87        connect(actionSettingsStyleSystem, SIGNAL(triggered(bool)), SLOT(actionSettingsStyleSystemTriggered(bool)));
88        connect(groupSettingsStyleList, SIGNAL(triggered(QAction*)), SLOT(groupSettingsStyleListTriggered(QAction*)));
[88a59e4d65]89        connect(actionHelpOnlineSupport, SIGNAL(triggered()), SLOT(actionHelpOnlineSupportTriggered()));
90        connect(actionHelpReportBug, SIGNAL(triggered()), SLOT(actionHelpReportBugTriggered()));
[e51c78af27]91        connect(actionHelpAboutQt, SIGNAL(triggered()), qApp, SLOT(aboutQt()));
92        connect(actionHelpAbout, SIGNAL(triggered()), SLOT(actionHelpAboutTriggered()));
[1babbd6ba3]93
[e51c78af27]94        connect(buttonSolve, SIGNAL(clicked()), SLOT(buttonSolveClicked()));
95        connect(buttonRandom, SIGNAL(clicked()), SLOT(buttonRandomClicked()));
96        connect(buttonBackToTask, SIGNAL(clicked()), SLOT(buttonBackToTaskClicked()));
97        connect(spinCities, SIGNAL(valueChanged(int)), SLOT(spinCitiesValueChanged(int)));
[1babbd6ba3]98
99#ifndef HANDHELD
100        // Centering main window
101QRect rect = geometry();
102        rect.moveCenter(QApplication::desktop()->availableGeometry(this).center());
103        setGeometry(rect);
104        if (settings->value("SavePos", DEF_SAVEPOS).toBool()) {
105                // Loading of saved window state
106                settings->beginGroup("MainWindow");
107                restoreGeometry(settings->value("Geometry").toByteArray());
108                restoreState(settings->value("State").toByteArray());
109                settings->endGroup();
110        }
111#endif // HANDHELD
112
113        tspmodel = new CTSPModel(this);
114        taskView->setModel(tspmodel);
[e51c78af27]115        connect(tspmodel, SIGNAL(numCitiesChanged(int)), SLOT(numCitiesChanged(int)));
116        connect(tspmodel, SIGNAL(dataChanged(const QModelIndex &, const QModelIndex &)), SLOT(dataChanged(const QModelIndex &, const QModelIndex &)));
117        connect(tspmodel, SIGNAL(layoutChanged()), SLOT(dataChanged()));
[1babbd6ba3]118        if ((QCoreApplication::arguments().count() > 1) && (tspmodel->loadTask(QCoreApplication::arguments().at(1))))
119                setFileName(QCoreApplication::arguments().at(1));
120        else {
121                setFileName();
122                spinCities->setValue(settings->value("NumCities",DEF_NUM_CITIES).toInt());
123                spinCitiesValueChanged(spinCities->value());
124        }
125        setWindowModified(false);
[f5c945d7ac]126
[760f2aae97]127        if (actionHelpCheck4Updates != NULL) {
128                if (!settings->contains("Check4Updates/Enabled")) {
129                        QApplication::setOverrideCursor(QCursor(Qt::ArrowCursor));
130                        settings->setValue("Check4Updates/Enabled",
131                                QMessageBox::question(this, QCoreApplication::applicationName(),
132                                        tr("Would you like %1 to automatically check for updates every %n day(s)?", "", settings->value("Check4Updates/Interval", DEF_UPDATE_CHECK_INTERVAL).toInt()).arg(QCoreApplication::applicationName()),
133                                        QMessageBox::Yes | QMessageBox::No
134                                ) == QMessageBox::Yes
135                        );
136                        QApplication::restoreOverrideCursor();
137                }
138                if ((settings->value("Check4Updates/Enabled", DEF_CHECK_FOR_UPDATES).toBool())
139                        && (QDate(qvariant_cast<QDate>(settings->value("Check4Updates/LastAttempt"))).daysTo(QDate::currentDate()) >= settings->value("Check4Updates/Interval", DEF_UPDATE_CHECK_INTERVAL).toInt())) {
140                        check4Updates(true);
141                }
[f5c945d7ac]142        }
[1babbd6ba3]143}
144
145MainWindow::~MainWindow()
146{
147#ifndef QT_NO_PRINTER
148        delete printer;
149#endif
150}
151
152/* Privates **********************************************************/
153
154void MainWindow::actionFileNewTriggered()
155{
156        if (!maybeSave())
157                return;
158        QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
159        tspmodel->clear();
160        setFileName();
161        setWindowModified(false);
162        tabWidget->setCurrentIndex(0);
163        solutionText->clear();
164        toggleSolutionActions(false);
165        QApplication::restoreOverrideCursor();
166}
167
168void MainWindow::actionFileOpenTriggered()
169{
170        if (!maybeSave())
171                return;
172
173QStringList filters(tr("All Supported Formats") + " (*.tspt *.zkt)");
174        filters.append(tr("%1 Task Files").arg("TSPSG") + " (*.tspt)");
175        filters.append(tr("%1 Task Files").arg("ZKomModRd") + " (*.zkt)");
176        filters.append(tr("All Files") + " (*)");
177
[ac76a6a753]178QString file;
179        if ((fileName == tr("Untitled") + ".tspt") && settings->value("SaveLastUsed", DEF_SAVE_LAST_USED).toBool())
[bbac1ebb13]180                file = settings->value(OS"/LastUsed/TaskLoadPath").toString();
[ac76a6a753]181        else
182                file = QFileInfo(fileName).path();
[1babbd6ba3]183QFileDialog::Options opts = settings->value("UseNativeDialogs", DEF_USE_NATIVE_DIALOGS).toBool() ? QFileDialog::Options() : QFileDialog::DontUseNativeDialog;
184        file = QFileDialog::getOpenFileName(this, tr("Task Load"), file, filters.join(";;"), NULL, opts);
185        if (file.isEmpty() || !QFileInfo(file).isFile())
186                return;
[ac76a6a753]187        if (settings->value("SaveLastUsed", DEF_SAVE_LAST_USED).toBool())
[bbac1ebb13]188                settings->setValue(OS"/LastUsed/TaskLoadPath", QFileInfo(file).path());
[ac76a6a753]189
[1babbd6ba3]190        if (!tspmodel->loadTask(file))
191                return;
192        setFileName(file);
193        tabWidget->setCurrentIndex(0);
194        setWindowModified(false);
195        solutionText->clear();
196        toggleSolutionActions(false);
197}
198
199bool MainWindow::actionFileSaveTriggered()
200{
[ac76a6a753]201        if ((fileName == tr("Untitled") + ".tspt") || !fileName.endsWith(".tspt", Qt::CaseInsensitive))
[1babbd6ba3]202                return saveTask();
203        else
204                if (tspmodel->saveTask(fileName)) {
205                        setWindowModified(false);
206                        return true;
207                } else
208                        return false;
209}
210
211void MainWindow::actionFileSaveAsTaskTriggered()
212{
213        saveTask();
214}
215
216void MainWindow::actionFileSaveAsSolutionTriggered()
217{
218static QString selectedFile;
[ac76a6a753]219        if (selectedFile.isEmpty()) {
220                if (settings->value("SaveLastUsed", DEF_SAVE_LAST_USED).toBool()) {
[bbac1ebb13]221                        selectedFile = settings->value(OS"/LastUsed/SolutionSavePath").toString();
[ac76a6a753]222                }
223        } else
224                selectedFile = QFileInfo(selectedFile).path();
[1babbd6ba3]225        if (!selectedFile.isEmpty())
[ac76a6a753]226                selectedFile.append("/");
[1babbd6ba3]227        if (fileName == tr("Untitled") + ".tspt") {
228#ifndef QT_NO_PRINTER
229                selectedFile += "solution.pdf";
230#else
231                selectedFile += "solution.html";
232#endif // QT_NO_PRINTER
233        } else {
234#ifndef QT_NO_PRINTER
235                selectedFile += QFileInfo(fileName).completeBaseName() + ".pdf";
236#else
237                selectedFile += QFileInfo(fileName).completeBaseName() + ".html";
238#endif // QT_NO_PRINTER
239        }
240
241QStringList filters;
242#ifndef QT_NO_PRINTER
243        filters.append(tr("PDF Files") + " (*.pdf)");
244#endif
245        filters.append(tr("HTML Files") + " (*.html *.htm)");
246        filters.append(tr("OpenDocument Files") + " (*.odt)");
247        filters.append(tr("All Files") + " (*)");
248
249QFileDialog::Options opts(settings->value("UseNativeDialogs", DEF_USE_NATIVE_DIALOGS).toBool() ? QFileDialog::Options() : QFileDialog::DontUseNativeDialog);
250QString file = QFileDialog::getSaveFileName(this, QString(), selectedFile, filters.join(";;"), NULL, opts);
251        if (file.isEmpty())
252                return;
253        selectedFile = file;
[ac76a6a753]254        if (settings->value("SaveLastUsed", DEF_SAVE_LAST_USED).toBool())
[bbac1ebb13]255                settings->setValue(OS"/LastUsed/SolutionSavePath", QFileInfo(selectedFile).path());
[1babbd6ba3]256        QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
257#ifndef QT_NO_PRINTER
258        if (selectedFile.endsWith(".pdf",Qt::CaseInsensitive)) {
259QPrinter printer(QPrinter::HighResolution);
260                printer.setOutputFormat(QPrinter::PdfFormat);
261                printer.setOutputFileName(selectedFile);
262                solutionText->document()->print(&printer);
263                QApplication::restoreOverrideCursor();
264                return;
265        }
266#endif
[ca3d2a30fa]267        if (selectedFile.endsWith(".htm", Qt::CaseInsensitive) || selectedFile.endsWith(".html", Qt::CaseInsensitive)) {
[1babbd6ba3]268QFile file(selectedFile);
[ca3d2a30fa]269                if (!file.open(QFile::WriteOnly)) {
270                        QApplication::restoreOverrideCursor();
271                        QMessageBox::critical(this, tr("Solution Save"), tr("Unable to save the solution.\nError: %1").arg(file.errorString()));
272                        return;
273                }
274QFileInfo fi(selectedFile);
[20015b41e7]275QString format = settings->value("Output/GraphImageFormat", DEF_GRAPH_IMAGE_FORMAT).toString();
[2a436ea693]276#if !defined(NOSVG)
[20015b41e7]277        if (!QImageWriter::supportedImageFormats().contains(format.toAscii()) && (format != "svg")) {
[2a436ea693]278#else // NOSVG
[20015b41e7]279        if (!QImageWriter::supportedImageFormats().contains(format.toAscii())) {
[2a436ea693]280#endif // NOSVG
[20015b41e7]281                format = DEF_GRAPH_IMAGE_FORMAT;
282                settings->remove("Output/GraphImageFormat");
283        }
[ca3d2a30fa]284QString html = solutionText->document()->toHtml("UTF-8"),
[20015b41e7]285                img =  fi.completeBaseName() + "." + format;
[131c5fc3ba]286                html.replace(QRegExp("font-family:([^;]*);"), "font-family:\\1, 'DejaVu Sans Mono', 'Courier New', Courier, monospace;");
[7aaa0b0ec7]287                html.replace(QRegExp("<img\\s+src=\"tspsg://graph.pic\""), QString("<img src=\"%1\" alt=\"%2\"").arg(img, tr("Solution Graph")));
[20015b41e7]288
[ca3d2a30fa]289                // Saving solution text as HTML
[1babbd6ba3]290QTextStream ts(&file);
[ca3d2a30fa]291                ts.setCodec(QTextCodec::codecForName("UTF-8"));
292                ts << html;
293                file.close();
[20015b41e7]294
295                // Saving solution graph as SVG or PNG (depending on settings and SVG support)
[2a436ea693]296#if !defined(NOSVG)
[20015b41e7]297                if (format == "svg") {
[ca3d2a30fa]298QSvgGenerator svg;
[131c5fc3ba]299                        svg.setSize(QSize(graph.width() + 2, graph.height() + 2));
[20015b41e7]300                        svg.setResolution(graph.logicalDpiX());
301                        svg.setFileName(fi.path() + "/" + img);
302                        svg.setTitle(tr("Solution Graph"));
[88a59e4d65]303                        svg.setDescription(tr("Generated with %1").arg(QCoreApplication::applicationName()));
[20015b41e7]304QPainter p;
305                        p.begin(&svg);
306                        p.drawPicture(1, 1, graph);
307                        p.end();
308                } else {
[2a436ea693]309#endif // NOSVG
[131c5fc3ba]310QImage i(graph.width() + 2, graph.height() + 2, QImage::Format_ARGB32);
[20015b41e7]311                        i.fill(0x00FFFFFF);
[ca3d2a30fa]312QPainter p;
[20015b41e7]313                        p.begin(&i);
314                        p.drawPicture(1, 1, graph);
315                        p.end();
316QImageWriter pic(fi.path() + "/" + img);
317                        if (pic.supportsOption(QImageIOHandler::Description)) {
318                                pic.setText("Title", "Solution Graph");
[88a59e4d65]319                                pic.setText("Software", QCoreApplication::applicationName());
[20015b41e7]320                        }
321                        if (format == "png")
322                                pic.setQuality(5);
323                        else if (format == "jpeg")
324                                pic.setQuality(80);
325                        if (!pic.write(i)) {
326                                QApplication::restoreOverrideCursor();
327                                QMessageBox::critical(this, tr("Solution Save"), tr("Unable to save the solution graph.\nError: %1").arg(pic.errorString()));
328                                return;
329                        }
[2a436ea693]330#if !defined(NOSVG)
[20015b41e7]331                }
[2a436ea693]332#endif // NOSVG
[ca3d2a30fa]333        } else {
334QTextDocumentWriter dw(selectedFile);
335                if (!selectedFile.endsWith(".odt",Qt::CaseInsensitive))
336                        dw.setFormat("plaintext");
337                if (!dw.write(solutionText->document()))
338                        QMessageBox::critical(this, tr("Solution Save"), tr("Unable to save the solution.\nError: %1").arg(dw.device()->errorString()));
339        }
[1babbd6ba3]340        QApplication::restoreOverrideCursor();
341}
342
343#ifndef QT_NO_PRINTER
344void MainWindow::actionFilePrintPreviewTriggered()
345{
346QPrintPreviewDialog ppd(printer, this);
347        connect(&ppd,SIGNAL(paintRequested(QPrinter *)),SLOT(printPreview(QPrinter *)));
348        ppd.exec();
349}
350
351void MainWindow::actionFilePrintTriggered()
352{
353QPrintDialog pd(printer,this);
354        if (pd.exec() != QDialog::Accepted)
355                return;
356        QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
[94cd045fad]357        solutionText->print(printer);
[1babbd6ba3]358        QApplication::restoreOverrideCursor();
359}
360#endif // QT_NO_PRINTER
361
362void MainWindow::actionSettingsPreferencesTriggered()
363{
364SettingsDialog sd(this);
365        if (sd.exec() != QDialog::Accepted)
366                return;
367        if (sd.colorChanged() || sd.fontChanged()) {
368                if (!solutionText->document()->isEmpty() && sd.colorChanged())
369                        QMessageBox::information(this, tr("Settings Changed"), tr("You have changed color settings.\nThey will be applied to the next solution output."));
370                initDocStyleSheet();
371        }
372        if (sd.translucencyChanged() != 0)
373                toggleTranclucency(sd.translucencyChanged() == 1);
374}
375
376void MainWindow::actionSettingsLanguageAutodetectTriggered(bool checked)
377{
378        if (checked) {
379                settings->remove("Language");
[88a59e4d65]380                QMessageBox::information(this, tr("Language change"), tr("Language will be autodetected on the next %1 start.").arg(QCoreApplication::applicationName()));
[1babbd6ba3]381        } else
382                settings->setValue("Language", groupSettingsLanguageList->checkedAction()->data().toString());
383}
384
385void MainWindow::groupSettingsLanguageListTriggered(QAction *action)
386{
[97e90f9be6]387#ifndef Q_WS_MAEMO_5
[1babbd6ba3]388        if (actionSettingsLanguageAutodetect->isChecked()) {
389                // We have language autodetection. It needs to be disabled to change language.
390                if (QMessageBox::question(this, 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) == QMessageBox::Yes) {
391                        actionSettingsLanguageAutodetect->trigger();
392                } else
393                        return;
394        }
[97e90f9be6]395#endif
[1babbd6ba3]396bool untitled = (fileName == tr("Untitled") + ".tspt");
397        if (loadLanguage(action->data().toString())) {
398                QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
399                settings->setValue("Language",action->data().toString());
400                retranslateUi();
401                if (untitled)
402                        setFileName();
[97e90f9be6]403#ifdef Q_WS_WIN32
[1babbd6ba3]404                if (QtWin::isCompositionEnabled() && settings->value("UseTranslucency", DEF_USE_TRANSLUCENCY).toBool())  {
405                        toggleStyle(labelVariant, true);
406                        toggleStyle(labelCities, true);
407                }
408#endif
409                QApplication::restoreOverrideCursor();
410                if (!solutionText->document()->isEmpty())
411                        QMessageBox::information(this, tr("Settings Changed"), tr("You have changed the application language.\nTo get current solution output in the new language\nyou need to re-run the solution process."));
412        }
413}
414
[e3533af1cf]415void MainWindow::actionSettingsStyleSystemTriggered(bool checked)
416{
417        if (checked) {
418                settings->remove("Style");
[88a59e4d65]419                QMessageBox::information(this, tr("Style Change"), tr("To apply the default style you need to restart %1.").arg(QCoreApplication::applicationName()));
[e3533af1cf]420        } else {
421                settings->setValue("Style", groupSettingsStyleList->checkedAction()->text());
422        }
423}
424
425void MainWindow::groupSettingsStyleListTriggered(QAction *action)
426{
427QStyle *s = QStyleFactory::create(action->text());
428        if (s != NULL) {
429                QApplication::setStyle(s);
430                settings->setValue("Style", action->text());
431                actionSettingsStyleSystem->setChecked(false);
432        }
433}
434
[7bb19df196]435#ifndef HANDHELD
436void MainWindow::actionSettingsToolbarsConfigureTriggered()
437{
438QtToolBarDialog dlg(this);
439        dlg.setToolBarManager(toolBarManager);
440        dlg.exec();
441QToolButton *tb = static_cast<QToolButton *>(toolBarMain->widgetForAction(actionFileSave));
442        if (tb != NULL) {
443                tb->setMenu(menuFileSaveAs);
444                tb->setPopupMode(QToolButton::MenuButtonPopup);
445                tb->resize(tb->sizeHint());
446        }
447
448        loadToolbarList();
449}
450#endif // HANDHELD
451
[1babbd6ba3]452void MainWindow::actionHelpCheck4UpdatesTriggered()
453{
454        if (!hasUpdater()) {
455                QMessageBox::warning(this, tr("Unsupported Feature"), tr("Sorry, but this feature is not supported on your platform\nor support for this feature was not installed."));
456                return;
457        }
458
[f5c945d7ac]459        check4Updates();
[1babbd6ba3]460}
461
462void MainWindow::actionHelpAboutTriggered()
463{
[43c29c04ba]464        QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
465
[1babbd6ba3]466QString title;
[88a59e4d65]467        title += QString("<b>%1</b><br>").arg(QCoreApplication::applicationName());
468        title += QString("%1: <b>%2</b><br>").arg(tr("Version"), QCoreApplication::applicationVersion());
[1babbd6ba3]469#ifndef HANDHELD
[88a59e4d65]470        title += QString("<b>&copy; 2007-%1 <a href=\"http://%2/\">%3</a></b><br>").arg(QDate::currentDate().toString("yyyy"), QCoreApplication::organizationDomain(), QCoreApplication::organizationName());
[7bb19df196]471#endif // HANDHELD
[672e522ba2]472        title += QString("<b><a href=\"http://tspsg.info/\">http://tspsg.info/</a></b>");
[1babbd6ba3]473
474QString about;
[bbac1ebb13]475        about += QString("%1: <b>%2</b><br>").arg(tr("Target OS (ARCH)"), PLATFROM);
[1babbd6ba3]476#ifndef STATIC_BUILD
477        about += QString("%1 (%2):<br>").arg(tr("Qt library"), tr("shared"));
478        about += QString("&nbsp;&nbsp;&nbsp;&nbsp;%1: <b>%2</b><br>").arg(tr("Build time"), QT_VERSION_STR);
479        about += QString("&nbsp;&nbsp;&nbsp;&nbsp;%1: <b>%2</b><br>").arg(tr("Runtime"), qVersion());
480#else
481        about += QString("%1: <b>%2</b> (%3)<br>").arg(tr("Qt library"), QT_VERSION_STR, tr("static"));
482#endif // STATIC_BUILD
[bbac1ebb13]483        about += tr("Buid <b>%1</b>, built on <b>%2</b> at <b>%3</b> with <b>%4</b> compiler.").arg(BUILD_NUMBER).arg(__DATE__).arg(__TIME__).arg(COMPILER) + "<br>";
[1babbd6ba3]484        about += QString("%1: <b>%2</b><br>").arg(tr("Algorithm"), CTSPSolver::getVersionId());
485        about += "<br>";
[43c29c04ba]486        about += tr("This program is free software: you can redistribute it and/or modify<br>\n"
487                "it under the terms of the GNU General Public License as published by<br>\n"
488                "the Free Software Foundation, either version 3 of the License, or<br>\n"
489                "(at your option) any later version.<br>\n"
490                "<br>\n"
491                "This program is distributed in the hope that it will be useful,<br>\n"
492                "but WITHOUT ANY WARRANTY; without even the implied warranty of<br>\n"
493                "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the<br>\n"
494                "GNU General Public License for more details.<br>\n"
495                "<br>\n"
496                "You should have received a copy of the GNU General Public License<br>\n"
497                "along with TSPSG.  If not, see <a href=\"http://www.gnu.org/licenses/\">www.gnu.org/licenses/</a>.");
498
499QString credits;
[e26679937d]500        credits += tr("%1 was created using <b>Qt&nbsp;framework</b> licensed "
501                "under the terms of the GNU Lesser General Public License,<br>\n"
[43c29c04ba]502                "see <a href=\"http://qt.nokia.com/\">qt.nokia.com</a><br>\n"
503                "<br>\n"
[e26679937d]504                "Most icons used in %1 are part of <b>Oxygen&nbsp;Icons</b> project "
[43c29c04ba]505                "licensed according to the GNU Lesser General Public License,<br>\n"
506                "see <a href=\"http://www.oxygen-icons.org/\">www.oxygen-icons.org</a><br>\n"
507                "<br>\n"
[e26679937d]508                "Country flag icons used in %1 are part of the free "
509                "<b>Flag&nbsp;Icons</b> collection created by <b>IconDrawer</b>,<br>\n"
[cb1608daaf]510                "see <a href=\"http://www.icondrawer.com/\">www.icondrawer.com</a><br>\n"
511                "<br>\n"
512                "%1 comes with the default \"embedded\" font <b>DejaVu&nbsp;LGC&nbsp;Sans&nbsp;"
513                "Mono</b> from the <b>DejaVu fonts</b> licensed under a Free license</a>,<br>\n"
[b81c0a73b7]514                "see <a href=\"http://dejavu-fonts.org/\">dejavu-fonts.org</a>")
515                        .arg("TSPSG");
[43c29c04ba]516
517QFile f(":/files/COPYING");
518        f.open(QIODevice::ReadOnly);
519
[88a59e4d65]520QString translation = QCoreApplication::translate("--------", "AUTHORS %1", "Please, provide translator credits here. %1 will be replaced with VERSION");
[43c29c04ba]521        if ((translation != "AUTHORS %1") && (translation.contains("%1"))) {
[88a59e4d65]522QString about = QCoreApplication::translate("--------", "VERSION", "Please, provide your translation version here.");
[43c29c04ba]523                if (about != "VERSION")
524                        translation = translation.arg(about);
525        }
[1babbd6ba3]526
527QDialog *dlg = new QDialog(this);
528QLabel *lblIcon = new QLabel(dlg),
[43c29c04ba]529        *lblTitle = new QLabel(dlg);
[1babbd6ba3]530#ifdef HANDHELD
[88a59e4d65]531QLabel *lblSubTitle = new QLabel(QString("<b>&copy; 2007-%1 <a href=\"http://%2/\">%3</a></b>").arg(QDate::currentDate().toString("yyyy"), QCoreApplication::organizationDomain(), QCoreApplication::organizationName()), dlg);
[1babbd6ba3]532#endif // HANDHELD
[43c29c04ba]533QTabWidget *tabs = new QTabWidget(dlg);
[1babbd6ba3]534QTextBrowser *txtAbout = new QTextBrowser(dlg);
[43c29c04ba]535QTextBrowser *txtLicense = new QTextBrowser(dlg);
536QTextBrowser *txtCredits = new QTextBrowser(dlg);
[1babbd6ba3]537QVBoxLayout *vb = new QVBoxLayout();
538QHBoxLayout *hb1 = new QHBoxLayout(),
539        *hb2 = new QHBoxLayout();
540QDialogButtonBox *bb = new QDialogButtonBox(QDialogButtonBox::Ok, Qt::Horizontal, dlg);
541
542        lblTitle->setOpenExternalLinks(true);
543        lblTitle->setText(title);
544        lblTitle->setAlignment(Qt::AlignTop);
545        lblTitle->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
546#ifndef HANDHELD
[e3533af1cf]547        lblTitle->setStyleSheet(QString("QLabel {background-color: %1; border-color: %2; border-width: 1px; border-style: solid; border-radius: 4px; padding: 1px;}").arg(palette().alternateBase().color().name(), palette().shadow().color().name()));
[1babbd6ba3]548#endif // HANDHELD
549
550        lblIcon->setPixmap(QPixmap(":/images/tspsg.png").scaledToHeight(lblTitle->sizeHint().height(), Qt::SmoothTransformation));
551        lblIcon->setAlignment(Qt::AlignVCenter);
552#ifndef HANDHELD
[e3533af1cf]553        lblIcon->setStyleSheet(QString("QLabel {background-color: white; border-color: %1; border-width: 1px; border-style: solid; border-radius: 4px; padding: 1px;}").arg(palette().windowText().color().name()));
[1babbd6ba3]554#endif // HANDHELD
555
556        hb1->addWidget(lblIcon);
557        hb1->addWidget(lblTitle);
558
559        txtAbout->setWordWrapMode(QTextOption::NoWrap);
560        txtAbout->setOpenExternalLinks(true);
561        txtAbout->setHtml(about);
562        txtAbout->moveCursor(QTextCursor::Start);
[43c29c04ba]563        txtAbout->setFrameShape(QFrame::NoFrame);
[1babbd6ba3]564
[43c29c04ba]565//      txtCredits->setWordWrapMode(QTextOption::NoWrap);
566        txtCredits->setOpenExternalLinks(true);
567        txtCredits->setHtml(credits);
568        txtCredits->moveCursor(QTextCursor::Start);
569        txtCredits->setFrameShape(QFrame::NoFrame);
[1babbd6ba3]570
[43c29c04ba]571        txtLicense->setWordWrapMode(QTextOption::NoWrap);
572        txtLicense->setOpenExternalLinks(true);
573        txtLicense->setText(f.readAll());
574        txtLicense->moveCursor(QTextCursor::Start);
575        txtLicense->setFrameShape(QFrame::NoFrame);
[1babbd6ba3]576
[43c29c04ba]577        bb->button(QDialogButtonBox::Ok)->setCursor(QCursor(Qt::PointingHandCursor));
[2a436ea693]578        bb->button(QDialogButtonBox::Ok)->setIcon(GET_ICON("dialog-ok"));
[3cadf24d00]579
[1babbd6ba3]580        hb2->addWidget(bb);
581
[97e90f9be6]582#ifdef Q_WS_WINCE_WM
[1babbd6ba3]583        vb->setMargin(3);
[97e90f9be6]584#endif // Q_WS_WINCE_WM
[1babbd6ba3]585        vb->addLayout(hb1);
586#ifdef HANDHELD
587        vb->addWidget(lblSubTitle);
588#endif // HANDHELD
[43c29c04ba]589
590        tabs->addTab(txtAbout, tr("About"));
591        tabs->addTab(txtLicense, tr("License"));
592        tabs->addTab(txtCredits, tr("Credits"));
593        if (translation != "AUTHORS %1") {
594QTextBrowser *txtTranslation = new QTextBrowser(dlg);
595//              txtTranslation->setWordWrapMode(QTextOption::NoWrap);
596                txtTranslation->setOpenExternalLinks(true);
597                txtTranslation->setText(translation);
598                txtTranslation->moveCursor(QTextCursor::Start);
599                txtTranslation->setFrameShape(QFrame::NoFrame);
600
601                tabs->addTab(txtTranslation, tr("Translation"));
602        }
603#ifndef HANDHELD
604        tabs->setStyleSheet(QString("QTabWidget::pane {background-color: %1; border-color: %3; border-width: 1px; border-style: solid; border-bottom-left-radius: 4px; border-bottom-right-radius: 4px; padding: 1px;} QTabBar::tab {background-color: %2; border-color: %3; border-width: 1px; border-style: solid; border-bottom: none; border-top-left-radius: 4px; border-top-right-radius: 4px; padding: 2px 6px;} QTabBar::tab:selected {background-color: %4;} QTabBar::tab:!selected {margin-top: 1px;}").arg(palette().base().color().name(), palette().button().color().name(), palette().shadow().color().name(), palette().light().color().name()));
605#endif // HANDHELD
606
607        vb->addWidget(tabs);
[1babbd6ba3]608        vb->addLayout(hb2);
609
610        dlg->setWindowFlags(Qt::Dialog | Qt::CustomizeWindowHint | Qt::WindowTitleHint | Qt::WindowCloseButtonHint);
[88a59e4d65]611        dlg->setWindowTitle(tr("About %1").arg(QCoreApplication::applicationName()));
[2a436ea693]612        dlg->setWindowIcon(GET_ICON("help-about"));
[1babbd6ba3]613        dlg->setLayout(vb);
614
615        connect(bb, SIGNAL(accepted()), dlg, SLOT(accept()));
616
[97e90f9be6]617#ifdef Q_WS_WIN32
[1babbd6ba3]618        // Adding some eyecandy in Vista and 7 :-)
619        if (QtWin::isCompositionEnabled())  {
620                QtWin::enableBlurBehindWindow(dlg, true);
621        }
[97e90f9be6]622#endif // Q_WS_WIN32
[1babbd6ba3]623
624        dlg->resize(450, 350);
[43c29c04ba]625        QApplication::restoreOverrideCursor();
[1babbd6ba3]626
627        dlg->exec();
628
629        delete dlg;
630}
631
632void MainWindow::buttonBackToTaskClicked()
633{
634        tabWidget->setCurrentIndex(0);
635}
636
637void MainWindow::buttonRandomClicked()
638{
639        QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
640        tspmodel->randomize();
641        QApplication::restoreOverrideCursor();
642}
643
644void MainWindow::buttonSolveClicked()
645{
646TMatrix matrix;
647QList<double> row;
648int n = spinCities->value();
649bool ok;
650        for (int r = 0; r < n; r++) {
651                row.clear();
652                for (int c = 0; c < n; c++) {
653                        row.append(tspmodel->index(r,c).data(Qt::UserRole).toDouble(&ok));
654                        if (!ok) {
655                                QMessageBox::critical(this, tr("Data error"), tr("Error in cell [Row %1; Column %2]: Invalid data format.").arg(r + 1).arg(c + 1));
656                                return;
657                        }
658                }
659                matrix.append(row);
660        }
661
662QProgressDialog pd(this);
663QProgressBar *pb = new QProgressBar(&pd);
664        pb->setAlignment(Qt::AlignCenter);
665        pb->setFormat(tr("%v of %1 parts found").arg(n));
666        pd.setBar(pb);
[43c29c04ba]667QPushButton *cancel = new QPushButton(&pd);
[2a436ea693]668        cancel->setIcon(GET_ICON("dialog-cancel"));
[88a59e4d65]669        cancel->setText(QCoreApplication::translate("QProgressDialog", "Cancel", "No need to translate this. This translation will be taken from Qt translation files."));
[43c29c04ba]670        pd.setCancelButton(cancel);
[1babbd6ba3]671        pd.setMaximum(n);
672        pd.setAutoReset(false);
673        pd.setLabelText(tr("Calculating optimal route..."));
674        pd.setWindowTitle(tr("Solution Progress"));
675        pd.setWindowModality(Qt::ApplicationModal);
676        pd.setWindowFlags(Qt::Dialog | Qt::CustomizeWindowHint | Qt::WindowTitleHint);
677        pd.show();
678
[97e90f9be6]679#ifdef Q_WS_WIN32
[43c29c04ba]680HRESULT hr = CoCreateInstance(CLSID_TaskbarList, NULL, CLSCTX_INPROC_SERVER, IID_ITaskbarList3, (LPVOID*)&tl);
681        if (SUCCEEDED(hr)) {
682                hr = tl->HrInit();
683                if (FAILED(hr)) {
684                        tl->Release();
685                        tl = NULL;
686                } else {
687//                      tl->SetProgressState(winId(), TBPF_INDETERMINATE);
688                        tl->SetProgressValue(winId(), 0, n * 2);
689                }
690        }
691#endif
692
[1babbd6ba3]693CTSPSolver solver;
[43c29c04ba]694        solver.setCleanupOnCancel(false);
[1babbd6ba3]695        connect(&solver, SIGNAL(routePartFound(int)), &pd, SLOT(setValue(int)));
696        connect(&pd, SIGNAL(canceled()), &solver, SLOT(cancel()));
[97e90f9be6]697#ifdef Q_WS_WIN32
[43c29c04ba]698        if (tl != NULL)
699                connect(&solver, SIGNAL(routePartFound(int)), SLOT(solverRoutePartFound(int)));
700#endif
[1babbd6ba3]701SStep *root = solver.solve(n, matrix);
[97e90f9be6]702#ifdef Q_WS_WIN32
[43c29c04ba]703        if (tl != NULL)
704                disconnect(&solver, SIGNAL(routePartFound(int)), this, SLOT(solverRoutePartFound(int)));
705#endif
[1babbd6ba3]706        disconnect(&solver, SIGNAL(routePartFound(int)), &pd, SLOT(setValue(int)));
707        disconnect(&pd, SIGNAL(canceled()), &solver, SLOT(cancel()));
708        if (!root) {
709                pd.reset();
[43c29c04ba]710                if (!solver.wasCanceled()) {
[97e90f9be6]711#ifdef Q_WS_WIN32
[43c29c04ba]712                        if (tl != NULL) {
713//                              tl->SetProgressValue(winId(), n, n * 2);
714                                tl->SetProgressState(winId(), TBPF_ERROR);
715                        }
716#endif
717                        QApplication::alert(this);
[1babbd6ba3]718                        QMessageBox::warning(this, tr("Solution Result"), tr("Unable to find a solution.\nMaybe, this task has no solution."));
[43c29c04ba]719                }
720                pd.setLabelText(tr("Cleaning up..."));
721                pd.setMaximum(0);
722                pd.setCancelButton(NULL);
723                pd.show();
[97e90f9be6]724#ifdef Q_WS_WIN32
[43c29c04ba]725                if (tl != NULL)
726                        tl->SetProgressState(winId(), TBPF_INDETERMINATE);
727#endif
[88a59e4d65]728                QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
[43c29c04ba]729
[a713b103e8]730#ifndef QT_NO_CONCURRENT
[43c29c04ba]731QFuture<void> f = QtConcurrent::run(&solver, &CTSPSolver::cleanup, false);
732                while (!f.isFinished()) {
[88a59e4d65]733                        QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
[43c29c04ba]734                }
[a713b103e8]735#else
736                solver.cleanup(true);
737#endif
[43c29c04ba]738                pd.reset();
[97e90f9be6]739#ifdef Q_WS_WIN32
[43c29c04ba]740                if (tl != NULL) {
741                        tl->SetProgressState(winId(), TBPF_NOPROGRESS);
742                        tl->Release();
743                        tl = NULL;
744                }
745#endif
[1babbd6ba3]746                return;
747        }
748        pb->setFormat(tr("Generating header"));
749        pd.setLabelText(tr("Generating solution output..."));
[9cda6e0f5d]750        pd.setMaximum(solver.getTotalSteps() + 1);
[1babbd6ba3]751        pd.setValue(0);
752
[97e90f9be6]753#ifdef Q_WS_WIN32
[43c29c04ba]754        if (tl != NULL)
755                tl->SetProgressValue(winId(), spinCities->value(), spinCities->value() + solver.getTotalSteps() + 1);
756#endif
757
[1babbd6ba3]758        solutionText->clear();
[317ba0432e]759        solutionText->setDocumentTitle(tr("Solution of Variant #%1 Task").arg(spinVariant->value()));
760
[345e7b6132]761QPainter pic;
[9cda6e0f5d]762        if (settings->value("Output/ShowGraph", DEF_SHOW_GRAPH).toBool()) {
763                pic.begin(&graph);
[7aaa0b0ec7]764                pic.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform);
[a713b103e8]765QFont font = qvariant_cast<QFont>(settings->value("Output/Font", QFont(DEF_FONT_FACE, 9)));
[e26679937d]766                if (settings->value("Output/HQGraph", DEF_HQ_GRAPH).toBool()) {
767                        font.setWeight(QFont::DemiBold);
768                        font.setPointSizeF(font.pointSizeF() * 2);
769                }
[7aaa0b0ec7]770                pic.setFont(font);
[20015b41e7]771                pic.setBrush(QBrush(QColor(Qt::white)));
[e26679937d]772                if (settings->value("Output/HQGraph", DEF_HQ_GRAPH).toBool()) {
[7aaa0b0ec7]773QPen pen = pic.pen();
[e26679937d]774                        pen.setWidth(2);
775                        pic.setPen(pen);
776                }
[20015b41e7]777                pic.setBackgroundMode(Qt::OpaqueMode);
[9cda6e0f5d]778        }
[345e7b6132]779
[317ba0432e]780QTextDocument *doc = solutionText->document();
781QTextCursor cur(doc);
782
783        cur.beginEditBlock();
784        cur.setBlockFormat(fmt_paragraph);
[345e7b6132]785        cur.insertText(tr("Variant #%1 Task").arg(spinVariant->value()), fmt_default);
[317ba0432e]786        cur.insertBlock(fmt_paragraph);
787        cur.insertText(tr("Task:"));
788        outputMatrix(cur, matrix);
[3cadf24d00]789        if (settings->value("Output/ShowGraph", DEF_SHOW_GRAPH).toBool()) {
790#ifdef _T_T_L_
[e9db3e216b]791                _b_ _i_ _z_ _a_ _r_ _r_ _e_
[3cadf24d00]792#endif
[9cda6e0f5d]793                drawNode(pic, 0);
[3cadf24d00]794        }
[317ba0432e]795        cur.insertHtml("<hr>");
796        cur.insertBlock(fmt_paragraph);
[345e7b6132]797int imgpos = cur.position();
798        cur.insertText(tr("Variant #%1 Solution").arg(spinVariant->value()), fmt_default);
[317ba0432e]799        cur.endEditBlock();
800
[1babbd6ba3]801SStep *step = root;
[9cda6e0f5d]802int c = n = 1;
[1babbd6ba3]803        pb->setFormat(tr("Generating step %v"));
[9cda6e0f5d]804        while ((step->next != SStep::NoNextStep) && (c < spinCities->value())) {
[1babbd6ba3]805                if (pd.wasCanceled()) {
[317ba0432e]806                        pd.setLabelText(tr("Cleaning up..."));
807                        pd.setMaximum(0);
808                        pd.setCancelButton(NULL);
809                        pd.show();
[88a59e4d65]810                        QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
[97e90f9be6]811#ifdef Q_WS_WIN32
[43c29c04ba]812                        if (tl != NULL)
813                                tl->SetProgressState(winId(), TBPF_INDETERMINATE);
814#endif
[a713b103e8]815#ifndef QT_NO_CONCURRENT
[43c29c04ba]816QFuture<void> f = QtConcurrent::run(&solver, &CTSPSolver::cleanup, false);
817                        while (!f.isFinished()) {
[88a59e4d65]818                                QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
[43c29c04ba]819                        }
[a713b103e8]820#else
821                        solver.cleanup(true);
822#endif
[1babbd6ba3]823                        solutionText->clear();
[317ba0432e]824                        toggleSolutionActions(false);
[97e90f9be6]825#ifdef Q_WS_WIN32
[43c29c04ba]826                        if (tl != NULL) {
827                                tl->SetProgressState(winId(), TBPF_NOPROGRESS);
828                                tl->Release();
829                                tl = NULL;
830                        }
831#endif
[1babbd6ba3]832                        return;
833                }
834                pd.setValue(n);
[97e90f9be6]835#ifdef Q_WS_WIN32
[43c29c04ba]836                if (tl != NULL)
837                        tl->SetProgressValue(winId(), spinCities->value() + n, spinCities->value() + solver.getTotalSteps() + 1);
838#endif
[1babbd6ba3]839
[9cda6e0f5d]840                cur.beginEditBlock();
841                cur.insertBlock(fmt_paragraph);
842                cur.insertText(tr("Step #%1").arg(n));
843                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())))) {
844                        outputMatrix(cur, *step);
845                }
846                cur.insertBlock(fmt_paragraph);
847                cur.insertText(tr("Selected route %1 %2 part.").arg((step->next == SStep::RightBranch) ? tr("with") : tr("without")).arg(tr("(%1;%2)").arg(step->candidate.nRow + 1).arg(step->candidate.nCol + 1)), fmt_default);
848                if (!step->alts.empty()) {
849                        SStep::SCandidate cand;
850                        QString alts;
851                        foreach(cand, step->alts) {
852                                if (!alts.isEmpty())
853                                        alts += ", ";
854                                alts += tr("(%1;%2)").arg(cand.nRow + 1).arg(cand.nCol + 1);
[1babbd6ba3]855                        }
[9cda6e0f5d]856                        cur.insertBlock(fmt_paragraph);
857                        cur.insertText(tr("%n alternate candidate(s) for branching: %1.", "", step->alts.count()).arg(alts), fmt_altlist);
[1babbd6ba3]858                }
[9cda6e0f5d]859                cur.insertBlock(fmt_paragraph);
860                cur.insertText(" ", fmt_default);
861                cur.endEditBlock();
862
863                if (settings->value("Output/ShowGraph", DEF_SHOW_GRAPH).toBool()) {
[345e7b6132]864                        if (step->prNode != NULL)
[9cda6e0f5d]865                                drawNode(pic, n, false, step->prNode);
[345e7b6132]866                        if (step->plNode != NULL)
[9cda6e0f5d]867                                drawNode(pic, n, true, step->plNode);
[345e7b6132]868                }
[9cda6e0f5d]869                n++;
870
871                if (step->next == SStep::RightBranch) {
872                        c++;
[1babbd6ba3]873                        step = step->prNode;
[9cda6e0f5d]874                } else if (step->next == SStep::LeftBranch) {
[1babbd6ba3]875                        step = step->plNode;
[345e7b6132]876                } else
[1babbd6ba3]877                        break;
878        }
879        pb->setFormat(tr("Generating footer"));
880        pd.setValue(n);
[97e90f9be6]881#ifdef Q_WS_WIN32
[43c29c04ba]882        if (tl != NULL)
883                tl->SetProgressValue(winId(), spinCities->value() + n, spinCities->value() + solver.getTotalSteps() + 1);
884#endif
[1babbd6ba3]885
[317ba0432e]886        cur.beginEditBlock();
887        cur.insertBlock(fmt_paragraph);
[1babbd6ba3]888        if (solver.isOptimal())
[317ba0432e]889                cur.insertText(tr("Optimal path:"));
[1babbd6ba3]890        else
[317ba0432e]891                cur.insertText(tr("Resulting path:"));
892
893        cur.insertBlock(fmt_paragraph);
[5d401f2c50]894        cur.insertText("  " + solver.getSortedPath(tr("City %1")));
[317ba0432e]895
896        cur.insertBlock(fmt_paragraph);
[1babbd6ba3]897        if (isInteger(step->price))
[317ba0432e]898                cur.insertHtml("<p>" + tr("The price is <b>%n</b> unit(s).", "", qRound(step->price)) + "</p>");
[1babbd6ba3]899        else
[317ba0432e]900                cur.insertHtml("<p>" + tr("The price is <b>%1</b> units.").arg(step->price, 0, 'f', settings->value("Task/FractionalAccuracy", DEF_FRACTIONAL_ACCURACY).toInt()) + "</p>");
[1babbd6ba3]901        if (!solver.isOptimal()) {
[317ba0432e]902                cur.insertBlock(fmt_paragraph);
903                cur.insertText(" ");
904                cur.insertBlock(fmt_paragraph);
905                cur.insertHtml("<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>");
[1babbd6ba3]906        }
[317ba0432e]907        cur.endEditBlock();
[9cda6e0f5d]908
909        if (settings->value("Output/ShowGraph", DEF_SHOW_GRAPH).toBool()) {
910                pic.end();
[345e7b6132]911
[131c5fc3ba]912QImage i(graph.width() + 2, graph.height() + 2, QImage::Format_RGB32);
[e26679937d]913                i.fill(0xFFFFFF);
[9cda6e0f5d]914                pic.begin(&i);
915                pic.drawPicture(1, 1, graph);
916                pic.end();
917                doc->addResource(QTextDocument::ImageResource, QUrl("tspsg://graph.pic"), i);
[345e7b6132]918
919QTextImageFormat img;
[9cda6e0f5d]920                img.setName("tspsg://graph.pic");
[e26679937d]921                if (settings->value("Output/HQGraph", DEF_HQ_GRAPH).toBool()) {
922                        img.setWidth(i.width() / 2);
923                        img.setHeight(i.height() / 2);
924                } else {
925                        img.setWidth(i.width());
926                        img.setHeight(i.height());
927                }
[345e7b6132]928
[9cda6e0f5d]929                cur.setPosition(imgpos);
930                cur.insertImage(img, QTextFrameFormat::FloatRight);
931        }
[1babbd6ba3]932
933        if (settings->value("Output/ScrollToEnd", DEF_SCROLL_TO_END).toBool()) {
[317ba0432e]934                // Scrolling to the end of the text.
[1babbd6ba3]935                solutionText->moveCursor(QTextCursor::End);
936        } else
937                solutionText->moveCursor(QTextCursor::Start);
938
939        pd.setLabelText(tr("Cleaning up..."));
940        pd.setMaximum(0);
941        pd.setCancelButton(NULL);
[88a59e4d65]942        QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
[97e90f9be6]943#ifdef Q_WS_WIN32
[43c29c04ba]944        if (tl != NULL)
945                tl->SetProgressState(winId(), TBPF_INDETERMINATE);
946#endif
[a713b103e8]947#ifndef QT_NO_CONCURRENT
[43c29c04ba]948QFuture<void> f = QtConcurrent::run(&solver, &CTSPSolver::cleanup, false);
949        while (!f.isFinished()) {
[88a59e4d65]950                QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
[43c29c04ba]951        }
[a713b103e8]952#else
953        solver.cleanup(true);
954#endif
[1babbd6ba3]955        toggleSolutionActions();
956        tabWidget->setCurrentIndex(1);
[97e90f9be6]957#ifdef Q_WS_WIN32
[43c29c04ba]958        if (tl != NULL) {
959                tl->SetProgressState(winId(), TBPF_NOPROGRESS);
960                tl->Release();
961                tl = NULL;
962        }
963#endif
964
965        pd.reset();
966        QApplication::alert(this, 3000);
[1babbd6ba3]967}
968
969void MainWindow::dataChanged()
970{
971        setWindowModified(true);
972}
973
974void MainWindow::dataChanged(const QModelIndex &tl, const QModelIndex &br)
975{
976        setWindowModified(true);
977        if (settings->value("Autosize", DEF_AUTOSIZE).toBool()) {
978                for (int k = tl.row(); k <= br.row(); k++)
979                        taskView->resizeRowToContents(k);
980                for (int k = tl.column(); k <= br.column(); k++)
981                        taskView->resizeColumnToContents(k);
982        }
983}
984
[97e90f9be6]985#ifdef Q_WS_WINCE_WM
[1babbd6ba3]986void MainWindow::changeEvent(QEvent *ev)
987{
988        if ((ev->type() == QEvent::ActivationChange) && isActiveWindow())
989                desktopResized(0);
990
991        QWidget::changeEvent(ev);
992}
993
994void MainWindow::desktopResized(int screen)
995{
996        if ((screen != 0) || !isActiveWindow())
997                return;
998
999QRect availableGeometry = QApplication::desktop()->availableGeometry(0);
1000        if (currentGeometry != availableGeometry) {
1001                QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
1002                /*!
1003                 * \hack HACK: This hack checks whether \link QDesktopWidget::availableGeometry() availableGeometry()\endlink's \c top + \c hegiht = \link QDesktopWidget::screenGeometry() screenGeometry()\endlink's \c height.
1004                 *  If \c true, the window gets maximized. If we used \c setGeometry() in this case, the bottom of the
1005                 *  window would end up being behind the soft buttons. Is this a bug in Qt or Windows Mobile?
1006                 */
1007                if ((availableGeometry.top() + availableGeometry.height()) == QApplication::desktop()->screenGeometry().height()) {
1008                        setWindowState(windowState() | Qt::WindowMaximized);
1009                } else {
1010                        if (windowState() & Qt::WindowMaximized)
1011                                setWindowState(windowState() ^ Qt::WindowMaximized);
1012                        setGeometry(availableGeometry);
1013                }
1014                currentGeometry = availableGeometry;
1015                QApplication::restoreOverrideCursor();
1016        }
1017}
[97e90f9be6]1018#endif // Q_WS_WINCE_WM
[1babbd6ba3]1019
1020void MainWindow::numCitiesChanged(int nCities)
1021{
1022        blockSignals(true);
1023        spinCities->setValue(nCities);
1024        blockSignals(false);
1025}
1026
1027#ifndef QT_NO_PRINTER
1028void MainWindow::printPreview(QPrinter *printer)
1029{
1030        solutionText->print(printer);
1031}
1032#endif // QT_NO_PRINTER
1033
[97e90f9be6]1034#ifdef Q_WS_WIN32
[43c29c04ba]1035void MainWindow::solverRoutePartFound(int n)
1036{
[97e90f9be6]1037#ifdef Q_WS_WIN32
[43c29c04ba]1038        tl->SetProgressValue(winId(), n, spinCities->value() * 2);
1039#else
1040        Q_UNUSED(n);
[97e90f9be6]1041#endif // Q_WS_WIN32
[43c29c04ba]1042}
[97e90f9be6]1043#endif // Q_WS_WIN32
[43c29c04ba]1044
[1babbd6ba3]1045void MainWindow::spinCitiesValueChanged(int n)
1046{
1047        QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
1048int count = tspmodel->numCities();
1049        tspmodel->setNumCities(n);
1050        if ((n > count) && settings->value("Autosize", DEF_AUTOSIZE).toBool())
1051                for (int k = count; k < n; k++) {
1052                        taskView->resizeColumnToContents(k);
1053                        taskView->resizeRowToContents(k);
1054                }
1055        QApplication::restoreOverrideCursor();
1056}
1057
[f5c945d7ac]1058void MainWindow::check4Updates(bool silent)
1059{
[97e90f9be6]1060#ifdef Q_WS_WIN32
[f5c945d7ac]1061        if (silent)
1062                QProcess::startDetached("updater/Update.exe -name=\"TSPSG: TSP Solver and Generator\" -check=\"freeupdate\" -silentcheck");
1063        else {
1064                QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
1065                QProcess::execute("updater/Update.exe -name=\"TSPSG: TSP Solver and Generator\" -check=\"freeupdate\"");
1066                QApplication::restoreOverrideCursor();
1067        }
[0007f69c46]1068#else
1069        Q_UNUSED(silent)
[f5c945d7ac]1070#endif
1071        settings->setValue("Check4Updates/LastAttempt", QDate::currentDate().toString(Qt::ISODate));
1072}
1073
[1babbd6ba3]1074void MainWindow::closeEvent(QCloseEvent *ev)
1075{
1076        if (!maybeSave()) {
1077                ev->ignore();
1078                return;
1079        }
1080        if (!settings->value("SettingsReset", false).toBool()) {
1081                settings->setValue("NumCities", spinCities->value());
1082
1083                // Saving Main Window state
[7bb19df196]1084#ifndef HANDHELD
[1babbd6ba3]1085                if (settings->value("SavePos", DEF_SAVEPOS).toBool()) {
1086                        settings->beginGroup("MainWindow");
1087                        settings->setValue("Geometry", saveGeometry());
1088                        settings->setValue("State", saveState());
[7bb19df196]1089                        settings->setValue("Toolbars", toolBarManager->saveState());
[1babbd6ba3]1090                        settings->endGroup();
1091                }
[a713b103e8]1092#else
1093                settings->setValue("MainWindow/ToolbarVisible", toolBarMain->isVisible());
[7bb19df196]1094#endif // HANDHELD
[1babbd6ba3]1095        } else {
1096                settings->remove("SettingsReset");
1097        }
1098
1099        QMainWindow::closeEvent(ev);
1100}
1101
[b574c383b7]1102void MainWindow::dragEnterEvent(QDragEnterEvent *ev)
1103{
1104        if (ev->mimeData()->hasUrls() && (ev->mimeData()->urls().count() == 1)) {
1105QFileInfo fi(ev->mimeData()->urls().first().toLocalFile());
1106                if ((fi.suffix() == "tspt") || (fi.suffix() == "zkt"))
1107                        ev->acceptProposedAction();
1108        }
1109}
1110
[345e7b6132]1111void MainWindow::drawNode(QPainter &pic, int nstep, bool left, SStep *step)
1112{
[e26679937d]1113int r;
1114        if (settings->value("Output/HQGraph", DEF_HQ_GRAPH).toBool())
1115                r = 70;
1116        else
1117                r = 35;
[345e7b6132]1118qreal x, y;
1119        if (step != NULL)
1120                x = left ? r : r * 3.5;
1121        else
1122                x = r * 2.25;
1123        y = r * (3 * nstep + 1);
1124
[3cadf24d00]1125#ifdef _T_T_L_
1126        if (nstep == -481124) {
1127                _t_t_l_(pic, r, x);
1128                return;
1129        }
1130#endif
1131
[345e7b6132]1132        pic.drawEllipse(QPointF(x, y), r, r);
1133
1134        if (step != NULL) {
1135QFont font;
1136                if (left) {
1137                        font = pic.font();
1138                        font.setStrikeOut(true);
1139                        pic.setFont(font);
1140                }
1141                pic.drawText(QRectF(x - r, y - r, r * 2, r * 2), Qt::AlignCenter, tr("(%1;%2)").arg(step->pNode->candidate.nRow + 1).arg(step->pNode->candidate.nCol + 1) + "\n");
1142                if (left) {
1143                        font.setStrikeOut(false);
1144                        pic.setFont(font);
1145                }
[9cda6e0f5d]1146                if (step->price != INFINITY) {
1147                        pic.drawText(QRectF(x - r, y - r, r * 2, r * 2), Qt::AlignCenter, isInteger(step->price) ?  QString("\n%1").arg(step->price) : QString("\n%1").arg(step->price, 0, 'f', settings->value("Task/FractionalAccuracy", DEF_FRACTIONAL_ACCURACY).toInt()));
1148                } else {
1149                        pic.drawText(QRectF(x - r, y - r, r * 2, r * 2), Qt::AlignCenter, "\n"INFSTR);
1150                }
[345e7b6132]1151        } else {
1152                pic.drawText(QRectF(x - r, y - r, r * 2, r * 2), Qt::AlignCenter, tr("Root"));
1153        }
1154
[9cda6e0f5d]1155        if (nstep == 1) {
1156                pic.drawLine(QPointF(x, y - r), QPointF(r * 2.25, y - 2 * r));
1157        } else if (nstep > 1) {
[5d401f2c50]1158                pic.drawLine(QPointF(x, y - r), QPointF((step->pNode->pNode->next == SStep::RightBranch) ? r * 3.5 : r, y - 2 * r));
[9cda6e0f5d]1159        }
[345e7b6132]1160
1161}
1162
[b574c383b7]1163void MainWindow::dropEvent(QDropEvent *ev)
1164{
1165        if (maybeSave() && tspmodel->loadTask(ev->mimeData()->urls().first().toLocalFile())) {
1166                setFileName(ev->mimeData()->urls().first().toLocalFile());
1167                tabWidget->setCurrentIndex(0);
1168                setWindowModified(false);
1169                solutionText->clear();
1170                toggleSolutionActions(false);
1171
[9cda6e0f5d]1172                ev->setDropAction(Qt::CopyAction);
1173                ev->accept();
[b574c383b7]1174        }
1175}
1176
[1babbd6ba3]1177void MainWindow::initDocStyleSheet()
1178{
[a713b103e8]1179        solutionText->document()->setDefaultFont(qvariant_cast<QFont>(settings->value("Output/Font", QFont(DEF_FONT_FACE, DEF_FONT_SIZE))));
[317ba0432e]1180
1181        fmt_paragraph.setTopMargin(0);
1182        fmt_paragraph.setRightMargin(10);
1183        fmt_paragraph.setBottomMargin(0);
1184        fmt_paragraph.setLeftMargin(10);
1185
1186        fmt_table.setTopMargin(5);
1187        fmt_table.setRightMargin(10);
1188        fmt_table.setBottomMargin(5);
1189        fmt_table.setLeftMargin(10);
1190        fmt_table.setBorder(0);
1191        fmt_table.setBorderStyle(QTextFrameFormat::BorderStyle_None);
1192        fmt_table.setCellSpacing(5);
1193
[345e7b6132]1194        fmt_cell.setAlignment(Qt::AlignHCenter);
[317ba0432e]1195
[8b0661d1ee]1196        settings->beginGroup("Output/Colors");
1197
[a713b103e8]1198QColor color = qvariant_cast<QColor>(settings->value("Text", DEF_TEXT_COLOR));
[1babbd6ba3]1199QColor hilight;
1200        if (color.value() < 192)
[317ba0432e]1201                hilight.setHsv(color.hue(), color.saturation(), 127 + qRound(color.value() / 2));
[1babbd6ba3]1202        else
[317ba0432e]1203                hilight.setHsv(color.hue(), color.saturation(), color.value() / 2);
1204
1205        solutionText->document()->setDefaultStyleSheet(QString("* {color: %1;}").arg(color.name()));
1206        fmt_default.setForeground(QBrush(color));
1207
[a713b103e8]1208        fmt_selected.setForeground(QBrush(qvariant_cast<QColor>(settings->value("Selected", DEF_SELECTED_COLOR))));
[317ba0432e]1209        fmt_selected.setFontWeight(QFont::Bold);
1210
[a713b103e8]1211        fmt_alternate.setForeground(QBrush(qvariant_cast<QColor>(settings->value("Alternate", DEF_ALTERNATE_COLOR))));
[317ba0432e]1212        fmt_alternate.setFontWeight(QFont::Bold);
1213        fmt_altlist.setForeground(QBrush(hilight));
1214
[8b0661d1ee]1215        settings->endGroup();
1216
[317ba0432e]1217        solutionText->setTextColor(color);
[1babbd6ba3]1218}
1219
1220void MainWindow::loadLangList()
1221{
[3cadf24d00]1222QMap<QString, QStringList> langlist;
1223QFileInfoList langs;
1224QFileInfo lang;
[1babbd6ba3]1225QString name;
[3cadf24d00]1226QStringList language, dirs;
1227QTranslator t;
1228QDir dir;
1229        dir.setFilter(QDir::Files);
1230        dir.setNameFilters(QStringList("tspsg_*.qm"));
1231        dir.setSorting(QDir::NoSort);
1232
1233        dirs << PATH_L10N << ":/l10n";
1234        foreach (QString dirname, dirs) {
1235                dir.setPath(dirname);
1236                if (dir.exists()) {
1237                        langs = dir.entryInfoList();
1238                        for (int k = 0; k < langs.size(); k++) {
1239                                lang = langs.at(k);
1240                                if (lang.completeBaseName().compare("tspsg_en", Qt::CaseInsensitive) && !langlist.contains(lang.completeBaseName().mid(6)) && t.load(lang.completeBaseName(), dirname)) {
1241
1242                                        language.clear();
1243                                        language.append(lang.completeBaseName().mid(6));
1244                                        language.append(t.translate("--------", "COUNTRY", "Please, provide an ISO 3166-1 alpha-2 country code for this translation language here (eg., UA).").toLower());
1245                                        language.append(t.translate("--------", "LANGNAME", "Please, provide a native name of your translation language here."));
1246                                        language.append(t.translate("MainWindow", "Set application language to %1", "").arg(name));
1247
1248                                        langlist.insert(language.at(0), language);
1249                                }
1250                        }
[1babbd6ba3]1251                }
1252        }
[3cadf24d00]1253
1254QAction *a;
1255        foreach (language, langlist) {
1256                a = menuSettingsLanguage->addAction(language.at(2));
[9adbc413c7]1257#ifndef QT_NO_STATUSTIP
[3cadf24d00]1258                a->setStatusTip(language.at(3));
[9adbc413c7]1259#endif
[2a436ea693]1260#if QT_VERSION >= 0x040600
[d2820c3a1f]1261                a->setIcon(QIcon::fromTheme(QString("flag-%1").arg(language.at(1)), QIcon(QString(":/images/icons/l10n/flag-%1.png").arg(language.at(1)))));
[2a436ea693]1262#else
1263                a->setIcon(QIcon(QString(":/images/icons/l10n/flag-%1.png").arg(language.at(1))));
1264#endif
[3cadf24d00]1265                a->setData(language.at(0));
1266                a->setCheckable(true);
1267                a->setActionGroup(groupSettingsLanguageList);
1268                if (settings->value("Language", QLocale::system().name()).toString().startsWith(language.at(0)))
1269                        a->setChecked(true);
1270        }
[1babbd6ba3]1271}
1272
1273bool MainWindow::loadLanguage(const QString &lang)
1274{
1275// i18n
1276bool ad = false;
1277QString lng = lang;
1278        if (lng.isEmpty()) {
[97e90f9be6]1279                ad = settings->value("Language").toString().isEmpty();
[1babbd6ba3]1280                lng = settings->value("Language", QLocale::system().name()).toString();
1281        }
1282static QTranslator *qtTranslator; // Qt library translator
1283        if (qtTranslator) {
1284                qApp->removeTranslator(qtTranslator);
1285                delete qtTranslator;
1286                qtTranslator = NULL;
1287        }
1288static QTranslator *translator; // Application translator
1289        if (translator) {
1290                qApp->removeTranslator(translator);
1291                delete translator;
1292                translator = NULL;
1293        }
1294
1295        if (lng == "en")
1296                return true;
1297
1298        // Trying to load system Qt library translation...
1299        qtTranslator = new QTranslator(this);
1300        if (qtTranslator->load("qt_" + lng, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
1301                qApp->installTranslator(qtTranslator);
1302        else {
1303                // No luck. Let's try to load a bundled one.
[3cadf24d00]1304                if (qtTranslator->load("qt_" + lng, PATH_L10N)) {
1305                        // We have a translation in the localization direcotry.
[1babbd6ba3]1306                        qApp->installTranslator(qtTranslator);
[3cadf24d00]1307                } else if (qtTranslator->load("qt_" + lng, ":/l10n")) {
1308                        // We have a translation "built-in" into application resources.
1309                        qApp->installTranslator(qtTranslator);
1310                } else {
1311                        // Qt library translation unavailable for this language.
[1babbd6ba3]1312                        delete qtTranslator;
1313                        qtTranslator = NULL;
1314                }
1315        }
1316
1317        // Now let's load application translation.
1318        translator = new QTranslator(this);
[3cadf24d00]1319        if (translator->load("tspsg_" + lng, PATH_L10N)) {
1320                // We have a translation in the localization directory.
[1babbd6ba3]1321                qApp->installTranslator(translator);
[3cadf24d00]1322        } else if (translator->load("tspsg_" + lng, ":/l10n")) {
1323                // We have a translation "built-in" into application resources.
1324                qApp->installTranslator(translator);
1325        } else {
[1babbd6ba3]1326                delete translator;
1327                translator = NULL;
1328                if (!ad) {
1329                        settings->remove("Language");
1330                        QApplication::setOverrideCursor(QCursor(Qt::ArrowCursor));
[3cadf24d00]1331                        QMessageBox::warning(isVisible() ? this : NULL, tr("Language Change"), tr("Unable to load the translation language.\nFalling back to autodetection."));
[1babbd6ba3]1332                        QApplication::restoreOverrideCursor();
1333                }
1334                return false;
1335        }
1336        return true;
1337}
1338
[e3533af1cf]1339void MainWindow::loadStyleList()
1340{
1341        menuSettingsStyle->clear();
1342QStringList styles = QStyleFactory::keys();
1343        menuSettingsStyle->insertAction(NULL, actionSettingsStyleSystem);
1344        actionSettingsStyleSystem->setChecked(!settings->contains("Style"));
1345        menuSettingsStyle->addSeparator();
1346QAction *a;
1347        foreach (QString style, styles) {
1348                a = menuSettingsStyle->addAction(style);
1349                a->setData(false);
[9adbc413c7]1350#ifndef QT_NO_STATUSTIP
[e3533af1cf]1351                a->setStatusTip(tr("Set application style to %1").arg(style));
[9adbc413c7]1352#endif
[e3533af1cf]1353                a->setCheckable(true);
1354                a->setActionGroup(groupSettingsStyleList);
[97e90f9be6]1355                if ((style == settings->value("Stlye").toString())
1356#ifndef Q_WS_MAEMO_5
1357                        || QString(QApplication::style()->metaObject()->className()).contains(QRegExp(QString("^Q?%1(Style)?$").arg(QRegExp::escape(style)), Qt::CaseInsensitive))
1358#endif
1359                ) {
[e3533af1cf]1360                        a->setChecked(true);
1361                }
1362        }
1363}
1364
[7bb19df196]1365void MainWindow::loadToolbarList()
1366{
1367        menuSettingsToolbars->clear();
1368#ifndef HANDHELD
1369        menuSettingsToolbars->insertAction(NULL, actionSettingsToolbarsConfigure);
1370        menuSettingsToolbars->addSeparator();
1371QList<QToolBar *> list = toolBarManager->toolBars();
1372        foreach (QToolBar *t, list) {
1373                menuSettingsToolbars->insertAction(NULL, t->toggleViewAction());
1374        }
1375#else // HANDHELD
1376        menuSettingsToolbars->insertAction(NULL, toolBarMain->toggleViewAction());
1377#endif // HANDHELD
1378}
1379
[1babbd6ba3]1380bool MainWindow::maybeSave()
1381{
1382        if (!isWindowModified())
1383                return true;
1384int res = QMessageBox::warning(this, tr("Unsaved Changes"), tr("Would you like to save changes in the current task?"), QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel);
1385        if (res == QMessageBox::Save)
1386                return actionFileSaveTriggered();
1387        else if (res == QMessageBox::Cancel)
1388                return false;
1389        else
1390                return true;
1391}
1392
[317ba0432e]1393void MainWindow::outputMatrix(QTextCursor &cur, const TMatrix &matrix)
[1babbd6ba3]1394{
1395int n = spinCities->value();
[317ba0432e]1396QTextTable *table = cur.insertTable(n, n, fmt_table);
1397
[1babbd6ba3]1398        for (int r = 0; r < n; r++) {
1399                for (int c = 0; c < n; c++) {
[317ba0432e]1400                        cur = table->cellAt(r, c).firstCursorPosition();
[345e7b6132]1401                        cur.setBlockFormat(fmt_cell);
[317ba0432e]1402                        cur.setBlockCharFormat(fmt_default);
[1babbd6ba3]1403                        if (matrix.at(r).at(c) == INFINITY)
[317ba0432e]1404                                cur.insertText(INFSTR);
[1babbd6ba3]1405                        else
[317ba0432e]1406                                cur.insertText(isInteger(matrix.at(r).at(c)) ? QString("%1").arg(matrix.at(r).at(c)) : QString("%1").arg(matrix.at(r).at(c), 0, 'f', settings->value("Task/FractionalAccuracy", DEF_FRACTIONAL_ACCURACY).toInt()));
[1babbd6ba3]1407                }
[88a59e4d65]1408                QCoreApplication::processEvents();
[1babbd6ba3]1409        }
[317ba0432e]1410        cur.movePosition(QTextCursor::End);
[1babbd6ba3]1411}
1412
[317ba0432e]1413void MainWindow::outputMatrix(QTextCursor &cur, const SStep &step)
[1babbd6ba3]1414{
1415int n = spinCities->value();
[317ba0432e]1416QTextTable *table = cur.insertTable(n, n, fmt_table);
1417
[1babbd6ba3]1418        for (int r = 0; r < n; r++) {
1419                for (int c = 0; c < n; c++) {
[317ba0432e]1420                        cur = table->cellAt(r, c).firstCursorPosition();
[345e7b6132]1421                        cur.setBlockFormat(fmt_cell);
[1babbd6ba3]1422                        if (step.matrix.at(r).at(c) == INFINITY)
[317ba0432e]1423                                cur.insertText(INFSTR, fmt_default);
[1babbd6ba3]1424                        else if ((r == step.candidate.nRow) && (c == step.candidate.nCol))
[317ba0432e]1425                                cur.insertText(isInteger(step.matrix.at(r).at(c)) ? QString("%1").arg(step.matrix.at(r).at(c)) : QString("%1").arg(step.matrix.at(r).at(c), 0, 'f', settings->value("Task/FractionalAccuracy", DEF_FRACTIONAL_ACCURACY).toInt()), fmt_selected);
[1babbd6ba3]1426                        else {
[9cda6e0f5d]1427SStep::SCandidate cand;
[1babbd6ba3]1428                                cand.nRow = r;
1429                                cand.nCol = c;
1430                                if (step.alts.contains(cand))
[317ba0432e]1431                                        cur.insertText(isInteger(step.matrix.at(r).at(c)) ? QString("%1").arg(step.matrix.at(r).at(c)) : QString("%1").arg(step.matrix.at(r).at(c), 0, 'f', settings->value("Task/FractionalAccuracy", DEF_FRACTIONAL_ACCURACY).toInt()), fmt_alternate);
[1babbd6ba3]1432                                else
[317ba0432e]1433                                        cur.insertText(isInteger(step.matrix.at(r).at(c)) ? QString("%1").arg(step.matrix.at(r).at(c)) : QString("%1").arg(step.matrix.at(r).at(c), 0, 'f', settings->value("Task/FractionalAccuracy", DEF_FRACTIONAL_ACCURACY).toInt()), fmt_default);
[1babbd6ba3]1434                        }
1435                }
[88a59e4d65]1436                QCoreApplication::processEvents();
[1babbd6ba3]1437        }
[317ba0432e]1438
1439        cur.movePosition(QTextCursor::End);
[1babbd6ba3]1440}
1441
1442void MainWindow::retranslateUi(bool all)
1443{
1444        if (all)
[a713b103e8]1445                Ui_MainWindow::retranslateUi(this);
[1babbd6ba3]1446
[e3533af1cf]1447        loadStyleList();
[7bb19df196]1448        loadToolbarList();
[e3533af1cf]1449
[1babbd6ba3]1450#ifndef QT_NO_PRINTER
[7bb19df196]1451        actionFilePrintPreview->setText(tr("P&rint Preview..."));
[1babbd6ba3]1452#ifndef QT_NO_TOOLTIP
[7bb19df196]1453        actionFilePrintPreview->setToolTip(tr("Preview solution results"));
[1babbd6ba3]1454#endif // QT_NO_TOOLTIP
1455#ifndef QT_NO_STATUSTIP
[7bb19df196]1456        actionFilePrintPreview->setStatusTip(tr("Preview current solution results before printing"));
[88a59e4d65]1457        actionFileExit->setStatusTip(tr("Exit %1").arg(QCoreApplication::applicationName()));
1458#endif // QT_NO_STATUSTIP
[1babbd6ba3]1459
[7bb19df196]1460        actionFilePrint->setText(tr("&Print..."));
[1babbd6ba3]1461#ifndef QT_NO_TOOLTIP
[7bb19df196]1462        actionFilePrint->setToolTip(tr("Print solution"));
[1babbd6ba3]1463#endif // QT_NO_TOOLTIP
1464#ifndef QT_NO_STATUSTIP
[7bb19df196]1465        actionFilePrint->setStatusTip(tr("Print current solution results"));
[1babbd6ba3]1466#endif // QT_NO_STATUSTIP
[7bb19df196]1467        actionFilePrint->setShortcut(tr("Ctrl+P"));
[1babbd6ba3]1468#endif // QT_NO_PRINTER
[8b0661d1ee]1469
1470#ifndef HANDHELD
1471        actionSettingsToolbarsConfigure->setText(tr("Configure..."));
1472#ifndef QT_NO_STATUSTIP
1473        actionSettingsToolbarsConfigure->setStatusTip(tr("Customize toolbars"));
1474#endif // QT_NO_STATUSTIP
1475#endif // HANDHELD
1476
[88a59e4d65]1477#ifndef QT_NO_STATUSTIP
1478        actionHelpReportBug->setStatusTip(tr("Report about a bug in %1").arg(QCoreApplication::applicationName()));
1479#endif // QT_NO_STATUSTIP
[f5c945d7ac]1480        if (actionHelpCheck4Updates != NULL) {
1481                actionHelpCheck4Updates->setText(tr("Check for &Updates..."));
[1babbd6ba3]1482#ifndef QT_NO_STATUSTIP
[88a59e4d65]1483                actionHelpCheck4Updates->setStatusTip(tr("Check for %1 updates").arg(QCoreApplication::applicationName()));
[1babbd6ba3]1484#endif // QT_NO_STATUSTIP
[f5c945d7ac]1485        }
[88a59e4d65]1486#ifndef QT_NO_STATUSTIP
1487        actionHelpAbout->setStatusTip(tr("About %1").arg(QCoreApplication::applicationName()));
1488#endif // QT_NO_STATUSTIP
[1babbd6ba3]1489}
1490
1491bool MainWindow::saveTask() {
1492QStringList filters(tr("%1 Task File").arg("TSPSG") + " (*.tspt)");
1493        filters.append(tr("All Files") + " (*)");
1494QString file;
[ac76a6a753]1495        if ((fileName == tr("Untitled") + ".tspt") && settings->value("SaveLastUsed", DEF_SAVE_LAST_USED).toBool()) {
[bbac1ebb13]1496                file = settings->value(OS"/LastUsed/TaskSavePath").toString();
[ac76a6a753]1497                if (!file.isEmpty())
1498                        file.append("/");
1499                file.append(fileName);
1500        } else if (fileName.endsWith(".tspt", Qt::CaseInsensitive))
[1babbd6ba3]1501                file = fileName;
1502        else
[ac76a6a753]1503                file = QFileInfo(fileName).path() + "/" + QFileInfo(fileName).completeBaseName() + ".tspt";
[1babbd6ba3]1504
1505QFileDialog::Options opts = settings->value("UseNativeDialogs", DEF_USE_NATIVE_DIALOGS).toBool() ? QFileDialog::Options() : QFileDialog::DontUseNativeDialog;
1506        file = QFileDialog::getSaveFileName(this, tr("Task Save"), file, filters.join(";;"), NULL, opts);
1507        if (file.isEmpty())
1508                return false;
[ac76a6a753]1509        else if (settings->value("SaveLastUsed", DEF_SAVE_LAST_USED).toBool())
[bbac1ebb13]1510                settings->setValue(OS"/LastUsed/TaskSavePath", QFileInfo(file).path());
[ac76a6a753]1511
[1babbd6ba3]1512        if (tspmodel->saveTask(file)) {
1513                setFileName(file);
1514                setWindowModified(false);
1515                return true;
1516        }
1517        return false;
1518}
1519
1520void MainWindow::setFileName(const QString &fileName)
1521{
1522        this->fileName = fileName;
[88a59e4d65]1523        setWindowTitle(QString("%1[*] - %2").arg(QFileInfo(fileName).completeBaseName()).arg(QCoreApplication::applicationName()));
[1babbd6ba3]1524}
1525
1526void MainWindow::setupUi()
1527{
[a713b103e8]1528        Ui_MainWindow::setupUi(this);
[1babbd6ba3]1529
[3cadf24d00]1530        // File Menu
[2a436ea693]1531        actionFileNew->setIcon(GET_ICON("document-new"));
1532        actionFileOpen->setIcon(GET_ICON("document-open"));
1533        actionFileSave->setIcon(GET_ICON("document-save"));
[a713b103e8]1534#ifndef HANDHELD
[2a436ea693]1535        menuFileSaveAs->setIcon(GET_ICON("document-save-as"));
[a713b103e8]1536#endif
[2a436ea693]1537        actionFileExit->setIcon(GET_ICON("application-exit"));
[3cadf24d00]1538        // Settings Menu
[a713b103e8]1539#ifndef HANDHELD
[2a436ea693]1540        menuSettingsLanguage->setIcon(GET_ICON("preferences-desktop-locale"));
[a713b103e8]1541#if QT_VERSION >= 0x040600
1542        actionSettingsLanguageEnglish->setIcon(QIcon::fromTheme("flag-gb", QIcon(":/images/icons/l10n/flag-gb.png")));
1543#else // QT_VERSION >= 0x040600
1544        actionSettingsLanguageEnglish->setIcon(QIcon(":/images/icons/l10n/flag-gb.png"));
1545#endif // QT_VERSION >= 0x040600
[2a436ea693]1546        menuSettingsStyle->setIcon(GET_ICON("preferences-desktop-theme"));
[a713b103e8]1547#endif // HANDHELD
[2a436ea693]1548        actionSettingsPreferences->setIcon(GET_ICON("preferences-system"));
[3cadf24d00]1549        // Help Menu
[a713b103e8]1550#ifndef HANDHELD
[2a436ea693]1551        actionHelpContents->setIcon(GET_ICON("help-contents"));
1552        actionHelpContextual->setIcon(GET_ICON("help-contextual"));
[88a59e4d65]1553        actionHelpOnlineSupport->setIcon(GET_ICON("applications-internet"));
1554        actionHelpReportBug->setIcon(GET_ICON("tools-report-bug"));
[2a436ea693]1555        actionHelpAbout->setIcon(GET_ICON("help-about"));
[131c5fc3ba]1556        actionHelpAboutQt->setIcon(QIcon(":/images/icons/"ICON_SIZE"/qtlogo."ICON_FORMAT));
[a713b103e8]1557#endif
[3cadf24d00]1558        // Buttons
[2a436ea693]1559        buttonRandom->setIcon(GET_ICON("roll"));
1560        buttonSolve->setIcon(GET_ICON("dialog-ok"));
1561        buttonSaveSolution->setIcon(GET_ICON("document-save-as"));
1562        buttonBackToTask->setIcon(GET_ICON("go-previous"));
[3cadf24d00]1563
[2a436ea693]1564//      action->setIcon(GET_ICON(""));
[3cadf24d00]1565
[1babbd6ba3]1566#if QT_VERSION >= 0x040600
1567        setToolButtonStyle(Qt::ToolButtonFollowStyle);
1568#endif
1569
1570#ifndef HANDHELD
1571QStatusBar *statusbar = new QStatusBar(this);
1572        statusbar->setObjectName("statusbar");
1573        setStatusBar(statusbar);
1574#endif // HANDHELD
1575
[97e90f9be6]1576#ifdef Q_WS_WINCE_WM
[1babbd6ba3]1577        menuBar()->setDefaultAction(menuFile->menuAction());
1578
1579QScrollArea *scrollArea = new QScrollArea(this);
1580        scrollArea->setFrameShape(QFrame::NoFrame);
1581        scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
1582        scrollArea->setWidgetResizable(true);
1583        scrollArea->setWidget(tabWidget);
1584        setCentralWidget(scrollArea);
1585#else
1586        setCentralWidget(tabWidget);
[97e90f9be6]1587#endif // Q_WS_WINCE_WM
[1babbd6ba3]1588
1589        //! \hack HACK: A little hack for toolbar icons to have a sane size.
[97e90f9be6]1590#if defined(HANDHELD) && !defined(Q_WS_MAEMO_5)
[7bb19df196]1591        toolBarMain->setIconSize(QSize(logicalDpiX() / 4, logicalDpiY() / 4));
[e51c78af27]1592#endif // HANDHELD
[7bb19df196]1593QToolButton *tb = static_cast<QToolButton *>(toolBarMain->widgetForAction(actionFileSave));
1594        if (tb != NULL)  {
1595                tb->setMenu(menuFileSaveAs);
1596                tb->setPopupMode(QToolButton::MenuButtonPopup);
1597        }
[1babbd6ba3]1598
[8b0661d1ee]1599//      solutionText->document()->setDefaultFont(settings->value("Output/Font", QFont(DEF_FONT_FAMILY, DEF_FONT_SIZE)).value<QFont>());
[1babbd6ba3]1600        solutionText->setWordWrapMode(QTextOption::WordWrap);
1601
1602#ifndef QT_NO_PRINTER
1603        actionFilePrintPreview = new QAction(this);
1604        actionFilePrintPreview->setObjectName("actionFilePrintPreview");
1605        actionFilePrintPreview->setEnabled(false);
[2a436ea693]1606        actionFilePrintPreview->setIcon(GET_ICON("document-print-preview"));
[1babbd6ba3]1607
1608        actionFilePrint = new QAction(this);
1609        actionFilePrint->setObjectName("actionFilePrint");
1610        actionFilePrint->setEnabled(false);
[2a436ea693]1611        actionFilePrint->setIcon(GET_ICON("document-print"));
[1babbd6ba3]1612
1613        menuFile->insertAction(actionFileExit,actionFilePrintPreview);
1614        menuFile->insertAction(actionFileExit,actionFilePrint);
1615        menuFile->insertSeparator(actionFileExit);
1616
[7bb19df196]1617        toolBarMain->insertAction(actionSettingsPreferences, actionFilePrint);
[1babbd6ba3]1618#endif // QT_NO_PRINTER
[e51c78af27]1619
[e3533af1cf]1620        groupSettingsLanguageList = new QActionGroup(this);
[97e90f9be6]1621#ifdef Q_WS_MAEMO_5
1622        groupSettingsLanguageList->addAction(actionSettingsLanguageAutodetect);
1623#endif
[e3533af1cf]1624        actionSettingsLanguageEnglish->setData("en");
1625        actionSettingsLanguageEnglish->setActionGroup(groupSettingsLanguageList);
1626        loadLangList();
1627        actionSettingsLanguageAutodetect->setChecked(settings->value("Language", "").toString().isEmpty());
1628
1629        actionSettingsStyleSystem->setData(true);
1630        groupSettingsStyleList = new QActionGroup(this);
[97e90f9be6]1631#ifdef Q_WS_MAEMO_5
1632        groupSettingsStyleList->addAction(actionSettingsStyleSystem);
1633#endif
[e3533af1cf]1634
[7bb19df196]1635#ifndef HANDHELD
1636        actionSettingsToolbarsConfigure = new QAction(this);
[2a436ea693]1637        actionSettingsToolbarsConfigure->setIcon(GET_ICON("configure-toolbars"));
[7bb19df196]1638#endif // HANDHELD
1639
[f5c945d7ac]1640        if (hasUpdater()) {
1641                actionHelpCheck4Updates = new QAction(this);
1642                actionHelpCheck4Updates->setIcon(GET_ICON("system-software-update"));
1643                actionHelpCheck4Updates->setEnabled(hasUpdater());
1644                menuHelp->insertAction(actionHelpAboutQt, actionHelpCheck4Updates);
1645                menuHelp->insertSeparator(actionHelpAboutQt);
1646        } else
1647                actionHelpCheck4Updates = NULL;
[1babbd6ba3]1648
1649        spinCities->setMaximum(MAX_NUM_CITIES);
1650
[94cd045fad]1651#ifndef HANDHELD
1652        toolBarManager = new QtToolBarManager;
1653        toolBarManager->setMainWindow(this);
[7bb19df196]1654QString cat = toolBarMain->windowTitle();
1655        toolBarManager->addToolBar(toolBarMain, cat);
[94cd045fad]1656#ifndef QT_NO_PRINTER
1657        toolBarManager->addAction(actionFilePrintPreview, cat);
1658#endif // QT_NO_PRINTER
1659        toolBarManager->addAction(actionHelpContents, cat);
1660        toolBarManager->addAction(actionHelpContextual, cat);
1661//      toolBarManager->addAction(action, cat);
[7bb19df196]1662        toolBarManager->restoreState(settings->value("MainWindow/Toolbars").toByteArray());
[a713b103e8]1663#else
1664        toolBarMain->setVisible(settings->value("MainWindow/ToolbarVisible", true).toBool());
[94cd045fad]1665#endif // HANDHELD
[7bb19df196]1666
1667        retranslateUi(false);
1668
[97e90f9be6]1669#ifdef Q_WS_WIN32
[7bb19df196]1670        // Adding some eyecandy in Vista and 7 :-)
1671        if (QtWin::isCompositionEnabled() && settings->value("UseTranslucency", DEF_USE_TRANSLUCENCY).toBool())  {
1672                toggleTranclucency(true);
1673        }
[97e90f9be6]1674#endif // Q_WS_WIN32
[1babbd6ba3]1675}
1676
1677void MainWindow::toggleSolutionActions(bool enable)
1678{
1679        buttonSaveSolution->setEnabled(enable);
1680        actionFileSaveAsSolution->setEnabled(enable);
1681        solutionText->setEnabled(enable);
1682#ifndef QT_NO_PRINTER
1683        actionFilePrint->setEnabled(enable);
1684        actionFilePrintPreview->setEnabled(enable);
1685#endif // QT_NO_PRINTER
1686}
1687
1688void MainWindow::toggleTranclucency(bool enable)
1689{
[97e90f9be6]1690#ifdef Q_WS_WIN32
[1babbd6ba3]1691        toggleStyle(labelVariant, enable);
1692        toggleStyle(labelCities, enable);
1693        toggleStyle(statusBar(), enable);
1694        tabWidget->setDocumentMode(enable);
1695        QtWin::enableBlurBehindWindow(this, enable);
1696#else
1697        Q_UNUSED(enable);
[97e90f9be6]1698#endif // Q_WS_WIN32
[1babbd6ba3]1699}
[88a59e4d65]1700
1701void MainWindow::actionHelpOnlineSupportTriggered()
1702{
1703        QDesktopServices::openUrl(QUrl("http://tspsg.info/goto/support"));
1704}
1705
1706void MainWindow::actionHelpReportBugTriggered()
1707{
1708        QDesktopServices::openUrl(QUrl("http://tspsg.info/goto/bugtracker"));
1709}
Note: See TracBrowser for help on using the repository browser.