source: tspsg/src/mainwindow.cpp @ 97e90f9be6

0.1.3.145-beta1-symbian0.1.4.170-beta2-bb10appveyorimgbotreadme
Last change on this file since 97e90f9be6 was 97e90f9be6, checked in by Oleksii Serdiuk, 14 years ago

+ Added support for Simulator from Nokia Qt SDK

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