source: tspsg/src/mainwindow.cpp @ b81c0a73b7

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

Updated translations...

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