source: tspsg/src/mainwindow.cpp @ 47c811cc09

appveyorimgbotreadme
Last change on this file since 47c811cc09 was 47c811cc09, checked in by Oleksii Serdiuk, 12 years ago

Added a way to change maximum number of cities without recompiling.

Added Tweaks/MaxNumCitites? setting to tspsg.ini. The maximum number of
cities limit can be controlled by setting it.

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