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

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