source: tspsg/src/mainwindow.cpp @ 9cda6e0f5d

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

+ Added SStep::next that indicates what branch was selected for the next step.
+ Added "Show solution graph" option.
+ New CTSPSolver::getTotalSteps() method that returns a total number of steps in the current solution.

  • Moved SCandidate declaration into SStep declaration.
  • Moved everything in tspsolver.h and tspsolver.cpp into TSPSolver namespace.
  • Force CopyAction? on file drop or it will be deleted after dropping in Windows if MoveAction? was selected.
  • Property mode set to 100644
File size: 41.3 KB
Line 
1/*
2 *  TSPSG: TSP Solver and Generator
3 *  Copyright (C) 2007-2010 Lёppa <contacts[at]oleksii[dot]name>
4 *
5 *  $Id$
6 *  $URL$
7 *
8 *  This file is part of TSPSG.
9 *
10 *  TSPSG is free software: you can redistribute it and/or modify
11 *  it under the terms of the GNU General Public License as published by
12 *  the Free Software Foundation, either version 3 of the License, or
13 *  (at your option) any later version.
14 *
15 *  TSPSG is distributed in the hope that it will be useful,
16 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
17 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 *  GNU General Public License for more details.
19 *
20 *  You should have received a copy of the GNU General Public License
21 *  along with TSPSG.  If not, see <http://www.gnu.org/licenses/>.
22 */
23
24#include "mainwindow.h"
25
26/*!
27 * \brief Class constructor.
28 * \param parent Main Window parent widget.
29 *
30 *  Initializes Main Window and creates its layout based on target OS.
31 *  Loads TSPSG settings and opens a task file if it was specified as a commandline parameter.
32 */
33MainWindow::MainWindow(QWidget *parent)
34        : QMainWindow(parent)
35{
36        settings = new QSettings(QSettings::IniFormat, QSettings::UserScope, "TSPSG", "tspsg", this);
37
38        loadLanguage();
39        setupUi();
40        setAcceptDrops(true);
41
42        initDocStyleSheet();
43
44#ifndef QT_NO_PRINTER
45        printer = new QPrinter(QPrinter::HighResolution);
46#endif // QT_NO_PRINTER
47
48#ifdef Q_OS_WINCE_WM
49        currentGeometry = QApplication::desktop()->availableGeometry(0);
50        // We need to react to SIP show/hide and resize the window appropriately
51        connect(QApplication::desktop(), SIGNAL(workAreaResized(int)), SLOT(desktopResized(int)));
52#endif // Q_OS_WINCE_WM
53        connect(actionFileNew,SIGNAL(triggered()),this,SLOT(actionFileNewTriggered()));
54        connect(actionFileOpen,SIGNAL(triggered()),this,SLOT(actionFileOpenTriggered()));
55        connect(actionFileSave,SIGNAL(triggered()),this,SLOT(actionFileSaveTriggered()));
56        connect(actionFileSaveAsTask,SIGNAL(triggered()),this,SLOT(actionFileSaveAsTaskTriggered()));
57        connect(actionFileSaveAsSolution,SIGNAL(triggered()),this,SLOT(actionFileSaveAsSolutionTriggered()));
58#ifndef QT_NO_PRINTER
59        connect(actionFilePrintPreview,SIGNAL(triggered()),this,SLOT(actionFilePrintPreviewTriggered()));
60        connect(actionFilePrint,SIGNAL(triggered()),this,SLOT(actionFilePrintTriggered()));
61#endif // QT_NO_PRINTER
62        connect(actionSettingsPreferences,SIGNAL(triggered()),this,SLOT(actionSettingsPreferencesTriggered()));
63#ifdef Q_OS_WIN32
64        connect(actionHelpCheck4Updates, SIGNAL(triggered()), SLOT(actionHelpCheck4UpdatesTriggered()));
65#endif // Q_OS_WIN32
66        connect(actionSettingsLanguageAutodetect,SIGNAL(triggered(bool)),this,SLOT(actionSettingsLanguageAutodetectTriggered(bool)));
67        connect(groupSettingsLanguageList,SIGNAL(triggered(QAction *)),this,SLOT(groupSettingsLanguageListTriggered(QAction *)));
68        connect(actionHelpAboutQt,SIGNAL(triggered()),qApp,SLOT(aboutQt()));
69        connect(actionHelpAbout,SIGNAL(triggered()),this,SLOT(actionHelpAboutTriggered()));
70
71        connect(buttonSolve,SIGNAL(clicked()),this,SLOT(buttonSolveClicked()));
72        connect(buttonRandom,SIGNAL(clicked()),this,SLOT(buttonRandomClicked()));
73        connect(buttonBackToTask,SIGNAL(clicked()),this,SLOT(buttonBackToTaskClicked()));
74        connect(spinCities,SIGNAL(valueChanged(int)),this,SLOT(spinCitiesValueChanged(int)));
75
76#ifndef HANDHELD
77        // Centering main window
78QRect rect = geometry();
79        rect.moveCenter(QApplication::desktop()->availableGeometry(this).center());
80        setGeometry(rect);
81        if (settings->value("SavePos", DEF_SAVEPOS).toBool()) {
82                // Loading of saved window state
83                settings->beginGroup("MainWindow");
84                restoreGeometry(settings->value("Geometry").toByteArray());
85                restoreState(settings->value("State").toByteArray());
86                settings->endGroup();
87        }
88#else
89        setWindowState(Qt::WindowMaximized);
90#endif // HANDHELD
91
92        tspmodel = new CTSPModel(this);
93        taskView->setModel(tspmodel);
94        connect(tspmodel,SIGNAL(numCitiesChanged(int)),this,SLOT(numCitiesChanged(int)));
95        connect(tspmodel,SIGNAL(dataChanged(const QModelIndex &, const QModelIndex &)),this,SLOT(dataChanged(const QModelIndex &, const QModelIndex &)));
96        connect(tspmodel,SIGNAL(layoutChanged()),this,SLOT(dataChanged()));
97        if ((QCoreApplication::arguments().count() > 1) && (tspmodel->loadTask(QCoreApplication::arguments().at(1))))
98                setFileName(QCoreApplication::arguments().at(1));
99        else {
100                setFileName();
101                spinCities->setValue(settings->value("NumCities",DEF_NUM_CITIES).toInt());
102                spinCitiesValueChanged(spinCities->value());
103        }
104        setWindowModified(false);
105}
106
107MainWindow::~MainWindow()
108{
109#ifndef QT_NO_PRINTER
110        delete printer;
111#endif
112}
113
114/* Privates **********************************************************/
115
116void MainWindow::actionFileNewTriggered()
117{
118        if (!maybeSave())
119                return;
120        QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
121        tspmodel->clear();
122        setFileName();
123        setWindowModified(false);
124        tabWidget->setCurrentIndex(0);
125        solutionText->clear();
126        toggleSolutionActions(false);
127        QApplication::restoreOverrideCursor();
128}
129
130void MainWindow::actionFileOpenTriggered()
131{
132        if (!maybeSave())
133                return;
134
135QStringList filters(tr("All Supported Formats") + " (*.tspt *.zkt)");
136        filters.append(tr("%1 Task Files").arg("TSPSG") + " (*.tspt)");
137        filters.append(tr("%1 Task Files").arg("ZKomModRd") + " (*.zkt)");
138        filters.append(tr("All Files") + " (*)");
139
140QString file = QFileInfo(fileName).canonicalPath();
141QFileDialog::Options opts = settings->value("UseNativeDialogs", DEF_USE_NATIVE_DIALOGS).toBool() ? QFileDialog::Options() : QFileDialog::DontUseNativeDialog;
142        file = QFileDialog::getOpenFileName(this, tr("Task Load"), file, filters.join(";;"), NULL, opts);
143        if (file.isEmpty() || !QFileInfo(file).isFile())
144                return;
145        if (!tspmodel->loadTask(file))
146                return;
147        setFileName(file);
148        tabWidget->setCurrentIndex(0);
149        setWindowModified(false);
150        solutionText->clear();
151        toggleSolutionActions(false);
152}
153
154bool MainWindow::actionFileSaveTriggered()
155{
156        if ((fileName == tr("Untitled") + ".tspt") || (!fileName.endsWith(".tspt", Qt::CaseInsensitive)))
157                return saveTask();
158        else
159                if (tspmodel->saveTask(fileName)) {
160                        setWindowModified(false);
161                        return true;
162                } else
163                        return false;
164}
165
166void MainWindow::actionFileSaveAsTaskTriggered()
167{
168        saveTask();
169}
170
171void MainWindow::actionFileSaveAsSolutionTriggered()
172{
173static QString selectedFile;
174        if (selectedFile.isEmpty())
175                selectedFile = QFileInfo(fileName).canonicalPath();
176        else
177                selectedFile = QFileInfo(selectedFile).canonicalPath();
178        if (!selectedFile.isEmpty())
179                selectedFile += "/";
180        if (fileName == tr("Untitled") + ".tspt") {
181#ifndef QT_NO_PRINTER
182                selectedFile += "solution.pdf";
183#else
184                selectedFile += "solution.html";
185#endif // QT_NO_PRINTER
186        } else {
187#ifndef QT_NO_PRINTER
188                selectedFile += QFileInfo(fileName).completeBaseName() + ".pdf";
189#else
190                selectedFile += QFileInfo(fileName).completeBaseName() + ".html";
191#endif // QT_NO_PRINTER
192        }
193
194QStringList filters;
195#ifndef QT_NO_PRINTER
196        filters.append(tr("PDF Files") + " (*.pdf)");
197#endif
198        filters.append(tr("HTML Files") + " (*.html *.htm)");
199#if QT_VERSION >= 0x040500
200        filters.append(tr("OpenDocument Files") + " (*.odt)");
201#endif // QT_VERSION >= 0x040500
202        filters.append(tr("All Files") + " (*)");
203
204QFileDialog::Options opts(settings->value("UseNativeDialogs", DEF_USE_NATIVE_DIALOGS).toBool() ? QFileDialog::Options() : QFileDialog::DontUseNativeDialog);
205QString file = QFileDialog::getSaveFileName(this, QString(), selectedFile, filters.join(";;"), NULL, opts);
206        if (file.isEmpty())
207                return;
208        selectedFile = file;
209        QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
210#ifndef QT_NO_PRINTER
211        if (selectedFile.endsWith(".pdf",Qt::CaseInsensitive)) {
212QPrinter printer(QPrinter::HighResolution);
213                printer.setOutputFormat(QPrinter::PdfFormat);
214                printer.setOutputFileName(selectedFile);
215                solutionText->document()->print(&printer);
216                QApplication::restoreOverrideCursor();
217                return;
218        }
219#endif
220#if QT_VERSION >= 0x040500
221QTextDocumentWriter dw(selectedFile);
222        if (!(selectedFile.endsWith(".htm",Qt::CaseInsensitive) || selectedFile.endsWith(".html",Qt::CaseInsensitive) || selectedFile.endsWith(".odt",Qt::CaseInsensitive) || selectedFile.endsWith(".txt",Qt::CaseInsensitive)))
223                dw.setFormat("plaintext");
224        if (!dw.write(solutionText->document()))
225                QMessageBox::critical(this, tr("Solution Save"), tr("Unable to save the solution.\nError: %1").arg(dw.device()->errorString()));
226#else // QT_VERSION >= 0x040500
227        // Qt < 4.5 has no QTextDocumentWriter class
228QFile file(selectedFile);
229        if (!file.open(QFile::WriteOnly)) {
230                QApplication::restoreOverrideCursor();
231                QMessageBox::critical(this, tr("Solution Save"), tr("Unable to save the solution.\nError: %1").arg(file->errorString()));
232                return;
233        }
234QTextStream ts(&file);
235        ts.setCodec(QTextCodec::codecForName("UTF-8"));
236        ts << solutionText->document()->toHtml("UTF-8");
237        file.close();
238#endif // QT_VERSION >= 0x040500
239        QApplication::restoreOverrideCursor();
240}
241
242#ifndef QT_NO_PRINTER
243void MainWindow::actionFilePrintPreviewTriggered()
244{
245QPrintPreviewDialog ppd(printer, this);
246        connect(&ppd,SIGNAL(paintRequested(QPrinter *)),SLOT(printPreview(QPrinter *)));
247        ppd.exec();
248}
249
250void MainWindow::actionFilePrintTriggered()
251{
252QPrintDialog pd(printer,this);
253#if QT_VERSION >= 0x040500
254        // No such methods in Qt < 4.5
255        pd.setOption(QAbstractPrintDialog::PrintSelection,false);
256        pd.setOption(QAbstractPrintDialog::PrintPageRange,false);
257#endif
258        if (pd.exec() != QDialog::Accepted)
259                return;
260        QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
261        solutionText->document()->print(printer);
262        QApplication::restoreOverrideCursor();
263}
264#endif // QT_NO_PRINTER
265
266void MainWindow::actionSettingsPreferencesTriggered()
267{
268SettingsDialog sd(this);
269        if (sd.exec() != QDialog::Accepted)
270                return;
271        if (sd.colorChanged() || sd.fontChanged()) {
272                if (!solutionText->document()->isEmpty() && sd.colorChanged())
273                        QMessageBox::information(this, tr("Settings Changed"), tr("You have changed color settings.\nThey will be applied to the next solution output."));
274                initDocStyleSheet();
275        }
276        if (sd.translucencyChanged() != 0)
277                toggleTranclucency(sd.translucencyChanged() == 1);
278}
279
280void MainWindow::actionSettingsLanguageAutodetectTriggered(bool checked)
281{
282        if (checked) {
283                settings->remove("Language");
284                QMessageBox::information(this, tr("Language change"), tr("Language will be autodetected on the next application start."));
285        } else
286                settings->setValue("Language", groupSettingsLanguageList->checkedAction()->data().toString());
287}
288
289void MainWindow::groupSettingsLanguageListTriggered(QAction *action)
290{
291        if (actionSettingsLanguageAutodetect->isChecked()) {
292                // We have language autodetection. It needs to be disabled to change language.
293                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) {
294                        actionSettingsLanguageAutodetect->trigger();
295                } else
296                        return;
297        }
298bool untitled = (fileName == tr("Untitled") + ".tspt");
299        if (loadLanguage(action->data().toString())) {
300                QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
301                settings->setValue("Language",action->data().toString());
302                retranslateUi();
303                if (untitled)
304                        setFileName();
305#ifdef Q_OS_WIN32
306                if (QtWin::isCompositionEnabled() && settings->value("UseTranslucency", DEF_USE_TRANSLUCENCY).toBool())  {
307                        toggleStyle(labelVariant, true);
308                        toggleStyle(labelCities, true);
309                }
310#endif
311                QApplication::restoreOverrideCursor();
312                if (!solutionText->document()->isEmpty())
313                        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."));
314        }
315}
316
317#ifdef Q_OS_WIN32
318void MainWindow::actionHelpCheck4UpdatesTriggered()
319{
320        if (!hasUpdater()) {
321                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."));
322                return;
323        }
324
325        QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
326        QProcess::execute("updater/Update.exe -name=\"TSPSG: TSP Solver and Generator\" -check=\"freeupdate\"");
327        QApplication::restoreOverrideCursor();
328}
329#endif // Q_OS_WIN32
330
331void MainWindow::actionHelpAboutTriggered()
332{
333QString title;
334#ifdef HANDHELD
335        title += QString("<b>TSPSG<br>TSP Solver and Generator</b><br>");
336#else
337        title += QString("<b>TSPSG: TSP Solver and Generator</b><br>");
338#endif // HANDHELD
339        title += QString("%1: <b>%2</b><br>").arg(tr("Version"), QApplication::applicationVersion());
340#ifndef HANDHELD
341        title += QString("<b>&copy; 2007-%1 <a href=\"http://%2/\">%3</a></b><br>").arg(QDate::currentDate().toString("yyyy"), QApplication::organizationDomain(), QApplication::organizationName());
342        title += QString("<b><a href=\"http://tspsg.sourceforge.net/\">http://tspsg.sourceforge.net/</a></b>");
343#else
344        title += QString("<b><a href=\"http://tspsg.sourceforge.net/\">http://tspsg.sf.net/</a></b>");
345#endif // Q_OS_WINCE_WM && Q_OS_SYMBIAN
346
347QString about;
348        about += QString("%1: <b>%2</b><br>").arg(tr("Target OS (ARCH)"), OS);
349#ifndef STATIC_BUILD
350        about += QString("%1 (%2):<br>").arg(tr("Qt library"), tr("shared"));
351        about += QString("&nbsp;&nbsp;&nbsp;&nbsp;%1: <b>%2</b><br>").arg(tr("Build time"), QT_VERSION_STR);
352        about += QString("&nbsp;&nbsp;&nbsp;&nbsp;%1: <b>%2</b><br>").arg(tr("Runtime"), qVersion());
353#else
354        about += QString("%1: <b>%2</b> (%3)<br>").arg(tr("Qt library"), QT_VERSION_STR, tr("static"));
355#endif // STATIC_BUILD
356        about += tr("Buid <b>%1</b>, built on <b>%2</b> at <b>%3</b>").arg(BUILD_NUMBER).arg(__DATE__).arg(__TIME__) + "<br>";
357        about += QString("%1: <b>%2</b><br>").arg(tr("Algorithm"), CTSPSolver::getVersionId());
358        about += "<br>";
359        about += tr("TSPSG is free software: you can redistribute it and/or modify it<br>"
360                "under the terms of the GNU General Public License as published<br>"
361                "by the Free Software Foundation, either version 3 of the License,<br>"
362                "or (at your option) any later version.<br>"
363                "<br>"
364                "TSPSG is distributed in the hope that it will be useful, but<br>"
365                "WITHOUT ANY WARRANTY; without even the implied warranty of<br>"
366                "MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the<br>"
367                "GNU General Public License for more details.<br>"
368                "<br>"
369                "You should have received a copy of the GNU General Public License<br>"
370                "along with TSPSG.  If not, see <a href=\"http://www.gnu.org/licenses/\">http://www.gnu.org/licenses/</a>.");
371
372QDialog *dlg = new QDialog(this);
373QLabel *lblIcon = new QLabel(dlg),
374        *lblTitle = new QLabel(dlg),
375        *lblTranslated = new QLabel(dlg);
376#ifdef HANDHELD
377QLabel *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);
378#endif // HANDHELD
379QTextBrowser *txtAbout = new QTextBrowser(dlg);
380QVBoxLayout *vb = new QVBoxLayout();
381QHBoxLayout *hb1 = new QHBoxLayout(),
382        *hb2 = new QHBoxLayout();
383QDialogButtonBox *bb = new QDialogButtonBox(QDialogButtonBox::Ok, Qt::Horizontal, dlg);
384
385        lblTitle->setOpenExternalLinks(true);
386        lblTitle->setText(title);
387        lblTitle->setAlignment(Qt::AlignTop);
388        lblTitle->setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Preferred);
389#ifndef HANDHELD
390        lblTitle->setStyleSheet(QString("QLabel {background-color: %1; border-color: %2; border-width: 1px; border-style: solid; border-radius: 3px;}").arg(palette().window().color().name(), palette().shadow().color().name()));
391#endif // HANDHELD
392
393        lblIcon->setPixmap(QPixmap(":/images/tspsg.png").scaledToHeight(lblTitle->sizeHint().height(), Qt::SmoothTransformation));
394        lblIcon->setAlignment(Qt::AlignVCenter);
395#ifndef HANDHELD
396        lblIcon->setStyleSheet(QString("QLabel {background-color: %1; border-color: %2; border-width: 1px; border-style: solid; border-radius: 3px;}").arg(palette().window().color().name(), palette().windowText().color().name()));
397#endif // HANDHELD
398
399        hb1->addWidget(lblIcon);
400        hb1->addWidget(lblTitle);
401
402        txtAbout->setWordWrapMode(QTextOption::NoWrap);
403        txtAbout->setOpenExternalLinks(true);
404        txtAbout->setHtml(about);
405        txtAbout->moveCursor(QTextCursor::Start);
406#ifndef HANDHELD
407        txtAbout->setStyleSheet(QString("QTextBrowser {border-color: %1; border-width: 1px; border-style: solid; border-radius: 3px;}").arg(palette().shadow().color().name()));
408#endif // HANDHELD
409
410        bb->button(QDialogButtonBox::Ok)->setCursor(QCursor(Qt::PointingHandCursor));
411
412        lblTranslated->setText(QApplication::translate("--------", "TRANSLATION", "Please, provide translator credits here."));
413        if (lblTranslated->text() == "TRANSLATION")
414                lblTranslated->hide();
415        else {
416                lblTranslated->setOpenExternalLinks(true);
417#ifndef HANDHELD
418                lblTranslated->setStyleSheet(QString("QLabel {background-color: %1; border-color: %2; border-width: 1px; border-style: solid; border-radius: 3px;}").arg(palette().window().color().name(), palette().shadow().color().name()));
419#endif // HANDHELD
420                hb2->addWidget(lblTranslated);
421        }
422
423        hb2->addWidget(bb);
424
425#ifdef Q_OS_WINCE_WM
426        vb->setMargin(3);
427#endif // Q_OS_WINCE_WM
428        vb->addLayout(hb1);
429#ifdef HANDHELD
430        vb->addWidget(lblSubTitle);
431#endif // HANDHELD
432        vb->addWidget(txtAbout);
433        vb->addLayout(hb2);
434
435        dlg->setWindowFlags(Qt::Dialog | Qt::CustomizeWindowHint | Qt::WindowTitleHint | Qt::WindowCloseButtonHint);
436        dlg->setWindowTitle(tr("About TSPSG"));
437        dlg->setLayout(vb);
438
439        connect(bb, SIGNAL(accepted()), dlg, SLOT(accept()));
440
441#ifdef Q_OS_WIN32
442        // Adding some eyecandy in Vista and 7 :-)
443        if (QtWin::isCompositionEnabled())  {
444                QtWin::enableBlurBehindWindow(dlg, true);
445        }
446#endif // Q_OS_WIN32
447
448        dlg->resize(450, 350);
449
450        dlg->exec();
451
452        delete dlg;
453}
454
455void MainWindow::buttonBackToTaskClicked()
456{
457        tabWidget->setCurrentIndex(0);
458}
459
460void MainWindow::buttonRandomClicked()
461{
462        QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
463        tspmodel->randomize();
464        QApplication::restoreOverrideCursor();
465}
466
467void MainWindow::buttonSolveClicked()
468{
469TMatrix matrix;
470QList<double> row;
471int n = spinCities->value();
472bool ok;
473        for (int r = 0; r < n; r++) {
474                row.clear();
475                for (int c = 0; c < n; c++) {
476                        row.append(tspmodel->index(r,c).data(Qt::UserRole).toDouble(&ok));
477                        if (!ok) {
478                                QMessageBox::critical(this, tr("Data error"), tr("Error in cell [Row %1; Column %2]: Invalid data format.").arg(r + 1).arg(c + 1));
479                                return;
480                        }
481                }
482                matrix.append(row);
483        }
484
485QProgressDialog pd(this);
486QProgressBar *pb = new QProgressBar(&pd);
487        pb->setAlignment(Qt::AlignCenter);
488        pb->setFormat(tr("%v of %1 parts found").arg(n));
489        pd.setBar(pb);
490        pd.setMaximum(n);
491        pd.setAutoReset(false);
492        pd.setLabelText(tr("Calculating optimal route..."));
493        pd.setWindowTitle(tr("Solution Progress"));
494        pd.setWindowModality(Qt::ApplicationModal);
495        pd.setWindowFlags(Qt::Dialog | Qt::CustomizeWindowHint | Qt::WindowTitleHint);
496        pd.show();
497
498CTSPSolver solver;
499        connect(&solver, SIGNAL(routePartFound(int)), &pd, SLOT(setValue(int)));
500        connect(&pd, SIGNAL(canceled()), &solver, SLOT(cancel()));
501SStep *root = solver.solve(n, matrix);
502        disconnect(&solver, SIGNAL(routePartFound(int)), &pd, SLOT(setValue(int)));
503        disconnect(&pd, SIGNAL(canceled()), &solver, SLOT(cancel()));
504        if (!root) {
505                pd.reset();
506                if (!solver.wasCanceled())
507                        QMessageBox::warning(this, tr("Solution Result"), tr("Unable to find a solution.\nMaybe, this task has no solution."));
508                return;
509        }
510        pb->setFormat(tr("Generating header"));
511        pd.setLabelText(tr("Generating solution output..."));
512        pd.setMaximum(solver.getTotalSteps() + 1);
513        pd.setValue(0);
514
515        solutionText->clear();
516        solutionText->setDocumentTitle(tr("Solution of Variant #%1 Task").arg(spinVariant->value()));
517
518QPainter pic;
519        if (settings->value("Output/ShowGraph", DEF_SHOW_GRAPH).toBool()) {
520                pic.begin(&graph);
521                pic.setRenderHint(QPainter::Antialiasing);
522        }
523
524QTextDocument *doc = solutionText->document();
525QTextCursor cur(doc);
526
527        cur.beginEditBlock();
528        cur.setBlockFormat(fmt_paragraph);
529        cur.insertText(tr("Variant #%1 Task").arg(spinVariant->value()), fmt_default);
530        cur.insertBlock(fmt_paragraph);
531        cur.insertText(tr("Task:"));
532        outputMatrix(cur, matrix);
533        if (settings->value("Output/ShowGraph", DEF_SHOW_GRAPH).toBool())
534                drawNode(pic, 0);
535        cur.insertHtml("<hr>");
536        cur.insertBlock(fmt_paragraph);
537int imgpos = cur.position();
538        cur.insertText(tr("Variant #%1 Solution").arg(spinVariant->value()), fmt_default);
539        cur.endEditBlock();
540
541SStep *step = root;
542int c = n = 1;
543        pb->setFormat(tr("Generating step %v"));
544        while ((step->next != SStep::NoNextStep) && (c < spinCities->value())) {
545                if (pd.wasCanceled()) {
546                        pd.setLabelText(tr("Cleaning up..."));
547                        pd.setMaximum(0);
548                        pd.setCancelButton(NULL);
549                        pd.show();
550                        QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
551                        solver.cleanup(true);
552                        solutionText->clear();
553                        toggleSolutionActions(false);
554                        return;
555                }
556                pd.setValue(n);
557
558                cur.beginEditBlock();
559                cur.insertBlock(fmt_paragraph);
560                cur.insertText(tr("Step #%1").arg(n));
561                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())))) {
562                        outputMatrix(cur, *step);
563                }
564                cur.insertBlock(fmt_paragraph);
565                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);
566                if (!step->alts.empty()) {
567                        SStep::SCandidate cand;
568                        QString alts;
569                        foreach(cand, step->alts) {
570                                if (!alts.isEmpty())
571                                        alts += ", ";
572                                alts += tr("(%1;%2)").arg(cand.nRow + 1).arg(cand.nCol + 1);
573                        }
574                        cur.insertBlock(fmt_paragraph);
575                        cur.insertText(tr("%n alternate candidate(s) for branching: %1.", "", step->alts.count()).arg(alts), fmt_altlist);
576                }
577                cur.insertBlock(fmt_paragraph);
578                cur.insertText(" ", fmt_default);
579                cur.endEditBlock();
580
581                if (settings->value("Output/ShowGraph", DEF_SHOW_GRAPH).toBool()) {
582                        if (step->prNode != NULL)
583                                drawNode(pic, n, false, step->prNode);
584                        if (step->plNode != NULL)
585                                drawNode(pic, n, true, step->plNode);
586                }
587                n++;
588
589                if (step->next == SStep::RightBranch) {
590                        c++;
591                        step = step->prNode;
592                } else if (step->next == SStep::LeftBranch) {
593                        step = step->plNode;
594                } else
595                        break;
596        }
597        pb->setFormat(tr("Generating footer"));
598        pd.setValue(n);
599
600        cur.beginEditBlock();
601        cur.insertBlock(fmt_paragraph);
602        if (solver.isOptimal())
603                cur.insertText(tr("Optimal path:"));
604        else
605                cur.insertText(tr("Resulting path:"));
606
607        cur.insertBlock(fmt_paragraph);
608        cur.insertText("  " + solver.getSortedPath());
609
610        cur.insertBlock(fmt_paragraph);
611        if (isInteger(step->price))
612                cur.insertHtml("<p>" + tr("The price is <b>%n</b> unit(s).", "", qRound(step->price)) + "</p>");
613        else
614                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>");
615        if (!solver.isOptimal()) {
616                cur.insertBlock(fmt_paragraph);
617                cur.insertText(" ");
618                cur.insertBlock(fmt_paragraph);
619                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>");
620        }
621        cur.endEditBlock();
622
623        if (settings->value("Output/ShowGraph", DEF_SHOW_GRAPH).toBool()) {
624                pic.end();
625
626QImage i(graph.width() + 2, graph.height() + 2, QImage::Format_ARGB32);
627                i.fill(0);
628                pic.begin(&i);
629                pic.drawPicture(1, 1, graph);
630                pic.end();
631                doc->addResource(QTextDocument::ImageResource, QUrl("tspsg://graph.pic"), i);
632
633QTextImageFormat img;
634                img.setName("tspsg://graph.pic");
635
636                cur.setPosition(imgpos);
637                cur.insertImage(img, QTextFrameFormat::FloatRight);
638        }
639
640        if (settings->value("Output/ScrollToEnd", DEF_SCROLL_TO_END).toBool()) {
641                // Scrolling to the end of the text.
642                solutionText->moveCursor(QTextCursor::End);
643        } else
644                solutionText->moveCursor(QTextCursor::Start);
645
646        pd.setLabelText(tr("Cleaning up..."));
647        pd.setMaximum(0);
648        pd.setCancelButton(NULL);
649        QApplication::processEvents(QEventLoop::ExcludeUserInputEvents);
650        solver.cleanup(true);
651        toggleSolutionActions();
652        tabWidget->setCurrentIndex(1);
653}
654
655void MainWindow::dataChanged()
656{
657        setWindowModified(true);
658}
659
660void MainWindow::dataChanged(const QModelIndex &tl, const QModelIndex &br)
661{
662        setWindowModified(true);
663        if (settings->value("Autosize", DEF_AUTOSIZE).toBool()) {
664                for (int k = tl.row(); k <= br.row(); k++)
665                        taskView->resizeRowToContents(k);
666                for (int k = tl.column(); k <= br.column(); k++)
667                        taskView->resizeColumnToContents(k);
668        }
669}
670
671#ifdef Q_OS_WINCE_WM
672void MainWindow::changeEvent(QEvent *ev)
673{
674        if ((ev->type() == QEvent::ActivationChange) && isActiveWindow())
675                desktopResized(0);
676
677        QWidget::changeEvent(ev);
678}
679
680void MainWindow::desktopResized(int screen)
681{
682        if ((screen != 0) || !isActiveWindow())
683                return;
684
685QRect availableGeometry = QApplication::desktop()->availableGeometry(0);
686        if (currentGeometry != availableGeometry) {
687                QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
688                /*!
689                 * \hack HACK: This hack checks whether \link QDesktopWidget::availableGeometry() availableGeometry()\endlink's \c top + \c hegiht = \link QDesktopWidget::screenGeometry() screenGeometry()\endlink's \c height.
690                 *  If \c true, the window gets maximized. If we used \c setGeometry() in this case, the bottom of the
691                 *  window would end up being behind the soft buttons. Is this a bug in Qt or Windows Mobile?
692                 */
693                if ((availableGeometry.top() + availableGeometry.height()) == QApplication::desktop()->screenGeometry().height()) {
694                        setWindowState(windowState() | Qt::WindowMaximized);
695                } else {
696                        if (windowState() & Qt::WindowMaximized)
697                                setWindowState(windowState() ^ Qt::WindowMaximized);
698                        setGeometry(availableGeometry);
699                }
700                currentGeometry = availableGeometry;
701                QApplication::restoreOverrideCursor();
702        }
703}
704#endif // Q_OS_WINCE_WM
705
706void MainWindow::numCitiesChanged(int nCities)
707{
708        blockSignals(true);
709        spinCities->setValue(nCities);
710        blockSignals(false);
711}
712
713#ifndef QT_NO_PRINTER
714void MainWindow::printPreview(QPrinter *printer)
715{
716        solutionText->print(printer);
717}
718#endif // QT_NO_PRINTER
719
720void MainWindow::spinCitiesValueChanged(int n)
721{
722        QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
723int count = tspmodel->numCities();
724        tspmodel->setNumCities(n);
725        if ((n > count) && settings->value("Autosize", DEF_AUTOSIZE).toBool())
726                for (int k = count; k < n; k++) {
727                        taskView->resizeColumnToContents(k);
728                        taskView->resizeRowToContents(k);
729                }
730        QApplication::restoreOverrideCursor();
731}
732
733void MainWindow::closeEvent(QCloseEvent *ev)
734{
735        if (!maybeSave()) {
736                ev->ignore();
737                return;
738        }
739        if (!settings->value("SettingsReset", false).toBool()) {
740                settings->setValue("NumCities", spinCities->value());
741
742                // Saving Main Window state
743                if (settings->value("SavePos", DEF_SAVEPOS).toBool()) {
744                        settings->beginGroup("MainWindow");
745#ifndef HANDHELD
746                        settings->setValue("Geometry", saveGeometry());
747#endif // HANDHELD
748                        settings->setValue("State", saveState());
749                        settings->endGroup();
750                }
751        } else {
752                settings->remove("SettingsReset");
753        }
754
755        QMainWindow::closeEvent(ev);
756}
757
758void MainWindow::dragEnterEvent(QDragEnterEvent *ev)
759{
760        if (ev->mimeData()->hasUrls() && (ev->mimeData()->urls().count() == 1)) {
761QFileInfo fi(ev->mimeData()->urls().first().toLocalFile());
762                if ((fi.suffix() == "tspt") || (fi.suffix() == "zkt"))
763                        ev->acceptProposedAction();
764        }
765}
766
767void MainWindow::drawNode(QPainter &pic, int nstep, bool left, SStep *step)
768{
769const int r = 35;
770qreal x, y;
771        if (step != NULL)
772                x = left ? r : r * 3.5;
773        else
774                x = r * 2.25;
775        y = r * (3 * nstep + 1);
776
777        pic.drawEllipse(QPointF(x, y), r, r);
778
779        if (step != NULL) {
780QFont font;
781                if (left) {
782                        font = pic.font();
783                        font.setStrikeOut(true);
784                        pic.setFont(font);
785                }
786                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");
787                if (left) {
788                        font.setStrikeOut(false);
789                        pic.setFont(font);
790                }
791                pic.setBackgroundMode(Qt::OpaqueMode);
792                if (step->price != INFINITY) {
793                        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()));
794                } else {
795                        pic.drawText(QRectF(x - r, y - r, r * 2, r * 2), Qt::AlignCenter, "\n"INFSTR);
796                }
797                pic.setBackgroundMode(Qt::TransparentMode);
798        } else {
799                pic.drawText(QRectF(x - r, y - r, r * 2, r * 2), Qt::AlignCenter, tr("Root"));
800        }
801
802        if (nstep == 1) {
803                pic.drawLine(QPointF(x, y - r), QPointF(r * 2.25, y - 2 * r));
804        } else if (nstep > 1) {
805                pic.drawLine(QPointF(x, y - r), QPointF((step->pNode->next == SStep::RightBranch) ? r * 3.5 : r, y - 2 * r));
806        }
807
808}
809
810void MainWindow::dropEvent(QDropEvent *ev)
811{
812        if (maybeSave() && tspmodel->loadTask(ev->mimeData()->urls().first().toLocalFile())) {
813                setFileName(ev->mimeData()->urls().first().toLocalFile());
814                tabWidget->setCurrentIndex(0);
815                setWindowModified(false);
816                solutionText->clear();
817                toggleSolutionActions(false);
818
819                ev->setDropAction(Qt::CopyAction);
820                ev->accept();
821        }
822}
823
824bool MainWindow::hasUpdater() const
825{
826#ifdef Q_OS_WIN32
827        return QFile::exists("updater/Update.exe");
828#else // Q_OS_WIN32
829        return false;
830#endif // Q_OS_WIN32
831}
832
833void MainWindow::initDocStyleSheet()
834{
835        solutionText->document()->setDefaultFont(settings->value("Output/Font", QFont(DEF_FONT_FAMILY, DEF_FONT_SIZE)).value<QFont>());
836
837        fmt_paragraph.setTopMargin(0);
838        fmt_paragraph.setRightMargin(10);
839        fmt_paragraph.setBottomMargin(0);
840        fmt_paragraph.setLeftMargin(10);
841
842        fmt_table.setTopMargin(5);
843        fmt_table.setRightMargin(10);
844        fmt_table.setBottomMargin(5);
845        fmt_table.setLeftMargin(10);
846        fmt_table.setBorder(0);
847        fmt_table.setBorderStyle(QTextFrameFormat::BorderStyle_None);
848        fmt_table.setCellSpacing(5);
849
850        fmt_cell.setAlignment(Qt::AlignHCenter);
851
852QColor color = settings->value("Output/Colors/Text", DEF_TEXT_COLOR).value<QColor>();
853QColor hilight;
854        if (color.value() < 192)
855                hilight.setHsv(color.hue(), color.saturation(), 127 + qRound(color.value() / 2));
856        else
857                hilight.setHsv(color.hue(), color.saturation(), color.value() / 2);
858
859        solutionText->document()->setDefaultStyleSheet(QString("* {color: %1;}").arg(color.name()));
860        fmt_default.setForeground(QBrush(color));
861
862        fmt_selected.setForeground(QBrush(settings->value("Output/Colors/Selected", DEF_SELECTED_COLOR).value<QColor>()));
863        fmt_selected.setFontWeight(QFont::Bold);
864
865        fmt_alternate.setForeground(QBrush(settings->value("Output/Colors/Alternate", DEF_ALTERNATE_COLOR).value<QColor>()));
866        fmt_alternate.setFontWeight(QFont::Bold);
867        fmt_altlist.setForeground(QBrush(hilight));
868
869        solutionText->setTextColor(color);
870}
871
872void MainWindow::loadLangList()
873{
874QDir dir(PATH_L10N, "tspsg_*.qm", QDir::Name | QDir::IgnoreCase, QDir::Files);
875        if (!dir.exists())
876                return;
877QFileInfoList langs = dir.entryInfoList();
878        if (langs.size() <= 0)
879                return;
880QAction *a;
881QTranslator t;
882QString name;
883        for (int k = 0; k < langs.size(); k++) {
884                QFileInfo lang = langs.at(k);
885                if (lang.completeBaseName().compare("tspsg_en", Qt::CaseInsensitive) && t.load(lang.completeBaseName(), PATH_L10N)) {
886                        name = t.translate("--------", "LANGNAME", "Please, provide a native name of your translation language here.");
887                        a = menuSettingsLanguage->addAction(name);
888                        a->setStatusTip(QString("Set application language to %1").arg(name));
889                        a->setData(lang.completeBaseName().mid(6));
890                        a->setCheckable(true);
891                        a->setActionGroup(groupSettingsLanguageList);
892                        if (settings->value("Language", QLocale::system().name()).toString().startsWith(lang.completeBaseName().mid(6)))
893                                a->setChecked(true);
894                }
895        }
896}
897
898bool MainWindow::loadLanguage(const QString &lang)
899{
900// i18n
901bool ad = false;
902QString lng = lang;
903        if (lng.isEmpty()) {
904                ad = settings->value("Language", "").toString().isEmpty();
905                lng = settings->value("Language", QLocale::system().name()).toString();
906        }
907static QTranslator *qtTranslator; // Qt library translator
908        if (qtTranslator) {
909                qApp->removeTranslator(qtTranslator);
910                delete qtTranslator;
911                qtTranslator = NULL;
912        }
913static QTranslator *translator; // Application translator
914        if (translator) {
915                qApp->removeTranslator(translator);
916                delete translator;
917                translator = NULL;
918        }
919
920        if (lng == "en")
921                return true;
922
923        // Trying to load system Qt library translation...
924        qtTranslator = new QTranslator(this);
925        if (qtTranslator->load("qt_" + lng, QLibraryInfo::location(QLibraryInfo::TranslationsPath)))
926                qApp->installTranslator(qtTranslator);
927        else {
928                // No luck. Let's try to load a bundled one.
929                if (qtTranslator->load("qt_" + lng, PATH_L10N))
930                        qApp->installTranslator(qtTranslator);
931                else {
932                        // Qt library translation unavailable
933                        delete qtTranslator;
934                        qtTranslator = NULL;
935                }
936        }
937
938        // Now let's load application translation.
939        translator = new QTranslator(this);
940        if (translator->load("tspsg_" + lng, PATH_L10N))
941                qApp->installTranslator(translator);
942        else {
943                delete translator;
944                translator = NULL;
945                if (!ad) {
946                        settings->remove("Language");
947                        QApplication::setOverrideCursor(QCursor(Qt::ArrowCursor));
948                        if (isVisible())
949                                QMessageBox::warning(this, tr("Language Change"), tr("Unable to load the translation language.\nFalling back to autodetection."));
950                        else
951                                QMessageBox::warning(NULL, tr("Language Change"), tr("Unable to load the translation language.\nFalling back to autodetection."));
952                        QApplication::restoreOverrideCursor();
953                }
954                return false;
955        }
956        return true;
957}
958
959bool MainWindow::maybeSave()
960{
961        if (!isWindowModified())
962                return true;
963int res = QMessageBox::warning(this, tr("Unsaved Changes"), tr("Would you like to save changes in the current task?"), QMessageBox::Save | QMessageBox::Discard | QMessageBox::Cancel);
964        if (res == QMessageBox::Save)
965                return actionFileSaveTriggered();
966        else if (res == QMessageBox::Cancel)
967                return false;
968        else
969                return true;
970}
971
972void MainWindow::outputMatrix(QTextCursor &cur, const TMatrix &matrix)
973{
974int n = spinCities->value();
975QTextTable *table = cur.insertTable(n, n, fmt_table);
976
977        for (int r = 0; r < n; r++) {
978                for (int c = 0; c < n; c++) {
979                        cur = table->cellAt(r, c).firstCursorPosition();
980                        cur.setBlockFormat(fmt_cell);
981                        cur.setBlockCharFormat(fmt_default);
982                        if (matrix.at(r).at(c) == INFINITY)
983                                cur.insertText(INFSTR);
984                        else
985                                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()));
986                }
987                QApplication::processEvents();
988        }
989        cur.movePosition(QTextCursor::End);
990}
991
992void MainWindow::outputMatrix(QTextCursor &cur, const SStep &step)
993{
994int n = spinCities->value();
995QTextTable *table = cur.insertTable(n, n, fmt_table);
996
997        for (int r = 0; r < n; r++) {
998                for (int c = 0; c < n; c++) {
999                        cur = table->cellAt(r, c).firstCursorPosition();
1000                        cur.setBlockFormat(fmt_cell);
1001                        if (step.matrix.at(r).at(c) == INFINITY)
1002                                cur.insertText(INFSTR, fmt_default);
1003                        else if ((r == step.candidate.nRow) && (c == step.candidate.nCol))
1004                                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);
1005                        else {
1006SStep::SCandidate cand;
1007                                cand.nRow = r;
1008                                cand.nCol = c;
1009                                if (step.alts.contains(cand))
1010                                        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);
1011                                else
1012                                        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);
1013                        }
1014                }
1015                QApplication::processEvents();
1016        }
1017
1018        cur.movePosition(QTextCursor::End);
1019}
1020
1021void MainWindow::retranslateUi(bool all)
1022{
1023        if (all)
1024                Ui::MainWindow::retranslateUi(this);
1025
1026        actionSettingsLanguageEnglish->setStatusTip(tr("Set application language to %1").arg("English"));
1027
1028#ifndef QT_NO_PRINTER
1029        actionFilePrintPreview->setText(QApplication::translate("MainWindow", "P&rint Preview...", 0, QApplication::UnicodeUTF8));
1030#ifndef QT_NO_TOOLTIP
1031        actionFilePrintPreview->setToolTip(QApplication::translate("MainWindow", "Preview solution results", 0, QApplication::UnicodeUTF8));
1032#endif // QT_NO_TOOLTIP
1033#ifndef QT_NO_STATUSTIP
1034        actionFilePrintPreview->setStatusTip(QApplication::translate("MainWindow", "Preview current solution results before printing", 0, QApplication::UnicodeUTF8));
1035#endif // QT_NO_STATUSTIP
1036
1037        actionFilePrint->setText(QApplication::translate("MainWindow", "&Print...", 0, QApplication::UnicodeUTF8));
1038#ifndef QT_NO_TOOLTIP
1039        actionFilePrint->setToolTip(QApplication::translate("MainWindow", "Print solution", 0, QApplication::UnicodeUTF8));
1040#endif // QT_NO_TOOLTIP
1041#ifndef QT_NO_STATUSTIP
1042        actionFilePrint->setStatusTip(QApplication::translate("MainWindow", "Print current solution results", 0, QApplication::UnicodeUTF8));
1043#endif // QT_NO_STATUSTIP
1044        actionFilePrint->setShortcut(QApplication::translate("MainWindow", "Ctrl+P", 0, QApplication::UnicodeUTF8));
1045#endif // QT_NO_PRINTER
1046#ifdef Q_OS_WIN32
1047        actionHelpCheck4Updates->setText(tr("Check for &Updates..."));
1048#ifndef QT_NO_TOOLTIP
1049        actionHelpCheck4Updates->setToolTip(tr("Check for %1 updates").arg(QApplication::applicationName()));
1050#endif // QT_NO_TOOLTIP
1051#ifndef QT_NO_STATUSTIP
1052        actionHelpCheck4Updates->setStatusTip(tr("Check for %1 updates").arg(QApplication::applicationName()));
1053#endif // QT_NO_STATUSTIP
1054#endif // Q_OS_WIN32
1055}
1056
1057bool MainWindow::saveTask() {
1058QStringList filters(tr("%1 Task File").arg("TSPSG") + " (*.tspt)");
1059        filters.append(tr("All Files") + " (*)");
1060QString file;
1061        if (fileName.endsWith(".tspt", Qt::CaseInsensitive))
1062                file = fileName;
1063        else
1064                file = QFileInfo(fileName).canonicalPath() + "/" + QFileInfo(fileName).completeBaseName() + ".tspt";
1065
1066QFileDialog::Options opts = settings->value("UseNativeDialogs", DEF_USE_NATIVE_DIALOGS).toBool() ? QFileDialog::Options() : QFileDialog::DontUseNativeDialog;
1067        file = QFileDialog::getSaveFileName(this, tr("Task Save"), file, filters.join(";;"), NULL, opts);
1068
1069        if (file.isEmpty())
1070                return false;
1071        if (tspmodel->saveTask(file)) {
1072                setFileName(file);
1073                setWindowModified(false);
1074                return true;
1075        }
1076        return false;
1077}
1078
1079void MainWindow::setFileName(const QString &fileName)
1080{
1081        this->fileName = fileName;
1082        setWindowTitle(QString("%1[*] - %2").arg(QFileInfo(fileName).completeBaseName()).arg(tr("Travelling Salesman Problem")));
1083}
1084
1085void MainWindow::setupUi()
1086{
1087        Ui::MainWindow::setupUi(this);
1088
1089#if QT_VERSION >= 0x040600
1090        setToolButtonStyle(Qt::ToolButtonFollowStyle);
1091#endif
1092
1093#ifndef HANDHELD
1094QStatusBar *statusbar = new QStatusBar(this);
1095        statusbar->setObjectName("statusbar");
1096        setStatusBar(statusbar);
1097#endif // HANDHELD
1098
1099#ifdef Q_OS_WINCE_WM
1100        menuBar()->setDefaultAction(menuFile->menuAction());
1101
1102QScrollArea *scrollArea = new QScrollArea(this);
1103        scrollArea->setFrameShape(QFrame::NoFrame);
1104        scrollArea->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
1105        scrollArea->setWidgetResizable(true);
1106        scrollArea->setWidget(tabWidget);
1107        setCentralWidget(scrollArea);
1108#else
1109        setCentralWidget(tabWidget);
1110#endif // Q_OS_WINCE_WM
1111
1112        //! \hack HACK: A little hack for toolbar icons to have a sane size.
1113#ifdef Q_OS_WINCE_WM
1114        toolBar->setIconSize(QSize(logicalDpiX() / 4, logicalDpiY() / 4));
1115#elif defined(Q_OS_SYMBIAN)
1116        toolBar->setIconSize(QSize(logicalDpiX() / 5, logicalDpiY() / 5));
1117#endif // Q_OS_WINCE_WM
1118
1119        solutionText->document()->setDefaultFont(settings->value("Output/Font", QFont(DEF_FONT_FAMILY, DEF_FONT_SIZE)).value<QFont>());
1120        solutionText->setWordWrapMode(QTextOption::WordWrap);
1121
1122#ifndef QT_NO_PRINTER
1123        actionFilePrintPreview = new QAction(this);
1124        actionFilePrintPreview->setObjectName("actionFilePrintPreview");
1125        actionFilePrintPreview->setEnabled(false);
1126        actionFilePrintPreview->setIcon(QIcon(":/images/icons/document_preview.png"));
1127
1128        actionFilePrint = new QAction(this);
1129        actionFilePrint->setObjectName("actionFilePrint");
1130        actionFilePrint->setEnabled(false);
1131        actionFilePrint->setIcon(QIcon(":/images/icons/fileprint.png"));
1132
1133        menuFile->insertAction(actionFileExit,actionFilePrintPreview);
1134        menuFile->insertAction(actionFileExit,actionFilePrint);
1135        menuFile->insertSeparator(actionFileExit);
1136
1137        toolBar->insertAction(actionSettingsPreferences,actionFilePrint);
1138#endif // QT_NO_PRINTER
1139#ifdef Q_OS_WIN32
1140        actionHelpCheck4Updates = new QAction(this);
1141        actionHelpCheck4Updates->setEnabled(hasUpdater());
1142        menuHelp->insertAction(actionHelpAboutQt, actionHelpCheck4Updates);
1143        menuHelp->insertSeparator(actionHelpAboutQt);
1144#endif // Q_OS_WIN32
1145
1146        groupSettingsLanguageList = new QActionGroup(this);
1147        actionSettingsLanguageEnglish->setData("en");
1148        actionSettingsLanguageEnglish->setActionGroup(groupSettingsLanguageList);
1149        loadLangList();
1150        actionSettingsLanguageAutodetect->setChecked(settings->value("Language", "").toString().isEmpty());
1151
1152        spinCities->setMaximum(MAX_NUM_CITIES);
1153
1154        retranslateUi(false);
1155
1156#ifdef Q_OS_WIN32
1157        // Adding some eyecandy in Vista and 7 :-)
1158        if (QtWin::isCompositionEnabled() && settings->value("UseTranslucency", DEF_USE_TRANSLUCENCY).toBool())  {
1159                toggleTranclucency(true);
1160        }
1161#endif // Q_OS_WIN32
1162}
1163
1164void MainWindow::toggleSolutionActions(bool enable)
1165{
1166        buttonSaveSolution->setEnabled(enable);
1167        actionFileSaveAsSolution->setEnabled(enable);
1168        solutionText->setEnabled(enable);
1169#ifndef QT_NO_PRINTER
1170        actionFilePrint->setEnabled(enable);
1171        actionFilePrintPreview->setEnabled(enable);
1172#endif // QT_NO_PRINTER
1173}
1174
1175void MainWindow::toggleTranclucency(bool enable)
1176{
1177#ifdef Q_OS_WIN32
1178        toggleStyle(labelVariant, enable);
1179        toggleStyle(labelCities, enable);
1180        toggleStyle(statusBar(), enable);
1181        tabWidget->setDocumentMode(enable);
1182        QtWin::enableBlurBehindWindow(this, enable);
1183#else
1184        Q_UNUSED(enable);
1185#endif // Q_OS_WIN32
1186}
Note: See TracBrowser for help on using the repository browser.