source: tspsg/src/mainwindow.cpp @ 20e8115cee

0.1.4.170-beta2-bb10appveyorimgbotreadme
Last change on this file since 20e8115cee was 20e8115cee, checked in by Oleksii Serdiuk, 13 years ago

+ Added the ability to setup page-related options for printing (closed ticket #5).

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