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

Last change on this file since 140 was 140, checked in by laleppa, 14 years ago

Fixed some compilation errors on some platforms intorduced in the previous build...

  • Property svn:eol-style set to native
  • Property svn:keywords set to Id URL
File size: 57.0 KB
Line 
1/*
2 *  TSPSG: TSP Solver and Generator
3 *  Copyright (C) 2007-2010 Lёppa <contacts[at]oleksii[dot]name>
4 *
5 *  $Id: mainwindow.cpp 140 2010-09-29 21:54:39Z laleppa $
6 *  $URL: https://tspsg.svn.sourceforge.net/svnroot/tspsg/trunk/src/mainwindow.cpp $
7 *
8 *  This file is part of TSPSG.
9 *
10 *  TSPSG is free software: you can redistribute it and/or modify
11 *  it under the terms of the GNU General Public License as published by
12 *  the Free Software Foundation, either version 3 of the License, or
13 *  (at your option) any later version.
14 *
15 *  TSPSG is distributed in the hope that it will be useful,
16 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
17 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 *  GNU General Public License for more details.
19 *
20 *  You should have received a copy of the GNU General Public License
21 *  along with TSPSG.  If not, see <http://www.gnu.org/licenses/>.
22 */
23
24#include "mainwindow.h"
25
26#ifdef Q_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        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        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
437void MainWindow::actionHelpCheck4UpdatesTriggered()
438{
439        if (!hasUpdater()) {
440                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."));
441                return;
442        }
443
444        check4Updates();
445}
446
447void MainWindow::actionHelpAboutTriggered()
448{
449        QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
450
451QString title;
452        title += QString("<b>%1</b><br>").arg(QApplication::applicationName());
453        title += QString("%1: <b>%2</b><br>").arg(tr("Version"), QApplication::applicationVersion());
454#ifndef HANDHELD
455        title += QString("<b>&copy; 2007-%1 <a href=\"http://%2/\">%3</a></b><br>").arg(QDate::currentDate().toString("yyyy"), QApplication::organizationDomain(), QApplication::organizationName());
456#endif // HANDHELD
457        title += QString("<b><a href=\"http://tspsg.info/\">http://tspsg.info/</a></b>");
458
459QString about;
460        about += QString("%1: <b>%2</b><br>").arg(tr("Target OS (ARCH)"), PLATFROM);
461#ifndef STATIC_BUILD
462        about += QString("%1 (%2):<br>").arg(tr("Qt library"), tr("shared"));
463        about += QString("&nbsp;&nbsp;&nbsp;&nbsp;%1: <b>%2</b><br>").arg(tr("Build time"), QT_VERSION_STR);
464        about += QString("&nbsp;&nbsp;&nbsp;&nbsp;%1: <b>%2</b><br>").arg(tr("Runtime"), qVersion());
465#else
466        about += QString("%1: <b>%2</b> (%3)<br>").arg(tr("Qt library"), QT_VERSION_STR, tr("static"));
467#endif // STATIC_BUILD
468        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>";
469        about += QString("%1: <b>%2</b><br>").arg(tr("Algorithm"), CTSPSolver::getVersionId());
470        about += "<br>";
471        about += tr("This program is free software: you can redistribute it and/or modify<br>\n"
472                "it under the terms of the GNU General Public License as published by<br>\n"
473                "the Free Software Foundation, either version 3 of the License, or<br>\n"
474                "(at your option) any later version.<br>\n"
475                "<br>\n"
476                "This program is distributed in the hope that it will be useful,<br>\n"
477                "but WITHOUT ANY WARRANTY; without even the implied warranty of<br>\n"
478                "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the<br>\n"
479                "GNU General Public License for more details.<br>\n"
480                "<br>\n"
481                "You should have received a copy of the GNU General Public License<br>\n"
482                "along with TSPSG.  If not, see <a href=\"http://www.gnu.org/licenses/\">www.gnu.org/licenses/</a>.");
483
484QString credits;
485        credits += tr("%1 was created using <b>Qt&nbsp;framework</b> licensed "
486                "under the terms of the GNU Lesser General Public License,<br>\n"
487                "see <a href=\"http://qt.nokia.com/\">qt.nokia.com</a><br>\n"
488                "<br>\n"
489                "Most icons used in %1 are part of <b>Oxygen&nbsp;Icons</b> project "
490                "licensed according to the GNU Lesser General Public License,<br>\n"
491                "see <a href=\"http://www.oxygen-icons.org/\">www.oxygen-icons.org</a><br>\n"
492                "<br>\n"
493                "Country flag icons used in %1 are part of the free "
494                "<b>Flag&nbsp;Icons</b> collection created by <b>IconDrawer</b>,<br>\n"
495                "see <a href=\"http://www.icondrawer.com/\">www.icondrawer.com</a><br>\n"
496                "<br>\n"
497                "%1 comes with the default \"embedded\" font <b>DejaVu&nbsp;LGC&nbsp;Sans&nbsp;"
498                "Mono</b> from the <b>DejaVu fonts</b> licensed under a Free license</a>,<br>\n"
499                "see <a href=\"http://dejavu-fonts.org/\">dejavu-fonts.org</a>")
500                        .arg("TSPSG");
501
502QFile f(":/files/COPYING");
503        f.open(QIODevice::ReadOnly);
504
505QString translation = QApplication::translate("--------", "AUTHORS %1", "Please, provide translator credits here. %1 will be replaced with VERSION");
506        if ((translation != "AUTHORS %1") && (translation.contains("%1"))) {
507QString about = QApplication::translate("--------", "VERSION", "Please, provide your translation version here.");
508                if (about != "VERSION")
509                        translation = translation.arg(about);
510        }
511
512QDialog *dlg = new QDialog(this);
513QLabel *lblIcon = new QLabel(dlg),
514        *lblTitle = new QLabel(dlg);
515#ifdef HANDHELD
516QLabel *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);
517#endif // HANDHELD
518QTabWidget *tabs = new QTabWidget(dlg);
519QTextBrowser *txtAbout = new QTextBrowser(dlg);
520QTextBrowser *txtLicense = new QTextBrowser(dlg);
521QTextBrowser *txtCredits = new QTextBrowser(dlg);
522QVBoxLayout *vb = new QVBoxLayout();
523QHBoxLayout *hb1 = new QHBoxLayout(),
524        *hb2 = new QHBoxLayout();
525QDialogButtonBox *bb = new QDialogButtonBox(QDialogButtonBox::Ok, Qt::Horizontal, dlg);
526
527        lblTitle->setOpenExternalLinks(true);
528        lblTitle->setText(title);
529        lblTitle->setAlignment(Qt::AlignTop);
530        lblTitle->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
531#ifndef HANDHELD
532        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()));
533#endif // HANDHELD
534
535        lblIcon->setPixmap(QPixmap(":/images/tspsg.png").scaledToHeight(lblTitle->sizeHint().height(), Qt::SmoothTransformation));
536        lblIcon->setAlignment(Qt::AlignVCenter);
537#ifndef HANDHELD
538        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()));
539#endif // HANDHELD
540
541        hb1->addWidget(lblIcon);
542        hb1->addWidget(lblTitle);
543
544        txtAbout->setWordWrapMode(QTextOption::NoWrap);
545        txtAbout->setOpenExternalLinks(true);
546        txtAbout->setHtml(about);
547        txtAbout->moveCursor(QTextCursor::Start);
548        txtAbout->setFrameShape(QFrame::NoFrame);
549
550//      txtCredits->setWordWrapMode(QTextOption::NoWrap);
551        txtCredits->setOpenExternalLinks(true);
552        txtCredits->setHtml(credits);
553        txtCredits->moveCursor(QTextCursor::Start);
554        txtCredits->setFrameShape(QFrame::NoFrame);
555
556        txtLicense->setWordWrapMode(QTextOption::NoWrap);
557        txtLicense->setOpenExternalLinks(true);
558        txtLicense->setText(f.readAll());
559        txtLicense->moveCursor(QTextCursor::Start);
560        txtLicense->setFrameShape(QFrame::NoFrame);
561
562        bb->button(QDialogButtonBox::Ok)->setCursor(QCursor(Qt::PointingHandCursor));
563        bb->button(QDialogButtonBox::Ok)->setIcon(GET_ICON("dialog-ok"));
564
565        hb2->addWidget(bb);
566
567#ifdef Q_OS_WINCE_WM
568        vb->setMargin(3);
569#endif // Q_OS_WINCE_WM
570        vb->addLayout(hb1);
571#ifdef HANDHELD
572        vb->addWidget(lblSubTitle);
573#endif // HANDHELD
574
575        tabs->addTab(txtAbout, tr("About"));
576        tabs->addTab(txtLicense, tr("License"));
577        tabs->addTab(txtCredits, tr("Credits"));
578        if (translation != "AUTHORS %1") {
579QTextBrowser *txtTranslation = new QTextBrowser(dlg);
580//              txtTranslation->setWordWrapMode(QTextOption::NoWrap);
581                txtTranslation->setOpenExternalLinks(true);
582                txtTranslation->setText(translation);
583                txtTranslation->moveCursor(QTextCursor::Start);
584                txtTranslation->setFrameShape(QFrame::NoFrame);
585
586                tabs->addTab(txtTranslation, tr("Translation"));
587        }
588#ifndef HANDHELD
589        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()));
590#endif // HANDHELD
591
592        vb->addWidget(tabs);
593        vb->addLayout(hb2);
594
595        dlg->setWindowFlags(Qt::Dialog | Qt::CustomizeWindowHint | Qt::WindowTitleHint | Qt::WindowCloseButtonHint);
596        dlg->setWindowTitle(tr("About %1").arg(QApplication::applicationName()));
597        dlg->setWindowIcon(GET_ICON("help-about"));
598        dlg->setLayout(vb);
599
600        connect(bb, SIGNAL(accepted()), dlg, SLOT(accept()));
601
602#ifdef Q_OS_WIN32
603        // Adding some eyecandy in Vista and 7 :-)
604        if (QtWin::isCompositionEnabled())  {
605                QtWin::enableBlurBehindWindow(dlg, true);
606        }
607#endif // Q_OS_WIN32
608
609        dlg->resize(450, 350);
610        QApplication::restoreOverrideCursor();
611
612        dlg->exec();
613
614        delete dlg;
615}
616
617void MainWindow::buttonBackToTaskClicked()
618{
619        tabWidget->setCurrentIndex(0);
620}
621
622void MainWindow::buttonRandomClicked()
623{
624        QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
625        tspmodel->randomize();
626        QApplication::restoreOverrideCursor();
627}
628
629void MainWindow::buttonSolveClicked()
630{
631TMatrix matrix;
632QList<double> row;
633int n = spinCities->value();
634bool ok;
635        for (int r = 0; r < n; r++) {
636                row.clear();
637                for (int c = 0; c < n; c++) {
638                        row.append(tspmodel->index(r,c).data(Qt::UserRole).toDouble(&ok));
639                        if (!ok) {
640                                QMessageBox::critical(this, tr("Data error"), tr("Error in cell [Row %1; Column %2]: Invalid data format.").arg(r + 1).arg(c + 1));
641                                return;
642                        }
643                }
644                matrix.append(row);
645        }
646
647QProgressDialog pd(this);
648QProgressBar *pb = new QProgressBar(&pd);
649        pb->setAlignment(Qt::AlignCenter);
650        pb->setFormat(tr("%v of %1 parts found").arg(n));
651        pd.setBar(pb);
652QPushButton *cancel = new QPushButton(&pd);
653        cancel->setIcon(GET_ICON("dialog-cancel"));
654        cancel->setText(QApplication::translate("QProgressDialog", "Cancel", "No need to translate this. This translation will be taken from Qt translation files."));
655        pd.setCancelButton(cancel);
656        pd.setMaximum(n);
657        pd.setAutoReset(false);
658        pd.setLabelText(tr("Calculating optimal route..."));
659        pd.setWindowTitle(tr("Solution Progress"));
660        pd.setWindowModality(Qt::ApplicationModal);
661        pd.setWindowFlags(Qt::Dialog | Qt::CustomizeWindowHint | Qt::WindowTitleHint);
662        pd.show();
663
664#ifdef Q_OS_WIN32
665HRESULT hr = CoCreateInstance(CLSID_TaskbarList, NULL, CLSCTX_INPROC_SERVER, IID_ITaskbarList3, (LPVOID*)&tl);
666        if (SUCCEEDED(hr)) {
667                hr = tl->HrInit();
668                if (FAILED(hr)) {
669                        tl->Release();
670                        tl = NULL;
671                } else {
672//                      tl->SetProgressState(winId(), TBPF_INDETERMINATE);
673                        tl->SetProgressValue(winId(), 0, n * 2);
674                }
675        }
676#endif
677
678CTSPSolver solver;
679        solver.setCleanupOnCancel(false);
680        connect(&solver, SIGNAL(routePartFound(int)), &pd, SLOT(setValue(int)));
681        connect(&pd, SIGNAL(canceled()), &solver, SLOT(cancel()));
682#ifdef Q_OS_WIN32
683        if (tl != NULL)
684                connect(&solver, SIGNAL(routePartFound(int)), SLOT(solverRoutePartFound(int)));
685#endif
686SStep *root = solver.solve(n, matrix);
687#ifdef Q_OS_WIN32
688        if (tl != NULL)
689                disconnect(&solver, SIGNAL(routePartFound(int)), this, SLOT(solverRoutePartFound(int)));
690#endif
691        disconnect(&solver, SIGNAL(routePartFound(int)), &pd, SLOT(setValue(int)));
692        disconnect(&pd, SIGNAL(canceled()), &solver, SLOT(cancel()));
693        if (!root) {
694                pd.reset();
695                if (!solver.wasCanceled()) {
696#ifdef Q_OS_WIN32
697                        if (tl != NULL) {
698//                              tl->SetProgressValue(winId(), n, n * 2);
699                                tl->SetProgressState(winId(), TBPF_ERROR);
700                        }
701#endif
702                        QApplication::alert(this);
703                        QMessageBox::warning(this, tr("Solution Result"), tr("Unable to find a solution.\nMaybe, this task has no solution."));
704                }
705                pd.setLabelText(tr("Cleaning up..."));
706                pd.setMaximum(0);
707                pd.setCancelButton(NULL);
708                pd.show();
709#ifdef Q_OS_WIN32
710                if (tl != NULL)
711                        tl->SetProgressState(winId(), TBPF_INDETERMINATE);
712#endif
713                QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
714
715#ifndef QT_NO_CONCURRENT
716QFuture<void> f = QtConcurrent::run(&solver, &CTSPSolver::cleanup, false);
717                while (!f.isFinished()) {
718                        QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
719                }
720#else
721                solver.cleanup(true);
722#endif
723                pd.reset();
724#ifdef Q_OS_WIN32
725                if (tl != NULL) {
726                        tl->SetProgressState(winId(), TBPF_NOPROGRESS);
727                        tl->Release();
728                        tl = NULL;
729                }
730#endif
731                return;
732        }
733        pb->setFormat(tr("Generating header"));
734        pd.setLabelText(tr("Generating solution output..."));
735        pd.setMaximum(solver.getTotalSteps() + 1);
736        pd.setValue(0);
737
738#ifdef Q_OS_WIN32
739        if (tl != NULL)
740                tl->SetProgressValue(winId(), spinCities->value(), spinCities->value() + solver.getTotalSteps() + 1);
741#endif
742
743        solutionText->clear();
744        solutionText->setDocumentTitle(tr("Solution of Variant #%1 Task").arg(spinVariant->value()));
745
746QPainter pic;
747        if (settings->value("Output/ShowGraph", DEF_SHOW_GRAPH).toBool()) {
748                pic.begin(&graph);
749                pic.setRenderHints(QPainter::Antialiasing | QPainter::SmoothPixmapTransform);
750QFont font = qvariant_cast<QFont>(settings->value("Output/Font", QFont(DEF_FONT_FACE, 9)));
751                if (settings->value("Output/HQGraph", DEF_HQ_GRAPH).toBool()) {
752                        font.setWeight(QFont::DemiBold);
753                        font.setPointSizeF(font.pointSizeF() * 2);
754                }
755                pic.setFont(font);
756                pic.setBrush(QBrush(QColor(Qt::white)));
757                if (settings->value("Output/HQGraph", DEF_HQ_GRAPH).toBool()) {
758QPen pen = pic.pen();
759                        pen.setWidth(2);
760                        pic.setPen(pen);
761                }
762                pic.setBackgroundMode(Qt::OpaqueMode);
763        }
764
765QTextDocument *doc = solutionText->document();
766QTextCursor cur(doc);
767
768        cur.beginEditBlock();
769        cur.setBlockFormat(fmt_paragraph);
770        cur.insertText(tr("Variant #%1 Task").arg(spinVariant->value()), fmt_default);
771        cur.insertBlock(fmt_paragraph);
772        cur.insertText(tr("Task:"));
773        outputMatrix(cur, matrix);
774        if (settings->value("Output/ShowGraph", DEF_SHOW_GRAPH).toBool()) {
775#ifdef _T_T_L_
776                _b_ _i_ _z_ _a_ _r_ _r_ _e_
777#endif
778                drawNode(pic, 0);
779        }
780        cur.insertHtml("<hr>");
781        cur.insertBlock(fmt_paragraph);
782int imgpos = cur.position();
783        cur.insertText(tr("Variant #%1 Solution").arg(spinVariant->value()), fmt_default);
784        cur.endEditBlock();
785
786SStep *step = root;
787int c = n = 1;
788        pb->setFormat(tr("Generating step %v"));
789        while ((step->next != SStep::NoNextStep) && (c < spinCities->value())) {
790                if (pd.wasCanceled()) {
791                        pd.setLabelText(tr("Cleaning up..."));
792                        pd.setMaximum(0);
793                        pd.setCancelButton(NULL);
794                        pd.show();
795                        QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
796#ifdef Q_OS_WIN32
797                        if (tl != NULL)
798                                tl->SetProgressState(winId(), TBPF_INDETERMINATE);
799#endif
800#ifndef QT_NO_CONCURRENT
801QFuture<void> f = QtConcurrent::run(&solver, &CTSPSolver::cleanup, false);
802                        while (!f.isFinished()) {
803                                QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
804                        }
805#else
806                        solver.cleanup(true);
807#endif
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() + 2, graph.height() + 2, 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
932#ifndef QT_NO_CONCURRENT
933QFuture<void> f = QtConcurrent::run(&solver, &CTSPSolver::cleanup, false);
934        while (!f.isFinished()) {
935                QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
936        }
937#else
938        solver.cleanup(true);
939#endif
940        toggleSolutionActions();
941        tabWidget->setCurrentIndex(1);
942#ifdef Q_OS_WIN32
943        if (tl != NULL) {
944                tl->SetProgressState(winId(), TBPF_NOPROGRESS);
945                tl->Release();
946                tl = NULL;
947        }
948#endif
949
950        pd.reset();
951        QApplication::alert(this, 3000);
952}
953
954void MainWindow::dataChanged()
955{
956        setWindowModified(true);
957}
958
959void MainWindow::dataChanged(const QModelIndex &tl, const QModelIndex &br)
960{
961        setWindowModified(true);
962        if (settings->value("Autosize", DEF_AUTOSIZE).toBool()) {
963                for (int k = tl.row(); k <= br.row(); k++)
964                        taskView->resizeRowToContents(k);
965                for (int k = tl.column(); k <= br.column(); k++)
966                        taskView->resizeColumnToContents(k);
967        }
968}
969
970#ifdef Q_OS_WINCE_WM
971void MainWindow::changeEvent(QEvent *ev)
972{
973        if ((ev->type() == QEvent::ActivationChange) && isActiveWindow())
974                desktopResized(0);
975
976        QWidget::changeEvent(ev);
977}
978
979void MainWindow::desktopResized(int screen)
980{
981        if ((screen != 0) || !isActiveWindow())
982                return;
983
984QRect availableGeometry = QApplication::desktop()->availableGeometry(0);
985        if (currentGeometry != availableGeometry) {
986                QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
987                /*!
988                 * \hack HACK: This hack checks whether \link QDesktopWidget::availableGeometry() availableGeometry()\endlink's \c top + \c hegiht = \link QDesktopWidget::screenGeometry() screenGeometry()\endlink's \c height.
989                 *  If \c true, the window gets maximized. If we used \c setGeometry() in this case, the bottom of the
990                 *  window would end up being behind the soft buttons. Is this a bug in Qt or Windows Mobile?
991                 */
992                if ((availableGeometry.top() + availableGeometry.height()) == QApplication::desktop()->screenGeometry().height()) {
993                        setWindowState(windowState() | Qt::WindowMaximized);
994                } else {
995                        if (windowState() & Qt::WindowMaximized)
996                                setWindowState(windowState() ^ Qt::WindowMaximized);
997                        setGeometry(availableGeometry);
998                }
999                currentGeometry = availableGeometry;
1000                QApplication::restoreOverrideCursor();
1001        }
1002}
1003#endif // Q_OS_WINCE_WM
1004
1005void MainWindow::numCitiesChanged(int nCities)
1006{
1007        blockSignals(true);
1008        spinCities->setValue(nCities);
1009        blockSignals(false);
1010}
1011
1012#ifndef QT_NO_PRINTER
1013void MainWindow::printPreview(QPrinter *printer)
1014{
1015        solutionText->print(printer);
1016}
1017#endif // QT_NO_PRINTER
1018
1019#ifdef Q_OS_WIN32
1020void MainWindow::solverRoutePartFound(int n)
1021{
1022#ifdef Q_OS_WIN32
1023        tl->SetProgressValue(winId(), n, spinCities->value() * 2);
1024#else
1025        Q_UNUSED(n);
1026#endif // Q_OS_WIN32
1027}
1028#endif // Q_OS_WIN32
1029
1030void MainWindow::spinCitiesValueChanged(int n)
1031{
1032        QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
1033int count = tspmodel->numCities();
1034        tspmodel->setNumCities(n);
1035        if ((n > count) && settings->value("Autosize", DEF_AUTOSIZE).toBool())
1036                for (int k = count; k < n; k++) {
1037                        taskView->resizeColumnToContents(k);
1038                        taskView->resizeRowToContents(k);
1039                }
1040        QApplication::restoreOverrideCursor();
1041}
1042
1043void MainWindow::check4Updates(bool silent)
1044{
1045#ifdef Q_OS_WIN32
1046        if (silent)
1047                QProcess::startDetached("updater/Update.exe -name=\"TSPSG: TSP Solver and Generator\" -check=\"freeupdate\" -silentcheck");
1048        else {
1049                QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
1050                QProcess::execute("updater/Update.exe -name=\"TSPSG: TSP Solver and Generator\" -check=\"freeupdate\"");
1051                QApplication::restoreOverrideCursor();
1052        }
1053#else
1054        Q_UNUSED(silent)
1055#endif
1056        settings->setValue("Check4Updates/LastAttempt", QDate::currentDate().toString(Qt::ISODate));
1057}
1058
1059void MainWindow::closeEvent(QCloseEvent *ev)
1060{
1061        if (!maybeSave()) {
1062                ev->ignore();
1063                return;
1064        }
1065        if (!settings->value("SettingsReset", false).toBool()) {
1066                settings->setValue("NumCities", spinCities->value());
1067
1068                // Saving Main Window state
1069#ifndef HANDHELD
1070                if (settings->value("SavePos", DEF_SAVEPOS).toBool()) {
1071                        settings->beginGroup("MainWindow");
1072                        settings->setValue("Geometry", saveGeometry());
1073                        settings->setValue("State", saveState());
1074                        settings->setValue("Toolbars", toolBarManager->saveState());
1075                        settings->endGroup();
1076                }
1077#else
1078                settings->setValue("MainWindow/ToolbarVisible", toolBarMain->isVisible());
1079#endif // HANDHELD
1080        } else {
1081                settings->remove("SettingsReset");
1082        }
1083
1084        QMainWindow::closeEvent(ev);
1085}
1086
1087void MainWindow::dragEnterEvent(QDragEnterEvent *ev)
1088{
1089        if (ev->mimeData()->hasUrls() && (ev->mimeData()->urls().count() == 1)) {
1090QFileInfo fi(ev->mimeData()->urls().first().toLocalFile());
1091                if ((fi.suffix() == "tspt") || (fi.suffix() == "zkt"))
1092                        ev->acceptProposedAction();
1093        }
1094}
1095
1096void MainWindow::drawNode(QPainter &pic, int nstep, bool left, SStep *step)
1097{
1098int r;
1099        if (settings->value("Output/HQGraph", DEF_HQ_GRAPH).toBool())
1100                r = 70;
1101        else
1102                r = 35;
1103qreal x, y;
1104        if (step != NULL)
1105                x = left ? r : r * 3.5;
1106        else
1107                x = r * 2.25;
1108        y = r * (3 * nstep + 1);
1109
1110#ifdef _T_T_L_
1111        if (nstep == -481124) {
1112                _t_t_l_(pic, r, x);
1113                return;
1114        }
1115#endif
1116
1117        pic.drawEllipse(QPointF(x, y), r, r);
1118
1119        if (step != NULL) {
1120QFont font;
1121                if (left) {
1122                        font = pic.font();
1123                        font.setStrikeOut(true);
1124                        pic.setFont(font);
1125                }
1126                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");
1127                if (left) {
1128                        font.setStrikeOut(false);
1129                        pic.setFont(font);
1130                }
1131                if (step->price != INFINITY) {
1132                        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()));
1133                } else {
1134                        pic.drawText(QRectF(x - r, y - r, r * 2, r * 2), Qt::AlignCenter, "\n"INFSTR);
1135                }
1136        } else {
1137                pic.drawText(QRectF(x - r, y - r, r * 2, r * 2), Qt::AlignCenter, tr("Root"));
1138        }
1139
1140        if (nstep == 1) {
1141                pic.drawLine(QPointF(x, y - r), QPointF(r * 2.25, y - 2 * r));
1142        } else if (nstep > 1) {
1143                pic.drawLine(QPointF(x, y - r), QPointF((step->pNode->pNode->next == SStep::RightBranch) ? r * 3.5 : r, y - 2 * r));
1144        }
1145
1146}
1147
1148void MainWindow::dropEvent(QDropEvent *ev)
1149{
1150        if (maybeSave() && tspmodel->loadTask(ev->mimeData()->urls().first().toLocalFile())) {
1151                setFileName(ev->mimeData()->urls().first().toLocalFile());
1152                tabWidget->setCurrentIndex(0);
1153                setWindowModified(false);
1154                solutionText->clear();
1155                toggleSolutionActions(false);
1156
1157                ev->setDropAction(Qt::CopyAction);
1158                ev->accept();
1159        }
1160}
1161
1162void MainWindow::initDocStyleSheet()
1163{
1164        solutionText->document()->setDefaultFont(qvariant_cast<QFont>(settings->value("Output/Font", QFont(DEF_FONT_FACE, DEF_FONT_SIZE))));
1165
1166        fmt_paragraph.setTopMargin(0);
1167        fmt_paragraph.setRightMargin(10);
1168        fmt_paragraph.setBottomMargin(0);
1169        fmt_paragraph.setLeftMargin(10);
1170
1171        fmt_table.setTopMargin(5);
1172        fmt_table.setRightMargin(10);
1173        fmt_table.setBottomMargin(5);
1174        fmt_table.setLeftMargin(10);
1175        fmt_table.setBorder(0);
1176        fmt_table.setBorderStyle(QTextFrameFormat::BorderStyle_None);
1177        fmt_table.setCellSpacing(5);
1178
1179        fmt_cell.setAlignment(Qt::AlignHCenter);
1180
1181        settings->beginGroup("Output/Colors");
1182
1183QColor color = qvariant_cast<QColor>(settings->value("Text", DEF_TEXT_COLOR));
1184QColor hilight;
1185        if (color.value() < 192)
1186                hilight.setHsv(color.hue(), color.saturation(), 127 + qRound(color.value() / 2));
1187        else
1188                hilight.setHsv(color.hue(), color.saturation(), color.value() / 2);
1189
1190        solutionText->document()->setDefaultStyleSheet(QString("* {color: %1;}").arg(color.name()));
1191        fmt_default.setForeground(QBrush(color));
1192
1193        fmt_selected.setForeground(QBrush(qvariant_cast<QColor>(settings->value("Selected", DEF_SELECTED_COLOR))));
1194        fmt_selected.setFontWeight(QFont::Bold);
1195
1196        fmt_alternate.setForeground(QBrush(qvariant_cast<QColor>(settings->value("Alternate", DEF_ALTERNATE_COLOR))));
1197        fmt_alternate.setFontWeight(QFont::Bold);
1198        fmt_altlist.setForeground(QBrush(hilight));
1199
1200        settings->endGroup();
1201
1202        solutionText->setTextColor(color);
1203}
1204
1205void MainWindow::loadLangList()
1206{
1207QMap<QString, QStringList> langlist;
1208QFileInfoList langs;
1209QFileInfo lang;
1210QString name;
1211QStringList language, dirs;
1212QTranslator t;
1213QDir dir;
1214        dir.setFilter(QDir::Files);
1215        dir.setNameFilters(QStringList("tspsg_*.qm"));
1216        dir.setSorting(QDir::NoSort);
1217
1218        dirs << PATH_L10N << ":/l10n";
1219        foreach (QString dirname, dirs) {
1220                dir.setPath(dirname);
1221                if (dir.exists()) {
1222                        langs = dir.entryInfoList();
1223                        for (int k = 0; k < langs.size(); k++) {
1224                                lang = langs.at(k);
1225                                if (lang.completeBaseName().compare("tspsg_en", Qt::CaseInsensitive) && !langlist.contains(lang.completeBaseName().mid(6)) && t.load(lang.completeBaseName(), dirname)) {
1226
1227                                        language.clear();
1228                                        language.append(lang.completeBaseName().mid(6));
1229                                        language.append(t.translate("--------", "COUNTRY", "Please, provide an ISO 3166-1 alpha-2 country code for this translation language here (eg., UA).").toLower());
1230                                        language.append(t.translate("--------", "LANGNAME", "Please, provide a native name of your translation language here."));
1231                                        language.append(t.translate("MainWindow", "Set application language to %1", "").arg(name));
1232
1233                                        langlist.insert(language.at(0), language);
1234                                }
1235                        }
1236                }
1237        }
1238
1239QAction *a;
1240        foreach (language, langlist) {
1241                a = menuSettingsLanguage->addAction(language.at(2));
1242                a->setStatusTip(language.at(3));
1243#if QT_VERSION >= 0x040600
1244                a->setIcon(QIcon::fromTheme(QString("flag-%1").arg(language.at(1)), QIcon(QString(":/images/icons/l10n/flag-%1.png").arg(language.at(1)))));
1245#else
1246                a->setIcon(QIcon(QString(":/images/icons/l10n/flag-%1.png").arg(language.at(1))));
1247#endif
1248                a->setData(language.at(0));
1249                a->setCheckable(true);
1250                a->setActionGroup(groupSettingsLanguageList);
1251                if (settings->value("Language", QLocale::system().name()).toString().startsWith(language.at(0)))
1252                        a->setChecked(true);
1253        }
1254}
1255
1256bool MainWindow::loadLanguage(const QString &lang)
1257{
1258// i18n
1259bool ad = false;
1260QString lng = lang;
1261        if (lng.isEmpty()) {
1262                ad = settings->value("Language", "").toString().isEmpty();
1263                lng = settings->value("Language", QLocale::system().name()).toString();
1264        }
1265static QTranslator *qtTranslator; // Qt library translator
1266        if (qtTranslator) {
1267                qApp->removeTranslator(qtTranslator);
1268                delete qtTranslator;
1269                qtTranslator = NULL;
1270        }
1271static QTranslator *translator; // Application translator
1272        if (translator) {
1273                qApp->removeTranslator(translator);
1274                delete translator;
1275                translator = NULL;
1276        }
1277
1278        if (lng == "en")
1279                return true;
1280
1281        // Trying to load system Qt library translation...
1282        qtTranslator = new QTranslator(this);
1283        if (qtTranslator->load("qt_" + lng, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
1284                qApp->installTranslator(qtTranslator);
1285        else {
1286                // No luck. Let's try to load a bundled one.
1287                if (qtTranslator->load("qt_" + lng, PATH_L10N)) {
1288                        // We have a translation in the localization direcotry.
1289                        qApp->installTranslator(qtTranslator);
1290                } else if (qtTranslator->load("qt_" + lng, ":/l10n")) {
1291                        // We have a translation "built-in" into application resources.
1292                        qApp->installTranslator(qtTranslator);
1293                } else {
1294                        // Qt library translation unavailable for this language.
1295                        delete qtTranslator;
1296                        qtTranslator = NULL;
1297                }
1298        }
1299
1300        // Now let's load application translation.
1301        translator = new QTranslator(this);
1302        if (translator->load("tspsg_" + lng, PATH_L10N)) {
1303                // We have a translation in the localization directory.
1304                qApp->installTranslator(translator);
1305        } else if (translator->load("tspsg_" + lng, ":/l10n")) {
1306                // We have a translation "built-in" into application resources.
1307                qApp->installTranslator(translator);
1308        } else {
1309                delete translator;
1310                translator = NULL;
1311                if (!ad) {
1312                        settings->remove("Language");
1313                        QApplication::setOverrideCursor(QCursor(Qt::ArrowCursor));
1314                        QMessageBox::warning(isVisible() ? this : NULL, tr("Language Change"), tr("Unable to load the translation language.\nFalling back to autodetection."));
1315                        QApplication::restoreOverrideCursor();
1316                }
1317                return false;
1318        }
1319        return true;
1320}
1321
1322void MainWindow::loadStyleList()
1323{
1324        menuSettingsStyle->clear();
1325QStringList styles = QStyleFactory::keys();
1326        menuSettingsStyle->insertAction(NULL, actionSettingsStyleSystem);
1327        actionSettingsStyleSystem->setChecked(!settings->contains("Style"));
1328        menuSettingsStyle->addSeparator();
1329QAction *a;
1330        foreach (QString style, styles) {
1331                a = menuSettingsStyle->addAction(style);
1332                a->setData(false);
1333                a->setStatusTip(tr("Set application style to %1").arg(style));
1334                a->setCheckable(true);
1335                a->setActionGroup(groupSettingsStyleList);
1336                if ((style == settings->value("Style").toString())
1337                        || QString(QApplication::style()->metaObject()->className()).contains(QRegExp(QString("^Q?%1(Style)?$").arg(QRegExp::escape(style)), Qt::CaseInsensitive))) {
1338                        a->setChecked(true);
1339                }
1340        }
1341}
1342
1343void MainWindow::loadToolbarList()
1344{
1345        menuSettingsToolbars->clear();
1346#ifndef HANDHELD
1347        menuSettingsToolbars->insertAction(NULL, actionSettingsToolbarsConfigure);
1348        menuSettingsToolbars->addSeparator();
1349QList<QToolBar *> list = toolBarManager->toolBars();
1350        foreach (QToolBar *t, list) {
1351                menuSettingsToolbars->insertAction(NULL, t->toggleViewAction());
1352        }
1353#else // HANDHELD
1354        menuSettingsToolbars->insertAction(NULL, toolBarMain->toggleViewAction());
1355#endif // HANDHELD
1356}
1357
1358bool MainWindow::maybeSave()
1359{
1360        if (!isWindowModified())
1361                return true;
1362int res = QMessageBox::warning(this, tr("Unsaved Changes"), tr("Would you like to save changes in the current task?"), QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel);
1363        if (res == QMessageBox::Save)
1364                return actionFileSaveTriggered();
1365        else if (res == QMessageBox::Cancel)
1366                return false;
1367        else
1368                return true;
1369}
1370
1371void MainWindow::outputMatrix(QTextCursor &cur, const TMatrix &matrix)
1372{
1373int n = spinCities->value();
1374QTextTable *table = cur.insertTable(n, n, fmt_table);
1375
1376        for (int r = 0; r < n; r++) {
1377                for (int c = 0; c < n; c++) {
1378                        cur = table->cellAt(r, c).firstCursorPosition();
1379                        cur.setBlockFormat(fmt_cell);
1380                        cur.setBlockCharFormat(fmt_default);
1381                        if (matrix.at(r).at(c) == INFINITY)
1382                                cur.insertText(INFSTR);
1383                        else
1384                                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()));
1385                }
1386                QApplication::processEvents();
1387        }
1388        cur.movePosition(QTextCursor::End);
1389}
1390
1391void MainWindow::outputMatrix(QTextCursor &cur, const SStep &step)
1392{
1393int n = spinCities->value();
1394QTextTable *table = cur.insertTable(n, n, fmt_table);
1395
1396        for (int r = 0; r < n; r++) {
1397                for (int c = 0; c < n; c++) {
1398                        cur = table->cellAt(r, c).firstCursorPosition();
1399                        cur.setBlockFormat(fmt_cell);
1400                        if (step.matrix.at(r).at(c) == INFINITY)
1401                                cur.insertText(INFSTR, fmt_default);
1402                        else if ((r == step.candidate.nRow) && (c == step.candidate.nCol))
1403                                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);
1404                        else {
1405SStep::SCandidate cand;
1406                                cand.nRow = r;
1407                                cand.nCol = c;
1408                                if (step.alts.contains(cand))
1409                                        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);
1410                                else
1411                                        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);
1412                        }
1413                }
1414                QApplication::processEvents();
1415        }
1416
1417        cur.movePosition(QTextCursor::End);
1418}
1419
1420void MainWindow::retranslateUi(bool all)
1421{
1422        if (all)
1423                Ui_MainWindow::retranslateUi(this);
1424
1425        loadStyleList();
1426        loadToolbarList();
1427
1428#ifndef QT_NO_PRINTER
1429        actionFilePrintPreview->setText(tr("P&rint Preview..."));
1430#ifndef QT_NO_TOOLTIP
1431        actionFilePrintPreview->setToolTip(tr("Preview solution results"));
1432#endif // QT_NO_TOOLTIP
1433#ifndef QT_NO_STATUSTIP
1434        actionFilePrintPreview->setStatusTip(tr("Preview current solution results before printing"));
1435#endif // QT_NO_STATUSTIP
1436
1437        actionFilePrint->setText(tr("&Print..."));
1438#ifndef QT_NO_TOOLTIP
1439        actionFilePrint->setToolTip(tr("Print solution"));
1440#endif // QT_NO_TOOLTIP
1441#ifndef QT_NO_STATUSTIP
1442        actionFilePrint->setStatusTip(tr("Print current solution results"));
1443#endif // QT_NO_STATUSTIP
1444        actionFilePrint->setShortcut(tr("Ctrl+P"));
1445#endif // QT_NO_PRINTER
1446
1447#ifndef HANDHELD
1448        actionSettingsToolbarsConfigure->setText(tr("Configure..."));
1449#ifndef QT_NO_STATUSTIP
1450        actionSettingsToolbarsConfigure->setStatusTip(tr("Customize toolbars"));
1451#endif // QT_NO_STATUSTIP
1452#endif // HANDHELD
1453
1454        if (actionHelpCheck4Updates != NULL) {
1455                actionHelpCheck4Updates->setText(tr("Check for &Updates..."));
1456#ifndef QT_NO_STATUSTIP
1457                actionHelpCheck4Updates->setStatusTip(tr("Check for %1 updates").arg(QApplication::applicationName()));
1458#endif // QT_NO_STATUSTIP
1459        }
1460}
1461
1462bool MainWindow::saveTask() {
1463QStringList filters(tr("%1 Task File").arg("TSPSG") + " (*.tspt)");
1464        filters.append(tr("All Files") + " (*)");
1465QString file;
1466        if ((fileName == tr("Untitled") + ".tspt") && settings->value("SaveLastUsed", DEF_SAVE_LAST_USED).toBool()) {
1467                file = settings->value(OS"/LastUsed/TaskSavePath").toString();
1468                if (!file.isEmpty())
1469                        file.append("/");
1470                file.append(fileName);
1471        } else if (fileName.endsWith(".tspt", Qt::CaseInsensitive))
1472                file = fileName;
1473        else
1474                file = QFileInfo(fileName).path() + "/" + QFileInfo(fileName).completeBaseName() + ".tspt";
1475
1476QFileDialog::Options opts = settings->value("UseNativeDialogs", DEF_USE_NATIVE_DIALOGS).toBool() ? QFileDialog::Options() : QFileDialog::DontUseNativeDialog;
1477        file = QFileDialog::getSaveFileName(this, tr("Task Save"), file, filters.join(";;"), NULL, opts);
1478        if (file.isEmpty())
1479                return false;
1480        else if (settings->value("SaveLastUsed", DEF_SAVE_LAST_USED).toBool())
1481                settings->setValue(OS"/LastUsed/TaskSavePath", QFileInfo(file).path());
1482
1483        if (tspmodel->saveTask(file)) {
1484                setFileName(file);
1485                setWindowModified(false);
1486                return true;
1487        }
1488        return false;
1489}
1490
1491void MainWindow::setFileName(const QString &fileName)
1492{
1493        this->fileName = fileName;
1494        setWindowTitle(QString("%1[*] - %2").arg(QFileInfo(fileName).completeBaseName()).arg(QApplication::applicationName()));
1495}
1496
1497void MainWindow::setupUi()
1498{
1499        Ui_MainWindow::setupUi(this);
1500
1501        // File Menu
1502        actionFileNew->setIcon(GET_ICON("document-new"));
1503        actionFileOpen->setIcon(GET_ICON("document-open"));
1504        actionFileSave->setIcon(GET_ICON("document-save"));
1505#ifndef HANDHELD
1506        menuFileSaveAs->setIcon(GET_ICON("document-save-as"));
1507#endif
1508        actionFileExit->setIcon(GET_ICON("application-exit"));
1509        // Settings Menu
1510#ifndef HANDHELD
1511        menuSettingsLanguage->setIcon(GET_ICON("preferences-desktop-locale"));
1512#if QT_VERSION >= 0x040600
1513        actionSettingsLanguageEnglish->setIcon(QIcon::fromTheme("flag-gb", QIcon(":/images/icons/l10n/flag-gb.png")));
1514#else // QT_VERSION >= 0x040600
1515        actionSettingsLanguageEnglish->setIcon(QIcon(":/images/icons/l10n/flag-gb.png"));
1516#endif // QT_VERSION >= 0x040600
1517        menuSettingsStyle->setIcon(GET_ICON("preferences-desktop-theme"));
1518#endif // HANDHELD
1519        actionSettingsPreferences->setIcon(GET_ICON("preferences-system"));
1520        // Help Menu
1521#ifndef HANDHELD
1522        actionHelpContents->setIcon(GET_ICON("help-contents"));
1523        actionHelpContextual->setIcon(GET_ICON("help-contextual"));
1524        actionHelpAbout->setIcon(GET_ICON("help-about"));
1525        actionHelpAboutQt->setIcon(QIcon(":/images/icons/"ICON_SIZE"/qtlogo."ICON_FORMAT));
1526#endif
1527        // Buttons
1528        buttonRandom->setIcon(GET_ICON("roll"));
1529        buttonSolve->setIcon(GET_ICON("dialog-ok"));
1530        buttonSaveSolution->setIcon(GET_ICON("document-save-as"));
1531        buttonBackToTask->setIcon(GET_ICON("go-previous"));
1532
1533//      action->setIcon(GET_ICON(""));
1534
1535#if QT_VERSION >= 0x040600
1536        setToolButtonStyle(Qt::ToolButtonFollowStyle);
1537#endif
1538
1539#ifndef HANDHELD
1540QStatusBar *statusbar = new QStatusBar(this);
1541        statusbar->setObjectName("statusbar");
1542        setStatusBar(statusbar);
1543#endif // HANDHELD
1544
1545#ifdef Q_OS_WINCE_WM
1546        menuBar()->setDefaultAction(menuFile->menuAction());
1547
1548QScrollArea *scrollArea = new QScrollArea(this);
1549        scrollArea->setFrameShape(QFrame::NoFrame);
1550        scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
1551        scrollArea->setWidgetResizable(true);
1552        scrollArea->setWidget(tabWidget);
1553        setCentralWidget(scrollArea);
1554#else
1555        setCentralWidget(tabWidget);
1556#endif // Q_OS_WINCE_WM
1557
1558        //! \hack HACK: A little hack for toolbar icons to have a sane size.
1559#ifdef HANDHELD
1560        toolBarMain->setIconSize(QSize(logicalDpiX() / 4, logicalDpiY() / 4));
1561#endif // HANDHELD
1562QToolButton *tb = static_cast<QToolButton *>(toolBarMain->widgetForAction(actionFileSave));
1563        if (tb != NULL)  {
1564                tb->setMenu(menuFileSaveAs);
1565                tb->setPopupMode(QToolButton::MenuButtonPopup);
1566        }
1567
1568//      solutionText->document()->setDefaultFont(settings->value("Output/Font", QFont(DEF_FONT_FAMILY, DEF_FONT_SIZE)).value<QFont>());
1569        solutionText->setWordWrapMode(QTextOption::WordWrap);
1570
1571#ifndef QT_NO_PRINTER
1572        actionFilePrintPreview = new QAction(this);
1573        actionFilePrintPreview->setObjectName("actionFilePrintPreview");
1574        actionFilePrintPreview->setEnabled(false);
1575        actionFilePrintPreview->setIcon(GET_ICON("document-print-preview"));
1576
1577        actionFilePrint = new QAction(this);
1578        actionFilePrint->setObjectName("actionFilePrint");
1579        actionFilePrint->setEnabled(false);
1580        actionFilePrint->setIcon(GET_ICON("document-print"));
1581
1582        menuFile->insertAction(actionFileExit,actionFilePrintPreview);
1583        menuFile->insertAction(actionFileExit,actionFilePrint);
1584        menuFile->insertSeparator(actionFileExit);
1585
1586        toolBarMain->insertAction(actionSettingsPreferences, actionFilePrint);
1587#endif // QT_NO_PRINTER
1588
1589        groupSettingsLanguageList = new QActionGroup(this);
1590        actionSettingsLanguageEnglish->setData("en");
1591        actionSettingsLanguageEnglish->setActionGroup(groupSettingsLanguageList);
1592        loadLangList();
1593        actionSettingsLanguageAutodetect->setChecked(settings->value("Language", "").toString().isEmpty());
1594
1595        actionSettingsStyleSystem->setData(true);
1596        groupSettingsStyleList = new QActionGroup(this);
1597
1598#ifndef HANDHELD
1599        actionSettingsToolbarsConfigure = new QAction(this);
1600        actionSettingsToolbarsConfigure->setIcon(GET_ICON("configure-toolbars"));
1601#endif // HANDHELD
1602
1603        if (hasUpdater()) {
1604                actionHelpCheck4Updates = new QAction(this);
1605                actionHelpCheck4Updates->setIcon(GET_ICON("system-software-update"));
1606                actionHelpCheck4Updates->setEnabled(hasUpdater());
1607                menuHelp->insertAction(actionHelpAboutQt, actionHelpCheck4Updates);
1608                menuHelp->insertSeparator(actionHelpAboutQt);
1609        } else
1610                actionHelpCheck4Updates = NULL;
1611
1612        spinCities->setMaximum(MAX_NUM_CITIES);
1613
1614#ifndef HANDHELD
1615        toolBarManager = new QtToolBarManager;
1616        toolBarManager->setMainWindow(this);
1617QString cat = toolBarMain->windowTitle();
1618        toolBarManager->addToolBar(toolBarMain, cat);
1619#ifndef QT_NO_PRINTER
1620        toolBarManager->addAction(actionFilePrintPreview, cat);
1621#endif // QT_NO_PRINTER
1622        toolBarManager->addAction(actionHelpContents, cat);
1623        toolBarManager->addAction(actionHelpContextual, cat);
1624//      toolBarManager->addAction(action, cat);
1625        toolBarManager->restoreState(settings->value("MainWindow/Toolbars").toByteArray());
1626#else
1627        toolBarMain->setVisible(settings->value("MainWindow/ToolbarVisible", true).toBool());
1628#endif // HANDHELD
1629
1630        retranslateUi(false);
1631
1632#ifdef Q_OS_WIN32
1633        // Adding some eyecandy in Vista and 7 :-)
1634        if (QtWin::isCompositionEnabled() && settings->value("UseTranslucency", DEF_USE_TRANSLUCENCY).toBool())  {
1635                toggleTranclucency(true);
1636        }
1637#endif // Q_OS_WIN32
1638}
1639
1640void MainWindow::toggleSolutionActions(bool enable)
1641{
1642        buttonSaveSolution->setEnabled(enable);
1643        actionFileSaveAsSolution->setEnabled(enable);
1644        solutionText->setEnabled(enable);
1645#ifndef QT_NO_PRINTER
1646        actionFilePrint->setEnabled(enable);
1647        actionFilePrintPreview->setEnabled(enable);
1648#endif // QT_NO_PRINTER
1649}
1650
1651void MainWindow::toggleTranclucency(bool enable)
1652{
1653#ifdef Q_OS_WIN32
1654        toggleStyle(labelVariant, enable);
1655        toggleStyle(labelCities, enable);
1656        toggleStyle(statusBar(), enable);
1657        tabWidget->setDocumentMode(enable);
1658        QtWin::enableBlurBehindWindow(this, enable);
1659#else
1660        Q_UNUSED(enable);
1661#endif // Q_OS_WIN32
1662}
Note: See TracBrowser for help on using the repository browser.