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
Line 
1/*
2 *  TSPSG: TSP Solver and Generator
3 *  Copyright (C) 2007-2012 Oleksii Serdiuk <contacts[at]oleksii[dot]name>
4 *
5 *  $Id: $Format:%h %ai %an$ $
6 *  $URL: http://tspsg.info/ $
7 *
8 *  This file is part of TSPSG.
9 *
10 *  TSPSG is free software: you can redistribute it and/or modify
11 *  it under the terms of the GNU General Public License as published by
12 *  the Free Software Foundation, either version 3 of the License, or
13 *  (at your option) any later version.
14 *
15 *  TSPSG is distributed in the hope that it will be useful,
16 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
17 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 *  GNU General Public License for more details.
19 *
20 *  You should have received a copy of the GNU General Public License
21 *  along with TSPSG.  If not, see <http://www.gnu.org/licenses/>.
22 */
23
24#include "mainwindow.h"
25#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
81
82#ifdef Q_OS_WIN32
83#   include "shobjidl.h"
84#endif
85
86#ifdef _T_T_L_
87#include "_.h"
88_C_ _R_ _Y_ _P_ _T_
89#endif
90
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
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)
128    : QMainWindow(parent)
129{
130    settings = initSettings(this);
131
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
137    if (settings->contains("Style")) {
138QStyle *s = QStyleFactory::create(settings->value("Style").toString());
139        if (s != NULL)
140            QApplication::setStyle(s);
141        else
142            settings->remove("Style");
143    }
144
145    loadLanguage();
146    setupUi();
147    setAcceptDrops(true);
148
149    initDocStyleSheet();
150
151#ifndef QT_NO_PRINTER
152    printer = new QPrinter(QPrinter::HighResolution);
153    settings->beginGroup("Printer");
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
162    printer->setOrientation(qvariant_cast<QPrinter::Orientation>(settings->value("PageOrientation", DEF_PAGE_ORIENTATION)));
163    printer->setPageMargins(
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(),
168        QPrinter::Millimeter);
169    settings->endGroup();
170#endif // QT_NO_PRINTER
171
172#ifdef Q_OS_WINCE_WM
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)));
176#endif // Q_OS_WINCE_WM
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()));
182#ifndef QT_NO_PRINTER
183    connect(actionFilePrintPreview, SIGNAL(triggered()), SLOT(actionFilePrintPreviewTriggered()));
184    connect(actionFilePageSetup, SIGNAL(triggered()), SLOT(actionFilePageSetupTriggered()));
185    connect(actionFilePrint, SIGNAL(triggered()), SLOT(actionFilePrintTriggered()));
186#endif // QT_NO_PRINTER
187#ifndef HANDHELD
188    connect(actionSettingsToolbarsConfigure, SIGNAL(triggered()), SLOT(actionSettingsToolbarsConfigureTriggered()));
189#endif // HANDHELD
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)));
206
207#ifndef HANDHELD
208    // Centering main window
209QRect rect = geometry();
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    }
219#endif // HANDHELD
220
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    }
251}
252
253MainWindow::~MainWindow()
254{
255#ifndef QT_NO_PRINTER
256    delete printer;
257#endif
258}
259
260/* Privates **********************************************************/
261
262void MainWindow::actionFileNewTriggered()
263{
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();
272    graph = QPicture();
273    toggleSolutionActions(false);
274    QApplication::restoreOverrideCursor();
275}
276
277void MainWindow::actionFileOpenTriggered()
278{
279    if (!maybeSave())
280        return;
281
282QStringList filters(tr("All Supported Formats") + " (*.tspt *.zkt)");
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") + " (*)");
286
287QString file;
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();
292QFileDialog::Options opts = settings->value("UseNativeDialogs", DEF_USE_NATIVE_DIALOGS).toBool() ? QFileDialog::Options() : QFileDialog::DontUseNativeDialog;
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);
306}
307
308bool MainWindow::actionFileSaveTriggered()
309{
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;
318}
319
320void MainWindow::actionFileSaveAsTaskTriggered()
321{
322    saveTask();
323}
324
325void MainWindow::actionFileSaveAsSolutionTriggered()
326{
327static QString selectedFile;
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") {
337#ifndef QT_NO_PRINTER
338        selectedFile += "solution.pdf";
339#else
340        selectedFile += "solution.html";
341#endif // QT_NO_PRINTER
342    } else {
343#ifndef QT_NO_PRINTER
344        selectedFile += QFileInfo(fileName).completeBaseName() + ".pdf";
345#else
346        selectedFile += QFileInfo(fileName).completeBaseName() + ".html";
347#endif // QT_NO_PRINTER
348    }
349
350QStringList filters;
351#ifndef QT_NO_PRINTER
352    filters.append(tr("PDF Files") + " (*.pdf)");
353#endif
354    filters.append(tr("HTML Files") + " (*.html *.htm)");
355    filters.append(tr("Web Archive Files") + " (*.mht *.mhtml)");
356    filters.append(tr("OpenDocument Files") + " (*.odt)");
357    filters.append(tr("All Files") + " (*)");
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);
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));
367#ifndef QT_NO_PRINTER
368    if (selectedFile.endsWith(".pdf", Qt::CaseInsensitive)) {
369        printer->setOutputFileName(selectedFile);
370        solutionText->document()->print(printer);
371        printer->setOutputFileName(QString());
372        QApplication::restoreOverrideCursor();
373        return;
374    }
375#endif
376    QByteArray imgdata;
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))) {
380        QFile file(selectedFile);
381        if (!file.open(QFile::WriteOnly | QFile::Text)) {
382            QApplication::restoreOverrideCursor();
383            QMessageBox::critical(this, tr("Solution Save"), tr("Unable to save the solution.\nError: %1").arg(file.errorString()));
384            return;
385        }
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();
398#if !defined(NOSVG)
399        if (!QImageWriter::supportedImageFormats().contains(format.toLatin1()) && (format != "svg")) {
400#else // NOSVG
401        if (!QImageWriter::supportedImageFormats().contains(format.toLatin1())) {
402#endif // NOSVG
403            format = DEF_GRAPH_IMAGE_FORMAT;
404            settings->remove("Output/GraphImageFormat");
405        }
406
407        if (!graph.isNull()) {
408            imgdata = generateImage(format);
409            if (imgdata.isEmpty()) {
410                return;
411            }
412            if (embed) {
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")));
423            }
424        }
425
426        // Saving solution text as HTML
427QTextStream ts(&file);
428        ts.setCodec(QTextCodec::codecForName("UTF-8"));
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        }
444        ts << html << endl;
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        }
458        file.close();
459        if (!embed && !mhtml) {
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        }
472    } else {
473QTextDocumentWriter dw(selectedFile);
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();
480}
481
482#ifndef QT_NO_PRINTER
483void MainWindow::actionFilePrintPreviewTriggered()
484{
485QPrintPreviewDialog ppd(printer, this);
486    connect(&ppd,SIGNAL(paintRequested(QPrinter *)),SLOT(printPreview(QPrinter *)));
487    ppd.exec();
488
489qreal l, t, r, b;
490    printer->getPageMargins(&l, &t, &r, &b, QPrinter::Millimeter);
491
492    settings->beginGroup("Printer");
493    settings->setValue("PaperSize", printer->paperSize());
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    }
523    settings->setValue("PageOrientation", printer->orientation());
524    settings->setValue("MarginLeft", l);
525    settings->setValue("MarginTop", t);
526    settings->setValue("MarginRight", r);
527    settings->setValue("MarginBottom", b);
528    settings->endGroup();
529}
530
531void MainWindow::actionFilePrintTriggered()
532{
533QPrintDialog pd(printer,this);
534    if (pd.exec() != QDialog::Accepted)
535        return;
536    QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
537    solutionText->print(printer);
538    QApplication::restoreOverrideCursor();
539}
540#endif // QT_NO_PRINTER
541
542void MainWindow::actionSettingsPreferencesTriggered()
543{
544SettingsDialog sd(this);
545#ifdef Q_OS_SYMBIAN
546    sd.setWindowState(Qt::WindowMaximized);
547#endif
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);
557}
558
559void MainWindow::actionSettingsLanguageAutodetectTriggered(bool checked)
560{
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());
566}
567
568void MainWindow::groupSettingsLanguageListTriggered(QAction *action)
569{
570#ifndef Q_WS_MAEMO_5
571    if (actionSettingsLanguageAutodetect->isChecked())
572        actionSettingsLanguageAutodetect->trigger();
573#endif
574bool untitled = (fileName == tr("Untitled") + ".tspt");
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();
581#ifndef HANDHELD
582        if (QtWin::isCompositionEnabled() && settings->value("UseTranslucency", DEF_USE_TRANSLUCENCY).toBool())  {
583            toggleStyle(labelVariant, true);
584            toggleStyle(labelCities, true);
585        }
586#endif
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    }
591}
592
593void MainWindow::actionSettingsStyleSystemTriggered(bool checked)
594{
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    }
601}
602
603void MainWindow::groupSettingsStyleListTriggered(QAction *action)
604{
605QStyle *s = QStyleFactory::create(action->text());
606    if (s != NULL) {
607        QApplication::setStyle(s);
608        settings->setValue("Style", action->text());
609        actionSettingsStyleSystem->setChecked(false);
610    }
611}
612
613#ifndef HANDHELD
614void MainWindow::actionSettingsToolbarsConfigureTriggered()
615{
616QtToolBarDialog dlg(this);
617    dlg.setToolBarManager(toolBarManager);
618    dlg.exec();
619QToolButton *tb = static_cast<QToolButton *>(toolBarMain->widgetForAction(actionFileSave));
620    if (tb != NULL) {
621        tb->setMenu(menuFileSaveAs);
622        tb->setPopupMode(QToolButton::MenuButtonPopup);
623        tb->resize(tb->sizeHint());
624    }
625
626    loadToolbarList();
627}
628#endif // HANDHELD
629
630void MainWindow::actionHelpCheck4UpdatesTriggered()
631{
632    if (!hasUpdater()) {
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."));
634        return;
635    }
636
637    check4Updates();
638}
639
640void MainWindow::actionHelpAboutTriggered()
641{
642    QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
643
644QString title;
645    title += QString("<b>%1</b><br>").arg(QCoreApplication::applicationName());
646    title += QString("%1: <b>%2</b><br>").arg(tr("Version"), QCoreApplication::applicationVersion());
647#ifndef HANDHELD
648    title += QString("<b>&copy; 2007-%1 <a href=\"http://%2/\">%3</a></b><br>").arg(QDate::currentDate().toString("yyyy"), QCoreApplication::organizationDomain(), QCoreApplication::organizationName());
649#endif // HANDHELD
650    title += QString("<b><a href=\"http://tspsg.info/\">http://tspsg.info/</a></b>");
651
652QString about;
653    about += QString("%1: <b>%2</b><br>").arg(tr("Target OS (ARCH)"), PLATFROM);
654    about += QString("%1:<br>").arg(tr("Qt library"));
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());
657    about.append(QString("%1: <b>%2x%3</b><br>").arg(tr("Logical screen DPI")).arg(logicalDpiX()).arg(logicalDpiY()));
658QString tag;
659#ifdef REVISION_STR
660    tag = tr(" from git commit <b>%1</b>").arg(QString(REVISION_STR).left(10));
661#endif
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>";
663    about += QString("%1: <b>%2</b><br>").arg(tr("Algorithm"), TSPSolver::CTSPSolver::getVersionId());
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>.");
677
678QString credits;
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");
695
696QFile f(":/files/COPYING");
697    f.open(QIODevice::ReadOnly);
698
699QString translation = QCoreApplication::translate("--------", "AUTHORS %1", "Please, provide translator credits here. %1 will be replaced with VERSION");
700    if ((translation != "AUTHORS %1") && (translation.contains("%1"))) {
701QString about = QCoreApplication::translate("--------", "VERSION", "Please, provide your translation version here.");
702        if (about != "VERSION")
703            translation = translation.arg(about);
704    }
705
706QDialog *dlg = new QDialog(this);
707QLabel *lblIcon = new QLabel(dlg),
708    *lblTitle = new QLabel(dlg);
709#ifdef HANDHELD
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);
711#endif // HANDHELD
712QTabWidget *tabs = new QTabWidget(dlg);
713QTextBrowser *txtAbout = new QTextBrowser(dlg);
714QTextBrowser *txtLicense = new QTextBrowser(dlg);
715QTextBrowser *txtCredits = new QTextBrowser(dlg);
716QVBoxLayout *vb = new QVBoxLayout();
717QHBoxLayout *hb1 = new QHBoxLayout(),
718    *hb2 = new QHBoxLayout();
719QDialogButtonBox *bb = new QDialogButtonBox(QDialogButtonBox::Ok, Qt::Horizontal, dlg);
720
721    lblTitle->setOpenExternalLinks(true);
722    lblTitle->setText(title);
723    lblTitle->setAlignment(Qt::AlignTop);
724    lblTitle->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
725#ifndef HANDHELD
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()));
727#endif // HANDHELD
728
729    lblIcon->setPixmap(QPixmap(":/images/tspsg.png").scaledToHeight(lblTitle->sizeHint().height(), Qt::SmoothTransformation));
730    lblIcon->setAlignment(Qt::AlignVCenter);
731#ifndef HANDHELD
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()));
733#endif // HANDHELD
734
735    hb1->addWidget(lblIcon);
736    hb1->addWidget(lblTitle);
737
738    txtAbout->setWordWrapMode(QTextOption::NoWrap);
739    txtAbout->setOpenExternalLinks(true);
740    txtAbout->setHtml(about);
741    txtAbout->moveCursor(QTextCursor::Start);
742    txtAbout->setFrameShape(QFrame::NoFrame);
743
744//      txtCredits->setWordWrapMode(QTextOption::NoWrap);
745    txtCredits->setOpenExternalLinks(true);
746    txtCredits->setHtml(credits);
747    txtCredits->moveCursor(QTextCursor::Start);
748    txtCredits->setFrameShape(QFrame::NoFrame);
749
750    txtLicense->setWordWrapMode(QTextOption::NoWrap);
751    txtLicense->setOpenExternalLinks(true);
752    txtLicense->setText(f.readAll());
753    txtLicense->moveCursor(QTextCursor::Start);
754    txtLicense->setFrameShape(QFrame::NoFrame);
755
756    bb->button(QDialogButtonBox::Ok)->setCursor(QCursor(Qt::PointingHandCursor));
757    bb->button(QDialogButtonBox::Ok)->setIcon(GET_ICON("dialog-ok"));
758
759    hb2->addWidget(bb);
760
761#ifdef Q_OS_WINCE_WM
762    vb->setMargin(3);
763#endif // Q_OS_WINCE_WM
764    vb->addLayout(hb1);
765#ifdef HANDHELD
766    vb->addWidget(lblSubTitle);
767#endif // HANDHELD
768
769    tabs->addTab(txtAbout, tr("About"));
770    tabs->addTab(txtLicense, tr("License"));
771    tabs->addTab(txtCredits, tr("Credits"));
772    if (translation != "AUTHORS %1") {
773QTextBrowser *txtTranslation = new QTextBrowser(dlg);
774//              txtTranslation->setWordWrapMode(QTextOption::NoWrap);
775        txtTranslation->setOpenExternalLinks(true);
776        txtTranslation->setText(translation);
777        txtTranslation->moveCursor(QTextCursor::Start);
778        txtTranslation->setFrameShape(QFrame::NoFrame);
779
780        tabs->addTab(txtTranslation, tr("Translation"));
781    }
782#ifndef HANDHELD
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()));
784#endif // HANDHELD
785
786    vb->addWidget(tabs);
787    vb->addLayout(hb2);
788
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"));
792
793    dlg->setLayout(vb);
794
795    connect(bb, SIGNAL(accepted()), dlg, SLOT(accept()));
796
797#ifndef HANDHELD
798    // Adding some eyecandy
799    if (QtWin::isCompositionEnabled())  {
800        QtWin::enableBlurBehindWindow(dlg, true);
801    }
802#endif // HANDHELD
803
804#ifndef HANDHELD
805    dlg->resize(450, 350);
806#elif defined(Q_OS_SYMBIAN)
807    dlg->setWindowState(Qt::WindowMaximized);
808#endif
809    QApplication::restoreOverrideCursor();
810
811    dlg->exec();
812
813    delete dlg;
814}
815
816void MainWindow::buttonBackToTaskClicked()
817{
818    tabWidget->setCurrentIndex(0);
819}
820
821void MainWindow::buttonRandomClicked()
822{
823    QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
824    tspmodel->randomize();
825    QApplication::restoreOverrideCursor();
826}
827
828void MainWindow::buttonSolveClicked()
829{
830    TSPSolver::TMatrix matrix;
831    QList<double> row;
832    int n = spinCities->value();
833    bool ok;
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    }
845
846QProgressDialog pd(this);
847QProgressBar *pb = new QProgressBar(&pd);
848    pb->setAlignment(Qt::AlignCenter);
849    pb->setFormat(tr("%v of %1 parts found").arg(n));
850    pd.setBar(pb);
851QPushButton *cancel = new QPushButton(&pd);
852    cancel->setIcon(GET_ICON("dialog-cancel"));
853    cancel->setText(QCoreApplication::translate("QDialogButtonBox", "Cancel", "No need to translate this. The translation will be taken from Qt translation files."));
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();
862
863#ifdef Q_OS_WIN32
864HRESULT hr = CoCreateInstance(CLSID_TaskbarList, NULL, CLSCTX_INPROC_SERVER, IID_ITaskbarList3, (LPVOID*)&tl);
865    if (SUCCEEDED(hr)) {
866        hr = tl->HrInit();
867        if (FAILED(hr)) {
868            tl->Release();
869            tl = NULL;
870        } else {
871            tl->SetProgressValue(HWND(winId()), 0, n * 2);
872        }
873    }
874#endif
875
876    TSPSolver::CTSPSolver solver;
877    solver.setCleanupOnCancel(false);
878    connect(&solver, SIGNAL(routePartFound(int)), &pd, SLOT(setValue(int)));
879    connect(&pd, SIGNAL(canceled()), &solver, SLOT(cancel()));
880#ifdef Q_OS_WIN32
881    if (tl != NULL)
882        connect(&solver, SIGNAL(routePartFound(int)), SLOT(solverRoutePartFound(int)));
883#endif
884    TSPSolver::SStep *root = solver.solve(n, matrix);
885#ifdef Q_OS_WIN32
886    if (tl != NULL)
887        disconnect(&solver, SIGNAL(routePartFound(int)), this, SLOT(solverRoutePartFound(int)));
888#endif
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()) {
894#ifdef Q_OS_WIN32
895            if (tl != NULL) {
896                tl->SetProgressState(HWND(winId()), TBPF_ERROR);
897            }
898#endif
899            QApplication::alert(this);
900            QMessageBox::warning(this, tr("Solution Result"), tr("Unable to find a solution.\nMaybe, this task has no solution."));
901        }
902        pd.setLabelText(tr("Memory cleanup..."));
903        pd.setMaximum(0);
904        pd.setCancelButton(NULL);
905        pd.show();
906#ifdef Q_OS_WIN32
907        if (tl != NULL)
908            tl->SetProgressState(HWND(winId()), TBPF_INDETERMINATE);
909#endif
910        QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
911
912#ifndef QT_NO_CONCURRENT
913        QFuture<void> f = QtConcurrent::run(&solver, &TSPSolver::CTSPSolver::cleanup, false);
914        while (!f.isFinished()) {
915            QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
916        }
917#else
918        solver.cleanup(true);
919#endif
920        pd.reset();
921#ifdef Q_OS_WIN32
922        if (tl != NULL) {
923            tl->SetProgressState(HWND(winId()), TBPF_NOPROGRESS);
924            tl->Release();
925            tl = NULL;
926        }
927#endif
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);
934
935#ifdef Q_OS_WIN32
936    if (tl != NULL)
937        tl->SetProgressValue(HWND(winId()), spinCities->value(), spinCities->value() + solver.getTotalSteps() + 1);
938#endif
939
940    solutionText->clear();
941    solutionText->setDocumentTitle(tr("Solution of Variant #%1 Task").arg(spinVariant->value()));
942
943QPainter pic;
944bool dograph = settings->value("Output/GenerateGraph", DEF_GENERATE_GRAPH).toBool();
945    if (dograph) {
946        pic.begin(&graph);
947        pic.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform);
948QFont font = qvariant_cast<QFont>(settings->value("Output/Font", QFont(DEF_FONT_FACE)));
949        font.setStyleHint(QFont::TypeWriter);
950        // Font size in pixels = graph node radius / 2.75.
951        // See MainWindow::drawNode() for graph node radius calcualtion description.
952#ifndef Q_OS_SYMBIAN
953        font.setPixelSize(logicalDpiX() * (settings->value("Output/GraphWidth", DEF_GRAPH_WIDTH).toReal() / CM_IN_INCH) / 4.5 / 2.75);
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
958        if (settings->value("Output/HQGraph", DEF_HQ_GRAPH).toBool()) {
959            font.setWeight(QFont::DemiBold);
960            font.setPixelSize(font.pixelSize() * HQ_FACTOR);
961        }
962        pic.setFont(font);
963        pic.setBrush(QBrush(QColor(Qt::white)));
964        if (settings->value("Output/HQGraph", DEF_HQ_GRAPH).toBool()) {
965QPen pen = pic.pen();
966            pen.setWidth(HQ_FACTOR);
967            pic.setPen(pen);
968        }
969        pic.setBackgroundMode(Qt::OpaqueMode);
970    } else {
971        graph = QPicture();
972    }
973
974QTextDocument *doc = solutionText->document();
975QTextCursor cur(doc);
976
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);
981    cur.insertText(tr("Task:"), fmt_default);
982    outputMatrix(cur, matrix);
983    if (dograph) {
984#ifdef _T_T_L_
985        _b_ _i_ _z_ _a_ _r_ _r_ _e_
986#endif
987        drawNode(pic, 0);
988    }
989    cur.insertHtml("<hr>");
990    cur.insertBlock(fmt_paragraph);
991    int imgpos = cur.position();
992    cur.insertText(tr("Variant #%1 Solution").arg(spinVariant->value()), fmt_default);
993    cur.endEditBlock();
994
995    TSPSolver::SStep *step = root;
996    int c = n = 1;
997    pb->setFormat(tr("Generating step %v"));
998    while ((step->next != TSPSolver::SStep::NoNextStep) && (c < spinCities->value())) {
999        if (pd.wasCanceled()) {
1000            pd.setLabelText(tr("Memory cleanup..."));
1001            pd.setMaximum(0);
1002            pd.setCancelButton(NULL);
1003            pd.show();
1004            QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
1005#ifdef Q_OS_WIN32
1006            if (tl != NULL)
1007                tl->SetProgressState(HWND(winId()), TBPF_INDETERMINATE);
1008#endif
1009#ifndef QT_NO_CONCURRENT
1010            QFuture<void> f = QtConcurrent::run(&solver, &TSPSolver::CTSPSolver::cleanup, false);
1011            while (!f.isFinished()) {
1012                QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
1013            }
1014#else
1015            solver.cleanup(true);
1016#endif
1017            solutionText->clear();
1018            toggleSolutionActions(false);
1019#ifdef Q_OS_WIN32
1020            if (tl != NULL) {
1021                tl->SetProgressState(HWND(winId()), TBPF_NOPROGRESS);
1022                tl->Release();
1023                tl = NULL;
1024            }
1025#endif
1026            return;
1027        }
1028        pd.setValue(n);
1029#ifdef Q_OS_WIN32
1030        if (tl != NULL)
1031            tl->SetProgressValue(HWND(winId()), spinCities->value() + n, spinCities->value() + solver.getTotalSteps() + 1);
1032#endif
1033
1034        cur.beginEditBlock();
1035        cur.insertBlock(fmt_paragraph);
1036        cur.insertText(tr("Step #%1").arg(n), fmt_default);
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        }
1040        if (step->alts.empty())
1041            cur.insertBlock(fmt_lastparagraph);
1042        else
1043            cur.insertBlock(fmt_paragraph);
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);
1045        if (!step->alts.empty()) {
1046            TSPSolver::SStep::SCandidate cand;
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            }
1053            cur.insertBlock(fmt_lastparagraph);
1054            cur.insertText(tr("%n alternate candidate(s) for branching: %1.", "", step->alts.count()).arg(alts), fmt_altlist);
1055        }
1056        cur.endEditBlock();
1057
1058        if (dograph) {
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
1066        if (step->next == TSPSolver::SStep::RightBranch) {
1067            c++;
1068            step = step->prNode;
1069        } else if (step->next == TSPSolver::SStep::LeftBranch) {
1070            step = step->plNode;
1071        } else
1072            break;
1073    }
1074    pb->setFormat(tr("Generating footer"));
1075    pd.setValue(n);
1076#ifdef Q_OS_WIN32
1077    if (tl != NULL)
1078        tl->SetProgressValue(HWND(winId()), spinCities->value() + n, spinCities->value() + solver.getTotalSteps() + 1);
1079#endif
1080
1081    cur.beginEditBlock();
1082    cur.insertBlock(fmt_paragraph);
1083    if (solver.isOptimal())
1084        cur.insertText(tr("Optimal path:"), fmt_default);
1085    else
1086        cur.insertText(tr("Resulting path:"), fmt_default);
1087
1088    cur.insertBlock(fmt_paragraph);
1089    cur.insertText("  " + solver.getSortedPath(tr("City %1")));
1090
1091    if (solver.isOptimal())
1092        cur.insertBlock(fmt_paragraph);
1093    else
1094        cur.insertBlock(fmt_lastparagraph);
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
1105    if (dograph) {
1106        pic.end();
1107
1108        QImage i(graph.width() + 2, graph.height() + 2, QImage::Format_ARGB32);
1109        i.fill(QColor(255, 255, 255, 0).rgba());
1110        pic.begin(&i);
1111        pic.drawPicture(1, 1, graph);
1112        pic.end();
1113        doc->addResource(QTextDocument::ImageResource, QUrl("tspsg://graph.pic"), i);
1114
1115QTextImageFormat img;
1116        img.setName("tspsg://graph.pic");
1117        if (settings->value("Output/HQGraph", DEF_HQ_GRAPH).toBool()) {
1118            img.setWidth(i.width() / HQ_FACTOR);
1119            img.setHeight(i.height() / HQ_FACTOR);
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
1135    pd.setLabelText(tr("Memory cleanup..."));
1136    pd.setMaximum(0);
1137    pd.setCancelButton(NULL);
1138    QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
1139#ifdef Q_OS_WIN32
1140    if (tl != NULL)
1141        tl->SetProgressState(HWND(winId()), TBPF_INDETERMINATE);
1142#endif
1143#ifndef QT_NO_CONCURRENT
1144    QFuture<void> f = QtConcurrent::run(&solver, &TSPSolver::CTSPSolver::cleanup, false);
1145    while (!f.isFinished()) {
1146        QCoreApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
1147    }
1148#else
1149    solver.cleanup(true);
1150#endif
1151    toggleSolutionActions();
1152    tabWidget->setCurrentIndex(1);
1153#ifdef Q_OS_WIN32
1154    if (tl != NULL) {
1155        tl->SetProgressState(HWND(winId()), TBPF_NOPROGRESS);
1156        tl->Release();
1157        tl = NULL;
1158    }
1159#endif
1160
1161    pd.reset();
1162    QApplication::alert(this, 3000);
1163}
1164
1165void MainWindow::dataChanged()
1166{
1167    setWindowModified(true);
1168}
1169
1170void MainWindow::dataChanged(const QModelIndex &tl, const QModelIndex &br)
1171{
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    }
1179}
1180
1181#ifdef Q_OS_WINCE_WM
1182void MainWindow::changeEvent(QEvent *ev)
1183{
1184    if ((ev->type() == QEvent::ActivationChange) && isActiveWindow())
1185        desktopResized(0);
1186
1187    QWidget::changeEvent(ev);
1188}
1189
1190void MainWindow::desktopResized(int screen)
1191{
1192    if ((screen != 0) || !isActiveWindow())
1193        return;
1194
1195QRect availableGeometry = QApplication::desktop()->availableGeometry(0);
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    }
1213}
1214#endif // Q_OS_WINCE_WM
1215
1216void MainWindow::numCitiesChanged(int nCities)
1217{
1218    blockSignals(true);
1219    spinCities->setValue(nCities);
1220    blockSignals(false);
1221}
1222
1223#ifndef QT_NO_PRINTER
1224void MainWindow::printPreview(QPrinter *printer)
1225{
1226    solutionText->print(printer);
1227}
1228#endif // QT_NO_PRINTER
1229
1230#ifdef Q_OS_WIN32
1231void MainWindow::solverRoutePartFound(int n)
1232{
1233    tl->SetProgressValue(HWND(winId()), n, spinCities->value() * 2);
1234}
1235#endif // Q_OS_WIN32
1236
1237void MainWindow::spinCitiesValueChanged(int n)
1238{
1239    QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
1240int count = tspmodel->numCities();
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();
1248}
1249
1250void MainWindow::check4Updates(bool silent)
1251{
1252#ifdef Q_OS_WIN32
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    }
1260#else
1261    Q_UNUSED(silent)
1262#endif
1263    settings->setValue("Check4Updates/LastAttempt", QDate::currentDate().toString(Qt::ISODate));
1264}
1265
1266void MainWindow::closeEvent(QCloseEvent *ev)
1267{
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
1276#ifndef HANDHELD
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        }
1284#else
1285        settings->setValue("MainWindow/ToolbarVisible", toolBarMain->isVisible());
1286#endif // HANDHELD
1287    } else {
1288        settings->remove("SettingsReset");
1289    }
1290
1291    QMainWindow::closeEvent(ev);
1292}
1293
1294void MainWindow::dragEnterEvent(QDragEnterEvent *ev)
1295{
1296    if (ev->mimeData()->hasUrls() && (ev->mimeData()->urls().count() == 1)) {
1297QFileInfo fi(ev->mimeData()->urls().first().toLocalFile());
1298        if ((fi.suffix() == "tspt") || (fi.suffix() == "zkt"))
1299            ev->acceptProposedAction();
1300    }
1301}
1302
1303void MainWindow::drawNode(QPainter &pic, int nstep, bool left, TSPSolver::SStep *step)
1304{
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;
1311    if (settings->value("Output/HQGraph", DEF_HQ_GRAPH).toBool())
1312        r *= HQ_FACTOR;
1313#ifdef Q_OS_SYMBIAN
1314    /*! \hack HACK: Solution graph on Symbian is visually larger than on
1315     *   Windows Mobile. This coefficient makes it about the same size.
1316     */
1317    r /= 1.3;
1318#endif
1319
1320qreal x, y;
1321    if (step != NULL)
1322        x = left ? r : r * 3.5;
1323    else
1324        x = r * 2.25;
1325    y = r * (3 * nstep + 1);
1326
1327#ifdef _T_T_L_
1328    if (nstep == -481124) {
1329        _t_t_l_(pic, r, x);
1330        return;
1331    }
1332#endif
1333
1334    pic.drawEllipse(QPointF(x, y), r, r);
1335
1336    if (step != NULL) {
1337QFont font;
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) {
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()));
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) {
1360        pic.drawLine(QPointF(x, y - r), QPointF((step->pNode->pNode->next == TSPSolver::SStep::RightBranch) ? r * 3.5 : r, y - 2 * r));
1361    }
1362
1363}
1364
1365void MainWindow::dropEvent(QDropEvent *ev)
1366{
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    }
1377}
1378
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);
1409        pic.setFormat(format.toLatin1());
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
1429void MainWindow::initDocStyleSheet()
1430{
1431    solutionText->document()->setDefaultFont(qvariant_cast<QFont>(settings->value("Output/Font", QFont(DEF_FONT_FACE, DEF_FONT_SIZE))));
1432
1433    fmt_paragraph.setTopMargin(5);
1434    fmt_paragraph.setRightMargin(10);
1435    fmt_paragraph.setBottomMargin(0);
1436    fmt_paragraph.setLeftMargin(10);
1437
1438    fmt_lastparagraph.setTopMargin(5);
1439    fmt_lastparagraph.setRightMargin(10);
1440    fmt_lastparagraph.setBottomMargin(15);
1441    fmt_lastparagraph.setLeftMargin(10);
1442
1443    settings->beginGroup("Output/Colors");
1444
1445    fmt_table.setTopMargin(5);
1446    fmt_table.setRightMargin(10);
1447    fmt_table.setBottomMargin(0);
1448    fmt_table.setLeftMargin(10);
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);
1454
1455    fmt_cell.setAlignment(Qt::AlignHCenter);
1456
1457QColor color = QColor(settings->value("Text", DEF_TEXT_COLOR).toString());
1458QColor hilight;
1459    if (color.value() < 192)
1460        hilight.setHsv(color.hue(), color.saturation(), 127 + (color.value() / 2));
1461    else
1462        hilight.setHsv(color.hue(), color.saturation(), color.value() / 2);
1463
1464#ifdef Q_OS_SYMBIAN
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
1471    solutionText->document()->setDefaultStyleSheet(QString("* {color: %1;}").arg(color.name()));
1472    fmt_default.setForeground(QBrush(color));
1473#ifdef Q_OS_SYMBIAN
1474    }
1475#endif
1476
1477    fmt_selected.setForeground(QBrush(QColor(settings->value("Selected", DEF_SELECTED_COLOR).toString())));
1478    fmt_selected.setFontWeight(QFont::Bold);
1479
1480    fmt_alternate.setForeground(QBrush(QColor(settings->value("Alternate", DEF_ALTERNATE_COLOR).toString())));
1481    fmt_alternate.setFontWeight(QFont::Bold);
1482    fmt_altlist.setForeground(QBrush(hilight));
1483
1484    settings->endGroup();
1485}
1486
1487void MainWindow::loadLangList()
1488{
1489QMap<QString, QStringList> langlist;
1490QFileInfoList langs;
1491QFileInfo lang;
1492QStringList language, dirs;
1493QTranslator t;
1494QDir dir;
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    }
1519
1520QAction *a;
1521    foreach (language, langlist) {
1522        a = menuSettingsLanguage->addAction(language.at(2));
1523#ifndef QT_NO_STATUSTIP
1524        a->setStatusTip(language.at(3));
1525#endif
1526#if QT_VERSION >= QT_VERSION_CHECK(4,6,0)
1527        a->setIcon(QIcon::fromTheme(QString("flag-%1").arg(language.at(1)), QIcon(QString(":/images/icons/l10n/flag-%1.png").arg(language.at(1)))));
1528#else
1529        a->setIcon(QIcon(QString(":/images/icons/l10n/flag-%1.png").arg(language.at(1))));
1530#endif
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    }
1537}
1538
1539bool MainWindow::loadLanguage(const QString &lang)
1540{
1541// i18n
1542bool ad = false;
1543QString lng = lang;
1544    if (lng.isEmpty()) {
1545        ad = settings->value("Language").toString().isEmpty();
1546        lng = settings->value("Language", QLocale::system().name()).toString();
1547    }
1548static QTranslator *qtTranslator; // Qt library translator
1549    if (qtTranslator) {
1550        qApp->removeTranslator(qtTranslator);
1551        delete qtTranslator;
1552        qtTranslator = NULL;
1553    }
1554static QTranslator *translator; // Application translator
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);
1566    if (qtTranslator->load("qt_" + lng, QLibraryInfo::location(QLibraryInfo::TranslationsPath))) {
1567        qApp->installTranslator(qtTranslator);
1568    } else {
1569        // Qt library translation unavailable for this language.
1570        delete qtTranslator;
1571        qtTranslator = NULL;
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;
1594}
1595
1596void MainWindow::loadStyleList()
1597{
1598    menuSettingsStyle->clear();
1599QStringList styles = QStyleFactory::keys();
1600    menuSettingsStyle->insertAction(NULL, actionSettingsStyleSystem);
1601    actionSettingsStyleSystem->setChecked(!settings->contains("Style"));
1602    menuSettingsStyle->addSeparator();
1603QAction *a;
1604    foreach (QString style, styles) {
1605        a = menuSettingsStyle->addAction(style);
1606        a->setData(false);
1607#ifndef QT_NO_STATUSTIP
1608        a->setStatusTip(tr("Set application style to %1").arg(style));
1609#endif
1610        a->setCheckable(true);
1611        a->setActionGroup(groupSettingsStyleList);
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)
1614#ifndef Q_WS_MAEMO_5
1615            || QString(QApplication::style()->metaObject()->className()).contains(rx)
1616#endif
1617        ) {
1618            a->setChecked(true);
1619        }
1620    }
1621}
1622
1623void MainWindow::loadToolbarList()
1624{
1625    menuSettingsToolbars->clear();
1626#ifndef HANDHELD
1627    menuSettingsToolbars->insertAction(NULL, actionSettingsToolbarsConfigure);
1628    menuSettingsToolbars->addSeparator();
1629QList<QToolBar *> list = toolBarManager->toolBars();
1630    foreach (QToolBar *t, list) {
1631        menuSettingsToolbars->insertAction(NULL, t->toggleViewAction());
1632    }
1633#else // HANDHELD
1634    menuSettingsToolbars->insertAction(NULL, toolBarMain->toggleViewAction());
1635#endif // HANDHELD
1636}
1637
1638bool MainWindow::maybeSave()
1639{
1640    if (!isWindowModified())
1641        return true;
1642#ifdef Q_OS_SYMBIAN
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
1647    if (res == QMessageBox::Save)
1648        return actionFileSaveTriggered();
1649    else if (res == QMessageBox::Cancel)
1650        return false;
1651    else
1652        return true;
1653}
1654
1655void MainWindow::outputMatrix(QTextCursor &cur, const TSPSolver::TMatrix &matrix)
1656{
1657int n = spinCities->value();
1658QTextTable *table = cur.insertTable(n, n, fmt_table);
1659
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);
1673}
1674
1675void MainWindow::outputMatrix(QTextCursor &cur, const TSPSolver::SStep &step)
1676{
1677int n = spinCities->value();
1678QTextTable *table = cur.insertTable(n, n, fmt_table);
1679
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 {
1689    TSPSolver::SStep::SCandidate cand;
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);
1702}
1703
1704#ifdef Q_OS_SYMBIAN
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}
1724#endif // Q_OS_SYMBIAN
1725
1726void MainWindow::retranslateUi(bool all)
1727{
1728    if (all)
1729        Ui_MainWindow::retranslateUi(this);
1730
1731    loadStyleList();
1732    loadToolbarList();
1733
1734#ifndef QT_NO_PRINTER
1735    actionFilePrintPreview->setText(tr("P&rint Preview..."));
1736#ifndef QT_NO_TOOLTIP
1737    actionFilePrintPreview->setToolTip(tr("Preview solution results"));
1738#endif // QT_NO_TOOLTIP
1739#ifndef QT_NO_STATUSTIP
1740    actionFilePrintPreview->setStatusTip(tr("Preview current solution results before printing"));
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"));
1749#endif // QT_NO_STATUSTIP
1750
1751    actionFilePrint->setText(tr("&Print..."));
1752#ifndef QT_NO_TOOLTIP
1753    actionFilePrint->setToolTip(tr("Print solution"));
1754#endif // QT_NO_TOOLTIP
1755#ifndef QT_NO_STATUSTIP
1756    actionFilePrint->setStatusTip(tr("Print current solution results"));
1757#endif // QT_NO_STATUSTIP
1758    actionFilePrint->setShortcut(tr("Ctrl+P"));
1759#endif // QT_NO_PRINTER
1760
1761#ifndef QT_NO_STATUSTIP
1762    actionFileExit->setStatusTip(tr("Exit %1").arg(QCoreApplication::applicationName()));
1763#endif // QT_NO_STATUSTIP
1764
1765#ifndef HANDHELD
1766    actionSettingsToolbarsConfigure->setText(tr("Configure..."));
1767#ifndef QT_NO_STATUSTIP
1768    actionSettingsToolbarsConfigure->setStatusTip(tr("Customize toolbars"));
1769#endif // QT_NO_STATUSTIP
1770#endif // HANDHELD
1771
1772#ifndef QT_NO_STATUSTIP
1773    actionHelpReportBug->setStatusTip(tr("Report about a bug in %1").arg(QCoreApplication::applicationName()));
1774#endif // QT_NO_STATUSTIP
1775    if (actionHelpCheck4Updates != NULL) {
1776        actionHelpCheck4Updates->setText(tr("Check for &Updates..."));
1777#ifndef QT_NO_STATUSTIP
1778        actionHelpCheck4Updates->setStatusTip(tr("Check for %1 updates").arg(QCoreApplication::applicationName()));
1779#endif // QT_NO_STATUSTIP
1780    }
1781#ifndef QT_NO_STATUSTIP
1782    actionHelpAbout->setStatusTip(tr("About %1").arg(QCoreApplication::applicationName()));
1783#endif // QT_NO_STATUSTIP
1784
1785#ifdef Q_OS_SYMBIAN
1786    actionRightSoftKey->setText(tr("E&xit"));
1787#endif
1788}
1789
1790bool MainWindow::saveTask() {
1791QStringList filters(tr("%1 Task File").arg("TSPSG") + " (*.tspt)");
1792    filters.append(tr("All Files") + " (*)");
1793QString file;
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";
1803
1804QFileDialog::Options opts = settings->value("UseNativeDialogs", DEF_USE_NATIVE_DIALOGS).toBool() ? QFileDialog::Options() : QFileDialog::DontUseNativeDialog;
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());
1810    if (QFileInfo(file).suffix().isEmpty()) {
1811        file.append(".tspt");
1812    }
1813
1814    if (tspmodel->saveTask(file)) {
1815        setFileName(file);
1816        setWindowModified(false);
1817        return true;
1818    }
1819    return false;
1820}
1821
1822void MainWindow::setFileName(const QString &fileName)
1823{
1824    this->fileName = fileName;
1825    setWindowTitle(QString("%1[*] - %2").arg(QFileInfo(fileName).completeBaseName()).arg(QCoreApplication::applicationName()));
1826}
1827
1828void MainWindow::setupUi()
1829{
1830    Ui_MainWindow::setupUi(this);
1831
1832#ifdef Q_OS_SYMBIAN
1833    setWindowFlags(windowFlags() | Qt::WindowSoftkeysVisibleHint);
1834#endif // Q_OS_SYMBIAN
1835
1836    // File Menu
1837    actionFileNew->setIcon(GET_ICON("document-new"));
1838    actionFileOpen->setIcon(GET_ICON("document-open"));
1839    actionFileSave->setIcon(GET_ICON("document-save"));
1840#ifndef HANDHELD
1841    menuFileSaveAs->setIcon(GET_ICON("document-save-as"));
1842#endif
1843    actionFileExit->setIcon(GET_ICON("application-exit"));
1844    // Settings Menu
1845#ifndef HANDHELD
1846    menuSettingsLanguage->setIcon(GET_ICON("preferences-desktop-locale"));
1847#if QT_VERSION >= QT_VERSION_CHECK(4,6,0)
1848    actionSettingsLanguageEnglish->setIcon(QIcon::fromTheme("flag-gb", QIcon(":/images/icons/l10n/flag-gb.png")));
1849#else
1850    actionSettingsLanguageEnglish->setIcon(QIcon(":/images/icons/l10n/flag-gb.png"));
1851#endif // QT_VERSION >= QT_VERSION_CHECK(4,6,0)
1852    menuSettingsStyle->setIcon(GET_ICON("preferences-desktop-theme"));
1853#endif // HANDHELD
1854    actionSettingsPreferences->setIcon(GET_ICON("preferences-system"));
1855    // Help Menu
1856#ifndef HANDHELD
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"));
1862#if QT_VERSION < QT_VERSION_CHECK(5,0,0)
1863    actionHelpAboutQt->setIcon(QIcon(":/trolltech/qmessagebox/images/qtlogo-64.png"));
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
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"));
1873
1874//      action->setIcon(GET_ICON(""));
1875
1876#if QT_VERSION >= QT_VERSION_CHECK(4,6,0)
1877    setToolButtonStyle(Qt::ToolButtonFollowStyle);
1878#endif
1879
1880#ifndef HANDHELD
1881QStatusBar *statusbar = new QStatusBar(this);
1882    statusbar->setObjectName("statusbar");
1883    setStatusBar(statusbar);
1884#endif // HANDHELD
1885
1886#ifdef Q_OS_WINCE_WM
1887    menuBar()->setDefaultAction(menuFile->menuAction());
1888
1889QScrollArea *scrollArea = new QScrollArea(this);
1890    scrollArea->setFrameShape(QFrame::NoFrame);
1891    scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
1892    scrollArea->setWidgetResizable(true);
1893    scrollArea->setWidget(tabWidget);
1894    setCentralWidget(scrollArea);
1895#else
1896    setCentralWidget(tabWidget);
1897#endif // Q_OS_WINCE_WM
1898
1899    //! \hack HACK: A little hack for toolbar icons to have a sane size.
1900#if defined(HANDHELD) && !defined(Q_WS_MAEMO_5)
1901#ifdef Q_OS_SYMBIAN
1902    toolBarMain->setIconSize(QSize(logicalDpiX() / 5.2, logicalDpiY() / 5.2));
1903#else
1904    toolBarMain->setIconSize(QSize(logicalDpiX() / 4, logicalDpiY() / 4));
1905#endif // Q_OS_SYMBIAN
1906#endif // HANDHELD && !Q_WS_MAEMO_5
1907QToolButton *tb = static_cast<QToolButton *>(toolBarMain->widgetForAction(actionFileSave));
1908    if (tb != NULL) {
1909        tb->setMenu(menuFileSaveAs);
1910        tb->setPopupMode(QToolButton::MenuButtonPopup);
1911    }
1912
1913//      solutionText->document()->setDefaultFont(settings->value("Output/Font", QFont(DEF_FONT_FAMILY, DEF_FONT_SIZE)).value<QFont>());
1914    solutionText->setWordWrapMode(QTextOption::WordWrap);
1915
1916#ifndef QT_NO_PRINTER
1917    actionFilePrintPreview = new QAction(this);
1918    actionFilePrintPreview->setObjectName("actionFilePrintPreview");
1919    actionFilePrintPreview->setEnabled(false);
1920    actionFilePrintPreview->setIcon(GET_ICON("document-print-preview"));
1921
1922    actionFilePageSetup = new QAction(this);
1923    actionFilePageSetup->setObjectName("actionFilePrintSetup");
1924//    actionFilePageSetup->setEnabled(false);
1925#if QT_VERSION >= QT_VERSION_CHECK(4,6,0)
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
1931    actionFilePrint = new QAction(this);
1932    actionFilePrint->setObjectName("actionFilePrint");
1933    actionFilePrint->setEnabled(false);
1934    actionFilePrint->setIcon(GET_ICON("document-print"));
1935
1936    menuFile->insertAction(actionFileExit, actionFilePrintPreview);
1937    menuFile->insertAction(actionFileExit, actionFilePageSetup);
1938    menuFile->insertAction(actionFileExit, actionFilePrint);
1939    menuFile->insertSeparator(actionFileExit);
1940
1941    toolBarMain->insertAction(actionSettingsPreferences, actionFilePrint);
1942#endif // QT_NO_PRINTER
1943
1944    groupSettingsLanguageList = new QActionGroup(this);
1945#ifdef Q_WS_MAEMO_5
1946    groupSettingsLanguageList->addAction(actionSettingsLanguageAutodetect);
1947#endif
1948    actionSettingsLanguageEnglish->setData("en");
1949    actionSettingsLanguageEnglish->setActionGroup(groupSettingsLanguageList);
1950    loadLangList();
1951    actionSettingsLanguageAutodetect->setChecked(settings->value("Language", "").toString().isEmpty());
1952
1953    actionSettingsStyleSystem->setData(true);
1954    groupSettingsStyleList = new QActionGroup(this);
1955#ifdef Q_WS_MAEMO_5
1956    groupSettingsStyleList->addAction(actionSettingsStyleSystem);
1957#endif
1958
1959#ifndef HANDHELD
1960    actionSettingsToolbarsConfigure = new QAction(this);
1961    actionSettingsToolbarsConfigure->setIcon(GET_ICON("configure-toolbars"));
1962#endif // HANDHELD
1963
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;
1972
1973    spinCities->setMaximum(settings->value("Tweaks/MaxNumCities", MAX_NUM_CITIES).toInt());
1974
1975#ifndef HANDHELD
1976    toolBarManager = new QtToolBarManager(this);
1977    toolBarManager->setMainWindow(this);
1978QString cat = toolBarMain->windowTitle();
1979    toolBarManager->addToolBar(toolBarMain, cat);
1980#ifndef QT_NO_PRINTER
1981    toolBarManager->addAction(actionFilePrintPreview, cat);
1982    toolBarManager->addAction(actionFilePageSetup, cat);
1983#endif // QT_NO_PRINTER
1984    toolBarManager->addAction(actionHelpContents, cat);
1985    toolBarManager->addAction(actionHelpContextual, cat);
1986    toolBarManager->restoreState(settings->value("MainWindow/Toolbars").toByteArray());
1987#else
1988    toolBarMain->setVisible(settings->value("MainWindow/ToolbarVisible", true).toBool());
1989#endif // HANDHELD
1990
1991#ifdef Q_OS_SYMBIAN
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
2000    retranslateUi(false);
2001
2002#ifndef HANDHELD
2003    // Adding some eyecandy
2004    if (QtWin::isCompositionEnabled() && settings->value("UseTranslucency", DEF_USE_TRANSLUCENCY).toBool())  {
2005        toggleTranclucency(true);
2006    }
2007#endif // HANDHELD
2008}
2009
2010void MainWindow::toggleSolutionActions(bool enable)
2011{
2012    buttonSaveSolution->setEnabled(enable);
2013    actionFileSaveAsSolution->setEnabled(enable);
2014    solutionText->setEnabled(enable);
2015#ifndef QT_NO_PRINTER
2016    actionFilePrint->setEnabled(enable);
2017    actionFilePrintPreview->setEnabled(enable);
2018#endif // QT_NO_PRINTER
2019}
2020
2021void MainWindow::toggleTranclucency(bool enable)
2022{
2023#ifndef HANDHELD
2024    toggleStyle(labelVariant, enable);
2025    toggleStyle(labelCities, enable);
2026    toggleStyle(statusBar(), enable);
2027    tabWidget->setDocumentMode(enable);
2028    QtWin::enableBlurBehindWindow(this, enable);
2029#else
2030    Q_UNUSED(enable);
2031#endif // HANDHELD
2032}
2033
2034void MainWindow::actionHelpOnlineSupportTriggered()
2035{
2036    QDesktopServices::openUrl(QUrl("http://tspsg.info/goto/support"));
2037}
2038
2039void MainWindow::actionHelpReportBugTriggered()
2040{
2041    QDesktopServices::openUrl(QUrl("http://tspsg.info/goto/bugtracker"));
2042}
2043
2044#ifdef Q_OS_SYMBIAN
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);
2054    m->addAction(QApplication::translate("QDialogButtonBox", "Discard", "No need to translate this. The translation will be taken from Qt translation files."),
2055                 this, SLOT(discard()));
2056    m->addAction(QApplication::translate("QDialogButtonBox", "Cancel", "No need to translate this. The translation will be taken from Qt translation files."),
2057                 this, SLOT(cancel()));
2058
2059    QAction *o = new QAction(QApplication::translate("QtToolBarDialog", "Actions"), this);
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}
2072#endif // Q_OS_SYMBIAN
Note: See TracBrowser for help on using the repository browser.