source: tspsg/src/mainwindow.cpp @ 97e90f9be6

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

+ Added support for Simulator from Nokia Qt SDK

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