source: tspsg/src/mainwindow.cpp @ 8f2427aaf0

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