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

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