source: tspsg/src/mainwindow.cpp @ a7998257bc

appveyorimgbot
Last change on this file since a7998257bc was a7998257bc, checked in by paulcdejean <paulcdejean@…>, 9 years ago

Changes I had to make to get this to build on windows.

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