source: tspsg/src/mainwindow.cpp @ d45b48efe9

0.1.3.145-beta1-symbian
Last change on this file since d45b48efe9 was d45b48efe9, checked in by Oleksii Serdiuk, 13 years ago

Initial Symbian port.

Version 0.1.3.145-beta1, as published in the Nokia Ovi Store.

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