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

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

+ Added more fonts to font-family css property on export.

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